rungate 0.3.0 → 0.4.1

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 (49) hide show
  1. package/lib/ac-quality.ts +119 -0
  2. package/lib/brief-precedence.ts +114 -0
  3. package/lib/ci-checkout.ts +27 -1
  4. package/lib/compliance-backfill.ts +16 -4
  5. package/lib/compliance-report.ts +109 -8
  6. package/lib/config-loader.ts +129 -5
  7. package/lib/config-readers.ts +86 -0
  8. package/lib/conformity.ts +520 -27
  9. package/lib/context-docs.ts +182 -0
  10. package/lib/create-brief.ts +22 -17
  11. package/lib/create-sc.ts +55 -33
  12. package/lib/decomposition-waves.ts +197 -0
  13. package/lib/doc-scan-targets.ts +435 -0
  14. package/lib/gate-check-audit.ts +190 -0
  15. package/lib/generators/agents-md.ts +10 -5
  16. package/lib/issue-extraction.ts +368 -0
  17. package/lib/organize.ts +129 -40
  18. package/lib/package-closure.ts +111 -0
  19. package/lib/phase2-decomposition.ts +270 -0
  20. package/lib/prior-branch.ts +24 -1
  21. package/lib/project-aliases.ts +100 -0
  22. package/lib/prove-label-gate.ts +93 -0
  23. package/lib/release-preflight.ts +225 -15
  24. package/lib/rungate-schema.ts +36 -2
  25. package/lib/sc-cover.ts +92 -1
  26. package/lib/sc-ids.ts +151 -0
  27. package/lib/scaffold/pre-push-hook.ts +165 -0
  28. package/lib/scaffold/rehearsal.ts +330 -0
  29. package/lib/scaffold/steps.ts +175 -122
  30. package/lib/scaffold/write-steps.ts +167 -0
  31. package/lib/scope-denylist.ts +258 -0
  32. package/lib/scratch-cleanup.ts +198 -0
  33. package/lib/scratch-roots.ts +94 -0
  34. package/lib/task-completion-checks.ts +50 -3
  35. package/lib/typescript-project.ts +233 -0
  36. package/lib/validators/spec-validators.ts +23 -34
  37. package/lib/verified-push.ts +179 -2
  38. package/lib/workflow-security.ts +51 -7
  39. package/lib/worktree-cleanup.ts +318 -20
  40. package/lib/worktree-repo.ts +465 -0
  41. package/package.json +8 -2
  42. package/scripts/audit-specs.ts +134 -37
  43. package/scripts/audit-transcript.ts +259 -0
  44. package/scripts/create-sc.ts +15 -1
  45. package/scripts/detect-sc-drift.ts +200 -0
  46. package/scripts/extract-constraints.ts +16 -36
  47. package/scripts/scaffold-project.ts +26 -136
  48. package/scripts/split-spec.ts +315 -0
  49. package/scripts/sync-sc-status.ts +751 -0
package/lib/conformity.ts CHANGED
@@ -17,6 +17,7 @@ import { tryLoadRungateConfig } from "./config-loader";
17
17
  import { stripJsComments } from "./strip-js-comments";
18
18
  import { parseScDeclarations } from "./sc-ids";
19
19
  import { isHarnessItself } from "./harness-identity";
20
+ import { tsconfigVerdict } from "./typescript-project";
20
21
 
21
22
  // ── Shared utilities ────────────────────────────────────────
22
23
 
@@ -539,17 +540,23 @@ function loadRegistry(
539
540
  return builtIn;
540
541
  }
541
542
 
542
- // Look for consumer custom matchers in .claude/rungate.json
543
- const configPath = join(projectRoot, ".claude", "rungate.json");
544
- if (!existsSync(configPath)) {
545
- _registryCache.set(cacheKey, builtIn);
546
- return builtIn;
547
- }
548
-
543
+ // Consumer custom matchers, via the loader (ADR-002 D1, #309). Reading the
544
+ // monolith directly saw nothing on a project that had migrated to the
545
+ // directory layout, so a consumer's custom matchers silently stopped
546
+ // existing the moment they ran the scaffold that migrates them.
547
+ // Named without constructing the path — the loader resolves either layout,
548
+ // so there is no single file to point at, and spelling one out here would
549
+ // be the very access CONFIG-1 forbids in the file that hosts CONFIG-1.
550
+ const configDesc = `the rungate config under ${projectRoot}`;
549
551
  let customMatchers: Array<{ name: string; regex: string }>;
