rungate 0.2.1 → 0.4.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 (129) 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/brief-precedence.ts +114 -0
  11. package/lib/canary.ts +117 -0
  12. package/lib/check-registry.ts +226 -0
  13. package/lib/ci-checkout.ts +426 -0
  14. package/lib/cli-commands.ts +137 -0
  15. package/lib/compliance-backfill.ts +232 -0
  16. package/lib/compliance-report.ts +605 -0
  17. package/lib/compliance.ts +361 -0
  18. package/lib/config-loader.ts +255 -0
  19. package/lib/config-readers.ts +86 -0
  20. package/lib/conformity.ts +2161 -137
  21. package/lib/container-provenance.ts +230 -0
  22. package/lib/create-brief.ts +150 -0
  23. package/lib/create-sc.ts +267 -0
  24. package/lib/decomposition-waves.ts +197 -0
  25. package/lib/deep-merge.ts +69 -0
  26. package/lib/dev-liveness.ts +214 -0
  27. package/lib/directive-extractor.ts +210 -0
  28. package/lib/distribution-standing.ts +113 -0
  29. package/lib/doc-hygiene.ts +238 -0
  30. package/lib/eval-criteria.ts +6 -0
  31. package/lib/evidence-portability.ts +123 -0
  32. package/lib/evidence-prevalidator.ts +390 -0
  33. package/lib/evidence-required.ts +150 -0
  34. package/lib/evidence-satisfiability.ts +288 -0
  35. package/lib/frontmatter.ts +163 -0
  36. package/lib/gap-scanner.ts +348 -0
  37. package/lib/gate-check-audit.ts +190 -0
  38. package/lib/gate-enforcement.ts +366 -0
  39. package/lib/generators/agent-briefs.ts +136 -0
  40. package/lib/generators/agents-md.ts +511 -0
  41. package/lib/generators/code-map.ts +60 -0
  42. package/lib/generators/types.ts +184 -0
  43. package/lib/git-ref-normalizer.ts +107 -0
  44. package/lib/github.ts +539 -0
  45. package/lib/harness-identity.ts +63 -0
  46. package/lib/hill-climb.ts +164 -0
  47. package/lib/instruction-effectiveness.ts +131 -0
  48. package/lib/issue-closure-audit.ts +225 -0
  49. package/lib/issue-create-override.ts +343 -0
  50. package/lib/issue-extraction.ts +368 -0
  51. package/lib/js-top-level-code.ts +250 -0
  52. package/lib/liveness-contradiction.ts +149 -0
  53. package/lib/organize.ts +505 -0
  54. package/lib/paths.ts +197 -6
  55. package/lib/phase2-decomposition.ts +270 -0
  56. package/lib/post-fix-verify.ts +157 -0
  57. package/lib/prior-branch.ts +512 -0
  58. package/lib/project-state-shape.ts +166 -0
  59. package/lib/promote-outputs.ts +156 -0
  60. package/lib/prove-label-gate.ts +128 -0
  61. package/lib/reachability.ts +302 -0
  62. package/lib/release-preflight.ts +288 -0
  63. package/lib/rule-health-pipeline.ts +264 -0
  64. package/lib/rule-health-trend.ts +161 -0
  65. package/lib/rule-provenance.ts +149 -0
  66. package/lib/rule-registry.ts +128 -0
  67. package/lib/rungate-schema.ts +127 -5
  68. package/lib/sc-claim-forms.ts +179 -0
  69. package/lib/sc-cover.ts +150 -0
  70. package/lib/sc-guard.ts +157 -0
  71. package/lib/sc-ids.ts +344 -0
  72. package/lib/scaffold/defaults.ts +165 -0
  73. package/lib/scaffold/managed-workflow.ts +370 -0
  74. package/lib/scaffold/owned-files.ts +265 -0
  75. package/lib/scaffold/pre-push-hook.ts +165 -0
  76. package/lib/scaffold/steps.ts +2621 -0
  77. package/lib/scanner.ts +701 -0
  78. package/lib/scope-denylist.ts +258 -0
  79. package/lib/screenshot-upload.ts +73 -0
  80. package/lib/secret-patterns.ts +112 -0
  81. package/lib/security-verdict.ts +616 -0
  82. package/lib/signal-phrases.ts +1 -0
  83. package/lib/spec-change-conformity.ts +80 -0
  84. package/lib/spec-files.ts +62 -0
  85. package/lib/spec-registry.ts +133 -0
  86. package/lib/spec-updater.ts +96 -0
  87. package/lib/stale-cleanup.ts +224 -0
  88. package/lib/stale-issue-scanner.ts +36 -0
  89. package/lib/strip-js-comments.ts +269 -0
  90. package/lib/suite-measurement.ts +228 -0
  91. package/lib/task-completion-checks.ts +224 -0
  92. package/lib/test-suite-lock.ts +1136 -0
  93. package/lib/transcript-checker.ts +1140 -0
  94. package/lib/typescript-project.ts +233 -0
  95. package/lib/validators/spec-validators.ts +171 -0
  96. package/lib/verdict-capture.ts +73 -0
  97. package/lib/verified-push.ts +535 -0
  98. package/lib/workflow-security.ts +174 -0
  99. package/lib/worktree-cleanup.ts +432 -0
  100. package/lib/worktree-collect.ts +283 -0
  101. package/lib/worktree-isolation.ts +82 -0
  102. package/lib/worktree-repo.ts +300 -0
  103. package/package.json +27 -3
  104. package/prompts/ac-adversary.md +14 -2
  105. package/prompts/aditi.md +5 -0
  106. package/prompts/blast-radius.md +5 -0
  107. package/prompts/container-verify.md +5 -0
  108. package/prompts/discovery.md +4 -0
  109. package/prompts/environment.md +5 -0
  110. package/prompts/evidence-hierarchy.md +5 -0
  111. package/prompts/evidence-validator.md +11 -0
  112. package/prompts/marcus.md +5 -0
  113. package/prompts/prevention.md +5 -0
  114. package/prompts/prove-reproducer.md +12 -0
  115. package/prompts/quinn-decision-tree.md +5 -0
  116. package/prompts/quinn-ui-brief.md +5 -0
  117. package/prompts/quinn.md +5 -0
  118. package/prompts/rca.md +5 -0
  119. package/prompts/read-before-write.md +4 -0
  120. package/prompts/regression.md +5 -0
  121. package/prompts/serena.md +5 -0
  122. package/scripts/audit-specs.ts +464 -0
  123. package/scripts/convert-spec.ts +293 -0
  124. package/scripts/create-sc.ts +92 -0
  125. package/scripts/create-spec.ts +166 -0
  126. package/scripts/extract-constraints.ts +4 -3
  127. package/scripts/generate-code-map.ts +1 -1
  128. package/scripts/scaffold-project.ts +138 -1426
  129. package/scripts/sync-spec-tests.ts +211 -126
