Skip to content

Commit b216a01

Browse files
donjor-agent[bot]donjor
authored andcommitted
feat(server): delegated tasks continue across rounds (#1653)
## Problem A parent can't keep one delegated child across review rounds. Each `delegate_task` round spawns a fresh child, which loses its context. Sending to the child with `t3_thread_send` keeps context, but the parent is never woken, and `task_status` can't see that round. ## Change `delegate_task` accepts `continueTaskId`: it reopens a finished app-owned task and sends the new brief to that task's child. | Concern | Behavior | | --- | --- | | Task | same `taskId`, same child thread | | Wake | each round wakes the parent | | Result | one result transfer per child run | | Status | `task_status` reads the current round | | Cancel | `task_cancel` stops the current round | | Release | archiving the child releases it; unarchiving makes it continuable again | | Refusals | task still running, child busy, released, or unknown | | Design | Detail | | --- | --- | | Fork-owned | `delegatedRounds.fork.ts`, behind `fork-hook: delegated-rounds/*` seams in `Orchestrator.ts` | | Upstream paths | finalize and delivery stay upstream's; later rounds leave the original node and turn item unchanged | | Delivery reset | the reopened row sets `completionDelivery` to `pending`; the projection keeps a stored value when the payload omits it | | Docs | new `delegated-rounds` domain in `fork-delta.md`; retires when upstream ships delegated follow-ups | ## Scope and approval Fork feature tracked in #1652. Server, contracts, and MCP instructions only; no client changes. ## Verification | Check | Result | | --- | --- | | `vp test run`, two new fork tests | exit 0 (3 tests) | | `vp test run`, MCP service, control-reads, instructions, toolkit integration | exit 0 (22 tests) | | `vp exec tsc --noEmit`, server and contracts | exit 0 | | `vp run fork:ci` | exit 0 | | `vp run build` in `apps/server` | exit 0 | | Mutation: delivery reset removed | orchestrator test fails, `expected 'acknowledged' to equal 'claimed'` | Live run on a dev server: a Claude Sonnet 5.5 parent had a Claude Sonnet 5.5 child remember `PELICAN-42`, then continued the same task and asked for it back. Both rounds woke the parent, and the child recalled the codeword. `task_status` reported `completed`, summary `PELICAN-42`, run `ordinal:2`, and a new transfer ID. https://github.com/user-attachments/assets/ac99f00f-f561-4b8e-b1c6-403708464b54 | Span | Real | Clip | | --- | --- | --- | | prompt typed | 24s | 8x | | two rounds | 51s | 6x | | result | 7s | 1x | **Not checked:** release by archiving in the UI; the orchestrator test covers it. **Known quirk:** each round's activity row reads the one task, so round 1's row shows the latest summary. Claude Opus 5.5 in Claude Code, hosted in T3 Code. Refs #1652 ## Fork trailers Squashes: - 0157b4f feat(server): delegated tasks continue across rounds (#1653) (#1653) - 1e2a604 fixup! feat(server): delegated tasks continue across rounds (#1653) (#1653) - f8cba10 feat(server): delegated tasks continue across rounds (#1653) (#1653) - 75bbd2a fixup! feat(server): delegated tasks continue across rounds (#1653) (#1653) - 9a9dfd2 feat(server): delegated tasks continue across rounds (#1653) (#1653) - bf1ea32 fixup! feat(server): delegated tasks continue across rounds (#1653) (#1653) - 19887ba fixup! feat(server): delegated tasks continue across rounds (#1653) (#1653) - 94ff1f9 feat(server): delegated tasks continue across rounds (#1653) (#1653) - 8b5fc68 fixup! feat(server): delegated tasks continue across rounds (#1653) (#1653) Fork-Domain: delegated-rounds Fork-Tier: core Co-authored-by: donjor <[email protected]>
1 parent 1a5ce45 commit b216a01

11 files changed

Lines changed: 671 additions & 18 deletions

File tree

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { delegatedRoundProgressFork } from "../orchestration-v2/delegatedRounds.fork.ts"; // fork-hook: delegated-rounds/mcp-progress-import
12
import {
23
CommandId,
34
type RunId,
@@ -84,10 +85,7 @@ import * as Schema from "effect/Schema";
8485
import * as Stream from "effect/Stream";
8586

8687
import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
87-
import {
88-
subagentResultForRun,
89-
delegatedTaskProgress,
90-
} from "@t3tools/provider-core/server/subagentProjection";
88+
import { subagentResultForRun } from "@t3tools/provider-core/server/subagentProjection"; // fork-hook: delegated-rounds/mcp-result-import
9189
import {
9290
DispatchModeLimit,
9391
type DispatchModeRefusal,
@@ -1428,7 +1426,7 @@ const make = Effect.gen(function* () {
14281426
.pipe(Effect.mapError(threadManagementFailure));
14291427
const childRun = delegatedTaskRun(childControls, task);
14301428
const terminalRun = latestTerminalResultRun(childControls, childRun);
1431-
const progress = delegatedTaskProgress(childControls);
1429+
const progress = delegatedRoundProgressFork(childControls, task.threadId); // fork-hook: delegated-rounds/mcp-progress
14321430
const taskResultRun =
14331431
childRun?.delegatedTaskId === task.id
14341432
? childControls.runs
@@ -1502,7 +1500,9 @@ const make = Effect.gen(function* () {
15021500
? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined)
15031501
: undefined) ??
15041502
null);
1505-
const resultTransfer = taskResultTransfer(parentProjection, childProjection, task) ?? null;
1503+
const resultTransfer =
1504+
resultTransferForRun(taskResultRun) ??
1505+
(task.result === null ? null : taskResultTransfer(parentProjection, childProjection, task)); // fork-hook: delegated-rounds/current-round-transfer
15061506
const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun);
15071507
const latestTerminalSummary = canExposeTaskRunResult(terminalRun)
15081508
? terminalRun.id === childRun?.id
@@ -2280,6 +2280,7 @@ const make = Effect.gen(function* () {
22802280
// delegations deliver through the blocking tool call, so a wake is
22812281
// only needed if the parent settled first (timeout, disconnect).
22822282
completionWake: input.mode === "wait" ? "settled_only" : "always",
2283+
...(input.continueTaskId === undefined ? {} : { continueTaskId: input.continueTaskId }), // fork-hook: delegated-rounds/mcp-continue
22832284
})
22842285
.pipe(
22852286
Effect.mapError((error) =>
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
import { assert, it } from "@effect/vitest";
2+
import {
3+
CommandId,
4+
MessageId,
5+
NodeId,
6+
ProjectId,
7+
ProviderDriverKind,
8+
ProviderInstanceId,
9+
type RunId,
10+
ThreadId,
11+
} from "@t3tools/contracts";
12+
import * as Effect from "effect/Effect";
13+
import * as Layer from "effect/Layer";
14+
import * as Stream from "effect/Stream";
15+
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
16+
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
17+
import * as EventSink from "./EventSink.ts";
18+
import * as Orchestrator from "./Orchestrator.ts";
19+
import * as ProjectionStore from "./ProjectionStore.ts";
20+
import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
21+
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
22+
import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts";
23+
24+
const instanceId = ProviderInstanceId.make("codex");
25+
const modelSelection = { instanceId, model: "gpt-5.1-codex" };
26+
const adapter = {
27+
instanceId,
28+
driver: ProviderDriverKind.make("codex"),
29+
getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
30+
planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
31+
openSession: () => Effect.die("Rounds end before any provider starts"),
32+
} as ProviderAdapterV2Shape;
33+
const database = SqlitePersistenceMemory;
34+
const testLayer = Layer.mergeAll(
35+
database,
36+
ProjectionStore.layer.pipe(Layer.provide(database)),
37+
makeOrchestratorV2ReplayLayerWithRegistry(
38+
{ name: "delegated-rounds" },
39+
ProviderAdapterRegistry.makeLayer([adapter]),
40+
{ databaseLayer: database, runEffectWorker: false },
41+
),
42+
);
43+
44+
it.effect("a delegated task continues on the same child, one result per round", () =>
45+
Effect.gen(function* () {
46+
const orchestrator = yield* Orchestrator.OrchestratorV2;
47+
const projections = yield* ProjectionStore.ProjectionStoreV2;
48+
const eventSink = yield* EventSink.EventSinkV2;
49+
const parentThreadId = ThreadId.make("thread:rounds-parent");
50+
yield* orchestrator.dispatch({
51+
type: "thread.create",
52+
commandId: CommandId.make("create-rounds-parent"),
53+
threadId: parentThreadId,
54+
projectId: ProjectId.make("project:rounds"),
55+
title: "Rounds parent",
56+
modelSelection,
57+
runtimeMode: "full-access",
58+
interactionMode: "default",
59+
branch: null,
60+
worktreePath: null,
61+
createdBy: "user",
62+
creationSource: "web",
63+
});
64+
yield* orchestrator.dispatch({
65+
type: "message.dispatch",
66+
commandId: CommandId.make("start-rounds-parent"),
67+
threadId: parentThreadId,
68+
messageId: MessageId.make("message:rounds-parent"),
69+
text: "Delegate a review",
70+
attachments: [],
71+
dispatchMode: { type: "start_immediately" },
72+
createdBy: "user",
73+
creationSource: "web",
74+
});
75+
const parentRun = (yield* projections.getThreadProjection(parentThreadId)).runs[0]!;
76+
const delegate = (round: string, continueTaskId?: NodeId) =>
77+
orchestrator.dispatch({
78+
type: "delegated_task.request",
79+
commandId: CommandId.make(`delegate-${round}`),
80+
parentThreadId,
81+
parentRunId: parentRun.id,
82+
parentNodeId: parentRun.rootNodeId!,
83+
task: `Brief for ${round}`,
84+
modelSelection,
85+
runtimeMode: "full-access",
86+
interactionMode: "default",
87+
completionWake: "always",
88+
...(continueTaskId === undefined ? {} : { continueTaskId }),
89+
createdBy: "agent",
90+
creationSource: "mcp",
91+
});
92+
const refusal = (round: string, continueTaskId: NodeId) =>
93+
delegate(round, continueTaskId).pipe(
94+
Effect.flip,
95+
Effect.map((error) => String(error.cause)),
96+
);
97+
const readParent = projections.getThreadProjection(parentThreadId);
98+
const resultTransfers = readParent.pipe(
99+
Effect.map((parent) =>
100+
parent.contextTransfers.filter((transfer) => transfer.type === "subagent_result"),
101+
),
102+
);
103+
// finalize reacts to the terminal run on the event stream, after the
104+
// interrupt commits; the stream replays from the given sequence, so the
105+
// result transfer cannot be missed.
106+
const endRound = (childThreadId: ThreadId, runId: RunId, round: string) =>
107+
Effect.gen(function* () {
108+
const after = yield* eventSink.latestSequence();
109+
yield* orchestrator.dispatch({
110+
type: "run.interrupt",
111+
commandId: CommandId.make(`interrupt-${round}`),
112+
threadId: childThreadId,
113+
runId,
114+
});
115+
yield* eventSink
116+
.stream({
117+
threadId: parentThreadId,
118+
afterSequence: after,
119+
eventType: "context-transfer.created",
120+
})
121+
.pipe(Stream.take(1), Stream.runDrain);
122+
});
123+
124+
yield* delegate("round-1");
125+
const opened = (yield* readParent).subagents[0]!;
126+
const childThreadId = opened.childThreadId!;
127+
const round1Run = (yield* projections.getThreadProjection(childThreadId)).runs[0]!;
128+
yield* endRound(childThreadId, round1Run.id, "round-1");
129+
130+
const afterRound1 = yield* readParent;
131+
const node = afterRound1.nodes.find((candidate) => candidate.id === opened.id);
132+
const turnItem = afterRound1.turnItems.find(
133+
(candidate) => candidate.type === "subagent" && candidate.subagentId === opened.id,
134+
);
135+
assert.equal(afterRound1.subagents[0]!.status, "interrupted");
136+
assert.equal((yield* resultTransfers).length, 1);
137+
// task_status acknowledges the round it reads; the next round still wakes.
138+
yield* orchestrator.dispatch({
139+
type: "delegated_task.completion-delivery.acknowledge",
140+
commandId: CommandId.make("acknowledge-round-1"),
141+
parentThreadId,
142+
taskId: opened.id,
143+
observedByRunId: parentRun.id,
144+
});
145+
146+
yield* delegate("round-2", opened.id);
147+
const reopened = (yield* readParent).subagents[0]!;
148+
assert.equal(reopened.id, opened.id);
149+
assert.equal(reopened.status, "running");
150+
assert.equal(reopened.runId, parentRun.id);
151+
assert.isNull(reopened.result);
152+
assert.deepEqual(reopened.completionDelivery, { state: "pending", observedByRunId: null });
153+
const child = yield* projections.getThreadProjection(childThreadId);
154+
const round2Run = child.runs.find((run) => run.ordinal === 2)!;
155+
assert.ok(
156+
child.messages.some(
157+
(message) => message.runId === round2Run.id && message.senderThreadId === parentThreadId,
158+
),
159+
);
160+
assert.include(yield* refusal("round-2-again", opened.id), "still running a round");
161+
162+
yield* endRound(childThreadId, round2Run.id, "round-2");
163+
const afterRound2 = yield* readParent;
164+
const transfers = yield* resultTransfers;
165+
assert.equal(afterRound2.subagents[0]!.status, "interrupted");
166+
assert.equal(afterRound2.subagents[0]!.completionDelivery?.state, "claimed");
167+
assert.deepEqual(
168+
transfers.map((transfer) => transfer.sourcePoint.runId),
169+
[round1Run.id, round2Run.id],
170+
);
171+
assert.deepEqual(
172+
afterRound2.nodes.find((candidate) => candidate.id === opened.id),
173+
node,
174+
);
175+
assert.deepEqual(
176+
afterRound2.turnItems.find(
177+
(candidate) => candidate.type === "subagent" && candidate.subagentId === opened.id,
178+
),
179+
turnItem,
180+
);
181+
182+
// Upstream thread_send creates a separate task in this same child.
183+
yield* orchestrator.dispatch({
184+
type: "message.dispatch",
185+
commandId: CommandId.make("send-separate-followup"),
186+
threadId: childThreadId,
187+
senderThreadId: parentThreadId,
188+
messageId: MessageId.make("message:separate-followup"),
189+
text: "Independent follow-up",
190+
attachments: [],
191+
dispatchMode: { type: "start_immediately" },
192+
createdBy: "agent",
193+
creationSource: "mcp",
194+
});
195+
const followupRun = (yield* projections.getThreadProjection(childThreadId)).runs.find(
196+
(run) => run.ordinal === 3,
197+
)!;
198+
assert.ok(followupRun.delegatedTaskId);
199+
assert.notEqual(followupRun.delegatedTaskId, opened.id);
200+
yield* endRound(childThreadId, followupRun.id, "separate-followup");
201+
const afterFollowup = yield* readParent;
202+
assert.deepEqual(
203+
afterFollowup.subagents.find((candidate) => candidate.id === opened.id),
204+
afterRound2.subagents[0],
205+
);
206+
assert.equal(
207+
afterFollowup.subagents.find((candidate) => candidate.id === followupRun.delegatedTaskId)
208+
?.status,
209+
"interrupted",
210+
);
211+
assert.equal(
212+
afterFollowup.nodes.find((candidate) => candidate.id === followupRun.delegatedTaskId)?.status,
213+
"interrupted",
214+
);
215+
216+
yield* orchestrator.dispatch({
217+
type: "thread.archive",
218+
commandId: CommandId.make("release-child"),
219+
threadId: childThreadId,
220+
});
221+
assert.include(yield* refusal("round-3-released", opened.id), "was released");
222+
yield* orchestrator.dispatch({
223+
type: "thread.unarchive",
224+
commandId: CommandId.make("retain-child"),
225+
threadId: childThreadId,
226+
});
227+
yield* delegate("round-3", opened.id);
228+
assert.equal((yield* readParent).subagents[0]!.status, "running");
229+
const round3Run = (yield* projections.getThreadProjection(childThreadId)).runs.find(
230+
(run) => run.ordinal === 4,
231+
)!;
232+
yield* endRound(childThreadId, round3Run.id, "round-3");
233+
assert.equal((yield* readParent).subagents[0]!.status, "interrupted");
234+
assert.deepEqual(
235+
(yield* resultTransfers).map((transfer) => transfer.sourcePoint.runId),
236+
[round1Run.id, round2Run.id, followupRun.id, round3Run.id],
237+
);
238+
239+
assert.include(
240+
yield* refusal("unknown", NodeId.make("node:unknown")),
241+
"not an app-owned delegated task",
242+
);
243+
}).pipe(Effect.provide(testLayer)),
244+
);

0 commit comments

Comments
 (0)