@cbartens/bkit 5.3.0 → 5.5.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 (186) hide show
  1. package/.bkit/README.md +20 -7
  2. package/.bkit/core/.agents/docs.md +1 -1
  3. package/.bkit/core/.agents/rules.md +14 -9
  4. package/.bkit/core/.bkit/README.md +19 -6
  5. package/.bkit/core/.bkit/cloud.md +77 -46
  6. package/.bkit/core/.bkit/comparison.md +3 -3
  7. package/.bkit/core/.bkit/install.md +21 -18
  8. package/.bkit/core/.bkit/lite.md +6 -6
  9. package/.bkit/core/.bkit/pipeline.md +6 -3
  10. package/.bkit/core/.bkit/prompts.md +14 -10
  11. package/.bkit/core/.bkit/providers.md +7 -7
  12. package/.bkit/core/.bkit/templates.md +46 -10
  13. package/.bkit/core/.bkit/trackers.md +92 -38
  14. package/.bkit/core/.bkit/workflows.md +140 -116
  15. package/.bkit/core/AGENTS.md +2 -2
  16. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +3 -2
  17. package/.bkit/core/docs/templates/bkit-audit-adoption.md +1 -1
  18. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  19. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  20. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  21. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  22. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +2 -2
  23. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  24. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  25. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +4 -2
  26. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  27. package/.bkit/core/docs/templates/bkit-audit-cost.md +3 -2
  28. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  29. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -2
  30. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +5 -5
  31. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  32. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +14 -13
  33. package/.bkit/core/docs/templates/bkit-audit-documentation.md +1 -1
  34. package/.bkit/core/docs/templates/bkit-audit-duplication.md +2 -2
  35. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  36. package/.bkit/core/docs/templates/bkit-audit-flakes.md +3 -2
  37. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -2
  38. package/.bkit/core/docs/templates/bkit-audit-issues.md +25 -8
  39. package/.bkit/core/docs/templates/bkit-audit-llm.md +3 -2
  40. package/.bkit/core/docs/templates/bkit-audit-logs.md +10 -6
  41. package/.bkit/core/docs/templates/bkit-audit-models.md +1 -1
  42. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  43. package/.bkit/core/docs/templates/bkit-audit-prompts.md +5 -5
  44. package/.bkit/core/docs/templates/bkit-audit-red-team.md +3 -2
  45. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  46. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  47. package/.bkit/core/docs/templates/bkit-audit-security.md +11 -9
  48. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  49. package/.bkit/core/docs/templates/bkit-audit-testing.md +6 -5
  50. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  51. package/.bkit/core/engine/checks/after/auth.ts +88 -45
  52. package/.bkit/core/engine/checks/after/github.ts +18 -5
  53. package/.bkit/core/engine/checks/after/index.ts +1 -1
  54. package/.bkit/core/engine/checks/after/tools.ts +1 -1
  55. package/.bkit/core/engine/checks/before/env.ts +28 -18
  56. package/.bkit/core/engine/checks/before/mcp.ts +4 -2
  57. package/.bkit/core/engine/checks/status-holes.ts +0 -1
  58. package/.bkit/core/engine/checks/tips/catalogue.ts +31 -2
  59. package/.bkit/core/engine/checks/tips/index.ts +49 -27
  60. package/.bkit/core/engine/cli.ts +27 -18
  61. package/.bkit/core/engine/commands/ci/ci.ts +107 -0
  62. package/.bkit/core/engine/commands/comply.ts +25 -16
  63. package/.bkit/core/engine/commands/install/install.ts +11 -4
  64. package/.bkit/core/engine/commands/install/uninstall.ts +46 -0
  65. package/.bkit/core/engine/commands/land.ts +156 -0
  66. package/.bkit/core/engine/commands/lib.ts +10 -8
  67. package/.bkit/core/engine/commands/registry.ts +2 -0
  68. package/.bkit/core/engine/commands/tips.ts +7 -3
  69. package/.bkit/core/engine/commands/workflow/branches.ts +382 -282
  70. package/.bkit/core/engine/commands/workflow/disk.ts +556 -0
  71. package/.bkit/core/engine/commands/workflow/fids.ts +23 -15
  72. package/.bkit/core/engine/commands/workflow/issues.ts +106 -42
  73. package/.bkit/core/engine/commands/workflow/ledgers.ts +28 -11
  74. package/.bkit/core/engine/commands/workflow/locks.ts +38 -152
  75. package/.bkit/core/engine/commands/workflow/prs.ts +14 -3
  76. package/.bkit/core/engine/commands/workflow/repo.ts +6 -0
  77. package/.bkit/core/engine/commands/workflow/roadmap.ts +53 -54
  78. package/.bkit/core/engine/commands/workflow/runtime.ts +3 -2
  79. package/.bkit/core/engine/commands/workflow/status.ts +33 -11
  80. package/.bkit/core/engine/commands/workflow/steps.ts +26 -17
  81. package/.bkit/core/engine/commands/workflow/workflows.ts +442 -269
  82. package/.bkit/core/engine/commands/workflow/workstreams.ts +3 -2
  83. package/.bkit/core/engine/commands/workflow/worktrees.ts +11 -1
  84. package/.bkit/core/engine/install/manifest.ts +31 -10
  85. package/.bkit/core/engine/install/modules/cloud.ts +3 -1
  86. package/.bkit/core/engine/install/modules/core.ts +97 -4
  87. package/.bkit/core/engine/install/modules/opencode.ts +5 -0
  88. package/.bkit/core/engine/install/placeholders.ts +13 -17
  89. package/.bkit/core/engine/install/write.ts +37 -1
  90. package/.bkit/core/engine/render/trackers.ts +35 -23
  91. package/.bkit/core/engine/shared/egress.ts +6 -0
  92. package/.bkit/core/engine/shared/settings.ts +96 -1
  93. package/.bkit/core/engine/shared/timeouts.ts +8 -7
  94. package/.bkit/core/hooks/guardrails-tiers.js +1 -1
  95. package/.bkit/core/prompts/bkit-audit-generate.md +80 -7
  96. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +1 -1
  97. package/.bkit/core/prompts/bkit-build-challenge-tests.md +1 -1
  98. package/.bkit/core/prompts/bkit-build-plan-execute.md +1 -1
  99. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +1 -1
  100. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +1 -1
  101. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +1 -1
  102. package/.bkit/core/prompts/bkit-debug-failure-soak.md +1 -1
  103. package/.bkit/core/prompts/bkit-design-generate.md +2 -1
  104. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +1 -1
  105. package/.bkit/core/prompts/bkit-utility-update-decisions.md +4 -2
  106. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +4 -2
  107. package/.bkit/core/prompts/bkit-utility-update-documentation.md +12 -2
  108. package/.bkit/core/prompts/bkit-utility-update-failures.md +4 -2
  109. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +4 -2
  110. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +12 -5
  111. package/.bkit/core/prompts/bkit-utility-update-tracker.md +159 -0
  112. package/.bkit/core/workflows/bkit-auto.md +19 -6
  113. package/.bkit/core/workflows/bkit-build.md +64 -22
  114. package/.bkit/core/workflows/bkit-debug.md +72 -28
  115. package/.bkit/core/workflows/bkit-design.md +101 -37
  116. package/.bkit/core/workflows/bkit-plan.md +82 -31
  117. package/.bkit/core/workflows/bkit-ship.md +127 -108
  118. package/.bkit/shared/.bkit/.env.example +8 -0
  119. package/.bkit/shared/.claude/bkit-cloud.md +12 -12
  120. package/.bkit/shared/.claude/settings.json +4 -1
  121. package/.bkit/shared/.cursor/bkit-cloud.md +2 -2
  122. package/.bkit/shared/.cursor/mcp.json +11 -4
  123. package/.bkit/shared/.mcp.json +11 -4
  124. package/.bkit/shared/.opencode/opencode.json +2 -0
  125. package/.bkit/shared/docs/deployments.md +44 -29
  126. package/.bkit/shared/docs/security.md +1 -1
  127. package/.bkit/shared/docs/testing.md +3 -3
  128. package/.bkit/shared/gitignore +1 -2
  129. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +2 -2
  130. package/.bkit/templates/.github/renovate.json5 +1 -1
  131. package/.bkit/templates/.github/workflows/bkit-ci.yml +29 -56
  132. package/.bkit/templates/.github/workflows/bkit-cloud.yml +40 -12
  133. package/.bkit/templates/.husky/pre-commit +10 -4
  134. package/.bkit/templates/.husky/pre-push +69 -12
  135. package/.bkit/templates/.lintstagedrc.json +5 -1
  136. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.mjs +138 -0
  137. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.test.mjs +181 -0
  138. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.machine.mjs +197 -0
  139. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +164 -0
  140. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +1 -1
  141. package/CHANGELOG.md +85 -1
  142. package/README.md +102 -100
  143. package/dist/checks/after/auth.js +81 -45
  144. package/dist/checks/after/github.js +17 -5
  145. package/dist/checks/after/index.js +1 -1
  146. package/dist/checks/after/tools.js +1 -1
  147. package/dist/checks/before/env.js +24 -17
  148. package/dist/checks/before/mcp.js +4 -2
  149. package/dist/checks/status-holes.js +0 -1
  150. package/dist/checks/tips/catalogue.js +28 -2
  151. package/dist/checks/tips/index.js +44 -28
  152. package/dist/cli.js +27 -19
  153. package/dist/commands/ci/ci.js +100 -0
  154. package/dist/commands/comply.js +20 -13
  155. package/dist/commands/install/install.js +10 -4
  156. package/dist/commands/install/uninstall.js +42 -0
  157. package/dist/commands/land.js +129 -0
  158. package/dist/commands/lib.js +9 -6
  159. package/dist/commands/registry.js +2 -0
  160. package/dist/commands/tips.js +7 -3
  161. package/dist/commands/workflow/branches.js +300 -243
  162. package/dist/commands/workflow/disk.js +452 -0
  163. package/dist/commands/workflow/fids.js +22 -15
  164. package/dist/commands/workflow/issues.js +90 -41
  165. package/dist/commands/workflow/ledgers.js +26 -11
  166. package/dist/commands/workflow/locks.js +35 -130
  167. package/dist/commands/workflow/prs.js +8 -3
  168. package/dist/commands/workflow/repo.js +5 -0
  169. package/dist/commands/workflow/roadmap.js +52 -57
  170. package/dist/commands/workflow/runtime.js +3 -2
  171. package/dist/commands/workflow/status.js +32 -12
  172. package/dist/commands/workflow/steps.js +20 -13
  173. package/dist/commands/workflow/workflows.js +397 -251
  174. package/dist/commands/workflow/workstreams.js +3 -2
  175. package/dist/commands/workflow/worktrees.js +11 -1
  176. package/dist/install/manifest.js +30 -10
  177. package/dist/install/modules/cloud.js +3 -1
  178. package/dist/install/modules/core.js +95 -5
  179. package/dist/install/modules/opencode.js +6 -0
  180. package/dist/install/placeholders.js +13 -19
  181. package/dist/install/write.js +26 -2
  182. package/dist/render/trackers.js +34 -20
  183. package/dist/shared/egress.js +6 -0
  184. package/dist/shared/settings.js +44 -0
  185. package/dist/shared/timeouts.js +8 -7
  186. package/package.json +11 -2
