rungate 0.8.3 → 0.8.5

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.
package/gates/.gate-salt CHANGED
@@ -1 +1 @@
1
- 47f8d47ee78dd4b50c501a7cb42b8c220a9511b6d5ce62c6012fe6596440fbe0
1
+ d12afb85b5ce604fa58cf050d86b431d8f5d26e9e0dc5f33320e97f7bf51bbc3
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * BunTestPathGuard.hook.ts — PreToolUse on Bash
4
+ *
5
+ * SC-370 (HOOK-ARCHITECTURE-SPEC): hook SC traceability
6
+ * SC-371 (HOOK-ARCHITECTURE-SPEC): no hook exceeds 150 lines
7
+ * SC-2543 (HOOK-ARCHITECTURE-SPEC): the guard is registered in all four positions
8
+ *
9
+ * The decision lives in lib/bun-test-paths.ts and not here — hooks are thin
10
+ * triggers (HOOK-ARCHITECTURE-SPEC), the same shape as TopLevelCdGuard over
11
+ * lib/top-level-cd.ts and BashToolGuard over lib/bash-file-read.ts.
12
+ *
13
+ * Refuses a Bash command that hands `bun test` a path matching no file.
14
+ *
15
+ * Why a hook and not a sentence. `bun test <real> <absent>` exits 0 and
16
+ * prints a pass total, so a typo'd path in a verification command is
17
+ * byte-identical to a suite that ran and passed. On 2026-10-24 an agent
18
+ * shipping #1536 reported six suites green; one of the six did not exist and
19
+ * had never been opened. The agent self-reported it, which is the only
20
+ * reason it is written down — an instruction to check the file count would
21
+ * have had to be followed by the one person who already believed they had.
22
+ *
23
+ * Why the Bash tool and not a wrapper. 55 sites in this tree execute
24
+ * `bun test` with a path argument and 49 are inside `test/`; a wrapper
25
+ * covers none of them until each is rewritten, and covers a hand-composed
26
+ * command never. The failure this exists for was in a command an agent
27
+ * composed by hand, so the binding has to be the one chokepoint those pass
28
+ * through. The known gap is the reverse: a spawn from inside a running
29
+ * process never reaches a PreToolUse hook. Both halves are stated in
30
+ * lib/bun-test-paths.ts under WHAT THIS DOES NOT COVER.
31
+ *
32
+ * It is registered at PROJECT scope, like TopLevelCdGuard:
33
+ * `${CLAUDE_PROJECT_DIR}` resolves to the worktree a session is in, every
34
+ * worktree carries the committed `.claude/settings.json`, and a targeted
35
+ * test run is a harness concern. Machine-wide registration lives in
36
+ * `~/.claude/settings.json`, which no PR can carry.
37
+ *
38
+ * SCOPED to harnessed projects via lib/harness-project.ts, the same decider
39
+ * TopLevelCdGuard and BashToolGuard use.
40
+ *
41
+ * Issue: #1544
42
+ */
43
+
44
+ import { parseHookInput } from './lib/parseStdin';
45
+ import {
46
+ BUN_TEST_PATH_GUARD_DECISION,
47
+ bunTestPathGuardMode,
48
+ bunTestPathRefusal,
49
+ } from '../lib/bun-test-paths';
50
+ import { isHarnessProject } from '../lib/harness-project';
51
+
52
+ async function main() {
53
+ const payload = await parseHookInput();
54
+ if (!payload) process.exit(0);
55
+
56
+ if (payload.tool_name !== 'Bash') process.exit(0);
57
+
58
+ // Scope before parse: outside a harnessed project this repo's verification
59
+ // conventions do not apply and there is nothing for this to protect.
60
+ // NARROWED, not `|| process.cwd()`: the payload field is untyped, and a
61
+ // non-string reaching `resolve()` would throw inside the guard and be
62
+ // swallowed by the fail-open below — a guard that silently stops firing.
63
+ const declared = payload.cwd;
64
+ const cwd = typeof declared === 'string' && declared !== '' ? declared : process.cwd();
65
+ if (!isHarnessProject(cwd)) process.exit(0);
66
+
67
+ const { mode, unrecognised } = bunTestPathGuardMode();
68
+ if (mode === 'off') process.exit(0);
69
+
70
+ // Fails open on an unexpected error, and says so. A broken guard must never
71
+ // be able to block every `bun test` in the repository — but it must not be
72
+ // able to do that SILENTLY either, which is a different thing and is the
73
+ // defect TestSuiteGuard's #194 found in itself.
74
+ let refusal: ReturnType<typeof bunTestPathRefusal>;
75
+ try {
76
+ refusal = bunTestPathRefusal(payload.tool_input?.command, cwd);
77
+ } catch (e) {
78
+ console.log(JSON.stringify({
79
+ systemMessage:
80
+ `GUARD-FAILURE-VISIBLE: BunTestPathGuard could not evaluate this command and ` +
81
+ `allowed it. #1544 is NOT being enforced right now. ${(e as Error)?.message ?? e}`,
82
+ }));
83
+ process.exit(0);
84
+ }
85
+
86
+ if (refusal === null) process.exit(0);
87
+
88
+ const note = unrecognised
89
+ ? `\n(${'RUNGATE_BUN_TEST_PATH_GUARD'}=${JSON.stringify(unrecognised)} is not a mode I know; refusing, which is the default.)`
90
+ : '';
91
+
92
+ if (mode === 'block') {
93
+ console.log(JSON.stringify({
94
+ decision: BUN_TEST_PATH_GUARD_DECISION,
95
+ reason: refusal.message + note,
96
+ }));
97
+ process.exit(0);
98
+ }
99
+
100
+ // WARN: the command RUNS. stderr, so it reaches the transcript without
101
+ // becoming a tool result the model might read as a refusal.
102
+ console.error(`[bun-test-path] ${refusal.message}${note}`);
103
+ process.exit(0);
104
+ }
105
+
106
+ main();
@@ -28,12 +28,44 @@
28
28
  * `.claude/rungate/hooks.json`, the current-state table in
