From 46e2bcdc35a5086dc6762ab807aaac725c8c7b55 Mon Sep 17 00:00:00 2001 From: Etan Joseph Heyman Date: Sat, 31 Oct 2026 13:29:22 +0200 Subject: [PATCH 1/6] fix(server): t3_workflow_run rejects specs it used to drop, and types its spec A stage with both agents and repeat ran its agents and silently dropped the repeat; unknown keys anywhere in a spec were stripped, so a run differed from what the model wrote. Both are now invalid_request with the stage named. Placeholders that mention a spec id but resolve to nothing are rejected, and until.path is checked against the judge's declared resultSchema. The judge no longer needs a parent-written resultSchema: the server gives it one with the field until reads, and adds the addAgents/rerun contract when the repeat has templates, so the judge sees the growth shape in its task. The tool description now types the spec as TypeScript. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/McpHttpServer.test.ts | 16 +++ apps/server/src/mcp/WorkflowRuns.test.ts | 4 +- .../src/mcp/advertisedJsonSchema.test.ts | 14 ++ apps/server/src/mcp/advertisedJsonSchema.ts | 15 ++- .../src/mcp/toolkits/orchestrator/tools.ts | 37 ++++-- apps/server/src/mcp/workflowRun.test.ts | 104 +++++++++++++++ apps/server/src/mcp/workflowRun.ts | 122 ++++++++++++++++-- .../src/provider/agentContextBudget.json | 2 +- evals/mcp-tool-use/run.test.ts | 20 +-- 9 files changed, 292 insertions(+), 42 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 484de4e6b1ff..0d2b6d0c5d87 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -487,6 +487,22 @@ it.effect("rejects a string workflow stage by naming the stage shape before the }).pipe(Effect.provide(layerRecordingTools(calls))); }); +it.effect( + "passes unknown workflow keys to the service, which rejects them, never strips them", + () => { + const calls: Array = []; + return Effect.gen(function* () { + const input = { + name: "review", + stages: [{ id: "draft", agents: [{ id: "a", task: "Draft." }], dependsOn: [] }], + timeout: 60_000, + }; + yield* callTool("t3_workflow_run", input).pipe(Effect.ignore); + expect(calls).toEqual([input]); + }).pipe(Effect.provide(layerRecordingTools(calls))); + }, +); + it("advertises workflow stages as objects that need an id", () => { const schema = advertisedJsonSchema(OrchestratorToolkit.tools.t3_workflow_run) as { properties: { stages: { items?: { type?: string; required?: Array } } }; diff --git a/apps/server/src/mcp/WorkflowRuns.test.ts b/apps/server/src/mcp/WorkflowRuns.test.ts index b283815f5209..ae842cb6753e 100644 --- a/apps/server/src/mcp/WorkflowRuns.test.ts +++ b/apps/server/src/mcp/WorkflowRuns.test.ts @@ -1269,7 +1269,9 @@ it.layer(layerTest)("t3_workflow_run", (it) => { const judged = { ok: false, addAgents: [{ template: "rewiter", task: "Fix line 1." }] }; yield* settleChild(critic, `\`\`\`json\n${JSON.stringify(judged)}\n\`\`\``); - const error = 'round 1 critic: addAgents[0]: unknown template "rewiter"'; + // The critic was delegated with its templates in its resultSchema, so its reply fails there. + const error = + 'round 1 critic: invalid_output: $.addAgents[0].template: not one of ["rewriter"]'; const row = yield* ended(parent.threadId, subagentId); assert.equal(row?.status, "failed"); assert.equal(JSON.parse(row?.result ?? "{}").error, error); diff --git a/apps/server/src/mcp/advertisedJsonSchema.test.ts b/apps/server/src/mcp/advertisedJsonSchema.test.ts index 09a90556a9dd..d9168f4fcb90 100644 --- a/apps/server/src/mcp/advertisedJsonSchema.test.ts +++ b/apps/server/src/mcp/advertisedJsonSchema.test.ts @@ -43,3 +43,17 @@ it("drops JSON noise, merges tagged unions, and keeps null where it is required" required: ["beforeRunId", "every"], }); }); + +it("advertises a struct that keeps unknown keys as the plain struct", () => { + const tool = Tool.make("example", { + parameters: Schema.StructWithRest(Schema.Struct({ id: Schema.String }), [ + Schema.Record(Schema.String, Schema.Unknown), + ]), + }); + + expect(advertisedJsonSchema(tool)).toEqual({ + type: "object", + properties: { id: { type: "string" } }, + required: ["id"], + }); +}); diff --git a/apps/server/src/mcp/advertisedJsonSchema.ts b/apps/server/src/mcp/advertisedJsonSchema.ts index 10001307f2d6..fe463b517b55 100644 --- a/apps/server/src/mcp/advertisedJsonSchema.ts +++ b/apps/server/src/mcp/advertisedJsonSchema.ts @@ -67,13 +67,15 @@ const mergeTaggedObjects = (branches: ReadonlyArray): JsonObject | undefin return { type: "object", properties, required: [tag, ...requiredByAll] }; }; +const isEmptyObject = (value: Json) => Predicate.isObject(value) && Object.keys(value).length === 0; + const compact = (schema: Json, optional: boolean): Json => { if (Array.isArray(schema)) return schema.map((item) => compact(item, false)); if (!Predicate.isObject(schema)) return schema; const required = new Set(Array.isArray(schema.required) ? schema.required : []); let result: JsonObject = {}; for (const [key, value] of Object.entries(schema)) { - if (key === "additionalProperties" && value === true) continue; + if (key === "additionalProperties" && (value === true || isEmptyObject(value))) continue; if (SAFE_INTEGER_BOUNDS[key] === value) continue; result[key] = key === "properties" && Predicate.isObject(value) @@ -85,6 +87,17 @@ const compact = (schema: Json, optional: boolean): Json => { ) : compact(value, false); } + // A `Schema.StructWithRest` rest compacts to an `allOf` branch that only restates the type. + if (Array.isArray(result.allOf)) { + const type = result.type; + const branches = result.allOf.filter( + (branch) => + !Predicate.isObject(branch) || + !Object.entries(branch).every(([key, value]) => key === "type" && value === type), + ); + const { allOf: _allOf, ...rest } = result; + result = branches.length === 0 ? rest : { ...rest, allOf: branches }; + } if (Array.isArray(result.anyOf)) { const branches = result.anyOf .flatMap((branch) => (isBareAnyOf(branch) ? branch.anyOf : [branch])) diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 67fafb4ce17e..8ee811070116 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -127,21 +127,32 @@ const TaskCancelTool = Tool.make("task_cancel", { const workflowDependencies = [...dependencies, WorkflowRuns.WorkflowRuns]; -// Stages advertise only their outline to keep the tool list small; the service decodes the full spec. -const WorkflowStage = Schema.Struct({ - id: Schema.String, - agents: Schema.optional(Schema.Array(Schema.Unknown)), - repeat: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), -}).annotate({ message: "stages[] entries are objects: {id, agents:[…]} or {id, repeat:{…}}" }); +// The description types the spec; the schema is an outline the service decodes in full. Unknown keys +// pass through so the service rejects them: stripping them would run a spec the model did not write. +const withRest = >(struct: S) => + Schema.StructWithRest(struct, [Schema.Record(Schema.String, Schema.Unknown)]); +const WorkflowStage = withRest( + Schema.Struct({ + id: Schema.String, + agents: Schema.optional(Schema.Array(Schema.Unknown)), + repeat: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + }), +).annotate({ message: "stages[] entries are objects: {id, agents:[…]} or {id, repeat:{…}}" }); const WorkflowRunTool = Tool.make("t3_workflow_run", { - description: - "Run stages in order; returns now, wakes you when done. Stage: `{id,agents:[{id,task,target?,role?,isolation?,resultSchema?}]}` (parallel) or `{id,repeat:{stages,judge,until:{path,equals},max,onExhausted?,dry?,templates?:{name:{task}}}}`. Its judge may return `addAgents:[{template,task?,input?,key?,stage?}]`, `rerun:[stage]`; `dry:N` ends after N rounds of neither. {{stage}},{{stage.agent}},{{feedback}},{{input.x}} insert output.", - parameters: Schema.Struct({ - name: TrimmedNonEmptyString, - stages: Schema.Array(WorkflowStage), - timeoutMs: Schema.optional(Schema.Int), - }), + description: `Run agents in stages; returns now, wakes you when done. +type Spec={name:string;stages:Stage[]} +type Stage={id:string;agents:Agent[]}|{id:string;repeat:Loop} // never both; agents run in parallel +type Agent={id:string;task:string;target?:{model?:string;options?:object}/*omit for yours*/;isolation?:'shared'|'worktree';resultSchema?:JSONSchema} +type Loop={stages:{id:string;agents:Agent[]}[]/*rerun in order each round*/;judge:string/*id of an agent in the LAST of these stages*/;until:{path:string/*field of the judge's result, e.g. 'ok'*/;equals:string|number|boolean};max:number/*rounds, 1-10*/;onExhausted?:'fail'|'pass';dry?:number;templates?:{[name:string]:{task:string}}} +In a task, {{stageId}} inserts all results of an earlier stage, {{stageId.agentId}} one. {{feedback}}: the judge's last result, null in round 1, so a fixer goes before the judge. The judge's result has until's field; with templates it may add addAgents:{template:string;task?:string;input?:object/*{{input.x}} in the template*/;stage?:string}[] (they run next round) and rerun:stageId[]; dry:N ends after N rounds with neither. Say so in its task.`, + parameters: withRest( + Schema.Struct({ + name: TrimmedNonEmptyString, + stages: Schema.Array(WorkflowStage), + timeoutMs: Schema.optional(Schema.Int), + }), + ), success: Schema.Struct({ subagentId: NodeId, next: Schema.Literal(ORCHESTRATOR_MCP_RUNNING_TASK_NEXT), diff --git a/apps/server/src/mcp/workflowRun.test.ts b/apps/server/src/mcp/workflowRun.test.ts index 54c8c3e97e33..1f729a1ce44f 100644 --- a/apps/server/src/mcp/workflowRun.test.ts +++ b/apps/server/src/mcp/workflowRun.test.ts @@ -683,6 +683,110 @@ it.effect("rejects bad references and judges before any start", () => }), ); +it.effect("rejects what it would otherwise drop or leave unresolved, before any start", () => + Effect.gen(function* () { + const one = (task: string) => ({ id: "x", task }); + const bad: Array<[unknown, string]> = [ + [ + { name: "both", stages: [{ id: "loop", agents: [one("x")], repeat: repeat(2) }] }, + "has both agents and repeat", + ], + [{ name: "key", stages: [{ id: "a", agents: [{ ...one("x"), model: "haiku" }] }] }, "model"], + [{ name: "top-key", stages: [{ id: "a", agents: [one("x")] }], timeout: 9 }, "timeout"], + [{ name: "stage-key", stages: [{ id: "a", agents: [one("x")], after: "b" }] }, "after"], + [ + { + name: "repeat-key", + stages: [draft, { id: "loop", repeat: { ...repeat(2), rounds: 3 } }], + }, + "rounds", + ], + [ + { name: "wrapper", stages: [draft, { id: "b", agents: [one("{{stage.draft}}")] }] }, + "{{stage.draft}}", + ], + [ + { name: "deep", stages: [draft, { id: "b", agents: [one("{{draft.a.result}}")] }] }, + "{{draft.a.result}}", + ], + [ + { + name: "until", + stages: [ + draft, + { + id: "loop", + repeat: { ...repeat(2), until: { path: "review.judge.verdict", equals: "accept" } }, + }, + ], + }, + "until.path", + ], + ]; + + for (const [input, message] of bad) { + const fake = makeFake({ reply: () => ({ outcome: ok("x") }) }); + const error = yield* runWorkflow(fake.port, input).pipe(Effect.flip); + expect(error.code).toBe("invalid_request"); + expect(error.message).toContain(message); + expect(fake.startCalls).toEqual([]); + } + }), +); + +it.effect("gives a judge the result schema its until and templates need", () => + Effect.gen(function* () { + const schemas = new Map(); + const fake = makeFake({ + reply: verdicts(["accept"]), + onStart: (start) => Effect.sync(() => schemas.set(start.key, start.agent.resultSchema)), + }); + const loop = repeat(2); + const [revise, review] = loop.stages; + const bare = { + ...review, + agents: [{ id: "judge", task: "Judge {{revise.writer}}." }], + }; + + const result = yield* runWorkflow(fake.port, { + name: "bare-judge", + stages: [ + draft, + { + id: "loop", + repeat: { ...loop, stages: [revise, bare], templates: { fix: { task: "Fix." } } }, + }, + ], + }); + + expect(result.status).toBe("completed"); + expect(schemas.get("review.judge#1")).toEqual({ + type: "object", + properties: { + verdict: { type: "string" }, + feedback: { type: "string" }, + addAgents: { + type: "array", + items: { + type: "object", + properties: { + template: { enum: ["fix"] }, + task: { type: "string" }, + input: { type: "object" }, + key: { type: "string" }, + stage: { enum: ["revise", "review"] }, + }, + required: ["template"], + }, + }, + rerun: { type: "array", items: { enum: ["revise", "review"] } }, + }, + required: ["verdict"], + }); + expect(schemas.get("revise.writer#1")).toBeUndefined(); + }), +); + /** Draft, probe, then a critic who judges and may grow the next round from two templates. */ const grow = (max: number, extra: Record = {}) => ({ name: "grow", diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index 003a36b2941e..4c1adc437dfc 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -8,6 +8,7 @@ import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; +import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; const DEFAULT_TIMEOUT_MS = 60 * 60 * 1_000; @@ -152,12 +153,29 @@ export const launchKey = (stage: string, round: number, agent: string) => `${stage}.${agent}#${round}`; const REFERENCE = /\{\{\s*([A-Za-z0-9_-]+)(?:\.([A-Za-z0-9_-]+))?\s*\}\}/g; +const EXACT_REFERENCE = new RegExp(`^${REFERENCE.source}$`); +const BRACES = /\{\{([^{}]*)\}\}/g; const CANCELLED: WorkflowAgentOutcome = { status: "cancelled", result: null }; const invalid = (message: string) => new OrchestratorMcpFailure({ code: "invalid_request", message }); -// Braces that name no stage stay literal, so a task can still show `{{x}}` syntax. +/** The field `until.path` names, as the parent's judge schema declares it, or null if it cannot tell. */ +function untilError(stage: RepeatStage, judge: WorkflowAgent): string | null { + let schema: unknown = judge.resultSchema; + for (const segment of stage.repeat.until.path.split(".")) { + const properties = isRecord(schema) && isRecord(schema.properties) ? schema.properties : null; + if (properties === null) return null; + if (!Object.hasOwn(properties, segment)) { + const example = Object.keys(properties)[0]; + return `Repeat "${stage.id}": until.path "${stage.repeat.until.path}" is not a field of judge "${judge.id}"'s resultSchema${example === undefined ? "" : `, such as "${example}"`}.`; + } + schema = properties[segment]; + } + return null; +} + +// Braces that name nothing in the spec stay literal, so a task can still show `{{x}}` syntax. function referenceError(spec: WorkflowSpec): string | null { const ids = new Set(); const repeats = new Set(); @@ -182,9 +200,8 @@ function referenceError(spec: WorkflowSpec): string | null { if (judge === undefined) { return `Repeat "${stage.id}": judge "${stage.repeat.judge}" must be an agent of its last stage.`; } - if (judge.resultSchema === undefined) { - return `Repeat "${stage.id}": judge "${judge.id}" needs a resultSchema for until.`; - } + const until = untilError(stage, judge); + if (until !== null) return until; } for (const s of inner) order.push({ stage: s, repeat: "agents" in stage ? null : stage }); // Templates check as if after the repeat's last stage: a grown agent may join any of them. @@ -197,21 +214,30 @@ function referenceError(spec: WorkflowSpec): string | null { } } const index = new Map(order.map(({ stage }, i) => [stage.id, i])); + const named = new Set([...ids, ...order.flatMap(({ stage }) => stage.agents.map((a) => a.id))]); for (const [position, { stage, repeat }] of order.entries()) { const agentIds = new Set(); for (const agent of stage.agents) { if (agentIds.has(agent.id)) return `Duplicate agent id "${stage.id}.${agent.id}".`; agentIds.add(agent.id); - for (const [text, stageRef, agentRef] of agent.task.matchAll(REFERENCE)) { + for (const [text, inner = ""] of agent.task.matchAll(BRACES)) { const where = `"${stage.id}.${agent.id}" uses ${text}`; + const [, stageRef, agentRef] = EXACT_REFERENCE.exec(text) ?? []; if (stageRef === "feedback") { - if (repeat === null || agentRef !== undefined) return `${where} outside a repeat.`; + if (repeat === null) return `${where} outside a repeat.`; + if (agentRef !== undefined) return `${where}; use {{feedback}}, the judge's last result.`; + continue; + } + if (stageRef === "input") continue; + const target = stageRef === undefined ? undefined : index.get(stageRef); + if (stageRef === undefined || target === undefined) { + // Braces that mention a spec id yet resolve to nothing would reach the agent verbatim. + if (inner.split(".").some((part) => named.has(part.trim()))) { + return `${where}, which is not a reference: use {{stage}} or {{stage.agent}}.`; + } continue; } - if (stageRef === undefined) continue; if (repeats.has(stageRef)) return `${where}; name one of the repeat's stages instead.`; - const target = index.get(stageRef); - if (target === undefined) continue; if (target >= position) return `${where}, which has not run yet.`; const known = order[target]?.stage.agents.some((a) => a.id === agentRef) ?? false; if (agentRef !== undefined && !known) return `${where}, which names no agent there.`; @@ -221,10 +247,34 @@ function referenceError(spec: WorkflowSpec): string | null { return null; } -const decodeSpec = Schema.decodeUnknownEffect(WorkflowSpec); +// An unknown key is a guess at a field that does not exist; ignoring it would run another spec. +const STRICT = { onExcessProperty: "error" } as const; +const decodeSpec = Schema.decodeUnknownEffect(WorkflowSpec, STRICT); +type StageDecoder = (stage: unknown) => Result.Result; +const stageDecoders: Record<"agents" | "repeat", StageDecoder> = { + agents: Schema.decodeUnknownResult(AgentStage, STRICT), + repeat: Schema.decodeUnknownResult(RepeatStage, STRICT), +}; + +/** The first stage that is not exactly one variant, judged by its own variant, not the union. */ +function stageError(input: unknown): string | null { + const stages = isRecord(input) && Array.isArray(input.stages) ? input.stages : []; + for (const [index, stage] of stages.entries()) { + if (!isRecord(stage)) continue; + const label = `Stage "${String(stage.id)}" (stages[${index}])`; + if ("agents" in stage && "repeat" in stage) { + return `${label} has both agents and repeat. Give it one: put a loop's agents in repeat.stages.`; + } + const decoded = stageDecoders["repeat" in stage ? "repeat" : "agents"](stage); + if (Result.isFailure(decoded)) return `${label}: ${decoded.failure.message}`; + } + return null; +} /** Decodes a spec and rejects unknown or forward references before anything starts. */ export const decodeWorkflowSpec = Effect.fn("WorkflowRun.decodeSpec")(function* (input: unknown) { + const shape = stageError(input); + if (shape !== null) return yield* invalid(shape); const spec = yield* decodeSpec(input).pipe(Effect.mapError((error) => invalid(error.message))); const error = referenceError(spec); if (error !== null) return yield* invalid(error); @@ -578,6 +628,51 @@ function decide(spec: WorkflowSpec, state: WorkflowSnapshot, now: number): Step return advance({ ...state, round: state.round + 1, phase: 0 }); } +/** + * What the judge is asked to return: the parent's schema, else one with the field `until` reads, plus + * the growth contract its templates need. The judge sees it in its task, so it never guesses one. + */ +function judgeSchema(stage: RepeatStage, judge: WorkflowAgent): WorkflowAgent["resultSchema"] { + const { stages, templates = {}, until } = stage.repeat; + const [field = "", ...rest] = until.path.split("."); + const leaf = { type: until.equals === null ? "null" : typeof until.equals }; + const nest = (schema: object, key: string) => ({ + type: "object", + properties: { [key]: schema }, + required: [key], + }); + const base = judge.resultSchema ?? { + type: "object", + properties: { [field]: rest.reduceRight(nest, leaf), feedback: { type: "string" } }, + required: [field], + }; + const names = Object.keys(templates); + if (names.length === 0) return base; + const ids = stages.map((s) => s.id); + const properties = isRecord(base.properties) ? base.properties : {}; + return { + ...base, + properties: { + addAgents: { + type: "array", + items: { + type: "object", + properties: { + template: { enum: names }, + task: { type: "string" }, + input: { type: "object" }, + key: { type: "string" }, + stage: { enum: ids }, + }, + required: ["template"], + }, + }, + rerun: { type: "array", items: { enum: ids } }, + ...properties, + }, + }; +} + /** A spec agent, or a grown one built from its template, with the task and input its judge gave it. */ function findAgent(spec: WorkflowSpec, state: WorkflowSnapshot, launch: WorkflowLaunch) { for (const stage of spec.stages) { @@ -586,6 +681,13 @@ function findAgent(spec: WorkflowSpec, state: WorkflowSnapshot, launch: Workflow ); if (phase === undefined) continue; const agent = phase.agents.find((a) => a.id === launch.agent); + if ( + !("agents" in stage) && + stage.repeat.stages.at(-1) === phase && + agent?.id === stage.repeat.judge + ) { + return { agent: { ...agent, resultSchema: judgeSchema(stage, agent) } }; + } if (agent !== undefined || "agents" in stage) return agent && { agent }; const add = growthIn(stage, state, launch.round - 1)?.adds.find((a) => a.key === launch.agent); const template = add && stage.repeat.templates?.[add.template]; diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 1d99b2763b8b..68a6ffa68e44 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5135, "codexAdditionalContextBytes": 6865, - "mcpToolListJsonBytes": 47106 + "mcpToolListJsonBytes": 47804 } diff --git a/evals/mcp-tool-use/run.test.ts b/evals/mcp-tool-use/run.test.ts index c5b005af9e55..244afc7e996e 100644 --- a/evals/mcp-tool-use/run.test.ts +++ b/evals/mcp-tool-use/run.test.ts @@ -148,23 +148,11 @@ it.effect("passes the staged-loop workflow case only for a real repeat stage", ( ]; const decodes = (stages: unknown) => Effect.exit(decodeWorkflowSpec({ name: "notes", stages })).pipe(Effect.map(Exit.isSuccess)); - const loop = real[1] as { repeat: { stages: Array<{ agents: Array }> } }; - const noSchema = [ - real[0], - { - ...loop, - repeat: { - ...loop.repeat, - stages: [ - loop.repeat.stages[0], - { id: "judge", agents: [agent("opus", "claude-opus-5-5")] }, - ], - }, - }, - ]; - expect([yield* decodes(real), yield* decodes(noSchema)]).toEqual([true, false]); + const loop = real[1] as { repeat: object }; + const judgeObject = [real[0], { ...loop, repeat: { ...loop.repeat, judge: { id: "opus" } } }]; + expect([yield* decodes(real), yield* decodes(judgeObject)]).toEqual([true, false]); expect(failed(staged.expect, run(real))).toEqual([]); - // The mock fails a spec the real decoder rejects, such as a judge without a resultSchema. + // The mock fails a spec the real decoder rejects, such as a judge given as an object. expect(failed(staged.expect, run(real, true))).not.toEqual([]); const named = [{ id: "repeat", agents: drafts.map((model, i) => agent(`d${i}`, model)) }]; expect(failed(staged.expect, run(named))).not.toEqual([]); From bbe4da2d06a5b1dfe003517b65a606687eafce67 Mon Sep 17 00:00:00 2001 From: Etan Joseph Heyman Date: Sat, 31 Oct 2026 13:55:31 +0200 Subject: [PATCH 2/6] fix(server): t3_workflow_run loop stages read last round, agents advertise as objects Codex parents sent every agent as a JSON string because the advertised schema gave agents no item type; agents (also inside repeat.stages) now advertise as objects. Inside a repeat, a stage may now read a same-loop stage that has not run yet this round: it gets last round's results, or null in round 1. A rewriter can fix its own previous version instead of failing with "has not run yet". The description says target can be omitted to inherit the parent's model and options, and that only a loop's judge adds agents, so round 1 belongs inside the loop. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/McpHttpServer.test.ts | 6 +++- .../src/mcp/toolkits/orchestrator/tools.ts | 16 ++++++--- apps/server/src/mcp/workflowRun.test.ts | 34 +++++++++++++++++++ apps/server/src/mcp/workflowRun.ts | 4 ++- .../src/provider/agentContextBudget.json | 2 +- 5 files changed, 55 insertions(+), 7 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 0d2b6d0c5d87..2884eee6fa11 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -492,9 +492,13 @@ it.effect( () => { const calls: Array = []; return Effect.gen(function* () { + const agents = [{ id: "a", task: "Draft." }]; const input = { name: "review", - stages: [{ id: "draft", agents: [{ id: "a", task: "Draft." }], dependsOn: [] }], + stages: [ + { id: "draft", agents, dependsOn: [] }, + { id: "loop", repeat: { stages: [{ id: "fix", agents }], judge: "a", max: 2 } }, + ], timeout: 60_000, }; yield* callTool("t3_workflow_run", input).pipe(Effect.ignore); diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 8ee811070116..4f3a1aa4a1b7 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -131,11 +131,19 @@ const workflowDependencies = [...dependencies, WorkflowRuns.WorkflowRuns]; // pass through so the service rejects them: stripping them would run a spec the model did not write. const withRest = >(struct: S) => Schema.StructWithRest(struct, [Schema.Record(Schema.String, Schema.Unknown)]); +// Codex sends the items of an array with no item type as JSON strings, so agents are typed objects. +const agents = Schema.optional(Schema.Array(Schema.Record(Schema.String, Schema.Unknown))); const WorkflowStage = withRest( Schema.Struct({ id: Schema.String, - agents: Schema.optional(Schema.Array(Schema.Unknown)), - repeat: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + agents, + repeat: Schema.optional( + withRest( + Schema.Struct({ + stages: Schema.optional(Schema.Array(withRest(Schema.Struct({ agents })))), + }), + ), + ), }), ).annotate({ message: "stages[] entries are objects: {id, agents:[…]} or {id, repeat:{…}}" }); @@ -143,9 +151,9 @@ const WorkflowRunTool = Tool.make("t3_workflow_run", { description: `Run agents in stages; returns now, wakes you when done. type Spec={name:string;stages:Stage[]} type Stage={id:string;agents:Agent[]}|{id:string;repeat:Loop} // never both; agents run in parallel -type Agent={id:string;task:string;target?:{model?:string;options?:object}/*omit for yours*/;isolation?:'shared'|'worktree';resultSchema?:JSONSchema} +type Agent={id:string;task:string;target?:{model?:string;options?:object}/*omit to inherit your model and options*/;isolation?:'shared'|'worktree';resultSchema?:JSONSchema} type Loop={stages:{id:string;agents:Agent[]}[]/*rerun in order each round*/;judge:string/*id of an agent in the LAST of these stages*/;until:{path:string/*field of the judge's result, e.g. 'ok'*/;equals:string|number|boolean};max:number/*rounds, 1-10*/;onExhausted?:'fail'|'pass';dry?:number;templates?:{[name:string]:{task:string}}} -In a task, {{stageId}} inserts all results of an earlier stage, {{stageId.agentId}} one. {{feedback}}: the judge's last result, null in round 1, so a fixer goes before the judge. The judge's result has until's field; with templates it may add addAgents:{template:string;task?:string;input?:object/*{{input.x}} in the template*/;stage?:string}[] (they run next round) and rerun:stageId[]; dry:N ends after N rounds with neither. Say so in its task.`, +In a task, {{stageId}} inserts an earlier stage's results, {{stageId.agentId}} one agent's. In a loop, a stage not yet run this round gives last round's (null in round 1); so does {{feedback}}, the judge's result. The judge's result has until's field; with templates it may add addAgents:{template:string;task?:string;input?:object/*{{input.x}} in the template*/;stage?:string}[] (they run next round) and rerun:stageId[]; dry:N ends after N rounds with neither. Only a loop's judge adds agents, so round 1 goes inside the loop.`, parameters: withRest( Schema.Struct({ name: TrimmedNonEmptyString, diff --git a/apps/server/src/mcp/workflowRun.test.ts b/apps/server/src/mcp/workflowRun.test.ts index 1f729a1ce44f..54cd88cec1c9 100644 --- a/apps/server/src/mcp/workflowRun.test.ts +++ b/apps/server/src/mcp/workflowRun.test.ts @@ -734,6 +734,40 @@ it.effect("rejects what it would otherwise drop or leave unresolved, before any }), ); +it.effect("lets a loop stage read its own loop's later stages as last round's results", () => + Effect.gen(function* () { + const fake = makeFake({ reply: verdicts(["reject", "accept"]) }); + const loop = repeat(2); + const [, review] = loop.stages; + + const result = yield* runWorkflow(fake.port, { + name: "back-reference", + stages: [ + draft, + { + id: "loop", + repeat: { + ...loop, + stages: [ + { + id: "revise", + agents: [{ id: "writer", task: "Fix {{revise.writer}} per {{review.judge}}." }], + }, + review, + ], + }, + }, + ], + }); + + expect(result.status).toBe("completed"); + expect(fake.rendered.get("revise.writer#1")).toBe("Fix null per null."); + expect(fake.rendered.get("revise.writer#2")).toBe( + 'Fix revise.writer#1 per {"verdict":"reject"}.', + ); + }), +); + it.effect("gives a judge the result schema its until and templates need", () => Effect.gen(function* () { const schemas = new Map(); diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index 4c1adc437dfc..8ecee78ffea8 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -238,7 +238,9 @@ function referenceError(spec: WorkflowSpec): string | null { continue; } if (repeats.has(stageRef)) return `${where}; name one of the repeat's stages instead.`; - if (target >= position) return `${where}, which has not run yet.`; + // In a loop, a stage that has not run this round reads last round's results (none in round 1). + const sameLoop = repeat !== null && order[target]?.repeat === repeat; + if (target >= position && !sameLoop) return `${where}, which has not run yet.`; const known = order[target]?.stage.agents.some((a) => a.id === agentRef) ?? false; if (agentRef !== undefined && !known) return `${where}, which names no agent there.`; } diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 68a6ffa68e44..ae55bf38c40a 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5135, "codexAdditionalContextBytes": 6865, - "mcpToolListJsonBytes": 47804 + "mcpToolListJsonBytes": 48069 } From edda7a635444d538aeb346503ac1670960044316 Mon Sep 17 00:00:00 2001 From: Etan Joseph Heyman Date: Sat, 31 Oct 2026 14:12:51 +0200 Subject: [PATCH 3/6] fix(server): t3_workflow_run defaults a loop's judge and allows empty loop stages A repeat that names no judge now takes its last stage's only agent; Sol parents left judge out while naming that agent "judge". A loop's stage may start with no agents, as the slot its judge grows agents into. The description says target options must be ones that model lists, and that after a loop its inner stages are referenced, not the loop's id. Co-Authored-By: Claude Opus 5.5 --- .../src/mcp/toolkits/orchestrator/tools.ts | 6 ++-- apps/server/src/mcp/workflowRun.test.ts | 36 +++++++++++++++++++ apps/server/src/mcp/workflowRun.ts | 23 ++++++++++-- .../src/provider/agentContextBudget.json | 2 +- 4 files changed, 60 insertions(+), 7 deletions(-) diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 4f3a1aa4a1b7..11ada7aee2c2 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -151,9 +151,9 @@ const WorkflowRunTool = Tool.make("t3_workflow_run", { description: `Run agents in stages; returns now, wakes you when done. type Spec={name:string;stages:Stage[]} type Stage={id:string;agents:Agent[]}|{id:string;repeat:Loop} // never both; agents run in parallel -type Agent={id:string;task:string;target?:{model?:string;options?:object}/*omit to inherit your model and options*/;isolation?:'shared'|'worktree';resultSchema?:JSONSchema} -type Loop={stages:{id:string;agents:Agent[]}[]/*rerun in order each round*/;judge:string/*id of an agent in the LAST of these stages*/;until:{path:string/*field of the judge's result, e.g. 'ok'*/;equals:string|number|boolean};max:number/*rounds, 1-10*/;onExhausted?:'fail'|'pass';dry?:number;templates?:{[name:string]:{task:string}}} -In a task, {{stageId}} inserts an earlier stage's results, {{stageId.agentId}} one agent's. In a loop, a stage not yet run this round gives last round's (null in round 1); so does {{feedback}}, the judge's result. The judge's result has until's field; with templates it may add addAgents:{template:string;task?:string;input?:object/*{{input.x}} in the template*/;stage?:string}[] (they run next round) and rerun:stageId[]; dry:N ends after N rounds with neither. Only a loop's judge adds agents, so round 1 goes inside the loop.`, +type Agent={id:string;task:string;target?:{model?:string;options?:object}/*omit to inherit your model and options; options must be ones that model lists*/;isolation?:'shared'|'worktree';resultSchema?:JSONSchema} +type Loop={stages:{id:string;agents:Agent[]/*[] to grow into*/}[]/*rerun in order each round*/;judge?:string/*id of an agent in the LAST of these stages; default: its only agent*/;until:{path:string/*field of the judge's result, e.g. 'ok'*/;equals:string|number|boolean};max:number/*rounds, 1-10*/;onExhausted?:'fail'|'pass';dry?:number;templates?:{[name:string]:{task:string}}} +In a task, {{stageId}} inserts an earlier stage's results, {{stageId.agentId}} one agent's; after a loop, name its inner stages, not the loop. In a loop, a stage not yet run this round gives last round's (null in round 1); so does {{feedback}}, the judge's result. The judge's result has until's field; with templates it may add addAgents:{template:string;task?:string;input?:object/*{{input.x}} in the template*/;stage?:string}[] (they run next round) and rerun:stageId[]; dry:N ends after N rounds with neither. Only a loop's judge adds agents, so round 1 goes inside the loop.`, parameters: withRest( Schema.Struct({ name: TrimmedNonEmptyString, diff --git a/apps/server/src/mcp/workflowRun.test.ts b/apps/server/src/mcp/workflowRun.test.ts index 54cd88cec1c9..6eafe800a682 100644 --- a/apps/server/src/mcp/workflowRun.test.ts +++ b/apps/server/src/mcp/workflowRun.test.ts @@ -734,6 +734,42 @@ it.effect("rejects what it would otherwise drop or leave unresolved, before any }), ); +it.effect( + "defaults a loop's judge to its last stage's only agent, and grows into empty stages", + () => + Effect.gen(function* () { + const fake = makeFake({ + reply: judging([{ addAgents: [{ key: "rw-1", template: "rewrite", stage: "fix" }] }, {}]), + }); + const { judge: _judge, ...loop } = grow(3).stages[0]!.repeat as Record; + const [draftStage, , critique] = grow(3).stages[0]!.repeat!.stages; + + const result = yield* runWorkflow(fake.port, { + name: "defaults", + stages: [ + { + id: "loop", + repeat: { + ...loop, + stages: [draftStage, { id: "fix", agents: [] }, critique], + max: 2, + onExhausted: "pass", + }, + }, + ], + }); + + expect(result.status).toBe("completed"); + expect(fake.startCalls).toEqual([ + "draft.poet#1", + "critique.critic#1", + "draft.poet#2", + "fix.rw-1#2", + "critique.critic#2", + ]); + }), +); + it.effect("lets a loop stage read its own loop's later stages as last round's results", () => Effect.gen(function* () { const fake = makeFake({ reply: verdicts(["reject", "accept"]) }); diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index 8ecee78ffea8..6e48f42c2766 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -26,14 +26,16 @@ export const WorkflowAgent = Schema.Struct({ export type WorkflowAgent = typeof WorkflowAgent.Type; const AgentStage = Schema.Struct({ id: WorkflowId, agents: Schema.NonEmptyArray(WorkflowAgent) }); -type AgentStage = typeof AgentStage.Type; +// A loop's stage may start empty: the judge grows agents into it. +const LoopStage = Schema.Struct({ id: WorkflowId, agents: Schema.Array(WorkflowAgent) }); +type AgentStage = typeof LoopStage.Type; const RoundCount = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })); const RepeatStage = Schema.Struct({ id: WorkflowId, repeat: Schema.Struct({ - stages: Schema.NonEmptyArray(AgentStage), + stages: Schema.NonEmptyArray(LoopStage), judge: WorkflowId, until: Schema.Struct({ path: TrimmedNonEmptyString, @@ -273,8 +275,23 @@ function stageError(input: unknown): string | null { return null; } +/** A loop that names no judge takes its last stage's only agent. */ +function withDefaultJudges(input: unknown): unknown { + if (!isRecord(input) || !Array.isArray(input.stages)) return input; + const stages = input.stages.map((stage: unknown) => { + if (!isRecord(stage) || !isRecord(stage.repeat) || "judge" in stage.repeat) return stage; + const last: unknown = Array.isArray(stage.repeat.stages) ? stage.repeat.stages.at(-1) : null; + const agents: unknown = isRecord(last) ? last.agents : null; + const [only] = Array.isArray(agents) && agents.length === 1 ? agents : []; + if (!isRecord(only) || typeof only.id !== "string") return stage; + return { ...stage, repeat: { ...stage.repeat, judge: only.id } }; + }); + return { ...input, stages }; +} + /** Decodes a spec and rejects unknown or forward references before anything starts. */ -export const decodeWorkflowSpec = Effect.fn("WorkflowRun.decodeSpec")(function* (input: unknown) { +export const decodeWorkflowSpec = Effect.fn("WorkflowRun.decodeSpec")(function* (raw: unknown) { + const input = withDefaultJudges(raw); const shape = stageError(input); if (shape !== null) return yield* invalid(shape); const spec = yield* decodeSpec(input).pipe(Effect.mapError((error) => invalid(error.message))); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index ae55bf38c40a..efe4941dcceb 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5135, "codexAdditionalContextBytes": 6865, - "mcpToolListJsonBytes": 48069 + "mcpToolListJsonBytes": 48204 } From ddb61bd8e4796675a93ae56ba744e6f042678f71 Mon Sep 17 00:00:00 2001 From: Etan Joseph Heyman Date: Sat, 31 Oct 2026 14:57:42 +0200 Subject: [PATCH 4/6] =?UTF-8?q?fix(server):=20t3=5Fworkflow=5Frun=20review?= =?UTF-8?q?=20round=201=20=E2=80=94=20loop=20reads,=20judge=20schema,=20un?= =?UTF-8?q?til=20checks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A same-loop stage that has not run this round reads only the last round it ran in, never a sibling finishing first in the current round, including after a resume. A whole-stage read with nothing earlier is null, as an agent read is. - The generated judge schema writes until's field after the default feedback field, so until.path "feedback" or "feedback.ok" keeps its type. - until.path is rejected only when the judge's schema rules it out: a closed object (additionalProperties: false), or a path starting with one of the loop's own stage/agent ids that the schema does not declare. Open schemas stay valid. - A parent's own judge schema wins; the server only adds absent growth fields. - Description: cut 153 B and advertise equals as nullable. Co-Authored-By: Claude Opus 5.5 --- .../src/mcp/toolkits/orchestrator/tools.ts | 8 +- apps/server/src/mcp/workflowRun.test.ts | 170 +++++++++++++++++- apps/server/src/mcp/workflowRun.ts | 63 +++++-- .../src/provider/agentContextBudget.json | 2 +- 4 files changed, 217 insertions(+), 26 deletions(-) diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 11ada7aee2c2..464f0ab82e71 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -150,10 +150,10 @@ const WorkflowStage = withRest( const WorkflowRunTool = Tool.make("t3_workflow_run", { description: `Run agents in stages; returns now, wakes you when done. type Spec={name:string;stages:Stage[]} -type Stage={id:string;agents:Agent[]}|{id:string;repeat:Loop} // never both; agents run in parallel -type Agent={id:string;task:string;target?:{model?:string;options?:object}/*omit to inherit your model and options; options must be ones that model lists*/;isolation?:'shared'|'worktree';resultSchema?:JSONSchema} -type Loop={stages:{id:string;agents:Agent[]/*[] to grow into*/}[]/*rerun in order each round*/;judge?:string/*id of an agent in the LAST of these stages; default: its only agent*/;until:{path:string/*field of the judge's result, e.g. 'ok'*/;equals:string|number|boolean};max:number/*rounds, 1-10*/;onExhausted?:'fail'|'pass';dry?:number;templates?:{[name:string]:{task:string}}} -In a task, {{stageId}} inserts an earlier stage's results, {{stageId.agentId}} one agent's; after a loop, name its inner stages, not the loop. In a loop, a stage not yet run this round gives last round's (null in round 1); so does {{feedback}}, the judge's result. The judge's result has until's field; with templates it may add addAgents:{template:string;task?:string;input?:object/*{{input.x}} in the template*/;stage?:string}[] (they run next round) and rerun:stageId[]; dry:N ends after N rounds with neither. Only a loop's judge adds agents, so round 1 goes inside the loop.`, +type Stage={id:string;agents:Agent[]}|{id:string;repeat:Loop} // never both; agents parallel +type Agent={id:string;task:string;target?:{model?:string;options?:object}/*omit to inherit model/options; options must match model*/;isolation?:'shared'|'worktree';resultSchema?:JSONSchema} +type Loop={stages:{id:string;agents:Agent[]/*may be empty*/}[];judge?:string/*agent id in LAST stage; defaults to its sole agent*/;until:{path:string/*judge result field, e.g. 'ok'*/;equals:string|number|boolean|null};max:number/*1-10 rounds*/;onExhausted?:'fail'|'pass';dry?:number;templates?:{[name:string]:{task:string}}} +Tasks: {{stageId}} or {{stageId.agentId}} insert earlier results. After a loop use inner stage ids, never its id. Loops rerun stages in order; forward/self references and {{feedback}} read last round (null in round 1). Judge schema is generated if omitted. With templates, judge may return addAgents:{template:string;task?:string;input?:object/*{{input.x}}*/;stage?:string}[] for next round and rerun:stageId[]. dry:N ends after N rounds with neither. Only loop judges add agents; put round 1 inside the loop.`, parameters: withRest( Schema.Struct({ name: TrimmedNonEmptyString, diff --git a/apps/server/src/mcp/workflowRun.test.ts b/apps/server/src/mcp/workflowRun.test.ts index 6eafe800a682..454db1f2361d 100644 --- a/apps/server/src/mcp/workflowRun.test.ts +++ b/apps/server/src/mcp/workflowRun.test.ts @@ -8,6 +8,7 @@ import * as Fiber from "effect/Fiber"; import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; +import { validateJson } from "./resultSchema.ts"; import { decodeWorkflowSpec, initialSnapshot, @@ -776,7 +777,7 @@ it.effect("lets a loop stage read its own loop's later stages as last round's re const loop = repeat(2); const [, review] = loop.stages; - const result = yield* runWorkflow(fake.port, { + const spec = { name: "back-reference", stages: [ draft, @@ -787,19 +788,60 @@ it.effect("lets a loop stage read its own loop's later stages as last round's re stages: [ { id: "revise", - agents: [{ id: "writer", task: "Fix {{revise.writer}} per {{review.judge}}." }], + agents: [ + { + id: "writer", + task: "Fix {{revise.writer}} per {{review.judge}} in {{revise}}.", + }, + { id: "peer", task: "Peer {{revise.writer}}, stage {{revise}}, {{review}}." }, + ], }, review, ], }, }, ], - }); + }; + + const result = yield* runWorkflow(fake.port, spec); expect(result.status).toBe("completed"); - expect(fake.rendered.get("revise.writer#1")).toBe("Fix null per null."); + expect(fake.rendered.get("revise.writer#1")).toBe("Fix null per null in null."); + expect(fake.rendered.get("revise.peer#1")).toBe("Peer null, stage null, null."); + const lastRound = '{"writer":"revise.writer#1","peer":"revise.peer#1"}'; expect(fake.rendered.get("revise.writer#2")).toBe( - 'Fix revise.writer#1 per {"verdict":"reject"}.', + `Fix revise.writer#1 per {"verdict":"reject"} in ${lastRound}.`, + ); + expect(fake.rendered.get("revise.peer#2")).toBe( + `Peer revise.writer#1, stage ${lastRound}, {"judge":{"verdict":"reject"}}.`, + ); + + // Resumed in round 2 after the writer finished there: the peer still reads round 1 only. + const decoded = yield* decodeWorkflowSpec(spec); + const done = (stage: string, round: number, agent: string, outcome: WorkflowAgentOutcome) => ({ + stage, + round, + agent, + taskId: `task:${launchKey(stage, round, agent)}`, + cancelRequested: false, + outcome, + }); + const resumed = makeFake({ reply: verdicts(["reject", "accept"]) }); + yield* resumeWorkflow(resumed.port, decoded, { + ...initialSnapshot(decoded, yield* Clock.currentTimeMillis), + cursor: 1, + round: 2, + launches: [ + done("draft", 1, "a", ok("A")), + done("draft", 1, "b", ok("B")), + done("revise", 1, "writer", ok("writer-1")), + done("revise", 1, "peer", ok("peer-1")), + done("review", 1, "judge", ok("verdict", { verdict: "reject" })), + done("revise", 2, "writer", ok("writer-2")), + ], + }); + expect(resumed.rendered.get("revise.peer#2")).toBe( + 'Peer writer-1, stage {"writer":"writer-1","peer":"peer-1"}, {"judge":{"verdict":"reject"}}.', ); }), ); @@ -854,6 +896,124 @@ it.effect("gives a judge the result schema its until and templates need", () => required: ["verdict"], }); expect(schemas.get("revise.writer#1")).toBeUndefined(); + + // A parent's own judge schema wins: its fields and constraints stay; only absent ones are added. + const own = { + type: "object", + properties: { verdict: { type: "string" }, addAgents: { type: "array" } }, + required: ["verdict", "addAgents"], + }; + const parented = makeFake({ + reply: verdicts(["accept"]), + onStart: (start) => Effect.sync(() => schemas.set(start.key, start.agent.resultSchema)), + }); + yield* runWorkflow(parented.port, { + name: "parent-judge", + stages: [ + draft, + { + id: "loop", + repeat: { + ...loop, + stages: [revise, { ...review, agents: [{ ...bare.agents[0]!, resultSchema: own }] }], + templates: { fix: { task: "Fix." } }, + }, + }, + ], + }); + expect(schemas.get("review.judge#1")).toEqual({ + ...own, + properties: { + ...own.properties, + rerun: { type: "array", items: { enum: ["revise", "review"] } }, + }, + }); + }), +); + +it.effect("a generated judge schema keeps until's field when it is named feedback", () => + Effect.gen(function* () { + for (const [path, accepting] of [ + ["feedback", { feedback: true }], + ["feedback.ok", { feedback: { ok: true } }], + ] as const) { + // The judge's reply passes through the real result validator, as a delegated task's does. + const fake = makeFake({ + reply: (start) => { + const value = start.agent.id === "judge" ? accepting : start.key; + const mismatch = + start.agent.resultSchema === undefined + ? null + : validateJson(start.agent.resultSchema, value); + return { + outcome: + mismatch === null + ? ok(start.key, start.agent.id === "judge" ? value : undefined) + : { status: "invalid_output", result: mismatch }, + }; + }, + }); + const loop = repeat(2); + const [revise, review] = loop.stages; + const result = yield* runWorkflow(fake.port, { + name: "feedback-until", + stages: [ + draft, + { + id: "loop", + repeat: { + ...loop, + stages: [revise, { ...review, agents: [{ id: "judge", task: "Judge." }] }], + until: { path, equals: true }, + }, + }, + ], + }); + expect({ path, status: result.status }).toEqual({ path, status: "completed" }); + } + }), +); + +it.effect("checks until.path only against what a judge schema actually rules out", () => + Effect.gen(function* () { + const withJudgeSchema = (resultSchema: Record) => { + const loop = repeat(2); + const [revise, review] = loop.stages; + return { + name: "until-path", + stages: [ + draft, + { + id: "loop", + repeat: { + ...loop, + stages: [ + revise, + { ...review, agents: [{ id: "judge", task: "Judge.", resultSchema }] }, + ], + until: { path: "ok", equals: true }, + }, + }, + ], + }; + }; + // Open schemas allow undeclared fields, so a path outside properties is still reachable. + const open = { type: "object", properties: { reason: { type: "string" } }, required: ["ok"] }; + const accepting = makeFake({ + reply: (start) => ({ + outcome: + start.agent.id === "judge" + ? ok("judged", { ok: true, reason: "accepted" }) + : ok(start.key), + }), + }); + expect((yield* runWorkflow(accepting.port, withJudgeSchema(open))).status).toBe("completed"); + + const closed = { ...open, required: [], additionalProperties: false }; + const fake = makeFake({ reply: () => ({ outcome: ok("x") }) }); + const error = yield* runWorkflow(fake.port, withJudgeSchema(closed)).pipe(Effect.flip); + expect(error.message).toContain('until.path "ok"'); + expect(fake.startCalls).toEqual([]); }), ); diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index 6e48f42c2766..65485a29f6d4 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -162,17 +162,33 @@ const CANCELLED: WorkflowAgentOutcome = { status: "cancelled", result: null }; const invalid = (message: string) => new OrchestratorMcpFailure({ code: "invalid_request", message }); -/** The field `until.path` names, as the parent's judge schema declares it, or null if it cannot tell. */ +/** + * Why `until.path` cannot be in the judge's result, or null. Open schemas allow undeclared fields, so + * a path is ruled out only by a closed object, or by starting with one of the loop's own ids + * (a `stage.agent.field` guess) that the schema does not declare. + */ function untilError(stage: RepeatStage, judge: WorkflowAgent): string | null { - let schema: unknown = judge.resultSchema; - for (const segment of stage.repeat.until.path.split(".")) { - const properties = isRecord(schema) && isRecord(schema.properties) ? schema.properties : null; - if (properties === null) return null; - if (!Object.hasOwn(properties, segment)) { - const example = Object.keys(properties)[0]; - return `Repeat "${stage.id}": until.path "${stage.repeat.until.path}" is not a field of judge "${judge.id}"'s resultSchema${example === undefined ? "" : `, such as "${example}"`}.`; + const { path } = stage.repeat.until; + const loopIds = new Set([ + stage.id, + ...stage.repeat.stages.flatMap((s) => [s.id, ...s.agents.map((a) => a.id)]), + ]); + let schema: unknown = judge.resultSchema ?? {}; + for (const [depth, segment] of path.split(".").entries()) { + if (!isRecord(schema)) return null; + const properties = isRecord(schema.properties) ? schema.properties : {}; + if (Object.hasOwn(properties, segment)) { + schema = properties[segment]; + continue; + } + const where = `Repeat "${stage.id}": until.path "${path}"`; + if (schema.additionalProperties === false) { + return `${where} is not a field judge "${judge.id}"'s resultSchema allows.`; } - schema = properties[segment]; + if (depth === 0 && loopIds.has(segment)) { + return `${where} names a stage or agent; it is a field of judge "${judge.id}"'s own result, such as "ok".`; + } + return null; } return null; } @@ -459,14 +475,20 @@ function dryStreak( /** delegate_task's prompt cap, in bytes; a task is measured before it is built. */ const TASK_BYTES = 120_000; -/** Null when the task would render past TASK_BYTES. `visible` limits the stages it may read. */ +/** + * Null when the task would render past TASK_BYTES. `from` is the rendering agent's stage; `visible` + * limits the stages it may read. + */ function renderTask( spec: WorkflowSpec, state: WorkflowSnapshot, template: string, + from: string, input?: Readonly>, visible?: ReadonlySet, ): string | null { + const loop = spec.stages[state.cursor]; + const order = loop === undefined || "agents" in loop ? [] : loop.repeat.stages.map((s) => s.id); const resolve = (match: string, stageRef: string, agentRef?: string) => { if (stageRef === "feedback") { const stage = spec.stages[state.cursor]; @@ -478,14 +500,22 @@ function renderTask( } if (visible !== undefined && !visible.has(stageRef)) return match; if (!agentStages(spec).some((stage) => stage.id === stageRef)) return match; + const completed = state.launches.filter( + (l) => l.stage === stageRef && l.outcome?.status === "completed", + ); + // A same-loop stage that has not run yet this round reads only the last round it ran in, so a + // sibling finishing first, or a resume, never changes what this task sees. + const ahead = order.includes(from) && order.indexOf(stageRef) >= order.indexOf(from); + const before = completed.filter((l) => l.round < state.round).map((l) => l.round); + const round = ahead ? Math.max(0, ...before) : undefined; const latest = new Map(); - for (const launch of state.launches) { - if (launch.stage === stageRef && launch.outcome?.status === "completed") { - latest.set(launch.agent, valueOf(launch.outcome)); + for (const launch of completed) { + if (round === undefined || launch.round === round) { + latest.set(launch.agent, valueOf(launch.outcome!)); } } if (agentRef !== undefined) return asText(latest.get(agentRef) ?? null); - return JSON.stringify(Object.fromEntries(latest)); + return latest.size === 0 && ahead ? "null" : JSON.stringify(Object.fromEntries(latest)); }; const values = new Map(); let bytes = Buffer.byteLength(template.replace(REFERENCE, "")); @@ -662,7 +692,8 @@ function judgeSchema(stage: RepeatStage, judge: WorkflowAgent): WorkflowAgent["r }); const base = judge.resultSchema ?? { type: "object", - properties: { [field]: rest.reduceRight(nest, leaf), feedback: { type: "string" } }, + // until's field comes last, so a path through `feedback` keeps its type. + properties: { feedback: { type: "string" }, [field]: rest.reduceRight(nest, leaf) }, required: [field], }; const names = Object.keys(templates); @@ -770,7 +801,7 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( return yield* update(key, { outcome: { status: "failed", result: "Not in the spec." } }); } const { agent } = found; - const task = renderTask(spec, state, agent.task, found.input, found.visible); + const task = renderTask(spec, state, agent.task, launch.stage, found.input, found.visible); if (task === null) { const result = `Its task renders to more than ${TASK_BYTES} bytes.`; return yield* update(key, { outcome: { status: "failed", result } }); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index efe4941dcceb..489dbc1dd223 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5135, "codexAdditionalContextBytes": 6865, - "mcpToolListJsonBytes": 48204 + "mcpToolListJsonBytes": 48051 } From 154db3ec3362845b2b452966136d1b951b0a9dee Mon Sep 17 00:00:00 2001 From: Etan Joseph Heyman Date: Sat, 31 Oct 2026 15:17:02 +0200 Subject: [PATCH 5/6] fix(server): t3_workflow_run description ties the judge's result to until again The round-1 cut dropped the sentence linking the judge's result to until, and Luna then omitted until in both grow-critics trials. Restore it, worded for a parent schema or a generated one. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/toolkits/orchestrator/tools.ts | 2 +- apps/server/src/provider/agentContextBudget.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 464f0ab82e71..d64ab517a342 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -153,7 +153,7 @@ type Spec={name:string;stages:Stage[]} type Stage={id:string;agents:Agent[]}|{id:string;repeat:Loop} // never both; agents parallel type Agent={id:string;task:string;target?:{model?:string;options?:object}/*omit to inherit model/options; options must match model*/;isolation?:'shared'|'worktree';resultSchema?:JSONSchema} type Loop={stages:{id:string;agents:Agent[]/*may be empty*/}[];judge?:string/*agent id in LAST stage; defaults to its sole agent*/;until:{path:string/*judge result field, e.g. 'ok'*/;equals:string|number|boolean|null};max:number/*1-10 rounds*/;onExhausted?:'fail'|'pass';dry?:number;templates?:{[name:string]:{task:string}}} -Tasks: {{stageId}} or {{stageId.agentId}} insert earlier results. After a loop use inner stage ids, never its id. Loops rerun stages in order; forward/self references and {{feedback}} read last round (null in round 1). Judge schema is generated if omitted. With templates, judge may return addAgents:{template:string;task?:string;input?:object/*{{input.x}}*/;stage?:string}[] for next round and rerun:stageId[]. dry:N ends after N rounds with neither. Only loop judges add agents; put round 1 inside the loop.`, +Tasks: {{stageId}} or {{stageId.agentId}} insert earlier results. After a loop use inner stage ids, never its id. Loops rerun stages in order; forward/self references and {{feedback}} read last round (null in round 1). The judge's result must have until's field; its schema is generated if omitted. With templates, judge may return addAgents:{template:string;task?:string;input?:object/*{{input.x}}*/;stage?:string}[] for next round and rerun:stageId[]. dry:N ends after N rounds with neither. Only loop judges add agents; put round 1 inside the loop.`, parameters: withRest( Schema.Struct({ name: TrimmedNonEmptyString, diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 489dbc1dd223..eae23d4e43d5 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5135, "codexAdditionalContextBytes": 6865, - "mcpToolListJsonBytes": 48051 + "mcpToolListJsonBytes": 48093 } From 0795c5b13ee08c3371176c58b61e991306809d9a Mon Sep 17 00:00:00 2001 From: Etan Joseph Heyman Date: Sat, 31 Oct 2026 15:41:33 +0200 Subject: [PATCH 6/6] fix(server): t3_workflow_run until.path honours patternProperties A closed judge schema (additionalProperties: false) still allows fields its patternProperties match, so until.path is now allowed when any pattern matches the segment, and descends into that pattern's schema. A pattern that fails to compile is treated as open and never rejects. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/workflowRun.test.ts | 46 +++++++++++++++++-------- apps/server/src/mcp/workflowRun.ts | 18 +++++++++- 2 files changed, 48 insertions(+), 16 deletions(-) diff --git a/apps/server/src/mcp/workflowRun.test.ts b/apps/server/src/mcp/workflowRun.test.ts index 454db1f2361d..8ac08cce4940 100644 --- a/apps/server/src/mcp/workflowRun.test.ts +++ b/apps/server/src/mcp/workflowRun.test.ts @@ -997,23 +997,39 @@ it.effect("checks until.path only against what a judge schema actually rules out ], }; }; - // Open schemas allow undeclared fields, so a path outside properties is still reachable. + // Open schemas allow undeclared fields, and a closed one still allows what a pattern matches. const open = { type: "object", properties: { reason: { type: "string" } }, required: ["ok"] }; - const accepting = makeFake({ - reply: (start) => ({ - outcome: - start.agent.id === "judge" - ? ok("judged", { ok: true, reason: "accepted" }) - : ok(start.key), - }), - }); - expect((yield* runWorkflow(accepting.port, withJudgeSchema(open))).status).toBe("completed"); - const closed = { ...open, required: [], additionalProperties: false }; - const fake = makeFake({ reply: () => ({ outcome: ok("x") }) }); - const error = yield* runWorkflow(fake.port, withJudgeSchema(closed)).pipe(Effect.flip); - expect(error.message).toContain('until.path "ok"'); - expect(fake.startCalls).toEqual([]); + const allowed = [ + open, + { + type: "object", + properties: { reason: { type: "string" } }, + patternProperties: { "^ok$": { type: "boolean" } }, + additionalProperties: false, + required: ["ok"], + }, + { ...closed, patternProperties: { "(": {} } }, + ]; + for (const schema of allowed) { + const accepting = makeFake({ + reply: (start) => ({ + outcome: + start.agent.id === "judge" + ? ok("judged", { ok: true, reason: "accepted" }) + : ok(start.key), + }), + }); + const { status } = yield* runWorkflow(accepting.port, withJudgeSchema(schema)); + expect({ schema, status }).toEqual({ schema, status: "completed" }); + } + + for (const schema of [closed, { ...closed, patternProperties: { "^no$": {} } }]) { + const fake = makeFake({ reply: () => ({ outcome: ok("x") }) }); + const error = yield* runWorkflow(fake.port, withJudgeSchema(schema)).pipe(Effect.flip); + expect(error.message).toContain('until.path "ok"'); + expect(fake.startCalls).toEqual([]); + } }), ); diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index 65485a29f6d4..4a4e74f9e91b 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -164,7 +164,8 @@ const invalid = (message: string) => /** * Why `until.path` cannot be in the judge's result, or null. Open schemas allow undeclared fields, so - * a path is ruled out only by a closed object, or by starting with one of the loop's own ids + * a path is ruled out only by a closed object whose properties and patterns all miss it, or by + * starting with one of the loop's own ids * (a `stage.agent.field` guess) that the schema does not declare. */ function untilError(stage: RepeatStage, judge: WorkflowAgent): string | null { @@ -181,6 +182,21 @@ function untilError(stage: RepeatStage, judge: WorkflowAgent): string | null { schema = properties[segment]; continue; } + const patterns = isRecord(schema.patternProperties) ? schema.patternProperties : {}; + let matched: unknown; + for (const [pattern, sub] of Object.entries(patterns)) { + let regex: RegExp; + try { + regex = new RegExp(pattern, "u"); + } catch { + return null; // A pattern this engine cannot compile may allow the field; never reject on it. + } + if (regex.test(segment)) matched ??= sub; + } + if (matched !== undefined) { + schema = matched; + continue; + } const where = `Repeat "${stage.id}": until.path "${path}"`; if (schema.additionalProperties === false) { return `${where} is not a field judge "${judge.id}"'s resultSchema allows.`;