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,578 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Ask whether a file has a live writer, and declare that you are one (#1413).
4
+ *
5
+ * ```
6
+ * bun scripts/claim-files.ts --check lib/scaffold/ai-review-step.ts
7
+ * bun scripts/claim-files.ts --claim lib/scaffold/ai-review-step.ts --owner rg/my-branch --issue 1405
8
+ * bun scripts/claim-files.ts --release --owner rg/my-branch
9
+ * bun scripts/claim-files.ts --list
10
+ * ```
11
+ *
12
+ * **Exit 0 from `--check` means nobody live holds those paths.** Any other
13
+ * exit means do not branch yet, and the reason is on stdout. A refusal is
14
+ * never a silence: an unreadable registry exits non-zero saying so, because a
15
+ * registry that fails to parse reporting "free" is the one fail-open this
16
+ * mechanism must not have.
17
+ *
18
+ * `--check` reads `origin/<default>`'s copy, not the working tree's, because
19
+ * a claim only exists for other sessions once it is pushed. It fetches first
20
+ * unless `--no-fetch` is passed, so the answer is about now rather than about
21
+ * whenever this worktree last synced. `lib/file-claims.ts` holds the whole
22
+ * decision; this file holds none of it, and is the part a library cannot be —
23
+ * a place to ask the question from a shell, before any code exists to import
24
+ * anything from.
25
+ *
26
+ * Liveness is resolved rather than trusted from the registry: an owner is
27
+ * live while its branch has an open pull request, or while the branch is on
28
+ * the remote with no pull request yet. A claim whose pull request merged or
29
+ * closed is reported DEAD and holds nothing, so an entry nobody pruned costs
30
+ * a line of output rather than a file nobody may ever work on again.
31
+ *
32
+ * ## Every lookup in this file, and what it does when it cannot resolve
33
+ *
34
+ * The AI review on PR #1436 said this three times before I listened: five
35
+ * separate instances of ONE class were found across seven rounds — a git or
36
+ * `gh` lookup that could not be resolved defaulting to the safe-looking
37
+ * answer — and each was fixed as a patch to the site that was caught, rather
38
+ * than by auditing the file for the shape. The audit, done once:
39
+ *
40
+ * | lookup | cannot resolve | round found |
41
+ * |-------------------------------|---------------------|-------------|
42
+ * | `defaultBranch` origin/HEAD | REFUSE, names the fix | 7 (low) |
43
+ * | `repoSlug` from origin | null -> UNMEASURED | push review |
44
+ * | `refreshRefs` fetch | `fetched: false`, an input | 2 (critical) |
45
+ * | `rev-parse origin/<owner>` | UNMEASURED unless fetched | 2 (critical) |
46
+ * | `pullsForBranch` via gh | null -> UNMEASURED | — |
47
+ * | `readFromRemote` ref resolve | UNMEASURED | 5 (high) |
48
+ * | `readFromRemote` path read | absent only on a resolved ref | 5 (high) |
49
+ * | `readLocal` | ENOENT absent, else throws | — |
50
+ * | `writeStore` round trip | refuses to write | 1 (medium) |
51
+ *
52
+ * Nothing in this file may answer "free" from a reading it did not take.
53
+ * `test/file-claims.test.ts` holds that list as an executed census, so a
54
+ * tenth lookup added later has to join it or redden the suite — which is the
55
+ * difference between closing a class and patching its instances.
56
+ *
57
+ * That answer comes from the tracker and not from the commit graph, which
58
+ * squash-merging has already destroyed the evidence in. Two git-only rules
59
+ * were tried and both reported merged branches live forever; the second was
60
+ * measured wrong on 11 of 12 recently merged branches. `lib/file-claims.ts`
61
+ * carries the measurement. The practical consequence here is that `--check`
62
+ * and `--list` need `gh` to be working: if it is not, the owners it covers
63
+ * are UNMEASURED and the tool refuses rather than reporting free.
64
+ */
65
+
66
+ import { spawnSync } from "child_process";
67
+ import { readFileSync, writeFileSync } from "fs";
68
+ import { join } from "path";
69
+
70
+ import {
71
+ FILE_CLAIMS_CONTROL_KEY,
72
+ FILE_CLAIMS_PATH,
73
+ allClaims,
74
+ contention,
75
+ ownerState,
76
+ readFileClaims,
77
+ type FileClaim,
78
+ type PullState,
79
+ } from "../lib/file-claims.ts";
80
+ import { normaliseRepoPath } from "../lib/repo-path.ts";
81
+
82
+ /** The one exit code every refusal travels through. */
83
+ export const REFUSE_EXIT = 1;
84
+
85
+ const FLAGS = new Set([
86
+ "check",
87
+ "claim",
88
+ "release",
89
+ "list",
90
+ "owner",
91
+ "issue",
92
+ "note",
93
+ "project",
94
+ "no-fetch",
95
+ // The ref the registry is read from. Defaults to the remote's default
96
+ // branch, which is the only answer that is true for every other session.
97
+ // Overridable because a registry on a branch that has not merged yet
98
+ // cannot otherwise be exercised at all — including by this repository's
99
+ // own tests, which is how the HELD path gets a witness before it ships.
100
+ "ref",
101
+ ]);
102
+
103
+ export interface Args {
104
+ check: string[];
105
+ claim: string[];
106
+ release: boolean;
107
+ list: boolean;
108
+ owner?: string;
109
+ issue?: number;
110
+ note?: string;
111
+ project: string;
112
+ fetch: boolean;
113
+ /** Ref the registry is read from; empty means the remote default branch. */
114
+ ref?: string;
115
+ }
116
+
117
+ export function parseArgs(argv: string[]): Args {
118
+ const out: Args = { check: [], claim: [], release: false, list: false, project: ".", fetch: true };
119
+ for (let i = 0; i < argv.length; i++) {
120
+ const m = /^--([a-z][a-z-]*)$/.exec(argv[i]);
121
+ if (!m || !FLAGS.has(m[1])) throw new Error(`unexpected argument "${String(argv[i]).slice(0, 80)}"`);
122
+ const flag = m[1];
123
+ if (flag === "release") { out.release = true; continue; }
124
+ if (flag === "list") { out.list = true; continue; }
125
+ if (flag === "no-fetch") { out.fetch = false; continue; }
126
+ // A repeated `--check a --check b` and a run of values after one flag are
127
+ // the same claim; both are accepted because a caller assembling paths in
128
+ // a shell loop naturally produces the first and a person types the second.
129
+ const values: string[] = [];
130
+ while (i + 1 < argv.length && !argv[i + 1].startsWith("--")) values.push(argv[++i]);
131
+ if (values.length === 0) throw new Error(`--${flag} needs a value`);
132
+ if (flag === "check" || flag === "claim") out[flag].push(...values);
133
+ else if (flag === "issue") {
134
+ const n = Number(values[0]);
135
+ if (!Number.isSafeInteger(n)) throw new Error(`--issue must be an integer, got "${values[0]}"`);
136
+ out.issue = n;
137
+ } else if (flag === "owner") out.owner = values[0];
138
+ else if (flag === "note") out.note = values.join(" ");
139
+ else if (flag === "project") out.project = values[0];
140
+ else if (flag === "ref") out.ref = values[0];
141
+ }
142
+ return out;
143
+ }
144
+
145
+ function git(project: string, ...args: string[]): { ok: boolean; out: string } {
146
+ const r = spawnSync("git", ["-C", project, ...args], { encoding: "utf-8" });
147
+ return { ok: r.status === 0, out: (r.stdout ?? "").trim() };
148
+ }
149
+
150
+ /**
151
+ * The remote's default branch, or `null` when it is not recorded here.
152
+ *
153
+ * It used to claim to be "read rather than assumed to be `main`" and then
154
+ * return `"main"` whenever `origin/HEAD` was not set — the fifth instance in
155
+ * this file of one unresolvable lookup defaulting to the safe-looking
156
+ * answer, and the AI review was right to keep saying so. `origin/HEAD` is
157
+ * not set by a plain `git clone --mirror`, nor in many CI checkouts, so this
158
+ * is not a rare path; on a project whose default branch is not `main` it
159
+ * reads the registry from a branch that may not exist, or worse, one that
160
+ * does and is stale.
161
+ *
162
+ * `null` here, and the caller refuses and says which command fixes it.
163
+ */
164
+ function defaultBranch(project: string): string | null {
165
+ const r = git(project, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD");
166
+ return r.ok && r.out !== "" ? r.out.replace("refs/remotes/origin/", "") : null;
167
+ }
168
+
169
+ /**
170
+ * The `owner/repo` this project pushes to, parsed from `origin`.
171
+ *
172
+ * Read rather than configured, and `null` rather than a guess: every owner
173
+ * is UNMEASURED if this cannot be resolved, because a `gh` call against the
174
+ * wrong repository would answer "no pull request" with total confidence.
175
+ *
176
+ * ## The host is compared, not pattern-matched
177
+ *
178
+ * Raised by a push review on this pull request. The first version was
179
+ * `/github\.com[:/]+([^/]+)\/(.+?)(?:\.git)?\/?$/` — unanchored, so
180
+ * `github.com` ANYWHERE in the URL satisfied it:
181
+ *
182
+ * https://gitlab.com/github.com/org/repo.git -> "org/repo" WRONG
183
+ * https://mygithub.com/org/repo.git -> "org/repo" WRONG
184
+ *
185
+ * That matters more here than it would elsewhere. This slug is the key a
186
+ * file claim is recorded and released under, so two different remotes
187
+ * resolving to one slug is two projects sharing one lock namespace — and a
188
+ * lock released on a key its holder never took is the exact fail-open the
189
+ * mechanism exists to prevent.
190
+ *
191
+ * Two arms, one per syntax, because `new URL()` is the right instrument for
192
+ * a URL and does not accept `git@github.com:owner/repo.git` at all. One
193
+ * regex covering both is how the first one ended up unanchored. Parsing the
194
+ * URL form also answers `https://github.com@evil.com/…` and
195
+ * `https://github.com./…` structurally rather than by adding patterns.
196
+ */
197
+ export function repoSlug(originUrl: string): string | null {
198
+ const raw = originUrl.trim();
199
+ if (raw === "") return null;
200
+
201
+ const onGitHub = (host: string, path: string): string | null => {
202
+ if (host.toLowerCase() !== "github.com") return null;
203
+ const m = /^\/?([^/]+)\/(.+?)(?:\.git)?\/?$/.exec(path);
204
+ return m === null ? null : `${m[1]}/${m[2]}`;
205
+ };
206
+
207
+ // scp-like: `git@github.com:owner/repo.git`. The lookahead keeps
208
+ // `https://…` out of this arm — there the colon is followed by a slash.
209
+ const scp = /^(?:[^@/]+@)?([^:/]+):(?!\/)(.+)$/.exec(raw);
210
+ if (scp !== null) return onGitHub(scp[1], scp[2]);
211
+
212
+ try {
213
+ const url = new URL(raw);
214
+ return onGitHub(url.hostname, url.pathname);
215
+ } catch {
216
+ return null;
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Pull requests whose head is `branch`, or `null` if the tracker was not read.
222
+ *
223
+ * `--state all` because a CLOSED pull request answers the question as well as
224
+ * a merged one: either way nobody is writing under that name. The `null`
225
+ * return is the whole reason this is not typed `PullState[]` — an empty array
226
+ * means "the tracker says there are none", and those must not be one value.
227
+ */
228
+ function pullsForBranch(slug: string, branch: string): PullState[] | null {
229
+ const r = spawnSync(
230
+ "gh",
231
+ ["pr", "list", "--repo", slug, "--head", branch, "--state", "all", "--json", "number,state"],
232
+ { encoding: "utf-8" },
233
+ );
234
+ if (r.status !== 0) return null;
235
+ try {
236
+ const parsed = JSON.parse(r.stdout) as unknown;
237
+ if (!Array.isArray(parsed)) return null;
238
+ return parsed as PullState[];
239
+ } catch {
240
+ return null;
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Which of `owners` are still being worked on.
246
+ *
247
+ * Asked per declared owner rather than by listing every branch or every open
248
+ * pull request, because the registry has a handful of entries and the remote
249
+ * has hundreds — and because a bounded `--limit` listing would answer "no
250
+ * pull request" for anything older than the page, which is the fail-open
251
+ * direction. A `--head` query is exact and unbounded.
252
+ *
253
+ * {@link ownerState} holds the decision and the evidence for it, including
254
+ * the two git-only rules that were tried first and the measurement that
255
+ * killed the second. Nothing here decides anything; it gathers three inputs
256
+ * per owner and hands them over.
257
+ *
258
+ * ## `fetched` is load-bearing, and the first version of this was a fail-open
259
+ *
260
+ * Raised as CRITICAL by the AI review on this pull request. `origin/<owner>`
261
+ * is a local remote-tracking ref, and the earlier code fetched only the
262
+ * default branch — so a peer's branch this worktree had never fetched failed
263
+ * `rev-parse` and fell through to "ref gone: holds nothing". A fresh worktree
264
+ * has fetched almost nothing, which is exactly the state an agent is in when
265
+ * it asks this question, so the common case silently reported FREE on a file
266
+ * somebody was writing. That is the whole defect this tool exists to prevent,
267
+ * arriving inside the tool.
268
+ *
269
+ * The ref reading still matters even with the tracker in play: it is what
270
+ * separates "pushed, no pull request yet" from "nothing there at all", and
271
+ * those are opposite answers.
272
+ */
273
+ function ownerLiveness(
274
+ project: string,
275
+ owners: readonly string[],
276
+ fetched: boolean,
277
+ ): { live: Set<string>; unmeasured: Map<string, string> } {
278
+ const live = new Set<string>();
279
+ const unmeasured = new Map<string, string>();
280
+ if (owners.length === 0) return { live, unmeasured };
281
+
282
+ const origin = git(project, "remote", "get-url", "origin");
283
+ const slug = origin.ok ? repoSlug(origin.out) : null;
284
+ if (slug === null) {
285
+ for (const o of owners) {
286
+ unmeasured.set(o, "could not resolve the GitHub repository from origin, so no pull request state was read");
287
+ }
288
+ return { live, unmeasured };
289
+ }
290
+
291
+ for (const owner of owners) {
292
+ const refExists = git(project, "rev-parse", "--verify", "--quiet", `origin/${owner}`).ok;
293
+ const { state, why } = ownerState(pullsForBranch(slug, owner), refExists, fetched);
294
+ if (state === "live") live.add(owner);
295
+ else if (state === "unmeasured") unmeasured.set(owner, why);
296
+ }
297
+ return { live, unmeasured };
298
+ }
299
+
300
+ /** {@link defaultBranch}, or a refusal that names the command which fixes it. */
301
+ function requireDefaultBranch(project: string): string {
302
+ const branch = defaultBranch(project);
303
+ if (branch === null) {
304
+ throw new Error(
305
+ "origin/HEAD is not set in this tree, so the remote's default branch is UNMEASURED. " +
306
+ "Not assuming `main`: reading the registry from a branch that is not the default is how " +
307
+ "a claim goes unseen, and this project's default branch is not this script's to guess. " +
308
+ "Run `git remote set-head origin -a`, or pass `--ref <ref>` explicitly.",
309
+ );
310
+ }
311
+ return branch;
312
+ }
313
+
314
+ /**
315
+ * Refresh every remote-tracking ref, and say whether it worked.
316
+ *
317
+ * All branches, not just the base: {@link ownerLiveness} resolves each
318
+ * declared owner through `origin/<owner>`, and a ref this worktree has never
319
+ * seen is indistinguishable from one that was deleted. `--prune` so a branch
320
+ * that really went away stops reading live.
321
+ */
322
+ function refreshRefs(project: string): boolean {
323
+ return git(project, "fetch", "--quiet", "--prune", "origin").ok;
324
+ }
325
+
326
+ /**
327
+ * The registry as `ref` carries it. `ref` is a full name, e.g. `origin/main`.
328
+ *
329
+ * Takes no fetch argument: {@link refreshRefs} runs once for the whole
330
+ * invocation, before this, because the liveness answers need every owner's
331
+ * ref and not only the base's. A second fetch here would be a second place
332
+ * that decides how current the reading is.
333
+ */
334
+ export function readFromRemote(project: string, ref: string) {
335
+ // ## The ref is resolved on its OWN, before anything is read from it
336
+ //
337
+ // Raised as HIGH by the AI review on this pull request, the fourth finding
338
+ // on it and the fourth in the fail-open direction. The classification below
339
+ // used to treat `unknown revision` and `invalid object name` as "the path
340
+ // is not on that ref" — but those two mean the REF did not resolve, which
341
+ // is a different fact entirely. Measured:
342
+ //
343
+ // $ claim-files --check lib/file-claims.ts --ref origin/no-such-ref
344
+ // free: there is no registry at specs/file-claims.json … yet
345
+ // exit=0
346
+ //
347
+ // A typo in `--ref`, or an `origin/main` this worktree has never fetched,
348
+ // reported every path free. "Nobody has declared anything" and "I could
349
+ // not find the place declarations live" are opposite answers and one of
350
+ // them must refuse.
351
+ //
352
+ // Asking `rev-parse` separately also takes the question off git's message
353
+ // wording. What remains to classify is only about the PATH, which is the
354
+ // one thing a successful ref resolution leaves open.
355
+ const resolved = spawnSync(
356
+ "git",
357
+ ["-C", project, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`],
358
+ { encoding: "utf-8" },
359
+ );
360
+ if (resolved.status !== 0) {
361
+ return {
362
+ status: "unreadable" as const,
363
+ path: FILE_CLAIMS_PATH,
364
+ claims: [],
365
+ reason:
366
+ `the ref ${ref} does not resolve in this tree, so the registry was never read. ` +
367
+ "This is not an absent registry: a ref nobody fetched and a ref that does not exist " +
368
+ "both land here, and neither one means nobody has declared anything.",
369
+ };
370
+ }
371
+
372
+ const r = spawnSync("git", ["-C", project, "show", `${ref}:${FILE_CLAIMS_PATH}`], {
373
+ encoding: "utf-8",
374
+ });
375
+ // The ref resolved, so a failure now is about the path. A path that does
376
+ // not exist on that ref and a `git show` that could not run are still
377
+ // different facts: the first is an absent registry, the second is a
378
+ // reading nobody took. Only the first may read as "nobody has declared".
379
+ if (r.status !== 0) {
380
+ const why = (r.stderr ?? "").trim().split("\n")[0];
381
+ if (/does not exist|exists on disk, but not in/i.test(why)) {
382
+ return readFileClaims(null);
383
+ }
384
+ return { status: "unreadable" as const, path: FILE_CLAIMS_PATH, claims: [], reason: `git show failed: ${why}` };
385
+ }
386
+ return readFileClaims(r.stdout);
387
+ }
388
+
389
+ /**
390
+ * Serialise the store, and refuse to write one the reader would reject.
391
+ *
392
+ * Raised by the AI review on this pull request and it was right. Without
393
+ * this, `--claim /etc/passwd` writes an absolute path that `readFileClaims`
394
+ * refuses — and because one bad entry refuses the WHOLE store, a single
395
+ * careless claim makes every path read UNMEASURED for every other session.
396
+ * The writer could brick the registry for everyone, which is a worse version
397
+ * of exactly the fail-open this file exists to prevent.
398
+ *
399
+ * The check is a ROUND TRIP rather than a second call to the validator: it
400
+ * serialises the bytes that are about to be written and reads them back
401
+ * through the real reader. A re-validation would be a second implementation
402
+ * of the rules and would agree with the first by construction — the fourth
403
+ * shape in `.claude/rules/checks-must-be-able-to-fail.md`. This agrees with
404
+ * nothing; it asks the only question that matters, which is whether the next
405
+ * reader can read the file.
406
+ */
407
+ function writeStore(project: string, claims: FileClaim[]): void {
408
+ const path = join(project, FILE_CLAIMS_PATH);
409
+ const bytes = `${JSON.stringify({ [FILE_CLAIMS_CONTROL_KEY]: claims }, null, 2)}\n`;
410
+ const back = readFileClaims(bytes, path);
411
+ if (back.status !== "read") {
412
+ throw new Error(
413
+ `refusing to write a registry the reader cannot read — ${back.reason ?? back.status}. ` +
414
+ "Nothing was written; one bad entry would make every path UNMEASURED for every session.",
415
+ );
416
+ }
417
+ writeFileSync(path, bytes);
418
+ }
419
+
420
+ function readLocal(project: string) {
421
+ const path = join(project, FILE_CLAIMS_PATH);
422
+ let raw: string | null;
423
+ try {
424
+ raw = readFileSync(path, "utf-8");
425
+ } catch (e) {
426
+ if ((e as NodeJS.ErrnoException).code === "ENOENT") raw = null;
427
+ else throw e;
428
+ }
429
+ return readFileClaims(raw, path);
430
+ }
431
+
432
+ if (import.meta.main) {
433
+ let exit = 0;
434
+ try {
435
+ const args = parseArgs(process.argv.slice(2));
436
+ // Lazy, because `--claim` and `--release` write the LOCAL file and never
437
+ // read a ref. Resolving eagerly made the default-branch refusal fire on
438
+ // the two modes that do not need it — a refusal in the wrong place is
439
+ // still a tool nobody can use.
440
+ const baseRef = () => args.ref ?? `origin/${requireDefaultBranch(args.project)}`;
441
+ // One refresh for the whole run, and whether it worked is an input to
442
+ // every liveness answer below. See `ownerLiveness`.
443
+ const fetched = args.fetch ? refreshRefs(args.project) : false;
444
+
445
+ if (args.check.length > 0) {
446
+ // THE THIRD AXIS (#1458). Two refusals below guard an unreadable
447
+ // registry and an unresolvable owner; this guards the caller's own
448
+ // path, and without it an unreadable one did not merely fail to match
449
+ // — it went around the owner refusal as well, because `allClaims` is
450
+ // `claimCovers` too. No claims found, empty `blind`, empty
451
+ // `contention`, `free:`, exit 0. A lock that answers "free" because it
452
+ // could not read the question is the one direction this must never be
453
+ // wrong in.
454
+ //
455
+ // Reachable by the intended use rather than by a hostile caller:
456
+ // `core.quotePath` defaults to true, so `git diff --name-only` emits
457
+ // `"lib/\303\251.ts"` for any non-ASCII filename, and piping a
458
+ // changed-file list in here is what `--check` is for. Spaces and globs
459
+ // take the same route, and the bare non-ASCII spelling is unreadable
460
+ // too because `normaliseRepoPath`'s character class is ASCII.
461
+ //
462
+ // Decided HERE and not in `underPrefix`. That function documents
463
+ // itself as never inventing an answer and leaves the meaning of
464
+ // unreadable to its caller; widening its return type would push this
465
+ // decision onto `risk-tier.ts` and `ai-review-findings.ts`, which
466
+ // already resolve it correctly in their own direction.
467
+ const unreadable = args.check.filter(p => normaliseRepoPath(p) === null);
468
+ if (unreadable.length > 0) {
469
+ console.log(
470
+ `UNMEASURED: ${unreadable.length} of ${args.check.length} path(s) could not be read as repository-relative paths.`,
471
+ );
472
+ for (const p of unreadable) console.log(` ${p}`);
473
+ console.log(
474
+ "Not reporting these free: a path this tool cannot parse is not a path nobody holds.",
475
+ );
476
+ console.log(
477
+ "If these came from `git diff --name-only`, re-run it with `-c core.quotePath=false`.",
478
+ );
479
+ process.exit(REFUSE_EXIT);
480
+ }
481
+ const base = baseRef();
482
+ const reading = readFromRemote(args.project, base);
483
+ if (reading.status === "unreadable") {
484
+ console.log(`UNMEASURED: the claim registry on ${base} could not be read — ${reading.reason}`);
485
+ console.log("Not reporting these paths free: an unreadable registry is not an empty one.");
486
+ process.exit(REFUSE_EXIT);
487
+ }
488
+ const { live, unmeasured } = ownerLiveness(args.project, reading.claims.map(c => c.owner), fetched);
489
+ // An owner whose liveness could not be established must not fall through
490
+ // to "dead". Only the claims on the paths being asked about matter — an
491
+ // unreadable branch elsewhere in the registry is not this caller's
492
+ // problem, and refusing on it would make the tool unusable.
493
+ const blind = args.check
494
+ .flatMap(p => allClaims(reading.claims, p))
495
+ .filter(c => unmeasured.has(c.owner));
496
+ if (blind.length > 0) {
497
+ console.log(`UNMEASURED: ${blind.length} claim(s) on these paths have an owner this tree cannot resolve.`);
498
+ for (const c of blind) console.log(` ${c.owner} — ${unmeasured.get(c.owner)}`);
499
+ console.log("Not reporting free: an owner that could not be read is not an owner that let go.");
500
+ process.exit(REFUSE_EXIT);
501
+ }
502
+ const hits = contention(reading.claims, args.check, live);
503
+ if (hits.size === 0) {
504
+ // Say what was read, so "free" is distinguishable from "read nothing".
505
+ const dead = args.check.flatMap(p => allClaims(reading.claims, p));
506
+ // Say which of the two "free"s this is. A registry that is not there
507
+ // and a registry that says nobody holds these paths are both safe to
508
+ // branch on, and they are not the same reading — the first means the
509
+ // mechanism has not reached this ref yet.
510
+ console.log(
511
+ reading.status === "absent"
512
+ ? `free: there is no registry at ${FILE_CLAIMS_PATH} on ${base} yet, so nothing is declared`
513
+ : `free: no live writer among ${reading.claims.length} claim(s) on ${base}` +
514
+ (dead.length > 0 ? ` (${dead.length} DEAD claim(s) here, owner branch merged or gone)` : ""),
515
+ );
516
+ for (const c of dead) console.log(` DEAD ${c.owner}${c.issue ? ` (#${c.issue})` : ""}`);
517
+ } else {
518
+ console.log(`HELD: ${hits.size} of ${args.check.length} path(s) have a live writer.`);
519
+ for (const [p, cs] of hits) {
520
+ for (const c of cs) {
521
+ console.log(` ${p} <- ${c.owner}${c.issue ? ` (#${c.issue})` : ""}${c.note ? ` — ${c.note}` : ""}`);
522
+ }
523
+ }
524
+ console.log("Branch on something else, or message that owner. Do not start here.");
525
+ exit = REFUSE_EXIT;
526
+ }
527
+ } else if (args.claim.length > 0) {
528
+ if (!args.owner) throw new Error("--claim needs --owner <branch>");
529
+ const reading = readLocal(args.project);
530
+ if (reading.status === "unreadable") throw new Error(`the local registry is unreadable: ${reading.reason}`);
531
+ const kept = reading.claims.filter(c => c.owner !== args.owner);
532
+ const entry: FileClaim = { owner: args.owner, paths: args.claim };
533
+ if (args.issue !== undefined) entry.issue = args.issue;
534
+ if (args.note !== undefined) entry.note = args.note;
535
+ writeStore(args.project, [...kept, entry]);
536
+ console.log(`claimed ${args.claim.length} path(s) for ${args.owner}.`);
537
+ console.log(`Commit and PUSH ${FILE_CLAIMS_PATH} now — an unpushed claim is invisible, which is the whole defect.`);
538
+ } else if (args.release) {
539
+ if (!args.owner) throw new Error("--release needs --owner <branch>");
540
+ const reading = readLocal(args.project);
541
+ if (reading.status === "unreadable") throw new Error(`the local registry is unreadable: ${reading.reason}`);
542
+ const kept = reading.claims.filter(c => c.owner !== args.owner);
543
+ writeStore(args.project, kept);
544
+ console.log(`released ${reading.claims.length - kept.length} claim(s) for ${args.owner}.`);
545
+ } else if (args.list) {
546
+ const base = baseRef();
547
+ const reading = readFromRemote(args.project, base);
548
+ if (reading.status === "unreadable") {
549
+ console.log(`UNMEASURED: ${reading.reason}`);
550
+ process.exit(REFUSE_EXIT);
551
+ }
552
+ const { live, unmeasured } = ownerLiveness(args.project, reading.claims.map(c => c.owner), fetched);
553
+ // ABSENT and READ-EMPTY print differently on purpose. "Nobody has
554
+ // declared anything" and "there is no registry on this ref yet" lead to
555
+ // different next actions, and one line for both is how a reader stops
556
+ // being able to tell.
557
+ if (reading.status === "absent") {
558
+ console.log(`no registry at ${FILE_CLAIMS_PATH} on ${base} — nothing has been declared yet`);
559
+ } else if (reading.claims.length === 0) {
560
+ console.log("the registry is present and declares no claims");
561
+ }
562
+ for (const c of reading.claims) {
563
+ // Three states in the listing too. A `?` is a claim whose owner this
564
+ // tree could not resolve, and printing it as DEAD would invite
565
+ // someone to prune a live lock.
566
+ const state = unmeasured.has(c.owner) ? "? " : live.has(c.owner) ? "LIVE" : "DEAD";
567
+ console.log(`${state} ${c.owner}${c.issue ? ` (#${c.issue})` : ""} ${c.paths.join(" ")}`);
568
+ if (unmeasured.has(c.owner)) console.log(` ${unmeasured.get(c.owner)}`);
569
+ }
570
+ } else {
571
+ throw new Error("one of --check, --claim, --release or --list is required");
572
+ }
573
+ } catch (e) {
574
+ console.log(`claim-files: ${e instanceof Error ? e.message : String(e)}`);
575
+ exit = REFUSE_EXIT;
576
+ }
577
+ process.exit(exit);
578
+ }