@cbartens/bkit 6.0.0 → 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 (375) hide show
  1. package/.bkit/README.md +154 -151
  2. package/.bkit/core/.agents/context.md +95 -29
  3. package/.bkit/core/.agents/docs.md +17 -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 +108 -107
  9. package/.bkit/core/.agents/skills.md +63 -15
  10. package/.bkit/core/.bkit/README.md +154 -151
  11. package/.bkit/core/.bkit/authoring.md +714 -84
  12. package/.bkit/core/.bkit/cli.md +407 -0
  13. package/.bkit/core/.bkit/cloud.md +281 -193
  14. package/.bkit/core/.bkit/comparison.md +43 -41
  15. package/.bkit/core/.bkit/install.md +154 -84
  16. package/.bkit/core/.bkit/jsonl.md +193 -130
  17. package/.bkit/core/.bkit/pipeline.md +114 -114
  18. package/.bkit/core/.bkit/prompts.md +272 -165
  19. package/.bkit/core/.bkit/providers.md +457 -271
  20. package/.bkit/core/.bkit/router.md +69 -0
  21. package/.bkit/core/.bkit/templates.md +529 -256
  22. package/.bkit/core/.bkit/trackers.md +80 -52
  23. package/.bkit/core/.bkit/workflows.md +589 -504
  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 +5 -73
  33. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +127 -105
  34. package/.bkit/core/docs/templates/bkit-audit-adoption.md +104 -70
  35. package/.bkit/core/docs/templates/bkit-audit-agents.md +94 -72
  36. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +99 -78
  37. package/.bkit/core/docs/templates/bkit-audit-analytics.md +140 -82
  38. package/.bkit/core/docs/templates/bkit-audit-annotations.md +98 -72
  39. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +121 -96
  40. package/.bkit/core/docs/templates/bkit-audit-app-store.md +157 -76
  41. package/.bkit/core/docs/templates/bkit-audit-architecture.md +113 -71
  42. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +75 -72
  43. package/.bkit/core/docs/templates/bkit-audit-config.md +122 -76
  44. package/.bkit/core/docs/templates/bkit-audit-cost.md +85 -74
  45. package/.bkit/core/docs/templates/bkit-audit-coverage.md +75 -68
  46. package/.bkit/core/docs/templates/bkit-audit-database.md +101 -70
  47. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +164 -83
  48. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +115 -86
  49. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +264 -88
  50. package/.bkit/core/docs/templates/bkit-audit-documentation.md +118 -93
  51. package/.bkit/core/docs/templates/bkit-audit-duplication.md +139 -86
  52. package/.bkit/core/docs/templates/bkit-audit-failures.md +110 -81
  53. package/.bkit/core/docs/templates/bkit-audit-flakes.md +99 -74
  54. package/.bkit/core/docs/templates/bkit-audit-gates.md +105 -77
  55. package/.bkit/core/docs/templates/bkit-audit-issues.md +104 -80
  56. package/.bkit/core/docs/templates/bkit-audit-llm.md +131 -58
  57. package/.bkit/core/docs/templates/bkit-audit-logs.md +123 -100
  58. package/.bkit/core/docs/templates/bkit-audit-models.md +98 -53
  59. package/.bkit/core/docs/templates/bkit-audit-privacy.md +56 -52
  60. package/.bkit/core/docs/templates/bkit-audit-prompts.md +63 -54
  61. package/.bkit/core/docs/templates/bkit-audit-red-team.md +124 -68
  62. package/.bkit/core/docs/templates/bkit-audit-reliability.md +95 -70
  63. package/.bkit/core/docs/templates/bkit-audit-repo.md +169 -73
  64. package/.bkit/core/docs/templates/bkit-audit-security.md +206 -96
  65. package/.bkit/core/docs/templates/bkit-audit-slop.md +77 -70
  66. package/.bkit/core/docs/templates/bkit-audit-testing.md +162 -114
  67. package/.bkit/core/docs/templates/bkit-audit-usability.md +113 -71
  68. package/.bkit/core/docs/templates/bkit-plan.md +138 -132
  69. package/.bkit/core/engine/checks/after/auth.ts +40 -37
  70. package/.bkit/core/engine/checks/after/ci-yml.ts +65 -2
  71. package/.bkit/core/engine/checks/after/index.ts +12 -2
  72. package/.bkit/core/engine/checks/after/tools.ts +80 -33
  73. package/.bkit/core/engine/checks/before/context-fetch.ts +227 -33
  74. package/.bkit/core/engine/checks/before/env.ts +1 -1
  75. package/.bkit/core/engine/checks/before/index.ts +7 -0
  76. package/.bkit/core/engine/checks/before/repo.ts +40 -0
  77. package/.bkit/core/engine/checks/status-holes.ts +916 -123
  78. package/.bkit/core/engine/checks/tips/catalogue.ts +68 -17
  79. package/.bkit/core/engine/checks/tips/detect.ts +32 -0
  80. package/.bkit/core/engine/checks/tips/index.ts +47 -6
  81. package/.bkit/core/engine/cli.ts +238 -84
  82. package/.bkit/core/engine/commands/analysis.ts +128 -76
  83. package/.bkit/core/engine/commands/ci/ci.ts +363 -29
  84. package/.bkit/core/engine/commands/ci/pins.ts +172 -0
  85. package/.bkit/core/engine/commands/ci/push-gate.ts +223 -0
  86. package/.bkit/core/engine/commands/install/uninstall.ts +21 -27
  87. package/.bkit/core/engine/commands/install/upgrade.ts +32 -15
  88. package/.bkit/core/engine/commands/land.ts +126 -11
  89. package/.bkit/core/engine/commands/lib.ts +303 -6
  90. package/.bkit/core/engine/commands/registry.ts +6 -2
  91. package/.bkit/core/engine/commands/setup/setup.ts +1 -0
  92. package/.bkit/core/engine/commands/stats.ts +91 -35
  93. package/.bkit/core/engine/commands/workflow/branches.ts +1477 -117
  94. package/.bkit/core/engine/commands/workflow/challenge.ts +114 -39
  95. package/.bkit/core/engine/commands/workflow/completeness.ts +109 -0
  96. package/.bkit/core/engine/commands/workflow/context.ts +433 -55
  97. package/.bkit/core/engine/commands/workflow/counters.ts +244 -39
  98. package/.bkit/core/engine/commands/workflow/decisions.ts +61 -17
  99. package/.bkit/core/engine/commands/workflow/disk.ts +237 -55
  100. package/.bkit/core/engine/commands/workflow/fids.ts +19 -1
  101. package/.bkit/core/engine/commands/workflow/issues.ts +6 -0
  102. package/.bkit/core/engine/commands/workflow/ledgers.ts +458 -18
  103. package/.bkit/core/engine/commands/workflow/locks.ts +2 -0
  104. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +124 -15
  105. package/.bkit/core/engine/commands/workflow/plans.ts +257 -0
  106. package/.bkit/core/engine/commands/workflow/prs.ts +12 -3
  107. package/.bkit/core/engine/commands/workflow/repo.ts +8 -0
  108. package/.bkit/core/engine/commands/workflow/roadmap.ts +56 -15
  109. package/.bkit/core/engine/commands/workflow/run-facts.ts +22 -31
  110. package/.bkit/core/engine/commands/workflow/runs.ts +652 -34
  111. package/.bkit/core/engine/commands/workflow/runtime.ts +3 -0
  112. package/.bkit/core/engine/commands/workflow/skills.ts +1 -0
  113. package/.bkit/core/engine/commands/workflow/status.ts +200 -17
  114. package/.bkit/core/engine/commands/workflow/step-table.ts +75 -33
  115. package/.bkit/core/engine/commands/workflow/steps.ts +635 -24
  116. package/.bkit/core/engine/commands/workflow/summary-findings.ts +177 -0
  117. package/.bkit/core/engine/commands/workflow/summary.ts +192 -46
  118. package/.bkit/core/engine/commands/workflow/tasks.ts +409 -0
  119. package/.bkit/core/engine/commands/workflow/test-blocks.ts +254 -0
  120. package/.bkit/core/engine/commands/workflow/tests-changed.ts +201 -0
  121. package/.bkit/core/engine/commands/workflow/tests.ts +1285 -356
  122. package/.bkit/core/engine/commands/workflow/workflows.ts +228 -43
  123. package/.bkit/core/engine/commands/workflow/worktrees.ts +389 -47
  124. package/.bkit/core/engine/install/cloud-env.ts +251 -121
  125. package/.bkit/core/engine/install/context-ci-workflow.ts +102 -0
  126. package/.bkit/core/engine/install/manifest.ts +60 -12
  127. package/.bkit/core/engine/install/modules/antigravity.ts +3 -2
  128. package/.bkit/core/engine/install/modules/cloud.ts +3 -3
  129. package/.bkit/core/engine/install/modules/codex.ts +15 -2
  130. package/.bkit/core/engine/install/modules/core.ts +956 -52
  131. package/.bkit/core/engine/install/modules/cursor.ts +6 -6
  132. package/.bkit/core/engine/install/modules/opencode.ts +16 -4
  133. package/.bkit/core/engine/install/template-notes.ts +130 -0
  134. package/.bkit/core/engine/install/version-file.ts +3 -2
  135. package/.bkit/core/engine/install/write.ts +5 -0
  136. package/.bkit/core/engine/ledgers/compact.ts +124 -0
  137. package/.bkit/core/engine/ledgers/journal.ts +291 -0
  138. package/.bkit/core/engine/ledgers/status.ts +160 -9
  139. package/.bkit/core/engine/ledgers/telemetry.ts +158 -21
  140. package/.bkit/core/engine/render/hosts.ts +114 -14
  141. package/.bkit/core/engine/shared/bkit-latest.ts +26 -4
  142. package/.bkit/core/engine/shared/dep-updater.ts +60 -0
  143. package/.bkit/core/engine/shared/egress.ts +1 -1
  144. package/.bkit/core/engine/shared/package-manager.ts +9 -0
  145. package/.bkit/core/engine/shared/settings.ts +92 -17
  146. package/.bkit/core/engine/shared/timeouts.ts +2 -0
  147. package/.bkit/core/engine/tools/cli-doc.ts +111 -0
  148. package/.bkit/core/engine/tools/grammar-density.ts +1 -1
  149. package/.bkit/core/engine/tools/instructions-sources.ts +15 -17
  150. package/.bkit/core/engine/tools/instructions.ts +94 -43
  151. package/.bkit/core/hooks/antigravity-hook.js +25 -10
  152. package/.bkit/core/hooks/gateguard-engine.js +53 -29
  153. package/.bkit/core/hooks/guardrails-shell.js +4 -4
  154. package/.bkit/core/hooks/guardrails-tiers.js +3 -3
  155. package/.bkit/core/hooks/preflight-linear.sh +9 -9
  156. package/.bkit/core/hooks/preflight-rules.sh +8 -0
  157. package/.bkit/core/hooks/readguard-engine.js +29 -10
  158. package/.bkit/core/hooks/session-rules-advisory.js +61 -0
  159. package/.bkit/core/prompts/bkit-audit-generate.md +187 -116
  160. package/.bkit/core/prompts/bkit-build-challenge-1.md +56 -37
  161. package/.bkit/core/prompts/bkit-build-challenge-2.md +65 -45
  162. package/.bkit/core/prompts/bkit-build-install-skills.md +38 -29
  163. package/.bkit/core/prompts/bkit-build-plan-convert.md +43 -32
  164. package/.bkit/core/prompts/bkit-build-plan-current.md +49 -39
  165. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +79 -55
  166. package/.bkit/core/prompts/bkit-build-plan-tasks.md +149 -0
  167. package/.bkit/core/prompts/bkit-build-plan-tests.md +120 -0
  168. package/.bkit/core/prompts/bkit-build-plan-verify.md +87 -50
  169. package/.bkit/core/prompts/bkit-debug-abort-handover.md +36 -35
  170. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +96 -64
  171. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +54 -45
  172. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +42 -33
  173. package/.bkit/core/prompts/bkit-debug-failure-soak.md +53 -37
  174. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +35 -30
  175. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +34 -29
  176. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +32 -28
  177. package/.bkit/core/prompts/bkit-design-generate.md +68 -52
  178. package/.bkit/core/prompts/bkit-design-organise.md +73 -35
  179. package/.bkit/core/prompts/bkit-design-review-1.md +58 -54
  180. package/.bkit/core/prompts/bkit-design-review-2.md +54 -50
  181. package/.bkit/core/prompts/bkit-design-spike.md +54 -47
  182. package/.bkit/core/prompts/bkit-design-update.md +42 -31
  183. package/.bkit/core/prompts/bkit-plan-generate.md +76 -58
  184. package/.bkit/core/prompts/bkit-plan-review-1.md +63 -49
  185. package/.bkit/core/prompts/bkit-plan-review-2.md +60 -48
  186. package/.bkit/core/prompts/bkit-plan-scope-check.md +53 -46
  187. package/.bkit/core/prompts/bkit-plan-update.md +70 -52
  188. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +82 -50
  189. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +80 -45
  190. package/.bkit/core/prompts/bkit-ship-update-docs.md +35 -29
  191. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +55 -49
  192. package/.bkit/core/prompts/bkit-utility-update-decisions.md +76 -49
  193. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +70 -41
  194. package/.bkit/core/prompts/bkit-utility-update-documentation.md +33 -30
  195. package/.bkit/core/prompts/bkit-utility-update-failures.md +73 -43
  196. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +77 -50
  197. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +77 -45
  198. package/.bkit/core/prompts/bkit-utility-update-tracker.md +144 -68
  199. package/.bkit/core/workflows/bkit-auto.md +53 -30
  200. package/.bkit/core/workflows/bkit-build.md +635 -304
  201. package/.bkit/core/workflows/bkit-debug.md +301 -148
  202. package/.bkit/core/workflows/bkit-design.md +167 -95
  203. package/.bkit/core/workflows/bkit-plan.md +172 -84
  204. package/.bkit/core/workflows/bkit-ship.md +299 -152
  205. package/.bkit/shared/.agents/plugins/bkit/hooks.json +10 -0
  206. package/.bkit/shared/.claude/bkit-cloud.md +12 -10
  207. package/.bkit/shared/.claude/settings.json +3 -0
  208. package/.bkit/shared/.codex/bkit-cloud.md +98 -0
  209. package/.bkit/shared/.codex/hooks.json +20 -0
  210. package/.bkit/shared/.cursor/bkit-cloud.md +3 -3
  211. package/.bkit/shared/.opencode/opencode.json +1 -1
  212. package/.bkit/shared/CLAUDE.md +5 -1
  213. package/.bkit/shared/GEMINI.md +4 -1
  214. package/.bkit/shared/docs/architecture.md +4 -7
  215. package/.bkit/shared/docs/data-schema.md +4 -7
  216. package/.bkit/shared/docs/deployments.md +239 -166
  217. package/.bkit/shared/docs/design.md +11 -12
  218. package/.bkit/shared/docs/noise.md +8 -7
  219. package/.bkit/shared/docs/observability.md +5 -8
  220. package/.bkit/shared/docs/security.md +35 -17
  221. package/.bkit/shared/docs/setup.md +29 -18
  222. package/.bkit/shared/docs/technology.md +3 -6
  223. package/.bkit/shared/docs/testing.md +282 -176
  224. package/.bkit/shared/gitignore +6 -2
  225. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +15 -16
  226. package/.bkit/templates/.cursor/Dockerfile +12 -8
  227. package/.bkit/templates/.cursor/environment.json +1 -1
  228. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-bug.yml +10 -8
  229. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +24 -12
  230. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +3 -3
  231. package/.bkit/templates/.github/renovate.json5 +34 -6
  232. package/.bkit/templates/.github/workflows/bkit-ci.yml +53 -50
  233. package/.bkit/templates/.github/workflows/bkit-cloud.yml +13 -14
  234. package/.bkit/templates/.github/workflows/bkit-health.yml +97 -0
  235. package/.bkit/templates/.github/workflows/bkit-renovate.yml +5 -4
  236. package/.bkit/templates/.github/workflows/bkit-trivy.yml +5 -4
  237. package/.bkit/templates/.husky/pre-commit +2 -2
  238. package/.bkit/templates/.husky/pre-push +95 -35
  239. package/.bkit/templates/.prettierignore +6 -7
  240. package/.bkit/templates/.vale.ini +27 -27
  241. package/.bkit/templates/context/bkit-cloudrun.md +23 -15
  242. package/.bkit/templates/context/bkit-expo.md +70 -52
  243. package/.bkit/templates/context/bkit-github.md +93 -56
  244. package/.bkit/templates/context/bkit-inngest.md +21 -15
  245. package/.bkit/templates/context/bkit-maestro.md +22 -16
  246. package/.bkit/templates/context/bkit-playwright.md +23 -17
  247. package/.bkit/templates/context/bkit-resend.md +12 -10
  248. package/.bkit/templates/context/bkit-sentry.md +30 -20
  249. package/.bkit/templates/context/bkit-serena.md +8 -7
  250. package/.bkit/templates/context/bkit-stripe.md +14 -13
  251. package/.bkit/templates/context/bkit-supabase.md +16 -13
  252. package/.bkit/templates/context/bkit-tavily.md +14 -11
  253. package/.bkit/templates/context/bkit-vercel.md +27 -18
  254. package/.bkit/templates/docs/capabilities.md +15 -14
  255. package/.bkit/templates/scripts/ci/{check-accepted-divergences.mjs → bkit-check-accepted-divergences.mjs} +6 -3
  256. package/.bkit/templates/scripts/ci/{check-accepted-divergences.test.mjs → bkit-check-accepted-divergences.test.mjs} +3 -3
  257. package/.bkit/templates/scripts/ci/{check-capstone.mjs → bkit-check-capstone.mjs} +2 -2
  258. package/.bkit/templates/scripts/ci/{check-capstone.test.mjs → bkit-check-capstone.test.mjs} +4 -4
  259. package/.bkit/templates/scripts/ci/{check-dependency-audit.mjs → bkit-check-dependency-audit.mjs} +103 -18
  260. package/.bkit/templates/scripts/ci/{check-dependency-audit.test.mjs → bkit-check-dependency-audit.test.mjs} +31 -3
  261. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +387 -0
  262. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +75 -0
  263. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +160 -0
  264. package/.bkit/templates/scripts/ci/lanes/{resolve-push-base.mjs → bkit-resolve-push-base.mjs} +3 -3
  265. package/.bkit/templates/scripts/ci/lanes/{resolve-push-base.test.mjs → bkit-resolve-push-base.test.mjs} +4 -4
  266. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +9 -1
  267. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +1 -1
  268. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +3 -3
  269. package/.bkit/templates/scripts/graphify/bkit-graph-embed.py +63 -0
  270. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +2 -2
  271. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +69 -18
  272. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +3 -3
  273. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +1 -1
  274. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  275. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +197 -126
  276. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +64 -41
  277. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +23 -7
  278. package/.bkit/templates/slop-scan.config.json +9 -2
  279. package/CHANGELOG.md +119 -0
  280. package/README.md +250 -76
  281. package/dist/checks/after/auth.js +36 -33
  282. package/dist/checks/after/ci-yml.js +52 -2
  283. package/dist/checks/after/index.js +12 -4
  284. package/dist/checks/after/tools.js +73 -33
  285. package/dist/checks/before/context-fetch.js +218 -33
  286. package/dist/checks/before/env.js +1 -1
  287. package/dist/checks/before/index.js +6 -2
  288. package/dist/checks/before/repo.js +35 -1
  289. package/dist/checks/status-holes.js +739 -114
  290. package/dist/checks/tips/catalogue.js +59 -17
  291. package/dist/checks/tips/detect.js +30 -0
  292. package/dist/checks/tips/index.js +48 -6
  293. package/dist/cli.js +222 -84
  294. package/dist/commands/analysis.js +77 -53
  295. package/dist/commands/ci/ci.js +302 -25
  296. package/dist/commands/ci/pins.js +142 -0
  297. package/dist/commands/ci/push-gate.js +194 -0
  298. package/dist/commands/install/uninstall.js +23 -27
  299. package/dist/commands/install/upgrade.js +21 -11
  300. package/dist/commands/land.js +126 -10
  301. package/dist/commands/lib.js +244 -5
  302. package/dist/commands/registry.js +6 -2
  303. package/dist/commands/setup/setup.js +1 -0
  304. package/dist/commands/stats.js +69 -30
  305. package/dist/commands/workflow/branches.js +1232 -111
  306. package/dist/commands/workflow/challenge.js +90 -37
  307. package/dist/commands/workflow/completeness.js +97 -0
  308. package/dist/commands/workflow/context.js +371 -51
  309. package/dist/commands/workflow/counters.js +206 -40
  310. package/dist/commands/workflow/decisions.js +60 -17
  311. package/dist/commands/workflow/disk.js +213 -55
  312. package/dist/commands/workflow/fids.js +18 -1
  313. package/dist/commands/workflow/issues.js +6 -0
  314. package/dist/commands/workflow/ledgers.js +372 -21
  315. package/dist/commands/workflow/locks.js +2 -0
  316. package/dist/commands/workflow/plan-blocks.js +78 -14
  317. package/dist/commands/workflow/plans.js +205 -0
  318. package/dist/commands/workflow/prs.js +12 -3
  319. package/dist/commands/workflow/repo.js +6 -0
  320. package/dist/commands/workflow/roadmap.js +50 -17
  321. package/dist/commands/workflow/run-facts.js +23 -28
  322. package/dist/commands/workflow/runs.js +530 -33
  323. package/dist/commands/workflow/runtime.js +3 -0
  324. package/dist/commands/workflow/skills.js +1 -0
  325. package/dist/commands/workflow/status.js +166 -19
  326. package/dist/commands/workflow/step-table.js +61 -29
  327. package/dist/commands/workflow/steps.js +542 -26
  328. package/dist/commands/workflow/summary-findings.js +117 -0
  329. package/dist/commands/workflow/summary.js +154 -41
  330. package/dist/commands/workflow/tasks.js +378 -0
  331. package/dist/commands/workflow/test-blocks.js +231 -0
  332. package/dist/commands/workflow/tests-changed.js +172 -0
  333. package/dist/commands/workflow/tests.js +1013 -321
  334. package/dist/commands/workflow/workflows.js +191 -38
  335. package/dist/commands/workflow/worktrees.js +310 -42
  336. package/dist/install/cloud-env.js +233 -99
  337. package/dist/install/context-ci-workflow.js +85 -0
  338. package/dist/install/manifest.js +57 -12
  339. package/dist/install/modules/antigravity.js +3 -2
  340. package/dist/install/modules/cloud.js +3 -3
  341. package/dist/install/modules/codex.js +12 -2
  342. package/dist/install/modules/core.js +851 -53
  343. package/dist/install/modules/cursor.js +6 -6
  344. package/dist/install/modules/opencode.js +11 -5
  345. package/dist/install/template-notes.js +116 -0
  346. package/dist/install/version-file.js +3 -2
  347. package/dist/ledgers/compact.js +87 -0
  348. package/dist/ledgers/journal.js +233 -0
  349. package/dist/ledgers/status.js +115 -5
  350. package/dist/ledgers/telemetry.js +121 -17
  351. package/dist/render/hosts.js +100 -14
  352. package/dist/shared/bkit-latest.js +26 -4
  353. package/dist/shared/dep-updater.js +49 -0
  354. package/dist/shared/egress.js +1 -1
  355. package/dist/shared/package-manager.js +6 -0
  356. package/dist/shared/settings.js +59 -10
  357. package/dist/shared/timeouts.js +2 -0
  358. package/dist/tools/cli-doc.js +97 -0
  359. package/dist/tools/grammar-density.js +1 -1
  360. package/dist/tools/instructions-sources.js +15 -16
  361. package/dist/tools/instructions.js +83 -39
  362. package/package.json +58 -42
  363. package/.bkit/core/.bkit/lite.md +0 -73
  364. package/.bkit/core/engine/commands/workflow/workstreams.ts +0 -172
  365. package/.bkit/core/prompts/bkit-build-plan-execute.md +0 -124
  366. package/.bkit/templates/scripts/ci/bkit-local-stack-lock.sh +0 -194
  367. package/dist/commands/workflow/workstreams.js +0 -149
  368. /package/.bkit/templates/.vale/styles/{House → Bkit}/Filler.yml +0 -0
  369. /package/.bkit/templates/.vale/styles/{House → Bkit}/Hedging.yml +0 -0
  370. /package/.bkit/templates/.vale/styles/{House → Bkit}/LLMSlop.yml +0 -0
  371. /package/.bkit/templates/.vale/styles/{House → Bkit}/Verbose.yml +0 -0
  372. /package/.bkit/templates/scripts/ci/{accepted-advisories.json → bkit-accepted-advisories.json} +0 -0
  373. /package/.bkit/templates/scripts/ci/{accepted-divergences.json → bkit-accepted-divergences.json} +0 -0
  374. /package/.bkit/templates/scripts/launchd/{launchd.env.example → bkit-launchd.env.example} +0 -0
  375. /package/.bkit/templates/scripts/launchd/{ai.bkit.launchd.plist → bkit-launchd.plist} +0 -0
