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

OrchestrationEngine.test.ts

658 lines21.3 KB

1import {
2 CheckpointRef,
3 CommandId,
4 MessageId,
5 ProjectId,
6 ThreadId,
7 TurnId,
8 type OrchestrationEvent,
9} from "@t3tools/contracts";
10import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
11import { describe, expect, it } from "vitest";
12​
13import { PersistenceSqlError } from "../../persistence/Errors.ts";
14import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
15import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
16import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
17import {
18 OrchestrationEventStore,
19 type OrchestrationEventStoreShape,
20} from "../../persistence/Services/OrchestrationEventStore.ts";
21import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
22import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
23import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
24import {
25 OrchestrationProjectionPipeline,
26 type OrchestrationProjectionPipelineShape,
27} from "../Services/ProjectionPipeline.ts";
28import { ServerConfig } from "../../config.ts";
29import * as NodeServices from "@effect/platform-node/NodeServices";
30​
31const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
32const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
33const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
34const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
35​
36async function createOrchestrationSystem() {
37 const orchestrationLayer = OrchestrationEngineLive.pipe(
38 Layer.provide(OrchestrationProjectionPipelineLive),
39 Layer.provide(OrchestrationEventStoreLive),
40 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
41 Layer.provide(SqlitePersistenceMemory),
42 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
43 Layer.provideMerge(NodeServices.layer),
44 );
45 const runtime = ManagedRuntime.make(orchestrationLayer);
46 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
47 return {
48 engine,
49 run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
50 dispose: () => runtime.dispose(),
51 };
53​
54function now() {
55 return new Date().toISOString();
57​
58describe("OrchestrationEngine", () => {
59 it("returns deterministic read models for repeated reads", async () => {
60 const createdAt = now();
61 const system = await createOrchestrationSystem();
62 const { engine } = system;
63​
64 await system.run(
65 engine.dispatch({
66 type: "project.create",
67 commandId: CommandId.makeUnsafe("cmd-project-1-create"),
68 projectId: asProjectId("project-1"),
69 title: "Project 1",
70 workspaceRoot: "/tmp/project-1",
71 defaultModel: "gpt-5-codex",
72 createdAt,
73 }),
74 );
75 await system.run(
76 engine.dispatch({
77 type: "thread.create",
78 commandId: CommandId.makeUnsafe("cmd-thread-1-create"),
79 threadId: ThreadId.makeUnsafe("thread-1"),
80 projectId: asProjectId("project-1"),
81 title: "Thread",
82 model: "gpt-5-codex",
83 branch: null,
84 worktreePath: null,
85 createdAt,
86 }),
87 );
88 await system.run(
89 engine.dispatch({
90 type: "thread.turn.start",
91 commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
92 threadId: ThreadId.makeUnsafe("thread-1"),
93 message: {
94 messageId: asMessageId("msg-1"),
95 role: "user",
96 text: "hello",
97 attachments: [],
98 },
99 approvalPolicy: "on-request",
100 sandboxMode: "workspace-write",
101 createdAt,
102 }),
103 );
104​
105 const readModelA = await system.run(engine.getReadModel());
106 const readModelB = await system.run(engine.getReadModel());
107 expect(readModelB).toEqual(readModelA);
108 await system.dispose();
109 });
110​
111 it("replays append-only events from sequence", async () => {
112 const system = await createOrchestrationSystem();
113 const { engine } = system;
114 const createdAt = now();
115​
116 await system.run(
117 engine.dispatch({
118 type: "project.create",
119 commandId: CommandId.makeUnsafe("cmd-project-replay-create"),
120 projectId: asProjectId("project-replay"),
121 title: "Replay Project",
122 workspaceRoot: "/tmp/project-replay",
123 defaultModel: "gpt-5-codex",
124 createdAt,
125 }),
126 );
127 await system.run(
128 engine.dispatch({
129 type: "thread.create",
130 commandId: CommandId.makeUnsafe("cmd-thread-replay-create"),
131 threadId: ThreadId.makeUnsafe("thread-replay"),
132 projectId: asProjectId("project-replay"),
133 title: "replay",
134 model: "gpt-5-codex",
135 branch: null,
136 worktreePath: null,
137 createdAt,
138 }),
139 );
140 await system.run(
141 engine.dispatch({
142 type: "thread.delete",
143 commandId: CommandId.makeUnsafe("cmd-thread-replay-delete"),
144 threadId: ThreadId.makeUnsafe("thread-replay"),
145 }),
146 );
147​
148 const events = await system.run(
149 Stream.runCollect(engine.readEvents(0)).pipe(
150 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
151 ),
152 );
153 expect(events.map((event) => event.type)).toEqual([
154 "project.created",
155 "thread.created",
156 "thread.deleted",
157 ]);
158 await system.dispose();
159 });
160​
161 it("streams persisted domain events in order", async () => {
162 const system = await createOrchestrationSystem();
163 const { engine } = system;
164 const createdAt = now();
165​
166 await system.run(
167 engine.dispatch({
168 type: "project.create",
169 commandId: CommandId.makeUnsafe("cmd-project-stream-create"),
170 projectId: asProjectId("project-stream"),
171 title: "Stream Project",
172 workspaceRoot: "/tmp/project-stream",
173 defaultModel: "gpt-5-codex",
174 createdAt,
175 }),
176 );
177​
178 const eventTypes: string[] = [];
179 await system.run(
180 Effect.gen(function* () {
181 const eventQueue = yield* Queue.unbounded<OrchestrationEvent>();
182 yield* Effect.forkScoped(
183 Stream.take(engine.streamDomainEvents, 2).pipe(
184 Stream.runForEach((event) => Queue.offer(eventQueue, event).pipe(Effect.asVoid)),
185 ),
186 );
187 yield* Effect.sleep("10 millis");
188 yield* engine.dispatch({
189 type: "thread.create",
190 commandId: CommandId.makeUnsafe("cmd-stream-thread-create"),
191 threadId: ThreadId.makeUnsafe("thread-stream"),
192 projectId: asProjectId("project-stream"),
193 title: "domain-stream",
194 model: "gpt-5-codex",
195 branch: null,
196 worktreePath: null,
197 createdAt,
198 });
199 yield* engine.dispatch({
200 type: "thread.meta.update",
201 commandId: CommandId.makeUnsafe("cmd-stream-thread-update"),
202 threadId: ThreadId.makeUnsafe("thread-stream"),
203 title: "domain-stream-updated",
204 });
205 eventTypes.push((yield* Queue.take(eventQueue)).type);
206 eventTypes.push((yield* Queue.take(eventQueue)).type);
207 }).pipe(Effect.scoped),
208 );
209​
210 expect(eventTypes).toEqual(["thread.created", "thread.meta-updated"]);
211 await system.dispose();
212 });
213​
214 it("stores completed checkpoint summaries even when no files changed", async () => {
215 const system = await createOrchestrationSystem();
216 const { engine } = system;
217 const createdAt = now();
218​
219 await system.run(
220 engine.dispatch({
221 type: "project.create",
222 commandId: CommandId.makeUnsafe("cmd-project-turn-diff-create"),
223 projectId: asProjectId("project-turn-diff"),
224 title: "Turn Diff Project",
225 workspaceRoot: "/tmp/project-turn-diff",
226 defaultModel: "gpt-5-codex",
227 createdAt,
228 }),
229 );
230 await system.run(
231 engine.dispatch({
232 type: "thread.create",
233 commandId: CommandId.makeUnsafe("cmd-thread-turn-diff-create"),
234 threadId: ThreadId.makeUnsafe("thread-turn-diff"),
235 projectId: asProjectId("project-turn-diff"),
236 title: "Turn diff thread",
237 model: "gpt-5-codex",
238 branch: null,
239 worktreePath: null,
240 createdAt,
241 }),
242 );
243 await system.run(
244 engine.dispatch({
245 type: "thread.turn.diff.complete",
246 commandId: CommandId.makeUnsafe("cmd-turn-diff-complete"),
247 threadId: ThreadId.makeUnsafe("thread-turn-diff"),
248 turnId: asTurnId("turn-1"),
249 completedAt: createdAt,
250 checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
251 status: "ready",
252 files: [],
253 checkpointTurnCount: 1,
254 createdAt,
255 }),
256 );
257​
258 const thread = (await system.run(engine.getReadModel())).threads.find(
259 (entry) => entry.id === "thread-turn-diff",
260 );
261 expect(thread?.checkpoints).toEqual([
262 {
263 turnId: asTurnId("turn-1"),
264 checkpointTurnCount: 1,
265 checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
266 status: "ready",
267 files: [],
268 assistantMessageId: null,
269 completedAt: createdAt,
270 },
271 ]);
272 await system.dispose();
273 });
274​
275 it("keeps processing queued commands after a storage failure", async () => {
276 type StoredEvent =
277 ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
278 ? A
279 : never;
280 const events: StoredEvent[] = [];
281 let nextSequence = 1;
282 let shouldFailFirstAppend = true;
283​
284 const flakyStore: OrchestrationEventStoreShape = {
285 append(event) {
286 if (shouldFailFirstAppend && event.commandId === CommandId.makeUnsafe("cmd-flaky-1")) {
287 shouldFailFirstAppend = false;
288 return Effect.fail(
289 new PersistenceSqlError({
290 operation: "test.append",
291 detail: "append failed",
292 }),
293 );
294 }
295 const savedEvent = {
296 ...event,
297 sequence: nextSequence,
298 } as StoredEvent;
299 nextSequence += 1;
300 events.push(savedEvent);
301 return Effect.succeed(savedEvent);
302 },
303 readFromSequence(sequenceExclusive) {
304 return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
305 },
306 readAll() {
307 return Stream.fromIterable(events);
308 },
309 };
310​
311 const runtime = ManagedRuntime.make(
312 OrchestrationEngineLive.pipe(
313 Layer.provide(OrchestrationProjectionPipelineLive),
314 Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
315 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
316 Layer.provide(SqlitePersistenceMemory),
317 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
318 Layer.provideMerge(NodeServices.layer),
319 ),
320 );
321 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
322 const createdAt = now();
323​
324 await runtime.runPromise(
325 engine.dispatch({
326 type: "project.create",
327 commandId: CommandId.makeUnsafe("cmd-project-flaky-create"),
328 projectId: asProjectId("project-flaky"),
329 title: "Flaky Project",
330 workspaceRoot: "/tmp/project-flaky",
331 defaultModel: "gpt-5-codex",
332 createdAt,
333 }),
334 );
335​
336 await expect(
337 runtime.runPromise(
338 engine.dispatch({
339 type: "thread.create",
340 commandId: CommandId.makeUnsafe("cmd-flaky-1"),
341 threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
342 projectId: asProjectId("project-flaky"),
343 title: "flaky-fail",
344 model: "gpt-5-codex",
345 branch: null,
346 worktreePath: null,
347 createdAt,
348 }),
349 ),
350 ).rejects.toThrow("append failed");
351​
352 const result = await runtime.runPromise(
353 engine.dispatch({
354 type: "thread.create",
355 commandId: CommandId.makeUnsafe("cmd-flaky-2"),
356 threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
357 projectId: asProjectId("project-flaky"),
358 title: "flaky-ok",
359 model: "gpt-5-codex",
360 branch: null,
361 worktreePath: null,
362 createdAt,
363 }),
364 );
365​
366 expect(result.sequence).toBe(2);
367 expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
368 await runtime.dispose();
369 });
370​
371 it("rolls back all events for a multi-event command when projection fails mid-dispatch", async () => {
372 let shouldFailRequestedProjection = true;
373 const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {
374 bootstrap: Effect.void,
375 projectEvent: (event) => {
376 if (
377 shouldFailRequestedProjection &&
378 event.commandId === CommandId.makeUnsafe("cmd-turn-start-atomic") &&
379 event.type === "thread.turn-start-requested"
380 ) {
381 shouldFailRequestedProjection = false;
382 return Effect.fail(
383 new PersistenceSqlError({
384 operation: "test.projection",
385 detail: "projection failed",
386 }),
387 );
388 }
389 return Effect.void;
390 },
391 };
392​
393 const runtime = ManagedRuntime.make(
394 OrchestrationEngineLive.pipe(
395 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
396 Layer.provide(OrchestrationEventStoreLive),
397 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
398 Layer.provide(SqlitePersistenceMemory),
399 ),
400 );
401 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
402 const createdAt = now();
403​
404 await runtime.runPromise(
405 engine.dispatch({
406 type: "project.create",
407 commandId: CommandId.makeUnsafe("cmd-project-atomic-create"),
408 projectId: asProjectId("project-atomic"),
409 title: "Atomic Project",
410 workspaceRoot: "/tmp/project-atomic",
411 defaultModel: "gpt-5-codex",
412 createdAt,
413 }),
414 );
415 await runtime.runPromise(
416 engine.dispatch({
417 type: "thread.create",
418 commandId: CommandId.makeUnsafe("cmd-thread-atomic-create"),
419 threadId: ThreadId.makeUnsafe("thread-atomic"),
420 projectId: asProjectId("project-atomic"),
421 title: "atomic",
422 model: "gpt-5-codex",
423 branch: null,
424 worktreePath: null,
425 createdAt,
426 }),
427 );
428​
429 const turnStartCommand = {
430 type: "thread.turn.start" as const,
431 commandId: CommandId.makeUnsafe("cmd-turn-start-atomic"),
432 threadId: ThreadId.makeUnsafe("thread-atomic"),
433 message: {
434 messageId: asMessageId("msg-atomic-1"),
435 role: "user" as const,
436 text: "hello",
437 attachments: [],
438 },
439 approvalPolicy: "on-request" as const,
440 sandboxMode: "workspace-write" as const,
441 createdAt,
442 };
443​
444 await expect(runtime.runPromise(engine.dispatch(turnStartCommand))).rejects.toThrow(
445 "projection failed",
446 );
447​
448 const eventsAfterFailure = await runtime.runPromise(
449 Stream.runCollect(engine.readEvents(0)).pipe(
450 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
451 ),
452 );
453 expect(eventsAfterFailure.map((event) => event.type)).toEqual([
454 "project.created",
455 "thread.created",
456 ]);
457 expect((await runtime.runPromise(engine.getReadModel())).snapshotSequence).toBe(2);
458​
459 const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
460 expect(retryResult.sequence).toBe(4);
461​
462 const eventsAfterRetry = await runtime.runPromise(
463 Stream.runCollect(engine.readEvents(0)).pipe(
464 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
465 ),
466 );
467 expect(eventsAfterRetry.map((event) => event.type)).toEqual([
468 "project.created",
469 "thread.created",
470 "thread.message-sent",
471 "thread.turn-start-requested",
472 ]);
473 expect(
474 eventsAfterRetry.filter((event) => event.commandId === turnStartCommand.commandId),
475 ).toHaveLength(2);
476​
477 await runtime.dispose();
478 });
479​
480 it("reconciles in-memory state when append persists but projection fails", async () => {
481 type StoredEvent =
482 ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
483 ? A
484 : never;
485 const events: StoredEvent[] = [];
486 let nextSequence = 1;
487​
488 const nonTransactionalStore: OrchestrationEventStoreShape = {
489 append(event) {
490 const savedEvent = {
491 ...event,
492 sequence: nextSequence,
493 } as StoredEvent;
494 nextSequence += 1;
495 events.push(savedEvent);
496 return Effect.succeed(savedEvent);
497 },
498 readFromSequence(sequenceExclusive) {
499 return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
500 },
501 readAll() {
502 return Stream.fromIterable(events);
503 },
504 };
505​
506 let shouldFailProjection = true;
507 const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {
508 bootstrap: Effect.void,
509 projectEvent: (event) => {
510 if (
511 shouldFailProjection &&
512 event.commandId === CommandId.makeUnsafe("cmd-thread-meta-sync-fail")
513 ) {
514 shouldFailProjection = false;
515 return Effect.fail(
516 new PersistenceSqlError({
517 operation: "test.projection",
518 detail: "projection failed",
519 }),
520 );
521 }
522 return Effect.void;
523 },
524 };
525​
526 const runtime = ManagedRuntime.make(
527 OrchestrationEngineLive.pipe(
528 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
529 Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
530 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
531 Layer.provide(SqlitePersistenceMemory),
532 ),
533 );
534 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
535 const createdAt = now();
536​
537 await runtime.runPromise(
538 engine.dispatch({
539 type: "project.create",
540 commandId: CommandId.makeUnsafe("cmd-project-sync-create"),
541 projectId: asProjectId("project-sync"),
542 title: "Sync Project",
543 workspaceRoot: "/tmp/project-sync",
544 defaultModel: "gpt-5-codex",
545 createdAt,
546 }),
547 );
548 await runtime.runPromise(
549 engine.dispatch({
550 type: "thread.create",
551 commandId: CommandId.makeUnsafe("cmd-thread-sync-create"),
552 threadId: ThreadId.makeUnsafe("thread-sync"),
553 projectId: asProjectId("project-sync"),
554 title: "sync-before",
555 model: "gpt-5-codex",
556 branch: null,
557 worktreePath: null,
558 createdAt,
559 }),
560 );
561​
562 await expect(
563 runtime.runPromise(
564 engine.dispatch({
565 type: "thread.meta.update",
566 commandId: CommandId.makeUnsafe("cmd-thread-meta-sync-fail"),
567 threadId: ThreadId.makeUnsafe("thread-sync"),
568 title: "sync-after-failed-projection",
569 }),
570 ),
571 ).rejects.toThrow("projection failed");
572​
573 const readModelAfterFailure = await runtime.runPromise(engine.getReadModel());
574 const updatedThread = readModelAfterFailure.threads.find(
575 (thread) => thread.id === "thread-sync",
576 );
577 expect(readModelAfterFailure.snapshotSequence).toBe(3);
578 expect(updatedThread?.title).toBe("sync-after-failed-projection");
579​
580 await runtime.dispose();
581 });
582​
583 it("fails command dispatch when command invariants are violated", async () => {
584 const system = await createOrchestrationSystem();
585 const { engine } = system;
586​
587 await expect(
588 system.run(
589 engine.dispatch({
590 type: "thread.turn.start",
591 commandId: CommandId.makeUnsafe("cmd-invariant-missing-thread"),
592 threadId: ThreadId.makeUnsafe("thread-missing"),
593 message: {
594 messageId: asMessageId("msg-missing"),
595 role: "user",
596 text: "hello",
597 attachments: [],
598 },
599 approvalPolicy: "on-request",
600 sandboxMode: "workspace-write",
601 createdAt: now(),
602 }),
603 ),
604 ).rejects.toThrow("Thread 'thread-missing' does not exist");
605​
606 await system.dispose();
607 });
608​
609 it("rejects duplicate thread creation", async () => {
610 const system = await createOrchestrationSystem();
611 const { engine } = system;
612 const createdAt = now();
613​
614 await system.run(
615 engine.dispatch({
616 type: "project.create",
617 commandId: CommandId.makeUnsafe("cmd-project-duplicate-create"),
618 projectId: asProjectId("project-duplicate"),
619 title: "Duplicate Project",
620 workspaceRoot: "/tmp/project-duplicate",
621 defaultModel: "gpt-5-codex",
622 createdAt,
623 }),
624 );
625​
626 await system.run(
627 engine.dispatch({
628 type: "thread.create",
629 commandId: CommandId.makeUnsafe("cmd-thread-duplicate-1"),
630 threadId: ThreadId.makeUnsafe("thread-duplicate"),
631 projectId: asProjectId("project-duplicate"),
632 title: "duplicate",
633 model: "gpt-5-codex",
634 branch: null,
635 worktreePath: null,
636 createdAt,
637 }),
638 );
639​
640 await expect(
641 system.run(
642 engine.dispatch({
643 type: "thread.create",
644 commandId: CommandId.makeUnsafe("cmd-thread-duplicate-2"),
645 threadId: ThreadId.makeUnsafe("thread-duplicate"),
646 projectId: asProjectId("project-duplicate"),
647 title: "duplicate",
648 model: "gpt-5-codex",
649 branch: null,
650 worktreePath: null,
651 createdAt,
652 }),
653 ),
654 ).rejects.toThrow("already exists");
655​
656 await system.dispose();
657 });
658});