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