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