rungate 0.7.0 → 0.8.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 (108) hide show
  1. package/gates/.gate-salt +1 -0
  2. package/gates/SCHEMA-GUIDE.md +485 -0
  3. package/gates/ac-quality.test.ts +106 -0
  4. package/gates/adversarial.test.ts +283 -0
  5. package/gates/brief-assembler.test.ts +487 -0
  6. package/gates/brief-assembler.ts +448 -0
  7. package/gates/bunfig.toml +2 -0
  8. package/gates/chain.test.ts +91 -0
  9. package/gates/e2e-smoke.test.ts +234 -0
  10. package/gates/error-classifier.test.ts +250 -0
  11. package/gates/error-classifier.ts +99 -0
  12. package/gates/gate-executor.ts +3071 -0
  13. package/gates/orchestrator.test.ts +968 -0
  14. package/gates/orchestrator.ts +827 -0
  15. package/gates/preload.ts +89 -0
  16. package/gates/prompts/ac-adversary.md +20 -0
  17. package/gates/prompts/evidence-validator.md +22 -0
  18. package/gates/prompts/prove-reproducer.md +53 -0
  19. package/gates/prompts.sha256 +3 -0
  20. package/gates/prove.test.ts +164 -0
  21. package/gates/rook-state.test.ts +108 -0
  22. package/gates/run-attribution.ts +290 -0
  23. package/gates/run-gate.ts +163 -0
  24. package/gates/schema-parity.test.ts +378 -0
  25. package/gates/schema.ts +1209 -0
  26. package/gates/self-heal.test.ts +511 -0
  27. package/gates/self-heal.ts +125 -0
  28. package/gates/ship-orchestrator.test.ts +399 -0
  29. package/gates/ship-orchestrator.ts +384 -0
  30. package/gates/spec-compliance-probe.ts +159 -0
  31. package/gates/test-fixtures/broken-no-environments.json +110 -0
  32. package/gates/test-fixtures/consumer-directory-layout.json +90 -0
  33. package/gates/test-fixtures/valid-standard.json +91 -0
  34. package/gates/test-utils.ts +43 -0
  35. package/gates/typecheck-gate.ts +111 -0
  36. package/gates/witness.ts +349 -0
  37. package/gates/workflow.test.ts +2018 -0
  38. package/hooks/ActionVerificationGate.hook.ts +96 -0
  39. package/hooks/AgentBriefGuard.hook.ts +38 -0
  40. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  41. package/hooks/AutoVerifyGate.hook.ts +79 -0
  42. package/hooks/BashToolGuard.hook.ts +65 -0
  43. package/hooks/BashWriteGuard.hook.ts +60 -0
  44. package/hooks/CommitEnforcement.hook.ts +130 -0
  45. package/hooks/DocHygiene.hook.ts +148 -0
  46. package/hooks/GateEnforcement.hook.ts +58 -0
  47. package/hooks/GateResultProtection.hook.ts +95 -0
  48. package/hooks/HarnessAFKGate.hook.ts +85 -0
  49. package/hooks/HookCurrency.hook.ts +99 -0
  50. package/hooks/IssueCloseGuard.hook.ts +149 -0
  51. package/hooks/MergeGuard.hook.ts +58 -0
  52. package/hooks/PostCompact.hook.ts +60 -0
  53. package/hooks/ProjectStateSync.hook.ts +103 -0
  54. package/hooks/SkillGuard.hook.ts +69 -0
  55. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  56. package/hooks/SpecSCGuard.hook.ts +123 -0
  57. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  58. package/hooks/TaskCompleted.hook.ts +51 -0
  59. package/hooks/TeamInit.hook.ts +85 -0
  60. package/hooks/TestSuiteGuard.hook.ts +70 -0
  61. package/hooks/TestSuiteRelease.hook.ts +85 -0
  62. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  63. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  64. package/hooks/WorkflowStateGuard.hook.ts +64 -0
  65. package/hooks/lib/agent-config.json +9 -0
  66. package/hooks/lib/agentDetection.ts +201 -0
  67. package/hooks/lib/comment-template.ts +86 -0
  68. package/hooks/lib/findWorkflow.ts +101 -0
  69. package/hooks/lib/parseStdin.ts +37 -0
  70. package/hooks/lib/paths.ts +111 -0
  71. package/hooks/lib/utils.ts +338 -0
  72. package/lib/affected-tests.ts +29 -0
  73. package/lib/bash-write-guard.ts +627 -0
  74. package/lib/branch-cleanup.ts +279 -7
  75. package/lib/config-trackable.ts +9 -0
  76. package/lib/distribution-currency.ts +55 -5
  77. package/lib/failure-intake.ts +7 -1
  78. package/lib/gate-enforcement.ts +360 -38
  79. package/lib/gate-names.ts +72 -0
  80. package/lib/gate-result-protection.ts +437 -0
  81. package/lib/generators/code-map.ts +55 -4
  82. package/lib/generators/types.ts +27 -1
  83. package/lib/intake-sources.ts +380 -0
  84. package/lib/js-top-level-code.ts +20 -2
  85. package/lib/junit-checks.ts +239 -1
  86. package/lib/late-env-spawn.ts +331 -0
  87. package/lib/launch-base.ts +128 -5
  88. package/lib/package-closure.ts +114 -0
  89. package/lib/paths.ts +96 -3
  90. package/lib/phase2-decomposition.ts +1 -1
  91. package/lib/published-artifact.ts +162 -18
  92. package/lib/sc-id-cross-tree.ts +84 -8
  93. package/lib/scaffold/ai-review-findings.ts +149 -4
  94. package/lib/scaffold/ai-review-step.ts +1006 -132
  95. package/lib/scaffold/defaults.ts +82 -1
  96. package/lib/scaffold/steps.ts +642 -54
  97. package/lib/scanner.ts +4 -2
  98. package/lib/security-verdict.ts +1 -1
  99. package/lib/shell-path-interpolation.ts +594 -0
  100. package/lib/text-dependents.ts +875 -0
  101. package/lib/transcript-checker.ts +6 -0
  102. package/lib/workflow-security.ts +29 -0
  103. package/lib/workflow-taint.ts +732 -0
  104. package/lib/worktree-cleanup.ts +65 -38
  105. package/lib/worktree-repo.ts +32 -2
  106. package/package.json +4 -1
  107. package/scripts/check-installed-hook-currency.ts +825 -0
  108. package/scripts/generate-code-map.ts +13 -8
