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

OrchestrationEngineHarness.integration.ts

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