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,617 @@
1
+ import { test, expect, describe, beforeAll, afterAll } from "bun:test";
2
+ import { existsSync, readFileSync, mkdirSync, writeFileSync } from "fs";
3
+ import { execSync } from "child_process";
4
+ import { join } from "path";
5
+ import { addFinding, addCandidate, addStaleness, getFindings, getCandidates, getStaleness, clearFindings, writeFindingsReport, parseFrontmatter } from "../lib/conformity";
6
+ import { extractConstraints } from "../scripts/extract-constraints";
7
+
8
+ // Spec-drift guard
9
+ const TEST_PLAN_HASH = "419d400dd23c9542";
10
+
11
+ const OUTPUT = "/tmp/rungate-phase1-test";
12
+ const HARNESS = join(import.meta.dir, "..");
13
+
14
+ function runConformitySubprocess(root: string, suiteFilter?: string): { pass: number; fail: number; output: string } {
15
+ const tmpTest = join(root, "_conformity-check.test.ts");
16
+ const importPath = join(import.meta.dir, "..", "lib", "conformity");
17
+ const suiteImports = suiteFilter || "runDocHygiene, runSpecDiscovery";
18
+ writeFileSync(tmpTest, `
19
+ import { ${suiteImports} } from "${importPath}";
20
+ const ROOT = "${root}";
21
+ ${suiteImports.split(",").map(s => `${s.trim()}(ROOT);`).join("\n ")}
22
+ `);
23
+ try {
24
+ const output = execSync(`bun test ${tmpTest} 2>&1`, { encoding: "utf-8", timeout: 30000 });
25
+ try { require("fs").unlinkSync(tmpTest); } catch {}
26
+ const passMatch = output.match(/(\d+) pass/);
27
+ const failMatch = output.match(/(\d+) fail/);
28
+ return { pass: passMatch ? parseInt(passMatch[1]) : 0, fail: failMatch ? parseInt(failMatch[1]) : 0, output };
29
+ } catch (e: any) {
30
+ try { require("fs").unlinkSync(tmpTest); } catch {}
31
+ const out = (e.stdout || "") + (e.stderr || "");
32
+ const passMatch = out.match(/(\d+) pass/);
33
+ const failMatch = out.match(/(\d+) fail/);
34
+ return { pass: passMatch ? parseInt(passMatch[1]) : 0, fail: failMatch ? parseInt(failMatch[1]) : 0, output: out };
35
+ }
36
+ }
37
+
38
+ beforeAll(() => {
39
+ execSync(`rm -rf ${OUTPUT}`);
40
+ mkdirSync(OUTPUT, { recursive: true });
41
+
42
+ // Create a project with docs that have known signal phrases for constraint extraction
43
+ mkdirSync(join(OUTPUT, "src"), { recursive: true });
44
+ mkdirSync(join(OUTPUT, "docs"), { recursive: true });
45
+ mkdirSync(join(OUTPUT, "docs/adr"), { recursive: true });
46
+ mkdirSync(join(OUTPUT, "specs"), { recursive: true });
47
+ mkdirSync(join(OUTPUT, "reference"), { recursive: true });
48
+ mkdirSync(join(OUTPUT, ".git"), { recursive: true });
49
+
50
+ writeFileSync(join(OUTPUT, "package.json"), JSON.stringify({
51
+ name: "phase1-test",
52
+ type: "module",
53
+ scripts: { test: "bun test" },
54
+ }, null, 2));
55
+
56
+ writeFileSync(join(OUTPUT, "tsconfig.json"), JSON.stringify({
57
+ compilerOptions: { strict: true, target: "ESNext", module: "ESNext" },
58
+ }, null, 2));
59
+
60
+ // Doc with signal phrases that should be extracted as constraint candidates
61
+ // Uses formats that match SIGNAL_PHRASE_PATTERNS: list items with "must/never/always"
62
+ writeFileSync(join(OUTPUT, "docs/rules.md"), `---
63
+ doc-type: guide
64
+ status: active
65
+ updated: 2026-09-01
66
+ ---
67
+
68
+ # Project Rules
69
+
70
+ - Never deploy on Fridays; this is a hard rule.
71
+ - The auth module must always be imported before the db module.
72
+ - All API responses must include a requestId header.
73
+ - Do not modify the migration files after they have been applied; intentional constraint.
74
+ `);
75
+
76
+ // Stale doc (simulate old git log date via frontmatter)
77
+ writeFileSync(join(OUTPUT, "docs/old-guide.md"), `---
78
+ doc-type: guide
79
+ status: active
80
+ updated: 2024-01-15
81
+ last-verified: 2024-01-15
82
+ ---
83
+
84
+ # Old Setup Guide
85
+
86
+ This guide is outdated.
87
+ `);
88
+
89
+ // Spec with correct frontmatter
90
+ writeFileSync(join(OUTPUT, "specs/api-spec.md"), `---
91
+ doc-type: spec
92
+ status: draft
93
+ owner: test
94
+ created: 2026-09-01
95
+ updated: 2026-09-01
96
+ governs: API behavior
97
+ testable: true
98
+ ---
99
+
100
+ # API Spec
101
+
102
+ ## Success Criteria
103
+
104
+ - [ ] SC-1: GET /health returns 200
105
+ `);
106
+
107
+ // Spec MISSING frontmatter (should fail spec discovery)
108
+ writeFileSync(join(OUTPUT, "specs/bare-spec.md"), `# Bare Spec
109
+
110
+ This spec has no frontmatter.
111
+ `);
112
+
113
+ // ADR with correct frontmatter
114
+ writeFileSync(join(OUTPUT, "docs/adr/ADR-001-framework.md"), `---
115
+ doc-type: adr
116
+ status: accepted
117
+ created: 2026-08-01
118
+ ---
119
+
120
+ # ADR-001: Framework Choice
121
+ `);
122
+
123
+ // ADR missing required frontmatter
124
+ writeFileSync(join(OUTPUT, "docs/adr/ADR-002-bad.md"), `---
125
+ status: draft
126
+ ---
127
+
128
+ # ADR-002: Missing doc-type
129
+ `);
130
+
131
+ // Misplaced file — spec at root instead of specs/
132
+ writeFileSync(join(OUTPUT, "SOME-SPEC.md"), `---
133
+ doc-type: spec
134
+ status: draft
135
+ governs: something
136
+ testable: false
137
+ ---
138
+
139
+ # Misplaced Spec
140
+ `);
141
+
142
+ // Rejected constraints file with existing rejections
143
+ writeFileSync(join(OUTPUT, "reference/rejected-constraints.md"), `# Rejected Constraints
144
+
145
+ <!-- content-hash: abc123 -->
146
+ - "Never deploy on Fridays" — rejected: team policy, not code constraint
147
+ `);
148
+
149
+ // Initialize git with old-guide.md having an old commit date for staleness detection
150
+ execSync("git init", { cwd: OUTPUT, stdio: "pipe" });
151
+ execSync("git add docs/old-guide.md && git commit -m 'add old guide'", {
152
+ cwd: OUTPUT, stdio: "pipe",
153
+ env: {
154
+ ...process.env,
155
+ GIT_AUTHOR_DATE: "2024-01-15T00:00:00",
156
+ GIT_COMMITTER_DATE: "2024-01-15T00:00:00",
157
+ },
158
+ });
159
+ execSync("git add -A && git commit -m 'init'", { cwd: OUTPUT, stdio: "pipe" });
160
+ });
161
+
162
+ describe("Phase 1: Knowledge extraction + doc hygiene", () => {
163
+
164
+ // Spec-drift guard
165
+ test("spec-drift: test plan spec hasn't changed", () => {
166
+ const specPath = join(import.meta.dir, "..", "specs", "BOOTSTRAP-TEST-PLAN.md");
167
+ if (existsSync(specPath)) {
168
+ const hash = execSync(`shasum -a 256 "${specPath}" | cut -c1-16`, { encoding: "utf-8" }).trim();
169
+ if (hash !== TEST_PLAN_HASH) {
170
+ throw new Error(
171
+ `SPEC DRIFT: test plan spec changed (hash ${hash} != ${TEST_PLAN_HASH}). ` +
172
+ `Update test file to match new spec, then update TEST_PLAN_HASH to "${hash}".`
173
+ );
174
+ }
175
+ }
176
+ });
177
+
178
+ // SC-12: Bootstrap scans docs for non-inferrable rule candidates using signal phrases
179
+ describe("SC-12: constraint extraction from docs", () => {
180
+ test("extract-constraints finds signal phrases in docs", () => {
181
+ try {
182
+ const output = execSync(
183
+ `bun run ${HARNESS}/scripts/extract-constraints.ts ${OUTPUT} --dry-run 2>&1`,
184
+ { encoding: "utf-8", timeout: 30000 }
185
+ );
186
+ // Should find IMPORTANT, WARNING, CRITICAL signal phrases
187
+ expect(output).toMatch(/never deploy|auth module|do not modify|requestId/i);
188
+ } catch (e: any) {
189
+ const out = (e.stdout || "") + (e.stderr || "");
190
+ // If extract-constraints doesn't exist yet, this is expected to fail
191
+ expect(out).toMatch(/never deploy|auth module|do not modify|requestId/i);
192
+ }
193
+ });
194
+ });
195
+
196
+ // SC-13: Extracted candidates presented for user confirmation before writing
197
+ describe("SC-13: dry-run mode for constraint extraction", () => {
198
+ test("--dry-run does not write to AGENTS.md", () => {
199
+ const agentsBefore = existsSync(join(OUTPUT, "AGENTS.md"))
200
+ ? readFileSync(join(OUTPUT, "AGENTS.md"), "utf-8")
201
+ : "";
202
+
203
+ try {
204
+ execSync(
205
+ `bun run ${HARNESS}/scripts/extract-constraints.ts ${OUTPUT} --dry-run 2>&1`,
206
+ { encoding: "utf-8", timeout: 30000 }
207
+ );
208
+ } catch {}
209
+
210
+ const agentsAfter = existsSync(join(OUTPUT, "AGENTS.md"))
211
+ ? readFileSync(join(OUTPUT, "AGENTS.md"), "utf-8")
212
+ : "";
213
+
214
+ expect(agentsAfter).toBe(agentsBefore);
215
+ });
216
+ });
217
+
218
+ // SC-14: Staleness uses git log date with per-type thresholds
219
+ describe("SC-14: doc staleness detection", () => {
220
+ test("staleness checker flags old docs", async () => {
221
+ const result = await extractConstraints(OUTPUT, { apply: false });
222
+ const staleFiles = result.staleness || [];
223
+ const oldGuide = staleFiles.find((s) => s.file.includes("old-guide"));
224
+ expect(oldGuide).toBeDefined();
225
+ expect(oldGuide!.daysSince).toBeGreaterThan(180);
226
+ });
227
+ });
228
+
229
+ // SC-75: Spec frontmatter required fields
230
+ describe("SC-75: spec frontmatter validation", () => {
231
+ test("spec with frontmatter has required fields", () => {
232
+ const content = readFileSync(join(OUTPUT, "specs/api-spec.md"), "utf-8");
233
+ expect(content).toContain("doc-type: spec");
234
+ expect(content).toContain("testable:");
235
+ expect(content).toContain("governs:");
236
+ });
237
+
238
+ test("Spec Discovery FAILs on bare spec without frontmatter", () => {
239
+ const result = runConformitySubprocess(OUTPUT, "runSpecDiscovery");
240
+ expect(result.fail).toBeGreaterThan(0);
241
+ expect(result.output).toMatch(/bare-spec|frontmatter|testable/i);
242
+ });
243
+ });
244
+
245
+ // SC-76: ADR frontmatter required fields
246
+ describe("SC-76: ADR frontmatter validation", () => {
247
+ test("correct ADR has required fields", () => {
248
+ const content = readFileSync(join(OUTPUT, "docs/adr/ADR-001-framework.md"), "utf-8");
249
+ expect(content).toContain("doc-type: adr");
250
+ expect(content).toContain("status:");
251
+ expect(content).toContain("created:");
252
+ });
253
+
254
+ test("Doc Hygiene FAILs on ADR missing doc-type field", () => {
255
+ const result = runConformitySubprocess(OUTPUT, "runDocHygiene");
256
+ // ADR-002-bad.md has no doc-type: adr — HYGIENE-10 should FAIL
257
+ expect(result.fail).toBeGreaterThan(0);
258
+ expect(result.output).toMatch(/HYGIENE-10|doc-type|ADR-002/i);
259
+ });
260
+ });
261
+
262
+ // SC-30: Misplaced spec/ADR/doc files are FAIL not WARN (HYGIENE-7/8/9)
263
+ describe("SC-30: misplaced file detection", () => {
264
+ test("HYGIENE-7: spec at root produces structured finding with fix command", () => {
265
+ clearFindings();
266
+ const allowlist = new Set([
267
+ "AGENTS.md", "CLAUDE.md", "CLAUDE.local.md", "CODE-MAP.md",
268
+ "README.md", "CHANGELOG.md", "CONTRIBUTING.md", "LICENSE.md",
269
+ "ARCHITECTURE.md", "PRINCIPLES.md", "MODEL.md", "PROJECT-STATE.md",
270
+ ]);
271
+ const files = require("fs").readdirSync(OUTPUT).filter((f: string) => f.endsWith(".md"));
272
+ for (const f of files) {
273
+ if (allowlist.has(f)) continue;
274
+ const content = readFileSync(join(OUTPUT, f), "utf-8");
275
+ const fm = parseFrontmatter(content);
276
+ if (fm?.["doc-type"] === "spec") {
277
+ addFinding({
278
+ ruleId: "HYGIENE-7",
279
+ severity: "FAIL",
280
+ file: f,
281
+ message: `Spec "${f}" is at root — must be in specs/`,
282
+ fixCommand: `mv ${f} specs/${f}`,
283
+ });
284
+ }
285
+ }
286
+ const findings = getFindings();
287
+ const specFindings = findings.filter(f => f.ruleId === "HYGIENE-7");
288
+ expect(specFindings.length).toBeGreaterThan(0);
289
+ expect(specFindings[0].file).toBe("SOME-SPEC.md");
290
+ expect(specFindings[0].fixCommand).toContain("mv SOME-SPEC.md specs/");
291
+ expect(specFindings[0].severity).toBe("FAIL");
292
+ });
293
+
294
+ test("HYGIENE-8: ADR outside docs/adr/ produces finding", () => {
295
+ clearFindings();
296
+ const tempAdr = join(OUTPUT, "TEMP-ADR.md");
297
+ writeFileSync(tempAdr, "---\ndoc-type: adr\nstatus: draft\n---\n# Temp ADR\n");
298
+
299
+ for (const f of require("fs").readdirSync(OUTPUT).filter((f: string) => f.endsWith(".md"))) {
300
+ const content = readFileSync(join(OUTPUT, f), "utf-8");
301
+ const fm = parseFrontmatter(content);
302
+ if (fm?.["doc-type"] === "adr") {
303
+ addFinding({
304
+ ruleId: "HYGIENE-8",
305
+ severity: "FAIL",
306
+ file: f,
307
+ message: `ADR "${f}" outside docs/adr/`,
308
+ fixCommand: `mv ${f} docs/adr/${f}`,
309
+ });
310
+ }
311
+ }
312
+
313
+ const findings = getFindings().filter(f => f.ruleId === "HYGIENE-8");
314
+ expect(findings.length).toBeGreaterThan(0);
315
+ expect(findings[0].fixCommand).toContain("docs/adr/");
316
+
317
+ require("fs").unlinkSync(tempAdr);
318
+ });
319
+
320
+ test("HYGIENE-9: doc file at root (non-allowlisted) produces finding", () => {
321
+ clearFindings();
322
+ const tempDoc = join(OUTPUT, "RANDOM-GUIDE.md");
323
+ writeFileSync(tempDoc, "---\ndoc-type: guide\nstatus: active\n---\n# Random Guide\n");
324
+
325
+ const allowlist = new Set([
326
+ "AGENTS.md", "CLAUDE.md", "CLAUDE.local.md", "CODE-MAP.md",
327
+ "README.md", "CHANGELOG.md", "CONTRIBUTING.md", "LICENSE.md",
328
+ "ARCHITECTURE.md", "PRINCIPLES.md", "MODEL.md", "PROJECT-STATE.md",
329
+ ]);
330
+
331
+ for (const f of require("fs").readdirSync(OUTPUT).filter((f: string) => f.endsWith(".md"))) {
332
+ if (allowlist.has(f)) continue;
333
+ const content = readFileSync(join(OUTPUT, f), "utf-8");
334
+ const fm = parseFrontmatter(content);
335
+ if (fm?.["doc-type"] === "guide" || fm?.["doc-type"] === "doc") {
336
+ addFinding({
337
+ ruleId: "HYGIENE-9",
338
+ severity: "FAIL",
339
+ file: f,
340
+ message: `Doc "${f}" at root — must be in docs/`,
341
+ fixCommand: `mv ${f} docs/${f}`,
342
+ });
343
+ }
344
+ }
345
+
346
+ const findings = getFindings().filter(f => f.ruleId === "HYGIENE-9");
347
+ expect(findings.length).toBeGreaterThan(0);
348
+ expect(findings[0].file).toBe("RANDOM-GUIDE.md");
349
+
350
+ require("fs").unlinkSync(tempDoc);
351
+ });
352
+ });
353
+
354
+ // Structured findings output (machine-readable for agents)
355
+ describe("structured findings output", () => {
356
+ test("writeFindingsReport produces JSON with findings", () => {
357
+ clearFindings();
358
+ addFinding({
359
+ ruleId: "TEST-1",
360
+ severity: "FAIL",
361
+ file: "test-file.md",
362
+ message: "Test finding",
363
+ fixCommand: "mv test-file.md docs/",
364
+ });
365
+ const reportPath = writeFindingsReport(OUTPUT);
366
+ expect(existsSync(reportPath)).toBe(true);
367
+ const report = JSON.parse(readFileSync(reportPath, "utf-8"));
368
+ expect(report.total).toBe(1);
369
+ expect(report.failures).toBe(1);
370
+ expect(report.findings[0].ruleId).toBe("TEST-1");
371
+ expect(report.findings[0].fixCommand).toBe("mv test-file.md docs/");
372
+ clearFindings();
373
+ });
374
+
375
+ test("unified report includes findings, candidates, and staleness", () => {
376
+ clearFindings();
377
+ addFinding({ ruleId: "A", severity: "FAIL", file: "a.md", message: "fail" });
378
+ addFinding({ ruleId: "B", severity: "WARN", file: "b.md", message: "warn" });
379
+ addCandidate({ rule: "Never deploy on Fridays", source: "docs/rules.md:9", hash: "abc123", status: "pending" });
380
+ addCandidate({ rule: "Auth before db", source: "docs/rules.md:10", hash: "def456", status: "pending" });
381
+ addStaleness({ file: "docs/old-guide.md", daysSince: 978, threshold: 180, type: "guide" });
382
+ const reportPath = writeFindingsReport(OUTPUT);
383
+ const report = JSON.parse(readFileSync(reportPath, "utf-8"));
384
+ expect(report.failures).toBe(1);
385
+ expect(report.warnings).toBe(1);
386
+ expect(report.candidateCount).toBe(2);
387
+ expect(report.staleCount).toBe(1);
388
+ expect(report.constraintCandidates.length).toBe(2);
389
+ expect(report.constraintCandidates[0].rule).toBe("Never deploy on Fridays");
390
+ expect(report.constraintCandidates[0].status).toBe("pending");
391
+ expect(report.staleness.length).toBe(1);
392
+ expect(report.staleness[0].file).toBe("docs/old-guide.md");
393
+ expect(report.staleness[0].daysSince).toBeGreaterThan(180);
394
+ clearFindings();
395
+ });
396
+ });
397
+
398
+ // SC-149: Conformity findings written to .rungate/conformity-findings.json
399
+ describe("SC-149: findings JSON output", () => {
400
+ test("writeFindingsReport writes to .rungate/conformity-findings.json", () => {
401
+ clearFindings();
402
+ addFinding({ ruleId: "SC149-TEST", severity: "FAIL", file: "x.md", message: "test" });
403
+ const reportPath = writeFindingsReport(OUTPUT);
404
+ expect(reportPath).toContain(".rungate/conformity-findings.json");
405
+ expect(existsSync(reportPath)).toBe(true);
406
+ const report = JSON.parse(readFileSync(reportPath, "utf-8"));
407
+ expect(report).toHaveProperty("findings");
408
+ expect(report).toHaveProperty("total");
409
+ expect(report).toHaveProperty("failures");
410
+ expect(report).toHaveProperty("warnings");
411
+ expect(report.findings[0]).toHaveProperty("ruleId");
412
+ expect(report.findings[0]).toHaveProperty("severity");
413
+ expect(report.findings[0]).toHaveProperty("file");
414
+ expect(report.findings[0]).toHaveProperty("message");
415
+ clearFindings();
416
+ });
417
+ });
418
+
419
+ // SC-150: Every FAIL finding includes a fixCommand
420
+ describe("SC-150: fixCommand on FAIL findings", () => {
421
+ test("FAIL finding with fixCommand is preserved in report", () => {
422
+ clearFindings();
423
+ addFinding({
424
+ ruleId: "SC150-TEST",
425
+ severity: "FAIL",
426
+ file: "misplaced.md",
427
+ message: "File misplaced",
428
+ fixCommand: "mv misplaced.md docs/misplaced.md",
429
+ });
430
+ const reportPath = writeFindingsReport(OUTPUT);
431
+ const report = JSON.parse(readFileSync(reportPath, "utf-8"));
432
+ expect(report.findings[0].fixCommand).toBe("mv misplaced.md docs/misplaced.md");
433
+ clearFindings();
434
+ });
435
+ });
436
+
437
+ // SC-154: Unified report includes constraintCandidates
438
+ describe("SC-154: constraintCandidates in report", () => {
439
+ test("report has constraintCandidates array with required fields", () => {
440
+ clearFindings();
441
+ addCandidate({ rule: "Test rule", source: "docs/test.md:5", hash: "abc", status: "pending" });
442
+ const reportPath = writeFindingsReport(OUTPUT);
443
+ const report = JSON.parse(readFileSync(reportPath, "utf-8"));
444
+ expect(report.constraintCandidates).toBeInstanceOf(Array);
445
+ expect(report.constraintCandidates[0]).toHaveProperty("rule");
446
+ expect(report.constraintCandidates[0]).toHaveProperty("source");
447
+ expect(report.constraintCandidates[0]).toHaveProperty("hash");
448
+ expect(report.constraintCandidates[0]).toHaveProperty("status");
449
+ expect(report.candidateCount).toBe(1);
450
+ clearFindings();
451
+ });
452
+ });
453
+
454
+ // SC-155: Unified report includes staleness array
455
+ describe("SC-155: staleness in report", () => {
456
+ test("report has staleness array with required fields", () => {
457
+ clearFindings();
458
+ addStaleness({ file: "docs/old.md", daysSince: 200, threshold: 180, type: "guide" });
459
+ const reportPath = writeFindingsReport(OUTPUT);
460
+ const report = JSON.parse(readFileSync(reportPath, "utf-8"));
461
+ expect(report.staleness).toBeInstanceOf(Array);
462
+ expect(report.staleness[0]).toHaveProperty("file");
463
+ expect(report.staleness[0]).toHaveProperty("daysSince");
464
+ expect(report.staleness[0]).toHaveProperty("threshold");
465
+ expect(report.staleness[0]).toHaveProperty("type");
466
+ expect(report.staleCount).toBe(1);
467
+ clearFindings();
468
+ });
469
+ });
470
+
471
+ // SC-156: HYGIENE-6 pipes extract-constraints into unified findings
472
+ describe("SC-156: extract-constraints feeds unified report", () => {
473
+ test("extractConstraints populates candidates and staleness", async () => {
474
+ const result = await extractConstraints(OUTPUT, { apply: false });
475
+ expect(result.candidates.length).toBeGreaterThan(0);
476
+ expect(result.staleness.length).toBeGreaterThan(0);
477
+ });
478
+ });
479
+
480
+ // SC-157: Gate runner reads conformity-findings.json after bun test
481
+ describe("SC-157: gate runner reads findings", () => {
482
+ test("gate runner imports or references conformity-findings.json", () => {
483
+ const gateRunner = join(HARNESS, "gates", "run-gate.ts");
484
+ if (existsSync(gateRunner)) {
485
+ const content = readFileSync(gateRunner, "utf-8");
486
+ expect(content).toContain("conformity-findings.json");
487
+ } else {
488
+ expect(existsSync(gateRunner)).toBe(true);
489
+ }
490
+ });
491
+ });
492
+
493
+ // SC-158: Gate runner stores conformityFindings in workflow-state.json
494
+ describe("SC-158: conformityFindings in workflow-state", () => {
495
+ test("gate runner writes conformityFindings field", () => {
496
+ const gateRunner = join(HARNESS, "gates", "run-gate.ts");
497
+ if (existsSync(gateRunner)) {
498
+ const content = readFileSync(gateRunner, "utf-8");
499
+ expect(content).toContain("conformityFindings");
500
+ } else {
501
+ expect(existsSync(gateRunner)).toBe(true);
502
+ }
503
+ });
504
+ });
505
+
506
+ // SC-151: HYGIENE-7 detects spec at root with mv fix command
507
+ describe("SC-151: HYGIENE-7 spec at root", () => {
508
+ test("detects SOME-SPEC.md at root and produces FAIL", () => {
509
+ const result = runConformitySubprocess(OUTPUT, "runDocHygiene");
510
+ expect(result.output).toMatch(/HYGIENE-7|SOME-SPEC|spec.*root/i);
511
+ });
512
+ });
513
+
514
+ // SC-152: HYGIENE-8 detects ADR outside docs/adr/
515
+ describe("SC-152: HYGIENE-8 ADR misplaced", () => {
516
+ test("detects ADR-002-bad.md missing doc-type", () => {
517
+ const result = runConformitySubprocess(OUTPUT, "runDocHygiene");
518
+ expect(result.output).toMatch(/HYGIENE-10|HYGIENE-8|ADR-002|doc-type/i);
519
+ });
520
+ });
521
+
522
+ // SC-153: HYGIENE-9 detects doc at root (non-allowlisted)
523
+ describe("SC-153: HYGIENE-9 doc at root", () => {
524
+ test("non-allowlisted .md at root detected", () => {
525
+ clearFindings();
526
+ const tempDoc = join(OUTPUT, "RANDOM-DOC.md");
527
+ writeFileSync(tempDoc, "---\ndoc-type: guide\nstatus: active\n---\n# Random\n");
528
+
529
+ const allowlist = new Set([
530
+ "AGENTS.md", "CLAUDE.md", "CLAUDE.local.md", "CODE-MAP.md",
531
+ "README.md", "CHANGELOG.md", "CONTRIBUTING.md", "LICENSE.md",
532
+ "ARCHITECTURE.md", "PRINCIPLES.md", "MODEL.md", "PROJECT-STATE.md",
533
+ ]);
534
+
535
+ for (const f of require("fs").readdirSync(OUTPUT).filter((f: string) => f.endsWith(".md"))) {
536
+ if (allowlist.has(f)) continue;
537
+ const content = readFileSync(join(OUTPUT, f), "utf-8");
538
+ const fm = parseFrontmatter(content);
539
+ if (fm?.["doc-type"] === "guide") {
540
+ addFinding({
541
+ ruleId: "HYGIENE-9",
542
+ severity: "FAIL",
543
+ file: f,
544
+ message: `Doc "${f}" at root`,
545
+ fixCommand: `mv ${f} docs/${f}`,
546
+ });
547
+ }
548
+ }
549
+
550
+ const findings = getFindings().filter(f => f.ruleId === "HYGIENE-9");
551
+ expect(findings.some(f => f.file === "RANDOM-DOC.md")).toBe(true);
552
+
553
+ require("fs").unlinkSync(tempDoc);
554
+ clearFindings();
555
+ });
556
+ });
557
+
558
+ // SC-22: Re-scaffold reports stale constraints
559
+ describe("SC-22: stale constraint reporting", () => {
560
+ test("re-scaffold or extract-constraints reports stale docs", async () => {
561
+ const result = await extractConstraints(OUTPUT, { apply: false });
562
+ expect(result.staleness.length).toBeGreaterThan(0);
563
+ expect(result.staleness.some((s) => s.file.includes("old-guide"))).toBe(true);
564
+ });
565
+ });
566
+
567
+ // SC-23: Re-scaffold reports line count if AGENTS.md exceeds 150 lines
568
+ describe("SC-23: AGENTS.md line count check", () => {
569
+ test("line count check is possible on generated AGENTS.md", () => {
570
+ try {
571
+ execSync(`bun run ${HARNESS}/scripts/scaffold-project.ts ${OUTPUT}`, {
572
+ timeout: 60000, stdio: "pipe",
573
+ });
574
+ } catch {}
575
+
576
+ if (existsSync(join(OUTPUT, "AGENTS.md"))) {
577
+ const lines = readFileSync(join(OUTPUT, "AGENTS.md"), "utf-8").split("\n").length;
578
+ expect(lines).toBeLessThanOrEqual(150);
579
+ }
580
+ });
581
+
582
+ test("AGENTS.md over 150 lines would be detected", () => {
583
+ const agentsPath = join(OUTPUT, "AGENTS.md");
584
+ const original = existsSync(agentsPath) ? readFileSync(agentsPath, "utf-8") : "";
585
+ const oversized = "# Test\n" + Array(160).fill("- rule line").join("\n");
586
+ writeFileSync(agentsPath, oversized);
587
+
588
+ const lines = oversized.split("\n").length;
589
+ expect(lines).toBeGreaterThan(150);
590
+
591
+ if (original) writeFileSync(agentsPath, original);
592
+ else require("fs").unlinkSync(agentsPath);
593
+ });
594
+ });
595
+
596
+ // SC-106: Doc lifecycle — stale docs flagged for archive
597
+ describe("SC-106: doc lifecycle", () => {
598
+ test("stale doc flagged by staleness detection", async () => {
599
+ const result = await extractConstraints(OUTPUT, { apply: false });
600
+ const stale = result.staleness || [];
601
+ expect(stale.some((s) => s.file.includes("old-guide"))).toBe(true);
602
+ });
603
+ });
604
+
605
+ // SC-137: Rejected constraints logged with content-hash dedup
606
+ describe("SC-137: rejected constraints dedup", () => {
607
+ test("extract-constraints deduplicates against rejected-constraints.md", async () => {
608
+ const result = await extractConstraints(OUTPUT, { apply: false });
609
+ expect(result.deduped).toHaveProperty("candidatesRemoved");
610
+ expect(result.deduped).toHaveProperty("rejectedPrior");
611
+ expect(result.deduped).toHaveProperty("existingConstraints");
612
+ // "Never deploy on Fridays" is in both docs/rules.md and rejected-constraints.md
613
+ // The dedup mechanism should detect this overlap
614
+ expect(typeof result.deduped.candidatesRemoved).toBe("number");
615
+ });
616
+ });
617
+ });