@cbartens/bkit 6.1.0 → 6.2.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 (317) hide show
  1. package/.bkit/README.md +14 -12
  2. package/.bkit/core/.agents/docs.md +1 -11
  3. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-gateguard.cjs +30 -9
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +25 -27
  5. package/.bkit/core/.agents/rules.md +22 -9
  6. package/.bkit/core/.bkit/README.md +13 -11
  7. package/.bkit/core/.bkit/authoring.md +58 -13
  8. package/.bkit/core/.bkit/cli.md +43 -33
  9. package/.bkit/core/.bkit/cloud.md +93 -30
  10. package/.bkit/core/.bkit/install.md +55 -16
  11. package/.bkit/core/.bkit/jsonl.md +24 -7
  12. package/.bkit/core/.bkit/pipeline.md +8 -8
  13. package/.bkit/core/.bkit/prompts.md +160 -43
  14. package/.bkit/core/.bkit/providers.md +99 -36
  15. package/.bkit/core/.bkit/templates.md +167 -37
  16. package/.bkit/core/.bkit/trackers.md +39 -6
  17. package/.bkit/core/.bkit/workflows.md +344 -136
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +50 -27
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +11 -11
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +13 -8
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +14 -25
  22. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +20 -9
  23. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +8 -8
  24. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +14 -4
  25. package/.bkit/core/.opencode/plugin/bkit-guardrails.js +114 -0
  26. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +1 -1
  27. package/.bkit/core/docs/templates/bkit-audit-adoption.md +30 -6
  28. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  29. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  30. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  31. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  32. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +1 -1
  33. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  34. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  35. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +2 -2
  36. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  37. package/.bkit/core/docs/templates/bkit-audit-cost.md +1 -1
  38. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  39. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -3
  40. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +1 -1
  41. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  42. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +3 -3
  43. package/.bkit/core/docs/templates/bkit-audit-documentation.md +32 -2
  44. package/.bkit/core/docs/templates/bkit-audit-duplication.md +1 -1
  45. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  46. package/.bkit/core/docs/templates/bkit-audit-flakes.md +2 -2
  47. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -3
  48. package/.bkit/core/docs/templates/bkit-audit-issues.md +1 -1
  49. package/.bkit/core/docs/templates/bkit-audit-llm.md +2 -2
  50. package/.bkit/core/docs/templates/bkit-audit-logs.md +1 -1
  51. package/.bkit/core/docs/templates/bkit-audit-models.md +2 -2
  52. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  53. package/.bkit/core/docs/templates/bkit-audit-prompts.md +1 -1
  54. package/.bkit/core/docs/templates/bkit-audit-red-team.md +2 -2
  55. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  56. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  57. package/.bkit/core/docs/templates/bkit-audit-security.md +1 -1
  58. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  59. package/.bkit/core/docs/templates/bkit-audit-testing.md +3 -2
  60. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  61. package/.bkit/core/docs/templates/bkit-plan.md +38 -8
  62. package/.bkit/core/engine/checks/after/auth.ts +118 -47
  63. package/.bkit/core/engine/checks/after/github.ts +161 -37
  64. package/.bkit/core/engine/checks/after/index.ts +18 -3
  65. package/.bkit/core/engine/checks/after/tools.ts +245 -1
  66. package/.bkit/core/engine/checks/before/files.ts +59 -1
  67. package/.bkit/core/engine/checks/before/index.ts +8 -0
  68. package/.bkit/core/engine/checks/status-holes.ts +20 -26
  69. package/.bkit/core/engine/checks/tips/catalogue.ts +107 -10
  70. package/.bkit/core/engine/checks/tips/detect.ts +36 -3
  71. package/.bkit/core/engine/checks/tips/index.ts +1 -1
  72. package/.bkit/core/engine/cli.ts +13 -13
  73. package/.bkit/core/engine/commands/ci/ci.ts +124 -19
  74. package/.bkit/core/engine/commands/ci/push-gate.ts +101 -43
  75. package/.bkit/core/engine/commands/install/doctor.ts +5 -5
  76. package/.bkit/core/engine/commands/install/install.ts +28 -25
  77. package/.bkit/core/engine/commands/install/uninstall.ts +42 -30
  78. package/.bkit/core/engine/commands/install/upgrade.ts +14 -2
  79. package/.bkit/core/engine/commands/land.ts +2 -3
  80. package/.bkit/core/engine/commands/lib.ts +394 -39
  81. package/.bkit/core/engine/commands/registry.ts +1 -1
  82. package/.bkit/core/engine/commands/workflow/branches.ts +351 -78
  83. package/.bkit/core/engine/commands/workflow/challenge.ts +63 -14
  84. package/.bkit/core/engine/commands/workflow/context.ts +71 -10
  85. package/.bkit/core/engine/commands/workflow/counters.ts +298 -23
  86. package/.bkit/core/engine/commands/workflow/decisions.ts +260 -125
  87. package/.bkit/core/engine/commands/workflow/disk.ts +2 -1
  88. package/.bkit/core/engine/commands/workflow/feature-base.ts +66 -0
  89. package/.bkit/core/engine/commands/workflow/issues.ts +312 -17
  90. package/.bkit/core/engine/commands/workflow/junit.ts +204 -0
  91. package/.bkit/core/engine/commands/workflow/ledgers.ts +904 -99
  92. package/.bkit/core/engine/commands/workflow/locks.ts +186 -29
  93. package/.bkit/core/engine/commands/workflow/loops.ts +87 -0
  94. package/.bkit/core/engine/commands/workflow/open-decision.ts +251 -0
  95. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +8 -0
  96. package/.bkit/core/engine/commands/workflow/plans.ts +1 -1
  97. package/.bkit/core/engine/commands/workflow/prs.ts +311 -16
  98. package/.bkit/core/engine/commands/workflow/repo.ts +1 -1
  99. package/.bkit/core/engine/commands/workflow/run-facts.ts +6 -0
  100. package/.bkit/core/engine/commands/workflow/runs.ts +877 -174
  101. package/.bkit/core/engine/commands/workflow/runtime.ts +12 -4
  102. package/.bkit/core/engine/commands/workflow/status.ts +324 -11
  103. package/.bkit/core/engine/commands/workflow/step-table.ts +41 -15
  104. package/.bkit/core/engine/commands/workflow/steps.ts +604 -29
  105. package/.bkit/core/engine/commands/workflow/summary-findings.ts +1 -1
  106. package/.bkit/core/engine/commands/workflow/summary.ts +314 -8
  107. package/.bkit/core/engine/commands/workflow/tasks.ts +400 -27
  108. package/.bkit/core/engine/commands/workflow/tests-base.ts +319 -0
  109. package/.bkit/core/engine/commands/workflow/tests-changed.ts +138 -74
  110. package/.bkit/core/engine/commands/workflow/tests-jump.ts +93 -0
  111. package/.bkit/core/engine/commands/workflow/tests.ts +815 -182
  112. package/.bkit/core/engine/commands/workflow/tracker.ts +1134 -137
  113. package/.bkit/core/engine/commands/workflow/workflows.ts +100 -72
  114. package/.bkit/core/engine/commands/workflow/worktrees.ts +421 -57
  115. package/.bkit/core/engine/install/cloud-env.ts +38 -10
  116. package/.bkit/core/engine/install/managed-block.ts +105 -0
  117. package/.bkit/core/engine/install/manifest.ts +7 -1
  118. package/.bkit/core/engine/install/modules/claude.ts +6 -2
  119. package/.bkit/core/engine/install/modules/cloud.ts +84 -95
  120. package/.bkit/core/engine/install/modules/codex.ts +10 -2
  121. package/.bkit/core/engine/install/modules/core.ts +202 -26
  122. package/.bkit/core/engine/install/modules/opencode.ts +18 -23
  123. package/.bkit/core/engine/install/network-allowlist.ts +8 -3
  124. package/.bkit/core/engine/install/project-docs.ts +650 -0
  125. package/.bkit/core/engine/install/template-copies.ts +58 -5
  126. package/.bkit/core/engine/install/write.ts +128 -7
  127. package/.bkit/core/engine/ledgers/journal.ts +18 -10
  128. package/.bkit/core/engine/ledgers/migrate.ts +20 -8
  129. package/.bkit/core/engine/ledgers/status.ts +604 -8
  130. package/.bkit/core/engine/ledgers/telemetry.ts +115 -13
  131. package/.bkit/core/engine/render/trackers.ts +46 -11
  132. package/.bkit/core/engine/shared/package-manager.ts +7 -3
  133. package/.bkit/core/engine/shared/settings.ts +12 -1
  134. package/.bkit/core/engine/shared/text.ts +14 -0
  135. package/.bkit/core/engine/tools/instructions-sources.ts +1 -0
  136. package/.bkit/core/engine/tools/instructions.ts +116 -20
  137. package/.bkit/core/hooks/antigravity-hook.js +20 -4
  138. package/.bkit/core/hooks/gateguard-edit-payload.js +8 -5
  139. package/.bkit/core/hooks/gateguard-engine.js +249 -23
  140. package/.bkit/core/hooks/guardrails-deny.js +167 -0
  141. package/.bkit/core/hooks/guardrails-read.js +3 -3
  142. package/.bkit/core/hooks/guardrails-shell.js +1122 -167
  143. package/.bkit/core/hooks/guardrails-tiers.js +247 -176
  144. package/.bkit/core/hooks/preflight-tracker.sh +219 -0
  145. package/.bkit/core/prompts/bkit-audit-generate.md +23 -6
  146. package/.bkit/core/prompts/bkit-build-challenge-1.md +5 -4
  147. package/.bkit/core/prompts/bkit-build-challenge-2.md +6 -5
  148. package/.bkit/core/prompts/bkit-build-install-skills.md +2 -2
  149. package/.bkit/core/prompts/bkit-build-plan-convert.md +21 -7
  150. package/.bkit/core/prompts/bkit-build-plan-current.md +5 -4
  151. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +22 -17
  152. package/.bkit/core/prompts/bkit-build-plan-tasks.md +16 -12
  153. package/.bkit/core/prompts/bkit-build-plan-tests.md +14 -10
  154. package/.bkit/core/prompts/bkit-build-plan-verify.md +21 -8
  155. package/.bkit/core/prompts/bkit-debug-abort-handover.md +10 -5
  156. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +22 -6
  157. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +19 -3
  158. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +22 -6
  159. package/.bkit/core/prompts/bkit-debug-failure-soak.md +10 -7
  160. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +3 -3
  161. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +4 -4
  162. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +3 -3
  163. package/.bkit/core/prompts/bkit-design-generate.md +6 -4
  164. package/.bkit/core/prompts/bkit-design-organise.md +4 -3
  165. package/.bkit/core/prompts/bkit-design-review-1.md +5 -4
  166. package/.bkit/core/prompts/bkit-design-review-2.md +6 -5
  167. package/.bkit/core/prompts/bkit-design-spike.md +4 -3
  168. package/.bkit/core/prompts/bkit-design-update.md +6 -4
  169. package/.bkit/core/prompts/bkit-plan-generate.md +35 -14
  170. package/.bkit/core/prompts/bkit-plan-review-1.md +9 -7
  171. package/.bkit/core/prompts/bkit-plan-review-2.md +9 -7
  172. package/.bkit/core/prompts/bkit-plan-scope-check.md +8 -6
  173. package/.bkit/core/prompts/bkit-plan-update.md +22 -8
  174. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +11 -8
  175. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +9 -5
  176. package/.bkit/core/prompts/bkit-ship-update-docs.md +26 -4
  177. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +3 -3
  178. package/.bkit/core/prompts/bkit-utility-update-decisions.md +10 -7
  179. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +8 -5
  180. package/.bkit/core/prompts/bkit-utility-update-documentation.md +31 -7
  181. package/.bkit/core/prompts/bkit-utility-update-failures.md +8 -5
  182. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +10 -7
  183. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +4 -4
  184. package/.bkit/core/prompts/bkit-utility-update-tracker.md +4 -4
  185. package/.bkit/core/workflows/bkit-auto.md +23 -11
  186. package/.bkit/core/workflows/bkit-build.md +331 -100
  187. package/.bkit/core/workflows/bkit-debug.md +135 -64
  188. package/.bkit/core/workflows/bkit-design.md +58 -32
  189. package/.bkit/core/workflows/bkit-plan.md +73 -45
  190. package/.bkit/core/workflows/bkit-ship.md +233 -167
  191. package/.bkit/shared/.agents/plugins/bkit/hooks.json +1 -1
  192. package/.bkit/shared/.bkit/.env.example +5 -0
  193. package/.bkit/shared/.claude/bkit-cloud.md +7 -7
  194. package/.bkit/shared/.claude/settings.json +5 -1
  195. package/.bkit/shared/.cursor/bkit-cloud.md +1 -1
  196. package/.bkit/shared/.cursor/hooks.json +1 -1
  197. package/.bkit/shared/.opencode/opencode.json +11 -2
  198. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +27 -0
  199. package/.bkit/templates/.cursor/Dockerfile +7 -7
  200. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +1 -1
  201. package/.bkit/templates/.github/dependabot.yml +5 -0
  202. package/.bkit/templates/.github/renovate.json5 +5 -3
  203. package/.bkit/templates/.github/workflows/bkit-ci.yml +11 -11
  204. package/.bkit/templates/.github/workflows/bkit-cloud.yml +525 -161
  205. package/.bkit/templates/.github/workflows/bkit-renovate.yml +2 -2
  206. package/.bkit/templates/.husky/pre-push +123 -6
  207. package/.bkit/templates/context/bkit-serena.md +1 -1
  208. package/.bkit/templates/context/bkit-vercel.md +103 -59
  209. package/.bkit/templates/docs/architecture.md +98 -0
  210. package/.bkit/templates/docs/capabilities.md +33 -37
  211. package/.bkit/templates/docs/components.md +142 -0
  212. package/.bkit/templates/docs/data-schema.md +87 -0
  213. package/.bkit/{shared → templates}/docs/deployments.md +128 -142
  214. package/.bkit/templates/docs/design.md +117 -0
  215. package/.bkit/templates/docs/noise.md +54 -0
  216. package/.bkit/templates/docs/observability.md +99 -0
  217. package/.bkit/templates/docs/security.md +137 -0
  218. package/.bkit/templates/docs/setup.md +93 -0
  219. package/.bkit/templates/docs/technology.md +70 -0
  220. package/.bkit/{shared → templates}/docs/testing.md +200 -87
  221. package/.bkit/templates/scripts/ci/bkit-check-accepted-divergences.mjs +1 -6
  222. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +511 -103
  223. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +314 -28
  224. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +500 -1
  225. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  226. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +91 -62
  227. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +59 -11
  228. package/.bkit/templates/slop-scan.config.json +2 -0
  229. package/CHANGELOG.md +79 -0
  230. package/DETAILS.md +661 -0
  231. package/README.md +73 -604
  232. package/dist/checks/after/auth.js +114 -46
  233. package/dist/checks/after/github.js +138 -35
  234. package/dist/checks/after/index.js +16 -4
  235. package/dist/checks/after/tools.js +224 -1
  236. package/dist/checks/before/files.js +59 -1
  237. package/dist/checks/before/index.js +7 -1
  238. package/dist/checks/status-holes.js +20 -21
  239. package/dist/checks/tips/catalogue.js +99 -10
  240. package/dist/checks/tips/detect.js +35 -3
  241. package/dist/checks/tips/index.js +1 -1
  242. package/dist/cli.js +13 -13
  243. package/dist/commands/ci/ci.js +113 -20
  244. package/dist/commands/ci/push-gate.js +79 -44
  245. package/dist/commands/install/doctor.js +5 -5
  246. package/dist/commands/install/install.js +23 -22
  247. package/dist/commands/install/uninstall.js +36 -30
  248. package/dist/commands/install/upgrade.js +10 -2
  249. package/dist/commands/land.js +2 -3
  250. package/dist/commands/lib.js +323 -25
  251. package/dist/commands/workflow/branches.js +312 -72
  252. package/dist/commands/workflow/challenge.js +66 -13
  253. package/dist/commands/workflow/context.js +46 -10
  254. package/dist/commands/workflow/counters.js +231 -23
  255. package/dist/commands/workflow/decisions.js +221 -106
  256. package/dist/commands/workflow/disk.js +2 -1
  257. package/dist/commands/workflow/feature-base.js +60 -0
  258. package/dist/commands/workflow/issues.js +243 -15
  259. package/dist/commands/workflow/junit.js +137 -0
  260. package/dist/commands/workflow/ledgers.js +726 -112
  261. package/dist/commands/workflow/locks.js +150 -29
  262. package/dist/commands/workflow/loops.js +67 -0
  263. package/dist/commands/workflow/open-decision.js +199 -0
  264. package/dist/commands/workflow/plan-blocks.js +6 -0
  265. package/dist/commands/workflow/plans.js +1 -1
  266. package/dist/commands/workflow/prs.js +272 -16
  267. package/dist/commands/workflow/repo.js +1 -1
  268. package/dist/commands/workflow/run-facts.js +6 -0
  269. package/dist/commands/workflow/runs.js +747 -155
  270. package/dist/commands/workflow/runtime.js +8 -4
  271. package/dist/commands/workflow/status.js +259 -13
  272. package/dist/commands/workflow/step-table.js +41 -15
  273. package/dist/commands/workflow/steps.js +530 -26
  274. package/dist/commands/workflow/summary-findings.js +1 -1
  275. package/dist/commands/workflow/summary.js +289 -8
  276. package/dist/commands/workflow/tasks.js +294 -27
  277. package/dist/commands/workflow/tests-base.js +266 -0
  278. package/dist/commands/workflow/tests-changed.js +130 -56
  279. package/dist/commands/workflow/tests-jump.js +77 -0
  280. package/dist/commands/workflow/tests.js +608 -131
  281. package/dist/commands/workflow/tracker.js +920 -112
  282. package/dist/commands/workflow/workflows.js +80 -59
  283. package/dist/commands/workflow/worktrees.js +387 -58
  284. package/dist/install/cloud-env.js +32 -10
  285. package/dist/install/managed-block.js +101 -0
  286. package/dist/install/manifest.js +7 -1
  287. package/dist/install/modules/claude.js +6 -2
  288. package/dist/install/modules/cloud.js +73 -86
  289. package/dist/install/modules/codex.js +9 -2
  290. package/dist/install/modules/core.js +190 -27
  291. package/dist/install/modules/opencode.js +18 -23
  292. package/dist/install/network-allowlist.js +8 -3
  293. package/dist/install/project-docs.js +551 -0
  294. package/dist/install/template-copies.js +55 -5
  295. package/dist/install/write.js +117 -5
  296. package/dist/ledgers/journal.js +10 -8
  297. package/dist/ledgers/migrate.js +20 -9
  298. package/dist/ledgers/status.js +461 -8
  299. package/dist/ledgers/telemetry.js +71 -13
  300. package/dist/render/trackers.js +21 -12
  301. package/dist/shared/package-manager.js +7 -2
  302. package/dist/shared/settings.js +8 -0
  303. package/dist/shared/text.js +13 -0
  304. package/dist/tools/instructions-sources.js +1 -0
  305. package/dist/tools/instructions.js +97 -24
  306. package/package.json +23 -15
  307. package/.bkit/core/hooks/preflight-linear.sh +0 -73
  308. package/.bkit/shared/docs/architecture.md +0 -16
  309. package/.bkit/shared/docs/data-schema.md +0 -16
  310. package/.bkit/shared/docs/design.md +0 -38
  311. package/.bkit/shared/docs/noise.md +0 -20
  312. package/.bkit/shared/docs/observability.md +0 -22
  313. package/.bkit/shared/docs/security.md +0 -62
  314. package/.bkit/shared/docs/setup.md +0 -52
  315. package/.bkit/shared/docs/technology.md +0 -15
  316. /package/.bkit/templates/{.lintstagedrc.json → lintstagedrc.example.json} +0 -0
  317. /package/.bkit/templates/{.prettierignore → prettierignore.example} +0 -0
