@cbartens/bkit 0.0.0-stage → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (375) hide show
  1. package/.bkit/README.md +417 -0
  2. package/.bkit/core/.agents/context.md +95 -0
  3. package/.bkit/core/.agents/docs.md +62 -0
  4. package/.bkit/core/.agents/rules.md +147 -0
  5. package/.bkit/core/.agents/skills.md +43 -0
  6. package/.bkit/core/.bkit/LICENSE.md +151 -0
  7. package/.bkit/core/.bkit/README.md +417 -0
  8. package/.bkit/core/.bkit/cloud.md +493 -0
  9. package/.bkit/core/.bkit/comparison.md +321 -0
  10. package/.bkit/core/.bkit/install.md +401 -0
  11. package/.bkit/core/.bkit/jsonl.md +497 -0
  12. package/.bkit/core/.bkit/prompts.md +474 -0
  13. package/.bkit/core/.bkit/providers.md +598 -0
  14. package/.bkit/core/.bkit/templates.md +470 -0
  15. package/.bkit/core/.bkit/trackers.md +95 -0
  16. package/.bkit/core/.bkit/workflows.md +1550 -0
  17. package/.bkit/core/.claude/hooks/bkit-gateguard.cjs +82 -0
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +93 -0
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +74 -0
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +115 -0
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +135 -0
  22. package/.bkit/core/.cursor/hooks/bkit-gateguard.cjs +111 -0
  23. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +169 -0
  24. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +63 -0
  25. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +225 -0
  26. package/.bkit/core/AGENTS.md +77 -0
  27. package/.bkit/core/LICENSE.md +149 -0
  28. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +272 -0
  29. package/.bkit/core/docs/templates/bkit-audit-adoption.md +223 -0
  30. package/.bkit/core/docs/templates/bkit-audit-agents.md +230 -0
  31. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +227 -0
  32. package/.bkit/core/docs/templates/bkit-audit-analytics.md +266 -0
  33. package/.bkit/core/docs/templates/bkit-audit-annotations.md +230 -0
  34. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +270 -0
  35. package/.bkit/core/docs/templates/bkit-audit-app-store.md +254 -0
  36. package/.bkit/core/docs/templates/bkit-audit-architecture.md +221 -0
  37. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +241 -0
  38. package/.bkit/core/docs/templates/bkit-audit-config.md +230 -0
  39. package/.bkit/core/docs/templates/bkit-audit-cost.md +218 -0
  40. package/.bkit/core/docs/templates/bkit-audit-coverage.md +221 -0
  41. package/.bkit/core/docs/templates/bkit-audit-database.md +229 -0
  42. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +251 -0
  43. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +283 -0
  44. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +268 -0
  45. package/.bkit/core/docs/templates/bkit-audit-documentation.md +280 -0
  46. package/.bkit/core/docs/templates/bkit-audit-duplication.md +253 -0
  47. package/.bkit/core/docs/templates/bkit-audit-failures.md +259 -0
  48. package/.bkit/core/docs/templates/bkit-audit-flakes.md +237 -0
  49. package/.bkit/core/docs/templates/bkit-audit-gates.md +250 -0
  50. package/.bkit/core/docs/templates/bkit-audit-issues.md +273 -0
  51. package/.bkit/core/docs/templates/bkit-audit-llm.md +239 -0
  52. package/.bkit/core/docs/templates/bkit-audit-logs.md +266 -0
  53. package/.bkit/core/docs/templates/bkit-audit-models.md +210 -0
  54. package/.bkit/core/docs/templates/bkit-audit-privacy.md +211 -0
  55. package/.bkit/core/docs/templates/bkit-audit-prompts.md +216 -0
  56. package/.bkit/core/docs/templates/bkit-audit-red-team.md +220 -0
  57. package/.bkit/core/docs/templates/bkit-audit-reliability.md +222 -0
  58. package/.bkit/core/docs/templates/bkit-audit-repo.md +224 -0
  59. package/.bkit/core/docs/templates/bkit-audit-security.md +274 -0
  60. package/.bkit/core/docs/templates/bkit-audit-slop.md +200 -0
  61. package/.bkit/core/docs/templates/bkit-audit-testing.md +270 -0
  62. package/.bkit/core/docs/templates/bkit-audit-usability.md +237 -0
  63. package/.bkit/core/docs/templates/bkit-plan.md +476 -0
  64. package/.bkit/core/engine/checks/after/auth.ts +149 -0
  65. package/.bkit/core/engine/checks/after/ci-yml.ts +701 -0
  66. package/.bkit/core/engine/checks/after/github.ts +424 -0
  67. package/.bkit/core/engine/checks/after/index.ts +530 -0
  68. package/.bkit/core/engine/checks/after/managed.ts +217 -0
  69. package/.bkit/core/engine/checks/after/suppression.ts +53 -0
  70. package/.bkit/core/engine/checks/after/tools.ts +427 -0
  71. package/.bkit/core/engine/checks/before/context-fetch.ts +429 -0
  72. package/.bkit/core/engine/checks/before/env.ts +187 -0
  73. package/.bkit/core/engine/checks/before/files.ts +204 -0
  74. package/.bkit/core/engine/checks/before/index.ts +206 -0
  75. package/.bkit/core/engine/checks/before/mcp.ts +127 -0
  76. package/.bkit/core/engine/checks/before/repo.ts +77 -0
  77. package/.bkit/core/engine/checks/before/version.ts +67 -0
  78. package/.bkit/core/engine/checks/status-holes.ts +479 -0
  79. package/.bkit/core/engine/cli.ts +867 -0
  80. package/.bkit/core/engine/commands/analysis.ts +550 -0
  81. package/.bkit/core/engine/commands/ci/ci.ts +483 -0
  82. package/.bkit/core/engine/commands/comply.ts +415 -0
  83. package/.bkit/core/engine/commands/harvest.ts +459 -0
  84. package/.bkit/core/engine/commands/install/check.ts +70 -0
  85. package/.bkit/core/engine/commands/install/doctor.ts +254 -0
  86. package/.bkit/core/engine/commands/install/install.ts +550 -0
  87. package/.bkit/core/engine/commands/install/uninstall.ts +995 -0
  88. package/.bkit/core/engine/commands/install/upgrade.ts +1037 -0
  89. package/.bkit/core/engine/commands/launch.ts +139 -0
  90. package/.bkit/core/engine/commands/lib.ts +495 -0
  91. package/.bkit/core/engine/commands/registry.ts +53 -0
  92. package/.bkit/core/engine/commands/setup/setup.ts +184 -0
  93. package/.bkit/core/engine/commands/telemetry.ts +32 -0
  94. package/.bkit/core/engine/commands/workflow/branches.ts +1514 -0
  95. package/.bkit/core/engine/commands/workflow/context.ts +961 -0
  96. package/.bkit/core/engine/commands/workflow/counters.ts +268 -0
  97. package/.bkit/core/engine/commands/workflow/fids.ts +243 -0
  98. package/.bkit/core/engine/commands/workflow/issues.ts +675 -0
  99. package/.bkit/core/engine/commands/workflow/ledgers.ts +575 -0
  100. package/.bkit/core/engine/commands/workflow/locks.ts +478 -0
  101. package/.bkit/core/engine/commands/workflow/prs.ts +1087 -0
  102. package/.bkit/core/engine/commands/workflow/repo.ts +220 -0
  103. package/.bkit/core/engine/commands/workflow/roadmap.ts +576 -0
  104. package/.bkit/core/engine/commands/workflow/runs.ts +2140 -0
  105. package/.bkit/core/engine/commands/workflow/runtime.ts +300 -0
  106. package/.bkit/core/engine/commands/workflow/skills.ts +118 -0
  107. package/.bkit/core/engine/commands/workflow/status.ts +455 -0
  108. package/.bkit/core/engine/commands/workflow/steps.ts +1300 -0
  109. package/.bkit/core/engine/commands/workflow/tests.ts +161 -0
  110. package/.bkit/core/engine/commands/workflow/workflows.ts +1573 -0
  111. package/.bkit/core/engine/commands/workflow/workstreams.ts +164 -0
  112. package/.bkit/core/engine/commands/workflow/worktrees.ts +534 -0
  113. package/.bkit/core/engine/install/cloud-env.ts +924 -0
  114. package/.bkit/core/engine/install/managed-block.ts +212 -0
  115. package/.bkit/core/engine/install/manifest.ts +448 -0
  116. package/.bkit/core/engine/install/modules/claude.ts +362 -0
  117. package/.bkit/core/engine/install/modules/cloud.ts +173 -0
  118. package/.bkit/core/engine/install/modules/codex.ts +219 -0
  119. package/.bkit/core/engine/install/modules/core.ts +620 -0
  120. package/.bkit/core/engine/install/modules/cursor.ts +231 -0
  121. package/.bkit/core/engine/install/modules/index.ts +242 -0
  122. package/.bkit/core/engine/install/modules/opencode.ts +573 -0
  123. package/.bkit/core/engine/install/payload-links.ts +150 -0
  124. package/.bkit/core/engine/install/placeholders.ts +108 -0
  125. package/.bkit/core/engine/install/template-copies.ts +119 -0
  126. package/.bkit/core/engine/install/version-file.ts +284 -0
  127. package/.bkit/core/engine/install/write.ts +467 -0
  128. package/.bkit/core/engine/ledgers/clamp-log.ts +32 -0
  129. package/.bkit/core/engine/ledgers/status.ts +213 -0
  130. package/.bkit/core/engine/ledgers/telemetry.ts +1143 -0
  131. package/.bkit/core/engine/render/hosts.ts +372 -0
  132. package/.bkit/core/engine/render/models.ts +323 -0
  133. package/.bkit/core/engine/render/parts.ts +38 -0
  134. package/.bkit/core/engine/render/trackers.ts +170 -0
  135. package/.bkit/core/engine/shared/egress.ts +345 -0
  136. package/.bkit/core/engine/shared/json.ts +16 -0
  137. package/.bkit/core/engine/shared/log-prefix.ts +9 -0
  138. package/.bkit/core/engine/shared/package-json.ts +29 -0
  139. package/.bkit/core/engine/shared/package-manager.ts +38 -0
  140. package/.bkit/core/engine/shared/package-roots.ts +163 -0
  141. package/.bkit/core/engine/shared/protected-paths.ts +164 -0
  142. package/.bkit/core/engine/shared/settings.ts +72 -0
  143. package/.bkit/core/engine/shared/timeouts.ts +20 -0
  144. package/.bkit/core/engine/tools/wording.ts +748 -0
  145. package/.bkit/core/hooks/gateguard-edit-payload.js +18 -0
  146. package/.bkit/core/hooks/gateguard-engine.js +193 -0
  147. package/.bkit/core/hooks/guardrails-shell.js +154 -0
  148. package/.bkit/core/hooks/guardrails-tiers.js +68 -0
  149. package/.bkit/core/hooks/preflight-linear.sh +73 -0
  150. package/.bkit/core/prompts/bkit-audit-generate.md +66 -0
  151. package/.bkit/core/prompts/bkit-build-challenge-1.md +79 -0
  152. package/.bkit/core/prompts/bkit-build-challenge-2.md +81 -0
  153. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +68 -0
  154. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +70 -0
  155. package/.bkit/core/prompts/bkit-build-challenge-tests.md +73 -0
  156. package/.bkit/core/prompts/bkit-build-install-skills.md +67 -0
  157. package/.bkit/core/prompts/bkit-build-plan-current.md +75 -0
  158. package/.bkit/core/prompts/bkit-build-plan-execute.md +72 -0
  159. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +73 -0
  160. package/.bkit/core/prompts/bkit-build-plan-verify.md +88 -0
  161. package/.bkit/core/prompts/bkit-build-summary.md +93 -0
  162. package/.bkit/core/prompts/bkit-debug-abort-handover.md +90 -0
  163. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +151 -0
  164. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +78 -0
  165. package/.bkit/core/prompts/bkit-debug-failure-soak.md +73 -0
  166. package/.bkit/core/prompts/bkit-debug-summary.md +95 -0
  167. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +72 -0
  168. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +72 -0
  169. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +75 -0
  170. package/.bkit/core/prompts/bkit-design-generate.md +110 -0
  171. package/.bkit/core/prompts/bkit-design-organise.md +85 -0
  172. package/.bkit/core/prompts/bkit-design-review-1.md +121 -0
  173. package/.bkit/core/prompts/bkit-design-review-2.md +111 -0
  174. package/.bkit/core/prompts/bkit-design-spike.md +97 -0
  175. package/.bkit/core/prompts/bkit-design-summary.md +106 -0
  176. package/.bkit/core/prompts/bkit-design-update.md +66 -0
  177. package/.bkit/core/prompts/bkit-plan-complexity-check.md +66 -0
  178. package/.bkit/core/prompts/bkit-plan-complexity-split.md +87 -0
  179. package/.bkit/core/prompts/bkit-plan-generate.md +74 -0
  180. package/.bkit/core/prompts/bkit-plan-review-1.md +90 -0
  181. package/.bkit/core/prompts/bkit-plan-review-2.md +80 -0
  182. package/.bkit/core/prompts/bkit-plan-review-3.md +92 -0
  183. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +84 -0
  184. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +84 -0
  185. package/.bkit/core/prompts/bkit-plan-summary.md +106 -0
  186. package/.bkit/core/prompts/bkit-plan-update.md +68 -0
  187. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +90 -0
  188. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +94 -0
  189. package/.bkit/core/prompts/bkit-ship-summary.md +77 -0
  190. package/.bkit/core/prompts/bkit-ship-update-docs.md +71 -0
  191. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +91 -0
  192. package/.bkit/core/prompts/bkit-utility-update-decisions.md +75 -0
  193. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +76 -0
  194. package/.bkit/core/prompts/bkit-utility-update-documentation.md +61 -0
  195. package/.bkit/core/prompts/bkit-utility-update-failures.md +76 -0
  196. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +75 -0
  197. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +82 -0
  198. package/.bkit/core/workflows/bkit-auto.md +121 -0
  199. package/.bkit/core/workflows/bkit-build.md +802 -0
  200. package/.bkit/core/workflows/bkit-debug.md +649 -0
  201. package/.bkit/core/workflows/bkit-design.md +495 -0
  202. package/.bkit/core/workflows/bkit-plan.md +510 -0
  203. package/.bkit/core/workflows/bkit-ship.md +650 -0
  204. package/.bkit/shared/.bkit/.env.example +86 -0
  205. package/.bkit/shared/.claude/bkit-cloud.md +117 -0
  206. package/.bkit/shared/.claude/settings.json +88 -0
  207. package/.bkit/shared/.codex/hooks.json +26 -0
  208. package/.bkit/shared/.cursor/bkit-cloud.md +84 -0
  209. package/.bkit/shared/.cursor/hooks.json +26 -0
  210. package/.bkit/shared/.cursor/mcp.json +15 -0
  211. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +12 -0
  212. package/.bkit/shared/.gitattributes +37 -0
  213. package/.bkit/shared/.mcp.json +16 -0
  214. package/.bkit/shared/.opencode/opencode.json +62 -0
  215. package/.bkit/shared/CLAUDE.md +11 -0
  216. package/.bkit/shared/LICENSE.md +22 -0
  217. package/.bkit/shared/docs/architecture.md +19 -0
  218. package/.bkit/shared/docs/data-schema.md +19 -0
  219. package/.bkit/shared/docs/deployments.md +433 -0
  220. package/.bkit/shared/docs/design.md +39 -0
  221. package/.bkit/shared/docs/noise.md +19 -0
  222. package/.bkit/shared/docs/observability.md +25 -0
  223. package/.bkit/shared/docs/security.md +42 -0
  224. package/.bkit/shared/docs/setup.md +30 -0
  225. package/.bkit/shared/docs/technology.md +18 -0
  226. package/.bkit/shared/docs/testing.md +413 -0
  227. package/.bkit/shared/gitignore +97 -0
  228. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +187 -0
  229. package/.bkit/templates/.cursor/Dockerfile +68 -0
  230. package/.bkit/templates/.cursor/environment.json +6 -0
  231. package/.bkit/templates/.cursor/settings.json +11 -0
  232. package/.bkit/templates/.envrc +7 -0
  233. package/.bkit/templates/.github/dependabot.yml +52 -0
  234. package/.bkit/templates/.github/renovate.json5 +224 -0
  235. package/.bkit/templates/.github/workflows/bkit-ci.yml +1062 -0
  236. package/.bkit/templates/.github/workflows/bkit-cloud.yml +564 -0
  237. package/.bkit/templates/.github/workflows/bkit-renovate.yml +102 -0
  238. package/.bkit/templates/.graphifyignore +108 -0
  239. package/.bkit/templates/.husky/pre-commit +16 -0
  240. package/.bkit/templates/.husky/pre-push +91 -0
  241. package/.bkit/templates/.lintstagedrc.json +3 -0
  242. package/.bkit/templates/.prettierignore +41 -0
  243. package/.bkit/templates/.serena/project.yml +243 -0
  244. package/.bkit/templates/.vale/styles/House/Filler.yml +11 -0
  245. package/.bkit/templates/.vale/styles/House/Hedging.yml +12 -0
  246. package/.bkit/templates/.vale/styles/House/LLMSlop.yml +13 -0
  247. package/.bkit/templates/.vale/styles/House/Verbose.yml +12 -0
  248. package/.bkit/templates/.vale.ini +67 -0
  249. package/.bkit/templates/LICENSE.md +22 -0
  250. package/.bkit/templates/context/bkit-cloudrun.md +84 -0
  251. package/.bkit/templates/context/bkit-expo.md +186 -0
  252. package/.bkit/templates/context/bkit-github.md +79 -0
  253. package/.bkit/templates/context/bkit-inngest.md +45 -0
  254. package/.bkit/templates/context/bkit-maestro.md +76 -0
  255. package/.bkit/templates/context/bkit-playwright.md +62 -0
  256. package/.bkit/templates/context/bkit-resend.md +36 -0
  257. package/.bkit/templates/context/bkit-sentry.md +65 -0
  258. package/.bkit/templates/context/bkit-serena.md +33 -0
  259. package/.bkit/templates/context/bkit-stripe.md +36 -0
  260. package/.bkit/templates/context/bkit-supabase.md +59 -0
  261. package/.bkit/templates/context/bkit-tavily.md +49 -0
  262. package/.bkit/templates/context/bkit-vercel.md +64 -0
  263. package/.bkit/templates/docs/capabilities.md +72 -0
  264. package/.bkit/templates/scripts/ci/accepted-divergences.json +21 -0
  265. package/.bkit/templates/scripts/ci/check-accepted-divergences.mjs +152 -0
  266. package/.bkit/templates/scripts/ci/check-accepted-divergences.test.mjs +130 -0
  267. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +98 -0
  268. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +86 -0
  269. package/.bkit/templates/scripts/graphify/bkit-graph-drift-rules.json +23 -0
  270. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +208 -0
  271. package/.bkit/templates/scripts/graphify/bkit-graph-eager-rules.json +35 -0
  272. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +236 -0
  273. package/.bkit/templates/scripts/graphify/bkit-graph-external-rules.json +17 -0
  274. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +290 -0
  275. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +19 -0
  276. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +120 -0
  277. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +232 -0
  278. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +36 -0
  279. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +927 -0
  280. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +351 -0
  281. package/.bkit/templates/scripts/launchd/ai.bkit.launchd.plist +26 -0
  282. package/.bkit/templates/scripts/launchd/bkit-launchd-env.sh +53 -0
  283. package/.bkit/templates/scripts/launchd/launchd.env.example +13 -0
  284. package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +275 -0
  285. package/.bkit/templates/scripts/secrets/bkit-secrets.config.mjs +66 -0
  286. package/.bkit/templates/scripts/secrets/bkit-secrets.mjs +785 -0
  287. package/.bkit/templates/scripts/serena/bkit-serena-mcp.sh +30 -0
  288. package/.bkit/templates/scripts/serena/bkit-serena.mcp.json +9 -0
  289. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +286 -0
  290. package/.bkit/templates/slop-scan.config.json +120 -0
  291. package/CHANGELOG.md +1503 -0
  292. package/LICENSE.md +161 -0
  293. package/README.md +184 -2
  294. package/dist/checks/after/auth.js +140 -0
  295. package/dist/checks/after/ci-yml.js +681 -0
  296. package/dist/checks/after/github.js +400 -0
  297. package/dist/checks/after/index.js +431 -0
  298. package/dist/checks/after/managed.js +187 -0
  299. package/dist/checks/after/suppression.js +39 -0
  300. package/dist/checks/after/tools.js +351 -0
  301. package/dist/checks/before/context-fetch.js +426 -0
  302. package/dist/checks/before/env.js +163 -0
  303. package/dist/checks/before/files.js +187 -0
  304. package/dist/checks/before/index.js +162 -0
  305. package/dist/checks/before/mcp.js +111 -0
  306. package/dist/checks/before/repo.js +71 -0
  307. package/dist/checks/before/version.js +60 -0
  308. package/dist/checks/status-holes.js +393 -0
  309. package/dist/cli.js +688 -0
  310. package/dist/commands/analysis.js +325 -0
  311. package/dist/commands/ci/ci.js +438 -0
  312. package/dist/commands/comply.js +310 -0
  313. package/dist/commands/harvest.js +354 -0
  314. package/dist/commands/install/check.js +61 -0
  315. package/dist/commands/install/doctor.js +209 -0
  316. package/dist/commands/install/install.js +475 -0
  317. package/dist/commands/install/uninstall.js +839 -0
  318. package/dist/commands/install/upgrade.js +782 -0
  319. package/dist/commands/launch.js +118 -0
  320. package/dist/commands/lib.js +363 -0
  321. package/dist/commands/registry.js +50 -0
  322. package/dist/commands/setup/setup.js +158 -0
  323. package/dist/commands/telemetry.js +29 -0
  324. package/dist/commands/workflow/branches.js +1265 -0
  325. package/dist/commands/workflow/context.js +846 -0
  326. package/dist/commands/workflow/counters.js +227 -0
  327. package/dist/commands/workflow/fids.js +224 -0
  328. package/dist/commands/workflow/issues.js +585 -0
  329. package/dist/commands/workflow/ledgers.js +472 -0
  330. package/dist/commands/workflow/locks.js +364 -0
  331. package/dist/commands/workflow/prs.js +904 -0
  332. package/dist/commands/workflow/repo.js +199 -0
  333. package/dist/commands/workflow/roadmap.js +495 -0
  334. package/dist/commands/workflow/runs.js +1717 -0
  335. package/dist/commands/workflow/runtime.js +257 -0
  336. package/dist/commands/workflow/skills.js +110 -0
  337. package/dist/commands/workflow/status.js +392 -0
  338. package/dist/commands/workflow/steps.js +1093 -0
  339. package/dist/commands/workflow/tests.js +144 -0
  340. package/dist/commands/workflow/workflows.js +1342 -0
  341. package/dist/commands/workflow/workstreams.js +141 -0
  342. package/dist/commands/workflow/worktrees.js +473 -0
  343. package/dist/install/cloud-env.js +818 -0
  344. package/dist/install/managed-block.js +182 -0
  345. package/dist/install/manifest.js +376 -0
  346. package/dist/install/modules/claude.js +288 -0
  347. package/dist/install/modules/cloud.js +151 -0
  348. package/dist/install/modules/codex.js +193 -0
  349. package/dist/install/modules/core.js +531 -0
  350. package/dist/install/modules/cursor.js +186 -0
  351. package/dist/install/modules/index.js +152 -0
  352. package/dist/install/modules/opencode.js +504 -0
  353. package/dist/install/payload-links.js +119 -0
  354. package/dist/install/placeholders.js +87 -0
  355. package/dist/install/template-copies.js +106 -0
  356. package/dist/install/version-file.js +204 -0
  357. package/dist/install/write.js +342 -0
  358. package/dist/ledgers/clamp-log.js +27 -0
  359. package/dist/ledgers/status.js +156 -0
  360. package/dist/ledgers/telemetry.js +637 -0
  361. package/dist/render/hosts.js +339 -0
  362. package/dist/render/models.js +288 -0
  363. package/dist/render/parts.js +33 -0
  364. package/dist/render/trackers.js +135 -0
  365. package/dist/shared/egress.js +299 -0
  366. package/dist/shared/json.js +16 -0
  367. package/dist/shared/log-prefix.js +7 -0
  368. package/dist/shared/package-json.js +22 -0
  369. package/dist/shared/package-manager.js +32 -0
  370. package/dist/shared/package-roots.js +145 -0
  371. package/dist/shared/protected-paths.js +153 -0
  372. package/dist/shared/settings.js +44 -0
  373. package/dist/shared/timeouts.js +19 -0
  374. package/dist/tools/wording.js +680 -0
  375. package/package.json +101 -4
