From 2bd0d3821ba44899cd33df22e365026b0ba94399 Mon Sep 17 00:00:00 2001 From: RiriAgent <39219425+RiriAgent@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:13:58 +0900 Subject: [PATCH] feat: adopt shared omompTool entry and explicit empty-meaning args (#263) --- CHANGELOG.md | 9 + README.md | 4 +- index.ts | 57 +++--- omomp-shared.json | 2 +- omomp-shared/tool-entry.ts | 372 ++++++++++++++++++++++++++++++++++ src/domain/parse.ts | 56 +++-- src/domain/public-grammar.ts | 34 +++- src/ports/host.ts | 71 +++---- src/runtime/coordinator.ts | 6 +- tests/sim/extension.ts | 6 +- tests/tool-parameters.test.ts | 209 +++++++++++++++++-- 11 files changed, 710 insertions(+), 116 deletions(-) create mode 100644 omomp-shared/tool-entry.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 13f886b..b5884d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## [Unreleased] +### Breaking Changes + +- `dispatch_step` launches with `launch: true` and an optional root `role` instead of `launch: { role? }`; convene and `resolve.add` ticket entries declare no dependencies with `independent: true` instead of `dependsOn: []`, and `resolve` clears a ticket's dependencies with `clearDependsOn: true` instead of `dependsOn: []` +- `replaceBody` clears an issue body with `clearBody: true` instead of an empty `body`; `body` must now be a non-empty string, and every entry or action sets exactly one of the pair + +### Changed + +- All five tools are registered through the shared `omompTool` entry: blank strings, empty arrays, empty objects and `null` in tool arguments now behave as if the field was omitted, array elements must not be empty, and arguments are re-validated before the tool runs + ### Fixed - With Meerkat integration on, an issue whose repository belongs to a different owner than the configured Project now has its Project Status read and confirmed, instead of every Status write ending `failed` and blocking `finish` diff --git a/README.md b/README.md index 536b79e..c1b3055 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ A delivery starts a coordinator on the event that makes the trigger condition tr Without the flag the extension registers no active coordinator tools, no timers, and no dispatch state (and `dispatch://` does not inject a global `promptDoc` entry). -Main starts a new agenda with `dispatch_ticket` (`convene`), supplying optional structured `parent` (`{"owner", "repo", "number"}`, omitted when there is none) and `tickets`. Every ticket entry has an `id`, a structured `issue` (`{"owner", "repo", "number"}`), a structured `target` (`{"owner", "repo", "branch"}`), and a `dependsOn` array of ticket IDs; an entry may also carry an optional structured `adoptPr` (`{"owner", "repo", "number"}`). All current parent sub-issues must be represented. Dependencies refer to ticket IDs; independent tickets have no edge. Main can change the topology and record exceptional rulings with `dispatch_step` (`resolve`), whose optional `githubActions` array encodes each GitHub write as a dedicated named action property (for example `publishPr`, `merge`, `replaceBody`, `createIssue`, `attachChild`, `rerunChecks`). A saved active agenda is taken over with `dispatch_ticket` (`resume: { agenda }`). +Main starts a new agenda with `dispatch_ticket` (`convene`), supplying optional structured `parent` (`{"owner", "repo", "number"}`, omitted when there is none) and `tickets`. Every ticket entry has an `id`, a structured `issue` (`{"owner", "repo", "number"}`), a structured `target` (`{"owner", "repo", "branch"}`), and exactly one of a `dependsOn` array of ticket IDs or `independent: true` for a ticket with no dependencies; an entry may also carry an optional structured `adoptPr` (`{"owner", "repo", "number"}`). All current parent sub-issues must be represented. Dependencies refer to ticket IDs; independent tickets have no edge. Main can change the topology and record exceptional rulings with `dispatch_step` (`resolve`), whose optional `githubActions` array encodes each GitHub write as a dedicated named action property (for example `publishPr`, `merge`, `replaceBody`, `createIssue`, `attachChild`, `rerunChecks`). A saved active agenda is taken over with `dispatch_ticket` (`resume: { agenda }`). An agenda belongs to the issue that is its `parent` or the `issue` of any of its tickets. A coordinator sees only the active agendas that belong to its launch issue: they alone appear in the startup message, can be resumed, and refuse a new `convene` while one is saved. Resuming any other agenda is refused with `ownershipBlocked` and changes neither its file nor the coordinator. Active agendas of other issues in the same data directory, such as one an earlier coordinator of another issue left behind, stay as they are and do not keep this issue from being convened. @@ -171,7 +171,7 @@ Notifications, command help, and the launcher CLI and HTML use English or Chines ## Ticket handoff -Main decides only when each ticket is launched. `read dispatch://status` returns the agenda, including its workflow, with the `launchable` tickets (never launched, neither `Escalated` nor delivered, every dependency delivered), the `asking` tickets (each with its worker's question, the id of its `ask` comment once GitHub shows it, and the council `agenda` once the ask was escalated there, see [Meerkat integration](#meerkat-integration)), and the seats currently `seated`. Main calls `dispatch_step` with `ticketId` and `launch: { role? }`, once per ticket; an omitted `role` means the ticket's currently executable seats, and a given `role` must be one of them. The call marks the ticket started, seats its current state at once, and returns their native async job IDs, so independent tickets can be launched back to back. From then on Dispatch follows the workflow by itself: it seats each work and judge state, performs each action, and evaluates each decision, including the parent machine once every ticket is delivered. A seat is one-shot per revision: a role seated at a revision is never seated at that revision again within the process, so a seat that ends without a handoff is followed by its escalation, not by a replacement. A work seat starts only after every seat of its ticket has exited. Native `task` is not used for these seats because its session allocator cannot accept a work-session fork manager. +Main decides only when each ticket is launched. `read dispatch://status` returns the agenda, including its workflow, with the `launchable` tickets (never launched, neither `Escalated` nor delivered, every dependency delivered), the `asking` tickets (each with its worker's question, the id of its `ask` comment once GitHub shows it, and the council `agenda` once the ask was escalated there, see [Meerkat integration](#meerkat-integration)), and the seats currently `seated`. Main calls `dispatch_step` with `ticketId` and `launch: true` (plus an optional `role`), once per ticket; an omitted `role` means the ticket's currently executable seats, and a given `role` must be one of them. The call marks the ticket started, seats its current state at once, and returns their native async job IDs, so independent tickets can be launched back to back. From then on Dispatch follows the workflow by itself: it seats each work and judge state, performs each action, and evaluates each decision, including the parent machine once every ticket is delivered. A seat is one-shot per revision: a role seated at a revision is never seated at that revision again within the process, so a seat that ends without a handoff is followed by its escalation, not by a replacement. A work seat starts only after every seat of its ticket has exited. Native `task` is not used for these seats because its session allocator cannot accept a work-session fork manager. Main is woken by a `dispatch-attention` message only for a decision it has not yet been told about and that is still open when its current turn ends: a ticket that became launchable, an `Escalated` ticket or closure (keyed by revision), a failed Meerkat effect (`failed::`, see [Meerkat integration](#meerkat-integration)), or a finished agenda awaiting `dispatch_ticket` `finish`. A decision Main settles within the turn that produced it, such as launching what `convene` unlocked, never wakes it again. Launching, running seats, seat job completions, a ticket waiting in `Asking`, and effects in flight do not notify. diff --git a/index.ts b/index.ts index 16e5fa4..79429e7 100644 --- a/index.ts +++ b/index.ts @@ -7,6 +7,7 @@ import { logger } from "@oh-my-pi/pi-utils"; import { applyActiveTools } from "./omomp-shared/active-tools.ts"; import { tr } from "./omomp-shared/i18n.ts"; import { registerInternalScheme } from "./omomp-shared/internal-url.ts"; +import { omompTool } from "./omomp-shared/tool-entry.ts"; import type { ParseError, PortInput, Result } from "./src/domain/model.ts"; import { parseDispatchStepParameters, parseDispatchTicketParameters } from "./src/domain/parse.ts"; import { buildPublicGrammar } from "./src/domain/public-grammar.ts"; @@ -222,32 +223,36 @@ export default function dispatch(pi: ExtensionAPI): void { description: tr("Start Main as coordinator for /#", "将 Main 启动为 /# 的协调者"), type: "string", }); - pi.registerTool({ - name: "dispatch_ticket", - label: tr("Dispatch Ticket", "调度工单"), - description: - "Manage Dispatch agenda lifecycle (convene a new ticket graph, resume a saved active agenda, or finish a completed agenda). Read live state via read dispatch://status, dispatch://tickets, or dispatch://.", - loadMode: "essential", - parameters: grammar.dispatchTicketParametersSchema, - defaultInactive: true, - async execute(_id, params, _signal, _update, ctx) { - const response = await runtime.execute(ctx, parseDispatchTicketParameters(params)); - return { content: [{ type: "text", text: JSON.stringify(response) }], details: response, isError: !response.ok }; - }, - }); - pi.registerTool({ - name: "dispatch_step", - label: tr("Dispatch Step", "调度步骤"), - description: - "Launch a Dispatch ticket once (Dispatch relays its seats automatically) or resolve a ticket/closure with an exceptional ruling, topology edit, effect disposition, or GitHub write actions. Read state via read dispatch://status or dispatch://.", - loadMode: "essential", - parameters: grammar.dispatchStepParametersSchema, - defaultInactive: true, - async execute(_id, params, _signal, _update, ctx) { - const response = await runtime.execute(ctx, parseDispatchStepParameters(params)); - return { content: [{ type: "text", text: JSON.stringify(response) }], details: response, isError: !response.ok }; - }, - }); + pi.registerTool( + omompTool({ + name: "dispatch_ticket", + label: tr("Dispatch Ticket", "调度工单"), + description: + "Manage Dispatch agenda lifecycle (convene a new ticket graph, resume a saved active agenda, or finish a completed agenda). Read live state via read dispatch://status, dispatch://tickets, or dispatch://.", + loadMode: "essential", + parameters: grammar.dispatchTicketParametersSchema, + defaultInactive: true, + async execute(_id, params, _signal, _update, ctx) { + const response = await runtime.execute(ctx, parseDispatchTicketParameters(params)); + return { content: [{ type: "text", text: JSON.stringify(response) }], details: response, isError: !response.ok }; + }, + }), + ); + pi.registerTool( + omompTool({ + name: "dispatch_step", + label: tr("Dispatch Step", "调度步骤"), + description: + "Launch a Dispatch ticket once (Dispatch relays its seats automatically) or resolve a ticket/closure with an exceptional ruling, topology edit, effect disposition, or GitHub write actions. Read state via read dispatch://status or dispatch://.", + loadMode: "essential", + parameters: grammar.dispatchStepParametersSchema, + defaultInactive: true, + async execute(_id, params, _signal, _update, ctx) { + const response = await runtime.execute(ctx, parseDispatchStepParameters(params)); + return { content: [{ type: "text", text: JSON.stringify(response) }], details: response, isError: !response.ok }; + }, + }), + ); pi.registerCommand("dispatch-launcher", { description: tr( "Install, uninstall, or inspect the local Dispatch launcher, or register its GitHub App (install|uninstall|status|github-app register --webhook-url )", diff --git a/omomp-shared.json b/omomp-shared.json index 5be193a..233ee1a 100644 --- a/omomp-shared.json +++ b/omomp-shared.json @@ -1,4 +1,4 @@ { "directory": "omomp-shared", - "files": ["active-tools.ts", "biome.base.json", "i18n.ts", "internal-url.ts"] + "files": ["active-tools.ts", "biome.base.json", "i18n.ts", "internal-url.ts", "tool-entry.ts"] } diff --git a/omomp-shared/tool-entry.ts b/omomp-shared/tool-entry.ts new file mode 100644 index 0000000..af44b53 --- /dev/null +++ b/omomp-shared/tool-entry.ts @@ -0,0 +1,372 @@ +import type { EmbeddableSchema, IR } from "@oh-my-pi/omptype"; +import { validateToolArguments } from "@oh-my-pi/pi-ai"; + +type ObjectIR = Extract; +type ArrayIR = Extract; + +const verbatimKey: unique symbol = Symbol("omomp.verbatim"); + +function hasVerbatimMark(target: object): boolean { + return Reflect.get(target, verbatimKey) === true; +} + +function isEmbeddableSchema(value: unknown): value is EmbeddableSchema { + if (typeof value !== "function" && (typeof value !== "object" || value === null)) return false; + const ir: unknown = Reflect.get(value, "ir"); + return typeof ir === "object" && ir !== null && typeof Reflect.get(ir, "k") === "string"; +} + +function markVerbatim(schema: unknown, visited: Set): void { + if (!isEmbeddableSchema(schema) || visited.has(schema)) return; + visited.add(schema); + if (!hasVerbatimMark(schema.ir)) { + const marked = { ...schema.ir }; + Reflect.set(marked, verbatimKey, true); + schema.ir = marked; + } + Object.defineProperty(schema, verbatimKey, { value: true, enumerable: false, configurable: true }); + for (const value of Object.values(schema)) { + if (isEmbeddableSchema(value)) markVerbatim(value, visited); + } + for (const key of Object.getOwnPropertySymbols(schema)) { + if (key === verbatimKey) continue; + const value: unknown = Reflect.get(schema, key); + if (isEmbeddableSchema(value)) markVerbatim(value, visited); + } +} + +export function verbatim(schema: S): S { + if (!isEmbeddableSchema(schema)) throw new Error("verbatim() requires a schema created by @oh-my-pi/omptype"); + markVerbatim(schema, new Set()); + return schema; +} + +type FieldKind = "string" | "array" | "object" | "other"; + +interface FieldType { + kind: FieldKind; + verbatim: boolean; +} + +function wrappedNode(node: IR): IR | undefined { + switch (node.k) { + case "morph": + return node.input; + case "refine": + return node.base; + case "sub": + return node.schema.ir; + case "unknown": + case "null": + case "undefined": + case "boolean": + case "bigint": + case "symbol": + case "never": + case "anyobject": + case "string": + case "number": + case "lit": + case "union": + case "intersection": + case "array": + case "tuple": + case "object": + case "instance": + case "alias": + return undefined; + default: + return assertNever(node); + } +} + +function assertNever(node: never): never { + throw new Error(`unhandled omptype IR node ${JSON.stringify(node)}`); +} + +function classifyField(node: IR, verbatim: boolean, depth: number): FieldType { + const own = verbatim || hasVerbatimMark(node); + if (depth > 12) return { kind: "other", verbatim: own }; + switch (node.k) { + case "string": + return { kind: "string", verbatim: own }; + case "lit": + return typeof node.v === "string" ? { kind: "string", verbatim: own } : { kind: "other", verbatim: own }; + case "array": + return { kind: "array", verbatim: own }; + case "object": + case "anyobject": + return { kind: "object", verbatim: own }; + case "union": { + const members = node.members.filter((member) => member.k !== "undefined" && member.k !== "null"); + const [only] = members; + if (only === undefined) return { kind: "other", verbatim: own }; + if (members.length === 1) return classifyField(only, own, depth + 1); + if (members.every((member) => member.k === "string" || (member.k === "lit" && typeof member.v === "string"))) { + return { kind: "string", verbatim: own }; + } + return { kind: "other", verbatim: own }; + } + case "sub": + return classifyField(node.schema.ir, own || hasVerbatimMark(node.schema), depth + 1); + case "morph": + case "refine": { + const inner = wrappedNode(node); + return inner === undefined ? { kind: "other", verbatim: own } : classifyField(inner, own, depth + 1); + } + case "alias": { + let resolved: IR; + try { + resolved = node.resolve(); + } catch { + return { kind: "other", verbatim: own }; + } + return classifyField(resolved, own, depth + 1); + } + case "unknown": + case "null": + case "undefined": + case "boolean": + case "bigint": + case "symbol": + case "never": + case "number": + case "intersection": + case "tuple": + case "instance": + return { kind: "other", verbatim: own }; + default: + return assertNever(node); + } +} + +function isEmptyValue(value: unknown, field: FieldType): boolean { + if (value === null) return true; + switch (field.kind) { + case "string": + if (typeof value !== "string") return false; + return field.verbatim ? value.length === 0 : value.trim().length === 0; + case "array": + return Array.isArray(value) && value.length === 0; + case "object": + return typeof value === "object" && !Array.isArray(value) && Object.keys(value as Record).length === 0; + case "other": + return false; + } +} + +interface ElementRefusal { + path: string; + index: number; +} + +function objectNodeOf(node: IR): ObjectIR | undefined { + let current: IR | undefined = node; + for (let depth = 0; current !== undefined && depth <= 12; depth++) { + if (current.k === "object") return current; + current = wrappedNode(current); + } + return undefined; +} + +function arrayNodeOf(node: IR): ArrayIR | undefined { + let current: IR | undefined = node; + for (let depth = 0; current !== undefined && depth <= 12; depth++) { + if (current.k === "array") return current; + current = wrappedNode(current); + } + return undefined; +} + +function peelOptional(node: IR): IR { + if (node.k !== "union") return node; + const members = node.members.filter((member) => member.k !== "undefined" && member.k !== "null"); + const [only] = members; + return members.length === 1 && only !== undefined ? only : node; +} + +function structuralObjectNode(node: IR): ObjectIR | undefined { + return objectNodeOf(peelOptional(node)); +} + +function structuralArrayNode(node: IR): ArrayIR | undefined { + return arrayNodeOf(peelOptional(node)); +} + +function pathJoin(base: string, key: string): string { + return base === "" ? key : `${base}.${key}`; +} + +type NormalizedField = { empty: true } | { empty: false; value: unknown; changed: boolean }; + +function normalizeField(node: IR, value: unknown, path: string, refusals: ElementRefusal[], depth: number): NormalizedField { + if (depth > 12) return { empty: false, value, changed: false }; + const field = classifyField(node, false, 0); + if (isEmptyValue(value, field)) return { empty: true }; + if (typeof value !== "object" || value === null) return { empty: false, value, changed: false }; + + if (Array.isArray(value)) { + const arrayNode = structuralArrayNode(node); + if (arrayNode === undefined) return { empty: false, value, changed: false }; + let changed = false; + const elements: unknown[] = []; + for (let index = 0; index < value.length; index++) { + const element = normalizeField(arrayNode.el, value[index], `${path}[${index}]`, refusals, depth + 1); + if (element.empty) { + refusals.push({ path, index }); + elements.push(value[index]); + continue; + } + if (element.changed) changed = true; + elements.push(element.changed ? element.value : value[index]); + } + return { empty: false, value: changed ? elements : value, changed }; + } + + const objectNode = structuralObjectNode(node); + if (objectNode === undefined) return { empty: false, value, changed: false }; + const input = value as Record; + let changed = false; + const copy: Record = {}; + for (const key of Object.keys(input)) copy[key] = input[key]; + for (const prop of objectNode.props) { + if (typeof prop.key !== "string" || !(prop.key in input)) continue; + const propPath = pathJoin(path, prop.key); + const normalized = normalizeField(prop.val, input[prop.key], propPath, refusals, depth + 1); + if (normalized.empty) { + delete copy[prop.key]; + changed = true; + } else if (normalized.changed) { + copy[prop.key] = normalized.value; + changed = true; + } + } + if (Object.keys(copy).length === 0) return { empty: true }; + return { empty: false, value: changed ? copy : value, changed }; +} + +interface NormalizeResult { + args: unknown; + changed: boolean; + refusals: ElementRefusal[]; +} + +function normalizeArguments(rootNode: IR, args: unknown): NormalizeResult { + const refusals: ElementRefusal[] = []; + if (typeof args !== "object" || args === null || Array.isArray(args)) return { args, changed: false, refusals }; + const objectNode = structuralObjectNode(rootNode); + if (objectNode === undefined) return { args, changed: false, refusals }; + let changed = false; + const input = args as Record; + const copy: Record = {}; + for (const key of Object.keys(input)) copy[key] = input[key]; + for (const prop of objectNode.props) { + if (typeof prop.key !== "string" || !(prop.key in input)) continue; + const propPath = pathJoin("", prop.key); + const normalized = normalizeField(prop.val, input[prop.key], propPath, refusals, 0); + if (normalized.empty) { + delete copy[prop.key]; + changed = true; + } else if (normalized.changed) { + copy[prop.key] = normalized.value; + changed = true; + } + } + return { args: changed ? copy : args, changed, refusals }; +} + +function truncateForError(value: unknown): unknown { + if (typeof value === "string") return value.length > 256 ? `${value.slice(0, 256)}…` : value; + if (Array.isArray(value)) return value.map(truncateForError); + if (typeof value === "object" && value !== null) { + const out: Record = {}; + for (const key of Object.keys(value)) out[key] = truncateForError((value as Record)[key]); + return out; + } + return value; +} + +function refuseEmptyElements(name: string, refusals: ElementRefusal[], originalArgs: unknown): never { + const lines = refusals.map((refusal) => ` - ${refusal.path}[${refusal.index}]: array element must not be empty`); + throw new Error( + `Validation failed for tool "${name}":\n${lines.join("\n")}\n\nReceived arguments:\n${JSON.stringify(truncateForError(originalArgs), null, 2)}`, + ); +} + +function stripUndeclaredRootKeys(rootNode: IR, args: unknown): unknown { + if (typeof args !== "object" || args === null || Array.isArray(args)) return args; + const objectNode = structuralObjectNode(rootNode); + if (objectNode === undefined) return args; + if (objectNode.index !== undefined) return args; + const declared = new Set(); + for (const prop of objectNode.props) declared.add(prop.key); + const input = args as Record; + let stripped = false; + const out: Record = {}; + for (const key of Object.keys(input)) { + if (declared.has(key)) { + out[key] = input[key]; + } else { + stripped = true; + } + } + return stripped ? out : args; +} + +function normalizeAndValidate(toolName: string, toolCallId: unknown, parameters: EmbeddableSchema, params: unknown): unknown { + const originalArgs = params; + const rootNode = parameters.ir; + + const initial = normalizeArguments(rootNode, params); + if (initial.refusals.length > 0) refuseEmptyElements(toolName, initial.refusals, originalArgs); + let current: unknown = initial.args; + + const id = typeof toolCallId === "string" ? toolCallId : "omomp"; + const seen = new Set(); + for (;;) { + const validated = validateToolArguments( + { name: toolName, description: "", parameters } as Parameters[0], + { type: "toolCall", id, name: toolName, arguments: current as Record }, + ); + const renormalized = normalizeArguments(rootNode, validated); + if (renormalized.refusals.length > 0) refuseEmptyElements(toolName, renormalized.refusals, originalArgs); + if (!renormalized.changed) { + return stripUndeclaredRootKeys(rootNode, validated); + } + const key = JSON.stringify(renormalized.args); + if (seen.has(key)) { + return stripUndeclaredRootKeys(rootNode, validated); + } + seen.add(key); + current = renormalized.args; + } +} + +interface OmompToolDefinitionShape { + name: string; + parameters: unknown; + execute: unknown; +} + +function schemaOf(name: string, parameters: unknown): EmbeddableSchema { + if (!isEmbeddableSchema(parameters)) { + throw new Error(`omompTool(${name}): parameters must be a schema created by @oh-my-pi/omptype`); + } + return parameters; +} + +export function omompTool(definition: D): D { + const descriptors = Object.getOwnPropertyDescriptors(definition); + const declared = descriptors.parameters; + if (declared !== undefined && "value" in declared) schemaOf(definition.name, declared.value); + const originalExecute = definition.execute as (toolCallId: unknown, params: unknown, ...rest: unknown[]) => unknown; + function execute(this: unknown, toolCallId: unknown, params: unknown, ...rest: unknown[]) { + const normalized = normalizeAndValidate(definition.name, toolCallId, schemaOf(definition.name, definition.parameters), params); + return originalExecute.call(this, toolCallId, normalized, ...rest); + } + return Object.create(Object.getPrototypeOf(definition), { + ...descriptors, + lenientArgValidation: { value: true, enumerable: true, writable: true, configurable: true }, + execute: { value: execute, enumerable: true, writable: true, configurable: true }, + }) as D; +} diff --git a/src/domain/parse.ts b/src/domain/parse.ts index 06364a1..cd42ea0 100644 --- a/src/domain/parse.ts +++ b/src/domain/parse.ts @@ -58,16 +58,33 @@ function toTarget(value: WireTarget): Target { return { repo: { owner: value.owner, name: value.repo }, base: value.branch }; } -function toEntry(value: WireEntry): Entry { +function toEntry(value: WireEntry, path: string): Result { + if (value.dependsOn !== undefined && value.independent === true) + return failure(`${path}.dependsOn`, "dependsOn and independent cannot be combined"); + if (value.dependsOn === undefined && value.independent !== true) + return failure(`${path}.dependsOn`, "Set exactly one of dependsOn or independent"); return { - id: value.id, - issue: toIssueRef(value.issue), - target: toTarget(value.target), - dependsOn: value.dependsOn, - adoptPr: value.adoptPr === undefined ? null : toIssueRef(value.adoptPr), + ok: true, + value: { + id: value.id, + issue: toIssueRef(value.issue), + target: toTarget(value.target), + dependsOn: value.dependsOn ?? [], + adoptPr: value.adoptPr === undefined ? null : toIssueRef(value.adoptPr), + }, }; } +function toEntries(values: readonly WireEntry[], path: string): Result { + const collected: Entry[] = []; + for (let index = 0; index < values.length; index++) { + const entry = toEntry(values[index]!, `${path}.${index}`); + if (!entry.ok) return entry; + collected.push(entry.value); + } + return { ok: true, value: collected }; +} + function toAction(value: WireGitHubAction, path: string): Result { const defined = Object.entries(value).filter(([, item]) => item !== undefined); if (defined.length !== 1) return failure(path, "Specify exactly one GitHub action property per item"); @@ -121,13 +138,15 @@ function toAction(value: WireGitHubAction, path: string): Result { const wire = parse(dispatchStepParametersSchema, value); if (!wire.ok) return wire; - const { ticketId, launch, resolve } = wire.value; - const chosen = [launch !== undefined, resolve !== undefined].filter(Boolean).length; + const { ticketId, launch, role, resolve } = wire.value; + const chosen = [launch === true, resolve !== undefined].filter(Boolean).length; if (chosen !== 1) return failure("", "Specify exactly one of launch or resolve"); - if (launch) { - return parse(portInputSchema, compact({ op: "launch", ticketId, role: launch.role })); + if (launch === true) { + return parse(portInputSchema, compact({ op: "launch", ticketId, role })); } + if (role !== undefined) return failure("role", "role is only allowed when launch is true"); const r = resolve!; if (r.clearAdoptPr === true && r.adoptPr !== undefined) { return failure("resolve.adoptPr", "adoptPr and clearAdoptPr cannot be combined"); } + if (r.clearDependsOn === true && r.dependsOn !== undefined) { + return failure("resolve.dependsOn", "dependsOn and clearDependsOn cannot be combined"); + } const adoptPr = r.clearAdoptPr === true ? null : r.adoptPr === undefined ? undefined : toIssueRef(r.adoptPr); + const dependsOn = r.clearDependsOn === true ? [] : r.dependsOn; + const added = r.add === undefined ? undefined : toEntries(r.add, "resolve.add"); + if (added !== undefined && !added.ok) return added; const enqueued = r.githubActions === undefined ? undefined : toActions(r.githubActions, "resolve.githubActions"); if (enqueued !== undefined && !enqueued.ok) return enqueued; return parse( @@ -268,11 +296,11 @@ export function parseDispatchStepParameters(value: unknown): Result or read dispatch://status. A stale revision is refused.", @@ -272,7 +285,14 @@ export function buildPublicGrammar(z: PublicZ) { .string() .regex(/^[A-Za-z][A-Za-z0-9_-]*$/) .describe("Workflow state to continue in, by name (use a state from the ticket workflow, or the parent workflow for the closure)."), - dependsOn: z.array(text).optional().describe("Replaces the ticket dependency ids; [] makes it independent."), + dependsOn: z + .array(text) + .optional() + .describe("Replaces the ticket dependency ids. Omit to keep them; do not combine with clearDependsOn."), + clearDependsOn: z + .literal(true) + .optional() + .describe("true removes every dependency so the ticket becomes independent; omit keeps them. Do not combine with dependsOn."), target: wireTargetSchema.optional().describe("Replaces the ticket target repository and base branch."), adoptPr: wireIssueRefSchema .optional() diff --git a/src/ports/host.ts b/src/ports/host.ts index 9b8187e..202a883 100644 --- a/src/ports/host.ts +++ b/src/ports/host.ts @@ -3,7 +3,7 @@ import { access, mkdir, readdir, rm } from "node:fs/promises"; import { dirname, join, resolve } from "node:path"; import { z } from "@oh-my-pi/omptype/zod"; // Compiled omp 19.1.0 exposes createAgentSession via the root shim, not a virtual @oh-my-pi/pi-coding-agent/sdk entry. -import { createAgentSession } from "@oh-my-pi/pi-coding-agent"; +import { type CreateAgentSessionOptions, createAgentSession } from "@oh-my-pi/pi-coding-agent"; import { resolveAgentModelSelection } from "@oh-my-pi/pi-coding-agent/config/model-resolver"; import type { ToolDefinition } from "@oh-my-pi/pi-coding-agent/extensibility/extensions/types"; import { MCPManager } from "@oh-my-pi/pi-coding-agent/mcp/manager"; @@ -17,6 +17,7 @@ import { followMCPTools, type MCPToolFollower } from "@oh-my-pi/pi-coding-agent/ import { cfgTaskAgentModelOverrides, cfgTaskDisabledAgents } from "@oh-my-pi/pi-coding-agent/task/settings"; import { USER_TODO_EDIT_CUSTOM_TYPE } from "@oh-my-pi/pi-coding-agent/tools/todo"; import { tr } from "../../omomp-shared/i18n.ts"; +import { omompTool } from "../../omomp-shared/tool-entry.ts"; import type { Caller, ParseError, PortInput, Result } from "../domain/model.ts"; import { parseSeatEscalateParameters, parseSeatSubmitParameters, parseSeatVerdictParameters } from "../domain/parse.ts"; import { buildPublicGrammar } from "../domain/public-grammar.ts"; @@ -244,7 +245,7 @@ export function createHostPort(options: HostOptions): HostPort { } return { content: [{ type: "text" as const, text: JSON.stringify(response) }], details: response, isError: !response.ok }; }; - const escalateTool: ToolDefinition = { + const escalateDefinition: ToolDefinition = { name: "dispatch_escalate", label: tr("Dispatch Escalate", "调度升级"), description: @@ -255,39 +256,29 @@ export function createHostPort(options: HostOptions): HostPort { return runHandoff(parseSeatEscalateParameters(params, { ticketId: input.ticketId, revision: input.revision })); }, }; - const seatTools: ToolDefinition[] = - input.seat === "work" - ? [ - { - name: "dispatch_submit", - label: tr("Dispatch Submit", "调度提交"), - description: - "Hand off your pushed branch for the bound ticket (use read dispatch://seat for context). A successful submit ends this seat.", - loadMode: "essential", - parameters: grammar.seatSubmitParametersSchema, - async execute(_id, params) { - return runHandoff(parseSeatSubmitParameters(params, { ticketId: input.ticketId, revision: input.revision })); - }, - }, - escalateTool, - ] - : [ - { - name: "dispatch_verdict", - label: tr("Dispatch Verdict", "调度裁决"), - description: - "Hand off your independent gate verdict for the bound ticket or closure (use read dispatch://seat for context). A successful verdict ends this seat.", - loadMode: "essential", - parameters: grammar.seatVerdictParametersSchema, - async execute(_id, params) { - return runHandoff( - parseSeatVerdictParameters(params, { ticketId: input.ticketId, revision: input.revision, role: input.role }), - ); - }, - }, - escalateTool, - ]; - const seatToolNames = seatTools.map((tool) => tool.name); + const submitDefinition: ToolDefinition = { + name: "dispatch_submit", + label: tr("Dispatch Submit", "调度提交"), + description: + "Hand off your pushed branch for the bound ticket (use read dispatch://seat for context). A successful submit ends this seat.", + loadMode: "essential", + parameters: grammar.seatSubmitParametersSchema, + async execute(_id, params) { + return runHandoff(parseSeatSubmitParameters(params, { ticketId: input.ticketId, revision: input.revision })); + }, + }; + const verdictDefinition: ToolDefinition = { + name: "dispatch_verdict", + label: tr("Dispatch Verdict", "调度裁决"), + description: + "Hand off your independent gate verdict for the bound ticket or closure (use read dispatch://seat for context). A successful verdict ends this seat.", + loadMode: "essential", + parameters: grammar.seatVerdictParametersSchema, + async execute(_id, params) { + return runHandoff(parseSeatVerdictParameters(params, { ticketId: input.ticketId, revision: input.revision, role: input.role })); + }, + }; + const seatToolNames = input.seat === "work" ? ["dispatch_submit", "dispatch_escalate"] : ["dispatch_verdict", "dispatch_escalate"]; const settings = (await parent.settings.cloneForCwd(workspace)).overlay({ "tools.approvalMode": "yolo", "compaction.midTurnEnabled": true, @@ -306,7 +297,7 @@ export function createHostPort(options: HostOptions): HostPort { const mcpManager = MCPManager.instance(); mcpFollower = mcpManager ? followMCPTools(mcpManager, { scope: manager.getSessionId() }, new Set(seatToolNames)) : undefined; const mcpTools = mcpFollower?.proxyTools() ?? []; - const created = await createAgentSession({ + const sessionBase: CreateAgentSessionOptions = { cwd: workspace, sessionManager: manager, authStorage: parent.modelRegistry.authStorage, @@ -322,7 +313,6 @@ export function createHostPort(options: HostOptions): HostPort { mountedToolNames: savedContract.data.mountedTools, } : { appendSystemPrompt: agent.systemPrompt, ...(agentTools ? { toolNames: agentTools } : {}) }), - customTools: seatTools, enableMCP: true, ...(mcpManager ? { mcpManager, ...(mcpTools.length ? { mcpTools } : {}) } : {}), ...(mcpFollower ? { mcpToolScope: mcpFollower.scope } : {}), @@ -343,7 +333,12 @@ export function createHostPort(options: HostOptions): HostPort { expectedAgentRef: null, spawns, inheritedSessionAgents: parent.getSessionAgents(), - }); + }; + const created = await createAgentSession( + input.seat === "work" + ? { ...sessionBase, customTools: [omompTool(submitDefinition), omompTool(escalateDefinition)] } + : { ...sessionBase, customTools: [omompTool(verdictDefinition), omompTool(escalateDefinition)] }, + ); seat.session = created.session; mcpFollower?.bind(created.session); if (mcpFollower) diff --git a/src/runtime/coordinator.ts b/src/runtime/coordinator.ts index 7b7d5ca..1c01d4b 100644 --- a/src/runtime/coordinator.ts +++ b/src/runtime/coordinator.ts @@ -16,15 +16,15 @@ export function coordinatorBriefing(check: StartupCheck): string { return [ `You are the persistent Dispatch Main coordinator for ${check.reference}. Saved agendas: ${summary}.`, `Read ${check.reference} completely, including comments and sub-issues. You decide serial/parallel topology and exceptional rulings. The state machine owns GitHub PR/issue writes, merge checks, and effects; do not perform those writes manually. Inspect live dispatch state with read: \`dispatch://status\` (full agenda, launchable/asking/seated), \`dispatch://tickets\` (supports optional \`?repo=&project=&limit=\`), and \`dispatch://\` (one ticket or closure).`, - 'For a new agenda call `dispatch_ticket` with {"convene":{"parent":{"owner":"","repo":"","number":1},"tickets":[{"id":"","issue":{"owner":"","repo":"","number":2},"target":{"owner":"","repo":"","branch":"main"},"dependsOn":[""]}]}}. Omit `parent` when the launch issue has no parent, and omit an entry\'s `adoptPr` unless that ticket adopts an existing pull request (`{"owner":"","repo":"","number":3}`). Include every parent sub-issue; independent tickets have no dependency edge. If the launch issue has no children, omit `parent` and use one ticket for that issue.', + 'For a new agenda call `dispatch_ticket` with {"convene":{"parent":{"owner":"","repo":"","number":1},"tickets":[{"id":"","issue":{"owner":"","repo":"","number":2},"target":{"owner":"","repo":"","branch":"main"},"dependsOn":[""]}]}}. Omit `parent` when the launch issue has no parent, and omit an entry\'s `adoptPr` unless that ticket adopts an existing pull request (`{"owner":"","repo":"","number":3}`). Include every parent sub-issue; an entry with no predecessors sets `"independent":true` instead of `dependsOn`. If the launch issue has no children, omit `parent` and use one ticket for that issue.', ...(resumable ? [ 'For the saved agenda listed above call `dispatch_ticket` with {"resume":{"agenda":""}} right away; Dispatch itself asks the operating system whether the previous coordinator process has ended. If it refuses with agenda_attached, that process is still running: tell the operator its pid and start time from the message and stop. Resume keeps each work role\'s session and the workflow the agenda was convened with; executing GitHub writes become uncertain and are reconciled, never blindly replayed, while an interrupted request to the intent guardians, which accept a repeat, is sent again.', ] : []), - 'Each ticket moves through the states of the agenda\'s workflow (`agenda.workflow` in `read dispatch://status`): work states seat a worker, judge states seat judges, action states perform one GitHub write, decision states branch on source facts, and final states mean delivered. You decide when each ticket is launched. Read `dispatch://status` to see launchable tickets (never launched, not Escalated or delivered, every dependency delivered), then call `dispatch_step` with {"ticketId":"","launch":{}} for each one your topology allows now; `launch.role` is optional and, when omitted, the ticket\'s currently executable seats start. Independent tickets may be launched back to back; launch returns at once. Launch every ticket exactly once: Dispatch then relays its seats and actions by itself along the workflow. Do not use native task for seats, do not wait on seat jobs, and do not relay verdicts.', + 'Each ticket moves through the states of the agenda\'s workflow (`agenda.workflow` in `read dispatch://status`): work states seat a worker, judge states seat judges, action states perform one GitHub write, decision states branch on source facts, and final states mean delivered. You decide when each ticket is launched. Read `dispatch://status` to see launchable tickets (never launched, not Escalated or delivered, every dependency delivered), then call `dispatch_step` with {"ticketId":"","launch":true} for each one your topology allows now; `role` is optional and, when omitted, the ticket\'s currently executable seats start. Independent tickets may be launched back to back; launch returns at once. Launch every ticket exactly once: Dispatch then relays its seats and actions by itself along the workflow. Do not use native task for seats, do not wait on seat jobs, and do not relay verdicts.', 'You are woken only by a dispatch-attention message naming a decision that is still open when your turn ends: `launch:` (its dependencies are now delivered), `escalated::` (the workflow routed it to you, a seat asked a question, a seat ended or failed to start without a handoff, an effect failed, or the source changed), or `finish`. A launch, a running or finishing seat, or a decision you already settled in the same turn produces no notification; between notifications there is nothing for you to do. With Meerkat integration on, a work seat\'s question does not reach you: its ticket waits in Asking (`read dispatch://status` lists it under `asking` with the question, its ask comment id, and the council agenda if the ask was escalated there) while the intent guardians settle it, and needs nothing from you. A reply on the issue resumes its worker by itself; a replacement ends the ticket in the final state Replaced, which counts as delivered. Only if the request to the guardians fails are you woken with `failed::`; send it again with `dispatch_step` `resolve` (`to: "Asking"`, `effects: [{"effectId":"","disposition":"retry"}]`), which keeps the question.', - "For an Escalated ticket or closure use `read dispatch://`, then call `dispatch_step` with `ticketId` and `resolve: { revision, ruling, to }` (for the parent closure, a state of the parent workflow); you may also resolve any other ticket to record an exceptional ruling, which supersedes its running seats. Entering an action or final state is refused unless its source requirements hold. `resolve` can synchronize the source contract, change `dependsOn`/`target`, `add`/`remove` tickets, adopt an existing pull request with `adoptPr` or clear it with `clearAdoptPr`, confirm `noCode` with a reason (landing in a closeIssue action state or a final state), settle failed/uncertain `effects`, and enqueue `githubActions`. A retried publishPr or rerunChecks is requested afresh by resolving to its action state; a failed merge or close must go back through the judge states it requires, because the ruling changes the fingerprint they approved. All rulings remain on the ticket. A launched ticket resumes its relay from the state you name; a ticket that was never launched still needs launch.", + "For an Escalated ticket or closure use `read dispatch://`, then call `dispatch_step` with `ticketId` and `resolve: { revision, ruling, to }` (for the parent closure, a state of the parent workflow); you may also resolve any other ticket to record an exceptional ruling, which supersedes its running seats. Entering an action or final state is refused unless its source requirements hold. `resolve` can synchronize the source contract, replace `dependsOn` or clear it with `clearDependsOn`, change `target`, `add`/`remove` tickets, adopt an existing pull request with `adoptPr` or clear it with `clearAdoptPr`, confirm `noCode` with a reason (landing in a closeIssue action state or a final state), settle failed/uncertain `effects`, and enqueue `githubActions`. A retried publishPr or rerunChecks is requested afresh by resolving to its action state; a failed merge or close must go back through the judge states it requires, because the ruling changes the fingerprint they approved. All rulings remain on the ticket. A launched ticket resumes its relay from the state you name; a ticket that was never launched still needs launch.", 'When every ticket and the parent closure rest in a final state, call `dispatch_ticket` with {"finish":{"summary":""}}. Do not declare completion before finish succeeds.', ].join("\n\n"); } diff --git a/tests/sim/extension.ts b/tests/sim/extension.ts index 03426af..df372b6 100644 --- a/tests/sim/extension.ts +++ b/tests/sim/extension.ts @@ -102,13 +102,13 @@ function* startPlan(trigger: string): MainPlan { id: ticket.id, issue: issueRef(ticket.issue), target, - dependsOn: ticket.dependsOn, + ...(ticket.dependsOn.length > 0 ? { dependsOn: ticket.dependsOn } : { independent: true as const }), })), }, }, }, }; - for (const id of opened.value?.launchable ?? []) yield { call: { name: "dispatch_step", args: { ticketId: id, launch: {} } } }; + for (const id of opened.value?.launchable ?? []) yield { call: { name: "dispatch_step", args: { ticketId: id, launch: true } } }; } function* attentionPlan(trigger: string): MainPlan { @@ -118,7 +118,7 @@ function* attentionPlan(trigger: string): MainPlan { }; for (const key of keys) { const [kind = "", id = "", effect = ""] = key.split(":"); - if (kind === "launch") yield { call: { name: "dispatch_step", args: { ticketId: id, launch: {} } } }; + if (kind === "launch") yield { call: { name: "dispatch_step", args: { ticketId: id, launch: true } } }; else if (kind === "finish") yield finish; else if (kind === "escalated") { const read = yield { call: { name: "read", args: { path: `dispatch://${id}:raw` } } }; diff --git a/tests/tool-parameters.test.ts b/tests/tool-parameters.test.ts index 212f2cc..691c8e5 100644 --- a/tests/tool-parameters.test.ts +++ b/tests/tool-parameters.test.ts @@ -1,5 +1,7 @@ import { expect, test } from "bun:test"; import { readdirSync, readFileSync } from "node:fs"; +import { z } from "@oh-my-pi/omptype/zod"; +import { omompTool } from "../omomp-shared/tool-entry.ts"; import type { Action, ParseError, PortInput, Result } from "../src/domain/model.ts"; import { parseAgenda, @@ -9,6 +11,7 @@ import { parseSeatSubmitParameters, parseSeatVerdictParameters, } from "../src/domain/parse.ts"; +import { buildPublicGrammar } from "../src/domain/public-grammar.ts"; const repo = { owner: "oh-my-omp", name: "omp-dispatch" }, other = { owner: "oh-my-omp", name: "omp-config" }; @@ -45,7 +48,7 @@ test("dispatch_ticket maps flat structured convene, resume, and finish onto Port dependsOn: ["B"], adoptPr: { owner: "oh-my-omp", repo: "omp-dispatch", number: 300 }, }, - { id: "B", issue: wireOtherIssue, target: wireTarget, dependsOn: [] }, + { id: "B", issue: wireOtherIssue, target: wireTarget, independent: true }, ], }, }), @@ -62,7 +65,7 @@ test("dispatch_ticket maps flat structured convene, resume, and finish onto Port required( parseDispatchTicketParameters({ convene: { - tickets: [{ id: "A", issue: wireIssue, target: wireTarget, dependsOn: [] }], + tickets: [{ id: "A", issue: wireIssue, target: wireTarget, independent: true }], }, }), ), @@ -82,12 +85,12 @@ test("dispatch_ticket refuses empty, combined, wrapped, or unknown fields", () = }); test("dispatch_step maps launch and resolve with every structured githubAction and three-state adoptPr", () => { - expect(required(parseDispatchStepParameters({ ticketId: "A", launch: { role: "review" } }))).toEqual({ + expect(required(parseDispatchStepParameters({ ticketId: "A", launch: true, role: "review" }))).toEqual({ op: "launch", ticketId: "A", role: "review", }); - expect(required(parseDispatchStepParameters({ ticketId: "A", launch: {} }))).toEqual({ + expect(required(parseDispatchStepParameters({ ticketId: "A", launch: true }))).toEqual({ op: "launch", ticketId: "A", }); @@ -127,7 +130,7 @@ test("dispatch_step maps launch and resolve with every structured githubAction a target: wireTarget, adoptPr: { owner: "oh-my-omp", repo: "omp-dispatch", number: 300 }, noCode: "No code needed.", - add: [{ id: "C", issue: { owner: "oh-my-omp", repo: "omp-dispatch", number: 238 }, target: wireTarget, dependsOn: [] }], + add: [{ id: "C", issue: { owner: "oh-my-omp", repo: "omp-dispatch", number: 238 }, target: wireTarget, independent: true }], remove: ["D"], effects: [{ effectId: "run/publishPr/1", disposition: "retry" }], githubActions: [ @@ -208,6 +211,15 @@ test("dispatch_step maps launch and resolve with every structured githubAction a }), ); expect("adoptPr" in untouched).toBe(false); + expect("dependsOn" in untouched).toBe(false); + + const depsCleared = required( + parseDispatchStepParameters({ + ticketId: "A", + resolve: { revision: 3, ruling: "Independent.", to: "Coding", clearDependsOn: true }, + }), + ); + expect(depsCleared).toEqual({ op: "resolve", ticketId: "A", revision: 3, ruling: "Independent.", to: "Coding", dependsOn: [] }); expect( parseDispatchStepParameters({ @@ -221,6 +233,15 @@ test("dispatch_step maps launch and resolve with every structured githubAction a }, }).ok, ).toBe(false); + expect( + parseDispatchStepParameters({ + ticketId: "A", + resolve: { revision: 3, ruling: "Conflict.", to: "Coding", dependsOn: ["B"], clearDependsOn: true }, + }).ok, + ).toBe(false); + expect(parseDispatchStepParameters({ ticketId: "A", role: "review", resolve: { revision: 3, ruling: "Ruling.", to: "Coding" } }).ok).toBe( + false, + ); }); test("dispatch_step refuses empty, combined, or malformed githubActions", () => { @@ -228,7 +249,7 @@ test("dispatch_step refuses empty, combined, or malformed githubActions", () => expect( parseDispatchStepParameters({ ticketId: "A", - launch: {}, + launch: true, resolve: { revision: 1, ruling: "Ruling.", to: "Coding" }, }).ok, ).toBe(false); @@ -283,7 +304,7 @@ test("dispatch_step refuses empty, combined, or malformed githubActions", () => ).toBe(false); }); -test("an empty replaceBody body is allowed, while an empty createIssue body is refused", () => { +test("replaceBody clears the body with clearBody or replaces it with body, refusing both or neither", () => { expect( required( parseDispatchStepParameters({ @@ -292,7 +313,7 @@ test("an empty replaceBody body is allowed, while an empty createIssue body is r revision: 3, ruling: "Clear body.", to: "Coding", - githubActions: [{ replaceBody: { issue: wireIssue, expectedHash: hash, body: "" } }], + githubActions: [{ replaceBody: { issue: wireIssue, expectedHash: hash, clearBody: true } }], }, }), ), @@ -304,17 +325,33 @@ test("an empty replaceBody body is allowed, while an empty createIssue body is r to: "Coding", actions: [{ kind: "replaceBody", issue, expectedHash: hash, body: "" }], }); - const refused = parseDispatchStepParameters({ - ticketId: "A", - resolve: { - revision: 3, - ruling: "Ruling.", - to: "Coding", - githubActions: [{ createIssue: { repo: wireOtherRepo, title: "New issue", body: "" } }], - }, - }); - expect(refused.ok).toBe(false); - if (!refused.ok) expect(refused.error.path).toBe("resolve.githubActions.0.createIssue.body"); + for (const action of [ + { replaceBody: { issue: wireIssue, expectedHash: hash } }, + { replaceBody: { issue: wireIssue, expectedHash: hash, body: "New body", clearBody: true } }, + { createIssue: { repo: wireOtherRepo, title: "New issue", body: "" } }, + ]) { + const refused = parseDispatchStepParameters({ + ticketId: "A", + resolve: { revision: 3, ruling: "Ruling.", to: "Coding", githubActions: [action] }, + }); + expect(refused.ok).toBe(false); + } +}); + +test("entries require exactly one of dependsOn or independent", () => { + for (const entry of [ + { id: "A", issue: wireIssue, target: wireTarget }, + { id: "A", issue: wireIssue, target: wireTarget, dependsOn: ["B"], independent: true }, + ]) { + expect(parseDispatchTicketParameters({ convene: { tickets: [entry] } }).ok).toBe(false); + } + expect( + required( + parseDispatchTicketParameters({ + convene: { tickets: [{ id: "A", issue: wireIssue, target: wireTarget, dependsOn: ["B"] }] }, + }), + ), + ).toEqual({ op: "convene", parent: null, tickets: [{ id: "A", issue, target, dependsOn: ["B"], adoptPr: null }] }); }); test("zero-op seat tools map flat parameters using bound seat identity", () => { @@ -380,7 +417,7 @@ test("zero-op seat tools map flat parameters using bound seat identity", () => { test("structured coordinates refuse malformed owner/repo/number fields and string DSLs", () => { const badOwner = parseDispatchTicketParameters({ convene: { - tickets: [{ id: "A", issue: { owner: "bad/owner", repo: "omp-dispatch", number: 236 }, target: wireTarget, dependsOn: [] }], + tickets: [{ id: "A", issue: { owner: "bad/owner", repo: "omp-dispatch", number: 236 }, target: wireTarget, independent: true }], }, }); expect(badOwner.ok).toBe(false); @@ -388,7 +425,7 @@ test("structured coordinates refuse malformed owner/repo/number fields and strin const badNumber = parseDispatchTicketParameters({ convene: { - tickets: [{ id: "A", issue: { owner: "oh-my-omp", repo: "omp-dispatch", number: 0 }, target: wireTarget, dependsOn: [] }], + tickets: [{ id: "A", issue: { owner: "oh-my-omp", repo: "omp-dispatch", number: 0 }, target: wireTarget, independent: true }], }, }); expect(badNumber.ok).toBe(false); @@ -396,12 +433,140 @@ test("structured coordinates refuse malformed owner/repo/number fields and strin const stringDslRefused = parseDispatchTicketParameters({ convene: { - tickets: [{ id: "A", issue: "oh-my-omp/omp-dispatch#236", target: "oh-my-omp/omp-dispatch@main", dependsOn: [] }], + tickets: [{ id: "A", issue: "oh-my-omp/omp-dispatch#236", target: "oh-my-omp/omp-dispatch@main", independent: true }], }, }); expect(stringDslRefused.ok).toBe(false); }); +test("omompTool normalizes empty values and refuses empty array elements across all five tools", () => { + const grammar = buildPublicGrammar(z); + const wrap = (name: string, parameters: unknown, parseFn: (params: unknown) => T) => + omompTool({ + name, + parameters, + execute(_id: string, params: unknown) { + return parseFn(params); + }, + }); + + const ticketTool = wrap("dispatch_ticket", grammar.dispatchTicketParametersSchema, parseDispatchTicketParameters); + const stepTool = wrap("dispatch_step", grammar.dispatchStepParametersSchema, parseDispatchStepParameters); + const submitTool = wrap("dispatch_submit", grammar.seatSubmitParametersSchema, (p) => + parseSeatSubmitParameters(p, { ticketId: "A", revision: 2 }), + ); + const verdictTool = wrap("dispatch_verdict", grammar.seatVerdictParametersSchema, (p) => + parseSeatVerdictParameters(p, { ticketId: "A", revision: 2, role: "review" }), + ); + const escalateTool = wrap("dispatch_escalate", grammar.seatEscalateParametersSchema, (p) => + parseSeatEscalateParameters(p, { ticketId: "A", revision: 2 }), + ); + + expect(required(stepTool.execute("1", { ticketId: "A", launch: true, resolve: {} }))).toEqual({ op: "launch", ticketId: "A" }); + expect( + required( + stepTool.execute("2", { + ticketId: "A", + launch: true, + role: " ", + resolve: { dependsOn: [], target: { owner: " ", repo: "", branch: " " } }, + }), + ), + ).toEqual({ op: "launch", ticketId: "A" }); + expect(stepTool.execute("3", { ticketId: "A", launch: null, resolve: {} }).ok).toBe(false); + + const kept = required(stepTool.execute("4", { ticketId: "A", resolve: { revision: 3, ruling: "Keep.", to: "Coding", dependsOn: [] } })); + expect("dependsOn" in kept).toBe(false); + expect( + required( + stepTool.execute("5", { ticketId: "A", resolve: { revision: 3, ruling: "Independent.", to: "Coding", clearDependsOn: true } }), + ), + ).toEqual({ op: "resolve", ticketId: "A", revision: 3, ruling: "Independent.", to: "Coding", dependsOn: [] }); + expect( + stepTool.execute("6", { + ticketId: "A", + resolve: { + revision: 3, + ruling: "Add.", + to: "Coding", + add: [{ id: "C", issue: wireIssue, target: wireTarget, dependsOn: [] }], + }, + }).ok, + ).toBe(false); + + expect( + required( + ticketTool.execute("7", { + convene: { tickets: [{ id: "A", issue: wireIssue, target: wireTarget, independent: true }] }, + }), + ), + ).toEqual({ op: "convene", parent: null, tickets: [{ id: "A", issue, target, dependsOn: [], adoptPr: null }] }); + expect( + ticketTool.execute("8", { + convene: { tickets: [{ id: "A", issue: wireIssue, target: wireTarget, dependsOn: [] }] }, + }).ok, + ).toBe(false); + + for (const [field, value] of [ + ["dependsOn", [" "]], + ["remove", [""]], + ["add", [{}]], + ["effects", [{}]], + ["githubActions", [{}]], + ] as const) { + expect(() => + stepTool.execute("9", { + ticketId: "A", + resolve: { revision: 3, ruling: "Ruling.", to: "Coding", [field]: value }, + }), + ).toThrow(`resolve.${field}[0]: array element must not be empty`); + } + + const noCodeOmitted = required( + stepTool.execute("10", { ticketId: "A", resolve: { revision: 3, ruling: "Ruling.", to: "Coding", noCode: " ", clearAdoptPr: false } }), + ); + expect("noCode" in noCodeOmitted).toBe(false); + expect("adoptPr" in noCodeOmitted).toBe(false); + + expect(required(escalateTool.execute("11", { kind: "question", reason: "Which?", tier: " " }))).toEqual({ + op: "escalate", + ticketId: "A", + revision: 2, + kind: "question", + reason: "Which?", + }); + expect(required(escalateTool.execute("12", { kind: "question", reason: "Which?", tier: null }))).toEqual({ + op: "escalate", + ticketId: "A", + revision: 2, + kind: "question", + reason: "Which?", + }); + + expect(() => stepTool.execute("13", { ticketId: " ", launch: true })).toThrow('Validation failed for tool "dispatch_step"'); + expect(() => stepTool.execute("14", { ticketId: "A", resolve: { revision: 3, ruling: " ", to: "Coding" } })).toThrow( + 'Validation failed for tool "dispatch_step"', + ); + expect(() => escalateTool.execute("15", { kind: "blocked", reason: " " })).toThrow('Validation failed for tool "dispatch_escalate"'); + expect(() => submitTool.execute("16", { branch: " ", head: sha, title: "Deliver", body: "Closes #236" })).toThrow( + 'Validation failed for tool "dispatch_submit"', + ); + expect(() => verdictTool.execute("17", { ok: true, note: " " })).toThrow('Validation failed for tool "dispatch_verdict"'); + expect(ticketTool.execute("18", { finish: { summary: " " } })).toEqual(ticketTool.execute("18b", {})); + + expect( + required(submitTool.execute("19", { branch: "feature", head: sha, title: "Deliver", body: "Closes #236", revision: null })), + ).toEqual({ op: "submit", ticketId: "A", revision: 2, branch: "feature", head: sha, title: "Deliver", body: "Closes #236" }); + expect(required(verdictTool.execute("20", { ok: true, note: "Verified.", revision: null }))).toEqual({ + op: "verdict", + ticketId: "A", + revision: 2, + role: "review", + ok: true, + note: "Verified.", + }); +}); + test("the stored agenda formats still parse", () => { const fixtures = new URL("../tests/sim/fixtures/", import.meta.url); const names = readdirSync(fixtures).filter((name) => name.endsWith(".json"));