@cbartens/bkit 0.0.0-stage → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (375) hide show
  1. package/.bkit/README.md +417 -0
  2. package/.bkit/core/.agents/context.md +95 -0
  3. package/.bkit/core/.agents/docs.md +62 -0
  4. package/.bkit/core/.agents/rules.md +147 -0
  5. package/.bkit/core/.agents/skills.md +43 -0
  6. package/.bkit/core/.bkit/LICENSE.md +151 -0
  7. package/.bkit/core/.bkit/README.md +417 -0
  8. package/.bkit/core/.bkit/cloud.md +493 -0
  9. package/.bkit/core/.bkit/comparison.md +321 -0
  10. package/.bkit/core/.bkit/install.md +401 -0
  11. package/.bkit/core/.bkit/jsonl.md +497 -0
  12. package/.bkit/core/.bkit/prompts.md +474 -0
  13. package/.bkit/core/.bkit/providers.md +598 -0
  14. package/.bkit/core/.bkit/templates.md +470 -0
  15. package/.bkit/core/.bkit/trackers.md +95 -0
  16. package/.bkit/core/.bkit/workflows.md +1550 -0
  17. package/.bkit/core/.claude/hooks/bkit-gateguard.cjs +82 -0
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +93 -0
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +74 -0
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +115 -0
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +135 -0
  22. package/.bkit/core/.cursor/hooks/bkit-gateguard.cjs +111 -0
  23. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +169 -0
  24. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +63 -0
  25. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +225 -0
  26. package/.bkit/core/AGENTS.md +77 -0
  27. package/.bkit/core/LICENSE.md +149 -0
  28. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +272 -0
  29. package/.bkit/core/docs/templates/bkit-audit-adoption.md +223 -0
  30. package/.bkit/core/docs/templates/bkit-audit-agents.md +230 -0
  31. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +227 -0
  32. package/.bkit/core/docs/templates/bkit-audit-analytics.md +266 -0
  33. package/.bkit/core/docs/templates/bkit-audit-annotations.md +230 -0
  34. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +270 -0
  35. package/.bkit/core/docs/templates/bkit-audit-app-store.md +254 -0
  36. package/.bkit/core/docs/templates/bkit-audit-architecture.md +221 -0
  37. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +241 -0
  38. package/.bkit/core/docs/templates/bkit-audit-config.md +230 -0
  39. package/.bkit/core/docs/templates/bkit-audit-cost.md +218 -0
  40. package/.bkit/core/docs/templates/bkit-audit-coverage.md +221 -0
  41. package/.bkit/core/docs/templates/bkit-audit-database.md +229 -0
  42. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +251 -0
  43. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +283 -0
  44. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +268 -0
  45. package/.bkit/core/docs/templates/bkit-audit-documentation.md +280 -0
  46. package/.bkit/core/docs/templates/bkit-audit-duplication.md +253 -0
  47. package/.bkit/core/docs/templates/bkit-audit-failures.md +259 -0
  48. package/.bkit/core/docs/templates/bkit-audit-flakes.md +237 -0
  49. package/.bkit/core/docs/templates/bkit-audit-gates.md +250 -0
  50. package/.bkit/core/docs/templates/bkit-audit-issues.md +273 -0
  51. package/.bkit/core/docs/templates/bkit-audit-llm.md +239 -0
  52. package/.bkit/core/docs/templates/bkit-audit-logs.md +266 -0
  53. package/.bkit/core/docs/templates/bkit-audit-models.md +210 -0
  54. package/.bkit/core/docs/templates/bkit-audit-privacy.md +211 -0
  55. package/.bkit/core/docs/templates/bkit-audit-prompts.md +216 -0
  56. package/.bkit/core/docs/templates/bkit-audit-red-team.md +220 -0
  57. package/.bkit/core/docs/templates/bkit-audit-reliability.md +222 -0
  58. package/.bkit/core/docs/templates/bkit-audit-repo.md +224 -0
  59. package/.bkit/core/docs/templates/bkit-audit-security.md +274 -0
  60. package/.bkit/core/docs/templates/bkit-audit-slop.md +200 -0
  61. package/.bkit/core/docs/templates/bkit-audit-testing.md +270 -0
  62. package/.bkit/core/docs/templates/bkit-audit-usability.md +237 -0
  63. package/.bkit/core/docs/templates/bkit-plan.md +476 -0
  64. package/.bkit/core/engine/checks/after/auth.ts +149 -0
  65. package/.bkit/core/engine/checks/after/ci-yml.ts +701 -0
  66. package/.bkit/core/engine/checks/after/github.ts +424 -0
  67. package/.bkit/core/engine/checks/after/index.ts +530 -0
  68. package/.bkit/core/engine/checks/after/managed.ts +217 -0
  69. package/.bkit/core/engine/checks/after/suppression.ts +53 -0
  70. package/.bkit/core/engine/checks/after/tools.ts +427 -0
  71. package/.bkit/core/engine/checks/before/context-fetch.ts +429 -0
  72. package/.bkit/core/engine/checks/before/env.ts +187 -0
  73. package/.bkit/core/engine/checks/before/files.ts +204 -0
  74. package/.bkit/core/engine/checks/before/index.ts +206 -0
  75. package/.bkit/core/engine/checks/before/mcp.ts +127 -0
  76. package/.bkit/core/engine/checks/before/repo.ts +77 -0
  77. package/.bkit/core/engine/checks/before/version.ts +67 -0
  78. package/.bkit/core/engine/checks/status-holes.ts +479 -0
  79. package/.bkit/core/engine/cli.ts +867 -0
  80. package/.bkit/core/engine/commands/analysis.ts +550 -0
  81. package/.bkit/core/engine/commands/ci/ci.ts +483 -0
  82. package/.bkit/core/engine/commands/comply.ts +415 -0
  83. package/.bkit/core/engine/commands/harvest.ts +459 -0
  84. package/.bkit/core/engine/commands/install/check.ts +70 -0
  85. package/.bkit/core/engine/commands/install/doctor.ts +254 -0
  86. package/.bkit/core/engine/commands/install/install.ts +550 -0
  87. package/.bkit/core/engine/commands/install/uninstall.ts +995 -0
  88. package/.bkit/core/engine/commands/install/upgrade.ts +1037 -0
  89. package/.bkit/core/engine/commands/launch.ts +139 -0
  90. package/.bkit/core/engine/commands/lib.ts +495 -0
  91. package/.bkit/core/engine/commands/registry.ts +53 -0
  92. package/.bkit/core/engine/commands/setup/setup.ts +184 -0
  93. package/.bkit/core/engine/commands/telemetry.ts +32 -0
  94. package/.bkit/core/engine/commands/workflow/branches.ts +1514 -0
  95. package/.bkit/core/engine/commands/workflow/context.ts +961 -0
  96. package/.bkit/core/engine/commands/workflow/counters.ts +268 -0
  97. package/.bkit/core/engine/commands/workflow/fids.ts +243 -0
  98. package/.bkit/core/engine/commands/workflow/issues.ts +675 -0
  99. package/.bkit/core/engine/commands/workflow/ledgers.ts +575 -0
  100. package/.bkit/core/engine/commands/workflow/locks.ts +478 -0
  101. package/.bkit/core/engine/commands/workflow/prs.ts +1087 -0
  102. package/.bkit/core/engine/commands/workflow/repo.ts +220 -0
  103. package/.bkit/core/engine/commands/workflow/roadmap.ts +576 -0
  104. package/.bkit/core/engine/commands/workflow/runs.ts +2140 -0
  105. package/.bkit/core/engine/commands/workflow/runtime.ts +300 -0
  106. package/.bkit/core/engine/commands/workflow/skills.ts +118 -0
  107. package/.bkit/core/engine/commands/workflow/status.ts +455 -0
  108. package/.bkit/core/engine/commands/workflow/steps.ts +1300 -0
  109. package/.bkit/core/engine/commands/workflow/tests.ts +161 -0
  110. package/.bkit/core/engine/commands/workflow/workflows.ts +1573 -0
  111. package/.bkit/core/engine/commands/workflow/workstreams.ts +164 -0
  112. package/.bkit/core/engine/commands/workflow/worktrees.ts +534 -0
  113. package/.bkit/core/engine/install/cloud-env.ts +924 -0
  114. package/.bkit/core/engine/install/managed-block.ts +212 -0
  115. package/.bkit/core/engine/install/manifest.ts +448 -0
  116. package/.bkit/core/engine/install/modules/claude.ts +362 -0
  117. package/.bkit/core/engine/install/modules/cloud.ts +173 -0
  118. package/.bkit/core/engine/install/modules/codex.ts +219 -0
  119. package/.bkit/core/engine/install/modules/core.ts +620 -0
  120. package/.bkit/core/engine/install/modules/cursor.ts +231 -0
  121. package/.bkit/core/engine/install/modules/index.ts +242 -0
  122. package/.bkit/core/engine/install/modules/opencode.ts +573 -0
  123. package/.bkit/core/engine/install/payload-links.ts +150 -0
  124. package/.bkit/core/engine/install/placeholders.ts +108 -0
  125. package/.bkit/core/engine/install/template-copies.ts +119 -0
  126. package/.bkit/core/engine/install/version-file.ts +284 -0
  127. package/.bkit/core/engine/install/write.ts +467 -0
  128. package/.bkit/core/engine/ledgers/clamp-log.ts +32 -0
  129. package/.bkit/core/engine/ledgers/status.ts +213 -0
  130. package/.bkit/core/engine/ledgers/telemetry.ts +1143 -0
  131. package/.bkit/core/engine/render/hosts.ts +372 -0
  132. package/.bkit/core/engine/render/models.ts +323 -0
  133. package/.bkit/core/engine/render/parts.ts +38 -0
  134. package/.bkit/core/engine/render/trackers.ts +170 -0
  135. package/.bkit/core/engine/shared/egress.ts +345 -0
  136. package/.bkit/core/engine/shared/json.ts +16 -0
  137. package/.bkit/core/engine/shared/log-prefix.ts +9 -0
  138. package/.bkit/core/engine/shared/package-json.ts +29 -0
  139. package/.bkit/core/engine/shared/package-manager.ts +38 -0
  140. package/.bkit/core/engine/shared/package-roots.ts +163 -0
  141. package/.bkit/core/engine/shared/protected-paths.ts +164 -0
  142. package/.bkit/core/engine/shared/settings.ts +72 -0
  143. package/.bkit/core/engine/shared/timeouts.ts +20 -0
  144. package/.bkit/core/engine/tools/wording.ts +748 -0
  145. package/.bkit/core/hooks/gateguard-edit-payload.js +18 -0
  146. package/.bkit/core/hooks/gateguard-engine.js +193 -0
  147. package/.bkit/core/hooks/guardrails-shell.js +154 -0
  148. package/.bkit/core/hooks/guardrails-tiers.js +68 -0
  149. package/.bkit/core/hooks/preflight-linear.sh +73 -0
  150. package/.bkit/core/prompts/bkit-audit-generate.md +66 -0
  151. package/.bkit/core/prompts/bkit-build-challenge-1.md +79 -0
  152. package/.bkit/core/prompts/bkit-build-challenge-2.md +81 -0
  153. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +68 -0
  154. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +70 -0
  155. package/.bkit/core/prompts/bkit-build-challenge-tests.md +73 -0
  156. package/.bkit/core/prompts/bkit-build-install-skills.md +67 -0
  157. package/.bkit/core/prompts/bkit-build-plan-current.md +75 -0
  158. package/.bkit/core/prompts/bkit-build-plan-execute.md +72 -0
  159. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +73 -0
  160. package/.bkit/core/prompts/bkit-build-plan-verify.md +88 -0
  161. package/.bkit/core/prompts/bkit-build-summary.md +93 -0
  162. package/.bkit/core/prompts/bkit-debug-abort-handover.md +90 -0
  163. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +151 -0
  164. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +78 -0
  165. package/.bkit/core/prompts/bkit-debug-failure-soak.md +73 -0
  166. package/.bkit/core/prompts/bkit-debug-summary.md +95 -0
  167. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +72 -0
  168. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +72 -0
  169. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +75 -0
  170. package/.bkit/core/prompts/bkit-design-generate.md +110 -0
  171. package/.bkit/core/prompts/bkit-design-organise.md +85 -0
  172. package/.bkit/core/prompts/bkit-design-review-1.md +121 -0
  173. package/.bkit/core/prompts/bkit-design-review-2.md +111 -0
  174. package/.bkit/core/prompts/bkit-design-spike.md +97 -0
  175. package/.bkit/core/prompts/bkit-design-summary.md +106 -0
  176. package/.bkit/core/prompts/bkit-design-update.md +66 -0
  177. package/.bkit/core/prompts/bkit-plan-complexity-check.md +66 -0
  178. package/.bkit/core/prompts/bkit-plan-complexity-split.md +87 -0
  179. package/.bkit/core/prompts/bkit-plan-generate.md +74 -0
  180. package/.bkit/core/prompts/bkit-plan-review-1.md +90 -0
  181. package/.bkit/core/prompts/bkit-plan-review-2.md +80 -0
  182. package/.bkit/core/prompts/bkit-plan-review-3.md +92 -0
  183. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +84 -0
  184. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +84 -0
  185. package/.bkit/core/prompts/bkit-plan-summary.md +106 -0
  186. package/.bkit/core/prompts/bkit-plan-update.md +68 -0
  187. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +90 -0
  188. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +94 -0
  189. package/.bkit/core/prompts/bkit-ship-summary.md +77 -0
  190. package/.bkit/core/prompts/bkit-ship-update-docs.md +71 -0
  191. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +91 -0
  192. package/.bkit/core/prompts/bkit-utility-update-decisions.md +75 -0
  193. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +76 -0
  194. package/.bkit/core/prompts/bkit-utility-update-documentation.md +61 -0
  195. package/.bkit/core/prompts/bkit-utility-update-failures.md +76 -0
  196. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +75 -0
  197. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +82 -0
  198. package/.bkit/core/workflows/bkit-auto.md +121 -0
  199. package/.bkit/core/workflows/bkit-build.md +802 -0
  200. package/.bkit/core/workflows/bkit-debug.md +649 -0
  201. package/.bkit/core/workflows/bkit-design.md +495 -0
  202. package/.bkit/core/workflows/bkit-plan.md +510 -0
  203. package/.bkit/core/workflows/bkit-ship.md +650 -0
  204. package/.bkit/shared/.bkit/.env.example +86 -0
  205. package/.bkit/shared/.claude/bkit-cloud.md +117 -0
  206. package/.bkit/shared/.claude/settings.json +88 -0
  207. package/.bkit/shared/.codex/hooks.json +26 -0
  208. package/.bkit/shared/.cursor/bkit-cloud.md +84 -0
  209. package/.bkit/shared/.cursor/hooks.json +26 -0
  210. package/.bkit/shared/.cursor/mcp.json +15 -0
  211. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +12 -0
  212. package/.bkit/shared/.gitattributes +37 -0
  213. package/.bkit/shared/.mcp.json +16 -0
  214. package/.bkit/shared/.opencode/opencode.json +62 -0
  215. package/.bkit/shared/CLAUDE.md +11 -0
  216. package/.bkit/shared/LICENSE.md +22 -0
  217. package/.bkit/shared/docs/architecture.md +19 -0
  218. package/.bkit/shared/docs/data-schema.md +19 -0
  219. package/.bkit/shared/docs/deployments.md +433 -0
  220. package/.bkit/shared/docs/design.md +39 -0
  221. package/.bkit/shared/docs/noise.md +19 -0
  222. package/.bkit/shared/docs/observability.md +25 -0
  223. package/.bkit/shared/docs/security.md +42 -0
  224. package/.bkit/shared/docs/setup.md +30 -0
  225. package/.bkit/shared/docs/technology.md +18 -0
  226. package/.bkit/shared/docs/testing.md +413 -0
  227. package/.bkit/shared/gitignore +97 -0
  228. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +187 -0
  229. package/.bkit/templates/.cursor/Dockerfile +68 -0
  230. package/.bkit/templates/.cursor/environment.json +6 -0
  231. package/.bkit/templates/.cursor/settings.json +11 -0
  232. package/.bkit/templates/.envrc +7 -0
  233. package/.bkit/templates/.github/dependabot.yml +52 -0
  234. package/.bkit/templates/.github/renovate.json5 +224 -0
  235. package/.bkit/templates/.github/workflows/bkit-ci.yml +1062 -0
  236. package/.bkit/templates/.github/workflows/bkit-cloud.yml +564 -0
  237. package/.bkit/templates/.github/workflows/bkit-renovate.yml +102 -0
  238. package/.bkit/templates/.graphifyignore +108 -0
  239. package/.bkit/templates/.husky/pre-commit +16 -0
  240. package/.bkit/templates/.husky/pre-push +91 -0
  241. package/.bkit/templates/.lintstagedrc.json +3 -0
  242. package/.bkit/templates/.prettierignore +41 -0
  243. package/.bkit/templates/.serena/project.yml +243 -0
  244. package/.bkit/templates/.vale/styles/House/Filler.yml +11 -0
  245. package/.bkit/templates/.vale/styles/House/Hedging.yml +12 -0
  246. package/.bkit/templates/.vale/styles/House/LLMSlop.yml +13 -0
  247. package/.bkit/templates/.vale/styles/House/Verbose.yml +12 -0
  248. package/.bkit/templates/.vale.ini +67 -0
  249. package/.bkit/templates/LICENSE.md +22 -0
  250. package/.bkit/templates/context/bkit-cloudrun.md +84 -0
  251. package/.bkit/templates/context/bkit-expo.md +186 -0
  252. package/.bkit/templates/context/bkit-github.md +79 -0
  253. package/.bkit/templates/context/bkit-inngest.md +45 -0
  254. package/.bkit/templates/context/bkit-maestro.md +76 -0
  255. package/.bkit/templates/context/bkit-playwright.md +62 -0
  256. package/.bkit/templates/context/bkit-resend.md +36 -0
  257. package/.bkit/templates/context/bkit-sentry.md +65 -0
  258. package/.bkit/templates/context/bkit-serena.md +33 -0
  259. package/.bkit/templates/context/bkit-stripe.md +36 -0
  260. package/.bkit/templates/context/bkit-supabase.md +59 -0
  261. package/.bkit/templates/context/bkit-tavily.md +49 -0
  262. package/.bkit/templates/context/bkit-vercel.md +64 -0
  263. package/.bkit/templates/docs/capabilities.md +72 -0
  264. package/.bkit/templates/scripts/ci/accepted-divergences.json +21 -0
  265. package/.bkit/templates/scripts/ci/check-accepted-divergences.mjs +152 -0
  266. package/.bkit/templates/scripts/ci/check-accepted-divergences.test.mjs +130 -0
  267. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +98 -0
  268. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +86 -0
  269. package/.bkit/templates/scripts/graphify/bkit-graph-drift-rules.json +23 -0
  270. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +208 -0
  271. package/.bkit/templates/scripts/graphify/bkit-graph-eager-rules.json +35 -0
  272. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +236 -0
  273. package/.bkit/templates/scripts/graphify/bkit-graph-external-rules.json +17 -0
  274. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +290 -0
  275. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +19 -0
  276. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +120 -0
  277. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +232 -0
  278. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +36 -0
  279. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +927 -0
  280. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +351 -0
  281. package/.bkit/templates/scripts/launchd/ai.bkit.launchd.plist +26 -0
  282. package/.bkit/templates/scripts/launchd/bkit-launchd-env.sh +53 -0
  283. package/.bkit/templates/scripts/launchd/launchd.env.example +13 -0
  284. package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +275 -0
  285. package/.bkit/templates/scripts/secrets/bkit-secrets.config.mjs +66 -0
  286. package/.bkit/templates/scripts/secrets/bkit-secrets.mjs +785 -0
  287. package/.bkit/templates/scripts/serena/bkit-serena-mcp.sh +30 -0
  288. package/.bkit/templates/scripts/serena/bkit-serena.mcp.json +9 -0
  289. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +286 -0
  290. package/.bkit/templates/slop-scan.config.json +120 -0
  291. package/CHANGELOG.md +1503 -0
  292. package/LICENSE.md +161 -0
  293. package/README.md +184 -2
  294. package/dist/checks/after/auth.js +140 -0
  295. package/dist/checks/after/ci-yml.js +681 -0
  296. package/dist/checks/after/github.js +400 -0
  297. package/dist/checks/after/index.js +431 -0
  298. package/dist/checks/after/managed.js +187 -0
  299. package/dist/checks/after/suppression.js +39 -0
  300. package/dist/checks/after/tools.js +351 -0
  301. package/dist/checks/before/context-fetch.js +426 -0
  302. package/dist/checks/before/env.js +163 -0
  303. package/dist/checks/before/files.js +187 -0
  304. package/dist/checks/before/index.js +162 -0
  305. package/dist/checks/before/mcp.js +111 -0
  306. package/dist/checks/before/repo.js +71 -0
  307. package/dist/checks/before/version.js +60 -0
  308. package/dist/checks/status-holes.js +393 -0
  309. package/dist/cli.js +688 -0
  310. package/dist/commands/analysis.js +325 -0
  311. package/dist/commands/ci/ci.js +438 -0
  312. package/dist/commands/comply.js +310 -0
  313. package/dist/commands/harvest.js +354 -0
  314. package/dist/commands/install/check.js +61 -0
  315. package/dist/commands/install/doctor.js +209 -0
  316. package/dist/commands/install/install.js +475 -0
  317. package/dist/commands/install/uninstall.js +839 -0
  318. package/dist/commands/install/upgrade.js +782 -0
  319. package/dist/commands/launch.js +118 -0
  320. package/dist/commands/lib.js +363 -0
  321. package/dist/commands/registry.js +50 -0
  322. package/dist/commands/setup/setup.js +158 -0
  323. package/dist/commands/telemetry.js +29 -0
  324. package/dist/commands/workflow/branches.js +1265 -0
  325. package/dist/commands/workflow/context.js +846 -0
  326. package/dist/commands/workflow/counters.js +227 -0
  327. package/dist/commands/workflow/fids.js +224 -0
  328. package/dist/commands/workflow/issues.js +585 -0
  329. package/dist/commands/workflow/ledgers.js +472 -0
  330. package/dist/commands/workflow/locks.js +364 -0
  331. package/dist/commands/workflow/prs.js +904 -0
  332. package/dist/commands/workflow/repo.js +199 -0
  333. package/dist/commands/workflow/roadmap.js +495 -0
  334. package/dist/commands/workflow/runs.js +1717 -0
  335. package/dist/commands/workflow/runtime.js +257 -0
  336. package/dist/commands/workflow/skills.js +110 -0
  337. package/dist/commands/workflow/status.js +392 -0
  338. package/dist/commands/workflow/steps.js +1093 -0
  339. package/dist/commands/workflow/tests.js +144 -0
  340. package/dist/commands/workflow/workflows.js +1342 -0
  341. package/dist/commands/workflow/workstreams.js +141 -0
  342. package/dist/commands/workflow/worktrees.js +473 -0
  343. package/dist/install/cloud-env.js +818 -0
  344. package/dist/install/managed-block.js +182 -0
  345. package/dist/install/manifest.js +376 -0
  346. package/dist/install/modules/claude.js +288 -0
  347. package/dist/install/modules/cloud.js +151 -0
  348. package/dist/install/modules/codex.js +193 -0
  349. package/dist/install/modules/core.js +531 -0
  350. package/dist/install/modules/cursor.js +186 -0
  351. package/dist/install/modules/index.js +152 -0
  352. package/dist/install/modules/opencode.js +504 -0
  353. package/dist/install/payload-links.js +119 -0
  354. package/dist/install/placeholders.js +87 -0
  355. package/dist/install/template-copies.js +106 -0
  356. package/dist/install/version-file.js +204 -0
  357. package/dist/install/write.js +342 -0
  358. package/dist/ledgers/clamp-log.js +27 -0
  359. package/dist/ledgers/status.js +156 -0
  360. package/dist/ledgers/telemetry.js +637 -0
  361. package/dist/render/hosts.js +339 -0
  362. package/dist/render/models.js +288 -0
  363. package/dist/render/parts.js +33 -0
  364. package/dist/render/trackers.js +135 -0
  365. package/dist/shared/egress.js +299 -0
  366. package/dist/shared/json.js +16 -0
  367. package/dist/shared/log-prefix.js +7 -0
  368. package/dist/shared/package-json.js +22 -0
  369. package/dist/shared/package-manager.js +32 -0
  370. package/dist/shared/package-roots.js +145 -0
  371. package/dist/shared/protected-paths.js +153 -0
  372. package/dist/shared/settings.js +44 -0
  373. package/dist/shared/timeouts.js +19 -0
  374. package/dist/tools/wording.js +680 -0
  375. package/package.json +101 -4
