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

OrchestrationEngineHarness.integration.ts

448 lines16.9 KB

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