@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,106 @@
1
+ // install/template-copies.ts — the consumer's `.bkit/templates/` copies: the sync that
2
+ // refreshes them, and the dotfile remap they share with the install/upgrade walk.
3
+ import * as fs from "node:fs";
4
+ import * as path from "node:path";
5
+ import { NPM_STRIP_REMAP, getPkgRoot, getTemplatesRoot, TEMPLATE_COPIES_DIR, } from "../shared/package-roots.js";
6
+ export function listFilesRecursive(dir) {
7
+ if (!fs.existsSync(dir))
8
+ return [];
9
+ const out = [];
10
+ for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
11
+ const p = path.join(dir, ent.name);
12
+ if (ent.isDirectory())
13
+ out.push(...listFilesRecursive(p));
14
+ else if (ent.isFile())
15
+ out.push(p);
16
+ }
17
+ return out;
18
+ }
19
+ // The dotfile remap: the one table lives in shared/package-roots.ts (NPM_STRIP_REMAP); the
20
+ // module install pass (install/modules/index.ts) and the `bkit upgrade` template walk both
21
+ // call this, so they never disagree about how a payload basename maps to its dest.
22
+ export function remapTemplateDest(rel) {
23
+ const dir = path.dirname(rel);
24
+ const base = path.basename(rel);
25
+ const mapped = NPM_STRIP_REMAP[base];
26
+ if (mapped === undefined)
27
+ return rel;
28
+ return dir === "." ? mapped : path.join(dir, mapped);
29
+ }
30
+ // Copy the whole templates root from the package into the consumer's
31
+ // `.bkit/templates/`, raw: no token substitution, so the copy is the package bytes and
32
+ // `git diff .bkit/templates` on an upgrade commit is the template changelog. Byte-compares
33
+ // first, keeps the source mode (hooks and scripts are executable), and prunes copies that
34
+ // left the set. Every change pushes a ws write in dry-run and live alike, so `bkit check`
35
+ // flags a stale copy. No-op in dogfood: there the folder IS the package's template source.
36
+ export function syncTemplateCopies(cwd, opts) {
37
+ const changes = { changed: [], added: [], removed: [] };
38
+ if (path.resolve(cwd) === getPkgRoot())
39
+ return changes;
40
+ const srcRoot = getTemplatesRoot();
41
+ const dstRoot = path.join(cwd, TEMPLATE_COPIES_DIR);
42
+ const shipped = new Set();
43
+ for (const srcPath of listFilesRecursive(srcRoot)) {
44
+ const rel = path.relative(srcRoot, srcPath);
45
+ shipped.add(rel);
46
+ const dstPath = path.join(dstRoot, rel);
47
+ const exists = fs.existsSync(dstPath);
48
+ if (exists && fs.readFileSync(srcPath).equals(fs.readFileSync(dstPath)))
49
+ continue;
50
+ (exists ? changes.changed : changes.added).push(rel);
51
+ if (!opts.dryRun) {
52
+ fs.mkdirSync(path.dirname(dstPath), { recursive: true });
53
+ fs.copyFileSync(srcPath, dstPath);
54
+ fs.chmodSync(dstPath, fs.statSync(srcPath).mode);
55
+ }
56
+ opts.ws.writes.push({
57
+ path: path.join(TEMPLATE_COPIES_DIR, rel),
58
+ action: exists ? "update" : "write",
59
+ });
60
+ }
61
+ for (const dstPath of listFilesRecursive(dstRoot)) {
62
+ const rel = path.relative(dstRoot, dstPath);
63
+ if (shipped.has(rel))
64
+ continue;
65
+ changes.removed.push(rel);
66
+ if (!opts.dryRun)
67
+ fs.rmSync(dstPath);
68
+ opts.ws.writes.push({ path: path.join(TEMPLATE_COPIES_DIR, rel), action: "update" });
69
+ }
70
+ if (!opts.dryRun)
71
+ pruneEmptyDirs(dstRoot);
72
+ return changes;
73
+ }
74
+ // Remove empty folders under `root`, deepest first. `root` itself stays.
75
+ function pruneEmptyDirs(root) {
76
+ if (!fs.existsSync(root))
77
+ return;
78
+ for (const ent of fs.readdirSync(root, { withFileTypes: true })) {
79
+ if (!ent.isDirectory())
80
+ continue;
81
+ const dir = path.join(root, ent.name);
82
+ pruneEmptyDirs(dir);
83
+ if (fs.readdirSync(dir).length === 0)
84
+ fs.rmdirSync(dir);
85
+ }
86
+ }
87
+ /** One-line pointer to the template docs, shared by the install and upgrade messages. */
88
+ export const TEMPLATES_POINTER = "Templates: see .bkit/templates.md; copies live in .bkit/templates/ (if your own gates scan the repo, ignore .bkit/templates/).";
89
+ /**
90
+ * The upgrade report for a template sync: one line per changed, added or removed
91
+ * template, then where to read about adopting them. Empty when nothing changed.
92
+ */
93
+ export function formatTemplateChanges(changes) {
94
+ const lines = [
95
+ ...changes.changed.map((p) => ` changed: ${path.join(TEMPLATE_COPIES_DIR, p)}`),
96
+ ...changes.added.map((p) => ` added: ${path.join(TEMPLATE_COPIES_DIR, p)}`),
97
+ ...changes.removed.map((p) => ` removed: ${path.join(TEMPLATE_COPIES_DIR, p)}`),
98
+ ];
99
+ if (lines.length === 0)
100
+ return "";
101
+ return [
102
+ `Templates updated (${lines.length}). bkit never applies these; diff them against your own copies and adopt what you want:`,
103
+ ...lines,
104
+ TEMPLATES_POINTER,
105
+ ].join("\n");
106
+ }
@@ -0,0 +1,204 @@
1
+ // install/version-file.ts — Schema for .bkit/version.
2
+ //
3
+ // Shape: JSON { pinnedVersion, canonicalHashes, claudeAllowDerived }. Content that is
4
+ // empty or not a JSON object reads as absent (null).
5
+ //
6
+ // `canonicalHashes`: map of consumer-relative path → sha256 hex of the file
7
+ // content bkit wrote. Used by `bkit upgrade` to detect consumer drift and by
8
+ // `bkit uninstall` to delete an owned file only when it is unchanged since bkit
9
+ // wrote it. Absent means "unknown" → treat as consumer-modified (preserve).
10
+ //
11
+ // Security note: sha256 used for content identity only, not cryptographic
12
+ // authentication. No secrets are stored here.
13
+ import * as fs from "node:fs";
14
+ import * as path from "node:path";
15
+ import * as crypto from "node:crypto";
16
+ import { parseJson } from "../shared/json.js";
17
+ import { getTemplatesRoot, templateRelPath } from "../shared/package-roots.js";
18
+ // ---------------------------------------------------------------------------
19
+ // Parse
20
+ // ---------------------------------------------------------------------------
21
+ /**
22
+ * Parse `.bkit/version` content into a BkitVersion object. Returns null when the
23
+ * content is empty or is not a JSON object (treat as absent). A missing
24
+ * `canonicalHashes` reads as {} (every file "unknown" → no silent overwrites) and a
25
+ * missing `claudeAllowDerived` as [] (bkit prunes nothing).
26
+ */
27
+ export function parseBkitVersion(content) {
28
+ const trimmed = content.trim();
29
+ if (!trimmed.startsWith("{"))
30
+ return null;
31
+ const json = parseJson(trimmed);
32
+ if (!json.ok || typeof json.value !== "object" || json.value === null)
33
+ return null;
34
+ const parsed = json.value;
35
+ const pinnedVersion = typeof parsed.pinnedVersion === "string" ? parsed.pinnedVersion : "";
36
+ const hashes = parsed.canonicalHashes;
37
+ const canonicalHashes = hashes && typeof hashes === "object" && !Array.isArray(hashes) ? { ...hashes } : {};
38
+ const claudeAllowDerived = Array.isArray(parsed.claudeAllowDerived)
39
+ ? parsed.claudeAllowDerived
40
+ : [];
41
+ return { pinnedVersion, canonicalHashes, claudeAllowDerived };
42
+ }
43
+ /**
44
+ * Read and parse `.bkit/version` from an absolute path.
45
+ * Returns null if the file is absent or content is empty.
46
+ */
47
+ export function readBkitVersion(versionFilePath) {
48
+ if (!fs.existsSync(versionFilePath))
49
+ return null;
50
+ const content = fs.readFileSync(versionFilePath, "utf-8");
51
+ return parseBkitVersion(content);
52
+ }
53
+ // ---------------------------------------------------------------------------
54
+ // Write — serialize to JSON
55
+ // ---------------------------------------------------------------------------
56
+ /**
57
+ * Serialize a BkitVersion to JSON for writing to `.bkit/version`.
58
+ * Always writes pretty-printed JSON with a trailing newline, schema fields only.
59
+ */
60
+ export function serializeBkitVersion(v) {
61
+ const { pinnedVersion, canonicalHashes, claudeAllowDerived } = v;
62
+ return JSON.stringify({ pinnedVersion, canonicalHashes, claudeAllowDerived }, null, 2) + "\n";
63
+ }
64
+ /**
65
+ * Write a BkitVersion to disk at `versionFilePath`.
66
+ */
67
+ export function writeBkitVersion(versionFilePath, v) {
68
+ fs.mkdirSync(path.dirname(versionFilePath), { recursive: true });
69
+ fs.writeFileSync(versionFilePath, serializeBkitVersion(v), "utf-8");
70
+ }
71
+ // ---------------------------------------------------------------------------
72
+ // canonicalHashes helpers (P4.T4)
73
+ // ---------------------------------------------------------------------------
74
+ /**
75
+ * Decide whether a managed file has been modified by the consumer since install.
76
+ *
77
+ * Returns true (treat as consumer-modified — block silent overwrite) when:
78
+ * - `canonicalHashes` has a recorded hash for `relPath` and the current on-disk
79
+ * content hash differs from it (true drift), OR
80
+ * - `canonicalHashes` has no entry for `relPath` (unknown hash state); upgrade then
81
+ * surfaces a conflict for the consumer to resolve.
82
+ *
83
+ * Returns false (no drift — safe to upgrade) only when:
84
+ * - The current on-disk content matches the recorded canonical hash, OR
85
+ * - The file is absent (nothing to compare).
86
+ *
87
+ * `relPath`: consumer-relative path (e.g. ".claude/agents/bkit-foo.md")
88
+ * `absolutePath`: absolute path to the file on disk
89
+ * `canonicalHashes`: the hashes map from the BkitVersion record
90
+ */
91
+ export function isConsumerModified(relPath, absolutePath, canonicalHashes) {
92
+ const current = hashFile(absolutePath);
93
+ if (!current)
94
+ return false; // absent → nothing to compare
95
+ const recorded = canonicalHashes[relPath];
96
+ if (!recorded)
97
+ return true; // unknown → treat as modified to prevent silent overwrites
98
+ return current !== recorded;
99
+ }
100
+ /**
101
+ * The merge both writers share (install's postDispatch and
102
+ * `updateCanonicalHashesAfterUpgrade`): fresh entries overwrite, and entries whose
103
+ * path is no longer on disk — or that belong to the copy-and-own template set —
104
+ * are dropped.
105
+ *
106
+ * A recorded hash is only ever consulted for a file that exists — drift detection
107
+ * reads the file, uninstall deletes it — so an entry for an absent path is dead
108
+ * bookkeeping, and a file recreated at that path later would be misclassified as
109
+ * bkit-owned. A template-set path is never a file bkit owns: install copies it
110
+ * byte-for-byte into `.bkit/templates/` and never writes the consumer's own copy,
111
+ * so it must carry no ownership hash. Retired and renamed managed files leave such
112
+ * entries behind, and a pure merge would preserve them forever (the
113
+ * `.bkit/scripts/…` entry a #507 move left and the `scripts/graphify/**` +
114
+ * `scripts/serena/bkit-serena-mcp.sh` entries a #489 move left are the observed
115
+ * cases; the latter survive the absent-path prune because the adopted copy stays on
116
+ * disk).
117
+ *
118
+ * `pruned` counts the dropped entries so callers can treat a prune-only merge as a
119
+ * change that is still worth writing.
120
+ */
121
+ export function mergeCanonicalHashes(cwd, existing, fresh) {
122
+ const canonicalHashes = {};
123
+ let pruned = 0;
124
+ for (const [relPath, hash] of Object.entries(existing)) {
125
+ if (!fs.existsSync(path.join(cwd, relPath)) || isTemplateSetPath(relPath)) {
126
+ pruned++;
127
+ continue;
128
+ }
129
+ canonicalHashes[relPath] = hash;
130
+ }
131
+ return { canonicalHashes: { ...canonicalHashes, ...fresh }, pruned };
132
+ }
133
+ /** True when `dest` is a member of the package's copy-and-own template set. */
134
+ function isTemplateSetPath(dest) {
135
+ return fs.existsSync(path.join(getTemplatesRoot(), templateRelPath(dest)));
136
+ }
137
+ // ---------------------------------------------------------------------------
138
+ // sha256 — content hashing for canonicalHashes
139
+ // ---------------------------------------------------------------------------
140
+ /**
141
+ * Compute the sha256 hex digest of a string or Buffer.
142
+ * Used to record the content of the files bkit writes.
143
+ */
144
+ export function sha256(content) {
145
+ return crypto.createHash("sha256").update(content).digest("hex");
146
+ }
147
+ /**
148
+ * Read a file and return its sha256 hex digest. Returns null if absent.
149
+ */
150
+ export function hashFile(filePath) {
151
+ if (!fs.existsSync(filePath))
152
+ return null;
153
+ const content = fs.readFileSync(filePath);
154
+ return sha256(content);
155
+ }
156
+ // Matches a stamped marker line in any form (anchored at a line start) including its
157
+ // trailing newline, so re-stamping replaces rather than appends (idempotent). Inline
158
+ // prose that quotes the marker never starts a line with it, so it never matches.
159
+ export const MANAGED_MARKER_LINE_RE = /^(?:<!-- |# <!-- |\/\/ )bkit:managed v[^\n]*\n?/m;
160
+ // Extracts the stamped version. `\S+` stops at the space before the em-dash.
161
+ export const MANAGED_MARKER_VERSION_RE = /bkit:managed v(\S+)/;
162
+ /** Build the managed-version marker for a given version, in the given comment syntax. */
163
+ export function managedVersionMarker(version, form = "html") {
164
+ const text = `bkit:managed v${version} — PolyForm Noncommercial 1.0.0 / Small Business 1.0.0 (https://polyformproject.org/licenses/) — do not edit; run \`bkit upgrade\` to refresh`;
165
+ if (form === "slash")
166
+ return `// ${text}`;
167
+ return form === "hash" ? `# <!-- ${text} -->` : `<!-- ${text} -->`;
168
+ }
169
+ /** Version of the first full-line managed-version marker in `content`, or null when none. */
170
+ export function readManagedVersion(content) {
171
+ const line = content.match(MANAGED_MARKER_LINE_RE)?.[0];
172
+ return line?.match(MANAGED_MARKER_VERSION_RE)?.[1] ?? null;
173
+ }
174
+ /**
175
+ * Insert (or replace) the managed-version marker immediately after the rendered
176
+ * file's frontmatter fence, always followed by exactly one blank line. Idempotent:
177
+ * any existing marker is stripped first and leading body blanks are collapsed, so
178
+ * stamping the same content twice yields identical bytes. With no frontmatter (e.g.
179
+ * cursor/opencode commands whose transforms strip the frontmatter), the marker sinks
180
+ * below the content's first Markdown heading instead, so it never becomes the
181
+ * IDE-visible first line; falls back to a top prepend only when there is no heading
182
+ * either, also followed by a blank line.
183
+ */
184
+ export function stampManagedVersion(content, version) {
185
+ const stripped = content.replace(MANAGED_MARKER_LINE_RE, "");
186
+ const marker = managedVersionMarker(version);
187
+ const fm = stripped.match(/^---\n[\s\S]*?\n---\n/);
188
+ if (fm) {
189
+ const cut = fm[0].length;
190
+ const body = stripped.slice(cut).replace(/^\n+/, "");
191
+ return stripped.slice(0, cut) + marker + "\n\n" + body;
192
+ }
193
+ // No frontmatter — the cursor/opencode command transforms remove it (applyT1 /
194
+ // applyOpencodeCommand). A marker on line 1 would be the IDE-visible command
195
+ // description, so it sinks below the first heading when there is one.
196
+ const heading = stripped.match(/^#{1,6} .*$/m);
197
+ if (heading?.index !== undefined) {
198
+ const cut = heading.index + heading[0].length;
199
+ const head = stripped.slice(0, cut);
200
+ const rest = stripped.slice(cut).replace(/^\n+/, "");
201
+ return rest ? `${head}\n\n${marker}\n\n${rest}` : `${head}\n\n${marker}\n`;
202
+ }
203
+ return marker + "\n\n" + stripped.replace(/^\n+/, "");
204
+ }
@@ -0,0 +1,342 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { updateManagedBlock, extractFullManagedBlock, extractManagedBlock, findLineAnchoredMarkers, selectMarkers, } from "./managed-block.js";
4
+ import { readTemplate } from "../render/parts.js";
5
+ import { applyTokens } from "./placeholders.js";
6
+ export function deepContains(template, consumer, pathPrefix = "") {
7
+ const missing = [];
8
+ const mismatched = [];
9
+ // null template: owns nothing → ok
10
+ if (template === null) {
11
+ return { ok: true, missing, mismatched };
12
+ }
13
+ // non-null template, null consumer → missing
14
+ if (consumer === null) {
15
+ missing.push(pathPrefix || "<root>");
16
+ return { ok: false, missing, mismatched };
17
+ }
18
+ // Both are arrays
19
+ if (Array.isArray(template) && Array.isArray(consumer)) {
20
+ _deepContainsArray(template, consumer, pathPrefix, missing);
21
+ return { ok: missing.length === 0 && mismatched.length === 0, missing, mismatched };
22
+ }
23
+ // Type mismatch (one is array, other is not, or different primitive types)
24
+ if (Array.isArray(template) !== Array.isArray(consumer)) {
25
+ mismatched.push(pathPrefix || "<root>");
26
+ return { ok: false, missing, mismatched };
27
+ }
28
+ // Both are plain objects
29
+ if (typeof template === "object" && typeof consumer === "object") {
30
+ const tObj = template;
31
+ const cObj = consumer;
32
+ for (const key of Object.keys(tObj)) {
33
+ const childPath = pathPrefix ? `${pathPrefix}.${key}` : key;
34
+ const tVal = tObj[key];
35
+ const cVal = cObj[key];
36
+ if (cVal === undefined) {
37
+ // If template has null for this key, still ok
38
+ if (tVal === null)
39
+ continue;
40
+ missing.push(childPath);
41
+ }
42
+ else {
43
+ const sub = deepContains(tVal, cVal, childPath);
44
+ missing.push(...sub.missing);
45
+ mismatched.push(...sub.mismatched);
46
+ }
47
+ }
48
+ return { ok: missing.length === 0 && mismatched.length === 0, missing, mismatched };
49
+ }
50
+ // Both are primitives — exact equality
51
+ if (template !== consumer) {
52
+ mismatched.push(pathPrefix || "<root>");
53
+ return { ok: false, missing, mismatched };
54
+ }
55
+ return { ok: true, missing, mismatched };
56
+ }
57
+ function _deepContainsArray(template, consumer, pathPrefix, missing) {
58
+ // Classify template elements as primitive or object
59
+ for (let i = 0; i < template.length; i++) {
60
+ const tEl = template[i];
61
+ const elPath = pathPrefix ? `${pathPrefix}[${i}]` : `[${i}]`;
62
+ if (tEl === null || typeof tEl !== "object") {
63
+ // Primitive — subset: consumer must contain this value
64
+ if (!consumer.includes(tEl)) {
65
+ missing.push(elPath);
66
+ }
67
+ }
68
+ else if (Array.isArray(tEl)) {
69
+ // Nested array element — must find an equal consumer element
70
+ const found = consumer.some((cEl) => Array.isArray(cEl) && deepContains(tEl, cEl, "").ok);
71
+ if (!found) {
72
+ missing.push(elPath);
73
+ }
74
+ }
75
+ else {
76
+ // Object element — order-insensitive deep-equal containment
77
+ const found = consumer.some((cEl) => cEl !== null &&
78
+ typeof cEl === "object" &&
79
+ !Array.isArray(cEl) &&
80
+ deepContains(tEl, cEl, "").ok);
81
+ if (!found) {
82
+ missing.push(elPath);
83
+ }
84
+ }
85
+ }
86
+ }
87
+ // ---------------------------------------------------------------------------
88
+ // deepMergeJson — recursive JSON merge primitive (P3.T1)
89
+ //
90
+ // Semantics (from DE-8 contract spec):
91
+ // - Objects: merge recursively (override keys win; base keys retained if absent from override)
92
+ // - Arrays: override replaces base (no concat — arrays are treated as atomic values)
93
+ // - Primitives / null: override replaces base
94
+ // ---------------------------------------------------------------------------
95
+ export function deepMergeJson(base, override) {
96
+ if (override === null || typeof override !== "object" || Array.isArray(override)) {
97
+ return override;
98
+ }
99
+ if (base === null || typeof base !== "object" || Array.isArray(base)) {
100
+ // base is not a plain object — override wins wholesale
101
+ return override;
102
+ }
103
+ // Both are plain objects — recursive merge.
104
+ //
105
+ // Key ORDER follows `override` (the bkit template) for keys it defines, then appends
106
+ // base-only (consumer) keys. Order-significant maps like opencode's last-match-wins
107
+ // `permission.bash` keep the template's order (`git push --force-with-lease*: allow`
108
+ // stays after `git push --force*: deny`).
109
+ const baseObj = base;
110
+ const overrideObj = override;
111
+ const result = {};
112
+ // 1. Template keys first, in template order (recurse where both sides are plain objects).
113
+ for (const [key, val] of Object.entries(overrideObj)) {
114
+ const baseVal = baseObj[key];
115
+ if (key in baseObj &&
116
+ baseVal !== null &&
117
+ typeof baseVal === "object" &&
118
+ !Array.isArray(baseVal) &&
119
+ val !== null &&
120
+ typeof val === "object" &&
121
+ !Array.isArray(val)) {
122
+ result[key] = deepMergeJson(baseVal, val);
123
+ }
124
+ else {
125
+ result[key] = val;
126
+ }
127
+ }
128
+ // 2. Consumer-only keys preserved, appended after the template's keys.
129
+ for (const [key, val] of Object.entries(baseObj)) {
130
+ if (!(key in result)) {
131
+ result[key] = val;
132
+ }
133
+ }
134
+ return result;
135
+ }
136
+ // ---------------------------------------------------------------------------
137
+ // writeTier2JsonContained — deep-containment JSON helper (BAR-167 Phase 1)
138
+ //
139
+ // Contract:
140
+ // - dest absent → write template as-is (first install)
141
+ // - dest present, valid JSON, template contained → no-op (idempotent)
142
+ // - dest present, valid JSON, containment fails → deepMergeJson(existing, template)
143
+ // (template wins on key collisions; consumer-only keys outside template tree preserved)
144
+ // - dest present, malformed JSON → overwrite with template
145
+ // - schemaFlipped: true when a path value changed type during deep-merge
146
+ // ---------------------------------------------------------------------------
147
+ export function writeTier2JsonContained(srcPath, dstPath, dryRun, ws) {
148
+ const srcRaw = fs.readFileSync(srcPath, "utf-8");
149
+ let template;
150
+ try {
151
+ template = JSON.parse(srcRaw);
152
+ }
153
+ catch {
154
+ throw new Error(`writeTier2JsonContained: template at ${srcPath} is not valid JSON`);
155
+ }
156
+ if (!fs.existsSync(dstPath)) {
157
+ // First install — write template as-is
158
+ ensureDir(path.dirname(dstPath));
159
+ if (!dryRun) {
160
+ fs.writeFileSync(dstPath, JSON.stringify(template, null, 2) + "\n", "utf-8");
161
+ const srcMode = fs.statSync(srcPath).mode;
162
+ fs.chmodSync(dstPath, srcMode);
163
+ }
164
+ ws.writes.push({ path: dstPath, action: "write" });
165
+ return;
166
+ }
167
+ // dest exists — read and check containment
168
+ const dstRaw = fs.readFileSync(dstPath, "utf-8");
169
+ let existing;
170
+ try {
171
+ existing = JSON.parse(dstRaw);
172
+ }
173
+ catch {
174
+ // Malformed destination — refuse to overwrite; require manual fix (matches malformed-package-json blocker discipline)
175
+ throw new Error(`[bkit] ${dstPath} is malformed JSON — fix manually before running bkit install`);
176
+ }
177
+ // Check if existing already contains the template
178
+ const containsResult = deepContains(template, existing);
179
+ if (containsResult.ok) {
180
+ return; // idempotent — no change needed
181
+ }
182
+ // Deep-merge: existing base, template override (template wins on conflicts)
183
+ const merged = deepMergeJson(existing, template);
184
+ const mergedStr = JSON.stringify(merged, null, 2) + "\n";
185
+ if (mergedStr === dstRaw)
186
+ return; // idempotent guard
187
+ if (!dryRun) {
188
+ fs.writeFileSync(dstPath, mergedStr, "utf-8");
189
+ }
190
+ ws.writes.push({ path: dstPath, action: "update" });
191
+ }
192
+ // ---------------------------------------------------------------------------
193
+ // Internal helpers
194
+ // ---------------------------------------------------------------------------
195
+ export function ensureDir(dir) {
196
+ fs.mkdirSync(dir, { recursive: true });
197
+ }
198
+ // ---------------------------------------------------------------------------
199
+ // fully-managed format — idempotent rewrite of whole file after token substitution
200
+ //
201
+ // Semantics: always writes the src content (with tokens applied) to dst.
202
+ // If dst exists with identical content, no-op (no double-count in WriteSet).
203
+ // ---------------------------------------------------------------------------
204
+ export function writeTier1(srcPath, dstPath, tokens, dryRun, ws) {
205
+ const srcRaw = readTemplate(srcPath);
206
+ const srcContent = applyTokens(srcRaw, tokens);
207
+ if (fs.existsSync(dstPath)) {
208
+ const existing = fs.readFileSync(dstPath, "utf-8");
209
+ if (existing === srcContent)
210
+ return; // identical — no-op
211
+ }
212
+ ensureDir(path.dirname(dstPath));
213
+ if (!dryRun) {
214
+ fs.writeFileSync(dstPath, srcContent, "utf-8");
215
+ // Preserve executable bit from src
216
+ const srcMode = fs.statSync(srcPath).mode;
217
+ fs.chmodSync(dstPath, srcMode);
218
+ }
219
+ ws.writes.push({ path: dstPath, action: "write" });
220
+ }
221
+ // ---------------------------------------------------------------------------
222
+ // markered-text format — managed-block (bkit owns content between markers; consumer owns rest)
223
+ //
224
+ // Semantics:
225
+ // - dest absent → write whole file (with token substitution)
226
+ // - dest has markers → update only the bkit block (tokens applied to new block content)
227
+ // - dest present, no marks → append full block at EOF; preserve consumer content above
228
+ //
229
+ // markerStyle: "html-comment" for markdown, shell and `.gitignore` (`# ` prefix allowed);
230
+ // "slash-comment" for JS.
231
+ // ---------------------------------------------------------------------------
232
+ export function writeTier2(srcPath, dstPath, tokens, markerStyle, dryRun, ws) {
233
+ const srcRaw = readTemplate(srcPath);
234
+ if (!fs.existsSync(dstPath)) {
235
+ // dest missing → write whole template (with tokens applied)
236
+ const content = applyTokens(srcRaw, tokens);
237
+ ensureDir(path.dirname(dstPath));
238
+ if (!dryRun) {
239
+ fs.writeFileSync(dstPath, content, "utf-8");
240
+ const srcMode = fs.statSync(srcPath).mode;
241
+ fs.chmodSync(dstPath, srcMode);
242
+ }
243
+ ws.writes.push({ path: dstPath, action: "write" });
244
+ return;
245
+ }
246
+ const destContent = fs.readFileSync(dstPath, "utf-8");
247
+ const fullBlock = extractFullManagedBlock(srcRaw, markerStyle);
248
+ if (fullBlock === null) {
249
+ // Template has no block for this marker style — nothing to manage
250
+ return;
251
+ }
252
+ // Check if dest already has markers
253
+ const blockContent = extractManagedBlock(destContent, markerStyle);
254
+ if (blockContent === null) {
255
+ // extractManagedBlock returns null for BOTH "no markers" and "ambiguous markers"
256
+ // (duplicates / inverted). Only the former should append — appending on the latter
257
+ // compounds corruption (dogfood docs grew a second stamped block every install).
258
+ const [startMarker, endMarker] = selectMarkers(markerStyle);
259
+ const starts = findLineAnchoredMarkers(destContent, startMarker);
260
+ const ends = findLineAnchoredMarkers(destContent, endMarker);
261
+ if (starts.length > 0 || ends.length > 0) {
262
+ console.warn(`[bkit] Managed block markers present but unparseable in ${dstPath} — skipping (expected exactly one start/end)`);
263
+ return;
264
+ }
265
+ // dest has no markers → append full block at EOF (with tokens applied)
266
+ const appliedBlock = applyTokens(fullBlock, tokens);
267
+ const sep = destContent.length === 0
268
+ ? ""
269
+ : destContent.endsWith("\n\n")
270
+ ? ""
271
+ : destContent.endsWith("\n")
272
+ ? "\n"
273
+ : "\n\n";
274
+ const tail = appliedBlock.endsWith("\n") ? "" : "\n";
275
+ if (!dryRun) {
276
+ fs.writeFileSync(dstPath, destContent + sep + appliedBlock + tail, "utf-8");
277
+ }
278
+ ws.writes.push({ path: dstPath, action: "append" });
279
+ return;
280
+ }
281
+ // dest has markers → update managed block with new content (tokens applied)
282
+ const newBlockContent = extractManagedBlock(srcRaw, markerStyle);
283
+ if (newBlockContent === null)
284
+ return;
285
+ const appliedNewContent = applyTokens(newBlockContent, tokens);
286
+ if (updateManagedBlock(dstPath, appliedNewContent, dryRun, markerStyle)) {
287
+ ws.writes.push({ path: dstPath, action: "update" });
288
+ }
289
+ }
290
+ // ---------------------------------------------------------------------------
291
+ // Managed package.json scripts — add-if-missing with consumer ownership
292
+ //
293
+ // Semantics:
294
+ // - File absent → no-op, returns missingPkg: true
295
+ // - File malformed JSON → no-op, returns malformed: true
296
+ // - script key absent → add with default value (recorded as one update)
297
+ // - script key exists → preserve consumer value (never overwrite)
298
+ //
299
+ // One WriteSet entry per call when any script was added. Drift
300
+ // surfaces in `bkit check` because `dryRun=true` still pushes to ws.writes.
301
+ // ---------------------------------------------------------------------------
302
+ export function ensurePackageJsonScripts(scripts, dryRun, ws) {
303
+ const pkgPath = "package.json";
304
+ if (!fs.existsSync(pkgPath)) {
305
+ return { added: [], preserved: [], missingPkg: true, malformed: false };
306
+ }
307
+ const raw = fs.readFileSync(pkgPath, "utf-8");
308
+ let pkg;
309
+ try {
310
+ pkg = JSON.parse(raw);
311
+ }
312
+ catch {
313
+ return { added: [], preserved: [], missingPkg: false, malformed: true };
314
+ }
315
+ let pkgScripts = pkg.scripts ?? undefined;
316
+ const added = [];
317
+ const preserved = [];
318
+ for (const [name, value] of Object.entries(scripts)) {
319
+ if (pkgScripts && Object.prototype.hasOwnProperty.call(pkgScripts, name)) {
320
+ preserved.push(name);
321
+ }
322
+ else {
323
+ if (!pkgScripts) {
324
+ pkgScripts = {};
325
+ pkg.scripts = pkgScripts;
326
+ }
327
+ pkgScripts[name] = value;
328
+ added.push(name);
329
+ }
330
+ }
331
+ if (added.length > 0) {
332
+ ws.writes.push({ path: pkgPath, action: "update" });
333
+ if (!dryRun) {
334
+ // Preserve indent style and trailing newline of the original file.
335
+ const indentMatch = raw.match(/\n([ \t]+)"/);
336
+ const indent = indentMatch ? indentMatch[1] : " ";
337
+ const trailingNewline = raw.endsWith("\n") ? "\n" : "";
338
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, indent) + trailingNewline, "utf-8");
339
+ }
340
+ }
341
+ return { added, preserved, missingPkg: false, malformed: false };
342
+ }
@@ -0,0 +1,27 @@
1
+ // The clamp record log: one JSON line per artifact `bkit context clamp` trimmed,
2
+ // read back into the step's status row (`clamped`) by `bkit context finalise` and
3
+ // `bkit steps finish --clamp-log`. Lives outside commands/workflow so both read it
4
+ // without importing each other.
5
+ import * as fs from "node:fs";
6
+ import * as path from "node:path";
7
+ import { git, parseJson } from "../commands/lib.js";
8
+ /** `tmp/bkit-clamp-{fid}-{step}[-{attempt}].jsonl` in the checkout `cwd` sits in. */
9
+ export function clampLogPath(cwd, fid, step, attempt) {
10
+ const top = git(cwd, ["rev-parse", "--show-toplevel"]) ?? cwd;
11
+ return path.join(top, "tmp", `bkit-clamp-${fid}-${step}${attempt ? `-${attempt}` : ""}.jsonl`);
12
+ }
13
+ /** Every record in the log; reading never drains it, so a retried status block sees the same array. */
14
+ export function readRecords(log, onBad = () => undefined) {
15
+ if (!fs.existsSync(log))
16
+ return [];
17
+ return fs
18
+ .readFileSync(log, "utf-8")
19
+ .split("\n")
20
+ .filter((l) => l.trim() !== "")
21
+ .flatMap((l) => {
22
+ const parsed = parseJson(l);
23
+ if (!parsed.ok)
24
+ onBad(l);
25
+ return parsed.ok ? [parsed.value] : [];
26
+ });
27
+ }