rungate 0.2.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 (196) hide show
  1. package/.claude/agents/aditi.md +47 -0
  2. package/.claude/agents/marcus.md +50 -0
  3. package/.claude/agents/quinn.md +58 -0
  4. package/.claude/agents/rook.md +47 -0
  5. package/.claude/agents/serena.md +46 -0
  6. package/.claude/rungate.json +11 -0
  7. package/.fallowrc.json +28 -0
  8. package/.github/copilot-instructions.md +20 -0
  9. package/.rungate/conformity-findings.json +648 -0
  10. package/AGENTS.md +106 -0
  11. package/CODE-MAP.md +50 -0
  12. package/HARNESS.md +88 -0
  13. package/bun.lock +26 -0
  14. package/bunfig.toml +2 -0
  15. package/config/brief-policies.json +28 -0
  16. package/config/ceremony-profiles.json +212 -0
  17. package/config/consumer-cascade-map.json +24 -0
  18. package/config/doc-cascade-map.json +24 -0
  19. package/config/eval.json +84 -0
  20. package/config/profiles/account-plan.yaml +36 -0
  21. package/config/profiles/campaign.yaml +94 -0
  22. package/config/prove-evidence.schema.json +65 -0
  23. package/config/spec-policies.json +36 -0
  24. package/config/workflow-schema.json +281 -0
  25. package/gates/SCHEMA-GUIDE.md +121 -0
  26. package/gates/ac-quality.test.ts +106 -0
  27. package/gates/adversarial.test.ts +274 -0
  28. package/gates/brief-assembler.test.ts +429 -0
  29. package/gates/brief-assembler.ts +334 -0
  30. package/gates/bunfig.toml +2 -0
  31. package/gates/chain.test.ts +91 -0
  32. package/gates/e2e-smoke.test.ts +234 -0
  33. package/gates/error-classifier.test.ts +249 -0
  34. package/gates/error-classifier.ts +89 -0
  35. package/gates/orchestrator.test.ts +950 -0
  36. package/gates/orchestrator.ts +569 -0
  37. package/gates/preload.ts +77 -0
  38. package/gates/prompts/ac-adversary.md +20 -0
  39. package/gates/prompts/evidence-validator.md +22 -0
  40. package/gates/prompts/prove-reproducer.md +53 -0
  41. package/gates/prove.test.ts +164 -0
  42. package/gates/run-gate.ts +936 -0
  43. package/gates/schema-parity.test.ts +197 -0
  44. package/gates/schema.ts +362 -0
  45. package/gates/self-heal.test.ts +511 -0
  46. package/gates/self-heal.ts +121 -0
  47. package/gates/ship-orchestrator.test.ts +379 -0
  48. package/gates/ship-orchestrator.ts +363 -0
  49. package/gates/test-fixtures/broken-no-environments.json +60 -0
  50. package/gates/test-fixtures/valid-standard.json +54 -0
  51. package/gates/test-utils.ts +43 -0
  52. package/gates/witness.ts +220 -0
  53. package/gates/workflow.test.ts +1053 -0
  54. package/hooks/AgentBriefGuard.hook.ts +586 -0
  55. package/hooks/AgentVerdictCapture.hook.ts +134 -0
  56. package/hooks/AutoVerifyGate.hook.ts +76 -0
  57. package/hooks/GateEnforcement.hook.ts +273 -0
  58. package/hooks/IssueCloseGuard.hook.ts +116 -0
  59. package/hooks/MergeGuard.hook.ts +55 -0
  60. package/hooks/StaleTTLCleanup.hook.ts +133 -0
  61. package/hooks/VerifyPhaseLock.hook.ts +81 -0
  62. package/hooks/WorkflowStateGuard.hook.ts +37 -0
  63. package/hooks/lib/agentDetection.ts +70 -0
  64. package/hooks/lib/findWorkflow.ts +101 -0
  65. package/hooks/lib/parseStdin.ts +37 -0
  66. package/hooks/lib/paths.ts +111 -0
  67. package/hooks/lib/utils.ts +81 -0
  68. package/lib/conformity.ts +959 -0
  69. package/lib/paths.ts +23 -0
  70. package/lib/rungate-schema.ts +60 -0
  71. package/lib/signal-phrases.ts +7 -0
  72. package/package.json +20 -0
  73. package/prompts/ac-adversary.md +20 -0
  74. package/prompts/ac-format.md +34 -0
  75. package/prompts/aditi.md +29 -0
  76. package/prompts/blast-radius.md +29 -0
  77. package/prompts/coding-principles.md +34 -0
  78. package/prompts/container-rebuild.md +29 -0
  79. package/prompts/container-verify.md +28 -0
  80. package/prompts/discovery.md +27 -0
  81. package/prompts/environment.md +28 -0
  82. package/prompts/escalation-decision-tree.md +38 -0
  83. package/prompts/evidence-hierarchy.md +31 -0
  84. package/prompts/evidence-validator.md +22 -0
  85. package/prompts/marcus.md +29 -0
  86. package/prompts/prevention.md +26 -0
  87. package/prompts/prove-reproducer.md +43 -0
  88. package/prompts/quinn-decision-tree.md +31 -0
  89. package/prompts/quinn-ui-brief.md +106 -0
  90. package/prompts/quinn.md +29 -0
  91. package/prompts/rca.md +28 -0
  92. package/prompts/read-before-write.md +30 -0
  93. package/prompts/regression.md +26 -0
  94. package/prompts/rook.md +29 -0
  95. package/prompts/serena.md +28 -0
  96. package/prompts/testing-strategy.md +34 -0
  97. package/reference/migration-manifest.json +554 -0
  98. package/reference/prompts/agent-aditi.md +38 -0
  99. package/reference/prompts/agent-marcus.md +38 -0
  100. package/reference/prompts/agent-quinn.md +38 -0
  101. package/reference/prompts/agent-rook.md +37 -0
  102. package/reference/prompts/agent-serena.md +37 -0
  103. package/reference/prompts/council-skill.md +170 -0
  104. package/reference/prompts/goal-skill.md +235 -0
  105. package/reference/prompts/prove-skill.md +283 -0
  106. package/reference/prompts/quinn-standard.md +246 -0
  107. package/reference/prompts/ship-convergence.md +65 -0
  108. package/reference/prompts/ship-escalation.md +43 -0
  109. package/reference/prompts/ship-iteration.md +382 -0
  110. package/reference/prompts/ship-pending-patches.md +246 -0
  111. package/reference/prompts/ship-reference.md +250 -0
  112. package/reference/prompts/ship-skill.md +347 -0
  113. package/reference/prompts/ship-templates.md +215 -0
  114. package/reference/scripts/batch-status.sh +68 -0
  115. package/reference/scripts/chain-compat-check.sh +67 -0
  116. package/reference/scripts/context-audit.sh +314 -0
  117. package/reference/scripts/dead-export-check.sh +61 -0
  118. package/reference/scripts/generate-qc-tables.sh +92 -0
  119. package/reference/scripts/harness-init.sh +111 -0
  120. package/reference/scripts/pai-054-baseline-check.sh +40 -0
  121. package/reference/scripts/prove-smoke-test.sh +112 -0
  122. package/reference/scripts/setup-keychain-salt.sh +12 -0
  123. package/reference/scripts/skill-optimizer-friday.sh +88 -0
  124. package/reference/scripts/skill-qc-test.sh +351 -0
  125. package/reference/scripts/skill-synthesize-tonight.sh +66 -0
  126. package/reference/specs/HARNESS-EXTRACTION-SPEC.md +263 -0
  127. package/reference/specs/harness-v3-bash-deletion-plan.md +65 -0
  128. package/reference/specs/harness-v3-migration-plan.md +188 -0
  129. package/scripts/decision-reconcile.sh +74 -0
  130. package/scripts/decision-reconcile.ts +152 -0
  131. package/scripts/extract-constraints.ts +260 -0
  132. package/scripts/generate-code-map.ts +339 -0
  133. package/scripts/git-hooks/pre-commit +76 -0
  134. package/scripts/git-hooks/pre-push +271 -0
  135. package/scripts/harness-skill-check.sh +52 -0
  136. package/scripts/lib/gap-emit.sh +65 -0
  137. package/scripts/lib/jq-update.sh +30 -0
  138. package/scripts/lib/resolve-slug.sh +30 -0
  139. package/scripts/lib/verify-spec-compliance.sh +102 -0
  140. package/scripts/prove-backfill.sh +87 -0
  141. package/scripts/scaffold-project.ts +1488 -0
  142. package/scripts/scaffold-rungate-config.ts +91 -0
  143. package/scripts/self-containment-check.sh +109 -0
  144. package/scripts/skill-qc-validator.sh +402 -0
  145. package/scripts/slug-resolver.sh +14 -0
  146. package/scripts/sync-spec-tests.ts +236 -0
  147. package/specs/BOOTSTRAP-DATA-FLOW-SPEC.md +2493 -0
  148. package/specs/BOOTSTRAP-TEST-PLAN.md +571 -0
  149. package/specs/HARNESS-GATES.md +256 -0
  150. package/specs/HARNESS-SKILL-CHAIN.md +286 -0
  151. package/specs/HARNESS-SKILL-CONTRACT.md +93 -0
  152. package/specs/HARNESS-STANDARD.md +488 -0
  153. package/specs/SPEC-TEMPLATE.md +53 -0
  154. package/specs/bootstrap-data-flow.png +0 -0
  155. package/specs/harness-automation-matrix.md +314 -0
  156. package/specs/harness-automation-matrix.rules.json +64 -0
  157. package/test/anti.test.ts +80 -0
  158. package/test/contract-negative.test.ts +86 -0
  159. package/test/contract.test.ts +158 -0
  160. package/test/external-deps.test.ts +48 -0
  161. package/test/fixtures/golden-project/.env.example +3 -0
  162. package/test/fixtures/golden-project/Makefile +7 -0
  163. package/test/fixtures/golden-project/docs/adr/ADR-001-framework.md +23 -0
  164. package/test/fixtures/golden-project/docs/setup-guide.md +10 -0
  165. package/test/fixtures/golden-project/package.json +10 -0
  166. package/test/fixtures/golden-project/specs/api-spec.md +20 -0
  167. package/test/fixtures/golden-project/src/auth.ts +8 -0
  168. package/test/fixtures/golden-project/src/db.ts +11 -0
  169. package/test/fixtures/golden-project/src/index.ts +19 -0
  170. package/test/fixtures/golden-project/src/utils/format.ts +3 -0
  171. package/test/fixtures/golden-project/test/auth.test.ts +15 -0
  172. package/test/fixtures/golden-project/tsconfig.json +12 -0
  173. package/test/meta-sc-coverage.test.ts +159 -0
  174. package/test/phase-0.test.ts +846 -0
  175. package/test/phase-1.test.ts +617 -0
  176. package/test/phase-2.test.ts +620 -0
  177. package/test/phase-3.test.ts +99 -0
  178. package/test/scaffold-conformity.test.ts +8 -0
  179. package/test/schema-canary.test.ts +51 -0
  180. package/test/spec-compliance-auto.test.ts +64 -0
  181. package/test/spec-compliance.test.ts +295 -0
  182. package/test/spec-discovery.test.ts +68 -0
  183. package/test/spec-drift.test.ts +5 -0
  184. package/test/structure.test.ts +165 -0
  185. package/test/unit/agent-brief-guard-ship.test.ts +293 -0
  186. package/test/unit/extract-constraints.test.ts +145 -0
  187. package/test/unit/issue-close-guard.test.ts +204 -0
  188. package/test/unit/scaffold-project.test.ts +417 -0
  189. package/test/unit/skill-cooccurrence.test.ts +177 -0
  190. package/test/unit/skill-sequence-logger.test.ts +244 -0
  191. package/test/unit/workflow-state-guard.test.ts +95 -0
  192. package/workflows/batch-ship.js +295 -0
  193. package/workflows/council.js +481 -0
  194. package/workflows/prove.js +560 -0
  195. package/workflows/ship.js +789 -0
  196. package/workflows/verify.js +236 -0
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env bun
2
+ // decision-reconcile.ts — Verify council decisions are present in target documents
3
+ // Usage: decision-reconcile.ts <council-synthesis.json> [--target <file>]
4
+ // Without --target: checks ALL decisions against their declared targets
5
+ // With --target: checks only decisions targeting that specific file
6
+
7
+ import { readFileSync, existsSync } from "fs";
8
+ import { resolve } from "path";
9
+ import { homedir } from "os";
10
+
11
+ interface Decision {
12
+ id: string;
13
+ statement: string;
14
+ target?: {
15
+ ref?: string;
16
+ section?: string;
17
+ };
18
+ }
19
+
20
+ interface Synthesis {
21
+ decisions?: Decision[];
22
+ }
23
+
24
+ type ResultStatus = "FOUND" | "MISSING";
25
+
26
+ interface Result {
27
+ status: ResultStatus;
28
+ id: string;
29
+ statement: string;
30
+ detail?: string;
31
+ }
32
+
33
+ function expandHome(filepath: string): string {
34
+ return filepath.startsWith("~") ? filepath.replace("~", homedir()) : filepath;
35
+ }
36
+
37
+ function usage(): never {
38
+ console.error(
39
+ "Usage: decision-reconcile.ts <council-synthesis.json> [--target <file>]"
40
+ );
41
+ process.exit(1);
42
+ }
43
+
44
+ // Parse args
45
+ const args = process.argv.slice(2);
46
+ if (args.length === 0) usage();
47
+
48
+ const synthesisPath = resolve(args[0]);
49
+ let targetFilter = "";
50
+
51
+ if (args[1] === "--target") {
52
+ if (!args[2]) usage();
53
+ targetFilter = args[2];
54
+ }
55
+
56
+ // Validate synthesis file
57
+ if (!existsSync(synthesisPath)) {
58
+ console.error(`FAIL: ${synthesisPath} not found`);
59
+ process.exit(1);
60
+ }
61
+
62
+ let data: Synthesis;
63
+ try {
64
+ data = JSON.parse(readFileSync(synthesisPath, "utf-8"));
65
+ } catch {
66
+ console.error(`FAIL: ${synthesisPath} is invalid JSON`);
67
+ process.exit(1);
68
+ }
69
+
70
+ const decisions = data.decisions ?? [];
71
+ const results: Result[] = [];
72
+
73
+ for (const d of decisions) {
74
+ const ref = d.target?.ref;
75
+ if (!ref) continue;
76
+ if (targetFilter && ref !== targetFilter) continue;
77
+
78
+ const filepath = expandHome(ref);
79
+
80
+ if (!existsSync(filepath)) {
81
+ results.push({
82
+ status: "MISSING",
83
+ id: d.id,
84
+ statement: d.statement.slice(0, 60),
85
+ detail: `file not found: ${ref}`,
86
+ });
87
+ continue;
88
+ }
89
+
90
+ const content = readFileSync(filepath, "utf-8");
91
+
92
+ // Extract key words (>3 chars) from statement, take first 3 as key phrase
93
+ const words = d.statement.split(/\s+/).filter((w) => w.length > 3);
94
+ const keyPhrase = words.slice(0, 3).join(" ");
95
+ const contentLower = content.toLowerCase();
96
+
97
+ if (
98
+ keyPhrase.toLowerCase() &&
99
+ contentLower.includes(keyPhrase.toLowerCase())
100
+ ) {
101
+ results.push({
102
+ status: "FOUND",
103
+ id: d.id,
104
+ statement: d.statement.slice(0, 60),
105
+ });
106
+ } else if (content.includes(d.id)) {
107
+ results.push({
108
+ status: "FOUND",
109
+ id: d.id,
110
+ statement: d.statement.slice(0, 60),
111
+ });
112
+ } else {
113
+ // Check section match as fallback
114
+ const section = d.target?.section;
115
+ if (section && contentLower.includes(section.toLowerCase())) {
116
+ results.push({
117
+ status: "FOUND",
118
+ id: d.id,
119
+ statement: d.statement.slice(0, 60),
120
+ detail: "via section match",
121
+ });
122
+ } else {
123
+ results.push({
124
+ status: "MISSING",
125
+ id: d.id,
126
+ statement: d.statement.slice(0, 60),
127
+ detail: `not found in ${ref}`,
128
+ });
129
+ }
130
+ }
131
+ }
132
+
133
+ // Report
134
+ let found = 0;
135
+ let missing = 0;
136
+
137
+ for (const r of results) {
138
+ if (r.status === "FOUND") {
139
+ found++;
140
+ const suffix = r.detail ? ` (${r.detail})` : "";
141
+ console.log(` FOUND: ${r.id} — ${r.statement}${suffix}`);
142
+ } else {
143
+ missing++;
144
+ console.log(` MISSING: ${r.id} — ${r.statement} (${r.detail})`);
145
+ }
146
+ }
147
+
148
+ console.log("");
149
+ console.log(
150
+ `=== Reconcile: ${found} found, ${missing} missing out of ${found + missing} decisions ===`
151
+ );
152
+ process.exit(missing === 0 ? 0 : 1);
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env bun
2
+ import { existsSync, readFileSync, writeFileSync, readdirSync } from "fs";
3
+ import { join, relative } from "path";
4
+ import { createHash } from "crypto";
5
+ import { SIGNAL_PHRASE_PATTERNS } from "../lib/signal-phrases";
6
+
7
+ // ── Types ────────────────────────────────────────────────────────
8
+
9
+ export interface Candidate {
10
+ rule: string;
11
+ source: string;
12
+ context: string;
13
+ hash: string;
14
+ }
15
+
16
+ export interface StalenessEntry {
17
+ file: string;
18
+ daysSince: number;
19
+ threshold: number;
20
+ type: string;
21
+ }
22
+
23
+ export interface ExtractResult {
24
+ candidates: Candidate[];
25
+ deduped: {
26
+ existingConstraints: number;
27
+ rejectedPrior: number;
28
+ candidatesRemoved: number;
29
+ };
30
+ staleness: StalenessEntry[];
31
+ }
32
+
33
+ // ── Helpers ──────────────────────────────────────────────────────
34
+
35
+ export function contentHash(text: string): string {
36
+ return createHash("sha256").update(text.trim().toLowerCase()).digest("hex").slice(0, 12);
37
+ }
38
+
39
+ function surroundingContext(lines: string[], lineIdx: number): string {
40
+ const start = Math.max(0, lineIdx - 1);
41
+ const end = Math.min(lines.length, lineIdx + 2);
42
+ return lines.slice(start, end).join("\n");
43
+ }
44
+
45
+ function collectScanTargets(projectPath: string): string[] {
46
+ const targets: string[] = [];
47
+
48
+ const rootFiles = ["ARCHITECTURE.md", "PRINCIPLES.md", "CONTRIBUTING.md", "CLAUDE.md"];
49
+ for (const f of rootFiles) {
50
+ const p = join(projectPath, f);
51
+ if (existsSync(p)) targets.push(p);
52
+ }
53
+
54
+ const docsDir = join(projectPath, "docs");
55
+ if (existsSync(docsDir)) {
56
+ for (const f of readdirSync(docsDir)) {
57
+ if (f === "archive" || !f.endsWith(".md")) continue;
58
+ targets.push(join(docsDir, f));
59
+ }
60
+ const adrDir = join(docsDir, "adr");
61
+ if (existsSync(adrDir)) {
62
+ for (const f of readdirSync(adrDir)) {
63
+ if (!f.endsWith(".md")) continue;
64
+ targets.push(join(adrDir, f));
65
+ }
66
+ }
67
+ }
68
+
69
+ const specsDir = join(projectPath, "specs");
70
+ if (existsSync(specsDir)) {
71
+ for (const f of readdirSync(specsDir)) {
72
+ if (!f.endsWith(".md")) continue;
73
+ targets.push(join(specsDir, f));
74
+ }
75
+ }
76
+
77
+ return targets;
78
+ }
79
+
80
+ function extractSignalPhrases(content: string, filePath: string, projectPath: string): Candidate[] {
81
+ const lines = content.split("\n");
82
+ const candidates: Candidate[] = [];
83
+ const seen = new Set<string>();
84
+ const rel = relative(projectPath, filePath);
85
+
86
+ for (const pattern of SIGNAL_PHRASE_PATTERNS) {
87
+ const re = new RegExp(pattern.source, pattern.flags);
88
+ for (const m of content.matchAll(re)) {
89
+ const rule = m[0].replace(/^[-*] /, "").trim().replace(/[.;]$/, "");
90
+ if (!rule || rule.length < 10) continue;
91
+ const hash = contentHash(rule);
92
+ if (seen.has(hash)) continue;
93
+ seen.add(hash);
94
+
95
+ const matchOffset = m.index ?? 0;
96
+ const lineIdx = content.slice(0, matchOffset).split("\n").length - 1;
97
+ const lineNum = lineIdx + 1;
98
+
99
+ candidates.push({
100
+ rule,
101
+ source: `${rel}:${lineNum}`,
102
+ context: surroundingContext(lines, lineIdx),
103
+ hash,
104
+ });
105
+ }
106
+ }
107
+
108
+ return candidates;
109
+ }
110
+
111
+ function loadExistingConstraints(projectPath: string): string[] {
112
+ const agentsPath = join(projectPath, "AGENTS.md");
113
+ if (!existsSync(agentsPath)) return [];
114
+ const content = readFileSync(agentsPath, "utf-8");
115
+ const hcMatch = content.match(/## Hard Constraints[^\n]*\n\n([\s\S]*?)(?=\n## |\s*$)/);
116
+ if (!hcMatch) return [];
117
+ return hcMatch[1]
118
+ .split("\n")
119
+ .filter((l) => l.startsWith("- "))
120
+ .map((l) => l.replace(/^- \*\*[^*]+\*\*\s*—?\s*/, "").trim().toLowerCase());
121
+ }
122
+
123
+ function loadRejectedHashes(projectPath: string): Set<string> {
124
+ const rejectedPath = join(projectPath, "reference", "rejected-constraints.md");
125
+ if (!existsSync(rejectedPath)) return new Set();
126
+ const content = readFileSync(rejectedPath, "utf-8");
127
+ const hashes = new Set<string>();
128
+ for (const line of content.split("\n")) {
129
+ const m = line.match(/^\|\s*([a-f0-9]+)\s*\|/);
130
+ if (m) hashes.add(m[1]);
131
+ }
132
+ return hashes;
133
+ }
134
+
135
+ function computeStaleness(projectPath: string, files: string[]): StalenessEntry[] {
136
+ const stale: StalenessEntry[] = [];
137
+ for (const filePath of files) {
138
+ const rel = relative(projectPath, filePath);
139
+ const isAdr = rel.includes("docs/adr/") || /ADR/i.test(rel);
140
+ if (isAdr) continue;
141
+ try {
142
+ const result = Bun.spawnSync(["git", "-C", projectPath, "log", "-1", "--format=%ci", "--", rel], { timeout: 5_000 });
143
+ const dateStr = result.stdout.toString().trim().split(" ")[0];
144
+ if (!dateStr) continue;
145
+ const daysSince = (Date.now() - new Date(dateStr).getTime()) / (1000 * 60 * 60 * 24);
146
+ const isSpec = rel.startsWith("specs/");
147
+ const threshold = isSpec ? 90 : 180;
148
+ const type = isSpec ? "spec" : "guide";
149
+ if (daysSince > threshold) {
150
+ stale.push({ file: rel, daysSince: Math.floor(daysSince), threshold, type });
151
+ }
152
+ } catch {}
153
+ }
154
+ return stale;
155
+ }
156
+
157
+ function applyToAgentsMd(projectPath: string, candidates: Candidate[]): void {
158
+ const agentsPath = join(projectPath, "AGENTS.md");
159
+ if (!existsSync(agentsPath)) return;
160
+ let content = readFileSync(agentsPath, "utf-8");
161
+
162
+ const formatted = candidates
163
+ .map((c) => {
164
+ const short = c.rule.length > 60 ? c.rule.slice(0, 57) + "..." : c.rule;
165
+ return `- **${short}** (${c.source})`;
166
+ })
167
+ .join("\n");
168
+
169
+ const markerStart = "<!-- BEGIN AUTO-EXTRACTED -->";
170
+ const markerEnd = "<!-- END AUTO-EXTRACTED -->";
171
+
172
+ if (content.includes(markerStart)) {
173
+ content = content.replace(
174
+ new RegExp(`${markerStart}[\\s\\S]*?${markerEnd}`),
175
+ `${markerStart}\n${formatted}\n${markerEnd}`
176
+ );
177
+ } else {
178
+ const hcMatch = content.match(/## Hard Constraints[^\n]*\n\n/);
179
+ if (hcMatch) {
180
+ const insertPos = (hcMatch.index ?? 0) + hcMatch[0].length;
181
+ content =
182
+ content.slice(0, insertPos) +
183
+ `${markerStart}\n${formatted}\n${markerEnd}\n\n` +
184
+ content.slice(insertPos);
185
+ }
186
+ }
187
+
188
+ writeFileSync(agentsPath, content);
189
+ }
190
+
191
+ // ── Main export ──────────────────────────────────────────────────
192
+
193
+ export async function extractConstraints(
194
+ projectPath: string,
195
+ options?: { apply?: boolean }
196
+ ): Promise<ExtractResult> {
197
+ const scanFiles = collectScanTargets(projectPath);
198
+ const existingConstraints = loadExistingConstraints(projectPath);
199
+ const rejectedHashes = loadRejectedHashes(projectPath);
200
+
201
+ let allCandidates: Candidate[] = [];
202
+ for (const filePath of scanFiles) {
203
+ const content = readFileSync(filePath, "utf-8");
204
+ allCandidates.push(...extractSignalPhrases(content, filePath, projectPath));
205
+ }
206
+
207
+ const beforeCount = allCandidates.length;
208
+ let existingRemoved = 0;
209
+ let rejectedRemoved = 0;
210
+
211
+ allCandidates = allCandidates.filter((c) => {
212
+ if (rejectedHashes.has(c.hash)) {
213
+ rejectedRemoved++;
214
+ return false;
215
+ }
216
+ const lower = c.rule.toLowerCase();
217
+ if (existingConstraints.some((ec) => lower.includes(ec) || ec.includes(lower))) {
218
+ existingRemoved++;
219
+ return false;
220
+ }
221
+ return true;
222
+ });
223
+
224
+ const staleness = computeStaleness(projectPath, scanFiles);
225
+
226
+ if (options?.apply && allCandidates.length > 0) {
227
+ applyToAgentsMd(projectPath, allCandidates);
228
+ }
229
+
230
+ return {
231
+ candidates: allCandidates,
232
+ deduped: {
233
+ existingConstraints: existingRemoved,
234
+ rejectedPrior: rejectedRemoved,
235
+ candidatesRemoved: existingRemoved + rejectedRemoved,
236
+ },
237
+ staleness,
238
+ };
239
+ }
240
+
241
+ // ── CLI entry ────────────────────────────────────────────────────
242
+
243
+ if (import.meta.main) {
244
+ const args = process.argv.slice(2);
245
+ const projectPath = args.find((a) => !a.startsWith("--"));
246
+ const apply = args.includes("--apply");
247
+
248
+ if (!projectPath) {
249
+ console.error("Usage: extract-constraints.ts /path/to/project [--apply]");
250
+ process.exit(1);
251
+ }
252
+
253
+ if (!existsSync(projectPath)) {
254
+ console.error(`ERROR: Path does not exist: ${projectPath}`);
255
+ process.exit(1);
256
+ }
257
+
258
+ const result = await extractConstraints(projectPath, { apply });
259
+ console.log(JSON.stringify(result, null, 2));
260
+ }