rungate 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/.claude/agents/aditi.md +47 -0
  2. package/.claude/agents/marcus.md +50 -0
  3. package/.claude/agents/quinn.md +58 -0
  4. package/.claude/agents/rook.md +47 -0
  5. package/.claude/agents/serena.md +46 -0
  6. package/.claude/rungate.json +11 -0
  7. package/.fallowrc.json +28 -0
  8. package/.github/copilot-instructions.md +20 -0
  9. package/.rungate/conformity-findings.json +648 -0
  10. package/AGENTS.md +106 -0
  11. package/CODE-MAP.md +50 -0
  12. package/HARNESS.md +88 -0
  13. package/bun.lock +26 -0
  14. package/bunfig.toml +2 -0
  15. package/config/brief-policies.json +28 -0
  16. package/config/ceremony-profiles.json +212 -0
  17. package/config/consumer-cascade-map.json +24 -0
  18. package/config/doc-cascade-map.json +24 -0
  19. package/config/eval.json +84 -0
  20. package/config/profiles/account-plan.yaml +36 -0
  21. package/config/profiles/campaign.yaml +94 -0
  22. package/config/prove-evidence.schema.json +65 -0
  23. package/config/spec-policies.json +36 -0
  24. package/config/workflow-schema.json +281 -0
  25. package/gates/SCHEMA-GUIDE.md +121 -0
  26. package/gates/ac-quality.test.ts +106 -0
  27. package/gates/adversarial.test.ts +274 -0
  28. package/gates/brief-assembler.test.ts +429 -0
  29. package/gates/brief-assembler.ts +334 -0
  30. package/gates/bunfig.toml +2 -0
  31. package/gates/chain.test.ts +91 -0
  32. package/gates/e2e-smoke.test.ts +234 -0
  33. package/gates/error-classifier.test.ts +249 -0
  34. package/gates/error-classifier.ts +89 -0
  35. package/gates/orchestrator.test.ts +950 -0
  36. package/gates/orchestrator.ts +569 -0
  37. package/gates/preload.ts +77 -0
  38. package/gates/prompts/ac-adversary.md +20 -0
  39. package/gates/prompts/evidence-validator.md +22 -0
  40. package/gates/prompts/prove-reproducer.md +53 -0
  41. package/gates/prove.test.ts +164 -0
  42. package/gates/run-gate.ts +936 -0
  43. package/gates/schema-parity.test.ts +197 -0
  44. package/gates/schema.ts +362 -0
  45. package/gates/self-heal.test.ts +511 -0
  46. package/gates/self-heal.ts +121 -0
  47. package/gates/ship-orchestrator.test.ts +379 -0
  48. package/gates/ship-orchestrator.ts +363 -0
  49. package/gates/test-fixtures/broken-no-environments.json +60 -0
  50. package/gates/test-fixtures/valid-standard.json +54 -0
  51. package/gates/test-utils.ts +43 -0
  52. package/gates/witness.ts +220 -0
  53. package/gates/workflow.test.ts +1053 -0
  54. package/hooks/AgentBriefGuard.hook.ts +586 -0
  55. package/hooks/AgentVerdictCapture.hook.ts +134 -0
  56. package/hooks/AutoVerifyGate.hook.ts +76 -0
  57. package/hooks/GateEnforcement.hook.ts +273 -0
  58. package/hooks/IssueCloseGuard.hook.ts +116 -0
  59. package/hooks/MergeGuard.hook.ts +55 -0
  60. package/hooks/StaleTTLCleanup.hook.ts +133 -0
  61. package/hooks/VerifyPhaseLock.hook.ts +81 -0
  62. package/hooks/WorkflowStateGuard.hook.ts +37 -0
  63. package/hooks/lib/agentDetection.ts +70 -0
  64. package/hooks/lib/findWorkflow.ts +101 -0
  65. package/hooks/lib/parseStdin.ts +37 -0
  66. package/hooks/lib/paths.ts +111 -0
  67. package/hooks/lib/utils.ts +81 -0
  68. package/lib/conformity.ts +959 -0
  69. package/lib/paths.ts +23 -0
  70. package/lib/rungate-schema.ts +60 -0
  71. package/lib/signal-phrases.ts +7 -0
  72. package/package.json +20 -0
  73. package/prompts/ac-adversary.md +20 -0
  74. package/prompts/ac-format.md +34 -0
  75. package/prompts/aditi.md +29 -0
  76. package/prompts/blast-radius.md +29 -0
  77. package/prompts/coding-principles.md +34 -0
  78. package/prompts/container-rebuild.md +29 -0
  79. package/prompts/container-verify.md +28 -0
  80. package/prompts/discovery.md +27 -0
  81. package/prompts/environment.md +28 -0
  82. package/prompts/escalation-decision-tree.md +38 -0
  83. package/prompts/evidence-hierarchy.md +31 -0
  84. package/prompts/evidence-validator.md +22 -0
  85. package/prompts/marcus.md +29 -0
  86. package/prompts/prevention.md +26 -0
  87. package/prompts/prove-reproducer.md +43 -0
  88. package/prompts/quinn-decision-tree.md +31 -0
  89. package/prompts/quinn-ui-brief.md +106 -0
  90. package/prompts/quinn.md +29 -0
  91. package/prompts/rca.md +28 -0
  92. package/prompts/read-before-write.md +30 -0
  93. package/prompts/regression.md +26 -0
  94. package/prompts/rook.md +29 -0
  95. package/prompts/serena.md +28 -0
  96. package/prompts/testing-strategy.md +34 -0
  97. package/reference/migration-manifest.json +554 -0
  98. package/reference/prompts/agent-aditi.md +38 -0
  99. package/reference/prompts/agent-marcus.md +38 -0
  100. package/reference/prompts/agent-quinn.md +38 -0
  101. package/reference/prompts/agent-rook.md +37 -0
  102. package/reference/prompts/agent-serena.md +37 -0
  103. package/reference/prompts/council-skill.md +170 -0
  104. package/reference/prompts/goal-skill.md +235 -0
  105. package/reference/prompts/prove-skill.md +283 -0
  106. package/reference/prompts/quinn-standard.md +246 -0
  107. package/reference/prompts/ship-convergence.md +65 -0
  108. package/reference/prompts/ship-escalation.md +43 -0
  109. package/reference/prompts/ship-iteration.md +382 -0
  110. package/reference/prompts/ship-pending-patches.md +246 -0
  111. package/reference/prompts/ship-reference.md +250 -0
  112. package/reference/prompts/ship-skill.md +347 -0
  113. package/reference/prompts/ship-templates.md +215 -0
  114. package/reference/scripts/batch-status.sh +68 -0
  115. package/reference/scripts/chain-compat-check.sh +67 -0
  116. package/reference/scripts/context-audit.sh +314 -0
  117. package/reference/scripts/dead-export-check.sh +61 -0
  118. package/reference/scripts/generate-qc-tables.sh +92 -0
  119. package/reference/scripts/harness-init.sh +111 -0
  120. package/reference/scripts/pai-054-baseline-check.sh +40 -0
  121. package/reference/scripts/prove-smoke-test.sh +112 -0
  122. package/reference/scripts/setup-keychain-salt.sh +12 -0
  123. package/reference/scripts/skill-optimizer-friday.sh +88 -0
  124. package/reference/scripts/skill-qc-test.sh +351 -0
  125. package/reference/scripts/skill-synthesize-tonight.sh +66 -0
  126. package/reference/specs/HARNESS-EXTRACTION-SPEC.md +263 -0
  127. package/reference/specs/harness-v3-bash-deletion-plan.md +65 -0
  128. package/reference/specs/harness-v3-migration-plan.md +188 -0
  129. package/scripts/decision-reconcile.sh +74 -0
  130. package/scripts/decision-reconcile.ts +152 -0
  131. package/scripts/extract-constraints.ts +260 -0
  132. package/scripts/generate-code-map.ts +339 -0
  133. package/scripts/git-hooks/pre-commit +76 -0
  134. package/scripts/git-hooks/pre-push +271 -0
  135. package/scripts/harness-skill-check.sh +52 -0
  136. package/scripts/lib/gap-emit.sh +65 -0
  137. package/scripts/lib/jq-update.sh +30 -0
  138. package/scripts/lib/resolve-slug.sh +30 -0
  139. package/scripts/lib/verify-spec-compliance.sh +102 -0
  140. package/scripts/prove-backfill.sh +87 -0
  141. package/scripts/scaffold-project.ts +1488 -0
  142. package/scripts/scaffold-rungate-config.ts +91 -0
  143. package/scripts/self-containment-check.sh +109 -0
  144. package/scripts/skill-qc-validator.sh +402 -0
  145. package/scripts/slug-resolver.sh +14 -0
  146. package/scripts/sync-spec-tests.ts +236 -0
  147. package/specs/BOOTSTRAP-DATA-FLOW-SPEC.md +2493 -0
  148. package/specs/BOOTSTRAP-TEST-PLAN.md +571 -0
  149. package/specs/HARNESS-GATES.md +256 -0
  150. package/specs/HARNESS-SKILL-CHAIN.md +286 -0
  151. package/specs/HARNESS-SKILL-CONTRACT.md +93 -0
  152. package/specs/HARNESS-STANDARD.md +488 -0
  153. package/specs/SPEC-TEMPLATE.md +53 -0
  154. package/specs/bootstrap-data-flow.png +0 -0
  155. package/specs/harness-automation-matrix.md +314 -0
  156. package/specs/harness-automation-matrix.rules.json +64 -0
  157. package/test/anti.test.ts +80 -0
  158. package/test/contract-negative.test.ts +86 -0
  159. package/test/contract.test.ts +158 -0
  160. package/test/external-deps.test.ts +48 -0
  161. package/test/fixtures/golden-project/.env.example +3 -0
  162. package/test/fixtures/golden-project/Makefile +7 -0
  163. package/test/fixtures/golden-project/docs/adr/ADR-001-framework.md +23 -0
  164. package/test/fixtures/golden-project/docs/setup-guide.md +10 -0
  165. package/test/fixtures/golden-project/package.json +10 -0
  166. package/test/fixtures/golden-project/specs/api-spec.md +20 -0
  167. package/test/fixtures/golden-project/src/auth.ts +8 -0
  168. package/test/fixtures/golden-project/src/db.ts +11 -0
  169. package/test/fixtures/golden-project/src/index.ts +19 -0
  170. package/test/fixtures/golden-project/src/utils/format.ts +3 -0
  171. package/test/fixtures/golden-project/test/auth.test.ts +15 -0
  172. package/test/fixtures/golden-project/tsconfig.json +12 -0
  173. package/test/meta-sc-coverage.test.ts +159 -0
  174. package/test/phase-0.test.ts +846 -0
  175. package/test/phase-1.test.ts +617 -0
  176. package/test/phase-2.test.ts +620 -0
  177. package/test/phase-3.test.ts +99 -0
  178. package/test/scaffold-conformity.test.ts +8 -0
  179. package/test/schema-canary.test.ts +51 -0
  180. package/test/spec-compliance-auto.test.ts +64 -0
  181. package/test/spec-compliance.test.ts +295 -0
  182. package/test/spec-discovery.test.ts +68 -0
  183. package/test/spec-drift.test.ts +5 -0
  184. package/test/structure.test.ts +165 -0
  185. package/test/unit/agent-brief-guard-ship.test.ts +293 -0
  186. package/test/unit/extract-constraints.test.ts +145 -0
  187. package/test/unit/issue-close-guard.test.ts +204 -0
  188. package/test/unit/scaffold-project.test.ts +417 -0
  189. package/test/unit/skill-cooccurrence.test.ts +177 -0
  190. package/test/unit/skill-sequence-logger.test.ts +244 -0
  191. package/test/unit/workflow-state-guard.test.ts +95 -0
  192. package/workflows/batch-ship.js +295 -0
  193. package/workflows/council.js +481 -0
  194. package/workflows/prove.js +560 -0
  195. package/workflows/ship.js +789 -0
  196. package/workflows/verify.js +236 -0
