Open History to see the last commit
1import fs from "node:fs";
2import os from "node:os";
3import path from "node:path";
4import { execFileSync } from "node:child_process";
5
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import {
8 ApprovalRequestId,
9 type OrchestrationEvent,
10 type OrchestrationThread,
11} from "@t3tools/contracts";
12import {
13 Effect,
14 Exit,
15 Layer,
16 ManagedRuntime,
17 Option,
18 Schedule,
19 Schema,
20 Scope,
21 Stream,
22} from "effect";
23
24import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
25import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
26import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
27import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
28import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
29import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts";
30import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
31import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
32import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
33import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
34import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
35import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
36import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
37import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
38import { ProviderService } from "../src/provider/Services/ProviderService.ts";
39import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
40import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
41import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
42import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
43import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
44import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
45import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
46import {
47 OrchestrationEngineService,
48 type OrchestrationEngineShape,
49} from "../src/orchestration/Services/OrchestrationEngine.ts";
50import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
51import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
52
53import {
54 makeTestProviderAdapterHarness,
55 type TestProviderAdapterHarness,
56} from "./TestProviderAdapter.integration.ts";
57
58function runGit(cwd: string, args: ReadonlyArray<string>) {
59 return execFileSync("git", args, {
60 cwd,
61 stdio: ["ignore", "pipe", "pipe"],
62 encoding: "utf8",
63 });
64}
65
66function initializeGitWorkspace(cwd: string) {
67 runGit(cwd, ["init", "--initial-branch=main"]);
68 runGit(cwd, ["config", "user.email", "test@example.com"]);
69 runGit(cwd, ["config", "user.name", "Test User"]);
70 fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
71 runGit(cwd, ["add", "."]);
72 runGit(cwd, ["commit", "-m", "Initial"]);
73}
74
75export function gitRefExists(cwd: string, ref: string): boolean {
76 try {
77 runGit(cwd, ["show-ref", "--verify", "--quiet", ref]);
78 return true;
79 } catch {
80 return false;
81 }
82}
83
84export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
85 return runGit(cwd, ["show", `${ref}:${filePath}`]);
86}
87
88class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()(
89 "WaitForTimeoutError",
90 {
91 description: Schema.String,
92 },
93) {}
94
95function waitFor<A, E>(
96 read: Effect.Effect<A, E>,
97 predicate: (value: A) => boolean,
98 description: string,
99 timeoutMs?: number,
100): Effect.Effect<A, never>;
101function waitFor<A, B extends A, E>(
102 read: Effect.Effect<A, E>,
103 predicate: (value: A) => value is B,
104 description: string,
105 timeoutMs?: number,
106): Effect.Effect<B, never>;
107function waitFor<A, E>(
108 read: Effect.Effect<A, E>,
109 predicate: (value: A) => boolean,
110 description: string,
111 timeoutMs = 3000,
112): Effect.Effect<A, never> {
113 const RETRY_SIGNAL = "wait_for_retry";
114 const retryIntervalMs = 10;
115 const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
116 const retrySchedule = Schedule.spaced(`${retryIntervalMs} millis`);
117
118 return read.pipe(
119 Effect.filterOrFail(predicate, () => RETRY_SIGNAL),
120 Effect.retry({
121 schedule: retrySchedule,
122 times: maxRetries,
123 while: (error) => error === RETRY_SIGNAL,
124 }),
125 Effect.mapError((error) =>
126 error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error,
127 ),
128 Effect.orDie,
129 );
130}
131
132class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<OrchestrationHarnessRuntimeError>()(
133 "OrchestrationHarnessRuntimeError",
134 {
135 operation: Schema.String,
136 cause: Schema.optional(Schema.Defect),
137 },
138) {}
139
140const tryRuntimePromise = <A>(operation: string, run: () => Promise<A>) =>
141 Effect.tryPromise({
142 try: run,
143 catch: (cause) => new OrchestrationHarnessRuntimeError({ operation, cause }),
144 });
145
146export interface OrchestrationIntegrationHarness {
147 readonly rootDir: string;
148 readonly workspaceDir: string;
149 readonly dbPath: string;
150 readonly adapterHarness: TestProviderAdapterHarness;
151 readonly engine: OrchestrationEngineShape;
152 readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
153 readonly providerService: ProviderService["Service"];
154 readonly checkpointStore: CheckpointStore["Service"];
155 readonly checkpointRepository: ProjectionCheckpointRepository["Service"];
156 readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];
157 readonly waitForThread: (
158 threadId: string,
159 predicate: (thread: OrchestrationThread) => boolean,
160 timeoutMs?: number,
161 ) => Effect.Effect<OrchestrationThread, never>;
162 readonly waitForDomainEvent: (
163 predicate: (event: OrchestrationEvent) => boolean,
164 timeoutMs?: number,
165 ) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
166 readonly waitForPendingApproval: (
167 requestId: string,
168 predicate: (row: {
169 readonly status: "pending" | "resolved";
170 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
171 readonly resolvedAt: string | null;
172 }) => boolean,
173 timeoutMs?: number,
174 ) => Effect.Effect<
175 {
176 readonly status: "pending" | "resolved";
177 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
178 readonly resolvedAt: string | null;
179 },
180 never
181 >;
182 readonly dispose: Effect.Effect<void, never>;
183}
184
185export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
186 const sleep = (ms: number) => Effect.sleep(ms);
187 const adapterHarness = yield* makeTestProviderAdapterHarness;
188
189 const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
190 const workspaceDir = path.join(rootDir, "workspace");
191 const stateDir = path.join(rootDir, "state");
192 const dbPath = path.join(stateDir, "state.sqlite");
193 fs.mkdirSync(workspaceDir, { recursive: true });
194 fs.mkdirSync(stateDir, { recursive: true });
195 initializeGitWorkspace(workspaceDir);
196
197 const registry: typeof ProviderAdapterRegistry.Service = {
198 getByProvider: (provider) =>
199 provider === "codex"
200 ? Effect.succeed(adapterHarness.adapter)
201 : Effect.fail(new ProviderUnsupportedError({ provider })),
202 listProviders: () => Effect.succeed(["codex"]),
203 };
204
205 const persistenceLayer = makeSqlitePersistenceLive(dbPath);
206 const orchestrationLayer = OrchestrationEngineLive.pipe(
207 Layer.provide(OrchestrationProjectionPipelineLive),
208 Layer.provide(OrchestrationEventStoreLive),
209 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
210 );
211 const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
212 Layer.provide(ProviderSessionRuntimeRepositoryLive),
213 );
214 const providerLayer = makeProviderServiceLive().pipe(
215 Layer.provide(providerSessionDirectoryLayer),
216 Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
217 );
218 const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer));
219
220 const runtimeServicesLayer = Layer.mergeAll(
221 orchestrationLayer,
222 OrchestrationProjectionSnapshotQueryLive,
223 ProjectionCheckpointRepositoryLive,
224 ProjectionPendingApprovalRepositoryLive,
225 checkpointStoreLayer,
226 providerLayer,
227 );
228 const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
229 Layer.provideMerge(runtimeServicesLayer),
230 );
231 const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
232 Layer.provideMerge(runtimeServicesLayer),
233 );
234 const checkpointReactorLayer = CheckpointReactorLive.pipe(
235 Layer.provideMerge(runtimeServicesLayer),
236 );
237 const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
238 Layer.provideMerge(runtimeIngestionLayer),
239 Layer.provideMerge(providerCommandReactorLayer),
240 Layer.provideMerge(checkpointReactorLayer),
241 );
242 const layer = orchestrationReactorLayer.pipe(
243 Layer.provide(persistenceLayer),
244 Layer.provideMerge(NodeServices.layer),
245 );
246
247 const runtime = ManagedRuntime.make(layer);
248 const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
249 runtime.runPromise(Effect.service(OrchestrationEngineService)),
250 ).pipe(Effect.orDie);
251 const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
252 runtime.runPromise(Effect.service(OrchestrationReactor)),
253 ).pipe(Effect.orDie);
254 const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
255 runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
256 ).pipe(Effect.orDie);
257 const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
258 runtime.runPromise(Effect.service(ProviderService)),
259 ).pipe(Effect.orDie);
260 const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
261 runtime.runPromise(Effect.service(CheckpointStore)),
262 ).pipe(Effect.orDie);
263 const checkpointRepository = yield* tryRuntimePromise(
264 "load ProjectionCheckpointRepository service",
265 () => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
266 ).pipe(Effect.orDie);
267 const pendingApprovalRepository = yield* tryRuntimePromise(
268 "load ProjectionPendingApprovalRepository service",
269 () => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
270 ).pipe(Effect.orDie);
271
272 const scope = yield* Scope.make("sequential");
273 yield* tryRuntimePromise("start OrchestrationReactor", () =>
274 runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
275 ).pipe(Effect.orDie);
276 yield* sleep(10);
277
278 const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
279 threadId,
280 predicate,
281 timeoutMs,
282 ) =>
283 waitFor(
284 snapshotQuery
285 .getSnapshot()
286 .pipe(
287 Effect.map(
288 (snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
289 ),
290 ),
291 (thread): thread is OrchestrationThread => thread !== null && predicate(thread),
292 `projected thread '${threadId}'`,
293 timeoutMs,
294 ) as Effect.Effect<OrchestrationThread, never>;
295
296 const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
297 predicate,
298 timeoutMs,
299 ) =>
300 waitFor(
301 Stream.runCollect(engine.readEvents(0)).pipe(
302 Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
303 ),
304 (events) => events.some(predicate),
305 "domain event",
306 timeoutMs,
307 );
308
309 const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
310 requestId,
311 predicate,
312 timeoutMs,
313 ) =>
314 waitFor(
315 pendingApprovalRepository
316 .getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
317 .pipe(
318 Effect.map((row) =>
319 Option.match(row, {
320 onNone: () => null,
321 onSome: (value) => ({
322 status: value.status,
323 decision: value.decision,
324 resolvedAt: value.resolvedAt,
325 }),
326 }),
327 ),
328 ),
329 (
330 row,
331 ): row is {
332 readonly status: "pending" | "resolved";
333 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
334 readonly resolvedAt: string | null;
335 } => row !== null && predicate(row),
336 `pending approval '${requestId}'`,
337 timeoutMs,
338 ) as Effect.Effect<
339 {
340 readonly status: "pending" | "resolved";
341 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
342 readonly resolvedAt: string | null;
343 },
344 never
345 >;
346
347 let disposed = false;
348 const dispose = Effect.gen(function* () {
349 if (disposed) {
350 return;
351 }
352 disposed = true;
353
354 const shutdown = Effect.gen(function* () {
355 const stopAllExit = yield* Effect.exit(
356 Effect.promise(() => runtime.runPromise(providerService.stopAll())),
357 );
358 const closeScopeExit = yield* Effect.exit(
359 Effect.promise(() => Effect.runPromise(Scope.close(scope, Exit.void))),
360 );
361 const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
362
363 const failureCause = Exit.isFailure(stopAllExit)
364 ? stopAllExit.cause
365 : Exit.isFailure(closeScopeExit)
366 ? closeScopeExit.cause
367 : Exit.isFailure(disposeRuntimeExit)
368 ? disposeRuntimeExit.cause
369 : null;
370
371 if (failureCause) {
372 return yield* Effect.failCause(failureCause);
373 }
374 });
375
376 yield* shutdown.pipe(
377 Effect.ensuring(
378 Effect.sync(() => {
379 fs.rmSync(rootDir, { recursive: true, force: true });
380 }),
381 ),
382 );
383 });
384
385 return {
386 rootDir,
387 workspaceDir,
388 dbPath,
389 adapterHarness,
390 engine,
391 snapshotQuery,
392 providerService,
393 checkpointStore,
394 checkpointRepository,
395 pendingApprovalRepository,
396 waitForThread,
397 waitForDomainEvent,
398 waitForPendingApproval,
399 dispose,
400 } satisfies OrchestrationIntegrationHarness;
401});