@cbartens/bkit 5.5.0 → 6.0.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 (297) hide show
  1. package/.bkit/README.md +30 -20
  2. package/.bkit/core/.agents/docs.md +1 -0
  3. package/.bkit/core/.agents/rules.md +51 -26
  4. package/.bkit/core/.bkit/README.md +29 -19
  5. package/.bkit/core/.bkit/authoring.md +117 -0
  6. package/.bkit/core/.bkit/cloud.md +11 -11
  7. package/.bkit/core/.bkit/comparison.md +5 -5
  8. package/.bkit/core/.bkit/install.md +20 -20
  9. package/.bkit/core/.bkit/jsonl.md +202 -122
  10. package/.bkit/core/.bkit/lite.md +1 -1
  11. package/.bkit/core/.bkit/pipeline.md +49 -52
  12. package/.bkit/core/.bkit/prompts.md +106 -167
  13. package/.bkit/core/.bkit/providers.md +29 -32
  14. package/.bkit/core/.bkit/templates.md +44 -18
  15. package/.bkit/core/.bkit/trackers.md +60 -28
  16. package/.bkit/core/.bkit/workflows.md +399 -359
  17. package/.bkit/core/AGENTS.md +16 -22
  18. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +14 -38
  19. package/.bkit/core/docs/templates/bkit-audit-adoption.md +16 -40
  20. package/.bkit/core/docs/templates/bkit-audit-agents.md +19 -43
  21. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +16 -40
  22. package/.bkit/core/docs/templates/bkit-audit-analytics.md +14 -38
  23. package/.bkit/core/docs/templates/bkit-audit-annotations.md +11 -35
  24. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +15 -39
  25. package/.bkit/core/docs/templates/bkit-audit-app-store.md +12 -36
  26. package/.bkit/core/docs/templates/bkit-audit-architecture.md +16 -40
  27. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +16 -40
  28. package/.bkit/core/docs/templates/bkit-audit-config.md +18 -42
  29. package/.bkit/core/docs/templates/bkit-audit-cost.md +16 -40
  30. package/.bkit/core/docs/templates/bkit-audit-coverage.md +15 -39
  31. package/.bkit/core/docs/templates/bkit-audit-database.md +16 -40
  32. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +15 -39
  33. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +15 -38
  34. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +16 -40
  35. package/.bkit/core/docs/templates/bkit-audit-documentation.md +11 -35
  36. package/.bkit/core/docs/templates/bkit-audit-duplication.md +18 -42
  37. package/.bkit/core/docs/templates/bkit-audit-failures.md +13 -37
  38. package/.bkit/core/docs/templates/bkit-audit-flakes.md +12 -36
  39. package/.bkit/core/docs/templates/bkit-audit-gates.md +14 -38
  40. package/.bkit/core/docs/templates/bkit-audit-issues.md +15 -39
  41. package/.bkit/core/docs/templates/bkit-audit-llm.md +16 -40
  42. package/.bkit/core/docs/templates/bkit-audit-logs.md +14 -38
  43. package/.bkit/core/docs/templates/bkit-audit-models.md +12 -36
  44. package/.bkit/core/docs/templates/bkit-audit-privacy.md +12 -36
  45. package/.bkit/core/docs/templates/bkit-audit-prompts.md +15 -39
  46. package/.bkit/core/docs/templates/bkit-audit-red-team.md +15 -39
  47. package/.bkit/core/docs/templates/bkit-audit-reliability.md +15 -39
  48. package/.bkit/core/docs/templates/bkit-audit-repo.md +12 -36
  49. package/.bkit/core/docs/templates/bkit-audit-security.md +13 -37
  50. package/.bkit/core/docs/templates/bkit-audit-slop.md +14 -38
  51. package/.bkit/core/docs/templates/bkit-audit-testing.md +12 -36
  52. package/.bkit/core/docs/templates/bkit-audit-usability.md +16 -40
  53. package/.bkit/core/docs/templates/bkit-plan.md +97 -226
  54. package/.bkit/core/engine/checks/after/ci-yml.ts +39 -30
  55. package/.bkit/core/engine/checks/after/github.ts +101 -72
  56. package/.bkit/core/engine/checks/after/index.ts +10 -12
  57. package/.bkit/core/engine/checks/after/suppression.ts +8 -5
  58. package/.bkit/core/engine/checks/after/tools.ts +47 -92
  59. package/.bkit/core/engine/checks/before/env.ts +2 -2
  60. package/.bkit/core/engine/checks/before/files.ts +5 -4
  61. package/.bkit/core/engine/checks/before/index.ts +18 -1
  62. package/.bkit/core/engine/checks/before/repo.ts +168 -2
  63. package/.bkit/core/engine/checks/tips/catalogue.ts +16 -5
  64. package/.bkit/core/engine/checks/tips/detect.ts +34 -0
  65. package/.bkit/core/engine/checks/tips/index.ts +10 -7
  66. package/.bkit/core/engine/cli.ts +20 -53
  67. package/.bkit/core/engine/commands/analysis.ts +171 -140
  68. package/.bkit/core/engine/commands/ci/ci.ts +6 -6
  69. package/.bkit/core/engine/commands/comply.ts +77 -103
  70. package/.bkit/core/engine/commands/install/doctor.ts +2 -2
  71. package/.bkit/core/engine/commands/install/install.ts +57 -18
  72. package/.bkit/core/engine/commands/install/uninstall.ts +65 -28
  73. package/.bkit/core/engine/commands/land.ts +18 -12
  74. package/.bkit/core/engine/commands/lib.ts +79 -17
  75. package/.bkit/core/engine/commands/registry.ts +4 -0
  76. package/.bkit/core/engine/commands/setup/setup.ts +7 -7
  77. package/.bkit/core/engine/commands/stats.ts +204 -0
  78. package/.bkit/core/engine/commands/tips.ts +10 -5
  79. package/.bkit/core/engine/commands/workflow/branches.ts +741 -62
  80. package/.bkit/core/engine/commands/workflow/challenge.ts +673 -0
  81. package/.bkit/core/engine/commands/workflow/context.ts +853 -29
  82. package/.bkit/core/engine/commands/workflow/counters.ts +267 -84
  83. package/.bkit/core/engine/commands/workflow/decisions.ts +541 -0
  84. package/.bkit/core/engine/commands/workflow/disk.ts +2 -2
  85. package/.bkit/core/engine/commands/workflow/fids.ts +793 -33
  86. package/.bkit/core/engine/commands/workflow/issues.ts +427 -105
  87. package/.bkit/core/engine/commands/workflow/ledgers.ts +884 -27
  88. package/.bkit/core/engine/commands/workflow/locks.ts +26 -2
  89. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +582 -0
  90. package/.bkit/core/engine/commands/workflow/plan-versions.ts +21 -0
  91. package/.bkit/core/engine/commands/workflow/prs.ts +166 -30
  92. package/.bkit/core/engine/commands/workflow/repo.ts +59 -7
  93. package/.bkit/core/engine/commands/workflow/roadmap.ts +16 -7
  94. package/.bkit/core/engine/commands/workflow/run-facts.ts +501 -0
  95. package/.bkit/core/engine/commands/workflow/runs.ts +179 -49
  96. package/.bkit/core/engine/commands/workflow/runtime.ts +22 -1
  97. package/.bkit/core/engine/commands/workflow/status.ts +142 -29
  98. package/.bkit/core/engine/commands/workflow/step-table.ts +339 -0
  99. package/.bkit/core/engine/commands/workflow/steps.ts +213 -88
  100. package/.bkit/core/engine/commands/workflow/summary.ts +398 -0
  101. package/.bkit/core/engine/commands/workflow/tests.ts +1013 -148
  102. package/.bkit/core/engine/commands/workflow/tracker.ts +1195 -0
  103. package/.bkit/core/engine/commands/workflow/workflows.ts +984 -207
  104. package/.bkit/core/engine/commands/workflow/workstreams.ts +11 -5
  105. package/.bkit/core/engine/commands/workflow/worktrees.ts +276 -22
  106. package/.bkit/core/engine/install/manifest.ts +11 -9
  107. package/.bkit/core/engine/install/modules/cloud.ts +21 -13
  108. package/.bkit/core/engine/install/modules/core.ts +325 -7
  109. package/.bkit/core/engine/install/modules/opencode.ts +2 -2
  110. package/.bkit/core/engine/install/version-file.ts +6 -2
  111. package/.bkit/core/engine/ledgers/migrate.ts +92 -0
  112. package/.bkit/core/engine/ledgers/status.ts +92 -15
  113. package/.bkit/core/engine/ledgers/telemetry.ts +1261 -254
  114. package/.bkit/core/engine/render/hosts.ts +4 -0
  115. package/.bkit/core/engine/render/models.ts +12 -0
  116. package/.bkit/core/engine/shared/branches.ts +4 -1
  117. package/.bkit/core/engine/shared/egress.ts +7 -0
  118. package/.bkit/core/engine/shared/json.ts +25 -7
  119. package/.bkit/core/engine/shared/settings.ts +202 -33
  120. package/.bkit/core/engine/shared/text.ts +361 -0
  121. package/.bkit/core/engine/tools/grammar-density.ts +215 -0
  122. package/.bkit/core/engine/tools/instructions-sources.ts +834 -0
  123. package/.bkit/core/engine/tools/instructions.ts +1751 -0
  124. package/.bkit/core/hooks/gateguard-engine.js +24 -23
  125. package/.bkit/core/hooks/guardrails-shell.js +2 -3
  126. package/.bkit/core/hooks/guardrails-tiers.js +7 -1
  127. package/.bkit/core/hooks/readguard-engine.js +2 -2
  128. package/.bkit/core/prompts/bkit-audit-generate.md +62 -25
  129. package/.bkit/core/prompts/bkit-build-challenge-1.md +40 -17
  130. package/.bkit/core/prompts/bkit-build-challenge-2.md +44 -17
  131. package/.bkit/core/prompts/bkit-build-install-skills.md +26 -13
  132. package/.bkit/core/prompts/bkit-build-plan-convert.md +74 -0
  133. package/.bkit/core/prompts/bkit-build-plan-current.md +26 -13
  134. package/.bkit/core/prompts/bkit-build-plan-execute.md +74 -26
  135. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +64 -23
  136. package/.bkit/core/prompts/bkit-build-plan-verify.md +57 -33
  137. package/.bkit/core/prompts/bkit-debug-abort-handover.md +30 -14
  138. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +34 -14
  139. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +34 -17
  140. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +26 -13
  141. package/.bkit/core/prompts/bkit-debug-failure-soak.md +31 -16
  142. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +21 -11
  143. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +20 -11
  144. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +20 -11
  145. package/.bkit/core/prompts/bkit-design-generate.md +33 -13
  146. package/.bkit/core/prompts/bkit-design-organise.md +25 -12
  147. package/.bkit/core/prompts/bkit-design-review-1.md +31 -15
  148. package/.bkit/core/prompts/bkit-design-review-2.md +28 -13
  149. package/.bkit/core/prompts/bkit-design-spike.md +30 -13
  150. package/.bkit/core/prompts/bkit-design-update.md +33 -19
  151. package/.bkit/core/prompts/bkit-plan-generate.md +75 -19
  152. package/.bkit/core/prompts/bkit-plan-review-1.md +50 -27
  153. package/.bkit/core/prompts/bkit-plan-review-2.md +59 -28
  154. package/.bkit/core/prompts/bkit-plan-scope-check.md +109 -0
  155. package/.bkit/core/prompts/bkit-plan-update.md +61 -24
  156. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +27 -15
  157. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +31 -16
  158. package/.bkit/core/prompts/bkit-ship-update-docs.md +30 -15
  159. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +24 -14
  160. package/.bkit/core/prompts/bkit-utility-update-decisions.md +32 -14
  161. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +29 -14
  162. package/.bkit/core/prompts/bkit-utility-update-documentation.md +28 -13
  163. package/.bkit/core/prompts/bkit-utility-update-failures.md +31 -14
  164. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +33 -14
  165. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +38 -17
  166. package/.bkit/core/prompts/bkit-utility-update-tracker.md +43 -20
  167. package/.bkit/core/workflows/bkit-auto.md +54 -46
  168. package/.bkit/core/workflows/bkit-build.md +577 -458
  169. package/.bkit/core/workflows/bkit-debug.md +348 -333
  170. package/.bkit/core/workflows/bkit-design.md +201 -237
  171. package/.bkit/core/workflows/bkit-plan.md +210 -321
  172. package/.bkit/core/workflows/bkit-ship.md +328 -278
  173. package/.bkit/shared/.bkit/.env.example +2 -2
  174. package/.bkit/shared/.claude/settings.json +11 -0
  175. package/.bkit/shared/.cursor/mcp.json +1 -1
  176. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +1 -1
  177. package/.bkit/shared/.gitattributes +1 -1
  178. package/.bkit/shared/.mcp.json +1 -1
  179. package/.bkit/shared/.opencode/opencode.json +11 -0
  180. package/.bkit/shared/CLAUDE.md +2 -2
  181. package/.bkit/shared/GEMINI.md +2 -2
  182. package/.bkit/shared/docs/architecture.md +1 -1
  183. package/.bkit/shared/docs/data-schema.md +1 -1
  184. package/.bkit/shared/docs/deployments.md +16 -28
  185. package/.bkit/shared/docs/design.md +1 -1
  186. package/.bkit/shared/docs/noise.md +1 -1
  187. package/.bkit/shared/docs/observability.md +2 -2
  188. package/.bkit/shared/docs/security.md +1 -1
  189. package/.bkit/shared/docs/setup.md +1 -1
  190. package/.bkit/shared/docs/technology.md +1 -1
  191. package/.bkit/shared/docs/testing.md +27 -10
  192. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +1 -1
  193. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +26 -5
  194. package/.bkit/templates/.github/workflows/bkit-ci.yml +22 -84
  195. package/.bkit/templates/.github/workflows/bkit-cloud.yml +21 -19
  196. package/.bkit/templates/.husky/pre-push +52 -13
  197. package/.bkit/templates/.prettierignore +7 -0
  198. package/.bkit/templates/scripts/ci/bkit-local-stack-lock.sh +194 -0
  199. package/.bkit/templates/scripts/ci/check-capstone.mjs +2 -4
  200. package/.bkit/templates/scripts/ci/check-capstone.test.mjs +4 -23
  201. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +104 -23
  202. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +103 -6
  203. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +1 -1
  204. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +3 -1
  205. package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +49 -29
  206. package/CHANGELOG.md +142 -0
  207. package/README.md +58 -34
  208. package/dist/checks/after/ci-yml.js +39 -29
  209. package/dist/checks/after/github.js +99 -72
  210. package/dist/checks/after/index.js +11 -13
  211. package/dist/checks/after/suppression.js +8 -5
  212. package/dist/checks/after/tools.js +40 -83
  213. package/dist/checks/before/env.js +2 -2
  214. package/dist/checks/before/files.js +5 -3
  215. package/dist/checks/before/index.js +15 -2
  216. package/dist/checks/before/repo.js +163 -2
  217. package/dist/checks/tips/catalogue.js +14 -5
  218. package/dist/checks/tips/detect.js +32 -0
  219. package/dist/checks/tips/index.js +7 -5
  220. package/dist/cli.js +19 -47
  221. package/dist/commands/analysis.js +109 -100
  222. package/dist/commands/ci/ci.js +6 -6
  223. package/dist/commands/comply.js +54 -91
  224. package/dist/commands/install/doctor.js +2 -2
  225. package/dist/commands/install/install.js +50 -19
  226. package/dist/commands/install/uninstall.js +59 -28
  227. package/dist/commands/land.js +16 -12
  228. package/dist/commands/lib.js +51 -16
  229. package/dist/commands/registry.js +4 -0
  230. package/dist/commands/setup/setup.js +7 -7
  231. package/dist/commands/stats.js +136 -0
  232. package/dist/commands/tips.js +7 -3
  233. package/dist/commands/workflow/branches.js +656 -56
  234. package/dist/commands/workflow/challenge.js +556 -0
  235. package/dist/commands/workflow/context.js +709 -30
  236. package/dist/commands/workflow/counters.js +208 -75
  237. package/dist/commands/workflow/decisions.js +441 -0
  238. package/dist/commands/workflow/disk.js +2 -2
  239. package/dist/commands/workflow/fids.js +689 -33
  240. package/dist/commands/workflow/issues.js +362 -99
  241. package/dist/commands/workflow/ledgers.js +762 -27
  242. package/dist/commands/workflow/locks.js +24 -2
  243. package/dist/commands/workflow/plan-blocks.js +437 -0
  244. package/dist/commands/workflow/plan-versions.js +22 -0
  245. package/dist/commands/workflow/prs.js +142 -32
  246. package/dist/commands/workflow/repo.js +52 -7
  247. package/dist/commands/workflow/roadmap.js +9 -7
  248. package/dist/commands/workflow/run-facts.js +426 -0
  249. package/dist/commands/workflow/runs.js +144 -43
  250. package/dist/commands/workflow/runtime.js +12 -1
  251. package/dist/commands/workflow/status.js +130 -29
  252. package/dist/commands/workflow/step-table.js +276 -0
  253. package/dist/commands/workflow/steps.js +171 -80
  254. package/dist/commands/workflow/summary.js +275 -0
  255. package/dist/commands/workflow/tests.js +834 -136
  256. package/dist/commands/workflow/tracker.js +983 -0
  257. package/dist/commands/workflow/workflows.js +834 -195
  258. package/dist/commands/workflow/workstreams.js +11 -5
  259. package/dist/commands/workflow/worktrees.js +221 -22
  260. package/dist/install/manifest.js +11 -9
  261. package/dist/install/modules/cloud.js +22 -13
  262. package/dist/install/modules/core.js +326 -7
  263. package/dist/install/modules/opencode.js +2 -2
  264. package/dist/install/version-file.js +6 -2
  265. package/dist/ledgers/migrate.js +81 -0
  266. package/dist/ledgers/status.js +61 -8
  267. package/dist/ledgers/telemetry.js +905 -124
  268. package/dist/render/hosts.js +4 -0
  269. package/dist/render/models.js +12 -0
  270. package/dist/shared/branches.js +3 -1
  271. package/dist/shared/egress.js +7 -0
  272. package/dist/shared/json.js +20 -7
  273. package/dist/shared/settings.js +147 -26
  274. package/dist/shared/text.js +333 -0
  275. package/dist/tools/grammar-density.js +183 -0
  276. package/dist/tools/instructions-sources.js +721 -0
  277. package/dist/tools/instructions.js +1579 -0
  278. package/package.json +114 -23
  279. package/.bkit/core/engine/commands/harvest.ts +0 -459
  280. package/.bkit/core/engine/tools/wording.ts +0 -748
  281. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +0 -69
  282. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +0 -71
  283. package/.bkit/core/prompts/bkit-build-challenge-tests.md +0 -74
  284. package/.bkit/core/prompts/bkit-build-summary.md +0 -94
  285. package/.bkit/core/prompts/bkit-debug-summary.md +0 -96
  286. package/.bkit/core/prompts/bkit-design-summary.md +0 -107
  287. package/.bkit/core/prompts/bkit-plan-complexity-check.md +0 -67
  288. package/.bkit/core/prompts/bkit-plan-complexity-split.md +0 -88
  289. package/.bkit/core/prompts/bkit-plan-review-3.md +0 -93
  290. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +0 -85
  291. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +0 -85
  292. package/.bkit/core/prompts/bkit-plan-summary.md +0 -107
  293. package/.bkit/core/prompts/bkit-ship-summary.md +0 -78
  294. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.mjs +0 -138
  295. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.test.mjs +0 -181
  296. package/dist/commands/harvest.js +0 -353
  297. package/dist/tools/wording.js +0 -680
