Open History to see the last commit
1import {
2 CommandId,
3 EventId,
4 ProjectId,
5 ThreadId,
6 type OrchestrationEvent,
7} from "@t3tools/contracts";
8import { Effect } from "effect";
9import { describe, expect, it } from "vitest";
10
11import { createEmptyReadModel, projectEvent } from "./projector.ts";
12
13function makeEvent(input: {
14 sequence: number;
15 type: OrchestrationEvent["type"];
16 occurredAt: string;
17 aggregateKind: OrchestrationEvent["aggregateKind"];
18 aggregateId: string;
19 commandId: string | null;
20 payload: unknown;
21}): OrchestrationEvent {
22 return {
23 sequence: input.sequence,
24 eventId: EventId.makeUnsafe(`event-${input.sequence}`),
25 type: input.type,
26 aggregateKind: input.aggregateKind,
27 aggregateId:
28 input.aggregateKind === "project"
29 ? ProjectId.makeUnsafe(input.aggregateId)
30 : ThreadId.makeUnsafe(input.aggregateId),
31 occurredAt: input.occurredAt,
32 commandId: input.commandId === null ? null : CommandId.makeUnsafe(input.commandId),
33 causationEventId: null,
34 correlationId: null,
35 metadata: {},
36 payload: input.payload as never,
37 } as OrchestrationEvent;
38}
39
40describe("orchestration projector", () => {
41 it("applies thread.created events", async () => {
42 const now = new Date().toISOString();
43 const model = createEmptyReadModel(now);
44
45 const next = await Effect.runPromise(
46 projectEvent(
47 model,
48 makeEvent({
49 sequence: 1,
50 type: "thread.created",
51 aggregateKind: "thread",
52 aggregateId: "thread-1",
53 occurredAt: now,
54 commandId: "cmd-thread-create",
55 payload: {
56 threadId: "thread-1",
57 projectId: "project-1",
58 title: "demo",
59 model: "gpt-5-codex",
60 branch: null,
61 worktreePath: null,
62 createdAt: now,
63 updatedAt: now,
64 },
65 }),
66 ),
67 );
68
69 expect(next.snapshotSequence).toBe(1);
70 expect(next.threads).toEqual([
71 {
72 id: "thread-1",
73 projectId: "project-1",
74 title: "demo",
75 model: "gpt-5-codex",
76 branch: null,
77 worktreePath: null,
78 latestTurn: null,
79 createdAt: now,
80 updatedAt: now,
81 deletedAt: null,
82 messages: [],
83 activities: [],
84 checkpoints: [],
85 session: null,
86 },
87 ]);
88 });
89
90 it("fails when event payload cannot be decoded by runtime schema", async () => {
91 const now = new Date().toISOString();
92 const model = createEmptyReadModel(now);
93
94 await expect(
95 Effect.runPromise(
96 projectEvent(
97 model,
98 makeEvent({
99 sequence: 1,
100 type: "thread.created",
101 aggregateKind: "thread",
102 aggregateId: "thread-1",
103 occurredAt: now,
104 commandId: "cmd-invalid",
105 payload: {
106 // missing required threadId
107 projectId: "project-1",
108 title: "demo",
109 model: "gpt-5-codex",
110 branch: null,
111 worktreePath: null,
112 createdAt: now,
113 updatedAt: now,
114 },
115 }),
116 ),
117 ),
118 ).rejects.toBeDefined();
119 });
120
121 it("keeps projector forward-compatible for unhandled event types", async () => {
122 const now = new Date().toISOString();
123 const model = createEmptyReadModel(now);
124
125 const next = await Effect.runPromise(
126 projectEvent(
127 model,
128 makeEvent({
129 sequence: 7,
130 type: "thread.turn-start-requested",
131 aggregateKind: "thread",
132 aggregateId: "thread-1",
133 occurredAt: "2026-01-01T00:00:00.000Z",
134 commandId: "cmd-unhandled",
135 payload: {
136 threadId: "thread-1",
137 messageId: "message-1",
138 approvalPolicy: "on-request",
139 sandboxMode: "workspace-write",
140 createdAt: "2026-01-01T00:00:00.000Z",
141 },
142 }),
143 ),
144 );
145
146 expect(next.snapshotSequence).toBe(7);
147 expect(next.updatedAt).toBe("2026-01-01T00:00:00.000Z");
148 expect(next.threads).toEqual([]);
149 });
150
151 it("tracks latest turn id from session lifecycle events", async () => {
152 const createdAt = "2026-02-23T08:00:00.000Z";
153 const startedAt = "2026-02-23T08:00:05.000Z";
154 const model = createEmptyReadModel(createdAt);
155
156 const afterCreate = await Effect.runPromise(
157 projectEvent(
158 model,
159 makeEvent({
160 sequence: 1,
161 type: "thread.created",
162 aggregateKind: "thread",
163 aggregateId: "thread-1",
164 occurredAt: createdAt,
165 commandId: "cmd-create",
166 payload: {
167 threadId: "thread-1",
168 projectId: "project-1",
169 title: "demo",
170 model: "gpt-5.3-codex",
171 branch: null,
172 worktreePath: null,
173 createdAt,
174 updatedAt: createdAt,
175 },
176 }),
177 ),
178 );
179
180 const afterRunning = await Effect.runPromise(
181 projectEvent(
182 afterCreate,
183 makeEvent({
184 sequence: 2,
185 type: "thread.session-set",
186 aggregateKind: "thread",
187 aggregateId: "thread-1",
188 occurredAt: startedAt,
189 commandId: "cmd-running",
190 payload: {
191 threadId: "thread-1",
192 session: {
193 threadId: "thread-1",
194 status: "running",
195 providerName: "codex",
196 providerSessionId: "session-1",
197 providerThreadId: "provider-thread-1",
198 approvalPolicy: "on-request",
199 sandboxMode: "workspace-write",
200 activeTurnId: "turn-1",
201 lastError: null,
202 updatedAt: startedAt,
203 },
204 },
205 }),
206 ),
207 );
208
209 const thread = afterRunning.threads[0];
210 expect(thread?.latestTurn?.turnId).toBe("turn-1");
211 expect(thread?.session?.status).toBe("running");
212 });
213
214 it("marks assistant messages completed with non-streaming updates", async () => {
215 const createdAt = "2026-02-23T09:00:00.000Z";
216 const deltaAt = "2026-02-23T09:00:01.000Z";
217 const completeAt = "2026-02-23T09:00:03.500Z";
218 const model = createEmptyReadModel(createdAt);
219
220 const afterCreate = await Effect.runPromise(
221 projectEvent(
222 model,
223 makeEvent({
224 sequence: 1,
225 type: "thread.created",
226 aggregateKind: "thread",
227 aggregateId: "thread-1",
228 occurredAt: createdAt,
229 commandId: "cmd-create",
230 payload: {
231 threadId: "thread-1",
232 projectId: "project-1",
233 title: "demo",
234 model: "gpt-5.3-codex",
235 branch: null,
236 worktreePath: null,
237 createdAt,
238 updatedAt: createdAt,
239 },
240 }),
241 ),
242 );
243
244 const afterDelta = await Effect.runPromise(
245 projectEvent(
246 afterCreate,
247 makeEvent({
248 sequence: 2,
249 type: "thread.message-sent",
250 aggregateKind: "thread",
251 aggregateId: "thread-1",
252 occurredAt: deltaAt,
253 commandId: "cmd-delta",
254 payload: {
255 threadId: "thread-1",
256 messageId: "assistant:msg-1",
257 role: "assistant",
258 text: "hello",
259 turnId: "turn-1",
260 streaming: true,
261 createdAt: deltaAt,
262 updatedAt: deltaAt,
263 },
264 }),
265 ),
266 );
267
268 const afterComplete = await Effect.runPromise(
269 projectEvent(
270 afterDelta,
271 makeEvent({
272 sequence: 3,
273 type: "thread.message-sent",
274 aggregateKind: "thread",
275 aggregateId: "thread-1",
276 occurredAt: completeAt,
277 commandId: "cmd-complete",
278 payload: {
279 threadId: "thread-1",
280 messageId: "assistant:msg-1",
281 role: "assistant",
282 text: "",
283 turnId: "turn-1",
284 streaming: false,
285 createdAt: completeAt,
286 updatedAt: completeAt,
287 },
288 }),
289 ),
290 );
291
292 const message = afterComplete.threads[0]?.messages[0];
293 expect(message?.id).toBe("assistant:msg-1");
294 expect(message?.text).toBe("hello");
295 expect(message?.streaming).toBe(false);
296 expect(message?.updatedAt).toBe(completeAt);
297 });
298
299 it("prunes reverted turn messages from in-memory thread snapshot", async () => {
300 const createdAt = "2026-02-23T10:00:00.000Z";
301 const model = createEmptyReadModel(createdAt);
302
303 const afterCreate = await Effect.runPromise(
304 projectEvent(
305 model,
306 makeEvent({
307 sequence: 1,
308 type: "thread.created",
309 aggregateKind: "thread",
310 aggregateId: "thread-1",
311 occurredAt: createdAt,
312 commandId: "cmd-create",
313 payload: {
314 threadId: "thread-1",
315 projectId: "project-1",
316 title: "demo",
317 model: "gpt-5.3-codex",
318 branch: null,
319 worktreePath: null,
320 createdAt,
321 updatedAt: createdAt,
322 },
323 }),
324 ),
325 );
326
327 const events: ReadonlyArray<OrchestrationEvent> = [
328 makeEvent({
329 sequence: 2,
330 type: "thread.message-sent",
331 aggregateKind: "thread",
332 aggregateId: "thread-1",
333 occurredAt: "2026-02-23T10:00:01.000Z",
334 commandId: "cmd-user-1",
335 payload: {
336 threadId: "thread-1",
337 messageId: "user-msg-1",
338 role: "user",
339 text: "First edit",
340 turnId: null,
341 streaming: false,
342 createdAt: "2026-02-23T10:00:01.000Z",
343 updatedAt: "2026-02-23T10:00:01.000Z",
344 },
345 }),
346 makeEvent({
347 sequence: 3,
348 type: "thread.message-sent",
349 aggregateKind: "thread",
350 aggregateId: "thread-1",
351 occurredAt: "2026-02-23T10:00:02.000Z",
352 commandId: "cmd-assistant-1",
353 payload: {
354 threadId: "thread-1",
355 messageId: "assistant-msg-1",
356 role: "assistant",
357 text: "Updated README to v2.\n",
358 turnId: "turn-1",
359 streaming: false,
360 createdAt: "2026-02-23T10:00:02.000Z",
361 updatedAt: "2026-02-23T10:00:02.000Z",
362 },
363 }),
364 makeEvent({
365 sequence: 4,
366 type: "thread.turn-diff-completed",
367 aggregateKind: "thread",
368 aggregateId: "thread-1",
369 occurredAt: "2026-02-23T10:00:02.500Z",
370 commandId: "cmd-turn-1-complete",
371 payload: {
372 threadId: "thread-1",
373 turnId: "turn-1",
374 checkpointTurnCount: 1,
375 checkpointRef: "refs/t3/checkpoints/thread-1/turn/1",
376 status: "ready",
377 files: [],
378 assistantMessageId: "assistant-msg-1",
379 completedAt: "2026-02-23T10:00:02.500Z",
380 },
381 }),
382 makeEvent({
383 sequence: 5,
384 type: "thread.activity-appended",
385 aggregateKind: "thread",
386 aggregateId: "thread-1",
387 occurredAt: "2026-02-23T10:00:02.750Z",
388 commandId: "cmd-activity-1",
389 payload: {
390 threadId: "thread-1",
391 activity: {
392 id: "activity-1",
393 tone: "tool",
394 kind: "tool.started",
395 summary: "Edit file started",
396 payload: { toolKind: "command" },
397 turnId: "turn-1",
398 createdAt: "2026-02-23T10:00:02.750Z",
399 },
400 },
401 }),
402 makeEvent({
403 sequence: 6,
404 type: "thread.message-sent",
405 aggregateKind: "thread",
406 aggregateId: "thread-1",
407 occurredAt: "2026-02-23T10:00:03.000Z",
408 commandId: "cmd-user-2",
409 payload: {
410 threadId: "thread-1",
411 messageId: "user-msg-2",
412 role: "user",
413 text: "Second edit",
414 turnId: null,
415 streaming: false,
416 createdAt: "2026-02-23T10:00:03.000Z",
417 updatedAt: "2026-02-23T10:00:03.000Z",
418 },
419 }),
420 makeEvent({
421 sequence: 7,
422 type: "thread.message-sent",
423 aggregateKind: "thread",
424 aggregateId: "thread-1",
425 occurredAt: "2026-02-23T10:00:04.000Z",
426 commandId: "cmd-assistant-2",
427 payload: {
428 threadId: "thread-1",
429 messageId: "assistant-msg-2",
430 role: "assistant",
431 text: "Updated README to v3.\n",
432 turnId: "turn-2",
433 streaming: false,
434 createdAt: "2026-02-23T10:00:04.000Z",
435 updatedAt: "2026-02-23T10:00:04.000Z",
436 },
437 }),
438 makeEvent({
439 sequence: 8,
440 type: "thread.turn-diff-completed",
441 aggregateKind: "thread",
442 aggregateId: "thread-1",
443 occurredAt: "2026-02-23T10:00:04.500Z",
444 commandId: "cmd-turn-2-complete",
445 payload: {
446 threadId: "thread-1",
447 turnId: "turn-2",
448 checkpointTurnCount: 2,
449 checkpointRef: "refs/t3/checkpoints/thread-1/turn/2",
450 status: "ready",
451 files: [],
452 assistantMessageId: "assistant-msg-2",
453 completedAt: "2026-02-23T10:00:04.500Z",
454 },
455 }),
456 makeEvent({
457 sequence: 9,
458 type: "thread.activity-appended",
459 aggregateKind: "thread",
460 aggregateId: "thread-1",
461 occurredAt: "2026-02-23T10:00:04.750Z",
462 commandId: "cmd-activity-2",
463 payload: {
464 threadId: "thread-1",
465 activity: {
466 id: "activity-2",
467 tone: "tool",
468 kind: "tool.completed",
469 summary: "Edit file complete",
470 payload: { toolKind: "command" },
471 turnId: "turn-2",
472 createdAt: "2026-02-23T10:00:04.750Z",
473 },
474 },
475 }),
476 makeEvent({
477 sequence: 10,
478 type: "thread.reverted",
479 aggregateKind: "thread",
480 aggregateId: "thread-1",
481 occurredAt: "2026-02-23T10:00:05.000Z",
482 commandId: "cmd-revert",
483 payload: {
484 threadId: "thread-1",
485 turnCount: 1,
486 },
487 }),
488 ];
489
490 const afterRevert = await events.reduce<Promise<ReturnType<typeof createEmptyReadModel>>>(
491 (statePromise, event) =>
492 statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
493 Promise.resolve(afterCreate),
494 );
495
496 const thread = afterRevert.threads[0];
497 expect(thread?.messages.map((message) => ({ role: message.role, text: message.text }))).toEqual(
498 [
499 { role: "user", text: "First edit" },
500 { role: "assistant", text: "Updated README to v2.\n" },
501 ],
502 );
503 expect(
504 thread?.activities.map((activity) => ({ id: activity.id, turnId: activity.turnId })),
505 ).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
506 expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
507 expect(thread?.latestTurn?.turnId).toBe("turn-1");
508 });
509
510 it("does not fallback-retain messages tied to removed turn IDs", async () => {
511 const createdAt = "2026-02-26T12:00:00.000Z";
512 const model = createEmptyReadModel(createdAt);
513
514 const afterCreate = await Effect.runPromise(
515 projectEvent(
516 model,
517 makeEvent({
518 sequence: 1,
519 type: "thread.created",
520 aggregateKind: "thread",
521 aggregateId: "thread-revert",
522 occurredAt: createdAt,
523 commandId: "cmd-create-revert",
524 payload: {
525 threadId: "thread-revert",
526 projectId: "project-1",
527 title: "demo",
528 model: "gpt-5.3-codex",
529 branch: null,
530 worktreePath: null,
531 createdAt,
532 updatedAt: createdAt,
533 },
534 }),
535 ),
536 );
537
538 const events: ReadonlyArray<OrchestrationEvent> = [
539 makeEvent({
540 sequence: 2,
541 type: "thread.turn-diff-completed",
542 aggregateKind: "thread",
543 aggregateId: "thread-revert",
544 occurredAt: "2026-02-26T12:00:01.000Z",
545 commandId: "cmd-turn-1",
546 payload: {
547 threadId: "thread-revert",
548 turnId: "turn-1",
549 checkpointTurnCount: 1,
550 checkpointRef: "refs/t3/checkpoints/thread-revert/turn/1",
551 status: "ready",
552 files: [],
553 assistantMessageId: "assistant-keep",
554 completedAt: "2026-02-26T12:00:01.000Z",
555 },
556 }),
557 makeEvent({
558 sequence: 3,
559 type: "thread.message-sent",
560 aggregateKind: "thread",
561 aggregateId: "thread-revert",
562 occurredAt: "2026-02-26T12:00:01.100Z",
563 commandId: "cmd-assistant-keep",
564 payload: {
565 threadId: "thread-revert",
566 messageId: "assistant-keep",
567 role: "assistant",
568 text: "kept",
569 turnId: "turn-1",
570 streaming: false,
571 createdAt: "2026-02-26T12:00:01.100Z",
572 updatedAt: "2026-02-26T12:00:01.100Z",
573 },
574 }),
575 makeEvent({
576 sequence: 4,
577 type: "thread.turn-diff-completed",
578 aggregateKind: "thread",
579 aggregateId: "thread-revert",
580 occurredAt: "2026-02-26T12:00:02.000Z",
581 commandId: "cmd-turn-2",
582 payload: {
583 threadId: "thread-revert",
584 turnId: "turn-2",
585 checkpointTurnCount: 2,
586 checkpointRef: "refs/t3/checkpoints/thread-revert/turn/2",
587 status: "ready",
588 files: [],
589 assistantMessageId: "assistant-remove",
590 completedAt: "2026-02-26T12:00:02.000Z",
591 },
592 }),
593 makeEvent({
594 sequence: 5,
595 type: "thread.message-sent",
596 aggregateKind: "thread",
597 aggregateId: "thread-revert",
598 occurredAt: "2026-02-26T12:00:02.050Z",
599 commandId: "cmd-user-remove",
600 payload: {
601 threadId: "thread-revert",
602 messageId: "user-remove",
603 role: "user",
604 text: "removed",
605 turnId: "turn-2",
606 streaming: false,
607 createdAt: "2026-02-26T12:00:02.050Z",
608 updatedAt: "2026-02-26T12:00:02.050Z",
609 },
610 }),
611 makeEvent({
612 sequence: 6,
613 type: "thread.message-sent",
614 aggregateKind: "thread",
615 aggregateId: "thread-revert",
616 occurredAt: "2026-02-26T12:00:02.100Z",
617 commandId: "cmd-assistant-remove",
618 payload: {
619 threadId: "thread-revert",
620 messageId: "assistant-remove",
621 role: "assistant",
622 text: "removed",
623 turnId: "turn-2",
624 streaming: false,
625 createdAt: "2026-02-26T12:00:02.100Z",
626 updatedAt: "2026-02-26T12:00:02.100Z",
627 },
628 }),
629 makeEvent({
630 sequence: 7,
631 type: "thread.reverted",
632 aggregateKind: "thread",
633 aggregateId: "thread-revert",
634 occurredAt: "2026-02-26T12:00:03.000Z",
635 commandId: "cmd-revert",
636 payload: {
637 threadId: "thread-revert",
638 turnCount: 1,
639 },
640 }),
641 ];
642
643 const afterRevert = await events.reduce<Promise<ReturnType<typeof createEmptyReadModel>>>(
644 (statePromise, event) =>
645 statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
646 Promise.resolve(afterCreate),
647 );
648
649 const thread = afterRevert.threads[0];
650 expect(
651 thread?.messages.map((message) => ({
652 id: message.id,
653 role: message.role,
654 turnId: message.turnId,
655 })),
656 ).toEqual([{ id: "assistant-keep", role: "assistant", turnId: "turn-1" }]);
657 });
658
659 it("caps message and checkpoint retention for long-lived threads", async () => {
660 const createdAt = "2026-03-01T10:00:00.000Z";
661 const model = createEmptyReadModel(createdAt);
662
663 const afterCreate = await Effect.runPromise(
664 projectEvent(
665 model,
666 makeEvent({
667 sequence: 1,
668 type: "thread.created",
669 aggregateKind: "thread",
670 aggregateId: "thread-capped",
671 occurredAt: createdAt,
672 commandId: "cmd-create-capped",
673 payload: {
674 threadId: "thread-capped",
675 projectId: "project-1",
676 title: "capped",
677 model: "gpt-5-codex",
678 branch: null,
679 worktreePath: null,
680 createdAt,
681 updatedAt: createdAt,
682 },
683 }),
684 ),
685 );
686
687 const messageEvents: ReadonlyArray<OrchestrationEvent> = Array.from(
688 { length: 2_100 },
689 (_, index) =>
690 makeEvent({
691 sequence: index + 2,
692 type: "thread.message-sent",
693 aggregateKind: "thread",
694 aggregateId: "thread-capped",
695 occurredAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`,
696 commandId: `cmd-message-${index}`,
697 payload: {
698 threadId: "thread-capped",
699 messageId: `msg-${index}`,
700 role: "assistant",
701 text: `message-${index}`,
702 turnId: `turn-${index}`,
703 streaming: false,
704 createdAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`,
705 updatedAt: `2026-03-01T10:00:${String(index % 60).padStart(2, "0")}.000Z`,
706 },
707 }),
708 );
709 const afterMessages = await messageEvents.reduce<
710 Promise<ReturnType<typeof createEmptyReadModel>>
711 >(
712 (statePromise, event) =>
713 statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
714 Promise.resolve(afterCreate),
715 );
716
717 const checkpointEvents: ReadonlyArray<OrchestrationEvent> = Array.from(
718 { length: 600 },
719 (_, index) =>
720 makeEvent({
721 sequence: index + 2_102,
722 type: "thread.turn-diff-completed",
723 aggregateKind: "thread",
724 aggregateId: "thread-capped",
725 occurredAt: `2026-03-01T10:30:${String(index % 60).padStart(2, "0")}.000Z`,
726 commandId: `cmd-checkpoint-${index}`,
727 payload: {
728 threadId: "thread-capped",
729 turnId: `turn-${index}`,
730 checkpointTurnCount: index + 1,
731 checkpointRef: `refs/t3/checkpoints/thread-capped/turn/${index + 1}`,
732 status: "ready",
733 files: [],
734 assistantMessageId: `msg-${index}`,
735 completedAt: `2026-03-01T10:30:${String(index % 60).padStart(2, "0")}.000Z`,
736 },
737 }),
738 );
739 const finalState = await checkpointEvents.reduce<
740 Promise<ReturnType<typeof createEmptyReadModel>>
741 >(
742 (statePromise, event) =>
743 statePromise.then((state) => Effect.runPromise(projectEvent(state, event))),
744 Promise.resolve(afterMessages),
745 );
746
747 const thread = finalState.threads[0];
748 expect(thread?.messages).toHaveLength(2_000);
749 expect(thread?.messages[0]?.id).toBe("msg-100");
750 expect(thread?.messages.at(-1)?.id).toBe("msg-2099");
751 expect(thread?.checkpoints).toHaveLength(500);
752 expect(thread?.checkpoints[0]?.turnId).toBe("turn-100");
753 expect(thread?.checkpoints.at(-1)?.turnId).toBe("turn-599");
754 });
755});