@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
@@ -28,18 +28,25 @@ import {
28
28
  runGit,
29
29
  SKIP_CI_TOKEN,
30
30
  type CommandSpec,
31
- type FlagValue,
32
31
  type RunContext,
33
32
  } from "../lib.js";
34
33
  import { bkitVersionStatus, type BkitVersionStatus } from "../../shared/bkit-latest.js";
34
+ import { landBackoffMs, landDir, pushToDev, sleep } from "../land.js";
35
35
  import { TIMEOUTS } from "../../shared/timeouts.js";
36
36
  import { commitBookkeeping } from "./ledgers.js";
37
- import { acquireDevLock, lockRoot, releaseLock, resolveMonth, workflowLockPath } from "./locks.js";
38
- import { closeTransportRow, crossCheckFile, mergePr, openPrFor, probePr } from "./prs.js";
37
+ import { releaseLock, resolveMonth, workflowLockPath } from "./locks.js";
38
+ import {
39
+ closeTransportRow,
40
+ crossCheckRows,
41
+ mergePr,
42
+ openPrFor,
43
+ probePr,
44
+ updateBranch,
45
+ } from "./prs.js";
39
46
  import { appendFeature } from "./roadmap.js";
40
47
  import { detect } from "./runtime.js";
41
- import { readStatusRows } from "./status.js";
42
- import { removeWorktree } from "./worktrees.js";
48
+ import { readStatusRows, readStatusRowsAt } from "./status.js";
49
+ import { removeWorktree, worktreeDir } from "./worktrees.js";
43
50
  import {
44
51
  COULD_NOT_RUN_EXIT_CODES,
45
52
  LOCKFILE_REGENERATE,
@@ -62,8 +69,6 @@ export const EXIT_FETCH_FAILED = 10;
62
69
  export const EXIT_MERGE_CONFLICT = 11;
63
70
  export const EXIT_ANCHOR_SKIP = 12;
64
71
  export const EXIT_NO_FILE = 13;
65
- export const EXIT_PULL_FAILED = 14;
66
- export const EXIT_RUNTIME_REFUSED = 15;
67
72
  export const EXIT_INSTALL_FAILED = 16;
68
73
  export const EXIT_LAND_STOPPED = 17;
69
74
  export const EXIT_LANDED_UNVERIFIED = 18;
@@ -110,12 +115,6 @@ function rebaseInProgress(top: string): boolean {
110
115
 
111
116
  const currentBranch = (cwd: string) => git(cwd, ["branch", "--show-current"]) ?? "";
112
117
 
113
- const boolString = (v: FlagValue, flag: string): boolean => {
114
- if (v === "true") return true;
115
- if (v === "false") return false;
116
- throw new CommandError(EXIT.USAGE, `--${flag} must be true or false, got "${String(v)}"`);
117
- };
118
-
119
118
  // ---------------------------------------------------------------------------
120
119
  // Conflict classification and resolution (rebase, and sync's docs merge)
121
120
  // ---------------------------------------------------------------------------
@@ -763,102 +762,30 @@ function syncVerb(ctx: RunContext): number {
763
762
  return EXIT.OK;
764
763
  }
765
764
 
766
- async function switchVerb(ctx: RunContext): Promise<number> {
767
- const devPushes = boolString(ctx.flags.devPushes, "dev-pushes");
768
- const worktrees = boolString(ctx.flags.worktrees, "worktrees");
765
+ /**
766
+ * Ship Step 13: after the merge, bring local dev up to origin/dev by a pure
767
+ * fast-forward without checking anything out, then a frozen install when the
768
+ * main checkout is on dev and moved. Never pushes.
769
+ */
770
+ function syncDevVerb(ctx: RunContext): number {
769
771
  const root = repoRoot(ctx.cwd);
770
- // `bkit install` can leave core.bare=true on the main checkout, which breaks every checkout below.
772
+ // `bkit install` can leave core.bare=true on the main checkout, which breaks `merge --ff-only` there.
771
773
  if (
772
774
  git(root, ["config", "--get", "core.bare"]) === "true" &&
773
775
  fs.statSync(path.join(root, ".git"), { throwIfNoEntry: false })?.isDirectory()
774
776
  ) {
775
777
  runGit(root, ["config", "core.bare", "false"]);
776
778
  }
777
- const out = {
778
- switched: false,
779
- branch: currentBranch(root),
780
- ahead: 0,
781
- pushed: false,
782
- installed: null as boolean | null,
783
- skipped: null as string | null,
784
- };
785
- if (!devPushes) {
786
- ctx.log(
787
- `this runtime does not push ${DEV} — skipping the local ${DEV} checkout; the merge already landed server-side`,
788
- );
789
- ctx.emit({ ...out, skipped: "dev-pushes-false" });
790
- return EXIT.OK;
791
- }
792
- if (!worktrees) {
793
- ctx.log(
794
- "refusing a local dev checkout in a runtime without worktrees (devPushes=true, worktrees=false)",
795
- );
796
- return EXIT_RUNTIME_REFUSED;
797
- }
798
- const fid = String(ctx.flags.fid);
799
- // Still held at the deadline: acquireDevLock throws EXIT.NO naming the holder.
800
- const lock = await acquireDevLock({
801
- cwd: root,
802
- workflow: "ship",
803
- fid,
804
- deadlineS: TIMEOUTS.SHIP_DEV_LOCK_ACQUIRE_DEADLINE_S,
805
- log: ctx.log,
806
- });
807
- try {
808
- runGit(root, ["checkout", DEV]);
809
- out.branch = currentBranch(root);
810
- if (out.branch !== DEV) {
811
- ctx.log(`not on ${DEV} after checkout (on '${out.branch}') — aborting dev ops`);
812
- return EXIT_NOT_DEV;
813
- }
814
- out.switched = true;
815
- const fetch = runGit(root, ["fetch", REMOTE, DEV]);
816
- if (!fetch.ok) {
817
- ctx.log(`git fetch ${REMOTE} ${DEV} failed: ${fetch.stderr}`);
818
- return EXIT_FETCH_FAILED;
819
- }
820
- out.ahead = Number(git(root, ["rev-list", "--count", `${UPSTREAM}..${DEV}`]) ?? "0");
821
- if (out.ahead > 0) {
822
- const triggering = (git(root, ["log", "--format=%h %s", `${UPSTREAM}..${DEV}`]) ?? "")
823
- .split("\n")
824
- .filter((l) => l !== "" && !SKIP_CI_TOKEN.test(l));
825
- if (triggering.length > 0) {
826
- ctx.log(
827
- `local ${DEV} is ${out.ahead} commit(s) ahead of ${UPSTREAM}, ${triggering.length} of them would run CI:`,
828
- );
829
- for (const l of triggering) ctx.log(` ${l}`);
830
- ctx.log(
831
- `ship will not push these: a CI run on ${DEV} can cancel the in-flight run validating this merge`,
832
- );
833
- ctx.log(
834
- `reconcile, then re-run ship: git -C "${root}" pull --rebase ${REMOTE} ${DEV} && git -C "${root}" push ${REMOTE} ${DEV}`,
835
- );
836
- return EXIT.NEEDS_HUMAN;
837
- }
838
- const pull = quietGit(root, ["pull", "--rebase", REMOTE, DEV]);
839
- if (!pull.ok) {
840
- ctx.log(`git pull --rebase ${REMOTE} ${DEV} failed: ${pull.stderr}`);
841
- return EXIT_PULL_FAILED;
842
- }
843
- const push = runGit(root, ["push", REMOTE, DEV]);
844
- if (!push.ok) {
845
- ctx.log(`git push ${REMOTE} ${DEV} failed: ${push.stderr}`);
846
- return EXIT_PUSH_FAILED;
847
- }
848
- out.pushed = true;
849
- } else {
850
- const pull = runGit(root, ["pull", "--ff-only", REMOTE, DEV]);
851
- if (!pull.ok) {
852
- ctx.log(`git pull --ff-only ${REMOTE} ${DEV} failed: ${pull.stderr}`);
853
- return EXIT_PULL_FAILED;
854
- }
855
- }
856
- out.installed = install(ctx, root);
857
- ctx.emit(out);
858
- return out.installed === false ? EXIT_INSTALL_FAILED : EXIT.OK;
859
- } finally {
860
- releaseLock(lock.path, { workflow: "ship", fid, token: lock.token });
779
+ const fetch = runGit(root, ["fetch", REMOTE, DEV]);
780
+ if (!fetch.ok) {
781
+ ctx.log(`git fetch ${REMOTE} ${DEV} failed: ${fetch.stderr}`);
782
+ return EXIT_FETCH_FAILED;
861
783
  }
784
+ const devLocal = fastForwardDev(root, git(root, ["rev-parse", UPSTREAM]) ?? "", ctx.log);
785
+ const branch = currentBranch(root);
786
+ const installed = branch === DEV && devLocal === "fast-forwarded" ? install(ctx, root) : null;
787
+ ctx.emit({ devLocal, branch, installed });
788
+ return installed === false ? EXIT_INSTALL_FAILED : EXIT.OK;
862
789
  }
863
790
 
864
791
  /** Frozen install in the main checkout: false (logged) when it failed or could not run, null when there is nothing to install. */
@@ -915,122 +842,189 @@ interface Landed {
915
842
  shape: "local" | "pr";
916
843
  transport: "git" | "gh" | "mcp";
917
844
  sha: string;
918
- canonicalRef: string;
919
845
  prNumber: number | null;
920
- worktree: Record<string, unknown> | null;
846
+ /** Pushes the direct close took; 0 for a PR close. */
847
+ pushAttempts: number;
921
848
  }
922
849
 
923
850
  class Stop extends CommandError {}
924
851
 
852
+ /** This run's artifacts written untracked into the main checkout instead of the worktree stop the close. */
853
+ function strayCheck(root: string, month: string, fid: string): void {
854
+ const stray = (
855
+ git(root, ["status", "--porcelain", "-uall", "--", `docs/plans/${month}/logs/${fid}/`]) ?? ""
856
+ )
857
+ .split("\n")
858
+ .filter((l) => l.startsWith("??"));
859
+ if (stray.length) {
860
+ throw new Stop(
861
+ EXIT_LAND_STOPPED,
862
+ `${fid} artifacts written to the main checkout instead of the worktree:\n${stray.join("\n")}\nMove them under .worktrees/${fid}/ or delete them, then re-run.`,
863
+ );
864
+ }
865
+ }
866
+
867
+ /** Non-empty lines of `rev:p`, trimmed; [] when `p` is absent there. */
868
+ function revLines(root: string, rev: string, p: string): string[] {
869
+ return (git(root, ["show", `${rev}:${p}`]) ?? "")
870
+ .split("\n")
871
+ .map((l) => l.trim())
872
+ .filter((l) => l !== "");
873
+ }
874
+
875
+ /**
876
+ * Put back the `.jsonl` rows `branch` added that the squash dropped: `-X ours`
877
+ * keeps dev's side of a conflicting hunk, and a ledger git does not union-merge
878
+ * (a consumer's `.bkit/friction.jsonl`) loses the branch's rows there. Each
879
+ * missing row is appended to the staged file.
880
+ */
881
+ function restoreBranchRows(dir: string, branch: string): void {
882
+ const base = git(dir, ["merge-base", "HEAD", branch]);
883
+ if (base === null) return;
884
+ const changed = (
885
+ git(dir, ["diff", "--name-only", "--no-renames", "--diff-filter=d", base, branch]) ?? ""
886
+ )
887
+ .split("\n")
888
+ .filter((p) => p.endsWith(".jsonl"));
889
+ for (const p of changed) {
890
+ const before = new Set(revLines(dir, base, p));
891
+ const file = path.join(dir, p);
892
+ const text = fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : "";
893
+ const have = new Set(text.split("\n").map((l) => l.trim()));
894
+ const missing = revLines(dir, branch, p).filter((l) => !before.has(l) && !have.has(l));
895
+ if (missing.length === 0) continue;
896
+ const sep = text !== "" && !text.endsWith("\n") ? "\n" : "";
897
+ fs.mkdirSync(path.dirname(file), { recursive: true });
898
+ fs.appendFileSync(file, `${sep}${missing.join("\n")}\n`);
899
+ runGit(dir, ["add", "--", p]);
900
+ }
901
+ }
902
+
903
+ /**
904
+ * Build the close in `dir`, a detached origin/dev checkout: squash `branch` with
905
+ * -X ours, put back ledger rows the squash dropped, check only docs came and the
906
+ * canonical docs are the branch's copy, add the roadmap row, commit `{workflow} DONE`.
907
+ */
908
+ function buildClose(
909
+ ctx: RunContext,
910
+ dir: string,
911
+ o: { workflow: string; fid: string; month: string; branch: string },
912
+ ): void {
913
+ const squash = runGit(dir, ["merge", "--squash", "-X", "ours", o.branch]);
914
+ if (!squash.ok) {
915
+ throw new Stop(
916
+ EXIT_LAND_STOPPED,
917
+ `squash of ${o.branch} onto ${UPSTREAM} failed — nothing landed; ${o.branch} and its worktree kept: ${squash.stderr}`,
918
+ );
919
+ }
920
+ restoreBranchRows(dir, o.branch);
921
+ const staged = (git(dir, ["diff", "--cached", "--name-only"]) ?? "")
922
+ .split("\n")
923
+ .filter((p) => p !== "" && !CLOSE_DOCS.test(p));
924
+ if (staged.length)
925
+ throw new Stop(
926
+ EXIT_LAND_STOPPED,
927
+ `${o.workflow} close staged non-doc files:\n${staged.join("\n")}`,
928
+ );
929
+ const docs = canonicalDocs(dir, o.branch, o.workflow, o.month, o.fid);
930
+ const main = `docs/plans/${o.month}/${o.fid}-${o.workflow}.md`;
931
+ if (!docs.includes(main))
932
+ throw new Stop(
933
+ EXIT_LAND_STOPPED,
934
+ `${o.branch} carries no ${main} — nothing landed; ${o.branch} kept`,
935
+ );
936
+ const unlanded = docs.filter(
937
+ (d) =>
938
+ git(dir, ["rev-parse", "-q", "--verify", `:${d}`]) !==
939
+ git(dir, ["rev-parse", `${o.branch}:${d}`]),
940
+ );
941
+ if (unlanded.length) {
942
+ throw new Stop(
943
+ EXIT_LAND_STOPPED,
944
+ `squash did not stage the ${o.branch} copy of:\n${unlanded.join("\n")}\nnothing landed; ${o.branch} kept`,
945
+ );
946
+ }
947
+ appendFeature(dir, { workflow: o.workflow, fid: o.fid }, ctx.log);
948
+ commitBookkeeping(
949
+ {
950
+ root: dir,
951
+ month: o.month,
952
+ fid: o.fid,
953
+ scope: "core",
954
+ mode: "commit-allow-empty",
955
+ squashOf: o.branch,
956
+ message: `docs(${o.fid}): ${o.workflow} DONE bkit [skip ci]`,
957
+ },
958
+ ctx.log,
959
+ );
960
+ }
961
+
925
962
  /**
926
- * The local close: under the dev lock, squash `feat/{fid}` into dev in the main
927
- * checkout, check the staged canonical docs are the branch's, commit the
928
- * bookkeeping plus what the squash brought, push dev, remove the worktree.
963
+ * The direct close, every runtime: build it in `.worktrees/_land-{fid}` off a
964
+ * fresh origin/dev and push it as dev. The main checkout is never touched. dev
965
+ * moved underneath → rebuild on the new dev and push again, with backoff,
966
+ * LAND_ATTEMPTS pushes in all. Any other refusal → null: the PR close takes over.
929
967
  */
930
- async function landLocal(
968
+ async function landDirect(
931
969
  ctx: RunContext,
932
970
  root: string,
933
- o: { workflow: string; fid: string; month: string },
934
- ): Promise<Landed> {
935
- const feat = `feat/${o.fid}`;
936
- const lock = await acquireDevLock({
937
- cwd: root,
938
- workflow: o.workflow,
939
- fid: o.fid,
940
- deadlineS: TIMEOUTS.SHIP_DEV_LOCK_ACQUIRE_DEADLINE_S,
941
- log: ctx.log,
942
- });
943
- try {
944
- runGit(root, ["checkout", DEV]);
945
- const on = currentBranch(root);
946
- if (on !== DEV)
947
- throw new Stop(EXIT_NOT_DEV, `not on dev after checkout (on '${on}') — aborting dev ops`);
948
- const stray = (
949
- git(root, ["status", "--porcelain", "-uall", "--", `docs/plans/${o.month}/logs/${o.fid}/`]) ??
950
- ""
951
- )
952
- .split("\n")
953
- .filter((l) => l.startsWith("??"));
954
- if (stray.length) {
971
+ o: { workflow: string; fid: string; month: string; branch: string },
972
+ ): Promise<Landed | null> {
973
+ const dir = landDir(root, o.fid);
974
+ const res = await pushToDev({ root, dir, build: (d) => buildClose(ctx, d, o), log: ctx.log });
975
+ switch (res.kind) {
976
+ case "landed":
977
+ return {
978
+ shape: "local",
979
+ transport: "git",
980
+ sha: res.sha,
981
+ prNumber: null,
982
+ pushAttempts: res.attempts,
983
+ };
984
+ case "refused":
985
+ ctx.log(`${REMOTE} refused the dev push — closing through a PR instead: ${res.stderr}`);
986
+ return null;
987
+ case "push-failed":
955
988
  throw new Stop(
956
- EXIT_LAND_STOPPED,
957
- `${o.fid} artifacts written to the main checkout instead of the worktree:\n${stray.join("\n")}\nMove them under .worktrees/${o.fid}/ or delete them, then re-run.`,
958
- );
959
- }
960
- if (!runGit(root, ["pull", "--ff-only", REMOTE, DEV]).ok)
961
- throw new Stop(EXIT_PULL_FAILED, "dev fast-forward failed");
962
- const squash = runGit(root, ["merge", "--squash", "-X", "ours", feat]);
963
- if (!squash.ok) {
964
- throw new Stop(
965
- EXIT_LAND_STOPPED,
966
- `squash of ${feat} into dev failed — nothing committed or pushed; ${feat} and its worktree kept. Clear what git names from the main checkout, then re-run: ${squash.stderr}`,
967
- );
968
- }
969
- const staged = (git(root, ["diff", "--cached", "--name-only"]) ?? "")
970
- .split("\n")
971
- .filter((p) => p !== "" && !CLOSE_DOCS.test(p));
972
- if (staged.length)
973
- throw new Stop(
974
- EXIT_LAND_STOPPED,
975
- `${o.workflow} close staged non-doc files:\n${staged.join("\n")}`,
989
+ EXIT_PUSH_FAILED,
990
+ `dev push failed without a server answer — nothing landed; ${o.branch} and its worktree kept; re-run the land: ${res.stderr}`,
976
991
  );
977
- const docs = canonicalDocs(root, feat, o.workflow, o.month, o.fid);
978
- const main = `docs/plans/${o.month}/${o.fid}-${o.workflow}.md`;
979
- if (!docs.includes(main))
992
+ case "fetch-failed":
980
993
  throw new Stop(
981
- EXIT_LAND_STOPPED,
982
- `${feat} carries no ${main} — nothing committed or pushed; ${feat} kept`,
994
+ EXIT_FETCH_FAILED,
995
+ `git fetch ${REMOTE} ${DEV} failed — nothing landed; ${o.branch} kept`,
983
996
  );
984
- const unlanded = docs.filter(
985
- (d) =>
986
- git(root, ["rev-parse", "-q", "--verify", `:${d}`]) !==
987
- git(root, ["rev-parse", `${feat}:${d}`]),
988
- );
989
- if (unlanded.length) {
997
+ case "setup-failed":
998
+ throw new Stop(EXIT_LAND_STOPPED, `could not create ${dir} — nothing landed: ${res.stderr}`);
999
+ case "exhausted":
990
1000
  throw new Stop(
991
- EXIT_LAND_STOPPED,
992
- `squash did not stage the ${feat} copy of:\n${unlanded.join("\n")}\nnothing committed or pushed; ${feat} kept; the main checkout index still holds the squash`,
993
- );
994
- }
995
- appendFeature(root, { workflow: o.workflow, fid: o.fid }, ctx.log);
996
- commitBookkeeping(
997
- {
998
- root,
999
- month: o.month,
1000
- fid: o.fid,
1001
- scope: "core",
1002
- mode: "commit-allow-empty",
1003
- squashOf: feat,
1004
- message: `docs(${o.fid}): ${o.workflow} DONE bkit [skip ci]`,
1005
- },
1006
- ctx.log,
1007
- );
1008
- if (!runGit(root, ["push", REMOTE, DEV]).ok)
1009
- throw new Stop(EXIT_PUSH_FAILED, "dev push failed");
1010
- const sha = git(root, ["rev-parse", "HEAD"]) ?? "";
1011
- let worktree: Record<string, unknown> | null = null;
1012
- try {
1013
- worktree = { ...removeWorktree(root, o.fid, feat, ctx.log) };
1014
- } catch (err) {
1015
- // The close landed; a leftover worktree is a human's to remove.
1016
- ctx.log(
1017
- `worktree removal failed — remove .worktrees/${o.fid} by hand: ${(err as Error).message}`,
1001
+ EXIT_PUSH_FAILED,
1002
+ `dev moved before each of ${res.attempts} pushes — nothing landed; ${o.branch} and its worktree kept; re-run the land`,
1018
1003
  );
1019
- }
1020
- return { shape: "local", transport: "git", sha, canonicalRef: DEV, prNumber: null, worktree };
1021
- } finally {
1022
- releaseLock(lock.path, { workflow: o.workflow, fid: o.fid, token: lock.token });
1023
1004
  }
1024
1005
  }
1025
1006
 
1007
+ /** The checkout that has `branch` checked out, or null. */
1008
+ function branchTree(root: string, branch: string): string | null {
1009
+ for (const block of (git(root, ["worktree", "list", "--porcelain"]) ?? "").split("\n\n")) {
1010
+ const lines = block.split("\n");
1011
+ if (lines.includes(`branch refs/heads/${branch}`))
1012
+ return lines.find((l) => l.startsWith("worktree "))?.slice("worktree ".length) ?? null;
1013
+ }
1014
+ return null;
1015
+ }
1016
+
1026
1017
  /**
1027
- * The PR close (a runtime that cannot push dev): commit the roadmap row on the
1028
- * branch, push it, open or reuse the PR, squash-merge it with an empty body. gh
1029
- * missing → EXIT.USE_MCP with what to create / merge; re-run with `--pr` (and
1030
- * `--merged-sha` once merged).
1018
+ * The PR close (the dev push was refused): commit the roadmap row on the branch
1019
+ * in the checkout holding it, push it, open or reuse the PR, squash-merge it with
1020
+ * an empty body. A merge that does not land on an open PR → update its branch
1021
+ * from dev and try again, with backoff, LAND_ATTEMPTS tries in all; then stop with
1022
+ * the PR left open. gh missing → EXIT.USE_MCP with what to create / merge; re-run
1023
+ * with `--pr` (and `--merged-sha` once merged).
1031
1024
  */
1032
- function landPr(
1025
+ async function landPr(
1033
1026
  ctx: RunContext,
1027
+ root: string,
1034
1028
  o: {
1035
1029
  workflow: string;
1036
1030
  fid: string;
@@ -1040,10 +1034,15 @@ function landPr(
1040
1034
  pr?: string;
1041
1035
  mergedSha?: string;
1042
1036
  },
1043
- ): Landed | number {
1044
- const tree = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? ctx.cwd;
1037
+ ): Promise<Landed | number> {
1045
1038
  let prNumber = o.pr;
1046
1039
  if (prNumber === undefined) {
1040
+ const tree = branchTree(root, o.branch);
1041
+ if (tree === null)
1042
+ throw new Stop(
1043
+ EXIT_LAND_STOPPED,
1044
+ `no checkout has ${o.branch} checked out — the PR close commits the roadmap row on it; nothing landed`,
1045
+ );
1047
1046
  runGit(tree, ["fetch", REMOTE, DEV, o.branch]);
1048
1047
  appendFeature(tree, { workflow: o.workflow, fid: o.fid }, ctx.log);
1049
1048
  commitBookkeeping(
@@ -1094,35 +1093,118 @@ function landPr(
1094
1093
  let sha = o.mergedSha ?? "";
1095
1094
  let transport: Landed["transport"] = o.mergedSha === undefined ? "gh" : "mcp";
1096
1095
  if (o.mergedSha === undefined) {
1097
- const merged = mergePr(tree, { number: prNumber, subject }, ctx.log);
1098
- if (merged.code === EXIT.USE_MCP) {
1099
- ctx.emit({ stage: "merge", prNumber: Number(prNumber), subject, body: "" });
1100
- return EXIT.USE_MCP;
1101
- }
1102
- if (!merged.out.merged)
1103
- throw new Stop(
1104
- EXIT_LAND_STOPPED,
1105
- `PR ${prNumber} did not reach MERGED (state=${merged.out.state ?? "unread"})`,
1096
+ for (let attempt = 1; ; attempt++) {
1097
+ const merged = mergePr(root, { number: prNumber, subject }, ctx.log);
1098
+ if (merged.code === EXIT.USE_MCP) {
1099
+ ctx.emit({ stage: "merge", prNumber: Number(prNumber), subject, body: "" });
1100
+ return EXIT.USE_MCP;
1101
+ }
1102
+ if (merged.out.merged) {
1103
+ sha = merged.out.mergeCommitOid ?? "";
1104
+ break;
1105
+ }
1106
+ // An unread state (gh read failed) is retried like an open PR; only a closed PR stops at once.
1107
+ if (merged.out.state !== null && merged.out.state !== "OPEN")
1108
+ throw new Stop(
1109
+ EXIT_LAND_STOPPED,
1110
+ `PR ${prNumber} did not reach MERGED (state=${merged.out.state})`,
1111
+ );
1112
+ if (attempt >= TIMEOUTS.LAND_ATTEMPTS)
1113
+ throw new Stop(
1114
+ EXIT_LAND_STOPPED,
1115
+ `PR ${prNumber} still not merged after ${attempt} tries — left open; merge it, then re-run with --pr=${prNumber} --merged-sha=<merge commit>`,
1116
+ );
1117
+ updateBranch(root, prNumber, ctx.log);
1118
+ const wait = landBackoffMs(attempt);
1119
+ ctx.log(
1120
+ `PR ${prNumber} not merged on try ${attempt} of ${TIMEOUTS.LAND_ATTEMPTS} — branch updated from dev; trying again in ${(wait / 1000).toFixed(1)}s`,
1106
1121
  );
1107
- sha = merged.out.mergeCommitOid ?? "";
1122
+ await sleep(wait);
1123
+ }
1108
1124
  transport = "gh";
1109
1125
  } else {
1110
- const back = probePr(tree, { number: prNumber, state: "open" });
1126
+ const back = probePr(root, { number: prNumber, state: "open" });
1111
1127
  if (back.kind === "ok" && back.pr && back.pr.state !== "MERGED")
1112
1128
  throw new Stop(EXIT_LAND_STOPPED, `PR ${prNumber} is ${back.pr.state}, not MERGED`);
1113
1129
  }
1114
1130
  if (sha === "")
1115
1131
  throw new Stop(EXIT_LAND_STOPPED, `could not resolve the landed SHA for PR ${prNumber}`);
1116
- if (!runGit(tree, ["fetch", REMOTE, DEV]).ok)
1132
+ if (!runGit(root, ["fetch", REMOTE, DEV]).ok)
1117
1133
  throw new Stop(EXIT_LAND_STOPPED, "fetch of origin/dev after the merge failed");
1118
- return {
1119
- shape: "pr",
1120
- transport,
1121
- sha,
1122
- canonicalRef: UPSTREAM,
1123
- prNumber: Number(prNumber),
1124
- worktree: null,
1125
- };
1134
+ return { shape: "pr", transport, sha, prNumber: Number(prNumber), pushAttempts: 0 };
1135
+ }
1136
+
1137
+ /**
1138
+ * Bring local dev up to `sha` when that is a pure fast-forward — `merge
1139
+ * --ff-only` when the main checkout is on dev, else move the branch pointer
1140
+ * alone; nothing is checked out or pushed. Local commits origin/dev lacks (listed
1141
+ * with the command that publishes them), or git refusing (an uncommitted edit the
1142
+ * move would overwrite, dev checked out in another worktree), skip it with a log
1143
+ * line: what landed is on origin/dev either way.
1144
+ */
1145
+ function fastForwardDev(
1146
+ root: string,
1147
+ sha: string,
1148
+ log: (m: string) => void,
1149
+ ): "fast-forwarded" | "current" | "skipped" | "none" {
1150
+ const local = git(root, ["rev-parse", "-q", "--verify", `refs/heads/${DEV}`]);
1151
+ if (local === null) return "none";
1152
+ if (local === sha) return "current";
1153
+ if (!runGit(root, ["merge-base", "--is-ancestor", local, sha]).ok) {
1154
+ const ahead = (git(root, ["log", "--format=%h %s", `${sha}..${local}`]) ?? "")
1155
+ .split("\n")
1156
+ .filter((l) => l !== "");
1157
+ log(`local ${DEV} has ${ahead.length} commit(s) ${UPSTREAM} does not — not fast-forwarded:`);
1158
+ for (const l of ahead) log(` ${l}`);
1159
+ log(
1160
+ `to publish them, on ${DEV} in ${root}: git pull --rebase ${REMOTE} ${DEV} && git push ${REMOTE} ${DEV}`,
1161
+ );
1162
+ return "skipped";
1163
+ }
1164
+ const moved =
1165
+ currentBranch(root) === DEV
1166
+ ? runGit(root, ["merge", "--ff-only", "-q", sha])
1167
+ : runGit(root, ["fetch", "-q", ".", `${sha}:refs/heads/${DEV}`]);
1168
+ if (!moved.ok) {
1169
+ log(`local ${DEV} not fast-forwarded — git refused: ${moved.stderr}`);
1170
+ return "skipped";
1171
+ }
1172
+ return "fast-forwarded";
1173
+ }
1174
+
1175
+ /**
1176
+ * What `branch` changed that origin/dev does not hold, compared file by file
1177
+ * against the branch's fork point: a file whose dev copy differs from the
1178
+ * branch's, or (a `.jsonl` ledger, union-merged) a line the branch added that
1179
+ * dev's copy lacks. `docs/roadmap.md` is re-rendered on every close, so it is
1180
+ * not compared. The branch and its worktree are deleted only when this is empty.
1181
+ */
1182
+ function notOnDev(root: string, branch: string): string[] {
1183
+ const base = git(root, ["merge-base", UPSTREAM, branch]);
1184
+ if (base === null) return [`${branch}: no common history with ${UPSTREAM}`];
1185
+ const lines = (rev: string, p: string) => revLines(root, rev, p);
1186
+ return (git(root, ["diff", "--name-only", "--no-renames", "--diff-filter=d", base, branch]) ?? "")
1187
+ .split("\n")
1188
+ .filter((p) => p !== "" && p !== "docs/roadmap.md")
1189
+ .filter((p) => {
1190
+ if (!p.endsWith(".jsonl"))
1191
+ return (
1192
+ git(root, ["rev-parse", `${branch}:${p}`]) !==
1193
+ git(root, ["rev-parse", "-q", "--verify", `${UPSTREAM}:${p}`])
1194
+ );
1195
+ const before = new Set(lines(base, p));
1196
+ const onDev = new Set(lines(UPSTREAM, p));
1197
+ return lines(branch, p).some((l) => !before.has(l) && !onDev.has(l));
1198
+ });
1199
+ }
1200
+
1201
+ /** Uncommitted or untracked files in the feature worktree; [] when there is no worktree. */
1202
+ function uncommitted(root: string, fid: string): string[] {
1203
+ const wt = worktreeDir(root, fid);
1204
+ if (!fs.existsSync(wt)) return [];
1205
+ const status = runGit(wt, ["status", "--porcelain", "-uall"]);
1206
+ if (!status.ok) return [`git status in ${wt} failed: ${status.stderr}`];
1207
+ return status.stdout.split("\n").filter((l) => l !== "");
1126
1208
  }
1127
1209
 
1128
1210
  async function landVerb(ctx: RunContext): Promise<number> {
@@ -1132,7 +1214,7 @@ async function landVerb(ctx: RunContext): Promise<number> {
1132
1214
  const fid = String(ctx.flags.fid);
1133
1215
  const root = repoRoot(ctx.cwd);
1134
1216
  const month = resolveMonth(root, fid, str(ctx.flags.month));
1135
- // `bkit install` can leave core.bare=true on the main checkout, which breaks every checkout below.
1217
+ // `bkit install` can leave core.bare=true on the main checkout, which breaks every worktree below.
1136
1218
  if (
1137
1219
  git(root, ["config", "--get", "core.bare"]) === "true" &&
1138
1220
  fs.statSync(path.join(root, ".git"), { throwIfNoEntry: false })?.isDirectory()
@@ -1150,34 +1232,49 @@ async function landVerb(ctx: RunContext): Promise<number> {
1150
1232
  );
1151
1233
  try {
1152
1234
  const devPushes = devPushesOf(root, worktreeStatus, ctx.log);
1153
- const landed = devPushes
1154
- ? await landLocal(ctx, root, { workflow, fid, month })
1155
- : landPr(ctx, {
1156
- workflow,
1157
- fid,
1158
- month,
1159
- issue: str(ctx.flags.issue) || undefined,
1160
- branch: String(ctx.flags.branch ?? currentBranch(ctx.cwd)),
1161
- pr: str(ctx.flags.pr),
1162
- mergedSha: str(ctx.flags.mergedSha),
1163
- });
1235
+ const branch = str(ctx.flags.branch) || (devPushes ? `feat/${fid}` : currentBranch(ctx.cwd));
1236
+ const pr = str(ctx.flags.pr);
1237
+ if (devPushes && pr === undefined) strayCheck(root, month, fid);
1238
+ const landed =
1239
+ (pr === undefined ? await landDirect(ctx, root, { workflow, fid, month, branch }) : null) ??
1240
+ (await landPr(ctx, root, {
1241
+ workflow,
1242
+ fid,
1243
+ month,
1244
+ issue: str(ctx.flags.issue) || undefined,
1245
+ branch,
1246
+ pr,
1247
+ mergedSha: str(ctx.flags.mergedSha),
1248
+ }));
1164
1249
  if (typeof landed === "number") return landed;
1165
1250
 
1166
- // The audit: canonical docs on dev, the landed body clean, the transport recorded.
1251
+ runGit(root, ["fetch", REMOTE, DEV]);
1252
+ const localDev = devPushes ? fastForwardDev(root, landed.sha, ctx.log) : null;
1253
+
1254
+ // The audit: canonical docs on origin/dev, the landed body clean, the transport recorded.
1167
1255
  const docs = canonicalDocs(root, landed.sha, workflow, month, fid);
1168
1256
  const main = `docs/plans/${month}/${fid}-${workflow}.md`;
1169
1257
  const missing = [main, ...docs].filter(
1170
- (d) => !runGit(root, ["cat-file", "-e", `${landed.canonicalRef}:${d}`]).ok,
1258
+ (d) => !runGit(root, ["cat-file", "-e", `${UPSTREAM}:${d}`]).ok,
1171
1259
  );
1172
- const status = path.join(root, "docs", "plans", month, "logs", fid, "status.jsonl");
1173
- runGit(root, ["fetch", REMOTE, DEV]);
1174
1260
  const token = bodySkipToken(root, landed.sha);
1175
1261
  if (token === undefined)
1176
1262
  throw new Stop(EXIT_LANDED_UNVERIFIED, `post-close body scan errored on ${landed.sha}`);
1177
1263
  const scanResult = token ? "skip-token-found" : "clean";
1178
- if (!crossCheckFile(status, landed.transport, ctx.log).ok)
1264
+ // A PR runtime's checkout holds the branch, so its status file is this run's.
1265
+ // A runtime that pushes dev never writes the main checkout: the cross-check
1266
+ // reads the landed commit's copy, and the transport is in the emitted result.
1267
+ const status = path.join(root, "docs", "plans", month, "logs", fid, "status.jsonl");
1268
+ const onDisk = !devPushes && fs.existsSync(status);
1269
+ const rows = onDisk ? readStatusRows(status) : readStatusRowsAt(status, landed.sha);
1270
+ const label = onDisk ? status : `${landed.sha}:${path.relative(root, status)}`;
1271
+ if (!crossCheckRows(rows, label, landed.transport, ctx.log).ok)
1179
1272
  throw new Stop(EXIT_LANDED_UNVERIFIED, "close transport cross-check failed");
1180
- closeTransportRow(status, { shape: landed.shape, sha: landed.sha, scanResult });
1273
+ if (onDisk) closeTransportRow(status, { shape: landed.shape, sha: landed.sha, scanResult });
1274
+ else
1275
+ ctx.log(
1276
+ `close-transport row not written — the main checkout is never written to; shape=${landed.shape} sha=${landed.sha} scan=${scanResult}`,
1277
+ );
1181
1278
  if (token)
1182
1279
  throw new Stop(
1183
1280
  EXIT_LANDED_UNVERIFIED,
@@ -1186,10 +1283,33 @@ async function landVerb(ctx: RunContext): Promise<number> {
1186
1283
  if (missing.length)
1187
1284
  throw new Stop(
1188
1285
  EXIT_LANDED_UNVERIFIED,
1189
- `canonical ${workflow} missing on dev: ${missing.join(", ")}`,
1286
+ `canonical ${workflow} missing on ${UPSTREAM}: ${missing.join(", ")}`,
1287
+ );
1288
+ const notLanded = notOnDev(root, branch);
1289
+ if (notLanded.length)
1290
+ throw new Stop(
1291
+ EXIT_LANDED_UNVERIFIED,
1292
+ `${branch} carries work ${UPSTREAM} does not — ${branch} and its worktree kept:\n${notLanded.join("\n")}`,
1190
1293
  );
1191
1294
 
1192
- const released = releaseLock(workflowLockPath(lockRoot(root, workflow, false), month, fid), {
1295
+ let worktree: Record<string, unknown> | null = null;
1296
+ const left = devPushes ? uncommitted(root, fid) : [];
1297
+ if (left.length) {
1298
+ ctx.log(
1299
+ `.worktrees/${fid} holds work that was never committed, so it is not on ${UPSTREAM} — it and ${branch} kept; commit or move it, then remove them by hand:\n${left.join("\n")}`,
1300
+ );
1301
+ worktree = { removed: false, reason: "uncommitted", files: left };
1302
+ } else if (devPushes) {
1303
+ try {
1304
+ worktree = { ...removeWorktree(root, fid, branch, ctx.log) };
1305
+ } catch (err) {
1306
+ // The close landed; a leftover worktree is a human's to remove.
1307
+ ctx.log(
1308
+ `worktree removal failed — remove .worktrees/${fid} by hand: ${(err as Error).message}`,
1309
+ );
1310
+ }
1311
+ }
1312
+ const released = releaseLock(workflowLockPath(root, month, fid), {
1193
1313
  workflow,
1194
1314
  fid,
1195
1315
  token: str(ctx.flags.token),
@@ -1200,9 +1320,11 @@ async function landVerb(ctx: RunContext): Promise<number> {
1200
1320
  transport: landed.transport,
1201
1321
  landedSha: landed.sha,
1202
1322
  prNumber: landed.prNumber,
1203
- canonicalRef: landed.canonicalRef,
1323
+ canonicalRef: UPSTREAM,
1204
1324
  scanResult,
1205
- worktree: landed.worktree,
1325
+ pushAttempts: landed.pushAttempts,
1326
+ localDev,
1327
+ worktree,
1206
1328
  });
1207
1329
  return EXIT.OK;
1208
1330
  } catch (err) {
@@ -1301,7 +1423,7 @@ function anchorReadVerb(ctx: RunContext): number {
1301
1423
 
1302
1424
  export const branchesCommand: CommandSpec = {
1303
1425
  noun: "branches",
1304
- summary: "Sync, push, rebase and switch branches; stamp and read a doc's base-commit anchor.",
1426
+ summary: "Sync, push, land and rebase branches; stamp and read a doc's base-commit anchor.",
1305
1427
  verbs: {
1306
1428
  sync: {
1307
1429
  summary: `Fetch ${UPSTREAM}; report whether it is an ancestor of HEAD (Path A/B) and how far docs/ is behind; optionally merge it in.`,
@@ -1405,51 +1527,26 @@ export const branchesCommand: CommandSpec = {
1405
1527
  },
1406
1528
  run: rebaseVerb,
1407
1529
  },
1408
- switch: {
1530
+ "sync-dev": {
1409
1531
  summary:
1410
- "After a merge, return the main checkout to dev and bring it level with origin/dev, under the dev lock.",
1411
- flags: [
1412
- {
1413
- name: "fid",
1414
- type: "string",
1415
- required: true,
1416
- help: "feature id, recorded in the dev lock",
1417
- },
1418
- {
1419
- name: "dev-pushes",
1420
- type: "string",
1421
- required: true,
1422
- help: "true | false — runtimeDevPushes; false skips the switch",
1423
- },
1424
- {
1425
- name: "worktrees",
1426
- type: "string",
1427
- required: true,
1428
- help: "true | false — runtimeWorktrees; a local dev checkout needs true",
1429
- },
1430
- ],
1532
+ "After a merge, fast-forward local dev to origin/dev without checking it out or pushing; frozen install when the main checkout is on dev and moved.",
1533
+ flags: [],
1431
1534
  output: {
1432
- switched: "true when the checkout is now on dev",
1433
- branch: "branch checked out afterwards",
1434
- ahead: "local dev commits that were ahead of origin/dev (all skip-CI, rebased and pushed)",
1435
- pushed: "true when those commits were pushed",
1535
+ devLocal:
1536
+ "fast-forwarded | current | skipped (local dev has commits origin/dev lacks, listed with the publish command, or git refused) | none (no local dev)",
1537
+ branch: "the branch the main checkout is on (unchanged)",
1436
1538
  installed:
1437
- "dependency install result: true, false (failed, exit 16), null (no package.json)",
1438
- skipped: "dev-pushes-false when the runtime does not push dev (null otherwise)",
1539
+ "dependency install result: true, false (failed, exit 16), null (not run: not on dev, dev did not move, or no package.json)",
1439
1540
  },
1440
1541
  exitCodes: {
1441
- [EXIT_NOT_DEV]: "the checkout is not on dev after git checkout dev",
1442
1542
  [EXIT_FETCH_FAILED]: `git fetch ${REMOTE} ${DEV} failed`,
1443
- [EXIT_PUSH_FAILED]: "pushing the rebased local dev commits failed",
1444
- [EXIT_PULL_FAILED]: "git pull failed: local dev is not level with origin/dev",
1445
- [EXIT_RUNTIME_REFUSED]: "--dev-pushes=true with --worktrees=false",
1446
1543
  [EXIT_INSTALL_FAILED]: "dependency install failed or the package manager could not run",
1447
1544
  },
1448
- run: switchVerb,
1545
+ run: syncDevVerb,
1449
1546
  },
1450
1547
  land: {
1451
1548
  summary:
1452
- "Design / plan close: land feat/{fid} on dev — the local squash under the dev lock, or the PR squash-merge — then audit it and release the lock.",
1549
+ "Design / plan close: squash the branch onto origin/dev in a throwaway worktree and push it as dev (retrying with backoff when dev moved), else the PR squash-merge; then audit it, fast-forward local dev on a laptop and release the lock.",
1453
1550
  flags: [
1454
1551
  { name: "workflow", type: "string", required: true, help: "design | plan" },
1455
1552
  { name: "fid", type: "string", required: true, help: "feature id" },
@@ -1463,7 +1560,7 @@ export const branchesCommand: CommandSpec = {
1463
1560
  {
1464
1561
  name: "branch",
1465
1562
  type: "string",
1466
- help: "PR close: the head branch (default: the current branch)",
1563
+ help: "the branch to land (default: feat/{fid} where the runtime pushes dev, else the current branch)",
1467
1564
  },
1468
1565
  {
1469
1566
  name: "pr",
@@ -1481,18 +1578,21 @@ export const branchesCommand: CommandSpec = {
1481
1578
  transport: "git | gh | mcp",
1482
1579
  landedSha: "the commit that landed on dev",
1483
1580
  prNumber: "the PR (pr shape), else null",
1484
- canonicalRef: "dev (local) | origin/dev (pr) — where the canonical docs were verified",
1581
+ canonicalRef: "origin/dev — where the canonical docs were verified",
1485
1582
  scanResult: "the landed commit body's scan: clean",
1486
- worktree: "the worktree removal result (local), else null",
1583
+ pushAttempts: "dev pushes the direct close took (0 for a PR close)",
1584
+ localDev:
1585
+ "fast-forwarded | current | skipped (local commits, or git refused) | none (no local dev) | null (runtime does not push dev)",
1586
+ worktree: "the worktree removal result (runtime pushes dev), else null",
1487
1587
  stage:
1488
1588
  "exit 80 only: open (create the PR via MCP with title / body / base / head) | merge (merge via MCP with subject, empty body)",
1489
1589
  },
1490
1590
  exitCodes: {
1491
- [EXIT_PUSH_FAILED]: "the dev or branch push failed",
1492
- [EXIT_NOT_DEV]: "the main checkout is not on dev after checkout",
1493
- [EXIT_PULL_FAILED]: "dev could not fast-forward",
1591
+ [EXIT_PUSH_FAILED]:
1592
+ "dev moved before every one of LAND_ATTEMPTS pushes, or the PR branch push failed (nothing landed)",
1593
+ [EXIT_FETCH_FAILED]: `git fetch ${REMOTE} ${DEV} failed (nothing landed)`,
1494
1594
  [EXIT_LAND_STOPPED]:
1495
- "a guard stopped the land: stray files, failed squash, staged non-doc files, canonical blob mismatch, PR not opened / merged (nothing landed)",
1595
+ "a guard stopped the land: stray files, failed squash, staged non-doc files, canonical blob mismatch, no checkout holds the branch, PR not opened / not merged after LAND_ATTEMPTS tries (nothing landed; the PR stays open)",
1496
1596
  [EXIT_LANDED_UNVERIFIED]:
1497
1597
  "landed, but the body scan, transport cross-check or canonical-on-dev check failed",
1498
1598
  [EXIT_LOCK_LEFT]: "landed and audited, but the workflow lock file survived removal",