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,605 @@
1
+ import { appendFileSync, readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
2
+ import { dirname, join } from "path";
3
+
4
+ /**
5
+ * The history's record shape (#116).
6
+ *
7
+ * **1** — `scores`, a flat `id → verdict` map, and nothing else.
8
+ * **2** — `rules`, the whole record the grader produced.
9
+ *
10
+ * A grade file carries `{ id, rule, verdict, evidence, category }` per rule.
11
+ * The history kept `id → verdict` and dropped the other three, so
12
+ *
13
+ * ```
14
+ * grade: { id: "DIR-L29", verdict: "VIOLATED",
15
+ * rule: "Run the full suite at most TWICE…",
16
+ * evidence: "5 bun test runs (expected 1-2)", category: "quality" }
17
+ * history: { "DIR-L29": "VIOLATED" }
18
+ * ```
19
+ *
20
+ * The second is an unsourced verdict. It cannot be re-checked, the rule text
21
+ * is unrecoverable once the rule is edited, and a trend built from it cannot
22
+ * explain itself — which is tier F by the standard this repo applies to ACs.
23
+ *
24
+ * The lossiness had not bitten only because the writer was never running
25
+ * (#69: the Grade-phase tail ran in a sandbox with no `require` and failed
26
+ * inside a `catch`). All four entries on disk when #116 was filed were
27
+ * synthetic fixtures, which is why the schema was changed then rather than
28
+ * migrated later.
29
+ */
30
+ export const COMPLIANCE_HISTORY_SCHEMA = 2;
31
+
32
+ /** One graded rule, as the grader produced it. */
33
+ export interface ComplianceRuleRecord {
34
+ id: string;
35
+ verdict: string;
36
+ /** The rule's text at grading time — not recoverable later if it is edited. */
37
+ rule?: string;
38
+ /** What the grader saw. Without it the verdict is unsourced. */
39
+ evidence?: string;
40
+ category?: string;
41
+ }
42
+
43
+ export interface ComplianceEntry {
44
+ timestamp: string;
45
+ issue: string;
46
+ role: string;
47
+ /**
48
+ * Absent means 1. Stamped rather than inferred so a reader can tell "written
49
+ * before the change" from "written after it and carrying nothing".
50
+ */
51
+ schema?: number;
52
+ /** Schema 1 only. New entries do not write it — see `entryVerdicts`. */
53
+ scores?: Record<string, string>;
54
+ /** Schema 2. The full records. */
55
+ rules?: ComplianceRuleRecord[];
56
+ total: number;
57
+ followed: number;
58
+ pct: number;
59
+ flagged: string[];
60
+ }
61
+
62
+ /** 1 for an unstamped entry, which is what every pre-#116 line is. */
63
+ export function historySchema(entry: ComplianceEntry): number {
64
+ return typeof entry.schema === "number" ? entry.schema : 1;
65
+ }
66
+
67
+ /**
68
+ * `id → verdict`, from whichever shape the entry is in.
69
+ *
70
+ * The single reader, so there is one place that knows both forms (SC-3). A
71
+ * v2 entry does NOT also carry `scores`: two copies of the same fact in one
72
+ * record can disagree, and nothing would notice which was right.
73
+ */
74
+ export function entryVerdicts(entry: ComplianceEntry): Record<string, string> {
75
+ if (Array.isArray(entry.rules)) {
76
+ const out: Record<string, string> = {};
77
+ for (const r of entry.rules) {
78
+ if (r && r.id) out[r.id] = r.verdict || "N/A";
79
+ }
80
+ return out;
81
+ }
82
+ return entry.scores ?? {};
83
+ }
84
+
85
+ /** The records, empty for a v1 entry — which is the point of the version. */
86
+ export function ruleRecords(entry: ComplianceEntry): ComplianceRuleRecord[] {
87
+ return Array.isArray(entry.rules) ? entry.rules : [];
88
+ }
89
+
90
+ /** The rule's recorded text for one id, newest entry first. Null if no entry kept it. */
91
+ export function recordedRuleText(entries: ComplianceEntry[], compId: string): string | null {
92
+ for (let i = entries.length - 1; i >= 0; i--) {
93
+ const hit = ruleRecords(entries[i]!).find(r => r.id === compId && r.rule);
94
+ if (hit?.rule) return hit.rule;
95
+ }
96
+ return null;
97
+ }
98
+
99
+ /** Everything recorded for one id, newest first, so a verdict can be re-checked. */
100
+ export function evidenceFor(entries: ComplianceEntry[], compId: string): ComplianceRuleRecord[] {
101
+ const out: ComplianceRuleRecord[] = [];
102
+ for (let i = entries.length - 1; i >= 0; i--) {
103
+ const hit = ruleRecords(entries[i]!).find(r => r.id === compId);
104
+ if (hit) out.push(hit);
105
+ }
106
+ return out;
107
+ }
108
+
109
+ export interface TrendLine {
110
+ compId: string;
111
+ rule: string;
112
+ lastN: string[];
113
+ passRate: number;
114
+ direction: "improving" | "stable" | "declining";
115
+ }
116
+
117
+ export interface ComplianceReport {
118
+ role: string;
119
+ issue: string;
120
+ current: { followed: number; total: number; pct: number };
121
+ threshold: number;
122
+ belowThreshold: boolean;
123
+ trend: { pcts: number[]; direction: string };
124
+ compTrends: TrendLine[];
125
+ alerts: string[];
126
+ }
127
+
128
+ const TREND_WINDOW = 5;
129
+ const ALERT_THRESHOLD = 0.4;
130
+
131
+ export function appendComplianceHistory(
132
+ historyPath: string,
133
+ entry: ComplianceEntry
134
+ ): void {
135
+ const dir = dirname(historyPath);
136
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
137
+ appendFileSync(historyPath, JSON.stringify(entry) + "\n");
138
+ }
139
+
140
+ export function loadComplianceHistory(historyPath: string): ComplianceEntry[] {
141
+ if (!existsSync(historyPath)) return [];
142
+ return readFileSync(historyPath, "utf-8")
143
+ .trim()
144
+ .split("\n")
145
+ .filter(Boolean)
146
+ .map((line) => JSON.parse(line));
147
+ }
148
+
149
+ function computeDirection(pcts: number[]): string {
150
+ if (pcts.length < 2) return "stable";
151
+ const first = pcts.slice(0, Math.ceil(pcts.length / 2));
152
+ const second = pcts.slice(Math.ceil(pcts.length / 2));
153
+ const avg = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length;
154
+ const diff = avg(second) - avg(first);
155
+ if (diff > 5) return "improving";
156
+ if (diff < -5) return "declining";
157
+ return "stable";
158
+ }
159
+
160
+ const COMP_RULES: Record<string, string> = {
161
+ "COMP-1": "AGENTS.md context",
162
+ "COMP-2": "Suite run limit",
163
+ "COMP-3": "Golden fixture pattern",
164
+ "COMP-4": "Spec-drift hash update",
165
+ "COMP-5": "Governing spec context",
166
+ "COMP-6": "No duplicate reads",
167
+ "COMP-7": "No cat/head via Bash",
168
+ "COMP-8": "PROJECT-STATE context",
169
+ "COMP-9": "Tool call budget",
170
+ "COMP-10": "Grep:Read ratio",
171
+ "COMP-11": "Coding principles context",
172
+ "COMP-12": "Grep before Read",
173
+ "COMP-13": "TDD ordering",
174
+ };
175
+
176
+ export function generateComplianceReport(
177
+ current: ComplianceEntry,
178
+ history: ComplianceEntry[],
179
+ threshold: number
180
+ ): ComplianceReport {
181
+ const roleHistory = history.filter((h) => h.role === current.role);
182
+ const window = roleHistory.slice(-TREND_WINDOW);
183
+ const allPcts = [...window.map((h) => h.pct), current.pct];
184
+
185
+ const considered = [...window, current];
186
+ const verdictMaps = new Map(considered.map(e => [e, entryVerdicts(e)]));
187
+
188
+ const allCompIds = new Set<string>();
189
+ for (const entry of considered) {
190
+ for (const id of Object.keys(verdictMaps.get(entry)!)) allCompIds.add(id);
191
+ }
192
+
193
+ // The rule text the grader recorded beats the hardcoded map (#116): the map
194
+ // goes stale the moment a rule is edited, and a v2 entry carries what the
195
+ // rule actually said when the verdict was reached.
196
+ const ruleTextFor = (compId: string) =>
197
+ recordedRuleText(considered, compId) || COMP_RULES[compId] || compId;
198
+
199
+ const compTrends: TrendLine[] = [];
200
+ for (const compId of [...allCompIds].sort()) {
201
+ const verdicts = considered.map((e) => verdictMaps.get(e)![compId] || "N/A");
202
+ const checkable = verdicts.filter((v) => v !== "N/A");
203
+ const passed = checkable.filter((v) => v === "FOLLOWED").length;
204
+ const passRate = checkable.length > 0 ? passed / checkable.length : 0;
205
+
206
+ if (checkable.length < 2) {
207
+ compTrends.push({ compId, rule: ruleTextFor(compId), lastN: verdicts, passRate, direction: "stable" });
208
+ continue;
209
+ }
210
+ const firstHalf = checkable.slice(0, Math.ceil(checkable.length / 2));
211
+ const secondHalf = checkable.slice(Math.ceil(checkable.length / 2));
212
+ const firstRate =
213
+ firstHalf.length > 0
214
+ ? firstHalf.filter((v) => v === "FOLLOWED").length / firstHalf.length
215
+ : 0;
216
+ const secondRate =
217
+ secondHalf.length > 0
218
+ ? secondHalf.filter((v) => v === "FOLLOWED").length / secondHalf.length
219
+ : 0;
220
+ let direction: TrendLine["direction"] = "stable";
221
+ if (secondRate - firstRate > 0.2) direction = "improving";
222
+ else if (firstRate - secondRate > 0.2) direction = "declining";
223
+
224
+ compTrends.push({
225
+ compId,
226
+ rule: ruleTextFor(compId),
227
+ lastN: verdicts,
228
+ passRate,
229
+ direction,
230
+ });
231
+ }
232
+
233
+ const alerts: string[] = [];
234
+ for (const ct of compTrends) {
235
+ if (!ct.compId.startsWith("COMP-") && !ct.compId.startsWith("DIR-")) continue;
236
+ if (ct.passRate <= ALERT_THRESHOLD && ct.lastN.length >= 2) {
237
+ alerts.push(
238
+ `${ct.compId}: ${Math.round(ct.passRate * 100)}% pass rate — ${ct.rule} needs improvement`
239
+ );
240
+ }
241
+ if (ct.direction === "declining" && ct.lastN.length >= 3) {
242
+ alerts.push(`${ct.compId}: declining trend — was passing, now failing`);
243
+ }
244
+ }
245
+
246
+ if (current.pct < threshold) {
247
+ alerts.unshift(
248
+ `Overall score ${current.pct}% is BELOW ${threshold}% threshold`
249
+ );
250
+ }
251
+
252
+ return {
253
+ role: current.role,
254
+ issue: current.issue,
255
+ current: {
256
+ followed: current.followed,
257
+ total: current.total,
258
+ pct: current.pct,
259
+ },
260
+ threshold,
261
+ belowThreshold: current.pct < threshold,
262
+ trend: { pcts: allPcts, direction: computeDirection(allPcts) },
263
+ compTrends,
264
+ alerts,
265
+ };
266
+ }
267
+
268
+ export function formatComplianceReport(report: ComplianceReport): string {
269
+ const lines: string[] = [];
270
+ const bar = "═".repeat(50);
271
+
272
+ lines.push(bar);
273
+ lines.push(`COMPLIANCE REPORT — ${report.role} (${report.issue})`);
274
+ lines.push(bar);
275
+
276
+ const statusIcon = report.belowThreshold ? "❌ BELOW THRESHOLD" : "✅";
277
+ lines.push(
278
+ `Score: ${report.current.followed}/${report.current.total} (${report.current.pct}%) ${statusIcon}`
279
+ );
280
+ lines.push(`Threshold: ${report.threshold}%`);
281
+
282
+ if (report.trend.pcts.length > 1) {
283
+ const arrow =
284
+ report.trend.direction === "improving"
285
+ ? "▲"
286
+ : report.trend.direction === "declining"
287
+ ? "▼"
288
+ : "→";
289
+ lines.push(
290
+ `Trend (last ${report.trend.pcts.length}): ${report.trend.pcts.join("% → ")}% ${arrow} ${report.trend.direction}`
291
+ );
292
+ }
293
+
294
+ const compChecks = report.compTrends.filter((ct) => ct.compId.startsWith("COMP-"));
295
+ const dirChecks = report.compTrends.filter((ct) => ct.compId.startsWith("DIR-"));
296
+
297
+ if (compChecks.length > 0) {
298
+ lines.push("");
299
+ lines.push("Per-COMP breakdown:");
300
+ for (const ct of compChecks) {
301
+ const icon = ct.passRate >= 0.8 ? "✅" : ct.passRate >= 0.5 ? "⚠️" : "❌";
302
+ const pctStr = Math.round(ct.passRate * 100);
303
+ lines.push(
304
+ ` ${icon} ${ct.compId.padEnd(8)} ${ct.rule.padEnd(28)} ${pctStr}% pass`
305
+ );
306
+ }
307
+ }
308
+
309
+ if (dirChecks.length > 0) {
310
+ const dirPass = dirChecks.filter((ct) => ct.passRate >= 0.5).length;
311
+ lines.push(
312
+ `\nDirective checks: ${dirPass}/${dirChecks.length} passing (${dirChecks.length - dirPass} need attention)`
313
+ );
314
+ }
315
+
316
+ const compAlerts = report.alerts.filter(
317
+ (a) => a.startsWith("COMP-") || a.startsWith("Overall")
318
+ );
319
+ if (compAlerts.length > 0) {
320
+ lines.push("");
321
+ lines.push("ALERTS:");
322
+ for (const alert of compAlerts) {
323
+ lines.push(` ⚠️ ${alert}`);
324
+ }
325
+ }
326
+
327
+ lines.push(bar);
328
+ return lines.join("\n");
329
+ }
330
+
331
+ // ── Config-driven compliance maps ────────────────────────
332
+ // All mappings (DIR→COMP, reinforcements, tier promotions) are read
333
+ // from .claude/rungate/compliance.json. Hardcoded fallbacks exist only
334
+ // for backward compatibility when the config directory doesn't exist.
335
+ import {
336
+ loadComplianceConfig,
337
+ buildDirToCompMap,
338
+ buildReinforcementMap,
339
+ buildTierPromotionMap,
340
+ type ComplianceConfig,
341
+ } from "./config-loader.js";
342
+
343
+ let _complianceCache: ComplianceConfig | null | undefined;
344
+ let _projectRoot: string | undefined;
345
+
346
+ export function setComplianceProjectRoot(root: string): void {
347
+ _projectRoot = root;
348
+ _complianceCache = undefined;
349
+ }
350
+
351
+ function getComplianceConfig(): ComplianceConfig | null {
352
+ if (_complianceCache !== undefined) return _complianceCache;
353
+ if (_projectRoot) {
354
+ _complianceCache = loadComplianceConfig(_projectRoot);
355
+ } else {
356
+ _complianceCache = null;
357
+ }
358
+ return _complianceCache;
359
+ }
360
+
361
+ function getDirToComp(): Record<string, string> {
362
+ const config = getComplianceConfig();
363
+ if (config) return buildDirToCompMap(config);
364
+ return {
365
+ "DIR-L29": "COMP-2",
366
+ "DIR-L25": "COMP-7",
367
+ "DIR-L31": "COMP-6",
368
+ "DIR-L23": "COMP-6",
369
+ };
370
+ }
371
+
372
+ function getReinforcementMap(): Record<string, string> {
373
+ const config = getComplianceConfig();
374
+ if (config) return buildReinforcementMap(config);
375
+ return {
376
+ "COMP-7": "NEVER read a file with cat, head, or tail via Bash — use Read with offset/limit. Piping output into head/tail as a stdin filter is fine (no file operand).",
377
+ "COMP-12": "Grep BEFORE Read for any file not in Key Files. Find the section, then Read with offset/limit.",
378
+ "COMP-13": "Write the test file BEFORE the implementation file. Tool-call order is mechanically checked.",
379
+ "COMP-6": "Read each file exactly ONCE. Use offset/limit to get what you need in one pass.",
380
+ "COMP-9": "Total tool calls must stay under 40. Batch related reads, use targeted tests.",
381
+ // No number here. The guard owns it, the reinforcement points at the
382
+ // guard, and a copy of "TWICE" in an agent's brief outlives any change to
383
+ // the rate — which is how an agent ends up obeying a limit that no longer
384
+ // exists while the grader measures a different one.
385
+ "COMP-2": "Run the full suite (bun test) sparingly. A per-worker rate limit enforces this mechanically and will refuse the run; do not plan around a specific number. Use targeted tests for iteration.",
386
+ };
387
+ }
388
+
389
+ function getTierPromotions(): Record<string, { tier: 2 | 3; promotion: string }> {
390
+ const config = getComplianceConfig();
391
+ if (config) return buildTierPromotionMap(config);
392
+ return {
393
+ "COMP-7": { tier: 3, promotion: "Deploy BashToolGuard hook" },
394
+ "COMP-12": { tier: 2, promotion: "Add grep-before-read reinforcement" },
395
+ "COMP-13": { tier: 2, promotion: "Add TDD-sequence reinforcement" },
396
+ "COMP-6": { tier: 2, promotion: "Add duplicate-read detection reinforcement" },
397
+ "COMP-9": { tier: 3, promotion: "Deploy tool-call budget hook" },
398
+ "COMP-2": { tier: 3, promotion: "Deploy test-run limiter hook" },
399
+ };
400
+ }
401
+
402
+ function getThresholds(): { consecutive: number; promote: number } {
403
+ const config = getComplianceConfig();
404
+ if (config) return { consecutive: config.defaults.consecutiveFailThreshold, promote: config.defaults.tierPromotionThreshold };
405
+ return { consecutive: 3, promote: 5 };
406
+ }
407
+
408
+ function normalizeDirToComp(id: string): string {
409
+ return getDirToComp()[id] || id;
410
+ }
411
+
412
+ // ── Auto hill-climb ──────────────────────────────────────
413
+
414
+ export interface HillClimbAction {
415
+ compId: string;
416
+ rule: string;
417
+ reinforcement: string;
418
+ consecutiveFails: number;
419
+ tier: 1 | 2 | 3;
420
+ promotion?: string;
421
+ }
422
+
423
+ function countConsecutiveFails(verdicts: string[]): number {
424
+ let count = 0;
425
+ for (let i = verdicts.length - 1; i >= 0; i--) {
426
+ if (verdicts[i] === "IGNORED" || verdicts[i] === "VIOLATED") count++;
427
+ else break;
428
+ }
429
+ return count;
430
+ }
431
+
432
+ export function detectHillClimbNeeds(report: ComplianceReport): HillClimbAction[] {
433
+ const actions: HillClimbAction[] = [];
434
+ const seen = new Set<string>();
435
+ for (const ct of report.compTrends) {
436
+ const compId = normalizeDirToComp(ct.compId);
437
+ if (seen.has(compId)) continue;
438
+ seen.add(compId);
439
+ const reinforcements = getReinforcementMap();
440
+ const promotions = getTierPromotions();
441
+ const thresholds = getThresholds();
442
+ if (!reinforcements[compId]) continue;
443
+ const consecutiveFails = countConsecutiveFails(ct.lastN);
444
+ if (consecutiveFails >= thresholds.promote && promotions[compId]) {
445
+ const promo = promotions[compId];
446
+ actions.push({
447
+ compId,
448
+ rule: ct.rule,
449
+ reinforcement: reinforcements[compId],
450
+ consecutiveFails,
451
+ tier: promo.tier,
452
+ promotion: promo.promotion,
453
+ });
454
+ } else if (consecutiveFails >= thresholds.consecutive) {
455
+ actions.push({
456
+ compId,
457
+ rule: ct.rule,
458
+ reinforcement: reinforcements[compId],
459
+ consecutiveFails,
460
+ tier: 1,
461
+ });
462
+ }
463
+ }
464
+ return actions;
465
+ }
466
+
467
+ export function applyHillClimb(
468
+ briefPath: string,
469
+ actions: HillClimbAction[]
470
+ ): { applied: string[]; skipped: string[] } {
471
+ if (!existsSync(briefPath) || actions.length === 0)
472
+ return { applied: [], skipped: [] };
473
+
474
+ let content = readFileSync(briefPath, "utf-8");
475
+ const applied: string[] = [];
476
+ const skipped: string[] = [];
477
+
478
+ for (const action of actions) {
479
+ if (action.tier >= 2) {
480
+ skipped.push(
481
+ `${action.compId}: TIER ${action.tier} PROMOTION needed — ${action.promotion}`
482
+ );
483
+ continue;
484
+ }
485
+
486
+ const normalizedReinforcement = action.reinforcement
487
+ .toLowerCase()
488
+ .replace(/[`*"']/g, "");
489
+ const normalizedContent = content.toLowerCase().replace(/[`*"']/g, "");
490
+
491
+ if (normalizedContent.includes(normalizedReinforcement.slice(0, 40))) {
492
+ skipped.push(
493
+ `${action.compId}: reinforcement already present in brief`
494
+ );
495
+ continue;
496
+ }
497
+
498
+ const efficiencyIdx = content.indexOf("## Efficiency Rules");
499
+ const testingIdx = content.indexOf("## Testing Rules");
500
+ const neverIdx = content.indexOf("## Never Do");
501
+
502
+ let insertIdx = -1;
503
+ let prefix = "\n- ";
504
+
505
+ if (
506
+ action.compId === "COMP-2" &&
507
+ testingIdx !== -1
508
+ ) {
509
+ const nextSection = content.indexOf("\n## ", testingIdx + 1);
510
+ insertIdx = nextSection !== -1 ? nextSection : content.length;
511
+ prefix = "\n- **REINFORCED (auto):** ";
512
+ } else if (efficiencyIdx !== -1) {
513
+ const nextSection = content.indexOf("\n## ", efficiencyIdx + 1);
514
+ insertIdx = nextSection !== -1 ? nextSection : content.length;
515
+ prefix = "\n- **REINFORCED (auto):** ";
516
+ } else if (neverIdx !== -1) {
517
+ const nextSection = content.indexOf("\n## ", neverIdx + 1);
518
+ insertIdx = nextSection !== -1 ? nextSection : content.length;
519
+ prefix = "\n- **REINFORCED (auto):** ";
520
+ }
521
+
522
+ if (insertIdx === -1) {
523
+ skipped.push(`${action.compId}: no suitable section found in brief`);
524
+ continue;
525
+ }
526
+
527
+ content =
528
+ content.slice(0, insertIdx) +
529
+ `${prefix}${action.reinforcement}` +
530
+ content.slice(insertIdx);
531
+ applied.push(
532
+ `${action.compId}: added reinforcement (${action.consecutiveFails} consecutive fails)`
533
+ );
534
+ }
535
+
536
+ if (applied.length > 0) {
537
+ writeFileSync(briefPath, content);
538
+ }
539
+
540
+ return { applied, skipped };
541
+ }
542
+
543
+ // --- WARN-to-FAIL promotion tracking (SC-515, DEC-012) ---
544
+
545
+ export interface PromotionFinding {
546
+ checkId: string;
547
+ verdict: 'TRUE_POSITIVE' | 'FALSE_POSITIVE';
548
+ }
549
+
550
+ export interface PromotionPrecision {
551
+ checkId: string;
552
+ /** Precision percentage — ratio of true positives to total findings */
553
+ precision: number;
554
+ total: number;
555
+ truePositives: number;
556
+ /** Eligible for WARN-to-FAIL promotion: precision >= 80% AND total >= 10 cycles */
557
+ eligible: boolean;
558
+ }
559
+
560
+ const PROMOTION_PRECISION_THRESHOLD = 80;
561
+ const PROMOTION_MIN_CYCLES = 10;
562
+
563
+ /**
564
+ * Calculate promotion precision for a specific check ID.
565
+ *
566
+ * WARN checks are promoted to FAIL only when mechanical precision tracking
567
+ * shows >80% precision over 10+ cycles (DEC-005, DEC-012).
568
+ *
569
+ * Filters findings by checkId, computes the ratio of TRUE_POSITIVE verdicts,
570
+ * and determines eligibility based on the 80% threshold and minimum sample size.
571
+ */
572
+ export function calculatePromotionPrecision(
573
+ checkId: string,
574
+ findings: PromotionFinding[],
575
+ ): PromotionPrecision {
576
+ const relevant = findings.filter(f => f.checkId === checkId);
577
+ const total = relevant.length;
578
+ const truePositives = relevant.filter(f => f.verdict === 'TRUE_POSITIVE').length;
579
+ const precision = total > 0 ? Math.round((truePositives / total) * 100) : 0;
580
+ const eligible = precision >= PROMOTION_PRECISION_THRESHOLD && total >= PROMOTION_MIN_CYCLES;
581
+
582
+ return { checkId, precision, total, truePositives, eligible };
583
+ }
584
+
585
+ /**
586
+ * Get all check IDs that are candidates for WARN-to-FAIL promotion.
587
+ *
588
+ * Scans all findings, groups by checkId, and returns those meeting the
589
+ * promotion criteria: >= 80% precision over >= 10 cycles.
590
+ */
591
+ export function getPromotionCandidates(
592
+ findings: PromotionFinding[],
593
+ ): PromotionPrecision[] {
594
+ const checkIds = new Set(findings.map(f => f.checkId));
595
+ const candidates: PromotionPrecision[] = [];
596
+
597
+ for (const checkId of checkIds) {
598
+ const result = calculatePromotionPrecision(checkId, findings);
599
+ if (result.eligible) {
600
+ candidates.push(result);
601
+ }
602
+ }
603
+
604
+ return candidates;
605
+ }