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

orchestrationV2.test.ts

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