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