commit f2e7d2fe3d2d8976b025a105176afe62485f21e9
parent 4ee40d8fd477fa87c1ae4683f1e4b4487f289611
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 6 Nov 2026 13:01:11 -0500
scripts: worktree port blocks are recorded and never move; `wt prune` removes the worktrees that are done
A worktree's ports were `index * 100`, the index its place in `git worktree
list`, which git sorts by name: removing a worktree moved every later
worktree's ports, so a suite running in one of them collided mid-run (the
6 Nov cleanup had to leave three merged worktrees standing for exactly that).
Now a block is recorded in the worktree's git admin directory
(archilyzer-ports.json: deleted with it, never in `git status`, unlike
.worktree-env, which makes a plain `git worktree remove` refuse):
- `wt add` records the lowest block no worktree uses; `wt add`, `wt rm` and
`wt prune` first pin every unrecorded worktree at the block it has now;
`wt run` records its own block before a server binds it;
- an unrecorded worktree keeps `index * 100` unless a record has it
(resolveBlocks, pure); `wt list` says which blocks are not recorded yet.
`wt prune [--dry-run] [--json] [--base main] [--idle 3d]` removes a worktree
only when its branch is an ancestor of main, its tree is clean (no tracked
change, no untracked file), no process has its cwd in it (/proc), it is not
locked, its git state is idle (a branch just cut from main is merged too),
and it does not sit before a checkout whose worktree.mjs still computes ports
from its index. `git worktree remove`, never --force; branches kept; a dry
run reads status with --no-optional-locks so it writes nothing at all.
Docs: WORKTREES.md (the recorded blocks, the transition, prune). Tests: the
resolution, the porcelain's locked/prunable, a real repo with six worktrees
(what goes, each reason kept, branches kept, no survivor's block moved), the
old-checkout guard, and `wt add` recording the lowest free block.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
4 files changed, 605 insertions(+), 42 deletions(-)
diff --git a/WORKTREES.md b/WORKTREES.md
@@ -13,18 +13,41 @@ The helper is `scripts/worktree.mjs`, exposed as `pnpm wt`.
## Port scheme
-Each worktree gets an offset of `index * 100`, where `index` is the worktree's position in
-`git worktree list`. The **main** worktree is always first, so it keeps the original
-defaults — nothing changes for the primary checkout.
+Each worktree's ports are its **block**: an offset, a multiple of 100, added to every base
+port. The **main** worktree's is 0, so it keeps the original defaults — nothing changes for the
+primary checkout.
The port table itself is `common/lib/ports.mjs` — one copy, which `scripts/worktree.mjs`
offsets and `pnpm archilyzer doctor` reports. Every port, its base and what uses it is in
**[ENVIRONMENT.md → Ports](ENVIRONMENT.md#ports)** (generated from it). The injector also
sets `PLAYWRIGHT_BASE_URL` (`http://localhost:<PORT>`) for node-side fetches in specs.
-So worktree #1 runs editor on **3101**, test server on **3111**, export on **3110**, etc.
-The hundreds digit is the worktree index. The allocator never overrides a variable already
-set in the environment, so CI and manual overrides always win.
+So the worktree with block 100 runs editor on **3101**, test server on **3111**, export on
+**3110**, etc. The allocator never overrides a variable already set in the environment, so CI
+and manual overrides always win; `.worktree-env` sets single variables under `wt run` too.
+
+### Blocks are recorded, so they never move
+
+A block used to be `index * 100`, the index being the worktree's position in `git worktree
+list` — which git sorts by name, so removing (or adding) a worktree moved every later one's
+ports, and a suite running in one of them collided mid-run. Now a worktree's block is
+**recorded** in its git admin directory, `.git/worktrees/<name>/archilyzer-ports.json`
+(`{offset, by, at}`): invisible to `git status`, deleted with the worktree by `git worktree
+remove`. (`.worktree-env` is not used for it: an untracked file there makes a plain `git
+worktree remove` refuse.)
+
+- `wt add` records the **lowest block no worktree uses** for the new one;
+- `wt add`, `wt rm` and `wt prune` first record every worktree that has none at the block it
+ has now ("pinning"), so the change they make to the list moves nobody;
+- `wt run` (every `pnpm dev:*`, `pnpm e2e`) records its own worktree's block before it binds it;
+- a worktree with no record (one made by plain `git worktree add`, or `.claude/worktrees/*`)
+ keeps `index * 100` — unless a recorded worktree already has that block, when it takes the
+ 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.
## Commands
@@ -35,12 +58,36 @@ pnpm wt add <branch> # create a sibling worktree, seeded + ports printe
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 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
```
`pnpm dev:editor`, `pnpm dev:export`, `pnpm start:export`, and `pnpm e2e` already run through
`wt run`, so they pick up the right ports automatically — no manual setup needed.
+### Removing the worktrees that are done: `pnpm wt prune`
+
+A worktree is removed only when ALL of these hold; every other one is listed with the reason
+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 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
+ 3 days) — a branch just made from `main` is an ancestor of it too, and an agent about to
+ start on it has no process in it yet;
+- it does not sit before a checkout that still computes its ports from its index
+ ("Transition" above).
+
+It runs `git worktree remove <path>` (never `--force`), keeps every branch, and records every
+other worktree's block first. `--dry-run` writes nothing (not even a refreshed index: the
+status is read with `--no-optional-locks`). The bytes are "about": allocated blocks of files
+with one link (a pnpm store's hard links are not freed). `archilyzer housekeeping` runs it
+weekly ([OPERATING.md](OPERATING.md), "Free disk").
+
### Load the ports into your shell (fish)
```fish
diff --git a/common/lib/ports.mjs b/common/lib/ports.mjs
@@ -1,8 +1,10 @@
// THE PORT DEFAULTS — the one copy.
//
// Every local server this repo starts has a default port, and a worktree adds
-// `index * OFFSET_STEP` to all of them (scripts/worktree.mjs, WORKTREES.md), so
-// the primary checkout keeps the numbers below and worktree #3 gets 33xx.
+// its block's offset, a multiple of OFFSET_STEP, to all of them -- recorded per
+// worktree since 2026-11-06 (scripts/worktree.mjs, WORKTREES.md) -- so the
+// primary checkout keeps the numbers below and the worktree with block 300
+// gets 33xx.
//
// Plain JS with JSDoc, like ytdlp/platformArgs.mjs, because the first reader is
// scripts/worktree.mjs, which runs under bare `node`. TS callers (the CLI's
@@ -57,7 +59,7 @@ export const PORT_BASES = Object.freeze(
Object.fromEntries(Object.entries(PORTS).map(([k, v]) => [k, v.base])),
);
-/** A worktree's block is `index * OFFSET_STEP` above the bases. */
+/** A worktree's block is a multiple of OFFSET_STEP above the bases. */
export const OFFSET_STEP = 100;
/**
diff --git a/scripts/worktree.mjs b/scripts/worktree.mjs
@@ -1,11 +1,31 @@
#!/usr/bin/env node
-// Git worktree helper: deterministic non-colliding ports per worktree, a wrapper
-// that injects them into dev/e2e commands, and add/list/rm lifecycle commands.
+// Git worktree helper: non-colliding, STABLE ports per worktree, a wrapper
+// that injects them into dev/e2e commands, and add/list/rm/prune lifecycle
+// commands.
//
-// Ports are offset by `worktreeIndex * 100`, where the index is the worktree's
-// position in `git worktree list` (the main worktree is first -> index 0 ->
-// default ports unchanged). So the main checkout behaves exactly as before, and
-// each extra worktree gets a clean 31xx / 32xx / ... block. See WORKTREES.md.
+// A worktree's port block is `offset` above the bases (common/lib/ports.mjs),
+// a multiple of OFFSET_STEP; the main worktree's is 0, so the main checkout
+// behaves exactly as before.
+//
+// WHICH OFFSET (2026-11-06). It used to be `index * 100`, the index being the
+// worktree's position in `git worktree list` -- which git sorts by name, so
+// removing (or adding) a worktree moved every later worktree's ports, and a
+// suite running in one of them collided mid-run. Now a worktree's block is
+// RECORDED: `archilyzer-ports.json` in its git admin directory
+// (`<common .git>/worktrees/<name>/`, which `git worktree remove` deletes with
+// it and `git status` never shows -- unlike `.worktree-env`, an untracked file
+// that makes a plain `git worktree remove` refuse). `wt add` records the
+// lowest block no worktree uses; `wt add`, `wt prune` and `wt run` first
+// record ("pin") every worktree that has none at the block it has now; and a
+// worktree with no record keeps its computed block (`index * 100`) unless a
+// recorded one already has it, when it takes the lowest free one.
+// `.worktree-env` still overrides single variables under `wt run`.
+//
+// `wt prune` removes worktrees that are done: the branch an ancestor of main,
+// the tree clean (no tracked change, no untracked file), no process working in
+// it (/proc/*/cwd), not locked, not touched for --idle (default 3d: a branch
+// just made from main is an ancestor of it too). `git worktree remove`, never
+// --force; the branches are kept. See WORKTREES.md.
import { execFileSync, spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
@@ -15,12 +35,25 @@ import { OFFSET_STEP, portsForOffset } from "../common/lib/ports.mjs";
// The port table — names, bases and the offset step — is common/lib/ports.mjs,
// the one copy. This file only decides WHICH offset a checkout gets.
+/** The record's name, in a worktree's git admin directory. */
+export const PORT_RECORD = "archilyzer-ports.json";
+
function git(args, opts = {}) {
// With stdio:"inherit" execFileSync returns null (output not captured).
const out = execFileSync("git", args, { encoding: "utf8", ...opts });
return out == null ? "" : out.trim();
}
+/** git's exit status alone (0 yes, 1 no), for the yes/no questions. */
+function gitOk(args, opts = {}) {
+ try {
+ execFileSync("git", args, { stdio: ["ignore", "ignore", "ignore"], ...opts });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
function realpath(p) {
try {
return fs.realpathSync(p);
@@ -29,14 +62,14 @@ function realpath(p) {
}
}
-// Parse `git worktree list --porcelain` into [{ path, branch, head }], in order.
-function listWorktrees() {
- const out = git(["worktree", "list", "--porcelain"]);
+// Parse `git worktree list --porcelain` into
+// [{ path, branch, head, locked, prunable }], in order.
+export function parseWorktreeList(out) {
const trees = [];
let cur = null;
for (const line of out.split("\n")) {
if (line.startsWith("worktree ")) {
- cur = { path: line.slice("worktree ".length), branch: null, head: null };
+ cur = { path: line.slice("worktree ".length), branch: null, head: null, locked: false, prunable: false };
trees.push(cur);
} else if (cur && line.startsWith("branch ")) {
cur.branch = line.slice("branch ".length).replace("refs/heads/", "");
@@ -44,16 +77,122 @@ function listWorktrees() {
cur.head = line.slice("HEAD ".length).slice(0, 12);
} else if (cur && line === "detached") {
cur.branch = "(detached)";
+ } else if (cur && (line === "locked" || line.startsWith("locked "))) {
+ cur.locked = true;
+ } else if (cur && (line === "prunable" || line.startsWith("prunable "))) {
+ cur.prunable = true;
}
}
return trees;
}
+function listWorktrees(cwd = undefined) {
+ return parseWorktreeList(git(["worktree", "list", "--porcelain"], cwd ? { cwd } : {}));
+}
+
// The main worktree is always the first entry of `git worktree list`.
function mainRoot(trees = listWorktrees()) {
return trees.length ? trees[0].path : git(["rev-parse", "--show-toplevel"]);
}
+// ---- the recorded port blocks ------------------------------------------------
+
+/**
+ * A linked worktree's git admin directory, from its `.git` file
+ * (`gitdir: <dir>`, absolute or relative to the worktree). Null for the main
+ * worktree (`.git` is a directory) and for one whose directory is gone.
+ */
+export function adminDirOf(wtPath) {
+ let text;
+ try {
+ const st = fs.lstatSync(path.join(wtPath, ".git"));
+ if (!st.isFile()) return null;
+ text = fs.readFileSync(path.join(wtPath, ".git"), "utf8");
+ } catch {
+ return null;
+ }
+ const m = /^gitdir:\s*(.+)$/m.exec(text);
+ return m ? path.resolve(wtPath, m[1].trim()) : null;
+}
+
+/** The recorded offset of a worktree, or null (none, or not one this file wrote). */
+export function readRecord(wtPath) {
+ const dir = adminDirOf(wtPath);
+ if (!dir) return null;
+ try {
+ const j = JSON.parse(fs.readFileSync(path.join(dir, PORT_RECORD), "utf8"));
+ return Number.isInteger(j?.offset) && j.offset > 0 && j.offset % OFFSET_STEP === 0 ? j.offset : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Record a worktree's offset (tmp + rename). False when it has no admin directory. */
+export function writeRecord(wtPath, offset, by, now = new Date()) {
+ const dir = adminDirOf(wtPath);
+ if (!dir || !fs.existsSync(dir)) return false;
+ const file = path.join(dir, PORT_RECORD);
+ const tmp = `${file}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, JSON.stringify({ offset, by, at: now.toISOString(), path: wtPath }) + "\n");
+ fs.renameSync(tmp, file);
+ return true;
+}
+
+/** The lowest offset above 0 that is not in `used`. */
+export function lowestFreeOffset(used) {
+ const taken = new Set(used);
+ let o = OFFSET_STEP;
+ while (taken.has(o)) o += OFFSET_STEP;
+ return o;
+}
+
+/**
+ * EVERY WORKTREE'S BLOCK, pure: `records[i]` is worktree i's recorded offset
+ * or null. The main worktree (0) is 0. A recorded one has its record. One
+ * with none keeps `index * OFFSET_STEP` unless that is taken (by a record, or
+ * an earlier unrecorded one), when it gets the lowest free offset.
+ * @param {(number | null)[]} records
+ * @returns {{ offset: number, source: "main" | "recorded" | "computed" | "moved" }[]}
+ */
+export function resolveBlocks(records) {
+ const out = records.map(() => ({ offset: 0, source: /** @type {"main" | "recorded" | "computed" | "moved"} */ ("main") }));
+ const used = new Set([0]);
+ records.forEach((r, i) => {
+ if (i > 0 && r !== null && !used.has(r)) {
+ out[i] = { offset: r, source: "recorded" };
+ used.add(r);
+ }
+ });
+ records.forEach((r, i) => {
+ if (i === 0 || out[i].source === "recorded") return;
+ const want = i * OFFSET_STEP;
+ const offset = used.has(want) ? lowestFreeOffset(used) : want;
+ out[i] = { offset, source: offset === want ? "computed" : "moved" };
+ used.add(offset);
+ });
+ return out;
+}
+
+/** The worktrees with their blocks: [{ ...tree, offset, source }]. */
+function blocks(cwd = undefined) {
+ const trees = listWorktrees(cwd);
+ const resolved = resolveBlocks(trees.map((t, i) => (i === 0 ? null : readRecord(t.path))));
+ return trees.map((t, i) => ({ ...t, ...resolved[i] }));
+}
+
+/**
+ * Record every linked worktree that has no record at the block it has now, so
+ * a later add or remove cannot move it. Returns what it recorded.
+ */
+function pinAll(cwd = undefined, by = "pin", { dryRun = false } = {}) {
+ const pinned = [];
+ for (const b of blocks(cwd)) {
+ if (b.source === "main" || b.source === "recorded" || b.prunable) continue;
+ if (dryRun || writeRecord(b.path, b.offset, by)) pinned.push({ path: b.path, branch: b.branch, offset: b.offset });
+ }
+ return pinned;
+}
+
// WHERE A WORKTREE LIVES, asked the same way by `add` and by `rm`.
//
// A branch name may contain "/" and a sibling directory name may not, so `add`
@@ -69,17 +208,14 @@ export function worktreeDirFor(main, name) {
return path.join(path.dirname(main), name.replace(/[^A-Za-z0-9._-]/g, "-"));
}
-function offsetForIndex(index) {
- return index * OFFSET_STEP;
-}
-
-// Index of the worktree containing `dir` (default: cwd) in the worktree list.
-function indexForDir(dir = process.cwd()) {
- const trees = listWorktrees();
- return indexForPath(
- trees.map((t) => realpath(t.path)),
+// The block of the worktree containing `dir` (default: cwd).
+function blockForDir(dir = process.cwd()) {
+ const list = blocks();
+ const i = indexForPath(
+ list.map((t) => realpath(t.path)),
realpath(dir),
);
+ return { index: i, ...list[i] };
}
// THE MOST SPECIFIC root containing `target`, by its index in `roots` (0 when
@@ -119,7 +255,8 @@ function readEnvFile(file) {
function cmdPorts(args) {
const shellIdx = args.indexOf("--shell");
const shell = shellIdx !== -1 ? args[shellIdx + 1] : null;
- const ports = portsForOffset(offsetForIndex(indexForDir()));
+ const block = blockForDir();
+ const ports = portsForOffset(block.offset);
if (shell === "fish") {
for (const [k, v] of Object.entries(ports)) {
@@ -135,9 +272,8 @@ function cmdPorts(args) {
}
// Default: human-readable table on stderr, plain KEY=VALUE on stdout.
- const idx = indexForDir();
process.stderr.write(
- `worktree #${idx} (offset ${offsetForIndex(idx)}) ${realpath(process.cwd())}\n`,
+ `worktree #${block.index} (offset ${block.offset}, ${block.source}) ${realpath(process.cwd())}\n`,
);
for (const [k, v] of Object.entries(ports)) {
process.stderr.write(` ${k.padEnd(20)} ${v}\n`);
@@ -147,15 +283,16 @@ function cmdPorts(args) {
}
function cmdList() {
- const trees = listWorktrees();
- for (let i = 0; i < trees.length; i++) {
- const p = portsForOffset(offsetForIndex(i));
- const branch = trees[i].branch ?? trees[i].head ?? "?";
+ const list = blocks();
+ list.forEach((t, i) => {
+ const p = portsForOffset(t.offset);
+ const branch = t.branch ?? t.head ?? "?";
+ const how = t.source === "main" ? "" : t.source === "recorded" ? "" : ` (${t.source}: not recorded yet)`;
process.stdout.write(
`#${i} ${branch.padEnd(24)} editor:${p.EDITOR_PORT} test:${p.PORT} ` +
- `export:${p.EXPORT_PORT} ${trees[i].path}\n`,
+ `export:${p.EXPORT_PORT} ${t.path}${how}\n`,
);
- }
+ });
return 0;
}
@@ -168,7 +305,11 @@ function cmdRun(args) {
return 1;
}
- const ports = portsForOffset(offsetForIndex(indexForDir()));
+ const block = blockForDir();
+ // A dev server or a suite is about to bind this block: record it, so a
+ // worktree added or removed meanwhile cannot move it.
+ if (block.source === "computed" || block.source === "moved") writeRecord(block.path, block.offset, "run");
+ const ports = portsForOffset(block.offset);
const fileEnv = readEnvFile(path.join(process.cwd(), ".worktree-env"));
const env = { ...process.env };
// Precedence: real environment (CI/manual) > .worktree-env > computed ports.
@@ -220,6 +361,9 @@ function cmdAdd(args) {
const main = mainRoot();
const dir = worktreeDirFor(main, branch);
+ // Every existing worktree keeps the block it has now, whatever this add does
+ // to the order of `git worktree list`.
+ pinAll(undefined, "add");
if (branchExists(branch)) {
git(["worktree", "add", dir, branch], { stdio: "inherit" });
@@ -270,7 +414,11 @@ function cmdAdd(args) {
}
}
- const ports = portsForOffset(offsetForIndex(indexForDir(dir)));
+ // 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));
+ 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`);
process.stderr.write(
` editor:${ports.EDITOR_PORT} test:${ports.PORT} export-dev:${ports.EXPORT_DEV_PORT} ` +
@@ -290,6 +438,8 @@ function cmdRm(args) {
// Sanitized exactly as `add` sanitized it, so `rm <the branch you added>`
// finds the directory `add` actually made.
const dir = worktreeDirFor(main, name);
+ // 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
// refuses a plain remove; --force handles that (and any other local files).
const rmArgs = ["worktree", "remove", ...(force ? ["--force"] : []), dir];
@@ -299,14 +449,224 @@ function cmdRm(args) {
return 0;
}
+// ---- prune ------------------------------------------------------------------
+
+export const DEFAULT_PRUNE_IDLE_MS = 3 * 24 * 3600 * 1000;
+
+/** Every process's working directory (Linux /proc), `{ pid, cwd }`. */
+export function processCwds(procRoot = "/proc") {
+ const out = [];
+ let names = [];
+ try {
+ names = fs.readdirSync(procRoot);
+ } catch {
+ return out;
+ }
+ for (const n of names) {
+ if (!/^\d+$/.test(n) || Number(n) === process.pid) continue;
+ try {
+ out.push({ pid: Number(n), cwd: fs.readlinkSync(path.join(procRoot, n, "cwd")) });
+ } catch {
+ /* gone, or another user's */
+ }
+ }
+ return out;
+}
+
+/**
+ * The newest mtime of a worktree's git state: its admin dir's HEAD, index,
+ * logs/HEAD and gitdir (written when it was made) -- not the directory
+ * itself, whose mtime any `git status` moves with its index.lock.
+ */
+export function touchedMs(wtPath) {
+ const dir = adminDirOf(wtPath);
+ let best = 0;
+ for (const f of dir ? ["HEAD", "index", path.join("logs", "HEAD"), "gitdir"].map((n) => path.join(dir, n)) : [wtPath]) {
+ try {
+ best = Math.max(best, fs.statSync(f).mtimeMs);
+ } catch {
+ /* not there */
+ }
+ }
+ return best;
+}
+
+/**
+ * Bytes a removal frees, near enough: allocated blocks of every file with one
+ * link (a pnpm store's hard links are not freed) and of every directory, never
+ * following a link.
+ */
+export function freeableBytes(dir) {
+ let bytes = 0;
+ const stack = [dir];
+ while (stack.length) {
+ const d = stack.pop();
+ let entries;
+ try {
+ entries = fs.readdirSync(d, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const e of entries) {
+ const p = path.join(d, e.name);
+ let st;
+ try {
+ st = fs.lstatSync(p);
+ } catch {
+ continue;
+ }
+ if (st.isDirectory()) {
+ bytes += st.blocks * 512;
+ stack.push(p);
+ } else if (st.nlink <= 1) bytes += st.blocks * 512;
+ }
+ }
+ return bytes;
+}
+
+/**
+ * WHICH WORKTREES `wt prune` WOULD REMOVE, and why each other one stays.
+ * Reads only. `cwd` is any directory of the repository.
+ * @param {{ cwd?: string, base?: string, idleMs?: number, now?: number, procs?: { pid: number, cwd: string }[], measure?: boolean }} [o]
+ */
+export function planWorktreePrune({ cwd = process.cwd(), base = "main", idleMs = DEFAULT_PRUNE_IDLE_MS, now = Date.now(), procs = processCwds(), measure = true } = {}) {
+ const list = blocks(cwd);
+ if (!gitOk(["rev-parse", "--verify", "--quiet", `refs/heads/${base}`], { cwd })) throw new Error(`no branch ${base}: pass --base <branch>`);
+ const remove = [];
+ const kept = [];
+ list.forEach((t, i) => {
+ const row = { path: t.path, branch: t.branch, offset: t.offset };
+ const keep = (why) => kept.push({ ...row, why });
+ if (i === 0) return keep("the main worktree");
+ if (t.prunable) return keep("its directory is gone: `git worktree prune` clears the entry (not done here)");
+ if (t.locked) return keep("locked (git worktree lock)");
+ if (!t.branch || t.branch === "(detached)") return keep("detached HEAD: no branch to judge");
+ if (t.branch === base) return keep(`it is ${base}`);
+ if (!gitOk(["merge-base", "--is-ancestor", `refs/heads/${t.branch}`, `refs/heads/${base}`], { cwd })) return keep(`${t.branch} is not merged into ${base}`);
+ // Read before `git status`, which may refresh the index (and its mtime).
+ const touched = touchedMs(t.path);
+ let status;
+ try {
+ // --no-optional-locks: a dry run writes nothing, not even a refreshed index.
+ status = git(["--no-optional-locks", "status", "--porcelain=v1", "--untracked-files=normal"], { cwd: t.path });
+ } catch (e) {
+ return keep(`git status failed: ${String(e?.message ?? e).split("\n")[0]}`);
+ }
+ if (status) {
+ const n = status.split("\n").length;
+ return keep(`not clean: ${n} changed or untracked path${n === 1 ? "" : "s"} (${status.split("\n")[0].trim()}${n > 1 ? ", …" : ""})`);
+ }
+ 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(`a process works in it (pid ${inIt.slice(0, 5).map((p) => p.pid).join(", ")}${inIt.length > 5 ? ", …" : ""})`);
+ if (touched && now - touched < idleMs) {
+ const h = (now - touched) / 3600000;
+ return keep(`touched ${h < 48 ? `${Math.round(h)} h` : `${(h / 24).toFixed(1)} d`} ago (idle needs ${(idleMs / 86400000).toFixed(1)} d): a branch just made from ${base} is merged too`);
+ }
+ remove.push({ ...row, index: i });
+ });
+ // A worktree whose own checkout predates recorded blocks still computes its
+ // ports from its index: removing one BEFORE it would move them under a
+ // running suite. Those removals wait until it is updated or gone.
+ const removing = new Set(remove.map((r) => r.index));
+ const oldCode = list.map((t, i) => i > 0 && !removing.has(i) && !t.prunable && !knowsRecords(t.path));
+ const last = oldCode.lastIndexOf(true);
+ const go = [];
+ for (const r of remove) {
+ const { index, ...row } = r;
+ if (index < last) kept.push({ ...row, why: `removing it would move ${list[last].branch ?? list[last].path}'s ports: that checkout's scripts/worktree.mjs predates recorded port blocks (merge main into it, or wait until it is gone)` });
+ else go.push({ ...row, bytes: measure ? freeableBytes(row.path) : null });
+ }
+ return { base, idleMs, remove: go, kept, bytes: go.reduce((s, r) => s + (r.bytes ?? 0), 0) };
+}
+
+/** Whether a checkout's own worktree.mjs reads the recorded blocks (else it computes ports from its index). */
+export function knowsRecords(wtPath) {
+ try {
+ return fs.readFileSync(path.join(wtPath, "scripts", "worktree.mjs"), "utf8").includes(PORT_RECORD);
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * REMOVE THEM: every other worktree's block recorded first (so none moves),
+ * then `git worktree remove <path>` each, never --force, branches kept.
+ */
+export function pruneWorktrees(o = {}) {
+ const cwd = o.cwd ?? process.cwd();
+ const plan = planWorktreePrune(o);
+ const pinned = pinAll(cwd, "prune", { dryRun: !!o.dryRun });
+ const removed = [];
+ const failed = [];
+ if (!o.dryRun) {
+ for (const r of plan.remove) {
+ try {
+ git(["worktree", "remove", r.path], { cwd, stdio: ["ignore", "pipe", "pipe"] });
+ removed.push(r);
+ } catch (e) {
+ failed.push({ ...r, error: String(e?.stderr || e?.message || e).trim().split("\n")[0] });
+ }
+ }
+ }
+ return { ...plan, dryRun: !!o.dryRun, pinned, removed, failed, freedBytes: removed.reduce((s, r) => s + (r.bytes ?? 0), 0) };
+}
+
+const fmtGB = (n) => `${(n / 1e9).toFixed(n >= 1e10 ? 0 : 1)} GB`;
+
+function parseIdle(v) {
+ const m = /^(\d+(?:\.\d+)?)(d|h|m)?$/.exec(String(v ?? ""));
+ if (!m) throw new Error(`--idle: "${v}" is not an age (3d, 12h, 90m)`);
+ return Number(m[1]) * { d: 86400000, h: 3600000, m: 60000 }[m[2] ?? "d"];
+}
+
+function cmdPrune(args) {
+ const dryRun = args.includes("--dry-run");
+ const json = args.includes("--json");
+ const val = (flag) => {
+ const i = args.indexOf(flag);
+ return i === -1 ? undefined : args[i + 1];
+ };
+ const known = new Set(["--dry-run", "--json", "--no-measure", "--base", "--idle"]);
+ for (let i = 0; i < args.length; i++) {
+ if (!known.has(args[i])) {
+ process.stderr.write(`worktree prune: unknown argument '${args[i]}'\n prune [--dry-run] [--json] [--base main] [--idle 3d] [--no-measure]\n`);
+ return 2;
+ }
+ if (args[i] === "--base" || args[i] === "--idle") i++;
+ }
+ let r;
+ try {
+ r = pruneWorktrees({ dryRun, base: val("--base") ?? "main", idleMs: val("--idle") !== undefined ? parseIdle(val("--idle")) : DEFAULT_PRUNE_IDLE_MS, measure: !args.includes("--no-measure") });
+ } catch (e) {
+ process.stderr.write(`worktree prune: ${e?.message ?? e}\n`);
+ return 1;
+ }
+ if (json) {
+ process.stdout.write(JSON.stringify(r, null, 2) + "\n");
+ return r.failed.length ? 1 : 0;
+ }
+ const verb = dryRun ? "would remove" : "removed";
+ for (const x of dryRun ? r.remove : r.removed) process.stdout.write(`${verb} ${x.path} (${x.branch})${x.bytes != null ? `, about ${fmtGB(x.bytes)}` : ""}\n`);
+ for (const f of r.failed) process.stdout.write(`NOT removed ${f.path}: ${f.error}\n`);
+ for (const k of r.kept) process.stdout.write(`kept ${k.path} (${k.branch ?? "?"}): ${k.why}\n`);
+ for (const p of r.pinned) process.stdout.write(`${dryRun ? "would record" : "recorded"} ${p.path}'s port block (offset ${p.offset})\n`);
+ const n = dryRun ? r.remove.length : r.removed.length;
+ process.stdout.write(`${dryRun ? "dry run — " : ""}${n} worktree(s) ${verb}, about ${fmtGB(dryRun ? r.bytes : r.freedBytes)}; ${r.kept.length} kept; branches kept\n`);
+ return r.failed.length ? 1 : 0;
+}
+
function usage() {
process.stderr.write(
`Usage: worktree <command>\n\n` +
` ports [--shell fish|bash|posix] Print this worktree's assigned ports\n` +
- ` run -- <cmd...> Run a command with ports injected into env\n` +
+ ` 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)\n` +
- ` rm <name|path> [--force] Remove a worktree (--force if it has local files)\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` +
+ ` 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`,
);
}
@@ -324,6 +684,8 @@ async function main() {
case "rm":
case "remove":
return cmdRm(rest);
+ case "prune":
+ return cmdPrune(rest);
case undefined:
case "-h":
case "--help":
diff --git a/scripts/worktree.test.mjs b/scripts/worktree.test.mjs
@@ -60,3 +60,155 @@ test("a worktree nested in the main checkout gets its OWN index, not the main on
assert.equal(indexForPath(roots, `${MAIN}-other`), 0);
assert.equal(indexForPath(roots, "/elsewhere"), 0);
});
+
+// ---- recorded port blocks and `wt prune` (2026-11-06) ------------------------
+// The pure resolution, then a real repository in a temp dir with real
+// worktrees: what prune removes and keeps, and that no survivor's block moves.
+
+import { execFileSync, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import {
+ PORT_RECORD,
+ adminDirOf,
+ lowestFreeOffset,
+ parseWorktreeList,
+ planWorktreePrune,
+ pruneWorktrees,
+ readRecord,
+ resolveBlocks,
+ writeRecord,
+} from "./worktree.mjs";
+
+const SCRIPT = path.join(path.dirname(new URL(import.meta.url).pathname), "worktree.mjs");
+
+test("resolveBlocks: unrecorded worktrees keep index * 100; a record wins; a clash moves to the lowest free block", () => {
+ assert.deepEqual(resolveBlocks([null, null, null]).map((b) => [b.offset, b.source]), [[0, "main"], [100, "computed"], [200, "computed"]]);
+ // #1 recorded at 300; #2 has none and keeps 200; #3 would be 300 (taken) -> the lowest free, 100.
+ assert.deepEqual(resolveBlocks([null, 300, null, null]).map((b) => [b.offset, b.source]), [[0, "main"], [300, "recorded"], [200, "computed"], [100, "moved"]]);
+ // Two records naming one block: the first keeps it, the second is resolved as unrecorded.
+ assert.deepEqual(resolveBlocks([null, 200, 200]).map((b) => b.offset), [0, 200, 100]);
+ assert.equal(lowestFreeOffset([0, 100, 200, 400]), 300);
+ assert.equal(lowestFreeOffset([0]), 100);
+});
+
+test("parseWorktreeList reads locked and prunable", () => {
+ const list = parseWorktreeList(
+ ["worktree /r", "HEAD FAKE-TEST-VALUE", "branch refs/heads/main", "", "worktree /w1", "HEAD 1234", "branch refs/heads/x", "locked reason", "", "worktree /w2", "HEAD 5678", "detached", "prunable gitdir file points to non-existent location", ""].join("\n"),
+ );
+ assert.deepEqual(list.map((t) => [t.path, t.branch, t.locked, t.prunable]), [["/r", "main", false, false], ["/w1", "x", true, false], ["/w2", "(detached)", false, true]]);
+});
+
+const gitEnv = { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" };
+const g = (cwd, ...args) => execFileSync("git", args, { cwd, env: gitEnv, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
+const DAY = 86400000;
+const NOW = Date.now();
+
+/** A repo with a worktree.mjs that knows records, and linked worktrees named in order. */
+function repo() {
+ const top = fs.mkdtempSync(path.join(os.tmpdir(), "wt-prune-"));
+ const main = path.join(top, "main");
+ fs.mkdirSync(path.join(main, "scripts"), { recursive: true });
+ g(main, "init", "-q", "-b", "main");
+ fs.writeFileSync(path.join(main, "scripts", "worktree.mjs"), `// reads ${PORT_RECORD}\n`);
+ fs.writeFileSync(path.join(main, ".gitignore"), "node_modules\n");
+ g(main, "add", ".");
+ g(main, "commit", "-q", "-m", "base");
+ const add = (name, { commit = false, oldCode = false } = {}) => {
+ const dir = path.join(top, name);
+ g(main, "worktree", "add", "-q", "-b", name, dir, "main");
+ if (oldCode) fs.writeFileSync(path.join(dir, "scripts", "worktree.mjs"), "// computes from the index\n");
+ if (commit || oldCode) {
+ fs.writeFileSync(path.join(dir, `${name}.txt`), "x\n");
+ g(dir, "add", ".");
+ g(dir, "commit", "-q", "-m", name);
+ }
+ return dir;
+ };
+ /** Age a worktree's git state, as if nobody touched it for `days`. */
+ const age = (dir, days = 10) => {
+ const admin = adminDirOf(dir);
+ const t = new Date(NOW - days * DAY);
+ for (const f of ["HEAD", "index", path.join("logs", "HEAD"), "gitdir"]) {
+ try {
+ fs.utimesSync(path.join(admin, f), t, t);
+ } catch {
+ /* not there */
+ }
+ }
+ };
+ return { top, main, add, age };
+}
+
+test("wt prune removes only the merged, clean, idle worktree nobody works in; branches stay; no survivor's block moves", (t) => {
+ const r = repo();
+ t.after(() => fs.rmSync(r.top, { recursive: true, force: true }));
+ const a = r.add("a-done");
+ const b = r.add("b-dirty");
+ const c = r.add("c-unmerged", { commit: true });
+ const d = r.add("d-busy");
+ const e = r.add("e-fresh");
+ const f = r.add("f-done");
+ fs.mkdirSync(path.join(a, "node_modules"));
+ fs.writeFileSync(path.join(a, "node_modules", "big"), Buffer.alloc(64 * 1024)); // ignored: not "dirty"
+ fs.writeFileSync(path.join(b, "scratch.txt"), "untracked\n");
+ for (const x of [a, b, c, d, f]) r.age(x);
+ const procs = [{ pid: 999999, cwd: path.join(fs.realpathSync(d), "scripts") }];
+
+ const order = parseWorktreeList(g(r.main, "worktree", "list", "--porcelain")).map((x) => path.basename(x.path));
+ assert.deepEqual(order, ["main", "a-done", "b-dirty", "c-unmerged", "d-busy", "e-fresh", "f-done"]);
+
+ const plan = planWorktreePrune({ cwd: r.main, now: NOW, procs });
+ assert.deepEqual(plan.remove.map((x) => path.basename(x.path)), ["a-done", "f-done"]);
+ assert.ok(plan.remove[0].bytes >= 64 * 1024, "the ignored node_modules counts toward what it frees");
+ const why = Object.fromEntries(plan.kept.map((k) => [path.basename(k.path), k.why]));
+ assert.match(why["b-dirty"], /not clean: 1 changed or untracked path/);
+ assert.match(why["c-unmerged"], /not merged into main/);
+ assert.match(why["d-busy"], /a process works in it \(pid 999999\)/);
+ assert.match(why["e-fresh"], /touched 0 h ago/);
+ assert.match(why.main, /the main worktree/);
+
+ // A dry run writes nothing: no record, nothing removed.
+ const dry = pruneWorktrees({ cwd: r.main, now: NOW, procs, dryRun: true });
+ assert.equal(dry.pinned.length, 6);
+ assert.equal(readRecord(e), null);
+ assert.ok(fs.existsSync(a));
+
+ const before = Object.fromEntries([b, c, d, e].map((x) => [path.basename(x), dry.pinned.find((p) => p.path === x)?.offset]));
+ assert.deepEqual(before, { "b-dirty": 200, "c-unmerged": 300, "d-busy": 400, "e-fresh": 500 });
+ const done = pruneWorktrees({ cwd: r.main, now: NOW, procs });
+ assert.deepEqual(done.removed.map((x) => path.basename(x.path)), ["a-done", "f-done"]);
+ assert.equal(done.failed.length, 0);
+ assert.equal(fs.existsSync(a), false);
+ assert.ok(g(r.main, "branch", "--list", "a-done").includes("a-done"), "the branch is kept");
+ // Every survivor kept its block: recorded, and index 1..4 now would have said 100..400.
+ for (const [name, off] of Object.entries(before)) assert.equal(readRecord(path.join(r.top, name)), off, name);
+});
+
+test("wt prune keeps a removal that would move a checkout still computing ports from its index", (t) => {
+ const r = repo();
+ t.after(() => fs.rmSync(r.top, { recursive: true, force: true }));
+ const a = r.add("a-done");
+ const old = r.add("b-old", { oldCode: true });
+ const c = r.add("c-done");
+ for (const x of [a, old, c]) r.age(x);
+ const plan = planWorktreePrune({ cwd: r.main, now: NOW, procs: [] });
+ assert.deepEqual(plan.remove.map((x) => path.basename(x.path)), ["c-done"], "after the old checkout: nothing of its moves");
+ assert.match(plan.kept.find((k) => k.path === a).why, /would move b-old's ports/);
+});
+
+test("wt add records the lowest free block and pins the others first", (t) => {
+ const r = repo();
+ t.after(() => fs.rmSync(r.top, { recursive: true, force: true }));
+ const z = r.add("z-later");
+ assert.equal(writeRecord(z, 300, "test"), 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);
+ // b-new sorts before z-later; z-later keeps 300, b-new gets 100.
+ assert.equal(readRecord(path.join(r.top, "b-new")), 100);
+ assert.equal(readRecord(z), 300);
+ assert.match(res.stderr, /editor:3101/);
+ const list = spawnSync(process.execPath, [SCRIPT, "list"], { cwd: r.main, env: gitEnv, encoding: "utf8" }).stdout;
+ assert.match(list, /b-new\s+editor:3101/);
+ assert.match(list, /z-later\s+editor:3301/);
+});