@@ -1,9 +1,11 @@
1
- // bkit branches sync|push|rebase|switch|land|anchor-stamp|anchor-read — the
2
- // branch mechanics every phase workflow repeated inline: bring a feature branch
3
- // up to date with dev, push it the one safe way for its kind, auto-resolve the
4
- // rebase conflicts that lose nothing, return the main checkout to dev after a
5
- // merge, land a design / plan close on dev, and stamp / read the base commit a
6
- // design or plan doc was written against.
1
+ // bkit branches sync|push|rebase|switch|land|fast-forward|scan-diff|force-build|
2
+ // anchor-stamp|anchor-read — the branch mechanics every phase workflow repeated
3
+ // inline: bring a feature branch up to date with dev, push it the one safe way
4
+ // for its kind, auto-resolve the rebase conflicts that lose nothing, return the
5
+ // main checkout to dev after a merge, land a design / plan close on dev,
6
+ // fast-forward onto a remote branch, route on what a branch's diff holds, force
7
+ // a full CI build, and stamp / read the base commit a design or plan doc was
8
+ // written against.
7
9
  //
8
10
  // Every verb works on `origin` and the integration branch `dev`, as the
9
11
  // workflows do. A push is always EXACTLY ONE `git push`: `dev` / `main` get a
@@ -14,16 +16,18 @@ import * as fs from "node:fs";
14
16
  import * as os from "node:os";