@@ -13,6 +13,7 @@
13
13
  // never force-pushed and a personal one survives the rebase that rewrote it.
14
14
 
15
15
  import { spawnSync } from "node:child_process";
16
+ import { createHash } from "node:crypto";
16
17
  import * as fs from "node:fs";
17
18
  import * as os from "node:os";
18
19
  import * as path from "node:path";
@@ -21,6 +22,7 @@ import { gitEnv } from "../../ledgers/telemetry.js";
21
22
  import { actionHash, actionKey, alreadyDone, recordAction } from "../../ledgers/status.js";
22
23
  import {
23
24
  bodySkipToken,
25
+ classifyLockExit,
24
26
  CommandError,
25
27
  DEV,
26
28
  EXIT,
@@ -33,11 +35,18 @@ import {
33
35
  runGh,
34
36
  runGit,
35
37
  SKIP_CI_TOKEN,
38
+ testsLockHolder,
39
+ wholeNumber,
36
40
  type CommandSpec,
37
41
  type RunContext,
38
42
  } from "../lib.js";
39
43
  import { bkitVersionStatus, type BkitVersionStatus } from "../../shared/bkit-latest.js";
40
- 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";
41
50
  import { TIMEOUTS } from "../../shared/timeouts.js";
42
51
  import {
43
52
  activeRecord,
@@ -55,18 +64,27 @@ import {
55
64
  mergePr,
56
65
  openPrFor,
57
66
  probePr,
58
- updateBranch,
59
67
  } from "./prs.js";
60
68
  import { AUTO_LABEL, AUTO_ROUTE_SUFFIX } from "./issues.js";
61
69
  import { appendFeature } from "./roadmap.js";
62
70
  import { detect } from "./runtime.js";
63
71
  import { readRuns, readStatusRows, readStatusRowsAt } from "./status.js";
64
- import { removeWorktree, worktreeDir } from "./worktrees.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";
65
81
  import {
66
82
  COULD_NOT_RUN_EXIT_CODES,
67
83
  LOCKFILE_REGENERATE,
68
84
  installCommand,
85
+ scriptCommand,
69
86
  } from "../../shared/package-manager.js";
87
+ import { readPackageJson } from "../../shared/package-json.js";
70
88
  import { str } from "./status.js";
71
89
 
72
90
  const REMOTE = "origin";
@@ -92,6 +110,8 @@ export const EXIT_NO_RECORD = 20;
92
110
  export const EXIT_NOTHING_TO_PUSH = 21;
93
111
  export const EXIT_DIVERGED = 22;
94
112
  export const EXIT_DIFF_FAILED = 23;
113
+ export const EXIT_HAND_RESOLVE = 24;
114
+ export const EXIT_GENERATE_FAILED = 25;
95
115
 
96
116
  // ---------------------------------------------------------------------------
97
117
  // Process helpers
@@ -170,10 +190,71 @@ const globToRegExp = (glob: string) =>
170
190
  );
171
191
  const LEDGER_PATTERNS = LEDGERS.map(globToRegExp);
172
192
 
173
- 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";
174
195
 
175
- /** How a conflicted path may be resolved. Only repo-root lockfiles count: the regenerate runs there. */
176
- export function classifyConflict(file: string): ConflictKind {
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";
246
+
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";
177
258
  if (Object.hasOwn(LOCKFILE_REGENERATE, file)) return "lockfile";
178
259
  if (LEDGER_PATTERNS.some((re) => re.test(file))) return "ledger";
179
260
  return "refuse";
@@ -240,22 +321,180 @@ export function unionResolve(
240
321
  }
241
322
 
242
323
  /**
243
- * Resolve a lockfile conflict: start from the rebase target's copy, then
244
- * regenerate from the manifest, which merged normally (or refused and stopped
245
- * the rebase before this). During a rebase `--ours` is the branch being rebased
246
- * 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`.
247
328
  */
248
- function lockfileResolve(top: string, file: string): boolean {
329
+ function lockfileResolve(top: string, file: string, dev: "ours" | "theirs" = "ours"): boolean {
249
330
  const regenerate = LOCKFILE_REGENERATE[file];
250
331
  if (!regenerate) return false;
251
- if (!runGit(top, ["checkout", "--ours", "--", file]).ok) return false;
332
+ if (!runGit(top, ["checkout", `--${dev}`, "--", file]).ok) return false;
252
333
  const res = spawnSync(regenerate[0]!, regenerate.slice(1), { cwd: top, stdio: "ignore" });
253
334
  return res.status === 0;
254
335
  }
255
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
+
256
495
  export interface Resolution {
257
496
  path: string;
258
- how: "union" | "lockfile" | "dev";
497
+ how: "union" | "lockfile" | "register" | "embed" | "record" | "dev";
259
498
  }
260
499
 
261
500
  export interface RebaseResult {
@@ -268,6 +507,18 @@ export interface RebaseResult {
268
507
  log: string[];
269
508
  }
270
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
+
271
522
  /**
272
523
  * Drive an in-progress rebase to completion, auto-resolving each stop. Loops
273
524
  * because `--continue` replays the next commit, which can conflict in turn; the
@@ -298,32 +549,47 @@ export function resolveRebase(
298
549
  return result;
299
550
  };
300
551
 
552
+ const embeds = embedDocs(top);
301
553
  while (result.rounds < 100) {
302
554
  result.rounds++;
303
555
  const conflicts = unmergedPaths(top);
304
556
  if (conflicts.length > 0) {
305
557
  // Classify the whole set before resolving any of it, so a refused path
306
558
  // never leaves half the set rewritten.
307
- const refused = conflicts.find((f) => classifyConflict(f) === "refuse");
559
+ const refused = conflicts.find((f) => classifyConflict(f, embeds) === "refuse");
308
560
  if (refused !== undefined) {
309
561
  return refuse(
310
- `REFUSE ${refused} — not an append-only ledger or a recognised lockfile; routing to Failure Path`,
562
+ `REFUSE ${refused} — ${NOT_RESOLVABLE}; routing to Failure Path`,
311
563
  refused,
312
- "not an append-only ledger or a recognised lockfile",
564
+ NOT_RESOLVABLE,
313
565
  );
314
566
  }
315
567
  for (const f of conflicts) {
316
- const kind = classifyConflict(f);
317
- 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));
318
582
  if (!ok || !runGit(top, ["add", "--", f]).ok) {
319
583
  return refuse(`REFUSE ${f} — resolution failed`, f, "resolution failed");
320
584
  }
321
- result.resolved.push({ path: f, how: kind === "ledger" ? "union" : "lockfile" });
322
- log(
585
+ const how: Exclude<Resolution["how"], "dev"> =
323
586
  kind === "ledger"
324
- ? `RESOLVED ${f} — union (append-only ledger)`
325
- : `RESOLVED ${f} — took rebase target + regenerated`,
326
- );
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]}`);
327
593
  }
328
594
  }
329
595
 
@@ -522,6 +788,7 @@ function rebaseVerb(ctx: RunContext): number {
522
788
  ctx.log("no rebase in progress");
523
789
  return EXIT_NO_REBASE;
524
790
  }
791
+ const origHead = rebaseOrigHead(top);
525
792
  const result = resolveRebase(top, (line) => ctx.log(line));
526
793
  let aborted = false;
527
794
  if (!result.ok) {
@@ -534,6 +801,19 @@ function rebaseVerb(ctx: RunContext): number {
534
801
  result.log.push(line);
535
802
  ctx.log(line);
536
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
+ }
537
817
  appendLog(ctx, str(ctx.flags.logFile), result.log);
538
818
  if (!result.ok && sentinelPath) {
539
819
  fs.mkdirSync(path.dirname(sentinelPath), { recursive: true });
@@ -548,10 +828,28 @@ function rebaseVerb(ctx: RunContext): number {
548
828
  reason: result.reason,
549
829
  aborted,
550
830
  sentinel: !result.ok && sentinel !== undefined ? sentinel : null,
831
+ rebuilt,
551
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"]));
552
836
  return result.ok ? EXIT.OK : EXIT_REFUSED;
553
837
  }
554
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
+
555
853
  export interface PushOutcome {
556
854
  code: number;
557
855
  out: {
@@ -563,6 +861,29 @@ export interface PushOutcome {
563
861
  prNumber: number | null;
564
862
  /** The run's commits went out as copies cherry-picked onto a fresh origin/dev. */
565
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,
566
887
  };
567
888
  }
568
889
 
@@ -606,6 +927,7 @@ export async function pushBranch(
606
927
  skipped: null,
607
928
  prNumber: null,
608
929
  replayed: false,
930
+ mergedDev: false,
609
931
  ...extra,
610
932
  },
611
933
  });
