@cbartens/bkit 6.1.1 → 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 (313) 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 +42 -32
  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 +97 -36
  15. package/.bkit/core/.bkit/templates.md +162 -34
  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 +89 -37
  64. package/.bkit/core/engine/checks/after/index.ts +15 -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 +64 -11
  74. package/.bkit/core/engine/commands/ci/push-gate.ts +101 -43
  75. package/.bkit/core/engine/commands/install/install.ts +28 -25
  76. package/.bkit/core/engine/commands/install/uninstall.ts +42 -30
  77. package/.bkit/core/engine/commands/install/upgrade.ts +14 -2
  78. package/.bkit/core/engine/commands/land.ts +2 -3
  79. package/.bkit/core/engine/commands/lib.ts +394 -39
  80. package/.bkit/core/engine/commands/registry.ts +1 -1
  81. package/.bkit/core/engine/commands/workflow/branches.ts +351 -78
  82. package/.bkit/core/engine/commands/workflow/challenge.ts +63 -14
  83. package/.bkit/core/engine/commands/workflow/context.ts +71 -10
  84. package/.bkit/core/engine/commands/workflow/counters.ts +298 -23
  85. package/.bkit/core/engine/commands/workflow/decisions.ts +260 -125
  86. package/.bkit/core/engine/commands/workflow/disk.ts +2 -1
  87. package/.bkit/core/engine/commands/workflow/feature-base.ts +66 -0
  88. package/.bkit/core/engine/commands/workflow/issues.ts +312 -17
  89. package/.bkit/core/engine/commands/workflow/junit.ts +204 -0
  90. package/.bkit/core/engine/commands/workflow/ledgers.ts +904 -99
  91. package/.bkit/core/engine/commands/workflow/locks.ts +186 -29
  92. package/.bkit/core/engine/commands/workflow/loops.ts +87 -0
  93. package/.bkit/core/engine/commands/workflow/open-decision.ts +251 -0
  94. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +8 -0
  95. package/.bkit/core/engine/commands/workflow/plans.ts +1 -1
  96. package/.bkit/core/engine/commands/workflow/prs.ts +311 -16
  97. package/.bkit/core/engine/commands/workflow/repo.ts +1 -1
  98. package/.bkit/core/engine/commands/workflow/run-facts.ts +6 -0
  99. package/.bkit/core/engine/commands/workflow/runs.ts +877 -174
  100. package/.bkit/core/engine/commands/workflow/runtime.ts +12 -4
  101. package/.bkit/core/engine/commands/workflow/status.ts +324 -11
  102. package/.bkit/core/engine/commands/workflow/step-table.ts +41 -15
  103. package/.bkit/core/engine/commands/workflow/steps.ts +604 -29
  104. package/.bkit/core/engine/commands/workflow/summary-findings.ts +1 -1
  105. package/.bkit/core/engine/commands/workflow/summary.ts +314 -8
  106. package/.bkit/core/engine/commands/workflow/tasks.ts +400 -27
  107. package/.bkit/core/engine/commands/workflow/tests-base.ts +319 -0
  108. package/.bkit/core/engine/commands/workflow/tests-changed.ts +138 -74
  109. package/.bkit/core/engine/commands/workflow/tests-jump.ts +93 -0
  110. package/.bkit/core/engine/commands/workflow/tests.ts +815 -182
  111. package/.bkit/core/engine/commands/workflow/tracker.ts +1134 -137
  112. package/.bkit/core/engine/commands/workflow/workflows.ts +100 -72
  113. package/.bkit/core/engine/commands/workflow/worktrees.ts +421 -57
  114. package/.bkit/core/engine/install/cloud-env.ts +38 -10
  115. package/.bkit/core/engine/install/managed-block.ts +105 -0
  116. package/.bkit/core/engine/install/manifest.ts +7 -1
  117. package/.bkit/core/engine/install/modules/claude.ts +6 -2
  118. package/.bkit/core/engine/install/modules/cloud.ts +84 -95
  119. package/.bkit/core/engine/install/modules/codex.ts +10 -2
  120. package/.bkit/core/engine/install/modules/core.ts +148 -14
  121. package/.bkit/core/engine/install/modules/opencode.ts +18 -23
  122. package/.bkit/core/engine/install/network-allowlist.ts +8 -3
  123. package/.bkit/core/engine/install/project-docs.ts +650 -0
  124. package/.bkit/core/engine/install/template-copies.ts +58 -5
  125. package/.bkit/core/engine/install/write.ts +128 -7
  126. package/.bkit/core/engine/ledgers/journal.ts +18 -10
  127. package/.bkit/core/engine/ledgers/migrate.ts +20 -8
  128. package/.bkit/core/engine/ledgers/status.ts +604 -8
  129. package/.bkit/core/engine/ledgers/telemetry.ts +115 -13
  130. package/.bkit/core/engine/render/trackers.ts +3 -1
  131. package/.bkit/core/engine/shared/package-manager.ts +7 -3
  132. package/.bkit/core/engine/shared/settings.ts +12 -1
  133. package/.bkit/core/engine/shared/text.ts +14 -0
  134. package/.bkit/core/engine/tools/instructions-sources.ts +1 -0
  135. package/.bkit/core/engine/tools/instructions.ts +116 -20
  136. package/.bkit/core/hooks/antigravity-hook.js +20 -4
  137. package/.bkit/core/hooks/gateguard-edit-payload.js +8 -5
  138. package/.bkit/core/hooks/gateguard-engine.js +249 -23
  139. package/.bkit/core/hooks/guardrails-deny.js +167 -0
  140. package/.bkit/core/hooks/guardrails-read.js +3 -3
  141. package/.bkit/core/hooks/guardrails-shell.js +1122 -167
  142. package/.bkit/core/hooks/guardrails-tiers.js +247 -176
  143. package/.bkit/core/hooks/preflight-tracker.sh +219 -0
  144. package/.bkit/core/prompts/bkit-audit-generate.md +23 -6
  145. package/.bkit/core/prompts/bkit-build-challenge-1.md +5 -4
  146. package/.bkit/core/prompts/bkit-build-challenge-2.md +6 -5
  147. package/.bkit/core/prompts/bkit-build-install-skills.md +2 -2
  148. package/.bkit/core/prompts/bkit-build-plan-convert.md +21 -7
  149. package/.bkit/core/prompts/bkit-build-plan-current.md +5 -4
  150. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +22 -17
  151. package/.bkit/core/prompts/bkit-build-plan-tasks.md +16 -12
  152. package/.bkit/core/prompts/bkit-build-plan-tests.md +14 -10
  153. package/.bkit/core/prompts/bkit-build-plan-verify.md +21 -8
  154. package/.bkit/core/prompts/bkit-debug-abort-handover.md +10 -5
  155. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +22 -6
  156. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +19 -3
  157. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +22 -6
  158. package/.bkit/core/prompts/bkit-debug-failure-soak.md +10 -7
  159. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +3 -3
  160. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +4 -4
  161. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +3 -3
  162. package/.bkit/core/prompts/bkit-design-generate.md +6 -4
  163. package/.bkit/core/prompts/bkit-design-organise.md +4 -3
  164. package/.bkit/core/prompts/bkit-design-review-1.md +5 -4
  165. package/.bkit/core/prompts/bkit-design-review-2.md +6 -5
  166. package/.bkit/core/prompts/bkit-design-spike.md +4 -3
  167. package/.bkit/core/prompts/bkit-design-update.md +6 -4
  168. package/.bkit/core/prompts/bkit-plan-generate.md +35 -14
  169. package/.bkit/core/prompts/bkit-plan-review-1.md +9 -7
  170. package/.bkit/core/prompts/bkit-plan-review-2.md +9 -7
  171. package/.bkit/core/prompts/bkit-plan-scope-check.md +8 -6
  172. package/.bkit/core/prompts/bkit-plan-update.md +22 -8
  173. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +11 -8
  174. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +9 -5
  175. package/.bkit/core/prompts/bkit-ship-update-docs.md +26 -4
  176. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +3 -3
  177. package/.bkit/core/prompts/bkit-utility-update-decisions.md +10 -7
  178. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +8 -5
  179. package/.bkit/core/prompts/bkit-utility-update-documentation.md +31 -7
  180. package/.bkit/core/prompts/bkit-utility-update-failures.md +8 -5
  181. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +10 -7
  182. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +4 -4
  183. package/.bkit/core/prompts/bkit-utility-update-tracker.md +4 -4
  184. package/.bkit/core/workflows/bkit-auto.md +23 -11
  185. package/.bkit/core/workflows/bkit-build.md +331 -100
  186. package/.bkit/core/workflows/bkit-debug.md +135 -64
  187. package/.bkit/core/workflows/bkit-design.md +58 -32
  188. package/.bkit/core/workflows/bkit-plan.md +73 -45
  189. package/.bkit/core/workflows/bkit-ship.md +233 -167
  190. package/.bkit/shared/.agents/plugins/bkit/hooks.json +1 -1
  191. package/.bkit/shared/.bkit/.env.example +5 -0
  192. package/.bkit/shared/.claude/bkit-cloud.md +7 -7
  193. package/.bkit/shared/.claude/settings.json +5 -1
  194. package/.bkit/shared/.cursor/bkit-cloud.md +1 -1
  195. package/.bkit/shared/.cursor/hooks.json +1 -1
  196. package/.bkit/shared/.opencode/opencode.json +11 -2
  197. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +27 -0
  198. package/.bkit/templates/.cursor/Dockerfile +7 -7
  199. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +1 -1
  200. package/.bkit/templates/.github/dependabot.yml +5 -0
  201. package/.bkit/templates/.github/renovate.json5 +5 -3
  202. package/.bkit/templates/.github/workflows/bkit-ci.yml +11 -11
  203. package/.bkit/templates/.github/workflows/bkit-cloud.yml +525 -161
  204. package/.bkit/templates/.github/workflows/bkit-renovate.yml +2 -2
  205. package/.bkit/templates/.husky/pre-push +123 -6
  206. package/.bkit/templates/context/bkit-serena.md +1 -1
  207. package/.bkit/templates/docs/architecture.md +98 -0
  208. package/.bkit/templates/docs/capabilities.md +33 -37
  209. package/.bkit/templates/docs/components.md +142 -0
  210. package/.bkit/templates/docs/data-schema.md +87 -0
  211. package/.bkit/{shared → templates}/docs/deployments.md +128 -142
  212. package/.bkit/templates/docs/design.md +117 -0
  213. package/.bkit/templates/docs/noise.md +54 -0
  214. package/.bkit/templates/docs/observability.md +99 -0
  215. package/.bkit/templates/docs/security.md +137 -0
  216. package/.bkit/templates/docs/setup.md +93 -0
  217. package/.bkit/templates/docs/technology.md +70 -0
  218. package/.bkit/{shared → templates}/docs/testing.md +200 -87
  219. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +511 -103
  220. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +228 -35
  221. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +270 -2
  222. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  223. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +92 -63
  224. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +59 -11
  225. package/.bkit/templates/slop-scan.config.json +2 -0
  226. package/CHANGELOG.md +64 -0
  227. package/DETAILS.md +24 -19
  228. package/README.md +1 -1
  229. package/dist/checks/after/auth.js +114 -46
  230. package/dist/checks/after/github.js +77 -35
  231. package/dist/checks/after/index.js +12 -3
  232. package/dist/checks/after/tools.js +224 -1
  233. package/dist/checks/before/files.js +59 -1
  234. package/dist/checks/before/index.js +7 -1
  235. package/dist/checks/status-holes.js +20 -21
  236. package/dist/checks/tips/catalogue.js +99 -10
  237. package/dist/checks/tips/detect.js +35 -3
  238. package/dist/checks/tips/index.js +1 -1
  239. package/dist/cli.js +13 -13
  240. package/dist/commands/ci/ci.js +56 -12
  241. package/dist/commands/ci/push-gate.js +79 -44
  242. package/dist/commands/install/install.js +23 -22
  243. package/dist/commands/install/uninstall.js +36 -30
  244. package/dist/commands/install/upgrade.js +10 -2
  245. package/dist/commands/land.js +2 -3
  246. package/dist/commands/lib.js +323 -25
  247. package/dist/commands/workflow/branches.js +312 -72
  248. package/dist/commands/workflow/challenge.js +66 -13
  249. package/dist/commands/workflow/context.js +46 -10
  250. package/dist/commands/workflow/counters.js +231 -23
  251. package/dist/commands/workflow/decisions.js +221 -106
  252. package/dist/commands/workflow/disk.js +2 -1
  253. package/dist/commands/workflow/feature-base.js +60 -0
  254. package/dist/commands/workflow/issues.js +243 -15
  255. package/dist/commands/workflow/junit.js +137 -0
  256. package/dist/commands/workflow/ledgers.js +726 -112
  257. package/dist/commands/workflow/locks.js +150 -29
  258. package/dist/commands/workflow/loops.js +67 -0
  259. package/dist/commands/workflow/open-decision.js +199 -0
  260. package/dist/commands/workflow/plan-blocks.js +6 -0
  261. package/dist/commands/workflow/plans.js +1 -1
  262. package/dist/commands/workflow/prs.js +272 -16
  263. package/dist/commands/workflow/repo.js +1 -1
  264. package/dist/commands/workflow/run-facts.js +6 -0
  265. package/dist/commands/workflow/runs.js +747 -155
  266. package/dist/commands/workflow/runtime.js +8 -4
  267. package/dist/commands/workflow/status.js +259 -13
  268. package/dist/commands/workflow/step-table.js +41 -15
  269. package/dist/commands/workflow/steps.js +530 -26
  270. package/dist/commands/workflow/summary-findings.js +1 -1
  271. package/dist/commands/workflow/summary.js +289 -8
  272. package/dist/commands/workflow/tasks.js +294 -27
  273. package/dist/commands/workflow/tests-base.js +266 -0
  274. package/dist/commands/workflow/tests-changed.js +130 -56
  275. package/dist/commands/workflow/tests-jump.js +77 -0
  276. package/dist/commands/workflow/tests.js +608 -131
  277. package/dist/commands/workflow/tracker.js +920 -112
  278. package/dist/commands/workflow/workflows.js +80 -59
  279. package/dist/commands/workflow/worktrees.js +387 -58
  280. package/dist/install/cloud-env.js +32 -10
  281. package/dist/install/managed-block.js +101 -0
  282. package/dist/install/manifest.js +7 -1
  283. package/dist/install/modules/claude.js +6 -2
  284. package/dist/install/modules/cloud.js +73 -86
  285. package/dist/install/modules/codex.js +9 -2
  286. package/dist/install/modules/core.js +133 -14
  287. package/dist/install/modules/opencode.js +18 -23
  288. package/dist/install/network-allowlist.js +8 -3
  289. package/dist/install/project-docs.js +551 -0
  290. package/dist/install/template-copies.js +55 -5
  291. package/dist/install/write.js +117 -5
  292. package/dist/ledgers/journal.js +10 -8
  293. package/dist/ledgers/migrate.js +20 -9
  294. package/dist/ledgers/status.js +461 -8
  295. package/dist/ledgers/telemetry.js +71 -13
  296. package/dist/render/trackers.js +3 -1
  297. package/dist/shared/package-manager.js +7 -2
  298. package/dist/shared/settings.js +8 -0
  299. package/dist/shared/text.js +13 -0
  300. package/dist/tools/instructions-sources.js +1 -0
  301. package/dist/tools/instructions.js +97 -24
  302. package/package.json +22 -15
  303. package/.bkit/core/hooks/preflight-linear.sh +0 -73
  304. package/.bkit/shared/docs/architecture.md +0 -16
  305. package/.bkit/shared/docs/data-schema.md +0 -16
  306. package/.bkit/shared/docs/design.md +0 -38
  307. package/.bkit/shared/docs/noise.md +0 -20
  308. package/.bkit/shared/docs/observability.md +0 -22
  309. package/.bkit/shared/docs/security.md +0 -62
  310. package/.bkit/shared/docs/setup.md +0 -52
  311. package/.bkit/shared/docs/technology.md +0 -15
  312. /package/.bkit/templates/{.lintstagedrc.json → lintstagedrc.example.json} +0 -0
  313. /package/.bkit/templates/{.prettierignore → prettierignore.example} +0 -0
