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
@@ -0,0 +1,2621 @@
1
+ /**
2
+ * scaffold/steps.ts — All scaffold step functions extracted from scaffold-project.ts.
3
+ *
4
+ * Each function takes a project root path and an actions array for reporting.
5
+ * Pure side-effect functions: read from disk, write to disk, push to actions.
6
+ *
7
+ * Extracted per SCAFFOLD-DECOMPOSITION-SPEC to keep scaffold-project.ts
8
+ * as orchestrator-only (under 200 lines).
9
+ */
10
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSync } from "fs";
11
+ import { join, basename, dirname } from "path";
12
+ import { auditSpecs } from "../../scripts/audit-specs";
13
+ import { generateAgentsMd as buildAgentsMdContent, generateScopedRules } from "../generators/agents-md";
14
+ import { isHarnessItself } from "../harness-identity";
15
+ import { generateAgentBriefs as buildAgentBriefsContent } from "../generators/agent-briefs";
16
+ import { generateCodeMap as buildCodeMapContent } from "../generators/code-map";
17
+ import { buildAgentMeta, DEFAULT_AGENT_META } from "../create-brief";
18
+ import { buildDefaultRoles, buildDefaultHooks } from "./defaults";
19
+ import { mergeManagedWorkflow } from "./managed-workflow";
20
+ import { PRE_PUSH_MANAGED_MARKER, prePushHookScript } from "./pre-push-hook";
21
+ import { tryLoadRungateConfig } from "../config-loader";
22
+ import type { ProjectScan, ProjectType, SpecEntry, TestFile, RefFile, DocRoute, Category } from "../generators/types";
23
+ import { tier1Ere } from "../secret-patterns";
24
+ import { healthPathIn } from "../liveness-contradiction";
25
+ import { decideRuleWrite } from "../rule-provenance";
26
+ import { referencedPaths } from "../agents-md-refs";
27
+ import { TS_SOURCE_DIRS, typeScriptSourceDirs, typecheckDecision } from "../typescript-project";
28
+ import {
29
+ OWNED_FILES,
30
+ SCAFFOLD_REFUSE,
31
+ decideOwnedWrite,
32
+ type WriteStrategy,
33
+ } from "./owned-files";
34
+
35
+ /**
36
+ * Look for a declared health route in the places a server declares one.
37
+ *
38
+ * Bounded deliberately: a handful of conventional entry points, read once
39
+ * each. A recursive scan of the whole tree would find more and would also
40
+ * find the word "health" in a test fixture, and a detector that reports a
41
+ * fixture's route as the server's is worse than one that reports null —
42
+ * null is honest, a wrong path is a DOWN verdict on a healthy server.
43
+ */
44
+ function detectHealthPath(root: string): string | null {
45
+ const candidates = [
46
+ "src/server.ts", "src/server.js", "src/index.ts", "src/index.js",
47
+ "src/app.ts", "src/app.js", "src/api.ts", "src/routes.ts",
48
+ "server.ts", "server.js", "index.ts", "app.ts",
49
+ ];
50
+ for (const rel of candidates) {
51
+ const abs = join(root, rel);
52
+ if (!existsSync(abs)) continue;
53
+ const found = healthPathIn(readFileSync(abs, "utf-8"));
54
+ if (found) return found;
55
+ }
56
+ return null;
57
+ }
58
+
59
+ // ── Helpers ────────────────────────────────────────────────────
60
+
61
+ /**
62
+ * Seed a file once. The content afterwards belongs to someone else.
63
+ *
64
+ * This is `create-only` in `OWNED_FILES` terms, and it is correct for
65
+ * `project-state.json` and `PROJECT-STATE.md` (DA-owned, #296) and for the
66
+ * two files the harness seeds but does not claim.
67
+ *
68
+ * It was ALSO being used for `test/scaffold-conformity.test.ts`, which
69
+ * `.claude/rules/harness-managed.md` claims is "regenerated on re-scaffold"
70
+ * (#208). It was not: it was skipped forever, and the run said
71
+ * `SKIP (already exists)`, which reads exactly like "already current". That
72
+ * call site now uses `regenerateOwned`.
73
+ *
74
+ * The wording changed with it. "SKIP … already exists" describes the check
75
+ * that was performed; "seeded once" describes the policy, and a reader of
76
+ * the log can tell that apart from "looked and found no difference".
77
+ *
78
+ * **It delegates rather than reimplementing, and that is load-bearing.** The
79
+ * first draft read the decision and then branched on `action !== "create"`,
80
+ * which is equivalent for every input `create-only` can produce today — and
81
+ * exactly because it is equivalent, it ABSORBED a mutation: deleting the
82
+ * `create-only` branch from `decideOwnedWrite` made every seeded file fall
83
+ * through to the regenerate path, and `safeWrite` reported `UNCHANGED` and
84
+ * declined to write anyway. Nothing went red. The #296 protection was
85
+ * asserted in the declaration and enforced in a second place, so mutating
86
+ * the declaration proved nothing. One writer, one decider.
87
+ */
88
+ export function safeWrite(filePath: string, content: string, label: string, actions: string[]): void {
89
+ regenerateOwned(filePath, content, label, actions, "create-only");
90
+ }
91
+
92
+ /**
93
+ * Write a file the harness OWNS, and report what actually changed.
94
+ *
95
+ * The difference from `safeWrite` is the whole of #208: this one writes
96
+ * every run, compares bytes, and reports `UNCHANGED` only after looking.
97
+ * `0 changed` becomes a measurement rather than the absence of an attempt.
98
+ *
99
+ * `strategy` comes from `OWNED_FILES`, which is the declaration the doc
100
+ * table is reconciled against — so a file cannot be claimed as managed in
101
+ * prose while being written by a helper that skips it.
102
+ */
103
+ export function ownedStrategy(label: string): WriteStrategy {
104
+ for (const owned of OWNED_FILES) {
105
+ if (owned.path === label) return owned.strategy;
106
+ if (owned.path.includes("*")) {
107
+ const [prefix, suffix] = owned.path.split("*");
108
+ if (label.startsWith(prefix) && label.endsWith(suffix)) return owned.strategy;
109
+ }
110
+ }
111
+ // An unlisted file is regenerated. The direction this is allowed to be
112
+ // wrong in: a file nobody declared gets rewritten with the generator's
113
+ // own output, which is recoverable. Defaulting to create-only would make
114
+ // forgetting to declare a file look exactly like #208.
115
+ return "regenerate";
116
+ }
117
+
118
+ export function regenerateOwned(
119
+ filePath: string,
120
+ content: string,
121
+ label: string,
122
+ actions: string[],
123
+ strategy: WriteStrategy = ownedStrategy(label),
124
+ ): void {
125
+ const existing = existsSync(filePath) ? readFileSync(filePath, "utf-8") : null;
126
+ const decision = decideOwnedWrite(strategy, existing, content);
127
+
128
+ if (decision.action === "preserve") {
129
+ actions.push(
130
+ `${SCAFFOLD_REFUSE}: ${label} (${decision.reason}) — generator output withheld; ` +
131
+ `delete the file and re-run to accept it`,
132
+ );
133
+ return;
134
+ }
135
+ if (decision.action === "unchanged") {
136
+ actions.push(`UNCHANGED: ${label} (${decision.reason})`);
137
+ return;
138
+ }
139
+
140
+ const dir = filePath.substring(0, filePath.lastIndexOf("/"));
141
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
142
+ writeFileSync(filePath, decision.content!);
143
+ actions.push(`${decision.action === "create" ? "CREATED" : "CHANGED"}: ${label}`);
144
+ }
145
+
146
+ export function safeDir(dirPath: string, label: string, actions: string[]): void {
147
+ if (existsSync(dirPath)) {
148
+ actions.push(`SKIP: ${label}/ (already exists)`);
149
+ return;
150
+ }
151
+ mkdirSync(dirPath, { recursive: true });
152
+ actions.push(`CREATED: ${label}/`);
153
+ }
154
+
155
+ function loadHarnessConfig(root: string): any {
156
+ const dirConfig = join(root, ".claude", "rungate", "config.json");
157
+ if (existsSync(dirConfig)) {
158
+ try {
159
+ const config = JSON.parse(readFileSync(dirConfig, "utf-8"));
160
+ // The split moved roles out of config.json into roles.json. Callers
161
+ // (buildAgentMeta) still read `.roles` off one object, so re-attach it
162
+ // here — otherwise every project on the directory layout silently falls
163
+ // back to DEFAULT_AGENT_META and its role config is ignored.
164
+ const rolesPath = join(root, ".claude", "rungate", "roles.json");
165
+ if (existsSync(rolesPath)) {
166
+ try {
167
+ const roles = JSON.parse(readFileSync(rolesPath, "utf-8"));
168
+ if (roles && typeof roles === "object" && !Array.isArray(roles)) {
169
+ config.roles = { ...(config.roles || {}), ...roles };
170
+ }
171
+ } catch {}
172
+ }
173
+ return config;
174
+ } catch {}
175
+ }
176
+ const p = join(root, ".claude", "rungate.json");
177
+ if (!existsSync(p)) return null;
178
+ try { return JSON.parse(readFileSync(p, "utf-8")); } catch { return null; }
179
+ }
180
+
181
+ // ── AGENTS.md generation and updates ───────────────────────────
182
+
183
+ export function updateSpecsTable(agentsMdPath: string, actions: string[]): void {
184
+ if (!existsSync(agentsMdPath)) return;
185
+ const specsDir = join(dirname(agentsMdPath), "specs");
186
+ if (!existsSync(specsDir)) return;
187
+
188
+ const specFiles = readdirSync(specsDir).filter(f => f.endsWith(".md") && f !== "SPEC-TEMPLATE.md");
189
+ if (specFiles.length === 0) return;
190
+
191
+ const specRows: string[] = [];
192
+ for (const f of specFiles) {
193
+ const content = readFileSync(join(specsDir, f), "utf-8");
194
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
195
+ let testable = "false";
196
+ let governs = f.replace(/\.md$/, "");
197
+ if (fmMatch) {
198
+ const tMatch = fmMatch[1].match(/testable:\s*(true|false)/);
199
+ if (tMatch) testable = tMatch[1];
200
+ const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
201
+ if (gMatch) governs = gMatch[1].trim();
202
+ }
203
+ specRows.push(`| ${f} | ${governs} | ${testable === "true" ? "yes" : "no"} |`);
204
+ }
205
+
206
+ const existing = readFileSync(agentsMdPath, "utf-8");
207
+ const tablePattern = /(\|[^\n]*Spec[^\n]*\|\n\|[-| ]+\|\n)((?:\|[^\n]+\|\n)*)/;
208
+ const match = existing.match(tablePattern);
209
+ if (match) {
210
+ const newTable = match[1] + specRows.join("\n") + "\n";
211
+ const updated = existing.replace(tablePattern, newTable);
212
+ writeFileSync(agentsMdPath, updated);
213
+ actions.push("UPDATED: AGENTS.md specs table from frontmatter");
214
+ }
215
+ }
216
+
217
+ export function injectEnvironmentSection(root: string, actions: string[]): void {
218
+ const agentsMdPath = join(root, "AGENTS.md");
219
+ if (!existsSync(agentsMdPath)) return;
220
+
221
+ let harness: any;
222
+ const dirConfig = join(root, ".claude", "rungate", "config.json");
223
+ const harnessPath = join(root, ".claude", "rungate.json");
224
+ if (existsSync(dirConfig)) {
225
+ try { harness = JSON.parse(readFileSync(dirConfig, "utf-8")); } catch { return; }
226
+ } else if (existsSync(harnessPath)) {
227
+ try { harness = JSON.parse(readFileSync(harnessPath, "utf-8")); } catch { return; }
228
+ } else {
229
+ return;
230
+ }
231
+
232
+ const lines: string[] = [];
233
+ if (harness.dev) {
234
+ lines.push("**Dev:**");
235
+ if (harness.dev.start) lines.push(`- Start: \`${harness.dev.start}\``);
236
+ if (harness.dev.apiBase) lines.push(`- API: ${harness.dev.apiBase}`);
237
+ if (harness.dev.uiBase) lines.push(`- UI: ${harness.dev.uiBase}`);
238
+ if (harness.dev.testCmd) lines.push(`- Test: \`${harness.dev.testCmd}\``);
239
+ }
240
+ if (harness.prod) {
241
+ const prodLines: string[] = [];
242
+ if (harness.prod.rebuild) prodLines.push(`- Deploy: \`${harness.prod.rebuild}\``);
243
+ if (harness.prod.apiBase) prodLines.push(`- API: ${harness.prod.apiBase}`);
244
+ if (prodLines.length > 0) {
245
+ lines.push("\n**Prod:**");
246
+ lines.push(...prodLines);
247
+ }
248
+ }
249
+ if (lines.length === 0) return;
250
+
251
+ const envSection = `## Environment\n\n${lines.join("\n")}`;
252
+ const existing = readFileSync(agentsMdPath, "utf-8");
253
+
254
+ // Insert before ## Workflow or append before last section
255
+ if (existing.includes("## Workflow")) {
256
+ const updated = existing.replace("## Workflow", `${envSection}\n\n## Workflow`);
257
+ writeFileSync(agentsMdPath, updated);
258
+ } else {
259
+ writeFileSync(agentsMdPath, existing + "\n\n" + envSection + "\n");
260
+ }
261
+ actions.push("UPDATED: AGENTS.md environment section from rungate.json");
262
+ }
263
+
264
+ export function generateAgentsMdContent(projectPath: string, type: ProjectType, actions: string[]): string {
265
+ const pkgPath = join(projectPath, "package.json");
266
+ let pkgDesc = "";
267
+ let pkgName = basename(projectPath);
268
+ if (existsSync(pkgPath)) {
269
+ try {
270
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
271
+ pkgDesc = pkg.description || "";
272
+ pkgName = pkg.name || pkgName;
273
+ } catch {}
274
+ }
275
+
276
+ // Read README.md first paragraph for identity
277
+ let readmeDesc = "";
278
+ const readmePath = join(projectPath, "README.md");
279
+ if (existsSync(readmePath)) {
280
+ try {
281
+ let readme = readFileSync(readmePath, "utf-8");
282
+ while (readme.startsWith("---\n")) {
283
+ const endFm = readme.indexOf("\n---\n", 4);
284
+ if (endFm > 0) { readme = readme.slice(endFm + 5); } else { break; }
285
+ }
286
+ readme = readme.replace(/<!--[\s\S]*?-->/g, "");
287
+ const paragraphs = readme.split(/\n\n+/).filter(p =>
288
+ !p.startsWith("#") && !p.startsWith("---") && !p.startsWith("<") &&
289
+ !/^[\s]*$/.test(p) && p.trim().length > 20
290
+ );
291
+ if (paragraphs.length > 0) readmeDesc = paragraphs[0].replace(/\n/g, " ").trim();
292
+ } catch {}
293
+ }
294
+
295
+ const typeLabel = type === "code" ? "Code" : type === "content" ? "Content" : "Infrastructure";
296
+ const identity = readmeDesc || pkgDesc || `${typeLabel} project. <!-- TODO: Describe what this project is -->`;
297
+
298
+ // Detect tech stack
299
+ const techStack: string[] = [];
300
+ if (existsSync(pkgPath)) {
301
+ try {
302
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
303
+ if (pkg.scripts?.test?.includes("bun") || pkg.scripts?.dev?.includes("bun") || pkg.scripts?.start?.includes("bun")) {
304
+ techStack.push("Bun");
305
+ } else if (pkg.scripts?.test?.includes("node") || pkg.scripts?.dev?.includes("node")) {
306
+ techStack.push("Node.js");
307
+ }
308
+ if (existsSync(join(projectPath, "tsconfig.json")) || pkg.devDependencies?.typescript || pkg.dependencies?.typescript) {
309
+ techStack.push("TypeScript");
310
+ }
311
+ if (pkg.type === "module") {
312
+ techStack.push("ESM");
313
+ }
314
+ } catch {}
315
+ }
316
+
317
+ // Detect git remote
318
+ let repoUrl = "";
319
+ try {
320
+ const result = Bun.spawnSync(["git", "-C", projectPath, "remote", "get-url", "origin"]);
321
+ repoUrl = result.stdout.toString().trim().replace(/\.git$/, "").replace("git@github.com:", "https://github.com/");
322
+ } catch {}
323
+
324
+ // Scan key files
325
+ const keyFiles: Array<{ file: string; what: string; when: string }> = [
326
+ { file: "AGENTS.md", what: "Project entry point", when: "Always first" },
327
+ { 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" },
328
+ { file: "project-state.json", what: "Source of truth for project status", when: "When editing state" },
329
+ ];
330
+ const conditionalPatterns: Array<{ pattern: string; what: string; when: string }> = [
331
+ { pattern: "package.json", what: "Dependencies and scripts", when: "Adding deps or scripts" },
332
+ { pattern: "Makefile", what: "Build/deploy commands", when: "Building or deploying" },
333
+ { pattern: "tsconfig.json", what: "TypeScript configuration", when: "Changing TS settings" },
334
+ { pattern: "Containerfile", what: "Container build definition", when: "Modifying container" },
335
+ { pattern: "Dockerfile", what: "Container build definition", when: "Modifying container" },
336
+ ];
337
+ // Include rungate config reference — check directory first, fall back to monolith
338
+ if (existsSync(join(projectPath, ".claude", "rungate", "config.json"))) {
339
+ keyFiles.push({ file: ".claude/rungate/", what: "Harness project config (directory)", when: "Shipping through harness" });
340
+ } else {
341
+ keyFiles.push({ file: ".claude/rungate.json", what: "Harness project config", when: "Shipping through harness" });
342
+ }
343
+ for (const kf of conditionalPatterns) {
344
+ if (existsSync(join(projectPath, kf.pattern))) {
345
+ keyFiles.push({ file: kf.pattern, what: kf.what, when: kf.when });
346
+ }
347
+ }
348
+ for (const srcDir of ["src", "lib", "gates", "workflows", "hooks"]) {
349
+ if (existsSync(join(projectPath, srcDir))) {
350
+ keyFiles.push({ file: `${srcDir}/`, what: `${srcDir.charAt(0).toUpperCase() + srcDir.slice(1)} directory`, when: `Working on ${srcDir}` });
351
+ }
352
+ }
353
+
354
+ // Scan specs
355
+ const specsDir = join(projectPath, "specs");
356
+ const specEntries: SpecEntry[] = [];
357
+ if (existsSync(specsDir)) {
358
+ const specFiles = readdirSync(specsDir).filter(f => f.endsWith(".md") && f !== "SPEC-TEMPLATE.md");
359
+ for (const f of specFiles) {
360
+ const content = readFileSync(join(specsDir, f), "utf-8");
361
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
362
+ let governs = "";
363
+ let testable = "TODO";
364
+ if (fmMatch) {
365
+ const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
366
+ if (gMatch && gMatch[1].trim() !== "TODO" && gMatch[1].trim().length > 5) {
367
+ governs = gMatch[1].trim().replace(/\|/g, "—").slice(0, 120);
368
+ }
369
+ const tMatch = fmMatch[1].match(/testable:\s*(.+)/);
370
+ if (tMatch) testable = tMatch[1].trim();
371
+ }
372
+ specEntries.push({ file: f, governs, testable });
373
+ }
374
+
375
+ // Also scan specs subdirectories
376
+ try {
377
+ const specSubDirs = readdirSync(specsDir, { withFileTypes: true })
378
+ .filter(d => d.isDirectory())
379
+ .map(d => d.name);
380
+ for (const sub of specSubDirs) {
381
+ const subPath = join(specsDir, sub);
382
+ const subFiles = readdirSync(subPath).filter(f => f.endsWith(".md") && f !== "INDEX.md");
383
+ if (subFiles.length > 0) {
384
+ const indexPath = join(subPath, "INDEX.md");
385
+ let groupGoverns = `${sub} (${subFiles.length} specs)`;
386
+ if (existsSync(indexPath)) {
387
+ const indexContent = readFileSync(indexPath, "utf-8");
388
+ const fmMatch = indexContent.match(/^---\n([\s\S]*?)\n---/);
389
+ if (fmMatch) {
390
+ const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
391
+ if (gMatch && gMatch[1].trim().length > 5) {
392
+ groupGoverns = gMatch[1].trim().replace(/\|/g, "—").slice(0, 120);
393
+ }
394
+ }
395
+ }
396
+ specEntries.push({ file: `${sub}/ (${subFiles.length} specs)`, governs: groupGoverns, testable: "yes" });
397
+ }
398
+ }
399
+ } catch {}
400
+ }
401
+
402
+ // Scan tests
403
+ const testDir = existsSync(join(projectPath, "test")) ? "test" : existsSync(join(projectPath, "tests")) ? "tests" : null;
404
+ const testEntries: TestFile[] = [];
405
+ if (testDir) {
406
+ for (const f of readdirSync(join(projectPath, testDir)).filter(f => f.endsWith(".test.ts"))) {
407
+ const label = f.replace(".test.ts", "").replace(/-/g, " ");
408
+ testEntries.push({ label, file: f });
409
+ }
410
+ }
411
+
412
+ // Detect test command
413
+ let testCmd = "bun test";
414
+ if (existsSync(pkgPath)) {
415
+ try {
416
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
417
+ if (pkg.scripts?.test) testCmd = pkg.scripts.test;
418
+ } catch {}
419
+ }
420
+
421
+ // Scan reference files
422
+ const refDir = join(projectPath, "reference");
423
+ const refEntries: RefFile[] = [];
424
+ if (existsSync(refDir)) {
425
+ for (const f of readdirSync(refDir)) {
426
+ refEntries.push({ file: f, what: "Historical reference" });
427
+ }
428
+ }
429
+
430
+ // Detect workflow info
431
+ let makeTargets = "";
432
+ if (existsSync(join(projectPath, "Makefile"))) {
433
+ try {
434
+ const makefile = readFileSync(join(projectPath, "Makefile"), "utf-8");
435
+ const targets = makefile.match(/^[\w-]+(?=:)/gm)?.filter(t => !t.startsWith(".") && !t.startsWith("_")).slice(0, 8);
436
+ if (targets?.length) makeTargets = `\n- **Key commands:** \`make ${targets.join("`, `make ")}\``;
437
+ } catch {}
438
+ }
439
+
440
+ // Load harness config
441
+ const harness = loadHarnessConfig(projectPath);
442
+
443
+ // Scan docs/ for routing
444
+ const docsDir = join(projectPath, "docs");
445
+ const categories = [
446
+ { dir: "specs", label: "Specs — success criteria, constraints, requirements", frontmatter: "`doc-type: spec`, `testable`, `governs`", notes: "SCs auto-generate tests" },
447
+ { dir: "docs/adr", label: "ADRs — architecture decisions", frontmatter: "`doc-type: adr`, `status`, `created`", notes: "Architecture decisions" },
448
+ { dir: "docs/research", label: "Research — findings, evaluations, competitive analysis", frontmatter: "`doc-type: research`, `governs`", notes: "Tool evaluations, competitive analysis, findings" },
449
+ { dir: "docs/council", label: "Council — synthesis, design debates", frontmatter: "`doc-type: council`", notes: "Council synthesis, design debates" },
450
+ { dir: "docs/guides", label: "Guides — setup, onboarding, reference", frontmatter: "`doc-type: guide`", notes: "Setup, onboarding, reference" },
451
+ { dir: "reference", label: "Reference — historical and inactive docs", frontmatter: "—", notes: "Historical reference" },
452
+ ];
453
+
454
+ const rootDocIntents: Record<string, string> = {
455
+ "ARCHITECTURE.md": "System architecture and design principles",
456
+ "PRINCIPLES.md": "Core engineering principles and standards",
457
+ "CONTRIBUTING.md": "How to contribute — workflow, conventions, review process",
458
+ "MODEL.md": "Domain model and data relationships",
459
+ "PROJECT-STATE.md": "Current project state, priorities, and session history",
460
+ };
461
+
462
+ const docRouting: Array<{ need: string; file: string }> = [];
463
+ // Always include scaffold-generated files for idempotency (SC-364)
464
+ docRouting.push({ need: "Codebase structure (routes, components, modules, health)", file: "CODE-MAP.md" });
465
+ docRouting.push({ need: "Current project state, priorities, and session history", file: "PROJECT-STATE.md" });
466
+ // Conditionally include other root docs
467
+ for (const [f, intent] of Object.entries(rootDocIntents)) {
468
+ if (f !== "PROJECT-STATE.md" && existsSync(join(projectPath, f))) {
469
+ docRouting.push({ need: intent, file: f });
470
+ }
471
+ }
472
+ for (const cat of categories) {
473
+ const catPath = join(projectPath, cat.dir);
474
+ if (existsSync(catPath)) {
475
+ // Recursive — see the same fix in scanner.ts. This is a second copy of
476
+ // scanDocRouting and it is the one the scaffold actually calls, so the
477
+ // scanner fix alone changed no generated output at all (#91).
478
+ const files = readdirSync(catPath, { recursive: true }).map(String).filter(f => f.endsWith(".md"));
479
+ docRouting.push({ need: `${cat.label} (${files.length} files)`, file: `${cat.dir}/` });
480
+ } else {
481
+ docRouting.push({ need: cat.label, file: `${cat.dir}/` });
482
+ actions.push(`WARN: ${cat.dir}/ listed in routing but directory does not exist`);
483
+ }
484
+ }
485
+ if (existsSync(docsDir)) {
486
+ const allDocs = readdirSync(docsDir).filter(f => f.endsWith(".md"));
487
+ for (const f of allDocs) {
488
+ const docPath = join(docsDir, f);
489
+ const content = readFileSync(docPath, "utf-8");
490
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
491
+ let need = f.replace(/\.md$/, "").replace(/-/g, " ");
492
+ if (fmMatch) {
493
+ const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
494
+ if (gMatch && gMatch[1].trim() !== "TODO") need = gMatch[1].trim();
495
+ }
496
+ docRouting.push({ need, file: `docs/${f}` });
497
+ }
498
+ const subDirs = readdirSync(docsDir, { withFileTypes: true })
499
+ .filter(d => d.isDirectory() && !categories.some(c => c.dir === `docs/${d.name}`))
500
+ .map(d => d.name);
501
+ for (const sub of subDirs) {
502
+ const subPath = join(docsDir, sub);
503
+ const subFiles = readdirSync(subPath).filter(f => f.endsWith(".md"));
504
+ if (subFiles.length > 0) {
505
+ docRouting.push({ need: `${sub} (${subFiles.length} files)`, file: `docs/${sub}/` });
506
+ }
507
+ }
508
+ }
509
+ const filteredRouting = docRouting.filter(d => {
510
+ const slug = d.file.replace(/\.md$/, "").replace(/.*\//, "").toLowerCase().replace(/-/g, " ");
511
+ const needLower = d.need.toLowerCase();
512
+ return !needLower.startsWith(slug) || d.need.includes("—") || d.need.includes("(");
513
+ });
514
+
515
+ const consumers = harness?.consumers || [];
516
+
517
+ const scan: ProjectScan = {
518
+ name: pkgName,
519
+ type,
520
+ root: projectPath,
521
+ identity,
522
+ techStack,
523
+ repoUrl,
524
+ testCmd,
525
+ keyFiles,
526
+ specs: specEntries,
527
+ testFiles: testEntries,
528
+ refFiles: refEntries,
529
+ docRouting: filteredRouting as DocRoute[],
530
+ categories: categories as Category[],
531
+ consumers,
532
+ hasCodeMap: true, // Always true for idempotency — scaffold generates CODE-MAP.md (SC-364)
533
+ makeTargets,
534
+ sourceDirs: [],
535
+ promptRouting: {},
536
+ harnessConfig: harness,
537
+ agentMeta: {},
538
+ dirs: [],
539
+ deps: 0,
540
+ devDeps: 0,
541
+ modules: [],
542
+ routes: [],
543
+ harnessTemplatesDir: "",
544
+ promptPrefix: "",
545
+ };
546
+
547
+ // Write scoped rules to .claude/rules/ — but only the ones the harness is
548
+ // still the author of. This loop used to be an unconditional writeFileSync,
549
+ // which truncated .claude/rules/checks-must-be-able-to-fail.md from 262
550
+ // lines to 65 and reported GENERATED (#370). See lib/rule-provenance.ts for
551
+ // why neither "never overwrite" nor "always overwrite" is the answer.
552
+ const rulesDir = join(projectPath, ".claude", "rules");
553
+ if (!existsSync(rulesDir)) mkdirSync(rulesDir, { recursive: true });
554
+ const scopedRules = generateScopedRules(scan);
555
+ for (const rule of scopedRules) {
556
+ const rulePath = join(rulesDir, rule.filename);
557
+ const existing = existsSync(rulePath) ? readFileSync(rulePath, "utf-8") : null;
558
+ const decision = decideRuleWrite(existing, rule.content);
559
+ if (decision.action === "preserve") {
560
+ // Reported, never resolved. A divergence the run silently fixed is the
561
+ // defect; a divergence named in the report is a decision for a human.
562
+ actions.push(
563
+ `PRESERVED: .claude/rules/${rule.filename} (${decision.reason}) — ` +
564
+ `generator output withheld; delete the file and re-run to accept it`,
565
+ );
566
+ continue;
567
+ }
568
+ writeFileSync(rulePath, decision.content!);
569
+ actions.push(
570
+ `${decision.action === "create" ? "GENERATED" : "UPDATED"}: .claude/rules/${rule.filename}`,
571
+ );
572
+ }
573
+
574
+ return buildAgentsMdContent(scan);
575
+ }
576
+
577
+ /**
578
+ * Rewrite `.claude/rules/` from a scan of the tree the run actually left (#123).
579
+ *
580
+ * The first pass happens in Phase 0.5, before `generateOrAuditProjectHarness`
581
+ * creates `.claude/rungate/` and before `copySpecTemplateIfEmpty` creates
582
+ * `specs/`. So a freshly scaffolded project shipped rules describing a tree that
583
+ * no longer existed:
584
+ *
585
+ * docs-routing.md "Specs — ... (0 files)" in a project with a spec
586
+ * key-files.md `.claude/rungate.json` the LEGACY monolith path, in a
587
+ * project using the directory layout
588
+ *
589
+ * The second one is the damaging one: it sends every agent in a new project to a
590
+ * config file that is not there, and key-files.md is the table agents are told
591
+ * to read first.
592
+ *
593
+ * Re-running the generator is safe and cheap: `generateAgentsMdContent` writes
594
+ * only the rules, and returns AGENTS.md content for its caller to write. The
595
+ * return value is discarded here on purpose — AGENTS.md has already been
596
+ * through `updateSpecsTable` and `injectEnvironmentSection` by this point, and
597
+ * rewriting it would undo both.
598
+ */
599
+ export function refreshScopedRulesStep(root: string, type: ProjectType, actions: string[]): void {
600
+ const sink: string[] = [];
601
+ generateAgentsMdContent(root, type, sink);
602
+ // Forward everything except the per-rule lines already reported by the
603
+ // Phase 0.5 pass. Swallowing the rest would hide a warning raised only on
604
+ // the second scan — the fail-open shape .claude/rules/checks-must-be-able-to-fail.md
605
+ // exists to prevent. PRESERVED is in the list because both passes reach the
606
+ // same decision over the same file, so the second is a duplicate and not a
607
+ // new finding; dropping the whole prefix is what keeps it that way.
608
+ for (const a of sink) {
609
+ if (!/^(GENERATED|UPDATED|PRESERVED): \.claude\/rules\//.test(a)) actions.push(a);
610
+ }
611
+ actions.push(`REFRESHED: .claude/rules/ (rescanned after harness config and specs/ existed)`);
612
+ }
613
+
614
+ export function refreshAgentsMd(root: string, type: ProjectType, actions: string[]): void {
615
+ const agentsPath = join(root, "AGENTS.md");
616
+ const content = readFileSync(agentsPath, "utf-8");
617
+ const issues: string[] = [];
618
+
619
+ // Check all file references resolve.
620
+ //
621
+ // `referencedPaths` rather than an inline backtick pattern (#380). The old
622
+ // one treated any backtick span ending in a known extension as a path, so
623
+ // the Commands table's `bun test test/scaffold-conformity.test.ts` was
624
+ // handed to existsSync whole. Three reports on this repo, three false
625
+ // positives, zero true positives.
626
+ const refs = referencedPaths(content);
627
+ for (const ref of refs) {
628
+ if (!existsSync(join(root, ref))) {
629
+ issues.push(`BROKEN: ${ref} (referenced in AGENTS.md but doesn't exist)`);
630
+ }
631
+ }
632
+
633
+ // Check staleness. The SAME predicate: this scan had its own copy of the
634
+ // pattern, and two scans with two ideas of what a reference is means the
635
+ // second silently stops covering spans the first rejects, with nothing
636
+ // able to notice because they never compare answers.
637
+ const staleFiles: string[] = [];
638
+ for (const ref of refs) {
639
+ if (!ref.endsWith(".md")) continue;
640
+ if (!existsSync(join(root, ref))) continue;
641
+ try {
642
+ const result = Bun.spawnSync(["git", "-C", root, "log", "-1", "--format=%ci", "--", ref], { timeout: 5_000 });
643
+ const dateStr = result.stdout.toString().trim().split(" ")[0];
644
+ if (dateStr) {
645
+ const daysSince = (Date.now() - new Date(dateStr).getTime()) / (1000 * 60 * 60 * 24);
646
+ const isAdr = ref.includes('docs/adr/') || /ADR/i.test(ref);
647
+ if (isAdr) continue;
648
+ const threshold = ref.startsWith('specs/') ? 90 : 180;
649
+ if (daysSince > threshold) staleFiles.push(`${ref} (${Math.floor(daysSince)}d old)`);
650
+ }
651
+ } catch (e: unknown) { console.warn('Staleness check failed for', ref, (e as Error).message); }
652
+ }
653
+
654
+ // Check specs table
655
+ const specsDir = join(root, "specs");
656
+ if (existsSync(specsDir)) {
657
+ const actualSpecs = readdirSync(specsDir).filter(f => f.endsWith(".md"));
658
+ const unlisted = actualSpecs.filter(f => !content.includes(f));
659
+ if (unlisted.length > 0) {
660
+ issues.push(`UNLISTED specs: ${unlisted.join(", ")} (in specs/ but not in AGENTS.md)`);
661
+ }
662
+ }
663
+
664
+ // Check CODE-MAP.md reference
665
+ if (existsSync(join(root, "CODE-MAP.md")) && !content.includes("CODE-MAP")) {
666
+ issues.push("CODE-MAP.md exists but not referenced in AGENTS.md routing table");
667
+ }
668
+
669
+ if (issues.length > 0 || staleFiles.length > 0) {
670
+ console.log("\n AGENTS.md audit:");
671
+ for (const issue of issues) console.log(` ⚠ ${issue}`);
672
+ if (staleFiles.length > 0) {
673
+ console.log(` ⚠ STALE (>90 days): ${staleFiles.join(", ")}`);
674
+ }
675
+ actions.push(`AUDITED: AGENTS.md (${issues.length} broken refs, ${staleFiles.length} stale docs)`);
676
+ } else {
677
+ actions.push("AUDITED: AGENTS.md (all references valid, no stale docs)");
678
+ }
679
+ }
680
+
681
+ // ── Conformity test generation ─────────────────────────────────
682
+
683
+ /**
684
+ * The conformity suite every scaffolded project runs.
685
+ *
686
+ * Two things here were only ever wrong because nothing regenerated this file
687
+ * (#208), and both are fixed in the same change that makes it regenerate:
688
+ *
689
+ * 1. Every call passed a `findings` array. No entry point has ever taken one
690
+ * — findings accumulate in a module-level collector that
691
+ * `writeFindingsReport(root)` reads. The extra argument typechecked
692
+ * nowhere and did nothing anywhere; it survived because the only tree that
693
+ * typechecks this file is rungate's, and rungate's copy was the
694
+ * hand-adapted one the skip preserved.
695
+ * 2. `runDirectoryValidation` was missing. rungate's hand-adapted copy ran
696
+ * it; the template did not. Regenerating without it would have deleted a
697
+ * live check — the same silent-coverage-loss this issue is about, just
698
+ * pointed the other way.
699
+ */
700
+ export function generateConformityTest(root?: string): string {
701
+ // A package cannot import itself by name without an `exports` map, and
702
+ // adding one to make a generated string uniform would be the tail wagging
703
+ // the dog.
704
+ //
705
+ // `isHarnessItself` rather than a second predicate of my own. #208 shipped
706
+ // one — identical in intent and in implementation to this, which already
707
+ // existed and which SC-811 names by name. Two deciders of the same fact
708
+ // survive any mutation of either, which is the defect #208 was about.
709
+ const from = root && isHarnessItself(root) ? "../lib/conformity" : "rungate/lib/conformity";
710
+ return `import { resolve } from "path";
711
+ import { afterAll } from "bun:test";
712
+ import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runDirectoryValidation, runPackageValidation, runTsconfigValidation, runConfigAccessValidation, runPromptConfigAccessValidation, writeFindingsReport } from "${from}";
713
+
714
+ const ROOT = resolve(import.meta.dir, "..");
715
+
716
+ runScaffoldConformity(ROOT);
717
+ runSpecDiscovery(ROOT);
718
+ runSpecDrift(ROOT);
719
+ runDocHygiene(ROOT);
720
+ runFallowCheck(ROOT);
721
+ runAgentFileValidation(ROOT);
722
+ runDirectoryValidation(ROOT);
723
+ runPackageValidation(ROOT);
724
+ runTsconfigValidation(ROOT);
725
+ runConfigAccessValidation(ROOT);
726
+ runPromptConfigAccessValidation(ROOT);
727
+
728
+ afterAll(() => writeFindingsReport(ROOT));
729
+ `;
730
+ }
731
+
732
+ // ── Agent briefs generation ────────────────────────────────────
733
+
734
+ export function generateAgentBriefsStep(root: string, actions: string[]): void {
735
+ const agentsDir = join(root, ".claude", "agents");
736
+ safeDir(agentsDir, ".claude/agents", actions);
737
+
738
+ // This copy had no try/catch, so an unreadable package.json threw here and
739
+ // killed the scaffold run, while the other three sites answering the same
740
+ // question shrugged and said "consumer" (#380).
741
+ const promptPrefix = isHarnessItself(root) ? "prompts" : "node_modules/rungate/prompts";
742
+
743
+ const harness = loadHarnessConfig(root);
744
+
745
+ let projectIdentity = "";
746
+ const agentsMdPath = join(root, "AGENTS.md");
747
+ if (existsSync(agentsMdPath)) {
748
+ const content = readFileSync(agentsMdPath, "utf-8");
749
+ const identityMatch = content.match(/## Project Identity\n\n([\s\S]*?)(?=\n##|\n\|)/);
750
+ if (identityMatch) projectIdentity = identityMatch[1].trim();
751
+ }
752
+ if (!projectIdentity) {
753
+ const readmePath = join(root, "README.md");
754
+ if (existsSync(readmePath)) {
755
+ const readme = readFileSync(readmePath, "utf-8");
756
+ const paragraphs = readme.split(/\n\n+/).filter(p => !p.startsWith("#") && p.trim().length > 20);
757
+ if (paragraphs.length > 0) projectIdentity = paragraphs[0].replace(/\n/g, " ").trim();
758
+ }
759
+ }
760
+
761
+ // Prompt routing
762
+ const promptsDir = join(root, "prompts");
763
+ const defaultKeywords: Record<string, string[]> = {
764
+ marcus: ["coding", "code", "standard", "implementation", "engineering", "convention", "principle"],
765
+ quinn: ["testing", "test", "qa", "quality", "coverage"],
766
+ rook: ["security", "auth", "secret", "vulnerability", "access"],
767
+ serena: ["architecture", "design-pattern", "system", "module", "structure"],
768
+ aditi: ["design", "ui", "ux", "component", "visual", "accessibility"],
769
+ discovery: ["discovery", "ac-format", "evidence", "scope", "sizing"],
770
+ };
771
+ const agentKeywords: Record<string, string[]> = { ...defaultKeywords, ...harness?.promptKeywords };
772
+ const promptsByAgent: Record<string, Array<{ file: string; when: string }>> = {
773
+ marcus: [], quinn: [], rook: [], serena: [], aditi: [], discovery: []
774
+ };
775
+ if (existsSync(promptsDir)) {
776
+ const promptFiles = readdirSync(promptsDir).filter(f => f.endsWith(".md"));
777
+ for (const f of promptFiles) {
778
+ const content = readFileSync(join(promptsDir, f), "utf-8");
779
+ const lower = f.toLowerCase();
780
+
781
+ let whenToRead = f.replace(/\.md$/, "").replace(/-/g, " ");
782
+ const headingMatch = content.match(/^#\s+(.+)$/m);
783
+ const descMatch = content.match(/^description:\s*(.+)$/m);
784
+ if (descMatch) {
785
+ whenToRead = descMatch[1].trim();
786
+ } else if (headingMatch) {
787
+ whenToRead = headingMatch[1].trim();
788
+ }
789
+
790
+ const stem = lower.replace(/\.md$/, "");
791
+ const segments = stem.split(/[-_]/);
792
+ for (const [agent, keywords] of Object.entries(agentKeywords)) {
793
+ const matches = stem === agent || keywords.some(kw =>
794
+ kw.includes("-") ? stem.includes(kw) : segments.includes(kw)
795
+ );
796
+ if (matches) {
797
+ promptsByAgent[agent].push({ file: `prompts/${f}`, when: whenToRead });
798
+ }
799
+ }
800
+ }
801
+ }
802
+
803
+ const srcDirs = ["src", "dashboard/src", "lib", "gates", "hooks"].filter(d => existsSync(join(root, d)));
804
+ const consumers = harness?.consumers || [];
805
+
806
+ // Resolve templates directory relative to this module
807
+ const harnessTemplatesDir = join(dirname(dirname(__dirname)), "templates", "agent-briefs");
808
+
809
+ // buildAgentMeta takes the whole harness config and reads .roles itself.
810
+ // Passing harness?.roles made it look for roles.roles, so every consumer's
811
+ // role config was silently dropped and DEFAULT_AGENT_META always won.
812
+ const configMeta = buildAgentMeta(harness ?? null);
813
+ const agentMeta: Record<string, any> = {};
814
+ for (const name of Object.keys({ ...DEFAULT_AGENT_META, ...configMeta })) {
815
+ agentMeta[name] = { ...DEFAULT_AGENT_META[name], ...configMeta[name] };
816
+ }
817
+
818
+ // Detect project type for accurate briefs. A DIFFERENT question from
819
+ // "is this the harness" — it also admits any project keyworded `harness` —
820
+ // so it keeps its own branch and borrows only the identity half (#380).
821
+ const pkgPath = join(root, "package.json");
822
+ let detectedType: ProjectType = "code";
823
+ if (existsSync(pkgPath)) {
824
+ try {
825
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
826
+ if (isHarnessItself(root) || pkg.keywords?.includes("harness")) detectedType = "infra";
827
+ } catch {}
828
+ } else if (!existsSync(join(root, "src")) && !existsSync(join(root, "lib"))) {
829
+ detectedType = "infra";
830
+ }
831
+
832
+ const briefScan: ProjectScan = {
833
+ name: basename(root),
834
+ type: detectedType,
835
+ root,
836
+ identity: projectIdentity,
837
+ techStack: [],
838
+ repoUrl: "",
839
+ testCmd: harness?.dev?.testCmd || "bun test",
840
+ keyFiles: [],
841
+ specs: [],
842
+ testFiles: [],
843
+ refFiles: [],
844
+ docRouting: [],
845
+ categories: [],
846
+ consumers,
847
+ hasCodeMap: false,
848
+ makeTargets: "",
849
+ sourceDirs: srcDirs,
850
+ promptRouting: promptsByAgent,
851
+ harnessConfig: harness,
852
+ agentMeta,
853
+ dirs: [],
854
+ deps: 0,
855
+ devDeps: 0,
856
+ modules: [],
857
+ routes: [],
858
+ harnessTemplatesDir,
859
+ promptPrefix,
860
+ };
861
+
862
+ const briefs = buildAgentBriefsContent(briefScan);
863
+
864
+ for (const [agentName, content] of Object.entries(briefs)) {
865
+ const p = join(agentsDir, `${agentName}.md`);
866
+ writeFileSync(p, content);
867
+ actions.push(existsSync(p) ? `UPDATED: .claude/agents/${agentName}.md` : `CREATED: .claude/agents/${agentName}.md`);
868
+ }
869
+ }
870
+
871
+ // ── Harness config generation/audit ────────────────────────────
872
+
873
+ export function generateOrAuditProjectHarness(root: string, actions: string[]): void {
874
+ const harnessPath = join(root, ".claude", "rungate.json");
875
+
876
+ const detectedHealthPath = detectHealthPath(root);
877
+
878
+ // Scan pages from route files
879
+ const scannedPages: Record<string, string> = {};
880
+ const routeFiles = ["src/App.tsx", "src/routes.tsx", "src/index.tsx", "src/app.tsx"]
881
+ .map(f => join(root, f))
882
+ .filter(f => existsSync(f));
883
+ for (const routeFile of routeFiles) {
884
+ const content = readFileSync(routeFile, "utf-8");
885
+ const routePattern = /path="([^"]+)"/g;
886
+ let m;
887
+ while ((m = routePattern.exec(content)) !== null) {
888
+ const path = m[1];
889
+ if (path === "*" || path.includes(":")) continue;
890
+ const label = path.split("/").pop() || "home";
891
+ scannedPages[path] = label;
892
+ }
893
+ }
894
+
895
+ // Scan pages from dashboard/src/pages/*.tsx (file-based routing)
896
+ const dashboardPagesDir = join(root, "dashboard", "src", "pages");
897
+ if (existsSync(dashboardPagesDir)) {
898
+ const pageFiles = readdirSync(dashboardPagesDir).filter(f => f.endsWith(".tsx") || f.endsWith(".jsx"));
899
+ for (const f of pageFiles) {
900
+ const componentName = f.replace(/\.(tsx|jsx)$/, "");
901
+ // Convert CamelCase to kebab-case route path
902
+ const routePath = "/" + componentName
903
+ .replace(/([a-z])([A-Z])/g, "$1-$2")
904
+ .toLowerCase();
905
+ scannedPages[routePath] = componentName;
906
+ }
907
+ }
908
+
909
+ // Scan test commands
910
+ const pkgPath = join(root, "package.json");
911
+ let testCmd = "bun test";
912
+ if (existsSync(pkgPath)) {
913
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
914
+ if (pkg.scripts?.test) testCmd = pkg.scripts.test;
915
+ }
916
+ // #87 — this defaulted to `bunx tsc --noEmit` for every project, including
917
+ // one with no tsconfig, and `gates/gate-executor.ts` RUNS what lands here.
918
+ // Without a tsconfig that command prints 147 lines of help and exits 1, so
919
+ // the verify gate reported "Type check FAIL" at every consumer that the
920
+ // three other sites had already agreed should not be type-checked at all.
921
+ // `null` is the honest value and the gate already skips on a falsy one.
922
+ const typeCheckCmd = typecheckDecision(root).command;
923
+
924
+ // Scan port from Makefile, docker-compose.yml, or .env.example
925
+ const makefile = join(root, "Makefile");
926
+
927
+ /**
928
+ * #343 — does the Makefile actually declare this target?
929
+ *
930
+ * The `dev.start` and `prod.rebuild` defaults tested only that a Makefile
931
+ * EXISTED, then wrote `make dev-all` / `make rebuild` into the consumer's
932
+ * config. Those are one consumer's target names. A project with a Makefile
933
+ * and no `rebuild` target got a `prod.rebuild` that cannot run, and the
934
+ * failure surfaces at rebuild time as "No rule to make target" rather than
935
+ * as a scaffold that guessed.
936
+ *
937
+ * `scripts/scaffold-rungate-config.ts:66` already did it this way; this
938
+ * brings the two into line rather than inventing a third behaviour.
939
+ */
940
+ const makeTarget = (name: string): boolean => {
941
+ if (!existsSync(makefile)) return false;
942
+ try {
943
+ return new RegExp(`^${name}\\s*:`, "m").test(readFileSync(makefile, "utf-8"));
944
+ } catch {
945
+ return false;
946
+ }
947
+ };
948
+ const detectedPort = (() => {
949
+ if (existsSync(makefile)) {
950
+ const content = readFileSync(makefile, "utf-8");
951
+ const portMatch = content.match(/(?:--port\s+|PORT=|-p\s+|:)(\d{4,5})/);
952
+ if (portMatch) return parseInt(portMatch[1]);
953
+ }
954
+ // Scan docker-compose.yml for port mappings
955
+ const dockerComposePaths = ["docker-compose.yml", "docker-compose.yaml"]
956
+ .map(f => join(root, f));
957
+ for (const dcPath of dockerComposePaths) {
958
+ if (existsSync(dcPath)) {
959
+ const content = readFileSync(dcPath, "utf-8");
960
+ // Match port mappings like "3001:3001" or "- 8080:8080"
961
+ const portMatch = content.match(/["']?(\d{4,5}):\d{4,5}["']?/);
962
+ if (portMatch) return parseInt(portMatch[1]);
963
+ }
964
+ }
965
+ const envExample = join(root, ".env.example");
966
+ if (existsSync(envExample)) {
967
+ const content = readFileSync(envExample, "utf-8");
968
+ const portMatch = content.match(/^PORT=(\d{4,5})/m);
969
+ if (portMatch) return parseInt(portMatch[1]);
970
+ }
971
+ return null;
972
+ })();
973
+
974
+ // Scan envVars
975
+ const envVars = (() => {
976
+ const envPath = join(root, ".env.example");
977
+ if (!existsSync(envPath)) return null;
978
+ const content = readFileSync(envPath, "utf-8");
979
+ return content.split("\n")
980
+ .filter(line => line.trim() && !line.startsWith("#"))
981
+ .map(line => line.split("=")[0].trim())
982
+ .filter(Boolean);
983
+ })();
984
+
985
+ // Detect git remote
986
+ let repo = "";
987
+ try {
988
+ const result = Bun.spawnSync(["git", "-C", root, "remote", "get-url", "origin"], { timeout: 5_000 });
989
+ repo = result.stdout.toString().trim()
990
+ .replace(/\.git$/, "")
991
+ .replace("git@github.com:", "")
992
+ .replace("https://github.com/", "");
993
+ } catch {}
994
+
995
+ // Scan consumers
996
+ const scannedConsumers: string[] = [];
997
+ const srcDir = join(root, "src");
998
+ if (existsSync(srcDir)) {
999
+ const consumerPatterns = ["-routes.ts", "-generator.ts", "-plan.ts", "-intel.ts"];
1000
+ for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts"))) {
1001
+ const content = readFileSync(join(srcDir, f), "utf-8");
1002
+ const isConsumer = consumerPatterns.some(p => f.includes(p)) ||
1003
+ content.includes("app.get(") || content.includes("app.post(") ||
1004
+ content.includes("router.") || content.includes("export default");
1005
+ if (isConsumer) {
1006
+ scannedConsumers.push(f.replace(/\.ts$/, "").replace(/-routes|-generator/, ""));
1007
+ }
1008
+ }
1009
+ }
1010
+
1011
+ const rungateDir = join(root, ".claude", "rungate");
1012
+ const hasDirectory = existsSync(join(rungateDir, "config.json"));
1013
+
1014
+ if (hasDirectory) {
1015
+ // Directory structure already exists — audit it, and repair the two
1016
+ // files #75 only ever fixed for greenfield projects (#121).
1017
+ const existing = JSON.parse(readFileSync(join(rungateDir, "config.json"), "utf-8"));
1018
+ repairEmptySidecars(rungateDir, actions);
1019
+ auditExistingConfig(existing, scannedPages, scannedConsumers, actions, rungateDir);
1020
+ } else if (existsSync(harnessPath)) {
1021
+ // Monolith exists — split into directory structure
1022
+ const existing = JSON.parse(readFileSync(harnessPath, "utf-8"));
1023
+
1024
+ // Check if monolith has roles/hooks/compliance to split
1025
+ if (existing.roles || existing.hooks || existing.compliance) {
1026
+ splitMonolithToDirectory(root, existing, actions);
1027
+ } else {
1028
+ // Simple monolith without split-worthy content — audit only
1029
+ auditExistingConfig(existing, scannedPages, scannedConsumers, actions);
1030
+ }
1031
+ } else {
1032
+ // No config exists — create directory structure
1033
+ let harnessVersion = "unknown";
1034
+ try {
1035
+ const harnessPkg = JSON.parse(readFileSync(join(dirname(dirname(__dirname)), "package.json"), "utf-8"));
1036
+ harnessVersion = harnessPkg.version || "unknown";
1037
+ } catch {}
1038
+
1039
+ // Prefer package.json name, fall back to directory basename
1040
+ let projectName = basename(root);
1041
+ if (existsSync(pkgPath)) {
1042
+ try {
1043
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
1044
+ if (pkg.name) projectName = pkg.name;
1045
+ } catch {}
1046
+ }
1047
+
1048
+ const config = {
1049
+ "$schema": "rungate",
1050
+ harnessVersion,
1051
+ scaffoldedAt: new Date().toISOString(),
1052
+ project: projectName,
1053
+ repo,
1054
+ issueRepo: repo,
1055
+ dev: {
1056
+ start: makeTarget("dev-all") ? "make dev-all" : "bun run dev",
1057
+ apiBase: detectedPort ? `http://localhost:${detectedPort}` : null,
1058
+ // Detected, never defaulted (#346).
1059
+ //
1060
+ // #346 suggested scaffolding a conventional value so the UNMEASURED
1061
+ // population shrinks. A plain default would re-create #304's bug
1062
+ // through a different door: `DevSchema.healthPath` says in so many
1063
+ // words "No default. A probe that guesses a path reports DOWN for a
1064
+ // server that is up", and a guess the scaffold writes into the
1065
+ // consumer's config is still a guess — it is just one the harness can
1066
+ // point at the consumer afterwards.
1067
+ //
1068
+ // So the route is looked for, and `null` when it is not found. That
1069
+ // keeps UNMEASURED meaning what it should: this project has no health
1070
+ // endpoint we could locate, rather than this probe did not try.
1071
+ healthPath: detectedHealthPath,
1072
+ uiBase: null as string | null,
1073
+ testCmd,
1074
+ typeCheck: typeCheckCmd,
1075
+ },
1076
+ prod: {
1077
+ rebuild: makeTarget("rebuild") ? "make rebuild" : undefined,
1078
+ apiBase: null as string | null,
1079
+ },
1080
+ pages: scannedPages,
1081
+ consumers: [...new Set(scannedConsumers)].sort(),
1082
+ envVars: envVars || [],
1083
+ ci: {
1084
+ runner: "ubuntu-latest",
1085
+ bunVersion: "latest",
1086
+ branches: ["main"],
1087
+ },
1088
+ contextDocs: {},
1089
+ test: {
1090
+ command: testCmd,
1091
+ timeout: 300000,
1092
+ },
1093
+ };
1094
+
1095
+ // Greenfield gets the DEFAULT roles and hooks, not `{}` and `[]`. An empty
1096
+ // roles.json reads as a configured project with nothing to dispatch (#70).
1097
+ // The split path below is deliberately NOT routed through these defaults.
1098
+ const roles = buildDefaultRoles();
1099
+ const hooks = buildDefaultHooks();
1100
+ writeDirectoryStructure(root, config, roles, hooks, undefined, actions);
1101
+ actions.push(
1102
+ `CREATED: .claude/rungate/ (${Object.keys(scannedPages).length} pages, ${scannedConsumers.length} consumers, ` +
1103
+ `${Object.keys(roles).length} roles, ${hooks.length} hooks)`
1104
+ );
1105
+ }
1106
+ }
1107
+
1108
+ /**
1109
+ * The two config files that are useless when empty, and what fills them.
1110
+ *
1111
+ * ONE table, read by both the repair and the audit, so they cannot disagree
1112
+ * about what "empty" means. Two deciders here would let the audit call a
1113
+ * project aligned that the repair had just declined to touch.
1114
+ */
1115
+ const SIDECARS = [
1116
+ { file: "roles.json", empty: "{}", fill: () => buildDefaultRoles() },
1117
+ { file: "hooks.json", empty: "[]", fill: () => buildDefaultHooks() },
1118
+ ] as const;
1119
+
1120
+ export type SidecarState = "missing" | "empty" | "unreadable" | "populated";
1121
+
1122
+ /**
1123
+ * What state one sidecar is in. FOUR answers, not two.
1124
+ *
1125
+ * The first draft returned a boolean, and the boolean hid a case: an
1126
+ * unreadable `roles.json` is neither empty nor populated. Repair must not
1127
+ * touch it — overwriting a file we failed to parse is how a repair destroys
1128
+ * work, and #370 and #208 already settled that for every other owned file —
1129
+ * but the audit must not call it aligned either. A boolean forced those two
1130
+ * needs onto one answer, and whichever way it fell, one of them was wrong.
1131
+ *
1132
+ * `{}` and `[]` are `empty`: the states #70 produced and #75 stopped
1133
+ * producing. They parse, they are valid, and they mean "a configured
1134
+ * project with nothing to dispatch".
1135
+ */
1136
+ export function sidecarState(dir: string, file: string): SidecarState {
1137
+ const p = join(dir, file);
1138
+ if (!existsSync(p)) return "missing";
1139
+ let parsed: unknown;
1140
+ try {
1141
+ parsed = JSON.parse(readFileSync(p, "utf-8"));
1142
+ } catch {
1143
+ return "unreadable";
1144
+ }
1145
+ if (Array.isArray(parsed)) return parsed.length === 0 ? "empty" : "populated";
1146
+ if (parsed !== null && typeof parsed === "object") {
1147
+ return Object.keys(parsed).length === 0 ? "empty" : "populated";
1148
+ }
1149
+ // A number, a string, `null` — parses, but is not a config.
1150
+ return "unreadable";
1151
+ }
1152
+
1153
+ /**
1154
+ * Fill an empty `roles.json` / `hooks.json` from the greenfield defaults.
1155
+ *
1156
+ * #121. #75 fixed the greenfield branch; a project scaffolded before it has
1157
+ * `config.json`, so every re-scaffold takes the audit branch and the empty
1158
+ * files were never touched. There was no path that repaired them.
1159
+ *
1160
+ * **A populated file is left alone, byte for byte.** Repair that overwrites
1161
+ * is not repair, and "some roles appeared" is satisfied by a `--fix` that
1162
+ * rewrites the whole directory — the opposite failure and the worse one,
1163
+ * because the overwritten file is gone and the skipped one is still there.
1164
+ */
1165
+ function repairEmptySidecars(rungateDir: string, actions: string[]): void {
1166
+ for (const { file, fill } of SIDECARS) {
1167
+ const state = sidecarState(rungateDir, file);
1168
+ if (state === "populated") continue;
1169
+ if (state === "unreadable") {
1170
+ // Reported, never resolved. A run that quietly declined to write is
1171
+ // indistinguishable from one that had nothing to do (#208, SC-819).
1172
+ actions.push(
1173
+ `PRESERVED: .claude/rungate/${file} (unreadable — not overwritten; ` +
1174
+ `fix the JSON or delete the file and re-run to reseed it)`,
1175
+ );
1176
+ continue;
1177
+ }
1178
+ const content = fill();
1179
+ writeFileSync(join(rungateDir, file), JSON.stringify(content, null, 2) + "\n");
1180
+ const n = Array.isArray(content) ? content.length : Object.keys(content).length;
1181
+ actions.push(`REPAIRED: .claude/rungate/${file} (was ${state} — seeded ${n} from defaults)`);
1182
+ }
1183
+ }
1184
+
1185
+ function auditExistingConfig(
1186
+ existing: any,
1187
+ scannedPages: Record<string, string>,
1188
+ scannedConsumers: string[],
1189
+ actions: string[],
1190
+ rungateDir?: string
1191
+ ): void {
1192
+ const issues: string[] = [];
1193
+
1194
+ // #121. The audit used to not even be PASSED the directory, so it could
1195
+ // not have read these if it wanted to — and it said "aligned with code"
1196
+ // over zero roles and zero hooks. A check that passes because of what it
1197
+ // never looked at, asserting health rather than staying silent.
1198
+ //
1199
+ // This runs AFTER `repairEmptySidecars`, so reaching it means the repair
1200
+ // declined: the file was unparseable, or not writable. Either way the
1201
+ // project is not aligned and the run must say so.
1202
+ if (rungateDir) {
1203
+ for (const { file } of SIDECARS) {
1204
+ const state = sidecarState(rungateDir, file);
1205
+ if (state !== "populated") {
1206
+ issues.push(`CONFIG: .claude/rungate/${file} is ${state} — nothing to dispatch`);
1207
+ }
1208
+ }
1209
+ }
1210
+
1211
+ const declaredPages = Object.keys(existing.pages || {});
1212
+ const scannedPaths = Object.keys(scannedPages);
1213
+ const missingPages = scannedPaths.filter(p => !declaredPages.some(d => existing.pages[d] === p || d === p));
1214
+ if (missingPages.length > 0) {
1215
+ issues.push(`PAGES: ${missingPages.length} routes in code not in rungate.json: ${missingPages.slice(0, 5).join(", ")}`);
1216
+ }
1217
+
1218
+ // Audit consumers: flag declared consumers not found in source code as stale
1219
+ const declaredConsumers = existing.consumers || [];
1220
+ if (declaredConsumers.length > 0) {
1221
+ const staleConsumers = declaredConsumers.filter((c: string) => !scannedConsumers.includes(c));
1222
+ if (staleConsumers.length > 0) {
1223
+ issues.push(`CONSUMERS: ${staleConsumers.length} stale consumers in rungate.json not found in source: ${staleConsumers.slice(0, 5).join(", ")}`);
1224
+ }
1225
+ }
1226
+
1227
+ if (issues.length > 0) {
1228
+ console.log("\n rungate.json audit:");
1229
+ for (const issue of issues) console.log(` ⚠ ${issue}`);
1230
+ // Every gap goes into the actions, not just its count (#121). The
1231
+ // detail used to reach `console.log` alone — so the returned report
1232
+ // said `1 gaps` and nothing about WHICH, and anything reading actions
1233
+ // rather than stdout could not tell one gap from another. CONSUMERS
1234
+ // was the single exception, pushed by hand; it is now the rule.
1235
+ for (const issue of issues) actions.push(`AUDIT: ${issue}`);
1236
+ actions.push(`AUDITED: rungate.json (${issues.length} gaps)`);
1237
+ } else {
1238
+ actions.push("AUDITED: rungate.json (aligned with code)");
1239
+ }
1240
+ }
1241
+
1242
+ function splitMonolithToDirectory(
1243
+ root: string,
1244
+ monolith: any,
1245
+ actions: string[]
1246
+ ): void {
1247
+ // Extract split-worthy fields
1248
+ const { roles, hooks, compliance, ...configFields } = monolith;
1249
+
1250
+ writeDirectoryStructure(
1251
+ root,
1252
+ configFields,
1253
+ roles || {},
1254
+ hooks || [],
1255
+ compliance,
1256
+ actions
1257
+ );
1258
+ actions.push(`SPLIT: .claude/rungate.json → .claude/rungate/ (config.json, roles.json, hooks.json, compliance.json)`);
1259
+ }
1260
+
1261
+ function writeDirectoryStructure(
1262
+ root: string,
1263
+ config: any,
1264
+ roles: any,
1265
+ hooks: any[],
1266
+ compliance: any | undefined,
1267
+ actions: string[]
1268
+ ): void {
1269
+ const rungateDir = join(root, ".claude", "rungate");
1270
+ if (!existsSync(rungateDir)) mkdirSync(rungateDir, { recursive: true });
1271
+
1272
+ writeFileSync(join(rungateDir, "config.json"), JSON.stringify(config, null, 2) + "\n");
1273
+ writeFileSync(join(rungateDir, "roles.json"), JSON.stringify(roles, null, 2) + "\n");
1274
+ writeFileSync(join(rungateDir, "hooks.json"), JSON.stringify(hooks, null, 2) + "\n");
1275
+
1276
+ const defaultCompliance = compliance || {
1277
+ rules: {},
1278
+ defaults: { consecutiveFailThreshold: 3, tierPromotionThreshold: 5 },
1279
+ organize: { fileTypes: [".md"], artifactClassification: {}, externalSources: [] },
1280
+ };
1281
+ writeFileSync(join(rungateDir, "compliance.json"), JSON.stringify(defaultCompliance, null, 2) + "\n");
1282
+ }
1283
+
1284
+ // ── Code map generation ────────────────────────────────────────
1285
+
1286
+ /**
1287
+ * Generate CODE-MAP.md. Must run LAST in the scaffold (#123).
1288
+ *
1289
+ * This used to be invoked in Phase 1, before `generateAgentBriefsStep` wrote
1290
+ * `.claude/agents/`, before `copySpecTemplateIfEmpty` wrote `specs/`, and
1291
+ * before `addPaiHarnessDevDep` added a devDependency — so a fresh project's
1292
+ * CODE-MAP.md described a tree that stopped existing moments later in the same
1293
+ * run, reporting `specs/ 0 files` and no agents directory in a project with
1294
+ * both.
1295
+ *
1296
+ * The lag was permanent rather than one-run-behind, because of the staleness
1297
+ * skip below: while the file is under 14 days old it is not regenerated at all,
1298
+ * so no later scaffold ever corrected it. Running this step last is what makes
1299
+ * that skip safe — the content it preserves is now right from run 1.
1300
+ */
1301
+ export function generateCodeMapStep(root: string, actions: string[], opts?: { fix?: boolean; dryRun?: boolean }): void {
1302
+ const fixMode = opts?.fix ?? !opts?.dryRun;
1303
+ const codeMapPath = join(root, "CODE-MAP.md");
1304
+
1305
+ // In dry-run/non-fix mode, only report gaps
1306
+ if (!fixMode) {
1307
+ if (!existsSync(codeMapPath)) {
1308
+ actions.push("GAP: CODE-MAP.md missing — run with --fix to generate");
1309
+ }
1310
+ return;
1311
+ }
1312
+
1313
+ // Check staleness
1314
+ if (existsSync(codeMapPath)) {
1315
+ const content = readFileSync(codeMapPath, "utf-8");
1316
+ const updatedMatch = content.match(/^updated:\s*(\d{4}-\d{2}-\d{2})/m);
1317
+ if (updatedMatch) {
1318
+ const lastScan = new Date(updatedMatch[1]);
1319
+ const daysSince = (Date.now() - lastScan.getTime()) / (1000 * 60 * 60 * 24);
1320
+ if (daysSince < 14) {
1321
+ const gitResult = Bun.spawnSync(
1322
+ ["git", "-C", root, "rev-list", "--count", `--since=${updatedMatch[1]}`, "HEAD"],
1323
+ { timeout: 5_000 }
1324
+ );
1325
+ const commits = parseInt(gitResult.stdout.toString().trim()) || 0;
1326
+ if (commits < 50) {
1327
+ actions.push(`SKIP: CODE-MAP.md (${daysSince.toFixed(0)}d old, ${commits} commits — still fresh)`);
1328
+ return;
1329
+ }
1330
+ }
1331
+ }
1332
+ }
1333
+
1334
+ // Run generate-code-map.ts if available
1335
+ const scriptPath = join(dirname(dirname(__dirname)), "scripts", "generate-code-map.ts");
1336
+ if (existsSync(scriptPath)) {
1337
+ const result = Bun.spawnSync(["bun", scriptPath, root], { timeout: 60_000 });
1338
+ if (result.exitCode === 0) {
1339
+ actions.push(existsSync(codeMapPath) ? "UPDATED: CODE-MAP.md" : "CREATED: CODE-MAP.md");
1340
+ } else {
1341
+ actions.push("WARN: CODE-MAP.md generation failed via script — trying inline");
1342
+ generateCodeMapInline(root, codeMapPath, actions);
1343
+ }
1344
+ } else {
1345
+ generateCodeMapInline(root, codeMapPath, actions);
1346
+ }
1347
+ }
1348
+
1349
+ function generateCodeMapInline(root: string, outPath: string, actions: string[]): void {
1350
+ const name = basename(root);
1351
+ const skip = new Set(["node_modules", ".git", "reference", "dist", "build", ".next", ".fallow"]);
1352
+ const dirs: Array<{ name: string; fileCount: number; types: string[] }> = [];
1353
+ for (const entry of readdirSync(root)) {
1354
+ if (entry.startsWith(".") && entry !== ".claude") continue;
1355
+ if (skip.has(entry)) continue;
1356
+ const full = join(root, entry);
1357
+ try {
1358
+ if (!statSync(full).isDirectory()) continue;
1359
+ const files = readdirSync(full, { recursive: true }).map(String);
1360
+ const exts = new Set(files.map(f => f.split(".").pop()).filter((e): e is string => Boolean(e)));
1361
+ dirs.push({ name: entry, fileCount: files.length, types: [...exts].slice(0, 5) });
1362
+ } catch {}
1363
+ }
1364
+ dirs.sort((a, b) => b.fileCount - a.fileCount);
1365
+
1366
+ let deps = 0, devDeps = 0;
1367
+ const pkgPath = join(root, "package.json");
1368
+ if (existsSync(pkgPath)) {
1369
+ try {
1370
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
1371
+ deps = Object.keys(pkg.dependencies || {}).length;
1372
+ devDeps = Object.keys(pkg.devDependencies || {}).length;
1373
+ } catch {}
1374
+ }
1375
+
1376
+ const srcDir = join(root, "src");
1377
+ const modules: Array<{ file: string; exports: string[] }> = [];
1378
+ if (existsSync(srcDir)) {
1379
+ for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts") || f.endsWith(".js"))) {
1380
+ const content = readFileSync(join(srcDir, f), "utf-8");
1381
+ const exports: string[] = [];
1382
+ const exportPattern = /export\s+(?:function|const|class|type|interface)\s+(\w+)/g;
1383
+ let m;
1384
+ while ((m = exportPattern.exec(content)) !== null) exports.push(m[1]);
1385
+ if (exports.length > 0) modules.push({ file: `src/${f}`, exports });
1386
+ }
1387
+ }
1388
+
1389
+ // Detect API routes
1390
+ const routes: Array<{ method: string; path: string; file: string }> = [];
1391
+ if (existsSync(srcDir)) {
1392
+ for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts") || f.endsWith(".js"))) {
1393
+ const content = readFileSync(join(srcDir, f), "utf-8");
1394
+ const routePatterns = [
1395
+ /app\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/gi,
1396
+ /router\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/gi,
1397
+ /["'`]((?:GET|POST|PUT|DELETE|PATCH)\s+\/[^"'`]+)["'`]/g,
1398
+ ];
1399
+ for (const pattern of routePatterns) {
1400
+ let rm;
1401
+ while ((rm = pattern.exec(content)) !== null) {
1402
+ if (rm[2]) routes.push({ method: rm[1].toUpperCase(), path: rm[2], file: `src/${f}` });
1403
+ else if (rm[1]) {
1404
+ const parts = rm[1].split(/\s+/);
1405
+ if (parts.length === 2) routes.push({ method: parts[0], path: parts[1], file: `src/${f}` });
1406
+ }
1407
+ }
1408
+ }
1409
+ }
1410
+ }
1411
+
1412
+ const mapScan: ProjectScan = {
1413
+ name,
1414
+ type: "code",
1415
+ root,
1416
+ identity: "",
1417
+ techStack: [],
1418
+ repoUrl: "",
1419
+ testCmd: "",
1420
+ keyFiles: [],
1421
+ specs: [],
1422
+ testFiles: [],
1423
+ refFiles: [],
1424
+ docRouting: [],
1425
+ categories: [],
1426
+ consumers: [],
1427
+ hasCodeMap: false,
1428
+ makeTargets: "",
1429
+ sourceDirs: [],
1430
+ promptRouting: {},
1431
+ harnessConfig: null,
1432
+ agentMeta: {},
1433
+ dirs,
1434
+ deps,
1435
+ devDeps,
1436
+ modules,
1437
+ routes,
1438
+ harnessTemplatesDir: "",
1439
+ promptPrefix: "",
1440
+ };
1441
+
1442
+ const md = buildCodeMapContent(mapScan);
1443
+ writeFileSync(outPath, md);
1444
+ actions.push("CREATED: CODE-MAP.md (inline)");
1445
+ }
1446
+
1447
+ // ── Misc scaffold steps ────────────────────────────────────────
1448
+
1449
+ export function copySpecTemplateIfEmpty(specsDir: string, actions: string[]): void {
1450
+ if (!existsSync(specsDir)) return;
1451
+
1452
+ // Skip if specs/ already has .md files (besides SPEC-TEMPLATE.md itself)
1453
+ const existingSpecs = readdirSync(specsDir).filter(
1454
+ f => f.endsWith(".md") && f !== "SPEC-TEMPLATE.md"
1455
+ );
1456
+ if (existingSpecs.length > 0) {
1457
+ actions.push("SKIP: spec template (specs/ already has .md files)");
1458
+ return;
1459
+ }
1460
+
1461
+ const templatePath = join(dirname(dirname(__dirname)), "specs", "SPEC-TEMPLATE.md");
1462
+ if (!existsSync(templatePath)) {
1463
+ actions.push("SKIP: spec template (SPEC-TEMPLATE.md not found in harness)");
1464
+ return;
1465
+ }
1466
+
1467
+ const template = readFileSync(templatePath, "utf-8");
1468
+ writeFileSync(join(specsDir, "SPEC-TEMPLATE.md"), template);
1469
+ actions.push("CREATED: specs/SPEC-TEMPLATE.md (starter template)");
1470
+ }
1471
+
1472
+ // ── tsconfig.json ──────────────────────────────────────────────
1473
+
1474
+ // `TS_SOURCE_DIRS`, `containsTypeScript` and the directory filter all moved to
1475
+ // lib/typescript-project.ts in #87. Five sites decided "is this a TypeScript
1476
+ // project" and they disagreed; two copies of a predicate survive any mutation
1477
+ // of either, which is what SC-842 and SC-843 already say about this file.
1478
+
1479
+ /**
1480
+ * Write a tsconfig.json for a TypeScript consumer that has none (#72, #65/#76).
1481
+ *
1482
+ * AGENTS.md has documented `bunx tsc --noEmit` as THE type check for every
1483
+ * scaffolded project since the scaffold existed, and `.github/workflows/ci.yml`
1484
+ * ran it — over a file rungate never created. With no tsconfig.json tsc prints
1485
+ * 147 lines of help text and exits 1, so the documented check had never checked
1486
+ * anything anywhere. `lib/generators/agents-md.ts` and `createCiWorkflows` were
1487
+ * taught to stop ADVERTISING the command without a tsconfig; this creates the
1488
+ * file so the command can be advertised again and mean something.
1489
+ *
1490
+ * Must run before AGENTS.md is generated and before createCiWorkflows: both
1491
+ * decide whether to emit the type check by looking for this file on disk.
1492
+ *
1493
+ * Never overwrites. A consumer's compiler settings are the consumer's, and
1494
+ * re-scaffold is routine.
1495
+ */
1496
+ export function createTsconfig(root: string, actions: string[]): void {
1497
+ const tsconfigPath = join(root, "tsconfig.json");
1498
+ if (existsSync(tsconfigPath)) {
1499
+ actions.push("SKIP: tsconfig.json (already exists)");
1500
+ return;
1501
+ }
1502
+
1503
+ // The include list, the "is this a TypeScript project" test and TSC-1's
1504
+ // applicability are the same question, answered once in
1505
+ // lib/typescript-project.ts. Deriving them separately is how you get a
1506
+ // tsconfig whose include matches no files — tsc error TS18003, which reads
1507
+ // as a broken type check rather than as "nothing to check" — and how TSC-1
1508
+ // came to hard-fail over a file this function had deliberately not written
1509
+ // (#87).
1510
+ const include = typeScriptSourceDirs(root).map(dir => `${dir}/**/*.ts`);
1511
+
1512
+ if (include.length === 0) {
1513
+ actions.push(`SKIP: tsconfig.json (no TypeScript source in ${TS_SOURCE_DIRS.join("/, ")}/)`);
1514
+ return;
1515
+ }
1516
+
1517
+ const tsconfig = {
1518
+ "//": "Created by rungate. Edit freely — re-scaffold never overwrites an existing tsconfig.json.",
1519
+ compilerOptions: {
1520
+ strict: true,
1521
+ target: "ESNext",
1522
+ module: "ESNext",
1523
+ moduleResolution: "bundler",
1524
+ noEmit: true,
1525
+ skipLibCheck: true,
1526
+ resolveJsonModule: true,
1527
+ },
1528
+ include,
1529
+ exclude: ["node_modules"],
1530
+ };
1531
+
1532
+ writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2) + "\n");
1533
+ actions.push("CREATED: tsconfig.json");
1534
+ }
1535
+
1536
+ export function createGitignore(root: string, actions: string[]): void {
1537
+ const gitignorePath = join(root, ".gitignore");
1538
+ const securityTemplate = `# Dependencies
1539
+ node_modules/
1540
+ .bun/
1541
+
1542
+ # Build output
1543
+ dist/
1544
+ build/
1545
+ *.tsbuildinfo
1546
+
1547
+ # Environment and secrets
1548
+ .env
1549
+ .env.*
1550
+ !.env.example
1551
+ *.pem
1552
+ *.key
1553
+ *.p12
1554
+ *.pfx
1555
+ credentials.json
1556
+ service-account*
1557
+ .secret*
1558
+
1559
+ # Harness working directory
1560
+ .rungate/
1561
+
1562
+ # IDE
1563
+ .vscode/
1564
+ .idea/
1565
+ *.swp
1566
+ *.swo
1567
+
1568
+ # OS
1569
+ .DS_Store
1570
+ Thumbs.db
1571
+
1572
+ # Test artifacts
1573
+ coverage/
1574
+ `;
1575
+
1576
+ if (existsSync(gitignorePath)) {
1577
+ const existing = readFileSync(gitignorePath, "utf-8");
1578
+ const required = [
1579
+ "node_modules", "dist", ".env", ".rungate",
1580
+ "*.pem", "*.key", "credentials.json", "service-account",
1581
+ ];
1582
+ const missing = required.filter(entry => !existing.includes(entry));
1583
+ if (missing.length > 0) {
1584
+ const additions = "\n# Added by rungate scaffold\n" +
1585
+ missing.map(e => {
1586
+ if (e === ".env") return ".env\n.env.*\n!.env.example";
1587
+ return e.includes("*") ? e : `${e}/`;
1588
+ }).join("\n") + "\n";
1589
+ writeFileSync(gitignorePath, existing.trimEnd() + "\n" + additions);
1590
+ actions.push(`UPDATED: .gitignore (added ${missing.length} missing entries)`);
1591
+ } else {
1592
+ actions.push("SKIP: .gitignore (all required entries present)");
1593
+ }
1594
+ } else {
1595
+ writeFileSync(gitignorePath, securityTemplate);
1596
+ actions.push("CREATED: .gitignore (security template)");
1597
+ }
1598
+ }
1599
+
1600
+ export function generateProjectState(root: string, actions: string[]): void {
1601
+ const specsDir = join(root, "specs");
1602
+ if (!existsSync(specsDir)) {
1603
+ actions.push("SKIP: PROJECT-STATE.md (no specs directory)");
1604
+ return;
1605
+ }
1606
+
1607
+ const today = new Date().toISOString().split("T")[0];
1608
+
1609
+ interface SC { id: string; what: string; done: boolean; }
1610
+ const scs: SC[] = [];
1611
+
1612
+ for (const file of new Bun.Glob("**/*.md").scanSync({ cwd: specsDir, absolute: true })) {
1613
+ if (file.endsWith("SPEC-TEMPLATE.md")) continue;
1614
+ const content = readFileSync(file, "utf-8");
1615
+ for (const line of content.split("\n")) {
1616
+ const doneMatch = line.match(/^- \[x\] (SC-\d+):\s*(.+)/i);
1617
+ if (doneMatch) {
1618
+ scs.push({ id: doneMatch[1].toUpperCase(), what: doneMatch[2].trim(), done: true });
1619
+ continue;
1620
+ }
1621
+ const openMatch = line.match(/^- \[ \] (SC-\d+):\s*(.+)/i);
1622
+ if (openMatch) {
1623
+ scs.push({ id: openMatch[1].toUpperCase(), what: openMatch[2].trim(), done: false });
1624
+ }
1625
+ }
1626
+ }
1627
+
1628
+ if (scs.length === 0) {
1629
+ actions.push("SKIP: PROJECT-STATE.md (no SCs found in specs)");
1630
+ return;
1631
+ }
1632
+
1633
+ scs.sort((a, b) => {
1634
+ const aNum = parseInt(a.id.replace("SC-", ""));
1635
+ const bNum = parseInt(b.id.replace("SC-", ""));
1636
+ return aNum - bNum;
1637
+ });
1638
+
1639
+ const state = {
1640
+ updated: today,
1641
+ priorities: ["Review and update priorities in project-state.json"],
1642
+ notes: `${scs.length} SCs discovered from specs. Organize into phases as project evolves.`,
1643
+ phases: [{ name: "Initial Implementation", scs }],
1644
+ sessions: []
1645
+ };
1646
+
1647
+ const openCount = scs.filter(sc => !sc.done).length;
1648
+ const currentLabel = openCount > 0
1649
+ ? `Initial Implementation — ${openCount} SCs open`
1650
+ : "All SCs complete";
1651
+
1652
+ const lines: string[] = [];
1653
+ lines.push("# Project State");
1654
+ lines.push("");
1655
+ lines.push(`**Current phase: ${currentLabel}**`);
1656
+ lines.push("");
1657
+ lines.push(state.notes);
1658
+ lines.push("");
1659
+
1660
+ if (state.priorities.length > 0) {
1661
+ lines.push("**Next priorities:**");
1662
+ state.priorities.forEach((p, i) => lines.push(`${i + 1}. ${p}`));
1663
+ lines.push("");
1664
+ }
1665
+
1666
+ lines.push(`## ${openCount === 0 ? "✅" : openCount < scs.length ? "🔄" : "⬜"} Initial Implementation (${openCount === 0 ? "COMPLETE" : openCount < scs.length ? "IN PROGRESS" : "NOT STARTED"})`);
1667
+ lines.push("");
1668
+ if (scs.length > 0) {
1669
+ lines.push("| Status | SC | What |");
1670
+ lines.push("|---|---|---|");
1671
+ for (const sc of scs) {
1672
+ lines.push(`| ${sc.done ? "✅" : "⬜"} | ${sc.id} | ${sc.what} |`);
1673
+ }
1674
+ lines.push("");
1675
+ }
1676
+
1677
+ const stateJson = join(root, "project-state.json");
1678
+ const stateMd = join(root, "PROJECT-STATE.md");
1679
+
1680
+ safeWrite(stateJson, JSON.stringify(state, null, 2) + "\n", "project-state.json", actions);
1681
+ safeWrite(stateMd, lines.join("\n") + "\n", "PROJECT-STATE.md", actions);
1682
+ }
1683
+
1684
+ export function createClaudeMdBridge(root: string, actions: string[]): void {
1685
+ const claudeMdPath = join(root, "CLAUDE.md");
1686
+ const bridgeLine = "@AGENTS.md";
1687
+
1688
+ if (existsSync(claudeMdPath)) {
1689
+ const existing = readFileSync(claudeMdPath, "utf-8");
1690
+ if (!existing.includes(bridgeLine)) {
1691
+ writeFileSync(claudeMdPath, existing.trimEnd() + "\n\n" + bridgeLine + "\n");
1692
+ actions.push("UPDATED: CLAUDE.md (added @AGENTS.md bridge)");
1693
+ } else {
1694
+ actions.push("SKIP: CLAUDE.md (@AGENTS.md bridge already present)");
1695
+ }
1696
+ } else {
1697
+ const content = `# Project Rules\n\n${bridgeLine}\n`;
1698
+ writeFileSync(claudeMdPath, content);
1699
+ actions.push("CREATED: CLAUDE.md (with @AGENTS.md bridge)");
1700
+ }
1701
+ }
1702
+
1703
+ // ── Managed writes that cannot destroy a consumer's content (#216) ─────────
1704
+ //
1705
+ // Re-scaffolding is the documented way to BOTH onboard and update a consumer,
1706
+ // and `createCiWorkflows` ended in two unconditional `writeFileSync` calls.
1707
+ // The first real consumer that added a deploy job to `.github/workflows/ci.yml`
1708
+ // would have lost it the moment they took an update — and the harness cannot
1709
+ // generate a deploy job, so nothing could have put it back. That is SUCCESS.md
1710
+ // claim 5 (the harness works on a repo that is not this one) failing in the
1711
+ // most expensive way available.
1712
+ //
1713
+ // The design is one binding, `resolveManagedWrite`, that turns the BEFORE and
1714
+ // AFTER content into the bytes to write, the verb to report, and — when the
1715
+ // write would destroy something — a refusal. Detection is semantic (a YAML
1716
+ // parse) and preservation is textual (a verbatim line slice). Where the two
1717
+ // disagree the write is refused rather than guessed at, because a guess here
1718
+ // deletes someone's pipeline.
1719
+
1720
+ export interface ManagedWrite {
1721
+ /** The bytes to write: generated content plus every job the harness did not author. */
1722
+ content: string;
1723
+ /** Derived from the measured before/after, never assumed by the caller. */
1724
+ verb: "CREATED" | "UPDATED" | "REPLACED" | "SKIP";
1725
+ /** after − before, in lines. Negative means content was removed. */
1726
+ lineDelta: number;
1727
+ /** Jobs carried forward from the existing file. */
1728
+ preservedJobs: string[];
1729
+ /** Jobs that could not be carried forward. Non-empty ⇒ refusal. */
1730
+ droppedJobs: string[];
1731
+ /**
1732
+ * Lines inside a harness-owned job that the regeneration overwrote.
1733
+ *
1734
+ * Not a refusal: a file whose banner says "do not edit" is the harness's to
1735
+ * rewrite, and refusing on any edit to it would make every update refuse.
1736
+ * It IS reported, because the whole of #216 is that a consumer reading the
1737
+ * log had no signal anything of theirs had gone. DailyBriefDashboard had
1738
+ * added `bun install --no-optional` inside the harness's own gates job for
1739
+ * CI resilience, and "REPLACED (+33 lines)" does not tell anyone that.
1740
+ */
1741
+ overwrittenLines: string[];
1742
+ /** Non-null ⇒ the write must not happen. Names the dropped jobs and the line delta. */
1743
+ refusal: string | null;
1744
+ }
1745
+
1746
+ const lineCount = (s: string): number => (s === "" ? 0 : s.split("\n").length);
1747
+ const signed = (n: number): string => `${n >= 0 ? "+" : ""}${n}`;
1748
+
1749
+ /**
1750
+ * Top-level job names, or null when the source cannot be read as a workflow.
1751
+ *
1752
+ * Null is handled as a refusal by every caller, never as "no jobs" — a parse
1753
+ * failure that defaults to an empty list is the fail-open this whole mechanism
1754
+ * exists to avoid (.claude/rules/checks-must-be-able-to-fail.md).
1755
+ */
1756
+ function workflowJobNames(src: string): string[] | null {
1757
+ let doc: unknown;
1758
+ try {
1759
+ doc = Bun.YAML.parse(src);
1760
+ } catch {
1761
+ return null;
1762
+ }
1763
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) return null;
1764
+ const jobs = (doc as Record<string, unknown>).jobs;
1765
+ if (!jobs || typeof jobs !== "object" || Array.isArray(jobs)) return null;
1766
+ return Object.keys(jobs as Record<string, unknown>);
1767
+ }
1768
+
1769
+ /**
1770
+ * Verbatim text of each job block, keyed by job name.
1771
+ *
1772
+ * Deliberately narrower than the parser: it only understands a top-level
1773
+ * `jobs:` key followed by indented `name:` blocks, which is the form every
1774
+ * generator and every hand-written workflow in practice uses. A job the
1775
+ * parser can see and this cannot is reported as dropped, which refuses the
1776
+ * write — the narrowness fails closed.
1777
+ */
1778
+ function sliceJobBlocks(src: string): Map<string, string> {
1779
+ const lines = src.split("\n");
1780
+ const out = new Map<string, string>();
1781
+
1782
+ let i = lines.findIndex(l => /^jobs:\s*$/.test(l));
1783
+ if (i < 0) return out;
1784
+ i++;
1785
+
1786
+ let childIndent = -1;
1787
+ while (i < lines.length) {
1788
+ const line = lines[i];
1789
+ if (line.trim() === "") { i++; continue; }
1790
+ const indent = line.length - line.trimStart().length;
1791
+ if (indent === 0) break; // left the jobs block
1792
+ if (childIndent < 0) childIndent = indent;
1793
+ const m = indent === childIndent ? /^\s*([A-Za-z0-9_.\-]+):\s*$/.exec(line) : null;
1794
+ if (!m) { i++; continue; }
1795
+
1796
+ const start = i;
1797
+ i++;
1798
+ while (i < lines.length) {
1799
+ const l = lines[i];
1800
+ if (l.trim() === "") { i++; continue; }
1801
+ if (l.length - l.trimStart().length <= childIndent) break;
1802
+ i++;
1803
+ }
1804
+ let end = i;
1805
+ while (end > start + 1 && lines[end - 1].trim() === "") end--;
1806
+ out.set(m[1], lines.slice(start, end).join("\n"));
1807
+ }
1808
+ return out;
1809
+ }
1810
+
1811
+ /** True when any non-blank line of `before` is absent from `after`. */
1812
+ function removesContent(before: string, after: string): boolean {
1813
+ const kept = new Set(after.split("\n").map(l => l.trim()).filter(Boolean));
1814
+ return before.split("\n").map(l => l.trim()).filter(Boolean).some(l => !kept.has(l));
1815
+ }
1816
+
1817
+ /**
1818
+ * The one place a scaffold action verb comes from: a comparison of the bytes
1819
+ * that were there with the bytes going out. Nothing passes a verb in, so no
1820
+ * write that removes content can be reported as a CREATED.
1821
+ */
1822
+ function measureWrite(existing: string | null, next: string): { verb: ManagedWrite["verb"]; lineDelta: number } {
1823
+ if (existing === null) return { verb: "CREATED", lineDelta: lineCount(next) };
1824
+ if (next === existing) return { verb: "SKIP", lineDelta: 0 };
1825
+ return {
1826
+ verb: removesContent(existing, next) ? "REPLACED" : "UPDATED",
1827
+ lineDelta: lineCount(next) - lineCount(existing),
1828
+ };
1829
+ }
1830
+
1831
+ /**
1832
+ * The single site that decides what a managed write does.
1833
+ *
1834
+ * Short-circuiting this to `return { content: generated, ... }` is an
1835
+ * unconditional overwrite — which is exactly the mutation
1836
+ * test/scaffold-ci-preservation-mutation.test.ts performs, so that
1837
+ * "preservation works" is a claim with a demonstrated way of being false.
1838
+ */
1839
+ export function resolveManagedWrite(existing: string | null, generated: string): ManagedWrite {
1840
+ const base: ManagedWrite = {
1841
+ content: generated, verb: "CREATED", lineDelta: lineCount(generated),
1842
+ preservedJobs: [], droppedJobs: [], overwrittenLines: [], refusal: null,
1843
+ };
1844
+ if (existing === null) return base;
1845
+
1846
+ const before = lineCount(existing);
1847
+ const unchanged = { ...base, content: existing, verb: "SKIP" as const, lineDelta: 0 };
1848
+
1849
+ const generatedJobs = workflowJobNames(generated);
1850
+ if (generatedJobs === null) {
1851
+ return { ...unchanged, refusal: `the generated workflow could not be parsed, so nothing can be compared against it (line delta ${signed(lineCount(generated) - before)})` };
1852
+ }
1853
+
1854
+ const existingJobs = workflowJobNames(existing);
1855
+ if (existingJobs === null) {
1856
+ return { ...unchanged, refusal: `the existing file could not be read as a workflow, so its jobs cannot be carried forward (line delta ${signed(lineCount(generated) - before)})` };
1857
+ }
1858
+
1859
+ // One merge, and it understands the whole file rather than only its jobs.
1860
+ //
1861
+ // The previous form appended consumer-only JOB blocks and computed its loss
1862
+ // set as a list of job NAMES, so content outside a job could not enter it and
1863
+ // therefore could not make a write refuse. Measured against a throwaway
1864
+ // worktree of DailyBriefDashboard at e8ef2823: every job survived and
1865
+ // `concurrency`, `cancel-in-progress`, `paths-ignore`, the top-level
1866
+ // `workflow_dispatch` trigger and the consumer's header comments were all
1867
+ // destroyed, reported as `REPLACED (+0 lines, preserved ...)` with 0 refused.
1868
+ // A refusal that is structurally incapable of firing on the thing being
1869
+ // destroyed is the defect class .claude/rules/checks-must-be-able-to-fail.md
1870
+ // exists for, and it was in the fix written to prevent a data-loss bug.
1871
+ const content = mergeManagedWorkflow(existing, generated);
1872
+ const lineDelta = lineCount(content) - before;
1873
+
1874
+ const preservedJobs = existingJobs.filter(j => !generatedJobs.includes(j));
1875
+
1876
+ // Verify rather than assume: re-read the bytes about to be written. A merge
1877
+ // that produced unparseable YAML must refuse like any other destructive
1878
+ // write, because the consumer cannot run a file that will not parse.
1879
+ const resultJobs = workflowJobNames(content);
1880
+ if (resultJobs === null) {
1881
+ return {
1882
+ ...unchanged, preservedJobs: [], droppedJobs: existingJobs, overwrittenLines: [], lineDelta,
1883
+ refusal: `the merged workflow does not parse, so it cannot be written (line delta ${signed(lineDelta)})`,
1884
+ };
1885
+ }
1886
+
1887
+ // The loss set is LINES, not job names. Every non-blank line the consumer
1888
+ // has that the merge did not carry is content the harness is about to drop,
1889
+ // wherever in the file it sits.
1890
+ //
1891
+ // Minus the lines the harness is entitled to rewrite, which is the same
1892
+ // ownership rule the merge states: the jobs the generator emits are the
1893
+ // harness's. Without that subtraction the harness's own stale output reads
1894
+ // as consumer content, and a regenerated `bun-version` would refuse its own
1895
+ // update — preservation by declining to write, which freezes the managed
1896
+ // half while passing every preservation assertion.
1897
+ const blocks = sliceJobBlocks(existing);
1898
+ const harnessOwned = new Set<string>();
1899
+ for (const name of generatedJobs) {
1900
+ const block = blocks.get(name);
1901
+ if (block !== undefined) for (const l of nonBlankLines(block)) harnessOwned.add(l);
1902
+ }
1903
+ // The harness's own banner is the harness's to reword. Without this, the
1904
+ // first run after the banner's text changed refused to update a file the
1905
+ // harness had written itself, naming its own previous sentence as consumer
1906
+ // content it declined to drop — a refusal is only useful if it is about
1907
+ // somebody else's work.
1908
+ for (const l of nonBlankLines(existing)) {
1909
+ if (l.startsWith(MANAGED_BANNER_PREFIX)) harnessOwned.add(l);
1910
+ }
1911
+
1912
+ const kept = new Set(nonBlankLines(content));
1913
+ const gone = nonBlankLines(existing).filter(l => !kept.has(l));
1914
+ const lostLines = gone.filter(l => !harnessOwned.has(l));
1915
+ const overwrittenLines = gone.filter(l => harnessOwned.has(l) && !l.startsWith(MANAGED_BANNER_PREFIX));
1916
+ const droppedJobs = existingJobs.filter(j => !resultJobs.includes(j));
1917
+
1918
+ if (lostLines.length > 0) {
1919
+ const where = droppedJobs.length > 0
1920
+ ? `job(s) ${droppedJobs.join(", ")}`
1921
+ : "content outside any job";
1922
+ return {
1923
+ ...unchanged, preservedJobs, droppedJobs, overwrittenLines: [], lineDelta,
1924
+ refusal:
1925
+ `${lostLines.length} line(s) the harness did not author would be dropped from ${where}` +
1926
+ `: ${lostLines.slice(0, 3).map(l => JSON.stringify(l)).join(", ")}` +
1927
+ `${lostLines.length > 3 ? ` and ${lostLines.length - 3} more` : ""}` +
1928
+ ` (line delta ${signed(lineDelta)})`,
1929
+ };
1930
+ }
1931
+
1932
+ return { content, ...measureWrite(existing, content), preservedJobs, droppedJobs: [], overwrittenLines, refusal: null };
1933
+ }
1934
+
1935
+ /** Non-blank lines, trimmed — the unit the loss set is counted in. */
1936
+ function nonBlankLines(text: string): string[] {
1937
+ return text.split("\n").map(l => l.trim()).filter(l => l !== "");
1938
+ }
1939
+
1940
+ /**
1941
+ * Opening of the banner every generated workflow carries.
1942
+ *
1943
+ * Deliberately the stable prefix and not the whole sentence: the rest of it
1944
+ * names the config path, and that is exactly the part that changed and caused
1945
+ * the harness to refuse to update its own file.
1946
+ */
1947
+ const MANAGED_BANNER_PREFIX = "# Managed by rungate";
1948
+
1949
+ /**
1950
+ * Write a harness-managed file, preserving whatever the harness did not author.
1951
+ *
1952
+ * Throws on refusal. Callers decide whether a refusal aborts the run or is
1953
+ * recorded and reported; what they may not do is write anyway.
1954
+ */
1955
+ export function writeManagedFile(
1956
+ filePath: string,
1957
+ generated: string,
1958
+ label: string,
1959
+ actions: string[],
1960
+ opts: { force?: boolean } = {},
1961
+ ): void {
1962
+ const existing = existsSync(filePath) ? readFileSync(filePath, "utf-8") : null;
1963
+ const resolved = resolveManagedWrite(existing, generated);
1964
+
1965
+ if (opts.force) {
1966
+ // The escape hatch, and it still reports a measured verb: --force changes
1967
+ // what is ALLOWED, not what gets claimed about it. The dropped jobs are
1968
+ // still named, because an operator who overrides the refusal should be
1969
+ // told in the report exactly what they overrode.
1970
+ const { verb, lineDelta } = measureWrite(existing, generated);
1971
+ if (verb === "SKIP") { actions.push(`SKIP: ${label} (unchanged)`); return; }
1972
+ const dropped = resolved.droppedJobs.length > 0 ? `, dropped ${resolved.droppedJobs.join(", ")}` : "";
1973
+ mkdirSync(dirname(filePath), { recursive: true });
1974
+ writeFileSync(filePath, generated);
1975
+ actions.push(`${verb}: ${label} (--force, ${signed(lineDelta)} lines${dropped})`);
1976
+ return;
1977
+ }
1978
+
1979
+ if (resolved.refusal) {
1980
+ throw new Error(`${label}: ${resolved.refusal}. Re-run the scaffold with --force to overwrite it anyway.`);
1981
+ }
1982
+
1983
+ // Named even on the no-op path: "unchanged" and "unchanged because three of
1984
+ // your jobs were carried back in" are different facts, and only the second
1985
+ // one tells a consumer the preservation is actually running.
1986
+ const kept = resolved.preservedJobs.length > 0 ? `, preserved ${resolved.preservedJobs.join(", ")}` : "";
1987
+
1988
+ // The other half of the same honesty. A regeneration that overwrote an edit
1989
+ // a consumer made inside a harness-owned job is allowed, and it is the thing
1990
+ // they most need told: #216 is a log that said CREATED while 470 lines went.
1991
+ const over = resolved.overwrittenLines;
1992
+ const overwrote = over.length === 0
1993
+ ? ""
1994
+ : `, overwrote ${over.length} edited line(s) in harness-owned jobs: ` +
1995
+ `${over.slice(0, 2).map(l => JSON.stringify(l)).join(", ")}` +
1996
+ `${over.length > 2 ? ` and ${over.length - 2} more` : ""}`;
1997
+
1998
+ if (resolved.verb === "SKIP") {
1999
+ actions.push(`SKIP: ${label} (unchanged${kept})`);
2000
+ return;
2001
+ }
2002
+
2003
+ mkdirSync(dirname(filePath), { recursive: true });
2004
+ writeFileSync(filePath, resolved.content);
2005
+ actions.push(`${resolved.verb}: ${label} (${signed(resolved.lineDelta)} lines${kept}${overwrote})`);
2006
+ }
2007
+
2008
+ export function createCiWorkflows(root: string, actions: string[], opts: { force?: boolean } = {}): void {
2009
+ const workflowsDir = join(root, ".github", "workflows");
2010
+ if (!existsSync(workflowsDir)) {
2011
+ mkdirSync(workflowsDir, { recursive: true });
2012
+ }
2013
+
2014
+ const harness = loadHarnessConfig(root);
2015
+ const bunVersion = harness?.ci?.bunVersion || "latest";
2016
+ const runner = harness?.ci?.runner || "ubuntu-latest";
2017
+ const branches = harness?.ci?.branches || ["main"];
2018
+ // Branch patterns are globs: a bare `*` is a YAML alias indicator and `*-dev`
2019
+ // an unresolved alias, so emitting them unquoted produces a workflow file
2020
+ // GitHub Actions refuses to parse. JSON.stringify yields a YAML-compatible
2021
+ // double-quoted scalar with the right escaping.
2022
+ const branchList = branches.map((b: string) => ` - ${JSON.stringify(String(b))}`).join("\n");
2023
+ const runsOn = JSON.stringify(String(runner));
2024
+
2025
+ // DRIFT-3 (#302) refuses a conformity exemption added in the same change as
2026
+ // the violation it exempts, by comparing the allowlist against the default
2027
+ // branch. `actions/checkout` fetches one commit and no remote-tracking ref,
2028
+ // so the check had nothing to compare against and reported UNMEASURED —
2029
+ // which is how a ratchet becomes decorative.
2030
+ //
2031
+ // A ONE-COMMIT fetch of the base, not `fetch-depth: 0`: `git show
2032
+ // <ref>:<path>` needs only that commit, and full history is a real cost to
2033
+ // impose on every consumer for one file read.
2034
+ //
2035
+ // The fetch must not FAIL the run — a repo whose default branch is not the
2036
+ // first configured branch, or a fork PR without access, would otherwise go
2037
+ // red over a fetch rather than over its code. But it must not be silent
2038
+ // either: a swallowed fetch leaves the ratchet unmeasured, and an
2039
+ // unmeasured ratchet is a decorative one. So the failure branch prints.
2040
+ // The check downstream is what decides — advisory for a consumer, while
2041
+ // rungate's own suite asserts the base IS readable, so a failed fetch
2042
+ // surfaces as a red test here rather than as a quiet pass.
2043
+ //
2044
+ // The branch name reaches a shell command, so it is validated AND quoted,
2045
+ // not either alone. The charset excludes every shell metacharacter and both
2046
+ // quote marks, which is what makes the single-quoted refspec below safe to
2047
+ // interpolate — the two defences are chosen to agree rather than to differ,
2048
+ // because a validator that admits something its consumer treats differently
2049
+ // is the gap, not the absence of a validator.
2050
+ const baseBranch = String(branches[0] ?? "main");
2051
+ const SAFE_BRANCH = /^[A-Za-z0-9][A-Za-z0-9._\/-]*$/;
2052
+ const baseRefStep =
2053
+ SAFE_BRANCH.test(baseBranch) && !baseBranch.includes("..")
2054
+ ? // `--depth=200`, not `--depth=1`. The conformity ratchet only diffs the
2055
+ // tip and was happy with one commit, but a tip with no history behind
2056
+ // it makes any check that reads the recent log unmeasurable — and an
2057
+ // empty log is indistinguishable from a clean one. Two hundred commits
2058
+ // is a few hundred KB and spans months of this project's history.
2059
+ ` - name: Fetch the comparison base for the conformity ratchet
2060
+ run: |
2061
+ git fetch --no-tags --depth=200 origin '+refs/heads/${baseBranch}:refs/remotes/origin/${baseBranch}' \\
2062
+ || echo "WARN: could not fetch ${baseBranch}; the conformity allowlist growth check will report UNMEASURED."`
2063
+ : // Not a fetchable ref: a glob pattern, a leading dash, or a traversal
2064
+ // segment. Emitted as a comment so the omission is visible in the
2065
+ // generated file rather than looking like it was never considered.
2066
+ ` # No comparison base fetched: the first configured branch (${JSON.stringify(baseBranch)}) is not a plain ref name,
2067
+ # so the conformity allowlist growth check will report UNMEASURED.`;
2068
+
2069
+ // The typecheck step used to be emitted unconditionally as `bunx tsc --noEmit`.
2070
+ // Without a tsconfig.json tsc prints its help text and exits 1, so every
2071
+ // scaffolded consumer that is not already a TypeScript project got a CI step
2072
+ // that could only fail, over a file rungate never created for them (#65/#76).
2073
+ // Rungate itself was shielded from noticing because `bun test` failed first
2074
+ // and the step never ran.
2075
+ //
2076
+ // Which command, and whether there is one at all, is `typecheckDecision`'s
2077
+ // to answer — the same binding AGENTS.md's row and the scanned
2078
+ // `dev.typeCheck` read (#87). This site used to check for
2079
+ // `scripts/typecheck.ts` on disk, a branch `files:` makes unreachable for
2080
+ // every consumer, and never looked at a project's own `typecheck` script.
2081
+ const typecheck = typecheckDecision(root);
2082
+ const typecheckStep = typecheck.command
2083
+ ? `\n - run: ${typecheck.command}`
2084
+ : `\n # No type check: ${typecheck.reason}.`;
2085
+
2086
+ const ciYml = `# Managed by rungate — do not edit. Customize the ci section of .claude/rungate/config.json.
2087
+ name: CI
2088
+
2089
+ on:
2090
+ push:
2091
+ branches:
2092
+ ${branchList}
2093
+ pull_request:
2094
+ branches:
2095
+ ${branchList}
2096
+
2097
+ jobs:
2098
+ test:
2099
+ runs-on: ${runsOn}
2100
+ steps:
2101
+ - uses: actions/checkout@v4
2102
+ ${baseRefStep}
2103
+ - uses: oven-sh/setup-bun@v2
2104
+ with:
2105
+ bun-version: "${bunVersion}"
2106
+ - run: bun install
2107
+ - run: bun test${typecheckStep}
2108
+ `;
2109
+
2110
+ const gatesYml = `# Managed by rungate — do not edit. Customize the ci section of .claude/rungate/config.json.
2111
+ name: Gates
2112
+
2113
+ on:
2114
+ push:
2115
+ branches:
2116
+ ${branchList}
2117
+ pull_request:
2118
+ branches:
2119
+ ${branchList}
2120
+
2121
+ jobs:
2122
+ gates:
2123
+ runs-on: ${runsOn}
2124
+ steps:
2125
+ - uses: actions/checkout@v4
2126
+ - uses: oven-sh/setup-bun@v2
2127
+ with:
2128
+ bun-version: "${bunVersion}"
2129
+ - run: bun install
2130
+ - name: Conformity + spec drift
2131
+ run: bun test test/scaffold-conformity.test.ts
2132
+ - name: Secret scan
2133
+ run: |
2134
+ # CI has nothing staged, so the old --cached scan examined zero files
2135
+ # on every run — a green check that verified nothing.
2136
+ # git grep handles paths with spaces natively, skips binaries with -I,
2137
+ # and surfaces real errors instead of hiding them behind 2>/dev/null,
2138
+ # so this cannot fail open the way the xargs pipeline could.
2139
+ # git grep exits 1 when nothing matches, which is the pass case.
2140
+ # Tier 1 patterns come from lib/secret-patterns.ts, the single registry
2141
+ # shared with the generated pre-commit hook. This comment used to
2142
+ # CLAIM parity while CI carried 3 patterns and the hook carried 8 —
2143
+ # CI missed gho_, ghs_, github_pat_, sk-ant- and PEM private keys
2144
+ # entirely. Asserted now in test/unit/secret-patterns.test.ts.
2145
+ if git grep -I -lE '${tier1Ere()}' -- .; then
2146
+ echo "::error::Potential secrets detected in tracked files"
2147
+ exit 1
2148
+ fi
2149
+ # Capture first so a git failure fails CLOSED. Piping git straight
2150
+ # into the filters would turn an error into empty input, which reads
2151
+ # as "clean" — passing exactly when the scan could not run.
2152
+ # git grep exits 1 for "no match", which is not an error.
2153
+ # NOTE: do NOT append "|| true" to the assignment below. It makes the
2154
+ # assignment itself succeed, so $? is always 0 and the error branch
2155
+ # becomes dead code — the scan would fail open on a git error.
2156
+ set +e
2157
+ tier2=$(git grep -I -hoE '(password|passwd|api[_-]?key|secret)[[:space:]]*[:=][[:space:]]*[A-Za-z0-9/+=_.-]{12,}' -- .)
2158
+ rc=$?
2159
+ set -e
2160
+ # git grep: 0 = match, 1 = no match, >1 = real error.
2161
+ if [ "$rc" -gt 1 ]; then
2162
+ echo "::error::git grep failed (exit $rc) — refusing to report a clean scan"
2163
+ exit 1
2164
+ fi
2165
+ # Exclusion applies to the extracted VALUE, not the whole line.
2166
+ # Matching anywhere on the line let a trailing "# placeholder"
2167
+ # launder a real secret past the check.
2168
+ if printf '%s\\n' "$tier2" | grep -qvE '^$|[:=][[:space:]]*(process\\.env|os\\.environ|Deno\\.env|getenv|REDACTED|CHANGEME|placeholder)'; then
2169
+ echo "::error::Potential credential assignment in tracked files"
2170
+ exit 1
2171
+ fi
2172
+ echo "Secret scan clean"
2173
+ `;
2174
+
2175
+ // Not `writeFileSync`. The harness owns the `test` and `gates` jobs; it does
2176
+ // not own the file, and a consumer's own jobs have to survive the update
2177
+ // that re-scaffolding IS. A refusal is recorded rather than thrown so that
2178
+ // one unpreservable workflow does not abandon the rest of the scaffold
2179
+ // half-done — scripts/scaffold-project.ts exits non-zero on it.
2180
+ for (const [name, content] of [["ci.yml", ciYml], ["gates.yml", gatesYml]] as const) {
2181
+ const label = `.github/workflows/${name}`;
2182
+ try {
2183
+ writeManagedFile(join(workflowsDir, name), content, label, actions, opts);
2184
+ } catch (e) {
2185
+ actions.push(`REFUSED: ${(e as Error).message}`);
2186
+ }
2187
+ }
2188
+ }
2189
+
2190
+ // ── Consumer hook deployment ─────────────────────────────────
2191
+
2192
+ /**
2193
+ * Deploy hooks marked deployToConsumers:true to consumer projects'
2194
+ * .claude/settings.local.json with correct hookFor and command paths.
2195
+ * SC-472: scaffold deploys consumer-facing hooks
2196
+ *
2197
+ * Reads through the config loader, so the hooks come from
2198
+ * `.claude/rungate/hooks.json` under the directory layout and from
2199
+ * `.claude/rungate.json` under the monolith. Reading the monolith path
2200
+ * directly — as this did — meant a project on the directory layout deployed
2201
+ * nothing and said nothing, because the early return is indistinguishable
2202
+ * from "this project has no hooks" (#70).
2203
+ */
2204
+ export function deployHooksToConsumers(root: string, actions: string[]): void {
2205
+ let harness: any;
2206
+ try {
2207
+ harness = tryLoadRungateConfig(root);
2208
+ } catch (err) {
2209
+ // A config that exists but cannot be read is not a config that is absent
2210
+ // (ADR-001 D2). Say so rather than returning as if there were no hooks.
2211
+ actions.push(`SKIP: hook deployment — unreadable rungate config: ${(err as Error).message}`);
2212
+ return;
2213
+ }
2214
+ if (!harness) return;
2215
+
2216
+ if (!harness?.hooks || !Array.isArray(harness.hooks)) return;
2217
+ if (!harness?.consumers || !Array.isArray(harness.consumers) || harness.consumers.length === 0) return;
2218
+
2219
+ const hooksDir = join(root, "hooks");
2220
+
2221
+ for (const consumer of harness.consumers) {
2222
+ const consumerRoot = consumer.startsWith("/") ? consumer : join(root, consumer);
2223
+ if (!existsSync(consumerRoot)) {
2224
+ actions.push(`SKIP: Consumer ${consumer} — directory not found`);
2225
+ continue;
2226
+ }
2227
+
2228
+ const claudeDir = join(consumerRoot, ".claude");
2229
+ if (!existsSync(claudeDir)) {
2230
+ mkdirSync(claudeDir, { recursive: true });
2231
+ }
2232
+
2233
+ const settingsPath = join(consumerRoot, ".claude", "settings.local.json");
2234
+ let settings: any = {};
2235
+ if (existsSync(settingsPath)) {
2236
+ try { settings = JSON.parse(readFileSync(settingsPath, "utf-8")); } catch {}
2237
+ }
2238
+
2239
+ if (!settings.hooks) settings.hooks = {};
2240
+
2241
+ let deployed = 0;
2242
+ for (const hook of harness.hooks) {
2243
+ if (!hook.enabled || !hook.hookFor || !hook.command) continue;
2244
+ if (hook.deployToConsumers !== true) continue;
2245
+
2246
+ const resolvedCommand = hook.command.replace("${RUNGATE_HOOKS_DIR}", hooksDir);
2247
+ const hookType = hook.hookFor as string;
2248
+
2249
+ if (!settings.hooks[hookType]) settings.hooks[hookType] = [];
2250
+
2251
+ // Check if this hook is already deployed
2252
+ const existing = settings.hooks[hookType].find(
2253
+ (h: any) => h.command === resolvedCommand || (h.command && h.command.includes(hook.name))
2254
+ );
2255
+ if (existing) continue;
2256
+
2257
+ const hookEntry: any = { command: resolvedCommand };
2258
+ if (hook.matcher) hookEntry.matcher = hook.matcher;
2259
+
2260
+ settings.hooks[hookType].push(hookEntry);
2261
+ deployed++;
2262
+ }
2263
+
2264
+ if (deployed > 0) {
2265
+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
2266
+ actions.push(`DEPLOYED: ${deployed} hooks to ${consumer}/.claude/settings.local.json`);
2267
+ } else {
2268
+ actions.push(`SKIP: All hooks already deployed to ${consumer}`);
2269
+ }
2270
+ }
2271
+ }
2272
+
2273
+ export function createGitHooks(root: string, actions: string[]): void {
2274
+ const hooksDir = join(root, ".git", "hooks");
2275
+ if (!existsSync(hooksDir)) return;
2276
+
2277
+ const { chmodSync } = require("fs");
2278
+
2279
+ const preCommit = join(hooksDir, "pre-commit");
2280
+ if (!existsSync(preCommit)) {
2281
+ writeFileSync(preCommit, `#!/bin/sh
2282
+ # Managed by rungate — secret scan + PROJECT-STATE update
2283
+ #
2284
+ # Scans the staged DIFF, not files on disk. This is deliberate and fixes four
2285
+ # failure modes the file-list approach had:
2286
+ # - nothing staged: the list was empty, xargs ran grep with no operands,
2287
+ # grep read stdin and exited 0, so every --amend was rejected
2288
+ # - paths with spaces: split into nonexistent fragments, grep errored,
2289
+ # 2>/dev/null hid it, and the file was silently never scanned
2290
+ # - 2>/dev/null masked every real error, so the scan failed open
2291
+ # - grep read the WORKING TREE, so a secret staged and then edited out of
2292
+ # the file on disk was committed unseen
2293
+ # Matching only added lines (^+) also means pre-existing matches elsewhere in
2294
+ # a touched file do not block unrelated commits.
2295
+ #
2296
+ # Capturing the diff first makes a git failure fail CLOSED. Piping git
2297
+ # straight into grep would swallow a git error as empty input, which grep
2298
+ # reads as "no secrets" — the scan would pass precisely when it could not run.
2299
+ staged_diff=$(git diff --cached --diff-filter=ACM -U0) || {
2300
+ echo "ERROR: could not read staged diff — refusing to commit unscanned"
2301
+ exit 1
2302
+ }
2303
+ # Tier 1 — anchored key formats. Unambiguous, so no exceptions.
2304
+ if printf '%s\\n' "$staged_diff" | grep -qE '^\\+.*${tier1Ere()}'; then
2305
+ echo "ERROR: Potential secrets detected in staged changes"
2306
+ exit 1
2307
+ fi
2308
+
2309
+ # Tier 2 — credential assignments. Restores the coverage the old
2310
+ # password="..." pattern was meant to provide, in a form with no quote
2311
+ # characters (quotes could not survive JS-template -> shell escaping).
2312
+ #
2313
+ # grep -o extracts just the assignment, so the exclusion below is applied to
2314
+ # the VALUE and not to the whole line. Matching the exclusion anywhere on the
2315
+ # line was an allowlist escape: appending "# placeholder" to a line holding a
2316
+ # real secret was enough to launder it past the check.
2317
+ #
2318
+ # Exclusions are env lookups and explicit non-values. password =
2319
+ # process.env.DB_PASSWORD is a reference, not a secret, and flagging it would
2320
+ # only train people to reach for --no-verify.
2321
+ if printf '%s\\n' "$staged_diff" \\
2322
+ | grep '^+' \\
2323
+ | grep -oE '(password|passwd|api[_-]?key|secret)[[:space:]]*[:=][[:space:]]*[A-Za-z0-9/+=_.-]{12,}' \\
2324
+ | grep -qvE '[:=][[:space:]]*(process\\.env|os\\.environ|Deno\\.env|getenv|REDACTED|CHANGEME|placeholder)'; then
2325
+ echo "ERROR: Potential credential assignment in staged changes"
2326
+ exit 1
2327
+ fi
2328
+
2329
+ # Update PROJECT-STATE if it exists
2330
+ if [ -f "project-state.json" ]; then
2331
+ bun node_modules/rungate/scripts/update-project-state.ts --skip-tests 2>/dev/null || true
2332
+ git add PROJECT-STATE.md project-state.json 2>/dev/null || true
2333
+ fi
2334
+
2335
+ # A script's exit status is its last command's. Without this, the [ -f ] test
2336
+ # failing (no project-state.json) or git add failing (no PROJECT-STATE.md yet)
2337
+ # made the hook exit non-zero and reject a perfectly good commit. Everything
2338
+ # that should block has already exited 1 above.
2339
+ exit 0
2340
+ `);
2341
+ chmodSync(preCommit, 0o755);
2342
+ actions.push("CREATED: .git/hooks/pre-commit (secret scan + PROJECT-STATE update)");
2343
+ }
2344
+
2345
+ const prePush = join(hooksDir, "pre-push");
2346
+ const MANAGED_MARKER = PRE_PUSH_MANAGED_MARKER;
2347
+
2348
+ // `2>/dev/null` threw away the only output that said WHY conformity failed,
2349
+ // leaving the developer a bare "fix before pushing" and no diagnosis. And the
2350
+ // old guard was `if (!existsSync(prePush))`, so once a hook existed it was
2351
+ // never updated again — every fix to this hook, including this one, would
2352
+ // have reached nobody. Overwrite only our own managed hook; a hook a human
2353
+ // wrote is left alone.
2354
+ const existing = existsSync(prePush) ? readFileSync(prePush, "utf-8") : null;
2355
+ if (existing !== null && !existing.includes(MANAGED_MARKER)) {
2356
+ actions.push("SKIP: .git/hooks/pre-push (hand-written, not overwriting)");
2357
+ return;
2358
+ }
2359
+
2360
+ // Checks the COMMITS BEING PUSHED, not the working tree (#85).
2361
+ //
2362
+ // The old hook ran the conformity suite in the working tree, which is not
2363
+ // what is being pushed. On 2026-10-05 that let a regression reach main:
2364
+ // HYGIENE-3's reference index recursed into .claude/worktrees/, 39 full repo
2365
+ // copies that exist locally and not in a clean checkout, so every file
2366
+ // looked referenced. It passed before push and Gates went red on main. A
2367
+ // gate that inspects something other than what it is gating is not a weaker
2368
+ // gate; it is a different gate wearing the name of the one you wanted.
2369
+ //
2370
+ // On node_modules, which #85 left open: symlinking the working tree's is
2371
+ // fast, and it is honest exactly while the pushed commit's lockfile matches
2372
+ // the one those modules were installed from. Installing unconditionally is
2373
+ // correct and slow enough that people disable the hook, which is worse than
2374
+ // either. So compare the lockfiles and only pay for an install when they
2375
+ // actually differ — the common push changes no dependencies and keeps the
2376
+ // fast path, and the push that does change them cannot quietly test against
2377
+ // the wrong ones.
2378
+ //
2379
+ // The script itself lives in lib/scaffold/pre-push-hook.ts (#397). As a
2380
+ // template literal here it was unrunnable, and the thing nothing runs is
2381
+ // the thing nothing checks: the lockfile comparison read the CHECKOUT's
2382
+ // `bun.lock`, so a consumer that gitignores its lockfile could never take
2383
+ // the fast path and could never pass. Over there it is one binding with one
2384
+ // exit-code constant, and test/pre-push-hook.test.ts drives it against
2385
+ // planted repositories.
2386
+ writeFileSync(prePush, prePushHookScript());
2387
+ chmodSync(prePush, 0o755);
2388
+ actions.push(existing === null
2389
+ ? "CREATED: .git/hooks/pre-push (conformity check)"
2390
+ : "UPDATED: .git/hooks/pre-push (conformity check)");
2391
+ }
2392
+
2393
+ /**
2394
+ * The version range a scaffolded project should depend on (#362).
2395
+ *
2396
+ * This used to be `file:${relative(root, harnessRoot)}` — a path to a
2397
+ * sibling directory on whichever machine ran the scaffold, then pinned into
2398
+ * the consumer's `bun.lock`. On CI, or on any second machine, that path does
2399
+ * not exist and `bun install` exits 1, so a consumer cannot install its
2400
+ * dependencies on a clean clone. That is a failure at step zero, before any
2401
+ * gate or tier question, and it is what broke DailyBriefDashboard's CI on
2402
+ * every run from 2026-10-03.
2403
+ *
2404
+ * `--no-optional` does not help, which is worth recording because it was the
2405
+ * attempted fix: `--frozen-lockfile` resolves the `file:` entries pinned in
2406
+ * the lock whether or not they are optional.
2407
+ *
2408
+ * ## Why the MINOR floor and not the current patch
2409
+ *
2410
+ * A caret on the exact current version — `^0.2.2` from a tree at 0.2.2 —
2411
+ * cannot resolve until that version is published, and this repo runs ahead
2412
+ * of npm (0.2.1 published against 0.2.2 in the tree when this was written;
2413
+ * #364 is about there being no release workflow at all). A consumer
2414
+ * scaffolded in that window would get an unresolvable dependency, which is
2415
+ * the same defect in a new costume.
2416
+ *
2417
+ * `^0.2.0` is satisfied by every published 0.2.x, so it resolves to the
2418
+ * newest one available today AND picks up the next release with no
2419
+ * re-scaffold. The floor moves when the harness's own minor moves, which is
2420
+ * when a consumer genuinely needs a newer line.
2421
+ */
2422
+ export function harnessDevDepRange(version?: string): string {
2423
+ const v = version ?? harnessVersion();
2424
+ const m = /^(\d+)\.(\d+)\./.exec(v);
2425
+ // An unparseable version falls back to the widest range that is still a
2426
+ // range rather than to `file:` or to `*`. `*` would let a consumer install
2427
+ // a major they were never scaffolded against; `file:` is the bug.
2428
+ if (!m) return "^0.2.0";
2429
+ return `^${m[1]}.${m[2]}.0`;
2430
+ }
2431
+
2432
+ function harnessVersion(): string {
2433
+ try {
2434
+ const pkg = JSON.parse(
2435
+ readFileSync(join(dirname(dirname(__dirname)), "package.json"), "utf-8"),
2436
+ );
2437
+ return typeof pkg?.version === "string" ? pkg.version : "";
2438
+ } catch {
2439
+ return "";
2440
+ }
2441
+ }
2442
+
2443
+ /**
2444
+ * `version` exists for the install tests, and the reason is a release
2445
+ * blocker rather than convenience (#364).
2446
+ *
2447
+ * The range this writes is floored at the harness's own minor, so a tree
2448
+ * carrying an UNPUBLISHED minor emits a range nothing on the registry
2449
+ * satisfies — `0.3.0` emits `^0.3.0` while npm's newest is `0.2.1`. That is
2450
+ * correct output and becomes resolvable the moment the version ships. But a
2451
+ * test that really runs `bun install` cannot pass in the window before the
2452
+ * publish, and the release workflow runs the suite BEFORE publishing, with
2453
+ * no bypass, which made every minor and major bump un-releasable: the check
2454
+ * could not pass until the step it gates had already run.
2455
+ *
2456
+ * Splitting it by phase is the fix. The resolvability half is driven over a
2457
+ * version that IS published, so it keeps catching the `file:` regression it
2458
+ * was written for; the "this tree's own range will resolve once shipped"
2459
+ * half is a pure property and needs no registry. See
2460
+ * `test/scaffold-installable.test.ts`.
2461
+ */
2462
+ export function addPaiHarnessDevDep(root: string, actions: string[], version?: string): void {
2463
+ const pkgPath = join(root, "package.json");
2464
+ if (!existsSync(pkgPath)) return;
2465
+
2466
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
2467
+ if (!pkg.devDependencies) {
2468
+ pkg.devDependencies = {};
2469
+ }
2470
+
2471
+ // Also a different question — "is rungate already available here" — but
2472
+ // the self-reference half is the same fact, so it routes through the one
2473
+ // predicate (#380).
2474
+ if (pkg.devDependencies["rungate"] || isHarnessItself(root)) {
2475
+ actions.push("SKIP: rungate devDep (already present or self-reference)");
2476
+ return;
2477
+ }
2478
+
2479
+ pkg.devDependencies["rungate"] = harnessDevDepRange(version);
2480
+
2481
+ if (!pkg.scripts) {
2482
+ pkg.scripts = {};
2483
+ }
2484
+ if (!pkg.scripts.test) {
2485
+ pkg.scripts.test = "bun test";
2486
+ }
2487
+
2488
+ writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
2489
+ // Names the PATH it wrote, not just what it did (#216). An action that does
2490
+ // not name its file is invisible to the stager and, worse, now reads as an
2491
+ // unexplained modification to the dirty-tree check.
2492
+ actions.push("UPDATED: package.json (rungate devDep)");
2493
+ }
2494
+
2495
+ export function runAuditSpecsFix(root: string, actions: string[]): void {
2496
+ const specsDir = join(root, "specs");
2497
+ if (!existsSync(specsDir)) {
2498
+ actions.push("SKIP: audit-specs (no specs/ directory)");
2499
+ return;
2500
+ }
2501
+ const specFiles = readdirSync(specsDir).filter(f => f.endsWith(".md"));
2502
+ if (specFiles.length === 0) {
2503
+ actions.push("SKIP: audit-specs (no spec files)");
2504
+ return;
2505
+ }
2506
+ const result = auditSpecs(root, { fix: true });
2507
+ const rewriteCount = result.rewrites?.length ?? 0;
2508
+ if (rewriteCount > 0) {
2509
+ // One action per spec file actually rewritten, naming the path (#216).
2510
+ // "rewrote 2 SCs" named no file, so the rewritten specs were never staged
2511
+ // and showed up to the dirty-tree check as somebody else's edit.
2512
+ const touched = [...new Set((result.rewrites ?? []).map(r => `specs/${r.specFile}`))];
2513
+ for (const file of touched) actions.push(`UPDATED: ${file} (audit-specs --fix)`);
2514
+ actions.push(`SKIP: audit-specs summary (rewrote ${rewriteCount} SCs across ${touched.length} spec file(s))`);
2515
+ } else {
2516
+ actions.push("SKIP: audit-specs (all SCs already matchable)");
2517
+ }
2518
+ }
2519
+
2520
+ /**
2521
+ * Paths with TRACKED modifications that this scaffold run did not produce.
2522
+ *
2523
+ * Untracked files are excluded on purpose: they were never going to be
2524
+ * committed, and treating a stray scratch file as "dirty" would refuse on
2525
+ * nearly every real repo, which is how a safety check gets switched off.
2526
+ */
2527
+ function dirtyPaths(root: string, generated: string[]): string[] {
2528
+ const porcelain = Bun.spawnSync(["git", "-C", root, "status", "--porcelain"]).stdout.toString();
2529
+ const owned = (p: string) => generated.some(g => p === g || p.startsWith(`${g}/`));
2530
+ return porcelain
2531
+ .split("\n")
2532
+ .filter(Boolean)
2533
+ .filter(l => !l.startsWith("??"))
2534
+ // Rename entries read `R old -> new`; the destination is what matters.
2535
+ .map(l => l.slice(3).trim().split(" -> ").pop()!.replace(/^"|"$/g, ""))
2536
+ .filter(p => p && !owned(p));
2537
+ }
2538
+
2539
+ /**
2540
+ * Print the run's action list and return how many of them were refusals.
2541
+ *
2542
+ * Lives here rather than in the orchestrator for the reason the whole file
2543
+ * exists (SCAFFOLD-DECOMPOSITION-SPEC): scripts/scaffold-project.ts sequences
2544
+ * steps, it does not implement them. The caller decides what a refusal costs;
2545
+ * this only counts them, so it stays callable from a test.
2546
+ */
2547
+ export function reportScaffoldActions(actions: string[]): number {
2548
+ console.log("\n=== Scaffold Report ===");
2549
+ for (const action of actions) console.log(` ${action}`);
2550
+ const count = (verb: string) => actions.filter(a => a.startsWith(verb)).length;
2551
+ console.log(`\nTotal: ${count("CREATED")} created, ${count("REPLACED")} replaced, ${count("SKIP")} skipped, ${count("REFUSED")} refused`);
2552
+ return count("REFUSED");
2553
+ }
2554
+
2555
+ export function postScaffoldCommit(
2556
+ root: string,
2557
+ actions: string[],
2558
+ opts: { commit?: boolean } = {},
2559
+ ): void {
2560
+ // #216: this used to commit unconditionally. On a consumer repo that meant
2561
+ // the documented onboarding command created a commit nobody asked for —
2562
+ // and, since it ran after a write that could destroy their ci.yml, it
2563
+ // committed the destruction too. Committing is the operator's call now.
2564
+ if (!opts.commit) {
2565
+ actions.push("SKIP: post-scaffold commit (--commit not passed)");
2566
+ return;
2567
+ }
2568
+ try {
2569
+ // Stage ONLY what this scaffold run generated, never `git add -A`.
2570
+ //
2571
+ // The blanket add swept up whatever else was in the working tree and
2572
+ // committed it under "scaffold: initialize rungate harness". Running
2573
+ // scaffold mid-session therefore hijacked unrelated in-progress work into
2574
+ // a commit with a message describing none of it — and, because the commit
2575
+ // already existed, the real commit then had to be an amend.
2576
+ const generated = [...new Set(
2577
+ actions
2578
+ // Verbs that mean "scaffold wrote this path". Deliberately excludes
2579
+ // SKIP / GAP / WARN / AUDIT (no write happened) — and all of them,
2580
+ // because missing one silently leaves generated files uncommitted.
2581
+ .map(a => a.trim().match(/^(?:CREATED|UPDATED|REPLACED|GENERATED|DEPLOYED|SPLIT): ([^\s(]+)/)?.[1])
2582
+ .filter((p): p is string => Boolean(p))
2583
+ // .git/ contents are not tracked; hooks live there.
2584
+ // .git/ contents are never tracked. Directories are kept — scaffold
2585
+ // reports some output as a created directory (.claude/rules/) rather
2586
+ // than per-file, and git add stages a directory's contents.
2587
+ .map(p => p.replace(/\/+$/, ""))
2588
+ .filter(p => p && !p.startsWith(".git/") && p !== ".git")
2589
+ .filter(p => existsSync(join(root, p)))
2590
+ )];
2591
+
2592
+ if (generated.length === 0) {
2593
+ actions.push("SKIP: post-scaffold commit (nothing generated)");
2594
+ return;
2595
+ }
2596
+
2597
+ // Refuse before staging, not after. A commit made on top of someone
2598
+ // else's half-finished edit is not something an operator can un-see.
2599
+ const dirty = dirtyPaths(root, generated);
2600
+ if (dirty.length > 0) {
2601
+ actions.push(`REFUSED: post-scaffold commit (dirty working tree: ${dirty.join(", ")})`);
2602
+ return;
2603
+ }
2604
+
2605
+ Bun.spawnSync(["git", "-C", root, "add", "--", ...generated]);
2606
+
2607
+ // Only commit if staging actually produced a change — re-scaffolding an
2608
+ // up-to-date project regenerates identical files and must stay a no-op.
2609
+ const staged = Bun.spawnSync(["git", "-C", root, "diff", "--cached", "--name-only"])
2610
+ .stdout.toString().trim();
2611
+ if (!staged) {
2612
+ actions.push("SKIP: post-scaffold commit (no changes)");
2613
+ return;
2614
+ }
2615
+
2616
+ Bun.spawnSync(["git", "-C", root, "commit", "-m", "scaffold: regenerate harness files"]);
2617
+ actions.push("CREATED: post-scaffold commit");
2618
+ } catch {
2619
+ actions.push("SKIP: post-scaffold commit (git error)");
2620
+ }
2621
+ }