Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OrchestrationEngineHarness.integration.ts

513 lines19.6 KB

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