@@ -12,18 +12,19 @@
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
  import { spawnSync } from "node:child_process";
16
17
  import { createHash } from "node:crypto";
17
18
  import * as fs from "node:fs";
18
19
  import * as path from "node:path";
19
- import { actionHash, actionKey, lastRun, recordAction } from "../../ledgers/status.js";
20
+ import { actionHash, actionKey, lastRun, recordAction, withTargetLock, } from "../../ledgers/status.js";
20
21
  import { APPEND_LEDGERS, gitEnv } from "../../ledgers/telemetry.js";
21
22
  import { parseJson } from "../../shared/json.js";
22
23
  import { readBkitConfig } from "../../shared/settings.js";
23
24
  import { COULD_NOT_RUN_EXIT_CODES, installCommand } from "../../shared/package-manager.js";
24
25
  import { CommandError, DEV, EXIT, git, isIgnoredPath, isSharedBranch, MAIN, mainCheckoutRoot, repoRoot, runGit, } from "../lib.js";
25
26
  import { ensureDiskSpace } from "./disk.js";
26
- import { listRecords, newRecord, readRecord, removeRecord, withSetupGuard, writeRecord, } from "./ledgers.js";
27
+ import { RUN_COMMITS_ROW, listRecords, newRecord, readParkedCommits, readRecord, readRunCommits, removeParkedCommits, removeRecord, runCommitsIn, withSetupGuard, writeRecord, } from "./ledgers.js";
27
28
  import { workflowLockFresh, workflowLockLive } from "./locks.js";
