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

ProjectionPipeline.ts

1,500 lines54.7 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​
743 const retainedTurns = yield* projectionTurnRepository.listByThreadId({
744 threadId: event.payload.threadId,
745 });
746 let latestTurnId: ProjectionTurn["turnId"] = null;
747 let latestCheckpointTurnCount = -1;
748 for (let index = 0; index < retainedTurns.length; index += 1) {
749 const turn = retainedTurns[index];
750 if (
751 !turn ||
752 turn.turnId === null ||
753 turn.checkpointTurnCount === null ||
754 turn.checkpointTurnCount > event.payload.turnCount
755 ) {
756 continue;
757 }
758 if (turn.checkpointTurnCount > latestCheckpointTurnCount) {
759 latestCheckpointTurnCount = turn.checkpointTurnCount;
760 latestTurnId = turn.turnId;
761 }
762 }
763​
764 yield* projectionThreadRepository.upsert({
765 ...existingRow.value,
766 latestTurnId,
767 updatedAt: event.occurredAt,
768 });
769 yield* refreshThreadShellSummary(event.payload.threadId);
770 return;
771 }
772​
773 default:
774 return;
775 }
776 });
777​
778 const applyThreadMessagesProjection: ProjectorDefinition["apply"] = Effect.fn(
779 "applyThreadMessagesProjection",
780 )(function* (event, attachmentSideEffects) {
781 switch (event.type) {
782 case "thread.message-sent": {
783 const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({
784 messageId: event.payload.messageId,
785 });
786 const previousMessage = Option.getOrUndefined(existingMessage);
787 const nextText = Option.match(existingMessage, {
788 onNone: () => event.payload.text,
789 onSome: (message) => {
790 if (event.payload.streaming) {
791 return `${message.text}${event.payload.text}`;
792 }
793 if (event.payload.text.length === 0) {
794 return message.text;
795 }
796 return event.payload.text;
797 },
798 });
799 const nextAttachments =
800 event.payload.attachments !== undefined
801 ? yield* materializeAttachmentsForProjection({
802 attachments: event.payload.attachments,
803 })
804 : previousMessage?.attachments;
805 yield* projectionThreadMessageRepository.upsert({
806 messageId: event.payload.messageId,
807 threadId: event.payload.threadId,
808 turnId: event.payload.turnId,
809 role: event.payload.role,
810 text: nextText,
811 ...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
812 isStreaming: event.payload.streaming,
813 createdAt: previousMessage?.createdAt ?? event.payload.createdAt,
814 updatedAt: event.payload.updatedAt,
815 });
816 return;
817 }
818​
819 case "thread.reverted": {
820 const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
821 threadId: event.payload.threadId,
822 });
823 if (existingRows.length === 0) {
824 return;
825 }
826​
827 const existingTurns = yield* projectionTurnRepository.listByThreadId({
828 threadId: event.payload.threadId,
829 });
830 const keptRows = retainProjectionMessagesAfterRevert(
831 existingRows,
832 existingTurns,
833 event.payload.turnCount,
834 );
835 if (keptRows.length === existingRows.length) {
836 return;
837 }
838​
839 yield* projectionThreadMessageRepository.deleteByThreadId({
840 threadId: event.payload.threadId,
841 });
842 yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {
843 concurrency: 1,
844 }).pipe(Effect.asVoid);
845 attachmentSideEffects.prunedThreadRelativePaths.set(
846 event.payload.threadId,
847 collectThreadAttachmentRelativePaths(event.payload.threadId, keptRows),
848 );
849 return;
850 }
851​
852 default:
853 return;
854 }
855 });
856​
857 const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = Effect.fn(
858 "applyThreadProposedPlansProjection",
859 )(function* (event, _attachmentSideEffects) {
860 switch (event.type) {
861 case "thread.proposed-plan-upserted":
862 yield* projectionThreadProposedPlanRepository.upsert({
863 planId: event.payload.proposedPlan.id,
864 threadId: event.payload.threadId,
865 turnId: event.payload.proposedPlan.turnId,
866 planMarkdown: event.payload.proposedPlan.planMarkdown,
867 implementedAt: event.payload.proposedPlan.implementedAt,
868 implementationThreadId: event.payload.proposedPlan.implementationThreadId,
869 createdAt: event.payload.proposedPlan.createdAt,
870 updatedAt: event.payload.proposedPlan.updatedAt,
871 });
872 return;
873​
874 case "thread.reverted": {
875 const existingRows = yield* projectionThreadProposedPlanRepository.listByThreadId({
876 threadId: event.payload.threadId,
877 });
878 if (existingRows.length === 0) {
879 return;
880 }
881​
882 const existingTurns = yield* projectionTurnRepository.listByThreadId({
883 threadId: event.payload.threadId,
884 });
885 const keptRows = retainProjectionProposedPlansAfterRevert(
886 existingRows,
887 existingTurns,
888 event.payload.turnCount,
889 );
890 if (keptRows.length === existingRows.length) {
891 return;
892 }
893​
894 yield* projectionThreadProposedPlanRepository.deleteByThreadId({
895 threadId: event.payload.threadId,
896 });
897 yield* Effect.forEach(keptRows, projectionThreadProposedPlanRepository.upsert, {
898 concurrency: 1,
899 }).pipe(Effect.asVoid);
900 return;
901 }
902​
903 default:
904 return;
905 }
906 });
907​
908 const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = Effect.fn(
909 "applyThreadActivitiesProjection",
910 )(function* (event, _attachmentSideEffects) {
911 switch (event.type) {
912 case "thread.activity-appended":
913 yield* projectionThreadActivityRepository.upsert({
914 activityId: event.payload.activity.id,
915 threadId: event.payload.threadId,
916 turnId: event.payload.activity.turnId,
917 tone: event.payload.activity.tone,
918 kind: event.payload.activity.kind,
919 summary: event.payload.activity.summary,
920 payload: event.payload.activity.payload,
921 ...(event.payload.activity.sequence !== undefined
922 ? { sequence: event.payload.activity.sequence }
923 : {}),
924 createdAt: event.payload.activity.createdAt,
925 });
926 return;
927​
928 case "thread.reverted": {
929 const existingRows = yield* projectionThreadActivityRepository.listByThreadId({
930 threadId: event.payload.threadId,
931 });
932 if (existingRows.length === 0) {
933 return;
934 }
935 const existingTurns = yield* projectionTurnRepository.listByThreadId({
936 threadId: event.payload.threadId,
937 });
938 const keptRows = retainProjectionActivitiesAfterRevert(
939 existingRows,
940 existingTurns,
941 event.payload.turnCount,
942 );
943 if (keptRows.length === existingRows.length) {
944 return;
945 }
946 yield* projectionThreadActivityRepository.deleteByThreadId({
947 threadId: event.payload.threadId,
948 });
949 yield* Effect.forEach(keptRows, projectionThreadActivityRepository.upsert, {
950 concurrency: 1,
951 }).pipe(Effect.asVoid);
952 return;
953 }
954​
955 default:
956 return;
957 }
958 });
959​
960 const applyThreadSessionsProjection: ProjectorDefinition["apply"] = Effect.fn(
961 "applyThreadSessionsProjection",
962 )(function* (event, _attachmentSideEffects) {
963 if (event.type !== "thread.session-set") {
964 return;
965 }
966 yield* projectionThreadSessionRepository.upsert({
967 threadId: event.payload.threadId,
968 status: event.payload.session.status,
969 providerName: event.payload.session.providerName,
970 providerInstanceId: event.payload.session.providerInstanceId ?? null,
971 runtimeMode: event.payload.session.runtimeMode,
972 activeTurnId: event.payload.session.activeTurnId,
973 lastError: event.payload.session.lastError,
974 updatedAt: event.payload.session.updatedAt,
975 });
976 });
977​
978 const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn(
979 "applyThreadTurnsProjection",
980 )(function* (event, _attachmentSideEffects) {
981 switch (event.type) {
982 case "thread.turn-start-requested": {
983 yield* projectionTurnRepository.replacePendingTurnStart({
984 threadId: event.payload.threadId,
985 messageId: event.payload.messageId,
986 sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null,
987 sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null,
988 requestedAt: event.payload.createdAt,
989 });
990 return;
991 }
992​
993 case "thread.session-set": {
994 const turnId = event.payload.session.activeTurnId;
995 if (turnId === null || event.payload.session.status !== "running") {
996 return;
997 }
998​
999 const existingTurn = yield* projectionTurnRepository.getByTurnId({
1000 threadId: event.payload.threadId,
1001 turnId,
1002 });
1003 const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
1004 threadId: event.payload.threadId,
1005 });
1006 if (Option.isSome(existingTurn)) {
1007 const nextState =
1008 existingTurn.value.state === "completed" || existingTurn.value.state === "error"
1009 ? existingTurn.value.state
1010 : "running";
1011 yield* projectionTurnRepository.upsertByTurnId({
1012 ...existingTurn.value,
1013 state: nextState,
1014 pendingMessageId:
1015 existingTurn.value.pendingMessageId ??
1016 (Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),
1017 sourceProposedPlanThreadId:
1018 existingTurn.value.sourceProposedPlanThreadId ??
1019 (Option.isSome(pendingTurnStart)
1020 ? pendingTurnStart.value.sourceProposedPlanThreadId
1021 : null),
1022 sourceProposedPlanId:
1023 existingTurn.value.sourceProposedPlanId ??
1024 (Option.isSome(pendingTurnStart)
1025 ? pendingTurnStart.value.sourceProposedPlanId
1026 : null),
1027 startedAt:
1028 existingTurn.value.startedAt ??
1029 (Option.isSome(pendingTurnStart)
1030 ? pendingTurnStart.value.requestedAt
1031 : event.occurredAt),
1032 requestedAt:
1033 existingTurn.value.requestedAt ??
1034 (Option.isSome(pendingTurnStart)
1035 ? pendingTurnStart.value.requestedAt
1036 : event.occurredAt),
1037 });
1038 } else {
1039 yield* projectionTurnRepository.upsertByTurnId({
1040 turnId,
1041 threadId: event.payload.threadId,
1042 pendingMessageId: Option.isSome(pendingTurnStart)
1043 ? pendingTurnStart.value.messageId
1044 : null,
1045 sourceProposedPlanThreadId: Option.isSome(pendingTurnStart)
1046 ? pendingTurnStart.value.sourceProposedPlanThreadId
1047 : null,
1048 sourceProposedPlanId: Option.isSome(pendingTurnStart)
1049 ? pendingTurnStart.value.sourceProposedPlanId
1050 : null,
1051 assistantMessageId: null,
1052 state: "running",
1053 requestedAt: Option.isSome(pendingTurnStart)
1054 ? pendingTurnStart.value.requestedAt
1055 : event.occurredAt,
1056 startedAt: Option.isSome(pendingTurnStart)
1057 ? pendingTurnStart.value.requestedAt
1058 : event.occurredAt,
1059 completedAt: null,
1060 checkpointTurnCount: null,
1061 checkpointRef: null,
1062 checkpointStatus: null,
1063 checkpointFiles: [],
1064 });
1066​
1067 yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
1068 threadId: event.payload.threadId,
1069 });
1070 return;
1072​
1073 case "thread.message-sent": {
1074 if (event.payload.turnId === null || event.payload.role !== "assistant") {
1075 return;
1077 const existingTurn = yield* projectionTurnRepository.getByTurnId({
1078 threadId: event.payload.threadId,
1079 turnId: event.payload.turnId,
1080 });
1081 if (Option.isSome(existingTurn)) {
1082 yield* projectionTurnRepository.upsertByTurnId({
1083 ...existingTurn.value,
1084 assistantMessageId: event.payload.messageId,
1085 state: event.payload.streaming
1086 ? existingTurn.value.state
1087 : existingTurn.value.state === "interrupted"
1088 ? "interrupted"
1089 : existingTurn.value.state === "error"
1090 ? "error"
1091 : "completed",
1092 completedAt: event.payload.streaming
1093 ? existingTurn.value.completedAt
1094 : (existingTurn.value.completedAt ?? event.payload.updatedAt),
1095 startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
1096 requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
1097 });
1098 return;
1100 yield* projectionTurnRepository.upsertByTurnId({
1101 turnId: event.payload.turnId,
1102 threadId: event.payload.threadId,
1103 pendingMessageId: null,
1104 sourceProposedPlanThreadId: null,
1105 sourceProposedPlanId: null,
1106 assistantMessageId: event.payload.messageId,
1107 state: event.payload.streaming ? "running" : "completed",
1108 requestedAt: event.payload.createdAt,
1109 startedAt: event.payload.createdAt,
1110 completedAt: event.payload.streaming ? null : event.payload.updatedAt,
1111 checkpointTurnCount: null,
1112 checkpointRef: null,
1113 checkpointStatus: null,
1114 checkpointFiles: [],
1115 });
1116 return;
1118​
1119 case "thread.turn-interrupt-requested": {
1120 if (event.payload.turnId === undefined) {
1121 return;
1123 const existingTurn = yield* projectionTurnRepository.getByTurnId({
1124 threadId: event.payload.threadId,
1125 turnId: event.payload.turnId,
1126 });
1127 if (Option.isSome(existingTurn)) {
1128 yield* projectionTurnRepository.upsertByTurnId({
1129 ...existingTurn.value,
1130 state: "interrupted",
1131 completedAt: existingTurn.value.completedAt ?? event.payload.createdAt,
1132 startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
1133 requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
1134 });
1135 return;
1137 yield* projectionTurnRepository.upsertByTurnId({
1138 turnId: event.payload.turnId,
1139 threadId: event.payload.threadId,
1140 pendingMessageId: null,
1141 sourceProposedPlanThreadId: null,
1142 sourceProposedPlanId: null,
1143 assistantMessageId: null,
1144 state: "interrupted",
1145 requestedAt: event.payload.createdAt,
1146 startedAt: event.payload.createdAt,
1147 completedAt: event.payload.createdAt,
1148 checkpointTurnCount: null,
1149 checkpointRef: null,
1150 checkpointStatus: null,
1151 checkpointFiles: [],
1152 });
1153 return;
1155​
1156 case "thread.turn-diff-completed": {
1157 const existingTurn = yield* projectionTurnRepository.getByTurnId({
1158 threadId: event.payload.threadId,
1159 turnId: event.payload.turnId,
1160 });
1161 const nextState = event.payload.status === "error" ? "error" : "completed";
1162 yield* projectionTurnRepository.clearCheckpointTurnConflict({
1163 threadId: event.payload.threadId,
1164 turnId: event.payload.turnId,
1165 checkpointTurnCount: event.payload.checkpointTurnCount,
1166 });
1167​
1168 if (Option.isSome(existingTurn)) {
1169 yield* projectionTurnRepository.upsertByTurnId({
1170 ...existingTurn.value,
1171 assistantMessageId: event.payload.assistantMessageId,
1172 state: nextState,
1173 checkpointTurnCount: event.payload.checkpointTurnCount,
1174 checkpointRef: event.payload.checkpointRef,
1175 checkpointStatus: event.payload.status,
1176 checkpointFiles: event.payload.files,
1177 startedAt: existingTurn.value.startedAt ?? event.payload.completedAt,
1178 requestedAt: existingTurn.value.requestedAt ?? event.payload.completedAt,
1179 completedAt: event.payload.completedAt,
1180 });
1181 return;
1183 yield* projectionTurnRepository.upsertByTurnId({
1184 turnId: event.payload.turnId,
1185 threadId: event.payload.threadId,
1186 pendingMessageId: null,
1187 sourceProposedPlanThreadId: null,
1188 sourceProposedPlanId: null,
1189 assistantMessageId: event.payload.assistantMessageId,
1190 state: nextState,
1191 requestedAt: event.payload.completedAt,
1192 startedAt: event.payload.completedAt,
1193 completedAt: event.payload.completedAt,
1194 checkpointTurnCount: event.payload.checkpointTurnCount,
1195 checkpointRef: event.payload.checkpointRef,
1196 checkpointStatus: event.payload.status,
1197 checkpointFiles: event.payload.files,
1198 });
1199 return;
1201​
1202 case "thread.reverted": {
1203 const existingTurns = yield* projectionTurnRepository.listByThreadId({
1204 threadId: event.payload.threadId,
1205 });
1206 const keptTurns = existingTurns.filter(
1207 (turn) =>
1208 turn.turnId !== null &&
1209 turn.checkpointTurnCount !== null &&
1210 turn.checkpointTurnCount <= event.payload.turnCount,
1211 );
1212 yield* projectionTurnRepository.deleteByThreadId({
1213 threadId: event.payload.threadId,
1214 });
1215 yield* Effect.forEach(
1216 keptTurns,
1217 (turn) =>
1218 turn.turnId === null
1219 ? Effect.void
1220 : projectionTurnRepository.upsertByTurnId({
1221 ...turn,
1222 turnId: turn.turnId,
1223 }),
1224 { concurrency: 1 },
1225 ).pipe(Effect.asVoid);
1226 return;
1228​
1229 default:
1230 return;
1232 });
1233​
1234 const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void;
1235​
1236 const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = Effect.fn(
1237 "applyPendingApprovalsProjection",
1238 )(function* (event, _attachmentSideEffects) {
1239 switch (event.type) {
1240 case "thread.activity-appended": {
1241 const requestId =
1242 extractActivityRequestId(event.payload.activity.payload) ??
1243 event.metadata.requestId ??
1244 null;
1245 if (requestId === null) {
1246 return;
1248 const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({
1249 requestId,
1250 });
1251 if (event.payload.activity.kind === "approval.resolved") {
1252 const resolvedDecisionRaw =
1253 typeof event.payload.activity.payload === "object" &&
1254 event.payload.activity.payload !== null &&
1255 "decision" in event.payload.activity.payload
1256 ? (event.payload.activity.payload as { decision?: unknown }).decision
1257 : null;
1258 const resolvedDecision =
1259 resolvedDecisionRaw === "accept" ||
1260 resolvedDecisionRaw === "acceptForSession" ||
1261 resolvedDecisionRaw === "decline" ||
1262 resolvedDecisionRaw === "cancel"
1263 ? resolvedDecisionRaw
1264 : null;
1265 yield* projectionPendingApprovalRepository.upsert({
1266 requestId,
1267 threadId: Option.isSome(existingRow)
1268 ? existingRow.value.threadId
1269 : event.payload.threadId,
1270 turnId: Option.isSome(existingRow)
1271 ? existingRow.value.turnId
1272 : event.payload.activity.turnId,
1273 status: "resolved",
1274 decision: resolvedDecision,
1275 createdAt: Option.isSome(existingRow)
1276 ? existingRow.value.createdAt
1277 : event.payload.activity.createdAt,
1278 resolvedAt: event.payload.activity.createdAt,
1279 });
1280 return;
1282 if (event.payload.activity.kind === "provider.approval.respond.failed") {
1283 const payload =
1284 typeof event.payload.activity.payload === "object" &&
1285 event.payload.activity.payload !== null
1286 ? (event.payload.activity.payload as Record<string, unknown>)
1287 : null;
1288 const detail =
1289 typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
1290 if (isStalePendingApprovalFailureDetail(detail)) {
1291 if (Option.isNone(existingRow)) {
1292 return;
1294 if (existingRow.value.status === "resolved") {
1295 return;
1297 yield* projectionPendingApprovalRepository.upsert({
1298 requestId,
1299 threadId: existingRow.value.threadId,
1300 turnId: existingRow.value.turnId,
1301 status: "resolved",
1302 decision: null,
1303 createdAt: existingRow.value.createdAt,
1304 resolvedAt: event.payload.activity.createdAt,
1305 });
1306 return;
1308 return;
1310 // Only approval-requested activities should create pending-approval
1311 // rows. Other activity kinds that happen to carry a requestId
1312 // (e.g. user-input.requested / user-input.resolved) must not
1313 // pollute this projection — they have their own accounting via
1314 // derivePendingUserInputCountFromActivities.
1315 if (event.payload.activity.kind !== "approval.requested") {
1316 return;
1318 if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
1319 return;
1321 yield* projectionPendingApprovalRepository.upsert({
1322 requestId,
1323 threadId: event.payload.threadId,
1324 turnId: event.payload.activity.turnId,
1325 status: "pending",
1326 decision: null,
1327 createdAt: Option.isSome(existingRow)
1328 ? existingRow.value.createdAt
1329 : event.payload.activity.createdAt,
1330 resolvedAt: null,
1331 });
1332 return;
1334​
1335 case "thread.approval-response-requested": {
1336 const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({
1337 requestId: event.payload.requestId,
1338 });
1339 yield* projectionPendingApprovalRepository.upsert({
1340 requestId: event.payload.requestId,
1341 threadId: Option.isSome(existingRow)
1342 ? existingRow.value.threadId
1343 : event.payload.threadId,
1344 turnId: Option.isSome(existingRow) ? existingRow.value.turnId : null,
1345 status: "resolved",
1346 decision: event.payload.decision,
1347 createdAt: Option.isSome(existingRow)
1348 ? existingRow.value.createdAt
1349 : event.payload.createdAt,
1350 resolvedAt: event.payload.createdAt,
1351 });
1352 return;
1354​
1355 default:
1356 return;
1358 });
1359​
1360 const projectors: ReadonlyArray<ProjectorDefinition> = [
1362 name: ORCHESTRATION_PROJECTOR_NAMES.projects,
1363 apply: applyProjectsProjection,
1364 },
1366 name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
1367 apply: applyThreadMessagesProjection,
1368 },
1370 name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
1371 apply: applyThreadProposedPlansProjection,
1372 },
1374 name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
1375 apply: applyThreadActivitiesProjection,
1376 },
1378 name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
1379 apply: applyThreadSessionsProjection,
1380 },
1382 name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
1383 apply: applyThreadTurnsProjection,
1384 },
1386 name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
1387 apply: applyCheckpointsProjection,
1388 },
1390 name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,
1391 apply: applyPendingApprovalsProjection,
1392 },
1394 name: ORCHESTRATION_PROJECTOR_NAMES.threads,
1395 apply: applyThreadsProjection,
1396 },
1397 ];
1398​
1399 const runProjectorForEvent = Effect.fn("runProjectorForEvent")(function* (
1400 projector: ProjectorDefinition,
1401 event: OrchestrationEvent,
1402 ) {
1403 const attachmentSideEffects: AttachmentSideEffects = {
1404 deletedThreadIds: new Set<string>(),
1405 prunedThreadRelativePaths: new Map<string, Set<string>>(),
1406 };
1407​
1408 yield* sql.withTransaction(
1409 projector.apply(event, attachmentSideEffects).pipe(
1410 Effect.flatMap(() =>
1411 projectionStateRepository.upsert({
1412 projector: projector.name,
1413 lastAppliedSequence: event.sequence,
1414 updatedAt: event.occurredAt,
1415 }),
1416 ),
1417 ),
1418 );
1419​
1420 yield* runAttachmentSideEffects(attachmentSideEffects).pipe(
1421 Effect.catch((cause) =>
1422 Effect.logWarning("failed to apply projected attachment side-effects", {
1423 projector: projector.name,
1424 sequence: event.sequence,
1425 eventType: event.type,
1426 cause,
1427 }),
1428 ),
1429 );
1430 });
1431​
1432 const bootstrapProjector = (projector: ProjectorDefinition) =>
1433 projectionStateRepository
1434 .getByProjector({
1435 projector: projector.name,
1436 })
1437 .pipe(
1438 Effect.flatMap((stateRow) =>
1439 Stream.runForEach(
1440 eventStore.readFromSequence(
1441 Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0,
1442 ),
1443 (event) => runProjectorForEvent(projector, event),
1444 ),
1445 ),
1446 );
1447​
1448 const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) =>
1449 Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {
1450 concurrency: 1,
1451 }).pipe(
1452 Effect.provideService(FileSystem.FileSystem, fileSystem),
1453 Effect.provideService(Path.Path, path),
1454 Effect.provideService(ServerConfig, serverConfig),
1455 Effect.asVoid,
1456 Effect.catchTag("SqlError", (sqlError) =>
1457 Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)),
1458 ),
1459 );
1460​
1461 const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach(
1462 projectors,
1463 bootstrapProjector,
1464 { concurrency: 1 },
1465 ).pipe(
1466 Effect.provideService(FileSystem.FileSystem, fileSystem),
1467 Effect.provideService(Path.Path, path),
1468 Effect.provideService(ServerConfig, serverConfig),
1469 Effect.asVoid,
1470 Effect.tap(() =>
1471 Effect.logDebug("orchestration projection pipeline bootstrapped").pipe(
1472 Effect.annotateLogs({ projectors: projectors.length }),
1473 ),
1474 ),
1475 Effect.catchTag("SqlError", (sqlError) =>
1476 Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)),
1477 ),
1478 );
1479​
1480 return {
1481 bootstrap,
1482 projectEvent,
1483 } satisfies OrchestrationProjectionPipelineShape;
1484 },
1486​
1487export const OrchestrationProjectionPipelineLive = Layer.effect(
1488 OrchestrationProjectionPipeline,
1489 makeOrchestrationProjectionPipeline(),
1490).pipe(
1491 Layer.provideMerge(ProjectionProjectRepositoryLive),
1492 Layer.provideMerge(ProjectionThreadRepositoryLive),
1493 Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
1494 Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
1495 Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
1496 Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
1497 Layer.provideMerge(ProjectionTurnRepositoryLive),
1498 Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),
1499 Layer.provideMerge(ProjectionStateRepositoryLive),