Skip to content

Commit 39c7a87

Browse files
Merge pull request #174 from ScriptedAlchemy/codex/delegated-assignment-outcomes
fix(server): preserve delegated assignments and report child run outcomes
2 parents c26218f + d5a8e64 commit 39c7a87

37 files changed

Lines changed: 511 additions & 119 deletions

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,22 @@ export const withRuntimeModeCeiling = (
133133
};
134134
};
135135

136+
export function linkedMessageSender(
137+
client: McpClientCaller | undefined,
138+
origin: { readonly sessionId: string } | undefined,
139+
): { readonly linkedSender?: OrchestrationV2LinkedSender } {
140+
if (client?.linked !== true || client.senderThread === undefined) return {};
141+
const { environmentId, threadId, title } = client.senderThread;
142+
return {
143+
linkedSender: {
144+
environmentId,
145+
threadId,
146+
title,
147+
...(client.sessionId === origin?.sessionId ? { fromOriginatingLink: true } : {}),
148+
},
149+
};
150+
}
151+
136152
/** Thread callers default to their own thread; client callers need thread for tools that act as the caller. */
137153
export interface McpInvocationScope {
138154
readonly environmentId: EnvironmentId;

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

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -524,7 +524,7 @@ describe("OrchestratorMcpService", () => {
524524
const childThreadId = ThreadId.make("thread:mcp-report-child");
525525
const taskA = NodeId.make("node:mcp-report-task-a");
526526
const taskB = NodeId.make("node:mcp-report-task-b");
527-
const silent = "Child task completed without an assistant result.";
527+
const silent = "Child run completed without an assistant result.";
528528
const parentProjection = {
529529
thread: { id: parentThreadId },
530530
runs: [],
@@ -606,10 +606,11 @@ describe("OrchestratorMcpService", () => {
606606
yield* Effect.gen(function* () {
607607
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
608608
// Task A reported, then a run queued behind the report ended without text.
609-
reports = [[1, "REPORT-A"]];
609+
reports = [[1, "I need access before I can review the change."]];
610610
const reported = yield* service.taskStatus(scope, taskA);
611611
assert.equal(reported.status, "completed");
612-
assert.equal(reported.summary, "REPORT-A");
612+
assert.equal(reported.assignmentOutcome, "unverified");
613+
assert.equal(reported.summary, "I need access before I can review the change.");
613614
assert.equal(reported.latestTerminalRunId, runs[2]!.id);
614615
assert.equal(reported.latestTerminalSummary, silent);
615616
assert.equal((yield* service.taskStatus(scope, taskB)).summary, silent);
@@ -5576,16 +5577,19 @@ describe("OrchestratorMcpService thread lookup", () => {
55765577

55775578
it.effect("records the linked environment's thread that sent a message", () =>
55785579
Effect.gen(function* () {
5579-
const target = liveThreadShell(ThreadId.make("thread:target"));
5580+
const target = {
5581+
...liveThreadShell(ThreadId.make("thread:target")),
5582+
linkOrigin: { sessionId: "link-a", label: "A", access: "full-access" as const },
5583+
};
55805584
const sender = {
55815585
environmentId: EnvironmentId.make("environment:a"),
55825586
threadId: ThreadId.make("thread:orc"),
55835587
title: "orc lead",
55845588
};
5585-
const linked = (senderThread?: typeof sender): McpInvocationScope => ({
5589+
const linked = (senderThread?: typeof sender, sessionId = "link-a"): McpInvocationScope => ({
55865590
...client,
55875591
client: {
5588-
sessionId: "link-a",
5592+
sessionId,
55895593
label: "A",
55905594
access: "full-access",
55915595
linked: true,
@@ -5617,7 +5621,8 @@ describe("OrchestratorMcpService thread lookup", () => {
56175621
});
56185622

56195623
const fromLink = yield* sendAs(linked(sender));
5620-
assert.deepStrictEqual(fromLink?.linkedSender, sender);
5624+
assert.deepStrictEqual(fromLink?.linkedSender, { ...sender, fromOriginatingLink: true });
5625+
assert.deepStrictEqual((yield* sendAs(linked(sender, "another-link")))?.linkedSender, sender);
56215626
assert.isUndefined(fromLink?.senderThreadId);
56225627
assert.isUndefined((yield* sendAs(linked()))?.linkedSender);
56235628
}),

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

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ import {
135135
type McpThreadInvocationScope,
136136
requireThreadScope,
137137
threadLinkFor,
138+
linkedMessageSender,
138139
} from "./McpInvocationContext.ts";
139140
import * as Metrics from "../observability/Metrics.ts";
140141
import {
@@ -1983,6 +1984,7 @@ const make = Effect.gen(function* () {
19831984
childRunId: childRun?.id ?? null,
19841985
childNodeId: task.id,
19851986
status,
1987+
...(status === "completed" ? { assignmentOutcome: "unverified" as const } : {}),
19861988
workState,
19871989
hasPendingChildRuns: hasPendingChildRuns(childProjection, childRun),
19881990
providerInstanceId: modelSelection.instanceId,
@@ -2178,6 +2180,7 @@ const make = Effect.gen(function* () {
21782180
childRunId: null,
21792181
childNodeId: task.id,
21802182
status,
2183+
...(status === "completed" ? { assignmentOutcome: "unverified" as const } : {}),
21812184
workState: terminal ? "result_available" : "working",
21822185
hasPendingChildRuns: false,
21832186
providerInstanceId: task.providerInstanceId,
@@ -3712,11 +3715,9 @@ const make = Effect.gen(function* () {
37123715
operation: "thread-send",
37133716
}),
37143717
threadId: input.threadId,
3715-
...(parent === undefined ? {} : { senderThreadId: parent.thread.id }),
3716-
// A linked environment's agent has no thread here; the link names it.
3717-
...(parent === undefined && scope.client?.senderThread !== undefined
3718-
? { linkedSender: scope.client.senderThread }
3719-
: {}),
3718+
...(parent === undefined
3719+
? linkedMessageSender(scope.client, target.thread.linkOrigin)
3720+
: { senderThreadId: parent.thread.id }),
37203721
messageId,
37213722
text: input.message,
37223723
attachments: [],

‎apps/server/src/mcp/linkOrigin.test.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -355,12 +355,17 @@ it.layer(Layer.provideMerge(layerTools, layerOrchestration))("work a link starts
355355

356356
// A link's delegated task names its parent there; only a link's launch may.
357357
const delegatedFrom = {
358-
environmentId: "environment-laptop",
359-
threadId: "thread:laptop-parent",
358+
environmentId: EnvironmentId.make("environment-laptop"),
359+
threadId: ThreadId.make("thread:laptop-parent"),
360360
title: "Laptop parent",
361361
};
362-
const task = yield* launch(laptop, "Delegated from the laptop", { delegatedFrom });
362+
const origin = { ...laptop, client: { ...laptop.client!, senderThread: delegatedFrom } };
363+
const task = yield* launch(origin, "Delegated from the laptop", { delegatedFrom });
363364
assert.deepEqual((yield* projections.getThreadShell(task))?.delegatedFrom, delegatedFrom);
365+
const mismatched = yield* launch(origin, "Other parent", {
366+
delegatedFrom: { ...delegatedFrom, threadId: "other" },
367+
});
368+
assert.equal((yield* projections.getThreadShell(mismatched))?.delegatedFrom, undefined);
364369
const claimed = yield* launch(claudeCode, "Claims a parent", { delegatedFrom });
365370
assert.equal((yield* projections.getThreadShell(claimed))?.delegatedFrom, undefined);
366371
}),

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ const DelegateTaskTool = Tool.make("delegate_task", {
102102

103103
const TaskStatusTool = Tool.make("task_status", {
104104
description:
105-
"Read a child task you started only after its completion wakes you. workState: working, waiting_for_children, result_available. A finished turn with live child work is not done. Reading summary marks the final result delivered.",
105+
"Read your child after its wake. workState: working, waiting_for_children, result_available. Child work can outlive a finished run. A completed run may report a blocker. Reading summary marks the result delivered.",
106106
parameters: OrchestratorMcpTaskStatusInput,
107107
success: OrchestratorMcpDelegateTaskResult,
108108
failure: OrchestratorMcpFailure,

‎apps/server/src/mcp/toolkits/project/handlers.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
type Project as ProjectRecord,
1111
type ModelSelection,
1212
type RuntimeMode,
13+
type OrchestrationV2DelegatedFrom,
1314
type OrchestrationV2ThreadShell,
1415
ThreadId,
1516
} from "@t3tools/contracts";
@@ -56,6 +57,7 @@ const clientLaunchHarness = (input: {
5657
readonly overrideModel?: ModelSelection;
5758
readonly launched: Array<ThreadLaunch.ThreadLaunchInput>;
5859
readonly clientSessionId?: string;
60+
readonly linkedSender?: OrchestrationV2DelegatedFrom;
5961
readonly workspaceRoot?: string;
6062
readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"];
6163
readonly hostedAppUrl?: string;
@@ -104,6 +106,9 @@ const clientLaunchHarness = (input: {
104106
client: {
105107
sessionId: clientSessionId,
106108
label: "Claude Code",
109+
...(input.linkedSender === undefined
110+
? {}
111+
: { linked: true, senderThread: input.linkedSender }),
107112
access: input.runtimeModeCeiling,
108113
hostedAppUrl: input.hostedAppUrl,
109114
},
@@ -208,6 +213,7 @@ it.effect(
208213
readonly targeted?: false;
209214
readonly overrideModel?: ModelSelection;
210215
readonly hostedAppUrl?: string;
216+
readonly delegatedFrom?: OrchestrationV2DelegatedFrom;
211217
readonly refusedByCeiling?: true;
212218
},
213219
) {
@@ -217,6 +223,7 @@ it.effect(
217223
runtimeModeCeiling,
218224
defaultRuntimeMode,
219225
launched,
226+
...(input.delegatedFrom === undefined ? {} : { linkedSender: input.delegatedFrom }),
220227
...(overrideModel === undefined ? {} : { overrideModel }),
221228
...(hostedAppUrl === undefined ? {} : { hostedAppUrl }),
222229
...(refusedByCeiling === undefined ? {} : { refusedByCeiling }),
@@ -246,6 +253,22 @@ it.effect(
246253
expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required");
247254
expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined();
248255

256+
const parent = {
257+
environmentId: EnvironmentId.make("remote"),
258+
threadId: ThreadId.make("parent"),
259+
title: "Coordinator",
260+
};
261+
const delegated = yield* launchWith("full-access", "approval-required", {
262+
title: "Review",
263+
message: "Review the diff",
264+
delegatedFrom: parent,
265+
});
266+
expect(delegated.launched[0]?.initialMessage?.linkedSender).toEqual({
267+
...parent,
268+
fromOriginatingLink: true,
269+
});
270+
expect(delegated.launched[0]?.delegatedFrom).toEqual(parent);
271+
249272
const aboveCeiling = yield* launchWith("auto-accept-edits", "full-access", {
250273
title: "Fix",
251274
hostedAppUrl: "https://t3.example.com",

‎apps/server/src/mcp/toolkits/project/handlers.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,19 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
392392
)?.supportedRuntimeModes,
393393
});
394394
}
395+
const { linkedSender } = McpInvocationContext.linkedMessageSender(scope.client, linkOrigin);
396+
const declaredParent = input.delegatedFrom;
397+
const delegatedFrom =
398+
caller === undefined &&
399+
linkedSender?.fromOriginatingLink === true &&
400+
declaredParent?.environmentId === linkedSender.environmentId &&
401+
declaredParent.threadId === linkedSender.threadId
402+
? {
403+
environmentId: linkedSender.environmentId,
404+
threadId: linkedSender.threadId,
405+
title: linkedSender.title,
406+
}
407+
: undefined;
395408
const result = yield* ThreadMessageIntake.launchThread({
396409
commandId,
397410
threadId,
@@ -407,15 +420,15 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
407420
initialMessage: {
408421
messageId,
409422
...(caller === undefined ? {} : { senderThreadId: caller.id }),
423+
...(linkedSender === undefined ? {} : { linkedSender }),
410424
text: input.message ?? "",
411425
attachments,
412426
},
413427
}),
414428
createdBy: "agent",
415429
creationSource: "mcp",
416430
...(linkOrigin === undefined ? {} : { linkOrigin }),
417-
// Kept only alongside linkOrigin: thread.create drops it otherwise.
418-
...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }),
431+
...(delegatedFrom === undefined ? {} : { delegatedFrom }),
419432
}).pipe(
420433
Effect.mapError((error) => {
421434
if (error._tag === "AttachmentClaimError") {

‎apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ const withBrowserRules = (rules: ReadonlyArray<unknown>, browser: ReadonlyArray<
118118
const TITLE = "Prime check";
119119
const sessionInfo = (overrides: Record<string, unknown> = {}) => ({
120120
id: SESSION,
121+
agent: "build",
121122
title: TITLE,
122123
permissions: t3Rules,
123124
projectID: "global",
@@ -344,6 +345,7 @@ const resumed = (
344345
readonly version?: "2.2.1" | "2.2.5" | "2.2.6";
345346
readonly shellRecovery?: ReadonlyArray<ProviderReplayEntry>;
346347
readonly lastRunOrdinal?: number;
348+
readonly missingAgent?: boolean;
347349
readonly pendingBackgroundTasks?: OrchestrationV2ProviderThread["pendingBackgroundTasks"];
348350
readonly goal?: OrchestrationV2ProviderThread["goal"];
349351
readonly contextUsage?: OrchestrationV2ProviderThread["contextUsage"];
@@ -365,7 +367,7 @@ const resumed = (
365367
[
366368
...opening,
367369
out("session.get", { sessionID: SESSION }),
368-
replyData("session.get", sessionInfo()),
370+
replyData("session.get", sessionInfo(options?.missingAgent ? { agent: undefined } : {})),
369371
...noOpenRequests,
370372
...(options?.version === "2.2.5" || options?.version === "2.2.6"
371373
? [out("rpc.call", "<any>"), reply("rpc.call", { output: null })]
@@ -507,6 +509,26 @@ const nativeGoal = (status: "active" | "paused" | "complete") => ({
507509
});
508510

509511
it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
512+
it.effect(
513+
"selects build before prompting a resumed session that uses the native default agent",
514+
() =>
515+
Effect.gen(function* () {
516+
const { runtime, thread } = yield* resumed(
517+
[
518+
out("session.switchAgent", { sessionID: SESSION, agent: "build" }),
519+
reply("session.switchAgent", null),
520+
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
521+
promptAccepted,
522+
event("session.execution.succeeded", { sessionID: SESSION }),
523+
],
524+
{ missingAgent: true },
525+
);
526+
const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
527+
yield* runtime.startTurn(turnInput(thread));
528+
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
529+
}),
530+
);
531+
510532
it.effect("switches the session's model and variant before a turn that changed them", () =>
511533
Effect.gen(function* () {
512534
const { runtime, thread } = yield* resumed([
@@ -3701,6 +3723,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
37013723
out("agent.list", "<any>"),
37023724
reply("agent.list", agentList),
37033725
out("session.create", {
3726+
agent: "build",
37043727
location: { directory: WORK },
37053728
model: { providerID: "opencode", id: "big-pickle" },
37063729
permissions: supervisedRules,
@@ -6805,6 +6828,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
68056828
})),
68066829
}),
68076830
out("session.create", {
6831+
agent: "build",
68086832
location: { directory: custom },
68096833
model: { providerID: "opencode", id: "big-pickle" },
68106834
permissions: t3Rules,

‎apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ const decodeHandoff = Schema.decodeUnknownSync(OrchestrationV2ContextHandoff);
4343

4444
const now = DateTime.makeUnsafe("2026-09-17T00:00:00Z");
4545
const threadId = ThreadId.make("thread:handoff");
46+
const thread = {
47+
lineage: { relationshipToParent: null, parentThreadId: null, rootThreadId: threadId },
48+
};
4649
const summaryScope = { projectId: ProjectId.make("project:handoff"), threadId };
4750
const providerThread: OrchestrationV2ProviderThread = {
4851
id: ProviderThreadId.make("provider-thread:target"),
@@ -208,7 +211,7 @@ describe("handoff budget", () => {
208211
assert.include(imageCommand!.text, "image/png");
209212
assert.include(imageCommand!.text, "read screenshot.png");
210213
const native = nativeContextHistory(
211-
{ runs: [], attempts: [], providerTurns: [], contextHandoffs: [] },
214+
{ thread, runs: [], attempts: [], providerTurns: [], contextHandoffs: [] },
212215
providerThread,
213216
);
214217
native.nativeInputRunIds.add(base.runId);
@@ -349,6 +352,7 @@ describe("handoff budget", () => {
349352
inputIntent: "turn_start",
350353
attachments: [],
351354
})!;
355+
assert.equal(peer.text, peerText);
352356
assert.deepEqual(peer.provenance, { createdBy: "agent", creationSource: "mcp", ...sender });
353357
for (const rendered of [
354358
renderHistory([peer], "Historical context"),
@@ -707,7 +711,7 @@ describe("handoff delivery", () => {
707711
const first = yield* deliver();
708712
assert.equal(
709713
nativeContextHistory(
710-
{ runs: [], attempts: [], providerTurns: [], contextHandoffs: durable },
714+
{ thread, runs: [], attempts: [], providerTurns: [], contextHandoffs: durable },
711715
providerThread,
712716
).estimate([tail]),
713717
native ? deliveredCost : 0,
@@ -720,7 +724,7 @@ describe("handoff delivery", () => {
720724
target = providerThread,
721725
) =>
722726
nativeContextHistory(
723-
{ runs: [], attempts: [], providerTurns: [], contextHandoffs },
727+
{ thread, runs: [], attempts: [], providerTurns: [], contextHandoffs },
724728
target,
725729
);
726730
const estimate = occupancy(durable.map((entry) => decodeHandoff(entry))).estimate([tail]);

0 commit comments

Comments
 (0)