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