Cotton code
106 lines · 5.3 KB · TypeScriptRaw
/** * `.worktrees/` holds OTHER commits, and nothing may read it by accident. * * `pnpm worktree:new` puts every in-flight branch under `.worktrees/<slug>/` * inside the primary checkout, so the primary's working tree contains a full * copy of the repo at some other commit for every lane that is running. A * search that walks the filesystem from the repo root therefore finds several * versions of the same file, and the one it reads first is whichever the * directory order hands over — a copy pinned before a merge, quite possibly a * copy of a file that main no longer has. Two lanes lost time to exactly that * on 2026-09-11, each reporting a claim about `main` that was only true of a * worktree. Cotton note "Repo landmines — why the build's rules exist" carries the rule for people; * this is the half a machine can keep. * * Three things are pinned here: * *   1. git ignores `.worktrees/`, so anything asking git — `git grep`, *      `git ls-files`, ripgrep in its default mode — cannot see it at all. *   2. a root `.ignore` says so too, for the search tools that read `.ignore` *      but do not consult the VCS ignore file (ripgrep under *      `--no-ignore-vcs`, and several editor and agent search backends). *   3. no sweep under `scripts/` walks the repo ROOT. Today none does — every *      one of them walks a named subdirectory, or asks `git ls-files` — and *      this is the tripwire that says so the day one starts, because such a *      sweep would silently start reading every other lane's copy of the tree *      and would go GREEN on a stale file rather than red. */import { existsSync, readFileSync, readdirSync } from "node:fs";import { join } from "node:path";import { describe, expect, it } from "vitest";const ROOT = join(__dirname, "..", "..");/** * Does this source walk the repo root itself? * * A recursive walker or a `readdirSync` handed the bare root identifier, with * no subdirectory joined on. Anything narrower is fine: `.worktrees/` is a * root-level directory, so a walk of `crates` or `apps` can never reach it. */export function walksTheRepoRoot(source: string): boolean {  // A walker's name starts with walk (walk, walkFiles) or ends with it (treeWalk); a name that only holds Walk  // in its middle (thisWalkHost, which reads lane-macs.json under the root) walks nothing.  return /(?:readdirSync|\b(?:walk\w*|\w*[Ww]alk))\(\s*(?:ROOT|REPO_ROOT)\s*[,)]/.test(source);}/** Does it then say it skips the worktrees? */export function excludesWorktrees(source: string): boolean {  return /\.worktrees/.test(source);}function sweepSources(): { name: string; text: string }[] {  const found: { name: string; text: string }[] = [];  for (const dir of ["scripts", join("scripts", "__tests__")]) {    const base = join(ROOT, dir);    if (!existsSync(base)) continue;    for (const entry of readdirSync(base, { withFileTypes: true })) {      if (!entry.isFile()) continue;      if (!/\.(ts|mjs|js)$/.test(entry.name)) continue;      found.push({ name: join(dir, entry.name), text: readFileSync(join(base, entry.name), "utf8") });    }  }  return found;}describe("`.worktrees/` is invisible to anything that sweeps the tree", () => {  it("is ignored by git, so git grep and ripgrep's default mode cannot reach it", () => {    const gitignore = readFileSync(join(ROOT, ".gitignore"), "utf8");    expect(gitignore, ".gitignore no longer ignores .worktrees/ — every repo-wide grep now reads other lanes' commits").toMatch(      /^\.worktrees\/$/m,    );  });  it("is ignored by a root `.ignore` too, for the tools that skip the VCS ignore file", () => {    const path = join(ROOT, ".ignore");    expect(existsSync(path), "no root .ignore — `rg --no-ignore-vcs` and several editor search backends would descend into .worktrees/").toBe(      true,    );    expect(readFileSync(path, "utf8")).toMatch(/^\.worktrees\/$/m);  });  it("is not reachable from any sweep under scripts/, because none walks the repo root", () => {    const offenders = sweepSources()      .filter(({ text }) => walksTheRepoRoot(text) && !excludesWorktrees(text))      .map(({ name }) => name);    expect(      offenders,      `these walk the repo ROOT and never exclude .worktrees/, so on the primary checkout they read every other lane's copy of the tree and go green on a stale file:\n${offenders.join(        "\n",      )}`,    ).toEqual([]);  });  // A tripwire that cannot fire is not a tripwire. The detector is exercised  // on samples here rather than trusted because today's answer is "none".  it("the detector fires on a root walk and stays quiet on a narrower one", () => {    expect(walksTheRepoRoot("const files = walk(ROOT);")).toBe(true);    expect(walksTheRepoRoot("const files = walkFiles(REPO_ROOT, keep);")).toBe(true);    expect(walksTheRepoRoot("for (const e of readdirSync(ROOT)) {}")).toBe(true);    expect(walksTheRepoRoot('const files = walk(join(ROOT, "crates"));')).toBe(false);    expect(walksTheRepoRoot('const files = walkFiles(join(REPO_ROOT, "apps"), keep);')).toBe(false);    expect(walksTheRepoRoot('execFileSync("git", ["ls-files"], { cwd: ROOT });')).toBe(false);    expect(walksTheRepoRoot("const files = treeWalk(ROOT);")).toBe(true);    expect(walksTheRepoRoot("const HOST = thisWalkHost(ROOT);")).toBe(false);  });});