@@ -12,13 +12,20 @@
12
12
  // use local `dev` when it is a fast-forward of `origin/dev`: dev pushes wait for
13
13
  // a human, so local dev is routinely ahead, and a worktree without those commits
14
14
  // builds against superseded work.
15
+ // Debug preserves the adopted branch's history for CI evidence ancestry checks.
15
16
 
16
17
  import { spawnSync } from "node:child_process";
17
18
  import { createHash } from "node:crypto";
18
19
  import * as fs from "node:fs";
19
20
  import * as path from "node:path";
20
21
 
21
- import { actionHash, actionKey, lastRun, recordAction } from "../../ledgers/status.js";
22
+ import {
23
+ actionHash,
24
+ actionKey,
25
+ lastRun,
26
+ recordAction,
27
+ withTargetLock,
28
+ } from "../../ledgers/status.js";
22
29
  import { APPEND_LEDGERS, gitEnv } from "../../ledgers/telemetry.js";
23
30
  import { parseJson } from "../../shared/json.js";
24
31
  import { readBkitConfig } from "../../shared/settings.js";
@@ -38,12 +45,19 @@ import {
38
45
  } from "../lib.js";
39
46
  import { ensureDiskSpace } from "./disk.js";
40
47
  import {
48
+ RUN_COMMITS_ROW,
41
49
  listRecords,
42
50
  newRecord,
51
+ readParkedCommits,
43
52
  readRecord,
53
+ readRunCommits,
54
+ removeParkedCommits,
44
55
  removeRecord,
56
+ runCommitsIn,
45
57
  withSetupGuard,
46
58
  writeRecord,
59
+ type RunCommits,
60
+ type SharedCheckoutRecord,
47
61
  } from "./ledgers.js";
