@cbartens/bkit 5.5.1 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (425) hide show
  1. package/.bkit/README.md +167 -154
  2. package/.bkit/core/.agents/context.md +95 -29
  3. package/.bkit/core/.agents/docs.md +18 -15
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-gateguard.cjs +1 -0
  5. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +6 -5
  6. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-readguard.cjs +1 -0
  7. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-rules.cjs +65 -0
  8. package/.bkit/core/.agents/rules.md +112 -102
  9. package/.bkit/core/.agents/skills.md +63 -15
  10. package/.bkit/core/.bkit/README.md +167 -154
  11. package/.bkit/core/.bkit/authoring.md +747 -0
  12. package/.bkit/core/.bkit/cli.md +407 -0
  13. package/.bkit/core/.bkit/cloud.md +283 -195
  14. package/.bkit/core/.bkit/comparison.md +45 -43
  15. package/.bkit/core/.bkit/install.md +166 -95
  16. package/.bkit/core/.bkit/jsonl.md +339 -196
  17. package/.bkit/core/.bkit/pipeline.md +142 -145
  18. package/.bkit/core/.bkit/prompts.md +295 -264
  19. package/.bkit/core/.bkit/providers.md +460 -277
  20. package/.bkit/core/.bkit/router.md +69 -0
  21. package/.bkit/core/.bkit/templates.md +530 -256
  22. package/.bkit/core/.bkit/trackers.md +116 -65
  23. package/.bkit/core/.bkit/workflows.md +742 -618
  24. package/.bkit/core/.claude/hooks/bkit-gateguard.cjs +2 -2
  25. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +3 -3
  26. package/.bkit/core/.claude/hooks/bkit-preflight.sh +45 -14
  27. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +3 -3
  28. package/.bkit/core/.codex/hooks/bkit-rules.cjs +57 -0
  29. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +7 -7
  30. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +47 -12
  31. package/.bkit/core/.opencode/plugin/bkit-rules.js +89 -0
  32. package/.bkit/core/AGENTS.md +6 -80
  33. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +128 -130
  34. package/.bkit/core/docs/templates/bkit-audit-adoption.md +104 -94
  35. package/.bkit/core/docs/templates/bkit-audit-agents.md +96 -98
  36. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +100 -103
  37. package/.bkit/core/docs/templates/bkit-audit-analytics.md +141 -107
  38. package/.bkit/core/docs/templates/bkit-audit-annotations.md +99 -97
  39. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +122 -121
  40. package/.bkit/core/docs/templates/bkit-audit-app-store.md +158 -101
  41. package/.bkit/core/docs/templates/bkit-audit-architecture.md +114 -96
  42. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +76 -97
  43. package/.bkit/core/docs/templates/bkit-audit-config.md +123 -101
  44. package/.bkit/core/docs/templates/bkit-audit-cost.md +86 -99
  45. package/.bkit/core/docs/templates/bkit-audit-coverage.md +76 -93
  46. package/.bkit/core/docs/templates/bkit-audit-database.md +102 -95
  47. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +165 -108
  48. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +115 -109
  49. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +265 -113
  50. package/.bkit/core/docs/templates/bkit-audit-documentation.md +119 -118
  51. package/.bkit/core/docs/templates/bkit-audit-duplication.md +140 -111
  52. package/.bkit/core/docs/templates/bkit-audit-failures.md +111 -106
  53. package/.bkit/core/docs/templates/bkit-audit-flakes.md +100 -99
  54. package/.bkit/core/docs/templates/bkit-audit-gates.md +107 -103
  55. package/.bkit/core/docs/templates/bkit-audit-issues.md +105 -105
  56. package/.bkit/core/docs/templates/bkit-audit-llm.md +134 -85
  57. package/.bkit/core/docs/templates/bkit-audit-logs.md +124 -125
  58. package/.bkit/core/docs/templates/bkit-audit-models.md +99 -78
  59. package/.bkit/core/docs/templates/bkit-audit-privacy.md +56 -76
  60. package/.bkit/core/docs/templates/bkit-audit-prompts.md +63 -78
  61. package/.bkit/core/docs/templates/bkit-audit-red-team.md +125 -93
  62. package/.bkit/core/docs/templates/bkit-audit-reliability.md +97 -96
  63. package/.bkit/core/docs/templates/bkit-audit-repo.md +170 -98
  64. package/.bkit/core/docs/templates/bkit-audit-security.md +207 -121
  65. package/.bkit/core/docs/templates/bkit-audit-slop.md +78 -95
  66. package/.bkit/core/docs/templates/bkit-audit-testing.md +163 -139
  67. package/.bkit/core/docs/templates/bkit-audit-usability.md +114 -96
  68. package/.bkit/core/docs/templates/bkit-plan.md +158 -281
  69. package/.bkit/core/engine/checks/after/auth.ts +40 -37
  70. package/.bkit/core/engine/checks/after/ci-yml.ts +104 -31
  71. package/.bkit/core/engine/checks/after/github.ts +95 -17
  72. package/.bkit/core/engine/checks/after/index.ts +21 -8
  73. package/.bkit/core/engine/checks/after/suppression.ts +8 -5
  74. package/.bkit/core/engine/checks/after/tools.ts +125 -123
  75. package/.bkit/core/engine/checks/before/context-fetch.ts +227 -33
  76. package/.bkit/core/engine/checks/before/env.ts +3 -3
  77. package/.bkit/core/engine/checks/before/files.ts +5 -4
  78. package/.bkit/core/engine/checks/before/index.ts +25 -1
  79. package/.bkit/core/engine/checks/before/repo.ts +208 -2
  80. package/.bkit/core/engine/checks/status-holes.ts +916 -123
  81. package/.bkit/core/engine/checks/tips/catalogue.ts +82 -20
  82. package/.bkit/core/engine/checks/tips/detect.ts +66 -0
  83. package/.bkit/core/engine/checks/tips/index.ts +52 -11
  84. package/.bkit/core/engine/cli.ts +251 -130
  85. package/.bkit/core/engine/commands/analysis.ts +282 -199
  86. package/.bkit/core/engine/commands/ci/ci.ts +363 -29
  87. package/.bkit/core/engine/commands/ci/pins.ts +172 -0
  88. package/.bkit/core/engine/commands/ci/push-gate.ts +223 -0
  89. package/.bkit/core/engine/commands/comply.ts +77 -103
  90. package/.bkit/core/engine/commands/install/doctor.ts +2 -2
  91. package/.bkit/core/engine/commands/install/install.ts +57 -18
  92. package/.bkit/core/engine/commands/install/uninstall.ts +86 -55
  93. package/.bkit/core/engine/commands/install/upgrade.ts +32 -15
  94. package/.bkit/core/engine/commands/land.ts +139 -18
  95. package/.bkit/core/engine/commands/lib.ts +381 -22
  96. package/.bkit/core/engine/commands/registry.ts +10 -2
  97. package/.bkit/core/engine/commands/setup/setup.ts +8 -7
  98. package/.bkit/core/engine/commands/stats.ts +260 -0
  99. package/.bkit/core/engine/commands/tips.ts +10 -5
  100. package/.bkit/core/engine/commands/workflow/branches.ts +2215 -176
  101. package/.bkit/core/engine/commands/workflow/challenge.ts +748 -0
  102. package/.bkit/core/engine/commands/workflow/completeness.ts +109 -0
  103. package/.bkit/core/engine/commands/workflow/context.ts +1249 -47
  104. package/.bkit/core/engine/commands/workflow/counters.ts +483 -95
  105. package/.bkit/core/engine/commands/workflow/decisions.ts +585 -0
  106. package/.bkit/core/engine/commands/workflow/disk.ts +238 -56
  107. package/.bkit/core/engine/commands/workflow/fids.ts +811 -33
  108. package/.bkit/core/engine/commands/workflow/issues.ts +413 -64
  109. package/.bkit/core/engine/commands/workflow/ledgers.ts +1333 -36
  110. package/.bkit/core/engine/commands/workflow/locks.ts +28 -2
  111. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +691 -0
  112. package/.bkit/core/engine/commands/workflow/plan-versions.ts +21 -0
  113. package/.bkit/core/engine/commands/workflow/plans.ts +257 -0
  114. package/.bkit/core/engine/commands/workflow/prs.ts +178 -33
  115. package/.bkit/core/engine/commands/workflow/repo.ts +66 -8
  116. package/.bkit/core/engine/commands/workflow/roadmap.ts +72 -22
  117. package/.bkit/core/engine/commands/workflow/run-facts.ts +492 -0
  118. package/.bkit/core/engine/commands/workflow/runs.ts +827 -79
  119. package/.bkit/core/engine/commands/workflow/runtime.ts +25 -1
  120. package/.bkit/core/engine/commands/workflow/skills.ts +1 -0
  121. package/.bkit/core/engine/commands/workflow/status.ts +329 -33
  122. package/.bkit/core/engine/commands/workflow/step-table.ts +381 -0
  123. package/.bkit/core/engine/commands/workflow/steps.ts +841 -105
  124. package/.bkit/core/engine/commands/workflow/summary-findings.ts +177 -0
  125. package/.bkit/core/engine/commands/workflow/summary.ts +544 -0
  126. package/.bkit/core/engine/commands/workflow/tasks.ts +409 -0
  127. package/.bkit/core/engine/commands/workflow/test-blocks.ts +254 -0
  128. package/.bkit/core/engine/commands/workflow/tests-changed.ts +201 -0
  129. package/.bkit/core/engine/commands/workflow/tests.ts +2124 -330
  130. package/.bkit/core/engine/commands/workflow/tracker.ts +1195 -0
  131. package/.bkit/core/engine/commands/workflow/workflows.ts +1197 -235
  132. package/.bkit/core/engine/commands/workflow/worktrees.ts +543 -24
  133. package/.bkit/core/engine/install/cloud-env.ts +251 -121
  134. package/.bkit/core/engine/install/context-ci-workflow.ts +102 -0
  135. package/.bkit/core/engine/install/manifest.ts +67 -17
  136. package/.bkit/core/engine/install/modules/antigravity.ts +3 -2
  137. package/.bkit/core/engine/install/modules/cloud.ts +24 -16
  138. package/.bkit/core/engine/install/modules/codex.ts +15 -2
  139. package/.bkit/core/engine/install/modules/core.ts +1196 -45
  140. package/.bkit/core/engine/install/modules/cursor.ts +6 -6
  141. package/.bkit/core/engine/install/modules/opencode.ts +18 -6
  142. package/.bkit/core/engine/install/template-notes.ts +130 -0
  143. package/.bkit/core/engine/install/version-file.ts +9 -4
  144. package/.bkit/core/engine/install/write.ts +5 -0
  145. package/.bkit/core/engine/ledgers/compact.ts +124 -0
  146. package/.bkit/core/engine/ledgers/journal.ts +291 -0
  147. package/.bkit/core/engine/ledgers/migrate.ts +92 -0
  148. package/.bkit/core/engine/ledgers/status.ts +249 -21
  149. package/.bkit/core/engine/ledgers/telemetry.ts +1397 -253
  150. package/.bkit/core/engine/render/hosts.ts +118 -14
  151. package/.bkit/core/engine/render/models.ts +12 -0
  152. package/.bkit/core/engine/shared/bkit-latest.ts +26 -4
  153. package/.bkit/core/engine/shared/branches.ts +4 -1
  154. package/.bkit/core/engine/shared/dep-updater.ts +60 -0
  155. package/.bkit/core/engine/shared/egress.ts +8 -1
  156. package/.bkit/core/engine/shared/json.ts +25 -7
  157. package/.bkit/core/engine/shared/package-manager.ts +9 -0
  158. package/.bkit/core/engine/shared/settings.ts +243 -31
  159. package/.bkit/core/engine/shared/text.ts +361 -0
  160. package/.bkit/core/engine/shared/timeouts.ts +2 -0
  161. package/.bkit/core/engine/tools/cli-doc.ts +111 -0
  162. package/.bkit/core/engine/tools/grammar-density.ts +215 -0
  163. package/.bkit/core/engine/tools/instructions-sources.ts +832 -0
  164. package/.bkit/core/engine/tools/instructions.ts +1802 -0
  165. package/.bkit/core/hooks/antigravity-hook.js +25 -10
  166. package/.bkit/core/hooks/gateguard-engine.js +54 -29
  167. package/.bkit/core/hooks/guardrails-shell.js +4 -5
  168. package/.bkit/core/hooks/guardrails-tiers.js +10 -4
  169. package/.bkit/core/hooks/preflight-linear.sh +9 -9
  170. package/.bkit/core/hooks/preflight-rules.sh +8 -0
  171. package/.bkit/core/hooks/readguard-engine.js +29 -10
  172. package/.bkit/core/hooks/session-rules-advisory.js +61 -0
  173. package/.bkit/core/prompts/bkit-audit-generate.md +202 -94
  174. package/.bkit/core/prompts/bkit-build-challenge-1.md +76 -34
  175. package/.bkit/core/prompts/bkit-build-challenge-2.md +85 -38
  176. package/.bkit/core/prompts/bkit-build-install-skills.md +50 -28
  177. package/.bkit/core/prompts/bkit-build-plan-convert.md +85 -0
  178. package/.bkit/core/prompts/bkit-build-plan-current.md +59 -36
  179. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +101 -36
  180. package/.bkit/core/prompts/bkit-build-plan-tasks.md +149 -0
  181. package/.bkit/core/prompts/bkit-build-plan-tests.md +120 -0
  182. package/.bkit/core/prompts/bkit-build-plan-verify.md +104 -43
  183. package/.bkit/core/prompts/bkit-debug-abort-handover.md +47 -32
  184. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +109 -57
  185. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +65 -39
  186. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +53 -31
  187. package/.bkit/core/prompts/bkit-debug-failure-soak.md +65 -34
  188. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +46 -31
  189. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +45 -31
  190. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +43 -30
  191. package/.bkit/core/prompts/bkit-design-generate.md +80 -46
  192. package/.bkit/core/prompts/bkit-design-organise.md +83 -32
  193. package/.bkit/core/prompts/bkit-design-review-1.md +70 -50
  194. package/.bkit/core/prompts/bkit-design-review-2.md +65 -46
  195. package/.bkit/core/prompts/bkit-design-spike.md +64 -40
  196. package/.bkit/core/prompts/bkit-design-update.md +53 -28
  197. package/.bkit/core/prompts/bkit-plan-generate.md +101 -29
  198. package/.bkit/core/prompts/bkit-plan-review-1.md +78 -41
  199. package/.bkit/core/prompts/bkit-plan-review-2.md +78 -35
  200. package/.bkit/core/prompts/bkit-plan-scope-check.md +116 -0
  201. package/.bkit/core/prompts/bkit-plan-update.md +86 -31
  202. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +94 -50
  203. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +91 -41
  204. package/.bkit/core/prompts/bkit-ship-update-docs.md +45 -24
  205. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +65 -49
  206. package/.bkit/core/prompts/bkit-utility-update-decisions.md +87 -42
  207. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +81 -37
  208. package/.bkit/core/prompts/bkit-utility-update-documentation.md +43 -25
  209. package/.bkit/core/prompts/bkit-utility-update-failures.md +84 -37
  210. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +88 -42
  211. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +92 -39
  212. package/.bkit/core/prompts/bkit-utility-update-tracker.md +159 -60
  213. package/.bkit/core/workflows/bkit-auto.md +89 -58
  214. package/.bkit/core/workflows/bkit-build.md +967 -517
  215. package/.bkit/core/workflows/bkit-debug.md +555 -387
  216. package/.bkit/core/workflows/bkit-design.md +319 -283
  217. package/.bkit/core/workflows/bkit-plan.md +319 -342
  218. package/.bkit/core/workflows/bkit-ship.md +525 -328
  219. package/.bkit/shared/.agents/plugins/bkit/hooks.json +10 -0
  220. package/.bkit/shared/.bkit/.env.example +2 -2
  221. package/.bkit/shared/.claude/bkit-cloud.md +12 -10
  222. package/.bkit/shared/.claude/settings.json +14 -0
  223. package/.bkit/shared/.codex/bkit-cloud.md +98 -0
  224. package/.bkit/shared/.codex/hooks.json +20 -0
  225. package/.bkit/shared/.cursor/bkit-cloud.md +3 -3
  226. package/.bkit/shared/.cursor/mcp.json +1 -1
  227. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +1 -1
  228. package/.bkit/shared/.gitattributes +1 -1
  229. package/.bkit/shared/.mcp.json +1 -1
  230. package/.bkit/shared/.opencode/opencode.json +12 -1
  231. package/.bkit/shared/CLAUDE.md +6 -2
  232. package/.bkit/shared/GEMINI.md +5 -2
  233. package/.bkit/shared/docs/architecture.md +4 -7
  234. package/.bkit/shared/docs/data-schema.md +4 -7
  235. package/.bkit/shared/docs/deployments.md +241 -168
  236. package/.bkit/shared/docs/design.md +11 -12
  237. package/.bkit/shared/docs/noise.md +8 -7
  238. package/.bkit/shared/docs/observability.md +5 -8
  239. package/.bkit/shared/docs/security.md +35 -17
  240. package/.bkit/shared/docs/setup.md +29 -18
  241. package/.bkit/shared/docs/technology.md +3 -6
  242. package/.bkit/shared/docs/testing.md +289 -174
  243. package/.bkit/shared/gitignore +6 -2
  244. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +15 -16
  245. package/.bkit/templates/.cursor/Dockerfile +12 -8
  246. package/.bkit/templates/.cursor/environment.json +1 -1
  247. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-bug.yml +10 -8
  248. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +45 -12
  249. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +3 -3
  250. package/.bkit/templates/.github/renovate.json5 +34 -6
  251. package/.bkit/templates/.github/workflows/bkit-ci.yml +54 -51
  252. package/.bkit/templates/.github/workflows/bkit-cloud.yml +34 -33
  253. package/.bkit/templates/.github/workflows/bkit-health.yml +97 -0
  254. package/.bkit/templates/.github/workflows/bkit-renovate.yml +5 -4
  255. package/.bkit/templates/.github/workflows/bkit-trivy.yml +5 -4
  256. package/.bkit/templates/.husky/pre-commit +2 -2
  257. package/.bkit/templates/.husky/pre-push +96 -36
  258. package/.bkit/templates/.prettierignore +6 -0
  259. package/.bkit/templates/.vale.ini +27 -27
  260. package/.bkit/templates/context/bkit-cloudrun.md +23 -15
  261. package/.bkit/templates/context/bkit-expo.md +70 -52
  262. package/.bkit/templates/context/bkit-github.md +93 -56
  263. package/.bkit/templates/context/bkit-inngest.md +21 -15
  264. package/.bkit/templates/context/bkit-maestro.md +22 -16
  265. package/.bkit/templates/context/bkit-playwright.md +23 -17
  266. package/.bkit/templates/context/bkit-resend.md +12 -10
  267. package/.bkit/templates/context/bkit-sentry.md +30 -20
  268. package/.bkit/templates/context/bkit-serena.md +8 -7
  269. package/.bkit/templates/context/bkit-stripe.md +14 -13
  270. package/.bkit/templates/context/bkit-supabase.md +16 -13
  271. package/.bkit/templates/context/bkit-tavily.md +14 -11
  272. package/.bkit/templates/context/bkit-vercel.md +27 -18
  273. package/.bkit/templates/docs/capabilities.md +15 -14
  274. package/.bkit/templates/scripts/ci/{check-accepted-divergences.mjs → bkit-check-accepted-divergences.mjs} +6 -3
  275. package/.bkit/templates/scripts/ci/{check-accepted-divergences.test.mjs → bkit-check-accepted-divergences.test.mjs} +3 -3
  276. package/.bkit/templates/scripts/ci/{check-capstone.mjs → bkit-check-capstone.mjs} +2 -2
  277. package/.bkit/templates/scripts/ci/{check-capstone.test.mjs → bkit-check-capstone.test.mjs} +4 -4
  278. package/.bkit/templates/scripts/ci/{check-dependency-audit.mjs → bkit-check-dependency-audit.mjs} +103 -18
  279. package/.bkit/templates/scripts/ci/{check-dependency-audit.test.mjs → bkit-check-dependency-audit.test.mjs} +31 -3
  280. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +387 -0
  281. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +75 -0
  282. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +160 -0
  283. package/.bkit/templates/scripts/ci/lanes/{resolve-push-base.mjs → bkit-resolve-push-base.mjs} +3 -3
  284. package/.bkit/templates/scripts/ci/lanes/{resolve-push-base.test.mjs → bkit-resolve-push-base.test.mjs} +4 -4
  285. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +10 -2
  286. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +1 -1
  287. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +3 -3
  288. package/.bkit/templates/scripts/graphify/bkit-graph-embed.py +63 -0
  289. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +2 -2
  290. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +69 -18
  291. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +3 -3
  292. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +1 -1
  293. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  294. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +197 -126
  295. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +64 -41
  296. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +23 -7
  297. package/.bkit/templates/slop-scan.config.json +9 -2
  298. package/CHANGELOG.md +231 -0
  299. package/README.md +278 -89
  300. package/dist/checks/after/auth.js +36 -33
  301. package/dist/checks/after/ci-yml.js +91 -30
  302. package/dist/checks/after/github.js +91 -17
  303. package/dist/checks/after/index.js +22 -11
  304. package/dist/checks/after/suppression.js +8 -5
  305. package/dist/checks/after/tools.js +111 -114
  306. package/dist/checks/before/context-fetch.js +218 -33
  307. package/dist/checks/before/env.js +3 -3
  308. package/dist/checks/before/files.js +5 -3
  309. package/dist/checks/before/index.js +20 -3
  310. package/dist/checks/before/repo.js +197 -2
  311. package/dist/checks/status-holes.js +739 -114
  312. package/dist/checks/tips/catalogue.js +70 -19
  313. package/dist/checks/tips/detect.js +62 -0
  314. package/dist/checks/tips/index.js +51 -9
  315. package/dist/cli.js +234 -124
  316. package/dist/commands/analysis.js +174 -141
  317. package/dist/commands/ci/ci.js +302 -25
  318. package/dist/commands/ci/pins.js +142 -0
  319. package/dist/commands/ci/push-gate.js +194 -0
  320. package/dist/commands/comply.js +54 -91
  321. package/dist/commands/install/doctor.js +2 -2
  322. package/dist/commands/install/install.js +50 -19
  323. package/dist/commands/install/uninstall.js +82 -55
  324. package/dist/commands/install/upgrade.js +21 -11
  325. package/dist/commands/land.js +137 -17
  326. package/dist/commands/lib.js +295 -21
  327. package/dist/commands/registry.js +10 -2
  328. package/dist/commands/setup/setup.js +8 -7
  329. package/dist/commands/stats.js +175 -0
  330. package/dist/commands/tips.js +7 -3
  331. package/dist/commands/workflow/branches.js +1873 -152
  332. package/dist/commands/workflow/challenge.js +609 -0
  333. package/dist/commands/workflow/completeness.js +97 -0
  334. package/dist/commands/workflow/context.js +1045 -46
  335. package/dist/commands/workflow/counters.js +385 -86
  336. package/dist/commands/workflow/decisions.js +484 -0
  337. package/dist/commands/workflow/disk.js +214 -56
  338. package/dist/commands/workflow/fids.js +706 -33
  339. package/dist/commands/workflow/issues.js +349 -59
  340. package/dist/commands/workflow/ledgers.js +1123 -37
  341. package/dist/commands/workflow/locks.js +26 -2
  342. package/dist/commands/workflow/plan-blocks.js +501 -0
  343. package/dist/commands/workflow/plan-versions.js +22 -0
  344. package/dist/commands/workflow/plans.js +205 -0
  345. package/dist/commands/workflow/prs.js +154 -35
  346. package/dist/commands/workflow/repo.js +58 -8
  347. package/dist/commands/workflow/roadmap.js +58 -23
  348. package/dist/commands/workflow/run-facts.js +421 -0
  349. package/dist/commands/workflow/runs.js +670 -72
  350. package/dist/commands/workflow/runtime.js +15 -1
  351. package/dist/commands/workflow/skills.js +1 -0
  352. package/dist/commands/workflow/status.js +282 -34
  353. package/dist/commands/workflow/step-table.js +308 -0
  354. package/dist/commands/workflow/steps.js +703 -96
  355. package/dist/commands/workflow/summary-findings.js +117 -0
  356. package/dist/commands/workflow/summary.js +388 -0
  357. package/dist/commands/workflow/tasks.js +378 -0
  358. package/dist/commands/workflow/test-blocks.js +231 -0
  359. package/dist/commands/workflow/tests-changed.js +172 -0
  360. package/dist/commands/workflow/tests.js +1695 -305
  361. package/dist/commands/workflow/tracker.js +983 -0
  362. package/dist/commands/workflow/workflows.js +1014 -222
  363. package/dist/commands/workflow/worktrees.js +432 -26
  364. package/dist/install/cloud-env.js +233 -99
  365. package/dist/install/context-ci-workflow.js +85 -0
  366. package/dist/install/manifest.js +64 -17
  367. package/dist/install/modules/antigravity.js +3 -2
  368. package/dist/install/modules/cloud.js +25 -16
  369. package/dist/install/modules/codex.js +12 -2
  370. package/dist/install/modules/core.js +1090 -48
  371. package/dist/install/modules/cursor.js +6 -6
  372. package/dist/install/modules/opencode.js +13 -7
  373. package/dist/install/template-notes.js +116 -0
  374. package/dist/install/version-file.js +9 -4
  375. package/dist/ledgers/compact.js +87 -0
  376. package/dist/ledgers/journal.js +233 -0
  377. package/dist/ledgers/migrate.js +81 -0
  378. package/dist/ledgers/status.js +176 -13
  379. package/dist/ledgers/telemetry.js +1010 -125
  380. package/dist/render/hosts.js +104 -14
  381. package/dist/render/models.js +12 -0
  382. package/dist/shared/bkit-latest.js +26 -4
  383. package/dist/shared/branches.js +3 -1
  384. package/dist/shared/dep-updater.js +49 -0
  385. package/dist/shared/egress.js +8 -1
  386. package/dist/shared/json.js +20 -7
  387. package/dist/shared/package-manager.js +6 -0
  388. package/dist/shared/settings.js +181 -24
  389. package/dist/shared/text.js +333 -0
  390. package/dist/shared/timeouts.js +2 -0
  391. package/dist/tools/cli-doc.js +97 -0
  392. package/dist/tools/grammar-density.js +183 -0
  393. package/dist/tools/instructions-sources.js +720 -0
  394. package/dist/tools/instructions.js +1623 -0
  395. package/package.json +156 -51
  396. package/.bkit/core/.bkit/lite.md +0 -73
  397. package/.bkit/core/engine/commands/harvest.ts +0 -459
  398. package/.bkit/core/engine/commands/workflow/workstreams.ts +0 -166
  399. package/.bkit/core/engine/tools/wording.ts +0 -748
  400. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +0 -69
  401. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +0 -71
  402. package/.bkit/core/prompts/bkit-build-challenge-tests.md +0 -74
  403. package/.bkit/core/prompts/bkit-build-plan-execute.md +0 -76
  404. package/.bkit/core/prompts/bkit-build-summary.md +0 -94
  405. package/.bkit/core/prompts/bkit-debug-summary.md +0 -96
  406. package/.bkit/core/prompts/bkit-design-summary.md +0 -107
  407. package/.bkit/core/prompts/bkit-plan-complexity-check.md +0 -67
  408. package/.bkit/core/prompts/bkit-plan-complexity-split.md +0 -88
  409. package/.bkit/core/prompts/bkit-plan-review-3.md +0 -93
  410. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +0 -85
  411. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +0 -85
  412. package/.bkit/core/prompts/bkit-plan-summary.md +0 -107
  413. package/.bkit/core/prompts/bkit-ship-summary.md +0 -78
  414. package/.bkit/templates/scripts/ci/bkit-local-stack-lock.sh +0 -194
  415. package/dist/commands/harvest.js +0 -353
  416. package/dist/commands/workflow/workstreams.js +0 -143
  417. package/dist/tools/wording.js +0 -680
  418. /package/.bkit/templates/.vale/styles/{House → Bkit}/Filler.yml +0 -0
  419. /package/.bkit/templates/.vale/styles/{House → Bkit}/Hedging.yml +0 -0
  420. /package/.bkit/templates/.vale/styles/{House → Bkit}/LLMSlop.yml +0 -0
  421. /package/.bkit/templates/.vale/styles/{House → Bkit}/Verbose.yml +0 -0
  422. /package/.bkit/templates/scripts/ci/{accepted-advisories.json → bkit-accepted-advisories.json} +0 -0
  423. /package/.bkit/templates/scripts/ci/{accepted-divergences.json → bkit-accepted-divergences.json} +0 -0
  424. /package/.bkit/templates/scripts/launchd/{launchd.env.example → bkit-launchd.env.example} +0 -0
  425. /package/.bkit/templates/scripts/launchd/{ai.bkit.launchd.plist → bkit-launchd.plist} +0 -0
