diff --git a/apps/server/src/checkpointing/CheckpointStore.ts b/apps/server/src/checkpointing/CheckpointStore.ts index 425cd2b0c815d..240b9fdf88b56 100644 --- a/apps/server/src/checkpointing/CheckpointStore.ts +++ b/apps/server/src/checkpointing/CheckpointStore.ts @@ -4,7 +4,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import type { CheckpointStoreError } from "./Errors.ts"; -import type { VcsCheckpointOps } from "../vcs/VcsDriver.ts"; +import type { VcsCheckpointOps, VcsCheckpointRange } from "../vcs/VcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; export interface CaptureCheckpointInput { @@ -16,6 +16,8 @@ export interface CaptureCheckpointInput { readonly excludePaths?: ReadonlyArray; } +export type CheckpointRange = VcsCheckpointRange; + export interface CaptureHeadCheckpointInput { readonly cwd: string; readonly checkpointRef: CheckpointRef; @@ -49,12 +51,16 @@ export interface DiffCheckpointsInput { readonly filePaths?: ReadonlyArray; /** Folders below `cwd` left out of the diff, as in a capture. */ readonly excludePaths?: ReadonlyArray; + /** The refs' range as their capture returned it; the refs are then not read. */ + readonly range?: VcsCheckpointRange; } export interface ListAuthoredPathsInput { readonly cwd: string; readonly fromCheckpointRef: CheckpointRef; readonly toCheckpointRef: CheckpointRef; + /** The refs' range as their capture returned it; the refs are then not read. */ + readonly range?: VcsCheckpointRange; } export interface DeleteCheckpointRefsInput { @@ -67,9 +73,10 @@ export class CheckpointStore extends Context.Service< { readonly isGitRepository: (cwd: string) => Effect.Effect; + /** The range from `previousCheckpointRef`, or null when there is none to compare with. */ readonly captureCheckpoint: ( input: CaptureCheckpointInput, - ) => Effect.Effect; + ) => Effect.Effect; /** * HEAD's commit when the folder matches it exactly: nothing staged, modified or untracked. diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index 31dd6b254d57c..d4326a63361ff 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -41,6 +41,13 @@ import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts"; +// `git -C -c log ...` reads as `log`. +const gitSubcommand = (args: ReadonlyArray) => { + let index = 0; + while (args[index] === "-C" || args[index] === "-c") index += 2; + return args[index] ?? ""; +}; + const layerProjectionStoreTest = Layer.mergeAll( ThreadCommandExecutor.layer, ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)), @@ -298,7 +305,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { Layer.mock(CheckpointStore.CheckpointStore)({ listAuthoredPaths: () => Effect.succeed(null), isGitRepository: () => Effect.succeed(true), - captureCheckpoint: () => Effect.void, + captureCheckpoint: () => Effect.succeed(null), hasCheckpointRef: () => Effect.fail( new VcsProcessTimeoutError({ @@ -914,7 +921,7 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { Layer.mock(CheckpointStore.CheckpointStore)({ isGitRepository: () => Effect.succeed(true), hasCheckpointRef: () => Effect.succeed(true), - captureCheckpoint: () => Effect.void, + captureCheckpoint: () => Effect.succeed(null), diffCheckpoints: () => Effect.succeed(""), listAuthoredPaths: () => Effect.succeed(null), }), @@ -1448,6 +1455,8 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { readonly threadId: ThreadId; readonly ids: IdAllocator.IdAllocatorV2["Service"]; readonly diffs: CheckpointDiffQuery.CheckpointDiffQuery["Service"]; + /** The git commands run since the last call, each as its subcommand and arguments. */ + readonly takeGitCommands: Effect.Effect>>; }) => Effect.Effect, ) => Effect.gen(function* () { @@ -1461,7 +1470,19 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { const labels = new Map([[repositoryRootScopeId, "root"]]); const committed = yield* Ref.make>([]); const layerNode = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer); - const layerVcsProcess = VcsProcess.layer.pipe(Layer.provide(layerNode)); + let gitCommands: Array> = []; + const layerVcsProcess = Layer.effect( + VcsProcess.VcsProcess, + Effect.map(VcsProcess.VcsProcess, (inner) => + VcsProcess.VcsProcess.of({ + run: (input) => + Effect.suspend(() => { + gitCommands.push(input.args); + return inner.run(input); + }), + }), + ), + ).pipe(Layer.provide(VcsProcess.layer), Layer.provide(layerNode)); const layerCheckpointStore = CheckpointStore.layer.pipe( Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(layerVcsProcess))), Layer.provide(layerNode), @@ -1728,10 +1749,79 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { threadId: repositoryThreadId, ids: yield* IdAllocator.IdAllocatorV2, diffs: yield* CheckpointDiffQuery.CheckpointDiffQuery, + takeGitCommands: Effect.sync(() => { + const taken = gitCommands; + gitCommands = []; + return taken; + }), }); }).pipe(Effect.provide(layer), Effect.scoped); }); + it.effect("captures a turn without re-reading the previous checkpoint", () => + withTrackedRepositories("capture-git-commands", (thread) => + Effect.gen(function* () { + const { root } = thread; + yield* thread.initRepository(root); + yield* thread.turn(1, thread.write(`${root}/README.md`, "# one\n")); + // Counted from after the turn's edits, so only the capture itself. + const capture = (ordinal: number, edits: Effect.Effect) => + Effect.gen(function* () { + const recorded = yield* thread.turn( + ordinal, + edits.pipe(Effect.andThen(thread.takeGitCommands)), + ); + return { + files: recorded.flatMap((entry) => entry.files ?? []), + commands: (yield* thread.takeGitCommands).map(gitSubcommand), + }; + }); + const snapshot = [ + "rev-parse", + "log", + "config", + "read-tree", + "ls-files", + "add", + "write-tree", + "log", + "commit-tree", + "update-ref", + ]; + + assert.deepEqual(yield* capture(2, thread.write(`${root}/README.md`, "# two\n")), { + files: ["README.md"], + commands: [...snapshot, "diff"], + }); + // Nothing changed, so there is nothing to diff. + assert.deepEqual(yield* capture(3, Effect.void), { files: [], commands: snapshot }); + // A commit moves HEAD; its paths are read without resolving the range again. + const committed = yield* capture( + 4, + thread + .write(`${root}/README.md`, "# four\n") + .pipe(Effect.andThen(thread.git(root, "commit", "-am", "four")), Effect.asVoid), + ); + assert.deepEqual(committed.files, ["README.md"]); + // The summary's reads run side by side, so only which commands ran is fixed. + assert.deepEqual( + committed.commands.toSorted(), + [ + ...snapshot, + "diff", + "version", + "rev-list", + "diff", + "diff", + "log", + "log", + "log", + ].toSorted(), + ); + }), + ), + ); + it.effect("checkpoints the repositories a folder that is not a repository holds", () => withTrackedRepositories("capture-wrapper", (thread) => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/CheckpointService.test.ts b/apps/server/src/orchestration-v2/CheckpointService.test.ts index 0433208167a73..fd6059ba61c51 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.test.ts @@ -153,6 +153,7 @@ it.effect( yield* Deferred.succeed(firstSnapshotStarted, undefined); yield* Effect.sleep("10 seconds"); yield* Ref.update(refs, (current) => new Set([...current, checkpointRef])); + return null; }), }), ), @@ -482,7 +483,9 @@ it.effect("backs off only baseline retries after repeated workspace capture time captureCheckpoint: () => Effect.suspend(() => { attempts++; - return healthy ? Effect.void : Effect.fail(nonTimeoutFailure ? failure : timeout); + return healthy + ? Effect.succeed(null) + : Effect.fail(nonTimeoutFailure ? failure : timeout); }), }), ), @@ -586,7 +589,7 @@ it.effect("skips post-turn captures that waited out another capture's timeout in yield* Effect.sleep("30 seconds"); const [next = "timeout", ...rest] = yield* Ref.get(script); yield* Ref.set(script, rest); - if (next === "ready") return; + if (next === "ready") return null; return yield* new VcsProcessTimeoutError({ operation: "GitVcsDriver.checkpoints.captureCheckpoint", command: "git", @@ -737,6 +740,7 @@ it.effect("keeps the pre-rewind snapshot of a folder a failed rewind could not p captured.push(input.cwd); existing.add(input.checkpointRef); preRewindRefs.set(input.cwd, input.checkpointRef); + return null; }), // The second folder's rewind fails, and then so does putting the first one back. restoreCheckpoint: (input) => diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index ec3e872d61c2b..9fc32d70b423d 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -12,6 +12,7 @@ import { ThreadId, } from "@t3tools/contracts"; import * as Cache from "effect/Cache"; +import type * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; @@ -28,6 +29,7 @@ import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import { isGitImport, parseTurnDiffFilesFromNumstat } from "../checkpointing/Diffs.ts"; +import type { CheckpointStoreError } from "../checkpointing/Errors.ts"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts"; @@ -411,7 +413,11 @@ export const layer: Layer.Layer< const captureWorkspaceCheckpoint = Effect.fn("CheckpointService.captureWorkspaceCheckpoint")( function* (input: CheckpointStore.CaptureCheckpointInput, baseline = false) { const capture = checkpointStore.captureCheckpoint(input); - yield* (baseline ? capture.pipe(Effect.timeout(BASELINE_CAPTURE_BUDGET)) : capture).pipe( + const bounded: Effect.Effect< + CheckpointStore.CheckpointRange | null, + CheckpointStoreError | Cause.TimeoutError + > = baseline ? capture.pipe(Effect.timeout(BASELINE_CAPTURE_BUDGET)) : capture; + return yield* bounded.pipe( Effect.tap(() => Effect.andThen( Cache.invalidate(captureTimeouts, input.cwd), @@ -669,41 +675,46 @@ export const layer: Layer.Layer< lastCapture !== undefined && lastCapture.timedOut && lastCapture.count > capturesBeforeLock; - const captureStatus = timedOutWhileWaiting + // `range` is undefined when the capture did not read the previous checkpoint itself. + type Captured = { + readonly status: "ready" | "missing" | "error"; + readonly range?: CheckpointStore.CheckpointRange | null; + }; + const snapshot: Effect.Effect = + input.cleanHead === undefined + ? captureWorkspaceCheckpoint({ + cwd: input.scope.cwd, + checkpointRef, + ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), + ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), + }).pipe(Effect.map((range) => ({ status: "ready" as const, range }))) + : checkpointStore + .captureHeadCheckpoint({ + cwd: input.scope.cwd, + checkpointRef, + head: input.cleanHead, + }) + .pipe(Effect.as({ status: "ready" as const })); + const captured: Captured = timedOutWhileWaiting ? yield* Effect.logWarning( "orchestration V2 checkpoint capture skipped after a capture timed out in its folder", { scopeId: input.scope.id, checkpointRef }, - ).pipe(Effect.as("error" as const)) - : yield* ( - input.cleanHead === undefined - ? captureWorkspaceCheckpoint({ - cwd: input.scope.cwd, - checkpointRef, - ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), - ...(input.excludePaths === undefined - ? {} - : { excludePaths: input.excludePaths }), - }) - : checkpointStore.captureHeadCheckpoint({ - cwd: input.scope.cwd, - checkpointRef, - head: input.cleanHead, - }) - ).pipe( - Effect.as("ready" as const), + ).pipe(Effect.as({ status: "error" as const })) + : yield* snapshot.pipe( Effect.catchTags({ - VcsUnsupportedOperationError: () => Effect.succeed("missing" as const), + VcsUnsupportedOperationError: () => + Effect.succeed({ status: "missing" as const }), }), Effect.catch((cause) => Effect.logWarning("orchestration V2 checkpoint capture failed", { scopeId: input.scope.id, checkpointRef, cause: String(cause), - }).pipe(Effect.as("error" as const)), + }).pipe(Effect.as({ status: "error" as const })), ), ); - if (captureStatus !== "ready") { + if (captured.status !== "ready") { return { checkpoint: makeCheckpoint({ id: checkpointId, @@ -714,7 +725,7 @@ export const layer: Layer.Layer< ordinalWithinScope: input.ordinalWithinScope, appRunOrdinal: input.appRunOrdinal, ref: checkpointRef, - status: captureStatus, + status: captured.status, files: [], capturedAt: input.capturedAt, }), @@ -722,65 +733,73 @@ export const layer: Layer.Layer< }; } - const previousExists = yield* checkpointStore - .hasCheckpointRef({ - cwd: input.scope.cwd, - checkpointRef: previousCheckpointRef, - }) - .pipe( - Effect.catch((cause) => - Effect.logWarning("orchestration V2 previous checkpoint ref lookup failed", { - scopeId: input.scope.id, - checkpointRef: previousCheckpointRef, - cause: String(cause), - }).pipe(Effect.as(false)), - ), - ); + const { range } = captured; + const previousExists = + range !== undefined + ? range !== null + : yield* checkpointStore + .hasCheckpointRef({ + cwd: input.scope.cwd, + checkpointRef: previousCheckpointRef, + }) + .pipe( + Effect.catch((cause) => + Effect.logWarning("orchestration V2 previous checkpoint ref lookup failed", { + scopeId: input.scope.id, + checkpointRef: previousCheckpointRef, + cause: String(cause), + }).pipe(Effect.as(false)), + ), + ); const refs = { cwd: input.scope.cwd, fromCheckpointRef: previousCheckpointRef, toCheckpointRef: checkpointRef, + ...(range === undefined || range === null ? {} : { range }), }; // A pull or rebase can change thousands of files the turn did not write. - const files = previousExists - ? yield* Effect.all([ - checkpointStore.diffCheckpoints({ - ...refs, - fallbackFromToHead: false, - ignoreWhitespace: false, - format: "numstat", - // An earlier checkpoint can predate a nested folder getting its own scope. - ...(input.excludePaths === undefined ? {} : { excludePaths: input.excludePaths }), - }), - checkpointStore.listAuthoredPaths(refs).pipe( + const files = + !previousExists || range?.unchanged === true + ? [] + : yield* Effect.all([ + checkpointStore.diffCheckpoints({ + ...refs, + fallbackFromToHead: false, + ignoreWhitespace: false, + format: "numstat", + // An earlier checkpoint can predate a nested folder getting its own scope. + ...(input.excludePaths === undefined + ? {} + : { excludePaths: input.excludePaths }), + }), + checkpointStore.listAuthoredPaths(refs).pipe( + Effect.catch((cause) => + Effect.logWarning("orchestration V2 checkpoint authored paths failed", { + scopeId: input.scope.id, + checkpointRef, + cause: String(cause), + }).pipe(Effect.as(null)), + ), + ), + ]).pipe( + Effect.map(([diff, authoredPaths]) => + parseTurnDiffFilesFromNumstat(diff) + .filter((file) => !isGitImport(file, authoredPaths)) + .map((file) => ({ + path: file.path, + kind: "modified", + additions: file.additions, + deletions: file.deletions, + })), + ), Effect.catch((cause) => - Effect.logWarning("orchestration V2 checkpoint authored paths failed", { + Effect.logWarning("orchestration V2 checkpoint diff summary failed", { scopeId: input.scope.id, checkpointRef, cause: String(cause), }).pipe(Effect.as(null)), ), - ), - ]).pipe( - Effect.map(([diff, authoredPaths]) => - parseTurnDiffFilesFromNumstat(diff) - .filter((file) => !isGitImport(file, authoredPaths)) - .map((file) => ({ - path: file.path, - kind: "modified", - additions: file.additions, - deletions: file.deletions, - })), - ), - Effect.catch((cause) => - Effect.logWarning("orchestration V2 checkpoint diff summary failed", { - scopeId: input.scope.id, - checkpointRef, - cause: String(cause), - }).pipe(Effect.as(null)), - ), - ) - : []; + ); return { checkpoint: makeCheckpoint({ diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 551c863510423..ffa8670b64607 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1347,7 +1347,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( { discard: true }, ); - yield* Effect.gen(function* () { + const range = yield* Effect.gen(function* () { const sparseConfig = yield* execute({ operation, cwd: input.cwd, @@ -1702,31 +1702,51 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } + // Read once: it is both where a branch switch is replayed from and the turn's range. + const previousCheckpointRef = input.previousCheckpointRef; + const previous = + previousCheckpointRef === undefined + ? null + : yield* execute({ + operation, + cwd: input.cwd, + args: [ + "-c", + "log.showSignature=false", + "log", + "--no-walk", + "--format=%H %T %ct %P%n%B", + `${previousCheckpointRef}^{commit}`, + ], + allowNonZeroExit: true, + }).pipe( + Effect.map((result) => { + if (result.exitCode !== 0) return null; + const [commit = "", tree = "", capturedAt = "", head = ""] = result.stdout + .slice(0, result.stdout.indexOf("\n")) + .split(" "); + return commit === "" || tree === "" + ? null + : { commit, tree, capturedAt, head, message: result.stdout }; + }), + Effect.catch((cause) => + Effect.logWarning("previous checkpoint lookup failed", { + cwd: input.cwd, + checkpointRef: previousCheckpointRef, + errorTag: cause._tag, + }).pipe(Effect.as(null)), + ), + ); + // Switching branches rewrites files the turn never wrote, and only HEAD's reflog tells a // switch from a reset. The trailer marks where that reflog stood for the next checkpoint. const turnStart = - headMark === undefined || input.previousCheckpointRef === undefined + headMark === undefined || previous === null ? null : yield* Effect.gen(function* () { - const previous = yield* execute({ - operation, - cwd: input.cwd, - args: [ - "-c", - "log.showSignature=false", - "log", - "--no-walk", - "--format=%H %T %ct %P%n%B", - `${input.previousCheckpointRef}^{commit}`, - ], - allowNonZeroExit: true, - }); - if (previous.exitCode !== 0) return null; - const [commit = "", tree = "", capturedAt = "", previousHead = ""] = previous.stdout - .slice(0, previous.stdout.indexOf("\n")) - .split(" "); + const { commit, tree, capturedAt, head: previousHead } = previous; const [, markedAt, markedCount] = - HEAD_MARK_TRAILER_PATTERN.exec(previous.stdout) ?? []; + HEAD_MARK_TRAILER_PATTERN.exec(previous.message) ?? []; const oldestMarked = headMoves.findLastIndex((move) => move.at === markedAt); // -1 when the scan ended inside the marked second, so the count cannot be placed. const since = @@ -1818,7 +1838,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( // listAuthoredPaths reads commits newer than the start as the turn's own. env: { ...commitEnv, GIT_COMMITTER_DATE: `${capturedAt} +0000` }, }); - return startCommit.stdout.trim() || null; + const startOid = startCommit.stdout.trim(); + return startOid === "" ? null : { commit: startOid, tree: startTree, landedOn }; }).pipe( Effect.catch((cause) => Effect.logWarning("checkpoint branch switch turn start failed", { @@ -1832,6 +1853,13 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const message = `t3 checkpoint ref=${input.checkpointRef}${ headMark === undefined ? "" : `\n\n${HEAD_MARK_TRAILER}: ${headMark}` }`; + // Git before 2.31 leaves `head` unread; a range names the parent the commit got. + const parentHead = + !headExists || head !== undefined + ? (head ?? "") + : previous === null + ? "" + : ((yield* resolveHeadCommit(input.cwd)) ?? ""); // HEAD is the first parent so listAuthoredPaths can see how HEAD moved between checkpoints. const commitTreeResult = yield* execute({ operation, @@ -1840,8 +1868,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ...durableWrite, "commit-tree", treeOid, - ...(headExists ? ["-p", head ?? "HEAD"] : []), - ...(turnStart === null ? [] : ["-p", turnStart]), + ...(headExists ? ["-p", parentHead || "HEAD"] : []), + ...(turnStart === null ? [] : ["-p", turnStart.commit]), "-m", message, ], @@ -1961,6 +1989,16 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( before, }); } + if (previous === null) return null; + // A turn start is committed at the previous checkpoint's time, after `landedOn`. + return { + from: turnStart?.commit ?? previous.commit, + to: commitOid, + fromCapturedAt: previous.capturedAt, + startHead: turnStart?.landedOn ?? previous.head, + endHead: parentHead, + unchanged: treeOid === (turnStart?.tree ?? previous.tree), + } satisfies VcsDriver.VcsCheckpointRange; }).pipe(Effect.ensuring(cleanupTempIndex)); // The tree records only each submodule's HEAD, so submodules keep their own ref. @@ -1969,7 +2007,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( (yield* fileSystem .exists(path.join(topLevel, ".gitmodules")) .pipe(Effect.orElseSucceed(() => true))); - if (!hasSubmodules) return; + if (!hasSubmodules) return range; // A submodule that cannot be captured drops its ref, so restore leaves it alone. yield* listSubmodules(input.cwd).pipe( Effect.flatMap((submodules) => @@ -1996,6 +2034,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( Effect.logWarning("submodule checkpoint capture failed", { cwd: input.cwd, cause }), ), ); + return range; }, Effect.scoped), resolveCleanHead: Effect.fn("GitVcsDriver.checkpoints.resolveCleanHead")(function* (cwd) { @@ -2319,8 +2358,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); const diffExclusions = excludedPathspecs(input.excludePaths); - let fromRevision = yield* resolveTurnStart(input); - if (input.fallbackFromToHead === true) { + let fromRevision = input.range?.from ?? (yield* resolveTurnStart(input)); + if (input.fallbackFromToHead === true && input.range === undefined) { const resolvedFromCommit = yield* resolveCheckpointCommit( input.cwd, input.fromCheckpointRef, @@ -2358,7 +2397,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ...PATCH_RENDER_PREFIX_ARGS, ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []), `${fromRevision}^{commit}`, - `${input.toCheckpointRef}^{commit}`, + `${input.range?.to ?? input.toCheckpointRef}^{commit}`, // Paths are repository-relative, while cwd can be a subdirectory. ...(input.filePaths ? ["--", ...input.filePaths.map((file) => `:(top,literal)${file}`), ...diffExclusions] @@ -2386,21 +2425,33 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( listAuthoredPaths: Effect.fn("GitVcsDriver.checkpoints.listAuthoredPaths")(function* (input) { const operation = "GitVcsDriver.checkpoints.listAuthoredPaths"; - const turnStart = yield* resolveTurnStart(input); - const heads = yield* execute({ - operation, - cwd: input.cwd, - args: [ - "log", - "--no-walk=unsorted", - "--format=%ct %P", - `${turnStart}^{commit}`, - `${input.toCheckpointRef}^{commit}`, - ], - }); - const [fromLine = "", toLine = ""] = heads.stdout.trimEnd().split("\n"); - const [capturedAt = "", startHead = ""] = fromLine.split(" "); - const [, endHead = ""] = toLine.split(" "); + const { turnStart, to, capturedAt, startHead, endHead } = + input.range === undefined + ? yield* Effect.gen(function* () { + const turnStart = yield* resolveTurnStart(input); + const heads = yield* execute({ + operation, + cwd: input.cwd, + args: [ + "log", + "--no-walk=unsorted", + "--format=%ct %P", + `${turnStart}^{commit}`, + `${input.toCheckpointRef}^{commit}`, + ], + }); + const [fromLine = "", toLine = ""] = heads.stdout.trimEnd().split("\n"); + const [capturedAt = "", startHead = ""] = fromLine.split(" "); + const [, endHead = ""] = toLine.split(" "); + return { turnStart, to: input.toCheckpointRef, capturedAt, startHead, endHead }; + }) + : { + turnStart: input.range.from, + to: input.range.to, + capturedAt: input.range.fromCapturedAt, + startHead: input.range.startHead, + endHead: input.range.endHead, + }; if (startHead === "" || endHead === "" || startHead === endHead) { return null; } @@ -2580,7 +2631,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( [ listLines(["rev-list", `--max-age=${capturedAt}`, `${startHead}..${endHead}`]), listPaths(["diff", startHead, `${turnStart}^{commit}`]), - listPaths(["diff", endHead, `${input.toCheckpointRef}^{commit}`]), + listPaths(["diff", endHead, `${to}^{commit}`]), listCommitPaths([`${endHead}..${startHead}`]), ], { concurrency: "unbounded" }, diff --git a/apps/server/src/vcs/VcsDriver.ts b/apps/server/src/vcs/VcsDriver.ts index c5a6408db0128..d7d59880708e7 100644 --- a/apps/server/src/vcs/VcsDriver.ts +++ b/apps/server/src/vcs/VcsDriver.ts @@ -20,6 +20,24 @@ export interface VcsCaptureCheckpointInput { readonly excludePaths?: ReadonlyArray; } +/** + * A turn's range as its capture found it, so summarizing it need not ask Git again. Commits, not + * refs: a later capture cannot move them. + */ +export interface VcsCheckpointRange { + /** Where the turn started: the previous checkpoint, or its turn start after a branch switch. */ + readonly from: string; + /** The checkpoint just captured. */ + readonly to: string; + /** `from`'s commit time, in epoch seconds. */ + readonly fromCapturedAt: string; + /** The HEAD `from` and `to` recorded as first parent; empty for none. */ + readonly startHead: string; + readonly endHead: string; + /** `to` holds the same files as `from`, so the turn changed nothing. */ + readonly unchanged: boolean; +} + export interface VcsCaptureHeadCheckpointInput { readonly cwd: string; readonly checkpointRef: CheckpointRef; @@ -55,12 +73,16 @@ export interface VcsDiffCheckpointsInput { readonly filePaths?: ReadonlyArray; /** Folders below `cwd` left out of the diff, as in a capture. */ readonly excludePaths?: ReadonlyArray; + /** The refs' range as their capture returned it; the refs are then not read. */ + readonly range?: VcsCheckpointRange; } export interface VcsListAuthoredPathsInput { readonly cwd: string; readonly fromCheckpointRef: CheckpointRef; readonly toCheckpointRef: CheckpointRef; + /** The refs' range as their capture returned it; the refs are then not read. */ + readonly range?: VcsCheckpointRange; } export interface VcsDeleteCheckpointRefsInput { @@ -69,7 +91,10 @@ export interface VcsDeleteCheckpointRefsInput { } export interface VcsCheckpointOps { - readonly captureCheckpoint: (input: VcsCaptureCheckpointInput) => Effect.Effect; + /** The range from `previousCheckpointRef`, or null when there is none to compare with. */ + readonly captureCheckpoint: ( + input: VcsCaptureCheckpointInput, + ) => Effect.Effect; /** * HEAD's commit when the folder matches it exactly: nothing staged, modified or untracked. * Null otherwise. One status, where a capture stages the whole worktree.