28
29
  import { detect } from "./runtime.js";
29
30
  import { WORKFLOW_FLAG, readRuns } from "./status.js";
@@ -49,7 +50,7 @@ function fidOf(value) {
49
50
  return fid;
50
51
  }
51
52
  export const worktreeDir = (root, fid) => path.join(root, ".worktrees", fid);
52
- /** `.worktree-owned` in the git common dir's outbox: shared by every worktree, survives removal. */
53
+ /** `.worktree-owned` is shared across worktrees; session invocation state stays separate. */
53
54
  export function ownershipMarker(root, fid) {
54
55
  const common = git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
55
56
  if (!common)
@@ -93,11 +94,67 @@ function fetchBranch(cwd, branch) {
93
94
  throw new CommandError(EXIT_FETCH, `could not fetch origin ${branch}: ${res.stderr}`);
94
95
  }
95
96
  }
97
+ /**
98
+ * `fresh` with the start, commits and pushed list of a `run-commits` row laid over it:
99
+ * the record a Stop removed. A commit that is not an ancestor of HEAD is dropped, and a
100
+ * row start that is not a commit leaves the fresh one.
101
+ */
102
+ function rebuildFromRow(root, fresh, row) {
103
+ if (row === null)
104
+ return fresh;
105
+ const onBranch = (sha) => runGit(root, ["merge-base", "--is-ancestor", sha, "HEAD"]).ok;
106
+ const isCommit = (sha) => runGit(root, ["rev-parse", "-q", "--verify", `${sha}^{commit}`]).ok;
107
+ const commits = row.commits.filter(onBranch);
108
+ return {
109
+ ...fresh,
110
+ startSha: row.startSha !== "" && isCommit(row.startSha) ? row.startSha : fresh.startSha,
111
+ commits,
112
+ pushed: row.pushed.filter((sha) => commits.includes(sha)),
113
+ };
114
+ }
115
+ /** The status rows that open or close a run. */
116
+ const RUN_BOUNDARY = new Set([
117
+ "workflow-started",
118
+ "workflow-done",
119
+ "workflow-failed",
120
+ ]);
121
+ /**
122
+ * The newest `run-commits` row of `workflow` in the copy of the status log on
123
+ * `origin/dev`. A landed handover takes the row's line back out of the checkout, so the
124
+ * landed copy is the one that holds it. That copy holds only the lines landings carried,
125
+ * so the run counts as open when no row that opens or closes a run follows the row.
126
+ * Null when the copy is missing or cannot be read, or the row is absent or followed by
127
+ * such a row. A failed fetch reads the copy this clone last saw.
128
+ */
129
+ function landedRunCommits(root, statusFile, workflow) {
130
+ runGit(root, ["fetch", "-q", "origin", `+refs/heads/${DEV}:refs/remotes/origin/${DEV}`]);
131
+ const rel = path.relative(root, statusFile).split(path.sep).join("/");
132
+ const landed = runGit(root, ["show", `refs/remotes/origin/${DEV}:${rel}`]);
133
+ if (!landed.ok)
134
+ return null;
135
+ const types = landed.stdout.split("\n").flatMap((line) => {
136
+ const parsed = parseJson(line);
137
+ const row = parsed.ok ? parsed.value : null;
138
+ return row !== null && typeof row === "object" && row["workflow"] === workflow
139
+ ? [String(row["type"])]
140
+ : [];
141
+ });
142
+ const at = types.lastIndexOf(RUN_COMMITS_ROW);
143
+ if (at < 0 || types.slice(at + 1).some((type) => RUN_BOUNDARY.has(type)))
144
+ return null;
145
+ return runCommitsIn(landed.stdout, workflow);
146
+ }
96
147
  /**
97
148
  * The shared-checkout record for an in-place run on `dev`. Another feature's
98
149
  * record with a live workflow lock means that run owns the checkout; one
99
150
  * without is left over and removed. The same feature with an open run in
100
- * `{logDir}/status.jsonl` is a resume and keeps its record; a new run rewrites it.
151
+ * `{logDir}/status.jsonl` is a resume and keeps its record. A run with no record
152
+ * takes the start, commits and pushed list of the first of these that has one:
153
+ * the parked copy in this clone's git dir, unless the checkout's log shows the
154
+ * run closed (then it is stale and removed); the `run-commits` row in
155
+ * `{logDir}/status.jsonl` of an open run; the row on `origin/dev` while that log
156
+ * shows no closed run after it, which is the only one that fetches. The parked
157
+ * copy is removed once the record is written.
101
158
  */
