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

OrchestrationEngine.test.ts

1,228 lines40.3 KB

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