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