@@ -643,6 +965,18 @@ export async function pushBranch(
643
965
  }
644
966
  }
645
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
+ }
646
980
  if (mode === "abort" && !shared) {
647
981
  const pr =
648
982
  openPrFlag === undefined
@@ -664,10 +998,10 @@ export async function pushBranch(
664
998
  REMOTE,
665
999
  branch,
666
1000
  ];
667
- const res = runGit(cwd, args);
1001
+ const res = runPush(cwd, args, branch);
668
1002
  if (!res.ok) {
669
1003
  log(`git ${args.join(" ")} failed: ${res.stderr}`);
670
- return notPushed(EXIT_PUSH_FAILED);
1004
+ return notPushed(res.lockExit ?? EXIT_PUSH_FAILED, { lockHolder: res.lockHolder });
671
1005
  }
672
1006
  log(`pushed ${branch}${shared ? "" : " (--force-with-lease)"}`);
673
1007
  return {
@@ -680,6 +1014,7 @@ export async function pushBranch(
680
1014
  skipped: null,
681
1015
  prNumber: null,
682
1016
  replayed: false,
1017
+ mergedDev,
683
1018
  },
684
1019
  };
685
1020
  }
@@ -732,10 +1067,10 @@ function pushPlain(
732
1067
  return notPushed(EXIT_SKIP_CI, { skipped: "skip-ci" });
733
1068
  }
