rungate 0.8.13 → 0.8.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +182 -0
  2. package/gates/.gate-salt +1 -1
  3. package/hooks/HarnessAFKGate.hook.ts +5 -1
  4. package/hooks/HookCurrency.hook.ts +11 -8
  5. package/hooks/MergeGuard.hook.ts +7 -1
  6. package/hooks/StaleTTLCleanup.hook.ts +4 -4
  7. package/hooks/VerifyPhaseLock.hook.ts +3 -3
  8. package/hooks/lib/findWorkflow.ts +3 -2
  9. package/hooks/lib/paths.ts +14 -2
  10. package/hooks/lib/utils.ts +23 -3
  11. package/lib/active-milestone.ts +50 -0
  12. package/lib/ai-review-rounds.ts +99 -0
  13. package/lib/ai-review-suppression.ts +200 -21
  14. package/lib/bash-write-guard.ts +397 -23
  15. package/lib/board-flow.ts +280 -0
  16. package/lib/board-lane-health.ts +578 -0
  17. package/lib/board-mirror.ts +136 -39
  18. package/lib/board-ready-fanout.ts +297 -14
  19. package/lib/board-ready-rule.ts +1211 -0
  20. package/lib/board-throughput.ts +136 -0
  21. package/lib/board-walkthrough.ts +240 -0
  22. package/lib/body-evidence.ts +203 -0
  23. package/lib/branch-protection.ts +399 -9
  24. package/lib/bun-version.ts +36 -0
  25. package/lib/cli-commands.ts +75 -4
  26. package/lib/closing-reference-audit.ts +307 -6
  27. package/lib/config-loader.ts +254 -25
  28. package/lib/config-readers.ts +170 -10
  29. package/lib/config-trackable.ts +96 -57
  30. package/lib/conformity.ts +121 -7
  31. package/lib/create-sc.ts +25 -2
  32. package/lib/derived-spec.ts +21 -9
  33. package/lib/filing-compliance.ts +367 -0
  34. package/lib/filing-plan.ts +47 -21
  35. package/lib/finding-arbiter.ts +79 -5
  36. package/lib/finding-jury.ts +43 -4
  37. package/lib/finding-promotion.ts +1123 -0
  38. package/lib/generators/agents-md.ts +149 -0
  39. package/lib/git-isolation.ts +137 -1
  40. package/lib/github-api-base.ts +66 -0
  41. package/lib/github.ts +194 -9
  42. package/lib/graphql-cursor.ts +80 -0
  43. package/lib/hook-scopes.ts +78 -0
  44. package/lib/issue-create-override.ts +415 -3
  45. package/lib/issue-decomposition.ts +124 -7
  46. package/lib/issue-extraction.ts +9 -7
  47. package/lib/issue-file-overlap.ts +373 -0
  48. package/lib/issue-filing-gate.ts +1109 -52
  49. package/lib/issue-repair.ts +90 -9
  50. package/lib/issue-shape.ts +199 -0
  51. package/lib/live-issues.ts +31 -2
  52. package/lib/local-work.ts +423 -0
  53. package/lib/markdown-fence.ts +134 -0
  54. package/lib/milestone-title.ts +46 -0
  55. package/lib/scaffold/ai-review-findings.ts +148 -3
  56. package/lib/scaffold/ai-review-step.ts +65 -5
  57. package/lib/scaffold/ai-review-unmeasured-workflow.ts +3 -0
  58. package/lib/scaffold/steps.ts +115 -9
  59. package/lib/source-census.ts +108 -0
  60. package/lib/spec-deps.ts +55 -11
  61. package/lib/spec-placement.ts +203 -13
  62. package/lib/spec-registry.ts +75 -16
  63. package/lib/spec-source.ts +609 -0
  64. package/lib/spec-write-sweep.ts +4 -0
  65. package/lib/stage-ladder.ts +896 -3
  66. package/lib/state-claim-readings.ts +252 -0
  67. package/lib/success-doc.ts +7 -6
  68. package/lib/test-command-positions.ts +135 -1
  69. package/lib/work-status.ts +551 -0
  70. package/lib/worktree-repo.ts +14 -2
  71. package/package.json +7 -1
  72. package/scripts/ai-review-findings.ts +8 -13
  73. package/scripts/ai-review-threads.ts +16 -17
  74. package/scripts/audit-closing-references.ts +330 -0
  75. package/scripts/audit-specs.ts +59 -103
  76. package/scripts/board-conformance.ts +747 -40
  77. package/scripts/board-mirror.ts +594 -13
  78. package/scripts/board-ready.ts +979 -0
  79. package/scripts/board-snapshot.ts +464 -12
  80. package/scripts/claim-files.ts +578 -0
  81. package/scripts/criterion-inventory.ts +526 -50
  82. package/scripts/finding-promotion.ts +547 -0
  83. package/scripts/generate-code-map.ts +1 -1
  84. package/scripts/plan-issues.ts +279 -40
  85. package/scripts/plan-spec.ts +105 -3
  86. package/scripts/sync-sc-status.ts +147 -7
  87. package/scripts/worktree-census.ts +958 -0
  88. package/scripts/worktree-sweep.ts +269 -0
