Open History to see the last commit
1import {
2 CheckpointId,
3 CheckpointRef,
4 CheckpointScopeId,
5 NodeId,
6 OrchestrationV2Checkpoint,
7 OrchestrationV2CheckpointScope,
8 type OrchestrationV2AppThread,
9 type ProjectId,
10 ProviderThreadId,
11 RunId,
12 ThreadId,
13} from "@t3tools/contracts";
14import * as Cache from "effect/Cache";
15import type * as Cause from "effect/Cause";
16import * as Clock from "effect/Clock";
17import * as Context from "effect/Context";
18import * as Digest from "effect/crypto/Digest";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as Exit from "effect/Exit";
22import * as Base64Url from "effect/encoding/Base64Url";
23import * as Hex from "effect/encoding/Hex";
24import * as FileSystem from "effect/FileSystem";
25import * as KeyedLock from "@t3tools/shared/KeyedLock";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Path from "effect/Path";
29import * as Schema from "effect/Schema";
30
31import { isGitImport, parseTurnDiffFilesFromNumstat } from "../checkpointing/Diffs.ts";
32import type { CheckpointStoreError } from "../checkpointing/Errors.ts";
33import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
34import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
35import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts";
36
37const CHECKPOINT_REFS_PREFIX = "refs/t3/orchestration-v2/checkpoints";
38const ROOT_CHECKPOINT_SCOPE_NAME = "root";
39// The provider turn waits on the baseline, so a workspace too slow for this starts without one.
40// It bounds a copy and the snapshot each; waiting on the lock lets a capture finish the same ref.
41const BASELINE_CAPTURE_BUDGET = "5 seconds";
42// Git processes are already capped server-wide; this keeps one thread from taking every slot.
43const REPOSITORY_SCOPE_CONCURRENCY = 6;
44
45export class CheckpointRootScopePrepareError extends Schema.TaggedError<CheckpointRootScopePrepareError>()(
46 "CheckpointRootScopePrepareError",
47 {
48 threadId: ThreadId,
49 runId: RunId,
50 cause: Schema.Defect(),
51 },
52) {
53 override get message(): string {
54 return `Failed to prepare root checkpoint scope for run ${this.runId}.`;
55 }
56}
57
58export class CheckpointBaselineCaptureError extends Schema.TaggedError<CheckpointBaselineCaptureError>()(
59 "CheckpointBaselineCaptureError",
60 {
61 scopeId: CheckpointScopeId,
62 ordinalWithinScope: Schema.Number,
63 cause: Schema.Defect(),
64 },
65) {
66 override get message(): string {
67 return `Failed to capture checkpoint baseline ${this.ordinalWithinScope} for scope ${this.scopeId}.`;
68 }
69}
70
71export class CheckpointCaptureError extends Schema.TaggedError<CheckpointCaptureError>()(
72 "CheckpointCaptureError",
73 {
74 scopeId: CheckpointScopeId,
75 parentCheckpointId: Schema.optional(CheckpointId),
76 cause: Schema.Defect(),
77 },
78) {
79 override get message(): string {
80 return `Failed to capture checkpoint for scope ${this.scopeId}.`;
81 }
82}
83
84export class CheckpointRestoreError extends Schema.TaggedError<CheckpointRestoreError>()(
85 "CheckpointRestoreError",
86 {
87 scopeId: CheckpointScopeId,
88 checkpointId: CheckpointId,
89 cause: Schema.Defect(),
90 },
91) {
92 override get message(): string {
93 return `Failed to restore checkpoint ${this.checkpointId} for scope ${this.scopeId}.`;
94 }
95}
96
97export class CheckpointDeleteStaleRefsError extends Schema.TaggedError<CheckpointDeleteStaleRefsError>()(
98 "CheckpointDeleteStaleRefsError",
99 {
100 scopeId: CheckpointScopeId,
101 checkpointIds: Schema.Array(CheckpointId),
102 cause: Schema.Defect(),
103 },
104) {
105 override get message(): string {
106 return `Failed to delete stale checkpoint refs for scope ${this.scopeId}.`;
107 }
108}
109
110export const CheckpointServiceV2Error = Schema.Union([
111 CheckpointRootScopePrepareError,
112 CheckpointBaselineCaptureError,
113 CheckpointCaptureError,
114 CheckpointRestoreError,
115 CheckpointDeleteStaleRefsError,
116]);
117export type CheckpointServiceV2Error = typeof CheckpointServiceV2Error.Type;
118
119const isCheckpointRestoreError = Schema.is(CheckpointRestoreError);
120
121/** Per scope, the other scopes' folders inside its own: relative, `/`-separated. */
122type NestedScopePaths = ReadonlyMap<CheckpointScopeId, ReadonlyArray<string>>;
123
124/**
125 * A scope leaves a folder that has its own scope to that scope, so a clone inside another checkout
126 * is not also recorded as that checkout's gitlink. A submodule stays: its gitlink is the commit
127 * its repository pins, which belongs to that repository's changes. Real paths, since a folder can
128 * be reached through a symlink.
129 */
130export const nestedScopePaths = Effect.fn("CheckpointService.nestedScopePaths")(function* (
131 scopes: ReadonlyArray<Pick<OrchestrationV2CheckpointScope, "id" | "cwd">>,
132) {
133 const fileSystem = yield* FileSystem.FileSystem;
134 const path = yield* Path.Path;
135 const resolved = yield* Effect.forEach(
136 scopes,
137 (scope) =>
138 fileSystem.realPath(scope.cwd).pipe(
139 Effect.orElseSucceed(() => path.resolve(scope.cwd)),
140 Effect.map((cwd) => ({ id: scope.id, cwd })),
141 ),
142 { concurrency: REPOSITORY_SCOPE_CONCURRENCY },
143 );
144 const nested = new Map<CheckpointScopeId, ReadonlyArray<string>>();
145 for (const outer of resolved) {
146 const inside = resolved.flatMap((inner) => {
147 const relative = path.relative(outer.cwd, inner.cwd);
148 return relative === "" ||
149 relative === ".." ||
150 relative.startsWith(`..${path.sep}`) ||
151 path.isAbsolute(relative)
152 ? []
153 : [relative.split(path.sep).join("/")];
154 });
155 if (inside.length === 0) continue;
156 const submodules = new Set(
157 WorkspaceFolders.parseGitmodulesPaths(
158 yield* fileSystem
159 .readFileString(path.join(outer.cwd, ".gitmodules"))
160 .pipe(Effect.orElseSucceed(() => "")),
161 ),
162 );
163 const excluded = [...new Set(inside)].filter((relative) => !submodules.has(relative));
164 if (excluded.length > 0) nested.set(outer.id, excluded);
165 }
166 return nested as NestedScopePaths;
167});
168
169export interface CheckpointServiceV2Shape {
170 readonly prepareRootRunScope: (input: {
171 readonly threadId: ThreadId;
172 readonly runId: RunId;
173 readonly rootNodeId: NodeId;
174 readonly providerThreadId: ProviderThreadId;
175 readonly cwd: string;
176 readonly createdAt: DateTime.Utc;
177 }) => Effect.Effect<OrchestrationV2CheckpointScope, CheckpointServiceV2Error>;
178 /**
179 * One scope per tracked Git folder the thread reaches now, under its root scope. Ids depend only
180 * on the thread and the tracked path, so every run names the same scope. Empty when the folders
181 * cannot be read: the thread then runs with its root scope alone.
182 */
183 readonly repositoryScopes: (input: {
184 readonly rootScope: OrchestrationV2CheckpointScope;
185 readonly projectId: ProjectId;
186 readonly worktreePath: string | null;
187 }) => Effect.Effect<ReadonlyArray<OrchestrationV2CheckpointScope>>;
188 /** As `repositoryScopes`, but null when the folders cannot be read: a rewind must not guess. */
189 readonly repositoryScopesIfReadable: (input: {
190 readonly rootScope: OrchestrationV2CheckpointScope;
191 readonly projectId: ProjectId;
192 readonly worktreePath: string | null;
193 }) => Effect.Effect<ReadonlyArray<OrchestrationV2CheckpointScope> | null>;
194 readonly nestedScopePaths: (
195 scopes: ReadonlyArray<Pick<OrchestrationV2CheckpointScope, "id" | "cwd">>,
196 ) => Effect.Effect<NestedScopePaths>;
197 readonly captureBaseline: (input: {
198 readonly scope: OrchestrationV2CheckpointScope;
199 readonly ordinalWithinScope: number;
200 /** An earlier checkpoint that still holds this baseline: no run since it has run. */
201 readonly sourceOrdinalWithinScope?: number | undefined;
202 /**
203 * Also baselines the tracked repositories this thread reaches, a few at a time and all within
204 * one budget, so many repositories delay a turn no longer than one. A repository that misses
205 * the budget has no baseline this turn.
206 */
207 readonly thread?: Pick<OrchestrationV2AppThread, "projectId" | "worktreePath">;
208 }) => Effect.Effect<void, CheckpointServiceV2Error>;
209 readonly materializeBaselineCheckpoint: (input: {
210 readonly scope: OrchestrationV2CheckpointScope;
211 readonly ordinalWithinScope: number;
212 /** The run materializing the baseline: its root node, and when it was requested. */
213 readonly nodeId: NodeId;
214 readonly capturedAt: DateTime.Utc;
215 /** Records a missing checkpoint without touching git, for side chats sharing a parent's worktree. */
216 readonly forceMissing?: boolean;
217 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
218 readonly capture: (input: {
219 readonly scope: OrchestrationV2CheckpointScope;
220 readonly runId: RunId | null;
221 readonly nodeId: NodeId;
222 readonly ordinalWithinScope: number;
223 readonly appRunOrdinal: number | null;
224 readonly capturedAt: DateTime.Utc;
225 readonly forceMissing?: boolean;
226 readonly excludePaths?: ReadonlyArray<string>;
227 /** `capturesSoFar` from before an earlier wait on the folder's lock, when there was one. */
228 readonly capturesBeforeLock?: number;
229 }) => Effect.Effect<OrchestrationV2Checkpoint, CheckpointServiceV2Error>;
230 /** How many captures have finished in a folder, for a caller that waits on it before `capture`. */
231 readonly capturesSoFar: (cwd: string) => Effect.Effect<number>;
232 /**
233 * A tracked repository's checkpoint for a run, with the baseline before it unless that is
234 * already recorded. None when the run left the repository as it found it, which costs one
235 * status and writes nothing: a project can track dozens of repositories a turn never touches.
236 */
237 readonly captureRepository: (input: {
238 readonly scope: OrchestrationV2CheckpointScope;
239 readonly runId: RunId;
240 readonly nodeId: NodeId;
241 readonly ordinalWithinScope: number;
242 readonly capturedAt: DateTime.Utc;
243 readonly baselineCapturedAt: DateTime.Utc;
244 readonly baselineRecorded: boolean;
245 readonly excludePaths?: ReadonlyArray<string>;
246 }) => Effect.Effect<
247 Option.Option<{
248 readonly baseline: OrchestrationV2Checkpoint | null;
249 readonly checkpoint: OrchestrationV2Checkpoint;
250 }>,
251 CheckpointServiceV2Error
252 >;
253 /**
254 * Restores a thread's folders together. Every snapshot is checked before a folder changes and
255 * each folder is snapshotted first, so a restore that fails puts back the ones already
256 * restored: a rewind changes all of them or none.
257 */
258 readonly restore: (input: {
259 readonly targets: ReadonlyArray<{
260 readonly scope: Pick<OrchestrationV2CheckpointScope, "id" | "cwd">;
261 readonly checkpoint: Pick<OrchestrationV2Checkpoint, "ordinalWithinScope" | "ref" | "status">;
262 }>;
263 /** Every folder of the thread with checkpoints of its own; a restore leaves the others' alone. */
264 readonly scopes: ReadonlyArray<Pick<OrchestrationV2CheckpointScope, "id" | "cwd">>;
265 }) => Effect.Effect<void, CheckpointServiceV2Error>;
266 readonly deleteStaleRefs: (input: {
267 readonly scope: OrchestrationV2CheckpointScope;
268 readonly checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>;
269 }) => Effect.Effect<void, CheckpointServiceV2Error>;
270 /**
271 * Drops the snapshots the thread's tracked repositories took at these run ordinals. A rollback
272 * reuses the ordinals, and a snapshot left behind would pass for a later turn's baseline. Most
273 * have no checkpoint record, so they are found by ordinal. A failure is logged, not raised.
274 */
275 readonly discardRepositorySnapshots: (input: {
276 readonly rootScope: OrchestrationV2CheckpointScope;
277 readonly thread: Pick<OrchestrationV2AppThread, "projectId" | "worktreePath">;
278 readonly ordinals: ReadonlyArray<number>;
279 }) => Effect.Effect<void>;
280}
281
282export class CheckpointServiceV2 extends Context.Service<
283 CheckpointServiceV2,
284 CheckpointServiceV2Shape
285>()("t3/orchestration-v2/CheckpointService/CheckpointServiceV2") {}
286
287const scopeRef = Effect.fnUntraced(function* (scopeId: CheckpointScopeId, name: string) {
288 const crypto = yield* Digest.Digest;
289 const digest = yield* crypto
290 .digest(Digest.sha256, new TextEncoder().encode(scopeId))
291 .pipe(Effect.orDie);
292 const scopeKey = Hex.encode(digest).slice(0, 32);
293 return CheckpointRef.make(`${CHECKPOINT_REFS_PREFIX}/${Base64Url.encode(scopeKey)}/${name}`);
294});
295
296export const checkpointRefForScopeOrdinal = Effect.fn("checkpointRefForScopeOrdinal")(
297 (input: { readonly scopeId: CheckpointScopeId; readonly ordinalWithinScope: number }) =>
298 scopeRef(input.scopeId, `ordinal/${input.ordinalWithinScope}`),
299);
300
301function checkpointIdForScopeOrdinal(
302 idAllocator: IdAllocator.IdAllocatorV2["Service"],
303 input: {
304 readonly scopeId: CheckpointScopeId;
305 readonly ordinalWithinScope: number;
306 },
307) {
308 return idAllocator.allocate.checkpoint({
309 checkpointScopeId: input.scopeId,
310 name: String(input.ordinalWithinScope),
311 });
312}
313
314const makeRootRunScope = Effect.fn("CheckpointService.makeRootRunScope")(function* (input: {
315 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
316 readonly threadId: ThreadId;
317 readonly runId: RunId;
318 readonly rootNodeId: NodeId;
319 readonly providerThreadId: ProviderThreadId;
320 readonly cwd: string;
321 readonly createdAt: DateTime.Utc;
322}) {
323 const scopeId = yield* input.idAllocator.allocate.checkpointScope({
324 threadId: input.threadId,
325 name: ROOT_CHECKPOINT_SCOPE_NAME,
326 });
327 return {
328 id: scopeId,
329 threadId: input.threadId,
330 runId: input.runId,
331 nodeId: input.rootNodeId,
332 parentScopeId: null,
333 providerThreadId: input.providerThreadId,
334 kind: "root_run",
335 ordinalWithinParent: 0,
336 advancesAppRunCount: true,
337 cwd: input.cwd,
338 createdAt: input.createdAt,
339 } satisfies OrchestrationV2CheckpointScope;
340});
341
342function makeCheckpoint(input: {
343 readonly id: CheckpointId;
344 readonly scope: OrchestrationV2CheckpointScope;
345 readonly runId: RunId | null;
346 readonly nodeId: NodeId;
347 readonly parentCheckpointId: CheckpointId | null;
348 readonly ordinalWithinScope: number;
349 readonly appRunOrdinal: number | null;
350 readonly ref: CheckpointRef;
351 readonly status: OrchestrationV2Checkpoint["status"];
352 readonly files: OrchestrationV2Checkpoint["files"];
353 readonly capturedAt: DateTime.Utc;
354}): OrchestrationV2Checkpoint {
355 return {
356 id: input.id,
357 threadId: input.scope.threadId,
358 scopeId: input.scope.id,
359 runId: input.runId,
360 nodeId: input.nodeId,
361 parentCheckpointId: input.parentCheckpointId,
362 ordinalWithinScope: input.ordinalWithinScope,
363 appRunOrdinal: input.appRunOrdinal,
364 ref: input.ref,
365 status: input.status,
366 files: input.files,
367 capturedAt: input.capturedAt,
368 };
369}
370
371export const layer: Layer.Layer<
372 CheckpointServiceV2,
373 never,
374 | CheckpointStore.CheckpointStore
375 | Digest.Digest
376 | IdAllocator.IdAllocatorV2
377 | WorkspaceFolders.WorkspaceFolders
378 | FileSystem.FileSystem
379 | Path.Path
380> = Layer.effect(
381 CheckpointServiceV2,
382 Effect.gen(function* () {
383 const checkpointStore = yield* CheckpointStore.CheckpointStore;
384 const workspaceFolders = yield* WorkspaceFolders.WorkspaceFolders;
385 const fileSystem = yield* FileSystem.FileSystem;
386 const path = yield* Path.Path;
387 const crypto = yield* Digest.Digest;
388 const checkpointRefFor = (input: Parameters<typeof checkpointRefForScopeOrdinal>[0]) =>
389 checkpointRefForScopeOrdinal(input).pipe(Effect.provideService(Digest.Digest, crypto));
390 const idAllocator = yield* IdAllocator.IdAllocatorV2;
391 const workspaceLocks = yield* KeyedLock.make<string>();
392 const withWorkspaceLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
393 workspaceLocks.withLock(cwd, effect);
394
395 const captureTimeouts = yield* Cache.make<string, number>({
396 capacity: 128,
397 lookup: () => Effect.succeed(0),
398 });
399 // Unlike the streak, a success never rewinds the count, so a waiter can order outcomes. A
400 // baseline running out of its short budget is not a post-turn capture timing out.
401 const lastCaptures = new Map<string, { readonly count: number; readonly timedOut: boolean }>();
402 const noteCapture = (cwd: string, timedOut: boolean) =>
403 Effect.sync(() => {
404 lastCaptures.set(cwd, { count: (lastCaptures.get(cwd)?.count ?? 0) + 1, timedOut });
405 });
406 const capturesSoFar = (cwd: string) => lastCaptures.get(cwd)?.count ?? 0;
407 const withCaptureLock = Effect.fn("CheckpointService.withCaptureLock")(function* <A, E, R>(
408 cwd: string,
409 capturesBeforeLock: number | undefined,
410 effect: (capturesBeforeLock: number) => Effect.Effect<A, E, R>,
411 ) {
412 return yield* withWorkspaceLock(cwd, effect(capturesBeforeLock ?? capturesSoFar(cwd)));
413 });
414 // Both callers hold the workspace lock; post-turn captures always probe for recovery.
415 const captureWorkspaceCheckpoint = Effect.fn("CheckpointService.captureWorkspaceCheckpoint")(
416 function* (input: CheckpointStore.CaptureCheckpointInput, baseline = false) {
417 const capture = checkpointStore.captureCheckpoint(input);
418 const bounded: Effect.Effect<
419 CheckpointStore.CheckpointRange | null,
420 CheckpointStoreError | Cause.TimeoutError
421 > = baseline ? capture.pipe(Effect.timeout(BASELINE_CAPTURE_BUDGET)) : capture;
422 return yield* bounded.pipe(
423 Effect.tap(() =>
424 Effect.andThen(
425 Cache.invalidate(captureTimeouts, input.cwd),
426 noteCapture(input.cwd, false),
427 ),
428 ),
429 Effect.tapError((error) =>
430 error._tag === "VcsProcessTimeoutError" || error._tag === "TimeoutError"
431 ? Effect.gen(function* () {
432 const previous = yield* Cache.get(captureTimeouts, input.cwd);
433 yield* Cache.set(captureTimeouts, input.cwd, previous + 1);
434 yield* noteCapture(input.cwd, !baseline);
435 })
436 : Effect.andThen(
437 Cache.invalidate(captureTimeouts, input.cwd),
438 noteCapture(input.cwd, false),
439 ),
440 ),
441 );
442 },
443 );
444
445 // A failed probe is an operational error, not proof that the workspace has no repository.
446 const probeRepository = (scope: OrchestrationV2CheckpointScope) =>
447 checkpointStore.isGitRepository(scope.cwd).pipe(
448 Effect.map((isRepository) =>
449 isRepository ? ("repository" as const) : ("missing" as const),
450 ),
451 Effect.catch((cause) =>
452 Effect.logWarning("orchestration V2 checkpoint repository probe failed", {
453 scopeId: scope.id,
454 cause: String(cause),
455 }).pipe(Effect.as("error" as const)),
456 ),
457 );
458
459 // What this process knows of each repository scope's folder as of a run ordinal. With
460 // `cleanHead` the folder matched that commit exactly, and no snapshot ref need exist until a
461 // turn changes it; null means the ordinal's ref holds its state. Unknown after a restart.
462 const repositoryStates = new Map<
463 CheckpointScopeId,
464 {
465 readonly ordinal: number;
466 readonly cleanHead: string | null;
467 /** Epoch seconds. */
468 readonly seenAt: number;
469 }
470 >();
471 const noteRepositoryState = Effect.fnUntraced(function* (
472 scopeId: CheckpointScopeId,
473 state: { readonly ordinal: number; readonly cleanHead: string | null },
474 ) {
475 const seenAt = Math.floor((yield* Clock.currentTimeMillis) / 1000);
476 repositoryStates.set(scopeId, { ...state, seenAt });
477 });
478
479 const skipBaselineAfterRepeatedTimeouts = Effect.fnUntraced(function* (input: {
480 readonly scope: OrchestrationV2CheckpointScope;
481 readonly ordinalWithinScope: number;
482 }) {
483 const timeouts = yield* Cache.getOption(captureTimeouts, input.scope.cwd);
484 if (Option.isNone(timeouts) || timeouts.value < 2) return false;
485 yield* Effect.logWarning(
486 "orchestration V2 checkpoint baseline skipped after repeated capture timeouts",
487 { scopeId: input.scope.id, ordinalWithinScope: input.ordinalWithinScope },
488 );
489 return true;
490 });
491
492 const captureScopeBaselineLocked = (input: {
493 readonly scope: OrchestrationV2CheckpointScope;
494 readonly ordinalWithinScope: number;
495 readonly sourceOrdinalWithinScope?: number | undefined;
496 readonly excludePaths: ReadonlyArray<string> | undefined;
497 }) =>
498 withWorkspaceLock(
499 input.scope.cwd,
500 Effect.gen(function* () {
501 if (!(yield* checkpointStore.isGitRepository(input.scope.cwd))) {
502 return;
503 }
504
505 const checkpointRef = yield* checkpointRefFor({
506 scopeId: input.scope.id,
507 ordinalWithinScope: input.ordinalWithinScope,
508 });
509 const exists = yield* checkpointStore.hasCheckpointRef({
510 cwd: input.scope.cwd,
511 checkpointRef,
512 });
513 if (exists) {
514 return;
515 }
516 const copied =
517 input.sourceOrdinalWithinScope !== undefined &&
518 (yield* checkpointStore
519 .copyCheckpointRef({
520 cwd: input.scope.cwd,
521 fromCheckpointRef: yield* checkpointRefFor({
522 scopeId: input.scope.id,
523 ordinalWithinScope: input.sourceOrdinalWithinScope,
524 }),
525 toCheckpointRef: checkpointRef,
526 })
527 .pipe(
528 Effect.timeout(BASELINE_CAPTURE_BUDGET),
529 Effect.orElseSucceed(() => false),
530 ));
531 if (copied) return;
532
533 if (yield* skipBaselineAfterRepeatedTimeouts(input)) return;
534
535 yield* captureWorkspaceCheckpoint(
536 {
537 cwd: input.scope.cwd,
538 checkpointRef,
539 ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }),
540 },
541 true,
542 ).pipe(
543 Effect.catchTags({
544 VcsUnsupportedOperationError: () => Effect.void,
545 }),
546 );
547 }),
548 ).pipe(
549 Effect.mapError(
550 (cause) =>
551 new CheckpointBaselineCaptureError({
552 scopeId: input.scope.id,
553 ordinalWithinScope: input.ordinalWithinScope,
554 cause,
555 }),
556 ),
557 );
558
559 // With no ref to copy, the skip needs no lock: waiting on another thread's capture only to
560 // learn it would hold this turn start for that capture's whole timeout.
561 const captureScopeBaseline = Effect.fnUntraced(function* (
562 input: Parameters<typeof captureScopeBaselineLocked>[0],
563 ) {
564 if (
565 input.sourceOrdinalWithinScope === undefined &&
566 (yield* skipBaselineAfterRepeatedTimeouts(input))
567 ) {
568 return;
569 }
570 return yield* captureScopeBaselineLocked(input);
571 });
572
573 // A clean repository is only noted, which costs one status. One with uncommitted work is
574 // snapshotted now, before the turn can change it.
575 const noteRepositoryBaseline = (input: {
576 readonly scope: OrchestrationV2CheckpointScope;
577 readonly ordinalWithinScope: number;
578 readonly excludePaths: ReadonlyArray<string> | undefined;
579 }) =>
580 withWorkspaceLock(
581 input.scope.cwd,
582 Effect.gen(function* () {
583 const { cwd, id } = input.scope;
584 // Usually the state its last run ended with, so most turns start without asking Git.
585 if (repositoryStates.get(id)?.ordinal === input.ordinalWithinScope) return;
586 const cleanHead = yield* checkpointStore.resolveCleanHead(cwd);
587 if (cleanHead === null) {
588 const checkpointRef = yield* checkpointRefFor({
589 scopeId: id,
590 ordinalWithinScope: input.ordinalWithinScope,
591 });
592 if (!(yield* checkpointStore.hasCheckpointRef({ cwd, checkpointRef }))) {
593 yield* checkpointStore.captureCheckpoint({
594 cwd,
595 checkpointRef,
596 ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }),
597 });
598 }
599 }
600 yield* noteRepositoryState(id, { ordinal: input.ordinalWithinScope, cleanHead });
601 }),
602 );
603
604 const materializeBaselineCheckpoint: CheckpointServiceV2Shape["materializeBaselineCheckpoint"] =
605 (input) =>
606 withWorkspaceLock(
607 input.scope.cwd,
608 Effect.gen(function* () {
609 const checkpointRef = yield* checkpointRefFor({
610 scopeId: input.scope.id,
611 ordinalWithinScope: input.ordinalWithinScope,
612 });
613 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
614 scopeId: input.scope.id,
615 ordinalWithinScope: input.ordinalWithinScope,
616 });
617 const repository =
618 input.forceMissing === true ? "missing" : yield* probeRepository(input.scope);
619 const status =
620 repository === "repository"
621 ? yield* checkpointStore
622 .hasCheckpointRef({
623 cwd: input.scope.cwd,
624 checkpointRef,
625 })
626 .pipe(
627 Effect.map((exists) => (exists ? ("ready" as const) : ("missing" as const))),
628 Effect.catch((cause) =>
629 Effect.logWarning("orchestration V2 baseline ref lookup failed", {
630 scopeId: input.scope.id,
631 checkpointRef,
632 cause: String(cause),
633 }).pipe(Effect.as("error" as const)),
634 ),
635 )
636 : repository;
637 return makeCheckpoint({
638 id: checkpointId,
639 scope: input.scope,
640 runId: null,
641 nodeId: input.nodeId,
642 parentCheckpointId: null,
643 ordinalWithinScope: input.ordinalWithinScope,
644 appRunOrdinal: null,
645 ref: checkpointRef,
646 status,
647 files: [],
648 capturedAt: input.capturedAt,
649 });
650 }),
651 ).pipe(
652 Effect.mapError(
653 (cause) =>
654 new CheckpointCaptureError({
655 scopeId: input.scope.id,
656 cause,
657 }),
658 ),
659 );
660
661 const captureSummarized = (
662 input: Parameters<CheckpointServiceV2Shape["capture"]>[0] & {
663 /** The commit a clean folder matches, which then needs no staging to snapshot. */
664 readonly cleanHead?: string;
665 },
666 ) =>
667 withCaptureLock(input.scope.cwd, input.capturesBeforeLock, (capturesBeforeLock) =>
668 Effect.gen(function* () {
669 const checkpointId = yield* checkpointIdForScopeOrdinal(idAllocator, {
670 scopeId: input.scope.id,
671 ordinalWithinScope: input.ordinalWithinScope,
672 });
673 const parentCheckpointId =
674 input.ordinalWithinScope > 0
675 ? yield* checkpointIdForScopeOrdinal(idAllocator, {
676 scopeId: input.scope.id,
677 ordinalWithinScope: input.ordinalWithinScope - 1,
678 })
679 : null;
680 const checkpointRef = yield* checkpointRefFor({
681 scopeId: input.scope.id,
682 ordinalWithinScope: input.ordinalWithinScope,
683 });
684 const previousCheckpointRef = yield* checkpointRefFor({
685 scopeId: input.scope.id,
686 ordinalWithinScope: Math.max(0, input.ordinalWithinScope - 1),
687 });
688
689 const repository =
690 input.forceMissing === true ? "missing" : yield* probeRepository(input.scope);
691 if (repository !== "repository") {
692 return {
693 checkpoint: makeCheckpoint({
694 id: checkpointId,
695 scope: input.scope,
696 runId: input.runId,
697 nodeId: input.nodeId,
698 parentCheckpointId,
699 ordinalWithinScope: input.ordinalWithinScope,
700 appRunOrdinal: input.appRunOrdinal,
701 ref: checkpointRef,
702 status: repository,
703 files: [],
704 capturedAt: input.capturedAt,
705 }),
706 summaryFailed: false,
707 };
708 }
709
710 // Threads sharing a folder queue on its lock. One that waited out another's timeout
711 // would only time out again while its own queued messages wait behind it.
712 const lastCapture = lastCaptures.get(input.scope.cwd);
713 const timedOutWhileWaiting =
714 input.cleanHead === undefined &&
715 lastCapture !== undefined &&
716 lastCapture.timedOut &&
717 lastCapture.count > capturesBeforeLock;
718 // `range` is undefined when the capture did not read the previous checkpoint itself.
719 type Captured = {
720 readonly status: "ready" | "missing" | "error";
721 readonly range?: CheckpointStore.CheckpointRange | null;
722 };
723 const snapshot: Effect.Effect<Captured, CheckpointStoreError | Cause.TimeoutError> =
724 input.cleanHead === undefined
725 ? captureWorkspaceCheckpoint({
726 cwd: input.scope.cwd,
727 checkpointRef,
728 ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}),
729 ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }),
730 }).pipe(Effect.map((range) => ({ status: "ready" as const, range })))
731 : checkpointStore
732 .captureHeadCheckpoint({
733 cwd: input.scope.cwd,
734 checkpointRef,
735 head: input.cleanHead,
736 })
737 .pipe(Effect.as({ status: "ready" as const }));
738 const captured: Captured = timedOutWhileWaiting
739 ? yield* Effect.logWarning(
740 "orchestration V2 checkpoint capture skipped after a capture timed out in its folder",
741 { scopeId: input.scope.id, checkpointRef },
742 ).pipe(Effect.as({ status: "error" as const }))
743 : yield* snapshot.pipe(
744 Effect.catchTags({
745 VcsUnsupportedOperationError: () =>
746 Effect.succeed({ status: "missing" as const }),
747 }),
748 Effect.catch((cause) =>
749 Effect.logWarning("orchestration V2 checkpoint capture failed", {
750 scopeId: input.scope.id,
751 checkpointRef,
752 cause: String(cause),
753 }).pipe(Effect.as({ status: "error" as const })),
754 ),
755 );
756
757 if (captured.status !== "ready") {
758 return {
759 checkpoint: makeCheckpoint({
760 id: checkpointId,
761 scope: input.scope,
762 runId: input.runId,
763 nodeId: input.nodeId,
764 parentCheckpointId,
765 ordinalWithinScope: input.ordinalWithinScope,
766 appRunOrdinal: input.appRunOrdinal,
767 ref: checkpointRef,
768 status: captured.status,
769 files: [],
770 capturedAt: input.capturedAt,
771 }),
772 summaryFailed: false,
773 };
774 }
775
776 const { range } = captured;
777 const previousExists =
778 range !== undefined
779 ? range !== null
780 : yield* checkpointStore
781 .hasCheckpointRef({
782 cwd: input.scope.cwd,
783 checkpointRef: previousCheckpointRef,
784 })
785 .pipe(
786 Effect.catch((cause) =>
787 Effect.logWarning("orchestration V2 previous checkpoint ref lookup failed", {
788 scopeId: input.scope.id,
789 checkpointRef: previousCheckpointRef,
790 cause: String(cause),
791 }).pipe(Effect.as(false)),
792 ),
793 );
794 const refs = {
795 cwd: input.scope.cwd,
796 fromCheckpointRef: previousCheckpointRef,
797 toCheckpointRef: checkpointRef,
798 ...(range === undefined || range === null ? {} : { range }),
799 };
800 // A pull or rebase can change thousands of files the turn did not write.
801 const files =
802 !previousExists || range?.unchanged === true
803 ? []
804 : yield* Effect.all([
805 checkpointStore.diffCheckpoints({
806 ...refs,
807 fallbackFromToHead: false,
808 ignoreWhitespace: false,
809 format: "numstat",
810 // An earlier checkpoint can predate a nested folder getting its own scope.
811 ...(input.excludePaths === undefined
812 ? {}
813 : { excludePaths: input.excludePaths }),
814 }),
815 checkpointStore.listAuthoredPaths(refs).pipe(
816 Effect.catch((cause) =>
817 Effect.logWarning("orchestration V2 checkpoint authored paths failed", {
818 scopeId: input.scope.id,
819 checkpointRef,
820 cause: String(cause),
821 }).pipe(Effect.as(null)),
822 ),
823 ),
824 ]).pipe(
825 Effect.map(([diff, authoredPaths]) =>
826 parseTurnDiffFilesFromNumstat(diff)
827 .filter((file) => !isGitImport(file, authoredPaths))
828 .map((file) => ({
829 path: file.path,
830 kind: "modified",
831 additions: file.additions,
832 deletions: file.deletions,
833 })),
834 ),
835 Effect.catch((cause) =>
836 Effect.logWarning("orchestration V2 checkpoint diff summary failed", {
837 scopeId: input.scope.id,
838 checkpointRef,
839 cause: String(cause),
840 }).pipe(Effect.as(null)),
841 ),
842 );
843
844 return {
845 checkpoint: makeCheckpoint({
846 id: checkpointId,
847 scope: input.scope,
848 runId: input.runId,
849 nodeId: input.nodeId,
850 parentCheckpointId,
851 ordinalWithinScope: input.ordinalWithinScope,
852 appRunOrdinal: input.appRunOrdinal,
853 ref: checkpointRef,
854 status: "ready",
855 files: files ?? [],
856 capturedAt: input.capturedAt,
857 }),
858 summaryFailed: files === null,
859 };
860 }),
861 ).pipe(
862 Effect.mapError(
863 (cause) =>
864 new CheckpointCaptureError({
865 scopeId: input.scope.id,
866 cause,
867 }),
868 ),
869 );
870
871 const capture = (input: Parameters<typeof captureSummarized>[0]) =>
872 captureSummarized(input).pipe(Effect.map((captured) => captured.checkpoint));
873
874 const resolveNestedScopePaths: CheckpointServiceV2Shape["nestedScopePaths"] = (scopes) =>
875 nestedScopePaths(scopes).pipe(
876 Effect.provideService(FileSystem.FileSystem, fileSystem),
877 Effect.provideService(Path.Path, path),
878 );
879
880 const restore: CheckpointServiceV2Shape["restore"] = Effect.fn("CheckpointService.restore")(
881 function* (input) {
882 type Target = (typeof input.targets)[number];
883 const failed = (target: Target, cause: unknown) =>
884 isCheckpointRestoreError(cause)
885 ? Effect.succeed(cause)
886 : Effect.map(
887 checkpointIdForScopeOrdinal(idAllocator, {
888 scopeId: target.scope.id,
889 ordinalWithinScope: target.checkpoint.ordinalWithinScope,
890 }),
891 (checkpointId) =>
892 new CheckpointRestoreError({ scopeId: target.scope.id, checkpointId, cause }),
893 );
894 for (const target of input.targets) {
895 if (target.checkpoint.status !== "ready") {
896 return yield* Effect.flip(
897 failed(target, `Checkpoint status is ${target.checkpoint.status}.`),
898 );
899 }
900 const exists = yield* checkpointStore
901 .hasCheckpointRef({ cwd: target.scope.cwd, checkpointRef: target.checkpoint.ref })
902 .pipe(Effect.catch((cause) => Effect.flip(failed(target, cause))));
903 if (!exists) return yield* Effect.flip(failed(target, "Checkpoint ref is unavailable."));
904 }
905 const nested = yield* resolveNestedScopePaths(input.scopes);
906 const snapshots: Array<Omit<CheckpointStore.RestoreCheckpointInput, "fallbackToHead">> = [];
907 // A snapshot that could not be put back is the only copy of the folder's pre-rewind state.
908 const unrecovered = new Set<string>();
909 yield* Effect.forEach(
910 input.targets,
911 (target) =>
912 withWorkspaceLock(
913 target.scope.cwd,
914 Effect.gen(function* () {
915 const excludePaths = nested.get(target.scope.id);
916 const folder = {
917 cwd: target.scope.cwd,
918 ...(excludePaths === undefined ? {} : { excludePaths }),
919 };
920 const preRewindRef = yield* scopeRef(target.scope.id, "pre-rewind").pipe(
921 Effect.provideService(Digest.Digest, crypto),
922 );
923 // One an earlier failed rewind left is still the only copy of how the folder was.
924 const kept = yield* checkpointStore.hasCheckpointRef({
925 cwd: target.scope.cwd,
926 checkpointRef: preRewindRef,
927 });
928 if (!kept) {
929 yield* checkpointStore.captureCheckpoint({
930 ...folder,
931 checkpointRef: preRewindRef,
932 });
933 }
934 snapshots.push({ ...folder, checkpointRef: preRewindRef });
935 // What this process knew of the folder no longer holds.
936 repositoryStates.delete(target.scope.id);
937 const restored = yield* checkpointStore.restoreCheckpoint({
938 ...folder,
939 checkpointRef: target.checkpoint.ref,
940 fallbackToHead: false,
941 });
942 if (!restored) return yield* Effect.fail("Checkpoint ref is unavailable.");
943 }),
944 ).pipe(Effect.catch((cause) => Effect.flip(failed(target, cause)))),
945 { discard: true },
946 ).pipe(
947 Effect.onError(() =>
948 Effect.forEach(
949 snapshots.toReversed(),
950 (snapshot) =>
951 withWorkspaceLock(snapshot.cwd, checkpointStore.restoreCheckpoint(snapshot)).pipe(
952 Effect.catchCause((cause) => {
953 unrecovered.add(snapshot.checkpointRef);
954 return Effect.logWarning("A failed rewind left a folder partly restored", {
955 cwd: snapshot.cwd,
956 preRewindRef: snapshot.checkpointRef,
957 cause,
958 });
959 }),
960 ),
961 { discard: true },
962 ),
963 ),
964 Effect.ensuring(
965 Effect.suspend(() =>
966 Effect.forEach(
967 snapshots.filter((snapshot) => !unrecovered.has(snapshot.checkpointRef)),
968 (snapshot) =>
969 checkpointStore
970 .deleteCheckpointRefs({
971 cwd: snapshot.cwd,
972 checkpointRefs: [snapshot.checkpointRef],
973 })
974 .pipe(Effect.ignore),
975 { discard: true },
976 ),
977 ),
978 ),
979 );
980 },
981 );
982
983 const repositoryScopesIfReadable: CheckpointServiceV2Shape["repositoryScopesIfReadable"] =
984 Effect.fn("CheckpointService.repositoryScopes")(
985 function* (input) {
986 const workspace = yield* workspaceFolders.forThread(input);
987 const submodules = yield* workspaceFolders.submodules({
988 ...input,
989 folders: workspace.folders,
990 });
991 return yield* Effect.forEach(
992 [...workspace.folders.filter((folder) => folder.isGitRepository), ...submodules],
993 (folder) =>
994 idAllocator.allocate
995 .checkpointScope({
996 threadId: input.rootScope.threadId,
997 name: `repository:${folder.repositoryPath ?? folder.path}`,
998 })
999 .pipe(
1000 Effect.map(
1001 (id) =>
1002 ({
1003 id,
1004 threadId: input.rootScope.threadId,
1005 runId: input.rootScope.runId,
1006 nodeId: input.rootScope.nodeId,
1007 parentScopeId: input.rootScope.id,
1008 providerThreadId: input.rootScope.providerThreadId,
1009 kind: "manual",
1010 ordinalWithinParent: 1,
1011 advancesAppRunCount: false,
1012 cwd: folder.path,
1013 label: folder.name,
1014 repositoryPath: folder.repositoryPath ?? folder.path,
1015 createdAt: input.rootScope.createdAt,
1016 }) satisfies OrchestrationV2CheckpointScope,
1017 ),
1018 ),
1019 );
1020 },
1021 (effect, input) =>
1022 effect.pipe(
1023 Effect.catch((cause) =>
1024 Effect.logWarning("orchestration V2 repository checkpoint scopes unavailable", {
1025 threadId: input.rootScope.threadId,
1026 cause,
1027 }).pipe(Effect.as(null)),
1028 ),
1029 ),
1030 );
1031 const repositoryScopes: CheckpointServiceV2Shape["repositoryScopes"] = (input) =>
1032 repositoryScopesIfReadable(input).pipe(Effect.map((scopes) => scopes ?? []));
1033
1034 const captureRepositoryBaselines = Effect.fn("CheckpointService.captureRepositoryBaselines")(
1035 function* (input: {
1036 readonly scopes: ReadonlyArray<OrchestrationV2CheckpointScope>;
1037 readonly ordinalWithinScope: number;
1038 readonly nested: NestedScopePaths;
1039 }) {
1040 const captured = yield* Effect.forEach(
1041 input.scopes,
1042 (scope) =>
1043 noteRepositoryBaseline({
1044 scope,
1045 ordinalWithinScope: input.ordinalWithinScope,
1046 excludePaths: input.nested.get(scope.id),
1047 }).pipe(
1048 Effect.catch((cause) =>
1049 Effect.logWarning("orchestration V2 repository baseline capture failed", {
1050 scopeId: scope.id,
1051 cause,
1052 }),
1053 ),
1054 ),
1055 { concurrency: REPOSITORY_SCOPE_CONCURRENCY, discard: true },
1056 ).pipe(Effect.timeoutOption(BASELINE_CAPTURE_BUDGET));
1057 if (Option.isNone(captured)) {
1058 yield* Effect.logWarning(
1059 "orchestration V2 repository baselines ran out of time; the rest start without one",
1060 { scopeCount: input.scopes.length },
1061 );
1062 }
1063 },
1064 );
1065
1066 const captureRepository: CheckpointServiceV2Shape["captureRepository"] = Effect.fn(
1067 "CheckpointService.captureRepository",
1068 )(function* (input) {
1069 const { cwd, id } = input.scope;
1070 const baselineOrdinal = input.ordinalWithinScope - 1;
1071 const capturesBeforeLock = capturesSoFar(cwd);
1072 const start = yield* withWorkspaceLock(
1073 cwd,
1074 Effect.gen(function* () {
1075 const cleanHead = yield* checkpointStore
1076 .resolveCleanHead(cwd)
1077 .pipe(Effect.orElseSucceed(() => null));
1078 const stored = repositoryStates.get(id);
1079 const known = stored?.ordinal === baselineOrdinal ? stored : undefined;
1080 const cleanAtStart = known?.cleanHead ?? null;
1081 const unchanged = { changed: false as const, cleanHead };
1082 if (cleanHead !== null && cleanAtStart === cleanHead) return unchanged;
1083 const baselineRef = yield* checkpointRefFor({
1084 scopeId: id,
1085 ordinalWithinScope: baselineOrdinal,
1086 });
1087 const baselineExists = yield* checkpointStore
1088 .hasCheckpointRef({ cwd, checkpointRef: baselineRef })
1089 .pipe(Effect.orElseSucceed(() => false));
1090 if (!baselineExists) {
1091 // The turn started on a clean folder; its snapshot was left until one was needed.
1092 if (known !== undefined && cleanAtStart !== null) {
1093 yield* checkpointStore
1094 .captureHeadCheckpoint({
1095 cwd,
1096 checkpointRef: baselineRef,
1097 head: cleanAtStart,
1098 seenAt: known.seenAt,
1099 })
1100 .pipe(Effect.ignore);
1101 } else if (cleanHead !== null) {
1102 // How the turn started is unknown and nothing is uncommitted: nothing to show.
1103 return unchanged;
1104 }
1105 }
1106 return { changed: true as const, cleanHead };
1107 }),
1108 );
1109 const settled = { ordinal: input.ordinalWithinScope, cleanHead: start.cleanHead };
1110 if (!start.changed) {
1111 yield* noteRepositoryState(id, settled);
1112 return Option.none();
1113 }
1114 const baseline = input.baselineRecorded
1115 ? null
1116 : yield* materializeBaselineCheckpoint({
1117 scope: input.scope,
1118 ordinalWithinScope: baselineOrdinal,
1119 nodeId: input.nodeId,
1120 capturedAt: input.baselineCapturedAt,
1121 });
1122 const { checkpoint, summaryFailed } = yield* captureSummarized({
1123 scope: input.scope,
1124 runId: input.runId,
1125 nodeId: input.nodeId,
1126 ordinalWithinScope: input.ordinalWithinScope,
1127 appRunOrdinal: null,
1128 capturedAt: input.capturedAt,
1129 capturesBeforeLock,
1130 ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }),
1131 ...(start.cleanHead === null ? {} : { cleanHead: start.cleanHead }),
1132 });
1133 if (checkpoint.status !== "ready") {
1134 repositoryStates.delete(id);
1135 return Option.some({ baseline, checkpoint });
1136 }
1137 yield* noteRepositoryState(id, settled);
1138 // A pull or a commit of what was already there moves the snapshot and lists no file.
1139 return !summaryFailed &&
1140 checkpoint.files.length === 0 &&
1141 (baseline === null || baseline.status === "ready")
1142 ? Option.none()
1143 : Option.some({ baseline, checkpoint });
1144 });
1145
1146 const discardRepositorySnapshots: CheckpointServiceV2Shape["discardRepositorySnapshots"] =
1147 Effect.fn("CheckpointService.discardRepositorySnapshots")(function* (input) {
1148 if (input.ordinals.length === 0) return;
1149 const repositories = yield* repositoryScopes({
1150 rootScope: input.rootScope,
1151 ...input.thread,
1152 });
1153 yield* Effect.forEach(
1154 repositories,
1155 (scope) =>
1156 withWorkspaceLock(
1157 scope.cwd,
1158 Effect.gen(function* () {
1159 repositoryStates.delete(scope.id);
1160 yield* checkpointStore.deleteCheckpointRefs({
1161 cwd: scope.cwd,
1162 checkpointRefs: yield* Effect.forEach(input.ordinals, (ordinalWithinScope) =>
1163 checkpointRefFor({ scopeId: scope.id, ordinalWithinScope }),
1164 ),
1165 });
1166 }),
1167 ).pipe(
1168 Effect.catch((cause) =>
1169 Effect.logWarning("orchestration V2 stale repository snapshots kept", {
1170 scopeId: scope.id,
1171 cause: String(cause),
1172 }),
1173 ),
1174 ),
1175 { concurrency: REPOSITORY_SCOPE_CONCURRENCY, discard: true },
1176 );
1177 });
1178
1179 const captureBaseline: CheckpointServiceV2Shape["captureBaseline"] = Effect.fn(
1180 "CheckpointService.captureBaseline",
1181 )(function* (input) {
1182 const repositories =
1183 input.thread === undefined
1184 ? []
1185 : yield* repositoryScopes({ rootScope: input.scope, ...input.thread });
1186 if (repositories.length === 0) {
1187 return yield* captureScopeBaseline({ ...input, excludePaths: undefined });
1188 }
1189 const nested = yield* resolveNestedScopePaths([input.scope, ...repositories]);
1190 // Side by side, so the repositories add no wait of their own; the thread folder's failure
1191 // is still the caller's to report once they have had their turn.
1192 const [root] = yield* Effect.all(
1193 [
1194 Effect.exit(captureScopeBaseline({ ...input, excludePaths: nested.get(input.scope.id) })),
1195 captureRepositoryBaselines({
1196 scopes: repositories,
1197 ordinalWithinScope: input.ordinalWithinScope,
1198 nested,
1199 }),
1200 ],
1201 { concurrency: 2 },
1202 );
1203 if (Exit.isFailure(root)) return yield* Effect.failCause(root.cause);
1204 });
1205
1206 const deleteStaleRefs: CheckpointServiceV2Shape["deleteStaleRefs"] = (input) =>
1207 withWorkspaceLock(
1208 input.scope.cwd,
1209 checkpointStore.deleteCheckpointRefs({
1210 cwd: input.scope.cwd,
1211 checkpointRefs: input.checkpoints.map((checkpoint) => checkpoint.ref),
1212 }),
1213 ).pipe(
1214 Effect.mapError(
1215 (cause) =>
1216 new CheckpointDeleteStaleRefsError({
1217 scopeId: input.scope.id,
1218 checkpointIds: input.checkpoints.map((checkpoint) => checkpoint.id),
1219 cause,
1220 }),
1221 ),
1222 );
1223
1224 return CheckpointServiceV2.of({
1225 prepareRootRunScope: (input) =>
1226 makeRootRunScope({ ...input, idAllocator }).pipe(
1227 Effect.mapError(
1228 (cause) =>
1229 new CheckpointRootScopePrepareError({
1230 threadId: input.threadId,
1231 runId: input.runId,
1232 cause,
1233 }),
1234 ),
1235 ),
1236 repositoryScopes,
1237 repositoryScopesIfReadable,
1238 nestedScopePaths: resolveNestedScopePaths,
1239 captureBaseline,
1240 materializeBaselineCheckpoint,
1241 capture,
1242 capturesSoFar: (cwd: string) => Effect.sync(() => capturesSoFar(cwd)),
1243 captureRepository,
1244 restore,
1245 deleteStaleRefs,
1246 discardRepositorySnapshots,
1247 } satisfies CheckpointServiceV2Shape);
1248 }),
1249);