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

CodexReplayFixtures.integration.test.ts

786 lines27.7 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import type { ProviderReplayTranscript } from "@t3tools/contracts";
4import * as CodexReplay from "effect-codex-app-server/replay";
5import * as Effect from "effect/Effect";
6import * as Schema from "effect/Schema";
7​
8import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts";
9import {
10 THREAD_FORK_NATIVE_CONTINUE_FORK_MARKER,
11 THREAD_FORK_NATIVE_CONTINUE_RECALL,
12 THREAD_FORK_NATIVE_CONTINUE_SOURCE_MARKER,
13 THREAD_MERGE_BACK_FORK_MARKER,
14 THREAD_MERGE_BACK_RECALL,
15 THREAD_MERGE_BACK_SIBLINGS_FIRST_MARKER,
16 THREAD_MERGE_BACK_SIBLINGS_RECALL,
17 THREAD_MERGE_BACK_SIBLINGS_SECOND_MARKER,
18 THREAD_MERGE_BACK_SIBLINGS_SOURCE_MARKER,
19 THREAD_MERGE_BACK_SOURCE_MARKER,
20} from "./fixtures/shared.ts";
21import { readProviderReplayTranscript } from "@t3tools/provider-testing/replayTranscript";
22​
23const PROVIDER_THREAD_RESUME_FIRST_FINAL = "provider thread resume fixture first turn complete";
24const PROVIDER_THREAD_RESUME_SECOND_FINAL = "provider thread resume fixture second turn complete";
25​
26type ProtocolReplayEntry = Extract<
27 ProviderReplayTranscript["entries"][number],
28 { readonly type: "expect_outbound" | "emit_inbound" }
29>;
30​
31interface CodexReplayFixtureRegistration {
32 readonly registrationScenario: string;
33 readonly recordedScenario: string;
34 readonly transcriptFile: URL;
36​
37const CODEX_REPLAY_FIXTURE_REGISTRATIONS = ORCHESTRATOR_REPLAY_FIXTURES.flatMap((fixture) =>
38 fixture.providers
39 .filter((provider) => provider.driver === "codex")
40 .map((provider) => ({
41 registrationScenario: fixture.name,
42 recordedScenario: provider.recordedScenario ?? fixture.name,
43 transcriptFile: provider.transcriptFile,
44 })),
45).concat([
46 {
47 registrationScenario: "provider_thread_resume",
48 recordedScenario: "provider_thread_resume",
49 transcriptFile: new URL(
50 "./fixtures/provider_thread_resume/codex_transcript.ndjson",
51 import.meta.url,
52 ),
53 },
54 {
55 registrationScenario: "thread_fork_native_continue",
56 recordedScenario: "thread_fork_native_continue",
57 transcriptFile: new URL(
58 "./fixtures/thread_fork_native_continue/codex_transcript.ndjson",
59 import.meta.url,
60 ),
61 },
62 {
63 registrationScenario: "thread_fork_native_siblings",
64 recordedScenario: "thread_fork_native_siblings",
65 transcriptFile: new URL(
66 "./fixtures/thread_fork_native_siblings/codex_transcript.ndjson",
67 import.meta.url,
68 ),
69 },
70 {
71 registrationScenario: "thread_merge_back_continue",
72 recordedScenario: "thread_merge_back_continue",
73 transcriptFile: new URL(
74 "./fixtures/thread_merge_back_continue/codex_transcript.ndjson",
75 import.meta.url,
76 ),
77 },
78 {
79 registrationScenario: "thread_merge_back_siblings",
80 recordedScenario: "thread_merge_back_siblings",
81 transcriptFile: new URL(
82 "./fixtures/thread_merge_back_siblings/codex_transcript.ndjson",
83 import.meta.url,
84 ),
85 },
86]);
87​
88function uniqueCanonicalTranscripts(
89 registrations: ReadonlyArray<CodexReplayFixtureRegistration>,
90): ReadonlyArray<CodexReplayFixtureRegistration> {
91 const canonicalTranscripts = new Map<string, CodexReplayFixtureRegistration>();
92 for (const registration of registrations) {
93 const canonicalUrl = registration.transcriptFile.href;
94 const existing = canonicalTranscripts.get(canonicalUrl);
95 if (existing !== undefined && existing.recordedScenario !== registration.recordedScenario) {
96 throw new Error(
97 `Codex replay transcript ${canonicalUrl} has conflicting recorded scenarios ${existing.recordedScenario} (${existing.registrationScenario}) and ${registration.recordedScenario} (${registration.registrationScenario}).`,
98 );
99 }
100 canonicalTranscripts.set(canonicalUrl, existing ?? registration);
101 }
102 return Array.from(canonicalTranscripts.values());
104​
105const CODEX_REPLAY_TRANSCRIPTS = uniqueCanonicalTranscripts(CODEX_REPLAY_FIXTURE_REGISTRATIONS);
106​
107const scenarioExpectations = {
108 simple: {
109 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
110 incoming: ["thread/started", "turn/started", "turn/completed"],
111 turnStartCount: 1,
112 turnCompletedCount: 1,
113 approvalRequestCount: 0,
114 },
115 tool_call_read_only_on_request: {
116 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
117 incoming: ["item/commandExecution/requestApproval", "serverRequest/resolved", "turn/completed"],
118 turnStartCount: 1,
119 turnCompletedCount: 1,
120 approvalRequestCount: 1,
121 },
122 tool_call_workspace_never: {
123 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
124 incoming: ["turn/completed"],
125 turnStartCount: 1,
126 turnCompletedCount: 1,
127 approvalRequestCount: 0,
128 },
129 tool_call_restricted_granular: {
130 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
131 incoming: ["item/fileChange/requestApproval", "serverRequest/resolved", "turn/completed"],
132 turnStartCount: 1,
133 turnCompletedCount: 1,
134 approvalRequestCount: 1,
135 },
136 subagent: {
137 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
138 incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
139 turnStartCount: 1,
140 turnCompletedCount: 3,
141 approvalRequestCount: 0,
142 },
143 subagent_continue: {
144 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
145 incoming: ["turn/started", "item/completed", "turn/completed"],
146 turnStartCount: 2,
147 turnCompletedCount: 4,
148 approvalRequestCount: 0,
149 },
150 subagent_v2: {
151 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
152 incoming: ["turn/started", "item/completed", "item/agentMessage/delta", "turn/completed"],
153 turnStartCount: 1,
154 turnCompletedCount: 2,
155 approvalRequestCount: 0,
156 },
157 subagent_v2_approval: {
158 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
159 incoming: [
160 "item/commandExecution/requestApproval",
161 "serverRequest/resolved",
162 "item/completed",
163 "turn/completed",
164 ],
165 turnStartCount: 1,
166 turnCompletedCount: 2,
167 approvalRequestCount: 1,
168 },
169 subagent_v2_nested: {
170 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
171 incoming: ["turn/started", "item/completed", "item/agentMessage/delta", "turn/completed"],
172 turnStartCount: 1,
173 turnCompletedCount: 4,
174 approvalRequestCount: 0,
175 },
176 subagent_v2_nested_approval: {
177 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
178 incoming: [
179 "item/commandExecution/requestApproval",
180 "serverRequest/resolved",
181 "item/completed",
182 "turn/completed",
183 ],
184 turnStartCount: 1,
185 turnCompletedCount: 3,
186 approvalRequestCount: 1,
187 },
188 multi_turn: {
189 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
190 incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
191 turnStartCount: 2,
192 turnCompletedCount: 2,
193 approvalRequestCount: 0,
194 },
195 plan_questions: {
196 outgoing: [
197 "initialize",
198 "initialized",
199 "thread/start",
200 "turn/start",
201 "item/tool/requestUserInput",
202 ],
203 incoming: [
204 "turn/started",
205 "turn/completed",
206 "item/tool/requestUserInput",
207 "serverRequest/resolved",
208 "item/agentMessage/delta",
209 ],
210 turnStartCount: 1,
211 turnCompletedCount: 1,
212 approvalRequestCount: 0,
213 },
214 proposed_plan: {
215 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
216 incoming: ["turn/started", "turn/completed", "item/plan/delta"],
217 turnStartCount: 1,
218 turnCompletedCount: 1,
219 approvalRequestCount: 0,
220 },
221 provider_thread_resume: {
222 outgoing: ["initialize", "initialized", "thread/start", "thread/resume", "turn/start"],
223 incoming: ["thread/started", "turn/started", "turn/completed", "item/agentMessage/delta"],
224 turnStartCount: 2,
225 turnCompletedCount: 2,
226 approvalRequestCount: 0,
227 },
228 queued_turn: {
229 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
230 incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
231 turnStartCount: 2,
232 turnCompletedCount: 2,
233 approvalRequestCount: 0,
234 },
235 message_steering: {
236 outgoing: ["initialize", "initialized", "thread/start", "turn/start", "turn/steer"],
237 incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
238 turnStartCount: 1,
239 turnCompletedCount: 1,
240 approvalRequestCount: 0,
241 },
242 turn_interrupt: {
243 outgoing: ["initialize", "initialized", "thread/start", "turn/start", "turn/interrupt"],
244 incoming: ["turn/started", "turn/completed"],
245 turnStartCount: 1,
246 turnCompletedCount: 1,
247 approvalRequestCount: 0,
248 },
249 command_output_streaming: {
250 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
251 incoming: [
252 "turn/started",
253 "item/started",
254 "item/commandExecution/outputDelta",
255 "item/completed",
256 "turn/completed",
257 ],
258 turnStartCount: 1,
259 turnCompletedCount: 1,
260 approvalRequestCount: 0,
261 },
262 turn_interrupt_mid_tool: {
263 outgoing: [
264 "initialize",
265 "initialized",
266 "thread/start",
267 "turn/start",
268 "turn/interrupt",
269 "thread/backgroundTerminals/terminate",
270 ],
271 incoming: ["turn/started", "item/started", "turn/completed"],
272 turnStartCount: 1,
273 turnCompletedCount: 1,
274 approvalRequestCount: 0,
275 },
276 thread_rollback: {
277 outgoing: [
278 "initialize",
279 "initialized",
280 "thread/start",
281 "turn/start",
282 "thread/read",
283 "thread/turns/list",
284 "thread/revert",
285 ],
286 incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
287 turnStartCount: 3,
288 turnCompletedCount: 3,
289 approvalRequestCount: 0,
290 },
291 thread_rollback_after_restart: {
292 outgoing: [
293 "initialize",
294 "initialized",
295 "thread/start",
296 "turn/start",
297 "thread/read",
298 "thread/resume",
299 "thread/turns/list",
300 "thread/revert",
301 ],
302 incoming: ["turn/started", "turn/completed", "item/agentMessage/delta", "thread/reverted"],
303 turnStartCount: 3,
304 turnCompletedCount: 3,
305 approvalRequestCount: 0,
306 },
307 thread_rollback_to_stopped_turn: {
308 outgoing: [
309 "initialize",
310 "initialized",
311 "thread/start",
312 "turn/start",
313 "turn/interrupt",
314 "thread/backgroundTerminals/terminate",
315 "thread/read",
316 "thread/turns/list",
317 "thread/revert",
318 ],
319 incoming: ["turn/started", "item/started", "turn/completed", "thread/reverted"],
320 turnStartCount: 4,
321 turnCompletedCount: 4,
322 approvalRequestCount: 0,
323 },
324 thread_fork_native_continue: {
325 outgoing: ["initialize", "initialized", "thread/start", "thread/fork", "turn/start"],
326 incoming: ["thread/started", "turn/started", "turn/completed", "item/agentMessage/delta"],
327 turnStartCount: 3,
328 turnCompletedCount: 3,
329 approvalRequestCount: 0,
330 },
331 thread_fork_native_siblings: {
332 outgoing: ["initialize", "initialized", "thread/start", "thread/fork", "turn/start"],
333 incoming: ["thread/started", "turn/started", "turn/completed", "item/agentMessage/delta"],
334 turnStartCount: 3,
335 turnCompletedCount: 3,
336 approvalRequestCount: 0,
337 },
338 thread_merge_back_continue: {
339 outgoing: ["initialize", "initialized", "thread/start", "thread/fork", "turn/start"],
340 incoming: ["thread/started", "turn/started", "turn/completed", "item/agentMessage/delta"],
341 turnStartCount: 4,
342 turnCompletedCount: 4,
343 approvalRequestCount: 0,
344 },
345 thread_merge_back_siblings: {
346 outgoing: ["initialize", "initialized", "thread/start", "thread/fork", "turn/start"],
347 incoming: ["thread/started", "turn/started", "turn/completed", "item/agentMessage/delta"],
348 turnStartCount: 6,
349 turnCompletedCount: 6,
350 approvalRequestCount: 0,
351 },
352 todo_list: {
353 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
354 incoming: ["turn/started", "turn/completed", "turn/plan/updated", "item/agentMessage/delta"],
355 turnStartCount: 1,
356 turnCompletedCount: 1,
357 approvalRequestCount: 0,
358 },
359 web_search: {
360 outgoing: ["initialize", "initialized", "thread/start", "turn/start"],
361 incoming: ["turn/started", "turn/completed", "item/agentMessage/delta"],
362 turnStartCount: 1,
363 turnCompletedCount: 1,
364 approvalRequestCount: 0,
365 },
366} as const;
367​
368const decodeCodexTranscript = Schema.decodeUnknownEffect(
369 CodexReplay.CodexAppServerReplayTranscript,
370);
371const readTranscript = Effect.fn("readCodexReplayFixture")(function* (file: URL) {
372 return yield* readProviderReplayTranscript(file);
373}, Effect.provide(NodeServices.layer));
374​
375function labels(
376 transcript: ProviderReplayTranscript,
377 type: "expect_outbound" | "emit_inbound",
378): ReadonlyArray<string> {
379 return transcript.entries.flatMap((entry) => {
380 if (entry.type !== type || entry.label === undefined) {
381 return [];
382 }
383 return [entry.label];
384 });
386​
387function countLabel(
388 transcript: ProviderReplayTranscript,
389 type: "expect_outbound" | "emit_inbound",
390 label: string,
391) {
392 return labels(transcript, type).filter((entryLabel) => entryLabel === label).length;
394​
395function countApprovalRequests(transcript: ProviderReplayTranscript) {
396 return labels(transcript, "emit_inbound").filter((label) => label.endsWith("/requestApproval"))
397 .length;
399​
400function isRecord(value: unknown): value is Record<string, unknown> {
401 return typeof value === "object" && value !== null && !Array.isArray(value);
403​
404function readPath(value: unknown, path: ReadonlyArray<string | number>): unknown {
405 let current = value;
406 for (const segment of path) {
407 if (typeof segment === "number") {
408 if (!Array.isArray(current)) {
409 throw new Error(`Expected array while reading ${path.join(".")}.`);
410 }
411 current = current[segment];
412 continue;
413 }
414​
415 if (!isRecord(current)) {
416 throw new Error(`Expected object while reading ${path.join(".")}.`);
417 }
418 current = current[segment];
419 }
420 return current;
422​
423function readString(value: unknown, path: ReadonlyArray<string | number>): string {
424 const current = readPath(value, path);
425 if (typeof current !== "string") {
426 throw new Error(`Expected string at ${path.join(".")}.`);
427 }
428 return current;
430​
431function readArray(value: unknown, path: ReadonlyArray<string | number>): ReadonlyArray<unknown> {
432 const current = readPath(value, path);
433 if (!Array.isArray(current)) {
434 throw new Error(`Expected array at ${path.join(".")}.`);
435 }
436 return current;
438​
439function findProtocolEntry(
440 transcript: ProviderReplayTranscript,
441 type: "expect_outbound" | "emit_inbound",
442 label: string,
443 occurrence = 0,
444): ProtocolReplayEntry {
445 const matches = transcript.entries.filter(
446 (entry): entry is ProtocolReplayEntry => entry.type === type && entry.label === label,
447 );
448 const entry = matches[occurrence];
449 if (!entry) {
450 throw new Error(`Missing ${type} ${label} occurrence ${occurrence}.`);
451 }
452 return entry;
454​
455function agentMessageTexts(transcript: ProviderReplayTranscript): ReadonlyArray<string> {
456 return transcript.entries.flatMap((entry) => {
457 if (entry.type !== "emit_inbound" || entry.label !== "item/completed") {
458 return [];
459 }
460​
461 const item = readPath(entry.frame, ["params", "item"]);
462 if (!isRecord(item) || item.type !== "agentMessage" || typeof item.text !== "string") {
463 return [];
464 }
465 return [item.text];
466 });
468​
469function assertScenarioExpectations(transcript: ProviderReplayTranscript) {
470 const expectation =
471 scenarioExpectations[transcript.scenario as keyof typeof scenarioExpectations];
472 const outgoingLabels = labels(transcript, "expect_outbound");
473 const incomingLabels = labels(transcript, "emit_inbound");
474​
475 assert.isDefined(expectation, `missing scenario expectation for ${transcript.scenario}`);
476 for (const label of expectation.outgoing) {
477 assert.include(outgoingLabels, label, `${transcript.scenario} missing outgoing ${label}`);
478 }
479 for (const label of expectation.incoming) {
480 assert.include(incomingLabels, label, `${transcript.scenario} missing incoming ${label}`);
481 }
482​
483 assert.equal(countLabel(transcript, "expect_outbound", "turn/start"), expectation.turnStartCount);
484 assert.equal(
485 countLabel(transcript, "emit_inbound", "turn/completed"),
486 expectation.turnCompletedCount,
487 );
488 assert.equal(countApprovalRequests(transcript), expectation.approvalRequestCount);
490​
491function assertProviderThreadResumeSemantics(transcript: ProviderReplayTranscript) {
492 if (transcript.scenario !== "provider_thread_resume") {
493 return;
494 }
495​
496 const startThreadId = readString(
497 findProtocolEntry(transcript, "emit_inbound", "thread/start").frame,
498 ["result", "thread", "id"],
499 );
500 const resumeRequestedThreadId = readString(
501 findProtocolEntry(transcript, "expect_outbound", "thread/resume").frame,
502 ["params", "threadId"],
503 );
504 const resumeRequest = findProtocolEntry(transcript, "expect_outbound", "thread/resume").frame;
505 const resumedThreadFrame = findProtocolEntry(transcript, "emit_inbound", "thread/resume").frame;
506 const resumedThreadId = readString(resumedThreadFrame, ["result", "thread", "id"]);
507 const secondTurnThreadId = readString(
508 findProtocolEntry(transcript, "expect_outbound", "turn/start", 1).frame,
509 ["params", "threadId"],
510 );
511 const texts = agentMessageTexts(transcript);
512 const secondFinalText = texts[1] ?? "";
513​
514 assert.equal(
515 resumeRequestedThreadId,
516 startThreadId,
517 "thread/resume must request the provider thread created by thread/start",
518 );
519 assert.equal(
520 resumedThreadId,
521 startThreadId,
522 "thread/resume must return the same provider thread id",
523 );
524 assert.equal(
525 secondTurnThreadId,
526 startThreadId,
527 "turn after resume must run on the resumed provider thread",
528 );
529 // The adapter resumes with excludeTurns, so history reaches the model, not the response.
530 assert.equal(readPath(resumeRequest, ["params", "excludeTurns"]), true);
531 assert.lengthOf(readArray(resumedThreadFrame, ["result", "thread", "turns"]), 0);
532 assert.equal(texts[0], PROVIDER_THREAD_RESUME_FIRST_FINAL);
533 assert.include(
534 secondFinalText,
535 PROVIDER_THREAD_RESUME_FIRST_FINAL,
536 "second turn must demonstrate access to resumed conversation history",
537 );
538 assert.include(
539 secondFinalText,
540 PROVIDER_THREAD_RESUME_SECOND_FINAL,
541 "second turn must include its own completion marker",
542 );
544​
545function assertContinuedForkSemantics(transcript: ProviderReplayTranscript) {
546 if (transcript.scenario !== "thread_fork_native_continue") {
547 return;
548 }
549​
550 const sourceThreadId = readString(
551 findProtocolEntry(transcript, "emit_inbound", "thread/start").frame,
552 ["result", "thread", "id"],
553 );
554 const forkRequestThreadId = readString(
555 findProtocolEntry(transcript, "expect_outbound", "thread/fork").frame,
556 ["params", "threadId"],
557 );
558 const forkThreadId = readString(
559 findProtocolEntry(transcript, "emit_inbound", "thread/fork").frame,
560 ["result", "thread", "id"],
561 );
562 const firstForkTurnThreadId = readString(
563 findProtocolEntry(transcript, "expect_outbound", "turn/start", 1).frame,
564 ["params", "threadId"],
565 );
566 const secondForkTurnThreadId = readString(
567 findProtocolEntry(transcript, "expect_outbound", "turn/start", 2).frame,
568 ["params", "threadId"],
569 );
570 const recallPrompt = readString(
571 findProtocolEntry(transcript, "expect_outbound", "turn/start", 2).frame,
572 ["params", "input", 0, "text"],
573 );
574​
575 assert.equal(forkRequestThreadId, sourceThreadId);
576 assert.notEqual(forkThreadId, sourceThreadId);
577 assert.equal(firstForkTurnThreadId, forkThreadId);
578 assert.equal(secondForkTurnThreadId, forkThreadId);
579 assert.notInclude(recallPrompt, THREAD_FORK_NATIVE_CONTINUE_SOURCE_MARKER);
580 assert.notInclude(recallPrompt, THREAD_FORK_NATIVE_CONTINUE_FORK_MARKER);
581 const texts = agentMessageTexts(transcript);
582 for (const expected of [
583 "source marker stored",
584 "fork marker stored",
585 THREAD_FORK_NATIVE_CONTINUE_RECALL,
586 ]) {
587 assert.include(texts, expected);
588 }
589 assert.equal(
590 texts.at(-1),
591 THREAD_FORK_NATIVE_CONTINUE_RECALL,
592 "the second fork-local turn must recall both the inherited source marker and fork-local marker",
593 );
595​
596function assertSiblingForkSemantics(transcript: ProviderReplayTranscript) {
597 if (transcript.scenario !== "thread_fork_native_siblings") {
598 return;
599 }
600​
601 const sourceThreadId = readString(
602 findProtocolEntry(transcript, "emit_inbound", "thread/start").frame,
603 ["result", "thread", "id"],
604 );
605 const firstForkFrame = findProtocolEntry(transcript, "emit_inbound", "thread/fork", 0).frame;
606 const secondForkFrame = findProtocolEntry(transcript, "emit_inbound", "thread/fork", 1).frame;
607 const firstForkId = readString(firstForkFrame, ["result", "thread", "id"]);
608 const secondForkId = readString(secondForkFrame, ["result", "thread", "id"]);
609 const firstForkParentId = readString(firstForkFrame, ["result", "thread", "forkedFromId"]);
610 const secondForkParentId = readString(secondForkFrame, ["result", "thread", "forkedFromId"]);
611 const firstForkTurnThreadId = readString(
612 findProtocolEntry(transcript, "expect_outbound", "turn/start", 1).frame,
613 ["params", "threadId"],
614 );
615 const secondForkTurnThreadId = readString(
616 findProtocolEntry(transcript, "expect_outbound", "turn/start", 2).frame,
617 ["params", "threadId"],
618 );
619 const texts = agentMessageTexts(transcript);
620 const firstRecall = texts[1]?.replace(/\s*\|\s*/u, "|") ?? "";
621 const secondRecall = texts[2]?.replace(/\s*\|\s*/u, "|") ?? "";
622​
623 assert.equal(firstForkParentId, sourceThreadId);
624 assert.equal(secondForkParentId, sourceThreadId);
625 assert.notEqual(firstForkId, secondForkId);
626 assert.equal(firstForkTurnThreadId, firstForkId);
627 assert.equal(secondForkTurnThreadId, secondForkId);
628 assert.equal(firstRecall, "sibling-source-8R3D|sibling-first-5L2P");
629 assert.notInclude(firstRecall, "sibling-second-9N6C");
630 assert.equal(secondRecall, "sibling-source-8R3D|sibling-second-9N6C");
631 assert.notInclude(secondRecall, "sibling-first-5L2P");
633​
634function assertMergeBackSemantics(transcript: ProviderReplayTranscript) {
635 if (transcript.scenario !== "thread_merge_back_continue") {
636 return;
637 }
638​
639 const sourceThreadId = readString(
640 findProtocolEntry(transcript, "emit_inbound", "thread/start").frame,
641 ["result", "thread", "id"],
642 );
643 const forkThreadId = readString(
644 findProtocolEntry(transcript, "emit_inbound", "thread/fork").frame,
645 ["result", "thread", "id"],
646 );
647 const mergeThreadId = readString(
648 findProtocolEntry(transcript, "expect_outbound", "turn/start", 2).frame,
649 ["params", "threadId"],
650 );
651 const recallFrame = findProtocolEntry(transcript, "expect_outbound", "turn/start", 3).frame;
652 const recallThreadId = readString(recallFrame, ["params", "threadId"]);
653 const recallPrompt = readString(recallFrame, ["params", "input", 0, "text"]);
654 const texts = agentMessageTexts(transcript);
655​
656 assert.notEqual(forkThreadId, sourceThreadId);
657 assert.equal(mergeThreadId, sourceThreadId);
658 assert.equal(recallThreadId, sourceThreadId);
659 assert.notInclude(recallPrompt, THREAD_MERGE_BACK_SOURCE_MARKER);
660 assert.notInclude(recallPrompt, THREAD_MERGE_BACK_FORK_MARKER);
661 assert.equal(texts.at(-1)?.replace(/\s*\|\s*/u, "|"), THREAD_MERGE_BACK_RECALL);
663​
664function assertSiblingMergeBackSemantics(transcript: ProviderReplayTranscript) {
665 if (transcript.scenario !== "thread_merge_back_siblings") {
666 return;
667 }
668​
669 const sourceThreadId = readString(
670 findProtocolEntry(transcript, "emit_inbound", "thread/start").frame,
671 ["result", "thread", "id"],
672 );
673 const firstForkId = readString(
674 findProtocolEntry(transcript, "emit_inbound", "thread/fork", 0).frame,
675 ["result", "thread", "id"],
676 );
677 const secondForkId = readString(
678 findProtocolEntry(transcript, "emit_inbound", "thread/fork", 1).frame,
679 ["result", "thread", "id"],
680 );
681 const firstMergeThreadId = readString(
682 findProtocolEntry(transcript, "expect_outbound", "turn/start", 3).frame,
683 ["params", "threadId"],
684 );
685 const secondMergeThreadId = readString(
686 findProtocolEntry(transcript, "expect_outbound", "turn/start", 4).frame,
687 ["params", "threadId"],
688 );
689 const recallFrame = findProtocolEntry(transcript, "expect_outbound", "turn/start", 5).frame;
690 const recallPrompt = readString(recallFrame, ["params", "input", 0, "text"]);
691 const finalText = agentMessageTexts(transcript)
692 .at(-1)
693 ?.replace(/\s*\|\s*/gu, "|");
694​
695 assert.notEqual(firstForkId, secondForkId);
696 assert.equal(firstMergeThreadId, sourceThreadId);
697 assert.equal(secondMergeThreadId, sourceThreadId);
698 assert.notInclude(recallPrompt, THREAD_MERGE_BACK_SIBLINGS_SOURCE_MARKER);
699 assert.notInclude(recallPrompt, THREAD_MERGE_BACK_SIBLINGS_FIRST_MARKER);
700 assert.notInclude(recallPrompt, THREAD_MERGE_BACK_SIBLINGS_SECOND_MARKER);
701 assert.equal(finalText, THREAD_MERGE_BACK_SIBLINGS_RECALL);
703​
704/**
705 * Codex announces a v2 child with the parent's `subAgentActivity(started)`
706 * before the child's first `turn/started`; the adapter registers children
707 * from that activity.
708 */
709function assertSubagentActivityPrecedesChildTurns(transcript: ProviderReplayTranscript) {
710 if (transcript.scenario !== "subagent_v2" && transcript.scenario !== "subagent_v2_nested") {
711 return;
712 }
713​
714 const announcedChildren = new Set<string>();
715 const startedChildren = new Set<string>();
716 const rootThreadId = readString(
717 findProtocolEntry(transcript, "emit_inbound", "thread/start").frame,
718 ["result", "thread", "id"],
719 );
720 for (const entry of transcript.entries) {
721 if (entry.type !== "emit_inbound") continue;
722 const method = readPath(entry.frame, ["method"]);
723 if (method === "item/started") {
724 const item = readPath(entry.frame, ["params", "item"]);
725 if (isRecord(item) && item.type === "subAgentActivity" && item.kind === "started") {
726 announcedChildren.add(readString(item, ["agentThreadId"]));
727 }
728 }
729 if (method === "turn/started") {
730 const threadId = readString(entry.frame, ["params", "threadId"]);
731 if (threadId === rootThreadId) continue;
732 assert.isTrue(
733 announcedChildren.has(threadId),
734 `${transcript.scenario}: child ${threadId} started a turn before its subAgentActivity`,
735 );
736 startedChildren.add(threadId);
737 }
738 }
739 assert.equal(
740 startedChildren.size,
741 transcript.scenario === "subagent_v2" ? 1 : 3,
742 `${transcript.scenario}: unexpected number of child turns`,
743 );
745​
746describe("Codex replay fixtures", () => {
747 it.effect("loads each canonical Codex fixture as an app-server replay transcript", () =>
748 Effect.gen(function* () {
749 for (const fixture of CODEX_REPLAY_TRANSCRIPTS) {
750 const transcript = yield* readTranscript(fixture.transcriptFile);
751 const codexTranscript = yield* decodeCodexTranscript(transcript);
752 const first = transcript.entries[0];
753​
754 assert.equal(codexTranscript.provider, "codex");
755 assert.equal(codexTranscript.protocol, "codex.app-server");
756 assert.equal(codexTranscript.scenario, fixture.recordedScenario);
757 assert.deepEqual(codexTranscript.entries.at(-1), {
758 type: "runtime_exit",
759 status: "success",
760 });
761 assert.equal(first?.type, "expect_outbound");
762 if (first?.type !== "expect_outbound") {
763 throw new Error(
764 `Expected ${fixture.recordedScenario} to start with initialize outbound frame.`,
765 );
766 }
767 assert.equal(first.label, "initialize");
768​
769 assertScenarioExpectations(transcript);
770 assertProviderThreadResumeSemantics(transcript);
771 assertContinuedForkSemantics(transcript);
772 assertSiblingForkSemantics(transcript);
773 assertMergeBackSemantics(transcript);
774 assertSiblingMergeBackSemantics(transcript);
775 assertSubagentActivityPrecedesChildTurns(transcript);
776 }
777 }),
778 );
779​
780 it("covers the expected replay suite exactly", () => {
781 assert.deepEqual(
782 CODEX_REPLAY_TRANSCRIPTS.map((fixture) => fixture.recordedScenario).toSorted(),
783 Object.keys(scenarioExpectations).toSorted(),
784 );
785 });
786});