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