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
@@ -39,6 +39,8 @@
39
39
  * to the act rather than to the record.
40
40
  */
41
41
 
42
+ import { escapeAnnotation } from "./scaffold/ai-review-findings";
43
+
42
44
  /** What the registry currently holds for a package. */
43
45
  export interface RegistryState {
44
46
  /** Every published version, in no particular order. */
@@ -457,14 +459,92 @@ export function parsePublishReceipt(pkg: string, log: string): PublishReceipt {
457
459
  };
458
460
  }
459
461
 
462
+ /**
463
+ * WHICH reading the postflight took, in a few words (#1563).
464
+ *
465
+ * `outcome` is not this, and conflating them is the defect. Two of the six
466
+ * readings below are `confirmed` and only ONE of them is a registry read —
467
+ * they share an exit code, a step conclusion and a step name, so before this
468
+ * existed the only place they differed was the log body. A label is the
469
+ * narrowest thing that can travel out of the log on a channel a reader
470
+ * already looks at.
471
+ *
472
+ * Closed union on purpose: a new branch in `postflightDecision` that forgets
473
+ * to name itself does not compile.
474
+ */
475
+ export type PostflightLabel =
476
+ /** The packument carried the version. The only confirmed REGISTRY read. */
477
+ | "REGISTRY SERVES"
478
+ /** Receipt plus npm's own lag notice. Confirmed, and NOT a registry read. */
479
+ | "PROPAGATION PENDING"
480
+ /** npm printed no `+ pkg@version` line: the publish did not happen. */
481
+ | "NO RECEIPT"
482
+ /** npm published a version this tree is not cutting. */
483
+ | "RECEIPT VERSION MISMATCH"
484
+ /** A receipt with no lag notice does not waive the registry read. */
485
+ | "RECEIPT WITHOUT LAG NOTICE"
486
+ /** Absent from the packument with nothing that explains the absence. */
487
+ | "VERSION ABSENT";
488
+
460
489
  /** What the postflight concluded, and which exit code says so. */
461
490
  export interface PostflightDecision {
462
491
  /** `confirmed` exits 0, `refused` exits REFUSE_EXIT, `unmeasured` exits UNMEASURED_EXIT. */
463
492
  outcome: "confirmed" | "refused" | "unmeasured";
493
+ /**
494
+ * WHICH of the readings this is. `outcome` collapses six into three and two
495
+ * of the collapsed pair exit 0 — see `PostflightLabel` (#1563).
496
+ */
497
+ label: PostflightLabel;
464
498
  /** The whole message, already worded for the reader of a failed release job. */
465
499
  message: string;
466
500
  }
467
501
 
