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