rungate 0.6.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 (164) 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 +427 -0
  36. package/lib/agent-audit.ts +2 -3
  37. package/lib/agent-worktree.ts +287 -0
  38. package/lib/agents-md-sections.ts +81 -16
  39. package/lib/bash-write-guard.ts +373 -0
  40. package/lib/behavioral-cache.ts +150 -2
  41. package/lib/branch-cleanup.ts +279 -7
  42. package/lib/branch-protection.ts +790 -0
  43. package/lib/brief-ac-alignment.ts +104 -0
  44. package/lib/brief-references.ts +205 -0
  45. package/lib/bun-version.ts +93 -14
  46. package/lib/check-remedy.ts +140 -0
  47. package/lib/ci-checkout.ts +17 -0
  48. package/lib/ci-history-depth.ts +159 -0
  49. package/lib/ci-setup-step.ts +96 -0
  50. package/lib/claude-code-action.ts +85 -0
  51. package/lib/claude-tool-vocabulary.ts +188 -0
  52. package/lib/cli-commands.ts +15 -0
  53. package/lib/commit-sha.ts +42 -0
  54. package/lib/commit-subject.ts +90 -0
  55. package/lib/compliance-report.ts +377 -45
  56. package/lib/compliance.ts +191 -17
  57. package/lib/config-loader.ts +39 -1
  58. package/lib/config-trackable.ts +400 -0
  59. package/lib/conformity.ts +1087 -100
  60. package/lib/containment.ts +238 -0
  61. package/lib/content-hash.ts +24 -0
  62. package/lib/create-sc.ts +249 -16
  63. package/lib/dev-liveness.ts +180 -0
  64. package/lib/discovery-branch-points.ts +432 -0
  65. package/lib/discovery-stability.ts +481 -0
  66. package/lib/distribution-currency.ts +236 -0
  67. package/lib/doc-routing.ts +157 -0
  68. package/lib/evidence-prevalidator.ts +224 -2
  69. package/lib/evidence-satisfiability.ts +534 -12
  70. package/lib/failure-intake.ts +323 -0
  71. package/lib/fallow-availability.ts +157 -0
  72. package/lib/fs-write-capabilities.ts +232 -0
  73. package/lib/gate-enforcement.ts +222 -28
  74. package/lib/gate-names.ts +72 -0
  75. package/lib/gate-result-protection.ts +427 -0
  76. package/lib/gate-run-split.ts +147 -0
  77. package/lib/generators/agents-md.ts +140 -32
  78. package/lib/git-isolation.ts +140 -0
  79. package/lib/github.ts +15 -0
  80. package/lib/google-auth-action.ts +93 -0
  81. package/lib/harness-project.ts +48 -0
  82. package/lib/harness-provenance.ts +255 -0
  83. package/lib/hook-evidence.ts +235 -0
  84. package/lib/hook-scopes.ts +386 -0
  85. package/lib/hook-target-tree.ts +398 -0
  86. package/lib/hook-trees.ts +447 -0
  87. package/lib/intake-sources.ts +380 -0
  88. package/lib/js-top-level-code.ts +78 -10
  89. package/lib/junit-checks.ts +52 -0
  90. package/lib/late-env-spawn.ts +331 -0
  91. package/lib/launch-base.ts +376 -0
  92. package/lib/line-citation.ts +372 -0
  93. package/lib/orphan-reaper.ts +468 -0
  94. package/lib/parity-binding.ts +205 -0
  95. package/lib/paths.ts +96 -3
  96. package/lib/per-test-timeouts.ts +219 -0
  97. package/lib/phase2-decomposition.ts +1 -1
  98. package/lib/plan-coverage.ts +151 -0
  99. package/lib/prior-branch.ts +201 -8
  100. package/lib/process-table.ts +146 -0
  101. package/lib/project-state-derivation.ts +219 -0
  102. package/lib/project-state-root.ts +258 -0
  103. package/lib/published-artifact.ts +669 -0
  104. package/lib/readdir-sorted.ts +45 -0
  105. package/lib/review-execution-reading.ts +206 -0
  106. package/lib/review-tool-agreement.ts +433 -0
  107. package/lib/rule-promotion.ts +234 -0
  108. package/lib/rule-retirement.ts +525 -0
  109. package/lib/run-branch.ts +612 -0
  110. package/lib/rungate-schema.ts +19 -0
  111. package/lib/runner-home.ts +274 -0
  112. package/lib/sc-id-cross-tree.ts +103 -15
  113. package/lib/sc-ids.ts +121 -13
  114. package/lib/sc-reservations.ts +289 -0
  115. package/lib/scaffold/ai-review-findings.ts +409 -0
  116. package/lib/scaffold/ai-review-step.ts +5406 -64
  117. package/lib/scaffold/defaults.ts +82 -1
  118. package/lib/scaffold/managed-workflow.ts +587 -192
  119. package/lib/scaffold/owned-files.ts +152 -45
  120. package/lib/scaffold/pre-push-hook.ts +49 -5
  121. package/lib/scaffold/steps.ts +1836 -275
  122. package/lib/scaffold/workflow-census.ts +217 -0
  123. package/lib/scaffold/workflow-drift.ts +217 -0
  124. package/lib/scaffold/write-steps.ts +4 -0
  125. package/lib/scan-budget.ts +247 -0
  126. package/lib/scanner.ts +43 -51
  127. package/lib/scratch-roots.ts +50 -5
  128. package/lib/screenshot-discovery.ts +121 -0
  129. package/lib/screenshot-upload.ts +41 -1
  130. package/lib/secret-patterns.ts +511 -8
  131. package/lib/security-verdict.ts +1 -1
  132. package/lib/shell-path-interpolation.ts +594 -0
  133. package/lib/ship-mode.ts +219 -0
  134. package/lib/source-slice.ts +294 -0
  135. package/lib/stale-cleanup.ts +37 -3
  136. package/lib/suite-flake.ts +278 -0
  137. package/lib/suite-measurement.ts +23 -4
  138. package/lib/suite-run-reading.ts +241 -1
  139. package/lib/suite-timeout-margin.ts +193 -0
  140. package/lib/test-case-bodies.ts +883 -0
  141. package/lib/test-case-deletion.ts +653 -0
  142. package/lib/test-census.ts +97 -29
  143. package/lib/test-command-positions.ts +274 -0
  144. package/lib/test-suite-lock.ts +159 -16
  145. package/lib/text-dependents.ts +875 -0
  146. package/lib/tool-probe.ts +31 -9
  147. package/lib/top-level-cd.ts +393 -0
  148. package/lib/tree-entries.ts +89 -0
  149. package/lib/ts-ast.ts +200 -0
  150. package/lib/walk-test-files.ts +97 -0
  151. package/lib/workflow-actions.ts +263 -0
  152. package/lib/workflow-security.ts +29 -0
  153. package/lib/workflow-taint.ts +732 -0
  154. package/lib/worktree-cleanup.ts +65 -38
  155. package/lib/worktree-collect.ts +177 -5
  156. package/lib/worktree-repo.ts +68 -3
  157. package/package.json +4 -1
  158. package/scripts/ai-review-findings.ts +45 -0
  159. package/scripts/check-installed-hook-currency.ts +825 -0
  160. package/scripts/create-sc.ts +21 -1
  161. package/scripts/extract-constraints.ts +107 -7
  162. package/scripts/generate-code-map.ts +23 -30
  163. package/scripts/scaffold-project.ts +8 -1
  164. package/scripts/sync-sc-status.ts +77 -16
