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