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