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

CheckpointService.ts

1,190 lines46.9 KB

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