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,959 @@
1
+ /**
2
+ * Exportable conformity test functions.
3
+ *
4
+ * Projects import these and pass their root path:
5
+ * import { runScaffoldConformity, runSpecDiscovery, runSpecDrift } from "rungate/lib/conformity";
6
+ * runScaffoldConformity(import.meta.dir + "/..");
7
+ */
8
+ import { describe, test, expect } from "bun:test";
9
+ import { existsSync, readFileSync, readdirSync } from "fs";
10
+ import { join } from "path";
11
+
12
+ // ── Shared utilities ────────────────────────────────────────
13
+
14
+ export function parseFrontmatter(content: string): Record<string, string> | null {
15
+ const match = content.match(/^---\n([\s\S]*?)\n---/);
16
+ if (!match) return null;
17
+ const fields: Record<string, string> = {};
18
+ for (const line of match[1].split("\n")) {
19
+ const kv = line.match(/^(\w[\w-]*):\s*(.+)$/);
20
+ if (kv) fields[kv[1]] = kv[2].trim();
21
+ }
22
+ return fields;
23
+ }
24
+
25
+ export { SIGNAL_PHRASE_PATTERNS } from "./signal-phrases";
26
+
27
+ // ── Structured findings (machine-readable for agents) ──────
28
+
29
+ export interface ConformityFinding {
30
+ ruleId: string;
31
+ severity: "FAIL" | "WARN";
32
+ file: string;
33
+ message: string;
34
+ fixCommand?: string;
35
+ }
36
+
37
+ export interface ConstraintCandidate {
38
+ rule: string;
39
+ source: string;
40
+ hash: string;
41
+ status: "pending" | "applied" | "rejected";
42
+ }
43
+
44
+ export interface StalenessEntry {
45
+ file: string;
46
+ daysSince: number;
47
+ threshold: number;
48
+ type: string;
49
+ }
50
+
51
+ const _findings: ConformityFinding[] = [];
52
+ const _candidates: ConstraintCandidate[] = [];
53
+ const _staleness: StalenessEntry[] = [];
54
+
55
+ export function addFinding(finding: ConformityFinding): void {
56
+ _findings.push(finding);
57
+ }
58
+
59
+ export function addCandidate(candidate: ConstraintCandidate): void {
60
+ _candidates.push(candidate);
61
+ }
62
+
63
+ export function addStaleness(entry: StalenessEntry): void {
64
+ _staleness.push(entry);
65
+ }
66
+
67
+ export function getFindings(): ConformityFinding[] {
68
+ return [..._findings];
69
+ }
70
+
71
+ export function getCandidates(): ConstraintCandidate[] {
72
+ return [..._candidates];
73
+ }
74
+
75
+ export function getStaleness(): StalenessEntry[] {
76
+ return [..._staleness];
77
+ }
78
+
79
+ export function clearFindings(): void {
80
+ _findings.length = 0;
81
+ _candidates.length = 0;
82
+ _staleness.length = 0;
83
+ }
84
+
85
+ export function writeFindingsReport(root: string): string {
86
+ const reportPath = join(root, ".rungate", "conformity-findings.json");
87
+ const dir = join(root, ".rungate");
88
+ if (!existsSync(dir)) {
89
+ require("fs").mkdirSync(dir, { recursive: true });
90
+ }
91
+ require("fs").writeFileSync(reportPath, JSON.stringify({
92
+ timestamp: new Date().toISOString(),
93
+ total: _findings.length + _candidates.length + _staleness.length,
94
+ failures: _findings.filter(f => f.severity === "FAIL").length,
95
+ warnings: _findings.filter(f => f.severity === "WARN").length,
96
+ candidateCount: _candidates.length,
97
+ staleCount: _staleness.length,
98
+ findings: _findings,
99
+ constraintCandidates: _candidates,
100
+ staleness: _staleness,
101
+ }, null, 2));
102
+ return reportPath;
103
+ }
104
+
105
+ interface ParsedSC {
106
+ id: string;
107
+ statement: string;
108
+ specFile: string;
109
+ }
110
+
111
+ function extractSCs(content: string, specFile: string): ParsedSC[] {
112
+ const scs: ParsedSC[] = [];
113
+ const pattern = /^- \[ \] (SC-\w+):\s*(.+)$/gm;
114
+ let match;
115
+ while ((match = pattern.exec(content)) !== null) {
116
+ scs.push({ id: match[1], statement: match[2].trim(), specFile });
117
+ }
118
+ return scs;
119
+ }
120
+
121
+ function collectTestableSpecs(root: string, extraSpecDirs?: string[]): ParsedSC[] {
122
+ const allSCs: ParsedSC[] = [];
123
+
124
+ const localSpecs = join(root, "specs");
125
+ if (existsSync(localSpecs)) {
126
+ for (const f of readdirSync(localSpecs).filter(f => f.endsWith(".md"))) {
127
+ const content = readFileSync(join(localSpecs, f), "utf-8");
128
+ const fm = parseFrontmatter(content);
129
+ if (fm?.testable === "true") {
130
+ allSCs.push(...extractSCs(content, f));
131
+ }
132
+ }
133
+ }
134
+
135
+ for (const dir of extraSpecDirs || []) {
136
+ if (!existsSync(dir)) continue;
137
+ for (const f of readdirSync(dir).filter(f => f.endsWith(".md"))) {
138
+ const content = readFileSync(join(dir, f), "utf-8");
139
+ const fm = parseFrontmatter(content);
140
+ if (fm?.testable !== "true") continue;
141
+ const governs = fm?.governs || "";
142
+ if (!governs.toLowerCase().includes("scaffold") && !governs.toLowerCase().includes("universal")) continue;
143
+ allSCs.push(...extractSCs(content, `${dir.split("/").pop()}/${f}`));
144
+ }
145
+ }
146
+
147
+ return allSCs;
148
+ }
149
+
150
+ // ── Pattern matchers ────────────────────────────────────────
151
+
152
+ type AssertionFn = (root: string) => void;
153
+
154
+ function matchPattern(sc: ParsedSC): AssertionFn | null {
155
+ const s = sc.statement;
156
+
157
+ const existsMatch = s.match(/^(\S+)\s+exists?\b(?:\s+at\s+root)?/i);
158
+ if (existsMatch) {
159
+ const target = existsMatch[1].replace(/`/g, "");
160
+ if (target.startsWith("~/") || target.startsWith("/")) return null;
161
+ const limitMatch = s.match(/≤\s*(\d+)\s*lines/);
162
+ return (root) => {
163
+ expect(existsSync(join(root, target))).toBe(true);
164
+ if (limitMatch) {
165
+ const content = readFileSync(join(root, target), "utf-8");
166
+ expect(content.split("\n").length).toBeLessThanOrEqual(parseInt(limitMatch[1]));
167
+ }
168
+ };
169
+ }
170
+
171
+ const dirMatch = s.match(/^(\S+?)\/?\s+directory\s+exists/i);
172
+ if (dirMatch) {
173
+ const dir = dirMatch[1].replace(/`/g, "");
174
+ const minMatch = s.match(/(?:with\s+)?≥\s*(\d+)\s+(\w+)/);
175
+ const aliases: Record<string, string[]> = {
176
+ "tests": ["tests", "test"],
177
+ "test": ["test", "tests"],
178
+ "reference": ["reference", "ref", "docs/archive"],
179
+ };
180
+ const candidates = aliases[dir] || [dir];
181
+ return (root) => {
182
+ const found = candidates.find(d => existsSync(join(root, d)));
183
+ expect(found).toBeDefined();
184
+ if (minMatch && found) {
185
+ expect(readdirSync(join(root, found)).length).toBeGreaterThanOrEqual(parseInt(minMatch[1]));
186
+ }
187
+ };
188
+ }
189
+
190
+ if (/^all\s+specs\s+have\b/i.test(s) && /frontmatter/i.test(s)) {
191
+ return (root) => {
192
+ const specsDir = join(root, "specs");
193
+ if (!existsSync(specsDir)) return;
194
+ const missing = readdirSync(specsDir).filter(f => f.endsWith(".md")).filter(f => {
195
+ const fm = parseFrontmatter(readFileSync(join(specsDir, f), "utf-8"));
196
+ return !fm || !("testable" in fm);
197
+ });
198
+ expect(missing).toEqual([]);
199
+ };
200
+ }
201
+
202
+ if (/all\s+paths\s+referenced\s+in\s+(\S+)\s+resolve/i.test(s)) {
203
+ const fileMatch = s.match(/in\s+(\S+)/i);
204
+ const target = fileMatch?.[1]?.replace(/`/g, "") || "AGENTS.md";
205
+ return (root) => {
206
+ const p = join(root, target);
207
+ if (!existsSync(p)) return;
208
+ const content = readFileSync(p, "utf-8");
209
+ const linkPattern = /\[.*?\]\(([^)]+)\)/g;
210
+ let m;
211
+ const broken: string[] = [];
212
+ while ((m = linkPattern.exec(content)) !== null) {
213
+ if (m[1].startsWith("http") || m[1].startsWith("#")) continue;
214
+ if (!existsSync(join(root, m[1]))) broken.push(m[1]);
215
+ }
216
+ expect(broken).toEqual([]);
217
+ };
218
+ }
219
+
220
+ if (/root\s+is\s+clean/i.test(s)) {
221
+ const contentLimit = s.match(/content:\s*≤\s*(\d+)/i);
222
+ const codeLimit = s.match(/code:\s*≤\s*(\d+)/i);
223
+ return (root) => {
224
+ const items = readdirSync(root).filter(f => !f.startsWith(".") && f !== "node_modules");
225
+ // Detect project type: if src/, lib/, gates/, or package.json with deps → code project
226
+ const isCode = existsSync(join(root, "src")) || existsSync(join(root, "lib")) ||
227
+ existsSync(join(root, "gates")) || existsSync(join(root, "Makefile"));
228
+ const limit = isCode
229
+ ? (codeLimit ? parseInt(codeLimit[1]) : 30)
230
+ : (contentLimit ? parseInt(contentLimit[1]) : 10);
231
+ expect(items.length).toBeLessThanOrEqual(limit);
232
+ };
233
+ }
234
+
235
+ const pointerMatch = s.match(/(\S+)\s+exists\s+with\s+pointer\s+to\s+(\S+)/i);
236
+ if (pointerMatch) {
237
+ const file = pointerMatch[1].replace(/`/g, "");
238
+ const target = pointerMatch[2].replace(/`/g, "");
239
+ return (root) => {
240
+ expect(existsSync(join(root, file))).toBe(true);
241
+ expect(readFileSync(join(root, file), "utf-8")).toContain(target);
242
+ };
243
+ }
244
+
245
+ if (/bun\s+test.*passes/i.test(s)) return () => { expect(true).toBe(true); };
246
+
247
+ if (/canary/i.test(s)) {
248
+ return (root) => {
249
+ const testDir = existsSync(join(root, "test")) ? join(root, "test") : join(root, "tests");
250
+ if (!existsSync(testDir)) return;
251
+ const testFiles = readdirSync(testDir).filter(f => f.includes("conformity") || f.includes("canary"));
252
+ expect(testFiles.length).toBeGreaterThanOrEqual(1);
253
+ };
254
+ }
255
+
256
+ return null;
257
+ }
258
+
259
+ // ── Exported test runners ───────────────────────────────────
260
+
261
+ export function runScaffoldConformity(root: string, opts?: { extraSpecDirs?: string[] }) {
262
+ const HOME = process.env.HOME || "";
263
+ const defaultExtraSpecs = [join(HOME, ".claude", "PAI", "specs")];
264
+ const allSCs = collectTestableSpecs(root, opts?.extraSpecDirs ?? defaultExtraSpecs);
265
+
266
+ describe("Spec-Driven Conformity Tests", () => {
267
+ if (allSCs.length === 0) {
268
+ test("at least one testable spec with SCs exists", () => {
269
+ expect(allSCs.length).toBeGreaterThan(0);
270
+ });
271
+ return;
272
+ }
273
+
274
+ const bySpec = new Map<string, ParsedSC[]>();
275
+ for (const sc of allSCs) {
276
+ const group = bySpec.get(sc.specFile) || [];
277
+ group.push(sc);
278
+ bySpec.set(sc.specFile, group);
279
+ }
280
+
281
+ for (const [specFile, scs] of bySpec) {
282
+ describe(specFile, () => {
283
+ const unmatched: string[] = [];
284
+ for (const sc of scs) {
285
+ const assertion = matchPattern(sc);
286
+ if (!assertion) { unmatched.push(`${sc.id}: ${sc.statement}`); continue; }
287
+ test(`${sc.id}: ${sc.statement}`, () => { assertion(root); });
288
+ }
289
+ if (unmatched.length > 0) {
290
+ test(`WARN: ${unmatched.length} SCs have no pattern matcher`, () => {
291
+ console.warn(`Unmatched SCs in ${specFile}:\n ${unmatched.join("\n ")}`);
292
+ expect(true).toBe(true);
293
+ });
294
+ }
295
+ });
296
+ }
297
+ });
298
+
299
+ describe("Scaffold: structural checks", () => {
300
+ test("AGENTS.md has required standard sections", () => {
301
+ if (!existsSync(join(root, "AGENTS.md"))) {
302
+ expect(existsSync(join(root, "AGENTS.md"))).toBe(true);
303
+ return;
304
+ }
305
+ const content = readFileSync(join(root, "AGENTS.md"), "utf-8");
306
+ const required = ["Project Identity", "Key Files", "Specs", "Tests", "Workflow"];
307
+ const missing = required.filter(s => !content.toLowerCase().includes(s.toLowerCase()));
308
+ expect(missing).toEqual([]);
309
+ });
310
+
311
+ test("rungate.json has required fields (if exists)", () => {
312
+ const p = join(root, ".claude", "rungate.json");
313
+ if (!existsSync(p)) return;
314
+ const config = JSON.parse(readFileSync(p, "utf-8"));
315
+ expect(config.project).toBeDefined();
316
+ expect(config.repo).toBeDefined();
317
+ });
318
+
319
+ test("AGENTS.md/CLAUDE.md no duplication (if both exist)", () => {
320
+ if (!existsSync(join(root, "AGENTS.md")) || !existsSync(join(root, "CLAUDE.md"))) return;
321
+ const agents = readFileSync(join(root, "AGENTS.md"), "utf-8");
322
+ const claude = readFileSync(join(root, "CLAUDE.md"), "utf-8");
323
+ const sentences = agents.split(/[.!?\n]/).map(s => s.trim()).filter(s => s.length > 30);
324
+ expect(sentences.filter(s => claude.includes(s))).toEqual([]);
325
+ });
326
+ });
327
+ }
328
+
329
+ export function runSpecDiscovery(root: string) {
330
+ const specsDir = join(root, "specs");
331
+
332
+ describe("Spec Discovery: frontmatter enforcement", () => {
333
+ test("specs/ directory exists", () => {
334
+ expect(existsSync(specsDir)).toBe(true);
335
+ });
336
+
337
+ test("every .md in specs/ has testable field", () => {
338
+ if (!existsSync(specsDir)) return;
339
+ const missing = readdirSync(specsDir).filter(f => f.endsWith(".md")).filter(f => {
340
+ const fm = parseFrontmatter(readFileSync(join(specsDir, f), "utf-8"));
341
+ return !fm || !("testable" in fm);
342
+ });
343
+ expect(missing).toEqual([]);
344
+ });
345
+
346
+ test("at least one testable spec exists", () => {
347
+ if (!existsSync(specsDir)) return;
348
+ const testable = readdirSync(specsDir).filter(f => f.endsWith(".md")).filter(f => {
349
+ const fm = parseFrontmatter(readFileSync(join(specsDir, f), "utf-8"));
350
+ return fm?.testable === "true";
351
+ });
352
+ expect(testable.length).toBeGreaterThan(0);
353
+ });
354
+ });
355
+ }
356
+
357
+ export function runSpecDrift(root: string) {
358
+ const specsDir = join(root, "specs");
359
+ const testDirs = [join(root, "test"), join(root, "tests")].filter(d => existsSync(d));
360
+
361
+ interface SpecRef { specFile: string; section: string; testFile: string; line: number; }
362
+
363
+ function extractRefs(testFile: string, dir: string): SpecRef[] {
364
+ const content = readFileSync(join(dir, testFile), "utf-8");
365
+ const refs: SpecRef[] = [];
366
+ const lines = content.split("\n");
367
+ for (let i = 0; i < lines.length; i++) {
368
+ const structured = lines[i].match(/\/\/\s*SPEC-REF:\s*(\S+\.md)\s*§\s*(.+)/);
369
+ if (structured && !structured[1].match(/^(filename|FILENAME|example)\./i)) {
370
+ refs.push({ specFile: structured[1], section: structured[2].trim(), testFile, line: i + 1 });
371
+ }
372
+ }
373
+ return refs;
374
+ }
375
+
376
+ describe("Spec-Test Drift Detector", () => {
377
+ test("DRIFT-1: Every SPEC-REF points to an existing spec file", () => {
378
+ const allRefs: SpecRef[] = [];
379
+ for (const dir of testDirs) {
380
+ for (const tf of readdirSync(dir).filter(f => f.endsWith(".test.ts"))) {
381
+ allRefs.push(...extractRefs(tf, dir));
382
+ }
383
+ }
384
+ const broken = allRefs.filter(r => !existsSync(join(specsDir, r.specFile)))
385
+ .map(r => `${r.testFile}:${r.line} → ${r.specFile}`);
386
+ expect(broken).toEqual([]);
387
+ });
388
+
389
+ test("DRIFT-2: Every testable spec is referenced by at least one test", () => {
390
+ if (!existsSync(specsDir)) return;
391
+ const testable = readdirSync(specsDir).filter(f => f.endsWith(".md")).filter(f => {
392
+ const fm = parseFrontmatter(readFileSync(join(specsDir, f), "utf-8"));
393
+ return fm?.testable === "true";
394
+ });
395
+
396
+ let allContent = "";
397
+ for (const dir of testDirs) {
398
+ for (const tf of readdirSync(dir).filter(f => f.endsWith(".test.ts"))) {
399
+ allContent += readFileSync(join(dir, tf), "utf-8");
400
+ }
401
+ }
402
+
403
+ const orphaned = testable.filter(s => !allContent.includes(s));
404
+ if (orphaned.length > 0) {
405
+ console.warn(`Testable specs with no test references: ${orphaned.join(", ")}`);
406
+ }
407
+ expect(true).toBe(true);
408
+ });
409
+ });
410
+ }
411
+
412
+ export function runDocHygiene(root: string) {
413
+ const specsDir = join(root, "specs");
414
+ const refDir = join(root, "reference");
415
+ // .claude/agents/ excluded — Claude Code reads those by name convention, not import
416
+ const scanPaths = ["specs", "scripts", "prompts"];
417
+ const scanDirs = scanPaths.map(d => join(root, d)).filter(d => existsSync(d));
418
+ const testDirs = [join(root, "test"), join(root, "tests")].filter(d => existsSync(d));
419
+
420
+ // Build reference index once — scan code/config/docs directories only (skip data/cache)
421
+ function buildReferenceIndex(): string {
422
+ const exts = [".ts", ".js", ".md", ".json"];
423
+ const skipDirs = new Set(["node_modules", "reference", ".git", "dist", "build", ".next",
424
+ "cache", "logs", "reports", "ctrf", "eval", "MEMORY"]);
425
+ const skipPrefixes = ["data-", "data/"];
426
+
427
+ const searchDirs: string[] = [root];
428
+ for (const entry of readdirSync(root)) {
429
+ if (entry.startsWith(".") || skipDirs.has(entry) || skipPrefixes.some(p => entry.startsWith(p))) continue;
430
+ const full = join(root, entry);
431
+ try { if (require("fs").statSync(full).isDirectory()) searchDirs.push(full); } catch {}
432
+ }
433
+ const dotClaude = join(root, ".claude");
434
+ if (existsSync(dotClaude)) searchDirs.push(dotClaude);
435
+
436
+ const chunks: string[] = [];
437
+ for (const dir of searchDirs) {
438
+ try {
439
+ const files = dir === root
440
+ ? readdirSync(dir).filter(f => exts.some(e => f.endsWith(e)))
441
+ : readdirSync(dir, { recursive: true }).map(f => String(f)).filter(f => exts.some(e => f.endsWith(e)));
442
+ for (const f of files) {
443
+ try { chunks.push(readFileSync(join(dir, String(f)), "utf-8")); } catch {}
444
+ }
445
+ } catch {}
446
+ }
447
+ return chunks.join("\n");
448
+ }
449
+
450
+ let _refIndex: string | null = null;
451
+ function getRefIndex(): string {
452
+ if (_refIndex === null) _refIndex = buildReferenceIndex();
453
+ return _refIndex;
454
+ }
455
+
456
+ describe("Doc Hygiene", () => {
457
+ test("HYGIENE-1: All specs have non-empty governs field", () => {
458
+ if (!existsSync(specsDir)) return;
459
+ const missing: string[] = [];
460
+ for (const f of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
461
+ const content = readFileSync(join(specsDir, f), "utf-8");
462
+ const fm = parseFrontmatter(content);
463
+ if (!fm) continue;
464
+ const governs = fm.governs || "";
465
+ if (!governs || governs.includes("TODO")) missing.push(f);
466
+ }
467
+ if (missing.length > 0) {
468
+ console.warn(`Specs with empty/TODO governs field: ${missing.join(", ")}`);
469
+ }
470
+ expect(true).toBe(true);
471
+ });
472
+
473
+ test("HYGIENE-2: All specs have updated field in frontmatter", () => {
474
+ if (!existsSync(specsDir)) return;
475
+ const missing: string[] = [];
476
+ for (const f of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
477
+ const content = readFileSync(join(specsDir, f), "utf-8");
478
+ const fm = parseFrontmatter(content);
479
+ if (!fm || !fm.updated) missing.push(f);
480
+ }
481
+ expect(missing).toEqual([]);
482
+ });
483
+
484
+ test("HYGIENE-3: No orphaned files (zero references outside reference/)", () => {
485
+ const index = getRefIndex();
486
+ const orphans: string[] = [];
487
+ for (const dir of scanDirs) {
488
+ const relPath = dir.startsWith(root) ? dir.slice(root.length + 1) : dir.split("/").pop()!;
489
+ for (const f of readdirSync(dir).filter(f => !f.startsWith("."))) {
490
+ if (!index.includes(f)) orphans.push(`${relPath}/${f}`);
491
+ }
492
+ }
493
+ if (orphans.length > 0) {
494
+ console.warn(`Orphaned files (0 references — consider archiving to reference/):\n ${orphans.join("\n ")}`);
495
+ }
496
+ expect(true).toBe(true);
497
+ });
498
+
499
+ test("HYGIENE-4: All specs listed in AGENTS.md are in AGENTS.md specs table", () => {
500
+ if (!existsSync(specsDir) || !existsSync(join(root, "AGENTS.md"))) return;
501
+ const agentsContent = readFileSync(join(root, "AGENTS.md"), "utf-8");
502
+ const specFiles = readdirSync(specsDir).filter(f => f.endsWith(".md"));
503
+ const unlisted = specFiles.filter(f => !agentsContent.includes(f));
504
+ if (unlisted.length > 0) {
505
+ console.warn(`Specs not listed in AGENTS.md: ${unlisted.join(", ")}`);
506
+ }
507
+ expect(true).toBe(true);
508
+ });
509
+
510
+ test("HYGIENE-5: reference/ contents not in active routing", () => {
511
+ if (!existsSync(refDir) || !existsSync(join(root, "AGENTS.md"))) return;
512
+ const agentsContent = readFileSync(join(root, "AGENTS.md"), "utf-8");
513
+ const leaked: string[] = [];
514
+ for (const sub of readdirSync(refDir)) {
515
+ const subPath = join(refDir, sub);
516
+ try {
517
+ if (require("fs").statSync(subPath).isDirectory()) {
518
+ for (const f of readdirSync(subPath)) {
519
+ if (agentsContent.includes(f) && !agentsContent.includes("reference/")) leaked.push(`reference/${sub}/${f}`);
520
+ }
521
+ } else {
522
+ if (agentsContent.includes(sub) && !agentsContent.includes("reference/")) leaked.push(`reference/${sub}`);
523
+ }
524
+ } catch {}
525
+ }
526
+ if (leaked.length > 0) {
527
+ console.warn(`Archived files still referenced in AGENTS.md (stale routing): ${leaked.join(", ")}`);
528
+ }
529
+ expect(true).toBe(true);
530
+ });
531
+
532
+ test("HYGIENE-10: All ADRs have doc-type: adr in frontmatter", () => {
533
+ const adrDir = join(root, "docs", "adr");
534
+ if (!existsSync(adrDir)) return;
535
+ const missing: string[] = [];
536
+ for (const f of readdirSync(adrDir).filter(f => f.endsWith(".md"))) {
537
+ const content = readFileSync(join(adrDir, f), "utf-8");
538
+ const fm = parseFrontmatter(content);
539
+ if (!fm || fm["doc-type"] !== "adr") {
540
+ missing.push(f);
541
+ addFinding({
542
+ ruleId: "HYGIENE-10",
543
+ severity: "FAIL",
544
+ file: `docs/adr/${f}`,
545
+ message: `ADR "${f}" missing doc-type: adr in frontmatter`,
546
+ fixCommand: `Add "doc-type: adr" to frontmatter of docs/adr/${f}`,
547
+ });
548
+ }
549
+ }
550
+ if (missing.length > 0) {
551
+ console.error(`HYGIENE-10 FAIL: ADRs missing doc-type: ${missing.join(", ")}`);
552
+ }
553
+ expect(missing).toEqual([]);
554
+ });
555
+
556
+ test("HYGIENE-7: No spec files at root (must be in specs/)", () => {
557
+ const allowlist = new Set([
558
+ "AGENTS.md", "CLAUDE.md", "CLAUDE.local.md", "CODE-MAP.md",
559
+ "README.md", "CHANGELOG.md", "CONTRIBUTING.md", "LICENSE.md",
560
+ "ARCHITECTURE.md", "PRINCIPLES.md", "MODEL.md", "PROJECT-STATE.md",
561
+ ]);
562
+ const misplaced: string[] = [];
563
+ for (const f of readdirSync(root).filter(f => f.endsWith(".md"))) {
564
+ if (allowlist.has(f)) continue;
565
+ const content = readFileSync(join(root, f), "utf-8");
566
+ const fm = parseFrontmatter(content);
567
+ if (fm?.["doc-type"] === "spec") {
568
+ misplaced.push(f);
569
+ addFinding({
570
+ ruleId: "HYGIENE-7",
571
+ severity: "FAIL",
572
+ file: f,
573
+ message: `Spec "${f}" is at root — must be in specs/`,
574
+ fixCommand: `mv ${f} specs/${f}`,
575
+ });
576
+ }
577
+ }
578
+ if (misplaced.length > 0) {
579
+ console.error(`HYGIENE-7 FAIL: Specs at root: ${misplaced.join(", ")}. Move to specs/.`);
580
+ }
581
+ expect(misplaced).toEqual([]);
582
+ });
583
+
584
+ test("HYGIENE-8: No ADR files outside docs/adr/", () => {
585
+ const misplaced: string[] = [];
586
+ const checkDirs = [root, join(root, "docs"), join(root, "specs")];
587
+ for (const dir of checkDirs) {
588
+ if (!existsSync(dir)) continue;
589
+ for (const f of readdirSync(dir).filter(f => f.endsWith(".md"))) {
590
+ const content = readFileSync(join(dir, f), "utf-8");
591
+ const fm = parseFrontmatter(content);
592
+ if (fm?.["doc-type"] === "adr") {
593
+ const relPath = dir === root ? f : `${dir.replace(root + "/", "")}/${f}`;
594
+ misplaced.push(relPath);
595
+ addFinding({
596
+ ruleId: "HYGIENE-8",
597
+ severity: "FAIL",
598
+ file: relPath,
599
+ message: `ADR "${relPath}" is outside docs/adr/ — must be in docs/adr/`,
600
+ fixCommand: `mv ${relPath} docs/adr/${f}`,
601
+ });
602
+ }
603
+ }
604
+ }
605
+ if (misplaced.length > 0) {
606
+ console.error(`HYGIENE-8 FAIL: ADRs outside docs/adr/: ${misplaced.join(", ")}. Move to docs/adr/.`);
607
+ }
608
+ expect(misplaced).toEqual([]);
609
+ });
610
+
611
+ test("HYGIENE-9: No doc files at root (except allowlisted)", () => {
612
+ const allowlist = new Set([
613
+ "AGENTS.md", "CLAUDE.md", "CLAUDE.local.md", "CODE-MAP.md",
614
+ "README.md", "CHANGELOG.md", "CONTRIBUTING.md", "LICENSE.md",
615
+ "ARCHITECTURE.md", "PRINCIPLES.md", "MODEL.md", "PROJECT-STATE.md",
616
+ ]);
617
+ const misplaced: string[] = [];
618
+ for (const f of readdirSync(root).filter(f => f.endsWith(".md"))) {
619
+ if (allowlist.has(f)) continue;
620
+ const content = readFileSync(join(root, f), "utf-8");
621
+ const fm = parseFrontmatter(content);
622
+ if (fm?.["doc-type"] === "guide" || fm?.["doc-type"] === "doc") {
623
+ misplaced.push(f);
624
+ addFinding({
625
+ ruleId: "HYGIENE-9",
626
+ severity: "FAIL",
627
+ file: f,
628
+ message: `Doc "${f}" is at root — must be in docs/`,
629
+ fixCommand: `mv ${f} docs/${f}`,
630
+ });
631
+ }
632
+ }
633
+ if (misplaced.length > 0) {
634
+ console.error(`HYGIENE-9 FAIL: Docs at root: ${misplaced.join(", ")}. Move to docs/.`);
635
+ }
636
+ expect(misplaced).toEqual([]);
637
+ });
638
+
639
+ test("HYGIENE-6: No unreviewed constraint candidates in changed docs", async () => {
640
+ const { extractConstraints } = await import("../scripts/extract-constraints");
641
+ const result = await extractConstraints(root, { apply: false });
642
+
643
+ for (const s of result.staleness) {
644
+ addStaleness({ file: s.file, daysSince: s.daysSince, threshold: s.threshold, type: s.type });
645
+ }
646
+
647
+ for (const c of result.candidates) {
648
+ addCandidate({ rule: c.rule, source: c.source, hash: c.hash, status: "pending" });
649
+ }
650
+
651
+ if (result.staleness.length > 0) {
652
+ console.warn(
653
+ `Stale docs (past threshold): ${result.staleness.map((s: any) => `${s.file} (${s.daysSince}d, ${s.type} threshold=${s.threshold}d)`).join(", ")}`
654
+ );
655
+ }
656
+
657
+ if (result.candidates.length > 0) {
658
+ console.warn(
659
+ `${result.candidates.length} unreviewed constraint candidates found. Run \`bunx rungate extract-constraints ${root}\` to review.`
660
+ );
661
+ }
662
+
663
+ expect(true).toBe(true);
664
+ });
665
+
666
+ test("HYGIENE-REPORT: Write unified findings report", () => {
667
+ const findings = getFindings();
668
+ const candidates = getCandidates();
669
+ const staleness = getStaleness();
670
+ const totalItems = findings.length + candidates.length + staleness.length;
671
+
672
+ if (totalItems > 0) {
673
+ const reportPath = writeFindingsReport(root);
674
+ console.log(`\n📋 Findings written to ${reportPath}`);
675
+ if (findings.length > 0) {
676
+ console.log(` Issues: ${findings.filter(f => f.severity === "FAIL").length} FAIL, ${findings.filter(f => f.severity === "WARN").length} WARN`);
677
+ for (const f of findings) {
678
+ console.log(` ${f.severity}: ${f.file} — ${f.message}`);
679
+ if (f.fixCommand) console.log(` Fix: ${f.fixCommand}`);
680
+ }
681
+ }
682
+ if (candidates.length > 0) {
683
+ console.log(` Constraint candidates: ${candidates.length} pending review`);
684
+ for (const c of candidates) {
685
+ console.log(` "${c.rule}" (${c.source})`);
686
+ }
687
+ console.log(` → Run \`bunx rungate extract-constraints ${root}\` to apply or reject`);
688
+ }
689
+ if (staleness.length > 0) {
690
+ console.log(` Stale docs: ${staleness.length}`);
691
+ for (const s of staleness) {
692
+ console.log(` ${s.file} — ${s.daysSince}d old (${s.type} threshold: ${s.threshold}d)`);
693
+ }
694
+ }
695
+ }
696
+ expect(true).toBe(true);
697
+ });
698
+ });
699
+ }
700
+
701
+ // ── Agent file validation ──────────────────────────────────
702
+
703
+ export function runAgentFileValidation(root: string) {
704
+ const agentsDir = join(root, ".claude", "agents");
705
+
706
+ describe("Agent File Validation", () => {
707
+ test("AGENT-1: .claude/agents/ directory exists (code projects)", () => {
708
+ const isCode = existsSync(join(root, "src")) || existsSync(join(root, "lib")) ||
709
+ existsSync(join(root, "gates")) || existsSync(join(root, "Makefile"));
710
+ if (!isCode) return;
711
+ expect(existsSync(agentsDir)).toBe(true);
712
+ });
713
+
714
+ test("AGENT-2: All agent files have required frontmatter (name + description)", () => {
715
+ if (!existsSync(agentsDir)) return;
716
+ const invalid: string[] = [];
717
+ for (const f of readdirSync(agentsDir).filter(f => f.endsWith(".md"))) {
718
+ const content = readFileSync(join(agentsDir, f), "utf-8");
719
+ const fm = parseFrontmatter(content);
720
+ if (!fm || !fm.name) invalid.push(`${f}: missing 'name' field`);
721
+ else if (!fm.description) invalid.push(`${f}: missing 'description' field`);
722
+ }
723
+ if (invalid.length > 0) {
724
+ console.warn(`Invalid agent files (Claude Code will SKIP these silently):\n ${invalid.join("\n ")}`);
725
+ }
726
+ expect(invalid).toEqual([]);
727
+ });
728
+
729
+ test("AGENT-3: Agent file names are lowercase (Claude Code matching requirement)", () => {
730
+ if (!existsSync(agentsDir)) return;
731
+ const bad: string[] = [];
732
+ for (const f of readdirSync(agentsDir).filter(f => f.endsWith(".md"))) {
733
+ const basename = f.replace(/\.md$/, "");
734
+ if (basename !== basename.toLowerCase() || basename.includes(" ")) {
735
+ bad.push(f);
736
+ }
737
+ }
738
+ expect(bad).toEqual([]);
739
+ });
740
+
741
+ test("AGENT-4: Agent name field matches filename", () => {
742
+ if (!existsSync(agentsDir)) return;
743
+ const mismatched: string[] = [];
744
+ for (const f of readdirSync(agentsDir).filter(f => f.endsWith(".md"))) {
745
+ const content = readFileSync(join(agentsDir, f), "utf-8");
746
+ const fm = parseFrontmatter(content);
747
+ if (!fm?.name) continue;
748
+ const basename = f.replace(/\.md$/, "");
749
+ if (fm.name !== basename) {
750
+ mismatched.push(`${f}: name="${fm.name}" but filename="${basename}"`);
751
+ }
752
+ }
753
+ if (mismatched.length > 0) {
754
+ console.warn(`Agent name/filename mismatch (subagent_type won't match):\n ${mismatched.join("\n ")}`);
755
+ }
756
+ expect(mismatched).toEqual([]);
757
+ });
758
+
759
+ test("AGENT-5: Agent files reference AGENTS.md for context", () => {
760
+ if (!existsSync(agentsDir)) return;
761
+ const missing: string[] = [];
762
+ for (const f of readdirSync(agentsDir).filter(f => f.endsWith(".md"))) {
763
+ const content = readFileSync(join(agentsDir, f), "utf-8");
764
+ if (!content.includes("AGENTS.md")) {
765
+ missing.push(f);
766
+ }
767
+ }
768
+ if (missing.length > 0) {
769
+ console.warn(`Agent files not referencing AGENTS.md (won't read project context):\n ${missing.join("\n ")}`);
770
+ }
771
+ expect(missing).toEqual([]);
772
+ });
773
+ });
774
+ }
775
+
776
+ // ── Fallow integration ─────────────────────────────────────
777
+
778
+ interface FallowResult {
779
+ total_issues: number;
780
+ elapsed_ms: number;
781
+ summary: Record<string, number>;
782
+ unused_files: Array<{ path: string }>;
783
+ unused_exports: Array<{ path: string; export_name: string; line?: number }>;
784
+ unused_dependencies: Array<{ name: string }>;
785
+ circular_dependencies: Array<{ path: string; chain?: string[] }>;
786
+ workspace_diagnostics: Array<{ kind: string; message: string }>;
787
+ }
788
+
789
+ function runFallowCommand(root: string, args: string[]): FallowResult | null {
790
+ const result = Bun.spawnSync(["npx", "fallow", ...args, "--format", "json", "--quiet"], {
791
+ cwd: root,
792
+ env: { ...process.env, NODE_NO_WARNINGS: "1" },
793
+ timeout: 30_000,
794
+ });
795
+ const stdout = result.stdout.toString().trim();
796
+ if (!stdout || stdout.startsWith("{\"error\"")) return null;
797
+ try {
798
+ return JSON.parse(stdout);
799
+ } catch {
800
+ return null;
801
+ }
802
+ }
803
+
804
+ export function runFallowCheck(root: string, opts?: { skipUnusedExports?: boolean; warnOnly?: boolean }) {
805
+ const fail = !opts?.warnOnly;
806
+ describe("Fallow: static analysis", () => {
807
+ test("FALLOW-1: No unused files", () => {
808
+ const result = runFallowCommand(root, ["dead-code", "--unused-files"]);
809
+ if (!result) {
810
+ console.warn("Fallow not available or failed to run — skipping");
811
+ return;
812
+ }
813
+ const unused = result.unused_files.map(f => f.path).filter(p => !p.includes("test/fixtures/") && !p.includes("reference/"));
814
+ if (unused.length > 0) {
815
+ console.warn(`Unused files (${unused.length}):\n ${unused.slice(0, 10).join("\n ")}${unused.length > 10 ? `\n ... and ${unused.length - 10} more` : ""}`);
816
+ }
817
+ if (fail) expect(unused).toEqual([]);
818
+ });
819
+
820
+ if (!opts?.skipUnusedExports) {
821
+ test("FALLOW-2: No unused exports", () => {
822
+ const result = runFallowCommand(root, ["dead-code", "--unused-exports"]);
823
+ if (!result) return;
824
+ const unused = (result.unused_exports || [])
825
+ .filter(e => !e.path.includes("test/fixtures/") && !e.path.includes("reference/"))
826
+ .map(e => `${e.path}:${e.line ?? "?"} ${e.export_name}`);
827
+ if (unused.length > 0) {
828
+ console.warn(`Unused exports (${unused.length}):\n ${unused.slice(0, 10).join("\n ")}${unused.length > 10 ? `\n ... and ${unused.length - 10} more` : ""}`);
829
+ }
830
+ if (fail) expect(unused).toEqual([]);
831
+ });
832
+ }
833
+
834
+ test("FALLOW-3: No unused dependencies", () => {
835
+ const result = runFallowCommand(root, ["dead-code", "--unused-deps"]);
836
+ if (!result) return;
837
+ const unused = result.unused_dependencies?.map(d => d.name) || [];
838
+ if (unused.length > 0) {
839
+ console.warn(`Unused dependencies (${unused.length}):\n ${unused.join("\n ")}`);
840
+ }
841
+ if (fail) expect(unused).toEqual([]);
842
+ });
843
+
844
+ test("FALLOW-4: No circular dependencies", () => {
845
+ const result = runFallowCommand(root, ["dead-code"]);
846
+ if (!result) return;
847
+ const circles = result.circular_dependencies || [];
848
+ if (circles.length > 0) {
849
+ console.warn(`Circular dependencies (${circles.length}):\n ${circles.slice(0, 5).map(c => c.path || JSON.stringify(c.files || c)).join("\n ")}${circles.length > 5 ? `\n ... and ${circles.length - 5} more` : ""}`);
850
+ }
851
+ if (fail) expect(circles).toEqual([]);
852
+ });
853
+ });
854
+ }
855
+
856
+ export function runPackageValidation(root: string) {
857
+ describe("Package validation", () => {
858
+ test("PKG-1: package.json exists", () => {
859
+ expect(existsSync(join(root, "package.json"))).toBe(true);
860
+ });
861
+
862
+ test("PKG-2: required fields present", () => {
863
+ const pkgPath = join(root, "package.json");
864
+ if (!existsSync(pkgPath)) return;
865
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
866
+ expect(pkg.name).toBeDefined();
867
+ expect(pkg.type).toBe("module");
868
+ expect(pkg.scripts?.test).toBeDefined();
869
+ });
870
+
871
+ test("PKG-3: devDependencies.rungate present", () => {
872
+ const pkgPath = join(root, "package.json");
873
+ if (!existsSync(pkgPath)) return;
874
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
875
+ expect(pkg.devDependencies?.rungate).toBeDefined();
876
+ });
877
+ });
878
+ }
879
+
880
+ export function runTsconfigValidation(root: string) {
881
+ describe("TSConfig validation", () => {
882
+ test("TSC-1: tsconfig.json exists", () => {
883
+ expect(existsSync(join(root, "tsconfig.json"))).toBe(true);
884
+ });
885
+
886
+ test("TSC-2: strict mode enabled", () => {
887
+ const tscPath = join(root, "tsconfig.json");
888
+ if (!existsSync(tscPath)) return;
889
+ const tsconfig = JSON.parse(readFileSync(tscPath, "utf-8"));
890
+ if (!tsconfig.compilerOptions?.strict) {
891
+ console.warn("WARN: tsconfig.json strict mode not enabled");
892
+ }
893
+ });
894
+ });
895
+ }
896
+
897
+ export function runModuleDepthCheck(root: string) {
898
+ describe("Module depth analysis", () => {
899
+ test("DEPTH-1: no shallow modules (more exports than internal functions)", () => {
900
+ const srcDir = join(root, "src");
901
+ if (!existsSync(srcDir)) return;
902
+ const shallow: string[] = [];
903
+ for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts"))) {
904
+ const content = readFileSync(join(srcDir, f), "utf-8");
905
+ const exportCount = (content.match(/export\s+(function|const|class|type|interface)\s/g) || []).length;
906
+ const internalCount = (content.match(/(?<!export\s)(function|const)\s+[a-z]/g) || []).length;
907
+ if (exportCount > 0 && internalCount > 0 && exportCount > internalCount) {
908
+ shallow.push(`${f}: ${exportCount} exports, ${internalCount} internal`);
909
+ }
910
+ }
911
+ if (shallow.length > 0) {
912
+ console.warn(`WARN: Shallow modules:\n ${shallow.join("\n ")}`);
913
+ }
914
+ });
915
+
916
+ test("DEPTH-2: modules with >3 importers have contract tests", () => {
917
+ const srcDir = join(root, "src");
918
+ const testDir = join(root, "test");
919
+ if (!existsSync(srcDir)) return;
920
+ const importCounts: Record<string, number> = {};
921
+ for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts"))) {
922
+ const content = readFileSync(join(srcDir, f), "utf-8");
923
+ const imports = content.match(/from\s+["']\.\/([^"']+)["']/g) || [];
924
+ for (const imp of imports) {
925
+ const target = imp.match(/["']\.\/([^"']+)["']/)?.[1] || "";
926
+ importCounts[target] = (importCounts[target] || 0) + 1;
927
+ }
928
+ }
929
+ const highImport = Object.entries(importCounts).filter(([, c]) => c > 3);
930
+ if (highImport.length > 0 && existsSync(testDir)) {
931
+ const testFiles = readdirSync(testDir).filter(f => f.endsWith(".test.ts"));
932
+ for (const [mod, count] of highImport) {
933
+ const hasTest = testFiles.some(t => t.includes(mod.replace(/\.ts$/, "")));
934
+ if (!hasTest) {
935
+ console.warn(`WARN: ${mod} has ${count} importers but no contract test`);
936
+ }
937
+ }
938
+ }
939
+ });
940
+ });
941
+ }
942
+
943
+ export function runAbsenceValidation(root: string) {
944
+ describe("Absence validation", () => {
945
+ test("ABSENCE-1: anti-criteria use absence verification", () => {
946
+ const specsDir = join(root, "specs");
947
+ if (!existsSync(specsDir)) return;
948
+ for (const f of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
949
+ const content = readFileSync(join(specsDir, f), "utf-8");
950
+ const antiCriteria = content.match(/^- \[ \] SC-A\d+:.+$/gm) || [];
951
+ for (const ac of antiCriteria) {
952
+ if (!ac.match(/not|never|no |absence|must not/i)) {
953
+ console.warn(`WARN: Anti-criterion may not verify absence: ${ac.substring(0, 80)}`);
954
+ }
955
+ }
956
+ }
957
+ });
958
+ });
959
+ }