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

CheckpointReactor.ts

1,063 lines36.8 KB

1import {
2 CommandId,
3 type CheckpointRef,
4 EventId,
5 MessageId,
6 type ProjectId,
7 ThreadId,
8 TurnId,
9 type OrchestrationEvent,
10 type ProviderRuntimeEvent,
11 type VcsStatusLocalResult,
12} from "@t3tools/contracts";
13import * as Cause from "effect/Cause";
14import * as Crypto from "effect/Crypto";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as FileSystem from "effect/FileSystem";
19import * as Path from "effect/Path";
20import * as Option from "effect/Option";
21import type * as PlatformError from "effect/PlatformError";
22import * as Stream from "effect/Stream";
23import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
24import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
25​
26import { parseTurnDiffFilesFromNumstat } from "../../checkpointing/Diffs.ts";
27import {
28 checkpointRefForThreadTurn,
29 resolveThreadWorkspaceCwd,
30} from "../../checkpointing/Utils.ts";
31import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
32import { ProviderService } from "../../provider/Services/ProviderService.ts";
33import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
34import { forkParked } from "../../serverActivation.ts";
35import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
36import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
37import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
38import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
39import type { OrchestrationDispatchError } from "../Errors.ts";
40import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
41import * as WorkspaceEntries from "../../workspace/WorkspaceEntries.ts";
42import * as PullRequestService from "../../pullRequest/PullRequestService.ts";
43​
44const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
45​
46type ReactorInput =
47 | {
48 readonly source: "runtime";
49 readonly event: ProviderRuntimeEvent;
50 }
51 | {
52 readonly source: "domain";
53 readonly event: OrchestrationEvent;
54 };
55​
56function toTurnId(value: string | undefined): TurnId | null {
57 return value === undefined ? null : TurnId.make(String(value));
59​
60function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
61 if (left === null || left === undefined || right === null || right === undefined) {
62 return false;
63 }
64 return left === right;
66​
67function checkpointStatusFromRuntime(status: string | undefined): "ready" | "missing" | "error" {
68 switch (status) {
69 case "failed":
70 return "error";
71 case "cancelled":
72 case "interrupted":
73 return "missing";
74 case "completed":
75 default:
76 return "ready";
77 }
79​
80const make = Effect.gen(function* () {
81 const crypto = yield* Crypto.Crypto;
82 const randomUUID = crypto.randomUUIDv4;
83 const serverEventId = randomUUID.pipe(Effect.map(EventId.make));
84 const serverCommandId = (tag: string) =>
85 randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));
86 const orchestrationEngine = yield* OrchestrationEngineService;
87 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
88 const providerService = yield* ProviderService;
89 const checkpointStore = yield* CheckpointStore.CheckpointStore;
90 const receiptBus = yield* RuntimeReceiptBus;
91 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
92 const fileSystem = yield* FileSystem.FileSystem;
93 const path = yield* Path.Path;
94 const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
95 const pullRequests = yield* PullRequestService.PullRequestService;
96 const queuedEntryRefreshes = new Set<string>();
97 const entryRefreshWorker = yield* makeDrainableWorker((cwd: string) =>
98 Effect.sync(() => queuedEntryRefreshes.delete(cwd)).pipe(
99 Effect.andThen(workspaceEntries.refresh(cwd)),
100 Effect.catchCauseIf(
101 (cause) => !Cause.hasInterruptsOnly(cause),
102 () =>
103 Effect.logWarning("failed to refresh checkpoint workspace entries", {
104 cwd,
105 }),
106 ),
107 ),
108 );
109 const refreshWorkspaceEntries = Effect.fn("refreshWorkspaceEntries")(function* (cwd: string) {
110 if (queuedEntryRefreshes.has(cwd)) return;
111 queuedEntryRefreshes.add(cwd);
112 yield* entryRefreshWorker.enqueue(cwd);
113 });
114​
115 const startedTurns = new Map<ThreadId, TurnId>();
116 const pending = new Set<ThreadId>();
117​
118 const appendRevertFailureActivity = (input: {
119 readonly threadId: ThreadId;
120 readonly turnCount: number;
121 readonly detail: string;
122 readonly createdAt: string;
123 }) =>
124 Effect.all({
125 commandId: serverCommandId("checkpoint-revert-failure"),
126 activityId: serverEventId,
127 }).pipe(
128 Effect.flatMap(({ commandId, activityId }) =>
129 orchestrationEngine.dispatch({
130 type: "thread.activity.append",
131 commandId,
132 threadId: input.threadId,
133 activity: {
134 id: activityId,
135 tone: "error",
136 kind: "checkpoint.revert.failed",
137 summary: "Checkpoint revert failed",
138 payload: {
139 turnCount: input.turnCount,
140 detail: input.detail,
141 },
142 turnId: null,
143 createdAt: input.createdAt,
144 },
145 createdAt: input.createdAt,
146 }),
147 ),
148 );
149​
150 const appendCaptureFailureActivity = (input: {
151 readonly threadId: ThreadId;
152 readonly turnId: TurnId | null;
153 readonly detail: string;
154 readonly createdAt: string;
155 }) =>
156 Effect.all({
157 commandId: serverCommandId("checkpoint-capture-failure"),
158 activityId: serverEventId,
159 }).pipe(
160 Effect.flatMap(({ commandId, activityId }) =>
161 orchestrationEngine.dispatch({
162 type: "thread.activity.append",
163 commandId,
164 threadId: input.threadId,
165 activity: {
166 id: activityId,
167 tone: "error",
168 kind: "checkpoint.capture.failed",
169 summary: "Checkpoint capture failed",
170 payload: {
171 detail: input.detail,
172 },
173 turnId: input.turnId,
174 createdAt: input.createdAt,
175 },
176 createdAt: input.createdAt,
177 }),
178 ),
179 );
180​
181 const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
182 threadId: ThreadId,
183 ): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
184 const sessions = yield* providerService.listSessions();
185 const session = sessions.find((entry) => entry.threadId === threadId);
186 return session?.cwd
187 ? Option.some({ threadId: session.threadId, cwd: session.cwd })
188 : Option.none();
189 });
190​
191 const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) {
192 return yield* projectionSnapshotQuery
193 .getThreadDetailById(threadId, { activityKinds: [] })
194 .pipe(Effect.map(Option.getOrUndefined));
195 });
196​
197 const resolveThreadProjects = Effect.fn("resolveThreadProjects")(function* (
198 projectId: ProjectId,
199 ) {
200 const project = yield* projectionSnapshotQuery
201 .getProjectShellById(projectId)
202 .pipe(Effect.map(Option.getOrUndefined));
203 return project ? [project] : [];
204 });
205​
206 // Resolves the workspace CWD for checkpoint operations, preferring the
207 // active provider session CWD and falling back to the thread/project config.
208 // Returns undefined when no CWD can be determined or the workspace is not
209 // a git repository.
210 const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: {
211 readonly threadId: ThreadId;
212 readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
213 readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
214 readonly preferSessionRuntime: boolean;
215 }): Effect.fn.Return<string | undefined, CheckpointStoreError> {
216 const fromSession = yield* resolveSessionRuntimeForThread(input.threadId);
217 const fromThread = resolveThreadWorkspaceCwd({
218 thread: input.thread,
219 projects: input.projects,
220 });
221​
222 const cwd = input.preferSessionRuntime
223 ? (Option.match(fromSession, {
224 onNone: () => undefined,
225 onSome: (runtime) => runtime.cwd,
226 }) ?? fromThread)
227 : (fromThread ??
228 Option.match(fromSession, {
229 onNone: () => undefined,
230 onSome: (runtime) => runtime.cwd,
231 }));
232​
233 if (!cwd) {
234 return undefined;
235 }
236 if (!(yield* checkpointStore.isGitRepository(cwd))) {
237 return undefined;
238 }
239 return cwd;
240 });
241​
242 // Capture the completed turn's files, then publish its summary and receipts.
243 const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: {
244 readonly threadId: ThreadId;
245 readonly turnId: TurnId;
246 readonly thread: {
247 readonly messages: ReadonlyArray<{
248 readonly id: MessageId;
249 readonly role: string;
250 readonly turnId: TurnId | null;
251 }>;
252 };
253 readonly cwd: string;
254 readonly turnCount: number;
255 readonly status: "ready" | "missing" | "error";
256 readonly assistantMessageId: MessageId | undefined;
257 readonly createdAt: string;
258 }) {
259 const fromTurnCount = Math.max(0, input.turnCount - 1);
260 const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, fromTurnCount);
261 const targetCheckpointRef = checkpointRefForThreadTurn(input.threadId, input.turnCount);
262​
263 const fromCheckpointExists = yield* checkpointStore
264 .hasCheckpointRef({
265 cwd: input.cwd,
266 checkpointRef: fromCheckpointRef,
267 })
268 .pipe(
269 Effect.catch((error) =>
270 Effect.logWarning("checkpoint capture previous ref lookup failed", {
271 threadId: input.threadId,
272 checkpointRef: fromCheckpointRef,
273 category: error._tag,
274 }).pipe(Effect.as(false)),
275 ),
276 );
277 if (!fromCheckpointExists) {
278 yield* Effect.logWarning("checkpoint capture missing pre-turn baseline", {
279 threadId: input.threadId,
280 turnId: input.turnId,
281 fromTurnCount,
282 });
283 }
284​
285 yield* checkpointStore.captureCheckpoint({
286 cwd: input.cwd,
287 checkpointRef: targetCheckpointRef,
288 });
289​
290 // Refresh the workspace entry index so the @-mention file picker
291 // reflects files created or deleted during this turn.
292 yield* refreshWorkspaceEntries(input.cwd);
293​
294 // Git may have been initialized during this turn, leaving no pre-turn
295 // snapshot. Keep the completion checkpoint for future turns, but do not
296 // invent a baseline or attempt a diff against a ref that does not exist.
297 const files = yield* (
298 fromCheckpointExists
299 ? checkpointStore.diffCheckpoints({
300 cwd: input.cwd,
301 fromCheckpointRef,
302 toCheckpointRef: targetCheckpointRef,
303 fallbackFromToHead: false,
304 ignoreWhitespace: false,
305 format: "numstat",
306 })
307 : Effect.succeed("")
308 ).pipe(
309 Effect.map((diff) =>
310 parseTurnDiffFilesFromNumstat(diff).map((file) => ({
311 path: file.path,
312 kind: "modified" as const,
313 additions: file.additions,
314 deletions: file.deletions,
315 })),
316 ),
317 Effect.tapError((error) =>
318 appendCaptureFailureActivity({
319 threadId: input.threadId,
320 turnId: input.turnId,
321 detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
322 createdAt: input.createdAt,
323 }),
324 ),
325 Effect.catch((error) =>
326 Effect.logWarning("failed to derive checkpoint file summary", {
327 threadId: input.threadId,
328 turnId: input.turnId,
329 turnCount: input.turnCount,
330 detail: error.message,
331 }).pipe(Effect.as([])),
332 ),
333 );
334​
335 const assistantMessageId =
336 input.assistantMessageId ??
337 input.thread.messages
338 .toReversed()
339 .find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ??
340 MessageId.make(`assistant:${input.turnId}`);
341​
342 yield* orchestrationEngine.dispatch({
343 type: "thread.turn.diff.complete",
344 commandId: yield* serverCommandId("checkpoint-turn-diff-complete"),
345 threadId: input.threadId,
346 turnId: input.turnId,
347 completedAt: input.createdAt,
348 checkpointRef: targetCheckpointRef,
349 status: input.status,
350 files,
351 assistantMessageId,
352 checkpointTurnCount: input.turnCount,
353 createdAt: input.createdAt,
354 });
355 yield* receiptBus.publish({
356 type: "checkpoint.diff.finalized",
357 threadId: input.threadId,
358 turnId: input.turnId,
359 checkpointTurnCount: input.turnCount,
360 checkpointRef: targetCheckpointRef,
361 status: input.status,
362 createdAt: input.createdAt,
363 });
364 yield* receiptBus.publish({
365 type: "turn.processing.quiesced",
366 threadId: input.threadId,
367 turnId: input.turnId,
368 checkpointTurnCount: input.turnCount,
369 createdAt: input.createdAt,
370 });
371​
372 yield* orchestrationEngine.dispatch({
373 type: "thread.activity.append",
374 commandId: yield* serverCommandId("checkpoint-captured-activity"),
375 threadId: input.threadId,
376 activity: {
377 id: EventId.make(yield* randomUUID),
378 tone: "info",
379 kind: "checkpoint.captured",
380 summary: "Checkpoint captured",
381 payload: {
382 turnCount: input.turnCount,
383 status: input.status,
384 },
385 turnId: input.turnId,
386 createdAt: input.createdAt,
387 },
388 createdAt: input.createdAt,
389 });
390 });
391​
392 // Capture the files left by a completed or interrupted turn.
393 const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")(
394 function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" | "turn.aborted" }>) {
395 const turnId = toTurnId(event.turnId);
396 if (!turnId) {
397 return;
398 }
399​
400 const thread = yield* resolveThreadDetail(event.threadId);
401 if (!thread) {
402 return;
403 }
404​
405 // When a primary turn is active, only that turn may produce completion checkpoints.
406 if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
407 return;
408 }
409​
410 // Only skip if a real (non-placeholder) checkpoint already exists for this turn.
411 // ProviderRuntimeIngestion may insert placeholder entries with status "missing"
412 // before this reactor runs; those must not prevent real git capture.
413 if (
414 thread.checkpoints.some(
415 (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
416 )
417 ) {
418 return;
419 }
420​
421 const projects = yield* resolveThreadProjects(thread.projectId);
422 const checkpointCwd = yield* resolveCheckpointCwd({
423 threadId: thread.id,
424 thread,
425 projects,
426 preferSessionRuntime: true,
427 });
428 if (!checkpointCwd) {
429 return;
430 }
431​
432 // If a placeholder checkpoint exists for this turn, reuse its turn count
433 // instead of incrementing past it.
434 const existingPlaceholder = thread.checkpoints.find(
435 (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
436 );
437 const currentTurnCount = thread.checkpoints.reduce(
438 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
439 0,
440 );
441 const nextTurnCount = existingPlaceholder
442 ? existingPlaceholder.checkpointTurnCount
443 : currentTurnCount + 1;
444​
445 yield* captureAndDispatchCheckpoint({
446 threadId: thread.id,
447 turnId,
448 thread,
449 cwd: checkpointCwd,
450 turnCount: nextTurnCount,
451 status:
452 event.type === "turn.aborted"
453 ? "ready"
454 : checkpointStatusFromRuntime(event.payload.state),
455 assistantMessageId: existingPlaceholder?.assistantMessageId ?? undefined,
456 createdAt: event.createdAt,
457 });
458 },
459 );
460​
461 const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")(
462 function* (event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>) {
463 const turnId = toTurnId(event.turnId);
464 if (!turnId) {
465 return;
466 }
467​
468 const thread = yield* resolveThreadDetail(event.threadId);
469 if (!thread) {
470 return;
471 }
472​
473 const projects = yield* resolveThreadProjects(thread.projectId);
474 const checkpointCwd = yield* resolveCheckpointCwd({
475 threadId: thread.id,
476 thread,
477 projects,
478 preferSessionRuntime: false,
479 });
480 if (!checkpointCwd) {
481 return;
482 }
483​
484 const currentTurnCount = thread.checkpoints.reduce(
485 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
486 0,
487 );
488 const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
489 const baselineExists = yield* checkpointStore.hasCheckpointRef({
490 cwd: checkpointCwd,
491 checkpointRef: baselineCheckpointRef,
492 });
493 if (baselineExists) {
494 return;
495 }
496​
497 yield* checkpointStore.captureCheckpoint({
498 cwd: checkpointCwd,
499 checkpointRef: baselineCheckpointRef,
500 });
501 yield* receiptBus.publish({
502 type: "checkpoint.baseline.captured",
503 threadId: thread.id,
504 checkpointTurnCount: currentTurnCount,
505 checkpointRef: baselineCheckpointRef,
506 createdAt: event.createdAt,
507 });
508 },
509 );
510​
511 const refreshLocalGitStatusFromTurnCompletion = Effect.fn(
512 "refreshLocalGitStatusFromTurnCompletion",
513 )(function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
514 const sessionRuntime = yield* resolveSessionRuntimeForThread(event.threadId);
515 if (Option.isNone(sessionRuntime)) {
516 return;
517 }
518​
519 const local = yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(
520 Effect.catch((error) =>
521 Effect.logWarning("failed to refresh local git status after turn completion", {
522 threadId: event.threadId,
523 turnId: event.turnId ?? null,
524 cwd: sessionRuntime.value.cwd,
525 detail: error.message,
526 }).pipe(Effect.as(null)),
527 ),
528 );
529 if (local !== null) {
530 yield* followWorktreeBranchDrift({
531 threadId: event.threadId,
532 cwd: sessionRuntime.value.cwd,
533 local,
534 });
535 yield* refreshPullRequestAfterTurn({
536 threadId: event.threadId,
537 turnId: toTurnId(event.turnId),
538 cwd: sessionRuntime.value.cwd,
539 local,
540 });
541 }
542 });
543​
544 // Retry a missing PR after the agent finishes its push and PR creation.
545 // Re-read the projected branch after drift adoption. A rejected metadata
546 // update must not let this thread refresh another thread's checkout.
547 const refreshPullRequestAfterTurn = Effect.fn("refreshPullRequestAfterTurn")(function* (input: {
548 readonly threadId: ThreadId;
549 readonly turnId: TurnId | null;
550 readonly cwd: string;
551 readonly local: VcsStatusLocalResult;
552 }) {
553 const checkedOutBranch = input.local.refName;
554 if (checkedOutBranch === null || input.local.isDefaultRef) return;
555 const thread = yield* projectionSnapshotQuery
556 .getThreadShellById(input.threadId)
557 .pipe(Effect.map(Option.getOrUndefined));
558 if (!thread || thread.branch !== checkedOutBranch) return;
559 if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, input.turnId)) return;
560 yield* vcsStatusBroadcaster.refreshPullRequestStatus(input.cwd).pipe(
561 Effect.catch((error) =>
562 Effect.logWarning("failed to refresh pull request status after turn completion", {
563 threadId: input.threadId,
564 cwd: input.cwd,
565 detail: error.message,
566 }),
567 ),
568 );
569 });
570​
571 // A `git checkout` run inside a thread's dedicated worktree (by an agent or
572 // the user) bypasses T3's commands, so the thread's recorded branch goes
573 // stale. Since #4460 the client only attributes PR state to a thread when
574 // the checked-out branch equals the recorded one, so stale metadata silently
575 // orphans the thread's PR. Follow the drift here: adopt the checked-out
576 // branch as the thread's branch, but only when the worktree belongs to
577 // exactly this thread — for shared cwds the strict matching is the point.
578 const followWorktreeBranchDrift = Effect.fn("followWorktreeBranchDrift")(function* (input: {
579 readonly threadId: ThreadId;
580 readonly cwd: string;
581 readonly local: VcsStatusLocalResult;
582 }) {
583 // Detached HEAD has no branch to adopt; a temporary placeholder checkout
584 // means the first-turn auto-rename is still in flight — don't race it.
585 const checkedOutBranch = input.local.refName;
586 if (checkedOutBranch === null || isTemporaryWorktreeBranch(checkedOutBranch)) {
587 return;
588 }
589​
590 yield* Effect.gen(function* () {
591 const thread = yield* projectionSnapshotQuery
592 .getThreadShellById(input.threadId)
593 .pipe(Effect.map(Option.getOrUndefined));
594 if (
595 !thread ||
596 thread.branch === null ||
597 thread.branch === checkedOutBranch ||
598 thread.worktreePath === null ||
599 thread.worktreePath !== input.cwd
600 ) {
601 return;
602 }
603​
604 const shell = yield* projectionSnapshotQuery.getShellSnapshot();
605 const worktreeIsShared = shell.threads.some(
606 (other) => other.id !== thread.id && other.worktreePath === thread.worktreePath,
607 );
608 if (worktreeIsShared) {
609 return;
610 }
611​
612 // expectedBranch makes this a compare-and-swap in the decider: if the
613 // recorded branch moved between our read and the dispatch (rename,
614 // concurrent drift-follow), the stale update is dropped.
615 yield* orchestrationEngine.dispatch({
616 type: "thread.meta.update",
617 commandId: yield* serverCommandId("worktree-branch-drift"),
618 threadId: thread.id,
619 branch: checkedOutBranch,
620 expectedBranch: thread.branch,
621 });
622 yield* Effect.logInfo("thread branch followed worktree checkout", {
623 threadId: thread.id,
624 previousBranch: thread.branch,
625 branch: checkedOutBranch,
626 });
627 }).pipe(
628 Effect.catchCauseIf(
629 (cause) => !Cause.hasInterruptsOnly(cause),
630 (cause) =>
631 Effect.logWarning("failed to follow worktree branch drift", {
632 threadId: input.threadId,
633 cause: Cause.pretty(cause),
634 }),
635 ),
636 );
637 });
638​
639 // Refreshing git status ends in a remote PR lookup under the vcs status
640 // write lock. Run it on its own worker so file capture for this turn (and
641 // checkpoints for other threads) never wait behind that network call.
642 const statusRefreshWorker = yield* makeDrainableWorker(
643 (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) =>
644 refreshLocalGitStatusFromTurnCompletion(event).pipe(
645 Effect.catchCauseIf(
646 (cause) => !Cause.hasInterruptsOnly(cause),
647 () =>
648 Effect.logWarning("failed to refresh git status after turn completion", {
649 threadId: event.threadId,
650 }),
651 ),
652 ),
653 );
654​
655 const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
656 "ensurePreTurnBaselineFromDomainTurnStart",
657 )(function* (
658 event: Extract<
659 OrchestrationEvent,
660 { type: "thread.turn-start-requested" | "thread.message-sent" }
661 >,
662 ) {
663 if (event.type === "thread.message-sent") {
664 // A bootstrap message lands before the worktree exists; its baseline
665 // would snapshot the project checkout. The turn-start event that
666 // follows captures it against the right cwd.
667 if (
668 event.metadata.historyImport === true ||
669 event.metadata.deferredTurn === true ||
670 event.payload.role !== "user" ||
671 event.payload.streaming ||
672 event.payload.turnId !== null
673 ) {
674 return;
675 }
676 }
677​
678 const threadId = event.payload.threadId;
679 const thread = yield* resolveThreadDetail(threadId);
680 if (!thread) {
681 return;
682 }
683​
684 const projects = yield* resolveThreadProjects(thread.projectId);
685 const checkpointCwd = yield* resolveCheckpointCwd({
686 threadId,
687 thread,
688 projects,
689 preferSessionRuntime: false,
690 });
691 if (!checkpointCwd) {
692 return;
693 }
694​
695 const currentTurnCount = thread.checkpoints.reduce(
696 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
697 0,
698 );
699 const baselineCheckpointRef = checkpointRefForThreadTurn(threadId, currentTurnCount);
700 const baselineExists = yield* checkpointStore.hasCheckpointRef({
701 cwd: checkpointCwd,
702 checkpointRef: baselineCheckpointRef,
703 });
704 if (baselineExists) {
705 return;
706 }
707​
708 yield* checkpointStore.captureCheckpoint({
709 cwd: checkpointCwd,
710 checkpointRef: baselineCheckpointRef,
711 });
712 yield* receiptBus.publish({
713 type: "checkpoint.baseline.captured",
714 threadId,
715 checkpointTurnCount: currentTurnCount,
716 checkpointRef: baselineCheckpointRef,
717 createdAt: event.occurredAt,
718 });
719 });
720​
721 // Checkpoints contain the whole checkout, so restoring a shared cwd can erase a sibling's work.
722 const isRestoreWorkspaceIsolated = Effect.fn("isRestoreWorkspaceIsolated")(function* (
723 thread: { readonly id: ThreadId; readonly worktreePath: string | null },
724 cwd: string,
725 ) {
726 if (thread.worktreePath === null) return false;
727 const canonicalCwd = yield* fileSystem.realPath(cwd);
728 if ((yield* fileSystem.realPath(thread.worktreePath)) !== canonicalCwd) return false;
729 const active = yield* projectionSnapshotQuery.getShellSnapshot();
730 const archived = yield* projectionSnapshotQuery.getArchivedShellSnapshot();
731 const projects = [...active.projects, ...archived.projects];
732 const paths = new Set<string>();
733 for (const other of [...active.threads, ...archived.threads]) {
734 if (other.id === thread.id) continue;
735 const candidate =
736 other.worktreePath ??
737 projects.find((project) => project.id === other.projectId)?.workspaceRoot;
738 if (candidate !== undefined) paths.add(candidate);
739 }
740 for (const session of yield* providerService.listSessions()) {
741 if (
742 session.threadId !== thread.id &&
743 session.status !== "closed" &&
744 session.cwd !== undefined
745 )
746 paths.add(session.cwd);
747 }
748 for (const candidate of paths) {
749 const otherCwd = yield* fileSystem
750 .realPath(candidate)
751 .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(null)));
752 if (otherCwd === null) continue;
753 const isWithin = (parent: string, child: string) => {
754 const relative = path.relative(parent, child);
755 return (
756 relative === "" ||
757 (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`))
758 );
759 };
760 // Parent and nested owners can both have files inside the restore target.
761 if (isWithin(canonicalCwd, otherCwd) || isWithin(otherCwd, canonicalCwd)) return false;
762 }
763 return true;
764 });
765​
766 const handleRevertRequested = Effect.fn("handleRevertRequested")(function* (
767 event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
768 ) {
769 const now = DateTime.formatIso(yield* DateTime.now);
770​
771 const thread = yield* resolveThreadDetail(event.payload.threadId);
772 if (!thread) {
773 yield* appendRevertFailureActivity({
774 threadId: event.payload.threadId,
775 turnCount: event.payload.turnCount,
776 detail: "Thread was not found in read model.",
777 createdAt: now,
778 }).pipe(Effect.catch(() => Effect.void));
779 return;
780 }
781​
782 const checkpointCwd = yield* resolveCheckpointCwd({
783 threadId: event.payload.threadId,
784 thread,
785 projects: yield* resolveThreadProjects(thread.projectId),
786 preferSessionRuntime: true,
787 }).pipe(
788 Effect.catch((error) =>
789 event.payload.restoreFiles === false ? Effect.undefined : Effect.fail(error),
790 ),
791 );
792​
793 const currentTurnCount = thread.checkpoints.reduce(
794 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
795 0,
796 );
797​
798 if (event.payload.turnCount > currentTurnCount) {
799 yield* appendRevertFailureActivity({
800 threadId: event.payload.threadId,
801 turnCount: event.payload.turnCount,
802 detail: `Checkpoint turn count ${event.payload.turnCount} exceeds current turn count ${currentTurnCount}.`,
803 createdAt: now,
804 }).pipe(Effect.catch(() => Effect.void));
805 return;
806 }
807​
808 yield* providerService.assertConversationRollbackSupported(event.payload.threadId);
809​
810 if (event.payload.restoreFiles !== false) {
811 if (!checkpointCwd) {
812 yield* appendRevertFailureActivity({
813 threadId: event.payload.threadId,
814 turnCount: event.payload.turnCount,
815 detail: "Checkpoint workspace is unavailable or is not a git repository.",
816 createdAt: now,
817 }).pipe(Effect.catch(() => Effect.void));
818 return;
819 }
820​
821 if (!(yield* isRestoreWorkspaceIsolated(thread, checkpointCwd))) {
822 yield* appendRevertFailureActivity({
823 threadId: thread.id,
824 turnCount: event.payload.turnCount,
825 detail:
826 "File restore requires an isolated worktree. This workspace may contain changes from another thread. Rewind the conversation without restoring files instead.",
827 createdAt: now,
828 }).pipe(Effect.catch(() => Effect.void));
829 return;
830 }
831​
832 const targetCheckpointRef =
833 event.payload.turnCount === 0
834 ? checkpointRefForThreadTurn(event.payload.threadId, 0)
835 : thread.checkpoints.find(
836 (checkpoint) => checkpoint.checkpointTurnCount === event.payload.turnCount,
837 )?.checkpointRef;
838​
839 if (!targetCheckpointRef) {
840 yield* appendRevertFailureActivity({
841 threadId: event.payload.threadId,
842 turnCount: event.payload.turnCount,
843 detail: `Checkpoint ref for turn ${event.payload.turnCount} is unavailable in read model.`,
844 createdAt: now,
845 }).pipe(Effect.catch(() => Effect.void));
846 return;
847 }
848​
849 const restored = yield* checkpointStore.restoreCheckpoint({
850 cwd: checkpointCwd,
851 checkpointRef: targetCheckpointRef,
852 fallbackToHead: event.payload.turnCount === 0,
853 });
854 if (!restored) {
855 yield* appendRevertFailureActivity({
856 threadId: event.payload.threadId,
857 turnCount: event.payload.turnCount,
858 detail: `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`,
859 createdAt: now,
860 }).pipe(Effect.catch(() => Effect.void));
861 return;
862 }
863​
864 // Refresh the workspace entry index so the @-mention file picker
865 // reflects the reverted filesystem state.
866 yield* refreshWorkspaceEntries(checkpointCwd);
867 }
868​
869 const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
870 if (rolledBackTurns > 0) {
871 yield* providerService.rollbackConversation({
872 threadId: event.payload.threadId,
873 numTurns: rolledBackTurns,
874 });
875 }
876​
877 const staleCheckpointRefs: Array<CheckpointRef> = [];
878 for (const checkpoint of thread.checkpoints) {
879 if (checkpoint.checkpointTurnCount > event.payload.turnCount) {
880 staleCheckpointRefs.push(checkpoint.checkpointRef);
881 }
882 }
883​
884 if (checkpointCwd && staleCheckpointRefs.length > 0) {
885 yield* checkpointStore.deleteCheckpointRefs({
886 cwd: checkpointCwd,
887 checkpointRefs: staleCheckpointRefs,
888 });
889 }
890​
891 yield* orchestrationEngine
892 .dispatch({
893 type: "thread.revert.complete",
894 commandId: yield* serverCommandId("checkpoint-revert-complete"),
895 threadId: event.payload.threadId,
896 turnCount: event.payload.turnCount,
897 createdAt: now,
898 })
899 .pipe(
900 Effect.catch((error) =>
901 appendRevertFailureActivity({
902 threadId: event.payload.threadId,
903 turnCount: event.payload.turnCount,
904 detail: error.message,
905 createdAt: now,
906 }),
907 ),
908 Effect.asVoid,
909 );
910 });
911​
912 const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) {
913 if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
914 if (event.type === "thread.turn-start-requested") pending.add(event.payload.threadId);
915 yield* ensurePreTurnBaselineFromDomainTurnStart(event);
916 return;
917 }
918​
919 if (event.type === "thread.checkpoint-revert-requested") {
920 yield* handleRevertRequested(event).pipe(
921 Effect.catch((error) =>
922 Effect.flatMap(nowIso, (createdAt) =>
923 appendRevertFailureActivity({
924 threadId: event.payload.threadId,
925 turnCount: event.payload.turnCount,
926 detail: error.message,
927 createdAt,
928 }),
929 ),
930 ),
931 );
932 return;
933 }
934 });
935​
936 const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
937 event: ProviderRuntimeEvent,
938 ) {
939 if (event.type === "session.exited") {
940 startedTurns.delete(event.threadId);
941 pending.delete(event.threadId);
942 return;
943 }
944​
945 if (event.type === "turn.started") {
946 const turnId = toTurnId(event.turnId);
947 const activeTurnId = (yield* providerService.listSessions()).find((session) =>
948 sameId(session.threadId, event.threadId),
949 )?.activeTurnId;
950 const mayReplace = pending.has(event.threadId) && sameId(activeTurnId, turnId);
951 if (turnId !== null && (!startedTurns.has(event.threadId) || mayReplace)) {
952 startedTurns.set(event.threadId, turnId);
953 pending.delete(event.threadId);
954 }
955 yield* ensurePreTurnBaselineFromTurnStart(event);
956 return;
957 }
958​
959 if (event.type === "turn.completed" || event.type === "turn.aborted") {
960 const turnId = toTurnId(event.turnId);
961 const thread = yield* resolveThreadDetail(event.threadId);
962 const startedTurnId = startedTurns.get(event.threadId);
963 const isTrackedTurn = sameId(startedTurnId, turnId);
964 if (isTrackedTurn) startedTurns.delete(event.threadId);
965 if (event.type === "turn.completed") {
966 yield* statusRefreshWorker.enqueue(event);
967 }
968 if (
969 turnId !== null &&
970 thread !== undefined &&
971 (isTrackedTurn ||
972 sameId(thread.session?.activeTurnId, turnId) ||
973 (startedTurnId === undefined && !thread.session?.activeTurnId))
974 ) {
975 pending.delete(event.threadId);
976 yield* pullRequests.refreshAfterTurn(thread.projectId);
977 }
978 if (
979 event.type === "turn.aborted" &&
980 !isTrackedTurn &&
981 !sameId(thread?.session?.activeTurnId, turnId)
982 ) {
983 return;
984 }
985 yield* captureCheckpointFromTurnCompletion(event).pipe(
986 Effect.catch((error) =>
987 Effect.flatMap(nowIso, (createdAt) =>
988 appendCaptureFailureActivity({
989 threadId: event.threadId,
990 turnId,
991 detail: error.message,
992 createdAt,
993 }).pipe(Effect.catch(() => Effect.void)),
994 ),
995 ),
996 );
997 return;
998 }
999 });
1000​
1001 const processInput = (
1002 input: ReactorInput,
1003 ): Effect.Effect<
1004 void,
1005 CheckpointStoreError | OrchestrationDispatchError | PlatformError.PlatformError,
1006 never
1007 > =>
1008 input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
1009​
1010 const processInputSafely = (input: ReactorInput) =>
1011 processInput(input).pipe(
1012 Effect.catchCauseIf(
1013 (cause) => !Cause.hasInterruptsOnly(cause),
1014 (cause) =>
1015 Effect.logWarning("checkpoint reactor failed to process input", {
1016 source: input.source,
1017 eventType: input.event.type,
1018 cause: Cause.pretty(cause),
1019 }),
1020 ),
1021 );
1022​
1023 const worker = yield* makeDrainableWorker(processInputSafely);
1024​
1025 const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () {
1026 yield* forkParked(
1027 Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
1028 if (
1029 event.type !== "thread.turn-start-requested" &&
1030 event.type !== "thread.message-sent" &&
1031 event.type !== "thread.checkpoint-revert-requested"
1032 ) {
1033 return Effect.void;
1035 return worker.enqueue({ source: "domain", event });
1036 }),
1037 );
1038​
1039 yield* forkParked(
1040 Stream.runForEach(providerService.streamEvents, (event) => {
1041 if (
1042 event.type !== "turn.started" &&
1043 event.type !== "turn.completed" &&
1044 event.type !== "turn.aborted" &&
1045 event.type !== "session.exited"
1046 ) {
1047 return Effect.void;
1049 return worker.enqueue({ source: "runtime", event });
1050 }),
1051 );
1052 });
1053​
1054 return {
1055 start,
1056 drain: worker.drain.pipe(
1057 Effect.andThen(statusRefreshWorker.drain),
1058 Effect.andThen(entryRefreshWorker.drain),
1059 ),
1060 } satisfies CheckpointReactorShape;
1061});
1062​
1063export const CheckpointReactorLive = Layer.effect(CheckpointReactor, make);