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

projector.test.ts

1,085 lines33.0 KB

1import {
2 CommandId,
3 EventId,
4 ProjectId,
5 ProviderDriverKind,
6 ThreadId,
7 type OrchestrationEvent,
8} from "@t3tools/contracts";
9import * as Effect from "effect/Effect";
10import { it as effectIt } from "@effect/vitest";
11import { describe, expect, it } from "vite-plus/test";
12​
13import { createEmptyReadModel, projectEvent } from "./projector.ts";
14​
15function makeEvent(input: {
16 sequence: number;
17 type: OrchestrationEvent["type"];
18 occurredAt: string;
19 aggregateKind: OrchestrationEvent["aggregateKind"];
20 aggregateId: string;
21 commandId: string | null;
22 payload: unknown;
23}): OrchestrationEvent {
24 return {
25 sequence: input.sequence,
26 eventId: EventId.make(`event-${input.sequence}`),
27 type: input.type,
28 aggregateKind: input.aggregateKind,
29 aggregateId:
30 input.aggregateKind === "project"
31 ? ProjectId.make(input.aggregateId)
32 : ThreadId.make(input.aggregateId),
33 occurredAt: input.occurredAt,
34 commandId: input.commandId === null ? null : CommandId.make(input.commandId),
35 causationEventId: null,
36 correlationId: null,
37 metadata: {},
38 payload: input.payload as never,
39 } as OrchestrationEvent;
41​
42describe("orchestration projector", () => {
43 it("applies thread.created events", async () => {
44 const now = "2026-01-01T00:00:00.000Z";
45 const model = createEmptyReadModel(now);
46​
47 const next = await Effect.runPromise(
48 projectEvent(
49 model,
50 makeEvent({
51 sequence: 1,
52 type: "thread.created",
53 aggregateKind: "thread",
54 aggregateId: "thread-1",
55 occurredAt: now,
56 commandId: "cmd-thread-create",
57 payload: {
58 threadId: "thread-1",
59 projectId: "project-1",
60 title: "demo",
61 modelSelection: {
62 provider: ProviderDriverKind.make("codex"),
63 model: "gpt-5-codex",
64 },
65 runtimeMode: "full-access",
66 branch: null,
67 worktreePath: null,
68 createdAt: now,
69 updatedAt: now,
70 },
71 }),
72 ),
73 );
74​
75 expect(next.snapshotSequence).toBe(1);
76 expect(next.threads).toEqual([
77 {
78 id: "thread-1",
79 projectId: "project-1",
80 title: "demo",
81 modelSelection: {
82 instanceId: "codex",
83 model: "gpt-5-codex",
84 },
85 runtimeMode: "full-access",
86 interactionMode: "default",
87 branch: null,
88 worktreePath: null,
89 latestTurn: null,
90 createdAt: now,
91 updatedAt: now,
92 archivedAt: null,
93 settledOverride: null,
94 settledAt: null,
95 unsettledAt: null,
96 snoozedUntil: null,
97 snoozedAt: null,
98 deletedAt: null,
99 messages: [],
100 proposedPlans: [],
101 activities: [],
102 checkpoints: [],
103 session: null,
104 },
105 ]);
106 });
107​
108 it("fails when event payload cannot be decoded by runtime schema", async () => {
109 const now = "2026-01-01T00:00:00.000Z";
110 const model = createEmptyReadModel(now);
111​
112 await expect(
113 Effect.runPromise(
114 projectEvent(
115 model,
116 makeEvent({
117 sequence: 1,
118 type: "thread.created",
119 aggregateKind: "thread",
120 aggregateId: "thread-1",
121 occurredAt: now,
122 commandId: "cmd-invalid",
123 payload: {
124 // missing required threadId
125 projectId: "project-1",
126 title: "demo",
127 modelSelection: {
128 provider: ProviderDriverKind.make("codex"),
129 model: "gpt-5-codex",
130 },
131 branch: null,
132 worktreePath: null,
133 createdAt: now,
134 updatedAt: now,
135 },
136 }),
137 ),
138 ),
139 ).rejects.toBeDefined();
140 });
141​
142 it("applies thread.archived and thread.unarchived events", async () => {
143 const now = "2026-01-01T00:00:00.000Z";
144 const later = "2026-01-01T00:00:01.000Z";
145 const created = await Effect.runPromise(
146 projectEvent(
147 createEmptyReadModel(now),
148 makeEvent({
149 sequence: 1,
150 type: "thread.created",
151 aggregateKind: "thread",
152 aggregateId: "thread-1",
153 occurredAt: now,
154 commandId: "cmd-thread-create",
155 payload: {
156 threadId: "thread-1",
157 projectId: "project-1",
158 title: "demo",
159 modelSelection: {
160 provider: ProviderDriverKind.make("codex"),
161 model: "gpt-5-codex",
162 },
163 runtimeMode: "full-access",
164 interactionMode: "default",
165 branch: null,
166 worktreePath: null,
167 createdAt: now,
168 updatedAt: now,
169 },
170 }),
171 ),
172 );
173​
174 const archived = await Effect.runPromise(
175 projectEvent(
176 created,
177 makeEvent({
178 sequence: 2,
179 type: "thread.archived",
180 aggregateKind: "thread",
181 aggregateId: "thread-1",
182 occurredAt: later,
183 commandId: "cmd-thread-archive",
184 payload: {
185 threadId: "thread-1",
186 archivedAt: later,
187 updatedAt: later,
188 },
189 }),
190 ),
191 );
192 expect(archived.threads[0]?.archivedAt).toBe(later);
193​
194 const unarchived = await Effect.runPromise(
195 projectEvent(
196 archived,
197 makeEvent({
198 sequence: 3,
199 type: "thread.unarchived",
200 aggregateKind: "thread",
201 aggregateId: "thread-1",
202 occurredAt: later,
203 commandId: "cmd-thread-unarchive",
204 payload: {
205 threadId: "thread-1",
206 updatedAt: later,
207 },
208 }),
209 ),
210 );
211 expect(unarchived.threads[0]?.archivedAt).toBeNull();
212 });
213​
214 it("keeps projector forward-compatible for unhandled event types", async () => {
215 const now = "2026-01-01T00:00:00.000Z";
216 const model = createEmptyReadModel(now);
217​
218 const next = await Effect.runPromise(
219 projectEvent(
220 model,
221 makeEvent({
222 sequence: 7,
223 type: "thread.turn-start-requested",
224 aggregateKind: "thread",
225 aggregateId: "thread-1",
226 occurredAt: "2026-01-01T00:00:00.000Z",
227 commandId: "cmd-unhandled",
228 payload: {
229 threadId: "thread-1",
230 messageId: "message-1",
231 runtimeMode: "approval-required",
232 createdAt: "2026-01-01T00:00:00.000Z",
233 },
234 }),
235 ),
236 );
237​
238 expect(next.snapshotSequence).toBe(7);
239 expect(next.updatedAt).toBe("2026-01-01T00:00:00.000Z");
240 expect(next.threads).toEqual([]);
241 });
242​
243 effectIt.effect.each([
244 ["ready", "completed"],
245 ["interrupted", "interrupted"],
246 ] as const)(
247 "preserves the turn state after a %s session captures its checkpoint",
248 ([status, state]) =>
249 Effect.gen(function* () {
250 const createdAt = "2026-02-23T08:00:00.000Z";
251 const startedAt = "2026-02-23T08:00:05.000Z";
252 const model = createEmptyReadModel(createdAt);
253​
254 const afterCreate = yield* projectEvent(
255 model,
256 makeEvent({
257 sequence: 1,
258 type: "thread.created",
259 aggregateKind: "thread",
260 aggregateId: "thread-1",
261 occurredAt: createdAt,
262 commandId: "cmd-create",
263 payload: {
264 threadId: "thread-1",
265 projectId: "project-1",
266 title: "demo",
267 modelSelection: {
268 provider: ProviderDriverKind.make("codex"),
269 model: "gpt-5.3-codex",
270 },
271 runtimeMode: "full-access",
272 branch: null,
273 worktreePath: null,
274 createdAt,
275 updatedAt: createdAt,
276 },
277 }),
278 );
279​
280 const settledAt = "2026-02-23T08:01:00.000Z";
281 const [afterRunning, afterReady] = yield* Effect.flatMap(
282 projectEvent(
283 afterCreate,
284 makeEvent({
285 sequence: 2,
286 type: "thread.session-set",
287 aggregateKind: "thread",
288 aggregateId: "thread-1",
289 occurredAt: startedAt,
290 commandId: "cmd-running",
291 payload: {
292 threadId: "thread-1",
293 session: {
294 threadId: "thread-1",
295 status: "running",
296 providerName: "codex",
297 providerSessionId: "session-1",
298 providerThreadId: "provider-thread-1",
299 runtimeMode: "approval-required",
300 activeTurnId: "turn-1",
301 lastError: null,
302 updatedAt: startedAt,
303 },
304 },
305 }),
306 ),
307 (running) =>
308 Effect.map(
309 projectEvent(
310 running,
311 makeEvent({
312 sequence: 3,
313 type: "thread.session-set",
314 aggregateKind: "thread",
315 aggregateId: "thread-1",
316 occurredAt: settledAt,
317 commandId: "cmd-ready",
318 payload: {
319 threadId: "thread-1",
320 session: {
321 threadId: "thread-1",
322 status,
323 providerName: "codex",
324 providerSessionId: "session-1",
325 providerThreadId: "provider-thread-1",
326 runtimeMode: "approval-required",
327 activeTurnId: null,
328 lastError: null,
329 updatedAt: settledAt,
330 },
331 },
332 }),
333 ),
334 (ready) => [running, ready] as const,
335 ),
336 );
337​
338 const thread = afterRunning.threads[0];
339 expect(thread?.latestTurn?.turnId).toBe("turn-1");
340 expect(thread?.session?.status).toBe("running");
341​
342 // Leaving the "running" session status settles the running turn with the
343 // session timestamp as the turn end.
344 const settledThread = afterReady.threads[0];
345 expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
346 expect(settledThread?.latestTurn?.state).toBe(state);
347 expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
348​
349 const captured = yield* projectEvent(
350 afterReady,
351 makeEvent({
352 sequence: 4,
353 type: "thread.turn-diff-completed",
354 aggregateKind: "thread",
355 aggregateId: "thread-1",
356 occurredAt: settledAt,
357 commandId: "cmd-final-checkpoint",
358 payload: {
359 threadId: "thread-1",
360 turnId: "turn-1",
361 checkpointTurnCount: 1,
362 checkpointRef: "refs/t3/checkpoints/thread-1/turn/1",
363 status: "ready",
364 files: [],
365 assistantMessageId: "assistant:turn-1",
366 completedAt: settledAt,
367 },
368 }),
369 );
370 expect(captured.threads[0]?.latestTurn?.state).toBe(state);
371 expect(captured.threads[0]?.checkpoints[0]?.status).toBe("ready");
372 }),
373 );
374​
375 effectIt.effect.each([null, "ready", "interrupted", "stopped"] as const)(
376 "replaces a missing checkpoint without inventing interruption for a %s session",
377 (sessionStatus) =>
378 Effect.gen(function* () {
379 const now = "2026-09-04T23:00:00.000Z";
380 const threadId = "thread-placeholder";
381 const event = (sequence: number, type: OrchestrationEvent["type"], payload: unknown) =>
382 makeEvent({
383 sequence,
384 type,
385 payload,
386 aggregateKind: "thread",
387 aggregateId: threadId,
388 occurredAt: now,
389 commandId: `placeholder-${sequence}`,
390 });
391 let model = yield* projectEvent(
392 createEmptyReadModel(now),
393 event(1, "thread.created", {
394 threadId,
395 projectId: "project-1",
396 title: "Placeholder",
397 modelSelection: { instanceId: "codex", model: "test" },
398 runtimeMode: "full-access",
399 interactionMode: "default",
400 branch: null,
401 worktreePath: null,
402 createdAt: now,
403 updatedAt: now,
404 }),
405 );
406 const checkpoint = {
407 threadId,
408 turnId: "turn-placeholder",
409 checkpointTurnCount: 1,
410 checkpointRef: "provider-diff:placeholder",
411 files: [],
412 assistantMessageId: "assistant:placeholder",
413 completedAt: now,
414 };
415 if (sessionStatus === "interrupted" || sessionStatus === "stopped") {
416 model = yield* projectEvent(
417 model,
418 event(2, "thread.session-set", {
419 threadId,
420 session: {
421 threadId,
422 status: "running",
423 providerName: "codex",
424 runtimeMode: "full-access",
425 activeTurnId: "turn-placeholder",
426 lastError: null,
427 updatedAt: now,
428 },
429 }),
430 );
431 }
432 model = yield* projectEvent(
433 model,
434 event(3, "thread.turn-diff-completed", {
435 ...checkpoint,
436 status: "missing",
437 }),
438 );
439 if (sessionStatus !== null) {
440 model = yield* projectEvent(
441 model,
442 event(4, "thread.session-set", {
443 threadId,
444 session: {
445 threadId,
446 status: sessionStatus,
447 providerName: "codex",
448 runtimeMode: "full-access",
449 activeTurnId: null,
450 lastError: null,
451 updatedAt: now,
452 },
453 }),
454 );
455 }
456 model = yield* projectEvent(
457 model,
458 event(5, "thread.turn-diff-completed", {
459 ...checkpoint,
460 status: "ready",
461 checkpointRef: "refs/t3/checkpoints/thread-placeholder/turn/1",
462 }),
463 );
464 expect(model.threads[0]?.latestTurn?.state).toBe(
465 sessionStatus === "interrupted" || sessionStatus === "stopped"
466 ? "interrupted"
467 : "completed",
468 );
469 }),
470 );
471​
472 it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
473 const createdAt = "2026-02-23T08:00:00.000Z";
474 const updatedAt = "2026-02-23T08:00:05.000Z";
475 const model = createEmptyReadModel(createdAt);
476​
477 const afterCreate = await Effect.runPromise(
478 projectEvent(
479 model,
480 makeEvent({
481 sequence: 1,
482 type: "thread.created",
483 aggregateKind: "thread",
484 aggregateId: "thread-1",
485 occurredAt: createdAt,
486 commandId: "cmd-create",
487 payload: {
488 threadId: "thread-1",
489 projectId: "project-1",
490 title: "demo",
491 modelSelection: {
492 provider: ProviderDriverKind.make("codex"),
493 model: "gpt-5.3-codex",
494 },
495 runtimeMode: "full-access",
496 branch: null,
497 worktreePath: null,
498 createdAt,
499 updatedAt: createdAt,
500 },
501 }),
502 ),
503 );
504​
505 const afterUpdate = await Effect.runPromise(
506 projectEvent(
507 afterCreate,
508 makeEvent({
509 sequence: 2,
510 type: "thread.runtime-mode-set",
511 aggregateKind: "thread",
512 aggregateId: "thread-1",
513 occurredAt: updatedAt,
514 commandId: "cmd-runtime-mode-set",
515 payload: {
516 threadId: "thread-1",
517 runtimeMode: "approval-required",
518 updatedAt,
519 },
520 }),
521 ),
522 );
523​
524 expect(afterUpdate.threads[0]?.runtimeMode).toBe("approval-required");
525 expect(afterUpdate.threads[0]?.updatedAt).toBe(updatedAt);
526 });
527​
528 it("marks assistant messages completed with non-streaming updates", async () => {
529 const createdAt = "2026-02-23T09:00:00.000Z";
530 const deltaAt = "2026-02-23T09:00:01.000Z";
531 const completeAt = "2026-02-23T09:00:03.500Z";
532 const model = createEmptyReadModel(createdAt);
533​
534 const afterCreate = await Effect.runPromise(
535 projectEvent(
536 model,
537 makeEvent({
538 sequence: 1,
539 type: "thread.created",
540 aggregateKind: "thread",
541 aggregateId: "thread-1",
542 occurredAt: createdAt,
543 commandId: "cmd-create",
544 payload: {
545 threadId: "thread-1",
546 projectId: "project-1",
547 title: "demo",
548 modelSelection: {
549 provider: ProviderDriverKind.make("codex"),
550 model: "gpt-5.3-codex",
551 },
552 runtimeMode: "full-access",
553 branch: null,
554 worktreePath: null,
555 createdAt,
556 updatedAt: createdAt,
557 },
558 }),
559 ),
560 );
561​
562 const afterDelta = await Effect.runPromise(
563 projectEvent(
564 afterCreate,
565 makeEvent({
566 sequence: 2,
567 type: "thread.message-sent",
568 aggregateKind: "thread",
569 aggregateId: "thread-1",
570 occurredAt: deltaAt,
571 commandId: "cmd-delta",
572 payload: {
573 threadId: "thread-1",
574 messageId: "assistant:msg-1",
575 role: "assistant",
576 text: "hello",
577 turnId: "turn-1",
578 streaming: true,
579 createdAt: deltaAt,
580 updatedAt: deltaAt,
581 },
582 }),
583 ),
584 );
585​
586 const afterComplete = await Effect.runPromise(
587 projectEvent(
588 afterDelta,
589 makeEvent({
590 sequence: 3,
591 type: "thread.message-sent",
592 aggregateKind: "thread",
593 aggregateId: "thread-1",
594 occurredAt: completeAt,
595 commandId: "cmd-complete",
596 payload: {
597 threadId: "thread-1",
598 messageId: "assistant:msg-1",
599 role: "assistant",
600 text: "",
601 turnId: "turn-1",
602 streaming: false,
603 createdAt: completeAt,
604 updatedAt: completeAt,
605 },
606 }),
607 ),
608 );
609​
610 const message = afterComplete.threads[0]?.messages[0];
611 expect(message?.id).toBe("assistant:msg-1");
612 expect(message?.text).toBe("hello");
613 expect(message?.streaming).toBe(false);
614 expect(message?.updatedAt).toBe(completeAt);
615 });
616​
617 it("prunes reverted turn messages from in-memory thread snapshot", async () => {
618 const createdAt = "2026-02-23T10:00:00.000Z";
619 const model = createEmptyReadModel(createdAt);
620​
621 const afterCreate = await Effect.runPromise(
622 projectEvent(
623 model,
624 makeEvent({
625 sequence: 1,
626 type: "thread.created",
627 aggregateKind: "thread",
628 aggregateId: "thread-1",
629 occurredAt: createdAt,
630 commandId: "cmd-create",
631 payload: {
632 threadId: "thread-1",
633 projectId: "project-1",
634 title: "demo",
635 modelSelection: {
636 provider: ProviderDriverKind.make("codex"),
637 model: "gpt-5.3-codex",
638 },
639 runtimeMode: "full-access",
640 branch: null,
641 worktreePath: null,
642 createdAt,
643 updatedAt: createdAt,
644 },
645 }),
646 ),
647 );
648​
649 const events: ReadonlyArray<OrchestrationEvent> = [
650 makeEvent({
651 sequence: 2,
652 type: "thread.message-sent",
653 aggregateKind: "thread",
654 aggregateId: "thread-1",
655 occurredAt: "2026-02-23T10:00:01.000Z",
656 commandId: "cmd-user-1",
657 payload: {
658 threadId: "thread-1",
659 messageId: "user-msg-1",
660 role: "user",
661 text: "First edit",
662 turnId: null,
663 streaming: false,
664 createdAt: "2026-02-23T10:00:01.000Z",
665 updatedAt: "2026-02-23T10:00:01.000Z",
666 },
667 }),
668 makeEvent({
669 sequence: 3,
670 type: "thread.message-sent",
671 aggregateKind: "thread",
672 aggregateId: "thread-1",
673 occurredAt: "2026-02-23T10:00:02.000Z",
674 commandId: "cmd-assistant-1",
675 payload: {
676 threadId: "thread-1",
677 messageId: "assistant-msg-1",
678 role: "assistant",
679 text: "Updated README to v2.\n",
680 turnId: "turn-1",
681 streaming: false,
682 createdAt: "2026-02-23T10:00:02.000Z",
683 updatedAt: "2026-02-23T10:00:02.000Z",
684 },
685 }),
686 makeEvent({
687 sequence: 4,
688 type: "thread.turn-diff-completed",
689 aggregateKind: "thread",
690 aggregateId: "thread-1",
691 occurredAt: "2026-02-23T10:00:02.500Z",
692 commandId: "cmd-turn-1-complete",
693 payload: {
694 threadId: "thread-1",
695 turnId: "turn-1",
696 checkpointTurnCount: 1,
697 checkpointRef: "refs/t3/checkpoints/thread-1/turn/1",
698 status: "ready",
699 files: [],
700 assistantMessageId: "assistant-msg-1",
701 completedAt: "2026-02-23T10:00:02.500Z",
702 },
703 }),
704 makeEvent({
705 sequence: 5,
706 type: "thread.activity-appended",
707 aggregateKind: "thread",
708 aggregateId: "thread-1",
709 occurredAt: "2026-02-23T10:00:02.750Z",
710 commandId: "cmd-activity-1",
711 payload: {
712 threadId: "thread-1",
713 activity: {
714 id: "activity-1",
715 tone: "tool",
716 kind: "tool.started",
717 summary: "Edit file started",
718 payload: { toolKind: "command" },
719 turnId: "turn-1",
720 createdAt: "2026-02-23T10:00:02.750Z",
721 },
722 },
723 }),
724 makeEvent({
725 sequence: 6,
726 type: "thread.message-sent",
727 aggregateKind: "thread",
728 aggregateId: "thread-1",
729 occurredAt: "2026-02-23T10:00:03.000Z",
730 commandId: "cmd-user-2",
731 payload: {
732 threadId: "thread-1",
733 messageId: "user-msg-2",
734 role: "user",
735 text: "Second edit",
736 turnId: null,
737 streaming: false,
738 createdAt: "2026-02-23T10:00:03.000Z",
739 updatedAt: "2026-02-23T10:00:03.000Z",
740 },
741 }),
742 makeEvent({
743 sequence: 7,
744 type: "thread.message-sent",
745 aggregateKind: "thread",
746 aggregateId: "thread-1",
747 occurredAt: "2026-02-23T10:00:04.000Z",
748 commandId: "cmd-assistant-2",
749 payload: {
750 threadId: "thread-1",
751 messageId: "assistant-msg-2",
752 role: "assistant",
753 text: "Updated README to v3.\n",
754 turnId: "turn-2",
755 streaming: false,
756 createdAt: "2026-02-23T10:00:04.000Z",
757 updatedAt: "2026-02-23T10:00:04.000Z",
758 },
759 }),
760 makeEvent({
761 sequence: 8,
762 type: "thread.turn-diff-completed",
763 aggregateKind: "thread",
764 aggregateId: "thread-1",
765 occurredAt: "2026-02-23T10:00:04.500Z",
766 commandId: "cmd-turn-2-complete",
767 payload: {
768 threadId: "thread-1",
769 turnId: "turn-2",
770 checkpointTurnCount: 2,
771 checkpointRef: "refs/t3/checkpoints/thread-1/turn/2",
772 status: "ready",
773 files: [],
774 assistantMessageId: "assistant-msg-2",
775 completedAt: "2026-02-23T10:00:04.500Z",
776 },
777 }),
778 makeEvent({
779 sequence: 9,
780 type: "thread.activity-appended",
781 aggregateKind: "thread",
782 aggregateId: "thread-1",
783 occurredAt: "2026-02-23T10:00:04.750Z",
784 commandId: "cmd-activity-2",
785 payload: {
786 threadId: "thread-1",
787 activity: {
788 id: "activity-2",
789 tone: "tool",
790 kind: "tool.completed",
791 summary: "Edit file complete",
792 payload: { toolKind: "command" },
793 turnId: "turn-2",
794 createdAt: "2026-02-23T10:00:04.750Z",
795 },
796 },
797 }),
798 makeEvent({
799 sequence: 10,
800 type: "thread.reverted",
801 aggregateKind: "thread",
802 aggregateId: "thread-1",
803 occurredAt: "2026-02-23T10:00:05.000Z",
804 commandId: "cmd-revert",
805 payload: {
806 threadId: "thread-1",
807 turnCount: 1,
808 },
809 }),
810 ];
811​
812 const afterRevert = await events.reduce<Promise<ReturnType<typeof createEmptyReadModel>>>(
813 (statePromise, event) =>
814 statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
815 Promise.resolve(afterCreate),
816 );
817​
818 const thread = afterRevert.threads[0];
819 expect(thread?.messages.map((message) => ({ role: message.role, text: message.text }))).toEqual(
820 [
821 { role: "user", text: "First edit" },
822 { role: "assistant", text: "Updated README to v2.\n" },
823 ],
824 );
825 expect(
826 thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })),
827 ).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
828 expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
829 expect(thread?.latestTurn?.turnId).toBe("turn-1");
830 });
831​
832 it("does not fallback-retain messages tied to removed turn IDs", async () => {
833 const createdAt = "2026-02-26T12:00:00.000Z";
834 const model = createEmptyReadModel(createdAt);
835​
836 const afterCreate = await Effect.runPromise(
837 projectEvent(
838 model,
839 makeEvent({
840 sequence: 1,
841 type: "thread.created",
842 aggregateKind: "thread",
843 aggregateId: "thread-revert",
844 occurredAt: createdAt,
845 commandId: "cmd-create-revert",
846 payload: {
847 threadId: "thread-revert",
848 projectId: "project-1",
849 title: "demo",
850 modelSelection: {
851 provider: ProviderDriverKind.make("codex"),
852 model: "gpt-5.3-codex",
853 },
854 runtimeMode: "full-access",
855 branch: null,
856 worktreePath: null,
857 createdAt,
858 updatedAt: createdAt,
859 },
860 }),
861 ),
862 );
863​
864 const events: ReadonlyArray<OrchestrationEvent> = [
865 makeEvent({
866 sequence: 2,
867 type: "thread.turn-diff-completed",
868 aggregateKind: "thread",
869 aggregateId: "thread-revert",
870 occurredAt: "2026-02-26T12:00:01.000Z",
871 commandId: "cmd-turn-1",
872 payload: {
873 threadId: "thread-revert",
874 turnId: "turn-1",
875 checkpointTurnCount: 1,
876 checkpointRef: "refs/t3/checkpoints/thread-revert/turn/1",
877 status: "ready",
878 files: [],
879 assistantMessageId: "assistant-keep",
880 completedAt: "2026-02-26T12:00:01.000Z",
881 },
882 }),
883 makeEvent({
884 sequence: 3,
885 type: "thread.message-sent",
886 aggregateKind: "thread",
887 aggregateId: "thread-revert",
888 occurredAt: "2026-02-26T12:00:01.100Z",
889 commandId: "cmd-assistant-keep",
890 payload: {
891 threadId: "thread-revert",
892 messageId: "assistant-keep",
893 role: "assistant",
894 text: "kept",
895 turnId: "turn-1",
896 streaming: false,
897 createdAt: "2026-02-26T12:00:01.100Z",
898 updatedAt: "2026-02-26T12:00:01.100Z",
899 },
900 }),
901 makeEvent({
902 sequence: 4,
903 type: "thread.turn-diff-completed",
904 aggregateKind: "thread",
905 aggregateId: "thread-revert",
906 occurredAt: "2026-02-26T12:00:02.000Z",
907 commandId: "cmd-turn-2",
908 payload: {
909 threadId: "thread-revert",
910 turnId: "turn-2",
911 checkpointTurnCount: 2,
912 checkpointRef: "refs/t3/checkpoints/thread-revert/turn/2",
913 status: "ready",
914 files: [],
915 assistantMessageId: "assistant-remove",
916 completedAt: "2026-02-26T12:00:02.000Z",
917 },
918 }),
919 makeEvent({
920 sequence: 5,
921 type: "thread.message-sent",
922 aggregateKind: "thread",
923 aggregateId: "thread-revert",
924 occurredAt: "2026-02-26T12:00:02.050Z",
925 commandId: "cmd-user-remove",
926 payload: {
927 threadId: "thread-revert",
928 messageId: "user-remove",
929 role: "user",
930 text: "removed",
931 turnId: "turn-2",
932 streaming: false,
933 createdAt: "2026-02-26T12:00:02.050Z",
934 updatedAt: "2026-02-26T12:00:02.050Z",
935 },
936 }),
937 makeEvent({
938 sequence: 6,
939 type: "thread.message-sent",
940 aggregateKind: "thread",
941 aggregateId: "thread-revert",
942 occurredAt: "2026-02-26T12:00:02.100Z",
943 commandId: "cmd-assistant-remove",
944 payload: {
945 threadId: "thread-revert",
946 messageId: "assistant-remove",
947 role: "assistant",
948 text: "removed",
949 turnId: "turn-2",
950 streaming: false,
951 createdAt: "2026-02-26T12:00:02.100Z",
952 updatedAt: "2026-02-26T12:00:02.100Z",
953 },
954 }),
955 makeEvent({
956 sequence: 7,
957 type: "thread.reverted",
958 aggregateKind: "thread",
959 aggregateId: "thread-revert",
960 occurredAt: "2026-02-26T12:00:03.000Z",
961 commandId: "cmd-revert",
962 payload: {
963 threadId: "thread-revert",
964 turnCount: 1,
965 },
966 }),
967 ];
968​
969 const afterRevert = await events.reduce<Promise<ReturnType<typeof createEmptyReadModel>>>(
970 (statePromise, event) =>
971 statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
972 Promise.resolve(afterCreate),
973 );
974​
975 const thread = afterRevert.threads[0];
976 expect(
977 thread?.messages.map((message) => ({
978 id: message.id,
979 role: message.role,
980 turnId: message.turnId,
981 })),
982 ).toEqual([{ id: "assistant-keep", role: "assistant", turnId: "turn-1" }]);
983 });
984​
985 it("caps message and checkpoint retention for long-lived threads", async () => {
986 const createdAt = "2026-03-01T10:00:00.000Z";
987 const model = createEmptyReadModel(createdAt);
988​
989 const afterCreate = await Effect.runPromise(
990 projectEvent(
991 model,
992 makeEvent({
993 sequence: 1,
994 type: "thread.created",
995 aggregateKind: "thread",
996 aggregateId: "thread-capped",
997 occurredAt: createdAt,
998 commandId: "cmd-create-capped",
999 payload: {
1000 threadId: "thread-capped",
1001 projectId: "project-1",
1002 title: "capped",
1003 modelSelection: {
1004 provider: ProviderDriverKind.make("codex"),
1005 model: "gpt-5-codex",
1006 },
1007 runtimeMode: "full-access",
1008 branch: null,
1009 worktreePath: null,
1010 createdAt,
1011 updatedAt: createdAt,
1012 },
1013 }),
1014 ),
1015 );
1016​
1017 const messageEvents: ReadonlyArray<OrchestrationEvent> = Array.from(
1018 { length: 2_100 },
1019 (_, index) =>
1020 makeEvent({
1021 sequence: index + 2,
1022 type: "thread.message-sent",
1023 aggregateKind: "thread",
1024 aggregateId: "thread-capped",
1025 occurredAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`,
1026 commandId: `cmd-message-${index}`,
1027 payload: {
1028 threadId: "thread-capped",
1029 messageId: `msg-${index}`,
1030 role: "assistant",
1031 text: `message-${index}`,
1032 turnId: `turn-${index}`,
1033 streaming: false,
1034 createdAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`,
1035 updatedAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`,
1036 },
1037 }),
1038 );
1039 const afterMessages = await messageEvents.reduce<
1040 Promise<ReturnType<typeof createEmptyReadModel>>
1041 >(
1042 (statePromise, event) =>
1043 statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
1044 Promise.resolve(afterCreate),
1045 );
1046​
1047 const checkpointEvents: ReadonlyArray<OrchestrationEvent> = Array.from(
1048 { length: 600 },
1049 (_, index) =>
1050 makeEvent({
1051 sequence: index + 2_102,
1052 type: "thread.turn-diff-completed",
1053 aggregateKind: "thread",
1054 aggregateId: "thread-capped",
1055 occurredAt: `2026-03-01T10:30:${String(index % 60).padStart(2, "0")}.000Z`,
1056 commandId: `cmd-checkpoint-${index}`,
1057 payload: {
1058 threadId: "thread-capped",
1059 turnId: `turn-${index}`,
1060 checkpointTurnCount: index + 1,
1061 checkpointRef: `refs/t3/checkpoints/thread-capped/turn/${index + 1}`,
1062 status: "ready",
1063 files: [],
1064 assistantMessageId: `msg-${index}`,
1065 completedAt: `2026-03-01T10:30:${String(index % 60).padStart(2, "0")}.000Z`,
1066 },
1067 }),
1068 );
1069 const finalState = await checkpointEvents.reduce<
1070 Promise<ReturnType<typeof createEmptyReadModel>>
1071 >(
1072 (statePromise, event) =>
1073 statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
1074 Promise.resolve(afterMessages),
1075 );
1076​
1077 const thread = finalState.threads[0];
1078 expect(thread?.messages).toHaveLength(2_000);
1079 expect(thread?.messages[0]?.id).toBe("msg-100");
1080 expect(thread?.messages.at(-1)?.id).toBe("msg-2099");
1081 expect(thread?.checkpoints).toHaveLength(500);
1082 expect(thread?.checkpoints[0]?.turnId).toBe("turn-100");
1083 expect(thread?.checkpoints.at(-1)?.turnId).toBe("turn-599");
1084 });
1085});