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