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