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

CheckpointReactor.ts

803 lines26.2 KB

1import {
2 CommandId,
3 EventId,
4 MessageId,
5 type ProjectId,
6 ThreadId,
7 TurnId,
8 type OrchestrationEvent,
9 type ProviderRuntimeEvent,
10} from "@t3tools/contracts";
11import { Cause, Effect, Layer, Option, Stream } from "effect";
12import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
13​
14import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts";
15import {
16 checkpointRefForThreadTurn,
17 resolveThreadWorkspaceCwd,
18} from "../../checkpointing/Utils.ts";
19import { clearWorkspaceIndexCache } from "../../workspaceEntries.ts";
20import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
21import { ProviderService } from "../../provider/Services/ProviderService.ts";
22import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
23import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
24import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
25import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
26import { OrchestrationDispatchError } from "../Errors.ts";
27import { isGitRepository } from "../../git/isRepo.ts";
28​
29type ReactorInput =
30 | {
31 readonly source: "runtime";
32 readonly event: ProviderRuntimeEvent;
33 }
34 | {
35 readonly source: "domain";
36 readonly event: OrchestrationEvent;
37 };
38​
39function toTurnId(value: string | undefined): TurnId | null {
40 return value === undefined ? null : TurnId.makeUnsafe(String(value));
42​
43function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
44 if (left === null || left === undefined || right === null || right === undefined) {
45 return false;
46 }
47 return left === right;
49​
50function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
51 switch (status) {
52 case "failed":
53 return "error";
54 case "cancelled":
55 case "interrupted":
56 return "missing";
57 case "completed":
58 default:
59 return "ready";
60 }
62​
63const serverCommandId = (tag: string): CommandId =>
64 CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
65​
66const make = Effect.gen(function* () {
67 const orchestrationEngine = yield* OrchestrationEngineService;
68 const providerService = yield* ProviderService;
69 const checkpointStore = yield* CheckpointStore;
70 const receiptBus = yield* RuntimeReceiptBus;
71​
72 const appendRevertFailureActivity = (input: {
73 readonly threadId: ThreadId;
74 readonly turnCount: number;
75 readonly detail: string;
76 readonly createdAt: string;
77 }) =>
78 orchestrationEngine.dispatch({
79 type: "thread.activity.append",
80 commandId: serverCommandId("checkpoint-revert-failure"),
81 threadId: input.threadId,
82 activity: {
83 id: EventId.makeUnsafe(crypto.randomUUID()),
84 tone: "error",
85 kind: "checkpoint.revert.failed",
86 summary: "Checkpoint revert failed",
87 payload: {
88 turnCount: input.turnCount,
89 detail: input.detail,
90 },
91 turnId: null,
92 workUnitId: null,
93 createdAt: input.createdAt,
94 },
95 createdAt: input.createdAt,
96 });
97​
98 const appendCaptureFailureActivity = (input: {
99 readonly threadId: ThreadId;
100 readonly turnId: TurnId | null;
101 readonly detail: string;
102 readonly createdAt: string;
103 }) =>
104 orchestrationEngine.dispatch({
105 type: "thread.activity.append",
106 commandId: serverCommandId("checkpoint-capture-failure"),
107 threadId: input.threadId,
108 activity: {
109 id: EventId.makeUnsafe(crypto.randomUUID()),
110 tone: "error",
111 kind: "checkpoint.capture.failed",
112 summary: "Checkpoint capture failed",
113 payload: {
114 detail: input.detail,
115 },
116 turnId: input.turnId,
117 workUnitId: null,
118 createdAt: input.createdAt,
119 },
120 createdAt: input.createdAt,
121 });
122​
123 const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
124 threadId: ThreadId,
125 ): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
126 const readModel = yield* orchestrationEngine.getReadModel();
127 const thread = readModel.threads.find((entry) => entry.id === threadId);
128​
129 const sessions = yield* providerService.listSessions();
130​
131 const findSessionWithCwd = (
132 session: (typeof sessions)[number] | undefined,
133 ): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => {
134 if (!session?.cwd) {
135 return Option.none();
136 }
137 return Option.some({ threadId: session.threadId, cwd: session.cwd });
138 };
139​
140 if (thread) {
141 const projectedSession = sessions.find((session) => session.threadId === thread.id);
142 const fromProjected = findSessionWithCwd(projectedSession);
143 if (Option.isSome(fromProjected)) {
144 return fromProjected;
145 }
146 }
147​
148 return Option.none();
149 });
150​
151 const isGitWorkspace = (cwd: string) => isGitRepository(cwd);
152​
153 // Resolves the workspace CWD for checkpoint operations, preferring the
154 // active provider session CWD and falling back to the thread/project config.
155 // Returns undefined when no CWD can be determined or the workspace is not
156 // a git repository.
157 const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {
158 readonly threadId: ThreadId;
159 readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
160 readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
161 readonly preferSessionRuntime: boolean;
162 }): Effect.fn.Return<string | undefined> {
163 const fromSession = yield* resolveSessionRuntimeForThread(input.threadId);
164 const fromThread = resolveThreadWorkspaceCwd({
165 thread: input.thread,
166 projects: input.projects,
167 });
168​
169 const cwd = input.preferSessionRuntime
170 ? (Option.match(fromSession, {
171 onNone: () => undefined,
172 onSome: (runtime) => runtime.cwd,
173 }) ?? fromThread)
174 : (fromThread ??
175 Option.match(fromSession, {
176 onNone: () => undefined,
177 onSome: (runtime) => runtime.cwd,
178 }));
179​
180 if (!cwd) {
181 return undefined;
182 }
183 if (!isGitWorkspace(cwd)) {
184 return undefined;
185 }
186 return cwd;
187 });
188​
189 // Shared tail for both capture paths: creates the git checkpoint ref, diffs
190 // it against the previous turn, then dispatches the domain events to update
191 // the orchestration read model.
192 const captureAndDispatchCheckpoint = Effect.fnUntraced(function* (input: {
193 readonly threadId: ThreadId;
194 readonly turnId: TurnId;
195 readonly thread: {
196 readonly messages: ReadonlyArray<{
197 readonly id: MessageId;
198 readonly role: string;
199 readonly turnId: TurnId | null;
200 }>;
201 };
202 readonly cwd: string;
203 readonly turnCount: number;
204 readonly status: "ready" | "missing" | "error";
205 readonly assistantMessageId: MessageId | undefined;
206 readonly createdAt: string;
207 }) {
208 const fromTurnCount = Math.max(0, input.turnCount - 1);
209 const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, fromTurnCount);
210 const targetCheckpointRef = checkpointRefForThreadTurn(input.threadId, input.turnCount);
211​
212 const fromCheckpointExists = yield* checkpointStore.hasCheckpointRef({
213 cwd: input.cwd,
214 checkpointRef: fromCheckpointRef,
215 });
216 if (!fromCheckpointExists) {
217 yield* Effect.logWarning("checkpoint capture missing pre-turn baseline", {
218 threadId: input.threadId,
219 turnId: input.turnId,
220 fromTurnCount,
221 });
222 }
223​
224 yield* checkpointStore.captureCheckpoint({
225 cwd: input.cwd,
226 checkpointRef: targetCheckpointRef,
227 });
228​
229 // Invalidate the workspace entry cache so the @-mention file picker
230 // reflects files created or deleted during this turn.
231 clearWorkspaceIndexCache(input.cwd);
232​
233 const files = yield* checkpointStore
234 .diffCheckpoints({
235 cwd: input.cwd,
236 fromCheckpointRef,
237 toCheckpointRef: targetCheckpointRef,
238 fallbackFromToHead: false,
239 })
240 .pipe(
241 Effect.map((diff) =>
242 parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
243 path: file.path,
244 kind: "modified" as const,
245 additions: file.additions,
246 deletions: file.deletions,
247 })),
248 ),
249 Effect.tapError((error) =>
250 appendCaptureFailureActivity({
251 threadId: input.threadId,
252 turnId: input.turnId,
253 detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
254 createdAt: input.createdAt,
255 }),
256 ),
257 Effect.catch((error) =>
258 Effect.logWarning("failed to derive checkpoint file summary", {
259 threadId: input.threadId,
260 turnId: input.turnId,
261 turnCount: input.turnCount,
262 detail: error.message,
263 }).pipe(Effect.as([])),
264 ),
265 );
266​
267 const assistantMessageId =
268 input.assistantMessageId ??
269 input.thread.messages
270 .toReversed()
271 .find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ??
272 MessageId.makeUnsafe(`assistant:${input.turnId}`);
273​
274 yield* orchestrationEngine.dispatch({
275 type: "thread.turn.diff.complete",
276 commandId: serverCommandId("checkpoint-turn-diff-complete"),
277 threadId: input.threadId,
278 turnId: input.turnId,
279 completedAt: input.createdAt,
280 checkpointRef: targetCheckpointRef,
281 status: input.status,
282 files,
283 assistantMessageId,
284 checkpointTurnCount: input.turnCount,
285 createdAt: input.createdAt,
286 });
287 yield* receiptBus.publish({
288 type: "checkpoint.diff.finalized",
289 threadId: input.threadId,
290 turnId: input.turnId,
291 checkpointTurnCount: input.turnCount,
292 checkpointRef: targetCheckpointRef,
293 status: input.status,
294 createdAt: input.createdAt,
295 });
296 yield* receiptBus.publish({
297 type: "turn.processing.quiesced",
298 threadId: input.threadId,
299 turnId: input.turnId,
300 checkpointTurnCount: input.turnCount,
301 createdAt: input.createdAt,
302 });
303​
304 yield* orchestrationEngine.dispatch({
305 type: "thread.activity.append",
306 commandId: serverCommandId("checkpoint-captured-activity"),
307 threadId: input.threadId,
308 activity: {
309 id: EventId.makeUnsafe(crypto.randomUUID()),
310 tone: "info",
311 kind: "checkpoint.captured",
312 summary: "Checkpoint captured",
313 payload: {
314 turnCount: input.turnCount,
315 status: input.status,
316 },
317 turnId: input.turnId,
318 workUnitId: null,
319 createdAt: input.createdAt,
320 },
321 createdAt: input.createdAt,
322 });
323 });
324​
325 // Captures a real git checkpoint when a turn completes via a runtime event.
326 const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
327 event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
328 ) {
329 const turnId = toTurnId(event.turnId);
330 if (!turnId) {
331 return;
332 }
333​
334 const readModel = yield* orchestrationEngine.getReadModel();
335 const thread = readModel.threads.find((entry) => entry.id === event.threadId);
336 if (!thread) {
337 return;
338 }
339​
340 // When a primary turn is active, only that turn may produce completion checkpoints.
341 if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
342 return;
343 }
344​
345 // Only skip if a real (non-placeholder) checkpoint already exists for this turn.
346 // ProviderRuntimeIngestion may insert placeholder entries with status "missing"
347 // before this reactor runs; those must not prevent real git capture.
348 if (
349 thread.checkpoints.some(
350 (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
351 )
352 ) {
353 return;
354 }
355​
356 const checkpointCwd = yield* resolveCheckpointCwd({
357 threadId: thread.id,
358 thread,
359 projects: readModel.projects,
360 preferSessionRuntime: true,
361 });
362 if (!checkpointCwd) {
363 return;
364 }
365​
366 // If a placeholder checkpoint exists for this turn, reuse its turn count
367 // instead of incrementing past it.
368 const existingPlaceholder = thread.checkpoints.find(
369 (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
370 );
371 const currentTurnCount = thread.checkpoints.reduce(
372 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
373 0,
374 );
375 const nextTurnCount = existingPlaceholder
376 ? existingPlaceholder.checkpointTurnCount
377 : currentTurnCount + 1;
378​
379 yield* captureAndDispatchCheckpoint({
380 threadId: thread.id,
381 turnId,
382 thread,
383 cwd: checkpointCwd,
384 turnCount: nextTurnCount,
385 status: checkpointStatusFromRuntime(event.payload.state),
386 assistantMessageId: undefined,
387 createdAt: event.createdAt,
388 });
389 });
390​
391 // Captures a real git checkpoint when a placeholder checkpoint (status "missing")
392 // is detected via a domain event. This replaces the placeholder with a real
393 // git-ref-based checkpoint.
394 //
395 // ProviderRuntimeIngestion creates placeholder checkpoints on turn.diff.updated
396 // events from the Codex runtime. This handler fires when the corresponding
397 // domain event arrives, allowing the reactor to capture the actual filesystem
398 // state into a git ref and dispatch a replacement checkpoint.
399 const captureCheckpointFromPlaceholder = Effect.fnUntraced(function* (
400 event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
401 ) {
402 const { threadId, turnId, checkpointTurnCount, status } = event.payload;
403​
404 // Only replace placeholders; skip events from our own real captures.
405 if (status !== "missing") {
406 return;
407 }
408​
409 const readModel = yield* orchestrationEngine.getReadModel();
410 const thread = readModel.threads.find((entry) => entry.id === threadId);
411 if (!thread) {
412 yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
413 threadId,
414 });
415 return;
416 }
417​
418 // If a real checkpoint already exists for this turn, skip.
419 if (
420 thread.checkpoints.some(
421 (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
422 )
423 ) {
424 yield* Effect.logDebug(
425 "checkpoint capture from placeholder skipped: real checkpoint already exists",
426 { threadId, turnId },
427 );
428 return;
429 }
430​
431 const checkpointCwd = yield* resolveCheckpointCwd({
432 threadId,
433 thread,
434 projects: readModel.projects,
435 preferSessionRuntime: true,
436 });
437 if (!checkpointCwd) {
438 return;
439 }
440​
441 yield* captureAndDispatchCheckpoint({
442 threadId,
443 turnId,
444 thread,
445 cwd: checkpointCwd,
446 turnCount: checkpointTurnCount,
447 status: "ready",
448 assistantMessageId: event.payload.assistantMessageId ?? undefined,
449 createdAt: event.payload.completedAt,
450 });
451 });
452​
453 const ensurePreTurnBaselineFromTurnStart = Effect.fnUntraced(function* (
454 event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>,
455 ) {
456 const turnId = toTurnId(event.turnId);
457 if (!turnId) {
458 return;
459 }
460​
461 const readModel = yield* orchestrationEngine.getReadModel();
462 const thread = readModel.threads.find((entry) => entry.id === event.threadId);
463 if (!thread) {
464 return;
465 }
466​
467 const checkpointCwd = yield* resolveCheckpointCwd({
468 threadId: thread.id,
469 thread,
470 projects: readModel.projects,
471 preferSessionRuntime: false,
472 });
473 if (!checkpointCwd) {
474 return;
475 }
476​
477 const currentTurnCount = thread.checkpoints.reduce(
478 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
479 0,
480 );
481 const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
482 const baselineExists = yield* checkpointStore.hasCheckpointRef({
483 cwd: checkpointCwd,
484 checkpointRef: baselineCheckpointRef,
485 });
486 if (baselineExists) {
487 return;
488 }
489​
490 yield* checkpointStore.captureCheckpoint({
491 cwd: checkpointCwd,
492 checkpointRef: baselineCheckpointRef,
493 });
494 yield* receiptBus.publish({
495 type: "checkpoint.baseline.captured",
496 threadId: thread.id,
497 checkpointTurnCount: currentTurnCount,
498 checkpointRef: baselineCheckpointRef,
499 createdAt: event.createdAt,
500 });
501 });
502​
503 const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
504 event: Extract<
505 OrchestrationEvent,
506 { type: "thread.turn-start-requested" | "thread.message-sent" }
507 >,
508 ) {
509 if (event.type === "thread.message-sent") {
510 if (
511 event.payload.role !== "user" ||
512 event.payload.streaming ||
513 event.payload.turnId !== null
514 ) {
515 return;
516 }
517 }
518​
519 const threadId = event.payload.threadId;
520 const readModel = yield* orchestrationEngine.getReadModel();
521 const thread = readModel.threads.find((entry) => entry.id === threadId);
522 if (!thread) {
523 return;
524 }
525​
526 const checkpointCwd = yield* resolveCheckpointCwd({
527 threadId,
528 thread,
529 projects: readModel.projects,
530 preferSessionRuntime: false,
531 });
532 if (!checkpointCwd) {
533 return;
534 }
535​
536 const currentTurnCount = thread.checkpoints.reduce(
537 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
538 0,
539 );
540 const baselineCheckpointRef = checkpointRefForThreadTurn(threadId, currentTurnCount);
541 const baselineExists = yield* checkpointStore.hasCheckpointRef({
542 cwd: checkpointCwd,
543 checkpointRef: baselineCheckpointRef,
544 });
545 if (baselineExists) {
546 return;
547 }
548​
549 yield* checkpointStore.captureCheckpoint({
550 cwd: checkpointCwd,
551 checkpointRef: baselineCheckpointRef,
552 });
553 yield* receiptBus.publish({
554 type: "checkpoint.baseline.captured",
555 threadId,
556 checkpointTurnCount: currentTurnCount,
557 checkpointRef: baselineCheckpointRef,
558 createdAt: event.occurredAt,
559 });
560 });
561​
562 const handleRevertRequested = Effect.fnUntraced(function* (
563 event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
564 ) {
565 const now = new Date().toISOString();
566​
567 const readModel = yield* orchestrationEngine.getReadModel();
568 const thread = readModel.threads.find((entry) => entry.id === event.payload.threadId);
569 if (!thread) {
570 yield* appendRevertFailureActivity({
571 threadId: event.payload.threadId,
572 turnCount: event.payload.turnCount,
573 detail: "Thread was not found in read model.",
574 createdAt: now,
575 }).pipe(Effect.catch(() => Effect.void));
576 return;
577 }
578​
579 const sessionRuntime = yield* resolveSessionRuntimeForThread(event.payload.threadId);
580 if (Option.isNone(sessionRuntime)) {
581 yield* appendRevertFailureActivity({
582 threadId: event.payload.threadId,
583 turnCount: event.payload.turnCount,
584 detail: "No active provider session with workspace cwd is bound to this thread.",
585 createdAt: now,
586 }).pipe(Effect.catch(() => Effect.void));
587 return;
588 }
589 if (!isGitWorkspace(sessionRuntime.value.cwd)) {
590 yield* appendRevertFailureActivity({
591 threadId: event.payload.threadId,
592 turnCount: event.payload.turnCount,
593 detail: "Checkpoints are unavailable because this project is not a git repository.",
594 createdAt: now,
595 }).pipe(Effect.catch(() => Effect.void));
596 return;
597 }
598​
599 const currentTurnCount = thread.checkpoints.reduce(
600 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
601 0,
602 );
603​
604 if (event.payload.turnCount > currentTurnCount) {
605 yield* appendRevertFailureActivity({
606 threadId: event.payload.threadId,
607 turnCount: event.payload.turnCount,
608 detail: `Checkpoint turn count ${event.payload.turnCount} exceeds current turn count ${currentTurnCount}.`,
609 createdAt: now,
610 }).pipe(Effect.catch(() => Effect.void));
611 return;
612 }
613​
614 const targetCheckpointRef =
615 event.payload.turnCount === 0
616 ? checkpointRefForThreadTurn(event.payload.threadId, 0)
617 : thread.checkpoints.find(
618 (checkpoint) => checkpoint.checkpointTurnCount === event.payload.turnCount,
619 )?.checkpointRef;
620​
621 if (!targetCheckpointRef) {
622 yield* appendRevertFailureActivity({
623 threadId: event.payload.threadId,
624 turnCount: event.payload.turnCount,
625 detail: `Checkpoint ref for turn ${event.payload.turnCount} is unavailable in read model.`,
626 createdAt: now,
627 }).pipe(Effect.catch(() => Effect.void));
628 return;
629 }
630​
631 const restored = yield* checkpointStore.restoreCheckpoint({
632 cwd: sessionRuntime.value.cwd,
633 checkpointRef: targetCheckpointRef,
634 fallbackToHead: event.payload.turnCount === 0,
635 });
636 if (!restored) {
637 yield* appendRevertFailureActivity({
638 threadId: event.payload.threadId,
639 turnCount: event.payload.turnCount,
640 detail: `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`,
641 createdAt: now,
642 }).pipe(Effect.catch(() => Effect.void));
643 return;
644 }
645​
646 // Invalidate the workspace entry cache so the @-mention file picker
647 // reflects the reverted filesystem state.
648 clearWorkspaceIndexCache(sessionRuntime.value.cwd);
649​
650 const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
651 if (rolledBackTurns > 0) {
652 yield* providerService.rollbackConversation({
653 threadId: sessionRuntime.value.threadId,
654 numTurns: rolledBackTurns,
655 });
656 }
657​
658 const staleCheckpointRefs = thread.checkpoints
659 .filter((checkpoint) => checkpoint.checkpointTurnCount > event.payload.turnCount)
660 .map((checkpoint) => checkpoint.checkpointRef);
661​
662 if (staleCheckpointRefs.length > 0) {
663 yield* checkpointStore.deleteCheckpointRefs({
664 cwd: sessionRuntime.value.cwd,
665 checkpointRefs: staleCheckpointRefs,
666 });
667 }
668​
669 yield* orchestrationEngine
670 .dispatch({
671 type: "thread.revert.complete",
672 commandId: serverCommandId("checkpoint-revert-complete"),
673 threadId: event.payload.threadId,
674 turnCount: event.payload.turnCount,
675 createdAt: now,
676 })
677 .pipe(
678 Effect.catch((error) =>
679 appendRevertFailureActivity({
680 threadId: event.payload.threadId,
681 turnCount: event.payload.turnCount,
682 detail: error.message,
683 createdAt: now,
684 }),
685 ),
686 Effect.asVoid,
687 );
688 });
689​
690 const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {
691 if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
692 yield* ensurePreTurnBaselineFromDomainTurnStart(event);
693 return;
694 }
695​
696 if (event.type === "thread.checkpoint-revert-requested") {
697 yield* handleRevertRequested(event).pipe(
698 Effect.catch((error) =>
699 appendRevertFailureActivity({
700 threadId: event.payload.threadId,
701 turnCount: event.payload.turnCount,
702 detail: error.message,
703 createdAt: new Date().toISOString(),
704 }),
705 ),
706 );
707 return;
708 }
709​
710 // When ProviderRuntimeIngestion creates a placeholder checkpoint (status "missing")
711 // from a turn.diff.updated runtime event, capture the real git checkpoint to
712 // replace it. The providerService.streamEvents PubSub does not reliably deliver
713 // turn.completed runtime events to this reactor (shared subscription), so
714 // reacting to the domain event is the reliable path.
715 if (event.type === "thread.turn-diff-completed") {
716 yield* captureCheckpointFromPlaceholder(event).pipe(
717 Effect.catch((error) =>
718 appendCaptureFailureActivity({
719 threadId: event.payload.threadId,
720 turnId: event.payload.turnId,
721 detail: error.message,
722 createdAt: new Date().toISOString(),
723 }).pipe(Effect.catch(() => Effect.void)),
724 ),
725 );
726 }
727 });
728​
729 const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) {
730 if (event.type === "turn.started") {
731 yield* ensurePreTurnBaselineFromTurnStart(event);
732 return;
733 }
734​
735 if (event.type === "turn.completed") {
736 const turnId = toTurnId(event.turnId);
737 yield* captureCheckpointFromTurnCompletion(event).pipe(
738 Effect.catch((error) =>
739 appendCaptureFailureActivity({
740 threadId: event.threadId,
741 turnId,
742 detail: error.message,
743 createdAt: new Date().toISOString(),
744 }).pipe(Effect.catch(() => Effect.void)),
745 ),
746 );
747 return;
748 }
749 });
750​
751 const processInput = (
752 input: ReactorInput,
753 ): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError, never> =>
754 input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
755​
756 const processInputSafely = (input: ReactorInput) =>
757 processInput(input).pipe(
758 Effect.catchCause((cause) => {
759 if (Cause.hasInterruptsOnly(cause)) {
760 return Effect.failCause(cause);
761 }
762 return Effect.logWarning("checkpoint reactor failed to process input", {
763 source: input.source,
764 eventType: input.event.type,
765 cause: Cause.pretty(cause),
766 });
767 }),
768 );
769​
770 const worker = yield* makeDrainableWorker(processInputSafely);
771​
772 const start: CheckpointReactorShape["start"] = Effect.gen(function* () {
773 yield* Effect.forkScoped(
774 Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
775 if (
776 event.type !== "thread.turn-start-requested" &&
777 event.type !== "thread.message-sent" &&
778 event.type !== "thread.checkpoint-revert-requested" &&
779 event.type !== "thread.turn-diff-completed"
780 ) {
781 return Effect.void;
782 }
783 return worker.enqueue({ source: "domain", event });
784 }),
785 );
786​
787 yield* Effect.forkScoped(
788 Stream.runForEach(providerService.streamEvents, (event) => {
789 if (event.type !== "turn.started" && event.type !== "turn.completed") {
790 return Effect.void;
791 }
792 return worker.enqueue({ source: "runtime", event });
793 }),
794 );
795 });
796​
797 return {
798 start,
799 drain: worker.drain,
800 } satisfies CheckpointReactorShape;
801});
802​
803export const CheckpointReactorLive = Layer.effect(CheckpointReactor, make);