rungate 0.2.0 → 0.3.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 (282) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/canary.ts +117 -0
  11. package/lib/check-registry.ts +226 -0
  12. package/lib/ci-checkout.ts +400 -0
  13. package/lib/cli-commands.ts +137 -0
  14. package/lib/compliance-backfill.ts +220 -0
  15. package/lib/compliance-report.ts +504 -0
  16. package/lib/compliance.ts +361 -0
  17. package/lib/config-loader.ts +255 -0
  18. package/lib/conformity.ts +1818 -131
  19. package/lib/container-provenance.ts +230 -0
  20. package/lib/create-brief.ts +150 -0
  21. package/lib/create-sc.ts +272 -0
  22. package/lib/deep-merge.ts +69 -0
  23. package/lib/dev-liveness.ts +214 -0
  24. package/lib/directive-extractor.ts +210 -0
  25. package/lib/distribution-standing.ts +113 -0
  26. package/lib/doc-hygiene.ts +238 -0
  27. package/lib/eval-criteria.ts +6 -0
  28. package/lib/evidence-portability.ts +123 -0
  29. package/lib/evidence-prevalidator.ts +390 -0
  30. package/lib/evidence-required.ts +150 -0
  31. package/lib/evidence-satisfiability.ts +288 -0
  32. package/lib/frontmatter.ts +163 -0
  33. package/lib/gap-scanner.ts +348 -0
  34. package/lib/gate-enforcement.ts +366 -0
  35. package/lib/generators/agent-briefs.ts +136 -0
  36. package/lib/generators/agents-md.ts +506 -0
  37. package/lib/generators/code-map.ts +60 -0
  38. package/lib/generators/types.ts +184 -0
  39. package/lib/git-ref-normalizer.ts +107 -0
  40. package/lib/github.ts +539 -0
  41. package/lib/harness-identity.ts +63 -0
  42. package/lib/hill-climb.ts +164 -0
  43. package/lib/instruction-effectiveness.ts +131 -0
  44. package/lib/issue-closure-audit.ts +225 -0
  45. package/lib/issue-create-override.ts +343 -0
  46. package/lib/js-top-level-code.ts +250 -0
  47. package/lib/liveness-contradiction.ts +149 -0
  48. package/lib/organize.ts +505 -0
  49. package/lib/paths.ts +197 -6
  50. package/lib/post-fix-verify.ts +157 -0
  51. package/lib/prior-branch.ts +489 -0
  52. package/lib/project-state-shape.ts +166 -0
  53. package/lib/promote-outputs.ts +156 -0
  54. package/lib/prove-label-gate.ts +35 -0
  55. package/lib/reachability.ts +302 -0
  56. package/lib/release-preflight.ts +186 -0
  57. package/lib/rule-health-pipeline.ts +264 -0
  58. package/lib/rule-health-trend.ts +161 -0
  59. package/lib/rule-provenance.ts +149 -0
  60. package/lib/rule-registry.ts +128 -0
  61. package/lib/rungate-schema.ts +114 -4
  62. package/lib/sc-claim-forms.ts +179 -0
  63. package/lib/sc-cover.ts +150 -0
  64. package/lib/sc-guard.ts +157 -0
  65. package/lib/sc-ids.ts +344 -0
  66. package/lib/scaffold/defaults.ts +165 -0
  67. package/lib/scaffold/managed-workflow.ts +370 -0
  68. package/lib/scaffold/owned-files.ts +265 -0
  69. package/lib/scaffold/steps.ts +2680 -0
  70. package/lib/scanner.ts +701 -0
  71. package/lib/screenshot-upload.ts +73 -0
  72. package/lib/secret-patterns.ts +112 -0
  73. package/lib/security-verdict.ts +616 -0
  74. package/lib/signal-phrases.ts +1 -0
  75. package/lib/spec-change-conformity.ts +80 -0
  76. package/lib/spec-files.ts +62 -0
  77. package/lib/spec-registry.ts +133 -0
  78. package/lib/spec-updater.ts +96 -0
  79. package/lib/stale-cleanup.ts +224 -0
  80. package/lib/stale-issue-scanner.ts +36 -0
  81. package/lib/strip-js-comments.ts +269 -0
  82. package/lib/suite-measurement.ts +228 -0
  83. package/lib/task-completion-checks.ts +177 -0
  84. package/lib/test-suite-lock.ts +1136 -0
  85. package/lib/transcript-checker.ts +1140 -0
  86. package/lib/validators/spec-validators.ts +171 -0
  87. package/lib/verdict-capture.ts +73 -0
  88. package/lib/verified-push.ts +358 -0
  89. package/lib/workflow-security.ts +174 -0
  90. package/lib/worktree-cleanup.ts +250 -0
  91. package/lib/worktree-collect.ts +283 -0
  92. package/lib/worktree-isolation.ts +82 -0
  93. package/package.json +36 -3
  94. package/prompts/ac-adversary.md +14 -2
  95. package/prompts/aditi.md +5 -0
  96. package/prompts/blast-radius.md +5 -0
  97. package/prompts/container-verify.md +5 -0
  98. package/prompts/discovery.md +4 -0
  99. package/prompts/environment.md +5 -0
  100. package/prompts/evidence-hierarchy.md +5 -0
  101. package/prompts/evidence-validator.md +11 -0
  102. package/prompts/marcus.md +5 -0
  103. package/prompts/prevention.md +5 -0
  104. package/prompts/prove-reproducer.md +12 -0
  105. package/prompts/quinn-decision-tree.md +5 -0
  106. package/prompts/quinn-ui-brief.md +5 -0
  107. package/prompts/quinn.md +5 -0
  108. package/prompts/rca.md +5 -0
  109. package/prompts/read-before-write.md +4 -0
  110. package/prompts/regression.md +5 -0
  111. package/prompts/serena.md +5 -0
  112. package/scripts/audit-specs.ts +464 -0
  113. package/scripts/convert-spec.ts +293 -0
  114. package/scripts/create-sc.ts +92 -0
  115. package/scripts/create-spec.ts +166 -0
  116. package/scripts/extract-constraints.ts +4 -3
  117. package/scripts/generate-code-map.ts +1 -1
  118. package/scripts/scaffold-project.ts +138 -1426
  119. package/scripts/sync-spec-tests.ts +211 -126
  120. package/.claude/agents/aditi.md +0 -47
  121. package/.claude/agents/marcus.md +0 -50
  122. package/.claude/agents/quinn.md +0 -58
  123. package/.claude/agents/rook.md +0 -47
  124. package/.claude/agents/serena.md +0 -46
  125. package/.claude/rungate.json +0 -11
  126. package/.fallowrc.json +0 -28
  127. package/.github/copilot-instructions.md +0 -20
  128. package/.rungate/conformity-findings.json +0 -648
  129. package/AGENTS.md +0 -106
  130. package/CODE-MAP.md +0 -50
  131. package/HARNESS.md +0 -88
  132. package/bun.lock +0 -26
  133. package/bunfig.toml +0 -2
  134. package/config/brief-policies.json +0 -28
  135. package/config/ceremony-profiles.json +0 -212
  136. package/config/consumer-cascade-map.json +0 -24
  137. package/config/doc-cascade-map.json +0 -24
  138. package/config/eval.json +0 -84
  139. package/config/profiles/account-plan.yaml +0 -36
  140. package/config/profiles/campaign.yaml +0 -94
  141. package/config/prove-evidence.schema.json +0 -65
  142. package/config/spec-policies.json +0 -36
  143. package/config/workflow-schema.json +0 -281
  144. package/gates/SCHEMA-GUIDE.md +0 -121
  145. package/gates/ac-quality.test.ts +0 -106
  146. package/gates/adversarial.test.ts +0 -274
  147. package/gates/brief-assembler.test.ts +0 -429
  148. package/gates/brief-assembler.ts +0 -334
  149. package/gates/bunfig.toml +0 -2
  150. package/gates/chain.test.ts +0 -91
  151. package/gates/e2e-smoke.test.ts +0 -234
  152. package/gates/error-classifier.test.ts +0 -249
  153. package/gates/error-classifier.ts +0 -89
  154. package/gates/orchestrator.test.ts +0 -950
  155. package/gates/orchestrator.ts +0 -569
  156. package/gates/preload.ts +0 -77
  157. package/gates/prompts/ac-adversary.md +0 -20
  158. package/gates/prompts/evidence-validator.md +0 -22
  159. package/gates/prompts/prove-reproducer.md +0 -53
  160. package/gates/prove.test.ts +0 -164
  161. package/gates/run-gate.ts +0 -936
  162. package/gates/schema-parity.test.ts +0 -197
  163. package/gates/schema.ts +0 -362
  164. package/gates/self-heal.test.ts +0 -511
  165. package/gates/self-heal.ts +0 -121
  166. package/gates/ship-orchestrator.test.ts +0 -379
  167. package/gates/ship-orchestrator.ts +0 -363
  168. package/gates/test-fixtures/broken-no-environments.json +0 -60
  169. package/gates/test-fixtures/valid-standard.json +0 -54
  170. package/gates/test-utils.ts +0 -43
  171. package/gates/witness.ts +0 -220
  172. package/gates/workflow.test.ts +0 -1053
  173. package/hooks/AgentBriefGuard.hook.ts +0 -586
  174. package/hooks/AgentVerdictCapture.hook.ts +0 -134
  175. package/hooks/AutoVerifyGate.hook.ts +0 -76
  176. package/hooks/GateEnforcement.hook.ts +0 -273
  177. package/hooks/IssueCloseGuard.hook.ts +0 -116
  178. package/hooks/MergeGuard.hook.ts +0 -55
  179. package/hooks/StaleTTLCleanup.hook.ts +0 -133
  180. package/hooks/VerifyPhaseLock.hook.ts +0 -81
  181. package/hooks/WorkflowStateGuard.hook.ts +0 -37
  182. package/hooks/lib/agentDetection.ts +0 -70
  183. package/hooks/lib/findWorkflow.ts +0 -101
  184. package/hooks/lib/parseStdin.ts +0 -37
  185. package/hooks/lib/paths.ts +0 -111
  186. package/hooks/lib/utils.ts +0 -81
  187. package/reference/migration-manifest.json +0 -554
  188. package/reference/prompts/agent-aditi.md +0 -38
  189. package/reference/prompts/agent-marcus.md +0 -38
  190. package/reference/prompts/agent-quinn.md +0 -38
  191. package/reference/prompts/agent-rook.md +0 -37
  192. package/reference/prompts/agent-serena.md +0 -37
  193. package/reference/prompts/council-skill.md +0 -170
  194. package/reference/prompts/goal-skill.md +0 -235
  195. package/reference/prompts/prove-skill.md +0 -283
  196. package/reference/prompts/quinn-standard.md +0 -246
  197. package/reference/prompts/ship-convergence.md +0 -65
  198. package/reference/prompts/ship-escalation.md +0 -43
  199. package/reference/prompts/ship-iteration.md +0 -382
  200. package/reference/prompts/ship-pending-patches.md +0 -246
  201. package/reference/prompts/ship-reference.md +0 -250
  202. package/reference/prompts/ship-skill.md +0 -347
  203. package/reference/prompts/ship-templates.md +0 -215
  204. package/reference/scripts/batch-status.sh +0 -68
  205. package/reference/scripts/chain-compat-check.sh +0 -67
  206. package/reference/scripts/context-audit.sh +0 -314
  207. package/reference/scripts/dead-export-check.sh +0 -61
  208. package/reference/scripts/generate-qc-tables.sh +0 -92
  209. package/reference/scripts/harness-init.sh +0 -111
  210. package/reference/scripts/pai-054-baseline-check.sh +0 -40
  211. package/reference/scripts/prove-smoke-test.sh +0 -112
  212. package/reference/scripts/setup-keychain-salt.sh +0 -12
  213. package/reference/scripts/skill-optimizer-friday.sh +0 -88
  214. package/reference/scripts/skill-qc-test.sh +0 -351
  215. package/reference/scripts/skill-synthesize-tonight.sh +0 -66
  216. package/reference/specs/HARNESS-EXTRACTION-SPEC.md +0 -263
  217. package/reference/specs/harness-v3-bash-deletion-plan.md +0 -65
  218. package/reference/specs/harness-v3-migration-plan.md +0 -188
  219. package/scripts/decision-reconcile.sh +0 -74
  220. package/scripts/decision-reconcile.ts +0 -152
  221. package/scripts/git-hooks/pre-commit +0 -76
  222. package/scripts/git-hooks/pre-push +0 -271
  223. package/scripts/harness-skill-check.sh +0 -52
  224. package/scripts/lib/gap-emit.sh +0 -65
  225. package/scripts/lib/jq-update.sh +0 -30
  226. package/scripts/lib/resolve-slug.sh +0 -30
  227. package/scripts/lib/verify-spec-compliance.sh +0 -102
  228. package/scripts/prove-backfill.sh +0 -87
  229. package/scripts/scaffold-rungate-config.ts +0 -91
  230. package/scripts/self-containment-check.sh +0 -109
  231. package/scripts/skill-qc-validator.sh +0 -402
  232. package/scripts/slug-resolver.sh +0 -14
  233. package/specs/BOOTSTRAP-DATA-FLOW-SPEC.md +0 -2493
  234. package/specs/BOOTSTRAP-TEST-PLAN.md +0 -571
  235. package/specs/HARNESS-GATES.md +0 -256
  236. package/specs/HARNESS-SKILL-CHAIN.md +0 -286
  237. package/specs/HARNESS-SKILL-CONTRACT.md +0 -93
  238. package/specs/HARNESS-STANDARD.md +0 -488
  239. package/specs/SPEC-TEMPLATE.md +0 -53
  240. package/specs/bootstrap-data-flow.png +0 -0
  241. package/specs/harness-automation-matrix.md +0 -314
  242. package/specs/harness-automation-matrix.rules.json +0 -64
  243. package/test/anti.test.ts +0 -80
  244. package/test/contract-negative.test.ts +0 -86
  245. package/test/contract.test.ts +0 -158
  246. package/test/external-deps.test.ts +0 -48
  247. package/test/fixtures/golden-project/.env.example +0 -3
  248. package/test/fixtures/golden-project/Makefile +0 -7
  249. package/test/fixtures/golden-project/docs/adr/ADR-001-framework.md +0 -23
  250. package/test/fixtures/golden-project/docs/setup-guide.md +0 -10
  251. package/test/fixtures/golden-project/package.json +0 -10
  252. package/test/fixtures/golden-project/specs/api-spec.md +0 -20
  253. package/test/fixtures/golden-project/src/auth.ts +0 -8
  254. package/test/fixtures/golden-project/src/db.ts +0 -11
  255. package/test/fixtures/golden-project/src/index.ts +0 -19
  256. package/test/fixtures/golden-project/src/utils/format.ts +0 -3
  257. package/test/fixtures/golden-project/test/auth.test.ts +0 -15
  258. package/test/fixtures/golden-project/tsconfig.json +0 -12
  259. package/test/meta-sc-coverage.test.ts +0 -159
  260. package/test/phase-0.test.ts +0 -846
  261. package/test/phase-1.test.ts +0 -617
  262. package/test/phase-2.test.ts +0 -620
  263. package/test/phase-3.test.ts +0 -99
  264. package/test/scaffold-conformity.test.ts +0 -8
  265. package/test/schema-canary.test.ts +0 -51
  266. package/test/spec-compliance-auto.test.ts +0 -64
  267. package/test/spec-compliance.test.ts +0 -295
  268. package/test/spec-discovery.test.ts +0 -68
  269. package/test/spec-drift.test.ts +0 -5
  270. package/test/structure.test.ts +0 -165
  271. package/test/unit/agent-brief-guard-ship.test.ts +0 -293
  272. package/test/unit/extract-constraints.test.ts +0 -145
  273. package/test/unit/issue-close-guard.test.ts +0 -204
  274. package/test/unit/scaffold-project.test.ts +0 -417
  275. package/test/unit/skill-cooccurrence.test.ts +0 -177
  276. package/test/unit/skill-sequence-logger.test.ts +0 -244
  277. package/test/unit/workflow-state-guard.test.ts +0 -95
  278. package/workflows/batch-ship.js +0 -295
  279. package/workflows/council.js +0 -481
  280. package/workflows/prove.js +0 -560
  281. package/workflows/ship.js +0 -789
  282. package/workflows/verify.js +0 -236