102
159
  function openSharedRecord(root, fid, workflow, logDir) {
103
160
  const busy = (other) => new CommandError(EXIT_SHARED_BUSY, `${other} is running in this checkout (workflow lock held) — wait for it to finish, then re-run`);
@@ -113,13 +170,23 @@ function openSharedRecord(root, fid, workflow, logDir) {
113
170
  }
114
171
  const existing = readRecord(root, fid);
115
172
  const statusFile = path.join(logDir, "status.jsonl");
116
- const open = fs.existsSync(statusFile) &&
117
- lastRun(readRuns(statusFile), workflow)?.status === "IN_PROGRESS";
118
- if (existing !== null && existing.branch === DEV && open)
173
+ const last = fs.existsSync(statusFile) ? lastRun(readRuns(statusFile), workflow) : undefined;
174
+ const open = last?.status === "IN_PROGRESS";
175
+ if (existing !== null && existing.branch === DEV && open) {
176
+ removeParkedCommits(root, fid);
119
177
  return existing;
178
+ }
120
179
  const fresh = newRecord(root, fid, DEV);
121
- writeRecord(root, fresh);
122
- return fresh;
180
+ // A closed run in the checkout's log ended the run every copy of the row belongs to.
181
+ const closed = last !== undefined && !open;
182
+ const parked = closed ? null : readParkedCommits(root, fid, workflow);
183
+ const row = parked ??
184
+ (open ? readRunCommits(statusFile, workflow) : null) ??
185
+ (closed ? null : landedRunCommits(root, statusFile, workflow));
186
+ const rebuilt = rebuildFromRow(root, fresh, row);
187
+ writeRecord(root, rebuilt);
188
+ removeParkedCommits(root, fid);
189
+ return rebuilt;
123
190
  });
124
191
  if (guarded === null)
125
192
  throw busy("another run");
@@ -183,13 +250,35 @@ export function worktreeBase(cwd, workflow, log) {
183
250
  * may bring docs and ledgers only, so such a branch can never land.
184
251
  */
185
252
  function inheritedDevCommits(root, branch) {
186
- const unpushed = new Set((git(root, ["rev-list", `${ORIGIN_DEV}..${DEV}`]) ?? "").split("\n").filter(Boolean));
253
+ if (!hasLocal(root, DEV))
254
+ return [];
255
+ const read = (args) => {
256
+ const result = runGit(root, args);
257
+ if (!result.ok)
258
+ throw new CommandError(EXIT_REFUSED, `cannot inspect unpublished ${DEV} work for ${branch}: ${result.stderr}`);
259
+ return result.stdout.trim();
260
+ };
261
+ const unpushed = new Set(read(["rev-list", `${ORIGIN_DEV}..${DEV}`])
262
+ .split("\n")
263
+ .filter(Boolean));
187
264
  if (unpushed.size === 0)
188
265
  return [];
189
- return (git(root, ["rev-list", branch, "--not", ORIGIN_DEV]) ?? "")
266
+ return read(["rev-list", branch, "--not", ORIGIN_DEV])
190
267
  .split("\n")
191
268
  .filter((c) => unpushed.has(c));
192
269
  }
270
+ /** Refuse a publication candidate that imports unpublished local dev ancestry. */
271
+ export function assertShipEligible(root, candidate) {
272
+ if (git(root, ["rev-parse", "--verify", "--quiet", `${candidate}^{commit}`]) === null)
273
+ throw new CommandError(EXIT_REFUSED, `cannot inspect ship candidate ${candidate}`);
274
+ const inherited = inheritedDevCommits(root, candidate);
275
+ if (inherited.length === 0)
276
+ return;
277
+ const commits = inherited
278
+ .map((sha) => git(root, ["show", "-s", "--format=%h %s", sha]) ?? sha)
279
+ .join("; ");
280
+ throw new CommandError(EXIT_REFUSED, `${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.`);
281
+ }
193
282
  /** Why a docs-only branch carrying unpushed `dev` cannot land, and what unblocks it. */
194
283
  function inheritedDevRefusal(root, target, workflow, count) {
195
284
  const ahead = git(root, ["rev-list", "--count", `${ORIGIN_DEV}..${DEV}`]) ?? "?";
@@ -248,6 +337,15 @@ function rebaseInProgress(wt) {
248
337
  return dir !== null && fs.existsSync(dir);
249
338
  });
250
339
  }
