Open History to see the last commit
1import { execFileSync } from "node:child_process";
2
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import {
5 ApprovalRequestId,
6 ProviderKind,
7 type OrchestrationEvent,
8 type OrchestrationThread,
9} from "@t3tools/contracts";
10import {
11 Effect,
12 Exit,
13 FileSystem,
14 Layer,
15 ManagedRuntime,
16 Option,
17 Path,
18 Ref,
19 Schedule,
20 Schema,
21 Scope,
22 Stream,
23} from "effect";
24
25import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
26import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
27import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
28import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
29import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
30import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
31import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
32import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
33import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts";
34import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
35import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
36import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
37import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
38import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
39import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
40import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
41import { ServerSettingsService } from "../src/serverSettings.ts";
42import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
43import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
44import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
45import { ProviderService } from "../src/provider/Services/ProviderService.ts";
46import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
47import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
48import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
49import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
50import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
51import { RuntimeReceiptBusLive } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
52import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
53import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
54import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
55import {
56 OrchestrationEngineService,
57 type OrchestrationEngineShape,
58} from "../src/orchestration/Services/OrchestrationEngine.ts";
59import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
60import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
61import {
62 RuntimeReceiptBus,
63 type OrchestrationRuntimeReceipt,
64} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
65
66import {
67 makeTestProviderAdapterHarness,
68 type TestProviderAdapterHarness,
69} from "./TestProviderAdapter.integration.ts";
70import { deriveServerPaths, ServerConfig } from "../src/config.ts";
71
72function runGit(cwd: string, args: ReadonlyArray<string>) {
73 return execFileSync("git", args, {
74 cwd,
75 stdio: ["ignore", "pipe", "pipe"],
76 encoding: "utf8",
77 });
78}
79
80const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
81 runGit(cwd, ["init", "--initial-branch=main"]);
82 runGit(cwd, ["config", "user.email", "test@example.com"]);
83 runGit(cwd, ["config", "user.name", "Test User"]);
84 const fileSystem = yield* FileSystem.FileSystem;
85 const { join } = yield* Path.Path;
86 yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
87 runGit(cwd, ["add", "."]);
88 runGit(cwd, ["commit", "-m", "Initial"]);
89});
90
91export function gitRefExists(cwd: string, ref: string): boolean {
92 try {
93 runGit(cwd, ["show-ref", "--verify", "--quiet", ref]);
94 return true;
95 } catch {
96 return false;
97 }
98}
99
100export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
101 return runGit(cwd, ["show", `${ref}:${filePath}`]);
102}
103
104class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()(
105 "WaitForTimeoutError",
106 {
107 description: Schema.String,
108 },
109) {}
110
111function waitFor<A, E>(
112 read: Effect.Effect<A, E>,
113 predicate: (value: A) => boolean,
114 description: string,
115 timeoutMs?: number,
116): Effect.Effect<A, never>;
117function waitFor<A, B extends A, E>(
118 read: Effect.Effect<A, E>,
119 predicate: (value: A) => value is B,
120 description: string,
121 timeoutMs?: number,
122): Effect.Effect<B, never>;
123function waitFor<A, E>(
124 read: Effect.Effect<A, E>,
125 predicate: (value: A) => boolean,
126 description: string,
127 timeoutMs = 10_000,
128): Effect.Effect<A, never> {
129 const RETRY_SIGNAL = "wait_for_retry";
130 const retryIntervalMs = 10;
131 const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
132 const retrySchedule = Schedule.spaced(`${retryIntervalMs} millis`);
133
134 return read.pipe(
135 Effect.filterOrFail(predicate, () => RETRY_SIGNAL),
136 Effect.retry({
137 schedule: retrySchedule,
138 times: maxRetries,
139 while: (error) => error === RETRY_SIGNAL,
140 }),
141 Effect.mapError((error) =>
142 error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error,
143 ),
144 Effect.orDie,
145 );
146}
147
148class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<OrchestrationHarnessRuntimeError>()(
149 "OrchestrationHarnessRuntimeError",
150 {
151 operation: Schema.String,
152 cause: Schema.optional(Schema.Defect),
153 },
154) {}
155
156const tryRuntimePromise = <A>(operation: string, run: () => Promise<A>) =>
157 Effect.tryPromise({
158 try: run,
159 catch: (cause) => new OrchestrationHarnessRuntimeError({ operation, cause }),
160 });
161
162export interface OrchestrationIntegrationHarness {
163 readonly rootDir: string;
164 readonly workspaceDir: string;
165 readonly dbPath: string;
166 readonly adapterHarness: TestProviderAdapterHarness | null;
167 readonly engine: OrchestrationEngineShape;
168 readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
169 readonly providerService: ProviderService["Service"];
170 readonly checkpointStore: CheckpointStore["Service"];
171 readonly checkpointRepository: ProjectionCheckpointRepository["Service"];
172 readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];
173 readonly waitForThread: (
174 threadId: string,
175 predicate: (thread: OrchestrationThread) => boolean,
176 timeoutMs?: number,
177 ) => Effect.Effect<OrchestrationThread, never>;
178 readonly waitForDomainEvent: (
179 predicate: (event: OrchestrationEvent) => boolean,
180 timeoutMs?: number,
181 ) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
182 readonly waitForPendingApproval: (
183 requestId: string,
184 predicate: (row: {
185 readonly status: "pending" | "resolved";
186 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
187 readonly resolvedAt: string | null;
188 }) => boolean,
189 timeoutMs?: number,
190 ) => Effect.Effect<
191 {
192 readonly status: "pending" | "resolved";
193 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
194 readonly resolvedAt: string | null;
195 },
196 never
197 >;
198 readonly waitForReceipt: {
199 (
200 predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
201 timeoutMs?: number,
202 ): Effect.Effect<OrchestrationRuntimeReceipt, never>;
203 <Receipt extends OrchestrationRuntimeReceipt>(
204 predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
205 timeoutMs?: number,
206 ): Effect.Effect<Receipt, never>;
207 };
208 readonly dispose: Effect.Effect<void, never>;
209}
210
211interface MakeOrchestrationIntegrationHarnessOptions {
212 readonly provider?: ProviderKind;
213 readonly realCodex?: boolean;
214}
215
216export const makeOrchestrationIntegrationHarness = (
217 options?: MakeOrchestrationIntegrationHarnessOptions,
218) =>
219 Effect.gen(function* () {
220 const path = yield* Path.Path;
221 const fileSystem = yield* FileSystem.FileSystem;
222
223 const provider = options?.provider ?? "codex";
224 const useRealCodex = options?.realCodex === true;
225 const adapterHarness = useRealCodex
226 ? null
227 : yield* makeTestProviderAdapterHarness({
228 provider,
229 });
230 const fakeRegistry = adapterHarness
231 ? Layer.succeed(ProviderAdapterRegistry, {
232 getByProvider: (resolvedProvider) =>
233 resolvedProvider === adapterHarness.provider
234 ? Effect.succeed(adapterHarness.adapter)
235 : Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
236 listProviders: () => Effect.succeed([adapterHarness.provider]),
237 } as typeof ProviderAdapterRegistry.Service)
238 : null;
239 const rootDir = yield* fileSystem.makeTempDirectoryScoped({
240 prefix: "t3-orchestration-integration-",
241 });
242 const workspaceDir = path.join(rootDir, "workspace");
243 const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
244 Effect.provideService(Path.Path, path),
245 );
246 yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
247 yield* fileSystem.makeDirectory(stateDir, { recursive: true });
248 yield* initializeGitWorkspace(workspaceDir);
249
250 const persistenceLayer = makeSqlitePersistenceLive(dbPath);
251 const orchestrationLayer = OrchestrationEngineLive.pipe(
252 Layer.provide(OrchestrationProjectionPipelineLive),
253 Layer.provide(OrchestrationEventStoreLive),
254 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
255 );
256 const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
257 Layer.provide(ProviderSessionRuntimeRepositoryLive),
258 );
259 const realCodexRegistry = Layer.effect(
260 ProviderAdapterRegistry,
261 Effect.gen(function* () {
262 const codexAdapter = yield* CodexAdapter;
263 return {
264 getByProvider: (resolvedProvider) =>
265 resolvedProvider === "codex"
266 ? Effect.succeed(codexAdapter)
267 : Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
268 listProviders: () => Effect.succeed(["codex"] as const),
269 } as typeof ProviderAdapterRegistry.Service;
270 }),
271 ).pipe(
272 Layer.provide(makeCodexAdapterLive()),
273 Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
274 Layer.provideMerge(NodeServices.layer),
275 Layer.provideMerge(providerSessionDirectoryLayer),
276 );
277 const providerLayer = useRealCodex
278 ? makeProviderServiceLive().pipe(
279 Layer.provide(providerSessionDirectoryLayer),
280 Layer.provide(realCodexRegistry),
281 Layer.provide(AnalyticsService.layerTest),
282 )
283 : makeProviderServiceLive().pipe(
284 Layer.provide(providerSessionDirectoryLayer),
285 Layer.provide(fakeRegistry!),
286 Layer.provide(AnalyticsService.layerTest),
287 );
288
289 const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
290 const runtimeServicesLayer = Layer.mergeAll(
291 orchestrationLayer,
292 OrchestrationProjectionSnapshotQueryLive,
293 ProjectionCheckpointRepositoryLive,
294 ProjectionPendingApprovalRepositoryLive,
295 checkpointStoreLayer,
296 providerLayer,
297 RuntimeReceiptBusLive,
298 );
299 const serverSettingsLayer = ServerSettingsService.layerTest();
300 const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
301 Layer.provideMerge(runtimeServicesLayer),
302 Layer.provideMerge(serverSettingsLayer),
303 );
304 const gitCoreLayer = Layer.succeed(GitCore, {
305 renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
306 Effect.succeed({ branch: input.newBranch }),
307 } as unknown as GitCoreShape);
308 const textGenerationLayer = Layer.succeed(TextGeneration, {
309 generateBranchName: () => Effect.succeed({ branch: "update" }),
310 generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
311 } as unknown as TextGenerationShape);
312 const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
313 Layer.provideMerge(runtimeServicesLayer),
314 Layer.provideMerge(gitCoreLayer),
315 Layer.provideMerge(textGenerationLayer),
316 Layer.provideMerge(serverSettingsLayer),
317 );
318 const checkpointReactorLayer = CheckpointReactorLive.pipe(
319 Layer.provideMerge(runtimeServicesLayer),
320 );
321 const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
322 Layer.provideMerge(runtimeIngestionLayer),
323 Layer.provideMerge(providerCommandReactorLayer),
324 Layer.provideMerge(checkpointReactorLayer),
325 );
326 const layer = orchestrationReactorLayer.pipe(
327 Layer.provide(persistenceLayer),
328 Layer.provideMerge(ServerSettingsService.layerTest()),
329 Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
330 Layer.provideMerge(NodeServices.layer),
331 );
332
333 const runtime = ManagedRuntime.make(layer);
334 const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
335 runtime.runPromise(Effect.service(OrchestrationEngineService)),
336 ).pipe(Effect.orDie);
337 const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
338 runtime.runPromise(Effect.service(OrchestrationReactor)),
339 ).pipe(Effect.orDie);
340 const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
341 runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
342 ).pipe(Effect.orDie);
343 const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
344 runtime.runPromise(Effect.service(ProviderService)),
345 ).pipe(Effect.orDie);
346 const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
347 runtime.runPromise(Effect.service(CheckpointStore)),
348 ).pipe(Effect.orDie);
349 const checkpointRepository = yield* tryRuntimePromise(
350 "load ProjectionCheckpointRepository service",
351 () => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
352 ).pipe(Effect.orDie);
353 const pendingApprovalRepository = yield* tryRuntimePromise(
354 "load ProjectionPendingApprovalRepository service",
355 () => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
356 ).pipe(Effect.orDie);
357 const runtimeReceiptBus = yield* tryRuntimePromise("load RuntimeReceiptBus service", () =>
358 runtime.runPromise(Effect.service(RuntimeReceiptBus)),
359 ).pipe(Effect.orDie);
360
361 const scope = yield* Scope.make("sequential");
362 yield* tryRuntimePromise("start OrchestrationReactor", () =>
363 runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
364 ).pipe(Effect.orDie);
365 const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
366 yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
367 Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
368 ).pipe(Effect.forkIn(scope));
369 yield* Effect.sleep(10);
370
371 const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
372 threadId,
373 predicate,
374 timeoutMs,
375 ) =>
376 waitFor(
377 snapshotQuery
378 .getSnapshot()
379 .pipe(
380 Effect.map(
381 (snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
382 ),
383 ),
384 (thread): thread is OrchestrationThread => thread !== null && predicate(thread),
385 `projected thread '${threadId}'`,
386 timeoutMs,
387 ) as Effect.Effect<OrchestrationThread, never>;
388
389 const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
390 predicate,
391 timeoutMs,
392 ) =>
393 waitFor(
394 Stream.runCollect(engine.readEvents(0)).pipe(
395 Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
396 ),
397 (events) => events.some(predicate),
398 "domain event",
399 timeoutMs,
400 );
401
402 const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
403 requestId,
404 predicate,
405 timeoutMs,
406 ) =>
407 waitFor(
408 pendingApprovalRepository
409 .getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
410 .pipe(
411 Effect.map((row) =>
412 Option.match(row, {
413 onNone: () => null,
414 onSome: (value) => ({
415 status: value.status,
416 decision: value.decision,
417 resolvedAt: value.resolvedAt,
418 }),
419 }),
420 ),
421 ),
422 (
423 row,
424 ): row is {
425 readonly status: "pending" | "resolved";
426 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
427 readonly resolvedAt: string | null;
428 } => row !== null && predicate(row),
429 `pending approval '${requestId}'`,
430 timeoutMs,
431 ) as Effect.Effect<
432 {
433 readonly status: "pending" | "resolved";
434 readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
435 readonly resolvedAt: string | null;
436 },
437 never
438 >;
439
440 function waitForReceipt(
441 predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
442 timeoutMs?: number,
443 ): Effect.Effect<OrchestrationRuntimeReceipt, never>;
444 function waitForReceipt<Receipt extends OrchestrationRuntimeReceipt>(
445 predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
446 timeoutMs?: number,
447 ): Effect.Effect<Receipt, never>;
448 function waitForReceipt(
449 predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
450 timeoutMs?: number,
451 ) {
452 const readMatchingReceipt = Ref.get(receiptHistory).pipe(
453 Effect.map((history) => history.find(predicate)),
454 );
455
456 return waitFor(
457 readMatchingReceipt,
458 (receipt): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
459 "runtime receipt",
460 timeoutMs,
461 );
462 }
463
464 let disposed = false;
465 const dispose = Effect.gen(function* () {
466 if (disposed) {
467 return;
468 }
469 disposed = true;
470
471 const shutdown = Effect.gen(function* () {
472 const closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void));
473 const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
474
475 const failureCause = Exit.isFailure(closeScopeExit)
476 ? closeScopeExit.cause
477 : Exit.isFailure(disposeRuntimeExit)
478 ? disposeRuntimeExit.cause
479 : null;
480
481 if (failureCause) {
482 return yield* Effect.failCause(failureCause);
483 }
484 });
485
486 yield* shutdown;
487 });
488
489 return {
490 rootDir,
491 workspaceDir,
492 dbPath,
493 adapterHarness,
494 engine,
495 snapshotQuery,
496 providerService,
497 checkpointStore,
498 checkpointRepository,
499 pendingApprovalRepository,
500 waitForThread,
501 waitForDomainEvent,
502 waitForPendingApproval,
503 waitForReceipt,
504 dispose,
505 } satisfies OrchestrationIntegrationHarness;
506 });