@@ -1,31 +1,39 @@
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.
1
+ // bkit branches sync|push|rebase|switch|land|fast-forward|scan-diff|force-build|
2
+ // anchor-stamp|anchor-read — the branch mechanics every phase workflow repeated
3
+ // inline: bring a feature branch up to date with dev, push it the one safe way
4
+ // for its kind, auto-resolve the rebase conflicts that lose nothing, return the
5
+ // main checkout to dev after a merge, land a design / plan close on dev,
6
+ // fast-forward onto a remote branch, route on what a branch's diff holds, force
7
+ // a full CI build, and stamp / read the base commit a design or plan doc was
8
+ // written against.
7
9
  //
8
10
  // Every verb works on `origin` and the integration branch `dev`, as the
9
11
  // workflows do. A push is always EXACTLY ONE `git push`: `dev` / `main` get a
10
12
  // plain push, every other branch `--force-with-lease`, so a shared branch is
11
13
  // never force-pushed and a personal one survives the rebase that rewrote it.
12
14
  import { spawnSync } from "node:child_process";
15
+ import { createHash } from "node:crypto";
13
16
  import * as fs from "node:fs";
14
17
  import * as os from "node:os";
15
18
  import * as path from "node:path";
16
19
  import { gitEnv } from "../../ledgers/telemetry.js";
17
- import { bodySkipToken, CommandError, DEV, EXIT, git, isSharedBranch, parseJson, repoRoot, runGit, SKIP_CI_TOKEN, } from "../lib.js";
20
+ import { actionHash, actionKey, alreadyDone, recordAction } from "../../ledgers/status.js";
21
+ import { bodySkipToken, classifyLockExit, CommandError, DEV, EXIT, ghUnavailable, git, isSharedBranch, OUTPUT_LIMIT, parseJson, repoRoot, runGh, runGit, SKIP_CI_TOKEN, testsLockHolder, wholeNumber, } from "../lib.js";
18
22
  import { bkitVersionStatus } from "../../shared/bkit-latest.js";
19
- import { landBackoffMs, landDir, pushToDev, sleep } from "../land.js";
23
+ import { parseBkitVersion, serializeBkitVersion, } from "../../install/version-file.js";
24
+ import { DEV_REFSPEC, fetchDev, landBackoffMs, landDir, pushToDev, sleep } from "../land.js";
20
25
  import { TIMEOUTS } from "../../shared/timeouts.js";
21
- import { commitBookkeeping } from "./ledgers.js";
26
+ import { activeRecord, commitBookkeeping, markRecordPushed, recordOnBranch, } from "./ledgers.js";
22
27
  import { releaseLock, resolveMonth, workflowLockPath } from "./locks.js";
23
- import { closeTransportRow, crossCheckRows, mergePr, openPrFor, probePr, updateBranch, } from "./prs.js";
28
+ import { EXIT_BASE_NOT_DEV, FORCE_BUILD, closeTransportRow, crossCheckRows, mergePr, openPrFor, probePr, } from "./prs.js";
29
+ import { AUTO_LABEL, AUTO_ROUTE_SUFFIX } from "./issues.js";
24
30
  import { appendFeature } from "./roadmap.js";
25
31
  import { detect } from "./runtime.js";
26
- import { readStatusRows, readStatusRowsAt } from "./status.js";
27
- import { removeWorktree, worktreeDir } from "./worktrees.js";
28
- import { COULD_NOT_RUN_EXIT_CODES, LOCKFILE_REGENERATE, installCommand, } from "../../shared/package-manager.js";
32
+ import { readRuns, readStatusRows, readStatusRowsAt } from "./status.js";
33
+ import { declaredName, testSource } from "./test-blocks.js";
34
+ import { addAllButCopied, copyExcludes, hasLeftovers, recordRebase, removeWorktree, worktreeDir, } from "./worktrees.js";
35
+ import { COULD_NOT_RUN_EXIT_CODES, LOCKFILE_REGENERATE, installCommand, scriptCommand, } from "../../shared/package-manager.js";
36
+ import { readPackageJson } from "../../shared/package-json.js";
29
37
  import { str } from "./status.js";
30
38
  const REMOTE = "origin";
31
39
  const UPSTREAM = `${REMOTE}/${DEV}`;
@@ -45,25 +53,26 @@ export const EXIT_INSTALL_FAILED = 16;
45
53
  export const EXIT_LAND_STOPPED = 17;
46
54
  export const EXIT_LANDED_UNVERIFIED = 18;
47
55
  export const EXIT_LOCK_LEFT = 19;
56
+ export const EXIT_NO_RECORD = 20;
57
+ export const EXIT_NOTHING_TO_PUSH = 21;
58
+ export const EXIT_DIVERGED = 22;
59
+ export const EXIT_DIFF_FAILED = 23;
60
+ export const EXIT_HAND_RESOLVE = 24;
61
+ export const EXIT_GENERATE_FAILED = 25;
48
62
  // ---------------------------------------------------------------------------
49
63
  // Process helpers
50
64
  // ---------------------------------------------------------------------------
51
65
  /** git with a non-interactive editor, so `--continue` / `--skip` / merge commits never open one. */
52
- const quietGit = (cwd, args) => {
53
- const res = spawnSync("git", args, {
54
- cwd,
55
- encoding: "utf-8",
56
- env: { ...gitEnv(), GIT_EDITOR: "true" },
57
- });
58
- return {
59
- ok: res.status === 0,
60
- stdout: (res.stdout ?? "").trim(),
61
- stderr: (res.stderr ?? "").trim(),
62
- };
63
- };
64
- /** `git show :<stage>:<path>` as raw bytes; empty when that stage does not exist. */
66
+ const quietGit = (cwd, args) => runGit(cwd, args, { GIT_EDITOR: "true" });
67
+ /** `git show :<stage>:<path>` as raw bytes; empty when that stage does not exist, null when git could not run. */
65
68
  function stageBytes(top, stage, file) {
66
- const res = spawnSync("git", ["show", `:${stage}:${file}`], { cwd: top, env: gitEnv() });
69
+ const res = spawnSync("git", ["show", `:${stage}:${file}`], {
70
+ cwd: top,
71
+ env: gitEnv(),
72
+ maxBuffer: OUTPUT_LIMIT,
73
+ });
74
+ if (res.error)
75
+ return null;
67
76
  // A missing stage is a legitimate shape (add/add, delete/modify): merge against empty.
68
77
  return res.status === 0 ? res.stdout : Buffer.alloc(0);
69
78
  }
@@ -91,7 +100,7 @@ const currentBranch = (cwd) => git(cwd, ["branch", "--show-current"]) ?? "";
91
100
  * ledger or is missing.
92
101
  *
93
102
  * `.bkit/friction.jsonl` ships WITHOUT `merge=union` but is listed here; a row union
94
- * resurrects after `bkit harvest` drained it is re-banked by the next harvest.
103
+ * resurrects after the harvest drained it is re-banked by the next harvest.
95
104
  *
96
105
  * `docs/roadmap.md` is not append-only — it is regenerated from
97
106
  * `.bkit/issues.jsonl` — but every workflow close re-folds it, so both sides of
@@ -116,8 +125,56 @@ const globToRegExp = (glob) => new RegExp(`^${glob
116
125
  .replace(/\*/g, "[^/]*")
117
126
  .replace(/\0/g, ".*")}$`);
118
127
  const LEDGER_PATTERNS = LEDGERS.map(globToRegExp);
