Skip to content

The open-source app everyone uses to manage agents at work

feat: save ignored files in git restore points (#17290)

Devin Foley687776090497
diff --git a/doc/recoverable-disk-cleanup.md b/doc/recoverable-disk-cleanup.md
index cde748386f..ac17c3dd6e 100644
--- a/doc/recoverable-disk-cleanup.md
+++ b/doc/recoverable-disk-cleanup.md
@@ -114,8 +114,15 @@ Before removal it saves a restore point:
- a git bundle of commits the remote does not have, against a remote-verified base,
including commits only reachable from the reflog or `ORIG_HEAD`;
- deterministic snapshots of the index and working tree, including untracked files and
- non-default file modes. Ignored files are left out, and so are untracked `.env` and
- `.env.*` files, which provisioning recreates with current secrets.
+ non-default file modes. Untracked `.env` and `.env.*` files are left out, because
+ provisioning recreates them with current secrets;
+- a separate snapshot of ignored files, such as build caches or files an agent kept out of
+ git. It leaves out `.env` files, nested `.paperclip-repositories` checkouts (they get their
+ own restore points), `.claude/settings.local.json` (saved with the workspace contents)
+ and anything inside a regenerable directory such as `node_modules` or `dist`. A
+ restore point with ignored files uses payload schema `v2`, which older servers reject
+ instead of restoring without them. Restoring never overwrites an ignored file that already
+ exists, and an ignored nested repository keeps the worktree.
The restore point is encrypted with a per-restore-point key wrapped by the instance
secrets key, uploaded to file storage, read back and hash-checked, then activated in
diff --git a/server/src/__tests__/git-restore-point-expiration.test.ts b/server/src/__tests__/git-restore-point-expiration.test.ts
index aea5a1e25d..510c9a536e 100644
--- a/server/src/__tests__/git-restore-point-expiration.test.ts
+++ b/server/src/__tests__/git-restore-point-expiration.test.ts
@@ -56,7 +56,7 @@ describeEmbeddedPostgres("git restore point expiration", () => {
git(source, "init", "--initial-branch=main");
await fs.writeFile(path.join(source, "marker.txt"), "commit A\n");
await fs.writeFile(path.join(source, "remove-me.txt"), "tracked\n");
- await fs.writeFile(path.join(source, ".gitignore"), "node_modules/\n.env\n.claude/settings.local.json\n");
+ await fs.writeFile(path.join(source, ".gitignore"), "node_modules/\n.env\n.claude/settings.local.json\n*.tsbuildinfo\nevidence/\n");
git(source, "add", "."); git(source, "commit", "-m", "A");
git(location, "clone", "--bare", source, remote); git(source, "remote", "add", "origin", remote);
await db.insert(companies).values({ id: companyId, name: "Restore point fixture", issuePrefix: `RP${companyId.slice(0, 6)}` });
@@ -356,6 +356,35 @@ describeEmbeddedPostgres("git restore point expiration", () => {
});
});
+ it("expires a worktree whose only extra files are ignored, and restores them on reopen", async () => {
+ const f = await fixture();
+ await fs.mkdir(path.join(f.cwd, "ui"), { recursive: true });
+ await fs.writeFile(path.join(f.cwd, "ui", "tsconfig.tsbuildinfo"), "{\"version\":\"5\"}\n");
+ await fs.mkdir(path.join(f.cwd, "evidence"));
+ await fs.writeFile(path.join(f.cwd, "evidence", "run.log"), "agent evidence\n");
+ await fs.mkdir(path.join(f.cwd, "node_modules", "pkg"), { recursive: true });
+ await fs.writeFile(path.join(f.cwd, "node_modules", "pkg", "index.js"), "regenerable\n");
+ expect(git(f.cwd, "status", "--porcelain")).toBe("");
+ expect(await f.expire({ restorePoint: undefined })).toMatchObject({ expired: false, skipReason: "unique_ignored_files" });
+ expect(await f.expire()).toMatchObject({ expired: true, restorePoint: true, skipReason: null });
+ expect(await exists(f.cwd)).toBe(false);
+ expect(await f.reopen()).toMatchObject({ ok: true, reopened: true });
+ expect(await fs.readFile(path.join(f.cwd, "ui", "tsconfig.tsbuildinfo"), "utf8")).toBe("{\"version\":\"5\"}\n");
+ expect(await fs.readFile(path.join(f.cwd, "evidence", "run.log"), "utf8")).toBe("agent evidence\n");
+ expect(await exists(path.join(f.cwd, "node_modules", "pkg", "index.js"))).toBe(false);
+ });
+
+ it("rolls back when an ignored file changes after capture", async () => {
+ const f = await fixture();
+ await fs.mkdir(path.join(f.cwd, "evidence"));
+ await fs.writeFile(path.join(f.cwd, "evidence", "run.log"), "agent evidence\n");
+ const result = await f.expire({ beforeDelete: async () => {
+ await fs.writeFile(path.join(f.cwd, "evidence", "run.log"), "written after capture\n");
+ } });
+ expect(result).toMatchObject({ expired: false, skipReason: "restore_point_contents_changed" });
+ expect(await fs.readFile(path.join(f.cwd, "evidence", "run.log"), "utf8")).toBe("written after capture\n");
+ });
+
it("reports a restore point candidate in dry run without storing anything", async () => {
const f = await fixture();
await makeUnsavedWork(f.cwd);
diff --git a/server/src/__tests__/git-restore-point.test.ts b/server/src/__tests__/git-restore-point.test.ts
index 62135a90e8..ba6a860ef9 100644
--- a/server/src/__tests__/git-restore-point.test.ts
+++ b/server/src/__tests__/git-restore-point.test.ts
@@ -7,6 +7,7 @@ import {
applyRestorePoint,
captureRestorePoint,
currentRestorePointSnapshot,
+ decodeRestorePointPayload,
importRestorePoint,
openRestorePoint,
RestorePointRestoreFailure,
@@ -96,7 +97,8 @@ describe("git restore points", () => {
const { payload, manifest } = captured!;
expect(manifest.head).toBe(git(work, "rev-parse", "HEAD"));
expect(manifest.prerequisites).toEqual(upstream());
- expect(await currentRestorePointSnapshot(work)).toEqual({ head: manifest.head, index: manifest.index, worktree: manifest.worktree, modes: manifest.modes });
+ expect(await currentRestorePointSnapshot(work)).toEqual({ head: manifest.head, index: manifest.index, worktree: manifest.worktree, ignored: null, modes: manifest.modes });
+ expect(manifest.schema).toBe("paperclip.git-restore-point-payload.v1");
const restored = await freshClone("restored");
expect(() => git(restored, "cat-file", "-e", `${manifest.head}^{commit}`)).toThrow();
@@ -228,6 +230,125 @@ describe("git restore points", () => {
expect(git(restored, "for-each-ref", "refs/paperclip-restore-import/")).toBe("");
});
+ describe("ignored files", () => {
+ async function ignoredWork() {
+ await write(work, ".gitignore", "node_modules/\n.env\n*.tsbuildinfo\nevidence/\ndist/\n");
+ git(work, "commit", "-q", "-am", "ignore build output");
+ git(work, "push", "-q", "origin", "HEAD:master");
+ await write(work, "ui/tsconfig.tsbuildinfo", "{\"version\":\"5\"}\n");
+ await write(work, "evidence/run.log", "agent evidence\n", 0o600);
+ await write(work, "dist/app.js", "regenerable\n");
+ await write(work, "node_modules/pkg/index.js", "regenerable\n");
+ await write(work, ".env", "TOKEN=never-saved\n");
+ }
+
+ it("saves ignored files that are not regenerable, as a v2 payload", async () => {
+ await ignoredWork();
+ const captured = await captureRestorePoint({ cwd: work, upstreamCommits: upstream() });
+ expect(captured).not.toBeNull();
+ const { manifest, payload } = captured!;
+ expect(manifest).toMatchObject({ schema: "paperclip.git-restore-point-payload.v2", index: null, worktree: null, ignored: expect.any(String) });
+ expect(manifest.modes).toEqual([{ path: "evidence/run.log", mode: 0o600 }]);
+ expect(await currentRestorePointSnapshot(work)).toMatchObject({ ignored: manifest.ignored });
+ const restored = await freshClone("restored-ignored");
+ const imported = await importRestorePoint({ repositoryCwd: restored, payload });
+ expect(git(restored, "ls-tree", "-r", "--name-only", manifest.ignored!).split("\n").sort()).toEqual(["evidence/run.log", "ui/tsconfig.tsbuildinfo"]);
+ await applyRestorePoint({ cwd: restored, manifest: imported });
+ expect(await read(restored, "ui/tsconfig.tsbuildinfo")).toBe("{\"version\":\"5\"}\n");
+ expect(await read(restored, "evidence/run.log")).toBe("agent evidence\n");
+ expect((await fs.stat(path.join(restored, "evidence/run.log"))).mode & 0o777).toBe(0o600);
+ for (const missing of ["dist/app.js", "node_modules/pkg/index.js", ".env"]) {
+ await expect(fs.access(path.join(restored, missing))).rejects.toMatchObject({ code: "ENOENT" });
+ }
+ expect(git(restored, "status", "--porcelain")).toBe("");
+ });
+
+ it("fails closed instead of overwriting an existing ignored file", async () => {
+ await ignoredWork();
+ const { payload } = (await captureRestorePoint({ cwd: work, upstreamCommits: upstream() }))!;
+ const restored = await freshClone("restored-conflict");
+ await write(restored, "evidence/run.log", "newer local evidence\n");
+ const imported = await importRestorePoint({ repositoryCwd: restored, payload });
+ await expect(applyRestorePoint({ cwd: restored, manifest: imported })).rejects.toBeInstanceOf(RestorePointRestoreFailure);
+ expect(await read(restored, "evidence/run.log")).toBe("newer local evidence\n");
+ });
+
+ it("restores ignored files byte for byte despite line ending attributes", async () => {
+ await write(work, ".gitattributes", "* text=auto\n");
+ git(work, "add", ".gitattributes"); git(work, "commit", "-q", "-m", "normalize text");
+ git(work, "push", "-q", "origin", "HEAD:master");
+ await ignoredWork();
+ await write(work, "evidence/windows.txt", "line one\r\nline two\r\n");
+ const { manifest, payload } = (await captureRestorePoint({ cwd: work, upstreamCommits: upstream() }))!;
+ const restored = await freshClone("restored-crlf");
+ const imported = await importRestorePoint({ repositoryCwd: restored, payload });
+ await applyRestorePoint({ cwd: restored, manifest: imported });
+ expect(await fs.readFile(path.join(restored, "evidence/windows.txt"))).toEqual(Buffer.from("line one\r\nline two\r\n"));
+ expect(manifest.ignored).toBeDefined();
+ });
+
+ it("removes the files a failed restore wrote, so a retry succeeds", async () => {
+ await ignoredWork();
+ const { payload } = (await captureRestorePoint({ cwd: work, upstreamCommits: upstream() }))!;
+ const restored = await freshClone("restored-partial");
+ await fs.writeFile(path.join(restored, "ui"), "a file where a directory is needed\n");
+ const imported = await importRestorePoint({ repositoryCwd: restored, payload });
+ await expect(applyRestorePoint({ cwd: restored, manifest: imported })).rejects.toBeInstanceOf(RestorePointRestoreFailure);
+ await expect(fs.access(path.join(restored, "evidence/run.log"))).rejects.toMatchObject({ code: "ENOENT" });
+ await fs.rm(path.join(restored, "ui"));
+ await applyRestorePoint({ cwd: restored, manifest: imported });
+ expect(await read(restored, "evidence/run.log")).toBe("agent evidence\n");
+ expect(await read(restored, "ui/tsconfig.tsbuildinfo")).toBe("{\"version\":\"5\"}\n");
+ });
+
+ it("saves a quoted-looking ignored path from inside the workspace, never the file it names", async () => {
+ await ignoredWork();
+ await write(work, ".gitignore", "node_modules/\n.env\n*.tsbuildinfo\nevidence/\ndist/\n\"*\n");
+ git(work, "commit", "-q", "-am", "ignore quoted names");
+ git(work, "push", "-q", "origin", "HEAD:master");
+ const outside = path.join(root, "outside-secret.txt");
+ await fs.writeFile(outside, "outside the workspace\n");
+ const crafted = `"${outside}"`;
+ await write(work, crafted, "workspace file with a quoted name\n");
+ const { payload } = (await captureRestorePoint({ cwd: work, upstreamCommits: upstream() }))!;
+ const restored = await freshClone("restored-quoted");
+ const imported = await importRestorePoint({ repositoryCwd: restored, payload });
+ await applyRestorePoint({ cwd: restored, manifest: imported });
+ expect(await read(restored, crafted)).toBe("workspace file with a quoted name\n");
+ });
+
+ it("keeps an ignored symlink's target bytes exactly", async () => {
+ await ignoredWork();
+ const target = Buffer.from([0x2e, 0x2e, 0x2f, 0x66, 0xff, 0x6f]);
+ try { await fs.symlink(target, path.join(work, "evidence", "odd-link")); }
+ catch { return; }
+ const { payload } = (await captureRestorePoint({ cwd: work, upstreamCommits: upstream() }))!;
+ const restored = await freshClone("restored-link");
+ const imported = await importRestorePoint({ repositoryCwd: restored, payload });
+ await applyRestorePoint({ cwd: restored, manifest: imported });
+ expect(await fs.readlink(path.join(restored, "evidence", "odd-link"), { encoding: "buffer" })).toEqual(target);
+ });
+
+ it("skips an ignored nested repository", async () => {
+ await ignoredWork();
+ git(work, "init", "-q", path.join(work, "evidence/nested"));
+ await write(work, "evidence/nested/file.txt", "inside a nested repository\n");
+ await expect(captureRestorePoint({ cwd: work, upstreamCommits: upstream() })).rejects.toBeInstanceOf(RestorePointSkip);
+ });
+
+ it("rejects a v1 payload that claims an ignored tree", async () => {
+ await ignoredWork();
+ const { payload } = (await captureRestorePoint({ cwd: work, upstreamCommits: upstream() }))!;
+ const magic = Buffer.from("PCRP-PLAIN1\n");
+ const length = payload.readUInt32BE(magic.length);
+ const manifest = JSON.parse(payload.subarray(magic.length + 4, magic.length + 4 + length).toString("utf8"));
+ const bytes = Buffer.from(JSON.stringify({ ...manifest, schema: "paperclip.git-restore-point-payload.v1" }));
+ const size = Buffer.alloc(4); size.writeUInt32BE(bytes.length);
+ const forged = Buffer.concat([magic, size, bytes, payload.subarray(magic.length + 4 + length)]);
+ expect(() => decodeRestorePointPayload(forged)).toThrow(RestorePointRestoreFailure);
+ });
+ });
+
it("skips a nested untracked repository", async () => {
git(root, "init", "-q", path.join(work, "vendor/other"));
await write(work, "vendor/other/file.txt", "x\n");
diff --git a/server/src/services/git-restore-point-storage.ts b/server/src/services/git-restore-point-storage.ts
index a373451506..aea44db582 100644
--- a/server/src/services/git-restore-point-storage.ts
+++ b/server/src/services/git-restore-point-storage.ts
@@ -34,6 +34,7 @@ export type GitRestorePointRef = {
head: string;
index: string | null;
worktree: string | null;
+ ignored?: string;
modes: Array<{ path: string; mode: number }>;
history?: string;
headOnRemote: boolean;
@@ -64,6 +65,7 @@ export function validateGitRestorePointRef(value: unknown, workspace: { companyI
|| !Number.isSafeInteger(ref.generation) || ref.generation < 1
|| !sha.test(ref.head) || (ref.index !== null && !sha.test(ref.index)) || (ref.worktree !== null && !sha.test(ref.worktree))
|| (ref.index === null) !== (ref.worktree === null) || typeof ref.headOnRemote !== "boolean"
+ || (ref.ignored !== undefined && (typeof ref.ignored !== "string" || !sha.test(ref.ignored)))
|| (ref.history !== undefined && !/^[0-9a-f]{64}$/.test(ref.history))
|| !Array.isArray(ref.modes) || ref.modes.length > 20_000 || ref.modes.some((entry) => !entry || typeof entry.path !== "string"
|| entry.path.startsWith("/") || entry.path.split("/").includes("..") || !Number.isInteger(entry.mode) || entry.mode < 0 || entry.mode > 0o777)
@@ -140,6 +142,7 @@ export async function storeGitRestorePoint(input: {
head: manifest.head,
index: manifest.index,
worktree: manifest.worktree,
+ ...(manifest.ignored ? { ignored: manifest.ignored } : {}),
modes: manifest.modes,
history,
headOnRemote: input.headOnRemote,
@@ -167,8 +170,9 @@ export async function restorePointHistoryUnchanged(ref: GitRestorePointRef, cwd:
return ref.history === undefined || await restorePointHistoryDigest(cwd, signal) === ref.history;
}
-export function restorePointSnapshotMatches(ref: GitRestorePointRef, snapshot: { head: string; index: string | null; worktree: string | null; modes: Array<{ path: string; mode: number }> }) {
- return snapshot.head === ref.head && snapshot.index === ref.index && snapshot.worktree === ref.worktree
+export function restorePointSnapshotMatches(ref: GitRestorePointRef, snapshot: { head: string; index: string | null; worktree: string | null;
+ ignored: string | null; modes: Array<{ path: string; mode: number }> }) {
+ return snapshot.head === ref.head && snapshot.index === ref.index && snapshot.worktree === ref.worktree && snapshot.ignored === (ref.ignored ?? null)
&& JSON.stringify(snapshot.modes) === JSON.stringify(ref.modes);
}
@@ -221,6 +225,7 @@ export async function loadGitRestorePoint(input: {
});
const { manifest } = decodeRestorePointPayload(payload);
if (manifest.head !== input.ref.head || manifest.index !== input.ref.index || manifest.worktree !== input.ref.worktree
+ || (manifest.ignored ?? null) !== (input.ref.ignored ?? null)
|| JSON.stringify(manifest.modes) !== JSON.stringify(input.ref.modes)) {
throw new RestorePointRestoreFailure("restore_point_manifest_mismatch");
}
@@ -255,7 +260,7 @@ export async function applyGitRestorePointToWorktree(input: {
}) {
const current = await currentRestorePointSnapshot(input.worktreePath, input.signal);
const matches = restorePointSnapshotMatches(input.ref, current);
- if (!matches && (current.head !== input.ref.head || current.index !== null || current.worktree !== null || current.modes.length > 0)) {
+ if (!matches && (current.head !== input.ref.head || current.index !== null || current.worktree !== null || current.ignored !== null || current.modes.length > 0)) {
throw new RestorePointRestoreFailure("worktree_diverged_from_restore_point");
}
const { payload } = await loadGitRestorePoint(input);
diff --git a/server/src/services/git-restore-point.ts b/server/src/services/git-restore-point.ts
index 7ec96b8f8a..74cbbfcbc1 100644
--- a/server/src/services/git-restore-point.ts
+++ b/server/src/services/git-restore-point.ts
@@ -6,10 +6,12 @@ import path from "node:path";
import { promisify } from "node:util";
import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js";
import type { StoredSecretVersionMaterial } from "../secrets/types.js";
+import { REGENERABLE_WORKSPACE_DIR_NAMES } from "./workspace-compaction.js";
const execFile = promisify(execFileCallback);
export const RESTORE_POINT_PAYLOAD_SCHEMA = "paperclip.git-restore-point-payload.v1";
+export const RESTORE_POINT_PAYLOAD_SCHEMA_V2 = "paperclip.git-restore-point-payload.v2";
const PAYLOAD_MAGIC = Buffer.from("PCRP-PLAIN1\n");
const SEALED_MAGIC = Buffer.from("PCRP1");
const KEY_SCHEMA = "paperclip.git-restore-point-key.v1";
@@ -42,16 +44,30 @@ export const DEFAULT_RESTORE_POINT_LIMITS: RestorePointLimits = {
};
export type RestorePointManifest = {
- schema: typeof RESTORE_POINT_PAYLOAD_SCHEMA;
+ schema: typeof RESTORE_POINT_PAYLOAD_SCHEMA | typeof RESTORE_POINT_PAYLOAD_SCHEMA_V2;
head: string;
index: string | null;
worktree: string | null;
+ ignored?: string;
preserved: string[];
prerequisites: string[];
modes: Array<{ path: string; mode: number }>;
};
-export type RestorePointSnapshot = { head: string; index: string | null; worktree: string | null; modes: Array<{ path: string; mode: number }> };
+export type RestorePointSnapshot = { head: string; index: string | null; worktree: string | null; ignored: string | null;
+ modes: Array<{ path: string; mode: number }> };
+
+export function restorePointSavesIgnoredFile(file: string) {
+ const parts = file.split("/").filter(Boolean);
+ if (parts.length === 0 || /^\.env(\..*)?$/.test(parts[parts.length - 1]!)) return false;
+ if (parts[0] === ".paperclip-repositories" || file === ".claude/settings.local.json") return false;
+ return !parts.slice(0, -1).some(part => REGENERABLE_WORKSPACE_DIR_NAMES.has(part));
+}
+
+async function savedIgnoredFiles(cwd: string, signal?: AbortSignal) {
+ return nulList(await git(cwd, ["ls-files", "-z", "--others", "--ignored", "--exclude-standard"], { signal }))
+ .filter(restorePointSavesIgnoredFile).sort();
+}
export type RestorePointIdentity = { companyId: string; workspaceId: string; restorePointId: string; generation: number };
@@ -144,6 +160,7 @@ async function scanChangedPaths(cwd: string, limits: RestorePointLimits, signal?
...nulList(await git(cwd, ["ls-files", "-z", "--modified"], { signal })),
...nulList(await git(cwd, ["diff", "--cached", "--name-only", "--no-renames", "-z", "HEAD"], { signal })),
...nulList(await git(cwd, ["ls-files", "-z", "--others", "--exclude-standard", "--", ".", ...EXCLUDED_UNTRACKED], { signal })),
+ ...await savedIgnoredFiles(cwd, signal),
]);
if (changed.size > limits.maxFiles) throw new RestorePointSkip("restore_point_too_large");
let totalBytes = 0;
@@ -174,6 +191,88 @@ async function scanChangedPaths(cwd: string, limits: RestorePointLimits, signal?
return { modes: modes.sort((a, b) => a.path.localeCompare(b.path)) };
}
+function quoteGitPath(file: string) {
+ let quoted = "\"";
+ for (const byte of Buffer.from(file, "utf8")) {
+ if (byte === 0x22 || byte === 0x5c) quoted += `\\${String.fromCharCode(byte)}`;
+ else if (byte < 0x20 || byte >= 0x7f) quoted += `\\${byte.toString(8).padStart(3, "0")}`;
+ else quoted += String.fromCharCode(byte);
+ }
+ return `${quoted}"`;
+}
+
+async function rawIgnoredTree(cwd: string, env: Record<string, string>, temporary: string, files: string[], signal?: AbortSignal) {
+ if (files.length === 0) return null;
+ const entries: string[] = [];
+ const regular: string[] = [];
+ for (const file of files) {
+ if (file.endsWith("/")) throw new RestorePointSkip("untracked_nested_repository");
+ if (/[\n\r]/.test(file)) throw new RestorePointSkip("unsupported_path");
+ const stat = await fs.lstat(path.join(cwd, file));
+ if (stat.isSymbolicLink()) {
+ const blob = await gitText(cwd, ["hash-object", "-w", "--no-filters", "--stdin"], { env, signal,
+ input: await fs.readlink(path.join(cwd, file), { encoding: "buffer" }) });
+ entries.push(`120000 ${blob}\t${file}`);
+ } else if (stat.isFile()) regular.push(file);
+ else if (stat.isDirectory()) throw new RestorePointSkip("untracked_nested_repository");
+ else throw new RestorePointSkip("unsupported_special_file");
+ }
+ if (regular.length > 0) {
+ const blobs = (await gitText(cwd, ["hash-object", "-w", "--no-filters", "--stdin-paths"], { env, signal,
+ input: regular.map(quoteGitPath).join("\n") + "\n" })).split("\n");
+ if (blobs.length !== regular.length || blobs.some(blob => !SHA.test(blob))) throw new RestorePointSkip("unsupported_path");
+ for (const [index, file] of regular.entries()) {
+ const mode = (await fs.lstat(path.join(cwd, file))).mode & 0o111 ? "100755" : "100644";
+ entries.push(`${mode} ${blobs[index]}\t${file}`);
+ }
+ }
+ const ignoredEnv = { ...env, GIT_INDEX_FILE: path.join(temporary, "ignored-index") };
+ await git(cwd, ["update-index", "-z", "--index-info"], { env: ignoredEnv, signal, input: entries.join("\0") + "\0" });
+ return await gitText(cwd, ["write-tree"], { env: ignoredEnv, signal });
+}
+
+async function writeIgnoredFiles(cwd: string, commit: string, signal?: AbortSignal) {
+ const listing = nulList(await git(cwd, ["ls-tree", "-r", "-z", `${commit}^{tree}`], { signal }));
+ const entries = listing.map((line) => {
+ const match = /^(100644|100755|120000) blob ([0-9a-f]{40})\t(.+)$/s.exec(line);
+ if (!match) throw new RestorePointRestoreFailure("invalid_payload");
+ const target = path.join(cwd, match[3]!);
+ if (path.isAbsolute(match[3]!) || match[3]!.split("/").includes("..") || !target.startsWith(`${cwd}${path.sep}`)) {
+ throw new RestorePointRestoreFailure("invalid_payload");
+ }
+ return { mode: match[1]!, blob: match[2]!, target };
+ });
+ for (const entry of entries) {
+ if (await fs.lstat(entry.target).then(() => true, () => false)) throw new RestorePointRestoreFailure("ignored_files_conflict");
+ }
+ const contents = await git(cwd, ["cat-file", "--batch"], { signal, input: entries.map((entry) => entry.blob).join("\n") + "\n",
+ maxBuffer: 2 * DEFAULT_RESTORE_POINT_LIMITS.maxTotalBytes });
+ const blobs: Buffer[] = [];
+ let offset = 0;
+ for (const entry of entries) {
+ const header = contents.subarray(offset, contents.indexOf(0x0a, offset)).toString("utf8");
+ const [sha, type, size] = header.split(" ");
+ if (sha !== entry.blob || type !== "blob" || !/^\d+$/.test(size ?? "")) throw new RestorePointRestoreFailure("invalid_payload");
+ const start = offset + header.length + 1;
+ blobs.push(contents.subarray(start, start + Number(size)));
+ offset = start + Number(size) + 1;
+ }
+ const written: string[] = [];
+ try {
+ for (const [index, entry] of entries.entries()) {
+ await fs.mkdir(path.dirname(entry.target), { recursive: true });
+ const parent = await fs.realpath(path.dirname(entry.target));
+ if (parent !== cwd && !parent.startsWith(`${cwd}${path.sep}`)) throw new RestorePointRestoreFailure("invalid_payload");
+ if (entry.mode === "120000") await fs.symlink(blobs[index]!, entry.target);
+ else await fs.writeFile(entry.target, blobs[index]!, { flag: "wx", mode: entry.mode === "100755" ? 0o755 : 0o644 });
+ written.push(entry.target);
+ }
+ } catch (error) {
+ for (const target of written.reverse()) await fs.rm(target, { force: true });
+ throw error instanceof RestorePointRestoreFailure ? error : new RestorePointRestoreFailure("ignored_files_conflict");
+ }
+}
+
async function snapshotTrees(cwd: string, env: Record<string, string>, temporary: string, signal?: AbortSignal) {
const indexCopy = path.join(temporary, "index");
await copyIndex(cwd, indexCopy);
@@ -187,17 +286,20 @@ async function snapshotTrees(cwd: string, env: Record<string, string>, temporary
const worktreeTree = await gitText(cwd, ["write-tree"], { env: worktreeEnv, signal });
const gitlinks = await gitText(cwd, ["ls-tree", "-r", worktreeTree], { env, signal });
if (/^160000 /m.test(gitlinks)) throw new RestorePointSkip("submodules_unsupported");
- return { indexTree, worktreeTree };
+ const ignoredTree = await rawIgnoredTree(cwd, env, temporary, await savedIgnoredFiles(cwd, signal), signal);
+ return { indexTree, worktreeTree, ignoredTree };
}
async function snapshotCommits(cwd: string, env: Record<string, string>, temporary: string, modes: RestorePointSnapshot["modes"], signal?: AbortSignal): Promise<RestorePointSnapshot> {
const head = await gitText(cwd, ["rev-parse", "--verify", "HEAD^{commit}"], { signal });
const headTree = await gitText(cwd, ["rev-parse", "HEAD^{tree}"], { signal });
- const { indexTree, worktreeTree } = await snapshotTrees(cwd, env, temporary, signal);
- if (indexTree === headTree && worktreeTree === headTree) return { head, index: null, worktree: null, modes: [] };
+ const { indexTree, worktreeTree, ignoredTree } = await snapshotTrees(cwd, env, temporary, signal);
+ const ignored = ignoredTree
+ ? await gitText(cwd, ["commit-tree", ignoredTree, "-p", head, "-m", "paperclip restore point ignored files"], { env, signal }) : null;
+ if (indexTree === headTree && worktreeTree === headTree) return { head, index: null, worktree: null, ignored, modes: ignored ? modes : [] };
const index = await gitText(cwd, ["commit-tree", indexTree, "-p", head, "-m", "paperclip restore point index"], { env, signal });
const worktree = await gitText(cwd, ["commit-tree", worktreeTree, "-p", head, "-p", index, "-m", "paperclip restore point worktree"], { env, signal });
- return { head, index, worktree, modes };
+ return { head, index, worktree, ignored, modes };
}
const UNBOUNDED_LIMITS: RestorePointLimits = {
@@ -268,8 +370,10 @@ export function decodeRestorePointPayload(payload: Buffer): { manifest: RestoreP
if (start + length > payload.length) throw new RestorePointRestoreFailure("invalid_payload");
const manifest = JSON.parse(payload.subarray(start, start + length).toString("utf8")) as RestorePointManifest;
const shas = [manifest.head, ...(manifest.index ? [manifest.index] : []), ...(manifest.worktree ? [manifest.worktree] : []),
- ...manifest.preserved, ...manifest.prerequisites];
- if (manifest.schema !== RESTORE_POINT_PAYLOAD_SCHEMA || shas.some((sha) => !SHA.test(sha))
+ ...(manifest.ignored !== undefined ? [manifest.ignored] : []), ...manifest.preserved, ...manifest.prerequisites];
+ const schemaValid = manifest.schema === RESTORE_POINT_PAYLOAD_SCHEMA ? manifest.ignored === undefined
+ : manifest.schema === RESTORE_POINT_PAYLOAD_SCHEMA_V2 && typeof manifest.ignored === "string";
+ if (!schemaValid || shas.some((sha) => typeof sha !== "string" || !SHA.test(sha))
|| (manifest.index === null) !== (manifest.worktree === null)
|| manifest.modes.some((entry) => typeof entry.path !== "string" || path.isAbsolute(entry.path)
|| entry.path.split("/").includes("..") || !Number.isInteger(entry.mode) || entry.mode < 0 || entry.mode > 0o777)) {
@@ -299,9 +403,10 @@ export async function captureRestorePoint(input: {
}
return false;
})();
- if (headOnUpstream && snapshot.worktree === null && preserved.length === 0) return null;
+ if (headOnUpstream && snapshot.worktree === null && snapshot.ignored === null && preserved.length === 0) return null;
const refs: Array<[string, string]> = [["refs/restore/head", snapshot.head]];
if (snapshot.index && snapshot.worktree) refs.push(["refs/restore/index", snapshot.index], ["refs/restore/worktree", snapshot.worktree]);
+ if (snapshot.ignored) refs.push(["refs/restore/ignored", snapshot.ignored]);
preserved.forEach((commit, index) => refs.push([`refs/restore/preserved/${index}`, commit]));
for (const [ref, commit] of refs) await git(store, ["update-ref", ref, commit], { env, signal: input.signal });
const exclusions = boundary.map((commit) => `^${commit}`);
@@ -316,10 +421,11 @@ export async function captureRestorePoint(input: {
if (bundle.length > limits.maxBundleBytes) throw new RestorePointSkip("restore_point_too_large");
const prerequisites = bundlePrerequisites(bundle);
const manifest: RestorePointManifest = {
- schema: RESTORE_POINT_PAYLOAD_SCHEMA,
+ schema: snapshot.ignored ? RESTORE_POINT_PAYLOAD_SCHEMA_V2 : RESTORE_POINT_PAYLOAD_SCHEMA,
head: snapshot.head,
index: snapshot.index,
worktree: snapshot.worktree,
+ ...(snapshot.ignored ? { ignored: snapshot.ignored } : {}),
preserved,
prerequisites,
modes: snapshot.modes,
@@ -345,6 +451,7 @@ export async function importRestorePoint(input: { repositoryCwd: string; payload
expected.set("refs/restore/index", manifest.index);
expected.set("refs/restore/worktree", manifest.worktree);
}
+ if (manifest.ignored) expected.set("refs/restore/ignored", manifest.ignored);
manifest.preserved.forEach((commit, index) => expected.set(`refs/restore/preserved/${index}`, commit));
if (heads.some(([sha, ref]) => expected.get(ref ?? "") !== sha)) throw new RestorePointRestoreFailure("bundle_manifest_mismatch");
const listed = new Set(heads.map(([, ref]) => ref));
@@ -375,6 +482,7 @@ export async function applyRestorePoint(input: { cwd: string; manifest: RestoreP
if (diff.length > 0) await git(cwd, ["apply", "--binary", "--whitespace=nowarn", "-"], { input: diff, signal: input.signal });
await git(cwd, ["read-tree", `${manifest.index}^{tree}`], { signal: input.signal });
}
+ if (manifest.ignored) await writeIgnoredFiles(cwd, manifest.ignored, input.signal);
for (const entry of manifest.modes) {
const target = path.join(cwd, entry.path);
if (path.relative(cwd, target).startsWith("..")) throw new RestorePointRestoreFailure("invalid_payload");
@@ -383,7 +491,7 @@ export async function applyRestorePoint(input: { cwd: string; manifest: RestoreP
}
const restored = await currentRestorePointSnapshot(cwd, input.signal);
if (restored.head !== manifest.head || restored.index !== manifest.index || restored.worktree !== manifest.worktree
- || JSON.stringify(restored.modes) !== JSON.stringify(manifest.modes)) {
+ || restored.ignored !== (manifest.ignored ?? null) || JSON.stringify(restored.modes) !== JSON.stringify(manifest.modes)) {
throw new RestorePointRestoreFailure("restored_contents_mismatch");
}
}
diff --git a/server/src/services/git-workspace-restoration.ts b/server/src/services/git-workspace-restoration.ts
index 017d71c272..82dec297fe 100644
--- a/server/src/services/git-workspace-restoration.ts
+++ b/server/src/services/git-workspace-restoration.ts
@@ -1,3 +1,4 @@
+import { restorePointSavesIgnoredFile } from "./git-restore-point.js";
import { validateGitWorkspaceContents, type GitWorkspaceContents } from "./git-workspace-contents.js";
import { recoverGitExpirationLocks, type GitExpirationLockLocation } from "./git-workspace-expiration-locks.js";
import fs from "node:fs/promises";
@@ -390,7 +391,7 @@ export async function assertReproducibleGitFiles(cwd: string, signal?: AbortSign
const regenerable = await findRegenerableWorkspaceDirs(cwd, { signal });
const ignored = (await gitCacheCommand(cwd, ["ls-files", "--others", "--ignored", "--exclude-standard", "-z"], signal)).split("\0").filter(Boolean);
const unexplained = ignored.filter(file => !(options.preserveSettings && file === PAPERCLIP_CLAUDE_SETTINGS_FILE) && !regenerable.some(dir => file.startsWith(`${dir}/`))
- && !(options.restorePoint && /^\.env(\..*)?$/.test(path.posix.basename(file))));
+ && !(options.restorePoint && (/^\.env(\..*)?$/.test(path.posix.basename(file)) || restorePointSavesIgnoredFile(file))));
const checkouts = new Set<string>();
for (const file of unexplained) {
const [namespace, name, rest] = file.split("/", 3);