340
+ /**
341
+ * Where setup holds its "rebase stopped" note while it leaves a rebase in progress:
342
+ * inside the worktree's git dir, never in the tree. `--continue` refuses while a
343
+ * tracked file has unstaged changes, and the run's rebase log is tracked once a run
344
+ * committed it. `branches rebase` writes the note ahead of its own log lines.
345
+ */
346
+ export function rebaseNoteFile(wt) {
347
+ return git(wt, ["rev-parse", "--path-format=absolute", "--git-path", "bkit-rebase-note.md"]);
348
+ }
251
349
  /**
252
350
  * bkit's own worktree copy entry, excluded from every bkit commit beside
253
351
  * `bkit.workflows.worktree.copy`: it holds the sign-in tokens, and a consumer whose
@@ -354,8 +452,10 @@ function putJournalRowsBack(wt, journal) {
354
452
  }
355
453
  for (const [rel, a] of journal) {
356
454
  const file = path.join(wt, rel);
357
- const text = fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : "";
358
- fs.appendFileSync(file, `${text !== "" && !text.endsWith("\n") ? "\n" : ""}${a.rows}`);
455
+ withTargetLock(file, () => {
456
+ const text = fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : "";
457
+ fs.appendFileSync(file, `${text !== "" && !text.endsWith("\n") ? "\n" : ""}${a.rows}`);
458
+ });
359
459
  }
360
460
  return "";
361
461
  }
@@ -409,11 +509,14 @@ function carryLeftovers(wt, o, log) {
409
509
  // Copy and install
410
510
  // ---------------------------------------------------------------------------
411
511
  /** Copy each `worktreeCopy` entry from the main checkout; a missing one is narrated, never fatal. */
