Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectionPipeline.ts

1,477 lines53.8 KB

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