rungate 0.7.0 → 0.8.0

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 (63) hide show
  1. package/hooks/ActionVerificationGate.hook.ts +96 -0
  2. package/hooks/AgentBriefGuard.hook.ts +38 -0
  3. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  4. package/hooks/AutoVerifyGate.hook.ts +79 -0
  5. package/hooks/BashToolGuard.hook.ts +65 -0
  6. package/hooks/BashWriteGuard.hook.ts +60 -0
  7. package/hooks/CommitEnforcement.hook.ts +130 -0
  8. package/hooks/DocHygiene.hook.ts +148 -0
  9. package/hooks/GateEnforcement.hook.ts +58 -0
  10. package/hooks/GateResultProtection.hook.ts +69 -0
  11. package/hooks/HarnessAFKGate.hook.ts +85 -0
  12. package/hooks/HookCurrency.hook.ts +99 -0
  13. package/hooks/IssueCloseGuard.hook.ts +149 -0
  14. package/hooks/MergeGuard.hook.ts +58 -0
  15. package/hooks/PostCompact.hook.ts +60 -0
  16. package/hooks/ProjectStateSync.hook.ts +103 -0
  17. package/hooks/SkillGuard.hook.ts +69 -0
  18. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  19. package/hooks/SpecSCGuard.hook.ts +123 -0
  20. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  21. package/hooks/TaskCompleted.hook.ts +51 -0
  22. package/hooks/TeamInit.hook.ts +85 -0
  23. package/hooks/TestSuiteGuard.hook.ts +70 -0
  24. package/hooks/TestSuiteRelease.hook.ts +85 -0
  25. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  26. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  27. package/hooks/WorkflowStateGuard.hook.ts +40 -0
  28. package/hooks/lib/agent-config.json +9 -0
  29. package/hooks/lib/agentDetection.ts +201 -0
  30. package/hooks/lib/comment-template.ts +86 -0
  31. package/hooks/lib/findWorkflow.ts +101 -0
  32. package/hooks/lib/parseStdin.ts +37 -0
  33. package/hooks/lib/paths.ts +111 -0
  34. package/hooks/lib/utils.ts +338 -0
  35. package/lib/affected-tests.ts +29 -0
  36. package/lib/bash-write-guard.ts +373 -0
  37. package/lib/branch-cleanup.ts +279 -7
  38. package/lib/config-trackable.ts +9 -0
  39. package/lib/distribution-currency.ts +55 -5
  40. package/lib/failure-intake.ts +7 -1
  41. package/lib/gate-enforcement.ts +222 -28
  42. package/lib/gate-names.ts +72 -0
  43. package/lib/gate-result-protection.ts +427 -0
  44. package/lib/intake-sources.ts +380 -0
  45. package/lib/late-env-spawn.ts +331 -0
  46. package/lib/launch-base.ts +128 -5
  47. package/lib/paths.ts +96 -3
  48. package/lib/phase2-decomposition.ts +1 -1
  49. package/lib/published-artifact.ts +162 -18
  50. package/lib/sc-id-cross-tree.ts +84 -8
  51. package/lib/scaffold/ai-review-findings.ts +7 -1
  52. package/lib/scaffold/ai-review-step.ts +861 -116
  53. package/lib/scaffold/defaults.ts +82 -1
  54. package/lib/scaffold/steps.ts +436 -44
  55. package/lib/security-verdict.ts +1 -1
  56. package/lib/shell-path-interpolation.ts +594 -0
  57. package/lib/text-dependents.ts +875 -0
  58. package/lib/workflow-security.ts +29 -0
  59. package/lib/workflow-taint.ts +732 -0
  60. package/lib/worktree-cleanup.ts +65 -38
  61. package/lib/worktree-repo.ts +32 -2
  62. package/package.json +3 -1
  63. package/scripts/check-installed-hook-currency.ts +825 -0
