rungate 0.8.2 → 0.8.4

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 (74) hide show
  1. package/bin/rungate.ts +11 -6
  2. package/config/prove-evidence.schema.json +21 -3
  3. package/gates/.gate-salt +1 -1
  4. package/gates/gate-executor.ts +153 -1
  5. package/gates/prove.test.ts +12 -6
  6. package/gates/schema.ts +69 -6
  7. package/gates/workflow.test.ts +12 -5
  8. package/hooks/BunTestPathGuard.hook.ts +106 -0
  9. package/hooks/DocHygiene.hook.ts +2 -1
  10. package/hooks/GateResultProtection.hook.ts +28 -7
  11. package/hooks/HookCurrency.hook.ts +48 -1
  12. package/hooks/TopLevelCdGuard.hook.ts +38 -6
  13. package/hooks/VerifyPhaseLock.hook.ts +25 -8
  14. package/hooks/WorkflowStateGuard.hook.ts +24 -7
  15. package/lib/ai-review-jury.ts +725 -0
  16. package/lib/ai-review-rounds.ts +791 -4
  17. package/lib/ai-review-unmeasured.ts +361 -0
  18. package/lib/bash-write-guard.ts +1235 -102
  19. package/lib/bun-test-paths.ts +253 -0
  20. package/lib/cli-commands.ts +252 -11
  21. package/lib/closing-reference-audit.ts +163 -0
  22. package/lib/conformity.ts +17 -1
  23. package/lib/create-sc.ts +45 -12
  24. package/lib/derived-spec.ts +206 -0
  25. package/lib/file-claims.ts +335 -0
  26. package/lib/finding-arbiter.ts +502 -28
  27. package/lib/finding-jury.ts +61 -5
  28. package/lib/finding-pr-routing.ts +333 -0
  29. package/lib/frontmatter.ts +16 -0
  30. package/lib/gate-check-audit.ts +646 -0
  31. package/lib/generators/agents-md.ts +29 -0
  32. package/lib/github.ts +112 -7
  33. package/lib/hook-tree-currency.ts +494 -0
  34. package/lib/issue-closure-audit.ts +161 -14
  35. package/lib/issue-create-override.ts +53 -3
  36. package/lib/issue-filing-gate.ts +1073 -76
  37. package/lib/local-review-rounds.ts +523 -0
  38. package/lib/organize.ts +21 -1
  39. package/lib/project-state-shape.ts +56 -5
  40. package/lib/release-preflight.ts +90 -1
  41. package/lib/repo-path.ts +94 -0
  42. package/lib/report-provenance.ts +218 -3
  43. package/lib/risk-tier.ts +302 -0
  44. package/lib/rounds-to-pass.ts +274 -0
  45. package/lib/rule-row-drift.ts +199 -0
  46. package/lib/sc-claim-forms.ts +33 -5
  47. package/lib/sc-guard.ts +11 -1
  48. package/lib/sc-id-cross-tree.ts +17 -2
  49. package/lib/sc-ids.ts +71 -6
  50. package/lib/sc-reservations.ts +158 -14
  51. package/lib/scaffold/ai-review-findings.ts +1369 -27
  52. package/lib/scaffold/ai-review-step.ts +4095 -119
  53. package/lib/scaffold/ai-review-unmeasured-workflow.ts +243 -0
  54. package/lib/scaffold/owned-files.ts +14 -0
  55. package/lib/scaffold/steps.ts +100 -9
  56. package/lib/scratch-roots.ts +93 -3
  57. package/lib/spec-updater.ts +22 -2
  58. package/lib/spec-write-ast.ts +728 -0
  59. package/lib/spec-write-sweep.ts +470 -0
  60. package/lib/test-suite-lock.ts +127 -13
  61. package/lib/ts-ast.ts +26 -0
  62. package/lib/validators/spec-validators.ts +36 -7
  63. package/lib/write-spec.ts +138 -0
  64. package/package.json +2 -1
  65. package/scripts/ai-review-findings.ts +41 -1
  66. package/scripts/arbitrate-finding.ts +330 -12
  67. package/scripts/audit-specs.ts +225 -24
  68. package/scripts/convert-spec.ts +7 -2
  69. package/scripts/create-sc.ts +14 -2
  70. package/scripts/create-spec.ts +5 -2
  71. package/scripts/detect-sc-drift.ts +10 -2
  72. package/scripts/record-ai-review-unmeasured.ts +370 -0
  73. package/scripts/split-spec.ts +17 -4
  74. package/scripts/sync-sc-status.ts +14 -2
@@ -11,6 +11,7 @@ import { existsSync, readFileSync } from "fs";
11
11
  import { join } from "path";