@@ -111,6 +111,17 @@ function attr(tag: string, name: string): string | null {
111
111
  interface ScannedTestcase {
112
112
  /** The full name, rebuilt from the `<testsuite>` nesting. */
113
113
  name: string;
114
+ /**
115
+ * The source file, as the report spells it — MEASURED on bun 1.3.14,
116
+ * `file="test/ai-review-wif.test.ts"`, repo-relative with the directory
117
+ * on the front (#1172).
118
+ *
119
+ * Read from the `<testcase>` attribute rather than from the outermost
120
+ * `<testsuite>` name, with that name as the fallback. Both carry it
121
+ * today; the attribute is the one that stays correct if a testcase is
122
+ * ever emitted outside a file-level suite.
123
+ */
124
+ file: string;
114
125
  /** The `time` attribute in MILLISECONDS, or `NaN` when it carries none. */
115
126
  ms: number;
116
127
  /** False for a `<skipped />` testcase — filtered out, `.skip` or `.todo`. */
@@ -173,6 +184,7 @@ function scanJunitTestcases(xml: string): { cases: ScannedTestcase[]; skipped: n
173
184
  // Everything above it is a `describe`.
174
185
  const testcase: ScannedTestcase = {
175
186
  name: [...suites.slice(1), attr(rest, "name") ?? ""].join(" > "),
187
+ file: attr(rest, "file") ?? suites[0] ?? "",
176
188
  ms: durationMs(rest),
177
189
  ran: true,
178
190
  failure: null,
@@ -351,6 +363,8 @@ export function unionNames(base: string[] | null, extra: string[]): string[] | n
351
363
  export interface TestcaseDuration {
352
364
  /** The full name, as the console prints it. */
353
365
  name: string;
366
+ /** The source file the report attributes it to, e.g. `test/a.test.ts`. */
367
+ file: string;
354
368
  /** Milliseconds. */
355
369
  ms: number;
356
370
  /** The runner killed it: bun wrote `<failure type="TimeoutError" />`. */
@@ -390,7 +404,7 @@ export function parseJunitDurations(xml: string): JunitDurationReading {
390
404
  const ran = scan.cases.filter(c => c.ran);
391
405
  const durations = ran
392
406
  .filter(c => Number.isFinite(c.ms))
393
- .map(c => ({ name: c.name, ms: c.ms, timedOut: c.failure === "TimeoutError" }));
407
+ .map(c => ({ name: c.name, file: c.file, ms: c.ms, timedOut: c.failure === "TimeoutError" }));
394
408
  return {
395
409
  durations,
396
410
  count: durations.length,
@@ -534,3 +548,227 @@ export function timeoutProximityViolations(
534
548
  }
535
549
  return out;
536
550
  }
551
+
552
+ /* ───────────────────────────────────────────────────────────────────────────
553
+ * #1172: a per-file budget list that can see files that are NOT on it
554
+ *
555
+ * `GIT_FIXTURE_SUITES` names the `ai-review-*` suites whose cases are built
556
+ * on real `git` subprocesses and which therefore declare a calibrated
557
+ * file-level budget instead of inheriting bun's default. `AC-3` of #1140
558
+ * iterates that list and asserts each named file declares one. That holds
559
+ * the list to its claim in **one direction only**: a file that is ON the
560
+ * list must declare. It says nothing about a file that should be on it and
561
+ * is not.
562
+ *
563
+ * So the list can go stale in silence. Someone adds an eighth `ai-review-*`
564
+ * suite built on `checkout()`, it inherits 5000ms, nothing reddens, and the
565
+ * first anyone hears is the "is this red mine?" rebase tax #1140 was filed
566
+ * about. That is the same shape as an allowlist whose own entries are the
567
+ * evidence for them: the budget governs its members and cannot see arrivals.
568
+ *
569
+ * ## Why the structural rule is not the fix, measured
570
+ *
571
+ * "Every `ai-review-*` suite that spawns `bash` and `git` must declare" is
572
+ * over-broad. Measured on 2026-10-22 it catches `ai-review-wif` and
573
+ * `ai-review-baseline-seal`, neither of which has a case above 2500ms.
574
+ * Handing a fast file a 120s ceiling costs hang-detection latency — a
575
+ * genuine hang reports in two minutes instead of five seconds — for no
576
+ * benefit. The criterion that actually qualifies a file is **the measured
577
+ * cost of its fixture**, and that needs a duration reading.
578
+ *
579
+ * ## …and nor is widening the list, which is the cheapest wrong fix
580
+ *
581
+ * Adding today's near-misses to `GIT_FIXTURE_SUITES` changes the membership
582
+ * ROSTER without changing how membership is DETERMINED, so the next arrival
583
+ * is exactly as invisible as this one was. `test/ai-review-fixture-budget.ts`
584
+ * performs that repair over a planted eighth file and measures what it
585
+ * reports, rather than dismissing it in prose.
586
+ *
587
+ * ## So the criterion is DECLARATION, not membership — and the two already disagree
588
+ *
589
+ * This check therefore does not ask "is this file on the list". It asks
590
+ * "does this file declare a budget of its own", read off the TREE. The two
591
+ * are not the same question, and the first real reading taken through this
592
+ * code proved it: over 562 cases of the live `ai-review-*` surface,
593
+ * `ai-review-fixture-budget.test.ts` carried a 5083.13ms case, was **not**
594
+ * on `GIT_FIXTURE_SUITES`, and was in no danger whatever, because it opens
595
+ * with `setDefaultTimeout(gitFixtureTestTimeout())`. A membership criterion
596
+ * reports that file forever; a declaration criterion reports nothing,
597
+ * truthfully, and still reports the eighth suite that declares nothing.
598
+ *
599
+ * The list survives for the job it can do — `budgetSurfaceCoverage` uses it
600
+ * to decide whether a reading COVERS the surface — and for `AC-3`, which
601
+ * holds its named files to declaring. Neither of those gates this check.
602
+ *
603
+ * ## UNMEASURED, never green
604
+ *
605
+ * A `bun test` run cannot read its own JUnit report — the file is written
606
+ * when the run ends — so the population arrives from outside via
607
+ * `SUITE_JUNIT_REPORT`, exactly as in #621. Two readings, not one verdict:
608
+ * `budgetSurfaceCoverage` answers "did this report see the surface at all?"
609
+ * and `budgetMembershipViolations` answers "is anything it saw unbudgeted?".
610
+ * An empty report satisfies the second perfectly, which is why the first
611
+ * exists and why the second stays SILENT on an empty reading rather than
612
+ * refusing it — if both refused, a red row could not say which broke.
613
+ * ──────────────────────────────────────────────────────────────────────── */
614
+
615
+ /** A set of files held to a per-file budget, and the rule for joining it. */
616
+ export interface BudgetSurface {
617
+ /** Names the surface in a failure message, e.g. `the ai-review-* suites`. */
618
+ label: string;
619
+ /**
620
+ * Which files the question is about, matched against the BASENAME.
621
+ *
622
+ * Basename because the two spellings disagree: bun writes
623
+ * `file="test/ai-review-wif.test.ts"` and the member lists in this repo
624
+ * hold bare `"ai-review-wif.test.ts"`. Comparing the two directly is a
625
+ * check that matches nothing and reports clean — the quietest possible
626
+ * version of this defect.
627
+ */
628
+ pattern: RegExp;
629
+ /**
630
+ * Does this file already declare a budget of its own? Read off the TREE.
631
+ *
632
+ * THIS is the criterion, and it is deliberately not "is it on `members`".
633
+ * A file that declares is not inheriting `inheritedMs`, so it is not at
634
+ * risk, whether or not any list knows about it — and the two readings
635
+ * already disagree on the live surface. See the block above.
636
+ */
637
+ declaresOwnBudget: (basename: string) => boolean;
638
+ /**
639
+ * The roster, used ONLY to judge whether a reading covers the surface.
640
+ *
641
+ * It does not gate `budgetMembershipViolations`. If it did, the check
642
+ * would be a list consulting itself about its own completeness, which is
643
+ * the defect #1172 is filed about.
644
+ */
645
+ members: readonly string[];
646
+ /** What a file on this surface inherits when it declares nothing. */
647
+ inheritedMs: number;
648
+ /**
649
+ * The fraction of `inheritedMs` at or above which a non-member qualifies.
650
+ *
651
+ * Not 1.0. A case that has already crossed the inherited budget has
652
+ * already gone red, and a list that only admits files after they have
653
+ * failed is the rebase tax rather than a guard against it. #1140 measured
654
+ * the population at 2500–7500ms against a 5000ms line, so half the
655
+ * inherited budget is the band where a file is one busy afternoon from
656
+ * red.
657
+ */
658
+ qualifyingFraction: number;
659
+ }
660
+
661
+ /** The last path segment, for comparing a report's spelling to a member list. */
662
+ function basenameOf(file: string): string {
663
+ const i = file.lastIndexOf("/");
664
+ return i === -1 ? file : file.slice(i + 1);
665
+ }
666
+
667
+ /** `pattern` without `g`/`y`, whose `lastIndex` makes `.test()` alternate. */
668
+ function stateless(pattern: RegExp): RegExp {
669
+ return new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""));
670
+ }
671
+
672
+ /** Every testcase in `reading` that belongs to `surface`. */
673
+ function onSurface(reading: JunitDurationReading, surface: BudgetSurface): TestcaseDuration[] {
674
+ const re = stateless(surface.pattern);
675
+ return (reading.durations ?? []).filter(d => re.test(basenameOf(d.file)));
676
+ }
677
+
678
+ /**
679
+ * What is wrong with the READING, before anything is concluded from it.
680
+ *
681
+ * A report of the whole suite with the surface filtered out passes
682
+ * `durationCoverageViolations` — it read thousands of durations — and
683
+ * satisfies the membership check by containing none of the files it is
684
+ * about. So the surface has its own coverage question, and it is the one
685
+ * that matters here.
686
+ */
687
+ export function budgetSurfaceCoverage(
688
+ reading: JunitDurationReading,
689
+ surface: BudgetSurface,
690
+ source: string,
691
+ ): string[] {
692
+ if (reading.durations === null) {
693
+ return [
694
+ `UNMEASURED: the JUnit report at ${source} could not be read ` +
695
+ `(${reading.reason ?? "no reason recorded"}), so nothing is known about what ${surface.label} cost (#1172)`,
696
+ ];
697
+ }
698
+ const seen = onSurface(reading, surface);
699
+ if (seen.length === 0) {
700
+ return [
701
+ `UNMEASURED: the JUnit report at ${source} carries ${reading.count} testcase durations and NONE of ` +
702
+ `them is on ${surface.label} — a report that did not see the surface satisfies the membership ` +
703
+ `check by having nothing to check, which is not a measurement (#1172)`,
704
+ ];
705
+ }
706
+ const files = new Set(seen.map(d => basenameOf(d.file)));
707
+ const unseenMembers = surface.members.filter(m => !files.has(m));
708
+ if (unseenMembers.length > 0) {
709
+ return [
710
+ `UNMEASURED: ${unseenMembers.length} of ${surface.members.length} files already on the list do not ` +
711
+ `appear in ${source} (${unseenMembers.join(", ")}) — the reading covers part of ${surface.label}, ` +
712
+ `so a qualifying file outside that part is invisible to it (#1172)`,
713
+ ];
714
+ }
715
+ return [];
716
+ }
717
+
718
+ /**
719
+ * Every file on `surface` that has earned a budget and has not been given
720
+ * one — named, with the case and the duration that qualified it.
721
+ *
722
+ * ## Three classes, and only one of them is a finding
723
+ *
724
+ * | What the report shows | What it means | Reported |
725
+ * |---|---|---|
726
+ * | an UNDECLARED file with a case at or above the qualifying band | it inherits a budget it is about to outgrow | **yes** |
727
+ * | a file that DECLARES, at any duration | it is not inheriting anything; its raised ceiling is why it is slow and green | no |
728
+ * | an undeclared file whose slowest case is under the band | fast, and a 120s ceiling would cost it hang-detection for nothing | no |
729
+ *
730
+ * The second row is what makes this usable rather than circular. A declared
731
+ * file's durations are taken UNDER the raised budget, so comparing them to
732
+ * the inherited default would report every one of them forever and train
733
+ * its reader to ignore the check — the cost #1140 is filed about,
734
+ * reintroduced by the guard against it.
735
+ *
736
+ * SILENT on a reading of nothing, deliberately — `budgetSurfaceCoverage` is
737
+ * the question about an empty reading, and keeping them apart is what makes
738
+ * a red row say which one broke.
739
+ */
740
+ export function budgetMembershipViolations(
741
+ reading: JunitDurationReading,
742
+ surface: BudgetSurface,
743
+ ): string[] {
744
+ if (!Number.isFinite(surface.inheritedMs) || surface.inheritedMs <= 0) {
745
+ return [
746
+ `no usable inherited budget to compare against (${surface.inheritedMs}) — a budget of zero or NaN ` +
747
+ `qualifies every file rather than none, which is noise and not a finding (#1172)`,
748
+ ];
749
+ }
750
+ const floor = surface.inheritedMs * surface.qualifyingFraction;
751
+
752
+ /** The slowest qualifying case per undeclared file, so one file is one row. */
753
+ const worst = new Map<string, TestcaseDuration>();
754
+ for (const d of onSurface(reading, surface)) {
755
+ const base = basenameOf(d.file);
756
+ if (!(d.ms >= floor)) continue;
757
+ // Asked per FILE, not per case, and asked last so a fast file never
758
+ // costs a source read.
759
+ if (surface.declaresOwnBudget(base)) continue;
760
+ const held = worst.get(base);
761
+ if (held === undefined || d.ms > held.ms) worst.set(base, d);
762
+ }
763
+
764
+ return [...worst.entries()]
765
+ .sort(([a], [b]) => a.localeCompare(b))
766
+ .map(
767
+ ([file, d]) =>
768
+ `${file} is on ${surface.label}, declares no budget of its own, and its case "${d.name}" took ` +
769
+ `${d.ms.toFixed(2)}ms — ${((d.ms / surface.inheritedMs) * 100).toFixed(1)}% of the ` +
770
+ `${surface.inheritedMs}ms it inherits. It is one busy run from a red that is about machine load ` +
771
+ `and not about the code. Add it to the budget list and declare the file-level budget, or make ` +
772
+ `it faster (#1172)`,
773
+ );
774
+ }
@@ -0,0 +1,331 @@
1
+ /**
2
+ * Spawn sites that may be relying on an environment Bun does not pass on.
3
+ *
4
+ * ## The runtime divergence, with its control
5
+ *
6
+ * Under Bun, a `process.env` write made AFTER process start does not reach a
7
+ * child spawned with no explicit `env` option. Under Node it does. Measured
8
+ * 2026-10-22, Bun 1.3.14 and Node v26.3.0, same script and same machine:
9
+ *
10
+ * ```ts
11
+ * process.env.RG_LATE_PROBE = "set-in-process";
12
+ * execFileSync("printenv", ["RG_LATE_PROBE"], { encoding: "utf8" });
13
+ * ```
14
+ *
15
+ * | runtime | no `env:` option | `env: { ...process.env }` |
16
+ * |---|---|---|
17
+ * | `bun probe.ts` | **child does not have it** | `"set-in-process"` |
18
+ * | `node probe.ts` | `"set-in-process"` | `"set-in-process"` |
19
+ *
20
+ * **The Node row is why this is a runtime divergence and not a bad probe.**
21
+ * Without it the next reader reasonably concludes that `printenv` or the
22
+ * variable name was at fault; the only difference between the two rows is
23
+ * which binary ran the identical file. It applies to `Bun.spawnSync` too,
24
+ * not only to the `node:child_process` shims — measured separately, both
25
+ * report the process's STARTUP value.
26
+ *
27
+ * Note the second column: the spread is not ceremony. `{ ...process.env }`
28
+ * reads the live object, so an explicit env is both the diagnosis and the
29
+ * whole fix.
30
+ *
31
+ * Anything scaffolded onto Bun inherits this, so it is worth stating
32
+ * wherever this harness tells a consumer how to write a test that spawns.
33
+ *
34
+ * ## Why a scan and not a list
35
+ *
36
+ * The failure is silent. The child takes its default path, and the assertion
37
+ * usually still passes — for a reason unrelated to the feature under test.
38
+ * Found on #1048 only because a mutation row came back 4 where 5 was
39
+ * predicted; the case was green on every tree, including the one with the
40
+ * feature deleted.
41
+ *
42
+ * So the population is DERIVED, never enumerated. A hand-written list of
43
+ * today's members is written by the person who just fixed them, which means
44
+ * it cannot fail on the day it ships and nothing adds tomorrow's member to
45
+ * it. `lateEnvSpawnSites` recomputes the population from the tree on every
46
+ * run, and a new un-exempted instance is red with no list to update.
47
+ *
48
+ * ## What a member is, and what it is not
49
+ *
50
+ * A member is a spawn call, in a test file that ALSO writes `process.env`,
51
+ * which passes no `env:` option. That is a shape worth looking at and not a
52
+ * defect: an env write and a spawn in one file does not mean the child reads
53
+ * the variable. Plenty of writes are consumed in-process, which works fine.
54
+ *
55
+ * The per-site question is **does this child read the variable this test just
56
+ * set?** A site where the answer is no says so in a `late-env-ok:` comment,
57
+ * and the reason has to be long enough to be a reason — see `MIN_REASON`.
58
+ *
59
+ * Comments and string literals are blanked before matching, via
60
+ * `lib/strip-js-comments.ts` with `blankLiterals`. Two of the eight files
61
+ * #1096 listed by hand are in it because a `grep` counted `execSync` inside a
62
+ * comment and a third because it matched `process.env.X === "1"`, which is a
63
+ * READ. A scanner that reads raw source cannot tell a call from a sentence
64
+ * about a call — `.claude/rules/checks-must-be-able-to-fail.md`.
65
+ *
66
+ * Issue: #1096. Found during #1048 (PR #1090).
67
+ */
68
+
69
+ import { readdirSync, readFileSync, statSync } from "fs";
70
+ import { join, relative, sep } from "path";
71
+
72
+ import { stripJsComments } from "./strip-js-comments";
73
+
74
+ /**
75
+ * How long a `late-env-ok:` reason has to be.
76
+ *
77
+ * A marker nobody has to justify is a marker everybody applies, which is the
78
+ * exemption list this scan exists to avoid wearing a different hat.
79
+ * `lib/gate-check-audit.ts` sets the same kind of floor at 80 for a check
80
+ * waiver; this one is lower because the question here is narrower — name the
81
+ * variable and say why the child does not read it.
82
+ */
83
+ export const MIN_REASON = 40;
84
+
85
+ /** The marker that exempts one site, followed by why. */
86
+ export const EXEMPT_MARKER = "late-env-ok:";
87
+
88
+ /**
89
+ * A write to `process.env.<CAPS>`, excluding comparisons.
90
+ *
91
+ * `=(?![=>])` is the whole discrimination: `process.env.X === "1"` is a read,
92
+ * and `process.env.X =>` cannot occur but costs nothing to exclude.
93
+ */
94
+ const ENV_WRITE = /\bprocess\.env\.([A-Z][A-Z0-9_]*)\s*=(?![=>])/g;
95
+
96
+ /** `delete process.env.X` changes the environment just as a write does. */
97
+ const ENV_DELETE = /\bdelete\s+process\.env\.([A-Z][A-Z0-9_]*)/g;
98
+
99
+ /** Every way this repository starts a child process. */
100
+ const SPAWN = /\b(?:Bun\.spawnSync|Bun\.spawn|spawnSync|execFileSync|execSync|spawn|execFile|exec)\s*\(/g;
101
+
102
+ /**
103
+ * An explicit `env` option, in either spelling.
104
+ *
105
+ * The shorthand half is load-bearing and was added after the first run read
106
+ * `test/sync-spec-tests-paths.test.ts:225` as bare. That site builds
107
+ * `const env = { ...process.env }; delete env.HARNESS_ROOT;` and passes
108
+ * `{ cwd, env, … }` — which is not merely explicit, it is the most careful
109
+ * site in the population. A detector that only knew `env:` would have
110
+ * reported the one author who got this exactly right.
111
+ *
112
+ * `(?<![.\w])` keeps `process.env }` out of the shorthand arm: a spread of
113
+ * the whole environment AS the options object is not an env option, and
114
+ * without the guard every `{ ...process.env }` would exempt its own call.
115
+ */
116
+ const ENV_OPTION = /(?<![.\w])env\s*(?::|(?=[,}]))/;
117
+
118
+ export interface LateEnvSite {
119
+ /** Repo-relative, POSIX separators, so a violation message is stable. */
120
+ file: string;
121
+ line: number;
122
+ callee: string;
123
+ /** The variables this file writes late. Named, so the reader can judge. */
124
+ vars: string[];
125
+ /** The stated reason this site does not need an explicit env, if any. */
126
+ exemption: string | null;
127
+ }
128
+
129
+ export class UnreadableScanError extends Error {
130
+ constructor(message: string) {
131
+ super(message);
132
+ this.name = "UnreadableScanError";
133
+ }
134
+ }
135
+
136
+ function testFiles(root: string): string[] {
137
+ const out: string[] = [];
138
+ const walk = (dir: string) => {
139
+ let entries: string[];
140
+ try {
141
+ entries = readdirSync(dir);
142
+ } catch {
143
+ return;
144
+ }
145
+ for (const e of entries) {
146
+ const p = join(dir, e);
147
+ if (statSync(p).isDirectory()) walk(p);
148
+ else if (p.endsWith(".test.ts")) out.push(p);
149
+ }
150
+ };
151
+ walk(join(root, "test"));
152
+ return out.sort();
153
+ }
154
+
155
+ /**
156
+ * The argument list of a call whose `(` is at `open`, or null if unbalanced.
157
+ *
158
+ * Counted over the literal-blanked view, which is the only view a bracket
159
+ * matcher may count over: a `)` inside a prompt string is text.
160
+ */
161
+ function argumentList(blanked: string, open: number): string | null {
162
+ let depth = 0;
163
+ for (let i = open; i < blanked.length; i++) {
164
+ const c = blanked[i];
165
+ if (c === "(") depth++;
166
+ else if (c === ")") {
167
+ depth--;
168
+ if (depth === 0) return blanked.slice(open + 1, i);
169
+ }
170
+ }
171
+ return null;
172
+ }
173
+
174
+ /**
175
+ * The contiguous comment block immediately above line `line` (1-based),
176
+ * plus that line itself so a trailing marker counts.
177
+ */
178
+ function commentBlockAbove(lines: string[], line: number): string {
179
+ /** Only the comment part of a line, so a reason cannot be padded by code. */
180
+ const commentPart = (raw: string): string | null => {
181
+ const t = raw.trim();
182
+ if (t.startsWith("//")) return t.slice(2).trim();
183
+ if (t.startsWith("*/")) return t.slice(2).replace(/^\*+/, "").trim();
184
+ if (t.startsWith("*")) return t.replace(/^\*+/, "").replace(/\*\/\s*$/, "").trim();
185
+ if (t.startsWith("/*")) return t.slice(2).replace(/^\*+/, "").replace(/\*\/\s*$/, "").trim();
186
+ return null;
187
+ };
188
+
189
+ const block: string[] = [];
190
+ for (let i = line - 2; i >= 0; i--) {
191
+ const part = commentPart(lines[i]);
192
+ if (part === null) break;
193
+ block.unshift(part);
194
+ }
195
+ // A trailing marker on the call's own line, comment part only. Without
196
+ // this restriction the reason runs on into the call text and a
197
+ // seven-character excuse measures sixty-six — which is the floor being
198
+ // satisfied by the code it is attached to.
199
+ const own = lines[line - 1] ?? "";
200
+ const slashes = own.indexOf("//");
201
+ if (slashes !== -1) block.push(own.slice(slashes + 2).trim());
202
+ return block.join("\n");
203
+ }
204
+
205
+ /**
206
+ * Every spawn site in a test file that also changes `process.env`.
207
+ *
208
+ * Throws rather than returning `[]` when it can see no test files or no
209
+ * spawn calls at all: an empty population and a scanner that stopped working
210
+ * are the same output, and only one of them is a result
211
+ * (`.claude/rules/checks-must-be-able-to-fail.md`).
212
+ */
213
+ export interface LateEnvReading {
214
+ /** Test files walked. */
215
+ filesScanned: number;
216
+ /** Spawn calls the pattern matched, across all of them. */
217
+ spawnsExamined: number;
218
+ /** Of those, the files that also change `process.env`. */
219
+ candidateFiles: number;
220
+ /** Spawn sites inside a candidate file that pass no `env`. */
221
+ sites: LateEnvSite[];
222
+ }
223
+
224
+ /**
225
+ * The reading, with its own coverage beside it.
226
+ *
227
+ * `1 site` and `1 site of 3 examined` are the same number and different
228
+ * facts, and `1 of 900` is a third. A scan that reports a verdict reports
229
+ * how much it read — `.claude/rules/config-access.md`'s `36/426`.
230
+ */
231
+ export function lateEnvSpawnReading(root: string): LateEnvReading {
232
+ return scan(root);
233
+ }
234
+
235
+ export function lateEnvSpawnSites(root: string): LateEnvSite[] {
236
+ return scan(root).sites;
237
+ }
238
+
239
+ function scan(root: string): LateEnvReading {
240
+ const files = testFiles(root);
241
+ if (files.length === 0) {
242
+ throw new UnreadableScanError(`no test files under ${join(root, "test")} — the walk found nothing to scan`);
243
+ }
244
+
245
+ const sites: LateEnvSite[] = [];
246
+ let spawnsSeen = 0;
247
+ let candidateFiles = 0;
248
+
249
+ for (const file of files) {
250
+ const raw = readFileSync(file, "utf-8");
251
+ const blanked = stripJsComments(raw, { blankLiterals: true });
252
+
253
+ const vars = [
254
+ ...new Set([
255
+ ...[...blanked.matchAll(ENV_WRITE)].map(m => m[1]),
256
+ ...[...blanked.matchAll(ENV_DELETE)].map(m => m[1]),
257
+ ]),
258
+ ].sort();
259
+
260
+ const spawns = [...blanked.matchAll(SPAWN)];
261
+ spawnsSeen += spawns.length;
262
+ if (vars.length === 0) continue;
263
+ candidateFiles++;
264
+
265
+ const rawLines = raw.split("\n");
266
+ for (const m of spawns) {
267
+ const at = m.index!;
268
+ const open = blanked.indexOf("(", at);
269
+ const args = argumentList(blanked, open);
270
+ if (args === null) {
271
+ throw new UnreadableScanError(
272
+ `${relative(root, file)}: a spawn call's argument list is unbalanced — the scan cannot say whether it passes env`,
273
+ );
274
+ }
275
+ if (ENV_OPTION.test(args)) continue;
276
+
277
+ const line = raw.slice(0, at).split("\n").length;
278
+ // The marker is read from RAW source: `stripJsComments` preserves every
279
+ // offset but blanks the comment it lives in.
280
+ //
281
+ // The window is the comment block ATTACHED to the call — every
282
+ // contiguous comment line immediately above it, plus the call's own
283
+ // line for a trailing marker. A fixed count of lines was the first
284
+ // version and it is the wrong shape: a reason long enough to satisfy
285
+ // MIN_REASON usually needs more lines than the window allows, so the
286
+ // floor and the window would fight each other and the way to win is
287
+ // to write a shorter reason.
288
+ const window = commentBlockAbove(rawLines, line);
289
+ const marked = window.indexOf(EXEMPT_MARKER);
290
+ const reason = marked === -1
291
+ ? null
292
+ : window.slice(marked + EXEMPT_MARKER.length)
293
+ .split("\n").map(l => l.replace(/^[\s*/]+/, "")).join(" ").trim();
294
+
295
+ sites.push({
296
+ file: relative(root, file).split(sep).join("/"),
297
+ line,
298
+ callee: m[0].replace(/\s*\($/, ""),
299
+ vars,
300
+ exemption: reason,
301
+ });
302
+ }
303
+ }
304
+
305
+ if (spawnsSeen === 0) {
306
+ throw new UnreadableScanError(
307
+ "no spawn calls were found in any test file — the spawn pattern has stopped matching",
308
+ );
309
+ }
310
+ return { filesScanned: files.length, spawnsExamined: spawnsSeen, candidateFiles, sites };
311
+ }
312
+
313
+ /**
314
+ * The sites that are neither explicit nor justified.
315
+ *
316
+ * Split from the scan so a case can assert the POPULATION is non-empty while
317
+ * asserting the violations are empty. Those are different claims, and a scan
318
+ * that found nothing satisfies the second one on its own.
319
+ */
320
+ export function lateEnvSpawnViolations(root: string): string[] {
321
+ return scan(root).sites
322
+ .filter(s => s.exemption === null || s.exemption.length < MIN_REASON)
323
+ .map(s =>
324
+ `${s.file}:${s.line} ${s.callee} passes no env: option, and this file writes ` +
325
+ `${s.vars.join(", ")}. Under Bun the child will NOT see those writes. Pass ` +
326
+ `env: { ...process.env } — or, if the child does not read them, say why in a ` +
327
+ `"${EXEMPT_MARKER} <reason>" comment within three lines above the call ` +
328
+ `(at least ${MIN_REASON} characters).` +
329
+ (s.exemption === null ? "" : ` The reason given is ${s.exemption.length} characters.`),
330
+ );
331
+ }