734
1069
  const args = ["push", ...(o.setUpstream === true ? ["-u"] : []), REMOTE, branch];
735
- const res = runGit(cwd, args);
1070
+ const res = runPush(cwd, args, branch);
736
1071
  if (!res.ok) {
737
1072
  log(`git ${args.join(" ")} failed: ${res.stderr}`);
738
- return notPushed(EXIT_PUSH_FAILED);
1073
+ return notPushed(res.lockExit ?? EXIT_PUSH_FAILED, { lockHolder: res.lockHolder });
739
1074
  }
740
1075
  log(`pushed ${branch}`);
741
1076
  return {
@@ -748,6 +1083,7 @@ function pushPlain(
748
1083
  skipped: null,
749
1084
  prNumber: null,
750
1085
  replayed: false,
1086
+ mergedDev: false,
751
1087
  },
752
1088
  };
753
1089
  }
@@ -777,7 +1113,7 @@ function markerCommit(
777
1113
  return { sha: prior.ref, deduped: true };
778
1114
  }
779
1115
  if (o.addAll) {
780
- const added = runGit(cwd, ["add", "-A"]);
1116
+ const added = addAllButCopied(cwd);
781
1117
  if (!added.ok) throw new CommandError(EXIT_PUSH_FAILED, `git add -A failed: ${added.stderr}`);
782
1118
  }