502
+ /**
503
+ * The annotation title every postflight verdict is printed under.
504
+ *
505
+ * It carries NO colon and NO comma. GitHub splits a workflow command's
506
+ * property list on `,` and ends it at `::`, and its own escaping rules
507
+ * require `%3A`/`%2C` inside a property value — `escapeAnnotation` encodes
508
+ * neither, because it is the escaper for message DATA. Keeping the separator
509
+ * out of the title means there is still one escaper and nothing to get wrong.
510
+ */
511
+ export const POSTFLIGHT_ANNOTATION_TITLE = "postflight —";
512
+
513
+ /**
514
+ * The decision as a GitHub Actions annotation — the fix for #1563.
515
+ *
516
+ * The step was named *"Postflight — the registry actually serves this
517
+ * version"* and on `v0.8.3` it exited 0 having said, in its own message, that
518
+ * it had taken no such reading. The name is what appears in the check list,
519
+ * the run summary and the notification; the message is 5.7 MB into a log.
520
+ *
521
+ * Retitling alone does not fix it. A title is static, so no title can
522
+ * distinguish `REGISTRY SERVES` from `PROPAGATION PENDING` — the criterion
523
+ * from the issue is that **some observable other than the log body differs
524
+ * between the two**, and an annotation is the cheapest channel that both
525
+ * carries the label and renders where the title does.
526
+ *
527
+ * Severity is derived from `outcome`, never from `label`: a `notice` for the
528
+ * two states that exit 0, an `error` for the four that stop the job. That
529
+ * leaves the open question the issue declined to answer — whether a pending
530
+ * propagation deserves a `warning` — unanswered, rather than answered by
531
+ * accident. Propagation lag is the normal path and a warning on the normal
532
+ * path is a warning nobody reads.
533
+ *
534
+ * `escapeAnnotation` is imported rather than reimplemented. A newline inside
535
+ * an interpolated value starts a NEW workflow command, and `::stop-commands::`
536
+ * on its own line disables annotation processing for everything after it — so
537
+ * a second escaper is a second rule nobody updates. The messages here embed a
538
+ * registry reading, and the confirmed one already contains a newline.
539
+ */
540
+ export function postflightAnnotation(decision: PostflightDecision): string {
541
+ const level = decision.outcome === "confirmed" ? "notice" : "error";
542
+ return (
543
+ `::${level} title=${POSTFLIGHT_ANNOTATION_TITLE} ${escapeAnnotation(decision.label)}` +
544
+ `::${escapeAnnotation(decision.message)}`
545
+ );
546
+ }
547
+
468
548
  /**
469
549
  * The ONE binding that decides whether a release happened (#472).
470
550
  *
@@ -511,6 +591,7 @@ export function postflightDecision(
511
591
  if (receipt.version === null) {
512
592
  return {
513
593
  outcome: "refused",
594
+ label: "NO RECEIPT",
514
595
  message:
515
596
  `the publish step produced no receipt. npm prints \`+ ${pkg}@${treeVersion}\` ` +
516
597
  `on a successful publish and the captured output (${receipt.bytes} bytes) has ` +
@@ -522,6 +603,7 @@ export function postflightDecision(
522
603
  if (receipt.version !== treeVersion) {
523
604
  return {
524
605
  outcome: "refused",
606
+ label: "RECEIPT VERSION MISMATCH",
525
607
  message:
526
608
  `the publish step published ${pkg}@${receipt.version}, but this tree is ` +
527
609
  `${treeVersion}. The receipt and package.json must name the same version or ` +
@@ -533,6 +615,7 @@ export function postflightDecision(
533
615
  if (reading.verdict.published) {
534
616
  return {
535
617
  outcome: "confirmed",
618
+ label: "REGISTRY SERVES",
536
619
  message:
537
620
  `the registry serves ${pkg}@${treeVersion} ` +
538
621
  `(read ${reading.attempts} time${reading.attempts === 1 ? "" : "s"}, ` +
@@ -561,6 +644,7 @@ export function postflightDecision(
561
644
  if (receipt !== null && receipt.version === treeVersion && receipt.propagationWarned) {
562
645
  return {
563
646
  outcome: "confirmed",
647
+ label: "PROPAGATION PENDING",
564
648
  message:
565
649
  `PROPAGATION PENDING — npm accepted ${pkg}@${treeVersion} and the registry is ` +
566
650
  `not serving it yet after ${reading.attempts} read` +
@@ -578,6 +662,7 @@ export function postflightDecision(
578
662
  if (receipt !== null && receipt.version === treeVersion) {
579
663
  return {
580
664
  outcome: "unmeasured",
665
+ label: "RECEIPT WITHOUT LAG NOTICE",
581
666
  message:
582
667
  `UNMEASURED: npm printed a receipt for ${pkg}@${treeVersion} but did NOT print its ` +
583
668
  `"being processed and may take a few minutes" notice, and the registry is still not ` +
@@ -588,5 +673,9 @@ export function postflightDecision(
588
673
  };
589
674
  }
590
675
 
591
- return { outcome: "unmeasured", message: reading.verdict.unmeasured ?? "no reading was taken" };
676
+ return {
677
+ outcome: "unmeasured",
678
+ label: "VERSION ABSENT",
679
+ message: reading.verdict.unmeasured ?? "no reading was taken",
680
+ };
592
681
  }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * One function that turns a string into a comparable repository path (#1437).
3
+ *
4
+ * Covers CRC-E2's precondition (CODE-REVIEW-CONVERGENCE-SPEC.md): a classifier
5
+ * that reads the change can only be trusted if both sides of every path
6
+ * comparison were spelled by the same hand.
7
+ *
8
+ * ## Why this is its own module
9
+ *
10
+ * The first version of this lived inside `lib/scaffold/ai-review-findings.ts`,
11
+ * where it decides whether a finding names a file the pull request touched.
12
+ * `lib/risk-tier.ts` needs the identical question answered — does this changed
13
+ * path sit under a sensitive prefix — and two private answers to one question
14
+ * are behaviourally ONE decider with a dead copy nobody can identify
15
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, the fourth shape).
16
+ *
17
+ * So the function lives here and both import it. The findings module still
18
+ * carries its own copy while #1435 is open; collapsing that one into this
19
+ * import is a one-line follow-up once #1435 lands, and it is deliberately NOT
20
+ * done from this branch — chaining onto an unmerged tip replays commits a
21
+ * squash merge is about to rewrite.
22
+ *
23
+ * ## What it refuses, and why refusing is the point
24
+ *
25
+ * A path it cannot read returns `null`, and every caller must decide what
26
+ * `null` means for it. Both current callers decide the same way — toward the
27
+ * stricter answer, blocking or HIGH — because the alternative is a gate that
28
+ * fails open on input it did not understand, which is the exact defect the
29
+ * push review found in the findings module's round one: six spellings of a
30
+ * file that WAS in the change list each read as "not in the change list" and
31
+ * demoted a `critical` to CLEAN.
32
+ *
33
+ * Git C-quoting (`"lib/\303\251.ts"`) is refused rather than decoded. Decoding
34
+ * it wrongly is the same fail-open wearing a different hat, and a caller that
35
+ * is told "I could not read this" can route to a person; a caller handed a
36
+ * mis-decoded path cannot tell that anything happened.
37
+ */
38
+
39
+ /**
40
+ * A repository-relative path in a single spelling, or `null` when the input
41
+ * cannot be read as one.
42
+ *
43
+ * Normalises: backslash separators, a leading `./`, leading slashes, a
44
+ * trailing `:line` or `:line:col` suffix, and case. Refuses: anything that is
45
+ * not a string, a git C-quoted path, and anything whose remaining shape is not
46
+ * a plain sequence of path segments.
47
+ */
48
+ export function normaliseRepoPath(value: unknown): string | null {
49
+ if (typeof value !== "string") return null;
50
+ let p = value.trim().replace(/\\/g, "/");
51
+ // A C-quoted path is refused, not decoded — see the module docblock.
52
+ if (p.startsWith('"') && p.endsWith('"')) return null;
53
+ p = p.replace(/^\/+/, "").replace(/:\d+(?::\d+)?$/, "");
54
+
55
+ // Dot segments are COLLAPSED, not stripped once. A single `.replace(/^\.\//)`
56
+ // removes one leading `./` and leaves `././lib/a.ts` as `./lib/a.ts`, which
57
+ // the shape test below accepts — `.` and `..` are both legal matches for
58
+ // `[\w.@+-]+`. The result compares unequal to `lib/a.ts` and every caller
59
+ // reads that as "a different file", which is this module's fail-open in its
60
+ // purest form: an attacker-chosen spelling of a path that IS in the change
61
+ // list reads as one that is not. Found by the push review on #1435.
62
+ //
63
+ // A `..` that would leave the repository root is refused rather than
64
+ // clamped: `../outside.ts` is not a repository-relative path, and silently
65
+ // turning it into `outside.ts` invents a file.
66
+ const out: string[] = [];
67
+ for (const segment of p.split("/")) {
68
+ if (segment === "" || segment === ".") continue;
69
+ if (segment === "..") {
70
+ if (out.pop() === undefined) return null;
71
+ continue;
72
+ }
73
+ out.push(segment);
74
+ }
75
+ p = out.join("/");
76
+ if (p === "") return null;
77
+
78
+ return /^(?:[\w.@+-]+\/)*[\w.@+-]+$/.test(p) ? p.toLowerCase() : null;
79
+ }
80
+
81
+ /**
82
+ * Does `path` sit at or under `prefix`? Both sides are normalised first.
83
+ *
84
+ * Segment-aware on purpose: `.github/workflows` must not match
85
+ * `.github/workflows-archive/x.yml`, which a bare `startsWith` would.
86
+ * Returns false when either side cannot be read — the caller decides what an
87
+ * unreadable path means, and this function never invents an answer.
88
+ */
89
+ export function underPrefix(path: unknown, prefix: string): boolean {
90
+ const p = normaliseRepoPath(path);
91
+ const q = normaliseRepoPath(prefix.replace(/\/+$/, ""));
92
+ if (p === null || q === null) return false;
93
+ return p === q || p.startsWith(`${q}/`);
94
+ }
@@ -37,12 +37,29 @@
37
37
  */
