@cbartens/bkit 5.2.4 → 5.4.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 (271) hide show
  1. package/.bkit/README.md +27 -11
  2. package/.bkit/core/.agents/context.md +1 -1
  3. package/.bkit/core/.agents/docs.md +1 -1
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +1 -1
  5. package/.bkit/core/.agents/rules.md +18 -1
  6. package/.bkit/core/.bkit/README.md +26 -10
  7. package/.bkit/core/.bkit/cloud.md +40 -39
  8. package/.bkit/core/.bkit/comparison.md +68 -345
  9. package/.bkit/core/.bkit/install.md +16 -9
  10. package/.bkit/core/.bkit/lite.md +73 -0
  11. package/.bkit/core/.bkit/pipeline.md +346 -0
  12. package/.bkit/core/.bkit/prompts.md +90 -74
  13. package/.bkit/core/.bkit/providers.md +42 -23
  14. package/.bkit/core/.bkit/templates.md +138 -19
  15. package/.bkit/core/.bkit/trackers.md +49 -4
  16. package/.bkit/core/.bkit/workflows.md +144 -123
  17. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +1 -1
  18. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +7 -4
  19. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +8 -5
  20. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +3 -2
  21. package/.bkit/core/docs/templates/bkit-audit-adoption.md +2 -2
  22. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  23. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  24. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  25. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  26. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +1 -1
  27. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  28. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  29. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +4 -2
  30. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  31. package/.bkit/core/docs/templates/bkit-audit-cost.md +3 -2
  32. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  33. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -2
  34. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +5 -5
  35. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  36. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +26 -21
  37. package/.bkit/core/docs/templates/bkit-audit-documentation.md +1 -1
  38. package/.bkit/core/docs/templates/bkit-audit-duplication.md +2 -2
  39. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  40. package/.bkit/core/docs/templates/bkit-audit-flakes.md +3 -2
  41. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -2
  42. package/.bkit/core/docs/templates/bkit-audit-issues.md +3 -2
  43. package/.bkit/core/docs/templates/bkit-audit-llm.md +22 -15
  44. package/.bkit/core/docs/templates/bkit-audit-logs.md +10 -6
  45. package/.bkit/core/docs/templates/bkit-audit-models.md +1 -1
  46. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  47. package/.bkit/core/docs/templates/bkit-audit-prompts.md +7 -7
  48. package/.bkit/core/docs/templates/bkit-audit-red-team.md +12 -9
  49. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  50. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  51. package/.bkit/core/docs/templates/bkit-audit-security.md +14 -12
  52. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  53. package/.bkit/core/docs/templates/bkit-audit-testing.md +10 -8
  54. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  55. package/.bkit/core/docs/templates/bkit-plan.md +8 -6
  56. package/.bkit/core/engine/checks/after/auth.ts +9 -9
  57. package/.bkit/core/engine/checks/after/ci-yml.ts +14 -12
  58. package/.bkit/core/engine/checks/after/github.ts +29 -120
  59. package/.bkit/core/engine/checks/after/index.ts +2 -2
  60. package/.bkit/core/engine/checks/after/managed.ts +8 -28
  61. package/.bkit/core/engine/checks/after/tools.ts +3 -15
  62. package/.bkit/core/engine/checks/before/context-fetch.ts +1 -21
  63. package/.bkit/core/engine/checks/before/index.ts +7 -43
  64. package/.bkit/core/engine/checks/before/mcp.ts +17 -8
  65. package/.bkit/core/engine/checks/before/repo.ts +9 -12
  66. package/.bkit/core/engine/checks/status-holes.ts +4 -6
  67. package/.bkit/core/engine/checks/tips/catalogue.ts +76 -24
  68. package/.bkit/core/engine/checks/tips/detect.ts +45 -2
  69. package/.bkit/core/engine/checks/tips/index.ts +77 -26
  70. package/.bkit/core/engine/cli.ts +57 -27
  71. package/.bkit/core/engine/commands/analysis.ts +36 -26
  72. package/.bkit/core/engine/commands/comply.ts +42 -32
  73. package/.bkit/core/engine/commands/harvest.ts +12 -12
  74. package/.bkit/core/engine/commands/install/doctor.ts +57 -28
  75. package/.bkit/core/engine/commands/install/install.ts +73 -130
  76. package/.bkit/core/engine/commands/install/uninstall.ts +191 -33
  77. package/.bkit/core/engine/commands/install/upgrade.ts +49 -43
  78. package/.bkit/core/engine/commands/land.ts +156 -0
  79. package/.bkit/core/engine/commands/lib.ts +45 -18
  80. package/.bkit/core/engine/commands/registry.ts +2 -0
  81. package/.bkit/core/engine/commands/tips.ts +12 -5
  82. package/.bkit/core/engine/commands/workflow/branches.ts +386 -286
  83. package/.bkit/core/engine/commands/workflow/counters.ts +21 -12
  84. package/.bkit/core/engine/commands/workflow/disk.ts +556 -0
  85. package/.bkit/core/engine/commands/workflow/fids.ts +46 -0
  86. package/.bkit/core/engine/commands/workflow/issues.ts +73 -28
  87. package/.bkit/core/engine/commands/workflow/ledgers.ts +3 -1
  88. package/.bkit/core/engine/commands/workflow/locks.ts +38 -152
  89. package/.bkit/core/engine/commands/workflow/prs.ts +15 -4
  90. package/.bkit/core/engine/commands/workflow/repo.ts +2 -2
  91. package/.bkit/core/engine/commands/workflow/roadmap.ts +49 -53
  92. package/.bkit/core/engine/commands/workflow/runs.ts +8 -7
  93. package/.bkit/core/engine/commands/workflow/runtime.ts +3 -2
  94. package/.bkit/core/engine/commands/workflow/status.ts +33 -11
  95. package/.bkit/core/engine/commands/workflow/steps.ts +25 -15
  96. package/.bkit/core/engine/commands/workflow/tests.ts +17 -5
  97. package/.bkit/core/engine/commands/workflow/workflows.ts +436 -267
  98. package/.bkit/core/engine/commands/workflow/workstreams.ts +4 -2
  99. package/.bkit/core/engine/commands/workflow/worktrees.ts +24 -6
  100. package/.bkit/core/engine/install/cloud-env.ts +10 -31
  101. package/.bkit/core/engine/install/manifest.ts +14 -7
  102. package/.bkit/core/engine/install/modules/antigravity.ts +15 -26
  103. package/.bkit/core/engine/install/modules/claude.ts +20 -28
  104. package/.bkit/core/engine/install/modules/cloud.ts +5 -2
  105. package/.bkit/core/engine/install/modules/codex.ts +15 -29
  106. package/.bkit/core/engine/install/modules/core.ts +106 -70
  107. package/.bkit/core/engine/install/modules/cursor.ts +6 -20
  108. package/.bkit/core/engine/install/modules/index.ts +7 -1
  109. package/.bkit/core/engine/install/modules/opencode.ts +48 -70
  110. package/.bkit/core/engine/install/network-allowlist.ts +73 -0
  111. package/.bkit/core/engine/install/placeholders.ts +16 -35
  112. package/.bkit/core/engine/install/write.ts +59 -12
  113. package/.bkit/core/engine/ledgers/telemetry.ts +6 -4
  114. package/.bkit/core/engine/render/hosts.ts +47 -67
  115. package/.bkit/core/engine/render/models.ts +29 -11
  116. package/.bkit/core/engine/shared/branches.ts +13 -0
  117. package/.bkit/core/engine/shared/egress.ts +3 -3
  118. package/.bkit/core/engine/shared/json.ts +18 -1
  119. package/.bkit/core/engine/shared/package-json.ts +63 -0
  120. package/.bkit/core/engine/shared/package-roots.ts +0 -10
  121. package/.bkit/core/engine/shared/protected-paths.ts +5 -130
  122. package/.bkit/core/engine/shared/settings.ts +44 -0
  123. package/.bkit/core/engine/shared/timeouts.ts +8 -7
  124. package/.bkit/core/hooks/antigravity-hook.js +1 -0
  125. package/.bkit/core/hooks/guardrails-shell.js +186 -40
  126. package/.bkit/core/hooks/guardrails-tiers.js +5 -78
  127. package/.bkit/core/prompts/bkit-audit-generate.md +103 -7
  128. package/.bkit/core/prompts/bkit-build-challenge-1.md +1 -1
  129. package/.bkit/core/prompts/bkit-build-challenge-2.md +1 -1
  130. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +1 -1
  131. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +1 -1
  132. package/.bkit/core/prompts/bkit-build-challenge-tests.md +1 -1
  133. package/.bkit/core/prompts/bkit-build-install-skills.md +1 -1
  134. package/.bkit/core/prompts/bkit-build-plan-current.md +1 -1
  135. package/.bkit/core/prompts/bkit-build-plan-execute.md +4 -4
  136. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +1 -1
  137. package/.bkit/core/prompts/bkit-build-plan-verify.md +2 -2
  138. package/.bkit/core/prompts/bkit-debug-abort-handover.md +1 -1
  139. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +1 -1
  140. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +1 -1
  141. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +78 -0
  142. package/.bkit/core/prompts/bkit-debug-failure-soak.md +1 -1
  143. package/.bkit/core/prompts/bkit-debug-summary.md +3 -3
  144. package/.bkit/core/prompts/bkit-design-spike.md +1 -1
  145. package/.bkit/core/prompts/bkit-design-summary.md +2 -2
  146. package/.bkit/core/prompts/bkit-design-update.md +1 -1
  147. package/.bkit/core/prompts/bkit-plan-complexity-check.md +1 -1
  148. package/.bkit/core/prompts/bkit-plan-generate.md +1 -1
  149. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +1 -1
  150. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +1 -1
  151. package/.bkit/core/prompts/bkit-plan-summary.md +1 -1
  152. package/.bkit/core/prompts/bkit-plan-update.md +1 -1
  153. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +1 -1
  154. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +1 -1
  155. package/.bkit/core/prompts/bkit-ship-update-docs.md +1 -1
  156. package/.bkit/core/prompts/bkit-utility-update-decisions.md +9 -2
  157. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +9 -2
  158. package/.bkit/core/prompts/bkit-utility-update-documentation.md +2 -1
  159. package/.bkit/core/prompts/bkit-utility-update-failures.md +9 -2
  160. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +9 -2
  161. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +11 -4
  162. package/.bkit/core/workflows/bkit-auto.md +2 -2
  163. package/.bkit/core/workflows/bkit-build.md +10 -10
  164. package/.bkit/core/workflows/bkit-debug.md +80 -44
  165. package/.bkit/core/workflows/bkit-design.md +22 -13
  166. package/.bkit/core/workflows/bkit-plan.md +33 -16
  167. package/.bkit/core/workflows/bkit-ship.md +87 -98
  168. package/.bkit/shared/.claude/bkit-cloud.md +58 -25
  169. package/.bkit/shared/.claude/settings.json +19 -0
  170. package/.bkit/shared/.cursor/mcp.json +2 -1
  171. package/.bkit/shared/.opencode/opencode.json +19 -1
  172. package/.bkit/shared/docs/deployments.md +49 -29
  173. package/.bkit/shared/docs/security.md +8 -6
  174. package/.bkit/shared/docs/testing.md +9 -5
  175. package/.bkit/shared/gitignore +1 -2
  176. package/.bkit/templates/.cursor/Dockerfile +30 -16
  177. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-bug.yml +78 -0
  178. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +91 -0
  179. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +56 -0
  180. package/.bkit/templates/.github/renovate.json5 +91 -12
  181. package/.bkit/templates/.github/workflows/bkit-ci.yml +73 -55
  182. package/.bkit/templates/.github/workflows/bkit-cloud.yml +3 -1
  183. package/.bkit/templates/.github/workflows/bkit-renovate.yml +8 -1
  184. package/.bkit/templates/.github/workflows/bkit-trivy.yml +67 -0
  185. package/.bkit/templates/.husky/pre-commit +6 -0
  186. package/.bkit/templates/.husky/pre-push +15 -3
  187. package/.bkit/templates/.lintstagedrc.json +5 -1
  188. package/.bkit/templates/.oxlintrc.json +21 -0
  189. package/.bkit/templates/docs/capabilities.md +1 -1
  190. package/.bkit/templates/scripts/ci/check-capstone.mjs +176 -0
  191. package/.bkit/templates/scripts/ci/check-capstone.test.mjs +311 -0
  192. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.machine.mjs +197 -0
  193. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +164 -0
  194. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +2 -2
  195. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +43 -20
  196. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +33 -11
  197. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +3 -2
  198. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +5 -5
  199. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +79 -19
  200. package/CHANGELOG.md +98 -3
  201. package/README.md +252 -122
  202. package/dist/checks/after/auth.js +10 -11
  203. package/dist/checks/after/ci-yml.js +11 -14
  204. package/dist/checks/after/github.js +32 -125
  205. package/dist/checks/after/index.js +3 -2
  206. package/dist/checks/after/managed.js +8 -24
  207. package/dist/checks/after/tools.js +3 -16
  208. package/dist/checks/before/context-fetch.js +1 -21
  209. package/dist/checks/before/index.js +6 -42
  210. package/dist/checks/before/mcp.js +14 -9
  211. package/dist/checks/before/repo.js +8 -11
  212. package/dist/checks/status-holes.js +5 -7
  213. package/dist/checks/tips/catalogue.js +65 -18
  214. package/dist/checks/tips/detect.js +41 -2
  215. package/dist/checks/tips/index.js +61 -25
  216. package/dist/cli.js +52 -26
  217. package/dist/commands/analysis.js +21 -5
  218. package/dist/commands/comply.js +40 -31
  219. package/dist/commands/harvest.js +12 -13
  220. package/dist/commands/install/doctor.js +55 -23
  221. package/dist/commands/install/install.js +72 -122
  222. package/dist/commands/install/uninstall.js +165 -31
  223. package/dist/commands/install/upgrade.js +46 -39
  224. package/dist/commands/land.js +129 -0
  225. package/dist/commands/lib.js +41 -16
  226. package/dist/commands/registry.js +2 -0
  227. package/dist/commands/tips.js +10 -3
  228. package/dist/commands/workflow/branches.js +303 -248
  229. package/dist/commands/workflow/counters.js +17 -7
  230. package/dist/commands/workflow/disk.js +452 -0
  231. package/dist/commands/workflow/fids.js +39 -0
  232. package/dist/commands/workflow/issues.js +63 -27
  233. package/dist/commands/workflow/ledgers.js +3 -1
  234. package/dist/commands/workflow/locks.js +35 -130
  235. package/dist/commands/workflow/prs.js +8 -5
  236. package/dist/commands/workflow/repo.js +2 -2
  237. package/dist/commands/workflow/roadmap.js +50 -57
  238. package/dist/commands/workflow/runs.js +5 -5
  239. package/dist/commands/workflow/runtime.js +3 -2
  240. package/dist/commands/workflow/status.js +32 -12
  241. package/dist/commands/workflow/steps.js +19 -11
  242. package/dist/commands/workflow/tests.js +16 -3
  243. package/dist/commands/workflow/workflows.js +390 -249
  244. package/dist/commands/workflow/workstreams.js +4 -2
  245. package/dist/commands/workflow/worktrees.js +15 -6
  246. package/dist/install/cloud-env.js +10 -23
  247. package/dist/install/manifest.js +14 -7
  248. package/dist/install/modules/antigravity.js +15 -26
  249. package/dist/install/modules/claude.js +17 -21
  250. package/dist/install/modules/cloud.js +6 -2
  251. package/dist/install/modules/codex.js +15 -29
  252. package/dist/install/modules/core.js +95 -63
  253. package/dist/install/modules/cursor.js +6 -9
  254. package/dist/install/modules/index.js +6 -1
  255. package/dist/install/modules/opencode.js +41 -72
  256. package/dist/install/network-allowlist.js +62 -0
  257. package/dist/install/placeholders.js +16 -35
  258. package/dist/install/write.js +55 -15
  259. package/dist/ledgers/telemetry.js +5 -4
  260. package/dist/render/hosts.js +30 -55
  261. package/dist/render/models.js +20 -9
  262. package/dist/shared/branches.js +11 -0
  263. package/dist/shared/egress.js +0 -2
  264. package/dist/shared/json.js +14 -0
  265. package/dist/shared/package-json.js +61 -0
  266. package/dist/shared/package-roots.js +0 -8
  267. package/dist/shared/protected-paths.js +5 -122
  268. package/dist/shared/settings.js +23 -1
  269. package/dist/shared/timeouts.js +8 -7
  270. package/package.json +21 -17
  271. package/.bkit/core/.agents/shortcuts.md +0 -73