783
1119
  const made = runGit(cwd, ["commit", "--allow-empty", "-m", o.message]);
@@ -842,7 +1178,7 @@ async function pushOwnCommits(
842
1178
  );
843
1179
  return notPushed(EXIT_PUSH_FAILED);
844
1180
  }
845
- const fetched = runGit(cwd, ["fetch", REMOTE, `+refs/heads/${DEV}:refs/remotes/${UPSTREAM}`]);
1181
+ const fetched = fetchDev(cwd);
846
1182
  if (!fetched.ok) {
847
1183
  log(`git fetch ${REMOTE} ${DEV} failed: ${fetched.stderr}`);
848
1184
  return notPushed(EXIT_FETCH_FAILED);
@@ -881,7 +1217,7 @@ async function pushOwnCommits(
881
1217
  REMOTE,
882
1218
  `${last}:refs/heads/${rec.branch}`,
883
1219
  ];
884
- const res = runGit(cwd, args);
1220
+ const res = runPush(cwd, args, rec.branch);
885
1221
  if (res.ok) {
886
1222
  log(`pushed ${rec.branch}: the run's ${pending.length} commit(s) are all local dev holds`);
887
1223
  return {
@@ -894,9 +1230,14 @@ async function pushOwnCommits(
894
1230
  skipped: null,
895
1231
  prNumber: null,
896
1232
  replayed: false,
1233
+ mergedDev: false,
897
1234
  },
898
1235
  };
899
1236
  }
1237
+ if (res.lockExit !== null) {
1238
+ log(`git ${args.join(" ")} failed: ${res.stderr}`);
1239
+ return notPushed(res.lockExit, { lockHolder: res.lockHolder });
1240
+ }
900
1241
  log(`git ${args.join(" ")} failed: ${res.stderr} — replaying onto a fresh ${UPSTREAM}`);
901
1242
  }
902
1243
 
@@ -930,6 +1271,7 @@ async function pushOwnCommits(
930
1271
  skipped: null,
931
1272
  prNumber: null,
932
1273
  replayed: true,
1274
+ mergedDev: false,
933
1275
  },
934
1276
  };
935
1277
  case "refused":
@@ -994,6 +1336,7 @@ async function pushVerb(ctx: RunContext): Promise<number> {
994
1336
  skipped: "skip-ci",
995
1337
  prNumber: null,
996
1338
  replayed: false,
1339
+ mergedDev: false,
997
1340
  });
998
1341
  return EXIT_SKIP_CI;
999
1342
  }