38
38
  import { execFileSync } from "child_process";
39
39
 
40
+ import { type DirectoryCurrency, type GitRunner, directoryCurrency } from "./hook-tree-currency";
40
41
  import { reviewIsCurrent } from "./security-verdict";
41
42
 
42
43
  /** The exit code of a stale or unmeasurable reading. One site, so it can be mutated. */
43
44
  export const STALE_EXIT = 1;
44
45
 
46
+ /**
47
+ * The refusal when the directory read is not the one under review (#1348).
48
+ *
49
+ * One site, so `test/report-provenance.test.ts` can prove the refusal fires
50
+ * rather than inferring it from an exit code that a dozen other conditions
51
+ * also produce.
52
+ */
53
+ export const WRONG_TREE = "UNMEASURED: wrong tree";
54
+
45
55
  export interface ProvenanceReading {
56
+ /**
57
+ * The directory the reading was taken in. Always present: a SHA does not
58
+ * say where it was read, and that is the fact a reader cannot reconstruct.
59
+ */
60
+ root: string;
61
+ /** The branch checked out at `root`, or null for a detached HEAD. */
62
+ branch: string | null;
46
63
  /** The commit the report describes. */
47
64
  measured: string | null;
48
65
  /** The commit the branch ends at now, or null when it could not be read. */
@@ -67,6 +84,16 @@ function git(root: string, args: string[]): string | null {
67
84
  }
68
85
  }