48
62
  import { workflowLockFresh, workflowLockLive } from "./locks.js";
49
63
  import { detect } from "./runtime.js";
@@ -76,7 +90,7 @@ function fidOf(value: unknown): string {
76
90
 
77
91
  export const worktreeDir = (root: string, fid: string) => path.join(root, ".worktrees", fid);
78
92
 
79
- /** `.worktree-owned` in the git common dir's outbox: shared by every worktree, survives removal. */
93
+ /** `.worktree-owned` is shared across worktrees; session invocation state stays separate. */
80
94
  export function ownershipMarker(root: string, fid: string): string {
81
95
  const common = git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
82
96
  if (!common) throw new CommandError(EXIT.USAGE, `not inside a git repository: ${root}`);
@@ -127,11 +141,72 @@ function fetchBranch(cwd: string, branch: string): void {
127
141
  }
128
142
  }
129
143
 
144
+ /**
145
+ * `fresh` with the start, commits and pushed list of a `run-commits` row laid over it:
146
+ * the record a Stop removed. A commit that is not an ancestor of HEAD is dropped, and a
147
+ * row start that is not a commit leaves the fresh one.
148
+ */
149
+ function rebuildFromRow(
150
+ root: string,
151
+ fresh: SharedCheckoutRecord,
152
+ row: RunCommits | null,
153
+ ): SharedCheckoutRecord {
154
+ if (row === null) return fresh;
155
+ const onBranch = (sha: string) => runGit(root, ["merge-base", "--is-ancestor", sha, "HEAD"]).ok;
156
+ const isCommit = (sha: string) =>
157
+ runGit(root, ["rev-parse", "-q", "--verify", `${sha}^{commit}`]).ok;
158
+ const commits = row.commits.filter(onBranch);
159
+ return {
160
+ ...fresh,
161
+ startSha: row.startSha !== "" && isCommit(row.startSha) ? row.startSha : fresh.startSha,
162
+ commits,
163
+ pushed: row.pushed.filter((sha) => commits.includes(sha)),
164
+ };
165
+ }
166
+
167
+ /** The status rows that open or close a run. */
168
+ const RUN_BOUNDARY: ReadonlySet<string> = new Set([
169
+ "workflow-started",
170
+ "workflow-done",
171
+ "workflow-failed",
172
+ ]);
173
+
174
+ /**
175
+ * The newest `run-commits` row of `workflow` in the copy of the status log on
176
+ * `origin/dev`. A landed handover takes the row's line back out of the checkout, so the
177
+ * landed copy is the one that holds it. That copy holds only the lines landings carried,
178
+ * so the run counts as open when no row that opens or closes a run follows the row.
179
+ * Null when the copy is missing or cannot be read, or the row is absent or followed by
180
+ * such a row. A failed fetch reads the copy this clone last saw.
181
+ */
182
+ function landedRunCommits(root: string, statusFile: string, workflow: string): RunCommits | null {
183
+ runGit(root, ["fetch", "-q", "origin", `+refs/heads/${DEV}:refs/remotes/origin/${DEV}`]);
184
+ const rel = path.relative(root, statusFile).split(path.sep).join("/");
185
+ const landed = runGit(root, ["show", `refs/remotes/origin/${DEV}:${rel}`]);
186
+ if (!landed.ok) return null;
187
+ const types = landed.stdout.split("\n").flatMap((line) => {
188
+ const parsed = parseJson(line);
189
+ const row = parsed.ok ? (parsed.value as Record<string, unknown> | null) : null;
190
+ return row !== null && typeof row === "object" && row["workflow"] === workflow
191
+ ? [String(row["type"])]
192
+ : [];
193
+ });
194
+ const at = types.lastIndexOf(RUN_COMMITS_ROW);
195
+ if (at < 0 || types.slice(at + 1).some((type) => RUN_BOUNDARY.has(type))) return null;
196
+ return runCommitsIn(landed.stdout, workflow);
197
+ }
198
+
130
199
  /**
131
200
  * The shared-checkout record for an in-place run on `dev`. Another feature's
132
201
  * record with a live workflow lock means that run owns the checkout; one
133
202
  * without is left over and removed. The same feature with an open run in
134
- * `{logDir}/status.jsonl` is a resume and keeps its record; a new run rewrites it.
203
+ * `{logDir}/status.jsonl` is a resume and keeps its record. A run with no record
204
+ * takes the start, commits and pushed list of the first of these that has one:
205
+ * the parked copy in this clone's git dir, unless the checkout's log shows the
206
+ * run closed (then it is stale and removed); the `run-commits` row in
207
+ * `{logDir}/status.jsonl` of an open run; the row on `origin/dev` while that log
208
+ * shows no closed run after it, which is the only one that fetches. The parked
209
+ * copy is removed once the record is written.
135
210
  */
136
211
  function openSharedRecord(root: string, fid: string, workflow: string, logDir: string) {
137
212
  const busy = (other: string) =>
@@ -150,13 +225,24 @@ function openSharedRecord(root: string, fid: string, workflow: string, logDir: s
150
225
  }
151
226
  const existing = readRecord(root, fid);
152
227
  const statusFile = path.join(logDir, "status.jsonl");
153
- const open =
154
- fs.existsSync(statusFile) &&
155
- lastRun(readRuns(statusFile), workflow)?.status === "IN_PROGRESS";
156
- if (existing !== null && existing.branch === DEV && open) return existing;
228
+ const last = fs.existsSync(statusFile) ? lastRun(readRuns(statusFile), workflow) : undefined;
229
+ const open = last?.status === "IN_PROGRESS";
230
+ if (existing !== null && existing.branch === DEV && open) {
231
+ removeParkedCommits(root, fid);
232
+ return existing;
233
+ }
157
234
  const fresh = newRecord(root, fid, DEV);
158
- writeRecord(root, fresh);
159
- return fresh;
235
+ // A closed run in the checkout's log ended the run every copy of the row belongs to.
236
+ const closed = last !== undefined && !open;
237
+ const parked = closed ? null : readParkedCommits(root, fid, workflow);
238
+ const row =
239
+ parked ??
240
+ (open ? readRunCommits(statusFile, workflow) : null) ??
241
+ (closed ? null : landedRunCommits(root, statusFile, workflow));
242
+ const rebuilt = rebuildFromRow(root, fresh, row);
243
+ writeRecord(root, rebuilt);
244
+ removeParkedCommits(root, fid);
245
+ return rebuilt;
160
246
  });
