Open History to see the last commit
1import {
2 ApprovalRequestId,
3 type ChatAttachment,
4 type OrchestrationEvent,
5} from "@t3tools/contracts";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
8import * as SqlClient from "effect/unstable/sql/SqlClient";
9
10import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
11import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
12import { ProjectionPendingApprovalRepository } from "../../persistence/Services/ProjectionPendingApprovals.ts";
13import { ProjectionProjectRepository } from "../../persistence/Services/ProjectionProjects.ts";
14import { ProjectionStateRepository } from "../../persistence/Services/ProjectionState.ts";
15import { ProjectionThreadActivityRepository } from "../../persistence/Services/ProjectionThreadActivities.ts";
16import { type ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
17import {
18 type ProjectionThreadMessage,
19 ProjectionThreadMessageRepository,
20} from "../../persistence/Services/ProjectionThreadMessages.ts";
21import {
22 type ProjectionThreadProposedPlan,
23 ProjectionThreadProposedPlanRepository,
24} from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
25import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
26import {
27 type ProjectionTurn,
28 ProjectionTurnRepository,
29} from "../../persistence/Services/ProjectionTurns.ts";
30import { ProjectionThreadRepository } from "../../persistence/Services/ProjectionThreads.ts";
31import { ProjectionPendingApprovalRepositoryLive } from "../../persistence/Layers/ProjectionPendingApprovals.ts";
32import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/ProjectionProjects.ts";
33import { ProjectionStateRepositoryLive } from "../../persistence/Layers/ProjectionState.ts";
34import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
35import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
36import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
37import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
38import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
39import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
40import { ServerConfig } from "../../config.ts";
41import {
42 OrchestrationProjectionPipeline,
43 type OrchestrationProjectionPipelineShape,
44} from "../Services/ProjectionPipeline.ts";
45import {
46 attachmentRelativePath,
47 parseAttachmentIdFromRelativePath,
48 parseThreadSegmentFromAttachmentId,
49 toSafeThreadAttachmentSegment,
50} from "../../attachmentStore.ts";
51
52export const ORCHESTRATION_PROJECTOR_NAMES = {
53 projects: "projection.projects",
54 threads: "projection.threads",
55 threadMessages: "projection.thread-messages",
56 threadProposedPlans: "projection.thread-proposed-plans",
57 threadActivities: "projection.thread-activities",
58 threadSessions: "projection.thread-sessions",
59 threadTurns: "projection.thread-turns",
60 checkpoints: "projection.checkpoints",
61 pendingApprovals: "projection.pending-approvals",
62} as const;
63
64type ProjectorName =
65 (typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES];
66
67interface ProjectorDefinition {
68 readonly name: ProjectorName;
69 readonly apply: (
70 event: OrchestrationEvent,
71 attachmentSideEffects: AttachmentSideEffects,
72 ) => Effect.Effect<void, ProjectionRepositoryError>;
73}
74
75interface AttachmentSideEffects {
76 readonly deletedThreadIds: Set<string>;
77 readonly prunedThreadRelativePaths: Map<string, Set<string>>;
78}
79
80const materializeAttachmentsForProjection = Effect.fn("materializeAttachmentsForProjection")(
81 (input: { readonly attachments: ReadonlyArray<ChatAttachment> }) =>
82 Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),
83);
84
85function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
86 if (typeof payload !== "object" || payload === null) {
87 return null;
88 }
89 const requestId = (payload as Record<string, unknown>).requestId;
90 return typeof requestId === "string" ? ApprovalRequestId.makeUnsafe(requestId) : null;
91}
92
93function retainProjectionMessagesAfterRevert(
94 messages: ReadonlyArray<ProjectionThreadMessage>,
95 turns: ReadonlyArray<ProjectionTurn>,
96 turnCount: number,
97): ReadonlyArray<ProjectionThreadMessage> {
98 const retainedMessageIds = new Set<string>();
99 const retainedTurnIds = new Set<string>();
100 const keptTurns = turns.filter(
101 (turn) =>
102 turn.turnId !== null &&
103 turn.checkpointTurnCount !== null &&
104 turn.checkpointTurnCount <= turnCount,
105 );
106 for (const turn of keptTurns) {
107 if (turn.turnId !== null) {
108 retainedTurnIds.add(turn.turnId);
109 }
110 if (turn.pendingMessageId !== null) {
111 retainedMessageIds.add(turn.pendingMessageId);
112 }
113 if (turn.assistantMessageId !== null) {
114 retainedMessageIds.add(turn.assistantMessageId);
115 }
116 }
117
118 for (const message of messages) {
119 if (message.role === "system") {
120 retainedMessageIds.add(message.messageId);
121 continue;
122 }
123 if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {
124 retainedMessageIds.add(message.messageId);
125 }
126 }
127
128 const retainedUserCount = messages.filter(
129 (message) => message.role === "user" && retainedMessageIds.has(message.messageId),
130 ).length;
131 const missingUserCount = Math.max(0, turnCount - retainedUserCount);
132 if (missingUserCount > 0) {
133 const fallbackUserMessages = messages
134 .filter(
135 (message) =>
136 message.role === "user" &&
137 !retainedMessageIds.has(message.messageId) &&
138 (message.turnId === null || retainedTurnIds.has(message.turnId)),
139 )
140 .toSorted(
141 (left, right) =>
142 left.createdAt.localeCompare(right.createdAt) ||
143 left.messageId.localeCompare(right.messageId),
144 )
145 .slice(0, missingUserCount);
146 for (const message of fallbackUserMessages) {
147 retainedMessageIds.add(message.messageId);
148 }
149 }
150
151 const retainedAssistantCount = messages.filter(
152 (message) => message.role === "assistant" && retainedMessageIds.has(message.messageId),
153 ).length;
154 const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount);
155 if (missingAssistantCount > 0) {
156 const fallbackAssistantMessages = messages
157 .filter(
158 (message) =>
159 message.role === "assistant" &&
160 !retainedMessageIds.has(message.messageId) &&
161 (message.turnId === null || retainedTurnIds.has(message.turnId)),
162 )
163 .toSorted(
164 (left, right) =>
165 left.createdAt.localeCompare(right.createdAt) ||
166 left.messageId.localeCompare(right.messageId),
167 )
168 .slice(0, missingAssistantCount);
169 for (const message of fallbackAssistantMessages) {
170 retainedMessageIds.add(message.messageId);
171 }
172 }
173
174 return messages.filter((message) => retainedMessageIds.has(message.messageId));
175}
176
177function retainProjectionActivitiesAfterRevert(
178 activities: ReadonlyArray<ProjectionThreadActivity>,
179 turns: ReadonlyArray<ProjectionTurn>,
180 turnCount: number,
181): ReadonlyArray<ProjectionThreadActivity> {
182 const retainedTurnIds = new Set<string>(
183 turns
184 .filter(
185 (turn) =>
186 turn.turnId !== null &&
187 turn.checkpointTurnCount !== null &&
188 turn.checkpointTurnCount <= turnCount,
189 )
190 .flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),
191 );
192 return activities.filter(
193 (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),
194 );
195}
196
197function retainProjectionProposedPlansAfterRevert(
198 proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>,
199 turns: ReadonlyArray<ProjectionTurn>,
200 turnCount: number,
201): ReadonlyArray<ProjectionThreadProposedPlan> {
202 const retainedTurnIds = new Set<string>(
203 turns
204 .filter(
205 (turn) =>
206 turn.turnId !== null &&
207 turn.checkpointTurnCount !== null &&
208 turn.checkpointTurnCount <= turnCount,
209 )
210 .flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),
211 );
212 return proposedPlans.filter(
213 (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),
214 );
215}
216
217function collectThreadAttachmentRelativePaths(
218 threadId: string,
219 messages: ReadonlyArray<ProjectionThreadMessage>,
220): Set<string> {
221 const threadSegment = toSafeThreadAttachmentSegment(threadId);
222 if (!threadSegment) {
223 return new Set();
224 }
225 const relativePaths = new Set<string>();
226 for (const message of messages) {
227 for (const attachment of message.attachments ?? []) {
228 if (attachment.type !== "image") {
229 continue;
230 }
231 const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);
232 if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
233 continue;
234 }
235 relativePaths.add(attachmentRelativePath(attachment));
236 }
237 }
238 return relativePaths;
239}
240
241const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function* (
242 sideEffects: AttachmentSideEffects,
243) {
244 const serverConfig = yield* Effect.service(ServerConfig);
245 const fileSystem = yield* Effect.service(FileSystem.FileSystem);
246 const path = yield* Effect.service(Path.Path);
247
248 const attachmentsRootDir = serverConfig.attachmentsDir;
249 const readAttachmentRootEntries = fileSystem
250 .readDirectory(attachmentsRootDir, { recursive: false })
251 .pipe(Effect.catch(() => Effect.succeed([] as Array<string>)));
252
253 const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")(
254 function* (threadSegment: string, entry: string) {
255 const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
256 if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) {
257 return;
258 }
259 const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);
260 if (!attachmentId) {
261 return;
262 }
263 const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
264 if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
265 return;
266 }
267 yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {
268 force: true,
269 });
270 },
271 );
272
273 const deleteThreadAttachments = Effect.fn("deleteThreadAttachments")(function* (
274 threadId: string,
275 ) {
276 const threadSegment = toSafeThreadAttachmentSegment(threadId);
277 if (!threadSegment) {
278 yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", {
279 threadId,
280 });
281 return;
282 }
283
284 const entries = yield* readAttachmentRootEntries;
285 yield* Effect.forEach(
286 entries,
287 (entry) => removeDeletedThreadAttachmentEntry(threadSegment, entry),
288 {
289 concurrency: 1,
290 },
291 );
292 });
293
294 const pruneThreadAttachmentEntry = Effect.fn("pruneThreadAttachmentEntry")(function* (
295 threadSegment: string,
296 keptThreadRelativePaths: Set<string>,
297 entry: string,
298 ) {
299 const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/");
300 if (relativePath.length === 0 || relativePath.includes("/")) {
301 return;
302 }
303 const attachmentId = parseAttachmentIdFromRelativePath(relativePath);
304 if (!attachmentId) {
305 return;
306 }
307 const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);
308 if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {
309 return;
310 }
311
312 const absolutePath = path.join(attachmentsRootDir, relativePath);
313 const fileInfo = yield* fileSystem
314 .stat(absolutePath)
315 .pipe(Effect.catch(() => Effect.succeed(null)));
316 if (!fileInfo || fileInfo.type !== "File") {
317 return;
318 }
319
320 if (!keptThreadRelativePaths.has(relativePath)) {
321 yield* fileSystem.remove(absolutePath, { force: true });
322 }
323 });
324
325 const pruneThreadAttachments = Effect.fn("pruneThreadAttachments")(function* (
326 threadId: string,
327 keptThreadRelativePaths: Set<string>,
328 ) {
329 if (sideEffects.deletedThreadIds.has(threadId)) {
330 return;
331 }
332
333 const threadSegment = toSafeThreadAttachmentSegment(threadId);
334 if (!threadSegment) {
335 yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId });
336 return;
337 }
338
339 const entries = yield* readAttachmentRootEntries;
340 yield* Effect.forEach(
341 entries,
342 (entry) => pruneThreadAttachmentEntry(threadSegment, keptThreadRelativePaths, entry),
343 { concurrency: 1 },
344 );
345 });
346
347 yield* Effect.forEach(sideEffects.deletedThreadIds, deleteThreadAttachments, {
348 concurrency: 1,
349 });
350
351 yield* Effect.forEach(
352 sideEffects.prunedThreadRelativePaths.entries(),
353 ([threadId, keptThreadRelativePaths]) =>
354 pruneThreadAttachments(threadId, keptThreadRelativePaths),
355 { concurrency: 1 },
356 );
357});
358
359const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectionPipeline")(
360 function* () {
361 const sql = yield* SqlClient.SqlClient;
362 const eventStore = yield* OrchestrationEventStore;
363 const projectionStateRepository = yield* ProjectionStateRepository;
364 const projectionProjectRepository = yield* ProjectionProjectRepository;
365 const projectionThreadRepository = yield* ProjectionThreadRepository;
366 const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
367 const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
368 const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
369 const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
370 const projectionTurnRepository = yield* ProjectionTurnRepository;
371 const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
372
373 const fileSystem = yield* FileSystem.FileSystem;
374 const path = yield* Path.Path;
375 const serverConfig = yield* ServerConfig;
376
377 const applyProjectsProjection: ProjectorDefinition["apply"] = Effect.fn(
378 "applyProjectsProjection",
379 )(function* (event, _attachmentSideEffects) {
380 switch (event.type) {
381 case "project.created":
382 yield* projectionProjectRepository.upsert({
383 projectId: event.payload.projectId,
384 title: event.payload.title,
385 workspaceRoot: event.payload.workspaceRoot,
386 defaultModelSelection: event.payload.defaultModelSelection,
387 scripts: event.payload.scripts,
388 createdAt: event.payload.createdAt,
389 updatedAt: event.payload.updatedAt,
390 deletedAt: null,
391 });
392 return;
393
394 case "project.meta-updated": {
395 const existingRow = yield* projectionProjectRepository.getById({
396 projectId: event.payload.projectId,
397 });
398 if (Option.isNone(existingRow)) {
399 return;
400 }
401 yield* projectionProjectRepository.upsert({
402 ...existingRow.value,
403 ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
404 ...(event.payload.workspaceRoot !== undefined
405 ? { workspaceRoot: event.payload.workspaceRoot }
406 : {}),
407 ...(event.payload.defaultModelSelection !== undefined
408 ? { defaultModelSelection: event.payload.defaultModelSelection }
409 : {}),
410 ...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
411 updatedAt: event.payload.updatedAt,
412 });
413 return;
414 }
415
416 case "project.deleted": {
417 const existingRow = yield* projectionProjectRepository.getById({
418 projectId: event.payload.projectId,
419 });
420 if (Option.isNone(existingRow)) {
421 return;
422 }
423 yield* projectionProjectRepository.upsert({
424 ...existingRow.value,
425 deletedAt: event.payload.deletedAt,
426 updatedAt: event.payload.deletedAt,
427 });
428 return;
429 }
430
431 default:
432 return;
433 }
434 });
435
436 const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn(
437 "applyThreadsProjection",
438 )(function* (event, attachmentSideEffects) {
439 switch (event.type) {
440 case "thread.created":
441 yield* projectionThreadRepository.upsert({
442 threadId: event.payload.threadId,
443 projectId: event.payload.projectId,
444 title: event.payload.title,
445 modelSelection: event.payload.modelSelection,
446 runtimeMode: event.payload.runtimeMode,
447 interactionMode: event.payload.interactionMode,
448 branch: event.payload.branch,
449 worktreePath: event.payload.worktreePath,
450 latestTurnId: null,
451 createdAt: event.payload.createdAt,
452 updatedAt: event.payload.updatedAt,
453 archivedAt: null,
454 deletedAt: null,
455 });
456 return;
457
458 case "thread.archived": {
459 const existingRow = yield* projectionThreadRepository.getById({
460 threadId: event.payload.threadId,
461 });
462 if (Option.isNone(existingRow)) {
463 return;
464 }
465 yield* projectionThreadRepository.upsert({
466 ...existingRow.value,
467 archivedAt: event.payload.archivedAt,
468 updatedAt: event.payload.updatedAt,
469 });
470 return;
471 }
472
473 case "thread.unarchived": {
474 const existingRow = yield* projectionThreadRepository.getById({
475 threadId: event.payload.threadId,
476 });
477 if (Option.isNone(existingRow)) {
478 return;
479 }
480 yield* projectionThreadRepository.upsert({
481 ...existingRow.value,
482 archivedAt: null,
483 updatedAt: event.payload.updatedAt,
484 });
485 return;
486 }
487
488 case "thread.meta-updated": {
489 const existingRow = yield* projectionThreadRepository.getById({
490 threadId: event.payload.threadId,
491 });
492 if (Option.isNone(existingRow)) {
493 return;
494 }
495 yield* projectionThreadRepository.upsert({
496 ...existingRow.value,
497 ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
498 ...(event.payload.modelSelection !== undefined
499 ? { modelSelection: event.payload.modelSelection }
500 : {}),
501 ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
502 ...(event.payload.worktreePath !== undefined
503 ? { worktreePath: event.payload.worktreePath }
504 : {}),
505 updatedAt: event.payload.updatedAt,
506 });
507 return;
508 }
509
510 case "thread.runtime-mode-set": {
511 const existingRow = yield* projectionThreadRepository.getById({
512 threadId: event.payload.threadId,
513 });
514 if (Option.isNone(existingRow)) {
515 return;
516 }
517 yield* projectionThreadRepository.upsert({
518 ...existingRow.value,
519 runtimeMode: event.payload.runtimeMode,
520 updatedAt: event.payload.updatedAt,
521 });
522 return;
523 }
524
525 case "thread.interaction-mode-set": {
526 const existingRow = yield* projectionThreadRepository.getById({
527 threadId: event.payload.threadId,
528 });
529 if (Option.isNone(existingRow)) {
530 return;
531 }
532 yield* projectionThreadRepository.upsert({
533 ...existingRow.value,
534 interactionMode: event.payload.interactionMode,
535 updatedAt: event.payload.updatedAt,
536 });
537 return;
538 }
539
540 case "thread.deleted": {
541 attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);
542 const existingRow = yield* projectionThreadRepository.getById({
543 threadId: event.payload.threadId,
544 });
545 if (Option.isNone(existingRow)) {
546 return;
547 }
548 yield* projectionThreadRepository.upsert({
549 ...existingRow.value,
550 deletedAt: event.payload.deletedAt,
551 updatedAt: event.payload.deletedAt,
552 });
553 return;
554 }
555
556 case "thread.message-sent":
557 case "thread.proposed-plan-upserted":
558 case "thread.activity-appended": {
559 const existingRow = yield* projectionThreadRepository.getById({
560 threadId: event.payload.threadId,
561 });
562 if (Option.isNone(existingRow)) {
563 return;
564 }
565 yield* projectionThreadRepository.upsert({
566 ...existingRow.value,
567 updatedAt: event.occurredAt,
568 });
569 return;
570 }
571
572 case "thread.session-set": {
573 const existingRow = yield* projectionThreadRepository.getById({
574 threadId: event.payload.threadId,
575 });
576 if (Option.isNone(existingRow)) {
577 return;
578 }
579 yield* projectionThreadRepository.upsert({
580 ...existingRow.value,
581 latestTurnId: event.payload.session.activeTurnId,
582 updatedAt: event.occurredAt,
583 });
584 return;
585 }
586
587 case "thread.turn-diff-completed": {
588 const existingRow = yield* projectionThreadRepository.getById({
589 threadId: event.payload.threadId,
590 });
591 if (Option.isNone(existingRow)) {
592 return;
593 }
594 yield* projectionThreadRepository.upsert({
595 ...existingRow.value,
596 latestTurnId: event.payload.turnId,
597 updatedAt: event.occurredAt,
598 });
599 return;
600 }
601
602 case "thread.reverted": {
603 const existingRow = yield* projectionThreadRepository.getById({
604 threadId: event.payload.threadId,
605 });
606 if (Option.isNone(existingRow)) {
607 return;
608 }
609 yield* projectionThreadRepository.upsert({
610 ...existingRow.value,
611 latestTurnId: null,
612 updatedAt: event.occurredAt,
613 });
614 return;
615 }
616
617 default:
618 return;
619 }
620 });
621
622 const applyThreadMessagesProjection: ProjectorDefinition["apply"] = Effect.fn(
623 "applyThreadMessagesProjection",
624 )(function* (event, attachmentSideEffects) {
625 switch (event.type) {
626 case "thread.message-sent": {
627 const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
628 threadId: event.payload.threadId,
629 });
630 const existingMessage = existingRows.find(
631 (row) => row.messageId === event.payload.messageId,
632 );
633 const nextText =
634 existingMessage && event.payload.streaming
635 ? `${existingMessage.text}${event.payload.text}`
636 : existingMessage && event.payload.text.length === 0
637 ? existingMessage.text
638 : event.payload.text;
639 const nextAttachments =
640 event.payload.attachments !== undefined
641 ? yield* materializeAttachmentsForProjection({
642 attachments: event.payload.attachments,
643 })
644 : existingMessage?.attachments;
645 yield* projectionThreadMessageRepository.upsert({
646 messageId: event.payload.messageId,
647 threadId: event.payload.threadId,
648 turnId: event.payload.turnId,
649 role: event.payload.role,
650 text: nextText,
651 ...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
652 isStreaming: event.payload.streaming,
653 createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
654 updatedAt: event.payload.updatedAt,
655 });
656 return;
657 }
658
659 case "thread.reverted": {
660 const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
661 threadId: event.payload.threadId,
662 });
663 if (existingRows.length === 0) {
664 return;
665 }
666
667 const existingTurns = yield* projectionTurnRepository.listByThreadId({
668 threadId: event.payload.threadId,
669 });
670 const keptRows = retainProjectionMessagesAfterRevert(
671 existingRows,
672 existingTurns,
673 event.payload.turnCount,
674 );
675 if (keptRows.length === existingRows.length) {
676 return;
677 }
678
679 yield* projectionThreadMessageRepository.deleteByThreadId({
680 threadId: event.payload.threadId,
681 });
682 yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {
683 concurrency: 1,
684 }).pipe(Effect.asVoid);
685 attachmentSideEffects.prunedThreadRelativePaths.set(
686 event.payload.threadId,
687 collectThreadAttachmentRelativePaths(event.payload.threadId, keptRows),
688 );
689 return;
690 }
691
692 default:
693 return;
694 }
695 });
696
697 const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = Effect.fn(
698 "applyThreadProposedPlansProjection",
699 )(function* (event, _attachmentSideEffects) {
700 switch (event.type) {
701 case "thread.proposed-plan-upserted":
702 yield* projectionThreadProposedPlanRepository.upsert({
703 planId: event.payload.proposedPlan.id,
704 threadId: event.payload.threadId,
705 turnId: event.payload.proposedPlan.turnId,
706 planMarkdown: event.payload.proposedPlan.planMarkdown,
707 implementedAt: event.payload.proposedPlan.implementedAt,
708 implementationThreadId: event.payload.proposedPlan.implementationThreadId,
709 createdAt: event.payload.proposedPlan.createdAt,
710 updatedAt: event.payload.proposedPlan.updatedAt,
711 });
712 return;
713
714 case "thread.reverted": {
715 const existingRows = yield* projectionThreadProposedPlanRepository.listByThreadId({
716 threadId: event.payload.threadId,
717 });
718 if (existingRows.length === 0) {
719 return;
720 }
721
722 const existingTurns = yield* projectionTurnRepository.listByThreadId({
723 threadId: event.payload.threadId,
724 });
725 const keptRows = retainProjectionProposedPlansAfterRevert(
726 existingRows,
727 existingTurns,
728 event.payload.turnCount,
729 );
730 if (keptRows.length === existingRows.length) {
731 return;
732 }
733
734 yield* projectionThreadProposedPlanRepository.deleteByThreadId({
735 threadId: event.payload.threadId,
736 });
737 yield* Effect.forEach(keptRows, projectionThreadProposedPlanRepository.upsert, {
738 concurrency: 1,
739 }).pipe(Effect.asVoid);
740 return;
741 }
742
743 default:
744 return;
745 }
746 });
747
748 const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = Effect.fn(
749 "applyThreadActivitiesProjection",
750 )(function* (event, _attachmentSideEffects) {
751 switch (event.type) {
752 case "thread.activity-appended":
753 yield* projectionThreadActivityRepository.upsert({
754 activityId: event.payload.activity.id,
755 threadId: event.payload.threadId,
756 turnId: event.payload.activity.turnId,
757 tone: event.payload.activity.tone,
758 kind: event.payload.activity.kind,
759 summary: event.payload.activity.summary,
760 payload: event.payload.activity.payload,
761 ...(event.payload.activity.sequence !== undefined
762 ? { sequence: event.payload.activity.sequence }
763 : {}),
764 createdAt: event.payload.activity.createdAt,
765 });
766 return;
767
768 case "thread.reverted": {
769 const existingRows = yield* projectionThreadActivityRepository.listByThreadId({
770 threadId: event.payload.threadId,
771 });
772 if (existingRows.length === 0) {
773 return;
774 }
775 const existingTurns = yield* projectionTurnRepository.listByThreadId({
776 threadId: event.payload.threadId,
777 });
778 const keptRows = retainProjectionActivitiesAfterRevert(
779 existingRows,
780 existingTurns,
781 event.payload.turnCount,
782 );
783 if (keptRows.length === existingRows.length) {
784 return;
785 }
786 yield* projectionThreadActivityRepository.deleteByThreadId({
787 threadId: event.payload.threadId,
788 });
789 yield* Effect.forEach(keptRows, projectionThreadActivityRepository.upsert, {
790 concurrency: 1,
791 }).pipe(Effect.asVoid);
792 return;
793 }
794
795 default:
796 return;
797 }
798 });
799
800 const applyThreadSessionsProjection: ProjectorDefinition["apply"] = Effect.fn(
801 "applyThreadSessionsProjection",
802 )(function* (event, _attachmentSideEffects) {
803 if (event.type !== "thread.session-set") {
804 return;
805 }
806 yield* projectionThreadSessionRepository.upsert({
807 threadId: event.payload.threadId,
808 status: event.payload.session.status,
809 providerName: event.payload.session.providerName,
810 runtimeMode: event.payload.session.runtimeMode,
811 activeTurnId: event.payload.session.activeTurnId,
812 lastError: event.payload.session.lastError,
813 updatedAt: event.payload.session.updatedAt,
814 });
815 });
816
817 const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn(
818 "applyThreadTurnsProjection",
819 )(function* (event, _attachmentSideEffects) {
820 switch (event.type) {
821 case "thread.turn-start-requested": {
822 yield* projectionTurnRepository.replacePendingTurnStart({
823 threadId: event.payload.threadId,
824 messageId: event.payload.messageId,
825 sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null,
826 sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null,
827 requestedAt: event.payload.createdAt,
828 });
829 return;
830 }
831
832 case "thread.session-set": {
833 const turnId = event.payload.session.activeTurnId;
834 if (turnId === null || event.payload.session.status !== "running") {
835 return;
836 }
837
838 const existingTurn = yield* projectionTurnRepository.getByTurnId({
839 threadId: event.payload.threadId,
840 turnId,
841 });
842 const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
843 threadId: event.payload.threadId,
844 });
845 if (Option.isSome(existingTurn)) {
846 const nextState =
847 existingTurn.value.state === "completed" || existingTurn.value.state === "error"
848 ? existingTurn.value.state
849 : "running";
850 yield* projectionTurnRepository.upsertByTurnId({
851 ...existingTurn.value,
852 state: nextState,
853 pendingMessageId:
854 existingTurn.value.pendingMessageId ??
855 (Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),
856 sourceProposedPlanThreadId:
857 existingTurn.value.sourceProposedPlanThreadId ??
858 (Option.isSome(pendingTurnStart)
859 ? pendingTurnStart.value.sourceProposedPlanThreadId
860 : null),
861 sourceProposedPlanId:
862 existingTurn.value.sourceProposedPlanId ??
863 (Option.isSome(pendingTurnStart)
864 ? pendingTurnStart.value.sourceProposedPlanId
865 : null),
866 startedAt:
867 existingTurn.value.startedAt ??
868 (Option.isSome(pendingTurnStart)
869 ? pendingTurnStart.value.requestedAt
870 : event.occurredAt),
871 requestedAt:
872 existingTurn.value.requestedAt ??
873 (Option.isSome(pendingTurnStart)
874 ? pendingTurnStart.value.requestedAt
875 : event.occurredAt),
876 });
877 } else {
878 yield* projectionTurnRepository.upsertByTurnId({
879 turnId,
880 threadId: event.payload.threadId,
881 pendingMessageId: Option.isSome(pendingTurnStart)
882 ? pendingTurnStart.value.messageId
883 : null,
884 sourceProposedPlanThreadId: Option.isSome(pendingTurnStart)
885 ? pendingTurnStart.value.sourceProposedPlanThreadId
886 : null,
887 sourceProposedPlanId: Option.isSome(pendingTurnStart)
888 ? pendingTurnStart.value.sourceProposedPlanId
889 : null,
890 assistantMessageId: null,
891 state: "running",
892 requestedAt: Option.isSome(pendingTurnStart)
893 ? pendingTurnStart.value.requestedAt
894 : event.occurredAt,
895 startedAt: Option.isSome(pendingTurnStart)
896 ? pendingTurnStart.value.requestedAt
897 : event.occurredAt,
898 completedAt: null,
899 checkpointTurnCount: null,
900 checkpointRef: null,
901 checkpointStatus: null,
902 checkpointFiles: [],
903 });
904 }
905
906 yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
907 threadId: event.payload.threadId,
908 });
909 return;
910 }
911
912 case "thread.message-sent": {
913 if (event.payload.turnId === null || event.payload.role !== "assistant") {
914 return;
915 }
916 const existingTurn = yield* projectionTurnRepository.getByTurnId({
917 threadId: event.payload.threadId,
918 turnId: event.payload.turnId,
919 });
920 if (Option.isSome(existingTurn)) {
921 yield* projectionTurnRepository.upsertByTurnId({
922 ...existingTurn.value,
923 assistantMessageId: event.payload.messageId,
924 state: event.payload.streaming
925 ? existingTurn.value.state
926 : existingTurn.value.state === "interrupted"
927 ? "interrupted"
928 : existingTurn.value.state === "error"
929 ? "error"
930 : "completed",
931 completedAt: event.payload.streaming
932 ? existingTurn.value.completedAt
933 : (existingTurn.value.completedAt ?? event.payload.updatedAt),
934 startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
935 requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
936 });
937 return;
938 }
939 yield* projectionTurnRepository.upsertByTurnId({
940 turnId: event.payload.turnId,
941 threadId: event.payload.threadId,
942 pendingMessageId: null,
943 sourceProposedPlanThreadId: null,
944 sourceProposedPlanId: null,
945 assistantMessageId: event.payload.messageId,
946 state: event.payload.streaming ? "running" : "completed",
947 requestedAt: event.payload.createdAt,
948 startedAt: event.payload.createdAt,
949 completedAt: event.payload.streaming ? null : event.payload.updatedAt,
950 checkpointTurnCount: null,
951 checkpointRef: null,
952 checkpointStatus: null,
953 checkpointFiles: [],
954 });
955 return;
956 }
957
958 case "thread.turn-interrupt-requested": {
959 if (event.payload.turnId === undefined) {
960 return;
961 }
962 const existingTurn = yield* projectionTurnRepository.getByTurnId({
963 threadId: event.payload.threadId,
964 turnId: event.payload.turnId,
965 });
966 if (Option.isSome(existingTurn)) {
967 yield* projectionTurnRepository.upsertByTurnId({
968 ...existingTurn.value,
969 state: "interrupted",
970 completedAt: existingTurn.value.completedAt ?? event.payload.createdAt,
971 startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
972 requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
973 });
974 return;
975 }
976 yield* projectionTurnRepository.upsertByTurnId({
977 turnId: event.payload.turnId,
978 threadId: event.payload.threadId,
979 pendingMessageId: null,
980 sourceProposedPlanThreadId: null,
981 sourceProposedPlanId: null,
982 assistantMessageId: null,
983 state: "interrupted",
984 requestedAt: event.payload.createdAt,
985 startedAt: event.payload.createdAt,
986 completedAt: event.payload.createdAt,
987 checkpointTurnCount: null,
988 checkpointRef: null,
989 checkpointStatus: null,
990 checkpointFiles: [],
991 });
992 return;
993 }
994
995 case "thread.turn-diff-completed": {
996 const existingTurn = yield* projectionTurnRepository.getByTurnId({
997 threadId: event.payload.threadId,
998 turnId: event.payload.turnId,
999 });
1000 const nextState = event.payload.status === "error" ? "error" : "completed";
1001 yield* projectionTurnRepository.clearCheckpointTurnConflict({
1002 threadId: event.payload.threadId,
1003 turnId: event.payload.turnId,
1004 checkpointTurnCount: event.payload.checkpointTurnCount,
1005 });
1006
1007 if (Option.isSome(existingTurn)) {
1008 yield* projectionTurnRepository.upsertByTurnId({
1009 ...existingTurn.value,
1010 assistantMessageId: event.payload.assistantMessageId,
1011 state: nextState,
1012 checkpointTurnCount: event.payload.checkpointTurnCount,
1013 checkpointRef: event.payload.checkpointRef,
1014 checkpointStatus: event.payload.status,
1015 checkpointFiles: event.payload.files,
1016 startedAt: existingTurn.value.startedAt ?? event.payload.completedAt,
1017 requestedAt: existingTurn.value.requestedAt ?? event.payload.completedAt,
1018 completedAt: event.payload.completedAt,
1019 });
1020 return;
1021 }
1022 yield* projectionTurnRepository.upsertByTurnId({
1023 turnId: event.payload.turnId,
1024 threadId: event.payload.threadId,
1025 pendingMessageId: null,
1026 sourceProposedPlanThreadId: null,
1027 sourceProposedPlanId: null,
1028 assistantMessageId: event.payload.assistantMessageId,
1029 state: nextState,
1030 requestedAt: event.payload.completedAt,
1031 startedAt: event.payload.completedAt,
1032 completedAt: event.payload.completedAt,
1033 checkpointTurnCount: event.payload.checkpointTurnCount,
1034 checkpointRef: event.payload.checkpointRef,
1035 checkpointStatus: event.payload.status,
1036 checkpointFiles: event.payload.files,
1037 });
1038 return;
1039 }
1040
1041 case "thread.reverted": {
1042 const existingTurns = yield* projectionTurnRepository.listByThreadId({
1043 threadId: event.payload.threadId,
1044 });
1045 const keptTurns = existingTurns.filter(
1046 (turn) =>
1047 turn.turnId !== null &&
1048 turn.checkpointTurnCount !== null &&
1049 turn.checkpointTurnCount <= event.payload.turnCount,
1050 );
1051 yield* projectionTurnRepository.deleteByThreadId({
1052 threadId: event.payload.threadId,
1053 });
1054 yield* Effect.forEach(
1055 keptTurns,
1056 (turn) =>
1057 turn.turnId === null
1058 ? Effect.void
1059 : projectionTurnRepository.upsertByTurnId({
1060 ...turn,
1061 turnId: turn.turnId,
1062 }),
1063 { concurrency: 1 },
1064 ).pipe(Effect.asVoid);
1065 return;
1066 }
1067
1068 default:
1069 return;
1070 }
1071 });
1072
1073 const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
1074
1075 const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = Effect.fn(
1076 "applyPendingApprovalsProjection",
1077 )(function* (event, _attachmentSideEffects) {
1078 switch (event.type) {
1079 case "thread.activity-appended": {
1080 const requestId =
1081 extractActivityRequestId(event.payload.activity.payload) ??
1082 event.metadata.requestId ??
1083 null;
1084 if (requestId === null) {
1085 return;
1086 }
1087 const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({
1088 requestId,
1089 });
1090 if (event.payload.activity.kind === "approval.resolved") {
1091 const resolvedDecisionRaw =
1092 typeof event.payload.activity.payload === "object" &&
1093 event.payload.activity.payload !== null &&
1094 "decision" in event.payload.activity.payload
1095 ? (event.payload.activity.payload as { decision?: unknown }).decision
1096 : null;
1097 const resolvedDecision =
1098 resolvedDecisionRaw === "accept" ||
1099 resolvedDecisionRaw === "acceptForSession" ||
1100 resolvedDecisionRaw === "decline" ||
1101 resolvedDecisionRaw === "cancel"
1102 ? resolvedDecisionRaw
1103 : null;
1104 yield* projectionPendingApprovalRepository.upsert({
1105 requestId,
1106 threadId: Option.isSome(existingRow)
1107 ? existingRow.value.threadId
1108 : event.payload.threadId,
1109 turnId: Option.isSome(existingRow)
1110 ? existingRow.value.turnId
1111 : event.payload.activity.turnId,
1112 status: "resolved",
1113 decision: resolvedDecision,
1114 createdAt: Option.isSome(existingRow)
1115 ? existingRow.value.createdAt
1116 : event.payload.activity.createdAt,
1117 resolvedAt: event.payload.activity.createdAt,
1118 });
1119 return;
1120 }
1121 if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
1122 return;
1123 }
1124 yield* projectionPendingApprovalRepository.upsert({
1125 requestId,
1126 threadId: event.payload.threadId,
1127 turnId: event.payload.activity.turnId,
1128 status: "pending",
1129 decision: null,
1130 createdAt: Option.isSome(existingRow)
1131 ? existingRow.value.createdAt
1132 : event.payload.activity.createdAt,
1133 resolvedAt: null,
1134 });
1135 return;
1136 }
1137
1138 case "thread.approval-response-requested": {
1139 const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({
1140 requestId: event.payload.requestId,
1141 });
1142 yield* projectionPendingApprovalRepository.upsert({
1143 requestId: event.payload.requestId,
1144 threadId: Option.isSome(existingRow)
1145 ? existingRow.value.threadId
1146 : event.payload.threadId,
1147 turnId: Option.isSome(existingRow) ? existingRow.value.turnId : null,
1148 status: "resolved",
1149 decision: event.payload.decision,
1150 createdAt: Option.isSome(existingRow)
1151 ? existingRow.value.createdAt
1152 : event.payload.createdAt,
1153 resolvedAt: event.payload.createdAt,
1154 });
1155 return;
1156 }
1157
1158 default:
1159 return;
1160 }
1161 });
1162
1163 const projectors: ReadonlyArray<ProjectorDefinition> = [
1164 {
1165 name: ORCHESTRATION_PROJECTOR_NAMES.projects,
1166 apply: applyProjectsProjection,
1167 },
1168 {
1169 name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
1170 apply: applyThreadMessagesProjection,
1171 },
1172 {
1173 name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
1174 apply: applyThreadProposedPlansProjection,
1175 },
1176 {
1177 name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
1178 apply: applyThreadActivitiesProjection,
1179 },
1180 {
1181 name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
1182 apply: applyThreadSessionsProjection,
1183 },
1184 {
1185 name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
1186 apply: applyThreadTurnsProjection,
1187 },
1188 {
1189 name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
1190 apply: applyCheckpointsProjection,
1191 },
1192 {
1193 name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,
1194 apply: applyPendingApprovalsProjection,
1195 },
1196 {
1197 name: ORCHESTRATION_PROJECTOR_NAMES.threads,
1198 apply: applyThreadsProjection,
1199 },
1200 ];
1201
1202 const runProjectorForEvent = Effect.fn("runProjectorForEvent")(function* (
1203 projector: ProjectorDefinition,
1204 event: OrchestrationEvent,
1205 ) {
1206 const attachmentSideEffects: AttachmentSideEffects = {
1207 deletedThreadIds: new Set<string>(),
1208 prunedThreadRelativePaths: new Map<string, Set<string>>(),
1209 };
1210
1211 yield* sql.withTransaction(
1212 projector.apply(event, attachmentSideEffects).pipe(
1213 Effect.flatMap(() =>
1214 projectionStateRepository.upsert({
1215 projector: projector.name,
1216 lastAppliedSequence: event.sequence,
1217 updatedAt: event.occurredAt,
1218 }),
1219 ),
1220 ),
1221 );
1222
1223 yield* runAttachmentSideEffects(attachmentSideEffects).pipe(
1224 Effect.catch((cause) =>
1225 Effect.logWarning("failed to apply projected attachment side-effects", {
1226 projector: projector.name,
1227 sequence: event.sequence,
1228 eventType: event.type,
1229 cause,
1230 }),
1231 ),
1232 );
1233 });
1234
1235 const bootstrapProjector = (projector: ProjectorDefinition) =>
1236 projectionStateRepository
1237 .getByProjector({
1238 projector: projector.name,
1239 })
1240 .pipe(
1241 Effect.flatMap((stateRow) =>
1242 Stream.runForEach(
1243 eventStore.readFromSequence(
1244 Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0,
1245 ),
1246 (event) => runProjectorForEvent(projector, event),
1247 ),
1248 ),
1249 );
1250
1251 const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>
1252 Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
1253 concurrency: 1,
1254 }).pipe(
1255 Effect.provideService(FileSystem.FileSystem, fileSystem),
1256 Effect.provideService(Path.Path, path),
1257 Effect.provideService(ServerConfig, serverConfig),
1258 Effect.asVoid,
1259 Effect.catchTag("SqlError", (sqlError) =>
1260 Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
1261 ),
1262 );
1263
1264 const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
1265 projectors,
1266 bootstrapProjector,
1267 { concurrency: 1 },
1268 ).pipe(
1269 Effect.provideService(FileSystem.FileSystem, fileSystem),
1270 Effect.provideService(Path.Path, path),
1271 Effect.provideService(ServerConfig, serverConfig),
1272 Effect.asVoid,
1273 Effect.tap(() =>
1274 Effect.log("orchestration projection pipeline bootstrapped").pipe(
1275 Effect.annotateLogs({ projectors: projectors.length }),
1276 ),
1277 ),
1278 Effect.catchTag("SqlError", (sqlError) =>
1279 Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)),
1280 ),
1281 );
1282
1283 return {
1284 bootstrap,
1285 projectEvent,
1286 } satisfies OrchestrationProjectionPipelineShape;
1287 },
1288);
1289
1290export const OrchestrationProjectionPipelineLive = Layer.effect(
1291 OrchestrationProjectionPipeline,
1292 makeOrchestrationProjectionPipeline(),
1293).pipe(
1294 Layer.provideMerge(NodeServices.layer),
1295 Layer.provideMerge(ProjectionProjectRepositoryLive),
1296 Layer.provideMerge(ProjectionThreadRepositoryLive),
1297 Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
1298 Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
1299 Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
1300 Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
1301 Layer.provideMerge(ProjectionTurnRepositoryLive),
1302 Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),
1303 Layer.provideMerge(ProjectionStateRepositoryLive),
1304);