69
86
 
87
+ /**
88
+ * The branch checked out at `root`. Null for a detached HEAD, an empty
89
+ * answer, or a directory that is not a repository — all three are "there is
90
+ * no branch here", which is a different fact from any branch name.
91
+ */
92
+ export function branchAt(root: string): string | null {
93
+ const branch = git(root, ["rev-parse", "--abbrev-ref", "HEAD"]);
94
+ return branch === null || branch === "" || branch === "HEAD" ? null : branch;
95
+ }
96
+
70
97
  /**
71
98
  * The ref whose tip a report should be aged against.
72
99
  *
@@ -75,8 +102,8 @@ function git(root: string, args: string[]): string | null {
75
102
  * has not been pushed. Detached HEAD has no branch and says so.
76
103
  */
77
104
  export function defaultRef(root: string): string | null {
78
- const branch = git(root, ["rev-parse", "--abbrev-ref", "HEAD"]);
79
- if (branch === null || branch === "" || branch === "HEAD") return null;
105
+ const branch = branchAt(root);
106
+ if (branch === null) return null;
80
107
  if (git(root, ["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]) !== null) {
81
108
  return `origin/${branch}`;
82
109
  }
@@ -93,12 +120,35 @@ export function provenanceReading(
93
120
  root: string,
94
121
  measured?: string,
95
122
  ref?: string,
123
+ expectBranch?: string,
96
124
  ): ProvenanceReading {
97
125
  const measuredSha = measured ?? git(root, ["rev-parse", "HEAD"]);
126
+ const branch = branchAt(root);
127
+
128
+ // Before anything else, because a reading taken in the wrong directory is
129
+ // not stale and not current — it is about a different tree, and every
130
+ // other field below would be a true statement about the wrong thing.
131
+ if (expectBranch !== undefined && branch !== expectBranch) {
132
+ return {
133
+ root,
134
+ branch,
135
+ measured: measuredSha,
136
+ tip: null,
137
+ ref: null,
138
+ current: false,
139
+ reason:
140
+ `${WRONG_TREE}: ${root} is on ${branch ?? "no branch"}, not ${expectBranch}. ` +
141
+ `A command reads the directory it ran in, which here is not the one under ` +
142
+ `review — re-run it in the worktree holding ${expectBranch}.`,
143
+ };
144
+ }
145
+
98
146
  const resolvedRef = ref ?? defaultRef(root);
99
147
 
100
148
  if (resolvedRef === null) {
101
149
  return {
150
+ root,
151
+ branch,
102
152
  measured: measuredSha,
103
153
  tip: null,
104
154
  ref: null,
@@ -117,6 +167,8 @@ export function provenanceReading(
117
167
  const tip = git(root, ["rev-parse", "--verify", `${resolvedRef}^{commit}`]);
118
168
  if (tip === null) {
119
169
  return {
170
+ root,
171
+ branch,
120
172
  measured: measuredSha,
121
173
  tip: null,
122
174
  ref: resolvedRef,
@@ -132,6 +184,8 @@ export function provenanceReading(
132
184
  // two to parity; this is the library side, imported rather than repeated.
133
185
  const currency = reviewIsCurrent(measuredSha, tip);
134
186
  return {
187
+ root,
188
+ branch,
135
189
  measured: measuredSha,
136
190
  tip,
137
191
  ref: resolvedRef,
@@ -143,9 +197,18 @@ export function provenanceReading(
143
197
  };
144
198
  }
145
199
 
146
- /** The block to paste at the top of a report. Always states both commits. */
200
+ /**
201
+ * The block to paste at the top of a report. Always states the directory
202
+ * and both commits.
203
+ *
204
+ * The directory line is first because it is the one a reader cannot
205
+ * reconstruct from the others (#1348): two SHAs describe a tree without
206
+ * saying which checkout they were read in, and a report whose reviewer was
207
+ * sitting in another worktree looks exactly like one whose reviewer was not.
208
+ */
147
209
  export function provenanceBlock(reading: ProvenanceReading): string {
148
210
  const lines = [
211
+ `Measured in: ${reading.root} (branch ${reading.branch ?? "none"})`,
149
212
  `Measured against: ${reading.measured ?? "UNKNOWN"}`,
150
213
  `Branch tip (${reading.ref ?? "unresolved"}): ${reading.tip ?? "UNKNOWN"}`,
151
214
  reading.current
@@ -154,3 +217,155 @@ export function provenanceBlock(reading: ProvenanceReading): string {
154
217
  ];
155
218
  return lines.join("\n");
156
219
  }
220
+
221
+ /**
222
+ * The OTHER tree a session is standing in, and the one nothing above can see
223
+ * (#1341).
224
+ *
225
+ * Everything to this point measures the checkout the session EDITS. A Claude
226
+ * Code hook registration names a directory through `RUNGATE_HOOKS_DIR`, and
227
+ * the code that executes out of it is on whatever commit the last hand
228
+ * fast-forward left. Those are two different trees and only one of them has
229
+ * ever been in the provenance block.
230
+ *
231
+ * ## The measured cost, 2026-10-24
232
+ *
233
+ * `/Users/jhorn/Projects/rg-hooks-live` sat at `7817f1df` while `origin/main`
234
+ * was at `2729ce62` — **135 commits behind**, measured with
235
+ * `git rev-list --count 7817f1df..2729ce62`. Every session's own checkout was
236
+ * clean and current, so `provenanceReading` reported CURRENT for all of them.
237
+ * In that window the finding arbiter refused three issue filings using
238
+ * duplicate-detection logic PR #1538 had corrected seven minutes earlier: two
239
+ * `DUPLICATE` verdicts on bare integers and one `DROPPED_CATEGORY/style` on
240
+ * `\btypo\b`. Three `arbiter-override` escalations were spent on a fixed bug,
241
+ * and the ledger rows record them as human overrides of real refusals.
242
+ *
243
+ * It had gone stale twice the day before. The gap is not an incident, it is
244
+ * the steady state: nothing advances that tree, so the interval between a fix
245
+ * merging and the behaviour changing is unbounded.
246
+ *
247
+ * ## Why the checkout's own SHA, and not a file recording one
248
+ *
249
+ * `rg-hooks-live` is a worktree on a detached HEAD, and a detached HEAD
250
+ * already names a commit — `git rev-parse HEAD` is the whole of the
251
+ * provenance. A `SYNCED_TO` file beside it would be a SECOND decider for one
252
+ * question, and the weaker one: it is correct only while nobody moves the
253
+ * checkout without rewriting it, so a hand fast-forward makes a current tree
254
+ * read as behind, and a hand-edited tree keeps reading as current. The
255
+ * checkout is right by construction. `.claude/rules/checks-must-be-able-to-fail.md`
256
+ * calls two deciders agreeing the shape no behavioural test can separate.
257
+ *
258
+ * ## Why the count, and not `merge-base --is-ancestor`
259
+ *
260
+ * This repository squash-merges, and the standing rule against `--is-ancestor`
261
+ * holds here for a reason the suite measures: on a hook tree that is **0
262
+ * commits behind and 1 ahead**, `--is-ancestor HEAD origin/main` exits 1 — it
263
+ * calls a checkout that is missing nothing stale — while
264
+ * `rev-list --count HEAD..origin/main` reads 0. A boolean also cannot carry
265
+ * the number, and the number is what tells a reader whether to care.
266
+ * `directoryCurrency` is imported rather than reimplemented, so there is one
267
+ * binding deciding what "behind" means.
268
+ *
269
+ * ## Why this is not a hook
270
+ *
271
+ * A currency check that ships through `${RUNGATE_HOOKS_DIR}` cannot bootstrap
272
+ * itself: the copy that is behind is exactly the copy without the reporting
273
+ * code. `scripts/report-provenance.ts` runs out of the session's own
274
+ * checkout, so it is reachable by a path that cannot be stale for the reason
275
+ * it reports.
276
+ *
277
+ * ## The binding is the env var, and an unset one SKIPS
278
+ *
279
+ * No path to any machine's hooks directory appears here. `hooksDir` is
280
+ * supplied by the caller from `RUNGATE_HOOKS_DIR`, and `null` or blank means
281
+ * no hook executes out of a foreign tree — nothing to age, so nothing to
282
+ * refuse. A check that refused on an unset binding would refuse on every CI
283
+ * runner and in every consumer's checkout, which is how a refusal becomes a
284
+ * line everyone clicks past.
285
+ */
286
+ export interface SessionProvenance {
287
+ /** The tree the session edits. Exactly what `provenanceReading` returns. */
288
+ tree: ProvenanceReading;
289
+ /**
290
+ * The tree the session's hooks execute out of, or `null` when
291
+ * `RUNGATE_HOOKS_DIR` binds nothing.
292
+ *
293
+ * `null` is NOT `current`. It means the question does not arise, and the
294
+ * block says so in those words rather than printing a pass.
295
+ */
296
+ hooks: DirectoryCurrency | null;
297
+ /**
298
+ * False when EITHER reading refuses. A rate, a refusal count or a ledger
299
+ * row produced by this session is attributable to `base` only when both
300
+ * trees are.
301
+ */
302
+ current: boolean;
303
+ }
304
+
305
+ /**
306
+ * Both readings, and one verdict over them.
307
+ *
308
+ * `base` has no default, for the reason `lib/hook-tree-currency.ts` gives: a
309
+ * default here would be a second place deciding which branch a tree is
310
+ * measured against.
311
+ */
312
+ export function sessionProvenance(input: {
313
+ root: string;
314
+ measured?: string;
315
+ ref?: string;
316
+ expectBranch?: string;
317
+ /** From `RUNGATE_HOOKS_DIR`. Never a literal path — see the header. */
318
+ hooksDir: string | null | undefined;
319
+ base: string;
320
+ git: GitRunner;
321
+ }): SessionProvenance {
322
+ const tree = provenanceReading(input.root, input.measured, input.ref, input.expectBranch);
323
+
324
+ const dir = input.hooksDir?.trim();
325
+ const hooks = dir === undefined || dir === "" ? null : directoryCurrency(dir, input.base, input.git);
326
+
327
+ return {
328
+ tree,
329
+ hooks,
330
+ // `current` is the ONLY state that clears. `behind` and `unmeasured` both
331
+ // refuse, and they keep their own names in the block below — folding them
332
+ // together here would weaken the UNMEASURED refusal that
333
+ // `lib/hook-tree-currency.ts` exists to keep separate from a count.
334
+ current: tree.current && (hooks === null || hooks.state === "current"),
335
+ };
336
+ }
337
+
338
+ /**
339
+ * The block to paste at the top of a report, now carrying both trees.
340
+ *
341
+ * `provenanceBlock` is called rather than re-rendered: the four lines a
342
+ * reader already knows how to read must not drift from the ones this adds to.
343
+ */
344
+ export function sessionProvenanceBlock(p: SessionProvenance): string {
345
+ const lines = [provenanceBlock(p.tree)];
346
+
347
+ if (p.hooks === null) {
348
+ lines.push(
349
+ "Hook tree: not bound — RUNGATE_HOOKS_DIR is unset, so no hook executes out of a " +
350
+ "directory this session could age.",
351
+ );
352
+ return lines.join("\n");
353
+ }
354
+
355
+ if (p.hooks.state === "current") {
356
+ lines.push(`Hook tree: CURRENT — ${p.hooks.detail}`);
357
+ return lines.join("\n");
358
+ }
359
+
360
+ // The state keeps its own word, and the consequence is spelled out rather
361
+ // than left to the reader: the failure this closes is a number reported as
362
+ // if it described main.
363
+ const tag = p.hooks.state === "behind" ? `BEHIND ${p.hooks.behind}` : "UNMEASURED";
364
+ lines.push(
365
+ `Hook tree: ${tag} — ${p.hooks.detail}`,
366
+ ` Any rate, refusal count or ledger row this session produces is UNMEASURED against ` +
367
+ `${p.hooks.base}: it describes the hook tree above, not ${p.hooks.base}. Say UNMEASURED ` +
368
+ `rather than reporting the number.`,
369
+ );
370
+ return lines.join("\n");
371
+ }