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
219 const runtimeServicesLayer = Layer.mergeAll(
220 orchestrationLayer,
221 OrchestrationProjectionSnapshotQueryLive,
222 ProjectionCheckpointRepositoryLive,
223 ProjectionPendingApprovalRepositoryLive,
224 CheckpointStoreLive,
225 providerLayer,
226 );
227 const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
228 Layer.provideMerge(runtimeServicesLayer),
229 );
230 const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
231 Layer.provideMerge(runtimeServicesLayer),
232 );
233 const checkpointReactorLayer = CheckpointReactorLive.pipe(
234 Layer.provideMerge(runtimeServicesLayer),
235 );
236 const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
237 Layer.provideMerge(runtimeIngestionLayer),
238 Layer.provideMerge(providerCommandReactorLayer),
239 Layer.provideMerge(checkpointReactorLayer),
240 );
241 const layer = orchestrationReactorLayer.pipe(
242 Layer.provide(persistenceLayer),
243 Layer.provideMerge(NodeServices.layer),
244 );
245
246 const runtime = ManagedRuntime.make(layer);
247 const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
248 runtime.runPromise(Effect.service(OrchestrationEngineService)),
249 ).pipe(Effect.orDie);
250 const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
251 runtime.runPromise(Effect.service(OrchestrationReactor)),
252 ).pipe(Effect.orDie);
253 const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
254 runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
255 ).pipe(Effect.orDie);
256 const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
257 runtime.runPromise(Effect.service(ProviderService)),
258 ).pipe(Effect.orDie);
259 const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
260 runtime.runPromise(Effect.service(CheckpointStore)),
261 ).pipe(Effect.orDie);
262 const checkpointRepository = yield* tryRuntimePromise(
263 "load ProjectionCheckpointRepository service",
264 () => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
265 ).pipe(Effect.orDie);
266 const pendingApprovalRepository = yield* tryRuntimePromise(
267 "load ProjectionPendingApprovalRepository service",
268 () => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
269 ).pipe(Effect.orDie);
270
271 const scope = yield* Scope.make("sequential");
272 yield* tryRuntimePromise("start OrchestrationReactor", () =>
273 runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
274 ).pipe(Effect.orDie);
275 yield* sleep(10);
276
277 const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
278 threadId,
279 predicate,
280 timeoutMs,
281 ) =>
282 waitFor(
283 snapshotQuery
284 .getSnapshot()
285 .pipe(
286 Effect.map(
287 (snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
288 ),
289 ),
290 (thread): thread is OrchestrationThread => thread !== null && predicate(thread),
291 `projected thread '${threadId}'`,
292 timeoutMs,
293 ) as Effect.Effect<OrchestrationThread, never>;
294
295 const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
296 predicate,
297 timeoutMs,
298 ) =>
299 waitFor(
300 Stream.runCollect(engine.readEvents(0)).pipe(
301 Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
302 ),
303 (events) => events.some(predicate),
304 "domain event",
305 timeoutMs,
306 );
307
308 const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
309 requestId,
310 predicate,
311 timeoutMs,
312 ) =>
313 waitFor(
314 pendingApprovalRepository
315 .getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
316 .pipe(
317 Effect.map((row) =>
318 Option.match(row, {
319 onNone: () => null,
320 onSome: (value) => ({
321 status: value.status,
322 decision: value.decision,
323 resolvedAt: value.resolvedAt,
324 }),
325 }),
326 ),
327 ),
328 (
329 row,
330 ): row is {
331 readonly status: "pending" | "resolved";
332 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
333 readonly resolvedAt: string | null;
334 } => row !== null && predicate(row),
335 `pending approval '${requestId}'`,
336 timeoutMs,
337 ) as Effect.Effect<
338 {
339 readonly status: "pending" | "resolved";
340 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
341 readonly resolvedAt: string | null;
342 },
343 never
344 >;
345
346 let disposed = false;
347 const dispose = Effect.gen(function* () {
348 if (disposed) {
349 return;
350 }
351 disposed = true;
352
353 const shutdown = Effect.gen(function* () {
354 const stopAllExit = yield* Effect.exit(
355 Effect.promise(() => runtime.runPromise(providerService.stopAll())),
356 );
357 const closeScopeExit = yield* Effect.exit(
358 Effect.promise(() => Effect.runPromise(Scope.close(scope, Exit.void))),
359 );
360 const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
361
362 const failureCause = Exit.isFailure(stopAllExit)
363 ? stopAllExit.cause
364 : Exit.isFailure(closeScopeExit)
365 ? closeScopeExit.cause
366 : Exit.isFailure(disposeRuntimeExit)
367 ? disposeRuntimeExit.cause
368 : null;
369
370 if (failureCause) {
371 return yield* Effect.failCause(failureCause);
372 }
373 });
374
375 yield* shutdown.pipe(
376 Effect.ensuring(
377 Effect.sync(() => {
378 fs.rmSync(rootDir, { recursive: true, force: true });
379 }),
380 ),
381 );
382 });
383
384 return {
385 rootDir,
386 workspaceDir,
387 dbPath,
388 adapterHarness,
389 engine,
390 snapshotQuery,
391 providerService,
392 checkpointStore,
393 checkpointRepository,
394 pendingApprovalRepository,
395 waitForThread,
396 waitForDomainEvent,
397 waitForPendingApproval,
398 dispose,
399 } satisfies OrchestrationIntegrationHarness;
400});