@@ -8,6 +8,42 @@ export interface UploadResult {
8
8
  markdownLinks: string[];
9
9
  }
10
10
 
11
+ /**
12
+ * Creates one gist and returns whatever the command printed.
13
+ *
14
+ * The return is deliberately the RAW stdout rather than a parsed URL: the
15
+ * caller's job is to decide whether what came back is a gist URL at all, and
16
+ * a seam that pre-validates would hide the case where it is not.
17
+ */
18
+ export type GistCreator = (filePath: string) => Promise<string>;
19
+
20
+ /**
21
+ * The ONE place this module reaches the network (#806).
22
+ *
23
+ * It is a seam because there was none, and the cost of there being none is
24
+ * measured rather than argued: three cases in
25
+ * `test/screenshot-upload.test.ts` handed a real file to the function below,
26
+ * so every `bun test` run published four PUBLIC gists to whoever ran it.
27
+ * 3,667 of them existed on the account when this was found, every gist on it,
28
+ * from 2026-09-30 to 2026-10-20 — and the same three cases were the red shard
29
+ * on `main`, timing out at bun's default 5000ms whenever GitHub was slow.
30
+ *
31
+ * A test must never need the network to find out what this function does with
32
+ * what the network says. One exported binding, so a test overrides it by
33
+ * passing it in and nothing has to mutate `PATH`, the environment, or the
34
+ * module.
35
+ */
36
+ export const createPublicGist: GistCreator = async (filePath: string) =>
37
+ await $`gh gist create --public ${filePath}`.text();
38
+
39
+ export interface UploadOpts {
40
+ /**
41
+ * Used instead of `createPublicGist`. Omitted in production; supplied by
42
+ * every test, which is what keeps the suite off the network.
43
+ */
44
+ createGist?: GistCreator;
45
+ }
46
+
11
47
  /**
12
48
  * Uploads screenshot files to GitHub via gists and returns markdown image links.
13
49
  *
@@ -17,13 +53,17 @@ export interface UploadResult {
17
53
  * @param issue - GitHub issue number (for future use in direct issue attachments)
18
54
  * @param repo - Repository in owner/repo format
19
55
  * @param screenshotPaths - Array of absolute paths to screenshot files
56
+ * @param opts - `createGist` overrides the network seam; omit it in production
20
57
  * @returns UploadResult with uploaded files, failed files, and markdown links
21
58
  */