@@ -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.
@@ -22,23 +22,23 @@ import * as path from "node:path";
22
22
  import { appendLine, fold, runNumber, runOrStepField, statusTimestamp, } from "../../ledgers/status.js";
23
23
  import { appendLine as telemetryLine, foldFrom, resolveRepoSlug, validate, workflowTelemetry, } from "../../ledgers/telemetry.js";
24
24
  import { readBkitVersion } from "../../install/version-file.js";
25
- import { TIMEOUTS } from "../../shared/timeouts.js";
25
+ import { readBkitConfig } from "../../shared/settings.js";
26
26
  import { gradeCompliance } from "../comply.js";
27
- import { CommandError, DEV, EXIT, git, parseJson, repoRoot, runGh, runGit, statusLocation, statusRelPath, } from "../lib.js";
27
+ import { landDir, pushToDev } from "../land.js";
28
+ import { CommandError, DEV, EXIT, git, isSharedBranch, parseJson, repoRoot, runGh, runGit, statusLocation, statusRelPath, } from "../lib.js";
28
29
  import { anchorBkitStatus, pushBranch, readAnchor, stampAnchor } from "./branches.js";
29
- import { AUTO_LABEL, AUTO_ROUTE_SUFFIX, buildComment, linearState, transitionLabels, } from "./issues.js";
30
+ import { AUTO_LABEL, AUTO_ROUTE_SUFFIX, buildComment, trackerState, transitionLabels, } from "./issues.js";
30
31
  import { EXIT_EMPTY, commitBookkeeping, unionLedgers } from "./ledgers.js";
31
- import { EXIT_REMOVE_FAILED, EXIT_SPLIT_BUCKET, acquireDevLock, acquireWorkflowLock, lockRoot, owns, readHolder, releaseLock, resolveMonth, workflowLockPath, } from "./locks.js";
32
+ import { EXIT_REMOVE_FAILED, EXIT_SPLIT_BUCKET, acquireWorkflowLock, owns, readHolder, releaseLock, resolveMonth, workflowLockPath, } from "./locks.js";
32
33
  import { mergePr, probePr } from "./prs.js";
33
34
  import { FEATURE_STATUS } from "./roadmap.js";
34
35
  import { EXIT_NO_STATUS, WORKFLOW_FLAG, positiveInt, readRuns, readStatusEvents, readStatusRows, str, } from "./status.js";
35
36
  import { writeStepRow } from "./steps.js";
37
+ import { removeWorktree } from "./worktrees.js";
36
38
  /** Sentinels a workflow leaves in its logs folder; either one existing means a handover is due. */
37
39
  export const SENTINELS = [".rebase-failed", ".deferred-blocked"];
38
40
  /** Exit code (start --lock-held): the lock is missing or belongs to another owner. */
39
41
  export const EXIT_LOCK_NOT_HELD = 6;
40
- /** Exit code (handover --push): the handover artifact is missing or empty. */
41
- export const EXIT_HANDOVER_MISSING = 8;
42
42
  /** Exit code (handover --push): the branch has an open PR, so nothing was pushed. */
43
43
  export const EXIT_OPEN_PR_KEPT = 9;
44
44
  /** Exit code (handover, close --flush): a push failed. */
@@ -52,16 +52,11 @@ function workflowName(workflow) {
52
52
  throw new CommandError(EXIT.USAGE, `--workflow must be ${Object.keys(FEATURE_STATUS).join(", ")}`);
53
53
  return workflow;
54
54
  }
55
- /**
56
- * start and close work in the current tree (ship: its book root), the root
57
- * `git rev-parse --show-toplevel` reports.
58
- */
55
+ /** start and close work in the current tree, the root `git rev-parse --show-toplevel` reports. */
59
56
  function whereInTree(cwd, o) {
60
57
  const root = repoRoot(cwd);
61
58
  const month = resolveMonth(root, o.fid, o.month);
62
- const tree = o.workflow === "ship"
63
- ? lockRoot(cwd, o.workflow, o.devPushes)
64
- : (git(cwd, ["rev-parse", "--show-toplevel"]) ?? root);
59
+ const tree = git(cwd, ["rev-parse", "--show-toplevel"]) ?? root;
65
60
  const status = o.file ? path.resolve(cwd, o.file) : path.join(tree, statusRelPath(month, o.fid));
66
61
  return { root, month, tree, status };
67
62
  }
