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
@@ -0,0 +1,427 @@
1
+ /**
2
+ * Which test files can reach a given set of changed files (#676).
3
+ *
4
+ * A ship run pays for the whole suite to learn about the handful of files it
5
+ * changed: 374 files, 13,915 tests, ~8.9 minutes and 5,360 MB. That last
6
+ * number is why `lib/test-suite-lock.ts` sets `DEFAULT_CAPACITY = 2` — the
7
+ * suite, not the checkout, is what holds concurrent runs at two.
8
+ *
9
+ * **The direction this is allowed to be wrong in is TOWARD running too much.**
10
+ * A selection that is too large costs minutes. A selection that is too small
11
+ * reports a green suite over a regression, wearing the most convincing
12
+ * disguise available. So every question this module cannot answer resolves to
13
+ * "run everything", and it says which question it was.
14
+ *
15
+ * In particular an empty `tests` list is NEVER an instruction to run nothing.
16
+ * `0`, `{}`, `null` and `SKIP` are indistinguishable from success
17
+ * (`.claude/rules/config-access.md`); `UNMEASURED` is not. A caller must be
18
+ * able to tell "nothing is affected" from "I could not work out what is
19
+ * affected", and those are `reading`, not `tests.length`.
20
+ *
21
+ * Three ways a test reaches a file, because a graph that knows only the first
22
+ * reads exactly like a graph that is satisfied (#484 — an import and a
23
+ * `readFileSync(join(...))` are one question in two syntaxes):
24
+ *
25
+ * 1. a chain of relative imports, followed transitively
26
+ * 2. a module-relative `readFileSync(join(import.meta.dir, ...))`
27
+ * 3. a sweep — `readdirSync` or a glob — which is affected by anything
28
+ * under the tree it walks and cannot be expressed as an edge at all
29
+ *
30
+ * Sweeps are included unconditionally AND listed in `sweeps`. Including one
31
+ * silently would make "the graph selected this" and "I could not reason about
32
+ * this so I kept it" the same output, which is the reporting-position defect
33
+ * this repo keeps finding.
34
+ */
35
+ import { readdirSync, readFileSync, realpathSync, statSync } from "fs";
36
+ import { join, dirname } from "path";
37
+
38
+ import { relativeImports, runtimeReads, unresolvedModuleRelativeJoins } from "./package-closure";
39
+ import { stripJsComments } from "./strip-js-comments";
40
+
41
+ /** Extensions whose dependencies this module can actually resolve. */
42
+ export const SELECTABLE_SOURCE = /\.(ts|tsx|js|jsx|mts|cts)$/;
43
+
44
+ /** A test file, by the convention this repo uses everywhere. */
45
+ export const TEST_FILE = /\.test\.(ts|tsx)$/;
46
+
47
+ /**
48
+ * The shape a path is allowed to have before it may be PRINTED as part of a
49
+ * `bun test …` selection.
50
+ *
51
+ * Every selector here writes its answer to stdout and a caller interpolates
52
+ * it into a shell command unquoted, because word-splitting is how a list
53
+ * becomes arguments. Rather than trust that a tree walk produced inert
54
+ * paths, anything outside this alphabet refuses the whole selection. The
55
+ * injection surface is removed by construction rather than by assuming the
56
+ * walk is well-behaved.
57
+ *
58
+ * **It lives here, next to `TEST_FILE`, because there is now more than one
59
+ * producer.** It was a `const` inside `scripts/select-affected-tests.ts`
60
+ * until `scripts/text-dependents.ts` (#1054) began emitting into the same
61
+ * composition without it — a guard that one of two producers applies is a
62
+ * guard with a hole, and the hole is invisible from either file. Copying
63
+ * the pattern into the second producer would have made it two deciders that
64
+ * agree, which `.claude/rules/checks-must-be-able-to-fail.md` names as a
65
+ * shape where mutating either leaves the other holding the case up. One
66
+ * binding, both importers, and `test/selection-path-safety.test.ts` fails
67
+ * if a third producer declares its own.
68
+ *
69
+ * The shape of the defect is worth naming, because it is the shape of the
70
+ * issue that introduced it: #1054 is about a dependency expressed in a
71
+ * syntax the checker did not know, and this was the same thing one level
72
+ * up — a validation expressed in one of two producers.
73
+ */
74
+ export const SAFE_TEST_PATH = /^[A-Za-z0-9._/-]+\.test\.tsx?$/;
75
+
76
+ /**
77
+ * Directories walked when building the graph.
78
+ *
79
+ * `workflows` is in this list for a reason worth stating: `ship.js` is the
80
+ * most-changed file in this repository and it cannot be imported (#69), so
81
+ * it is reached only by the tests that read it as text. Leaving the
82
+ * directory out did not make a change to it UNMEASURED — it made the change
83
+ * resolve to nothing and report MEASURED, which is silent under-selection
84
+ * and the exact failure this module exists to prevent. Found in review
85
+ * before it shipped; every fixture in the battery put its changed files
86
+ * inside the walked tree, so the branch where that is false was outside the
87
+ * battery's reach entirely (#492).
88
+ */
89
+ export const SCAN_DIRS = ["test", "lib", "scripts", "gates", "bin", "hooks", "workflows"];
90
+
91
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", "coverage"]);
92
+
93
+ /**
94
+ * A test that discovers its subjects at runtime rather than importing them.
95
+ *
96
+ * Deliberately a family rather than one spelling: a detector that knows only
97
+ * `readdirSync` is the narrow-detector shape in
98
+ * `.claude/rules/checks-must-be-able-to-fail.md`, and the cost of missing a
99
+ * sweep is a green run over a tree it never walked.
100
+ *
101
+ * `execSync`/`spawnSync` are included ONLY when the command text contains an
102
+ * enumeration verb. Marking every shell-out a sweep would catch the tests
103
+ * that `git grep` the tree — which are genuine sweeps — and also every test
104
+ * that runs `git rev-parse`, which is most of them, and the selection would
105
+ * collapse to the whole suite. The matched spelling is reported so the
106
+ * over-inclusion stays visible rather than becoming a number nobody can
107
+ * explain.
108
+ */
109
+ const SWEEP_PATTERNS: Array<[string, RegExp]> = [
110
+ ["readdir", /\b(readdirSync|readdir|opendirSync|opendir)\s*\(/],
111
+ ["glob", /\b(globSync|glob)\s*\(|\bGlob\b|\.scan\s*\(/],
112
+ ["shell-enumeration", /\b(execSync|spawnSync|execFileSync)\s*\([^)]*?(grep\s+-r|git\s+grep|git\s+ls-files|\bfind\b|\bls\b)/],
113
+ ];
114
+
115
+ export interface AffectedTestsReading {
116
+ /** `UNMEASURED` means run the full suite; `tests` is empty and means nothing. */
117
+ reading: "MEASURED" | "UNMEASURED";
118
+ /** Repo-relative test files to run, sorted. Empty under UNMEASURED. */
119
+ tests: string[];
120
+ /** Why the selection cannot be trusted. Empty when MEASURED. */
121
+ unmeasuredReasons: string[];
122
+ /** Test files the walk found — the denominator for `selected`. */
123
+ testFilesSeen: number;
124
+ /** `tests.length`, stated so a reader does not have to count. */
125
+ selected: number;
126
+ /** Selected because they enumerate a directory, not because of an edge. */
127
+ sweeps: string[];
128
+ }
129
+
130
+ /** Repo-relative, forward slashes, no leading `./`. */
131
+ function norm(p: string): string {
132
+ return p.split("\\").join("/").replace(/^\.\//, "");
133
+ }
134
+
135
+ /**
136
+ * Every source file under SCAN_DIRS, repo-relative.
137
+ *
138
+ * Symlinked directories are followed — a monorepo whose packages are linked
139
+ * into place is a real layout, and `readdirSync(withFileTypes)` reports a
140
+ * symlink as not-a-directory, so a `statSync` is the only thing that makes
141
+ * them visible (#500). Following them means a link cycle would recurse
142
+ * forever, so every directory is recorded by its REAL path and visited
143
+ * once, and a link pointing outside the root is declined rather than
144
+ * walked.
145
+ */
146
+ function sourceFiles(root: string): string[] {
147
+ const out: string[] = [];
148
+ const seenDirs = new Set<string>();
149
+ const rootReal = (() => {
150
+ try {
151
+ return realpathSync(root);
152
+ } catch {
153
+ return root;
154
+ }
155
+ })();
156
+
157
+ const walk = (rel: string): void => {
158
+ const abs = join(root, rel);
159
+ let real: string;
160
+ try {
161
+ real = realpathSync(abs);
162
+ } catch {
163
+ return;
164
+ }
165
+ if (real !== rootReal && !real.startsWith(rootReal + "/")) return; // escaped the tree
166
+ if (seenDirs.has(real)) return; // a cycle, or two links to one directory
167
+ seenDirs.add(real);
168
+
169
+ let entries;
170
+ try {
171
+ entries = readdirSync(abs, { withFileTypes: true });
172
+ } catch {
173
+ return; // a directory this project does not have
174
+ }
175
+ for (const e of entries) {
176
+ if (SKIP_DIRS.has(e.name)) continue;
177
+ const child = norm(join(rel, e.name));
178
+ let isDir = e.isDirectory();
179
+ if (e.isSymbolicLink()) {
180
+ try {
181
+ isDir = statSync(join(root, child)).isDirectory();
182
+ } catch {
183
+ continue;
184
+ }
185
+ }
186
+ if (isDir) walk(child);
187
+ else if (SELECTABLE_SOURCE.test(e.name)) out.push(child);
188
+ }
189
+ };
190
+ for (const d of SCAN_DIRS) walk(d);
191
+ return out;
192
+ }
193
+
194
+ /**
195
+ * Resolve a relative specifier written in `from` to a file in `known`.
196
+ *
197
+ * The `.js` → `.ts` candidates are not decoration: TypeScript source that
198
+ * targets ESM writes `./x.js` for a file on disk called `x.ts`, and a
199
+ * resolver that does not know that drops the edge silently.
200
+ */
201
+ function resolveSpec(from: string, spec: string, known: Set<string>): string | null {
202
+ const base = norm(join(dirname(from), spec));
203
+ const candidates = [
204
+ base,
205
+ `${base}.ts`,
206
+ `${base}.tsx`,
207
+ `${base}.js`,
208
+ base.replace(/\.js$/, ".ts"),
209
+ base.replace(/\.js$/, ".tsx"),
210
+ norm(join(base, "index.ts")),
211
+ norm(join(base, "index.tsx")),
212
+ ];
213
+ for (const c of candidates) if (known.has(c)) return c;
214
+ return null;
215
+ }
216
+
217
+ /** Where a module-relative `join(import.meta.dir, ...)` points, repo-relative. */
218
+ function resolveRuntimeRead(from: string, up: number, segments: string[]): string {
219
+ let base = dirname(from);
220
+ for (let i = 0; i < up; i++) base = dirname(base);
221
+ return norm(join(base, ...segments));
222
+ }
223
+
224
+ /**
225
+ * The test files that can reach any of `changed`.
226
+ *
227
+ * `changed` is repo-relative. The reading is UNMEASURED — meaning "run the
228
+ * full suite" — when the graph provably cannot answer: an empty change set,
229
+ * a changed module the walk never saw, a changed non-module nothing in the
230
+ * tree names, or a walk that found no tests at all. That last one is #492's
231
+ * lesson: a scan that reached nothing reports the same clean result as a
232
+ * scan that found nothing wrong.
233
+ */
234
+ export function affectedTests(root: string, changed: string[]): AffectedTestsReading {
235
+ const unmeasuredReasons: string[] = [];
236
+ const wanted = changed.map(norm);
237
+
238
+ if (wanted.length === 0) {
239
+ unmeasuredReasons.push(
240
+ "no changed files were supplied, so nothing constrains the selection — " +
241
+ "an unconstrained selection is the whole suite, not an empty one",
242
+ );
243
+ }
244
+
245
+ const nonModule = wanted.filter(c => !SELECTABLE_SOURCE.test(c));
246
+ const files = sourceFiles(root);
247
+ const known = new Set(files);
248
+ const testFiles = files.filter(f => TEST_FILE.test(f));
249
+
250
+ // A changed file the walk never saw has NO EDGE to it by construction, so
251
+ // every test comes back unaffected and the reading would say MEASURED over
252
+ // a question it never asked. This is the one that nearly shipped: before
253
+ // `workflows` was in SCAN_DIRS, a change to `ship.js` landed here.
254
+ for (const c of wanted) {
255
+ if (SELECTABLE_SOURCE.test(c) && !known.has(c)) {
256
+ unmeasuredReasons.push(
257
+ `${c} is outside the walked tree (${SCAN_DIRS.join(", ")}) or no longer exists, so no ` +
258
+ "edge to it can exist — \"nothing is affected\" would be an artefact of not looking",
259
+ );
260
+ }
261
+ }
262
+
263
+ if (testFiles.length === 0) {
264
+ unmeasuredReasons.push(
265
+ `the walk over ${SCAN_DIRS.join(", ")} found no test files, which is not the ` +
266
+ "same as finding no affected ones",
267
+ );
268
+ }
269
+
270
+ // REVERSE edges: for each file, who depends on it.
271
+ //
272
+ // Walking dependents outward from the changed set is linear and has no
273
+ // interaction with cycles at all. The first draft walked forward from each
274
+ // test with a memo, which is unsound in exactly one way that is hard to
275
+ // see: a `false` computed while a cycle edge was cut gets cached, and a
276
+ // later query reads the wrong answer. Reversing the question removes the
277
+ // bug rather than guarding it.
278
+ const dependents = new Map<string, Set<string>>();
279
+ const sweeps: string[] = [];
280
+ const opaque: string[] = [];
281
+
282
+ const addEdge = (from: string, to: string): void => {
283
+ let s = dependents.get(to);
284
+ if (!s) {
285
+ s = new Set();
286
+ dependents.set(to, s);
287
+ }
288
+ s.add(from);
289
+ };
290
+
291
+ for (const f of files) {
292
+ let source: string;
293
+ try {
294
+ source = readFileSync(join(root, f), "utf-8");
295
+ } catch {
296
+ continue;
297
+ }
298
+ for (const spec of relativeImports(source)) {
299
+ const target = resolveSpec(f, spec, known);
300
+ if (target) addEdge(f, target);
301
+ }
302
+ const resolvedBasenames = new Set<string>();
303
+ for (const read of runtimeReads(source)) {
304
+ const target = resolveRuntimeRead(f, read.up, read.segments);
305
+ resolvedBasenames.add(target.split("/").pop() as string);
306
+ addEdge(f, target);
307
+ }
308
+
309
+ // A changed file that is not a module is reached by the files that NAME
310
+ // it. Nothing imports a rule file, a spec or a YAML, so the first draft
311
+ // refused the whole selection whenever one appeared in the change set —
312
+ // and measured against eight real commits of this repository, seven
313
+ // carried at least one, so the feature was inert on the input it exists
314
+ // to serve.
315
+ //
316
+ // **Over a COMMENT-STRIPPED view.** A citation and a read are the same
317
+ // bytes, and this repository cites its own rule files constantly:
318
+ // matching raw source, `.claude/rules/checks-must-be-able-to-fail.md`
319
+ // alone selected 322 of 388 files — 83% of the suite — because almost
320
+ // every test mentions it in a docstring. Over code only it is 108, of
321
+ // which 72 are the sweep floor. `blankLiterals` stays OFF: the path
322
+ // lives in a string literal, which is exactly the thing a read is made
323
+ // of.
324
+ //
325
+ // The direction of error is unchanged. A reader that does not write the
326
+ // path down in code is assembling it at runtime, and a file that does
327
+ // that is already a sweep.
328
+ const code = stripJsComments(source);
329
+ for (const c of nonModule) {
330
+ if (code.includes(c)) addEdge(f, c);
331
+ }
332
+
333
+ // The same question in a third syntax (#484). `runtimeReads` sees
334
+ // `join(import.meta.dir, "..", "workflows", "ship.js")` and nothing
335
+ // else, so one const of indirection hides the read:
336
+ //
337
+ // const REPO_ROOT = join(import.meta.dir, "..");
338
+ // readFileSync(join(REPO_ROOT, "workflows", "ship.js"), "utf-8")
339
+ //
340
+ // Measured on this repository, that is not hypothetical — it is how
341
+ // `test/implement-empty-result.test.ts` and
342
+ // `test/files-changed-path-shape.test.ts` reach `ship.js`, and both
343
+ // were silently unselected by a change to it. Resolving the
344
+ // indirection means evaluating the module, so instead the BASENAME as
345
+ // a quoted literal in code is an edge. It over-selects for a common
346
+ // basename and that is the direction this is allowed to be wrong in;
347
+ // a missed read is the direction that reports green over code it
348
+ // never ran.
349
+ //
350
+ // **Skipped for a basename this file already reads resolvably**, and
351
+ // that clause is what keeps `runtimeReads` load-bearing rather than a
352
+ // second decider agreeing with this one. Measured before it was added:
353
+ // deleting the `runtimeReads` call entirely was 0 red and moved the
354
+ // real selection by 0 files, because a resolvable read always quotes
355
+ // its own basename. With the clause, a file that resolvably reads
356
+ // `lib/a/config.ts` is NOT selected by a change to `lib/b/config.ts`
357
+ // — it has shown it can name that basename precisely — while a file
358
+ // that reaches the same path through a const still is. Two deciders,
359
+ // each with an input only it can reach.
360
+ for (const c of wanted) {
361
+ const b = c.split("/").pop();
362
+ if (!b || resolvedBasenames.has(b)) continue;
363
+ if (new RegExp(`["'\`]${b.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["'\`]`).test(code)) {
364
+ addEdge(f, c);
365
+ }
366
+ }
367
+
368
+ // A module-relative join whose segments are not all literals reads a
369
+ // path nobody can name statically. `runtimeReads` drops those; dropping
370
+ // them here would be the fail-open `lib/package-closure.ts` built
371
+ // `unresolvedModuleRelativeJoins` to prevent. A test that does it is a
372
+ // sweep; anything else becomes a seed, so every test that can reach it
373
+ // runs too.
374
+ const unresolved = unresolvedModuleRelativeJoins(source).length > 0;
375
+ if (TEST_FILE.test(f)) {
376
+ if (unresolved || SWEEP_PATTERNS.some(([, re]) => re.test(code))) sweeps.push(f);
377
+ } else if (unresolved) {
378
+ opaque.push(f);
379
+ }
380
+ }
381
+
382
+ // A non-module file nothing in the tree names is not an unaffected file —
383
+ // it is a file whose readers, if it has any, build its path at runtime,
384
+ // and the graph has no way to see them. Refuse by name.
385
+ for (const c of nonModule) {
386
+ if (!dependents.has(c)) {
387
+ unmeasuredReasons.push(
388
+ `${c} is not a module, and no file under ${SCAN_DIRS.join(", ")} names it, so any test ` +
389
+ "that reads it builds the path at runtime where the graph cannot follow",
390
+ );
391
+ }
392
+ }
393
+
394
+ if (unmeasuredReasons.length > 0) {
395
+ return {
396
+ reading: "UNMEASURED",
397
+ tests: [],
398
+ unmeasuredReasons,
399
+ testFilesSeen: testFiles.length,
400
+ selected: 0,
401
+ sweeps: [],
402
+ };
403
+ }
404
+
405
+ // Breadth-first over dependents, seeded with the change set and with every
406
+ // module whose own reads could not be resolved.
407
+ const reached = new Set<string>();
408
+ const queue = [...wanted, ...opaque];
409
+ while (queue.length > 0) {
410
+ const cur = queue.pop() as string;
411
+ if (reached.has(cur)) continue;
412
+ reached.add(cur);
413
+ for (const d of dependents.get(cur) ?? []) if (!reached.has(d)) queue.push(d);
414
+ }
415
+
416
+ const sweepSet = new Set(sweeps);
417
+ const tests = testFiles.filter(t => sweepSet.has(t) || reached.has(t)).sort();
418
+
419
+ return {
420
+ reading: "MEASURED",
421
+ tests,
422
+ unmeasuredReasons: [],
423
+ testFilesSeen: testFiles.length,
424
+ selected: tests.length,
425
+ sweeps: sweeps.sort(),
426
+ };
427
+ }
@@ -10,7 +10,7 @@
10
10
  import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
11
11
  import { join } from 'path';
12
12
  import { auditAgent, type Role } from '../scripts/audit-transcript';
13
- import { writeCache, type BehavioralCache } from './behavioral-cache';
13
+ import { behavioralCachePath, writeCache, type BehavioralCache } from './behavioral-cache';
14
14
 
15
15
  export interface AgentAuditResult {
16
16
  role: Role;
@@ -109,8 +109,7 @@ export function populateBehavioralCache(
109
109
  }
110
110
 
111
111
  if (Object.keys(cacheData).length > 0) {
112
- const cachePath = join(projectRoot, '.rungate', 'behavioral-results.json');
113
- writeCache(cachePath, cacheData);
112
+ writeCache(behavioralCachePath(projectRoot), cacheData);
114
113
  return Object.keys(cacheData).length;
115
114
  }
116
115
  } catch {