22
59
  export async function uploadScreenshotsToIssue(
23
60
  issue: number,
24
61
  repo: string,
25
62
  screenshotPaths: string[],
63
+ opts?: UploadOpts,
26
64
  ): Promise<UploadResult> {
65
+ const createGist = opts?.createGist ?? createPublicGist;
66
+
27
67
  const result: UploadResult = {
28
68
  uploaded: [],
29
69
  failed: [],
@@ -44,7 +84,7 @@ export async function uploadScreenshotsToIssue(
44
84
  try {
45
85
  // Upload to GitHub gist
46
86
  // gh gist create returns the gist URL on stdout
47
- const gistResult = await $`gh gist create --public ${filePath}`.text();
87
+ const gistResult = await createGist(filePath);
48
88
  const gistUrl = gistResult.trim();
49
89
 
50
90
  if (!gistUrl || !gistUrl.startsWith("https://gist.github.com/")) {
@@ -37,6 +37,30 @@ export interface SecretPattern {
37
37
  description: string;
38
38
  }
39
39
 
40
+ /*
41
+ * There was a `hookProbe?: string` here for one commit, and the second
42
+ * security review of #868 was right that it should not exist.
43
+ *
44
+ * The parity guard used to grep the hook for a PREFIX of each ERE, derived by
45
+ * cutting at the first metacharacter. That derivation yields `eyJ` for `jwt`
46
+ * and `sk-` for `openai` — three characters each — and the guard skipped
47
+ * anything under four, which is how the hook went its whole life missing
48
+ * `jwt` entirely and carrying `{48}` where this registry says `{20,}`. The
49
+ * first repair made a short derivation demand an explicit probe rather than
50
+ * waive the check.
51
+ *
52
+ * That was still the weaker design, for a reason the review named: a probe is
53
+ * a DECLARATION, and nothing checked it was even a substring of its own ERE.
54
+ * A prefix also cannot see a hook that carries the right prefix and the wrong
55
+ * quantifier, which is precisely the `{48}` defect.
56
+ *
57
+ * The guard now greps the hook for each pattern's ENTIRE ere. Measured: all
58
+ * nine are already present verbatim in `scripts/git-hooks/pre-commit`, modulo
59
+ * `\-` for `-` inside a bracket expression, so the stronger check needed no
60
+ * per-pattern metadata at all. It catches both halves of the historical gap —
61
+ * a missing pattern and a narrowed one — with one assertion and no field.
62
+ */
63
+
40
64
  /**
41
65
  * Tier 1 — anchored key formats.
42
66
  *
@@ -54,6 +78,13 @@ export const TIER1_SECRET_PATTERNS: SecretPattern[] = [
54
78
  // shorter than 48 chars — a coverage regression smuggled in by a
55
79
  // deduplication. When registries disagree, the union is the safe merge, not
56
80
  // whichever copy you happened to start from.
81
+ // The hook carried `{48}` against this `{20,}` until #868, and the parity
82
+ // guard could not say so: `sk-` is the derived prefix and three characters
83
+ // long, so the guard skipped this entry for its whole life. A 30-character
84
+ // key committed cleanly and was caught in CI, which is the gap the skip was
85
+ // hiding in the OTHER direction from `jwt` — not a missing pattern, a
86
+ // narrowed one. A prefix probe could not have caught it either: `sk-` is in
87
+ // the hook under both quantifiers. Comparing the whole ERE can.
57
88
  { id: "openai", ere: "sk-[A-Za-z0-9]{20,}", description: "OpenAI-style API key" },
58
89
  { id: "anthropic", ere: "sk-ant-[A-Za-z0-9-]{90,}", description: "Anthropic API key" },
59
90
  {
@@ -61,15 +92,121 @@ export const TIER1_SECRET_PATTERNS: SecretPattern[] = [
61
92
  ere: "-----BEGIN (RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----",
62
93
  description: "PEM private key block",
63
94
  },
95
+ // #863. The one unquoted credential form that LOOKS like a dotted
96
+ // identifier path, which is the population `TIER2_DOTTED_PATH_ERE` below
97
+ // removes from tier 2. Tier 2 cannot tell the two apart — the shape IS the
98
+ // same — so the exclusion would launder a bearer token out of a `.env`.
99
+ //
100
+ // It belongs here and not there because a JWT is a FORMAT, not a shape:
101
+ // both the header and the payload are base64url of a JSON object, so both
102
+ // begin `eyJ`, and two anchored prefixes separated by a dot is not
103
+ // something ordinary source produces. That is what makes it safe in the
104
+ // tier with no allowlist.
105
+ //
106
+ // The signature segment is required. A two-segment `alg: none` token is
107
+ // not a credential, and matching two segments alone would catch
108
+ // `a.b`-shaped prose beginning with those three letters.
109
+ //
110
+ // THE SIGNATURE FLOOR IS 43 AND IT IS A FORMAT FACT, NOT A TUNING (#863)
111
+ //
112
+ // A JWS signature is a fixed-width base64url encoding of a fixed-width
113
+ // MAC or signature, so the shortest one any standard algorithm produces is
114
+ // HS256's 32 bytes — 43 base64url characters. ES256 is 86, RS256 342.
115
+ // There is no signed JWT below the floor, so nothing is given up by it.
116
+ //
117
+ // What it buys is the false-positive side, which tier 1 cannot absorb.
118
+ // Measured 2026-10-21 on one consumer tree: a `{10,}` signature reports
119
+ // two quoted browser-test fixtures whose third segment is an English
120
+ // phrase of 21 and 26 characters. Both are JWT-shaped and neither is a
121
+ // token, and tier 1 has no allowlist to excuse them — so that consumer's
122
+ // Gates job would have gone from red on two property references to red on
123
+ // two test fixtures, which is #863 reintroduced by its own fix. The tree
124
+ // and the lines are named in `test/unit/gates-tier1-jwt.test.ts`; a module
125
+ // under `lib/` may carry no consumer-specific value (SC-A1).
126
+ {
127
+ id: "jwt",
128
+ ere: "eyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{43,}",
129
+ description: "JSON Web Token (signed, three segments)",
130
+ },
64
131
  ];
65
132
 
66
133
  /**
67
134
  * Tier 2 — credential assignments.
68
135
  *
69
136
  * Shape-based rather than format-based, so it needs the allowlist below.
137
+ *
138
+ * THE FIRST VALUE CHARACTER MAY NOT BE `=` (#489)
139
+ *
140
+ * `=` is in the value charset because base64 pads with it. Minified
141
+ * JavaScript collapses whitespace, so `if (e.password === t.password) {...}`
142
+ * — which does NOT match, the space after `===` ends the value at two
143
+ * characters — comes out of a minifier with the spaces gone and then
144
+ * presented as `password` -> `=` -> `==t.password`, twelve characters all
145
+ * inside the charset, matched by nothing in the allowlist, and the generated
146
+ * job's branch is `exit 1` rather than a warning. Every consumer with
147
+ * committed minified build output hard-failed CI on a comparison.
148
+ *
149
+ * So the value is split: one leading character from the charset WITHOUT `=`,
150
+ * then eleven or more from the full charset. Twelve total, unchanged. Every
151
+ * `===`, `==` or `=>` comparison produces a value beginning with `=` and is
152
+ * now excluded; no real credential form this pattern can see begins with one
153
+ * — measured against the detectable control set, not assumed.
154
+ *
155
+ * This narrows the detector, which is the change most likely to buy green
156
+ * with blindness, so the boundary is a mutation battery in
157
+ * test/unit/secret-patterns.test.ts rather than this comment.
158
+ *
159
+ * ONE BLIND SPOT THAT IS NOT #489 AND MUST NOT BE FIXED HERE
160
+ *
161
+ * The charset excludes `"` and `'`, so a quoted literal — the normal way a
162
+ * credential is written in TS, JS, Python and JSON — stops the match at the
163
+ * opening quote. That is a real gap and a separate issue: widening the
164
+ * charset in the same change would make this narrowing unmeasurable, because
165
+ * the minified fixtures would then match for a new reason. The test file pins
166
+ * it so a widening cannot ride along.
167
+ *
168
+ * The second blind spot recorded here — no `-i`, so `PASSWORD` and
169
+ * `DB_PASSWORD` were invisible — is closed by `TIER2_GREP_CASE_FLAG` below
170
+ * (#844). It is kept out of the expression itself deliberately: spelling the
171
+ * vocabulary as `[Pp][Aa][Ss][Ss]...` would quadruple the length of a string
172
+ * that is read in a generated workflow by whoever is debugging a blocked
173
+ * commit, for no behaviour a flag does not already buy.
70
174
  */
175
+ export const TIER2_KEY_ERE = "(password|passwd|api[_-]?key|secret)";
176
+
71
177
  export const TIER2_ASSIGNMENT_ERE =
72
- "(password|passwd|api[_-]?key|secret)[[:space:]]*[:=][[:space:]]*[A-Za-z0-9/+=_.-]{12,}";
178
+ `${TIER2_KEY_ERE}[[:space:]]*[:=][[:space:]]*[A-Za-z0-9/+_.-][A-Za-z0-9/+=_.-]{11,}`;
179
+
180
+ /**
181
+ * The flag every tier-2 grep carries, and tier 1 carries nowhere (#844).
182
+ *
183
+ * Environment variables and shell defaults are conventionally UPPERCASE, so
184
+ * the spelling a case-sensitive `(password|passwd|api[_-]?key|secret)` can
185
+ * see is the one real credentials are least often written in. Measured on
186
+ * six realistic inputs, tier 2 scored 0 on all three uppercase spellings and
187
+ * 1 on all three lowercase ones; `-i` takes all six to 1. The live instance
188
+ * is a consumer repository that committed a real API key in a shell default
189
+ * of the form `<NAME>_KEY="${<NAME>_API_KEY:-<key>}"`; the scaffolded gate
190
+ * reported clean for as long as it sat on the default branch, because the
191
+ * pattern could not see an uppercase variable name. The consumer and the
192
+ * issue are named in `test/unit/secret-patterns.test.ts` — a module under
193
+ * `lib/` may carry no consumer-specific value (SC-A1).
194
+ *
195
+ * **It is a constant and not a literal in the generators for the reason the
196
+ * rest of this file exists.** Four positions consume it — the capture and
197
+ * the allowlist, in `gates.yml` and in the generated pre-commit hook — and
198
+ * four hand-typed flags are four things that can disagree about what counts
199
+ * as a secret. The cheapest wrong fix for #844 is to add `-i` to the
200
+ * committed `gates.yml` and stop: the symptom disappears for the repository
201
+ * that noticed it, every consumer's next scaffold writes the gate back
202
+ * without it, and so does this one's.
203
+ *
204
+ * **Tier 1 must never carry it.** Its patterns are anchored key FORMATS —
205
+ * `AKIA`, `ghp_`, a PEM header — whose case is part of the format. A
206
+ * case-insensitive tier 1 is a widening of the one tier that has no
207
+ * allowlist to absorb a false positive.
208
+ */
209
+ export const TIER2_GREP_CASE_FLAG = "-i";
73
210
 
74
211
  /**
75
212
  * Values that look like credentials but are not.
@@ -77,15 +214,385 @@ export const TIER2_ASSIGNMENT_ERE =
77
214
  * Applied to the extracted VALUE, never the whole line. Matching anywhere on
78
215
  * the line was an allowlist escape: appending `# placeholder` to a line
79
216
  * holding a real secret laundered it past the scan.
217
+ *
218
+ * READ CASE-INSENSITIVELY TOO, AND THAT IS A WIDENING (#844)
219
+ *
220
+ * The exclusion carries `TIER2_GREP_CASE_FLAG` in the same positions the
221
+ * capture does. This widens what is let through, which is the direction that
222
+ * fails open, so it is a deliberate choice rather than symmetry for its own
223
+ * sake: the population newly visible to the capture is dominated by `.env`
224
+ * and `.env.example` files, where the conventional spelling of a non-value
225
+ * is `API_KEY=CHANGEME` and `SECRET=PLACEHOLDER`. Closing the case gap
226
+ * without it would hard-fail CI — the generated job's branch is `exit 1`,
227
+ * not a warning — for every consumer who committed the example env file the
228
+ * documentation told them to, which is a gate consumers delete.
229
+ *
230
+ * The exclusion stays anchored at `[:=][[:space:]]*`, so a value is only let
231
+ * through when it STARTS with one of these tokens. A credential beginning
232
+ * with the letters of `getenv` or `placeholder` is the laundering this
233
+ * widens, and no form of it was detectable before either.
234
+ */
235
+ /**
236
+ * An unquoted value that is a DOTTED IDENTIFIER PATH, not a literal (#863).
237
+ *
238
+ * `-i` (above) made `api[_-]?key` match `apiKey`, which it could not before.
239
+ * `apiKey` is the conventional TypeScript spelling, so every consumer that
240
+ * passes a key through an object property started hard-failing the gate on
241
+ * lines like `apiKey:` config.judge.apiKey — a property REFERENCE, excused by
242
+ * nothing in the list above, and the generated job's branch is `exit 1`, not
243
+ * a warning. A secret gate that hard-fails CI on a property reference is a
244
+ * gate a consumer deletes, and deleting it costs the #844 fix too.
245
+ *
246
+ * WHY THIS CANNOT HIDE A CREDENTIAL THE CAPTURE CAN SEE
247
+ *
248
+ * The value charset excludes `"` and `'`, so in a source file tier 2 can only
249
+ * ever see an UNQUOTED value — and an unquoted value in source is an
250
+ * expression. The false-positive class is precisely dotted identifier paths,
251
+ * so excluding them removes no credential FORM this pattern is able to
252
+ * report, with one exception, which is why the exception is a tier-1 pattern:
253
+ * a signed JWT has this exact shape and is reachable in a `.env`. See the
254
+ * `jwt` entry in `TIER1_SECRET_PATTERNS`.
255
+ *
256
+ * It is anchored at BOTH ends of the value — `[:=][[:space:]]*` on the left,
257
+ * `$` on the right — so the whole value must be the path. The cheapest wrong
258
+ * fix for #863 is an "anything unquoted" exclusion, which deletes tier 2 for
259
+ * every source file while making the symptom go away; dropping the `$` is
260
+ * that fix wearing one character. An `API_KEY=` carrying `sk-live` and
261
+ * eighteen more characters has no dot and stays a FAIL, and so does a
262
+ * `${NAME_API_KEY:-...}` default, whose value begins `-`.
263
+ *
264
+ * Every example in this module is written so it is NOT itself a tier-2
265
+ * capture — the value is described rather than spelled, or a character
266
+ * outside the value charset leads it. A docstring that its own scanner
267
+ * reports is a module that fails the repository's Gates job the day somebody
268
+ * narrows one of these expressions, and the failure would name this file
269
+ * rather than their change.
270
+ *
271
+ * It is a named constant rather than six more tokens inside the string below
272
+ * because it is the component a reader of a blocked commit needs to find, and
273
+ * because `test/unit/gates-tier1-jwt.test.ts` asserts the committed
274
+ * `gates.yml` carries THIS and not a hand-typed near-copy. It is still a
275
+ * component OF the allowlist and not a second expression the generator joins
276
+ * on its own: four generated greps interpolate one allowlist binding, and a
277
+ * second string to interpolate is a second thing that can disagree about what
278
+ * counts as a secret.
279
+ *
280
+ * THE ROOT IS A CLOSED VOCABULARY, AND THE FIRST DRAFT'S WAS NOT
281
+ *
282
+ * This read `[A-Za-z_][A-Za-z0-9_]*` for the first segment — any identifier —
283
+ * and the security review of PR #868 was right that it is a hole. The premise
284
+ * above is that an unquoted value is an EXPRESSION, and that premise is a fact
285
+ * about source languages, not about every file a `git grep -- .` reaches. In a
286
+ * dotenv file, a shell script or a YAML document an unquoted dotted value is a
287
+ * LITERAL, and some credentials are literally shaped like an identifier path:
288
+ * a key of the form two letters, a dot, a base62 run, a dot, another base62
289
+ * run — the shape one well-known mail provider issues — walks through an
290
+ * any-identifier root. Measured on the first draft: it was excused.
291
+ *
292
+ * So the root is a fixed list of the words real code roots an expression at.
293
+ * It is the same decision as the placeholder vocabulary below and for the same
294
+ * reason: a closed list of words is auditable, and "anything shaped like an
295
+ * identifier" is a judgement the scanner is not entitled to make. A consumer
296
+ * whose expression roots at a word not on this list gets a false positive and
297
+ * a one-line change here, which is the direction this is allowed to be wrong
298
+ * in — the other direction is a credential nobody sees.
299
+ */
300
+ export const TIER2_EXPRESSION_ROOT_ERE =
301
+ "(process|os|Deno|globalThis|module|exports|this|self|config|conf|cfg|" +
302
+ "settings|options|opts|env|deps|current|ctx|context|params|args|argv|" +
303
+ "input|data|state|store|creds|credentials|auth|secrets|vars)";
304
+
305
+ export const TIER2_DOTTED_PATH_ERE =
306
+ `${TIER2_EXPRESSION_ROOT_ERE}(\\.[A-Za-z_][A-Za-z0-9_]*)+`;
307
+
308
+ /**
309
+ * The FIXED vocabulary of documented non-values (#863).
310
+ *
311
+ * The dotted-path exclusion above covers only two of the seven lines the
312
+ * widened capture reports on one consumer tree. Four of the remaining five
313
+ * are the spelling every getting-started document in the world uses,
314
+ * measured 2026-10-21. The tree and the file positions are named in
315
+ * `test/unit/gates-tier1-jwt.test.ts`, which also carries the four lines
316
+ * byte-exact; a module under `lib/` may carry no consumer-specific value
317
+ * (SC-A1). The shapes, with this file's own angle brackets:
318
+ *
319
+ * API_KEY:- <your-api-key-goes-here>
320
+ * API_KEY= <your_key_here>
321
+ * API_KEY= <your_gemini_key_here>
322
+ * SECRET:- <example-value-not-real>
323
+ *
324
+ * (The angle brackets and the space are this file's, not the consumer's —
325
+ * see the note above about a docstring that matches its own scanner.)
326
+ *
327
+ * A fix measured only on the repository that reported it is a fix measured on
328
+ * one input, and the dotted-path class alone leaves a second consumer red.
329
+ *
330
+ * WHAT MAKES THIS SAFE AND AN "IT LOOKS HARMLESS" RULE NOT
331
+ *
332
+ * This is a VOCABULARY — a closed list of words — not a judgement about
333
+ * whether a value looks like a credential. `your[_-]` and `example[_-]`
334
+ * require the separator, so the exclusion is the documented placeholder
335
+ * idiom and not every value beginning with four common letters.
336
+ * An `API_KEY=` carrying `sk-live` and eighteen more characters carries none
337
+ * of these words and stays a FAIL.
338
+ *
339
+ * It is ONE NAMED CONSTANT and not five more tokens spliced into the string
340
+ * below, for the reason `TIER2_GREP_CASE_FLAG` is one: the positions that
341
+ * consume it are generated into four greps, and a vocabulary a reader cannot
342
+ * point at is a vocabulary that gets re-typed somewhere else.
343
+ *
344
+ * It does NOT widen what the dotted-path exclusion covers and must not be
345
+ * read as a general placeholder heuristic. Adding a word here is adding a
346
+ * word to a gate's blind spot; measure the consumer line that needs it
347
+ * first, the way these four were measured.
348
+ *
349
+ * THE TAIL CARRIES NO DIGIT, AND THE FIRST DRAFT'S COULD
350
+ *
351
+ * `your[_-]` alone is a PREFIX test, so a value beginning with those five
352
+ * characters and continuing into thirty-two random ones was excused — the
353
+ * security review of PR #868 was right, and it reproduced. End-anchoring
354
+ * alone does not fix it, because the tail is still arbitrary.
355
+ *
356
+ * The discriminator is the digit. A documented placeholder is words and
357
+ * separators (`your` then a dash then `api` then a dash then `key`, and so
358
+ * on); a credential is not. The grep that consumes this runs `-i`, so case
359
+ * cannot be the discriminator here even though a real key is usually mixed —
360
+ * which is worth stating, because reaching for `[a-z]` is the obvious move
361
+ * and it silently matches everything under that flag.
362
+ *
363
+ * THAT TAIL RULE HELD FOR TWO OF THE THREE WORDS, AND THE SECOND REVIEW
364
+ * CAUGHT THE THIRD
365
+ *
366
+ * `your[_-]` and `example[_-]` require the separator. `REDACTED|CHANGEME|
367
+ * placeholder` did not — it carried a bare `[A-Za-z_-]*` tail — so a value
368
+ * beginning with one of those three words and continuing into a digit-free
369
+ * random run was excused. Reproduced on the shipped expression: an
370
+ * `API_KEY=` carrying `CHANGEME` and twenty-two more letters read CLEAN.
371
+ * It is the same defect as the `your_` one directly above, in the sibling
372
+ * the first repair did not look at.
373
+ *
374
+ * The separator is now required of all three, which is the rule the other
375
+ * two already stated. It costs nothing real: the consumer shape that needs
376
+ * a tail at all is `Placeholder_value_here`, whose tail begins `_`.
377
+ */
378
+ export const TIER2_PLACEHOLDER_VOCAB_ERE =
379
+ "(REDACTED|CHANGEME|placeholder)([_-][A-Za-z][A-Za-z_-]*)?" +
380
+ "|your[_-][A-Za-z][A-Za-z_-]*" +
381
+ "|example[_-][A-Za-z][A-Za-z_-]*";
382
+
383
+ /**
384
+ * The optional `-` is the SHELL DEFAULT separator, not a widening of the
385
+ * value (#863). Three of the four placeholder lines above are written as a
386
+ * `${NAME_API_KEY:-...}` default, so the character after `[:=]` is `-` and
387
+ * an anchor without it cannot reach the vocabulary at all.
388
+ *
389
+ * It cannot soften `SC-C`: the #844 shape is `${SAPLING_API_KEY:-<32 random
390
+ * chars>}`, whose value begins with no word in the vocabulary, so it is still
391
+ * reported. The anchor decides WHERE to look; the vocabulary decides what is
392
+ * excused, and only the second of those two is a list anyone can lengthen.
393
+ */
394
+ const TIER2_VALUE_ANCHOR = `^${TIER2_KEY_ERE}[[:space:]]*[:=][[:space:]]*-?`;
395
+
396
+ /**
397
+ * THE ENV-LOOKUP BRANCH WAS UNANCHORED, AND THREE QUARTERS OF IT WAS A
398
+ * SECOND DECIDER (second review of #868)
399
+ *
400
+ * It read `(process\.env|os\.environ|Deno\.env|getenv)` and was the only one
401
+ * of the four branches with no `$`. So it was a PREFIX test, and an
402
+ * `API_KEY=` carrying `getenv` and sixteen random characters was excused —
403
+ * the third instance of the unanchored-prefix defect in this one expression,
404
+ * after `your[_-]` and the placeholder vocabulary. Measured on the shipped
405
+ * expression before the repair: CLEAN.
406
+ *
407
+ * Anchoring it closes that. What anchoring alone does NOT do is notice that
408
+ * `process`, `os` and `Deno` have all been in `TIER2_EXPRESSION_ROOT_ERE`
409
+ * since #863 widened the root to a vocabulary — so three of the four
410
+ * alternatives were already excused by the dotted-path branch below, and an
411
+ * anchored branch naming them is two deciders answering one question. A
412
+ * mutation of either would leave the other holding every case up.
413
+ *
414
+ * Measured over this whole tree and nine control lines: the four-alternative
415
+ * branch and a `getenv`-only branch give identical verdicts on every input,
416
+ * including `os.environ.get` and `Deno.env.toObject`.
417
+ *
418
+ * `getenv` is the one that is NOT redundant, because it is a bare function
419
+ * name rather than an object, so no dotted path reaches it. It stays, with
420
+ * the end anchor and an identifier tail.
421
+ *
422
+ * A NOTE ON WHAT THAT TAIL IS FOR, BECAUSE THE FIRST DRAFT DELETED IT
423
+ *
424
+ * This branch was briefly removed outright, on the reasoning that nothing
425
+ * real is shaped like `getenv` followed by an identifier — a bare `getenv`
426
+ * is six characters against a twelve-character floor, and a genuine call
427
+ * writes `getenv(`, which ends the capture at the paren. That reasoning is
428
+ * sound and it is beside the point: #844's own case pins a `SECRET:` whose
429
+ * value is < Getenv_SOME_LONG_NAME > CLEAN, as the fixture proving the
430
+ * allowlist reads case the way the capture does. The class is not empty —
431
+ * there is a case in it. An argument that a class has no members is not
432
+ * evidence when the suite already holds one.
433
+ *
434
+ * (The angle brackets and the spaces are this file's. Spelling that value
435
+ * plainly makes this docstring a tier-2 capture excused only by the branch
436
+ * it is describing — so narrowing the branch would turn the Gates job red on
437
+ * THIS FILE rather than on the change that narrowed it. Measured: it did,
438
+ * and the tier-2 self-scan case in `test/unit/secret-patterns.test.ts` is
439
+ * what reported it. See the note above the dotted-path constant.)
80
440
  */
81
441
  export const TIER2_ALLOWED_VALUE_ERE =
82
- "^$|[:=][[:space:]]*(process\\.env|os\\.environ|Deno\\.env|getenv|REDACTED|CHANGEME|placeholder)";
442
+ "^$" +
443
+ `|${TIER2_VALUE_ANCHOR}getenv([A-Za-z_][A-Za-z0-9_]*)?(\\.[A-Za-z_][A-Za-z0-9_]*)*$` +
444
+ `|${TIER2_VALUE_ANCHOR}(${TIER2_PLACEHOLDER_VOCAB_ERE})$` +
445
+ `|${TIER2_VALUE_ANCHOR}${TIER2_DOTTED_PATH_ERE}$`;
446
+
447
+ /**
448
+ * Tier 3 — a credential written as a shell default, caught by SHAPE.
449
+ *
450
+ * Tiers 1 and 2 both need something in the text to tell them where to look: a
451
+ * provider prefix, or a variable name carrying credential vocabulary. A shell
452
+ * default gives neither when the variable is named for what it holds rather
453
+ * than for what kind of thing it is, and it is camouflaged in a way an
454
+ * assignment is not — every neighbouring line in such a block genuinely is a
455
+ * default, so the one that is not sits in a list of things that look alike.
456
+ *
457
+ * TWO DISCRIMINATORS, AND ONE OF THEM IS ON THE NAME SIDE (#848)
458
+ *
459
+ * The name must begin with a letter or underscore, which excludes positional
460
+ * parameters. A positional parameter is an argument, never a credential
461
+ * declaration, and both false positives this repository had were that shape.
462
+ *
463
+ * The VALUE must carry both a letter and a digit, which is the exclusion
464
+ * below rather than part of this expression — a `grep -oE` capture cannot
465
+ * express "contains one of these and one of those" without an alternation
466
+ * that doubles its length, and the two-stage pipeline tier 2 already uses
467
+ * reads better and is the shape every generated scanner already has.
468
+ *
469
+ * THE FLOOR IS NOT THE DISCRIMINATOR, AND REACHING FOR IT IS THE WRONG FIX
470
+ *
471
+ * Measured on a consumer tree: the false-positive values are 13, 13, 13, 13,
472
+ * 23 and 32 characters, and the real credential is 32. No length floor
473
+ * separates them. 12 is kept to match tier 2, as a floor and nothing more.
474
+ *
475
+ * MEASURED BEFORE IT WAS SHIPPED
476
+ *
477
+ * Captured / reported after the exclusion, over the tracked files of this
478
+ * repository and three consumer trees: 0/0 of 1138, 10/1 of 1726, 0/0 of
479
+ * 374, 0/0 of 52. Zero false positives over 3,290 tracked files, and the one
480
+ * reported hit is already caught by tier 2 because its name carries
481
+ * `API_KEY` — so on every tree available to measure, this tier adds nothing.
482
+ * The population it exists for has to be constructed, which is what
483
+ * `test/unit/secret-patterns.test.ts` does, and the constructed case asserts
484
+ * tier 2 reads CLEAN on it or this tier is measuring nothing #844 did not
485
+ * already do.
486
+ *
487
+ * The trees are named in that test file and deliberately not here: a module
488
+ * under `lib/` may carry no consumer-specific value (SC-A1), which is the
489
+ * same rule the `-i` note above defers to.
490
+ *
491
+ * A narrower charset with `/` removed — the obvious way to kill relative-path
492
+ * defaults — captures 8 instead of 10 on the consumer and reports the same 1.
493
+ * It differs only in captures the exclusion throws away, and it costs base64
494
+ * secrets, which carry `/`. Declined on the measurement, not on an argument.
495
+ *
496
+ * WHY `[$][{]` AND NOT `\$\{`
497
+ *
498
+ * Every pattern here is interpolated into a JS template literal on its way to
499
+ * generated shell. A literal `$` adjacent to a `{` inside one of those is an
500
+ * interpolation, and `unshellSafePatterns()` below refuses any pattern
501
+ * carrying that adjacency. Bracket expressions say the same thing in POSIX
502
+ * ERE with no backslash and no adjacency, and `[{]` additionally avoids a
503
+ * bare `{`, which some greps read as the start of an interval.
504
+ *
505
+ * NO CASE FLAG, DELIBERATELY. Tier 2 needs `-i` because its vocabulary is
506
+ * spelled in one case and credentials are written in another. This tier has
507
+ * no vocabulary: every character class is already written for both cases, and
508
+ * the exclusion is structural rather than a list of words. `-i` here would
509
+ * change nothing except to widen the value class, which is the direction that
510
+ * fails open.
511
+ *
512
+ * WHAT IT DOES NOT CATCH, named rather than left as an omission: a value with
513
+ * no digit at all, a `:=` or bare `-` default, and a quoted value — the last
514
+ * for the same reason recorded for tier 2 above.
515
+ */
516
+ export const TIER3_SHELL_DEFAULT_ERE = "[$][{][A-Za-z_][A-Za-z0-9_]*:-[A-Za-z0-9][A-Za-z0-9/+=_.-]{11,}";
517
+
518
+ /**
519
+ * Values in a shell default that look like credentials but are not.
520
+ *
521
+ * Applied to the extracted MATCH, anchored at the `:-` separator, for the
522
+ * reason tier 2's is anchored at its own: matching anywhere on the line is an
523
+ * allowlist escape.
524
+ *
525
+ * `^$` absorbs the single empty line `printf '%s\n' "$tier3"` produces from an
526
+ * empty capture — the same device tier 2's exclusion uses.
527
+ *
528
+ * The other two alternatives are the discriminator: a value with no digit, or
529
+ * a value with no letter, is let through. That one rule covers every false
530
+ * positive measured on three consumer trees — path defaults, scan-directory
531
+ * defaults and container names are letters and separators, port and timeout
532
+ * defaults are digits — and it subsumes the placeholder vocabulary tier 2
533
+ * needs a word list for, since `CHANGEME`, `placeholder` and `REDACTED` all
534
+ * carry no digit.
535
+ *
536
+ * `:` is not in the value charset and the name charset excludes it too, so
537
+ * `:-` occurs exactly once in any captured match and these anchors cannot
538
+ * attach to the wrong place.
539
+ */
540
+ export const TIER3_ALLOWED_VALUE_ERE = "^$|:-[^0-9]*$|:-[^A-Za-z]*$";
83
541
 
84
542
  /** Tier 1 as one alternation, parenthesised and ready to embed in `grep -E '...'`. */
85
543
  export function tier1Ere(): string {
86
544
  return `(${TIER1_SECRET_PATTERNS.map(p => p.ere).join("|")})`;
87
545
  }
88
546
 
547
+ /**
548
+ * Tier 2, ready to embed in `grep -E '...'`.
549
+ *
550
+ * Mirrors `tier1Ere()` so the generator has ONE binding to interpolate for
551
+ * each tier. It had `tier1Ere()` and then a hardcoded copy of the tier-2
552
+ * string, which is the two-deciders shape this file's header says the
553
+ * registry exists to prevent — and it cost #489: the narrowing had to be
554
+ * applied in three places that nothing compared.
555
+ */
556
+ export function tier2Ere(): string {
557
+ return TIER2_ASSIGNMENT_ERE;
558
+ }
559
+
560
+ /**
561
+ * Tier 3, ready to embed in `grep -E '...'`.
562
+ *
563
+ * Mirrors `tier1Ere()` and `tier2Ere()` for the same reason: the generator
564
+ * interpolates ONE binding per tier, so a mutation of a tier has one site.
565
+ */
566
+ export function tier3Ere(): string {
567
+ return TIER3_SHELL_DEFAULT_ERE;
568
+ }
569
+
570
+ /**
571
+ * EVERY registry expression that reaches generated shell, each with the id a
572
+ * refusal names it by.
573
+ *
574
+ * One binding, two consumers, because they are one question asked twice.
575
+ * `unshellSafePatterns()` below asks whether each of these survives the trip
576
+ * into a single-quoted shell string; `scripts/check-installed-hook-currency.ts`
577
+ * asks which of them the hook a developer actually commits through is missing
578
+ * (#874). A second list in the check script would be a second decider that
579
+ * agrees with this one right up until somebody adds a pattern to one of them
580
+ * — `.claude/rules/checks-must-be-able-to-fail.md`, fourth shape — and the
581
+ * failure mode is the one this registry exists to prevent: a scanner position
582
+ * nothing compares.
583
+ *
584
+ * Tier 1 is spread rather than re-listed, so an entry added to
585
+ * `TIER1_SECRET_PATTERNS` is covered here without a second edit. The four
586
+ * tier-2 and tier-3 expressions have no list of their own to spread.
587
+ */
588
+ export const EMBEDDED_PATTERNS: ReadonlyArray<{ id: string; ere: string }> = [
589
+ ...TIER1_SECRET_PATTERNS.map(p => ({ id: p.id, ere: p.ere })),
590
+ { id: "tier2-assignment", ere: TIER2_ASSIGNMENT_ERE },
591
+ { id: "tier2-allowlist", ere: TIER2_ALLOWED_VALUE_ERE },
592
+ { id: "tier3-shell-default", ere: TIER3_SHELL_DEFAULT_ERE },
593
+ { id: "tier3-allowlist", ere: TIER3_ALLOWED_VALUE_ERE },
594
+ ];
595
+
89
596
  /**
90
597
  * Guard against a pattern that cannot survive the trip into generated shell.
91
598
  *
@@ -100,13 +607,9 @@ export function unshellSafePatterns(): string[] {
100
607
  // tier-2 assignment and allowlist expressions are embedded the same way, so
101
608
  // checking only tier 1 would have been a validator with a narrower view
102
609
  // than the thing it validates.
103
- const embedded: Array<{ id: string; ere: string }> = [
104
- ...TIER1_SECRET_PATTERNS.map(p => ({ id: p.id, ere: p.ere })),
105
- { id: "tier2-assignment", ere: TIER2_ASSIGNMENT_ERE },
106
- { id: "tier2-allowlist", ere: TIER2_ALLOWED_VALUE_ERE },
107
- ];
610
+ //
108
611
  // A single quote ends the shell quoting; a backtick or ${ ends the JS
109
612
  // template the shell is built in. Backslashes are legitimate regex escapes,
110
613
  // so they are not disqualifying on their own.
111
- return embedded.filter(p => /['`]|\$\{/.test(p.ere)).map(p => p.id);
614
+ return EMBEDDED_PATTERNS.filter(p => /['`]|\$\{/.test(p.ere)).map(p => p.id);
112
615
  }
@@ -326,7 +326,7 @@ export function rookScopeCommand(
326
326
  // quoting is not a SHA.
327
327
  const q = (w: string) => `'${String(w).replace(/'/g, "'\\''")}'`;
328
328
  return (
329
- `cd ${q(projectRoot)} && bun ${q(`${harnessRoot}/scripts/rook-review-scope.ts`)} ` +
329
+ `bun --cwd ${q(projectRoot)} ${q(`${harnessRoot}/scripts/rook-review-scope.ts`)} ` +
330
330
  `--project ${q(projectRoot)} --sha ${pinned}` +
331
331
  (pinnedBase ? ` --base ${pinnedBase}` : "") +
332
332
  ` --out ${q(outPath)}`