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 * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
35import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
36import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
37import {
38 OrchestrationProjectionPipeline,
39 type OrchestrationProjectionPipelineShape,
40} from "../Services/ProjectionPipeline.ts";
41import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
42import { ServerConfig } from "../../config.ts";
43
44const asProjectId = (value: string): ProjectId => ProjectId.make(value);
45const asMessageId = (value: string): MessageId => MessageId.make(value);
46const asTurnId = (value: string): TurnId => TurnId.make(value);
47const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
48
49async function createOrchestrationSystem() {
50 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
51 prefix: "t3-orchestration-engine-test-",
52 });
53 const orchestrationLayer = Layer.mergeAll(
54 OrchestrationEngineLive.pipe(
55 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
56 Layer.provide(OrchestrationProjectionPipelineLive),
57 ),
58 OrchestrationProjectionSnapshotQueryLive,
59 ).pipe(
60 Layer.provide(ThreadBackgroundLiveness.layer),
61 Layer.provide(ThreadPlanProgress.layer),
62 Layer.provide(OrchestrationEventStoreLive),
63 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
64 Layer.provide(RepositoryIdentityResolver.layer),
65 Layer.provide(SqlitePersistenceMemory),
66 Layer.provideMerge(ServerConfigLayer),
67 Layer.provideMerge(NodeServices.layer),
68 );
69 const runtime = ManagedRuntime.make(orchestrationLayer);
70 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
71 const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery));
72 return {
73 engine,
74 readModel: () => runtime.runPromise(snapshotQuery.getSnapshot()),
75 run: <A, E>(effect: Effect.Effect<A, E>) => runtime.runPromise(effect),
76 dispose: () => runtime.dispose(),
77 };
78}
79
80function now() {
81 return "2026-01-01T00:00:00.000Z";
82}
83
84const hasMetricSnapshot = (
85 snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
86 id: string,
87 attributes: Readonly<Record<string, string>>,
88) =>
89 snapshots.some(
90 (snapshot) =>
91 snapshot.id === id &&
92 Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
93 );
94
95describe("OrchestrationEngine", () => {
96 it("bootstraps command handling from persisted projections without reading the full snapshot", async () => {
97 let nextSequence = 8;
98 const eventStore: OrchestrationEventStoreShape = {
99 append: (event) =>
100 Effect.sync(() => {
101 const savedEvent = {
102 ...event,
103 sequence: nextSequence,
104 } as OrchestrationEvent;
105 nextSequence += 1;
106 return savedEvent;
107 }),
108 readFromSequence: () => Stream.empty,
109 readAll: () =>
110 Stream.fail(
111 new PersistenceSqlError({
112 operation: "test.readAll",
113 detail: "historical replay should not be used during bootstrap",
114 }),
115 ),
116 };
117
118 const projectionSnapshot = {
119 snapshotSequence: 7,
120 updatedAt: "2026-03-03T00:00:04.000Z",
121 projects: [
122 {
123 id: asProjectId("project-bootstrap"),
124 title: "Bootstrap Project",
125 workspaceRoot: "/tmp/project-bootstrap",
126 defaultModelSelection: {
127 instanceId: ProviderInstanceId.make("codex"),
128 model: "gpt-5-codex",
129 },
130 scripts: [],
131 createdAt: "2026-03-03T00:00:00.000Z",
132 updatedAt: "2026-03-03T00:00:01.000Z",
133 deletedAt: null,
134 },
135 ],
136 threads: [
137 {
138 id: ThreadId.make("thread-bootstrap"),
139 projectId: asProjectId("project-bootstrap"),
140 title: "Bootstrap Thread",
141 modelSelection: {
142 instanceId: ProviderInstanceId.make("codex"),
143 model: "gpt-5-codex",
144 },
145 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
146 runtimeMode: "full-access" as const,
147 branch: null,
148 worktreePath: null,
149 latestTurn: null,
150 createdAt: "2026-03-03T00:00:02.000Z",
151 updatedAt: "2026-03-03T00:00:03.000Z",
152 archivedAt: null,
153 settledOverride: null,
154 settledAt: null,
155 deletedAt: null,
156 messages: [],
157 proposedPlans: [],
158 activities: [],
159 checkpoints: [],
160 session: null,
161 },
162 ],
163 };
164 const commandReadModel = {
165 ...projectionSnapshot,
166 threads: projectionSnapshot.threads.map((thread) => ({
167 ...thread,
168 messages: [],
169 proposedPlans: [],
170 activities: [],
171 checkpoints: [],
172 })),
173 };
174 let fullSnapshotReadCount = 0;
175
176 const layer = OrchestrationEngineLive.pipe(
177 Layer.provide(
178 Layer.succeed(ProjectionSnapshotQuery, {
179 getCommandReadModel: () => Effect.succeed(commandReadModel),
180 getSnapshot: () =>
181 Effect.sync(() => {
182 fullSnapshotReadCount += 1;
183 return projectionSnapshot;
184 }),
185 getShellSnapshot: () =>
186 Effect.succeed({
187 snapshotSequence: projectionSnapshot.snapshotSequence,
188 projects: [],
189 threads: [],
190 updatedAt: projectionSnapshot.updatedAt,
191 }),
192 getArchivedShellSnapshot: () =>
193 Effect.succeed({
194 snapshotSequence: projectionSnapshot.snapshotSequence,
195 projects: [],
196 threads: [],
197 updatedAt: projectionSnapshot.updatedAt,
198 }),
199 getSnapshotSequence: () =>
200 Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
201 getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
202 getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
203 getProjectShellById: () => Effect.succeed(Option.none()),
204 getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
205 getThreadCheckpointContext: () => Effect.succeed(Option.none()),
206 getFullThreadDiffContext: () => Effect.succeed(Option.none()),
207 getThreadShellById: () => Effect.succeed(Option.none()),
208 getThreadDetailById: () => Effect.succeed(Option.none()),
209 getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
210 searchThreads: () => Effect.succeed({ matches: [] }),
211 }),
212 ),
213 Layer.provide(
214 Layer.succeed(OrchestrationProjectionPipeline, {
215 bootstrap: Effect.void,
216 projectEvent: () => Effect.void,
217 } satisfies OrchestrationProjectionPipelineShape),
218 ),
219 Layer.provide(Layer.succeed(OrchestrationEventStore, eventStore)),
220 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
221 Layer.provide(SqlitePersistenceMemory),
222 Layer.provideMerge(NodeServices.layer),
223 );
224
225 const runtime = ManagedRuntime.make(layer);
226
227 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
228 expect(await runtime.runPromise(engine.latestSequence)).toBe(7);
229 const result = await runtime.runPromise(
230 engine.dispatch({
231 type: "thread.meta.update",
232 commandId: CommandId.make("cmd-bootstrap-thread-update"),
233 threadId: ThreadId.make("thread-bootstrap"),
234 title: "Updated Bootstrap Thread",
235 }),
236 );
237
238 expect(result.sequence).toBe(8);
239 expect(await runtime.runPromise(engine.latestSequence)).toBe(8);
240 expect(fullSnapshotReadCount).toBe(0);
241
242 await runtime.dispose();
243 });
244
245 it("persists deterministic read models for repeated snapshot reads", async () => {
246 const createdAt = now();
247 const system = await createOrchestrationSystem();
248 const { engine } = system;
249
250 await system.run(
251 engine.dispatch({
252 type: "project.create",
253 commandId: CommandId.make("cmd-project-1-create"),
254 projectId: asProjectId("project-1"),
255 title: "Project 1",
256 workspaceRoot: "/tmp/project-1",
257 defaultModelSelection: {
258 instanceId: ProviderInstanceId.make("codex"),
259 model: "gpt-5-codex",
260 },
261 createdAt,
262 }),
263 );
264 await system.run(
265 engine.dispatch({
266 type: "thread.create",
267 commandId: CommandId.make("cmd-thread-1-create"),
268 threadId: ThreadId.make("thread-1"),
269 projectId: asProjectId("project-1"),
270 title: "Thread",
271 modelSelection: {
272 instanceId: ProviderInstanceId.make("codex"),
273 model: "gpt-5-codex",
274 },
275 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
276 runtimeMode: "approval-required",
277 branch: null,
278 worktreePath: null,
279 createdAt,
280 }),
281 );
282 await system.run(
283 engine.dispatch({
284 type: "thread.turn.start",
285 commandId: CommandId.make("cmd-turn-start-1"),
286 threadId: ThreadId.make("thread-1"),
287 message: {
288 messageId: asMessageId("msg-1"),
289 role: "user",
290 text: "hello",
291 attachments: [],
292 },
293 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
294 runtimeMode: "approval-required",
295 createdAt,
296 }),
297 );
298
299 const readModelA = await system.readModel();
300 const readModelB = await system.readModel();
301 expect(readModelB).toEqual(readModelA);
302 await system.dispose();
303 });
304
305 it("archives and unarchives threads through orchestration commands", async () => {
306 const system = await createOrchestrationSystem();
307 const { engine } = system;
308 const createdAt = now();
309
310 await system.run(
311 engine.dispatch({
312 type: "project.create",
313 commandId: CommandId.make("cmd-project-archive-create"),
314 projectId: asProjectId("project-archive"),
315 title: "Project Archive",
316 workspaceRoot: "/tmp/project-archive",
317 defaultModelSelection: {
318 instanceId: ProviderInstanceId.make("codex"),
319 model: "gpt-5-codex",
320 },
321 createdAt,
322 }),
323 );
324 await system.run(
325 engine.dispatch({
326 type: "thread.create",
327 commandId: CommandId.make("cmd-thread-archive-create"),
328 threadId: ThreadId.make("thread-archive"),
329 projectId: asProjectId("project-archive"),
330 title: "Archive me",
331 modelSelection: {
332 instanceId: ProviderInstanceId.make("codex"),
333 model: "gpt-5-codex",
334 },
335 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
336 runtimeMode: "full-access",
337 branch: null,
338 worktreePath: null,
339 createdAt,
340 }),
341 );
342
343 await system.run(
344 engine.dispatch({
345 type: "thread.meta.update",
346 commandId: CommandId.make("cmd-thread-archive-title-regeneration"),
347 threadId: ThreadId.make("thread-archive"),
348 regenerateTitle: true,
349 }),
350 );
351 await system.run(
352 engine.dispatch({
353 type: "thread.archive",
354 commandId: CommandId.make("cmd-thread-archive"),
355 threadId: ThreadId.make("thread-archive"),
356 }),
357 );
358 expect(
359 (await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
360 ?.archivedAt,
361 ).not.toBeNull();
362 expect(
363 (await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
364 ?.titleRegeneration,
365 ).toBeNull();
366
367 await system.run(
368 engine.dispatch({
369 type: "thread.unarchive",
370 commandId: CommandId.make("cmd-thread-unarchive"),
371 threadId: ThreadId.make("thread-archive"),
372 }),
373 );
374 expect(
375 (await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
376 ?.archivedAt,
377 ).toBeNull();
378 expect(
379 (await system.readModel()).threads.find((thread) => thread.id === "thread-archive")
380 ?.titleRegeneration,
381 ).toBeNull();
382 await system.run(
383 engine.dispatch({
384 type: "thread.title.regeneration.complete",
385 commandId: CommandId.make("cmd-thread-archive-stale-title-completion"),
386 threadId: ThreadId.make("thread-archive"),
387 requestId: CommandId.make("cmd-thread-archive-title-regeneration"),
388 title: "Stale generated title",
389 }),
390 );
391 expect(
392 (await system.readModel()).threads.find((thread) => thread.id === "thread-archive")?.title,
393 ).toBe("Archive me");
394
395 await system.dispose();
396 });
397
398 it("replays append-only events from sequence", async () => {
399 const system = await createOrchestrationSystem();
400 const { engine } = system;
401 const createdAt = now();
402
403 await system.run(
404 engine.dispatch({
405 type: "project.create",
406 commandId: CommandId.make("cmd-project-replay-create"),
407 projectId: asProjectId("project-replay"),
408 title: "Replay Project",
409 workspaceRoot: "/tmp/project-replay",
410 defaultModelSelection: {
411 instanceId: ProviderInstanceId.make("codex"),
412 model: "gpt-5-codex",
413 },
414 createdAt,
415 }),
416 );
417 await system.run(
418 engine.dispatch({
419 type: "thread.create",
420 commandId: CommandId.make("cmd-thread-replay-create"),
421 threadId: ThreadId.make("thread-replay"),
422 projectId: asProjectId("project-replay"),
423 title: "replay",
424 modelSelection: {
425 instanceId: ProviderInstanceId.make("codex"),
426 model: "gpt-5-codex",
427 },
428 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
429 runtimeMode: "approval-required",
430 branch: null,
431 worktreePath: null,
432 createdAt,
433 }),
434 );
435 await system.run(
436 engine.dispatch({
437 type: "thread.delete",
438 commandId: CommandId.make("cmd-thread-replay-delete"),
439 threadId: ThreadId.make("thread-replay"),
440 }),
441 );
442
443 const events = await system.run(
444 Stream.runCollect(engine.readEvents(0)).pipe(
445 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
446 ),
447 );
448 expect(events.map((event) => event.type)).toEqual([
449 "project.created",
450 "thread.created",
451 "thread.deleted",
452 ]);
453 await system.dispose();
454 });
455
456 it("streams persisted domain events in order", async () => {
457 const system = await createOrchestrationSystem();
458 const { engine } = system;
459 const createdAt = now();
460
461 await system.run(
462 engine.dispatch({
463 type: "project.create",
464 commandId: CommandId.make("cmd-project-stream-create"),
465 projectId: asProjectId("project-stream"),
466 title: "Stream Project",
467 workspaceRoot: "/tmp/project-stream",
468 defaultModelSelection: {
469 instanceId: ProviderInstanceId.make("codex"),
470 model: "gpt-5-codex",
471 },
472 createdAt,
473 }),
474 );
475
476 const eventTypes: string[] = [];
477 await system.run(
478 Effect.gen(function* () {
479 const eventQueue = yield* Queue.unbounded<OrchestrationEvent>();
480 yield* Effect.forkScoped(
481 Stream.take(engine.streamDomainEvents, 2).pipe(
482 Stream.runForEach((event) => Queue.offer(eventQueue, event).pipe(Effect.asVoid)),
483 ),
484 );
485 yield* Effect.sleep("10 millis");
486 yield* engine.dispatch({
487 type: "thread.create",
488 commandId: CommandId.make("cmd-stream-thread-create"),
489 threadId: ThreadId.make("thread-stream"),
490 projectId: asProjectId("project-stream"),
491 title: "domain-stream",
492 modelSelection: {
493 instanceId: ProviderInstanceId.make("codex"),
494 model: "gpt-5-codex",
495 },
496 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
497 runtimeMode: "approval-required",
498 branch: null,
499 worktreePath: null,
500 createdAt,
501 });
502 yield* engine.dispatch({
503 type: "thread.meta.update",
504 commandId: CommandId.make("cmd-stream-thread-update"),
505 threadId: ThreadId.make("thread-stream"),
506 title: "domain-stream-updated",
507 });
508 eventTypes.push((yield* Queue.take(eventQueue)).type);
509 eventTypes.push((yield* Queue.take(eventQueue)).type);
510 }).pipe(Effect.scoped),
511 );
512
513 expect(eventTypes).toEqual(["thread.created", "thread.meta-updated"]);
514 await system.dispose();
515 });
516
517 it("does not regress a generated branch to a stale temporary worktree branch", async () => {
518 const system = await createOrchestrationSystem();
519 const { engine } = system;
520 const createdAt = now();
521
522 await system.run(
523 engine.dispatch({
524 type: "project.create",
525 commandId: CommandId.make("cmd-branch-race-project-create"),
526 projectId: asProjectId("project-branch-race"),
527 title: "Branch Race Project",
528 workspaceRoot: "/tmp/project-branch-race",
529 defaultModelSelection: {
530 instanceId: ProviderInstanceId.make("codex"),
531 model: "gpt-5-codex",
532 },
533 createdAt,
534 }),
535 );
536 await system.run(
537 engine.dispatch({
538 type: "thread.create",
539 commandId: CommandId.make("cmd-branch-race-thread-create"),
540 threadId: ThreadId.make("thread-branch-race"),
541 projectId: asProjectId("project-branch-race"),
542 title: "Branch Race Thread",
543 modelSelection: {
544 instanceId: ProviderInstanceId.make("codex"),
545 model: "gpt-5-codex",
546 },
547 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
548 runtimeMode: "approval-required",
549 branch: "t3code/generated-branch-name",
550 worktreePath: "/tmp/project-branch-race-worktree",
551 createdAt,
552 }),
553 );
554
555 await system.run(
556 engine.dispatch({
557 type: "thread.meta.update",
558 commandId: CommandId.make("cmd-stale-temporary-branch-sync"),
559 threadId: ThreadId.make("thread-branch-race"),
560 branch: "t3code/1234abcd",
561 expectedBranch: "t3code/1234abcd",
562 }),
563 );
564
565 const snapshot = await system.readModel();
566 expect(snapshot.threads[0]?.branch).toBe("t3code/generated-branch-name");
567 await system.dispose();
568 });
569
570 it("allows authoritative worktree bootstrap to assign a temporary branch", async () => {
571 const system = await createOrchestrationSystem();
572 const { engine } = system;
573 const createdAt = now();
574
575 await system.run(
576 engine.dispatch({
577 type: "project.create",
578 commandId: CommandId.make("cmd-worktree-bootstrap-project-create"),
579 projectId: asProjectId("project-worktree-bootstrap"),
580 title: "Worktree Bootstrap Project",
581 workspaceRoot: "/tmp/project-worktree-bootstrap",
582 defaultModelSelection: {
583 instanceId: ProviderInstanceId.make("codex"),
584 model: "gpt-5-codex",
585 },
586 createdAt,
587 }),
588 );
589 await system.run(
590 engine.dispatch({
591 type: "thread.create",
592 commandId: CommandId.make("cmd-worktree-bootstrap-thread-create"),
593 threadId: ThreadId.make("thread-worktree-bootstrap"),
594 projectId: asProjectId("project-worktree-bootstrap"),
595 title: "Worktree Bootstrap Thread",
596 modelSelection: {
597 instanceId: ProviderInstanceId.make("codex"),
598 model: "gpt-5-codex",
599 },
600 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
601 runtimeMode: "approval-required",
602 branch: "main",
603 worktreePath: null,
604 createdAt,
605 }),
606 );
607 await system.run(
608 engine.dispatch({
609 type: "thread.meta.update",
610 commandId: CommandId.make("cmd-authoritative-worktree-bootstrap"),
611 threadId: ThreadId.make("thread-worktree-bootstrap"),
612 branch: "t3code/1234abcd",
613 worktreePath: "/tmp/project-worktree-bootstrap-worktree",
614 }),
615 );
616
617 const snapshot = await system.readModel();
618 expect(snapshot.threads[0]?.branch).toBe("t3code/1234abcd");
619 expect(snapshot.threads[0]?.worktreePath).toBe("/tmp/project-worktree-bootstrap-worktree");
620 await system.dispose();
621 });
622
623 it("records command ack duration using the first committed event type", async () => {
624 const system = await createOrchestrationSystem();
625 const { engine } = system;
626 const createdAt = now();
627
628 await system.run(
629 engine.dispatch({
630 type: "project.create",
631 commandId: CommandId.make("cmd-project-ack-create"),
632 projectId: asProjectId("project-ack"),
633 title: "Ack Project",
634 workspaceRoot: "/tmp/project-ack",
635 defaultModelSelection: {
636 instanceId: ProviderInstanceId.make("codex"),
637 model: "gpt-5-codex",
638 },
639 createdAt,
640 }),
641 );
642
643 await system.run(
644 engine.dispatch({
645 type: "thread.create",
646 commandId: CommandId.make("cmd-thread-ack-create"),
647 threadId: ThreadId.make("thread-ack"),
648 projectId: asProjectId("project-ack"),
649 title: "Ack Thread",
650 modelSelection: {
651 instanceId: ProviderInstanceId.make("codex"),
652 model: "gpt-5-codex",
653 },
654 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
655 runtimeMode: "full-access",
656 branch: null,
657 worktreePath: null,
658 createdAt,
659 }),
660 );
661
662 const snapshots = await system.run(Metric.snapshot);
663 expect(
664 hasMetricSnapshot(snapshots, "t3_orchestration_command_ack_duration", {
665 commandType: "thread.create",
666 aggregateKind: "thread",
667 ackEventType: "thread.created",
668 }),
669 ).toBe(true);
670
671 await system.dispose();
672 });
673
674 it("records failed command dispatches as metric failures", async () => {
675 const system = await createOrchestrationSystem();
676 const { engine } = system;
677 const createdAt = now();
678
679 await expect(
680 system.run(
681 engine.dispatch({
682 type: "thread.create",
683 commandId: CommandId.make("cmd-thread-missing-project"),
684 threadId: ThreadId.make("thread-missing-project"),
685 projectId: asProjectId("project-missing"),
686 title: "Missing Project Thread",
687 modelSelection: {
688 instanceId: ProviderInstanceId.make("codex"),
689 model: "gpt-5-codex",
690 },
691 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
692 runtimeMode: "full-access",
693 branch: null,
694 worktreePath: null,
695 createdAt,
696 }),
697 ),
698 ).rejects.toThrow("does not exist");
699
700 const snapshots = await system.run(Metric.snapshot);
701 expect(
702 hasMetricSnapshot(snapshots, "t3_orchestration_commands_total", {
703 commandType: "thread.create",
704 aggregateKind: "thread",
705 outcome: "failure",
706 }),
707 ).toBe(true);
708
709 await system.dispose();
710 });
711
712 it("stores completed checkpoint summaries even when no files changed", async () => {
713 const system = await createOrchestrationSystem();
714 const { engine } = system;
715 const createdAt = now();
716
717 await system.run(
718 engine.dispatch({
719 type: "project.create",
720 commandId: CommandId.make("cmd-project-turn-diff-create"),
721 projectId: asProjectId("project-turn-diff"),
722 title: "Turn Diff Project",
723 workspaceRoot: "/tmp/project-turn-diff",
724 defaultModelSelection: {
725 instanceId: ProviderInstanceId.make("codex"),
726 model: "gpt-5-codex",
727 },
728 createdAt,
729 }),
730 );
731 await system.run(
732 engine.dispatch({
733 type: "thread.create",
734 commandId: CommandId.make("cmd-thread-turn-diff-create"),
735 threadId: ThreadId.make("thread-turn-diff"),
736 projectId: asProjectId("project-turn-diff"),
737 title: "Turn diff thread",
738 modelSelection: {
739 instanceId: ProviderInstanceId.make("codex"),
740 model: "gpt-5-codex",
741 },
742 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
743 runtimeMode: "approval-required",
744 branch: null,
745 worktreePath: null,
746 createdAt,
747 }),
748 );
749 await system.run(
750 engine.dispatch({
751 type: "thread.turn.diff.complete",
752 commandId: CommandId.make("cmd-turn-diff-complete"),
753 threadId: ThreadId.make("thread-turn-diff"),
754 turnId: asTurnId("turn-1"),
755 completedAt: createdAt,
756 checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
757 status: "ready",
758 files: [],
759 checkpointTurnCount: 1,
760 createdAt,
761 }),
762 );
763
764 const thread = (await system.readModel()).threads.find(
765 (entry) => entry.id === "thread-turn-diff",
766 );
767 expect(thread?.checkpoints).toEqual([
768 {
769 turnId: asTurnId("turn-1"),
770 checkpointTurnCount: 1,
771 checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
772 status: "ready",
773 files: [],
774 assistantMessageId: null,
775 completedAt: createdAt,
776 },
777 ]);
778 await system.dispose();
779 });
780
781 it("keeps processing queued commands after a storage failure", async () => {
782 type StoredEvent =
783 ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
784 ? A
785 : never;
786 const events: StoredEvent[] = [];
787 let nextSequence = 1;
788 let shouldFailFirstAppend = true;
789
790 const flakyStore: OrchestrationEventStoreShape = {
791 append(event) {
792 if (shouldFailFirstAppend && event.commandId === CommandId.make("cmd-flaky-1")) {
793 shouldFailFirstAppend = false;
794 return Effect.fail(
795 new PersistenceSqlError({
796 operation: "test.append",
797 detail: "append failed",
798 }),
799 );
800 }
801 const savedEvent = {
802 ...event,
803 sequence: nextSequence,
804 } as StoredEvent;
805 nextSequence += 1;
806 events.push(savedEvent);
807 return Effect.succeed(savedEvent);
808 },
809 readFromSequence(sequenceExclusive) {
810 return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
811 },
812 readAll() {
813 return Stream.fromIterable(events);
814 },
815 };
816
817 const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
818 prefix: "t3-orchestration-engine-test-",
819 });
820
821 const runtime = ManagedRuntime.make(
822 OrchestrationEngineLive.pipe(
823 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
824 Layer.provide(ThreadBackgroundLiveness.layer),
825 Layer.provide(ThreadPlanProgress.layer),
826 Layer.provide(OrchestrationProjectionPipelineLive),
827 Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
828 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
829 Layer.provide(RepositoryIdentityResolver.layer),
830 Layer.provide(SqlitePersistenceMemory),
831 Layer.provideMerge(ServerConfigLayer),
832 Layer.provideMerge(NodeServices.layer),
833 ),
834 );
835 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
836 const createdAt = now();
837
838 await runtime.runPromise(
839 engine.dispatch({
840 type: "project.create",
841 commandId: CommandId.make("cmd-project-flaky-create"),
842 projectId: asProjectId("project-flaky"),
843 title: "Flaky Project",
844 workspaceRoot: "/tmp/project-flaky",
845 defaultModelSelection: {
846 instanceId: ProviderInstanceId.make("codex"),
847 model: "gpt-5-codex",
848 },
849 createdAt,
850 }),
851 );
852
853 await expect(
854 runtime.runPromise(
855 engine.dispatch({
856 type: "thread.create",
857 commandId: CommandId.make("cmd-flaky-1"),
858 threadId: ThreadId.make("thread-flaky-fail"),
859 projectId: asProjectId("project-flaky"),
860 title: "flaky-fail",
861 modelSelection: {
862 instanceId: ProviderInstanceId.make("codex"),
863 model: "gpt-5-codex",
864 },
865 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
866 runtimeMode: "approval-required",
867 branch: null,
868 worktreePath: null,
869 createdAt,
870 }),
871 ),
872 ).rejects.toThrow("append failed");
873
874 const result = await runtime.runPromise(
875 engine.dispatch({
876 type: "thread.create",
877 commandId: CommandId.make("cmd-flaky-2"),
878 threadId: ThreadId.make("thread-flaky-ok"),
879 projectId: asProjectId("project-flaky"),
880 title: "flaky-ok",
881 modelSelection: {
882 instanceId: ProviderInstanceId.make("codex"),
883 model: "gpt-5-codex",
884 },
885 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
886 runtimeMode: "approval-required",
887 branch: null,
888 worktreePath: null,
889 createdAt,
890 }),
891 );
892
893 expect(result.sequence).toBe(2);
894 const eventsAfterRetry = await runtime.runPromise(
895 Stream.runCollect(engine.readEvents(0)).pipe(
896 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
897 ),
898 );
899 expect(eventsAfterRetry.map((event) => event.type)).toEqual([
900 "project.created",
901 "thread.created",
902 ]);
903 await runtime.dispose();
904 });
905
906 it("rolls back all events for a multi-event command when projection fails mid-dispatch", async () => {
907 let shouldFailRequestedProjection = true;
908 const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {
909 bootstrap: Effect.void,
910 projectEvent: (event) => {
911 if (
912 shouldFailRequestedProjection &&
913 event.commandId === CommandId.make("cmd-turn-start-atomic") &&
914 event.type === "thread.turn-start-requested"
915 ) {
916 shouldFailRequestedProjection = false;
917 return Effect.fail(
918 new PersistenceSqlError({
919 operation: "test.projection",
920 detail: "projection failed",
921 }),
922 );
923 }
924 return Effect.void;
925 },
926 };
927
928 const runtime = ManagedRuntime.make(
929 OrchestrationEngineLive.pipe(
930 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
931 Layer.provide(ThreadBackgroundLiveness.layer),
932 Layer.provide(ThreadPlanProgress.layer),
933 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
934 Layer.provide(OrchestrationEventStoreLive),
935 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
936 Layer.provide(RepositoryIdentityResolver.layer),
937 Layer.provide(SqlitePersistenceMemory),
938 Layer.provide(NodeServices.layer),
939 ),
940 );
941 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
942 const createdAt = now();
943
944 await runtime.runPromise(
945 engine.dispatch({
946 type: "project.create",
947 commandId: CommandId.make("cmd-project-atomic-create"),
948 projectId: asProjectId("project-atomic"),
949 title: "Atomic Project",
950 workspaceRoot: "/tmp/project-atomic",
951 defaultModelSelection: {
952 instanceId: ProviderInstanceId.make("codex"),
953 model: "gpt-5-codex",
954 },
955 createdAt,
956 }),
957 );
958 await runtime.runPromise(
959 engine.dispatch({
960 type: "thread.create",
961 commandId: CommandId.make("cmd-thread-atomic-create"),
962 threadId: ThreadId.make("thread-atomic"),
963 projectId: asProjectId("project-atomic"),
964 title: "atomic",
965 modelSelection: {
966 instanceId: ProviderInstanceId.make("codex"),
967 model: "gpt-5-codex",
968 },
969 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
970 runtimeMode: "approval-required",
971 branch: null,
972 worktreePath: null,
973 createdAt,
974 }),
975 );
976
977 const turnStartCommand = {
978 type: "thread.turn.start" as const,
979 commandId: CommandId.make("cmd-turn-start-atomic"),
980 threadId: ThreadId.make("thread-atomic"),
981 message: {
982 messageId: asMessageId("msg-atomic-1"),
983 role: "user" as const,
984 text: "hello",
985 attachments: [],
986 },
987 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
988 runtimeMode: "approval-required" as const,
989 createdAt,
990 };
991
992 await expect(runtime.runPromise(engine.dispatch(turnStartCommand))).rejects.toThrow(
993 "projection failed",
994 );
995
996 const eventsAfterFailure = await runtime.runPromise(
997 Stream.runCollect(engine.readEvents(0)).pipe(
998 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
999 ),
1000 );
1001 expect(eventsAfterFailure.map((event) => event.type)).toEqual([
1002 "project.created",
1003 "thread.created",
1004 ]);
1005
1006 const retryResult = await runtime.runPromise(engine.dispatch(turnStartCommand));
1007 expect(retryResult.sequence).toBe(4);
1008
1009 const eventsAfterRetry = await runtime.runPromise(
1010 Stream.runCollect(engine.readEvents(0)).pipe(
1011 Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
1012 ),
1013 );
1014 expect(eventsAfterRetry.map((event) => event.type)).toEqual([
1015 "project.created",
1016 "thread.created",
1017 "thread.message-sent",
1018 "thread.turn-start-requested",
1019 ]);
1020 expect(
1021 eventsAfterRetry.filter((event) => event.commandId === turnStartCommand.commandId),
1022 ).toHaveLength(2);
1023
1024 await runtime.dispose();
1025 });
1026
1027 it("reconciles command state when append persists but projection fails", async () => {
1028 type StoredEvent =
1029 ReturnType<OrchestrationEventStoreShape["append"]> extends Effect.Effect<infer A, any, any>
1030 ? A
1031 : never;
1032 const events: StoredEvent[] = [];
1033 let nextSequence = 1;
1034
1035 const nonTransactionalStore: OrchestrationEventStoreShape = {
1036 append(event) {
1037 const savedEvent = {
1038 ...event,
1039 sequence: nextSequence,
1040 } as StoredEvent;
1041 nextSequence += 1;
1042 events.push(savedEvent);
1043 return Effect.succeed(savedEvent);
1044 },
1045 readFromSequence(sequenceExclusive) {
1046 return Stream.fromIterable(events.filter((event) => event.sequence > sequenceExclusive));
1047 },
1048 readAll() {
1049 return Stream.fromIterable(events);
1050 },
1051 };
1052
1053 let shouldFailProjection = true;
1054 const flakyProjectionPipeline: OrchestrationProjectionPipelineShape = {
1055 bootstrap: Effect.void,
1056 projectEvent: (event) => {
1057 if (
1058 shouldFailProjection &&
1059 event.commandId === CommandId.make("cmd-thread-archive-sync-fail")
1060 ) {
1061 shouldFailProjection = false;
1062 return Effect.fail(
1063 new PersistenceSqlError({
1064 operation: "test.projection",
1065 detail: "projection failed",
1066 }),
1067 );
1068 }
1069 return Effect.void;
1070 },
1071 };
1072
1073 const runtime = ManagedRuntime.make(
1074 OrchestrationEngineLive.pipe(
1075 Layer.provide(OrchestrationProjectionSnapshotQueryLive),
1076 Layer.provide(ThreadBackgroundLiveness.layer),
1077 Layer.provide(ThreadPlanProgress.layer),
1078 Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
1079 Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
1080 Layer.provide(OrchestrationCommandReceiptRepositoryLive),
1081 Layer.provide(RepositoryIdentityResolver.layer),
1082 Layer.provide(SqlitePersistenceMemory),
1083 Layer.provide(NodeServices.layer),
1084 ),
1085 );
1086 const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
1087 const createdAt = now();
1088
1089 await runtime.runPromise(
1090 engine.dispatch({
1091 type: "project.create",
1092 commandId: CommandId.make("cmd-project-sync-create"),
1093 projectId: asProjectId("project-sync"),
1094 title: "Sync Project",
1095 workspaceRoot: "/tmp/project-sync",
1096 defaultModelSelection: {
1097 instanceId: ProviderInstanceId.make("codex"),
1098 model: "gpt-5-codex",
1099 },
1100 createdAt,
1101 }),
1102 );
1103 await runtime.runPromise(
1104 engine.dispatch({
1105 type: "thread.create",
1106 commandId: CommandId.make("cmd-thread-sync-create"),
1107 threadId: ThreadId.make("thread-sync"),
1108 projectId: asProjectId("project-sync"),
1109 title: "sync-before",
1110 modelSelection: {
1111 instanceId: ProviderInstanceId.make("codex"),
1112 model: "gpt-5-codex",
1113 },
1114 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1115 runtimeMode: "approval-required",
1116 branch: null,
1117 worktreePath: null,
1118 createdAt,
1119 }),
1120 );
1121
1122 await expect(
1123 runtime.runPromise(
1124 engine.dispatch({
1125 type: "thread.archive",
1126 commandId: CommandId.make("cmd-thread-archive-sync-fail"),
1127 threadId: ThreadId.make("thread-sync"),
1128 }),
1129 ),
1130 ).rejects.toThrow("projection failed");
1131
1132 await expect(
1133 runtime.runPromise(
1134 engine.dispatch({
1135 type: "thread.archive",
1136 commandId: CommandId.make("cmd-thread-archive-sync-retry"),
1137 threadId: ThreadId.make("thread-sync"),
1138 }),
1139 ),
1140 ).rejects.toThrow("already archived");
1141
1142 await runtime.dispose();
1143 });
1144
1145 it("fails command dispatch when command invariants are violated", async () => {
1146 const system = await createOrchestrationSystem();
1147 const { engine } = system;
1148
1149 await expect(
1150 system.run(
1151 engine.dispatch({
1152 type: "thread.turn.start",
1153 commandId: CommandId.make("cmd-invariant-missing-thread"),
1154 threadId: ThreadId.make("thread-missing"),
1155 message: {
1156 messageId: asMessageId("msg-missing"),
1157 role: "user",
1158 text: "hello",
1159 attachments: [],
1160 },
1161 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1162 runtimeMode: "approval-required",
1163 createdAt: now(),
1164 }),
1165 ),
1166 ).rejects.toThrow("Thread 'thread-missing' does not exist");
1167
1168 await system.dispose();
1169 });
1170
1171 it("rejects duplicate thread creation", async () => {
1172 const system = await createOrchestrationSystem();
1173 const { engine } = system;
1174 const createdAt = now();
1175
1176 await system.run(
1177 engine.dispatch({
1178 type: "project.create",
1179 commandId: CommandId.make("cmd-project-duplicate-create"),
1180 projectId: asProjectId("project-duplicate"),
1181 title: "Duplicate Project",
1182 workspaceRoot: "/tmp/project-duplicate",
1183 defaultModelSelection: {
1184 instanceId: ProviderInstanceId.make("codex"),
1185 model: "gpt-5-codex",
1186 },
1187 createdAt,
1188 }),
1189 );
1190
1191 await system.run(
1192 engine.dispatch({
1193 type: "thread.create",
1194 commandId: CommandId.make("cmd-thread-duplicate-1"),
1195 threadId: ThreadId.make("thread-duplicate"),
1196 projectId: asProjectId("project-duplicate"),
1197 title: "duplicate",
1198 modelSelection: {
1199 instanceId: ProviderInstanceId.make("codex"),
1200 model: "gpt-5-codex",
1201 },
1202 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1203 runtimeMode: "approval-required",
1204 branch: null,
1205 worktreePath: null,
1206 createdAt,
1207 }),
1208 );
1209
1210 await expect(
1211 system.run(
1212 engine.dispatch({
1213 type: "thread.create",
1214 commandId: CommandId.make("cmd-thread-duplicate-2"),
1215 threadId: ThreadId.make("thread-duplicate"),
1216 projectId: asProjectId("project-duplicate"),
1217 title: "duplicate",
1218 modelSelection: {
1219 instanceId: ProviderInstanceId.make("codex"),
1220 model: "gpt-5-codex",
1221 },
1222 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1223 runtimeMode: "approval-required",
1224 branch: null,
1225 worktreePath: null,
1226 createdAt,
1227 }),
1228 ),
1229 ).rejects.toThrow("already exists");
1230
1231 await system.dispose();
1232 });
1233
1234 it("replays the accepted receipt for a genuine retry of the same command", async () => {
1235 const createdAt = now();
1236 const system = await createOrchestrationSystem();
1237 const { engine } = system;
1238
1239 await system.run(
1240 engine.dispatch({
1241 type: "project.create",
1242 commandId: CommandId.make("cmd-retry-project-create"),
1243 projectId: asProjectId("project-retry"),
1244 title: "Retry Project",
1245 workspaceRoot: "/tmp/project-retry",
1246 defaultModelSelection: {
1247 instanceId: ProviderInstanceId.make("codex"),
1248 model: "gpt-5-codex",
1249 },
1250 createdAt,
1251 }),
1252 );
1253 await system.run(
1254 engine.dispatch({
1255 type: "thread.create",
1256 commandId: CommandId.make("cmd-retry-thread-create"),
1257 threadId: ThreadId.make("thread-retry"),
1258 projectId: asProjectId("project-retry"),
1259 title: "retry",
1260 modelSelection: {
1261 instanceId: ProviderInstanceId.make("codex"),
1262 model: "gpt-5-codex",
1263 },
1264 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1265 runtimeMode: "approval-required",
1266 branch: null,
1267 worktreePath: null,
1268 createdAt,
1269 }),
1270 );
1271
1272 const turnStart = {
1273 type: "thread.turn.start",
1274 commandId: CommandId.make("cmd-retry-turn-start"),
1275 threadId: ThreadId.make("thread-retry"),
1276 message: {
1277 messageId: asMessageId("msg-retry"),
1278 role: "user",
1279 text: "hello",
1280 attachments: [],
1281 },
1282 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1283 runtimeMode: "approval-required",
1284 createdAt,
1285 } as const;
1286
1287 const first = await system.run(engine.dispatch(turnStart));
1288 const second = await system.run(engine.dispatch(turnStart));
1289 expect(second.sequence).toBe(first.sequence);
1290
1291 const readModel = await system.readModel();
1292 const thread = readModel.threads.find((candidate) => candidate.id === "thread-retry");
1293 expect(thread?.messages.filter((message) => message.role === "user")).toHaveLength(1);
1294
1295 await system.dispose();
1296 });
1297
1298 it("rejects reusing an accepted command id for a different aggregate", async () => {
1299 const createdAt = now();
1300 const system = await createOrchestrationSystem();
1301 const { engine } = system;
1302
1303 await system.run(
1304 engine.dispatch({
1305 type: "project.create",
1306 commandId: CommandId.make("cmd-conflict-project-create"),
1307 projectId: asProjectId("project-conflict"),
1308 title: "Conflict Project",
1309 workspaceRoot: "/tmp/project-conflict",
1310 defaultModelSelection: {
1311 instanceId: ProviderInstanceId.make("codex"),
1312 model: "gpt-5-codex",
1313 },
1314 createdAt,
1315 }),
1316 );
1317 for (const threadId of ["thread-conflict-a", "thread-conflict-b"]) {
1318 await system.run(
1319 engine.dispatch({
1320 type: "thread.create",
1321 commandId: CommandId.make(`cmd-${threadId}-create`),
1322 threadId: ThreadId.make(threadId),
1323 projectId: asProjectId("project-conflict"),
1324 title: threadId,
1325 modelSelection: {
1326 instanceId: ProviderInstanceId.make("codex"),
1327 model: "gpt-5-codex",
1328 },
1329 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1330 runtimeMode: "approval-required",
1331 branch: null,
1332 worktreePath: null,
1333 createdAt,
1334 }),
1335 );
1336 }
1337
1338 await system.run(
1339 engine.dispatch({
1340 type: "thread.turn.start",
1341 commandId: CommandId.make("cmd-conflict-turn-start"),
1342 threadId: ThreadId.make("thread-conflict-a"),
1343 message: {
1344 messageId: asMessageId("msg-conflict-a"),
1345 role: "user",
1346 text: "hello",
1347 attachments: [],
1348 },
1349 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1350 runtimeMode: "approval-required",
1351 createdAt,
1352 }),
1353 );
1354
1355 await expect(
1356 system.run(
1357 engine.dispatch({
1358 type: "thread.turn.start",
1359 commandId: CommandId.make("cmd-conflict-turn-start"),
1360 threadId: ThreadId.make("thread-conflict-b"),
1361 message: {
1362 messageId: asMessageId("msg-conflict-b"),
1363 role: "user",
1364 text: "hello again",
1365 attachments: [],
1366 },
1367 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
1368 runtimeMode: "approval-required",
1369 createdAt,
1370 }),
1371 ),
1372 ).rejects.toThrow("already used for thread 'thread-conflict-a'");
1373
1374 const readModel = await system.readModel();
1375 const targetThread = readModel.threads.find(
1376 (candidate) => candidate.id === "thread-conflict-b",
1377 );
1378 expect(targetThread?.messages.filter((message) => message.role === "user")).toHaveLength(0);
1379
1380 await system.dispose();
1381 });
1382});