@@ -99,13 +94,12 @@ function abortRebase(tree, log) {
99
94
  }
100
95
  /** The workflow-failed state: row, rebase abort, lock release, sentinels. */
101
96
  function failState(ctx, workflow, fid) {
102
- const devPushes = ctx.flags.devPushes === true;
103
97
  const root = repoRoot(ctx.cwd);
104
98
  const month = resolveMonth(root, fid, str(ctx.flags.month) || undefined);
105
99
  const file = str(ctx.flags.file) || undefined;
106
100
  const status = file
107
101
  ? path.resolve(ctx.cwd, file)
108
- : statusLocation({ cwd: ctx.cwd, workflow, fid, month, devPushes }).path;
102
+ : statusLocation({ cwd: ctx.cwd, workflow, fid, month }).path;
109
103
  // The run's own tree: the feature worktree when there is one, else this checkout.
110
104
  // Never the main checkout behind a worktree, where a rebase would be a human's.
111
105
  const worktree = path.join(root, ".worktrees", fid);
@@ -126,7 +120,7 @@ function failState(ctx, workflow, fid) {
126
120
  else {
127
121
  ctx.log(`${status} does not exist — no workflow-failed row written`);
128
122
  }
129
- const lockFile = workflowLockPath(lockRoot(ctx.cwd, workflow, devPushes), month, fid);
123
+ const lockFile = workflowLockPath(root, month, fid);
130
124
  const { removeFailed, ...lock } = releaseLock(lockFile, {
131
125
  workflow,
132
126
  fid,
@@ -137,7 +131,7 @@ function failState(ctx, workflow, fid) {
137
131
  if (removeFailed)
138
132
  ctx.log(`lock removal failed: ${lockFile}`);
139
133
  // Each sentinel is cleared where it was created: `.rebase-failed` in the run's
140
- // tree, `.deferred-blocked` beside status.jsonl (ship: the book root).
134
+ // tree, `.deferred-blocked` beside status.jsonl.
141
135
  const logDirs = new Set([path.join(tree, logDirRel(month, fid)), path.dirname(status)]);
142
136
  const sentinels = [];
143
137
  for (const dir of logDirs) {
@@ -179,9 +173,11 @@ function failVerb(ctx) {
179
173
  }
180
174
  const merged = prState === "MERGED";
181
175
  const transition = merged ? { phase: "merged" } : { failed: true };
182
- const labels = transitionLabels(list(ctx.flags.label), transition).labels;
176
+ const current = list(ctx.flags.label);
177
+ const labels = transitionLabels(current, transition).labels;
183
178
  if (merged && !labels.includes("bkit:failed"))
184
179
  labels.push("bkit:failed");
180
+ const add = labels.filter((l) => !current.includes(l));
185
181
  // The failure comment, when the step is named.
186
182
  let comment = null;
187
183
  const stepNumber = str(ctx.flags.stepNumber);
@@ -204,8 +200,9 @@ function failVerb(ctx) {
204
200
  sentinels: state.sentinels,
205
201
  handoverNeeded: token !== undefined &&
206
202
  (ctx.flags.maxExceeded === true || state.sentinels.length > 0 || state.soak),
203
+ add,
207
204
  labels,
208
- linearState: linearState(transition, undefined),
205
+ trackerState: trackerState(transition, undefined, readBkitConfig(repoRoot(ctx.cwd))),
209
206
  prState,
210
207
  comment,
211
208
  });
@@ -221,97 +218,237 @@ function readText(cwd, rel) {
221
218
  // ---------------------------------------------------------------------------
222
219
  // handover
223
220
  // ---------------------------------------------------------------------------
221
+ /** Non-empty lines; a final newline ends the last line rather than starting an empty one. */
222
+ const textLines = (text) => text.split("\n").filter((l) => l.trim() !== "");
223
+ /** `rel` in `tree` differs from its HEAD copy, or is untracked: the run wrote it. */
224
+ const ownWrite = (tree, rel) => (git(tree, ["status", "--porcelain", "--untracked-files=all", "--", rel]) ?? "") !== "";
225
+ /** Copy each `.md` log in the run's log folder that dev lacks, or that the run rewrote. */
226
+ function carryLogs(src, dst, rel) {
227
+ if (!fs.existsSync(path.join(src, rel)))
228
+ return [];
229
+ fs.mkdirSync(path.join(dst, rel), { recursive: true });
230
+ const copied = [];
231
+ for (const f of fs.readdirSync(path.join(src, rel)).filter((n) => n.endsWith(".md"))) {
232
+ const from = path.join(src, rel, f);
233
+ const to = path.join(dst, rel, f);
234
+ const same = fs.existsSync(to) && fs.readFileSync(to).equals(fs.readFileSync(from));
235
+ if (same || (fs.existsSync(to) && !ownWrite(src, path.join(rel, f))))
236
+ continue;
237
+ fs.copyFileSync(from, to);
238
+ copied.push(path.join(rel, f));
239
+ }
240
+ return copied;
241
+ }
224
242
  /**
225
- * Ship's Failure Path flush: copy branch-side logs and ledger rows into the book
226
- * root, then ONE `chore({fid}): ship FAILED bkit [skip ci]` commit and ONE push —
227
- * to dev under the dev lock when this runtime pushes dev, else the current branch.
243
+ * Carry a run's book (its feature worktree) into a dev checkout: its `.md` logs,
244
+ * and its ledger rows unioned line-wise (both hold rows the other does not).
228
245
  */
229
- async function shipFlush(ctx, o) {
230
- const root = repoRoot(ctx.cwd);
231
- const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
232
- const bookRoot = o.devPushes ? root : top;
246
+ function carryBook(src, dst, month, fid) {
247
+ carryLogs(src, dst, logDirRel(month, fid));
248
+ unionLedgers(src, dst);
249
+ }
250
+ /** Shared ledgers a run may append to, outside its own log folder. */
251
+ const SHARED_LEDGERS = [
252
+ ":(glob)docs/*.jsonl",
253
+ ":(glob).bkit/*.jsonl",
254
+ ":(exclude).bkit/issues.jsonl",
255
+ ];
256
+ /**
257
+ * Carry ONLY the run's own record out of a dev / main / detached checkout, which
258
+ * other sessions and local-only commits share: the `.md` logs it wrote in its log
259
+ * folder; the lines of that folder's `.jsonl` files its HEAD lacks; and, from the
260
+ * shared ledgers, lines its HEAD lacks that are rows of `workflow` at or after
261
+ * the run's start (`startMs`). No start known → no shared-ledger row is carried.
262
+ */
263
+ function carryOwnBook(src, dst, o, log) {
233
264
  const rel = logDirRel(o.month, o.fid);
234
- const src = o.worktree ?? path.join(root, ".worktrees", o.fid);
235
- if (fs.existsSync(path.join(src, rel)) && path.resolve(src) !== path.resolve(bookRoot)) {
236
- fs.mkdirSync(path.join(bookRoot, rel), { recursive: true });
237
- for (const f of fs.readdirSync(path.join(src, rel)).filter((n) => n.endsWith(".md"))) {
238
- const to = path.join(bookRoot, rel, f);
239
- if (!fs.existsSync(to))
240
- fs.copyFileSync(path.join(src, rel, f), to);
241
- }
242
- unionLedgers(src, bookRoot);
243
- }
244
- let wt = bookRoot;
245
- let target = "";
246
- let release;
247
- if (o.devPushes) {
248
- let lock;
249
- try {
250
- lock = await acquireDevLock({
251
- cwd: root,
252
- workflow: "ship",
253
- fid: o.fid,
254
- deadlineS: 60,
255
- log: ctx.log,
256
- });
257
- }
258
- catch {
259
- // Busy: the FAILED record rides along on the next dev commit; never a second failure.
260
- ctx.log(`dev lock busy — ship FAILED bookkeeping left uncommitted in ${bookRoot}`);
261
- return { code: EXIT.OK, pushed: false, ref: null, skipped: "dev-lock-busy" };
262
- }
263
- release = () => releaseLock(lock.path, { workflow: "ship", fid: o.fid, token: lock.token });
264
- runGit(root, ["checkout", DEV]);
265
- if (git(root, ["branch", "--show-current"]) !== DEV) {
266
- release();
267
- ctx.log(`not on dev after checkout — FAILED bookkeeping left uncommitted in ${bookRoot}`);
268
- return { code: EXIT_FLUSH_FAILED, pushed: false, ref: null, skipped: null };
269
- }
270
- runGit(root, ["pull", "--ff-only", "origin", DEV]);
271
- wt = root;
272
- target = DEV;
265
+ const carried = { files: carryLogs(src, dst, rel), lines: new Map() };
266
+ const uncommitted = (file) => {
267
+ const head = new Set(textLines(git(src, ["show", `HEAD:${file}`]) ?? "").map((l) => l.trim()));
268
+ return textLines(fs.readFileSync(path.join(src, file), "utf-8")).filter((l) => !head.has(l.trim()));
269
+ };
270
+ const add = (file, lines) => {
271
+ const to = path.join(dst, file);
272
+ const existing = fs.existsSync(to) ? fs.readFileSync(to, "utf-8") : "";
273
+ const have = new Set(textLines(existing).map((l) => l.trim()));
274
+ const fresh = lines.filter((l) => !have.has(l.trim()));
275
+ if (fresh.length === 0)
276
+ return;
277
+ fs.mkdirSync(path.dirname(to), { recursive: true });
278
+ const sep = existing !== "" && !existing.endsWith("\n") ? "\n" : "";
279
+ fs.appendFileSync(to, `${sep}${fresh.join("\n")}\n`);
280
+ carried.lines.set(file, fresh);
281
+ };
282
+ const listed = (specs) => (git(src, ["ls-files", "--cached", "--others", "--exclude-standard", "--", ...specs]) ?? "")
283
+ .split("\n")
284
+ .filter((f) => f !== "" && fs.existsSync(path.join(src, f)));
285
+ for (const file of listed([`:(glob)${rel}/*.jsonl`]))
286
+ add(file, uncommitted(file));
287
+ if (o.startMs === undefined) {
288
+ log(`no ${o.workflow} start row for ${o.fid} — no shared-ledger row carried`);
289
+ return carried;
273
290
  }
274
- else {
275
- ctx.log("RUNTIME_DEVPUSHES=false — the FAILED record commits on the current branch");
276
- target = git(wt, ["branch", "--show-current"]) ?? "";
291
+ for (const file of listed(SHARED_LEDGERS)) {
292
+ const own = uncommitted(file).filter((l) => {
293
+ const parsed = parseJson(l);
294
+ const row = parsed.ok ? parsed.value : null;
295
+ return row?.workflow === o.workflow && Number(row.ts) >= o.startMs;
296
+ });
297
+ if (own.length > 0)
298
+ add(file, own);
277
299
  }
278
- try {
279
- if (target === "") {
280
- ctx.log(`push target empty (detached HEAD?) — bookkeeping left uncommitted in ${wt}`);
281
- return { code: EXIT_FLUSH_FAILED, pushed: false, ref: null, skipped: null };
300
+ return carried;
301
+ }
302
+ /**
303
+ * After a landing from a dev / main / detached checkout: hand back what was
304
+ * carried, so a later fast-forward of dev does not stop on it. A carried `.md`
305
+ * log identical to the landed copy is removed when untracked, or returns to HEAD
306
+ * when tracked. A carried ledger loses exactly the carried lines; it returns to
307
+ * HEAD when that leaves it equal, and an untracked one left empty is removed.
308
+ * Anything staged, or a log changed since it landed, stays and is named.
309
+ */
310
+ function handBack(tree, sha, carried, log) {
311
+ const back = [];
312
+ const kept = [];
313
+ const staged = (rel) => !runGit(tree, ["diff", "--cached", "--quiet", "--", rel]).ok;
314
+ const tracked = (rel) => runGit(tree, ["ls-files", "--error-unmatch", "--", rel]).ok;
315
+ for (const rel of carried.files) {
316
+ const abs = path.join(tree, rel);
317
+ const landed = runGit(tree, ["show", `${sha}:${rel}`]);
318
+ const same = landed.ok && fs.existsSync(abs) && fs.readFileSync(abs, "utf-8").trim() === landed.stdout;
319
+ if (!same || staged(rel))
320
+ kept.push(rel);
321
+ else if (!tracked(rel)) {
322
+ fs.rmSync(abs);
323
+ back.push(rel);
282
324
  }
283
- const before = headSha(wt);
284
- try {
285
- commitBookkeeping({
286
- root: wt,
287
- month: o.month,
288
- fid: o.fid,
289
- scope: "full",
290
- mode: "commit",
291
- message: `chore(${o.fid}): ship FAILED bkit [skip ci]`,
292
- }, ctx.log);
325
+ else if (runGit(tree, ["restore", "--source=HEAD", "--worktree", "--", rel]).ok)
326
+ back.push(rel);
327
+ else
328
+ kept.push(rel);
329
+ }
330
+ for (const [rel, lines] of carried.lines) {
331
+ const abs = path.join(tree, rel);
332
+ if (!fs.existsSync(abs) || staged(rel)) {
333
+ kept.push(rel);
334
+ continue;
293
335
  }
294
- catch (err) {
295
- if (err instanceof CommandError && err.code === EXIT_EMPTY) {
296
- ctx.log("no bookkeeping delta to record — nothing committed, nothing pushed");
297
- return { code: EXIT.OK, pushed: false, ref: null, skipped: "nothing-to-commit" };
336
+ const drop = new Map();
337
+ for (const l of lines)
338
+ drop.set(l.trim(), (drop.get(l.trim()) ?? 0) + 1);
339
+ const left = fs
340
+ .readFileSync(abs, "utf-8")
341
+ .split("\n")
342
+ .filter((l) => {
343
+ const n = drop.get(l.trim()) ?? 0;
344
+ if (n === 0)
345
+ return true;
346
+ drop.set(l.trim(), n - 1);
347
+ return false;
348
+ })
349
+ .join("\n");
350
+ const head = runGit(tree, ["show", `HEAD:${rel}`]);
351
+ if (head.ok && left.trim() === head.stdout.trim()) {
352
+ if (!runGit(tree, ["restore", "--source=HEAD", "--worktree", "--", rel]).ok) {
353
+ kept.push(rel);
354
+ continue;
298
355
  }
299
- ctx.log(`bookkeeping commit failed — FAILED bookkeeping left uncommitted in ${wt}: ${err.message}`);
300
- return { code: EXIT_FLUSH_FAILED, pushed: false, ref: null, skipped: null };
301
356
  }
302
- if (headSha(wt) === before) {
357
+ else if (!tracked(rel) && left.trim() === "")
358
+ fs.rmSync(abs);
359
+ else
360
+ fs.writeFileSync(abs, left.endsWith("\n") || left === "" ? left : `${left}\n`);
361
+ back.push(rel);
362
+ }
363
+ if (back.length > 0)
364
+ log(`handed back ${back.length} file(s) now on dev: ${back.join(", ")}`);
365
+ if (kept.length > 0)
366
+ log(`kept in ${tree}, not all on dev: ${kept.join(", ")}`);
367
+ }
368
+ /** Thrown by a landing's build when the book adds nothing to dev. */
369
+ const NOTHING_TO_LAND = new Error("no bookkeeping delta");
370
+ /**
371
+ * Land a failed run's record on dev: carry its book (the run's tree) into a
372
+ * throwaway origin/dev checkout, commit it as ONE
373
+ * `chore({fid}): {workflow} FAILED bkit [skip ci]` and push it. Ship's Failure
374
+ * Path always lands here; the other workflows land here only from a `dev` /
375
+ * `main` / detached checkout, where a commit in the checkout would publish code.
376
+ * `shared` (the book is such a checkout) → only the run's own record is carried
377
+ * (`carryOwnBook`), and `carried` says what, for the hand-back.
378
+ * Not landed → the record stays in the book, and the next run carries it.
379
+ */
380
+ async function landFailedRecord(ctx, o) {
381
+ const root = repoRoot(ctx.cwd);
382
+ const { book } = o;
383
+ const kept = `${o.workflow} FAILED record kept in ${book} — the next ${o.workflow} of ${o.fid} carries it`;
384
+ const stop = (code, why) => {
385
+ ctx.log(`${why} — ${kept}`);
386
+ return { code, pushed: false, ref: null, skipped: null };
387
+ };
388
+ // Read leniently: an unreadable row only leaves the run's start unknown.
389
+ const statusAbs = path.join(book, statusRelPath(o.month, o.fid));
390
+ const starts = (fs.existsSync(statusAbs) ? textLines(fs.readFileSync(statusAbs, "utf-8")) : [])
391
+ .map((l) => parseObject(l))
392
+ .filter((e) => e?.type === "workflow-started" && e.workflow === o.workflow)
393
+ .map((e) => Date.parse(String(e?.at)))
394
+ .filter((ms) => Number.isFinite(ms));
395
+ const startMs = starts.length > 0 ? Math.max(...starts) : NaN;
396
+ let carried;
397
+ let res;
398
+ try {
399
+ res = await pushToDev({
400
+ root,
401
+ dir: landDir(root, o.fid),
402
+ build: (dir) => {
403
+ if (o.shared)
404
+ carried = carryOwnBook(book, dir, {
405
+ month: o.month,
406
+ fid: o.fid,
407
+ workflow: o.workflow,
408
+ startMs: Number.isFinite(startMs) ? startMs : undefined,
409
+ }, ctx.log);
410
+ else
411
+ carryBook(book, dir, o.month, o.fid);
412
+ const before = headSha(dir);
413
+ try {
414
+ commitBookkeeping({
415
+ root: dir,
416
+ month: o.month,
417
+ fid: o.fid,
418
+ scope: "full",
419
+ mode: "commit",
420
+ message: `chore(${o.fid}): ${o.workflow} FAILED bkit [skip ci]`,
421
+ }, ctx.log);
422
+ }
423
+ catch (err) {
424
+ throw err instanceof CommandError && err.code === EXIT_EMPTY ? NOTHING_TO_LAND : err;
425
+ }
426
+ if (headSha(dir) === before)
427
+ throw NOTHING_TO_LAND;
428
+ },
429
+ log: ctx.log,
430
+ });
431
+ }
432
+ catch (err) {
433
+ if (err === NOTHING_TO_LAND) {
303
434
  ctx.log("no bookkeeping delta to record — nothing committed, nothing pushed");
304
435
  return { code: EXIT.OK, pushed: false, ref: null, skipped: "nothing-to-commit" };
305
436
  }
306
- const push = runGit(wt, ["push", "origin", target]);
307
- if (!push.ok) {
308
- ctx.log(`git push origin ${target} failed: ${push.stderr}`);
309
- return { code: EXIT_PUSH_FAILED, pushed: false, ref: null, skipped: null };
310
- }
311
- return { code: EXIT.OK, pushed: true, ref: target, skipped: null };
437
+ return stop(EXIT_FLUSH_FAILED, `bookkeeping commit failed: ${err.message}`);
312
438
  }
313
- finally {
314
- release?.();
439
+ switch (res.kind) {
440
+ case "landed":
441
+ return { code: EXIT.OK, pushed: true, ref: DEV, skipped: null, sha: res.sha, carried };
442
+ case "refused":
443
+ return stop(EXIT_PUSH_FAILED, `dev refused the push: ${res.stderr}`);
444
+ case "push-failed":
445
+ return stop(EXIT_PUSH_FAILED, `dev push failed without a server answer: ${res.stderr}`);
446
+ case "exhausted":
447
+ return stop(EXIT_PUSH_FAILED, `dev moved before each of ${res.attempts} pushes`);
448
+ case "fetch-failed":
449
+ return stop(EXIT_FLUSH_FAILED, `fetch of dev failed: ${res.stderr}`);
450
+ case "setup-failed":
451
+ return stop(EXIT_FLUSH_FAILED, `throwaway checkout failed: ${res.stderr}`);
315
452
  }
316
453
  }
317
454
  async function handoverVerb(ctx) {
@@ -333,20 +470,26 @@ async function handoverVerb(ctx) {
333
470
  let ref = str(ctx.flags.ref) ?? null;
334
471
  let pushed = false;
335
472
  let skipped = null;
336
- if (push) {
337
- if (!present) {
338
- ctx.log(`${artifact} is missing or empty — nothing to hand over`);
339
- return EXIT_HANDOVER_MISSING;
340
- }
341
- runGit(ctx.cwd, ["add", "-A"]);
342
- const made = runGit(ctx.cwd, [
343
- "commit",
344
- "-m",
345
- `docs(${fid}): ${workflow} aborted bkit [skip ci]`,
346
- ]);
473
+ const tree = worktree === undefined ? (git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? base) : base;
474
+ const branch = git(tree, ["branch", "--show-current"]) ?? "";
475
+ // A dev / main / detached checkout is shared: only the run's own record leaves it.
476
+ const shared = branch === "" || isSharedBranch(branch);
477
+ let handed;
478
+ if (push && shared) {
479
+ const r = await landFailedRecord(ctx, { workflow, fid, month, book: tree, shared });
480
+ if (r.sha !== undefined && r.carried !== undefined)
481
+ handed = { sha: r.sha, carried: r.carried };
482
+ code = r.code;
483
+ pushed = r.pushed;
484
+ ref = r.ref;
485
+ skipped = r.skipped;
486
+ }
487
+ else if (push) {
488
+ runGit(tree, ["add", "-A"]);
489
+ const made = runGit(tree, ["commit", "-m", `docs(${fid}): ${workflow} aborted bkit [skip ci]`]);
347
490
  if (!made.ok)
348
491
  ctx.log(`abort commit: ${made.stderr || made.stdout}`);
349
- const r = pushBranch(ctx.cwd, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
492
+ const r = pushBranch(tree, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
350
493
  if (r.code === EXIT.USE_MCP)
351
494
  return r.code;
352
495
  pushed = r.out.pushed;
@@ -360,12 +503,9 @@ async function handoverVerb(ctx) {
360
503
  : EXIT_PUSH_FAILED;
361
504
  }
362
505
  else if (flush) {
363
- const r = await shipFlush(ctx, {
364
- fid,
365
- month,
366
- devPushes: ctx.flags.devPushes === true,
367
- worktree: worktree === undefined ? undefined : base,
368
- });
506
+ const r = await landFailedRecord(ctx, { workflow, fid, month, book: tree, shared });
507
+ if (r.sha !== undefined && r.carried !== undefined)
508
+ handed = { sha: r.sha, carried: r.carried };
369
509
  code = r.code;
370
510
  pushed = r.pushed;
371
511
  ref = r.ref;
@@ -381,6 +521,8 @@ async function handoverVerb(ctx) {
381
521
  bodyFile: artifact,
382
522
  })
383
523
  : null;
524
+ if (handed !== undefined)
525
+ handBack(tree, handed.sha, handed.carried, ctx.log);
384
526
  ctx.emit({
385
527
  handover: present ? artifact : null,
386
528
  pushed,
@@ -550,7 +692,7 @@ export function closeWorkflow(cwd, o, log) {
550
692
  if (o.squashSha !== undefined && !/^[0-9a-f]{7,40}$/.test(o.squashSha))
551
693
  throw new CommandError(EXIT.USAGE, `--squash-sha "${o.squashSha}" is not a commit sha`);
552
694
  // Graded first, so the report below carries this run's grade.
553
- const violations = gradeCompliance(where.tree, workflow, log);
695
+ const violations = gradeCompliance(where.tree, workflow, log, o.squashSha);
554
696
  const step = `${workflow}-close-workflow`;
555
697
  if (o.recordStep === true) {
556
698
  writeStepRow(where.tree, { file: where.status, workflow, step, artifacts: [], commit: "none" }, log);
@@ -669,124 +811,136 @@ export function closeWorkflow(cwd, o, log) {
669
811
  };
670
812
  }
671
813
  /**
672
- * Ship's close: under the dev lock, on dev (this runtime pushes it) or on a
673
- * detached `origin/dev` worktree in the outbox (it does not), run the close, commit
674
- * `docs({fid}): ship DONE bkit [skip ci]`, release the workflow lock, then land the
675
- * commit — push dev, push `HEAD:dev`, or, when that is refused, a `ship-close/{fid}`
676
- * PR merged with an empty body.
814
+ * Publish a close commit dev refused through its own `ship-close/{fid}` PR,
815
+ * merged with an empty body. Returns where it landed, or why it did not.
816
+ */
817
+ function closePr(ctx, dir, fid, subject) {
818
+ const branch = `ship-close/${fid}`;
819
+ const head = headSha(dir);
820
+ if (!runGit(dir, ["push", "origin", `HEAD:refs/heads/${branch}`]).ok)
821
+ return { failed: `close branch push failed` };
822
+ const created = runGh(dir, [
823
+ "pr",
824
+ "create",
825
+ "--base",
826
+ DEV,
827
+ "--head",
828
+ branch,
829
+ "--title",
830
+ `docs(${fid}): ship DONE`,
831
+ "--body",
832
+ "",
833
+ ]);
834
+ if (!created.ok)
835
+ return { failed: `gh pr create failed: ${created.stderr}` };
836
+ const pr = probePr(dir, { head: branch, base: DEV, state: "open" });
837
+ const number = pr.kind === "ok" ? pr.pr?.number : undefined;
838
+ if (number === undefined)
839
+ return { failed: `close PR not found for ${branch}` };
840
+ const merged = mergePr(dir, { number: String(number), subject, matchHead: head, deleteBranch: true }, ctx.log);
841
+ if (!merged.out.merged)
842
+ ctx.log(`close PR #${number} opened but not merged — merge it by hand`);
843
+ return { ref: branch, via: merged.out.merged ? "close-pr" : "close-pr-open" };
844
+ }
845
+ /**
846
+ * Ship's close, in the run's tree (the feature worktree, or the adopted
847
+ * checkout): the close rows there, then ONE `docs({fid}): ship DONE bkit [skip ci]`
848
+ * commit built in a throwaway origin/dev checkout carrying the run's book and
849
+ * landed on dev — a refused push publishes it through a `ship-close/{fid}` PR.
850
+ * Only a close that landed (or opened its PR) releases the workflow lock; once
851
+ * the close is on dev, the feature worktree and `branch` are removed. A close
852
+ * that did not land keeps the lock for the Failure Path.
677
853
  */
678
854
  async function shipClose(ctx, o, token) {
679
855
  const root = repoRoot(ctx.cwd);
680
- const outbox = o.outbox === undefined ? undefined : path.resolve(ctx.cwd, o.outbox);
681
- if (outbox === undefined)
856
+ if (o.outbox === undefined)
682
857
  throw new CommandError(EXIT.USAGE, "--flush needs --outbox");
683
858
  const month = resolveMonth(root, o.fid, o.month);
684
- const lock = await acquireDevLock({
685
- cwd: root,
686
- workflow: "ship",
687
- fid: o.fid,
688
- deadlineS: TIMEOUTS.SHIP_DEV_LOCK_ACQUIRE_DEADLINE_S,
689
- log: ctx.log,
690
- });
691
- const fail = (why) => {
692
- ctx.log(why);
859
+ const book = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
860
+ const subject = `docs(${o.fid}): ship DONE bkit [skip ci]`;
861
+ const kept = `close bookkeeping kept in ${book}`;
862
+ const out = closeWorkflow(book, { ...o, recordStep: true, message: undefined }, ctx.log);
863
+ let viaPr = null;
864
+ let res;
865
+ try {
866
+ res = await pushToDev({
867
+ root,
868
+ dir: landDir(root, o.fid),
869
+ build: (dir) => {
870
+ carryBook(book, dir, month, o.fid);
871
+ commitBookkeeping({
872
+ root: dir,
873
+ month,
874
+ fid: o.fid,
875
+ scope: "full",
876
+ mode: "commit-allow-empty",
877
+ message: subject,
878
+ }, ctx.log);
879
+ },
880
+ refused: async (dir, stderr) => {
881
+ ctx.log(`dev refused the close push — publishing it through a PR: ${stderr}`);
882
+ viaPr = closePr(ctx, dir, o.fid, subject);
883
+ },
884
+ log: ctx.log,
885
+ });
886
+ }
887
+ catch (err) {
888
+ ctx.log(`close commit failed: ${err.message} — ${kept}`);
693
889
  return { code: EXIT_FLUSH_FAILED, out: null };
694
- };
695
- let closeRoot = "";
890
+ }
891
+ // A close that did not land keeps the lock: the Failure Path releases it.
696
892
  let landed = null;
697
- let out = {};
698
- try {
699
- let wt;
700
- if (o.devPushes) {
701
- runGit(root, ["checkout", DEV]);
702
- if (git(root, ["branch", "--show-current"]) !== DEV)
703
- return fail("not on dev after checkout — aborting dev ops");
704
- wt = root;
705
- }
706
- else {
707
- ctx.log("RUNTIME_DEVPUSHES=false — the close commit lands through a detached origin/dev worktree");
708
- wt = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
709
- }
710
- out = closeWorkflow(wt, { ...o, recordStep: true, message: undefined }, ctx.log);
711
- if (o.devPushes) {
712
- closeRoot = wt;
713
- }
714
- else {
715
- if (!runGit(wt, ["fetch", "origin", DEV]).ok)
716
- return fail(`fetch origin dev failed — close bookkeeping left uncommitted in ${wt}`);
717
- closeRoot = path.join(outbox, "close");
718
- if (fs.existsSync(closeRoot))
719
- runGit(wt, ["worktree", "remove", "--force", closeRoot]);
720
- runGit(wt, ["worktree", "prune"]);
721
- if (!runGit(wt, ["worktree", "add", "--detach", closeRoot, "origin/dev"]).ok)
722
- return fail(`close worktree add failed — close bookkeeping left uncommitted in ${wt}`);
723
- unionLedgers(wt, closeRoot);
724
- }
725
- commitBookkeeping({
726
- root: closeRoot,
727
- month,
728
- fid: o.fid,
729
- scope: "full",
730
- mode: "commit-allow-empty",
731
- message: `docs(${o.fid}): ship DONE bkit [skip ci]`,
732
- }, ctx.log);
733
- const released = releaseLock(workflowLockPath(lockRoot(ctx.cwd, "ship", o.devPushes), month, o.fid), { workflow: "ship", fid: o.fid, token });
734
- if (released.removeFailed)
735
- return fail("Lock removal failed");
736
- if (o.devPushes) {
737
- if (!runGit(closeRoot, ["push", "origin", DEV]).ok) {
738
- ctx.log("dev push failed");
739
- return { code: EXIT_PUSH_FAILED, out };
893
+ switch (res.kind) {
894
+ case "landed":
895
+ landed = { ref: DEV, via: "head-push" };
896
+ break;
897
+ case "refused": {
898
+ const pr = viaPr;
899
+ if (pr === null || "failed" in pr) {
900
+ ctx.log(`${pr === null ? "close PR not attempted" : pr.failed} — ${kept}`);
901
+ return { code: EXIT_FLUSH_FAILED, out: null };
740
902
  }
741
- landed = { ref: DEV, via: "dev-push" };
903
+ landed = pr;
904
+ break;
742
905
  }
906
+ case "push-failed":
907
+ ctx.log(`dev push failed without a server answer: ${res.stderr} — ${kept}`);
908
+ return { code: EXIT_PUSH_FAILED, out };
909
+ case "exhausted":
910
+ ctx.log(`dev moved before each of ${res.attempts} pushes — ${kept}`);
911
+ return { code: EXIT_PUSH_FAILED, out };
912
+ case "fetch-failed":
913
+ ctx.log(`fetch of dev failed: ${res.stderr} — ${kept}`);
914
+ return { code: EXIT_FLUSH_FAILED, out: null };
915
+ case "setup-failed":
916
+ ctx.log(`throwaway checkout failed: ${res.stderr} — ${kept}`);
917
+ return { code: EXIT_FLUSH_FAILED, out: null };
743
918
  }
744
- finally {
745
- releaseLock(lock.path, { workflow: "ship", fid: o.fid, token: lock.token });
919
+ const released = releaseLock(workflowLockPath(root, month, o.fid), {
920
+ workflow: "ship",
921
+ fid: o.fid,
922
+ token,
923
+ });
924
+ if (released.removeFailed) {
925
+ ctx.log("Lock removal failed");
926
+ return { code: EXIT_FLUSH_FAILED, out: null };
746
927
  }
747
- if (!o.devPushes) {
748
- if (runGit(closeRoot, ["push", "origin", "HEAD:dev"]).ok) {
749
- landed = { ref: DEV, via: "head-push" };
928
+ // The book is on dev only once the close landed or its PR merged.
929
+ let worktree = null;
930
+ if (landed.via === "close-pr-open") {
931
+ ctx.log(`close PR not merged — ${kept} until it is`);
932
+ }
933
+ else {
934
+ if (landed.via === "close-pr" && !runGit(root, ["fetch", "origin", DEV]).ok)
935
+ ctx.log(`fetch of dev after the close PR failed — origin/${DEV} is stale until the next fetch`);
936
+ try {
937
+ worktree = removeWorktree(root, o.fid, o.branch, ctx.log);
750
938
  }
751
- else {
752
- // dev refused the push: publish the close commit through its own PR.
753
- const branch = `ship-close/${o.fid}`;
754
- const head = headSha(closeRoot);
755
- if (!runGit(closeRoot, ["push", "origin", `HEAD:refs/heads/${branch}`]).ok)
756
- return fail(`close branch push failed — close bookkeeping left in ${closeRoot}`);
757
- const created = runGh(closeRoot, [
758
- "pr",
759
- "create",
760
- "--base",
761
- DEV,
762
- "--head",
763
- branch,
764
- "--title",
765
- `docs(${o.fid}): ship DONE`,
766
- "--body",
767
- "",
768
- ]);
769
- if (!created.ok)
770
- return fail(`gh pr create failed: ${created.stderr}`);
771
- const pr = probePr(closeRoot, { head: branch, base: DEV, state: "open" });
772
- const number = pr.kind === "ok" ? pr.pr?.number : undefined;
773
- if (number === undefined)
774
- return fail(`close PR not found for ${branch}`);
775
- const merged = mergePr(closeRoot, {
776
- number: String(number),
777
- subject: `docs(${o.fid}): ship DONE bkit [skip ci]`,
778
- matchHead: head,
779
- deleteBranch: true,
780
- }, ctx.log);
781
- if (!merged.out.merged)
782
- ctx.log(`close PR #${number} opened but not merged — merge it by hand`);
783
- landed = { ref: branch, via: merged.out.merged ? "close-pr" : "close-pr-open" };
939
+ catch (err) {
940
+ ctx.log(`${err.message} — remove ${book} by hand`);
784
941
  }
785
- const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
786
- runGit(top, ["worktree", "remove", "--force", closeRoot]);
787
- runGit(top, ["worktree", "prune"]);
788
942
  }
789
- return { code: EXIT.OK, out: { ...out, closeRoot, landed } };
943
+ return { code: EXIT.OK, out: { ...out, landed, worktree } };
790
944
  }
791
945
  // ---------------------------------------------------------------------------
792
946
  // promote
@@ -917,11 +1071,6 @@ const MONTH_FLAG = {
917
1071
  type: "string",
918
1072
  help: "month bucket YYYYMM (default: the feature's bucket, else this UTC month)",
919
1073
  };
920
- const DEV_PUSHES_FLAG = {
921
- name: "dev-pushes",
922
- type: "boolean",
923
- help: "ship only: this runtime pushes to dev (logs book in the main checkout)",
924
- };
925
1074
  const STATUS_FILE_FLAG = {
926
1075
  name: "file",
927
1076
  type: "string",
@@ -951,7 +1100,6 @@ export const workflowsCommand = {
951
1100
  WORKFLOW_FLAG,
952
1101
  FID_FLAG,
953
1102
  MONTH_FLAG,
954
- DEV_PUSHES_FLAG,
955
1103
  STATUS_FILE_FLAG,
956
1104
  {
957
1105
  name: "lock-held",
@@ -975,7 +1123,6 @@ export const workflowsCommand = {
975
1123
  run: (ctx) => {
976
1124
  const workflow = workflowName(String(ctx.flags.workflow));
977
1125
  const fid = String(ctx.flags.fid);
978
- const devPushes = ctx.flags.devPushes === true;
979
1126
  const token = str(ctx.flags.token);
980
1127
  if (token !== undefined && ctx.flags.lockHeld !== true)
981
1128
  throw new CommandError(EXIT.USAGE, "--token applies with --lock-held only");
@@ -983,12 +1130,11 @@ export const workflowsCommand = {
983
1130
  workflow,
984
1131
  fid,
985
1132
  month: str(ctx.flags.month),
986
- devPushes,
987
1133
  file: str(ctx.flags.file),
988
1134
  });
989
1135
  let lock;
990
1136
  if (ctx.flags.lockHeld === true) {
991
- const file = workflowLockPath(lockRoot(ctx.cwd, workflow, devPushes), where.month, fid);
1137
+ const file = workflowLockPath(where.root, where.month, fid);
992
1138
  checkHeldLock(file, { workflow, fid, token });
993
1139
  lock = { path: file };
994
1140
  }
@@ -999,7 +1145,6 @@ export const workflowsCommand = {
999
1145
  workflow,
1000
1146
  fid,
1001
1147
  month: where.month,
1002
- devPushes,
1003
1148
  log: ctx.log,
1004
1149
  }),
1005
1150
  };
@@ -1036,7 +1181,6 @@ export const workflowsCommand = {
1036
1181
  WORKFLOW_FLAG,
1037
1182
  { ...FID_FLAG, required: false, help: "feature id (needed with --token)" },
1038
1183
  MONTH_FLAG,
1039
- DEV_PUSHES_FLAG,
1040
1184
  STATUS_FILE_FLAG,
1041
1185
  {
1042
1186
  ...TOKEN_FLAG,
@@ -1083,8 +1227,9 @@ export const workflowsCommand = {
1083
1227
  lock: "{path, existed, released, heldBy}: heldBy is another owner's lock line, left in place; null without --token",
1084
1228
  sentinels: "[{name, path}] sentinels that existed before this call removed them",
1085
1229
  handoverNeeded: "--max-exceeded, a sentinel existed, or a debug run in SOAK mode: write the abort handover",
1230
+ add: "labels in the set that the issue does not carry yet",
1086
1231
  labels: "the label set to write: the current labels plus bkit:failed (and bkit:merged for a merged ship PR)",
1087
- linearState: "the Linear state for the failed issue",
1232
+ trackerState: "the Linear or Jira state for the failed issue (null under github, none)",
1088
1233
  prState: "the --pr PR's state, or null",
1089
1234
  comment: "the failure comment body (with --step-number), else null",
1090
1235
  },
@@ -1095,7 +1240,7 @@ export const workflowsCommand = {
1095
1240
  run: failVerb,
1096
1241
  },
1097
1242
  handover: {
1098
- summary: "After the handover subagent: commit and abort-push it (--push), or ship's one-commit flush (--flush); print the handover comment.",
1243
+ summary: "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.",
1099
1244
  flags: [
1100
1245
  WORKFLOW_FLAG,
1101
1246
  FID_FLAG,
@@ -1103,12 +1248,12 @@ export const workflowsCommand = {
1103
1248
  {
1104
1249
  name: "push",
1105
1250
  type: "boolean",
1106
- help: "git add -A, commit `docs({fid}): {workflow} aborted bkit [skip ci]`, push --mode=abort",
1251
+ 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",
1107
1252
  },
1108
1253
  {
1109
1254
  name: "flush",
1110
1255
  type: "boolean",
1111
- help: "ship: copy the worktree's logs and ledgers into the book root, ONE FAILED commit, ONE push",
1256
+ 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",
1112
1257
  },
1113
1258
  {
1114
1259
  name: "open-pr",
@@ -1116,11 +1261,10 @@ export const workflowsCommand = {
1116
1261
  help: "--push: the open-PR answer from MCP (a number, or none) instead of asking gh",
1117
1262
  },
1118
1263
  { name: "ref", type: "string", help: "link the handover at this ref (no push / flush)" },
1119
- DEV_PUSHES_FLAG,
1120
1264
  {
1121
1265
  name: "worktree",
1122
1266
  type: "string",
1123
- help: "ship: the worktree holding the handover and the branch-side logs (default: cwd / .worktrees/{fid})",
1267
+ help: "the run's tree: holds the handover and the logs, and is where --push commits (default: cwd's checkout)",
1124
1268
  },
1125
1269
  OWNER_REPO_FLAG,
1126
1270
  ],
@@ -1128,15 +1272,14 @@ export const workflowsCommand = {
1128
1272
  handover: "the handover artifact, or null when absent",
1129
1273
  pushed: "the push (or flush push) ran and succeeded",
1130
1274
  ref: "where the handover now lives, or null when nothing was pushed",
1131
- skipped: "why nothing was pushed: open-pr | skip-ci | dev-lock-busy | nothing-to-commit (null otherwise)",
1275
+ skipped: "why nothing was pushed: open-pr | skip-ci | nothing-to-commit (null otherwise)",
1132
1276
  comment: "the handover comment body (null when there is no handover); links only when pushed",
1133
1277
  },
1134
1278
  exitCodes: {
1135
1279
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1136
- [EXIT_HANDOVER_MISSING]: "--push: the handover artifact is missing or empty (nothing committed)",
1137
1280
  [EXIT_OPEN_PR_KEPT]: "--push: the branch has an open PR, nothing pushed (the comment has no link)",
1138
- [EXIT_PUSH_FAILED]: "the push failed (the comment has no link)",
1139
- [EXIT_FLUSH_FAILED]: "--flush: not on dev after checkout, detached HEAD, or the FAILED commit failed",
1281
+ [EXIT_PUSH_FAILED]: "the push failed, or dev refused / kept moving under the FAILED landing (the comment has no link)",
1282
+ [EXIT_FLUSH_FAILED]: "the dev fetch, the throwaway checkout or the FAILED commit failed; the record stays in the run's tree",
1140
1283
  },
1141
1284
  run: handoverVerb,
1142
1285
  },
@@ -1146,7 +1289,6 @@ export const workflowsCommand = {
1146
1289
  WORKFLOW_FLAG,
1147
1290
  FID_FLAG,
1148
1291
  MONTH_FLAG,
1149
- DEV_PUSHES_FLAG,
1150
1292
  STATUS_FILE_FLAG,
1151
1293
  {
1152
1294
  name: "pr-number",
@@ -1195,9 +1337,14 @@ export const workflowsCommand = {
1195
1337
  {
1196
1338
  name: "flush",
1197
1339
  type: "boolean",
1198
- help: "ship: under the dev lock, close on dev (or a detached origin/dev worktree), commit `ship DONE`, release the lock (--token), push",
1340
+ 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",
1199
1341
  },
1200
1342
  { ...TOKEN_FLAG, help: "--flush: the workflow lock token to release" },
1343
+ {
1344
+ name: "branch",
1345
+ type: "string",
1346
+ help: "--flush: the shipped branch, deleted locally and on origin with the worktree once the close is on dev",
1347
+ },
1201
1348
  ],
1202
1349
  output: {
1203
1350
  row: "the appended workflow-done row",
@@ -1213,14 +1360,14 @@ export const workflowsCommand = {
1213
1360
  comment: "the close comment (--number with --outbox), else null",
1214
1361
  roadmapFoldNeeded: "always true: append the feature row and re-render the board (not run here)",
1215
1362
  featureStatus: "roadmap status this close moves the feature to",
1216
- closeRoot: "--flush: the checkout the close commit was made in",
1217
- landed: "--flush: {ref, via: dev-push | head-push | close-pr | close-pr-open}",
1363
+ landed: "--flush: {ref, via: head-push | close-pr | close-pr-open}",
1364
+ worktree: "--flush: the `bkit worktrees remove` result once the close is on dev; null while the close PR is unmerged or the removal failed",
1218
1365
  },
1219
1366
  exitCodes: {
1220
1367
  [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
1221
1368
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1222
- [EXIT_PUSH_FAILED]: "--flush: the dev push failed",
1223
- [EXIT_FLUSH_FAILED]: "--flush: not on dev after checkout, the dev fetch / close worktree failed, the lock stayed, or the close PR could not be opened",
1369
+ [EXIT_PUSH_FAILED]: "--flush: dev moved before every push, or the push failed without a server answer; the lock is kept",
1370
+ [EXIT_FLUSH_FAILED]: "--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",
1224
1371
  },
1225
1372
  run: async (ctx) => {
1226
1373
  const f = ctx.flags;
@@ -1228,7 +1375,6 @@ export const workflowsCommand = {
1228
1375
  workflow: String(f.workflow),
1229
1376
  fid: String(f.fid),
1230
1377
  month: str(f.month),
1231
- devPushes: f.devPushes === true,
1232
1378
  file: str(f.file),
1233
1379
  prNumber: positiveInt(f.prNumber, "pr-number"),
1234
1380
  squashSha: str(f.squashSha),
@@ -1246,7 +1392,7 @@ export const workflowsCommand = {
1246
1392
  if (f.flush === true) {
1247
1393
  if (input.workflow !== "ship")
1248
1394
  throw new CommandError(EXIT.USAGE, "--flush is ship only");
1249
- const r = await shipClose(ctx, input, str(f.token));
1395
+ const r = await shipClose(ctx, { ...input, branch: str(f.branch) }, str(f.token));
1250
1396
  if (r.out)
1251
1397
  ctx.emit(r.out);
1252
1398
  return r.code;