Open History to see the last commit
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));
58}
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;
65}
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 }
78}
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.catchCause((cause) =>
101 Cause.hasInterruptsOnly(cause)
102 ? Effect.failCause(cause)
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.catchCause((cause) => {
629 if (Cause.hasInterruptsOnly(cause)) {
630 return Effect.failCause(cause);
631 }
632 return Effect.logWarning("failed to follow worktree branch drift", {
633 threadId: input.threadId,
634 cause: Cause.pretty(cause),
635 });
636 }),
637 );
638 });
639
640 // Refreshing git status ends in a remote PR lookup under the vcs status
641 // write lock. Run it on its own worker so file capture for this turn (and
642 // checkpoints for other threads) never wait behind that network call.
643 const statusRefreshWorker = yield* makeDrainableWorker(
644 (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) =>
645 refreshLocalGitStatusFromTurnCompletion(event).pipe(
646 Effect.catchCause((cause) =>
647 Cause.hasInterruptsOnly(cause)
648 ? Effect.failCause(cause)
649 : Effect.logWarning("failed to refresh git status after turn completion", {
650 threadId: event.threadId,
651 }),
652 ),
653 ),
654 );
655
656 const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
657 "ensurePreTurnBaselineFromDomainTurnStart",
658 )(function* (
659 event: Extract<
660 OrchestrationEvent,
661 { type: "thread.turn-start-requested" | "thread.message-sent" }
662 >,
663 ) {
664 if (event.type === "thread.message-sent") {
665 // A bootstrap message lands before the worktree exists; its baseline
666 // would snapshot the project checkout. The turn-start event that
667 // follows captures it against the right cwd.
668 if (
669 event.metadata.historyImport === true ||
670 event.metadata.deferredTurn === true ||
671 event.payload.role !== "user" ||
672 event.payload.streaming ||
673 event.payload.turnId !== null
674 ) {
675 return;
676 }
677 }
678
679 const threadId = event.payload.threadId;
680 const thread = yield* resolveThreadDetail(threadId);
681 if (!thread) {
682 return;
683 }
684
685 const projects = yield* resolveThreadProjects(thread.projectId);
686 const checkpointCwd = yield* resolveCheckpointCwd({
687 threadId,
688 thread,
689 projects,
690 preferSessionRuntime: false,
691 });
692 if (!checkpointCwd) {
693 return;
694 }
695
696 const currentTurnCount = thread.checkpoints.reduce(
697 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
698 0,
699 );
700 const baselineCheckpointRef = checkpointRefForThreadTurn(threadId, currentTurnCount);
701 const baselineExists = yield* checkpointStore.hasCheckpointRef({
702 cwd: checkpointCwd,
703 checkpointRef: baselineCheckpointRef,
704 });
705 if (baselineExists) {
706 return;
707 }
708
709 yield* checkpointStore.captureCheckpoint({
710 cwd: checkpointCwd,
711 checkpointRef: baselineCheckpointRef,
712 });
713 yield* receiptBus.publish({
714 type: "checkpoint.baseline.captured",
715 threadId,
716 checkpointTurnCount: currentTurnCount,
717 checkpointRef: baselineCheckpointRef,
718 createdAt: event.occurredAt,
719 });
720 });
721
722 // Checkpoints contain the whole checkout, so restoring a shared cwd can erase a sibling's work.
723 const isRestoreWorkspaceIsolated = Effect.fn("isRestoreWorkspaceIsolated")(function* (
724 thread: { readonly id: ThreadId; readonly worktreePath: string | null },
725 cwd: string,
726 ) {
727 if (thread.worktreePath === null) return false;
728 const canonicalCwd = yield* fileSystem.realPath(cwd);
729 if ((yield* fileSystem.realPath(thread.worktreePath)) !== canonicalCwd) return false;
730 const active = yield* projectionSnapshotQuery.getShellSnapshot();
731 const archived = yield* projectionSnapshotQuery.getArchivedShellSnapshot();
732 const projects = [...active.projects, ...archived.projects];
733 const paths = new Set<string>();
734 for (const other of [...active.threads, ...archived.threads]) {
735 if (other.id === thread.id) continue;
736 const candidate =
737 other.worktreePath ??
738 projects.find((project) => project.id === other.projectId)?.workspaceRoot;
739 if (candidate !== undefined) paths.add(candidate);
740 }
741 for (const session of yield* providerService.listSessions()) {
742 if (
743 session.threadId !== thread.id &&
744 session.status !== "closed" &&
745 session.cwd !== undefined
746 )
747 paths.add(session.cwd);
748 }
749 for (const candidate of paths) {
750 const otherCwd = yield* fileSystem
751 .realPath(candidate)
752 .pipe(
753 Effect.catch((error) =>
754 error.reason._tag === "NotFound" ? Effect.succeed(null) : Effect.fail(error),
755 ),
756 );
757 if (otherCwd === null) continue;
758 const isWithin = (parent: string, child: string) => {
759 const relative = path.relative(parent, child);
760 return (
761 relative === "" ||
762 (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`))
763 );
764 };
765 // Parent and nested owners can both have files inside the restore target.
766 if (isWithin(canonicalCwd, otherCwd) || isWithin(otherCwd, canonicalCwd)) return false;
767 }
768 return true;
769 });
770
771 const handleRevertRequested = Effect.fn("handleRevertRequested")(function* (
772 event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
773 ) {
774 const now = DateTime.formatIso(yield* DateTime.now);
775
776 const thread = yield* resolveThreadDetail(event.payload.threadId);
777 if (!thread) {
778 yield* appendRevertFailureActivity({
779 threadId: event.payload.threadId,
780 turnCount: event.payload.turnCount,
781 detail: "Thread was not found in read model.",
782 createdAt: now,
783 }).pipe(Effect.catch(() => Effect.void));
784 return;
785 }
786
787 const checkpointCwd = yield* resolveCheckpointCwd({
788 threadId: event.payload.threadId,
789 thread,
790 projects: yield* resolveThreadProjects(thread.projectId),
791 preferSessionRuntime: true,
792 }).pipe(
793 Effect.catch((error) =>
794 event.payload.restoreFiles === false ? Effect.succeed(undefined) : Effect.fail(error),
795 ),
796 );
797
798 const currentTurnCount = thread.checkpoints.reduce(
799 (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
800 0,
801 );
802
803 if (event.payload.turnCount > currentTurnCount) {
804 yield* appendRevertFailureActivity({
805 threadId: event.payload.threadId,
806 turnCount: event.payload.turnCount,
807 detail: `Checkpoint turn count ${event.payload.turnCount} exceeds current turn count ${currentTurnCount}.`,
808 createdAt: now,
809 }).pipe(Effect.catch(() => Effect.void));
810 return;
811 }
812
813 yield* providerService.assertConversationRollbackSupported(event.payload.threadId);
814
815 if (event.payload.restoreFiles !== false) {
816 if (!checkpointCwd) {
817 yield* appendRevertFailureActivity({
818 threadId: event.payload.threadId,
819 turnCount: event.payload.turnCount,
820 detail: "Checkpoint workspace is unavailable or is not a git repository.",
821 createdAt: now,
822 }).pipe(Effect.catch(() => Effect.void));
823 return;
824 }
825
826 if (!(yield* isRestoreWorkspaceIsolated(thread, checkpointCwd))) {
827 yield* appendRevertFailureActivity({
828 threadId: thread.id,
829 turnCount: event.payload.turnCount,
830 detail:
831 "File restore requires an isolated worktree. This workspace may contain changes from another thread. Rewind the conversation without restoring files instead.",
832 createdAt: now,
833 }).pipe(Effect.catch(() => Effect.void));
834 return;
835 }
836
837 const targetCheckpointRef =
838 event.payload.turnCount === 0
839 ? checkpointRefForThreadTurn(event.payload.threadId, 0)
840 : thread.checkpoints.find(
841 (checkpoint) => checkpoint.checkpointTurnCount === event.payload.turnCount,
842 )?.checkpointRef;
843
844 if (!targetCheckpointRef) {
845 yield* appendRevertFailureActivity({
846 threadId: event.payload.threadId,
847 turnCount: event.payload.turnCount,
848 detail: `Checkpoint ref for turn ${event.payload.turnCount} is unavailable in read model.`,
849 createdAt: now,
850 }).pipe(Effect.catch(() => Effect.void));
851 return;
852 }
853
854 const restored = yield* checkpointStore.restoreCheckpoint({
855 cwd: checkpointCwd,
856 checkpointRef: targetCheckpointRef,
857 fallbackToHead: event.payload.turnCount === 0,
858 });
859 if (!restored) {
860 yield* appendRevertFailureActivity({
861 threadId: event.payload.threadId,
862 turnCount: event.payload.turnCount,
863 detail: `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`,
864 createdAt: now,
865 }).pipe(Effect.catch(() => Effect.void));
866 return;
867 }
868
869 // Refresh the workspace entry index so the @-mention file picker
870 // reflects the reverted filesystem state.
871 yield* refreshWorkspaceEntries(checkpointCwd);
872 }
873
874 const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
875 if (rolledBackTurns > 0) {
876 yield* providerService.rollbackConversation({
877 threadId: event.payload.threadId,
878 numTurns: rolledBackTurns,
879 });
880 }
881
882 const staleCheckpointRefs: Array<CheckpointRef> = [];
883 for (const checkpoint of thread.checkpoints) {
884 if (checkpoint.checkpointTurnCount > event.payload.turnCount) {
885 staleCheckpointRefs.push(checkpoint.checkpointRef);
886 }
887 }
888
889 if (checkpointCwd && staleCheckpointRefs.length > 0) {
890 yield* checkpointStore.deleteCheckpointRefs({
891 cwd: checkpointCwd,
892 checkpointRefs: staleCheckpointRefs,
893 });
894 }
895
896 yield* orchestrationEngine
897 .dispatch({
898 type: "thread.revert.complete",
899 commandId: yield* serverCommandId("checkpoint-revert-complete"),
900 threadId: event.payload.threadId,
901 turnCount: event.payload.turnCount,
902 createdAt: now,
903 })
904 .pipe(
905 Effect.catch((error) =>
906 appendRevertFailureActivity({
907 threadId: event.payload.threadId,
908 turnCount: event.payload.turnCount,
909 detail: error.message,
910 createdAt: now,
911 }),
912 ),
913 Effect.asVoid,
914 );
915 });
916
917 const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) {
918 if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
919 if (event.type === "thread.turn-start-requested") pending.add(event.payload.threadId);
920 yield* ensurePreTurnBaselineFromDomainTurnStart(event);
921 return;
922 }
923
924 if (event.type === "thread.checkpoint-revert-requested") {
925 yield* handleRevertRequested(event).pipe(
926 Effect.catch((error) =>
927 Effect.flatMap(nowIso, (createdAt) =>
928 appendRevertFailureActivity({
929 threadId: event.payload.threadId,
930 turnCount: event.payload.turnCount,
931 detail: error.message,
932 createdAt,
933 }),
934 ),
935 ),
936 );
937 return;
938 }
939 });
940
941 const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
942 event: ProviderRuntimeEvent,
943 ) {
944 if (event.type === "session.exited") {
945 startedTurns.delete(event.threadId);
946 pending.delete(event.threadId);
947 return;
948 }
949
950 if (event.type === "turn.started") {
951 const turnId = toTurnId(event.turnId);
952 const activeTurnId = (yield* providerService.listSessions()).find((session) =>
953 sameId(session.threadId, event.threadId),
954 )?.activeTurnId;
955 const mayReplace = pending.has(event.threadId) && sameId(activeTurnId, turnId);
956 if (turnId !== null && (!startedTurns.has(event.threadId) || mayReplace)) {
957 startedTurns.set(event.threadId, turnId);
958 pending.delete(event.threadId);
959 }
960 yield* ensurePreTurnBaselineFromTurnStart(event);
961 return;
962 }
963
964 if (event.type === "turn.completed" || event.type === "turn.aborted") {
965 const turnId = toTurnId(event.turnId);
966 const thread = yield* resolveThreadDetail(event.threadId);
967 const startedTurnId = startedTurns.get(event.threadId);
968 const isTrackedTurn = sameId(startedTurnId, turnId);
969 if (isTrackedTurn) startedTurns.delete(event.threadId);
970 if (event.type === "turn.completed") {
971 yield* statusRefreshWorker.enqueue(event);
972 }
973 if (
974 turnId !== null &&
975 thread !== undefined &&
976 (isTrackedTurn ||
977 sameId(thread.session?.activeTurnId, turnId) ||
978 (startedTurnId === undefined && !thread.session?.activeTurnId))
979 ) {
980 pending.delete(event.threadId);
981 yield* pullRequests.refreshAfterTurn(thread.projectId);
982 }
983 if (
984 event.type === "turn.aborted" &&
985 !isTrackedTurn &&
986 !sameId(thread?.session?.activeTurnId, turnId)
987 ) {
988 return;
989 }
990 yield* captureCheckpointFromTurnCompletion(event).pipe(
991 Effect.catch((error) =>
992 Effect.flatMap(nowIso, (createdAt) =>
993 appendCaptureFailureActivity({
994 threadId: event.threadId,
995 turnId,
996 detail: error.message,
997 createdAt,
998 }).pipe(Effect.catch(() => Effect.void)),
999 ),
1000 ),
1001 );
1002 return;
1003 }
1004 });
1005
1006 const processInput = (
1007 input: ReactorInput,
1008 ): Effect.Effect<
1009 void,
1010 CheckpointStoreError | OrchestrationDispatchError | PlatformError.PlatformError,
1011 never
1012 > =>
1013 input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
1014
1015 const processInputSafely = (input: ReactorInput) =>
1016 processInput(input).pipe(
1017 Effect.catchCause((cause) => {
1018 if (Cause.hasInterruptsOnly(cause)) {
1019 return Effect.failCause(cause);
1020 }
1021 return Effect.logWarning("checkpoint reactor failed to process input", {
1022 source: input.source,
1023 eventType: input.event.type,
1024 cause: Cause.pretty(cause),
1025 });
1026 }),
1027 );
1028
1029 const worker = yield* makeDrainableWorker(processInputSafely);
1030
1031 const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () {
1032 yield* forkParked(
1033 Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
1034 if (
1035 event.type !== "thread.turn-start-requested" &&
1036 event.type !== "thread.message-sent" &&
1037 event.type !== "thread.checkpoint-revert-requested"
1038 ) {
1039 return Effect.void;
1040 }
1041 return worker.enqueue({ source: "domain", event });
1042 }),
1043 );
1044
1045 yield* forkParked(
1046 Stream.runForEach(providerService.streamEvents, (event) => {
1047 if (
1048 event.type !== "turn.started" &&
1049 event.type !== "turn.completed" &&
1050 event.type !== "turn.aborted" &&
1051 event.type !== "session.exited"
1052 ) {
1053 return Effect.void;
1054 }
1055 return worker.enqueue({ source: "runtime", event });
1056 }),
1057 );
1058 });
1059
1060 return {
1061 start,
1062 drain: worker.drain.pipe(
1063 Effect.andThen(statusRefreshWorker.drain),
1064 Effect.andThen(entryRefreshWorker.drain),
1065 ),
1066 } satisfies CheckpointReactorShape;
1067});
1068
1069export const CheckpointReactorLive = Layer.effect(CheckpointReactor, make);