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