Cotton code
907 lines · 40.7 KB · TypeScriptRaw
/** * `scripts/rust-verify.sh` cleans up after itself. * * Every verify extracts the whole repo and builds it into its own cargo target * directory — about 29 GB. Until 2026-09-09 nothing ever removed one: five * extractions held 102 GB of the build Mac's disk, `df` read 87% full and two * agents died on ENOSPC mid-run. Four behaviours answer that, and this file * runs the real script against a stub `cargo` and a scratch root to hold them: * *   - a run REMOVES what it made on the way out — target, cold target, the *     extraction — green, red or interrupted, and `--keep` opts out, *   - every run sweeps sibling extractions nothing has touched for the window, *   - and then, LAST, evicts oldest-first until what is left fits the budget. * * THE DEFAULT WAS THE OTHER WAY ROUND FROM 2026-09-15 TO 2026-09-27: a green run * kept its target warm because a cold rebuild was twenty minutes. It left about * 29 GB behind per run — one scratch per worktree, reclaimed only by a later run * from a DIFFERENT worktree — and the Macs now carry one shared sccache that * serves the rebuild (cargo check included), so a warm target buys little and * the owner asked for a run that leaves nothing but its log. * * The sweep deletes, so the guard that matters most is the last group: a path * that does not RESOLVE inside the scratch root is refused, symlinks included. */import { execFileSync, spawn, spawnSync } from "node:child_process";import {  existsSync,  mkdirSync,  mkdtempSync,  readdirSync,  readFileSync,  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";import { publishDiskReading } from "./helpers/disk-reading";const ROOT = resolve(__dirname, "../..");const SCRIPT = join(ROOT, "scripts/rust-verify.sh");const TEST_PHASE = join(ROOT, "scripts/rust-verify-tests.sh");const MACHINE_LOCK = join(ROOT, "scripts/ci/with-machine-lock.sh");const BUILD_LOCK = join(ROOT, "scripts/with-build-lock.sh");const CALLER_CLASS = join(ROOT, "scripts/lib/caller-class.sh");/** * The bare verb exports `COTTON_GIT` through `scripts/ci/setup-test-git.sh` * before its three phases (the server's git-backed suites skip without one), * so the fixture carries that script too — the lane's copy, never a stub. */const TEST_GIT = join(ROOT, "scripts/ci/setup-test-git.sh");const SCCACHE_SHIM = join(ROOT, "scripts/ci/sccache-shim.sh");let scratch = "";afterEach(() => {  if (scratch) rmSync(scratch, { recursive: true, force: true });  scratch = "";});type Fixture = {  /** A miniature repo with the real script at scripts/rust-verify.sh. */  repo: string;  /** The scratch root the script is pointed at, via RUST_VERIFY_DIR. */  root: string;  /** Where this repo's own extraction lands under that root. */  own: string;  home: string;  bin: string;  calls: string;};/** * A `cargo` on PATH that records every invocation. `check`/`clippy`/`test` * create the target directory the way a real build would and exit with * `exitCode`; `clean --target-dir X` removes X, which is what cargo does. */function stubCargo(dir: string, exitCode: number): string {  const bin = join(dir, "bin");  mkdirSync(bin, { recursive: true });  writeFileSync(    join(bin, "cargo"),    [      "#!/usr/bin/env bash",      `echo "$@" >> "${join(dir, "calls.txt")}"`,      'if [ "$1" = "clean" ]; then',      '  target=""',      '  while [ $# -gt 0 ]; do',      '    if [ "$1" = "--target-dir" ]; then target="$2"; fi',      "    shift",      "  done",      '  [ -n "$target" ] && rm -rf "$target"',      "  exit 0",      "fi",      // A build populates its target directory.      'mkdir -p "$CARGO_TARGET_DIR/debug"',      // `test` leaves the one line the test phase reads to know a crate ran.      'if [ "$1" = "test" ]; then',      `  echo "test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out"`,      "fi",      'if [ -n "${STUB_WAIT_FOR:-}" ]; then',      '  while [ ! -f "$STUB_WAIT_FOR" ]; do sleep 0.05; done',      'fi',      `exit ${exitCode}`,    ].join("\n"),    { mode: 0o755 },  );  return bin;}function makeFixture(exitCode = 0): Fixture {  scratch = mkdtempSync(join(tmpdir(), "rust-verify-cleanup-"));  const repo = join(scratch, "repo");  mkdirSync(join(repo, "scripts"), { recursive: true });  mkdirSync(join(repo, "crates"), { recursive: true });  writeFileSync(join(repo, "scripts/rust-verify.sh"), readFileSync(SCRIPT, "utf8"), { mode: 0o755 });  // The `test` verb hands off to the phase script, which runs one cargo per  // member; the fixture carries two so the hand-off is visible in the calls.  writeFileSync(join(repo, "scripts/rust-verify-tests.sh"), readFileSync(TEST_PHASE, "utf8"), { mode: 0o755 });  mkdirSync(join(repo, "scripts/ci"), { recursive: true });  writeFileSync(join(repo, "scripts/ci/setup-test-git.sh"), readFileSync(TEST_GIT, "utf8"), { mode: 0o755 });  // The sccache wrapper is a SHIM, not the binary — it drops CARGO_TARGET_DIR,  // which sccache hashes and which this script sets per worktree. The fixture  // carries the generator because the script calls it by path.  writeFileSync(join(repo, "scripts/ci/sccache-shim.sh"), readFileSync(SCCACHE_SHIM, "utf8"), { mode: 0o755 });  // The machine's build mutex, which the script takes on a Mac since 28 Sep  // 2026 by re-running itself under the wrapper; the fixture carries both  // halves so the Darwin case below runs the real thing against a scratch lock.  writeFileSync(join(repo, "scripts/ci/with-machine-lock.sh"), readFileSync(MACHINE_LOCK, "utf8"), { mode: 0o755 });  writeFileSync(join(repo, "scripts/with-build-lock.sh"), readFileSync(BUILD_LOCK, "utf8"), { mode: 0o755 });  // On a Mac the wrapper runs its command through the device policy beside it.  writeFileSync(join(repo, "scripts/mac-build-policy.sh"), readFileSync(join(ROOT, "scripts/mac-build-policy.sh"), "utf8"), { mode: 0o755 });  mkdirSync(join(repo, "scripts/lib"), { recursive: true });  writeFileSync(join(repo, "scripts/lib/caller-class.sh"), readFileSync(CALLER_CLASS, "utf8"));  writeFileSync(join(repo, "scripts/lib/mac_disk_policy.py"), readFileSync(join(ROOT, "scripts/lib/mac_disk_policy.py")));  writeFileSync(join(repo, "scripts/lib/evidence.py"), readFileSync(join(ROOT, "scripts/lib/evidence.py")));  // The script asks this about its scratch root before it removes anything there.  writeFileSync(join(repo, "scripts/lib/owned-root.sh"), readFileSync(join(ROOT, "scripts/lib/owned-root.sh"), "utf8"));  writeFileSync(join(repo, "crates/Cargo.toml"), '[workspace]\nmembers = ["alpha", "beta"]\n');  const git = (...args: string[]) =>    execFileSync("git", ["-C", repo, ...args], { encoding: "utf8", stdio: "pipe" });  git("init", "-q", "-b", "main");  git("config", "user.email", "test@example.invalid");  git("config", "user.name", "test");  git(    "add",    "scripts/rust-verify.sh",    "scripts/rust-verify-tests.sh",    "scripts/ci/setup-test-git.sh",    "scripts/ci/sccache-shim.sh",    "crates/Cargo.toml",  );  git("commit", "-q", "-m", "fixture");  const root = join(scratch, "root");  mkdirSync(root, { recursive: true });  const home = join(scratch, "home");  mkdirSync(home, { recursive: true });  const bin = stubCargo(scratch, exitCode);  // Dependency installation is outside this harness; never reach a real pnpm.  // `PNPM_WAIT_FOR` holds it mid-install (after writing `PNPM_STARTED`), so a  // case can interrupt a run while it is still extracting.  writeFileSync(    join(bin, "pnpm"),    [      "#!/usr/bin/env bash",      'if [ -n "${PNPM_WAIT_FOR:-}" ]; then',      '  touch "$PNPM_STARTED"',      '  while [ ! -f "$PNPM_WAIT_FOR" ]; do sleep 0.05; done',      "fi",      "exit 0",    ].join("\n"),    { mode: 0o755 },  );  // The script derives its own directory name from the repo path; ask it.  // (One per Mac on macOS, one per worktree elsewhere — rust-verify-shared-scratch.test.ts.)  const own = execFileSync("bash", [join(repo, "scripts/rust-verify.sh"), "--print-scratch"], {    encoding: "utf8",    env: { ...process.env, HOME: home, RUST_VERIFY_DIR: root, TMPDIR: root },  }).trim();  return { repo, root, own, home, bin, calls: join(scratch, "calls.txt") };}function run(f: Fixture, args: string[], extraEnv: Record<string, string> = {}) {  return spawnSync("bash", [join(f.repo, "scripts/rust-verify.sh"), ...args], {    encoding: "utf8",    timeout: 15000,    cwd: f.repo,    env: {      ...process.env,      // HOME first: the script prepends $HOME/.cargo/bin, which would shadow the stub.      HOME: f.home,      // Off the machine's real build mutex unless a case asks for it: a test      // must never queue behind a CI build on the Mac running it.      COTTON_MACHINE_LOCK_OS: "Linux",      PATH: `${f.bin}:${process.env.PATH ?? ""}`,      RUST_VERIFY_DIR: f.root,      TMPDIR: f.root,      // The machine running these tests may carry a real sccache; a wrapper      // chosen by the host is not a property of the script.      RUST_VERIFY_SCCACHE: "off",      ...extraEnv,    },  });}const calls = (f: Fixture): string[] =>  existsSync(f.calls) ? readFileSync(f.calls, "utf8").trim().split("\n").filter(Boolean) : [];/** The verb's own cargo calls — without the `cargo clean` the cleanup runs on the way out. */const cargoCalls = (f: Fixture): string[] => calls(f).filter((c) => !c.startsWith("clean "));/** Backdate a whole extraction past the sweep's window. Directory mtimes move *  when their entries are written, so the directory itself goes last. */function backdate(dir: string, hoursAgo: number) {  const when = new Date(Date.now() - hoursAgo * 3600_000);  for (const p of [join(dir, "target"), join(dir, "extracted-from"), dir]) {    if (existsSync(p)) utimesSync(p, when, when);  }}function fakeSibling(root: string, name: string): string {  const dir = join(root, name);  mkdirSync(join(dir, "target", "debug"), { recursive: true });  writeFileSync(join(dir, "extracted-from"), "0".repeat(40) + "\n");  return dir;}describe("rust-verify.sh — a run REMOVES what it made on the way out", () => {  // RULE: A green rust:verify run removes its target directory and its extraction before it exits, cargo clean first, and says what went and how much came back — only the run log stays.  it("runs the cargo verb, cleans the target, removes the extraction, and keeps only the log", () => {    const f = makeFixture(0);    const r = run(f, ["check"]);    expect(r.status).toBe(0);    expect(calls(f)).toEqual([      "check --workspace --all-targets",      `clean --manifest-path ${join(f.own, "base/crates/Cargo.toml")} --target-dir ${join(f.own, "target")}`,    ]);    expect(existsSync(join(f.own, "target"))).toBe(false);    expect(existsSync(join(f.own, "base"))).toBe(false);    expect(existsSync(join(f.own, "extracted-from"))).toBe(false);    expect(existsSync(join(f.own, "logs"))).toBe(true);    expect(r.stdout).toMatch(/removed .*target \(\d+ MB\)/);    expect(r.stdout).toMatch(/removed the extraction .*base \(\d+ MB\)/);    expect(r.stdout).toMatch(/cleaned up — 2 directories removed, \d+ MB back; only the log stays/);    expect(existsSync(join(f.own, ".lock"))).toBe(false);  });  // RULE: Every building verb cleans up — clippy and test as well as check.  it("cleans up after clippy and after test too — not only check", () => {    for (const verb of ["clippy", "test"]) {      const f = makeFixture(0);      const r = run(f, [verb]);      expect(r.status, `${verb} should pass`).toBe(0);      expect(calls(f).filter((c) => c.startsWith("clean ")), `${verb} must clean`).toHaveLength(1);      expect(existsSync(join(f.own, "target"))).toBe(false);      expect(existsSync(join(f.own, "base"))).toBe(false);      rmSync(scratch, { recursive: true, force: true });      scratch = "";    }  });  // RULE: --keep is the only way a run leaves its target and extraction warm, and it says what the next run will do about them.  it("--keep leaves the target and the extraction warm, and says so", () => {    const f = makeFixture(0);    const r = run(f, ["check", "--keep"]);    expect(r.status).toBe(0);    expect(calls(f)).toEqual(["check --workspace --all-targets"]);    expect(existsSync(join(f.own, "target"))).toBe(true);    expect(existsSync(join(f.own, "base"))).toBe(true);    expect(r.stdout).toMatch(/--keep — leaving .* warm \(\d+ MB under .*\); the next run here without --keep removes them/);  });  // RULE: --clean is the default spelled out, and it wins over --keep when both are typed — a flag the caller typed is never second-guessed.  it("--clean is accepted, and beats --keep", () => {    const f = makeFixture(0);    const r = run(f, ["check", "--keep", "--clean"]);    expect(r.status).toBe(0);    expect(existsSync(join(f.own, "target"))).toBe(false);    expect(existsSync(join(f.own, "base"))).toBe(false);    expect(r.stdout).toMatch(/cleaned up — 2 directories removed/);  });  // RULE: A RED run cleans up too, and tells the caller on stderr that --keep holds a target warm for a retry.  it("a RED run removes the target as well, and names --keep for the retry", () => {    const f = makeFixture(101);    const r = run(f, ["test"]);    // The phase script's own exit code: red is red, whatever cargo answered.    expect(r.status).toBe(1);    expect(calls(f).filter((c) => !c.startsWith("clean "))).toEqual(["test -p alpha --no-fail-fast", "test -p beta --no-fail-fast"]);    expect(existsSync(join(f.own, "target"))).toBe(false);    expect(existsSync(join(f.own, "base"))).toBe(false);    expect(r.stderr).toMatch(/exit 1 — removing the target and the extraction/);    expect(r.stderr).toMatch(/--keep/);    expect(existsSync(join(f.own, ".lock"))).toBe(false);  });  // RULE: A RED run under --keep holds the target for the retry — the flag the caller typed holds on the failure it was typed for.  it("a RED run under --keep holds the target warm", () => {    const f = makeFixture(101);    const r = run(f, ["test", "--keep"]);    expect(r.status).toBe(1);    expect(existsSync(join(f.own, "target"))).toBe(true);    expect(r.stderr).toMatch(/--keep holds .*target warm for the retry/);  });  // RULE: The cleanup removes EVERY target the scratch owns, the cold target included, whatever verb ran.  it("removes EVERY target this scratch owns, cold's included", () => {    const f = makeFixture(0);    expect(run(f, ["check", "--keep"]).status).toBe(0);    mkdirSync(join(f.own, "target-cold", "debug"), { recursive: true });    const r = run(f, ["check"]);    expect(r.status).toBe(0);    expect(existsSync(join(f.own, "target"))).toBe(false);    expect(existsSync(join(f.own, "target-cold"))).toBe(false);    expect(r.stdout).toMatch(/3 directories removed/);  });  // RULE: A run interrupted by TERM still leaves only its log — the cleanup runs from the EXIT trap, not only after a verb that returned.  it("a run killed by TERM cleans up from its exit trap", async () => {    const f = makeFixture(0);    const gate = join(scratch, "release-cargo");    const holder = start(f, ["check"], { STUB_WAIT_FOR: gate });    try {      await expect.poll(() => calls(f), { timeout: 5000 }).toContain("check --workspace --all-targets");      holder.child.kill("SIGTERM");      writeFileSync(gate, "release");      expect(await holder.done).toBe(143);      expect(existsSync(join(f.own, "target"))).toBe(false);      expect(existsSync(join(f.own, "base"))).toBe(false);      expect(existsSync(join(f.own, ".lock"))).toBe(false);      expect(existsSync(join(f.own, "logs"))).toBe(true);    } finally {      writeFileSync(gate, "release");      await holder.done;    }  }, 10000);  // RULE: A run interrupted while it is still EXTRACTING (git archive, the dependency install) removes the half-made extraction too — the cleanup is armed as soon as the lock is held, not only once cargo starts.  it("a run killed by TERM during the extraction removes the half-made extraction", async () => {    const f = makeFixture(0);    const gate = join(scratch, "release-pnpm");    const started = join(scratch, "pnpm-started");    const holder = start(f, ["check"], { PNPM_WAIT_FOR: gate, PNPM_STARTED: started });    try {      await expect.poll(() => existsSync(started), { timeout: 5000 }).toBe(true);      expect(existsSync(join(f.own, "base"))).toBe(true);      holder.child.kill("SIGTERM");      writeFileSync(gate, "release");      expect(await holder.done).toBe(143);      expect(cargoCalls(f)).toEqual([]);      expect(existsSync(join(f.own, "base"))).toBe(false);      expect(existsSync(join(f.own, "extracted-from"))).toBe(false);      expect(existsSync(join(f.own, ".lock"))).toBe(false);    } finally {      writeFileSync(gate, "release");      await holder.done;    }  }, 10000);  // RULE: A run killed while it WAITS for another run's lock never removes that holder's scratch — the cleanup is armed only once the lock is this run's.  it("a run killed while waiting for the lock leaves the holder's extraction alone", async () => {    const f = makeFixture(0);    const gate = join(scratch, "release-cargo");    const first = start(f, ["check"], { STUB_WAIT_FOR: gate });    try {      await expect.poll(() => calls(f), { timeout: 5000 }).toContain("check --workspace --all-targets");      const waiter = start(f, ["check"]);      await expect.poll(() => waiter.stderr(), { timeout: 5000 }).toMatch(/waiting for pid/);      waiter.child.kill("SIGTERM");      await waiter.done;      expect(existsSync(join(f.own, "base"))).toBe(true);      expect(existsSync(join(f.own, "target"))).toBe(true);    } finally {      writeFileSync(gate, "release");      await first.done;    }  }, 15000);  it("says nothing was removed rather than claiming a directory that never existed", () => {    const f = makeFixture(0);    const r = run(f, ["sweep"]);    expect(r.status).toBe(0);    expect(r.stdout).not.toMatch(/removed/);  });  it("the usage text names --keep, --clean and sweep", () => {    const f = makeFixture(0);    const r = run(f, ["nonsense"]);    expect(r.status).toBe(2);    expect(r.stderr).toMatch(/--keep/);    expect(r.stderr).toMatch(/--clean/);    expect(r.stderr).toMatch(/sweep/);  });});describe("rust-verify.sh — the run log is namespaced, and its path is printed first", () => {  /**   * Three agents share the build Mac. A verify's log at a fixed path is two   * runs writing one file and a third reading neither, so the script names its   * own after the verb, a UTC stamp and the pid, under the scratch that is   * already one directory per worktree — and prints it before the lock wait   * that is usually what somebody is trying to look into.   */  it("prints the path as its first line and writes the run's output there", () => {    const f = makeFixture(0);    const r = run(f, ["check"]);    expect(r.status).toBe(0);    const first = r.stdout.trim().split("\n")[0];    expect(first).toMatch(/^rust-verify: log → /);    const logPath = first.replace(/^rust-verify: log → /, "").trim();    expect(logPath.startsWith(join(f.own, "logs") + "/")).toBe(true);    expect(logPath).toMatch(/\/check-\d{8}T\d{6}Z-\d+\.log$/);    expect(existsSync(logPath)).toBe(true);    // Both streams land in it: the log is the whole run, not half of it.    const body = readFileSync(logPath, "utf8");    expect(body).toMatch(/cleaned up/);  });  it("two runs never share one — the pid separates them inside the same second", () => {    const f = makeFixture(0);    const paths = ["check", "clippy"].map((verb) => {      const r = run(f, [verb]);      expect(r.status, r.stderr).toBe(0);      return r.stdout.trim().split("\n")[0].replace(/^rust-verify: log → /, "").trim();    });    expect(paths[0]).not.toBe(paths[1]);    expect(paths.every((p) => existsSync(p))).toBe(true);  });  it("the log carries stderr too, and the caller still sees two streams", () => {    const f = makeFixture(101);    const r = run(f, ["test"]);    expect(r.status).toBe(1);    expect(r.stderr).toMatch(/removing the target/);    // stdout is NOT stderr: merging them would break every caller that reads one.    expect(r.stdout).not.toMatch(/keeping .* warm for the retry/);    const logPath = r.stdout.trim().split("\n")[0].replace(/^rust-verify: log → /, "").trim();    expect(readFileSync(logPath, "utf8")).toMatch(/removing the target/);  });  it("keeps the newest 20 logs and no more", () => {    const f = makeFixture(0);    const logs = join(f.own, "logs");    mkdirSync(logs, { recursive: true });    for (let i = 0; i < 25; i++) writeFileSync(join(logs, `old-${i}.log`), "x");    const r = run(f, ["check"]);    expect(r.status).toBe(0);    expect(readdirSync(logs).length).toBeLessThanOrEqual(20);  });});describe("rust-verify.sh — sccache, when the machine already has the pinned one", () => {  it("wraps rustc with the copy the CI bootstrap left, and turns incremental off", () => {    // `scripts/ci/setup-sccache.sh` owns the version and its sha256 and installs    // exactly here. This script FETCHES NOTHING — it uses what is there.    const f = makeFixture(0);    const bin = join(f.home, ".cache/cottondb/rust/bin");    mkdirSync(bin, { recursive: true });    writeFileSync(join(bin, "sccache"), "#!/usr/bin/env bash\nexit 0\n", { mode: 0o755 });    const r = run(f, ["check"], { RUST_VERIFY_SCCACHE: "" });    expect(r.status).toBe(0);    expect(r.stdout).toMatch(/wrapping rustc with .*sccache/);    expect(r.stdout).toMatch(/incremental off/);  });  it("says nothing and builds as before when there is none", () => {    const f = makeFixture(0);    const r = run(f, ["check"], { RUST_VERIFY_SCCACHE: "off" });    expect(r.status).toBe(0);    expect(r.stdout).not.toMatch(/wrapping rustc/);  });  it("`cold` never wraps — it answers what a build from NOTHING costs", () => {    const f = makeFixture(0);    const bin = join(f.home, ".cache/cottondb/rust/bin");    mkdirSync(bin, { recursive: true });    writeFileSync(join(bin, "sccache"), "#!/usr/bin/env bash\nexit 0\n", { mode: 0o755 });    const r = run(f, ["cold"], { RUST_VERIFY_SCCACHE: "" });    expect(r.status).toBe(0);    expect(r.stdout).not.toMatch(/wrapping rustc/);  });});function start(f: Fixture, args: string[], extraEnv: Record<string, string> = {}) {  const child = spawn("bash", [join(f.repo, "scripts/rust-verify.sh"), ...args], {    cwd: f.repo,    env: {      ...process.env,      HOME: f.home,      // Off the machine's real build mutex — see `run`.      COTTON_MACHINE_LOCK_OS: "Linux",      PATH: `${f.bin}:${process.env.PATH ?? ""}`,      RUST_VERIFY_DIR: f.root,      RUST_VERIFY_SCCACHE: "off",      ...extraEnv,    },  });  let stderr = "";  child.stdout.resume();  child.stderr.on("data", (chunk: Buffer) => { stderr += chunk.toString(); });  const done = new Promise<number | null>((resolve, reject) => {    child.on("error", reject);    child.on("close", resolve);  });  return { child, done, stderr: () => stderr };}describe("rust-verify.sh — the whole run holds its scratch lock", () => {  it("waits before re-extracting while the first cargo still reads the source", async () => {    const f = makeFixture();    const gate = join(scratch, "release-cargo");    // --keep: the point here is the lock, and the target's survival at the end    // shows the second run's re-extraction replaced only `$BASE`.    const first = start(f, ["check", "--keep"], { STUB_WAIT_FOR: gate });    let second: ReturnType<typeof start> | undefined;    try {      await expect.poll(() => calls(f), { timeout: 5000 }).toContain("check --workspace --all-targets");      const marker = join(f.own, "base", "still-compiling");      writeFileSync(marker, "the first cargo is reading this extraction");      const stamp = readFileSync(join(f.own, "extracted-from"), "utf8");      second = start(f, ["extract"]);      await expect.poll(() => second?.stderr(), { timeout: 5000 }).toMatch(        new RegExp(`waiting for pid ${first.child.pid}, .* since \\d{4}-\\d{2}-\\d{2}T`),      );      expect(existsSync(marker)).toBe(true);      expect(readFileSync(join(f.own, "extracted-from"), "utf8")).toBe(stamp);      expect(calls(f)).toEqual(["check --workspace --all-targets"]);      writeFileSync(gate, "release");      expect(await first.done).toBe(0);      expect(await second.done).toBe(0);      expect(second.stderr().match(/waiting for pid/g)).toHaveLength(1);      expect(existsSync(marker)).toBe(false);      // The first run kept its target (--keep) and the second run's      // re-extraction left it alone: only `$BASE` is replaced, never the      // target directory beside it.      expect(existsSync(join(f.own, "target"))).toBe(true);      expect(existsSync(join(f.own, ".lock"))).toBe(false);    } finally {      writeFileSync(gate, "release");      await first.done;      if (second) await second.done;    }  }, 25000);  it("reclaims a dead holder's lock and releases it after extraction", () => {    const f = makeFixture();    const deadPid = execFileSync("bash", ["-c", "echo $$"], { encoding: "utf8" }).trim();    const lock = join(f.own, ".lock");    mkdirSync(lock, { recursive: true });    writeFileSync(join(lock, deadPid), "2026-01-01T00:00:00Z\n");    const r = run(f, ["extract"]);    expect(r.status, r.stderr).toBe(0);    expect(r.stderr).toContain(`holder pid ${deadPid} is dead`);    expect(existsSync(join(f.own, "extracted-from"))).toBe(true);    expect(existsSync(lock)).toBe(false);  });  it("releases the holder's lock on TERM after its cargo finishes", async () => {    const f = makeFixture();    const gate = join(scratch, "release-cargo");    const holder = start(f, ["check"], { STUB_WAIT_FOR: gate });    try {      await expect.poll(() => calls(f), { timeout: 5000 }).toContain("check --workspace --all-targets");      holder.child.kill("SIGTERM");      writeFileSync(gate, "release");      expect(await holder.done).toBe(143);      expect(existsSync(join(f.own, ".lock"))).toBe(false);    } finally {      writeFileSync(gate, "release");      await holder.done;    }  }, 10000);  it("reclaims an old empty lock left by a crash during acquisition", () => {    const f = makeFixture();    const lock = join(f.own, ".lock");    mkdirSync(lock, { recursive: true });    utimesSync(lock, new Date("2020-01-01"), new Date("2020-01-01"));    expect(run(f, ["extract"]).status).toBe(0);    expect(existsSync(lock)).toBe(false);  });  it("releases on an extraction failure", () => {    const f = makeFixture();    rmSync(join(f.repo, ".git", "refs", "heads", "main"));    expect(run(f, ["extract"]).status).not.toBe(0);    expect(existsSync(join(f.own, ".lock"))).toBe(false);  });  it("a sweep refuses to delete a locked extraction even when it is old", () => {    const f = makeFixture();    const sibling = fakeSibling(f.root, "active");    mkdirSync(join(sibling, ".lock"));    writeFileSync(join(sibling, ".lock", String(process.pid)), "2026-01-01T00:00:00Z\n");    backdate(sibling, 48);    expect(run(f, ["sweep"]).status).toBe(0);    expect(existsSync(sibling)).toBe(true);    const named = run(f, ["sweep", sibling]);    expect(named.status).toBe(1);    expect(named.stderr).toMatch(/verify lock exists/);  });  it("a sweep removes an old extraction whose lock holder is dead — a crash's lock protects nothing", () => {    const f = makeFixture();    const sibling = fakeSibling(f.root, "crashed");    mkdirSync(join(sibling, ".lock"));    // A pid no process holds: the largest a Linux or macOS kernel hands out is    // far below this, and the script only asks whether it is alive.    writeFileSync(join(sibling, ".lock", "4194303999"), "2026-01-01T00:00:00Z\n");    backdate(sibling, 48);    expect(run(f, ["sweep"]).status).toBe(0);    expect(existsSync(sibling)).toBe(false);  });});describe("rust-verify.sh — the stale sweep", () => {  it("removes a sibling extraction nothing has touched for over 24h", () => {    const f = makeFixture(0);    const stale = fakeSibling(f.root, "old-lane-deadbeef");    backdate(stale, 30);    const r = run(f, ["check"]);    expect(r.status).toBe(0);    expect(existsSync(stale)).toBe(false);    expect(r.stdout).toMatch(/swept/);  });  it("leaves a sibling another lane is still using — and its own extraction", () => {    const f = makeFixture(0);    const fresh = fakeSibling(f.root, "live-lane-cafebabe");    const stale = fakeSibling(f.root, "old-lane-deadbeef");    backdate(stale, 30);    // The directory itself is old; the target it is building into is not.    backdate(fresh, 30);    utimesSync(join(fresh, "target"), new Date(), new Date());    const r = run(f, ["check", "--keep"]);    expect(r.status).toBe(0);    expect(existsSync(fresh)).toBe(true);    expect(existsSync(stale)).toBe(false);    // Its own scratch is never a sweep candidate, whatever its age.    expect(existsSync(f.own)).toBe(true);  });  it("`sweep` on its own reclaims the stale siblings without building anything", () => {    const f = makeFixture(0);    const stale = fakeSibling(f.root, "old-lane-deadbeef");    backdate(stale, 48);    const r = run(f, ["sweep"]);    expect(r.status).toBe(0);    expect(existsSync(stale)).toBe(false);    expect(calls(f).filter((c) => /^(check|clippy|test) /.test(c))).toEqual([]);  });  it("the window is configurable, and nothing inside it is touched", () => {    const f = makeFixture(0);    const recent = fakeSibling(f.root, "two-hours-ago");    backdate(recent, 2);    expect(run(f, ["sweep"]).status).toBe(0);    expect(existsSync(recent)).toBe(true);    expect(run(f, ["sweep"], { RUST_VERIFY_STALE_HOURS: "1" }).status).toBe(0);    expect(existsSync(recent)).toBe(false);  });  // THE RULE STATED IN GIGABYTES, and it runs LAST. The age rule above is a  // proxy for size and cannot say "60 GB": three branches verified inside one  // day leave three 21 GB extractions, every one of them inside its window and  // every one of them correct by that rule. `RUST_VERIFY_BUDGET_KB` is the same  // number in the unit the arithmetic happens in — a gigabyte is not a size a  // fixture can reach, and a budget test whose fixture cannot exceed the budget  // proves only that the eviction loop compiles.  it("evicts the OLDEST siblings until what is left fits the budget", () => {    const f = makeFixture(0);    const oldest = fakeSibling(f.root, "aaa-oldest");    const newer = fakeSibling(f.root, "zzz-newer");    // Both inside the age window, so only the budget can reclaim either — and    // the names are deliberately in the opposite order to the ages, so a sweep    // that took whatever the glob listed first would take the wrong one.    backdate(oldest, 3);    backdate(newer, 1);    const r = run(f, ["sweep"], { RUST_VERIFY_BUDGET_KB: "1" });    expect(r.status).toBe(0);    expect(r.stdout).toMatch(/budget/);    expect(existsSync(oldest), "the oldest sibling goes first").toBe(false);  });  it("leaves everything alone when the set already fits, and when the budget is off", () => {    const f = makeFixture(0);    const sibling = fakeSibling(f.root, "recent-lane");    backdate(sibling, 1);    expect(run(f, ["sweep"], { RUST_VERIFY_BUDGET_KB: "999999999" }).status).toBe(0);    expect(existsSync(sibling)).toBe(true);    expect(run(f, ["sweep"], { RUST_VERIFY_BUDGET_GB: "0", RUST_VERIFY_BUDGET_KB: "" }).status).toBe(0);    expect(existsSync(sibling)).toBe(true);  });  it("never evicts THIS run's own extraction, however tight the budget", () => {    // The budget runs before the build and must not take the extraction the    // run is about to use; what the run itself removes on the way out is the    // cleanup's business (--keep shows the sweep left it standing).    const f = makeFixture(0);    const r = run(f, ["check", "--keep"], { RUST_VERIFY_BUDGET_KB: "1" });    expect(r.status).toBe(0);    expect(r.stdout).not.toMatch(new RegExp(`swept ${f.own.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`));    expect(existsSync(join(f.own, "target"))).toBe(true);  });});describe("rust-verify.sh — it only ever removes what it owns", () => {  it("refuses a path outside the scratch root", () => {    const f = makeFixture(0);    const outside = join(scratch, "not-ours");    mkdirSync(join(outside, "target"), { recursive: true });    const r = run(f, ["sweep", outside]);    expect(r.status).not.toBe(0);    expect(r.stderr).toMatch(/refusing to remove/);    expect(r.stderr).toContain(f.root);    expect(existsSync(outside)).toBe(true);  });  it("refuses the scratch root itself", () => {    const f = makeFixture(0);    const r = run(f, ["sweep", f.root]);    expect(r.status).not.toBe(0);    expect(r.stderr).toMatch(/refusing to remove/);    expect(existsSync(f.root)).toBe(true);  });  it("refuses a sibling that is a SYMLINK pointing out of the root", () => {    // The one that would really hurt: `cargo clean --target-dir` follows a    // symlink, so a name inside the prefix is not enough — it has to resolve    // inside it.    const f = makeFixture(0);    const realTree = join(scratch, "somebodys-checkout");    mkdirSync(join(realTree, "target"), { recursive: true });    writeFileSync(join(realTree, "keep-me.txt"), "real work\n");    symlinkSync(realTree, join(f.root, "looks-like-a-lane"));    const r = run(f, ["sweep", join(f.root, "looks-like-a-lane")]);    expect(r.status).not.toBe(0);    expect(r.stderr).toMatch(/refusing to remove/);    expect(existsSync(join(realTree, "keep-me.txt"))).toBe(true);    expect(existsSync(join(realTree, "target"))).toBe(true);  });  it("refuses a path that only looks like a prefix match", () => {    const f = makeFixture(0);    const sneaky = `${f.root}-elsewhere`;    mkdirSync(sneaky, { recursive: true });    try {      const r = run(f, ["sweep", sneaky]);      expect(r.status).not.toBe(0);      expect(existsSync(sneaky)).toBe(true);    } finally {      rmSync(sneaky, { recursive: true, force: true });    }  });  it("a refusal does not stop the paths that ARE ours from being reclaimed", () => {    const f = makeFixture(0);    const ours = fakeSibling(f.root, "old-lane-deadbeef");    const outside = join(scratch, "not-ours");    mkdirSync(outside, { recursive: true });    const r = run(f, ["sweep", outside, ours]);    expect(r.status).not.toBe(0);    expect(existsSync(outside)).toBe(true);    expect(existsSync(ours)).toBe(false);  });});/** * THE BARE VERB IS THE WHOLE VERIFICATION, AND A PARTIAL ONE SAYS SO. * * `pnpm rust:verify` defaulted to `check` for as long as it existed, which means * a green bare run proved the workspace COMPILES and nothing more. Three agents * in one night read that as "the Rust tests pass" and wrote it into PR bodies — * an easy mistake to make, because the command is called verify. A default that * is quietly the cheapest third of what its name promises is a wrong answer, not * a fast path, so the bare form runs all three phases and every single-phase * verb names the ones it skipped. */describe("rust-verify.sh — what the bare verb actually runs", () => {  it("runs check, then clippy, then the tests when no verb is given", () => {    const f = makeFixture(0);    const r = run(f, []);    expect(r.status, r.stderr).toBe(0);    const ran = calls(f);    expect(ran[0]).toBe("check --workspace --all-targets");    expect(ran[1]).toBe("clippy --all-targets -- -D warnings");    // The test phase runs one cargo per workspace member; the fixture has two.    expect(ran.filter((c) => c.startsWith("test"))).toHaveLength(2);    expect(r.stdout).toMatch(/all three phases passed/);  });  it("`all` is the same thing written out", () => {    const f = makeFixture(0);    const r = run(f, ["all"]);    expect(r.status, r.stderr).toBe(0);    expect(calls(f)[0]).toBe("check --workspace --all-targets");    expect(calls(f)[1]).toBe("clippy --all-targets -- -D warnings");  });  it("stops at the first red — clippy over a tree that does not compile answers nothing", () => {    const f = makeFixture(1);    const r = run(f, []);    expect(r.status).not.toBe(0);    expect(cargoCalls(f)).toEqual(["check --workspace --all-targets"]);  });  it("a single-phase verb says WHICH phases it did not run", () => {    const f = makeFixture(0);    const r = run(f, ["check"]);    expect(r.status, r.stderr).toBe(0);    expect(cargoCalls(f)).toEqual(["check --workspace --all-targets"]);    expect(r.stdout, "a partial verify that does not say so is read as a whole one").toMatch(      /that was `check` ONLY — clippy and the tests did NOT run/,    );  });  it("…and the tests verb says clippy did not run", () => {    const f = makeFixture(0);    const r = run(f, ["test"]);    expect(r.status, r.stderr).toBe(0);    expect(r.stdout).toMatch(/that was `test` ONLY — clippy did NOT run/);  });  it("the usage text names `all` and says it is the default", () => {    const f = makeFixture(0);    const r = run(f, ["nonsense"]);    expect(r.status).toBe(2);    expect(r.stderr).toMatch(/all\|extract\|check/);    expect(r.stderr).toMatch(/the DEFAULT when no verb is given/);  });});/** * THE TWO NUMBERS, AND WHEN THE SWEEP RUNS. * * The window and the budget were sized against a ~21 GB extraction and a Mac * with room to spare. Measured on one Mac, 2026-09-22, they held neither: the * scratch root carried 81 GB in THREE extractions — 27 GB each — every one * inside the 24-hour window and the set inside the 60 GB budget. A verify is * minutes of work and the next one is usually on a different branch, so a * day-long window keeps two extractions nobody will touch again. * * And the sweeps run BEFORE the extraction, never only after it: a new * extraction needs 27 GB, and reclaiming afterwards means the disk carried both * at once — which is the shape of every ENOSPC this script was written for. */describe("rust-verify.sh — the sweep's defaults and its place in the run", () => {  const source = readFileSync(SCRIPT, "utf8");  it("keeps six hours and 30 GB, the sizes an extraction actually is", () => {    expect(source).toMatch(/STALE_HOURS="\$\{RUST_VERIFY_STALE_HOURS:-6\}"/);    expect(source).toMatch(/BUDGET_GB="\$\{RUST_VERIFY_BUDGET_GB:-30\}"/);  });  it("sweeps before every verb that can extract, not after it", () => {    // `sweep` itself is the one verb that extracts nothing.    for (const verb of ["all", "extract", "check", "clippy", "test", "cold"]) {      const block = source.match(new RegExp(`\\n  ${verb}\\\\?\\)\\n([\\s\\S]*?)\\n    ;;`));      expect(block, `scripts/rust-verify.sh: no \`${verb})\` case`).not.toBeNull();      const body = block![1];      const stale = body.indexOf("sweep_stale");      const budget = body.indexOf("sweep_budget");      const extracted = Math.max(body.indexOf("ensure_extracted"), body.indexOf("\n    extract"));      expect(stale, `${verb}: no stale sweep`).toBeGreaterThan(-1);      expect(budget, `${verb}: no budget sweep`).toBeGreaterThan(-1);      expect(extracted, `${verb}: nothing extracts`).toBeGreaterThan(-1);      expect(stale, `${verb}: the stale sweep must run before the extraction`).toBeLessThan(extracted);      expect(budget, `${verb}: the budget sweep must run before the extraction`).toBeLessThan(extracted);    }  });});describe("rust-verify.sh takes the machine's build mutex on a Mac", () => {  // PR #1026 (todo bb40fae2, defect 2): one Swift test died with a signal —  // 5199 of 5200 passed — while a hand-run `rust:verify` had the same Mac's  // memory; on 27 Sep 2026 two `swift` CI jobs on the signing Mac died mid-compile  // beside a session's cargo runs. CI's own cargo steps queue behind  // `/tmp/tinmen-build.lock` through `scripts/ci/with-machine-lock.sh`; since  // 28 Sep the local verify does too, so a verify and a CI build on one Mac  // take turns instead of swapping it to death. The lock's own wait log is the  // witness: one line per acquire, with the label. On Linux nothing is taken.  it("acquires the lock as local-rust-verify on Darwin, and nothing on Linux", () => {    const f = makeFixture(0);    // The Mac wrapper admits a build only against the device's published reading.    publishDiskReading(f.home);    const lockDir = join(scratch, "lock");    const lockLog = join(scratch, "build-lock.log");    const onMac = run(f, ["check"], {      COTTON_MACHINE_LOCK_OS: "Darwin",      BUILD_LOCK_DIR: lockDir,      BUILD_LOCK_LOG: lockLog,    });    expect(onMac.status, `${onMac.stdout}${onMac.stderr}`).toBe(0);    expect(readFileSync(f.calls, "utf8")).toMatch(/^check /m);    expect(readFileSync(lockLog, "utf8")).toMatch(/\tlocal-rust-verify\t/);    expect(existsSync(lockDir), "the lock is released when the verify ends").toBe(false);    rmSync(lockLog, { force: true });    const onLinux = run(f, ["check"], { BUILD_LOCK_DIR: lockDir, BUILD_LOCK_LOG: lockLog });    expect(onLinux.status, `${onLinux.stdout}${onLinux.stderr}`).toBe(0);    expect(existsSync(lockLog), "Linux takes no machine-wide lock").toBe(false);  });});