@cbartens/bkit 0.0.0-stage → 5.0.0

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