15
17
  import * as path from "node:path";
16
18
  import { gitEnv } from "../../ledgers/telemetry.js";
17
- import { bodySkipToken, CommandError, DEV, EXIT, git, isSharedBranch, parseJson, repoRoot, runGit, SKIP_CI_TOKEN, } from "../lib.js";
19
+ import { actionHash, actionKey, alreadyDone, recordAction } from "../../ledgers/status.js";
20
+ import { bodySkipToken, CommandError, DEV, EXIT, ghUnavailable, git, isSharedBranch, OUTPUT_LIMIT, parseJson, repoRoot, runGh, runGit, SKIP_CI_TOKEN, } from "../lib.js";
18
21
  import { bkitVersionStatus } from "../../shared/bkit-latest.js";
19
22
  import { landBackoffMs, landDir, pushToDev, sleep } from "../land.js";
20
23
  import { TIMEOUTS } from "../../shared/timeouts.js";
21
- import { commitBookkeeping } from "./ledgers.js";
24
+ import { activeRecord, commitBookkeeping, markRecordPushed, recordOnBranch, } from "./ledgers.js";
22
25
  import { releaseLock, resolveMonth, workflowLockPath } from "./locks.js";
23
- import { closeTransportRow, crossCheckRows, mergePr, openPrFor, probePr, updateBranch, } from "./prs.js";
26
+ import { EXIT_BASE_NOT_DEV, FORCE_BUILD, closeTransportRow, crossCheckRows, mergePr, openPrFor, probePr, updateBranch, } from "./prs.js";
27
+ import { AUTO_LABEL, AUTO_ROUTE_SUFFIX } from "./issues.js";
24
28
  import { appendFeature } from "./roadmap.js";
25
29
  import { detect } from "./runtime.js";
26
- import { readStatusRows, readStatusRowsAt } from "./status.js";
30
+ import { readRuns, readStatusRows, readStatusRowsAt } from "./status.js";
27
31
  import { removeWorktree, worktreeDir } from "./worktrees.js";
28
32
  import { COULD_NOT_RUN_EXIT_CODES, LOCKFILE_REGENERATE, installCommand, } from "../../shared/package-manager.js";
29
33
  import { str } from "./status.js";
@@ -45,25 +49,24 @@ export const EXIT_INSTALL_FAILED = 16;
45
49
  export const EXIT_LAND_STOPPED = 17;
46
50
  export const EXIT_LANDED_UNVERIFIED = 18;
47
51
  export const EXIT_LOCK_LEFT = 19;
52
+ export const EXIT_NO_RECORD = 20;
53
+ export const EXIT_NOTHING_TO_PUSH = 21;
54
+ export const EXIT_DIVERGED = 22;
55
+ export const EXIT_DIFF_FAILED = 23;
48
56
  // ---------------------------------------------------------------------------
49
57
  // Process helpers
50
58
  // ---------------------------------------------------------------------------
51
59
  /** git with a non-interactive editor, so `--continue` / `--skip` / merge commits never open one. */
52
- const quietGit = (cwd, args) => {
53
- const res = spawnSync("git", args, {
54
- cwd,
55
- encoding: "utf-8",
56
- env: { ...gitEnv(), GIT_EDITOR: "true" },
57
- });
58
- return {
59
- ok: res.status === 0,
60
- stdout: (res.stdout ?? "").trim(),
61
- stderr: (res.stderr ?? "").trim(),
62
- };
63
- };
64
- /** `git show :<stage>:<path>` as raw bytes; empty when that stage does not exist. */
60
+ const quietGit = (cwd, args) => runGit(cwd, args, { GIT_EDITOR: "true" });
61
+ /** `git show :<stage>:<path>` as raw bytes; empty when that stage does not exist, null when git could not run. */
65
62
  function stageBytes(top, stage, file) {
66
- const res = spawnSync("git", ["show", `:${stage}:${file}`], { cwd: top, env: gitEnv() });
63
+ const res = spawnSync("git", ["show", `:${stage}:${file}`], {
64
+ cwd: top,
65
+ env: gitEnv(),
66
+ maxBuffer: OUTPUT_LIMIT,
67
+ });
68
+ if (res.error)
69
+ return null;
67
70
  // A missing stage is a legitimate shape (add/add, delete/modify): merge against empty.
68
71
  return res.status === 0 ? res.stdout : Buffer.alloc(0);
69
72
  }
@@ -91,7 +94,7 @@ const currentBranch = (cwd) => git(cwd, ["branch", "--show-current"]) ?? "";
91
94
  * ledger or is missing.
92
95
  *
93
96
  * `.bkit/friction.jsonl` ships WITHOUT `merge=union` but is listed here; a row union
94
- * resurrects after `bkit harvest` drained it is re-banked by the next harvest.
97
+ * resurrects after the harvest drained it is re-banked by the next harvest.
95
98
  *
96
99
  * `docs/roadmap.md` is not append-only — it is regenerated from
97
100
  * `.bkit/issues.jsonl` — but every workflow close re-folds it, so both sides of
