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