Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

orchestrationV2.test.ts

1,045 lines33.8 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as DateTime from "effect/DateTime";
3import * as Schema from "effect/Schema";
4​
5import {
6 CheckpointId,
7 CheckpointRef,
8 CheckpointScopeId,
9 ContextTransferId,
10 CommandId,
11 EventId,
12 MessageId,
13 NodeId,
14 NonNegativeInt,
15 ProjectId,
16 ProviderInstanceId,
17 ProviderReplayTranscript,
18 ProviderThreadId,
19 RunId,
20 ThreadId,
21 TurnItemId,
22} from "./index.ts";
23import {
24 OrchestrationV2Checkpoint,
25 OrchestrationV2CheckpointScope,
26 OrchestrationV2Command,
27 OrchestrationV2LimitRecoveryUpdate,
28 OrchestrationV2DomainEvent,
29 OrchestrationV2ProviderCapabilities,
30 OrchestrationV2ProviderThread,
31 OrchestrationV2ProviderThreadJson,
32 OrchestrationV2ShellSnapshot,
33 OrchestrationV2SubscribeThreadInput,
34 OrchestrationV2Subagent,
35 OrchestrationV2ThreadProjection,
36 OrchestrationV2ThreadStreamItem,
37 OrchestrationV2ThreadShell,
38 OrchestrationV2TurnItem,
39 OrchestrationV2TurnItemJson,
40} from "./orchestrationV2.ts";
41​
42const now = DateTime.makeUnsafe("2026-04-20T00:00:00.000Z");
43const LegacyShellStreamItem = Schema.Union([
44 Schema.Struct({ kind: Schema.Literal("synchronized") }),
45 Schema.Struct({
46 kind: Schema.Literal("snapshot"),
47 snapshot: OrchestrationV2ShellSnapshot,
48 }),
49]);
50const LegacySubscribeThreadInput = Schema.Struct({
51 threadId: ThreadId,
52 afterSequence: Schema.optionalKey(NonNegativeInt),
53 requestCompletionMarker: Schema.optionalKey(Schema.Boolean),
54});
55const decodeLegacyShellStreamItem = Schema.decodeUnknownSync(LegacyShellStreamItem);
56const decodeLegacySubscribeThreadInput = Schema.decodeUnknownSync(LegacySubscribeThreadInput);
57const decodeOrchestrationV2Command = Schema.decodeUnknownSync(OrchestrationV2Command);
58const decodeOrchestrationV2TurnItem = Schema.decodeUnknownSync(OrchestrationV2TurnItem);
59const decodeOrchestrationV2TurnItemJson = Schema.decodeUnknownSync(OrchestrationV2TurnItemJson);
60const encodeOrchestrationV2TurnItemJson = Schema.encodeSync(OrchestrationV2TurnItemJson);
61const decodeOrchestrationV2CheckpointScope = Schema.decodeUnknownSync(
62 OrchestrationV2CheckpointScope,
63);
64const decodeOrchestrationV2Checkpoint = Schema.decodeUnknownSync(OrchestrationV2Checkpoint);
65const decodeOrchestrationV2DomainEvent = Schema.decodeUnknownSync(OrchestrationV2DomainEvent);
66const decodeProviderReplayTranscript = Schema.decodeUnknownSync(ProviderReplayTranscript);
67const decodeOrchestrationV2Subagent = Schema.decodeUnknownSync(OrchestrationV2Subagent);
68const decodeOrchestrationV2ThreadProjection = Schema.decodeUnknownSync(
69 OrchestrationV2ThreadProjection,
70);
71const decodeOrchestrationV2ThreadStreamItem = Schema.decodeUnknownSync(
72 OrchestrationV2ThreadStreamItem,
73);
74const decodeOrchestrationV2ProviderThreadJson = Schema.decodeUnknownSync(
75 OrchestrationV2ProviderThreadJson,
76);
77const decodeOrchestrationV2ProviderThread = Schema.decodeUnknownSync(OrchestrationV2ProviderThread);
78const decodeOrchestrationV2ThreadShell = Schema.decodeUnknownSync(OrchestrationV2ThreadShell);
79const decodeOrchestrationV2ProviderCapabilities = Schema.decodeUnknownSync(
80 OrchestrationV2ProviderCapabilities,
81);
82​
83const decodeOrchestrationV2SubscribeThreadInput = Schema.decodeUnknownSync(
84 OrchestrationV2SubscribeThreadInput,
85);
86​
87describe("orchestration V2 contracts", () => {
88 it("carries command failure metadata through runtime and JSON schemas without output text", () => {
89 const base = {
90 id: "command-item",
91 type: "command_execution",
92 threadId: "thread-1",
93 runId: null,
94 nodeId: null,
95 providerThreadId: null,
96 providerTurnId: null,
97 nativeItemRef: null,
98 parentItemId: null,
99 ordinal: 1,
100 status: "completed",
101 title: "Command",
102 input: "example",
103 startedAt: null,
104 completedAt: null,
105 };
106 for (const metadata of [
107 {},
108 { outputIndicatesFailure: true },
109 { outputIndicatesFailure: false },
110 ]) {
111 const runtime = decodeOrchestrationV2TurnItem({ ...base, ...metadata, updatedAt: now });
112 const json = decodeOrchestrationV2TurnItemJson({
113 ...base,
114 ...metadata,
115 updatedAt: DateTime.formatIso(now),
116 });
117 expect(runtime.type).toBe("command_execution");
118 expect(json.type).toBe("command_execution");
119 expect(runtime).toMatchObject(metadata);
120 expect(json).toMatchObject(metadata);
121 expect(runtime).not.toHaveProperty("output");
122 expect(json).not.toHaveProperty("output");
123 }
124 });
125​
126 it("negotiates bounded socket snapshots as an optional capability", () => {
127 expect(
128 decodeOrchestrationV2SubscribeThreadInput({
129 threadId: "thread-1",
130 acceptBoundedSnapshot: true,
131 }).acceptBoundedSnapshot,
132 ).toBe(true);
133 expect(
134 decodeOrchestrationV2SubscribeThreadInput({ threadId: "thread-1" }).acceptBoundedSnapshot,
135 ).toBeUndefined();
136​
137 const legacyDecoded = decodeLegacySubscribeThreadInput({
138 threadId: "thread-1",
139 afterSequence: 12,
140 acceptBoundedSnapshot: true,
141 });
142 expect(legacyDecoded.afterSequence).toBe(12);
143 expect("acceptBoundedSnapshot" in legacyDecoded).toBe(false);
144 });
145​
146 it("decodes persisted capability snapshots that predate runtimePolicy", () => {
147 // Events written before the field existed must replay; absent decodes to
148 // the weaker client-boundary guarantee so history never overclaims.
149 const legacyCapabilities = {
150 sessions: {
151 supportsMultipleProviderThreadsPerSession: false,
152 supportsModelSwitchInSession: false,
153 supportsProviderSwitchingViaHandoff: true,
154 supportsRuntimeModeSwitchInSession: false,
155 pendingRequestsSurviveRestart: false,
156 },
157 threads: {
158 canCreateEmptyThread: true,
159 canReadThreadSnapshot: false,
160 canRollbackThread: true,
161 canForkThread: false,
162 canForkFromTurn: false,
163 canForkFromSubagentThread: false,
164 exposesNativeThreadId: true,
165 },
166 turns: {
167 exposesNativeTurnId: false,
168 emitsTurnStarted: true,
169 emitsTurnCompleted: true,
170 supportsInterrupt: true,
171 supportsActiveSteering: false,
172 supportsSteeringByInterruptRestart: true,
173 supportsQueuedMessages: true,
174 terminalStatusQuality: "strong",
175 },
176 streaming: {
177 streamsAssistantText: true,
178 streamsReasoning: true,
179 streamsToolOutput: true,
180 streamsPlanText: false,
181 emitsMessageCompleted: true,
182 },
183 tools: {
184 exposesToolItemIds: true,
185 emitsToolStarted: true,
186 emitsToolCompleted: true,
187 emitsToolOutput: true,
188 supportsMcpTools: false,
189 supportsDynamicToolCallbacks: false,
190 },
191 approvals: {
192 supportsCommandApproval: true,
193 supportsFileReadApproval: true,
194 supportsFileChangeApproval: true,
195 supportsApplyPatchApproval: false,
196 approvalsHaveNativeRequestIds: false,
197 approvalCallbacksAreLiveOnly: true,
198 approvalsCanOriginateFromSubagents: false,
199 },
200 planning: {
201 emitsPlanUpdated: true,
202 emitsTodoList: true,
203 emitsProposedPlan: false,
204 supportsStructuredQuestions: true,
205 planDeltasHaveItemIds: false,
206 },
207 subagents: {
208 supportsSubagents: false,
209 exposesSubagentThreadIds: false,
210 emitsSubagentLifecycle: false,
211 canWaitForSubagents: false,
212 canCloseSubagents: false,
213 canForkSubagentThread: false,
214 },
215 context: {
216 acceptsSystemContext: false,
217 acceptsDeveloperContext: false,
218 acceptsSyntheticUserContext: true,
219 canGenerateSummaries: true,
220 canConsumeHandoffSummaries: true,
221 supportsDeltaHandoff: true,
222 supportsFullThreadHandoff: true,
223 maxRecommendedHandoffChars: null,
224 },
225 checkpointing: {
226 appCanCheckpointFilesystem: true,
227 supportsNestedCheckpointScopes: true,
228 providerCanRollbackConversation: true,
229 providerRollbackReturnsSnapshot: true,
230 providerCanReadConversationSnapshot: false,
231 },
232 identity: {
233 nativeThreadIds: "strong",
234 nativeTurnIds: "weak",
235 nativeItemIds: "weak",
236 nativeRequestIds: "weak",
237 },
238 };
239​
240 const decoded = decodeOrchestrationV2ProviderCapabilities(legacyCapabilities);
241 expect(decoded.runtimePolicy).toEqual({ enforcement: "client-boundary" });
242​
243 const explicit = decodeOrchestrationV2ProviderCapabilities({
244 ...legacyCapabilities,
245 runtimePolicy: { enforcement: "native" },
246 });
247 expect(explicit.runtimePolicy).toEqual({ enforcement: "native" });
248 });
249​
250 it("lets legacy snapshot decoders ignore enrichment metadata", () => {
251 const decoded = decodeLegacyShellStreamItem({
252 kind: "snapshot",
253 snapshot: {
254 schemaVersion: 1,
255 snapshotSequence: 0,
256 projects: [],
257 threads: [],
258 archivedThreads: [],
259 },
260 resolvedRepositoryIdentityRoots: ["/workspace/project"],
261 });
262​
263 expect(decoded.kind).toBe("snapshot");
264 expect("resolvedRepositoryIdentityRoots" in decoded).toBe(false);
265 });
266​
267 it("decodes nested checkpoint scopes without making child scopes advance app run count", () => {
268 const rootScope = decodeOrchestrationV2CheckpointScope({
269 id: "scope-root-1",
270 threadId: "thread-1",
271 runId: "run-1",
272 nodeId: "node-root-1",
273 parentScopeId: null,
274 providerThreadId: "provider-thread-1",
275 kind: "root_run",
276 ordinalWithinParent: 1,
277 advancesAppRunCount: true,
278 cwd: "/tmp/project",
279 createdAt: now,
280 });
281 const childScope = decodeOrchestrationV2CheckpointScope({
282 id: "scope-child-1",
283 threadId: "thread-1",
284 runId: "run-1",
285 nodeId: "node-child-1",
286 parentScopeId: rootScope.id,
287 providerThreadId: "provider-thread-child-1",
288 kind: "subagent",
289 ordinalWithinParent: 1,
290 advancesAppRunCount: false,
291 cwd: "/tmp/project",
292 createdAt: now,
293 });
294​
295 expect(rootScope.advancesAppRunCount).toBe(true);
296 expect(childScope.parentScopeId).toBe(rootScope.id);
297 expect(childScope.advancesAppRunCount).toBe(false);
298 });
299​
300 it("decodes checkpoint captures that attach to scopes, nodes, and optional app run ordinals", () => {
301 const checkpoint = decodeOrchestrationV2Checkpoint({
302 id: "checkpoint-1",
303 threadId: "thread-1",
304 scopeId: "scope-child-1",
305 runId: "run-1",
306 nodeId: "node-child-1",
307 parentCheckpointId: "checkpoint-root-1",
308 ordinalWithinScope: 1,
309 appRunOrdinal: null,
310 ref: "git-ref-1",
311 status: "ready",
312 files: [{ path: "package.json", kind: "modified", additions: 2, deletions: 1 }],
313 capturedAt: now,
314 });
315​
316 expect(checkpoint.appRunOrdinal).toBeNull();
317 expect(checkpoint.scopeId).toBe(CheckpointScopeId.make("scope-child-1"));
318 expect(checkpoint.parentCheckpointId).toBe(CheckpointId.make("checkpoint-root-1"));
319 });
320​
321 it("decodes command and domain event shapes for command-to-projection tests", () => {
322 const command = decodeOrchestrationV2Command({
323 type: "message.dispatch",
324 createdBy: "user",
325 creationSource: "web",
326 commandId: "command-1",
327 threadId: "thread-1",
328 messageId: "message-1",
329 text: "hello",
330 attachments: [],
331 dispatchMode: { type: "start_immediately" },
332 });
333 const event = decodeOrchestrationV2DomainEvent({
334 id: "event-1",
335 type: "run.created",
336 threadId: "thread-1",
337 runId: "run-1",
338 occurredAt: now,
339 payload: {
340 id: "run-1",
341 threadId: "thread-1",
342 ordinal: 1,
343 providerInstanceId: "codex",
344 modelSelection: {
345 instanceId: "codex",
346 model: "gpt-5.4",
347 },
348 providerThreadId: "provider-thread-1",
349 userMessageId: "message-1",
350 rootNodeId: null,
351 activeAttemptId: null,
352 status: "queued",
353 requestedAt: now,
354 startedAt: null,
355 completedAt: null,
356 checkpointId: null,
357 contextHandoffId: null,
358 },
359 });
360​
361 expect(command.commandId).toBe(CommandId.make("command-1"));
362 expect(event.id).toBe(EventId.make("event-1"));
363 if (event.type !== "run.created") {
364 throw new Error(`Expected run.created, received ${event.type}.`);
365 }
366 expect(event.payload.id).toBe(RunId.make("run-1"));
367 });
368​
369 it("decodes app-owned delegated task commands", () => {
370 const command = decodeOrchestrationV2Command({
371 type: "delegated_task.request",
372 createdBy: "user",
373 creationSource: "web",
374 commandId: "command-delegate-1",
375 parentThreadId: "thread-parent-1",
376 parentRunId: "run-parent-1",
377 parentNodeId: "node-parent-1",
378 task: "Inspect the API boundary.",
379 title: "API inspection",
380 modelSelection: {
381 instanceId: "claudeAgent",
382 model: "claude-sonnet-4-6",
383 },
384 runtimeMode: "approval-required",
385 interactionMode: "plan",
386 });
387​
388 expect(command.type).toBe("delegated_task.request");
389 if (command.type !== "delegated_task.request") {
390 throw new Error("expected delegated_task.request");
391 }
392 expect(command.parentThreadId).toBe(ThreadId.make("thread-parent-1"));
393 expect(command.parentRunId).toBe(RunId.make("run-parent-1"));
394 expect(command.parentNodeId).toBe(NodeId.make("node-parent-1"));
395 });
396​
397 it("decodes delegated task wake-policy commands", () => {
398 const command = decodeOrchestrationV2Command({
399 type: "delegated_task.wake-policy",
400 commandId: "command-delegate-wake-policy-1",
401 parentThreadId: "thread-parent-1",
402 taskId: "node-subagent-1",
403 completionWake: "always",
404 });
405​
406 expect(command.type).toBe("delegated_task.wake-policy");
407 if (command.type !== "delegated_task.wake-policy") {
408 throw new Error("expected delegated_task.wake-policy");
409 }
410 expect(command.parentThreadId).toBe(ThreadId.make("thread-parent-1"));
411 expect(command.taskId).toBe(NodeId.make("node-subagent-1"));
412 expect(command.completionWake).toBe("always");
413​
414 // The policy carries the whole decision, so it is required and closed.
415 expect(() =>
416 decodeOrchestrationV2Command({
417 type: "delegated_task.wake-policy",
418 commandId: "command-delegate-wake-policy-2",
419 parentThreadId: "thread-parent-1",
420 taskId: "node-subagent-1",
421 }),
422 ).toThrow();
423 expect(() =>
424 decodeOrchestrationV2Command({
425 type: "delegated_task.wake-policy",
426 commandId: "command-delegate-wake-policy-3",
427 parentThreadId: "thread-parent-1",
428 taskId: "node-subagent-1",
429 completionWake: "sometimes",
430 }),
431 ).toThrow();
432 });
433​
434 it("decodes durable created-thread timeline records", () => {
435 const command = decodeOrchestrationV2Command({
436 type: "thread.created.record",
437 commandId: "command-thread-record-1",
438 parentThreadId: "thread-parent-1",
439 parentRunId: "run-parent-1",
440 parentNodeId: "node-parent-1",
441 targetThreadId: "thread-child-1",
442 targetRunId: "run-child-1",
443 });
444 const item = decodeOrchestrationV2TurnItem({
445 id: "turn-item-thread-created-1",
446 type: "thread_created",
447 threadId: "thread-parent-1",
448 runId: "run-parent-1",
449 nodeId: "node-parent-1",
450 providerThreadId: "provider-thread-parent-1",
451 providerTurnId: null,
452 nativeItemRef: null,
453 parentItemId: null,
454 ordinal: 4,
455 status: "completed",
456 title: "Child thread",
457 targetThreadId: "thread-child-1",
458 targetRunId: "run-child-1",
459 targetProviderInstanceId: "claude-default",
460 targetModel: "claude-sonnet-4-6",
461 startedAt: now,
462 completedAt: now,
463 updatedAt: now,
464 });
465​
466 expect(command.type).toBe("thread.created.record");
467 if (command.type !== "thread.created.record") {
468 throw new Error("expected thread.created.record");
469 }
470 expect(command.targetThreadId).toBe(ThreadId.make("thread-child-1"));
471 expect(item.type).toBe("thread_created");
472 if (item.type !== "thread_created") {
473 throw new Error("expected thread_created");
474 }
475 expect(item.targetRunId).toBe(RunId.make("run-child-1"));
476 });
477​
478 it("decodes provider-neutral replay transcripts", () => {
479 const transcript = decodeProviderReplayTranscript({
480 provider: "codex",
481 protocol: "codex.app-server",
482 version: "0.120.0",
483 scenario: "simple",
484 metadata: {
485 source: "real-probe",
486 },
487 entries: [
488 {
489 type: "expect_outbound",
490 label: "initialize",
491 frame: { id: 1, method: "initialize" },
492 },
493 {
494 type: "emit_inbound",
495 label: "initialize-result",
496 frame: { id: 1, result: { ok: true } },
497 },
498 {
499 type: "runtime_exit",
500 status: "success",
501 },
502 ],
503 });
504​
505 expect(transcript.entries).toHaveLength(3);
506 expect(transcript.protocol).toBe("codex.app-server");
507 });
508​
509 it("decodes strictly typed turn items for known tools and dynamic fallback tools", () => {
510 const fileChange = decodeOrchestrationV2TurnItem({
511 id: "turn-item-file-change-1",
512 type: "file_change",
513 threadId: "thread-1",
514 runId: "run-1",
515 nodeId: "node-file-change-1",
516 providerThreadId: "provider-thread-1",
517 providerTurnId: "provider-turn-1",
518 nativeItemRef: { driver: "codex", nativeId: "item-file-change-1", strength: "strong" },
519 parentItemId: null,
520 ordinal: 3,
521 status: "completed",
522 title: "Edited package.json",
523 fileName: "package.json",
524 additions: 4,
525 deletions: 2,
526 diffStr: "@@ fixture diff",
527 startedAt: now,
528 completedAt: now,
529 updatedAt: now,
530 });
531 const dynamicTool = decodeOrchestrationV2TurnItem({
532 id: "turn-item-dynamic-1",
533 type: "dynamic_tool",
534 threadId: "thread-1",
535 runId: "run-1",
536 nodeId: "node-dynamic-1",
537 providerThreadId: "provider-thread-1",
538 providerTurnId: "provider-turn-1",
539 nativeItemRef: { driver: "codex", nativeId: "item-dynamic-1", strength: "strong" },
540 parentItemId: null,
541 ordinal: 4,
542 status: "completed",
543 title: "Custom tool",
544 toolName: "custom.lookup",
545 input: { query: "fixture" },
546 output: { ok: true },
547 startedAt: now,
548 completedAt: now,
549 updatedAt: now,
550 });
551​
552 expect(fileChange.type).toBe("file_change");
553 if (fileChange.type !== "file_change") {
554 throw new Error("expected file_change");
555 }
556 expect(fileChange.fileName).toBe("package.json");
557 expect(fileChange.additions).toBe(4);
558 expect(dynamicTool.id).toBe(TurnItemId.make("turn-item-dynamic-1"));
559 });
560​
561 it("decodes bounded provider failures as expected error turn items", () => {
562 const errorItem = decodeOrchestrationV2TurnItem({
563 id: "turn-item-error-1",
564 type: "error",
565 threadId: "thread-1",
566 runId: "run-1",
567 nodeId: "node-root-1",
568 providerThreadId: "provider-thread-1",
569 providerTurnId: "provider-turn-1",
570 nativeItemRef: null,
571 parentItemId: null,
572 ordinal: 199,
573 status: "failed",
574 title: "Provider error",
575 failure: {
576 class: "validation_error",
577 message: "Invalid reasoning effort.",
578 code: "invalid_request",
579 retryable: false,
580 },
581 startedAt: now,
582 completedAt: now,
583 updatedAt: now,
584 });
585​
586 expect(errorItem.type).toBe("error");
587 if (errorItem.type !== "error") throw new Error("expected error item");
588 expect(errorItem.failure.message).toBe("Invalid reasoning effort.");
589 const usageLimited = decodeOrchestrationV2TurnItem({
590 ...errorItem,
591 startedAt: now,
592 completedAt: now,
593 updatedAt: now,
594 failure: { ...errorItem.failure, class: "usage_limit" },
595 });
596 expect(usageLimited.type === "error" && usageLimited.failure.class).toBe("usage_limit");
597 expect(() =>
598 decodeOrchestrationV2TurnItem({
599 ...errorItem,
600 failure: { ...errorItem.failure, message: "x".repeat(4_097) },
601 }),
602 ).toThrow();
603 });
604​
605 it("decodes provider-native subagent lifecycle records and timeline items", () => {
606 const subagent = decodeOrchestrationV2Subagent({
607 id: "node-subagent-1",
608 threadId: "thread-1",
609 runId: "run-1",
610 parentNodeId: "node-root-1",
611 origin: "provider_native",
612 createdBy: "agent",
613 driver: "codex",
614 providerInstanceId: "codex",
615 providerThreadId: "provider-thread-subagent-1",
616 childThreadId: null,
617 nativeTaskRef: {
618 driver: "codex",
619 nativeId: "native-task-1",
620 strength: "strong",
621 },
622 prompt: "Inspect package.json",
623 title: "Package audit",
624 model: "gpt-5.4",
625 status: "completed",
626 progress: "Inspecting package metadata",
627 result: "Package is private.",
628 startedAt: now,
629 completedAt: now,
630 updatedAt: now,
631 });
632 const turnItem = decodeOrchestrationV2TurnItem({
633 id: "turn-item-subagent-1",
634 type: "subagent",
635 threadId: "thread-1",
636 runId: "run-1",
637 nodeId: subagent.id,
638 providerThreadId: subagent.providerThreadId,
639 providerTurnId: "provider-turn-1",
640 nativeItemRef: subagent.nativeTaskRef,
641 parentItemId: null,
642 ordinal: 2,
643 status: "completed",
644 title: subagent.title,
645 subagentId: subagent.id,
646 origin: subagent.origin,
647 driver: subagent.driver,
648 providerInstanceId: subagent.providerInstanceId,
649 childThreadId: subagent.childThreadId,
650 prompt: subagent.prompt,
651 progress: subagent.progress,
652 result: subagent.result,
653 startedAt: now,
654 completedAt: now,
655 updatedAt: now,
656 });
657​
658 expect(subagent.origin).toBe("provider_native");
659 expect(subagent.progress).toBe("Inspecting package metadata");
660 expect(subagent.childThreadId).toBeNull();
661 expect(turnItem.type).toBe("subagent");
662 if (turnItem.type !== "subagent") throw new Error("expected subagent item");
663 expect(turnItem.progress).toBe("Inspecting package metadata");
664 });
665​
666 it("decodes app-owned subagent parent-wake policies", () => {
667 const appOwnedSubagent = {
668 id: "node-subagent-2",
669 threadId: "thread-1",
670 runId: "run-1",
671 parentNodeId: "node-root-1",
672 origin: "app_owned",
673 createdBy: "agent",
674 driver: "codex",
675 providerInstanceId: "codex",
676 providerThreadId: null,
677 childThreadId: "thread-child-1",
678 nativeTaskRef: null,
679 prompt: "Inspect the API boundary.",
680 title: "API inspection",
681 model: "gpt-5.4",
682 status: "running",
683 result: null,
684 startedAt: now,
685 completedAt: null,
686 updatedAt: now,
687 };
688 const decode = Schema.decodeUnknownSync(OrchestrationV2Subagent);
689​
690 // Legacy records predate the field and must behave as settled_only.
691 expect(decode(appOwnedSubagent).completionWake).toBeUndefined();
692 expect(decode({ ...appOwnedSubagent, completionWake: "always" }).completionWake).toBe("always");
693 expect(decode({ ...appOwnedSubagent, completionWake: "settled_only" }).completionWake).toBe(
694 "settled_only",
695 );
696 expect(() => decode({ ...appOwnedSubagent, completionWake: "sometimes" })).toThrow();
697 });
698​
699 it("decodes thread projections with an ordered turn item rendering stream", () => {
700 const projection = decodeOrchestrationV2ThreadProjection({
701 thread: {
702 createdBy: "user",
703 creationSource: "web",
704 id: "thread-1",
705 projectId: "project-1",
706 title: "Thread",
707 providerInstanceId: "codex",
708 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
709 runtimeMode: "full-access",
710 interactionMode: "default",
711 branch: null,
712 worktreePath: null,
713 activeProviderThreadId: null,
714 lineage: {
715 parentThreadId: null,
716 relationshipToParent: null,
717 rootThreadId: "thread-1",
718 },
719 forkedFrom: null,
720 createdAt: now,
721 updatedAt: now,
722 archivedAt: null,
723 deletedAt: null,
724 },
725 runs: [],
726 attempts: [],
727 nodes: [],
728 subagents: [],
729 providerSessions: [],
730 providerThreads: [],
731 providerTurns: [],
732 runtimeRequests: [],
733 messages: [],
734 plans: [],
735 turnItems: [
736 {
737 id: "turn-item-command-1",
738 type: "command_execution",
739 threadId: "thread-1",
740 runId: "run-1",
741 nodeId: "node-command-1",
742 providerThreadId: "provider-thread-1",
743 providerTurnId: "provider-turn-1",
744 nativeItemRef: { driver: "codex", nativeId: "item-command-1", strength: "strong" },
745 parentItemId: null,
746 ordinal: 1,
747 status: "completed",
748 title: "Ran command",
749 input: "bun typecheck",
750 output: "Tasks: 10 successful",
751 exitCode: 0,
752 startedAt: now,
753 completedAt: now,
754 updatedAt: now,
755 },
756 ],
757 visibleTurnItems: [
758 {
759 position: 0,
760 visibility: "local",
761 sourceThreadId: "thread-1",
762 sourceItemId: "turn-item-command-1",
763 item: {
764 id: "turn-item-command-1",
765 type: "command_execution",
766 threadId: "thread-1",
767 runId: "run-1",
768 nodeId: "node-command-1",
769 providerThreadId: "provider-thread-1",
770 providerTurnId: "provider-turn-1",
771 nativeItemRef: { driver: "codex", nativeId: "item-command-1", strength: "strong" },
772 parentItemId: null,
773 ordinal: 1,
774 status: "completed",
775 title: "Ran command",
776 input: "bun typecheck",
777 output: "Tasks: 10 successful",
778 exitCode: 0,
779 startedAt: now,
780 completedAt: now,
781 updatedAt: now,
782 },
783 },
784 ],
785 checkpointScopes: [],
786 checkpoints: [],
787 contextHandoffs: [],
788 contextTransfers: [],
789 updatedAt: now,
790 });
791​
792 expect(projection.turnItems.map((item) => item.type)).toEqual(["command_execution"]);
793​
794 const boundedSnapshot = decodeOrchestrationV2ThreadStreamItem({
795 kind: "snapshot",
796 snapshotSequence: 12,
797 projection,
798 historyCursor: "older-page",
799 hasMoreHistory: true,
800 latestLocalTurnOrdinal: 1,
801 payloadBudgetExceeded: false,
802 });
803 expect(boundedSnapshot).toMatchObject({
804 kind: "snapshot",
805 historyCursor: "older-page",
806 hasMoreHistory: true,
807 latestLocalTurnOrdinal: 1,
808 payloadBudgetExceeded: false,
809 });
810 });
811​
812 it("decodes orchestration lifecycle turn items for compaction, handoff, and fork UI", () => {
813 const compaction = decodeOrchestrationV2TurnItem({
814 id: "turn-item-compaction-1",
815 type: "compaction",
816 threadId: "thread-1",
817 runId: "run-1",
818 nodeId: "node-compaction-1",
819 providerThreadId: "provider-thread-1",
820 providerTurnId: "provider-turn-1",
821 nativeItemRef: null,
822 parentItemId: null,
823 ordinal: 5,
824 status: "running",
825 title: "Compacting context...",
826 driver: "codex",
827 beforeTokenCount: 180000,
828 startedAt: now,
829 completedAt: null,
830 updatedAt: now,
831 });
832 const handoff = decodeOrchestrationV2TurnItem({
833 id: "turn-item-handoff-1",
834 type: "handoff",
835 threadId: "thread-1",
836 runId: "run-2",
837 nodeId: null,
838 providerThreadId: "provider-thread-claude-1",
839 providerTurnId: null,
840 nativeItemRef: null,
841 parentItemId: null,
842 ordinal: 6,
843 status: "completed",
844 title: "Handed off to Claude",
845 contextHandoffId: "handoff-1",
846 fromProviderThreadIds: ["provider-thread-codex-1"],
847 toProviderThreadId: "provider-thread-claude-1",
848 fromProviderInstanceIds: ["codex"],
849 toProviderInstanceId: "claudeAgent",
850 strategy: "delta_since_target_last_seen",
851 summary: "Codex completed the setup work.",
852 startedAt: now,
853 completedAt: now,
854 updatedAt: now,
855 });
856 const fork = decodeOrchestrationV2TurnItem({
857 id: "turn-item-fork-1",
858 type: "fork",
859 threadId: "thread-1",
860 runId: "run-2",
861 nodeId: "node-subagent-1",
862 providerThreadId: "provider-thread-child-1",
863 providerTurnId: null,
864 nativeItemRef: null,
865 parentItemId: null,
866 ordinal: 7,
867 status: "completed",
868 title: "Forked subagent thread",
869 source: { type: "node", nodeId: "node-subagent-1" },
870 targetThreadId: "thread-fork-1",
871 startedAt: now,
872 completedAt: now,
873 updatedAt: now,
874 });
875​
876 expect(compaction.type).toBe("compaction");
877 expect(compaction.status).toBe("running");
878 expect(handoff.type).toBe("handoff");
879 if (handoff.type !== "handoff") {
880 throw new Error("expected handoff");
881 }
882 expect(handoff.toProviderInstanceId).toBe("claudeAgent");
883 expect(fork.type).toBe("fork");
884 });
885​
886 it("exports the V2 branded ids through the public contracts entrypoint", () => {
887 expect(ThreadId.make("thread-1")).toBe("thread-1");
888 expect(ProjectId.make("project-1")).toBe("project-1");
889 expect(MessageId.make("message-1")).toBe("message-1");
890 expect(NodeId.make("node-1")).toBe("node-1");
891 expect(ProviderThreadId.make("provider-thread-1")).toBe("provider-thread-1");
892 expect(CheckpointRef.make("git-ref-1")).toBe("git-ref-1");
893 expect(ContextTransferId.make("context-transfer-1")).toBe("context-transfer-1");
894 });
895​
896 it("decodes historical provider-thread JSON without pendingBackgroundTasks as empty roster", () => {
897 const providerThread = decodeOrchestrationV2ProviderThreadJson({
898 id: "provider-thread-1",
899 driver: "claude",
900 providerInstanceId: "claudeAgent",
901 providerSessionId: "provider-session-1",
902 appThreadId: "thread-1",
903 ownerNodeId: null,
904 nativeThreadRef: {
905 driver: "claude",
906 nativeId: "native-session-1",
907 strength: "strong",
908 },
909 nativeConversationHeadRef: null,
910 status: "idle",
911 firstRunOrdinal: 1,
912 lastRunOrdinal: 1,
913 handoffIds: [],
914 forkedFrom: null,
915 createdAt: "2026-04-20T00:00:00.000Z",
916 updatedAt: "2026-04-20T00:00:00.000Z",
917 });
918​
919 expect(providerThread.pendingBackgroundTasks).toEqual([]);
920 expect(providerThread.contextUsage).toBeNull();
921 expect(providerThread.nativeMetadata).toBeNull();
922​
923 const runtimeThread = decodeOrchestrationV2ProviderThread({
924 id: "provider-thread-2",
925 driver: "claude",
926 providerInstanceId: "claudeAgent",
927 providerSessionId: null,
928 appThreadId: "thread-2",
929 ownerNodeId: null,
930 nativeThreadRef: null,
931 nativeConversationHeadRef: null,
932 status: "idle",
933 firstRunOrdinal: null,
934 lastRunOrdinal: null,
935 handoffIds: [],
936 forkedFrom: null,
937 createdAt: now,
938 updatedAt: now,
939 });
940 expect(runtimeThread.pendingBackgroundTasks).toEqual([]);
941 expect(runtimeThread.contextUsage).toBeNull();
942 expect(runtimeThread.nativeMetadata).toBeNull();
943 });
944​
945 it("decodes historical thread shell JSON without pendingBackgroundTasks as empty roster", () => {
946 const shell = decodeOrchestrationV2ThreadShell({
947 createdBy: "user",
948 creationSource: "web",
949 id: "thread-1",
950 projectId: "project-1",
951 title: "Thread",
952 providerInstanceId: "claudeAgent",
953 modelSelection: {
954 instanceId: ProviderInstanceId.make("claudeAgent"),
955 model: "claude-sonnet",
956 },
957 runtimeMode: "full-access",
958 interactionMode: "default",
959 branch: null,
960 worktreePath: null,
961 lineage: {
962 parentThreadId: null,
963 relationshipToParent: null,
964 rootThreadId: "thread-1",
965 },
966 forkedFrom: null,
967 activeProviderThreadId: "provider-thread-1",
968 latestRunId: "run-1",
969 activeRunId: null,
970 status: "completed",
971 pendingRuntimeRequest: null,
972 latestVisibleMessage: null,
973 latestUserMessageAt: null,
974 hasActionableProposedPlan: false,
975 itemCount: 0,
976 visibleItemCount: 0,
977 createdAt: now,
978 updatedAt: now,
979 archivedAt: null,
980 settledOverride: null,
981 settledAt: null,
982 deletedAt: null,
983 });
984​
985 expect(shell.pendingBackgroundTasks).toEqual([]);
986 });
987});
988​
989it("round-trips typed notifications and keeps work outcome separate from item status", () => {
990 const now = DateTime.makeUnsafe("2026-09-09T00:00:00Z");
991 const base = {
992 id: "notification",
993 threadId: "parent",
994 runId: null,
995 nodeId: null,
996 providerThreadId: null,
997 providerTurnId: null,
998 nativeItemRef: null,
999 parentItemId: null,
1000 ordinal: 1,
1001 status: "completed",
1002 title: null,
1003 startedAt: null,
1004 completedAt: null,
1005 type: "notification",
1006 outcome: "failed",
1007 summary: "Build failed",
1008 detail: "Exit code 1",
1009 };
1010 for (const source of [
1011 { kind: "delegated_task", taskIds: ["task-1", "task-2"] },
1012 { kind: "background_task" },
1013 { kind: "background_command" },
1014 { kind: "monitor" },
1015 ]) {
1016 const runtime = decodeOrchestrationV2TurnItem({ ...base, source, updatedAt: now });
1017 const wire = encodeOrchestrationV2TurnItemJson(runtime);
1018 expect(decodeOrchestrationV2TurnItemJson(wire)).toEqual(runtime);
1019 expect(runtime).toMatchObject({ status: "completed", outcome: "failed", source });
1020 expect(runtime).not.toHaveProperty("messageId");
1021 expect(() =>
1022 decodeOrchestrationV2TurnItem({ ...base, source, summary: "", updatedAt: now }),
1023 ).toThrow();
1025 expect(() =>
1026 decodeOrchestrationV2TurnItem({ ...base, source: { kind: "delegated_task" }, updatedAt: now }),
1027 ).toThrow();
1028});
1029​
1030describe("limit recovery choice updates", () => {
1031 const decode = Schema.decodeUnknownSync(OrchestrationV2LimitRecoveryUpdate);
1032 const identity = { runId: "run:limited", resetAt: "2026-09-20T21:00:00.000Z" };
1033 it("rejects updates that would disable defaults without choosing an option", () => {
1034 expect(() => decode(identity)).toThrow("A recovery update must include autoResume or snooze");
1035 });
1036 it.each([
1037 { autoResume: true },
1038 { autoResume: false },
1039 { snooze: true },
1040 { snooze: false },
1041 { autoResume: true, snooze: false },
1042 ])("accepts an explicit independent choice %j", (choice) => {
1043 expect(decode({ ...identity, ...choice })).toEqual({ ...identity, ...choice });
1044 });
1045});