@@ -0,0 +1,958 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * What is actually true about each registered worktree (#1021).
4
+ *
5
+ * `git -C . worktree list` prints 170 lines here and marks an abandoned
6
+ * worktree exactly the same as one a session is typing into right now. That
7
+ * is not a cosmetic problem. On 2026-10-16 the stale directories were tidied
8
+ * by hand — an ordinary thing to do, from a list where nothing distinguished
9
+ * them — and two sessions lost uncommitted work, one about 500 lines and one
10
+ * holding PR #452's branch (`.claude/rules/parallel-sessions.md`).
11
+ *
12
+ * So this is a READING, not a reaper. It deletes nothing, removes nothing,
13
+ * unlocks nothing and prunes nothing. It takes four readings per worktree and
14
+ * prints them with the verdict they imply. Removal stays a human decision
15
+ * made with the evidence in front of it.
16
+ *
17
+ * 1. its branch has a MERGED pull request, at the commit the worktree holds
18
+ * 2. `git status --porcelain` was read and was empty
19
+ * 3. no process holds a file under it
20
+ * 4. nothing under it has been modified inside a declared age
21
+ *
22
+ * ## The distinction the whole file exists for
23
+ *
24
+ * A reading that could not be TAKEN is not a reading that came back negative.
25
+ * `0`, `{}`, `null`, an empty string and a command that died are all
26
+ * indistinguishable from "clean" if you only look at the output, and
27
+ * collapsing them is exactly how 2026-10-16 happened: `git status` in a
28
+ * directory that no longer exists prints nothing at all, which reads as a
29
+ * pristine tree.
30
+ *
31
+ * Every reading is therefore `Measured<T>` — a value, or the reason there is
32
+ * no value — and a worktree with any unmeasured reading is **UNMEASURED**,
33
+ * counted apart from ABANDONED and never folded into it. `verdictFor` is the
34
+ * only place a verdict is decided, so that property is provable in one place
35
+ * rather than argued about in four.
36
+ *
37
+ * ## Why the merge reading asks the pull request and not git
38
+ *
39
+ * Because ancestry does not work here. A squash merge destroys it:
40
+ * `git merge-base --is-ancestor` reports ORPHANED for all six of the commits
41
+ * #511 and #512 recovered, whose content is fully on main
42
+ * (`scripts/verify-merge-content.ts` carries the measurement). An ancestry
43
+ * guard fires on the NORMAL case — every squash merge this repo makes — and
44
+ * a worktree holding real unmerged work would be reported abandoned. There is
45
+ * no ancestry question anywhere in this file, and a test asserts that.
46
+ *
47
+ * The pull request is asked instead, and it is asked for an IDENTITY, not an
48
+ * implication: the branch counts as merged only when the worktree's `HEAD` is
49
+ * the exact `headRefOid` GitHub merged. A branch that gained commits after
50
+ * its PR merged reads `MERGED_BUT_MOVED` and is not abandoned-ward, because
51
+ * those commits are on no other ref and are precisely the work that gets lost.
52
+ *
53
+ * ## What this must never do, and how it is kept from doing it
54
+ *
55
+ * - **No deletion.** There is no `rm`, no `worktree remove`, no `worktree
56
+ * prune` and no `--force` anywhere, asserted by the test.
57
+ * - **No acting on the process reading.** It answers "who holds this"; it
58
+ * never signals anybody. `pkill` is not in this file and must not be.
59
+ * - **No writes into the worktrees it reads.** Status is taken with
60
+ * `git --no-optional-locks`, which is what keeps a refresh of the index out
61
+ * of a directory another session is working in.
62
+ *
63
+ * Usage:
64
+ * bun scripts/worktree-census.ts [--repo <dir>] [--older-than 7d]
65
+ * [--json] [--out <file>] [--no-gh]
66
+ * [--gh-repo <owner/name>] [--max-entries <n>]
67
+ *
68
+ * stdout: the table, or the JSON verdict with `--json`.
69
+ * stderr: diagnostics and refusals.
70
+ * exit: 0 when the census was produced, however many rows are UNMEASURED —
71
+ * an unmeasured row is a finding, not a failure. REFUSE_EXIT when the
72
+ * census could not be produced at all.
73
+ */
74
+
75
+ import { execFileSync } from "child_process";
76
+ import { lstatSync, readdirSync, realpathSync, writeFileSync } from "fs";
77
+ import { join } from "path";
78
+ import { gitIsolatedArgs, gitIsolatedEnv } from "../lib/git-isolation";
79
+
80
+ /**
81
+ * The ONE place this script runs `git` (#1048).
82
+ *
83
+ * ## Why a seam and not the flags at each call site
84
+ *
85
+ * `git -C <dir>` runs the configuration of whatever repository it is pointed
86
+ * at, and this tool's whole purpose is to point it at directories nobody is
87
+ * currently thinking about — 175 of them on the machine this was written on
88
+ * (`git worktree list --porcelain | grep -c '^worktree '`, 2026-10-22 01:30;
89
+ * the number moves every time a session starts or finishes). So the question
90
+ * is not whether these two call sites are isolated today. It is whether the
91
+ * THIRD one will be, and a call site is the unit that gets forgotten.
92
+ *
93
+ * `lib/git-isolation.ts` is the single declaring position for WHAT isolation
94
+ * is. This function is the single declaring position for WHERE this module
95
+ * applies it. Adding the `-c` flags inline at both sites would have been the
96
+ * cheaper change and is the thing #1001 exists to prevent: two spellings that
97
+ * drift, with nothing comparing them.
98
+ *
99
+ * ## What was measured, because "read-only subcommand" is not a safety class
100
+ *
101
+ * git 2.50.1, a scratch repo whose own `.git/config` carries the poison —
102
+ * the scope `GIT_CONFIG_GLOBAL=/dev/null` cannot reach:
103
+ *
104
+ * | subcommand | poisoned key | unisolated | isolated |
105
+ * |---|---|---|---|
106
+ * | `--no-optional-locks status --porcelain` | `core.fsmonitor` | **ran it** | not run |
107
+ * | `--no-optional-locks status --porcelain` | `core.excludesFile` | **plant INVISIBLE** | `?? plant.txt` |
108
+ * | `--no-optional-locks status --porcelain` | `core.hooksPath` | not fired | not fired |
109
+ * | `status --porcelain` (no lock flag) | `core.hooksPath` | **hook fired** | not fired |
110
+ * | `worktree list --porcelain` | all three | nothing fired | nothing fired |
111
+ *
112
+ * Three things follow, and only the first is the security argument:
113
+ *
114
+ * 1. `--no-optional-locks` does NOT stop `core.fsmonitor`. It stops the
115
+ * index WRITE, so `post-index-change` does not fire — which means the
116
+ * hook exposure here was closed by a flag chosen for an unrelated
117
+ * reason, and would reopen the day somebody drops it.
118
+ * 2. **`core.excludesFile` falsifies the reading itself.** An untracked
119
+ * file goes invisible, so a worktree holding work reports CLEAN — in
120
+ * the tool whose output decides what is safe to remove. That is a
121
+ * correctness defect, not a parity argument, and it is the one that
122
+ * would bite on this machine first.
123
+ * 3. `worktree list` executed nothing under any of the three. It is
124
+ * genuinely `rev-parse`-class, and no behavioural case can witness its
125
+ * isolation — see `test/worktree-census.test.ts`, which says so rather
126
+ * than shipping a fixture that would pass either way.
127
+ *
128
+ * Isolation changes no output on this machine: no global, system or local
129
+ * config here sets any key in `GIT_ISOLATION_CONFIG` (measured 2026-10-22).
130
+ */
131
+ function censusGit(args: readonly string[], maxBuffer?: number): string {
132
+ return execFileSync("git", gitIsolatedArgs(args), {
133
+ encoding: "utf-8",
134
+ stdio: ["pipe", "pipe", "pipe"],
135
+ env: gitIsolatedEnv(),
136
+ ...(maxBuffer === undefined ? {} : { maxBuffer }),
137
+ });
138
+ }
139
+
140
+ /**
141
+ * The one exit code every refusal travels through, declared exactly once.
142
+ *
143
+ * `test/worktree-census.test.ts` builds a mutant copy with this set to 0 and
144
+ * runs every negative case twice — real refuses, mutant does not. A refusal
145
+ * exiting with a hard-coded number instead of this constant would slip past
146
+ * that mutation, so there are none; the success path exits by returning.
147
+ */
148
+ export const REFUSE_EXIT = 1;
149
+
150
+ export class CensusRefused extends Error {
151
+ constructor(message: string) {
152
+ super(message);
153
+ this.name = "CensusRefused";
154
+ }
155
+ }
156
+
157
+ /* ------------------------------------------------------------------ *
158
+ * Measured<T>: a value, or the reason there is no value
159
+ * ------------------------------------------------------------------ */
160
+
161
+ export type Measured<T> = { measured: true; value: T } | { measured: false; why: string };
162
+
163
+ export const took = <T>(value: T): Measured<T> => ({ measured: true, value });
164
+ export const couldNotRead = <T>(why: string): Measured<T> => ({ measured: false, why });
165
+
166
+ /* ------------------------------------------------------------------ *
167
+ * The worktree list
168
+ * ------------------------------------------------------------------ */
169
+
170
+ export interface WorktreeRecord {
171
+ /** Absolute, as git reports it. */
172
+ path: string;
173
+ head: string | null;
174
+ /** Short branch name, or null when detached. */
175
+ branch: string | null;
176
+ detached: boolean;
177
+ locked: boolean;
178
+ lockReason: string;
179
+ /** git itself says the directory is gone. */
180
+ prunable: boolean;
181
+ prunableReason: string;
182
+ /** The first entry: the checkout everything else is linked to. */
183
+ isMain: boolean;
184
+ }
185
+
186
+ /**
187
+ * Parse `git worktree list --porcelain`.
188
+ *
189
+ * Records are blank-line separated and the first is always the main checkout.
190
+ * `locked` and `prunable` may appear bare or with a reason, and a bare
191
+ * `locked` is still locked — reading the reason as the fact would turn an
192
+ * explicit do-not-touch marker into nothing.
193
+ */
194
+ export function parseWorktreeList(porcelain: string): WorktreeRecord[] {
195
+ const out: WorktreeRecord[] = [];
196
+ let cur: WorktreeRecord | null = null;
197
+ for (const raw of porcelain.split("\n")) {
198
+ const line = raw.replace(/\r$/, "");
199
+ if (line === "") continue;
200
+ const sp = line.indexOf(" ");
201
+ const key = sp === -1 ? line : line.slice(0, sp);
202
+ const rest = sp === -1 ? "" : line.slice(sp + 1);
203
+ if (key === "worktree") {
204
+ cur = {
205
+ path: rest,
206
+ head: null,
207
+ branch: null,
208
+ detached: false,
209
+ locked: false,
210
+ lockReason: "",
211
+ prunable: false,
212
+ prunableReason: "",
213
+ isMain: out.length === 0,
214
+ };
215
+ out.push(cur);
216
+ continue;
217
+ }
218
+ if (!cur) continue;
219
+ if (key === "HEAD") cur.head = rest;
220
+ else if (key === "branch") cur.branch = rest.replace(/^refs\/heads\//, "");
221
+ else if (key === "detached") cur.detached = true;
222
+ else if (key === "locked") {
223
+ cur.locked = true;
224
+ cur.lockReason = rest;
225
+ } else if (key === "prunable") {
226
+ cur.prunable = true;
227
+ cur.prunableReason = rest;
228
+ }
229
+ }
230
+ return out;
231
+ }
232
+
233
+ /* ------------------------------------------------------------------ *
234
+ * Reading 1 — does the branch have a merged pull request?
235
+ * ------------------------------------------------------------------ */
236
+
237
+ export type MergeState =
238
+ /** A merged PR, at exactly the commit this worktree holds. */
239
+ | "MERGED"
240
+ /** A merged PR, but the branch has moved since: those commits are on no other ref. */
241
+ | "MERGED_BUT_MOVED"
242
+ | "OPEN"
243
+ | "CLOSED"
244
+ | "NO_PR"
245
+ /** No branch to ask about. */
246
+ | "DETACHED";
247
+
248
+ export interface PullRequest {
249
+ number: number;
250
+ headRefName: string;
251
+ headRefOid: string;
252
+ state: string;
253
+ }
254
+
255
+ export interface BranchPulls {
256
+ merged: PullRequest | null;
257
+ open: PullRequest | null;
258
+ closed: PullRequest | null;
259
+ }
260
+
261
+ /**
262
+ * Index pull requests by head branch.
263
+ *
264
+ * A branch can carry several over its life, so all three states are kept
265
+ * rather than last-one-wins: a branch with a merged PR *and* a later open one
266
+ * is a branch somebody is still using, and a reader that kept only the merged
267
+ * row would call it abandoned.
268
+ */
269
+ export function indexPullRequests(prs: PullRequest[]): Map<string, BranchPulls> {
270
+ const byBranch = new Map<string, BranchPulls>();
271
+ for (const pr of prs) {
272
+ if (!pr || typeof pr.headRefName !== "string") continue;
273
+ let slot = byBranch.get(pr.headRefName);
274
+ if (!slot) {
275
+ slot = { merged: null, open: null, closed: null };
276
+ byBranch.set(pr.headRefName, slot);
277
+ }
278
+ if (pr.state === "MERGED") slot.merged = pr;
279
+ else if (pr.state === "OPEN") slot.open = pr;
280
+ else slot.closed = pr;
281
+ }
282
+ return byBranch;
283
+ }
284
+
285
+ /**
286
+ * The merge reading for one worktree.
287
+ *
288
+ * `index` being null means the pull request list could not be fetched, which
289
+ * is UNMEASURED for every row — not "no PR found".
290
+ */
291
+ export function mergeReading(
292
+ record: WorktreeRecord,
293
+ index: Map<string, BranchPulls> | null,
294
+ indexWhy: string,
295
+ ): Measured<{ state: MergeState; pr: number | null }> {
296
+ if (record.branch === null) return took({ state: "DETACHED" as MergeState, pr: null });
297
+ if (index === null) return couldNotRead(`pull requests not read: ${indexWhy}`);
298
+ const slot = index.get(record.branch);
299
+ if (!slot) return took({ state: "NO_PR" as MergeState, pr: null });
300
+ if (slot.open) return took({ state: "OPEN" as MergeState, pr: slot.open.number });
301
+ if (slot.merged) {
302
+ // Identity, never ancestry. A squash merge leaves the branch head on no
303
+ // ref main can reach, so "is it an ancestor" is the wrong question; "is
304
+ // it the commit GitHub merged" is a fact with one answer.
305
+ if (record.head && slot.merged.headRefOid && record.head !== slot.merged.headRefOid) {
306
+ return took({ state: "MERGED_BUT_MOVED" as MergeState, pr: slot.merged.number });
307
+ }
308
+ if (!record.head || !slot.merged.headRefOid) {
309
+ return couldNotRead(
310
+ `PR #${slot.merged.number} is merged but the head commit could not be compared`,
311
+ );
312
+ }
313
+ return took({ state: "MERGED" as MergeState, pr: slot.merged.number });
314
+ }
315
+ return took({ state: "CLOSED" as MergeState, pr: slot.closed ? slot.closed.number : null });
316
+ }
317
+
318
+ /* ------------------------------------------------------------------ *
319
+ * Reading 2 — is the working tree clean?
320
+ * ------------------------------------------------------------------ */
321
+
322
+ /**
323
+ * `git status --porcelain`, read or refused.
324
+ *
325
+ * **The trap this exists to avoid.** An empty `git status` in a worktree
326
+ * whose directory is gone is not an empty `git status` — the command fails
327
+ * and prints nothing, and nothing is what clean looks like. So the exit
328
+ * status decides, never the emptiness of stdout.
329
+ *
330
+ * `--no-optional-locks` because this reads worktrees other sessions are
331
+ * using: without it, status refreshes and rewrites the index, which is a
332
+ * write into somebody else's run from a tool whose whole claim is that it
333
+ * only reads. It buys nothing against `core.fsmonitor`, which `status` runs
334
+ * either way — that is `censusGit`'s job, and the measurement is there.
335
+ */
336
+ export function cleanReading(dir: string): Measured<{ clean: boolean; entries: number }> {
337
+ let out: string;
338
+ try {
339
+ out = censusGit(["--no-optional-locks", "-C", dir, "status", "--porcelain"]);
340
+ } catch (e) {
341
+ const msg = String((e as Error).message || "").split("\n").slice(0, 2).join(" ").trim();
342
+ return couldNotRead(`git status failed: ${msg}`);
343
+ }
344
+ const lines = out.split("\n").filter(l => l.trim() !== "");
345
+ return took({ clean: lines.length === 0, entries: lines.length });
346
+ }
347
+
348
+ /* ------------------------------------------------------------------ *
349
+ * Reading 3 — does any process hold a file under it?
350
+ * ------------------------------------------------------------------ */
351
+
352
+ export interface Holder {
353
+ pid: string;
354
+ command: string;
355
+ path: string;
356
+ }
357
+
358
+ /**
359
+ * Parse `lsof -F pcn` and attribute every open path to the deepest root that
360
+ * contains it.
361
+ *
362
+ * Output is a stream of records: a `p<pid>` line opens a process, `c<cmd>`
363
+ * names it, and each following `n<path>` is one of its open files — cwd and
364
+ * the executable included, which is what makes a shell sitting in a worktree
365
+ * visible at all.
366
+ *
367
+ * Matching walks the path upward against a set rather than testing every
368
+ * root against every path: with 170 roots and 50k open files the quadratic
369
+ * form is the difference between a tool people run and one they do not.
370
+ */
371
+ export function holdersByRoot(lsofOutput: string, roots: string[]): Map<string, Holder[]> {
372
+ const rootSet = new Set(roots);
373
+ const found = new Map<string, Holder[]>();
374
+ let pid = "";
375
+ let command = "";
376
+ for (const line of lsofOutput.split("\n")) {
377
+ if (line === "") continue;
378
+ const tag = line[0];
379
+ const body = line.slice(1);
380
+ if (tag === "p") {
381
+ pid = body;
382
+ command = "";
383
+ } else if (tag === "c") {
384
+ command = body;
385
+ } else if (tag === "n") {
386
+ if (!body.startsWith("/")) continue;
387
+ let probe = body;
388
+ while (probe.length > 1) {
389
+ if (rootSet.has(probe)) {
390
+ const list = found.get(probe);
391
+ if (list) list.push({ pid, command, path: body });
392
+ else found.set(probe, [{ pid, command, path: body }]);
393
+ break;
394
+ }
395
+ const cut = probe.lastIndexOf("/");
396
+ if (cut <= 0) break;
397
+ probe = probe.slice(0, cut);
398
+ }
399
+ }
400
+ }
401
+ return found;
402
+ }
403
+
404
+ /**
405
+ * Run lsof once for the whole machine.
406
+ *
407
+ * Once, not per worktree: `lsof +D <dir>` descends the tree and 170 of those
408
+ * is minutes of work, where one full enumeration is a fraction of a second.
409
+ *
410
+ * A failure here is UNMEASURED for every row at once, which is the honest
411
+ * reading — "lsof is not installed" and "nothing holds any of them" are the
412
+ * same empty output and must not be the same answer.
413
+ */
414
+ export function readLsof(): Measured<string> {
415
+ try {
416
+ const out = execFileSync("lsof", ["-w", "-n", "-P", "-F", "pcn"], {
417
+ encoding: "utf-8",
418
+ stdio: ["pipe", "pipe", "pipe"],
419
+ maxBuffer: 256 * 1024 * 1024,
420
+ });
421
+ if (out.trim() === "") {
422
+ return couldNotRead("lsof produced no output at all, which no running system does");
423
+ }
424
+ return took(out);
425
+ } catch (e) {
426
+ // lsof exits non-zero when some file systems could not be stat'd even
427
+ // though it listed plenty. Partial output is still a real reading of the
428
+ // processes it did see; empty output is not.
429
+ const err = e as { stdout?: string | Buffer; message?: string };
430
+ const partial = err.stdout ? String(err.stdout) : "";
431
+ if (partial.trim() !== "") return took(partial);
432
+ const msg = String(err.message || "").split("\n")[0];
433
+ return couldNotRead(`lsof failed: ${msg}`);
434
+ }
435
+ }
436
+
437
+ /* ------------------------------------------------------------------ *
438
+ * Reading 4 — how recently was anything under it modified?
439
+ * ------------------------------------------------------------------ */
440
+
441
+ export interface AgeValue {
442
+ newestMtimeMs: number;
443
+ scanned: number;
444
+ stale: boolean;
445
+ }
446
+
447
+ /**
448
+ * The newest mtime anywhere under the worktree, or the reason there isn't one.
449
+ *
450
+ * **A partial walk is refused, not reported.** Every way this walk can come
451
+ * up short — an unreadable subdirectory, a tree past `maxEntries` — makes the
452
+ * answer a LOWER bound on recency, and a lower bound can only ever make a
453
+ * live worktree look old. That is the one direction that costs work, so a
454
+ * walk that did not finish returns no value.
455
+ *
456
+ * `.git` is skipped because this script runs `git status` in every worktree
457
+ * and that touches the git directory: including it would mean measuring our
458
+ * own footprints. `node_modules` is skipped because in these worktrees it is
459
+ * a symlink to the main checkout, shared by all of them, and its mtime says
460
+ * nothing about any one. Symlinks are stat'd, never followed.
461
+ *
462
+ * A worktree nested inside another — `.claude/worktrees/*` under the main
463
+ * checkout — is walked as part of its container, which makes the container
464
+ * look as fresh as its freshest child. That is left alone deliberately: it
465
+ * errs toward IN_USE, and the only direction worth engineering against is
466
+ * the one that makes a live worktree look abandoned.
467
+ */
468
+ export function ageReading(
469
+ root: string,
470
+ nowMs: number,
471
+ olderThanMs: number,
472
+ maxEntries: number,
473
+ ): Measured<AgeValue> {
474
+ const SKIP = new Set([".git", "node_modules"]);
475
+ let newest = 0;
476
+ let scanned = 0;
477
+ const stack: string[] = [root];
478
+ try {
479
+ newest = lstatSync(root).mtimeMs;
480
+ } catch (e) {
481
+ return couldNotRead(`cannot stat the worktree directory: ${String((e as Error).message).split("\n")[0]}`);
482
+ }
483
+ while (stack.length > 0) {
484
+ const dir = stack.pop() as string;
485
+ let entries;
486
+ try {
487
+ entries = readdirSync(dir, { withFileTypes: true });
488
+ } catch (e) {
489
+ return couldNotRead(
490
+ `walk stopped at ${dir}: ${String((e as Error).message).split("\n")[0]} — ` +
491
+ `a partial walk can only under-report recency`,
492
+ );
493
+ }
494
+ for (const ent of entries) {
495
+ if (SKIP.has(ent.name)) continue;
496
+ scanned += 1;
497
+ if (scanned > maxEntries) {
498
+ return couldNotRead(
499
+ `more than ${maxEntries} entries under this worktree — ` +
500
+ `a truncated walk can only under-report recency`,
501
+ );
502
+ }
503
+ const abs = join(dir, ent.name);
504
+ let st;
505
+ try {
506
+ st = lstatSync(abs);
507
+ } catch {
508
+ // A file that vanished between readdir and lstat is something
509
+ // changing right now, which is the opposite of stale.
510
+ return couldNotRead(`${abs} disappeared mid-walk`);
511
+ }
512
+ if (st.mtimeMs > newest) newest = st.mtimeMs;
513
+ if (ent.isDirectory() && !ent.isSymbolicLink()) stack.push(abs);
514
+ }
515
+ }
516
+ return took({ newestMtimeMs: newest, scanned, stale: nowMs - newest >= olderThanMs });
517
+ }
518
+
519
+ /* ------------------------------------------------------------------ *
520
+ * The verdict — one decider, and only one
521
+ * ------------------------------------------------------------------ */
522
+
523
+ export interface Readings {
524
+ merge: Measured<{ state: MergeState; pr: number | null }>;
525
+ clean: Measured<{ clean: boolean; entries: number }>;
526
+ holders: Measured<Holder[]>;
527
+ age: Measured<AgeValue>;
528
+ }
529
+
530
+ export type Verdict = "ABANDONED" | "IN_USE" | "UNMEASURED";
531
+
532
+ /**
533
+ * Which readings could not be taken, by name.
534
+ *
535
+ * One binding, used by both the verdict and the report. Two copies would be
536
+ * two deciders that agree, which no test can tell apart.
537
+ */
538
+ export function unmeasuredReadings(r: Readings): string[] {
539
+ const out: string[] = [];
540
+ if (!r.merge.measured) out.push("merge");
541
+ if (!r.clean.measured) out.push("clean");
542
+ if (!r.holders.measured) out.push("holders");
543
+ if (!r.age.measured) out.push("age");
544
+ return out;
545
+ }
546
+
547
+ /**
548
+ * Rows that are IN_USE before any reading is consulted, and why.
549
+ *
550
+ * The main checkout is never a candidate for removal, and a lock is somebody
551
+ * having already said so in writing. One binding rather than two, because
552
+ * both the verdict and the evidence column ask this and a second copy would
553
+ * be a decider no mutation of the first can reach.
554
+ *
555
+ * It is also the reason the summary can carry an unmeasured READING with no
556
+ * unmeasured VERDICT: a locked worktree whose directory is unreadable is
557
+ * still IN_USE, and the counts would otherwise look like they disagree.
558
+ */
559
+ export function decidedWithoutReadings(record: WorktreeRecord): string | null {
560
+ if (record.isMain) return "main checkout";
561
+ if (record.locked) return `locked${record.lockReason ? `: ${record.lockReason}` : ""}`;
562
+ return null;
563
+ }
564
+
565
+ /**
566
+ * The only place a verdict is decided.
567
+ *
568
+ * ABANDONED requires all four readings to have been TAKEN and all four to
569
+ * point the same way. Anything unmeasured is UNMEASURED, never ABANDONED,
570
+ * and that is the property the whole file is for — `git status` in a deleted
571
+ * directory prints exactly what a pristine tree prints.
572
+ */
573
+ export function verdictFor(record: WorktreeRecord, r: Readings): Verdict {
574
+ if (decidedWithoutReadings(record) !== null) return "IN_USE";
575
+ if (unmeasuredReadings(r).length > 0) return "UNMEASURED";
576
+ // One narrowing cast of the whole object rather than four checks the
577
+ // compiler would accept: a second `if (!r.merge.measured) ...` here would
578
+ // be a second decider for a question `unmeasuredReadings` already answers,
579
+ // and two deciders that agree are one that no test can mutate.
580
+ const t = r as {
581
+ merge: { value: { state: MergeState } };
582
+ clean: { value: { clean: boolean } };
583
+ holders: { value: Holder[] };
584
+ age: { value: AgeValue };
585
+ };
586
+ const abandonedWard =
587
+ t.merge.value.state === "MERGED" &&
588
+ t.clean.value.clean === true &&
589
+ t.holders.value.length === 0 &&
590
+ t.age.value.stale === true;
591
+ return abandonedWard ? "ABANDONED" : "IN_USE";
592
+ }
593
+
594
+ /**
595
+ * Why a row is not ABANDONED, in the words of the readings themselves.
596
+ *
597
+ * An UNMEASURED row reports what it could not read AND what it did read, so
598
+ * a reader can see that a worktree whose PR lookup failed is also one a
599
+ * process is holding. A verdict is a summary; the evidence is the output.
600
+ */
601
+ export function evidenceFor(record: WorktreeRecord, r: Readings): string[] {
602
+ const why: string[] = [];
603
+ const settled = decidedWithoutReadings(record);
604
+ if (settled !== null) why.push(settled);
605
+ if (record.prunable) why.push(`git calls it prunable: ${record.prunableReason || "no reason given"}`);
606
+ if (!r.merge.measured) why.push(`merge UNMEASURED (${r.merge.why})`);
607
+ else if (r.merge.value.state !== "MERGED") why.push(`merge: ${r.merge.value.state}`);
608
+ if (!r.clean.measured) why.push(`clean UNMEASURED (${r.clean.why})`);
609
+ else if (!r.clean.value.clean) why.push(`${r.clean.value.entries} uncommitted change(s)`);
610
+ if (!r.holders.measured) why.push(`holders UNMEASURED (${r.holders.why})`);
611
+ else if (r.holders.value.length > 0) {
612
+ const names = [...new Set(r.holders.value.map(h => `${h.command}[${h.pid}]`))].slice(0, 4);
613
+ why.push(`held by ${names.join(", ")}`);
614
+ }
615
+ if (!r.age.measured) why.push(`age UNMEASURED (${r.age.why})`);
616
+ else if (!r.age.value.stale) why.push("modified inside the declared age");
617
+ return why;
618
+ }
619
+
620
+ /* ------------------------------------------------------------------ *
621
+ * Census
622
+ * ------------------------------------------------------------------ */
623
+
624
+ export interface CensusRow {
625
+ path: string;
626
+ branch: string | null;
627
+ head: string | null;
628
+ verdict: Verdict;
629
+ readings: {
630
+ merge: Measured<{ state: MergeState; pr: number | null }>;
631
+ clean: Measured<{ clean: boolean; entries: number }>;
632
+ holders: Measured<{ count: number; by: string[] }>;
633
+ age: Measured<{ newestMtimeMs: number; ageMs: number; stale: boolean }>;
634
+ };
635
+ unmeasured: string[];
636
+ evidence: string[];
637
+ }
638
+
639
+ export interface CensusResult {
640
+ repo: string;
641
+ takenAt: string;
642
+ olderThanMs: number;
643
+ /** Present always, so "nobody warned me" and "there was nothing to warn about" differ. */
644
+ warnings: string[];
645
+ counts: {
646
+ total: number;
647
+ abandoned: number;
648
+ inUse: number;
649
+ unmeasured: number;
650
+ /**
651
+ * Rows with an unmeasured reading that are IN_USE anyway because the main
652
+ * checkout and a locked worktree are settled before readings are
653
+ * consulted. Reported so `unmeasuredByReading` summing above
654
+ * `counts.unmeasured` is an explained difference rather than a puzzle.
655
+ */
656
+ unmeasuredButSettled: number;
657
+ };
658
+ /** How many rows each reading could not be taken for. */
659
+ unmeasuredByReading: Record<string, number>;
660
+ rows: CensusRow[];
661
+ }
662
+
663
+ /**
664
+ * `git worktree prune` is a hazard here and the census is where to say so.
665
+ *
666
+ * prune drops `.git/worktrees/<name>` for ANY registered worktree whose
667
+ * directory is already gone — not only the one the person running it was
668
+ * thinking about. It deletes no branch and no commit, so the blast radius is
669
+ * bookkeeping, but a session whose directory was removed out from under it
670
+ * loses the registration that makes `git worktree repair` possible.
671
+ */
672
+ export function pruneWarnings(records: WorktreeRecord[]): string[] {
673
+ const gone = records.filter(r => r.prunable);
674
+ if (gone.length === 0) return [];
675
+ return [
676
+ `${gone.length} registered worktree(s) have no directory on disk. ` +
677
+ `\`git worktree prune\` would drop the bookkeeping for ALL of them, not just yours: ` +
678
+ gone.map(r => r.path).join(", "),
679
+ ];
680
+ }
681
+
682
+ export interface CensusOptions {
683
+ repo: string;
684
+ olderThanMs: number;
685
+ maxEntries: number;
686
+ nowMs: number;
687
+ pulls: Measured<PullRequest[]>;
688
+ lsof: Measured<string>;
689
+ }
690
+
691
+ /** Resolve a path through symlinks, or keep it: /tmp is /private/tmp here. */
692
+ function canonical(p: string): string {
693
+ try {
694
+ return realpathSync(p);
695
+ } catch {
696
+ return p;
697
+ }
698
+ }
699
+
700
+ export function census(records: WorktreeRecord[], opts: CensusOptions): CensusResult {
701
+ const index = opts.pulls.measured ? indexPullRequests(opts.pulls.value) : null;
702
+ const indexWhy = opts.pulls.measured ? "" : opts.pulls.why;
703
+
704
+ const canonicalOf = new Map<string, string>();
705
+ for (const r of records) canonicalOf.set(r.path, canonical(r.path));
706
+ const held = opts.lsof.measured
707
+ ? holdersByRoot(opts.lsof.value, [...new Set(canonicalOf.values())])
708
+ : new Map<string, Holder[]>();
709
+
710
+ const rows: CensusRow[] = [];
711
+ const counts = {
712
+ total: records.length,
713
+ abandoned: 0,
714
+ inUse: 0,
715
+ unmeasured: 0,
716
+ unmeasuredButSettled: 0,
717
+ };
718
+ const unmeasuredByReading: Record<string, number> = { merge: 0, clean: 0, holders: 0, age: 0 };
719
+
720
+ for (const record of records) {
721
+ const dir = canonicalOf.get(record.path) as string;
722
+ const merge = mergeReading(record, index, indexWhy);
723
+ const clean = cleanReading(record.path);
724
+ const holders: Measured<Holder[]> = opts.lsof.measured
725
+ ? took(held.get(dir) ?? [])
726
+ : couldNotRead(opts.lsof.why);
727
+ const age = ageReading(record.path, opts.nowMs, opts.olderThanMs, opts.maxEntries);
728
+ const readings: Readings = { merge, clean, holders, age };
729
+
730
+ const verdict = verdictFor(record, readings);
731
+ const unmeasured = unmeasuredReadings(readings);
732
+ for (const name of unmeasured) unmeasuredByReading[name] += 1;
733
+ if (unmeasured.length > 0 && verdict !== "UNMEASURED") counts.unmeasuredButSettled += 1;
734
+ if (verdict === "ABANDONED") counts.abandoned += 1;
735
+ else if (verdict === "UNMEASURED") counts.unmeasured += 1;
736
+ else counts.inUse += 1;
737
+
738
+ rows.push({
739
+ path: record.path,
740
+ branch: record.branch,
741
+ head: record.head,
742
+ verdict,
743
+ readings: {
744
+ merge,
745
+ clean,
746
+ holders: holders.measured
747
+ ? took({
748
+ count: holders.value.length,
749
+ by: [...new Set(holders.value.map(h => `${h.command}[${h.pid}]`))],
750
+ })
751
+ : couldNotRead(holders.why),
752
+ age: age.measured
753
+ ? took({
754
+ newestMtimeMs: age.value.newestMtimeMs,
755
+ ageMs: opts.nowMs - age.value.newestMtimeMs,
756
+ stale: age.value.stale,
757
+ })
758
+ : couldNotRead(age.why),
759
+ },
760
+ unmeasured,
761
+ evidence: evidenceFor(record, readings),
762
+ });
763
+ }
764
+
765
+ return {
766
+ repo: opts.repo,
767
+ takenAt: new Date(opts.nowMs).toISOString(),
768
+ olderThanMs: opts.olderThanMs,
769
+ warnings: pruneWarnings(records),
770
+ counts,
771
+ unmeasuredByReading,
772
+ rows,
773
+ };
774
+ }
775
+
776
+ /* ------------------------------------------------------------------ *
777
+ * Rendering
778
+ * ------------------------------------------------------------------ */
779
+
780
+ export function humanAge(ms: number): string {
781
+ if (!Number.isFinite(ms) || ms < 0) return "?";
782
+ const m = Math.floor(ms / 60000);
783
+ if (m < 60) return `${m}m`;
784
+ const h = Math.floor(m / 60);
785
+ if (h < 48) return `${h}h`;
786
+ return `${Math.floor(h / 24)}d`;
787
+ }
788
+
789
+ export function renderTable(result: CensusResult): string {
790
+ const header = ["VERDICT", "MERGE", "TREE", "HELD", "AGE", "WORKTREE", "EVIDENCE"];
791
+ const body = result.rows.map(row => [
792
+ row.verdict,
793
+ row.readings.merge.measured ? row.readings.merge.value.state : "UNMEASURED",
794
+ row.readings.clean.measured ? (row.readings.clean.value.clean ? "clean" : "dirty") : "UNMEASURED",
795
+ row.readings.holders.measured ? String(row.readings.holders.value.count) : "UNMEASURED",
796
+ row.readings.age.measured ? humanAge(row.readings.age.value.ageMs) : "UNMEASURED",
797
+ row.path,
798
+ row.evidence.join("; "),
799
+ ]);
800
+ const widths = header.map((h, i) =>
801
+ Math.max(h.length, ...body.map(r => r[i].length).concat(0)),
802
+ );
803
+ // The last column is free-form, so it is not padded.
804
+ const line = (cells: string[]) =>
805
+ cells.map((c, i) => (i === cells.length - 1 ? c : c.padEnd(widths[i]))).join(" ").trimEnd();
806
+
807
+ const lines = [line(header), ...body.map(line), ""];
808
+ for (const w of result.warnings) lines.push(`WARNING: ${w}`);
809
+ if (result.warnings.length === 0) lines.push("WARNING: none — every registered worktree has a directory on disk.");
810
+ lines.push("");
811
+ lines.push(
812
+ `${result.counts.total} worktrees: ${result.counts.abandoned} ABANDONED, ` +
813
+ `${result.counts.inUse} IN_USE, ${result.counts.unmeasured} UNMEASURED ` +
814
+ `(declared age ${humanAge(result.olderThanMs)}, taken ${result.takenAt})`,
815
+ );
816
+ lines.push(
817
+ "unmeasured readings: " +
818
+ Object.entries(result.unmeasuredByReading)
819
+ .map(([k, v]) => `${k}=${v}`)
820
+ .join(" ") +
821
+ ` (${result.counts.unmeasuredButSettled} of them on rows settled as IN_USE ` +
822
+ `before readings — the main checkout and locked worktrees)`,
823
+ );
824
+ lines.push("This tool removes nothing. UNMEASURED is not ABANDONED; neither is a licence to delete.");
825
+ return lines.join("\n");
826
+ }
827
+
828
+ /* ------------------------------------------------------------------ *
829
+ * CLI
830
+ * ------------------------------------------------------------------ */
831
+
832
+ export interface Args {
833
+ repo: string;
834
+ olderThanMs: number;
835
+ maxEntries: number;
836
+ json: boolean;
837
+ out: string | null;
838
+ gh: boolean;
839
+ ghRepo: string | null;
840
+ }
841
+
842
+ const DURATION = /^([0-9]+)(m|h|d)$/;
843
+
844
+ export function parseDuration(text: string): number {
845
+ const m = DURATION.exec(text);
846
+ if (!m) {
847
+ throw new CensusRefused(
848
+ `--older-than ${text} is not a duration — use <n>m, <n>h or <n>d, e.g. 7d`,
849
+ );
850
+ }
851
+ const n = Number(m[1]);
852
+ const unit = { m: 60000, h: 3600000, d: 86400000 }[m[2] as "m" | "h" | "d"];
853
+ return n * unit;
854
+ }
855
+
856
+ export function parseArgs(argv: string[]): Args {
857
+ const args: Args = {
858
+ repo: process.cwd(),
859
+ olderThanMs: parseDuration("7d"),
860
+ maxEntries: 20000,
861
+ json: false,
862
+ out: null,
863
+ gh: true,
864
+ ghRepo: null,
865
+ };
866
+ const need = (i: number, flag: string): string => {
867
+ if (i + 1 >= argv.length) throw new CensusRefused(`${flag} needs a value`);
868
+ return argv[i + 1];
869
+ };
870
+ for (let i = 0; i < argv.length; i++) {
871
+ const a = argv[i];
872
+ if (a === "--repo") args.repo = need(i++, a);
873
+ else if (a === "--older-than") args.olderThanMs = parseDuration(need(i++, a));
874
+ else if (a === "--max-entries") {
875
+ const v = Number(need(i++, a));
876
+ if (!Number.isInteger(v) || v < 1) throw new CensusRefused(`--max-entries needs a positive integer`);
877
+ args.maxEntries = v;
878
+ } else if (a === "--json") args.json = true;
879
+ else if (a === "--out") args.out = need(i++, a);
880
+ else if (a === "--no-gh") args.gh = false;
881
+ else if (a === "--gh-repo") args.ghRepo = need(i++, a);
882
+ else throw new CensusRefused(`unknown argument: ${a}`);
883
+ }
884
+ return args;
885
+ }
886
+
887
+ /** `git worktree list --porcelain`, or a refusal naming why it could not run. */
888
+ export function readWorktreeList(repo: string): string {
889
+ try {
890
+ return censusGit(["-C", repo, "worktree", "list", "--porcelain"], 64 * 1024 * 1024);
891
+ } catch (e) {
892
+ const msg = String((e as Error).message || "").split("\n").slice(0, 2).join(" ").trim();
893
+ throw new CensusRefused(`cannot list worktrees in ${repo}: ${msg}`);
894
+ }
895
+ }
896
+
897
+ /**
898
+ * Every pull request, in one call.
899
+ *
900
+ * One call and not 170: `gh pr list --head <branch>` per worktree is 170
901
+ * round trips against a rate limit, and a tool that gets throttled half way
902
+ * reports the second half as unmeasured for a reason that is about itself.
903
+ */
904
+ export function readPullRequests(repoFlag: string | null): Measured<PullRequest[]> {
905
+ const argv = ["pr", "list", "--state", "all", "--limit", "2000", "--json",
906
+ "number,headRefName,headRefOid,state"];
907
+ if (repoFlag) argv.push("--repo", repoFlag);
908
+ try {
909
+ const out = execFileSync("gh", argv, {
910
+ encoding: "utf-8",
911
+ stdio: ["pipe", "pipe", "pipe"],
912
+ maxBuffer: 64 * 1024 * 1024,
913
+ });
914
+ const parsed = JSON.parse(out);
915
+ if (!Array.isArray(parsed)) return couldNotRead("gh did not return a list of pull requests");
916
+ return took(parsed as PullRequest[]);
917
+ } catch (e) {
918
+ const msg = String((e as Error).message || "").split("\n")[0];
919
+ return couldNotRead(`gh pr list failed: ${msg}`);
920
+ }
921
+ }
922
+
923
+ export function main(argv: string[]): number {
924
+ const args = parseArgs(argv);
925
+ const records = parseWorktreeList(readWorktreeList(args.repo));
926
+ const result = census(records, {
927
+ repo: args.repo,
928
+ olderThanMs: args.olderThanMs,
929
+ maxEntries: args.maxEntries,
930
+ nowMs: Date.now(),
931
+ pulls: args.gh
932
+ ? readPullRequests(args.ghRepo)
933
+ : couldNotRead<PullRequest[]>("--no-gh was passed, so no pull request was consulted"),
934
+ lsof: readLsof(),
935
+ });
936
+ const rendered = args.json ? JSON.stringify(result, null, 2) : renderTable(result);
937
+ if (args.out) {
938
+ try {
939
+ writeFileSync(args.out, JSON.stringify(result, null, 2));
940
+ } catch (e) {
941
+ throw new CensusRefused(`cannot write ${args.out}: ${String((e as Error).message).split("\n")[0]}`);
942
+ }
943
+ }
944
+ process.stdout.write(rendered + "\n");
945
+ return result.counts.total;
946
+ }
947
+
948
+ if (import.meta.main) {
949
+ try {
950
+ main(process.argv.slice(2));
951
+ } catch (e) {
952
+ if (e instanceof CensusRefused) {
953
+ process.stderr.write(`worktree-census: ${e.message}\n`);
954
+ process.exit(REFUSE_EXIT);
955
+ }
956
+ throw e;
957
+ }
958
+ }