rungate 0.2.1 → 0.3.0

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