@@ -0,0 +1,825 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Compare every INSTALLED git hook against what the generator produces
4
+ * today, and refuse when they differ (#599, #891).
5
+ *
6
+ * The population is `GENERATED_HOOKS` in `lib/scaffold/steps.ts` — the same
7
+ * declaration `createGitHooks` installs from — and not a list here. Until
8
+ * #891 this script joined the literal `pre-commit` and compared that one
9
+ * file, so the `pre-push` installed in this repository sat a mutation
10
+ * battery behind its generator (#728) while the check printed a clean
11
+ * verdict about the other hook and exited 0. A hook the scaffold gains is
12
+ * now a hook this reports on, without this file being edited.
13
+ *
14
+ * `.git/hooks/pre-commit` is untracked. Nothing in the repository can see it,
15
+ * no CI job installs it, and `createGitHooks` only runs on a re-scaffold — so
16
+ * a fix to the generator reaches a developer's own commits when somebody
17
+ * remembers, and not otherwise. "The generator is fixed" and "my commits are
18
+ * fixed" are two claims and only the first has ever had evidence here: #450
19
+ * landed the linked-worktree guard on 2026-10-17 and this repository went on
20
+ * committing through the pre-#450 hook, which is the only reason #599 was
21
+ * observable at all.
22
+ *
23
+ * The comparison is BYTE-EXACT, and the named guards below are diagnosis
24
+ * rather than the test. A check that asked only "does the installed hook
25
+ * contain the worktree guard" would be satisfiable by pasting the string into
26
+ * a hook that does nothing with it — the proxy trap
27
+ * `.claude/rules/checks-must-be-able-to-fail.md` records against #492. What
28
+ * the named guards buy is a refusal that says WHICH fix the installed copy
29
+ * predates, which is the difference between a message someone acts on and one
30
+ * they learn to click past.
31
+ *
32
+ * Usage:
33
+ * bun scripts/check-installed-hook-currency.ts [--project <dir>] [--generator <dir>] [--install]
34
+ *
35
+ * `--project` the checkout whose installed hook is read. Defaults to cwd.
36
+ * A LINKED WORKTREE is resolved to the shared `.git` it points
37
+ * at, because that is where the hook it will actually run lives.
38
+ * `--generator` the rungate checkout holding `lib/scaffold/steps.ts`. Defaults
39
+ * to this script's own repository.
40
+ * `--install` write the generator output to the installed path. The remedy
41
+ * the refusal names, so it is one command rather than a
42
+ * paragraph.
43
+ *
44
+ * THREE PROPERTIES THIS FILE MUST KEEP, all asserted by
45
+ * test/unit/installed-hook-currency.test.ts (see
46
+ * .claude/rules/checks-must-be-able-to-fail.md, "For a script whose job is to
47
+ * exit non-zero"):
48
+ *
49
+ * 1. Every refusal exits through REFUSE_EXIT, declared exactly once. The
50
+ * test builds a mutant copy with that constant set to 0 and runs every
51
+ * negative case twice — real refuses, mutant does not. An exit written
52
+ * with a literal code would slip past the mutation and the case guarding
53
+ * it would be indistinguishable from one passing by accident.
54
+ * 2. No relative imports, static or dynamic. The mutant runs from a temp
55
+ * directory, and a relative import of anything under lib/ would make it
56
+ * die on module resolution — a non-zero exit that reads as the mutation
57
+ * having been rejected on the merits. The generator is reached through a
58
+ * path computed from `--generator` instead, which is why that option
59
+ * exists at all.
60
+ * 3. Every refusal carries a CLASS, and the class decides the label (#613).
61
+ * The exit code says a refusal happened; it cannot say what was refused,
62
+ * and one label over every class is the same defect as one exit code
63
+ * over every outcome. See REFUSAL_PREFIX below.
64
+ */
65
+
66
+ import { execFileSync } from "child_process";
67
+ import { chmodSync, existsSync, lstatSync, readFileSync, writeFileSync } from "fs";
68
+ import { dirname, isAbsolute, join } from "path";
69
+ import { fileURLToPath } from "url";
70
+
71
+ /** The one exit code every refusal travels through. See note 1 above. */
72
+ export const REFUSE_EXIT = 1;
73
+
74
+ /**
75
+ * What a refusal is ABOUT. See note 3 above.
76
+ *
77
+ * Before #613 every refusal in this file was printed under the staleness
78
+ * label, including the three `parseArgs` raises — so `--harness` instead of
79
+ * `--generator` reported the installed hook as stale on a checkout whose hook
80
+ * was current, and the remedy the label implies is `--install`, which replaces
81
+ * a hook that was fine. Three more classes were collapsed the same way and two
82
+ * of them are worse than the typo:
83
+ *
84
+ * - the GENERATOR failing to load or run is the INSTRUMENT, not the subject.
85
+ * "The installed hook differs from the generator" is a measurement; "the
86
+ * generator could not be run" is the ABSENCE of one, and reporting an
87
+ * absent measurement as the stalest available verdict is
88
+ * `.claude/rules/config-access.md`'s UNMEASURED distinction with the sign
89
+ * flipped.
90
+ * - `installHook` failing reports STALENESS in `--install` mode, so the
91
+ * remedy the message names is the command that just failed.
92
+ *
93
+ * `0`, `{}`, `null` and silence are indistinguishable from success. One label
94
+ * over four classes is the same defect one level up: the reader cannot tell an
95
+ * argument error from a measured failure from a reading that was never taken.
96
+ */
97
+ export type RefusalClass = "ARGUMENTS" | "UNMEASURED" | "STALE" | "INSTALL";
98
+
99
+ /**
100
+ * The one place a refusal label is written. Each literal appears exactly once
101
+ * in this file — asserted by the test, because a second copy at a print site
102
+ * would survive any mutation of this table and both would read as covered
103
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
104
+ */
105
+ export const REFUSAL_PREFIX: Record<RefusalClass, string> = {
106
+ ARGUMENTS: "ARGUMENT ERROR",
107
+ UNMEASURED: "HOOK CURRENCY UNMEASURED",
108
+ STALE: "INSTALLED HOOK STALE",
109
+ INSTALL: "HOOK INSTALL REFUSED",
110
+ };
111
+
112
+ export class HookRefused extends Error {
113
+ readonly refusalClass: RefusalClass;
114
+ constructor(refusalClass: RefusalClass, message: string) {
115
+ super(message);
116
+ this.name = "HookRefused";
117
+ this.refusalClass = refusalClass;
118
+ }
119
+ }
120
+
121
+ /**
122
+ * The fixes an installed hook can predate, each named by the issue that
123
+ * landed it and probed by a fragment of the generator's own output.
124
+ *
125
+ * Every probe is asserted present in the generated hook before any comparison
126
+ * is made. Without that, a generator rewrite would silently empty this table
127
+ * and the refusal would stop being able to say anything — the table would
128
+ * become a check that cannot fail, inside a script about checks that cannot
129
+ * fail.
130
+ */
131
+ export interface GuardProperty {
132
+ name: string;
133
+ probe: string;
134
+ }
135
+
136
+ export const GUARD_PROPERTIES: GuardProperty[] = [
137
+ {
138
+ name: "the linked-worktree guard (#450)",
139
+ probe: "--git-common-dir",
140
+ },
141
+ {
142
+ name: "the updater resolution (#599)",
143
+ probe: "project-state: UNMEASURED",
144
+ },
145
+ {
146
+ name: "the decline on stderr (#599)",
147
+ probe: "are DA-owned (#296); update them from the primary checkout.\" >&2",
148
+ },
149
+ {
150
+ // #610. Deliberately NOT either baked path: the generator emits
151
+ // `scripts/update-project-state.ts` for the harness and
152
+ // `node_modules/rungate/scripts/…` for a consumer, so a probe naming
153
+ // either one reports every tree of the other kind as predating a fix it
154
+ // carries. This marker is in every form the generator emits, including
155
+ // the UNMEASURED one.
156
+ name: "the generation-time updater resolution (#610)",
157
+ probe: "Which updater runs was decided when this hook was generated (#610)",
158
+ },
159
+ ];
160
+
161
+ /**
162
+ * The guard properties of the generated `pre-push` (#891).
163
+ *
164
+ * Same discipline as the table above and the same instrument check: every
165
+ * probe must be present in the generator's own output, or the run is
166
+ * UNMEASURED rather than a pile of refusals naming a fix the hook carries.
167
+ */
168
+ export const PRE_PUSH_GUARD_PROPERTIES: GuardProperty[] = [
169
+ {
170
+ // The whole of #869's symptom. `--show-toplevel` answers "where is this
171
+ // working tree", and in a linked worktree that is not where
172
+ // `node_modules` lives, so every worktree push was refused as UNMEASURED
173
+ // over a repository whose dependencies were installed the whole time.
174
+ name: "the main-checkout modules root (#728)",
175
+ // The ASSIGNMENT, not the flag. `--git-common-dir` on its own also
176
+ // appears in the comment above that line explaining why it is there, so
177
+ // a probe naming the flag reports a genuinely pre-#728 hook as carrying
178
+ // the fix — a detector that cannot tell code from the prose about it
179
+ // (#235). Caught by AC-3, which plants the real pre-#728 hook and
180
+ // expects to be told which fix it predates.
181
+ probe: "$(git rev-parse --git-common-dir)/..",
182
+ },
183
+ {
184
+ // `ln -s` does not look at its target, so a link to a path that does not
185
+ // exist succeeds and the suite then dies on an import error naming no
186
+ // cause. This is the refusal that says which it was.
187
+ name: "the absent-modules refusal (#728)",
188
+ probe: "run bun install there",
189
+ },
190
+ {
191
+ // Three outcomes, not two: conformity FAILED, conformity could not be
192
+ // RUN, and conformity passed. The first two used to share a message
193
+ // (#397), so an install that could not happen was reported as a test
194
+ // that did not pass.
195
+ name: "the three-outcome reading (#397)",
196
+ probe: "unmeasured=1",
197
+ },
198
+ ];
199
+
200
+ /**
201
+ * What this checker knows about a hook, BEYOND comparing its bytes (#891).
202
+ *
203
+ * Keyed by the name in `GENERATED_HOOKS`, and deliberately not part of that
204
+ * declaration. A generator that declared the probes for its own output would
205
+ * satisfy them by construction, which is #530 — an artifact agreeing with
206
+ * whatever you put in it. These are assertions ABOUT the generator, so they
207
+ * live with the thing doing the asserting.
208
+ *
209
+ * **A hook with no entry here is still compared, byte for byte, and still
210
+ * reported.** That is the point: the population comes from the generator and
211
+ * the projections come from here, so a hook this checker has never heard of
212
+ * gets the weaker verdict rather than no verdict. AC-5 is the case.
213
+ */
214
+ export interface HookProjection {
215
+ properties: GuardProperty[];
216
+ /** Does this hook embed the secret registry? Only `pre-commit` does. */
217
+ carriesSecretScanner: boolean;
218
+ }
219
+
220
+ export const HOOK_PROJECTIONS: Record<string, HookProjection> = {
221
+ "pre-commit": { properties: GUARD_PROPERTIES, carriesSecretScanner: true },
222
+ "pre-push": { properties: PRE_PUSH_GUARD_PROPERTIES, carriesSecretScanner: false },
223
+ };
224
+
225
+ export function projectionFor(hookName: string): HookProjection {
226
+ return HOOK_PROJECTIONS[hookName] ?? { properties: [], carriesSecretScanner: false };
227
+ }
228
+
229
+ /**
230
+ * Where the hook that will actually run lives.
231
+ *
232
+ * `rev-parse --git-path hooks`, which is GIT's answer to this question rather
233
+ * than a reconstruction of it. Two things make the reconstruction wrong, and
234
+ * only the first was ever handled here:
235
+ *
236
+ * - In a linked worktree `--git-dir` is `.git/worktrees/<name>`, which has no
237
+ * `hooks/` and never will, so a check joining `<project>/.git/hooks` would
238
+ * report "not installed" from every worktree in the repository — exactly
239
+ * where an agent runs it. `--git-path hooks` answers with the SHARED
240
+ * `.git/hooks`, because git treats `hooks` as a common path; measured on
241
+ * a real linked worktree, and asserted by AC-6 in the test.
242
+ * - `core.hooksPath` redirects git wholesale (#874). With it set,
243
+ * `<common-dir>/hooks/pre-commit` is an ordinary untracked file that
244
+ * nothing executes, and a verdict taken there is a verdict about a program
245
+ * that will never run. Measured 2026-10-21 against the previous version of
246
+ * this function: a repository whose hooksPath held `exit 0` and whose
247
+ * `.git/hooks/pre-commit` held the current generator output printed
248
+ * `pre-commit is current` and exited 0.
249
+ *
250
+ * Reading `core.hooksPath` here instead would be a SECOND decider for a
251
+ * question git already answers, and it would have to re-implement git's own
252
+ * resolution rules. Those rules are not obvious: a relative value is resolved
253
+ * against the directory the hook runs from, so `core.hooksPath = relhooks`
254
+ * means a DIFFERENT directory in each linked worktree. `--git-path` reproduces
255
+ * that for free — it answered `relhooks` from the toplevel and `../relhooks`
256
+ * from a subdirectory of the same repository — which is why a relative answer
257
+ * is resolved against the directory git was asked from, and not against the
258
+ * worktree toplevel.
259
+ */
260
+ export function installedHookPath(projectRoot: string, hookName: string): string {
261
+ let hooks = "";
262
+ try {
263
+ hooks = execFileSync("git", ["-C", projectRoot, "rev-parse", "--git-path", "hooks"], {
264
+ encoding: "utf-8",
265
+ stdio: ["pipe", "pipe", "pipe"],
266
+ timeout: 30_000,
267
+ }).trim();
268
+ } catch (e) {
269
+ throw new HookRefused(
270
+ "UNMEASURED",
271
+ `${projectRoot} is not a git checkout, so it has no installed hook to read: ${firstLine(e)}`,
272
+ );
273
+ }
274
+ if (!hooks) {
275
+ throw new HookRefused("UNMEASURED", `git reported no hooks directory for ${projectRoot}`);
276
+ }
277
+ return join(isAbsolute(hooks) ? hooks : join(projectRoot, hooks), hookName);
278
+ }
279
+
280
+ /**
281
+ * One registry expression, as the refusal names it (#874).
282
+ *
283
+ * Structurally identical to `EMBEDDED_PATTERNS` in `lib/secret-patterns.ts`,
284
+ * declared here only because this script may not import it — see note 2 in
285
+ * the header. The LIST is never rebuilt: it is read out of the registry
286
+ * module at the path `--generator` names, so there is one declaration of what
287
+ * the hook's scanner consists of and this file holds a type, not a copy.
288
+ */
289
+ export interface RegistryPattern {
290
+ id: string;
291
+ ere: string;
292
+ }
293
+
294
+ export interface GeneratorOutput {
295
+ /** The hook's file name, from the generator's own declaration (#891). */
296
+ name: string;
297
+ content: string;
298
+ marker: string;
299
+ /** Empty for a hook that does not embed the secret registry. */
300
+ patterns: RegistryPattern[];
301
+ /** The probes this checker knows for this hook; empty for one it does not. */
302
+ properties: GuardProperty[];
303
+ }
304
+
305
+ /**
306
+ * The registry expressions the generated hook does NOT carry.
307
+ *
308
+ * The instrument check for `missingPatternIds` below. A registry entry the
309
+ * generator never interpolates would be reported missing from every installed
310
+ * hook on every run — a refusal that names the wrong thing always, which is
311
+ * the stale-probe failure `GUARD_PROPERTIES` is guarded against one table up.
312
+ * Separate exported function so it can be driven with a synthetic list, which
313
+ * is the only way to reach it without editing the real registry.
314
+ */
315
+ export function patternsBlindToGenerator(
316
+ generated: string,
317
+ patterns: RegistryPattern[],
318
+ ): string[] {
319
+ return patterns.filter(p => !generated.includes(p.ere)).map(p => p.id);
320
+ }
321
+
322
+ /**
323
+ * Which of the registry's expressions the installed hook is missing, by name
324
+ * (#874).
325
+ *
326
+ * The byte-exact comparison below already catches a hook whose scanner has
327
+ * drifted. What it could not do is SAY SO: on 2026-10-21 the hook installed in
328
+ * this repository was missing tier 1's `jwt` and the whole of tiers 2 and 3,
329
+ * and the refusal reported that it "predates the generation-time updater
330
+ * resolution (#610)" — true, and the least consequential of the differences.
331
+ *
332
+ * Derived from the registry at runtime rather than from a table here. A
333
+ * hand-written list naming `jwt` is the cheap repair and it is wrong: the
334
+ * tenth pattern is invisible again, and the table and the registry become two
335
+ * deciders that agree until one of them is edited.
336
+ */
337
+ export function missingPatternIds(installed: string, patterns: RegistryPattern[]): string[] {
338
+ return patterns.filter(p => !installed.includes(p.ere)).map(p => p.id);
339
+ }
340
+
341
+ /**
342
+ * What `createGitHooks` writes today, obtained by RUNNING it into a scratch
343
+ * directory rather than by re-deriving the template here.
344
+ *
345
+ * A second copy of the hook text in this file would be a second decider that
346
+ * always agrees with the first: the comparison would pass while the generator
347
+ * drifted, and no mutation of either could tell them apart.
348
+ */
349
+ export async function generatorHooks(
350
+ generatorRoot: string,
351
+ projectRoot: string,
352
+ ): Promise<GeneratorOutput[]> {
353
+ const modulePath = join(generatorRoot, "lib", "scaffold", "steps.ts");
354
+ let mod: any;
355
+ try {
356
+ mod = await import(modulePath);
357
+ } catch (e) {
358
+ throw new HookRefused(
359
+ "UNMEASURED",
360
+ `could not load the hook generator at ${modulePath}: ${firstLine(e)}. ` +
361
+ `Pass --generator <rungate checkout> if this project is not the harness.`,
362
+ );
363
+ }
364
+
365
+ // THE population, read from the generator (#891). A list here instead
366
+ // would be a second decider for "which hooks does the scaffold install",
367
+ // and it would agree with the generator right up until somebody added a
368
+ // hook — which is exactly how `pre-push` went unchecked from #397 to #891.
369
+ const declared = mod.GENERATED_HOOKS;
370
+ if (!Array.isArray(declared) || declared.length === 0) {
371
+ throw new HookRefused(
372
+ "UNMEASURED",
373
+ `${modulePath} does not export a non-empty GENERATED_HOOKS, so there is no declaration ` +
374
+ `of which hooks the scaffold installs and nothing here can say what should have been ` +
375
+ `compared. An empty population is not a clean tree.`,
376
+ );
377
+ }
378
+
379
+ // #874, hoisted out of the per-hook loop: the registry is one module and
380
+ // the projection that reads it is one hook's, so loading it once and
381
+ // asking `carriesSecretScanner` keeps a single declaration of both.
382
+ const registryPath = join(generatorRoot, "lib", "secret-patterns.ts");
383
+ let registry: any;
384
+ try {
385
+ registry = await import(registryPath);
386
+ } catch (e) {
387
+ throw new HookRefused(
388
+ "UNMEASURED",
389
+ `could not load the secret registry at ${registryPath}: ${firstLine(e)}. Without it ` +
390
+ `nothing here can say WHICH patterns an installed hook is missing.`,
391
+ );
392
+ }
393
+ const allPatterns = registry.EMBEDDED_PATTERNS;
394
+ if (!Array.isArray(allPatterns) || allPatterns.length === 0) {
395
+ throw new HookRefused(
396
+ "UNMEASURED",
397
+ `${registryPath} does not export a non-empty EMBEDDED_PATTERNS, so the scanner the hook ` +
398
+ `is supposed to carry has no declaration to be compared against`,
399
+ );
400
+ }
401
+
402
+ const out: GeneratorOutput[] = [];
403
+ for (const hook of declared) {
404
+ const name = hook?.name;
405
+ if (typeof name !== "string" || name.length === 0 || typeof hook.script !== "function") {
406
+ throw new HookRefused(
407
+ "UNMEASURED",
408
+ `${modulePath} declares a hook with no name or no script function, so one of the ` +
409
+ `things the scaffold installs cannot be compared`,
410
+ );
411
+ }
412
+ let content: string;
413
+ try {
414
+ // Generated FOR THE PROJECT, and written nowhere (#610). The pre-commit
415
+ // hook names one updater, chosen from what the project declares itself
416
+ // to be — so a scratch directory would produce the hook for an empty
417
+ // consumer and report every real checkout as stale. And a generator
418
+ // that could only answer by installing itself would make this check the
419
+ // thing it is checking, over a `.git/hooks/` shared by every linked
420
+ // worktree of the repository at once.
421
+ content = hook.script(projectRoot);
422
+ } catch (e) {
423
+ throw new HookRefused(
424
+ "UNMEASURED",
425
+ `the ${name} generator threw for ${projectRoot}: ${firstLine(e)}`,
426
+ );
427
+ }
428
+ const marker = hook.marker;
429
+ if (typeof marker !== "string" || marker.length === 0 || !content.includes(marker)) {
430
+ throw new HookRefused(
431
+ "UNMEASURED",
432
+ `the generator's own ${name} output does not carry its declared managed marker, so no ` +
433
+ `installed ${name} could ever be recognised as managed`,
434
+ );
435
+ }
436
+
437
+ const projection = projectionFor(name);
438
+ const blind = projection.properties.filter(p => !content.includes(p.probe));
439
+ if (blind.length > 0) {
440
+ throw new HookRefused(
441
+ "UNMEASURED",
442
+ `the ${name} generator no longer contains ${blind.map(b => b.name).join(", ")}. The probe` +
443
+ `${blind.length > 1 ? "s" : ""} in HOOK_PROJECTIONS ha${blind.length > 1 ? "ve" : "s"} ` +
444
+ `gone stale, and a stale probe reports every installed hook as predating a fix it may ` +
445
+ `well carry. Update the table in the same change as the generator.`,
446
+ );
447
+ }
448
+
449
+ const patterns: RegistryPattern[] = projection.carriesSecretScanner ? allPatterns : [];
450
+ const unreachable = patternsBlindToGenerator(content, patterns);
451
+ if (unreachable.length > 0) {
452
+ throw new HookRefused(
453
+ "UNMEASURED",
454
+ `the ${name} generator does not interpolate ${unreachable.join(", ")} from the registry, ` +
455
+ `so every installed hook would be reported as missing ` +
456
+ `${unreachable.length > 1 ? "them" : "it"}. A probe the generator cannot satisfy names ` +
457
+ `the wrong thing on every run.`,
458
+ );
459
+ }
460
+ out.push({ name, content, marker, patterns, properties: projection.properties });
461
+ }
462
+ return out;
463
+ }
464
+
465
+ /**
466
+ * One hook's verdict: `null` when the installed copy IS the generator
467
+ * output, and a CLASSIFIED reason otherwise.
468
+ *
469
+ * One function, one binding to mutate. The CLI below does not re-ask any of
470
+ * these questions — a second guard answering the same question would survive
471
+ * any mutation of this one, and both would read as covered. That includes
472
+ * the CLASS: it is decided here, beside the reason it belongs to, and the
473
+ * CLI renders it (#613, #879).
474
+ *
475
+ * **Absent is not stale (#879).** A tree with no installed hook has not
476
+ * failed a comparison; it has not had one. A fresh clone and a CI checkout
477
+ * are both in that state as a matter of course, and a session-start reading
478
+ * that calls them STALE is a refusal everybody learns to ignore. The same
479
+ * goes for a hand-written hook, whose own message says in as many words that
480
+ * nothing here can tell you what it enforces — that is the definition of
481
+ * unmeasured. What is STALE is narrower and exact: a hook carrying the
482
+ * managed marker that is not what the generator emits.
483
+ */
484
+ export interface HookVerdict {
485
+ cls: RefusalClass;
486
+ reason: string;
487
+ }
488
+ export function currencyRefusal(
489
+ installed: string | null,
490
+ generated: string,
491
+ marker: string,
492
+ path: string,
493
+ patterns: RegistryPattern[],
494
+ // No defaults (#891). A default of `"pre-commit"` here is a second
495
+ // statement about which hooks exist, in the one function that must not
496
+ // hold one — and it is the exact form the cheapest wrong fix takes.
497
+ hookName: string,
498
+ properties: GuardProperty[],
499
+ ): HookVerdict | null {
500
+ if (installed === null) {
501
+ return {
502
+ cls: "UNMEASURED",
503
+ reason:
504
+ `no ${hookName} hook is installed at ${path}, so nothing was compared. The generator is ` +
505
+ `not the thing that runs on your commits; the file is. Re-run ` +
506
+ `\`bun bin/rungate.ts scaffold .\`, or this script with --install.`,
507
+ };
508
+ }
509
+ if (!installed.includes(marker)) {
510
+ return {
511
+ cls: "UNMEASURED",
512
+ reason:
513
+ `the hook installed at ${path} is hand-written — it does not carry the rungate managed ` +
514
+ `marker, so it is not compared and not replaced. Nothing here can tell you whether it ` +
515
+ `enforces the DA-owned state rule. Move it aside and re-run with --install if you want ` +
516
+ `the generated one.`,
517
+ };
518
+ }
519
+ if (installed === generated) return null;
520
+
521
+ const missing = properties.filter(p => !installed.includes(p.probe));
522
+ const how = `Re-run this script with --install, or \`bun bin/rungate.ts scaffold .\`.`;
523
+
524
+ // The scanner first, and on its own sentence. A hook that predates a fix to
525
+ // the PROJECT-STATE arm stages the wrong file; a hook whose scanner is short
526
+ // a pattern commits the credential. Both are differences, and reporting only
527
+ // the one the GUARD_PROPERTIES table happens to name is how the live hook
528
+ // here was described as predating #610 while silently missing `jwt` and the
529
+ // whole of tiers 2 and 3 (#874).
530
+ const absent = missingPatternIds(installed, patterns);
531
+ const scanner =
532
+ absent.length > 0
533
+ ? `Its secret scanner is missing ${absent.length} of the ${patterns.length} expressions ` +
534
+ `lib/secret-patterns.ts declares: ${absent.join(", ")}. A commit from this checkout is ` +
535
+ `not scanned for ${absent.length > 1 ? "those" : "that"}. `
536
+ : "";
537
+
538
+ if (missing.length > 0) {
539
+ return {
540
+ cls: "STALE",
541
+ reason:
542
+ `the hook installed at ${path} predates ${missing.map(m => m.name).join(", ")}. ` +
543
+ // "Every commit" was right while this script only ever read one hook,
544
+ // and became wrong the moment it read two (#891): a pre-push refusal
545
+ // that talks about commits is a message an operator has to translate
546
+ // before acting on it.
547
+ `${scanner}Every ${hookName} from this checkout is running the old behaviour, whatever ` +
548
+ `the generator says. ${how}`,
549
+ };
550
+ }
551
+ if (absent.length > 0) {
552
+ return {
553
+ cls: "STALE",
554
+ reason:
555
+ `the hook installed at ${path} carries every named guard and is not byte-identical to ` +
556
+ `the generator's output. ${scanner}${how}`,
557
+ };
558
+ }
559
+ return {
560
+ cls: "STALE",
561
+ reason:
562
+ `the hook installed at ${path} carries every named guard and every registry pattern but ` +
563
+ `is not byte-identical to the generator's output, so something edited it or it predates ` +
564
+ `a change this table does not name. ${how}`,
565
+ };
566
+ }
567
+
568
+ /**
569
+ * Write the generator output to the installed path.
570
+ *
571
+ * Refuses a symlink rather than following one — BUG-440-A's shape. A
572
+ * `pre-commit` symlinked at a path outside the repository would otherwise be
573
+ * overwritten with the hook, outside the project, reported as a success.
574
+ */
575
+ export function installHook(path: string, content: string): void {
576
+ let link: ReturnType<typeof lstatSync> | null = null;
577
+ try {
578
+ link = lstatSync(path);
579
+ } catch {
580
+ link = null;
581
+ }
582
+ if (link?.isSymbolicLink()) {
583
+ throw new HookRefused(
584
+ "INSTALL",
585
+ `${path} is a symlink, and the hook is not written through one — the target may be ` +
586
+ `outside this repository. Replace it with a real file, or delete it and re-run.`,
587
+ );
588
+ }
589
+ if (link && !link.isFile()) {
590
+ throw new HookRefused(
591
+ "INSTALL",
592
+ `${path} exists but is not a regular file, so it will not be replaced.`,
593
+ );
594
+ }
595
+ // Refused, not created (#874). Since `core.hooksPath` decides this
596
+ // directory, it can be anywhere on disk and a `mkdir -p` here would create
597
+ // a tree outside the repository on the strength of one config value. The
598
+ // honest reading is that git is pointed at a directory that does not exist,
599
+ // which is a thing to say rather than to repair. Without this the ENOENT
600
+ // escapes as an unclassified string and the refusal carries no label at
601
+ // all, which is #613.
602
+ const dir = dirname(path);
603
+ if (!existsSync(dir)) {
604
+ throw new HookRefused(
605
+ "INSTALL",
606
+ `${dir} does not exist, so the hook was not written. git is pointed at it by ` +
607
+ `core.hooksPath; create it, or clear the setting, and re-run.`,
608
+ );
609
+ }
610
+ // The same refusal as the leaf, one level up. Refusing a symlinked
611
+ // `pre-commit` because "the target may be outside this repository" and then
612
+ // writing happily into a symlinked `hooks/` is a policy with a hole in it
613
+ // the exact width of one directory — and since #874 the directory is chosen
614
+ // by `core.hooksPath`, so it is the half an operator is least likely to
615
+ // have looked at.
616
+ //
617
+ // Deliberately NOT a containment check against the worktree. A hooks
618
+ // directory outside the repository is the ordinary way a team shares hooks
619
+ // (`git config core.hooksPath ~/.githooks`), and refusing to install there
620
+ // is the M2 wrong fix in a different costume: a correct configuration
621
+ // turned into a refusal, which is how a check becomes one people switch
622
+ // off. What is refused here is the write whose destination the path does
623
+ // not state.
624
+ let dirLink: ReturnType<typeof lstatSync> | null = null;
625
+ try {
626
+ dirLink = lstatSync(dir);
627
+ } catch {
628
+ dirLink = null;
629
+ }
630
+ if (dirLink?.isSymbolicLink()) {
631
+ throw new HookRefused(
632
+ "INSTALL",
633
+ `${dir} is a symlink, and the hook is not written through one — the directory it resolves ` +
634
+ `to may be nowhere near this repository. Point core.hooksPath at the real directory, or ` +
635
+ `replace the link, and re-run.`,
636
+ );
637
+ }
638
+ writeFileSync(path, content);
639
+ chmodSync(path, 0o755);
640
+ }
641
+
642
+ function firstLine(e: unknown): string {
643
+ const msg = e instanceof Error ? e.message : String(e);
644
+ return msg.split("\n")[0];
645
+ }
646
+
647
+ const VALUE_OPTIONS = new Set(["project", "generator"]);
648
+ const FLAG_OPTIONS = new Set(["install"]);
649
+
650
+ export function parseArgs(argv: string[]): Record<string, string | boolean> {
651
+ const out: Record<string, string | boolean> = {};
652
+ for (let i = 0; i < argv.length; i++) {
653
+ const arg = argv[i];
654
+ const m = /^--([A-Za-z][A-Za-z-]*)$/.exec(arg);
655
+ if (!m) {
656
+ throw new HookRefused(
657
+ "ARGUMENTS",
658
+ `unexpected argument "${arg.slice(0, 80)}" — every input is a --flag, with a value where one is needed`,
659
+ );
660
+ }
661
+ if (FLAG_OPTIONS.has(m[1])) {
662
+ out[m[1]] = true;
663
+ continue;
664
+ }
665
+ if (!VALUE_OPTIONS.has(m[1])) {
666
+ throw new HookRefused("ARGUMENTS", `unknown option --${m[1]}`);
667
+ }
668
+ const value = argv[++i];
669
+ if (value === undefined || value.startsWith("--")) {
670
+ throw new HookRefused("ARGUMENTS", `--${m[1]} needs a value`);
671
+ }
672
+ out[m[1]] = value;
673
+ }
674
+ return out;
675
+ }
676
+
677
+ /** This script's own repository, used when --generator is not given. */
678
+ export function defaultGeneratorRoot(): string {
679
+ return join(fileURLToPath(new URL(".", import.meta.url)), "..");
680
+ }
681
+
682
+ function readIfPresent(path: string): string | null {
683
+ try {
684
+ const link = lstatSync(path);
685
+ if (link.isSymbolicLink()) {
686
+ throw new HookRefused(
687
+ "UNMEASURED",
688
+ `${path} is a symlink. The hook that runs is the link's target, which may be outside ` +
689
+ `this repository, so this check will not follow it. Replace it with a real file.`,
690
+ );
691
+ }
692
+ if (!link.isFile()) {
693
+ throw new HookRefused("UNMEASURED", `${path} exists but is not a regular file`);
694
+ }
695
+ return readFileSync(path, "utf-8");
696
+ } catch (e) {
697
+ if (e instanceof HookRefused) throw e;
698
+ return null;
699
+ }
700
+ }
701
+
702
+ /**
703
+ * One reading of every hook the generator declares, taken without deciding
704
+ * what to do about it (#879).
705
+ *
706
+ * The CLI raises on it and the SessionStart hook prints it. Both had to
707
+ * exist, and the loop below is the ONE position that pairs a generated hook
708
+ * with the file installed at its address — a hook that walked the population
709
+ * itself would be a second decider about which hooks exist and what a
710
+ * current one is called, agreeing with this one until the day it did not.
711
+ */
712
+ export interface CurrencyReading {
713
+ current: string[];
714
+ refusals: HookVerdict[];
715
+ }
716
+
717
+ export async function readHookCurrency(
718
+ project: string,
719
+ generatorRoot: string,
720
+ ): Promise<CurrencyReading> {
721
+ const hooks = await generatorHooks(generatorRoot, project);
722
+
723
+ // Every hook is read before any verdict is raised, so a stale FIRST hook
724
+ // cannot hide the state of the ones after it. The old shape could not have
725
+ // this problem because it only ever looked at one file, which is the
726
+ // problem (#891).
727
+ const current: string[] = [];
728
+ const refusals: HookVerdict[] = [];
729
+ for (const hook of hooks) {
730
+ const path = installedHookPath(project, hook.name);
731
+ // One decider, asked once per hook. The verdict is RETURNED rather than
732
+ // printed or raised here (#613), so there is exactly one position in
733
+ // this file that turns a refusal into a line of output and exactly one
734
+ // that turns it into an exit code.
735
+ const refusal = currencyRefusal(
736
+ readIfPresent(path),
737
+ hook.content,
738
+ hook.marker,
739
+ path,
740
+ hook.patterns,
741
+ hook.name,
742
+ hook.properties,
743
+ );
744
+ if (refusal) refusals.push(refusal);
745
+ else current.push(`${hook.name} is current at ${path}`);
746
+ }
747
+ return { current, refusals };
748
+ }
749
+
750
+ /**
751
+ * The STRONGEST class present, or `null` when every hook is current.
752
+ *
753
+ * A tree with one stale hook and one absent one HAS a stale hook, and
754
+ * reporting the pair as UNMEASURED would hide it; reporting a tree whose
755
+ * hooks are merely absent as STALE is the error #879 is about, in the other
756
+ * direction. One binding, because the CLI and the hook both need the answer
757
+ * and two copies of this comparison would agree right up until they did not.
758
+ */
759
+ export function currencyClass(refusals: HookVerdict[]): RefusalClass | null {
760
+ if (refusals.some(v => v.cls === "STALE")) return "STALE";
761
+ return refusals.length > 0 ? "UNMEASURED" : null;
762
+ }
763
+
764
+ /** Each line keeps its own WORDS; the class prefix is rendered once, by the
765
+ * caller that reports (#613). */
766
+ export function currencyLines(refusals: HookVerdict[]): string {
767
+ return refusals.map(v => v.reason).join("\n ");
768
+ }
769
+
770
+ // CLI entry point. Guarded so the module can be imported by tests without
771
+ // running the check and calling process.exit.
772
+ if (import.meta.main) {
773
+ try {
774
+ const args = parseArgs(process.argv.slice(2));
775
+ const project = typeof args.project === "string" ? args.project : process.cwd();
776
+ const generatorRoot = typeof args.generator === "string" ? args.generator : defaultGeneratorRoot();
777
+
778
+ // An explicit zero exit is deliberately absent from both arms: success
779
+ // falls off the end, so the "every exit goes through REFUSE_EXIT" scan
780
+ // has no exception to carve out, and an exception is where a literal
781
+ // exit code hides. An early zero exit written here turned four cases
782
+ // red, which is the scan doing its job — and naming the call in this
783
+ // comment turned the same case red a second time, because the scan
784
+ // reads prose as code (#235).
785
+ if (args.install === true) {
786
+ for (const hook of await generatorHooks(generatorRoot, project)) {
787
+ const path = installedHookPath(project, hook.name);
788
+ installHook(path, hook.content);
789
+ console.log(`${hook.name} installed, and current, at ${path}`);
790
+ }
791
+ } else {
792
+ const { current, refusals } = await readHookCurrency(project, generatorRoot);
793
+ for (const line of current) console.log(line);
794
+
795
+ // One raise, after the whole population has been read. A throw inside the
796
+ // loop would make the report depend on declaration order, and an operator
797
+ // who fixed the first hook would discover the second only on the next run.
798
+ //
799
+ // Two raises, each naming its class as a LITERAL, over one call to the
800
+ // decider. Raising once with the class held in a variable was written
801
+ // first and is exactly what SC-2145 exists to refuse: a label that is
802
+ // not spelled at the raise cannot be read off the source, so "every
803
+ // class in REFUSAL_PREFIX is reachable" stops being a checkable claim
804
+ // about this file. The comparison itself is still in one place; these
805
+ // two arms only rename its answer.
806
+ //
807
+ // SC-2145 caught the first draft of this very comment, which quoted the
808
+ // rejected call verbatim and so read as a fourteenth raise naming no
809
+ // class. The probe cannot tell code from prose about code (#235), and
810
+ // the fix is to not write the call — not to teach the probe about
811
+ // comments.
812
+ const lines = currencyLines(refusals);
813
+ const cls = currencyClass(refusals);
814
+ if (cls === "STALE") throw new HookRefused("STALE", lines);
815
+ if (cls === "UNMEASURED") throw new HookRefused("UNMEASURED", lines);
816
+ }
817
+ } catch (e) {
818
+ // The class decides the label. `e.refusalClass` is set at the raise, by
819
+ // the code that knows what it refused; nothing here re-derives it from
820
+ // the message, because a second reading of the same fact is a second
821
+ // decider that always agrees.
822
+ console.error(e instanceof HookRefused ? `${REFUSAL_PREFIX[e.refusalClass]}: ${e.message}` : String(e));
823
+ process.exit(REFUSE_EXIT);
824
+ }
825
+ }