29
29
  * `specs/HOOK-ARCHITECTURE-SPEC.md`, and `.claude/settings.json`.
30
30
  *
31
- * It is registered at PROJECT scope. `${CLAUDE_PROJECT_DIR}` resolves to the
32
- * worktree a session is in, every worktree carries the committed
33
- * `.claude/settings.json`, and worktree isolation — the thing a stray `cd`
34
- * breaks — is a harness concern. Machine-wide registration lives in
35
- * `~/.claude/settings.json`, which no PR can carry and no test here can
36
- * honestly assert (`test/hook-registration-reconciler.test.ts`).
31
+ * ## NOT LIVE. User scope since #1578, and why the first classification was wrong
32
+ *
33
+ * #992 registered this at PROJECT scope, reasoning that `${CLAUDE_PROJECT_DIR}`
34
+ * resolves to the worktree a session is in, that every worktree carries the
35
+ * committed `.claude/settings.json`, and that worktree isolation is a harness
36
+ * concern. **The second clause is true and the conclusion does not follow.**
37
+ *
38
+ * Measured on 2026-10-24 in a worktree whose committed `.claude/settings.json`
39
+ * registered this hook: three bare `cd` calls were NOT refused, while a
40
+ * user-scoped COMP-7 refusal fired on the same `Bash` matcher in the same
41
+ * session. The decider returns `block` when invoked by hand from that cwd;
42
+ * `isHarnessProject()` resolves; `RUNGATE_CD_GUARD` is unset. The worktree
43
+ * carries the file. The session does not load it. So this hook has been
44
+ * green, registered, tested and INERT since #1050 — which is #1578, and is
45
+ * the purest form of *absence of evidence recorded as clean*.
46
+ *
47
+ * The scope follows from what a hook PROTECTS. This one protects the
48
+ * SESSION's primary working directory — the directory `isolation: 'worktree'`
49
+ * resolves against — and a session may be rooted anywhere while working on
50
+ * this repo, including via an added working directory. That is machine-wide
51
+ * state, so SC-518 governs it: machine-wide hooks live in user settings,
52
+ * because project settings only load for sessions started in that directory.
53
+ * It was misclassified from the start.
54
+ *
55
+ * Two consequences, both deliberate:
56
+ *
57
+ * - The repo no longer registers it in `.claude/settings.json`. SC-518 says
58
+ * the two scopes are not de-duplicated, so leaving it there would fire the
59
+ * hook twice once the real registration exists.
60
+ * - `test/hook-registration-reconciler.test.ts` now reports it UNMEASURED on
61
+ * every run, and that reading is the deliverable rather than a loss. A test
62
+ * saying *this cannot be verified here* beats one reporting a registration
63
+ * nobody loads as satisfied.
64
+ *
65
+ * **Live registration in `~/.claude/settings.json` is a human action, is
66
+ * outside every agent's permitted scope, and is STILL PENDING.** Merging this
67
+ * does not switch the guard on. Until a human does that, this hook refuses
68
+ * nothing.
37
69
  *