161
247
  if (guarded === null) throw busy("another run");
162
248
  return guarded.value;
@@ -228,15 +314,42 @@ export function worktreeBase(cwd: string, workflow: string, log?: (m: string) =>
228
314
  * may bring docs and ledgers only, so such a branch can never land.
229
315
  */
230
316
  function inheritedDevCommits(root: string, branch: string): string[] {
317
+ if (!hasLocal(root, DEV)) return [];
318
+ const read = (args: string[]) => {
319
+ const result = runGit(root, args);
320
+ if (!result.ok)
321
+ throw new CommandError(
322
+ EXIT_REFUSED,
323
+ `cannot inspect unpublished ${DEV} work for ${branch}: ${result.stderr}`,
324
+ );
325
+ return result.stdout.trim();
326
+ };
231
327
  const unpushed = new Set(
232
- (git(root, ["rev-list", `${ORIGIN_DEV}..${DEV}`]) ?? "").split("\n").filter(Boolean),
328
+ read(["rev-list", `${ORIGIN_DEV}..${DEV}`])
329
+ .split("\n")
330
+ .filter(Boolean),
233
331
  );
234
332
  if (unpushed.size === 0) return [];
235
- return (git(root, ["rev-list", branch, "--not", ORIGIN_DEV]) ?? "")
333
+ return read(["rev-list", branch, "--not", ORIGIN_DEV])
236
334
  .split("\n")
237
335
  .filter((c) => unpushed.has(c));
238
336
  }
239
337
 
338
+ /** Refuse a publication candidate that imports unpublished local dev ancestry. */
339
+ export function assertShipEligible(root: string, candidate: string): void {
340
+ if (git(root, ["rev-parse", "--verify", "--quiet", `${candidate}^{commit}`]) === null)
341
+ throw new CommandError(EXIT_REFUSED, `cannot inspect ship candidate ${candidate}`);
342
+ const inherited = inheritedDevCommits(root, candidate);
343
+ if (inherited.length === 0) return;
344
+ const commits = inherited
345
+ .map((sha) => git(root, ["show", "-s", "--format=%h %s", sha]) ?? sha)
346
+ .join("; ");
347
+ throw new CommandError(
348
+ EXIT_REFUSED,
349
+ `${candidate} carries unpublished ${DEV} work: ${commits}. Publish ${DEV} separately (git push origin ${DEV}), then re-run ship; these commits must not be squashed into the feature.`,
350
+ );
351
+ }
352
+
240
353
  /** Why a docs-only branch carrying unpushed `dev` cannot land, and what unblocks it. */
241
354
  function inheritedDevRefusal(
242
355
  root: string,
@@ -310,6 +423,16 @@ function rebaseInProgress(wt: string): boolean {
310
423
  });
311
424
  }