@@ -1021,7 +1364,9 @@ async function pushVerb(ctx: RunContext): Promise<number> {
1021
1364
  // A detached HEAD and a wrong checkout print nothing, as the push never got to run.
1022
1365
  if (r.code !== EXIT_DETACHED && r.code !== EXIT_NOT_DEV) {
1023
1366
  ctx.emit(
1024
- marker === undefined ? r.out : { ...r.out, commit: marker.sha, deduped: marker.deduped },
1367
+ marker === undefined
1368
+ ? { lockHolder: null, ...r.out }
1369
+ : { lockHolder: null, ...r.out, commit: marker.sha, deduped: marker.deduped },
1025
1370
  );
1026
1371
  }
1027
1372
  return r.code;
@@ -1058,14 +1403,261 @@ function fastForwardVerb(ctx: RunContext): number {
1058
1403
  /** Paths a source-change check leaves out: plan logs and the append-only ledgers. */
1059
1404
  const NOT_CODE = [":(exclude)docs/plans", ":(exclude)docs/*.jsonl", ":(exclude).bkit/*.jsonl"];
1060
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;
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
+
1061
1644
  function scanDiffVerb(ctx: RunContext): number {
1062
1645
  const base = String(ctx.flags.base);
1063
1646
  const pattern = str(ctx.flags.paths);
1064
1647
  const marker = str(ctx.flags.marker);
1065
1648
  const code = ctx.flags.code === true;
1066
- if ([pattern !== undefined, marker !== undefined, code].filter(Boolean).length !== 1) {
1067
- throw new CommandError(EXIT.USAGE, "give exactly one of --paths, --marker, --code");
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
+ );
1068
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
+ );
1069
1661
  let re: RegExp | undefined;
1070
1662
  if (pattern !== undefined) {
1071
1663
  try {
@@ -1085,6 +1677,21 @@ function scanDiffVerb(ctx: RunContext): number {
1085
1677
  return EXIT_DIFF_FAILED;
1086
1678
  }
1087
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
+ }
1088
1695
  let paths: string[];
1089
1696
  if (marker !== undefined) {
1090
1697
  const diff = quietGit(top, ["diff", "--no-renames", range, "--", ".", ":(exclude)docs/plans"]);
@@ -1212,41 +1819,529 @@ async function forceBuildVerb(ctx: RunContext): Promise<number> {
1212
1819
  return pushed.code;
1213
1820
  }
1214
1821
 
1215
- /** Resolve sync's docs-merge conflicts: ledgers by union, other `docs/` paths take dev's side. */
1216
- function resolveDocsMerge(top: string): { resolved: Resolution[] } | { refused: string } {
1217
- const conflicts = unmergedPaths(top);
1218
- const refused = conflicts.find((f) => classifyConflict(f) !== "ledger" && !f.startsWith("docs/"));
1219
- if (refused !== undefined) return { refused };
1220
- const resolved: Resolution[] = [];
1221
- for (const f of conflicts) {
1222
- if (classifyConflict(f) === "ledger") {
1223
- if (!unionResolve(top, f).ok || !runGit(top, ["add", "--", f]).ok) return { refused: f };
1224
- resolved.push({ path: f, how: "union" });
1225
- continue;
1226
- }
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 };
2012
+ }
2013
+
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;
2072
+ }
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,
2095
+ ctx.log,
2096
+ );
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;
2120
+ }
2121
+
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" };
1227
2168
  // In a merge `--theirs` is the branch merged in: dev. Dev deleting the file
1228
2169
  // leaves no stage 3, and taking dev's side means deleting it here too.
1229
- const devHasIt = runGit(top, ["cat-file", "-e", `:3:${f}`]).ok;
2170
+ const devHasIt = runGit(top, ["cat-file", "-e", `:3:${file}`]).ok;
1230
2171
  const ok = devHasIt
1231
- ? runGit(top, ["checkout", "--theirs", "--", f]).ok && runGit(top, ["add", "--", f]).ok
1232
- : runGit(top, ["rm", "-q", "--", f]).ok;
1233
- if (!ok) return { refused: f };
1234
- 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" };
1235
2179
  }
1236
- return { resolved };
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;
2309
+ }
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
+ });
1237
2326
  }
1238
2327
 
