rungate 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/brief-precedence.ts +114 -0
  11. package/lib/canary.ts +117 -0
  12. package/lib/check-registry.ts +226 -0
  13. package/lib/ci-checkout.ts +426 -0
  14. package/lib/cli-commands.ts +137 -0
  15. package/lib/compliance-backfill.ts +232 -0
  16. package/lib/compliance-report.ts +605 -0
  17. package/lib/compliance.ts +361 -0
  18. package/lib/config-loader.ts +255 -0
  19. package/lib/config-readers.ts +86 -0
  20. package/lib/conformity.ts +2161 -137
  21. package/lib/container-provenance.ts +230 -0
  22. package/lib/create-brief.ts +150 -0
  23. package/lib/create-sc.ts +267 -0
  24. package/lib/decomposition-waves.ts +197 -0
  25. package/lib/deep-merge.ts +69 -0
  26. package/lib/dev-liveness.ts +214 -0
  27. package/lib/directive-extractor.ts +210 -0
  28. package/lib/distribution-standing.ts +113 -0
  29. package/lib/doc-hygiene.ts +238 -0
  30. package/lib/eval-criteria.ts +6 -0
  31. package/lib/evidence-portability.ts +123 -0
  32. package/lib/evidence-prevalidator.ts +390 -0
  33. package/lib/evidence-required.ts +150 -0
  34. package/lib/evidence-satisfiability.ts +288 -0
  35. package/lib/frontmatter.ts +163 -0
  36. package/lib/gap-scanner.ts +348 -0
  37. package/lib/gate-check-audit.ts +190 -0
  38. package/lib/gate-enforcement.ts +366 -0
  39. package/lib/generators/agent-briefs.ts +136 -0
  40. package/lib/generators/agents-md.ts +511 -0
  41. package/lib/generators/code-map.ts +60 -0
  42. package/lib/generators/types.ts +184 -0
  43. package/lib/git-ref-normalizer.ts +107 -0
  44. package/lib/github.ts +539 -0
  45. package/lib/harness-identity.ts +63 -0
  46. package/lib/hill-climb.ts +164 -0
  47. package/lib/instruction-effectiveness.ts +131 -0
  48. package/lib/issue-closure-audit.ts +225 -0
  49. package/lib/issue-create-override.ts +343 -0
  50. package/lib/issue-extraction.ts +368 -0
  51. package/lib/js-top-level-code.ts +250 -0
  52. package/lib/liveness-contradiction.ts +149 -0
  53. package/lib/organize.ts +505 -0
  54. package/lib/paths.ts +197 -6
  55. package/lib/phase2-decomposition.ts +270 -0
  56. package/lib/post-fix-verify.ts +157 -0
  57. package/lib/prior-branch.ts +512 -0
  58. package/lib/project-state-shape.ts +166 -0
  59. package/lib/promote-outputs.ts +156 -0
  60. package/lib/prove-label-gate.ts +128 -0
  61. package/lib/reachability.ts +302 -0
  62. package/lib/release-preflight.ts +288 -0
  63. package/lib/rule-health-pipeline.ts +264 -0
  64. package/lib/rule-health-trend.ts +161 -0
  65. package/lib/rule-provenance.ts +149 -0
  66. package/lib/rule-registry.ts +128 -0
  67. package/lib/rungate-schema.ts +127 -5
  68. package/lib/sc-claim-forms.ts +179 -0
  69. package/lib/sc-cover.ts +150 -0
  70. package/lib/sc-guard.ts +157 -0
  71. package/lib/sc-ids.ts +344 -0
  72. package/lib/scaffold/defaults.ts +165 -0
  73. package/lib/scaffold/managed-workflow.ts +370 -0
  74. package/lib/scaffold/owned-files.ts +265 -0
  75. package/lib/scaffold/pre-push-hook.ts +165 -0
  76. package/lib/scaffold/steps.ts +2621 -0
  77. package/lib/scanner.ts +701 -0
  78. package/lib/scope-denylist.ts +258 -0
  79. package/lib/screenshot-upload.ts +73 -0
  80. package/lib/secret-patterns.ts +112 -0
  81. package/lib/security-verdict.ts +616 -0
  82. package/lib/signal-phrases.ts +1 -0
  83. package/lib/spec-change-conformity.ts +80 -0
  84. package/lib/spec-files.ts +62 -0
  85. package/lib/spec-registry.ts +133 -0
  86. package/lib/spec-updater.ts +96 -0
  87. package/lib/stale-cleanup.ts +224 -0
  88. package/lib/stale-issue-scanner.ts +36 -0
  89. package/lib/strip-js-comments.ts +269 -0
  90. package/lib/suite-measurement.ts +228 -0
  91. package/lib/task-completion-checks.ts +224 -0
  92. package/lib/test-suite-lock.ts +1136 -0
  93. package/lib/transcript-checker.ts +1140 -0
  94. package/lib/typescript-project.ts +233 -0
  95. package/lib/validators/spec-validators.ts +171 -0
  96. package/lib/verdict-capture.ts +73 -0
  97. package/lib/verified-push.ts +535 -0
  98. package/lib/workflow-security.ts +174 -0
  99. package/lib/worktree-cleanup.ts +432 -0
  100. package/lib/worktree-collect.ts +283 -0
  101. package/lib/worktree-isolation.ts +82 -0
  102. package/lib/worktree-repo.ts +300 -0
  103. package/package.json +27 -3
  104. package/prompts/ac-adversary.md +14 -2
  105. package/prompts/aditi.md +5 -0
  106. package/prompts/blast-radius.md +5 -0
  107. package/prompts/container-verify.md +5 -0
  108. package/prompts/discovery.md +4 -0
  109. package/prompts/environment.md +5 -0
  110. package/prompts/evidence-hierarchy.md +5 -0
  111. package/prompts/evidence-validator.md +11 -0
  112. package/prompts/marcus.md +5 -0
  113. package/prompts/prevention.md +5 -0
  114. package/prompts/prove-reproducer.md +12 -0
  115. package/prompts/quinn-decision-tree.md +5 -0
  116. package/prompts/quinn-ui-brief.md +5 -0
  117. package/prompts/quinn.md +5 -0
  118. package/prompts/rca.md +5 -0
  119. package/prompts/read-before-write.md +4 -0
  120. package/prompts/regression.md +5 -0
  121. package/prompts/serena.md +5 -0
  122. package/scripts/audit-specs.ts +464 -0
  123. package/scripts/convert-spec.ts +293 -0
  124. package/scripts/create-sc.ts +92 -0
  125. package/scripts/create-spec.ts +166 -0
  126. package/scripts/extract-constraints.ts +4 -3
  127. package/scripts/generate-code-map.ts +1 -1
  128. package/scripts/scaffold-project.ts +138 -1426
  129. package/scripts/sync-spec-tests.ts +211 -126
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
+ }