@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,1037 @@
1
+ // commands/install/upgrade.ts — `bkit upgrade` orchestrator + diff engine.
2
+ //
3
+ // Design contract:
4
+ //
5
+ // `bkit upgrade` diffs old vs new template content against consumer drift using
6
+ // the `canonicalHashes` field from `.bkit/version`. Files whose on-disk
7
+ // content matches the canonical hash recorded at last install are safe to upgrade
8
+ // (no consumer drift). Files that differ have consumer drift — do NOT silently
9
+ // overwrite.
10
+ //
11
+ // Non-interactive mode (--non-interactive):
12
+ // - Auto-apply non-conflicting changes.
13
+ // - Emit conflict list to stderr (one line per conflicting file).
14
+ // - Exit non-zero when any conflict is detected.
15
+ //
16
+ // Conflict = a bkit-managed file where:
17
+ // - The template content has changed (new bkit version ships an update), AND
18
+ // - The consumer has modified the file since last install (on-disk hash != canonical hash).
19
+ //
20
+ // Dependency: `canonicalHashes` + `isConsumerModified` from install/version-file.ts.
21
+
22
+ import * as fs from "node:fs";
23
+ import * as path from "node:path";
24
+ import {
25
+ readBkitVersion,
26
+ writeBkitVersion,
27
+ sha256,
28
+ isConsumerModified,
29
+ mergeCanonicalHashes,
30
+ type BkitVersion,
31
+ } from "../../install/version-file.js";
32
+ import { writeTier2, writeTier2JsonContained, type WriteSet } from "../../install/write.js";
33
+ import { detectMarkerStyle } from "../../install/managed-block.js";
34
+ import { applyTokens, type TokenMap, resolveTokens } from "../../install/placeholders.js";
35
+ import type { ManifestEntry } from "../../install/manifest.js";
36
+ import { readTemplate } from "../../render/parts.js";
37
+ import {
38
+ TEMPLATE_COPIES_DIR,
39
+ getCoreRoot,
40
+ getSharedRoot,
41
+ getBkitDocsRoot,
42
+ getPkgRoot,
43
+ } from "../../shared/package-roots.js";
44
+ import type { ModuleFlag, UpgradeFlags } from "../../cli.js";
45
+ import {
46
+ getInstallingVersion,
47
+ requireOpencodeProvider,
48
+ detectOpencodeProviders,
49
+ } from "./install.js";
50
+ import { setLogPrefix } from "../../shared/log-prefix.js";
51
+ import {
52
+ getInstallManifest,
53
+ getModuleManifest,
54
+ type ModuleName,
55
+ type IssueTracker,
56
+ DEFAULT_ISSUE_TRACKER,
57
+ parseIssueTracker,
58
+ } from "../../install/manifest.js";
59
+ import { OPTIN_MODULES } from "../../install/manifest.js";
60
+ import { detectInstalledModules } from "./check.js";
61
+ import { remapTemplateDest } from "../../install/template-copies.js";
62
+ import {
63
+ CLAUDE_CLOUD_RELPATH,
64
+ CURSOR_CLOUD_RELPATH,
65
+ writeClaudeCloudDoc,
66
+ writeCursorCloudDoc,
67
+ writeNetworkAllowlistArtifact,
68
+ writeCursorCliPermissionsArtifact,
69
+ } from "../../install/cloud-env.js";
70
+ import { syncTemplateCopies, formatTemplateChanges } from "../../install/template-copies.js";
71
+ import { formatPayloadLinkChanges, syncPayloadLinks } from "../../install/payload-links.js";
72
+ import { renderOpencodeJson, reconcileOpencodeJson } from "../../install/modules/opencode.js";
73
+ import { type ModuleContext, renderManagedOutputs } from "../../install/modules/index.js";
74
+ import { reconcileMcpJson, enrichClaudeSettingsAllows } from "../../install/modules/claude.js";
75
+ import {
76
+ type EffortMap,
77
+ parseModelLookup,
78
+ applyModelOverrides,
79
+ buildOpencodeModelLookup,
80
+ parseEffortMap,
81
+ } from "../../render/models.js";
82
+
83
+ /** Zero-value token map — markered-text templates managed on upgrade are token-free. */
84
+ const EMPTY_TOKENS: TokenMap = {
85
+ DEFAULT_BRANCH: "",
86
+ PROJECT_NAME: "",
87
+ REPO_SLUG: "",
88
+ };
89
+
90
+ // ---------------------------------------------------------------------------
91
+ // planSelfBump — pure decision for `bkit upgrade --to=<v>` / `--latest`
92
+ //
93
+ // Decides what the atomic self-bump should do WITHOUT any IO: bump the installed
94
+ // @cbartens/bkit package, then re-render at the new version. The imperative half
95
+ // (pnpm add + re-exec of the freshly-installed binary) lives in commands/install/install.ts
96
+ // (runSelfBump); the version logic is split out here so it is unit-testable with
97
+ // `resolveLatest` injected. The package bump and the re-render are ONE command.
98
+ // ---------------------------------------------------------------------------
99
+
100
+ /** Accepts X.Y.Z with an optional prerelease tag (e.g. 4.1.5, 4.2.0-rc.1). */
101
+ const SELF_BUMP_SEMVER_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
102
+
103
+ export type SelfBumpPlan =
104
+ | { kind: "invalid"; message: string }
105
+ /** Already at the target → caller falls through to a normal in-place re-render. */
106
+ | { kind: "noop"; target: string }
107
+ /** Install `target`, then re-exec the new binary to re-render + re-pin. */
108
+ | { kind: "bump"; target: string };
109
+
110
+ /**
111
+ * Resolve the self-bump target and decide the action. `resolveLatest` is only
112
+ * invoked for `--latest` (it shells out to the registry in production); injected
113
+ * so tests stay offline. A leading `v` is tolerated on either source.
114
+ */
115
+ export function planSelfBump(
116
+ installed: string,
117
+ flags: { toVersion: string | null; latest: boolean },
118
+ resolveLatest: () => string,
119
+ ): SelfBumpPlan {
120
+ let target: string;
121
+ if (flags.toVersion !== null) {
122
+ target = flags.toVersion.trim().replace(/^v/, "");
123
+ if (!SELF_BUMP_SEMVER_RE.test(target)) {
124
+ return {
125
+ kind: "invalid",
126
+ message: `--to=<version> must be a semver (e.g. 4.1.5). Got: ${JSON.stringify(flags.toVersion)}`,
127
+ };
128
+ }
129
+ } else {
130
+ target = resolveLatest().trim().replace(/^v/, "");
131
+ if (!SELF_BUMP_SEMVER_RE.test(target)) {
132
+ return {
133
+ kind: "invalid",
134
+ message: `could not resolve a valid latest @cbartens/bkit version from the registry (got ${JSON.stringify(
135
+ target,
136
+ )}). Pin explicitly with --to=<version>.`,
137
+ };
138
+ }
139
+ }
140
+ if (target === installed.trim().replace(/^v/, "")) return { kind: "noop", target };
141
+ return { kind: "bump", target };
142
+ }
143
+
144
+ export const LOG_PREFIX = "[bkit-upgrade]";
145
+
146
+ // ---------------------------------------------------------------------------
147
+ // Types
148
+ // ---------------------------------------------------------------------------
149
+
150
+ export interface UpgradeConflict {
151
+ /** Consumer-relative path of the conflicting file. */
152
+ relPath: string;
153
+ /** The new template content bkit would write. */
154
+ templateContent: string;
155
+ /** The current on-disk content (consumer-modified). */
156
+ diskContent: string;
157
+ }
158
+
159
+ export interface UpgradeResult {
160
+ /** Files upgraded (written/updated). */
161
+ updated: string[];
162
+ /** Files with conflicts (consumer drift detected). */
163
+ conflicts: UpgradeConflict[];
164
+ /** Files skipped (template unchanged — no upgrade needed). */
165
+ skipped: string[];
166
+ /**
167
+ * Subset of `skipped` whose on-disk content is bkit's canonical baseline: block/scope-merge
168
+ * skips, and whole-file skips where disk == template. A whole-file skip over consumer
169
+ * drift is excluded, so the drift record survives.
170
+ */
171
+ skippedSeedable: string[];
172
+ }
173
+
174
+ // ---------------------------------------------------------------------------
175
+ // DiffEngine — compare template content vs consumer disk state
176
+ // ---------------------------------------------------------------------------
177
+
178
+ /**
179
+ * Determine the upgrade action for a single file.
180
+ *
181
+ * Returns:
182
+ * - `{ action: "update", templateContent }` when the template has changed
183
+ * AND the consumer has no drift (on-disk hash matches canonical hash).
184
+ * - `{ action: "conflict", templateContent, diskContent }` when the template
185
+ * has changed AND the consumer has drift.
186
+ * - `{ action: "skip", reason: "in-sync" }` when disk already equals the template.
187
+ * - `{ action: "skip", reason: "template-unchanged" }` when the template has NOT changed
188
+ * since last install but disk differs from it (consumer drift, left alone).
189
+ * - `{ action: "new" }` when the file doesn't exist on disk (first-time write).
190
+ */
191
+ export type DiffAction =
192
+ | { action: "update"; templateContent: string }
193
+ | { action: "conflict"; templateContent: string; diskContent: string }
194
+ | { action: "skip"; reason: "in-sync" | "template-unchanged" }
195
+ | { action: "new"; templateContent: string };
196
+
197
+ export function diffFile(
198
+ relPath: string,
199
+ absolutePath: string,
200
+ templateContent: string,
201
+ canonicalHashes: Record<string, string>,
202
+ ): DiffAction {
203
+ // File absent → new write (no consumer drift possible)
204
+ if (!fs.existsSync(absolutePath)) {
205
+ return { action: "new", templateContent };
206
+ }
207
+
208
+ const diskContent = fs.readFileSync(absolutePath, "utf-8");
209
+ const templateHash = sha256(templateContent);
210
+ const diskHash = sha256(diskContent);
211
+
212
+ // Disk already matches template → skip (idempotent; nothing to apply).
213
+ // Checked first so a missing canonical hash never produces a spurious conflict
214
+ // when the file content is already identical to the template.
215
+ if (diskHash === templateHash) {
216
+ return { action: "skip", reason: "in-sync" };
217
+ }
218
+
219
+ // Template unchanged since last install → skip.
220
+ const canonicalHash = canonicalHashes[relPath];
221
+ if (canonicalHash && canonicalHash === templateHash) {
222
+ return { action: "skip", reason: "template-unchanged" };
223
+ }
224
+
225
+ // Template has changed (or canonical hash unknown). Check consumer drift —
226
+ // when canonical hash is missing, isConsumerModified treats the file as drifted
227
+ // to block a silent overwrite of a file bkit has no record of writing.
228
+ if (isConsumerModified(relPath, absolutePath, canonicalHashes)) {
229
+ return { action: "conflict", templateContent, diskContent };
230
+ }
231
+
232
+ return { action: "update", templateContent };
233
+ }
234
+
235
+ // ---------------------------------------------------------------------------
236
+ // runUpgrade — orchestrator
237
+ // ---------------------------------------------------------------------------
238
+
239
+ /**
240
+ * A bkit-managed template the upgrade engine may write to the consumer repo.
241
+ * - `relPath`: consumer-relative dest path (already dotfile-remapped).
242
+ * - `templatePath`: absolute path to the new template file in the bkit package.
243
+ * - `format`: manifest format that drives the write strategy. When omitted the
244
+ * file is treated as whole-file byte-equal (drift-detected, conflict-aware).
245
+ */
246
+ export interface UpgradeCandidate {
247
+ relPath: string;
248
+ templatePath: string;
249
+ format?: ManifestEntry["format"];
250
+ /**
251
+ * Pre-rendered template content that overrides reading `templatePath`. Used for
252
+ * files install writes via a transform the upgrade walk can't reproduce from the raw
253
+ * template — e.g. `opencode.json`, rendered with the consumer's tracker and
254
+ * provider so install and upgrade emit byte-identical output.
255
+ */
256
+ contentOverride?: string;
257
+ }
258
+
259
+ export interface UpgradeOptions {
260
+ /** When true: auto-apply non-conflicting; emit conflicts to stderr; exit non-zero on conflict. */
261
+ nonInteractive: boolean;
262
+ /** When true: show what would change without writing. */
263
+ dryRun: boolean;
264
+ cwd?: string;
265
+ /** Tokens applied to markered-text templates (defaults to zero-value — those templates are token-free). */
266
+ tokens?: TokenMap;
267
+ }
268
+
269
+ /**
270
+ * Run the upgrade engine against a set of (relPath, absoluteTemplatePath) pairs.
271
+ *
272
+ * Each entry in `candidates` describes a file bkit manages:
273
+ * - `relPath`: consumer-relative path (e.g. ".claude/agents/bkit-foo.md")
274
+ * - `templatePath`: absolute path to the new template file in the bkit package
275
+ *
276
+ * The function reads `canonicalHashes` from `.bkit/version`, diffs each
277
+ * candidate, and applies the upgrade strategy based on `options`.
278
+ *
279
+ * Returns an `UpgradeResult` describing what happened.
280
+ */
281
+ export function runUpgrade(candidates: UpgradeCandidate[], options: UpgradeOptions): UpgradeResult {
282
+ const cwd = options.cwd ?? process.cwd();
283
+ const versionFile = path.join(cwd, ".bkit", "version");
284
+ const bkitVersion = readBkitVersion(versionFile);
285
+ const canonicalHashes = bkitVersion?.canonicalHashes ?? {};
286
+ const tokens = options.tokens ?? EMPTY_TOKENS;
287
+
288
+ const result: UpgradeResult = { updated: [], conflicts: [], skipped: [], skippedSeedable: [] };
289
+ // Local WriteSet drives updated/skipped classification for the block/scope-merge
290
+ // formats; the tier writers push exactly one entry per file they actually change.
291
+ const ws: WriteSet = { writes: [] };
292
+
293
+ for (const { relPath, templatePath, format, contentOverride } of candidates) {
294
+ if (contentOverride === undefined && !fs.existsSync(templatePath)) {
295
+ console.error(`${LOG_PREFIX} Template not found: ${templatePath} — skipping ${relPath}`);
296
+ continue;
297
+ }
298
+
299
+ const absolutePath = path.join(cwd, relPath);
300
+ // `contentOverride` (e.g. the rendered opencode.json) wins over the raw
301
+ // template so upgrade emits the same bytes install would.
302
+ const templateContent = contentOverride ?? readTemplate(templatePath);
303
+
304
+ // Resolve the write strategy the SAME way `bkit install` does:
305
+ //
306
+ // - manifest `format` is authoritative when present:
307
+ // markered-text → block-merge (writeTier2, preserves content outside markers)
308
+ // json → deep-merge (writeTier2JsonContained, preserves consumer keys)
309
+ // byte-equal-text → whole-file/diff — even when the template carries markers
310
+ // (install writes these verbatim via writeTier1).
311
+ // - NO manifest entry: the install core payload pass block-merges markered
312
+ // MARKDOWN it manages as a directory (`docs/*.md`, `.agents/*.md`) where the
313
+ // consumer's prose lives after `bkit:end`; everything else (e.g. canonical
314
+ // `.vale/styles/**.yml`) is whole-file. So: markered `.md` → block-merge.
315
+ //
316
+ // Block/scope-merge are ALWAYS safe (never a whole-file overwrite), so they have no
317
+ // conflict path; whole-file keeps the drift-detect/conflict guard.
318
+ const isMarkdown = relPath.endsWith(".md");
319
+ const markerStyle = detectMarkerStyle(templateContent);
320
+ const blockMerge =
321
+ format === "markered-text" || (format === undefined && isMarkdown && markerStyle !== null);
322
+ if (blockMerge || format === "json") {
323
+ const before = ws.writes.length;
324
+ if (format === "json") {
325
+ // `contentOverride` (e.g. the rendered opencode.json with `@@OPENCODE_*@@`
326
+ // sentinels resolved) wins over the raw template.
327
+ if (contentOverride !== undefined && options.dryRun) {
328
+ // Dry-run must NOT touch disk — mirror install's opencode.json dry-run path (no
329
+ // `.bkit-staging/` temp file). Compare the consumer dest against the rendered
330
+ // override directly.
331
+ if (
332
+ !fs.existsSync(absolutePath) ||
333
+ fs.readFileSync(absolutePath, "utf-8") !== contentOverride
334
+ ) {
335
+ ws.writes.push({ path: absolutePath, action: "write" });
336
+ }
337
+ } else {
338
+ // writeTier2JsonContained reads from a path, so stage the override to a temp file.
339
+ let jsonSrc = templatePath;
340
+ let jsonTmp: string | null = null;
341
+ if (contentOverride !== undefined) {
342
+ jsonTmp = path.join(cwd, ".bkit-staging", "upgrade-json-rendered.json");
343
+ fs.mkdirSync(path.dirname(jsonTmp), { recursive: true });
344
+ fs.writeFileSync(jsonTmp, contentOverride, "utf-8");
345
+ jsonSrc = jsonTmp;
346
+ }
347
+ try {
348
+ writeTier2JsonContained(jsonSrc, absolutePath, options.dryRun, ws);
349
+ } finally {
350
+ if (jsonTmp) {
351
+ try {
352
+ fs.rmSync(jsonTmp, { force: true });
353
+ const stagingDir = path.dirname(jsonTmp);
354
+ if (fs.existsSync(stagingDir) && fs.readdirSync(stagingDir).length === 0) {
355
+ fs.rmdirSync(stagingDir);
356
+ }
357
+ } catch {
358
+ // non-fatal staging cleanup
359
+ }
360
+ }
361
+ }
362
+ }
363
+ } else {
364
+ writeTier2(
365
+ templatePath,
366
+ absolutePath,
367
+ tokens,
368
+ markerStyle ?? "html-comment",
369
+ options.dryRun,
370
+ ws,
371
+ );
372
+ }
373
+ if (ws.writes.length > before) {
374
+ result.updated.push(relPath);
375
+ console.log(
376
+ `${LOG_PREFIX}${options.dryRun ? " [dry-run]" : ""} upgrade (merge): ${relPath}`,
377
+ );
378
+ } else {
379
+ result.skipped.push(relPath);
380
+ result.skippedSeedable.push(relPath);
381
+ }
382
+ continue;
383
+ }
384
+
385
+ // Whole-file formats (byte-equal-text, or unmanaged non-markered templates).
386
+ // Token-substitute FIRST (matching install's writeTier1 tokens) so
387
+ // drift-detect compares like-for-like and a freshly-seeded file gets real values,
388
+ // not a literal `{{DEFAULT_BRANCH}}`. Token-free templates are unchanged.
389
+ const effectiveTemplate = applyTokens(templateContent, tokens);
390
+ const diffAction = diffFile(relPath, absolutePath, effectiveTemplate, canonicalHashes);
391
+
392
+ switch (diffAction.action) {
393
+ case "skip":
394
+ result.skipped.push(relPath);
395
+ if (diffAction.reason === "in-sync") result.skippedSeedable.push(relPath);
396
+ break;
397
+
398
+ case "new":
399
+ case "update": {
400
+ if (!options.dryRun) {
401
+ fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
402
+ fs.writeFileSync(absolutePath, diffAction.templateContent, "utf-8");
403
+ }
404
+ result.updated.push(relPath);
405
+ console.log(`${LOG_PREFIX}${options.dryRun ? " [dry-run]" : ""} upgrade: ${relPath}`);
406
+ break;
407
+ }
408
+
409
+ case "conflict": {
410
+ result.conflicts.push({
411
+ relPath,
412
+ templateContent: diffAction.templateContent,
413
+ diskContent: diffAction.diskContent,
414
+ });
415
+ console.error(
416
+ `${LOG_PREFIX} conflict: ${relPath} — consumer drift detected, NOT overwriting`,
417
+ );
418
+ break;
419
+ }
420
+ }
421
+ }
422
+
423
+ // In non-interactive mode: emit conflict summary to stderr
424
+ if (options.nonInteractive && result.conflicts.length > 0) {
425
+ console.error(
426
+ `${LOG_PREFIX} ${result.conflicts.length} conflict(s) detected. Manually merge or revert consumer changes:`,
427
+ );
428
+ for (const c of result.conflicts) {
429
+ console.error(` - ${c.relPath}`);
430
+ }
431
+ }
432
+
433
+ return result;
434
+ }
435
+
436
+ // ---------------------------------------------------------------------------
437
+ // updateCanonicalHashes — record hashes of written files back to .bkit/version
438
+ // ---------------------------------------------------------------------------
439
+
440
+ /**
441
+ * After a successful upgrade, update `.bkit/version`:
442
+ * - `canonicalHashes`: refresh from the ON-DISK content of every file bkit wrote
443
+ * or confirmed (`result.updated` ∪ `result.skippedSeedable`):
444
+ * - updated → always (disk is what bkit just wrote).
445
+ * - block/scope-merge skips → always. Disk is NOT the template (it carries
446
+ * consumer content too), so the file is hashed as it now sits on disk.
447
+ * - whole-file skips → only when disk == template. A template-unchanged skip
448
+ * over consumer drift keeps its prior hash, so the next template change is
449
+ * a conflict, not a silent overwrite.
450
+ * - conflicts → never, for the same reason.
451
+ * - entries whose path is no longer on disk are pruned (a retired or renamed
452
+ * managed file leaves one behind), in both directions of the merge.
453
+ * - `pinnedVersion`: bump to the version just upgraded TO (`options.pinnedVersion`).
454
+ * Written here exactly as `install`/`check` do, so the next `bkit check` has no
455
+ * pin write.
456
+ *
457
+ * Call this AFTER `runUpgrade` completes (hashes stay in sync with the files bkit
458
+ * actually wrote).
459
+ */
460
+ export function updateCanonicalHashesAfterUpgrade(
461
+ result: UpgradeResult,
462
+ options: {
463
+ dryRun: boolean;
464
+ cwd?: string;
465
+ pinnedVersion?: string;
466
+ /** What enrich recorded this run. `null`/absent = not determined; keep the prior record. */
467
+ claudeAllowDerived?: readonly string[] | null;
468
+ },
469
+ ): void {
470
+ if (options.dryRun) return;
471
+
472
+ const cwd = options.cwd ?? process.cwd();
473
+ const versionFile = path.join(cwd, ".bkit", "version");
474
+ const bkitVersion = readBkitVersion(versionFile);
475
+ if (!bkitVersion) return;
476
+
477
+ const seedablePaths = new Set([...result.updated, ...result.skippedSeedable]);
478
+
479
+ const fresh: Record<string, string> = {};
480
+ for (const relPath of seedablePaths) {
481
+ // Exclude .agents/ internal files (docs.md, friction.md, rules.md, skills.md,
482
+ // .env.example etc.) from canonicalHashes — they are not consumer-facing files
483
+ // whose hashes bkit uses for drift detection. Mirrors the same filter applied
484
+ // in the install path (install/modules/index.ts postDispatch). Template copies carry no
485
+ // hash there either.
486
+ if (relPath.startsWith(".agents" + path.sep)) continue;
487
+ if (relPath.startsWith(TEMPLATE_COPIES_DIR + path.sep)) continue;
488
+ const absolutePath = path.join(cwd, relPath);
489
+ if (!fs.existsSync(absolutePath)) continue;
490
+ fresh[relPath] = sha256(fs.readFileSync(absolutePath, "utf-8"));
491
+ }
492
+
493
+ // Fresh hashes overwrite; entries for paths gone from disk are pruned (a retired
494
+ // or renamed managed file leaves one behind — mergeCanonicalHashes).
495
+ const { canonicalHashes: newCanonicalHashes, pruned } = mergeCanonicalHashes(
496
+ cwd,
497
+ bkitVersion.canonicalHashes,
498
+ fresh,
499
+ );
500
+
501
+ const pinnedVersion = options.pinnedVersion ?? bkitVersion.pinnedVersion;
502
+
503
+ const webFetchUnchanged =
504
+ options.claudeAllowDerived == null ||
505
+ JSON.stringify([...options.claudeAllowDerived]) ===
506
+ JSON.stringify(bkitVersion.claudeAllowDerived);
507
+
508
+ // Nothing to persist: no files processed AND nothing pruned AND the pin is
509
+ // current AND the record is unchanged.
510
+ if (
511
+ seedablePaths.size === 0 &&
512
+ pruned === 0 &&
513
+ pinnedVersion === bkitVersion.pinnedVersion &&
514
+ webFetchUnchanged
515
+ ) {
516
+ return;
517
+ }
518
+
519
+ const updated: BkitVersion = {
520
+ ...bkitVersion,
521
+ pinnedVersion,
522
+ canonicalHashes: newCanonicalHashes,
523
+ ...(options.claudeAllowDerived == null
524
+ ? {}
525
+ : { claudeAllowDerived: [...options.claudeAllowDerived] }),
526
+ };
527
+ writeBkitVersion(versionFile, updated);
528
+ }
529
+
530
+ /**
531
+ * Detect which host modules a consumer has installed, by the presence of each host's
532
+ * source-rendered agents directory. Used by `bkit upgrade` to re-render only the hosts
533
+ * the consumer installed — never force-creating an opencode/cursor tree.
534
+ */
535
+ export function detectInstalledHostModules(cwd: string): Set<ModuleFlag> {
536
+ const mods = new Set<ModuleFlag>();
537
+ if (fs.existsSync(path.join(cwd, ".claude", "agents"))) mods.add("claude");
538
+ if (fs.existsSync(path.join(cwd, ".cursor", "agents"))) mods.add("cursor");
539
+ if (fs.existsSync(path.join(cwd, ".opencode", "agents"))) mods.add("opencode");
540
+ if (fs.existsSync(path.join(cwd, ".codex", "agents"))) mods.add("codex");
541
+ return mods;
542
+ }
543
+
544
+ /**
545
+ * Resolve the newest published @cbartens/bkit version from the registry for
546
+ * `bkit upgrade --latest`. Shells out to `pnpm view` (honours the consumer's
547
+ * registry auth). Hard-exits with guidance on failure — the caller has nothing
548
+ * to fall back to.
549
+ */
550
+ async function resolveLatestPublishedVersion(cwd: string): Promise<string> {
551
+ const { spawnSync } = await import("node:child_process");
552
+ const r = spawnSync("pnpm", ["view", "@cbartens/bkit", "version"], { cwd, encoding: "utf-8" });
553
+ if (r.status !== 0 || !r.stdout || !r.stdout.trim()) {
554
+ console.error(
555
+ `${LOG_PREFIX} could not resolve the latest @cbartens/bkit version from the registry ` +
556
+ `(pnpm view exit ${r.status ?? "null"}). Check your network / registry access, ` +
557
+ `or pin a version with --to=<version>.`,
558
+ );
559
+ process.exit(1);
560
+ }
561
+ return r.stdout.trim();
562
+ }
563
+
564
+ /**
565
+ * Atomic self-bump for `bkit upgrade --to=<v>` / `--latest`: install the target
566
+ * @cbartens/bkit, then RE-EXEC the freshly-installed binary so the NEW code does
567
+ * the render + re-pin (this process is still the OLD code). The package bump and
568
+ * the re-render are one command.
569
+ *
570
+ * Returns true when it handled the run (bumped + re-exec'd, or dry-run reported a
571
+ * bump) → the caller should return. Returns false when already at target → the
572
+ * caller falls through to a normal in-place re-render.
573
+ */
574
+ export async function runSelfBump(flags: UpgradeFlags, cwd: string): Promise<boolean> {
575
+ const installed = getInstallingVersion();
576
+ // --latest needs async registry resolution, but planSelfBump's injected resolver
577
+ // is sync; resolve the latest first (only when asked), then feed it a constant.
578
+ const latestVersion = flags.latest ? await resolveLatestPublishedVersion(cwd) : "";
579
+ const resolvedPlan = planSelfBump(
580
+ installed,
581
+ { toVersion: flags.toVersion, latest: flags.latest },
582
+ () => latestVersion,
583
+ );
584
+
585
+ if (resolvedPlan.kind === "invalid") {
586
+ console.error(`${LOG_PREFIX} ${resolvedPlan.message}`);
587
+ process.exit(1);
588
+ }
589
+ if (resolvedPlan.kind === "noop") {
590
+ console.log(
591
+ `${LOG_PREFIX} already at @cbartens/bkit@${resolvedPlan.target} — re-rendering in place at the installed version.`,
592
+ );
593
+ return false; // fall through to the normal upgrade path
594
+ }
595
+
596
+ // resolvedPlan.kind === "bump"
597
+ //
598
+ // In a pnpm workspace ROOT, `pnpm add` refuses without -w/--workspace-root
599
+ // (ERR_PNPM_ADDING_TO_ROOT) when bkit is a root devDependency — the standard
600
+ // layout for a workspace consumer. Detect the workspace (pnpm-workspace.yaml at
601
+ // cwd) and pass -w so the documented upgrade path works there. A single-package
602
+ // repo has no pnpm-workspace.yaml and must NOT get -w (pnpm errors that -w may
603
+ // only be used inside a workspace).
604
+ const inWorkspaceRoot = fs.existsSync(path.join(cwd, "pnpm-workspace.yaml"));
605
+ const addArgs = [
606
+ "add",
607
+ "-D",
608
+ ...(inWorkspaceRoot ? ["-w"] : []),
609
+ `@cbartens/bkit@${resolvedPlan.target}`,
610
+ ];
611
+ const addCmd = `pnpm ${addArgs.join(" ")}`;
612
+ if (flags.dryRun) {
613
+ console.log(
614
+ `${LOG_PREFIX} [dry-run] would bump @cbartens/bkit ${installed} -> ${resolvedPlan.target} ` +
615
+ `(${addCmd}), then re-render + re-pin via the ` +
616
+ `freshly-installed binary. No changes made.`,
617
+ );
618
+ return true;
619
+ }
620
+
621
+ const { spawnSync } = await import("node:child_process");
622
+ console.log(`${LOG_PREFIX} bumping @cbartens/bkit ${installed} -> ${resolvedPlan.target} ...`);
623
+ const add = spawnSync("pnpm", addArgs, {
624
+ cwd,
625
+ stdio: "inherit",
626
+ });
627
+ if (add.status !== 0) {
628
+ console.error(
629
+ `${LOG_PREFIX} \`${addCmd}\` failed (exit ${add.status ?? "null"}). ` +
630
+ `Check your network / registry access. Nothing re-rendered.`,
631
+ );
632
+ process.exit(1);
633
+ }
634
+
635
+ // Re-exec the just-installed (NEW) bkit so IT renders + re-pins, not this old process.
636
+ console.log(`${LOG_PREFIX} re-rendering with @cbartens/bkit@${resolvedPlan.target} ...`);
637
+ const reArgs = ["exec", "bkit", "upgrade"];
638
+ if (flags.nonInteractive) reArgs.push("--auto-apply");
639
+ const re = spawnSync("pnpm", reArgs, { cwd, stdio: "inherit" });
640
+ process.exit(re.status ?? 1);
641
+ }
642
+
643
+ export async function runUpgradeCommand(upgradeFlags: UpgradeFlags): Promise<void> {
644
+ setLogPrefix("[bkit-upgrade]");
645
+
646
+ // --to=<version> / --latest: atomic self-bump. Install the target package,
647
+ // then re-exec the freshly-installed binary to render + re-pin (this process
648
+ // is the OLD code). When a bump happens (or a dry-run reports one) runSelfBump
649
+ // handles the whole run; when already at target it returns false and we fall
650
+ // through to a normal in-place re-render.
651
+ if (upgradeFlags.toVersion !== null || upgradeFlags.latest) {
652
+ const handled = await runSelfBump(upgradeFlags, process.cwd());
653
+ if (handled) return;
654
+ }
655
+
656
+ console.log(
657
+ `${LOG_PREFIX} Running upgrade${upgradeFlags.dryRun ? " (dry-run)" : ""}${upgradeFlags.nonInteractive ? " (non-interactive)" : ""}`,
658
+ );
659
+
660
+ // Collect bkit-managed payload candidates from the package: `shared/` and
661
+ // `core/` hold every file install writes. `templates/` is excluded — it is
662
+ // copy-and-own, and syncTemplateCopies refreshes the consumer's copies instead.
663
+ const sharedRoot = getSharedRoot();
664
+
665
+ // Package-only core subtrees: engine/ (TypeScript source), workflows/ and
666
+ // prompts/ (rendered mirrors), .bkit/ (canonical docs, handled by
667
+ // renderManagedOutputs) and hooks/ (spliced into hooks at render time).
668
+ const CORE_SKIP_TOP_DIRS: ReadonlySet<string> = new Set([
669
+ "engine",
670
+ "workflows",
671
+ "prompts",
672
+ ".bkit",
673
+ "hooks",
674
+ ]);
675
+
676
+ // Manifest entry drives the per-file write strategy in runUpgrade:
677
+ // markered-text → block-merge, json → deep-merge (both preserve consumer
678
+ // content outside the managed region), byte-equal-text / unmanaged →
679
+ // whole-file write with drift detection.
680
+ const entryByPath = new Map<string, ManifestEntry>();
681
+ for (const entry of getInstallManifest()) {
682
+ entryByPath.set(entry.path, entry);
683
+ }
684
+
685
+ // Opt-in module files (cloud, opencode, codex) must NEVER be force-created by
686
+ // upgrade — they ship only via an explicit install flag. Update them when the
687
+ // consumer has opted in (dest present).
688
+ const optInPaths = new Set<string>();
689
+ for (const mod of OPTIN_MODULES) {
690
+ for (const entry of getModuleManifest(mod as ModuleName)) optInPaths.add(entry.path);
691
+ }
692
+
693
+ // Host modules (claude, cursor, codex, opencode) are never force-created by upgrade: they
694
+ // are gated on sentinel-detected installation, exactly like `bkit check` scopes its
695
+ // drift gate. core + unmanaged files (docs/*.md, no manifest entry) always upgrade; the
696
+ // opt-in modules keep their dest-presence gating just below.
697
+ const installedModules = detectInstalledModules(process.cwd());
698
+
699
+ // Resolve the consumer's tracker so upgrade renders tracker-conditional files
700
+ // (opencode.json, the mcp.json files) the same way install does.
701
+ let upgradeTracker: IssueTracker = DEFAULT_ISSUE_TRACKER;
702
+ try {
703
+ const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf-8")) as {
704
+ bkit?: { issueTracker?: unknown };
705
+ };
706
+ const stored = parseIssueTracker(pkg.bkit?.issueTracker);
707
+ if (stored !== null) upgradeTracker = stored;
708
+ } catch {
709
+ // package.json absent/unparseable — default tracker
710
+ }
711
+
712
+ // opencode.json is provider/tracker-templated on install (renderOpencodeJson resolves the
713
+ // `@@OPENCODE_*@@` sentinels). Upgrade renders it the same way, with the installed
714
+ // provider, so no raw sentinel key reaches the consumer's config.
715
+ const OPENCODE_JSON_RELPATH = path.join(".opencode", "opencode.json");
716
+ // Demanded only when the consumer actually has an opencode.json to re-render — a repo
717
+ // without the host must not be failed for a provider it was never asked to choose.
718
+ const upgradeOpencodeProvider = fs.existsSync(path.join(process.cwd(), OPENCODE_JSON_RELPATH))
719
+ ? requireOpencodeProvider(process.cwd(), "upgrade")
720
+ : null;
721
+
722
+ // .mcp.json / .cursor/mcp.json: bkit owns only its tracker entry, which the walk's json
723
+ // deep-merge cannot express. reconcileMcpJson handles them after runUpgrade, like install.
724
+ const MCP_ROOT_RELPATH = ".mcp.json";
725
+ const CURSOR_MCP_RELPATH = path.join(".cursor", "mcp.json");
726
+
727
+ const candidates: UpgradeCandidate[] = [];
728
+ const collectPayload = (dir: string, rel: string, skipTopDirs: ReadonlySet<string>): void => {
729
+ for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
730
+ if (rel === "" && ent.isDirectory() && skipTopDirs.has(ent.name)) continue;
731
+ const entRel = rel ? path.join(rel, ent.name) : ent.name;
732
+ const entAbs = path.join(dir, ent.name);
733
+ if (ent.isDirectory()) {
734
+ collectPayload(entAbs, entRel, skipTopDirs);
735
+ } else if (ent.isFile()) {
736
+ // Each payload root's LICENSE.md is package metadata, never an install source.
737
+ if (ent.name === "LICENSE.md") continue;
738
+ // Single shared dotfile remap (gitignore → .gitignore, npmignore → .npmignore).
739
+ const relPath = remapTemplateDest(entRel);
740
+ // `.claude/bkit-cloud.md` + `.cursor/bkit-cloud.md` are GENERATED output files
741
+ // (writeClaudeCloudDoc / writeCursorCloudDoc), not payload files to reconcile:
742
+ // install/upgrade regenerate them with resolved secret values, so the raw
743
+ // source is never a byte-match and the walk must never drift-flag or
744
+ // overwrite them. Regenerated explicitly in the runUpgrade block below
745
+ // (host-gated, non-dry-run).
746
+ if (relPath === CLAUDE_CLOUD_RELPATH || relPath === CURSOR_CLOUD_RELPATH) continue;
747
+ if (relPath === MCP_ROOT_RELPATH || relPath === CURSOR_MCP_RELPATH) continue;
748
+ // Skip opt-in-module files the consumer hasn't opted into (dest absent).
749
+ if (optInPaths.has(relPath) && !fs.existsSync(path.join(process.cwd(), relPath))) {
750
+ continue;
751
+ }
752
+ const entry = entryByPath.get(relPath);
753
+ // Skip host-module files when that module is not installed — upgrade updates
754
+ // only what the consumer opted into, never force-creating a new module. opt-ins are
755
+ // handled by the dest-presence check above; core + entry-less files always pass.
756
+ const ownerModule = entry?.module;
757
+ if (
758
+ ownerModule &&
759
+ ownerModule !== "core" &&
760
+ !optInPaths.has(relPath) &&
761
+ !installedModules.has(ownerModule)
762
+ ) {
763
+ continue;
764
+ }
765
+ const contentOverride =
766
+ relPath === OPENCODE_JSON_RELPATH && upgradeOpencodeProvider
767
+ ? renderOpencodeJson(entAbs, upgradeTracker, upgradeOpencodeProvider, process.cwd())
768
+ : undefined;
769
+ candidates.push({
770
+ relPath,
771
+ templatePath: entAbs,
772
+ format: entry?.format,
773
+ contentOverride,
774
+ });
775
+ }
776
+ }
777
+ };
778
+ if (fs.existsSync(sharedRoot)) collectPayload(sharedRoot, "", new Set<string>());
779
+ const coreRoot = getCoreRoot();
780
+ if (fs.existsSync(coreRoot)) collectPayload(coreRoot, "", CORE_SKIP_TOP_DIRS);
781
+
782
+ // Markered-text templates managed on upgrade are token-free, but resolve real
783
+ // tokens when possible so any future token-bearing block stays correct.
784
+ const tokens = await resolveTokens(process.cwd()).catch(() => undefined);
785
+
786
+ const result = runUpgrade(candidates, {
787
+ nonInteractive: upgradeFlags.nonInteractive,
788
+ dryRun: upgradeFlags.dryRun,
789
+ cwd: process.cwd(),
790
+ tokens,
791
+ });
792
+
793
+ // Refresh the consumer's `.bkit/templates/` copies and name what changed. The
794
+ // list is computed before overwriting, so it is exactly the package's template
795
+ // diff. The copies carry no hash, so nothing here feeds `.bkit/version`.
796
+ const templateChanges = syncTemplateCopies(process.cwd(), {
797
+ dryRun: upgradeFlags.dryRun,
798
+ ws: { writes: [] },
799
+ });
800
+ const templateReport = formatTemplateChanges(templateChanges);
801
+ if (templateReport) console.log(`${LOG_PREFIX} ${templateReport}`);
802
+
803
+ // Payload view links — the same sync install runs (`.bkit/core` + `.bkit/shared`
804
+ // point into the installed package). Never clobbers a real directory; a platform
805
+ // refusal is reported, never fatal. Throwaway WriteSet: links carry no hash.
806
+ const linkChanges = syncPayloadLinks(process.cwd(), {
807
+ dryRun: upgradeFlags.dryRun,
808
+ ws: { writes: [] },
809
+ });
810
+ const linkReport = formatPayloadLinkChanges(linkChanges);
811
+ if (linkReport) console.log(`${LOG_PREFIX} ${linkReport}`);
812
+
813
+ // Re-render all installed provider blocks for upgrade.
814
+ // The candidates walk above handles the ACTIVE provider's block via renderOpencodeJson.
815
+ // For each ADDITIONAL installed provider, reconcile their template block into opencode.json
816
+ // so template changes (new keys, updated placeholders) propagate to all providers' blocks.
817
+ const OPENCODE_JSON_DST = path.join(".opencode", "opencode.json");
818
+ if (fs.existsSync(path.join(process.cwd(), OPENCODE_JSON_DST))) {
819
+ const allProviders = detectOpencodeProviders(process.cwd());
820
+ const otherProviders = allProviders.filter((p) => p !== upgradeOpencodeProvider);
821
+ if (otherProviders.length > 0) {
822
+ const jsonSrc = path.join(sharedRoot, ".opencode", "opencode.json");
823
+ if (fs.existsSync(jsonSrc)) {
824
+ const upgradeWs: WriteSet = { writes: [] };
825
+ for (const provider of otherProviders) {
826
+ const rendered = renderOpencodeJson(jsonSrc, upgradeTracker, provider, process.cwd());
827
+ reconcileOpencodeJson(rendered, OPENCODE_JSON_DST, upgradeFlags.dryRun, upgradeWs);
828
+ }
829
+ for (const w of upgradeWs.writes) {
830
+ console.log(
831
+ `${LOG_PREFIX}${upgradeFlags.dryRun ? " [dry-run]" : ""} upgrade: additional provider ${w.path}`,
832
+ );
833
+ }
834
+ }
835
+ }
836
+ }
837
+
838
+ // The payload walk above only covers the written payload files. Re-render the
839
+ // bkit-managed OUTPUT files install also produces but that are NOT payload — host
840
+ // agents/commands (source-rendered from core/prompts + core/workflows), the
841
+ // `.bkit/*.md` canonical docs (runBkitDocs) and core's package.json scripts (the
842
+ // bkit:gate:* names, add-if-missing). These are
843
+ // bkit-owned, force-overwritten output. Only the hosts the consumer installed are
844
+ // re-rendered (detected by their agents dir). `.bkit/prompts.md` is markered → runBkitDocs
845
+ // block-merges it: managed block refreshed, consumer `## Model Overrides` below bkit:end
846
+ // preserved. Docs stay single-source PACKAGE-side, never in the payload walk.
847
+ const renderModules = detectInstalledHostModules(process.cwd());
848
+ // Demanded only when opencode is one of the detected hosts — see requireOpencodeProvider.
849
+ const renderProvider = renderModules.has("opencode")
850
+ ? requireOpencodeProvider(process.cwd(), "upgrade render")
851
+ : null;
852
+ // Build the model lookups the SAME way the install dispatch does: DEFAULTS from the
853
+ // package's .bkit/prompts.md § Models, consumer overrides from the consumer's installed
854
+ // .bkit/prompts.md `## Model Overrides` (per-agent, per-provider, preserved across upgrades).
855
+ let renderModelLookup: Map<string, string> = new Map();
856
+ let renderOpencodeModelLookup: Map<string, string> = new Map();
857
+ let renderCodexModelLookup: Map<string, string> = new Map();
858
+ let renderEffortMap: EffortMap = new Map();
859
+ const pkgPromptsMd = path.join(getBkitDocsRoot(), "prompts.md");
860
+ const consumerPromptsMd = path.join(process.cwd(), ".bkit", "prompts.md");
861
+ if (fs.existsSync(pkgPromptsMd)) {
862
+ try {
863
+ renderModelLookup = parseModelLookup(pkgPromptsMd);
864
+ } catch {
865
+ // Not fatal — the cursor render fails per-file if a model is missing
866
+ }
867
+ applyModelOverrides(renderModelLookup, "cursor", consumerPromptsMd);
868
+ // Non-null exactly when opencode is a detected host (see renderProvider above).
869
+ if (renderProvider) {
870
+ try {
871
+ renderOpencodeModelLookup = buildOpencodeModelLookup(pkgPromptsMd, renderProvider);
872
+ } catch {
873
+ // Not fatal — the opencode render fails per-file if a model is missing
874
+ }
875
+ applyModelOverrides(renderOpencodeModelLookup, renderProvider, consumerPromptsMd);
876
+ }
877
+ if (renderModules.has("codex")) {
878
+ try {
879
+ renderCodexModelLookup = buildOpencodeModelLookup(pkgPromptsMd, "openai");
880
+ } catch {
881
+ // Not fatal — the codex module fails per-file if a model is missing
882
+ }
883
+ applyModelOverrides(renderCodexModelLookup, "openai", consumerPromptsMd);
884
+ }
885
+ renderEffortMap = parseEffortMap(pkgPromptsMd);
886
+ }
887
+ const renderWs: WriteSet = { writes: [] };
888
+ const renderCtx: ModuleContext = {
889
+ dryRun: upgradeFlags.dryRun,
890
+ tokens: tokens ?? { DEFAULT_BRANCH: "", PROJECT_NAME: "", REPO_SLUG: "" },
891
+ modelLookup: renderModelLookup,
892
+ opencodeModelLookup: renderOpencodeModelLookup,
893
+ codexModelLookup: renderCodexModelLookup,
894
+ effortMap: renderEffortMap,
895
+ opencodeProvider: renderProvider,
896
+ advisories: [],
897
+ ws: renderWs,
898
+ logPrefix: LOG_PREFIX,
899
+ postDispatch: [],
900
+ issueTracker: upgradeTracker,
901
+ cloudVariant: null,
902
+ // Re-stamp every rendered agent + command at the version we are upgrading TO,
903
+ // so a clean upgrade refreshes the managed-version marker and `bkit check` stays green.
904
+ version: getInstallingVersion(),
905
+ };
906
+ const rendered = renderManagedOutputs(renderModules, renderCtx);
907
+
908
+ // MCP config: bkit's tracker entry only (reconcileMcpJson), for the hosts the consumer
909
+ // installed — the same pass install's claude/cursor modules run. Never force-creates the
910
+ // file for a host the consumer does not have.
911
+ const mcpWs: WriteSet = { writes: [] };
912
+ for (const [host, relPath] of [
913
+ ["claude", MCP_ROOT_RELPATH],
914
+ ["cursor", CURSOR_MCP_RELPATH],
915
+ ] as const) {
916
+ if (!renderModules.has(host)) continue;
917
+ const src = path.join(sharedRoot, relPath);
918
+ if (!fs.existsSync(src)) continue;
919
+ reconcileMcpJson(
920
+ src,
921
+ path.join(process.cwd(), relPath),
922
+ upgradeTracker,
923
+ upgradeFlags.dryRun,
924
+ mcpWs,
925
+ );
926
+ }
927
+ for (const w of mcpWs.writes) {
928
+ console.log(
929
+ `${LOG_PREFIX}${upgradeFlags.dryRun ? " [dry-run]" : ""} upgrade: ${path.relative(process.cwd(), w.path)} (tracker MCP entry)`,
930
+ );
931
+ }
932
+
933
+ // Regenerate `.claude/bkit-cloud.md` (excluded from the payload walk above — it is a
934
+ // generated, untracked, secret-bearing OUTPUT file). Claude-host-gated so upgrade
935
+ // never force-creates it for a non-claude repo; non-dry-run so `bkit check` never
936
+ // writes resolved secrets. Rotated secrets / version bumps reach the paste doc via
937
+ // the same helper install uses (runClaudeModule). Untracked → not in canonicalHashes.
938
+ // What enrich recorded this upgrade, threaded into the one .bkit/version writer.
939
+ // null = not determined (dry run / no settings file) -> keep the prior record.
940
+ let upgradeClaudeAllowDerived: readonly string[] | null = null;
941
+ if (!upgradeFlags.dryRun && renderModules.has("claude") && tokens) {
942
+ if (writeClaudeCloudDoc(process.cwd(), tokens)) {
943
+ console.log(
944
+ `${LOG_PREFIX} upgrade: .claude/bkit-cloud.md (regenerated — gitignored, holds resolved secrets)`,
945
+ );
946
+ }
947
+ }
948
+
949
+ // Same for `.cursor/bkit-cloud.md` — cursor-host-gated twin (see writeCursorCloudDoc).
950
+ // Uses upgradeTracker so the Linear/GitHub env-var policy matches the installed
951
+ // tracker; excluded from the payload walk above for the same reason as the Claude doc.
952
+ if (!upgradeFlags.dryRun && renderModules.has("cursor") && tokens) {
953
+ if (writeCursorCloudDoc(process.cwd(), tokens, upgradeTracker)) {
954
+ console.log(
955
+ `${LOG_PREFIX} upgrade: .cursor/bkit-cloud.md (regenerated — gitignored, holds resolved secrets)`,
956
+ );
957
+ }
958
+ }
959
+
960
+ // Network allowlist + MCP allows — OpenCode from renderOpencodeJson; Claude enrich
961
+ // below; Cursor `.cursor/allowlist.json` + `.cursor/cli.json` only when cursor
962
+ // module installed.
963
+ {
964
+ const cwd = process.cwd();
965
+ if (renderModules.has("cursor")) {
966
+ for (const art of [
967
+ writeNetworkAllowlistArtifact(cwd, upgradeFlags.dryRun),
968
+ writeCursorCliPermissionsArtifact(cwd, upgradeFlags.dryRun),
969
+ ]) {
970
+ if (art.wrote) {
971
+ console.log(
972
+ `${LOG_PREFIX}${upgradeFlags.dryRun ? " [dry-run]" : ""} upgrade: ${art.path}`,
973
+ );
974
+ }
975
+ }
976
+ }
977
+ if (renderModules.has("claude") && fs.existsSync(path.join(cwd, ".claude", "settings.json"))) {
978
+ const enrichWs: WriteSet = { writes: [] };
979
+ upgradeClaudeAllowDerived = enrichClaudeSettingsAllows(
980
+ ".claude/settings.json",
981
+ cwd,
982
+ upgradeFlags.dryRun,
983
+ enrichWs,
984
+ );
985
+ for (const w of enrichWs.writes) {
986
+ console.log(
987
+ `${LOG_PREFIX}${upgradeFlags.dryRun ? " [dry-run]" : ""} upgrade: ${w.path} (WebFetch + MCP derived allows)`,
988
+ );
989
+ }
990
+ }
991
+ }
992
+
993
+ // Refresh canonicalHashes (from resulting on-disk content) AND bump pinnedVersion
994
+ // to the version we just upgraded TO, so the next `bkit check` has nothing to write.
995
+ // Called unconditionally (non-dry-run) so the pin bumps even when every file was a
996
+ // no-op skip. The re-rendered `.bkit/*.md` docs AND
997
+ // host agent/command mirrors land in renderWs.writes (mirrors count toward check
998
+ // exit), so feed those writes into canonicalHashes — keeping install/upgrade `.bkit/version`
999
+ // parity.
1000
+ if (!upgradeFlags.dryRun) {
1001
+ const pkgVersion = JSON.parse(fs.readFileSync(path.join(getPkgRoot(), "package.json"), "utf-8"))
1002
+ .version as string;
1003
+ const renderedDocPaths = renderWs.writes.map((w) =>
1004
+ path.relative(
1005
+ process.cwd(),
1006
+ path.isAbsolute(w.path) ? w.path : path.resolve(process.cwd(), w.path),
1007
+ ),
1008
+ );
1009
+ updateCanonicalHashesAfterUpgrade(
1010
+ {
1011
+ updated: [
1012
+ ...result.updated,
1013
+ ...renderedDocPaths,
1014
+ ...mcpWs.writes.map((w) => path.relative(process.cwd(), w.path)),
1015
+ ],
1016
+ skipped: result.skipped,
1017
+ skippedSeedable: result.skippedSeedable,
1018
+ conflicts: result.conflicts,
1019
+ },
1020
+ {
1021
+ dryRun: false,
1022
+ cwd: process.cwd(),
1023
+ pinnedVersion: pkgVersion,
1024
+ claudeAllowDerived: upgradeClaudeAllowDerived,
1025
+ },
1026
+ );
1027
+ }
1028
+
1029
+ console.log(
1030
+ `${LOG_PREFIX} Done. updated: ${result.updated.length}, skipped: ${result.skipped.length}, conflicts: ${result.conflicts.length}, re-rendered: ${rendered.length}`,
1031
+ );
1032
+
1033
+ // Non-interactive mode: exit non-zero on conflicts
1034
+ if (upgradeFlags.nonInteractive && result.conflicts.length > 0) {
1035
+ process.exit(1);
1036
+ }
1037
+ }