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

orchestrationV2.test.ts

756 lines26.8 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as DateTime from "effect/DateTime";
3import * as Schema from "effect/Schema";
4​
5import {
6 EnvironmentId,
7 NodeId,
8 RunAttemptId,
9 RunId,
10 ScheduledTaskId,
11 ThreadId,
12 TrimmedNonEmptyString,
13} from "./index.ts";
14import {
15 latestProviderTurnForAttempt,
16 OrchestrationV2CheckpointFileSummary,
17 OrchestrationV2FileSearchResult,
18 repositoryRewindCheckpoint,
19 OrchestrationV2ProviderCapabilities,
20 OrchestrationV2ProviderThread,
21 OrchestrationV2ProviderThreadJson,
22 OrchestrationV2RpcSchemas,
23 OrchestrationV2Subagent,
24 OrchestrationV2ThreadShellJson,
25 OrchestrationV2SubagentJson,
26 OrchestrationV2ThreadHistoryPage,
27 OrchestrationV2TurnItem,
28 OrchestrationV2TurnItemJson,
29 withMessageSenderNote,
30} from "./orchestrationV2.ts";
31​
32const now = DateTime.makeUnsafe("2026-04-20T00:00:00.000Z");
33​
34const decodeOrchestrationV2TurnItemJson = Schema.decodeUnknownSync(OrchestrationV2TurnItemJson);
35const encodeOrchestrationV2TurnItemJson = Schema.encodeSync(OrchestrationV2TurnItemJson);
36const decodeOrchestrationV2Subagent = Schema.decodeUnknownSync(OrchestrationV2Subagent);
37const decodeCheckpointFileSummary = Schema.decodeSync(OrchestrationV2CheckpointFileSummary);
38const encodeOrchestrationV2SubagentJson = Schema.encodeSync(OrchestrationV2SubagentJson);
39const decodeOrchestrationV2ProviderThreadJson = Schema.decodeUnknownSync(
40 OrchestrationV2ProviderThreadJson,
41);
42const encodeOrchestrationV2ProviderThreadJson = Schema.encodeSync(
43 OrchestrationV2ProviderThreadJson,
44);
45const decodeOrchestrationV2ProviderThread = Schema.decodeUnknownSync(OrchestrationV2ProviderThread);
46const decodeOrchestrationV2ProviderCapabilities = Schema.decodeUnknownSync(
47 OrchestrationV2ProviderCapabilities,
48);
49​
50describe("orchestration V2 contracts", () => {
51 it("preserves trailing spaces in file search result paths on the wire", () => {
52 const codec = Schema.toCodecJson(OrchestrationV2FileSearchResult);
53 const result = { fileName: "docs/Release notes.md ", line: 3 };
54 const encoded = Schema.encodeSync(codec)(result);
55 expect(encoded).toEqual(result);
56 expect(Schema.decodeSync(codec)(result)).toEqual(result);
57 });
58​
59 it("decodes thread event types from a newer server as skippable items", () => {
60 const decodeWireItems = Schema.decodeUnknownSync(
61 Schema.toCodecJson(Schema.Array(OrchestrationV2RpcSchemas.subscribeThread.output)),
62 );
63 const detached = (id: string, sequence: number) => ({
64 kind: "event",
65 sequence,
66 event: {
67 id,
68 type: "provider-session.detached",
69 threadId: "thread-1",
70 occurredAt: DateTime.formatIso(now),
71 payload: { providerSessionId: "provider-session-1", detachedAt: DateTime.formatIso(now) },
72 },
73 });
74​
75 const items = decodeWireItems([
76 detached("event-1", 1),
77 {
78 kind: "event",
79 sequence: 2,
80 event: {
81 id: "event-2",
82 type: "run.from-a-future-server",
83 threadId: "thread-1",
84 occurredAt: DateTime.formatIso(now),
85 payload: { runId: "run-1" },
86 },
87 },
88 detached("event-3", 3),
89 ]);
90​
91 expect(items.map((item) => item.kind)).toEqual(["event", "unknown-event", "event"]);
92 expect(items[1]).toEqual({
93 kind: "unknown-event",
94 sequence: 2,
95 eventType: "run.from-a-future-server",
96 });
97 expect(() =>
98 decodeWireItems([
99 { ...detached("event-4", 4), event: { ...detached("event-4", 4).event, payload: {} } },
100 ]),
101 ).toThrow();
102 });
103​
104 it("skips turn item types from a newer server in snapshots and turn-item events", () => {
105 const decodeWireItems = Schema.decodeUnknownSync(
106 Schema.toCodecJson(Schema.Array(OrchestrationV2RpcSchemas.subscribeThread.output)),
107 );
108 const decodeHistoryPage = Schema.decodeUnknownSync(
109 Schema.toCodecJson(OrchestrationV2ThreadHistoryPage),
110 );
111 const item = (id: string, type: string, extra: Record<string, unknown>) => ({
112 id,
113 type,
114 threadId: "thread-1",
115 runId: null,
116 nodeId: null,
117 providerThreadId: null,
118 providerTurnId: null,
119 nativeItemRef: null,
120 parentItemId: null,
121 ordinal: 1,
122 status: "completed",
123 title: null,
124 startedAt: null,
125 completedAt: null,
126 updatedAt: DateTime.formatIso(now),
127 ...extra,
128 });
129 const known = item("item-known", "system_notice", { message: "Hello" });
130 const future = item("item-future", "hologram", { beam: "ref-1" });
131 const projected = (position: number, turnItem: { readonly id: string }) => ({
132 position,
133 visibility: "local",
134 sourceThreadId: "thread-1",
135 sourceItemId: turnItem.id,
136 item: turnItem,
137 });
138 const projection = {
139 thread: {
140 createdBy: "user",
141 creationSource: "web",
142 id: "thread-1",
143 projectId: "project-1",
144 title: "Thread",
145 providerInstanceId: "codex",
146 modelSelection: { instanceId: "codex", model: "gpt-5-codex" },
147 runtimeMode: "full-access",
148 interactionMode: "default",
149 branch: null,
150 worktreePath: null,
151 activeProviderThreadId: null,
152 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: "thread-1" },
153 forkedFrom: null,
154 createdAt: DateTime.formatIso(now),
155 updatedAt: DateTime.formatIso(now),
156 archivedAt: null,
157 deletedAt: null,
158 },
159 runs: [],
160 attempts: [],
161 nodes: [],
162 subagents: [],
163 providerSessions: [],
164 providerThreads: [],
165 providerTurns: [],
166 runtimeRequests: [],
167 messages: [],
168 plans: [],
169 turnItems: [future, known],
170 checkpointScopes: [],
171 checkpoints: [],
172 contextHandoffs: [],
173 contextTransfers: [],
174 visibleTurnItems: [projected(0, future), projected(1, known)],
175 updatedAt: DateTime.formatIso(now),
176 };
177 const turnItemEvent = (sequence: number, payload: unknown) => ({
178 kind: "event",
179 sequence,
180 event: {
181 id: `event-${sequence}`,
182 type: "turn-item.updated",
183 threadId: "thread-1",
184 occurredAt: DateTime.formatIso(now),
185 payload,
186 },
187 });
188​
189 const [snapshot, futureEvent, knownEvent] = decodeWireItems([
190 { kind: "snapshot", snapshotSequence: 1, projection },
191 turnItemEvent(2, future),
192 turnItemEvent(3, known),
193 ]);
194​
195 expect(snapshot).toMatchObject({ kind: "snapshot" });
196 if (snapshot?.kind !== "snapshot") throw new Error("expected a snapshot");
197 expect(snapshot.projection.turnItems.map((turnItem) => turnItem.id)).toEqual(["item-known"]);
198 expect(snapshot.projection.visibleTurnItems.map((row) => row.item.id)).toEqual(["item-known"]);
199 // The same snapshot with an ID table: refs resolve before unknown items are skipped.
200 const tabled = (turnItem: { readonly id: string }, ref: number) => ({ ...turnItem, id: ref });
201 const [tabledSnapshot] = decodeWireItems([
202 {
203 kind: "snapshot",
204 snapshotSequence: 1,
205 projection: {
206 ...projection,
207 turnItems: [tabled(future, 0), tabled(known, 1)],
208 visibleTurnItems: [
209 { ...projected(0, future), sourceItemId: 0, item: tabled(future, 0) },
210 { ...projected(1, known), sourceItemId: 1, item: tabled(known, 1) },
211 ],
212 },
213 ids: ["item-future", "item-known"],
214 },
215 ]);
216 expect(tabledSnapshot).toEqual(snapshot);
217 expect(futureEvent).toEqual({
218 kind: "unknown-event",
219 sequence: 2,
220 eventType: "turn-item.updated",
221 });
222 expect(knownEvent).toMatchObject({
223 kind: "event",
224 event: { type: "turn-item.updated", payload: { id: "item-known", type: "system_notice" } },
225 });
226 expect(
227 decodeHistoryPage({
228 snapshotSequence: 1,
229 items: [projected(0, future), projected(1, known)],
230 nextCursor: null,
231 hasMoreHistory: false,
232 }).items.map((row) => row.item.id),
233 ).toEqual(["item-known"]);
234​
235 const broken = item("item-broken", "system_notice", {});
236 expect(() => decodeWireItems([turnItemEvent(4, broken)])).toThrow();
237 expect(() =>
238 decodeWireItems([
239 {
240 kind: "snapshot",
241 snapshotSequence: 1,
242 projection: { ...projection, turnItems: [broken] },
243 },
244 ]),
245 ).toThrow();
246 });
247​
248 it("decodes persisted capability snapshots that predate runtimePolicy", () => {
249 const legacyCapabilities = {
250 sessions: {
251 supportsMultipleProviderThreadsPerSession: false,
252 supportsModelSwitchInSession: false,
253 supportsProviderSwitchingViaHandoff: true,
254 supportsRuntimeModeSwitchInSession: false,
255 pendingRequestsSurviveRestart: false,
256 },
257 threads: {
258 canCreateEmptyThread: true,
259 canReadThreadSnapshot: false,
260 canRollbackThread: true,
261 canForkThread: false,
262 canForkFromTurn: false,
263 canForkFromSubagentThread: false,
264 exposesNativeThreadId: true,
265 },
266 turns: {
267 exposesNativeTurnId: false,
268 emitsTurnStarted: true,
269 emitsTurnCompleted: true,
270 supportsInterrupt: true,
271 supportsActiveSteering: false,
272 supportsSteeringByInterruptRestart: true,
273 supportsQueuedMessages: true,
274 terminalStatusQuality: "strong",
275 },
276 streaming: {
277 streamsAssistantText: true,
278 streamsReasoning: true,
279 streamsToolOutput: true,
280 streamsPlanText: false,
281 emitsMessageCompleted: true,
282 },
283 tools: {
284 exposesToolItemIds: true,
285 emitsToolStarted: true,
286 emitsToolCompleted: true,
287 emitsToolOutput: true,
288 supportsMcpTools: false,
289 supportsDynamicToolCallbacks: false,
290 },
291 approvals: {
292 supportsCommandApproval: true,
293 supportsFileReadApproval: true,
294 supportsFileChangeApproval: true,
295 supportsApplyPatchApproval: false,
296 approvalsHaveNativeRequestIds: false,
297 approvalCallbacksAreLiveOnly: true,
298 approvalsCanOriginateFromSubagents: false,
299 },
300 planning: {
301 emitsPlanUpdated: true,
302 emitsTodoList: true,
303 emitsProposedPlan: false,
304 supportsStructuredQuestions: true,
305 planDeltasHaveItemIds: false,
306 },
307 subagents: {
308 supportsSubagents: false,
309 exposesSubagentThreadIds: false,
310 emitsSubagentLifecycle: false,
311 canWaitForSubagents: false,
312 canCloseSubagents: false,
313 canForkSubagentThread: false,
314 },
315 context: {
316 acceptsSystemContext: false,
317 acceptsDeveloperContext: false,
318 acceptsSyntheticUserContext: true,
319 canGenerateSummaries: true,
320 canConsumeHandoffSummaries: true,
321 supportsDeltaHandoff: true,
322 supportsFullThreadHandoff: true,
323 maxRecommendedHandoffChars: null,
324 },
325 checkpointing: {
326 appCanCheckpointFilesystem: true,
327 supportsNestedCheckpointScopes: true,
328 providerCanRollbackConversation: true,
329 providerRollbackReturnsSnapshot: true,
330 providerCanReadConversationSnapshot: false,
331 },
332 identity: {
333 nativeThreadIds: "strong",
334 nativeTurnIds: "weak",
335 nativeItemIds: "weak",
336 nativeRequestIds: "weak",
337 },
338 };
339​
340 const decoded = decodeOrchestrationV2ProviderCapabilities(legacyCapabilities);
341 expect(decoded.runtimePolicy).toEqual({ enforcement: "client-boundary" });
342​
343 const explicit = decodeOrchestrationV2ProviderCapabilities({
344 ...legacyCapabilities,
345 runtimePolicy: { enforcement: "native" },
346 });
347 expect(explicit.runtimePolicy).toEqual({ enforcement: "native" });
348 });
349​
350 it.each([" indented prompt\n", "\n \t\n"])(
351 "preserves workflow prompt and result %j in stored and wire JSON",
352 (preview) => {
353 const subagent = {
354 ...decodeOrchestrationV2Subagent({
355 id: "workflow-coordinator",
356 threadId: "thread-1",
357 runId: "run-1",
358 parentNodeId: "node-root-1",
359 origin: "provider_native",
360 createdBy: "agent",
361 driver: "claudeAgent",
362 providerInstanceId: "claudeAgent",
363 providerThreadId: null,
364 childThreadId: null,
365 nativeTaskRef: null,
366 prompt: "Run workflow",
367 title: null,
368 model: null,
369 status: "running",
370 result: null,
371 startedAt: now,
372 completedAt: null,
373 updatedAt: now,
374 }),
375 workflow: {
376 phases: [],
377 agents: [
378 {
379 index: 1,
380 label: "Member",
381 state: "completed" as const,
382 model: "claude-opus-5[1m]",
383 effort: "xhigh",
384 speed: "standard",
385 prompt: preview,
386 result: preview,
387 },
388 ],
389 },
390 };
391 const { workflow, ...coordinator } = subagent;
392 const incoming = { ...encodeOrchestrationV2SubagentJson(coordinator), workflow };
393 for (const codec of [
394 OrchestrationV2SubagentJson,
395 Schema.toCodecJson(OrchestrationV2Subagent),
396 ]) {
397 const encode = Schema.encodeSync(codec);
398 const decode = Schema.decodeUnknownSync(codec);
399 const json: unknown = JSON.parse(JSON.stringify(encode(subagent)));
400 expect(json).toMatchObject({
401 workflow: { agents: [{ prompt: preview, result: preview }] },
402 });
403 expect(decode(json).workflow?.agents[0]).toMatchObject({
404 prompt: preview,
405 result: preview,
406 model: "claude-opus-5[1m]",
407 effort: "xhigh",
408 speed: "standard",
409 });
410 expect(decode(incoming).workflow?.agents[0]).toMatchObject({
411 prompt: preview,
412 result: preview,
413 model: "claude-opus-5[1m]",
414 effort: "xhigh",
415 speed: "standard",
416 });
417 }
418 },
419 );
420​
421 it.each([" leading.ts", "src/trailing.ts "])(
422 "decodes the checkpoint file path %j exactly",
423 (path) => {
424 expect(
425 decodeCheckpointFileSummary({ path, kind: "added", additions: 1, deletions: 0 }).path,
426 ).toBe(path);
427 },
428 );
429​
430 it("decodes historical provider-thread JSON without pendingBackgroundTasks as empty roster", () => {
431 const providerThread = decodeOrchestrationV2ProviderThreadJson({
432 id: "provider-thread-1",
433 driver: "claude",
434 providerInstanceId: "claudeAgent",
435 providerSessionId: "provider-session-1",
436 appThreadId: "thread-1",
437 ownerNodeId: null,
438 nativeThreadRef: {
439 driver: "claude",
440 nativeId: "native-session-1",
441 strength: "strong",
442 },
443 nativeConversationHeadRef: null,
444 status: "idle",
445 firstRunOrdinal: 1,
446 lastRunOrdinal: 1,
447 handoffIds: [],
448 forkedFrom: null,
449 createdAt: "2026-04-20T00:00:00.000Z",
450 updatedAt: "2026-04-20T00:00:00.000Z",
451 });
452​
453 expect(providerThread.pendingBackgroundTasks).toEqual([]);
454 expect(providerThread.contextUsage).toBeNull();
455 expect(providerThread.nativeMetadata).toBeNull();
456​
457 const runtimeThread = decodeOrchestrationV2ProviderThread({
458 id: "provider-thread-2",
459 driver: "claude",
460 providerInstanceId: "claudeAgent",
461 providerSessionId: null,
462 appThreadId: "thread-2",
463 ownerNodeId: null,
464 nativeThreadRef: null,
465 nativeConversationHeadRef: null,
466 status: "idle",
467 firstRunOrdinal: null,
468 lastRunOrdinal: null,
469 handoffIds: [],
470 forkedFrom: null,
471 createdAt: now,
472 updatedAt: now,
473 });
474 expect(runtimeThread.pendingBackgroundTasks).toEqual([]);
475 expect(runtimeThread.contextUsage).toBeNull();
476 expect(runtimeThread.nativeMetadata).toBeNull();
477 });
478});
479​
480describe("thread open stats", () => {
481 it("reads a thread whose open stats this build cannot read, without them", () => {
482 const shell = {
483 id: "thread-test",
484 projectId: "project-test",
485 title: "Thread",
486 providerInstanceId: "codex",
487 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
488 runtimeMode: "full-access",
489 interactionMode: "default",
490 branch: null,
491 worktreePath: null,
492 activeProviderThreadId: null,
493 lineage: { rootThreadId: "thread-test", parentThreadId: null, relationshipToParent: null },
494 forkedFrom: null,
495 createdBy: "user",
496 creationSource: "mobile",
497 latestRunId: null,
498 activeRunId: null,
499 status: "idle",
500 pendingRuntimeRequest: null,
501 latestVisibleMessage: null,
502 latestUserMessageAt: null,
503 hasActionableProposedPlan: false,
504 itemCount: 0,
505 visibleItemCount: 0,
506 createdAt: "2026-10-01T00:00:00.000Z",
507 updatedAt: "2026-10-01T00:00:00.000Z",
508 archivedAt: null,
509 settledOverride: null,
510 settledAt: null,
511 deletedAt: null,
512 };
513 const decode = Schema.decodeUnknownSync(OrchestrationV2ThreadShellJson);
514 const opens = { openedAt: 1, score: 1, picks: [{ query: "upl", at: 1 }] };
515 expect(decode({ ...shell, opens }).opens).toEqual(opens);
516 expect(decode({ ...shell, opens: { openedAt: "2026-10-01", score: 1 } }).opens).toBeNull();
517 });
518});
519​
520describe("background work kinds from older or newer servers", () => {
521 const storedNotification = (source: unknown) => ({
522 id: "notification",
523 threadId: "parent",
524 runId: null,
525 nodeId: null,
526 providerThreadId: null,
527 providerTurnId: null,
528 nativeItemRef: null,
529 parentItemId: null,
530 ordinal: 1,
531 status: "completed",
532 title: null,
533 startedAt: null,
534 completedAt: null,
535 updatedAt: "2026-09-09T00:00:00.000Z",
536 type: "notification",
537 outcome: "completed",
538 summary: "Background activity updated",
539 source,
540 });
541​
542 it("decodes notification sources stored before specific kinds existed", () => {
543 const sourceOf = (source: unknown) => {
544 const item = decodeOrchestrationV2TurnItemJson(storedNotification(source));
545 return item.type === "notification" ? item.source : undefined;
546 };
547 expect(
548 sourceOf({ kind: "background_task", nativeRef: { driver: "claude", nativeId: "task-1" } }),
549 ).toEqual({ kind: "background_task" });
550 expect(sourceOf({ kind: "background_command" })).toEqual({ kind: "command" });
551 expect(sourceOf({ kind: "monitor" })).toEqual({ kind: "monitor" });
552 });
553​
554 it("sends and stores sources that clients from before specific kinds still decode", () => {
555 const PreSpecificKindsNotification = Schema.Struct({
556 type: Schema.Literal("notification"),
557 source: Schema.Union([
558 Schema.Struct({ kind: Schema.Literal("delegated_task"), taskIds: Schema.Array(NodeId) }),
559 Schema.Struct({
560 kind: Schema.Literals(["background_task", "background_command", "monitor"]),
561 nativeRef: Schema.optional(Schema.Unknown),
562 }),
563 ]),
564 outcome: Schema.Literals(["completed", "failed", "cancelled", "updated", "unknown"]),
565 summary: Schema.String,
566 detail: Schema.optional(Schema.String),
567 });
568 const decodePreSpecificKinds = Schema.decodeUnknownSync(PreSpecificKindsNotification);
569 const sendOverWire = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2TurnItem));
570 const cases = [
571 [{ kind: "subagent", childThreadId: "child" }, { kind: "background_task" }],
572 [{ kind: "subagent" }, { kind: "background_task" }],
573 [{ kind: "command" }, { kind: "background_command" }],
574 [{ kind: "monitor" }, { kind: "monitor" }],
575 [{ kind: "background_task" }, { kind: "background_task" }],
576 [
577 { kind: "delegated_task", taskIds: ["task-1"], childThreadId: "child" },
578 { kind: "delegated_task", taskIds: ["task-1"] },
579 ],
580 ] as const;
581 for (const [source, preSpecificKindsSource] of cases) {
582 const item = decodeOrchestrationV2TurnItemJson(storedNotification(source));
583 for (const encoded of [encodeOrchestrationV2TurnItemJson(item), sendOverWire(item)]) {
584 expect(decodePreSpecificKinds(encoded).source).toEqual(preSpecificKindsSource);
585 expect(decodeOrchestrationV2TurnItemJson(encoded)).toEqual(item);
586 }
587 expect(item).toMatchObject({ source });
588 }
589 });
590​
591 it("decodes a notification source kind from a newer server as generic background work", () => {
592 const item = decodeOrchestrationV2TurnItemJson(
593 storedNotification({ kind: "workflow", workflowId: "wf-1" }),
594 );
595 expect(item).toMatchObject({ type: "notification", source: { kind: "background_task" } });
596 });
597​
598 it("decodes rosters stored before kinds existed, and kinds from a newer server, as generic tasks", () => {
599 const providerThread = decodeOrchestrationV2ProviderThreadJson({
600 id: "provider-thread-1",
601 driver: "claude",
602 providerInstanceId: "claudeAgent",
603 providerSessionId: null,
604 appThreadId: "thread-1",
605 ownerNodeId: null,
606 nativeThreadRef: null,
607 nativeConversationHeadRef: null,
608 status: "idle",
609 firstRunOrdinal: 1,
610 lastRunOrdinal: 1,
611 handoffIds: [],
612 forkedFrom: null,
613 createdAt: "2026-04-20T00:00:00.000Z",
614 updatedAt: "2026-04-20T00:00:00.000Z",
615 pendingBackgroundTasks: [
616 { taskId: "bg-1", description: "Background sleep", taskType: "local_bash" },
617 { taskId: "bg-2" },
618 { taskId: "bg-3", description: "Nightly", kind: "workflow", schedule: "0 3 * * *" },
619 { taskId: "bg-4", description: "npm test", kind: "command" },
620 { taskId: "bg-5", kind: "subagent", childThreadId: "thread-child" },
621 { taskId: "bg-6", kind: "subagent", providerInstanceId: "claudeAgent" },
622 ],
623 });
624 expect(providerThread.pendingBackgroundTasks).toEqual([
625 { taskId: "bg-1", description: "Background sleep", kind: "background_task" },
626 { taskId: "bg-2", kind: "background_task" },
627 { taskId: "bg-3", description: "Nightly", kind: "background_task" },
628 { taskId: "bg-4", description: "npm test", kind: "command" },
629 { taskId: "bg-5", kind: "subagent", childThreadId: "thread-child" },
630 { taskId: "bg-6", kind: "subagent", providerInstanceId: "claudeAgent" },
631 ]);
632 const encoded = encodeOrchestrationV2ProviderThreadJson(providerThread).pendingBackgroundTasks;
633 expect(encoded).toEqual(providerThread.pendingBackgroundTasks);
634 const decodePreKindsRoster = Schema.decodeUnknownSync(
635 Schema.Array(
636 Schema.Struct({
637 taskId: TrimmedNonEmptyString,
638 description: Schema.optional(TrimmedNonEmptyString),
639 taskType: Schema.optional(TrimmedNonEmptyString),
640 }),
641 ),
642 );
643 expect(decodePreKindsRoster(encoded).map((task) => task.taskId)).toEqual([
644 "bg-1",
645 "bg-2",
646 "bg-3",
647 "bg-4",
648 "bg-5",
649 "bg-6",
650 ]);
651 expect(() =>
652 decodeOrchestrationV2ProviderThreadJson({
653 ...encodeOrchestrationV2ProviderThreadJson(providerThread),
654 pendingBackgroundTasks: [{ taskId: "", kind: "command" }],
655 }),
656 ).toThrow();
657 });
658});
659​
660describe("latestProviderTurnForAttempt", () => {
661 it("returns the attempt's highest-ordinal turn, as a Codex goal run spans several", () => {
662 const turns = [
663 { id: "first", runAttemptId: RunAttemptId.make("goal-attempt"), ordinal: 3 },
664 { id: "other", runAttemptId: RunAttemptId.make("other-attempt"), ordinal: 9 },
665 { id: "last", runAttemptId: RunAttemptId.make("goal-attempt"), ordinal: 5 },
666 { id: "subagent", runAttemptId: null, ordinal: 7 },
667 ];
668 expect(latestProviderTurnForAttempt(turns, RunAttemptId.make("goal-attempt"))?.id).toBe("last");
669 expect(latestProviderTurnForAttempt(turns, null)).toBeUndefined();
670 });
671});
672​
673describe("repositoryRewindCheckpoint", () => {
674 const run = RunId.make("run");
675 // Runs 2 and 6 changed the repository; a rewind to run 3 already discarded what run 5 recorded.
676 // Run 11's snapshot failed, run 12 left the repository alone, run 13 changed it.
677 const checkpoints = [
678 { ordinalWithinScope: 1, runId: null, status: "ready" },
679 { ordinalWithinScope: 2, runId: run, status: "ready" },
680 { ordinalWithinScope: 4, runId: null, status: "stale" },
681 { ordinalWithinScope: 5, runId: run, status: "stale" },
682 { ordinalWithinScope: 5, runId: null, status: "ready" },
683 { ordinalWithinScope: 6, runId: run, status: "ready" },
684 { ordinalWithinScope: 8, runId: null, status: "missing" },
685 { ordinalWithinScope: 9, runId: run, status: "ready" },
686 { ordinalWithinScope: 10, runId: null, status: "missing" },
687 { ordinalWithinScope: 11, runId: run, status: "error" },
688 { ordinalWithinScope: 12, runId: null, status: "ready" },
689 { ordinalWithinScope: 13, runId: run, status: "ready" },
690 ] as const;
691​
692 it.each([
693 { target: 0, restores: 1, why: "the baseline before the first change" },
694 { target: 2, restores: 2, why: "the target run's own checkpoint" },
695 { target: 3, restores: 5, why: "the baseline before the next change, past stale records" },
696 { target: 6, restores: 6, why: "the target run's own checkpoint" },
697 { target: 7, restores: null, why: "nothing: the state before run 9 was never snapshotted" },
698 { target: 10, restores: null, why: "nothing: run 11's failed snapshot hides what it changed" },
699 {
700 target: 11,
701 restores: 12,
702 why: "the baseline before the next change, its own snapshot failed",
703 },
704 { target: 14, restores: null, why: "nothing: no later run changed the repository" },
705 ])("a rewind to run $target restores $why", ({ target, restores }) => {
706 expect(repositoryRewindCheckpoint(checkpoints, target)?.ordinalWithinScope ?? null).toBe(
707 restores,
708 );
709 });
710});
711​
712describe("withMessageSenderNote", () => {
713 const thread = {
714 createdBy: "agent",
715 creationSource: "mcp",
716 senderThreadId: ThreadId.make("t"),
717 } as const;
718 it.each([
719 [thread, "Hi", '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]\n\nHi'],
720 [thread, "", '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]'],
721 [thread, " /git/review staged", " /git/review staged"],
722 [thread, "$deploy ship it", "$deploy ship it"],
723 [
724 thread,
725 "$25 left",
726 '[T3 Code: the agent in T3 thread "t" sent this message, not the user.]\n\n$25 left',
727 ],
728 [
729 {
730 createdBy: "agent",
731 creationSource: "mcp",
732 linkedSender: {
733 environmentId: EnvironmentId.make("e"),
734 threadId: ThreadId.make("r"),
735 title: "x",
736 },
737 },
738 "Hi",
739 '[T3 Code: the agent in T3 thread "r" on linked environment "e" sent this message, not the user.]\n\nHi',
740 ],
741 [
742 { createdBy: "user", creationSource: "web", scheduledTaskId: ScheduledTaskId.make("s") },
743 "Hi",
744 '[T3 Code: scheduled task "s" sent this prompt, not the user typing in this chat.]\n\nHi',
745 ],
746 [
747 { createdBy: "agent", creationSource: "mcp" },
748 "Hi",
749 "[T3 Code: this message came through T3 Code's tools, not from the user typing in this chat.]\n\nHi",
750 ],
751 [{ createdBy: "user", creationSource: "web" }, "Hi", "Hi"],
752 [{ createdBy: "agent", creationSource: "server" }, "Hi", "Hi"],
753 ] as const)("labels %j's message %j for the provider", (message, text, expected) => {
754 expect(withMessageSenderNote(message, text)).toBe(expected);
755 });
756});