package/lib/scanner.ts ADDED
@@ -0,0 +1,701 @@
1
+ /**
2
+ * scanner.ts — Project scanner extracted from scaffold-project.ts (SC-358, SC-359)
3
+ *
4
+ * Scans a project root and returns a typed ProjectScan object containing
5
+ * tech stack, specs, consumers, source directories, and other project metadata.
6
+ *
7
+ * This module imports ONLY from fs, path, generators/types, and config-loader —
8
+ * no generation logic (agents-md, agent-briefs, code-map) is imported here
9
+ * (SC-365, AC-3).
10
+ */
11
+ import { existsSync, readFileSync, readdirSync, statSync } from "fs";
12
+ import { join, basename } from "path";
13
+ import { resolveConfig } from "./config-loader";
14
+ // A leaf, not a generator. SC-365 / AC-3 keeps generation logic out of the
15
+ // scanner; `lib/harness-identity.ts` imports nothing but fs and path, and
16
+ // exists precisely so this module and the generators can share one answer
17
+ // instead of drifting apart (#380).
18
+ import { isHarnessItself } from "./harness-identity";
19
+ import type {
20
+ ProjectScan,
21
+ ProjectType,
22
+ KeyFile,
23
+ SpecEntry,
24
+ TestFile,
25
+ RefFile,
26
+ DocRoute,
27
+ Category,
28
+ DirEntry,
29
+ ModuleEntry,
30
+ RouteEntry,
31
+ } from "./generators/types";
32
+
33
+ // Re-export ProjectType for callers that need it
34
+ export type { ProjectType } from "./generators/types";
35
+
36
+ // ── Project type detection ─────────────────────────────────────
37
+
38
+ export function detectProjectType(root: string): ProjectType {
39
+ const hasPackageJson = existsSync(join(root, "package.json"));
40
+ const hasSrc = existsSync(join(root, "src"));
41
+ const hasLib = existsSync(join(root, "lib"));
42
+ const hasMakefile = existsSync(join(root, "Makefile"));
43
+ const hasTsConfig = existsSync(join(root, "tsconfig.json"));
44
+ const hasDockerCompose = existsSync(join(root, "docker-compose.yml")) || existsSync(join(root, "docker-compose.yaml"));
45
+ const hasDockerfile = existsSync(join(root, "Dockerfile"));
46
+ const hasScriptsDir = existsSync(join(root, "scripts"));
47
+ const hasManifests = hasDockerCompose || hasDockerfile ||
48
+ existsSync(join(root, "k8s")) || existsSync(join(root, "terraform"));
49
+
50
+ if (hasSrc || hasLib || hasTsConfig || (hasPackageJson && (hasSrc || hasLib))) {
51
+ return "code";
52
+ }
53
+
54
+ if (hasManifests || (hasScriptsDir && !hasPackageJson)) {
55
+ return "infra";
56
+ }
57
+
58
+ if (hasPackageJson && hasMakefile) {
59
+ return "code";
60
+ }
61
+
62
+ if (hasPackageJson) {
63
+ return "code";
64
+ }
65
+
66
+ if (hasScriptsDir) {
67
+ return "infra";
68
+ }
69
+
70
+ return "content";
71
+ }
72
+
73
+ // ── Tech stack detection ───────────────────────────────────────
74
+
75
+ function detectTechStack(root: string): string[] {
76
+ const pkgPath = join(root, "package.json");
77
+ const techStack: string[] = [];
78
+
79
+ if (!existsSync(pkgPath)) return techStack;
80
+
81
+ try {
82
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
83
+
84
+ // Detect runtime
85
+ if (pkg.scripts?.test?.includes("bun") || pkg.scripts?.dev?.includes("bun") || pkg.scripts?.start?.includes("bun")) {
86
+ techStack.push("Bun");
87
+ } else if (pkg.scripts?.test?.includes("node") || pkg.scripts?.dev?.includes("node") || pkg.scripts?.start?.includes("node")) {
88
+ techStack.push("Node.js");
89
+ }
90
+
91
+ // Detect TypeScript
92
+ if (existsSync(join(root, "tsconfig.json")) || pkg.devDependencies?.typescript || pkg.dependencies?.typescript) {
93
+ techStack.push("TypeScript");
94
+ }
95
+
96
+ // Detect module system
97
+ if (pkg.type === "module") {
98
+ techStack.push("ESM");
99
+ }
100
+ } catch {}
101
+
102
+ return techStack;
103
+ }
104
+
105
+ // ── Spec scanning ──────────────────────────────────────────────
106
+
107
+ function scanSpecs(root: string): SpecEntry[] {
108
+ const specsDir = join(root, "specs");
109
+ if (!existsSync(specsDir)) return [];
110
+
111
+ const specs: SpecEntry[] = [];
112
+ const specFiles = readdirSync(specsDir).filter(f => f.endsWith(".md") && f !== "SPEC-TEMPLATE.md");
113
+
114
+ for (const f of specFiles) {
115
+ const content = readFileSync(join(specsDir, f), "utf-8");
116
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
117
+ let governs = "";
118
+ let testable = "TODO";
119
+
120
+ if (fmMatch) {
121
+ const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
122
+ if (gMatch && gMatch[1].trim() !== "TODO" && gMatch[1].trim().length > 5) {
123
+ governs = gMatch[1].trim().replace(/\|/g, "—").slice(0, 120);
124
+ }
125
+ const tMatch = fmMatch[1].match(/testable:\s*(.+)/);
126
+ if (tMatch) testable = tMatch[1].trim();
127
+ }
128
+
129
+ specs.push({ file: f, governs, testable });
130
+ }
131
+
132
+ // Also scan specs subdirectories
133
+ try {
134
+ const specSubDirs = readdirSync(specsDir, { withFileTypes: true })
135
+ .filter(d => d.isDirectory())
136
+ .map(d => d.name);
137
+
138
+ for (const sub of specSubDirs) {
139
+ const subPath = join(specsDir, sub);
140
+ const subFiles = readdirSync(subPath).filter(f => f.endsWith(".md") && f !== "INDEX.md");
141
+ if (subFiles.length > 0) {
142
+ const indexPath = join(subPath, "INDEX.md");
143
+ let groupGoverns = `${sub} (${subFiles.length} specs)`;
144
+ if (existsSync(indexPath)) {
145
+ const indexContent = readFileSync(indexPath, "utf-8");
146
+ const fmMatch = indexContent.match(/^---\n([\s\S]*?)\n---/);
147
+ if (fmMatch) {
148
+ const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
149
+ if (gMatch && gMatch[1].trim().length > 5) {
150
+ groupGoverns = gMatch[1].trim().replace(/\|/g, "—").slice(0, 120);
151
+ }
152
+ }
153
+ }
154
+ specs.push({ file: `${sub}/ (${subFiles.length} specs)`, governs: groupGoverns, testable: "yes" });
155
+ }
156
+ }
157
+ } catch {}
158
+
159
+ return specs;
160
+ }
161
+
162
+ // ── Consumer detection ─────────────────────────────────────────
163
+
164
+ function detectConsumers(root: string): string[] {
165
+ // First check the harness config (.claude/rungate/ directory, or the
166
+ // .claude/rungate.json monolith as fallback) — #70
167
+ const harness = loadHarnessConfig(root);
168
+ if (harness?.consumers && Array.isArray(harness.consumers) && harness.consumers.length > 0) {
169
+ return harness.consumers;
170
+ }
171
+
172
+ // Scan src/ for consumer modules
173
+ const srcDir = join(root, "src");
174
+ if (!existsSync(srcDir)) return [];
175
+
176
+ const consumers: string[] = [];
177
+ const consumerPatterns = ["-routes.ts", "-generator.ts", "-plan.ts", "-intel.ts"];
178
+
179
+ for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts"))) {
180
+ try {
181
+ const content = readFileSync(join(srcDir, f), "utf-8");
182
+ const isConsumer = consumerPatterns.some(p => f.includes(p)) ||
183
+ content.includes("app.get(") || content.includes("app.post(") ||
184
+ content.includes("router.") || content.includes("export default");
185
+ if (isConsumer) {
186
+ consumers.push(f.replace(/\.ts$/, "").replace(/-routes|-generator/, ""));
187
+ }
188
+ } catch {}
189
+ }
190
+
191
+ return [...new Set(consumers)].sort();
192
+ }
193
+
194
+ // ── Source directory detection ──────────────────────────────────
195
+
196
+ function detectSourceDirectories(root: string): string[] {
197
+ const candidates = ["src", "lib", "gates", "workflows", "hooks", "dashboard/src"];
198
+ return candidates.filter(dir => existsSync(join(root, dir)));
199
+ }
200
+
201
+ // ── Key file scanning ──────────────────────────────────────────
202
+
203
+ function scanKeyFiles(root: string): KeyFile[] {
204
+ // Always include scaffold-generated files for idempotency (SC-364)
205
+ const keyFiles: KeyFile[] = [
206
+ { file: "AGENTS.md", what: "Project entry point", when: "Always first" },
207
+ { file: "PROJECT-STATE.md", what: "Live status + handoff (generated from project-state.json — don't edit directly)", when: "Session start, always first after AGENTS.md" },
208
+ { file: "project-state.json", what: "Source of truth for project status", when: "When editing state" },
209
+ ];
210
+
211
+ // Conditionally included files (only if they exist)
212
+ const conditionalPatterns: Array<{ pattern: string; what: string; when: string }> = [
213
+ { pattern: "package.json", what: "Dependencies and scripts", when: "Adding deps or scripts" },
214
+ { pattern: "Makefile", what: "Build/deploy commands", when: "Building or deploying" },
215
+ { pattern: "tsconfig.json", what: "TypeScript configuration", when: "Changing TS settings" },
216
+ { pattern: "Containerfile", what: "Container build definition", when: "Modifying container" },
217
+ { pattern: "Dockerfile", what: "Container build definition", when: "Modifying container" },
218
+ ];
219
+
220
+ // Always include the .claude/rungate/ directory for idempotency — scaffold
221
+ // generates the directory form, not the legacy monolith (#70)
222
+ keyFiles.push({ file: ".claude/rungate/", what: "Harness project config (directory)", when: "Shipping through harness" });
223
+
224
+ for (const kf of conditionalPatterns) {
225
+ if (existsSync(join(root, kf.pattern))) {
226
+ keyFiles.push({ file: kf.pattern, what: kf.what, when: kf.when });
227
+ }
228
+ }
229
+
230
+ // Scan for main source directories
231
+ for (const srcDir of ["src", "lib", "gates", "workflows", "hooks"]) {
232
+ if (existsSync(join(root, srcDir))) {
233
+ keyFiles.push({
234
+ file: `${srcDir}/`,
235
+ what: `${srcDir.charAt(0).toUpperCase() + srcDir.slice(1)} directory`,
236
+ when: `Working on ${srcDir}`,
237
+ });
238
+ }
239
+ }
240
+
241
+ return keyFiles;
242
+ }
243
+
244
+ // ── Test file scanning ─────────────────────────────────────────
245
+
246
+ function scanTestFiles(root: string): TestFile[] {
247
+ const testDir = existsSync(join(root, "test")) ? "test"
248
+ : existsSync(join(root, "tests")) ? "tests"
249
+ : null;
250
+
251
+ if (!testDir) return [];
252
+
253
+ try {
254
+ return readdirSync(join(root, testDir))
255
+ .filter(f => f.endsWith(".test.ts"))
256
+ .map(f => ({
257
+ label: f.replace(".test.ts", "").replace(/-/g, " "),
258
+ file: f,
259
+ }));
260
+ } catch {
261
+ return [];
262
+ }
263
+ }
264
+
265
+ // ── Reference file scanning ───────────────────────────────────
266
+
267
+ function scanRefFiles(root: string): RefFile[] {
268
+ const refDir = join(root, "reference");
269
+ if (!existsSync(refDir)) return [];
270
+
271
+ try {
272
+ return readdirSync(refDir).map(f => ({
273
+ file: f,
274
+ what: "Historical reference",
275
+ }));
276
+ } catch {
277
+ return [];
278
+ }
279
+ }
280
+
281
+ // ── Doc routing scanning ───────────────────────────────────────
282
+
283
+ function scanDocRouting(root: string, categories: Category[]): DocRoute[] {
284
+ const docRouting: DocRoute[] = [];
285
+
286
+ // Always include scaffold-generated files for idempotency (SC-364)
287
+ docRouting.push({ need: "Codebase structure (routes, components, modules, health)", file: "CODE-MAP.md" });
288
+ docRouting.push({ need: "Current project state, priorities, and session history", file: "PROJECT-STATE.md" });
289
+
290
+ // Root-level docs with intent descriptions (conditionally included)
291
+ const rootDocIntents: Record<string, string> = {
292
+ "ARCHITECTURE.md": "System architecture and design principles",
293
+ "PRINCIPLES.md": "Core engineering principles and standards",
294
+ "CONTRIBUTING.md": "How to contribute — workflow, conventions, review process",
295
+ "MODEL.md": "Domain model and data relationships",
296
+ };
297
+
298
+ for (const [f, intent] of Object.entries(rootDocIntents)) {
299
+ if (existsSync(join(root, f))) {
300
+ docRouting.push({ need: intent, file: f });
301
+ }
302
+ }
303
+
304
+ // Categories
305
+ for (const cat of categories) {
306
+ const catPath = join(root, cat.dir);
307
+ if (existsSync(catPath)) {
308
+ try {
309
+ // Recursive: reference/ held 19 markdown files, every one of them in a
310
+ // subdirectory, and a shallow count advertised it as "(0 files)" (#91).
311
+ // A row saying a directory is empty reads as an instruction not to look.
312
+ const files = readdirSync(catPath, { recursive: true }).map(String).filter(f => f.endsWith(".md"));
313
+ docRouting.push({ need: `${cat.label} (${files.length} files)`, file: `${cat.dir}/` });
314
+ } catch {
315
+ docRouting.push({ need: cat.label, file: `${cat.dir}/` });
316
+ }
317
+ } else {
318
+ docRouting.push({ need: cat.label, file: `${cat.dir}/` });
319
+ }
320
+ }
321
+
322
+ // Docs top-level files
323
+ const docsDir = join(root, "docs");
324
+ if (existsSync(docsDir)) {
325
+ try {
326
+ const allDocs = readdirSync(docsDir).filter(f => f.endsWith(".md"));
327
+ for (const f of allDocs) {
328
+ const docPath = join(docsDir, f);
329
+ const content = readFileSync(docPath, "utf-8");
330
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
331
+ let need = f.replace(/\.md$/, "").replace(/-/g, " ");
332
+ if (fmMatch) {
333
+ const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
334
+ if (gMatch && gMatch[1].trim() !== "TODO") need = gMatch[1].trim();
335
+ }
336
+ docRouting.push({ need, file: `docs/${f}` });
337
+ }
338
+ const subDirs = readdirSync(docsDir, { withFileTypes: true })
339
+ .filter(d => d.isDirectory() && !categories.some(c => c.dir === `docs/${d.name}`))
340
+ .map(d => d.name);
341
+ for (const sub of subDirs) {
342
+ const subPath = join(docsDir, sub);
343
+ const subFiles = readdirSync(subPath).filter(f => f.endsWith(".md"));
344
+ if (subFiles.length > 0) {
345
+ docRouting.push({ need: `${sub} (${subFiles.length} files)`, file: `docs/${sub}/` });
346
+ }
347
+ }
348
+ } catch {}
349
+ }
350
+
351
+ // Filter to non-obvious mappings
352
+ return docRouting.filter(d => {
353
+ const slug = d.file.replace(/\.md$/, "").replace(/.*\//, "").toLowerCase().replace(/-/g, " ");
354
+ const needLower = d.need.toLowerCase();
355
+ return !needLower.startsWith(slug) || d.need.includes("—") || d.need.includes("(");
356
+ });
357
+ }
358
+
359
+ // ── Identity detection ─────────────────────────────────────────
360
+
361
+ function detectIdentity(root: string, pkgDesc: string, type: ProjectType): string {
362
+ // Read README.md first paragraph
363
+ const readmePath = join(root, "README.md");
364
+ if (existsSync(readmePath)) {
365
+ try {
366
+ let readme = readFileSync(readmePath, "utf-8");
367
+ // Normalize CRLF to LF for consistent parsing
368
+ readme = readme.replace(/\r\n/g, "\n");
369
+ // Strip YAML frontmatter
370
+ while (readme.startsWith("---\n")) {
371
+ const endFm = readme.indexOf("\n---\n", 4);
372
+ if (endFm > 0) { readme = readme.slice(endFm + 5); } else { break; }
373
+ }
374
+ readme = readme.replace(/<!--[\s\S]*?-->/g, "");
375
+ const paragraphs = readme.split(/\n\n+/).filter(p => {
376
+ const trimmed = p.trim();
377
+ if (!trimmed || trimmed.length <= 20) return false;
378
+ if (trimmed.startsWith("#") || trimmed.startsWith("---") || trimmed.startsWith("<")) return false;
379
+ // Skip badge lines (shield.io badges, linked images)
380
+ if (/^\[!\[.*\]\(.*\)\]\(.*\)/.test(trimmed)) return false;
381
+ // Skip image-only paragraphs (![alt](url) lines with nothing else)
382
+ const lines = trimmed.split("\n");
383
+ if (lines.every(l => /^\s*!\[.*\]\(.*\)\s*$/.test(l) || /^\s*$/.test(l))) return false;
384
+ return true;
385
+ });
386
+ if (paragraphs.length > 0) return paragraphs[0].replace(/\n/g, " ").trim();
387
+ } catch {}
388
+ }
389
+
390
+ if (pkgDesc) return pkgDesc;
391
+
392
+ const typeLabel = type === "code" ? "Code" : type === "content" ? "Content" : "Infrastructure";
393
+ return `${typeLabel} project. <!-- TODO: Describe what this project is -->`;
394
+ }
395
+
396
+ // ── Repo URL detection ─────────────────────────────────────────
397
+
398
+ function detectRepoUrl(root: string): string {
399
+ try {
400
+ const result = Bun.spawnSync(["git", "-C", root, "remote", "get-url", "origin"], { timeout: 5_000 });
401
+ return result.stdout.toString().trim()
402
+ .replace(/\.git$/, "")
403
+ .replace("git@github.com:", "https://github.com/");
404
+ } catch {
405
+ return "";
406
+ }
407
+ }
408
+
409
+ // ── Makefile targets ───────────────────────────────────────────
410
+
411
+ function scanMakeTargets(root: string): string {
412
+ const makefile = join(root, "Makefile");
413
+ if (!existsSync(makefile)) return "";
414
+
415
+ try {
416
+ const content = readFileSync(makefile, "utf-8");
417
+ const targets = content.match(/^[\w-]+(?=:)/gm)?.filter(t => !t.startsWith(".") && !t.startsWith("_")).slice(0, 8);
418
+ if (targets?.length) return `\n- **Key commands:** \`make ${targets.join("`, `make ")}\``;
419
+ } catch {}
420
+
421
+ return "";
422
+ }
423
+
424
+ // ── Harness config loading ─────────────────────────────────────
425
+
426
+ /**
427
+ * Resolves the harness config via lib/config-loader — `.claude/rungate/`
428
+ * directory form first, `.claude/rungate.json` monolith as fallback (#70).
429
+ *
430
+ * `null` means ABSENT and nothing else. The `try/catch` this replaces caught
431
+ * two throws, not one — the deliberate malformed/orphan throw ADR-001 D2
432
+ * exists to raise, and the ordinary "no config found" — and answered `null`
433
+ * to both, so a project whose config could not be read scanned identically to
434
+ * a project that had none. That is the fail-open archetype in
435
+ * `.claude/rules/checks-must-be-able-to-fail.md`: a catch that reports
436
+ * "nothing here". A broken config now propagates (ADR-002 Step 3).
437
+ */
438
+ function loadHarnessConfig(root: string): Record<string, any> | null {
439
+ const resolution = resolveConfig(root);
440
+ return resolution.status === "resolved"
441
+ ? (resolution.config as unknown as Record<string, any>)
442
+ : null;
443
+ }
444
+
445
+ // ── Code structure scanning (dirs, modules, routes) ────────────
446
+
447
+ function scanDirs(root: string): DirEntry[] {
448
+ const skip = new Set(["node_modules", ".git", "reference", "dist", "build", ".next", ".fallow"]);
449
+ const dirs: DirEntry[] = [];
450
+
451
+ try {
452
+ for (const entry of readdirSync(root)) {
453
+ if (entry.startsWith(".") && entry !== ".claude") continue;
454
+ if (skip.has(entry)) continue;
455
+ const full = join(root, entry);
456
+ try {
457
+ if (!statSync(full).isDirectory()) continue;
458
+ const files = readdirSync(full, { recursive: true }).map(String);
459
+ const exts = new Set(files.map(f => f.split(".").pop()).filter((e): e is string => Boolean(e)));
460
+ dirs.push({ name: entry, fileCount: files.length, types: [...exts].slice(0, 5) });
461
+ } catch {}
462
+ }
463
+ } catch {}
464
+
465
+ dirs.sort((a, b) => b.fileCount - a.fileCount);
466
+ return dirs;
467
+ }
468
+
469
+ function scanModules(root: string): ModuleEntry[] {
470
+ const srcDir = join(root, "src");
471
+ const modules: ModuleEntry[] = [];
472
+
473
+ if (!existsSync(srcDir)) return modules;
474
+
475
+ try {
476
+ for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts") || f.endsWith(".js"))) {
477
+ const content = readFileSync(join(srcDir, f), "utf-8");
478
+ const exports: string[] = [];
479
+ const exportPattern = /export\s+(?:function|const|class|type|interface)\s+(\w+)/g;
480
+ let m;
481
+ while ((m = exportPattern.exec(content)) !== null) exports.push(m[1]);
482
+ if (exports.length > 0) modules.push({ file: `src/${f}`, exports });
483
+ }
484
+ } catch {}
485
+
486
+ return modules;
487
+ }
488
+
489
+ function scanRoutes(root: string): RouteEntry[] {
490
+ const srcDir = join(root, "src");
491
+ const routes: RouteEntry[] = [];
492
+
493
+ if (!existsSync(srcDir)) return routes;
494
+
495
+ try {
496
+ for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts") || f.endsWith(".js"))) {
497
+ const content = readFileSync(join(srcDir, f), "utf-8");
498
+ const routePatterns = [
499
+ /app\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/gi,
500
+ /router\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/gi,
501
+ /["'`]((?:GET|POST|PUT|DELETE|PATCH)\s+\/[^"'`]+)["'`]/g,
502
+ ];
503
+ for (const pattern of routePatterns) {
504
+ let rm;
505
+ while ((rm = pattern.exec(content)) !== null) {
506
+ if (rm[2]) routes.push({ method: rm[1].toUpperCase(), path: rm[2], file: `src/${f}` });
507
+ else if (rm[1]) {
508
+ const parts = rm[1].split(/\s+/);
509
+ if (parts.length === 2) routes.push({ method: parts[0], path: parts[1], file: `src/${f}` });
510
+ }
511
+ }
512
+ }
513
+ }
514
+ } catch {}
515
+
516
+ return routes;
517
+ }
518
+
519
+ // ── Dependency counting ────────────────────────────────────────
520
+
521
+ function countDeps(root: string): { deps: number; devDeps: number } {
522
+ const pkgPath = join(root, "package.json");
523
+ if (!existsSync(pkgPath)) return { deps: 0, devDeps: 0 };
524
+
525
+ try {
526
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
527
+ return {
528
+ deps: Object.keys(pkg.dependencies || {}).length,
529
+ devDeps: Object.keys(pkg.devDependencies || {}).length,
530
+ };
531
+ } catch {
532
+ return { deps: 0, devDeps: 0 };
533
+ }
534
+ }
535
+
536
+ // ── Prompt routing scanning ────────────────────────────────────
537
+
538
+ function scanPromptRouting(root: string, harness: Record<string, any> | null): Record<string, Array<{ file: string; when: string }>> {
539
+ const defaultKeywords: Record<string, string[]> = {
540
+ marcus: ["coding", "code", "standard", "implementation", "engineering", "convention", "principle"],
541
+ quinn: ["testing", "test", "qa", "quality", "coverage"],
542
+ rook: ["security", "auth", "secret", "vulnerability", "access"],
543
+ serena: ["architecture", "design-pattern", "system", "module", "structure"],
544
+ aditi: ["design", "ui", "ux", "component", "visual", "accessibility"],
545
+ discovery: ["discovery", "ac-format", "evidence", "scope", "sizing"],
546
+ };
547
+ const agentKeywords: Record<string, string[]> = { ...defaultKeywords, ...harness?.promptKeywords };
548
+ const promptsByAgent: Record<string, Array<{ file: string; when: string }>> = {
549
+ marcus: [], quinn: [], rook: [], serena: [], aditi: [], discovery: [],
550
+ };
551
+
552
+ const promptsDir = join(root, "prompts");
553
+ if (!existsSync(promptsDir)) return promptsByAgent;
554
+
555
+ try {
556
+ const promptFiles = readdirSync(promptsDir).filter(f => f.endsWith(".md"));
557
+ for (const f of promptFiles) {
558
+ const content = readFileSync(join(promptsDir, f), "utf-8");
559
+ const lower = f.toLowerCase();
560
+
561
+ let whenToRead = f.replace(/\.md$/, "").replace(/-/g, " ");
562
+ const descMatch = content.match(/^description:\s*(.+)$/m);
563
+ const headingMatch = content.match(/^#\s+(.+)$/m);
564
+ if (descMatch) {
565
+ whenToRead = descMatch[1].trim();
566
+ } else if (headingMatch) {
567
+ whenToRead = headingMatch[1].trim();
568
+ }
569
+
570
+ let matched = false;
571
+ for (const [agent, keywords] of Object.entries(agentKeywords)) {
572
+ if (keywords.some(kw => lower.includes(kw))) {
573
+ promptsByAgent[agent].push({ file: `prompts/${f}`, when: whenToRead });
574
+ matched = true;
575
+ }
576
+ }
577
+ if (!matched) {
578
+ for (const agent of Object.keys(promptsByAgent)) {
579
+ promptsByAgent[agent].push({ file: `prompts/${f}`, when: whenToRead });
580
+ }
581
+ }
582
+ }
583
+ } catch {}
584
+
585
+ return promptsByAgent;
586
+ }
587
+
588
+ // ── Agent meta scanning ────────────────────────────────────────
589
+
590
+ function scanAgentMeta(harness: Record<string, any> | null): Record<string, { description: string; tools: string; model: string; tiers?: Record<string, string[]> }> {
591
+ const agentMeta: Record<string, { description: string; tools: string; model: string; tiers?: Record<string, string[]> }> = {};
592
+
593
+ if (!harness?.roles) return agentMeta;
594
+
595
+ for (const [roleName, roleConfig] of Object.entries(harness.roles as Record<string, any>)) {
596
+ if (roleConfig.description || roleConfig.tools || roleConfig.model) {
597
+ agentMeta[roleName] = {
598
+ description: roleConfig.description || `${roleName} agent`,
599
+ tools: roleConfig.tools || "[Bash, Read]",
600
+ model: roleConfig.model || "sonnet",
601
+ ...(roleConfig.tiers ? { tiers: roleConfig.tiers } : {}),
602
+ };
603
+ }
604
+ }
605
+
606
+ return agentMeta;
607
+ }
608
+
609
+ // ── Test command detection ─────────────────────────────────────
610
+
611
+ function detectTestCmd(root: string): string {
612
+ const pkgPath = join(root, "package.json");
613
+ if (!existsSync(pkgPath)) return "bun test";
614
+
615
+ try {
616
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
617
+ if (pkg.scripts?.test) return pkg.scripts.test;
618
+ } catch {}
619
+
620
+ return "bun test";
621
+ }
622
+
623
+ // ── Categories ─────────────────────────────────────────────────
624
+
625
+ function buildCategories(): Category[] {
626
+ return [
627
+ { dir: "specs", label: "Specs — success criteria, constraints, requirements", frontmatter: "`doc-type: spec`, `testable`, `governs`", notes: "SCs auto-generate tests" },
628
+ { dir: "docs/adr", label: "ADRs — architecture decisions", frontmatter: "`doc-type: adr`, `status`, `created`", notes: "Architecture decisions" },
629
+ { dir: "docs/research", label: "Research — findings, evaluations, competitive analysis", frontmatter: "`doc-type: research`, `governs`", notes: "Tool evaluations, competitive analysis, findings" },
630
+ { dir: "docs/council", label: "Council — synthesis, design debates", frontmatter: "`doc-type: council`", notes: "Council synthesis, design debates" },
631
+ { dir: "docs/guides", label: "Guides — setup, onboarding, reference", frontmatter: "`doc-type: guide`", notes: "Setup, onboarding, reference" },
632
+ { dir: "reference", label: "Reference — historical and inactive docs", frontmatter: "—", notes: "Historical reference" },
633
+ ];
634
+ }
635
+
636
+ // ── Prompt prefix detection ────────────────────────────────────
637
+
638
+ function detectPromptPrefix(root: string): string {
639
+ return isHarnessItself(root) ? "prompts" : "node_modules/rungate/prompts";
640
+ }
641
+
642
+ // ── Main scanner ───────────────────────────────────────────────
643
+
644
+ export function scanProject(root: string): ProjectScan {
645
+ const type = detectProjectType(root);
646
+ const pkgPath = join(root, "package.json");
647
+ let pkgName = basename(root);
648
+ let pkgDesc = "";
649
+
650
+ if (existsSync(pkgPath)) {
651
+ try {
652
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
653
+ pkgName = pkg.name || pkgName;
654
+ pkgDesc = pkg.description || "";
655
+ } catch {}
656
+ }
657
+
658
+ const harness = loadHarnessConfig(root);
659
+ const categories = buildCategories();
660
+ const { deps, devDeps } = countDeps(root);
661
+
662
+ const harnessTemplatesDir = (() => {
663
+ // Find templates relative to scanner location
664
+ const localTemplates = join(__dirname, "..", "templates", "agent-briefs");
665
+ if (existsSync(localTemplates)) return localTemplates;
666
+ // Fallback: node_modules/rungate/templates/agent-briefs
667
+ const nmTemplates = join(root, "node_modules", "rungate", "templates", "agent-briefs");
668
+ if (existsSync(nmTemplates)) return nmTemplates;
669
+ return "";
670
+ })();
671
+
672
+ return {
673
+ name: pkgName,
674
+ type,
675
+ root,
676
+ identity: detectIdentity(root, pkgDesc, type),
677
+ techStack: detectTechStack(root),
678
+ repoUrl: detectRepoUrl(root),
679
+ testCmd: detectTestCmd(root),
680
+ keyFiles: scanKeyFiles(root),
681
+ specs: scanSpecs(root),
682
+ testFiles: scanTestFiles(root),
683
+ refFiles: scanRefFiles(root),
684
+ docRouting: scanDocRouting(root, categories),
685
+ categories,
686
+ consumers: detectConsumers(root),
687
+ hasCodeMap: true, // Always true for idempotency — scaffold generates CODE-MAP.md (SC-364)
688
+ makeTargets: scanMakeTargets(root),
689
+ sourceDirs: detectSourceDirectories(root),
690
+ promptRouting: scanPromptRouting(root, harness),
691
+ harnessConfig: harness,
692
+ agentMeta: scanAgentMeta(harness),
693
+ dirs: scanDirs(root),
694
+ deps,
695
+ devDeps,
696
+ modules: scanModules(root),
697
+ routes: scanRoutes(root),
698
+ harnessTemplatesDir,
699
+ promptPrefix: detectPromptPrefix(root),
700
+ };
701
+ }