@cbartens/bkit 0.0.0-stage → 5.0.1

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 (375) hide show
  1. package/.bkit/README.md +417 -0
  2. package/.bkit/core/.agents/context.md +95 -0
  3. package/.bkit/core/.agents/docs.md +62 -0
  4. package/.bkit/core/.agents/rules.md +147 -0
  5. package/.bkit/core/.agents/skills.md +43 -0
  6. package/.bkit/core/.bkit/LICENSE.md +151 -0
  7. package/.bkit/core/.bkit/README.md +417 -0
  8. package/.bkit/core/.bkit/cloud.md +493 -0
  9. package/.bkit/core/.bkit/comparison.md +321 -0
  10. package/.bkit/core/.bkit/install.md +401 -0
  11. package/.bkit/core/.bkit/jsonl.md +497 -0
  12. package/.bkit/core/.bkit/prompts.md +474 -0
  13. package/.bkit/core/.bkit/providers.md +598 -0
  14. package/.bkit/core/.bkit/templates.md +470 -0
  15. package/.bkit/core/.bkit/trackers.md +95 -0
  16. package/.bkit/core/.bkit/workflows.md +1550 -0
  17. package/.bkit/core/.claude/hooks/bkit-gateguard.cjs +82 -0
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +93 -0
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +74 -0
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +115 -0
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +135 -0
  22. package/.bkit/core/.cursor/hooks/bkit-gateguard.cjs +111 -0
  23. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +169 -0
  24. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +63 -0
  25. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +225 -0
  26. package/.bkit/core/AGENTS.md +77 -0
  27. package/.bkit/core/LICENSE.md +149 -0
  28. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +272 -0
  29. package/.bkit/core/docs/templates/bkit-audit-adoption.md +223 -0
  30. package/.bkit/core/docs/templates/bkit-audit-agents.md +230 -0
  31. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +227 -0
  32. package/.bkit/core/docs/templates/bkit-audit-analytics.md +266 -0
  33. package/.bkit/core/docs/templates/bkit-audit-annotations.md +230 -0
  34. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +270 -0
  35. package/.bkit/core/docs/templates/bkit-audit-app-store.md +254 -0
  36. package/.bkit/core/docs/templates/bkit-audit-architecture.md +221 -0
  37. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +241 -0
  38. package/.bkit/core/docs/templates/bkit-audit-config.md +230 -0
  39. package/.bkit/core/docs/templates/bkit-audit-cost.md +218 -0
  40. package/.bkit/core/docs/templates/bkit-audit-coverage.md +221 -0
  41. package/.bkit/core/docs/templates/bkit-audit-database.md +229 -0
  42. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +251 -0
  43. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +283 -0
  44. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +268 -0
  45. package/.bkit/core/docs/templates/bkit-audit-documentation.md +280 -0
  46. package/.bkit/core/docs/templates/bkit-audit-duplication.md +253 -0
  47. package/.bkit/core/docs/templates/bkit-audit-failures.md +259 -0
  48. package/.bkit/core/docs/templates/bkit-audit-flakes.md +237 -0
  49. package/.bkit/core/docs/templates/bkit-audit-gates.md +250 -0
  50. package/.bkit/core/docs/templates/bkit-audit-issues.md +273 -0
  51. package/.bkit/core/docs/templates/bkit-audit-llm.md +239 -0
  52. package/.bkit/core/docs/templates/bkit-audit-logs.md +266 -0
  53. package/.bkit/core/docs/templates/bkit-audit-models.md +210 -0
  54. package/.bkit/core/docs/templates/bkit-audit-privacy.md +211 -0
  55. package/.bkit/core/docs/templates/bkit-audit-prompts.md +216 -0
  56. package/.bkit/core/docs/templates/bkit-audit-red-team.md +220 -0
  57. package/.bkit/core/docs/templates/bkit-audit-reliability.md +222 -0
  58. package/.bkit/core/docs/templates/bkit-audit-repo.md +224 -0
  59. package/.bkit/core/docs/templates/bkit-audit-security.md +274 -0
  60. package/.bkit/core/docs/templates/bkit-audit-slop.md +200 -0
  61. package/.bkit/core/docs/templates/bkit-audit-testing.md +270 -0
  62. package/.bkit/core/docs/templates/bkit-audit-usability.md +237 -0
  63. package/.bkit/core/docs/templates/bkit-plan.md +476 -0
  64. package/.bkit/core/engine/checks/after/auth.ts +149 -0
  65. package/.bkit/core/engine/checks/after/ci-yml.ts +701 -0
  66. package/.bkit/core/engine/checks/after/github.ts +424 -0
  67. package/.bkit/core/engine/checks/after/index.ts +530 -0
  68. package/.bkit/core/engine/checks/after/managed.ts +217 -0
  69. package/.bkit/core/engine/checks/after/suppression.ts +53 -0
  70. package/.bkit/core/engine/checks/after/tools.ts +427 -0
  71. package/.bkit/core/engine/checks/before/context-fetch.ts +429 -0
  72. package/.bkit/core/engine/checks/before/env.ts +187 -0
  73. package/.bkit/core/engine/checks/before/files.ts +204 -0
  74. package/.bkit/core/engine/checks/before/index.ts +206 -0
  75. package/.bkit/core/engine/checks/before/mcp.ts +127 -0
  76. package/.bkit/core/engine/checks/before/repo.ts +77 -0
  77. package/.bkit/core/engine/checks/before/version.ts +67 -0
  78. package/.bkit/core/engine/checks/status-holes.ts +479 -0
  79. package/.bkit/core/engine/cli.ts +867 -0
  80. package/.bkit/core/engine/commands/analysis.ts +550 -0
  81. package/.bkit/core/engine/commands/ci/ci.ts +483 -0
  82. package/.bkit/core/engine/commands/comply.ts +415 -0
  83. package/.bkit/core/engine/commands/harvest.ts +459 -0
  84. package/.bkit/core/engine/commands/install/check.ts +70 -0
  85. package/.bkit/core/engine/commands/install/doctor.ts +254 -0
  86. package/.bkit/core/engine/commands/install/install.ts +550 -0
  87. package/.bkit/core/engine/commands/install/uninstall.ts +995 -0
  88. package/.bkit/core/engine/commands/install/upgrade.ts +1037 -0
  89. package/.bkit/core/engine/commands/launch.ts +139 -0
  90. package/.bkit/core/engine/commands/lib.ts +495 -0
  91. package/.bkit/core/engine/commands/registry.ts +53 -0
  92. package/.bkit/core/engine/commands/setup/setup.ts +184 -0
  93. package/.bkit/core/engine/commands/telemetry.ts +32 -0
  94. package/.bkit/core/engine/commands/workflow/branches.ts +1514 -0
  95. package/.bkit/core/engine/commands/workflow/context.ts +961 -0
  96. package/.bkit/core/engine/commands/workflow/counters.ts +268 -0
  97. package/.bkit/core/engine/commands/workflow/fids.ts +243 -0
  98. package/.bkit/core/engine/commands/workflow/issues.ts +675 -0
  99. package/.bkit/core/engine/commands/workflow/ledgers.ts +575 -0
  100. package/.bkit/core/engine/commands/workflow/locks.ts +478 -0
  101. package/.bkit/core/engine/commands/workflow/prs.ts +1087 -0
  102. package/.bkit/core/engine/commands/workflow/repo.ts +220 -0
  103. package/.bkit/core/engine/commands/workflow/roadmap.ts +576 -0
  104. package/.bkit/core/engine/commands/workflow/runs.ts +2140 -0
  105. package/.bkit/core/engine/commands/workflow/runtime.ts +300 -0
  106. package/.bkit/core/engine/commands/workflow/skills.ts +118 -0
  107. package/.bkit/core/engine/commands/workflow/status.ts +455 -0
  108. package/.bkit/core/engine/commands/workflow/steps.ts +1300 -0
  109. package/.bkit/core/engine/commands/workflow/tests.ts +161 -0
  110. package/.bkit/core/engine/commands/workflow/workflows.ts +1573 -0
  111. package/.bkit/core/engine/commands/workflow/workstreams.ts +164 -0
  112. package/.bkit/core/engine/commands/workflow/worktrees.ts +534 -0
  113. package/.bkit/core/engine/install/cloud-env.ts +924 -0
  114. package/.bkit/core/engine/install/managed-block.ts +212 -0
  115. package/.bkit/core/engine/install/manifest.ts +448 -0
  116. package/.bkit/core/engine/install/modules/claude.ts +362 -0
  117. package/.bkit/core/engine/install/modules/cloud.ts +173 -0
  118. package/.bkit/core/engine/install/modules/codex.ts +219 -0
  119. package/.bkit/core/engine/install/modules/core.ts +620 -0
  120. package/.bkit/core/engine/install/modules/cursor.ts +231 -0
  121. package/.bkit/core/engine/install/modules/index.ts +242 -0
  122. package/.bkit/core/engine/install/modules/opencode.ts +573 -0
  123. package/.bkit/core/engine/install/payload-links.ts +150 -0
  124. package/.bkit/core/engine/install/placeholders.ts +108 -0
  125. package/.bkit/core/engine/install/template-copies.ts +119 -0
  126. package/.bkit/core/engine/install/version-file.ts +284 -0
  127. package/.bkit/core/engine/install/write.ts +467 -0
  128. package/.bkit/core/engine/ledgers/clamp-log.ts +32 -0
  129. package/.bkit/core/engine/ledgers/status.ts +213 -0
  130. package/.bkit/core/engine/ledgers/telemetry.ts +1143 -0
  131. package/.bkit/core/engine/render/hosts.ts +372 -0
  132. package/.bkit/core/engine/render/models.ts +323 -0
  133. package/.bkit/core/engine/render/parts.ts +38 -0
  134. package/.bkit/core/engine/render/trackers.ts +170 -0
  135. package/.bkit/core/engine/shared/egress.ts +345 -0
  136. package/.bkit/core/engine/shared/json.ts +16 -0
  137. package/.bkit/core/engine/shared/log-prefix.ts +9 -0
  138. package/.bkit/core/engine/shared/package-json.ts +29 -0
  139. package/.bkit/core/engine/shared/package-manager.ts +38 -0
  140. package/.bkit/core/engine/shared/package-roots.ts +163 -0
  141. package/.bkit/core/engine/shared/protected-paths.ts +164 -0
  142. package/.bkit/core/engine/shared/settings.ts +72 -0
  143. package/.bkit/core/engine/shared/timeouts.ts +20 -0
  144. package/.bkit/core/engine/tools/wording.ts +748 -0
  145. package/.bkit/core/hooks/gateguard-edit-payload.js +18 -0
  146. package/.bkit/core/hooks/gateguard-engine.js +193 -0
  147. package/.bkit/core/hooks/guardrails-shell.js +154 -0
  148. package/.bkit/core/hooks/guardrails-tiers.js +68 -0
  149. package/.bkit/core/hooks/preflight-linear.sh +73 -0
  150. package/.bkit/core/prompts/bkit-audit-generate.md +66 -0
  151. package/.bkit/core/prompts/bkit-build-challenge-1.md +79 -0
  152. package/.bkit/core/prompts/bkit-build-challenge-2.md +81 -0
  153. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +68 -0
  154. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +70 -0
  155. package/.bkit/core/prompts/bkit-build-challenge-tests.md +73 -0
  156. package/.bkit/core/prompts/bkit-build-install-skills.md +67 -0
  157. package/.bkit/core/prompts/bkit-build-plan-current.md +75 -0
  158. package/.bkit/core/prompts/bkit-build-plan-execute.md +72 -0
  159. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +73 -0
  160. package/.bkit/core/prompts/bkit-build-plan-verify.md +88 -0
  161. package/.bkit/core/prompts/bkit-build-summary.md +93 -0
  162. package/.bkit/core/prompts/bkit-debug-abort-handover.md +90 -0
  163. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +151 -0
  164. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +78 -0
  165. package/.bkit/core/prompts/bkit-debug-failure-soak.md +73 -0
  166. package/.bkit/core/prompts/bkit-debug-summary.md +95 -0
  167. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +72 -0
  168. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +72 -0
  169. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +75 -0
  170. package/.bkit/core/prompts/bkit-design-generate.md +110 -0
  171. package/.bkit/core/prompts/bkit-design-organise.md +85 -0
  172. package/.bkit/core/prompts/bkit-design-review-1.md +121 -0
  173. package/.bkit/core/prompts/bkit-design-review-2.md +111 -0
  174. package/.bkit/core/prompts/bkit-design-spike.md +97 -0
  175. package/.bkit/core/prompts/bkit-design-summary.md +106 -0
  176. package/.bkit/core/prompts/bkit-design-update.md +66 -0
  177. package/.bkit/core/prompts/bkit-plan-complexity-check.md +66 -0
  178. package/.bkit/core/prompts/bkit-plan-complexity-split.md +87 -0
  179. package/.bkit/core/prompts/bkit-plan-generate.md +74 -0
  180. package/.bkit/core/prompts/bkit-plan-review-1.md +90 -0
  181. package/.bkit/core/prompts/bkit-plan-review-2.md +80 -0
  182. package/.bkit/core/prompts/bkit-plan-review-3.md +92 -0
  183. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +84 -0
  184. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +84 -0
  185. package/.bkit/core/prompts/bkit-plan-summary.md +106 -0
  186. package/.bkit/core/prompts/bkit-plan-update.md +68 -0
  187. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +90 -0
  188. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +94 -0
  189. package/.bkit/core/prompts/bkit-ship-summary.md +77 -0
  190. package/.bkit/core/prompts/bkit-ship-update-docs.md +71 -0
  191. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +91 -0
  192. package/.bkit/core/prompts/bkit-utility-update-decisions.md +75 -0
  193. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +76 -0
  194. package/.bkit/core/prompts/bkit-utility-update-documentation.md +61 -0
  195. package/.bkit/core/prompts/bkit-utility-update-failures.md +76 -0
  196. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +75 -0
  197. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +82 -0
  198. package/.bkit/core/workflows/bkit-auto.md +121 -0
  199. package/.bkit/core/workflows/bkit-build.md +802 -0
  200. package/.bkit/core/workflows/bkit-debug.md +649 -0
  201. package/.bkit/core/workflows/bkit-design.md +495 -0
  202. package/.bkit/core/workflows/bkit-plan.md +510 -0
  203. package/.bkit/core/workflows/bkit-ship.md +650 -0
  204. package/.bkit/shared/.bkit/.env.example +86 -0
  205. package/.bkit/shared/.claude/bkit-cloud.md +117 -0
  206. package/.bkit/shared/.claude/settings.json +88 -0
  207. package/.bkit/shared/.codex/hooks.json +26 -0
  208. package/.bkit/shared/.cursor/bkit-cloud.md +84 -0
  209. package/.bkit/shared/.cursor/hooks.json +26 -0
  210. package/.bkit/shared/.cursor/mcp.json +15 -0
  211. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +12 -0
  212. package/.bkit/shared/.gitattributes +37 -0
  213. package/.bkit/shared/.mcp.json +16 -0
  214. package/.bkit/shared/.opencode/opencode.json +62 -0
  215. package/.bkit/shared/CLAUDE.md +11 -0
  216. package/.bkit/shared/LICENSE.md +22 -0
  217. package/.bkit/shared/docs/architecture.md +19 -0
  218. package/.bkit/shared/docs/data-schema.md +19 -0
  219. package/.bkit/shared/docs/deployments.md +433 -0
  220. package/.bkit/shared/docs/design.md +39 -0
  221. package/.bkit/shared/docs/noise.md +19 -0
  222. package/.bkit/shared/docs/observability.md +25 -0
  223. package/.bkit/shared/docs/security.md +42 -0
  224. package/.bkit/shared/docs/setup.md +30 -0
  225. package/.bkit/shared/docs/technology.md +18 -0
  226. package/.bkit/shared/docs/testing.md +413 -0
  227. package/.bkit/shared/gitignore +97 -0
  228. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +187 -0
  229. package/.bkit/templates/.cursor/Dockerfile +68 -0
  230. package/.bkit/templates/.cursor/environment.json +6 -0
  231. package/.bkit/templates/.cursor/settings.json +11 -0
  232. package/.bkit/templates/.envrc +7 -0
  233. package/.bkit/templates/.github/dependabot.yml +52 -0
  234. package/.bkit/templates/.github/renovate.json5 +224 -0
  235. package/.bkit/templates/.github/workflows/bkit-ci.yml +1062 -0
  236. package/.bkit/templates/.github/workflows/bkit-cloud.yml +564 -0
  237. package/.bkit/templates/.github/workflows/bkit-renovate.yml +102 -0
  238. package/.bkit/templates/.graphifyignore +108 -0
  239. package/.bkit/templates/.husky/pre-commit +16 -0
  240. package/.bkit/templates/.husky/pre-push +91 -0
  241. package/.bkit/templates/.lintstagedrc.json +3 -0
  242. package/.bkit/templates/.prettierignore +41 -0
  243. package/.bkit/templates/.serena/project.yml +243 -0
  244. package/.bkit/templates/.vale/styles/House/Filler.yml +11 -0
  245. package/.bkit/templates/.vale/styles/House/Hedging.yml +12 -0
  246. package/.bkit/templates/.vale/styles/House/LLMSlop.yml +13 -0
  247. package/.bkit/templates/.vale/styles/House/Verbose.yml +12 -0
  248. package/.bkit/templates/.vale.ini +67 -0
  249. package/.bkit/templates/LICENSE.md +22 -0
  250. package/.bkit/templates/context/bkit-cloudrun.md +84 -0
  251. package/.bkit/templates/context/bkit-expo.md +186 -0
  252. package/.bkit/templates/context/bkit-github.md +79 -0
  253. package/.bkit/templates/context/bkit-inngest.md +45 -0
  254. package/.bkit/templates/context/bkit-maestro.md +76 -0
  255. package/.bkit/templates/context/bkit-playwright.md +62 -0
  256. package/.bkit/templates/context/bkit-resend.md +36 -0
  257. package/.bkit/templates/context/bkit-sentry.md +65 -0
  258. package/.bkit/templates/context/bkit-serena.md +33 -0
  259. package/.bkit/templates/context/bkit-stripe.md +36 -0
  260. package/.bkit/templates/context/bkit-supabase.md +59 -0
  261. package/.bkit/templates/context/bkit-tavily.md +49 -0
  262. package/.bkit/templates/context/bkit-vercel.md +64 -0
  263. package/.bkit/templates/docs/capabilities.md +72 -0
  264. package/.bkit/templates/scripts/ci/accepted-divergences.json +21 -0
  265. package/.bkit/templates/scripts/ci/check-accepted-divergences.mjs +152 -0
  266. package/.bkit/templates/scripts/ci/check-accepted-divergences.test.mjs +130 -0
  267. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +98 -0
  268. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +86 -0
  269. package/.bkit/templates/scripts/graphify/bkit-graph-drift-rules.json +23 -0
  270. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +208 -0
  271. package/.bkit/templates/scripts/graphify/bkit-graph-eager-rules.json +35 -0
  272. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +236 -0
  273. package/.bkit/templates/scripts/graphify/bkit-graph-external-rules.json +17 -0
  274. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +290 -0
  275. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +19 -0
  276. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +120 -0
  277. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +232 -0
  278. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +36 -0
  279. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +927 -0
  280. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +351 -0
  281. package/.bkit/templates/scripts/launchd/ai.bkit.launchd.plist +26 -0
  282. package/.bkit/templates/scripts/launchd/bkit-launchd-env.sh +53 -0
  283. package/.bkit/templates/scripts/launchd/launchd.env.example +13 -0
  284. package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +275 -0
  285. package/.bkit/templates/scripts/secrets/bkit-secrets.config.mjs +66 -0
  286. package/.bkit/templates/scripts/secrets/bkit-secrets.mjs +785 -0
  287. package/.bkit/templates/scripts/serena/bkit-serena-mcp.sh +30 -0
  288. package/.bkit/templates/scripts/serena/bkit-serena.mcp.json +9 -0
  289. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +286 -0
  290. package/.bkit/templates/slop-scan.config.json +120 -0
  291. package/CHANGELOG.md +1503 -0
  292. package/LICENSE.md +161 -0
  293. package/README.md +184 -2
  294. package/dist/checks/after/auth.js +140 -0
  295. package/dist/checks/after/ci-yml.js +681 -0
  296. package/dist/checks/after/github.js +400 -0
  297. package/dist/checks/after/index.js +431 -0
  298. package/dist/checks/after/managed.js +187 -0
  299. package/dist/checks/after/suppression.js +39 -0
  300. package/dist/checks/after/tools.js +351 -0
  301. package/dist/checks/before/context-fetch.js +426 -0
  302. package/dist/checks/before/env.js +163 -0
  303. package/dist/checks/before/files.js +187 -0
  304. package/dist/checks/before/index.js +162 -0
  305. package/dist/checks/before/mcp.js +111 -0
  306. package/dist/checks/before/repo.js +71 -0
  307. package/dist/checks/before/version.js +60 -0
  308. package/dist/checks/status-holes.js +393 -0
  309. package/dist/cli.js +688 -0
  310. package/dist/commands/analysis.js +325 -0
  311. package/dist/commands/ci/ci.js +438 -0
  312. package/dist/commands/comply.js +310 -0
  313. package/dist/commands/harvest.js +354 -0
  314. package/dist/commands/install/check.js +61 -0
  315. package/dist/commands/install/doctor.js +209 -0
  316. package/dist/commands/install/install.js +475 -0
  317. package/dist/commands/install/uninstall.js +839 -0
  318. package/dist/commands/install/upgrade.js +782 -0
  319. package/dist/commands/launch.js +118 -0
  320. package/dist/commands/lib.js +363 -0
  321. package/dist/commands/registry.js +50 -0
  322. package/dist/commands/setup/setup.js +158 -0
  323. package/dist/commands/telemetry.js +29 -0
  324. package/dist/commands/workflow/branches.js +1265 -0
  325. package/dist/commands/workflow/context.js +846 -0
  326. package/dist/commands/workflow/counters.js +227 -0
  327. package/dist/commands/workflow/fids.js +224 -0
  328. package/dist/commands/workflow/issues.js +585 -0
  329. package/dist/commands/workflow/ledgers.js +472 -0
  330. package/dist/commands/workflow/locks.js +364 -0
  331. package/dist/commands/workflow/prs.js +904 -0
  332. package/dist/commands/workflow/repo.js +199 -0
  333. package/dist/commands/workflow/roadmap.js +495 -0
  334. package/dist/commands/workflow/runs.js +1717 -0
  335. package/dist/commands/workflow/runtime.js +257 -0
  336. package/dist/commands/workflow/skills.js +110 -0
  337. package/dist/commands/workflow/status.js +392 -0
  338. package/dist/commands/workflow/steps.js +1093 -0
  339. package/dist/commands/workflow/tests.js +144 -0
  340. package/dist/commands/workflow/workflows.js +1342 -0
  341. package/dist/commands/workflow/workstreams.js +141 -0
  342. package/dist/commands/workflow/worktrees.js +473 -0
  343. package/dist/install/cloud-env.js +818 -0
  344. package/dist/install/managed-block.js +182 -0
  345. package/dist/install/manifest.js +376 -0
  346. package/dist/install/modules/claude.js +288 -0
  347. package/dist/install/modules/cloud.js +151 -0
  348. package/dist/install/modules/codex.js +193 -0
  349. package/dist/install/modules/core.js +531 -0
  350. package/dist/install/modules/cursor.js +186 -0
  351. package/dist/install/modules/index.js +152 -0
  352. package/dist/install/modules/opencode.js +504 -0
  353. package/dist/install/payload-links.js +119 -0
  354. package/dist/install/placeholders.js +87 -0
  355. package/dist/install/template-copies.js +106 -0
  356. package/dist/install/version-file.js +204 -0
  357. package/dist/install/write.js +342 -0
  358. package/dist/ledgers/clamp-log.js +27 -0
  359. package/dist/ledgers/status.js +156 -0
  360. package/dist/ledgers/telemetry.js +637 -0
  361. package/dist/render/hosts.js +339 -0
  362. package/dist/render/models.js +288 -0
  363. package/dist/render/parts.js +33 -0
  364. package/dist/render/trackers.js +135 -0
  365. package/dist/shared/egress.js +299 -0
  366. package/dist/shared/json.js +16 -0
  367. package/dist/shared/log-prefix.js +7 -0
  368. package/dist/shared/package-json.js +22 -0
  369. package/dist/shared/package-manager.js +32 -0
  370. package/dist/shared/package-roots.js +145 -0
  371. package/dist/shared/protected-paths.js +153 -0
  372. package/dist/shared/settings.js +44 -0
  373. package/dist/shared/timeouts.js +19 -0
  374. package/dist/tools/wording.js +680 -0
  375. package/package.json +101 -4