@@ -12,8 +12,8 @@
12
12
  // ship's one-commit flush (`--flush`), and print the handover comment.
13
13
  // close grade compliance, then the `workflow-done` row, the run's counter and
14
14
  // outcome rows in `.bkit/stats.jsonl`, this workflow's telemetry report
15
- // and the artifact links. `--flush` is ship's close: under the dev lock,
16
- // on dev or a detached origin/dev worktree, commit and land it.
15
+ // and the artifact links. `--flush` is ship's close: land it on dev
16
+ // through a throwaway origin/dev checkout, then remove the worktree.
17
17
  // promote design / plan close: the highest versioned draft becomes the
18
18
  // canonical doc (anchor stamped, a superseded canonical archived).
19
19
  // links the feature docs and this workflow's logs on a ref, as markdown links.
@@ -38,12 +38,14 @@ import {
38
38
  type CoverageStats,
39
39
  } from "../../ledgers/telemetry.js";
40
40
  import { readBkitVersion } from "../../install/version-file.js";
41
- import { TIMEOUTS } from "../../shared/timeouts.js";
42
41
  import { gradeCompliance } from "../comply.js";
42
+ import { landDir, pushToDev, type DevPush } from "../land.js";
43
43
  import {
44
44
  CommandError,
45
+ DEV,
45
46
  EXIT,
46
47
  git,
48
+ isSharedBranch,
47
49
  parseJson,
48
50
  repoRoot,
49
51
  runGh,
@@ -67,9 +69,7 @@ import { EXIT_EMPTY, commitBookkeeping, unionLedgers } from "./ledgers.js";
67
69
  import {
68
70
  EXIT_REMOVE_FAILED,
69
71
  EXIT_SPLIT_BUCKET,
70
- acquireDevLock,
71
72
  acquireWorkflowLock,
72
- lockRoot,
73
73
  owns,
74
74
  readHolder,
75
75
  releaseLock,
@@ -88,14 +88,13 @@ import {
88
88
  str,
89
89
  } from "./status.js";
90
90
  import { writeStepRow } from "./steps.js";
91
+ import { removeWorktree, type RemoveResult } from "./worktrees.js";
91
92
 
92
93
  /** Sentinels a workflow leaves in its logs folder; either one existing means a handover is due. */
93
94
  export const SENTINELS = [".rebase-failed", ".deferred-blocked"] as const;
94
95
 
95
96
  /** Exit code (start --lock-held): the lock is missing or belongs to another owner. */
96
97
  export const EXIT_LOCK_NOT_HELD = 6;
97
- /** Exit code (handover --push): the handover artifact is missing or empty. */
98
- export const EXIT_HANDOVER_MISSING = 8;
99
98
  /** Exit code (handover --push): the branch has an open PR, so nothing was pushed. */
100
99
  export const EXIT_OPEN_PR_KEPT = 9;
101
100
  /** Exit code (handover, close --flush): a push failed. */
@@ -112,7 +111,7 @@ export const EXIT_NO_VERSION = 12;
112
111
  interface Where {
113
112
  root: string;
114
113
  month: string;
115
- /** Tree the run works in: ship's book root, else the current worktree's top. */
114
+ /** Tree the run works in: the current worktree's top. */
116
115
  tree: string;
117
116
  status: string;
118
117
  }
@@ -126,20 +125,14 @@ function workflowName(workflow: string): string {
126
125
  return workflow;
127
126
  }
128
127
 
129
- /**
130
- * start and close work in the current tree (ship: its book root), the root
131
- * `git rev-parse --show-toplevel` reports.
132
- */
128
+ /** start and close work in the current tree, the root `git rev-parse --show-toplevel` reports. */
133
129
  function whereInTree(
134
130
  cwd: string,
135
- o: { workflow: string; fid: string; month?: string; devPushes: boolean; file?: string },
131
+ o: { workflow: string; fid: string; month?: string; file?: string },
136
132
  ): Where {
137
133
  const root = repoRoot(cwd);
138
134
  const month = resolveMonth(root, o.fid, o.month);
139
- const tree =
140
- o.workflow === "ship"
141
- ? lockRoot(cwd, o.workflow, o.devPushes)
142
- : (git(cwd, ["rev-parse", "--show-toplevel"]) ?? root);
135
+ const tree = git(cwd, ["rev-parse", "--show-toplevel"]) ?? root;
143
136
  const status = o.file ? path.resolve(cwd, o.file) : path.join(tree, statusRelPath(month, o.fid));
144
137
  return { root, month, tree, status };
145
138
  }
@@ -180,13 +173,12 @@ function abortRebase(tree: string, log: (m: string) => void): boolean {
180
173
 
181
174
  /** The workflow-failed state: row, rebase abort, lock release, sentinels. */
182
175
  function failState(ctx: RunContext, workflow: string, fid: string) {
183
- const devPushes = ctx.flags.devPushes === true;
184
176
  const root = repoRoot(ctx.cwd);
185
177
  const month = resolveMonth(root, fid, str(ctx.flags.month) || undefined);
186
178
  const file = str(ctx.flags.file) || undefined;
187
179
  const status = file
188
180
  ? path.resolve(ctx.cwd, file)
189
- : statusLocation({ cwd: ctx.cwd, workflow, fid, month, devPushes }).path;
181
+ : statusLocation({ cwd: ctx.cwd, workflow, fid, month }).path;
190
182
 
191
183
  // The run's own tree: the feature worktree when there is one, else this checkout.
192
184
  // Never the main checkout behind a worktree, where a rebase would be a human's.
@@ -209,7 +201,7 @@ function failState(ctx: RunContext, workflow: string, fid: string) {
209
201
  ctx.log(`${status} does not exist — no workflow-failed row written`);
210
202
  }
211
203
 
212
- const lockFile = workflowLockPath(lockRoot(ctx.cwd, workflow, devPushes), month, fid);
204
+ const lockFile = workflowLockPath(root, month, fid);
213
205
  const { removeFailed, ...lock } = releaseLock(lockFile, {
214
206
  workflow,
215
207
  fid,
@@ -220,7 +212,7 @@ function failState(ctx: RunContext, workflow: string, fid: string) {
220
212
  if (removeFailed) ctx.log(`lock removal failed: ${lockFile}`);
221
213
 
222
214
  // Each sentinel is cleared where it was created: `.rebase-failed` in the run's
223
- // tree, `.deferred-blocked` beside status.jsonl (ship: the book root).
215
+ // tree, `.deferred-blocked` beside status.jsonl.
224
216
  const logDirs = new Set([path.join(tree, logDirRel(month, fid)), path.dirname(status)]);
225
217
  const sentinels: Array<{ name: string; path: string }> = [];
226
218
  for (const dir of logDirs) {
@@ -312,101 +304,261 @@ function readText(cwd: string, rel: string): string {
312
304
  // handover
313
305
  // ---------------------------------------------------------------------------
314
306
 
307
+ /** Non-empty lines; a final newline ends the last line rather than starting an empty one. */
308
+ const textLines = (text: string) => text.split("\n").filter((l) => l.trim() !== "");
309
+
310
+ /** `rel` in `tree` differs from its HEAD copy, or is untracked: the run wrote it. */
311
+ const ownWrite = (tree: string, rel: string) =>
312
+ (git(tree, ["status", "--porcelain", "--untracked-files=all", "--", rel]) ?? "") !== "";
313
+
314
+ /** Copy each `.md` log in the run's log folder that dev lacks, or that the run rewrote. */
315
+ function carryLogs(src: string, dst: string, rel: string): string[] {
316
+ if (!fs.existsSync(path.join(src, rel))) return [];
317
+ fs.mkdirSync(path.join(dst, rel), { recursive: true });
318
+ const copied: string[] = [];
319
+ for (const f of fs.readdirSync(path.join(src, rel)).filter((n) => n.endsWith(".md"))) {
320
+ const from = path.join(src, rel, f);
321
+ const to = path.join(dst, rel, f);
322
+ const same = fs.existsSync(to) && fs.readFileSync(to).equals(fs.readFileSync(from));
323
+ if (same || (fs.existsSync(to) && !ownWrite(src, path.join(rel, f)))) continue;
324
+ fs.copyFileSync(from, to);
325
+ copied.push(path.join(rel, f));
326
+ }
327
+ return copied;
328
+ }
329
+
315
330
  /**
316
- * Ship's Failure Path flush: copy branch-side logs and ledger rows into the book
317
- * root, then ONE `chore({fid}): ship FAILED bkit [skip ci]` commit and ONE push —
318
- * to dev under the dev lock when this runtime pushes dev, else the current branch.
331
+ * Carry a run's book (its feature worktree) into a dev checkout: its `.md` logs,
332
+ * and its ledger rows unioned line-wise (both hold rows the other does not).
319
333
  */
320
- async function shipFlush(
321
- ctx: RunContext,
322
- o: { fid: string; month: string; devPushes: boolean; worktree?: string },
323
- ): Promise<{ code: number; pushed: boolean; ref: string | null; skipped: string | null }> {
324
- const root = repoRoot(ctx.cwd);
325
- const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
326
- const bookRoot = o.devPushes ? root : top;
334
+ function carryBook(src: string, dst: string, month: string, fid: string): void {
335
+ carryLogs(src, dst, logDirRel(month, fid));
336
+ unionLedgers(src, dst);
337
+ }
338
+
339
+ /** What a landing carried out of a shared checkout: whole `.md` logs, and ledger lines per file. */
340
+ interface Carried {
341
+ files: string[];
342
+ lines: Map<string, string[]>;
343
+ }
344
+
345
+ /** Shared ledgers a run may append to, outside its own log folder. */
346
+ const SHARED_LEDGERS = [
347
+ ":(glob)docs/*.jsonl",
348
+ ":(glob).bkit/*.jsonl",
349
+ ":(exclude).bkit/issues.jsonl",
350
+ ];
351
+
352
+ /**
353
+ * Carry ONLY the run's own record out of a dev / main / detached checkout, which
354
+ * other sessions and local-only commits share: the `.md` logs it wrote in its log
355
+ * folder; the lines of that folder's `.jsonl` files its HEAD lacks; and, from the
356
+ * shared ledgers, lines its HEAD lacks that are rows of `workflow` at or after
357
+ * the run's start (`startMs`). No start known → no shared-ledger row is carried.
358
+ */
359
+ function carryOwnBook(
360
+ src: string,
361
+ dst: string,
362
+ o: { month: string; fid: string; workflow: string; startMs: number | undefined },
363
+ log: (line: string) => void,
364
+ ): Carried {
327
365
  const rel = logDirRel(o.month, o.fid);
328
- const src = o.worktree ?? path.join(root, ".worktrees", o.fid);
329
- if (fs.existsSync(path.join(src, rel)) && path.resolve(src) !== path.resolve(bookRoot)) {
330
- fs.mkdirSync(path.join(bookRoot, rel), { recursive: true });
331
- for (const f of fs.readdirSync(path.join(src, rel)).filter((n) => n.endsWith(".md"))) {
332
- const to = path.join(bookRoot, rel, f);
333
- if (!fs.existsSync(to)) fs.copyFileSync(path.join(src, rel, f), to);
334
- }
335
- unionLedgers(src, bookRoot);
366
+ const carried: Carried = { files: carryLogs(src, dst, rel), lines: new Map() };
367
+ const uncommitted = (file: string) => {
368
+ const head = new Set(textLines(git(src, ["show", `HEAD:${file}`]) ?? "").map((l) => l.trim()));
369
+ return textLines(fs.readFileSync(path.join(src, file), "utf-8")).filter(
370
+ (l) => !head.has(l.trim()),
371
+ );
372
+ };
373
+ const add = (file: string, lines: string[]) => {
374
+ const to = path.join(dst, file);
375
+ const existing = fs.existsSync(to) ? fs.readFileSync(to, "utf-8") : "";
376
+ const have = new Set(textLines(existing).map((l) => l.trim()));
377
+ const fresh = lines.filter((l) => !have.has(l.trim()));
378
+ if (fresh.length === 0) return;
379
+ fs.mkdirSync(path.dirname(to), { recursive: true });
380
+ const sep = existing !== "" && !existing.endsWith("\n") ? "\n" : "";
381
+ fs.appendFileSync(to, `${sep}${fresh.join("\n")}\n`);
382
+ carried.lines.set(file, fresh);
383
+ };
384
+ const listed = (specs: string[]) =>
385
+ (git(src, ["ls-files", "--cached", "--others", "--exclude-standard", "--", ...specs]) ?? "")
386
+ .split("\n")
387
+ .filter((f) => f !== "" && fs.existsSync(path.join(src, f)));
388
+
389
+ for (const file of listed([`:(glob)${rel}/*.jsonl`])) add(file, uncommitted(file));
390
+ if (o.startMs === undefined) {
391
+ log(`no ${o.workflow} start row for ${o.fid} — no shared-ledger row carried`);
392
+ return carried;
336
393
  }
394
+ for (const file of listed(SHARED_LEDGERS)) {
395
+ const own = uncommitted(file).filter((l) => {
396
+ const parsed = parseJson(l);
397
+ const row = parsed.ok ? (parsed.value as Record<string, unknown> | null) : null;
398
+ return row?.workflow === o.workflow && Number(row.ts) >= o.startMs!;
399
+ });
400
+ if (own.length > 0) add(file, own);
401
+ }
402
+ return carried;
403
+ }
337
404
 
338
- let wt = bookRoot;
339
- let target = "";
340
- let release: (() => void) | undefined;
341
- if (o.devPushes) {
342
- let lock: { path: string; token: string };
343
- try {
344
- lock = await acquireDevLock({
345
- cwd: root,
346
- workflow: "ship",
347
- fid: o.fid,
348
- deadlineS: 60,
349
- log: ctx.log,
350
- });
351
- } catch {
352
- // Busy: the FAILED record rides along on the next dev commit; never a second failure.
353
- ctx.log(`dev lock busy — ship FAILED bookkeeping left uncommitted in ${bookRoot}`);
354
- return { code: EXIT.OK, pushed: false, ref: null, skipped: "dev-lock-busy" };
355
- }
356
- release = () => releaseLock(lock.path, { workflow: "ship", fid: o.fid, token: lock.token });
357
- runGit(root, ["checkout", "dev"]);
358
- if (git(root, ["branch", "--show-current"]) !== "dev") {
359
- release();
360
- ctx.log(`not on dev after checkout — FAILED bookkeeping left uncommitted in ${bookRoot}`);
361
- return { code: EXIT_FLUSH_FAILED, pushed: false, ref: null, skipped: null };
362
- }
363
- runGit(root, ["pull", "--ff-only", "origin", "dev"]);
364
- wt = root;
365
- target = "dev";
366
- } else {
367
- ctx.log("RUNTIME_DEVPUSHES=false — the FAILED record commits on the current branch");
368
- target = git(wt, ["branch", "--show-current"]) ?? "";
405
+ /**
406
+ * After a landing from a dev / main / detached checkout: hand back what was
407
+ * carried, so a later fast-forward of dev does not stop on it. A carried `.md`
408
+ * log identical to the landed copy is removed when untracked, or returns to HEAD
409
+ * when tracked. A carried ledger loses exactly the carried lines; it returns to
410
+ * HEAD when that leaves it equal, and an untracked one left empty is removed.
411
+ * Anything staged, or a log changed since it landed, stays and is named.
412
+ */
413
+ function handBack(tree: string, sha: string, carried: Carried, log: (line: string) => void): void {
414
+ const back: string[] = [];
415
+ const kept: string[] = [];
416
+ const staged = (rel: string) => !runGit(tree, ["diff", "--cached", "--quiet", "--", rel]).ok;
417
+ const tracked = (rel: string) => runGit(tree, ["ls-files", "--error-unmatch", "--", rel]).ok;
418
+ for (const rel of carried.files) {
419
+ const abs = path.join(tree, rel);
420
+ const landed = runGit(tree, ["show", `${sha}:${rel}`]);
421
+ const same =
422
+ landed.ok && fs.existsSync(abs) && fs.readFileSync(abs, "utf-8").trim() === landed.stdout;
423
+ if (!same || staged(rel)) kept.push(rel);
424
+ else if (!tracked(rel)) {
425
+ fs.rmSync(abs);
426
+ back.push(rel);
427
+ } else if (runGit(tree, ["restore", "--source=HEAD", "--worktree", "--", rel]).ok)
428
+ back.push(rel);
429
+ else kept.push(rel);
369
430
  }
370
- try {
371
- if (target === "") {
372
- ctx.log(`push target empty (detached HEAD?) — bookkeeping left uncommitted in ${wt}`);
373
- return { code: EXIT_FLUSH_FAILED, pushed: false, ref: null, skipped: null };
431
+ for (const [rel, lines] of carried.lines) {
432
+ const abs = path.join(tree, rel);
433
+ if (!fs.existsSync(abs) || staged(rel)) {
434
+ kept.push(rel);
435
+ continue;
374
436
  }
375
- const before = headSha(wt);
376
- try {
377
- commitBookkeeping(
378
- {
379
- root: wt,
380
- month: o.month,
381
- fid: o.fid,
382
- scope: "full",
383
- mode: "commit",
384
- message: `chore(${o.fid}): ship FAILED bkit [skip ci]`,
385
- },
386
- ctx.log,
387
- );
388
- } catch (err) {
389
- if (err instanceof CommandError && err.code === EXIT_EMPTY) {
390
- ctx.log("no bookkeeping delta to record — nothing committed, nothing pushed");
391
- return { code: EXIT.OK, pushed: false, ref: null, skipped: "nothing-to-commit" };
437
+ const drop = new Map<string, number>();
438
+ for (const l of lines) drop.set(l.trim(), (drop.get(l.trim()) ?? 0) + 1);
439
+ const left = fs
440
+ .readFileSync(abs, "utf-8")
441
+ .split("\n")
442
+ .filter((l) => {
443
+ const n = drop.get(l.trim()) ?? 0;
444
+ if (n === 0) return true;
445
+ drop.set(l.trim(), n - 1);
446
+ return false;
447
+ })
448
+ .join("\n");
449
+ const head = runGit(tree, ["show", `HEAD:${rel}`]);
450
+ if (head.ok && left.trim() === head.stdout.trim()) {
451
+ if (!runGit(tree, ["restore", "--source=HEAD", "--worktree", "--", rel]).ok) {
452
+ kept.push(rel);
453
+ continue;
392
454
  }
393
- ctx.log(
394
- `bookkeeping commit failed — FAILED bookkeeping left uncommitted in ${wt}: ${(err as Error).message}`,
395
- );
396
- return { code: EXIT_FLUSH_FAILED, pushed: false, ref: null, skipped: null };
397
- }
398
- if (headSha(wt) === before) {
455
+ } else if (!tracked(rel) && left.trim() === "") fs.rmSync(abs);
456
+ else fs.writeFileSync(abs, left.endsWith("\n") || left === "" ? left : `${left}\n`);
457
+ back.push(rel);
458
+ }
459
+ if (back.length > 0) log(`handed back ${back.length} file(s) now on dev: ${back.join(", ")}`);
460
+ if (kept.length > 0) log(`kept in ${tree}, not all on dev: ${kept.join(", ")}`);
461
+ }
462
+
463
+ /** Thrown by a landing's build when the book adds nothing to dev. */
464
+ const NOTHING_TO_LAND = new Error("no bookkeeping delta");
465
+
466
+ /**
467
+ * Land a failed run's record on dev: carry its book (the run's tree) into a
468
+ * throwaway origin/dev checkout, commit it as ONE
469
+ * `chore({fid}): {workflow} FAILED bkit [skip ci]` and push it. Ship's Failure
470
+ * Path always lands here; the other workflows land here only from a `dev` /
471
+ * `main` / detached checkout, where a commit in the checkout would publish code.
472
+ * `shared` (the book is such a checkout) → only the run's own record is carried
473
+ * (`carryOwnBook`), and `carried` says what, for the hand-back.
474
+ * Not landed → the record stays in the book, and the next run carries it.
475
+ */
476
+ async function landFailedRecord(
477
+ ctx: RunContext,
478
+ o: { workflow: string; fid: string; month: string; book: string; shared: boolean },
479
+ ): Promise<{
480
+ code: number;
481
+ pushed: boolean;
482
+ ref: string | null;
483
+ skipped: string | null;
484
+ sha?: string;
485
+ carried?: Carried;
486
+ }> {
487
+ const root = repoRoot(ctx.cwd);
488
+ const { book } = o;
489
+ const kept = `${o.workflow} FAILED record kept in ${book} — the next ${o.workflow} of ${o.fid} carries it`;
490
+ const stop = (code: number, why: string) => {
491
+ ctx.log(`${why} — ${kept}`);
492
+ return { code, pushed: false, ref: null, skipped: null };
493
+ };
494
+ // Read leniently: an unreadable row only leaves the run's start unknown.
495
+ const statusAbs = path.join(book, statusRelPath(o.month, o.fid));
496
+ const starts = (fs.existsSync(statusAbs) ? textLines(fs.readFileSync(statusAbs, "utf-8")) : [])
497
+ .map((l) => parseObject(l))
498
+ .filter((e) => e?.type === "workflow-started" && e.workflow === o.workflow)
499
+ .map((e) => Date.parse(String(e?.at)))
500
+ .filter((ms) => Number.isFinite(ms));
501
+ const startMs = starts.length > 0 ? Math.max(...starts) : NaN;
502
+ let carried: Carried | undefined;
503
+ let res: DevPush;
504
+ try {
505
+ res = await pushToDev({
506
+ root,
507
+ dir: landDir(root, o.fid),
508
+ build: (dir) => {
509
+ if (o.shared)
510
+ carried = carryOwnBook(
511
+ book,
512
+ dir,
513
+ {
514
+ month: o.month,
515
+ fid: o.fid,
516
+ workflow: o.workflow,
517
+ startMs: Number.isFinite(startMs) ? startMs : undefined,
518
+ },
519
+ ctx.log,
520
+ );
521
+ else carryBook(book, dir, o.month, o.fid);
522
+ const before = headSha(dir);
523
+ try {
524
+ commitBookkeeping(
525
+ {
526
+ root: dir,
527
+ month: o.month,
528
+ fid: o.fid,
529
+ scope: "full",
530
+ mode: "commit",
531
+ message: `chore(${o.fid}): ${o.workflow} FAILED bkit [skip ci]`,
532
+ },
533
+ ctx.log,
534
+ );
535
+ } catch (err) {
536
+ throw err instanceof CommandError && err.code === EXIT_EMPTY ? NOTHING_TO_LAND : err;
537
+ }
538
+ if (headSha(dir) === before) throw NOTHING_TO_LAND;
539
+ },
540
+ log: ctx.log,
541
+ });
542
+ } catch (err) {
543
+ if (err === NOTHING_TO_LAND) {
399
544
  ctx.log("no bookkeeping delta to record — nothing committed, nothing pushed");
400
545
  return { code: EXIT.OK, pushed: false, ref: null, skipped: "nothing-to-commit" };
401
546
  }
402
- const push = runGit(wt, ["push", "origin", target]);
403
- if (!push.ok) {
404
- ctx.log(`git push origin ${target} failed: ${push.stderr}`);
405
- return { code: EXIT_PUSH_FAILED, pushed: false, ref: null, skipped: null };
406
- }
407
- return { code: EXIT.OK, pushed: true, ref: target, skipped: null };
408
- } finally {
409
- release?.();
547
+ return stop(EXIT_FLUSH_FAILED, `bookkeeping commit failed: ${(err as Error).message}`);
548
+ }
549
+ switch (res.kind) {
550
+ case "landed":
551
+ return { code: EXIT.OK, pushed: true, ref: DEV, skipped: null, sha: res.sha, carried };
552
+ case "refused":
553
+ return stop(EXIT_PUSH_FAILED, `dev refused the push: ${res.stderr}`);
554
+ case "push-failed":
555
+ return stop(EXIT_PUSH_FAILED, `dev push failed without a server answer: ${res.stderr}`);
556
+ case "exhausted":
557
+ return stop(EXIT_PUSH_FAILED, `dev moved before each of ${res.attempts} pushes`);
558
+ case "fetch-failed":
559
+ return stop(EXIT_FLUSH_FAILED, `fetch of dev failed: ${res.stderr}`);
560
+ case "setup-failed":
561
+ return stop(EXIT_FLUSH_FAILED, `throwaway checkout failed: ${res.stderr}`);
410
562
  }
411
563
  }
412
564
 
@@ -428,19 +580,24 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
428
580
  let ref = str(ctx.flags.ref) ?? null;
429
581
  let pushed = false;
430
582
  let skipped: string | null = null;
431
- if (push) {
432
- if (!present) {
433
- ctx.log(`${artifact} is missing or empty — nothing to hand over`);
434
- return EXIT_HANDOVER_MISSING;
435
- }
436
- runGit(ctx.cwd, ["add", "-A"]);
437
- const made = runGit(ctx.cwd, [
438
- "commit",
439
- "-m",
440
- `docs(${fid}): ${workflow} aborted bkit [skip ci]`,
441
- ]);
583
+ const tree =
584
+ worktree === undefined ? (git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? base) : base;
585
+ const branch = git(tree, ["branch", "--show-current"]) ?? "";
586
+ // A dev / main / detached checkout is shared: only the run's own record leaves it.
587
+ const shared = branch === "" || isSharedBranch(branch);
588
+ let handed: { sha: string; carried: Carried } | undefined;
589
+ if (push && shared) {
590
+ const r = await landFailedRecord(ctx, { workflow, fid, month, book: tree, shared });
591
+ if (r.sha !== undefined && r.carried !== undefined) handed = { sha: r.sha, carried: r.carried };
592
+ code = r.code;
593
+ pushed = r.pushed;
594
+ ref = r.ref;
595
+ skipped = r.skipped;
596
+ } else if (push) {
597
+ runGit(tree, ["add", "-A"]);
598
+ const made = runGit(tree, ["commit", "-m", `docs(${fid}): ${workflow} aborted bkit [skip ci]`]);
442
599
  if (!made.ok) ctx.log(`abort commit: ${made.stderr || made.stdout}`);
443
- const r = pushBranch(ctx.cwd, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
600
+ const r = pushBranch(tree, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
444
601
  if (r.code === EXIT.USE_MCP) return r.code;
445
602
  pushed = r.out.pushed;
446
603
  ref = r.out.ref;
@@ -452,12 +609,8 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
452
609
  ? EXIT_OPEN_PR_KEPT
453
610
  : EXIT_PUSH_FAILED;
454
611
  } else if (flush) {
455
- const r = await shipFlush(ctx, {
456
- fid,
457
- month,
458
- devPushes: ctx.flags.devPushes === true,
459
- worktree: worktree === undefined ? undefined : base,
460
- });
612
+ const r = await landFailedRecord(ctx, { workflow, fid, month, book: tree, shared });
613
+ if (r.sha !== undefined && r.carried !== undefined) handed = { sha: r.sha, carried: r.carried };
461
614
  code = r.code;
462
615
  pushed = r.pushed;
463
616
  ref = r.ref;
@@ -474,6 +627,7 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
474
627
  bodyFile: artifact,
475
628
  })
476
629
  : null;
630
+ if (handed !== undefined) handBack(tree, handed.sha, handed.carried, ctx.log);
477
631
  ctx.emit({
478
632
  handover: present ? artifact : null,
479
633
  pushed,
@@ -674,7 +828,6 @@ export interface CloseInput {
674
828
  workflow: string;
675
829
  fid: string;
676
830
  month?: string;
677
- devPushes: boolean;
678
831
  file?: string;
679
832
  prNumber?: number;
680
833
  squashSha?: string;
@@ -708,7 +861,7 @@ export function closeWorkflow(
708
861
  throw new CommandError(EXIT.USAGE, `--squash-sha "${o.squashSha}" is not a commit sha`);
709
862
 
710
863
  // Graded first, so the report below carries this run's grade.
711
- const violations = gradeCompliance(where.tree, workflow, log);
864
+ const violations = gradeCompliance(where.tree, workflow, log, o.squashSha);
712
865
 
713
866
  const step = `${workflow}-close-workflow`;
714
867
  if (o.recordStep === true) {
@@ -789,7 +942,7 @@ export function closeWorkflow(
789
942
  const ref =
790
943
  o.ref ??
791
944
  (["design", "plan", "ship"].includes(workflow)
792
- ? "dev"
945
+ ? DEV
793
946
  : (git(cwd, ["branch", "--show-current"]) ?? "HEAD"));
794
947
  const artifacts = artifactLinks(
795
948
  where.root,
@@ -856,128 +1009,152 @@ export function closeWorkflow(
856
1009
  }
857
1010
 
858
1011
  /**
859
- * Ship's close: under the dev lock, on dev (this runtime pushes it) or on a
860
- * detached `origin/dev` worktree in the outbox (it does not), run the close, commit
861
- * `docs({fid}): ship DONE bkit [skip ci]`, release the workflow lock, then land the
862
- * commit — push dev, push `HEAD:dev`, or, when that is refused, a `ship-close/{fid}`
863
- * PR merged with an empty body.
1012
+ * Publish a close commit dev refused through its own `ship-close/{fid}` PR,
1013
+ * merged with an empty body. Returns where it landed, or why it did not.
1014
+ */
1015
+ function closePr(
1016
+ ctx: RunContext,
1017
+ dir: string,
1018
+ fid: string,
1019
+ subject: string,
1020
+ ): { ref: string; via: string } | { failed: string } {
1021
+ const branch = `ship-close/${fid}`;
1022
+ const head = headSha(dir);
1023
+ if (!runGit(dir, ["push", "origin", `HEAD:refs/heads/${branch}`]).ok)
1024
+ return { failed: `close branch push failed` };
1025
+ const created = runGh(dir, [
1026
+ "pr",
1027
+ "create",
1028
+ "--base",
1029
+ DEV,
1030
+ "--head",
1031
+ branch,
1032
+ "--title",
1033
+ `docs(${fid}): ship DONE`,
1034
+ "--body",
1035
+ "",
1036
+ ]);
1037
+ if (!created.ok) return { failed: `gh pr create failed: ${created.stderr}` };
1038
+ const pr = probePr(dir, { head: branch, base: DEV, state: "open" });
1039
+ const number = pr.kind === "ok" ? pr.pr?.number : undefined;
1040
+ if (number === undefined) return { failed: `close PR not found for ${branch}` };
1041
+ const merged = mergePr(
1042
+ dir,
1043
+ { number: String(number), subject, matchHead: head, deleteBranch: true },
1044
+ ctx.log,
1045
+ );
1046
+ if (!merged.out.merged) ctx.log(`close PR #${number} opened but not merged — merge it by hand`);
1047
+ return { ref: branch, via: merged.out.merged ? "close-pr" : "close-pr-open" };
1048
+ }
1049
+
1050
+ /**
1051
+ * Ship's close, in the run's tree (the feature worktree, or the adopted
1052
+ * checkout): the close rows there, then ONE `docs({fid}): ship DONE bkit [skip ci]`
1053
+ * commit built in a throwaway origin/dev checkout carrying the run's book and
1054
+ * landed on dev — a refused push publishes it through a `ship-close/{fid}` PR.
1055
+ * Only a close that landed (or opened its PR) releases the workflow lock; once
1056
+ * the close is on dev, the feature worktree and `branch` are removed. A close
1057
+ * that did not land keeps the lock for the Failure Path.
864
1058
  */
865
- async function shipClose(ctx: RunContext, o: CloseInput, token: string | undefined) {
1059
+ async function shipClose(
1060
+ ctx: RunContext,
1061
+ o: CloseInput & { branch?: string },
1062
+ token: string | undefined,
1063
+ ) {
866
1064
  const root = repoRoot(ctx.cwd);
867
- const outbox = o.outbox === undefined ? undefined : path.resolve(ctx.cwd, o.outbox);
868
- if (outbox === undefined) throw new CommandError(EXIT.USAGE, "--flush needs --outbox");
1065
+ if (o.outbox === undefined) throw new CommandError(EXIT.USAGE, "--flush needs --outbox");
869
1066
  const month = resolveMonth(root, o.fid, o.month);
870
- const lock = await acquireDevLock({
871
- cwd: root,
872
- workflow: "ship",
873
- fid: o.fid,
874
- deadlineS: TIMEOUTS.SHIP_DEV_LOCK_ACQUIRE_DEADLINE_S,
875
- log: ctx.log,
876
- });
877
- const fail = (why: string) => {
878
- ctx.log(why);
879
- return { code: EXIT_FLUSH_FAILED, out: null as Record<string, unknown> | null };
880
- };
881
- let closeRoot = "";
882
- let landed: { ref: string; via: string } | null = null;
883
- let out: Record<string, unknown> = {};
1067
+ const book = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
1068
+ const subject = `docs(${o.fid}): ship DONE bkit [skip ci]`;
1069
+ const kept = `close bookkeeping kept in ${book}`;
1070
+ const out = closeWorkflow(book, { ...o, recordStep: true, message: undefined }, ctx.log);
1071
+
1072
+ let viaPr: { ref: string; via: string } | { failed: string } | null = null;
1073
+ let res: DevPush;
884
1074
  try {
885
- let wt: string;
886
- if (o.devPushes) {
887
- runGit(root, ["checkout", "dev"]);
888
- if (git(root, ["branch", "--show-current"]) !== "dev")
889
- return fail("not on dev after checkout — aborting dev ops");
890
- wt = root;
891
- } else {
892
- ctx.log(
893
- "RUNTIME_DEVPUSHES=false — the close commit lands through a detached origin/dev worktree",
894
- );
895
- wt = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
896
- }
897
- out = closeWorkflow(wt, { ...o, recordStep: true, message: undefined }, ctx.log);
898
- if (o.devPushes) {
899
- closeRoot = wt;
900
- } else {
901
- if (!runGit(wt, ["fetch", "origin", "dev"]).ok)
902
- return fail(`fetch origin dev failed — close bookkeeping left uncommitted in ${wt}`);
903
- closeRoot = path.join(outbox, "close");
904
- if (fs.existsSync(closeRoot)) runGit(wt, ["worktree", "remove", "--force", closeRoot]);
905
- runGit(wt, ["worktree", "prune"]);
906
- if (!runGit(wt, ["worktree", "add", "--detach", closeRoot, "origin/dev"]).ok)
907
- return fail(`close worktree add failed — close bookkeeping left uncommitted in ${wt}`);
908
- unionLedgers(wt, closeRoot);
909
- }
910
- commitBookkeeping(
911
- {
912
- root: closeRoot,
913
- month,
914
- fid: o.fid,
915
- scope: "full",
916
- mode: "commit-allow-empty",
917
- message: `docs(${o.fid}): ship DONE bkit [skip ci]`,
1075
+ res = await pushToDev({
1076
+ root,
1077
+ dir: landDir(root, o.fid),
1078
+ build: (dir) => {
1079
+ carryBook(book, dir, month, o.fid);
1080
+ commitBookkeeping(
1081
+ {
1082
+ root: dir,
1083
+ month,
1084
+ fid: o.fid,
1085
+ scope: "full",
1086
+ mode: "commit-allow-empty",
1087
+ message: subject,
1088
+ },
1089
+ ctx.log,
1090
+ );
918
1091
  },
919
- ctx.log,
920
- );
921
- const released = releaseLock(
922
- workflowLockPath(lockRoot(ctx.cwd, "ship", o.devPushes), month, o.fid),
923
- { workflow: "ship", fid: o.fid, token },
924
- );
925
- if (released.removeFailed) return fail("Lock removal failed");
926
- if (o.devPushes) {
927
- if (!runGit(closeRoot, ["push", "origin", "dev"]).ok) {
928
- ctx.log("dev push failed");
929
- return { code: EXIT_PUSH_FAILED, out };
1092
+ refused: async (dir, stderr) => {
1093
+ ctx.log(`dev refused the close push — publishing it through a PR: ${stderr}`);
1094
+ viaPr = closePr(ctx, dir, o.fid, subject);
1095
+ },
1096
+ log: ctx.log,
1097
+ });
1098
+ } catch (err) {
1099
+ ctx.log(`close commit failed: ${(err as Error).message} — ${kept}`);
1100
+ return { code: EXIT_FLUSH_FAILED, out: null };
1101
+ }
1102
+
1103
+ // A close that did not land keeps the lock: the Failure Path releases it.
1104
+ let landed: { ref: string; via: string } | null = null;
1105
+ switch (res.kind) {
1106
+ case "landed":
1107
+ landed = { ref: DEV, via: "head-push" };
1108
+ break;
1109
+ case "refused": {
1110
+ const pr = viaPr as { ref: string; via: string } | { failed: string } | null;
1111
+ if (pr === null || "failed" in pr) {
1112
+ ctx.log(`${pr === null ? "close PR not attempted" : pr.failed} — ${kept}`);
1113
+ return { code: EXIT_FLUSH_FAILED, out: null };
930
1114
  }
931
- landed = { ref: "dev", via: "dev-push" };
1115
+ landed = pr;
1116
+ break;
932
1117
  }
933
- } finally {
934
- releaseLock(lock.path, { workflow: "ship", fid: o.fid, token: lock.token });
1118
+ case "push-failed":
1119
+ ctx.log(`dev push failed without a server answer: ${res.stderr} — ${kept}`);
1120
+ return { code: EXIT_PUSH_FAILED, out };
1121
+ case "exhausted":
1122
+ ctx.log(`dev moved before each of ${res.attempts} pushes — ${kept}`);
1123
+ return { code: EXIT_PUSH_FAILED, out };
1124
+ case "fetch-failed":
1125
+ ctx.log(`fetch of dev failed: ${res.stderr} — ${kept}`);
1126
+ return { code: EXIT_FLUSH_FAILED, out: null };
1127
+ case "setup-failed":
1128
+ ctx.log(`throwaway checkout failed: ${res.stderr} — ${kept}`);
1129
+ return { code: EXIT_FLUSH_FAILED, out: null };
935
1130
  }
936
1131
 
937
- if (!o.devPushes) {
938
- if (runGit(closeRoot, ["push", "origin", "HEAD:dev"]).ok) {
939
- landed = { ref: "dev", via: "head-push" };
940
- } else {
941
- // dev refused the push: publish the close commit through its own PR.
942
- const branch = `ship-close/${o.fid}`;
943
- const head = headSha(closeRoot);
944
- if (!runGit(closeRoot, ["push", "origin", `HEAD:refs/heads/${branch}`]).ok)
945
- return fail(`close branch push failed — close bookkeeping left in ${closeRoot}`);
946
- const created = runGh(closeRoot, [
947
- "pr",
948
- "create",
949
- "--base",
950
- "dev",
951
- "--head",
952
- branch,
953
- "--title",
954
- `docs(${o.fid}): ship DONE`,
955
- "--body",
956
- "",
957
- ]);
958
- if (!created.ok) return fail(`gh pr create failed: ${created.stderr}`);
959
- const pr = probePr(closeRoot, { head: branch, base: "dev", state: "open" });
960
- const number = pr.kind === "ok" ? pr.pr?.number : undefined;
961
- if (number === undefined) return fail(`close PR not found for ${branch}`);
962
- const merged = mergePr(
963
- closeRoot,
964
- {
965
- number: String(number),
966
- subject: `docs(${o.fid}): ship DONE bkit [skip ci]`,
967
- matchHead: head,
968
- deleteBranch: true,
969
- },
970
- ctx.log,
1132
+ const released = releaseLock(workflowLockPath(root, month, o.fid), {
1133
+ workflow: "ship",
1134
+ fid: o.fid,
1135
+ token,
1136
+ });
1137
+ if (released.removeFailed) {
1138
+ ctx.log("Lock removal failed");
1139
+ return { code: EXIT_FLUSH_FAILED, out: null };
1140
+ }
1141
+
1142
+ // The book is on dev only once the close landed or its PR merged.
1143
+ let worktree: RemoveResult | null = null;
1144
+ if (landed.via === "close-pr-open") {
1145
+ ctx.log(`close PR not merged — ${kept} until it is`);
1146
+ } else {
1147
+ if (landed.via === "close-pr" && !runGit(root, ["fetch", "origin", DEV]).ok)
1148
+ ctx.log(
1149
+ `fetch of dev after the close PR failed — origin/${DEV} is stale until the next fetch`,
971
1150
  );
972
- if (!merged.out.merged)
973
- ctx.log(`close PR #${number} opened but not merged — merge it by hand`);
974
- landed = { ref: branch, via: merged.out.merged ? "close-pr" : "close-pr-open" };
1151
+ try {
1152
+ worktree = removeWorktree(root, o.fid, o.branch, ctx.log);
1153
+ } catch (err) {
1154
+ ctx.log(`${(err as Error).message} — remove ${book} by hand`);
975
1155
  }
976
- const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
977
- runGit(top, ["worktree", "remove", "--force", closeRoot]);
978
- runGit(top, ["worktree", "prune"]);
979
1156
  }
980
- return { code: EXIT.OK, out: { ...out, closeRoot, landed } };
1157
+ return { code: EXIT.OK, out: { ...out, landed, worktree } };
981
1158
  }
982
1159
 
983
1160
  // ---------------------------------------------------------------------------
@@ -1123,11 +1300,6 @@ const MONTH_FLAG: FlagSpec = {
1123
1300
  type: "string",
1124
1301
  help: "month bucket YYYYMM (default: the feature's bucket, else this UTC month)",
1125
1302
  };
1126
- const DEV_PUSHES_FLAG: FlagSpec = {
1127
- name: "dev-pushes",
1128
- type: "boolean",
1129
- help: "ship only: this runtime pushes to dev (logs book in the main checkout)",
1130
- };
1131
1303
  const STATUS_FILE_FLAG: FlagSpec = {
1132
1304
  name: "file",
1133
1305
  type: "string",
@@ -1158,7 +1330,6 @@ export const workflowsCommand: CommandSpec = {
1158
1330
  WORKFLOW_FLAG,
1159
1331
  FID_FLAG,
1160
1332
  MONTH_FLAG,
1161
- DEV_PUSHES_FLAG,
1162
1333
  STATUS_FILE_FLAG,
1163
1334
  {
1164
1335
  name: "lock-held",
@@ -1182,7 +1353,6 @@ export const workflowsCommand: CommandSpec = {
1182
1353
  run: (ctx) => {
1183
1354
  const workflow = workflowName(String(ctx.flags.workflow));
1184
1355
  const fid = String(ctx.flags.fid);
1185
- const devPushes = ctx.flags.devPushes === true;
1186
1356
  const token = str(ctx.flags.token);
1187
1357
  if (token !== undefined && ctx.flags.lockHeld !== true)
1188
1358
  throw new CommandError(EXIT.USAGE, "--token applies with --lock-held only");
@@ -1190,13 +1360,12 @@ export const workflowsCommand: CommandSpec = {
1190
1360
  workflow,
1191
1361
  fid,
1192
1362
  month: str(ctx.flags.month),
1193
- devPushes,
1194
1363
  file: str(ctx.flags.file),
1195
1364
  });
1196
1365
 
1197
1366
  let lock: Record<string, unknown>;
1198
1367
  if (ctx.flags.lockHeld === true) {
1199
- const file = workflowLockPath(lockRoot(ctx.cwd, workflow, devPushes), where.month, fid);
1368
+ const file = workflowLockPath(where.root, where.month, fid);
1200
1369
  checkHeldLock(file, { workflow, fid, token });
1201
1370
  lock = { path: file };
1202
1371
  } else {
@@ -1206,7 +1375,6 @@ export const workflowsCommand: CommandSpec = {
1206
1375
  workflow,
1207
1376
  fid,
1208
1377
  month: where.month,
1209
- devPushes,
1210
1378
  log: ctx.log,
1211
1379
  }),
1212
1380
  };
@@ -1245,7 +1413,6 @@ export const workflowsCommand: CommandSpec = {
1245
1413
  WORKFLOW_FLAG,
1246
1414
  { ...FID_FLAG, required: false, help: "feature id (needed with --token)" },
1247
1415
  MONTH_FLAG,
1248
- DEV_PUSHES_FLAG,
1249
1416
  STATUS_FILE_FLAG,
1250
1417
  {
1251
1418
  ...TOKEN_FLAG,
@@ -1308,7 +1475,7 @@ export const workflowsCommand: CommandSpec = {
1308
1475
  },
1309
1476
  handover: {
1310
1477
  summary:
1311
- "After the handover subagent: commit and abort-push it (--push), or ship's one-commit flush (--flush); print the handover comment.",
1478
+ "Keep a failed run's record: commit and push it on the feature branch, or land its logs and ledgers on dev (--push from dev / main, ship's --flush); print the handover comment.",
1312
1479
  flags: [
1313
1480
  WORKFLOW_FLAG,
1314
1481
  FID_FLAG,
@@ -1316,12 +1483,12 @@ export const workflowsCommand: CommandSpec = {
1316
1483
  {
1317
1484
  name: "push",
1318
1485
  type: "boolean",
1319
- help: "git add -A, commit `docs({fid}): {workflow} aborted bkit [skip ci]`, push --mode=abort",
1486
+ help: "feature branch: git add -A, commit `docs({fid}): {workflow} aborted bkit [skip ci]`, push --mode=abort; dev / main / detached: lands like --flush, the checkout untouched",
1320
1487
  },
1321
1488
  {
1322
1489
  name: "flush",
1323
1490
  type: "boolean",
1324
- help: "ship: copy the worktree's logs and ledgers into the book root, ONE FAILED commit, ONE push",
1491
+ help: "ship: carry the run's logs and ledgers into a throwaway origin/dev checkout, ONE `chore({fid}): {workflow} FAILED bkit [skip ci]` commit, landed on dev",
1325
1492
  },
1326
1493
  {
1327
1494
  name: "open-pr",
@@ -1329,11 +1496,10 @@ export const workflowsCommand: CommandSpec = {
1329
1496
  help: "--push: the open-PR answer from MCP (a number, or none) instead of asking gh",
1330
1497
  },
1331
1498
  { name: "ref", type: "string", help: "link the handover at this ref (no push / flush)" },
1332
- DEV_PUSHES_FLAG,
1333
1499
  {
1334
1500
  name: "worktree",
1335
1501
  type: "string",
1336
- help: "ship: the worktree holding the handover and the branch-side logs (default: cwd / .worktrees/{fid})",
1502
+ help: "the run's tree: holds the handover and the logs, and is where --push commits (default: cwd's checkout)",
1337
1503
  },
1338
1504
  OWNER_REPO_FLAG,
1339
1505
  ],
@@ -1341,20 +1507,18 @@ export const workflowsCommand: CommandSpec = {
1341
1507
  handover: "the handover artifact, or null when absent",
1342
1508
  pushed: "the push (or flush push) ran and succeeded",
1343
1509
  ref: "where the handover now lives, or null when nothing was pushed",
1344
- skipped:
1345
- "why nothing was pushed: open-pr | skip-ci | dev-lock-busy | nothing-to-commit (null otherwise)",
1510
+ skipped: "why nothing was pushed: open-pr | skip-ci | nothing-to-commit (null otherwise)",
1346
1511
  comment:
1347
1512
  "the handover comment body (null when there is no handover); links only when pushed",
1348
1513
  },
1349
1514
  exitCodes: {
1350
1515
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1351
- [EXIT_HANDOVER_MISSING]:
1352
- "--push: the handover artifact is missing or empty (nothing committed)",
1353
1516
  [EXIT_OPEN_PR_KEPT]:
1354
1517
  "--push: the branch has an open PR, nothing pushed (the comment has no link)",
1355
- [EXIT_PUSH_FAILED]: "the push failed (the comment has no link)",
1518
+ [EXIT_PUSH_FAILED]:
1519
+ "the push failed, or dev refused / kept moving under the FAILED landing (the comment has no link)",
1356
1520
  [EXIT_FLUSH_FAILED]:
1357
- "--flush: not on dev after checkout, detached HEAD, or the FAILED commit failed",
1521
+ "the dev fetch, the throwaway checkout or the FAILED commit failed; the record stays in the run's tree",
1358
1522
  },
1359
1523
  run: handoverVerb,
1360
1524
  },
@@ -1365,7 +1529,6 @@ export const workflowsCommand: CommandSpec = {
1365
1529
  WORKFLOW_FLAG,
1366
1530
  FID_FLAG,
1367
1531
  MONTH_FLAG,
1368
- DEV_PUSHES_FLAG,
1369
1532
  STATUS_FILE_FLAG,
1370
1533
  {
1371
1534
  name: "pr-number",
@@ -1414,9 +1577,14 @@ export const workflowsCommand: CommandSpec = {
1414
1577
  {
1415
1578
  name: "flush",
1416
1579
  type: "boolean",
1417
- help: "ship: under the dev lock, close on dev (or a detached origin/dev worktree), commit `ship DONE`, release the lock (--token), push",
1580
+ help: "ship: commit `ship DONE` in a throwaway origin/dev checkout carrying the run's book, land it on dev (refused: a ship-close PR), release the lock (--token), remove the worktree",
1418
1581
  },
1419
1582
  { ...TOKEN_FLAG, help: "--flush: the workflow lock token to release" },
1583
+ {
1584
+ name: "branch",
1585
+ type: "string",
1586
+ help: "--flush: the shipped branch, deleted locally and on origin with the worktree once the close is on dev",
1587
+ },
1420
1588
  ],
1421
1589
  output: {
1422
1590
  row: "the appended workflow-done row",
@@ -1436,15 +1604,17 @@ export const workflowsCommand: CommandSpec = {
1436
1604
  roadmapFoldNeeded:
1437
1605
  "always true: append the feature row and re-render the board (not run here)",
1438
1606
  featureStatus: "roadmap status this close moves the feature to",
1439
- closeRoot: "--flush: the checkout the close commit was made in",
1440
- landed: "--flush: {ref, via: dev-push | head-push | close-pr | close-pr-open}",
1607
+ landed: "--flush: {ref, via: head-push | close-pr | close-pr-open}",
1608
+ worktree:
1609
+ "--flush: the `bkit worktrees remove` result once the close is on dev; null while the close PR is unmerged or the removal failed",
1441
1610
  },
1442
1611
  exitCodes: {
1443
1612
  [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
1444
1613
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1445
- [EXIT_PUSH_FAILED]: "--flush: the dev push failed",
1614
+ [EXIT_PUSH_FAILED]:
1615
+ "--flush: dev moved before every push, or the push failed without a server answer; the lock is kept",
1446
1616
  [EXIT_FLUSH_FAILED]:
1447
- "--flush: not on dev after checkout, the dev fetch / close worktree failed, the lock stayed, or the close PR could not be opened",
1617
+ "--flush: the dev fetch, the throwaway checkout or the close commit failed, the close PR could not be opened (the lock is kept), or the lock could not be removed",
1448
1618
  },
1449
1619
  run: async (ctx) => {
1450
1620
  const f = ctx.flags;
@@ -1452,7 +1622,6 @@ export const workflowsCommand: CommandSpec = {
1452
1622
  workflow: String(f.workflow),
1453
1623
  fid: String(f.fid),
1454
1624
  month: str(f.month),
1455
- devPushes: f.devPushes === true,
1456
1625
  file: str(f.file),
1457
1626
  prNumber: positiveInt(f.prNumber, "pr-number"),
1458
1627
  squashSha: str(f.squashSha),
@@ -1469,7 +1638,7 @@ export const workflowsCommand: CommandSpec = {
1469
1638
  };
1470
1639
  if (f.flush === true) {
1471
1640
  if (input.workflow !== "ship") throw new CommandError(EXIT.USAGE, "--flush is ship only");
1472
- const r = await shipClose(ctx, input, str(f.token));
1641
+ const r = await shipClose(ctx, { ...input, branch: str(f.branch) }, str(f.token));
1473
1642
  if (r.out) ctx.emit(r.out);
1474
1643
  return r.code;
1475
1644
  }
@@ -1545,7 +1714,7 @@ export const workflowsCommand: CommandSpec = {
1545
1714
  const month = resolveMonth(root, fid, str(ctx.flags.month));
1546
1715
  const artifacts = artifactLinks(
1547
1716
  root,
1548
- str(ctx.flags.ref) ?? "dev",
1717
+ str(ctx.flags.ref) ?? DEV,
1549
1718
  month,
1550
1719
  fid,
1551
1720
  workflow,