@@ -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
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Thin typed accessors over the resolved config (#214, ADR-001 D1).
3
+ *
4
+ * ADR-001 decided on 2026-10-05 that `lib/config-loader.ts` is the sole config
5
+ * access point and named the enforcement: a conformity check that FAILS the
6
+ * suite. The check shipped under #309 as CONFIG-1/CONFIG-2 with a
7
+ * known-violations ratchet. This module is the other half — the migration the
8
+ * ratchet exists to let happen one commit at a time.
9
+ *
10
+ * ## Why accessors and not "just call the loader at each site"
11
+ *
12
+ * Six call sites wanted the same three values and each hand-rolled the whole
13
+ * read: `existsSync`, `JSON.parse`, pick a key, and — at four of them — a bare
14
+ * `catch` returning a default. Pointing six copies of that at the loader would
15
+ * remove the path construction and keep the six private answers to "what does
16
+ * unresolvable mean", which ADR-002 names as the defect under the defect:
17
+ *
18
+ * > Drift was not the failure. Defaulting was.
19
+ *
20
+ * Each function here answers that question once, in the open:
21
+ *
22
+ * - **absent config** — a legitimate state for every one of these callers
23
+ * (an unscaffolded directory, a consumer repo that has never run rungate),
24
+ * so the empty value is returned and that is the whole of the contract.
25
+ * - **malformed config** — THROWS, inherited from `tryLoadRungateConfig` and
26
+ * deliberately not caught here. ADR-001 D2's corollary: a malformed config
27
+ * is never a missing config. The bare `catch` at `scripts/fresh-eyes-test`
28
+ * and `scripts/grade-deterministic` converted a corrupt config into an
29
+ * unconfigured project, which is exactly how #70 stayed silent.
30
+ *
31
+ * ## What the migration actually fixes, beyond the policy
32
+ *
33
+ * Every site these replace read `.claude/rungate.json` and nothing else. A
34
+ * consumer on the directory layout — the layout
35
+ * `specs/CONFIG-DIRECTORY-STRUCTURE-SPEC.md` D-1 asks every consumer to
36
+ * migrate to — got `{}` from all of them, silently: no roles, no slug, no
37
+ * pre-flight hosts. The documented migration switched the features off.
38
+ */
39
+
40
+ import { tryLoadRungateConfig } from "./config-loader";
41
+ import type { RoleConfig } from "./rungate-schema";
42
+
43
+ /**
44
+ * Every configured role, keyed by name. `{}` when the project has no config.
45
+ *
46
+ * `roles` is `z.record(z.unknown()).default({})` in the resolved shape — the
47
+ * loader merges `roles.json` in but does not validate each entry against
48
+ * `RoleSchema`, so consumers carrying a role with a missing `brief` reach
49
+ * here. Narrowing is therefore an assertion about shape, not a guarantee of
50
+ * it; callers that index `brief` already handle it being absent.
51
+ */
52
+ export function loadRoleConfig(projectRoot: string): Record<string, RoleConfig> {
53
+ const config = tryLoadRungateConfig(projectRoot);
54
+ if (!config) return {};
55
+ return (config.roles ?? {}) as Record<string, RoleConfig>;
56
+ }
57
+
58
+ /**
59
+ * The project slug, or null when the config does not name one.
60
+ *
61
+ * Null rather than a `"project"` default: the caller that wanted that default
62
+ * uses it to name a worktree directory, and a second project falling back to
63
+ * the same literal would collide with the first. The default belongs at the
64
+ * site that can see the collision, not here.
65
+ */
66
+ export function readProjectSlug(projectRoot: string): string | null {
67
+ const config = tryLoadRungateConfig(projectRoot);
68
+ const slug = config?.project;
69
+ return typeof slug === "string" && slug.trim() ? slug : null;
70
+ }
71
+
72
+ /**
73
+ * Pre-flight SSH hosts, keyed by name. `{}` when none are configured.
74
+ *
75
+ * `remoteHosts` is not in `ProjectHarnessSchema`; it reaches the resolved
76
+ * config through `.passthrough()`, which is why the value is `unknown` and
77
+ * every field access downstream is guarded. Declaring it would be a schema
78
+ * change affecting every consumer config in the wild — out of scope here, and
79
+ * recorded rather than done.
80
+ */
81
+ export function readRemoteHosts(projectRoot: string): Record<string, unknown> {
82
+ const config = tryLoadRungateConfig(projectRoot);
83
+ const hosts = (config as Record<string, unknown> | null)?.remoteHosts;
84
+ if (!hosts || typeof hosts !== "object" || Array.isArray(hosts)) return {};
85
+ return hosts as Record<string, unknown>;
86
+ }