Cotton code
473 lines · 18.8 KB · TypeScriptRaw
/** * The per-branch cargo target directories a developer machine collects, and the * three rules that bound them. * * `worktree-new.sh` gives each BRANCH its own target directory under * `~/.cache/cottondb/cargo-target` (2026-09-15), which ends the two problems a * shared one had — one worktree handed another's compiled crates, and a * touch-guard that made every alternation a full rebuild — and buys the CI * lanes' own problem in exchange: a merged branch's 15-25 GB is never touched * again. So the same three rules apply here: * *   DEAD    — the branch is gone from EVERY remote this checkout has, which *             after a squash-merge is every branch that shipped. The union and *             not the home remote alone: a branch pushed to another remote and *             not yet to the home one is live, and asking one remote alone *             deleted two live branches' targets on 2026-09-27; *   AGE     — nothing has touched it for `--days`; *   BUDGET  — and LAST, in gigabytes: evict oldest-first until the set fits. * * The one that matters most is what it REFUSES: a path that does not resolve * inside the root, symlinks included. */import { execFileSync, spawnSync } from "node:child_process";import {  existsSync,  mkdirSync,  mkdtempSync,  rmSync,  symlinkSync,  utimesSync,  writeFileSync,} from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { afterEach, describe, expect, it } from "vitest";const ROOT = resolve(__dirname, "../..");const SCRIPT = join(ROOT, "scripts/sweep-worktree-targets.sh");let scratch = "";afterEach(() => {  if (scratch) rmSync(scratch, { recursive: true, force: true });  scratch = "";});type Fixture = { root: string; origin: string; repo: string; other?: string };/** * A targets root, and real remotes the dead-branch rule can be asked about. * * `branches` land on `origin`. `options.otherBranches` creates a SECOND remote * named `other` and pushes those branches to it alone. */function makeFixture(branches: string[] = [], options: { otherBranches?: string[] } = {}): Fixture {  scratch = mkdtempSync(join(tmpdir(), "sweep-worktree-targets-"));  const root = join(scratch, "cargo-target");  mkdirSync(root, { recursive: true });  const origin = join(scratch, "origin.git");  execFileSync("git", ["init", "-q", "--bare", "-b", "main", origin]);  const repo = join(scratch, "repo");  execFileSync("git", ["clone", "-q", origin, repo]);  const git = (...args: string[]) =>    execFileSync("git", ["-C", repo, ...args], { encoding: "utf8", stdio: "pipe" });  git("config", "user.email", "t@t.test");  git("config", "user.name", "t");  writeFileSync(join(repo, "seed.txt"), "seed\n");  git("add", "-A");  git("commit", "-q", "-m", "seed");  git("push", "-q", "origin", "main");  for (const branch of branches) {    git("checkout", "-q", "-b", branch);    git("push", "-q", "origin", branch);    git("checkout", "-q", "main");  }  let other: string | undefined;  if (options.otherBranches) {    other = join(scratch, "other.git");    execFileSync("git", ["init", "-q", "--bare", "-b", "main", other]);    git("remote", "add", "other", other);    git("push", "-q", "other", "main");    for (const branch of options.otherBranches) {      git("checkout", "-q", "-b", branch);      git("push", "-q", "other", branch);      git("checkout", "-q", "main");    }  }  return { root, origin, repo, other };}/** A branch target of a given size, with the two levels a real one has. */function target(f: Fixture, name: string, kb = 16): string {  const dir = join(f.root, name);  mkdirSync(join(dir, "debug", "deps"), { recursive: true });  writeFileSync(join(dir, "debug", "deps", "blob.rlib"), Buffer.alloc(kb * 1024, 1));  writeFileSync(join(dir, "CACHEDIR.TAG"), "Signature: 8a477f597d28d172789f06886806bc55\n");  return dir;}/** Push a whole target back past a window. Children first; the directory last. */function backdate(dir: string, daysAgo: number): void {  const when = new Date(Date.now() - daysAgo * 86_400_000);  for (const p of [    join(dir, "debug", "deps", "blob.rlib"),    join(dir, "debug", "deps"),    join(dir, "debug"),    join(dir, "CACHEDIR.TAG"),    dir,  ]) {    if (existsSync(p)) utimesSync(p, when, when);  }}/** The same, in minutes — the unit both grace windows are stated in. */function minutesAgo(dir: string, mins: number): void {  const when = new Date(Date.now() - mins * 60_000);  for (const p of [    join(dir, "debug", "deps", "blob.rlib"),    join(dir, "debug", "deps"),    join(dir, "debug"),    join(dir, "CACHEDIR.TAG"),    dir,  ]) {    if (existsSync(p)) utimesSync(p, when, when);  }}/** What the script itself will measure — `du -sk`, in KiB of allocated blocks. */function du(dir: string): number {  return Number(execFileSync("du", ["-sk", dir], { encoding: "utf8" }).split(/\s+/)[0]);}function run(f: Fixture, args: string[] = [], env: Record<string, string> = {}) {  return spawnSync("bash", [SCRIPT, "--root", f.root, ...args], {    encoding: "utf8",    timeout: 20000,    // From the clone, so `git ls-remote --heads origin` has a remote to ask.    cwd: f.repo,    // A LOCK PATH THAT DOES NOT EXIST, unless a case says otherwise. The sweep    // reads the machine-wide build lock to spare the branch a live holder is    // building; left at its default these tests would read whatever this Mac is    // really building and a case would pass or fail by what else is running.    env: { ...process.env, BUILD_LOCK_DIR: join(f.root, "..", "no-such-lock"), ...env },  });}describe("the dead-branch rule", () => {  // RULE: A branch target is deleted only when its branch is gone from every remote, so a branch that lives only on another remote survives.  it("KEEPS a target whose branch exists only on another remote, not on the home one", () => {    // The failure, exactly as it happened: two branches pushed to one remote    // and not yet to another, and the sweep read one list and called them    // dead. That is two full workspace rebuilds for branches somebody was    // working in.    const f = makeFixture([], { otherBranches: ["live-on-other-only"] });    const live = target(f, "live-on-other-only");    const gone = target(f, "on-no-remote");    backdate(live, 2);    backdate(gone, 2);    const r = run(f);    expect(r.status, r.stderr).toBe(0);    expect(existsSync(live), r.stdout).toBe(true);    expect(existsSync(gone), r.stdout).toBe(false);    expect(r.stdout).toMatch(/live branches read from:.*other/);  });  it("removes a target whose branch is gone from every remote — the squash-merge case", () => {    const f = makeFixture(["still-open"]);    const merged = target(f, "already-merged");    const open = target(f, "still-open");    backdate(merged, 2);    backdate(open, 2);    const r = run(f);    expect(r.status, r.stderr).toBe(0);    expect(existsSync(merged)).toBe(false);    expect(existsSync(open)).toBe(true);    expect(r.stdout).toMatch(/gone from every remote/);  });  it("spares a directory written inside the grace window — a build may be inside it", () => {    // A branch pushed seconds ago, or a local-only one, is not yet on origin.    const f = makeFixture([]);    const fresh = target(f, "building-right-now");    const r = run(f);    expect(r.status, r.stderr).toBe(0);    expect(existsSync(fresh)).toBe(true);    expect(r.stdout).toMatch(/a build may be inside it/);  });  it("is OFF when the remote cannot be listed — a network failure is not 'every branch is dead'", () => {    const f = makeFixture(["still-open"]);    const dir = target(f, "still-open");    backdate(dir, 2);    // No remote at all: run from a directory that is not a checkout.    const r = spawnSync("bash", [SCRIPT, "--root", f.root], {      encoding: "utf8",      cwd: f.root,      env: process.env,    });    expect(r.status, r.stderr).toBe(0);    expect(existsSync(dir)).toBe(true);    expect(r.stdout).toMatch(/dead-branch rule is OFF/);  });  it("--no-remote turns it off outright, leaving age and budget", () => {    const f = makeFixture([]);    const dir = target(f, "orphan");    backdate(dir, 2);    expect(run(f, ["--no-remote"]).status).toBe(0);    expect(existsSync(dir)).toBe(true);  });  it("--keep spares this build's own directory, whatever the remote says", () => {    const f = makeFixture([]);    const mine = target(f, "mine");    backdate(mine, 2);    expect(run(f, ["--keep", "mine"]).status).toBe(0);    expect(existsSync(mine)).toBe(true);  });});describe("the age rule", () => {  it("removes a target nothing has touched for over --days, though its branch is live", () => {    const f = makeFixture(["abandoned", "worked-on"]);    const stale = target(f, "abandoned");    const fresh = target(f, "worked-on");    backdate(stale, 30);    backdate(fresh, 1);    const r = run(f, ["--days", "14"]);    expect(r.status, r.stderr).toBe(0);    expect(existsSync(stale)).toBe(false);    expect(existsSync(fresh)).toBe(true);    expect(r.stdout).toMatch(/nothing has touched it for over 14 days/);  });  it("reads 'used' two levels down — a top-level mtime sits still through a build", () => {    const f = makeFixture(["deep"]);    const dir = target(f, "deep");    backdate(dir, 30);    // Only the deps directory is recent, which is exactly where cargo writes.    utimesSync(join(dir, "debug", "deps"), new Date(), new Date());    expect(run(f, ["--days", "14"]).status).toBe(0);    expect(existsSync(dir)).toBe(true);  });});describe("the budget — the only rule stated in gigabytes", () => {  it("evicts the OLDEST survivors until the set fits, and STOPS there", () => {    const f = makeFixture(["aaa-oldest", "zzz-newer"]);    const oldest = target(f, "aaa-oldest", 512);    const newer = target(f, "zzz-newer", 16);    // Both live on origin and both inside the age window, so only the budget    // can reclaim either — and the names sort opposite to the ages, so a sweep    // taking whatever the glob listed first would take the wrong one.    backdate(oldest, 5);    backdate(newer, 1);    // THE BUDGET IS MEASURED, NOT GUESSED. `du -sk` answers in allocated    // blocks, and ext4 on the CI host and APFS on a Mac do not agree about what    // a 16 KB file costs — a literal budget was right on one and evicted BOTH    // on the other. Sizing it from the survivor's own `du` is the same    // arithmetic the script does, so the assertion is about the ORDER and the    // stopping point rather than about a filesystem.    const budgetKb = du(newer);    expect(du(oldest), "the fixture must not fit inside the budget").toBeGreaterThan(0);    const r = run(f, ["--days", "14"], { COTTON_WORKTREE_TARGETS_BUDGET_KB: String(budgetKb) });    expect(r.status, r.stderr).toBe(0);    expect(r.stdout).toMatch(/budget/);    expect(existsSync(oldest), "the oldest goes first").toBe(false);    expect(existsSync(newer), "and the loop STOPS once the set fits").toBe(true);  });  it("leaves everything alone when the set already fits", () => {    const f = makeFixture(["one"]);    const dir = target(f, "one");    backdate(dir, 1);    const r = run(f, ["--days", "14"]);    expect(r.status, r.stderr).toBe(0);    expect(existsSync(dir)).toBe(true);    expect(r.stdout).toMatch(/inside the 60 GB budget/);  });  it("is off at 0, and the default is 60 GB", () => {    const f = makeFixture(["one"]);    const dir = target(f, "one");    backdate(dir, 1);    expect(run(f, ["--days", "14", "--budget-gb", "0"]).status).toBe(0);    expect(existsSync(dir)).toBe(true);    expect(run(f, ["--days", "14"]).stdout).toContain("60 GB budget");  });  it("never takes one written inside the grace window, however tight the budget", () => {    const f = makeFixture(["hot"]);    const dir = target(f, "hot");    const r = run(f, ["--days", "14"], { COTTON_WORKTREE_TARGETS_BUDGET_KB: "1" });    expect(r.status, r.stderr).toBe(0);    expect(existsSync(dir)).toBe(true);  });});describe("what it will not do", () => {  it("never follows a symlink standing where a target should be", () => {    // `rm -rf` would follow it, and what it points at is somebody's checkout.    const f = makeFixture([]);    const real = join(scratch, "somebodys-checkout");    mkdirSync(real, { recursive: true });    writeFileSync(join(real, "keep-me.txt"), "real work\n");    symlinkSync(real, join(f.root, "looks-like-a-branch"));    expect(run(f).status).toBe(0);    expect(existsSync(join(real, "keep-me.txt"))).toBe(true);  });  it("says so and exits 0 when the root does not exist yet", () => {    const f = makeFixture([]);    rmSync(f.root, { recursive: true, force: true });    const r = run(f);    expect(r.status).toBe(0);    expect(r.stdout).toMatch(/does not exist yet/);  });  it("refuses a knob that is not a whole number rather than guessing", () => {    const f = makeFixture([]);    expect(run(f, ["--days", "soon"]).status).toBe(2);    expect(run(f, ["--budget-gb", "lots"]).status).toBe(2);  });  it("--dry-run says what would go and takes nothing", () => {    const f = makeFixture([]);    const dir = target(f, "orphan");    backdate(dir, 30);    const r = run(f, ["--dry-run"]);    expect(r.status, r.stderr).toBe(0);    expect(r.stdout).toMatch(/would remove/);    expect(existsSync(dir)).toBe(true);  });});describe("the disk guard runs it", () => {  it("calls the sweep in the build-agnostic tier, where it cannot reach a live build", () => {    // The sweep never takes a directory written inside its grace window, which    // is what makes it safe above the build gate; a merged branch's 15-25 GB is    // the largest regenerable thing on a week-old machine.    const guard = join(ROOT, "scripts/disk-guard.sh");    expect(existsSync(guard), `${guard} has moved`).toBe(true);    const source = execFileSync("cat", [guard], { encoding: "utf8" });    expect(source).toContain("sweep-worktree-targets.sh");    const at = source.indexOf("sweep-worktree-targets.sh");    const gate = source.indexOf("Build-affecting reclaim");    expect(gate, "the build-affecting tier's banner moved").toBeGreaterThan(-1);    expect(at, "the sweep must run ABOVE the build-affecting gate").toBeLessThan(gate);  });});/** * THE BUDGET'S OWN GRACE, AND THE BUILD LOCK. * * The dead-branch and age rules spare anything written in the last hour, which * is right for them: they are optional deletes. Applied to the BUDGET the same * hour cost everything — on a Mac running four agent worktrees every directory * is touched inside any hour, so the budget spared all of them and evicted * nothing. Measured on one Mac, 2026-09-22: 120 GB under the root against a * 60 GB budget, one branch holding 88 GB, and a dry run that skipped three * directories for grace and stopped. * * So the budget has a SHORTER grace (10 minutes — cargo writes into * `debug/deps` and `debug/.fingerprint` as each unit finishes), and the case a * short grace could get wrong is covered exactly rather than by a wider window: * the branch whose build holds the machine-wide lock is never evicted. */describe("the budget evicts by use, not by age", () => {  it("takes a directory written half an hour ago — inside the hour the other rules spare", () => {    const f = makeFixture(["warm", "warmer"]);    const warm = target(f, "warm", 64);    const warmer = target(f, "warmer", 64);    // Both well inside the 14-day age rule and inside the 60-minute grace the    // dead-branch rule uses; only `warm` is outside the budget's 10 minutes.    minutesAgo(warm, 30);    const r = run(f, [], { COTTON_WORKTREE_TARGETS_BUDGET_KB: "1" });    expect(r.status, r.stderr).toBe(0);    expect(existsSync(warm), r.stdout).toBe(false);    expect(existsSync(warmer), "a directory written just now is building").toBe(true);  });  // RULE: Every live build slot protects its target from eviction, because a quiet linker still owns its output.  it.each(["", ".slot-2"])("spares the branch whose build holds slot %s, whatever its mtime", (suffix) => {    const f = makeFixture(["building", "idle"]);    const building = target(f, "building", 64);    const idle = target(f, "idle", 64);    minutesAgo(building, 30);    minutesAgo(idle, 30);    const lock = join(f.root, "..", "build.lock");    mkdirSync(lock + suffix, { recursive: true });    writeFileSync(join(lock + suffix, "pid"), `${process.pid}\n`);    writeFileSync(join(lock + suffix, "target"), "building\n");    const r = run(f, [], { COTTON_WORKTREE_TARGETS_BUDGET_KB: "1", BUILD_LOCK_DIR: lock });    expect(r.status, r.stderr).toBe(0);    expect(existsSync(building), r.stdout).toBe(true);    expect(existsSync(idle)).toBe(false);  });  it("ignores a lock whose holder is dead — a crashed build pins nothing", () => {    const f = makeFixture(["building"]);    const building = target(f, "building", 64);    minutesAgo(building, 30);    const lock = join(f.root, "..", "dead.lock");    mkdirSync(lock, { recursive: true });    // Nothing can be running as pid 0; `kill -0 0` addresses the process group    // rather than a process, so the pid is one that cannot be alive AND cannot    // be mistaken for this test's own.    writeFileSync(join(lock, "pid"), "2147483647\n");    writeFileSync(join(lock, "target"), "building\n");    const r = run(f, [], { COTTON_WORKTREE_TARGETS_BUDGET_KB: "1", BUILD_LOCK_DIR: lock });    expect(r.status, r.stderr).toBe(0);    expect(existsSync(building), r.stdout).toBe(false);  });  it("says so when it could not reach the budget, instead of exiting quietly", () => {    const f = makeFixture(["warmer"]);    target(f, "warmer", 64);    const r = run(f, [], { COTTON_WORKTREE_TARGETS_BUDGET_KB: "1" });    expect(r.status, r.stderr).toBe(0);    expect(r.stdout).toMatch(/still \d+ GB against the \d+ GB budget/);  });});/// RULE: Evidence is never evicted as cargo output, even when the branch-age and budget rules would reclaim its parent.it("keeps marked evidence under an otherwise reclaimable target", () => {  const f = makeFixture();  const dir = target(f, "evidence");  mkdirSync(join(dir, "walk"));  writeFileSync(join(dir, "walk/.cotton-evidence"), "");  const old = new Date(Date.now() - 30 * 86400_000);  utimesSync(join(dir, "walk/.cotton-evidence"), old, old);  utimesSync(join(dir, "walk"), old, old);  backdate(dir, 30);  const result = run(f, ["--no-remote", "--days", "1", "--budget-gb", "0"]);  expect(existsSync(dir)).toBe(true);  expect(result.stdout).toContain("EVIDENCE marker");});// RULE: The shared machine Cargo target survives branch, age and budget cleanup; lanes never wipe another lane's warm cache.it("keeps shared even when old, absent from remotes and over budget", () => {  const f = makeFixture();  const shared = target(f, "shared");  const old = new Date("2020-01-01T00:00:00Z");  utimesSync(shared, old, old);  const result = run(f, ["--days", "1"], { COTTON_WORKTREE_TARGETS_BUDGET_KB: "1" });  expect(existsSync(shared), result.stderr).toBe(true);});