12
12
  import type { ProjectScan } from "./types";
13
13
  import { OWNED_FILES, ownedFilesTable } from "../scaffold/owned-files";
14
+ import { commandRoutingTable } from "../cli-commands";
14
15
  import { isHarnessItself } from "../harness-identity";
15
16
  import { typecheckDecision } from "../typescript-project";
16
17
  import { localCalendarDay } from "../local-calendar-day";
@@ -408,6 +409,34 @@ ${createRows.join("\n")}
408
409
  });
409
410
  }
410
411
 
412
+ // #1309. The three rules above route DOCUMENTS, and `key-files.md` routes
413
+ // FILES. Nothing routed the project's CLI, so a command reached an agent
414
+ // only if somebody had hand-written a row for it in AGENTS.md's Commands
415
+ // table — four of ten, and the generated table reads as complete, so
416
+ // nothing signals that six more exist. Seven of the ten were named in no
417
+ // file an agent loads at launch.
418
+ //
419
+ // Un-scoped on purpose: a `paths:` key here would move the rule out of the
420
+ // launch surface, and the whole defect is a command nobody loads. It is the
421
+ // cheapest thing to reach for when the byte budget complains, so
422
+ // `test/commands-routed.test.ts` refuses it by name.
423
+ const cliPrefix = isHarnessItself(scan.root) ? "bun bin/rungate.ts" : "bunx rungate";
424
+ rules.push({
425
+ filename: "commands-routing.md",
426
+ content: `---
427
+ description: Every command the rungate CLI exposes in this project, generated from its command registry
428
+ ---
429
+
430
+ ## Command Routing
431
+
432
+ Generated from the CLI's own command registry, so it cannot list a subset.
433
+ Run one as \`${cliPrefix} <command>\`.
434
+ \`${cliPrefix} --help\` prints each command's own arguments.
435
+
436
+ ${commandRoutingTable()}
437
+ `,
438
+ });
439
+
411
440
  rules.push({
412
441
  filename: "harness-managed.md",
413
442
  content: `---
package/lib/github.ts CHANGED
@@ -317,8 +317,39 @@ export interface OpenIssue {
317
317
  number: number;
318
318
  title: string;
319
319
  body: string;
320
+ /**
321
+ * The author's relationship to the repository, verbatim from the API.
322
+ *
323
+ * Carried because a caller that uses issue text as a SUPPRESSION input has
324
+ * to know who wrote it — see `TRUSTED_ASSOCIATIONS`. Not interpreted here:
325
+ * this function reports what GitHub said and the policy lives with the
326
+ * caller that has something to lose.
327
+ */
328
+ authorAssociation: string;
320
329
  }
321
330
 
331
+ /**
332
+ * Issue authors whose text may be used to suppress something.
333
+ *
334
+ * `hornjason/pai-harness` is a PUBLIC repository, so **anyone on the internet
335
+ * can open an issue**, and `lib/issue-filing-gate.ts` deduplicates proposed
336
+ * filings against the open-issue corpus. Without this filter that is a
337
+ * remote, unauthenticated path to switching off our own quality mechanism:
338
+ * open an issue stuffed with the right symbols, files and readings, and every
339
+ * future finding that shares them is refused as a duplicate. A suppressed
340
+ * finding is indistinguishable from a finding nobody had, so it is silent.
341
+ *
342
+ * `NONE`, `CONTRIBUTOR` and `FIRST_TIME_CONTRIBUTOR` are excluded. A drive-by
343
+ * issue can still be a real duplicate, and excluding it costs one duplicate
344
+ * filing — the direction this is allowed to be wrong in. Including it costs
345
+ * real findings, which is the direction nothing here may fail in.
346
+ */
347
+ export const TRUSTED_ASSOCIATIONS: ReadonlySet<string> = new Set([
348
+ "OWNER",
349
+ "MEMBER",
350
+ "COLLABORATOR",
351
+ ]);
352
+
322
353
  /**
323
354
  * Open issues, newest first, **pull requests excluded** (#1261).
324
355
  *
@@ -337,28 +368,102 @@ export interface OpenIssue {
337
368
  * filing most likely to collide with an open PR is the one reporting the
338
369
  * defect that PR has not yet merged. That is the exact filing this gate must
339
370
  * not silence.
371
+ *
372
+ * ## It returns a PAGE, not a list, and that is the whole of #1374
373
+ *
374
+ * This used to return `OpenIssue[]`, so the only count a caller could take
375
+ * was a POST-filter one. `lib/issue-filing-gate.ts` took it, and its guard
376
+ * against "a corpus we emptied is not a clean tracker" was therefore blind to
377
+ * a page we had emptied **here**: 100 pull requests arrived as zero issues,
378
+ * the caller read `considered === 0`, and a page holding nothing usable was
379
+ * reported as a tracker holding nothing. The same fail-open #1338 closed, one
380
+ * level up, with a function boundary between the filter and the counter.
381
+ *
382
+ * So the filter now reports what it dropped, in the same value. The fix is
383
+ * not a fourth check at the caller's depth — it is moving the boundary, so
384
+ * there is no depth left at which a count can be taken of something already
385
+ * filtered. A caller that wants only the issues reads `.issues`; it can no
386
+ * longer do so without the population being in its hand.
387
+ *
388
+ * `truncated` is the second half, and it is the one that is weeks away rather
389
+ * than live: one page, no pagination, so a tracker with more open issues than
390
+ * `limit` returns exactly `limit` and a caller cannot tell a complete answer
391
+ * from a cut-off one. It is reported rather than fixed by paginating, because
392
+ * what the dedupe needs is to KNOW the comparison was narrower than the
393
+ * question, and that is true of a second page nobody fetched as well.
394
+ */
395
+ export interface DroppedRow {
396
+ /** The row's number when it had a usable one, else `null`. */
397
+ number: number | null;
398
+ reason: "pull-request" | "malformed-row";
399
+ }
400
+
401
+ /**
402
+ * One page of open issues, with the population it was drawn from.
403
+ *
404
+ * `considered` is the count **before** this module dropped anything, so a
405
+ * caller deciding whether its own empty result is a reading or the absence of
406
+ * one has the number that question needs.
340
407
  */
408
+ export interface OpenIssuePage {
409
+ /** Rows the API returned, before any filter here saw them. */
410
+ considered: number;
411
+ /** The page size actually requested, which is not always `limit`. */
412
+ perPage: number;
413
+ /** The page came back full, so the tracker may hold rows nobody fetched. */
414
+ truncated: boolean;
415
+ /** Every row this module dropped, with why. */
416
+ droppedRows: DroppedRow[];
417
+ issues: OpenIssue[];
418
+ }
419
+
341
420
  export async function listOpenIssues(
342
421
  client: GitHubClient,
343
422
  repoSlug: string,
344
423
  limit = 100,
345
- ): Promise<OpenIssue[]> {
424
+ ): Promise<OpenIssuePage> {
346
425
  const { owner, repo } = parseOwnerRepo(repoSlug);
426
+ const perPage = Math.min(Math.max(limit, 1), 100);
347
427
  const response = await client.rest.issues.listForRepo({
348
428
  owner,
349
429
  repo,
350
430
  state: "open",
351
- per_page: Math.min(Math.max(limit, 1), 100),
431
+ per_page: perPage,
352
432
  });
353
433
  const rows = Array.isArray(response?.data) ? response.data : [];
354
- return rows
355
- .filter(row => row !== null && typeof row === "object" && row.pull_request === undefined)
356
- .filter(row => typeof row.number === "number" && typeof row.title === "string")
357
- .map(row => ({
434
+ const issues: OpenIssue[] = [];
435
+ const droppedRows: DroppedRow[] = [];
436
+ for (const row of rows) {
437
+ // Order matters for the reason recorded, never for the verdict. A null
438
+ // row is malformed and not a pull request, and a row reported under the
439
+ // wrong reason is a report nobody can act on.
440
+ if (row === null || typeof row !== "object") {
441
+ droppedRows.push({ number: null, reason: "malformed-row" });
442
+ continue;
443
+ }
444
+ const numbered = typeof row.number === "number" ? (row.number as number) : null;
445
+ if (row.pull_request !== undefined) {
446
+ droppedRows.push({ number: numbered, reason: "pull-request" });
447
+ continue;
448
+ }
449
+ if (typeof row.number !== "number" || typeof row.title !== "string") {
450
+ droppedRows.push({ number: numbered, reason: "malformed-row" });
451
+ continue;
452
+ }
453
+ issues.push({
358
454
  number: row.number as number,
359
455
  title: row.title as string,
360
456
  body: typeof row.body === "string" ? row.body : "",
361
- }));
457
+ // An absent association is not a trusted one. `""` fails every
458
+ // membership test in `TRUSTED_ASSOCIATIONS`, which is the reading a
459
+ // caller should get when GitHub did not say.
460
+ authorAssociation: typeof row.author_association === "string" ? row.author_association : "",
461
+ });
462
+ }
463
+ // `>=` and not `>`: a full page is the only observation available, and the
464
+ // API cannot return more than was asked for, so `>` is a predicate that can
465
+ // never fire. It is the cheapest wrong spelling of this line.
466
+ return { considered: rows.length, perPage, truncated: rows.length >= perPage, droppedRows, issues };
362
467
  }
363
468
 
364
469
  /**
@@ -0,0 +1,494 @@
1
+ /**
2
+ * How OLD are the bytes a hook registration resolves to (#1216).
3
+ *
4
+ * `lib/hook-target-tree.ts` answers *which directory* a registration names.
5
+ * This answers *which commit that directory is on*, and it exists because the
6
+ * first question has been standing in for the second — its own header says so
7
+ * at the end: `hook-target-tree` "answers which directory, never which
8
+ * commit", and `specs/HOOK-ARCHITECTURE-SPEC.md` repeats the caution under
9
+ * *Which tree the table was measured against*.
10
+ *
11
+ * ## The cost, measured twice in one day
12
+ *
13
+ * On 2026-10-23 the finding arbiter merged as #1282 and then adjudicated
14
+ * nothing for several hours. `RUNGATE_HOOKS_DIR` resolves to
15
+ * a hand-maintained working tree, and that tree was **14 commits behind
16
+ * `origin/main`** — it did not contain the arbiter that had just merged. A
17
+ * hand `fetch` + `merge --ff-only` turned it on, and it went stale again
18
+ * within hours, twice the same day (`62536bd3` → `9f2080d6` → `7817f1df`).
19
+ *
20
+ * Nothing on disk said which `main` those hooks were. **A hook that is absent
21
+ * and a hook that is fourteen commits old produce the same observation** —
22
+ * the code runs and finds nothing — and only one of them is a bug in the
23
+ * code.
24
+ *
25
+ * Same class as *An Unreleased Fix Looks Like a Fixed Bug*: a `lib/` fix is
26
+ * dormant until the next publish. Worse here, because a published package
27
+ * carries a version number and a working tree carries nothing at all.
28
+ *
29
+ * ## This is a READING. It does not move anything
30
+ *
31
+ * No `fetch`, no `merge`, no write of any kind. Silently updating a directory
32
+ * somebody is executing from is worse than saying it is old: the operator
33
+ * loses the one moment where they could have noticed, and a hook changing
34
+ * under a running session is a failure mode nobody is looking for. Every git
35
+ * invocation below is a query.
36
+ *
37
+ * Not fetching has a consequence the reading must own: the base is the
38
+ * TARGET directory's own `origin/main`, whose freshness depends on when that
39
+ * tree last fetched. A tree that has never fetched can read `current` against
40
+ * a remote-tracking ref that is itself months old. That is why every line
41
+ * names the base SHA — two directories reporting different `origin/main`
42
+ * SHAs is visible at a glance, and a reader who wants certainty can fetch by
43
+ * hand. Reporting a number without the ref it was taken against would be the
44
+ * same defect one level up.
45
+ *
46
+ * ## Three states, and the third is not a rounding of the first
47
+ *
48
+ * | state | means |
49
+ * |---|---|
50
+ * | `current` | the directory's HEAD contains every commit on the base |
51
+ * | `behind` | N commits on the base are not in that HEAD, N and both SHAs named |
52
+ * | `unmeasured` | not a working tree, absent, base unresolvable, or dirty |
53
+ *
54
+ * `unmeasured` never degrades to `current`. The whole defect is that a
55
+ * reading nobody could take looks exactly like a clean one — the three
56
+ * fail-open shapes in `lib/hook-target-tree.ts`'s header are the same list,
57
+ * one question earlier.
58
+ *
59
+ * **Uncommitted changes read as `unmeasured`, not `current`.** Bytes that
60
+ * correspond to no commit cannot be certified against one, and a hand-edited
61
+ * live hook is precisely how a tree gets code nothing merged. But dirtiness
62
+ * can only ever prevent a `current` reading — it never masks a `behind` one,
63
+ * because "14 behind, and also edited" is strictly more useful than
64
+ * "unmeasured".
65
+ *
66
+ * ## Where the reading has to appear
67
+ *
68
+ * Three surfaces were weighed; two are rejected here rather than in a PR
69
+ * comment, because the rejections are the argument for the one that was
70
+ * taken.
71
+ *
72
+ * - **A case in an existing suite.** CI has no `~/.claude/settings.json`, so
73
+ * on a runner the reading is UNMEASURED by construction — a permanent
74
+ * refusal, or a permanent skip. And it reaches whoever runs the suite,
75
+ * never the session whose hooks are the stale ones. Those are different
76
+ * people on different machines, and only the second can act.
77
+ * - **A line in each hook's own output.** Fourteen registrations firing on
78
+ * every tool call is a message an operator stops reading, which is the
79
+ * failure `hooks/HookCurrency.hook.ts`'s CADENCE note already argues
80
+ * against. It also inverts: the copy that is fourteen commits old is
81
+ * exactly the one that does not contain the reporting code, so the stale
82
+ * hooks would be the silent ones and the current hooks would do all the
83
+ * reporting.
84
+ * - **A startup report — taken.** Once per session, in the session whose
85
+ * hooks those are, printed beside `#879`'s reading, which is this one
86
+ * asked of `.git/hooks` instead.
87
+ *
88
+ * That third bullet's objection applies to the reporter too, and the answer
89
+ * is structural: `HookCurrency` is registered twice — through
90
+ * `${RUNGATE_HOOKS_DIR}` in `.claude/rungate/hooks.json`, which is subject to
91
+ * the staleness it reports, and through `${CLAUDE_PROJECT_DIR}` in the repo's
92
+ * `.claude/settings.json`, which resolves to the session's own checkout and
93
+ * is not. **A reporter must be reachable by a path that cannot be stale for
94
+ * the reason it reports**, and the second registration is what makes that
95
+ * true here.
96
+ *
97
+ * ## Why `ahead` is not a fourth state
98
+ *
99
+ * A directory carrying local commits on top of the base still contains every
100
+ * merged commit, so every merged fix reaches it. That is the question this
101
+ * module asks. Whether the extra commits should exist is a different one and
102
+ * `lib/hook-target-tree.ts` already refuses to answer two questions at once.
103
+ */
104
+
105
+ import {
106
+ type TargetTreeCensus,
107
+ readEnvScopes,
108
+ registeredTreeCensus,
109
+ } from "./hook-target-tree";
110
+ import { readRegistrationScopes } from "./hook-scopes";
111
+ import { gitIsolatedArgs, gitIsolatedEnv } from "./git-isolation";
112
+
113
+ /** One git query's result. `status` is the exit code; a non-zero one is a reading. */
114
+ export interface GitResult {
115
+ status: number;
116
+ stdout: string;
117
+ }
118
+
119
+ /**
120
+ * Run git in a directory.
121
+ *
122
+ * Injected rather than imported, for the reason `readFile` is injected into
123
+ * `readRegistrationScopes`: a function that reaches for `child_process`
124
+ * itself can only be tested against whatever repositories happen to be on the
125
+ * machine running the suite.
126
+ *
127
+ * It must NOT throw for a non-zero exit — a directory that is not a
128
+ * repository is the single most important case here, and an exception would
129
+ * have to be caught somewhere that could turn it into silence.
130
+ */
131
+ export type GitRunner = (dir: string, args: string[]) => GitResult;
132
+
133
+ /**
134
+ * `spawnSync`, narrowed to what the runner below needs.
135
+ *
136
+ * Injected so this module keeps no `child_process` import, for the same
137
+ * reason `readFile` is injected: a function that reaches for the machine can
138
+ * only be tested against the machine.
139
+ */
140
+ export type SpawnGit = (
141
+ command: string,
142
+ args: string[],
143
+ options: { encoding: "utf-8"; env: NodeJS.ProcessEnv; timeout: number },
144
+ ) => { status: number | null; stdout: string | null };
145
+
146
+ /** Per-invocation budget. A wedged directory must become a reading, not a hang. */
147
+ export const GIT_TIMEOUT_MS = 5_000;
148
+
149
+ /**
150
+ * The ONE isolated runner, and the only one anything in production may use.
151
+ *
152
+ * ## Why this is not an optional hardening
153
+ *
154
+ * `git -C <dir>` reads that directory's `.git/config`, and several of its
155
+ * keys are EXECUTABLE: `core.fsmonitor` is a command git runs, `core.hooksPath`
156
+ * points at hooks git fires, `core.excludesFile` decides what git can see.
157
+ * `lib/git-isolation.ts` holds the measured table.
158
+ *
159
+ * The exposure is sharper here than at any other call site in this tree,
160
+ * and it comes from the feature's own premise. The directories this module
161
+ * reads are the ones `RUNGATE_HOOKS_DIR` and friends resolve to — a
162
+ * hand-maintained worktree that **this module exists because nobody is
163
+ * watching**. And it runs at SessionStart, in every session on the machine.
164
+ * An unisolated reader would be a hook written to report that an unsupervised
165
+ * directory is stale, which executes whatever that unsupervised directory
166
+ * tells it to.
167
+ *
168
+ * Measured 2026-10-23 on a planted repository with the key in its own
169
+ * `.git/config` (not `~/.gitconfig`), git 2.x:
170
+ *
171
+ * | poisoned key | unisolated | isolated |
172
+ * |---|---|---|
173
+ * | `core.fsmonitor` → a script writing a marker | **marker written twice — git ran it** | not run |
174
+ * | `core.excludesFile` → a list naming the edited hook | **`current`** | `unmeasured` |
175
+ *
176
+ * The second row is the one specific to this module: poisoning
177
+ * `core.excludesFile` in the unwatched tree blinds the uncommitted-bytes
178
+ * check, so a hand-edited hook certifies as matching a merged commit. The
179
+ * directory gets to lie about its own cleanliness to the reading whose job
180
+ * is to catch exactly that.
181
+ *
182
+ * `safe.directory` comes along from `GIT_ISOLATION_CONFIG` and is
183
+ * load-bearing rather than a loosening — neutralising the global file
184
+ * removes the ownership exception with it, and reading a worktree we
185
+ * deliberately do not own is this module's whole job.
186
+ *
187
+ * Both halves or neither: the `-c` flags are the only thing covering the
188
+ * checkout's own `.git/config`, and the env vars are the only thing covering
189
+ * files nobody enumerated. That is why one binding builds both, instead of a
190
+ * convention each caller follows.
191
+ */
192
+ export function spawnGitRunner(spawn: SpawnGit, timeoutMs = GIT_TIMEOUT_MS): GitRunner {
193
+ const env = gitIsolatedEnv();
194
+ return (dir, args) => {
195
+ const r = spawn("git", gitIsolatedArgs(["-C", dir, ...args]), {
196
+ encoding: "utf-8",
197
+ env,
198
+ timeout: timeoutMs,
199
+ });
200
+ // A timed-out or killed child reports `status: null`. Mapping that to a
201
+ // non-zero code makes it UNMEASURED, which is the honest reading — the
202
+ // alternative is a SessionStart that hangs on a poisoned fsmonitor.
203
+ return { status: r.status ?? 1, stdout: r.stdout ?? "" };
204
+ };
205
+ }
206
+
207
+ export type CurrencyState = "current" | "behind" | "unmeasured";
208
+
209
+ export interface DirectoryCurrency {
210
+ dir: string;
211
+ state: CurrencyState;
212
+ /** Commits on the base that this HEAD does not contain. `null` unless `behind`. */
213
+ behind: number | null;
214
+ /** The ref the comparison was taken against, as written. */
215
+ base: string;
216
+ /** What the base resolved to IN THIS DIRECTORY, so a reader can compare two rows. */
217
+ baseSha: string | null;
218
+ headSha: string | null;
219
+ /** How many hook registrations execute out of this directory. */
220
+ registrations: number;
221
+ detail: string;
222
+ }
223
+
224
+ export interface RegistrationCurrency {
225
+ reading: "MEASURED" | "UNMEASURED";
226
+ unmeasuredReasons: string[];
227
+ /** One row per distinct directory, sorted, worst state first. */
228
+ directories: DirectoryCurrency[];
229
+ /** Registrations whose path never resolved to a directory at all. */
230
+ unresolved: number;
231
+ /** Registrations this run looked at. Zero is UNMEASURED, not agreement. */
232
+ examined: number;
233
+ }
234
+
235
+ const SHORT = 8;
236
+
237
+ function short(sha: string): string {
238
+ return sha.slice(0, SHORT);
239
+ }
240
+
241
+ function unmeasured(
242
+ dir: string,
243
+ base: string,
244
+ registrations: number,
245
+ reason: string,
246
+ ): DirectoryCurrency {
247
+ return {
248
+ dir,
249
+ state: "unmeasured",
250
+ behind: null,
251
+ base,
252
+ baseSha: null,
253
+ headSha: null,
254
+ registrations,
255
+ detail: `${dir} could not be compared with ${base}: ${reason}`,
256
+ };
257
+ }
258
+
259
+ /**
260
+ * The currency of ONE directory.
261
+ *
262
+ * Ordered so each refusal names the cheapest distinct cause. A single
263
+ * "could not read it" would be a refusal nobody can act on — "not a working
264
+ * tree" and "the tree has no `origin/main`" need different repairs, and the
265
+ * second one is a tree someone cloned without a remote, not a stale one.
266
+ */
267
+ export function directoryCurrency(
268
+ dir: string,
269
+ base: string,
270
+ git: GitRunner,
271
+ registrations = 0,
272
+ ): DirectoryCurrency {
273
+ const top = git(dir, ["rev-parse", "--show-toplevel"]);
274
+ if (top.status !== 0) {
275
+ return unmeasured(
276
+ dir,
277
+ base,
278
+ registrations,
279
+ "it is not inside a git working tree — it is absent, or it is a hand-copied directory, and " +
280
+ "either way nothing there relates those bytes to any merged commit",
281
+ );
282
+ }
283
+
284
+ const head = git(dir, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]);
285
+ if (head.status !== 0 || head.stdout.trim() === "") {
286
+ return unmeasured(dir, base, registrations, "it has no HEAD commit");
287
+ }
288
+
289
+ const tip = git(dir, ["rev-parse", "--verify", "--quiet", `${base}^{commit}`]);
290
+ if (tip.status !== 0 || tip.stdout.trim() === "") {
291
+ return unmeasured(
292
+ dir,
293
+ base,
294
+ registrations,
295
+ `${base} is not a ref in that tree, so nothing there says which ${base} those bytes came ` +
296
+ `from. This reading never fetches, so an unfetched remote is a refusal and not a pass`,
297
+ );
298
+ }
299
+
300
+ const headSha = head.stdout.trim();
301
+ const baseSha = tip.stdout.trim();
302
+
303
+ // `HEAD..base` — commits reachable from the base that this HEAD does not
304
+ // contain. The direction is the whole measurement: transposed, the live
305
+ // tree measured on 2026-10-23 reads 1 rather than 14, and 14 is the number
306
+ // that matters. `test/unit/hook-tree-currency.test.ts` pins it with a
307
+ // fixture that is behind by 3 AND ahead by 1, so no transposition can
308
+ // produce the expected count.
309
+ const count = git(dir, ["rev-list", "--count", `${headSha}..${baseSha}`]);
310
+ const raw = count.stdout.trim();
311
+ if (count.status !== 0 || !/^\d+$/.test(raw)) {
312
+ return unmeasured(
313
+ dir,
314
+ base,
315
+ registrations,
316
+ `the commit count between HEAD and ${base} could not be read`,
317
+ );
318
+ }
319
+ const behind = Number(raw);
320
+
321
+ if (behind > 0) {
322
+ return {
323
+ dir,
324
+ state: "behind",
325
+ behind,
326
+ base,
327
+ baseSha,
328
+ headSha,
329
+ registrations,
330
+ detail:
331
+ `${dir} is at ${short(headSha)}, ${behind} commit(s) behind ${base} ` +
332
+ `(${short(baseSha)}) in that tree. Anything merged in those ${behind} commit(s) is on ` +
333
+ `main and is not running`,
334
+ };
335
+ }
336
+
337
+ // Only reached when the directory is otherwise current, by design: see the
338
+ // header. A dirty tree that is also behind keeps its `behind` reading.
339
+ const dirty = git(dir, ["status", "--porcelain", "--", dir]);
340
+ if (dirty.status !== 0) {
341
+ return unmeasured(dir, base, registrations, "its working-tree status could not be read");
342
+ }
343
+ const modified = dirty.stdout.split("\n").filter(l => l.trim() !== "").length;
344
+ if (modified > 0) {
345
+ return unmeasured(
346
+ dir,
347
+ base,
348
+ registrations,
349
+ `its HEAD is ${base} (${short(baseSha)}) but ${modified} path(s) under it are uncommitted, ` +
350
+ `so the bytes that execute correspond to no commit`,
351
+ );
352
+ }
353
+
354
+ return {
355
+ dir,
356
+ state: "current",
357
+ behind: 0,
358
+ base,
359
+ baseSha,
360
+ headSha,
361
+ registrations,
362
+ detail: `${dir} is at ${short(headSha)}, which contains every commit on ${base}`,
363
+ };
364
+ }
365
+
366
+ /** `current` last, so the rows that need acting on are the ones at the top. */
367
+ const ORDER: Record<CurrencyState, number> = { behind: 0, unmeasured: 1, current: 2 };
368
+
369
+ /**
370
+ * The currency of every directory a resolved registration lands in.
371
+ *
372
+ * Takes the census rather than re-resolving anything: `registeredTreeCensus`
373
+ * is the one binding that decides which directory a registration names, and a
374
+ * second resolver here would be two deciders for one question
375
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, the fourth shape).
376
+ *
377
+ * This is also `registeredTreeCensus`'s first caller outside `test/`. It was
378
+ * shipped by #1006 and nothing in production has ever called it — a library
379
+ * function with no production caller is not shipped, however well tested.
380
+ */
381
+ export function registrationCurrency(
382
+ census: TargetTreeCensus,
383
+ base: string,
384
+ git: GitRunner,
385
+ ): RegistrationCurrency {
386
+ const reasons = [...census.unmeasuredReasons];
387
+
388
+ const perDir = new Map<string, number>();
389
+ for (const r of [...census.inRepo, ...census.foreign]) {
390
+ if (r.resolved === null) continue;
391
+ const dir = r.resolved.slice(0, r.resolved.lastIndexOf("/"));
392
+ perDir.set(dir, (perDir.get(dir) ?? 0) + 1);
393
+ }
394
+
395
+ const directories = [...perDir.entries()]
396
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
397
+ .map(([dir, n]) => directoryCurrency(dir, base, git, n));
398
+
399
+ for (const d of directories) {
400
+ if (d.state !== "current") reasons.push(d.detail);
401
+ }
402
+
403
+ if (directories.length === 0) {
404
+ reasons.push(
405
+ `no registration resolved to a directory, so no tree's age was read. Zero directories ` +
406
+ `compared is not agreement — an empty row list here means the run found nothing to ` +
407
+ `look at`,
408
+ );
409
+ }
410
+
411
+ return {
412
+ reading: reasons.length === 0 ? "MEASURED" : "UNMEASURED",
413
+ unmeasuredReasons: reasons,
414
+ directories: directories.sort((a, b) => ORDER[a.state] - ORDER[b.state]),
415
+ unresolved: census.unresolved.length,
416
+ examined: census.examined,
417
+ };
418
+ }
419
+
420
+ /**
421
+ * Assemble the whole reading from a machine.
422
+ *
423
+ * Every input is injected — `readFile`, the owned-hook list, the registry
424
+ * commands and `git` — so this module keeps no `fs` and no `child_process`
425
+ * import and a case can drive an absent scope, an empty tree or a directory
426
+ * that is not a repository without touching the machine running the suite.
427
+ * `lib/hook-scopes.ts` and `lib/hook-target-tree.ts` are both built this way
428
+ * and the reason is the same one.
429
+ *
430
+ * `base` has no default. A default here would be a second place deciding
431
+ * which branch a tree is measured against, and the caller already has to
432
+ * know (`.claude/rules/config-access.md`: a built-in substituted silently is
433
+ * the anti-pattern).
434
+ */
435
+ export function readRegistrationCurrency(input: {
436
+ repoRoot: string;
437
+ home: string;
438
+ base: string;
439
+ readFile: (path: string) => string | null;
440
+ ownedHooks: string[];
441
+ registryCommands: string[];
442
+ git: GitRunner;
443
+ }): RegistrationCurrency {
444
+ const census = registeredTreeCensus(
445
+ input.ownedHooks,
446
+ readRegistrationScopes(input.repoRoot, input.home, input.readFile, input.registryCommands),
447
+ readEnvScopes(input.repoRoot, input.home, input.readFile),
448
+ input.repoRoot,
449
+ );
450
+ return registrationCurrency(census, input.base, input.git);
451
+ }
452
+
453
+ /**
454
+ * The reading, as lines a human reads at session start.
455
+ *
456
+ * The headline carries all three counts rather than picking a class, so a
457
+ * `behind` row and an `unmeasured` row can never hide behind each other —
458
+ * which is the shape of the defect, not a formatting preference. Directories
459
+ * that are `current` get no row: they are the ones nobody has to do anything
460
+ * about, and a report whose every line is routine is a report nobody reads.
461
+ */
462
+ export function currencyReportLines(r: RegistrationCurrency): string[] {
463
+ const n = (s: CurrencyState) => r.directories.filter(d => d.state === s).length;
464
+ const behind = n("behind");
465
+ const unread = n("unmeasured");
466
+ const current = n("current");
467
+ const total = r.directories.length;
468
+
469
+ if (total === 0) {
470
+ return [`Hook tree currency UNMEASURED: ${r.unmeasuredReasons.join("; ")}`];
471
+ }
472
+
473
+ const lines: string[] = [
474
+ behind === 0 && unread === 0
475
+ ? `Hook tree currency: ${current} director(ies) current with ${r.directories[0]!.base}`
476
+ : `Hook tree currency: ${current} current, ${behind} BEHIND, ${unread} UNMEASURED — ` +
477
+ `of ${total} director(ies) hook registrations execute from`,
478
+ ];
479
+
480
+ for (const d of r.directories) {
481
+ if (d.state === "current") continue;
482
+ const tag = d.state === "behind" ? `BEHIND ${d.behind}` : "UNMEASURED";
483
+ lines.push(` ${tag}: ${d.detail} [${d.registrations} registration(s)]`);
484
+ }
485
+
486
+ if (r.unresolved > 0) {
487
+ lines.push(
488
+ ` UNMEASURED: ${r.unresolved} registration(s) name a path that resolves to no directory ` +
489
+ `at all, so their age was not read either`,
490
+ );
491
+ }
492
+
493
+ return lines;
494
+ }