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