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 settledOverride: null,
150 settledAt: null,
151 deletedAt: null,
152 messages: [],
153 proposedPlans: [],
154 activities: [],
155 checkpoints: [],
156 session: null,
157 },
158 ],
159 };
160 const commandReadModel = {
161 ...projectionSnapshot,
162 threads: projectionSnapshot.threads.map((thread) => ({
163 ...thread,
164 messages: [],
165 proposedPlans: [],
166 activities: [],
167 checkpoints: [],
168 })),
169 };
170 let fullSnapshotReadCount = 0;
171
172 const layer = OrchestrationEngineLive.pipe(
173 Layer.provide(
174 Layer.succeed(ProjectionSnapshotQuery, {
175 getCommandReadModel: () => Effect.succeed(commandReadModel),
176 getSnapshot: () =>
177 Effect.sync(() => {
178 fullSnapshotReadCount += 1;
179 return projectionSnapshot;
180 }),
181 getShellSnapshot: () =>
182 Effect.succeed({
183 snapshotSequence: projectionSnapshot.snapshotSequence,
184 projects: [],
185 threads: [],
186 updatedAt: projectionSnapshot.updatedAt,
187 }),
188 getArchivedShellSnapshot: () =>
189 Effect.succeed({
190 snapshotSequence: projectionSnapshot.snapshotSequence,
191 projects: [],
192 threads: [],
193 updatedAt: projectionSnapshot.updatedAt,
194 }),
195 getSnapshotSequence: () =>
196 Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
197 getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
198 getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
199 getProjectShellById: () => Effect.succeed(Option.none()),
200 getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
201 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
202 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
203 getThreadShellById: () => Effect.succeed(Option.none()),
204 getThreadDetailById: () => Effect.succeed(Option.none()),
205 getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
206 }),
207 ),
208 Layer.provide(
209 Layer.succeed(OrchestrationProjectionPipeline, {
210 bootstrap: Effect.void,
211 projectEvent: () => Effect.void,
212 } satisfies OrchestrationProjectionPipelineShape),
213 ),
214 Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
215 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
216 Layer.provide(SqlitePersistenceMemory),
217 Layer.provideMerge(NodeServices.layer),
218 );
219
220 const runtime = ManagedRuntime.make(layer);
221
222 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
223 expect(await runtime.runPromise(engine.latestSequence)).toBe(7);
224 const result = await runtime.runPromise(
225 engine.dispatch({
226 type: "thread.meta.update",
227 commandId: CommandId.make("cmd-bootstrap-thread-update"),
228 threadId: ThreadId.make("thread-bootstrap"),
229 title: "Updated Bootstrap Thread",
230 }),
231 );
232
233 expect(result.sequence).toBe(8);
234 expect(await runtime.runPromise(engine.latestSequence)).toBe(8);
235 expect(fullSnapshotReadCount).toBe(0);
236
237 await runtime.dispose();
238 });
239
240 it("persists deterministic read models for repeated snapshot reads", async () => {
241 const createdAt = now();
242 const system = await createOrchestrationSystem();
243 const { engine } = system;
244
245 await system.run(
246 engine.dispatch({
247 type: "project.create",
248 commandId: CommandId.make("cmd-project-1-create"),
249 projectId: asProjectId("project-1"),
250 title: "Project 1",
251 workspaceRoot: "/tmp/project-1",
252 defaultModelSelection: {
253 instanceId: ProviderInstanceId.make("codex"),
254 model: "gpt-5-codex",
255 },
256 createdAt,
257 }),
258 );
259 await system.run(
260 engine.dispatch({
261 type: "thread.create",
262 commandId: CommandId.make("cmd-thread-1-create"),
263 threadId: ThreadId.make("thread-1"),
264 projectId: asProjectId("project-1"),
265 title: "Thread",
266 modelSelection: {
267 instanceId: ProviderInstanceId.make("codex"),
268 model: "gpt-5-codex",
269 },
270 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
271 runtimeMode: "approval-required",
272 branch: null,
273 worktreePath: null,
274 createdAt,
275 }),
276 );
277 await system.run(
278 engine.dispatch({
279 type: "thread.turn.start",
280 commandId: CommandId.make("cmd-turn-start-1"),
281 threadId: ThreadId.make("thread-1"),
282 message: {
283 messageId: asMessageId("msg-1"),
284 role: "user",
285 text: "hello",
286 attachments: [],
287 },
288 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
289 runtimeMode: "approval-required",
290 createdAt,
291 }),
292 );
293
294 const readModelA = await system.readModel();
295 const readModelB = await system.readModel();
296 expect(readModelB).toEqual(readModelA);
297 await system.dispose();
298 });
299
300 it("archives and unarchives threads through orchestration commands", async () => {
301 const system = await createOrchestrationSystem();
302 const { engine } = system;
303 const createdAt = now();
304
305 await system.run(
306 engine.dispatch({
307 type: "project.create",
308 commandId: CommandId.make("cmd-project-archive-create"),
309 projectId: asProjectId("project-archive"),
310 title: "Project Archive",
311 workspaceRoot: "/tmp/project-archive",
312 defaultModelSelection: {
313 instanceId: ProviderInstanceId.make("codex"),
314 model: "gpt-5-codex",
315 },
316 createdAt,
317 }),
318 );
319 await system.run(
320 engine.dispatch({
321 type: "thread.create",
322 commandId: CommandId.make("cmd-thread-archive-create"),
323 threadId: ThreadId.make("thread-archive"),
324 projectId: asProjectId("project-archive"),
325 title: "Archive me",
326 modelSelection: {
327 instanceId: ProviderInstanceId.make("codex"),
328 model: "gpt-5-codex",
329 },
330 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
331 runtimeMode: "full-access",
332 branch: null,
333 worktreePath: null,
334 createdAt,
335 }),
336 );
337
338 await system.run(
339 engine.dispatch({
340 type: "thread.archive",
341 commandId: CommandId.make("cmd-thread-archive"),
342 threadId: ThreadId.make("thread-archive"),
343 }),
344 );
345 expect(
346 (await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
347 ?.archivedAt,
348 ).not.toBeNull();
349
350 await system.run(
351 engine.dispatch({
352 type: "thread.unarchive",
353 commandId: CommandId.make("cmd-thread-unarchive"),
354 threadId: ThreadId.make("thread-archive"),
355 }),
356 );
357 expect(
358 (await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
359 ?.archivedAt,
360 ).toBeNull();
361
362 await system.dispose();
363 });
364
365 it("replays append-only events from sequence", async () => {
366 const system = await createOrchestrationSystem();
367 const { engine } = system;
368 const createdAt = now();
369
370 await system.run(
371 engine.dispatch({
372 type: "project.create",
373 commandId: CommandId.make("cmd-project-replay-create"),
374 projectId: asProjectId("project-replay"),
375 title: "Replay Project",
376 workspaceRoot: "/tmp/project-replay",
377 defaultModelSelection: {
378 instanceId: ProviderInstanceId.make("codex"),
379 model: "gpt-5-codex",
380 },
381 createdAt,
382 }),
383 );
384 await system.run(
385 engine.dispatch({
386 type: "thread.create",
387 commandId: CommandId.make("cmd-thread-replay-create"),
388 threadId: ThreadId.make("thread-replay"),
389 projectId: asProjectId("project-replay"),
390 title: "replay",
391 modelSelection: {
392 instanceId: ProviderInstanceId.make("codex"),
393 model: "gpt-5-codex",
394 },
395 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
396 runtimeMode: "approval-required",
397 branch: null,
398 worktreePath: null,
399 createdAt,
400 }),
401 );
402 await system.run(
403 engine.dispatch({
404 type: "thread.delete",
405 commandId: CommandId.make("cmd-thread-replay-delete"),
406 threadId: ThreadId.make("thread-replay"),
407 }),
408 );
409
410 const events = await system.run(
411 Stream.runCollect(engine.readEvents(0)).pipe(
412 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
413 ),
414 );
415 expect(events.map((event) => event.type)).toEqual([
416 "project.created",
417 "thread.created",
418 "thread.deleted",
419 ]);
420 await system.dispose();
421 });
422
423 it("streams persisted domain events in order", async () => {
424 const system = await createOrchestrationSystem();
425 const { engine } = system;
426 const createdAt = now();
427
428 await system.run(
429 engine.dispatch({
430 type: "project.create",
431 commandId: CommandId.make("cmd-project-stream-create"),
432 projectId: asProjectId("project-stream"),
433 title: "Stream Project",
434 workspaceRoot: "/tmp/project-stream",
435 defaultModelSelection: {
436 instanceId: ProviderInstanceId.make("codex"),
437 model: "gpt-5-codex",
438 },
439 createdAt,
440 }),
441 );
442
443 const eventTypes: string[] = [];
444 await system.run(
445 Effect.gen(function* () {
446 const eventQueue = yield* Queue.unbounded<OrchestrationEvent>();
447 yield* Effect.forkScoped(
448 Stream.take(engine.streamDomainEvents, 2).pipe(
449 Stream.runForEach((event) => Queue.offer(eventQueue, event).pipe(Effect.asVoid)),
450 ),
451 );
452 yield* Effect.sleep("10 millis");
453 yield* engine.dispatch({
454 type: "thread.create",
455 commandId: CommandId.make("cmd-stream-thread-create"),
456 threadId: ThreadId.make("thread-stream"),
457 projectId: asProjectId("project-stream"),
458 title: "domain-stream",
459 modelSelection: {
460 instanceId: ProviderInstanceId.make("codex"),
461 model: "gpt-5-codex",
462 },
463 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
464 runtimeMode: "approval-required",
465 branch: null,
466 worktreePath: null,
467 createdAt,
468 });
469 yield* engine.dispatch({
470 type: "thread.meta.update",
471 commandId: CommandId.make("cmd-stream-thread-update"),
472 threadId: ThreadId.make("thread-stream"),
473 title: "domain-stream-updated",
474 });
475 eventTypes.push((yield* Queue.take(eventQueue)).type);
476 eventTypes.push((yield* Queue.take(eventQueue)).type);
477 }).pipe(Effect.scoped),
478 );
479
480 expect(eventTypes).toEqual(["thread.created", "thread.meta-updated"]);
481 await system.dispose();
482 });
483
484 it("does not regress a generated branch to a stale temporary worktree branch", async () => {
485 const system = await createOrchestrationSystem();
486 const { engine } = system;
487 const createdAt = now();
488
489 await system.run(
490 engine.dispatch({
491 type: "project.create",
492 commandId: CommandId.make("cmd-branch-race-project-create"),
493 projectId: asProjectId("project-branch-race"),
494 title: "Branch Race Project",
495 workspaceRoot: "/tmp/project-branch-race",
496 defaultModelSelection: {
497 instanceId: ProviderInstanceId.make("codex"),
498 model: "gpt-5-codex",
499 },
500 createdAt,
501 }),
502 );
503 await system.run(
504 engine.dispatch({
505 type: "thread.create",
506 commandId: CommandId.make("cmd-branch-race-thread-create"),
507 threadId: ThreadId.make("thread-branch-race"),
508 projectId: asProjectId("project-branch-race"),
509 title: "Branch Race Thread",
510 modelSelection: {
511 instanceId: ProviderInstanceId.make("codex"),
512 model: "gpt-5-codex",
513 },
514 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
515 runtimeMode: "approval-required",
516 branch: "t3code/generated-branch-name",
517 worktreePath: "/tmp/project-branch-race-worktree",
518 createdAt,
519 }),
520 );
521
522 await system.run(
523 engine.dispatch({
524 type: "thread.meta.update",
525 commandId: CommandId.make("cmd-stale-temporary-branch-sync"),
526 threadId: ThreadId.make("thread-branch-race"),
527 branch: "t3code/1234abcd",
528 expectedBranch: "t3code/1234abcd",
529 }),
530 );
531
532 const snapshot = await system.readModel();
533 expect(snapshot.threads[0]?.branch).toBe("t3code/generated-branch-name");
534 await system.dispose();
535 });
536
537 it("allows authoritative worktree bootstrap to assign a temporary branch", async () => {
538 const system = await createOrchestrationSystem();
539 const { engine } = system;
540 const createdAt = now();
541
542 await system.run(
543 engine.dispatch({
544 type: "project.create",
545 commandId: CommandId.make("cmd-worktree-bootstrap-project-create"),
546 projectId: asProjectId("project-worktree-bootstrap"),
547 title: "Worktree Bootstrap Project",
548 workspaceRoot: "/tmp/project-worktree-bootstrap",
549 defaultModelSelection: {
550 instanceId: ProviderInstanceId.make("codex"),
551 model: "gpt-5-codex",
552 },
553 createdAt,
554 }),
555 );
556 await system.run(
557 engine.dispatch({
558 type: "thread.create",
559 commandId: CommandId.make("cmd-worktree-bootstrap-thread-create"),
560 threadId: ThreadId.make("thread-worktree-bootstrap"),
561 projectId: asProjectId("project-worktree-bootstrap"),
562 title: "Worktree Bootstrap Thread",
563 modelSelection: {
564 instanceId: ProviderInstanceId.make("codex"),
565 model: "gpt-5-codex",
566 },
567 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
568 runtimeMode: "approval-required",
569 branch: "main",
570 worktreePath: null,
571 createdAt,
572 }),
573 );
574 await system.run(
575 engine.dispatch({
576 type: "thread.meta.update",
577 commandId: CommandId.make("cmd-authoritative-worktree-bootstrap"),
578 threadId: ThreadId.make("thread-worktree-bootstrap"),
579 branch: "t3code/1234abcd",
580 worktreePath: "/tmp/project-worktree-bootstrap-worktree",
581 }),
582 );
583
584 const snapshot = await system.readModel();
585 expect(snapshot.threads[0]?.branch).toBe("t3code/1234abcd");
586 expect(snapshot.threads[0]?.worktreePath).toBe("/tmp/project-worktree-bootstrap-worktree");
587 await system.dispose();
588 });
589
590 it("records command ack duration using the first committed event type", async () => {
591 const system = await createOrchestrationSystem();
592 const { engine } = system;
593 const createdAt = now();
594
595 await system.run(
596 engine.dispatch({
597 type: "project.create",
598 commandId: CommandId.make("cmd-project-ack-create"),
599 projectId: asProjectId("project-ack"),
600 title: "Ack Project",
601 workspaceRoot: "/tmp/project-ack",
602 defaultModelSelection: {
603 instanceId: ProviderInstanceId.make("codex"),
604 model: "gpt-5-codex",
605 },
606 createdAt,
607 }),
608 );
609
610 await system.run(
611 engine.dispatch({
612 type: "thread.create",
613 commandId: CommandId.make("cmd-thread-ack-create"),
614 threadId: ThreadId.make("thread-ack"),
615 projectId: asProjectId("project-ack"),
616 title: "Ack Thread",
617 modelSelection: {
618 instanceId: ProviderInstanceId.make("codex"),
619 model: "gpt-5-codex",
620 },
621 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
622 runtimeMode: "full-access",
623 branch: null,
624 worktreePath: null,
625 createdAt,
626 }),
627 );
628
629 const snapshots = await system.run(Metric.snapshot);
630 expect(
631 hasMetricSnapshot(snapshots, "t3_orchestration_command_ack_duration", {
632 commandType: "thread.create",
633 aggregateKind: "thread",
634 ackEventType: "thread.created",
635 }),
636 ).toBe(true);
637
638 await system.dispose();
639 });
640
641 it("records failed command dispatches as metric failures", async () => {
642 const system = await createOrchestrationSystem();
643 const { engine } = system;
644 const createdAt = now();
645
646 await expect(
647 system.run(
648 engine.dispatch({
649 type: "thread.create",
650 commandId: CommandId.make("cmd-thread-missing-project"),
651 threadId: ThreadId.make("thread-missing-project"),
652 projectId: asProjectId("project-missing"),
653 title: "Missing Project Thread",
654 modelSelection: {
655 instanceId: ProviderInstanceId.make("codex"),
656 model: "gpt-5-codex",
657 },
658 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
659 runtimeMode: "full-access",
660 branch: null,
661 worktreePath: null,
662 createdAt,
663 }),
664 ),
665 ).rejects.toThrow("does not exist");
666
667 const snapshots = await system.run(Metric.snapshot);
668 expect(
669 hasMetricSnapshot(snapshots, "t3_orchestration_commands_total", {
670 commandType: "thread.create",
671 aggregateKind: "thread",
672 outcome: "failure",
673 }),
674 ).toBe(true);
675
676 await system.dispose();
677 });
678
679 it("stores completed checkpoint summaries even when no files changed", async () => {
680 const system = await createOrchestrationSystem();
681 const { engine } = system;
682 const createdAt = now();
683
684 await system.run(
685 engine.dispatch({
686 type: "project.create",
687 commandId: CommandId.make("cmd-project-turn-diff-create"),
688 projectId: asProjectId("project-turn-diff"),
689 title: "Turn Diff Project",
690 workspaceRoot: "/tmp/project-turn-diff",
691 defaultModelSelection: {
692 instanceId: ProviderInstanceId.make("codex"),
693 model: "gpt-5-codex",
694 },
695 createdAt,
696 }),
697 );
698 await system.run(
699 engine.dispatch({
700 type: "thread.create",
701 commandId: CommandId.make("cmd-thread-turn-diff-create"),
702 threadId: ThreadId.make("thread-turn-diff"),
703 projectId: asProjectId("project-turn-diff"),
704 title: "Turn diff thread",
705 modelSelection: {
706 instanceId: ProviderInstanceId.make("codex"),
707 model: "gpt-5-codex",
708 },
709 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
710 runtimeMode: "approval-required",
711 branch: null,
712 worktreePath: null,
713 createdAt,
714 }),
715 );
716 await system.run(
717 engine.dispatch({
718 type: "thread.turn.diff.complete",
719 commandId: CommandId.make("cmd-turn-diff-complete"),
720 threadId: ThreadId.make("thread-turn-diff"),
721 turnId: asTurnId("turn-1"),
722 completedAt: createdAt,
723 checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
724 status: "ready",
725 files: [],
726 checkpointTurnCount: 1,
727 createdAt,
728 }),
729 );
730
731 const thread = (await system.readModel()).threads.find(
732 (entry) => entry.id === "thread-turn-diff",
733 );
734 expect(thread?.checkpoints).toEqual([
735 {
736 turnId: asTurnId("turn-1"),
737 checkpointTurnCount: 1,
738 checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
739 status: "ready",
740 files: [],
741 assistantMessageId: null,
742 completedAt: createdAt,
743 },
744 ]);
745 await system.dispose();
746 });
747
748 it("keeps processing queued commands after a storage failure", async () => {
749 type StoredEvent =
750 ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
751 ? A
752 : never;
753 const events: StoredEvent[] = [];
754 let nextSequence = 1;
755 let shouldFailFirstAppend = true;
756
757 const flakyStore: OrchestrationEventStoreShape = {
758 append(event) {
759 if (shouldFailFirstAppend && event.commandId === CommandId.make("cmd-flaky-1")) {
760 shouldFailFirstAppend = false;
761 return Effect.fail(
762 new PersistenceSqlError({
763 operation: "test.append",
764 detail: "append failed",
765 }),
766 );
767 }
768 const savedEvent = {
769 ...event,
770 sequence: nextSequence,
771 } as StoredEvent;
772 nextSequence += 1;
773 events.push(savedEvent);
774 return Effect.succeed(savedEvent);
775 },
776 readFromSequence(sequenceExclusive) {
777 return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
778 },
779 readAll() {
780 return Stream.fromIterable(events);
781 },
782 };
783
784 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
785 prefix: "t3-orchestration-engine-test-",
786 });
787
788 const runtime = ManagedRuntime.make(
789 OrchestrationEngineLive.pipe(
790 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
791 Layer.provide(OrchestrationProjectionPipelineLive),
792 Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
793 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
794 Layer.provide(RepositoryIdentityResolver.layer),
795 Layer.provide(SqlitePersistenceMemory),
796 Layer.provideMerge(ServerConfigLayer),
797 Layer.provideMerge(NodeServices.layer),
798 ),
799 );
800 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
801 const createdAt = now();
802
803 await runtime.runPromise(
804 engine.dispatch({
805 type: "project.create",
806 commandId: CommandId.make("cmd-project-flaky-create"),
807 projectId: asProjectId("project-flaky"),
808 title: "Flaky Project",
809 workspaceRoot: "/tmp/project-flaky",
810 defaultModelSelection: {
811 instanceId: ProviderInstanceId.make("codex"),
812 model: "gpt-5-codex",
813 },
814 createdAt,
815 }),
816 );
817
818 await expect(
819 runtime.runPromise(
820 engine.dispatch({
821 type: "thread.create",
822 commandId: CommandId.make("cmd-flaky-1"),
823 threadId: ThreadId.make("thread-flaky-fail"),
824 projectId: asProjectId("project-flaky"),
825 title: "flaky-fail",
826 modelSelection: {
827 instanceId: ProviderInstanceId.make("codex"),
828 model: "gpt-5-codex",
829 },
830 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
831 runtimeMode: "approval-required",
832 branch: null,
833 worktreePath: null,
834 createdAt,
835 }),
836 ),
837 ).rejects.toThrow("append failed");
838
839 const result = await runtime.runPromise(
840 engine.dispatch({
841 type: "thread.create",
842 commandId: CommandId.make("cmd-flaky-2"),
843 threadId: ThreadId.make("thread-flaky-ok"),
844 projectId: asProjectId("project-flaky"),
845 title: "flaky-ok",
846 modelSelection: {
847 instanceId: ProviderInstanceId.make("codex"),
848 model: "gpt-5-codex",
849 },
850 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
851 runtimeMode: "approval-required",
852 branch: null,
853 worktreePath: null,
854 createdAt,
855 }),
856 );
857
858 expect(result.sequence).toBe(2);
859 const eventsAfterRetry = await runtime.runPromise(
860 Stream.runCollect(engine.readEvents(0)).pipe(
861 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
862 ),
863 );
864 expect(eventsAfterRetry.map((event) => event.type)).toEqual([
865 "project.created",
866 "thread.created",
867 ]);
868 await runtime.dispose();
869 });
870
871 it("rolls back all events for a multi-event command when projection fails mid-dispatch", async () => {
872 let shouldFailRequestedProjection = true;
873 const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {
874 bootstrap: Effect.void,
875 projectEvent: (event) => {
876 if (
877 shouldFailRequestedProjection &&
878 event.commandId === CommandId.make("cmd-turn-start-atomic") &&
879 event.type === "thread.turn-start-requested"
880 ) {
881 shouldFailRequestedProjection = false;
882 return Effect.fail(
883 new PersistenceSqlError({
884 operation: "test.projection",
885 detail: "projection failed",
886 }),
887 );
888 }
889 return Effect.void;
890 },
891 };
892
893 const runtime = ManagedRuntime.make(
894 OrchestrationEngineLive.pipe(
895 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
896 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
897 Layer.provide(OrchestrationEventStoreLive),
898 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
899 Layer.provide(RepositoryIdentityResolver.layer),
900 Layer.provide(SqlitePersistenceMemory),
901 Layer.provide(NodeServices.layer),
902 ),
903 );
904 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
905 const createdAt = now();
906
907 await runtime.runPromise(
908 engine.dispatch({
909 type: "project.create",
910 commandId: CommandId.make("cmd-project-atomic-create"),
911 projectId: asProjectId("project-atomic"),
912 title: "Atomic Project",
913 workspaceRoot: "/tmp/project-atomic",
914 defaultModelSelection: {
915 instanceId: ProviderInstanceId.make("codex"),
916 model: "gpt-5-codex",
917 },
918 createdAt,
919 }),
920 );
921 await runtime.runPromise(
922 engine.dispatch({
923 type: "thread.create",
924 commandId: CommandId.make("cmd-thread-atomic-create"),
925 threadId: ThreadId.make("thread-atomic"),
926 projectId: asProjectId("project-atomic"),
927 title: "atomic",
928 modelSelection: {
929 instanceId: ProviderInstanceId.make("codex"),
930 model: "gpt-5-codex",
931 },
932 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
933 runtimeMode: "approval-required",
934 branch: null,
935 worktreePath: null,
936 createdAt,
937 }),
938 );
939
940 const turnStartCommand = {
941 type: "thread.turn.start" as const,
942 commandId: CommandId.make("cmd-turn-start-atomic"),
943 threadId: ThreadId.make("thread-atomic"),
944 message: {
945 messageId: asMessageId("msg-atomic-1"),
946 role: "user" as const,
947 text: "hello",
948 attachments: [],
949 },
950 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
951 runtimeMode: "approval-required" as const,
952 createdAt,
953 };
954
955 await expect(runtime.runPromise(engine.dispatch(turnStartCommand))).rejects.toThrow(
956 "projection failed",
957 );
958
959 const eventsAfterFailure = await runtime.runPromise(
960 Stream.runCollect(engine.readEvents(0)).pipe(
961 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
962 ),
963 );
964 expect(eventsAfterFailure.map((event) => event.type)).toEqual([
965 "project.created",
966 "thread.created",
967 ]);
968
969 const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
970 expect(retryResult.sequence).toBe(4);
971
972 const eventsAfterRetry = await runtime.runPromise(
973 Stream.runCollect(engine.readEvents(0)).pipe(
974 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
975 ),
976 );
977 expect(eventsAfterRetry.map((event) => event.type)).toEqual([
978 "project.created",
979 "thread.created",
980 "thread.message-sent",
981 "thread.turn-start-requested",
982 ]);
983 expect(
984 eventsAfterRetry.filter((event) => event.commandId === turnStartCommand.commandId),
985 ).toHaveLength(2);
986
987 await runtime.dispose();
988 });
989
990 it("reconciles command state when append persists but projection fails", async () => {
991 type StoredEvent =
992 ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
993 ? A
994 : never;
995 const events: StoredEvent[] = [];
996 let nextSequence = 1;
997
998 const nonTransactionalStore: OrchestrationEventStoreShape = {
999 append(event) {
1000 const savedEvent = {
1001 ...event,
1002 sequence: nextSequence,
1003 } as StoredEvent;
1004 nextSequence += 1;
1005 events.push(savedEvent);
1006 return Effect.succeed(savedEvent);
1007 },
1008 readFromSequence(sequenceExclusive) {
1009 return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
1010 },
1011 readAll() {
1012 return Stream.fromIterable(events);
1013 },
1014 };
1015
1016 let shouldFailProjection = true;
1017 const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {
1018 bootstrap: Effect.void,
1019 projectEvent: (event) => {
1020 if (
1021 shouldFailProjection &&
1022 event.commandId === CommandId.make("cmd-thread-archive-sync-fail")
1023 ) {
1024 shouldFailProjection = false;
1025 return Effect.fail(
1026 new PersistenceSqlError({
1027 operation: "test.projection",
1028 detail: "projection failed",
1029 }),
1030 );
1031 }
1032 return Effect.void;
1033 },
1034 };
1035
1036 const runtime = ManagedRuntime.make(
1037 OrchestrationEngineLive.pipe(
1038 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
1039 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
1040 Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
1041 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
1042 Layer.provide(RepositoryIdentityResolver.layer),
1043 Layer.provide(SqlitePersistenceMemory),
1044 Layer.provide(NodeServices.layer),
1045 ),
1046 );
1047 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
1048 const createdAt = now();
1049
1050 await runtime.runPromise(
1051 engine.dispatch({
1052 type: "project.create",
1053 commandId: CommandId.make("cmd-project-sync-create"),
1054 projectId: asProjectId("project-sync"),
1055 title: "Sync Project",
1056 workspaceRoot: "/tmp/project-sync",
1057 defaultModelSelection: {
1058 instanceId: ProviderInstanceId.make("codex"),
1059 model: "gpt-5-codex",
1060 },
1061 createdAt,
1062 }),
1063 );
1064 await runtime.runPromise(
1065 engine.dispatch({
1066 type: "thread.create",
1067 commandId: CommandId.make("cmd-thread-sync-create"),
1068 threadId: ThreadId.make("thread-sync"),
1069 projectId: asProjectId("project-sync"),
1070 title: "sync-before",
1071 modelSelection: {
1072 instanceId: ProviderInstanceId.make("codex"),
1073 model: "gpt-5-codex",
1074 },
1075 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1076 runtimeMode: "approval-required",
1077 branch: null,
1078 worktreePath: null,
1079 createdAt,
1080 }),
1081 );
1082
1083 await expect(
1084 runtime.runPromise(
1085 engine.dispatch({
1086 type: "thread.archive",
1087 commandId: CommandId.make("cmd-thread-archive-sync-fail"),
1088 threadId: ThreadId.make("thread-sync"),
1089 }),
1090 ),
1091 ).rejects.toThrow("projection failed");
1092
1093 await expect(
1094 runtime.runPromise(
1095 engine.dispatch({
1096 type: "thread.archive",
1097 commandId: CommandId.make("cmd-thread-archive-sync-retry"),
1098 threadId: ThreadId.make("thread-sync"),
1099 }),
1100 ),
1101 ).rejects.toThrow("already archived");
1102
1103 await runtime.dispose();
1104 });
1105
1106 it("fails command dispatch when command invariants are violated", async () => {
1107 const system = await createOrchestrationSystem();
1108 const { engine } = system;
1109
1110 await expect(
1111 system.run(
1112 engine.dispatch({
1113 type: "thread.turn.start",
1114 commandId: CommandId.make("cmd-invariant-missing-thread"),
1115 threadId: ThreadId.make("thread-missing"),
1116 message: {
1117 messageId: asMessageId("msg-missing"),
1118 role: "user",
1119 text: "hello",
1120 attachments: [],
1121 },
1122 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1123 runtimeMode: "approval-required",
1124 createdAt: now(),
1125 }),
1126 ),
1127 ).rejects.toThrow("Thread 'thread-missing' does not exist");
1128
1129 await system.dispose();
1130 });
1131
1132 it("rejects duplicate thread creation", async () => {
1133 const system = await createOrchestrationSystem();
1134 const { engine } = system;
1135 const createdAt = now();
1136
1137 await system.run(
1138 engine.dispatch({
1139 type: "project.create",
1140 commandId: CommandId.make("cmd-project-duplicate-create"),
1141 projectId: asProjectId("project-duplicate"),
1142 title: "Duplicate Project",
1143 workspaceRoot: "/tmp/project-duplicate",
1144 defaultModelSelection: {
1145 instanceId: ProviderInstanceId.make("codex"),
1146 model: "gpt-5-codex",
1147 },
1148 createdAt,
1149 }),
1150 );
1151
1152 await system.run(
1153 engine.dispatch({
1154 type: "thread.create",
1155 commandId: CommandId.make("cmd-thread-duplicate-1"),
1156 threadId: ThreadId.make("thread-duplicate"),
1157 projectId: asProjectId("project-duplicate"),
1158 title: "duplicate",
1159 modelSelection: {
1160 instanceId: ProviderInstanceId.make("codex"),
1161 model: "gpt-5-codex",
1162 },
1163 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1164 runtimeMode: "approval-required",
1165 branch: null,
1166 worktreePath: null,
1167 createdAt,
1168 }),
1169 );
1170
1171 await expect(
1172 system.run(
1173 engine.dispatch({
1174 type: "thread.create",
1175 commandId: CommandId.make("cmd-thread-duplicate-2"),
1176 threadId: ThreadId.make("thread-duplicate"),
1177 projectId: asProjectId("project-duplicate"),
1178 title: "duplicate",
1179 modelSelection: {
1180 instanceId: ProviderInstanceId.make("codex"),
1181 model: "gpt-5-codex",
1182 },
1183 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1184 runtimeMode: "approval-required",
1185 branch: null,
1186 worktreePath: null,
1187 createdAt,
1188 }),
1189 ),
1190 ).rejects.toThrow("already exists");
1191
1192 await system.dispose();
1193 });
1194});