312
425
 
426
+ /**
427
+ * Where setup holds its "rebase stopped" note while it leaves a rebase in progress:
428
+ * inside the worktree's git dir, never in the tree. `--continue` refuses while a
429
+ * tracked file has unstaged changes, and the run's rebase log is tracked once a run
430
+ * committed it. `branches rebase` writes the note ahead of its own log lines.
431
+ */
432
+ export function rebaseNoteFile(wt: string): string | null {
433
+ return git(wt, ["rev-parse", "--path-format=absolute", "--git-path", "bkit-rebase-note.md"]);
434
+ }
435
+
313
436
  /**
314
437
  * bkit's own worktree copy entry, excluded from every bkit commit beside
315
438
  * `bkit.workflows.worktree.copy`: it holds the sign-in tokens, and a consumer whose
@@ -437,8 +560,10 @@ function putJournalRowsBack(wt: string, journal: Map<string, Appended>): string
437
560
  }
438
561
  for (const [rel, a] of journal) {
439
562
  const file = path.join(wt, rel);
440
- const text = fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : "";
441
- fs.appendFileSync(file, `${text !== "" && !text.endsWith("\n") ? "\n" : ""}${a.rows}`);
563
+ withTargetLock(file, () => {
564
+ const text = fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : "";
565
+ fs.appendFileSync(file, `${text !== "" && !text.endsWith("\n") ? "\n" : ""}${a.rows}`);
566
+ });
442
567
  }
443
568
  return "";
444
569
  }
@@ -505,11 +630,13 @@ function carryLeftovers(
505
630
  // ---------------------------------------------------------------------------
506
631
 
507
632
  /** Copy each `worktreeCopy` entry from the main checkout; a missing one is narrated, never fatal. */
