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

OrchestrationEngine.test.ts

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