@@ -0,0 +1,927 @@
1
+ # Example. Copy into the repo and own it.
2
+ # bkit install does not write this file and does not overwrite a copy.
3
+ # Adapt app roots, the workspace package scope, and the rules JSON to this repo.
4
+
5
+ #!/usr/bin/env python3
6
+ """Collapse the whole-symbol code graph into two readable views.
7
+
8
+ Called by `pnpm graph:rollup` and `pnpm graph:graphml` (scripts/graphify/
9
+ bkit-graphify.sh) through GRAPHIFY'S OWN interpreter, not the system python — it
10
+ imports networkx, which is a graphify dependency and is not installed repo-wide.
11
+
12
+ bkit-graphify-rollup.py <graph.json> [--build-dir DIR]
13
+ [--packages-graphml P] [--modules-graphml M]
14
+
15
+ Both outputs are opt-in, and the two commands ask for different ones:
16
+
17
+ --build-dir a graphify-format graph.json per level, which the caller
18
+ renders to interactive HTML via `graphify cluster-only`,
19
+ then moves and deletes. This is `pnpm graph:rollup`.
20
+ --*-graphml the same two views as GraphML for Gephi. Only `pnpm
21
+ graph:graphml` asks for these — GraphML is not produced by
22
+ default.
23
+
24
+ Node attrs: symbols, files, internal_edges. Edge attrs: weight (number of
25
+ underlying symbol edges) and relations (top three kinds, e.g.
26
+ `calls:115,imports_from:107`).
27
+ """
28
+
29
+ import argparse
30
+ import collections
31
+ import hashlib
32
+ import json
33
+ import os
34
+ import re
35
+
36
+ ap = argparse.ArgumentParser()
37
+ ap.add_argument("graph_json")
38
+ ap.add_argument("--build-dir")
39
+ ap.add_argument("--packages-graphml")
40
+ ap.add_argument("--modules-graphml")
41
+ ap.add_argument("--packages-mermaid")
42
+ ap.add_argument("--modules-mermaid")
43
+ ap.add_argument("--capabilities-doc")
44
+ ap.add_argument("--surface")
45
+ ap.add_argument("--eager")
46
+ ap.add_argument("--reachability")
47
+ ap.add_argument("--min-weight", type=int, default=0,
48
+ help="drop cross-group edges lighter than this (0 = keep all)")
49
+ ap.add_argument("--overlay",
50
+ help="JSON {path_prefix: [class, note]} painting drift status onto "
51
+ "matching nodes. class is one of split|bypassed|gap.")
52
+ args = ap.parse_args()
53
+
54
+ raw = json.load(open(args.graph_json))
55
+ ns = {n["id"]: n for n in raw["nodes"]}
56
+ _REPAIRED_EDGES = None # set after graph_imports is importable, below
57
+ SRC = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".sql")
58
+
59
+ # graphify misses two whole classes of import: a `.js` specifier is never
60
+ # resolved to a `.tsx` file, and workspace subpaths through an `exports` map are
61
+ # not resolved at all. ~540 edges on this repo. bkit-graph-repair.py writes them into
62
+ # graph.json during `pnpm graph`, so this reads them like any other edge and
63
+ # does NOT re-derive them. A graph built without that step gets a warning, and the
64
+ # numbers below are understated.
65
+ # bkit-graph-imports.py is hyphenated, which `import` cannot spell, so it is loaded
66
+ # by path.
67
+ import importlib.util as _ilu
68
+ _spec = _ilu.spec_from_file_location(
69
+ "graph_imports",
70
+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "bkit-graph-imports.py"))
71
+ graph_imports = _ilu.module_from_spec(_spec)
72
+ _spec.loader.exec_module(graph_imports)
73
+
74
+ _REPAIRED_EDGES = graph_imports.warn_if_unrepaired(raw, "graph")
75
+
76
+
77
+ def sf(i):
78
+ return str(ns.get(i, {}).get("source_file") or "")
79
+
80
+
81
+ # Manifest/config endpoints are dropped: package.json stays in the CORPUS for
82
+ # resolution, but package.json -> package.json edges are not drawn.
83
+ def is_src(p):
84
+ return p.endswith(SRC)
85
+
86
+
87
+ # Test code is IN the graph (.graphifyignore keeps it, so `graphify affected` sees test
88
+ # callers, and graph.json, GraphML and the HTML views all carry it) and OUT of the Mermaid
89
+ # pictures. Wider than bkit-graph-drift.py's test SURFACE, which partitions the register's
90
+ # counts; this one only decides what a picture draws.
91
+ TEST_DIRS = {"e2e", "__tests__", "__mocks__", "__fixtures__", "__snapshots__", "fixtures",
92
+ "test", "tests", "testing", "test-utils"}
93
+ TEST_FILE = re.compile(r"\.(?:test|spec)\.[^/]+$|(?:^|/)(?:vitest|jest|playwright)\.(?:config|setup|workspace)[^/]*$")
94
+
95
+
96
+ def is_test_code(p):
97
+ """True for a test file, test-runner config, or any path under a test folder.
98
+
99
+ Takes a file path or a folder key (`apps/web/e2e/helpers`), so the same check
100
+ filters graph nodes, drift rows and the route chain's caller modules."""
101
+ return any(seg in TEST_DIRS for seg in p.split("/")) or bool(TEST_FILE.search(p))
102
+
103
+
104
+ def by_package(p):
105
+ m = re.match(r"(apps/[^/]+|packages/[^/]+|tooling/[^/]+|scripts|supabase)", p)
106
+ return m.group(1) if m else None
107
+
108
+
109
+ def by_module(p):
110
+ return "/".join(p.split("/")[:-1][:4]) or p.split("/")[0]
111
+
112
+
113
+ def collapse(keyfn, include_tests=True):
114
+ """Group every source symbol by keyfn(path), and sum the edges between groups.
115
+
116
+ One pass, three consumers (GraphML, graphify-JSON, Mermaid) — they differ only
117
+ in how they serialise the same counters. Mermaid passes include_tests=False:
118
+ a test file's symbols and edges then count toward no box, so a folder holding
119
+ `x.ts` and `x.test.ts` is drawn with `x.ts` alone.
120
+ """
121
+ keep = (lambda p: is_src(p)) if include_tests else (lambda p: is_src(p) and not is_test_code(p))
122
+ symbols, files, internal = collections.Counter(), collections.defaultdict(set), collections.Counter()
123
+ for n in raw["nodes"]:
124
+ p = str(n.get("source_file") or "")
125
+ if not keep(p):
126
+ continue
127
+ k = keyfn(p)
128
+ if k:
129
+ symbols[k] += 1
130
+ files[k].add(p)
131
+ edges, rels = collections.Counter(), collections.defaultdict(collections.Counter)
132
+ for l in raw["links"]:
133
+ a, b = sf(l["source"]), sf(l["target"])
134
+ if not (keep(a) and keep(b)):
135
+ continue
136
+ ka, kb = keyfn(a), keyfn(b)
137
+ if not (ka and kb):
138
+ continue
139
+ if ka == kb:
140
+ internal[ka] += 1
141
+ else:
142
+ edges[(ka, kb)] += 1
143
+ rels[(ka, kb)][l.get("relation")] += 1
144
+ return symbols, files, internal, edges, rels
145
+
146
+
147
+ def rollup(keyfn, out, level):
148
+ # Only the GraphML path needs networkx; --mermaid runs under system python.
149
+ import networkx as nx
150
+
151
+ symbols, files, internal, edges, rels = collapse(keyfn)
152
+ G = nx.DiGraph()
153
+ for k in symbols:
154
+ G.add_node(k, label=k, level=level, symbols=symbols[k],
155
+ files=len(files[k]), internal_edges=internal[k])
156
+ for (a, b), w in edges.items():
157
+ G.add_edge(a, b, weight=w,
158
+ relations=",".join(f"{r}:{c}" for r, c in rels[(a, b)].most_common(3)))
159
+ os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
160
+ nx.write_graphml(G, out)
161
+ print(f"[graph] {out}: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")
162
+
163
+
164
+ def as_graphify_json(keyfn, out_dir):
165
+ """Write the rollup in graphify's own node-link format.
166
+
167
+ `graphify cluster-only` then renders it with the SAME interactive viz as the
168
+ full graph — click a node, its neighbours highlight and everything else dims.
169
+ """
170
+ sym, files = collections.Counter(), collections.defaultdict(set)
171
+ for n in raw["nodes"]:
172
+ p = str(n.get("source_file") or "")
173
+ k = keyfn(p) if is_src(p) else None
174
+ if k:
175
+ sym[k] += 1
176
+ files[k].add(p)
177
+ ew, er = collections.Counter(), collections.defaultdict(collections.Counter)
178
+ for l in raw["links"]:
179
+ a, b = sf(l["source"]), sf(l["target"])
180
+ if not (is_src(a) and is_src(b)):
181
+ continue
182
+ ka, kb = keyfn(a), keyfn(b)
183
+ if ka and kb and ka != kb:
184
+ ew[(ka, kb)] += 1
185
+ er[(ka, kb)][l.get("relation")] += 1
186
+ groups = sorted(sym)
187
+ payload = {
188
+ "directed": True, "multigraph": False, "graph": {}, "hyperedges": [],
189
+ "nodes": [{"id": g, "label": g, "community": i,
190
+ "community_name": g.split("/")[0], "source_file": g,
191
+ "source_location": f"{len(files[g])} files, {sym[g]} symbols",
192
+ "file_type": "code", "norm_label": g,
193
+ "_callable": False, "_origin": "rollup"}
194
+ for i, g in enumerate(groups)],
195
+ "links": [{"source": a, "target": b, "relation": "imports",
196
+ "weight": float(w), "confidence": "EXTRACTED",
197
+ "confidence_score": 1.0, "source_file": a,
198
+ "source_location": f"weight {w}",
199
+ "context": ",".join(f"{r}:{c}" for r, c in er[(a, b)].most_common(3))}
200
+ for (a, b), w in ew.items()],
201
+ }
202
+ # cluster-only reads <dir>/graphify-out/graph.json; the caller runs it with
203
+ # GRAPHIFY_OUT pinned to that default so this layout holds wherever the real
204
+ # output dir points.
205
+ os.makedirs(f"{out_dir}/graphify-out", exist_ok=True)
206
+ json.dump(payload, open(f"{out_dir}/graphify-out/graph.json", "w"))
207
+ return len(payload["nodes"]), len(payload["links"])
208
+
209
+
210
+ # Two visual channels, one meaning each:
211
+ # colour = the CALLED capability. A node that is called owns a hue, and
212
+ # every edge INTO it takes that hue, so all the callers of one
213
+ # capability are one colour and can be followed back at a glance.
214
+ # A node nothing calls has no hue and stays grey — web and mobile
215
+ # routes only ever call, so the whole UI column is grey.
216
+ # dash + fill = drift status.
217
+ # Hues are mid-tone, legible on both the light and dark Mermaid themes. An undrifted
218
+ # node sets no fill, so it keeps the theme's background and text colour.
219
+ PALETTE = [
220
+ "#d73a4a", "#0969da", "#1a7f37", "#9a6700", "#8250df", "#bf3989",
221
+ "#0e7490", "#a0522d", "#5b8c00", "#b45309", "#6d28d9", "#be123c",
222
+ "#0f766e", "#4d7c0f", "#a21caf", "#1d4ed8", "#c2410c", "#15803d",
223
+ "#7c3aed", "#b91c1c", "#0891b2", "#65a30d", "#c026d3", "#2563eb",
224
+ ]
225
+ # Drift = a dashed border plus a tinted box; no tint and a solid border means no
226
+ # drift. Each drift status has its own dash pattern. The status colours the BOX;
227
+ # the label carries no emoji (GitHub renders Mermaid at securityLevel strict).
228
+ # Every fill pins its own `color` (INK), so text stays dark on any theme.
229
+ INK, PAPER = "#1f2328", "#ffffff"
230
+ # ONE colour (amber) for every drift status; the status word and the dash pattern
231
+ # tell them apart.
232
+ WARN = "#ffcc80"
233
+ # `budgeted` is the one marked state that is NOT a warning: solid border, blue tint.
234
+ # It still gets a box. Blue, not green: green reads as `one`.
235
+ SETTLED = "#cfe2f3"
236
+ DRIFT_STYLE = {"split": f"stroke-width:4px,stroke-dasharray:2 3,fill:{WARN},color:{INK}",
237
+ "bypassed": f"stroke-width:4px,stroke-dasharray:8 4,fill:{WARN},color:{INK}",
238
+ "gap": f"stroke-width:3px,stroke-dasharray:1 5,fill:{WARN},color:{INK}",
239
+ "dead": f"stroke-width:4px,stroke-dasharray:3 3,fill:{WARN},color:{INK}",
240
+ "budgeted": f"stroke-width:3px,fill:{SETTLED},color:{INK}",
241
+ "ok": "stroke-width:2px"}
242
+
243
+
244
+ def hue(key):
245
+ """Stable per-node colour. Hashed, not enumerated, so adding a node upstream
246
+ does not recolour every node after it and churn the whole diff."""
247
+ return PALETTE[int(hashlib.md5(key.encode()).hexdigest(), 16) % len(PALETTE)]
248
+
249
+
250
+ GREY = "#8b949e"
251
+
252
+
253
+ def style_lines(nodes, edge_target_keys):
254
+ """`style` per node and `linkStyle` per edge.
255
+
256
+ Pass the TARGET key of each edge, in emission order — linkStyle indexes are
257
+ that order, and the colour belongs to the capability being called, not the
258
+ caller. A node that is never a target keeps the grey default.
259
+ """
260
+ called = set(edge_target_keys)
261
+ out = [f" style {nid} stroke:{hue(key) if key in called else GREY},{DRIFT_STYLE[cls]}"
262
+ for nid, key, cls in nodes]
263
+ for i, tgt_key in enumerate(edge_target_keys):
264
+ out.append(f" linkStyle {i} stroke:{hue(tgt_key)},stroke-width:2px")
265
+ return out
266
+
267
+
268
+ OV_START, OV_END = "<!-- overrides:start -->", "<!-- overrides:end -->"
269
+ # Pasting the whole fenced block (or past its end) into an online editor fails to parse.
270
+ VIEW_ONLINE = ("To view online, paste only the lines inside the block below — not the "
271
+ "fence lines — into [mermaid.live](https://mermaid.live/).")
272
+ OV_DEFAULT = """{
273
+ "rename": {},
274
+ "note": {},
275
+ "hide_nodes": [],
276
+ "hide_edges": [],
277
+ "group": {}
278
+ }"""
279
+
280
+
281
+ def read_overrides(doc_path):
282
+ """Recover the hand-maintained overrides block from the generated doc.
283
+
284
+ The doc is otherwise rewritten wholesale, so this one region round-trips:
285
+ read before writing, re-emitted verbatim. It is the only part of
286
+ capabilities.md a human is meant to touch.
287
+
288
+ An overrides block with no ```json fence, or with invalid JSON, RAISES; the
289
+ file is never rewritten without its overrides.
290
+ """
291
+ if not doc_path or not os.path.exists(doc_path):
292
+ return json.loads(OV_DEFAULT), OV_DEFAULT
293
+ text = open(doc_path, encoding="utf-8").read()
294
+ if OV_START not in text:
295
+ return json.loads(OV_DEFAULT), OV_DEFAULT
296
+ body = text.split(OV_START, 1)[1].split(OV_END, 1)[0]
297
+ m = re.search(r"```json\n(.*?)```", body, re.S)
298
+ if not m:
299
+ raise SystemExit(f"[graph] {doc_path}: overrides block present but has no ```json fence. "
300
+ "Refusing to overwrite it; fix or delete the block.")
301
+ try:
302
+ return json.loads(m.group(1)), m.group(1).rstrip()
303
+ except json.JSONDecodeError as e:
304
+ raise SystemExit(f"[graph] {doc_path}: overrides block is not valid JSON ({e}). "
305
+ "Refusing to overwrite it.")
306
+
307
+
308
+ def resolve_paint(overlay, keys):
309
+ """Map each drift row to exactly ONE node — the most specific one present.
310
+
311
+ The overlay keys a row by the owner FILE; a diagram's nodes are directories at
312
+ whatever depth that view uses. Longest matching key wins; ties cannot occur
313
+ because one key is a prefix of the other.
314
+ """
315
+ # Rows landing on one node merge: worst status wins the border, every note is
316
+ # kept, sorted by this rank (worst first). `budgeted` ranks below every warning.
317
+ rank = {"split": 3, "bypassed": 2, "gap": 1, "budgeted": 0}
318
+ acc = collections.defaultdict(list)
319
+ for okey, val in overlay.items():
320
+ best = None
321
+ for k in keys:
322
+ if k == okey or okey.startswith(k.rstrip("/") + "/"):
323
+ if best is None or len(k) > len(best):
324
+ best = k
325
+ if best is not None:
326
+ acc[best].append(val)
327
+ out = {}
328
+ for k, vals in acc.items():
329
+ cls = max((v[0] for v in vals), key=lambda c: rank.get(c, 0))
330
+ out[k] = (cls, " · ".join(v[1] for v in sorted(vals, key=lambda v: -rank.get(v[0], 0))))
331
+ return out
332
+
333
+
334
+ def as_mermaid(keyfn, out, level, min_weight, overlay):
335
+ """Emit the rollup as a Mermaid flowchart, nested by folder.
336
+
337
+ Grouping is the directory tree, not a clustering algorithm — `apps/web` is a
338
+ subgraph, its subfolders are the nodes inside it. Nothing is inferred, so the
339
+ picture cannot disagree with the repo layout.
340
+
341
+ GOTCHA, and it costs an afternoon: a subgraph id must never equal a node id.
342
+ by_module("apps/web/x.ts") is "apps/web", which is also its by_package group,
343
+ and Mermaid then fails with "Setting napps_web as parent of napps_web would
344
+ create a cycle" (dagre) or "Referenced shape does not exist" (ELK) — neither
345
+ of which names the collision. Group ids therefore carry a `g` prefix.
346
+ """
347
+ symbols, files, _internal, edges, _rels = collapse(keyfn, include_tests=False)
348
+ overlay = {k: v for k, v in overlay.items() if not is_test_code(k)}
349
+ hidden = set(OVERRIDES.get("hide_nodes", []))
350
+ hidden_edges = {tuple(e) for e in OVERRIDES.get("hide_edges", [])}
351
+ renames = OVERRIDES.get("rename", {})
352
+ extra_notes = OVERRIDES.get("note", {})
353
+ forced = {n: g for g, members in OVERRIDES.get("group", {}).items() for n in members}
354
+ edges = {k: v for k, v in edges.items()
355
+ if v >= min_weight and k not in hidden_edges
356
+ and k[0] not in hidden and k[1] not in hidden}
357
+ keep = ({x for e in edges for x in e} | {k for k in overlay if k in symbols}) - hidden
358
+ sid = lambda k: "n" + re.sub(r"[^a-z0-9]", "_", k.lower())
359
+
360
+ resolved = resolve_paint(overlay, keep)
361
+
362
+ def paint(k):
363
+ if k in resolved:
364
+ cls, note = resolved[k]
365
+ return cls, "<br/>" + note
366
+ return "ok", ""
367
+
368
+ L = ["---", "config:", " layout: elk", " flowchart:", " useMaxWidth: false", "---",
369
+ "flowchart LR",
370
+ f" %% Generated by bkit-graphify-rollup.py from {raw.get('built_at_commit', '?')} — do not edit"]
371
+ NODES, ELIST = [], []
372
+ def node(k, label, indent):
373
+ cls, note = paint(k)
374
+ label = renames.get(k, label)
375
+ if k in extra_notes:
376
+ note += "<br/>" + extra_notes[k]
377
+ NODES.append((sid(k), k, cls))
378
+ L.append(f'{indent}{sid(k)}["{label}<br/>'
379
+ f'{symbols[k]} symbols · {len(files[k])} files{note}"]')
380
+
381
+ if level == "package":
382
+ # The group IS the node at this level; no subgraph per group.
383
+ for k in sorted(keep):
384
+ node(k, k, " ")
385
+ else:
386
+ # The folder tree, drawn as nested subgraphs — Mermaid nests them to any
387
+ # depth. A chain of single-child directories (apps > apps/web > .../src)
388
+ # is collapsed into one box titled with the joined path.
389
+ grouped = collections.defaultdict(list)
390
+ for k in sorted(keep):
391
+ if k in forced:
392
+ grouped[forced[k]].append(k)
393
+ for g, members in sorted(grouped.items()):
394
+ L.append(f' subgraph g{sid("custom-" + g)}["{g}"]')
395
+ for k in members:
396
+ node(k, k, " ")
397
+ L.append(" end")
398
+
399
+ tree = {}
400
+ for k in sorted(keep):
401
+ if k in forced:
402
+ continue
403
+ cur = tree
404
+ for seg in k.split("/"):
405
+ cur = cur.setdefault(seg, {})
406
+ cur["__leaf__"] = k
407
+
408
+ def emit(subtree, path, depth, root=False):
409
+ dirs = {k: v for k, v in subtree.items() if k != "__leaf__"}
410
+ leaf = subtree.get("__leaf__")
411
+ pad = " " * (depth + 1)
412
+ if leaf and not dirs:
413
+ # At the top level the short name has lost its folder, so carry the path.
414
+ node(leaf, path if root else path.split("/")[-1], pad)
415
+ return
416
+ title, inner = path, subtree
417
+ while not inner.get("__leaf__") and len(
418
+ {k: v for k, v in inner.items() if k != "__leaf__"}) == 1:
419
+ only = next(k for k in inner if k != "__leaf__")
420
+ title, inner = f"{title}/{only}", inner[only]
421
+ inner_dirs = {k: v for k, v in inner.items() if k != "__leaf__"}
422
+ if inner.get("__leaf__") and not inner_dirs:
423
+ # A box around exactly one node is the node, drawn twice. Emit the
424
+ # node carrying the full path instead, so it keeps its context.
425
+ node(inner["__leaf__"], title, pad)
426
+ return
427
+ L.append(f'{pad}subgraph g{sid(title)}["{title}"]')
428
+ if inner.get("__leaf__"):
429
+ node(inner["__leaf__"], title.split("/")[-1], pad + " ")
430
+ for seg, sub in sorted((k, v) for k, v in inner.items() if k != "__leaf__"):
431
+ emit(sub, f"{title}/{seg}", depth + 1)
432
+ L.append(f"{pad}end")
433
+
434
+ # The root segment is dropped: an `apps` box around apps/web and apps/mobile
435
+ # only says they are both apps, which their own titles already carry. Every
436
+ # level below it groups things whose short labels do NOT say where they live.
437
+ for seg, sub in sorted(tree.items()):
438
+ if sub.get("__leaf__"):
439
+ node(sub["__leaf__"], seg, " ")
440
+ for child, sub2 in sorted((k, v) for k, v in sub.items() if k != "__leaf__"):
441
+ emit(sub2, f"{seg}/{child}", 0, root=True)
442
+
443
+ for (a, b), w in sorted(edges.items(), key=lambda x: -x[1]):
444
+ ELIST.append(b)
445
+ L.append(f" {sid(a)} -->|{w}| {sid(b)}")
446
+ L += style_lines(NODES, ELIST)
447
+ # The YAML front matter must be the FIRST thing in the file. A leading %%
448
+ # provenance comment makes Mermaid fail with a bare "Parse error on line 1"
449
+ # that names nothing, so the marker goes inside the graph instead.
450
+ text = "\n".join(L) + "\n"
451
+ if out:
452
+ with open(out, "w") as fh:
453
+ fh.write(text)
454
+ print(f"[graph] {out or 'inline'}: {len(keep)} nodes, {len(edges)} edges "
455
+ f"(level={level}, min-weight={min_weight}, {len(overlay)} drift markers)")
456
+ return text
457
+
458
+
459
+ def chain_block(surface, overlay, reach):
460
+ """UI -> api -> backend -> external, left to right, in one graph.
461
+
462
+ Five columns, each a real artifact: the route file, the /api/v1 segment, the
463
+ Hono router that serves it, the service module the router imports, and the
464
+ external provider that module talks to. Drift status is painted on the backend
465
+ column, so a `split` capability is visible in the same picture as the routes
466
+ that depend on it.
467
+
468
+ hide_nodes from the doc's overrides block applies here too — a node id is the
469
+ route path, the endpoint segment, the module key, the provider name, or a
470
+ `METHOD /path` string from the reachability scan.
471
+ """
472
+ if not surface:
473
+ return None, 0
474
+ routes, eps = surface.get("routes", {}), surface.get("endpoints", {})
475
+ ext = surface.get("external", {})
476
+ hidden = set(OVERRIDES.get("hide_nodes", []))
477
+ renames = OVERRIDES.get("rename", {})
478
+ sid = lambda pre, k: pre + re.sub(r"[^a-z0-9]", "_", k.lower())
479
+
480
+ def paint(k):
481
+ if k in RESOLVED:
482
+ cls, note = RESOLVED[k]
483
+ return cls, "<br/>" + note
484
+ return "ok", ""
485
+
486
+ used_eps = sorted({e for r, d in routes.items() if r not in hidden for e in d["endpoints"]}
487
+ - hidden)
488
+ routers = {seg: eps.get(seg, {}).get("routers", []) for seg in used_eps}
489
+ svc_of = {seg: eps.get(seg, {}).get("services", []) for seg in used_eps}
490
+ # Three sources, all normalised to the SAME module key, or the node cannot
491
+ # take an edge and floats:
492
+ # 1. routers' service imports — the spine of the chain
493
+ # 2. drift owners — kept even when no router reaches them, else 6 of 7 drift
494
+ # rows vanish and the chain reads clean. The overlay keys them by FILE
495
+ # (packages/storage/src/admin.ts) while edges join on MODULE, so they get
496
+ # folded up here; without that they are guaranteed orphans.
497
+ # 3. external callers — a provider whose caller is absent has nothing to
498
+ # attach to, which is what stranded Upstash, Resend and OpenRouter.
499
+ to_mod = lambda p: "/".join(p.split("/")[:-1][:4]) or p
500
+ reached = {f"packages/services/src/{s}" for v in svc_of.values() for s in v}
501
+ drifted = {to_mod(k) if k.endswith((".ts", ".tsx")) else k
502
+ for k in overlay if k.startswith(("packages/", "apps/"))}
503
+ # Only callers of a SHOWN provider. Pulling in callers of hidden ones adds a
504
+ # module whose only edge was to the thing just hidden — apps/web/src/app and
505
+ # packages/constants/src arrived this way, reaching nothing but the social
506
+ # links in the footer.
507
+ ext_callers = {c for pv in ext if pv not in hidden for c in ext[pv]["callers"]
508
+ if not is_test_code(c)}
509
+ mods = sorted(m for m in (reached | drifted | ext_callers) - hidden if not is_test_code(m))
510
+ RESOLVED = resolve_paint(overlay, mods)
511
+ # A provider only test code calls is not drawn.
512
+ provs = sorted(p for p in ext if p not in hidden
513
+ and any(not is_test_code(c) for c in ext[p]["callers"]))
514
+
515
+ L = ["---", "config:", " layout: elk", " flowchart:", " useMaxWidth: false", "---",
516
+ "flowchart LR"]
517
+ NODES, ELIST = [], []
518
+
519
+ def decl(nid, key, label, cls="ok", indent=" "):
520
+ NODES.append((nid, key, cls))
521
+ L.append(f'{indent}{nid}["{label}"]')
522
+
523
+ for platform, title in (("web", "apps/web routes"), ("native", "apps/mobile routes")):
524
+ members = [r for r, d in sorted(routes.items())
525
+ if d["platform"] == platform and r not in hidden]
526
+ if members:
527
+ L.append(f' subgraph gp_{platform}["UI — {title}"]')
528
+ for r in members:
529
+ decl(sid("r_", r), r, renames.get(r, r))
530
+ L.append(" end")
531
+
532
+ L.append(' subgraph gp_ep["API — /api/v1 endpoints"]')
533
+ for seg in used_eps:
534
+ decl(sid("e_", seg), seg, f"/{seg}")
535
+ L.append(" end")
536
+
537
+ # The one class of drift the edges can never show. A request URL is a string
538
+ # inside a template literal, so a call to a route that does not exist has no
539
+ # edge to be missing — it is simply absent, and absence is invisible. Giving
540
+ # it its own column is what makes it visible AS an absence, in the same
541
+ # picture as the endpoints that do resolve.
542
+ dead = [(k, d["sites"], d["refusedBy"])
543
+ for k, d in sorted((reach or {}).get("unreachable", {}).items()) if k not in hidden]
544
+ # A stranded route that is also a dead fetch is drawn once, from the dead list
545
+ # (Mermaid keeps only the second label of a duplicate node id).
546
+ dead_keys = {k for k, _, _ in dead}
547
+ stranded = [r for r in (reach or {}).get("strandedHonoRoutes", [])
548
+ if r not in hidden and r not in dead_keys]
549
+ if dead or stranded:
550
+ L.append(' subgraph gp_dead["UNREACHABLE — 404 at runtime"]')
551
+ for key, sites, refused in dead:
552
+ where = "<br/>".join(sites[:3]) + ("<br/>…" if len(sites) > 3 else "")
553
+ decl(sid("d_", key), key, f"{key}<br/>{refused}<br/>{where}", "dead")
554
+ for r in stranded:
555
+ decl(sid("d_", r), r, f"{r}<br/>registered in Hono, nothing forwards it", "dead")
556
+ L.append(" end")
557
+
558
+ all_routers = sorted({rf for v in routers.values() for rf in v} - hidden)
559
+ L.append(' subgraph gp_rt["API — Hono routers"]')
560
+ for rf in all_routers:
561
+ decl(sid("t_", rf), rf, f"routes/{rf}.ts")
562
+ L.append(" end")
563
+
564
+ L.append(' subgraph gp_svc["BACKEND — modules"]')
565
+ for m in mods:
566
+ cls, note = paint(m)
567
+ decl(sid("s_", m), m, f"{renames.get(m, m)}{note}", cls)
568
+ L.append(" end")
569
+
570
+ if provs:
571
+ L.append(' subgraph gp_ext["EXTERNAL — third-party APIs"]')
572
+ for pv in provs:
573
+ d = ext[pv]
574
+ # Reached by BOTH a client library and a hand-rolled fetch = two
575
+ # mechanisms for one capability. env+sdk is one mechanism (an SDK
576
+ # reading its DSN from env).
577
+ two_ways = "sdk" in d["via"] and "url" in d["via"]
578
+ detail = f"{len(d['endpoints'])} endpoint{'' if len(d['endpoints']) == 1 else 's'}" \
579
+ if d["endpoints"] else "SDK"
580
+ if two_ways:
581
+ detail += " · SDK *and* raw fetch"
582
+ outside = [c for c in d["callers"] if f"packages/services/src/{c.split('/')[-1]}" not in mods
583
+ and c not in mods]
584
+ extra = f"<br/>also: {', '.join(outside[:2])}" if outside else ""
585
+ decl(sid("x_", pv), pv, f'{pv}<br/>{detail} · via {"+".join(d["via"])}{extra}',
586
+ "split" if two_ways else "ok")
587
+ L.append(" end")
588
+
589
+ drawn = set()
590
+
591
+ def edge(a, b, tgt_key):
592
+ if (a, b) not in drawn:
593
+ drawn.add((a, b))
594
+ ELIST.append(tgt_key)
595
+ L.append(f" {a} --> {b}")
596
+
597
+ for r, d in sorted(routes.items()):
598
+ if r in hidden:
599
+ continue
600
+ for seg in d["endpoints"]:
601
+ if seg in used_eps:
602
+ edge(sid("r_", r), sid("e_", seg), seg)
603
+ for seg in used_eps:
604
+ for rf in routers[seg]:
605
+ if rf not in hidden:
606
+ edge(sid("e_", seg), sid("t_", rf), rf)
607
+ for sv in svc_of[seg]:
608
+ m = f"packages/services/src/{sv}"
609
+ if m in mods:
610
+ edge(sid("t_", rf), sid("s_", m), m)
611
+ for pv in provs:
612
+ for c in ext[pv]["callers"]:
613
+ if c in mods:
614
+ edge(sid("s_", c), sid("x_", pv), pv)
615
+ # Only when the call sits in the route file itself. Any other dead call stands
616
+ # alone; the call site in its label says where to look.
617
+ route_of_file = {d["file"]: r for r, d in routes.items() if r not in hidden}
618
+ for key, sites, _ in dead:
619
+ for site in sites:
620
+ r = route_of_file.get(site.rsplit(":", 1)[0])
621
+ if r:
622
+ edge(sid("r_", r), sid("d_", key), key)
623
+ L += style_lines(NODES, ELIST)
624
+ return "\n".join(L), len(routes)
625
+
626
+
627
+ def eager_block(eager):
628
+ """Render bkit-graph-eager.py's findings as the import-time side-effect table.
629
+
630
+ Its own section, per file; NOT painted onto the diagrams.
631
+ """
632
+ if not eager:
633
+ return ["_No import-time scan; run with `--eager`._"]
634
+ shown = [r for r in eager["files"] if r["downstream"] >= eager["min_downstream"]]
635
+ hidden = len(eager["files"]) - len(shown)
636
+ sites = sum(len(r["sites"]) for r in eager["files"])
637
+ L = [
638
+ f"{sites} module-scope side effects in {len(eager['files'])} of {eager['scanned']} "
639
+ f"source files. A call here runs on **import**, not on first use, so every file "
640
+ f"downstream pays for it, because under Jest that is a mandatory stub in tests that never "
641
+ f"touch the thing. Sorted by reach.",
642
+ "",
643
+ "<!-- prettier-ignore -->",
644
+ "| File | Evaluates at import | Downstream files | of which tests |",
645
+ "| --- | --- | --- | --- |",
646
+ ]
647
+ L += [f"| `{r['file']}` | {', '.join(f'`{c}`' for c in r['callees'])} | "
648
+ f"{r['downstream']} | {r['downstream_tests']} |" for r in shown]
649
+ if hidden:
650
+ L += ["", f"{hidden} further file{'' if hidden == 1 else 's'} nothing imports, though an "
651
+ "entrypoint is supposed to do work when it loads. In the JSON report only."]
652
+ if eager.get("not_in_graph"):
653
+ L += ["", f"> [!WARNING]", f"> {eager['not_in_graph']} scanned files are absent from "
654
+ "`graph.json`, so only the column-0 filter applied to them and their downstream "
655
+ "counts are 0. Run `pnpm graph:update` and re-run the rollup."]
656
+ return L
657
+
658
+
659
+ def reachability_block(reach):
660
+ """The register's rows for client calls no route serves.
661
+
662
+ Separate from the capability table: one row per dead URL and call site, no owner.
663
+ """
664
+ if reach is None:
665
+ return ["Not scanned; run the rollup with `--reachability`."]
666
+ unreachable = reach.get("unreachable", {})
667
+ stranded = reach.get("strandedHonoRoutes", [])
668
+ n_sites = sum(len(d["sites"]) for d in unreachable.values())
669
+ L = [
670
+ "A request URL is a string inside a template literal, so nothing that reads types can",
671
+ "see that it has no server-side counterpart, because `lint`, `check:type`, `knip` and",
672
+ "`slop:delta` all pass on a path that 404s. This is the one drift class no graph query",
673
+ "finds either: a string is not an edge. Scanned every run by",
674
+ "`scripts/ci/guards/assert-routes-reachable.mjs`; run it alone for the full served-route inventory.",
675
+ "",
676
+ "Two layers have to agree, and a path can fail at either. Next.js decides whether any",
677
+ "handler runs at all, from the directory tree under `apps/web/src/app/api/`. A catch-all",
678
+ "(`[...route]`) forwards its whole subtree into Hono; a static file that calls",
679
+ "`handle(v1ApiRouter)` forwards exactly its own path and nothing below it (`/api/health`,",
680
+ "`/api/config`); a static file with its own handler (`/api/export/file`) never reaches",
681
+ "Hono at all. Hono then routes within what it was handed.",
682
+ "`no Next entry point` means the request never reached Hono, so no mount in `v1.ts` can",
683
+ "fix it; `no handler` means it arrived and Hono had nothing matching.",
684
+ "",
685
+ ]
686
+ if not unreachable:
687
+ L.append("**None.** Every path the clients fetch is served.")
688
+ else:
689
+ L += [
690
+ f"**{len(unreachable)} path{'' if len(unreachable) == 1 else 's'} fetched but not served**"
691
+ f", across {n_sites} call site{'' if n_sites == 1 else 's'}. Each 404s at runtime, though which",
692
+ "may be deliberate. Read this as a list to check, not a list of defects: a stub, a path",
693
+ "served by something outside this repo, or a call behind a flag that never runs all look",
694
+ "identical to the scan.",
695
+ "",
696
+ "<!-- prettier-ignore -->",
697
+ "| Method | Path | Refused by | Call site |",
698
+ "| --- | --- | --- | --- |",
699
+ ]
700
+ for key, d in sorted(unreachable.items()):
701
+ method, path = key.split(" ", 1)
702
+ for site in d["sites"]:
703
+ L.append(f"| `{method}` | `{path}` | `{d['refusedBy']}` | `{site}` |")
704
+ if stranded:
705
+ L += [
706
+ "",
707
+ f"{len(stranded)} Hono route{'' if len(stranded) == 1 else 's'} mounted correctly in "
708
+ "`packages/api/src/v1.ts` and unreachable anyway, because no Next entry point forwards "
709
+ "the path: " + " · ".join(f"`{r}`" for r in stranded)
710
+ + ". Reading either layer on its own says these are fine.",
711
+ ]
712
+ return L
713
+
714
+
715
+ def as_capabilities_doc(out, min_weight, overlay, rows, rules_path, surface, ov_text, eager,
716
+ reach):
717
+ """Write docs/capabilities.md — the tracked register, wholly generated.
718
+
719
+ Source of truth is bkit-graph-drift-rules.json (which capability, which owner,
720
+ which literal marker); every status in the table is derived from live source
721
+ by bkit-graph-drift.py, never typed in. Editing this file by hand loses the edit
722
+ on the next `pnpm graph:rollup`.
723
+ """
724
+ GRAPH_COMMIT = str(raw.get("built_at_commit") or "unknown")
725
+ ROUTES_MMD, n_routes = chain_block(surface, overlay, reach)
726
+ ROUTES_PROSE = (
727
+ f"{n_routes} routes across web and native, each linked to the service domains it reaches. "
728
+ "The static import graph does not cross the HTTP boundary — a page imports `ui` and "
729
+ "`validators`, never `services` — so the link is the endpoint literal at the calling "
730
+ "symbol, followed through `v1.ts` to the router file and its service imports. Attribution "
731
+ "is per symbol, not per file, so a domain named only in a shared helper's comment is not "
732
+ "credited to every page that imports the helper."
733
+ ) if ROUTES_MMD else "No route layer; run with `--surface`."
734
+ order = {"split": 0, "gap": 1, "bypassed": 2, "budgeted": 3, "one": 4, "unchecked": 5}
735
+ rows = sorted(rows, key=lambda r: (order.get(r["status"], 9), r["lane"], r["capability"]))
736
+ counts = collections.Counter(r["status"] for r in rows)
737
+ tally = " · ".join(f"{counts[k]} `{k}`" for k in order if counts.get(k))
738
+
739
+ def cell(r):
740
+ owner = f"`{r['owner']}`" if r["owner"] else "—"
741
+ issue = f"#{r['issue']}" if r["issue"] else ""
742
+ sites = f"{r['bypasses']} of {r['sites']}" if r["sites"] else "—"
743
+ # The declared number, next to the measured one. A `budgeted` status is a
744
+ # claim that these two agree, and a reader should not have to take the word
745
+ # for it — nor open the rules file to find out what was promised.
746
+ budget = "—" if r.get("budget") is None else f"`{r['budget']}`"
747
+ if r.get("budget_state") in ("over", "stale"):
748
+ budget += f" {r['budget_state']}"
749
+ # The surface column names the file set a row's counts were taken over.
750
+ return (f"| {r['lane']} | {r['capability']} | {owner} | `{r['pattern']}` | "
751
+ f"`{r.get('surface', 'product')}` | `{r['status']}` | {sites} | {budget} | "
752
+ f"{issue} |")
753
+
754
+ D = [
755
+ "# Capabilities",
756
+ "",
757
+ "> [!CAUTION]",
758
+ "> **Purpose:** One row per app capability — owner module, the literal marker that finds",
759
+ "> every use of it, whether anything bypasses the owner. The drift register.",
760
+ ">",
761
+ "> **Rules:**",
762
+ ">",
763
+ "> - Generated — do not edit. `pnpm graph:update && pnpm graph:rollup` rewrites this file.",
764
+ f"> - Source of truth: `{rules_path}`. Every status derived from live source, never typed.",
765
+ "> - Add a capability = add a rule there: capability · lane · owner module · one literal marker.",
766
+ "> - Markers literal, never regex, because `new Ratelimit(` as a regex is an unclosed group matching nothing.",
767
+ "> - Match the mechanism, not the name, because `createClient(` misses an owner that aliases its import.",
768
+ "> - Optional `scope` narrows the tree scanned when a marker means different things per package.",
769
+ "> - Optional `surface`: `product` (default) · `tests` (any `e2e/` dir + every `.test.` / `.spec.` file) · `all`. The two surfaces partition the tree.",
770
+ "> - Optional `budgets`: the exact non-owner site count allowed per scope prefix. Measured == declared everywhere ⇒ `budgeted`, which is not a warning.",
771
+ "> - A budget is not a shrug, because `owned-query-shape-guard.test.ts` reds CI when the count moves either way, and a site landing outside every declared prefix reads as over budget.",
772
+ "> - Test code is in `graph.json` on purpose (`.graphifyignore`) and out of every diagram here by rule (`is_test_code` in `bkit-graphify-rollup.py`): test folders, `.test.` / `.spec.` files, test-runner config. `hide_nodes` below is diagram-only too, for whatever else a picture should not draw.",
773
+ "> - Status computed: no owner → `split`; owner absent → `gap`; owner present, others use marker → `bypassed`; else `one`. A `split|bypassed` at budget → `budgeted`.",
774
+ "> - Externals: `scripts/graphify/bkit-graph-external-rules.json` — `sdk` · `hosts` · `env`. SDK and url = `split`.",
775
+ "> - Import-time scan: `scripts/graphify/bkit-graph-eager-rules.json` lists only what is pure. Unclassified = reported.",
776
+ "> - That scan reads source, not the graph, because module-level initialiser calls are the one construct graphify drops.",
777
+ "> - Nothing discovers an SDK itself; find gaps by listing non-workspace deps.",
778
+ "> - Only the Overrides block is hand-maintained. It round-trips; malformed aborts the run.",
779
+ "> - Colour = called capability, shared by its inbound edges. Grey = never called.",
780
+ "> - Drift = dashed border + one amber box for all four. No ranking: each scan proves a shape, never an intent.",
781
+ "> - `budgeted` = solid border + blue box. Still drawn, because a declared bypass is still a bypass, but it is settled, not an open question.",
782
+ "> - Which status is which: `split` fine dash · `bypassed` long dash · `dead` even dash · `gap` dotted · `budgeted` no dash.",
783
+ "> - A fetched URL is a STRING, never an edge, because `assert-routes-reachable.mjs` is the only check that sees it.",
784
+ f"> - Table rescanned every run, never stale. Diagrams from `graph.json` @ `{GRAPH_COMMIT[:9]}`; when that differs from HEAD ⇒ run `pnpm graph:update` first.",
785
+ "> - Detail-level module graph → `pnpm graph`. This doc is the altitude above that: capabilities, not files.",
786
+ "",
787
+ "## Status Vocabulary",
788
+ "",
789
+ "The first four are warnings, not verdicts, and they share one amber in the diagrams. Any",
790
+ "of them can turn out to be deliberate, because the scans prove a shape, never an intent.",
791
+ "",
792
+ "`budgeted` is what one of those four becomes once somebody has decided. The rule declares",
793
+ "the exact number of non-owner sites allowed per scope prefix, its `note` says why that",
794
+ "number is not zero, and `tooling/eslint/tests/owned-query-shape-guard.test.ts` reds CI the",
795
+ "moment the count moves in either direction — too many (a copy appeared) or too few (the",
796
+ "budget is stale). That guard is why the status can be quieter without being a place to",
797
+ "hide work, and it is the half the register itself cannot do: `graphify` is a per-developer",
798
+ "install, absent in CI, so nothing here can turn a build red.",
799
+ "",
800
+ "It still gets a box in the diagrams, drawn solid and blue rather than dashed and amber. A",
801
+ "budgeted bypass is still a bypass; the different drawing stops the picture asking the",
802
+ "same question of it every sweep. Drawn identically, an unbounded marker (18 of 19) and a",
803
+ "marker that is exactly at its declared count — whose note says the copies are probes and",
804
+ "the budget is not meant to reach zero — would make each pass rediscover the settled rows",
805
+ "and re-read the notes to dismiss them.",
806
+ "",
807
+ "<!-- prettier-ignore -->",
808
+ "| Status | Meaning | Action |",
809
+ "| --- | --- | --- |",
810
+ "| `split` | Two or more competing implementations, no single owner | Centralise; file an issue. Or budget it, with the reason in `note` |",
811
+ "| `bypassed` | Owner exists, some callers skip it | Repoint the bypasses. Or budget them, with the reason in `note` |",
812
+ "| `dead` | A client fetches a path nothing serves. A WARNING, though some are deliberate | Check the call site, then delete the call or serve the path |",
813
+ "| `gap` | Designed, not built. No owner yet | Name the owner BEFORE the first caller |",
814
+ "| `budgeted` | A `split` or `bypassed` whose site count is declared, guarded and currently met | None — the CI guard owns it. Lower the budget when a site goes |",
815
+ "| `one` | One implementation, every caller routes through it | None — keep it that way |",
816
+ "",
817
+ "## Register",
818
+ "",
819
+ f"{len(rows)} capabilities: {tally}.",
820
+ "",
821
+ "<!-- prettier-ignore -->",
822
+ "| Lane | Capability | Owner | Marker | Surface | Status | Bypasses | Budget | Issue |",
823
+ "| --- | --- | --- | --- | --- | --- | --- | --- | --- |",
824
+ ]
825
+ D += [cell(r) for r in rows]
826
+ D += [
827
+ "",
828
+ "## Unreachable API calls",
829
+ "",
830
+ ] + reachability_block(reach) + [
831
+ "",
832
+ "## Import-time side effects",
833
+ "",
834
+ ] + eager_block(eager) + [
835
+ "",
836
+ "## Overrides",
837
+ "",
838
+ "The one hand-maintained region of this file. Everything else is rewritten on each run;",
839
+ "this block is read back first and re-emitted verbatim. Rename a node, hide a node or an",
840
+ "edge, pin a note, or force nodes into a named group. A malformed block aborts the run",
841
+ "rather than being silently dropped. Every `hide_nodes` entry needs a one-line reason in",
842
+ "`hide_nodes_why`; `tooling/eslint/tests/hide-nodes-registry.test.ts` fails CI otherwise.",
843
+ "",
844
+ OV_START,
845
+ "",
846
+ "```json",
847
+ ov_text,
848
+ "```",
849
+ "",
850
+ OV_END,
851
+ "",
852
+ "## User-facing routes → backend capabilities",
853
+ "",
854
+ ROUTES_PROSE,
855
+ "",
856
+ VIEW_ONLINE,
857
+ "",
858
+ "```mermaid",
859
+ ROUTES_MMD,
860
+ "```",
861
+ "",
862
+ "## Architecture — packages",
863
+ "",
864
+ "Grouped by the folder tree, not by a clustering algorithm. Edge labels are the number of",
865
+ "underlying symbol edges. Drift status is painted onto the owning module.",
866
+ "",
867
+ VIEW_ONLINE,
868
+ "",
869
+ "```mermaid",
870
+ as_mermaid(by_package, None, "package", min_weight, overlay).rstrip(),
871
+ "```",
872
+ "",
873
+ "## Architecture — modules",
874
+ "",
875
+ f"The same graph one level down: `apps/web` is a box, its subfolders are the nodes inside it.",
876
+ f"Cross-group edges lighter than {min_weight} are dropped — see `MMD_MIN_WEIGHT` in",
877
+ "`scripts/graphify/bkit-graphify.sh`.",
878
+ "",
879
+ VIEW_ONLINE,
880
+ "",
881
+ "```mermaid",
882
+ as_mermaid(by_module, None, "module", min_weight, overlay).rstrip(),
883
+ "```",
884
+ "",
885
+ ]
886
+ with open(out, "w") as fh:
887
+ fh.write("\n".join(D))
888
+ print(f"[graph] {out}: {len(rows)} capabilities, {tally}")
889
+
890
+
891
+ OVERRIDES, OV_TEXT = read_overrides(args.capabilities_doc)
892
+ OVERLAY, ROWS = {}, []
893
+ if args.overlay and os.path.exists(args.overlay):
894
+ _o = json.load(open(args.overlay))
895
+ OVERLAY = {k: tuple(v) for k, v in _o["overlay"].items()}
896
+ ROWS = _o.get("rows", [])
897
+
898
+ SURFACE = {}
899
+ if args.surface and os.path.exists(args.surface):
900
+ SURFACE = json.load(open(args.surface))
901
+
902
+ EAGER = {}
903
+ if args.eager and os.path.exists(args.eager):
904
+ EAGER = json.load(open(args.eager))
905
+
906
+ REACH = None
907
+ if args.reachability and os.path.exists(args.reachability):
908
+ REACH = json.load(open(args.reachability))
909
+
910
+ if args.capabilities_doc:
911
+ as_capabilities_doc(args.capabilities_doc, max(args.min_weight, 1), OVERLAY, ROWS,
912
+ _o.get("generated_from", "scripts/graphify/bkit-graph-drift-rules.json"),
913
+ SURFACE, OV_TEXT, EAGER, REACH)
914
+
915
+ if args.packages_mermaid:
916
+ as_mermaid(by_package, args.packages_mermaid, "package", max(args.min_weight, 1), OVERLAY)
917
+ if args.modules_mermaid:
918
+ as_mermaid(by_module, args.modules_mermaid, "module", max(args.min_weight, 1), OVERLAY)
919
+ if args.packages_graphml:
920
+ rollup(by_package, args.packages_graphml, "package")
921
+ if args.modules_graphml:
922
+ rollup(by_module, args.modules_graphml, "module")
923
+ if args.build_dir:
924
+ n, e = as_graphify_json(by_package, f"{args.build_dir}/packages")
925
+ print(f"[graph] package view: {n} nodes, {e} edges")
926
+ n, e = as_graphify_json(by_module, f"{args.build_dir}/modules")
927
+ print(f"[graph] module view: {n} nodes, {e} edges")