@@ -0,0 +1,1488 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * scaffold-project.ts — Bootstrap any project to scaffold conformity.
4
+ *
5
+ * Usage: bun ~/Projects/rungate/scripts/scaffold-project.ts /path/to/project
6
+ *
7
+ * Detects project type (code/content/infra), creates missing directories,
8
+ * generates AGENTS.md stub, creates thin conformity test, adds frontmatter
9
+ * to bare specs. NEVER overwrites existing files.
10
+ */
11
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, statSync } from "fs";
12
+ import { join, basename } from "path";
13
+
14
+ // ── CLI argument parsing ───────────────────────────────────────
15
+
16
+ const projectPath = process.argv[2];
17
+
18
+ if (!projectPath) {
19
+ console.error("Usage: scaffold-project.ts /path/to/project");
20
+ process.exit(1);
21
+ }
22
+
23
+ if (!existsSync(projectPath)) {
24
+ console.error(`ERROR: Path does not exist: ${projectPath}`);
25
+ process.exit(1);
26
+ }
27
+
28
+ if (!statSync(projectPath).isDirectory()) {
29
+ console.error(`ERROR: Not a directory: ${projectPath}`);
30
+ process.exit(1);
31
+ }
32
+
33
+ // ── Project type detection ─────────────────────────────────────
34
+
35
+ type ProjectType = "code" | "content" | "infra";
36
+
37
+ function detectProjectType(root: string): ProjectType {
38
+ const hasPackageJson = existsSync(join(root, "package.json"));
39
+ const hasSrc = existsSync(join(root, "src"));
40
+ const hasLib = existsSync(join(root, "lib"));
41
+ const hasMakefile = existsSync(join(root, "Makefile"));
42
+ const hasTsConfig = existsSync(join(root, "tsconfig.json"));
43
+ const hasDockerCompose = existsSync(join(root, "docker-compose.yml")) || existsSync(join(root, "docker-compose.yaml"));
44
+ const hasDockerfile = existsSync(join(root, "Dockerfile"));
45
+ const hasScriptsDir = existsSync(join(root, "scripts"));
46
+ const hasManifests = hasDockerCompose || hasDockerfile ||
47
+ existsSync(join(root, "k8s")) || existsSync(join(root, "terraform"));
48
+
49
+ // Code project: has source directories or package.json with source
50
+ if (hasSrc || hasLib || hasTsConfig || (hasPackageJson && (hasSrc || hasLib))) {
51
+ return "code";
52
+ }
53
+
54
+ // Infra project: has deployment/config files
55
+ if (hasManifests || (hasScriptsDir && !hasPackageJson)) {
56
+ return "infra";
57
+ }
58
+
59
+ // Code project: has package.json (even without src/)
60
+ if (hasPackageJson && hasMakefile) {
61
+ return "code";
62
+ }
63
+
64
+ // Content project: predominantly markdown/media files
65
+ if (hasPackageJson) {
66
+ return "code";
67
+ }
68
+
69
+ // Infra: has scripts dir
70
+ if (hasScriptsDir) {
71
+ return "infra";
72
+ }
73
+
74
+ return "content";
75
+ }
76
+
77
+ // ── Helpers ────────────────────────────────────────────────────
78
+
79
+ const actions: string[] = [];
80
+
81
+ function safeWrite(filePath: string, content: string, label: string): void {
82
+ if (existsSync(filePath)) {
83
+ actions.push(`SKIP: ${label} (already exists)`);
84
+ return;
85
+ }
86
+ const dir = filePath.substring(0, filePath.lastIndexOf("/"));
87
+ if (!existsSync(dir)) {
88
+ mkdirSync(dir, { recursive: true });
89
+ }
90
+ writeFileSync(filePath, content);
91
+ actions.push(`CREATED: ${label}`);
92
+ }
93
+
94
+ function safeDir(dirPath: string, label: string): void {
95
+ if (existsSync(dirPath)) {
96
+ actions.push(`SKIP: ${label}/ (already exists)`);
97
+ return;
98
+ }
99
+ mkdirSync(dirPath, { recursive: true });
100
+ actions.push(`CREATED: ${label}/`);
101
+ }
102
+
103
+ // ── Main ───────────────────────────────────────────────────────
104
+
105
+ const projectType = detectProjectType(projectPath);
106
+ const projectName = basename(projectPath);
107
+
108
+ console.log(`Detected project type: ${projectType}`);
109
+ console.log(`Project: ${projectName}`);
110
+ console.log(`Path: ${projectPath}`);
111
+ console.log("---");
112
+
113
+ // Phase 0.10: .gitignore with security template (BEFORE any other file creation)
114
+ createGitignore(projectPath);
115
+
116
+ // Phase 0.11-0.14: Create missing directories
117
+ safeDir(join(projectPath, "specs"), "specs");
118
+ safeDir(join(projectPath, "reference"), "reference");
119
+ safeDir(join(projectPath, ".github"), ".github");
120
+ safeDir(join(projectPath, ".github", "workflows"), ".github/workflows");
121
+ safeDir(join(projectPath, "scripts"), "scripts");
122
+ safeDir(join(projectPath, "docs"), "docs");
123
+ safeDir(join(projectPath, "docs", "adr"), "docs/adr");
124
+
125
+ // tests/ or test/ — respect existing convention
126
+ const existingTestDir = existsSync(join(projectPath, "test")) ? "test" : null;
127
+ const testDirName = existingTestDir || "tests";
128
+ safeDir(join(projectPath, testDirName), testDirName);
129
+
130
+ // 2. Generate or refresh AGENTS.md
131
+ if (existsSync(join(projectPath, "AGENTS.md"))) {
132
+ refreshAgentsMd(projectPath, projectType);
133
+ } else {
134
+ const agentsMd = generateAgentsMd(projectName, projectType);
135
+ safeWrite(join(projectPath, "AGENTS.md"), agentsMd, "AGENTS.md");
136
+ }
137
+
138
+ // 3. Create .github/copilot-instructions.md
139
+ const copilotInstructions = `# Copilot Instructions
140
+
141
+ Read [AGENTS.md](../AGENTS.md) for project context, key files, specs, and workflow.
142
+
143
+ All project knowledge lives in AGENTS.md. Start there.
144
+ `;
145
+ safeWrite(join(projectPath, ".github", "copilot-instructions.md"), copilotInstructions, ".github/copilot-instructions.md");
146
+
147
+ // 4. Create thin conformity test file
148
+ const conformityTest = generateConformityTest();
149
+ safeWrite(
150
+ join(projectPath, testDirName, "scaffold-conformity.test.ts"),
151
+ conformityTest,
152
+ `${testDirName}/scaffold-conformity.test.ts`
153
+ );
154
+
155
+ // 5. Add frontmatter to bare spec files
156
+ addFrontmatterToSpecs(join(projectPath, "specs"));
157
+
158
+ // Phase 1: Scan code and generate config (data flows DOWN — config before briefs)
159
+ // 6. Generate or refresh CODE-MAP.md (code projects only)
160
+ if (projectType === "code") {
161
+ generateCodeMap(projectPath);
162
+ }
163
+
164
+ // 7. Generate or audit rungate.json (code projects only)
165
+ if (projectType === "code") {
166
+ generateOrAuditProjectHarness(projectPath);
167
+ }
168
+
169
+ // Phase 2: Generate briefs AFTER config (briefs read from rungate.json)
170
+ // 8. Generate .claude/agents/ briefing files (code projects only)
171
+ if (projectType === "code") {
172
+ generateAgentBriefs(projectPath);
173
+ }
174
+
175
+ // 9. Copy spec template if specs/ is empty (#529)
176
+ copySpecTemplateIfEmpty(join(projectPath, "specs"));
177
+
178
+ // 10. Add rungate to package.json devDeps (only if package.json exists)
179
+ addPaiHarnessDevDep(projectPath);
180
+
181
+ // 11. Create CLAUDE.md with @AGENTS.md bridge
182
+ createClaudeMdBridge(projectPath);
183
+
184
+ // 12. Create CI/CD workflows (harness-owned — always regenerated)
185
+ createCiWorkflows(projectPath);
186
+
187
+ // 13. Create git hooks (pre-commit + pre-push)
188
+ createGitHooks(projectPath);
189
+
190
+ // 14. Post-scaffold git commit
191
+ postScaffoldCommit(projectPath);
192
+
193
+ // ── Report ─────────────────────────────────────────────────────
194
+
195
+ console.log("\n=== Scaffold Report ===");
196
+ for (const action of actions) {
197
+ console.log(` ${action}`);
198
+ }
199
+ console.log(`\nTotal: ${actions.filter(a => a.startsWith("CREATED")).length} created, ${actions.filter(a => a.startsWith("SKIP")).length} skipped`);
200
+
201
+ // ── Generators ─────────────────────────────────────────────────
202
+
203
+ function generateAgentsMd(name: string, type: ProjectType): string {
204
+ const typeLabel = type === "code" ? "Code" : type === "content" ? "Content" : "Infrastructure";
205
+
206
+ // Read package.json for description
207
+ const pkgPath = join(projectPath, "package.json");
208
+ let pkgDesc = "";
209
+ let pkgName = name;
210
+ if (existsSync(pkgPath)) {
211
+ try {
212
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
213
+ pkgDesc = pkg.description || "";
214
+ pkgName = pkg.name || name;
215
+ } catch {}
216
+ }
217
+
218
+ // Read README.md first paragraph for identity (skip ALL YAML frontmatter blocks, HTML, and comments)
219
+ let readmeDesc = "";
220
+ const readmePath = join(projectPath, "README.md");
221
+ if (existsSync(readmePath)) {
222
+ try {
223
+ let readme = readFileSync(readmePath, "utf-8");
224
+ // Strip all YAML frontmatter blocks (some files have multiple from templates)
225
+ while (readme.startsWith("---\n")) {
226
+ const endFm = readme.indexOf("\n---\n", 4);
227
+ if (endFm > 0) { readme = readme.slice(endFm + 5); } else { break; }
228
+ }
229
+ // Strip HTML comments
230
+ readme = readme.replace(/<!--[\s\S]*?-->/g, "");
231
+ const paragraphs = readme.split(/\n\n+/).filter(p =>
232
+ !p.startsWith("#") && !p.startsWith("---") && !p.startsWith("<") &&
233
+ !/^[\s]*$/.test(p) && p.trim().length > 20
234
+ );
235
+ if (paragraphs.length > 0) readmeDesc = paragraphs[0].replace(/\n/g, " ").trim();
236
+ } catch {}
237
+ }
238
+
239
+ // Preserve existing Hard Constraints section if AGENTS.md already exists
240
+ let existingHardConstraints = "";
241
+ const existingAgentsPath = join(projectPath, "AGENTS.md");
242
+ if (existsSync(existingAgentsPath)) {
243
+ try {
244
+ const existing = readFileSync(existingAgentsPath, "utf-8");
245
+ const hcMatch = existing.match(/## Hard Constraints[^\n]*\n\n([\s\S]*?)(?=\n## |\s*$)/);
246
+ if (hcMatch) {
247
+ const hcContent = hcMatch[1].trim();
248
+ // Only preserve if it has actual content (not just the placeholder comment)
249
+ if (hcContent && !hcContent.startsWith("<!-- Add project-specific")) {
250
+ existingHardConstraints = hcContent;
251
+ }
252
+ }
253
+ } catch (e: unknown) { console.error('Hard Constraints preservation failed:', (e as Error).message); throw e; }
254
+ }
255
+
256
+ const identity = readmeDesc || pkgDesc || `${typeLabel} project. <!-- TODO: Describe what this project is -->`;
257
+
258
+ // Detect git remote for repo URL
259
+ let repoUrl = "";
260
+ try {
261
+ const result = Bun.spawnSync(["git", "-C", projectPath, "remote", "get-url", "origin"]);
262
+ repoUrl = result.stdout.toString().trim().replace(/\.git$/, "").replace("git@github.com:", "https://github.com/");
263
+ } catch {}
264
+
265
+ // Scan key files
266
+ const keyFiles: Array<{ file: string; what: string; when: string }> = [
267
+ { file: "AGENTS.md", what: "Project entry point", when: "Always first" },
268
+ ];
269
+ const keyFilePatterns: Array<{ pattern: string; what: string; when: string }> = [
270
+ { pattern: "package.json", what: "Dependencies and scripts", when: "Adding deps or scripts" },
271
+ { pattern: "Makefile", what: "Build/deploy commands", when: "Building or deploying" },
272
+ { pattern: "tsconfig.json", what: "TypeScript configuration", when: "Changing TS settings" },
273
+ { pattern: "Containerfile", what: "Container build definition", when: "Modifying container" },
274
+ { pattern: "Dockerfile", what: "Container build definition", when: "Modifying container" },
275
+ { pattern: ".claude/rungate.json", what: "Harness project config", when: "Shipping through harness" },
276
+ ];
277
+ for (const kf of keyFilePatterns) {
278
+ if (existsSync(join(projectPath, kf.pattern))) {
279
+ keyFiles.push({ file: kf.pattern, what: kf.what, when: kf.when });
280
+ }
281
+ }
282
+ // Scan for main source files
283
+ for (const srcDir of ["src", "lib", "gates", "workflows", "hooks"]) {
284
+ if (existsSync(join(projectPath, srcDir))) {
285
+ keyFiles.push({ file: `${srcDir}/`, what: `${srcDir.charAt(0).toUpperCase() + srcDir.slice(1)} directory`, when: `Working on ${srcDir}` });
286
+ }
287
+ }
288
+
289
+ const keyFilesTable = keyFiles.map(kf => `| ${kf.file} | ${kf.what} | ${kf.when} |`).join("\n");
290
+
291
+ // Scan specs
292
+ const specsDir = join(projectPath, "specs");
293
+ const specRows: string[] = [];
294
+ if (existsSync(specsDir)) {
295
+ for (const f of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
296
+ const content = readFileSync(join(specsDir, f), "utf-8");
297
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
298
+ let testable = "false";
299
+ let governs = f.replace(/\.md$/, "");
300
+ if (fmMatch) {
301
+ const tMatch = fmMatch[1].match(/testable:\s*(true|false)/);
302
+ if (tMatch) testable = tMatch[1];
303
+ const gMatch = fmMatch[1].match(/governs:\s*(.+)/);
304
+ if (gMatch) governs = gMatch[1].trim();
305
+ }
306
+ specRows.push(`| ${f} | ${testable} | ${governs} |`);
307
+ }
308
+ }
309
+ const specsTable = specRows.length > 0
310
+ ? specRows.join("\n")
311
+ : "| (none yet — copy SPEC-TEMPLATE.md from rungate) | | |";
312
+
313
+ // Scan test files
314
+ const testDir = existsSync(join(projectPath, "test")) ? "test" : existsSync(join(projectPath, "tests")) ? "tests" : null;
315
+ const testRows: string[] = [];
316
+ if (testDir) {
317
+ for (const f of readdirSync(join(projectPath, testDir)).filter(f => f.endsWith(".test.ts"))) {
318
+ const label = f.replace(".test.ts", "").replace(/-/g, " ");
319
+ testRows.push(`| ${label} | ${f} | Auto-detected |`);
320
+ }
321
+ }
322
+ const testsTable = testRows.length > 0
323
+ ? testRows.join("\n")
324
+ : "| scaffold conformity | scaffold-conformity.test.ts | Structure validation |";
325
+
326
+ // Detect test command
327
+ let testCmd = "bun test";
328
+ if (existsSync(pkgPath)) {
329
+ try {
330
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
331
+ if (pkg.scripts?.test) testCmd = pkg.scripts.test;
332
+ } catch {}
333
+ }
334
+
335
+ // Scan reference/ files
336
+ const refDir = join(projectPath, "reference");
337
+ const refRows: string[] = [];
338
+ if (existsSync(refDir)) {
339
+ for (const f of readdirSync(refDir)) {
340
+ refRows.push(`| ${f} | Historical reference |`);
341
+ }
342
+ }
343
+ const refTable = refRows.join("\n");
344
+ const refSection = refRows.length > 0
345
+ ? `\n## Reference Files\n\nHistorical and inactive docs live in \`reference/\`.\n\n| File | What |\n|------|------|\n${refTable}\n`
346
+ : "";
347
+
348
+ // Detect workflow info
349
+ const repoLine = repoUrl ? `- **Repo:** ${repoUrl}` : "<!-- TODO: Add repo URL -->";
350
+
351
+ // Makefile targets for workflow section
352
+ let makeTargets = "";
353
+ if (existsSync(join(projectPath, "Makefile"))) {
354
+ try {
355
+ const makefile = readFileSync(join(projectPath, "Makefile"), "utf-8");
356
+ const targets = makefile.match(/^[\w-]+(?=:)/gm)?.filter(t => !t.startsWith(".") && !t.startsWith("_")).slice(0, 8);
357
+ if (targets?.length) makeTargets = `\n- **Key commands:** \`make ${targets.join("`, `make ")}\``;
358
+ } catch {}
359
+ }
360
+
361
+ // Load rungate.json for environment info
362
+ const harness = (() => {
363
+ const p = join(projectPath, ".claude", "rungate.json");
364
+ if (!existsSync(p)) return null;
365
+ try { return JSON.parse(readFileSync(p, "utf-8")); } catch { return null; }
366
+ })();
367
+
368
+ // Scan docs/ directory for documentation routing
369
+ const docsDir = join(projectPath, "docs");
370
+ const docRouting: Array<{ need: string; file: string }> = [];
371
+ // CODE-MAP first (auto-generated, always fresh)
372
+ if (existsSync(join(projectPath, "CODE-MAP.md"))) {
373
+ docRouting.push({ need: "Codebase structure (routes, components, modules, health)", file: "CODE-MAP.md" });
374
+ }
375
+ // Root-level docs (highest priority)
376
+ for (const f of ["ARCHITECTURE.md", "PRINCIPLES.md", "CONTRIBUTING.md", "MODEL.md", "PROJECT-STATE.md"]) {
377
+ if (existsSync(join(projectPath, f))) {
378
+ docRouting.push({ need: f.replace(/\.md$/, "").replace(/-/g, " "), file: f });
379
+ }
380
+ }
381
+ // docs/ directory — cap at 10 most relevant (prioritize by name patterns)
382
+ if (existsSync(docsDir)) {
383
+ const priority = ["ARCHITECTURE", "DOMAIN", "TESTING", "SECURITY", "DATA", "SETUP", "INSTALL"];
384
+ const allDocs = readdirSync(docsDir).filter(f => f.endsWith(".md"))
385
+ .map(f => ({ name: f, label: f.replace(/\.md$/, "").replace(/-/g, " "), score: priority.findIndex(p => f.toUpperCase().includes(p)) }))
386
+ .sort((a, b) => (a.score === -1 ? 999 : a.score) - (b.score === -1 ? 999 : b.score));
387
+ const topDocs = allDocs.slice(0, 10);
388
+ for (const d of topDocs) {
389
+ docRouting.push({ need: d.label, file: `docs/${d.name}` });
390
+ }
391
+ if (allDocs.length > 10) {
392
+ docRouting.push({ need: `... and ${allDocs.length - 10} more`, file: "docs/" });
393
+ }
394
+ }
395
+ const docRoutingTable = docRouting.length > 0
396
+ ? docRouting.map(d => `| ${d.need} | \`${d.file}\` |`).join("\n")
397
+ : "| (no docs found) | |";
398
+
399
+ // Environment section from rungate.json
400
+ let envSection = "";
401
+ if (harness) {
402
+ const lines: string[] = ["## Environment\n"];
403
+ if (harness.dev) {
404
+ lines.push("**Dev:**");
405
+ if (harness.dev.start) lines.push(`- Start: \`${harness.dev.start}\``);
406
+ if (harness.dev.uiBase) lines.push(`- UI: ${harness.dev.uiBase}`);
407
+ if (harness.dev.apiBase) lines.push(`- API: ${harness.dev.apiBase}`);
408
+ if (harness.dev.testCmd) lines.push(`- Test: \`${harness.dev.testCmd}\``);
409
+ }
410
+ if (harness.prod) {
411
+ lines.push("\n**Prod:**");
412
+ if (harness.prod.rebuild) lines.push(`- Deploy: \`${harness.prod.rebuild}\``);
413
+ if (harness.prod.apiBase) lines.push(`- API: ${harness.prod.apiBase}`);
414
+ if (harness.prod.smokeTest) lines.push(`- Smoke: \`${harness.prod.smokeTest}\``);
415
+ }
416
+ if (harness.pages && Object.keys(harness.pages).length > 0) {
417
+ lines.push("\n**Pages:**\n");
418
+ lines.push("| Page | Path |");
419
+ lines.push("|------|------|");
420
+ for (const [path, label] of Object.entries(harness.pages)) {
421
+ lines.push(`| ${label} | ${path} |`);
422
+ }
423
+ }
424
+ envSection = lines.join("\n");
425
+ }
426
+
427
+ // Consumers from rungate.json
428
+ const consumers = harness?.consumers || [];
429
+ const consumerSection = consumers.length > 0
430
+ ? `## Consumers (${consumers.length})\n\n${consumers.map((c: string) => `- ${c}`).join("\n")}\n\nCheck cascade impact when modifying shared modules.`
431
+ : "";
432
+
433
+ // CODE-MAP reference
434
+ const codeMapRef = existsSync(join(projectPath, "CODE-MAP.md"))
435
+ ? "| `CODE-MAP.md` | Auto-generated codebase map (routes, components, modules, health) | Understanding codebase structure |"
436
+ : "";
437
+
438
+ return `# ${pkgName}
439
+
440
+ ## Project Identity
441
+
442
+ ${identity}
443
+ ${repoLine}
444
+
445
+ ## Hard Constraints (non-inferrable — agents cannot discover these from code)
446
+
447
+ ${existingHardConstraints || `<!-- Add project-specific rules that agents can't figure out from reading code.
448
+ Examples: intentional anti-patterns, safety boundaries, deploy restrictions.
449
+ Delete this comment after filling in. -->`}
450
+
451
+ ## Key Files
452
+
453
+ | File | What | When to Read |
454
+ |------|------|--------------|
455
+ ${keyFilesTable}
456
+ ${codeMapRef}
457
+
458
+ ## Documentation Routing
459
+
460
+ | I need to understand... | Read |
461
+ |------------------------|------|
462
+ ${docRoutingTable}
463
+
464
+ ## Where to Create Things
465
+
466
+ | Type | Location | Notes |
467
+ |------|----------|-------|
468
+ | Specs | \`specs/\` | Must have YAML frontmatter with \`doc-type: spec\` |
469
+ | ADRs | \`docs/adr/\` | Must have \`doc-type: adr\` in frontmatter |
470
+ | Guides/docs | \`docs/\` | Must have \`doc-type: guide\` in frontmatter |
471
+ | Source code | \`src/\` | Follow existing module structure |
472
+ | Tests | \`test/\` | Mirror source structure |
473
+
474
+ ## Specs
475
+
476
+ All specs live in \`specs/\` with YAML frontmatter declaring \`testable: true/false\`.
477
+
478
+ | Spec | Testable | Governs |
479
+ |------|----------|---------|
480
+ ${specsTable}
481
+
482
+ ## Tests
483
+
484
+ \`\`\`bash
485
+ ${testCmd}
486
+ \`\`\`
487
+
488
+ | Category | File | What |
489
+ |----------|------|------|
490
+ ${testsTable}
491
+
492
+ ## Commands
493
+
494
+ | Action | Command |
495
+ |--------|---------|
496
+ | Install | \`bun install\` |
497
+ | Test | \`${testCmd}\` |
498
+ | Type check | \`bunx tsc --noEmit\` |
499
+ | Conformity | \`bun test test/scaffold-conformity.test.ts\` |
500
+ | Sync spec tests | \`bunx rungate sync-tests .\` |
501
+ | Create spec | \`bunx rungate create-spec "title"\` |
502
+ | Create ADR | \`bunx rungate create-adr "title"\` |
503
+ | Extract constraints | \`bunx rungate extract-constraints .\` |
504
+ | Check findings | \`cat .rungate/conformity-findings.json\` |
505
+ | Re-scaffold | \`bun ~/Projects/rungate/scripts/scaffold-project.ts .\` |
506
+
507
+ ${envSection}
508
+
509
+ ${consumerSection}
510
+
511
+ ## Workflow
512
+ ${repoLine}${makeTargets}
513
+ - **Test:** \`${testCmd}\`
514
+ - **Conformity:** Imported from rungate. \`bun update rungate && bun test\` to sync.
515
+
516
+ ## Quick Reference
517
+
518
+ 1. AGENTS.md is the single entry point — everything routes from here
519
+ 2. CODE-MAP.md has the auto-generated codebase map — routes, components, modules, health
520
+ 3. Specs in specs/ are source of truth — testable: true specs auto-generate tests
521
+ 4. \`bun test\` runs conformity + domain tests
522
+ 5. Agent briefings in .claude/agents/ are auto-generated — run bootstrap to refresh
523
+ 6. After test failures, read \`.rungate/conformity-findings.json\` for structured findings with fix commands
524
+
525
+ ## Harness-Managed Files
526
+
527
+ These files are managed by rungate and regenerated on re-scaffold. **Do not edit them directly.**
528
+
529
+ | File | How to customize | What NOT to do |
530
+ |------|-----------------|----------------|
531
+ | \`.github/workflows/ci.yml\` | Set \`ci\` fields in \`.claude/rungate.json\` | Don't edit the YAML |
532
+ | \`.github/workflows/gates.yml\` | Settings from \`.claude/rungate.json\` | Don't edit the YAML |
533
+ | \`.claude/agents/*.md\` | Settings from \`.claude/rungate.json\` | Don't edit briefs |
534
+ | \`test/scaffold-conformity.test.ts\` | Runs automatically | Don't edit |
535
+ | \`CODE-MAP.md\` | Auto-generated from code scan | Don't edit |
536
+ ${refSection}`;
537
+ }
538
+
539
+
540
+ function generateConformityTest(): string {
541
+ return `import { resolve } from "path";
542
+ import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runPackageValidation, runTsconfigValidation } from "rungate/lib/conformity";
543
+
544
+ const ROOT = resolve(import.meta.dir, "..");
545
+
546
+ runScaffoldConformity(ROOT);
547
+ runSpecDiscovery(ROOT);
548
+ runSpecDrift(ROOT);
549
+ runDocHygiene(ROOT);
550
+ runFallowCheck(ROOT, { warnOnly: true });
551
+ runAgentFileValidation(ROOT);
552
+ runPackageValidation(ROOT);
553
+ runTsconfigValidation(ROOT);
554
+ `;
555
+ }
556
+
557
+ function addFrontmatterToSpecs(specsDir: string): void {
558
+ if (!existsSync(specsDir)) return;
559
+
560
+ for (const file of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
561
+ const filePath = join(specsDir, file);
562
+ const content = readFileSync(filePath, "utf-8");
563
+
564
+ // Skip files that already have frontmatter
565
+ if (content.startsWith("---\n")) {
566
+ continue;
567
+ }
568
+
569
+ const today = new Date().toISOString().split("T")[0];
570
+ const frontmatter = `---
571
+ doc-type: spec
572
+ status: draft
573
+ owner: TODO
574
+ created: ${today}
575
+ updated: ${today}
576
+ governs: TODO — describe what this spec governs
577
+ testable: false
578
+ ---
579
+
580
+ `;
581
+ writeFileSync(filePath, frontmatter + content);
582
+ actions.push(`UPDATED: specs/${file} (added frontmatter)`);
583
+ }
584
+ }
585
+
586
+ function addPaiHarnessDevDep(root: string): void {
587
+ const pkgPath = join(root, "package.json");
588
+ if (!existsSync(pkgPath)) return;
589
+
590
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
591
+ if (!pkg.devDependencies) {
592
+ pkg.devDependencies = {};
593
+ }
594
+
595
+ if (pkg.devDependencies["rungate"] || pkg.name === "rungate") {
596
+ actions.push("SKIP: rungate devDep (already present or self-reference)");
597
+ return;
598
+ }
599
+
600
+ const harnessRelative = require("path").relative(root, join(__dirname, ".."));
601
+ pkg.devDependencies["rungate"] = `file:${harnessRelative}`;
602
+
603
+ // Add test script if missing
604
+ if (!pkg.scripts) {
605
+ pkg.scripts = {};
606
+ }
607
+ if (!pkg.scripts.test) {
608
+ pkg.scripts.test = "bun test";
609
+ }
610
+
611
+ writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
612
+ actions.push("CREATED: rungate devDep in package.json");
613
+ }
614
+
615
+ function generateAgentBriefs(root: string): void {
616
+ const agentsDir = join(root, ".claude", "agents");
617
+ safeDir(agentsDir, ".claude/agents");
618
+
619
+ const harness = loadHarnessConfig(root);
620
+ const devUi = harness?.dev?.uiBase || null;
621
+ const devApi = harness?.dev?.apiBase || null;
622
+ const testCmd = harness?.dev?.testCmd || "bun test";
623
+ const typeCheck = harness?.dev?.typeCheck || "bunx tsc --noEmit";
624
+ const pages = harness?.pages || {};
625
+ const pagesTable = Object.keys(pages).length > 0
626
+ ? "### Pages Map\n\n| Path | Page |\n|------|------|\n" +
627
+ Object.entries(pages).map(([k, v]) => `| ${v} | ${k} |`).join("\n")
628
+ : "";
629
+
630
+ // Pull project identity from AGENTS.md or README
631
+ let projectIdentity = "";
632
+ const agentsMdPath = join(root, "AGENTS.md");
633
+ if (existsSync(agentsMdPath)) {
634
+ const content = readFileSync(agentsMdPath, "utf-8");
635
+ const identityMatch = content.match(/## Project Identity\n\n([\s\S]*?)(?=\n##|\n\|)/);
636
+ if (identityMatch) projectIdentity = identityMatch[1].trim();
637
+ }
638
+ if (!projectIdentity) {
639
+ const readmePath = join(root, "README.md");
640
+ if (existsSync(readmePath)) {
641
+ const readme = readFileSync(readmePath, "utf-8");
642
+ const paragraphs = readme.split(/\n\n+/).filter(p => !p.startsWith("#") && p.trim().length > 20);
643
+ if (paragraphs.length > 0) projectIdentity = paragraphs[0].replace(/\n/g, " ").trim();
644
+ }
645
+ }
646
+ const identitySection = projectIdentity ? `## Project\n\n${projectIdentity}\n` : "";
647
+
648
+ const architecturalTruths = "";
649
+
650
+ // Pull directory structure for Marcus
651
+ const srcDirs = ["src", "dashboard/src", "lib", "gates", "hooks"].filter(d => existsSync(join(root, d)));
652
+ const dirList = srcDirs.length > 0 ? srcDirs.map(d => `- \`${d}/\``).join("\n") : "";
653
+
654
+ // Pull consumers from harness config
655
+ const consumers = harness?.consumers || [];
656
+ const consumerNote = consumers.length > 0
657
+ ? `\n## Consumers (${consumers.length})\n\n${consumers.map((c: string) => `- ${c}`).join("\n")}\n\nCheck cascade impact when modifying shared modules.\n`
658
+ : "";
659
+
660
+ const quinnBrief = `---
661
+ name: quinn
662
+ description: QA engineer — tests as a brand-new user using Playwright MCP tools
663
+ tools: [Bash, Read, mcp__playwright__*]
664
+ model: sonnet
665
+ ---
666
+
667
+ You are Quinn Torres, QA engineer. You test as a brand-new user who has never seen this app before.
668
+
669
+ ${identitySection}## Core Principles
670
+ - Verify before asserting — try it, then report what happened
671
+ - Never report PASS with known gaps — list every gap
672
+ - Read AGENTS.md FIRST — project identity, constraints, commands
673
+ - Run \`bun test\` after every change — conformity is mechanical
674
+ - Null in config means skip — never guess values
675
+ - Research before guessing — use available tools
676
+
677
+ ## Always Do
678
+ - Run \`bun test\` after every change
679
+ - Read AGENTS.md before starting work
680
+ - Verify before asserting
681
+
682
+ ## Ask First
683
+ - Modifying files outside the brief's listed files
684
+ - Adding new dependencies
685
+ - Changing public interfaces
686
+
687
+ ## Never Do
688
+ - Self-attest evidence (tier F)
689
+ - Skip ACs without rationale
690
+ - Commit secrets or credentials
691
+
692
+ ## Methodology
693
+ - Read \`node_modules/rungate/prompts/quinn-journey-decision-tree.md\` for UI testing methodology
694
+
695
+ ## Context (MANDATORY — read before testing)
696
+
697
+ 1. **AGENTS.md** — project identity, critical rules, documentation routing
698
+ 2. **CODE-MAP.md § Page → Component Map** — which components are on each page (your test targets)
699
+ 3. **CODE-MAP.md § API Routes** — endpoint inventory for API-level checks
700
+ 4. **node_modules/rungate/prompts/quinn-ui-brief.md** — structured UI testing methodology
701
+
702
+ ## Environment
703
+
704
+ ${devUi ? `- **Dev UI:** ${devUi}` : "- **Dev UI:** not configured — check .claude/rungate.json"}
705
+ ${devApi ? `- **Dev API:** ${devApi}` : "- **Dev API:** not configured — check .claude/rungate.json"}
706
+ - **Viewport:** 1280x720 (set via browser_resize FIRST)
707
+
708
+ ${pagesTable}
709
+
710
+ ## Pre-conditions (GATE — stop if any fail)
711
+
712
+ 1. Set viewport: browser_resize(1280, 720)
713
+ 2. Navigate to target URL
714
+ 3. browser_snapshot() — verify page loaded (no error banners, data present)
715
+ If pre-conditions fail → report FAIL immediately, do NOT proceed.
716
+
717
+ ## Tools
718
+
719
+ - browser_snapshot() for ALL assertions (text, fast, cheap)
720
+ - browser_take_screenshot() ONLY for evidence after assertions pass
721
+ - Never guess URLs — read .claude/rungate.json pages map
722
+
723
+ ## Anti-checks (ALWAYS run)
724
+
725
+ - No "undefined" or "null" rendered as visible text
726
+ - No stuck loading spinners
727
+ - No error banners or toast messages
728
+ - Interactive elements respond to clicks
729
+
730
+ ## Report
731
+
732
+ - PASS/FAIL per AC with snapshot/screenshot evidence
733
+ - Anti-check results
734
+ - Any new findings flagged as blocking or non-blocking
735
+ `;
736
+
737
+ const marcusBrief = `---
738
+ name: marcus
739
+ description: Principal engineer — implements code changes with TDD, writes tests, commits
740
+ tools: [Bash, Read, Write, Edit]
741
+ model: opus
742
+ ---
743
+
744
+ You are Marcus Webb, principal engineer. You implement code changes, write tests, and commit.
745
+
746
+ ${identitySection}## Core Principles
747
+ - Verify before asserting — try it, then report what happened
748
+ - Never report PASS with known gaps — list every gap
749
+ - Read AGENTS.md FIRST — project identity, constraints, commands
750
+ - Run \`bun test\` after every change — conformity is mechanical
751
+ - Null in config means skip — never guess values
752
+ - Research before guessing — use available tools
753
+
754
+ ## Always Do
755
+ - Run \`bun test\` after every change
756
+ - Read AGENTS.md before starting work
757
+ - Verify before asserting
758
+
759
+ ## Ask First
760
+ - Modifying files outside the brief's listed files
761
+ - Adding new dependencies
762
+ - Changing public interfaces
763
+
764
+ ## Never Do
765
+ - Self-attest evidence (tier F)
766
+ - Skip ACs without rationale
767
+ - Commit secrets or credentials
768
+
769
+ ## Methodology
770
+ - Read \`node_modules/rungate/prompts/coding-principles.md\` for coding standards
771
+ - Read \`node_modules/rungate/prompts/testing-strategy.md\` for testing approach
772
+
773
+ ## Context (MANDATORY — read before coding)
774
+
775
+ 1. **AGENTS.md** — project identity, critical rules, documentation routing
776
+ 2. **CODE-MAP.md § Module Dependencies** — import chains for cascade impact analysis
777
+ 3. **CODE-MAP.md § Code Health** — circular deps and unused files to avoid
778
+
779
+ ${dirList ? `## Source Directories\n\n${dirList}\n` : ""}${consumerNote}## Before writing code
780
+ 2. Read every file listed in the brief's **Files** section
781
+ 3. Read the **Governing Spec** if one is cited
782
+ 4. Run existing tests to establish baseline: \`${testCmd}\`
783
+
784
+ ## While coding
785
+
786
+ - TDD: write the failing test first, then the implementation
787
+ - Deep modules, thin consumers: shared logic in lib/, consumers call one function
788
+ - No hardcoded values — use config or environment variables
789
+ - All thresholds configurable
790
+
791
+ ## Before reporting done
792
+
793
+ 1. Run \`${testCmd}\` — all tests pass
794
+ 2. Run \`${typeCheck}\` — no type errors
795
+ 3. Run \`npx fallow audit\` — no new dead code or circular deps introduced
796
+ 4. Commit all changes referencing the issue number
797
+ 5. Push branch with -u flag
798
+
799
+ ## Rules
800
+
801
+ - Never run \`make rebuild\` — only the DA does that
802
+ - Dev server: \`make dev-all\`${devApi ? ` starts API (${devApi})` : ""}${devUi ? ` and UI (${devUi})` : ""}
803
+ `;
804
+
805
+ const rookBrief = `---
806
+ name: rook
807
+ description: Security engineer — scans changed files for vulnerabilities
808
+ tools: [Bash, Read]
809
+ model: sonnet
810
+ ---
811
+
812
+ You are Rook Blackburn, security engineer. You scan changed files for vulnerabilities.
813
+
814
+ ${identitySection}## Core Principles
815
+ - Verify before asserting — try it, then report what happened
816
+ - Never report PASS with known gaps — list every gap
817
+ - Read AGENTS.md FIRST — project identity, constraints, commands
818
+ - Run \`bun test\` after every change — conformity is mechanical
819
+ - Null in config means skip — never guess values
820
+ - Research before guessing — use available tools
821
+
822
+ ## Always Do
823
+ - Run \`bun test\` after every change
824
+ - Read AGENTS.md before starting work
825
+ - Verify before asserting
826
+
827
+ ## Ask First
828
+ - Modifying files outside the brief's listed files
829
+ - Adding new dependencies
830
+ - Changing public interfaces
831
+
832
+ ## Never Do
833
+ - Self-attest evidence (tier F)
834
+ - Skip ACs without rationale
835
+ - Commit secrets or credentials
836
+
837
+ ## Context (MANDATORY — read before scanning)
838
+
839
+ 1. **AGENTS.md** — project identity, critical rules, security baseline routing
840
+ 2. **CODE-MAP.md § Code Health** — circular deps and unused files (vulnerability surface)
841
+ 3. **CODE-MAP.md § Module Dependencies** — data flow chains for injection analysis
842
+
843
+ ## What you scan
844
+
845
+ 1. All files changed in the current branch vs main
846
+ 2. Pattern siblings — files that share imports or data flow with changed files
847
+ 3. Configuration files touched by the change
848
+
849
+ ## What you look for
850
+
851
+ - Injection vulnerabilities (XSS, SQL injection, command injection)
852
+ - Authentication/authorization bypasses
853
+ - Sensitive data exposure (credentials, tokens, PII in logs)
854
+ - Insecure defaults or missing input validation
855
+ - Path traversal in file operations
856
+ - Unsafe deserialization
857
+
858
+ ## Report
859
+
860
+ - CLEAR or FINDINGS with severity (CRITICAL/HIGH/MEDIUM/LOW)
861
+ - Each finding: file, line, vulnerability type, remediation
862
+ - False positives noted as such with reasoning
863
+
864
+ ## Rules
865
+
866
+ - Never modify source code — report only
867
+ - Never touch production config files
868
+ - Never run \`make rebuild\`
869
+ `;
870
+
871
+ const serenaBrief = `---
872
+ name: serena
873
+ description: Software architect — structural decisions, ADRs, module boundary review
874
+ tools: [Bash, Read]
875
+ model: opus
876
+ ---
877
+
878
+ You are Serena Blackwood, software architect. You make structural decisions and write ADRs.
879
+
880
+ ${identitySection}## Core Principles
881
+ - Verify before asserting — try it, then report what happened
882
+ - Never report PASS with known gaps — list every gap
883
+ - Read AGENTS.md FIRST — project identity, constraints, commands
884
+ - Run \`bun test\` after every change — conformity is mechanical
885
+ - Null in config means skip — never guess values
886
+ - Research before guessing — use available tools
887
+
888
+ ## Always Do
889
+ - Run \`bun test\` after every change
890
+ - Read AGENTS.md before starting work
891
+ - Verify before asserting
892
+
893
+ ## Ask First
894
+ - Modifying files outside the brief's listed files
895
+ - Adding new dependencies
896
+ - Changing public interfaces
897
+
898
+ ## Never Do
899
+ - Self-attest evidence (tier F)
900
+ - Skip ACs without rationale
901
+ - Commit secrets or credentials
902
+
903
+ ## Context (MANDATORY — read before designing)
904
+
905
+ 1. **AGENTS.md** — project identity, critical rules, documentation routing
906
+ 2. **CODE-MAP.md § Module Dependencies** — import chains for boundary analysis
907
+ 3. **CODE-MAP.md § Directory Structure** — module inventory for architecture review
908
+
909
+ ## What you do
910
+
911
+ 1. Evaluate proposed architectural changes against existing ADRs
912
+ 2. Write new ADRs for decisions that don't have one
913
+ 3. Review module boundaries and dependency direction
914
+ 4. Assess scalability, maintainability, and complexity tradeoffs
915
+
916
+ ## Architecture principles
917
+
918
+ - Deep modules, thin consumers
919
+ - Single chokepoint for mutations
920
+ - Config-driven over hardcoded
921
+ - Shared logic in lib/, never duplicated across consumers
922
+ - Schema validation at system boundaries
923
+
924
+ ## Report
925
+
926
+ - ADR document for new decisions
927
+ - APPROVED or CONCERNS for reviews
928
+ - Specific module/file recommendations, not abstract guidance
929
+
930
+ ## Rules
931
+
932
+ - Never write implementation code — provide specs for Marcus
933
+ - Never run builds, tests, or deployments
934
+ `;
935
+
936
+ const aditiBrief = `---
937
+ name: aditi
938
+ description: UX/UI designer — component specs, visual review, accessibility
939
+ tools: [Bash, Read]
940
+ model: sonnet
941
+ ---
942
+
943
+ You are Aditi Sharma, UX/UI designer. You design component specs and review UI implementations.
944
+
945
+ ${identitySection}## Core Principles
946
+ - Verify before asserting — try it, then report what happened
947
+ - Never report PASS with known gaps — list every gap
948
+ - Read AGENTS.md FIRST — project identity, constraints, commands
949
+ - Run \`bun test\` after every change — conformity is mechanical
950
+ - Null in config means skip — never guess values
951
+ - Research before guessing — use available tools
952
+
953
+ ## Always Do
954
+ - Run \`bun test\` after every change
955
+ - Read AGENTS.md before starting work
956
+ - Verify before asserting
957
+
958
+ ## Ask First
959
+ - Modifying files outside the brief's listed files
960
+ - Adding new dependencies
961
+ - Changing public interfaces
962
+
963
+ ## Never Do
964
+ - Self-attest evidence (tier F)
965
+ - Skip ACs without rationale
966
+ - Commit secrets or credentials
967
+
968
+ ## Context (MANDATORY — read before designing)
969
+
970
+ 1. **AGENTS.md** — project identity, critical rules, documentation routing
971
+ 2. **CODE-MAP.md § Page → Component Map** — which components render on each page
972
+ 3. **CODE-MAP.md § React Components** — full component inventory
973
+ 4. Read any visual specs or mockups referenced in the brief
974
+
975
+ ## What you do
976
+
977
+ 1. Review proposed UI changes against design principles
978
+ 2. Create component specs with layout, spacing, typography, color
979
+ 3. Assess visual hierarchy and information density
980
+ 4. Evaluate accessibility (contrast, focus order, screen reader labels)
981
+
982
+ ## Design principles
983
+
984
+ - shadcn/ui component library as the base
985
+ - Consistent spacing scale (4px base)
986
+ - Clear visual hierarchy — primary action obvious
987
+ - Accessible: WCAG 2.1 AA minimum
988
+
989
+ ## Report
990
+
991
+ - APPROVED or REVISION_NEEDED with specific changes
992
+ - Mockups as HTML when proposing new layouts
993
+ - Annotated screenshots when reviewing existing UI
994
+ - Specific CSS values, not vague directions
995
+
996
+ ## Rules
997
+
998
+ - Never modify source code directly — provide specs for Marcus
999
+ - Never run builds or tests
1000
+ `;
1001
+
1002
+ // Agent briefs always regenerate — they're harness-owned templates, not user-customized
1003
+ for (const [name, content] of [
1004
+ ["quinn.md", quinnBrief], ["marcus.md", marcusBrief], ["rook.md", rookBrief],
1005
+ ["serena.md", serenaBrief], ["aditi.md", aditiBrief],
1006
+ ] as const) {
1007
+ const p = join(agentsDir, name);
1008
+ writeFileSync(p, content);
1009
+ actions.push(existsSync(p) ? `UPDATED: .claude/agents/${name}` : `CREATED: .claude/agents/${name}`);
1010
+ }
1011
+ }
1012
+
1013
+ function refreshAgentsMd(root: string, type: ProjectType): void {
1014
+ const agentsPath = join(root, "AGENTS.md");
1015
+ const content = readFileSync(agentsPath, "utf-8");
1016
+ const issues: string[] = [];
1017
+
1018
+ // Check all file references resolve
1019
+ const linkPattern = /`([^`]+\.(md|json|ts|js|tsx|yml|yaml))`/g;
1020
+ let match;
1021
+ while ((match = linkPattern.exec(content)) !== null) {
1022
+ const ref = match[1];
1023
+ if (ref.startsWith("http") || ref.includes("*")) continue;
1024
+ if (!existsSync(join(root, ref))) {
1025
+ issues.push(`BROKEN: ${ref} (referenced in AGENTS.md but doesn't exist)`);
1026
+ }
1027
+ }
1028
+
1029
+ // Check staleness of referenced files
1030
+ const staleFiles: string[] = [];
1031
+ const linkPattern2 = /`([^`]+\.md)`/g;
1032
+ while ((match = linkPattern2.exec(content)) !== null) {
1033
+ const ref = match[1];
1034
+ if (!existsSync(join(root, ref))) continue;
1035
+ try {
1036
+ const result = Bun.spawnSync(["git", "-C", root, "log", "-1", "--format=%ci", "--", ref], { timeout: 5_000 });
1037
+ const dateStr = result.stdout.toString().trim().split(" ")[0];
1038
+ if (dateStr) {
1039
+ const daysSince = (Date.now() - new Date(dateStr).getTime()) / (1000 * 60 * 60 * 24);
1040
+ const isAdr = ref.includes('docs/adr/') || /ADR/i.test(ref);
1041
+ if (isAdr) continue;
1042
+ const threshold = ref.startsWith('specs/') ? 90 : 180;
1043
+ if (daysSince > threshold) staleFiles.push(`${ref} (${Math.floor(daysSince)}d old)`);
1044
+ }
1045
+ } catch (e: unknown) { console.warn('Staleness check failed for', ref, (e as Error).message); }
1046
+ }
1047
+
1048
+ // Check specs/ table matches actual specs
1049
+ const specsDir = join(root, "specs");
1050
+ if (existsSync(specsDir)) {
1051
+ const actualSpecs = readdirSync(specsDir).filter(f => f.endsWith(".md"));
1052
+ const listedInAgents = actualSpecs.filter(f => content.includes(f));
1053
+ const unlisted = actualSpecs.filter(f => !content.includes(f));
1054
+ if (unlisted.length > 0) {
1055
+ issues.push(`UNLISTED specs: ${unlisted.join(", ")} (in specs/ but not in AGENTS.md)`);
1056
+ }
1057
+ }
1058
+
1059
+ // Check CODE-MAP.md is referenced
1060
+ if (existsSync(join(root, "CODE-MAP.md")) && !content.includes("CODE-MAP")) {
1061
+ issues.push("CODE-MAP.md exists but not referenced in AGENTS.md routing table");
1062
+ }
1063
+
1064
+ if (issues.length > 0 || staleFiles.length > 0) {
1065
+ console.log("\n AGENTS.md audit:");
1066
+ for (const issue of issues) console.log(` ⚠ ${issue}`);
1067
+ if (staleFiles.length > 0) {
1068
+ console.log(` ⚠ STALE (>90 days): ${staleFiles.join(", ")}`);
1069
+ }
1070
+ actions.push(`AUDITED: AGENTS.md (${issues.length} broken refs, ${staleFiles.length} stale docs)`);
1071
+ } else {
1072
+ actions.push("AUDITED: AGENTS.md (all references valid, no stale docs)");
1073
+ }
1074
+ }
1075
+
1076
+ function generateOrAuditProjectHarness(root: string): void {
1077
+ const harnessPath = join(root, ".claude", "rungate.json");
1078
+
1079
+ // Scan pages from route files (App.tsx, routes.ts, etc.) in src/
1080
+ const scannedPages: Record<string, string> = {};
1081
+ const routeFiles = ["src/App.tsx", "src/routes.tsx", "src/index.tsx", "src/app.tsx"]
1082
+ .map(f => join(root, f))
1083
+ .filter(f => existsSync(f));
1084
+ for (const routeFile of routeFiles) {
1085
+ const content = readFileSync(routeFile, "utf-8");
1086
+ const routePattern = /path="([^"]+)"/g;
1087
+ let m;
1088
+ while ((m = routePattern.exec(content)) !== null) {
1089
+ const path = m[1];
1090
+ if (path === "*" || path.includes(":")) continue;
1091
+ const label = path.split("/").pop() || "home";
1092
+ scannedPages[path] = label;
1093
+ }
1094
+ }
1095
+
1096
+ // Scan test commands from package.json
1097
+ const pkgPath = join(root, "package.json");
1098
+ let testCmd = "bun test";
1099
+ let typeCheckCmd = "bunx tsc --noEmit";
1100
+ if (existsSync(pkgPath)) {
1101
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
1102
+ if (pkg.scripts?.test) testCmd = pkg.scripts.test;
1103
+ if (pkg.scripts?.typecheck) typeCheckCmd = pkg.scripts.typecheck;
1104
+ }
1105
+
1106
+ // Scan port from Makefile
1107
+ const makefile = join(root, "Makefile");
1108
+ const detectedPort = (() => {
1109
+ if (!existsSync(makefile)) return null;
1110
+ const content = readFileSync(makefile, "utf-8");
1111
+ const portMatch = content.match(/(?:--port\s+|PORT=|-p\s+|:)(\d{4,5})/);
1112
+ return portMatch ? parseInt(portMatch[1]) : null;
1113
+ })();
1114
+
1115
+ // Scan envVars from .env.example
1116
+ const envVars = (() => {
1117
+ const envPath = join(root, ".env.example");
1118
+ if (!existsSync(envPath)) return null;
1119
+ const content = readFileSync(envPath, "utf-8");
1120
+ return content.split("\n")
1121
+ .filter(line => line.trim() && !line.startsWith("#"))
1122
+ .map(line => line.split("=")[0].trim())
1123
+ .filter(Boolean);
1124
+ })();
1125
+
1126
+ // Detect git remote for repo
1127
+ let repo = "";
1128
+ try {
1129
+ const result = Bun.spawnSync(["git", "-C", root, "remote", "get-url", "origin"], { timeout: 5_000 });
1130
+ repo = result.stdout.toString().trim()
1131
+ .replace(/\.git$/, "")
1132
+ .replace("git@github.com:", "")
1133
+ .replace("https://github.com/", "");
1134
+ } catch {}
1135
+
1136
+ // Scan for consumer modules (files in src/ that are route handlers or generators)
1137
+ const scannedConsumers: string[] = [];
1138
+ const srcDir = join(root, "src");
1139
+ if (existsSync(srcDir)) {
1140
+ const consumerPatterns = ["-routes.ts", "-generator.ts", "-plan.ts", "-intel.ts"];
1141
+ for (const f of readdirSync(srcDir).filter(f => f.endsWith(".ts"))) {
1142
+ const content = readFileSync(join(srcDir, f), "utf-8");
1143
+ const isConsumer = consumerPatterns.some(p => f.includes(p)) ||
1144
+ content.includes("app.get(") || content.includes("app.post(") ||
1145
+ content.includes("router.") || content.includes("export default");
1146
+ if (isConsumer) {
1147
+ scannedConsumers.push(f.replace(/\.ts$/, "").replace(/-routes|-generator/, ""));
1148
+ }
1149
+ }
1150
+ }
1151
+
1152
+ if (existsSync(harnessPath)) {
1153
+ // Audit existing — compare scanned vs declared
1154
+ const existing = JSON.parse(readFileSync(harnessPath, "utf-8"));
1155
+ const issues: string[] = [];
1156
+
1157
+ // Check pages drift
1158
+ const declaredPages = Object.keys(existing.pages || {});
1159
+ const scannedPaths = Object.keys(scannedPages);
1160
+ const missingPages = scannedPaths.filter(p => !declaredPages.some(d => existing.pages[d] === p || d === p));
1161
+ if (missingPages.length > 0) {
1162
+ issues.push(`PAGES: ${missingPages.length} routes in code not in rungate.json: ${missingPages.slice(0, 5).join(", ")}`);
1163
+ }
1164
+
1165
+ if (issues.length > 0) {
1166
+ console.log("\n rungate.json audit:");
1167
+ for (const issue of issues) console.log(` ⚠ ${issue}`);
1168
+ actions.push(`AUDITED: rungate.json (${issues.length} gaps)`);
1169
+ } else {
1170
+ actions.push("AUDITED: rungate.json (aligned with code)");
1171
+ }
1172
+ } else {
1173
+ // Read harness version from own package.json
1174
+ let harnessVersion = "unknown";
1175
+ try {
1176
+ const harnessPkg = JSON.parse(readFileSync(join(__dirname, "..", "package.json"), "utf-8"));
1177
+ harnessVersion = harnessPkg.version || "unknown";
1178
+ } catch {}
1179
+
1180
+ // Generate new rungate.json
1181
+ const config = {
1182
+ "$schema": "rungate",
1183
+ harnessVersion,
1184
+ scaffoldedAt: new Date().toISOString(),
1185
+ project: basename(root),
1186
+ repo,
1187
+ issueRepo: repo,
1188
+ dev: {
1189
+ start: existsSync(makefile) ? "make dev-all" : "bun run dev",
1190
+ apiBase: detectedPort ? `http://localhost:${detectedPort}` : null,
1191
+ uiBase: null as string | null,
1192
+ testCmd,
1193
+ typeCheck: typeCheckCmd,
1194
+ },
1195
+ prod: {
1196
+ rebuild: existsSync(makefile) ? "make rebuild" : undefined,
1197
+ apiBase: null as string | null,
1198
+ },
1199
+ pages: scannedPages,
1200
+ consumers: [...new Set(scannedConsumers)].sort(),
1201
+ envVars: envVars || [],
1202
+ ci: {
1203
+ runner: "ubuntu-latest",
1204
+ bunVersion: "latest",
1205
+ branches: ["main"],
1206
+ },
1207
+ contextDocs: {},
1208
+ };
1209
+
1210
+ const dir = join(root, ".claude");
1211
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1212
+ const targetPath = join(root, ".claude", "rungate.json");
1213
+ writeFileSync(targetPath, JSON.stringify(config, null, 2) + "\n");
1214
+ actions.push(`CREATED: .claude/rungate.json (${Object.keys(scannedPages).length} pages, ${scannedConsumers.length} consumers)`);
1215
+ }
1216
+ }
1217
+
1218
+ function loadHarnessConfig(root: string): any {
1219
+ const p = join(root, ".claude", "rungate.json");
1220
+ if (!existsSync(p)) return null;
1221
+ try { return JSON.parse(readFileSync(p, "utf-8")); } catch { return null; }
1222
+ }
1223
+
1224
+ function generateCodeMap(root: string): void {
1225
+ const codeMapPath = join(root, "CODE-MAP.md");
1226
+
1227
+ // Check staleness: skip if <14 days old AND <50 commits since last scan
1228
+ if (existsSync(codeMapPath)) {
1229
+ const content = readFileSync(codeMapPath, "utf-8");
1230
+ const updatedMatch = content.match(/^updated:\s*(\d{4}-\d{2}-\d{2})/m);
1231
+ if (updatedMatch) {
1232
+ const lastScan = new Date(updatedMatch[1]);
1233
+ const daysSince = (Date.now() - lastScan.getTime()) / (1000 * 60 * 60 * 24);
1234
+ if (daysSince < 14) {
1235
+ // Check commit count since last scan
1236
+ const gitResult = Bun.spawnSync(
1237
+ ["git", "-C", root, "rev-list", "--count", `--since=${updatedMatch[1]}`, "HEAD"],
1238
+ { timeout: 5_000 }
1239
+ );
1240
+ const commits = parseInt(gitResult.stdout.toString().trim()) || 0;
1241
+ if (commits < 50) {
1242
+ actions.push(`SKIP: CODE-MAP.md (${daysSince.toFixed(0)}d old, ${commits} commits — still fresh)`);
1243
+ return;
1244
+ }
1245
+ }
1246
+ }
1247
+ }
1248
+
1249
+ // Run generate-code-map.ts
1250
+ const scriptPath = join(__dirname, "generate-code-map.ts");
1251
+ if (!existsSync(scriptPath)) {
1252
+ actions.push("SKIP: CODE-MAP.md (generate-code-map.ts not found)");
1253
+ return;
1254
+ }
1255
+
1256
+ const result = Bun.spawnSync(["bun", scriptPath, root], { timeout: 60_000 });
1257
+ if (result.exitCode === 0) {
1258
+ actions.push(existsSync(codeMapPath) ? "UPDATED: CODE-MAP.md" : "CREATED: CODE-MAP.md");
1259
+ } else {
1260
+ actions.push("WARN: CODE-MAP.md generation failed");
1261
+ }
1262
+ }
1263
+
1264
+ function copySpecTemplateIfEmpty(specsDir: string): void {
1265
+ if (!existsSync(specsDir)) return;
1266
+ const specs = readdirSync(specsDir).filter(f => f.endsWith(".md") && f !== "SPEC-TEMPLATE.md");
1267
+ // Always copy/update the template
1268
+ const templatePath = join(__dirname, "..", "specs", "SPEC-TEMPLATE.md");
1269
+ if (!existsSync(templatePath)) {
1270
+ actions.push("SKIP: spec template (SPEC-TEMPLATE.md not found in harness)");
1271
+ return;
1272
+ }
1273
+
1274
+ const template = readFileSync(templatePath, "utf-8");
1275
+ writeFileSync(join(specsDir, "SPEC-TEMPLATE.md"), template);
1276
+ actions.push("CREATED: specs/SPEC-TEMPLATE.md (starter template)");
1277
+ }
1278
+
1279
+ function createGitignore(root: string): void {
1280
+ const gitignorePath = join(root, ".gitignore");
1281
+ const securityTemplate = `# Dependencies
1282
+ node_modules/
1283
+ .bun/
1284
+
1285
+ # Build output
1286
+ dist/
1287
+ build/
1288
+ *.tsbuildinfo
1289
+
1290
+ # Environment and secrets
1291
+ .env
1292
+ .env.*
1293
+ !.env.example
1294
+ *.pem
1295
+ *.key
1296
+ *.p12
1297
+ *.pfx
1298
+ credentials.json
1299
+ service-account*
1300
+ .secret*
1301
+
1302
+ # Harness working directory
1303
+ .rungate/
1304
+
1305
+ # IDE
1306
+ .vscode/
1307
+ .idea/
1308
+ *.swp
1309
+ *.swo
1310
+
1311
+ # OS
1312
+ .DS_Store
1313
+ Thumbs.db
1314
+
1315
+ # Test artifacts
1316
+ coverage/
1317
+ `;
1318
+
1319
+ if (existsSync(gitignorePath)) {
1320
+ const existing = readFileSync(gitignorePath, "utf-8");
1321
+ const required = [
1322
+ "node_modules", "dist", ".env", ".rungate",
1323
+ "*.pem", "*.key", "credentials.json", "service-account",
1324
+ ];
1325
+ const missing = required.filter(entry => !existing.includes(entry));
1326
+ if (missing.length > 0) {
1327
+ const additions = "\n# Added by rungate scaffold\n" +
1328
+ missing.map(e => {
1329
+ if (e === ".env") return ".env\n.env.*\n!.env.example";
1330
+ return e.includes("*") ? e : `${e}/`;
1331
+ }).join("\n") + "\n";
1332
+ writeFileSync(gitignorePath, existing.trimEnd() + "\n" + additions);
1333
+ actions.push(`UPDATED: .gitignore (added ${missing.length} missing entries)`);
1334
+ } else {
1335
+ actions.push("SKIP: .gitignore (all required entries present)");
1336
+ }
1337
+ } else {
1338
+ writeFileSync(gitignorePath, securityTemplate);
1339
+ actions.push("CREATED: .gitignore (security template)");
1340
+ }
1341
+ }
1342
+
1343
+ function createClaudeMdBridge(root: string): void {
1344
+ const claudeMdPath = join(root, "CLAUDE.md");
1345
+ const bridgeLine = "@AGENTS.md";
1346
+
1347
+ if (existsSync(claudeMdPath)) {
1348
+ const existing = readFileSync(claudeMdPath, "utf-8");
1349
+ if (!existing.includes(bridgeLine)) {
1350
+ writeFileSync(claudeMdPath, existing.trimEnd() + "\n\n" + bridgeLine + "\n");
1351
+ actions.push("UPDATED: CLAUDE.md (added @AGENTS.md bridge)");
1352
+ } else {
1353
+ actions.push("SKIP: CLAUDE.md (@AGENTS.md bridge already present)");
1354
+ }
1355
+ } else {
1356
+ const content = `# Project Rules
1357
+
1358
+ ${bridgeLine}
1359
+ `;
1360
+ writeFileSync(claudeMdPath, content);
1361
+ actions.push("CREATED: CLAUDE.md (with @AGENTS.md bridge)");
1362
+ }
1363
+ }
1364
+
1365
+ function createCiWorkflows(root: string): void {
1366
+ const workflowsDir = join(root, ".github", "workflows");
1367
+ if (!existsSync(workflowsDir)) {
1368
+ mkdirSync(workflowsDir, { recursive: true });
1369
+ }
1370
+
1371
+ const harness = loadHarnessConfig(root);
1372
+ const bunVersion = harness?.ci?.bunVersion || "latest";
1373
+ const runner = harness?.ci?.runner || "ubuntu-latest";
1374
+ const branches = harness?.ci?.branches || ["main"];
1375
+ const branchList = branches.map((b: string) => ` - ${b}`).join("\n");
1376
+
1377
+ const ciYml = `# Managed by rungate — do not edit. Customize via .claude/rungate.json ci section.
1378
+ name: CI
1379
+
1380
+ on:
1381
+ push:
1382
+ branches:
1383
+ ${branchList}
1384
+ pull_request:
1385
+ branches:
1386
+ ${branchList}
1387
+
1388
+ jobs:
1389
+ test:
1390
+ runs-on: ${runner}
1391
+ steps:
1392
+ - uses: actions/checkout@v4
1393
+ - uses: oven-sh/setup-bun@v2
1394
+ with:
1395
+ bun-version: "${bunVersion}"
1396
+ - run: bun install
1397
+ - run: bun test
1398
+ - run: bunx tsc --noEmit
1399
+ `;
1400
+
1401
+ const gatesYml = `# Managed by rungate — do not edit. Customize via .claude/rungate.json ci section.
1402
+ name: Gates
1403
+
1404
+ on:
1405
+ push:
1406
+ branches:
1407
+ ${branchList}
1408
+ pull_request:
1409
+ branches:
1410
+ ${branchList}
1411
+
1412
+ jobs:
1413
+ gates:
1414
+ runs-on: ${runner}
1415
+ steps:
1416
+ - uses: actions/checkout@v4
1417
+ - uses: oven-sh/setup-bun@v2
1418
+ with:
1419
+ bun-version: "${bunVersion}"
1420
+ - run: bun install
1421
+ - name: Conformity + spec drift
1422
+ run: bun test test/scaffold-conformity.test.ts
1423
+ - name: Secret scan
1424
+ run: |
1425
+ if git diff --cached --name-only | xargs grep -l -E '(AKIA|sk-|ghp_|password\s*=)' 2>/dev/null; then
1426
+ echo "::error::Potential secrets detected in staged files"
1427
+ exit 1
1428
+ fi
1429
+ `;
1430
+
1431
+ // CI and gates workflows are harness-owned — always regenerated
1432
+ writeFileSync(join(workflowsDir, "ci.yml"), ciYml);
1433
+ actions.push("CREATED: .github/workflows/ci.yml (harness-owned)");
1434
+
1435
+ writeFileSync(join(workflowsDir, "gates.yml"), gatesYml);
1436
+ actions.push("CREATED: .github/workflows/gates.yml (harness-owned)");
1437
+ }
1438
+
1439
+ function createGitHooks(root: string): void {
1440
+ const hooksDir = join(root, ".git", "hooks");
1441
+ if (!existsSync(hooksDir)) return;
1442
+
1443
+ const { chmodSync } = require("fs");
1444
+
1445
+ const preCommit = join(hooksDir, "pre-commit");
1446
+ if (!existsSync(preCommit)) {
1447
+ writeFileSync(preCommit, `#!/bin/sh
1448
+ # Managed by rungate — secret scan on staged files
1449
+ if git diff --cached --name-only | xargs grep -l -E '(AKIA[A-Z0-9]{16}|sk-[a-zA-Z0-9]{20,}|ghp_[a-zA-Z0-9]{36}|password\\s*=\\s*["\\''][^\\"\\'']+["\\''])' 2>/dev/null; then
1450
+ echo "ERROR: Potential secrets detected in staged files"
1451
+ exit 1
1452
+ fi
1453
+ `);
1454
+ chmodSync(preCommit, 0o755);
1455
+ actions.push("CREATED: .git/hooks/pre-commit (secret scan)");
1456
+ }
1457
+
1458
+ const prePush = join(hooksDir, "pre-push");
1459
+ if (!existsSync(prePush)) {
1460
+ writeFileSync(prePush, `#!/bin/sh
1461
+ # Managed by rungate — conformity check before push
1462
+ bun test test/scaffold-conformity.test.ts 2>/dev/null
1463
+ if [ $? -ne 0 ]; then
1464
+ echo "ERROR: Conformity tests failed — fix before pushing"
1465
+ exit 1
1466
+ fi
1467
+ `);
1468
+ chmodSync(prePush, 0o755);
1469
+ actions.push("CREATED: .git/hooks/pre-push (conformity check)");
1470
+ }
1471
+ }
1472
+
1473
+ function postScaffoldCommit(root: string): void {
1474
+ try {
1475
+ const result = Bun.spawnSync(["git", "-C", root, "status", "--porcelain"]);
1476
+ const status = result.stdout.toString().trim();
1477
+ if (!status) {
1478
+ actions.push("SKIP: post-scaffold commit (no changes)");
1479
+ return;
1480
+ }
1481
+
1482
+ Bun.spawnSync(["git", "-C", root, "add", "-A"]);
1483
+ Bun.spawnSync(["git", "-C", root, "commit", "-m", "scaffold: initialize rungate harness"]);
1484
+ actions.push("CREATED: post-scaffold commit");
1485
+ } catch {
1486
+ actions.push("SKIP: post-scaffold commit (git error)");
1487
+ }
1488
+ }