38
70
  * ## The rung, and what #1040 left behind
39
71
  *
@@ -0,0 +1,295 @@
1
+ /**
2
+ * CRC-N4's suppression gate — the production caller `suppressRepeats` never
3
+ * had (#1586).
4
+ *
5
+ * `lib/ai-review-rounds.ts` has exported `carryKey → suppressRepeats` since
6
+ * #1351 and nothing called either. #1381 shipped the WALKER — the generated
7
+ * `ai-review-carry` step reads the ledger and hands the reviewer the
8
+ * unresolved set — so a repeat became *marked* rather than *dropped*. This is
9
+ * the half that drops it.
10
+ *
11
+ * ## Why the prior state arrives as a file and not as a fetch
12
+ *
13
+ * The generated job runs `ai-review-carry` → the reviewer →
14
+ * `ai-review-persist`, **which upserts this round into the ledger comment** →
15
+ * `ai-review-run`, which invokes the adjudicator. A gate that fetched the
16
+ * ledger itself would read a comment that already contains the payload it is
17
+ * deciding about: every finding would match a "prior" key that is its own,
18
+ * every round would suppress everything, and the outcome would be CLEAN
19
+ * forever. The carry step is the last position holding the state as it was
20
+ * before the reviewer ran, so it writes a snapshot and this reads it.
21
+ *
22
+ * ## Two files, because one of them cannot say why it is absent
23
+ *
24
+ * The snapshot carries BYTES and exists only on the READ path. The carry file
25
+ * carries the STATE and is written on every path by the single `carry_state`
26
+ * site. An absent snapshot therefore never means "no earlier findings" — the
27
+ * carry file says which of `AI_REVIEW_CARRY_READ`, `AI_REVIEW_CARRY_ABSENT`
28
+ * and `AI_REVIEW_CARRY_UNMEASURED` produced it. Collapsing those is #1568, in
29
+ * the half that decides a required check.
30
+ *
31
+ * ## Every refusal suppresses NOTHING
32
+ *
33
+ * There is one direction of error this module is allowed to make. Re-posting
34
+ * an advisory that was already answered is loud, cheap and self-correcting;
35
+ * dropping a finding that is still live is silent and permanent. So an
36
+ * unreadable carry file, an unreadable snapshot, a stale snapshot, an
37
+ * unrecognised identity rule and a ledger that will not parse all produce the
38
+ * same behaviour — report everything — and each produces a DIFFERENT sentence
39
+ * saying so, because "nothing was a repeat" and "nothing could be compared"
40
+ * are different facts about this round's report.
41
+ *
42
+ * ## It never sees a blocking finding
43
+ *
44
+ * `findingMustAlwaysBeReported` in `lib/scaffold/ai-review-findings.ts`
45
+ * filters before anything reaches this gate. The exemption is structural, not
46
+ * a rule this module is trusted to follow — see that predicate for the
47
+ * measurement, and for the declared deviation from the spec it rests on.
48
+ */
49
+ import { readFileSync } from "fs";
50
+ import { isAbsolute, resolve, sep } from "path";
51
+
52
+ import {
53
+ AI_REVIEW_PRIOR_MEASURED,
54
+ carryKey,
55
+ priorFindings,
56
+ readLedger,
57
+ type ReviewFinding,
58
+ } from "./ai-review-rounds";
59
+ import {
60
+ AI_REVIEW_CARRY_ABSENT,
61
+ AI_REVIEW_CARRY_READ,
62
+ AI_REVIEW_CARRY_STATE_KEY,
63
+ AI_REVIEW_CARRY_UNMEASURED,
64
+ AI_REVIEW_SNAPSHOT_ROUND_KEY,
65
+ } from "./scaffold/ai-review-step";
66
+ import type { AiReviewSuppressionGate } from "./scaffold/ai-review-findings";
67
+
68
+ /** What the gate reads, so a test can drive it without a filesystem. */
69
+ export interface SuppressionInputs {
70
+ /** The carry file's contents, or `null` when it could not be read. */
71
+ carry: string | null;
72
+ /** The snapshot's contents, or `null` when it could not be read. */
73
+ snapshot: string | null;
74
+ /** The text at a finding's cited line NOW, or `undefined`. */
75
+ lineTextFor: (finding: ReviewFinding) => string | undefined;
76
+ }
77
+
78
+ /** A prior set that was established, or the sentence saying it was not. */
79
+ export type PriorKeys =
80
+ | { status: "MEASURED"; keys: string[] }
81
+ | { status: "UNMEASURED"; reason: string };
82
+
83
+ /**
84
+ * The carry file's first line, which is the one site that decided the state.
85
+ *
86
+ * Read rather than re-derived: the walker already made this decision against
87
+ * the live API, and a second reading here would be a second decider over the
88
+ * same question — which is the shape #1568 cost three rounds of #1569.
89
+ */
90
+ export function carryStateOf(carry: string | null): string | null {
91
+ if (carry === null) return null;
92
+ const first = carry.split("\n", 1)[0] ?? "";
93
+ const prefix = `${AI_REVIEW_CARRY_STATE_KEY}=`;
94
+ return first.startsWith(prefix) ? first.slice(prefix.length).trim() : null;
95
+ }
96
+
97
+ /**
98
+ * Split the snapshot into the round it precedes and the ledger body.
99
+ *
100
+ * `round` is `null` when the header is missing or not an integer, and that is
101
+ * a REFUSAL rather than a default: a snapshot that cannot say which round it
102
+ * precedes cannot be shown to predate this one.
103
+ */
104
+ export function readSnapshot(snapshot: string): { round: number | null; body: string } {
105
+ const at = snapshot.indexOf("\n");
106
+ const head = at === -1 ? snapshot : snapshot.slice(0, at);
107
+ const body = at === -1 ? "" : snapshot.slice(at + 1);
108
+ const prefix = `${AI_REVIEW_SNAPSHOT_ROUND_KEY}=`;
109
+ if (!head.startsWith(prefix)) return { round: null, body };
110
+ const raw = head.slice(prefix.length).trim();
111
+ return { round: /^\d+$/.test(raw) ? Number(raw) : null, body };
112
+ }
113
+
114
+ /**
115
+ * Turn the two files into the keys earlier rounds raised, or the sentence
116
+ * saying they could not be established.
117
+ *
118
+ * Exported and pure so the battery can drive every refusal without a
119
+ * filesystem, and so there is one place to mutate.
120
+ */
121
+ export function priorKeysFrom(carry: string | null, snapshot: string | null): PriorKeys {
122
+ const state = carryStateOf(carry);
123
+ if (state === null) {
124
+ return {
125
+ status: "UNMEASURED",
126
+ reason:
127
+ "the carry step's own reading could not be read, so whether this pull request has " +
128
+ "earlier rounds is unknown",
129
+ };
130
+ }
131
+ if (state === AI_REVIEW_CARRY_UNMEASURED) {
132
+ return {
133
+ status: "UNMEASURED",
134
+ reason: "the carry step reported that the pull request's history could not be read",
135
+ };
136
+ }
137
+ // A complete reading, and the answer is that there is nothing to compare
138
+ // against. MEASURED with no keys, which is not the same statement as the
139
+ // branch above and must not print the same sentence.
140
+ if (state === AI_REVIEW_CARRY_ABSENT) return { status: "MEASURED", keys: [] };
141
+ if (state !== AI_REVIEW_CARRY_READ) {
142
+ return {
143
+ status: "UNMEASURED",
144
+ reason: `the carry step reported a state this reader does not know (${JSON.stringify(state)})`,
145
+ };
146
+ }
147
+
148
+ if (snapshot === null) {
149
+ return {
150
+ status: "UNMEASURED",
151
+ reason:
152
+ "the carry step read the pull request's history and the copy it left for this step " +
153
+ "could not be read",
154
+ };
155
+ }
156
+ const { round, body } = readSnapshot(snapshot);
157
+ if (round === null) {
158
+ return {
159
+ status: "UNMEASURED",
160
+ reason:
161
+ "the history copy does not say which round it precedes, so it cannot be shown to " +
162
+ "predate this round's own findings",
163
+ };
164
+ }
165
+
166
+ const reading = priorFindings(readLedger(body));
167
+ if (reading.status !== AI_REVIEW_PRIOR_MEASURED) {
168
+ return { status: "UNMEASURED", reason: reading.reason };
169
+ }
170
+
171
+ // THE ORDERING GUARD. A snapshot taken after the persist step is the same
172
+ // comment fetched the same way and is byte-shaped like a correct one; the
173
+ // only tell is that it already holds this round. Without this, the wrong
174
+ // ordering suppresses the entire payload and reports CLEAN every round.
175
+ const stale = reading.prior.filter(p => typeof p.round === "number" && p.round >= round);
176
+ if (stale.length > 0) {
177
+ return {
178
+ status: "UNMEASURED",
179
+ reason:
180
+ `the history copy holds ${stale.length} finding(s) from round ${round} or later, so it ` +
181
+ `was taken AFTER this round was recorded rather than before it. Suppressing against it ` +
182
+ `would drop this round's own findings`,
183
+ };
184
+ }
185
+
186
+ // `unmeasuredRounds` and `unkeyableRounds` are deliberately NOT a refusal.
187
+ // Both mean the key set is INCOMPLETE, and an incomplete key set suppresses
188
+ // less than a complete one — the direction this module is allowed to be
189
+ // wrong in. Refusing on them would turn a partially readable history into
190
+ // no history at all, which is the same report with a worse sentence.
191
+ return { status: "MEASURED", keys: reading.keys };
192
+ }
193
+
194
+ /**
195
+ * Build the gate the adjudicator is handed, or `null` when nothing is plumbed.
196
+ *
197
+ * `null` rather than a gate that answers "no repeats": a consumer that has
198
+ * not re-scaffolded gets exactly the reading it had before #1586, and "no
199
+ * repeat reader" is a state that cannot be confused with "the reader found
200
+ * nothing".
201
+ */
202
+ export function aiReviewSuppressionGate(inputs: SuppressionInputs): AiReviewSuppressionGate {
203
+ return (candidates: readonly unknown[]) => {
204
+ const prior = priorKeysFrom(inputs.carry, inputs.snapshot);
205
+ if (prior.status === "UNMEASURED") {
206
+ return { repeat: candidates.map(() => null), unmeasured: prior.reason };
207
+ }
208
+ // `suppressRepeats` is not called here, and that is deliberate: it
209
+ // returns partitioned LISTS, and the adjudicator's contract is
210
+ // positional. Re-deriving the position from a list would be a second
211
+ // identity derivation over findings already in order — the fault
212
+ // `AiReviewJuryGate`'s docblock names. `carryKey` is the shared rule and
213
+ // the within-round half is the growing `seen` set, exactly as
214
+ // `suppressRepeats` spells it.
215
+ const seen = new Set<string>(prior.keys);
216
+ const repeat = candidates.map(c => {
217
+ const key = carryKey(c, inputs.lineTextFor(c as ReviewFinding));
218
+ // Unkeyable CARRIES. It cannot be shown to be a repeat, and the
219
+ // direction this is allowed to be wrong in is toward reporting.
220
+ if (key === null) return null;
221
+ if (!seen.has(key)) {
222
+ seen.add(key);
223
+ return null;
224
+ }
225
+ const f = c as ReviewFinding;
226
+ return (
227
+ `${String(f.file ?? "(no file)")}: ${String(f.summary ?? "(no summary)")} — already ` +
228
+ `raised on an earlier round of this pull request, so it is not raised again`
229
+ );
230
+ });
231
+ return { repeat, unmeasured: null };
232
+ };
233
+ }
234
+
235
+ /**
236
+ * THE KEY-SYMMETRY HALF. The text at a finding's cited line, read out of the
237
+ * checkout.
238
+ *
239
+ * `carryKey` anchors on the TEXT of the cited line and falls back to the line
240
+ * NUMBER when no text is supplied — so a caller that supplies nothing is not
241
+ * computing a weaker version of the same key, it is computing keys in a
242
+ * DIFFERENT NAMESPACE from the ledger's. The ledger records `recordedText`
243
+ * and keys `t:<text>`; a text-less caller keys `n:<line>`; the two never
244
+ * collide, so the dedupe silently suppresses nothing and every round looks
245
+ * like a round with no repeats. Measured before this landed: `kept: 1,
246
+ * suppressed: 0` on a planted exact repeat.
247
+ *
248
+ * A line that cannot be read yields `undefined` and the finding falls back to
249
+ * the number anchor — asymmetric again, for that one finding, and therefore
250
+ * reported rather than dropped.
251
+ *
252
+ * `root` bounds it. A payload is written by the reviewer and names its own
253
+ * paths, so `../../etc/passwd` is an input this must handle; `resolve`
254
+ * normalises the `..` away, which is why the containment test is on the
255
+ * RESOLVED path and not on the spelling.
256
+ */
257
+ export function checkoutLineText(root: string): (finding: ReviewFinding) => string | undefined {
258
+ const base = resolve(root);
259
+ const cache = new Map<string, string[] | null>();
260
+ return (finding: ReviewFinding) => {
261
+ const file = finding.file;
262
+ const line = finding.line;
263
+ if (typeof file !== "string" || file === "") return undefined;
264
+ if (typeof line !== "number" || !Number.isInteger(line) || line < 1) return undefined;
265
+ if (isAbsolute(file)) return undefined;
266
+ const path = resolve(base, file);
267
+ if (path !== base && !path.startsWith(base + sep)) return undefined;
268
+ if (!cache.has(path)) {
269
+ try {
270
+ cache.set(path, readFileSync(path, "utf-8").split("\n"));
271
+ } catch {
272
+ cache.set(path, null);
273
+ }
274
+ }
275
+ const lines = cache.get(path) ?? null;
276
+ if (lines === null) return undefined;
277
+ const text = lines[line - 1];
278
+ return typeof text === "string" && text.trim() !== "" ? text : undefined;
279
+ };
280
+ }
281
+
282
+ /**
283
+ * Read a path, or `null`. Absent and unreadable collapse HERE and only here,
284
+ * because the caller's three-state reading comes from the carry file's
285
+ * contents rather than from its presence — and every `null` reaching
286
+ * `priorKeysFrom` produces an UNMEASURED sentence rather than an empty set.
287
+ */
288
+ export function readOrNull(path: string | undefined): string | null {
289
+ if (path === undefined || path === "") return null;
290
+ try {
291
+ return readFileSync(path, "utf-8");
292
+ } catch {
293
+ return null;
294
+ }
295
+ }