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

OrchestrationEngine.test.ts

1,067 lines34.4 KB

1import {
2 CheckpointRef,
3 CommandId,
4 DEFAULT_PROVIDER_INTERACTION_MODE,
5 MessageId,
6 ProjectId,
7 ThreadId,
8 TurnId,
9 type OrchestrationEvent,
10 ProviderInstanceId,
11 type OrchestrationReadModel,
12} from "@t3tools/contracts";
13import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
14import { describe, expect, it } from "vitest";
15​
16import { PersistenceSqlError } from "../../persistence/Errors.ts";
17import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
18import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
19import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
20import {
21 OrchestrationEventStore,
22 type OrchestrationEventStoreShape,
23} from "../../persistence/Services/OrchestrationEventStore.ts";
24import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
25import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
26import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
27import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
28import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
29import {
30 OrchestrationProjectionPipeline,
31 type OrchestrationProjectionPipelineShape,
32} from "../Services/ProjectionPipeline.ts";
33import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
34import { ServerConfig } from "../../config.ts";
35import * as NodeServices from "@effect/platform-node/NodeServices";
36​
37const asProjectId = (value: string): ProjectId => ProjectId.make(value);
38const asMessageId = (value: string): MessageId => MessageId.make(value);
39const asTurnId = (value: string): TurnId => TurnId.make(value);
40const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
41​
42async function createOrchestrationSystem() {
43 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
44 prefix: "t3-orchestration-engine-test-",
45 });
46 const orchestrationLayer = Layer.mergeAll(
47 OrchestrationEngineLive.pipe(
48 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
49 Layer.provide(OrchestrationProjectionPipelineLive),
50 ),
51 OrchestrationProjectionSnapshotQueryLive,
52 ).pipe(
53 Layer.provide(OrchestrationEventStoreLive),
54 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
55 Layer.provide(RepositoryIdentityResolverLive),
56 Layer.provide(SqlitePersistenceMemory),
57 Layer.provideMerge(ServerConfigLayer),
58 Layer.provideMerge(NodeServices.layer),
59 );
60 const runtime = ManagedRuntime.make(orchestrationLayer);
61 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
62 const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
63 return {
64 engine,
65 readModel: () => runtime.runPromise(snapshotQuery.getSnapshot()),
66 run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
67 dispose: () => runtime.dispose(),
68 };
70​
71function now() {
72 return new Date().toISOString();
74​
75const hasMetricSnapshot = (
76 snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
77 id: string,
78 attributes: Readonly<Record<string, string>>,
79) =>
80 snapshots.some(
81 (snapshot) =>
82 snapshot.id === id &&
83 Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
84 );
85​
86describe("OrchestrationEngine", () => {
87 it("bootstraps command handling from persisted projections without reading the full snapshot", async () => {
88 let nextSequence = 8;
89 const eventStore: OrchestrationEventStoreShape = {
90 append: (event) =>
91 Effect.sync(() => {
92 const savedEvent = {
93 ...event,
94 sequence: nextSequence,
95 } as OrchestrationEvent;
96 nextSequence += 1;
97 return savedEvent;
98 }),
99 readFromSequence: () => Stream.empty,
100 readAll: () =>
101 Stream.fail(
102 new PersistenceSqlError({
103 operation: "test.readAll",
104 detail: "historical replay should not be used during bootstrap",
105 }),
106 ),
107 };
108​
109 const projectionSnapshot = {
110 snapshotSequence: 7,
111 updatedAt: "2026-03-03T00:00:04.000Z",
112 projects: [
113 {
114 id: asProjectId("project-bootstrap"),
115 title: "Bootstrap Project",
116 workspaceRoot: "/tmp/project-bootstrap",
117 defaultModelSelection: {
118 instanceId: ProviderInstanceId.make("codex"),
119 model: "gpt-5-codex",
120 },
121 scripts: [],
122 createdAt: "2026-03-03T00:00:00.000Z",
123 updatedAt: "2026-03-03T00:00:01.000Z",
124 deletedAt: null,
125 },
126 ],
127 threads: [
128 {
129 id: ThreadId.make("thread-bootstrap"),
130 projectId: asProjectId("project-bootstrap"),
131 title: "Bootstrap Thread",
132 modelSelection: {
133 instanceId: ProviderInstanceId.make("codex"),
134 model: "gpt-5-codex",
135 },
136 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
137 runtimeMode: "full-access" as const,
138 branch: null,
139 worktreePath: null,
140 latestTurn: null,
141 createdAt: "2026-03-03T00:00:02.000Z",
142 updatedAt: "2026-03-03T00:00:03.000Z",
143 archivedAt: null,
144 deletedAt: null,
145 messages: [],
146 proposedPlans: [],
147 activities: [],
148 checkpoints: [],
149 session: null,
150 },
151 ],
152 };
153 const commandReadModel = {
154 ...projectionSnapshot,
155 threads: projectionSnapshot.threads.map((thread) => ({
156 ...thread,
157 messages: [],
158 proposedPlans: [],
159 activities: [],
160 checkpoints: [],
161 })),
162 };
163 let fullSnapshotReadCount = 0;
164​
165 const layer = OrchestrationEngineLive.pipe(
166 Layer.provide(
167 Layer.succeed(ProjectionSnapshotQuery, {
168 getCommandReadModel: () => Effect.succeed(commandReadModel),
169 getSnapshot: () =>
170 Effect.sync(() => {
171 fullSnapshotReadCount += 1;
172 return projectionSnapshot;
173 }),
174 getShellSnapshot: () =>
175 Effect.succeed({
176 snapshotSequence: projectionSnapshot.snapshotSequence,
177 projects: [],
178 threads: [],
179 updatedAt: projectionSnapshot.updatedAt,
180 }),
181 getSnapshotSequence: () =>
182 Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
183 getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
184 getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
185 getProjectShellById: () => Effect.succeed(Option.none()),
186 getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
187 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
188 getThreadShellById: () => Effect.succeed(Option.none()),
189 getThreadDetailById: () => Effect.succeed(Option.none()),
190 }),
191 ),
192 Layer.provide(
193 Layer.succeed(OrchestrationProjectionPipeline, {
194 bootstrap: Effect.void,
195 projectEvent: () => Effect.void,
196 } satisfies OrchestrationProjectionPipelineShape),
197 ),
198 Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
199 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
200 Layer.provide(SqlitePersistenceMemory),
201 );
202​
203 const runtime = ManagedRuntime.make(layer);
204​
205 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
206 const result = await runtime.runPromise(
207 engine.dispatch({
208 type: "thread.meta.update",
209 commandId: CommandId.make("cmd-bootstrap-thread-update"),
210 threadId: ThreadId.make("thread-bootstrap"),
211 title: "Updated Bootstrap Thread",
212 }),
213 );
214​
215 expect(result.sequence).toBe(8);
216 expect(fullSnapshotReadCount).toBe(0);
217​
218 await runtime.dispose();
219 });
220​
221 it("persists deterministic read models for repeated snapshot reads", async () => {
222 const createdAt = now();
223 const system = await createOrchestrationSystem();
224 const { engine } = system;
225​
226 await system.run(
227 engine.dispatch({
228 type: "project.create",
229 commandId: CommandId.make("cmd-project-1-create"),
230 projectId: asProjectId("project-1"),
231 title: "Project 1",
232 workspaceRoot: "/tmp/project-1",
233 defaultModelSelection: {
234 instanceId: ProviderInstanceId.make("codex"),
235 model: "gpt-5-codex",
236 },
237 createdAt,
238 }),
239 );
240 await system.run(
241 engine.dispatch({
242 type: "thread.create",
243 commandId: CommandId.make("cmd-thread-1-create"),
244 threadId: ThreadId.make("thread-1"),
245 projectId: asProjectId("project-1"),
246 title: "Thread",
247 modelSelection: {
248 instanceId: ProviderInstanceId.make("codex"),
249 model: "gpt-5-codex",
250 },
251 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
252 runtimeMode: "approval-required",
253 branch: null,
254 worktreePath: null,
255 createdAt,
256 }),
257 );
258 await system.run(
259 engine.dispatch({
260 type: "thread.turn.start",
261 commandId: CommandId.make("cmd-turn-start-1"),
262 threadId: ThreadId.make("thread-1"),
263 message: {
264 messageId: asMessageId("msg-1"),
265 role: "user",
266 text: "hello",
267 attachments: [],
268 },
269 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
270 runtimeMode: "approval-required",
271 createdAt,
272 }),
273 );
274​
275 const readModelA = await system.readModel();
276 const readModelB = await system.readModel();
277 expect(readModelB).toEqual(readModelA);
278 await system.dispose();
279 });
280​
281 it("archives and unarchives threads through orchestration commands", async () => {
282 const system = await createOrchestrationSystem();
283 const { engine } = system;
284 const createdAt = now();
285​
286 await system.run(
287 engine.dispatch({
288 type: "project.create",
289 commandId: CommandId.make("cmd-project-archive-create"),
290 projectId: asProjectId("project-archive"),
291 title: "Project Archive",
292 workspaceRoot: "/tmp/project-archive",
293 defaultModelSelection: {
294 instanceId: ProviderInstanceId.make("codex"),
295 model: "gpt-5-codex",
296 },
297 createdAt,
298 }),
299 );
300 await system.run(
301 engine.dispatch({
302 type: "thread.create",
303 commandId: CommandId.make("cmd-thread-archive-create"),
304 threadId: ThreadId.make("thread-archive"),
305 projectId: asProjectId("project-archive"),
306 title: "Archive me",
307 modelSelection: {
308 instanceId: ProviderInstanceId.make("codex"),
309 model: "gpt-5-codex",
310 },
311 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
312 runtimeMode: "full-access",
313 branch: null,
314 worktreePath: null,
315 createdAt,
316 }),
317 );
318​
319 await system.run(
320 engine.dispatch({
321 type: "thread.archive",
322 commandId: CommandId.make("cmd-thread-archive"),
323 threadId: ThreadId.make("thread-archive"),
324 }),
325 );
326 expect(
327 (await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
328 ?.archivedAt,
329 ).not.toBeNull();
330​
331 await system.run(
332 engine.dispatch({
333 type: "thread.unarchive",
334 commandId: CommandId.make("cmd-thread-unarchive"),
335 threadId: ThreadId.make("thread-archive"),
336 }),
337 );
338 expect(
339 (await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
340 ?.archivedAt,
341 ).toBeNull();
342​
343 await system.dispose();
344 });
345​
346 it("replays append-only events from sequence", async () => {
347 const system = await createOrchestrationSystem();
348 const { engine } = system;
349 const createdAt = now();
350​
351 await system.run(
352 engine.dispatch({
353 type: "project.create",
354 commandId: CommandId.make("cmd-project-replay-create"),
355 projectId: asProjectId("project-replay"),
356 title: "Replay Project",
357 workspaceRoot: "/tmp/project-replay",
358 defaultModelSelection: {
359 instanceId: ProviderInstanceId.make("codex"),
360 model: "gpt-5-codex",
361 },
362 createdAt,
363 }),
364 );
365 await system.run(
366 engine.dispatch({
367 type: "thread.create",
368 commandId: CommandId.make("cmd-thread-replay-create"),
369 threadId: ThreadId.make("thread-replay"),
370 projectId: asProjectId("project-replay"),
371 title: "replay",
372 modelSelection: {
373 instanceId: ProviderInstanceId.make("codex"),
374 model: "gpt-5-codex",
375 },
376 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
377 runtimeMode: "approval-required",
378 branch: null,
379 worktreePath: null,
380 createdAt,
381 }),
382 );
383 await system.run(
384 engine.dispatch({
385 type: "thread.delete",
386 commandId: CommandId.make("cmd-thread-replay-delete"),
387 threadId: ThreadId.make("thread-replay"),
388 }),
389 );
390​
391 const events = await system.run(
392 Stream.runCollect(engine.readEvents(0)).pipe(
393 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
394 ),
395 );
396 expect(events.map((event) => event.type)).toEqual([
397 "project.created",
398 "thread.created",
399 "thread.deleted",
400 ]);
401 await system.dispose();
402 });
403​
404 it("streams persisted domain events in order", async () => {
405 const system = await createOrchestrationSystem();
406 const { engine } = system;
407 const createdAt = now();
408​
409 await system.run(
410 engine.dispatch({
411 type: "project.create",
412 commandId: CommandId.make("cmd-project-stream-create"),
413 projectId: asProjectId("project-stream"),
414 title: "Stream Project",
415 workspaceRoot: "/tmp/project-stream",
416 defaultModelSelection: {
417 instanceId: ProviderInstanceId.make("codex"),
418 model: "gpt-5-codex",
419 },
420 createdAt,
421 }),
422 );
423​
424 const eventTypes: string[] = [];
425 await system.run(
426 Effect.gen(function* () {
427 const eventQueue = yield* Queue.unbounded<OrchestrationEvent>();
428 yield* Effect.forkScoped(
429 Stream.take(engine.streamDomainEvents, 2).pipe(
430 Stream.runForEach((event) => Queue.offer(eventQueue, event).pipe(Effect.asVoid)),
431 ),
432 );
433 yield* Effect.sleep("10 millis");
434 yield* engine.dispatch({
435 type: "thread.create",
436 commandId: CommandId.make("cmd-stream-thread-create"),
437 threadId: ThreadId.make("thread-stream"),
438 projectId: asProjectId("project-stream"),
439 title: "domain-stream",
440 modelSelection: {
441 instanceId: ProviderInstanceId.make("codex"),
442 model: "gpt-5-codex",
443 },
444 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
445 runtimeMode: "approval-required",
446 branch: null,
447 worktreePath: null,
448 createdAt,
449 });
450 yield* engine.dispatch({
451 type: "thread.meta.update",
452 commandId: CommandId.make("cmd-stream-thread-update"),
453 threadId: ThreadId.make("thread-stream"),
454 title: "domain-stream-updated",
455 });
456 eventTypes.push((yield* Queue.take(eventQueue)).type);
457 eventTypes.push((yield* Queue.take(eventQueue)).type);
458 }).pipe(Effect.scoped),
459 );
460​
461 expect(eventTypes).toEqual(["thread.created", "thread.meta-updated"]);
462 await system.dispose();
463 });
464​
465 it("records command ack duration using the first committed event type", async () => {
466 const system = await createOrchestrationSystem();
467 const { engine } = system;
468 const createdAt = now();
469​
470 await system.run(
471 engine.dispatch({
472 type: "project.create",
473 commandId: CommandId.make("cmd-project-ack-create"),
474 projectId: asProjectId("project-ack"),
475 title: "Ack Project",
476 workspaceRoot: "/tmp/project-ack",
477 defaultModelSelection: {
478 instanceId: ProviderInstanceId.make("codex"),
479 model: "gpt-5-codex",
480 },
481 createdAt,
482 }),
483 );
484​
485 await system.run(
486 engine.dispatch({
487 type: "thread.create",
488 commandId: CommandId.make("cmd-thread-ack-create"),
489 threadId: ThreadId.make("thread-ack"),
490 projectId: asProjectId("project-ack"),
491 title: "Ack Thread",
492 modelSelection: {
493 instanceId: ProviderInstanceId.make("codex"),
494 model: "gpt-5-codex",
495 },
496 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
497 runtimeMode: "full-access",
498 branch: null,
499 worktreePath: null,
500 createdAt,
501 }),
502 );
503​
504 const snapshots = await system.run(Metric.snapshot);
505 expect(
506 hasMetricSnapshot(snapshots, "t3_orchestration_command_ack_duration", {
507 commandType: "thread.create",
508 aggregateKind: "thread",
509 ackEventType: "thread.created",
510 }),
511 ).toBe(true);
512​
513 await system.dispose();
514 });
515​
516 it("records failed command dispatches as metric failures", async () => {
517 const system = await createOrchestrationSystem();
518 const { engine } = system;
519 const createdAt = now();
520​
521 await expect(
522 system.run(
523 engine.dispatch({
524 type: "thread.create",
525 commandId: CommandId.make("cmd-thread-missing-project"),
526 threadId: ThreadId.make("thread-missing-project"),
527 projectId: asProjectId("project-missing"),
528 title: "Missing Project Thread",
529 modelSelection: {
530 instanceId: ProviderInstanceId.make("codex"),
531 model: "gpt-5-codex",
532 },
533 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
534 runtimeMode: "full-access",
535 branch: null,
536 worktreePath: null,
537 createdAt,
538 }),
539 ),
540 ).rejects.toThrow("does not exist");
541​
542 const snapshots = await system.run(Metric.snapshot);
543 expect(
544 hasMetricSnapshot(snapshots, "t3_orchestration_commands_total", {
545 commandType: "thread.create",
546 aggregateKind: "thread",
547 outcome: "failure",
548 }),
549 ).toBe(true);
550​
551 await system.dispose();
552 });
553​
554 it("stores completed checkpoint summaries even when no files changed", async () => {
555 const system = await createOrchestrationSystem();
556 const { engine } = system;
557 const createdAt = now();
558​
559 await system.run(
560 engine.dispatch({
561 type: "project.create",
562 commandId: CommandId.make("cmd-project-turn-diff-create"),
563 projectId: asProjectId("project-turn-diff"),
564 title: "Turn Diff Project",
565 workspaceRoot: "/tmp/project-turn-diff",
566 defaultModelSelection: {
567 instanceId: ProviderInstanceId.make("codex"),
568 model: "gpt-5-codex",
569 },
570 createdAt,
571 }),
572 );
573 await system.run(
574 engine.dispatch({
575 type: "thread.create",
576 commandId: CommandId.make("cmd-thread-turn-diff-create"),
577 threadId: ThreadId.make("thread-turn-diff"),
578 projectId: asProjectId("project-turn-diff"),
579 title: "Turn diff thread",
580 modelSelection: {
581 instanceId: ProviderInstanceId.make("codex"),
582 model: "gpt-5-codex",
583 },
584 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
585 runtimeMode: "approval-required",
586 branch: null,
587 worktreePath: null,
588 createdAt,
589 }),
590 );
591 await system.run(
592 engine.dispatch({
593 type: "thread.turn.diff.complete",
594 commandId: CommandId.make("cmd-turn-diff-complete"),
595 threadId: ThreadId.make("thread-turn-diff"),
596 turnId: asTurnId("turn-1"),
597 completedAt: createdAt,
598 checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
599 status: "ready",
600 files: [],
601 checkpointTurnCount: 1,
602 createdAt,
603 }),
604 );
605​
606 const thread = (await system.readModel()).threads.find(
607 (entry) => entry.id === "thread-turn-diff",
608 );
609 expect(thread?.checkpoints).toEqual([
610 {
611 turnId: asTurnId("turn-1"),
612 checkpointTurnCount: 1,
613 checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
614 status: "ready",
615 files: [],
616 assistantMessageId: null,
617 completedAt: createdAt,
618 },
619 ]);
620 await system.dispose();
621 });
622​
623 it("keeps processing queued commands after a storage failure", async () => {
624 type StoredEvent =
625 ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
626 ? A
627 : never;
628 const events: StoredEvent[] = [];
629 let nextSequence = 1;
630 let shouldFailFirstAppend = true;
631​
632 const flakyStore: OrchestrationEventStoreShape = {
633 append(event) {
634 if (shouldFailFirstAppend && event.commandId === CommandId.make("cmd-flaky-1")) {
635 shouldFailFirstAppend = false;
636 return Effect.fail(
637 new PersistenceSqlError({
638 operation: "test.append",
639 detail: "append failed",
640 }),
641 );
642 }
643 const savedEvent = {
644 ...event,
645 sequence: nextSequence,
646 } as StoredEvent;
647 nextSequence += 1;
648 events.push(savedEvent);
649 return Effect.succeed(savedEvent);
650 },
651 readFromSequence(sequenceExclusive) {
652 return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
653 },
654 readAll() {
655 return Stream.fromIterable(events);
656 },
657 };
658​
659 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
660 prefix: "t3-orchestration-engine-test-",
661 });
662​
663 const runtime = ManagedRuntime.make(
664 OrchestrationEngineLive.pipe(
665 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
666 Layer.provide(OrchestrationProjectionPipelineLive),
667 Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
668 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
669 Layer.provide(RepositoryIdentityResolverLive),
670 Layer.provide(SqlitePersistenceMemory),
671 Layer.provideMerge(ServerConfigLayer),
672 Layer.provideMerge(NodeServices.layer),
673 ),
674 );
675 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
676 const createdAt = now();
677​
678 await runtime.runPromise(
679 engine.dispatch({
680 type: "project.create",
681 commandId: CommandId.make("cmd-project-flaky-create"),
682 projectId: asProjectId("project-flaky"),
683 title: "Flaky Project",
684 workspaceRoot: "/tmp/project-flaky",
685 defaultModelSelection: {
686 instanceId: ProviderInstanceId.make("codex"),
687 model: "gpt-5-codex",
688 },
689 createdAt,
690 }),
691 );
692​
693 await expect(
694 runtime.runPromise(
695 engine.dispatch({
696 type: "thread.create",
697 commandId: CommandId.make("cmd-flaky-1"),
698 threadId: ThreadId.make("thread-flaky-fail"),
699 projectId: asProjectId("project-flaky"),
700 title: "flaky-fail",
701 modelSelection: {
702 instanceId: ProviderInstanceId.make("codex"),
703 model: "gpt-5-codex",
704 },
705 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
706 runtimeMode: "approval-required",
707 branch: null,
708 worktreePath: null,
709 createdAt,
710 }),
711 ),
712 ).rejects.toThrow("append failed");
713​
714 const result = await runtime.runPromise(
715 engine.dispatch({
716 type: "thread.create",
717 commandId: CommandId.make("cmd-flaky-2"),
718 threadId: ThreadId.make("thread-flaky-ok"),
719 projectId: asProjectId("project-flaky"),
720 title: "flaky-ok",
721 modelSelection: {
722 instanceId: ProviderInstanceId.make("codex"),
723 model: "gpt-5-codex",
724 },
725 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
726 runtimeMode: "approval-required",
727 branch: null,
728 worktreePath: null,
729 createdAt,
730 }),
731 );
732​
733 expect(result.sequence).toBe(2);
734 const eventsAfterRetry = await runtime.runPromise(
735 Stream.runCollect(engine.readEvents(0)).pipe(
736 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
737 ),
738 );
739 expect(eventsAfterRetry.map((event) => event.type)).toEqual([
740 "project.created",
741 "thread.created",
742 ]);
743 await runtime.dispose();
744 });
745​
746 it("rolls back all events for a multi-event command when projection fails mid-dispatch", async () => {
747 let shouldFailRequestedProjection = true;
748 const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {
749 bootstrap: Effect.void,
750 projectEvent: (event) => {
751 if (
752 shouldFailRequestedProjection &&
753 event.commandId === CommandId.make("cmd-turn-start-atomic") &&
754 event.type === "thread.turn-start-requested"
755 ) {
756 shouldFailRequestedProjection = false;
757 return Effect.fail(
758 new PersistenceSqlError({
759 operation: "test.projection",
760 detail: "projection failed",
761 }),
762 );
763 }
764 return Effect.void;
765 },
766 };
767​
768 const runtime = ManagedRuntime.make(
769 OrchestrationEngineLive.pipe(
770 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
771 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
772 Layer.provide(OrchestrationEventStoreLive),
773 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
774 Layer.provide(RepositoryIdentityResolverLive),
775 Layer.provide(SqlitePersistenceMemory),
776 ),
777 );
778 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
779 const createdAt = now();
780​
781 await runtime.runPromise(
782 engine.dispatch({
783 type: "project.create",
784 commandId: CommandId.make("cmd-project-atomic-create"),
785 projectId: asProjectId("project-atomic"),
786 title: "Atomic Project",
787 workspaceRoot: "/tmp/project-atomic",
788 defaultModelSelection: {
789 instanceId: ProviderInstanceId.make("codex"),
790 model: "gpt-5-codex",
791 },
792 createdAt,
793 }),
794 );
795 await runtime.runPromise(
796 engine.dispatch({
797 type: "thread.create",
798 commandId: CommandId.make("cmd-thread-atomic-create"),
799 threadId: ThreadId.make("thread-atomic"),
800 projectId: asProjectId("project-atomic"),
801 title: "atomic",
802 modelSelection: {
803 instanceId: ProviderInstanceId.make("codex"),
804 model: "gpt-5-codex",
805 },
806 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
807 runtimeMode: "approval-required",
808 branch: null,
809 worktreePath: null,
810 createdAt,
811 }),
812 );
813​
814 const turnStartCommand = {
815 type: "thread.turn.start" as const,
816 commandId: CommandId.make("cmd-turn-start-atomic"),
817 threadId: ThreadId.make("thread-atomic"),
818 message: {
819 messageId: asMessageId("msg-atomic-1"),
820 role: "user" as const,
821 text: "hello",
822 attachments: [],
823 },
824 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
825 runtimeMode: "approval-required" as const,
826 createdAt,
827 };
828​
829 await expect(runtime.runPromise(engine.dispatch(turnStartCommand))).rejects.toThrow(
830 "projection failed",
831 );
832​
833 const eventsAfterFailure = await runtime.runPromise(
834 Stream.runCollect(engine.readEvents(0)).pipe(
835 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
836 ),
837 );
838 expect(eventsAfterFailure.map((event) => event.type)).toEqual([
839 "project.created",
840 "thread.created",
841 ]);
842​
843 const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
844 expect(retryResult.sequence).toBe(4);
845​
846 const eventsAfterRetry = await runtime.runPromise(
847 Stream.runCollect(engine.readEvents(0)).pipe(
848 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
849 ),
850 );
851 expect(eventsAfterRetry.map((event) => event.type)).toEqual([
852 "project.created",
853 "thread.created",
854 "thread.message-sent",
855 "thread.turn-start-requested",
856 ]);
857 expect(
858 eventsAfterRetry.filter((event) => event.commandId === turnStartCommand.commandId),
859 ).toHaveLength(2);
860​
861 await runtime.dispose();
862 });
863​
864 it("reconciles command state when append persists but projection fails", async () => {
865 type StoredEvent =
866 ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
867 ? A
868 : never;
869 const events: StoredEvent[] = [];
870 let nextSequence = 1;
871​
872 const nonTransactionalStore: OrchestrationEventStoreShape = {
873 append(event) {
874 const savedEvent = {
875 ...event,
876 sequence: nextSequence,
877 } as StoredEvent;
878 nextSequence += 1;
879 events.push(savedEvent);
880 return Effect.succeed(savedEvent);
881 },
882 readFromSequence(sequenceExclusive) {
883 return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
884 },
885 readAll() {
886 return Stream.fromIterable(events);
887 },
888 };
889​
890 let shouldFailProjection = true;
891 const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {
892 bootstrap: Effect.void,
893 projectEvent: (event) => {
894 if (
895 shouldFailProjection &&
896 event.commandId === CommandId.make("cmd-thread-archive-sync-fail")
897 ) {
898 shouldFailProjection = false;
899 return Effect.fail(
900 new PersistenceSqlError({
901 operation: "test.projection",
902 detail: "projection failed",
903 }),
904 );
905 }
906 return Effect.void;
907 },
908 };
909​
910 const runtime = ManagedRuntime.make(
911 OrchestrationEngineLive.pipe(
912 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
913 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
914 Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
915 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
916 Layer.provide(RepositoryIdentityResolverLive),
917 Layer.provide(SqlitePersistenceMemory),
918 ),
919 );
920 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
921 const createdAt = now();
922​
923 await runtime.runPromise(
924 engine.dispatch({
925 type: "project.create",
926 commandId: CommandId.make("cmd-project-sync-create"),
927 projectId: asProjectId("project-sync"),
928 title: "Sync Project",
929 workspaceRoot: "/tmp/project-sync",
930 defaultModelSelection: {
931 instanceId: ProviderInstanceId.make("codex"),
932 model: "gpt-5-codex",
933 },
934 createdAt,
935 }),
936 );
937 await runtime.runPromise(
938 engine.dispatch({
939 type: "thread.create",
940 commandId: CommandId.make("cmd-thread-sync-create"),
941 threadId: ThreadId.make("thread-sync"),
942 projectId: asProjectId("project-sync"),
943 title: "sync-before",
944 modelSelection: {
945 instanceId: ProviderInstanceId.make("codex"),
946 model: "gpt-5-codex",
947 },
948 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
949 runtimeMode: "approval-required",
950 branch: null,
951 worktreePath: null,
952 createdAt,
953 }),
954 );
955​
956 await expect(
957 runtime.runPromise(
958 engine.dispatch({
959 type: "thread.archive",
960 commandId: CommandId.make("cmd-thread-archive-sync-fail"),
961 threadId: ThreadId.make("thread-sync"),
962 }),
963 ),
964 ).rejects.toThrow("projection failed");
965​
966 await expect(
967 runtime.runPromise(
968 engine.dispatch({
969 type: "thread.archive",
970 commandId: CommandId.make("cmd-thread-archive-sync-retry"),
971 threadId: ThreadId.make("thread-sync"),
972 }),
973 ),
974 ).rejects.toThrow("already archived");
975​
976 await runtime.dispose();
977 });
978​
979 it("fails command dispatch when command invariants are violated", async () => {
980 const system = await createOrchestrationSystem();
981 const { engine } = system;
982​
983 await expect(
984 system.run(
985 engine.dispatch({
986 type: "thread.turn.start",
987 commandId: CommandId.make("cmd-invariant-missing-thread"),
988 threadId: ThreadId.make("thread-missing"),
989 message: {
990 messageId: asMessageId("msg-missing"),
991 role: "user",
992 text: "hello",
993 attachments: [],
994 },
995 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
996 runtimeMode: "approval-required",
997 createdAt: now(),
998 }),
999 ),
1000 ).rejects.toThrow("Thread 'thread-missing' does not exist");
1001​
1002 await system.dispose();
1003 });
1004​
1005 it("rejects duplicate thread creation", async () => {
1006 const system = await createOrchestrationSystem();
1007 const { engine } = system;
1008 const createdAt = now();
1009​
1010 await system.run(
1011 engine.dispatch({
1012 type: "project.create",
1013 commandId: CommandId.make("cmd-project-duplicate-create"),
1014 projectId: asProjectId("project-duplicate"),
1015 title: "Duplicate Project",
1016 workspaceRoot: "/tmp/project-duplicate",
1017 defaultModelSelection: {
1018 instanceId: ProviderInstanceId.make("codex"),
1019 model: "gpt-5-codex",
1020 },
1021 createdAt,
1022 }),
1023 );
1024​
1025 await system.run(
1026 engine.dispatch({
1027 type: "thread.create",
1028 commandId: CommandId.make("cmd-thread-duplicate-1"),
1029 threadId: ThreadId.make("thread-duplicate"),
1030 projectId: asProjectId("project-duplicate"),
1031 title: "duplicate",
1032 modelSelection: {
1033 instanceId: ProviderInstanceId.make("codex"),
1034 model: "gpt-5-codex",
1035 },
1036 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1037 runtimeMode: "approval-required",
1038 branch: null,
1039 worktreePath: null,
1040 createdAt,
1041 }),
1042 );
1043​
1044 await expect(
1045 system.run(
1046 engine.dispatch({
1047 type: "thread.create",
1048 commandId: CommandId.make("cmd-thread-duplicate-2"),
1049 threadId: ThreadId.make("thread-duplicate"),
1050 projectId: asProjectId("project-duplicate"),
1051 title: "duplicate",
1052 modelSelection: {
1053 instanceId: ProviderInstanceId.make("codex"),
1054 model: "gpt-5-codex",
1055 },
1056 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1057 runtimeMode: "approval-required",
1058 branch: null,
1059 worktreePath: null,
1060 createdAt,
1061 }),
1062 ),
1063 ).rejects.toThrow("already exists");
1064​
1065 await system.dispose();
1066 });
1067});