@cbartens/bkit 5.3.0 → 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 (128) hide show
  1. package/.bkit/README.md +3 -2
  2. package/.bkit/core/.agents/docs.md +1 -1
  3. package/.bkit/core/.agents/rules.md +8 -2
  4. package/.bkit/core/.bkit/README.md +2 -1
  5. package/.bkit/core/.bkit/cloud.md +33 -33
  6. package/.bkit/core/.bkit/comparison.md +1 -1
  7. package/.bkit/core/.bkit/install.md +6 -5
  8. package/.bkit/core/.bkit/lite.md +6 -6
  9. package/.bkit/core/.bkit/pipeline.md +4 -3
  10. package/.bkit/core/.bkit/prompts.md +4 -3
  11. package/.bkit/core/.bkit/providers.md +1 -1
  12. package/.bkit/core/.bkit/templates.md +35 -5
  13. package/.bkit/core/.bkit/trackers.md +7 -8
  14. package/.bkit/core/.bkit/workflows.md +106 -86
  15. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +3 -2
  16. package/.bkit/core/docs/templates/bkit-audit-adoption.md +1 -1
  17. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  18. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  19. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  20. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  21. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +1 -1
  22. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  23. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  24. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +4 -2
  25. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  26. package/.bkit/core/docs/templates/bkit-audit-cost.md +3 -2
  27. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  28. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -2
  29. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +5 -5
  30. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  31. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +14 -13
  32. package/.bkit/core/docs/templates/bkit-audit-documentation.md +1 -1
  33. package/.bkit/core/docs/templates/bkit-audit-duplication.md +2 -2
  34. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  35. package/.bkit/core/docs/templates/bkit-audit-flakes.md +3 -2
  36. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -2
  37. package/.bkit/core/docs/templates/bkit-audit-issues.md +3 -2
  38. package/.bkit/core/docs/templates/bkit-audit-llm.md +3 -2
  39. package/.bkit/core/docs/templates/bkit-audit-logs.md +10 -6
  40. package/.bkit/core/docs/templates/bkit-audit-models.md +1 -1
  41. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  42. package/.bkit/core/docs/templates/bkit-audit-prompts.md +5 -5
  43. package/.bkit/core/docs/templates/bkit-audit-red-team.md +3 -2
  44. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  45. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  46. package/.bkit/core/docs/templates/bkit-audit-security.md +11 -9
  47. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  48. package/.bkit/core/docs/templates/bkit-audit-testing.md +6 -5
  49. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  50. package/.bkit/core/engine/checks/status-holes.ts +0 -1
  51. package/.bkit/core/engine/checks/tips/catalogue.ts +16 -0
  52. package/.bkit/core/engine/checks/tips/index.ts +49 -27
  53. package/.bkit/core/engine/cli.ts +22 -15
  54. package/.bkit/core/engine/commands/comply.ts +25 -16
  55. package/.bkit/core/engine/commands/install/install.ts +11 -4
  56. package/.bkit/core/engine/commands/land.ts +156 -0
  57. package/.bkit/core/engine/commands/lib.ts +10 -8
  58. package/.bkit/core/engine/commands/registry.ts +2 -0
  59. package/.bkit/core/engine/commands/tips.ts +7 -3
  60. package/.bkit/core/engine/commands/workflow/branches.ts +382 -282
  61. package/.bkit/core/engine/commands/workflow/disk.ts +556 -0
  62. package/.bkit/core/engine/commands/workflow/issues.ts +73 -28
  63. package/.bkit/core/engine/commands/workflow/locks.ts +38 -152
  64. package/.bkit/core/engine/commands/workflow/prs.ts +11 -2
  65. package/.bkit/core/engine/commands/workflow/roadmap.ts +48 -53
  66. package/.bkit/core/engine/commands/workflow/runtime.ts +3 -2
  67. package/.bkit/core/engine/commands/workflow/status.ts +33 -11
  68. package/.bkit/core/engine/commands/workflow/steps.ts +24 -15
  69. package/.bkit/core/engine/commands/workflow/workflows.ts +433 -265
  70. package/.bkit/core/engine/commands/workflow/workstreams.ts +3 -2
  71. package/.bkit/core/engine/commands/workflow/worktrees.ts +11 -1
  72. package/.bkit/core/engine/install/modules/core.ts +15 -0
  73. package/.bkit/core/engine/install/placeholders.ts +13 -17
  74. package/.bkit/core/engine/shared/settings.ts +8 -0
  75. package/.bkit/core/engine/shared/timeouts.ts +8 -7
  76. package/.bkit/core/prompts/bkit-audit-generate.md +47 -4
  77. package/.bkit/core/prompts/bkit-utility-update-decisions.md +1 -1
  78. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +1 -1
  79. package/.bkit/core/prompts/bkit-utility-update-documentation.md +1 -1
  80. package/.bkit/core/prompts/bkit-utility-update-failures.md +1 -1
  81. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +1 -1
  82. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +3 -3
  83. package/.bkit/core/workflows/bkit-auto.md +2 -2
  84. package/.bkit/core/workflows/bkit-build.md +7 -7
  85. package/.bkit/core/workflows/bkit-debug.md +11 -11
  86. package/.bkit/core/workflows/bkit-design.md +20 -11
  87. package/.bkit/core/workflows/bkit-plan.md +23 -13
  88. package/.bkit/core/workflows/bkit-ship.md +82 -93
  89. package/.bkit/shared/.claude/bkit-cloud.md +12 -12
  90. package/.bkit/shared/.claude/settings.json +1 -0
  91. package/.bkit/shared/docs/deployments.md +29 -25
  92. package/.bkit/shared/gitignore +1 -2
  93. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +2 -2
  94. package/.bkit/templates/.github/workflows/bkit-ci.yml +7 -2
  95. package/.bkit/templates/.husky/pre-commit +6 -0
  96. package/.bkit/templates/.husky/pre-push +7 -0
  97. package/.bkit/templates/.lintstagedrc.json +5 -1
  98. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.machine.mjs +197 -0
  99. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +164 -0
  100. package/CHANGELOG.md +48 -0
  101. package/README.md +97 -96
  102. package/dist/checks/status-holes.js +0 -1
  103. package/dist/checks/tips/catalogue.js +14 -0
  104. package/dist/checks/tips/index.js +44 -28
  105. package/dist/cli.js +22 -16
  106. package/dist/commands/comply.js +20 -13
  107. package/dist/commands/install/install.js +10 -4
  108. package/dist/commands/land.js +129 -0
  109. package/dist/commands/lib.js +9 -6
  110. package/dist/commands/registry.js +2 -0
  111. package/dist/commands/tips.js +7 -3
  112. package/dist/commands/workflow/branches.js +300 -243
  113. package/dist/commands/workflow/disk.js +452 -0
  114. package/dist/commands/workflow/issues.js +63 -27
  115. package/dist/commands/workflow/locks.js +35 -130
  116. package/dist/commands/workflow/prs.js +5 -2
  117. package/dist/commands/workflow/roadmap.js +49 -56
  118. package/dist/commands/workflow/runtime.js +3 -2
  119. package/dist/commands/workflow/status.js +32 -12
  120. package/dist/commands/workflow/steps.js +18 -11
  121. package/dist/commands/workflow/workflows.js +388 -247
  122. package/dist/commands/workflow/workstreams.js +3 -2
  123. package/dist/commands/workflow/worktrees.js +11 -1
  124. package/dist/install/modules/core.js +13 -0
  125. package/dist/install/placeholders.js +13 -19
  126. package/dist/shared/settings.js +5 -0
  127. package/dist/shared/timeouts.js +8 -7
  128. package/package.json +1 -1
