Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

A read-only safe-deletion check for a git working copy (not wired in) (#7243)

Milind Soni82446ecaf763
diff --git a/server/git/working-copy-state.test.ts b/server/git/working-copy-state.test.ts
new file mode 100644
index 0000000000..2dc8c98267
--- /dev/null
+++ b/server/git/working-copy-state.test.ts
@@ -0,0 +1,555 @@
+import { execFileSync } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ driverOverrides, gitEnvironment, gitIsRecentEnough, isDisposable, remoteIsOffDisk, samePath, workingCopyState, type WorkKind, type WorkingCopyState,
+} from "./working-copy-state.ts";
+
+const made: string[] = [];
+// Retries: on Windows a stopped git (or the stand-in that never answers) can hold its folder for a moment after taskkill.
+afterEach(() => { for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true, maxRetries: 20, retryDelay: 250 }); });
+
+function scratch(): string {
+ const dir = mkdtempSync(join(tmpdir(), "wcs-"));
+ made.push(dir);
+ return dir;
+}
+
+/** The tests' own git: no config from this machine, a fixed identity, no signing. */
+const testEnv = { ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !/^GIT_/i.test(name))), GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null" };
+function git(cwd: string, ...args: string[]): string {
+ return execFileSync("git", ["-c", "[email protected]", "-c", "user.name=T", "-c", "commit.gpgsign=false", "-c", "tag.gpgsign=false",
+ "-c", "init.defaultBranch=main", "-c", "protocol.file.allow=always", "-c", "core.hooksPath=/dev/null", ...args],
+ { cwd, env: testEnv, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
+}
+function gitMayFail(cwd: string, ...args: string[]): void {
+ try { git(cwd, ...args); } catch {}
+}
+/** As if pushed: an off-disk origin whose remote-tracking ref is at HEAD. */
+function markPushed(dir: string, branch = "main"): void {
+ if (!git(dir, "remote").includes("origin")) git(dir, "remote", "add", "origin", "https://example.invalid/repo.git");
+ git(dir, "update-ref", `refs/remotes/origin/${branch}`, "HEAD");
+}
+function repo(name = "repo"): string {
+ const dir = join(scratch(), name);
+ mkdirSync(dir);
+ git(dir, "init", "-q");
+ writeFileSync(join(dir, "a.txt"), "one\n");
+ writeFileSync(join(dir, ".gitignore"), "node_modules/\n.env\n");
+ git(dir, "add", ".");
+ git(dir, "commit", "-qm", "first");
+ markPushed(dir);
+ return dir;
+}
+function commit(dir: string, file: string, text: string, message = "change"): void {
+ writeFileSync(join(dir, file), text);
+ git(dir, "add", file);
+ git(dir, "commit", "-qm", message);
+}
+function kinds(state: WorkingCopyState): WorkKind[] {
+ return state.state === "has-unpushed-work" ? state.reasons.map((reason) => reason.kind) : [];
+}
+/** Makes git re-read a tracked file: same content, another modification time. */
+function statDirty(file: string): void {
+ const when = new Date(Date.UTC(2020, 0, 1 + Math.floor(Math.random() * 300)));
+ utimesSync(file, when, when);
+}
+
+/** A program that writes `marker` when run and passes its input through (for a clean filter). Forward slashes for git's shell. */
+function markerCommand(dir: string, marker: string): string {
+ const script = join(dir, "mark.mjs");
+ writeFileSync(script, `import { writeFileSync } from "node:fs";\nwriteFileSync(${JSON.stringify(marker)}, "ran");\nprocess.stdin.pipe(process.stdout);\n`);
+ const slash = (path: string) => path.replace(/\\/g, "/");
+ return `"${slash(process.execPath)}" "${slash(script)}"`;
+}
+
+describe("workingCopyState: what it judges", () => {
+ it("calls a folder with no .git not a repo, and a bare repository or a missing folder unknown", async () => {
+ const plain = scratch();
+ writeFileSync(join(plain, "notes.txt"), "x");
+ expect(await workingCopyState(plain)).toEqual({ state: "not-a-repo" });
+ const bare = join(scratch(), "bare.git");
+ git(scratch(), "init", "-q", "--bare", bare);
+ expect((await workingCopyState(bare)).state).toBe("unknown");
+ expect((await workingCopyState(join(plain, "gone"))).state).toBe("unknown");
+ });
+
+ it("calls a clean repository whose every commit is on its remote disposable, ignored files and all", async () => {
+ const dir = repo();
+ mkdirSync(join(dir, "node_modules"));
+ writeFileSync(join(dir, "node_modules", "x.js"), "x");
+ writeFileSync(join(dir, ".env"), "TOKEN=1");
+ const state = await workingCopyState(dir);
+ expect(state).toEqual({ state: "disposable" });
+ expect(isDisposable(state)).toBe(true);
+ });
+
+ it("counts an untracked file that is not ignored, a modified file and a staged file as work", async () => {
+ const untracked = repo();
+ writeFileSync(join(untracked, "new.txt"), "new");
+ expect(kinds(await workingCopyState(untracked))).toEqual(["changes"]);
+ const modified = repo();
+ writeFileSync(join(modified, "a.txt"), "two\n");
+ expect(kinds(await workingCopyState(modified))).toEqual(["changes"]);
+ const staged = repo();
+ writeFileSync(join(staged, "b.txt"), "b");
+ git(staged, "add", "b.txt");
+ const state = await workingCopyState(staged);
+ expect(kinds(state)).toEqual(["changes"]);
+ expect(isDisposable(state)).toBe(false);
+ });
+
+ it("counts commits on no remote as work: a new commit, a local branch, a detached HEAD, a local tag", async () => {
+ const ahead = repo();
+ commit(ahead, "a.txt", "two\n");
+ expect(kinds(await workingCopyState(ahead))).toEqual(["commits"]);
+ const branch = repo();
+ git(branch, "checkout", "-qb", "side");
+ commit(branch, "b.txt", "b");
+ git(branch, "checkout", "-q", "main");
+ expect(kinds(await workingCopyState(branch))).toEqual(["commits"]);
+ const detached = repo();
+ git(detached, "checkout", "-q", "--detach");
+ commit(detached, "b.txt", "b");
+ expect(kinds(await workingCopyState(detached))).toEqual(["commits"]);
+ const tagged = repo();
+ commit(tagged, "b.txt", "b");
+ git(tagged, "tag", "kept");
+ git(tagged, "reset", "-q", "--hard", "origin/main");
+ expect(kinds(await workingCopyState(tagged))).toEqual(["commits"]);
+ });
+
+ it("counts every commit as unpushed when the remote has no remote-tracking refs", async () => {
+ const dir = repo();
+ git(dir, "update-ref", "-d", "refs/remotes/origin/main");
+ expect(kinds(await workingCopyState(dir))).toEqual(["commits"]);
+ });
+
+ it("counts a repository of its own inside an ignored folder as work, however it is ignored", async () => {
+ const nest = (dir: string, inside: string) => {
+ const inner = join(dir, inside);
+ mkdirSync(inner, { recursive: true });
+ git(inner, "init", "-q");
+ writeFileSync(join(inner, "x.txt"), "work");
+ git(inner, "add", "x.txt");
+ git(inner, "commit", "-qm", "only here");
+ };
+ const gitignore = repo();
+ writeFileSync(join(gitignore, ".gitignore"), "node_modules/\n.env\nwork/\n");
+ git(gitignore, "commit", "-qam", "ignore work");
+ markPushed(gitignore);
+ nest(gitignore, "work");
+ expect(git(gitignore, "status", "--porcelain")).toBe("");
+ expect(kinds(await workingCopyState(gitignore))).toEqual(["nested-repo"]);
+
+ const exclude = repo();
+ writeFileSync(join(exclude, ".git", "info", "exclude"), "scratch/\n");
+ nest(exclude, join("scratch", "deep", "down"));
+ expect(git(exclude, "status", "--porcelain")).toBe("");
+ expect(kinds(await workingCopyState(exclude))).toEqual(["nested-repo"]);
+
+ const untracked = repo();
+ nest(untracked, "work");
+ expect(kinds(await workingCopyState(untracked))).toEqual(["changes"]);
+ });
+
+ it("answers unknown when the ignored folders are too many to look through", async () => {
+ const dir = repo();
+ for (let index = 0; index < 10; index++) mkdirSync(join(dir, "node_modules", `p${index}`, "lib"), { recursive: true });
+ expect(await workingCopyState(dir)).toEqual({ state: "disposable" });
+ const state = await workingCopyState(dir, { maxIgnoredFolders: 5 });
+ expect(state.state).toBe("unknown");
+ });
+
+ it("counts a stash as work", async () => {
+ const dir = repo();
+ writeFileSync(join(dir, "a.txt"), "two\n");
+ git(dir, "stash", "-q");
+ expect(kinds(await workingCopyState(dir))).toEqual(["stash"]);
+ });
+
+ it("never calls a repository with no remote, or only remotes that are folders on this disk, disposable", async () => {
+ const none = repo();
+ git(none, "remote", "remove", "origin");
+ expect(kinds(await workingCopyState(none))).toEqual(["no-remote"]);
+ const local = repo();
+ const bare = join(scratch(), "remote.git");
+ git(scratch(), "init", "-q", "--bare", bare);
+ git(local, "remote", "set-url", "origin", bare);
+ git(local, "push", "-q", "origin", "main");
+ const state = await workingCopyState(local);
+ expect(kinds(state)).toEqual(["no-remote"]);
+ expect(state.state === "has-unpushed-work" && state.reasons[0]!.detail).toBe("its only remotes are folders on this disk");
+ git(local, "remote", "set-url", "origin", `file://${bare.replace(/\\/g, "/")}`);
+ expect(kinds(await workingCopyState(local))).toEqual(["no-remote"]);
+ });
+
+ it("does not count a remote whose push address is a folder on this disk", async () => {
+ const bare = join(scratch(), "remote.git");
+ git(scratch(), "init", "-q", "--bare", bare);
+ const pushUrl = repo();
+ commit(pushUrl, "b.txt", "b");
+ git(pushUrl, "remote", "set-url", "--push", "origin", bare);
+ git(pushUrl, "push", "-q", "origin", "main");
+ expect(git(pushUrl, "rev-parse", "origin/main")).toBe(git(pushUrl, "rev-parse", "HEAD"));
+ expect(kinds(await workingCopyState(pushUrl))).toEqual(["no-remote"]);
+
+ const insteadOf = repo();
+ commit(insteadOf, "b.txt", "b");
+ git(insteadOf, "config", `url.${scratch().replace(/\\/g, "/")}/.pushInsteadOf`, "https://example.invalid/");
+ git(insteadOf, "update-ref", "refs/remotes/origin/main", "HEAD");
+ expect(kinds(await workingCopyState(insteadOf))).toEqual(["no-remote"]);
+ });
+
+ it("answers unknown when one remote's name is another's plus /…", async () => {
+ const dir = repo();
+ commit(dir, "b.txt", "b");
+ const bare = join(scratch(), "backup.git");
+ git(scratch(), "init", "-q", "--bare", bare);
+ // Newer git refuses `git remote add origin/backup` next to origin; a bot can still write the config by hand.
+ git(dir, "config", "remote.origin/backup.url", bare);
+ git(dir, "config", "remote.origin/backup.fetch", "+refs/heads/*:refs/remotes/origin/backup/*");
+ git(dir, "push", "-q", "origin/backup", "main");
+ expect(git(dir, "for-each-ref", "--format=%(refname)", "refs/remotes/origin/backup")).toContain("refs/remotes/origin/backup/main");
+ expect((await workingCopyState(dir)).state).toBe("unknown");
+ });
+
+ it("puts no file names in a reason's detail", async () => {
+ const dir = repo();
+ writeFileSync(join(dir, "a.txt"), "two\n");
+ writeFileSync(join(dir, "private-name.txt"), "x");
+ const state = await workingCopyState(dir);
+ expect(kinds(state)).toEqual(["changes"]);
+ expect(JSON.stringify(state)).not.toMatch(/private-name|a\.txt/);
+ });
+
+ it("counts a merge, rebase, cherry-pick, revert or bisect in progress as work", async () => {
+ const conflicted = () => {
+ const dir = repo();
+ git(dir, "checkout", "-qb", "side");
+ commit(dir, "a.txt", "side\n");
+ markPushed(dir, "side");
+ git(dir, "checkout", "-q", "main");
+ commit(dir, "a.txt", "main\n");
+ markPushed(dir);
+ return dir;
+ };
+ const merge = conflicted();
+ gitMayFail(merge, "merge", "-q", "side");
+ const rebase = conflicted();
+ gitMayFail(rebase, "rebase", "-q", "side");
+ const pick = conflicted();
+ gitMayFail(pick, "cherry-pick", "side");
+ const revert = repo();
+ commit(revert, "a.txt", "two\n");
+ commit(revert, "a.txt", "three\n");
+ markPushed(revert);
+ gitMayFail(revert, "revert", "--no-edit", "HEAD~1");
+ const bisect = repo();
+ git(bisect, "bisect", "start");
+ for (const dir of [merge, rebase, pick, revert, bisect]) {
+ expect(existsSync(join(dir, ".git", "MERGE_HEAD")) || existsSync(join(dir, ".git", "rebase-merge")) || existsSync(join(dir, ".git", "rebase-apply"))
+ || existsSync(join(dir, ".git", "CHERRY_PICK_HEAD")) || existsSync(join(dir, ".git", "REVERT_HEAD")) || existsSync(join(dir, ".git", "BISECT_START"))).toBe(true);
+ expect(kinds(await workingCopyState(dir))).toContain("in-progress");
+ }
+ expect(kinds(await workingCopyState(bisect))).toEqual(["in-progress"]);
+ });
+
+ it("judges the main checkout with its linked worktrees, and a linked worktree on its own tree", async () => {
+ const dir = repo();
+ const linked = join(scratch(), "linked");
+ git(dir, "worktree", "add", "-q", "--detach", linked);
+ expect(await workingCopyState(dir)).toEqual({ state: "disposable" });
+ writeFileSync(join(linked, "wip.txt"), "wip");
+ const main = await workingCopyState(dir);
+ expect(kinds(main)).toEqual(["worktree"]);
+ expect(main.state === "has-unpushed-work" && main.reasons[0]!.path).toContain("linked");
+ expect(kinds(await workingCopyState(linked))).toEqual(["changes"]);
+ rmSync(join(linked, "wip.txt"));
+ writeFileSync(join(dir, "wip.txt"), "wip");
+ expect(await workingCopyState(linked)).toEqual({ state: "disposable" });
+ // A commit on the linked worktree's detached HEAD is unpushed from the main checkout too, and only that tree's own.
+ rmSync(join(dir, "wip.txt"));
+ commit(linked, "b.txt", "b");
+ expect(kinds(await workingCopyState(dir))).toEqual(["worktree"]);
+ const own = await workingCopyState(linked);
+ expect(own.state === "has-unpushed-work" && own.reasons.map(({ kind, scope }) => ({ kind, scope }))).toEqual([{ kind: "commits", scope: "this-worktree" }]);
+ });
+
+ it("finds a commit kept only by a linked worktree's refs/worktree/*, from the main checkout", async () => {
+ const dir = repo();
+ const linked = join(scratch(), "linked");
+ git(dir, "worktree", "add", "-q", "--detach", linked);
+ commit(linked, "b.txt", "b");
+ git(linked, "update-ref", "refs/worktree/keep", "HEAD");
+ git(linked, "checkout", "-q", "--detach", "origin/main");
+ const state = await workingCopyState(dir);
+ expect(kinds(state)).toEqual(["worktree"]);
+ expect(state.state === "has-unpushed-work" && state.reasons[0]!.detail).toContain("refs/worktree");
+ });
+
+ it("tells commits on a shared branch from commits only on this working tree's HEAD", async () => {
+ const branch = repo();
+ git(branch, "branch", "side");
+ git(branch, "checkout", "-q", "side");
+ commit(branch, "b.txt", "b");
+ git(branch, "checkout", "-q", "main");
+ const shared = await workingCopyState(branch);
+ expect(shared.state === "has-unpushed-work" && shared.reasons.map(({ kind, scope }) => ({ kind, scope }))).toEqual([{ kind: "commits", scope: "repository" }]);
+ const head = repo();
+ git(head, "checkout", "-q", "--detach");
+ commit(head, "b.txt", "b");
+ const own = await workingCopyState(head);
+ expect(own.state === "has-unpushed-work" && own.reasons.map(({ kind, scope }) => ({ kind, scope }))).toEqual([{ kind: "commits", scope: "this-worktree" }]);
+ });
+
+ it("calls files marked assume-unchanged or skip-worktree hidden changes", async () => {
+ const assumed = repo();
+ git(assumed, "update-index", "--assume-unchanged", "a.txt");
+ writeFileSync(join(assumed, "a.txt"), "changed, but git status says nothing\n");
+ expect(git(assumed, "status", "--porcelain")).toBe("");
+ expect(kinds(await workingCopyState(assumed))).toEqual(["hidden-changes"]);
+ const skipped = repo();
+ git(skipped, "update-index", "--skip-worktree", "a.txt");
+ writeFileSync(join(skipped, "a.txt"), "changed\n");
+ expect(kinds(await workingCopyState(skipped))).toEqual(["hidden-changes"]);
+ });
+
+ it("judges each checked-out submodule as its own working copy", async () => {
+ const source = repo("sub-source");
+ const dir = repo();
+ git(dir, "submodule", "add", "-q", source, "sm");
+ git(dir, "commit", "-qm", "submodule");
+ markPushed(dir);
+ const sm = join(dir, "sm");
+ git(sm, "remote", "set-url", "origin", "https://example.invalid/sub.git");
+ markPushed(sm);
+ expect(await workingCopyState(dir)).toEqual({ state: "disposable" });
+
+ writeFileSync(join(sm, "new.txt"), "x");
+ expect(kinds(await workingCopyState(dir))).toEqual(["submodule"]);
+ rmSync(join(sm, "new.txt"));
+
+ writeFileSync(join(sm, "a.txt"), "stashed\n");
+ git(sm, "stash", "-q");
+ expect(kinds(await workingCopyState(dir))).toEqual(["submodule"]);
+ git(sm, "stash", "drop", "-q");
+
+ // The parent records and "pushes" a submodule commit that the submodule never pushed.
+ commit(sm, "a.txt", "sub work\n");
+ git(dir, "add", "sm");
+ git(dir, "commit", "-qm", "bump");
+ markPushed(dir);
+ expect(git(dir, "status", "--porcelain")).toBe("");
+ const state = await workingCopyState(dir);
+ expect(kinds(state)).toEqual(["submodule"]);
+ expect(state.state === "has-unpushed-work" && state.reasons[0]!.detail).toContain("on no remote");
+ markPushed(sm);
+ expect(await workingCopyState(dir)).toEqual({ state: "disposable" });
+
+ // A submodule moved to a commit the parent has not recorded is a change in the parent.
+ git(sm, "checkout", "-q", "HEAD~1");
+ expect(kinds(await workingCopyState(dir))).toContain("changes");
+ git(sm, "checkout", "-q", "main");
+
+ // Deinit keeps the submodule's repository in .git/modules with no checkout: nothing to judge it by.
+ git(dir, "submodule", "deinit", "-q", "-f", "sm");
+ expect(existsSync(join(dir, ".git", "modules", "sm"))).toBe(true);
+ expect((await workingCopyState(dir)).state).toBe("unknown");
+ });
+
+ it("calls a corrupt repository unknown", async () => {
+ const dir = repo();
+ writeFileSync(join(dir, ".git", "HEAD"), "garbage\n");
+ expect((await workingCopyState(dir)).state).toBe("unknown");
+ });
+
+ it("calls a git that does not answer in time unknown", async () => {
+ const dir = repo();
+ const sleeper = join(scratch(), "sleep.mjs");
+ writeFileSync(sleeper, "setTimeout(() => {}, 30_000);\n");
+ const started = Date.now();
+ const state = await workingCopyState(dir, { git: [process.execPath, sleeper], timeoutMs: 1_500 });
+ expect(state).toEqual({ state: "unknown", detail: "git did not answer in time" });
+ expect(Date.now() - started).toBeLessThan(20_000);
+ expect((await workingCopyState(dir, { git: [join(scratch(), "no-such-git")] })).state).toBe("unknown");
+ });
+});
+
+describe("workingCopyState against a hostile repository config", () => {
+ it("runs no fsmonitor hook the repository names", async () => {
+ const dir = repo();
+ const marker = join(scratch(), "fsmonitor-ran");
+ git(dir, "config", "core.fsmonitor", markerCommand(scratch(), marker));
+ gitMayFail(dir, "status", "--porcelain");
+ expect(existsSync(marker)).toBe(true);
+ rmSync(marker);
+ expect(await workingCopyState(dir)).toEqual({ state: "disposable" });
+ expect(existsSync(marker)).toBe(false);
+ });
+
+ it("runs no clean or process filter, whatever its driver is called", async () => {
+ for (const kind of ["clean", "process"]) {
+ const dir = repo();
+ const driver = `d${Math.random().toString(36).slice(2)}.x`;
+ writeFileSync(join(dir, ".gitattributes"), `*.txt filter=${driver}\n`);
+ git(dir, "add", ".gitattributes");
+ git(dir, "commit", "-qm", "attributes");
+ markPushed(dir);
+ const marker = join(scratch(), `${kind}-ran`);
+ git(dir, "config", `filter.${driver}.${kind}`, markerCommand(scratch(), marker));
+ git(dir, "config", `filter.${driver}.required`, "true");
+ statDirty(join(dir, "a.txt"));
+ gitMayFail(dir, "status", "--porcelain");
+ expect(existsSync(marker), kind).toBe(true);
+ rmSync(marker);
+ statDirty(join(dir, "a.txt"));
+ expect(await workingCopyState(dir)).toEqual({ state: "disposable" });
+ expect(existsSync(marker), kind).toBe(false);
+ }
+ });
+
+ it("runs no filter a submodule's own config names", async () => {
+ const source = repo("sub-source");
+ const dir = repo();
+ git(dir, "submodule", "add", "-q", source, "sm");
+ git(dir, "commit", "-qm", "submodule");
+ markPushed(dir);
+ const sm = join(dir, "sm");
+ git(sm, "remote", "set-url", "origin", "https://example.invalid/sub.git");
+ writeFileSync(join(sm, ".gitattributes"), "*.txt filter=evil\n");
+ git(sm, "add", ".gitattributes");
+ git(sm, "commit", "-qm", "attributes");
+ markPushed(sm);
+ git(dir, "add", "sm");
+ git(dir, "commit", "-qm", "bump");
+ markPushed(dir);
+ const marker = join(scratch(), "sub-filter-ran");
+ git(sm, "config", "filter.evil.clean", markerCommand(scratch(), marker));
+ statDirty(join(sm, "a.txt"));
+ gitMayFail(dir, "status", "--porcelain", "--ignore-submodules=none");
+ expect(existsSync(marker)).toBe(true);
+ rmSync(marker);
+ statDirty(join(sm, "a.txt"));
+ expect(await workingCopyState(dir)).toEqual({ state: "disposable" });
+ expect(existsSync(marker)).toBe(false);
+ });
+
+ it("is not blinded by config that hides untracked files, ignores everything, or skips stat checks", async () => {
+ const hidden = repo();
+ git(hidden, "config", "status.showUntrackedFiles", "no");
+ writeFileSync(join(hidden, "new.txt"), "x");
+ expect(git(hidden, "status", "--porcelain")).toBe("");
+ expect(kinds(await workingCopyState(hidden))).toEqual(["changes"]);
+
+ const excluded = repo();
+ const everything = join(scratch(), "ignore-all");
+ writeFileSync(everything, "*\n");
+ git(excluded, "config", "core.excludesFile", everything);
+ writeFileSync(join(excluded, "new.txt"), "x");
+ expect(git(excluded, "status", "--porcelain")).toBe("");
+ expect(kinds(await workingCopyState(excluded))).toEqual(["changes"]);
+
+ const ignoreStat = repo();
+ git(ignoreStat, "config", "core.ignoreStat", "true");
+ git(ignoreStat, "update-index", "--really-refresh");
+ writeFileSync(join(ignoreStat, "a.txt"), "changed\n");
+ expect(kinds(await workingCopyState(ignoreStat))).not.toEqual([]);
+ });
+
+ it("is not blinded by config that ignores submodules", async () => {
+ const source = repo("sub-source");
+ const dir = repo();
+ git(dir, "submodule", "add", "-q", source, "sm");
+ git(dir, "commit", "-qm", "submodule");
+ markPushed(dir);
+ const sm = join(dir, "sm");
+ git(sm, "remote", "set-url", "origin", "https://example.invalid/sub.git");
+ markPushed(sm);
+ git(dir, "config", "diff.ignoreSubmodules", "all");
+ git(dir, "config", "submodule.sm.ignore", "all");
+ writeFileSync(join(sm, "a.txt"), "changed\n");
+ expect(git(dir, "status", "--porcelain")).toBe("");
+ expect(kinds(await workingCopyState(dir))).toEqual(["submodule"]);
+ });
+
+ it("calls a repository whose core.worktree points elsewhere unknown", async () => {
+ const dir = repo();
+ const elsewhere = scratch();
+ git(dir, "config", "core.worktree", elsewhere);
+ writeFileSync(join(dir, "wip.txt"), "wip");
+ const state = await workingCopyState(dir);
+ expect(state.state).toBe("unknown");
+ });
+
+ it("writes nothing to the repository, even where git status would refresh the index", async () => {
+ const dir = repo();
+ for (let index = 0; index < 20; index++) writeFileSync(join(dir, `f${index}.txt`), `${index}`);
+ git(dir, "add", ".");
+ git(dir, "commit", "-qm", "more");
+ markPushed(dir);
+ for (let index = 0; index < 20; index++) statDirty(join(dir, `f${index}.txt`));
+ const snapshot = () => {
+ const out: string[] = [];
+ const walk = (folder: string) => {
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
+ const path = join(folder, entry.name);
+ if (entry.isDirectory()) walk(path);
+ else { const info = statSync(path); out.push(`${path} ${info.size} ${info.mtimeMs}`); }
+ }
+ };
+ walk(join(dir, ".git"));
+ return out.sort();
+ };
+ const before = snapshot();
+ expect(await workingCopyState(dir)).toEqual({ state: "disposable" });
+ expect(snapshot()).toEqual(before);
+ // Plain git status would have rewritten the index here.
+ git(dir, "status", "--porcelain");
+ expect(snapshot()).not.toEqual(before);
+ });
+});
+
+describe("working-copy-state helpers", () => {
+ it("counts only remotes off this disk", () => {
+ for (const url of ["https://github.com/a/b.git", "http://host/x", "ssh://git@host/x", "git://host/x", "[email protected]:a/b.git", "host:path/x"]) expect(remoteIsOffDisk(url), url).toBe(true);
+ for (const url of ["/srv/repo.git", "../repo", "file:///srv/repo.git", "C:\\repos\\x", "c:/repos/x", "ext::sh -c touch% /tmp/x", "./a:b/c", "fd::17"]) expect(remoteIsOffDisk(url), url).toBe(false);
+ });
+
+ it("asks for git 2.36 or later", () => {
+ for (const version of ["git version 2.36.0", "git version 2.50.1 (Apple Git-155)", "git version 2.45.1.windows.1", "git version 3.0.0"]) expect(gitIsRecentEnough(version), version).toBe(true);
+ for (const version of ["git version 2.35.9", "git version 2.30.2", "git version 1.9.5", "", "garbage"]) expect(gitIsRecentEnough(version), version).toBe(false);
+ });
+
+ it("compares git's paths with Node's, on Windows too", () => {
+ expect(samePath("C:/Users/ash/repo", "C:\\Users\\ash\\repo", "win32")).toBe(true);
+ expect(samePath("c:/users/ash/repo/", "C:\\Users\\Ash\\repo", "win32")).toBe(true);
+ expect(samePath("D:/repo", "C:\\repo", "win32")).toBe(false);
+ expect(samePath("/home/ash/Repo", "/home/ash/repo", "linux")).toBe(false);
+ expect(samePath("/home/ash/repo/", "/home/ash/repo", "linux")).toBe(true);
+ });
+
+ it("blanks every driver the config names, odd names included", () => {
+ const listing = ["core.bare\nfalse", "filter.a=b.c.clean\nrm -rf x", "diff.Weird Name.textconv\nx", "merge.m.driver\nx", "filter.lfs.required\ntrue"].join("\0") + "\0";
+ const env = driverOverrides(listing);
+ const pairs = Array.from({ length: Number(env.GIT_CONFIG_COUNT) }, (_, index) => `${env[`GIT_CONFIG_KEY_${index}`]}=${env[`GIT_CONFIG_VALUE_${index}`]}`);
+ expect(pairs).toEqual([
+ "filter.a=b.c.clean=", "filter.a=b.c.smudge=", "filter.a=b.c.process=", "filter.a=b.c.required=false",
+ "diff.Weird Name.textconv=", "diff.Weird Name.command=", "merge.m.driver=",
+ "filter.lfs.clean=", "filter.lfs.smudge=", "filter.lfs.process=", "filter.lfs.required=false",
+ ]);
+ expect(driverOverrides("core.bare\nfalse\0")).toEqual({});
+ });
+
+ it("gives git an environment with nothing inherited it would act on", () => {
+ const env = gitEnvironment("/work/repo", { PATH: "/bin", GIT_DIR: "/elsewhere", GIT_WORK_TREE: "/x", git_index_file: "/i", GIT_SSH_COMMAND: "evil", PAGER: "evil", SSH_ASKPASS: "evil" });
+ expect(env.GIT_DIR).toBeUndefined();
+ expect(env.GIT_WORK_TREE).toBeUndefined();
+ expect(env.git_index_file).toBeUndefined();
+ expect(env.GIT_SSH_COMMAND).toBeUndefined();
+ expect(env.SSH_ASKPASS).toBeUndefined();
+ expect(env).toMatchObject({ PATH: "/bin", PAGER: "cat", GIT_PAGER: "cat", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_OPTIONAL_LOCKS: "0", GIT_NO_LAZY_FETCH: "1", GIT_TERMINAL_PROMPT: "0", GIT_CEILING_DIRECTORIES: "/work" });
+ });
+});
diff --git a/server/git/working-copy-state.ts b/server/git/working-copy-state.ts
new file mode 100644
index 0000000000..da4f65adfc
--- /dev/null
+++ b/server/git/working-copy-state.ts
@@ -0,0 +1,398 @@
+// Whether a git working copy can be deleted without losing anything: the safe-deletion rule a storage cleanup will use.
+// Nothing calls it yet. It only reads: it never fetches, never runs gc, never refreshes or writes the index, and runs no
+// program the repository names.
+//
+// A folder is "disposable" only when ALL of these hold, for its own working tree and, when it is the main checkout, every
+// linked worktree of the same repository that still exists on disk:
+// - `git status` shows nothing: untracked files that are not ignored count as work (an untracked folder that is its own
+// repository shows there too). Files ignored by the repository's .gitignore files or .git/info/exclude (node_modules,
+// build output, and also an ignored .env) do not count, with one exception: an ignored folder that holds a nested
+// repository (a .git entry anywhere inside it, found by a bounded walk) is work ("nested-repo"), and a walk that hits its
+// bound is "unknown".
+// - every commit reachable from any local ref or HEAD (branches, tags, detached HEADs of every worktree, notes; `--all`
+// without the stash, so stricter than branches alone) is on a remote-tracking ref of a remote whose address is off this
+// disk (https, ssh, git, or user@host:path). A remote that is a folder or a file:// address does not count, and a
+// repository with no such remote is never disposable. Both the fetch and the push addresses must be off the disk (a push
+// to a folder would move refs/remotes/<name>/* and make commits look pushed), and when one remote's name is another's plus
+// "/…" (origin and origin/backup share refs/remotes/origin/…) the answer is "unknown".
+// - from the main checkout, each linked worktree's HEAD and refs/worktree/* are on a remote too. A "commits" reason says
+// whether the commits are on a branch, tag or other ref shared by the repository ("repository") or only on this working
+// tree's HEAD or refs/worktree/* ("this-worktree").
+// - there is no stash, and no rebase, merge, cherry-pick, revert or bisect in progress.
+// - no index entry is marked assume-unchanged, and no skip-worktree entry has a file on disk (git status skips both).
+// - every checked-out submodule is itself disposable (judged the same way, up to 3 levels), points at the commit the parent
+// records, and no submodule repository is kept in .git/modules without a checkout.
+// A folder with no .git entry is "not-a-repo" (a bare repository's folder is "unknown"). A subfolder of a working tree, or a
+// plain folder that holds repositories further down, has no .git entry, so it is "not-a-repo" too: a caller must never read
+// "not-a-repo" as "safe to delete", and must only ask about a repository's top folder.
+//
+// Reasons carry counts and kinds, never file names (a detail is safe to log); `path` is the working tree it was found in.
+//
+// LIMITS, plainly:
+// - It is for clones a bot made in its own working folders, never for a person's own folders.
+// - "disposable" is a statement about the repository's own local records. A bot that controls the folder can forge them:
+// write refs/remotes/origin/x itself, point origin at any https address, or ignore everything in .gitignore. So the caller
+// (storage cleanup) combines this with idle time and never applies it to a person's main work folder.
+// - It judges one folder. A linked worktree's own folder is judged with the repository-wide checks but without its sibling
+// worktrees (deleting it does not delete them); the main checkout is judged with all of them, since its .git holds theirs.
+// - Reflogs are not read: commits reachable only from a reflog (a reset-away branch tip) are not counted as work.
+//
+// Hostile configuration: the repository's .git/config is written by a bot, so it must not make this function run a program
+// or hide work. Every git call here:
+// - runs with an environment stripped of GIT_* and pager/askpass variables, GIT_CONFIG_NOSYSTEM and GIT_CONFIG_GLOBAL=/dev/null
+// (only the repository's own config is read, and only for data), GIT_OPTIONAL_LOCKS=0 plus --no-optional-locks (no index
+// refresh writes), GIT_NO_LAZY_FETCH and protocol.allow=never (a partial clone cannot fetch, so no ssh, ext:: or
+// uploadpack program), --no-pager, --no-replace-objects, and GIT_CEILING_DIRECTORIES at the folder's parent.
+// - overrides on the command line: core.fsmonitor=false, core.hooksPath=/dev/null, core.pager=cat, credential.helper=,
+// core.alternateRefsCommand=, log.showSignature=false, submodule.recurse=false, core.excludesFile=/dev/null, and the
+// settings that hide changes (core.ignoreStat, core.checkStat, core.trustctime).
+// - lists the repository's config first and blanks every filter.<name>.clean/smudge/process (with required=false),
+// diff.<name>.textconv/command and merge.<name>.driver it names, then lists it again at the end and answers "unknown" if it
+// changed in between (the window a running bot could otherwise use).
+// - uses only commands that never call a pager, signature program, editor, alias or hook: rev-parse, config --list, remote,
+// status (with --untracked-files=normal, --ignore-submodules=dirty so no git runs inside a submodule with the parent's
+// overrides, --no-renames), rev-list, for-each-ref, ls-files and worktree list. Submodules are opened one by one with
+// their own config listed and blanked the same way.
+// - does not trust safe.directory from anywhere but git's own default: a repository owned by another user is refused by git
+// and answered "unknown".
+// Any git error, timeout (one deadline across every call, default 30 s), unreadable repository, unexpected output or a git
+// older than 2.36 (which would ignore GIT_CONFIG_COUNT, so the driver blanking) is "unknown", which is never disposable.
+import { spawn } from "node:child_process";
+import { existsSync, lstatSync, readdirSync, realpathSync, statSync } from "node:fs";
+import { readdir } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+import { OWN_GROUP, stopGroup } from "../group-exec.ts";
+
+export type WorkKind = "changes" | "commits" | "stash" | "in-progress" | "no-remote" | "hidden-changes" | "submodule" | "worktree" | "nested-repo";
+/** `scope` only on "commits": on a ref the repository shares, or only on this working tree's HEAD or refs/worktree/*. */
+export type WorkReason = { kind: WorkKind; path: string; detail: string; scope?: "repository" | "this-worktree" };
+export type WorkingCopyState =
+ | { state: "not-a-repo" }
+ | { state: "disposable" }
+ | { state: "has-unpushed-work"; reasons: WorkReason[] }
+ | { state: "unknown"; detail: string };
+
+export type WorkingCopyOptions = {
+ /** One deadline across every git call. */
+ timeoutMs?: number;
+ /** The git command line prefix; tests swap in a stand-in. */
+ git?: readonly string[];
+ /** How many folders the walk of ignored folders for nested repositories may open before answering "unknown". */
+ maxIgnoredFolders?: number;
+};
+
+export function isDisposable(state: WorkingCopyState): boolean {
+ return state.state === "disposable";
+}
+
+const DEFAULT_TIMEOUT_MS = 30_000;
+const MAX_SUBMODULE_DEPTH = 3;
+const MAX_SUBMODULES = 50;
+const MAX_LISTING_BYTES = 64 * 1024 * 1024;
+const MAX_IGNORED_FOLDERS = 50_000;
+const MAX_IGNORED_DEPTH = 40;
+
+class Unknown extends Error {}
+
+const STATIC_OVERRIDES = [
+ "core.fsmonitor=false", "core.hooksPath=/dev/null", "core.pager=cat", "credential.helper=", "core.alternateRefsCommand=",
+ "protocol.allow=never", "log.showSignature=false", "submodule.recurse=false", "core.excludesFile=/dev/null",
+ "core.ignoreStat=false", "core.checkStat=default", "core.trustctime=true", "core.untrackedCache=false", "gc.auto=0",
+ "maintenance.auto=false", "core.useReplaceRefs=false",
+];
+/** Config keys whose value is a program git may run while reading a working tree. */
+const DRIVER_KEY = /^(filter)\.(.+)\.(clean|smudge|process|required)$|^(diff)\.(.+)\.(textconv|command)$|^(merge)\.(.+)\.(driver)$/s;
+const IN_PROGRESS: Array<[string, string]> = [
+ ["rebase-merge", "rebase"], ["rebase-apply", "rebase"], ["MERGE_HEAD", "merge"], ["CHERRY_PICK_HEAD", "cherry-pick"],
+ ["REVERT_HEAD", "revert"], ["sequencer", "cherry-pick or revert"], ["BISECT_LOG", "bisect"], ["BISECT_START", "bisect"],
+];
+
+/** The environment every git call gets: nothing inherited that git reads, nothing that names a program. */
+export function gitEnvironment(folder: string, env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
+ const dropped = /^(GIT_|SSH_ASKPASS$|PAGER$|LESS$|EDITOR$|VISUAL$|XDG_CONFIG_HOME$)/i;
+ const kept = Object.fromEntries(Object.entries(env).filter(([name]) => !dropped.test(name)));
+ return {
+ ...kept,
+ GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", GIT_ATTR_NOSYSTEM: "1", GIT_OPTIONAL_LOCKS: "0",
+ GIT_TERMINAL_PROMPT: "0", GIT_NO_LAZY_FETCH: "1", GIT_NO_REPLACE_OBJECTS: "1", GIT_PAGER: "cat", PAGER: "cat",
+ GIT_CEILING_DIRECTORIES: dirname(folder), LC_ALL: "C",
+ };
+}
+
+/** Blank every driver program the repository's config names (`git config --list -z` output). */
+export function driverOverrides(listing: string): Record<string, string> {
+ const env: Record<string, string> = {};
+ const seen = new Set<string>();
+ const add = (key: string, value: string) => {
+ if (seen.has(key)) return;
+ seen.add(key);
+ const index = seen.size - 1;
+ env[`GIT_CONFIG_KEY_${index}`] = key;
+ env[`GIT_CONFIG_VALUE_${index}`] = value;
+ };
+ for (const entry of listing.split("\0")) {
+ const key = entry.split("\n", 1)[0]!;
+ const match = DRIVER_KEY.exec(key);
+ if (!match) continue;
+ if (match[1]) {
+ for (const name of ["clean", "smudge", "process"]) add(`filter.${match[2]}.${name}`, "");
+ add(`filter.${match[2]}.required`, "false");
+ }
+ if (match[4]) {
+ add(`diff.${match[5]}.textconv`, "");
+ add(`diff.${match[5]}.command`, "");
+ }
+ if (match[7]) add(`merge.${match[8]}.driver`, "");
+ }
+ return seen.size ? { ...env, GIT_CONFIG_COUNT: String(seen.size) } : {};
+}
+
+/** True when a remote address is off this disk (https, http, ssh, git, or scp-like user@host:path); a folder or file:// is not. */
+export function remoteIsOffDisk(url: string): boolean {
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(url)?.[1]?.toLowerCase();
+ if (scheme) return ["https", "http", "ssh", "git", "git+ssh", "ssh+git"].includes(scheme);
+ if (/^[a-z]:[\\/]/i.test(url) || url.includes("::")) return false;
+ // scp-like: a colon before the first slash.
+ const colon = url.indexOf(":");
+ return colon > 0 && (url.indexOf("/") === -1 || colon < url.indexOf("/"));
+}
+
+/** `git version` output names 2.36 or later. */
+export function gitIsRecentEnough(version: string): boolean {
+ const match = /git version (\d+)\.(\d+)/.exec(version);
+ return Boolean(match) && (Number(match![1]) > 2 || (Number(match![1]) === 2 && Number(match![2]) >= 36));
+}
+
+/** Two locations are the same folder: git prints C:/x/y on Windows where Node has C:\x\y, and Windows ignores case. */
+export function samePath(a: string, b: string, platform: NodeJS.Platform = process.platform): boolean {
+ const norm = (value: string) => {
+ let out = value.replace(/\\/g, "/").replace(/\/+$/, "");
+ if (platform === "win32") out = out.toLowerCase();
+ return out;
+ };
+ return norm(a) === norm(b);
+}
+
+function real(path: string): string {
+ return realpathSync.native(path);
+}
+
+type Run = (cwd: string, args: string[], options?: { allowExit?: number[]; stopAfterBytes?: number }) => Promise<{ code: number; stdout: string }>;
+type Context = { run: Run; overrides: Map<string, Record<string, string>>; deadline: number; ignoredFolders: { left: number }; covered: Set<string> };
+
+function runner(options: WorkingCopyOptions): Context {
+ const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
+ const [command, ...prefix] = options.git ?? ["git"];
+ const overrides = new Map<string, Record<string, string>>();
+ const run: Run = (cwd, args, { allowExit = [0], stopAfterBytes } = {}) => new Promise((done, fail) => {
+ const left = deadline - Date.now();
+ if (left <= 0) return fail(new Unknown("git did not answer in time"));
+ const full = [...prefix, "--no-pager", "--no-optional-locks", "--no-replace-objects",
+ ...STATIC_OVERRIDES.flatMap((setting) => ["-c", setting]), ...args];
+ const child = spawn(command!, full, { cwd, env: { ...gitEnvironment(cwd), ...overrides.get(cwd) }, stdio: ["ignore", "pipe", "pipe"], ...OWN_GROUP });
+ let stdout = "", stderr = "", truncated = false, settled = false;
+ const settle = (fn: () => void) => { if (!settled) { settled = true; clearTimeout(timer); fn(); } };
+ const timer = setTimeout(() => { stopGroup(child, 0); settle(() => fail(new Unknown("git did not answer in time"))); }, left);
+ child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
+ stdout += chunk;
+ const cap = stopAfterBytes ?? MAX_LISTING_BYTES;
+ if (stdout.length > cap && !truncated) {
+ truncated = true;
+ stopGroup(child, 0);
+ if (stopAfterBytes) settle(() => done({ code: 0, stdout }));
+ else settle(() => fail(new Unknown(`git ${args[0]} wrote too much`)));
+ }
+ });
+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => { if (stderr.length < 4_000) stderr += chunk; });
+ child.once("error", (error) => settle(() => fail(new Unknown(`git could not run: ${error.message}`))));
+ child.once("close", (code, signal) => settle(() => {
+ if (signal || code === null || !allowExit.includes(code)) fail(new Unknown(`git ${args[0]} failed: ${stderr.trim().split("\n").at(-1) || `exit ${code ?? signal}`}`));
+ else done({ code, stdout });
+ }));
+ });
+ return { run, overrides, deadline, ignoredFolders: { left: options.maxIgnoredFolders ?? MAX_IGNORED_FOLDERS }, covered: new Set() };
+}
+
+/** Walks an ignored folder for a .git entry, without following links. True when one is found. */
+async function holdsRepository(ctx: Context, start: string): Promise<boolean> {
+ const stack: Array<[string, number]> = [[start, 0]];
+ while (stack.length) {
+ const [dir, depth] = stack.pop()!;
+ if (Date.now() > ctx.deadline) throw new Unknown("git did not answer in time");
+ if (--ctx.ignoredFolders.left < 0) throw new Unknown("too many ignored folders to look through for nested repositories");
+ let entries;
+ try { entries = await readdir(dir, { withFileTypes: true }); } catch { throw new Unknown("an ignored folder could not be read"); }
+ for (const entry of entries) {
+ if (entry.name === ".git") return true;
+ if (!entry.isDirectory()) continue;
+ if (depth + 1 > MAX_IGNORED_DEPTH) throw new Unknown("ignored folders nested too deeply to look through");
+ stack.push([join(dir, entry.name), depth + 1]);
+ }
+ }
+ return false;
+}
+
+type Tree = { path: string; gitDir: string; commonDir: string };
+
+/** rev-parse in `folder`, which must be the top of its own working tree. */
+async function openTree(ctx: Context, folder: string): Promise<Tree> {
+ const { stdout } = await ctx.run(folder, ["rev-parse", "--path-format=absolute", "--is-bare-repository", "--show-toplevel", "--git-dir", "--git-common-dir"]);
+ const [bare, top, gitDir, commonDir] = stdout.split("\n");
+ if (bare !== "false" || !top || !gitDir || !commonDir) throw new Unknown("not a working tree");
+ if (!samePath(real(top), folder)) throw new Unknown("git's working tree for this folder is another folder");
+ ctx.overrides.set(folder, driverOverrides((await ctx.run(folder, ["config", "--list", "-z"])).stdout));
+ return { path: folder, gitDir: real(gitDir), commonDir: real(commonDir) };
+}
+
+async function configUnchanged(ctx: Context, folder: string): Promise<void> {
+ const now = driverOverrides((await ctx.run(folder, ["config", "--list", "-z"])).stdout);
+ if (JSON.stringify(now) !== JSON.stringify(ctx.overrides.get(folder))) throw new Unknown("the repository's config changed while it was read");
+}
+
+/** Remotes whose fetch and push addresses are all off this disk. */
+async function offDiskRemotes(ctx: Context, folder: string): Promise<{ names: string[]; offDisk: string[] }> {
+ const names = (await ctx.run(folder, ["remote"])).stdout.split("\n").filter(Boolean);
+ // refs/remotes/origin/* holds origin/backup's refs too: which remote a ref belongs to can't be told apart.
+ if (names.some((name) => names.some((other) => other.startsWith(`${name}/`)))) throw new Unknown("one remote's name is another's plus /…");
+ const offDisk: string[] = [];
+ for (const name of names) {
+ const fetch = (await ctx.run(folder, ["remote", "get-url", "--all", name])).stdout.split("\n").filter(Boolean);
+ const push = (await ctx.run(folder, ["remote", "get-url", "--push", "--all", name])).stdout.split("\n").filter(Boolean);
+ if (fetch.length && push.length && [...fetch, ...push].every(remoteIsOffDisk)) offDisk.push(name);
+ }
+ return { names, offDisk };
+}
+
+const any = async (ctx: Context, cwd: string, args: string[]) => (await ctx.run(cwd, ["rev-list", "--max-count=1", ...args])).stdout.trim() !== "";
+/** Every ref the repository shares, as rev-list arguments: not the stash, remote-tracking, per-worktree or bisect refs. */
+const SHARED_REFS = ["--exclude=refs/stash", "--exclude=refs/remotes/*", "--exclude=refs/worktree/*", "--exclude=refs/bisect/*", "--glob=refs/*"];
+
+/** Commits on no off-disk remote, seen from `tree`: on a ref the repository shares, or only on this tree's HEAD and refs/worktree/*. */
+async function commitReasons(ctx: Context, tree: Tree, offDisk: string[]): Promise<WorkReason[]> {
+ const remotes = offDisk.map((name) => `--remotes=${name}`);
+ const reasons: WorkReason[] = [];
+ if (await any(ctx, tree.path, [...SHARED_REFS, "--not", ...remotes])) {
+ reasons.push({ kind: "commits", scope: "repository", path: tree.path, detail: "commits on a branch, tag or other shared ref that are on no remote" });
+ }
+ const born = (await ctx.run(tree.path, ["rev-parse", "--verify", "-q", "HEAD"], { allowExit: [0, 1] })).code === 0;
+ if (await any(ctx, tree.path, [...(born ? ["HEAD"] : []), "--glob=refs/worktree/*", "--not", ...SHARED_REFS, ...remotes])) {
+ reasons.push({ kind: "commits", scope: "this-worktree", path: tree.path, detail: "commits only on this working tree's HEAD or refs/worktree/*, on no remote" });
+ }
+ return reasons;
+}
+
+/** What one working tree holds that is not in a commit: changes, hidden entries, nested repositories, an operation, submodules. */
+async function treeReasons(ctx: Context, tree: Tree, depth: number): Promise<WorkReason[]> {
+ const reasons: WorkReason[] = [];
+ const status = await ctx.run(tree.path, ["status", "--porcelain=v1", "-z", "--untracked-files=normal", "--ignore-submodules=dirty", "--no-renames"], { stopAfterBytes: 64 * 1024 });
+ const changed = status.stdout.split("\0").filter(Boolean).length;
+ if (changed) reasons.push({ kind: "changes", path: tree.path, detail: `${changed}${changed > 1000 ? "+" : ""} uncommitted or untracked file(s) or folder(s)` });
+ for (const [file, operation] of IN_PROGRESS) {
+ if (existsSync(join(tree.gitDir, file))) { reasons.push({ kind: "in-progress", path: tree.path, detail: `a ${operation} is in progress` }); break; }
+ }
+ // An ignored folder that is, or holds, a repository of its own: its commits are nowhere in this one.
+ let nested = 0;
+ for (const entry of (await ctx.run(tree.path, ["ls-files", "-o", "-i", "--exclude-standard", "--directory", "-z"])).stdout.split("\0").filter(Boolean)) {
+ const path = resolve(tree.path, entry);
+ let folder = false;
+ try { folder = lstatSync(path).isDirectory(); } catch {}
+ if (folder && await holdsRepository(ctx, path)) nested++;
+ }
+ if (nested) reasons.push({ kind: "nested-repo", path: tree.path, detail: `${nested} ignored folder(s) holding a repository of their own` });
+ const entries = (await ctx.run(tree.path, ["ls-files", "-s", "-v", "-z"])).stdout.split("\0").filter(Boolean);
+ const gitlinks: Array<{ path: string; sha: string }> = [];
+ let hidden = 0;
+ for (const entry of entries) {
+ const match = /^(\S) (\d{6}) ([0-9a-f]{40,64}) \d\t(.+)$/s.exec(entry);
+ if (!match) throw new Unknown("unexpected ls-files output");
+ const [, tag, mode, sha, path] = match as unknown as [string, string, string, string, string];
+ if (/[a-z]/.test(tag)) hidden++;
+ else if (tag === "S" && existsSync(join(tree.path, path))) hidden++;
+ if (mode === "160000") gitlinks.push({ path, sha });
+ }
+ if (hidden) reasons.push({ kind: "hidden-changes", path: tree.path, detail: `${hidden} file(s) marked assume-unchanged or skip-worktree that git status does not check` });
+ if (gitlinks.length > MAX_SUBMODULES) throw new Unknown("too many submodules");
+ for (const link of gitlinks) {
+ const path = resolve(tree.path, link.path);
+ if (!existsSync(join(path, ".git"))) {
+ if (existsSync(path) && readdirSync(path).length) throw new Unknown("a submodule folder has files but no repository");
+ continue;
+ }
+ if (depth >= MAX_SUBMODULE_DEPTH) throw new Unknown("submodules nested too deeply");
+ const subFolder = real(path);
+ const sub = await judge(ctx, subFolder, depth + 1);
+ if (sub.state === "unknown") throw new Unknown(`a submodule: ${sub.detail}`);
+ if (sub.state === "not-a-repo") throw new Unknown("a submodule is not a repository");
+ if (sub.state === "has-unpushed-work") reasons.push({ kind: "submodule", path, detail: sub.reasons.map((reason) => reason.detail).join("; ") });
+ const head = (await ctx.run(subFolder, ["rev-parse", "--verify", "HEAD"])).stdout.trim();
+ if (head !== link.sha) reasons.push({ kind: "changes", path: tree.path, detail: "a submodule is at a commit the parent has not recorded" });
+ }
+ return reasons;
+}
+
+/** Repository directories under <git dir>/modules, not descending into one once found. */
+function moduleRepositories(dir: string, depth = 0): string[] {
+ if (depth > 6 || !existsSync(dir)) return [];
+ if (existsSync(join(dir, "HEAD")) && existsSync(join(dir, "objects"))) return [real(dir)];
+ return readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).flatMap((entry) => moduleRepositories(join(dir, entry.name), depth + 1));
+}
+
+async function judge(ctx: Context, folder: string, depth: number): Promise<WorkingCopyState> {
+ const tree = await openTree(ctx, folder);
+ ctx.covered.add(tree.gitDir);
+ const reasons: WorkReason[] = [];
+ const { names, offDisk } = await offDiskRemotes(ctx, folder);
+ if (!offDisk.length) reasons.push({ kind: "no-remote", path: folder, detail: names.length ? "its only remotes are folders on this disk" : "it has no remote" });
+ else {
+ reasons.push(...await commitReasons(ctx, tree, offDisk));
+ }
+ if ((await ctx.run(folder, ["for-each-ref", "--count=1", "--format=%(refname)", "refs/stash"])).stdout.trim()) reasons.push({ kind: "stash", path: folder, detail: "a stash" });
+ reasons.push(...await treeReasons(ctx, tree, depth));
+ let commitsSeen = reasons.some((reason) => reason.kind === "commits");
+ // The main checkout's .git holds every linked worktree's state: judge those trees too, with their own HEAD and refs/worktree/*.
+ const listing = (await ctx.run(folder, ["worktree", "list", "--porcelain", "-z"])).stdout.split("\0");
+ const worktrees = listing.filter((line) => line.startsWith("worktree ")).map((line) => line.slice("worktree ".length));
+ if (worktrees[0] && existsSync(worktrees[0]) && samePath(real(worktrees[0]), folder)) {
+ for (const other of worktrees.slice(1)) {
+ if (!existsSync(other)) continue;
+ const linked = await openTree(ctx, real(other));
+ ctx.covered.add(linked.gitDir);
+ const own = offDisk.length ? (await commitReasons(ctx, linked, offDisk)).filter((reason) => reason.scope === "this-worktree") : [];
+ commitsSeen ||= own.length > 0;
+ const found = [...own, ...await treeReasons(ctx, linked, depth)];
+ if (found.length) reasons.push({ kind: "worktree", path: linked.path, detail: found.map((reason) => reason.detail).join("; ") });
+ await configUnchanged(ctx, linked.path);
+ }
+ }
+ // What neither check saw: another working tree's HEAD, such as one whose folder is gone.
+ if (offDisk.length && !commitsSeen && await any(ctx, folder, ["--exclude=refs/stash", "--all", "--not", ...offDisk.map((name) => `--remotes=${name}`)])) {
+ reasons.push({ kind: "commits", scope: "repository", path: folder, detail: "commits on another working tree's HEAD that are on no remote" });
+ }
+ // A submodule repository kept in .git/modules without a checkout may hold commits that are nowhere else.
+ for (const dir of new Set([join(tree.commonDir, "modules"), join(tree.gitDir, "modules")])) {
+ for (const repository of moduleRepositories(dir)) {
+ if (!ctx.covered.has(repository)) throw new Unknown("a submodule repository in .git/modules has no checkout to judge");
+ }
+ }
+ await configUnchanged(ctx, folder);
+ return reasons.length ? { state: "has-unpushed-work", reasons } : { state: "disposable" };
+}
+
+/** Whether `folder` (the top folder of a clone a bot made) can be deleted with nothing lost. Never throws; read-only. */
+export async function workingCopyState(folder: string, options: WorkingCopyOptions = {}): Promise<WorkingCopyState> {
+ try {
+ if (!existsSync(folder) || !statSync(folder).isDirectory()) return { state: "unknown", detail: "the folder is missing" };
+ const root = real(folder);
+ try { lstatSync(join(root, ".git")); } catch {
+ // A bare repository's folder holds commits but no .git entry.
+ if (existsSync(join(root, "HEAD")) && existsSync(join(root, "objects"))) return { state: "unknown", detail: "a bare repository" };
+ return { state: "not-a-repo" };
+ }
+ const ctx = runner(options);
+ // Older git ignores GIT_CONFIG_COUNT (so the driver blanking) and lacks `worktree list -z`.
+ if (!gitIsRecentEnough((await ctx.run(root, ["version"])).stdout)) return { state: "unknown", detail: "git is older than 2.36" };
+ return await judge(ctx, root, 0);
+ } catch (error) {
+ return { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
+ }
+}