@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,9 +1,11 @@
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
@@ -11,47 +13,78 @@
11
13
  // never force-pushed and a personal one survives the rebase that rewrote it.
12
14
 
13
15
  import { spawnSync } from "node:child_process";
16
+ import { createHash } from "node:crypto";
14
17
  import * as fs from "node:fs";
15
18
  import * as os from "node:os";
16
19
  import * as path from "node:path";
17
20
 
18
21
  import { gitEnv } from "../../ledgers/telemetry.js";
22
+ import { actionHash, actionKey, alreadyDone, recordAction } from "../../ledgers/status.js";
19
23
  import {
20
24
  bodySkipToken,
25
+ classifyLockExit,
21
26
  CommandError,
22
27
  DEV,
23
28
  EXIT,
29
+ ghUnavailable,
24
30
  git,
25
31
  isSharedBranch,
32
+ OUTPUT_LIMIT,
26
33
  parseJson,
27
34
  repoRoot,
35
+ runGh,
28
36
  runGit,
29
37
  SKIP_CI_TOKEN,
38
+ testsLockHolder,
39
+ wholeNumber,
30
40
  type CommandSpec,
31
41
  type RunContext,
32
42
  } from "../lib.js";
33
43
  import { bkitVersionStatus, type BkitVersionStatus } from "../../shared/bkit-latest.js";
34
- import { landBackoffMs, landDir, pushToDev, sleep } from "../land.js";
44
+ import {
45
+ parseBkitVersion,
46
+ serializeBkitVersion,
47
+ type BkitVersion,
48
+ } from "../../install/version-file.js";
49
+ import { DEV_REFSPEC, fetchDev, landBackoffMs, landDir, pushToDev, sleep } from "../land.js";
35
50
  import { TIMEOUTS } from "../../shared/timeouts.js";
36
- import { commitBookkeeping } from "./ledgers.js";
51
+ import {
52
+ activeRecord,
53
+ commitBookkeeping,
54
+ markRecordPushed,
55
+ recordOnBranch,
56
+ type SharedCheckoutRecord,
57
+ } from "./ledgers.js";
37
58
  import { releaseLock, resolveMonth, workflowLockPath } from "./locks.js";
38
59
  import {
60
+ EXIT_BASE_NOT_DEV,
61
+ FORCE_BUILD,
39
62
  closeTransportRow,
40
63
  crossCheckRows,
41
64
  mergePr,
42
65
  openPrFor,
43
66
  probePr,
44
- updateBranch,
45
67
  } from "./prs.js";
68
+ import { AUTO_LABEL, AUTO_ROUTE_SUFFIX } from "./issues.js";
46
69
  import { appendFeature } from "./roadmap.js";
47
70
  import { detect } from "./runtime.js";
48
- import { readStatusRows, readStatusRowsAt } from "./status.js";
49
- import { removeWorktree, worktreeDir } from "./worktrees.js";
71
+ import { readRuns, readStatusRows, readStatusRowsAt } from "./status.js";
72
+ import { declaredName, testSource } from "./test-blocks.js";
73
+ import {
74
+ addAllButCopied,
75
+ copyExcludes,
76
+ hasLeftovers,
77
+ recordRebase,
78
+ removeWorktree,
79
+ worktreeDir,
80
+ } from "./worktrees.js";
50
81
  import {
51
82
  COULD_NOT_RUN_EXIT_CODES,
52
83
  LOCKFILE_REGENERATE,
53
84
  installCommand,
85
+ scriptCommand,
54
86
  } from "../../shared/package-manager.js";
87
+ import { readPackageJson } from "../../shared/package-json.js";
55
88
  import { str } from "./status.js";
56
89
 
57
90
  const REMOTE = "origin";
@@ -73,28 +106,28 @@ export const EXIT_INSTALL_FAILED = 16;
73
106
  export const EXIT_LAND_STOPPED = 17;
74
107
  export const EXIT_LANDED_UNVERIFIED = 18;
75
108
  export const EXIT_LOCK_LEFT = 19;
109
+ export const EXIT_NO_RECORD = 20;
110
+ export const EXIT_NOTHING_TO_PUSH = 21;
111
+ export const EXIT_DIVERGED = 22;
112
+ export const EXIT_DIFF_FAILED = 23;
113
+ export const EXIT_HAND_RESOLVE = 24;
114
+ export const EXIT_GENERATE_FAILED = 25;
76
115
 
77
116
  // ---------------------------------------------------------------------------
78
117
  // Process helpers
79
118
  // ---------------------------------------------------------------------------
80
119
 
81
120
  /** git with a non-interactive editor, so `--continue` / `--skip` / merge commits never open one. */
82
- const quietGit = (cwd: string, args: string[]) => {
83
- const res = spawnSync("git", args, {
84
- cwd,
85
- encoding: "utf-8",
86
- env: { ...gitEnv(), GIT_EDITOR: "true" },
87
- });
88
- return {
89
- ok: res.status === 0,
90
- stdout: (res.stdout ?? "").trim(),
91
- stderr: (res.stderr ?? "").trim(),
92
- };
93
- };
121
+ const quietGit = (cwd: string, args: string[]) => runGit(cwd, args, { GIT_EDITOR: "true" });
94
122
 
95
- /** `git show :<stage>:<path>` as raw bytes; empty when that stage does not exist. */
96
- function stageBytes(top: string, stage: 1 | 2 | 3, file: string): Buffer {
97
- const res = spawnSync("git", ["show", `:${stage}:${file}`], { cwd: top, env: gitEnv() });
123
+ /** `git show :<stage>:<path>` as raw bytes; empty when that stage does not exist, null when git could not run. */
124
+ function stageBytes(top: string, stage: 1 | 2 | 3, file: string): Buffer | null {
125
+ const res = spawnSync("git", ["show", `:${stage}:${file}`], {
126
+ cwd: top,
127
+ env: gitEnv(),
128
+ maxBuffer: OUTPUT_LIMIT,
129
+ });
130
+ if (res.error) return null;
98
131
  // A missing stage is a legitimate shape (add/add, delete/modify): merge against empty.
99
132
  return res.status === 0 ? res.stdout : Buffer.alloc(0);
100
133
  }
@@ -127,7 +160,7 @@ const currentBranch = (cwd: string) => git(cwd, ["branch", "--show-current"]) ??
127
160
  * ledger or is missing.
128
161
  *
129
162
  * `.bkit/friction.jsonl` ships WITHOUT `merge=union` but is listed here; a row union
130
- * resurrects after `bkit harvest` drained it is re-banked by the next harvest.
163
+ * resurrects after the harvest drained it is re-banked by the next harvest.
131
164
  *
132
165
  * `docs/roadmap.md` is not append-only — it is regenerated from
133
166
  * `.bkit/issues.jsonl` — but every workflow close re-folds it, so both sides of
@@ -157,10 +190,71 @@ const globToRegExp = (glob: string) =>
157
190
  );
158
191
  const LEDGER_PATTERNS = LEDGERS.map(globToRegExp);
159
192
 
160
- export type ConflictKind = "ledger" | "lockfile" | "refuse";
193
+ /** bkit's install record: merged entry by entry (`recordResolve`), never line by line. */
194
+ export const INSTALL_RECORD = ".bkit/version";
195
+
196
+ /**
197
+ * Generated registers a conflict is settled in by taking dev's copy. Each side rebuilt
198
+ * the whole file, so neither side's text is worth a hand merge, and running `script`
199
+ * with `args` after the rebase or merge makes dev's copy current. `keep` brackets the
200
+ * one hand-written region, which the rebuild reads back and re-emits, so a branch's
201
+ * edit to it is carried onto dev's copy. `embed` names the variable in `script` that
202
+ * lists the hand-written docs the rebuild copies a generated block into, and the
203
+ * markers around that block.
204
+ */
205
+ export const REGISTERS: Readonly<
206
+ Record<
207
+ string,
208
+ {
209
+ script: string;
210
+ args: readonly string[];
211
+ keep: readonly [string, string];
212
+ embed: { variable: string; block: readonly [string, string] };
213
+ }
214
+ >
215
+ > = {
216
+ "docs/capabilities.md": {
217
+ script: "scripts/graphify/bkit-graphify.sh",
218
+ args: ["refresh"],
219
+ keep: ["<!-- overrides:start -->", "<!-- overrides:end -->"],
220
+ embed: {
221
+ variable: "GRAPH_EMBED_DOCS",
222
+ block: ["<!-- graph:packages:start -->", "<!-- graph:packages:end -->"],
223
+ },
224
+ },
225
+ };
226
+
227
+ /**
228
+ * Each doc a register's script in `top` embeds a generated block into, mapped to that
229
+ * register. Read from the script's own `embed.variable` assignment, so a repo whose
230
+ * script lists no docs, or that has no script, gets an empty map.
231
+ */
232
+ export function embedDocs(top: string): Map<string, string> {
233
+ const out = new Map<string, string>();
234
+ for (const [register, entry] of Object.entries(REGISTERS)) {
235
+ const script = path.join(top, entry.script);
236
+ if (!fs.existsSync(script)) continue;
237
+ const assigned = new RegExp(`^${entry.embed.variable}="([^"]*)"`, "m").exec(
238
+ fs.readFileSync(script, "utf-8"),
239
+ );
240
+ for (const doc of (assigned?.[1] ?? "").split(/\s+/).filter(Boolean)) out.set(doc, register);
241
+ }
242
+ return out;
243
+ }
244
+
245
+ export type ConflictKind = "ledger" | "lockfile" | "register" | "embed" | "record" | "refuse";
161
246
 
