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