From b03a25f1fc91e885513db091b0abd383d7231b10 Mon Sep 17 00:00:00 2001 From: Etan Joseph Heyman Date: Sat, 31 Oct 2026 04:27:12 +0200 Subject: [PATCH 1/2] feat(server): a workflow repeat grows within one run from its judge's result A repeat can declare agent templates. Its judge's structured result may add agents for the next round (addAgents, deduplicated by key across the run), choose which inner stages rerun, and an optional dry: K ends the loop after K rounds that add nothing and ask for no rerun. An invalid or missing judge result fails the run instead of voting dry. Grown agents are recorded as launches (stage.key#round) when the judge's result is processed, one per update, so their rows show before the next round starts and resume never starts them twice. Seen keys, the dry streak and each round's stage selection are derived from the persisted judge results. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/workflowRun.test.ts | 267 +++++++++++++++++++++- apps/server/src/mcp/workflowRun.ts | 261 +++++++++++++++++---- packages/contracts/src/orchestrationV2.ts | 2 +- 3 files changed, 475 insertions(+), 55 deletions(-) diff --git a/apps/server/src/mcp/workflowRun.test.ts b/apps/server/src/mcp/workflowRun.test.ts index 3a048b758496..adf39f83164d 100644 --- a/apps/server/src/mcp/workflowRun.test.ts +++ b/apps/server/src/mcp/workflowRun.test.ts @@ -33,6 +33,8 @@ interface FakeOptions { interface FakeTask { readonly key: string; + readonly stage: string; + readonly round: number; readonly reply: Reply; readonly finishAt: number; readonly cancelled: Deferred.Deferred; @@ -116,10 +118,10 @@ const makeFake = (options: FakeOptions) => { ) { violations.push(`${start.key} restarted after its task was recorded`); } - for (const launch of persisted.at(-1)?.snapshot.launches ?? []) { - const samePhase = launch.stage === start.stage && launch.round === start.round; - if (!samePhase && launch.outcome === null) { - violations.push(`${start.key} started while ${recordKey(launch)} was live`); + for (const task of tasks.values()) { + const samePhase = task.stage === start.stage && task.round === start.round; + if (!samePhase && task.settled === null) { + violations.push(`${start.key} started while ${task.key} was live`); } } const existing = tasks.get(`task:${start.key}`); @@ -128,6 +130,8 @@ const makeFake = (options: FakeOptions) => { const now = yield* Clock.currentTimeMillis; tasks.set(`task:${start.key}`, { key: start.key, + stage: start.stage, + round: start.round, reply, finishAt: now + ("afterMs" in reply ? (reply.afterMs ?? 0) : 0), cancelled: yield* Deferred.make(), @@ -633,6 +637,18 @@ it.effect("rejects bad references and judges before any start", () => ], }, { name: "fb", stages: [{ id: "a", agents: [one("{{feedback}}")] }] }, + { name: "reserved-input", stages: [{ id: "input", agents: [one("x")] }] }, + { + name: "template-forward", + stages: [ + { id: "loop", repeat: { ...repeat(2), templates: { t: { task: "{{polish}}" } } } }, + { id: "polish", agents: [one("x")] }, + ], + }, + { + name: "template-repeat", + stages: [{ id: "loop", repeat: { ...repeat(2), templates: { t: { task: "{{loop}}" } } } }], + }, { name: "dup-repeat", stages: [draft, { id: "draft", repeat: repeat(2) }] }, { name: "judge", stages: [draft, { id: "loop", repeat: { ...repeat(2), judge: "writer" } }] }, { @@ -663,3 +679,246 @@ it.effect("rejects bad references and judges before any start", () => } }), ); + +/** Draft, probe, then a critic who judges and may grow the next round from two templates. */ +const grow = (max: number, extra: Record = {}) => ({ + name: "grow", + stages: [ + { + id: "loop", + repeat: { + stages: [ + { id: "draft", agents: [{ id: "poet", task: "Write {{feedback}}." }] }, + { id: "probe", agents: [{ id: "reader", task: "Read {{draft}}." }] }, + { + id: "critique", + agents: [{ id: "critic", task: "Judge {{probe}}.", resultSchema: VERDICT }], + }, + ], + judge: "critic", + until: { path: "verdict", equals: "accept" }, + max, + templates: { + rewrite: { task: "Rewrite {{draft.poet}} for {{input.focus}}." }, + redteam: { task: "Attack {{draft}} on {{input.angle}}." }, + }, + ...extra, + }, + }, + { id: "polish", agents: [{ id: "editor", task: "Polish {{draft}}." }] }, + ], +}); +const rewrite = (key: string, focus: string) => ({ key, template: "rewrite", input: { focus } }); +const redteam = (key: string, angle: string) => ({ + key, + template: "redteam", + input: { angle }, + stage: "probe", +}); + +/** The critic's structured result by round, rejecting unless told otherwise; others echo. */ +const judged = + (byRound: ReadonlyArray>) => + (start: WorkflowAgentStart): WorkflowAgentOutcome => + start.agent.id === "critic" + ? ok("judged", { verdict: "reject", ...byRound[start.round - 1] }) + : ok(start.key); +const judging = + (byRound: ReadonlyArray>) => (start: WorkflowAgentStart) => ({ + outcome: judged(byRound)(start), + }); + +/** Round 1 grows both stages; round 2 repeats a key, adds one, reruns only probe; round 3 accepts. */ +const GROWN = [ + { addAgents: [rewrite("rw-1", "rhythm"), redteam("rt-1", "cliche")] }, + { addAgents: [rewrite("rw-1", "again"), redteam("rt-2", "meter")], rerun: ["probe"] }, + { verdict: "accept" }, +]; + +const roster = (result: WorkflowResult, round: number) => { + const loop = result.stages[0]; + if (loop === undefined || !("rounds" in loop)) return []; + return (loop.rounds[round - 1]?.stages ?? []).flatMap((stage) => + stage.agents.map((agent) => `${stage.id}.${agent.id}:${agent.status}`), + ); +}; + +it.effect( + "grows the next round from the judge's addAgents, deduplicated by key across the run", + () => + Effect.gen(function* () { + const fake = makeFake({ reply: judging(GROWN) }); + + const result = yield* runWorkflow(fake.port, grow(4)); + + expect(result.status).toBe("completed"); + expect(result.stages[0]).toMatchObject({ exit: "accepted" }); + expect(fake.startCalls).toEqual([ + "draft.poet#1", + "probe.reader#1", + "critique.critic#1", + "draft.poet#2", + "draft.rw-1#2", + "probe.reader#2", + "probe.rt-1#2", + "critique.critic#2", + "probe.reader#3", + "probe.rt-2#3", + "critique.critic#3", + "polish.editor#1", + ]); + expect(fake.rendered.get("probe.rt-1#2")).toBe( + 'Attack {"poet":"draft.poet#2","rw-1":"draft.rw-1#2"} on cliche.', + ); + expect(roster(result, 3)).toEqual([ + "draft.poet:skipped", + "probe.reader:completed", + "probe.rt-2:completed", + "critique.critic:completed", + ]); + // Grown rows are recorded with the judge's result, before the next round starts anything. + const grown = fake.persisted.find(({ snapshot }) => + snapshot.launches.some((l) => recordKey(l) === "probe.rt-1#2"), + )!.snapshot; + expect( + grown.launches.filter((l) => l.round === 2).map((l) => [recordKey(l), l.taskId]), + ).toEqual([ + ["draft.rw-1#2", null], + ["probe.rt-1#2", null], + ]); + expect(fake.violations).toEqual([]); + }), +); + +it.effect("exits after K consecutive dry votes, never on an invalid or missing judge result", () => + Effect.gen(function* () { + const dry = makeFake({ reply: judging([{ addAgents: [rewrite("rw-1", "x")] }]) }); + const dried = yield* runWorkflow(dry.port, grow(4, { dry: 2 })); + expect(dried.status).toBe("completed"); + expect(dried.stages[0]).toMatchObject({ exit: "dry" }); + expect(dry.created.filter((key) => key.startsWith("critique."))).toEqual([ + "critique.critic#1", + "critique.critic#2", + "critique.critic#3", + ]); + + // A rerun request is unresolved work, so those rounds never vote dry. + const busy = makeFake({ reply: judging([{ rerun: ["draft"] }, { rerun: ["draft"] }]) }); + expect((yield* runWorkflow(busy.port, grow(2, { dry: 1 }))).status).toBe("failed"); + + for (const bad of [ + { addAgents: [{ key: "x", template: "nope" }] }, + { addAgents: [{ key: "x", template: "rewrite", stage: "polish" }] }, + { rerun: ["polish"] }, + ]) { + const invalid = makeFake({ reply: judging([bad]) }); + expect((yield* runWorkflow(invalid.port, grow(3, { dry: 1 }))).status).toBe("failed"); + expect(invalid.created).not.toContain("draft.poet#2"); + } + const missing = makeFake({ reply: (start) => ({ outcome: ok(start.key) }) }); + expect((yield* runWorkflow(missing.port, grow(3, { dry: 1 }))).status).toBe("failed"); + expect(missing.created).not.toContain("draft.poet#2"); + }), +); + +it.effect("waits for grown agents before starting the next stage or judge", () => + Effect.gen(function* () { + const fake = makeFake({ + reply: (start) => ({ + afterMs: start.agent.id === "rw-1" ? 10_000 : 1_000, + outcome: judged(GROWN)(start), + }), + }); + + const fiber = yield* Effect.forkChild(runWorkflow(fake.port, grow(4))); + yield* TestClock.adjust("1 minute"); + const result = yield* Fiber.join(fiber); + + expect(result.status).toBe("completed"); + expect(fake.startCalls.indexOf("probe.reader#2")).toBeGreaterThan( + fake.startCalls.indexOf("draft.rw-1#2"), + ); + expect(fake.violations).toEqual([]); + }), +); + +it.effect("resumes a grown run without launching an instance twice", () => + Effect.gen(function* () { + const fake = makeFake({ + reply: judging(GROWN), + crash: (snapshot) => + snapshot.launches.some((l) => recordKey(l) === "draft.rw-1#2" && l.taskId !== null) + ? "instead" + : undefined, + }); + + const result = yield* runOnce(fake, grow(4)); + + expect(result.status).toBe("completed"); + expect(fake.startCalls.filter((key) => key === "draft.rw-1#2")).toHaveLength(2); + expect(fake.created.filter((key) => key === "draft.rw-1#2")).toHaveLength(1); + expect(new Set(fake.created).size).toBe(fake.created.length); + expect(fake.violations).toEqual([]); + }), +); + +it.effect("a stop after growth never starts a grown instance, across restart", () => + Effect.gen(function* () { + const spec = yield* decodeWorkflowSpec(grow(4)); + const fake = makeFake({ + reply: judging(GROWN), + crash: (snapshot) => + snapshot.launches.some((l) => recordKey(l) === "draft.rw-1#2") ? "after" : undefined, + }); + expect(Exit.isFailure(yield* Effect.exit(runWorkflow(fake.port, grow(4))))).toBe(true); + + const result = yield* resumeWorkflow(fake.port, spec, { ...fake.last()!, stop: true }); + + expect(result.status).toBe("cancelled"); + expect(fake.startCalls.filter((key) => key.endsWith("#2"))).toEqual([]); + expect( + fake + .last()! + .launches.filter((l) => l.round === 2) + .map((l) => [recordKey(l), l.outcome?.status]), + ).toEqual([["draft.rw-1#2", "cancelled"]]); + expect(fake.violations).toEqual([]); + }), +); + +it.effect("never grows a round beyond max", () => + Effect.gen(function* () { + const fake = makeFake({ + reply: (start) => ({ + outcome: judged([1, 2, 3].map((n) => ({ addAgents: [rewrite(`rw-${n}`, "x")] })))(start), + }), + }); + + const result = yield* runWorkflow(fake.port, grow(2)); + + expect(result.status).toBe("failed"); + expect( + fake.persisted.every(({ snapshot }) => snapshot.launches.every((l) => l.round <= 2)), + ).toBe(true); + expect(fake.created.filter((key) => key.endsWith("#3"))).toEqual([]); + }), +); + +it.effect("a run that grows survives a crash at, and instead of, every persist", () => + Effect.gen(function* () { + const check = (fake: Fake, result: WorkflowResult) => { + expect(result.status).toBe("completed"); + expect(fake.violations).toEqual([]); + expect(new Set(fake.created).size).toBe(fake.created.length); + for (const { snapshot } of fake.persisted) { + expect(decodeSnapshot(JSON.parse(JSON.stringify(snapshot)))).toEqual(snapshot); + } + }; + yield* crashSweep(grow(4), judging(GROWN), check); + yield* crashSweep( + grow(4, { dry: 2 }), + judging([{ addAgents: [rewrite("rw-1", "x"), redteam("rt-1", "y")] }]), + check, + ); + }), +); diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index 9d9ff832777b..eff0ff18275b 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -27,6 +27,8 @@ export type WorkflowAgent = typeof WorkflowAgent.Type; const AgentStage = Schema.Struct({ id: WorkflowId, agents: Schema.NonEmptyArray(WorkflowAgent) }); type AgentStage = typeof AgentStage.Type; +const RoundCount = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })); + const RepeatStage = Schema.Struct({ id: WorkflowId, repeat: Schema.Struct({ @@ -36,12 +38,39 @@ const RepeatStage = Schema.Struct({ path: TrimmedNonEmptyString, equals: Schema.Union([Schema.String, Schema.Number, Schema.Boolean, Schema.Null]), }), - max: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10 })), + max: RoundCount, onExhausted: Schema.optional(Schema.Literals(["fail", "pass"])), + dry: Schema.optional(RoundCount), + templates: Schema.optional( + Schema.Record( + Schema.String, + Schema.Struct({ + task: WorkflowAgent.fields.task, + target: WorkflowAgent.fields.target, + resultSchema: WorkflowAgent.fields.resultSchema, + }), + ), + ), }), }); type RepeatStage = typeof RepeatStage.Type; +/** What a judge's structured result may ask of the next round, beyond `until`. */ +const Growth = Schema.Struct({ + addAgents: Schema.optional( + Schema.Array( + Schema.Struct({ + key: WorkflowId, + template: Schema.String, + input: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + stage: Schema.optional(Schema.String), + }), + ), + ), + rerun: Schema.optional(Schema.Array(Schema.String)), +}); +const decodeGrowth = Schema.decodeUnknownOption(Growth); + export const WorkflowSpec = Schema.Struct({ name: TrimmedNonEmptyString, stages: Schema.NonEmptyArray(Schema.Union([AgentStage, RepeatStage])), @@ -80,7 +109,7 @@ export const WorkflowSnapshot = Schema.Struct({ exits: Schema.Array( Schema.Struct({ stage: WorkflowId, - reason: Schema.Literals(["accepted", "exhausted"]), + reason: Schema.Literals(["accepted", "exhausted", "dry"]), round: Schema.Int, }), ), @@ -121,7 +150,7 @@ export type WorkflowResult = { | StageResult | { readonly id: string; - readonly exit: "accepted" | "exhausted" | null; + readonly exit: WorkflowSnapshot["exits"][number]["reason"] | null; readonly rounds: ReadonlyArray<{ readonly round: number; readonly stages: ReadonlyArray; @@ -143,11 +172,18 @@ const invalid = (message: string) => function referenceError(spec: WorkflowSpec): string | null { const ids = new Set(); const repeats = new Set(); - const order: Array<{ stage: AgentStage; repeat: RepeatStage | null }> = []; + const order: Array<{ + stage: { + readonly id: string; + readonly agents: ReadonlyArray>; + }; + repeat: RepeatStage | null; + }> = []; for (const stage of spec.stages) { const inner = "agents" in stage ? [stage] : stage.repeat.stages; for (const id of [stage.id, ...("agents" in stage ? [] : inner.map((s) => s.id))]) { - if (id === "feedback") return `"feedback" is reserved and cannot name a stage.`; + if (id === "feedback" || id === "input") + return `"${id}" is reserved and cannot name a stage.`; if (ids.has(id)) return `Duplicate stage id "${id}".`; ids.add(id); } @@ -162,6 +198,14 @@ function referenceError(spec: WorkflowSpec): string | null { } } 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. + if (!("agents" in stage)) { + const agents = Object.entries(stage.repeat.templates ?? {}).map(([id, { task }]) => ({ + id, + task, + })); + order.push({ stage: { id: stage.id, agents }, repeat: stage }); + } } const index = new Map(order.map(({ stage }, i) => [stage.id, i])); for (const [position, { stage, repeat }] of order.entries()) { @@ -209,14 +253,62 @@ const asText = (value: unknown) => (typeof value === "string" ? value : JSON.str export const agentStages = (spec: WorkflowSpec) => spec.stages.flatMap((stage) => ("agents" in stage ? [stage] : stage.repeat.stages)); -function renderTask(spec: WorkflowSpec, state: WorkflowSnapshot, template: string): string { +const judgedIn = (state: WorkflowSnapshot, stage: RepeatStage, round: number) => + findLaunch(state, stage.repeat.stages.at(-1)?.id ?? "", round, stage.repeat.judge)?.outcome + ?.structuredResult; + +/** The judge's requests for the next round; null when it names a template or stage not in the repeat. */ +function growthOf(stage: RepeatStage, value: unknown) { + const growth = Option.getOrNull(decodeGrowth(value)); + if (growth === null) return null; + const { stages, templates = {} } = stage.repeat; + const ids = stages.map((s) => s.id); + const adds = (growth.addAgents ?? []).map((add) => ({ + ...add, + stage: add.stage ?? stages[0].id, + })); + const known = + adds.every((add) => ids.includes(add.stage) && Object.hasOwn(templates, add.template)) && + (growth.rerun ?? []).every((id) => ids.includes(id)); + return known ? { adds, rerun: growth.rerun ?? [] } : null; +} + +const isGrown = (stage: RepeatStage, launch: WorkflowLaunch) => + stage.repeat.stages.some( + (s) => s.id === launch.stage && !s.agents.some((agent) => agent.id === launch.agent), + ); + +/** Round 1 and the judge's stage always run; later rounds run what the last judge named, or all. */ +function runsAgain(stage: RepeatStage, state: WorkflowSnapshot, phaseId: string) { + if (state.round === 1 || phaseId === stage.repeat.stages.at(-1)?.id) return true; + const rerun = growthOf(stage, judgedIn(state, stage, state.round - 1))?.rerun ?? []; + return rerun.length === 0 || rerun.includes(phaseId); +} + +/** Consecutive dry votes ending at this round: rounds that grew nothing and asked for no rerun. */ +function dryStreak(stage: RepeatStage, state: WorkflowSnapshot, dryNow: boolean) { + const wasDry = (round: number) => + !state.launches.some((l) => l.round === round + 1 && isGrown(stage, l)) && + !growthOf(stage, judgedIn(state, stage, round))?.rerun.length; + let streak = dryNow ? 1 : 0; + while (streak > 0 && streak < state.round && wasDry(state.round - streak)) streak += 1; + return streak; +} + +function renderTask( + spec: WorkflowSpec, + state: WorkflowSnapshot, + template: string, + input?: Readonly>, +): string { return template.replace(REFERENCE, (match, stageRef: string, agentRef?: string) => { if (stageRef === "feedback") { const stage = spec.stages[state.cursor]; if (stage === undefined || "agents" in stage) return match; - const judges = stage.repeat.stages.at(-1)?.id ?? ""; - const judge = findLaunch(state, judges, state.round - 1, stage.repeat.judge); - return JSON.stringify(judge?.outcome?.structuredResult ?? null); + return JSON.stringify(judgedIn(state, stage, state.round - 1) ?? null); + } + if (stageRef === "input" && input !== undefined) { + return agentRef === undefined ? JSON.stringify(input) : asText(input[agentRef] ?? null); } if (!agentStages(spec).some((stage) => stage.id === stageRef)) return match; const latest = new Map(); @@ -242,6 +334,7 @@ function accepts(until: RepeatStage["repeat"]["until"], value: unknown): boolean type Step = | { readonly _tag: "finish"; readonly status: typeof WorkflowRunStatus.Type } | { readonly _tag: "launch"; readonly stage: string; readonly agent: WorkflowAgent } + | { readonly _tag: "start" | "record"; readonly launch: WorkflowLaunch } | { readonly _tag: "advance"; readonly state: WorkflowSnapshot } | { readonly _tag: "wait" }; @@ -257,34 +350,86 @@ function decide(spec: WorkflowSpec, state: WorkflowSnapshot, now: number): Step } const stage = spec.stages[state.cursor]; if (stage === undefined) return finish("completed"); + const loop = "agents" in stage ? null : stage; const phase = "agents" in stage ? stage : stage.repeat.stages[state.phase]; if (phase === undefined) return finish("failed"); - const launches = phase.agents.map((agent) => ({ - agent, - launch: findLaunch(state, phase.id, state.round, agent.id), - })); - const unlaunched = launches.find(({ launch }) => launch === undefined); - if (unlaunched !== undefined) return { _tag: "launch", stage: phase.id, agent: unlaunched.agent }; - if (launches.some(({ launch }) => launch?.outcome === null)) return { _tag: "wait" }; + if (loop === null || runsAgain(loop, state, phase.id)) { + const unlaunched = phase.agents.find( + (agent) => findLaunch(state, phase.id, state.round, agent.id) === undefined, + ); + if (unlaunched !== undefined) return { _tag: "launch", stage: phase.id, agent: unlaunched }; + } + // Grown agents, and launches a crash cut off before their task id was recorded. + const current = state.launches.filter((l) => l.stage === phase.id && l.round === state.round); + const intent = current.find((l) => l.taskId === null && l.outcome === null); + if (intent !== undefined) return { _tag: "start", launch: intent }; + if (current.some((l) => l.outcome === null)) return { _tag: "wait" }; const next = { ...state, cursor: state.cursor + 1, round: 1, phase: 0 }; - if ("agents" in stage) return advance(next); - const { repeat } = stage; + if (loop === null) return advance(next); + const { repeat } = loop; if (state.phase < repeat.stages.length - 1) return advance({ ...state, phase: state.phase + 1 }); - const exit = (reason: "accepted" | "exhausted") => ({ + const exit = (reason: WorkflowSnapshot["exits"][number]["reason"]) => ({ ...next, - exits: [...state.exits, { stage: stage.id, reason, round: state.round }], + exits: [...state.exits, { stage: loop.id, reason, round: state.round }], + }); + const value = judgedIn(state, loop, state.round); + if (accepts(repeat.until, value)) return advance(exit("accepted")); + // A missing or malformed judge result fails the run; it never counts as a dry vote. + const growth = growthOf(loop, value); + if (growth === null) return finish("failed"); + const round = state.round + 1; + const recorded = state.launches.filter((l) => l.round === round && isGrown(loop, l)); + const seen = new Set([ + ...repeat.stages.flatMap((s) => s.agents.map((agent) => agent.id)), + ...state.launches.filter((l) => l.round < round && isGrown(loop, l)).map((l) => l.agent), + ]); + const grown = growth.adds.filter(({ key }) => { + const fresh = !seen.has(key); + seen.add(key); + return fresh; }); - const judge = findLaunch(state, phase.id, state.round, repeat.judge); - if (accepts(repeat.until, judge?.outcome?.structuredResult)) return advance(exit("accepted")); - if (state.round < repeat.max) return advance({ ...state, round: state.round + 1, phase: 0 }); - return repeat.onExhausted === "pass" ? advance(exit("exhausted")) : finish("failed"); + const dryNow = grown.length === 0 && growth.rerun.length === 0; + if (repeat.dry !== undefined && dryStreak(loop, state, dryNow) >= repeat.dry) { + return advance(exit("dry")); + } + if (state.round === repeat.max) { + return repeat.onExhausted === "pass" ? advance(exit("exhausted")) : finish("failed"); + } + // One row per update keeps each within the wire budget; all land before the next round starts. + const add = grown[recorded.length]; + if (add === undefined) return advance({ ...state, round, phase: 0 }); + return { + _tag: "record", + launch: { + stage: add.stage, + round, + agent: add.key, + taskId: null, + cancelRequested: false, + outcome: null, + }, + }; } -const findAgent = (spec: WorkflowSpec, launch: WorkflowLaunch) => - agentStages(spec) - .find((stage) => stage.id === launch.stage) - ?.agents.find((agent) => agent.id === launch.agent); +/** A spec agent, or a grown one built from its template and the input its judge gave it. */ +function findAgent(spec: WorkflowSpec, state: WorkflowSnapshot, launch: WorkflowLaunch) { + for (const stage of spec.stages) { + const phase = ("agents" in stage ? [stage] : stage.repeat.stages).find( + (s) => s.id === launch.stage, + ); + if (phase === undefined) continue; + const agent = phase.agents.find((a) => a.id === launch.agent); + if (agent !== undefined || "agents" in stage) return agent && { agent }; + const add = growthOf(stage, judgedIn(state, stage, launch.round - 1))?.adds.find( + (a) => a.key === launch.agent, + ); + const template = add && stage.repeat.templates?.[add.template]; + if (add === undefined || template === undefined) return undefined; + return { agent: { ...template, id: add.key }, input: add.input ?? {} }; + } + return undefined; +} type WorkflowEvent = | { readonly _tag: "settled"; readonly key: string; readonly outcome: WorkflowAgentOutcome } @@ -331,11 +476,12 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( ); const startTask = Effect.fn("WorkflowRun.startAgent")(function* (launch: WorkflowLaunch) { const key = keyOf(launch); - const agent = findAgent(spec, launch); - if (agent === undefined) { + const found = findAgent(spec, state, launch); + if (found === undefined) { return yield* update(key, { outcome: { status: "failed", result: "Not in the spec." } }); } - const task = renderTask(spec, state, agent.task); + const { agent } = found; + const task = renderTask(spec, state, agent.task, found.input); const started = yield* port .start({ key, stage: launch.stage, round: launch.round, agent, task }) .pipe(Effect.result); @@ -355,9 +501,8 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( ); } for (const launch of state.launches) { - if (launch.outcome !== null) continue; - if (launch.taskId === null) yield* startTask(launch); - else yield* watch(keyOf(launch), launch.taskId); + if (launch.outcome === null && launch.taskId !== null) + yield* watch(keyOf(launch), launch.taskId); } const apply = (event: WorkflowEvent) => { @@ -399,6 +544,12 @@ export const resumeWorkflow = Effect.fn("WorkflowRun.resume")(function* ( yield* startTask(launch); break; } + case "start": + yield* startTask(step.launch); + break; + case "record": + yield* save({ ...state, launches: [...state.launches, step.launch] }); + break; case "advance": state = step.state; break; @@ -421,24 +572,34 @@ export const initialSnapshot = (spec: WorkflowSpec, now: number): WorkflowSnapsh }); export function workflowResult(spec: WorkflowSpec, state: WorkflowSnapshot): WorkflowResult { + const agentResult = (id: string, launch: WorkflowLaunch | undefined): AgentResult => { + if (launch === undefined) return { id, status: "skipped", taskId: null, result: null }; + const { outcome } = launch; + return { + id, + status: outcome?.status ?? "running", + taskId: launch.taskId, + result: outcome?.result ?? null, + ...(outcome?.structuredResult === undefined + ? {} + : { structuredResult: outcome.structuredResult }), + }; + }; const agents = (stage: AgentStage, round: number): StageResult => ({ id: stage.id, - agents: stage.agents.map((agent): AgentResult => { - const launch = findLaunch(state, stage.id, round, agent.id); - if (launch === undefined) { - return { id: agent.id, status: "skipped", taskId: null, result: null }; - } - const { outcome } = launch; - return { - id: agent.id, - status: outcome?.status ?? "running", - taskId: launch.taskId, - result: outcome?.result ?? null, - ...(outcome?.structuredResult === undefined - ? {} - : { structuredResult: outcome.structuredResult }), - }; - }), + agents: [ + ...stage.agents.map((agent) => + agentResult(agent.id, findLaunch(state, stage.id, round, agent.id)), + ), + ...state.launches + .filter( + (l) => + l.stage === stage.id && + l.round === round && + !stage.agents.some((agent) => agent.id === l.agent), + ) + .map((l) => agentResult(l.agent, l)), + ], }); return { name: spec.name, diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 91230b96b1f5..08fdcf73d99e 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -864,7 +864,7 @@ export const OrchestrationV2WorkflowRunState = Schema.Struct({ exits: Schema.Array( Schema.Struct({ stage: Schema.String, - reason: Schema.Literals(["accepted", "exhausted"]), + reason: Schema.Literals(["accepted", "exhausted", "dry"]), round: NonNegativeInt, }), ), From bacd92f6f510ed4cf3583d756b4cce33720698fa Mon Sep 17 00:00:00 2001 From: Etan Joseph Heyman Date: Sat, 31 Oct 2026 04:42:34 +0200 Subject: [PATCH 2/2] fix(server): a workflow judge's growth is checked before acceptance and its keys are unique run-wide An accepting judge whose addAgents or rerun named an unknown template or stage, or was malformed, passed the repeat. Growth is now validated first, so invalid growth fails the run and never accepts or votes dry. Grown keys were deduplicated only within the current repeat, so a key could collide with a static agent elsewhere or grow in two repeats; seen keys now cover every spec agent and every earlier launch in the run. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/workflowRun.test.ts | 70 +++++++++++++++++++++++++ apps/server/src/mcp/workflowRun.ts | 9 ++-- 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/apps/server/src/mcp/workflowRun.test.ts b/apps/server/src/mcp/workflowRun.test.ts index adf39f83164d..34054f1ec123 100644 --- a/apps/server/src/mcp/workflowRun.test.ts +++ b/apps/server/src/mcp/workflowRun.test.ts @@ -821,6 +821,76 @@ it.effect("exits after K consecutive dry votes, never on an invalid or missing j }), ); +it.effect("an accepting judge whose growth is invalid fails the run instead of passing", () => + Effect.gen(function* () { + for (const bad of [ + { verdict: "accept", rerun: ["polish"] }, + { verdict: "accept", addAgents: [{ key: "x", template: "nope" }] }, + { verdict: "accept", addAgents: "bad" }, + ]) { + const fake = makeFake({ reply: judging([bad]) }); + const result = yield* runWorkflow(fake.port, grow(3, { dry: 1 })); + expect({ bad, status: result.status }).toEqual({ bad, status: "failed" }); + expect(result.stages[0]).toMatchObject({ exit: null }); + expect(fake.created).not.toContain("polish.editor#1"); + } + for (const raw of [null, "bad", []]) { + const fake = makeFake({ + reply: (start) => ({ + outcome: start.agent.id === "critic" ? ok("judged", raw) : ok(start.key), + }), + }); + const result = yield* runWorkflow(fake.port, grow(3, { dry: 1 })); + expect({ raw, status: result.status }).toEqual({ raw, status: "failed" }); + } + }), +); + +it.effect("deduplicates grown keys across the whole run, not just the current repeat", () => + Effect.gen(function* () { + const second = { + id: "again", + repeat: { + stages: [ + { id: "redraft", agents: [{ id: "poet2", task: "Write." }] }, + { id: "recheck", agents: [{ id: "critic2", task: "Judge.", resultSchema: VERDICT }] }, + ], + judge: "critic2", + until: { path: "verdict", equals: "accept" }, + max: 2, + templates: { rewrite: { task: "Rewrite for {{input.focus}}." } }, + }, + }; + const spec = { + name: "two-loops", + stages: [{ id: "intro", agents: [{ id: "seed", task: "Seed." }] }, grow(2).stages[0], second], + }; + const judge = (start: WorkflowAgentStart, addAgents: ReadonlyArray) => + ok("judged", start.round === 1 ? { verdict: "reject", addAgents } : { verdict: "accept" }); + const fake = makeFake({ + reply: (start) => ({ + outcome: + start.agent.id === "critic" + ? judge(start, [rewrite("seed", "x"), rewrite("poet2", "w"), rewrite("gap", "y")]) + : start.agent.id === "critic2" + ? judge(start, [rewrite("gap", "z")]) + : ok(start.key), + }), + }); + + const result = yield* runWorkflow(fake.port, spec); + + expect(result.status).toBe("completed"); + // A static agent of a later repeat counts as seen before it ever runs. + expect(fake.created).not.toContain("draft.poet2#2"); + expect(fake.created.filter((key) => /\.(seed|gap)#/.test(key))).toEqual([ + "intro.seed#1", + "draft.gap#2", + ]); + expect(fake.violations).toEqual([]); + }), +); + it.effect("waits for grown agents before starting the next stage or judge", () => Effect.gen(function* () { const fake = makeFake({ diff --git a/apps/server/src/mcp/workflowRun.ts b/apps/server/src/mcp/workflowRun.ts index eff0ff18275b..f9781e6057cb 100644 --- a/apps/server/src/mcp/workflowRun.ts +++ b/apps/server/src/mcp/workflowRun.ts @@ -374,15 +374,16 @@ function decide(spec: WorkflowSpec, state: WorkflowSnapshot, now: number): Step exits: [...state.exits, { stage: loop.id, reason, round: state.round }], }); const value = judgedIn(state, loop, state.round); - if (accepts(repeat.until, value)) return advance(exit("accepted")); - // A missing or malformed judge result fails the run; it never counts as a dry vote. + // A missing or malformed judge result fails the run; it never accepts or counts as dry. const growth = growthOf(loop, value); if (growth === null) return finish("failed"); + if (accepts(repeat.until, value)) return advance(exit("accepted")); const round = state.round + 1; const recorded = state.launches.filter((l) => l.round === round && isGrown(loop, l)); + // Keys are unique across the run: every spec agent and every launch before this batch. const seen = new Set([ - ...repeat.stages.flatMap((s) => s.agents.map((agent) => agent.id)), - ...state.launches.filter((l) => l.round < round && isGrown(loop, l)).map((l) => l.agent), + ...agentStages(spec).flatMap((s) => s.agents.map((agent) => agent.id)), + ...state.launches.filter((l) => !recorded.includes(l)).map((l) => l.agent), ]); const grown = growth.adds.filter(({ key }) => { const fresh = !seen.has(key);