commit 17949856828aff12ef97f8aa37a8bf942694015b
parent 15bcd92e777f2c65e81d78f3f9f15ff91ede30c1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 6 Nov 2026 14:06:13 -0500
scripts: wt add/rm respect checkouts that still compute ports from their place; wt prune keeps ignored content that is somebody's
Review of lane/housekeeping:
- `git worktree list` sorts by path, and a checkout whose worktree.mjs
predates records still computes `index * 100`, so `wt add` could record
the very block an old checkout moves onto (today r13-phase-5's). While any
old checkout remains, `wt add` records above (list length + 10) × 100
(newBlockFor), and says when the new worktree moved an old one by a block.
`wt rm` refuses to remove a worktree before an old checkout (--anyway),
the guard `wt prune` already had (oldCheckoutsAfter).
- `wt prune` keeps a worktree holding ignored content that is somebody's,
which `git worktree remove` would delete with it: a real transcripts/
directory, any .env* file, a settings.json not byte-identical to the main
checkout's, a git repository inside an ignored directory. The scan walks
ignored directories (a directory of ignored files is reported collapsed),
never through a link, not into node_modules/.next/build output; the
reason names what it found.
Docs: WORKTREES.md (the transition's three rules, the new condition). Tests:
newBlockFor, a mixed old/new repo where `wt add` lands clear of the old
checkout's block and `wt rm` refuses then passes with --anyway, and prune
keeping a corpus, an env file, a changed settings.json and a nested repo
while removing a seeded settings.json and a linked transcripts.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
3 files changed, 222 insertions(+), 11 deletions(-)
diff --git a/WORKTREES.md b/WORKTREES.md
@@ -45,9 +45,17 @@ worktree remove` refuse.)
lowest free one. `wt list` marks such a block `(computed: not recorded yet)` or `(moved: …)`.
**Transition.** A worktree whose own checkout predates this (its `scripts/worktree.mjs` does
-not read records) still computes `index * 100` itself. `wt prune` therefore never removes a
-worktree that sits BEFORE such a checkout in the list; merging main into that branch, or its
-removal, lifts it.
+not read records) still computes `index * 100` itself, from its place in the list. While one
+remains:
+
+- `wt add` records a block above anything such a checkout could compute: above (the list's
+ length + 10) × 100, not the lowest free one. It says so when the new worktree sorts before an
+ old checkout and so moves it one block up (a server started there afterwards binds the next
+ block);
+- `wt rm` refuses to remove a worktree that sits before one (`--anyway` when nothing runs there);
+- `wt prune` never removes a worktree that sits before one.
+
+Merging main into that branch, or its removal, lifts all three.
## Commands
@@ -56,8 +64,9 @@ pnpm wt ports # print this worktree's assigned ports (table + KE
pnpm wt list # list all worktrees with their port blocks
pnpm wt add <branch> # create a sibling worktree, seeded + ports printed
pnpm wt add <branch> --from <ref> --share-data
-pnpm wt rm <name> [--force] # remove a worktree (--force if it has local files,
- # e.g. a --share-data worktree's .worktree-env)
+pnpm wt rm <name> [--force] [--anyway]
+ # remove a worktree (--force if it has local files, e.g. a
+ # --share-data worktree's .worktree-env; --anyway past an old checkout)
pnpm wt prune [--dry-run] [--json] [--base main] [--idle 3d] [--no-measure]
# remove the worktrees that are done (below)
pnpm wt run -- <cmd...> # run a command with this worktree's ports injected
@@ -74,6 +83,10 @@ it stays:
- its branch is an ancestor of `main` (`--base`): merged, so nothing on it is lost;
- its tree is clean — no tracked change and no untracked file (`git status --porcelain`;
ignored files such as `node_modules` and `.next` do not count, and go with it);
+- no ignored content in it is somebody's — `git worktree remove` deletes ignored files with the
+ tree: a real (not linked) `transcripts/` directory, any `.env*` file, a `settings.json` that is
+ not byte-identical to the main checkout's (`wt add` seeds a copy), or a git repository inside an
+ ignored directory (`node_modules`, `.next` and other build output are not searched);
- no process has its working directory in it (`/proc/*/cwd`: a dev server, a suite, a shell);
- it is not locked (`git worktree lock`), and its directory exists;
- its git state (HEAD, index, reflog, creation) was not touched within `--idle` (default
diff --git a/scripts/worktree.mjs b/scripts/worktree.mjs
@@ -138,6 +138,24 @@ export function writeRecord(wtPath, offset, by, now = new Date()) {
return true;
}
+/** How many worktrees a checkout that computes its block from its index may yet gain before a new record is reached. */
+export const OLD_CHECKOUT_HEADROOM = 10;
+
+/**
+ * The block `wt add` records: the lowest one no worktree uses -- and, while
+ * any listed checkout still computes `index * 100` itself (its worktree.mjs
+ * predates records), one above every block such a checkout could reach:
+ * the list's length plus OLD_CHECKOUT_HEADROOM, times 100.
+ * @param {{ path: string, prunable?: boolean }[]} list every worktree, the new one included
+ * @param {number[]} used the offsets the others have
+ * @param {(p: string) => boolean} [isOld]
+ */
+export function newBlockFor(list, used, isOld = (p) => !knowsRecords(p)) {
+ const old = list.some((t, i) => i > 0 && !t.prunable && isOld(t.path));
+ const reach = old ? Array.from({ length: list.length + OLD_CHECKOUT_HEADROOM + 1 }, (_, k) => k * OFFSET_STEP) : [];
+ return lowestFreeOffset([0, ...used, ...reach]);
+}
+
/** The lowest offset above 0 that is not in `used`. */
export function lowestFreeOffset(used) {
const taken = new Set(used);
@@ -414,9 +432,20 @@ function cmdAdd(args) {
}
}
- // The lowest block no worktree uses, recorded.
- const others = blocks().filter((b) => realpath(b.path) !== realpath(dir));
- const offset = lowestFreeOffset(others.map((b) => b.offset));
+ // The lowest block no worktree uses, recorded -- and, while a checkout that
+ // predates recorded blocks remains, above every block such a checkout could
+ // compute (index * 100) now or after OLD_CHECKOUT_HEADROOM more worktrees.
+ const after = blocks();
+ const others = after.filter((b) => realpath(b.path) !== realpath(dir));
+ const offset = newBlockFor(after, others.map((b) => b.offset));
+ const at = after.findIndex((x) => realpath(x.path) === realpath(dir));
+ const shifted = after.filter((b, i) => i > at && at > 0 && !b.prunable && !knowsRecords(b.path));
+ if (shifted.length) {
+ process.stderr.write(
+ `note: ${shifted.map((b) => b.branch ?? b.path).join(", ")} still compute${shifted.length === 1 ? "s" : ""} ports from ${shifted.length === 1 ? "its" : "their"} place in the list, ` +
+ `which this worktree moved by one block (a server started there from now on binds the next block up; merging main into ${shifted.length === 1 ? "it" : "them"} ends that)\n`,
+ );
+ }
if (!writeRecord(dir, offset, "add")) process.stderr.write(`could not record ${dir}'s port block; it is computed until it is\n`);
const ports = portsForOffset(offset);
process.stderr.write(`\nWorktree ready at ${dir}\n`);
@@ -427,17 +456,37 @@ function cmdAdd(args) {
return 0;
}
+/**
+ * The checkouts whose ports removing worktree `dir` would move: the ones after
+ * it in the list whose own worktree.mjs still computes `index * 100`.
+ */
+export function oldCheckoutsAfter(list, dir, isOld = (p) => !knowsRecords(p)) {
+ const at = list.findIndex((t) => realpath(t.path) === realpath(dir));
+ if (at < 1) return [];
+ return list.filter((t, i) => i > at && !t.prunable && isOld(t.path));
+}
+
function cmdRm(args) {
const force = args.includes("--force") || args.includes("-f");
- const name = args.find((a) => a !== "--force" && a !== "-f");
+ const anyway = args.includes("--anyway");
+ const name = args.find((a) => a !== "--force" && a !== "-f" && a !== "--anyway");
if (!name) {
- process.stderr.write("worktree rm: usage: rm <name|path> [--force]\n");
+ process.stderr.write("worktree rm: usage: rm <name|path> [--force] [--anyway]\n");
return 1;
}
const main = mainRoot();
// Sanitized exactly as `add` sanitized it, so `rm <the branch you added>`
// finds the directory `add` actually made.
const dir = worktreeDirFor(main, name);
+ // A checkout after this one that computes its ports from its place would move.
+ const moved = oldCheckoutsAfter(listWorktrees(), dir);
+ if (moved.length && !anyway) {
+ process.stderr.write(
+ `worktree rm: refused — removing ${dir} would move the ports of ${moved.map((t) => t.branch ?? t.path).join(", ")} ` +
+ `(${moved.length === 1 ? "its" : "their"} scripts/worktree.mjs predates recorded port blocks): merge main into ${moved.length === 1 ? "it" : "them"}, or pass --anyway when nothing runs there\n`,
+ );
+ return 1;
+ }
// The others keep their blocks: removing this one would move the later ones'.
pinAll(undefined, "rm");
// --share-data worktrees always carry an untracked .worktree-env, so git
@@ -524,6 +573,77 @@ export function freeableBytes(dir) {
return bytes;
}
+/** Ignored directories a nested-repository search does not enter: built or installed, never anyone's work. */
+const NO_DESCEND = new Set(["node_modules", ".next", ".turbo", ".cache", "test-results", "blob-report", ".export-builds", "out", "dist"]);
+
+/**
+ * IGNORED CONTENT THAT IS SOMEBODY'S, which `git worktree remove` would delete
+ * with the tree because git ignores it: a real (not linked) `transcripts/`
+ * directory, any `.env*` file, a `settings.json` that is not byte-identical to
+ * the main checkout's (`wt add` seeds a copy), and any nested git repository
+ * in an ignored directory. Each found is a sentence; [] when none.
+ * @param {string} wtPath
+ * @param {string} mainPath
+ */
+export function realIgnoredContent(wtPath, mainPath) {
+ let out;
+ try {
+ out = git(["--no-optional-locks", "status", "--porcelain=v1", "--ignored=traditional", "--untracked-files=normal"], { cwd: wtPath });
+ } catch (e) {
+ return [`its ignored files could not be listed (${String(e?.message ?? e).split("\n")[0]})`];
+ }
+ const found = [];
+ const mainSettings = (() => {
+ try {
+ return fs.readFileSync(path.join(mainPath, "settings.json"));
+ } catch {
+ return null;
+ }
+ })();
+ const seen = new Set();
+ const judge = (abs, rel, depth) => {
+ if (found.length >= 10 || seen.has(abs)) return;
+ seen.add(abs);
+ const name = path.basename(rel);
+ let st;
+ try {
+ st = fs.lstatSync(abs);
+ } catch {
+ return;
+ }
+ if (st.isSymbolicLink()) return; // a link is removed as a link: what it points at stays
+ if (name === "transcripts" && st.isDirectory()) return void found.push(`a real ${rel}/ directory (not a link)`);
+ if (/^\.env/.test(name) && st.isFile()) return void found.push(`${rel} (an env file)`);
+ if (rel === "settings.json" && st.isFile()) {
+ let same = false;
+ try {
+ same = mainSettings !== null && fs.readFileSync(abs).equals(mainSettings);
+ } catch {
+ same = false;
+ }
+ if (!same) found.push("settings.json, not the same as the main checkout's");
+ return;
+ }
+ if (/^settings\.json./.test(name) && st.isFile()) return void found.push(`${rel} (a settings copy)`);
+ if (!st.isDirectory() || NO_DESCEND.has(name)) return;
+ if (fs.existsSync(path.join(abs, ".git"))) return void found.push(`a git repository inside ${rel}/`);
+ if (depth <= 0) return;
+ let entries = [];
+ try {
+ entries = fs.readdirSync(abs);
+ } catch {
+ return;
+ }
+ for (const n of entries) judge(path.join(abs, n), `${rel}/${n}`, depth - 1);
+ };
+ for (const line of out.split("\n")) {
+ if (!line.startsWith("!! ")) continue;
+ const rel = line.slice(3).replace(/^"|"$/g, "").replace(/\/$/, "");
+ judge(path.join(wtPath, rel), rel, 4);
+ }
+ return found;
+}
+
/**
* WHICH WORKTREES `wt prune` WOULD REMOVE, and why each other one stays.
* Reads only. `cwd` is any directory of the repository.
@@ -556,6 +676,8 @@ export function planWorktreePrune({ cwd = process.cwd(), base = "main", idleMs =
const n = status.split("\n").length;
return keep("dirty", `not clean: ${n} changed or untracked path${n === 1 ? "" : "s"} (${status.split("\n")[0].trim()}${n > 1 ? ", …" : ""})`);
}
+ const mine = realIgnoredContent(t.path, list[0].path);
+ if (mine.length) return keep("ignored-content", `holds ignored content that is somebody's: ${mine.slice(0, 3).join("; ")}${mine.length > 3 ? "; …" : ""}`);
const real = realpath(t.path);
const inIt = procs.filter((p) => p.cwd === real || p.cwd.startsWith(real + path.sep) || p.cwd === t.path || p.cwd.startsWith(t.path + path.sep));
if (inIt.length) return keep("process", `a process works in it (pid ${inIt.slice(0, 5).map((p) => p.pid).join(", ")}${inIt.length > 5 ? ", …" : ""})`);
@@ -663,7 +785,7 @@ function usage() {
` run -- <cmd...> Run a command with ports injected into env (records the block)\n` +
` list List worktrees and their port blocks\n` +
` add <branch> [--from <ref>] [--share-data] [--no-install] Create a pre-configured worktree (installs deps unless --no-install); records the lowest free port block\n` +
- ` rm <name|path> [--force] Remove a worktree (--force if it has local files)\n` +
+ ` rm <name|path> [--force] [--anyway] Remove a worktree (--force if it has local files; --anyway past a checkout whose ports it would move)\n` +
` prune [--dry-run] [--json] [--base main] [--idle 3d] [--no-measure]\n` +
` Remove worktrees whose branch is merged into main, clean, idle, with no\n` +
` process in them (git worktree remove, never --force; branches kept)\n`,
diff --git a/scripts/worktree.test.mjs b/scripts/worktree.test.mjs
@@ -212,3 +212,79 @@ test("wt add records the lowest free block and pins the others first", (t) => {
assert.match(list, /b-new\s+editor:3101/);
assert.match(list, /z-later\s+editor:3301/);
});
+
+// ---- review fixes (6 Nov): old checkouts beside new records; ignored real content ----
+
+import { OLD_CHECKOUT_HEADROOM, newBlockFor, oldCheckoutsAfter, realIgnoredContent } from "./worktree.mjs";
+
+test("newBlockFor: lowest free with no old checkout; above anything an old checkout could compute while one remains", () => {
+ const list = [{ path: "/m" }, { path: "/a" }, { path: "/b" }];
+ assert.equal(newBlockFor(list, [100], () => false), 200);
+ assert.equal(newBlockFor(list, [100], (p) => p === "/b"), (list.length + OLD_CHECKOUT_HEADROOM + 1) * 100);
+ // A gone (prunable) old checkout computes nothing.
+ assert.equal(newBlockFor([{ path: "/m" }, { path: "/a" }, { path: "/b", prunable: true }], [100], (p) => p === "/b"), 200);
+});
+
+test("wt add beside an old checkout records a block it cannot reach, and says it moved; wt rm refuses to move one", (t) => {
+ const r = repo();
+ t.after(() => fs.rmSync(r.top, { recursive: true, force: true }));
+ const a = r.add("a-new");
+ assert.equal(writeRecord(a, 100, "test"), true);
+ const old = r.add("r-old", { oldCode: true });
+ const res = spawnSync(process.execPath, [SCRIPT, "add", "b-new", "--no-install"], { cwd: r.main, env: gitEnv, encoding: "utf8" });
+ assert.equal(res.status, 0, res.stderr);
+ // After the add the list is main, a-new, b-new, r-old: r-old now computes 300 itself.
+ const got = readRecord(path.join(r.top, "b-new"));
+ assert.equal(got, (4 + OLD_CHECKOUT_HEADROOM + 1) * 100);
+ assert.notEqual(got, 300);
+ assert.match(res.stderr, /r-old still computes ports from its place in the list, which this worktree moved by one block/);
+
+ const list = parseWorktreeList(g(r.main, "worktree", "list", "--porcelain"));
+ assert.deepEqual(oldCheckoutsAfter(list, a).map((x) => x.branch), ["r-old"]);
+ assert.deepEqual(oldCheckoutsAfter(list, old), []);
+ const rm = spawnSync(process.execPath, [SCRIPT, "rm", a], { cwd: r.main, env: gitEnv, encoding: "utf8" });
+ assert.equal(rm.status, 1);
+ assert.match(rm.stderr, /refused — removing .*a-new would move the ports of r-old/);
+ assert.ok(fs.existsSync(a));
+ const anyway = spawnSync(process.execPath, [SCRIPT, "rm", a, "--anyway"], { cwd: r.main, env: gitEnv, encoding: "utf8" });
+ assert.equal(anyway.status, 0, anyway.stderr);
+ assert.equal(fs.existsSync(a), false);
+});
+
+test("wt prune keeps a worktree holding ignored content that is somebody's, and says what", (t) => {
+ const r = repo();
+ t.after(() => fs.rmSync(r.top, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(r.main, ".gitignore"), "node_modules\ntranscripts\n.env*\nsettings.json\ndata\n");
+ fs.writeFileSync(path.join(r.main, "settings.json"), '{"a":1}\n');
+ g(r.main, "add", ".gitignore");
+ g(r.main, "commit", "-q", "-m", "ignores");
+ const corpus = r.add("a-corpus");
+ const env = r.add("b-env");
+ const settings = r.add("c-settings");
+ const seeded = r.add("d-seeded");
+ const nested = r.add("e-nested");
+ const linked = r.add("f-linked");
+ fs.mkdirSync(path.join(corpus, "transcripts", "channels"), { recursive: true });
+ fs.writeFileSync(path.join(corpus, "transcripts", "channels", "x.json"), "{}");
+ fs.mkdirSync(path.join(env, "editor"), { recursive: true });
+ fs.writeFileSync(path.join(env, "editor", ".env.local"), "TOKEN=x\n");
+ fs.writeFileSync(path.join(settings, "settings.json"), '{"a":2}\n');
+ fs.copyFileSync(path.join(r.main, "settings.json"), path.join(seeded, "settings.json"));
+ fs.mkdirSync(path.join(nested, "data", "deep"), { recursive: true });
+ g(path.join(nested, "data", "deep"), "init", "-q");
+ fs.writeFileSync(path.join(nested, "data", "deep", "f"), "x");
+ fs.mkdirSync(path.join(linked, "node_modules", "pkg"), { recursive: true });
+ fs.writeFileSync(path.join(linked, "node_modules", "pkg", "index.js"), "x");
+ fs.symlinkSync(path.join(r.main, "settings.json"), path.join(linked, "transcripts"));
+ for (const x of [corpus, env, settings, seeded, nested, linked]) r.age(x);
+
+ assert.deepEqual(realIgnoredContent(seeded, r.main), []);
+ const plan = planWorktreePrune({ cwd: r.main, now: NOW, procs: [] });
+ assert.deepEqual(plan.remove.map((x) => path.basename(x.path)).sort(), ["d-seeded", "f-linked"]);
+ const why = Object.fromEntries(plan.kept.map((k) => [path.basename(k.path), k]));
+ assert.equal(why["a-corpus"].code, "ignored-content");
+ assert.match(why["a-corpus"].why, /a real transcripts\/ directory/);
+ assert.match(why["b-env"].why, /editor\/\.env\.local \(an env file\)/);
+ assert.match(why["c-settings"].why, /settings\.json, not the same as the main checkout's/);
+ assert.match(why["e-nested"].why, /a git repository inside data\/deep\//);
+});