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

OrchestrationEngine.test.ts

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