@@ -0,0 +1,924 @@
1
+ // install/cloud-env.ts — resolve a copy-paste-ready Claude Code on the web env-var block
2
+ // by *following the consumer's `.envrc`*.
3
+ //
4
+ // The generated `.claude/bkit-cloud.md` (see runClaudeModule) inlines REAL SECRET
5
+ // VALUES so it is gitignored + chmod 600 and never committed. This module owns the
6
+ // stack-agnostic resolution: it reads whatever dotenv files the repo's `.envrc`
7
+ // sources, honours the `.envrc` `unset` lines, and drops session-hijack keys.
8
+ // bkit hardcodes NO stack-specific key lists — the stack knowledge lives in the
9
+ // consumer's `.envrc`, keeping bkit's shipped surface stack-independent.
10
+ //
11
+ // Excluded keys are exactly the vars `.envrc` unsets, and the review key is
12
+ // BKIT_ANTHROPIC_API_KEY — both derived here without a bespoke key list.
13
+
14
+ import * as fs from "node:fs";
15
+ import * as path from "node:path";
16
+ import type { IssueTracker } from "./manifest.js";
17
+ import { getSharedRoot } from "../shared/package-roots.js";
18
+ import { applyTokens, type TokenMap } from "./placeholders.js";
19
+ import { BKIT_EGRESS_SOURCES, type EgressSource } from "../shared/egress.js";
20
+ import { sha256 } from "./version-file.js";
21
+
22
+ // Consumer-relative paths of the generated docs. Shared so the upgrade template walk
23
+ // (commands/install/install.ts) can exclude them — they are generated OUTPUT files, never
24
+ // templates to reconcile. One per cloud host (Claude Code on the web / Cursor
25
+ // Background Agents); both inline resolved secrets, both gitignored + chmod 600.
26
+ export const CLAUDE_CLOUD_RELPATH = path.join(".claude", "bkit-cloud.md");
27
+ export const CURSOR_CLOUD_RELPATH = path.join(".cursor", "bkit-cloud.md");
28
+
29
+ // Session-hijack keys: exporting these into a cloud env redirects Claude Code's
30
+ // OWN model calls onto API-key billing instead of the user's subscription
31
+ // (`.bkit/cloud.md` § Environment variables). Always dropped from the paste block.
32
+ export const SESSION_HIJACK_KEYS = [
33
+ "ANTHROPIC_API_KEY",
34
+ "BKIT_ANTHROPIC_API_KEY",
35
+ "ANTHROPIC_AUTH_TOKEN",
36
+ ] as const;
37
+
38
+ // bkit baseline env-var NAMES every Claude-on-web environment needs. Emitted as a
39
+ // placeholder ONLY when absent from the resolved `.envrc` set — a present value
40
+ // (e.g. BKIT_GH_TOKEN already in `.bkit/.env`) keeps its real resolved value.
41
+ const BASELINE_TOKEN_PLACEHOLDERS: ReadonlyArray<readonly [string, string]> = [
42
+ ["BKIT_GH_TOKEN", "<fine-grained PAT — see .bkit/cloud.md § BKIT_GH_TOKEN permissions>"],
43
+ ];
44
+
45
+ // Earlier-compaction override — a bkit constant, not a secret. Appended to the
46
+ // block when not already resolved from a source file. Claude-harness-only knob —
47
+ // Cursor has no equivalent, so it is NOT in the Cursor policy's constants.
48
+ const AUTOCOMPACT_KEY = "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE";
49
+ const AUTOCOMPACT_VALUE = "70";
50
+
51
+ // Per-cloud env-var policy. The `.envrc`-following resolver core is identical for
52
+ // both clouds (same dotenv sources, same unset/hijack/empty drops) — only the
53
+ // baseline placeholder set and the appended constants differ. Claude pairs with the
54
+ // GitHub tracker and wants the autocompact override; Cursor pairs with Linear (and
55
+ // so also needs `BKIT_LINEAR_API_KEY`) and has no autocompact knob. Keeping one resolver
56
+ // with a small policy object is what guarantees the two generated docs describe the
57
+ // SAME cloud environment — just different mechanics (pasted setup vs. Dockerfile).
58
+ export interface CloudEnvPolicy {
59
+ /** Baseline env-var NAMES this cloud always needs; emitted as `NAME=<placeholder>`
60
+ * when absent from the resolved `.envrc` set. */
61
+ baseline: ReadonlyArray<readonly [string, string]>;
62
+ /** Constant KEY/value pairs appended when not already resolved from a source. */
63
+ constants: ReadonlyArray<readonly [string, string]>;
64
+ }
65
+
66
+ // Claude Code on the web: GitHub tracker, autocompact override.
67
+ export const CLAUDE_CLOUD_POLICY: CloudEnvPolicy = {
68
+ baseline: BASELINE_TOKEN_PLACEHOLDERS,
69
+ constants: [[AUTOCOMPACT_KEY, AUTOCOMPACT_VALUE]],
70
+ };
71
+
72
+ // Cursor Background Agents: `BKIT_LINEAR_API_KEY` prepended for the Linear tracker
73
+ // (bkit-preflight.sh calls the Linear GraphQL API and hard-fails without it); GitHub
74
+ // tracker uses the same GH baseline as Claude, minus the autocompact knob.
75
+ const CURSOR_LINEAR_PLACEHOLDER: readonly [string, string] = [
76
+ "BKIT_LINEAR_API_KEY",
77
+ "<Linear personal API key — https://linear.app/settings/api>",
78
+ ];
79
+ export function cursorCloudPolicy(tracker: IssueTracker): CloudEnvPolicy {
80
+ return {
81
+ baseline:
82
+ tracker === "linear"
83
+ ? [CURSOR_LINEAR_PLACEHOLDER, ...BASELINE_TOKEN_PLACEHOLDERS]
84
+ : BASELINE_TOKEN_PLACEHOLDERS,
85
+ constants: [],
86
+ };
87
+ }
88
+
89
+ export interface CloudEnvResolution {
90
+ /** Resolved KEY/value pairs, non-empty, ordered first-seen with last-source value. */
91
+ included: Array<[string, string]>;
92
+ /** Vars a source file set that `.envrc` then `unset`s (dropped by design). */
93
+ unset: string[];
94
+ /** Session-hijack keys that were present and were dropped. */
95
+ hijackDropped: string[];
96
+ /** Keys whose resolved value was empty (skipped from the paste block). */
97
+ emptySkipped: string[];
98
+ /** Baseline token names absent from sources — emitted as placeholders. */
99
+ placeholders: string[];
100
+ /** `.envrc` dotenv targets that existed and were read (for the Notes line). */
101
+ sources: string[];
102
+ /** Whether an `.envrc` was found at all. */
103
+ hasEnvrc: boolean;
104
+ }
105
+
106
+ /** Strip one layer of matching surrounding single/double quotes. */
107
+ function stripQuotes(v: string): string {
108
+ const t = v.trim();
109
+ if (
110
+ t.length >= 2 &&
111
+ ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'")))
112
+ ) {
113
+ return t.slice(1, -1);
114
+ }
115
+ return t;
116
+ }
117
+
118
+ /**
119
+ * Parse an `.envrc` for the direnv directives bkit follows: `dotenv` /
120
+ * `dotenv_if_exists <file>` targets (in order), `unset <VAR...>` lines, and direct
121
+ * `export KEY=value` assignments. Arbitrary bash (conditionals, PATH_add, etc.) is
122
+ * ignored — bkit never executes the `.envrc`, it reads these declarative lines.
123
+ */
124
+ export function parseEnvrc(content: string): {
125
+ dotenvFiles: string[];
126
+ unsets: string[];
127
+ exports: Array<[string, string]>;
128
+ } {
129
+ const dotenvFiles: string[] = [];
130
+ const unsets: string[] = [];
131
+ const exports: Array<[string, string]> = [];
132
+ for (const raw of content.split("\n")) {
133
+ const line = raw.trim();
134
+ if (line === "" || line.startsWith("#")) continue;
135
+ let m: RegExpMatchArray | null;
136
+ if ((m = line.match(/^dotenv(?:_if_exists)?\s+(.+)$/))) {
137
+ dotenvFiles.push(stripQuotes(m[1]!.trim()));
138
+ } else if ((m = line.match(/^unset\s+(.+)$/))) {
139
+ for (const v of m[1]!.split(/\s+/)) if (v) unsets.push(v);
140
+ } else if ((m = line.match(/^export\s+([A-Za-z_][A-Za-z0-9_]*)=(.*)$/))) {
141
+ exports.push([m[1]!, stripQuotes(m[2]!)]);
142
+ }
143
+ }
144
+ return { dotenvFiles, unsets, exports };
145
+ }
146
+
147
+ /** Parse a dotenv file into ordered KEY/value pairs (values quote-stripped). */
148
+ export function parseDotenv(content: string): Array<[string, string]> {
149
+ const out: Array<[string, string]> = [];
150
+ for (const raw of content.split("\n")) {
151
+ const line = raw.trim();
152
+ if (line === "" || line.startsWith("#")) continue;
153
+ // `(.*)$` keeps `=` characters inside the value intact.
154
+ const m = line.match(/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
155
+ if (!m) continue;
156
+ out.push([m[1]!, stripQuotes(m[2]!)]);
157
+ }
158
+ return out;
159
+ }
160
+
161
+ /**
162
+ * Resolve the cloud env-var set by following the consumer's `.envrc`. Later dotenv
163
+ * sources override earlier (direnv last-wins); direct `export`s win over files.
164
+ * Applies `.envrc` unsets, then drops session-hijack keys. Returns empty when no
165
+ * `.envrc` exists — the caller still emits a usable placeholder doc.
166
+ */
167
+ export function resolveCloudEnvVars(
168
+ cwd: string,
169
+ policy: CloudEnvPolicy = CLAUDE_CLOUD_POLICY,
170
+ ): CloudEnvResolution {
171
+ const res: CloudEnvResolution = {
172
+ included: [],
173
+ unset: [],
174
+ hijackDropped: [],
175
+ emptySkipped: [],
176
+ placeholders: [],
177
+ sources: [],
178
+ hasEnvrc: false,
179
+ };
180
+
181
+ const envrcPath = path.join(cwd, ".envrc");
182
+ let dotenvFiles: string[] = [];
183
+ let unsets: string[] = [];
184
+ let exports: Array<[string, string]> = [];
185
+ if (fs.existsSync(envrcPath)) {
186
+ res.hasEnvrc = true;
187
+ ({ dotenvFiles, unsets, exports } = parseEnvrc(fs.readFileSync(envrcPath, "utf-8")));
188
+ }
189
+
190
+ // Accumulate. A Map preserves first-seen insertion order; re-setting an existing
191
+ // key updates its value in place, giving "first-seen order, last-source value".
192
+ const map = new Map<string, string>();
193
+ for (const rel of dotenvFiles) {
194
+ const p = path.join(cwd, rel);
195
+ if (!fs.existsSync(p)) continue;
196
+ res.sources.push(rel);
197
+ for (const [k, v] of parseDotenv(fs.readFileSync(p, "utf-8"))) map.set(k, v);
198
+ }
199
+ for (const [k, v] of exports) map.set(k, v);
200
+
201
+ // Honour `.envrc` unsets (record only those a source actually set).
202
+ for (const k of unsets) {
203
+ if (map.has(k)) {
204
+ res.unset.push(k);
205
+ map.delete(k);
206
+ }
207
+ }
208
+
209
+ // Drop session-hijack keys.
210
+ for (const k of SESSION_HIJACK_KEYS) {
211
+ if (map.has(k)) {
212
+ res.hijackDropped.push(k);
213
+ map.delete(k);
214
+ }
215
+ }
216
+
217
+ // Partition non-empty (included) vs empty (skipped).
218
+ for (const [k, v] of map) {
219
+ if (v === "") res.emptySkipped.push(k);
220
+ else res.included.push([k, v]);
221
+ }
222
+
223
+ // Baseline names absent from the resolved set → emitted as placeholders.
224
+ const present = new Set(res.included.map(([k]) => k));
225
+ for (const [name] of policy.baseline) {
226
+ if (!present.has(name)) res.placeholders.push(name);
227
+ }
228
+
229
+ return res;
230
+ }
231
+
232
+ /**
233
+ * Render the `.env`-format paste block: resolved KEY=value lines, then placeholder
234
+ * lines for any absent baseline token, then the autocompact override if unset.
235
+ */
236
+ export function renderCloudEnvBlock(
237
+ res: CloudEnvResolution,
238
+ policy: CloudEnvPolicy = CLAUDE_CLOUD_POLICY,
239
+ ): string {
240
+ const lines: string[] = [];
241
+ for (const [k, v] of res.included) lines.push(`${k}=${v}`);
242
+ for (const [name, placeholder] of policy.baseline) {
243
+ if (res.placeholders.includes(name)) lines.push(`${name}=${placeholder}`);
244
+ }
245
+ for (const [key, value] of policy.constants) {
246
+ if (!res.included.some(([k]) => k === key)) lines.push(`${key}=${value}`);
247
+ }
248
+ return lines.join("\n");
249
+ }
250
+
251
+ function fmtList(items: string[]): string {
252
+ return items.map((x) => `\`${x}\``).join(", ");
253
+ }
254
+
255
+ /** Render the markdown notes under the env-var block (transparency for what was dropped). */
256
+ export function renderCloudEnvNotes(res: CloudEnvResolution): string {
257
+ if (!res.hasEnvrc) {
258
+ return (
259
+ "_No `.envrc` found — the block above lists only the bkit baseline token names as " +
260
+ "placeholders. Add your `.envrc` (`bkit install` seeds one) and re-run to inline real values._"
261
+ );
262
+ }
263
+ const bullets: string[] = [];
264
+ if (res.placeholders.length) {
265
+ bullets.push(
266
+ `- **Fill in (absent from your env files):** ${fmtList(res.placeholders)} — placeholder values above.`,
267
+ );
268
+ }
269
+ if (res.unset.length) {
270
+ bullets.push(
271
+ `- **Dropped — \`.envrc\` unsets these:** ${fmtList(res.unset)} — kept out of the cloud env by design.`,
272
+ );
273
+ }
274
+ if (res.hijackDropped.length) {
275
+ bullets.push(
276
+ `- **Dropped — session-billing hijack:** ${fmtList(res.hijackDropped)} — would redirect the agent's own model calls onto API-key billing instead of your subscription.`,
277
+ );
278
+ }
279
+ if (res.emptySkipped.length) {
280
+ bullets.push(`- **Empty in source (skipped):** ${fmtList(res.emptySkipped)}`);
281
+ }
282
+ const header = `_${res.included.length} var${res.included.length === 1 ? "" : "s"} resolved${
283
+ res.sources.length ? ` from ${fmtList(res.sources)}` : ""
284
+ }._`;
285
+ return bullets.length ? `${header}\n\n${bullets.join("\n")}` : header;
286
+ }
287
+
288
+ /** Parse the pnpm `X.Y.Z` from `package.json` `packageManager` ("" if absent/non-pnpm). */
289
+ export function resolveConsumerPnpm(cwd: string): string {
290
+ try {
291
+ const pkg = JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf-8")) as Record<
292
+ string,
293
+ unknown
294
+ >;
295
+ const pm = typeof pkg["packageManager"] === "string" ? (pkg["packageManager"] as string) : "";
296
+ const m = pm.match(/^pnpm@(\d+\.\d+\.\d+)/);
297
+ return m?.[1] ?? "";
298
+ } catch {
299
+ return "";
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Render the setup-script corepack line from the consumer's own `packageManager`
305
+ * pin (NOT bkit's — the pin is a snapshot pre-warm, non-load-bearing: corepack
306
+ * resolves each repo's `packageManager` in-repo). Degrades to bare `corepack
307
+ * enable` when the pin is absent.
308
+ */
309
+ export function renderCorepackLine(cwd: string): string {
310
+ const v = resolveConsumerPnpm(cwd);
311
+ return v
312
+ ? `corepack enable && corepack prepare pnpm@${v} --activate`
313
+ : `corepack enable # pnpm resolved from package.json "packageManager" in-repo`;
314
+ }
315
+
316
+ /**
317
+ * Extract the bash body of every `context-fetch:provision <name>` block the consumer
318
+ * enabled below `<!-- bkit:end -->` in `.agents/context.md`. Stack-agnostic: bkit
319
+ * hardcodes no CLI names — the install recipe lives in the consumer's context.md,
320
+ * co-located with the fetch block that needs the CLI. `bkit context list-blocks` returns
321
+ * the same list as `provision`, which `.claude/hooks/bkit-cloud-bootstrap.sh` runs, so the web
322
+ * setup-script snapshot and the per-session hook provision the same CLIs. Returns one
323
+ * string per block (bash body).
324
+ */
325
+ export function extractContextFetchProvisionRecipes(cwd: string): string[] {
326
+ const filePath = path.join(cwd, ".agents", "context.md");
327
+ if (!fs.existsSync(filePath)) return [];
328
+ const content = fs.readFileSync(filePath, "utf-8");
329
+ const endIdx = content.search(/^<!-- bkit:end -->$/m);
330
+ if (endIdx === -1) return [];
331
+ const consumer = content.slice(endIdx);
332
+ const recipes: string[] = [];
333
+ let cur: string[] | null = null;
334
+ let inProv = false;
335
+ let inFence = false;
336
+ for (const line of consumer.split("\n")) {
337
+ if (/^<!-- context-fetch:provision/.test(line)) {
338
+ inProv = true;
339
+ inFence = false;
340
+ cur = [];
341
+ continue;
342
+ }
343
+ if (/^<!-- context-fetch:(start|end|none)/.test(line)) {
344
+ if (inProv && cur && cur.length > 0) recipes.push(cur.join("\n"));
345
+ inProv = false;
346
+ inFence = false;
347
+ cur = null;
348
+ continue;
349
+ }
350
+ if (inProv && /^```/.test(line)) {
351
+ inFence = !inFence;
352
+ continue;
353
+ }
354
+ if (inProv && inFence && cur) cur.push(line);
355
+ }
356
+ return recipes;
357
+ }
358
+
359
+ /**
360
+ * Render the `@@CLOUD_CACHE_BUST@@` line — a `# cache-bust YYYY-MM-DD-N` comment at
361
+ * the top of the setup script. claude.ai/code snapshots the setup script keyed on its
362
+ * exact text and reuses that snapshot; a changing cache-bust line forces a fresh
363
+ * snapshot on the next paste, so "latest"-resolved downloads (gh, gcloud SDK) and
364
+ * base-image drift get re-pulled even when the rest of the script is byte-identical.
365
+ * The counter increments per regeneration WITHIN a day (read back from the prior doc)
366
+ * and resets to 1 on a new date, so every regeneration yields a distinct value —
367
+ * guaranteeing a re-paste always busts. `today` (YYYY-MM-DD) is injected so the caller
368
+ * owns the clock and this stays deterministic under test.
369
+ */
370
+ export function renderCloudCacheBust(cwd: string, today: string): string {
371
+ const dst = path.join(cwd, CLAUDE_CLOUD_RELPATH);
372
+ let counter = 1;
373
+ if (fs.existsSync(dst)) {
374
+ const prev = fs.readFileSync(dst, "utf-8");
375
+ const m = prev.match(/^# cache-bust (\d{4}-\d{2}-\d{2})-(\d+)$/m);
376
+ if (m && m[1] === today) counter = Number.parseInt(m[2], 10) + 1;
377
+ }
378
+ return `# cache-bust ${today}-${counter}`;
379
+ }
380
+
381
+ /**
382
+ * `pnpm add -g` aborts ("The configured global bin directory … is not in PATH")
383
+ * unless pnpm's global-bin dir is on PATH. corepack-activated pnpm never runs
384
+ * `pnpm setup`, so under the setup script's `set -euo pipefail` a single `pnpm add
385
+ * -g <cli>` provision block kills the whole snapshot build (observed in cloud with
386
+ * `pnpm@11`). Prepend an explicit `PNPM_HOME` + PATH export so every provision
387
+ * recipe runs in a shell where `pnpm add -g` succeeds. `$PNPM_HOME` and
388
+ * `$PNPM_HOME/bin` are both added — pnpm's global-bin dir has differed by version.
389
+ */
390
+ const CLOUD_PNPM_GLOBAL_PATH_SETUP =
391
+ "# pnpm refuses `add -g` unless its global-bin dir is on PATH (corepack pnpm skips `pnpm setup`).\n" +
392
+ 'export PNPM_HOME="${PNPM_HOME:-$HOME/.local/share/pnpm}"\n' +
393
+ 'export PATH="$PNPM_HOME:$PNPM_HOME/bin:$PATH"';
394
+
395
+ /**
396
+ * Render the `@@CLOUD_CONTEXT_FETCH_PROVISION@@` setup-script region: the consumer's
397
+ * `context-fetch:provision` recipes, or "" when none are enabled. Placed AFTER the
398
+ * corepack line in the template so `pnpm add -g …` recipes have pnpm available.
399
+ *
400
+ * Recipes run in a best-effort `( set +e … ) || …` subshell: the setup script is
401
+ * `set -euo pipefail`, so without this a single failing recipe (e.g. a heavy `curl |
402
+ * bash` CLI installer that trips over a missing base-image dep) aborts the whole
403
+ * snapshot build and discards every CLI provisioned before it. `set +e` also lets a
404
+ * later recipe run after an earlier one fails. Mirrors the non-blocking per-session
405
+ * hook (`… | bash || log`), keeping the two cloud provision paths behaviourally equal.
406
+ */
407
+ export function renderCloudContextFetchProvision(cwd: string): string {
408
+ const recipes = extractContextFetchProvisionRecipes(cwd);
409
+ if (recipes.length === 0) return "";
410
+ return (
411
+ "# context-fetch CLIs (from .agents/context.md provision blocks) — self-guarded, best-effort.\n" +
412
+ CLOUD_PNPM_GLOBAL_PATH_SETUP +
413
+ "\n" +
414
+ "(\n" +
415
+ " set +e\n" +
416
+ recipes.join("\n") +
417
+ "\n" +
418
+ ') || echo "[cloud-setup] a context-fetch provision recipe failed (non-blocking); its CLI will be absent" >&2'
419
+ );
420
+ }
421
+
422
+ /**
423
+ * Entries of every `<!-- {tag}:start --> … <!-- {tag}:end -->` list block BELOW
424
+ * `<!-- bkit:end -->` in `.agents/context.md` — one entry per line; blank, `#` comment
425
+ * and marker lines ignored. Blocks above the marker are never read. Returns entries
426
+ * verbatim, in order.
427
+ */
428
+ function extractConsumerListBlock(cwd: string, tag: string): string[] {
429
+ const filePath = path.join(cwd, ".agents", "context.md");
430
+ if (!fs.existsSync(filePath)) return [];
431
+ const content = fs.readFileSync(filePath, "utf-8");
432
+ const endIdx = content.search(/^<!-- bkit:end -->$/m);
433
+ if (endIdx === -1) return [];
434
+ const consumer = content.slice(endIdx);
435
+ const entries: string[] = [];
436
+ let inBlock = false;
437
+ for (const line of consumer.split("\n")) {
438
+ if (line.startsWith(`<!-- ${tag}:start`)) {
439
+ inBlock = true;
440
+ continue;
441
+ }
442
+ if (line.startsWith(`<!-- ${tag}:end`) || line.startsWith(`<!-- ${tag}:none`)) {
443
+ inBlock = false;
444
+ continue;
445
+ }
446
+ if (!inBlock) continue;
447
+ const t = line.trim();
448
+ if (!t || t.startsWith("#") || t.startsWith("<!--")) continue;
449
+ entries.push(t);
450
+ }
451
+ return entries;
452
+ }
453
+
454
+ /**
455
+ * Cloud network-allowlist domains the consumer declared in `allowed-domains` blocks
456
+ * (one registrable domain per line). Stack-agnostic: bkit hardcodes no domains — the
457
+ * consumer declares which log-backend / API / app hosts their cloud sessions must
458
+ * reach. Returns declared entries verbatim (pre-expansion), in order.
459
+ */
460
+ export function extractAllowedDomains(cwd: string): string[] {
461
+ return extractConsumerListBlock(cwd, "allowed-domains");
462
+ }
463
+
464
+ /**
465
+ * MCP server names the consumer declared in `mcp-servers` blocks (one per line,
466
+ * spelled exactly as each host names the server in its tool ids). Every tool on a
467
+ * listed server is pre-approved on every host — see `.bkit/providers.md` § MCP
468
+ * servers. Deduplicated, declaration order kept.
469
+ */
470
+ export function extractMcpServers(cwd: string): string[] {
471
+ return [...new Set(extractConsumerListBlock(cwd, "mcp-servers"))];
472
+ }
473
+
474
+ /**
475
+ * Expand each declared registrable domain to BOTH the apex and a `*.` wildcard so the
476
+ * WHOLE domain is allowlisted — the egress proxy matches apex and subdomains
477
+ * separately, so `inngest.com` alone misses `api.inngest.com` and vice-versa. A
478
+ * consumer entry already written as `*.x` is normalised to its apex `x` first, then
479
+ * both forms are emitted. Grouped apex-then-wildcard per domain, domains sorted.
480
+ */
481
+ export function expandAllowedDomains(declared: string[]): string[] {
482
+ const bases = [
483
+ ...new Set(declared.map((d) => d.replace(/^\*\./, "").trim()).filter(Boolean)),
484
+ ].sort();
485
+ return bases.flatMap((b) => [b, `*.${b}`]);
486
+ }
487
+
488
+ /** True for a bracketed IPv6 literal or a dotted-quad IPv4 literal. */
489
+ export function isIpLiteral(host: string): boolean {
490
+ return host.startsWith("[") || /^\d{1,3}(\.\d{1,3}){3}$/.test(host);
491
+ }
492
+
493
+ /**
494
+ * Propose the registrable base for a provider `baseURL`, or `""` when the URL
495
+ * contributes no allowlistable host. `URL.canParse` gates the parse, so this never
496
+ * throws and carries no `try` / `catch`; an unparseable value contributes nothing.
497
+ *
498
+ * Contributes nothing for an empty host, `localhost` and its subdomains, an IP
499
+ * literal, and any host of fewer than two labels: none of those is reachable through
500
+ * a cloud egress allowlist. Everything else collapses to its last two labels.
501
+ *
502
+ * The collapse is the naive last-two-labels rule. Multi-label public suffixes and
503
+ * shared-tenant apexes are a DENY at authoring time in the registry gate test, never a
504
+ * base rewrite here.
505
+ */
506
+ export function proposeEgressBase(baseURL: string): string {
507
+ if (!URL.canParse(baseURL)) return "";
508
+ const host = new URL(baseURL).hostname;
509
+ if (host === "" || isIpLiteral(host)) return "";
510
+ if (host === "localhost" || host.endsWith(".localhost")) return "";
511
+ const labels = host.split(".");
512
+ if (labels.length < 2) return "";
513
+ return labels.slice(-2).join(".");
514
+ }
515
+
516
+ /**
517
+ * Sorted-unique `hosts` and `bases` across a set of egress sources. Pure: takes the
518
+ * rows rather than reading {@link BKIT_EGRESS_SOURCES}, so a test can inject a fixture
519
+ * set without mocking the module.
520
+ */
521
+ export function deriveEgressEntries(rows: readonly EgressSource[]): {
522
+ hosts: string[];
523
+ bases: string[];
524
+ } {
525
+ return {
526
+ hosts: [...new Set(rows.flatMap((r) => r.hosts))].sort(),
527
+ bases: [...new Set(rows.flatMap((r) => r.bases))].sort(),
528
+ };
529
+ }
530
+
531
+ /**
532
+ * Stack-agnostic tooling bases, derived from {@link BKIT_EGRESS_SOURCES} rather than
533
+ * hand-typed — adding a provider, tracker or shipped tooling host updates this export
534
+ * by editing one registry row. **Never** ship observability / app stacks here (Vercel,
535
+ * Supabase, Sentry, …) — those come solely from the consumer's `.agents/context.md`
536
+ * `allowed-domains` block (after `<!-- bkit:end -->`) via {@link resolveNetworkAllowlist}.
537
+ */
538
+ export const BKIT_SHIPPED_NETWORK_DOMAINS: readonly string[] =
539
+ deriveEgressEntries(BKIT_EGRESS_SOURCES).bases;
540
+
541
+ /**
542
+ * The exact hostnames behind {@link BKIT_SHIPPED_NETWORK_DOMAINS}. Consumers of the
543
+ * base list allowlist a whole domain; this is the narrower set, for surfaces that
544
+ * match a literal host.
545
+ */
546
+ export const BKIT_SHIPPED_NETWORK_HOSTS: readonly string[] =
547
+ deriveEgressEntries(BKIT_EGRESS_SOURCES).hosts;
548
+
549
+ /**
550
+ * Apex-only unique bases from an expanded (apex + `*.`) domain list.
551
+ *
552
+ * Single call site (injectOpencodeDerivedAllows in install/modules/index.ts). Same apex-collapse
553
+ * shape as expandAllowedDomains above.
554
+ */
555
+ export function networkAllowlistBases(expanded: string[]): string[] {
556
+ return [...new Set(expanded.map((d) => d.replace(/^\*\./, "").trim()).filter(Boolean))].sort();
557
+ }
558
+
559
+ /**
560
+ * Local + cloud network allowlist: stack-agnostic tooling defaults ∪ consumer
561
+ * `allowed-domains` from `.agents/context.md` (after `<!-- bkit:end -->`), each as
562
+ * apex + `*.` wildcard. Empty consumer block ⇒ tooling hosts only — no Vercel/etc.
563
+ */
564
+ export function resolveNetworkAllowlist(cwd: string): string[] {
565
+ return expandAllowedDomains([...BKIT_SHIPPED_NETWORK_DOMAINS, ...extractAllowedDomains(cwd)]);
566
+ }
567
+
568
+ /**
569
+ * Every `permissions.allow` row bkit derives into `.claude/settings.json`: one
570
+ * `WebFetch(domain:…)` per {@link resolveNetworkAllowlist} entry, then two MCP rows per
571
+ * {@link extractMcpServers} entry — `mcp__<s>__*` (`.mcp.json` servers, and claude.ai
572
+ * connectors in cloud sessions) and `mcp__claude_ai_<s>__*` (claude.ai connectors in
573
+ * the local CLI). Single source for install / upgrade enrichment and uninstall strip.
574
+ */
575
+ export function resolveClaudeDerivedAllows(cwd: string): string[] {
576
+ return [
577
+ ...resolveNetworkAllowlist(cwd).map((d) => `WebFetch(domain:${d})`),
578
+ ...extractMcpServers(cwd).flatMap((s) => [`mcp__${s}__*`, `mcp__claude_ai_${s}__*`]),
579
+ ];
580
+ }
581
+
582
+ /** Cursor-relative path of the install-written curl/wget allowlist (guardrails). */
583
+ export const NETWORK_ALLOWLIST_RELPATH = path.join(".cursor", "allowlist.json");
584
+
585
+ /**
586
+ * Write `.cursor/allowlist.json` for Cursor `bkit-guardrails.cjs` (runtime curl/wget host
587
+ * checks). Claude/OpenCode bake the same domain set into their own configs at
588
+ * install/upgrade — they do not read this file. Call only when the cursor module
589
+ * is installed (do not create `.cursor/` for claude-only consumers).
590
+ */
591
+ export function writeNetworkAllowlistArtifact(
592
+ cwd: string,
593
+ dryRun: boolean,
594
+ ): { path: string; domains: string[]; wrote: boolean } {
595
+ const domains = resolveNetworkAllowlist(cwd);
596
+ const rel = NETWORK_ALLOWLIST_RELPATH;
597
+ return { path: rel, domains, wrote: writeGeneratedJson(cwd, rel, { domains }, dryRun) };
598
+ }
599
+
600
+ /** Cursor-relative path of the install-written Cursor CLI permissions (MCP allows). */
601
+ export const CURSOR_CLI_PERMISSIONS_RELPATH = path.join(".cursor", "cli.json");
602
+
603
+ /**
604
+ * Write `.cursor/cli.json` — the project-level Cursor CLI / cloud-agent permissions —
605
+ * with one `Mcp(<server>:*)` allow per {@link extractMcpServers} entry. bkit-owned and
606
+ * regenerated whole, like `.cursor/allowlist.json`: hand edits do not survive, the
607
+ * `mcp-servers` block is the source. Call only when the cursor module is installed.
608
+ */
609
+ export function writeCursorCliPermissionsArtifact(
610
+ cwd: string,
611
+ dryRun: boolean,
612
+ ): { path: string; wrote: boolean } {
613
+ const allow = extractMcpServers(cwd).map((s) => `Mcp(${s}:*)`);
614
+ const rel = CURSOR_CLI_PERMISSIONS_RELPATH;
615
+ const doc = { permissions: { allow, deny: [] } };
616
+ return { path: rel, wrote: writeGeneratedJson(cwd, rel, doc, dryRun) };
617
+ }
618
+
619
+ /**
620
+ * Write a whole-file generated JSON artifact. Returns whether the on-disk bytes differ
621
+ * from the rendered body — under `dryRun` that is computed without writing, so dry
622
+ * and real runs report the identical write set (the `bkit check` drift signal).
623
+ */
624
+ function writeGeneratedJson(cwd: string, rel: string, doc: unknown, dryRun: boolean): boolean {
625
+ const abs = path.join(cwd, rel);
626
+ const body = JSON.stringify(doc, null, 2) + "\n";
627
+ const prev = fs.existsSync(abs) ? fs.readFileSync(abs, "utf-8") : null;
628
+ if (prev === body) return false;
629
+ if (!dryRun) {
630
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
631
+ fs.writeFileSync(abs, body, "utf-8");
632
+ }
633
+ return true;
634
+ }
635
+
636
+ /**
637
+ * 8-hex fingerprint of the DERIVED egress set only — bases and hosts, sorted, never
638
+ * the consumer union. Hosts are included (the Cursor paste is hosts-only). Editing
639
+ * `allowed-domains` never moves it; editing a registry row does.
640
+ */
641
+ export function egressFingerprint(): string {
642
+ const derived = [
643
+ ...new Set([...BKIT_SHIPPED_NETWORK_DOMAINS, ...BKIT_SHIPPED_NETWORK_HOSTS]),
644
+ ].sort();
645
+ return sha256(derived.join("\n")).slice(0, 8);
646
+ }
647
+
648
+ /**
649
+ * Render the `@@CLOUD_NETWORK_ALLOWLIST@@` region — the whole `## Network access`
650
+ * body. Always emits a **Custom** paste block: the list is the derived shipped bases
651
+ * union whatever the consumer declared, so it is never empty and there is no
652
+ * zero-declaration branch. Declaring nothing narrows the list, it does not change the
653
+ * instruction.
654
+ */
655
+ export function renderCloudNetworkAllowlist(cwd: string): string {
656
+ const declared = extractAllowedDomains(cwd);
657
+ const domains = resolveNetworkAllowlist(cwd);
658
+ const derivedCount = BKIT_SHIPPED_NETWORK_DOMAINS.length;
659
+ const declaredNote =
660
+ declared.length === 0
661
+ ? "\n\n_No `allowed-domains` block is declared in `.agents/context.md`. The list above is\n" +
662
+ "bkit's own shipped hosts. If you run cloud `/bkit-debug` or e2e against a deployment,\n" +
663
+ "declare your log-backend + app domains there (apex per line) and they join this list._"
664
+ : "";
665
+ return (
666
+ "Set to **Custom** and tick **Also include default list of common package\n" +
667
+ "managers** — this EXTENDS the trusted defaults (package registries, GitHub,\n" +
668
+ "cloud SDKs), it does not replace them. Paste into the **Allowed domains** field\n" +
669
+ "(one per line):\n\n" +
670
+ "```text\n" +
671
+ domains.join("\n") +
672
+ "\n```\n\n" +
673
+ `_${domains.length} entries — ${derivedCount} derived from bkit's shipped egress registry ` +
674
+ `and ${declared.length} declared in \`allowed-domains\` in \`.agents/context.md\`, ` +
675
+ "each as apex + `*.` wildcard. Derived set fingerprint `" +
676
+ egressFingerprint() +
677
+ "`._" +
678
+ declaredNote +
679
+ "\n\nUnder **Trusted**, your app domains and most observability / API hosts are\n" +
680
+ "unreachable, so cloud `/bkit-debug` gets no runtime logs and e2e can't hit your\n" +
681
+ "deployment. **Full** works too but opens all egress."
682
+ );
683
+ }
684
+
685
+ /**
686
+ * Parent directory Claude Code on the web clones a repo into.
687
+ *
688
+ * Observed on the current image (`/home/user/<repo-name>`, agent running as uid=0
689
+ * with `HOME=/root`) and NOT a documented contract: no environment variable in the
690
+ * container names the repo root. The setup script bakes the resolved path and
691
+ * `bkit-cloud-bootstrap.sh` checks the DISCOVERED one, warning loudly on mismatch.
692
+ */
693
+ const CLOUD_REPO_PARENT = "/home/user";
694
+
695
+ /** The path {@link renderCloudWorkspaceTrust} bakes into the setup script. */
696
+ export function cloudRepoPath(cwd: string): string {
697
+ return `${CLOUD_REPO_PARENT}/${path.basename(path.resolve(cwd))}`;
698
+ }
699
+
700
+ /**
701
+ * Render the `@@CLOUD_WORKSPACE_TRUST@@` setup-script region — the workspace-trust flip.
702
+ *
703
+ * `permissions.allow` and `permissions.additionalDirectories` in a project's
704
+ * `.claude/settings.json` GRANT capability, so Claude Code applies them only once the
705
+ * workspace trust dialog has been accepted — and it never shows that dialog in a
706
+ * `claude -p` or SDK session. (`deny` and `ask` are unaffected; they only restrict.)
707
+ *
708
+ * Runs in the setup script: as root, before the clone, before Claude Code starts, with
709
+ * its filesystem snapshotted. Settings resolve before SessionStart, and `.claude/` is a
710
+ * protected path allow rules never pre-approve.
711
+ *
712
+ * Merges into the file (it may or may not exist at snapshot time, and Claude Code
713
+ * stores its own state alongside the key on first run).
714
+ */
715
+ export function renderCloudWorkspaceTrust(cwd: string): string {
716
+ const repoPath = cloudRepoPath(cwd);
717
+ return (
718
+ "# Workspace trust. Without this Claude Code IGNORES every permissions.allow row in\n" +
719
+ "# .claude/settings.json — it only applies them once the trust dialog is accepted, and\n" +
720
+ "# cloud sessions never show that dialog. deny/ask are unaffected. Nothing inside the\n" +
721
+ "# session can set this: settings resolve before SessionStart, and .claude/ is a\n" +
722
+ "# protected path that allow rules never pre-approve.\n" +
723
+ 'CLAUDE_JSON="${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json"\n' +
724
+ 'mkdir -p "$(dirname "$CLAUDE_JSON")"\n' +
725
+ '[ -f "$CLAUDE_JSON" ] || printf \'{}\' > "$CLAUDE_JSON"\n' +
726
+ `jq --arg p '${repoPath}' '.projects[$p].hasTrustDialogAccepted = true' \\\n` +
727
+ ' "$CLAUDE_JSON" > "$CLAUDE_JSON.tmp" && mv "$CLAUDE_JSON.tmp" "$CLAUDE_JSON"'
728
+ );
729
+ }
730
+
731
+ /**
732
+ * Environment entries seeded into `~/.claude/settings.json` by {@link renderCloudUserSettings}.
733
+ *
734
+ * `"$defaults"` is NOT optional: omitting it replaces the entire built-in list for that
735
+ * section, which for `environment` discards every built-in trust slot (including
736
+ * "Trusted repo"). It is always emitted first, and asserted in the tests.
737
+ *
738
+ * Unconfigured, the classifier trusts only the working repo and its configured remotes,
739
+ * and `Host containment` defaults to "an ordinary developer machine or CI runner with
740
+ * open internet". These entries name the context-fetch hosts, the egress-allowlisted
741
+ * sandbox, and the session's identity.
742
+ */
743
+ export function cloudAutoModeEnvironment(cwd: string): string[] {
744
+ const entries = [
745
+ "$defaults",
746
+ "Host containment: Claude Code runs inside the Claude Code on the web sandbox — a " +
747
+ "single-tenant container with no neighbouring workloads to reach, and egress " +
748
+ "restricted to the allowed-domains list configured on that environment. The cloud " +
749
+ "metadata endpoint is not used and should stay unreachable. The only credentials " +
750
+ "in the session are the environment variables set in the Claude app, so nothing " +
751
+ "should ever request credentials belonging to the host itself.",
752
+ ];
753
+ const bases = networkAllowlistBases(resolveNetworkAllowlist(cwd));
754
+ if (bases.length > 0) {
755
+ entries.push(
756
+ `Trusted internal domains: ${bases.join(", ")} — all on the egress allowlist for ` +
757
+ "this environment, rendered from declarations in this repository, and the hosts " +
758
+ "context-fetch blocks read logs and diagnostics from during /bkit-debug.",
759
+ );
760
+ }
761
+ // Apostrophes would terminate the single-quoted `--argjson` literal in the generated
762
+ // setup script; keep the seeded prose free of them (asserted in the tests).
763
+ return entries;
764
+ }
765
+
766
+ /**
767
+ * Render the `@@CLOUD_USER_SETTINGS@@` setup-script region — the auto-mode classifier config.
768
+ *
769
+ * Written host-side: the classifier does NOT read `autoMode` from `.claude/settings.json`
770
+ * or `.claude/settings.local.json`.
771
+ *
772
+ * Seeds with `//=`, not `=`: a consumer's own `autoMode.environment` is never stomped by a
773
+ * re-pasted setup script, and later bkit changes to the seeded entries do not reach a
774
+ * container that already has them.
775
+ */
776
+ export function renderCloudUserSettings(cwd: string): string {
777
+ const env = JSON.stringify(cloudAutoModeEnvironment(cwd));
778
+ return (
779
+ "# Auto-mode classifier config. The classifier does NOT read `autoMode` from\n" +
780
+ "# .claude/settings.json or .claude/settings.local.json — deliberately, so a checked-in\n" +
781
+ "# repo cannot inject its own classifier rules — so this cannot be shipped in the repo.\n" +
782
+ "# Seeded with //= so a consumer's existing entries are never overwritten.\n" +
783
+ 'CLAUDE_SETTINGS="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/settings.json"\n' +
784
+ 'mkdir -p "$(dirname "$CLAUDE_SETTINGS")"\n' +
785
+ '[ -f "$CLAUDE_SETTINGS" ] || printf \'{}\' > "$CLAUDE_SETTINGS"\n' +
786
+ `jq --argjson e '${env}' '.autoMode.environment //= $e' \\\n` +
787
+ ' "$CLAUDE_SETTINGS" > "$CLAUDE_SETTINGS.tmp" && mv "$CLAUDE_SETTINGS.tmp" "$CLAUDE_SETTINGS"'
788
+ );
789
+ }
790
+
791
+ /**
792
+ * Generate `.claude/bkit-cloud.md` — a copy-paste-ready Claude Code on the web setup doc
793
+ * with the env-var block resolved to REAL VALUES from the consumer's `.envrc`.
794
+ *
795
+ * The file is gitignored + chmod 600 and holds live secrets: it is UNTRACKED (not
796
+ * pushed to any WriteSet / manifest / canonicalHashes) so it never enters `bkit
797
+ * check` drift or the upgrade template walk — its values are machine-local and
798
+ * expected to differ. Shared by install (runClaudeModule) and upgrade so a rotated
799
+ * secret or version bump reaches the doc either way. Callers MUST guard on
800
+ * `!dryRun` (never write secrets during `bkit check` / `--dry-run`) and on the
801
+ * claude host being installed. Returns true when a file was written (false when the
802
+ * template is absent). Never logs the resolved values.
803
+ */
804
+ export function writeClaudeCloudDoc(cwd: string, tokens: TokenMap): boolean {
805
+ const src = path.join(getSharedRoot(), ".claude", "bkit-cloud.md");
806
+ if (!fs.existsSync(src)) return false;
807
+ const res = resolveCloudEnvVars(cwd);
808
+ // UTC day drives the cache-bust; renderCloudCacheBust reads the PRIOR dst below to
809
+ // continue the per-day counter, before dst is overwritten.
810
+ const today = new Date().toISOString().slice(0, 10);
811
+ // Function-form replacers: resolved secret values may contain `$`, which a string
812
+ // replacement would interpret ($&, $1, …).
813
+ const content = applyTokens(fs.readFileSync(src, "utf-8"), tokens)
814
+ .replace(/@@CLOUD_CACHE_BUST@@/g, () => renderCloudCacheBust(cwd, today))
815
+ .replace(/@@CLOUD_NETWORK_ALLOWLIST@@/g, () => renderCloudNetworkAllowlist(cwd))
816
+ .replace(/@@CLOUD_WORKSPACE_TRUST@@/g, () => renderCloudWorkspaceTrust(cwd))
817
+ .replace(/@@CLOUD_USER_SETTINGS@@/g, () => renderCloudUserSettings(cwd))
818
+ .replace(/@@CLOUD_COREPACK@@/g, () => renderCorepackLine(cwd))
819
+ .replace(/@@CLOUD_CONTEXT_FETCH_PROVISION@@/g, () => renderCloudContextFetchProvision(cwd))
820
+ .replace(/@@CLOUD_ENV_VARS@@/g, () => renderCloudEnvBlock(res))
821
+ .replace(/@@CLOUD_ENV_NOTES@@/g, () => renderCloudEnvNotes(res));
822
+ const dst = path.join(cwd, CLAUDE_CLOUD_RELPATH);
823
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
824
+ fs.writeFileSync(dst, content, "utf-8");
825
+ fs.chmodSync(dst, 0o600);
826
+ return true;
827
+ }
828
+
829
+ /**
830
+ * Render the `@@CURSOR_CONTEXT_FETCH@@` region of `.cursor/bkit-cloud.md`: the consumer's
831
+ * `context-fetch:provision` recipes formatted for the Cursor mechanic, or "" when none
832
+ * are enabled. On Claude these CLIs are baked into the pasted setup script (see
833
+ * renderCloudContextFetchProvision); Cursor has no setup script, so — to keep the two
834
+ * cloud environments aligned — the same recipes are surfaced as a copy-paste block for
835
+ * the per-snapshot `install` command in `.cursor/environment.json`. The recipes are
836
+ * already idempotent (`command -v X || pnpm add -g X`), so they are safe to re-run on
837
+ * every snapshot build. Reuses the SAME extractor as the Claude path so the two clouds
838
+ * never diverge on which CLIs they provision.
839
+ */
840
+ export function renderCursorContextFetchProvision(cwd: string): string {
841
+ const recipes = extractContextFetchProvisionRecipes(cwd);
842
+ // Empty → "" and the template's sentinel line collapses to a single blank between
843
+ // sections; non-empty → a self-contained section with its own leading/trailing blank.
844
+ if (recipes.length === 0) return "";
845
+ return (
846
+ "\n## Context-fetch CLIs (parity with the Claude setup script)\n\n" +
847
+ "Your `.agents/context.md` declares these context-fetch CLIs. The Claude setup script\n" +
848
+ "bakes them into its snapshot; for the SAME tools on Cursor, chain them into the\n" +
849
+ "`install` command in `.cursor/environment.json` (idempotent — safe every rebuild):\n\n" +
850
+ "```bash\n" +
851
+ recipes.join("\n") +
852
+ "\n```\n"
853
+ );
854
+ }
855
+
856
+ /**
857
+ * Render the `@@CURSOR_NETWORK@@` region — Cursor Cloud Agents DO have an egress
858
+ * allowlist (dashboard → Security: "Allow all" / "Default + allowlist" / "Allowlist
859
+ * only"), unlike the earlier assumption. Reuses the SAME declared `allowed-domains`
860
+ * as the Claude side, but — critically — does NOT apply Claude's apex+`*.`
861
+ * expansion: Cursor's own docs warn that a broad wildcard (`*.s3….amazonaws.com`)
862
+ * opens egress far wider than intended, so the declared apex entries are emitted
863
+ * verbatim with a note to add only the specific subdomains you need.
864
+ */
865
+ export function renderCursorNetworkAllowlist(cwd: string): string {
866
+ const declared = extractAllowedDomains(cwd);
867
+ // Exact hosts, never apex + `*.`: Cursor's own docs warn a broad wildcard opens
868
+ // egress far wider than intended, so the shipped set contributes its HOSTS here
869
+ // while the Claude side takes the wildcard-expanded bases.
870
+ const entries = [...new Set([...BKIT_SHIPPED_NETWORK_HOSTS, ...declared])].sort();
871
+ return (
872
+ "If your org runs Cloud Agents in **Allowlist only** / **Default + allowlist** mode\n" +
873
+ "(dashboard → **Security**), add these hosts so cloud `/bkit-debug` + e2e can reach\n" +
874
+ "bkit's own tooling and your app and log backends:\n\n" +
875
+ "```text\n" +
876
+ entries.join("\n") +
877
+ "\n```\n\n" +
878
+ `_${entries.length} host(s) — ${BKIT_SHIPPED_NETWORK_HOSTS.length} derived from bkit's shipped ` +
879
+ `egress registry and ${declared.length} declared in \`allowed-domains\` in ` +
880
+ "`.agents/context.md`. Derived set fingerprint `" +
881
+ egressFingerprint() +
882
+ "`._ Add only the\n" +
883
+ "specific subdomains you need (e.g. `api.example.com`) — Cursor warns that a broad `*.`\n" +
884
+ "wildcard opens egress far wider than intended. (The Claude side auto-expands to apex + `*.`;\n" +
885
+ "Cursor's allowlist is deliberately narrower.)"
886
+ );
887
+ }
888
+
889
+ /**
890
+ * Generate `.cursor/bkit-cloud.md` — the Cursor Cloud Agents analogue of
891
+ * `.claude/bkit-cloud.md`. Both describe the SAME bkit cloud environment; only the
892
+ * mechanics differ. On Claude the doc carries a pasted setup script + network
893
+ * selector; on Cursor the toolchain lives in `.cursor/Dockerfile` + the per-snapshot
894
+ * `.cursor/environment.json` `install` (both committed, nothing to paste), so this doc
895
+ * is narrower: it resolves the **dashboard environment variables** to real values from
896
+ * the consumer's `.envrc` (Cursor policy — Linear tracker adds `BKIT_LINEAR_API_KEY`, no
897
+ * autocompact knob) and surfaces any context-fetch CLIs for parity.
898
+ *
899
+ * Like `.claude/bkit-cloud.md` it is gitignored + chmod 600 and UNTRACKED (never pushed to
900
+ * any WriteSet / manifest / canonicalHashes) — its values are machine-local and
901
+ * expected to differ, so it never enters `bkit check` drift or the upgrade template
902
+ * walk. Shared by install (runCursorModule) and upgrade. Callers MUST guard on
903
+ * `!dryRun` (never write secrets during `bkit check` / `--dry-run`) and on the cursor
904
+ * host being installed. Returns true when a file was written (false when the template
905
+ * is absent). Never logs the resolved values.
906
+ */
907
+ export function writeCursorCloudDoc(cwd: string, tokens: TokenMap, tracker: IssueTracker): boolean {
908
+ const src = path.join(getSharedRoot(), ".cursor", "bkit-cloud.md");
909
+ if (!fs.existsSync(src)) return false;
910
+ const policy = cursorCloudPolicy(tracker);
911
+ const res = resolveCloudEnvVars(cwd, policy);
912
+ // Function-form replacers: resolved secret values may contain `$`, which a string
913
+ // replacement would interpret ($&, $1, …).
914
+ const content = applyTokens(fs.readFileSync(src, "utf-8"), tokens)
915
+ .replace(/@@CLOUD_ENV_VARS@@/g, () => renderCloudEnvBlock(res, policy))
916
+ .replace(/@@CLOUD_ENV_NOTES@@/g, () => renderCloudEnvNotes(res))
917
+ .replace(/@@CURSOR_NETWORK@@/g, () => renderCursorNetworkAllowlist(cwd))
918
+ .replace(/@@CURSOR_CONTEXT_FETCH@@/g, () => renderCursorContextFetchProvision(cwd));
919
+ const dst = path.join(cwd, CURSOR_CLOUD_RELPATH);
920
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
921
+ fs.writeFileSync(dst, content, "utf-8");
922
+ fs.chmodSync(dst, 0o600);
923
+ return true;
924
+ }