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