rungate 0.2.0 → 0.3.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 (282) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/canary.ts +117 -0
  11. package/lib/check-registry.ts +226 -0
  12. package/lib/ci-checkout.ts +400 -0
  13. package/lib/cli-commands.ts +137 -0
  14. package/lib/compliance-backfill.ts +220 -0
  15. package/lib/compliance-report.ts +504 -0
  16. package/lib/compliance.ts +361 -0
  17. package/lib/config-loader.ts +255 -0
  18. package/lib/conformity.ts +1818 -131
  19. package/lib/container-provenance.ts +230 -0
  20. package/lib/create-brief.ts +150 -0
  21. package/lib/create-sc.ts +272 -0
  22. package/lib/deep-merge.ts +69 -0
  23. package/lib/dev-liveness.ts +214 -0
  24. package/lib/directive-extractor.ts +210 -0
  25. package/lib/distribution-standing.ts +113 -0
  26. package/lib/doc-hygiene.ts +238 -0
  27. package/lib/eval-criteria.ts +6 -0
  28. package/lib/evidence-portability.ts +123 -0
  29. package/lib/evidence-prevalidator.ts +390 -0
  30. package/lib/evidence-required.ts +150 -0
  31. package/lib/evidence-satisfiability.ts +288 -0
  32. package/lib/frontmatter.ts +163 -0
  33. package/lib/gap-scanner.ts +348 -0
  34. package/lib/gate-enforcement.ts +366 -0
  35. package/lib/generators/agent-briefs.ts +136 -0
  36. package/lib/generators/agents-md.ts +506 -0
  37. package/lib/generators/code-map.ts +60 -0
  38. package/lib/generators/types.ts +184 -0
  39. package/lib/git-ref-normalizer.ts +107 -0
  40. package/lib/github.ts +539 -0
  41. package/lib/harness-identity.ts +63 -0
  42. package/lib/hill-climb.ts +164 -0
  43. package/lib/instruction-effectiveness.ts +131 -0
  44. package/lib/issue-closure-audit.ts +225 -0
  45. package/lib/issue-create-override.ts +343 -0
  46. package/lib/js-top-level-code.ts +250 -0
  47. package/lib/liveness-contradiction.ts +149 -0
  48. package/lib/organize.ts +505 -0
  49. package/lib/paths.ts +197 -6
  50. package/lib/post-fix-verify.ts +157 -0
  51. package/lib/prior-branch.ts +489 -0
  52. package/lib/project-state-shape.ts +166 -0
  53. package/lib/promote-outputs.ts +156 -0
  54. package/lib/prove-label-gate.ts +35 -0
  55. package/lib/reachability.ts +302 -0
  56. package/lib/release-preflight.ts +186 -0
  57. package/lib/rule-health-pipeline.ts +264 -0
  58. package/lib/rule-health-trend.ts +161 -0
  59. package/lib/rule-provenance.ts +149 -0
  60. package/lib/rule-registry.ts +128 -0
  61. package/lib/rungate-schema.ts +114 -4
  62. package/lib/sc-claim-forms.ts +179 -0
  63. package/lib/sc-cover.ts +150 -0
  64. package/lib/sc-guard.ts +157 -0
  65. package/lib/sc-ids.ts +344 -0
  66. package/lib/scaffold/defaults.ts +165 -0
  67. package/lib/scaffold/managed-workflow.ts +370 -0
  68. package/lib/scaffold/owned-files.ts +265 -0
  69. package/lib/scaffold/steps.ts +2680 -0
  70. package/lib/scanner.ts +701 -0
  71. package/lib/screenshot-upload.ts +73 -0
  72. package/lib/secret-patterns.ts +112 -0
  73. package/lib/security-verdict.ts +616 -0
  74. package/lib/signal-phrases.ts +1 -0
  75. package/lib/spec-change-conformity.ts +80 -0
  76. package/lib/spec-files.ts +62 -0
  77. package/lib/spec-registry.ts +133 -0
  78. package/lib/spec-updater.ts +96 -0
  79. package/lib/stale-cleanup.ts +224 -0
  80. package/lib/stale-issue-scanner.ts +36 -0
  81. package/lib/strip-js-comments.ts +269 -0
  82. package/lib/suite-measurement.ts +228 -0
  83. package/lib/task-completion-checks.ts +177 -0
  84. package/lib/test-suite-lock.ts +1136 -0
  85. package/lib/transcript-checker.ts +1140 -0
  86. package/lib/validators/spec-validators.ts +171 -0
  87. package/lib/verdict-capture.ts +73 -0
  88. package/lib/verified-push.ts +358 -0
  89. package/lib/workflow-security.ts +174 -0
  90. package/lib/worktree-cleanup.ts +250 -0
  91. package/lib/worktree-collect.ts +283 -0
  92. package/lib/worktree-isolation.ts +82 -0
  93. package/package.json +36 -3
  94. package/prompts/ac-adversary.md +14 -2
  95. package/prompts/aditi.md +5 -0
  96. package/prompts/blast-radius.md +5 -0
  97. package/prompts/container-verify.md +5 -0
  98. package/prompts/discovery.md +4 -0
  99. package/prompts/environment.md +5 -0
  100. package/prompts/evidence-hierarchy.md +5 -0
  101. package/prompts/evidence-validator.md +11 -0
  102. package/prompts/marcus.md +5 -0
  103. package/prompts/prevention.md +5 -0
  104. package/prompts/prove-reproducer.md +12 -0
  105. package/prompts/quinn-decision-tree.md +5 -0
  106. package/prompts/quinn-ui-brief.md +5 -0
  107. package/prompts/quinn.md +5 -0
  108. package/prompts/rca.md +5 -0
  109. package/prompts/read-before-write.md +4 -0
  110. package/prompts/regression.md +5 -0
  111. package/prompts/serena.md +5 -0
  112. package/scripts/audit-specs.ts +464 -0
  113. package/scripts/convert-spec.ts +293 -0
  114. package/scripts/create-sc.ts +92 -0
  115. package/scripts/create-spec.ts +166 -0
  116. package/scripts/extract-constraints.ts +4 -3
  117. package/scripts/generate-code-map.ts +1 -1
  118. package/scripts/scaffold-project.ts +138 -1426
  119. package/scripts/sync-spec-tests.ts +211 -126
  120. package/.claude/agents/aditi.md +0 -47
  121. package/.claude/agents/marcus.md +0 -50
  122. package/.claude/agents/quinn.md +0 -58
  123. package/.claude/agents/rook.md +0 -47
  124. package/.claude/agents/serena.md +0 -46
  125. package/.claude/rungate.json +0 -11
  126. package/.fallowrc.json +0 -28
  127. package/.github/copilot-instructions.md +0 -20
  128. package/.rungate/conformity-findings.json +0 -648
  129. package/AGENTS.md +0 -106
  130. package/CODE-MAP.md +0 -50
  131. package/HARNESS.md +0 -88
  132. package/bun.lock +0 -26
  133. package/bunfig.toml +0 -2
  134. package/config/brief-policies.json +0 -28
  135. package/config/ceremony-profiles.json +0 -212
  136. package/config/consumer-cascade-map.json +0 -24
  137. package/config/doc-cascade-map.json +0 -24
  138. package/config/eval.json +0 -84
  139. package/config/profiles/account-plan.yaml +0 -36
  140. package/config/profiles/campaign.yaml +0 -94
  141. package/config/prove-evidence.schema.json +0 -65
  142. package/config/spec-policies.json +0 -36
  143. package/config/workflow-schema.json +0 -281
  144. package/gates/SCHEMA-GUIDE.md +0 -121
  145. package/gates/ac-quality.test.ts +0 -106
  146. package/gates/adversarial.test.ts +0 -274
  147. package/gates/brief-assembler.test.ts +0 -429
  148. package/gates/brief-assembler.ts +0 -334
  149. package/gates/bunfig.toml +0 -2
  150. package/gates/chain.test.ts +0 -91
  151. package/gates/e2e-smoke.test.ts +0 -234
  152. package/gates/error-classifier.test.ts +0 -249
  153. package/gates/error-classifier.ts +0 -89
  154. package/gates/orchestrator.test.ts +0 -950
  155. package/gates/orchestrator.ts +0 -569
  156. package/gates/preload.ts +0 -77
  157. package/gates/prompts/ac-adversary.md +0 -20
  158. package/gates/prompts/evidence-validator.md +0 -22
  159. package/gates/prompts/prove-reproducer.md +0 -53
  160. package/gates/prove.test.ts +0 -164
  161. package/gates/run-gate.ts +0 -936
  162. package/gates/schema-parity.test.ts +0 -197
  163. package/gates/schema.ts +0 -362
  164. package/gates/self-heal.test.ts +0 -511
  165. package/gates/self-heal.ts +0 -121
  166. package/gates/ship-orchestrator.test.ts +0 -379
  167. package/gates/ship-orchestrator.ts +0 -363
  168. package/gates/test-fixtures/broken-no-environments.json +0 -60
  169. package/gates/test-fixtures/valid-standard.json +0 -54
  170. package/gates/test-utils.ts +0 -43
  171. package/gates/witness.ts +0 -220
  172. package/gates/workflow.test.ts +0 -1053
  173. package/hooks/AgentBriefGuard.hook.ts +0 -586
  174. package/hooks/AgentVerdictCapture.hook.ts +0 -134
  175. package/hooks/AutoVerifyGate.hook.ts +0 -76
  176. package/hooks/GateEnforcement.hook.ts +0 -273
  177. package/hooks/IssueCloseGuard.hook.ts +0 -116
  178. package/hooks/MergeGuard.hook.ts +0 -55
  179. package/hooks/StaleTTLCleanup.hook.ts +0 -133
  180. package/hooks/VerifyPhaseLock.hook.ts +0 -81
  181. package/hooks/WorkflowStateGuard.hook.ts +0 -37
  182. package/hooks/lib/agentDetection.ts +0 -70
  183. package/hooks/lib/findWorkflow.ts +0 -101
  184. package/hooks/lib/parseStdin.ts +0 -37
  185. package/hooks/lib/paths.ts +0 -111
  186. package/hooks/lib/utils.ts +0 -81
  187. package/reference/migration-manifest.json +0 -554
  188. package/reference/prompts/agent-aditi.md +0 -38
  189. package/reference/prompts/agent-marcus.md +0 -38
  190. package/reference/prompts/agent-quinn.md +0 -38
  191. package/reference/prompts/agent-rook.md +0 -37
  192. package/reference/prompts/agent-serena.md +0 -37
  193. package/reference/prompts/council-skill.md +0 -170
  194. package/reference/prompts/goal-skill.md +0 -235
  195. package/reference/prompts/prove-skill.md +0 -283
  196. package/reference/prompts/quinn-standard.md +0 -246
  197. package/reference/prompts/ship-convergence.md +0 -65
  198. package/reference/prompts/ship-escalation.md +0 -43
  199. package/reference/prompts/ship-iteration.md +0 -382
  200. package/reference/prompts/ship-pending-patches.md +0 -246
  201. package/reference/prompts/ship-reference.md +0 -250
  202. package/reference/prompts/ship-skill.md +0 -347
  203. package/reference/prompts/ship-templates.md +0 -215
  204. package/reference/scripts/batch-status.sh +0 -68
  205. package/reference/scripts/chain-compat-check.sh +0 -67
  206. package/reference/scripts/context-audit.sh +0 -314
  207. package/reference/scripts/dead-export-check.sh +0 -61
  208. package/reference/scripts/generate-qc-tables.sh +0 -92
  209. package/reference/scripts/harness-init.sh +0 -111
  210. package/reference/scripts/pai-054-baseline-check.sh +0 -40
  211. package/reference/scripts/prove-smoke-test.sh +0 -112
  212. package/reference/scripts/setup-keychain-salt.sh +0 -12
  213. package/reference/scripts/skill-optimizer-friday.sh +0 -88
  214. package/reference/scripts/skill-qc-test.sh +0 -351
  215. package/reference/scripts/skill-synthesize-tonight.sh +0 -66
  216. package/reference/specs/HARNESS-EXTRACTION-SPEC.md +0 -263
  217. package/reference/specs/harness-v3-bash-deletion-plan.md +0 -65
  218. package/reference/specs/harness-v3-migration-plan.md +0 -188
  219. package/scripts/decision-reconcile.sh +0 -74
  220. package/scripts/decision-reconcile.ts +0 -152
  221. package/scripts/git-hooks/pre-commit +0 -76
  222. package/scripts/git-hooks/pre-push +0 -271
  223. package/scripts/harness-skill-check.sh +0 -52
  224. package/scripts/lib/gap-emit.sh +0 -65
  225. package/scripts/lib/jq-update.sh +0 -30
  226. package/scripts/lib/resolve-slug.sh +0 -30
  227. package/scripts/lib/verify-spec-compliance.sh +0 -102
  228. package/scripts/prove-backfill.sh +0 -87
  229. package/scripts/scaffold-rungate-config.ts +0 -91
  230. package/scripts/self-containment-check.sh +0 -109
  231. package/scripts/skill-qc-validator.sh +0 -402
  232. package/scripts/slug-resolver.sh +0 -14
  233. package/specs/BOOTSTRAP-DATA-FLOW-SPEC.md +0 -2493
  234. package/specs/BOOTSTRAP-TEST-PLAN.md +0 -571
  235. package/specs/HARNESS-GATES.md +0 -256
  236. package/specs/HARNESS-SKILL-CHAIN.md +0 -286
  237. package/specs/HARNESS-SKILL-CONTRACT.md +0 -93
  238. package/specs/HARNESS-STANDARD.md +0 -488
  239. package/specs/SPEC-TEMPLATE.md +0 -53
  240. package/specs/bootstrap-data-flow.png +0 -0
  241. package/specs/harness-automation-matrix.md +0 -314
  242. package/specs/harness-automation-matrix.rules.json +0 -64
  243. package/test/anti.test.ts +0 -80
  244. package/test/contract-negative.test.ts +0 -86
  245. package/test/contract.test.ts +0 -158
  246. package/test/external-deps.test.ts +0 -48
  247. package/test/fixtures/golden-project/.env.example +0 -3
  248. package/test/fixtures/golden-project/Makefile +0 -7
  249. package/test/fixtures/golden-project/docs/adr/ADR-001-framework.md +0 -23
  250. package/test/fixtures/golden-project/docs/setup-guide.md +0 -10
  251. package/test/fixtures/golden-project/package.json +0 -10
  252. package/test/fixtures/golden-project/specs/api-spec.md +0 -20
  253. package/test/fixtures/golden-project/src/auth.ts +0 -8
  254. package/test/fixtures/golden-project/src/db.ts +0 -11
  255. package/test/fixtures/golden-project/src/index.ts +0 -19
  256. package/test/fixtures/golden-project/src/utils/format.ts +0 -3
  257. package/test/fixtures/golden-project/test/auth.test.ts +0 -15
  258. package/test/fixtures/golden-project/tsconfig.json +0 -12
  259. package/test/meta-sc-coverage.test.ts +0 -159
  260. package/test/phase-0.test.ts +0 -846
  261. package/test/phase-1.test.ts +0 -617
  262. package/test/phase-2.test.ts +0 -620
  263. package/test/phase-3.test.ts +0 -99
  264. package/test/scaffold-conformity.test.ts +0 -8
  265. package/test/schema-canary.test.ts +0 -51
  266. package/test/spec-compliance-auto.test.ts +0 -64
  267. package/test/spec-compliance.test.ts +0 -295
  268. package/test/spec-discovery.test.ts +0 -68
  269. package/test/spec-drift.test.ts +0 -5
  270. package/test/structure.test.ts +0 -165
  271. package/test/unit/agent-brief-guard-ship.test.ts +0 -293
  272. package/test/unit/extract-constraints.test.ts +0 -145
  273. package/test/unit/issue-close-guard.test.ts +0 -204
  274. package/test/unit/scaffold-project.test.ts +0 -417
  275. package/test/unit/skill-cooccurrence.test.ts +0 -177
  276. package/test/unit/skill-sequence-logger.test.ts +0 -244
  277. package/test/unit/workflow-state-guard.test.ts +0 -95
  278. package/workflows/batch-ship.js +0 -295
  279. package/workflows/council.js +0 -481
  280. package/workflows/prove.js +0 -560
  281. package/workflows/ship.js +0 -789
  282. package/workflows/verify.js +0 -236
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Instruction compliance scoring for agent-read files.
3
+ *
4
+ * Wraps agnix (SC-180) and RepoRails (SC-181) via Bun.spawnSync.
5
+ * Does NOT reimplement scoring with regex (SC-240).
6
+ *
7
+ * Layer 1: runTemplateCompliance() — scores instruction language via external tools
8
+ * Layer 2: runGeneratedCompliance() — verifies scaffold doesn't degrade quality
9
+ * Layer 3: runBehavioralCompliance() — spawns agent + auditor (future)
10
+ */
11
+ import { existsSync, readFileSync, readdirSync, mkdirSync, writeFileSync } from "fs";
12
+ import { join, relative } from "path";
13
+
14
+ // ── Types ──────────────────────────────────────────────────
15
+
16
+ export interface InstructionFinding {
17
+ file: string;
18
+ line: number;
19
+ rule: string;
20
+ source: "agnix" | "reporails";
21
+ severity: "HIGH" | "MEDIUM" | "LOW";
22
+ category: string;
23
+ message: string;
24
+ suggestion: string;
25
+ }
26
+
27
+ export interface FileScore {
28
+ file: string;
29
+ agnixFindings: number;
30
+ reporailsFindings: number;
31
+ reporailsQuality: number | null;
32
+ findings: InstructionFinding[];
33
+ }
34
+
35
+ export interface ComplianceReport {
36
+ timestamp: string;
37
+ layer: "template" | "generated" | "behavioral";
38
+ surface: string[];
39
+ files: FileScore[];
40
+ overallQuality: number | null;
41
+ totalFindings: number;
42
+ highCount: number;
43
+ toolsAvailable: { agnix: boolean; reporails: boolean };
44
+ }
45
+
46
+ // ── Tool Runners ───────────────────────────────────────────
47
+
48
+ interface AgnixDiagnostic {
49
+ level: string;
50
+ rule: string;
51
+ file: string;
52
+ line: number;
53
+ message: string;
54
+ suggestion?: string;
55
+ rule_severity?: string;
56
+ category?: string;
57
+ }
58
+
59
+ interface AgnixOutput {
60
+ diagnostics: AgnixDiagnostic[];
61
+ }
62
+
63
+ function runAgnixBatch(paths: string[]): AgnixDiagnostic[] | null {
64
+ try {
65
+ const result = Bun.spawnSync(["agnix", ...paths, "--format", "json"], {
66
+ timeout: 15_000,
67
+ env: { ...process.env, NODE_NO_WARNINGS: "1" },
68
+ });
69
+ const stdout = result.stdout.toString().trim();
70
+ if (!stdout) return null;
71
+ const parsed: AgnixOutput = JSON.parse(stdout);
72
+ return parsed.diagnostics || [];
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+
78
+ interface RepoRailsFinding {
79
+ line: number;
80
+ severity: string;
81
+ rule: string;
82
+ category: string;
83
+ leverage?: string;
84
+ message: string;
85
+ fix?: string;
86
+ }
87
+
88
+ interface RepoRailsOutput {
89
+ quality: number;
90
+ level: string;
91
+ files: Record<string, { findings: RepoRailsFinding[] }>;
92
+ }
93
+
94
+ /**
95
+ * RepoRails ships only as an npx package here, so every invocation pays a cold
96
+ * `npx` resolve (~8s). Running the surface one file at a time serially put the
97
+ * whole scan at ~257s. These run concurrently instead.
98
+ */
99
+ async function runRepoRailsOne(path: string): Promise<RepoRailsOutput | null> {
100
+ try {
101
+ const proc = Bun.spawn(["npx", "@reporails/cli", "check", path, "--format", "json"], {
102
+ stdout: "pipe",
103
+ stderr: "ignore",
104
+ env: { ...process.env, NODE_NO_WARNINGS: "1" },
105
+ });
106
+ const timer = setTimeout(() => proc.kill(), 60_000);
107
+ try {
108
+ const stdout = (await new Response(proc.stdout).text()).trim();
109
+ await proc.exited;
110
+ if (!stdout) return null;
111
+ return JSON.parse(stdout) as RepoRailsOutput;
112
+ } finally {
113
+ clearTimeout(timer);
114
+ }
115
+ } catch {
116
+ return null;
117
+ }
118
+ }
119
+
120
+ /** How many RepoRails processes to keep in flight at once. */
121
+ export const REPORAILS_CONCURRENCY = 8;
122
+
123
+ /** Runs `fn` over `items` with at most `limit` in flight. Results keep input order. */
124
+ export async function mapWithConcurrency<T, R>(
125
+ items: T[],
126
+ limit: number,
127
+ fn: (item: T) => Promise<R>,
128
+ ): Promise<R[]> {
129
+ const results = new Array<R>(items.length);
130
+ let next = 0;
131
+
132
+ const workers = Array.from(
133
+ { length: Math.max(1, Math.min(limit, items.length)) },
134
+ async () => {
135
+ while (true) {
136
+ const i = next++;
137
+ if (i >= items.length) return;
138
+ results[i] = await fn(items[i]);
139
+ }
140
+ },
141
+ );
142
+
143
+ await Promise.all(workers);
144
+ return results;
145
+ }
146
+
147
+ // ── Severity Mapping ───────────────────────────────────────
148
+
149
+ function mapAgnixSeverity(level: string, ruleSeverity?: string): "HIGH" | "MEDIUM" | "LOW" {
150
+ if (ruleSeverity === "HIGH" || level === "error") return "HIGH";
151
+ if (ruleSeverity === "MEDIUM" || level === "warning") return "MEDIUM";
152
+ return "LOW";
153
+ }
154
+
155
+ function mapRepoRailsSeverity(severity: string): "HIGH" | "MEDIUM" | "LOW" {
156
+ if (severity === "error") return "HIGH";
157
+ if (severity === "warning") return "MEDIUM";
158
+ return "LOW";
159
+ }
160
+
161
+ // ── Compliance Surface ─────────────────────────────────────
162
+
163
+ const DEFAULT_SURFACE = [
164
+ "prompts",
165
+ "AGENTS.md",
166
+ ".claude/agents",
167
+ "CLAUDE.md",
168
+ ];
169
+
170
+ export function collectComplianceSurface(root: string, surface?: string[]): string[] {
171
+ const patterns = surface || DEFAULT_SURFACE;
172
+ const files: string[] = [];
173
+
174
+ for (const pattern of patterns) {
175
+ const full = join(root, pattern);
176
+ if (!existsSync(full)) continue;
177
+
178
+ try {
179
+ const stat = require("fs").statSync(full);
180
+ if (stat.isDirectory()) {
181
+ for (const f of readdirSync(full).filter(f => f.endsWith(".md"))) {
182
+ files.push(join(full, f));
183
+ }
184
+ } else {
185
+ files.push(full);
186
+ }
187
+ } catch {}
188
+ }
189
+
190
+ return files;
191
+ }
192
+
193
+ // ── Tool Availability ──────────────────────────────────────
194
+
195
+ function checkToolAvailable(command: string, args: string[]): boolean {
196
+ try {
197
+ const result = Bun.spawnSync([command, ...args], { timeout: 5_000 });
198
+ return result.exitCode === 0 || result.stdout.toString().length > 0;
199
+ } catch {
200
+ return false;
201
+ }
202
+ }
203
+
204
+ // ── Layer 1: Template Compliance ───────────────────────────
205
+
206
+ export interface TemplateComplianceOpts {
207
+ surface?: string[];
208
+ writeReport?: boolean;
209
+ }
210
+
211
+ export async function runTemplateCompliance(
212
+ root: string,
213
+ opts?: TemplateComplianceOpts,
214
+ ): Promise<ComplianceReport> {
215
+ const files = collectComplianceSurface(root, opts?.surface);
216
+
217
+ const agnixAvailable = checkToolAvailable("agnix", ["--version"]);
218
+ const reporailsAvailable = checkToolAvailable("npx", ["@reporails/cli", "version"]);
219
+
220
+ // agnix: batch mode works fine for file attribution
221
+ const agnixByFile = new Map<string, AgnixDiagnostic[]>();
222
+ // RepoRails: per-file mode — batch drops findings for small files
223
+ const rrByFile = new Map<string, { quality: number | null; findings: RepoRailsFinding[] }>();
224
+
225
+ if (agnixAvailable) {
226
+ const results = runAgnixBatch(files);
227
+ if (results) {
228
+ for (const d of results) {
229
+ const key = d.file;
230
+ if (!agnixByFile.has(key)) agnixByFile.set(key, []);
231
+ agnixByFile.get(key)!.push(d);
232
+ }
233
+ }
234
+ }
235
+
236
+ if (reporailsAvailable && files.length > 0) {
237
+ const results = await mapWithConcurrency(files, REPORAILS_CONCURRENCY, runRepoRailsOne);
238
+ files.forEach((filePath, i) => {
239
+ const result = results[i];
240
+ if (!result) return;
241
+ rrByFile.set(relative(root, filePath), {
242
+ quality: result.quality,
243
+ findings: Object.values(result.files).flatMap(d => d.findings),
244
+ });
245
+ });
246
+ }
247
+
248
+ const fileScores: FileScore[] = [];
249
+
250
+ for (const filePath of files) {
251
+ const relPath = relative(root, filePath);
252
+ const findings: InstructionFinding[] = [];
253
+ let reporailsQuality: number | null = null;
254
+
255
+ const agnixResults = agnixByFile.get(relPath) || agnixByFile.get(filePath) || [];
256
+ for (const d of agnixResults) {
257
+ findings.push({
258
+ file: relPath,
259
+ line: d.line,
260
+ rule: `AGNIX-${d.rule}`,
261
+ source: "agnix",
262
+ severity: mapAgnixSeverity(d.level, d.rule_severity),
263
+ category: d.category || "general",
264
+ message: d.message,
265
+ suggestion: d.suggestion || "",
266
+ });
267
+ }
268
+
269
+ const rrData = rrByFile.get(relPath) || rrByFile.get(filePath);
270
+ if (rrData) {
271
+ reporailsQuality = rrData.quality;
272
+ for (const f of rrData.findings) {
273
+ findings.push({
274
+ file: relPath,
275
+ line: f.line,
276
+ rule: `REPORAILS-${f.rule}`,
277
+ source: "reporails",
278
+ severity: mapRepoRailsSeverity(f.severity),
279
+ category: f.category || "general",
280
+ message: f.message,
281
+ suggestion: f.fix || "",
282
+ });
283
+ }
284
+ }
285
+
286
+ fileScores.push({
287
+ file: relPath,
288
+ agnixFindings: findings.filter(f => f.source === "agnix").length,
289
+ reporailsFindings: findings.filter(f => f.source === "reporails").length,
290
+ reporailsQuality,
291
+ findings,
292
+ });
293
+ }
294
+
295
+ const totalFindings = fileScores.reduce((sum, f) => sum + f.findings.length, 0);
296
+ const highCount = fileScores.reduce(
297
+ (sum, f) => sum + f.findings.filter(fi => fi.severity === "HIGH").length,
298
+ 0,
299
+ );
300
+
301
+ const qualityScores = fileScores.filter(f => f.reporailsQuality !== null);
302
+ const overallQuality = qualityScores.length > 0
303
+ ? qualityScores.reduce((sum, f) => sum + f.reporailsQuality!, 0) / qualityScores.length
304
+ : null;
305
+
306
+ const report: ComplianceReport = {
307
+ timestamp: new Date().toISOString(),
308
+ layer: "template",
309
+ surface: files.map(f => relative(root, f)),
310
+ files: fileScores,
311
+ overallQuality,
312
+ totalFindings,
313
+ highCount,
314
+ toolsAvailable: { agnix: agnixAvailable, reporails: reporailsAvailable },
315
+ };
316
+
317
+ if (opts?.writeReport !== false) {
318
+ const outDir = join(root, ".rungate");
319
+ if (!existsSync(outDir)) mkdirSync(outDir, { recursive: true });
320
+ writeFileSync(
321
+ join(outDir, "compliance-report.json"),
322
+ JSON.stringify(report, null, 2),
323
+ );
324
+ }
325
+
326
+ if (!agnixAvailable) {
327
+ console.warn("WARN TOOL-NOT-INSTALLED-agnix: agnix not found — install globally or via npm");
328
+ }
329
+ if (!reporailsAvailable) {
330
+ console.warn("WARN TOOL-NOT-INSTALLED-reporails: @reporails/cli not found — install via npm");
331
+ }
332
+
333
+ return report;
334
+ }
335
+
336
+ // ── Layer 2: Generated Compliance ──────────────────────────
337
+
338
+ export async function runGeneratedCompliance(
339
+ root: string,
340
+ baselineReport?: ComplianceReport,
341
+ ): Promise<ComplianceReport> {
342
+ const report = await runTemplateCompliance(root, { writeReport: false });
343
+ report.layer = "generated";
344
+
345
+ if (baselineReport && baselineReport.overallQuality !== null && report.overallQuality !== null) {
346
+ if (report.overallQuality < baselineReport.overallQuality - 0.5) {
347
+ console.error(
348
+ `FAIL: Scaffold degraded instruction quality from ${baselineReport.overallQuality.toFixed(1)} to ${report.overallQuality.toFixed(1)}`
349
+ );
350
+ }
351
+ }
352
+
353
+ const outDir = join(root, ".rungate");
354
+ if (!existsSync(outDir)) mkdirSync(outDir, { recursive: true });
355
+ writeFileSync(
356
+ join(outDir, "compliance-generated.json"),
357
+ JSON.stringify(report, null, 2),
358
+ );
359
+
360
+ return report;
361
+ }
@@ -0,0 +1,255 @@
1
+ /**
2
+ * config-loader.ts — Central config loader for rungate
3
+ *
4
+ * Reads config from .claude/rungate/ directory (preferred) or
5
+ * .claude/rungate.json (fallback). Merges directory files into
6
+ * the same shape as the monolith for backward compatibility.
7
+ */
8
+ import { existsSync, readFileSync } from "fs";
9
+ import { join } from "path";
10
+ import { z } from "zod";
11
+ import {
12
+ ContainerSchema,
13
+ DevSchema,
14
+ ProdSchema,
15
+ ProjectHarnessSchema,
16
+ TestSchema,
17
+ } from "./rungate-schema";
18
+
19
+ export interface ComplianceRule {
20
+ description: string;
21
+ directives: string[];
22
+ reinforcement: string;
23
+ tiers: Record<string, { action: string; hook?: string }>;
24
+ threshold: { consecutive: number; promote: number };
25
+ }
26
+
27
+ export interface OrganizeExternalSource {
28
+ path: string;
29
+ type: string;
30
+ target: string | null;
31
+ method: "symlink" | "copy" | "discover";
32
+ matchBy: string;
33
+ }
34
+
35
+ export interface ComplianceConfig {
36
+ rules: Record<string, ComplianceRule>;
37
+ defaults: { consecutiveFailThreshold: number; tierPromotionThreshold: number };
38
+ organize: {
39
+ fileTypes: string[];
40
+ artifactClassification: Record<string, string>;
41
+ externalSources: OrganizeExternalSource[];
42
+ };
43
+ }
44
+
45
+ /**
46
+ * URLs are validated where a config is AUTHORED (`parseProjectHarness`), not
47
+ * where it is READ. A reader that throws on a cosmetically odd `apiBase` turns
48
+ * a working project into a broken one, which is the opposite of ADR-001 D2's
49
+ * intent: the loader distinguishes present / absent / unreadable, and nothing
50
+ * else. Top-level keys are optional for the same reason — requiring `project`
51
+ * here would add a third outcome the two wrappers have no way to express.
52
+ */
53
+ const LooseUrl = z.string().nullish();
54
+
55
+ /**
56
+ * The resolved shape (ADR-002 D3), derived from the authored schema rather
57
+ * than hand-declared. The interface this replaces claimed `test.command` was
58
+ * required while `TestSchema` did not declare it at all — two hand-written
59
+ * types for one file, disagreeing, which is how a reader could be written
60
+ * against a key the validator deleted.
61
+ *
62
+ * `.passthrough()` is load-bearing: consumers carry keys rungate has never
63
+ * heard of (DDB's `remoteHosts`), and a loader that silently drops them is the
64
+ * same defect as a validator that strips `container`.
65
+ */
66
+ export const ResolvedConfigSchema = ProjectHarnessSchema.partial()
67
+ .extend({
68
+ // `null` is what a greenfield scaffold writes for a base URL it could not
69
+ // detect. It is an authored absence, not a broken config.
70
+ dev: DevSchema.partial().extend({ apiBase: LooseUrl, uiBase: LooseUrl }).optional(),
71
+ test: TestSchema.extend({ apiBase: LooseUrl }).optional(),
72
+ prod: ProdSchema.extend({ apiBase: LooseUrl, uiBase: LooseUrl }).optional(),
73
+ container: ContainerSchema.optional(),
74
+ pages: z.record(z.unknown()).optional(),
75
+ // Merged from side files by the directory loader, so always present in the
76
+ // resolved shape — callers index them without a null check.
77
+ roles: z.record(z.unknown()).default({}),
78
+ hooks: z.array(z.unknown()).default([]),
79
+ compliance: z
80
+ .custom<ComplianceConfig>((value) => typeof value === "object" && value !== null)
81
+ .optional(),
82
+ // Normalised, not authored — see normaliseConfig.
83
+ apiUrl: z.string().optional(),
84
+ uiUrl: z.string().optional(),
85
+ })
86
+ .passthrough();
87
+
88
+ export type ResolvedConfig = z.infer<typeof ResolvedConfigSchema>;
89
+
90
+ /** ship.js:1705's fallback, kept identical so normalisation changes no run. */
91
+ export const DEFAULT_TEST_TIMEOUT = 120000;
92
+
93
+ /**
94
+ * The resolution (ADR-002 D2(a)). `absent` is TRUTHY and carries no `.test`,
95
+ * so the four sites that wrote `config?.test?.command || fallback` cannot
96
+ * silently absorb it — `null`, `0`, `{}` and `""` all could.
97
+ *
98
+ * Malformed JSON and orphaned fragments THROW, per ADR-001 D2. Unchanged.
99
+ */
100
+ export type ConfigResolution =
101
+ | { status: "resolved"; config: ResolvedConfig; source: "directory" | "monolith" }
102
+ | { status: "absent" };
103
+
104
+ const DIRECTORY_CONFIG_FILES = ["config.json", "roles.json", "hooks.json", "compliance.json"];
105
+
106
+ /**
107
+ * ADR-002 D3. `dev.*` is the authored canonical shape; `test.command` keeps
108
+ * being read and is NOT deprecated here — it is rungate's own live config, and
109
+ * moving the dogfood and the consumer path in one change would leave neither
110
+ * as a control for the other.
111
+ */
112
+ function normaliseConfig(raw: unknown): ResolvedConfig {
113
+ const parsed = ResolvedConfigSchema.parse(raw);
114
+
115
+ // The trailing `?? undefined` collapses an authored `null` — a base URL the
116
+ // scaffold could not detect — into the same absence an omitted key gives.
117
+ // Two spellings of "not set" reaching readers is how this class of bug
118
+ // started.
119
+ return {
120
+ ...parsed,
121
+ apiUrl: parsed.apiUrl ?? parsed.dev?.apiBase ?? undefined,
122
+ uiUrl: parsed.uiUrl ?? parsed.dev?.uiBase ?? undefined,
123
+ test: {
124
+ ...parsed.test,
125
+ // dev.* wins. No `|| "bun test"` fallback: an absent command must stay
126
+ // absent so a reader can report it unmeasured rather than run the wrong
127
+ // suite and report 0 failures.
128
+ command: parsed.dev?.testCmd ?? parsed.test?.command,
129
+ timeout: parsed.test?.timeout ?? DEFAULT_TEST_TIMEOUT,
130
+ },
131
+ };
132
+ }
133
+
134
+ /**
135
+ * The single resolution point. Directory form wins over the monolith.
136
+ */
137
+ export function resolveConfig(projectRoot: string): ConfigResolution {
138
+ const dirPath = join(projectRoot, ".claude", "rungate");
139
+ const monolithPath = join(projectRoot, ".claude", "rungate.json");
140
+
141
+ // config.json is the sole marker for the directory form. Treating any
142
+ // fragment as the marker let a stray roles.json shadow a complete monolith
143
+ // and silently drop issueRepo/ci/test — ADR-001 Step E keeps the monolith
144
+ // in place during migration, so that state is on the normal upgrade path.
145
+ if (existsSync(join(dirPath, "config.json"))) {
146
+ return { status: "resolved", config: loadFromDirectory(dirPath), source: "directory" };
147
+ }
148
+
149
+ if (existsSync(monolithPath)) {
150
+ return { status: "resolved", config: loadFromMonolith(monolithPath), source: "monolith" };
151
+ }
152
+
153
+ // Fragments with no config.json and no monolith is a broken directory
154
+ // config, not an unconfigured project. Fail loudly rather than reporting
155
+ // absent, which the caller would read as "no rungate here".
156
+ const orphans = DIRECTORY_CONFIG_FILES.filter((file) => existsSync(join(dirPath, file)));
157
+ if (orphans.length > 0) {
158
+ throw new Error(
159
+ `Incomplete rungate config at ${dirPath}: found ${orphans.join(", ")} but no config.json`
160
+ );
161
+ }
162
+
163
+ return { status: "absent" };
164
+ }
165
+
166
+ export function loadRungateConfig(projectRoot: string): ResolvedConfig {
167
+ const dirPath = join(projectRoot, ".claude", "rungate");
168
+ const monolithPath = join(projectRoot, ".claude", "rungate.json");
169
+
170
+ const resolution = resolveConfig(projectRoot);
171
+ if (resolution.status === "resolved") return resolution.config;
172
+
173
+ throw new Error(`No rungate config found at ${dirPath} or ${monolithPath}`);
174
+ }
175
+
176
+ /**
177
+ * Non-throwing variant of loadRungateConfig.
178
+ *
179
+ * Returns null ONLY when no config is present. A config that exists but
180
+ * cannot be parsed still throws — per ADR-001 D2, a malformed config is
181
+ * never a missing config. Conflating the two is what let #70 stay silent:
182
+ * the caller could not tell "not configured" from "configured wrong".
183
+ */
184
+ export function tryLoadRungateConfig(projectRoot: string): ResolvedConfig | null {
185
+ const resolution = resolveConfig(projectRoot);
186
+ return resolution.status === "resolved" ? resolution.config : null;
187
+ }
188
+
189
+ function loadFromDirectory(dirPath: string): ResolvedConfig {
190
+ const config = readJson(join(dirPath, "config.json"));
191
+ const roles = existsSync(join(dirPath, "roles.json"))
192
+ ? readJson(join(dirPath, "roles.json"))
193
+ : {};
194
+ const hooks = existsSync(join(dirPath, "hooks.json"))
195
+ ? readJson(join(dirPath, "hooks.json"))
196
+ : [];
197
+ const compliance = existsSync(join(dirPath, "compliance.json"))
198
+ ? readJson(join(dirPath, "compliance.json"))
199
+ : undefined;
200
+
201
+ return normaliseConfig({ ...config, roles, hooks, compliance });
202
+ }
203
+
204
+ function loadFromMonolith(path: string): ResolvedConfig {
205
+ return normaliseConfig(readJson(path));
206
+ }
207
+
208
+ function readJson(path: string): any {
209
+ return JSON.parse(readFileSync(path, "utf-8"));
210
+ }
211
+
212
+ export function loadComplianceConfig(projectRoot: string): ComplianceConfig | null {
213
+ const dirPath = join(projectRoot, ".claude", "rungate", "compliance.json");
214
+ if (existsSync(dirPath)) {
215
+ return readJson(dirPath);
216
+ }
217
+ return null;
218
+ }
219
+
220
+ export function buildDirToCompMap(compliance: ComplianceConfig): Record<string, string> {
221
+ const map: Record<string, string> = {};
222
+ for (const [compId, rule] of Object.entries(compliance.rules)) {
223
+ for (const dir of rule.directives) {
224
+ map[dir] = compId;
225
+ }
226
+ }
227
+ return map;
228
+ }
229
+
230
+ export function buildReinforcementMap(compliance: ComplianceConfig): Record<string, string> {
231
+ const map: Record<string, string> = {};
232
+ for (const [compId, rule] of Object.entries(compliance.rules)) {
233
+ map[compId] = rule.reinforcement;
234
+ }
235
+ return map;
236
+ }
237
+
238
+ export function buildTierPromotionMap(
239
+ compliance: ComplianceConfig
240
+ ): Record<string, { tier: 2 | 3; promotion: string }> {
241
+ const map: Record<string, { tier: 2 | 3; promotion: string }> = {};
242
+ for (const [compId, rule] of Object.entries(compliance.rules)) {
243
+ const maxTier = Math.max(...Object.keys(rule.tiers).map(Number));
244
+ if (maxTier >= 2) {
245
+ const tierAction = rule.tiers[String(maxTier)];
246
+ map[compId] = {
247
+ tier: maxTier as 2 | 3,
248
+ promotion: tierAction.hook
249
+ ? `Deploy ${tierAction.hook} hook (${tierAction.action})`
250
+ : tierAction.action,
251
+ };
252
+ }
253
+ }
254
+ return map;
255
+ }