412
- function copyListed(root, wt, entries, log) {
512
+ export function copyListed(root, wt, entries, log) {
413
513
  const copied = [];
414
514
  const copyMissing = [];
415
515
  for (const entry of entries) {
416
516
  const rel = path.normalize(entry);
517
+ // bkit's own env is managed by linkBkitEnv, including on resume.
518
+ if (BKIT_OWN_COPY.some((owned) => path.normalize(owned) === rel))
519
+ continue;
417
520
  if (!insideCheckout(rel)) {
418
521
  log(`worktree copy: ${entry} is outside the main checkout — skipped`);
419
522
  continue;
@@ -490,7 +593,8 @@ function linkBkitEnv(root, wt, fid, log) {
490
593
  * `direnv allow` the worktree's `.envrc` when it matches the main checkout's
491
594
  * byte for byte, so the worktree inherits the trust given there and nothing
492
595
  * more; a differing file is left for a human to read. No `.envrc`, direnv
493
- * missing or failing → false, narrated, never fatal.
596
+ * missing or failing → false, narrated (a differing or failed one says the push will
597
+ * block, since the pre-push hook refuses an untrusted `.envrc`), never fatal.
494
598
  */
495
599
  function allowDirenv(root, wt, log) {
496
600
  const envrc = path.join(wt, ".envrc");
@@ -498,7 +602,7 @@ function allowDirenv(root, wt, log) {
498
602
  return false;
499
603
  const main = path.join(root, ".envrc");
500
604
  if (!fs.existsSync(main) || !fs.readFileSync(main).equals(fs.readFileSync(envrc))) {
501
- log(`direnv: ${envrc} differs from the main checkout's — not allowed; read it, then run direnv allow`);
605
+ log(`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 .)`);
502
606
  return false;
503
607
  }
504
608
  const res = spawnSync("direnv", ["allow", wt], { cwd: wt, encoding: "utf-8" });
@@ -507,14 +611,14 @@ function allowDirenv(root, wt, log) {
507
611
  return false;
508
612
  }
509
613
  if (res.status !== 0) {
510
- log(`direnv allow failed (exit ${res.status}): ${(res.stderr ?? "").trim()}`);
614
+ log(`direnv allow failed (exit ${res.status}): ${(res.stderr ?? "").trim()} — the push will block until you run direnv allow . in the worktree`);
511
615
  return false;
512
616
  }
513
617
  return true;
514
618
  }
515
619
  /** Run the frozen install in `wt`; the exit status, with a spawn failure read as "could not run". */
516
- function install(wt, log) {
517
- const [cmd, ...args] = installCommand({ frozen: true });
620
+ export function install(wt, log, opts = {}) {
621
+ const [cmd, ...args] = installCommand({ frozen: true, preferOffline: opts.preferOffline });
518
622
  const res = spawnSync(cmd, args, { cwd: wt, encoding: "utf-8", maxBuffer: 1 << 26 });
519
623
  const status = res.error ? 127 : (res.status ?? 1);
520
624
  if (status !== 0) {
@@ -527,9 +631,147 @@ function install(wt, log) {
527
631
  // ---------------------------------------------------------------------------
528
632
  // Branch cleanup
529
633
  // ---------------------------------------------------------------------------
634
+ /** Preserve NUL-delimited paths and the status columns that runGit trims. */
635
+ function cleanupRead(root, args) {
636
+ const result = spawnSync("git", args, {
637
+ cwd: root,
638
+ encoding: "utf-8",
639
+ env: gitEnv(),
640
+ maxBuffer: 1 << 26,
641
+ });
642
+ return {
643
+ ok: !result.error && result.status === 0,
644
+ stdout: result.stdout ?? "",
645
+ stderr: result.error?.message ?? result.stderr ?? "",
646
+ };
647
+ }
648
+ function treeEntry(root, rev, file) {
649
+ const result = cleanupRead(root, ["ls-tree", "-z", rev, "--", file]);
650
+ if (!result.ok)
651
+ throw new Error(`cannot inspect ${rev}:${file}: ${result.stderr}`);
652
+ return result.stdout === "" ? null : result.stdout.slice(0, result.stdout.indexOf("\t"));
653
+ }
654
+ function committedLines(root, rev, file) {
655
+ if (treeEntry(root, rev, file) === null)
656
+ return [];
657
+ const result = cleanupRead(root, ["show", `${rev}:${file}`]);
658
+ if (!result.ok)
659
+ throw new Error(`cannot read ${rev}:${file}: ${result.stderr}`);
660
+ return result.stdout.split("\n").filter(Boolean);
661
+ }
662
+ /** Branch changes absent from dev, including deletions and tree-entry mode/type. */
663
+ export function notOnDev(root, branch) {
664
+ const base = git(root, ["merge-base", ORIGIN_DEV, branch]);
665
+ if (base === null)
666
+ return [`${branch}: no common history with ${ORIGIN_DEV}`];
667
+ const changed = cleanupRead(root, ["diff", "--name-only", "-z", "--no-renames", base, branch]);
668
+ if (!changed.ok)
669
+ return [`cannot inspect ${branch}: ${changed.stderr}`];
670
+ try {
671
+ return changed.stdout
672
+ .split("\0")
673
+ .filter((file) => file !== "" && file !== "docs/roadmap.md")
674
+ .filter((file) => {
675
+ const feature = treeEntry(root, branch, file);
676
+ const dev = treeEntry(root, ORIGIN_DEV, file);
677
+ if (feature === dev)
678
+ return false;
679
+ if (feature === null ||
680
+ dev === null ||
681
+ !file.endsWith(".jsonl") ||
682
+ !/^100(?:644|755) blob /.test(feature) ||
683
+ feature.split(" ").slice(0, 2).join(" ") !== dev.split(" ").slice(0, 2).join(" "))
684
+ return true;
685
+ const before = new Set(committedLines(root, base, file));
686
+ const onDev = new Set(committedLines(root, ORIGIN_DEV, file));
687
+ return committedLines(root, branch, file).some((line) => !before.has(line) && !onDev.has(line));
688
+ });
689
+ }
690
+ catch (error) {
691
+ return [error.message];
692
+ }
693
+ }
694
+ /** Uncommitted files whose index or working contents are not already safely on dev. */
695
+ function dirtyWork(root, wt, landed) {
696
+ const status = cleanupRead(wt, [
697
+ "status",
698
+ "--porcelain=v1",
699
+ "-z",
700
+ "--untracked-files=all",
701
+ "--",
702
+ ".",
703
+ ...copyExcludes(wt),
704
+ ]);
705
+ if (!status.ok)
706
+ return [`cannot inspect dirty work: ${status.stderr}`];
707
+ const entries = status.stdout.split("\0").filter(Boolean);
708
+ const paths = [];
709
+ const staged = new Set();
710
+ for (let i = 0; i < entries.length; i++) {
711
+ const row = entries[i];
712
+ const changed = [row.slice(3)];
713
+ if (/[RC]/.test(row.slice(0, 2)))
714
+ changed.push(entries[++i]);
715
+ paths.push(...changed);
716
+ if (row[0] !== " " && row[0] !== "?") {
717
+ for (const file of changed)
718
+ staged.add(file);
719
+ }
720
+ }
721
+ if (!landed)
722
+ return paths;
723
+ return paths.filter((file) => {
724
+ try {
725
+ if (staged.has(file) &&
726
+ !cleanupRead(wt, ["diff", "--cached", "--quiet", ORIGIN_DEV, "--", file]).ok)
727
+ return true;
728
+ const entry = treeEntry(root, ORIGIN_DEV, file);
729
+ const full = path.join(wt, file);
730
+ const stat = fs.lstatSync(full, { throwIfNoEntry: false });
731
+ if (stat === undefined)
732
+ return entry !== null;
733
+ if (entry === null || (!stat.isFile() && !stat.isSymbolicLink()))
734
+ return true;
735
+ const mode = stat.isSymbolicLink()
736
+ ? "120000"
737
+ : (stat.mode & 0o111) !== 0
738
+ ? "100755"
739
+ : "100644";
740
+ if (!entry.startsWith(`${mode} blob `))
741
+ return true;
742
+ const bytes = stat.isSymbolicLink()
743
+ ? Buffer.from(fs.readlinkSync(full))
744
+ : fs.readFileSync(full);
745
+ const hash = spawnSync("git", ["hash-object", "--stdin"], {
746
+ cwd: root,
747
+ input: bytes,
748
+ encoding: "utf-8",
749
+ env: gitEnv(),
750
+ });
751
+ if (hash.status !== 0)
752
+ return true;
753
+ if (entry.endsWith(` ${hash.stdout.trim()}`))
754
+ return false;
755
+ if (!file.endsWith(".jsonl"))
756
+ return true;
757
+ const onDev = new Set(committedLines(root, ORIGIN_DEV, file));
758
+ return bytes
759
+ .toString("utf-8")
760
+ .split("\n")
761
+ .filter(Boolean)
762
+ .some((line) => !onDev.has(line));
763
+ }
764
+ catch {
765
+ return true;
766
+ }
767
+ });
768
+ }
530
769
  /** The worktree (main checkout included) with `branch` checked out, else null. */
531
770
  export function worktreeHolding(root, branch) {
532
- const list = git(root, ["worktree", "list", "--porcelain"]) ?? "";
771
+ const result = cleanupRead(root, ["worktree", "list", "--porcelain"]);
772
+ if (!result.ok)
773
+ throw new CommandError(EXIT_REMOVE, `cannot inspect worktrees holding ${branch}: ${result.stderr}`);
774
+ const list = result.stdout;
533
775
  let current = null;
534
776
  for (const line of list.split("\n")) {
535
777
  if (line.startsWith("worktree "))
@@ -540,63 +782,127 @@ export function worktreeHolding(root, branch) {
540
782
  return null;
541
783
  }
542
784
  /**
543
- * Delete `branch` locally and on origin. A worktree still holding it blocks
544
- * both deletes: the local one would fail, and the remote one would strand that
545
- * worktree's branch without its upstream.
785
+ * Delete the proved local tip atomically, then the proved remote tip. A worktree
786
+ * still holding the branch blocks both. The remote delete carries a lease on its
787
+ * proved tip, so origin refuses it when someone pushed after the proof.
546
788
  */
547
- function deleteBranch(root, branch, log) {
789
+ function deleteBranch(root, branch, log, expected, remoteExpected) {
548
790
  const holder = worktreeHolding(root, branch);
549
791
  if (holder !== null) {
550
792
  log(`${branch} is checked out in ${holder} (not a workflow worktree) — local and remote branch left in place`);
551
793
  return { branchDeleted: false, remoteDeleted: false, branchBlockedBy: holder };
552
794
  }
553
- if (hasLocal(root, branch)) {
554
- const del = runGit(root, ["branch", "-D", branch]);
555
- if (!del.ok)
556
- log(`git branch -D ${branch} failed: ${del.stderr}`);
795
+ const del = runGit(root, ["update-ref", "-d", `refs/heads/${branch}`, expected]);
796
+ if (!del.ok)
797
+ log(`local ${branch} changed after its cleanup proof — preserved: ${del.stderr}`);
798
+ let remoteDeleted = false;
799
+ if (del.ok && remoteExpected !== null) {
800
+ const ref = `refs/heads/${branch}`;
801
+ const remote = runGit(root, [
802
+ "push",
803
+ `--force-with-lease=${ref}:${remoteExpected}`,
804
+ "origin",
805
+ `:${ref}`,
806
+ ]);
807
+ remoteDeleted = remote.ok;
808
+ if (!remote.ok)
809
+ log(`remote origin/${branch} not deleted — preserved: ${remote.stderr}`);
557
810
  }
558
- const remote = runGit(root, ["push", "origin", "--delete", branch]);
559
- if (!remote.ok)
560
- log(`git push origin --delete ${branch} failed or it was already gone`);
561
- runGit(root, ["fetch", "--prune", "origin"]);
562
811
  return {
563
- branchDeleted: !hasLocal(root, branch),
564
- remoteDeleted: remote.ok,
565
- branchBlockedBy: null,
812
+ branchDeleted: del.ok,
813
+ remoteDeleted,
814
+ branchBlockedBy: del.ok ? null : "changed-after-proof",
566
815
  };
567
816
  }
568
817
  /**
569
818
  * Remove `.worktrees/{fid}` when a workflow created it (the ownership marker),
570
- * prune stale entries, then delete `branch` locally and on origin unless another
571
- * worktree holds it. Throws EXIT_REMOVE when `git worktree remove` fails.
819
+ * preserve unlanded or dirty work, then delete the proved local and remote branch
820
+ * tips unless another worktree holds the branch. Throws EXIT_REMOVE
821
+ * when `git worktree remove` fails.
572
822
  */
573
- export function removeWorktree(cwd, fid, branch, log) {
823
+ export function removeWorktree(cwd, fid, branch, log, options = {}) {
574
824
  if (branch !== undefined && isSharedBranch(branch)) {
575
825
  throw new CommandError(EXIT.USAGE, `refusing to delete branch ${branch}`);
576
826
  }
577
827
  const root = repoRoot(cwd);
578
828
  const wt = worktreeDir(root, fid);
579
829
  const marker = ownershipMarker(root, fid);
580
- const result = (removed, reason) => {
581
- const cleanup = branch === undefined ? null : deleteBranch(root, branch, log);
830
+ let expected = null;
831
+ let remoteExpected = null;
832
+ const result = (removed, reason, removeBranch = false) => {
833
+ const cleanup = branch === undefined || !removeBranch || expected === null
834
+ ? null
835
+ : deleteBranch(root, branch, log, expected, remoteExpected);
582
836
  return {
583
837
  removed,
584
838
  reason,
585
839
  worktreePath: wt,
586
840
  repoRoot: root,
587
- branchDeleted: cleanup?.branchDeleted ?? null,
588
- remoteDeleted: cleanup?.remoteDeleted ?? null,
589
- branchBlockedBy: cleanup?.branchBlockedBy ?? null,
841
+ branchDeleted: cleanup?.branchDeleted ?? (branch === undefined ? null : false),
842
+ remoteDeleted: cleanup?.remoteDeleted ?? (branch === undefined ? null : false),
843
+ branchBlockedBy: cleanup?.branchBlockedBy ?? (branch === undefined ? null : worktreeHolding(root, branch)),
590
844
  };
591
845
  };
592
- if (!fs.existsSync(wt)) {
593
- runGit(root, ["worktree", "prune"]);
594
- return result(false, "absent");
595
- }
596
- if (!fs.existsSync(marker)) {
846
+ if (fs.existsSync(wt) && !fs.existsSync(marker)) {
597
847
  log(`${wt} exists but has no ownership marker (${marker}) — not ours, left in place`);
848
+ if (branch !== undefined)
849
+ log(`${branch} is checked out in ${worktreeHolding(root, branch) ?? wt} — local and remote branch left in place`);
598
850
  return result(false, "not-owned");
599
851
  }
852
+ if (branch !== undefined) {
853
+ const holder = worktreeHolding(root, branch);
854
+ if (holder !== null && real(holder) !== real(wt)) {
855
+ log(`${branch} is checked out in ${holder} — local and remote branch left in place`);
856
+ return result(false, fs.existsSync(wt) ? "held-elsewhere" : "absent");
857
+ }
858
+ try {
859
+ fetchBranch(root, DEV);
860
+ expected = git(root, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}^{commit}`]);
861
+ if (expected === null) {
862
+ log(`cannot read local ${branch}; cleanup evidence unavailable — preserved`);
863
+ return result(false, "unavailable");
864
+ }
865
+ const missing = notOnDev(root, expected);
866
+ if (missing.length > 0) {
867
+ log(`${branch} carries work ${ORIGIN_DEV} does not — preserved: ${missing.join(", ")}`);
868
+ return result(false, "not-landed");
869
+ }
870
+ const remote = remoteHas(root, branch);
871
+ if (remote === "error") {
872
+ log(`cannot read remote origin/${branch}; cleanup evidence unavailable — preserved`);
873
+ return result(false, "unavailable");
874
+ }
875
+ if (remote === "yes") {
876
+ fetchBranch(root, branch);
877
+ const remoteMissing = notOnDev(root, `refs/remotes/origin/${branch}`);
878
+ if (remoteMissing.length > 0) {
879
+ log(`remote origin/${branch} holds unlanded work — local worktree and remote branch preserved: ${remoteMissing.join(", ")}`);
880
+ return result(false, "remote-not-landed");
881
+ }
882
+ remoteExpected = git(root, [
883
+ "rev-parse",
884
+ "--verify",
885
+ "--quiet",
886
+ `refs/remotes/origin/${branch}^{commit}`,
887
+ ]);
888
+ }
889
+ }
890
+ catch (error) {
891
+ log(`cleanup evidence unavailable — preserved: ${error.message}`);
892
+ return result(false, "unavailable");
893
+ }
894
+ }
895
+ if (fs.existsSync(wt)) {
896
+ const dirty = dirtyWork(root, wt, options.landed === true);
897
+ if (dirty.length > 0) {
898
+ log(`${wt} holds uncommitted work — preserved: ${dirty.join(", ")}`);
899
+ return result(false, "uncommitted");
900
+ }
901
+ }
902
+ if (!fs.existsSync(wt)) {
903
+ runGit(root, ["worktree", "prune"]);
904
+ return result(false, "absent", true);
905
+ }
600
906
  const inside = !path.relative(real(wt), real(cwd)).startsWith("..");
601
907
  const res = runGit(root, ["worktree", "remove", "--force", wt]);
602
908
  if (!res.ok)
@@ -605,7 +911,7 @@ export function removeWorktree(cwd, fid, branch, log) {
605
911
  fs.rmSync(marker, { force: true });
606
912
  if (inside)
607
913
  log(`the working directory was inside ${wt} — cd to ${root}`);
608
- return result(true, null);
914
+ return result(true, null, true);
609
915
  }
610
916
  // ---------------------------------------------------------------------------
611
917
  // Command
@@ -723,6 +1029,18 @@ export const worktreesCommand = {
723
1029
  ? `refusing to ship ${target}: /bkit-ship ships a feature branch into ${DEV} only; it never opens a PR from ${DEV} into ${MAIN} or merges into ${MAIN}, releases stay manual. Name the feature branch to ship.`
724
1030
  : `refusing to ship ${target} as a feature branch`);
725
1031
  }
1032
+ if (workflow === "ship" && git(root, ["remote", "get-url", "origin"]) !== null) {
1033
+ fetchBranch(root, DEV);
1034
+ const remote = remoteHas(root, target);
1035
+ if (remote === "error")
1036
+ throw new CommandError(EXIT_FETCH, `cannot fetch origin ${target}: remote branch evidence unavailable`);
1037
+ if (remote === "yes") {
1038
+ fetchBranch(root, target);
1039
+ assertShipEligible(root, `refs/remotes/origin/${target}`);
1040
+ }
1041
+ if (hasLocal(root, target))
1042
+ assertShipEligible(root, `refs/heads/${target}`);
1043
+ }
726
1044
  if (workflow === "debug" &&
727
1045
  named &&
728
1046
  !hasLocal(root, target) &&
@@ -775,7 +1093,9 @@ export const worktreesCommand = {
775
1093
  throw new CommandError(EXIT_REFUSED, `adopt mode: checkout does not hold requested ${target}; use its existing checkout or enable worktrees`);
776
1094
  }
777
1095
  if (workflow === "ship" && git(root, ["branch", "--show-current"]) !== target) {
778
- const sw = runGit(root, ["switch", target]);
1096
+ const sw = runGit(root, hasLocal(root, target)
1097
+ ? ["switch", target]
1098
+ : ["switch", "--no-track", "-c", target, `refs/remotes/origin/${target}`]);
779
1099
  if (!sw.ok) {
780
1100
  if (!hasLocal(root, target) && remoteHas(root, target) !== "yes") {
781
1101
  throw new CommandError(EXIT_REFUSED, `${target} does not exist — name the feature branch to ship`);
@@ -822,6 +1142,9 @@ export const worktreesCommand = {
822
1142
  onto: worktreeBase(wt, workflow),
823
1143
  };
824
1144
  }
1145
+ else if (workflow === "debug") {
1146
+ ctx.log("debug resume: preserving branch history for CI evidence; no rebase");
1147
+ }
825
1148
  else {
826
1149
  fetchBranch(wt, DEV);
827
1150
  const onto = worktreeBase(wt, workflow, ctx.log);
@@ -854,8 +1177,14 @@ export const worktreesCommand = {
854
1177
  }
855
1178
  }
856
1179
  if (failure) {
857
- fs.mkdirSync(logDir, { recursive: true });
858
- fs.appendFileSync(path.join(logDir, "rebase-resolve-log.md"), `[bkit-worktrees] ${new Date().toISOString()} rebase onto ${failure.onto} stopped\n${failure.detail}\n`);
1180
+ const note = `[bkit-worktrees] ${new Date().toISOString()} rebase onto ${failure.onto} stopped\n${failure.detail}\n`;
1181
+ const held = rebaseInProgress(wt) ? rebaseNoteFile(wt) : null;
1182
+ if (held !== null)
1183
+ fs.appendFileSync(held, note);
1184
+ else {
1185
+ fs.mkdirSync(logDir, { recursive: true });
1186
+ fs.appendFileSync(path.join(logDir, "rebase-resolve-log.md"), note);
1187
+ }
859
1188
  fs.writeFileSync(sentinelPath, "");
860
1189
  ctx.log(`rebase onto ${failure.onto} failed in ${wt}: ${failure.detail.split("\n")[0]}`);
861
1190
  rebaseConflict = failure.conflict;
@@ -919,24 +1248,24 @@ export const worktreesCommand = {
919
1248
  },
920
1249
  },
921
1250
  remove: {
922
- summary: "Remove .worktrees/{fid} when a workflow created it, prune stale entries, and delete the feature branch.",
1251
+ summary: "Remove a workflow-owned worktree when its work is safely on dev; conditionally delete its local and remote branch at their proved landed tips.",
923
1252
  use: "workflow",
924
1253
  flags: [
925
1254
  FID_FLAG,
926
1255
  {
927
1256
  name: "branch",
928
1257
  type: "string",
929
- help: "feature branch to delete locally and on origin once the worktree is gone; skipped when another worktree still holds it",
1258
+ help: "feature branch to delete locally and on origin only at its proved landed tips; preserve unlanded/uncertain work",
930
1259
  },
931
1260
  ],
932
1261
  output: {
933
1262
  removed: "the worktree was removed",
934
- reason: "why it was not: absent | not-owned (no .worktree-owned marker); null when removed",
1263
+ reason: "why it was not removed: absent | not-owned | held-elsewhere | uncommitted | not-landed | remote-not-landed | unavailable; null when removed",
935
1264
  worktreePath: "the worktree's path",
936
1265
  repoRoot: "the main checkout — cd here if the shell was inside the removed worktree",
937
- branchDeleted: "--branch: the local branch is gone (deleted or already absent); null without --branch",
938
- remoteDeleted: "--branch: git push origin --delete succeeded; false when it failed or was already gone; null without --branch",
939
- branchBlockedBy: "--branch: the worktree still holding the branch, so neither the local nor the remote branch was deleted; null when none",
1266
+ branchDeleted: "--branch: the proved local tip was atomically deleted; false when preserved or unavailable, null without --branch",
1267
+ remoteDeleted: "--branch: the remote branch was deleted at its proved landed tip; false when absent, refused or changed, null without --branch",
1268
+ branchBlockedBy: "--branch: the worktree still holding the branch or changed-after-proof; null when none",
940
1269
  },
941
1270
  exitCodes: { [EXIT_REMOVE]: "git worktree remove failed" },
942
1271
  run: (ctx) => {