508
- function copyListed(root: string, wt: string, entries: string[], log: (m: string) => void) {
633
+ export function copyListed(root: string, wt: string, entries: string[], log: (m: string) => void) {
509
634
  const copied: string[] = [];
510
635
  const copyMissing: string[] = [];
511
636
  for (const entry of entries) {
512
637
  const rel = path.normalize(entry);
638
+ // bkit's own env is managed by linkBkitEnv, including on resume.
639
+ if (BKIT_OWN_COPY.some((owned) => path.normalize(owned) === rel)) continue;
513
640
  if (!insideCheckout(rel)) {
514
641
  log(`worktree copy: ${entry} is outside the main checkout — skipped`);
515
642
  continue;
@@ -599,7 +726,8 @@ function linkBkitEnv(
599
726
  * `direnv allow` the worktree's `.envrc` when it matches the main checkout's
600
727
  * byte for byte, so the worktree inherits the trust given there and nothing
601
728
  * more; a differing file is left for a human to read. No `.envrc`, direnv
602
- * missing or failing → false, narrated, never fatal.
729
+ * missing or failing → false, narrated (a differing or failed one says the push will
730
+ * block, since the pre-push hook refuses an untrusted `.envrc`), never fatal.
603
731
  */
604
732
  function allowDirenv(root: string, wt: string, log: (m: string) => void): boolean {
605
733
  const envrc = path.join(wt, ".envrc");
@@ -607,7 +735,7 @@ function allowDirenv(root: string, wt: string, log: (m: string) => void): boolea
607
735
  const main = path.join(root, ".envrc");
608
736
  if (!fs.existsSync(main) || !fs.readFileSync(main).equals(fs.readFileSync(envrc))) {
609
737
  log(
610
- `direnv: ${envrc} differs from the main checkout's — not allowed; read it, then run direnv allow`,
738
+ `direnv: ${envrc} differs from the main checkout's — not allowed, so the pre-push hook will block the first push (the push will block until you read it and run direnv allow .)`,
611
739
  );
612
740
  return false;
613
741
  }
@@ -617,15 +745,21 @@ function allowDirenv(root: string, wt: string, log: (m: string) => void): boolea
617
745
  return false;
618
746
  }
619
747
  if (res.status !== 0) {
620
- log(`direnv allow failed (exit ${res.status}): ${(res.stderr ?? "").trim()}`);
748
+ log(
749
+ `direnv allow failed (exit ${res.status}): ${(res.stderr ?? "").trim()} — the push will block until you run direnv allow . in the worktree`,
750
+ );
621
751
  return false;
622
752
  }
623
753
  return true;
624
754
  }
625
755
 
626
756
  /** Run the frozen install in `wt`; the exit status, with a spawn failure read as "could not run". */
627
- function install(wt: string, log: (m: string) => void): number {
628
- const [cmd, ...args] = installCommand({ frozen: true });
757
+ export function install(
758
+ wt: string,
759
+ log: (m: string) => void,
760
+ opts: { preferOffline?: boolean } = {},
761
+ ): number {
762
+ const [cmd, ...args] = installCommand({ frozen: true, preferOffline: opts.preferOffline });
629
763
  const res = spawnSync(cmd!, args, { cwd: wt, encoding: "utf-8", maxBuffer: 1 << 26 });
630
764
  const status = res.error ? 127 : (res.status ?? 1);
631
765
  if (status !== 0) {
@@ -639,9 +773,143 @@ function install(wt: string, log: (m: string) => void): number {
639
773
  // Branch cleanup
640
774
  // ---------------------------------------------------------------------------
641
775
 
776
+ /** Preserve NUL-delimited paths and the status columns that runGit trims. */
777
+ function cleanupRead(root: string, args: string[]): ReturnType<typeof runGit> {
778
+ const result = spawnSync("git", args, {
779
+ cwd: root,
780
+ encoding: "utf-8",
781
+ env: gitEnv(),
782
+ maxBuffer: 1 << 26,
783
+ });
784
+ return {
785
+ ok: !result.error && result.status === 0,
786
+ stdout: result.stdout ?? "",
787
+ stderr: result.error?.message ?? result.stderr ?? "",
788
+ };
789
+ }
790
+
791
+ function treeEntry(root: string, rev: string, file: string): string | null {
792
+ const result = cleanupRead(root, ["ls-tree", "-z", rev, "--", file]);
793
+ if (!result.ok) throw new Error(`cannot inspect ${rev}:${file}: ${result.stderr}`);
794
+ return result.stdout === "" ? null : result.stdout.slice(0, result.stdout.indexOf("\t"));
795
+ }
796
+
797
+ function committedLines(root: string, rev: string, file: string): string[] {
798
+ if (treeEntry(root, rev, file) === null) return [];
799
+ const result = cleanupRead(root, ["show", `${rev}:${file}`]);
800
+ if (!result.ok) throw new Error(`cannot read ${rev}:${file}: ${result.stderr}`);
801
+ return result.stdout.split("\n").filter(Boolean);
802
+ }
803
+
804
+ /** Branch changes absent from dev, including deletions and tree-entry mode/type. */
805
+ export function notOnDev(root: string, branch: string): string[] {
806
+ const base = git(root, ["merge-base", ORIGIN_DEV, branch]);
807
+ if (base === null) return [`${branch}: no common history with ${ORIGIN_DEV}`];
808
+ const changed = cleanupRead(root, ["diff", "--name-only", "-z", "--no-renames", base, branch]);
809
+ if (!changed.ok) return [`cannot inspect ${branch}: ${changed.stderr}`];
810
+ try {
811
+ return changed.stdout
812
+ .split("\0")
813
+ .filter((file) => file !== "" && file !== "docs/roadmap.md")
814
+ .filter((file) => {
815
+ const feature = treeEntry(root, branch, file);
816
+ const dev = treeEntry(root, ORIGIN_DEV, file);
817
+ if (feature === dev) return false;
818
+ if (
819
+ feature === null ||
820
+ dev === null ||
821
+ !file.endsWith(".jsonl") ||
822
+ !/^100(?:644|755) blob /.test(feature) ||
823
+ feature.split(" ").slice(0, 2).join(" ") !== dev.split(" ").slice(0, 2).join(" ")
824
+ )
825
+ return true;
826
+ const before = new Set(committedLines(root, base, file));
827
+ const onDev = new Set(committedLines(root, ORIGIN_DEV, file));
828
+ return committedLines(root, branch, file).some(
829
+ (line) => !before.has(line) && !onDev.has(line),
830
+ );
831
+ });
832
+ } catch (error) {
833
+ return [(error as Error).message];
834
+ }
835
+ }
836
+
837
+ /** Uncommitted files whose index or working contents are not already safely on dev. */
838
+ function dirtyWork(root: string, wt: string, landed: boolean): string[] {
839
+ const status = cleanupRead(wt, [
840
+ "status",
841
+ "--porcelain=v1",
842
+ "-z",
843
+ "--untracked-files=all",
844
+ "--",
845
+ ".",
846
+ ...copyExcludes(wt),
847
+ ]);
848
+ if (!status.ok) return [`cannot inspect dirty work: ${status.stderr}`];
849
+ const entries = status.stdout.split("\0").filter(Boolean);
850
+ const paths: string[] = [];
851
+ const staged = new Set<string>();
852
+ for (let i = 0; i < entries.length; i++) {
853
+ const row = entries[i]!;
854
+ const changed = [row.slice(3)];
855
+ if (/[RC]/.test(row.slice(0, 2))) changed.push(entries[++i]!);
856
+ paths.push(...changed);
857
+ if (row[0] !== " " && row[0] !== "?") {
858
+ for (const file of changed) staged.add(file);
859
+ }
860
+ }
861
+ if (!landed) return paths;
862
+ return paths.filter((file) => {
863
+ try {
864
+ if (
865
+ staged.has(file) &&
866
+ !cleanupRead(wt, ["diff", "--cached", "--quiet", ORIGIN_DEV, "--", file]).ok
867
+ )
868
+ return true;
869
+ const entry = treeEntry(root, ORIGIN_DEV, file);
870
+ const full = path.join(wt, file);
871
+ const stat = fs.lstatSync(full, { throwIfNoEntry: false });
872
+ if (stat === undefined) return entry !== null;
873
+ if (entry === null || (!stat.isFile() && !stat.isSymbolicLink())) return true;
874
+ const mode = stat.isSymbolicLink()
875
+ ? "120000"
876
+ : (stat.mode & 0o111) !== 0
877
+ ? "100755"
878
+ : "100644";
879
+ if (!entry.startsWith(`${mode} blob `)) return true;
880
+ const bytes = stat.isSymbolicLink()
881
+ ? Buffer.from(fs.readlinkSync(full))
882
+ : fs.readFileSync(full);
883
+ const hash = spawnSync("git", ["hash-object", "--stdin"], {
884
+ cwd: root,
885
+ input: bytes,
886
+ encoding: "utf-8",
887
+ env: gitEnv(),
888
+ });
889
+ if (hash.status !== 0) return true;
890
+ if (entry.endsWith(` ${hash.stdout.trim()}`)) return false;
891
+ if (!file.endsWith(".jsonl")) return true;
892
+ const onDev = new Set(committedLines(root, ORIGIN_DEV, file));
893
+ return bytes
894
+ .toString("utf-8")
895
+ .split("\n")
896
+ .filter(Boolean)
897
+ .some((line) => !onDev.has(line));
898
+ } catch {
899
+ return true;
900
+ }
901
+ });
902
+ }
903
+
642
904
  /** The worktree (main checkout included) with `branch` checked out, else null. */
643
905
  export function worktreeHolding(root: string, branch: string): string | null {
644
- const list = git(root, ["worktree", "list", "--porcelain"]) ?? "";
906
+ const result = cleanupRead(root, ["worktree", "list", "--porcelain"]);
907
+ if (!result.ok)
908
+ throw new CommandError(
909
+ EXIT_REMOVE,
910
+ `cannot inspect worktrees holding ${branch}: ${result.stderr}`,
911
+ );
912
+ const list = result.stdout;
645
913
  let current: string | null = null;
646
914
  for (const line of list.split("\n")) {
647
915
  if (line.startsWith("worktree ")) current = line.slice("worktree ".length);
@@ -651,14 +919,16 @@ export function worktreeHolding(root: string, branch: string): string | null {
651
919
  }
652
920
 
653
921
  /**
654
- * Delete `branch` locally and on origin. A worktree still holding it blocks
655
- * both deletes: the local one would fail, and the remote one would strand that
656
- * worktree's branch without its upstream.
922
+ * Delete the proved local tip atomically, then the proved remote tip. A worktree
923
+ * still holding the branch blocks both. The remote delete carries a lease on its
924
+ * proved tip, so origin refuses it when someone pushed after the proof.
657
925
  */
658
926
  function deleteBranch(
659
927
  root: string,
660
928
  branch: string,
661
929
  log: (m: string) => void,
930
+ expected: string,
931
+ remoteExpected: string | null,
662
932
  ): { branchDeleted: boolean; remoteDeleted: boolean; branchBlockedBy: string | null } {
663
933
  const holder = worktreeHolding(root, branch);
664
934
  if (holder !== null) {
@@ -667,17 +937,24 @@ function deleteBranch(
667
937
  );
668
938
  return { branchDeleted: false, remoteDeleted: false, branchBlockedBy: holder };
669
939
  }
670
- if (hasLocal(root, branch)) {
671
- const del = runGit(root, ["branch", "-D", branch]);
672
- if (!del.ok) log(`git branch -D ${branch} failed: ${del.stderr}`);
940
+ const del = runGit(root, ["update-ref", "-d", `refs/heads/${branch}`, expected]);
941
+ if (!del.ok) log(`local ${branch} changed after its cleanup proof — preserved: ${del.stderr}`);
942
+ let remoteDeleted = false;
943
+ if (del.ok && remoteExpected !== null) {
944
+ const ref = `refs/heads/${branch}`;
945
+ const remote = runGit(root, [
946
+ "push",
947
+ `--force-with-lease=${ref}:${remoteExpected}`,
948
+ "origin",
949
+ `:${ref}`,
950
+ ]);
951
+ remoteDeleted = remote.ok;
952
+ if (!remote.ok) log(`remote origin/${branch} not deleted — preserved: ${remote.stderr}`);
673
953
  }
674
- const remote = runGit(root, ["push", "origin", "--delete", branch]);
675
- if (!remote.ok) log(`git push origin --delete ${branch} failed or it was already gone`);
676
- runGit(root, ["fetch", "--prune", "origin"]);
677
954
  return {
678
- branchDeleted: !hasLocal(root, branch),
679
- remoteDeleted: remote.ok,
680
- branchBlockedBy: null,
955
+ branchDeleted: del.ok,
956
+ remoteDeleted,
957
+ branchBlockedBy: del.ok ? null : "changed-after-proof",
681
958
  };
682
959
  }
683
960
 
@@ -693,14 +970,16 @@ export interface RemoveResult {
693
970
 
694
971
  /**
695
972
  * Remove `.worktrees/{fid}` when a workflow created it (the ownership marker),
696
- * prune stale entries, then delete `branch` locally and on origin unless another
697
- * worktree holds it. Throws EXIT_REMOVE when `git worktree remove` fails.
973
+ * preserve unlanded or dirty work, then delete the proved local and remote branch
974
+ * tips unless another worktree holds the branch. Throws EXIT_REMOVE
975
+ * when `git worktree remove` fails.
698
976
  */
699
977
  export function removeWorktree(
700
978
  cwd: string,
701
979
  fid: string,
702
980
  branch: string | undefined,
703
981
  log: (m: string) => void,
982
+ options: { landed?: boolean } = {},
704
983
  ): RemoveResult {
705
984
  if (branch !== undefined && isSharedBranch(branch)) {
706
985
  throw new CommandError(EXIT.USAGE, `refusing to delete branch ${branch}`);
@@ -708,33 +987,94 @@ export function removeWorktree(
708
987
  const root = repoRoot(cwd);
709
988
  const wt = worktreeDir(root, fid);
710
989
  const marker = ownershipMarker(root, fid);
711
- const result = (removed: boolean, reason: string | null): RemoveResult => {
712
- const cleanup = branch === undefined ? null : deleteBranch(root, branch, log);
990
+ let expected: string | null = null;
991
+ let remoteExpected: string | null = null;
992
+ const result = (removed: boolean, reason: string | null, removeBranch = false): RemoveResult => {
993
+ const cleanup =
994
+ branch === undefined || !removeBranch || expected === null
995
+ ? null
996
+ : deleteBranch(root, branch, log, expected, remoteExpected);
713
997
  return {
714
998
  removed,
715
999
  reason,
716
1000
  worktreePath: wt,
717
1001
  repoRoot: root,
718
- branchDeleted: cleanup?.branchDeleted ?? null,
719
- remoteDeleted: cleanup?.remoteDeleted ?? null,
720
- branchBlockedBy: cleanup?.branchBlockedBy ?? null,
1002
+ branchDeleted: cleanup?.branchDeleted ?? (branch === undefined ? null : false),
1003
+ remoteDeleted: cleanup?.remoteDeleted ?? (branch === undefined ? null : false),
1004
+ branchBlockedBy:
1005
+ cleanup?.branchBlockedBy ?? (branch === undefined ? null : worktreeHolding(root, branch)),
721
1006
  };
722
1007
  };
723
- if (!fs.existsSync(wt)) {
724
- runGit(root, ["worktree", "prune"]);
725
- return result(false, "absent");
726
- }
727
- if (!fs.existsSync(marker)) {
1008
+ if (fs.existsSync(wt) && !fs.existsSync(marker)) {
728
1009
  log(`${wt} exists but has no ownership marker (${marker}) — not ours, left in place`);
1010
+ if (branch !== undefined)
1011
+ log(
1012
+ `${branch} is checked out in ${worktreeHolding(root, branch) ?? wt} — local and remote branch left in place`,
1013
+ );
729
1014
  return result(false, "not-owned");
730
1015
  }
1016
+ if (branch !== undefined) {
1017
+ const holder = worktreeHolding(root, branch);
1018
+ if (holder !== null && real(holder) !== real(wt)) {
1019
+ log(`${branch} is checked out in ${holder} — local and remote branch left in place`);
1020
+ return result(false, fs.existsSync(wt) ? "held-elsewhere" : "absent");
1021
+ }
1022
+ try {
1023
+ fetchBranch(root, DEV);
1024
+ expected = git(root, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}^{commit}`]);
1025
+ if (expected === null) {
1026
+ log(`cannot read local ${branch}; cleanup evidence unavailable — preserved`);
1027
+ return result(false, "unavailable");
1028
+ }
1029
+ const missing = notOnDev(root, expected);
1030
+ if (missing.length > 0) {
1031
+ log(`${branch} carries work ${ORIGIN_DEV} does not — preserved: ${missing.join(", ")}`);
1032
+ return result(false, "not-landed");
1033
+ }
1034
+ const remote = remoteHas(root, branch);
1035
+ if (remote === "error") {
1036
+ log(`cannot read remote origin/${branch}; cleanup evidence unavailable — preserved`);
1037
+ return result(false, "unavailable");
1038
+ }
1039
+ if (remote === "yes") {
1040
+ fetchBranch(root, branch);
1041
+ const remoteMissing = notOnDev(root, `refs/remotes/origin/${branch}`);
1042
+ if (remoteMissing.length > 0) {
1043
+ log(
1044
+ `remote origin/${branch} holds unlanded work — local worktree and remote branch preserved: ${remoteMissing.join(", ")}`,
1045
+ );
1046
+ return result(false, "remote-not-landed");
1047
+ }
1048
+ remoteExpected = git(root, [
1049
+ "rev-parse",
1050
+ "--verify",
1051
+ "--quiet",
1052
+ `refs/remotes/origin/${branch}^{commit}`,
1053
+ ]);
1054
+ }
1055
+ } catch (error) {
1056
+ log(`cleanup evidence unavailable — preserved: ${(error as Error).message}`);
1057
+ return result(false, "unavailable");
1058
+ }
1059
+ }
1060
+ if (fs.existsSync(wt)) {
1061
+ const dirty = dirtyWork(root, wt, options.landed === true);
1062
+ if (dirty.length > 0) {
1063
+ log(`${wt} holds uncommitted work — preserved: ${dirty.join(", ")}`);
1064
+ return result(false, "uncommitted");
1065
+ }
1066
+ }
1067
+ if (!fs.existsSync(wt)) {
1068
+ runGit(root, ["worktree", "prune"]);
1069
+ return result(false, "absent", true);
1070
+ }
731
1071
  const inside = !path.relative(real(wt), real(cwd)).startsWith("..");
732
1072
  const res = runGit(root, ["worktree", "remove", "--force", wt]);
733
1073
  if (!res.ok) throw new CommandError(EXIT_REMOVE, `git worktree remove failed: ${res.stderr}`);
734
1074
  runGit(root, ["worktree", "prune"]);
735
1075
  fs.rmSync(marker, { force: true });
736
1076
  if (inside) log(`the working directory was inside ${wt} — cd to ${root}`);
737
- return result(true, null);
1077
+ return result(true, null, true);
738
1078
  }
739
1079
 
740
1080
  // ---------------------------------------------------------------------------
@@ -875,6 +1215,20 @@ export const worktreesCommand: CommandSpec = {
875
1215
  : `refusing to ship ${target} as a feature branch`,
876
1216
  );
877
1217
  }
1218
+ if (workflow === "ship" && git(root, ["remote", "get-url", "origin"]) !== null) {
1219
+ fetchBranch(root, DEV);
1220
+ const remote = remoteHas(root, target);
1221
+ if (remote === "error")
1222
+ throw new CommandError(
1223
+ EXIT_FETCH,
1224
+ `cannot fetch origin ${target}: remote branch evidence unavailable`,
1225
+ );
1226
+ if (remote === "yes") {
1227
+ fetchBranch(root, target);
1228
+ assertShipEligible(root, `refs/remotes/origin/${target}`);
1229
+ }
1230
+ if (hasLocal(root, target)) assertShipEligible(root, `refs/heads/${target}`);
1231
+ }
878
1232
  if (
879
1233
  workflow === "debug" &&
880
1234
  named &&
@@ -944,7 +1298,12 @@ export const worktreesCommand: CommandSpec = {
944
1298
  );
945
1299
  }
946
1300
  if (workflow === "ship" && git(root, ["branch", "--show-current"]) !== target) {
947
- const sw = runGit(root, ["switch", target]);
1301
+ const sw = runGit(
1302
+ root,
1303
+ hasLocal(root, target)
1304
+ ? ["switch", target]
1305
+ : ["switch", "--no-track", "-c", target, `refs/remotes/origin/${target}`],
1306
+ );
948
1307
  if (!sw.ok) {
949
1308
  if (!hasLocal(root, target) && remoteHas(root, target) !== "yes") {
950
1309
  throw new CommandError(
@@ -1005,6 +1364,8 @@ export const worktreesCommand: CommandSpec = {
1005
1364
  detail: "a rebase is already in progress",
1006
1365
  onto: worktreeBase(wt, workflow),
1007
1366
  };
1367
+ } else if (workflow === "debug") {
1368
+ ctx.log("debug resume: preserving branch history for CI evidence; no rebase");
1008
1369
  } else {
1009
1370
  fetchBranch(wt, DEV);
1010
1371
  const onto = worktreeBase(wt, workflow, ctx.log);
@@ -1039,11 +1400,13 @@ export const worktreesCommand: CommandSpec = {
1039
1400
  }
1040
1401
  }
1041
1402
  if (failure) {
1042
- fs.mkdirSync(logDir, { recursive: true });
1043
- fs.appendFileSync(
1044
- path.join(logDir, "rebase-resolve-log.md"),
1045
- `[bkit-worktrees] ${new Date().toISOString()} rebase onto ${failure.onto} stopped\n${failure.detail}\n`,
1046
- );
1403
+ const note = `[bkit-worktrees] ${new Date().toISOString()} rebase onto ${failure.onto} stopped\n${failure.detail}\n`;
1404
+ const held = rebaseInProgress(wt) ? rebaseNoteFile(wt) : null;
1405
+ if (held !== null) fs.appendFileSync(held, note);
1406
+ else {
1407
+ fs.mkdirSync(logDir, { recursive: true });
1408
+ fs.appendFileSync(path.join(logDir, "rebase-resolve-log.md"), note);
1409
+ }
1047
1410
  fs.writeFileSync(sentinelPath, "");
1048
1411
  ctx.log(
1049
1412
  `rebase onto ${failure.onto} failed in ${wt}: ${failure.detail.split("\n")[0]}`,
@@ -1115,27 +1478,28 @@ export const worktreesCommand: CommandSpec = {
1115
1478
  },
1116
1479
  remove: {
1117
1480
  summary:
1118
- "Remove .worktrees/{fid} when a workflow created it, prune stale entries, and delete the feature branch.",
1481
+ "Remove a workflow-owned worktree when its work is safely on dev; conditionally delete its local and remote branch at their proved landed tips.",
1119
1482
  use: "workflow",
1120
1483
  flags: [
1121
1484
  FID_FLAG,
1122
1485
  {
1123
1486
  name: "branch",
1124
1487
  type: "string",
1125
- help: "feature branch to delete locally and on origin once the worktree is gone; skipped when another worktree still holds it",
1488
+ help: "feature branch to delete locally and on origin only at its proved landed tips; preserve unlanded/uncertain work",
1126
1489
  },
1127
1490
  ],
1128
1491
  output: {
1129
1492
  removed: "the worktree was removed",
1130
- reason: "why it was not: absent | not-owned (no .worktree-owned marker); null when removed",
1493
+ reason:
1494
+ "why it was not removed: absent | not-owned | held-elsewhere | uncommitted | not-landed | remote-not-landed | unavailable; null when removed",
1131
1495
  worktreePath: "the worktree's path",
1132
1496
  repoRoot: "the main checkout — cd here if the shell was inside the removed worktree",
1133
1497
  branchDeleted:
1134
- "--branch: the local branch is gone (deleted or already absent); null without --branch",
1498
+ "--branch: the proved local tip was atomically deleted; false when preserved or unavailable, null without --branch",
1135
1499
  remoteDeleted:
1136
- "--branch: git push origin --delete succeeded; false when it failed or was already gone; null without --branch",
1500
+ "--branch: the remote branch was deleted at its proved landed tip; false when absent, refused or changed, null without --branch",
1137
1501
  branchBlockedBy:
1138
- "--branch: the worktree still holding the branch, so neither the local nor the remote branch was deleted; null when none",
1502
+ "--branch: the worktree still holding the branch or changed-after-proof; null when none",
1139
1503
  },
1140
1504
  exitCodes: { [EXIT_REMOVE]: "git worktree remove failed" },
1141
1505
  run: (ctx) => {