162
- /** How a conflicted path may be resolved. Only repo-root lockfiles count: the regenerate runs there. */
163
- export function classifyConflict(file: string): ConflictKind {
247
+ /**
248
+ * How a conflicted path may be resolved. Only repo-root lockfiles count: the regenerate
249
+ * runs there. `embeds` is the repo's `embedDocs`.
250
+ */
251
+ export function classifyConflict(
252
+ file: string,
253
+ embeds: ReadonlyMap<string, string> = new Map(),
254
+ ): ConflictKind {
255
+ if (Object.hasOwn(REGISTERS, file)) return "register";
256
+ if (embeds.has(file)) return "embed";
257
+ if (file === INSTALL_RECORD) return "record";
164
258
  if (Object.hasOwn(LOCKFILE_REGENERATE, file)) return "lockfile";
165
259
  if (LEDGER_PATTERNS.some((re) => re.test(file))) return "ledger";
166
260
  return "refuse";
@@ -191,7 +285,9 @@ export function unionResolve(
191
285
  try {
192
286
  const sides = { base: 1, ours: 2, theirs: 3 } as const;
193
287
  for (const [name, stage] of Object.entries(sides)) {
194
- fs.writeFileSync(path.join(tmp, name), stageBytes(top, stage, file));
288
+ const bytes = stageBytes(top, stage, file);
289
+ if (bytes === null) return { ok: false, problem: `git show :${stage}:${file} failed` };
290
+ fs.writeFileSync(path.join(tmp, name), bytes);
195
291
  }
196
292
  const merged = spawnSync(
197
293
  "git",
@@ -203,10 +299,11 @@ export function unionResolve(
203
299
  path.join(tmp, "base"),
204
300
  path.join(tmp, "theirs"),
205
301
  ],
206
- { cwd: top, env: gitEnv() },
302
+ { cwd: top, env: gitEnv(), maxBuffer: OUTPUT_LIMIT },
207
303
  );
208
304
  // --union never leaves conflict markers, so a non-zero exit is an I/O failure.
209
- if (merged.status !== 0) return { ok: false, problem: "git merge-file --union failed" };
305
+ if (merged.error || merged.status !== 0)
306
+ return { ok: false, problem: "git merge-file --union failed" };
210
307
  let text = merged.stdout.toString("utf-8");
211
308
  if (file.endsWith(".jsonl")) {
212
309
  if (!text.split("\n").every((l) => l.trim() === "" || parseJson(l).ok)) {
@@ -224,22 +321,180 @@ export function unionResolve(
224
321
  }
225
322
 
226
323
  /**
227
- * Resolve a lockfile conflict: start from the rebase target's copy, then
228
- * regenerate from the manifest, which merged normally (or refused and stopped
229
- * the rebase before this). During a rebase `--ours` is the branch being rebased
230
- * ONTO; `--theirs` is the commit being replayed.
324
+ * Resolve a lockfile conflict: start from dev's copy, then regenerate from the
325
+ * manifest, which merged normally (or refused and stopped the rebase or merge
326
+ * before this). During a rebase dev is `--ours` (the branch being rebased ONTO;
327
+ * `--theirs` is the commit being replayed); in a merge of origin/dev it is `--theirs`.
231
328
  */
232
- function lockfileResolve(top: string, file: string): boolean {
329
+ function lockfileResolve(top: string, file: string, dev: "ours" | "theirs" = "ours"): boolean {
233
330
  const regenerate = LOCKFILE_REGENERATE[file];
234
331
  if (!regenerate) return false;
235
- if (!runGit(top, ["checkout", "--ours", "--", file]).ok) return false;
332
+ if (!runGit(top, ["checkout", `--${dev}`, "--", file]).ok) return false;
236
333
  const res = spawnSync(regenerate[0]!, regenerate.slice(1), { cwd: top, stdio: "ignore" });
237
334
  return res.status === 0;
238
335
  }
239
336
 
337
+ /** The text from `keep`'s open marker through its close marker; null when either is missing. */
338
+ function keptRegion(text: string, [open, close]: readonly [string, string]): string | null {
339
+ const start = text.indexOf(open);
340
+ if (start === -1) return null;
341
+ const end = text.indexOf(close, start + open.length);
342
+ return end === -1 ? null : text.slice(start, end + close.length);
343
+ }
344
+
345
+ /**
346
+ * Settle a conflicted register on dev's copy, carrying the branch's edit to the
347
+ * hand-written region when dev left that region as the merge base had it. Refuses when
348
+ * a side deleted the file, or both sides changed the region: that needs a hand merge.
349
+ * During a rebase dev is `ours`; in a merge of origin/dev it is `theirs`.
350
+ */
351
+ export function registerResolve(
352
+ top: string,
353
+ file: string,
354
+ dev: "ours" | "theirs",
355
+ ): { ok: true } | { ok: false; problem: string } {
356
+ const entry = REGISTERS[file];
357
+ if (entry === undefined) return { ok: false, problem: "not a generated register" };
358
+ const base = stageBytes(top, 1, file);
359
+ const devSide = stageBytes(top, dev === "ours" ? 2 : 3, file);
360
+ const branchSide = stageBytes(top, dev === "ours" ? 3 : 2, file);
361
+ if (base === null || devSide === null || branchSide === null)
362
+ return { ok: false, problem: "git show of a conflict stage failed" };
363
+ if (devSide.length === 0 || branchSide.length === 0)
364
+ return { ok: false, problem: "one side deleted the register" };
365
+ let text = devSide.toString("utf-8");
366
+ const baseKept = keptRegion(base.toString("utf-8"), entry.keep);
367
+ const devKept = keptRegion(text, entry.keep);
368
+ const branchKept = keptRegion(branchSide.toString("utf-8"), entry.keep);
369
+ if (branchKept !== baseKept && branchKept !== devKept) {
370
+ if (devKept !== baseKept)
371
+ return { ok: false, problem: "both sides changed the hand-written region" };
372
+ if (devKept === null || branchKept === null)
373
+ return { ok: false, problem: "one side added or removed the hand-written region" };
374
+ text = text.replace(devKept, () => branchKept);
375
+ }
376
+ fs.writeFileSync(path.join(top, file), text);
377
+ return { ok: true };
378
+ }
379
+
380
+ /**
381
+ * Settle a conflicted doc that embeds a register's generated block: give all three
382
+ * stages dev's copy of the block, then merge the rest of the doc as git would. Refuses
383
+ * when a side lacks the block, or when the doc still conflicts outside it: that needs a
384
+ * hand merge. The register's rebuild rewrites the block afterwards.
385
+ */
386
+ export function embedResolve(
387
+ top: string,
388
+ file: string,
389
+ register: string,
390
+ dev: "ours" | "theirs",
391
+ ): { ok: true } | { ok: false; problem: string } {
392
+ const entry = REGISTERS[register];
393
+ if (entry === undefined) return { ok: false, problem: "not a generated register" };
394
+ const stages = { base: 1, ours: 2, theirs: 3 } as const;
395
+ const texts: Record<keyof typeof stages, string> = { base: "", ours: "", theirs: "" };
396
+ for (const [name, stage] of Object.entries(stages) as [keyof typeof stages, 1 | 2 | 3][]) {
397
+ const bytes = stageBytes(top, stage, file);
398
+ if (bytes === null) return { ok: false, problem: `git show :${stage}:${file} failed` };
399
+ texts[name] = bytes.toString("utf-8");
400
+ }
401
+ const devBlock = keptRegion(texts[dev], entry.embed.block);
402
+ if (devBlock === null) return { ok: false, problem: "a side lacks the generated block" };
403
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bkit-embed-"));
404
+ try {
405
+ for (const name of Object.keys(stages) as (keyof typeof stages)[]) {
406
+ const block = keptRegion(texts[name], entry.embed.block);
407
+ if (block === null) return { ok: false, problem: "a side lacks the generated block" };
408
+ fs.writeFileSync(
409
+ path.join(tmp, name),
410
+ texts[name].replace(block, () => devBlock),
411
+ );
412
+ }
413
+ const merged = spawnSync(
414
+ "git",
415
+ [
416
+ "merge-file",
417
+ "-p",
418
+ path.join(tmp, "ours"),
419
+ path.join(tmp, "base"),
420
+ path.join(tmp, "theirs"),
421
+ ],
422
+ { cwd: top, env: gitEnv(), maxBuffer: OUTPUT_LIMIT },
423
+ );
424
+ // Exit status = conflicts left, capped at 127; above that it failed.
425
+ if (merged.error || merged.status === null || merged.status > 127)
426
+ return { ok: false, problem: "git merge-file failed" };
427
+ if (merged.status > 0)
428
+ return { ok: false, problem: "it conflicts outside the generated block" };
429
+ fs.writeFileSync(path.join(top, file), merged.stdout);
430
+ return { ok: true };
431
+ } finally {
432
+ fs.rmSync(tmp, { recursive: true, force: true });
433
+ }
434
+ }
435
+
436
+ /** The value one entry takes: the side that changed it, or dev's when both did. */
437
+ function pickEntry<T>(base: T, dev: T, branch: T): T {
438
+ const same = (a: T, b: T) => JSON.stringify(a) === JSON.stringify(b);
439
+ return same(dev, base) ? branch : dev;
440
+ }
441
+
442
+ /**
443
+ * Merge a conflicted install record entry by entry: `pinnedVersion`,
444
+ * `claudeAllowDerived` and each `canonicalHashes` path take the side that changed
445
+ * them, and dev's value when both did. A fingerprint left at dev's value makes
446
+ * `bkit upgrade` treat that file as edited by hand until it refreshes the entry, so
447
+ * the record needs no rebuild. Refuses when a side deleted the record or a copy is
448
+ * not a record. During a rebase dev is `ours`; in a merge of origin/dev it is `theirs`.
449
+ */
450
+ export function recordResolve(
451
+ top: string,
452
+ dev: "ours" | "theirs",
453
+ ): { ok: true } | { ok: false; problem: string } {
454
+ const copies: BkitVersion[] = [];
455
+ for (const stage of [1, dev === "ours" ? 2 : 3, dev === "ours" ? 3 : 2] as const) {
456
+ const bytes = stageBytes(top, stage, INSTALL_RECORD);
457
+ if (bytes === null)
458
+ return { ok: false, problem: `git show :${stage}:${INSTALL_RECORD} failed` };
459
+ if (bytes.length === 0 && stage !== 1)
460
+ return { ok: false, problem: "one side deleted the install record" };
461
+ // Both sides adding the record leaves no base: merge against an empty one.
462
+ const parsed =
463
+ bytes.length === 0
464
+ ? { pinnedVersion: "", canonicalHashes: {}, claudeAllowDerived: [] }
465
+ : parseBkitVersion(bytes.toString("utf-8"));
466
+ if (parsed === null) return { ok: false, problem: "a copy of the install record is not valid" };
467
+ copies.push(parsed);
468
+ }
469
+ const [base, devSide, branch] = copies as [BkitVersion, BkitVersion, BkitVersion];
470
+ const canonicalHashes: Record<string, string> = {};
471
+ for (const p of new Set([
472
+ ...Object.keys(devSide.canonicalHashes),
473
+ ...Object.keys(branch.canonicalHashes),
474
+ ])) {
475
+ const hash = pickEntry(
476
+ base.canonicalHashes[p],
477
+ devSide.canonicalHashes[p],
478
+ branch.canonicalHashes[p],
479
+ );
480
+ if (hash !== undefined) canonicalHashes[p] = hash;
481
+ }
482
+ const merged: BkitVersion = {
483
+ pinnedVersion: pickEntry(base.pinnedVersion, devSide.pinnedVersion, branch.pinnedVersion),
484
+ canonicalHashes,
485
+ claudeAllowDerived: pickEntry(
486
+ base.claudeAllowDerived,
487
+ devSide.claudeAllowDerived,
488
+ branch.claudeAllowDerived,
489
+ ),
490
+ };
491
+ fs.writeFileSync(path.join(top, INSTALL_RECORD), serializeBkitVersion(merged));
492
+ return { ok: true };
493
+ }
494
+
240
495
  export interface Resolution {
241
496
  path: string;
242
- how: "union" | "lockfile" | "dev";
497
+ how: "union" | "lockfile" | "register" | "embed" | "record" | "dev";
243
498
  }
244
499
 
245
500
  export interface RebaseResult {
@@ -252,6 +507,18 @@ export interface RebaseResult {
252
507
  log: string[];
253
508
  }
254
509
 
510
+ const NOT_RESOLVABLE =
511
+ "not an append-only ledger, a recognised lockfile, a generated register, a doc embedding one or the install record";
512
+
513
+ /** How a rebase settled each kind of conflict, for its log. */
514
+ const REBASE_HOW: Record<Exclude<Resolution["how"], "dev">, string> = {
515
+ union: "union (append-only ledger)",
516
+ lockfile: "took rebase target + regenerated",
517
+ register: "took rebase target's copy of a generated register",
518
+ embed: "took rebase target's copy of the generated block, merged the rest",
519
+ record: "merged the install record entry by entry, rebase target's value where both changed",
520
+ };
521
+
255
522
  /**
256
523
  * Drive an in-progress rebase to completion, auto-resolving each stop. Loops
257
524
  * because `--continue` replays the next commit, which can conflict in turn; the
@@ -282,32 +549,47 @@ export function resolveRebase(
282
549
  return result;
283
550
  };
284
551
 
552
+ const embeds = embedDocs(top);
285
553
  while (result.rounds < 100) {
286
554
  result.rounds++;
287
555
  const conflicts = unmergedPaths(top);
288
556
  if (conflicts.length > 0) {
289
557
  // Classify the whole set before resolving any of it, so a refused path
290
558
  // never leaves half the set rewritten.
291
- const refused = conflicts.find((f) => classifyConflict(f) === "refuse");
559
+ const refused = conflicts.find((f) => classifyConflict(f, embeds) === "refuse");
292
560
  if (refused !== undefined) {
293
561
  return refuse(
294
- `REFUSE ${refused} — not an append-only ledger or a recognised lockfile; routing to Failure Path`,
562
+ `REFUSE ${refused} — ${NOT_RESOLVABLE}; routing to Failure Path`,
295
563
  refused,
296
- "not an append-only ledger or a recognised lockfile",
564
+ NOT_RESOLVABLE,
297
565
  );
298
566
  }
299
567
  for (const f of conflicts) {
300
- const kind = classifyConflict(f);
301
- const ok = kind === "ledger" ? unionResolve(top, f).ok : lockfileResolve(top, f);
568
+ const kind = classifyConflict(f, embeds);
569
+ const settled =
570
+ kind === "register"
571
+ ? registerResolve(top, f, "ours")
572
+ : kind === "embed"
573
+ ? embedResolve(top, f, embeds.get(f)!, "ours")
574
+ : kind === "record"
575
+ ? recordResolve(top, "ours")
576
+ : null;
577
+ if (settled !== null && !settled.ok)
578
+ return refuse(`REFUSE ${f} — ${settled.problem}`, f, settled.problem);
579
+ const ok =
580
+ settled !== null ||
581
+ (kind === "ledger" ? unionResolve(top, f).ok : lockfileResolve(top, f));
302
582
  if (!ok || !runGit(top, ["add", "--", f]).ok) {
303
583
  return refuse(`REFUSE ${f} — resolution failed`, f, "resolution failed");
304
584
  }
305
- result.resolved.push({ path: f, how: kind === "ledger" ? "union" : "lockfile" });
306
- log(
585
+ const how: Exclude<Resolution["how"], "dev"> =
307
586
  kind === "ledger"
308
- ? `RESOLVED ${f} — union (append-only ledger)`
309
- : `RESOLVED ${f} — took rebase target + regenerated`,
310
- );
587
+ ? "union"
588
+ : kind === "register" || kind === "embed" || kind === "record"
589
+ ? kind
590
+ : "lockfile";
591
+ result.resolved.push({ path: f, how });
592
+ log(`RESOLVED ${f} — ${REBASE_HOW[how]}`);
311
593
  }
312
594
  }
313
595
 
@@ -458,6 +740,7 @@ function openPrNumber(cwd: string, branch: string): number | null {
458
740
  {
459
741
  cwd,
460
742
  encoding: "utf-8",
743
+ maxBuffer: OUTPUT_LIMIT,
461
744
  },
462
745
  );
463
746
  const parsed = res.status === 0 ? parseJson(res.stdout ?? "") : { ok: false as const };
@@ -505,6 +788,7 @@ function rebaseVerb(ctx: RunContext): number {
505
788
  ctx.log("no rebase in progress");
506
789
  return EXIT_NO_REBASE;
507
790
  }
791
+ const origHead = rebaseOrigHead(top);
508
792
  const result = resolveRebase(top, (line) => ctx.log(line));
509
793
  let aborted = false;
510
794
  if (!result.ok) {
@@ -517,6 +801,19 @@ function rebaseVerb(ctx: RunContext): number {
517
801
  result.log.push(line);
518
802
  ctx.log(line);
519
803
  }
804
+ let rebuilt: boolean | null = null;
805
+ if (result.ok) {
806
+ const fid = currentBranch(top).replace(/^feat\//, "") || "rebase";
807
+ rebuilt = rebuildRegisters(
808
+ top,
809
+ result.resolved,
810
+ (files) => `chore(${fid}): rebuild ${files.join(" ")} after the rebase`,
811
+ (line) => {
812
+ result.log.push(line);
813
+ ctx.log(line);
814
+ },
815
+ );
816
+ }
520
817
  appendLog(ctx, str(ctx.flags.logFile), result.log);
521
818
  if (!result.ok && sentinelPath) {
522
819
  fs.mkdirSync(path.dirname(sentinelPath), { recursive: true });
@@ -531,10 +828,28 @@ function rebaseVerb(ctx: RunContext): number {
531
828
  reason: result.reason,
532
829
  aborted,
533
830
  sentinel: !result.ok && sentinel !== undefined ? sentinel : null,
831
+ rebuilt,
534
832
  });
833
+ const statusFile = str(ctx.flags.file);
834
+ if (result.ok && statusFile !== undefined)
835
+ recordRebase(path.resolve(ctx.cwd, statusFile), origHead, git(top, ["rev-parse", "HEAD"]));
535
836
  return result.ok ? EXIT.OK : EXIT_REFUSED;
536
837
  }
537
838
 
839
+ /** The branch tip the in-progress rebase started from. */
840
+ function rebaseOrigHead(top: string): string | null {
841
+ for (const dir of ["rebase-merge", "rebase-apply"]) {
842
+ const file = git(top, [
843
+ "rev-parse",
844
+ "--path-format=absolute",
845
+ "--git-path",
846
+ `${dir}/orig-head`,
847
+ ]);
848
+ if (file !== null && fs.existsSync(file)) return fs.readFileSync(file, "utf-8").trim();
849
+ }
850
+ return null;
851
+ }
852
+
538
853
  export interface PushOutcome {
539
854
  code: number;
540
855
  out: {
@@ -544,6 +859,31 @@ export interface PushOutcome {
544
859
  forced: boolean;
545
860
  skipped: string | null;
546
861
  prNumber: number | null;
862
+ /** The run's commits went out as copies cherry-picked onto a fresh origin/dev. */
863
+ replayed: boolean;
864
+ /** origin/dev's docs and ledger commits were merged in before the push. */
865
+ mergedDev: boolean;
866
+ lockHolder?: string | null;
867
+ };
868
+ }
869
+
870
+ /** Git collapses a failing pre-push hook's status; classify its exact tests-lock markers. */
871
+ function runPush(cwd: string, args: string[], branch: string) {
872
+ const who = `bkit branches push ${branch}`;
873
+ const wait = wholeNumber(process.env.BKIT_LOCK_WAIT_S, "BKIT_LOCK_WAIT_S", 60);
874
+ const res = runGit(cwd, args, {
875
+ LOCAL_STACK_LOCK_WAIT_S: String(wait),
876
+ LOCAL_STACK_LOCK_WHO: who,
877
+ });
878
+ const log = [res.stdout, res.stderr].filter(Boolean).join("\n");
879
+ const lockHolder = res.ok ? null : testsLockHolder(log, who);
880
+ const outcome = res.ok
881
+ ? "gate"
882
+ : classifyLockExit({ exitCode: lockHolder === null ? 73 : 75, log, who });
883
+ return {
884
+ ...res,
885
+ lockHolder,
886
+ lockExit: outcome === "lock-wait" ? EXIT.AGENT_WAIT : outcome === "could-not-run" ? 4 : null,
547
887
  };
548
888
  }
549
889
 
@@ -551,17 +891,24 @@ export interface PushOutcome {
551
891
  * Push the current branch with exactly one `git push`: plain for dev / main,
552
892
  * `--force-with-lease` otherwise. `abort` never pushes into an open PR (`openPr`:
553
893
  * the answer MCP gave; undefined asks gh, which throws EXIT.USE_MCP when it cannot).
894
+ * An in-place run on dev (a shared-checkout record exists) pushes only the
895
+ * commits it made: plain when they are all that local dev holds beyond
896
+ * origin/dev, else replayed onto a fresh origin/dev through `pushToDev`.
554
897
  */
555
- export function pushBranch(
898
+ export async function pushBranch(
556
899
  cwd: string,
557
900
  o: {
558
- mode: "feature" | "abort" | "dev";
901
+ mode: "feature" | "abort" | "dev" | "plain";
559
902
  setUpstream?: boolean;
903
+ /** --mode=plain: refuse when HEAD has no commits beyond this ref (fetched first when origin/<b>). */
904
+ aheadOf?: string;
560
905
  requireCi?: boolean;
561
906
  openPr?: string;
907
+ /** The in-place run's FID: selects its shared-checkout record, and a missing record refuses the push. */
908
+ fid?: string;
562
909
  },
563
910
  log: (m: string) => void,
564
- ): PushOutcome {
911
+ ): Promise<PushOutcome> {
565
912
  const { mode, openPr: openPrFlag } = o;
566
913
  if (openPrFlag !== undefined && openPrFlag !== "none" && !/^[1-9][0-9]*$/.test(openPrFlag)) {
567
914
  throw new CommandError(
@@ -579,6 +926,8 @@ export function pushBranch(
579
926
  forced: false,
580
927
  skipped: null,
581
928
  prNumber: null,
929
+ replayed: false,
930
+ mergedDev: false,
582
931
  ...extra,
583
932
  },
584
933
  });
@@ -590,8 +939,24 @@ export function pushBranch(
590
939
  log(`--mode=dev pushes ${DEV}, but the checkout is on ${branch}`);
591
940
  return notPushed(EXIT_NOT_DEV);
592
941
  }
942
+ if (mode === "plain") return pushPlain(cwd, branch, o, log, notPushed);
943
+ const shared = isSharedBranch(branch);
944
+ const rec = !shared
945
+ ? null
946
+ : o.fid === undefined
947
+ ? recordOnBranch(cwd, branch)
948
+ : activeRecord(cwd, o.fid);
949
+ // Without the run's record the push would carry all of local dev, not the run's commits.
950
+ if (shared && rec === null && (mode === "dev" || o.fid !== undefined)) {
951
+ log(
952
+ `no shared-checkout record${o.fid === undefined ? "" : ` for ${o.fid}`} on ${branch} — refusing to push: it would carry commits the run does not own`,
953
+ );
954
+ return notPushed(EXIT_NO_RECORD);
955
+ }
593
956
  if (o.requireCi === true) {
594
- const message = git(cwd, ["log", "-1", "--pretty=%B"]) ?? "";
957
+ // With a record, the commit that reaches the remote last is the run's own.
958
+ const last = rec?.commits.at(-1) ?? "HEAD";
959
+ const message = git(cwd, ["log", "-1", "--pretty=%B", last]) ?? "";
595
960
  if (SKIP_CI_TOKEN.test(message)) {
596
961
  log(
597
962
  `HEAD message on ${branch} carries a CI-suppressing token, and this push needs a CI run — refusing`,
@@ -599,7 +964,19 @@ export function pushBranch(
599
964
  return notPushed(EXIT_SKIP_CI, { skipped: "skip-ci" });
600
965
  }
601
966
  }
602
- const shared = isSharedBranch(branch);
967
+ if (rec !== null) return pushOwnCommits(cwd, rec, o, log, notPushed);
968
+ let mergedDev = false;
969
+ if (mode === "feature" && o.requireCi === true && !shared) {
970
+ const top = topLevel(cwd);
971
+ const fetched = fetchDev(top);
972
+ if (!fetched.ok) {
973
+ log(`git fetch ${REMOTE} ${DEV} failed: ${fetched.stderr}`);
974
+ return notPushed(EXIT_FETCH_FAILED);
975
+ }
976
+ const m = mergeDevDocs(top, { branch, generate: true }, log);
977
+ if (m.code !== EXIT.OK) return notPushed(m.code, { mergedDev: m.merged });
978
+ mergedDev = m.merged;
979
+ }
603
980
  if (mode === "abort" && !shared) {
604
981
  const pr =
605
982
  openPrFlag === undefined
@@ -621,10 +998,10 @@ export function pushBranch(
621
998
  REMOTE,
622
999
  branch,
623
1000
  ];
624
- const res = runGit(cwd, args);
1001
+ const res = runPush(cwd, args, branch);
625
1002
  if (!res.ok) {
626
1003
  log(`git ${args.join(" ")} failed: ${res.stderr}`);
627
- return notPushed(EXIT_PUSH_FAILED);
1004
+ return notPushed(res.lockExit ?? EXIT_PUSH_FAILED, { lockHolder: res.lockHolder });
628
1005
  }
629
1006
  log(`pushed ${branch}${shared ? "" : " (--force-with-lease)"}`);
630
1007
  return {
@@ -636,65 +1013,1335 @@ export function pushBranch(
636
1013
  forced: !shared,
637
1014
  skipped: null,
638
1015
  prNumber: null,
1016
+ replayed: false,
1017
+ mergedDev,
1018
+ },
1019
+ };
1020
+ }
1021
+
1022
+ /**
1023
+ * `git fetch` of `ref` when it names a branch of origin (`origin/<b>`); null when
1024
+ * it names anything else (a SHA, a local branch), which needs no fetch.
1025
+ */
1026
+ export function fetchRemoteRef(cwd: string, ref: string): { ok: boolean; stderr: string } | null {
1027
+ const m = new RegExp(`^${REMOTE}/(.+)$`).exec(ref);
1028
+ if (!m) return null;
1029
+ return runGit(cwd, ["fetch", REMOTE, `+refs/heads/${m[1]}:refs/remotes/${REMOTE}/${m[1]}`]);
1030
+ }
1031
+
1032
+ /** Commits HEAD holds beyond `ref`; 0 when the count cannot be read. */
1033
+ function commitsAhead(cwd: string, ref: string): number {
1034
+ const n = Number(git(cwd, ["rev-list", "--count", `${ref}..HEAD`]) ?? "0");
1035
+ return Number.isFinite(n) ? n : 0;
1036
+ }
1037
+
1038
+ /**
1039
+ * `--mode=plain`: one `git push [-u] origin <branch>`, never forced. A feature
1040
+ * branch only: dev / main and a branch with nothing beyond `aheadOf` have nothing to ship.
1041
+ */
1042
+ function pushPlain(
1043
+ cwd: string,
1044
+ branch: string,
1045
+ o: { setUpstream?: boolean; aheadOf?: string; requireCi?: boolean },
1046
+ log: (m: string) => void,
1047
+ notPushed: (code: number, extra?: Partial<PushOutcome["out"]>) => PushOutcome,
1048
+ ): PushOutcome {
1049
+ if (isSharedBranch(branch)) {
1050
+ log(`Nothing to ship: on '${branch}', no feature branch`);
1051
+ return notPushed(EXIT_NOTHING_TO_PUSH);
1052
+ }
1053
+ if (o.aheadOf !== undefined) {
1054
+ const fetched = fetchRemoteRef(cwd, o.aheadOf);
1055
+ if (fetched !== null && !fetched.ok) {
1056
+ log(`git fetch for ${o.aheadOf} failed: ${fetched.stderr} — counting against the local ref`);
1057
+ }
1058
+ if (commitsAhead(cwd, o.aheadOf) === 0) {
1059
+ log(`Nothing to ship: ${branch} has no commits ahead of ${o.aheadOf}`);
1060
+ return notPushed(EXIT_NOTHING_TO_PUSH);
1061
+ }
1062
+ }
1063
+ if (o.requireCi === true && SKIP_CI_TOKEN.test(git(cwd, ["log", "-1", "--pretty=%B"]) ?? "")) {
1064
+ log(
1065
+ `HEAD message on ${branch} carries a CI-suppressing token, and this push needs a CI run — refusing`,
1066
+ );
1067
+ return notPushed(EXIT_SKIP_CI, { skipped: "skip-ci" });
1068
+ }
1069
+ const args = ["push", ...(o.setUpstream === true ? ["-u"] : []), REMOTE, branch];
1070
+ const res = runPush(cwd, args, branch);
1071
+ if (!res.ok) {
1072
+ log(`git ${args.join(" ")} failed: ${res.stderr}`);
1073
+ return notPushed(res.lockExit ?? EXIT_PUSH_FAILED, { lockHolder: res.lockHolder });
1074
+ }
1075
+ log(`pushed ${branch}`);
1076
+ return {
1077
+ code: EXIT.OK,
1078
+ out: {
1079
+ pushed: true,
1080
+ ref: branch,
1081
+ sha: git(cwd, ["rev-parse", "HEAD"]),
1082
+ forced: false,
1083
+ skipped: null,
1084
+ prNumber: null,
1085
+ replayed: false,
1086
+ mergedDev: false,
1087
+ },
1088
+ };
1089
+ }
1090
+
1091
+ /**
1092
+ * The `key` of an engine-action row for a marker commit this run makes: keyed on the
1093
+ * workflow's latest run, in progress or just closed by `workflows close`.
1094
+ */
1095
+ function markerKey(file: string, workflow: string, what: string): string {
1096
+ const runs = fs.existsSync(file) ? readRuns(file).filter((r) => r.workflow === workflow) : [];
1097
+ return actionKey(workflow, Math.max(runs.length, 1), what);
1098
+ }
1099
+
1100
+ /**
1101
+ * Make a marker commit once per run: an engine-action row with the same key and
1102
+ * message whose commit is still on HEAD means it is already made (`deduped`).
1103
+ * `addAll` stages every change first (`git add -A`); the commit is always
1104
+ * allowed to be empty. The row is written before the caller pushes.
1105
+ */
1106
+ function markerCommit(
1107
+ cwd: string,
1108
+ o: { file: string; key: string; message: string; addAll: boolean },
1109
+ ): { sha: string; deduped: boolean } {
1110
+ const hash = actionHash(o.message);
1111
+ const prior = alreadyDone(o.file, o.key, hash);
1112
+ if (prior?.ref && runGit(cwd, ["merge-base", "--is-ancestor", prior.ref, "HEAD"]).ok) {
1113
+ return { sha: prior.ref, deduped: true };
1114
+ }
1115
+ if (o.addAll) {
1116
+ const added = addAllButCopied(cwd);
1117
+ if (!added.ok) throw new CommandError(EXIT_PUSH_FAILED, `git add -A failed: ${added.stderr}`);
1118
+ }
1119
+ const made = runGit(cwd, ["commit", "--allow-empty", "-m", o.message]);
1120
+ if (!made.ok) {
1121
+ throw new CommandError(EXIT_PUSH_FAILED, `git commit failed: ${made.stderr || made.stdout}`);
1122
+ }
1123
+ const sha = git(cwd, ["rev-parse", "HEAD"]) ?? "";
1124
+ recordAction(o.file, { action: "commit", key: o.key, hash, ref: sha });
1125
+ return { sha, deduped: false };
1126
+ }
1127
+
1128
+ const autoRouteSuffix = (labels: string[]) =>
1129
+ labels.includes(AUTO_LABEL) ? AUTO_ROUTE_SUFFIX : "";
1130
+
1131
+ /** A replayed commit that does not apply onto origin/dev without the foreign commits it builds on. */
1132
+ class ReplayConflict extends Error {}
1133
+
1134
+ /**
1135
+ * The `pushToDev` build callback that replays `shas` (oldest first) onto the
1136
+ * fresh origin/dev in `dir`, each as a cherry-pick that keeps its message and
1137
+ * author and keeps empty commits. A commit that does not apply throws a
1138
+ * ReplayConflict naming the conflicting paths, after aborting the cherry-pick.
1139
+ */
1140
+ export function replayBuild(shas: string[]): (dir: string) => void {
1141
+ return (dir) => {
1142
+ for (const sha of shas) {
1143
+ const picked = runGit(dir, ["cherry-pick", "--allow-empty", "--keep-redundant-commits", sha]);
1144
+ if (picked.ok) continue;
1145
+ const paths = (git(dir, ["diff", "--name-only", "--diff-filter=U"]) ?? "")
1146
+ .split("\n")
1147
+ .filter(Boolean);
1148
+ runGit(dir, ["cherry-pick", "--abort"]);
1149
+ throw new ReplayConflict(
1150
+ `commit ${sha.slice(0, 12)} does not apply onto ${UPSTREAM} without the local ${DEV} commits it builds on — ${
1151
+ paths.length > 0 ? `conflicts in: ${paths.join(", ")}` : picked.stderr
1152
+ }`,
1153
+ );
1154
+ }
1155
+ };
1156
+ }
1157
+
1158
+ /**
1159
+ * Push only the commits an in-place run on dev made (the record's `commits`).
1160
+ * Plain push of their tip SHA when origin/dev is an ancestor of local dev and they
1161
+ * are exactly what local dev holds beyond it; otherwise (a foreign commit among
1162
+ * them, origin/dev moved, or the plain push is rejected) they are replayed onto a
1163
+ * fresh origin/dev in the throwaway checkout and pushed from there.
1164
+ */
1165
+ async function pushOwnCommits(
1166
+ cwd: string,
1167
+ rec: SharedCheckoutRecord,
1168
+ o: { setUpstream?: boolean },
1169
+ log: (m: string) => void,
1170
+ notPushed: (code: number, extra?: Partial<PushOutcome["out"]>) => PushOutcome,
1171
+ ): Promise<PushOutcome> {
1172
+ const gone = rec.commits.filter(
1173
+ (c) => !runGit(cwd, ["merge-base", "--is-ancestor", c, "HEAD"]).ok,
1174
+ );
1175
+ if (gone.length > 0) {
1176
+ log(
1177
+ `the run's commit(s) ${gone.map((c) => c.slice(0, 12)).join(", ")} are no longer on ${rec.branch} — refusing to push`,
1178
+ );
1179
+ return notPushed(EXIT_PUSH_FAILED);
1180
+ }
1181
+ const fetched = fetchDev(cwd);
1182
+ if (!fetched.ok) {
1183
+ log(`git fetch ${REMOTE} ${DEV} failed: ${fetched.stderr}`);
1184
+ return notPushed(EXIT_FETCH_FAILED);
1185
+ }
1186
+ // Oldest first, minus what origin/dev already has (pushed plain before) and
1187
+ // what an earlier replay already landed.
1188
+ const mine = new Set(rec.commits);
1189
+ const landed = new Set(rec.pushed ?? []);
1190
+ const range = runGit(cwd, ["rev-parse", "-q", "--verify", `${rec.startSha}^{commit}`]).ok
1191
+ ? `${rec.startSha}..HEAD`
1192
+ : "HEAD";
1193
+ const pending = (git(cwd, ["rev-list", "--reverse", range]) ?? "")
1194
+ .split("\n")
1195
+ .filter(
1196
+ (c) =>
1197
+ mine.has(c) &&
1198
+ !landed.has(c) &&
1199
+ !runGit(cwd, ["merge-base", "--is-ancestor", c, UPSTREAM]).ok,
1200
+ );
1201
+ if (pending.length === 0) {
1202
+ log("every commit the run made is already on origin/dev — nothing to push");
1203
+ return notPushed(EXIT.OK, { skipped: "no-run-commits" });
1204
+ }
1205
+ const ahead = (git(cwd, ["rev-list", "--reverse", `${UPSTREAM}..HEAD`]) ?? "")
1206
+ .split("\n")
1207
+ .filter(Boolean);
1208
+ // Plain only when origin/dev is an ancestor of local dev (a fast-forward) and
1209
+ // the run's commits are all local dev holds beyond it; the explicit SHA keeps
1210
+ // a commit made after the check out of the push.
1211
+ const fastForward = runGit(cwd, ["merge-base", "--is-ancestor", UPSTREAM, "HEAD"]).ok;
1212
+ if (fastForward && ahead.length === pending.length && ahead.every((c, i) => c === pending[i])) {
1213
+ const last = pending[pending.length - 1];
1214
+ const args = [
1215
+ "push",
1216
+ ...(o.setUpstream === true ? ["-u"] : []),
1217
+ REMOTE,
1218
+ `${last}:refs/heads/${rec.branch}`,
1219
+ ];
1220
+ const res = runPush(cwd, args, rec.branch);
1221
+ if (res.ok) {
1222
+ log(`pushed ${rec.branch}: the run's ${pending.length} commit(s) are all local dev holds`);
1223
+ return {
1224
+ code: EXIT.OK,
1225
+ out: {
1226
+ pushed: true,
1227
+ ref: rec.branch,
1228
+ sha: last,
1229
+ forced: false,
1230
+ skipped: null,
1231
+ prNumber: null,
1232
+ replayed: false,
1233
+ mergedDev: false,
1234
+ },
1235
+ };
1236
+ }
1237
+ if (res.lockExit !== null) {
1238
+ log(`git ${args.join(" ")} failed: ${res.stderr}`);
1239
+ return notPushed(res.lockExit, { lockHolder: res.lockHolder });
1240
+ }
1241
+ log(`git ${args.join(" ")} failed: ${res.stderr} — replaying onto a fresh ${UPSTREAM}`);
1242
+ }
1243
+
1244
+ const root = repoRoot(cwd);
1245
+ let res: Awaited<ReturnType<typeof pushToDev>>;
1246
+ try {
1247
+ res = await pushToDev({
1248
+ root,
1249
+ dir: landDir(root, rec.fid),
1250
+ build: replayBuild(pending),
1251
+ log,
1252
+ });
1253
+ } catch (err) {
1254
+ if (!(err instanceof ReplayConflict)) throw err;
1255
+ log(`replaying the run's commits onto ${UPSTREAM} stopped: ${err.message}`);
1256
+ return notPushed(EXIT_MERGE_CONFLICT);
1257
+ }
1258
+ switch (res.kind) {
1259
+ case "landed":
1260
+ markRecordPushed(cwd, rec.fid, pending);
1261
+ log(
1262
+ `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}`,
1263
+ );
1264
+ return {
1265
+ code: EXIT.OK,
1266
+ out: {
1267
+ pushed: true,
1268
+ ref: rec.branch,
1269
+ sha: res.sha,
1270
+ forced: false,
1271
+ skipped: null,
1272
+ prNumber: null,
1273
+ replayed: true,
1274
+ mergedDev: false,
1275
+ },
1276
+ };
1277
+ case "refused":
1278
+ log(`${DEV} refused the push: ${res.stderr}`);
1279
+ return notPushed(EXIT_PUSH_FAILED);
1280
+ case "push-failed":
1281
+ log(`push to ${DEV} failed without a server answer: ${res.stderr}`);
1282
+ return notPushed(EXIT_PUSH_FAILED);
1283
+ case "exhausted":
1284
+ log(`${DEV} moved before each of ${res.attempts} pushes`);
1285
+ return notPushed(EXIT_PUSH_FAILED);
1286
+ case "fetch-failed":
1287
+ log(`git fetch ${REMOTE} ${DEV} failed: ${res.stderr}`);
1288
+ return notPushed(EXIT_FETCH_FAILED);
1289
+ case "setup-failed":
1290
+ log(`throwaway checkout failed: ${res.stderr}`);
1291
+ return notPushed(EXIT_PUSH_FAILED);
1292
+ }
1293
+ }
1294
+
1295
+ async function pushVerb(ctx: RunContext): Promise<number> {
1296
+ const mode = String(ctx.flags.mode);
1297
+ if (!["feature", "abort", "dev", "plain"].includes(mode)) {
1298
+ throw new CommandError(EXIT.USAGE, "--mode must be feature, abort, dev, or plain");
1299
+ }
1300
+ const aheadOf = str(ctx.flags.aheadOf);
1301
+ if (aheadOf !== undefined && mode !== "plain") {
1302
+ throw new CommandError(EXIT.USAGE, "--ahead-of applies to --mode=plain only");
1303
+ }
1304
+ const commitMessage = str(ctx.flags.commit);
1305
+ let marker: { sha: string; deduped: boolean } | undefined;
1306
+ if (commitMessage !== undefined) {
1307
+ const file = str(ctx.flags.file);
1308
+ const workflow = str(ctx.flags.workflow);
1309
+ if (mode !== "feature" || file === undefined || workflow === undefined) {
1310
+ throw new CommandError(
1311
+ EXIT.USAGE,
1312
+ "--commit needs --mode=feature, --file (status.jsonl) and --workflow",
1313
+ );
1314
+ }
1315
+ const branch = currentBranch(ctx.cwd);
1316
+ if (branch === "") {
1317
+ ctx.log("no branch checked out (detached HEAD) — refusing to commit and push");
1318
+ return EXIT_DETACHED;
1319
+ }
1320
+ if (isSharedBranch(branch)) {
1321
+ ctx.log(
1322
+ `Nothing to ship: --commit makes a marker commit on a feature branch, not '${branch}'`,
1323
+ );
1324
+ return EXIT_NOTHING_TO_PUSH;
1325
+ }
1326
+ const message = `${commitMessage}${autoRouteSuffix((ctx.flags.label as string[] | undefined) ?? [])}`;
1327
+ if (ctx.flags.requireCi === true && SKIP_CI_TOKEN.test(message)) {
1328
+ ctx.log(
1329
+ "the --commit message carries a CI-suppressing token, and this push needs a CI run — refusing",
1330
+ );
1331
+ ctx.emit({
1332
+ pushed: false,
1333
+ ref: null,
1334
+ sha: null,
1335
+ forced: false,
1336
+ skipped: "skip-ci",
1337
+ prNumber: null,
1338
+ replayed: false,
1339
+ mergedDev: false,
1340
+ });
1341
+ return EXIT_SKIP_CI;
1342
+ }
1343
+ marker = markerCommit(ctx.cwd, {
1344
+ file: path.resolve(ctx.cwd, file),
1345
+ key: markerKey(path.resolve(ctx.cwd, file), workflow, "push-commit"),
1346
+ message,
1347
+ addAll: true,
1348
+ });
1349
+ if (marker.deduped)
1350
+ ctx.log(`marker commit ${marker.sha.slice(0, 12)} already made this run — pushing it`);
1351
+ }
1352
+ const r = await pushBranch(
1353
+ ctx.cwd,
1354
+ {
1355
+ mode: mode as "feature" | "abort" | "dev" | "plain",
1356
+ setUpstream: ctx.flags.setUpstream === true,
1357
+ aheadOf,
1358
+ requireCi: ctx.flags.requireCi === true,
1359
+ openPr: str(ctx.flags.openPr),
1360
+ fid: str(ctx.flags.fid),
639
1361
  },
1362
+ ctx.log,
1363
+ );
1364
+ // A detached HEAD and a wrong checkout print nothing, as the push never got to run.
1365
+ if (r.code !== EXIT_DETACHED && r.code !== EXIT_NOT_DEV) {
1366
+ ctx.emit(
1367
+ marker === undefined
1368
+ ? { lockHolder: null, ...r.out }
1369
+ : { lockHolder: null, ...r.out, commit: marker.sha, deduped: marker.deduped },
1370
+ );
1371
+ }
1372
+ return r.code;
1373
+ }
1374
+
1375
+ function fastForwardVerb(ctx: RunContext): number {
1376
+ const onto = String(ctx.flags.onto);
1377
+ const top = topLevel(ctx.cwd);
1378
+ const fetched = fetchRemoteRef(top, onto);
1379
+ if (fetched !== null && !fetched.ok) {
1380
+ ctx.log(`git fetch for ${onto} failed: ${fetched.stderr}`);
1381
+ return EXIT_FETCH_FAILED;
1382
+ }
1383
+ if (!runGit(top, ["rev-parse", "-q", "--verify", `${onto}^{commit}`]).ok) {
1384
+ ctx.log(`unknown ref: ${onto}`);
1385
+ return EXIT_FETCH_FAILED;
1386
+ }
1387
+ const before = git(top, ["rev-parse", "HEAD"]);
1388
+ if (runGit(top, ["merge-base", "--is-ancestor", onto, "HEAD"]).ok) {
1389
+ ctx.emit({ moved: false, head: before });
1390
+ return EXIT.OK;
1391
+ }
1392
+ const merged = runGit(top, ["merge", "--ff-only", onto]);
1393
+ if (!merged.ok) {
1394
+ ctx.log(`local ${currentBranch(top) || "HEAD"} diverged from ${onto} — reconcile, then re-run`);
1395
+ return EXIT_DIVERGED;
1396
+ }
1397
+ const head = git(top, ["rev-parse", "HEAD"]);
1398
+ ctx.log(`fast-forwarded onto ${onto} (${head?.slice(0, 12) ?? ""})`);
1399
+ ctx.emit({ moved: head !== before, head });
1400
+ return EXIT.OK;
1401
+ }
1402
+
1403
+ /** Paths a source-change check leaves out: plan logs and the append-only ledgers. */
1404
+ const NOT_CODE = [":(exclude)docs/plans", ":(exclude)docs/*.jsonl", ":(exclude).bkit/*.jsonl"];
1405
+
1406
+ /** One added line that disables a test, or removes one of its assertions. */
1407
+ export interface DisabledTest {
1408
+ file: string;
1409
+ /** 1-based line in the new file, or in the old one when the diff deletes the file. */
1410
+ line: number;
1411
+ /** The test it sits in, else the marker line's own text. */
1412
+ test: string;
1413
+ }
1414
+
1415
+ /** A test file's name at any tier: unit, integration, E2E. */
1416
+ const TEST_FILE = /\.(?:test|spec)\.|_test\.|(^|\/)test_[^/]*\.py$/;
1417
+
1418
+ /** Added-line markers that disable a test: `bkit-slop-type-suppression.mjs`'s set, widened. */
1419
+ const MARKERS = [
1420
+ /\b(?:describe|context|it|test|suite|bench)\.(?:skip|todo|fixme)\b/,
1421
+ /(?<!\.)\bx(?:it|describe|test|context)\s*\(/,
1422
+ /\bxfail\b/,
1423
+ /\bt\.Skip\(/,
1424
+ /#\[ignore\b/,
1425
+ /@Disabled\b/,
1426
+ /@pytest\.mark\.skip\b/,
1427
+ /@unittest\.skip\b/,
1428
+ /\.skip\s*\(/,
1429
+ ];
1430
+
1431
+ /** The markers that apply to an added line of `file`: only a test file carries them. */
1432
+ const markersFor = (file: string) => (TEST_FILE.test(file) ? MARKERS : []);
1433
+
1434
+ /** A quoted span: a marker inside it is prose or a fixture string, not a call. */
1435
+ const QUOTED = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g;
1436
+
1437
+ /** A line's trailing comment (`#` is one unless it opens a Rust or C attribute). */
1438
+ const COMMENT_TAIL = /(?:^|\s)(?:\/\/|#(?!\[))/;
1439
+
1440
+ /** A line that opens or continues a block comment. */
1441
+ const BLOCK_COMMENT = /^\s*(?:\/\*|\*)/;
1442
+
1443
+ /** `line` with its quoted spans and comment removed — the part a marker can be a call in. */
1444
+ function stripProse(line: string): string {
1445
+ if (BLOCK_COMMENT.test(line)) return "";
1446
+ const code = line.replace(QUOTED, '""');
1447
+ const cut = code.search(COMMENT_TAIL);
1448
+ return cut === -1 ? code : code.slice(0, cut);
1449
+ }
1450
+
1451
+ /** An assertion call a change deletes from a test file: `expect(…)`, `assert.equal(…)`, `should(…)`. */
1452
+ const ASSERTION = /(?<![\w$])(?:expect|assert\w*|should_\w+|should)\s*[(.]/;
1453
+
1454
+ /** Python's bare `assert x` statement, which calls nothing but asserts. */
1455
+ const BARE_ASSERT = /^\s*assert\s+\S/;
1456
+
1457
+ /** A commented-out line: its words are prose, not a call. */
1458
+ const COMMENT = /^\s*(?:\/\/|\/\*|\*|#|--)/;
1459
+
1460
+ /** True when a removed `line` takes an assertion, rather than being a comment or an import. */
1461
+ const isAssertion = (line: string) =>
1462
+ !COMMENT.test(line) && (ASSERTION.test(line) || BARE_ASSERT.test(line));
1463
+
1464
+ /** The test at 1-based `at` in `body`: the nearest declaration above it, else `line` itself. */
1465
+ function testAt(body: string | null, line: string, at: number): string {
1466
+ if (body !== null) {
1467
+ const lines = body.split(/\r?\n/);
1468
+ const from = Math.min(at, lines.length) - 1;
1469
+ // A decorator (`@pytest.mark.skip`) names the test it sits on, which is below it.
1470
+ if (line.trimStart().startsWith("@")) {
1471
+ for (let i = from + 1; i < lines.length; i++) {
1472
+ const name = declaredName(lines[i]!);
1473
+ if (name !== null) return name;
1474
+ }
1475
+ }
1476
+ for (let i = from; i >= 0; i--) {
1477
+ const name = declaredName(lines[i]!);
1478
+ if (name !== null) return name;
1479
+ }
1480
+ }
1481
+ return line.trim();
1482
+ }
1483
+
1484
+ const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
1485
+
1486
+ /**
1487
+ * The text of the regular file `rel` names under `root`, or null when it is missing, a
1488
+ * symlink, or resolves outside `root` — so a diff path never opens a file the repo does not hold.
1489
+ */
1490
+ function inRepoFile(root: string, rel: string): string | null {
1491
+ const abs = path.resolve(root, rel);
1492
+ const inside = (base: string, p: string) => {
1493
+ const r = path.relative(base, p);
1494
+ return r !== "" && !r.startsWith("..") && !path.isAbsolute(r);
1495
+ };
1496
+ if (!inside(root, abs)) return null;
1497
+ const stat = fs.lstatSync(abs, { throwIfNoEntry: false });
1498
+ if (stat === undefined || stat.isSymbolicLink() || !stat.isFile()) return null;
1499
+ // A symlinked parent directory can still lead outside the repo.
1500
+ if (!inside(fs.realpathSync(root), fs.realpathSync(abs))) return null;
1501
+ return fs.readFileSync(abs, "utf-8");
1502
+ }
1503
+
1504
+ /**
1505
+ * Unmatched disabled markers and removed assertion occurrences in a unified diff.
1506
+ * Exact moves consume one added occurrence; cross-file moves require unchanged test context.
1507
+ * Rewritten assertions pair only inside the same file and test. Removed lines retain their
1508
+ * original test name; a deleted file uses old line numbers, otherwise the new hunk position.
1509
+ */
1510
+ export function disabledTestsIn(diff: string, root: string): DisabledTest[] {
1511
+ const out: DisabledTest[] = [];
1512
+ const bodies = new Map<string, string | null>();
1513
+ const body = (rel: string) => {
1514
+ if (!bodies.has(rel)) bodies.set(rel, inRepoFile(root, rel));
1515
+ return bodies.get(rel)!;
1516
+ };
1517
+ type Occurrence = DisabledTest & { text: string };
1518
+ type Removed = { file: string; line: number; old: number; text: string };
1519
+ type Hunk = { start: number; count: number; lines: string[] };
1520
+ const added: Occurrence[] = [];
1521
+ const removed: Removed[] = [];
1522
+ const addedMarkers: Occurrence[] = [];
1523
+ const removedMarkers: Removed[] = [];
1524
+ const patches = new Map<string, Hunk[]>();
1525
+ let file = "";
1526
+ let from = "";
1527
+ let deleted = false;
1528
+ let current: Hunk | undefined;
1529
+ let next = 0;
1530
+ let old = 0;
1531
+ for (const raw of diff.split("\n")) {
1532
+ if (raw.startsWith("diff --git ")) {
1533
+ current = undefined;
1534
+ file = "";
1535
+ continue;
1536
+ }
1537
+ if (raw.startsWith("--- ")) {
1538
+ from = raw.replace(/^--- (a\/)?/, "");
1539
+ continue;
1540
+ }
1541
+ if (raw.startsWith("+++ ")) {
1542
+ const plus = raw.replace(/^\+\+\+ (b\/)?/, "");
1543
+ file = plus === "/dev/null" ? from : plus;
1544
+ deleted = plus === "/dev/null";
1545
+ continue;
1546
+ }
1547
+ const hunk = HUNK.exec(raw);
1548
+ if (hunk !== null) {
1549
+ old = Number(hunk[1]);
1550
+ next = Number(hunk[3]);
1551
+ current = { start: next, count: Number(hunk[4] ?? 1), lines: [] };
1552
+ const hunks = patches.get(file) ?? [];
1553
+ hunks.push(current);
1554
+ patches.set(file, hunks);
1555
+ continue;
1556
+ }
1557
+ if (current === undefined) continue;
1558
+ if (raw.startsWith("+")) {
1559
+ const text = raw.slice(1);
1560
+ if (TEST_FILE.test(file)) {
1561
+ const occurrence = { file, line: next, text, test: testAt(body(file), text, next) };
1562
+ if (markersFor(file).some((m) => m.test(stripProse(text)))) addedMarkers.push(occurrence);
1563
+ if (isAssertion(text)) added.push(occurrence);
1564
+ }
1565
+ next++;
1566
+ } else if (raw.startsWith("-")) {
1567
+ const text = raw.slice(1);
1568
+ current.lines.push(text);
1569
+ if (TEST_FILE.test(file)) {
1570
+ const occurrence = { file, line: deleted ? old : next, old, text };
1571
+ if (isAssertion(text)) removed.push(occurrence);
1572
+ if (markersFor(file).some((m) => m.test(stripProse(text)))) removedMarkers.push(occurrence);
1573
+ }
1574
+ old++;
1575
+ } else if (raw.startsWith(" ")) {
1576
+ current.lines.push(raw.slice(1));
1577
+ next++;
1578
+ old++;
1579
+ }
1580
+ }
1581
+ const oldBodies = new Map<string, string>();
1582
+ const original = (r: Removed): Occurrence => {
1583
+ if (!oldBodies.has(r.file)) {
1584
+ const lines = body(r.file)?.split(/\r?\n/) ?? [];
1585
+ for (const hunk of [...(patches.get(r.file) ?? [])].reverse())
1586
+ lines.splice(Math.max(0, hunk.start - 1), hunk.count, ...hunk.lines);
1587
+ oldBodies.set(r.file, lines.join("\n"));
1588
+ }
1589
+ return { ...r, test: testAt(oldBodies.get(r.file)!, r.text, r.old) };
1590
+ };
1591
+ const contexts = new Map<string, string | null>();
1592
+ const context = (occurrence: Occurrence, before: boolean) => {
1593
+ const key = JSON.stringify([before, occurrence.file, occurrence.test]);
1594
+ if (!contexts.has(key)) {
1595
+ const source = before ? oldBodies.get(occurrence.file) : body(occurrence.file);
1596
+ const lines = source == null ? null : testSource(source, occurrence.test);
1597
+ contexts.set(
1598
+ key,
1599
+ lines === null
1600
+ ? null
1601
+ : lines
1602
+ .filter((line) => stripProse(line).trim() !== "" && !isAssertion(stripProse(line)))
1603
+ .map((line) =>
1604
+ line
1605
+ .trim()
1606
+ .replace(
1607
+ /\b(it|test|suite|describe|context|bench)\.(?:skip|todo|fixme)\b/g,
1608
+ "$1",
1609
+ ),
1610
+ )
1611
+ .join("\n"),
1612
+ );
1613
+ }
1614
+ return contexts.get(key)!;
1615
+ };
1616
+ const exact = (a: Occurrence, b: Occurrence) =>
1617
+ a.text.trim() === b.text.trim() &&
1618
+ (a.file === b.file ||
1619
+ (a.test === b.test && context(a, true) !== null && context(a, true) === context(b, false)));
1620
+ const consume = (available: Occurrence[], occurrence: Occurrence, match = exact) => {
1621
+ const index = available.findIndex((candidate) => match(occurrence, candidate));
1622
+ if (index === -1) return false;
1623
+ available.splice(index, 1);
1624
+ return true;
640
1625
  };
1626
+ for (const r of removedMarkers)
1627
+ consume(
1628
+ addedMarkers,
1629
+ original(r),
1630
+ (a, b) =>
1631
+ exact(a, b) &&
1632
+ a.test === b.test &&
1633
+ context(a, true) !== null &&
1634
+ context(a, true) === context(b, false),
1635
+ );
1636
+ const drops = removed.map(original).filter((r) => !consume(added, r));
1637
+ for (const r of drops)
1638
+ if (!consume(added, r, (a, b) => a.file === b.file && a.test === b.test))
1639
+ out.push({ file: r.file, line: r.line, test: r.test });
1640
+ out.unshift(...addedMarkers.map(({ file, line, test }) => ({ file, line, test })));
1641
+ return out;
1642
+ }
1643
+
1644
+ function scanDiffVerb(ctx: RunContext): number {
1645
+ const base = String(ctx.flags.base);
1646
+ const pattern = str(ctx.flags.paths);
1647
+ const marker = str(ctx.flags.marker);
1648
+ const code = ctx.flags.code === true;
1649
+ const disabled = ctx.flags.disabledTests === true;
1650
+ if ([pattern !== undefined, marker !== undefined, code, disabled].filter(Boolean).length !== 1) {
1651
+ throw new CommandError(
1652
+ EXIT.USAGE,
1653
+ "give exactly one of --paths, --marker, --code, --disabled-tests",
1654
+ );
1655
+ }
1656
+ if (disabled && ctx.flags.expectNone === true)
1657
+ throw new CommandError(
1658
+ EXIT.USAGE,
1659
+ "--disabled-tests inverts the exit already; drop --expect-none",
1660
+ );
1661
+ let re: RegExp | undefined;
1662
+ if (pattern !== undefined) {
1663
+ try {
1664
+ re = new RegExp(pattern, "i");
1665
+ } catch (err) {
1666
+ ctx.log(`--paths is not a valid pattern: ${(err as Error).message}`);
1667
+ return EXIT.USAGE;
1668
+ }
1669
+ }
1670
+ const top = topLevel(ctx.cwd);
1671
+ const fetched = fetchRemoteRef(top, base);
1672
+ if (fetched !== null && !fetched.ok) {
1673
+ ctx.log(`git fetch for ${base} failed: ${fetched.stderr} — diffing against the local ref`);
1674
+ }
1675
+ if (!runGit(top, ["rev-parse", "-q", "--verify", `${base}^{commit}`]).ok) {
1676
+ ctx.log(`unknown base: ${base}`);
1677
+ return EXIT_DIFF_FAILED;
1678
+ }
1679
+ const range = `${base}...HEAD`;
1680
+ if (disabled) {
1681
+ const diff = quietGit(top, ["diff", "--no-renames", range, "--", ".", ":(exclude)docs/plans"]);
1682
+ if (!diff.ok) {
1683
+ ctx.log(`git diff ${range} failed: ${diff.stderr}`);
1684
+ return EXIT_DIFF_FAILED;
1685
+ }
1686
+ const hits = disabledTestsIn(diff.stdout, top);
1687
+ const files = [...new Set(hits.map((h) => h.file))];
1688
+ ctx.emit({ found: hits.length > 0, paths: files, disabled: hits });
1689
+ if (hits.length > 0)
1690
+ ctx.log(
1691
+ `disabled tests or removed assertions:\n${hits.map((h) => `${h.file}:${h.line} — ${h.test}`).join("\n")}`,
1692
+ );
1693
+ return hits.length > 0 ? EXIT.NO : EXIT.OK;
1694
+ }
1695
+ let paths: string[];
1696
+ if (marker !== undefined) {
1697
+ const diff = quietGit(top, ["diff", "--no-renames", range, "--", ".", ":(exclude)docs/plans"]);
1698
+ if (!diff.ok) {
1699
+ ctx.log(`git diff ${range} failed: ${diff.stderr}`);
1700
+ return EXIT_DIFF_FAILED;
1701
+ }
1702
+ const hits = new Set<string>();
1703
+ let file = "";
1704
+ for (const line of diff.stdout.split("\n")) {
1705
+ if (line.startsWith("+++ ")) {
1706
+ file = line.replace(/^\+\+\+ (b\/)?/, "");
1707
+ continue;
1708
+ }
1709
+ if (line.startsWith("+") && line.includes(marker)) hits.add(file);
1710
+ }
1711
+ paths = [...hits];
1712
+ } else {
1713
+ const diff = quietGit(top, [
1714
+ "diff",
1715
+ "--name-only",
1716
+ "-z",
1717
+ "--no-renames",
1718
+ range,
1719
+ ...(code ? ["--", ".", ...NOT_CODE] : []),
1720
+ ]);
1721
+ if (!diff.ok) {
1722
+ ctx.log(`git diff ${range} failed: ${diff.stderr}`);
1723
+ return EXIT_DIFF_FAILED;
1724
+ }
1725
+ paths = diff.stdout.split("\0").filter(Boolean);
1726
+ if (re !== undefined) paths = paths.filter((p) => re.test(p));
1727
+ }
1728
+ ctx.emit({ found: paths.length > 0, paths });
1729
+ if (ctx.flags.expectNone === true) {
1730
+ if (paths.length > 0) {
1731
+ ctx.log(
1732
+ marker !== undefined
1733
+ ? `added lines still carry ${marker} in: ${paths.join(", ")}`
1734
+ : `expected no match, found: ${paths.join(", ")}`,
1735
+ );
1736
+ }
1737
+ return paths.length > 0 ? EXIT.NO : EXIT.OK;
1738
+ }
1739
+ return paths.length > 0 ? EXIT.OK : EXIT.NO;
1740
+ }
1741
+
1742
+ async function forceBuildVerb(ctx: RunContext): Promise<number> {
1743
+ const f = ctx.flags;
1744
+ const fid = String(f.fid);
1745
+ const file = path.resolve(ctx.cwd, String(f.file));
1746
+ const workflow = String(f.workflow);
1747
+ const openPrFlag = str(f.openPr);
1748
+ if (openPrFlag !== undefined && openPrFlag !== "none" && !/^[1-9][0-9]*$/.test(openPrFlag)) {
1749
+ throw new CommandError(
1750
+ EXIT.USAGE,
1751
+ `--open-pr must be a PR number or none, got "${openPrFlag}"`,
1752
+ );
1753
+ }
1754
+ const branch = currentBranch(ctx.cwd);
1755
+ if (branch === "") {
1756
+ ctx.log("no branch checked out (detached HEAD) — refusing to force a build");
1757
+ return EXIT_DETACHED;
1758
+ }
1759
+ if (isSharedBranch(branch)) {
1760
+ ctx.log(`Nothing to ship: force-build marks a feature branch, not '${branch}'`);
1761
+ return EXIT_NOTHING_TO_PUSH;
1762
+ }
1763
+
1764
+ // (1) The PR title: CI reads the marker from it on pull_request events.
1765
+ const viaMcp = (why: string) => {
1766
+ ctx.log(
1767
+ `${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`,
1768
+ );
1769
+ return EXIT.USE_MCP;
1770
+ };
1771
+ let prNumber: number | null = null;
1772
+ let titleChanged = false;
1773
+ if (f.titleSet !== true && openPrFlag !== "none") {
1774
+ const probe = probePr(
1775
+ ctx.cwd,
1776
+ openPrFlag === undefined
1777
+ ? { head: branch, state: "open" }
1778
+ : { number: openPrFlag, state: "open" },
1779
+ );
1780
+ if (probe.kind !== "ok") return viaMcp(probe.message);
1781
+ if (probe.pr) {
1782
+ prNumber = probe.pr.number;
1783
+ if (!probe.pr.title.includes(FORCE_BUILD)) {
1784
+ const next = `${probe.pr.title} bkit ${FORCE_BUILD}`;
1785
+ const edit = runGh(ctx.cwd, ["pr", "edit", String(prNumber), "--title", next]);
1786
+ if (!edit.ok) {
1787
+ return viaMcp(
1788
+ ghUnavailable(edit)
1789
+ ? "gh unavailable for gh pr edit"
1790
+ : `gh pr edit ${prNumber} failed: ${edit.stderr}`,
1791
+ );
1792
+ }
1793
+ titleChanged = true;
1794
+ ctx.log(`PR #${prNumber} title now carries ${FORCE_BUILD}`);
1795
+ }
1796
+ }
1797
+ }
1798
+
1799
+ // (2) The empty marker commit, once per run; its push is the event that starts the run.
1800
+ const message = `chore(${fid}): force build bkit ${FORCE_BUILD}${autoRouteSuffix((f.label as string[] | undefined) ?? [])}`;
1801
+ const marker = markerCommit(ctx.cwd, {
1802
+ file,
1803
+ key: markerKey(file, workflow, "force-build"),
1804
+ message,
1805
+ addAll: false,
1806
+ });
1807
+ if (marker.deduped)
1808
+ ctx.log(`force-build commit ${marker.sha.slice(0, 12)} already made this run — pushing it`);
1809
+ const pushed = await pushBranch(ctx.cwd, { mode: "feature", requireCi: true }, ctx.log);
1810
+ ctx.emit({
1811
+ prNumber,
1812
+ titleChanged,
1813
+ commit: marker.sha,
1814
+ deduped: marker.deduped,
1815
+ pushed: pushed.out.pushed,
1816
+ ref: pushed.out.ref,
1817
+ sha: pushed.out.sha,
1818
+ });
1819
+ return pushed.code;
1820
+ }
1821
+
1822
+ /** The paths a feature branch must hold dev's commits for before GitHub reads it: docs/ and every ledger. */
1823
+ const DEV_DOC_PATHSPECS = ["docs/", ...LEDGERS.map((l) => `:(glob)${l}`)];
1824
+
1825
+ /** Commits on origin/dev not in `head` that touch docs/ or a ledger. */
1826
+ function docsBehindOf(top: string, head: string): number {
1827
+ return Number(
1828
+ git(top, ["rev-list", "--count", `${head}..${UPSTREAM}`, "--", ...DEV_DOC_PATHSPECS]) ?? "0",
1829
+ );
1830
+ }
1831
+
1832
+ export interface DevDocsMerge extends DevMerge {
1833
+ docsBehind: number;
1834
+ }
1835
+
1836
+ /**
1837
+ * The `docs` merge: bring dev's docs/ and ledger commits onto the feature branch
1838
+ * when it is behind them, so GitHub, which ignores `merge=union`, reads no ledger
1839
+ * conflict and CI runs. Nothing on a shared branch or when docs/ is current.
1840
+ */
1841
+ function mergeDevDocs(
1842
+ top: string,
1843
+ o: { branch: string; generate: boolean },
1844
+ log: (m: string) => void,
1845
+ ): DevDocsMerge {
1846
+ const docsBehind = docsBehindOf(top, "HEAD");
1847
+ const current = isSharedBranch(o.branch) || docsBehind === 0;
1848
+ if (!current)
1849
+ log(`docs/ and the ledgers are ${docsBehind} commit(s) behind ${UPSTREAM} — merging it in`);
1850
+ const merged = mergeDev(
1851
+ top,
1852
+ { branch: o.branch, policy: "docs", generate: o.generate, current },
1853
+ log,
1854
+ );
1855
+ return { ...merged, docsBehind };
1856
+ }
1857
+
1858
+ /**
1859
+ * Run the consumer's `bkit:generate` (`.bkit/workflows.md` § Local gate scripts)
1860
+ * and commit what it changed (`commitWhatChanged`). null when the script is undeclared.
1861
+ */
1862
+ function regenerate(
1863
+ top: string,
1864
+ branch: string,
1865
+ log: (m: string) => void,
1866
+ o: { fid?: string } = {},
1867
+ ): boolean | null {
1868
+ if (!generateDeclared(top)) return null;
1869
+ const fid = o.fid ?? branch.replace(/^feat\//, "");
1870
+ const message = `chore(${fid}): regenerate after merging ${DEV}`;
1871
+ const done = commitWhatChanged(
1872
+ top,
1873
+ "bkit:generate",
1874
+ () => runGenerate(top, log, "after the merge"),
1875
+ message,
1876
+ log,
1877
+ );
1878
+ if (done.outcome === "committed")
1879
+ log(`committed bkit:generate's output after merging ${UPSTREAM}`);
1880
+ return done.outcome !== "failed";
1881
+ }
1882
+
1883
+ /** Whether `top`'s package.json declares a non-empty `bkit:generate` script. */
1884
+ function generateDeclared(top: string): boolean {
1885
+ const pkg = readPackageJson(top);
1886
+ const scripts = pkg.ok ? pkg.pkg.scripts : undefined;
1887
+ return (
1888
+ typeof scripts === "object" &&
1889
+ scripts !== null &&
1890
+ typeof (scripts as Record<string, unknown>)["bkit:generate"] === "string" &&
1891
+ (scripts as Record<string, unknown>)["bkit:generate"] !== ""
1892
+ );
1893
+ }
1894
+
1895
+ /** Run `bkit:generate` in `top`; false when it failed, logged with its output's last lines. */
1896
+ function runGenerate(top: string, log: (m: string) => void, when: string): boolean {
1897
+ return runLogged(top, scriptCommand("bkit:generate"), log, when);
1898
+ }
1899
+
1900
+ /** Run `argv` in `top`; false when it failed, logged with its output's last lines. */
1901
+ function runLogged(
1902
+ top: string,
1903
+ argv: readonly string[],
1904
+ log: (m: string) => void,
1905
+ when: string,
1906
+ ): boolean {
1907
+ const res = spawnSync(argv[0]!, argv.slice(1), {
1908
+ cwd: top,
1909
+ encoding: "utf-8",
1910
+ stdio: ["ignore", "pipe", "pipe"],
1911
+ maxBuffer: 1 << 26,
1912
+ });
1913
+ if (res.status === 0) return true;
1914
+ log(`${argv.join(" ")} exited ${String(res.status ?? res.error?.message)} ${when}`);
1915
+ const out = `${res.stdout ?? ""}${res.stderr ?? ""}`.trim();
1916
+ if (out !== "") for (const line of out.split("\n").slice(-20)) log(` ${line}`);
1917
+ return false;
1918
+ }
1919
+
1920
+ /**
1921
+ * Each changed path in `top` (the entries worktree setup copies in left out), with a hash
1922
+ * of its content ("" when deleted); null when git could not run. Read raw: `--porcelain`
1923
+ * lines start with a status column that may be a space.
1924
+ */
1925
+ function changedPaths(top: string): Map<string, string> | null {
1926
+ const res = spawnSync(
1927
+ "git",
1928
+ ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--", ".", ...copyExcludes(top)],
1929
+ { cwd: top, env: gitEnv(), encoding: "utf-8", maxBuffer: OUTPUT_LIMIT },
1930
+ );
1931
+ if (res.error || res.status !== 0) return null;
1932
+ const out = new Map<string, string>();
1933
+ const entries = res.stdout.split("\0");
1934
+ for (let i = 0; i < entries.length; i++) {
1935
+ const entry = entries[i]!;
1936
+ if (entry.length < 4) continue;
1937
+ const file = entry.slice(3);
1938
+ // A staged rename or copy carries its source as the next entry.
1939
+ if (entry[0] === "R" || entry[0] === "C") i++;
1940
+ const abs = path.join(top, file);
1941
+ out.set(
1942
+ file,
1943
+ fs.existsSync(abs) && fs.statSync(abs).isFile()
1944
+ ? createHash("sha256").update(fs.readFileSync(abs)).digest("hex")
1945
+ : "",
1946
+ );
1947
+ }
1948
+ return out;
1949
+ }
1950
+
1951
+ /**
1952
+ * What a generator changed between two `changedPaths` reads: `rewritten` were already
1953
+ * changed and changed again, so they cannot be told apart from work that is not
1954
+ * generated; `added` are the paths only the generator changed, sorted.
1955
+ */
1956
+ function changedSince(
1957
+ dirty: Map<string, string>,
1958
+ after: Map<string, string>,
1959
+ ): { rewritten: string[]; added: string[] } {
1960
+ return {
1961
+ rewritten: [...after].filter(([f, h]) => dirty.has(f) && dirty.get(f) !== h).map(([f]) => f),
1962
+ added: [...after.keys()].filter((f) => !dirty.has(f)).sort(),
1963
+ };
1964
+ }
1965
+
1966
+ /** Commit exactly `paths`, deletions included; false when the add or the commit failed. */
1967
+ function commitPaths(top: string, paths: string[], message: string): boolean {
1968
+ return (
1969
+ runGit(top, ["add", "-A", "--", ...paths]).ok &&
1970
+ quietGit(top, ["commit", "-q", "-m", message, "--", ...paths]).ok
1971
+ );
1972
+ }
1973
+
1974
+ /**
1975
+ * Run a generator (`run`, named `what` in the log) in `top` and commit exactly the paths
1976
+ * it changed as `message`, so uncommitted work already in the tree stays out of the
1977
+ * commit. `failed` (logged) when `git status` or the commit failed, `run` failed, or it
1978
+ * changed a path that already held uncommitted changes again: that cannot be told apart
1979
+ * from work that is not generated. `unchanged` when it changed nothing.
1980
+ */
1981
+ function commitWhatChanged(
1982
+ top: string,
1983
+ what: string,
1984
+ run: () => boolean,
1985
+ message: string,
1986
+ log: (m: string) => void,
1987
+ ): { outcome: "committed" | "unchanged" | "failed"; paths: string[] } {
1988
+ const failed = { outcome: "failed" as const, paths: [] };
1989
+ const dirty = changedPaths(top);
1990
+ if (dirty === null) {
1991
+ log(`git status failed — ${what} not run`);
1992
+ return failed;
1993
+ }
1994
+ if (!run()) return failed;
1995
+ const after = changedPaths(top);
1996
+ if (after === null) {
1997
+ log(`git status failed after ${what}`);
1998
+ return failed;
1999
+ }
2000
+ const { rewritten, added } = changedSince(dirty, after);
2001
+ if (rewritten.length > 0) {
2002
+ for (const f of rewritten) log(` ${f}`);
2003
+ log(`${what} changed paths that already held uncommitted changes — nothing committed`);
2004
+ return failed;
2005
+ }
2006
+ if (added.length === 0) return { outcome: "unchanged", paths: [] };
2007
+ if (!commitPaths(top, added, message)) {
2008
+ log(`committing the output of ${what} failed`);
2009
+ return failed;
2010
+ }
2011
+ return { outcome: "committed", paths: added };
641
2012
  }
642
2013
 
643
- function pushVerb(ctx: RunContext): number {
644
- const mode = String(ctx.flags.mode);
645
- if (!["feature", "abort", "dev"].includes(mode)) {
646
- throw new CommandError(EXIT.USAGE, "--mode must be feature, abort, or dev");
2014
+ /**
2015
+ * Rebuild each register a conflict settled on dev's copy (`REGISTERS`), or whose
2016
+ * generated block a conflicted doc took from dev, and commit only the paths the rebuild
2017
+ * changed. null when none was settled, or no settled register's script exists in the
2018
+ * repo; false when a rebuild failed, or changed a path that already held uncommitted
2019
+ * changes. A register not rebuilt keeps dev's copy: the pre-push gate, CI and ship's
2020
+ * `bkit:generate` still judge it.
2021
+ */
2022
+ function rebuildRegisters(
2023
+ top: string,
2024
+ resolved: Resolution[],
2025
+ commitMessage: (files: string[]) => string,
2026
+ log: (m: string) => void,
2027
+ ): boolean | null {
2028
+ const embeds = embedDocs(top);
2029
+ const settled = [
2030
+ ...new Set(
2031
+ resolved.flatMap((r) => {
2032
+ const register =
2033
+ r.how === "register" ? r.path : r.how === "embed" ? embeds.get(r.path) : undefined;
2034
+ return register === undefined ? [] : [register];
2035
+ }),
2036
+ ),
2037
+ ];
2038
+ const due = settled.filter((f) => fs.existsSync(path.join(top, REGISTERS[f]!.script)));
2039
+ for (const f of settled)
2040
+ if (!due.includes(f)) log(`NOT REBUILT ${f} — ${REGISTERS[f]!.script} is absent`);
2041
+ if (due.length === 0) return null;
2042
+ const which = due.join(", ");
2043
+ const rebuild = () =>
2044
+ due.every((f) => {
2045
+ const { script, args } = REGISTERS[f]!;
2046
+ if (runLogged(top, ["bash", script, ...args], log, `rebuilding ${f}`)) return true;
2047
+ log(`NOT REBUILT ${f} — it keeps ${DEV}'s copy`);
2048
+ return false;
2049
+ });
2050
+ const done = commitWhatChanged(top, `the rebuild of ${which}`, rebuild, commitMessage(due), log);
2051
+ if (done.outcome === "failed") return false;
2052
+ log(
2053
+ done.outcome === "unchanged"
2054
+ ? `REBUILT ${which} — ${DEV}'s copy was already current`
2055
+ : `REBUILT ${which} — committed as ${git(top, ["rev-parse", "HEAD"])}`,
2056
+ );
2057
+ return true;
2058
+ }
2059
+
2060
+ /**
2061
+ * Ship's regenerate (`.bkit/workflows.md` § `/bkit-ship`): run a declared `bkit:generate`
2062
+ * on the checked-out feature branch and commit only the paths it changed
2063
+ * (`commitWhatChanged`), so the run's own uncommitted bookkeeping (status.jsonl) stays out
2064
+ * of the commit. Step 10 runs it when every failed CI step is one it fixes (`--attempt`).
2065
+ */
2066
+ function regenerateVerb(ctx: RunContext): number {
2067
+ const top = topLevel(ctx.cwd);
2068
+ const branch = currentBranch(top);
2069
+ if (branch === "") {
2070
+ ctx.log("no branch checked out (detached HEAD) — cannot regenerate");
2071
+ return EXIT_DETACHED;
647
2072
  }
648
- const r = pushBranch(
649
- ctx.cwd,
650
- {
651
- mode: mode as "feature" | "abort" | "dev",
652
- setUpstream: ctx.flags.setUpstream === true,
653
- requireCi: ctx.flags.requireCi === true,
654
- openPr: str(ctx.flags.openPr),
655
- },
2073
+ if (isSharedBranch(branch))
2074
+ throw new CommandError(EXIT.USAGE, `regenerate runs on a feature branch, never on ${branch}`);
2075
+ const attempt = str(ctx.flags.attempt);
2076
+ if (attempt !== undefined && !/^[1-9]\d*$/.test(attempt))
2077
+ throw new CommandError(EXIT.USAGE, "--attempt must be a whole number >= 1");
2078
+ const fid = str(ctx.flags.fid) || branch.replace(/^feat\//, "");
2079
+ const before = git(top, ["rev-parse", "HEAD"]);
2080
+ const out = { outcome: "undeclared", head: before, paths: [] as string[] };
2081
+ if (!generateDeclared(top)) {
2082
+ ctx.log("bkit:generate is not declared — nothing regenerated");
2083
+ ctx.emit(out);
2084
+ return EXIT.OK;
2085
+ }
2086
+ const message =
2087
+ attempt === undefined
2088
+ ? `chore(${fid}): regenerate before re-validating`
2089
+ : `fix(${fid}): regenerate attempt ${attempt}`;
2090
+ const done = commitWhatChanged(
2091
+ top,
2092
+ "bkit:generate",
2093
+ () => runGenerate(top, ctx.log, "on the branch"),
2094
+ message,
656
2095
  ctx.log,
657
2096
  );
658
- // A detached HEAD and a wrong checkout print nothing, as the push never got to run.
659
- if (r.code !== EXIT_DETACHED && r.code !== EXIT_NOT_DEV) ctx.emit(r.out);
660
- return r.code;
2097
+ if (done.outcome === "failed") return EXIT_GENERATE_FAILED;
2098
+ out.paths = done.paths;
2099
+ if (done.outcome === "unchanged") {
2100
+ out.outcome = "unchanged";
2101
+ ctx.log("bkit:generate changed nothing");
2102
+ ctx.emit(out);
2103
+ return EXIT.OK;
2104
+ }
2105
+ out.outcome = "committed";
2106
+ out.head = git(top, ["rev-parse", "HEAD"]);
2107
+ for (const f of out.paths) ctx.log(`regenerated ${f}`);
2108
+ ctx.log(`committed bkit:generate's output as ${out.head}`);
2109
+ const statusFile = str(ctx.flags.file);
2110
+ if (statusFile !== undefined && before !== null && out.head !== null) {
2111
+ recordAction(path.resolve(ctx.cwd, statusFile), {
2112
+ action: "regenerate",
2113
+ key: actionKey("regenerate", before),
2114
+ hash: actionHash(`${before}..${out.head}`),
2115
+ ref: out.head,
2116
+ });
2117
+ }
2118
+ ctx.emit(out);
2119
+ return EXIT.OK;
661
2120
  }
662
2121
 
663
- /** Resolve sync's docs-merge conflicts: ledgers by union, other `docs/` paths take dev's side. */
664
- function resolveDocsMerge(top: string): { resolved: Resolution[] } | { refused: string } {
665
- const conflicts = unmergedPaths(top);
666
- const refused = conflicts.find((f) => classifyConflict(f) !== "ledger" && !f.startsWith("docs/"));
667
- if (refused !== undefined) return { refused };
668
- const resolved: Resolution[] = [];
669
- for (const f of conflicts) {
670
- if (classifyConflict(f) === "ledger") {
671
- if (!unionResolve(top, f).ok || !runGit(top, ["add", "--", f]).ok) return { refused: f };
672
- resolved.push({ path: f, how: "union" });
673
- continue;
674
- }
2122
+ /** Whether a merge is in progress in `top` (its MERGE_HEAD exists). */
2123
+ function mergeInProgress(top: string): boolean {
2124
+ const p = git(top, ["rev-parse", "--path-format=absolute", "--git-path", "MERGE_HEAD"]);
2125
+ return p !== null && fs.existsSync(p);
2126
+ }
2127
+
2128
+ /**
2129
+ * Which conflicts a merge of origin/dev settles on its own. `docs` (build's Branch
2130
+ * Sync, a `--require-ci` push, land's PR retry) integrates only what GitHub must see
2131
+ * merged: ledgers union, other docs/ paths take dev, anything else refuses and the
2132
+ * merge is aborted. `full` (ship Step 4) integrates all of dev: ledgers union, a
2133
+ * lockfile regenerates from dev's copy, anything else is left conflicted for a hand
2134
+ * resolution with the merge in progress.
2135
+ */
2136
+ export type MergePolicy = "docs" | "full";
2137
+
2138
+ /** Settle one conflicted path under `policy`, staging it when it is resolved. */
2139
+ function resolvePath(
2140
+ top: string,
2141
+ file: string,
2142
+ policy: MergePolicy,
2143
+ embeds: ReadonlyMap<string, string>,
2144
+ ): Resolution["how"] | "pending" | { refused: string } {
2145
+ const kind = classifyConflict(file, embeds);
2146
+ if (kind === "ledger") {
2147
+ const union = unionResolve(top, file);
2148
+ if (!union.ok) return { refused: union.problem };
2149
+ return runGit(top, ["add", "--", file]).ok ? "union" : { refused: "git add failed" };
2150
+ }
2151
+ if (kind === "register") {
2152
+ const settled = registerResolve(top, file, "theirs");
2153
+ if (!settled.ok) return { refused: settled.problem };
2154
+ return runGit(top, ["add", "--", file]).ok ? "register" : { refused: "git add failed" };
2155
+ }
2156
+ if (kind === "embed") {
2157
+ const settled = embedResolve(top, file, embeds.get(file)!, "theirs");
2158
+ if (!settled.ok) return { refused: settled.problem };
2159
+ return runGit(top, ["add", "--", file]).ok ? "embed" : { refused: "git add failed" };
2160
+ }
2161
+ if (kind === "record") {
2162
+ const settled = recordResolve(top, "theirs");
2163
+ if (!settled.ok) return { refused: settled.problem };
2164
+ return runGit(top, ["add", "--", file]).ok ? "record" : { refused: "git add failed" };
2165
+ }
2166
+ if (policy === "docs") {
2167
+ if (!file.startsWith("docs/")) return { refused: "outside docs/ and the ledgers" };
675
2168
  // In a merge `--theirs` is the branch merged in: dev. Dev deleting the file
676
2169
  // leaves no stage 3, and taking dev's side means deleting it here too.
677
- const devHasIt = runGit(top, ["cat-file", "-e", `:3:${f}`]).ok;
2170
+ const devHasIt = runGit(top, ["cat-file", "-e", `:3:${file}`]).ok;
678
2171
  const ok = devHasIt
679
- ? runGit(top, ["checkout", "--theirs", "--", f]).ok && runGit(top, ["add", "--", f]).ok
680
- : runGit(top, ["rm", "-q", "--", f]).ok;
681
- if (!ok) return { refused: f };
682
- resolved.push({ path: f, how: "dev" });
2172
+ ? runGit(top, ["checkout", "--theirs", "--", file]).ok && runGit(top, ["add", "--", file]).ok
2173
+ : runGit(top, ["rm", "-q", "--", file]).ok;
2174
+ return ok ? "dev" : { refused: `taking ${DEV}'s side failed` };
2175
+ }
2176
+ if (kind === "lockfile") {
2177
+ if (!lockfileResolve(top, file, "theirs")) return { refused: "lockfile regenerate failed" };
2178
+ return runGit(top, ["add", "--", file]).ok ? "lockfile" : { refused: "git add failed" };
2179
+ }
2180
+ return "pending";
2181
+ }
2182
+
2183
+ const RESOLVED_HOW: Record<Resolution["how"], string> = {
2184
+ union: "union (append-only ledger)",
2185
+ dev: `took ${DEV}`,
2186
+ lockfile: `lockfile regenerated from ${DEV}'s copy`,
2187
+ register: `took ${DEV}'s copy of a generated register`,
2188
+ embed: `took ${DEV}'s copy of the generated block, merged the rest`,
2189
+ record: `merged the install record entry by entry, ${DEV}'s value where both changed`,
2190
+ };
2191
+
2192
+ export interface DevMerge {
2193
+ /** EXIT.OK, EXIT_REFUSED, EXIT_MERGE_CONFLICT, EXIT_HAND_RESOLVE or EXIT_GENERATE_FAILED. */
2194
+ code: number;
2195
+ outcome: "merged" | "current" | "pending" | "refused";
2196
+ merged: boolean;
2197
+ /** The commit that carried the tree's uncommitted work before the merge; null when it was clean or not carried. */
2198
+ carried: string | null;
2199
+ resolved: Resolution[];
2200
+ /** Paths left conflicted for a hand resolution, the merge still in progress (`full` only). */
2201
+ pending: string[];
2202
+ /** A refused merge was aborted. */
2203
+ aborted: boolean;
2204
+ /** bkit:generate ran after the merge: true, false (failed), null (not run). */
2205
+ generated: boolean | null;
2206
+ /** A register settled on dev's copy was rebuilt: true, false (failed), null (not run). */
2207
+ rebuilt: boolean | null;
2208
+ /** The branch tip the merge started from (ORIG_HEAD when continuing one). */
2209
+ before: string | null;
2210
+ }
2211
+
2212
+ interface MergeDevOptions {
2213
+ branch: string;
2214
+ policy: MergePolicy;
2215
+ /** The feature id in the commit messages (default: the branch name without feat/). */
2216
+ fid?: string;
2217
+ /** Rebuild a register settled on dev's copy, then run a declared bkit:generate, committing each one's output. */
2218
+ generate: boolean;
2219
+ /** Nothing to integrate: outcome `current`, the tree untouched. */
2220
+ current: boolean;
2221
+ }
2222
+
2223
+ /**
2224
+ * Merge origin/dev (already fetched) into the checked-out feature branch under
2225
+ * `policy`. A merge in progress at the start is continued: its remaining conflicts
2226
+ * are settled and it is committed, which is how a `full` hand resolution finishes
2227
+ * (`git add`, then run again). `full` also commits the tree's uncommitted work first
2228
+ * (ship's open status.jsonl). No commit carries a skip token: the merge brings dev's
2229
+ * code, and the pre-push hook refuses a skip-token head that carries code while the
2230
+ * PR is open. Never a rebase: GitHub ignores `merge=union`, so a
2231
+ * branch rebased onto dev still shows as conflicting on every ledger both sides
2232
+ * appended to, while the merge commit is what GitHub's own merge would compute.
2233
+ */
2234
+ function mergeDev(top: string, o: MergeDevOptions, log: (m: string) => void): DevMerge {
2235
+ const out: DevMerge = {
2236
+ code: EXIT.OK,
2237
+ outcome: "merged",
2238
+ merged: false,
2239
+ carried: null,
2240
+ resolved: [],
2241
+ pending: [],
2242
+ aborted: false,
2243
+ generated: null,
2244
+ rebuilt: null,
2245
+ before: null,
2246
+ };
2247
+ const full = o.policy === "full";
2248
+ const fid = o.fid ?? o.branch.replace(/^feat\//, "");
2249
+ const refuse = (why: string): DevMerge => {
2250
+ const abort = runGit(top, ["merge", "--abort"]);
2251
+ out.aborted = abort.ok;
2252
+ log(abort.ok ? `${why} — merge aborted` : `${why} — git merge --abort failed: ${abort.stderr}`);
2253
+ return { ...out, code: EXIT_MERGE_CONFLICT, outcome: "refused" };
2254
+ };
2255
+ if (mergeInProgress(top)) {
2256
+ out.before = git(top, ["rev-parse", "--verify", "--quiet", "ORIG_HEAD"]);
2257
+ log(`a merge of ${UPSTREAM} is in progress — continuing it`);
2258
+ } else {
2259
+ if (o.current) return { ...out, outcome: "current" };
2260
+ if (full && hasLeftovers(top)) {
2261
+ const message = `chore(${fid}): carry uncommitted work before merging ${DEV}`;
2262
+ if (!addAllButCopied(top).ok || !quietGit(top, ["commit", "-q", "-m", message]).ok) {
2263
+ log("the uncommitted work could not be committed before the merge");
2264
+ return { ...out, code: EXIT_REFUSED, outcome: "refused" };
2265
+ }
2266
+ out.carried = git(top, ["rev-parse", "HEAD"]);
2267
+ log(`committed the uncommitted work as ${out.carried} before merging ${UPSTREAM}`);
2268
+ }
2269
+ out.before = git(top, ["rev-parse", "HEAD"]);
2270
+ const message = `chore(${fid}): merge ${DEV}`;
2271
+ const merge = quietGit(top, ["merge", "--no-edit", "-m", message, UPSTREAM]);
2272
+ if (!merge.ok && !mergeInProgress(top)) {
2273
+ // Not a conflict: git refused to start the merge at all.
2274
+ log(`git merge ${UPSTREAM} failed: ${merge.stderr.trim()}`);
2275
+ return { ...out, code: EXIT_MERGE_CONFLICT, outcome: "refused" };
2276
+ }
2277
+ }
2278
+ if (mergeInProgress(top)) {
2279
+ const embeds = embedDocs(top);
2280
+ for (const f of unmergedPaths(top)) {
2281
+ const r = resolvePath(top, f, o.policy, embeds);
2282
+ if (typeof r === "object") return refuse(`${f}: ${r.refused}`);
2283
+ if (r === "pending") {
2284
+ out.pending.push(f);
2285
+ continue;
2286
+ }
2287
+ out.resolved.push({ path: f, how: r });
2288
+ log(`RESOLVED ${f} — ${RESOLVED_HOW[r]}`);
2289
+ }
2290
+ if (out.pending.length > 0) {
2291
+ for (const p of out.pending)
2292
+ log(`PENDING ${p} — needs a hand resolution; run again after git add`);
2293
+ return { ...out, code: EXIT_HAND_RESOLVE, outcome: "pending" };
2294
+ }
2295
+ if (!quietGit(top, ["commit", "--no-edit"]).ok)
2296
+ return refuse("the merge could not be committed");
2297
+ }
2298
+ out.merged = true;
2299
+ log(`merged ${UPSTREAM} into ${o.branch} as ${git(top, ["rev-parse", "HEAD"])}`);
2300
+ if (o.generate) {
2301
+ out.rebuilt = rebuildRegisters(
2302
+ top,
2303
+ out.resolved,
2304
+ (files) => `chore(${fid}): rebuild ${files.join(" ")} after merging ${DEV}`,
2305
+ log,
2306
+ );
2307
+ out.generated = regenerate(top, o.branch, log, { fid });
2308
+ if (out.generated === false) out.code = EXIT_GENERATE_FAILED;
683
2309
  }
684
- return { resolved };
2310
+ return out;
2311
+ }
2312
+
2313
+ /**
2314
+ * An engine-action row for a merge of origin/dev that moved the branch, keyed on
2315
+ * the tip it started from, so the run's record shows the integration. Nothing when
2316
+ * HEAD did not move.
2317
+ */
2318
+ function recordMerge(statusFile: string, before: string | null, after: string | null): void {
2319
+ if (before === null || after === null || before === after) return;
2320
+ recordAction(statusFile, {
2321
+ action: "merge",
2322
+ key: actionKey("merge", before),
2323
+ hash: actionHash(`${before}..${after}`),
2324
+ ref: after,
2325
+ });
685
2326
  }
686
2327
 
687
2328
  function syncVerb(ctx: RunContext): number {
688
2329
  const mergeDocs = ctx.flags.mergeDocs === true;
2330
+ const merge = ctx.flags.merge === true;
689
2331
  const headFlag = str(ctx.flags.head);
690
- if (mergeDocs && headFlag !== undefined) {
2332
+ if ((mergeDocs || merge) && headFlag !== undefined) {
691
2333
  throw new CommandError(
692
2334
  EXIT.USAGE,
693
- "--merge-docs merges into HEAD; give --head or --merge-docs, not both",
2335
+ "--merge and --merge-docs merge into HEAD; give --head or one of them, not both",
694
2336
  );
695
2337
  }
2338
+ if (mergeDocs && merge)
2339
+ throw new CommandError(EXIT.USAGE, "give --merge or --merge-docs, not both");
2340
+ const sentinel = str(ctx.flags.sentinel);
2341
+ const sentinelPath = sentinel === undefined ? undefined : path.resolve(ctx.cwd, sentinel);
2342
+ if (merge && sentinelPath) fs.rmSync(sentinelPath, { force: true });
696
2343
  const top = topLevel(ctx.cwd);
697
- const fetch = runGit(top, ["fetch", REMOTE, DEV]);
2344
+ const fetch = fetchDev(top);
698
2345
  if (!fetch.ok) {
699
2346
  ctx.log(`git fetch ${REMOTE} ${DEV} failed: ${fetch.stderr}`);
700
2347
  return EXIT_FETCH_FAILED;
@@ -716,7 +2363,7 @@ function syncVerb(ctx: RunContext): number {
716
2363
  }
717
2364
  const count = (args: string[]) => Number(git(top, ["rev-list", "--count", ...args]) ?? "0");
718
2365
  const behind = count([`${head}..${UPSTREAM}`]);
719
- const docsBehind = count([`${head}..${UPSTREAM}`, "--", "docs/"]);
2366
+ const docsBehind = docsBehindOf(top, head);
720
2367
  const out = {
721
2368
  branch: branch === "" ? null : branch,
722
2369
  head,
@@ -725,6 +2372,8 @@ function syncVerb(ctx: RunContext): number {
725
2372
  docsBehind,
726
2373
  merged: false,
727
2374
  resolved: [] as Resolution[],
2375
+ generated: null as boolean | null,
2376
+ rebuilt: null as boolean | null,
728
2377
  };
729
2378
 
730
2379
  if (mergeDocs) {
@@ -732,31 +2381,56 @@ function syncVerb(ctx: RunContext): number {
732
2381
  ctx.log("no branch checked out (detached HEAD) — cannot merge dev's docs");
733
2382
  return EXIT_DETACHED;
734
2383
  }
735
- if (!isSharedBranch(branch) && docsBehind > 0) {
736
- ctx.log(`docs/ is ${docsBehind} commit(s) behind ${UPSTREAM} — merging it in`);
737
- if (!quietGit(top, ["merge", "--no-edit", UPSTREAM]).ok) {
738
- const outcome = resolveDocsMerge(top);
739
- if ("refused" in outcome) {
740
- runGit(top, ["merge", "--abort"]);
741
- ctx.log(
742
- `merge of ${UPSTREAM} conflicts on ${outcome.refused} — outside docs/, merge aborted`,
743
- );
744
- return EXIT_MERGE_CONFLICT;
745
- }
746
- if (unmergedPaths(top).length > 0 || !quietGit(top, ["commit", "--no-edit"]).ok) {
747
- runGit(top, ["merge", "--abort"]);
748
- ctx.log(`merge of ${UPSTREAM} could not be committed — merge aborted`);
749
- return EXIT_MERGE_CONFLICT;
750
- }
751
- out.resolved = outcome.resolved;
752
- for (const r of outcome.resolved)
753
- ctx.log(
754
- `RESOLVED ${r.path} — ${r.how === "union" ? "union (append-only ledger)" : `took ${DEV}`}`,
755
- );
756
- }
757
- out.merged = true;
758
- out.head = git(top, ["rev-parse", "HEAD"]) ?? head;
2384
+ const m = mergeDevDocs(top, { branch, generate: true }, ctx.log);
2385
+ if (m.code === EXIT_MERGE_CONFLICT) return m.code;
2386
+ out.merged = m.merged;
2387
+ out.resolved = m.resolved;
2388
+ out.generated = m.generated;
2389
+ out.rebuilt = m.rebuilt;
2390
+ if (m.merged) out.head = git(top, ["rev-parse", "HEAD"]) ?? head;
2391
+ ctx.emit(out);
2392
+ return m.code;
2393
+ }
2394
+ if (merge) {
2395
+ if (branch === "") {
2396
+ ctx.log(`no branch checked out (detached HEAD) — cannot merge ${UPSTREAM}`);
2397
+ return EXIT_DETACHED;
2398
+ }
2399
+ if (isSharedBranch(branch)) {
2400
+ throw new CommandError(
2401
+ EXIT.USAGE,
2402
+ `--merge merges ${UPSTREAM} into a feature branch, never into ${branch}`,
2403
+ );
2404
+ }
2405
+ const fid = str(ctx.flags.fid) || branch.replace(/^feat\//, "");
2406
+ const m = mergeDev(
2407
+ top,
2408
+ { branch, policy: "full", fid, generate: true, current: out.basePath === "A" },
2409
+ ctx.log,
2410
+ );
2411
+ const refused = m.outcome === "refused";
2412
+ if (refused && sentinelPath) {
2413
+ fs.mkdirSync(path.dirname(sentinelPath), { recursive: true });
2414
+ fs.writeFileSync(sentinelPath, "");
759
2415
  }
2416
+ const newHead = git(top, ["rev-parse", "HEAD"]) ?? head;
2417
+ ctx.emit({
2418
+ ...out,
2419
+ head: newHead,
2420
+ merged: m.merged,
2421
+ resolved: m.resolved,
2422
+ generated: m.generated,
2423
+ rebuilt: m.rebuilt,
2424
+ outcome: m.outcome,
2425
+ carried: m.carried,
2426
+ pending: m.pending,
2427
+ aborted: m.aborted,
2428
+ sentinel: refused && sentinel !== undefined ? sentinel : null,
2429
+ });
2430
+ const statusFile = str(ctx.flags.file);
2431
+ if (m.merged && statusFile !== undefined)
2432
+ recordMerge(path.resolve(ctx.cwd, statusFile), m.before, newHead);
2433
+ return m.code;
760
2434
  }
761
2435
  ctx.emit(out);
762
2436
  return EXIT.OK;
@@ -769,14 +2443,7 @@ function syncVerb(ctx: RunContext): number {
769
2443
  */
770
2444
  function syncDevVerb(ctx: RunContext): number {
771
2445
  const root = repoRoot(ctx.cwd);
772
- // `bkit install` can leave core.bare=true on the main checkout, which breaks `merge --ff-only` there.
773
- if (
774
- git(root, ["config", "--get", "core.bare"]) === "true" &&
775
- fs.statSync(path.join(root, ".git"), { throwIfNoEntry: false })?.isDirectory()
776
- ) {
777
- runGit(root, ["config", "core.bare", "false"]);
778
- }
779
- const fetch = runGit(root, ["fetch", REMOTE, DEV]);
2446
+ const fetch = fetchDev(root);
780
2447
  if (!fetch.ok) {
781
2448
  ctx.log(`git fetch ${REMOTE} ${DEV} failed: ${fetch.stderr}`);
782
2449
  return EXIT_FETCH_FAILED;
@@ -810,7 +2477,7 @@ function install(ctx: RunContext, root: string): boolean | null {
810
2477
  /** What a design / plan close may bring to dev: docs and ledgers, nothing else. */
811
2478
  const CLOSE_DOCS = /^docs\/plans\/|^docs\/roadmap\.md$|^docs\/[^/]+\.jsonl$|^\.bkit\/[^/]+\.jsonl$/;
812
2479
 
813
- /** The canonical docs `ref` carries for the feature: design, or plan plus sub-plans. */
2480
+ /** The canonical doc `ref` carries for the feature: `{fid}-design.md` or `{fid}-plan.md`. */
814
2481
  function canonicalDocs(
815
2482
  root: string,
816
2483
  ref: string,
@@ -818,10 +2485,7 @@ function canonicalDocs(
818
2485
  month: string,
819
2486
  fid: string,
820
2487
  ): string[] {
821
- const re =
822
- workflow === "plan"
823
- ? new RegExp(`^docs/plans/${month}/${fid}-plan(-[0-9]+)?\\.md$`)
824
- : new RegExp(`^docs/plans/${month}/${fid}-design\\.md$`);
2488
+ const re = new RegExp(`^docs/plans/${month}/${fid}-${workflow}\\.md$`);
825
2489
  return (git(root, ["ls-tree", "-r", "--name-only", ref, "--", `docs/plans/${month}/`]) ?? "")
826
2490
  .split("\n")
827
2491
  .filter((f) => re.test(f));
@@ -921,11 +2585,13 @@ function buildClose(
921
2585
  const staged = (git(dir, ["diff", "--cached", "--name-only"]) ?? "")
922
2586
  .split("\n")
923
2587
  .filter((p) => p !== "" && !CLOSE_DOCS.test(p));
924
- if (staged.length)
2588
+ if (staged.length) {
2589
+ const inherited = localDevCopies(dir, staged, (p) => `:${p}`);
925
2590
  throw new Stop(
926
2591
  EXIT_LAND_STOPPED,
927
- `${o.workflow} close staged non-doc files:\n${staged.join("\n")}`,
2592
+ `${o.workflow} close staged non-doc files:\n${staged.join("\n")}${unpushedDevCause(dir, inherited.length, staged.length, ", then re-run the close.")}`,
928
2593
  );
2594
+ }
929
2595
  const docs = canonicalDocs(dir, o.branch, o.workflow, o.month, o.fid);
930
2596
  const main = `docs/plans/${o.month}/${o.fid}-${o.workflow}.md`;
931
2597
  if (!docs.includes(main))
@@ -1014,11 +2680,42 @@ function branchTree(root: string, branch: string): string | null {
1014
2680
  return null;
1015
2681
  }
1016
2682
 
2683
+ /**
2684
+ * A land retry: merge origin/dev's docs and ledger commits into the PR branch in
2685
+ * the checkout holding it and push, so the PR carries dev's ledger rows. GitHub's
2686
+ * own branch update ignores `merge=union` and fails on the same conflict each time.
2687
+ */
2688
+ async function mergeDevIntoPrBranch(
2689
+ root: string,
2690
+ branch: string,
2691
+ log: (m: string) => void,
2692
+ ): Promise<void> {
2693
+ const tree = branchTree(root, branch);
2694
+ if (tree === null)
2695
+ throw new Stop(
2696
+ EXIT_LAND_STOPPED,
2697
+ `no checkout has ${branch} checked out — cannot merge ${DEV} into the PR branch; the PR stays open`,
2698
+ );
2699
+ if (!fetchDev(tree).ok)
2700
+ throw new Stop(EXIT_LAND_STOPPED, `fetch of ${UPSTREAM} failed — the PR stays open`);
2701
+ const m = mergeDevDocs(tree, { branch, generate: false }, log);
2702
+ if (m.code !== EXIT.OK)
2703
+ throw new Stop(
2704
+ EXIT_LAND_STOPPED,
2705
+ `merging ${UPSTREAM} into ${branch} stopped on a conflict outside docs/ and the ledgers — the PR stays open`,
2706
+ );
2707
+ if (!m.merged) return;
2708
+ const pushed = await pushBranch(tree, { mode: "feature" }, log);
2709
+ if (pushed.code !== EXIT.OK)
2710
+ throw new Stop(EXIT_PUSH_FAILED, `push of ${branch} after merging ${DEV} failed`);
2711
+ log(`merged ${UPSTREAM} into ${branch} and pushed it`);
2712
+ }
2713
+
1017
2714
  /**
1018
2715
  * The PR close (the dev push was refused): commit the roadmap row on the branch
1019
2716
  * in the checkout holding it, push it, open or reuse the PR, squash-merge it with
1020
- * an empty body. A merge that does not land on an open PR → update its branch
1021
- * from dev and try again, with backoff, LAND_ATTEMPTS tries in all; then stop with
2717
+ * an empty body. A merge that does not land on an open PR → merge dev into its
2718
+ * branch locally, push, and try again, with backoff, LAND_ATTEMPTS tries in all; then stop with
1022
2719
  * the PR left open. gh missing → EXIT.USE_MCP with what to create / merge; re-run
1023
2720
  * with `--pr` (and `--merged-sha` once merged).
1024
2721
  */
@@ -1043,7 +2740,12 @@ async function landPr(
1043
2740
  EXIT_LAND_STOPPED,
1044
2741
  `no checkout has ${o.branch} checked out — the PR close commits the roadmap row on it; nothing landed`,
1045
2742
  );
1046
- runGit(tree, ["fetch", REMOTE, DEV, o.branch]);
2743
+ runGit(tree, [
2744
+ "fetch",
2745
+ REMOTE,
2746
+ DEV_REFSPEC,
2747
+ `+refs/heads/${o.branch}:refs/remotes/${REMOTE}/${o.branch}`,
2748
+ ]);
1047
2749
  appendFeature(tree, { workflow: o.workflow, fid: o.fid }, ctx.log);
1048
2750
  commitBookkeeping(
1049
2751
  {
@@ -1064,7 +2766,7 @@ async function landPr(
1064
2766
  EXIT_LAND_STOPPED,
1065
2767
  `${o.workflow} close diff carries non-doc files:\n${stray.join("\n")}`,
1066
2768
  );
1067
- const pushed = pushBranch(tree, { mode: "feature" }, ctx.log);
2769
+ const pushed = await pushBranch(tree, { mode: "feature" }, ctx.log);
1068
2770
  if (pushed.code !== EXIT.OK)
1069
2771
  throw new Stop(
1070
2772
  EXIT_PUSH_FAILED,
@@ -1099,6 +2801,11 @@ async function landPr(
1099
2801
  ctx.emit({ stage: "merge", prNumber: Number(prNumber), subject, body: "" });
1100
2802
  return EXIT.USE_MCP;
1101
2803
  }
2804
+ if (merged.code === EXIT_BASE_NOT_DEV)
2805
+ throw new Stop(
2806
+ EXIT_LAND_STOPPED,
2807
+ `PR ${prNumber} does not target ${DEV} — bkit merges into ${DEV} only, releases stay manual; nothing merged, PR left open`,
2808
+ );
1102
2809
  if (merged.out.merged) {
1103
2810
  sha = merged.out.mergeCommitOid ?? "";
1104
2811
  break;
@@ -1114,10 +2821,10 @@ async function landPr(
1114
2821
  EXIT_LAND_STOPPED,
1115
2822
  `PR ${prNumber} still not merged after ${attempt} tries — left open; merge it, then re-run with --pr=${prNumber} --merged-sha=<merge commit>`,
1116
2823
  );
1117
- updateBranch(root, prNumber, ctx.log);
2824
+ await mergeDevIntoPrBranch(root, o.branch, ctx.log);
1118
2825
  const wait = landBackoffMs(attempt);
1119
2826
  ctx.log(
1120
- `PR ${prNumber} not merged on try ${attempt} of ${TIMEOUTS.LAND_ATTEMPTS} — branch updated from dev; trying again in ${(wait / 1000).toFixed(1)}s`,
2827
+ `PR ${prNumber} not merged on try ${attempt} of ${TIMEOUTS.LAND_ATTEMPTS} — trying again in ${(wait / 1000).toFixed(1)}s`,
1121
2828
  );
1122
2829
  await sleep(wait);
1123
2830
  }
@@ -1129,7 +2836,7 @@ async function landPr(
1129
2836
  }
1130
2837
  if (sha === "")
1131
2838
  throw new Stop(EXIT_LAND_STOPPED, `could not resolve the landed SHA for PR ${prNumber}`);
1132
- if (!runGit(root, ["fetch", REMOTE, DEV]).ok)
2839
+ if (!fetchDev(root).ok)
1133
2840
  throw new Stop(EXIT_LAND_STOPPED, "fetch of origin/dev after the merge failed");
1134
2841
  return { shape: "pr", transport, sha, prNumber: Number(prNumber), pushAttempts: 0 };
1135
2842
  }
@@ -1137,10 +2844,11 @@ async function landPr(
1137
2844
  /**
1138
2845
  * Bring local dev up to `sha` when that is a pure fast-forward — `merge
1139
2846
  * --ff-only` when the main checkout is on dev, else move the branch pointer
1140
- * alone; nothing is checked out or pushed. Local commits origin/dev lacks (listed
1141
- * with the command that publishes them), or git refusing (an uncommitted edit the
1142
- * move would overwrite, dev checked out in another worktree), skip it with a log
1143
- * line: what landed is on origin/dev either way.
2847
+ * alone; nothing is checked out or pushed. Local dev already past `sha` and on
2848
+ * origin/dev (a later landing fast-forwarded it) is current. Local commits
2849
+ * origin/dev lacks (listed with the command that publishes them), or git refusing
2850
+ * (an uncommitted edit the move would overwrite, dev checked out in another
2851
+ * worktree), skip it with a log line: what landed is on origin/dev either way.
1144
2852
  */
1145
2853
  function fastForwardDev(
1146
2854
  root: string,
@@ -1150,8 +2858,11 @@ function fastForwardDev(
1150
2858
  const local = git(root, ["rev-parse", "-q", "--verify", `refs/heads/${DEV}`]);
1151
2859
  if (local === null) return "none";
1152
2860
  if (local === sha) return "current";
1153
- if (!runGit(root, ["merge-base", "--is-ancestor", local, sha]).ok) {
1154
- const ahead = (git(root, ["log", "--format=%h %s", `${sha}..${local}`]) ?? "")
2861
+ const isAncestor = (a: string, b: string) =>
2862
+ runGit(root, ["merge-base", "--is-ancestor", a, b]).ok;
2863
+ if (!isAncestor(local, sha)) {
2864
+ if (isAncestor(sha, local) && isAncestor(local, UPSTREAM)) return "current";
2865
+ const ahead = (git(root, ["log", "--format=%h %s", `${UPSTREAM}..${local}`]) ?? "")
1155
2866
  .split("\n")
1156
2867
  .filter((l) => l !== "");
1157
2868
  log(`local ${DEV} has ${ahead.length} commit(s) ${UPSTREAM} does not — not fast-forwarded:`);
@@ -1198,11 +2909,41 @@ function notOnDev(root: string, branch: string): string[] {
1198
2909
  });
1199
2910
  }
1200
2911
 
1201
- /** Uncommitted or untracked files in the feature worktree; [] when there is no worktree. */
2912
+ /**
2913
+ * Those of `paths` whose content at `spec(p)` is already local `dev`'s: work the
2914
+ * branch carries because `dev` is unpushed, not work a run in this branch made.
2915
+ * `spec` names the side to compare — the index (`:path`) or a commit (`ref:path`).
2916
+ */
2917
+ function localDevCopies(root: string, paths: string[], spec: (p: string) => string): string[] {
2918
+ if (git(root, ["rev-parse", "-q", "--verify", `refs/heads/${DEV}`]) === null) return [];
2919
+ return paths.filter((p) => {
2920
+ const at = git(root, ["rev-parse", "-q", "--verify", `${DEV}:${p}`]);
2921
+ return at !== null && at === git(root, ["rev-parse", "-q", "--verify", spec(p)]);
2922
+ });
2923
+ }
2924
+
2925
+ /**
2926
+ * What a close refusal adds when some of the paths it names are unpushed `dev`'s
2927
+ * own content: the branch inherited them, and publishing `dev` is what unblocks
2928
+ * the close. Empty when none are, so the refusal reads as it did before.
2929
+ */
2930
+ function unpushedDevCause(root: string, inherited: number, total: number, then: string): string {
2931
+ if (inherited === 0) return "";
2932
+ const ahead = git(root, ["rev-list", "--count", `${UPSTREAM}..${DEV}`]) ?? "?";
2933
+ const tip = git(root, ["rev-parse", "--short", DEV]) ?? DEV;
2934
+ const which = inherited === total ? "all of them" : `${inherited} of them`;
2935
+ 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}`;
2936
+ }
2937
+
2938
+ /**
2939
+ * Uncommitted or untracked files in the feature worktree; [] when there is no
2940
+ * worktree. The worktree copy entries setup copied in (`copyExcludes`) are never
2941
+ * committed, so they are not work left behind.
2942
+ */
1202
2943
  function uncommitted(root: string, fid: string): string[] {
1203
2944
  const wt = worktreeDir(root, fid);
1204
2945
  if (!fs.existsSync(wt)) return [];
1205
- const status = runGit(wt, ["status", "--porcelain", "-uall"]);
2946
+ const status = runGit(wt, ["status", "--porcelain", "-uall", "--", ".", ...copyExcludes(wt)]);
1206
2947
  if (!status.ok) return [`git status in ${wt} failed: ${status.stderr}`];
1207
2948
  return status.stdout.split("\n").filter((l) => l !== "");
1208
2949
  }
@@ -1214,13 +2955,6 @@ async function landVerb(ctx: RunContext): Promise<number> {
1214
2955
  const fid = String(ctx.flags.fid);
1215
2956
  const root = repoRoot(ctx.cwd);
1216
2957
  const month = resolveMonth(root, fid, str(ctx.flags.month));
1217
- // `bkit install` can leave core.bare=true on the main checkout, which breaks every worktree below.
1218
- if (
1219
- git(root, ["config", "--get", "core.bare"]) === "true" &&
1220
- fs.statSync(path.join(root, ".git"), { throwIfNoEntry: false })?.isDirectory()
1221
- ) {
1222
- runGit(root, ["config", "core.bare", "false"]);
1223
- }
1224
2958
  const worktreeStatus = path.join(
1225
2959
  git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root,
1226
2960
  "docs",
@@ -1248,7 +2982,7 @@ async function landVerb(ctx: RunContext): Promise<number> {
1248
2982
  }));
1249
2983
  if (typeof landed === "number") return landed;
1250
2984
 
1251
- runGit(root, ["fetch", REMOTE, DEV]);
2985
+ fetchDev(root);
1252
2986
  const localDev = devPushes ? fastForwardDev(root, landed.sha, ctx.log) : null;
1253
2987
 
1254
2988
  // The audit: canonical docs on origin/dev, the landed body clean, the transport recorded.
@@ -1286,11 +3020,13 @@ async function landVerb(ctx: RunContext): Promise<number> {
1286
3020
  `canonical ${workflow} missing on ${UPSTREAM}: ${missing.join(", ")}`,
1287
3021
  );
1288
3022
  const notLanded = notOnDev(root, branch);
1289
- if (notLanded.length)
3023
+ if (notLanded.length) {
3024
+ const inherited = localDevCopies(root, notLanded, (p) => `${branch}:${p}`);
1290
3025
  throw new Stop(
1291
3026
  EXIT_LANDED_UNVERIFIED,
1292
- `${branch} carries work ${UPSTREAM} does not — ${branch} and its worktree kept:\n${notLanded.join("\n")}`,
3027
+ `${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.")}`,
1293
3028
  );
3029
+ }
1294
3030
 
1295
3031
  let worktree: Record<string, unknown> | null = null;
1296
3032
  const left = devPushes ? uncommitted(root, fid) : [];
@@ -1425,80 +3161,372 @@ export const branchesCommand: CommandSpec = {
1425
3161
  noun: "branches",
1426
3162
  summary: "Sync, push, land and rebase branches; stamp and read a doc's base-commit anchor.",
1427
3163
  verbs: {
3164
+ parse: {
3165
+ summary: "Read an explicitly named or existing branch from the session prompt.",
3166
+ use: "workflow",
3167
+ flags: [
3168
+ { name: "prompt-file", type: "string", required: true, help: "session prompt" },
3169
+ {
3170
+ name: "workflow",
3171
+ type: "string",
3172
+ help: "debug: validate an explicit debug adoption request",
3173
+ },
3174
+ ],
3175
+ output: {
3176
+ branch: "one existing branch, or null",
3177
+ via: "explicit | token | null",
3178
+ where: "local | remote | both | null",
3179
+ },
3180
+ exitCodes: {
3181
+ 3: "an explicit branch is invalid or absent",
3182
+ 8: "multiple branches were named",
3183
+ },
3184
+ run: (ctx) => {
3185
+ if (ctx.flags.workflow !== undefined && ctx.flags.workflow !== "debug")
3186
+ throw new CommandError(EXIT.USAGE, "--workflow must be debug");
3187
+ const prompt = fs.readFileSync(path.resolve(ctx.cwd, String(ctx.flags.promptFile)), "utf8");
3188
+ const candidates = new Map<string, { via: string; where: string }>();
3189
+ for (const token of prompt.split(/\s+/)) {
3190
+ const explicit = token.startsWith("branch=");
3191
+ const branch = explicit ? token.slice("branch=".length) : token;
3192
+ if (!explicit && (!branch.includes("/") || /^[a-z][a-z0-9+.-]*:\/\//i.test(branch)))
3193
+ continue;
3194
+ const valid = runGit(ctx.cwd, ["check-ref-format", "--branch", branch]).ok;
3195
+ const local =
3196
+ valid &&
3197
+ runGit(ctx.cwd, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]).ok;
3198
+ const remote =
3199
+ valid &&
3200
+ runGit(ctx.cwd, ["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`])
3201
+ .ok;
3202
+ if (!local && !remote) {
3203
+ if (explicit)
3204
+ throw new CommandError(3, `branch ${branch} is invalid or does not exist`);
3205
+ continue;
3206
+ }
3207
+ candidates.set(branch, {
3208
+ via: explicit ? "explicit" : "token",
3209
+ where: local && remote ? "both" : local ? "local" : "remote",
3210
+ });
3211
+ }
3212
+ if (candidates.size > 1)
3213
+ throw new CommandError(
3214
+ 8,
3215
+ `multiple branch selections: ${[...candidates.keys()].join(", ")}`,
3216
+ );
3217
+ const selected = [...candidates.entries()][0];
3218
+ ctx.emit(
3219
+ selected
3220
+ ? { branch: selected[0], ...selected[1] }
3221
+ : { branch: null, via: null, where: null },
3222
+ );
3223
+ return EXIT.OK;
3224
+ },
3225
+ },
1428
3226
  sync: {
1429
- summary: `Fetch ${UPSTREAM}; report whether it is an ancestor of HEAD (Path A/B) and how far docs/ is behind; optionally merge it in.`,
3227
+ 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.`,
3228
+ use: "workflow",
1430
3229
  flags: [
1431
3230
  {
1432
3231
  name: "head",
1433
3232
  type: "string",
1434
3233
  help: "commit to compare (default HEAD), e.g. ship's ENTRY_HEAD",
1435
3234
  },
3235
+ {
3236
+ name: "merge",
3237
+ type: "boolean",
3238
+ 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`,
3239
+ },
1436
3240
  {
1437
3241
  name: "merge-docs",
1438
3242
  type: "boolean",
1439
- help: `on a feature branch whose docs/ is behind, merge ${UPSTREAM} (ledgers union, other docs/ take ${DEV}, anything else aborts)`,
3243
+ 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`,
3244
+ },
3245
+ {
3246
+ name: "fid",
3247
+ type: "string",
3248
+ help: "--merge: the feature id in the commit messages (default: the branch name without feat/)",
3249
+ },
3250
+ {
3251
+ name: "file",
3252
+ type: "string",
3253
+ 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)",
3254
+ },
3255
+ {
3256
+ name: "sentinel",
3257
+ type: "string",
3258
+ help: "--merge: file removed at start and created on refusal, e.g. logs/{FID}/.rebase-failed",
1440
3259
  },
1441
3260
  ],
1442
3261
  output: {
1443
3262
  branch: "current branch (null when detached)",
1444
- head: "commit compared (after a merge: the merge commit)",
3263
+ head: "commit compared (after a merge: the new HEAD)",
1445
3264
  basePath: `A when ${UPSTREAM} is an ancestor of head (nothing to integrate), else B`,
1446
3265
  behind: `commits on ${UPSTREAM} not in head`,
1447
- docsBehind: `of those, commits touching docs/`,
1448
- merged: `true when --merge-docs merged ${UPSTREAM}`,
1449
- resolved: "conflicts the merge resolved: [{path, how: union|dev}]",
3266
+ docsBehind: `of those, commits touching docs/ or a ledger path (LEDGERS)`,
3267
+ merged: `true when --merge or --merge-docs merged ${UPSTREAM}`,
3268
+ resolved:
3269
+ "conflicts the merge resolved: [{path, how: union|lockfile|register|embed|record|dev}]",
3270
+ rebuilt:
3271
+ "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)",
3272
+ generated:
3273
+ "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)",
3274
+ outcome: `--merge: merged | current (${UPSTREAM} already an ancestor; nothing done) | pending (conflicts left for a hand resolution, merge in progress) | refused (merge aborted)`,
3275
+ carried:
3276
+ "--merge: the commit that carried the uncommitted work before the merge (null when the tree was clean)",
3277
+ pending: "--merge: the paths left conflicted for a hand resolution (empty otherwise)",
3278
+ aborted: "--merge: a refused merge was aborted",
3279
+ sentinel: "--merge: the sentinel written on refusal (null otherwise)",
1450
3280
  },
1451
3281
  exitCodes: {
1452
- [EXIT_DETACHED]: "--merge-docs with no branch checked out",
3282
+ [EXIT_REFUSED]: "--merge: the uncommitted work could not be committed before the merge",
3283
+ [EXIT_DETACHED]: "--merge / --merge-docs with no branch checked out",
1453
3284
  [EXIT_FETCH_FAILED]: `git fetch ${REMOTE} ${DEV} failed`,
1454
- [EXIT_MERGE_CONFLICT]:
1455
- "the docs merge conflicted outside docs/ or could not be committed; merge aborted",
3285
+ [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`,
3286
+ [EXIT_HAND_RESOLVE]:
3287
+ "--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",
3288
+ [EXIT_GENERATE_FAILED]:
3289
+ "bkit:generate failed after the merge, or its output could not be committed; the merge commit stays",
1456
3290
  },
1457
3291
  run: syncVerb,
1458
3292
  },
3293
+ regenerate: {
3294
+ summary:
3295
+ "Run a declared bkit:generate on the feature branch and commit only the paths it changed (ship Step 10's fix round).",
3296
+ use: "workflow",
3297
+ flags: [
3298
+ {
3299
+ name: "fid",
3300
+ type: "string",
3301
+ help: "the feature id in the commit message (default: the branch name without feat/)",
3302
+ },
3303
+ {
3304
+ name: "attempt",
3305
+ type: "string",
3306
+ help: "ship Step 10's merge round: the commit is fix({FID}): regenerate attempt {N}; without it, chore({FID}): regenerate before re-validating",
3307
+ },
3308
+ {
3309
+ name: "file",
3310
+ type: "string",
3311
+ help: "the run's status.jsonl: a commit appends an engine-action row (action regenerate, key regenerate/{old tip}, ref the new HEAD)",
3312
+ },
3313
+ ],
3314
+ output: {
3315
+ outcome:
3316
+ "committed (bkit:generate changed paths; committed) | unchanged (it changed nothing) | undeclared (no bkit:generate script; nothing run)",
3317
+ head: "HEAD after the verb (the regenerate commit when committed)",
3318
+ paths: "the paths bkit:generate changed and the commit carries (empty otherwise)",
3319
+ },
3320
+ exitCodes: {
3321
+ [EXIT_DETACHED]: "no branch checked out",
3322
+ [EXIT_GENERATE_FAILED]:
3323
+ "bkit:generate failed, changed a path that already held uncommitted changes, or its output could not be committed; nothing committed",
3324
+ },
3325
+ run: regenerateVerb,
3326
+ },
1459
3327
  push: {
1460
3328
  summary:
1461
- "Push the current branch with exactly one git push: plain for dev/main, --force-with-lease otherwise.",
3329
+ "Push the current branch with exactly one git push: plain for dev/main, --force-with-lease otherwise; 81 tests lock held.",
3330
+ use: "workflow",
1462
3331
  flags: [
1463
3332
  {
1464
3333
  name: "mode",
1465
3334
  type: "string",
1466
3335
  required: true,
1467
- help: "feature (a step's push) | abort (Failure Path: never into an open PR) | dev (the checkout must be on dev)",
3336
+ 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)",
1468
3337
  },
1469
3338
  { name: "set-upstream", type: "boolean", help: "push with -u" },
3339
+ {
3340
+ name: "ahead-of",
3341
+ type: "string",
3342
+ help: "--mode=plain: refuse (21) when HEAD has no commits beyond this ref; an origin/<branch> ref is fetched first",
3343
+ },
3344
+ {
3345
+ name: "commit",
3346
+ type: "string",
3347
+ 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",
3348
+ },
3349
+ {
3350
+ name: "label",
3351
+ type: "string",
3352
+ repeatable: true,
3353
+ help: "--commit: the issue's labels, one per flag",
3354
+ },
3355
+ { name: "file", type: "string", help: "--commit: status.jsonl for the engine-action row" },
3356
+ { name: "workflow", type: "string", help: "--commit: the workflow, for the run number" },
1470
3357
  {
1471
3358
  name: "require-ci",
1472
3359
  type: "boolean",
1473
- help: "this push must start a CI run: refuse when the HEAD message carries a skip-CI token",
3360
+ 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`,
1474
3361
  },
1475
3362
  {
1476
3363
  name: "open-pr",
1477
3364
  type: "string",
1478
3365
  help: "--mode=abort: the open-PR answer from MCP (a number, or none) instead of asking gh",
1479
3366
  },
3367
+ {
3368
+ name: "fid",
3369
+ type: "string",
3370
+ 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",
3371
+ },
1480
3372
  ],
1481
3373
  output: {
1482
3374
  pushed: "true when the push ran and succeeded",
3375
+ lockHolder: "the tests-lock holder on exit 81 (null otherwise)",
3376
+ replayed:
3377
+ "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",
1483
3378
  ref: "the branch pushed — link handover artifacts to this ref; null when nothing was pushed",
1484
3379
  sha: "HEAD commit pushed (null when not pushed)",
1485
3380
  forced: "true when pushed with --force-with-lease",
1486
- skipped: "why the push did not run: open-pr | skip-ci (null otherwise)",
3381
+ skipped:
3382
+ "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)",
1487
3383
  prNumber: "the open PR that stopped an abort push (null otherwise)",
3384
+ mergedDev: `--require-ci: ${UPSTREAM} was merged in before the push`,
3385
+ commit: "--commit: the marker commit's sha",
3386
+ deduped: "--commit: the marker commit was already made this run (not made again)",
1488
3387
  },
1489
3388
  exitCodes: {
3389
+ 4: "the pre-push hook could not acquire the tests lock",
1490
3390
  [EXIT_DETACHED]: "no branch checked out",
3391
+ [EXIT_NOTHING_TO_PUSH]:
3392
+ "--mode=plain or --commit on dev / main, or --ahead-of and HEAD has no commits beyond it",
1491
3393
  [EXIT_SKIP_CI]: "--require-ci and the HEAD message carries a skip-CI token",
1492
3394
  [EXIT_OPEN_PR]:
1493
3395
  "--mode=abort and the branch has an open PR: push skipped, remote HEAD kept",
1494
- [EXIT_PUSH_FAILED]: "git push failed",
3396
+ [EXIT_PUSH_FAILED]:
3397
+ "git push failed, or dev refused a replayed push (in-place run on dev: the refusal is printed)",
1495
3398
  [EXIT_NOT_DEV]: "--mode=dev and the checkout is not on dev",
3399
+ [EXIT_NO_RECORD]:
3400
+ "--mode=dev, or --fid, on dev with no shared-checkout record for the run: nothing pushed",
3401
+ [EXIT_FETCH_FAILED]:
3402
+ "fetching origin/dev failed (in-place run on dev, or a --require-ci feature push); nothing pushed",
3403
+ [EXIT_MERGE_CONFLICT]:
3404
+ "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",
3405
+ [EXIT_GENERATE_FAILED]:
3406
+ "--require-ci feature push: bkit:generate failed after merging origin/dev; nothing pushed",
1496
3407
  },
1497
3408
  run: pushVerb,
1498
3409
  },
3410
+ "fast-forward": {
3411
+ summary: "Fetch a remote branch and fast-forward the checkout onto it; refuse when diverged.",
3412
+ use: "workflow",
3413
+ flags: [
3414
+ {
3415
+ name: "onto",
3416
+ type: "string",
3417
+ required: true,
3418
+ help: "the ref to fast-forward onto; an origin/<branch> ref is fetched first",
3419
+ },
3420
+ ],
3421
+ output: { moved: "HEAD moved", head: "HEAD after" },
3422
+ exitCodes: {
3423
+ [EXIT_FETCH_FAILED]: "fetching --onto failed, or it does not resolve",
3424
+ [EXIT_DIVERGED]: "the checkout has commits --onto lacks: nothing moved",
3425
+ },
3426
+ run: fastForwardVerb,
3427
+ },
3428
+ "scan-diff": {
3429
+ summary:
3430
+ "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.",
3431
+ use: "by-hand",
3432
+ flags: [
3433
+ {
3434
+ name: "base",
3435
+ type: "string",
3436
+ required: true,
3437
+ help: "diff <base>...HEAD; an origin/<branch> base is fetched first",
3438
+ },
3439
+ {
3440
+ name: "paths",
3441
+ type: "string",
3442
+ help: "a changed path matches this pattern (case-insensitive)",
3443
+ },
3444
+ {
3445
+ name: "marker",
3446
+ type: "string",
3447
+ help: "an added line carries this text, outside docs/plans",
3448
+ },
3449
+ {
3450
+ name: "code",
3451
+ type: "boolean",
3452
+ help: "a path changed outside docs/plans, docs/*.jsonl and .bkit/*.jsonl",
3453
+ },
3454
+ {
3455
+ name: "disabled-tests",
3456
+ type: "boolean",
3457
+ 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",
3458
+ },
3459
+ {
3460
+ name: "expect-none",
3461
+ type: "boolean",
3462
+ help: "invert the exit: 0 when nothing matched, 1 (naming the paths on stderr) when something did",
3463
+ },
3464
+ ],
3465
+ output: {
3466
+ found: "something matched",
3467
+ paths: "the matching paths",
3468
+ disabled:
3469
+ "[{file, line, test}]: unmatched added disabling markers and removed assertion occurrences, attributed to their original test (only with --disabled-tests)",
3470
+ },
3471
+ exitCodes: {
3472
+ [EXIT_DIFF_FAILED]: "--base does not resolve, or git diff failed",
3473
+ },
3474
+ run: scanDiffVerb,
3475
+ },
3476
+ "force-build": {
3477
+ summary: `Force a full CI build: put ${FORCE_BUILD} on the open PR's title, then push an empty marker commit (once per run).`,
3478
+ use: "workflow",
3479
+ flags: [
3480
+ { name: "fid", type: "string", required: true, help: "feature id, for the commit subject" },
3481
+ {
3482
+ name: "file",
3483
+ type: "string",
3484
+ required: true,
3485
+ help: "status.jsonl for the engine-action row",
3486
+ },
3487
+ {
3488
+ name: "workflow",
3489
+ type: "string",
3490
+ required: true,
3491
+ help: "the workflow, for the run number",
3492
+ },
3493
+ {
3494
+ name: "label",
3495
+ type: "string",
3496
+ repeatable: true,
3497
+ help: "the issue's labels; bkit:auto adds ` bkit [auto route]` to the commit",
3498
+ },
3499
+ {
3500
+ name: "open-pr",
3501
+ type: "string",
3502
+ help: "the open-PR answer from MCP (a number, or none) instead of asking gh",
3503
+ },
3504
+ {
3505
+ name: "title-set",
3506
+ type: "boolean",
3507
+ help: "the title is handled (set through MCP, or no PR is open): skip gh",
3508
+ },
3509
+ ],
3510
+ output: {
3511
+ prNumber: "the open PR whose title was checked, or null",
3512
+ titleChanged: `the title gained ${FORCE_BUILD}`,
3513
+ commit: "the marker commit's sha",
3514
+ deduped: "the marker commit was already made this run",
3515
+ pushed: "the push ran and succeeded",
3516
+ ref: "the branch pushed",
3517
+ sha: "HEAD pushed",
3518
+ },
3519
+ exitCodes: {
3520
+ [EXIT_DETACHED]: "no branch checked out",
3521
+ [EXIT_NOTHING_TO_PUSH]: "on dev / main",
3522
+ [EXIT_PUSH_FAILED]: "git commit or git push failed",
3523
+ },
3524
+ run: forceBuildVerb,
3525
+ },
1499
3526
  rebase: {
1500
3527
  summary:
1501
- "Drive a rebase to completion, auto-resolving ledger (union) and lockfile (regenerate) conflicts; refuse and abort on anything else.",
3528
+ "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.",
3529
+ use: "workflow",
1502
3530
  flags: [
1503
3531
  {
1504
3532
  name: "log-file",
@@ -1510,14 +3538,21 @@ export const branchesCommand: CommandSpec = {
1510
3538
  type: "string",
1511
3539
  help: "file removed at start and created on refusal, e.g. logs/{FID}/.rebase-failed",
1512
3540
  },
3541
+ {
3542
+ name: "file",
3543
+ type: "string",
3544
+ help: "the run's status.jsonl: a completed rebase appends an engine-action row (action rebase, key rebase/{old tip}, ref the new HEAD)",
3545
+ },
1513
3546
  ],
1514
3547
  output: {
1515
3548
  outcome: "resolved | refused (a refused rebase is aborted)",
1516
- resolved: "conflicts resolved: [{path, how: union|lockfile}]",
3549
+ resolved: "conflicts resolved: [{path, how: union|lockfile|register|embed|record}]",
3550
+ rebuilt:
3551
+ "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)",
1517
3552
  skippedCommits: "commits skipped because resolution emptied them",
1518
3553
  rounds: "resolve rounds run",
1519
3554
  refused: "the path that stopped resolution (null when none, or not path-specific)",
1520
- reason: "why resolution refused (null on success)",
3555
+ reason: "why resolution refused or stopped (null on success)",
1521
3556
  aborted: "a refused rebase was aborted (false on success, or when the abort failed)",
1522
3557
  sentinel: "the sentinel written on refusal (null otherwise)",
1523
3558
  },
@@ -1530,6 +3565,7 @@ export const branchesCommand: CommandSpec = {
1530
3565
  "sync-dev": {
1531
3566
  summary:
1532
3567
  "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.",
3568
+ use: "workflow",
1533
3569
  flags: [],
1534
3570
  output: {
1535
3571
  devLocal:
@@ -1547,6 +3583,7 @@ export const branchesCommand: CommandSpec = {
1547
3583
  land: {
1548
3584
  summary:
1549
3585
  "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.",
3586
+ use: "workflow",
1550
3587
  flags: [
1551
3588
  { name: "workflow", type: "string", required: true, help: "design | plan" },
1552
3589
  { name: "fid", type: "string", required: true, help: "feature id" },
@@ -1592,7 +3629,7 @@ export const branchesCommand: CommandSpec = {
1592
3629
  "dev moved before every one of LAND_ATTEMPTS pushes, or the PR branch push failed (nothing landed)",
1593
3630
  [EXIT_FETCH_FAILED]: `git fetch ${REMOTE} ${DEV} failed (nothing landed)`,
1594
3631
  [EXIT_LAND_STOPPED]:
1595
- "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)",
3632
+ "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)",
1596
3633
  [EXIT_LANDED_UNVERIFIED]:
1597
3634
  "landed, but the body scan, transport cross-check or canonical-on-dev check failed",
1598
3635
  [EXIT_LOCK_LEFT]: "landed and audited, but the workflow lock file survived removal",
@@ -1602,6 +3639,7 @@ export const branchesCommand: CommandSpec = {
1602
3639
  "anchor-stamp": {
1603
3640
  summary:
1604
3641
  "Put a <!-- bkit:anchor --> block recording the base commit and bkit release on top of a design/plan doc or audit report (idempotent).",
3642
+ use: "workflow",
1605
3643
  flags: [
1606
3644
  { name: "file", type: "string", required: true, help: "doc to stamp (must exist)" },
1607
3645
  {
@@ -1642,6 +3680,7 @@ export const branchesCommand: CommandSpec = {
1642
3680
  "anchor-read": {
1643
3681
  summary:
1644
3682
  "Read a doc's anchor fields; with --against, decide whether anything landed since its baseSha.",
3683
+ use: "by-hand",
1645
3684
  flags: [
1646
3685
  { name: "file", type: "string", required: true, help: "design/plan doc or audit report" },
1647
3686
  {