119
- /** How a conflicted path may be resolved. Only repo-root lockfiles count: the regenerate runs there. */
120
- export function classifyConflict(file) {
128
+ /** bkit's install record: merged entry by entry (`recordResolve`), never line by line. */
129
+ export const INSTALL_RECORD = ".bkit/version";
130
+ /**
131
+ * Generated registers a conflict is settled in by taking dev's copy. Each side rebuilt
132
+ * the whole file, so neither side's text is worth a hand merge, and running `script`
133
+ * with `args` after the rebase or merge makes dev's copy current. `keep` brackets the
134
+ * one hand-written region, which the rebuild reads back and re-emits, so a branch's
135
+ * edit to it is carried onto dev's copy. `embed` names the variable in `script` that
136
+ * lists the hand-written docs the rebuild copies a generated block into, and the
137
+ * markers around that block.
138
+ */
139
+ export const REGISTERS = {
140
+ "docs/capabilities.md": {
141
+ script: "scripts/graphify/bkit-graphify.sh",
142
+ args: ["refresh"],
143
+ keep: ["<!-- overrides:start -->", "<!-- overrides:end -->"],
144
+ embed: {
145
+ variable: "GRAPH_EMBED_DOCS",
146
+ block: ["<!-- graph:packages:start -->", "<!-- graph:packages:end -->"],
147
+ },
148
+ },
149
+ };
150
+ /**
151
+ * Each doc a register's script in `top` embeds a generated block into, mapped to that
152
+ * register. Read from the script's own `embed.variable` assignment, so a repo whose
153
+ * script lists no docs, or that has no script, gets an empty map.
154
+ */
155
+ export function embedDocs(top) {
156
+ const out = new Map();
157
+ for (const [register, entry] of Object.entries(REGISTERS)) {
158
+ const script = path.join(top, entry.script);
159
+ if (!fs.existsSync(script))
160
+ continue;
161
+ const assigned = new RegExp(`^${entry.embed.variable}="([^"]*)"`, "m").exec(fs.readFileSync(script, "utf-8"));
162
+ for (const doc of (assigned?.[1] ?? "").split(/\s+/).filter(Boolean))
163
+ out.set(doc, register);
164
+ }
165
+ return out;
166
+ }
167
+ /**
168
+ * How a conflicted path may be resolved. Only repo-root lockfiles count: the regenerate
169
+ * runs there. `embeds` is the repo's `embedDocs`.
170
+ */
171
+ export function classifyConflict(file, embeds = new Map()) {
172
+ if (Object.hasOwn(REGISTERS, file))
173
+ return "register";
174
+ if (embeds.has(file))
175
+ return "embed";
176
+ if (file === INSTALL_RECORD)
177
+ return "record";
121
178
  if (Object.hasOwn(LOCKFILE_REGENERATE, file))
122
179
  return "lockfile";
123
180
  if (LEDGER_PATTERNS.some((re) => re.test(file)))
@@ -147,7 +204,10 @@ export function unionResolve(top, file) {
147
204
  try {
148
205
  const sides = { base: 1, ours: 2, theirs: 3 };
149
206
  for (const [name, stage] of Object.entries(sides)) {
150
- fs.writeFileSync(path.join(tmp, name), stageBytes(top, stage, file));
207
+ const bytes = stageBytes(top, stage, file);
208
+ if (bytes === null)
209
+ return { ok: false, problem: `git show :${stage}:${file} failed` };
210
+ fs.writeFileSync(path.join(tmp, name), bytes);
151
211
  }
152
212
  const merged = spawnSync("git", [
153
213
  "merge-file",
@@ -156,9 +216,9 @@ export function unionResolve(top, file) {
156
216
  path.join(tmp, "ours"),
157
217
  path.join(tmp, "base"),
158
218
  path.join(tmp, "theirs"),
159
- ], { cwd: top, env: gitEnv() });
219
+ ], { cwd: top, env: gitEnv(), maxBuffer: OUTPUT_LIMIT });
160
220
  // --union never leaves conflict markers, so a non-zero exit is an I/O failure.
161
- if (merged.status !== 0)
221
+ if (merged.error || merged.status !== 0)
162
222
  return { ok: false, problem: "git merge-file --union failed" };
163
223
  let text = merged.stdout.toString("utf-8");
164
224
  if (file.endsWith(".jsonl")) {
@@ -178,20 +238,163 @@ export function unionResolve(top, file) {
178
238
  }
179
239
  }
180
240
  /**
181
- * Resolve a lockfile conflict: start from the rebase target's copy, then
182
- * regenerate from the manifest, which merged normally (or refused and stopped
183
- * the rebase before this). During a rebase `--ours` is the branch being rebased
184
- * ONTO; `--theirs` is the commit being replayed.
241
+ * Resolve a lockfile conflict: start from dev's copy, then regenerate from the
242
+ * manifest, which merged normally (or refused and stopped the rebase or merge
243
+ * before this). During a rebase dev is `--ours` (the branch being rebased ONTO;
244
+ * `--theirs` is the commit being replayed); in a merge of origin/dev it is `--theirs`.
185
245
  */
186
- function lockfileResolve(top, file) {
246
+ function lockfileResolve(top, file, dev = "ours") {
187
247
  const regenerate = LOCKFILE_REGENERATE[file];
188
248
  if (!regenerate)
189
249
  return false;
190
- if (!runGit(top, ["checkout", "--ours", "--", file]).ok)
250
+ if (!runGit(top, ["checkout", `--${dev}`, "--", file]).ok)
191
251
  return false;
192
252
  const res = spawnSync(regenerate[0], regenerate.slice(1), { cwd: top, stdio: "ignore" });
193
253
  return res.status === 0;
194
254
  }
255
+ /** The text from `keep`'s open marker through its close marker; null when either is missing. */
256
+ function keptRegion(text, [open, close]) {
257
+ const start = text.indexOf(open);
258
+ if (start === -1)
259
+ return null;
260
+ const end = text.indexOf(close, start + open.length);
261
+ return end === -1 ? null : text.slice(start, end + close.length);
262
+ }
263
+ /**
264
+ * Settle a conflicted register on dev's copy, carrying the branch's edit to the
265
+ * hand-written region when dev left that region as the merge base had it. Refuses when
266
+ * a side deleted the file, or both sides changed the region: that needs a hand merge.
267
+ * During a rebase dev is `ours`; in a merge of origin/dev it is `theirs`.
268
+ */
269
+ export function registerResolve(top, file, dev) {
270
+ const entry = REGISTERS[file];
271
+ if (entry === undefined)
272
+ return { ok: false, problem: "not a generated register" };
273
+ const base = stageBytes(top, 1, file);
274
+ const devSide = stageBytes(top, dev === "ours" ? 2 : 3, file);
275
+ const branchSide = stageBytes(top, dev === "ours" ? 3 : 2, file);
276
+ if (base === null || devSide === null || branchSide === null)
277
+ return { ok: false, problem: "git show of a conflict stage failed" };
278
+ if (devSide.length === 0 || branchSide.length === 0)
279
+ return { ok: false, problem: "one side deleted the register" };
280
+ let text = devSide.toString("utf-8");
281
+ const baseKept = keptRegion(base.toString("utf-8"), entry.keep);
282
+ const devKept = keptRegion(text, entry.keep);
283
+ const branchKept = keptRegion(branchSide.toString("utf-8"), entry.keep);
284
+ if (branchKept !== baseKept && branchKept !== devKept) {
285
+ if (devKept !== baseKept)
286
+ return { ok: false, problem: "both sides changed the hand-written region" };
287
+ if (devKept === null || branchKept === null)
288
+ return { ok: false, problem: "one side added or removed the hand-written region" };
289
+ text = text.replace(devKept, () => branchKept);
290
+ }
291
+ fs.writeFileSync(path.join(top, file), text);
292
+ return { ok: true };
293
+ }
294
+ /**
295
+ * Settle a conflicted doc that embeds a register's generated block: give all three
296
+ * stages dev's copy of the block, then merge the rest of the doc as git would. Refuses
297
+ * when a side lacks the block, or when the doc still conflicts outside it: that needs a
298
+ * hand merge. The register's rebuild rewrites the block afterwards.
299
+ */
300
+ export function embedResolve(top, file, register, dev) {
301
+ const entry = REGISTERS[register];
302
+ if (entry === undefined)
303
+ return { ok: false, problem: "not a generated register" };
304
+ const stages = { base: 1, ours: 2, theirs: 3 };
305
+ const texts = { base: "", ours: "", theirs: "" };
306
+ for (const [name, stage] of Object.entries(stages)) {
307
+ const bytes = stageBytes(top, stage, file);
308
+ if (bytes === null)
309
+ return { ok: false, problem: `git show :${stage}:${file} failed` };
310
+ texts[name] = bytes.toString("utf-8");
311
+ }
312
+ const devBlock = keptRegion(texts[dev], entry.embed.block);
313
+ if (devBlock === null)
314
+ return { ok: false, problem: "a side lacks the generated block" };
315
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bkit-embed-"));
316
+ try {
317
+ for (const name of Object.keys(stages)) {
318
+ const block = keptRegion(texts[name], entry.embed.block);
319
+ if (block === null)
320
+ return { ok: false, problem: "a side lacks the generated block" };
321
+ fs.writeFileSync(path.join(tmp, name), texts[name].replace(block, () => devBlock));
322
+ }
323
+ const merged = spawnSync("git", [
324
+ "merge-file",
325
+ "-p",
326
+ path.join(tmp, "ours"),
327
+ path.join(tmp, "base"),
328
+ path.join(tmp, "theirs"),
329
+ ], { cwd: top, env: gitEnv(), maxBuffer: OUTPUT_LIMIT });
330
+ // Exit status = conflicts left, capped at 127; above that it failed.
331
+ if (merged.error || merged.status === null || merged.status > 127)
332
+ return { ok: false, problem: "git merge-file failed" };
333
+ if (merged.status > 0)
334
+ return { ok: false, problem: "it conflicts outside the generated block" };
335
+ fs.writeFileSync(path.join(top, file), merged.stdout);
336
+ return { ok: true };
337
+ }
338
+ finally {
339
+ fs.rmSync(tmp, { recursive: true, force: true });
340
+ }
341
+ }
342
+ /** The value one entry takes: the side that changed it, or dev's when both did. */
343
+ function pickEntry(base, dev, branch) {
344
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
345
+ return same(dev, base) ? branch : dev;
346
+ }
347
+ /**
348
+ * Merge a conflicted install record entry by entry: `pinnedVersion`,
349
+ * `claudeAllowDerived` and each `canonicalHashes` path take the side that changed
350
+ * them, and dev's value when both did. A fingerprint left at dev's value makes
351
+ * `bkit upgrade` treat that file as edited by hand until it refreshes the entry, so
352
+ * the record needs no rebuild. Refuses when a side deleted the record or a copy is
353
+ * not a record. During a rebase dev is `ours`; in a merge of origin/dev it is `theirs`.
354
+ */
355
+ export function recordResolve(top, dev) {
356
+ const copies = [];
357
+ for (const stage of [1, dev === "ours" ? 2 : 3, dev === "ours" ? 3 : 2]) {
358
+ const bytes = stageBytes(top, stage, INSTALL_RECORD);
359
+ if (bytes === null)
360
+ return { ok: false, problem: `git show :${stage}:${INSTALL_RECORD} failed` };
361
+ if (bytes.length === 0 && stage !== 1)
362
+ return { ok: false, problem: "one side deleted the install record" };
363
+ // Both sides adding the record leaves no base: merge against an empty one.
364
+ const parsed = bytes.length === 0
365
+ ? { pinnedVersion: "", canonicalHashes: {}, claudeAllowDerived: [] }
366
+ : parseBkitVersion(bytes.toString("utf-8"));
367
+ if (parsed === null)
368
+ return { ok: false, problem: "a copy of the install record is not valid" };
369
+ copies.push(parsed);
370
+ }
371
+ const [base, devSide, branch] = copies;
372
+ const canonicalHashes = {};
373
+ for (const p of new Set([
374
+ ...Object.keys(devSide.canonicalHashes),
375
+ ...Object.keys(branch.canonicalHashes),
376
+ ])) {
377
+ const hash = pickEntry(base.canonicalHashes[p], devSide.canonicalHashes[p], branch.canonicalHashes[p]);
378
+ if (hash !== undefined)
379
+ canonicalHashes[p] = hash;
380
+ }
381
+ const merged = {
382
+ pinnedVersion: pickEntry(base.pinnedVersion, devSide.pinnedVersion, branch.pinnedVersion),
383
+ canonicalHashes,
384
+ claudeAllowDerived: pickEntry(base.claudeAllowDerived, devSide.claudeAllowDerived, branch.claudeAllowDerived),
385
+ };
386
+ fs.writeFileSync(path.join(top, INSTALL_RECORD), serializeBkitVersion(merged));
387
+ return { ok: true };
388
+ }
389
+ const NOT_RESOLVABLE = "not an append-only ledger, a recognised lockfile, a generated register, a doc embedding one or the install record";
390
+ /** How a rebase settled each kind of conflict, for its log. */
391
+ const REBASE_HOW = {
392
+ union: "union (append-only ledger)",
393
+ lockfile: "took rebase target + regenerated",
394
+ register: "took rebase target's copy of a generated register",
395
+ embed: "took rebase target's copy of the generated block, merged the rest",
396
+ record: "merged the install record entry by entry, rebase target's value where both changed",
397
+ };
195
398
  /**
196
399
  * Drive an in-progress rebase to completion, auto-resolving each stop. Loops
197
400
  * because `--continue` replays the next commit, which can conflict in turn; the
@@ -218,26 +421,40 @@ export function resolveRebase(top, onLog = () => undefined) {
218
421
  result.reason = reason;
219
422
  return result;
220
423
  };
424
+ const embeds = embedDocs(top);
221
425
  while (result.rounds < 100) {
222
426
  result.rounds++;
223
427
  const conflicts = unmergedPaths(top);
224
428
  if (conflicts.length > 0) {
225
429
  // Classify the whole set before resolving any of it, so a refused path
226
430
  // never leaves half the set rewritten.
227
- const refused = conflicts.find((f) => classifyConflict(f) === "refuse");
431
+ const refused = conflicts.find((f) => classifyConflict(f, embeds) === "refuse");
228
432
  if (refused !== undefined) {
229
- return refuse(`REFUSE ${refused} — not an append-only ledger or a recognised lockfile; routing to Failure Path`, refused, "not an append-only ledger or a recognised lockfile");
433
+ return refuse(`REFUSE ${refused} — ${NOT_RESOLVABLE}; routing to Failure Path`, refused, NOT_RESOLVABLE);
230
434
  }
231
435
  for (const f of conflicts) {
232
- const kind = classifyConflict(f);
233
- const ok = kind === "ledger" ? unionResolve(top, f).ok : lockfileResolve(top, f);
436
+ const kind = classifyConflict(f, embeds);
437
+ const settled = kind === "register"
438
+ ? registerResolve(top, f, "ours")
439
+ : kind === "embed"
440
+ ? embedResolve(top, f, embeds.get(f), "ours")
441
+ : kind === "record"
442
+ ? recordResolve(top, "ours")
443
+ : null;
444
+ if (settled !== null && !settled.ok)
445
+ return refuse(`REFUSE ${f} — ${settled.problem}`, f, settled.problem);
446
+ const ok = settled !== null ||
447
+ (kind === "ledger" ? unionResolve(top, f).ok : lockfileResolve(top, f));
234
448
  if (!ok || !runGit(top, ["add", "--", f]).ok) {
235
449
  return refuse(`REFUSE ${f} — resolution failed`, f, "resolution failed");
236
450
  }
237
- result.resolved.push({ path: f, how: kind === "ledger" ? "union" : "lockfile" });
238
- log(kind === "ledger"
239
- ? `RESOLVED ${f} — union (append-only ledger)`
240
- : `RESOLVED ${f} — took rebase target + regenerated`);
451
+ const how = kind === "ledger"
452
+ ? "union"
453
+ : kind === "register" || kind === "embed" || kind === "record"
454
+ ? kind
455
+ : "lockfile";
456
+ result.resolved.push({ path: f, how });
457
+ log(`RESOLVED ${f} — ${REBASE_HOW[how]}`);
241
458
  }
242
459
  }
243
460
  // A resolution can empty the commit (both sides appended the same rows);
@@ -362,6 +579,7 @@ function openPrNumber(cwd, branch) {
362
579
  const res = spawnSync("gh", ["pr", "list", "--head", branch, "--state", "open", "--json", "number,state"], {
363
580
  cwd,
364
581
  encoding: "utf-8",
582
+ maxBuffer: OUTPUT_LIMIT,
365
583
  });
366
584
  const parsed = res.status === 0 ? parseJson(res.stdout ?? "") : { ok: false };
367
585
  const prs = parsed.ok ? parsed.value : undefined;
@@ -400,6 +618,7 @@ function rebaseVerb(ctx) {
400
618
  ctx.log("no rebase in progress");
401
619
  return EXIT_NO_REBASE;
402
620
  }
621
+ const origHead = rebaseOrigHead(top);
403
622
  const result = resolveRebase(top, (line) => ctx.log(line));
404
623
  let aborted = false;
405
624
  if (!result.ok) {
@@ -412,6 +631,14 @@ function rebaseVerb(ctx) {
412
631
  result.log.push(line);
413
632
  ctx.log(line);
414
633
  }
634
+ let rebuilt = null;
635
+ if (result.ok) {
636
+ const fid = currentBranch(top).replace(/^feat\//, "") || "rebase";
637
+ rebuilt = rebuildRegisters(top, result.resolved, (files) => `chore(${fid}): rebuild ${files.join(" ")} after the rebase`, (line) => {
638
+ result.log.push(line);
639
+ ctx.log(line);
640
+ });
641
+ }
415
642
  appendLog(ctx, str(ctx.flags.logFile), result.log);
416
643
  if (!result.ok && sentinelPath) {
417
644
  fs.mkdirSync(path.dirname(sentinelPath), { recursive: true });
@@ -426,15 +653,55 @@ function rebaseVerb(ctx) {
426
653
  reason: result.reason,
427
654
  aborted,
428
655
  sentinel: !result.ok && sentinel !== undefined ? sentinel : null,
656
+ rebuilt,
429
657
  });
658
+ const statusFile = str(ctx.flags.file);
659
+ if (result.ok && statusFile !== undefined)
660
+ recordRebase(path.resolve(ctx.cwd, statusFile), origHead, git(top, ["rev-parse", "HEAD"]));
430
661
  return result.ok ? EXIT.OK : EXIT_REFUSED;
431
662
  }
663
+ /** The branch tip the in-progress rebase started from. */
664
+ function rebaseOrigHead(top) {
665
+ for (const dir of ["rebase-merge", "rebase-apply"]) {
666
+ const file = git(top, [
667
+ "rev-parse",
668
+ "--path-format=absolute",
669
+ "--git-path",
670
+ `${dir}/orig-head`,
671
+ ]);
672
+ if (file !== null && fs.existsSync(file))
673
+ return fs.readFileSync(file, "utf-8").trim();
674
+ }
675
+ return null;
676
+ }
677
+ /** Git collapses a failing pre-push hook's status; classify its exact tests-lock markers. */
678
+ function runPush(cwd, args, branch) {
679
+ const who = `bkit branches push ${branch}`;
680
+ const wait = wholeNumber(process.env.BKIT_LOCK_WAIT_S, "BKIT_LOCK_WAIT_S", 60);
681
+ const res = runGit(cwd, args, {
682
+ LOCAL_STACK_LOCK_WAIT_S: String(wait),
683
+ LOCAL_STACK_LOCK_WHO: who,
684
+ });
685
+ const log = [res.stdout, res.stderr].filter(Boolean).join("\n");
686
+ const lockHolder = res.ok ? null : testsLockHolder(log, who);
687
+ const outcome = res.ok
688
+ ? "gate"
689
+ : classifyLockExit({ exitCode: lockHolder === null ? 73 : 75, log, who });
690
+ return {
691
+ ...res,
692
+ lockHolder,
693
+ lockExit: outcome === "lock-wait" ? EXIT.AGENT_WAIT : outcome === "could-not-run" ? 4 : null,
694
+ };
695
+ }
432
696
  /**
433
697
  * Push the current branch with exactly one `git push`: plain for dev / main,
434
698
  * `--force-with-lease` otherwise. `abort` never pushes into an open PR (`openPr`:
435
699
  * the answer MCP gave; undefined asks gh, which throws EXIT.USE_MCP when it cannot).
700
+ * An in-place run on dev (a shared-checkout record exists) pushes only the
701
+ * commits it made: plain when they are all that local dev holds beyond
702
+ * origin/dev, else replayed onto a fresh origin/dev through `pushToDev`.
436
703
  */
437
- export function pushBranch(cwd, o, log) {
704
+ export async function pushBranch(cwd, o, log) {
438
705
  const { mode, openPr: openPrFlag } = o;
439
706
  if (openPrFlag !== undefined && openPrFlag !== "none" && !/^[1-9][0-9]*$/.test(openPrFlag)) {
440
707
  throw new CommandError(EXIT.USAGE, `--open-pr must be a PR number or none, got "${openPrFlag}"`);
@@ -449,6 +716,8 @@ export function pushBranch(cwd, o, log) {
449
716
  forced: false,
450
717
  skipped: null,
451
718
  prNumber: null,
719
+ replayed: false,
720
+ mergedDev: false,
452
721
  ...extra,
453
722
  },
454
723
  });
@@ -460,14 +729,43 @@ export function pushBranch(cwd, o, log) {
460
729
  log(`--mode=dev pushes ${DEV}, but the checkout is on ${branch}`);
461
730
  return notPushed(EXIT_NOT_DEV);
462
731
  }
732
+ if (mode === "plain")
733
+ return pushPlain(cwd, branch, o, log, notPushed);
734
+ const shared = isSharedBranch(branch);
735
+ const rec = !shared
736
+ ? null
737
+ : o.fid === undefined
738
+ ? recordOnBranch(cwd, branch)
739
+ : activeRecord(cwd, o.fid);
740
+ // Without the run's record the push would carry all of local dev, not the run's commits.
741
+ if (shared && rec === null && (mode === "dev" || o.fid !== undefined)) {
742
+ log(`no shared-checkout record${o.fid === undefined ? "" : ` for ${o.fid}`} on ${branch} — refusing to push: it would carry commits the run does not own`);
743
+ return notPushed(EXIT_NO_RECORD);
744
+ }
463
745
  if (o.requireCi === true) {
464
- const message = git(cwd, ["log", "-1", "--pretty=%B"]) ?? "";
746
+ // With a record, the commit that reaches the remote last is the run's own.
747
+ const last = rec?.commits.at(-1) ?? "HEAD";
748
+ const message = git(cwd, ["log", "-1", "--pretty=%B", last]) ?? "";
465
749
  if (SKIP_CI_TOKEN.test(message)) {
466
750
  log(`HEAD message on ${branch} carries a CI-suppressing token, and this push needs a CI run — refusing`);
467
751
  return notPushed(EXIT_SKIP_CI, { skipped: "skip-ci" });
468
752
  }
469
753
  }
470
- const shared = isSharedBranch(branch);
754
+ if (rec !== null)
755
+ return pushOwnCommits(cwd, rec, o, log, notPushed);
756
+ let mergedDev = false;
757
+ if (mode === "feature" && o.requireCi === true && !shared) {
758
+ const top = topLevel(cwd);
759
+ const fetched = fetchDev(top);
760
+ if (!fetched.ok) {
761
+ log(`git fetch ${REMOTE} ${DEV} failed: ${fetched.stderr}`);
762
+ return notPushed(EXIT_FETCH_FAILED);
763
+ }
764
+ const m = mergeDevDocs(top, { branch, generate: true }, log);
765
+ if (m.code !== EXIT.OK)
766
+ return notPushed(m.code, { mergedDev: m.merged });
767
+ mergedDev = m.merged;
768
+ }
471
769
  if (mode === "abort" && !shared) {
472
770
  const pr = openPrFlag === undefined
473
771
  ? openPrNumber(cwd, branch)
@@ -488,10 +786,10 @@ export function pushBranch(cwd, o, log) {
488
786
  REMOTE,
489
787
  branch,
490
788
  ];
491
- const res = runGit(cwd, args);
789
+ const res = runPush(cwd, args, branch);
492
790
  if (!res.ok) {
493
791
  log(`git ${args.join(" ")} failed: ${res.stderr}`);
494
- return notPushed(EXIT_PUSH_FAILED);
792
+ return notPushed(res.lockExit ?? EXIT_PUSH_FAILED, { lockHolder: res.lockHolder });
495
793
  }
496
794
  log(`pushed ${branch}${shared ? "" : " (--force-with-lease)"}`);
497
795
  return {
@@ -503,59 +801,1125 @@ export function pushBranch(cwd, o, log) {
503
801
  forced: !shared,
504
802
  skipped: null,
505
803
  prNumber: null,
804
+ replayed: false,
805
+ mergedDev,
806
+ },
807
+ };
808
+ }
809
+ /**
810
+ * `git fetch` of `ref` when it names a branch of origin (`origin/<b>`); null when
811
+ * it names anything else (a SHA, a local branch), which needs no fetch.
812
+ */
813
+ export function fetchRemoteRef(cwd, ref) {
814
+ const m = new RegExp(`^${REMOTE}/(.+)$`).exec(ref);
815
+ if (!m)
816
+ return null;
817
+ return runGit(cwd, ["fetch", REMOTE, `+refs/heads/${m[1]}:refs/remotes/${REMOTE}/${m[1]}`]);
818
+ }
819
+ /** Commits HEAD holds beyond `ref`; 0 when the count cannot be read. */
820
+ function commitsAhead(cwd, ref) {
821
+ const n = Number(git(cwd, ["rev-list", "--count", `${ref}..HEAD`]) ?? "0");
822
+ return Number.isFinite(n) ? n : 0;
823
+ }
824
+ /**
825
+ * `--mode=plain`: one `git push [-u] origin <branch>`, never forced. A feature
826
+ * branch only: dev / main and a branch with nothing beyond `aheadOf` have nothing to ship.
827
+ */
828
+ function pushPlain(cwd, branch, o, log, notPushed) {
829
+ if (isSharedBranch(branch)) {
830
+ log(`Nothing to ship: on '${branch}', no feature branch`);
831
+ return notPushed(EXIT_NOTHING_TO_PUSH);
832
+ }
833
+ if (o.aheadOf !== undefined) {
834
+ const fetched = fetchRemoteRef(cwd, o.aheadOf);
835
+ if (fetched !== null && !fetched.ok) {
836
+ log(`git fetch for ${o.aheadOf} failed: ${fetched.stderr} — counting against the local ref`);
837
+ }
838
+ if (commitsAhead(cwd, o.aheadOf) === 0) {
839
+ log(`Nothing to ship: ${branch} has no commits ahead of ${o.aheadOf}`);
840
+ return notPushed(EXIT_NOTHING_TO_PUSH);
841
+ }
842
+ }
843
+ if (o.requireCi === true && SKIP_CI_TOKEN.test(git(cwd, ["log", "-1", "--pretty=%B"]) ?? "")) {
844
+ log(`HEAD message on ${branch} carries a CI-suppressing token, and this push needs a CI run — refusing`);
845
+ return notPushed(EXIT_SKIP_CI, { skipped: "skip-ci" });
846
+ }
847
+ const args = ["push", ...(o.setUpstream === true ? ["-u"] : []), REMOTE, branch];
848
+ const res = runPush(cwd, args, branch);
849
+ if (!res.ok) {
850
+ log(`git ${args.join(" ")} failed: ${res.stderr}`);
851
+ return notPushed(res.lockExit ?? EXIT_PUSH_FAILED, { lockHolder: res.lockHolder });
852
+ }
853
+ log(`pushed ${branch}`);
854
+ return {
855
+ code: EXIT.OK,
856
+ out: {
857
+ pushed: true,
858
+ ref: branch,
859
+ sha: git(cwd, ["rev-parse", "HEAD"]),
860
+ forced: false,
861
+ skipped: null,
862
+ prNumber: null,
863
+ replayed: false,
864
+ mergedDev: false,
506
865
  },
507
866
  };
508
867
  }
509
- function pushVerb(ctx) {
868
+ /**
869
+ * The `key` of an engine-action row for a marker commit this run makes: keyed on the
870
+ * workflow's latest run, in progress or just closed by `workflows close`.
871
+ */
872
+ function markerKey(file, workflow, what) {
873
+ const runs = fs.existsSync(file) ? readRuns(file).filter((r) => r.workflow === workflow) : [];
874
+ return actionKey(workflow, Math.max(runs.length, 1), what);
875
+ }
876
+ /**
877
+ * Make a marker commit once per run: an engine-action row with the same key and
878
+ * message whose commit is still on HEAD means it is already made (`deduped`).
879
+ * `addAll` stages every change first (`git add -A`); the commit is always
880
+ * allowed to be empty. The row is written before the caller pushes.
881
+ */
882
+ function markerCommit(cwd, o) {
883
+ const hash = actionHash(o.message);
884
+ const prior = alreadyDone(o.file, o.key, hash);
885
+ if (prior?.ref && runGit(cwd, ["merge-base", "--is-ancestor", prior.ref, "HEAD"]).ok) {
886
+ return { sha: prior.ref, deduped: true };
887
+ }
888
+ if (o.addAll) {
889
+ const added = addAllButCopied(cwd);
890
+ if (!added.ok)
891
+ throw new CommandError(EXIT_PUSH_FAILED, `git add -A failed: ${added.stderr}`);
892
+ }
893
+ const made = runGit(cwd, ["commit", "--allow-empty", "-m", o.message]);
894
+ if (!made.ok) {
895
+ throw new CommandError(EXIT_PUSH_FAILED, `git commit failed: ${made.stderr || made.stdout}`);
896
+ }
897
+ const sha = git(cwd, ["rev-parse", "HEAD"]) ?? "";
898
+ recordAction(o.file, { action: "commit", key: o.key, hash, ref: sha });
899
+ return { sha, deduped: false };
900
+ }
901
+ const autoRouteSuffix = (labels) => labels.includes(AUTO_LABEL) ? AUTO_ROUTE_SUFFIX : "";
902
+ /** A replayed commit that does not apply onto origin/dev without the foreign commits it builds on. */
903
+ class ReplayConflict extends Error {
904
+ }
905
+ /**
906
+ * The `pushToDev` build callback that replays `shas` (oldest first) onto the
907
+ * fresh origin/dev in `dir`, each as a cherry-pick that keeps its message and
908
+ * author and keeps empty commits. A commit that does not apply throws a
909
+ * ReplayConflict naming the conflicting paths, after aborting the cherry-pick.
910
+ */
911
+ export function replayBuild(shas) {
912
+ return (dir) => {
913
+ for (const sha of shas) {
914
+ const picked = runGit(dir, ["cherry-pick", "--allow-empty", "--keep-redundant-commits", sha]);
915
+ if (picked.ok)
916
+ continue;
917
+ const paths = (git(dir, ["diff", "--name-only", "--diff-filter=U"]) ?? "")
918
+ .split("\n")
919
+ .filter(Boolean);
920
+ runGit(dir, ["cherry-pick", "--abort"]);
921
+ throw new ReplayConflict(`commit ${sha.slice(0, 12)} does not apply onto ${UPSTREAM} without the local ${DEV} commits it builds on — ${paths.length > 0 ? `conflicts in: ${paths.join(", ")}` : picked.stderr}`);
922
+ }
923
+ };
924
+ }
925
+ /**
926
+ * Push only the commits an in-place run on dev made (the record's `commits`).
927
+ * Plain push of their tip SHA when origin/dev is an ancestor of local dev and they
928
+ * are exactly what local dev holds beyond it; otherwise (a foreign commit among
929
+ * them, origin/dev moved, or the plain push is rejected) they are replayed onto a
930
+ * fresh origin/dev in the throwaway checkout and pushed from there.
931
+ */
932
+ async function pushOwnCommits(cwd, rec, o, log, notPushed) {
933
+ const gone = rec.commits.filter((c) => !runGit(cwd, ["merge-base", "--is-ancestor", c, "HEAD"]).ok);
934
+ if (gone.length > 0) {
935
+ log(`the run's commit(s) ${gone.map((c) => c.slice(0, 12)).join(", ")} are no longer on ${rec.branch} — refusing to push`);
936
+ return notPushed(EXIT_PUSH_FAILED);
937
+ }
938
+ const fetched = fetchDev(cwd);
939
+ if (!fetched.ok) {
940
+ log(`git fetch ${REMOTE} ${DEV} failed: ${fetched.stderr}`);
941
+ return notPushed(EXIT_FETCH_FAILED);
942
+ }
943
+ // Oldest first, minus what origin/dev already has (pushed plain before) and
944
+ // what an earlier replay already landed.
945
+ const mine = new Set(rec.commits);
946
+ const landed = new Set(rec.pushed ?? []);
947
+ const range = runGit(cwd, ["rev-parse", "-q", "--verify", `${rec.startSha}^{commit}`]).ok
948
+ ? `${rec.startSha}..HEAD`
949
+ : "HEAD";
950
+ const pending = (git(cwd, ["rev-list", "--reverse", range]) ?? "")
951
+ .split("\n")
952
+ .filter((c) => mine.has(c) &&
953
+ !landed.has(c) &&
954
+ !runGit(cwd, ["merge-base", "--is-ancestor", c, UPSTREAM]).ok);
955
+ if (pending.length === 0) {
956
+ log("every commit the run made is already on origin/dev — nothing to push");
957
+ return notPushed(EXIT.OK, { skipped: "no-run-commits" });
958
+ }
959
+ const ahead = (git(cwd, ["rev-list", "--reverse", `${UPSTREAM}..HEAD`]) ?? "")
960
+ .split("\n")
961
+ .filter(Boolean);
962
+ // Plain only when origin/dev is an ancestor of local dev (a fast-forward) and
963
+ // the run's commits are all local dev holds beyond it; the explicit SHA keeps
964
+ // a commit made after the check out of the push.
965
+ const fastForward = runGit(cwd, ["merge-base", "--is-ancestor", UPSTREAM, "HEAD"]).ok;
966
+ if (fastForward && ahead.length === pending.length && ahead.every((c, i) => c === pending[i])) {
967
+ const last = pending[pending.length - 1];
968
+ const args = [
969
+ "push",
970
+ ...(o.setUpstream === true ? ["-u"] : []),
971
+ REMOTE,
972
+ `${last}:refs/heads/${rec.branch}`,
973
+ ];
974
+ const res = runPush(cwd, args, rec.branch);
975
+ if (res.ok) {
976
+ log(`pushed ${rec.branch}: the run's ${pending.length} commit(s) are all local dev holds`);
977
+ return {
978
+ code: EXIT.OK,
979
+ out: {
980
+ pushed: true,
981
+ ref: rec.branch,
982
+ sha: last,
983
+ forced: false,
984
+ skipped: null,
985
+ prNumber: null,
986
+ replayed: false,
987
+ mergedDev: false,
988
+ },
989
+ };
990
+ }
991
+ if (res.lockExit !== null) {
992
+ log(`git ${args.join(" ")} failed: ${res.stderr}`);
993
+ return notPushed(res.lockExit, { lockHolder: res.lockHolder });
994
+ }
995
+ log(`git ${args.join(" ")} failed: ${res.stderr} — replaying onto a fresh ${UPSTREAM}`);
996
+ }
997
+ const root = repoRoot(cwd);
998
+ let res;
999
+ try {
1000
+ res = await pushToDev({
1001
+ root,
1002
+ dir: landDir(root, rec.fid),
1003
+ build: replayBuild(pending),
1004
+ log,
1005
+ });
1006
+ }
1007
+ catch (err) {
1008
+ if (!(err instanceof ReplayConflict))
1009
+ throw err;
1010
+ log(`replaying the run's commits onto ${UPSTREAM} stopped: ${err.message}`);
1011
+ return notPushed(EXIT_MERGE_CONFLICT);
1012
+ }
1013
+ switch (res.kind) {
1014
+ case "landed":
1015
+ markRecordPushed(cwd, rec.fid, pending);
1016
+ log(`pushed ${pending.length} commit(s) of the run to ${DEV} as copies on a fresh ${UPSTREAM} (${res.sha.slice(0, 12)}); local ${DEV} still holds the originals beside other commits — resync with: git pull --rebase ${REMOTE} ${DEV}`);
1017
+ return {
1018
+ code: EXIT.OK,
1019
+ out: {
1020
+ pushed: true,
1021
+ ref: rec.branch,
1022
+ sha: res.sha,
1023
+ forced: false,
1024
+ skipped: null,
1025
+ prNumber: null,
1026
+ replayed: true,
1027
+ mergedDev: false,
1028
+ },
1029
+ };
1030
+ case "refused":
1031
+ log(`${DEV} refused the push: ${res.stderr}`);
1032
+ return notPushed(EXIT_PUSH_FAILED);
1033
+ case "push-failed":
1034
+ log(`push to ${DEV} failed without a server answer: ${res.stderr}`);
1035
+ return notPushed(EXIT_PUSH_FAILED);
1036
+ case "exhausted":
1037
+ log(`${DEV} moved before each of ${res.attempts} pushes`);
1038
+ return notPushed(EXIT_PUSH_FAILED);
1039
+ case "fetch-failed":
1040
+ log(`git fetch ${REMOTE} ${DEV} failed: ${res.stderr}`);
1041
+ return notPushed(EXIT_FETCH_FAILED);
1042
+ case "setup-failed":
1043
+ log(`throwaway checkout failed: ${res.stderr}`);
1044
+ return notPushed(EXIT_PUSH_FAILED);
1045
+ }
1046
+ }
1047
+ async function pushVerb(ctx) {
510
1048
  const mode = String(ctx.flags.mode);
511
- if (!["feature", "abort", "dev"].includes(mode)) {
512
- throw new CommandError(EXIT.USAGE, "--mode must be feature, abort, or dev");
1049
+ if (!["feature", "abort", "dev", "plain"].includes(mode)) {
1050
+ throw new CommandError(EXIT.USAGE, "--mode must be feature, abort, dev, or plain");
1051
+ }
1052
+ const aheadOf = str(ctx.flags.aheadOf);
1053
+ if (aheadOf !== undefined && mode !== "plain") {
1054
+ throw new CommandError(EXIT.USAGE, "--ahead-of applies to --mode=plain only");
1055
+ }
1056
+ const commitMessage = str(ctx.flags.commit);
1057
+ let marker;
1058
+ if (commitMessage !== undefined) {
1059
+ const file = str(ctx.flags.file);
1060
+ const workflow = str(ctx.flags.workflow);
1061
+ if (mode !== "feature" || file === undefined || workflow === undefined) {
1062
+ throw new CommandError(EXIT.USAGE, "--commit needs --mode=feature, --file (status.jsonl) and --workflow");
1063
+ }
1064
+ const branch = currentBranch(ctx.cwd);
1065
+ if (branch === "") {
1066
+ ctx.log("no branch checked out (detached HEAD) — refusing to commit and push");
1067
+ return EXIT_DETACHED;
1068
+ }
1069
+ if (isSharedBranch(branch)) {
1070
+ ctx.log(`Nothing to ship: --commit makes a marker commit on a feature branch, not '${branch}'`);
1071
+ return EXIT_NOTHING_TO_PUSH;
1072
+ }
1073
+ const message = `${commitMessage}${autoRouteSuffix(ctx.flags.label ?? [])}`;
1074
+ if (ctx.flags.requireCi === true && SKIP_CI_TOKEN.test(message)) {
1075
+ ctx.log("the --commit message carries a CI-suppressing token, and this push needs a CI run — refusing");
1076
+ ctx.emit({
1077
+ pushed: false,
1078
+ ref: null,
1079
+ sha: null,
1080
+ forced: false,
1081
+ skipped: "skip-ci",
1082
+ prNumber: null,
1083
+ replayed: false,
1084
+ mergedDev: false,
1085
+ });
1086
+ return EXIT_SKIP_CI;
1087
+ }
1088
+ marker = markerCommit(ctx.cwd, {
1089
+ file: path.resolve(ctx.cwd, file),
1090
+ key: markerKey(path.resolve(ctx.cwd, file), workflow, "push-commit"),
1091
+ message,
1092
+ addAll: true,
1093
+ });
1094
+ if (marker.deduped)
1095
+ ctx.log(`marker commit ${marker.sha.slice(0, 12)} already made this run — pushing it`);
513
1096
  }
514
- const r = pushBranch(ctx.cwd, {
1097
+ const r = await pushBranch(ctx.cwd, {
515
1098
  mode: mode,
516
1099
  setUpstream: ctx.flags.setUpstream === true,
1100
+ aheadOf,
517
1101
  requireCi: ctx.flags.requireCi === true,
518
1102
  openPr: str(ctx.flags.openPr),
1103
+ fid: str(ctx.flags.fid),
519
1104
  }, ctx.log);
520
1105
  // A detached HEAD and a wrong checkout print nothing, as the push never got to run.
521
- if (r.code !== EXIT_DETACHED && r.code !== EXIT_NOT_DEV)
522
- ctx.emit(r.out);
1106
+ if (r.code !== EXIT_DETACHED && r.code !== EXIT_NOT_DEV) {
1107
+ ctx.emit(marker === undefined
1108
+ ? { lockHolder: null, ...r.out }
1109
+ : { lockHolder: null, ...r.out, commit: marker.sha, deduped: marker.deduped });
1110
+ }
523
1111
  return r.code;
524
1112
  }
525
- /** Resolve sync's docs-merge conflicts: ledgers by union, other `docs/` paths take dev's side. */
526
- function resolveDocsMerge(top) {
527
- const conflicts = unmergedPaths(top);
528
- const refused = conflicts.find((f) => classifyConflict(f) !== "ledger" && !f.startsWith("docs/"));
529
- if (refused !== undefined)
530
- return { refused };
531
- const resolved = [];
532
- for (const f of conflicts) {
533
- if (classifyConflict(f) === "ledger") {
534
- if (!unionResolve(top, f).ok || !runGit(top, ["add", "--", f]).ok)
535
- return { refused: f };
536
- resolved.push({ path: f, how: "union" });
1113
+ function fastForwardVerb(ctx) {
1114
+ const onto = String(ctx.flags.onto);
1115
+ const top = topLevel(ctx.cwd);
1116
+ const fetched = fetchRemoteRef(top, onto);
1117
+ if (fetched !== null && !fetched.ok) {
1118
+ ctx.log(`git fetch for ${onto} failed: ${fetched.stderr}`);
1119
+ return EXIT_FETCH_FAILED;
1120
+ }
1121
+ if (!runGit(top, ["rev-parse", "-q", "--verify", `${onto}^{commit}`]).ok) {
1122
+ ctx.log(`unknown ref: ${onto}`);
1123
+ return EXIT_FETCH_FAILED;
1124
+ }
1125
+ const before = git(top, ["rev-parse", "HEAD"]);
1126
+ if (runGit(top, ["merge-base", "--is-ancestor", onto, "HEAD"]).ok) {
1127
+ ctx.emit({ moved: false, head: before });
1128
+ return EXIT.OK;
1129
+ }
1130
+ const merged = runGit(top, ["merge", "--ff-only", onto]);
1131
+ if (!merged.ok) {
1132
+ ctx.log(`local ${currentBranch(top) || "HEAD"} diverged from ${onto} — reconcile, then re-run`);
1133
+ return EXIT_DIVERGED;
1134
+ }
1135
+ const head = git(top, ["rev-parse", "HEAD"]);
1136
+ ctx.log(`fast-forwarded onto ${onto} (${head?.slice(0, 12) ?? ""})`);
1137
+ ctx.emit({ moved: head !== before, head });
1138
+ return EXIT.OK;
1139
+ }
1140
+ /** Paths a source-change check leaves out: plan logs and the append-only ledgers. */
1141
+ const NOT_CODE = [":(exclude)docs/plans", ":(exclude)docs/*.jsonl", ":(exclude).bkit/*.jsonl"];
1142
+ /** A test file's name at any tier: unit, integration, E2E. */
1143
+ const TEST_FILE = /\.(?:test|spec)\.|_test\.|(^|\/)test_[^/]*\.py$/;
1144
+ /** Added-line markers that disable a test: `bkit-slop-type-suppression.mjs`'s set, widened. */
1145
+ const MARKERS = [
1146
+ /\b(?:describe|context|it|test|suite|bench)\.(?:skip|todo|fixme)\b/,
1147
+ /(?<!\.)\bx(?:it|describe|test|context)\s*\(/,
1148
+ /\bxfail\b/,
1149
+ /\bt\.Skip\(/,
1150
+ /#\[ignore\b/,
1151
+ /@Disabled\b/,
1152
+ /@pytest\.mark\.skip\b/,
1153
+ /@unittest\.skip\b/,
1154
+ /\.skip\s*\(/,
1155
+ ];
1156
+ /** The markers that apply to an added line of `file`: only a test file carries them. */
1157
+ const markersFor = (file) => (TEST_FILE.test(file) ? MARKERS : []);
1158
+ /** A quoted span: a marker inside it is prose or a fixture string, not a call. */
1159
+ const QUOTED = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g;
1160
+ /** A line's trailing comment (`#` is one unless it opens a Rust or C attribute). */
1161
+ const COMMENT_TAIL = /(?:^|\s)(?:\/\/|#(?!\[))/;
1162
+ /** A line that opens or continues a block comment. */
1163
+ const BLOCK_COMMENT = /^\s*(?:\/\*|\*)/;
1164
+ /** `line` with its quoted spans and comment removed — the part a marker can be a call in. */
1165
+ function stripProse(line) {
1166
+ if (BLOCK_COMMENT.test(line))
1167
+ return "";
1168
+ const code = line.replace(QUOTED, '""');
1169
+ const cut = code.search(COMMENT_TAIL);
1170
+ return cut === -1 ? code : code.slice(0, cut);
1171
+ }
1172
+ /** An assertion call a change deletes from a test file: `expect(…)`, `assert.equal(…)`, `should(…)`. */
1173
+ const ASSERTION = /(?<![\w$])(?:expect|assert\w*|should_\w+|should)\s*[(.]/;
1174
+ /** Python's bare `assert x` statement, which calls nothing but asserts. */
1175
+ const BARE_ASSERT = /^\s*assert\s+\S/;
1176
+ /** A commented-out line: its words are prose, not a call. */
1177
+ const COMMENT = /^\s*(?:\/\/|\/\*|\*|#|--)/;
1178
+ /** True when a removed `line` takes an assertion, rather than being a comment or an import. */
1179
+ const isAssertion = (line) => !COMMENT.test(line) && (ASSERTION.test(line) || BARE_ASSERT.test(line));
1180
+ /** The test at 1-based `at` in `body`: the nearest declaration above it, else `line` itself. */
1181
+ function testAt(body, line, at) {
1182
+ if (body !== null) {
1183
+ const lines = body.split(/\r?\n/);
1184
+ const from = Math.min(at, lines.length) - 1;
1185
+ // A decorator (`@pytest.mark.skip`) names the test it sits on, which is below it.
1186
+ if (line.trimStart().startsWith("@")) {
1187
+ for (let i = from + 1; i < lines.length; i++) {
1188
+ const name = declaredName(lines[i]);
1189
+ if (name !== null)
1190
+ return name;
1191
+ }
1192
+ }
1193
+ for (let i = from; i >= 0; i--) {
1194
+ const name = declaredName(lines[i]);
1195
+ if (name !== null)
1196
+ return name;
1197
+ }
1198
+ }
1199
+ return line.trim();
1200
+ }
1201
+ const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
1202
+ /**
1203
+ * The text of the regular file `rel` names under `root`, or null when it is missing, a
1204
+ * symlink, or resolves outside `root` — so a diff path never opens a file the repo does not hold.
1205
+ */
1206
+ function inRepoFile(root, rel) {
1207
+ const abs = path.resolve(root, rel);
1208
+ const inside = (base, p) => {
1209
+ const r = path.relative(base, p);
1210
+ return r !== "" && !r.startsWith("..") && !path.isAbsolute(r);
1211
+ };
1212
+ if (!inside(root, abs))
1213
+ return null;
1214
+ const stat = fs.lstatSync(abs, { throwIfNoEntry: false });
1215
+ if (stat === undefined || stat.isSymbolicLink() || !stat.isFile())
1216
+ return null;
1217
+ // A symlinked parent directory can still lead outside the repo.
1218
+ if (!inside(fs.realpathSync(root), fs.realpathSync(abs)))
1219
+ return null;
1220
+ return fs.readFileSync(abs, "utf-8");
1221
+ }
1222
+ /**
1223
+ * Unmatched disabled markers and removed assertion occurrences in a unified diff.
1224
+ * Exact moves consume one added occurrence; cross-file moves require unchanged test context.
1225
+ * Rewritten assertions pair only inside the same file and test. Removed lines retain their
1226
+ * original test name; a deleted file uses old line numbers, otherwise the new hunk position.
1227
+ */
1228
+ export function disabledTestsIn(diff, root) {
1229
+ const out = [];
1230
+ const bodies = new Map();
1231
+ const body = (rel) => {
1232
+ if (!bodies.has(rel))
1233
+ bodies.set(rel, inRepoFile(root, rel));
1234
+ return bodies.get(rel);
1235
+ };
1236
+ const added = [];
1237
+ const removed = [];
1238
+ const addedMarkers = [];
1239
+ const removedMarkers = [];
1240
+ const patches = new Map();
1241
+ let file = "";
1242
+ let from = "";
1243
+ let deleted = false;
1244
+ let current;
1245
+ let next = 0;
1246
+ let old = 0;
1247
+ for (const raw of diff.split("\n")) {
1248
+ if (raw.startsWith("diff --git ")) {
1249
+ current = undefined;
1250
+ file = "";
1251
+ continue;
1252
+ }
1253
+ if (raw.startsWith("--- ")) {
1254
+ from = raw.replace(/^--- (a\/)?/, "");
1255
+ continue;
1256
+ }
1257
+ if (raw.startsWith("+++ ")) {
1258
+ const plus = raw.replace(/^\+\+\+ (b\/)?/, "");
1259
+ file = plus === "/dev/null" ? from : plus;
1260
+ deleted = plus === "/dev/null";
1261
+ continue;
1262
+ }
1263
+ const hunk = HUNK.exec(raw);
1264
+ if (hunk !== null) {
1265
+ old = Number(hunk[1]);
1266
+ next = Number(hunk[3]);
1267
+ current = { start: next, count: Number(hunk[4] ?? 1), lines: [] };
1268
+ const hunks = patches.get(file) ?? [];
1269
+ hunks.push(current);
1270
+ patches.set(file, hunks);
537
1271
  continue;
538
1272
  }
1273
+ if (current === undefined)
1274
+ continue;
1275
+ if (raw.startsWith("+")) {
1276
+ const text = raw.slice(1);
1277
+ if (TEST_FILE.test(file)) {
1278
+ const occurrence = { file, line: next, text, test: testAt(body(file), text, next) };
1279
+ if (markersFor(file).some((m) => m.test(stripProse(text))))
1280
+ addedMarkers.push(occurrence);
1281
+ if (isAssertion(text))
1282
+ added.push(occurrence);
1283
+ }
1284
+ next++;
1285
+ }
1286
+ else if (raw.startsWith("-")) {
1287
+ const text = raw.slice(1);
1288
+ current.lines.push(text);
1289
+ if (TEST_FILE.test(file)) {
1290
+ const occurrence = { file, line: deleted ? old : next, old, text };
1291
+ if (isAssertion(text))
1292
+ removed.push(occurrence);
1293
+ if (markersFor(file).some((m) => m.test(stripProse(text))))
1294
+ removedMarkers.push(occurrence);
1295
+ }
1296
+ old++;
1297
+ }
1298
+ else if (raw.startsWith(" ")) {
1299
+ current.lines.push(raw.slice(1));
1300
+ next++;
1301
+ old++;
1302
+ }
1303
+ }
1304
+ const oldBodies = new Map();
1305
+ const original = (r) => {
1306
+ if (!oldBodies.has(r.file)) {
1307
+ const lines = body(r.file)?.split(/\r?\n/) ?? [];
1308
+ for (const hunk of [...(patches.get(r.file) ?? [])].reverse())
1309
+ lines.splice(Math.max(0, hunk.start - 1), hunk.count, ...hunk.lines);
1310
+ oldBodies.set(r.file, lines.join("\n"));
1311
+ }
1312
+ return { ...r, test: testAt(oldBodies.get(r.file), r.text, r.old) };
1313
+ };
1314
+ const contexts = new Map();
1315
+ const context = (occurrence, before) => {
1316
+ const key = JSON.stringify([before, occurrence.file, occurrence.test]);
1317
+ if (!contexts.has(key)) {
1318
+ const source = before ? oldBodies.get(occurrence.file) : body(occurrence.file);
1319
+ const lines = source == null ? null : testSource(source, occurrence.test);
1320
+ contexts.set(key, lines === null
1321
+ ? null
1322
+ : lines
1323
+ .filter((line) => stripProse(line).trim() !== "" && !isAssertion(stripProse(line)))
1324
+ .map((line) => line
1325
+ .trim()
1326
+ .replace(/\b(it|test|suite|describe|context|bench)\.(?:skip|todo|fixme)\b/g, "$1"))
1327
+ .join("\n"));
1328
+ }
1329
+ return contexts.get(key);
1330
+ };
1331
+ const exact = (a, b) => a.text.trim() === b.text.trim() &&
1332
+ (a.file === b.file ||
1333
+ (a.test === b.test && context(a, true) !== null && context(a, true) === context(b, false)));
1334
+ const consume = (available, occurrence, match = exact) => {
1335
+ const index = available.findIndex((candidate) => match(occurrence, candidate));
1336
+ if (index === -1)
1337
+ return false;
1338
+ available.splice(index, 1);
1339
+ return true;
1340
+ };
1341
+ for (const r of removedMarkers)
1342
+ consume(addedMarkers, original(r), (a, b) => exact(a, b) &&
1343
+ a.test === b.test &&
1344
+ context(a, true) !== null &&
1345
+ context(a, true) === context(b, false));
1346
+ const drops = removed.map(original).filter((r) => !consume(added, r));
1347
+ for (const r of drops)
1348
+ if (!consume(added, r, (a, b) => a.file === b.file && a.test === b.test))
1349
+ out.push({ file: r.file, line: r.line, test: r.test });
1350
+ out.unshift(...addedMarkers.map(({ file, line, test }) => ({ file, line, test })));
1351
+ return out;
1352
+ }
1353
+ function scanDiffVerb(ctx) {
1354
+ const base = String(ctx.flags.base);
1355
+ const pattern = str(ctx.flags.paths);
1356
+ const marker = str(ctx.flags.marker);
1357
+ const code = ctx.flags.code === true;
1358
+ const disabled = ctx.flags.disabledTests === true;
1359
+ if ([pattern !== undefined, marker !== undefined, code, disabled].filter(Boolean).length !== 1) {
1360
+ throw new CommandError(EXIT.USAGE, "give exactly one of --paths, --marker, --code, --disabled-tests");
1361
+ }
1362
+ if (disabled && ctx.flags.expectNone === true)
1363
+ throw new CommandError(EXIT.USAGE, "--disabled-tests inverts the exit already; drop --expect-none");
1364
+ let re;
1365
+ if (pattern !== undefined) {
1366
+ try {
1367
+ re = new RegExp(pattern, "i");
1368
+ }
1369
+ catch (err) {
1370
+ ctx.log(`--paths is not a valid pattern: ${err.message}`);
1371
+ return EXIT.USAGE;
1372
+ }
1373
+ }
1374
+ const top = topLevel(ctx.cwd);
1375
+ const fetched = fetchRemoteRef(top, base);
1376
+ if (fetched !== null && !fetched.ok) {
1377
+ ctx.log(`git fetch for ${base} failed: ${fetched.stderr} — diffing against the local ref`);
1378
+ }
1379
+ if (!runGit(top, ["rev-parse", "-q", "--verify", `${base}^{commit}`]).ok) {
1380
+ ctx.log(`unknown base: ${base}`);
1381
+ return EXIT_DIFF_FAILED;
1382
+ }
1383
+ const range = `${base}...HEAD`;
1384
+ if (disabled) {
1385
+ const diff = quietGit(top, ["diff", "--no-renames", range, "--", ".", ":(exclude)docs/plans"]);
1386
+ if (!diff.ok) {
1387
+ ctx.log(`git diff ${range} failed: ${diff.stderr}`);
1388
+ return EXIT_DIFF_FAILED;
1389
+ }
1390
+ const hits = disabledTestsIn(diff.stdout, top);
1391
+ const files = [...new Set(hits.map((h) => h.file))];
1392
+ ctx.emit({ found: hits.length > 0, paths: files, disabled: hits });
1393
+ if (hits.length > 0)
1394
+ ctx.log(`disabled tests or removed assertions:\n${hits.map((h) => `${h.file}:${h.line} — ${h.test}`).join("\n")}`);
1395
+ return hits.length > 0 ? EXIT.NO : EXIT.OK;
1396
+ }
1397
+ let paths;
1398
+ if (marker !== undefined) {
1399
+ const diff = quietGit(top, ["diff", "--no-renames", range, "--", ".", ":(exclude)docs/plans"]);
1400
+ if (!diff.ok) {
1401
+ ctx.log(`git diff ${range} failed: ${diff.stderr}`);
1402
+ return EXIT_DIFF_FAILED;
1403
+ }
1404
+ const hits = new Set();
1405
+ let file = "";
1406
+ for (const line of diff.stdout.split("\n")) {
1407
+ if (line.startsWith("+++ ")) {
1408
+ file = line.replace(/^\+\+\+ (b\/)?/, "");
1409
+ continue;
1410
+ }
1411
+ if (line.startsWith("+") && line.includes(marker))
1412
+ hits.add(file);
1413
+ }
1414
+ paths = [...hits];
1415
+ }
1416
+ else {
1417
+ const diff = quietGit(top, [
1418
+ "diff",
1419
+ "--name-only",
1420
+ "-z",
1421
+ "--no-renames",
1422
+ range,
1423
+ ...(code ? ["--", ".", ...NOT_CODE] : []),
1424
+ ]);
1425
+ if (!diff.ok) {
1426
+ ctx.log(`git diff ${range} failed: ${diff.stderr}`);
1427
+ return EXIT_DIFF_FAILED;
1428
+ }
1429
+ paths = diff.stdout.split("\0").filter(Boolean);
1430
+ if (re !== undefined)
1431
+ paths = paths.filter((p) => re.test(p));
1432
+ }
1433
+ ctx.emit({ found: paths.length > 0, paths });
1434
+ if (ctx.flags.expectNone === true) {
1435
+ if (paths.length > 0) {
1436
+ ctx.log(marker !== undefined
1437
+ ? `added lines still carry ${marker} in: ${paths.join(", ")}`
1438
+ : `expected no match, found: ${paths.join(", ")}`);
1439
+ }
1440
+ return paths.length > 0 ? EXIT.NO : EXIT.OK;
1441
+ }
1442
+ return paths.length > 0 ? EXIT.OK : EXIT.NO;
1443
+ }
1444
+ async function forceBuildVerb(ctx) {
1445
+ const f = ctx.flags;
1446
+ const fid = String(f.fid);
1447
+ const file = path.resolve(ctx.cwd, String(f.file));
1448
+ const workflow = String(f.workflow);
1449
+ const openPrFlag = str(f.openPr);
1450
+ if (openPrFlag !== undefined && openPrFlag !== "none" && !/^[1-9][0-9]*$/.test(openPrFlag)) {
1451
+ throw new CommandError(EXIT.USAGE, `--open-pr must be a PR number or none, got "${openPrFlag}"`);
1452
+ }
1453
+ const branch = currentBranch(ctx.cwd);
1454
+ if (branch === "") {
1455
+ ctx.log("no branch checked out (detached HEAD) — refusing to force a build");
1456
+ return EXIT_DETACHED;
1457
+ }
1458
+ if (isSharedBranch(branch)) {
1459
+ ctx.log(`Nothing to ship: force-build marks a feature branch, not '${branch}'`);
1460
+ return EXIT_NOTHING_TO_PUSH;
1461
+ }
1462
+ // (1) The PR title: CI reads the marker from it on pull_request events.
1463
+ const viaMcp = (why) => {
1464
+ ctx.log(`${why} — add " bkit ${FORCE_BUILD}" to the open PR's title through update_pull_request (skip when no PR is open), then re-run with --title-set`);
1465
+ return EXIT.USE_MCP;
1466
+ };
1467
+ let prNumber = null;
1468
+ let titleChanged = false;
1469
+ if (f.titleSet !== true && openPrFlag !== "none") {
1470
+ const probe = probePr(ctx.cwd, openPrFlag === undefined
1471
+ ? { head: branch, state: "open" }
1472
+ : { number: openPrFlag, state: "open" });
1473
+ if (probe.kind !== "ok")
1474
+ return viaMcp(probe.message);
1475
+ if (probe.pr) {
1476
+ prNumber = probe.pr.number;
1477
+ if (!probe.pr.title.includes(FORCE_BUILD)) {
1478
+ const next = `${probe.pr.title} bkit ${FORCE_BUILD}`;
1479
+ const edit = runGh(ctx.cwd, ["pr", "edit", String(prNumber), "--title", next]);
1480
+ if (!edit.ok) {
1481
+ return viaMcp(ghUnavailable(edit)
1482
+ ? "gh unavailable for gh pr edit"
1483
+ : `gh pr edit ${prNumber} failed: ${edit.stderr}`);
1484
+ }
1485
+ titleChanged = true;
1486
+ ctx.log(`PR #${prNumber} title now carries ${FORCE_BUILD}`);
1487
+ }
1488
+ }
1489
+ }
1490
+ // (2) The empty marker commit, once per run; its push is the event that starts the run.
1491
+ const message = `chore(${fid}): force build bkit ${FORCE_BUILD}${autoRouteSuffix(f.label ?? [])}`;
1492
+ const marker = markerCommit(ctx.cwd, {
1493
+ file,
1494
+ key: markerKey(file, workflow, "force-build"),
1495
+ message,
1496
+ addAll: false,
1497
+ });
1498
+ if (marker.deduped)
1499
+ ctx.log(`force-build commit ${marker.sha.slice(0, 12)} already made this run — pushing it`);
1500
+ const pushed = await pushBranch(ctx.cwd, { mode: "feature", requireCi: true }, ctx.log);
1501
+ ctx.emit({
1502
+ prNumber,
1503
+ titleChanged,
1504
+ commit: marker.sha,
1505
+ deduped: marker.deduped,
1506
+ pushed: pushed.out.pushed,
1507
+ ref: pushed.out.ref,
1508
+ sha: pushed.out.sha,
1509
+ });
1510
+ return pushed.code;
1511
+ }
1512
+ /** The paths a feature branch must hold dev's commits for before GitHub reads it: docs/ and every ledger. */
1513
+ const DEV_DOC_PATHSPECS = ["docs/", ...LEDGERS.map((l) => `:(glob)${l}`)];
1514
+ /** Commits on origin/dev not in `head` that touch docs/ or a ledger. */
1515
+ function docsBehindOf(top, head) {
1516
+ return Number(git(top, ["rev-list", "--count", `${head}..${UPSTREAM}`, "--", ...DEV_DOC_PATHSPECS]) ?? "0");
1517
+ }
1518
+ /**
1519
+ * The `docs` merge: bring dev's docs/ and ledger commits onto the feature branch
1520
+ * when it is behind them, so GitHub, which ignores `merge=union`, reads no ledger
1521
+ * conflict and CI runs. Nothing on a shared branch or when docs/ is current.
1522
+ */
1523
+ function mergeDevDocs(top, o, log) {
1524
+ const docsBehind = docsBehindOf(top, "HEAD");
1525
+ const current = isSharedBranch(o.branch) || docsBehind === 0;
1526
+ if (!current)
1527
+ log(`docs/ and the ledgers are ${docsBehind} commit(s) behind ${UPSTREAM} — merging it in`);
1528
+ const merged = mergeDev(top, { branch: o.branch, policy: "docs", generate: o.generate, current }, log);
1529
+ return { ...merged, docsBehind };
1530
+ }
1531
+ /**
1532
+ * Run the consumer's `bkit:generate` (`.bkit/workflows.md` § Local gate scripts)
1533
+ * and commit what it changed (`commitWhatChanged`). null when the script is undeclared.
1534
+ */
1535
+ function regenerate(top, branch, log, o = {}) {
1536
+ if (!generateDeclared(top))
1537
+ return null;
1538
+ const fid = o.fid ?? branch.replace(/^feat\//, "");
1539
+ const message = `chore(${fid}): regenerate after merging ${DEV}`;
1540
+ const done = commitWhatChanged(top, "bkit:generate", () => runGenerate(top, log, "after the merge"), message, log);
1541
+ if (done.outcome === "committed")
1542
+ log(`committed bkit:generate's output after merging ${UPSTREAM}`);
1543
+ return done.outcome !== "failed";
1544
+ }
1545
+ /** Whether `top`'s package.json declares a non-empty `bkit:generate` script. */
1546
+ function generateDeclared(top) {
1547
+ const pkg = readPackageJson(top);
1548
+ const scripts = pkg.ok ? pkg.pkg.scripts : undefined;
1549
+ return (typeof scripts === "object" &&
1550
+ scripts !== null &&
1551
+ typeof scripts["bkit:generate"] === "string" &&
1552
+ scripts["bkit:generate"] !== "");
1553
+ }
1554
+ /** Run `bkit:generate` in `top`; false when it failed, logged with its output's last lines. */
1555
+ function runGenerate(top, log, when) {
1556
+ return runLogged(top, scriptCommand("bkit:generate"), log, when);
1557
+ }
1558
+ /** Run `argv` in `top`; false when it failed, logged with its output's last lines. */
1559
+ function runLogged(top, argv, log, when) {
1560
+ const res = spawnSync(argv[0], argv.slice(1), {
1561
+ cwd: top,
1562
+ encoding: "utf-8",
1563
+ stdio: ["ignore", "pipe", "pipe"],
1564
+ maxBuffer: 1 << 26,
1565
+ });
1566
+ if (res.status === 0)
1567
+ return true;
1568
+ log(`${argv.join(" ")} exited ${String(res.status ?? res.error?.message)} ${when}`);
1569
+ const out = `${res.stdout ?? ""}${res.stderr ?? ""}`.trim();
1570
+ if (out !== "")
1571
+ for (const line of out.split("\n").slice(-20))
1572
+ log(` ${line}`);
1573
+ return false;
1574
+ }
1575
+ /**
1576
+ * Each changed path in `top` (the entries worktree setup copies in left out), with a hash
1577
+ * of its content ("" when deleted); null when git could not run. Read raw: `--porcelain`
1578
+ * lines start with a status column that may be a space.
1579
+ */
1580
+ function changedPaths(top) {
1581
+ const res = spawnSync("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--", ".", ...copyExcludes(top)], { cwd: top, env: gitEnv(), encoding: "utf-8", maxBuffer: OUTPUT_LIMIT });
1582
+ if (res.error || res.status !== 0)
1583
+ return null;
1584
+ const out = new Map();
1585
+ const entries = res.stdout.split("\0");
1586
+ for (let i = 0; i < entries.length; i++) {
1587
+ const entry = entries[i];
1588
+ if (entry.length < 4)
1589
+ continue;
1590
+ const file = entry.slice(3);
1591
+ // A staged rename or copy carries its source as the next entry.
1592
+ if (entry[0] === "R" || entry[0] === "C")
1593
+ i++;
1594
+ const abs = path.join(top, file);
1595
+ out.set(file, fs.existsSync(abs) && fs.statSync(abs).isFile()
1596
+ ? createHash("sha256").update(fs.readFileSync(abs)).digest("hex")
1597
+ : "");
1598
+ }
1599
+ return out;
1600
+ }
1601
+ /**
1602
+ * What a generator changed between two `changedPaths` reads: `rewritten` were already
1603
+ * changed and changed again, so they cannot be told apart from work that is not
1604
+ * generated; `added` are the paths only the generator changed, sorted.
1605
+ */
1606
+ function changedSince(dirty, after) {
1607
+ return {
1608
+ rewritten: [...after].filter(([f, h]) => dirty.has(f) && dirty.get(f) !== h).map(([f]) => f),
1609
+ added: [...after.keys()].filter((f) => !dirty.has(f)).sort(),
1610
+ };
1611
+ }
1612
+ /** Commit exactly `paths`, deletions included; false when the add or the commit failed. */
1613
+ function commitPaths(top, paths, message) {
1614
+ return (runGit(top, ["add", "-A", "--", ...paths]).ok &&
1615
+ quietGit(top, ["commit", "-q", "-m", message, "--", ...paths]).ok);
1616
+ }
1617
+ /**
1618
+ * Run a generator (`run`, named `what` in the log) in `top` and commit exactly the paths
1619
+ * it changed as `message`, so uncommitted work already in the tree stays out of the
1620
+ * commit. `failed` (logged) when `git status` or the commit failed, `run` failed, or it
1621
+ * changed a path that already held uncommitted changes again: that cannot be told apart
1622
+ * from work that is not generated. `unchanged` when it changed nothing.
1623
+ */
1624
+ function commitWhatChanged(top, what, run, message, log) {
1625
+ const failed = { outcome: "failed", paths: [] };
1626
+ const dirty = changedPaths(top);
1627
+ if (dirty === null) {
1628
+ log(`git status failed — ${what} not run`);
1629
+ return failed;
1630
+ }
1631
+ if (!run())
1632
+ return failed;
1633
+ const after = changedPaths(top);
1634
+ if (after === null) {
1635
+ log(`git status failed after ${what}`);
1636
+ return failed;
1637
+ }
1638
+ const { rewritten, added } = changedSince(dirty, after);
1639
+ if (rewritten.length > 0) {
1640
+ for (const f of rewritten)
1641
+ log(` ${f}`);
1642
+ log(`${what} changed paths that already held uncommitted changes — nothing committed`);
1643
+ return failed;
1644
+ }
1645
+ if (added.length === 0)
1646
+ return { outcome: "unchanged", paths: [] };
1647
+ if (!commitPaths(top, added, message)) {
1648
+ log(`committing the output of ${what} failed`);
1649
+ return failed;
1650
+ }
1651
+ return { outcome: "committed", paths: added };
1652
+ }
1653
+ /**
1654
+ * Rebuild each register a conflict settled on dev's copy (`REGISTERS`), or whose
1655
+ * generated block a conflicted doc took from dev, and commit only the paths the rebuild
1656
+ * changed. null when none was settled, or no settled register's script exists in the
1657
+ * repo; false when a rebuild failed, or changed a path that already held uncommitted
1658
+ * changes. A register not rebuilt keeps dev's copy: the pre-push gate, CI and ship's
1659
+ * `bkit:generate` still judge it.
1660
+ */
1661
+ function rebuildRegisters(top, resolved, commitMessage, log) {
1662
+ const embeds = embedDocs(top);
1663
+ const settled = [
1664
+ ...new Set(resolved.flatMap((r) => {
1665
+ const register = r.how === "register" ? r.path : r.how === "embed" ? embeds.get(r.path) : undefined;
1666
+ return register === undefined ? [] : [register];
1667
+ })),
1668
+ ];
1669
+ const due = settled.filter((f) => fs.existsSync(path.join(top, REGISTERS[f].script)));
1670
+ for (const f of settled)
1671
+ if (!due.includes(f))
1672
+ log(`NOT REBUILT ${f} — ${REGISTERS[f].script} is absent`);
1673
+ if (due.length === 0)
1674
+ return null;
1675
+ const which = due.join(", ");
1676
+ const rebuild = () => due.every((f) => {
1677
+ const { script, args } = REGISTERS[f];
1678
+ if (runLogged(top, ["bash", script, ...args], log, `rebuilding ${f}`))
1679
+ return true;
1680
+ log(`NOT REBUILT ${f} — it keeps ${DEV}'s copy`);
1681
+ return false;
1682
+ });
1683
+ const done = commitWhatChanged(top, `the rebuild of ${which}`, rebuild, commitMessage(due), log);
1684
+ if (done.outcome === "failed")
1685
+ return false;
1686
+ log(done.outcome === "unchanged"
1687
+ ? `REBUILT ${which} — ${DEV}'s copy was already current`
1688
+ : `REBUILT ${which} — committed as ${git(top, ["rev-parse", "HEAD"])}`);
1689
+ return true;
1690
+ }
1691
+ /**
1692
+ * Ship's regenerate (`.bkit/workflows.md` § `/bkit-ship`): run a declared `bkit:generate`
1693
+ * on the checked-out feature branch and commit only the paths it changed
1694
+ * (`commitWhatChanged`), so the run's own uncommitted bookkeeping (status.jsonl) stays out
1695
+ * of the commit. Step 10 runs it when every failed CI step is one it fixes (`--attempt`).
1696
+ */
1697
+ function regenerateVerb(ctx) {
1698
+ const top = topLevel(ctx.cwd);
1699
+ const branch = currentBranch(top);
1700
+ if (branch === "") {
1701
+ ctx.log("no branch checked out (detached HEAD) — cannot regenerate");
1702
+ return EXIT_DETACHED;
1703
+ }
1704
+ if (isSharedBranch(branch))
1705
+ throw new CommandError(EXIT.USAGE, `regenerate runs on a feature branch, never on ${branch}`);
1706
+ const attempt = str(ctx.flags.attempt);
1707
+ if (attempt !== undefined && !/^[1-9]\d*$/.test(attempt))
1708
+ throw new CommandError(EXIT.USAGE, "--attempt must be a whole number >= 1");
1709
+ const fid = str(ctx.flags.fid) || branch.replace(/^feat\//, "");
1710
+ const before = git(top, ["rev-parse", "HEAD"]);
1711
+ const out = { outcome: "undeclared", head: before, paths: [] };
1712
+ if (!generateDeclared(top)) {
1713
+ ctx.log("bkit:generate is not declared — nothing regenerated");
1714
+ ctx.emit(out);
1715
+ return EXIT.OK;
1716
+ }
1717
+ const message = attempt === undefined
1718
+ ? `chore(${fid}): regenerate before re-validating`
1719
+ : `fix(${fid}): regenerate attempt ${attempt}`;
1720
+ const done = commitWhatChanged(top, "bkit:generate", () => runGenerate(top, ctx.log, "on the branch"), message, ctx.log);
1721
+ if (done.outcome === "failed")
1722
+ return EXIT_GENERATE_FAILED;
1723
+ out.paths = done.paths;
1724
+ if (done.outcome === "unchanged") {
1725
+ out.outcome = "unchanged";
1726
+ ctx.log("bkit:generate changed nothing");
1727
+ ctx.emit(out);
1728
+ return EXIT.OK;
1729
+ }
1730
+ out.outcome = "committed";
1731
+ out.head = git(top, ["rev-parse", "HEAD"]);
1732
+ for (const f of out.paths)
1733
+ ctx.log(`regenerated ${f}`);
1734
+ ctx.log(`committed bkit:generate's output as ${out.head}`);
1735
+ const statusFile = str(ctx.flags.file);
1736
+ if (statusFile !== undefined && before !== null && out.head !== null) {
1737
+ recordAction(path.resolve(ctx.cwd, statusFile), {
1738
+ action: "regenerate",
1739
+ key: actionKey("regenerate", before),
1740
+ hash: actionHash(`${before}..${out.head}`),
1741
+ ref: out.head,
1742
+ });
1743
+ }
1744
+ ctx.emit(out);
1745
+ return EXIT.OK;
1746
+ }
1747
+ /** Whether a merge is in progress in `top` (its MERGE_HEAD exists). */
1748
+ function mergeInProgress(top) {
1749
+ const p = git(top, ["rev-parse", "--path-format=absolute", "--git-path", "MERGE_HEAD"]);
1750
+ return p !== null && fs.existsSync(p);
1751
+ }
1752
+ /** Settle one conflicted path under `policy`, staging it when it is resolved. */
1753
+ function resolvePath(top, file, policy, embeds) {
1754
+ const kind = classifyConflict(file, embeds);
1755
+ if (kind === "ledger") {
1756
+ const union = unionResolve(top, file);
1757
+ if (!union.ok)
1758
+ return { refused: union.problem };
1759
+ return runGit(top, ["add", "--", file]).ok ? "union" : { refused: "git add failed" };
1760
+ }
1761
+ if (kind === "register") {
1762
+ const settled = registerResolve(top, file, "theirs");
1763
+ if (!settled.ok)
1764
+ return { refused: settled.problem };
1765
+ return runGit(top, ["add", "--", file]).ok ? "register" : { refused: "git add failed" };
1766
+ }
1767
+ if (kind === "embed") {
1768
+ const settled = embedResolve(top, file, embeds.get(file), "theirs");
1769
+ if (!settled.ok)
1770
+ return { refused: settled.problem };
1771
+ return runGit(top, ["add", "--", file]).ok ? "embed" : { refused: "git add failed" };
1772
+ }
1773
+ if (kind === "record") {
1774
+ const settled = recordResolve(top, "theirs");
1775
+ if (!settled.ok)
1776
+ return { refused: settled.problem };
1777
+ return runGit(top, ["add", "--", file]).ok ? "record" : { refused: "git add failed" };
1778
+ }
1779
+ if (policy === "docs") {
1780
+ if (!file.startsWith("docs/"))
1781
+ return { refused: "outside docs/ and the ledgers" };
539
1782
  // In a merge `--theirs` is the branch merged in: dev. Dev deleting the file
540
1783
  // leaves no stage 3, and taking dev's side means deleting it here too.
541
- const devHasIt = runGit(top, ["cat-file", "-e", `:3:${f}`]).ok;
1784
+ const devHasIt = runGit(top, ["cat-file", "-e", `:3:${file}`]).ok;
542
1785
  const ok = devHasIt
543
- ? runGit(top, ["checkout", "--theirs", "--", f]).ok && runGit(top, ["add", "--", f]).ok
544
- : runGit(top, ["rm", "-q", "--", f]).ok;
545
- if (!ok)
546
- return { refused: f };
547
- resolved.push({ path: f, how: "dev" });
1786
+ ? runGit(top, ["checkout", "--theirs", "--", file]).ok && runGit(top, ["add", "--", file]).ok
1787
+ : runGit(top, ["rm", "-q", "--", file]).ok;
1788
+ return ok ? "dev" : { refused: `taking ${DEV}'s side failed` };
1789
+ }
1790
+ if (kind === "lockfile") {
1791
+ if (!lockfileResolve(top, file, "theirs"))
1792
+ return { refused: "lockfile regenerate failed" };
1793
+ return runGit(top, ["add", "--", file]).ok ? "lockfile" : { refused: "git add failed" };
1794
+ }
1795
+ return "pending";
1796
+ }
1797
+ const RESOLVED_HOW = {
1798
+ union: "union (append-only ledger)",
1799
+ dev: `took ${DEV}`,
1800
+ lockfile: `lockfile regenerated from ${DEV}'s copy`,
1801
+ register: `took ${DEV}'s copy of a generated register`,
1802
+ embed: `took ${DEV}'s copy of the generated block, merged the rest`,
1803
+ record: `merged the install record entry by entry, ${DEV}'s value where both changed`,
1804
+ };
1805
+ /**
1806
+ * Merge origin/dev (already fetched) into the checked-out feature branch under
1807
+ * `policy`. A merge in progress at the start is continued: its remaining conflicts
1808
+ * are settled and it is committed, which is how a `full` hand resolution finishes
1809
+ * (`git add`, then run again). `full` also commits the tree's uncommitted work first
1810
+ * (ship's open status.jsonl). No commit carries a skip token: the merge brings dev's
1811
+ * code, and the pre-push hook refuses a skip-token head that carries code while the
1812
+ * PR is open. Never a rebase: GitHub ignores `merge=union`, so a
1813
+ * branch rebased onto dev still shows as conflicting on every ledger both sides
1814
+ * appended to, while the merge commit is what GitHub's own merge would compute.
1815
+ */
1816
+ function mergeDev(top, o, log) {
1817
+ const out = {
1818
+ code: EXIT.OK,
1819
+ outcome: "merged",
1820
+ merged: false,
1821
+ carried: null,
1822
+ resolved: [],
1823
+ pending: [],
1824
+ aborted: false,
1825
+ generated: null,
1826
+ rebuilt: null,
1827
+ before: null,
1828
+ };
1829
+ const full = o.policy === "full";
1830
+ const fid = o.fid ?? o.branch.replace(/^feat\//, "");
1831
+ const refuse = (why) => {
1832
+ const abort = runGit(top, ["merge", "--abort"]);
1833
+ out.aborted = abort.ok;
1834
+ log(abort.ok ? `${why} — merge aborted` : `${why} — git merge --abort failed: ${abort.stderr}`);
1835
+ return { ...out, code: EXIT_MERGE_CONFLICT, outcome: "refused" };
1836
+ };
1837
+ if (mergeInProgress(top)) {
1838
+ out.before = git(top, ["rev-parse", "--verify", "--quiet", "ORIG_HEAD"]);
1839
+ log(`a merge of ${UPSTREAM} is in progress — continuing it`);
1840
+ }
1841
+ else {
1842
+ if (o.current)
1843
+ return { ...out, outcome: "current" };
1844
+ if (full && hasLeftovers(top)) {
1845
+ const message = `chore(${fid}): carry uncommitted work before merging ${DEV}`;
1846
+ if (!addAllButCopied(top).ok || !quietGit(top, ["commit", "-q", "-m", message]).ok) {
1847
+ log("the uncommitted work could not be committed before the merge");
1848
+ return { ...out, code: EXIT_REFUSED, outcome: "refused" };
1849
+ }
1850
+ out.carried = git(top, ["rev-parse", "HEAD"]);
1851
+ log(`committed the uncommitted work as ${out.carried} before merging ${UPSTREAM}`);
1852
+ }
1853
+ out.before = git(top, ["rev-parse", "HEAD"]);
1854
+ const message = `chore(${fid}): merge ${DEV}`;
1855
+ const merge = quietGit(top, ["merge", "--no-edit", "-m", message, UPSTREAM]);
1856
+ if (!merge.ok && !mergeInProgress(top)) {
1857
+ // Not a conflict: git refused to start the merge at all.
1858
+ log(`git merge ${UPSTREAM} failed: ${merge.stderr.trim()}`);
1859
+ return { ...out, code: EXIT_MERGE_CONFLICT, outcome: "refused" };
1860
+ }
1861
+ }
1862
+ if (mergeInProgress(top)) {
1863
+ const embeds = embedDocs(top);
1864
+ for (const f of unmergedPaths(top)) {
1865
+ const r = resolvePath(top, f, o.policy, embeds);
1866
+ if (typeof r === "object")
1867
+ return refuse(`${f}: ${r.refused}`);
1868
+ if (r === "pending") {
1869
+ out.pending.push(f);
1870
+ continue;
1871
+ }
1872
+ out.resolved.push({ path: f, how: r });
1873
+ log(`RESOLVED ${f} — ${RESOLVED_HOW[r]}`);
1874
+ }
1875
+ if (out.pending.length > 0) {
1876
+ for (const p of out.pending)
1877
+ log(`PENDING ${p} — needs a hand resolution; run again after git add`);
1878
+ return { ...out, code: EXIT_HAND_RESOLVE, outcome: "pending" };
1879
+ }
1880
+ if (!quietGit(top, ["commit", "--no-edit"]).ok)
1881
+ return refuse("the merge could not be committed");
548
1882
  }
549
- return { resolved };
1883
+ out.merged = true;
1884
+ log(`merged ${UPSTREAM} into ${o.branch} as ${git(top, ["rev-parse", "HEAD"])}`);
1885
+ if (o.generate) {
1886
+ out.rebuilt = rebuildRegisters(top, out.resolved, (files) => `chore(${fid}): rebuild ${files.join(" ")} after merging ${DEV}`, log);
1887
+ out.generated = regenerate(top, o.branch, log, { fid });
1888
+ if (out.generated === false)
1889
+ out.code = EXIT_GENERATE_FAILED;
1890
+ }
1891
+ return out;
1892
+ }
1893
+ /**
1894
+ * An engine-action row for a merge of origin/dev that moved the branch, keyed on
1895
+ * the tip it started from, so the run's record shows the integration. Nothing when
1896
+ * HEAD did not move.
1897
+ */
1898
+ function recordMerge(statusFile, before, after) {
1899
+ if (before === null || after === null || before === after)
1900
+ return;
1901
+ recordAction(statusFile, {
1902
+ action: "merge",
1903
+ key: actionKey("merge", before),
1904
+ hash: actionHash(`${before}..${after}`),
1905
+ ref: after,
1906
+ });
550
1907
  }
551
1908
  function syncVerb(ctx) {
552
1909
  const mergeDocs = ctx.flags.mergeDocs === true;
1910
+ const merge = ctx.flags.merge === true;
553
1911
  const headFlag = str(ctx.flags.head);
554
- if (mergeDocs && headFlag !== undefined) {
555
- throw new CommandError(EXIT.USAGE, "--merge-docs merges into HEAD; give --head or --merge-docs, not both");
1912
+ if ((mergeDocs || merge) && headFlag !== undefined) {
1913
+ throw new CommandError(EXIT.USAGE, "--merge and --merge-docs merge into HEAD; give --head or one of them, not both");
556
1914
  }
1915
+ if (mergeDocs && merge)
1916
+ throw new CommandError(EXIT.USAGE, "give --merge or --merge-docs, not both");
1917
+ const sentinel = str(ctx.flags.sentinel);
1918
+ const sentinelPath = sentinel === undefined ? undefined : path.resolve(ctx.cwd, sentinel);
1919
+ if (merge && sentinelPath)
1920
+ fs.rmSync(sentinelPath, { force: true });
557
1921
  const top = topLevel(ctx.cwd);
558
- const fetch = runGit(top, ["fetch", REMOTE, DEV]);
1922
+ const fetch = fetchDev(top);
559
1923
  if (!fetch.ok) {
560
1924
  ctx.log(`git fetch ${REMOTE} ${DEV} failed: ${fetch.stderr}`);
561
1925
  return EXIT_FETCH_FAILED;
@@ -573,7 +1937,7 @@ function syncVerb(ctx) {
573
1937
  }
574
1938
  const count = (args) => Number(git(top, ["rev-list", "--count", ...args]) ?? "0");
575
1939
  const behind = count([`${head}..${UPSTREAM}`]);
576
- const docsBehind = count([`${head}..${UPSTREAM}`, "--", "docs/"]);
1940
+ const docsBehind = docsBehindOf(top, head);
577
1941
  const out = {
578
1942
  branch: branch === "" ? null : branch,
579
1943
  head,
@@ -582,33 +1946,59 @@ function syncVerb(ctx) {
582
1946
  docsBehind,
583
1947
  merged: false,
584
1948
  resolved: [],
1949
+ generated: null,
1950
+ rebuilt: null,
585
1951
  };
586
1952
  if (mergeDocs) {
587
1953
  if (branch === "") {
588
1954
  ctx.log("no branch checked out (detached HEAD) — cannot merge dev's docs");
589
1955
  return EXIT_DETACHED;
590
1956
  }
591
- if (!isSharedBranch(branch) && docsBehind > 0) {
592
- ctx.log(`docs/ is ${docsBehind} commit(s) behind ${UPSTREAM} — merging it in`);
593
- if (!quietGit(top, ["merge", "--no-edit", UPSTREAM]).ok) {
594
- const outcome = resolveDocsMerge(top);
595
- if ("refused" in outcome) {
596
- runGit(top, ["merge", "--abort"]);
597
- ctx.log(`merge of ${UPSTREAM} conflicts on ${outcome.refused} — outside docs/, merge aborted`);
598
- return EXIT_MERGE_CONFLICT;
599
- }
600
- if (unmergedPaths(top).length > 0 || !quietGit(top, ["commit", "--no-edit"]).ok) {
601
- runGit(top, ["merge", "--abort"]);
602
- ctx.log(`merge of ${UPSTREAM} could not be committed — merge aborted`);
603
- return EXIT_MERGE_CONFLICT;
604
- }
605
- out.resolved = outcome.resolved;
606
- for (const r of outcome.resolved)
607
- ctx.log(`RESOLVED ${r.path} — ${r.how === "union" ? "union (append-only ledger)" : `took ${DEV}`}`);
608
- }
609
- out.merged = true;
1957
+ const m = mergeDevDocs(top, { branch, generate: true }, ctx.log);
1958
+ if (m.code === EXIT_MERGE_CONFLICT)
1959
+ return m.code;
1960
+ out.merged = m.merged;
1961
+ out.resolved = m.resolved;
1962
+ out.generated = m.generated;
1963
+ out.rebuilt = m.rebuilt;
1964
+ if (m.merged)
610
1965
  out.head = git(top, ["rev-parse", "HEAD"]) ?? head;
1966
+ ctx.emit(out);
1967
+ return m.code;
1968
+ }
1969
+ if (merge) {
1970
+ if (branch === "") {
1971
+ ctx.log(`no branch checked out (detached HEAD) — cannot merge ${UPSTREAM}`);
1972
+ return EXIT_DETACHED;
1973
+ }
1974
+ if (isSharedBranch(branch)) {
1975
+ throw new CommandError(EXIT.USAGE, `--merge merges ${UPSTREAM} into a feature branch, never into ${branch}`);
611
1976
  }
1977
+ const fid = str(ctx.flags.fid) || branch.replace(/^feat\//, "");
1978
+ const m = mergeDev(top, { branch, policy: "full", fid, generate: true, current: out.basePath === "A" }, ctx.log);
1979
+ const refused = m.outcome === "refused";
1980
+ if (refused && sentinelPath) {
1981
+ fs.mkdirSync(path.dirname(sentinelPath), { recursive: true });
1982
+ fs.writeFileSync(sentinelPath, "");
1983
+ }
1984
+ const newHead = git(top, ["rev-parse", "HEAD"]) ?? head;
1985
+ ctx.emit({
1986
+ ...out,
1987
+ head: newHead,
1988
+ merged: m.merged,
1989
+ resolved: m.resolved,
1990
+ generated: m.generated,
1991
+ rebuilt: m.rebuilt,
1992
+ outcome: m.outcome,
1993
+ carried: m.carried,
1994
+ pending: m.pending,
1995
+ aborted: m.aborted,
1996
+ sentinel: refused && sentinel !== undefined ? sentinel : null,
1997
+ });
1998
+ const statusFile = str(ctx.flags.file);
1999
+ if (m.merged && statusFile !== undefined)
2000
+ recordMerge(path.resolve(ctx.cwd, statusFile), m.before, newHead);
2001
+ return m.code;
612
2002
  }
613
2003
  ctx.emit(out);
614
2004
  return EXIT.OK;
@@ -620,12 +2010,7 @@ function syncVerb(ctx) {
620
2010
  */
621
2011
  function syncDevVerb(ctx) {
622
2012
  const root = repoRoot(ctx.cwd);
623
- // `bkit install` can leave core.bare=true on the main checkout, which breaks `merge --ff-only` there.
624
- if (git(root, ["config", "--get", "core.bare"]) === "true" &&
625
- fs.statSync(path.join(root, ".git"), { throwIfNoEntry: false })?.isDirectory()) {
626
- runGit(root, ["config", "core.bare", "false"]);
627
- }
628
- const fetch = runGit(root, ["fetch", REMOTE, DEV]);
2013
+ const fetch = fetchDev(root);
629
2014
  if (!fetch.ok) {
630
2015
  ctx.log(`git fetch ${REMOTE} ${DEV} failed: ${fetch.stderr}`);
631
2016
  return EXIT_FETCH_FAILED;
@@ -655,11 +2040,9 @@ function install(ctx, root) {
655
2040
  // ---------------------------------------------------------------------------
656
2041
  /** What a design / plan close may bring to dev: docs and ledgers, nothing else. */
657
2042
  const CLOSE_DOCS = /^docs\/plans\/|^docs\/roadmap\.md$|^docs\/[^/]+\.jsonl$|^\.bkit\/[^/]+\.jsonl$/;
658
- /** The canonical docs `ref` carries for the feature: design, or plan plus sub-plans. */
2043
+ /** The canonical doc `ref` carries for the feature: `{fid}-design.md` or `{fid}-plan.md`. */
659
2044
  function canonicalDocs(root, ref, workflow, month, fid) {
660
- const re = workflow === "plan"
661
- ? new RegExp(`^docs/plans/${month}/${fid}-plan(-[0-9]+)?\\.md$`)
662
- : new RegExp(`^docs/plans/${month}/${fid}-design\\.md$`);
2045
+ const re = new RegExp(`^docs/plans/${month}/${fid}-${workflow}\\.md$`);
663
2046
  return (git(root, ["ls-tree", "-r", "--name-only", ref, "--", `docs/plans/${month}/`]) ?? "")
664
2047
  .split("\n")
665
2048
  .filter((f) => re.test(f));
@@ -734,8 +2117,10 @@ function buildClose(ctx, dir, o) {
734
2117
  const staged = (git(dir, ["diff", "--cached", "--name-only"]) ?? "")
735
2118
  .split("\n")
736
2119
  .filter((p) => p !== "" && !CLOSE_DOCS.test(p));
737
- if (staged.length)
738
- throw new Stop(EXIT_LAND_STOPPED, `${o.workflow} close staged non-doc files:\n${staged.join("\n")}`);
2120
+ if (staged.length) {
2121
+ const inherited = localDevCopies(dir, staged, (p) => `:${p}`);
2122
+ throw new Stop(EXIT_LAND_STOPPED, `${o.workflow} close staged non-doc files:\n${staged.join("\n")}${unpushedDevCause(dir, inherited.length, staged.length, ", then re-run the close.")}`);
2123
+ }
739
2124
  const docs = canonicalDocs(dir, o.branch, o.workflow, o.month, o.fid);
740
2125
  const main = `docs/plans/${o.month}/${o.fid}-${o.workflow}.md`;
741
2126
  if (!docs.includes(main))
@@ -796,11 +2181,32 @@ function branchTree(root, branch) {
796
2181
  }
797
2182
  return null;
798
2183
  }
2184
+ /**
2185
+ * A land retry: merge origin/dev's docs and ledger commits into the PR branch in
2186
+ * the checkout holding it and push, so the PR carries dev's ledger rows. GitHub's
2187
+ * own branch update ignores `merge=union` and fails on the same conflict each time.
2188
+ */
2189
+ async function mergeDevIntoPrBranch(root, branch, log) {
2190
+ const tree = branchTree(root, branch);
2191
+ if (tree === null)
2192
+ throw new Stop(EXIT_LAND_STOPPED, `no checkout has ${branch} checked out — cannot merge ${DEV} into the PR branch; the PR stays open`);
2193
+ if (!fetchDev(tree).ok)
2194
+ throw new Stop(EXIT_LAND_STOPPED, `fetch of ${UPSTREAM} failed — the PR stays open`);
2195
+ const m = mergeDevDocs(tree, { branch, generate: false }, log);
2196
+ if (m.code !== EXIT.OK)
2197
+ throw new Stop(EXIT_LAND_STOPPED, `merging ${UPSTREAM} into ${branch} stopped on a conflict outside docs/ and the ledgers — the PR stays open`);
2198
+ if (!m.merged)
2199
+ return;
2200
+ const pushed = await pushBranch(tree, { mode: "feature" }, log);
2201
+ if (pushed.code !== EXIT.OK)
2202
+ throw new Stop(EXIT_PUSH_FAILED, `push of ${branch} after merging ${DEV} failed`);
2203
+ log(`merged ${UPSTREAM} into ${branch} and pushed it`);
2204
+ }
799
2205
  /**
800
2206
  * The PR close (the dev push was refused): commit the roadmap row on the branch
801
2207
  * in the checkout holding it, push it, open or reuse the PR, squash-merge it with
802
- * an empty body. A merge that does not land on an open PR → update its branch
803
- * from dev and try again, with backoff, LAND_ATTEMPTS tries in all; then stop with
2208
+ * an empty body. A merge that does not land on an open PR → merge dev into its
2209
+ * branch locally, push, and try again, with backoff, LAND_ATTEMPTS tries in all; then stop with
804
2210
  * the PR left open. gh missing → EXIT.USE_MCP with what to create / merge; re-run
805
2211
  * with `--pr` (and `--merged-sha` once merged).
806
2212
  */
@@ -810,7 +2216,12 @@ async function landPr(ctx, root, o) {
810
2216
  const tree = branchTree(root, o.branch);
811
2217
  if (tree === null)
812
2218
  throw new Stop(EXIT_LAND_STOPPED, `no checkout has ${o.branch} checked out — the PR close commits the roadmap row on it; nothing landed`);
813
- runGit(tree, ["fetch", REMOTE, DEV, o.branch]);
2219
+ runGit(tree, [
2220
+ "fetch",
2221
+ REMOTE,
2222
+ DEV_REFSPEC,
2223
+ `+refs/heads/${o.branch}:refs/remotes/${REMOTE}/${o.branch}`,
2224
+ ]);
814
2225
  appendFeature(tree, { workflow: o.workflow, fid: o.fid }, ctx.log);
815
2226
  commitBookkeeping({
816
2227
  root: tree,
@@ -825,7 +2236,7 @@ async function landPr(ctx, root, o) {
825
2236
  .filter((p) => p !== "" && !CLOSE_DOCS.test(p));
826
2237
  if (stray.length)
827
2238
  throw new Stop(EXIT_LAND_STOPPED, `${o.workflow} close diff carries non-doc files:\n${stray.join("\n")}`);
828
- const pushed = pushBranch(tree, { mode: "feature" }, ctx.log);
2239
+ const pushed = await pushBranch(tree, { mode: "feature" }, ctx.log);
829
2240
  if (pushed.code !== EXIT.OK)
830
2241
  throw new Stop(EXIT_PUSH_FAILED, "close-commit push failed — the PR would not carry the roadmap row or the close status rows");
831
2242
  const opened = openPrFor(tree, {
@@ -853,6 +2264,8 @@ async function landPr(ctx, root, o) {
853
2264
  ctx.emit({ stage: "merge", prNumber: Number(prNumber), subject, body: "" });
854
2265
  return EXIT.USE_MCP;
855
2266
  }
2267
+ if (merged.code === EXIT_BASE_NOT_DEV)
2268
+ throw new Stop(EXIT_LAND_STOPPED, `PR ${prNumber} does not target ${DEV} — bkit merges into ${DEV} only, releases stay manual; nothing merged, PR left open`);
856
2269
  if (merged.out.merged) {
857
2270
  sha = merged.out.mergeCommitOid ?? "";
858
2271
  break;
@@ -862,9 +2275,9 @@ async function landPr(ctx, root, o) {
862
2275
  throw new Stop(EXIT_LAND_STOPPED, `PR ${prNumber} did not reach MERGED (state=${merged.out.state})`);
863
2276
  if (attempt >= TIMEOUTS.LAND_ATTEMPTS)
864
2277
  throw new Stop(EXIT_LAND_STOPPED, `PR ${prNumber} still not merged after ${attempt} tries — left open; merge it, then re-run with --pr=${prNumber} --merged-sha=<merge commit>`);
865
- updateBranch(root, prNumber, ctx.log);
2278
+ await mergeDevIntoPrBranch(root, o.branch, ctx.log);
866
2279
  const wait = landBackoffMs(attempt);
867
- ctx.log(`PR ${prNumber} not merged on try ${attempt} of ${TIMEOUTS.LAND_ATTEMPTS} — branch updated from dev; trying again in ${(wait / 1000).toFixed(1)}s`);
2280
+ ctx.log(`PR ${prNumber} not merged on try ${attempt} of ${TIMEOUTS.LAND_ATTEMPTS} — trying again in ${(wait / 1000).toFixed(1)}s`);
868
2281
  await sleep(wait);
869
2282
  }
870
2283
  transport = "gh";
@@ -876,17 +2289,18 @@ async function landPr(ctx, root, o) {
876
2289
  }
877
2290
  if (sha === "")
878
2291
  throw new Stop(EXIT_LAND_STOPPED, `could not resolve the landed SHA for PR ${prNumber}`);
879
- if (!runGit(root, ["fetch", REMOTE, DEV]).ok)
2292
+ if (!fetchDev(root).ok)
880
2293
  throw new Stop(EXIT_LAND_STOPPED, "fetch of origin/dev after the merge failed");
881
2294
  return { shape: "pr", transport, sha, prNumber: Number(prNumber), pushAttempts: 0 };
882
2295
  }
883
2296
  /**
884
2297
  * Bring local dev up to `sha` when that is a pure fast-forward — `merge
885
2298
  * --ff-only` when the main checkout is on dev, else move the branch pointer
886
- * alone; nothing is checked out or pushed. Local commits origin/dev lacks (listed
887
- * with the command that publishes them), or git refusing (an uncommitted edit the
888
- * move would overwrite, dev checked out in another worktree), skip it with a log
889
- * line: what landed is on origin/dev either way.
2299
+ * alone; nothing is checked out or pushed. Local dev already past `sha` and on
2300
+ * origin/dev (a later landing fast-forwarded it) is current. Local commits
2301
+ * origin/dev lacks (listed with the command that publishes them), or git refusing
2302
+ * (an uncommitted edit the move would overwrite, dev checked out in another
2303
+ * worktree), skip it with a log line: what landed is on origin/dev either way.
890
2304
  */
891
2305
  function fastForwardDev(root, sha, log) {
892
2306
  const local = git(root, ["rev-parse", "-q", "--verify", `refs/heads/${DEV}`]);
@@ -894,8 +2308,11 @@ function fastForwardDev(root, sha, log) {
894
2308
  return "none";
895
2309
  if (local === sha)
896
2310
  return "current";
897
- if (!runGit(root, ["merge-base", "--is-ancestor", local, sha]).ok) {
898
- const ahead = (git(root, ["log", "--format=%h %s", `${sha}..${local}`]) ?? "")
2311
+ const isAncestor = (a, b) => runGit(root, ["merge-base", "--is-ancestor", a, b]).ok;
2312
+ if (!isAncestor(local, sha)) {
2313
+ if (isAncestor(sha, local) && isAncestor(local, UPSTREAM))
2314
+ return "current";
2315
+ const ahead = (git(root, ["log", "--format=%h %s", `${UPSTREAM}..${local}`]) ?? "")
899
2316
  .split("\n")
900
2317
  .filter((l) => l !== "");
901
2318
  log(`local ${DEV} has ${ahead.length} commit(s) ${UPSTREAM} does not — not fast-forwarded:`);
@@ -937,12 +2354,42 @@ function notOnDev(root, branch) {
937
2354
  return lines(branch, p).some((l) => !before.has(l) && !onDev.has(l));
938
2355
  });
939
2356
  }
940
- /** Uncommitted or untracked files in the feature worktree; [] when there is no worktree. */
2357
+ /**
2358
+ * Those of `paths` whose content at `spec(p)` is already local `dev`'s: work the
2359
+ * branch carries because `dev` is unpushed, not work a run in this branch made.
2360
+ * `spec` names the side to compare — the index (`:path`) or a commit (`ref:path`).
2361
+ */
2362
+ function localDevCopies(root, paths, spec) {
2363
+ if (git(root, ["rev-parse", "-q", "--verify", `refs/heads/${DEV}`]) === null)
2364
+ return [];
2365
+ return paths.filter((p) => {
2366
+ const at = git(root, ["rev-parse", "-q", "--verify", `${DEV}:${p}`]);
2367
+ return at !== null && at === git(root, ["rev-parse", "-q", "--verify", spec(p)]);
2368
+ });
2369
+ }
2370
+ /**
2371
+ * What a close refusal adds when some of the paths it names are unpushed `dev`'s
2372
+ * own content: the branch inherited them, and publishing `dev` is what unblocks
2373
+ * the close. Empty when none are, so the refusal reads as it did before.
2374
+ */
2375
+ function unpushedDevCause(root, inherited, total, then) {
2376
+ if (inherited === 0)
2377
+ return "";
2378
+ const ahead = git(root, ["rev-list", "--count", `${UPSTREAM}..${DEV}`]) ?? "?";
2379
+ const tip = git(root, ["rev-parse", "--short", DEV]) ?? DEV;
2380
+ const which = inherited === total ? "all of them" : `${inherited} of them`;
2381
+ return `\n${which} are local ${DEV}'s content (tip ${tip}, ${ahead} commit(s) ahead of ${UPSTREAM}): this branch carries unpushed ${DEV} work — publish ${DEV} (git push ${REMOTE} ${DEV})${then}`;
2382
+ }
2383
+ /**
2384
+ * Uncommitted or untracked files in the feature worktree; [] when there is no
2385
+ * worktree. The worktree copy entries setup copied in (`copyExcludes`) are never
2386
+ * committed, so they are not work left behind.
2387
+ */
941
2388
  function uncommitted(root, fid) {
942
2389
  const wt = worktreeDir(root, fid);
943
2390
  if (!fs.existsSync(wt))
944
2391
  return [];
945
- const status = runGit(wt, ["status", "--porcelain", "-uall"]);
2392
+ const status = runGit(wt, ["status", "--porcelain", "-uall", "--", ".", ...copyExcludes(wt)]);
946
2393
  if (!status.ok)
947
2394
  return [`git status in ${wt} failed: ${status.stderr}`];
948
2395
  return status.stdout.split("\n").filter((l) => l !== "");
@@ -954,11 +2401,6 @@ async function landVerb(ctx) {
954
2401
  const fid = String(ctx.flags.fid);
955
2402
  const root = repoRoot(ctx.cwd);
956
2403
  const month = resolveMonth(root, fid, str(ctx.flags.month));
957
- // `bkit install` can leave core.bare=true on the main checkout, which breaks every worktree below.
958
- if (git(root, ["config", "--get", "core.bare"]) === "true" &&
959
- fs.statSync(path.join(root, ".git"), { throwIfNoEntry: false })?.isDirectory()) {
960
- runGit(root, ["config", "core.bare", "false"]);
961
- }
962
2404
  const worktreeStatus = path.join(git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root, "docs", "plans", month, "logs", fid, "status.jsonl");
963
2405
  try {
964
2406
  const devPushes = devPushesOf(root, worktreeStatus, ctx.log);
@@ -978,7 +2420,7 @@ async function landVerb(ctx) {
978
2420
  }));
979
2421
  if (typeof landed === "number")
980
2422
  return landed;
981
- runGit(root, ["fetch", REMOTE, DEV]);
2423
+ fetchDev(root);
982
2424
  const localDev = devPushes ? fastForwardDev(root, landed.sha, ctx.log) : null;
983
2425
  // The audit: canonical docs on origin/dev, the landed body clean, the transport recorded.
984
2426
  const docs = canonicalDocs(root, landed.sha, workflow, month, fid);
@@ -1006,8 +2448,10 @@ async function landVerb(ctx) {
1006
2448
  if (missing.length)
1007
2449
  throw new Stop(EXIT_LANDED_UNVERIFIED, `canonical ${workflow} missing on ${UPSTREAM}: ${missing.join(", ")}`);
1008
2450
  const notLanded = notOnDev(root, branch);
1009
- if (notLanded.length)
1010
- throw new Stop(EXIT_LANDED_UNVERIFIED, `${branch} carries work ${UPSTREAM} does not — ${branch} and its worktree kept:\n${notLanded.join("\n")}`);
2451
+ if (notLanded.length) {
2452
+ const inherited = localDevCopies(root, notLanded, (p) => `${branch}:${p}`);
2453
+ throw new Stop(EXIT_LANDED_UNVERIFIED, `${branch} carries work ${UPSTREAM} does not — ${branch} and its worktree kept:\n${notLanded.join("\n")}${unpushedDevCause(root, inherited.length, notLanded.length, "; the close landed without it.")}`);
2454
+ }
1011
2455
  let worktree = null;
1012
2456
  const left = devPushes ? uncommitted(root, fid) : [];
1013
2457
  if (left.length) {
@@ -1141,76 +2585,343 @@ export const branchesCommand = {
1141
2585
  noun: "branches",
1142
2586
  summary: "Sync, push, land and rebase branches; stamp and read a doc's base-commit anchor.",
1143
2587
  verbs: {
2588
+ parse: {
2589
+ summary: "Read an explicitly named or existing branch from the session prompt.",
2590
+ use: "workflow",
2591
+ flags: [
2592
+ { name: "prompt-file", type: "string", required: true, help: "session prompt" },
2593
+ {
2594
+ name: "workflow",
2595
+ type: "string",
2596
+ help: "debug: validate an explicit debug adoption request",
2597
+ },
2598
+ ],
2599
+ output: {
2600
+ branch: "one existing branch, or null",
2601
+ via: "explicit | token | null",
2602
+ where: "local | remote | both | null",
2603
+ },
2604
+ exitCodes: {
2605
+ 3: "an explicit branch is invalid or absent",
2606
+ 8: "multiple branches were named",
2607
+ },
2608
+ run: (ctx) => {
2609
+ if (ctx.flags.workflow !== undefined && ctx.flags.workflow !== "debug")
2610
+ throw new CommandError(EXIT.USAGE, "--workflow must be debug");
2611
+ const prompt = fs.readFileSync(path.resolve(ctx.cwd, String(ctx.flags.promptFile)), "utf8");
2612
+ const candidates = new Map();
2613
+ for (const token of prompt.split(/\s+/)) {
2614
+ const explicit = token.startsWith("branch=");
2615
+ const branch = explicit ? token.slice("branch=".length) : token;
2616
+ if (!explicit && (!branch.includes("/") || /^[a-z][a-z0-9+.-]*:\/\//i.test(branch)))
2617
+ continue;
2618
+ const valid = runGit(ctx.cwd, ["check-ref-format", "--branch", branch]).ok;
2619
+ const local = valid &&
2620
+ runGit(ctx.cwd, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]).ok;
2621
+ const remote = valid &&
2622
+ runGit(ctx.cwd, ["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`])
2623
+ .ok;
2624
+ if (!local && !remote) {
2625
+ if (explicit)
2626
+ throw new CommandError(3, `branch ${branch} is invalid or does not exist`);
2627
+ continue;
2628
+ }
2629
+ candidates.set(branch, {
2630
+ via: explicit ? "explicit" : "token",
2631
+ where: local && remote ? "both" : local ? "local" : "remote",
2632
+ });
2633
+ }
2634
+ if (candidates.size > 1)
2635
+ throw new CommandError(8, `multiple branch selections: ${[...candidates.keys()].join(", ")}`);
2636
+ const selected = [...candidates.entries()][0];
2637
+ ctx.emit(selected
2638
+ ? { branch: selected[0], ...selected[1] }
2639
+ : { branch: null, via: null, where: null });
2640
+ return EXIT.OK;
2641
+ },
2642
+ },
1144
2643
  sync: {
1145
- summary: `Fetch ${UPSTREAM}; report whether it is an ancestor of HEAD (Path A/B) and how far docs/ is behind; optionally merge it in.`,
2644
+ summary: `Fetch ${UPSTREAM}; report whether it is an ancestor of HEAD (Path A/B) and how far docs/ and the ledgers are behind; optionally merge it in.`,
2645
+ use: "workflow",
1146
2646
  flags: [
1147
2647
  {
1148
2648
  name: "head",
1149
2649
  type: "string",
1150
2650
  help: "commit to compare (default HEAD), e.g. ship's ENTRY_HEAD",
1151
2651
  },
2652
+ {
2653
+ name: "merge",
2654
+ type: "boolean",
2655
+ help: `ship Step 4: merge ${UPSTREAM} into the checked-out feature branch — the run's uncommitted work is committed first, ledger conflicts union, a lockfile regenerates from ${DEV}'s copy, a generated register takes ${DEV}'s copy and is rebuilt after the merge, a doc embedding the register's generated block takes ${DEV}'s block and merges the rest, the install record (.bkit/version) merges entry by entry with ${DEV}'s value where both changed, any other conflict stays in the tree with the merge in progress for a hand resolution (exit 24; run again after git add), then a declared bkit:generate runs and its output is committed; never a rebase or force-push, never on ${DEV} / main`,
2656
+ },
1152
2657
  {
1153
2658
  name: "merge-docs",
1154
2659
  type: "boolean",
1155
- help: `on a feature branch whose docs/ is behind, merge ${UPSTREAM} (ledgers union, other docs/ take ${DEV}, anything else aborts)`,
2660
+ help: `on a feature branch whose docs/ or ledgers are behind, merge ${UPSTREAM} (ledgers union, a generated register takes ${DEV}'s copy and is rebuilt, a doc embedding its generated block takes ${DEV}'s block and merges the rest, the install record (.bkit/version) merges entry by entry, other docs/ take ${DEV}, anything else aborts), then run a declared bkit:generate and commit its output`,
2661
+ },
2662
+ {
2663
+ name: "fid",
2664
+ type: "string",
2665
+ help: "--merge: the feature id in the commit messages (default: the branch name without feat/)",
2666
+ },
2667
+ {
2668
+ name: "file",
2669
+ type: "string",
2670
+ help: "--merge: the run's status.jsonl: a completed merge appends an engine-action row (action merge, key merge/{old tip}, ref the new HEAD)",
2671
+ },
2672
+ {
2673
+ name: "sentinel",
2674
+ type: "string",
2675
+ help: "--merge: file removed at start and created on refusal, e.g. logs/{FID}/.rebase-failed",
1156
2676
  },
1157
2677
  ],
1158
2678
  output: {
1159
2679
  branch: "current branch (null when detached)",
1160
- head: "commit compared (after a merge: the merge commit)",
2680
+ head: "commit compared (after a merge: the new HEAD)",
1161
2681
  basePath: `A when ${UPSTREAM} is an ancestor of head (nothing to integrate), else B`,
1162
2682
  behind: `commits on ${UPSTREAM} not in head`,
1163
- docsBehind: `of those, commits touching docs/`,
1164
- merged: `true when --merge-docs merged ${UPSTREAM}`,
1165
- resolved: "conflicts the merge resolved: [{path, how: union|dev}]",
2683
+ docsBehind: `of those, commits touching docs/ or a ledger path (LEDGERS)`,
2684
+ merged: `true when --merge or --merge-docs merged ${UPSTREAM}`,
2685
+ resolved: "conflicts the merge resolved: [{path, how: union|lockfile|register|embed|record|dev}]",
2686
+ rebuilt: "a generated register the merge settled on dev's copy, or whose generated block a doc took from dev, rebuilt after the merge: true (rebuilt; output committed), false (failed: it keeps dev's copy), null (not run: none settled, its script absent, or no merge)",
2687
+ generated: "bkit:generate after the merge: true (ran; only the paths it changed committed), false (failed, or it changed a path that already held uncommitted changes; exit 25), null (not run: no merge, or undeclared)",
2688
+ outcome: `--merge: merged | current (${UPSTREAM} already an ancestor; nothing done) | pending (conflicts left for a hand resolution, merge in progress) | refused (merge aborted)`,
2689
+ carried: "--merge: the commit that carried the uncommitted work before the merge (null when the tree was clean)",
2690
+ pending: "--merge: the paths left conflicted for a hand resolution (empty otherwise)",
2691
+ aborted: "--merge: a refused merge was aborted",
2692
+ sentinel: "--merge: the sentinel written on refusal (null otherwise)",
1166
2693
  },
1167
2694
  exitCodes: {
1168
- [EXIT_DETACHED]: "--merge-docs with no branch checked out",
2695
+ [EXIT_REFUSED]: "--merge: the uncommitted work could not be committed before the merge",
2696
+ [EXIT_DETACHED]: "--merge / --merge-docs with no branch checked out",
1169
2697
  [EXIT_FETCH_FAILED]: `git fetch ${REMOTE} ${DEV} failed`,
1170
- [EXIT_MERGE_CONFLICT]: "the docs merge conflicted outside docs/ or could not be committed; merge aborted",
2698
+ [EXIT_MERGE_CONFLICT]: `the merge conflicted where it may not (--merge-docs: outside docs/ and the ledgers; --merge: a ledger union, lockfile regenerate or register resolution failed), could not be committed, or (--merge) ${UPSTREAM} could not be merged at all; merge aborted`,
2699
+ [EXIT_HAND_RESOLVE]: "--merge: conflicts outside the ledgers, lockfiles, generated registers, their generated blocks and the install record are left in the tree with the merge in progress; resolve them, git add, run again",
2700
+ [EXIT_GENERATE_FAILED]: "bkit:generate failed after the merge, or its output could not be committed; the merge commit stays",
1171
2701
  },
1172
2702
  run: syncVerb,
1173
2703
  },
2704
+ regenerate: {
2705
+ summary: "Run a declared bkit:generate on the feature branch and commit only the paths it changed (ship Step 10's fix round).",
2706
+ use: "workflow",
2707
+ flags: [
2708
+ {
2709
+ name: "fid",
2710
+ type: "string",
2711
+ help: "the feature id in the commit message (default: the branch name without feat/)",
2712
+ },
2713
+ {
2714
+ name: "attempt",
2715
+ type: "string",
2716
+ help: "ship Step 10's merge round: the commit is fix({FID}): regenerate attempt {N}; without it, chore({FID}): regenerate before re-validating",
2717
+ },
2718
+ {
2719
+ name: "file",
2720
+ type: "string",
2721
+ help: "the run's status.jsonl: a commit appends an engine-action row (action regenerate, key regenerate/{old tip}, ref the new HEAD)",
2722
+ },
2723
+ ],
2724
+ output: {
2725
+ outcome: "committed (bkit:generate changed paths; committed) | unchanged (it changed nothing) | undeclared (no bkit:generate script; nothing run)",
2726
+ head: "HEAD after the verb (the regenerate commit when committed)",
2727
+ paths: "the paths bkit:generate changed and the commit carries (empty otherwise)",
2728
+ },
2729
+ exitCodes: {
2730
+ [EXIT_DETACHED]: "no branch checked out",
2731
+ [EXIT_GENERATE_FAILED]: "bkit:generate failed, changed a path that already held uncommitted changes, or its output could not be committed; nothing committed",
2732
+ },
2733
+ run: regenerateVerb,
2734
+ },
1174
2735
  push: {
1175
- summary: "Push the current branch with exactly one git push: plain for dev/main, --force-with-lease otherwise.",
2736
+ summary: "Push the current branch with exactly one git push: plain for dev/main, --force-with-lease otherwise; 81 tests lock held.",
2737
+ use: "workflow",
1176
2738
  flags: [
1177
2739
  {
1178
2740
  name: "mode",
1179
2741
  type: "string",
1180
2742
  required: true,
1181
- help: "feature (a step's push) | abort (Failure Path: never into an open PR) | dev (the checkout must be on dev)",
2743
+ help: "feature (a step's push) | abort (Failure Path: never into an open PR) | dev (the checkout must be on dev) | plain (a feature branch, never forced)",
1182
2744
  },
1183
2745
  { name: "set-upstream", type: "boolean", help: "push with -u" },
2746
+ {
2747
+ name: "ahead-of",
2748
+ type: "string",
2749
+ help: "--mode=plain: refuse (21) when HEAD has no commits beyond this ref; an origin/<branch> ref is fetched first",
2750
+ },
2751
+ {
2752
+ name: "commit",
2753
+ type: "string",
2754
+ help: "--mode=feature: `git add -A`, then an allow-empty commit with this message (plus ` bkit [auto route]` when --label holds bkit:auto), once per run, before the push",
2755
+ },
2756
+ {
2757
+ name: "label",
2758
+ type: "string",
2759
+ repeatable: true,
2760
+ help: "--commit: the issue's labels, one per flag",
2761
+ },
2762
+ { name: "file", type: "string", help: "--commit: status.jsonl for the engine-action row" },
2763
+ { name: "workflow", type: "string", help: "--commit: the workflow, for the run number" },
1184
2764
  {
1185
2765
  name: "require-ci",
1186
2766
  type: "boolean",
1187
- help: "this push must start a CI run: refuse when the HEAD message carries a skip-CI token",
2767
+ help: `this push must start a CI run: refuse when the HEAD message carries a skip-CI token; --mode=feature on a feature branch first merges ${UPSTREAM} in when its docs/ or ledgers are behind (as sync --merge-docs does), so GitHub sees no ledger conflict`,
1188
2768
  },
1189
2769
  {
1190
2770
  name: "open-pr",
1191
2771
  type: "string",
1192
2772
  help: "--mode=abort: the open-PR answer from MCP (a number, or none) instead of asking gh",
1193
2773
  },
2774
+ {
2775
+ name: "fid",
2776
+ type: "string",
2777
+ help: "an in-place run on dev: its FID, which selects the run's shared-checkout record; with it a missing record refuses the push",
2778
+ },
1194
2779
  ],
1195
2780
  output: {
1196
2781
  pushed: "true when the push ran and succeeded",
2782
+ lockHolder: "the tests-lock holder on exit 81 (null otherwise)",
2783
+ replayed: "true when the run's commits went out as copies cherry-picked onto a fresh origin/dev (an in-place run on dev whose local dev holds other commits); sha is then the landed origin/dev commit",
1197
2784
  ref: "the branch pushed — link handover artifacts to this ref; null when nothing was pushed",
1198
2785
  sha: "HEAD commit pushed (null when not pushed)",
1199
2786
  forced: "true when pushed with --force-with-lease",
1200
- skipped: "why the push did not run: open-pr | skip-ci (null otherwise)",
2787
+ skipped: "why the push did not run: open-pr | skip-ci | no-run-commits (an in-place run on dev with nothing new to push) (null otherwise)",
1201
2788
  prNumber: "the open PR that stopped an abort push (null otherwise)",
2789
+ mergedDev: `--require-ci: ${UPSTREAM} was merged in before the push`,
2790
+ commit: "--commit: the marker commit's sha",
2791
+ deduped: "--commit: the marker commit was already made this run (not made again)",
1202
2792
  },
1203
2793
  exitCodes: {
2794
+ 4: "the pre-push hook could not acquire the tests lock",
1204
2795
  [EXIT_DETACHED]: "no branch checked out",
2796
+ [EXIT_NOTHING_TO_PUSH]: "--mode=plain or --commit on dev / main, or --ahead-of and HEAD has no commits beyond it",
1205
2797
  [EXIT_SKIP_CI]: "--require-ci and the HEAD message carries a skip-CI token",
1206
2798
  [EXIT_OPEN_PR]: "--mode=abort and the branch has an open PR: push skipped, remote HEAD kept",
1207
- [EXIT_PUSH_FAILED]: "git push failed",
2799
+ [EXIT_PUSH_FAILED]: "git push failed, or dev refused a replayed push (in-place run on dev: the refusal is printed)",
1208
2800
  [EXIT_NOT_DEV]: "--mode=dev and the checkout is not on dev",
2801
+ [EXIT_NO_RECORD]: "--mode=dev, or --fid, on dev with no shared-checkout record for the run: nothing pushed",
2802
+ [EXIT_FETCH_FAILED]: "fetching origin/dev failed (in-place run on dev, or a --require-ci feature push); nothing pushed",
2803
+ [EXIT_MERGE_CONFLICT]: "in-place run on dev: a run commit does not apply onto origin/dev without the local commits it builds on; or a --require-ci feature push: merging origin/dev conflicts outside docs/ and the ledgers (merge aborted). The conflicting paths are printed, nothing pushed",
2804
+ [EXIT_GENERATE_FAILED]: "--require-ci feature push: bkit:generate failed after merging origin/dev; nothing pushed",
1209
2805
  },
1210
2806
  run: pushVerb,
1211
2807
  },
2808
+ "fast-forward": {
2809
+ summary: "Fetch a remote branch and fast-forward the checkout onto it; refuse when diverged.",
2810
+ use: "workflow",
2811
+ flags: [
2812
+ {
2813
+ name: "onto",
2814
+ type: "string",
2815
+ required: true,
2816
+ help: "the ref to fast-forward onto; an origin/<branch> ref is fetched first",
2817
+ },
2818
+ ],
2819
+ output: { moved: "HEAD moved", head: "HEAD after" },
2820
+ exitCodes: {
2821
+ [EXIT_FETCH_FAILED]: "fetching --onto failed, or it does not resolve",
2822
+ [EXIT_DIVERGED]: "the checkout has commits --onto lacks: nothing moved",
2823
+ },
2824
+ run: fastForwardVerb,
2825
+ },
2826
+ "scan-diff": {
2827
+ summary: "Exit 0 when the branch's diff from --base matches (paths, an added marker line, a source change, or a disabled test); 1 when not — --disabled-tests turns that round: 1 when a test was disabled or lost an assertion, 0 when none was.",
2828
+ use: "by-hand",
2829
+ flags: [
2830
+ {
2831
+ name: "base",
2832
+ type: "string",
2833
+ required: true,
2834
+ help: "diff <base>...HEAD; an origin/<branch> base is fetched first",
2835
+ },
2836
+ {
2837
+ name: "paths",
2838
+ type: "string",
2839
+ help: "a changed path matches this pattern (case-insensitive)",
2840
+ },
2841
+ {
2842
+ name: "marker",
2843
+ type: "string",
2844
+ help: "an added line carries this text, outside docs/plans",
2845
+ },
2846
+ {
2847
+ name: "code",
2848
+ type: "boolean",
2849
+ help: "a path changed outside docs/plans, docs/*.jsonl and .bkit/*.jsonl",
2850
+ },
2851
+ {
2852
+ name: "disabled-tests",
2853
+ type: "boolean",
2854
+ help: "an added line disables a test (`.skip` / `.todo` / `.fixme` / `xfail`, `t.Skip()`, `#[ignore]`, `@Disabled`, `@pytest.mark.skip`, `@unittest.skip`), outside comments or quotes, or an assertion is removed; matches exact moved occurrences once (unchanged test name, scope and setup across files), and rewritten assertions within the same file and test; unchanged duplicates do not cancel removals; inverts --paths / --marker / --code's polarity, so never pass it with --expect-none",
2855
+ },
2856
+ {
2857
+ name: "expect-none",
2858
+ type: "boolean",
2859
+ help: "invert the exit: 0 when nothing matched, 1 (naming the paths on stderr) when something did",
2860
+ },
2861
+ ],
2862
+ output: {
2863
+ found: "something matched",
2864
+ paths: "the matching paths",
2865
+ disabled: "[{file, line, test}]: unmatched added disabling markers and removed assertion occurrences, attributed to their original test (only with --disabled-tests)",
2866
+ },
2867
+ exitCodes: {
2868
+ [EXIT_DIFF_FAILED]: "--base does not resolve, or git diff failed",
2869
+ },
2870
+ run: scanDiffVerb,
2871
+ },
2872
+ "force-build": {
2873
+ summary: `Force a full CI build: put ${FORCE_BUILD} on the open PR's title, then push an empty marker commit (once per run).`,
2874
+ use: "workflow",
2875
+ flags: [
2876
+ { name: "fid", type: "string", required: true, help: "feature id, for the commit subject" },
2877
+ {
2878
+ name: "file",
2879
+ type: "string",
2880
+ required: true,
2881
+ help: "status.jsonl for the engine-action row",
2882
+ },
2883
+ {
2884
+ name: "workflow",
2885
+ type: "string",
2886
+ required: true,
2887
+ help: "the workflow, for the run number",
2888
+ },
2889
+ {
2890
+ name: "label",
2891
+ type: "string",
2892
+ repeatable: true,
2893
+ help: "the issue's labels; bkit:auto adds ` bkit [auto route]` to the commit",
2894
+ },
2895
+ {
2896
+ name: "open-pr",
2897
+ type: "string",
2898
+ help: "the open-PR answer from MCP (a number, or none) instead of asking gh",
2899
+ },
2900
+ {
2901
+ name: "title-set",
2902
+ type: "boolean",
2903
+ help: "the title is handled (set through MCP, or no PR is open): skip gh",
2904
+ },
2905
+ ],
2906
+ output: {
2907
+ prNumber: "the open PR whose title was checked, or null",
2908
+ titleChanged: `the title gained ${FORCE_BUILD}`,
2909
+ commit: "the marker commit's sha",
2910
+ deduped: "the marker commit was already made this run",
2911
+ pushed: "the push ran and succeeded",
2912
+ ref: "the branch pushed",
2913
+ sha: "HEAD pushed",
2914
+ },
2915
+ exitCodes: {
2916
+ [EXIT_DETACHED]: "no branch checked out",
2917
+ [EXIT_NOTHING_TO_PUSH]: "on dev / main",
2918
+ [EXIT_PUSH_FAILED]: "git commit or git push failed",
2919
+ },
2920
+ run: forceBuildVerb,
2921
+ },
1212
2922
  rebase: {
1213
- summary: "Drive a rebase to completion, auto-resolving ledger (union) and lockfile (regenerate) conflicts; refuse and abort on anything else.",
2923
+ summary: "Drive a rebase to completion, auto-resolving ledger (union), lockfile (regenerate), generated-register (take the target's copy, rebuild after), embedded generated-block (take the target's block, merge the rest, rebuild after) and install-record (merge entry by entry, the target's value where both changed) conflicts; refuse and abort on anything else.",
2924
+ use: "workflow",
1214
2925
  flags: [
1215
2926
  {
1216
2927
  name: "log-file",
@@ -1222,14 +2933,20 @@ export const branchesCommand = {
1222
2933
  type: "string",
1223
2934
  help: "file removed at start and created on refusal, e.g. logs/{FID}/.rebase-failed",
1224
2935
  },
2936
+ {
2937
+ name: "file",
2938
+ type: "string",
2939
+ help: "the run's status.jsonl: a completed rebase appends an engine-action row (action rebase, key rebase/{old tip}, ref the new HEAD)",
2940
+ },
1225
2941
  ],
1226
2942
  output: {
1227
2943
  outcome: "resolved | refused (a refused rebase is aborted)",
1228
- resolved: "conflicts resolved: [{path, how: union|lockfile}]",
2944
+ resolved: "conflicts resolved: [{path, how: union|lockfile|register|embed|record}]",
2945
+ rebuilt: "a generated register settled on the rebase target's copy, or whose generated block a doc took from the target, rebuilt after the rebase: true (rebuilt; output committed), false (failed: it keeps the target's copy), null (not run: none settled, or its script absent)",
1229
2946
  skippedCommits: "commits skipped because resolution emptied them",
1230
2947
  rounds: "resolve rounds run",
1231
2948
  refused: "the path that stopped resolution (null when none, or not path-specific)",
1232
- reason: "why resolution refused (null on success)",
2949
+ reason: "why resolution refused or stopped (null on success)",
1233
2950
  aborted: "a refused rebase was aborted (false on success, or when the abort failed)",
1234
2951
  sentinel: "the sentinel written on refusal (null otherwise)",
1235
2952
  },
@@ -1241,6 +2958,7 @@ export const branchesCommand = {
1241
2958
  },
1242
2959
  "sync-dev": {
1243
2960
  summary: "After a merge, fast-forward local dev to origin/dev without checking it out or pushing; frozen install when the main checkout is on dev and moved.",
2961
+ use: "workflow",
1244
2962
  flags: [],
1245
2963
  output: {
1246
2964
  devLocal: "fast-forwarded | current | skipped (local dev has commits origin/dev lacks, listed with the publish command, or git refused) | none (no local dev)",
@@ -1255,6 +2973,7 @@ export const branchesCommand = {
1255
2973
  },
1256
2974
  land: {
1257
2975
  summary: "Design / plan close: squash the branch onto origin/dev in a throwaway worktree and push it as dev (retrying with backoff when dev moved), else the PR squash-merge; then audit it, fast-forward local dev on a laptop and release the lock.",
2976
+ use: "workflow",
1258
2977
  flags: [
1259
2978
  { name: "workflow", type: "string", required: true, help: "design | plan" },
1260
2979
  { name: "fid", type: "string", required: true, help: "feature id" },
@@ -1296,7 +3015,7 @@ export const branchesCommand = {
1296
3015
  exitCodes: {
1297
3016
  [EXIT_PUSH_FAILED]: "dev moved before every one of LAND_ATTEMPTS pushes, or the PR branch push failed (nothing landed)",
1298
3017
  [EXIT_FETCH_FAILED]: `git fetch ${REMOTE} ${DEV} failed (nothing landed)`,
1299
- [EXIT_LAND_STOPPED]: "a guard stopped the land: stray files, failed squash, staged non-doc files, canonical blob mismatch, no checkout holds the branch, PR not opened / not merged after LAND_ATTEMPTS tries (nothing landed; the PR stays open)",
3018
+ [EXIT_LAND_STOPPED]: "a guard stopped the land: stray files, failed squash, staged non-doc files, canonical blob mismatch, no checkout holds the branch, PR not opened / not merged after LAND_ATTEMPTS tries, PR base not dev or unreadable (nothing landed; the PR stays open)",
1300
3019
  [EXIT_LANDED_UNVERIFIED]: "landed, but the body scan, transport cross-check or canonical-on-dev check failed",
1301
3020
  [EXIT_LOCK_LEFT]: "landed and audited, but the workflow lock file survived removal",
1302
3021
  },
@@ -1304,6 +3023,7 @@ export const branchesCommand = {
1304
3023
  },
1305
3024
  "anchor-stamp": {
1306
3025
  summary: "Put a <!-- bkit:anchor --> block recording the base commit and bkit release on top of a design/plan doc or audit report (idempotent).",
3026
+ use: "workflow",
1307
3027
  flags: [
1308
3028
  { name: "file", type: "string", required: true, help: "doc to stamp (must exist)" },
1309
3029
  {
@@ -1340,6 +3060,7 @@ export const branchesCommand = {
1340
3060
  },
1341
3061
  "anchor-read": {
1342
3062
  summary: "Read a doc's anchor fields; with --against, decide whether anything landed since its baseSha.",
3063
+ use: "by-hand",
1343
3064
  flags: [
1344
3065
  { name: "file", type: "string", required: true, help: "design/plan doc or audit report" },
1345
3066
  {