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

OrchestrationEngine.test.ts

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