@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,1514 @@
1
+ // bkit branches sync|push|rebase|switch|land|anchor-stamp|anchor-read — the
2
+ // branch mechanics every phase workflow repeated inline: bring a feature branch
3
+ // up to date with dev, push it the one safe way for its kind, auto-resolve the
4
+ // rebase conflicts that lose nothing, return the main checkout to dev after a
5
+ // merge, land a design / plan close on dev, and stamp / read the base commit a
6
+ // design or plan doc was written against.
7
+ //
8
+ // Every verb works on `origin` and the integration branch `dev`, as the
9
+ // workflows do. A push is always EXACTLY ONE `git push`: `dev` / `main` get a
10
+ // plain push, every other branch `--force-with-lease`, so a shared branch is
11
+ // never force-pushed and a personal one survives the rebase that rewrote it.
12
+
13
+ import { spawnSync } from "node:child_process";
14
+ import * as fs from "node:fs";
15
+ import * as os from "node:os";
16
+ import * as path from "node:path";
17
+
18
+ import { gitEnv } from "../../ledgers/telemetry.js";
19
+ import {
20
+ bodySkipToken,
21
+ CommandError,
22
+ EXIT,
23
+ git,
24
+ parseJson,
25
+ repoRoot,
26
+ runGit,
27
+ SKIP_CI_TOKEN,
28
+ type CommandSpec,
29
+ type FlagValue,
30
+ type RunContext,
31
+ } from "../lib.js";
32
+ import { TIMEOUTS } from "../../shared/timeouts.js";
33
+ import { commitBookkeeping } from "./ledgers.js";
34
+ import { acquireDevLock, lockRoot, releaseLock, resolveMonth, workflowLockPath } from "./locks.js";
35
+ import { closeTransportRow, crossCheckFile, mergePr, openPrFor, probePr } from "./prs.js";
36
+ import { appendFeature } from "./roadmap.js";
37
+ import { detect } from "./runtime.js";
38
+ import { readStatusRows } from "./status.js";
39
+ import { removeWorktree } from "./worktrees.js";
40
+ import {
41
+ COULD_NOT_RUN_EXIT_CODES,
42
+ LOCKFILE_REGENERATE,
43
+ installCommand,
44
+ } from "../../shared/package-manager.js";
45
+ import { str } from "./status.js";
46
+
47
+ const REMOTE = "origin";
48
+ const DEV = "dev";
49
+ const UPSTREAM = `${REMOTE}/${DEV}`;
50
+ const SHARED_BRANCHES = new Set([DEV, "main"]);
51
+
52
+ /** Exit codes, distinct across verbs so a code means one thing anywhere in this noun. */
53
+ export const EXIT_REFUSED = 3;
54
+ export const EXIT_NO_REBASE = 4;
55
+ export const EXIT_DETACHED = 5;
56
+ export const EXIT_SKIP_CI = 6;
57
+ export const EXIT_OPEN_PR = 7;
58
+ export const EXIT_PUSH_FAILED = 8;
59
+ export const EXIT_NOT_DEV = 9;
60
+ export const EXIT_FETCH_FAILED = 10;
61
+ export const EXIT_MERGE_CONFLICT = 11;
62
+ export const EXIT_ANCHOR_SKIP = 12;
63
+ export const EXIT_NO_FILE = 13;
64
+ export const EXIT_PULL_FAILED = 14;
65
+ export const EXIT_RUNTIME_REFUSED = 15;
66
+ export const EXIT_INSTALL_FAILED = 16;
67
+ export const EXIT_LAND_STOPPED = 17;
68
+ export const EXIT_LANDED_UNVERIFIED = 18;
69
+ export const EXIT_LOCK_LEFT = 19;
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // Process helpers
73
+ // ---------------------------------------------------------------------------
74
+
75
+ /** git with a non-interactive editor, so `--continue` / `--skip` / merge commits never open one. */
76
+ const quietGit = (cwd: string, args: string[]) => {
77
+ const res = spawnSync("git", args, {
78
+ cwd,
79
+ encoding: "utf-8",
80
+ env: { ...gitEnv(), GIT_EDITOR: "true" },
81
+ });
82
+ return {
83
+ ok: res.status === 0,
84
+ stdout: (res.stdout ?? "").trim(),
85
+ stderr: (res.stderr ?? "").trim(),
86
+ };
87
+ };
88
+
89
+ /** `git show :<stage>:<path>` as raw bytes; empty when that stage does not exist. */
90
+ function stageBytes(top: string, stage: 1 | 2 | 3, file: string): Buffer {
91
+ const res = spawnSync("git", ["show", `:${stage}:${file}`], { cwd: top, env: gitEnv() });
92
+ // A missing stage is a legitimate shape (add/add, delete/modify): merge against empty.
93
+ return res.status === 0 ? res.stdout : Buffer.alloc(0);
94
+ }
95
+
96
+ /** Paths still unmerged, NUL-separated so unusual names arrive unquoted. */
97
+ function unmergedPaths(top: string): string[] {
98
+ return (git(top, ["diff", "--name-only", "--diff-filter=U", "-z"]) ?? "")
99
+ .split("\0")
100
+ .filter(Boolean);
101
+ }
102
+
103
+ function rebaseInProgress(top: string): boolean {
104
+ return ["rebase-merge", "rebase-apply"].some((d) => {
105
+ const p = git(top, ["rev-parse", "--git-path", d]);
106
+ return p !== null && fs.existsSync(path.resolve(top, p));
107
+ });
108
+ }
109
+
110
+ const currentBranch = (cwd: string) => git(cwd, ["branch", "--show-current"]) ?? "";
111
+
112
+ const boolString = (v: FlagValue, flag: string): boolean => {
113
+ if (v === "true") return true;
114
+ if (v === "false") return false;
115
+ throw new CommandError(EXIT.USAGE, `--${flag} must be true or false, got "${String(v)}"`);
116
+ };
117
+
118
+ // ---------------------------------------------------------------------------
119
+ // Conflict classification and resolution (rebase, and sync's docs merge)
120
+ // ---------------------------------------------------------------------------
121
+
122
+ /**
123
+ * Ledgers a conflict may be resolved in by union. Each is append-only and its
124
+ * reader folds last-wins by `ts` over an identity tuple, so union loses nothing:
125
+ * interleaved or duplicated rows are resolved by the reader. Same result as
126
+ * `merge=union` in `.gitattributes`, for a repo whose `.gitattributes` lacks a
127
+ * ledger or is missing.
128
+ *
129
+ * `.bkit/friction.jsonl` ships WITHOUT `merge=union` but is listed here; a row union
130
+ * resurrects after `bkit harvest` drained it is re-banked by the next harvest.
131
+ *
132
+ * `docs/roadmap.md` is not append-only — it is regenerated from
133
+ * `.bkit/issues.jsonl` — but every workflow close re-folds it, so both sides of
134
+ * almost any rebase changed it. The duplicated sections a union leaves are erased
135
+ * by the next fold, which rewrites the marker blocks wholesale.
136
+ */
137
+ export const LEDGERS: readonly string[] = [
138
+ "docs/knowledge.jsonl",
139
+ "docs/decisions.jsonl",
140
+ "docs/deferrals.jsonl",
141
+ "docs/failures.jsonl",
142
+ ".bkit/issues.jsonl",
143
+ "docs/roadmap.md",
144
+ ".bkit/stats.jsonl",
145
+ ".bkit/friction.jsonl",
146
+ "docs/plans/**/status.jsonl",
147
+ ];
148
+
149
+ /** `.gitattributes` glob semantics: `**` crosses `/`, `*` stays inside one segment. */
150
+ const globToRegExp = (glob: string) =>
151
+ new RegExp(
152
+ `^${glob
153
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
154
+ .replace(/\*\*/g, "\0")
155
+ .replace(/\*/g, "[^/]*")
156
+ .replace(/\0/g, ".*")}$`,
157
+ );
158
+ const LEDGER_PATTERNS = LEDGERS.map(globToRegExp);
159
+
160
+ export type ConflictKind = "ledger" | "lockfile" | "refuse";
161
+
162
+ /** How a conflicted path may be resolved. Only repo-root lockfiles count: the regenerate runs there. */
163
+ export function classifyConflict(file: string): ConflictKind {
164
+ if (Object.hasOwn(LOCKFILE_REGENERATE, file)) return "lockfile";
165
+ if (LEDGER_PATTERNS.some((re) => re.test(file))) return "ledger";
166
+ return "refuse";
167
+ }
168
+
169
+ /** First-occurrence-wins line de-dup; a non-empty result always ends with a newline. */
170
+ function dedupeLines(text: string): string {
171
+ if (text === "") return "";
172
+ const lines = text.split("\n");
173
+ if (text.endsWith("\n")) lines.pop();
174
+ const seen = new Set<string>();
175
+ const kept = lines.filter((l) => !seen.has(l) && Boolean(seen.add(l)));
176
+ return `${kept.join("\n")}\n`;
177
+ }
178
+
179
+ /**
180
+ * Union-resolve one conflicted ledger in place: rebuild the three stages from the
181
+ * index and run `git merge-file --union`, the driver `merge=union` runs, so the
182
+ * result is byte-identical to the attribute's. JSONL output is checked line by
183
+ * line (a side whose last row lacked a newline can splice two rows into one) and
184
+ * exact duplicates are dropped; prose (`docs/roadmap.md`) is never de-duped.
185
+ */
186
+ export function unionResolve(
187
+ top: string,
188
+ file: string,
189
+ ): { ok: true } | { ok: false; problem: string } {
190
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bkit-union-"));
191
+ try {
192
+ const sides = { base: 1, ours: 2, theirs: 3 } as const;
193
+ for (const [name, stage] of Object.entries(sides)) {
194
+ fs.writeFileSync(path.join(tmp, name), stageBytes(top, stage, file));
195
+ }
196
+ const merged = spawnSync(
197
+ "git",
198
+ [
199
+ "merge-file",
200
+ "--union",
201
+ "-p",
202
+ path.join(tmp, "ours"),
203
+ path.join(tmp, "base"),
204
+ path.join(tmp, "theirs"),
205
+ ],
206
+ { cwd: top, env: gitEnv() },
207
+ );
208
+ // --union never leaves conflict markers, so a non-zero exit is an I/O failure.
209
+ if (merged.status !== 0) return { ok: false, problem: "git merge-file --union failed" };
210
+ let text = merged.stdout.toString("utf-8");
211
+ if (file.endsWith(".jsonl")) {
212
+ if (!text.split("\n").every((l) => l.trim() === "" || parseJson(l).ok)) {
213
+ return { ok: false, problem: "union produced a line that is not valid JSON (torn row?)" };
214
+ }
215
+ text = dedupeLines(text);
216
+ }
217
+ // The next append must start on its own line.
218
+ if (text !== "" && !text.endsWith("\n")) text += "\n";
219
+ fs.writeFileSync(path.join(top, file), text);
220
+ return { ok: true };
221
+ } finally {
222
+ fs.rmSync(tmp, { recursive: true, force: true });
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Resolve a lockfile conflict: start from the rebase target's copy, then
228
+ * regenerate from the manifest, which merged normally (or refused and stopped
229
+ * the rebase before this). During a rebase `--ours` is the branch being rebased
230
+ * ONTO; `--theirs` is the commit being replayed.
231
+ */
232
+ function lockfileResolve(top: string, file: string): boolean {
233
+ const regenerate = LOCKFILE_REGENERATE[file];
234
+ if (!regenerate) return false;
235
+ if (!runGit(top, ["checkout", "--ours", "--", file]).ok) return false;
236
+ const res = spawnSync(regenerate[0]!, regenerate.slice(1), { cwd: top, stdio: "ignore" });
237
+ return res.status === 0;
238
+ }
239
+
240
+ export interface Resolution {
241
+ path: string;
242
+ how: "union" | "lockfile" | "dev";
243
+ }
244
+
245
+ export interface RebaseResult {
246
+ ok: boolean;
247
+ resolved: Resolution[];
248
+ skippedCommits: number;
249
+ rounds: number;
250
+ refused: string | null;
251
+ reason: string | null;
252
+ log: string[];
253
+ }
254
+
255
+ /**
256
+ * Drive an in-progress rebase to completion, auto-resolving each stop. Loops
257
+ * because `--continue` replays the next commit, which can conflict in turn; the
258
+ * bound is a runaway guard. Never aborts: on refusal the rebase is left in
259
+ * progress and `branches rebase` aborts it.
260
+ */
261
+ export function resolveRebase(
262
+ top: string,
263
+ onLog: (line: string) => void = () => undefined,
264
+ ): RebaseResult {
265
+ const result: RebaseResult = {
266
+ ok: false,
267
+ resolved: [],
268
+ skippedCommits: 0,
269
+ rounds: 0,
270
+ refused: null,
271
+ reason: null,
272
+ log: [],
273
+ };
274
+ const log = (line: string) => {
275
+ result.log.push(line);
276
+ onLog(line);
277
+ };
278
+ const refuse = (line: string, refused: string | null, reason: string) => {
279
+ log(line);
280
+ result.refused = refused;
281
+ result.reason = reason;
282
+ return result;
283
+ };
284
+
285
+ while (result.rounds < 100) {
286
+ result.rounds++;
287
+ const conflicts = unmergedPaths(top);
288
+ if (conflicts.length > 0) {
289
+ // Classify the whole set before resolving any of it, so a refused path
290
+ // never leaves half the set rewritten.
291
+ const refused = conflicts.find((f) => classifyConflict(f) === "refuse");
292
+ if (refused !== undefined) {
293
+ return refuse(
294
+ `REFUSE ${refused} — not an append-only ledger or a recognised lockfile; routing to Failure Path`,
295
+ refused,
296
+ "not an append-only ledger or a recognised lockfile",
297
+ );
298
+ }
299
+ for (const f of conflicts) {
300
+ const kind = classifyConflict(f);
301
+ const ok = kind === "ledger" ? unionResolve(top, f).ok : lockfileResolve(top, f);
302
+ if (!ok || !runGit(top, ["add", "--", f]).ok) {
303
+ return refuse(`REFUSE ${f} — resolution failed`, f, "resolution failed");
304
+ }
305
+ result.resolved.push({ path: f, how: kind === "ledger" ? "union" : "lockfile" });
306
+ log(
307
+ kind === "ledger"
308
+ ? `RESOLVED ${f} — union (append-only ledger)`
309
+ : `RESOLVED ${f} — took rebase target + regenerated`,
310
+ );
311
+ }
312
+ }
313
+
314
+ // A resolution can empty the commit (both sides appended the same rows);
315
+ // `--continue` refuses an empty commit, so skip it instead.
316
+ if (runGit(top, ["diff", "--cached", "--quiet"]).ok && unmergedPaths(top).length === 0) {
317
+ const skip = quietGit(top, ["rebase", "--skip"]);
318
+ if (skip.ok || unmergedPaths(top).length > 0) {
319
+ result.skippedCommits++;
320
+ log("SKIPPED an empty commit (its changes were already on the target)");
321
+ // The skip moved on and the next commit conflicted: resolve it next round.
322
+ if (!skip.ok) continue;
323
+ } else {
324
+ return refuse("REFUSE — git rebase --skip failed", null, "git rebase --skip failed");
325
+ }
326
+ } else if (!quietGit(top, ["rebase", "--continue"]).ok) {
327
+ // The next commit conflicted (next round handles it), or the rebase is stuck.
328
+ if (unmergedPaths(top).length === 0) {
329
+ return refuse(
330
+ "REFUSE — git rebase --continue failed with no unmerged paths",
331
+ null,
332
+ "git rebase --continue failed with no unmerged paths",
333
+ );
334
+ }
335
+ continue;
336
+ }
337
+
338
+ if (!rebaseInProgress(top)) {
339
+ log(`COMPLETE — rebase finished after ${result.rounds} auto-resolved round(s)`);
340
+ result.ok = true;
341
+ return result;
342
+ }
343
+ }
344
+ return refuse(
345
+ "REFUSE — exceeded 100 auto-resolve rounds; treating as stuck",
346
+ null,
347
+ "exceeded 100 auto-resolve rounds",
348
+ );
349
+ }
350
+
351
+ // ---------------------------------------------------------------------------
352
+ // Anchor block
353
+ // ---------------------------------------------------------------------------
354
+
355
+ const ANCHOR_OPEN = "<!-- bkit:anchor";
356
+ const ANCHOR_CLOSE = "-->";
357
+ export const ANCHOR_FIELDS = ["baseSha", "baseRef", "designPath", "designBaseSha"] as const;
358
+ export type AnchorField = (typeof ANCHOR_FIELDS)[number];
359
+
360
+ /** Lines of `text` with whether each sits inside an anchor block (a `sed '/open/,/close/'` range). */
361
+ function anchorLines(text: string): Array<{ line: string; inBlock: boolean; last: boolean }> {
362
+ const lines = text.split("\n");
363
+ const trailing = text.endsWith("\n");
364
+ if (trailing) lines.pop();
365
+ let open = false;
366
+ return lines.map((line, i) => {
367
+ // Like sed: the close line is looked for from the line AFTER the open line,
368
+ // and a block never closed runs to the end of the file.
369
+ let inBlock = open;
370
+ if (!open && line === ANCHOR_OPEN) {
371
+ open = true;
372
+ inBlock = true;
373
+ } else if (open && line === ANCHOR_CLOSE) {
374
+ open = false;
375
+ }
376
+ return { line, inBlock, last: i === lines.length - 1 && !trailing };
377
+ });
378
+ }
379
+
380
+ /** Every field in the file's anchor block(s); first occurrence wins, absent fields are omitted. */
381
+ export function readAnchor(text: string): Partial<Record<AnchorField, string>> {
382
+ const out: Partial<Record<AnchorField, string>> = {};
383
+ for (const { line, inBlock } of anchorLines(text)) {
384
+ if (!inBlock) continue;
385
+ for (const field of ANCHOR_FIELDS) {
386
+ if (out[field] === undefined && line.startsWith(`${field}: `))
387
+ out[field] = line.slice(field.length + 2);
388
+ }
389
+ }
390
+ return out;
391
+ }
392
+
393
+ /** `text` with a fresh anchor block on top and every prior one removed, so re-stamping is idempotent. */
394
+ export function stampAnchor(
395
+ text: string,
396
+ baseSha: string,
397
+ design?: { path: string; baseSha: string },
398
+ ): string {
399
+ const header = [ANCHOR_OPEN, `baseSha: ${baseSha}`, `baseRef: ${UPSTREAM}`];
400
+ if (design) header.push(`designPath: ${design.path}`, `designBaseSha: ${design.baseSha}`);
401
+ header.push(ANCHOR_CLOSE);
402
+ const body = anchorLines(text)
403
+ .filter((l) => !l.inBlock)
404
+ .map((l) => (l.last ? l.line : `${l.line}\n`))
405
+ .join("");
406
+ return `${header.join("\n")}\n${body}`;
407
+ }
408
+
409
+ // ---------------------------------------------------------------------------
410
+ // Open-PR probe (push --mode=abort)
411
+ // ---------------------------------------------------------------------------
412
+
413
+ /** The open PR number on `branch`, or null. gh missing or failing → use MCP, never a guess. */
414
+ function openPrNumber(cwd: string, branch: string): number | null {
415
+ const res = spawnSync(
416
+ "gh",
417
+ ["pr", "list", "--head", branch, "--state", "open", "--json", "number,state"],
418
+ {
419
+ cwd,
420
+ encoding: "utf-8",
421
+ },
422
+ );
423
+ const parsed = res.status === 0 ? parseJson(res.stdout ?? "") : { ok: false as const };
424
+ const prs = parsed.ok ? parsed.value : undefined;
425
+ if (!Array.isArray(prs)) {
426
+ const why = res.error
427
+ ? "gh is not available"
428
+ : `gh pr list failed: ${(res.stderr ?? "").trim()}`;
429
+ throw new CommandError(
430
+ EXIT.USE_MCP,
431
+ `${why} — look up the open PR on ${branch} via MCP and re-run with --open-pr=<number>|none`,
432
+ );
433
+ }
434
+ const open = prs.find(
435
+ (p: unknown) =>
436
+ typeof p === "object" && p !== null && (p as { state?: unknown }).state === "OPEN",
437
+ ) as { number?: unknown } | undefined;
438
+ return typeof open?.number === "number" ? open.number : null;
439
+ }
440
+
441
+ // ---------------------------------------------------------------------------
442
+ // Verbs
443
+ // ---------------------------------------------------------------------------
444
+
445
+ function topLevel(cwd: string): string {
446
+ const top = git(cwd, ["rev-parse", "--show-toplevel"]);
447
+ if (!top) throw new CommandError(EXIT.USAGE, `not inside a git work tree: ${cwd}`);
448
+ return top;
449
+ }
450
+
451
+ function appendLog(ctx: RunContext, file: string | undefined, lines: string[]): void {
452
+ if (file === undefined || lines.length === 0) return;
453
+ const abs = path.resolve(ctx.cwd, file);
454
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
455
+ fs.appendFileSync(abs, lines.map((l) => `[bkit-rebase] ${l}\n`).join(""));
456
+ }
457
+
458
+ function rebaseVerb(ctx: RunContext): number {
459
+ const top = topLevel(ctx.cwd);
460
+ const sentinel = str(ctx.flags.sentinel);
461
+ const sentinelPath = sentinel === undefined ? undefined : path.resolve(ctx.cwd, sentinel);
462
+ if (sentinelPath) fs.rmSync(sentinelPath, { force: true });
463
+
464
+ if (!rebaseInProgress(top)) {
465
+ ctx.log("no rebase in progress");
466
+ return EXIT_NO_REBASE;
467
+ }
468
+ const result = resolveRebase(top, (line) => ctx.log(line));
469
+ let aborted = false;
470
+ if (!result.ok) {
471
+ // Abort before the log and sentinel writes: the abort resets tracked files.
472
+ const abort = runGit(top, ["rebase", "--abort"]);
473
+ aborted = abort.ok;
474
+ const line = abort.ok
475
+ ? "ABORTED — git rebase --abort restored the branch"
476
+ : `ABORT FAILED — git rebase --abort: ${abort.stderr}`;
477
+ result.log.push(line);
478
+ ctx.log(line);
479
+ }
480
+ appendLog(ctx, str(ctx.flags.logFile), result.log);
481
+ if (!result.ok && sentinelPath) {
482
+ fs.mkdirSync(path.dirname(sentinelPath), { recursive: true });
483
+ fs.writeFileSync(sentinelPath, "");
484
+ }
485
+ ctx.emit({
486
+ outcome: result.ok ? "resolved" : "refused",
487
+ resolved: result.resolved,
488
+ skippedCommits: result.skippedCommits,
489
+ rounds: result.rounds,
490
+ refused: result.refused,
491
+ reason: result.reason,
492
+ aborted,
493
+ sentinel: !result.ok && sentinel !== undefined ? sentinel : null,
494
+ });
495
+ return result.ok ? EXIT.OK : EXIT_REFUSED;
496
+ }
497
+
498
+ export interface PushOutcome {
499
+ code: number;
500
+ out: {
501
+ pushed: boolean;
502
+ ref: string | null;
503
+ sha: string | null;
504
+ forced: boolean;
505
+ skipped: string | null;
506
+ prNumber: number | null;
507
+ };
508
+ }
509
+
510
+ /**
511
+ * Push the current branch with exactly one `git push`: plain for dev / main,
512
+ * `--force-with-lease` otherwise. `abort` never pushes into an open PR (`openPr`:
513
+ * the answer MCP gave; undefined asks gh, which throws EXIT.USE_MCP when it cannot).
514
+ */
515
+ export function pushBranch(
516
+ cwd: string,
517
+ o: {
518
+ mode: "feature" | "abort" | "dev";
519
+ setUpstream?: boolean;
520
+ requireCi?: boolean;
521
+ openPr?: string;
522
+ },
523
+ log: (m: string) => void,
524
+ ): PushOutcome {
525
+ const { mode, openPr: openPrFlag } = o;
526
+ if (openPrFlag !== undefined && openPrFlag !== "none" && !/^[1-9][0-9]*$/.test(openPrFlag)) {
527
+ throw new CommandError(
528
+ EXIT.USAGE,
529
+ `--open-pr must be a PR number or none, got "${openPrFlag}"`,
530
+ );
531
+ }
532
+ const branch = currentBranch(cwd);
533
+ const notPushed = (code: number, extra: Partial<PushOutcome["out"]> = {}): PushOutcome => ({
534
+ code,
535
+ out: {
536
+ pushed: false,
537
+ ref: null,
538
+ sha: null,
539
+ forced: false,
540
+ skipped: null,
541
+ prNumber: null,
542
+ ...extra,
543
+ },
544
+ });
545
+ if (branch === "") {
546
+ log("no branch checked out (detached HEAD) — refusing to push");
547
+ return notPushed(EXIT_DETACHED);
548
+ }
549
+ if (mode === "dev" && branch !== DEV) {
550
+ log(`--mode=dev pushes ${DEV}, but the checkout is on ${branch}`);
551
+ return notPushed(EXIT_NOT_DEV);
552
+ }
553
+ if (o.requireCi === true) {
554
+ const message = git(cwd, ["log", "-1", "--pretty=%B"]) ?? "";
555
+ if (SKIP_CI_TOKEN.test(message)) {
556
+ log(
557
+ `HEAD message on ${branch} carries a CI-suppressing token, and this push needs a CI run — refusing`,
558
+ );
559
+ return notPushed(EXIT_SKIP_CI, { skipped: "skip-ci" });
560
+ }
561
+ }
562
+ const shared = SHARED_BRANCHES.has(branch);
563
+ if (mode === "abort" && !shared) {
564
+ const pr =
565
+ openPrFlag === undefined
566
+ ? openPrNumber(cwd, branch)
567
+ : openPrFlag === "none"
568
+ ? null
569
+ : Number(openPrFlag);
570
+ if (pr !== null) {
571
+ // CI and the cloud router would run on an abort commit pushed into an open
572
+ // PR; the last validated remote HEAD is kept instead.
573
+ log(`open PR #${pr} on ${branch} — preserving the last validated remote HEAD (no push)`);
574
+ return notPushed(EXIT_OPEN_PR, { skipped: "open-pr", prNumber: pr });
575
+ }
576
+ }
577
+ const args = [
578
+ "push",
579
+ ...(o.setUpstream === true ? ["-u"] : []),
580
+ ...(shared ? [] : ["--force-with-lease"]),
581
+ REMOTE,
582
+ branch,
583
+ ];
584
+ const res = runGit(cwd, args);
585
+ if (!res.ok) {
586
+ log(`git ${args.join(" ")} failed: ${res.stderr}`);
587
+ return notPushed(EXIT_PUSH_FAILED);
588
+ }
589
+ log(`pushed ${branch}${shared ? "" : " (--force-with-lease)"}`);
590
+ return {
591
+ code: EXIT.OK,
592
+ out: {
593
+ pushed: true,
594
+ ref: branch,
595
+ sha: git(cwd, ["rev-parse", "HEAD"]),
596
+ forced: !shared,
597
+ skipped: null,
598
+ prNumber: null,
599
+ },
600
+ };
601
+ }
602
+
603
+ function pushVerb(ctx: RunContext): number {
604
+ const mode = String(ctx.flags.mode);
605
+ if (!["feature", "abort", "dev"].includes(mode)) {
606
+ throw new CommandError(EXIT.USAGE, "--mode must be feature, abort, or dev");
607
+ }
608
+ const r = pushBranch(
609
+ ctx.cwd,
610
+ {
611
+ mode: mode as "feature" | "abort" | "dev",
612
+ setUpstream: ctx.flags.setUpstream === true,
613
+ requireCi: ctx.flags.requireCi === true,
614
+ openPr: str(ctx.flags.openPr),
615
+ },
616
+ ctx.log,
617
+ );
618
+ // A detached HEAD and a wrong checkout print nothing, as the push never got to run.
619
+ if (r.code !== EXIT_DETACHED && r.code !== EXIT_NOT_DEV) ctx.emit(r.out);
620
+ return r.code;
621
+ }
622
+
623
+ /** Resolve sync's docs-merge conflicts: ledgers by union, other `docs/` paths take dev's side. */
624
+ function resolveDocsMerge(top: string): { resolved: Resolution[] } | { refused: string } {
625
+ const conflicts = unmergedPaths(top);
626
+ const refused = conflicts.find((f) => classifyConflict(f) !== "ledger" && !f.startsWith("docs/"));
627
+ if (refused !== undefined) return { refused };
628
+ const resolved: Resolution[] = [];
629
+ for (const f of conflicts) {
630
+ if (classifyConflict(f) === "ledger") {
631
+ if (!unionResolve(top, f).ok || !runGit(top, ["add", "--", f]).ok) return { refused: f };
632
+ resolved.push({ path: f, how: "union" });
633
+ continue;
634
+ }
635
+ // In a merge `--theirs` is the branch merged in: dev. Dev deleting the file
636
+ // leaves no stage 3, and taking dev's side means deleting it here too.
637
+ const devHasIt = runGit(top, ["cat-file", "-e", `:3:${f}`]).ok;
638
+ const ok = devHasIt
639
+ ? runGit(top, ["checkout", "--theirs", "--", f]).ok && runGit(top, ["add", "--", f]).ok
640
+ : runGit(top, ["rm", "-q", "--", f]).ok;
641
+ if (!ok) return { refused: f };
642
+ resolved.push({ path: f, how: "dev" });
643
+ }
644
+ return { resolved };
645
+ }
646
+
647
+ function syncVerb(ctx: RunContext): number {
648
+ const mergeDocs = ctx.flags.mergeDocs === true;
649
+ const headFlag = str(ctx.flags.head);
650
+ if (mergeDocs && headFlag !== undefined) {
651
+ throw new CommandError(
652
+ EXIT.USAGE,
653
+ "--merge-docs merges into HEAD; give --head or --merge-docs, not both",
654
+ );
655
+ }
656
+ const top = topLevel(ctx.cwd);
657
+ const fetch = runGit(top, ["fetch", REMOTE, DEV]);
658
+ if (!fetch.ok) {
659
+ ctx.log(`git fetch ${REMOTE} ${DEV} failed: ${fetch.stderr}`);
660
+ return EXIT_FETCH_FAILED;
661
+ }
662
+ const head = git(top, ["rev-parse", "--verify", "--quiet", `${headFlag ?? "HEAD"}^{commit}`]);
663
+ if (!head)
664
+ throw new CommandError(EXIT.USAGE, `--head ${headFlag ?? "HEAD"} does not name a commit`);
665
+ const branch = currentBranch(top);
666
+
667
+ const ancestor = spawnSync("git", ["merge-base", "--is-ancestor", UPSTREAM, head], {
668
+ cwd: top,
669
+ env: gitEnv(),
670
+ });
671
+ if (ancestor.status !== 0 && ancestor.status !== 1) {
672
+ throw new CommandError(
673
+ EXIT.USAGE,
674
+ `cannot compare ${UPSTREAM} with ${head}: ${String(ancestor.stderr).trim()}`,
675
+ );
676
+ }
677
+ const count = (args: string[]) => Number(git(top, ["rev-list", "--count", ...args]) ?? "0");
678
+ const behind = count([`${head}..${UPSTREAM}`]);
679
+ const docsBehind = count([`${head}..${UPSTREAM}`, "--", "docs/"]);
680
+ const out = {
681
+ branch: branch === "" ? null : branch,
682
+ head,
683
+ basePath: ancestor.status === 0 ? "A" : "B",
684
+ behind,
685
+ docsBehind,
686
+ merged: false,
687
+ resolved: [] as Resolution[],
688
+ };
689
+
690
+ if (mergeDocs) {
691
+ if (branch === "") {
692
+ ctx.log("no branch checked out (detached HEAD) — cannot merge dev's docs");
693
+ return EXIT_DETACHED;
694
+ }
695
+ if (!SHARED_BRANCHES.has(branch) && docsBehind > 0) {
696
+ ctx.log(`docs/ is ${docsBehind} commit(s) behind ${UPSTREAM} — merging it in`);
697
+ if (!quietGit(top, ["merge", "--no-edit", UPSTREAM]).ok) {
698
+ const outcome = resolveDocsMerge(top);
699
+ if ("refused" in outcome) {
700
+ runGit(top, ["merge", "--abort"]);
701
+ ctx.log(
702
+ `merge of ${UPSTREAM} conflicts on ${outcome.refused} — outside docs/, merge aborted`,
703
+ );
704
+ return EXIT_MERGE_CONFLICT;
705
+ }
706
+ if (unmergedPaths(top).length > 0 || !quietGit(top, ["commit", "--no-edit"]).ok) {
707
+ runGit(top, ["merge", "--abort"]);
708
+ ctx.log(`merge of ${UPSTREAM} could not be committed — merge aborted`);
709
+ return EXIT_MERGE_CONFLICT;
710
+ }
711
+ out.resolved = outcome.resolved;
712
+ for (const r of outcome.resolved)
713
+ ctx.log(
714
+ `RESOLVED ${r.path} — ${r.how === "union" ? "union (append-only ledger)" : `took ${DEV}`}`,
715
+ );
716
+ }
717
+ out.merged = true;
718
+ out.head = git(top, ["rev-parse", "HEAD"]) ?? head;
719
+ }
720
+ }
721
+ ctx.emit(out);
722
+ return EXIT.OK;
723
+ }
724
+
725
+ async function switchVerb(ctx: RunContext): Promise<number> {
726
+ const devPushes = boolString(ctx.flags.devPushes, "dev-pushes");
727
+ const worktrees = boolString(ctx.flags.worktrees, "worktrees");
728
+ const root = repoRoot(ctx.cwd);
729
+ // `bkit install` can leave core.bare=true on the main checkout, which breaks every checkout below.
730
+ if (
731
+ git(root, ["config", "--get", "core.bare"]) === "true" &&
732
+ fs.statSync(path.join(root, ".git"), { throwIfNoEntry: false })?.isDirectory()
733
+ ) {
734
+ runGit(root, ["config", "core.bare", "false"]);
735
+ }
736
+ const out = {
737
+ switched: false,
738
+ branch: currentBranch(root),
739
+ ahead: 0,
740
+ pushed: false,
741
+ installed: null as boolean | null,
742
+ skipped: null as string | null,
743
+ };
744
+ if (!devPushes) {
745
+ ctx.log(
746
+ `this runtime does not push ${DEV} — skipping the local ${DEV} checkout; the merge already landed server-side`,
747
+ );
748
+ ctx.emit({ ...out, skipped: "dev-pushes-false" });
749
+ return EXIT.OK;
750
+ }
751
+ if (!worktrees) {
752
+ ctx.log(
753
+ "refusing a local dev checkout in a runtime without worktrees (devPushes=true, worktrees=false)",
754
+ );
755
+ return EXIT_RUNTIME_REFUSED;
756
+ }
757
+ const fid = String(ctx.flags.fid);
758
+ // Still held at the deadline: acquireDevLock throws EXIT.NO naming the holder.
759
+ const lock = await acquireDevLock({
760
+ cwd: root,
761
+ workflow: "ship",
762
+ fid,
763
+ deadlineS: TIMEOUTS.SHIP_DEV_LOCK_ACQUIRE_DEADLINE_S,
764
+ log: ctx.log,
765
+ });
766
+ try {
767
+ runGit(root, ["checkout", DEV]);
768
+ out.branch = currentBranch(root);
769
+ if (out.branch !== DEV) {
770
+ ctx.log(`not on ${DEV} after checkout (on '${out.branch}') — aborting dev ops`);
771
+ return EXIT_NOT_DEV;
772
+ }
773
+ out.switched = true;
774
+ const fetch = runGit(root, ["fetch", REMOTE, DEV]);
775
+ if (!fetch.ok) {
776
+ ctx.log(`git fetch ${REMOTE} ${DEV} failed: ${fetch.stderr}`);
777
+ return EXIT_FETCH_FAILED;
778
+ }
779
+ out.ahead = Number(git(root, ["rev-list", "--count", `${UPSTREAM}..${DEV}`]) ?? "0");
780
+ if (out.ahead > 0) {
781
+ const triggering = (git(root, ["log", "--format=%h %s", `${UPSTREAM}..${DEV}`]) ?? "")
782
+ .split("\n")
783
+ .filter((l) => l !== "" && !SKIP_CI_TOKEN.test(l));
784
+ if (triggering.length > 0) {
785
+ ctx.log(
786
+ `local ${DEV} is ${out.ahead} commit(s) ahead of ${UPSTREAM}, ${triggering.length} of them would run CI:`,
787
+ );
788
+ for (const l of triggering) ctx.log(` ${l}`);
789
+ ctx.log(
790
+ `ship will not push these: a CI run on ${DEV} can cancel the in-flight run validating this merge`,
791
+ );
792
+ ctx.log(
793
+ `reconcile, then re-run ship: git -C "${root}" pull --rebase ${REMOTE} ${DEV} && git -C "${root}" push ${REMOTE} ${DEV}`,
794
+ );
795
+ return EXIT.NEEDS_HUMAN;
796
+ }
797
+ const pull = quietGit(root, ["pull", "--rebase", REMOTE, DEV]);
798
+ if (!pull.ok) {
799
+ ctx.log(`git pull --rebase ${REMOTE} ${DEV} failed: ${pull.stderr}`);
800
+ return EXIT_PULL_FAILED;
801
+ }
802
+ const push = runGit(root, ["push", REMOTE, DEV]);
803
+ if (!push.ok) {
804
+ ctx.log(`git push ${REMOTE} ${DEV} failed: ${push.stderr}`);
805
+ return EXIT_PUSH_FAILED;
806
+ }
807
+ out.pushed = true;
808
+ } else {
809
+ const pull = runGit(root, ["pull", "--ff-only", REMOTE, DEV]);
810
+ if (!pull.ok) {
811
+ ctx.log(`git pull --ff-only ${REMOTE} ${DEV} failed: ${pull.stderr}`);
812
+ return EXIT_PULL_FAILED;
813
+ }
814
+ }
815
+ out.installed = install(ctx, root);
816
+ ctx.emit(out);
817
+ return out.installed === false ? EXIT_INSTALL_FAILED : EXIT.OK;
818
+ } finally {
819
+ releaseLock(lock.path, { workflow: "ship", fid, token: lock.token });
820
+ }
821
+ }
822
+
823
+ /** Frozen install in the main checkout: false (logged) when it failed or could not run, null when there is nothing to install. */
824
+ function install(ctx: RunContext, root: string): boolean | null {
825
+ if (!fs.existsSync(path.join(root, "package.json"))) return null;
826
+ const argv = installCommand({ frozen: true });
827
+ const res = spawnSync(argv[0]!, argv.slice(1), { cwd: root, stdio: "ignore" });
828
+ if (res.status === 0) return true;
829
+ const couldNotRun = res.error !== undefined || COULD_NOT_RUN_EXIT_CODES.has(res.status ?? -1);
830
+ ctx.log(
831
+ couldNotRun
832
+ ? `${argv.join(" ")} could not run — dependencies not installed`
833
+ : `${argv.join(" ")} exited ${String(res.status)} — dependency install failed`,
834
+ );
835
+ return false;
836
+ }
837
+
838
+ // ---------------------------------------------------------------------------
839
+ // land (design / plan close)
840
+ // ---------------------------------------------------------------------------
841
+
842
+ /** What a design / plan close may bring to dev: docs and ledgers, nothing else. */
843
+ const CLOSE_DOCS = /^docs\/plans\/|^docs\/roadmap\.md$|^docs\/[^/]+\.jsonl$|^\.bkit\/[^/]+\.jsonl$/;
844
+
845
+ /** The canonical docs `ref` carries for the feature: design, or plan plus sub-plans. */
846
+ function canonicalDocs(
847
+ root: string,
848
+ ref: string,
849
+ workflow: string,
850
+ month: string,
851
+ fid: string,
852
+ ): string[] {
853
+ const re =
854
+ workflow === "plan"
855
+ ? new RegExp(`^docs/plans/${month}/${fid}-plan(-[0-9]+)?\\.md$`)
856
+ : new RegExp(`^docs/plans/${month}/${fid}-design\\.md$`);
857
+ return (git(root, ["ls-tree", "-r", "--name-only", ref, "--", `docs/plans/${month}/`]) ?? "")
858
+ .split("\n")
859
+ .filter((f) => re.test(f));
860
+ }
861
+
862
+ /** Whether this runtime pushes dev: the run's runtime-resolved row, else a fresh detect. */
863
+ function devPushesOf(root: string, status: string, log: (m: string) => void): boolean {
864
+ const row = fs.existsSync(status)
865
+ ? readStatusRows(status)
866
+ .filter((r) => r.type === "runtime-resolved")
867
+ .at(-1)
868
+ : undefined;
869
+ if (typeof row?.runtimeDevPushes === "boolean") return row.runtimeDevPushes;
870
+ return detect(root, root, log).runtimeDevPushes;
871
+ }
872
+
873
+ interface Landed {
874
+ shape: "local" | "pr";
875
+ transport: "git" | "gh" | "mcp";
876
+ sha: string;
877
+ canonicalRef: string;
878
+ prNumber: number | null;
879
+ worktree: Record<string, unknown> | null;
880
+ }
881
+
882
+ class Stop extends CommandError {}
883
+
884
+ /**
885
+ * The local close: under the dev lock, squash `feat/{fid}` into dev in the main
886
+ * checkout, check the staged canonical docs are the branch's, commit the
887
+ * bookkeeping plus what the squash brought, push dev, remove the worktree.
888
+ */
889
+ async function landLocal(
890
+ ctx: RunContext,
891
+ root: string,
892
+ o: { workflow: string; fid: string; month: string },
893
+ ): Promise<Landed> {
894
+ const feat = `feat/${o.fid}`;
895
+ const lock = await acquireDevLock({
896
+ cwd: root,
897
+ workflow: o.workflow,
898
+ fid: o.fid,
899
+ deadlineS: TIMEOUTS.SHIP_DEV_LOCK_ACQUIRE_DEADLINE_S,
900
+ log: ctx.log,
901
+ });
902
+ try {
903
+ runGit(root, ["checkout", DEV]);
904
+ const on = currentBranch(root);
905
+ if (on !== DEV)
906
+ throw new Stop(EXIT_NOT_DEV, `not on dev after checkout (on '${on}') — aborting dev ops`);
907
+ const stray = (
908
+ git(root, ["status", "--porcelain", "-uall", "--", `docs/plans/${o.month}/logs/${o.fid}/`]) ??
909
+ ""
910
+ )
911
+ .split("\n")
912
+ .filter((l) => l.startsWith("??"));
913
+ if (stray.length) {
914
+ throw new Stop(
915
+ EXIT_LAND_STOPPED,
916
+ `${o.fid} artifacts written to the main checkout instead of the worktree:\n${stray.join("\n")}\nMove them under .worktrees/${o.fid}/ or delete them, then re-run.`,
917
+ );
918
+ }
919
+ if (!runGit(root, ["pull", "--ff-only", REMOTE, DEV]).ok)
920
+ throw new Stop(EXIT_PULL_FAILED, "dev fast-forward failed");
921
+ const squash = runGit(root, ["merge", "--squash", "-X", "ours", feat]);
922
+ if (!squash.ok) {
923
+ throw new Stop(
924
+ EXIT_LAND_STOPPED,
925
+ `squash of ${feat} into dev failed — nothing committed or pushed; ${feat} and its worktree kept. Clear what git names from the main checkout, then re-run: ${squash.stderr}`,
926
+ );
927
+ }
928
+ const staged = (git(root, ["diff", "--cached", "--name-only"]) ?? "")
929
+ .split("\n")
930
+ .filter((p) => p !== "" && !CLOSE_DOCS.test(p));
931
+ if (staged.length)
932
+ throw new Stop(
933
+ EXIT_LAND_STOPPED,
934
+ `${o.workflow} close staged non-doc files:\n${staged.join("\n")}`,
935
+ );
936
+ const docs = canonicalDocs(root, feat, o.workflow, o.month, o.fid);
937
+ const main = `docs/plans/${o.month}/${o.fid}-${o.workflow}.md`;
938
+ if (!docs.includes(main))
939
+ throw new Stop(
940
+ EXIT_LAND_STOPPED,
941
+ `${feat} carries no ${main} — nothing committed or pushed; ${feat} kept`,
942
+ );
943
+ const unlanded = docs.filter(
944
+ (d) =>
945
+ git(root, ["rev-parse", "-q", "--verify", `:${d}`]) !==
946
+ git(root, ["rev-parse", `${feat}:${d}`]),
947
+ );
948
+ if (unlanded.length) {
949
+ throw new Stop(
950
+ EXIT_LAND_STOPPED,
951
+ `squash did not stage the ${feat} copy of:\n${unlanded.join("\n")}\nnothing committed or pushed; ${feat} kept; the main checkout index still holds the squash`,
952
+ );
953
+ }
954
+ appendFeature(root, { workflow: o.workflow, fid: o.fid }, ctx.log);
955
+ commitBookkeeping(
956
+ {
957
+ root,
958
+ month: o.month,
959
+ fid: o.fid,
960
+ scope: "core",
961
+ mode: "commit-allow-empty",
962
+ squashOf: feat,
963
+ message: `docs(${o.fid}): ${o.workflow} DONE bkit [skip ci]`,
964
+ },
965
+ ctx.log,
966
+ );
967
+ if (!runGit(root, ["push", REMOTE, DEV]).ok)
968
+ throw new Stop(EXIT_PUSH_FAILED, "dev push failed");
969
+ const sha = git(root, ["rev-parse", "HEAD"]) ?? "";
970
+ let worktree: Record<string, unknown> | null = null;
971
+ try {
972
+ worktree = { ...removeWorktree(root, o.fid, feat, ctx.log) };
973
+ } catch (err) {
974
+ // The close landed; a leftover worktree is a human's to remove.
975
+ ctx.log(
976
+ `worktree removal failed — remove .worktrees/${o.fid} by hand: ${(err as Error).message}`,
977
+ );
978
+ }
979
+ return { shape: "local", transport: "git", sha, canonicalRef: DEV, prNumber: null, worktree };
980
+ } finally {
981
+ releaseLock(lock.path, { workflow: o.workflow, fid: o.fid, token: lock.token });
982
+ }
983
+ }
984
+
985
+ /**
986
+ * The PR close (a runtime that cannot push dev): commit the roadmap row on the
987
+ * branch, push it, open or reuse the PR, squash-merge it with an empty body. gh
988
+ * missing → EXIT.USE_MCP with what to create / merge; re-run with `--pr` (and
989
+ * `--merged-sha` once merged).
990
+ */
991
+ function landPr(
992
+ ctx: RunContext,
993
+ o: {
994
+ workflow: string;
995
+ fid: string;
996
+ month: string;
997
+ issue?: string;
998
+ branch: string;
999
+ pr?: string;
1000
+ mergedSha?: string;
1001
+ },
1002
+ ): Landed | number {
1003
+ const tree = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? ctx.cwd;
1004
+ let prNumber = o.pr;
1005
+ if (prNumber === undefined) {
1006
+ runGit(tree, ["fetch", REMOTE, DEV, o.branch]);
1007
+ appendFeature(tree, { workflow: o.workflow, fid: o.fid }, ctx.log);
1008
+ commitBookkeeping(
1009
+ {
1010
+ root: tree,
1011
+ month: o.month,
1012
+ fid: o.fid,
1013
+ scope: "core",
1014
+ mode: "commit-allow-empty",
1015
+ message: `docs(${o.fid}): ${o.workflow} roadmap update bkit [skip ci]`,
1016
+ },
1017
+ ctx.log,
1018
+ );
1019
+ const stray = (git(tree, ["diff", "--name-only", `${UPSTREAM}...${o.branch}`]) ?? "")
1020
+ .split("\n")
1021
+ .filter((p) => p !== "" && !CLOSE_DOCS.test(p));
1022
+ if (stray.length)
1023
+ throw new Stop(
1024
+ EXIT_LAND_STOPPED,
1025
+ `${o.workflow} close diff carries non-doc files:\n${stray.join("\n")}`,
1026
+ );
1027
+ const pushed = pushBranch(tree, { mode: "feature" }, ctx.log);
1028
+ if (pushed.code !== EXIT.OK)
1029
+ throw new Stop(
1030
+ EXIT_PUSH_FAILED,
1031
+ "close-commit push failed — the PR would not carry the roadmap row or the close status rows",
1032
+ );
1033
+ const opened = openPrFor(
1034
+ tree,
1035
+ {
1036
+ fid: o.fid,
1037
+ title: `docs(${o.fid}): ${o.workflow} DONE`,
1038
+ issue: o.issue,
1039
+ head: o.branch,
1040
+ existing: "reuse",
1041
+ },
1042
+ ctx.log,
1043
+ );
1044
+ if (opened.code === EXIT.USE_MCP) {
1045
+ ctx.emit({ stage: "open", ...opened.out });
1046
+ return EXIT.USE_MCP;
1047
+ }
1048
+ if (opened.code !== EXIT.OK || !opened.out?.number)
1049
+ throw new Stop(EXIT_LAND_STOPPED, `could not open or reuse a PR for ${o.branch} to dev`);
1050
+ prNumber = String(opened.out.number);
1051
+ }
1052
+ const subject = `docs(${o.fid}): ${o.workflow} DONE bkit [skip ci]`;
1053
+ let sha = o.mergedSha ?? "";
1054
+ let transport: Landed["transport"] = o.mergedSha === undefined ? "gh" : "mcp";
1055
+ if (o.mergedSha === undefined) {
1056
+ const merged = mergePr(tree, { number: prNumber, subject }, ctx.log);
1057
+ if (merged.code === EXIT.USE_MCP) {
1058
+ ctx.emit({ stage: "merge", prNumber: Number(prNumber), subject, body: "" });
1059
+ return EXIT.USE_MCP;
1060
+ }
1061
+ if (!merged.out.merged)
1062
+ throw new Stop(
1063
+ EXIT_LAND_STOPPED,
1064
+ `PR ${prNumber} did not reach MERGED (state=${merged.out.state ?? "unread"})`,
1065
+ );
1066
+ sha = merged.out.mergeCommitOid ?? "";
1067
+ transport = "gh";
1068
+ } else {
1069
+ const back = probePr(tree, { number: prNumber, state: "open" });
1070
+ if (back.kind === "ok" && back.pr && back.pr.state !== "MERGED")
1071
+ throw new Stop(EXIT_LAND_STOPPED, `PR ${prNumber} is ${back.pr.state}, not MERGED`);
1072
+ }
1073
+ if (sha === "")
1074
+ throw new Stop(EXIT_LAND_STOPPED, `could not resolve the landed SHA for PR ${prNumber}`);
1075
+ if (!runGit(tree, ["fetch", REMOTE, DEV]).ok)
1076
+ throw new Stop(EXIT_LAND_STOPPED, "fetch of origin/dev after the merge failed");
1077
+ return {
1078
+ shape: "pr",
1079
+ transport,
1080
+ sha,
1081
+ canonicalRef: UPSTREAM,
1082
+ prNumber: Number(prNumber),
1083
+ worktree: null,
1084
+ };
1085
+ }
1086
+
1087
+ async function landVerb(ctx: RunContext): Promise<number> {
1088
+ const workflow = String(ctx.flags.workflow);
1089
+ if (!["design", "plan"].includes(workflow))
1090
+ throw new CommandError(EXIT.USAGE, "--workflow must be design or plan");
1091
+ const fid = String(ctx.flags.fid);
1092
+ const root = repoRoot(ctx.cwd);
1093
+ const month = resolveMonth(root, fid, str(ctx.flags.month));
1094
+ // `bkit install` can leave core.bare=true on the main checkout, which breaks every checkout below.
1095
+ if (
1096
+ git(root, ["config", "--get", "core.bare"]) === "true" &&
1097
+ fs.statSync(path.join(root, ".git"), { throwIfNoEntry: false })?.isDirectory()
1098
+ ) {
1099
+ runGit(root, ["config", "core.bare", "false"]);
1100
+ }
1101
+ const worktreeStatus = path.join(
1102
+ git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root,
1103
+ "docs",
1104
+ "plans",
1105
+ month,
1106
+ "logs",
1107
+ fid,
1108
+ "status.jsonl",
1109
+ );
1110
+ try {
1111
+ const devPushes = devPushesOf(root, worktreeStatus, ctx.log);
1112
+ const landed = devPushes
1113
+ ? await landLocal(ctx, root, { workflow, fid, month })
1114
+ : landPr(ctx, {
1115
+ workflow,
1116
+ fid,
1117
+ month,
1118
+ issue: str(ctx.flags.issue) || undefined,
1119
+ branch: String(ctx.flags.branch ?? currentBranch(ctx.cwd)),
1120
+ pr: str(ctx.flags.pr),
1121
+ mergedSha: str(ctx.flags.mergedSha),
1122
+ });
1123
+ if (typeof landed === "number") return landed;
1124
+
1125
+ // The audit: canonical docs on dev, the landed body clean, the transport recorded.
1126
+ const docs = canonicalDocs(root, landed.sha, workflow, month, fid);
1127
+ const main = `docs/plans/${month}/${fid}-${workflow}.md`;
1128
+ const missing = [main, ...docs].filter(
1129
+ (d) => !runGit(root, ["cat-file", "-e", `${landed.canonicalRef}:${d}`]).ok,
1130
+ );
1131
+ const status = path.join(root, "docs", "plans", month, "logs", fid, "status.jsonl");
1132
+ runGit(root, ["fetch", REMOTE, DEV]);
1133
+ const token = bodySkipToken(root, landed.sha);
1134
+ if (token === undefined)
1135
+ throw new Stop(EXIT_LANDED_UNVERIFIED, `post-close body scan errored on ${landed.sha}`);
1136
+ const scanResult = token ? "skip-token-found" : "clean";
1137
+ if (!crossCheckFile(status, landed.transport, ctx.log).ok)
1138
+ throw new Stop(EXIT_LANDED_UNVERIFIED, "close transport cross-check failed");
1139
+ closeTransportRow(status, { shape: landed.shape, sha: landed.sha, scanResult });
1140
+ if (token)
1141
+ throw new Stop(
1142
+ EXIT_LANDED_UNVERIFIED,
1143
+ `landed commit ${landed.sha} inherited a CI-suppression token in its body`,
1144
+ );
1145
+ if (missing.length)
1146
+ throw new Stop(
1147
+ EXIT_LANDED_UNVERIFIED,
1148
+ `canonical ${workflow} missing on dev: ${missing.join(", ")}`,
1149
+ );
1150
+
1151
+ const released = releaseLock(workflowLockPath(lockRoot(root, workflow, false), month, fid), {
1152
+ workflow,
1153
+ fid,
1154
+ token: str(ctx.flags.token),
1155
+ });
1156
+ if (released.removeFailed) throw new Stop(EXIT_LOCK_LEFT, "Lock removal failed");
1157
+ ctx.emit({
1158
+ shape: landed.shape,
1159
+ transport: landed.transport,
1160
+ landedSha: landed.sha,
1161
+ prNumber: landed.prNumber,
1162
+ canonicalRef: landed.canonicalRef,
1163
+ scanResult,
1164
+ worktree: landed.worktree,
1165
+ });
1166
+ return EXIT.OK;
1167
+ } catch (err) {
1168
+ if (!(err instanceof Stop)) throw err;
1169
+ ctx.log(err.message);
1170
+ return err.code;
1171
+ }
1172
+ }
1173
+
1174
+ function anchorStampVerb(ctx: RunContext): number {
1175
+ const rel = String(ctx.flags.file);
1176
+ const file = path.resolve(ctx.cwd, rel);
1177
+ const baseSha = String(ctx.flags.baseSha);
1178
+ if (!fs.statSync(file, { throwIfNoEntry: false })?.isFile()) {
1179
+ ctx.log(`${rel} is missing or not a file — nothing to stamp`);
1180
+ return EXIT_NO_FILE;
1181
+ }
1182
+ if (baseSha === "") throw new CommandError(EXIT.USAGE, "--base-sha must be non-empty");
1183
+ const designFlag = str(ctx.flags.design);
1184
+ const designFile = designFlag === undefined ? undefined : path.resolve(ctx.cwd, designFlag);
1185
+ const design =
1186
+ designFlag !== undefined && designFile !== undefined && fs.existsSync(designFile)
1187
+ ? {
1188
+ path: designFlag,
1189
+ baseSha: readAnchor(fs.readFileSync(designFile, "utf-8")).baseSha ?? "",
1190
+ }
1191
+ : undefined;
1192
+ const before = fs.readFileSync(file, "utf-8");
1193
+ const after = stampAnchor(before, baseSha, design);
1194
+ // Temp file + rename: a crash mid-write never leaves a half-stamped doc.
1195
+ const tmp = `${file}.bkit-anchor.tmp`;
1196
+ fs.writeFileSync(tmp, after);
1197
+ fs.renameSync(tmp, file);
1198
+ ctx.emit({
1199
+ file: rel,
1200
+ baseSha,
1201
+ designPath: design?.path ?? null,
1202
+ designBaseSha: design?.baseSha ?? null,
1203
+ changed: before !== after,
1204
+ });
1205
+ return EXIT.OK;
1206
+ }
1207
+
1208
+ function anchorReadVerb(ctx: RunContext): number {
1209
+ const rel = String(ctx.flags.file);
1210
+ const file = path.resolve(ctx.cwd, rel);
1211
+ const field = str(ctx.flags.field);
1212
+ if (field !== undefined && !(ANCHOR_FIELDS as readonly string[]).includes(field)) {
1213
+ throw new CommandError(EXIT.USAGE, `--field must be one of ${ANCHOR_FIELDS.join(", ")}`);
1214
+ }
1215
+ const against = str(ctx.flags.against);
1216
+ const skip = (reason: string, message: string, fields: Record<string, unknown>) => {
1217
+ ctx.log(message);
1218
+ ctx.emit({ ...fields, value: null, skip: reason, landed: null });
1219
+ return EXIT_ANCHOR_SKIP;
1220
+ };
1221
+ const none = { baseSha: null, baseRef: null, designPath: null, designBaseSha: null };
1222
+ if (!fs.statSync(file, { throwIfNoEntry: false })?.isFile()) {
1223
+ if (against !== undefined) return skip("no-file", `no ${rel} — nothing to check`, none);
1224
+ ctx.log(`${rel} not found`);
1225
+ return EXIT_NO_FILE;
1226
+ }
1227
+ const anchor = readAnchor(fs.readFileSync(file, "utf-8"));
1228
+ const fields = Object.fromEntries(ANCHOR_FIELDS.map((f) => [f, anchor[f] ?? null]));
1229
+ const value = field === undefined ? null : (anchor[field as AnchorField] ?? null);
1230
+ if (against === undefined) {
1231
+ ctx.emit({ ...fields, value, skip: null, landed: null });
1232
+ return EXIT.OK;
1233
+ }
1234
+ const base = anchor.baseSha ?? "";
1235
+ if (base === "") return skip("no-anchor", `no anchor on ${rel}`, fields);
1236
+ if (!runGit(ctx.cwd, ["cat-file", "-e", base]).ok) {
1237
+ return skip("unreachable", `base ${base} unreachable in this clone`, fields);
1238
+ }
1239
+ const diff = runGit(ctx.cwd, ["diff", "--name-only", `${base}..${against}`]);
1240
+ if (!diff.ok)
1241
+ throw new CommandError(EXIT.USAGE, `cannot diff ${base}..${against}: ${diff.stderr}`);
1242
+ const landed = diff.stdout.split("\n").filter(Boolean).length;
1243
+ if (landed === 0)
1244
+ return skip("nothing-landed", `nothing landed on ${against} since ${base}`, fields);
1245
+ ctx.emit({ ...fields, value, skip: null, landed });
1246
+ return EXIT.OK;
1247
+ }
1248
+
1249
+ // ---------------------------------------------------------------------------
1250
+ // Spec
1251
+ // ---------------------------------------------------------------------------
1252
+
1253
+ export const branchesCommand: CommandSpec = {
1254
+ noun: "branches",
1255
+ summary: "Sync, push, rebase and switch branches; stamp and read a doc's base-commit anchor.",
1256
+ verbs: {
1257
+ sync: {
1258
+ summary: `Fetch ${UPSTREAM}; report whether it is an ancestor of HEAD (Path A/B) and how far docs/ is behind; optionally merge it in.`,
1259
+ flags: [
1260
+ {
1261
+ name: "head",
1262
+ type: "string",
1263
+ help: "commit to compare (default HEAD), e.g. ship's ENTRY_HEAD",
1264
+ },
1265
+ {
1266
+ name: "merge-docs",
1267
+ type: "boolean",
1268
+ help: `on a feature branch whose docs/ is behind, merge ${UPSTREAM} (ledgers union, other docs/ take ${DEV}, anything else aborts)`,
1269
+ },
1270
+ ],
1271
+ output: {
1272
+ branch: "current branch (null when detached)",
1273
+ head: "commit compared (after a merge: the merge commit)",
1274
+ basePath: `A when ${UPSTREAM} is an ancestor of head (nothing to integrate), else B`,
1275
+ behind: `commits on ${UPSTREAM} not in head`,
1276
+ docsBehind: `of those, commits touching docs/`,
1277
+ merged: `true when --merge-docs merged ${UPSTREAM}`,
1278
+ resolved: "conflicts the merge resolved: [{path, how: union|dev}]",
1279
+ },
1280
+ exitCodes: {
1281
+ [EXIT_DETACHED]: "--merge-docs with no branch checked out",
1282
+ [EXIT_FETCH_FAILED]: `git fetch ${REMOTE} ${DEV} failed`,
1283
+ [EXIT_MERGE_CONFLICT]:
1284
+ "the docs merge conflicted outside docs/ or could not be committed; merge aborted",
1285
+ },
1286
+ run: syncVerb,
1287
+ },
1288
+ push: {
1289
+ summary:
1290
+ "Push the current branch with exactly one git push: plain for dev/main, --force-with-lease otherwise.",
1291
+ flags: [
1292
+ {
1293
+ name: "mode",
1294
+ type: "string",
1295
+ required: true,
1296
+ help: "feature (a step's push) | abort (Failure Path: never into an open PR) | dev (the checkout must be on dev)",
1297
+ },
1298
+ { name: "set-upstream", type: "boolean", help: "push with -u" },
1299
+ {
1300
+ name: "require-ci",
1301
+ type: "boolean",
1302
+ help: "this push must start a CI run: refuse when the HEAD message carries a skip-CI token",
1303
+ },
1304
+ {
1305
+ name: "open-pr",
1306
+ type: "string",
1307
+ help: "--mode=abort: the open-PR answer from MCP (a number, or none) instead of asking gh",
1308
+ },
1309
+ ],
1310
+ output: {
1311
+ pushed: "true when the push ran and succeeded",
1312
+ ref: "the branch pushed — link handover artifacts to this ref; null when nothing was pushed",
1313
+ sha: "HEAD commit pushed (null when not pushed)",
1314
+ forced: "true when pushed with --force-with-lease",
1315
+ skipped: "why the push did not run: open-pr | skip-ci (null otherwise)",
1316
+ prNumber: "the open PR that stopped an abort push (null otherwise)",
1317
+ },
1318
+ exitCodes: {
1319
+ [EXIT_DETACHED]: "no branch checked out",
1320
+ [EXIT_SKIP_CI]: "--require-ci and the HEAD message carries a skip-CI token",
1321
+ [EXIT_OPEN_PR]:
1322
+ "--mode=abort and the branch has an open PR: push skipped, remote HEAD kept",
1323
+ [EXIT_PUSH_FAILED]: "git push failed",
1324
+ [EXIT_NOT_DEV]: "--mode=dev and the checkout is not on dev",
1325
+ },
1326
+ run: pushVerb,
1327
+ },
1328
+ rebase: {
1329
+ summary:
1330
+ "Drive a rebase to completion, auto-resolving ledger (union) and lockfile (regenerate) conflicts; refuse and abort on anything else.",
1331
+ flags: [
1332
+ {
1333
+ name: "log-file",
1334
+ type: "string",
1335
+ help: "append the resolution log lines here, e.g. logs/{FID}/rebase-resolve-log.md",
1336
+ },
1337
+ {
1338
+ name: "sentinel",
1339
+ type: "string",
1340
+ help: "file removed at start and created on refusal, e.g. logs/{FID}/.rebase-failed",
1341
+ },
1342
+ ],
1343
+ output: {
1344
+ outcome: "resolved | refused (a refused rebase is aborted)",
1345
+ resolved: "conflicts resolved: [{path, how: union|lockfile}]",
1346
+ skippedCommits: "commits skipped because resolution emptied them",
1347
+ rounds: "resolve rounds run",
1348
+ refused: "the path that stopped resolution (null when none, or not path-specific)",
1349
+ reason: "why resolution refused (null on success)",
1350
+ aborted: "a refused rebase was aborted (false on success, or when the abort failed)",
1351
+ sentinel: "the sentinel written on refusal (null otherwise)",
1352
+ },
1353
+ exitCodes: {
1354
+ [EXIT_REFUSED]: "a conflict is not auto-resolvable",
1355
+ [EXIT_NO_REBASE]: "no rebase in progress",
1356
+ },
1357
+ run: rebaseVerb,
1358
+ },
1359
+ switch: {
1360
+ summary:
1361
+ "After a merge, return the main checkout to dev and bring it level with origin/dev, under the dev lock.",
1362
+ flags: [
1363
+ {
1364
+ name: "fid",
1365
+ type: "string",
1366
+ required: true,
1367
+ help: "feature id, recorded in the dev lock",
1368
+ },
1369
+ {
1370
+ name: "dev-pushes",
1371
+ type: "string",
1372
+ required: true,
1373
+ help: "true | false — runtimeDevPushes; false skips the switch",
1374
+ },
1375
+ {
1376
+ name: "worktrees",
1377
+ type: "string",
1378
+ required: true,
1379
+ help: "true | false — runtimeWorktrees; a local dev checkout needs true",
1380
+ },
1381
+ ],
1382
+ output: {
1383
+ switched: "true when the checkout is now on dev",
1384
+ branch: "branch checked out afterwards",
1385
+ ahead: "local dev commits that were ahead of origin/dev (all skip-CI, rebased and pushed)",
1386
+ pushed: "true when those commits were pushed",
1387
+ installed:
1388
+ "dependency install result: true, false (failed, exit 16), null (no package.json)",
1389
+ skipped: "dev-pushes-false when the runtime does not push dev (null otherwise)",
1390
+ },
1391
+ exitCodes: {
1392
+ [EXIT_NOT_DEV]: "the checkout is not on dev after git checkout dev",
1393
+ [EXIT_FETCH_FAILED]: `git fetch ${REMOTE} ${DEV} failed`,
1394
+ [EXIT_PUSH_FAILED]: "pushing the rebased local dev commits failed",
1395
+ [EXIT_PULL_FAILED]: "git pull failed: local dev is not level with origin/dev",
1396
+ [EXIT_RUNTIME_REFUSED]: "--dev-pushes=true with --worktrees=false",
1397
+ [EXIT_INSTALL_FAILED]: "dependency install failed or the package manager could not run",
1398
+ },
1399
+ run: switchVerb,
1400
+ },
1401
+ land: {
1402
+ summary:
1403
+ "Design / plan close: land feat/{fid} on dev — the local squash under the dev lock, or the PR squash-merge — then audit it and release the lock.",
1404
+ flags: [
1405
+ { name: "workflow", type: "string", required: true, help: "design | plan" },
1406
+ { name: "fid", type: "string", required: true, help: "feature id" },
1407
+ {
1408
+ name: "month",
1409
+ type: "string",
1410
+ help: "month bucket YYYYMM (default: the feature's bucket)",
1411
+ },
1412
+ { name: "token", type: "string", help: "the workflow lock token to release once landed" },
1413
+ { name: "issue", type: "string", help: "PR close: the issue id for the PR-body marker" },
1414
+ {
1415
+ name: "branch",
1416
+ type: "string",
1417
+ help: "PR close: the head branch (default: the current branch)",
1418
+ },
1419
+ {
1420
+ name: "pr",
1421
+ type: "string",
1422
+ help: "PR close re-entry: the PR MCP created (after exit 80 at stage open)",
1423
+ },
1424
+ {
1425
+ name: "merged-sha",
1426
+ type: "string",
1427
+ help: "PR close re-entry: the squash commit MCP's merge returned (after exit 80 at stage merge)",
1428
+ },
1429
+ ],
1430
+ output: {
1431
+ shape: "local | pr",
1432
+ transport: "git | gh | mcp",
1433
+ landedSha: "the commit that landed on dev",
1434
+ prNumber: "the PR (pr shape), else null",
1435
+ canonicalRef: "dev (local) | origin/dev (pr) — where the canonical docs were verified",
1436
+ scanResult: "the landed commit body's scan: clean",
1437
+ worktree: "the worktree removal result (local), else null",
1438
+ stage:
1439
+ "exit 80 only: open (create the PR via MCP with title / body / base / head) | merge (merge via MCP with subject, empty body)",
1440
+ },
1441
+ exitCodes: {
1442
+ [EXIT_PUSH_FAILED]: "the dev or branch push failed",
1443
+ [EXIT_NOT_DEV]: "the main checkout is not on dev after checkout",
1444
+ [EXIT_PULL_FAILED]: "dev could not fast-forward",
1445
+ [EXIT_LAND_STOPPED]:
1446
+ "a guard stopped the land: stray files, failed squash, staged non-doc files, canonical blob mismatch, PR not opened / merged (nothing landed)",
1447
+ [EXIT_LANDED_UNVERIFIED]:
1448
+ "landed, but the body scan, transport cross-check or canonical-on-dev check failed",
1449
+ [EXIT_LOCK_LEFT]: "landed and audited, but the workflow lock file survived removal",
1450
+ },
1451
+ run: landVerb,
1452
+ },
1453
+ "anchor-stamp": {
1454
+ summary:
1455
+ "Put a <!-- bkit:anchor --> block recording the base commit on top of a design/plan doc (idempotent).",
1456
+ flags: [
1457
+ { name: "file", type: "string", required: true, help: "doc to stamp (must exist)" },
1458
+ {
1459
+ name: "base-sha",
1460
+ type: "string",
1461
+ required: true,
1462
+ help: "base commit the doc was written against (non-empty)",
1463
+ },
1464
+ {
1465
+ name: "design",
1466
+ type: "string",
1467
+ help: "plan docs: the design doc it targets; when that file exists, designPath and its own baseSha are stamped too",
1468
+ },
1469
+ ],
1470
+ output: {
1471
+ file: "doc stamped",
1472
+ baseSha: "base commit stamped",
1473
+ designPath: "design path stamped (null when none)",
1474
+ designBaseSha:
1475
+ "the design doc's baseSha stamped (null when none; empty when it had no anchor)",
1476
+ changed: "false when the doc already carried exactly this block",
1477
+ },
1478
+ exitCodes: { [EXIT_NO_FILE]: "--file is missing or not a file" },
1479
+ run: anchorStampVerb,
1480
+ },
1481
+ "anchor-read": {
1482
+ summary:
1483
+ "Read a doc's anchor fields; with --against, decide whether anything landed since its baseSha.",
1484
+ flags: [
1485
+ { name: "file", type: "string", required: true, help: "design/plan doc" },
1486
+ {
1487
+ name: "field",
1488
+ type: "string",
1489
+ help: `one field to return as value: ${ANCHOR_FIELDS.join(" | ")}`,
1490
+ },
1491
+ {
1492
+ name: "against",
1493
+ type: "string",
1494
+ help: `ref to compare baseSha with, e.g. ${UPSTREAM}: exits ${EXIT_ANCHOR_SKIP} when the check should be skipped`,
1495
+ },
1496
+ ],
1497
+ output: {
1498
+ baseSha: "anchor baseSha (null when absent)",
1499
+ baseRef: "anchor baseRef (null when absent)",
1500
+ designPath: "anchor designPath (null when absent)",
1501
+ designBaseSha: "anchor designBaseSha (null when absent)",
1502
+ value: "the --field value (null when absent or no --field)",
1503
+ skip: "with --against: no-file | no-anchor | unreachable | nothing-landed (null = run the check)",
1504
+ landed: "with --against: paths changed between baseSha and the ref",
1505
+ },
1506
+ exitCodes: {
1507
+ [EXIT_ANCHOR_SKIP]:
1508
+ "--against: skip the check (no file, no anchor, base unreachable, nothing landed)",
1509
+ [EXIT_NO_FILE]: "--file not found (without --against)",
1510
+ },
1511
+ run: anchorReadVerb,
1512
+ },
1513
+ },
1514
+ };