550
552
  try {
551
- const config = JSON.parse(readFileSync(configPath, "utf-8"));
552
- customMatchers = config.customMatchers ?? [];
553
+ const config = tryLoadRungateConfig(projectRoot);
554
+ if (!config) {
555
+ _registryCache.set(cacheKey, builtIn);
556
+ return builtIn;
557
+ }
558
+ customMatchers = (config as { customMatchers?: Array<{ name: string; regex: string }> })
559
+ .customMatchers ?? [];
553
560
  } catch (err) {
554
561
  // Falling back to the built-ins is right — one consumer's broken config
555
562
  // must not take the engine's own matchers down with it. Doing it in
@@ -563,7 +570,7 @@ function loadRegistry(
563
570
  // logs is how a secret in a misplaced field reaches somewhere it was
564
571
  // never meant to go.
565
572
  console.warn(
566
- `WARN: ${configPath} could not be read as JSON (${err instanceof Error ? err.name : "error"}; ` +
573
+ `WARN: ${configDesc} could not be read as JSON (${err instanceof Error ? err.name : "error"}; ` +
567
574
  `message withheld — it can quote file contents). ` +
568
575
  `Falling back to the built-in matcher registry — any customMatchers in that file are NOT loaded, ` +
569
576
  `so SCs written against them will be reported as having no matcher.`,
@@ -582,7 +589,7 @@ function loadRegistry(
582
589
  for (const candidate of customMatchers) {
583
590
  if (!allowOverride && builtInNames.has(candidate.name)) {
584
591
  console.warn(
585
- `WARN: ${configPath} defines a custom matcher named "${candidate.name}", which is a built-in. ` +
592
+ `WARN: ${configDesc} defines a custom matcher named "${candidate.name}", which is a built-in. ` +
586
593
  `A project cannot replace a built-in matcher while being verified by it — the entry is IGNORED. ` +
587
594
  `Rename it to extend the vocabulary instead.`,
588
595
  );
@@ -595,7 +602,7 @@ function loadRegistry(
595
602
  new RegExp(candidate.regex, "i");
596
603
  } catch {
597
604
  console.warn(
598
- `WARN: ${configPath} custom matcher "${candidate.name}" has a regex that does not compile — the entry is IGNORED.`,
605
+ `WARN: ${configDesc} custom matcher "${candidate.name}" has a regex that does not compile — the entry is IGNORED.`,
599
606
  );
600
607
  continue;
601
608
  }
@@ -1389,10 +1396,15 @@ export function runScaffoldConformity(root: string, opts?: { extraSpecDirs?: str
1389
1396
  expect(missing).toEqual([]);
1390
1397
  });
1391
1398
 
1392
- test("rungate.json has required fields (if exists)", () => {
1393
- const p = join(root, ".claude", "rungate.json");
1394
- if (!existsSync(p)) return;
1395
- const config = JSON.parse(readFileSync(p, "utf-8"));
1399
+ test("rungate config has required fields (if configured)", () => {
1400
+ // Through the loader (ADR-002 D1, #309). Reading the monolith directly
1401
+ // meant a project on the directory layout skipped this check entirely —
1402
+ // `existsSync` was false, the test returned, and a config missing
1403
+ // `project` or `repo` passed by never being looked at. Exactly the
1404
+ // shape .claude/rules/checks-must-be-able-to-fail.md opens with, in the
1405
+ // check that validates config.
1406
+ const config = tryLoadRungateConfig(root);
1407
+ if (!config) return;
1396
1408
  expect(config.project).toBeDefined();
1397
1409
  expect(config.repo).toBeDefined();
1398
1410
  });
@@ -1994,16 +2006,22 @@ export function runDocHygiene(
1994
2006
 
1995
2007
  test("HYGIENE-11: Stale unreferenced files warn with archival suggestion", () => {
1996
2008
  const index = getRefIndex();
1997
- // Load stalenessThreshold from rungate.json, default 90 days
1998
- const configPath = join(root, ".claude", "rungate.json");
2009
+ // stalenessThreshold through the loader (ADR-002 D1, #309), default 90
2010
+ // days. The bare `catch {}` is kept deliberately narrow in meaning: a
2011
+ // config that cannot be read must not take HYGIENE-11 down, but it also
2012
+ // must not silently become 90 — which, with nothing logged, is what it
2013
+ // used to do.
1999
2014
  let threshold = 90;
2000
- if (existsSync(configPath)) {
2001
- try {
2002
- const config = JSON.parse(readFileSync(configPath, "utf-8"));
2003
- if (typeof config.stalenessThreshold === "number") {
2004
- threshold = config.stalenessThreshold;
2005
- }
2006
- } catch {}
2015
+ try {
2016
+ const config = tryLoadRungateConfig(root);
2017
+ if (typeof config?.stalenessThreshold === "number") {
2018
+ threshold = config.stalenessThreshold;
2019
+ }
2020
+ } catch (err) {
2021
+ console.warn(
2022
+ `WARN: HYGIENE-11 could not read the rungate config (${(err as Error).name}); ` +
2023
+ `using the ${threshold}-day default. A configured threshold is NOT in effect.`,
2024
+ );
2007
2025
  }
2008
2026
 
2009
2027
  // Scan docs directories for markdown files — skip reference/ entirely (AC-2)
@@ -2564,10 +2582,39 @@ export function runPackageValidation(root: string) {
2564
2582
  });
2565
2583
  }
2566
2584
 
2585
+ /**
2586
+ * #87 — TSC-1 demanded a tsconfig.json that the generator had deliberately
2587
+ * decided not to write.
2588
+ *
2589
+ * `createTsconfig` skips a project with no hand-written TypeScript, because a
2590
+ * tsconfig whose `include` matches nothing is tsc error TS18003 — a type check
2591
+ * that reads as broken rather than as "nothing to check". `createCiWorkflows`
2592
+ * and the AGENTS.md generator both agreed and emitted no step and no row. Then
2593
+ * this hard assert ran in that same consumer's generated conformity suite and
2594
+ * failed over the absent file. Both halves of the question were asserted at
2595
+ * once, which is the contradiction #87 was filed to settle.
2596
+ *
2597
+ * Settled in favour of "consumers may be non-TypeScript projects", so TSC-1
2598
+ * asks `tsconfigVerdict` — the one predicate `createTsconfig` uses — whether
2599
+ * it has anything to assert. The skip is RECORDED as a finding rather than
2600
+ * taken quietly: an unmeasured check and a satisfied check look identical from
2601
+ * the outside, and `.claude/rules/config-access.md` names the silent form as
2602
+ * the anti-pattern it is.
2603
+ */
2567
2604
  export function runTsconfigValidation(root: string) {
2568
2605
  describe("TSConfig validation", () => {
2569
- test("TSC-1: tsconfig.json exists", () => {
2570
- expect(existsSync(join(root, "tsconfig.json"))).toBe(true);
2606
+ test("TSC-1: tsconfig.json exists where TypeScript source does", () => {
2607
+ const verdict = tsconfigVerdict(root);
2608
+ if (!verdict.applicable) {
2609
+ addFinding({
2610
+ ruleId: "TSC-1",
2611
+ severity: "WARN",
2612
+ file: "tsconfig.json",
2613
+ message: `UNMEASURED: ${verdict.reason}`,
2614
+ });
2615
+ return;
2616
+ }
2617
+ expect(verdict.present, verdict.reason).toBe(true);
2571
2618
  });
2572
2619
 
2573
2620
  test("TSC-2: strict mode enabled", () => {
@@ -2627,6 +2674,452 @@ export function runModuleDepthCheck(root: string) {
2627
2674
  });
2628
2675
  }
2629
2676
 
2677
+ // ── Config access conformity (ADR-002 D4, #309) ────────────────
2678
+ //
2679
+ // ADR-001 decided the single-loader policy on 2026-10-05 and specified this
2680
+ // check as the enforcement. It was never built. Six days later the thing it
2681
+ // was written to stop had gone from ~24 sites to ~89 — the policy was
2682
+ // written down the whole time, which is the measurement that makes
2683
+ // "a rule nothing executes is not a rule" a number rather than a slogan.
2684
+ //
2685
+ // TWO checks, not one, because there are two bypass routes and ADR-001's
2686
+ // single check would have missed eleven of them: `workflows/*.js` reaches
2687
+ // config from inside agent PROMPT TEXT, which a TypeScript-source scan does
2688
+ // not look at.
2689
+ //
2690
+ // ## The self-reference trap
2691
+ //
2692
+ // This file is inside the scanned set and is about to contain the literals
2693
+ // it searches for. An allowlist naming the exempt files becomes evidence
2694
+ // those files are referenced — this repo has hit that three times. So the
2695
+ // pattern is ASSEMBLED from fragments that never appear adjacent in this
2696
+ // source, and the test asserts the check reports zero against its own file.
2697
+ // The three real violations this file used to carry are migrated to the
2698
+ // loader in the same change, so that zero is a fact and not an exemption.
2699
+ const CFG_DOT = ".";
2700
+ const CFG_DIR = "claude";
2701
+ const CFG_NAME = "rungate";
2702
+
2703
+ /**
2704
+ * A path being built to the config, in CODE.
2705
+ *
2706
+ * Comments are blanked by `stripJsComments` before this runs — offset
2707
+ * preserving, already proven on `ship.js` by its own suite — rather than by a
2708
+ * line rule of my own. Prose that DISCUSSES the config is not an access, and
2709
+ * counting it would bury the real sites in noise until the ratchet became a
2710
+ * number nobody reads.
2711
+ *
2712
+ * STATED LIMIT, carried over from ADR-001 and not an oversight: this is
2713
+ * string matching, so `join(root, CFG_DOT + CFG_DIR, dynamicName)` is not
2714
+ * caught. It catches every one of the present sites; a variable-constructed
2715
+ * path is not the realistic failure mode and an AST check is not worth the
2716
+ * dependency.
2717
+ */
2718
+ function configAccessPattern(): RegExp {
2719
+ return new RegExp(
2720
+ "\\" + CFG_DOT + CFG_DIR + "[\"'`/\\\\,\\s)]+\\s*[\"'`]?" + CFG_NAME,
2721
+ "g",
2722
+ );
2723
+ }
2724
+
2725
+ /**
2726
+ * Calls whose arguments are FILESYSTEM PATHS (#415).
2727
+ *
2728
+ * The positive list IS the definition, not a heuristic: a config path that
2729
+ * reaches the disk is either built by a path API or handed straight to an fs
2730
+ * one. Everything a `node:path` call touches is a path by construction.
2731
+ */
2732
+ const FS_PATH_CALLS = new Set([
2733
+ "existsSync", "readFileSync", "writeFileSync", "appendFileSync", "readdirSync",
2734
+ "mkdirSync", "rmSync", "rmdirSync", "unlinkSync", "statSync", "lstatSync",
2735
+ "copyFileSync", "cpSync", "renameSync", "realpathSync", "readlinkSync", "openSync",
2736
+ ]);
2737
+
2738
+ /**
2739
+ * `node:path` builders. Receiver-checked, unlike the fs names above, because
2740
+ * `Array.prototype.join` shares one of them and `["a", "b"].join(", ")` is
2741
+ * text. A bare `join` is the named import this repo uses; `path.join` is the
2742
+ * namespace form.
2743
+ */
2744
+ const PATH_BUILDERS = new Set(["join", "resolve", "relative", "normalize"]);
2745
+
2746
+ /**
2747
+ * Handing a shell a command that names the config is a read, and the literal
2748
+ * carrying it has spaces in it by construction — `cat <root>/…json` would
2749
+ * otherwise read as prose and go uncounted, which is the one fail-open the
2750
+ * prose rule could have opened on its own.
2751
+ */
2752
+ const SHELL_CALLS = new Set(["execSync", "exec", "execFileSync", "spawnSync", "spawn"]);
2753
+
2754
+ function isPathCall(callee: string | null): boolean {
2755
+ if (!callee) return false;
2756
+ const bare = callee.slice(callee.lastIndexOf(".") + 1);
2757
+ if (FS_PATH_CALLS.has(bare) || SHELL_CALLS.has(bare)) return true;
2758
+ return PATH_BUILDERS.has(bare) && (callee === bare || callee === `path.${bare}`);
2759
+ }
2760
+
2761
+ /**
2762
+ * Calls that take TEXT. Both are universal JS idioms rather than names out of
2763
+ * this repo — `x.push(…)` into a list of messages, and `console.*` — and both
2764
+ * are needed because a documentation entry can carry a path-SHAPED literal:
2765
+ * `keyFiles.push({ file: "…/" })` is a row in a generated table, not a read.
2766
+ */
2767
+ function isTextCall(callee: string | null): boolean {
2768
+ if (!callee) return false;
2769
+ return callee.endsWith(".push") || callee.startsWith("console.");
2770
+ }
2771
+
2772
+ /** The dotted name immediately left of an open paren, or `""` for a group. */
2773
+ function calleeBefore(text: string, parenIndex: number): string {
2774
+ let j = parenIndex - 1;
2775
+ while (j >= 0 && /\s/.test(text[j]!)) j--;
2776
+ const end = j + 1;
2777
+ while (j >= 0 && /[A-Za-z0-9_$.]/.test(text[j]!)) j--;
2778
+ return text.slice(j + 1, end);
2779
+ }
2780
+
2781
+ /** What a config-path match turned out to be. */
2782
+ export type ConfigSiteKind = "use" | "mention";
2783
+
2784
+ export interface ConfigSite {
2785
+ /** Offset in the comment-stripped source. */
2786
+ index: number;
2787
+ kind: ConfigSiteKind;
2788
+ /** Innermost enclosing call, or null at statement level. */
2789
+ callee: string | null;
2790
+ /** The literal run the match sits in, or null if it is not in one. */
2791
+ literal: string | null;
2792
+ }
2793
+
2794
+ /**
2795
+ * Is this path being BUILT, or merely NAMED? (#415)
2796
+ *
2797
+ * The one place that decides, so the mutation harness has one site to
2798
+ * collapse (`.claude/rules/checks-must-be-able-to-fail.md`). Collapsing it
2799
+ * either way moves a banked number and the both-ways ratchet refuses, which
2800
+ * is the property `test/config-access-mentions.test.ts` SC-1553 pins down.
2801
+ *
2802
+ * ## How the two views are read
2803
+ *
2804
+ * There is NO second lexer here. `stripJsComments` already scans code,
2805
+ * strings, templates (with `${}` to any depth) and regex literals, offset
2806
+ * preserving, and `blankLiterals` gives a view in which every literal's
2807
+ * CONTENTS are spaces and its delimiters are not. Over that view a naive
2808
+ * paren counter is exact — no quote, paren or brace inside a string or a
2809
+ * regex can reach it — and the literal a match sits in is simply the maximal
2810
+ * run of blanked offsets around it. A second scanner answering the same
2811
+ * question is a second scanner to drift.
2812
+ *
2813
+ * ## The decision, and which way each branch is allowed to be wrong
2814
+ *
2815
+ * 1. an fs, shell or `node:path` call
2816
+ * around it → USE, whatever the text says
2817
+ * 2. otherwise, prose around the path → MENTION
2818
+ * 3. otherwise, a path-shaped literal into a
2819
+ * message list or the console → MENTION
2820
+ * 4. otherwise → USE
2821
+ *
2822
+ * Rule 4 is the fail-closed default and it is the reason an unrecognised
2823
+ * helper, a bare `const p = "…"` or a path built by concatenation still
2824
+ * counts: a path-shaped literal is a path until something shows otherwise.
2825
+ *
2826
+ * STATED LIMIT, in the tradition of ADR-001's: a literal containing
2827
+ * whitespace, passed to a call this cannot recognise, reads as prose. Both
2828
+ * halves have to be true at once, which is why the remaining blind spot is a
2829
+ * sentence that is also a path.
2830
+ */
2831
+ export function classifyConfigSites(source: string): ConfigSite[] {
2832
+ const code = stripJsComments(source);
2833
+ const bare = stripJsComments(source, { blankLiterals: true });
2834
+
2835
+ const sites: ConfigSite[] = [];
2836
+ const pattern = configAccessPattern();
2837
+ let match: RegExpExecArray | null;
2838
+ while ((match = pattern.exec(code)) !== null) {
2839
+ const at = match.index;
2840
+
2841
+ let depthCallee: string | null = null;
2842
+ const stack: string[] = [];
2843
+ for (let i = 0; i < at; i++) {
2844
+ const c = bare[i];
2845
+ if (c === "(") stack.push(calleeBefore(bare, i));
2846
+ else if (c === ")") stack.pop();
2847
+ }
2848
+ depthCallee = stack.length > 0 ? stack[stack.length - 1]! : null;
2849
+
2850
+ let literal: string | null = null;
2851
+ if (bare[at] === " " && code[at] !== " ") {
2852
+ let lo = at;
2853
+ let hi = at;
2854
+ while (lo > 0 && bare[lo - 1] === " ") lo--;
2855
+ while (hi + 1 < bare.length && bare[hi + 1] === " ") hi++;
2856
+ literal = code.slice(lo, hi + 1);
2857
+ }
2858
+
2859
+ const kind: ConfigSiteKind = isPathCall(depthCallee)
2860
+ ? "use"
2861
+ : literal !== null && /\s/.test(literal)
2862
+ ? "mention"
2863
+ : isTextCall(depthCallee)
2864
+ ? "mention"
2865
+ : "use";
2866
+
2867
+ sites.push({ index: at, kind, callee: depthCallee, literal });
2868
+ }
2869
+ return sites;
2870
+ }
2871
+
2872
+ /** Directories CHECK-1 walks. Tests and `test/` are excluded by ADR-002 D4. */
2873
+ const CONFIG_SCAN_DIRS = ["lib", "gates", "scripts", "hooks", "generators"];
2874
+
2875
+ /** The one module allowed to read the config. ADR-002 D1. */
2876
+ const CONFIG_LOADER = "lib/config-loader.ts";
2877
+
2878
+ function walkSources(dir: string, rel: string, out: Array<{ path: string; text: string }>) {
2879
+ let entries;
2880
+ try {
2881
+ entries = readdirSync(dir, { withFileTypes: true });
2882
+ } catch {
2883
+ return;
2884
+ }
2885
+ for (const e of entries) {
2886
+ const abs = join(dir, e.name);
2887
+ const relPath = rel ? `${rel}/${e.name}` : e.name;
2888
+ if (e.isDirectory()) {
2889
+ if (e.name === "test" || e.name === "node_modules") continue;
2890
+ walkSources(abs, relPath, out);
2891
+ continue;
2892
+ }
2893
+ if (!/\.(ts|js)$/.test(e.name) || /\.test\.ts$/.test(e.name)) continue;
2894
+ out.push({ path: relPath, text: readFileSync(abs, "utf-8") });
2895
+ }
2896
+ }
2897
+
2898
+ /** What a scan saw: per-file counts, and how much it actually read. */
2899
+ export interface ConfigAccessScan {
2900
+ /** Repo-relative path -> site count. Allowlisted files are excluded. */
2901
+ counts: Record<string, number>;
2902
+ /** Files walked. ZERO means the scan found nothing to look at. */
2903
+ filesScanned: number;
2904
+ /** Bytes read. Zero with a non-zero file count means empty sources. */
2905
+ bytesScanned: number;
2906
+ }
2907
+
2908
+ /**
2909
+ * CHECK-1's reading: direct config access in TypeScript sources.
2910
+ *
2911
+ * A separate function from the refusal so there is ONE site for the mutation
2912
+ * harness to short-circuit (`.claude/rules/checks-must-be-able-to-fail.md`,
2913
+ * and ADR-002 D4's third mutation).
2914
+ */
2915
+ export function scanConfigAccess(root: string): ConfigAccessScan {
2916
+ const files: Array<{ path: string; text: string }> = [];
2917
+ for (const d of CONFIG_SCAN_DIRS) walkSources(join(root, d), d, files);
2918
+
2919
+ const counts: Record<string, number> = {};
2920
+ let bytesScanned = 0;
2921
+ for (const f of files) {
2922
+ bytesScanned += f.text.length;
2923
+ if (f.path === CONFIG_LOADER) continue;
2924
+ const n = classifyConfigSites(f.text).filter(site => site.kind === "use").length;
2925
+ if (n > 0) counts[f.path] = n;
2926
+ }
2927
+ return { counts, filesScanned: files.length, bytesScanned };
2928
+ }
2929
+
2930
+ /**
2931
+ * CHECK-2's reading: config access inside `workflows/*.js`, prompts included.
2932
+ *
2933
+ * Comments are stripped and literals are NOT, which is the whole point —
2934
+ * `ship.js` is mostly prompt text, and the eleven sites ADR-001's check could
2935
+ * not see all live inside template literals handed to agents.
2936
+ *
2937
+ * **It does NOT use `classifyConfigSites`, and must not** (#415). CHECK-1's
2938
+ * subject is a path being built in code, so a sentence naming the file is
2939
+ * noise. CHECK-2's subject is the sentence: "Read ${PROJECT_ROOT}/…" IS the
2940
+ * violation, and it is prose by construction. Pointing the classifier at this
2941
+ * scan would silently empty the check — every one of its sites would reclassify
2942
+ * as a mention. `test/config-access-mentions.test.ts` SC-1552 runs one sentence
2943
+ * through both scans and asserts they disagree, so the collapse cannot be made
2944
+ * quietly in the name of consistency.
2945
+ */
2946
+ export function scanPromptConfigAccess(root: string): ConfigAccessScan {
2947
+ const dir = join(root, "workflows");
2948
+ const counts: Record<string, number> = {};
2949
+ let filesScanned = 0;
2950
+ let bytesScanned = 0;
2951
+ let entries: string[];
2952
+ try {
2953
+ entries = readdirSync(dir).filter(f => f.endsWith(".js"));
2954
+ } catch {
2955
+ return { counts, filesScanned: 0, bytesScanned: 0 };
2956
+ }
2957
+ for (const f of entries) {
2958
+ const text = readFileSync(join(dir, f), "utf-8");
2959
+ filesScanned++;
2960
+ bytesScanned += text.length;
2961
+ const n = (stripJsComments(text).match(configAccessPattern()) || []).length;
2962
+ if (n > 0) counts[`workflows/${f}`] = n;
2963
+ }
2964
+ return { counts, filesScanned, bytesScanned };
2965
+ }
2966
+
2967
+ /**
2968
+ * The banked violations, read from `.claude/config-access-ratchet.json`.
2969
+ *
2970
+ * Data rather than a constant, because `lib/conformity.ts` travels into every
2971
+ * scaffolded project and rungate's own numbers have no business there. A
2972
+ * consumer with no ratchet file gets `{}` — zero tolerance, which is the
2973
+ * right default for a tree that has never had the defect.
2974
+ *
2975
+ * NOT `.claude/rungate*`, deliberately: this is harness metadata about a
2976
+ * migration, not project config, and routing it through the loader would make
2977
+ * the check depend on the thing it is enforcing access to.
2978
+ */
2979
+ export function readConfigAccessRatchet(
2980
+ root: string,
2981
+ scope: "sources" | "workflows" | "all" = "all",
2982
+ ): Record<string, number> {
2983
+ const p = join(root, ".claude", "config-access-ratchet.json");
2984
+ if (!existsSync(p)) return {};
2985
+ const raw = JSON.parse(readFileSync(p, "utf-8"));
2986
+ const out: Record<string, number> = {};
2987
+ for (const [k, v] of Object.entries(raw)) {
2988
+ if (typeof v !== "number") continue;
2989
+ // One file, two checks. Scoping matters because the both-ways ratchet
2990
+ // complains about a banked entry with no violations left, and CHECK-1
2991
+ // never scans `workflows/` — without this it would demand the removal of
2992
+ // every entry CHECK-2 owns, and vice versa.
2993
+ const isWorkflow = k.startsWith("workflows/");
2994
+ if (scope === "sources" && isWorkflow) continue;
2995
+ if (scope === "workflows" && !isWorkflow) continue;
2996
+ out[k] = v;
2997
+ }
2998
+ return out;
2999
+ }
3000
+
3001
+ /**
3002
+ * Turn a scan into refusals. Empty allows. BOTH DIRECTIONS.
3003
+ *
3004
+ * Over its number refuses, and so does UNDER — an entry that has stopped
3005
+ * being a violation is an entry nobody will ever remove, and the list rots
3006
+ * into one more artefact that certifies nothing. A file absent from the
3007
+ * ratchet is allowed nothing, which is ADR-002 D4's requirement that the
3008
+ * ratchet "refuses on any new file entering the violation set even while the
3009
+ * count is above zero": the migration window is exactly when the next reader
3010
+ * is most likely to be written.
3011
+ *
3012
+ * An EMPTY SCAN REFUSES. A conformity check that silently scans zero files
3013
+ * reports zero violations and is indistinguishable from compliance, which is
3014
+ * this repo's defining defect and would be the most embarrassing possible
3015
+ * place to reproduce it (ADR-002 D4, mutation 5).
3016
+ */
3017
+ export function configAccessViolations(
3018
+ scan: ConfigAccessScan,
3019
+ banked: Record<string, number>,
3020
+ label: string,
3021
+ requireNonEmpty = true,
3022
+ ): string[] {
3023
+ const out: string[] = [];
3024
+ if (requireNonEmpty && scan.filesScanned === 0) {
3025
+ return [
3026
+ `${label}: the scan read NO files. A check that scans nothing reports ` +
3027
+ `zero violations and cannot be told from compliance — refusing rather ` +
3028
+ `than reporting clean (ADR-002 D4).`,
3029
+ ];
3030
+ }
3031
+ if (requireNonEmpty && scan.filesScanned > 0 && scan.bytesScanned === 0) {
3032
+ return [`${label}: ${scan.filesScanned} files were walked and none had any content.`];
3033
+ }
3034
+
3035
+ for (const [file, n] of Object.entries(scan.counts).sort()) {
3036
+ const allowed = banked[file] ?? 0;
3037
+ if (n > allowed) {
3038
+ out.push(
3039
+ `${label}: ${file} has ${n} direct config access site(s), ${allowed} allowed. ` +
3040
+ `Only ${CONFIG_LOADER} may read the config (ADR-002 D1). Use ` +
3041
+ `loadRungateConfig / tryLoadRungateConfig / resolveConfig.`,
3042
+ );
3043
+ } else if (n < allowed) {
3044
+ out.push(
3045
+ `${label}: ${file} is banked at ${allowed} but only ${n} remain — lower the ` +
3046
+ `number in .claude/config-access-ratchet.json in the same commit that earned it.`,
3047
+ );
3048
+ }
3049
+ }
3050
+ for (const [file, allowed] of Object.entries(banked).sort()) {
3051
+ if (allowed > 0 && !(file in scan.counts)) {
3052
+ out.push(
3053
+ `${label}: ${file} is banked at ${allowed} but has no violations left — ` +
3054
+ `remove its entry from .claude/config-access-ratchet.json.`,
3055
+ );
3056
+ }
3057
+ }
3058
+ return out;
3059
+ }
3060
+
3061
+ /**
3062
+ * CHECK-1 — direct config access in TypeScript sources (ADR-002 D4).
3063
+ *
3064
+ * FAILS; does not warn. `DEPTH-1` and `ABSENCE-1` only `console.warn`, and
3065
+ * warnings are how 89 sites accumulated with the policy written down.
3066
+ */
3067
+ export function runConfigAccessValidation(root: string) {
3068
+ describe("Config access (ADR-002 D1)", () => {
3069
+ test("CONFIG-1: only the loader reads the rungate config", () => {
3070
+ const scan = scanConfigAccess(root);
3071
+ const violations = configAccessViolations(
3072
+ scan,
3073
+ readConfigAccessRatchet(root, "sources"),
3074
+ "CONFIG-1",
3075
+ );
3076
+ for (const v of violations) {
3077
+ addFinding({
3078
+ ruleId: "CONFIG-1",
3079
+ severity: "FAIL",
3080
+ file: v.split(": ")[1]?.split(" ")[0] || "",
3081
+ message: v,
3082
+ fixCommand: "Route the read through lib/config-loader.ts",
3083
+ });
3084
+ }
3085
+ expect(violations, violations.join("\n")).toEqual([]);
3086
+ });
3087
+ });
3088
+ }
3089
+
3090
+ /**
3091
+ * CHECK-2 — config access inside workflow prompt text (ADR-002 D4).
3092
+ *
3093
+ * The check ADR-001 did not have, and the reason its single check would have
3094
+ * been insufficient: `ship.js:1637` reaches the config from inside a prompt.
3095
+ * Allowlist is empty — no workflow has any business reading it directly.
3096
+ */
3097
+ export function runPromptConfigAccessValidation(root: string) {
3098
+ describe("Config access in workflows (ADR-002 D4)", () => {
3099
+ test("CONFIG-2: no workflow reaches the rungate config, prompts included", () => {
3100
+ const scan = scanPromptConfigAccess(root);
3101
+ // A project with no workflows/ directory is not in violation; the
3102
+ // empty-scan refusal above is for a scan that should have found files.
3103
+ const violations = configAccessViolations(
3104
+ scan,
3105
+ readConfigAccessRatchet(root, "workflows"),
3106
+ "CONFIG-2",
3107
+ scan.filesScanned > 0,
3108
+ );
3109
+ for (const v of violations) {
3110
+ addFinding({
3111
+ ruleId: "CONFIG-2",
3112
+ severity: "FAIL",
3113
+ file: v.split(": ")[1]?.split(" ")[0] || "",
3114
+ message: v,
3115
+ fixCommand: "Point the prompt at the resolved-config artefact instead",
3116
+ });
3117
+ }
3118
+ expect(violations, violations.join("\n")).toEqual([]);
3119
+ });
3120
+ });
3121
+ }
3122
+
2630
3123
  export function runAbsenceValidation(root: string) {
2631
3124
  describe("Absence validation", () => {
2632
3125
  test("ABSENCE-1: anti-criteria use absence verification", () => {