@@ -147,7 +150,10 @@ export function unionResolve(top, file) {
147
150
  try {
148
151
  const sides = { base: 1, ours: 2, theirs: 3 };
149
152
  for (const [name, stage] of Object.entries(sides)) {
150
- fs.writeFileSync(path.join(tmp, name), stageBytes(top, stage, file));
153
+ const bytes = stageBytes(top, stage, file);
154
+ if (bytes === null)
155
+ return { ok: false, problem: `git show :${stage}:${file} failed` };
156
+ fs.writeFileSync(path.join(tmp, name), bytes);
151
157
  }
152
158
  const merged = spawnSync("git", [
153
159
  "merge-file",
@@ -156,9 +162,9 @@ export function unionResolve(top, file) {
156
162
  path.join(tmp, "ours"),
157
163
  path.join(tmp, "base"),
158
164
  path.join(tmp, "theirs"),
159
- ], { cwd: top, env: gitEnv() });
165
+ ], { cwd: top, env: gitEnv(), maxBuffer: OUTPUT_LIMIT });
160
166
  // --union never leaves conflict markers, so a non-zero exit is an I/O failure.
161
- if (merged.status !== 0)
167
+ if (merged.error || merged.status !== 0)
162
168
  return { ok: false, problem: "git merge-file --union failed" };
163
169
  let text = merged.stdout.toString("utf-8");
164
170
  if (file.endsWith(".jsonl")) {
@@ -362,6 +368,7 @@ function openPrNumber(cwd, branch) {
362
368
  const res = spawnSync("gh", ["pr", "list", "--head", branch, "--state", "open", "--json", "number,state"], {
363
369
  cwd,
364
370
  encoding: "utf-8",
371
+ maxBuffer: OUTPUT_LIMIT,
365
372
  });
366
373
  const parsed = res.status === 0 ? parseJson(res.stdout ?? "") : { ok: false };
367
374
  const prs = parsed.ok ? parsed.value : undefined;
@@ -433,8 +440,11 @@ function rebaseVerb(ctx) {
433
440
  * Push the current branch with exactly one `git push`: plain for dev / main,
434
441
  * `--force-with-lease` otherwise. `abort` never pushes into an open PR (`openPr`:
435
442
  * the answer MCP gave; undefined asks gh, which throws EXIT.USE_MCP when it cannot).
443
+ * An in-place run on dev (a shared-checkout record exists) pushes only the
444
+ * commits it made: plain when they are all that local dev holds beyond
445
+ * origin/dev, else replayed onto a fresh origin/dev through `pushToDev`.
436
446
  */
437
- export function pushBranch(cwd, o, log) {
447
+ export async function pushBranch(cwd, o, log) {
438
448
  const { mode, openPr: openPrFlag } = o;
439
449
  if (openPrFlag !== undefined && openPrFlag !== "none" && !/^[1-9][0-9]*$/.test(openPrFlag)) {
440
450
  throw new CommandError(EXIT.USAGE, `--open-pr must be a PR number or none, got "${openPrFlag}"`);
@@ -449,6 +459,7 @@ export function pushBranch(cwd, o, log) {
449
459
  forced: false,
450
460
  skipped: null,
451
461
  prNumber: null,
462
+ replayed: false,
452
463
  ...extra,
453
464
  },
454
465
  });
@@ -460,14 +471,30 @@ export function pushBranch(cwd, o, log) {
460
471
  log(`--mode=dev pushes ${DEV}, but the checkout is on ${branch}`);
461
472
  return notPushed(EXIT_NOT_DEV);
462
473
  }
474
+ if (mode === "plain")
475
+ return pushPlain(cwd, branch, o, log, notPushed);
476
+ const shared = isSharedBranch(branch);
477
+ const rec = !shared
478
+ ? null
479
+ : o.fid === undefined
480
+ ? recordOnBranch(cwd, branch)
481
+ : activeRecord(cwd, o.fid);
482
+ // Without the run's record the push would carry all of local dev, not the run's commits.
483
+ if (shared && rec === null && (mode === "dev" || o.fid !== undefined)) {
484
+ log(`no shared-checkout record${o.fid === undefined ? "" : ` for ${o.fid}`} on ${branch} — refusing to push: it would carry commits the run does not own`);
485
+ return notPushed(EXIT_NO_RECORD);
486
+ }
463
487
  if (o.requireCi === true) {
464
- const message = git(cwd, ["log", "-1", "--pretty=%B"]) ?? "";
488
+ // With a record, the commit that reaches the remote last is the run's own.
489
+ const last = rec?.commits.at(-1) ?? "HEAD";
490
+ const message = git(cwd, ["log", "-1", "--pretty=%B", last]) ?? "";
465
491
  if (SKIP_CI_TOKEN.test(message)) {
466
492
  log(`HEAD message on ${branch} carries a CI-suppressing token, and this push needs a CI run — refusing`);
467
493
  return notPushed(EXIT_SKIP_CI, { skipped: "skip-ci" });
468
494
  }
469
495
  }
470
- const shared = isSharedBranch(branch);
496
+ if (rec !== null)
497
+ return pushOwnCommits(cwd, rec, o, log, notPushed);
471
498
  if (mode === "abort" && !shared) {
472
499
  const pr = openPrFlag === undefined
473
500
  ? openPrNumber(cwd, branch)
@@ -503,25 +530,476 @@ export function pushBranch(cwd, o, log) {
503
530
  forced: !shared,
504
531
  skipped: null,
505
532
  prNumber: null,
533
+ replayed: false,
506
534
  },
507
535
  };
508
536
  }
509
- function pushVerb(ctx) {
537
+ /**
538
+ * `git fetch` of `ref` when it names a branch of origin (`origin/<b>`); null when
539
+ * it names anything else (a SHA, a local branch), which needs no fetch.
540
+ */
541
+ export function fetchRemoteRef(cwd, ref) {
542
+ const m = new RegExp(`^${REMOTE}/(.+)$`).exec(ref);
543
+ if (!m)
544
+ return null;
545
+ return runGit(cwd, ["fetch", REMOTE, `+refs/heads/${m[1]}:refs/remotes/${REMOTE}/${m[1]}`]);
546
+ }
547
+ /** Commits HEAD holds beyond `ref`; 0 when the count cannot be read. */
548
+ function commitsAhead(cwd, ref) {
549
+ const n = Number(git(cwd, ["rev-list", "--count", `${ref}..HEAD`]) ?? "0");
550
+ return Number.isFinite(n) ? n : 0;
551
+ }
552
+ /**
553
+ * `--mode=plain`: one `git push [-u] origin <branch>`, never forced. A feature
554
+ * branch only: dev / main and a branch with nothing beyond `aheadOf` have nothing to ship.
555
+ */
556
+ function pushPlain(cwd, branch, o, log, notPushed) {
557
+ if (isSharedBranch(branch)) {
558
+ log(`Nothing to ship: on '${branch}', no feature branch`);
559
+ return notPushed(EXIT_NOTHING_TO_PUSH);
560
+ }
561
+ if (o.aheadOf !== undefined) {
562
+ const fetched = fetchRemoteRef(cwd, o.aheadOf);
563
+ if (fetched !== null && !fetched.ok) {
564
+ log(`git fetch for ${o.aheadOf} failed: ${fetched.stderr} — counting against the local ref`);
565
+ }
566
+ if (commitsAhead(cwd, o.aheadOf) === 0) {
567
+ log(`Nothing to ship: ${branch} has no commits ahead of ${o.aheadOf}`);
568
+ return notPushed(EXIT_NOTHING_TO_PUSH);
569
+ }
570
+ }
571
+ if (o.requireCi === true && SKIP_CI_TOKEN.test(git(cwd, ["log", "-1", "--pretty=%B"]) ?? "")) {
572
+ log(`HEAD message on ${branch} carries a CI-suppressing token, and this push needs a CI run — refusing`);
573
+ return notPushed(EXIT_SKIP_CI, { skipped: "skip-ci" });
574
+ }
575
+ const args = ["push", ...(o.setUpstream === true ? ["-u"] : []), REMOTE, branch];
576
+ const res = runGit(cwd, args);
577
+ if (!res.ok) {
578
+ log(`git ${args.join(" ")} failed: ${res.stderr}`);
579
+ return notPushed(EXIT_PUSH_FAILED);
580
+ }
581
+ log(`pushed ${branch}`);
582
+ return {
583
+ code: EXIT.OK,
584
+ out: {
585
+ pushed: true,
586
+ ref: branch,
587
+ sha: git(cwd, ["rev-parse", "HEAD"]),
588
+ forced: false,
589
+ skipped: null,
590
+ prNumber: null,
591
+ replayed: false,
592
+ },
593
+ };
594
+ }
595
+ /**
596
+ * The `key` of an engine-action row for a marker commit this run makes: keyed on the
597
+ * workflow's latest run, in progress or just closed by `workflows close`.
598
+ */
599
+ function markerKey(file, workflow, what) {
600
+ const runs = fs.existsSync(file) ? readRuns(file).filter((r) => r.workflow === workflow) : [];
601
+ return actionKey(workflow, Math.max(runs.length, 1), what);
602
+ }
603
+ /**
604
+ * Make a marker commit once per run: an engine-action row with the same key and
605
+ * message whose commit is still on HEAD means it is already made (`deduped`).
606
+ * `addAll` stages every change first (`git add -A`); the commit is always
607
+ * allowed to be empty. The row is written before the caller pushes.
608
+ */
609
+ function markerCommit(cwd, o) {
610
+ const hash = actionHash(o.message);
611
+ const prior = alreadyDone(o.file, o.key, hash);
612
+ if (prior?.ref && runGit(cwd, ["merge-base", "--is-ancestor", prior.ref, "HEAD"]).ok) {
613
+ return { sha: prior.ref, deduped: true };
614
+ }
615
+ if (o.addAll) {
616
+ const added = runGit(cwd, ["add", "-A"]);
617
+ if (!added.ok)
618
+ throw new CommandError(EXIT_PUSH_FAILED, `git add -A failed: ${added.stderr}`);
619
+ }
620
+ const made = runGit(cwd, ["commit", "--allow-empty", "-m", o.message]);
621
+ if (!made.ok) {
622
+ throw new CommandError(EXIT_PUSH_FAILED, `git commit failed: ${made.stderr || made.stdout}`);
623
+ }
624
+ const sha = git(cwd, ["rev-parse", "HEAD"]) ?? "";
625
+ recordAction(o.file, { action: "commit", key: o.key, hash, ref: sha });
626
+ return { sha, deduped: false };
627
+ }
628
+ const autoRouteSuffix = (labels) => labels.includes(AUTO_LABEL) ? AUTO_ROUTE_SUFFIX : "";
629
+ /** A replayed commit that does not apply onto origin/dev without the foreign commits it builds on. */
630
+ class ReplayConflict extends Error {
631
+ }
632
+ /**
633
+ * The `pushToDev` build callback that replays `shas` (oldest first) onto the
634
+ * fresh origin/dev in `dir`, each as a cherry-pick that keeps its message and
635
+ * author and keeps empty commits. A commit that does not apply throws a
636
+ * ReplayConflict naming the conflicting paths, after aborting the cherry-pick.
637
+ */
638
+ export function replayBuild(shas) {
639
+ return (dir) => {
640
+ for (const sha of shas) {
641
+ const picked = runGit(dir, ["cherry-pick", "--allow-empty", "--keep-redundant-commits", sha]);
642
+ if (picked.ok)
643
+ continue;
644
+ const paths = (git(dir, ["diff", "--name-only", "--diff-filter=U"]) ?? "")
645
+ .split("\n")
646
+ .filter(Boolean);
647
+ runGit(dir, ["cherry-pick", "--abort"]);
648
+ throw new ReplayConflict(`commit ${sha.slice(0, 12)} does not apply onto ${UPSTREAM} without the local ${DEV} commits it builds on — ${paths.length > 0 ? `conflicts in: ${paths.join(", ")}` : picked.stderr}`);
649
+ }
650
+ };
651
+ }
652
+ /**
653
+ * Push only the commits an in-place run on dev made (the record's `commits`).
654
+ * Plain push of their tip SHA when origin/dev is an ancestor of local dev and they
655
+ * are exactly what local dev holds beyond it; otherwise (a foreign commit among
656
+ * them, origin/dev moved, or the plain push is rejected) they are replayed onto a
657
+ * fresh origin/dev in the throwaway checkout and pushed from there.
658
+ */
659
+ async function pushOwnCommits(cwd, rec, o, log, notPushed) {
660
+ const gone = rec.commits.filter((c) => !runGit(cwd, ["merge-base", "--is-ancestor", c, "HEAD"]).ok);
661
+ if (gone.length > 0) {
662
+ log(`the run's commit(s) ${gone.map((c) => c.slice(0, 12)).join(", ")} are no longer on ${rec.branch} — refusing to push`);
663
+ return notPushed(EXIT_PUSH_FAILED);
664
+ }
665
+ const fetched = runGit(cwd, ["fetch", REMOTE, `+refs/heads/${DEV}:refs/remotes/${UPSTREAM}`]);
666
+ if (!fetched.ok) {
667
+ log(`git fetch ${REMOTE} ${DEV} failed: ${fetched.stderr}`);
668
+ return notPushed(EXIT_FETCH_FAILED);
669
+ }
670
+ // Oldest first, minus what origin/dev already has (pushed plain before) and
671
+ // what an earlier replay already landed.
672
+ const mine = new Set(rec.commits);
673
+ const landed = new Set(rec.pushed ?? []);
674
+ const range = runGit(cwd, ["rev-parse", "-q", "--verify", `${rec.startSha}^{commit}`]).ok
675
+ ? `${rec.startSha}..HEAD`
676
+ : "HEAD";
677
+ const pending = (git(cwd, ["rev-list", "--reverse", range]) ?? "")
678
+ .split("\n")
679
+ .filter((c) => mine.has(c) &&
680
+ !landed.has(c) &&
681
+ !runGit(cwd, ["merge-base", "--is-ancestor", c, UPSTREAM]).ok);
682
+ if (pending.length === 0) {
683
+ log("every commit the run made is already on origin/dev — nothing to push");
684
+ return notPushed(EXIT.OK, { skipped: "no-run-commits" });
685
+ }
686
+ const ahead = (git(cwd, ["rev-list", "--reverse", `${UPSTREAM}..HEAD`]) ?? "")
687
+ .split("\n")
688
+ .filter(Boolean);
689
+ // Plain only when origin/dev is an ancestor of local dev (a fast-forward) and
690
+ // the run's commits are all local dev holds beyond it; the explicit SHA keeps
691
+ // a commit made after the check out of the push.
692
+ const fastForward = runGit(cwd, ["merge-base", "--is-ancestor", UPSTREAM, "HEAD"]).ok;
693
+ if (fastForward && ahead.length === pending.length && ahead.every((c, i) => c === pending[i])) {
694
+ const last = pending[pending.length - 1];
695
+ const args = [
696
+ "push",
697
+ ...(o.setUpstream === true ? ["-u"] : []),
698
+ REMOTE,
699
+ `${last}:refs/heads/${rec.branch}`,
700
+ ];
701
+ const res = runGit(cwd, args);
702
+ if (res.ok) {
703
+ log(`pushed ${rec.branch}: the run's ${pending.length} commit(s) are all local dev holds`);
704
+ return {
705
+ code: EXIT.OK,
706
+ out: {
707
+ pushed: true,
708
+ ref: rec.branch,
709
+ sha: last,
710
+ forced: false,
711
+ skipped: null,
712
+ prNumber: null,
713
+ replayed: false,
714
+ },
715
+ };
716
+ }
717
+ log(`git ${args.join(" ")} failed: ${res.stderr} — replaying onto a fresh ${UPSTREAM}`);
718
+ }
719
+ const root = repoRoot(cwd);
720
+ let res;
721
+ try {
722
+ res = await pushToDev({
723
+ root,
724
+ dir: landDir(root, rec.fid),
725
+ build: replayBuild(pending),
726
+ log,
727
+ });
728
+ }
729
+ catch (err) {
730
+ if (!(err instanceof ReplayConflict))
731
+ throw err;
732
+ log(`replaying the run's commits onto ${UPSTREAM} stopped: ${err.message}`);
733
+ return notPushed(EXIT_MERGE_CONFLICT);
734
+ }
735
+ switch (res.kind) {
736
+ case "landed":
737
+ markRecordPushed(cwd, rec.fid, pending);
738
+ log(`pushed ${pending.length} commit(s) of the run to ${DEV} as copies on a fresh ${UPSTREAM} (${res.sha.slice(0, 12)}); local ${DEV} still holds the originals beside other commits — resync with: git pull --rebase ${REMOTE} ${DEV}`);
739
+ return {
740
+ code: EXIT.OK,
741
+ out: {
742
+ pushed: true,
743
+ ref: rec.branch,
744
+ sha: res.sha,
745
+ forced: false,
746
+ skipped: null,
747
+ prNumber: null,
748
+ replayed: true,
749
+ },
750
+ };
751
+ case "refused":
752
+ log(`${DEV} refused the push: ${res.stderr}`);
753
+ return notPushed(EXIT_PUSH_FAILED);
754
+ case "push-failed":
755
+ log(`push to ${DEV} failed without a server answer: ${res.stderr}`);
756
+ return notPushed(EXIT_PUSH_FAILED);
757
+ case "exhausted":
758
+ log(`${DEV} moved before each of ${res.attempts} pushes`);
759
+ return notPushed(EXIT_PUSH_FAILED);
760
+ case "fetch-failed":
761
+ log(`git fetch ${REMOTE} ${DEV} failed: ${res.stderr}`);
762
+ return notPushed(EXIT_FETCH_FAILED);
763
+ case "setup-failed":
764
+ log(`throwaway checkout failed: ${res.stderr}`);
765
+ return notPushed(EXIT_PUSH_FAILED);
766
+ }
767
+ }
768
+ async function pushVerb(ctx) {
510
769
  const mode = String(ctx.flags.mode);
511
- if (!["feature", "abort", "dev"].includes(mode)) {
512
- throw new CommandError(EXIT.USAGE, "--mode must be feature, abort, or dev");
770
+ if (!["feature", "abort", "dev", "plain"].includes(mode)) {
771
+ throw new CommandError(EXIT.USAGE, "--mode must be feature, abort, dev, or plain");
772
+ }
773
+ const aheadOf = str(ctx.flags.aheadOf);
774
+ if (aheadOf !== undefined && mode !== "plain") {
775
+ throw new CommandError(EXIT.USAGE, "--ahead-of applies to --mode=plain only");
776
+ }
777
+ const commitMessage = str(ctx.flags.commit);
778
+ let marker;
779
+ if (commitMessage !== undefined) {
780
+ const file = str(ctx.flags.file);
781
+ const workflow = str(ctx.flags.workflow);
782
+ if (mode !== "feature" || file === undefined || workflow === undefined) {
783
+ throw new CommandError(EXIT.USAGE, "--commit needs --mode=feature, --file (status.jsonl) and --workflow");
784
+ }
785
+ const branch = currentBranch(ctx.cwd);
786
+ if (branch === "") {
787
+ ctx.log("no branch checked out (detached HEAD) — refusing to commit and push");
788
+ return EXIT_DETACHED;
789
+ }
790
+ if (isSharedBranch(branch)) {
791
+ ctx.log(`Nothing to ship: --commit makes a marker commit on a feature branch, not '${branch}'`);
792
+ return EXIT_NOTHING_TO_PUSH;
793
+ }
794
+ const message = `${commitMessage}${autoRouteSuffix(ctx.flags.label ?? [])}`;
795
+ if (ctx.flags.requireCi === true && SKIP_CI_TOKEN.test(message)) {
796
+ ctx.log("the --commit message carries a CI-suppressing token, and this push needs a CI run — refusing");
797
+ ctx.emit({
798
+ pushed: false,
799
+ ref: null,
800
+ sha: null,
801
+ forced: false,
802
+ skipped: "skip-ci",
803
+ prNumber: null,
804
+ replayed: false,
805
+ });
806
+ return EXIT_SKIP_CI;
807
+ }
808
+ marker = markerCommit(ctx.cwd, {
809
+ file: path.resolve(ctx.cwd, file),
810
+ key: markerKey(path.resolve(ctx.cwd, file), workflow, "push-commit"),
811
+ message,
812
+ addAll: true,
813
+ });
814
+ if (marker.deduped)
815
+ ctx.log(`marker commit ${marker.sha.slice(0, 12)} already made this run — pushing it`);
513
816
  }
514
- const r = pushBranch(ctx.cwd, {
817
+ const r = await pushBranch(ctx.cwd, {
515
818
  mode: mode,
516
819
  setUpstream: ctx.flags.setUpstream === true,
820
+ aheadOf,
517
821
  requireCi: ctx.flags.requireCi === true,
518
822
  openPr: str(ctx.flags.openPr),
823
+ fid: str(ctx.flags.fid),
519
824
  }, ctx.log);
520
825
  // A detached HEAD and a wrong checkout print nothing, as the push never got to run.
521
- if (r.code !== EXIT_DETACHED && r.code !== EXIT_NOT_DEV)
522
- ctx.emit(r.out);
826
+ if (r.code !== EXIT_DETACHED && r.code !== EXIT_NOT_DEV) {
827
+ ctx.emit(marker === undefined ? r.out : { ...r.out, commit: marker.sha, deduped: marker.deduped });
828
+ }
523
829
  return r.code;
524
830
  }
831
+ function fastForwardVerb(ctx) {
832
+ const onto = String(ctx.flags.onto);
833
+ const top = topLevel(ctx.cwd);
834
+ const fetched = fetchRemoteRef(top, onto);
835
+ if (fetched !== null && !fetched.ok) {
836
+ ctx.log(`git fetch for ${onto} failed: ${fetched.stderr}`);
837
+ return EXIT_FETCH_FAILED;
838
+ }
839
+ if (!runGit(top, ["rev-parse", "-q", "--verify", `${onto}^{commit}`]).ok) {
840
+ ctx.log(`unknown ref: ${onto}`);
841
+ return EXIT_FETCH_FAILED;
842
+ }
843
+ const before = git(top, ["rev-parse", "HEAD"]);
844
+ if (runGit(top, ["merge-base", "--is-ancestor", onto, "HEAD"]).ok) {
845
+ ctx.emit({ moved: false, head: before });
846
+ return EXIT.OK;
847
+ }
848
+ const merged = runGit(top, ["merge", "--ff-only", onto]);
849
+ if (!merged.ok) {
850
+ ctx.log(`local ${currentBranch(top) || "HEAD"} diverged from ${onto} — reconcile, then re-run`);
851
+ return EXIT_DIVERGED;
852
+ }
853
+ const head = git(top, ["rev-parse", "HEAD"]);
854
+ ctx.log(`fast-forwarded onto ${onto} (${head?.slice(0, 12) ?? ""})`);
855
+ ctx.emit({ moved: head !== before, head });
856
+ return EXIT.OK;
857
+ }
858
+ /** Paths a source-change check leaves out: plan logs and the append-only ledgers. */
859
+ const NOT_CODE = [":(exclude)docs/plans", ":(exclude)docs/*.jsonl", ":(exclude).bkit/*.jsonl"];
860
+ function scanDiffVerb(ctx) {
861
+ const base = String(ctx.flags.base);
862
+ const pattern = str(ctx.flags.paths);
863
+ const marker = str(ctx.flags.marker);
864
+ const code = ctx.flags.code === true;
865
+ if ([pattern !== undefined, marker !== undefined, code].filter(Boolean).length !== 1) {
866
+ throw new CommandError(EXIT.USAGE, "give exactly one of --paths, --marker, --code");
867
+ }
868
+ let re;
869
+ if (pattern !== undefined) {
870
+ try {
871
+ re = new RegExp(pattern, "i");
872
+ }
873
+ catch (err) {
874
+ ctx.log(`--paths is not a valid pattern: ${err.message}`);
875
+ return EXIT.USAGE;
876
+ }
877
+ }
878
+ const top = topLevel(ctx.cwd);
879
+ const fetched = fetchRemoteRef(top, base);
880
+ if (fetched !== null && !fetched.ok) {
881
+ ctx.log(`git fetch for ${base} failed: ${fetched.stderr} — diffing against the local ref`);
882
+ }
883
+ if (!runGit(top, ["rev-parse", "-q", "--verify", `${base}^{commit}`]).ok) {
884
+ ctx.log(`unknown base: ${base}`);
885
+ return EXIT_DIFF_FAILED;
886
+ }
887
+ const range = `${base}...HEAD`;
888
+ let paths;
889
+ if (marker !== undefined) {
890
+ const diff = quietGit(top, ["diff", "--no-renames", range, "--", ".", ":(exclude)docs/plans"]);
891
+ if (!diff.ok) {
892
+ ctx.log(`git diff ${range} failed: ${diff.stderr}`);
893
+ return EXIT_DIFF_FAILED;
894
+ }
895
+ const hits = new Set();
896
+ let file = "";
897
+ for (const line of diff.stdout.split("\n")) {
898
+ if (line.startsWith("+++ ")) {
899
+ file = line.replace(/^\+\+\+ (b\/)?/, "");
900
+ continue;
901
+ }
902
+ if (line.startsWith("+") && line.includes(marker))
903
+ hits.add(file);
904
+ }
905
+ paths = [...hits];
906
+ }
907
+ else {
908
+ const diff = quietGit(top, [
909
+ "diff",
910
+ "--name-only",
911
+ "-z",
912
+ "--no-renames",
913
+ range,
914
+ ...(code ? ["--", ".", ...NOT_CODE] : []),
915
+ ]);
916
+ if (!diff.ok) {
917
+ ctx.log(`git diff ${range} failed: ${diff.stderr}`);
918
+ return EXIT_DIFF_FAILED;
919
+ }
920
+ paths = diff.stdout.split("\0").filter(Boolean);
921
+ if (re !== undefined)
922
+ paths = paths.filter((p) => re.test(p));
923
+ }
924
+ ctx.emit({ found: paths.length > 0, paths });
925
+ if (ctx.flags.expectNone === true) {
926
+ if (paths.length > 0) {
927
+ ctx.log(marker !== undefined
928
+ ? `added lines still carry ${marker} in: ${paths.join(", ")}`
929
+ : `expected no match, found: ${paths.join(", ")}`);
930
+ }
931
+ return paths.length > 0 ? EXIT.NO : EXIT.OK;
932
+ }
933
+ return paths.length > 0 ? EXIT.OK : EXIT.NO;
934
+ }
935
+ async function forceBuildVerb(ctx) {
936
+ const f = ctx.flags;
937
+ const fid = String(f.fid);
938
+ const file = path.resolve(ctx.cwd, String(f.file));
939
+ const workflow = String(f.workflow);
940
+ const openPrFlag = str(f.openPr);
941
+ if (openPrFlag !== undefined && openPrFlag !== "none" && !/^[1-9][0-9]*$/.test(openPrFlag)) {
942
+ throw new CommandError(EXIT.USAGE, `--open-pr must be a PR number or none, got "${openPrFlag}"`);
943
+ }
944
+ const branch = currentBranch(ctx.cwd);
945
+ if (branch === "") {
946
+ ctx.log("no branch checked out (detached HEAD) — refusing to force a build");
947
+ return EXIT_DETACHED;
948
+ }
949
+ if (isSharedBranch(branch)) {
950
+ ctx.log(`Nothing to ship: force-build marks a feature branch, not '${branch}'`);
951
+ return EXIT_NOTHING_TO_PUSH;
952
+ }
953
+ // (1) The PR title: CI reads the marker from it on pull_request events.
954
+ const viaMcp = (why) => {
955
+ ctx.log(`${why} — add " bkit ${FORCE_BUILD}" to the open PR's title through update_pull_request (skip when no PR is open), then re-run with --title-set`);
956
+ return EXIT.USE_MCP;
957
+ };
958
+ let prNumber = null;
959
+ let titleChanged = false;
960
+ if (f.titleSet !== true && openPrFlag !== "none") {
961
+ const probe = probePr(ctx.cwd, openPrFlag === undefined
962
+ ? { head: branch, state: "open" }
963
+ : { number: openPrFlag, state: "open" });
964
+ if (probe.kind !== "ok")
965
+ return viaMcp(probe.message);
966
+ if (probe.pr) {
967
+ prNumber = probe.pr.number;
968
+ if (!probe.pr.title.includes(FORCE_BUILD)) {
969
+ const next = `${probe.pr.title} bkit ${FORCE_BUILD}`;
970
+ const edit = runGh(ctx.cwd, ["pr", "edit", String(prNumber), "--title", next]);
971
+ if (!edit.ok) {
972
+ return viaMcp(ghUnavailable(edit)
973
+ ? "gh unavailable for gh pr edit"
974
+ : `gh pr edit ${prNumber} failed: ${edit.stderr}`);
975
+ }
976
+ titleChanged = true;
977
+ ctx.log(`PR #${prNumber} title now carries ${FORCE_BUILD}`);
978
+ }
979
+ }
980
+ }
981
+ // (2) The empty marker commit, once per run; its push is the event that starts the run.
982
+ const message = `chore(${fid}): force build bkit ${FORCE_BUILD}${autoRouteSuffix(f.label ?? [])}`;
983
+ const marker = markerCommit(ctx.cwd, {
984
+ file,
985
+ key: markerKey(file, workflow, "force-build"),
986
+ message,
987
+ addAll: false,
988
+ });
989
+ if (marker.deduped)
990
+ ctx.log(`force-build commit ${marker.sha.slice(0, 12)} already made this run — pushing it`);
991
+ const pushed = await pushBranch(ctx.cwd, { mode: "feature", requireCi: true }, ctx.log);
992
+ ctx.emit({
993
+ prNumber,
994
+ titleChanged,
995
+ commit: marker.sha,
996
+ deduped: marker.deduped,
997
+ pushed: pushed.out.pushed,
998
+ ref: pushed.out.ref,
999
+ sha: pushed.out.sha,
1000
+ });
1001
+ return pushed.code;
1002
+ }
525
1003
  /** Resolve sync's docs-merge conflicts: ledgers by union, other `docs/` paths take dev's side. */
526
1004
  function resolveDocsMerge(top) {
527
1005
  const conflicts = unmergedPaths(top);
@@ -620,11 +1098,6 @@ function syncVerb(ctx) {
620
1098
  */
621
1099
  function syncDevVerb(ctx) {
622
1100
  const root = repoRoot(ctx.cwd);
623
- // `bkit install` can leave core.bare=true on the main checkout, which breaks `merge --ff-only` there.
624
- if (git(root, ["config", "--get", "core.bare"]) === "true" &&
625
- fs.statSync(path.join(root, ".git"), { throwIfNoEntry: false })?.isDirectory()) {
626
- runGit(root, ["config", "core.bare", "false"]);
627
- }
628
1101
  const fetch = runGit(root, ["fetch", REMOTE, DEV]);
629
1102
  if (!fetch.ok) {
630
1103
  ctx.log(`git fetch ${REMOTE} ${DEV} failed: ${fetch.stderr}`);
@@ -655,11 +1128,9 @@ function install(ctx, root) {
655
1128
  // ---------------------------------------------------------------------------
656
1129
  /** What a design / plan close may bring to dev: docs and ledgers, nothing else. */
657
1130
  const CLOSE_DOCS = /^docs\/plans\/|^docs\/roadmap\.md$|^docs\/[^/]+\.jsonl$|^\.bkit\/[^/]+\.jsonl$/;
658
- /** The canonical docs `ref` carries for the feature: design, or plan plus sub-plans. */
1131
+ /** The canonical doc `ref` carries for the feature: `{fid}-design.md` or `{fid}-plan.md`. */
659
1132
  function canonicalDocs(root, ref, workflow, month, fid) {
660
- const re = workflow === "plan"
661
- ? new RegExp(`^docs/plans/${month}/${fid}-plan(-[0-9]+)?\\.md$`)
662
- : new RegExp(`^docs/plans/${month}/${fid}-design\\.md$`);
1133
+ const re = new RegExp(`^docs/plans/${month}/${fid}-${workflow}\\.md$`);
663
1134
  return (git(root, ["ls-tree", "-r", "--name-only", ref, "--", `docs/plans/${month}/`]) ?? "")
664
1135
  .split("\n")
665
1136
  .filter((f) => re.test(f));
@@ -825,7 +1296,7 @@ async function landPr(ctx, root, o) {
825
1296
  .filter((p) => p !== "" && !CLOSE_DOCS.test(p));
826
1297
  if (stray.length)
827
1298
  throw new Stop(EXIT_LAND_STOPPED, `${o.workflow} close diff carries non-doc files:\n${stray.join("\n")}`);
828
- const pushed = pushBranch(tree, { mode: "feature" }, ctx.log);
1299
+ const pushed = await pushBranch(tree, { mode: "feature" }, ctx.log);
829
1300
  if (pushed.code !== EXIT.OK)
830
1301
  throw new Stop(EXIT_PUSH_FAILED, "close-commit push failed — the PR would not carry the roadmap row or the close status rows");
831
1302
  const opened = openPrFor(tree, {
@@ -853,6 +1324,8 @@ async function landPr(ctx, root, o) {
853
1324
  ctx.emit({ stage: "merge", prNumber: Number(prNumber), subject, body: "" });
854
1325
  return EXIT.USE_MCP;
855
1326
  }
1327
+ if (merged.code === EXIT_BASE_NOT_DEV)
1328
+ throw new Stop(EXIT_LAND_STOPPED, `PR ${prNumber} does not target ${DEV} — bkit merges into ${DEV} only, releases stay manual; nothing merged, PR left open`);
856
1329
  if (merged.out.merged) {
857
1330
  sha = merged.out.mergeCommitOid ?? "";
858
1331
  break;
@@ -954,11 +1427,6 @@ async function landVerb(ctx) {
954
1427
  const fid = String(ctx.flags.fid);
955
1428
  const root = repoRoot(ctx.cwd);
956
1429
  const month = resolveMonth(root, fid, str(ctx.flags.month));
957
- // `bkit install` can leave core.bare=true on the main checkout, which breaks every worktree below.
958
- if (git(root, ["config", "--get", "core.bare"]) === "true" &&
959
- fs.statSync(path.join(root, ".git"), { throwIfNoEntry: false })?.isDirectory()) {
960
- runGit(root, ["config", "core.bare", "false"]);
961
- }
962
1430
  const worktreeStatus = path.join(git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root, "docs", "plans", month, "logs", fid, "status.jsonl");
963
1431
  try {
964
1432
  const devPushes = devPushesOf(root, worktreeStatus, ctx.log);
@@ -1178,9 +1646,27 @@ export const branchesCommand = {
1178
1646
  name: "mode",
1179
1647
  type: "string",
1180
1648
  required: true,
1181
- help: "feature (a step's push) | abort (Failure Path: never into an open PR) | dev (the checkout must be on dev)",
1649
+ help: "feature (a step's push) | abort (Failure Path: never into an open PR) | dev (the checkout must be on dev) | plain (a feature branch, never forced)",
1182
1650
  },
1183
1651
  { name: "set-upstream", type: "boolean", help: "push with -u" },
1652
+ {
1653
+ name: "ahead-of",
1654
+ type: "string",
1655
+ help: "--mode=plain: refuse (21) when HEAD has no commits beyond this ref; an origin/<branch> ref is fetched first",
1656
+ },
1657
+ {
1658
+ name: "commit",
1659
+ type: "string",
1660
+ help: "--mode=feature: `git add -A`, then an allow-empty commit with this message (plus ` bkit [auto route]` when --label holds bkit:auto), once per run, before the push",
1661
+ },
1662
+ {
1663
+ name: "label",
1664
+ type: "string",
1665
+ repeatable: true,
1666
+ help: "--commit: the issue's labels, one per flag",
1667
+ },
1668
+ { name: "file", type: "string", help: "--commit: status.jsonl for the engine-action row" },
1669
+ { name: "workflow", type: "string", help: "--commit: the workflow, for the run number" },
1184
1670
  {
1185
1671
  name: "require-ci",
1186
1672
  type: "boolean",
@@ -1191,24 +1677,138 @@ export const branchesCommand = {
1191
1677
  type: "string",
1192
1678
  help: "--mode=abort: the open-PR answer from MCP (a number, or none) instead of asking gh",
1193
1679
  },
1680
+ {
1681
+ name: "fid",
1682
+ type: "string",
1683
+ help: "an in-place run on dev: its FID, which selects the run's shared-checkout record; with it a missing record refuses the push",
1684
+ },
1194
1685
  ],
1195
1686
  output: {
1196
1687
  pushed: "true when the push ran and succeeded",
1688
+ replayed: "true when the run's commits went out as copies cherry-picked onto a fresh origin/dev (an in-place run on dev whose local dev holds other commits); sha is then the landed origin/dev commit",
1197
1689
  ref: "the branch pushed — link handover artifacts to this ref; null when nothing was pushed",
1198
1690
  sha: "HEAD commit pushed (null when not pushed)",
1199
1691
  forced: "true when pushed with --force-with-lease",
1200
- skipped: "why the push did not run: open-pr | skip-ci (null otherwise)",
1692
+ skipped: "why the push did not run: open-pr | skip-ci | no-run-commits (an in-place run on dev with nothing new to push) (null otherwise)",
1201
1693
  prNumber: "the open PR that stopped an abort push (null otherwise)",
1694
+ commit: "--commit: the marker commit's sha",
1695
+ deduped: "--commit: the marker commit was already made this run (not made again)",
1202
1696
  },
1203
1697
  exitCodes: {
1204
1698
  [EXIT_DETACHED]: "no branch checked out",
1699
+ [EXIT_NOTHING_TO_PUSH]: "--mode=plain or --commit on dev / main, or --ahead-of and HEAD has no commits beyond it",
1205
1700
  [EXIT_SKIP_CI]: "--require-ci and the HEAD message carries a skip-CI token",
1206
1701
  [EXIT_OPEN_PR]: "--mode=abort and the branch has an open PR: push skipped, remote HEAD kept",
1207
- [EXIT_PUSH_FAILED]: "git push failed",
1702
+ [EXIT_PUSH_FAILED]: "git push failed, or dev refused a replayed push (in-place run on dev: the refusal is printed)",
1208
1703
  [EXIT_NOT_DEV]: "--mode=dev and the checkout is not on dev",
1704
+ [EXIT_NO_RECORD]: "--mode=dev, or --fid, on dev with no shared-checkout record for the run: nothing pushed",
1705
+ [EXIT_FETCH_FAILED]: "in-place run on dev: fetching origin/dev failed",
1706
+ [EXIT_MERGE_CONFLICT]: "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",
1209
1707
  },
1210
1708
  run: pushVerb,
1211
1709
  },
1710
+ "fast-forward": {
1711
+ summary: "Fetch a remote branch and fast-forward the checkout onto it; refuse when diverged.",
1712
+ flags: [
1713
+ {
1714
+ name: "onto",
1715
+ type: "string",
1716
+ required: true,
1717
+ help: "the ref to fast-forward onto; an origin/<branch> ref is fetched first",
1718
+ },
1719
+ ],
1720
+ output: { moved: "HEAD moved", head: "HEAD after" },
1721
+ exitCodes: {
1722
+ [EXIT_FETCH_FAILED]: "fetching --onto failed, or it does not resolve",
1723
+ [EXIT_DIVERGED]: "the checkout has commits --onto lacks: nothing moved",
1724
+ },
1725
+ run: fastForwardVerb,
1726
+ },
1727
+ "scan-diff": {
1728
+ summary: "Exit 0 when the branch's diff from --base matches (paths, an added marker line, or a source change); 1 when not.",
1729
+ flags: [
1730
+ {
1731
+ name: "base",
1732
+ type: "string",
1733
+ required: true,
1734
+ help: "diff <base>...HEAD; an origin/<branch> base is fetched first",
1735
+ },
1736
+ {
1737
+ name: "paths",
1738
+ type: "string",
1739
+ help: "a changed path matches this pattern (case-insensitive)",
1740
+ },
1741
+ {
1742
+ name: "marker",
1743
+ type: "string",
1744
+ help: "an added line carries this text, outside docs/plans",
1745
+ },
1746
+ {
1747
+ name: "code",
1748
+ type: "boolean",
1749
+ help: "a path changed outside docs/plans, docs/*.jsonl and .bkit/*.jsonl",
1750
+ },
1751
+ {
1752
+ name: "expect-none",
1753
+ type: "boolean",
1754
+ help: "invert the exit: 0 when nothing matched, 1 (naming the paths on stderr) when something did",
1755
+ },
1756
+ ],
1757
+ output: { found: "something matched", paths: "the matching paths" },
1758
+ exitCodes: {
1759
+ [EXIT_DIFF_FAILED]: "--base does not resolve, or git diff failed",
1760
+ },
1761
+ run: scanDiffVerb,
1762
+ },
1763
+ "force-build": {
1764
+ summary: `Force a full CI build: put ${FORCE_BUILD} on the open PR's title, then push an empty marker commit (once per run).`,
1765
+ flags: [
1766
+ { name: "fid", type: "string", required: true, help: "feature id, for the commit subject" },
1767
+ {
1768
+ name: "file",
1769
+ type: "string",
1770
+ required: true,
1771
+ help: "status.jsonl for the engine-action row",
1772
+ },
1773
+ {
1774
+ name: "workflow",
1775
+ type: "string",
1776
+ required: true,
1777
+ help: "the workflow, for the run number",
1778
+ },
1779
+ {
1780
+ name: "label",
1781
+ type: "string",
1782
+ repeatable: true,
1783
+ help: "the issue's labels; bkit:auto adds ` bkit [auto route]` to the commit",
1784
+ },
1785
+ {
1786
+ name: "open-pr",
1787
+ type: "string",
1788
+ help: "the open-PR answer from MCP (a number, or none) instead of asking gh",
1789
+ },
1790
+ {
1791
+ name: "title-set",
1792
+ type: "boolean",
1793
+ help: "the title is handled (set through MCP, or no PR is open): skip gh",
1794
+ },
1795
+ ],
1796
+ output: {
1797
+ prNumber: "the open PR whose title was checked, or null",
1798
+ titleChanged: `the title gained ${FORCE_BUILD}`,
1799
+ commit: "the marker commit's sha",
1800
+ deduped: "the marker commit was already made this run",
1801
+ pushed: "the push ran and succeeded",
1802
+ ref: "the branch pushed",
1803
+ sha: "HEAD pushed",
1804
+ },
1805
+ exitCodes: {
1806
+ [EXIT_DETACHED]: "no branch checked out",
1807
+ [EXIT_NOTHING_TO_PUSH]: "on dev / main",
1808
+ [EXIT_PUSH_FAILED]: "git commit or git push failed",
1809
+ },
1810
+ run: forceBuildVerb,
1811
+ },
1212
1812
  rebase: {
1213
1813
  summary: "Drive a rebase to completion, auto-resolving ledger (union) and lockfile (regenerate) conflicts; refuse and abort on anything else.",
1214
1814
  flags: [
@@ -1296,7 +1896,7 @@ export const branchesCommand = {
1296
1896
  exitCodes: {
1297
1897
  [EXIT_PUSH_FAILED]: "dev moved before every one of LAND_ATTEMPTS pushes, or the PR branch push failed (nothing landed)",
1298
1898
  [EXIT_FETCH_FAILED]: `git fetch ${REMOTE} ${DEV} failed (nothing landed)`,
1299
- [EXIT_LAND_STOPPED]: "a guard stopped the land: stray files, failed squash, staged non-doc files, canonical blob mismatch, no checkout holds the branch, PR not opened / not merged after LAND_ATTEMPTS tries (nothing landed; the PR stays open)",
1899
+ [EXIT_LAND_STOPPED]: "a guard stopped the land: stray files, failed squash, staged non-doc files, canonical blob mismatch, no checkout holds the branch, PR not opened / not merged after LAND_ATTEMPTS tries, PR base not dev or unreadable (nothing landed; the PR stays open)",
1300
1900
  [EXIT_LANDED_UNVERIFIED]: "landed, but the body scan, transport cross-check or canonical-on-dev check failed",
1301
1901
  [EXIT_LOCK_LEFT]: "landed and audited, but the workflow lock file survived removal",
1302
1902
  },