@@ -0,0 +1,1342 @@
1
+ // bkit workflows start|fail|handover|close|promote|links — a phase workflow's
2
+ // lifecycle state.
3
+ //
4
+ // start takes the feature lock (or checks the one Step 1 took) and opens a run
5
+ // with a `workflow-started` row, unless this is a resume of the same
6
+ // workflow's IN_PROGRESS run.
7
+ // fail the Failure Path's state and payloads: `workflow-failed` row, abort an
8
+ // in-progress rebase, release the lock, clear the sentinels, say whether
9
+ // a handover is due, and print the `bkit:failed` label set and the
10
+ // failure comment. The tracker calls stay in the workflow.
11
+ // handover after the handover subagent: commit and abort-push it (`--push`), or
12
+ // ship's one-commit flush (`--flush`), and print the handover comment.
13
+ // close grade compliance, then the `workflow-done` row, the run's counter and
14
+ // outcome rows in `.bkit/stats.jsonl`, this workflow's telemetry report
15
+ // and the artifact links. `--flush` is ship's close: under the dev lock,
16
+ // on dev or a detached origin/dev worktree, commit and land it.
17
+ // promote design / plan close: the highest versioned draft becomes the
18
+ // canonical doc (anchor stamped, a superseded canonical archived).
19
+ // links the feature docs and this workflow's logs on a ref, as markdown links.
20
+ import * as fs from "node:fs";
21
+ import * as path from "node:path";
22
+ import { appendLine, fold, runNumber, runOrStepField, statusTimestamp, } from "../../ledgers/status.js";
23
+ import { appendLine as telemetryLine, foldFrom, resolveRepoSlug, validate, workflowTelemetry, } from "../../ledgers/telemetry.js";
24
+ import { readBkitVersion } from "../../install/version-file.js";
25
+ import { TIMEOUTS } from "../../shared/timeouts.js";
26
+ import { gradeCompliance } from "../comply.js";
27
+ import { CommandError, EXIT, git, parseJson, repoRoot, runGh, runGit, statusLocation, statusRelPath, } from "../lib.js";
28
+ import { pushBranch, readAnchor, stampAnchor } from "./branches.js";
29
+ import { AUTO_LABEL, AUTO_ROUTE_SUFFIX, buildComment, linearState, transitionLabels, } from "./issues.js";
30
+ import { EXIT_EMPTY, commitBookkeeping, unionLedgers } from "./ledgers.js";
31
+ import { EXIT_REMOVE_FAILED, EXIT_SPLIT_BUCKET, acquireDevLock, acquireWorkflowLock, lockRoot, owns, readHolder, releaseLock, resolveMonth, workflowLockPath, } from "./locks.js";
32
+ import { mergePr, probePr } from "./prs.js";
33
+ import { FEATURE_STATUS } from "./roadmap.js";
34
+ import { EXIT_NO_STATUS, WORKFLOW_FLAG, positiveInt, readRuns, readStatusEvents, readStatusRows, str, } from "./status.js";
35
+ import { writeStepRow } from "./steps.js";
36
+ /** Sentinels a workflow leaves in its logs folder; either one existing means a handover is due. */
37
+ export const SENTINELS = [".rebase-failed", ".deferred-blocked"];
38
+ /** Exit code (start --lock-held): the lock is missing or belongs to another owner. */
39
+ export const EXIT_LOCK_NOT_HELD = 6;
40
+ /** Exit code (handover --push): the handover artifact is missing or empty. */
41
+ export const EXIT_HANDOVER_MISSING = 8;
42
+ /** Exit code (handover --push): the branch has an open PR, so nothing was pushed. */
43
+ export const EXIT_OPEN_PR_KEPT = 9;
44
+ /** Exit code (handover, close --flush): a push failed. */
45
+ export const EXIT_PUSH_FAILED = 10;
46
+ /** Exit code (handover --flush, close --flush): a dev checkout, commit or worktree step failed. */
47
+ export const EXIT_FLUSH_FAILED = 11;
48
+ /** Exit code (promote): no versioned draft to promote. */
49
+ export const EXIT_NO_VERSION = 12;
50
+ function workflowName(workflow) {
51
+ if (!Object.hasOwn(FEATURE_STATUS, workflow))
52
+ throw new CommandError(EXIT.USAGE, `--workflow must be ${Object.keys(FEATURE_STATUS).join(", ")}`);
53
+ return workflow;
54
+ }
55
+ /**
56
+ * start and close work in the current tree (ship: its book root), the root
57
+ * `git rev-parse --show-toplevel` reports.
58
+ */
59
+ function whereInTree(cwd, o) {
60
+ const root = repoRoot(cwd);
61
+ const month = resolveMonth(root, o.fid, o.month);
62
+ const tree = o.workflow === "ship"
63
+ ? lockRoot(cwd, o.workflow, o.devPushes)
64
+ : (git(cwd, ["rev-parse", "--show-toplevel"]) ?? root);
65
+ const status = o.file ? path.resolve(cwd, o.file) : path.join(tree, statusRelPath(month, o.fid));
66
+ return { root, month, tree, status };
67
+ }
68
+ const headSha = (cwd) => git(cwd, ["rev-parse", "HEAD"]) ?? "";
69
+ const logDirRel = (month, fid) => path.join("docs", "plans", month, "logs", fid);
70
+ const list = (v) => v ?? [];
71
+ // ---------------------------------------------------------------------------
72
+ // start
73
+ // ---------------------------------------------------------------------------
74
+ function checkHeldLock(file, who) {
75
+ const holder = readHolder(file);
76
+ if (holder === undefined)
77
+ throw new CommandError(EXIT_LOCK_NOT_HELD, `no lock at ${file}`);
78
+ if (!owns(holder, who))
79
+ throw new CommandError(EXIT_LOCK_NOT_HELD, `${file} is held by another owner: ${holder.line}`);
80
+ }
81
+ // ---------------------------------------------------------------------------
82
+ // fail
83
+ // ---------------------------------------------------------------------------
84
+ /**
85
+ * Abort a rebase left in progress in `tree`. `git rev-parse --git-path X` always
86
+ * exits 0 (it only computes the path), so the directory's existence is the test.
87
+ */
88
+ function abortRebase(tree, log) {
89
+ const inProgress = ["rebase-merge", "rebase-apply"].some((name) => {
90
+ const p = git(tree, ["rev-parse", "--path-format=absolute", "--git-path", name]);
91
+ return p !== null && fs.existsSync(p);
92
+ });
93
+ if (!inProgress)
94
+ return false;
95
+ const res = runGit(tree, ["rebase", "--abort"]);
96
+ if (!res.ok)
97
+ log(`git rebase --abort failed in ${tree}: ${res.stderr}`);
98
+ return res.ok;
99
+ }
100
+ /** The workflow-failed state: row, rebase abort, lock release, sentinels. */
101
+ function failState(ctx, workflow, fid) {
102
+ const devPushes = ctx.flags.devPushes === true;
103
+ const root = repoRoot(ctx.cwd);
104
+ const month = resolveMonth(root, fid, str(ctx.flags.month) || undefined);
105
+ const file = str(ctx.flags.file) || undefined;
106
+ const status = file
107
+ ? path.resolve(ctx.cwd, file)
108
+ : statusLocation({ cwd: ctx.cwd, workflow, fid, month, devPushes }).path;
109
+ // The run's own tree: the feature worktree when there is one, else this checkout.
110
+ // Never the main checkout behind a worktree, where a rebase would be a human's.
111
+ const worktree = path.join(root, ".worktrees", fid);
112
+ const tree = fs.existsSync(worktree)
113
+ ? worktree
114
+ : (git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root);
115
+ // Abort first: the abort resets the tree, which would drop a row appended to a
116
+ // tracked status.jsonl before it.
117
+ const rebaseAborted = abortRebase(tree, ctx.log);
118
+ let row = null;
119
+ let soak = false;
120
+ if (fs.existsSync(status)) {
121
+ soak =
122
+ workflow === "debug" && runOrStepField(readRuns(status), "debug", "debugMode") === "SOAK";
123
+ row = { type: "workflow-failed", workflow, at: statusTimestamp() };
124
+ fs.appendFileSync(status, appendLine(row));
125
+ }
126
+ else {
127
+ ctx.log(`${status} does not exist — no workflow-failed row written`);
128
+ }
129
+ const lockFile = workflowLockPath(lockRoot(ctx.cwd, workflow, devPushes), month, fid);
130
+ const { removeFailed, ...lock } = releaseLock(lockFile, {
131
+ workflow,
132
+ fid,
133
+ token: str(ctx.flags.token),
134
+ });
135
+ if (lock.heldBy !== null)
136
+ ctx.log(`${lockFile} belongs to another owner, left in place: ${lock.heldBy}`);
137
+ if (removeFailed)
138
+ ctx.log(`lock removal failed: ${lockFile}`);
139
+ // Each sentinel is cleared where it was created: `.rebase-failed` in the run's
140
+ // tree, `.deferred-blocked` beside status.jsonl (ship: the book root).
141
+ const logDirs = new Set([path.join(tree, logDirRel(month, fid)), path.dirname(status)]);
142
+ const sentinels = [];
143
+ for (const dir of logDirs) {
144
+ for (const name of SENTINELS) {
145
+ const p = path.join(dir, name);
146
+ if (!fs.existsSync(p))
147
+ continue;
148
+ sentinels.push({ name, path: p });
149
+ fs.rmSync(p, { force: true });
150
+ }
151
+ }
152
+ return { row, rebaseAborted, lock, sentinels, removeFailed, soak };
153
+ }
154
+ function failVerb(ctx) {
155
+ const workflow = workflowName(String(ctx.flags.workflow));
156
+ // An empty value is a placeholder not held yet (the failure came before it was set).
157
+ const fid = str(ctx.flags.fid) || undefined;
158
+ const token = str(ctx.flags.token) || undefined;
159
+ if (token !== undefined && fid === undefined)
160
+ throw new CommandError(EXIT.USAGE, "--token needs --fid");
161
+ // State only for a run that took the lock: without the token the failure came
162
+ // before Step 1 locked, and nothing here is this run's to change.
163
+ const state = token === undefined || fid === undefined
164
+ ? {
165
+ row: null,
166
+ rebaseAborted: false,
167
+ lock: null,
168
+ sentinels: [],
169
+ removeFailed: false,
170
+ soak: false,
171
+ }
172
+ : failState(ctx, workflow, fid);
173
+ // Labels: bkit:failed added; a ship whose PR already merged also moves to bkit:merged.
174
+ const pr = str(ctx.flags.pr) || undefined;
175
+ let prState = null;
176
+ if (pr !== undefined && pr !== "") {
177
+ const probed = probePr(ctx.cwd, { number: pr, state: "open" });
178
+ prState = probed.kind === "ok" ? (probed.pr?.state ?? null) : null;
179
+ }
180
+ const merged = prState === "MERGED";
181
+ const transition = merged ? { phase: "merged" } : { failed: true };
182
+ const labels = transitionLabels(list(ctx.flags.label), transition).labels;
183
+ if (merged && !labels.includes("bkit:failed"))
184
+ labels.push("bkit:failed");
185
+ // The failure comment, when the step is named.
186
+ let comment = null;
187
+ const stepNumber = str(ctx.flags.stepNumber);
188
+ if (stepNumber !== undefined) {
189
+ const errorFile = str(ctx.flags.errorFile);
190
+ const error = errorFile === undefined ? (str(ctx.flags.error) ?? "") : readText(ctx.cwd, errorFile);
191
+ comment = buildComment(ctx.cwd, {
192
+ kind: "failure",
193
+ stepNumber,
194
+ stepTitle: str(ctx.flags.stepTitle),
195
+ subStep: str(ctx.flags.subStep),
196
+ error: state.removeFailed ? `${error}; Lock removal failed` : error,
197
+ stderrFile: str(ctx.flags.stderrFile) || undefined,
198
+ });
199
+ }
200
+ ctx.emit({
201
+ row: state.row,
202
+ rebaseAborted: state.rebaseAborted,
203
+ lock: state.lock,
204
+ sentinels: state.sentinels,
205
+ handoverNeeded: token !== undefined &&
206
+ (ctx.flags.maxExceeded === true || state.sentinels.length > 0 || state.soak),
207
+ labels,
208
+ linearState: linearState(transition, undefined),
209
+ prState,
210
+ comment,
211
+ });
212
+ return state.removeFailed ? EXIT_REMOVE_FAILED : EXIT.OK;
213
+ }
214
+ /** A text file's content, trailing newlines dropped; a missing file is a usage error. */
215
+ function readText(cwd, rel) {
216
+ const abs = path.resolve(cwd, rel);
217
+ if (!fs.existsSync(abs))
218
+ throw new CommandError(EXIT.USAGE, `${rel} does not exist`);
219
+ return fs.readFileSync(abs, "utf-8").replace(/\n+$/, "");
220
+ }
221
+ // ---------------------------------------------------------------------------
222
+ // handover
223
+ // ---------------------------------------------------------------------------
224
+ /**
225
+ * Ship's Failure Path flush: copy branch-side logs and ledger rows into the book
226
+ * root, then ONE `chore({fid}): ship FAILED bkit [skip ci]` commit and ONE push —
227
+ * to dev under the dev lock when this runtime pushes dev, else the current branch.
228
+ */
229
+ async function shipFlush(ctx, o) {
230
+ const root = repoRoot(ctx.cwd);
231
+ const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
232
+ const bookRoot = o.devPushes ? root : top;
233
+ const rel = logDirRel(o.month, o.fid);
234
+ const src = o.worktree ?? path.join(root, ".worktrees", o.fid);
235
+ if (fs.existsSync(path.join(src, rel)) && path.resolve(src) !== path.resolve(bookRoot)) {
236
+ fs.mkdirSync(path.join(bookRoot, rel), { recursive: true });
237
+ for (const f of fs.readdirSync(path.join(src, rel)).filter((n) => n.endsWith(".md"))) {
238
+ const to = path.join(bookRoot, rel, f);
239
+ if (!fs.existsSync(to))
240
+ fs.copyFileSync(path.join(src, rel, f), to);
241
+ }
242
+ unionLedgers(src, bookRoot);
243
+ }
244
+ let wt = bookRoot;
245
+ let target = "";
246
+ let release;
247
+ if (o.devPushes) {
248
+ let lock;
249
+ try {
250
+ lock = await acquireDevLock({
251
+ cwd: root,
252
+ workflow: "ship",
253
+ fid: o.fid,
254
+ deadlineS: 60,
255
+ log: ctx.log,
256
+ });
257
+ }
258
+ catch {
259
+ // Busy: the FAILED record rides along on the next dev commit; never a second failure.
260
+ ctx.log(`dev lock busy — ship FAILED bookkeeping left uncommitted in ${bookRoot}`);
261
+ return { code: EXIT.OK, pushed: false, ref: null, skipped: "dev-lock-busy" };
262
+ }
263
+ release = () => releaseLock(lock.path, { workflow: "ship", fid: o.fid, token: lock.token });
264
+ runGit(root, ["checkout", "dev"]);
265
+ if (git(root, ["branch", "--show-current"]) !== "dev") {
266
+ release();
267
+ ctx.log(`not on dev after checkout — FAILED bookkeeping left uncommitted in ${bookRoot}`);
268
+ return { code: EXIT_FLUSH_FAILED, pushed: false, ref: null, skipped: null };
269
+ }
270
+ runGit(root, ["pull", "--ff-only", "origin", "dev"]);
271
+ wt = root;
272
+ target = "dev";
273
+ }
274
+ else {
275
+ ctx.log("RUNTIME_DEVPUSHES=false — the FAILED record commits on the current branch");
276
+ target = git(wt, ["branch", "--show-current"]) ?? "";
277
+ }
278
+ try {
279
+ if (target === "") {
280
+ ctx.log(`push target empty (detached HEAD?) — bookkeeping left uncommitted in ${wt}`);
281
+ return { code: EXIT_FLUSH_FAILED, pushed: false, ref: null, skipped: null };
282
+ }
283
+ const before = headSha(wt);
284
+ try {
285
+ commitBookkeeping({
286
+ root: wt,
287
+ month: o.month,
288
+ fid: o.fid,
289
+ scope: "full",
290
+ mode: "commit",
291
+ message: `chore(${o.fid}): ship FAILED bkit [skip ci]`,
292
+ }, ctx.log);
293
+ }
294
+ catch (err) {
295
+ if (err instanceof CommandError && err.code === EXIT_EMPTY) {
296
+ ctx.log("no bookkeeping delta to record — nothing committed, nothing pushed");
297
+ return { code: EXIT.OK, pushed: false, ref: null, skipped: "nothing-to-commit" };
298
+ }
299
+ ctx.log(`bookkeeping commit failed — FAILED bookkeeping left uncommitted in ${wt}: ${err.message}`);
300
+ return { code: EXIT_FLUSH_FAILED, pushed: false, ref: null, skipped: null };
301
+ }
302
+ if (headSha(wt) === before) {
303
+ ctx.log("no bookkeeping delta to record — nothing committed, nothing pushed");
304
+ return { code: EXIT.OK, pushed: false, ref: null, skipped: "nothing-to-commit" };
305
+ }
306
+ const push = runGit(wt, ["push", "origin", target]);
307
+ if (!push.ok) {
308
+ ctx.log(`git push origin ${target} failed: ${push.stderr}`);
309
+ return { code: EXIT_PUSH_FAILED, pushed: false, ref: null, skipped: null };
310
+ }
311
+ return { code: EXIT.OK, pushed: true, ref: target, skipped: null };
312
+ }
313
+ finally {
314
+ release?.();
315
+ }
316
+ }
317
+ async function handoverVerb(ctx) {
318
+ const workflow = workflowName(String(ctx.flags.workflow));
319
+ const fid = String(ctx.flags.fid);
320
+ const month = resolveMonth(repoRoot(ctx.cwd), fid, str(ctx.flags.month));
321
+ const push = ctx.flags.push === true;
322
+ const flush = ctx.flags.flush === true;
323
+ if (push && flush)
324
+ throw new CommandError(EXIT.USAGE, "give --push or --flush, not both");
325
+ if (flush && workflow !== "ship")
326
+ throw new CommandError(EXIT.USAGE, "--flush is ship only");
327
+ const worktree = str(ctx.flags.worktree);
328
+ const base = worktree === undefined ? ctx.cwd : path.resolve(ctx.cwd, worktree);
329
+ const artifact = path.join(logDirRel(month, fid), `${workflow}-handover.md`);
330
+ const abs = path.join(base, artifact);
331
+ const present = fs.existsSync(abs) && fs.statSync(abs).size > 0;
332
+ let code = EXIT.OK;
333
+ let ref = str(ctx.flags.ref) ?? null;
334
+ let pushed = false;
335
+ let skipped = null;
336
+ if (push) {
337
+ if (!present) {
338
+ ctx.log(`${artifact} is missing or empty — nothing to hand over`);
339
+ return EXIT_HANDOVER_MISSING;
340
+ }
341
+ runGit(ctx.cwd, ["add", "-A"]);
342
+ const made = runGit(ctx.cwd, [
343
+ "commit",
344
+ "-m",
345
+ `docs(${fid}): ${workflow} aborted bkit [skip ci]`,
346
+ ]);
347
+ if (!made.ok)
348
+ ctx.log(`abort commit: ${made.stderr || made.stdout}`);
349
+ const r = pushBranch(ctx.cwd, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
350
+ if (r.code === EXIT.USE_MCP)
351
+ return r.code;
352
+ pushed = r.out.pushed;
353
+ ref = r.out.ref;
354
+ skipped = r.out.skipped;
355
+ code =
356
+ r.code === EXIT.OK
357
+ ? EXIT.OK
358
+ : r.out.skipped === "open-pr"
359
+ ? EXIT_OPEN_PR_KEPT
360
+ : EXIT_PUSH_FAILED;
361
+ }
362
+ else if (flush) {
363
+ const r = await shipFlush(ctx, {
364
+ fid,
365
+ month,
366
+ devPushes: ctx.flags.devPushes === true,
367
+ worktree: worktree === undefined ? undefined : base,
368
+ });
369
+ code = r.code;
370
+ pushed = r.pushed;
371
+ ref = r.ref;
372
+ skipped = r.skipped;
373
+ }
374
+ const linkable = ref !== null && (pushed || (!push && !flush));
375
+ const comment = present
376
+ ? buildComment(base, {
377
+ kind: "handover",
378
+ ownerRepo: linkable ? (str(ctx.flags.ownerRepo) ?? resolveRepoSlug(base)) : undefined,
379
+ ref: linkable ? ref : undefined,
380
+ artifacts: linkable ? [artifact] : [],
381
+ bodyFile: artifact,
382
+ })
383
+ : null;
384
+ ctx.emit({
385
+ handover: present ? artifact : null,
386
+ pushed,
387
+ ref: pushed ? ref : null,
388
+ skipped,
389
+ comment,
390
+ });
391
+ return code;
392
+ }
393
+ /** Rows of a JSONL ledger; malformed lines are skipped, a missing file is empty. */
394
+ function ledgerRows(file) {
395
+ if (!fs.existsSync(file))
396
+ return [];
397
+ return fs
398
+ .readFileSync(file, "utf-8")
399
+ .split("\n")
400
+ .filter((l) => l.trim() !== "")
401
+ .flatMap((l) => {
402
+ const row = parseObject(l);
403
+ return row === undefined ? [] : [row];
404
+ });
405
+ }
406
+ /** Not JSON reads as undefined: callers treat that as "no value" and say what it means for them. */
407
+ function jsonOrUndefined(text) {
408
+ const parsed = parseJson(text);
409
+ return parsed.ok ? parsed.value : undefined;
410
+ }
411
+ function parseObject(line) {
412
+ const v = jsonOrUndefined(line);
413
+ return v !== null && typeof v === "object" ? v : undefined;
414
+ }
415
+ const distinctKeys = (rows) => new Set(rows.filter((r) => r.key !== undefined).map((r) => String(r.key))).size;
416
+ /**
417
+ * Cumulative distinct deferrals / failures, and how many keys THIS run added to
418
+ * each instinct ledger (rows of this workflow at or after the run's start). With
419
+ * no start time the per-run counts are unknown, so they are omitted rather than
420
+ * counting the ledger's whole history as this run's.
421
+ */
422
+ function ledgerCounts(tree, workflow, startMs) {
423
+ const deferrals = ledgerRows(path.join(tree, "docs", "deferrals.jsonl"));
424
+ const failures = ledgerRows(path.join(tree, "docs", "failures.jsonl"));
425
+ const friction = ledgerRows(path.join(tree, ".bkit", "friction.jsonl"));
426
+ const added = (rows) => distinctKeys(rows.filter((r) => r.workflow === workflow && Number(r.ts) >= startMs));
427
+ return {
428
+ deferrals: distinctKeys(deferrals.filter((r) => r.kind === "deferral")),
429
+ failures: distinctKeys(failures.filter((r) => r.kind === "failure")),
430
+ ...(startMs === undefined
431
+ ? {}
432
+ : {
433
+ frictionAdded: added(friction),
434
+ deferralsAdded: added(deferrals),
435
+ failuresAdded: added(failures),
436
+ }),
437
+ };
438
+ }
439
+ /** `git diff --shortstat` numbers; 0 for anything absent or a range git rejects. */
440
+ export function diffStat(cwd, range) {
441
+ const out = runGit(cwd, ["diff", "--shortstat", range]).stdout;
442
+ const num = (re) => Number(re.exec(out)?.[1] ?? 0);
443
+ const linesAdded = num(/(\d+) insertions?\(/);
444
+ const linesDeleted = num(/(\d+) deletions?\(/);
445
+ return {
446
+ linesAdded,
447
+ linesDeleted,
448
+ linesChanged: linesAdded + linesDeleted,
449
+ filesChanged: num(/(\d+) files? changed/),
450
+ };
451
+ }
452
+ /** Checklist items (`- [`) across the feature's plan and sub-plans. */
453
+ function taskCount(tree, month, fid) {
454
+ const dir = path.join(tree, "docs", "plans", month);
455
+ if (!fs.existsSync(dir))
456
+ return 0;
457
+ return fs
458
+ .readdirSync(dir)
459
+ .filter((f) => f.startsWith(`${fid}-plan`) && f.endsWith(".md"))
460
+ .flatMap((f) => fs.readFileSync(path.join(dir, f), "utf-8").split("\n"))
461
+ .filter((l) => l.startsWith("- [")).length;
462
+ }
463
+ /** Per-tier coverage from `coverage/{tier}/coverage-summary.json`; undefined when none. */
464
+ function coverage(tree) {
465
+ const out = {};
466
+ for (const tier of ["unit", "integration", "e2e"]) {
467
+ const file = path.join(tree, "coverage", tier, "coverage-summary.json");
468
+ if (!fs.existsSync(file))
469
+ continue;
470
+ const total = parseObject(fs.readFileSync(file, "utf-8"))?.total;
471
+ if (typeof total?.lines?.pct !== "number")
472
+ continue;
473
+ const stats = {};
474
+ for (const k of ["lines", "branches", "functions", "statements"]) {
475
+ const pct = total[k]?.pct;
476
+ if (typeof pct === "number")
477
+ stats[k] = pct;
478
+ }
479
+ out[tier] = stats;
480
+ }
481
+ return Object.keys(out).length ? out : undefined;
482
+ }
483
+ /** Last row of `type` for `workflow`, in `at` order (a union merge may interleave lines). */
484
+ function lastOfType(events, type, workflow) {
485
+ return events
486
+ .filter((e) => e.type === type && e.workflow === workflow)
487
+ .sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0))
488
+ .at(-1);
489
+ }
490
+ /** Append telemetry rows; best-effort, so a bad path is logged and never fails the close. */
491
+ function appendStats(file, rows, log) {
492
+ const valid = rows.filter((r) => {
493
+ const v = validate(r);
494
+ if (!v.ok)
495
+ log(`[bkit-telemetry] ${String(r.kind)} row invalid, not written: ${v.reason}`);
496
+ return v.ok;
497
+ });
498
+ if (valid.length === 0)
499
+ return false;
500
+ try {
501
+ fs.appendFileSync(file, valid.map((r) => `${telemetryLine(r)}\n`).join(""));
502
+ return true;
503
+ }
504
+ catch (err) {
505
+ // Telemetry never gates a close: report the failed append and carry on.
506
+ log(`[bkit-telemetry] append failed: ${file} — ${err.message}`);
507
+ return false;
508
+ }
509
+ }
510
+ /** Markdown link per feature doc and per log of this workflow, as on `ref`. */
511
+ export function artifactLinks(root, ref, month, fid, workflow, ownerRepo) {
512
+ const list = (dir) => (git(root, ["ls-tree", "-r", "--name-only", ref, "--", dir]) ?? "").split("\n").filter(Boolean);
513
+ const docs = list(`docs/plans/${month}/`).filter((f) => path.posix.dirname(f) === `docs/plans/${month}` &&
514
+ path.posix.basename(f).startsWith(`${fid}-`));
515
+ const logs = list(`docs/plans/${month}/logs/${fid}/`).filter((f) => path.posix.basename(f).startsWith(`${workflow}-`));
516
+ // The URL names the branch, never the remote-tracking ref it was read from.
517
+ const urlRef = ref.replace(/^origin\//, "");
518
+ return [...docs, ...logs].map((f) => ({
519
+ name: path.posix.basename(f),
520
+ path: f,
521
+ url: `https://github.com/${ownerRepo}/blob/${urlRef}/${f}`,
522
+ }));
523
+ }
524
+ const linkLines = (artifacts) => artifacts.map((a) => `- [${a.name}](${a.url})`).join("\n");
525
+ const ARTIFACTS_FILE = "close-artifacts.md";
526
+ const TELEMETRY_FILE = "close-telemetry.md";
527
+ /** The close comment: optional tree link, then the Artifacts and Telemetry sections from the outbox. */
528
+ function closeComment(cwd, outbox, o) {
529
+ const sections = [ARTIFACTS_FILE, TELEMETRY_FILE]
530
+ .filter((f) => fs.existsSync(path.join(outbox, f)))
531
+ .map((f) => `${f === ARTIFACTS_FILE ? "Artifacts" : "Telemetry"}=${path.join(outbox, f)}`);
532
+ return buildComment(cwd, {
533
+ stepNumber: o.number,
534
+ stepTitle: o.title,
535
+ ownerRepo: o.tree === undefined ? undefined : (o.ownerRepo ?? resolveRepoSlug(cwd)),
536
+ tree: o.tree,
537
+ sections,
538
+ });
539
+ }
540
+ /**
541
+ * Grade compliance, append the workflow-done row (and, with `recordStep`, the
542
+ * close step's row first), the counter and outcome telemetry rows, and build the
543
+ * report and artifact links; with `outbox`, write them for the close comment; with
544
+ * `message`, commit everything (`git add -A`) in the tree.
545
+ */
546
+ export function closeWorkflow(cwd, o, log) {
547
+ const workflow = workflowName(o.workflow);
548
+ const where = whereInTree(cwd, o);
549
+ const events = readStatusEvents(where.status);
550
+ if (o.squashSha !== undefined && !/^[0-9a-f]{7,40}$/.test(o.squashSha))
551
+ throw new CommandError(EXIT.USAGE, `--squash-sha "${o.squashSha}" is not a commit sha`);
552
+ // Graded first, so the report below carries this run's grade.
553
+ const violations = gradeCompliance(where.tree, workflow, log);
554
+ const step = `${workflow}-close-workflow`;
555
+ if (o.recordStep === true) {
556
+ writeStepRow(where.tree, { file: where.status, workflow, step, artifacts: [], commit: "none" }, log);
557
+ }
558
+ const row = { type: "workflow-done", workflow, at: statusTimestamp() };
559
+ fs.appendFileSync(where.status, appendLine(row));
560
+ const repo = resolveRepoSlug(where.root) || "unknown/repo";
561
+ const bkitVersion = readBkitVersion(path.join(where.root, ".bkit", "version"))?.pinnedVersion || "unknown";
562
+ const parentSha = headSha(where.tree);
563
+ const started = lastOfType(events, "workflow-started", workflow);
564
+ const startAt = started?.at;
565
+ const startMs = startAt ? Date.parse(startAt) : NaN;
566
+ const startKnown = Number.isFinite(startMs) ? startMs : undefined;
567
+ const planSource = events
568
+ .filter((e) => e.type === "workflow-meta" &&
569
+ e.workflow === workflow &&
570
+ (startAt === undefined || e.at >= startAt) &&
571
+ e.planSource)
572
+ .at(-1);
573
+ const base = typeof started?.parentSha === "string" ? started.parentSha : "";
574
+ const range = o.squashSha
575
+ ? `${o.squashSha}^..${o.squashSha}`
576
+ : base
577
+ ? `${base}..HEAD`
578
+ : "origin/dev...HEAD";
579
+ const durationSeconds = startKnown === undefined ? 0 : Math.max(0, Math.floor((Date.now() - startKnown) / 1000));
580
+ const startedRows = new Set(events.filter((e) => e.type === "workflow-started" && e.workflow === workflow).map((e) => e.at)).size;
581
+ const ts = Date.now();
582
+ const counterRow = {
583
+ ts,
584
+ kind: "counter",
585
+ workflow,
586
+ repo,
587
+ bkitVersion,
588
+ step,
589
+ counterName: `${workflow.toUpperCase()}_ATTEMPT`,
590
+ counterValue: Math.max(1, startedRows),
591
+ counterSource: "shell-bus",
592
+ parentSha,
593
+ };
594
+ const cov = workflow === "ship" ? coverage(where.tree) : undefined;
595
+ const outcomeRow = {
596
+ ts: ts + 1,
597
+ kind: "outcome",
598
+ workflow,
599
+ repo,
600
+ bkitVersion,
601
+ step,
602
+ parentSha,
603
+ ...(o.prNumber === undefined ? {} : { prNumber: o.prNumber }),
604
+ ...diffStat(where.tree, range),
605
+ taskCount: taskCount(where.tree, where.month, o.fid),
606
+ durationSeconds,
607
+ ...ledgerCounts(where.tree, workflow, startKnown),
608
+ ...(planSource?.planSource ? { planSource: planSource.planSource } : {}),
609
+ ...(cov ? { coverage: cov } : {}),
610
+ };
611
+ const stats = path.join(where.tree, ".bkit", "stats.jsonl");
612
+ const telemetryWritten = appendStats(stats, [counterRow, outcomeRow], log);
613
+ const report = fs.existsSync(stats)
614
+ ? workflowTelemetry(foldFrom([stats]), workflow).lines
615
+ : ["[bkit-telemetry] stats.jsonl not found — no telemetry rows yet"];
616
+ const ref = o.ref ??
617
+ (["design", "plan", "ship"].includes(workflow)
618
+ ? "dev"
619
+ : (git(cwd, ["branch", "--show-current"]) ?? "HEAD"));
620
+ const artifacts = artifactLinks(where.root, ref, where.month, o.fid, workflow, o.ownerRepo ?? repo);
621
+ let comment = null;
622
+ if (o.outbox !== undefined) {
623
+ const outbox = path.resolve(cwd, o.outbox);
624
+ fs.mkdirSync(outbox, { recursive: true });
625
+ fs.writeFileSync(path.join(outbox, ARTIFACTS_FILE), `${linkLines(artifacts)}\n`);
626
+ fs.writeFileSync(path.join(outbox, TELEMETRY_FILE), `${report.join("\n")}\n`);
627
+ if (o.number !== undefined) {
628
+ if (o.title === undefined)
629
+ throw new CommandError(EXIT.USAGE, "--number needs --title");
630
+ comment = closeComment(where.tree, outbox, {
631
+ number: o.number,
632
+ title: o.title,
633
+ tree: o.tree,
634
+ ownerRepo: o.ownerRepo,
635
+ });
636
+ }
637
+ }
638
+ else if (o.number !== undefined) {
639
+ throw new CommandError(EXIT.USAGE, "--number needs --outbox (the comment's sections live there)");
640
+ }
641
+ let commit = null;
642
+ if (o.message !== undefined) {
643
+ let message = o.message;
644
+ if (o.verboseCiLocal === true &&
645
+ runOrStepField(readRuns(where.status), workflow, "pushMode") === "LOCAL")
646
+ message += " bkit [verbose ci]";
647
+ if ((o.labels ?? []).includes(AUTO_LABEL))
648
+ message += AUTO_ROUTE_SUFFIX;
649
+ const add = runGit(where.tree, ["add", "-A"]);
650
+ const made = add.ok ? runGit(where.tree, ["commit", "--allow-empty", "-m", message]) : add;
651
+ if (!made.ok)
652
+ throw new CommandError(EXIT.NO, `close commit failed: ${made.stderr || made.stdout}`);
653
+ commit = headSha(where.tree);
654
+ }
655
+ return {
656
+ row,
657
+ counterRow: validate(counterRow).ok ? counterRow : null,
658
+ outcomeRow: validate(outcomeRow).ok ? outcomeRow : null,
659
+ telemetryWritten,
660
+ compliance: violations === null ? null : violations.length,
661
+ report,
662
+ artifacts,
663
+ artifactLinks: linkLines(artifacts),
664
+ parentSha,
665
+ commit,
666
+ comment,
667
+ roadmapFoldNeeded: true,
668
+ featureStatus: FEATURE_STATUS[workflow],
669
+ };
670
+ }
671
+ /**
672
+ * Ship's close: under the dev lock, on dev (this runtime pushes it) or on a
673
+ * detached `origin/dev` worktree in the outbox (it does not), run the close, commit
674
+ * `docs({fid}): ship DONE bkit [skip ci]`, release the workflow lock, then land the
675
+ * commit — push dev, push `HEAD:dev`, or, when that is refused, a `ship-close/{fid}`
676
+ * PR merged with an empty body.
677
+ */
678
+ async function shipClose(ctx, o, token) {
679
+ const root = repoRoot(ctx.cwd);
680
+ const outbox = o.outbox === undefined ? undefined : path.resolve(ctx.cwd, o.outbox);
681
+ if (outbox === undefined)
682
+ throw new CommandError(EXIT.USAGE, "--flush needs --outbox");
683
+ const month = resolveMonth(root, o.fid, o.month);
684
+ const lock = await acquireDevLock({
685
+ cwd: root,
686
+ workflow: "ship",
687
+ fid: o.fid,
688
+ deadlineS: TIMEOUTS.SHIP_DEV_LOCK_ACQUIRE_DEADLINE_S,
689
+ log: ctx.log,
690
+ });
691
+ const fail = (why) => {
692
+ ctx.log(why);
693
+ return { code: EXIT_FLUSH_FAILED, out: null };
694
+ };
695
+ let closeRoot = "";
696
+ let landed = null;
697
+ let out = {};
698
+ try {
699
+ let wt;
700
+ if (o.devPushes) {
701
+ runGit(root, ["checkout", "dev"]);
702
+ if (git(root, ["branch", "--show-current"]) !== "dev")
703
+ return fail("not on dev after checkout — aborting dev ops");
704
+ wt = root;
705
+ }
706
+ else {
707
+ ctx.log("RUNTIME_DEVPUSHES=false — the close commit lands through a detached origin/dev worktree");
708
+ wt = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
709
+ }
710
+ out = closeWorkflow(wt, { ...o, recordStep: true, message: undefined }, ctx.log);
711
+ if (o.devPushes) {
712
+ closeRoot = wt;
713
+ }
714
+ else {
715
+ if (!runGit(wt, ["fetch", "origin", "dev"]).ok)
716
+ return fail(`fetch origin dev failed — close bookkeeping left uncommitted in ${wt}`);
717
+ closeRoot = path.join(outbox, "close");
718
+ if (fs.existsSync(closeRoot))
719
+ runGit(wt, ["worktree", "remove", "--force", closeRoot]);
720
+ runGit(wt, ["worktree", "prune"]);
721
+ if (!runGit(wt, ["worktree", "add", "--detach", closeRoot, "origin/dev"]).ok)
722
+ return fail(`close worktree add failed — close bookkeeping left uncommitted in ${wt}`);
723
+ unionLedgers(wt, closeRoot);
724
+ }
725
+ commitBookkeeping({
726
+ root: closeRoot,
727
+ month,
728
+ fid: o.fid,
729
+ scope: "full",
730
+ mode: "commit-allow-empty",
731
+ message: `docs(${o.fid}): ship DONE bkit [skip ci]`,
732
+ }, ctx.log);
733
+ const released = releaseLock(workflowLockPath(lockRoot(ctx.cwd, "ship", o.devPushes), month, o.fid), { workflow: "ship", fid: o.fid, token });
734
+ if (released.removeFailed)
735
+ return fail("Lock removal failed");
736
+ if (o.devPushes) {
737
+ if (!runGit(closeRoot, ["push", "origin", "dev"]).ok) {
738
+ ctx.log("dev push failed");
739
+ return { code: EXIT_PUSH_FAILED, out };
740
+ }
741
+ landed = { ref: "dev", via: "dev-push" };
742
+ }
743
+ }
744
+ finally {
745
+ releaseLock(lock.path, { workflow: "ship", fid: o.fid, token: lock.token });
746
+ }
747
+ if (!o.devPushes) {
748
+ if (runGit(closeRoot, ["push", "origin", "HEAD:dev"]).ok) {
749
+ landed = { ref: "dev", via: "head-push" };
750
+ }
751
+ else {
752
+ // dev refused the push: publish the close commit through its own PR.
753
+ const branch = `ship-close/${o.fid}`;
754
+ const head = headSha(closeRoot);
755
+ if (!runGit(closeRoot, ["push", "origin", `HEAD:refs/heads/${branch}`]).ok)
756
+ return fail(`close branch push failed — close bookkeeping left in ${closeRoot}`);
757
+ const created = runGh(closeRoot, [
758
+ "pr",
759
+ "create",
760
+ "--base",
761
+ "dev",
762
+ "--head",
763
+ branch,
764
+ "--title",
765
+ `docs(${o.fid}): ship DONE`,
766
+ "--body",
767
+ "",
768
+ ]);
769
+ if (!created.ok)
770
+ return fail(`gh pr create failed: ${created.stderr}`);
771
+ const pr = probePr(closeRoot, { head: branch, base: "dev", state: "open" });
772
+ const number = pr.kind === "ok" ? pr.pr?.number : undefined;
773
+ if (number === undefined)
774
+ return fail(`close PR not found for ${branch}`);
775
+ const merged = mergePr(closeRoot, {
776
+ number: String(number),
777
+ subject: `docs(${o.fid}): ship DONE bkit [skip ci]`,
778
+ matchHead: head,
779
+ deleteBranch: true,
780
+ }, ctx.log);
781
+ if (!merged.out.merged)
782
+ ctx.log(`close PR #${number} opened but not merged — merge it by hand`);
783
+ landed = { ref: branch, via: merged.out.merged ? "close-pr" : "close-pr-open" };
784
+ }
785
+ const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
786
+ runGit(top, ["worktree", "remove", "--force", closeRoot]);
787
+ runGit(top, ["worktree", "prune"]);
788
+ }
789
+ return { code: EXIT.OK, out: { ...out, closeRoot, landed } };
790
+ }
791
+ // ---------------------------------------------------------------------------
792
+ // promote
793
+ // ---------------------------------------------------------------------------
794
+ /** The highest `{workflow}-v{N}-*.md` draft (sub-plan children `-v{N}-{k}.md` excluded), or null. */
795
+ export function highestVersion(dir, workflow) {
796
+ if (!fs.existsSync(dir))
797
+ return null;
798
+ const re = new RegExp(`^${workflow}-v([0-9]+)-(.+)\\.md$`);
799
+ let best = null;
800
+ for (const f of fs.readdirSync(dir).sort()) {
801
+ const m = re.exec(f);
802
+ if (!m || /^[0-9]+$/.test(m[2]))
803
+ continue;
804
+ const n = Number(m[1]);
805
+ if (best === null || n > best.n)
806
+ best = { file: f, n };
807
+ }
808
+ return best;
809
+ }
810
+ /** Stamp `file`'s anchor when a base commit is known (plan: with its design's own anchor). */
811
+ function stamp(cwd, file, baseSha, design) {
812
+ if (baseSha === "")
813
+ return;
814
+ const abs = path.resolve(cwd, file);
815
+ const designAbs = design === undefined ? undefined : path.resolve(cwd, design);
816
+ const d = design !== undefined && designAbs !== undefined && fs.existsSync(designAbs)
817
+ ? { path: design, baseSha: readAnchor(fs.readFileSync(designAbs, "utf-8")).baseSha ?? "" }
818
+ : undefined;
819
+ const tmp = `${abs}.bkit-anchor.tmp`;
820
+ fs.writeFileSync(tmp, stampAnchor(fs.readFileSync(abs, "utf-8"), baseSha, d));
821
+ fs.renameSync(tmp, abs);
822
+ }
823
+ function promoteVerb(ctx) {
824
+ const workflow = String(ctx.flags.workflow);
825
+ if (!["design", "plan"].includes(workflow))
826
+ throw new CommandError(EXIT.USAGE, "--workflow must be design or plan");
827
+ const fid = String(ctx.flags.fid);
828
+ const month = resolveMonth(repoRoot(ctx.cwd), fid, str(ctx.flags.month));
829
+ const logs = logDirRel(month, fid);
830
+ const best = highestVersion(path.resolve(ctx.cwd, logs), workflow);
831
+ if (best === null) {
832
+ ctx.log(`no ${workflow}-v*.md under ${logs}`);
833
+ return EXIT_NO_VERSION;
834
+ }
835
+ const final = path.join(logs, best.file);
836
+ if (ctx.flags.resolve === true) {
837
+ ctx.emit({ final, canonical: null, archived: [], subPlans: [], baseSha: null });
838
+ return EXIT.OK;
839
+ }
840
+ // The base commit Step 2 recorded on the runtime-resolved row.
841
+ const statusRel = str(ctx.flags.file) ?? path.join(logs, "status.jsonl");
842
+ const statusAbs = path.resolve(ctx.cwd, statusRel);
843
+ const runtime = fs.existsSync(statusAbs)
844
+ ? readStatusRows(statusAbs)
845
+ .filter((r) => r.type === "runtime-resolved")
846
+ .at(-1)
847
+ : undefined;
848
+ const baseSha = typeof runtime?.baseSha === "string" ? runtime.baseSha : "";
849
+ if (runtime === undefined)
850
+ ctx.log("no runtime-resolved row — the canonical doc carries no anchor");
851
+ const design = workflow === "plan" ? path.join("docs", "plans", month, `${fid}-design.md`) : undefined;
852
+ const bucket = path.join("docs", "plans", month);
853
+ const canonical = path.join(bucket, `${fid}-${workflow}.md`);
854
+ stamp(ctx.cwd, final, baseSha, design);
855
+ const children = workflow === "plan"
856
+ ? fs
857
+ .readdirSync(path.resolve(ctx.cwd, logs))
858
+ .filter((f) => new RegExp(`^plan-v${best.n}-[0-9]+\\.md$`).test(f))
859
+ .sort()
860
+ : [];
861
+ // A changed canonical moves to archive/ first — plan moves the whole set under one timestamp.
862
+ const archived = [];
863
+ const canonicalAbs = path.resolve(ctx.cwd, canonical);
864
+ if (fs.existsSync(canonicalAbs) &&
865
+ !fs.readFileSync(canonicalAbs).equals(fs.readFileSync(path.resolve(ctx.cwd, final)))) {
866
+ const ts = new Date()
867
+ .toISOString()
868
+ .replace(/[-:]/g, "")
869
+ .replace(/\.\d+Z$/, "Z");
870
+ const archive = path.join(bucket, "archive");
871
+ fs.mkdirSync(path.resolve(ctx.cwd, archive), { recursive: true });
872
+ const set = fs
873
+ .readdirSync(path.resolve(ctx.cwd, bucket))
874
+ .filter((f) => workflow === "plan"
875
+ ? f === `${fid}-plan.md` || new RegExp(`^${fid}-plan-[0-9]+\\.md$`).test(f)
876
+ : f === `${fid}-design.md`);
877
+ for (const f of set) {
878
+ const to = path.join(archive, `${ts}-${f}`);
879
+ fs.renameSync(path.resolve(ctx.cwd, bucket, f), path.resolve(ctx.cwd, to));
880
+ archived.push(to);
881
+ }
882
+ }
883
+ fs.mkdirSync(path.resolve(ctx.cwd, bucket), { recursive: true });
884
+ fs.copyFileSync(path.resolve(ctx.cwd, final), canonicalAbs);
885
+ const subPlans = [];
886
+ for (const child of children) {
887
+ const k = /-([0-9]+)\.md$/.exec(child)[1];
888
+ stamp(ctx.cwd, path.join(logs, child), baseSha, design);
889
+ const to = path.join(bucket, `${fid}-plan-${k}.md`);
890
+ fs.copyFileSync(path.resolve(ctx.cwd, logs, child), path.resolve(ctx.cwd, to));
891
+ subPlans.push(to);
892
+ }
893
+ if (workflow === "plan") {
894
+ // Working names in the copies become the canonical names.
895
+ for (const f of [canonical, ...subPlans]) {
896
+ const abs = path.resolve(ctx.cwd, f);
897
+ fs.writeFileSync(abs, fs
898
+ .readFileSync(abs, "utf-8")
899
+ .replace(/plan-v[0-9]+-split\.md/g, `${fid}-plan.md`)
900
+ .replace(/plan-v[0-9]+-([0-9]+)\.md/g, `${fid}-plan-$1.md`));
901
+ }
902
+ }
903
+ if (fs.statSync(canonicalAbs).size === 0) {
904
+ ctx.log(`canonical empty: ${canonical}`);
905
+ return EXIT_NO_VERSION;
906
+ }
907
+ ctx.emit({ final, canonical, archived, subPlans, baseSha: baseSha || null });
908
+ return EXIT.OK;
909
+ }
910
+ // ---------------------------------------------------------------------------
911
+ // Command
912
+ // ---------------------------------------------------------------------------
913
+ const FID_FLAG = { name: "fid", type: "string", required: true, help: "feature id" };
914
+ const MONTH_FLAG = {
915
+ name: "month",
916
+ type: "string",
917
+ help: "month bucket YYYYMM (default: the feature's bucket, else this UTC month)",
918
+ };
919
+ const DEV_PUSHES_FLAG = {
920
+ name: "dev-pushes",
921
+ type: "boolean",
922
+ help: "ship only: this runtime pushes to dev (logs book in the main checkout)",
923
+ };
924
+ const STATUS_FILE_FLAG = {
925
+ name: "file",
926
+ type: "string",
927
+ help: "path to status.jsonl (default: derived from --workflow, --fid, --month)",
928
+ };
929
+ const TOKEN_FLAG = {
930
+ name: "token",
931
+ type: "string",
932
+ help: "the lock token `bkit locks acquire` returned (default: match workflow and fid)",
933
+ };
934
+ const OWNER_REPO_FLAG = {
935
+ name: "owner-repo",
936
+ type: "string",
937
+ help: "owner/repo for links (default: from the origin remote)",
938
+ };
939
+ const COMMENT_FLAGS = [
940
+ { name: "number", type: "string", help: "step number: print the close comment (needs --outbox)" },
941
+ { name: "title", type: "string", help: "step title of the close comment" },
942
+ ];
943
+ export const workflowsCommand = {
944
+ noun: "workflows",
945
+ summary: "Start, fail, hand over and close a phase workflow run; promote and link its documents.",
946
+ verbs: {
947
+ start: {
948
+ summary: "Take the feature lock and open a run (workflow-started unless resuming).",
949
+ flags: [
950
+ WORKFLOW_FLAG,
951
+ FID_FLAG,
952
+ MONTH_FLAG,
953
+ DEV_PUSHES_FLAG,
954
+ STATUS_FILE_FLAG,
955
+ {
956
+ name: "lock-held",
957
+ type: "boolean",
958
+ help: "Step 1 already took the lock: check it is ours instead of acquiring",
959
+ },
960
+ TOKEN_FLAG,
961
+ ],
962
+ output: {
963
+ lock: "{path, month, token, reclaimed} of the lock taken, or {path} with --lock-held",
964
+ file: "absolute path to status.jsonl",
965
+ resumed: "the latest run was this workflow, IN_PROGRESS: no new row",
966
+ row: "the appended workflow-started row, or null when resuming",
967
+ run: "which run of the workflow this is (1-based)",
968
+ },
969
+ exitCodes: {
970
+ [EXIT_NO_STATUS]: "status.jsonl is not valid",
971
+ [EXIT_SPLIT_BUCKET]: "the feature has logs in more than one month bucket",
972
+ [EXIT_LOCK_NOT_HELD]: "--lock-held: the lock is missing or belongs to another owner",
973
+ },
974
+ run: (ctx) => {
975
+ const workflow = workflowName(String(ctx.flags.workflow));
976
+ const fid = String(ctx.flags.fid);
977
+ const devPushes = ctx.flags.devPushes === true;
978
+ const token = str(ctx.flags.token);
979
+ if (token !== undefined && ctx.flags.lockHeld !== true)
980
+ throw new CommandError(EXIT.USAGE, "--token applies with --lock-held only");
981
+ const where = whereInTree(ctx.cwd, {
982
+ workflow,
983
+ fid,
984
+ month: str(ctx.flags.month),
985
+ devPushes,
986
+ file: str(ctx.flags.file),
987
+ });
988
+ let lock;
989
+ if (ctx.flags.lockHeld === true) {
990
+ const file = workflowLockPath(lockRoot(ctx.cwd, workflow, devPushes), where.month, fid);
991
+ checkHeldLock(file, { workflow, fid, token });
992
+ lock = { path: file };
993
+ }
994
+ else {
995
+ lock = {
996
+ ...acquireWorkflowLock({
997
+ cwd: ctx.cwd,
998
+ workflow,
999
+ fid,
1000
+ month: where.month,
1001
+ devPushes,
1002
+ log: ctx.log,
1003
+ }),
1004
+ };
1005
+ }
1006
+ const file = where.status;
1007
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1008
+ if (!fs.existsSync(file))
1009
+ fs.writeFileSync(file, "");
1010
+ const latest = fold(readStatusEvents(file)).at(-1);
1011
+ const resumed = latest?.workflow === workflow && latest.status === "IN_PROGRESS";
1012
+ let row = null;
1013
+ if (!resumed) {
1014
+ row = {
1015
+ type: "workflow-started",
1016
+ workflow,
1017
+ at: statusTimestamp(),
1018
+ parentSha: headSha(path.dirname(file)),
1019
+ };
1020
+ fs.appendFileSync(file, appendLine(row));
1021
+ }
1022
+ ctx.emit({
1023
+ lock,
1024
+ file,
1025
+ resumed,
1026
+ row,
1027
+ run: runNumber(fold(readStatusEvents(file)), workflow),
1028
+ });
1029
+ return EXIT.OK;
1030
+ },
1031
+ },
1032
+ fail: {
1033
+ summary: "Failure Path: workflow-failed row, abort rebase, release lock, clear sentinels (with --token); the bkit:failed labels and the failure comment.",
1034
+ flags: [
1035
+ WORKFLOW_FLAG,
1036
+ { ...FID_FLAG, required: false, help: "feature id (needed with --token)" },
1037
+ MONTH_FLAG,
1038
+ DEV_PUSHES_FLAG,
1039
+ STATUS_FILE_FLAG,
1040
+ {
1041
+ ...TOKEN_FLAG,
1042
+ help: "the lock token Step 1 took; without it nothing is written or released (the run never locked)",
1043
+ },
1044
+ {
1045
+ name: "max-exceeded",
1046
+ type: "boolean",
1047
+ help: "the failure is a MAX_* attempt limit being exceeded (a handover is due)",
1048
+ },
1049
+ {
1050
+ name: "label",
1051
+ type: "string",
1052
+ repeatable: true,
1053
+ help: "a label the issue carries now (labels: those plus bkit:failed)",
1054
+ },
1055
+ {
1056
+ name: "pr",
1057
+ type: "string",
1058
+ help: "ship: the PR number; a MERGED PR moves the issue to bkit:merged as well",
1059
+ },
1060
+ {
1061
+ name: "step-number",
1062
+ type: "string",
1063
+ help: "the failed step's number: print the failure comment",
1064
+ },
1065
+ { name: "step-title", type: "string", help: "the failed step's title" },
1066
+ { name: "sub-step", type: "string", help: "the failed sub-step" },
1067
+ {
1068
+ name: "error-file",
1069
+ type: "string",
1070
+ help: "file holding the error message / tool response for the comment",
1071
+ },
1072
+ { name: "error", type: "string", help: "the error text, when there is no --error-file" },
1073
+ {
1074
+ name: "stderr-file",
1075
+ type: "string",
1076
+ help: "the failed shell command's stderr (last 20 lines kept)",
1077
+ },
1078
+ ],
1079
+ output: {
1080
+ row: "the appended workflow-failed row, or null (no --token, or no status.jsonl)",
1081
+ rebaseAborted: "an in-progress rebase was found and aborted",
1082
+ lock: "{path, existed, released, heldBy}: heldBy is another owner's lock line, left in place; null without --token",
1083
+ sentinels: "[{name, path}] sentinels that existed before this call removed them",
1084
+ handoverNeeded: "--max-exceeded, a sentinel existed, or a debug run in SOAK mode: write the abort handover",
1085
+ labels: "the label set to write: the current labels plus bkit:failed (and bkit:merged for a merged ship PR)",
1086
+ linearState: "the Linear state for the failed issue",
1087
+ prState: "the --pr PR's state, or null",
1088
+ comment: "the failure comment body (with --step-number), else null",
1089
+ },
1090
+ exitCodes: {
1091
+ [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1092
+ [EXIT_REMOVE_FAILED]: "the lock file is still there after removing it (everything else was done; the comment says so)",
1093
+ },
1094
+ run: failVerb,
1095
+ },
1096
+ handover: {
1097
+ summary: "After the handover subagent: commit and abort-push it (--push), or ship's one-commit flush (--flush); print the handover comment.",
1098
+ flags: [
1099
+ WORKFLOW_FLAG,
1100
+ FID_FLAG,
1101
+ MONTH_FLAG,
1102
+ {
1103
+ name: "push",
1104
+ type: "boolean",
1105
+ help: "git add -A, commit `docs({fid}): {workflow} aborted bkit [skip ci]`, push --mode=abort",
1106
+ },
1107
+ {
1108
+ name: "flush",
1109
+ type: "boolean",
1110
+ help: "ship: copy the worktree's logs and ledgers into the book root, ONE FAILED commit, ONE push",
1111
+ },
1112
+ {
1113
+ name: "open-pr",
1114
+ type: "string",
1115
+ help: "--push: the open-PR answer from MCP (a number, or none) instead of asking gh",
1116
+ },
1117
+ { name: "ref", type: "string", help: "link the handover at this ref (no push / flush)" },
1118
+ DEV_PUSHES_FLAG,
1119
+ {
1120
+ name: "worktree",
1121
+ type: "string",
1122
+ help: "ship: the worktree holding the handover and the branch-side logs (default: cwd / .worktrees/{fid})",
1123
+ },
1124
+ OWNER_REPO_FLAG,
1125
+ ],
1126
+ output: {
1127
+ handover: "the handover artifact, or null when absent",
1128
+ pushed: "the push (or flush push) ran and succeeded",
1129
+ ref: "where the handover now lives, or null when nothing was pushed",
1130
+ skipped: "why nothing was pushed: open-pr | skip-ci | dev-lock-busy | nothing-to-commit (null otherwise)",
1131
+ comment: "the handover comment body (null when there is no handover); links only when pushed",
1132
+ },
1133
+ exitCodes: {
1134
+ [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1135
+ [EXIT_HANDOVER_MISSING]: "--push: the handover artifact is missing or empty (nothing committed)",
1136
+ [EXIT_OPEN_PR_KEPT]: "--push: the branch has an open PR, nothing pushed (the comment has no link)",
1137
+ [EXIT_PUSH_FAILED]: "the push failed (the comment has no link)",
1138
+ [EXIT_FLUSH_FAILED]: "--flush: not on dev after checkout, detached HEAD, or the FAILED commit failed",
1139
+ },
1140
+ run: handoverVerb,
1141
+ },
1142
+ close: {
1143
+ summary: "Grade compliance, workflow-done row, counter + outcome telemetry, report, artifact links; --flush lands ship's close on dev.",
1144
+ flags: [
1145
+ WORKFLOW_FLAG,
1146
+ FID_FLAG,
1147
+ MONTH_FLAG,
1148
+ DEV_PUSHES_FLAG,
1149
+ STATUS_FILE_FLAG,
1150
+ {
1151
+ name: "pr-number",
1152
+ type: "string",
1153
+ help: "ship: the merged PR number (outcome row prNumber)",
1154
+ },
1155
+ {
1156
+ name: "squash-sha",
1157
+ type: "string",
1158
+ help: "ship: the PR's squash commit; size is measured over it (default: run start..HEAD)",
1159
+ },
1160
+ {
1161
+ name: "ref",
1162
+ type: "string",
1163
+ help: "branch the artifact links point at (default: dev for design / plan / ship, else the current branch)",
1164
+ },
1165
+ OWNER_REPO_FLAG,
1166
+ {
1167
+ name: "outbox",
1168
+ type: "string",
1169
+ help: "write close-artifacts.md and close-telemetry.md here, for the close comment",
1170
+ },
1171
+ {
1172
+ name: "record-step",
1173
+ type: "boolean",
1174
+ help: "append the {workflow}-close-workflow step-done row first",
1175
+ },
1176
+ {
1177
+ name: "message",
1178
+ type: "string",
1179
+ help: "then git add -A and commit with this message in the tree",
1180
+ },
1181
+ {
1182
+ name: "label",
1183
+ type: "string",
1184
+ repeatable: true,
1185
+ help: "a label the issue carries now: bkit:auto appends ` bkit [auto route]` to --message",
1186
+ },
1187
+ {
1188
+ name: "verbose-ci-local",
1189
+ type: "boolean",
1190
+ help: "append ` bkit [verbose ci]` to --message when the run's pushMode is LOCAL",
1191
+ },
1192
+ ...COMMENT_FLAGS,
1193
+ { name: "tree", type: "string", help: "the close comment links the tree of this ref" },
1194
+ {
1195
+ name: "flush",
1196
+ type: "boolean",
1197
+ help: "ship: under the dev lock, close on dev (or a detached origin/dev worktree), commit `ship DONE`, release the lock (--token), push",
1198
+ },
1199
+ { ...TOKEN_FLAG, help: "--flush: the workflow lock token to release" },
1200
+ ],
1201
+ output: {
1202
+ row: "the appended workflow-done row",
1203
+ counterRow: "the {WORKFLOW}_ATTEMPT counter row written to .bkit/stats.jsonl, or null if invalid",
1204
+ outcomeRow: "the outcome row written to .bkit/stats.jsonl, or null if invalid",
1205
+ telemetryWritten: "the stats rows were appended (false: append failed, logged, close continues)",
1206
+ compliance: "compliance violations graded before the report (null: the grader was unavailable)",
1207
+ report: "this workflow's telemetry report lines, for the close comment",
1208
+ artifacts: "[{name, path, url}] feature docs and this workflow's logs on --ref",
1209
+ artifactLinks: "the same as markdown `- [name](url)` lines",
1210
+ parentSha: "HEAD before the --message commit (the close step's parentSha)",
1211
+ commit: "the --message commit, or null",
1212
+ comment: "the close comment (--number with --outbox), else null",
1213
+ roadmapFoldNeeded: "always true: append the feature row and re-render the board (not run here)",
1214
+ featureStatus: "roadmap status this close moves the feature to",
1215
+ closeRoot: "--flush: the checkout the close commit was made in",
1216
+ landed: "--flush: {ref, via: dev-push | head-push | close-pr | close-pr-open}",
1217
+ },
1218
+ exitCodes: {
1219
+ [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
1220
+ [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1221
+ [EXIT_PUSH_FAILED]: "--flush: the dev push failed",
1222
+ [EXIT_FLUSH_FAILED]: "--flush: not on dev after checkout, the dev fetch / close worktree failed, the lock stayed, or the close PR could not be opened",
1223
+ },
1224
+ run: async (ctx) => {
1225
+ const f = ctx.flags;
1226
+ const input = {
1227
+ workflow: String(f.workflow),
1228
+ fid: String(f.fid),
1229
+ month: str(f.month),
1230
+ devPushes: f.devPushes === true,
1231
+ file: str(f.file),
1232
+ prNumber: positiveInt(f.prNumber, "pr-number"),
1233
+ squashSha: str(f.squashSha),
1234
+ ref: str(f.ref),
1235
+ ownerRepo: str(f.ownerRepo),
1236
+ outbox: str(f.outbox),
1237
+ recordStep: f.recordStep === true,
1238
+ message: str(f.message),
1239
+ labels: list(f.label),
1240
+ verboseCiLocal: f.verboseCiLocal === true,
1241
+ number: str(f.number),
1242
+ title: str(f.title),
1243
+ tree: str(f.tree),
1244
+ };
1245
+ if (f.flush === true) {
1246
+ if (input.workflow !== "ship")
1247
+ throw new CommandError(EXIT.USAGE, "--flush is ship only");
1248
+ const r = await shipClose(ctx, input, str(f.token));
1249
+ if (r.out)
1250
+ ctx.emit(r.out);
1251
+ return r.code;
1252
+ }
1253
+ ctx.emit(closeWorkflow(ctx.cwd, input, ctx.log));
1254
+ return EXIT.OK;
1255
+ },
1256
+ },
1257
+ promote: {
1258
+ summary: "Design / plan close: the highest versioned draft becomes the canonical doc (anchor stamped, a changed canonical archived, plan sub-plans copied).",
1259
+ flags: [
1260
+ { ...WORKFLOW_FLAG, help: "design | plan" },
1261
+ FID_FLAG,
1262
+ MONTH_FLAG,
1263
+ {
1264
+ name: "file",
1265
+ type: "string",
1266
+ help: "status.jsonl whose runtime-resolved row holds the base commit (default: in the logs folder)",
1267
+ },
1268
+ {
1269
+ name: "resolve",
1270
+ type: "boolean",
1271
+ help: "only print the highest draft (final); copy nothing",
1272
+ },
1273
+ ],
1274
+ output: {
1275
+ final: "the highest versioned draft, e.g. docs/plans/202610/logs/12-x/design-v3-organised.md",
1276
+ canonical: "the canonical doc written, or null with --resolve",
1277
+ archived: "superseded canonical docs moved to archive/",
1278
+ subPlans: "plan: the canonical sub-plans written",
1279
+ baseSha: "the base commit stamped into the anchor, or null when none was recorded",
1280
+ },
1281
+ exitCodes: {
1282
+ [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1283
+ [EXIT_NO_VERSION]: "no versioned draft to promote, or the canonical came out empty",
1284
+ },
1285
+ run: promoteVerb,
1286
+ },
1287
+ links: {
1288
+ summary: "The feature's docs and this workflow's logs on a ref as markdown links; optionally the close comment.",
1289
+ flags: [
1290
+ WORKFLOW_FLAG,
1291
+ FID_FLAG,
1292
+ MONTH_FLAG,
1293
+ {
1294
+ name: "ref",
1295
+ type: "string",
1296
+ help: "ref to list (default dev; origin/dev lists the remote copy, links still name dev)",
1297
+ },
1298
+ OWNER_REPO_FLAG,
1299
+ {
1300
+ name: "outbox",
1301
+ type: "string",
1302
+ help: "write close-artifacts.md here (beside close's close-telemetry.md)",
1303
+ },
1304
+ ...COMMENT_FLAGS,
1305
+ ],
1306
+ output: {
1307
+ artifacts: "[{name, path, url}]",
1308
+ artifactLinks: "the same as markdown `- [name](url)` lines",
1309
+ comment: "the close comment (--number with --outbox): Artifacts and Telemetry sections, else null",
1310
+ },
1311
+ exitCodes: {
1312
+ [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1313
+ },
1314
+ run: (ctx) => {
1315
+ const workflow = workflowName(String(ctx.flags.workflow));
1316
+ const fid = String(ctx.flags.fid);
1317
+ const root = repoRoot(ctx.cwd);
1318
+ const month = resolveMonth(root, fid, str(ctx.flags.month));
1319
+ const artifacts = artifactLinks(root, str(ctx.flags.ref) ?? "dev", month, fid, workflow, str(ctx.flags.ownerRepo) ?? (resolveRepoSlug(root) || "unknown/repo"));
1320
+ let comment = null;
1321
+ const outbox = str(ctx.flags.outbox);
1322
+ if (outbox !== undefined) {
1323
+ const dir = path.resolve(ctx.cwd, outbox);
1324
+ fs.mkdirSync(dir, { recursive: true });
1325
+ fs.writeFileSync(path.join(dir, ARTIFACTS_FILE), `${linkLines(artifacts)}\n`);
1326
+ const number = str(ctx.flags.number);
1327
+ if (number !== undefined) {
1328
+ const title = str(ctx.flags.title);
1329
+ if (title === undefined)
1330
+ throw new CommandError(EXIT.USAGE, "--number needs --title");
1331
+ comment = closeComment(root, dir, { number, title });
1332
+ }
1333
+ }
1334
+ else if (ctx.flags.number !== undefined) {
1335
+ throw new CommandError(EXIT.USAGE, "--number needs --outbox");
1336
+ }
1337
+ ctx.emit({ artifacts, artifactLinks: linkLines(artifacts), comment });
1338
+ return EXIT.OK;
1339
+ },
1340
+ },
1341
+ },
1342
+ };