1239
2328
  function syncVerb(ctx: RunContext): number {
1240
2329
  const mergeDocs = ctx.flags.mergeDocs === true;
2330
+ const merge = ctx.flags.merge === true;
1241
2331
  const headFlag = str(ctx.flags.head);
1242
- if (mergeDocs && headFlag !== undefined) {
2332
+ if ((mergeDocs || merge) && headFlag !== undefined) {
1243
2333
  throw new CommandError(
1244
2334
  EXIT.USAGE,
1245
- "--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",
1246
2336
  );
1247
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 });
1248
2343
  const top = topLevel(ctx.cwd);
1249
- const fetch = runGit(top, ["fetch", REMOTE, DEV]);
2344
+ const fetch = fetchDev(top);
1250
2345
  if (!fetch.ok) {
1251
2346
  ctx.log(`git fetch ${REMOTE} ${DEV} failed: ${fetch.stderr}`);
1252
2347
  return EXIT_FETCH_FAILED;
@@ -1268,7 +2363,7 @@ function syncVerb(ctx: RunContext): number {
1268
2363
  }
1269
2364
  const count = (args: string[]) => Number(git(top, ["rev-list", "--count", ...args]) ?? "0");
1270
2365
  const behind = count([`${head}..${UPSTREAM}`]);
1271
- const docsBehind = count([`${head}..${UPSTREAM}`, "--", "docs/"]);
2366
+ const docsBehind = docsBehindOf(top, head);
1272
2367
  const out = {
1273
2368
  branch: branch === "" ? null : branch,
1274
2369
  head,
@@ -1277,6 +2372,8 @@ function syncVerb(ctx: RunContext): number {
1277
2372
  docsBehind,
1278
2373
  merged: false,
1279
2374
  resolved: [] as Resolution[],
2375
+ generated: null as boolean | null,
2376
+ rebuilt: null as boolean | null,
1280
2377
  };
1281
2378
 
1282
2379
  if (mergeDocs) {
@@ -1284,31 +2381,56 @@ function syncVerb(ctx: RunContext): number {
1284
2381
  ctx.log("no branch checked out (detached HEAD) — cannot merge dev's docs");
1285
2382
  return EXIT_DETACHED;
1286
2383
  }
1287
- if (!isSharedBranch(branch) && docsBehind > 0) {
1288
- ctx.log(`docs/ is ${docsBehind} commit(s) behind ${UPSTREAM} — merging it in`);
1289
- if (!quietGit(top, ["merge", "--no-edit", UPSTREAM]).ok) {
1290
- const outcome = resolveDocsMerge(top);
1291
- if ("refused" in outcome) {
1292
- runGit(top, ["merge", "--abort"]);
1293
- ctx.log(
1294
- `merge of ${UPSTREAM} conflicts on ${outcome.refused} — outside docs/, merge aborted`,
1295
- );
1296
- return EXIT_MERGE_CONFLICT;
1297
- }
1298
- if (unmergedPaths(top).length > 0 || !quietGit(top, ["commit", "--no-edit"]).ok) {
1299
- runGit(top, ["merge", "--abort"]);
1300
- ctx.log(`merge of ${UPSTREAM} could not be committed — merge aborted`);
1301
- return EXIT_MERGE_CONFLICT;
1302
- }
1303
- out.resolved = outcome.resolved;
1304
- for (const r of outcome.resolved)
1305
- ctx.log(
1306
- `RESOLVED ${r.path} — ${r.how === "union" ? "union (append-only ledger)" : `took ${DEV}`}`,
1307
- );
1308
- }
1309
- out.merged = true;
1310
- 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;
1311
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, "");
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;
1312
2434
  }
1313
2435
  ctx.emit(out);
1314
2436
  return EXIT.OK;
@@ -1321,7 +2443,7 @@ function syncVerb(ctx: RunContext): number {
1321
2443
  */
1322
2444
  function syncDevVerb(ctx: RunContext): number {
1323
2445
  const root = repoRoot(ctx.cwd);
1324
- const fetch = runGit(root, ["fetch", REMOTE, DEV]);
2446
+ const fetch = fetchDev(root);
1325
2447
  if (!fetch.ok) {
1326
2448
  ctx.log(`git fetch ${REMOTE} ${DEV} failed: ${fetch.stderr}`);
1327
2449
  return EXIT_FETCH_FAILED;
@@ -1463,11 +2585,13 @@ function buildClose(
1463
2585
  const staged = (git(dir, ["diff", "--cached", "--name-only"]) ?? "")
1464
2586
  .split("\n")
1465
2587
  .filter((p) => p !== "" && !CLOSE_DOCS.test(p));
1466
- if (staged.length)
2588
+ if (staged.length) {
2589
+ const inherited = localDevCopies(dir, staged, (p) => `:${p}`);
1467
2590
  throw new Stop(
1468
2591
  EXIT_LAND_STOPPED,
1469
- `${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.")}`,
1470
2593
  );
2594
+ }
1471
2595
  const docs = canonicalDocs(dir, o.branch, o.workflow, o.month, o.fid);
1472
2596
  const main = `docs/plans/${o.month}/${o.fid}-${o.workflow}.md`;
1473
2597
  if (!docs.includes(main))
@@ -1556,11 +2680,42 @@ function branchTree(root: string, branch: string): string | null {
1556
2680
  return null;
1557
2681
  }
1558
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
+
1559
2714
  /**
1560
2715
  * The PR close (the dev push was refused): commit the roadmap row on the branch
1561
2716
  * in the checkout holding it, push it, open or reuse the PR, squash-merge it with
1562
- * an empty body. A merge that does not land on an open PR → update its branch
1563
- * 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
1564
2719
  * the PR left open. gh missing → EXIT.USE_MCP with what to create / merge; re-run
1565
2720
  * with `--pr` (and `--merged-sha` once merged).
1566
2721
  */
@@ -1585,7 +2740,12 @@ async function landPr(
1585
2740
  EXIT_LAND_STOPPED,
1586
2741
  `no checkout has ${o.branch} checked out — the PR close commits the roadmap row on it; nothing landed`,
1587
2742
  );
1588
- 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
+ ]);
1589
2749
  appendFeature(tree, { workflow: o.workflow, fid: o.fid }, ctx.log);
1590
2750
  commitBookkeeping(
1591
2751
  {
@@ -1661,10 +2821,10 @@ async function landPr(
1661
2821
  EXIT_LAND_STOPPED,
1662
2822
  `PR ${prNumber} still not merged after ${attempt} tries — left open; merge it, then re-run with --pr=${prNumber} --merged-sha=<merge commit>`,
1663
2823
  );
1664
- updateBranch(root, prNumber, ctx.log);
2824
+ await mergeDevIntoPrBranch(root, o.branch, ctx.log);
1665
2825
  const wait = landBackoffMs(attempt);
1666
2826
  ctx.log(
1667
- `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`,
1668
2828
  );
1669
2829
  await sleep(wait);
1670
2830
  }
@@ -1676,7 +2836,7 @@ async function landPr(
1676
2836
  }
1677
2837
  if (sha === "")
1678
2838
  throw new Stop(EXIT_LAND_STOPPED, `could not resolve the landed SHA for PR ${prNumber}`);
1679
- if (!runGit(root, ["fetch", REMOTE, DEV]).ok)
2839
+ if (!fetchDev(root).ok)
1680
2840
  throw new Stop(EXIT_LAND_STOPPED, "fetch of origin/dev after the merge failed");
1681
2841
  return { shape: "pr", transport, sha, prNumber: Number(prNumber), pushAttempts: 0 };
1682
2842
  }
@@ -1684,10 +2844,11 @@ async function landPr(
1684
2844
  /**
1685
2845
  * Bring local dev up to `sha` when that is a pure fast-forward — `merge
1686
2846
  * --ff-only` when the main checkout is on dev, else move the branch pointer
1687
- * alone; nothing is checked out or pushed. Local commits origin/dev lacks (listed
1688
- * with the command that publishes them), or git refusing (an uncommitted edit the
1689
- * move would overwrite, dev checked out in another worktree), skip it with a log
1690
- * 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.
1691
2852
  */
1692
2853
  function fastForwardDev(
1693
2854
  root: string,
@@ -1697,8 +2858,11 @@ function fastForwardDev(
1697
2858
  const local = git(root, ["rev-parse", "-q", "--verify", `refs/heads/${DEV}`]);
1698
2859
  if (local === null) return "none";
1699
2860
  if (local === sha) return "current";
1700
- if (!runGit(root, ["merge-base", "--is-ancestor", local, sha]).ok) {
1701
- 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}`]) ?? "")
1702
2866
  .split("\n")
1703
2867
  .filter((l) => l !== "");
1704
2868
  log(`local ${DEV} has ${ahead.length} commit(s) ${UPSTREAM} does not — not fast-forwarded:`);
@@ -1745,11 +2909,41 @@ function notOnDev(root: string, branch: string): string[] {
1745
2909
  });
1746
2910
  }
1747
2911
 
1748
- /** 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
+ */
1749
2943
  function uncommitted(root: string, fid: string): string[] {
1750
2944
  const wt = worktreeDir(root, fid);
1751
2945
  if (!fs.existsSync(wt)) return [];
1752
- const status = runGit(wt, ["status", "--porcelain", "-uall"]);
2946
+ const status = runGit(wt, ["status", "--porcelain", "-uall", "--", ".", ...copyExcludes(wt)]);
1753
2947
  if (!status.ok) return [`git status in ${wt} failed: ${status.stderr}`];
1754
2948
  return status.stdout.split("\n").filter((l) => l !== "");
1755
2949
  }
@@ -1788,7 +2982,7 @@ async function landVerb(ctx: RunContext): Promise<number> {
1788
2982
  }));
1789
2983
  if (typeof landed === "number") return landed;
1790
2984
 
1791
- runGit(root, ["fetch", REMOTE, DEV]);
2985
+ fetchDev(root);
1792
2986
  const localDev = devPushes ? fastForwardDev(root, landed.sha, ctx.log) : null;
1793
2987
 
1794
2988
  // The audit: canonical docs on origin/dev, the landed body clean, the transport recorded.
@@ -1826,11 +3020,13 @@ async function landVerb(ctx: RunContext): Promise<number> {
1826
3020
  `canonical ${workflow} missing on ${UPSTREAM}: ${missing.join(", ")}`,
1827
3021
  );
1828
3022
  const notLanded = notOnDev(root, branch);
1829
- if (notLanded.length)
3023
+ if (notLanded.length) {
3024
+ const inherited = localDevCopies(root, notLanded, (p) => `${branch}:${p}`);
1830
3025
  throw new Stop(
1831
3026
  EXIT_LANDED_UNVERIFIED,
1832
- `${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.")}`,
1833
3028
  );
3029
+ }
1834
3030
 
1835
3031
  let worktree: Record<string, unknown> | null = null;
1836
3032
  const left = devPushes ? uncommitted(root, fid) : [];
@@ -1965,40 +3161,173 @@ export const branchesCommand: CommandSpec = {
1965
3161
  noun: "branches",
1966
3162
  summary: "Sync, push, land and rebase branches; stamp and read a doc's base-commit anchor.",
1967
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
+ },
1968
3226
  sync: {
1969
- 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",
1970
3229
  flags: [
1971
3230
  {
1972
3231
  name: "head",
1973
3232
  type: "string",
1974
3233
  help: "commit to compare (default HEAD), e.g. ship's ENTRY_HEAD",
1975
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
+ },
1976
3240
  {
1977
3241
  name: "merge-docs",
1978
3242
  type: "boolean",
1979
- 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",
1980
3259
  },
1981
3260
  ],
1982
3261
  output: {
1983
3262
  branch: "current branch (null when detached)",
1984
- head: "commit compared (after a merge: the merge commit)",
3263
+ head: "commit compared (after a merge: the new HEAD)",
1985
3264
  basePath: `A when ${UPSTREAM} is an ancestor of head (nothing to integrate), else B`,
1986
3265
  behind: `commits on ${UPSTREAM} not in head`,
1987
- docsBehind: `of those, commits touching docs/`,
1988
- merged: `true when --merge-docs merged ${UPSTREAM}`,
1989
- 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)",
1990
3280
  },
1991
3281
  exitCodes: {
1992
- [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",
1993
3284
  [EXIT_FETCH_FAILED]: `git fetch ${REMOTE} ${DEV} failed`,
1994
- [EXIT_MERGE_CONFLICT]:
1995
- "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",
1996
3290
  },
1997
3291
  run: syncVerb,
1998
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
+ },
1999
3327
  push: {
2000
3328
  summary:
2001
- "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",
2002
3331
  flags: [
2003
3332
  {
2004
3333
  name: "mode",
@@ -2028,7 +3357,7 @@ export const branchesCommand: CommandSpec = {
2028
3357
  {
2029
3358
  name: "require-ci",
2030
3359
  type: "boolean",
2031
- 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`,
2032
3361
  },
2033
3362
  {
2034
3363
  name: "open-pr",
@@ -2043,6 +3372,7 @@ export const branchesCommand: CommandSpec = {
2043
3372
  ],
2044
3373
  output: {
2045
3374
  pushed: "true when the push ran and succeeded",
3375
+ lockHolder: "the tests-lock holder on exit 81 (null otherwise)",
2046
3376
  replayed:
2047
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",
2048
3378
  ref: "the branch pushed — link handover artifacts to this ref; null when nothing was pushed",
@@ -2051,10 +3381,12 @@ export const branchesCommand: CommandSpec = {
2051
3381
  skipped:
2052
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)",
2053
3383
  prNumber: "the open PR that stopped an abort push (null otherwise)",
3384
+ mergedDev: `--require-ci: ${UPSTREAM} was merged in before the push`,
2054
3385
  commit: "--commit: the marker commit's sha",
2055
3386
  deduped: "--commit: the marker commit was already made this run (not made again)",
2056
3387
  },
2057
3388
  exitCodes: {
3389
+ 4: "the pre-push hook could not acquire the tests lock",
2058
3390
  [EXIT_DETACHED]: "no branch checked out",
2059
3391
  [EXIT_NOTHING_TO_PUSH]:
2060
3392
  "--mode=plain or --commit on dev / main, or --ahead-of and HEAD has no commits beyond it",
@@ -2066,14 +3398,18 @@ export const branchesCommand: CommandSpec = {
2066
3398
  [EXIT_NOT_DEV]: "--mode=dev and the checkout is not on dev",
2067
3399
  [EXIT_NO_RECORD]:
2068
3400
  "--mode=dev, or --fid, on dev with no shared-checkout record for the run: nothing pushed",
2069
- [EXIT_FETCH_FAILED]: "in-place run on dev: fetching origin/dev failed",
3401
+ [EXIT_FETCH_FAILED]:
3402
+ "fetching origin/dev failed (in-place run on dev, or a --require-ci feature push); nothing pushed",
2070
3403
  [EXIT_MERGE_CONFLICT]:
2071
- "in-place run on dev: a run commit does not apply onto origin/dev without the local commits it builds on; the conflicting paths are printed, nothing pushed",
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",
2072
3407
  },
2073
3408
  run: pushVerb,
2074
3409
  },
2075
3410
  "fast-forward": {
2076
3411
  summary: "Fetch a remote branch and fast-forward the checkout onto it; refuse when diverged.",
3412
+ use: "workflow",
2077
3413
  flags: [
2078
3414
  {
2079
3415
  name: "onto",
@@ -2091,7 +3427,8 @@ export const branchesCommand: CommandSpec = {
2091
3427
  },
2092
3428
  "scan-diff": {
2093
3429
  summary:
2094
- "Exit 0 when the branch's diff from --base matches (paths, an added marker line, or a source change); 1 when not.",
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",
2095
3432
  flags: [
2096
3433
  {
2097
3434
  name: "base",
@@ -2114,13 +3451,23 @@ export const branchesCommand: CommandSpec = {
2114
3451
  type: "boolean",
2115
3452
  help: "a path changed outside docs/plans, docs/*.jsonl and .bkit/*.jsonl",
2116
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
+ },
2117
3459
  {
2118
3460
  name: "expect-none",
2119
3461
  type: "boolean",
2120
3462
  help: "invert the exit: 0 when nothing matched, 1 (naming the paths on stderr) when something did",
2121
3463
  },
2122
3464
  ],
2123
- output: { found: "something matched", paths: "the matching paths" },
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
+ },
2124
3471
  exitCodes: {
2125
3472
  [EXIT_DIFF_FAILED]: "--base does not resolve, or git diff failed",
2126
3473
  },
@@ -2128,6 +3475,7 @@ export const branchesCommand: CommandSpec = {
2128
3475
  },
2129
3476
  "force-build": {
2130
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",
2131
3479
  flags: [
2132
3480
  { name: "fid", type: "string", required: true, help: "feature id, for the commit subject" },
2133
3481
  {
@@ -2177,7 +3525,8 @@ export const branchesCommand: CommandSpec = {
2177
3525
  },
2178
3526
  rebase: {
2179
3527
  summary:
2180
- "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",
2181
3530
  flags: [
2182
3531
  {
2183
3532
  name: "log-file",
@@ -2189,14 +3538,21 @@ export const branchesCommand: CommandSpec = {
2189
3538
  type: "string",
2190
3539
  help: "file removed at start and created on refusal, e.g. logs/{FID}/.rebase-failed",
2191
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
+ },
2192
3546
  ],
2193
3547
  output: {
2194
3548
  outcome: "resolved | refused (a refused rebase is aborted)",
2195
- 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)",
2196
3552
  skippedCommits: "commits skipped because resolution emptied them",
2197
3553
  rounds: "resolve rounds run",
2198
3554
  refused: "the path that stopped resolution (null when none, or not path-specific)",
2199
- reason: "why resolution refused (null on success)",
3555
+ reason: "why resolution refused or stopped (null on success)",
2200
3556
  aborted: "a refused rebase was aborted (false on success, or when the abort failed)",
2201
3557
  sentinel: "the sentinel written on refusal (null otherwise)",
2202
3558
  },
@@ -2209,6 +3565,7 @@ export const branchesCommand: CommandSpec = {
2209
3565
  "sync-dev": {
2210
3566
  summary:
2211
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",
2212
3569
  flags: [],
2213
3570
  output: {
2214
3571
  devLocal:
@@ -2226,6 +3583,7 @@ export const branchesCommand: CommandSpec = {
2226
3583
  land: {
2227
3584
  summary:
2228
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",
2229
3587
  flags: [
2230
3588
  { name: "workflow", type: "string", required: true, help: "design | plan" },
2231
3589
  { name: "fid", type: "string", required: true, help: "feature id" },
@@ -2281,6 +3639,7 @@ export const branchesCommand: CommandSpec = {
2281
3639
  "anchor-stamp": {
2282
3640
  summary:
2283
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",
2284
3643
  flags: [
2285
3644
  { name: "file", type: "string", required: true, help: "doc to stamp (must exist)" },
2286
3645
  {
@@ -2321,6 +3680,7 @@ export const branchesCommand: CommandSpec = {
2321
3680
  "anchor-read": {
2322
3681
  summary:
2323
3682
  "Read a doc's anchor fields; with --against, decide whether anything landed since its baseSha.",
3683
+ use: "by-hand",
2324
3684
  flags: [
2325
3685
  { name: "file", type: "string", required: true, help: "design/plan doc or audit report" },
2326
3686
  {