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