@@ -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,13 +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
45
  DEV,
46
46
  EXIT,
47
47
  git,
48
+ isSharedBranch,
48
49
  parseJson,
49
50
  repoRoot,
50
51
  runGh,
@@ -68,9 +69,7 @@ import { EXIT_EMPTY, commitBookkeeping, unionLedgers } from "./ledgers.js";
68
69
  import {
69
70
  EXIT_REMOVE_FAILED,
70
71
  EXIT_SPLIT_BUCKET,
71
- acquireDevLock,
72
72
  acquireWorkflowLock,
73
- lockRoot,
74
73
  owns,
75
74
  readHolder,
76
75
  releaseLock,
@@ -89,14 +88,13 @@ import {
89
88
  str,
90
89
  } from "./status.js";
91
90
  import { writeStepRow } from "./steps.js";
91
+ import { removeWorktree, type RemoveResult } from "./worktrees.js";
92
92
 
93
93
  /** Sentinels a workflow leaves in its logs folder; either one existing means a handover is due. */
94
94
  export const SENTINELS = [".rebase-failed", ".deferred-blocked"] as const;
95
95
 
96
96
  /** Exit code (start --lock-held): the lock is missing or belongs to another owner. */
97
97
  export const EXIT_LOCK_NOT_HELD = 6;
98
- /** Exit code (handover --push): the handover artifact is missing or empty. */
99
- export const EXIT_HANDOVER_MISSING = 8;
100
98
  /** Exit code (handover --push): the branch has an open PR, so nothing was pushed. */
101
99
  export const EXIT_OPEN_PR_KEPT = 9;
102
100
  /** Exit code (handover, close --flush): a push failed. */
@@ -113,7 +111,7 @@ export const EXIT_NO_VERSION = 12;
113
111
  interface Where {
114
112
  root: string;
115
113
  month: string;
116
- /** 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. */
117
115
  tree: string;
118
116
  status: string;
119
117
  }
@@ -127,20 +125,14 @@ function workflowName(workflow: string): string {
127
125
  return workflow;
128
126
  }
129
127
 
130
- /**
131
- * start and close work in the current tree (ship: its book root), the root
132
- * `git rev-parse --show-toplevel` reports.
133
- */
128
+ /** start and close work in the current tree, the root `git rev-parse --show-toplevel` reports. */
134
129
  function whereInTree(
135
130
  cwd: string,
136
- o: { workflow: string; fid: string; month?: string; devPushes: boolean; file?: string },
131
+ o: { workflow: string; fid: string; month?: string; file?: string },
137
132
  ): Where {
138
133
  const root = repoRoot(cwd);
139
134
  const month = resolveMonth(root, o.fid, o.month);
140
- const tree =
141
- o.workflow === "ship"
142
- ? lockRoot(cwd, o.workflow, o.devPushes)
143
- : (git(cwd, ["rev-parse", "--show-toplevel"]) ?? root);
135
+ const tree = git(cwd, ["rev-parse", "--show-toplevel"]) ?? root;
144
136
  const status = o.file ? path.resolve(cwd, o.file) : path.join(tree, statusRelPath(month, o.fid));
145
137
  return { root, month, tree, status };
146
138
  }
@@ -181,13 +173,12 @@ function abortRebase(tree: string, log: (m: string) => void): boolean {
181
173
 
182
174
  /** The workflow-failed state: row, rebase abort, lock release, sentinels. */
183
175
  function failState(ctx: RunContext, workflow: string, fid: string) {
184
- const devPushes = ctx.flags.devPushes === true;
185
176
  const root = repoRoot(ctx.cwd);
186
177
  const month = resolveMonth(root, fid, str(ctx.flags.month) || undefined);
187
178
  const file = str(ctx.flags.file) || undefined;
188
179
  const status = file
189
180
  ? path.resolve(ctx.cwd, file)
190
- : statusLocation({ cwd: ctx.cwd, workflow, fid, month, devPushes }).path;
181
+ : statusLocation({ cwd: ctx.cwd, workflow, fid, month }).path;
191
182
 
192
183
  // The run's own tree: the feature worktree when there is one, else this checkout.
193
184
  // Never the main checkout behind a worktree, where a rebase would be a human's.
@@ -210,7 +201,7 @@ function failState(ctx: RunContext, workflow: string, fid: string) {
210
201
  ctx.log(`${status} does not exist — no workflow-failed row written`);
211
202
  }
212
203
 
213
- const lockFile = workflowLockPath(lockRoot(ctx.cwd, workflow, devPushes), month, fid);
204
+ const lockFile = workflowLockPath(root, month, fid);
214
205
  const { removeFailed, ...lock } = releaseLock(lockFile, {
215
206
  workflow,
216
207
  fid,
@@ -221,7 +212,7 @@ function failState(ctx: RunContext, workflow: string, fid: string) {
221
212
  if (removeFailed) ctx.log(`lock removal failed: ${lockFile}`);
222
213
 
223
214
  // Each sentinel is cleared where it was created: `.rebase-failed` in the run's
224
- // tree, `.deferred-blocked` beside status.jsonl (ship: the book root).
215
+ // tree, `.deferred-blocked` beside status.jsonl.
225
216
  const logDirs = new Set([path.join(tree, logDirRel(month, fid)), path.dirname(status)]);
226
217
  const sentinels: Array<{ name: string; path: string }> = [];
227
218
  for (const dir of logDirs) {
@@ -313,101 +304,261 @@ function readText(cwd: string, rel: string): string {
313
304
  // handover
314
305
  // ---------------------------------------------------------------------------
315
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
+
316
330
  /**
317
- * Ship's Failure Path flush: copy branch-side logs and ledger rows into the book
318
- * root, then ONE `chore({fid}): ship FAILED bkit [skip ci]` commit and ONE push —
319
- * 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).
320
333
  */
321
- async function shipFlush(
322
- ctx: RunContext,
323
- o: { fid: string; month: string; devPushes: boolean; worktree?: string },
324
- ): Promise<{ code: number; pushed: boolean; ref: string | null; skipped: string | null }> {
325
- const root = repoRoot(ctx.cwd);
326
- const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
327
- 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 {
328
365
  const rel = logDirRel(o.month, o.fid);
329
- const src = o.worktree ?? path.join(root, ".worktrees", o.fid);
330
- if (fs.existsSync(path.join(src, rel)) && path.resolve(src) !== path.resolve(bookRoot)) {
331
- fs.mkdirSync(path.join(bookRoot, rel), { recursive: true });
332
- for (const f of fs.readdirSync(path.join(src, rel)).filter((n) => n.endsWith(".md"))) {
333
- const to = path.join(bookRoot, rel, f);
334
- if (!fs.existsSync(to)) fs.copyFileSync(path.join(src, rel, f), to);
335
- }
336
- 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;
337
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
+ }
338
404
 
339
- let wt = bookRoot;
340
- let target = "";
341
- let release: (() => void) | undefined;
342
- if (o.devPushes) {
343
- let lock: { path: string; token: string };
344
- try {
345
- lock = await acquireDevLock({
346
- cwd: root,
347
- workflow: "ship",
348
- fid: o.fid,
349
- deadlineS: 60,
350
- log: ctx.log,
351
- });
352
- } catch {
353
- // Busy: the FAILED record rides along on the next dev commit; never a second failure.
354
- ctx.log(`dev lock busy — ship FAILED bookkeeping left uncommitted in ${bookRoot}`);
355
- return { code: EXIT.OK, pushed: false, ref: null, skipped: "dev-lock-busy" };
356
- }
357
- release = () => releaseLock(lock.path, { workflow: "ship", fid: o.fid, token: lock.token });
358
- runGit(root, ["checkout", DEV]);
359
- if (git(root, ["branch", "--show-current"]) !== DEV) {
360
- release();
361
- ctx.log(`not on dev after checkout — FAILED bookkeeping left uncommitted in ${bookRoot}`);
362
- return { code: EXIT_FLUSH_FAILED, pushed: false, ref: null, skipped: null };
363
- }
364
- runGit(root, ["pull", "--ff-only", "origin", DEV]);
365
- wt = root;
366
- target = DEV;
367
- } else {
368
- ctx.log("RUNTIME_DEVPUSHES=false — the FAILED record commits on the current branch");
369
- 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);
370
430
  }
371
- try {
372
- if (target === "") {
373
- ctx.log(`push target empty (detached HEAD?) — bookkeeping left uncommitted in ${wt}`);
374
- 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;
375
436
  }
376
- const before = headSha(wt);
377
- try {
378
- commitBookkeeping(
379
- {
380
- root: wt,
381
- month: o.month,
382
- fid: o.fid,
383
- scope: "full",
384
- mode: "commit",
385
- message: `chore(${o.fid}): ship FAILED bkit [skip ci]`,
386
- },
387
- ctx.log,
388
- );
389
- } catch (err) {
390
- if (err instanceof CommandError && err.code === EXIT_EMPTY) {
391
- ctx.log("no bookkeeping delta to record — nothing committed, nothing pushed");
392
- 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;
393
454
  }
394
- ctx.log(
395
- `bookkeeping commit failed — FAILED bookkeeping left uncommitted in ${wt}: ${(err as Error).message}`,
396
- );
397
- return { code: EXIT_FLUSH_FAILED, pushed: false, ref: null, skipped: null };
398
- }
399
- 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) {
400
544
  ctx.log("no bookkeeping delta to record — nothing committed, nothing pushed");
401
545
  return { code: EXIT.OK, pushed: false, ref: null, skipped: "nothing-to-commit" };
402
546
  }
403
- const push = runGit(wt, ["push", "origin", target]);
404
- if (!push.ok) {
405
- ctx.log(`git push origin ${target} failed: ${push.stderr}`);
406
- return { code: EXIT_PUSH_FAILED, pushed: false, ref: null, skipped: null };
407
- }
408
- return { code: EXIT.OK, pushed: true, ref: target, skipped: null };
409
- } finally {
410
- 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}`);
411
562
  }
412
563
  }
413
564
 
@@ -429,19 +580,24 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
429
580
  let ref = str(ctx.flags.ref) ?? null;
430
581
  let pushed = false;
431
582
  let skipped: string | null = null;
432
- if (push) {
433
- if (!present) {
434
- ctx.log(`${artifact} is missing or empty — nothing to hand over`);
435
- return EXIT_HANDOVER_MISSING;
436
- }
437
- runGit(ctx.cwd, ["add", "-A"]);
438
- const made = runGit(ctx.cwd, [
439
- "commit",
440
- "-m",
441
- `docs(${fid}): ${workflow} aborted bkit [skip ci]`,
442
- ]);
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]`]);
443
599
  if (!made.ok) ctx.log(`abort commit: ${made.stderr || made.stdout}`);
444
- 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);
445
601
  if (r.code === EXIT.USE_MCP) return r.code;
446
602
  pushed = r.out.pushed;
447
603
  ref = r.out.ref;
@@ -453,12 +609,8 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
453
609
  ? EXIT_OPEN_PR_KEPT
454
610
  : EXIT_PUSH_FAILED;
455
611
  } else if (flush) {
456
- const r = await shipFlush(ctx, {
457
- fid,
458
- month,
459
- devPushes: ctx.flags.devPushes === true,
460
- worktree: worktree === undefined ? undefined : base,
461
- });
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 };
462
614
  code = r.code;
463
615
  pushed = r.pushed;
464
616
  ref = r.ref;
@@ -475,6 +627,7 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
475
627
  bodyFile: artifact,
476
628
  })
477
629
  : null;
630
+ if (handed !== undefined) handBack(tree, handed.sha, handed.carried, ctx.log);
478
631
  ctx.emit({
479
632
  handover: present ? artifact : null,
480
633
  pushed,
@@ -675,7 +828,6 @@ export interface CloseInput {
675
828
  workflow: string;
676
829
  fid: string;
677
830
  month?: string;
678
- devPushes: boolean;
679
831
  file?: string;
680
832
  prNumber?: number;
681
833
  squashSha?: string;
@@ -709,7 +861,7 @@ export function closeWorkflow(
709
861
  throw new CommandError(EXIT.USAGE, `--squash-sha "${o.squashSha}" is not a commit sha`);
710
862
 
711
863
  // Graded first, so the report below carries this run's grade.
712
- const violations = gradeCompliance(where.tree, workflow, log);
864
+ const violations = gradeCompliance(where.tree, workflow, log, o.squashSha);
713
865
 
714
866
  const step = `${workflow}-close-workflow`;
715
867
  if (o.recordStep === true) {
@@ -857,128 +1009,152 @@ export function closeWorkflow(
857
1009
  }
858
1010
 
859
1011
  /**
860
- * Ship's close: under the dev lock, on dev (this runtime pushes it) or on a
861
- * detached `origin/dev` worktree in the outbox (it does not), run the close, commit
862
- * `docs({fid}): ship DONE bkit [skip ci]`, release the workflow lock, then land the
863
- * commit — push dev, push `HEAD:dev`, or, when that is refused, a `ship-close/{fid}`
864
- * 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.
865
1014
  */
866
- async function shipClose(ctx: RunContext, o: CloseInput, token: string | undefined) {
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.
1058
+ */
1059
+ async function shipClose(
1060
+ ctx: RunContext,
1061
+ o: CloseInput & { branch?: string },
1062
+ token: string | undefined,
1063
+ ) {
867
1064
  const root = repoRoot(ctx.cwd);
868
- const outbox = o.outbox === undefined ? undefined : path.resolve(ctx.cwd, o.outbox);
869
- if (outbox === undefined) throw new CommandError(EXIT.USAGE, "--flush needs --outbox");
1065
+ if (o.outbox === undefined) throw new CommandError(EXIT.USAGE, "--flush needs --outbox");
870
1066
  const month = resolveMonth(root, o.fid, o.month);
871
- const lock = await acquireDevLock({
872
- cwd: root,
873
- workflow: "ship",
874
- fid: o.fid,
875
- deadlineS: TIMEOUTS.SHIP_DEV_LOCK_ACQUIRE_DEADLINE_S,
876
- log: ctx.log,
877
- });
878
- const fail = (why: string) => {
879
- ctx.log(why);
880
- return { code: EXIT_FLUSH_FAILED, out: null as Record<string, unknown> | null };
881
- };
882
- let closeRoot = "";
883
- let landed: { ref: string; via: string } | null = null;
884
- 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;
885
1074
  try {
886
- let wt: string;
887
- if (o.devPushes) {
888
- runGit(root, ["checkout", DEV]);
889
- if (git(root, ["branch", "--show-current"]) !== DEV)
890
- return fail("not on dev after checkout — aborting dev ops");
891
- wt = root;
892
- } else {
893
- ctx.log(
894
- "RUNTIME_DEVPUSHES=false — the close commit lands through a detached origin/dev worktree",
895
- );
896
- wt = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
897
- }
898
- out = closeWorkflow(wt, { ...o, recordStep: true, message: undefined }, ctx.log);
899
- if (o.devPushes) {
900
- closeRoot = wt;
901
- } else {
902
- if (!runGit(wt, ["fetch", "origin", DEV]).ok)
903
- return fail(`fetch origin dev failed — close bookkeeping left uncommitted in ${wt}`);
904
- closeRoot = path.join(outbox, "close");
905
- if (fs.existsSync(closeRoot)) runGit(wt, ["worktree", "remove", "--force", closeRoot]);
906
- runGit(wt, ["worktree", "prune"]);
907
- if (!runGit(wt, ["worktree", "add", "--detach", closeRoot, "origin/dev"]).ok)
908
- return fail(`close worktree add failed — close bookkeeping left uncommitted in ${wt}`);
909
- unionLedgers(wt, closeRoot);
910
- }
911
- commitBookkeeping(
912
- {
913
- root: closeRoot,
914
- month,
915
- fid: o.fid,
916
- scope: "full",
917
- mode: "commit-allow-empty",
918
- 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
+ );
919
1091
  },
920
- ctx.log,
921
- );
922
- const released = releaseLock(
923
- workflowLockPath(lockRoot(ctx.cwd, "ship", o.devPushes), month, o.fid),
924
- { workflow: "ship", fid: o.fid, token },
925
- );
926
- if (released.removeFailed) return fail("Lock removal failed");
927
- if (o.devPushes) {
928
- if (!runGit(closeRoot, ["push", "origin", DEV]).ok) {
929
- ctx.log("dev push failed");
930
- 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 };
931
1114
  }
932
- landed = { ref: DEV, via: "dev-push" };
1115
+ landed = pr;
1116
+ break;
933
1117
  }
934
- } finally {
935
- 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 };
936
1130
  }
937
1131
 
938
- if (!o.devPushes) {
939
- if (runGit(closeRoot, ["push", "origin", "HEAD:dev"]).ok) {
940
- landed = { ref: DEV, via: "head-push" };
941
- } else {
942
- // dev refused the push: publish the close commit through its own PR.
943
- const branch = `ship-close/${o.fid}`;
944
- const head = headSha(closeRoot);
945
- if (!runGit(closeRoot, ["push", "origin", `HEAD:refs/heads/${branch}`]).ok)
946
- return fail(`close branch push failed — close bookkeeping left in ${closeRoot}`);
947
- const created = runGh(closeRoot, [
948
- "pr",
949
- "create",
950
- "--base",
951
- DEV,
952
- "--head",
953
- branch,
954
- "--title",
955
- `docs(${o.fid}): ship DONE`,
956
- "--body",
957
- "",
958
- ]);
959
- if (!created.ok) return fail(`gh pr create failed: ${created.stderr}`);
960
- const pr = probePr(closeRoot, { head: branch, base: DEV, state: "open" });
961
- const number = pr.kind === "ok" ? pr.pr?.number : undefined;
962
- if (number === undefined) return fail(`close PR not found for ${branch}`);
963
- const merged = mergePr(
964
- closeRoot,
965
- {
966
- number: String(number),
967
- subject: `docs(${o.fid}): ship DONE bkit [skip ci]`,
968
- matchHead: head,
969
- deleteBranch: true,
970
- },
971
- 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`,
972
1150
  );
973
- if (!merged.out.merged)
974
- ctx.log(`close PR #${number} opened but not merged — merge it by hand`);
975
- 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`);
976
1155
  }
977
- const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? root;
978
- runGit(top, ["worktree", "remove", "--force", closeRoot]);
979
- runGit(top, ["worktree", "prune"]);
980
1156
  }
981
- return { code: EXIT.OK, out: { ...out, closeRoot, landed } };
1157
+ return { code: EXIT.OK, out: { ...out, landed, worktree } };
982
1158
  }
983
1159
 
984
1160
  // ---------------------------------------------------------------------------
@@ -1124,11 +1300,6 @@ const MONTH_FLAG: FlagSpec = {
1124
1300
  type: "string",
1125
1301
  help: "month bucket YYYYMM (default: the feature's bucket, else this UTC month)",
1126
1302
  };
1127
- const DEV_PUSHES_FLAG: FlagSpec = {
1128
- name: "dev-pushes",
1129
- type: "boolean",
1130
- help: "ship only: this runtime pushes to dev (logs book in the main checkout)",
1131
- };
1132
1303
  const STATUS_FILE_FLAG: FlagSpec = {
1133
1304
  name: "file",
1134
1305
  type: "string",
@@ -1159,7 +1330,6 @@ export const workflowsCommand: CommandSpec = {
1159
1330
  WORKFLOW_FLAG,
1160
1331
  FID_FLAG,
1161
1332
  MONTH_FLAG,
1162
- DEV_PUSHES_FLAG,
1163
1333
  STATUS_FILE_FLAG,
1164
1334
  {
1165
1335
  name: "lock-held",
@@ -1183,7 +1353,6 @@ export const workflowsCommand: CommandSpec = {
1183
1353
  run: (ctx) => {
1184
1354
  const workflow = workflowName(String(ctx.flags.workflow));
1185
1355
  const fid = String(ctx.flags.fid);
1186
- const devPushes = ctx.flags.devPushes === true;
1187
1356
  const token = str(ctx.flags.token);
1188
1357
  if (token !== undefined && ctx.flags.lockHeld !== true)
1189
1358
  throw new CommandError(EXIT.USAGE, "--token applies with --lock-held only");
@@ -1191,13 +1360,12 @@ export const workflowsCommand: CommandSpec = {
1191
1360
  workflow,
1192
1361
  fid,
1193
1362
  month: str(ctx.flags.month),
1194
- devPushes,
1195
1363
  file: str(ctx.flags.file),
1196
1364
  });
1197
1365
 
1198
1366
  let lock: Record<string, unknown>;
1199
1367
  if (ctx.flags.lockHeld === true) {
1200
- const file = workflowLockPath(lockRoot(ctx.cwd, workflow, devPushes), where.month, fid);
1368
+ const file = workflowLockPath(where.root, where.month, fid);
1201
1369
  checkHeldLock(file, { workflow, fid, token });
1202
1370
  lock = { path: file };
1203
1371
  } else {
@@ -1207,7 +1375,6 @@ export const workflowsCommand: CommandSpec = {
1207
1375
  workflow,
1208
1376
  fid,
1209
1377
  month: where.month,
1210
- devPushes,
1211
1378
  log: ctx.log,
1212
1379
  }),
1213
1380
  };
@@ -1246,7 +1413,6 @@ export const workflowsCommand: CommandSpec = {
1246
1413
  WORKFLOW_FLAG,
1247
1414
  { ...FID_FLAG, required: false, help: "feature id (needed with --token)" },
1248
1415
  MONTH_FLAG,
1249
- DEV_PUSHES_FLAG,
1250
1416
  STATUS_FILE_FLAG,
1251
1417
  {
1252
1418
  ...TOKEN_FLAG,
@@ -1309,7 +1475,7 @@ export const workflowsCommand: CommandSpec = {
1309
1475
  },
1310
1476
  handover: {
1311
1477
  summary:
1312
- "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.",
1313
1479
  flags: [
1314
1480
  WORKFLOW_FLAG,
1315
1481
  FID_FLAG,
@@ -1317,12 +1483,12 @@ export const workflowsCommand: CommandSpec = {
1317
1483
  {
1318
1484
  name: "push",
1319
1485
  type: "boolean",
1320
- 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",
1321
1487
  },
1322
1488
  {
1323
1489
  name: "flush",
1324
1490
  type: "boolean",
1325
- 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",
1326
1492
  },
1327
1493
  {
1328
1494
  name: "open-pr",
@@ -1330,11 +1496,10 @@ export const workflowsCommand: CommandSpec = {
1330
1496
  help: "--push: the open-PR answer from MCP (a number, or none) instead of asking gh",
1331
1497
  },
1332
1498
  { name: "ref", type: "string", help: "link the handover at this ref (no push / flush)" },
1333
- DEV_PUSHES_FLAG,
1334
1499
  {
1335
1500
  name: "worktree",
1336
1501
  type: "string",
1337
- 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)",
1338
1503
  },
1339
1504
  OWNER_REPO_FLAG,
1340
1505
  ],
@@ -1342,20 +1507,18 @@ export const workflowsCommand: CommandSpec = {
1342
1507
  handover: "the handover artifact, or null when absent",
1343
1508
  pushed: "the push (or flush push) ran and succeeded",
1344
1509
  ref: "where the handover now lives, or null when nothing was pushed",
1345
- skipped:
1346
- "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)",
1347
1511
  comment:
1348
1512
  "the handover comment body (null when there is no handover); links only when pushed",
1349
1513
  },
1350
1514
  exitCodes: {
1351
1515
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1352
- [EXIT_HANDOVER_MISSING]:
1353
- "--push: the handover artifact is missing or empty (nothing committed)",
1354
1516
  [EXIT_OPEN_PR_KEPT]:
1355
1517
  "--push: the branch has an open PR, nothing pushed (the comment has no link)",
1356
- [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)",
1357
1520
  [EXIT_FLUSH_FAILED]:
1358
- "--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",
1359
1522
  },
1360
1523
  run: handoverVerb,
1361
1524
  },
@@ -1366,7 +1529,6 @@ export const workflowsCommand: CommandSpec = {
1366
1529
  WORKFLOW_FLAG,
1367
1530
  FID_FLAG,
1368
1531
  MONTH_FLAG,
1369
- DEV_PUSHES_FLAG,
1370
1532
  STATUS_FILE_FLAG,
1371
1533
  {
1372
1534
  name: "pr-number",
@@ -1415,9 +1577,14 @@ export const workflowsCommand: CommandSpec = {
1415
1577
  {
1416
1578
  name: "flush",
1417
1579
  type: "boolean",
1418
- 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",
1419
1581
  },
1420
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
+ },
1421
1588
  ],
1422
1589
  output: {
1423
1590
  row: "the appended workflow-done row",
@@ -1437,15 +1604,17 @@ export const workflowsCommand: CommandSpec = {
1437
1604
  roadmapFoldNeeded:
1438
1605
  "always true: append the feature row and re-render the board (not run here)",
1439
1606
  featureStatus: "roadmap status this close moves the feature to",
1440
- closeRoot: "--flush: the checkout the close commit was made in",
1441
- 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",
1442
1610
  },
1443
1611
  exitCodes: {
1444
1612
  [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
1445
1613
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1446
- [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",
1447
1616
  [EXIT_FLUSH_FAILED]:
1448
- "--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",
1449
1618
  },
1450
1619
  run: async (ctx) => {
1451
1620
  const f = ctx.flags;
@@ -1453,7 +1622,6 @@ export const workflowsCommand: CommandSpec = {
1453
1622
  workflow: String(f.workflow),
1454
1623
  fid: String(f.fid),
1455
1624
  month: str(f.month),
1456
- devPushes: f.devPushes === true,
1457
1625
  file: str(f.file),
1458
1626
  prNumber: positiveInt(f.prNumber, "pr-number"),
1459
1627
  squashSha: str(f.squashSha),
@@ -1470,7 +1638,7 @@ export const workflowsCommand: CommandSpec = {
1470
1638
  };
1471
1639
  if (f.flush === true) {
1472
1640
  if (input.workflow !== "ship") throw new CommandError(EXIT.USAGE, "--flush is ship only");
1473
- const r = await shipClose(ctx, input, str(f.token));
1641
+ const r = await shipClose(ctx, { ...input, branch: str(f.branch) }, str(f.token));
1474
1642
  if (r.out) ctx.emit(r.out);
1475
1643
  return r.code;
1476
1644
  }