Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import type { OrchestrationV2DomainEvent, ProviderReplayTranscript } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Path from "effect/Path";
7
8import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
9import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
10import { readProviderReplayTranscript } from "@t3tools/provider-testing/replayTranscript";
11import { provideDeterministicTestRuntime } from "./DeterministicRuntime.ts";
12import { ORCHESTRATOR_REPLAY_FIXTURES } from "./fixtures/index.ts";
13import {
14 assertProviderNativeSubagentRootTurns,
15 materializeFixtureInput,
16 type OrchestratorFixtureInput,
17 type ProviderOrchestratorReplayVariant,
18} from "./fixtures/shared.ts";
19import {
20 runOrchestratorV2ProviderReplayScenario,
21 type OrchestratorV2ProviderReplayHarness,
22} from "./ProviderReplayHarness.ts";
23import { materializeReplayTranscriptRuntimeInstructions } from "./ReplayRuntimeInstructions.ts";
24
25// Each driver's fixtures run from its own <Provider>ReplayFixtures.integration.test.ts,
26// so a focused run loads one adapter. A fixture for a driver missing here would
27// silently never run, so loading this module fails instead.
28const DRIVERS_WITH_REPLAY_FIXTURE_FILES = new Set([
29 "acpRegistry",
30 "claudeAgent",
31 "codex",
32 "cursor",
33 "fx",
34 "grok",
35 "muse",
36 "opencode",
37 "pi",
38]);
39for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) {
40 for (const provider of fixture.providers) {
41 if (!DRIVERS_WITH_REPLAY_FIXTURE_FILES.has(provider.driver)) {
42 throw new Error(
43 `${fixture.name}/${provider.driver} has no ReplayFixtures test file to run it.`,
44 );
45 }
46 }
47}
48
49export const readReplayFixtureTranscript = Effect.fn("readOrchestratorReplayTranscript")(function* (
50 file: URL,
51) {
52 return yield* readProviderReplayTranscript(file);
53}, Effect.provide(NodeServices.layer));
54
55function normalizeTestError(cause: unknown): Error {
56 return cause instanceof Error ? cause : new Error(String(cause));
57}
58
59function transcriptEntriesThroughLabel(
60 transcript: ProviderReplayTranscript,
61 label: string | undefined,
62): ProviderReplayTranscript {
63 if (label === undefined) {
64 return transcript;
65 }
66 const entryIndex = transcript.entries.findIndex(
67 (entry) => entry.type === "emit_inbound" && entry.label === label,
68 );
69 if (entryIndex === -1) {
70 throw new Error(`${transcript.scenario} is missing inbound transcript label ${label}.`);
71 }
72 return {
73 ...transcript,
74 entries: transcript.entries.slice(0, entryIndex + 1),
75 };
76}
77
78function isStreamingAssistantEvent(event: OrchestrationV2DomainEvent): boolean {
79 switch (event.type) {
80 case "node.updated":
81 return event.payload.kind === "assistant_message" && event.payload.status === "running";
82 case "message.updated":
83 return event.payload.role === "assistant" && event.payload.streaming;
84 case "turn-item.updated":
85 return event.payload.type === "assistant_message" && event.payload.streaming;
86 default:
87 return false;
88 }
89}
90
91export interface ReplayFixtureCase {
92 readonly fixtureName: string;
93 readonly buildInput: () => OrchestratorFixtureInput;
94 readonly driver: ProviderOrchestratorReplayVariant;
95 readonly transformTranscript?: (transcript: ProviderReplayTranscript) => ProviderReplayTranscript;
96}
97
98export interface ReplayFixtureRun<
99 Transcript extends ProviderReplayTranscript,
100 Error,
101 WorkspaceError = never,
102> extends ReplayFixtureCase {
103 readonly harness: OrchestratorV2ProviderReplayHarness<Transcript, Error>;
104 /** Rewrites recorded workspace paths to the replay workspace, for drivers that record them. */
105 readonly materializeWorkspace?: (
106 transcript: ProviderReplayTranscript,
107 workspace: string,
108 ) => Effect.Effect<ProviderReplayTranscript, WorkspaceError>;
109}
110
111const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* <
112 Transcript extends ProviderReplayTranscript,
113 Error,
114 WorkspaceError,
115>(input: ReplayFixtureRun<Transcript, Error, WorkspaceError>) {
116 const recordedTranscript = yield* readReplayFixtureTranscript(input.driver.transcriptFile);
117 const rawTranscript = input.transformTranscript?.(recordedTranscript) ?? recordedTranscript;
118 const replayTranscript = materializeReplayTranscriptRuntimeInstructions(
119 transcriptEntriesThroughLabel(rawTranscript, input.driver.transcriptEntriesThroughLabel),
120 { driver: input.driver.driver, model: input.driver.modelSelection.model },
121 );
122 const fixtureInput = input.buildInput();
123 const workspace = yield* checkpointWorkspace(input.fixtureName, fixtureInput.workspaceFiles);
124 const transcript = yield* input.harness.decodeTranscript(
125 input.materializeWorkspace === undefined
126 ? replayTranscript
127 : yield* input.materializeWorkspace(replayTranscript, workspace),
128 );
129 const materialized = yield* materializeFixtureInput({
130 scenario: input.fixtureName,
131 fixtureInput,
132 driver: input.driver.driver,
133 modelSelection: input.driver.modelSelection,
134 }).pipe(Effect.provide(IdAllocator.layer), provideDeterministicTestRuntime);
135 const scenario = {
136 name: `${input.fixtureName}/${input.driver.driver}`,
137 transcript,
138 commands: materialized.commands,
139 steps: materialized.steps,
140 projectionThreadIds: materialized.projectionThreadIds,
141 runtimePolicyOverride: {
142 ...input.driver.runtimePolicyOverride,
143 cwd: workspace,
144 },
145 };
146
147 const result = yield* runOrchestratorV2ProviderReplayScenario(
148 scenario,
149 input.harness,
150 input.driver.runContinuationWorker === true ? { runContinuationWorker: true } : {},
151 ).pipe(provideDeterministicTestRuntime);
152 input.driver.assertOutput(result, transcript);
153 assertProviderNativeSubagentRootTurns(result);
154 const expectedAbsentWorkspacePaths = input.driver.expectedAbsentWorkspacePaths;
155 if (expectedAbsentWorkspacePaths !== undefined) {
156 yield* Effect.gen(function* () {
157 const fs = yield* FileSystem.FileSystem;
158 const path = yield* Path.Path;
159 for (const relativePath of expectedAbsentWorkspacePaths) {
160 assert.isFalse(
161 yield* fs.exists(path.join(workspace, relativePath)),
162 `${input.fixtureName}/${input.driver.driver} must not create ${relativePath} in the replay workspace`,
163 );
164 }
165 }).pipe(Effect.provide(NodeServices.layer));
166 }
167 assert.isFalse(
168 result.domainEvents.some(isStreamingAssistantEvent),
169 "buffered delivery must not persist streaming assistant artifacts",
170 );
171 const projectionThreadId = materialized.projectionThreadIds[0];
172 assert.isDefined(projectionThreadId);
173 const projection = result.projections.get(projectionThreadId);
174 assert.isDefined(projection);
175 const latestRun = projection.runs.at(-1);
176 assert.deepEqual(latestRun?.modelSelection, input.driver.modelSelection);
177 if (projection.runs.some((run) => run.status === "completed")) {
178 const threadStartCheckpoint = projection.checkpoints.find(
179 (checkpoint) => checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null,
180 );
181 assert.isDefined(
182 threadStartCheckpoint,
183 "completed threads must retain an addressable thread-start checkpoint",
184 );
185 assert.equal(threadStartCheckpoint.status, "ready");
186 }
187 return result;
188});
189
190/** Replays one fixture variant through OrchestratorV2 and runs the shared output checks. */
191export function runReplayFixture<
192 Transcript extends ProviderReplayTranscript,
193 Error,
194 WorkspaceError = never,
195>(input: ReplayFixtureRun<Transcript, Error, WorkspaceError>) {
196 return runFixtureProvider(input).pipe(Effect.mapError(normalizeTestError), Effect.scoped);
197}
198
199export function findReplayFixture(name: string) {
200 return ORCHESTRATOR_REPLAY_FIXTURES.find((fixture) => fixture.name === name);
201}
202
203/**
204 * Registers one test per recorded fixture variant of `driver`. Call it inside the
205 * provider file's `describe`. `run` picks the harness for each variant.
206 */
207export function itRunsReplayFixtures<E>(
208 driver: string,
209 run: (input: ReplayFixtureCase) => Effect.Effect<unknown, E>,
210) {
211 it.effect.each(
212 ORCHESTRATOR_REPLAY_FIXTURES.flatMap((fixture) =>
213 fixture.providers
214 .filter((provider) => provider.driver === driver)
215 .map((provider) => [fixture.name, provider.driver, fixture, provider] as const),
216 ),
217 )("runs %s/%s through OrchestratorV2 using deterministic replay", ([, , fixture, provider]) =>
218 run({ fixtureName: fixture.name, buildInput: fixture.buildInput, driver: provider }),
219 );
220}