import { execFileSync } from"node:child_process";import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from"node:fs";import { tmpdir } from"node:os";import { join, resolve } from"node:path";import { afterEach, describe, expect, it } from"vitest";import { GIT_LOCAL_ENV, dropGitLocalEnv } from"../../vitest.git-env";import { publishBuildPeaks, publishDiskReading } from"./helpers/disk-reading";/** The manually invoked verify:fast check, exercised against synthetic tools. */const ROOT = resolve(__dirname, "../..");const VERIFY = join(ROOT, "scripts/verify-fast.sh");let scratch = "";afterEach(() => {if (scratch) rmSync(scratch, { recursive: true, force: true }); scratch = "";});/** A bin directory placed FIRST on PATH, holding the stubs a case needs. */function stubs(bins: Record<string, string>): string { scratch = mkdtempSync(join(tmpdir(), "verify-fast-"));const bin = join(scratch, "bin"); mkdirSync(bin, { recursive: true });for (const [name, body] ofObject.entries(bins)) { writeFileSync(join(bin, name), `#!/usr/bin/env bash\n${body}\n`, { mode: 0o755 }); }return bin;}function run( script: string, bin: string, env: Record<string, string> = {}, opts: { cwd?: string; stdin?: string } = {},): { status: number; out: string } {try {// `2>&1` through a shell rather than two pipes: half of what these scripts// say (a skip, a RED) is on stderr, and `execFileSync` returns stdout only —// so a green run would silently assert against half its own output.const out = execFileSync("bash", ["-c", `bash "${script}" 2>&1`], { cwd: opts.cwd ?? ROOT, encoding: "utf8",// stdin is what git feeds a pre-push hook (one line per ref); a case that// says nothing is a hook run with nothing to diff. stdio: [opts.stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"], input: opts.stdin,// The stub bin is FIRST, so a stubbed name wins over a real one; the rest// of PATH stays so `bash`, `git` and the shell's own builtins still work.// `CI` is cleared: the hook stands down under it, and this suite runs// under it on the runner.// Off the machine's real build mutex: `verify-fast.sh` takes it on a Mac// since 28 Sep 2026, and a test must never queue behind a CI build. env: { ...process.env, CI: "", COTTON_MACHINE_LOCK_OS: "Linux", PATH: `${bin}:${process.env.PATH ?? ""}`,// Stubbed cargo must never wait on the real runner's shared artifacts. CARGO_TARGET_DIR: join(scratch, "target"), COTTON_CARGO_LOCK: join(scratch, "cargo.lock"), BUILD_LOCK_DIR: join(scratch, "build.lock"), ...env, }, });return { status: 0, out }; } catch (e) {const err = e as { status?: number; stdout?: string; stderr?: string };return { status: err.status ?? 1, out: `${err.stdout ?? ""}${err.stderr ?? ""}` }; }}describe("verify:fast — the local gate", () => { it("runs nextest over the three crates every consumer links, and the root scripts", () => {const bin = stubs({ cargo: 'printf "%s\\n" "$*" >> "$COTTON_CARGO_LOG"; exit 0', pnpm: 'printf "%s\\n" "$*" >> "$COTTON_PNPM_LOG"; exit 0', });const cargoLog = join(scratch, "cargo.log");const pnpmLog = join(scratch, "pnpm.log");const r = run(VERIFY, bin, { COTTON_CARGO_LOG: cargoLog, COTTON_PNPM_LOG: pnpmLog }); expect(r.status, r.out).toBe(0);const cargo = readFileSync(cargoLog, "utf8");// `nextest --version` is the availability probe; the run itself is the line// that matters, and it names the manifest because the Cargo workspace is// `crates/Cargo.toml` at the repo ROOT and this may be run from anywhere. expect(cargo).toMatch(/nextest run --manifest-path crates\/Cargo\.toml/);for (const crate of ["cotton-store", "cotton-core", "cotton-tools"]) { expect(cargo).toContain(`-p ${crate}`); }// NOT cotton-server: its several dozen integration binaries are most of the// workspace's test time and they exercise transport, not the rules under it. expect(cargo).not.toContain("cotton-server"); expect(readFileSync(pnpmLog, "utf8")).toContain("test:scripts"); }); it("SKIPS the Rust half by name when there is no cargo — it never fails for a missing tool", () => {// A local check that goes red because a toolchain is absent is a check// people learn to bypass.const bin = stubs({ pnpm: "exit 0",// `command -v cargo` must find nothing: a stub that exists would be found// whatever it does, so the case is made by NOT writing one and blanking// the rest of PATH. });// The system bin stays so `bash` and `command` still resolve; what is gone// is any directory that could hold a real `cargo`.const r = run(VERIFY, bin, { PATH: `${bin}:/usr/bin:/bin` }); expect(r.status, r.out).toBe(0); expect(r.out).toContain("no cargo on PATH"); }); it("runs the same crates under `cargo test` when cargo-nextest is missing, and names the install line", () => {// A gate that stood down whenever a plugin was absent would be no gate on// a fresh Mac — and the signing Mac had cargo and no nextest on 2026-09-27.const bin = stubs({ cargo: 'printf "%s\\n" "$*" >> "$COTTON_CARGO_LOG"; if [ "$1" = "nextest" ]; then exit 1; fi; exit 0', pnpm: "exit 0", });const cargoLog = join(scratch, "cargo.log");const r = run(VERIFY, bin, { COTTON_CARGO_LOG: cargoLog }); expect(r.status, r.out).toBe(0); expect(r.out).toContain("cargo-nextest is not installed"); expect(r.out).toContain("cargo install cargo-nextest --locked");const cargo = readFileSync(cargoLog, "utf8"); expect(cargo).toMatch(/^test --manifest-path crates\/Cargo\.toml -p cotton-store -p cotton-core -p cotton-tools$/m); expect(cargo).not.toMatch(/^nextest run/m); }); it("is RED under the `cargo test` fallback too — a fallback is not a skip", () => {const bin = stubs({ cargo: 'if [ "$1" = "nextest" ]; then exit 1; fi; exit 101', pnpm: "exit 0", });const r = run(VERIFY, bin); expect(r.status).toBe(1); expect(r.out).toContain("the Rust core is RED"); }); it("is RED when the Rust core fails, and says which half broke", () => {const bin = stubs({ cargo: 'if [ "$1" = "nextest" ] && [ "$2" = "--version" ]; then exit 0; fi; exit 101', pnpm: "exit 0", });const r = run(VERIFY, bin); expect(r.status).toBe(1); expect(r.out).toContain("the Rust core is RED");// It still runs the other half rather than stopping at the first failure:// one run should report everything that is broken. expect(r.out).toContain("pnpm test:scripts"); }); it("is RED when scripts/__tests__ fails", () => {const bin = stubs({ cargo: "exit 0", pnpm: "exit 1" });const r = run(VERIFY, bin); expect(r.status).toBe(1); expect(r.out).toContain("scripts/__tests__ is RED"); expect(r.out).toContain("--no-verify"); });});describe("verify:fast caps its own test workers", () => {// Todos 0a5e9c47 and 25307244: inside the pre-push hook `pnpm test:scripts`// ran at full vitest parallelism on a Mac also running CI jobs, and the// shell-spawning tests (setup-pnpm "four jobs at once", relay-watchdog)// blew vitest's 5 s timeout.const caps = (env: Record<string, string>): string => {const bin = stubs({ cargo: "exit 0", pnpm: 'printf "%s|%s|%s\\n" "${VITEST_MAX_WORKERS:-}" "${VITEST_MAX_FORKS:-}" "${VITEST_MAX_THREADS:-}" >> "$COTTON_PNPM_LOG"; exit 0', });const log = join(scratch, "pnpm.log");const r = run(VERIFY, bin, { COTTON_PNPM_LOG: log, VITEST_MAX_WORKERS: "", VITEST_MAX_FORKS: "", VITEST_MAX_THREADS: "", ...env, }); expect(r.status, r.out).toBe(0);return readFileSync(log, "utf8").trim(); };// RULE: verify:fast runs scripts/__tests__ with VITEST_MAX_WORKERS=2 unless the caller already named a worker cap, which it passes through untouched. it("defaults the cap to two workers, and leaves a caller's cap under any of the three names alone", () => { expect(caps({})).toBe("2||"); expect(caps({ VITEST_MAX_WORKERS: "6" })).toBe("6||");// A cap under the pool-specific names is still the caller's: a default// written into VITEST_MAX_WORKERS would win over it (`vitest.workers.ts`// reads that name first) and quietly override what they asked for. expect(caps({ VITEST_MAX_FORKS: "3" })).toBe("|3|"); expect(caps({ VITEST_MAX_THREADS: "50%" })).toBe("||50%"); });});describe("what a run started by a git hook hands its tests", () => {/// RULE: nothing verify:fast runs sees the environment git hands a hook.// Git exports `GIT_DIR` to a hook; a test's `git init` in a temp directory// then writes to the repository being pushed (2026-09-27: fixture commits on// `main`, `core.bare = true`, `origin/main` overwritten). it("drops GIT_DIR and its siblings before cargo or pnpm runs", () => {const seen = join(mkdtempSync(join(tmpdir(), "verify-fast-env-")), "seen.log");const bin = stubs({ cargo: 'printf "cargo %s %s\\n" "${GIT_DIR:-unset}" "${GIT_INDEX_FILE:-unset}" >> "$COTTON_SEEN"; exit 0', pnpm: 'printf "pnpm %s %s\\n" "${GIT_DIR:-unset}" "${GIT_COMMON_DIR:-unset}" >> "$COTTON_SEEN"; exit 0', });const r = run(VERIFY, bin, { COTTON_SEEN: seen, GIT_DIR: "/somewhere/else", GIT_INDEX_FILE: "/somewhere/else/index", GIT_COMMON_DIR: "/somewhere/else", }); expect(r.status, r.out).toBe(0);const lines = readFileSync(seen, "utf8").trim().split("\n"); expect(lines.length).toBeGreaterThan(1);for (const line of lines) expect(line).toMatch(/^(cargo|pnpm) unset unset$/); }); it("drops them inside the test run too, for a run that did not come through verify:fast", () => {const env: NodeJS.ProcessEnv = { GIT_DIR: "/x/.git", GIT_WORK_TREE: "/x", PATH: "/usr/bin" }; expect(dropGitLocalEnv(env)).toEqual(["GIT_DIR", "GIT_WORK_TREE"]); expect(env).toEqual({ PATH: "/usr/bin" });// This very process was started with the setup file in place.for (const name of GIT_LOCAL_ENV) expect(process.env[name], name).toBeUndefined(); }); it("names every variable git calls local", () => {const git = execFileSync("git", ["rev-parse", "--local-env-vars"], { encoding: "utf8" }).trim().split("\n");for (const name of git) expect(GIT_LOCAL_ENV).toContain(name); });});describe("verify-fast.sh takes the machine's build mutex on a Mac", () => {// PR #1026 (todo bb40fae2, defect 2): a Swift test died with a signal while// a hand-run cargo had the same Mac's memory; two `swift` CI jobs on the signing Mac// died mid-compile on 27 Sep 2026 beside a session's cargo runs. CI's cargo// steps queue behind `/tmp/tinmen-build.lock` (`scripts/ci/with-machine-lock.sh`);// The manual verify command takes the same lock. On Linux nothing is taken. it("runs cargo under the lock, labelled local-verify-fast, on Darwin only", () => {const bin = stubs({ cargo: `echo "lock=\${TINMEN_BUILD_LOCK_LABEL:-none}"; exit 0`, pnpm: "exit 0", });// The Mac's lock admits through the device policy, which reads a scratch// HOME's fresh reading — never the person's HOME.const home = join(scratch, "home"); publishDiskReading(home);// A byte of RAM per build: admission must not turn on the machine's free RAM. publishBuildPeaks(home);const onMac = run(VERIFY, bin, { COTTON_MACHINE_LOCK_OS: "Darwin", BUILD_LOCK_DIR: join(scratch, "lock"), HOME: home }); expect(onMac.status, onMac.out).toBe(0); expect(onMac.out).toContain("lock=local-verify-fast");const onLinux = run(VERIFY, bin, { BUILD_LOCK_DIR: join(scratch, "lock") }); expect(onLinux.status, onLinux.out).toBe(0); expect(onLinux.out).toContain("lock=none"); });});