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,339 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * generate-code-map.ts — Scan a codebase and produce CODE-MAP.md
4
+ *
5
+ * Usage: bun ~/Projects/rungate/scripts/generate-code-map.ts /path/to/project
6
+ *
7
+ * Combines fallow analysis + route scanning + directory structure into a
8
+ * machine-generated architecture snapshot. Agents read this to understand
9
+ * the codebase without exploring manually.
10
+ */
11
+ import { existsSync, readFileSync, readdirSync, writeFileSync, statSync } from "fs";
12
+ import { join, basename } from "path";
13
+
14
+ const projectPath = process.argv[2];
15
+ if (!projectPath || !existsSync(projectPath)) {
16
+ console.error("Usage: generate-code-map.ts /path/to/project");
17
+ process.exit(1);
18
+ }
19
+
20
+ const projectName = basename(projectPath);
21
+ const today = new Date().toISOString().split("T")[0];
22
+
23
+ // ── Fallow analysis ──────────────────────────────────────────
24
+
25
+ interface FallowData {
26
+ entryPoints: number;
27
+ unusedFiles: string[];
28
+ unusedExports: Array<{ path: string; export_name: string; line: number }>;
29
+ circularDeps: Array<{ files: string[] }>;
30
+ elapsed: number;
31
+ }
32
+
33
+ function runFallow(): FallowData | null {
34
+ const result = Bun.spawnSync(
35
+ ["npx", "fallow", "dead-code", "--format", "json", "--quiet"],
36
+ { cwd: projectPath, timeout: 30_000 }
37
+ );
38
+ const stdout = result.stdout.toString().trim();
39
+ if (!stdout || stdout.startsWith("{\"error\"")) return null;
40
+ try {
41
+ const d = JSON.parse(stdout);
42
+ return {
43
+ entryPoints: d.entry_points?.total || 0,
44
+ unusedFiles: (d.unused_files || []).map((f: any) => f.path),
45
+ unusedExports: (d.unused_exports || []).map((e: any) => ({
46
+ path: e.path, export_name: e.export_name, line: e.line
47
+ })),
48
+ circularDeps: (d.circular_dependencies || []).map((c: any) => ({
49
+ files: c.files || [c.path]
50
+ })),
51
+ elapsed: d.elapsed_ms || 0,
52
+ };
53
+ } catch { return null; }
54
+ }
55
+
56
+ // ── Route scanning ───────────────────────────────────────────
57
+
58
+ interface Route { method: string; path: string; file: string; line: number }
59
+
60
+ function scanRoutes(): Route[] {
61
+ const routes: Route[] = [];
62
+ const srcDir = join(projectPath, "src");
63
+ if (!existsSync(srcDir)) return routes;
64
+
65
+ const routePattern = /app\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/gi;
66
+
67
+ for (const file of readdirSync(srcDir, { recursive: true }).map(String)) {
68
+ if (!file.endsWith(".ts") && !file.endsWith(".js")) continue;
69
+ const fullPath = join(srcDir, file);
70
+ try {
71
+ const content = readFileSync(fullPath, "utf-8");
72
+ const lines = content.split("\n");
73
+ for (let i = 0; i < lines.length; i++) {
74
+ let match;
75
+ const lineRoutePattern = /app\.(get|post|put|delete|patch)\s*\(\s*["'`]([^"'`]+)["'`]/gi;
76
+ while ((match = lineRoutePattern.exec(lines[i])) !== null) {
77
+ routes.push({
78
+ method: match[1].toUpperCase(),
79
+ path: match[2],
80
+ file: `src/${file}`,
81
+ line: i + 1,
82
+ });
83
+ }
84
+ }
85
+ } catch {}
86
+ }
87
+ return routes;
88
+ }
89
+
90
+ // ── Directory structure ──────────────────────────────────────
91
+
92
+ interface DirSummary { name: string; fileCount: number; types: string[] }
93
+
94
+ function scanDirectories(): DirSummary[] {
95
+ const dirs: DirSummary[] = [];
96
+ const skip = new Set(["node_modules", ".git", "reference", "dist", "build", ".next", ".fallow"]);
97
+
98
+ for (const entry of readdirSync(projectPath)) {
99
+ if (entry.startsWith(".") && entry !== ".claude") continue;
100
+ if (skip.has(entry)) continue;
101
+ const full = join(projectPath, entry);
102
+ try {
103
+ if (!statSync(full).isDirectory()) continue;
104
+ const files = readdirSync(full, { recursive: true }).map(String);
105
+ const exts = new Set(files.map(f => f.split(".").pop()).filter(Boolean));
106
+ dirs.push({ name: entry, fileCount: files.length, types: [...exts].slice(0, 5) });
107
+ } catch {}
108
+ }
109
+ return dirs.sort((a, b) => b.fileCount - a.fileCount);
110
+ }
111
+
112
+ // ── Component scanning (React) ───────────────────────────────
113
+
114
+ function scanComponents(): string[] {
115
+ const componentDirs = [
116
+ join(projectPath, "dashboard/src/components"),
117
+ join(projectPath, "src/components"),
118
+ ];
119
+ const components: string[] = [];
120
+ for (const dir of componentDirs) {
121
+ if (!existsSync(dir)) continue;
122
+ for (const f of readdirSync(dir)) {
123
+ if (f.endsWith(".tsx") || f.endsWith(".jsx")) {
124
+ components.push(f.replace(/\.(tsx|jsx)$/, ""));
125
+ }
126
+ }
127
+ }
128
+ return components.sort();
129
+ }
130
+
131
+ // ── Consumer-module mapping (for Marcus) ─────────────────────
132
+
133
+ interface ConsumerMapping { consumer: string; imports: string[] }
134
+
135
+ function scanConsumerModules(): ConsumerMapping[] {
136
+ const srcDir = join(projectPath, "src");
137
+ if (!existsSync(srcDir)) return [];
138
+ const mappings: ConsumerMapping[] = [];
139
+
140
+ for (const file of readdirSync(srcDir).filter(f => f.endsWith(".ts"))) {
141
+ const content = readFileSync(join(srcDir, file), "utf-8");
142
+ const imports: string[] = [];
143
+ const importPattern = /from\s+["']\.\/([^"']+)["']/g;
144
+ let m;
145
+ while ((m = importPattern.exec(content)) !== null) {
146
+ imports.push(m[1]);
147
+ }
148
+ if (imports.length > 0) {
149
+ mappings.push({ consumer: file, imports: imports.slice(0, 8) });
150
+ }
151
+ }
152
+ return mappings.sort((a, b) => b.imports.length - a.imports.length).slice(0, 15);
153
+ }
154
+
155
+ // ── Page-component mapping (for Quinn) ───────────────────────
156
+
157
+ function scanPageComponents(): Array<{ page: string; components: string[] }> {
158
+ const pagesDir = join(projectPath, "dashboard/src/pages");
159
+ if (!existsSync(pagesDir)) return [];
160
+ const pages: Array<{ page: string; components: string[] }> = [];
161
+
162
+ for (const file of readdirSync(pagesDir).filter(f => f.endsWith(".tsx"))) {
163
+ const content = readFileSync(join(pagesDir, file), "utf-8");
164
+ const components: string[] = [];
165
+ const importPattern = /from\s+["'].*?\/components\/([^"']+)["']/g;
166
+ let m;
167
+ while ((m = importPattern.exec(content)) !== null) {
168
+ components.push(m[1].replace(/["']$/, ""));
169
+ }
170
+ if (components.length > 0) {
171
+ pages.push({ page: file.replace(/\.tsx$/, ""), components });
172
+ }
173
+ }
174
+ return pages;
175
+ }
176
+
177
+ // ── Package info ─────────────────────────────────────────────
178
+
179
+ function readPackageInfo(): { name: string; deps: number; devDeps: number; scripts: string[] } {
180
+ const pkgPath = join(projectPath, "package.json");
181
+ if (!existsSync(pkgPath)) return { name: projectName, deps: 0, devDeps: 0, scripts: [] };
182
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
183
+ return {
184
+ name: pkg.name || projectName,
185
+ deps: Object.keys(pkg.dependencies || {}).length,
186
+ devDeps: Object.keys(pkg.devDependencies || {}).length,
187
+ scripts: Object.keys(pkg.scripts || {}),
188
+ };
189
+ }
190
+
191
+ // ── Generate ─────────────────────────────────────────────────
192
+
193
+ console.log(`Scanning ${projectName}...`);
194
+
195
+ const fallow = runFallow();
196
+ const routes = scanRoutes();
197
+ const dirs = scanDirectories();
198
+ const components = scanComponents();
199
+ const pkg = readPackageInfo();
200
+ const consumerMappings = scanConsumerModules();
201
+ const pageMappings = scanPageComponents();
202
+
203
+ console.log(` Fallow: ${fallow ? `${fallow.entryPoints} entry points, ${fallow.elapsed}ms` : "not available"}`);
204
+ console.log(` Routes: ${routes.length}`);
205
+ console.log(` Directories: ${dirs.length}`);
206
+ console.log(` Components: ${components.length}`);
207
+ console.log(` Module mappings: ${consumerMappings.length}`);
208
+ console.log(` Page mappings: ${pageMappings.length}`);
209
+
210
+ // ── Build CODE-MAP.md ────────────────────────────────────────
211
+
212
+ let headSha = "unknown";
213
+ try {
214
+ const result = Bun.spawnSync(["git", "-C", projectPath, "rev-parse", "HEAD"]);
215
+ headSha = result.stdout.toString().trim().substring(0, 8);
216
+ } catch {}
217
+
218
+ const sections: string[] = [];
219
+
220
+ sections.push(`---
221
+ doc-type: code-map
222
+ status: generated
223
+ updated: ${today}
224
+ scanned-at-sha: ${headSha}
225
+ generator: rungate/scripts/generate-code-map.ts
226
+ ---
227
+
228
+ # Code Map — ${pkg.name}
229
+
230
+ Auto-generated architecture snapshot. Re-run \`bun generate-code-map.ts ${projectPath}\` to refresh.
231
+ Regenerate when src/ has commits since scanned-at-sha.`);
232
+
233
+ // Summary
234
+ sections.push(`## Summary
235
+
236
+ | Metric | Count |
237
+ |--------|-------|
238
+ | Source directories | ${dirs.length} |
239
+ | Dependencies | ${pkg.deps} |
240
+ | Dev dependencies | ${pkg.devDeps} |
241
+ | API routes | ${routes.length} |
242
+ | React components | ${components.length} |
243
+ | Entry points (fallow) | ${fallow?.entryPoints || "N/A"} |
244
+ | Unused files | ${fallow?.unusedFiles.length || "N/A"} |
245
+ | Unused exports | ${fallow?.unusedExports.length || "N/A"} |
246
+ | Circular dependencies | ${fallow?.circularDeps.length || "N/A"} |
247
+ | Module import mappings | ${consumerMappings.length} |
248
+ | Page-component mappings | ${pageMappings.length} |`);
249
+
250
+ // Directory structure
251
+ sections.push(`## Directory Structure
252
+
253
+ | Directory | Files | Types |
254
+ |-----------|-------|-------|
255
+ ${dirs.map(d => `| ${d.name}/ | ${d.fileCount} | ${d.types.join(", ")} |`).join("\n")}`);
256
+
257
+ // Routes
258
+ if (routes.length > 0) {
259
+ const byMethod: Record<string, Route[]> = {};
260
+ for (const r of routes) {
261
+ (byMethod[r.method] ||= []).push(r);
262
+ }
263
+ let routeTable = "## API Routes\n\n";
264
+ for (const [method, methodRoutes] of Object.entries(byMethod).sort()) {
265
+ routeTable += `### ${method} (${methodRoutes.length})\n\n`;
266
+ routeTable += "| Path | File | Line |\n|------|------|------|\n";
267
+ for (const r of methodRoutes.sort((a, b) => a.path.localeCompare(b.path))) {
268
+ routeTable += `| ${r.path} | ${r.file} | ${r.line} |\n`;
269
+ }
270
+ routeTable += "\n";
271
+ }
272
+ sections.push(routeTable.trim());
273
+ }
274
+
275
+ // Components
276
+ if (components.length > 0) {
277
+ sections.push(`## React Components (${components.length})
278
+
279
+ ${components.map(c => `- ${c}`).join("\n")}`);
280
+ }
281
+
282
+ // Module import mappings (for Marcus — shows dependency chains)
283
+ if (consumerMappings.length > 0) {
284
+ let modSection = `## Module Dependencies (top ${consumerMappings.length})\n\n`;
285
+ modSection += "Which modules depend on which — for cascade impact analysis.\n\n";
286
+ modSection += "| Module | Imports From |\n|--------|-------------|\n";
287
+ for (const cm of consumerMappings) {
288
+ modSection += `| ${cm.consumer} | ${cm.imports.join(", ")} |\n`;
289
+ }
290
+ sections.push(modSection.trim());
291
+ }
292
+
293
+ // Page-component mappings (for Quinn — shows which components are on each page)
294
+ if (pageMappings.length > 0) {
295
+ let pageSection = `## Page → Component Map (for UI testing)\n\n`;
296
+ pageSection += "Which components render on each page — for targeted UI verification.\n\n";
297
+ for (const pm of pageMappings) {
298
+ pageSection += `### ${pm.page}\n\n`;
299
+ pageSection += pm.components.map(c => `- ${c}`).join("\n") + "\n\n";
300
+ }
301
+ sections.push(pageSection.trim());
302
+ }
303
+
304
+ // Health (fallow findings)
305
+ if (fallow) {
306
+ let health = "## Code Health (fallow)\n\n";
307
+
308
+ if (fallow.circularDeps.length > 0) {
309
+ health += `### Circular Dependencies (${fallow.circularDeps.length})\n\n`;
310
+ for (const cd of fallow.circularDeps.slice(0, 10)) {
311
+ health += `- ${cd.files.join(" → ")}\n`;
312
+ }
313
+ if (fallow.circularDeps.length > 10) health += `- ... and ${fallow.circularDeps.length - 10} more\n`;
314
+ health += "\n";
315
+ }
316
+
317
+ if (fallow.unusedFiles.length > 0) {
318
+ health += `### Unused Files (${fallow.unusedFiles.length})\n\n`;
319
+ for (const f of fallow.unusedFiles.slice(0, 15)) {
320
+ health += `- ${f}\n`;
321
+ }
322
+ if (fallow.unusedFiles.length > 15) health += `- ... and ${fallow.unusedFiles.length - 15} more\n`;
323
+ health += "\n";
324
+ }
325
+
326
+ sections.push(health.trim());
327
+ }
328
+
329
+ // Scripts
330
+ if (pkg.scripts.length > 0) {
331
+ sections.push(`## Package Scripts
332
+
333
+ ${pkg.scripts.map(s => `- \`${s}\``).join("\n")}`);
334
+ }
335
+
336
+ const codeMap = sections.join("\n\n") + "\n";
337
+ const outPath = join(projectPath, "CODE-MAP.md");
338
+ writeFileSync(outPath, codeMap);
339
+ console.log(`\nWritten: ${outPath} (${codeMap.split("\n").length} lines)`);
@@ -0,0 +1,76 @@
1
+ #!/bin/bash
2
+ # Dump current crontab before every commit so scripts/crontab.txt never drifts.
3
+
4
+ CRONTAB_FILE="$(git rev-parse --show-toplevel)/scripts/crontab.txt"
5
+
6
+ {
7
+ echo "# PAI Crontab — restore with: crontab ~/.claude/scripts/crontab.txt"
8
+ echo "# Last updated: $(date '+%Y-%m-%d')"
9
+ echo ""
10
+ crontab -l 2>/dev/null || true
11
+ } > "$CRONTAB_FILE"
12
+
13
+ git add "$CRONTAB_FILE"
14
+
15
+ # ─── Secret Scanner ─────────────────────────────────────────────────
16
+ # Scans staged diff content for leaked secrets. Blocks commit on match.
17
+
18
+ REPO_ROOT="$(git rev-parse --show-toplevel)"
19
+ ALLOWLIST="$REPO_ROOT/.secret-scan-allowlist"
20
+
21
+ # Build grep pattern for all 8 secret types
22
+ SECRET_PATTERNS='(ghp_[A-Za-z0-9]{36}|gho_[A-Za-z0-9]{36}|ghs_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9]{22}_[A-Za-z0-9]{59}|AKIA[A-Z0-9]{16}|sk-[A-Za-z0-9]{48}|-----BEGIN (RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----|sk-ant-[A-Za-z0-9\-]{90,})'
23
+
24
+ # Get staged diff (added/copied/modified files only, exclude crontab.txt)
25
+ STAGED_DIFF="$(git diff --cached --diff-filter=ACM -U0 -- . ':!scripts/crontab.txt')"
26
+
27
+ if [ -n "$STAGED_DIFF" ]; then
28
+ MATCHES=""
29
+ CURRENT_FILE=""
30
+ IS_BINARY=false
31
+
32
+ while IFS= read -r line; do
33
+ # Track which file we're in
34
+ if [[ "$line" =~ ^diff\ --git\ a/(.+)\ b/ ]]; then
35
+ CURRENT_FILE="${BASH_REMATCH[1]}"
36
+ IS_BINARY=false
37
+ continue
38
+ fi
39
+
40
+ # Skip binary files
41
+ if [[ "$line" == "Binary files"* ]] || [[ "$line" == "GIT binary patch"* ]]; then
42
+ IS_BINARY=true
43
+ continue
44
+ fi
45
+ if [ "$IS_BINARY" = true ]; then
46
+ continue
47
+ fi
48
+
49
+ # Only check added lines (start with +, but not +++ header)
50
+ if [[ "$line" =~ ^\+[^+] ]] || [[ "$line" == "+" ]]; then
51
+ # Check against allowlist
52
+ if [ -n "$CURRENT_FILE" ] && [ -f "$ALLOWLIST" ]; then
53
+ if grep -qxF "$CURRENT_FILE" "$ALLOWLIST" 2>/dev/null; then
54
+ continue
55
+ fi
56
+ fi
57
+
58
+ # Scan for secret patterns
59
+ if echo "$line" | grep -qE "$SECRET_PATTERNS"; then
60
+ MATCHES="${MATCHES}[SECRET SCAN] BLOCKED: potential secret found in ${CURRENT_FILE}\n"
61
+ fi
62
+ fi
63
+ done <<< "$STAGED_DIFF"
64
+
65
+ if [ -n "$MATCHES" ]; then
66
+ echo ""
67
+ echo "════════════════════════════════════════════════════"
68
+ echo " SECRET SCAN FAILED — commit blocked"
69
+ echo "════════════════════════════════════════════════════"
70
+ echo ""
71
+ echo -e "$MATCHES"
72
+ echo "To allowlist a file, add its path to .secret-scan-allowlist"
73
+ echo "════════════════════════════════════════════════════"
74
+ exit 1
75
+ fi
76
+ fi
@@ -0,0 +1,271 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Pre-push hook — blocks push to main when ship verify-gate hasn't passed.
4
+ * TypeScript port of the bash pre-push (ADR-008 #448).
5
+ *
6
+ * Uses findWorkflowForIssue() from hooks/lib/findWorkflow.ts for resolution.
7
+ * Resolution priority: projectRoot > issue number > mtime fallback.
8
+ */
9
+
10
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'fs';
11
+ import { join, dirname } from 'path';
12
+ import { execSync } from 'child_process';
13
+ import { harnessRoot } from '../../lib/paths';
14
+ const _hr = harnessRoot();
15
+ const { findWorkflowForIssue, extractIssueNumber } = await import(join(_hr, 'hooks/lib/findWorkflow'));
16
+ const { verifyWitnessChain } = await import(join(_hr, 'gates/witness'));
17
+
18
+ const BASE_DIR = process.env.PAI_DIR || join(process.env.HOME!, '.claude');
19
+ const WORK_DIR = process.env.PAI_WORK_DIR || join(process.env.HOME!, '.pai-work');
20
+ const SIGNALS_DIR = join(BASE_DIR, 'MEMORY/LEARNING/SIGNALS');
21
+
22
+ const TTL_SECONDS = 14400; // 4 hours
23
+
24
+ // ── Helpers ──────────────────────────────────────────────────────────
25
+
26
+ function git(cmd: string): string {
27
+ try {
28
+ return execSync(`git ${cmd}`, { encoding: 'utf-8' }).trim();
29
+ } catch {
30
+ return '';
31
+ }
32
+ }
33
+
34
+ function resolveSlugFromPath(absPath: string): string {
35
+ return absPath.replace(WORK_DIR + '/', '');
36
+ }
37
+
38
+ function nowISO(): string {
39
+ return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
40
+ }
41
+
42
+ function writeSignal(prefix: string, data: Record<string, unknown>): void {
43
+ mkdirSync(SIGNALS_DIR, { recursive: true });
44
+ const file = join(SIGNALS_DIR, `${prefix}-${Math.floor(Date.now() / 1000)}.json`);
45
+ writeFileSync(file, JSON.stringify(data, null, 2) + '\n');
46
+ }
47
+
48
+ // ── Read stdin: determine if pushing to main ─────────────────────────
49
+
50
+ const stdin = readFileSync(0, 'utf-8');
51
+ const remote = process.argv[2] || '';
52
+ const url = process.argv[3] || '';
53
+
54
+ let pushingToMain = false;
55
+ for (const line of stdin.split('\n')) {
56
+ const parts = line.trim().split(/\s+/);
57
+ const remoteRef = parts[2] || '';
58
+ if (remoteRef === 'refs/heads/main' || remoteRef === 'refs/heads/master') {
59
+ pushingToMain = true;
60
+ }
61
+ }
62
+
63
+ if (!pushingToMain) process.exit(0);
64
+
65
+ // ── Commit-prefix fast-path ──────────────────────────────────────────
66
+
67
+ const commitMsg = git('log --oneline -1 HEAD');
68
+ if (/^[a-f0-9]+ (docs:|chore:|backup:|nightly:)/.test(commitMsg)) {
69
+ process.exit(0);
70
+ }
71
+
72
+ // ── Find active workflow via shared resolution ───────────────────────
73
+
74
+ const repoRoot = git('rev-parse --show-toplevel');
75
+ const issueNum = extractIssueNumber(commitMsg);
76
+
77
+ // Active phases — exclude DONE and CIRCUIT_BREAK
78
+ const activePhases = ['BUILD', 'VERIFY', 'SCOPE', 'SHIP'];
79
+
80
+ const workflow = findWorkflowForIssue(issueNum, activePhases, undefined, repoRoot || undefined);
81
+
82
+ // ── No active workflow → audit for orphans, allow push ───────────────
83
+
84
+ if (!workflow) {
85
+ // Check for orphaned workflow-state.json (marker deletion bypass)
86
+ if (existsSync(WORK_DIR)) {
87
+ try {
88
+ const scanDirs = (base: string) => {
89
+ for (const d of readdirSync(base, { withFileTypes: true })) {
90
+ if (!d.isDirectory()) continue;
91
+ const wfPath = join(base, d.name, 'workflow-state.json');
92
+ if (!existsSync(wfPath)) continue;
93
+ try {
94
+ const data = JSON.parse(readFileSync(wfPath, 'utf-8'));
95
+ const phase = data.phase;
96
+ if (phase && phase !== 'DONE' && phase !== 'CIRCUIT_BREAK') {
97
+ const shipActive = join(base, d.name, '.ship-active');
98
+ if (!existsSync(shipActive)) {
99
+ writeSignal('marker-missing', {
100
+ ts: nowISO(),
101
+ type: 'marker_missing',
102
+ phase,
103
+ slug: resolveSlugFromPath(join(base, d.name)),
104
+ issue: data.issue || 0,
105
+ remote,
106
+ url,
107
+ user: process.env.USER || 'unknown',
108
+ });
109
+ console.error('⚠️ Ship marker missing for active issue — audit logged');
110
+ }
111
+ }
112
+ } catch {}
113
+ }
114
+ };
115
+ scanDirs(WORK_DIR);
116
+ // Scan nested (e.g., pai/361)
117
+ for (const d of readdirSync(WORK_DIR, { withFileTypes: true })) {
118
+ if (d.isDirectory()) scanDirs(join(WORK_DIR, d.name));
119
+ }
120
+ } catch {}
121
+ }
122
+ process.exit(0);
123
+ }
124
+
125
+ const wfDir = dirname(workflow.path);
126
+ const wfData = workflow.data;
127
+ const shipIssue: number = wfData.issue || 0;
128
+
129
+ // ── HOTFIX override ─────────────────────────────────────────────────
130
+
131
+ const hotfix = process.env.HOTFIX;
132
+ if (hotfix) {
133
+ // Format validation — restrict to known categories
134
+ if (!/^(issue-\d+|docs|chore|backup|nightly)$/.test(hotfix)) {
135
+ console.error(`HOTFIX format invalid: '${hotfix}' (expected: issue-NNN, docs, chore, backup, nightly)`);
136
+ process.exit(1);
137
+ }
138
+
139
+ // Rate-limit warning — flag repeated overrides for same ref
140
+ if (existsSync(SIGNALS_DIR)) {
141
+ try {
142
+ const oneHourAgo = Date.now() - 3600000;
143
+ const recentCount = readdirSync(SIGNALS_DIR)
144
+ .filter(f => f.startsWith('hotfix-'))
145
+ .filter(f => {
146
+ const fPath = join(SIGNALS_DIR, f);
147
+ if (statSync(fPath).mtimeMs < oneHourAgo) return false;
148
+ try {
149
+ const content = JSON.parse(readFileSync(fPath, 'utf-8'));
150
+ return content.hotfix_ref === hotfix;
151
+ } catch { return false; }
152
+ }).length;
153
+ if (recentCount >= 2) {
154
+ console.error(`⚠️ WARN: ${recentCount} HOTFIX overrides for '${hotfix}' in last hour`);
155
+ }
156
+ } catch {}
157
+ }
158
+
159
+ writeSignal('hotfix', {
160
+ ts: nowISO(),
161
+ type: 'hotfix_override',
162
+ issue: shipIssue,
163
+ hotfix_ref: hotfix,
164
+ remote,
165
+ url,
166
+ user: process.env.USER || 'unknown',
167
+ hostname: execSync('hostname -s', { encoding: 'utf-8' }).trim(),
168
+ });
169
+ console.error(`⚠️ HOTFIX override — audit logged to ${SIGNALS_DIR}`);
170
+ process.exit(0);
171
+ }
172
+
173
+ // ── GATE_PASSED_PUSH bypass ──────────────────────────────────────────
174
+
175
+ if (process.env.GATE_PASSED_PUSH) {
176
+ const gateSha = wfData.gates?.ship?.commitSha;
177
+ const headSha = git('rev-parse HEAD');
178
+ if (gateSha && gateSha === headSha) {
179
+ console.error(` Gate-passed push — SHA verified (${gateSha})`);
180
+ process.exit(0);
181
+ }
182
+ console.error(gateSha
183
+ ? ` Gate SHA mismatch (${gateSha} vs ${headSha}) — running gates`
184
+ : ' Cannot verify gate SHA — running gates');
185
+ }
186
+
187
+ // ── Verify gate results from workflow-state ──────────────────────────
188
+ // Pre-push is ADVISORY — IssueCloseGuard is the enforcement point.
189
+
190
+ const headSha = git('rev-parse HEAD');
191
+ let allPass = true;
192
+ let missingGates: string[] = [];
193
+
194
+ for (const gate of ['scope', 'verify', 'ship'] as const) {
195
+ const gateResult: string = wfData.gates?.[gate]?.result || '';
196
+ const gateSha: string = wfData.gates?.[gate]?.commitSha || '';
197
+
198
+ if (gateResult === 'PASS') {
199
+ if (gateSha && gateSha === headSha) {
200
+ console.error(` ✓ ${gate} — PASS (SHA verified)`);
201
+ } else {
202
+ console.error(` ⚠ ${gate} — PASS but SHA mismatch (${gateSha} vs ${headSha}) — WARN`);
203
+ }
204
+ } else if (!gateResult) {
205
+ console.error(` ○ ${gate} — not run yet`);
206
+ missingGates.push(gate);
207
+ allPass = false;
208
+ } else {
209
+ console.error(` ✗ ${gate} — ${gateResult}`);
210
+ allPass = false;
211
+ }
212
+ }
213
+
214
+ if (allPass) {
215
+ console.error(' All gates PASS — push allowed');
216
+ } else if (missingGates.length > 0) {
217
+ // Active workflow but gates not run — BLOCK unless ship gate PASS
218
+ const shipGate = wfData.gates?.ship?.result;
219
+ if (shipGate !== 'PASS') {
220
+ console.error(` BLOCKED: Active workflow exists but ship gate not PASS (missing: ${missingGates.join(', ')})`);
221
+ console.error(' Run gate checks or set HOTFIX=issue-NNN to override.');
222
+ process.exit(1);
223
+ }
224
+ console.error(` ⚠️ WARN: Gates not run: ${missingGates.join(', ')} — push allowed (ship gate PASS)`);
225
+ } else {
226
+ // Active workflow with failed gates — BLOCK
227
+ console.error(' BLOCKED: Gates not PASS — fix gate failures before pushing.');
228
+ console.error(' Set HOTFIX=issue-NNN to override.');
229
+ process.exit(1);
230
+ }
231
+
232
+ // ── Stale-PASS detection ─────────────────────────────────────────────
233
+
234
+ const staleSha = wfData.gates?.ship?.commitSha || wfData.gates?.verify?.commitSha;
235
+ if (staleSha && staleSha !== headSha) {
236
+ console.error(`⚠️ WARN: Gates passed at commit ${staleSha} but HEAD is now ${headSha}`);
237
+ console.error(' New commits since gate-run may not be validated.');
238
+ }
239
+
240
+ // ── Witness chain verification (#471) ───────────────────────────────
241
+ // Ground-truth check: verify HMAC-signed witness files match gate results
242
+
243
+ const wfSlug = resolveSlugFromPath(wfDir);
244
+ try {
245
+ const chain = verifyWitnessChain(wfSlug, headSha);
246
+ if (chain.valid) {
247
+ console.error(` ✓ Witness chain verified (${chain.witnesses.length} witnesses)`);
248
+ } else {
249
+ for (const err of chain.errors) {
250
+ console.error(` ⚠ Witness: ${err}`);
251
+ }
252
+ // WARN, not BLOCK — witness chain is additive; workflow-state gates are primary
253
+ console.error(' ⚠️ WARN: Witness chain verification failed — audit logged');
254
+ writeSignal('witness-chain-fail', {
255
+ ts: nowISO(),
256
+ type: 'witness_chain_failure',
257
+ slug: wfSlug,
258
+ issue: shipIssue,
259
+ errors: chain.errors,
260
+ witnessCount: chain.witnesses.length,
261
+ remote,
262
+ url,
263
+ user: process.env.USER || 'unknown',
264
+ });
265
+ }
266
+ } catch (e: any) {
267
+ // Witness module not available or salt missing — degrade gracefully
268
+ console.error(` ○ Witness chain: ${e.message}`);
269
+ }
270
+
271
+ process.exit(0);