@cbartens/bkit 5.5.1 → 6.1.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 (425) hide show
  1. package/.bkit/README.md +167 -154
  2. package/.bkit/core/.agents/context.md +95 -29
  3. package/.bkit/core/.agents/docs.md +18 -15
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-gateguard.cjs +1 -0
  5. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +6 -5
  6. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-readguard.cjs +1 -0
  7. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-rules.cjs +65 -0
  8. package/.bkit/core/.agents/rules.md +112 -102
  9. package/.bkit/core/.agents/skills.md +63 -15
  10. package/.bkit/core/.bkit/README.md +167 -154
  11. package/.bkit/core/.bkit/authoring.md +747 -0
  12. package/.bkit/core/.bkit/cli.md +407 -0
  13. package/.bkit/core/.bkit/cloud.md +283 -195
  14. package/.bkit/core/.bkit/comparison.md +45 -43
  15. package/.bkit/core/.bkit/install.md +166 -95
  16. package/.bkit/core/.bkit/jsonl.md +339 -196
  17. package/.bkit/core/.bkit/pipeline.md +142 -145
  18. package/.bkit/core/.bkit/prompts.md +295 -264
  19. package/.bkit/core/.bkit/providers.md +460 -277
  20. package/.bkit/core/.bkit/router.md +69 -0
  21. package/.bkit/core/.bkit/templates.md +530 -256
  22. package/.bkit/core/.bkit/trackers.md +116 -65
  23. package/.bkit/core/.bkit/workflows.md +742 -618
  24. package/.bkit/core/.claude/hooks/bkit-gateguard.cjs +2 -2
  25. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +3 -3
  26. package/.bkit/core/.claude/hooks/bkit-preflight.sh +45 -14
  27. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +3 -3
  28. package/.bkit/core/.codex/hooks/bkit-rules.cjs +57 -0
  29. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +7 -7
  30. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +47 -12
  31. package/.bkit/core/.opencode/plugin/bkit-rules.js +89 -0
  32. package/.bkit/core/AGENTS.md +6 -80
  33. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +128 -130
  34. package/.bkit/core/docs/templates/bkit-audit-adoption.md +104 -94
  35. package/.bkit/core/docs/templates/bkit-audit-agents.md +96 -98
  36. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +100 -103
  37. package/.bkit/core/docs/templates/bkit-audit-analytics.md +141 -107
  38. package/.bkit/core/docs/templates/bkit-audit-annotations.md +99 -97
  39. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +122 -121
  40. package/.bkit/core/docs/templates/bkit-audit-app-store.md +158 -101
  41. package/.bkit/core/docs/templates/bkit-audit-architecture.md +114 -96
  42. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +76 -97
  43. package/.bkit/core/docs/templates/bkit-audit-config.md +123 -101
  44. package/.bkit/core/docs/templates/bkit-audit-cost.md +86 -99
  45. package/.bkit/core/docs/templates/bkit-audit-coverage.md +76 -93
  46. package/.bkit/core/docs/templates/bkit-audit-database.md +102 -95
  47. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +165 -108
  48. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +115 -109
  49. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +265 -113
  50. package/.bkit/core/docs/templates/bkit-audit-documentation.md +119 -118
  51. package/.bkit/core/docs/templates/bkit-audit-duplication.md +140 -111
  52. package/.bkit/core/docs/templates/bkit-audit-failures.md +111 -106
  53. package/.bkit/core/docs/templates/bkit-audit-flakes.md +100 -99
  54. package/.bkit/core/docs/templates/bkit-audit-gates.md +107 -103
  55. package/.bkit/core/docs/templates/bkit-audit-issues.md +105 -105
  56. package/.bkit/core/docs/templates/bkit-audit-llm.md +134 -85
  57. package/.bkit/core/docs/templates/bkit-audit-logs.md +124 -125
  58. package/.bkit/core/docs/templates/bkit-audit-models.md +99 -78
  59. package/.bkit/core/docs/templates/bkit-audit-privacy.md +56 -76
  60. package/.bkit/core/docs/templates/bkit-audit-prompts.md +63 -78
  61. package/.bkit/core/docs/templates/bkit-audit-red-team.md +125 -93
  62. package/.bkit/core/docs/templates/bkit-audit-reliability.md +97 -96
  63. package/.bkit/core/docs/templates/bkit-audit-repo.md +170 -98
  64. package/.bkit/core/docs/templates/bkit-audit-security.md +207 -121
  65. package/.bkit/core/docs/templates/bkit-audit-slop.md +78 -95
  66. package/.bkit/core/docs/templates/bkit-audit-testing.md +163 -139
  67. package/.bkit/core/docs/templates/bkit-audit-usability.md +114 -96
  68. package/.bkit/core/docs/templates/bkit-plan.md +158 -281
  69. package/.bkit/core/engine/checks/after/auth.ts +40 -37
  70. package/.bkit/core/engine/checks/after/ci-yml.ts +104 -31
  71. package/.bkit/core/engine/checks/after/github.ts +95 -17
  72. package/.bkit/core/engine/checks/after/index.ts +21 -8
  73. package/.bkit/core/engine/checks/after/suppression.ts +8 -5
  74. package/.bkit/core/engine/checks/after/tools.ts +125 -123
  75. package/.bkit/core/engine/checks/before/context-fetch.ts +227 -33
  76. package/.bkit/core/engine/checks/before/env.ts +3 -3
  77. package/.bkit/core/engine/checks/before/files.ts +5 -4
  78. package/.bkit/core/engine/checks/before/index.ts +25 -1
  79. package/.bkit/core/engine/checks/before/repo.ts +208 -2
  80. package/.bkit/core/engine/checks/status-holes.ts +916 -123
  81. package/.bkit/core/engine/checks/tips/catalogue.ts +82 -20
  82. package/.bkit/core/engine/checks/tips/detect.ts +66 -0
  83. package/.bkit/core/engine/checks/tips/index.ts +52 -11
  84. package/.bkit/core/engine/cli.ts +251 -130
  85. package/.bkit/core/engine/commands/analysis.ts +282 -199
  86. package/.bkit/core/engine/commands/ci/ci.ts +363 -29
  87. package/.bkit/core/engine/commands/ci/pins.ts +172 -0
  88. package/.bkit/core/engine/commands/ci/push-gate.ts +223 -0
  89. package/.bkit/core/engine/commands/comply.ts +77 -103
  90. package/.bkit/core/engine/commands/install/doctor.ts +2 -2
  91. package/.bkit/core/engine/commands/install/install.ts +57 -18
  92. package/.bkit/core/engine/commands/install/uninstall.ts +86 -55
  93. package/.bkit/core/engine/commands/install/upgrade.ts +32 -15
  94. package/.bkit/core/engine/commands/land.ts +139 -18
  95. package/.bkit/core/engine/commands/lib.ts +381 -22
  96. package/.bkit/core/engine/commands/registry.ts +10 -2
  97. package/.bkit/core/engine/commands/setup/setup.ts +8 -7
  98. package/.bkit/core/engine/commands/stats.ts +260 -0
  99. package/.bkit/core/engine/commands/tips.ts +10 -5
  100. package/.bkit/core/engine/commands/workflow/branches.ts +2215 -176
  101. package/.bkit/core/engine/commands/workflow/challenge.ts +748 -0
  102. package/.bkit/core/engine/commands/workflow/completeness.ts +109 -0
  103. package/.bkit/core/engine/commands/workflow/context.ts +1249 -47
  104. package/.bkit/core/engine/commands/workflow/counters.ts +483 -95
  105. package/.bkit/core/engine/commands/workflow/decisions.ts +585 -0
  106. package/.bkit/core/engine/commands/workflow/disk.ts +238 -56
  107. package/.bkit/core/engine/commands/workflow/fids.ts +811 -33
  108. package/.bkit/core/engine/commands/workflow/issues.ts +413 -64
  109. package/.bkit/core/engine/commands/workflow/ledgers.ts +1333 -36
  110. package/.bkit/core/engine/commands/workflow/locks.ts +28 -2
  111. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +691 -0
  112. package/.bkit/core/engine/commands/workflow/plan-versions.ts +21 -0
  113. package/.bkit/core/engine/commands/workflow/plans.ts +257 -0
  114. package/.bkit/core/engine/commands/workflow/prs.ts +178 -33
  115. package/.bkit/core/engine/commands/workflow/repo.ts +66 -8
  116. package/.bkit/core/engine/commands/workflow/roadmap.ts +72 -22
  117. package/.bkit/core/engine/commands/workflow/run-facts.ts +492 -0
  118. package/.bkit/core/engine/commands/workflow/runs.ts +827 -79
  119. package/.bkit/core/engine/commands/workflow/runtime.ts +25 -1
  120. package/.bkit/core/engine/commands/workflow/skills.ts +1 -0
  121. package/.bkit/core/engine/commands/workflow/status.ts +329 -33
  122. package/.bkit/core/engine/commands/workflow/step-table.ts +381 -0
  123. package/.bkit/core/engine/commands/workflow/steps.ts +841 -105
  124. package/.bkit/core/engine/commands/workflow/summary-findings.ts +177 -0
  125. package/.bkit/core/engine/commands/workflow/summary.ts +544 -0
  126. package/.bkit/core/engine/commands/workflow/tasks.ts +409 -0
  127. package/.bkit/core/engine/commands/workflow/test-blocks.ts +254 -0
  128. package/.bkit/core/engine/commands/workflow/tests-changed.ts +201 -0
  129. package/.bkit/core/engine/commands/workflow/tests.ts +2124 -330
  130. package/.bkit/core/engine/commands/workflow/tracker.ts +1195 -0
  131. package/.bkit/core/engine/commands/workflow/workflows.ts +1197 -235
  132. package/.bkit/core/engine/commands/workflow/worktrees.ts +543 -24
  133. package/.bkit/core/engine/install/cloud-env.ts +251 -121
  134. package/.bkit/core/engine/install/context-ci-workflow.ts +102 -0
  135. package/.bkit/core/engine/install/manifest.ts +67 -17
  136. package/.bkit/core/engine/install/modules/antigravity.ts +3 -2
  137. package/.bkit/core/engine/install/modules/cloud.ts +24 -16
  138. package/.bkit/core/engine/install/modules/codex.ts +15 -2
  139. package/.bkit/core/engine/install/modules/core.ts +1196 -45
  140. package/.bkit/core/engine/install/modules/cursor.ts +6 -6
  141. package/.bkit/core/engine/install/modules/opencode.ts +18 -6
  142. package/.bkit/core/engine/install/template-notes.ts +130 -0
  143. package/.bkit/core/engine/install/version-file.ts +9 -4
  144. package/.bkit/core/engine/install/write.ts +5 -0
  145. package/.bkit/core/engine/ledgers/compact.ts +124 -0
  146. package/.bkit/core/engine/ledgers/journal.ts +291 -0
  147. package/.bkit/core/engine/ledgers/migrate.ts +92 -0
  148. package/.bkit/core/engine/ledgers/status.ts +249 -21
  149. package/.bkit/core/engine/ledgers/telemetry.ts +1397 -253
  150. package/.bkit/core/engine/render/hosts.ts +118 -14
  151. package/.bkit/core/engine/render/models.ts +12 -0
  152. package/.bkit/core/engine/shared/bkit-latest.ts +26 -4
  153. package/.bkit/core/engine/shared/branches.ts +4 -1
  154. package/.bkit/core/engine/shared/dep-updater.ts +60 -0
  155. package/.bkit/core/engine/shared/egress.ts +8 -1
  156. package/.bkit/core/engine/shared/json.ts +25 -7
  157. package/.bkit/core/engine/shared/package-manager.ts +9 -0
  158. package/.bkit/core/engine/shared/settings.ts +243 -31
  159. package/.bkit/core/engine/shared/text.ts +361 -0
  160. package/.bkit/core/engine/shared/timeouts.ts +2 -0
  161. package/.bkit/core/engine/tools/cli-doc.ts +111 -0
  162. package/.bkit/core/engine/tools/grammar-density.ts +215 -0
  163. package/.bkit/core/engine/tools/instructions-sources.ts +832 -0
  164. package/.bkit/core/engine/tools/instructions.ts +1802 -0
  165. package/.bkit/core/hooks/antigravity-hook.js +25 -10
  166. package/.bkit/core/hooks/gateguard-engine.js +54 -29
  167. package/.bkit/core/hooks/guardrails-shell.js +4 -5
  168. package/.bkit/core/hooks/guardrails-tiers.js +10 -4
  169. package/.bkit/core/hooks/preflight-linear.sh +9 -9
  170. package/.bkit/core/hooks/preflight-rules.sh +8 -0
  171. package/.bkit/core/hooks/readguard-engine.js +29 -10
  172. package/.bkit/core/hooks/session-rules-advisory.js +61 -0
  173. package/.bkit/core/prompts/bkit-audit-generate.md +202 -94
  174. package/.bkit/core/prompts/bkit-build-challenge-1.md +76 -34
  175. package/.bkit/core/prompts/bkit-build-challenge-2.md +85 -38
  176. package/.bkit/core/prompts/bkit-build-install-skills.md +50 -28
  177. package/.bkit/core/prompts/bkit-build-plan-convert.md +85 -0
  178. package/.bkit/core/prompts/bkit-build-plan-current.md +59 -36
  179. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +101 -36
  180. package/.bkit/core/prompts/bkit-build-plan-tasks.md +149 -0
  181. package/.bkit/core/prompts/bkit-build-plan-tests.md +120 -0
  182. package/.bkit/core/prompts/bkit-build-plan-verify.md +104 -43
  183. package/.bkit/core/prompts/bkit-debug-abort-handover.md +47 -32
  184. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +109 -57
  185. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +65 -39
  186. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +53 -31
  187. package/.bkit/core/prompts/bkit-debug-failure-soak.md +65 -34
  188. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +46 -31
  189. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +45 -31
  190. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +43 -30
  191. package/.bkit/core/prompts/bkit-design-generate.md +80 -46
  192. package/.bkit/core/prompts/bkit-design-organise.md +83 -32
  193. package/.bkit/core/prompts/bkit-design-review-1.md +70 -50
  194. package/.bkit/core/prompts/bkit-design-review-2.md +65 -46
  195. package/.bkit/core/prompts/bkit-design-spike.md +64 -40
  196. package/.bkit/core/prompts/bkit-design-update.md +53 -28
  197. package/.bkit/core/prompts/bkit-plan-generate.md +101 -29
  198. package/.bkit/core/prompts/bkit-plan-review-1.md +78 -41
  199. package/.bkit/core/prompts/bkit-plan-review-2.md +78 -35
  200. package/.bkit/core/prompts/bkit-plan-scope-check.md +116 -0
  201. package/.bkit/core/prompts/bkit-plan-update.md +86 -31
  202. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +94 -50
  203. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +91 -41
  204. package/.bkit/core/prompts/bkit-ship-update-docs.md +45 -24
  205. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +65 -49
  206. package/.bkit/core/prompts/bkit-utility-update-decisions.md +87 -42
  207. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +81 -37
  208. package/.bkit/core/prompts/bkit-utility-update-documentation.md +43 -25
  209. package/.bkit/core/prompts/bkit-utility-update-failures.md +84 -37
  210. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +88 -42
  211. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +92 -39
  212. package/.bkit/core/prompts/bkit-utility-update-tracker.md +159 -60
  213. package/.bkit/core/workflows/bkit-auto.md +89 -58
  214. package/.bkit/core/workflows/bkit-build.md +967 -517
  215. package/.bkit/core/workflows/bkit-debug.md +555 -387
  216. package/.bkit/core/workflows/bkit-design.md +319 -283
  217. package/.bkit/core/workflows/bkit-plan.md +319 -342
  218. package/.bkit/core/workflows/bkit-ship.md +525 -328
  219. package/.bkit/shared/.agents/plugins/bkit/hooks.json +10 -0
  220. package/.bkit/shared/.bkit/.env.example +2 -2
  221. package/.bkit/shared/.claude/bkit-cloud.md +12 -10
  222. package/.bkit/shared/.claude/settings.json +14 -0
  223. package/.bkit/shared/.codex/bkit-cloud.md +98 -0
  224. package/.bkit/shared/.codex/hooks.json +20 -0
  225. package/.bkit/shared/.cursor/bkit-cloud.md +3 -3
  226. package/.bkit/shared/.cursor/mcp.json +1 -1
  227. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +1 -1
  228. package/.bkit/shared/.gitattributes +1 -1
  229. package/.bkit/shared/.mcp.json +1 -1
  230. package/.bkit/shared/.opencode/opencode.json +12 -1
  231. package/.bkit/shared/CLAUDE.md +6 -2
  232. package/.bkit/shared/GEMINI.md +5 -2
  233. package/.bkit/shared/docs/architecture.md +4 -7
  234. package/.bkit/shared/docs/data-schema.md +4 -7
  235. package/.bkit/shared/docs/deployments.md +241 -168
  236. package/.bkit/shared/docs/design.md +11 -12
  237. package/.bkit/shared/docs/noise.md +8 -7
  238. package/.bkit/shared/docs/observability.md +5 -8
  239. package/.bkit/shared/docs/security.md +35 -17
  240. package/.bkit/shared/docs/setup.md +29 -18
  241. package/.bkit/shared/docs/technology.md +3 -6
  242. package/.bkit/shared/docs/testing.md +289 -174
  243. package/.bkit/shared/gitignore +6 -2
  244. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +15 -16
  245. package/.bkit/templates/.cursor/Dockerfile +12 -8
  246. package/.bkit/templates/.cursor/environment.json +1 -1
  247. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-bug.yml +10 -8
  248. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +45 -12
  249. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +3 -3
  250. package/.bkit/templates/.github/renovate.json5 +34 -6
  251. package/.bkit/templates/.github/workflows/bkit-ci.yml +54 -51
  252. package/.bkit/templates/.github/workflows/bkit-cloud.yml +34 -33
  253. package/.bkit/templates/.github/workflows/bkit-health.yml +97 -0
  254. package/.bkit/templates/.github/workflows/bkit-renovate.yml +5 -4
  255. package/.bkit/templates/.github/workflows/bkit-trivy.yml +5 -4
  256. package/.bkit/templates/.husky/pre-commit +2 -2
  257. package/.bkit/templates/.husky/pre-push +96 -36
  258. package/.bkit/templates/.prettierignore +6 -0
  259. package/.bkit/templates/.vale.ini +27 -27
  260. package/.bkit/templates/context/bkit-cloudrun.md +23 -15
  261. package/.bkit/templates/context/bkit-expo.md +70 -52
  262. package/.bkit/templates/context/bkit-github.md +93 -56
  263. package/.bkit/templates/context/bkit-inngest.md +21 -15
  264. package/.bkit/templates/context/bkit-maestro.md +22 -16
  265. package/.bkit/templates/context/bkit-playwright.md +23 -17
  266. package/.bkit/templates/context/bkit-resend.md +12 -10
  267. package/.bkit/templates/context/bkit-sentry.md +30 -20
  268. package/.bkit/templates/context/bkit-serena.md +8 -7
  269. package/.bkit/templates/context/bkit-stripe.md +14 -13
  270. package/.bkit/templates/context/bkit-supabase.md +16 -13
  271. package/.bkit/templates/context/bkit-tavily.md +14 -11
  272. package/.bkit/templates/context/bkit-vercel.md +27 -18
  273. package/.bkit/templates/docs/capabilities.md +15 -14
  274. package/.bkit/templates/scripts/ci/{check-accepted-divergences.mjs → bkit-check-accepted-divergences.mjs} +6 -3
  275. package/.bkit/templates/scripts/ci/{check-accepted-divergences.test.mjs → bkit-check-accepted-divergences.test.mjs} +3 -3
  276. package/.bkit/templates/scripts/ci/{check-capstone.mjs → bkit-check-capstone.mjs} +2 -2
  277. package/.bkit/templates/scripts/ci/{check-capstone.test.mjs → bkit-check-capstone.test.mjs} +4 -4
  278. package/.bkit/templates/scripts/ci/{check-dependency-audit.mjs → bkit-check-dependency-audit.mjs} +103 -18
  279. package/.bkit/templates/scripts/ci/{check-dependency-audit.test.mjs → bkit-check-dependency-audit.test.mjs} +31 -3
  280. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +387 -0
  281. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +75 -0
  282. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +160 -0
  283. package/.bkit/templates/scripts/ci/lanes/{resolve-push-base.mjs → bkit-resolve-push-base.mjs} +3 -3
  284. package/.bkit/templates/scripts/ci/lanes/{resolve-push-base.test.mjs → bkit-resolve-push-base.test.mjs} +4 -4
  285. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +10 -2
  286. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +1 -1
  287. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +3 -3
  288. package/.bkit/templates/scripts/graphify/bkit-graph-embed.py +63 -0
  289. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +2 -2
  290. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +69 -18
  291. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +3 -3
  292. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +1 -1
  293. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  294. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +197 -126
  295. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +64 -41
  296. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +23 -7
  297. package/.bkit/templates/slop-scan.config.json +9 -2
  298. package/CHANGELOG.md +231 -0
  299. package/README.md +278 -89
  300. package/dist/checks/after/auth.js +36 -33
  301. package/dist/checks/after/ci-yml.js +91 -30
  302. package/dist/checks/after/github.js +91 -17
  303. package/dist/checks/after/index.js +22 -11
  304. package/dist/checks/after/suppression.js +8 -5
  305. package/dist/checks/after/tools.js +111 -114
  306. package/dist/checks/before/context-fetch.js +218 -33
  307. package/dist/checks/before/env.js +3 -3
  308. package/dist/checks/before/files.js +5 -3
  309. package/dist/checks/before/index.js +20 -3
  310. package/dist/checks/before/repo.js +197 -2
  311. package/dist/checks/status-holes.js +739 -114
  312. package/dist/checks/tips/catalogue.js +70 -19
  313. package/dist/checks/tips/detect.js +62 -0
  314. package/dist/checks/tips/index.js +51 -9
  315. package/dist/cli.js +234 -124
  316. package/dist/commands/analysis.js +174 -141
  317. package/dist/commands/ci/ci.js +302 -25
  318. package/dist/commands/ci/pins.js +142 -0
  319. package/dist/commands/ci/push-gate.js +194 -0
  320. package/dist/commands/comply.js +54 -91
  321. package/dist/commands/install/doctor.js +2 -2
  322. package/dist/commands/install/install.js +50 -19
  323. package/dist/commands/install/uninstall.js +82 -55
  324. package/dist/commands/install/upgrade.js +21 -11
  325. package/dist/commands/land.js +137 -17
  326. package/dist/commands/lib.js +295 -21
  327. package/dist/commands/registry.js +10 -2
  328. package/dist/commands/setup/setup.js +8 -7
  329. package/dist/commands/stats.js +175 -0
  330. package/dist/commands/tips.js +7 -3
  331. package/dist/commands/workflow/branches.js +1873 -152
  332. package/dist/commands/workflow/challenge.js +609 -0
  333. package/dist/commands/workflow/completeness.js +97 -0
  334. package/dist/commands/workflow/context.js +1045 -46
  335. package/dist/commands/workflow/counters.js +385 -86
  336. package/dist/commands/workflow/decisions.js +484 -0
  337. package/dist/commands/workflow/disk.js +214 -56
  338. package/dist/commands/workflow/fids.js +706 -33
  339. package/dist/commands/workflow/issues.js +349 -59
  340. package/dist/commands/workflow/ledgers.js +1123 -37
  341. package/dist/commands/workflow/locks.js +26 -2
  342. package/dist/commands/workflow/plan-blocks.js +501 -0
  343. package/dist/commands/workflow/plan-versions.js +22 -0
  344. package/dist/commands/workflow/plans.js +205 -0
  345. package/dist/commands/workflow/prs.js +154 -35
  346. package/dist/commands/workflow/repo.js +58 -8
  347. package/dist/commands/workflow/roadmap.js +58 -23
  348. package/dist/commands/workflow/run-facts.js +421 -0
  349. package/dist/commands/workflow/runs.js +670 -72
  350. package/dist/commands/workflow/runtime.js +15 -1
  351. package/dist/commands/workflow/skills.js +1 -0
  352. package/dist/commands/workflow/status.js +282 -34
  353. package/dist/commands/workflow/step-table.js +308 -0
  354. package/dist/commands/workflow/steps.js +703 -96
  355. package/dist/commands/workflow/summary-findings.js +117 -0
  356. package/dist/commands/workflow/summary.js +388 -0
  357. package/dist/commands/workflow/tasks.js +378 -0
  358. package/dist/commands/workflow/test-blocks.js +231 -0
  359. package/dist/commands/workflow/tests-changed.js +172 -0
  360. package/dist/commands/workflow/tests.js +1695 -305
  361. package/dist/commands/workflow/tracker.js +983 -0
  362. package/dist/commands/workflow/workflows.js +1014 -222
  363. package/dist/commands/workflow/worktrees.js +432 -26
  364. package/dist/install/cloud-env.js +233 -99
  365. package/dist/install/context-ci-workflow.js +85 -0
  366. package/dist/install/manifest.js +64 -17
  367. package/dist/install/modules/antigravity.js +3 -2
  368. package/dist/install/modules/cloud.js +25 -16
  369. package/dist/install/modules/codex.js +12 -2
  370. package/dist/install/modules/core.js +1090 -48
  371. package/dist/install/modules/cursor.js +6 -6
  372. package/dist/install/modules/opencode.js +13 -7
  373. package/dist/install/template-notes.js +116 -0
  374. package/dist/install/version-file.js +9 -4
  375. package/dist/ledgers/compact.js +87 -0
  376. package/dist/ledgers/journal.js +233 -0
  377. package/dist/ledgers/migrate.js +81 -0
  378. package/dist/ledgers/status.js +176 -13
  379. package/dist/ledgers/telemetry.js +1010 -125
  380. package/dist/render/hosts.js +104 -14
  381. package/dist/render/models.js +12 -0
  382. package/dist/shared/bkit-latest.js +26 -4
  383. package/dist/shared/branches.js +3 -1
  384. package/dist/shared/dep-updater.js +49 -0
  385. package/dist/shared/egress.js +8 -1
  386. package/dist/shared/json.js +20 -7
  387. package/dist/shared/package-manager.js +6 -0
  388. package/dist/shared/settings.js +181 -24
  389. package/dist/shared/text.js +333 -0
  390. package/dist/shared/timeouts.js +2 -0
  391. package/dist/tools/cli-doc.js +97 -0
  392. package/dist/tools/grammar-density.js +183 -0
  393. package/dist/tools/instructions-sources.js +720 -0
  394. package/dist/tools/instructions.js +1623 -0
  395. package/package.json +156 -51
  396. package/.bkit/core/.bkit/lite.md +0 -73
  397. package/.bkit/core/engine/commands/harvest.ts +0 -459
  398. package/.bkit/core/engine/commands/workflow/workstreams.ts +0 -166
  399. package/.bkit/core/engine/tools/wording.ts +0 -748
  400. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +0 -69
  401. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +0 -71
  402. package/.bkit/core/prompts/bkit-build-challenge-tests.md +0 -74
  403. package/.bkit/core/prompts/bkit-build-plan-execute.md +0 -76
  404. package/.bkit/core/prompts/bkit-build-summary.md +0 -94
  405. package/.bkit/core/prompts/bkit-debug-summary.md +0 -96
  406. package/.bkit/core/prompts/bkit-design-summary.md +0 -107
  407. package/.bkit/core/prompts/bkit-plan-complexity-check.md +0 -67
  408. package/.bkit/core/prompts/bkit-plan-complexity-split.md +0 -88
  409. package/.bkit/core/prompts/bkit-plan-review-3.md +0 -93
  410. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +0 -85
  411. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +0 -85
  412. package/.bkit/core/prompts/bkit-plan-summary.md +0 -107
  413. package/.bkit/core/prompts/bkit-ship-summary.md +0 -78
  414. package/.bkit/templates/scripts/ci/bkit-local-stack-lock.sh +0 -194
  415. package/dist/commands/harvest.js +0 -353
  416. package/dist/commands/workflow/workstreams.js +0 -143
  417. package/dist/tools/wording.js +0 -680
  418. /package/.bkit/templates/.vale/styles/{House → Bkit}/Filler.yml +0 -0
  419. /package/.bkit/templates/.vale/styles/{House → Bkit}/Hedging.yml +0 -0
  420. /package/.bkit/templates/.vale/styles/{House → Bkit}/LLMSlop.yml +0 -0
  421. /package/.bkit/templates/.vale/styles/{House → Bkit}/Verbose.yml +0 -0
  422. /package/.bkit/templates/scripts/ci/{accepted-advisories.json → bkit-accepted-advisories.json} +0 -0
  423. /package/.bkit/templates/scripts/ci/{accepted-divergences.json → bkit-accepted-divergences.json} +0 -0
  424. /package/.bkit/templates/scripts/launchd/{launchd.env.example → bkit-launchd.env.example} +0 -0
  425. /package/.bkit/templates/scripts/launchd/{ai.bkit.launchd.plist → bkit-launchd.plist} +0 -0
@@ -1,4 +1,4 @@
1
- // bkit workflows start|fail|handover|close|promote|links — a phase workflow's
1
+ // bkit workflows start|fail|handover|close|promote|links|summary — a phase workflow's
2
2
  // lifecycle state.
3
3
  //
4
4
  // start takes the feature lock (or checks the one Step 1 took) and opens a run
@@ -7,7 +7,7 @@
7
7
  // fail the Failure Path's state and payloads: `workflow-failed` row, abort an
8
8
  // in-progress rebase, release the lock, clear the sentinels, say whether
9
9
  // a handover is due, and print the `bkit:failed` label set and the
10
- // failure comment. The tracker calls stay in the workflow.
10
+ // failure comment; `--post` sends both to the issue.
11
11
  // handover after the handover subagent: commit and abort-push it (`--push`), or
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
@@ -17,30 +17,43 @@
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.
20
+ // summary the Summary step: `{workflow}-summary.md` with its verdict, reasons and
21
+ // next command, from the run's rows, logs, plan and ledger rows.
20
22
 
21
23
  import * as fs from "node:fs";
24
+ import * as os from "node:os";
22
25
  import * as path from "node:path";
23
26
 
24
27
  import {
25
28
  appendLine,
26
29
  fold,
30
+ lastRun,
27
31
  runNumber,
28
32
  runOrStepField,
29
33
  statusTimestamp,
30
34
  type StatusEvent,
35
+ type StatusRow,
31
36
  } from "../../ledgers/status.js";
32
37
  import {
33
- appendLine as telemetryLine,
38
+ compareTs,
34
39
  foldFrom,
40
+ normalize,
35
41
  resolveRepoSlug,
36
- validate,
37
42
  workflowTelemetry,
38
43
  type CoverageStats,
44
+ type OutcomePayload,
39
45
  } from "../../ledgers/telemetry.js";
40
- import { readBkitVersion } from "../../install/version-file.js";
41
- import { readBkitConfig } from "../../shared/settings.js";
46
+ import {
47
+ check as checkCompleteness,
48
+ deriveContract,
49
+ parseRows,
50
+ readCompleteness,
51
+ type StatusRow as HoleRow,
52
+ } from "../../checks/status-holes.js";
53
+ import { getWorkflowsRoot } from "../../shared/package-roots.js";
54
+ import { ASK_POINTS, readBkitConfig } from "../../shared/settings.js";
42
55
  import { gradeCompliance } from "../comply.js";
43
- import { landDir, pushToDev, type DevPush } from "../land.js";
56
+ import { fetchDev, landDir, pushToDev, type DevPush } from "../land.js";
44
57
  import {
45
58
  CommandError,
46
59
  DEV,
@@ -63,10 +76,43 @@ import {
63
76
  AUTO_LABEL,
64
77
  AUTO_ROUTE_SUFFIX,
65
78
  buildComment,
79
+ issueParts,
80
+ parseComments,
81
+ sortOldestFirst,
66
82
  trackerState,
67
83
  transitionLabels,
84
+ type IssueComment,
85
+ type IssuePart,
68
86
  } from "./issues.js";
69
- import { EXIT_EMPTY, commitBookkeeping, unionLedgers } from "./ledgers.js";
87
+ import {
88
+ EXIT_EMPTY,
89
+ activeRecord,
90
+ commitBookkeeping,
91
+ ownPathCommit,
92
+ ownSet,
93
+ removeRecord,
94
+ appendLedgerRows,
95
+ runRows,
96
+ unionLedgers,
97
+ } from "./ledgers.js";
98
+ import { readIssueTracker } from "./fids.js";
99
+ import {
100
+ agentContextBlock,
101
+ buildBlock,
102
+ chatFingerprint,
103
+ ciList,
104
+ claudeTranscripts,
105
+ hostChat,
106
+ planBlock,
107
+ planFiles,
108
+ runChats,
109
+ runLines,
110
+ runStatusRows,
111
+ stepsBlock,
112
+ timeBlock,
113
+ } from "./run-facts.js";
114
+ import { buildSummary, refOf, SUMMARY_WORKFLOWS, type SummaryWorkflow } from "./summary.js";
115
+ import { parsePlans, parseWorkstreams } from "./plans.js";
70
116
  import {
71
117
  EXIT_REMOVE_FAILED,
72
118
  EXIT_SPLIT_BUCKET,
@@ -77,6 +123,7 @@ import {
77
123
  resolveMonth,
78
124
  workflowLockPath,
79
125
  } from "./locks.js";
126
+ import { highestVersion } from "./plan-versions.js";
80
127
  import { mergePr, probePr } from "./prs.js";
81
128
  import { FEATURE_STATUS } from "./roadmap.js";
82
129
  import {
@@ -88,8 +135,25 @@ import {
88
135
  readStatusRows,
89
136
  str,
90
137
  } from "./status.js";
91
- import { writeStepRow } from "./steps.js";
92
- import { removeWorktree, type RemoveResult } from "./worktrees.js";
138
+ import {
139
+ COMMENT_FILE_OUTPUT,
140
+ POST_FLAG,
141
+ TRACKER_OUTPUT,
142
+ attempt,
143
+ commentFileOf,
144
+ postForVerb,
145
+ issueRef,
146
+ readLabels,
147
+ endedRunActionKey,
148
+ skipOf,
149
+ trackerTarget,
150
+ writeLabels,
151
+ type TrackerOutcome,
152
+ } from "./tracker.js";
153
+ import type { TipsContext } from "../../cli.js";
154
+ import { tipsText } from "../tips.js";
155
+ import { EXIT_NO_RECORD, requireRecordOnShared, writeStepRow } from "./steps.js";
156
+ import { addAllButCopied, removeWorktree, type RemoveResult } from "./worktrees.js";
93
157
 
94
158
  /** Sentinels a workflow leaves in its logs folder; either one existing means a handover is due. */
95
159
  export const SENTINELS = [".rebase-failed", ".deferred-blocked"] as const;
@@ -104,6 +168,12 @@ export const EXIT_PUSH_FAILED = 10;
104
168
  export const EXIT_FLUSH_FAILED = 11;
105
169
  /** Exit code (promote): no versioned draft to promote. */
106
170
  export const EXIT_NO_VERSION = 12;
171
+ /** Exit code (input): a named input file is missing or not in the expected shape. */
172
+ export const EXIT_NO_INPUT = 13;
173
+ /** Exit code (start --branch): the checkout is not on the named branch. */
174
+ export const EXIT_WRONG_BRANCH = 15;
175
+ /** Exit code (summary): the status file has no run of the workflow. */
176
+ export const EXIT_NO_RUN = 16;
107
177
 
108
178
  // ---------------------------------------------------------------------------
109
179
  // Where things live
@@ -139,6 +209,92 @@ function whereInTree(
139
209
  }
140
210
 
141
211
  const headSha = (cwd: string) => git(cwd, ["rev-parse", "HEAD"]) ?? "";
212
+
213
+ /**
214
+ * Append a `session` row naming the chat that runs this start (`hostChat`), as its
215
+ * fingerprint, unless the current run's latest `session` row already names it. Nothing when
216
+ * the host names no chat. The close and the harvest read the run's chats from these rows.
217
+ */
218
+ export function recordChat(file: string, workflow: string, env: NodeJS.ProcessEnv): void {
219
+ const chat = hostChat(env);
220
+ if (chat === undefined) return;
221
+ const session = chatFingerprint(chat.platform, chat.id);
222
+ const events = readStatusEvents(file);
223
+ const startAt = lastOfType(events, "workflow-started", workflow)?.at;
224
+ const last = (events as Array<Record<string, unknown>>)
225
+ .filter(
226
+ (e) =>
227
+ e.type === "session" &&
228
+ e.workflow === workflow &&
229
+ (startAt === undefined || String(e.at) >= startAt),
230
+ )
231
+ .at(-1);
232
+ if (last?.session === session) return;
233
+ const row = {
234
+ type: "session",
235
+ workflow,
236
+ at: statusTimestamp(),
237
+ platform: chat.platform,
238
+ session,
239
+ };
240
+ fs.appendFileSync(file, appendLine(row));
241
+ }
242
+
243
+ /** An OPEN Decision Pause file of the current run, as `workflows start` prints it. */
244
+ export interface OpenDecision {
245
+ file: string;
246
+ decision: number;
247
+ question: string | null;
248
+ from: string | null;
249
+ pauseStep: number | null;
250
+ group: number | null;
251
+ verifyAttempt: number | null;
252
+ testAttempt: number | null;
253
+ plan: string | null;
254
+ }
255
+
256
+ /**
257
+ * The highest-numbered `{workflow}-decision-{run}-{N}.md` in `logDir` whose header holds
258
+ * `Status: OPEN`, or null. Only the given run's files count, so an earlier run's pause
259
+ * never resurfaces. `file` is relative to `tree`.
260
+ */
261
+ export function openDecision(
262
+ logDir: string,
263
+ tree: string,
264
+ workflow: string,
265
+ run: number,
266
+ ): OpenDecision | null {
267
+ if (!fs.existsSync(logDir)) return null;
268
+ const name = new RegExp(`^${workflow}-decision-${run}-([0-9]+)\\.md$`);
269
+ const found = fs
270
+ .readdirSync(logDir)
271
+ .map((f) => ({ f, m: name.exec(f) }))
272
+ .filter((x): x is { f: string; m: RegExpExecArray } => x.m !== null)
273
+ .map(({ f, m }) => ({ f, n: Number(m[1]) }))
274
+ .sort((a, b) => b.n - a.n);
275
+ for (const { f, n } of found) {
276
+ const text = fs.readFileSync(path.join(logDir, f), "utf-8");
277
+ const field = (key: string) =>
278
+ new RegExp(`^${key}:[ \\t]*(.+?)[ \\t]*$`, "m").exec(text)?.[1] ?? null;
279
+ if (field("Status") !== "OPEN") continue;
280
+ const num = (key: string) => {
281
+ const v = field(key);
282
+ return v !== null && /^[0-9]+$/.test(v) ? Number(v) : null;
283
+ };
284
+ return {
285
+ file: path.relative(tree, path.join(logDir, f)),
286
+ decision: n,
287
+ question: field("Question"),
288
+ from: field("From"),
289
+ pauseStep: num("Pause step"),
290
+ group: num("Group"),
291
+ verifyAttempt: num("Verify attempt"),
292
+ testAttempt: num("Test attempt"),
293
+ plan: field("Plan"),
294
+ };
295
+ }
296
+ return null;
297
+ }
142
298
  const logDirRel = (month: string, fid: string) => path.join("docs", "plans", month, "logs", fid);
143
299
  const list = (v: FlagValue) => (v as string[] | undefined) ?? [];
144
300
 
@@ -158,17 +314,23 @@ function checkHeldLock(file: string, who: { workflow: string; fid: string; token
158
314
  // ---------------------------------------------------------------------------
159
315
 
160
316
  /**
161
- * Abort a rebase left in progress in `tree`. `git rev-parse --git-path X` always
162
- * exits 0 (it only computes the path), so the directory's existence is the test.
317
+ * Abort a rebase or a merge left in progress in `tree` (ship Step 4 leaves a merge
318
+ * of origin/dev in progress for a hand resolution). `git rev-parse --git-path X`
319
+ * always exits 0 (it only computes the path), so the path's existence is the test.
163
320
  */
164
321
  function abortRebase(tree: string, log: (m: string) => void): boolean {
165
- const inProgress = ["rebase-merge", "rebase-apply"].some((name) => {
322
+ const present = (name: string) => {
166
323
  const p = git(tree, ["rev-parse", "--path-format=absolute", "--git-path", name]);
167
324
  return p !== null && fs.existsSync(p);
168
- });
169
- if (!inProgress) return false;
170
- const res = runGit(tree, ["rebase", "--abort"]);
171
- if (!res.ok) log(`git rebase --abort failed in ${tree}: ${res.stderr}`);
325
+ };
326
+ const op = ["rebase-merge", "rebase-apply"].some(present)
327
+ ? "rebase"
328
+ : present("MERGE_HEAD")
329
+ ? "merge"
330
+ : null;
331
+ if (op === null) return false;
332
+ const res = runGit(tree, [op, "--abort"]);
333
+ if (!res.ok) log(`git ${op} --abort failed in ${tree}: ${res.stderr}`);
172
334
  return res.ok;
173
335
  }
174
336
 
@@ -224,10 +386,10 @@ function failState(ctx: RunContext, workflow: string, fid: string) {
224
386
  fs.rmSync(p, { force: true });
225
387
  }
226
388
  }
227
- return { row, rebaseAborted, lock, sentinels, removeFailed, soak };
389
+ return { row, rebaseAborted, lock, sentinels, removeFailed, soak, status };
228
390
  }
229
391
 
230
- function failVerb(ctx: RunContext): number {
392
+ async function failVerb(ctx: RunContext): Promise<number> {
231
393
  const workflow = workflowName(String(ctx.flags.workflow));
232
394
  // An empty value is a placeholder not held yet (the failure came before it was set).
233
395
  const fid = str(ctx.flags.fid) || undefined;
@@ -246,6 +408,7 @@ function failVerb(ctx: RunContext): number {
246
408
  sentinels: [],
247
409
  removeFailed: false,
248
410
  soak: false,
411
+ status: undefined,
249
412
  }
250
413
  : failState(ctx, workflow, fid);
251
414
 
@@ -258,10 +421,15 @@ function failVerb(ctx: RunContext): number {
258
421
  }
259
422
  const merged = prState === "MERGED";
260
423
  const transition = merged ? { phase: "merged" } : { failed: true };
424
+ const failedSet = (current: string[]) => {
425
+ const labels = transitionLabels(current, transition).labels;
426
+ if (merged && !labels.includes("bkit:failed")) labels.push("bkit:failed");
427
+ return labels;
428
+ };
261
429
  const current = list(ctx.flags.label);
262
- const labels = transitionLabels(current, transition).labels;
263
- if (merged && !labels.includes("bkit:failed")) labels.push("bkit:failed");
430
+ const labels = failedSet(current);
264
431
  const add = labels.filter((l) => !current.includes(l));
432
+ const failedState = trackerState(transition, undefined, readBkitConfig(repoRoot(ctx.cwd)));
265
433
 
266
434
  // The failure comment, when the step is named.
267
435
  let comment: string | null = null;
@@ -279,6 +447,26 @@ function failVerb(ctx: RunContext): number {
279
447
  stderrFile: str(ctx.flags.stderrFile) || undefined,
280
448
  });
281
449
  }
450
+ if (ctx.flags.post === true && comment === null)
451
+ throw new CommandError(EXIT.USAGE, "--post needs --step-number");
452
+ // Once per run and step: an engine-action row where the run's status.jsonl exists.
453
+ const key = endedRunActionKey(
454
+ state.status,
455
+ workflow,
456
+ "failure",
457
+ stepNumber,
458
+ str(ctx.flags.subStep) || undefined,
459
+ );
460
+ const tracker =
461
+ ctx.flags.post === true && comment !== null
462
+ ? await postForVerb(ctx, comment, {
463
+ fid,
464
+ issue: str(ctx.flags.issue),
465
+ ...(key === undefined ? {} : { file: state.status, key }),
466
+ })
467
+ : undefined;
468
+ const labelsWrite =
469
+ ctx.flags.post === true ? await writeFailedLabels(ctx, fid, failedSet, failedState) : undefined;
282
470
 
283
471
  ctx.emit({
284
472
  row: state.row,
@@ -290,13 +478,42 @@ function failVerb(ctx: RunContext): number {
290
478
  (ctx.flags.maxExceeded === true || state.sentinels.length > 0 || state.soak),
291
479
  add,
292
480
  labels,
293
- trackerState: trackerState(transition, undefined, readBkitConfig(repoRoot(ctx.cwd))),
481
+ trackerState: failedState,
294
482
  prState,
295
483
  comment,
484
+ commentFile: commentFileOf(ctx.cwd, comment),
485
+ ...(tracker === undefined ? {} : { tracker }),
486
+ ...(labelsWrite === undefined ? {} : { labelsWrite }),
487
+ ...sessionRemoval(ctx),
296
488
  });
297
489
  return state.removeFailed ? EXIT_REMOVE_FAILED : EXIT.OK;
298
490
  }
299
491
 
492
+ /**
493
+ * `fail --post`: read the issue's labels, write the failed set and the review state.
494
+ * The set comes from the labels read, not `--label`, so a label added since Step 1 stays.
495
+ */
496
+ async function writeFailedLabels(
497
+ ctx: RunContext,
498
+ fid: string | undefined,
499
+ failedSet: (current: string[]) => string[],
500
+ state: string | null,
501
+ ): Promise<TrackerOutcome> {
502
+ const t = trackerTarget(ctx.cwd, { fid, issue: str(ctx.flags.issue) });
503
+ const skip = skipOf(t);
504
+ if (skip) return skip;
505
+ return attempt("labels", ctx.log, async () => {
506
+ const current = await readLabels(t);
507
+ const labels = failedSet(current);
508
+ await writeLabels(t, {
509
+ add: labels.filter((l) => !current.includes(l)),
510
+ remove: current.filter((l) => !labels.includes(l)),
511
+ labels,
512
+ state,
513
+ });
514
+ });
515
+ }
516
+
300
517
  /** A text file's content, trailing newlines dropped; a missing file is a usage error. */
301
518
  function readText(cwd: string, rel: string): string {
302
519
  const abs = path.resolve(cwd, rel);
@@ -353,12 +570,54 @@ const SHARED_LEDGERS = [
353
570
  ":(exclude).bkit/issues.jsonl",
354
571
  ];
355
572
 
573
+ /**
574
+ * Kinds no workflow run writes: bkit's harvest script writes them to `harvest/`, and a
575
+ * `run` row names any feature's workflow (`.bkit/jsonl.md` § Ledgers & Writers).
576
+ */
577
+ const NOT_A_RUNS_OWN_KIND = new Set(["chat", "run"]);
578
+
579
+ /** HEAD and every `parentSha` the run's status rows of `workflow` carry: the shas its `run.parentSha` can name. */
580
+ function runShas(src: string, status: string, workflow: string): Set<string> {
581
+ const shas = new Set<string>([headSha(src)]);
582
+ for (const e of fs.existsSync(status) ? readStatusEvents(status) : []) {
583
+ const sha = (e as Record<string, unknown>).parentSha;
584
+ if (e.workflow === workflow && typeof sha === "string") shas.add(sha);
585
+ }
586
+ shas.delete("");
587
+ return shas;
588
+ }
589
+
590
+ /** A feature id in `references`: a bare number or `{N}-{slug}`. */
591
+ const FEATURE_REF = /^\d+(-[a-z0-9-]+)?$/;
592
+
593
+ /**
594
+ * A shared-ledger row (normalized) of THIS run: a row of `workflow` at or after its
595
+ * start, never a kind no run writes. A row with `run.parentSha` (compliance, counter,
596
+ * outcome) must name one of the run's shas; any other row must not point at a
597
+ * different feature in its `references`.
598
+ */
599
+ function isRunsOwnRow(
600
+ row: Record<string, unknown>,
601
+ o: { fid: string; workflow: string; startMs: number | undefined },
602
+ shas: Set<string>,
603
+ ): boolean {
604
+ if (byWorkflow(row) !== o.workflow || !(Number(row.ts) >= o.startMs!)) return false;
605
+ if (NOT_A_RUNS_OWN_KIND.has(String(row.kind))) return false;
606
+ const sha = (row.run as Record<string, unknown> | undefined)?.parentSha;
607
+ if (sha !== undefined) return typeof sha === "string" && shas.has(sha);
608
+ const features = (Array.isArray(row.references) ? row.references : [])
609
+ .map(String)
610
+ .filter((r) => FEATURE_REF.test(r));
611
+ const n = /^(\d+)-/.exec(o.fid)?.[1];
612
+ return features.length === 0 || features.some((r) => r === o.fid || r === n);
613
+ }
614
+
356
615
  /**
357
616
  * Carry ONLY the run's own record out of a dev / main / detached checkout, which
358
617
  * other sessions and local-only commits share: the `.md` logs it wrote in its log
359
618
  * folder; the lines of that folder's `.jsonl` files its HEAD lacks; and, from the
360
- * shared ledgers, lines its HEAD lacks that are rows of `workflow` at or after
361
- * the run's start (`startMs`). No start known → no shared-ledger row is carried.
619
+ * shared ledgers, lines its HEAD lacks that are this run's rows ({@link isRunsOwnRow}).
620
+ * No start known → no shared-ledger row is carried.
362
621
  */
363
622
  function carryOwnBook(
364
623
  src: string,
@@ -368,12 +627,9 @@ function carryOwnBook(
368
627
  ): Carried {
369
628
  const rel = logDirRel(o.month, o.fid);
370
629
  const carried: Carried = { files: carryLogs(src, dst, rel), lines: new Map() };
371
- const uncommitted = (file: string) => {
372
- const head = new Set(textLines(git(src, ["show", `HEAD:${file}`]) ?? "").map((l) => l.trim()));
373
- return textLines(fs.readFileSync(path.join(src, file), "utf-8")).filter(
374
- (l) => !head.has(l.trim()),
375
- );
376
- };
630
+ // Rows the run appended; on a shared checkout, recorded foreign rows are never carried.
631
+ const rec = activeRecord(src, o.fid);
632
+ const uncommitted = (file: string) => runRows(src, file, rec);
377
633
  const add = (file: string, lines: string[]) => {
378
634
  const to = path.join(dst, file);
379
635
  const existing = fs.existsSync(to) ? fs.readFileSync(to, "utf-8") : "";
@@ -395,11 +651,11 @@ function carryOwnBook(
395
651
  log(`no ${o.workflow} start row for ${o.fid} — no shared-ledger row carried`);
396
652
  return carried;
397
653
  }
654
+ const shas = runShas(src, path.join(src, statusRelPath(o.month, o.fid)), o.workflow);
398
655
  for (const file of listed(SHARED_LEDGERS)) {
399
656
  const own = uncommitted(file).filter((l) => {
400
- const parsed = parseJson(l);
401
- const row = parsed.ok ? (parsed.value as Record<string, unknown> | null) : null;
402
- return row?.workflow === o.workflow && Number(row.ts) >= o.startMs!;
657
+ const row = parseObject(l);
658
+ return row !== undefined && isRunsOwnRow(normalize(row), o, shas);
403
659
  });
404
660
  if (own.length > 0) add(file, own);
405
661
  }
@@ -412,14 +668,23 @@ function carryOwnBook(
412
668
  * log identical to the landed copy is removed when untracked, or returns to HEAD
413
669
  * when tracked. A carried ledger loses exactly the carried lines; it returns to
414
670
  * HEAD when that leaves it equal, and an untracked one left empty is removed.
415
- * Anything staged, or a log changed since it landed, stays and is named.
671
+ * Anything staged, or a log changed since it landed, stays and is named. A path
672
+ * the shared-checkout record lists is never reset or removed.
416
673
  */
417
- function handBack(tree: string, sha: string, carried: Carried, log: (line: string) => void): void {
674
+ function handBack(
675
+ tree: string,
676
+ sha: string,
677
+ carried: Carried,
678
+ log: (line: string) => void,
679
+ recorded: ReadonlySet<string> = new Set(),
680
+ ): void {
418
681
  const back: string[] = [];
419
682
  const kept: string[] = [];
420
683
  const staged = (rel: string) => !runGit(tree, ["diff", "--cached", "--quiet", "--", rel]).ok;
421
684
  const tracked = (rel: string) => runGit(tree, ["ls-files", "--error-unmatch", "--", rel]).ok;
422
685
  for (const rel of carried.files) {
686
+ // A path that was dirty before the run started is not the run's to reset.
687
+ if (recorded.has(rel)) continue;
423
688
  const abs = path.join(tree, rel);
424
689
  const landed = runGit(tree, ["show", `${sha}:${rel}`]);
425
690
  const same =
@@ -566,6 +831,20 @@ async function landFailedRecord(
566
831
  }
567
832
  }
568
833
 
834
+ /**
835
+ * What `handover --push` would sweep into the abort commit besides the run's own
836
+ * logs: tracked files with changes, and untracked files (each one listed, not its folder).
837
+ */
838
+ function strayPaths(tree: string, logDir: string): { modified: string[]; untracked: string[] } {
839
+ const outside = (out: string | null) =>
840
+ (out ?? "").split("\0").filter((p) => p !== "" && p !== logDir && !p.startsWith(`${logDir}/`));
841
+ return {
842
+ // Staged and unstaged changes alike, against HEAD.
843
+ modified: outside(git(tree, ["diff", "--name-only", "-z", "--no-renames", "HEAD"])),
844
+ untracked: outside(git(tree, ["ls-files", "-z", "--others", "--exclude-standard"])),
845
+ };
846
+ }
847
+
569
848
  async function handoverVerb(ctx: RunContext): Promise<number> {
570
849
  const workflow = workflowName(String(ctx.flags.workflow));
571
850
  const fid = String(ctx.flags.fid);
@@ -589,7 +868,17 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
589
868
  const branch = git(tree, ["branch", "--show-current"]) ?? "";
590
869
  // A dev / main / detached checkout is shared: only the run's own record leaves it.
591
870
  const shared = branch === "" || isSharedBranch(branch);
871
+ if (ctx.flags.listStray === true) {
872
+ if (push || flush || ctx.flags.post === true)
873
+ throw new CommandError(
874
+ EXIT.USAGE,
875
+ "--list-stray only lists: drop --push, --flush and --post",
876
+ );
877
+ ctx.emit({ shared, ...strayPaths(tree, logDirRel(month, fid)) });
878
+ return EXIT.OK;
879
+ }
592
880
  let handed: { sha: string; carried: Carried } | undefined;
881
+ const rec = shared && (push || flush) ? activeRecord(tree, fid) : null;
593
882
  if (push && shared) {
594
883
  const r = await landFailedRecord(ctx, { workflow, fid, month, book: tree, shared });
595
884
  if (r.sha !== undefined && r.carried !== undefined) handed = { sha: r.sha, carried: r.carried };
@@ -598,10 +887,11 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
598
887
  ref = r.ref;
599
888
  skipped = r.skipped;
600
889
  } else if (push) {
601
- runGit(tree, ["add", "-A"]);
890
+ const added = addAllButCopied(tree);
891
+ if (!added.ok) ctx.log(`abort commit: git add failed: ${added.stderr}`);
602
892
  const made = runGit(tree, ["commit", "-m", `docs(${fid}): ${workflow} aborted bkit [skip ci]`]);
603
893
  if (!made.ok) ctx.log(`abort commit: ${made.stderr || made.stdout}`);
604
- const r = pushBranch(tree, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
894
+ const r = await pushBranch(tree, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
605
895
  if (r.code === EXIT.USE_MCP) return r.code;
606
896
  pushed = r.out.pushed;
607
897
  ref = r.out.ref;
@@ -631,13 +921,23 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
631
921
  bodyFile: artifact,
632
922
  })
633
923
  : null;
634
- if (handed !== undefined) handBack(tree, handed.sha, handed.carried, ctx.log);
924
+ if (handed !== undefined) {
925
+ handBack(tree, handed.sha, handed.carried, ctx.log, new Set(rec?.paths.map((p) => p.path)));
926
+ }
927
+ // The run is over once its record is handed back: the next run starts a fresh one.
928
+ if (rec !== null) removeRecord(tree, fid);
929
+ const tracker =
930
+ ctx.flags.post === true && comment !== null
931
+ ? await postForVerb(ctx, comment, { fid })
932
+ : undefined;
635
933
  ctx.emit({
636
934
  handover: present ? artifact : null,
637
935
  pushed,
638
936
  ref: pushed ? ref : null,
639
937
  skipped,
640
938
  comment,
939
+ commentFile: commentFileOf(ctx.cwd, comment),
940
+ ...(tracker === undefined ? {} : { tracker }),
641
941
  });
642
942
  return code;
643
943
  }
@@ -646,16 +946,14 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
646
946
  // close
647
947
  // ---------------------------------------------------------------------------
648
948
 
649
- interface Ledgers {
650
- frictionAdded?: number;
651
- deferralsAdded?: number;
652
- failuresAdded?: number;
653
- deferrals: number;
654
- failures: number;
655
- }
949
+ type Ledgers = OutcomePayload["ledgers"];
950
+
951
+ /** The row's `by.workflow`, on a row already normalized. */
952
+ const byWorkflow = (r: Record<string, unknown>) =>
953
+ (r.by as Record<string, unknown> | undefined)?.workflow;
656
954
 
657
955
  /** Rows of a JSONL ledger; malformed lines are skipped, a missing file is empty. */
658
- function ledgerRows(file: string): Array<Record<string, unknown>> {
956
+ export function ledgerRows(file: string): Array<Record<string, unknown>> {
659
957
  if (!fs.existsSync(file)) return [];
660
958
  return fs
661
959
  .readFileSync(file, "utf-8")
@@ -688,49 +986,31 @@ const distinctKeys = (rows: Array<Record<string, unknown>>) =>
688
986
  * counting the ledger's whole history as this run's.
689
987
  */
690
988
  function ledgerCounts(tree: string, workflow: string, startMs: number | undefined): Ledgers {
691
- const deferrals = ledgerRows(path.join(tree, "docs", "deferrals.jsonl"));
692
- const failures = ledgerRows(path.join(tree, "docs", "failures.jsonl"));
693
- const friction = ledgerRows(path.join(tree, ".bkit", "friction.jsonl"));
989
+ const read = (file: string) => ledgerRows(file).map((r) => normalize(r));
990
+ const deferrals = read(path.join(tree, "docs", "deferrals.jsonl"));
991
+ const failures = read(path.join(tree, "docs", "failures.jsonl"));
992
+ const friction = read(path.join(tree, ".bkit", "friction.jsonl"));
694
993
  const added = (rows: Array<Record<string, unknown>>) =>
695
- distinctKeys(rows.filter((r) => r.workflow === workflow && Number(r.ts) >= startMs!));
696
- return {
697
- deferrals: distinctKeys(deferrals.filter((r) => r.kind === "deferral")),
698
- failures: distinctKeys(failures.filter((r) => r.kind === "failure")),
699
- ...(startMs === undefined
994
+ startMs === undefined
700
995
  ? {}
701
996
  : {
702
- frictionAdded: added(friction),
703
- deferralsAdded: added(deferrals),
704
- failuresAdded: added(failures),
705
- }),
706
- };
707
- }
708
-
709
- /** `git diff --shortstat` numbers; 0 for anything absent or a range git rejects. */
710
- export function diffStat(cwd: string, range: string) {
711
- const out = runGit(cwd, ["diff", "--shortstat", range]).stdout;
712
- const num = (re: RegExp) => Number(re.exec(out)?.[1] ?? 0);
713
- const linesAdded = num(/(\d+) insertions?\(/);
714
- const linesDeleted = num(/(\d+) deletions?\(/);
997
+ added: distinctKeys(
998
+ rows.filter((r) => byWorkflow(r) === workflow && Number(r.ts) >= startMs),
999
+ ),
1000
+ };
715
1001
  return {
716
- linesAdded,
717
- linesDeleted,
718
- linesChanged: linesAdded + linesDeleted,
719
- filesChanged: num(/(\d+) files? changed/),
1002
+ deferrals: {
1003
+ repo: distinctKeys(deferrals.filter((r) => r.kind === "deferral")),
1004
+ ...added(deferrals),
1005
+ },
1006
+ failures: {
1007
+ repo: distinctKeys(failures.filter((r) => r.kind === "failure")),
1008
+ ...added(failures),
1009
+ },
1010
+ friction: added(friction),
720
1011
  };
721
1012
  }
722
1013
 
723
- /** Checklist items (`- [`) across the feature's plan and sub-plans. */
724
- function taskCount(tree: string, month: string, fid: string): number {
725
- const dir = path.join(tree, "docs", "plans", month);
726
- if (!fs.existsSync(dir)) return 0;
727
- return fs
728
- .readdirSync(dir)
729
- .filter((f) => f.startsWith(`${fid}-plan`) && f.endsWith(".md"))
730
- .flatMap((f) => fs.readFileSync(path.join(dir, f), "utf-8").split("\n"))
731
- .filter((l) => l.startsWith("- [")).length;
732
- }
733
-
734
1014
  /** Per-tier coverage from `coverage/{tier}/coverage-summary.json`; undefined when none. */
735
1015
  function coverage(tree: string): Record<string, CoverageStats> | undefined {
736
1016
  const out: Record<string, CoverageStats> = {};
@@ -758,24 +1038,112 @@ function lastOfType(events: StatusEvent[], type: string, workflow: string) {
758
1038
  .at(-1) as (StatusEvent & Record<string, unknown>) | undefined;
759
1039
  }
760
1040
 
761
- /** Append telemetry rows; best-effort, so a bad path is logged and never fails the close. */
762
- function appendStats(file: string, rows: Array<Record<string, unknown>>, log: (m: string) => void) {
763
- const valid = rows.filter((r) => {
764
- const v = validate(r);
765
- if (!v.ok) log(`[bkit-telemetry] ${String(r.kind)} row invalid, not written: ${v.reason}`);
766
- return v.ok;
767
- });
768
- if (valid.length === 0) return false;
1041
+ /** Append the close's stats rows; best-effort, so a refused row or a bad path is logged and never fails the close. */
1042
+ function appendStats(tree: string, rows: Array<Record<string, unknown>>, log: (m: string) => void) {
769
1043
  try {
770
- fs.appendFileSync(file, valid.map((r) => `${telemetryLine(r as never)}\n`).join(""));
1044
+ appendLedgerRows(tree, "stats", rows);
771
1045
  return true;
772
1046
  } catch (err) {
773
- // Telemetry never gates a close: report the failed append and carry on.
774
- log(`[bkit-telemetry] append failed: ${file} — ${(err as Error).message}`);
1047
+ // Telemetry never gates a close: report the refused append and carry on.
1048
+ log(`[bkit-telemetry] stats rows not written: ${(err as Error).message}`);
775
1049
  return false;
776
1050
  }
777
1051
  }
778
1052
 
1053
+ /**
1054
+ * The rows of `workflow`'s `nth` run in `file` (the last when omitted), in time order;
1055
+ * unreadable lines skipped. Runs split as `fold` splits them: rows ordered by `at`, file
1056
+ * order on a tie, each new `workflow-started` opening a run, so a previous run's rows in
1057
+ * the same second as this run's start stay with the previous run.
1058
+ */
1059
+ function runRowsOf(file: string, workflow: string, nth = -1): HoleRow[] {
1060
+ const at = (r: HoleRow) => (typeof r["at"] === "string" ? r["at"] : "");
1061
+ const ordered = parseRows(fs.readFileSync(file, "utf-8"))
1062
+ .map((r, i) => ({ r, i }))
1063
+ .filter(({ r }) => r.workflow === workflow)
1064
+ .sort((a, b) => (at(a.r) < at(b.r) ? -1 : at(a.r) > at(b.r) ? 1 : a.i - b.i))
1065
+ .map(({ r }) => r);
1066
+ const runs: HoleRow[][] = [];
1067
+ const starts = new Set<string>();
1068
+ for (const r of ordered) {
1069
+ if (r.type === "workflow-started" && !starts.has(at(r))) {
1070
+ starts.add(at(r));
1071
+ runs.push([]);
1072
+ } else if (runs.length === 0 && r.type === "step-done") {
1073
+ runs.push([]);
1074
+ }
1075
+ runs.at(-1)?.push(r);
1076
+ }
1077
+ return runs.at(nth) ?? [];
1078
+ }
1079
+
1080
+ /** The contract of `workflow`, derived from its shipped markdown rendered for the tracker `cwd` is configured with. */
1081
+ const contractOf = (workflow: string, cwd: string) =>
1082
+ deriveContract(
1083
+ fs.readFileSync(path.join(getWorkflowsRoot(), `bkit-${workflow}.md`), "utf-8"),
1084
+ workflow,
1085
+ readIssueTracker(cwd),
1086
+ );
1087
+
1088
+ /**
1089
+ * Appends the close's `completeness` row for `workflow`'s last run. Advisory:
1090
+ * a failure of the check or of the write is logged in one line and never fails the close.
1091
+ * `journalSuspect` is set here only: the closing engine journals itself.
1092
+ */
1093
+ function writeCompletenessRow(
1094
+ file: string,
1095
+ workflow: string,
1096
+ parentSha: string,
1097
+ log: (m: string) => void,
1098
+ ): void {
1099
+ try {
1100
+ const verdict = checkCompleteness(
1101
+ runRowsOf(file, workflow),
1102
+ contractOf(workflow, path.dirname(file)),
1103
+ {
1104
+ journalSuspect: true,
1105
+ },
1106
+ );
1107
+ const row: StatusRow = { type: "completeness", ...verdict, at: statusTimestamp(), parentSha };
1108
+ fs.appendFileSync(file, appendLine(row));
1109
+ if (verdict.journalSuspect) {
1110
+ log(
1111
+ "[bkit-telemetry] journal looks dead at close: no engine-call rows for this run; the completeness verdict cannot be trusted",
1112
+ );
1113
+ }
1114
+ } catch (err) {
1115
+ // The check is advisory: report the failure and close without the row.
1116
+ log(`[bkit-telemetry] completeness row not written: ${(err as Error).message}`);
1117
+ }
1118
+ }
1119
+
1120
+ /**
1121
+ * The warning line for the run before the one being started (or resumed) when that run
1122
+ * was holey; `null` when it is clean, absent or unreadable. Never throws.
1123
+ */
1124
+ function previousRunWarning(file: string, resumed: boolean): string | null {
1125
+ try {
1126
+ const events = readStatusEvents(file);
1127
+ const runs = fold(events);
1128
+ const at = runs.length - (resumed ? 2 : 1);
1129
+ const prev = runs[at];
1130
+ if (prev === undefined) return null;
1131
+ const number = runs.slice(0, at + 1).filter((r) => r.workflow === prev.workflow).length;
1132
+ const own = runRowsOf(file, prev.workflow, number - 1);
1133
+ const { verdict } = readCompleteness(own, contractOf(prev.workflow, path.dirname(file)));
1134
+ if (!verdict.holey) return null;
1135
+ const closed = own.filter((e) => e.type === "workflow-done").at(-1)?.["at"] ?? "never";
1136
+ return (
1137
+ `[bkit-workflows] previous run (${prev.workflow} run ${number}, closed ${closed}) was incomplete: ` +
1138
+ `${verdict.evidenceHoles.length} evidence hole(s), ${verdict.stepHoles.length} step hole(s); ` +
1139
+ `see: bkit completeness check --workflow=${prev.workflow} --file=${path.relative(process.cwd(), file) || file}`
1140
+ );
1141
+ } catch {
1142
+ // Advisory: an unreadable run or checker failure degrades to no warning.
1143
+ return null;
1144
+ }
1145
+ }
1146
+
779
1147
  /** Markdown link per feature doc and per log of this workflow, as on `ref`. */
780
1148
  export function artifactLinks(
781
1149
  root: string,
@@ -828,6 +1196,20 @@ function closeComment(
828
1196
  });
829
1197
  }
830
1198
 
1199
+ /** `--ending` / `--publish` of the close verb, validated. */
1200
+ function closeEnding(f: Record<string, FlagValue>): Pick<CloseInput, "ending" | "publish"> {
1201
+ const ending = str(f.ending);
1202
+ if (ending !== undefined && ending !== "done" && ending !== "held")
1203
+ throw new CommandError(EXIT.USAGE, `--ending must be done or held, got ${ending}`);
1204
+ const publish = str(f.publish);
1205
+ if (publish !== undefined && publish !== "true" && publish !== "false")
1206
+ throw new CommandError(EXIT.USAGE, `--publish must be true or false, got ${publish}`);
1207
+ return {
1208
+ ...(ending === undefined ? {} : { ending }),
1209
+ ...(publish === undefined ? {} : { publish: publish === "true" }),
1210
+ };
1211
+ }
1212
+
831
1213
  export interface CloseInput {
832
1214
  workflow: string;
833
1215
  fid: string;
@@ -845,13 +1227,18 @@ export interface CloseInput {
845
1227
  number?: string;
846
1228
  title?: string;
847
1229
  tree?: string;
1230
+ /** `held` = a local build that published nothing; default `done`. */
1231
+ ending?: "done" | "held";
1232
+ /** The resolved publish value of a build; absent when unset. */
1233
+ publish?: boolean;
848
1234
  }
849
1235
 
850
1236
  /**
851
1237
  * Grade compliance, append the workflow-done row (and, with `recordStep`, the
852
1238
  * close step's row first), the counter and outcome telemetry rows, and build the
853
1239
  * report and artifact links; with `outbox`, write them for the close comment; with
854
- * `message`, commit everything (`git add -A`) in the tree.
1240
+ * `message`, commit everything (`git add -A`, minus the `bkit.workflows.worktree.copy` entries) in the tree, or, in an in-place run
1241
+ * on a shared branch, only the run's own paths.
855
1242
  */
856
1243
  export function closeWorkflow(
857
1244
  cwd: string,
@@ -864,81 +1251,110 @@ export function closeWorkflow(
864
1251
  if (o.squashSha !== undefined && !/^[0-9a-f]{7,40}$/.test(o.squashSha))
865
1252
  throw new CommandError(EXIT.USAGE, `--squash-sha "${o.squashSha}" is not a commit sha`);
866
1253
 
867
- // Graded first, so the report below carries this run's grade.
868
- const violations = gradeCompliance(where.tree, workflow, log, o.squashSha);
1254
+ // An in-place run on a shared branch commits its own paths only; a refusal
1255
+ // comes before any row is appended, so the re-run after the human's fix writes each row once.
1256
+ const rec = o.message === undefined ? null : activeRecord(where.tree, o.fid);
1257
+ if (o.message !== undefined) requireRecordOnShared(where.tree, workflow, rec);
1258
+ if (rec !== null) ownSet(where.tree, rec);
869
1259
 
870
1260
  const step = `${workflow}-close-workflow`;
1261
+ // The run's join key: every row of this run carries HEAD at close as `run.parentSha`.
1262
+ const parentSha = headSha(where.tree);
1263
+ // Graded first, so the report below carries this run's grade.
1264
+ const violations = gradeCompliance(where.tree, workflow, log, o.squashSha, { parentSha, step });
1265
+
1266
+ let progressLine: string | undefined;
871
1267
  if (o.recordStep === true) {
872
- writeStepRow(
1268
+ const written = writeStepRow(
873
1269
  where.tree,
874
1270
  { file: where.status, workflow, step, artifacts: [], commit: "none" },
875
1271
  log,
876
1272
  );
1273
+ progressLine = written.progressLine;
877
1274
  }
878
- const row = { type: "workflow-done" as const, workflow, at: statusTimestamp() };
1275
+ writeCompletenessRow(where.status, workflow, parentSha, log);
1276
+ const endAt = statusTimestamp();
1277
+ const ending = o.ending ?? "done";
1278
+ const row = {
1279
+ type: "workflow-done" as const,
1280
+ workflow,
1281
+ at: endAt,
1282
+ parentSha,
1283
+ ending,
1284
+ ...(o.publish === undefined ? {} : { publish: o.publish }),
1285
+ };
879
1286
  fs.appendFileSync(where.status, appendLine(row));
880
1287
 
881
1288
  const repo = resolveRepoSlug(where.root) || "unknown/repo";
882
- const bkitVersion =
883
- readBkitVersion(path.join(where.root, ".bkit", "version"))?.pinnedVersion || "unknown";
884
- const parentSha = headSha(where.tree);
885
1289
  const started = lastOfType(events, "workflow-started", workflow);
886
1290
  const startAt = started?.at;
887
1291
  const startMs = startAt ? Date.parse(startAt) : NaN;
888
1292
  const startKnown = Number.isFinite(startMs) ? startMs : undefined;
889
- const planSource = events
890
- .filter(
891
- (e) =>
892
- e.type === "workflow-meta" &&
893
- e.workflow === workflow &&
894
- (startAt === undefined || e.at >= startAt) &&
895
- (e as Record<string, unknown>).planSource,
896
- )
897
- .at(-1) as Record<string, unknown> | undefined;
1293
+ const runRowsOf =
1294
+ startAt === undefined ? [] : runStatusRows(readStatusEvents(where.status), workflow, startAt);
898
1295
  const base = typeof started?.parentSha === "string" ? started.parentSha : "";
899
- const range = o.squashSha
900
- ? `${o.squashSha}^..${o.squashSha}`
901
- : base
902
- ? `${base}..HEAD`
903
- : "origin/dev...HEAD";
904
- const durationSeconds =
905
- startKnown === undefined ? 0 : Math.max(0, Math.floor((Date.now() - startKnown) / 1000));
1296
+ const lines = o.squashSha
1297
+ ? runLines(where.tree, `${o.squashSha}^`, o.squashSha)
1298
+ : runLines(where.tree, base, parentSha);
906
1299
  const startedRows = new Set(
907
1300
  events.filter((e) => e.type === "workflow-started" && e.workflow === workflow).map((e) => e.at),
908
1301
  ).size;
909
- const ts = Date.now();
1302
+ const by = { workflow, step };
910
1303
 
911
1304
  const counterRow = {
912
- ts,
913
1305
  kind: "counter",
914
- workflow,
915
- repo,
916
- bkitVersion,
917
- step,
918
- counterName: `${workflow.toUpperCase()}_ATTEMPT`,
919
- counterValue: Math.max(1, startedRows),
920
- counterSource: "shell-bus",
921
- parentSha,
1306
+ by,
1307
+ run: { parentSha },
1308
+ counter: {
1309
+ name: `${workflow.toUpperCase()}_ATTEMPT`,
1310
+ value: Math.max(1, startedRows),
1311
+ source: "shell-bus",
1312
+ },
922
1313
  };
923
1314
  const cov = workflow === "ship" ? coverage(where.tree) : undefined;
1315
+ const ci = ciList(runRowsOf);
1316
+ const plan = ["plan", "build", "ship"].includes(workflow)
1317
+ ? planBlock(where.tree, where.month, o.fid, events)
1318
+ : undefined;
1319
+ const endMs = Date.parse(endAt);
1320
+ /** This run's `docs/deferrals.jsonl` rows; none when its start is unknown. */
1321
+ const runDeferrals = () =>
1322
+ startKnown === undefined
1323
+ ? []
1324
+ : ledgerRows(path.join(where.tree, "docs", "deferrals.jsonl"))
1325
+ .map((r) => normalize(r))
1326
+ .filter((r) => byWorkflow(r) === workflow && Number(r.ts) >= startKnown);
1327
+ const context =
1328
+ startKnown === undefined
1329
+ ? undefined
1330
+ : agentContextBlock(
1331
+ startKnown,
1332
+ endMs,
1333
+ claudeTranscripts(process.env, os.homedir()),
1334
+ runChats(runRowsOf),
1335
+ );
924
1336
  const outcomeRow = {
925
- ts: ts + 1,
926
1337
  kind: "outcome",
927
- workflow,
928
- repo,
929
- bkitVersion,
930
- step,
931
- parentSha,
932
- ...(o.prNumber === undefined ? {} : { prNumber: o.prNumber }),
933
- ...diffStat(where.tree, range),
934
- taskCount: taskCount(where.tree, where.month, o.fid),
935
- durationSeconds,
936
- ...ledgerCounts(where.tree, workflow, startKnown),
937
- ...(planSource?.planSource ? { planSource: planSource.planSource } : {}),
938
- ...(cov ? { coverage: cov } : {}),
1338
+ by,
1339
+ run: { parentSha, ...(o.prNumber === undefined ? {} : { pr: o.prNumber }) },
1340
+ time: startKnown === undefined ? null : timeBlock(startKnown, Math.max(startKnown, endMs)),
1341
+ ending,
1342
+ ...(o.publish === undefined ? {} : { publish: o.publish }),
1343
+ lines,
1344
+ ...(runRowsOf.length > 0 ? { steps: stepsBlock(runRowsOf) } : {}),
1345
+ ...(ci.length > 0 ? { ci } : {}),
1346
+ ledgers: ledgerCounts(where.tree, workflow, startKnown),
1347
+ ...(plan === undefined ? {} : { plan }),
1348
+ ...(workflow === "build"
1349
+ ? {
1350
+ build: buildBlock(runRowsOf, planFiles(where.tree, where.month, o.fid), runDeferrals()),
1351
+ }
1352
+ : {}),
1353
+ ...(context === undefined ? {} : { context }),
1354
+ ...(cov ? { ship: { coverage: cov } } : {}),
939
1355
  };
940
1356
  const stats = path.join(where.tree, ".bkit", "stats.jsonl");
941
- const telemetryWritten = appendStats(stats, [counterRow, outcomeRow], log);
1357
+ const telemetryWritten = appendStats(where.tree, [counterRow, outcomeRow], log);
942
1358
 
943
1359
  const report = fs.existsSync(stats)
944
1360
  ? workflowTelemetry(foldFrom([stats]), workflow).lines
@@ -988,17 +1404,23 @@ export function closeWorkflow(
988
1404
  )
989
1405
  message += " bkit [verbose ci]";
990
1406
  if ((o.labels ?? []).includes(AUTO_LABEL)) message += AUTO_ROUTE_SUFFIX;
991
- const add = runGit(where.tree, ["add", "-A"]);
992
- const made = add.ok ? runGit(where.tree, ["commit", "--allow-empty", "-m", message]) : add;
993
- if (!made.ok)
994
- throw new CommandError(EXIT.NO, `close commit failed: ${made.stderr || made.stdout}`);
1407
+ if (rec !== null) {
1408
+ const made = ownPathCommit(where.tree, rec, message, { allowEmpty: true });
1409
+ if (!made.ok) throw new CommandError(EXIT.NO, `close commit failed: ${made.error}`);
1410
+ } else {
1411
+ const add = addAllButCopied(where.tree);
1412
+ const made = add.ok ? runGit(where.tree, ["commit", "--allow-empty", "-m", message]) : add;
1413
+ if (!made.ok)
1414
+ throw new CommandError(EXIT.NO, `close commit failed: ${made.stderr || made.stdout}`);
1415
+ }
995
1416
  commit = headSha(where.tree);
996
1417
  }
997
1418
 
998
1419
  return {
999
1420
  row,
1000
- counterRow: validate(counterRow).ok ? counterRow : null,
1001
- outcomeRow: validate(outcomeRow).ok ? outcomeRow : null,
1421
+ // The rows as drafted; the ledger copies add the top section `ledgers append` fills.
1422
+ counterRow: telemetryWritten ? counterRow : null,
1423
+ outcomeRow: telemetryWritten ? outcomeRow : null,
1002
1424
  telemetryWritten,
1003
1425
  compliance: violations === null ? null : violations.length,
1004
1426
  report,
@@ -1009,6 +1431,7 @@ export function closeWorkflow(
1009
1431
  comment,
1010
1432
  roadmapFoldNeeded: true,
1011
1433
  featureStatus: FEATURE_STATUS[workflow],
1434
+ ...(progressLine === undefined ? {} : { progressLine }),
1012
1435
  };
1013
1436
  }
1014
1437
 
@@ -1056,8 +1479,8 @@ function closePr(
1056
1479
  * checkout): the close rows there, then ONE `docs({fid}): ship DONE bkit [skip ci]`
1057
1480
  * commit built in a throwaway origin/dev checkout carrying the run's book and
1058
1481
  * landed on dev — a refused push publishes it through a `ship-close/{fid}` PR.
1059
- * Only a close that landed (or opened its PR) releases the workflow lock; once
1060
- * the close is on dev, the feature worktree and `branch` are removed. A close
1482
+ * Once the close is on dev, the feature worktree and `branch` are removed; then
1483
+ * a close that landed (or opened its PR) releases the workflow lock. A close
1061
1484
  * that did not land keeps the lock for the Failure Path.
1062
1485
  */
1063
1486
  async function shipClose(
@@ -1133,22 +1556,13 @@ async function shipClose(
1133
1556
  return { code: EXIT_FLUSH_FAILED, out: null };
1134
1557
  }
1135
1558
 
1136
- const released = releaseLock(workflowLockPath(root, month, o.fid), {
1137
- workflow: "ship",
1138
- fid: o.fid,
1139
- token,
1140
- });
1141
- if (released.removeFailed) {
1142
- ctx.log("Lock removal failed");
1143
- return { code: EXIT_FLUSH_FAILED, out: null };
1144
- }
1145
-
1146
- // The book is on dev only once the close landed or its PR merged.
1559
+ // The book is on dev only once the close landed or its PR merged. The worktree
1560
+ // goes while the lock is still held, so no run of this FID resumes into it.
1147
1561
  let worktree: RemoveResult | null = null;
1148
1562
  if (landed.via === "close-pr-open") {
1149
1563
  ctx.log(`close PR not merged — ${kept} until it is`);
1150
1564
  } else {
1151
- if (landed.via === "close-pr" && !runGit(root, ["fetch", "origin", DEV]).ok)
1565
+ if (landed.via === "close-pr" && !fetchDev(root).ok)
1152
1566
  ctx.log(
1153
1567
  `fetch of dev after the close PR failed — origin/${DEV} is stale until the next fetch`,
1154
1568
  );
@@ -1158,6 +1572,16 @@ async function shipClose(
1158
1572
  ctx.log(`${(err as Error).message} — remove ${book} by hand`);
1159
1573
  }
1160
1574
  }
1575
+
1576
+ const released = releaseLock(workflowLockPath(root, month, o.fid), {
1577
+ workflow: "ship",
1578
+ fid: o.fid,
1579
+ token,
1580
+ });
1581
+ if (released.removeFailed) {
1582
+ ctx.log("Lock removal failed");
1583
+ return { code: EXIT_FLUSH_FAILED, out: null };
1584
+ }
1161
1585
  return { code: EXIT.OK, out: { ...out, landed, worktree } };
1162
1586
  }
1163
1587
 
@@ -1165,20 +1589,6 @@ async function shipClose(
1165
1589
  // promote
1166
1590
  // ---------------------------------------------------------------------------
1167
1591
 
1168
- /** The highest `{workflow}-v{N}-*.md` draft (sub-plan children `-v{N}-{k}.md` excluded), or null. */
1169
- export function highestVersion(dir: string, workflow: string): { file: string; n: number } | null {
1170
- if (!fs.existsSync(dir)) return null;
1171
- const re = new RegExp(`^${workflow}-v([0-9]+)-(.+)\\.md$`);
1172
- let best: { file: string; n: number } | null = null;
1173
- for (const f of fs.readdirSync(dir).sort()) {
1174
- const m = re.exec(f);
1175
- if (!m || /^[0-9]+$/.test(m[2]!)) continue;
1176
- const n = Number(m[1]);
1177
- if (best === null || n > best.n) best = { file: f, n };
1178
- }
1179
- return best;
1180
- }
1181
-
1182
1592
  /** Stamp `file`'s anchor when a base commit is known (plan: with its design's own anchor; both: the bkit release). */
1183
1593
  function stamp(cwd: string, file: string, baseSha: string, design?: string): void {
1184
1594
  if (baseSha === "") return;
@@ -1208,7 +1618,7 @@ function promoteVerb(ctx: RunContext): number {
1208
1618
  }
1209
1619
  const final = path.join(logs, best.file);
1210
1620
  if (ctx.flags.resolve === true) {
1211
- ctx.emit({ final, canonical: null, archived: [], subPlans: [], baseSha: null });
1621
+ ctx.emit({ final, canonical: null, archived: [], baseSha: null });
1212
1622
  return EXIT.OK;
1213
1623
  }
1214
1624
 
@@ -1229,15 +1639,8 @@ function promoteVerb(ctx: RunContext): number {
1229
1639
  const bucket = path.join("docs", "plans", month);
1230
1640
  const canonical = path.join(bucket, `${fid}-${workflow}.md`);
1231
1641
  stamp(ctx.cwd, final, baseSha, design);
1232
- const children =
1233
- workflow === "plan"
1234
- ? fs
1235
- .readdirSync(path.resolve(ctx.cwd, logs))
1236
- .filter((f) => new RegExp(`^plan-v${best.n}-[0-9]+\\.md$`).test(f))
1237
- .sort()
1238
- : [];
1239
-
1240
- // A changed canonical moves to archive/ first — plan moves the whole set under one timestamp.
1642
+
1643
+ // A changed canonical moves to archive/ first.
1241
1644
  const archived: string[] = [];
1242
1645
  const canonicalAbs = path.resolve(ctx.cwd, canonical);
1243
1646
  if (
@@ -1250,47 +1653,131 @@ function promoteVerb(ctx: RunContext): number {
1250
1653
  .replace(/\.\d+Z$/, "Z");
1251
1654
  const archive = path.join(bucket, "archive");
1252
1655
  fs.mkdirSync(path.resolve(ctx.cwd, archive), { recursive: true });
1253
- const set = fs
1254
- .readdirSync(path.resolve(ctx.cwd, bucket))
1255
- .filter((f) =>
1256
- workflow === "plan"
1257
- ? f === `${fid}-plan.md` || new RegExp(`^${fid}-plan-[0-9]+\\.md$`).test(f)
1258
- : f === `${fid}-design.md`,
1259
- );
1260
- for (const f of set) {
1261
- const to = path.join(archive, `${ts}-${f}`);
1262
- fs.renameSync(path.resolve(ctx.cwd, bucket, f), path.resolve(ctx.cwd, to));
1263
- archived.push(to);
1264
- }
1656
+ const to = path.join(archive, `${ts}-${fid}-${workflow}.md`);
1657
+ fs.renameSync(canonicalAbs, path.resolve(ctx.cwd, to));
1658
+ archived.push(to);
1265
1659
  }
1266
1660
  fs.mkdirSync(path.resolve(ctx.cwd, bucket), { recursive: true });
1267
1661
  fs.copyFileSync(path.resolve(ctx.cwd, final), canonicalAbs);
1268
- const subPlans: string[] = [];
1269
- for (const child of children) {
1270
- const k = /-([0-9]+)\.md$/.exec(child)![1]!;
1271
- stamp(ctx.cwd, path.join(logs, child), baseSha, design);
1272
- const to = path.join(bucket, `${fid}-plan-${k}.md`);
1273
- fs.copyFileSync(path.resolve(ctx.cwd, logs, child), path.resolve(ctx.cwd, to));
1274
- subPlans.push(to);
1275
- }
1276
- if (workflow === "plan") {
1277
- // Working names in the copies become the canonical names.
1278
- for (const f of [canonical, ...subPlans]) {
1279
- const abs = path.resolve(ctx.cwd, f);
1280
- fs.writeFileSync(
1281
- abs,
1282
- fs
1283
- .readFileSync(abs, "utf-8")
1284
- .replace(/plan-v[0-9]+-split\.md/g, `${fid}-plan.md`)
1285
- .replace(/plan-v[0-9]+-([0-9]+)\.md/g, `${fid}-plan-$1.md`),
1286
- );
1287
- }
1288
- }
1289
1662
  if (fs.statSync(canonicalAbs).size === 0) {
1290
1663
  ctx.log(`canonical empty: ${canonical}`);
1291
1664
  return EXIT_NO_VERSION;
1292
1665
  }
1293
- ctx.emit({ final, canonical, archived, subPlans, baseSha: baseSha || null });
1666
+ ctx.emit({ final, canonical, archived, baseSha: baseSha || null });
1667
+ return EXIT.OK;
1668
+ }
1669
+
1670
+ // ---------------------------------------------------------------------------
1671
+ // summary
1672
+ // ---------------------------------------------------------------------------
1673
+
1674
+ /** ship: the PR's size from `gh pr view`; undefined (logged) when gh cannot answer. */
1675
+ function prSize(cwd: string, pr: number, log: (m: string) => void) {
1676
+ const res = runGh(cwd, ["pr", "view", String(pr), "--json", "additions,deletions,changedFiles"]);
1677
+ const parsed = res.ok ? parseJson(res.stdout) : undefined;
1678
+ const v = parsed?.ok === true ? (parsed.value as Record<string, unknown>) : undefined;
1679
+ if (
1680
+ typeof v?.additions !== "number" ||
1681
+ typeof v.deletions !== "number" ||
1682
+ typeof v.changedFiles !== "number"
1683
+ ) {
1684
+ log(`gh pr view ${pr} gave no size; the summary leaves the PR line out`);
1685
+ return undefined;
1686
+ }
1687
+ return {
1688
+ number: pr,
1689
+ additions: v.additions,
1690
+ deletions: v.deletions,
1691
+ changedFiles: v.changedFiles,
1692
+ };
1693
+ }
1694
+
1695
+ function summaryVerb(ctx: RunContext): number {
1696
+ const workflow = String(ctx.flags.workflow);
1697
+ if (!(SUMMARY_WORKFLOWS as readonly string[]).includes(workflow))
1698
+ throw new CommandError(EXIT.USAGE, `--workflow must be ${SUMMARY_WORKFLOWS.join(", ")}`);
1699
+ const file = path.resolve(ctx.cwd, String(ctx.flags.file));
1700
+ const logDir = path.dirname(file);
1701
+ const fid = path.basename(logDir);
1702
+ const month = path.basename(path.dirname(path.dirname(logDir)));
1703
+ const tree = path.resolve(logDir, "..", "..", "..", "..", "..");
1704
+ if (!/^[0-9]{6}$/.test(month) || path.join(tree, logDirRel(month, fid)) !== logDir)
1705
+ throw new CommandError(
1706
+ EXIT.USAGE,
1707
+ `--file must be docs/plans/{YYYYMM}/logs/{FID}/status.jsonl, got ${file}`,
1708
+ );
1709
+
1710
+ const events = readStatusEvents(file);
1711
+ const started = lastOfType(events, "workflow-started", workflow);
1712
+ if (started === undefined)
1713
+ throw new CommandError(EXIT_NO_RUN, `${file} has no ${workflow} run (no workflow-started row)`);
1714
+ const rows = runStatusRows(events, workflow, started.at);
1715
+ const startMs = Date.parse(started.at);
1716
+ const rel = (abs: string) => path.relative(tree, abs).split(path.sep).join("/");
1717
+ const given = list(ctx.flags.plan).map((p) => path.resolve(ctx.cwd, p));
1718
+ const plans = given.length > 0 ? given : workflow === "build" ? planFiles(tree, month, fid) : [];
1719
+ const read = (r: string) => {
1720
+ const abs = path.resolve(tree, r);
1721
+ return fs.existsSync(abs) && fs.statSync(abs).isFile() ? fs.readFileSync(abs, "utf-8") : null;
1722
+ };
1723
+ const deferralHistory = ledgerRows(path.join(tree, "docs", "deferrals.jsonl")).map((r) =>
1724
+ normalize(r),
1725
+ );
1726
+ const runDeferralKeys = new Set(
1727
+ deferralHistory
1728
+ .filter((r) => isRunsOwnRow(r, { fid, workflow, startMs }, new Set()))
1729
+ .map((r) => r.key),
1730
+ );
1731
+ const currentDeferrals = new Map(
1732
+ deferralHistory.sort((a, b) => compareTs({ ts: a.ts }, { ts: b.ts })).map((r) => [r.key, r]),
1733
+ );
1734
+ const deferrals = [...currentDeferrals.values()].filter((r) => runDeferralKeys.has(r.key));
1735
+ const organisedPath = path.join(logDir, "design-v3-organised.md");
1736
+ const organised =
1737
+ workflow === "design" && fs.existsSync(organisedPath)
1738
+ ? fs.readFileSync(organisedPath, "utf-8")
1739
+ : undefined;
1740
+ const prNumber = positiveInt(ctx.flags.pr, "pr");
1741
+ const publishFlag = str(ctx.flags.publish);
1742
+ if (publishFlag !== undefined && publishFlag !== "true" && publishFlag !== "false")
1743
+ throw new CommandError(EXIT.USAGE, `--publish must be true or false, got ${publishFlag}`);
1744
+
1745
+ const summary = buildSummary({
1746
+ root: tree,
1747
+ publish: publishFlag === undefined ? undefined : publishFlag === "true",
1748
+ workflow: workflow as SummaryWorkflow,
1749
+ fid,
1750
+ ref: refOf(fid, readIssueTracker(tree)),
1751
+ rows,
1752
+ plans: plans.map((p) => ({ path: rel(p), text: fs.readFileSync(p, "utf-8") })),
1753
+ deferrals,
1754
+ deferralsAdded: deferrals.filter((r) => r.status !== "CLOSED").length,
1755
+ decisionFiles:
1756
+ (workflow === "build" || workflow === "ship") && fs.existsSync(logDir)
1757
+ ? fs
1758
+ .readdirSync(logDir)
1759
+ .filter((f) => /^build-decision-.*\.md$/.test(f))
1760
+ .sort()
1761
+ .map((f) => rel(path.join(logDir, f)))
1762
+ : [],
1763
+ read,
1764
+ workstreams: organised === undefined ? undefined : parseWorkstreams(organised),
1765
+ suggestedPlans: organised === undefined ? undefined : parsePlans(organised),
1766
+ organised,
1767
+ pr:
1768
+ workflow === "ship" && prNumber !== undefined
1769
+ ? prSize(ctx.cwd, prNumber, ctx.log)
1770
+ : undefined,
1771
+ });
1772
+ const out = path.join(logDir, `${workflow}-summary.md`);
1773
+ fs.writeFileSync(out, summary.markdown);
1774
+ ctx.emit({
1775
+ verdict: summary.verdict,
1776
+ failures: summary.failures,
1777
+ reasons: summary.reasons,
1778
+ file: rel(out),
1779
+ nextStep: summary.nextStep,
1780
+ });
1294
1781
  return EXIT.OK;
1295
1782
  }
1296
1783
 
@@ -1322,14 +1809,251 @@ const OWNER_REPO_FLAG: FlagSpec = {
1322
1809
  const COMMENT_FLAGS: FlagSpec[] = [
1323
1810
  { name: "number", type: "string", help: "step number: print the close comment (needs --outbox)" },
1324
1811
  { name: "title", type: "string", help: "step title of the close comment" },
1812
+ {
1813
+ ...POST_FLAG,
1814
+ help: "post the close comment (needs --number) to the FID's issue unless one of its latest comments carries the same marker hash; prints `tracker`",
1815
+ },
1325
1816
  ];
1326
1817
 
1818
+ const SESSION_DIR_FLAG: FlagSpec = {
1819
+ name: "session-dir",
1820
+ type: "string",
1821
+ help: "the run's session folder (`repo info` sessionDir): deleted once this run ends",
1822
+ };
1823
+ const SESSION_REMOVED_OUTPUT =
1824
+ "with --session-dir: the folder was deleted (false: not under <git common dir>/bkit-outbox/sessions/, kept)";
1825
+
1826
+ /**
1827
+ * `--session-dir`: delete the run's session folder. Only a folder directly under
1828
+ * `<git common dir>/bkit-outbox/sessions/` is deleted; any other path is kept and logged.
1829
+ */
1830
+ function sessionRemoval(ctx: RunContext): { sessionRemoved?: boolean } {
1831
+ const given = str(ctx.flags.sessionDir);
1832
+ if (!given) return {};
1833
+ const common = git(ctx.cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
1834
+ const real = (p: string) => (fs.existsSync(p) ? fs.realpathSync(p) : p);
1835
+ const sessions = common === null ? null : real(path.join(common, "bkit-outbox", "sessions"));
1836
+ const abs = path.resolve(ctx.cwd, given);
1837
+ if (sessions === null || real(path.dirname(abs)) !== sessions) {
1838
+ ctx.log(
1839
+ `--session-dir ${given} is not a session folder under ${sessions ?? "the outbox"}; kept`,
1840
+ );
1841
+ return { sessionRemoved: false };
1842
+ }
1843
+ fs.rmSync(abs, { recursive: true, force: true });
1844
+ return { sessionRemoved: true };
1845
+ }
1846
+
1847
+ const PLAIN_ENGLISH_REPLY =
1848
+ "Would you like me to explain any of this in plain English? Then write 'yes, explain in plain english'.";
1849
+
1850
+ /**
1851
+ * `--final-return`: the run's last message, read up front (the close may remove the tree
1852
+ * holding the summary, and `--session-dir` the issue facts). Tips are added at print time.
1853
+ */
1854
+ function finalReturnParts(ctx: RunContext, fid: string): string[] | null {
1855
+ if (ctx.flags.finalReturn !== true) return null;
1856
+ const summaryFile = str(ctx.flags.summaryFile);
1857
+ const summary = str(ctx.flags.summary);
1858
+ if (summaryFile !== undefined && summary !== undefined)
1859
+ throw new CommandError(EXIT.USAGE, "give --summary-file or --summary, not both");
1860
+ if (!summaryFile && !summary)
1861
+ throw new CommandError(EXIT.USAGE, "--final-return needs --summary-file or --summary");
1862
+ const parts: string[] = [];
1863
+ const warning = str(ctx.flags.warning);
1864
+ if (warning) parts.push(warning);
1865
+ parts.push(
1866
+ summary ? summaryOrMissing(ctx, summary) : inputText(ctx.cwd, summaryFile!, "summary-file"),
1867
+ );
1868
+ parts.push(...list(ctx.flags.line));
1869
+ const session = str(ctx.flags.sessionDir);
1870
+ const factsFile = session ? path.resolve(ctx.cwd, session, "issue-facts.json") : "";
1871
+ if (factsFile && fs.existsSync(factsFile)) {
1872
+ const parsed = parseJson(fs.readFileSync(factsFile, "utf-8"));
1873
+ const facts = (parsed.ok ? parsed.value : {}) as { title?: unknown; url?: unknown };
1874
+ const t = trackerTarget(ctx.cwd, { fid });
1875
+ const title = typeof facts.title === "string" ? facts.title : "";
1876
+ const label = [issueRef(t.issue, t.tracker), title].filter(Boolean).join(" ");
1877
+ if (typeof facts.url === "string" && facts.url) parts.push(`[${label}](${facts.url})`);
1878
+ }
1879
+ parts.push("## Suggested Replies", ...list(ctx.flags.suggest), PLAIN_ENGLISH_REPLY);
1880
+ return parts;
1881
+ }
1882
+
1883
+ /**
1884
+ * `--summary`: the summary file's text, or the `--summary-missing` line when the
1885
+ * file is absent; with `--outbox`, the text is also kept there under the file's
1886
+ * name, outside the tree the close may remove.
1887
+ */
1888
+ function summaryOrMissing(ctx: RunContext, rel: string): string {
1889
+ const missing = str(ctx.flags.summaryMissing);
1890
+ if (!missing) throw new CommandError(EXIT.USAGE, "--summary needs --summary-missing");
1891
+ const abs = path.resolve(ctx.cwd, rel);
1892
+ const text = fs.existsSync(abs) ? fs.readFileSync(abs, "utf-8").replace(/\s+$/, "") : missing;
1893
+ const outbox = str(ctx.flags.outbox);
1894
+ if (outbox) {
1895
+ const dir = path.resolve(ctx.cwd, outbox);
1896
+ fs.mkdirSync(dir, { recursive: true });
1897
+ fs.writeFileSync(path.join(dir, path.basename(abs)), `${text}\n`);
1898
+ }
1899
+ return text;
1900
+ }
1901
+
1902
+ function finalReturnText(
1903
+ ctx: RunContext,
1904
+ workflow: string,
1905
+ parts: string[] | null,
1906
+ ): {
1907
+ finalReturn?: string;
1908
+ } {
1909
+ if (parts === null) return {};
1910
+ const tips = tipsText(false, workflow as TipsContext, ctx.cwd);
1911
+ return { finalReturn: [...parts, ...(tips ? ["## bkit Tips", tips] : [])].join("\n\n") };
1912
+ }
1913
+
1914
+ // ---------------------------------------------------------------------------
1915
+ // input
1916
+ // ---------------------------------------------------------------------------
1917
+
1918
+ /** A required input file's text, trailing newlines dropped; missing exits EXIT_NO_INPUT. */
1919
+ function inputText(cwd: string, rel: string, flag: string): string {
1920
+ const abs = path.resolve(cwd, rel);
1921
+ if (!fs.existsSync(abs)) throw new CommandError(EXIT_NO_INPUT, `--${flag} ${rel} does not exist`);
1922
+ return fs.readFileSync(abs, "utf-8").replace(/\s+$/, "");
1923
+ }
1924
+
1925
+ /** The run's issue parts from `issues fetch`'s files, oldest first; none for a run with no issue. */
1926
+ function inputIssueParts(ctx: RunContext): IssuePart[] {
1927
+ const descFile = str(ctx.flags.descriptionFile);
1928
+ const commentsFile = str(ctx.flags.commentsFile);
1929
+ const description = descFile ? inputText(ctx.cwd, descFile, "description-file") : "";
1930
+ let comments: IssueComment[] = [];
1931
+ if (commentsFile) {
1932
+ const parsed = parseJson(inputText(ctx.cwd, commentsFile, "comments-file"));
1933
+ const list = parsed.ok ? parseComments(parsed.value) : null;
1934
+ if (list === null)
1935
+ throw new CommandError(
1936
+ EXIT_NO_INPUT,
1937
+ `--comments-file ${commentsFile} is not a list of comments`,
1938
+ );
1939
+ comments = sortOldestFirst(list).comments;
1940
+ }
1941
+ return issueParts(description, comments);
1942
+ }
1943
+
1944
+ /** An ISO-8601 time in UTC, or undefined when it does not parse. */
1945
+ function utc(at: string | undefined): string | undefined {
1946
+ const t = at === undefined ? NaN : Date.parse(at);
1947
+ return Number.isNaN(t) ? undefined : new Date(t).toISOString();
1948
+ }
1949
+
1950
+ /**
1951
+ * When a design or plan file last changed: the author date of its last commit (a
1952
+ * rebase keeps it, unlike the committer date), or undefined (newer than any commit) when the file
1953
+ * has uncommitted changes or no commit.
1954
+ */
1955
+ function committedAt(cwd: string, rel: string): string | undefined {
1956
+ if ((git(cwd, ["status", "--porcelain", "--", rel]) ?? "") !== "") return undefined;
1957
+ return utc(git(cwd, ["log", "-1", "--format=%aI", "--", rel]) || undefined);
1958
+ }
1959
+
1960
+ const fileDate = (cwd: string, rel: string) => {
1961
+ const at = committedAt(cwd, rel);
1962
+ return at === undefined ? "uncommitted changes, newer than any commit" : `last committed ${at}`;
1963
+ };
1964
+
1965
+ function issueHeading(part: IssuePart): string {
1966
+ if (part.kind === "description") return "Issue description — oldest";
1967
+ const at = utc(part.createdAt);
1968
+ return at === undefined
1969
+ ? "Issue comment — no date, counts as oldest"
1970
+ : `Issue comment — posted ${at}`;
1971
+ }
1972
+
1973
+ /** Comments posted after the plan's last commit; none when the plan is missing or uncommitted. */
1974
+ function newerThanPlan(cwd: string, plan: string | undefined, parts: IssuePart[]): number {
1975
+ if (!plan || !fs.existsSync(path.resolve(cwd, plan))) return 0;
1976
+ const since = committedAt(cwd, plan);
1977
+ if (since === undefined) return 0;
1978
+ return parts.filter((p) => {
1979
+ const at = utc(p.createdAt);
1980
+ return p.kind === "comment" && at !== undefined && at > since;
1981
+ }).length;
1982
+ }
1983
+
1984
+ function inputVerb(ctx: RunContext): number {
1985
+ const workflow = workflowName(String(ctx.flags.workflow));
1986
+ const fid = String(ctx.flags.fid);
1987
+ const run = positiveInt(ctx.flags.run, "run")!;
1988
+ const file = str(ctx.flags.file);
1989
+ const status = file
1990
+ ? path.resolve(ctx.cwd, file)
1991
+ : statusLocation({
1992
+ cwd: ctx.cwd,
1993
+ workflow,
1994
+ fid,
1995
+ month: resolveMonth(repoRoot(ctx.cwd), fid, str(ctx.flags.month) || undefined),
1996
+ }).path;
1997
+ const sections: Array<[string, string]> = [
1998
+ [
1999
+ "Session Prompt — this run's, newer than everything below",
2000
+ inputText(ctx.cwd, String(ctx.flags.promptFile), "prompt-file"),
2001
+ ],
2002
+ ];
2003
+ const issue = inputIssueParts(ctx);
2004
+ for (const part of issue) sections.push([issueHeading(part), part.text]);
2005
+ const plan = str(ctx.flags.plan);
2006
+ if (plan && fs.existsSync(path.resolve(ctx.cwd, plan)))
2007
+ sections.push([
2008
+ `Plan — ${plan} — ${fileDate(ctx.cwd, plan)}`,
2009
+ inputText(ctx.cwd, plan, "plan"),
2010
+ ]);
2011
+ const design = str(ctx.flags.design);
2012
+ if (design) {
2013
+ const text = inputText(ctx.cwd, design, "design");
2014
+ sections.push([`Design — ${design} — ${fileDate(ctx.cwd, design)}`, text]);
2015
+ }
2016
+ for (const audit of list(ctx.flags.audit)) {
2017
+ const text = inputText(ctx.cwd, audit, "audit");
2018
+ sections.push([`Audit Report — ${audit} — ${fileDate(ctx.cwd, audit)}`, text]);
2019
+ }
2020
+ const body = sections.map(([h, text]) => `## ${h}\n\n${text}\n`).join("\n");
2021
+ const abs = path.join(path.dirname(status), `${workflow}-input-${run}.md`);
2022
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
2023
+ fs.writeFileSync(abs, body);
2024
+ ctx.emit({
2025
+ path: path.relative(ctx.cwd, abs),
2026
+ bytes: Buffer.byteLength(body),
2027
+ newerThanPlan: newerThanPlan(ctx.cwd, plan, issue),
2028
+ });
2029
+ return EXIT.OK;
2030
+ }
2031
+
2032
+ /**
2033
+ * Close / links output gains `commentFile`; with `--post`, the close comment once,
2034
+ * deduped by marker hash against the issue's latest comments (the close commit is
2035
+ * already made, so no engine-action row can land in it).
2036
+ */
2037
+ async function postClose(
2038
+ ctx: RunContext,
2039
+ fid: string,
2040
+ out: Record<string, unknown>,
2041
+ ): Promise<Record<string, unknown>> {
2042
+ const comment = typeof out.comment === "string" ? out.comment : null;
2043
+ const withFile = { ...out, commentFile: commentFileOf(ctx.cwd, comment) };
2044
+ if (ctx.flags.post !== true) return withFile;
2045
+ if (comment === null) throw new CommandError(EXIT.USAGE, "--post needs --number");
2046
+ return { ...withFile, tracker: await postForVerb(ctx, comment, { fid }) };
2047
+ }
2048
+
1327
2049
  export const workflowsCommand: CommandSpec = {
1328
2050
  noun: "workflows",
1329
- summary: "Start, fail, hand over and close a phase workflow run; promote and link its documents.",
2051
+ summary:
2052
+ "Start, fail, hand over, summarize and close a phase workflow run; promote and link its documents.",
1330
2053
  verbs: {
1331
2054
  start: {
1332
2055
  summary: "Take the feature lock and open a run (workflow-started unless resuming).",
2056
+ use: "workflow",
1333
2057
  flags: [
1334
2058
  WORKFLOW_FLAG,
1335
2059
  FID_FLAG,
@@ -1341,18 +2065,28 @@ export const workflowsCommand: CommandSpec = {
1341
2065
  help: "Step 1 already took the lock: check it is ours instead of acquiring",
1342
2066
  },
1343
2067
  TOKEN_FLAG,
2068
+ {
2069
+ name: "branch",
2070
+ type: "string",
2071
+ help: "the branch the checkout must be on; refuse (15) before anything is written when it is not",
2072
+ },
1344
2073
  ],
1345
2074
  output: {
1346
2075
  lock: "{path, month, token, reclaimed} of the lock taken, or {path} with --lock-held",
1347
2076
  file: "absolute path to status.jsonl",
1348
2077
  resumed: "the latest run was this workflow, IN_PROGRESS: no new row",
1349
- row: "the appended workflow-started row, or null when resuming",
2078
+ row: "the appended workflow-started row, with `limits` (the workflow's ask points from bkit.workflows, frozen for the run), or null when resuming",
1350
2079
  run: "which run of the workflow this is (1-based)",
2080
+ lastDoneStep: "the current run's last DONE step: resume after it (null on a new run)",
2081
+ openDecision:
2082
+ "{file, decision, question, from, pauseStep, group, verifyAttempt, testAttempt, plan} of the current run's highest {workflow}-decision-{run}-{N}.md holding Status: OPEN, else null",
1351
2083
  },
2084
+ textOmit: ["row"],
1352
2085
  exitCodes: {
1353
2086
  [EXIT_NO_STATUS]: "status.jsonl is not valid",
1354
2087
  [EXIT_SPLIT_BUCKET]: "the feature has logs in more than one month bucket",
1355
2088
  [EXIT_LOCK_NOT_HELD]: "--lock-held: the lock is missing or belongs to another owner",
2089
+ [EXIT_WRONG_BRANCH]: "--branch: the checkout is on another branch",
1356
2090
  },
1357
2091
  run: (ctx) => {
1358
2092
  const workflow = workflowName(String(ctx.flags.workflow));
@@ -1360,6 +2094,14 @@ export const workflowsCommand: CommandSpec = {
1360
2094
  const token = str(ctx.flags.token);
1361
2095
  if (token !== undefined && ctx.flags.lockHeld !== true)
1362
2096
  throw new CommandError(EXIT.USAGE, "--token applies with --lock-held only");
2097
+ const branch = str(ctx.flags.branch);
2098
+ if (branch !== undefined) {
2099
+ const on = git(ctx.cwd, ["branch", "--show-current"]) ?? "";
2100
+ if (on !== branch) {
2101
+ ctx.log(`[bkit-${workflow}] not on ${branch} in ${ctx.cwd} (on '${on}')`);
2102
+ return EXIT_WRONG_BRANCH;
2103
+ }
2104
+ }
1363
2105
  const where = whereInTree(ctx.cwd, {
1364
2106
  workflow,
1365
2107
  fid,
@@ -1387,25 +2129,49 @@ export const workflowsCommand: CommandSpec = {
1387
2129
  const file = where.status;
1388
2130
  fs.mkdirSync(path.dirname(file), { recursive: true });
1389
2131
  if (!fs.existsSync(file)) fs.writeFileSync(file, "");
2132
+ // A ship decides its handover afresh: a sentinel an earlier run left is stale.
2133
+ if (workflow === "ship") {
2134
+ for (const name of SENTINELS) {
2135
+ const p = path.join(path.dirname(file), name);
2136
+ if (!fs.existsSync(p)) continue;
2137
+ fs.rmSync(p, { force: true });
2138
+ ctx.log(`cleared stale ${name}`);
2139
+ }
2140
+ }
1390
2141
 
1391
- const latest = fold(readStatusEvents(file)).at(-1);
1392
- const resumed = latest?.workflow === workflow && latest.status === "IN_PROGRESS";
2142
+ const resumed = lastRun(fold(readStatusEvents(file)), workflow)?.status === "IN_PROGRESS";
2143
+ const holeyWarning = previousRunWarning(file, resumed);
2144
+ if (holeyWarning !== null) ctx.log(holeyWarning);
1393
2145
  let row: Record<string, unknown> | null = null;
1394
2146
  if (!resumed) {
2147
+ // The run's limits, frozen here: `counters route` reads them for the whole run.
2148
+ const asks = readBkitConfig(where.tree).asks;
2149
+ const limits = Object.fromEntries(
2150
+ ASK_POINTS.filter((p) => p.startsWith(`${workflow}.`)).map((p) => [p, asks[p]]),
2151
+ );
1395
2152
  row = {
1396
2153
  type: "workflow-started",
1397
2154
  workflow,
1398
2155
  at: statusTimestamp(),
1399
2156
  parentSha: headSha(path.dirname(file)),
2157
+ ...(Object.keys(limits).length === 0 ? {} : { limits }),
1400
2158
  };
1401
2159
  fs.appendFileSync(file, appendLine(row as StatusEvent));
1402
2160
  }
2161
+ recordChat(file, workflow, process.env);
2162
+ const runs = fold(readStatusEvents(file));
2163
+ const run = runNumber(runs, workflow);
2164
+ const current = resumed ? lastRun(runs, workflow) : undefined;
1403
2165
  ctx.emit({
1404
2166
  lock,
1405
2167
  file,
1406
2168
  resumed,
1407
2169
  row,
1408
- run: runNumber(fold(readStatusEvents(file)), workflow),
2170
+ run,
2171
+ lastDoneStep: current?.steps.filter((s) => s.status === "DONE").at(-1)?.step ?? null,
2172
+ openDecision: resumed
2173
+ ? openDecision(path.dirname(file), where.tree, workflow, run)
2174
+ : null,
1409
2175
  });
1410
2176
  return EXIT.OK;
1411
2177
  },
@@ -1413,6 +2179,7 @@ export const workflowsCommand: CommandSpec = {
1413
2179
  fail: {
1414
2180
  summary:
1415
2181
  "Failure Path: workflow-failed row, abort rebase, release lock, clear sentinels (with --token); the bkit:failed labels and the failure comment.",
2182
+ use: "workflow",
1416
2183
  flags: [
1417
2184
  WORKFLOW_FLAG,
1418
2185
  { ...FID_FLAG, required: false, help: "feature id (needed with --token)" },
@@ -1456,10 +2223,20 @@ export const workflowsCommand: CommandSpec = {
1456
2223
  type: "string",
1457
2224
  help: "the failed shell command's stderr (last 20 lines kept)",
1458
2225
  },
2226
+ {
2227
+ ...POST_FLAG,
2228
+ help: "post the failure comment (needs --step-number) to the --fid / --issue issue and write its failed labels; prints `tracker` and `labelsWrite`",
2229
+ },
2230
+ {
2231
+ name: "issue",
2232
+ type: "string",
2233
+ help: "with --post: the issue id when there is no --fid yet",
2234
+ },
2235
+ SESSION_DIR_FLAG,
1459
2236
  ],
1460
2237
  output: {
1461
2238
  row: "the appended workflow-failed row, or null (no --token, or no status.jsonl)",
1462
- rebaseAborted: "an in-progress rebase was found and aborted",
2239
+ rebaseAborted: "an in-progress rebase or merge was found and aborted",
1463
2240
  lock: "{path, existed, released, heldBy}: heldBy is another owner's lock line, left in place; null without --token",
1464
2241
  sentinels: "[{name, path}] sentinels that existed before this call removed them",
1465
2242
  handoverNeeded:
@@ -1470,7 +2247,13 @@ export const workflowsCommand: CommandSpec = {
1470
2247
  trackerState: "the Linear or Jira state for the failed issue (null under github, none)",
1471
2248
  prState: "the --pr PR's state, or null",
1472
2249
  comment: "the failure comment body (with --step-number), else null",
2250
+ commentFile: COMMENT_FILE_OUTPUT,
2251
+ tracker: TRACKER_OUTPUT,
2252
+ labelsWrite:
2253
+ "with --post: the label and state write, read fresh from the issue: {done: true, action: labels} | {done: false, action, reason} (write `labels` / `trackerState` via the tracker MCP) | {skipped}",
2254
+ sessionRemoved: SESSION_REMOVED_OUTPUT,
1473
2255
  },
2256
+ textOmit: ["row"],
1474
2257
  exitCodes: {
1475
2258
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1476
2259
  [EXIT_REMOVE_FAILED]:
@@ -1481,6 +2264,7 @@ export const workflowsCommand: CommandSpec = {
1481
2264
  handover: {
1482
2265
  summary:
1483
2266
  "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.",
2267
+ use: "workflow",
1484
2268
  flags: [
1485
2269
  WORKFLOW_FLAG,
1486
2270
  FID_FLAG,
@@ -1488,7 +2272,7 @@ export const workflowsCommand: CommandSpec = {
1488
2272
  {
1489
2273
  name: "push",
1490
2274
  type: "boolean",
1491
- 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",
2275
+ help: "feature branch: git add -A (minus bkit.workflows.worktree.copy entries), commit `docs({fid}): {workflow} aborted bkit [skip ci]`, push --mode=abort; dev / main / detached: lands like --flush, the checkout untouched",
1492
2276
  },
1493
2277
  {
1494
2278
  name: "flush",
@@ -1501,12 +2285,18 @@ export const workflowsCommand: CommandSpec = {
1501
2285
  help: "--push: the open-PR answer from MCP (a number, or none) instead of asking gh",
1502
2286
  },
1503
2287
  { name: "ref", type: "string", help: "link the handover at this ref (no push / flush)" },
2288
+ {
2289
+ name: "list-stray",
2290
+ type: "boolean",
2291
+ help: "only list what --push would sweep in besides the run's logs (modified, untracked) and whether the checkout is shared; writes nothing",
2292
+ },
1504
2293
  {
1505
2294
  name: "worktree",
1506
2295
  type: "string",
1507
2296
  help: "the run's tree: holds the handover and the logs, and is where --push commits (default: cwd's checkout)",
1508
2297
  },
1509
2298
  OWNER_REPO_FLAG,
2299
+ { ...POST_FLAG, help: "post the handover comment to the FID's issue; prints `tracker`" },
1510
2300
  ],
1511
2301
  output: {
1512
2302
  handover: "the handover artifact, or null when absent",
@@ -1515,6 +2305,11 @@ export const workflowsCommand: CommandSpec = {
1515
2305
  skipped: "why nothing was pushed: open-pr | skip-ci | nothing-to-commit (null otherwise)",
1516
2306
  comment:
1517
2307
  "the handover comment body (null when there is no handover); links only when pushed",
2308
+ commentFile: COMMENT_FILE_OUTPUT,
2309
+ tracker: `${TRACKER_OUTPUT}; absent when there is no handover`,
2310
+ shared: "--list-stray: the checkout is dev / main / detached (remove nothing)",
2311
+ modified: "--list-stray: tracked paths with changes, outside the run's logs",
2312
+ untracked: "--list-stray: untracked paths, outside the run's logs",
1518
2313
  },
1519
2314
  exitCodes: {
1520
2315
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
@@ -1530,6 +2325,7 @@ export const workflowsCommand: CommandSpec = {
1530
2325
  close: {
1531
2326
  summary:
1532
2327
  "Grade compliance, workflow-done row, counter + outcome telemetry, report, artifact links; --flush lands ship's close on dev.",
2328
+ use: "workflow",
1533
2329
  flags: [
1534
2330
  WORKFLOW_FLAG,
1535
2331
  FID_FLAG,
@@ -1564,7 +2360,7 @@ export const workflowsCommand: CommandSpec = {
1564
2360
  {
1565
2361
  name: "message",
1566
2362
  type: "string",
1567
- help: "then git add -A and commit with this message in the tree",
2363
+ help: "then git add -A (minus bkit.workflows.worktree.copy entries) and commit with this message in the tree",
1568
2364
  },
1569
2365
  {
1570
2366
  name: "label",
@@ -1579,6 +2375,16 @@ export const workflowsCommand: CommandSpec = {
1579
2375
  },
1580
2376
  ...COMMENT_FLAGS,
1581
2377
  { name: "tree", type: "string", help: "the close comment links the tree of this ref" },
2378
+ {
2379
+ name: "ending",
2380
+ type: "string",
2381
+ help: "done|held (default done); held = a local build that published nothing",
2382
+ },
2383
+ {
2384
+ name: "publish",
2385
+ type: "string",
2386
+ help: "build: true|false, the resolved publish value; recorded on the workflow-done and outcome rows",
2387
+ },
1582
2388
  {
1583
2389
  name: "flush",
1584
2390
  type: "boolean",
@@ -1590,6 +2396,40 @@ export const workflowsCommand: CommandSpec = {
1590
2396
  type: "string",
1591
2397
  help: "--flush: the shipped branch, deleted locally and on origin with the worktree once the close is on dev",
1592
2398
  },
2399
+ SESSION_DIR_FLAG,
2400
+ {
2401
+ name: "final-return",
2402
+ type: "boolean",
2403
+ help: "print finalReturn: the run's last message to the person (needs --summary-file)",
2404
+ },
2405
+ {
2406
+ name: "summary-file",
2407
+ type: "string",
2408
+ help: "--final-return: the summary shown verbatim (read before the close runs)",
2409
+ },
2410
+ {
2411
+ name: "summary",
2412
+ type: "string",
2413
+ help: "--final-return: like --summary-file, but a missing file shows --summary-missing; a copy is kept in --outbox",
2414
+ },
2415
+ {
2416
+ name: "summary-missing",
2417
+ type: "string",
2418
+ help: "--summary: the line shown when the summary file does not exist",
2419
+ },
2420
+ { name: "warning", type: "string", help: "--final-return: line 1, before the summary" },
2421
+ {
2422
+ name: "line",
2423
+ type: "string",
2424
+ repeatable: true,
2425
+ help: "--final-return: a line after the summary, before the issue link",
2426
+ },
2427
+ {
2428
+ name: "suggest",
2429
+ type: "string",
2430
+ repeatable: true,
2431
+ help: "--final-return: a suggested reply, before the plain-English offer",
2432
+ },
1593
2433
  ],
1594
2434
  output: {
1595
2435
  row: "the appended workflow-done row",
@@ -1606,20 +2446,31 @@ export const workflowsCommand: CommandSpec = {
1606
2446
  parentSha: "HEAD before the --message commit (the close step's parentSha)",
1607
2447
  commit: "the --message commit, or null",
1608
2448
  comment: "the close comment (--number with --outbox), else null",
2449
+ commentFile: COMMENT_FILE_OUTPUT,
2450
+ tracker: TRACKER_OUTPUT,
1609
2451
  roadmapFoldNeeded:
1610
2452
  "always true: append the feature row and re-render the board (not run here)",
1611
2453
  featureStatus: "roadmap status this close moves the feature to",
2454
+ progressLine:
2455
+ "--record-step: the exact chat progress line after a numbered completion is recorded",
1612
2456
  landed: "--flush: {ref, via: head-push | close-pr | close-pr-open}",
1613
2457
  worktree:
1614
2458
  "--flush: the `bkit worktrees remove` result once the close is on dev; null while the close PR is unmerged or the removal failed",
2459
+ sessionRemoved: SESSION_REMOVED_OUTPUT,
2460
+ finalReturn:
2461
+ "--final-return: the warning, the summary verbatim, the issue link from {session-dir}/issue-facts.json, `## Suggested Replies` (each --suggest, then the plain-English offer) and `## bkit Tips` (what `bkit tips --workflow` prints, when anything)",
1615
2462
  },
2463
+ textOmit: ["row", "counterRow", "outcomeRow"],
1616
2464
  exitCodes: {
1617
2465
  [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
2466
+ [EXIT_NO_INPUT]: "--final-return: --summary-file does not exist (nothing written)",
1618
2467
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1619
2468
  [EXIT_PUSH_FAILED]:
1620
- "--flush: dev moved before every push, or the push failed without a server answer; the lock is kept",
2469
+ "--flush: dev moved before every push, or the push failed without a server answer; the lock is kept. Without --flush, --message in an in-place run: a path that was dirty before the run changed during it (EXIT_FOREIGN_PATH) — no row written, nothing committed",
1621
2470
  [EXIT_FLUSH_FAILED]:
1622
2471
  "--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",
2472
+ [EXIT_NO_RECORD]:
2473
+ "--message in a debug run on dev/main with no shared-checkout record: no row written, nothing committed",
1623
2474
  },
1624
2475
  run: async (ctx) => {
1625
2476
  const f = ctx.flags;
@@ -1640,20 +2491,84 @@ export const workflowsCommand: CommandSpec = {
1640
2491
  number: str(f.number),
1641
2492
  title: str(f.title),
1642
2493
  tree: str(f.tree),
2494
+ ...closeEnding(f),
1643
2495
  };
2496
+ const finalParts = finalReturnParts(ctx, input.fid);
1644
2497
  if (f.flush === true) {
1645
2498
  if (input.workflow !== "ship") throw new CommandError(EXIT.USAGE, "--flush is ship only");
1646
2499
  const r = await shipClose(ctx, { ...input, branch: str(f.branch) }, str(f.token));
1647
- if (r.out) ctx.emit(r.out);
2500
+ if (r.out) {
2501
+ const out = r.out as Record<string, unknown>;
2502
+ const posted =
2503
+ typeof out.comment === "string"
2504
+ ? await postClose(ctx, input.fid, out)
2505
+ : { ...out, commentFile: null };
2506
+ const final = finalReturnText(ctx, input.workflow, finalParts);
2507
+ ctx.emit({ ...posted, ...final, ...sessionRemoval(ctx) });
2508
+ }
1648
2509
  return r.code;
1649
2510
  }
1650
- ctx.emit(closeWorkflow(ctx.cwd, input, ctx.log));
2511
+ const out = await postClose(ctx, input.fid, { ...closeWorkflow(ctx.cwd, input, ctx.log) });
2512
+ const final = finalReturnText(ctx, input.workflow, finalParts);
2513
+ ctx.emit({ ...out, ...final, ...sessionRemoval(ctx) });
1651
2514
  return EXIT.OK;
1652
2515
  },
1653
2516
  },
2517
+ input: {
2518
+ summary:
2519
+ "Write logs/{FID}/{workflow}-input-{run}.md: the session prompt, the issue description and each human comment, then the plan, design and audit reports, each section dated.",
2520
+ use: "workflow",
2521
+ flags: [
2522
+ WORKFLOW_FLAG,
2523
+ FID_FLAG,
2524
+ MONTH_FLAG,
2525
+ {
2526
+ ...STATUS_FILE_FLAG,
2527
+ help: "status.jsonl: the input file goes beside it (default: derived)",
2528
+ },
2529
+ { name: "run", type: "string", required: true, help: "the run number ({RUN})" },
2530
+ {
2531
+ name: "prompt-file",
2532
+ type: "string",
2533
+ required: true,
2534
+ help: "the session prompt ({SESSION_DIR}/prompt.md)",
2535
+ },
2536
+ {
2537
+ name: "description-file",
2538
+ type: "string",
2539
+ help: "issue-description.md from `issues fetch` (omit for a run with no issue)",
2540
+ },
2541
+ {
2542
+ name: "comments-file",
2543
+ type: "string",
2544
+ help: "issue-comments.json from `issues fetch`: bkit:generated comments dropped, the ignore-earlier cut applied",
2545
+ },
2546
+ { name: "plan", type: "string", help: "appended under `## Plan — <path>` when it exists" },
2547
+ { name: "design", type: "string", help: "plan: the parent design, appended (must exist)" },
2548
+ {
2549
+ name: "audit",
2550
+ type: "string",
2551
+ repeatable: true,
2552
+ help: "plan: an audit report, appended in flag order (must exist)",
2553
+ },
2554
+ ],
2555
+ output: {
2556
+ path: "the input file written, relative to cwd",
2557
+ bytes: "its size in bytes",
2558
+ newerThanPlan:
2559
+ "issue comments posted after the plan's last commit (0 with no plan, or one with uncommitted changes)",
2560
+ },
2561
+ exitCodes: {
2562
+ [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
2563
+ [EXIT_NO_INPUT]:
2564
+ "the prompt, description, comments, design or an audit file is missing, or the comments are not a list",
2565
+ },
2566
+ run: inputVerb,
2567
+ },
1654
2568
  promote: {
1655
2569
  summary:
1656
- "Design / plan close: the highest versioned draft becomes the canonical doc (anchor stamped, a changed canonical archived, plan sub-plans copied).",
2570
+ "Design / plan close: the highest versioned draft becomes the canonical doc (anchor stamped, a changed canonical archived).",
2571
+ use: "workflow",
1657
2572
  flags: [
1658
2573
  { ...WORKFLOW_FLAG, help: "design | plan" },
1659
2574
  FID_FLAG,
@@ -1673,8 +2588,7 @@ export const workflowsCommand: CommandSpec = {
1673
2588
  final:
1674
2589
  "the highest versioned draft, e.g. docs/plans/202610/logs/12-x/design-v3-organised.md",
1675
2590
  canonical: "the canonical doc written, or null with --resolve",
1676
- archived: "superseded canonical docs moved to archive/",
1677
- subPlans: "plan: the canonical sub-plans written",
2591
+ archived: "the superseded canonical doc moved to archive/, if any",
1678
2592
  baseSha: "the base commit stamped into the anchor, or null when none was recorded",
1679
2593
  },
1680
2594
  exitCodes: {
@@ -1686,6 +2600,7 @@ export const workflowsCommand: CommandSpec = {
1686
2600
  links: {
1687
2601
  summary:
1688
2602
  "The feature's docs and this workflow's logs on a ref as markdown links; optionally the close comment.",
2603
+ use: "workflow",
1689
2604
  flags: [
1690
2605
  WORKFLOW_FLAG,
1691
2606
  FID_FLAG,
@@ -1708,11 +2623,13 @@ export const workflowsCommand: CommandSpec = {
1708
2623
  artifactLinks: "the same as markdown `- [name](url)` lines",
1709
2624
  comment:
1710
2625
  "the close comment (--number with --outbox): Artifacts and Telemetry sections, else null",
2626
+ commentFile: COMMENT_FILE_OUTPUT,
2627
+ tracker: TRACKER_OUTPUT,
1711
2628
  },
1712
2629
  exitCodes: {
1713
2630
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1714
2631
  },
1715
- run: (ctx) => {
2632
+ run: async (ctx) => {
1716
2633
  const workflow = workflowName(String(ctx.flags.workflow));
1717
2634
  const fid = String(ctx.flags.fid);
1718
2635
  const root = repoRoot(ctx.cwd);
@@ -1740,9 +2657,54 @@ export const workflowsCommand: CommandSpec = {
1740
2657
  } else if (ctx.flags.number !== undefined) {
1741
2658
  throw new CommandError(EXIT.USAGE, "--number needs --outbox");
1742
2659
  }
1743
- ctx.emit({ artifacts, artifactLinks: linkLines(artifacts), comment });
2660
+ ctx.emit(
2661
+ await postClose(ctx, fid, { artifacts, artifactLinks: linkLines(artifacts), comment }),
2662
+ );
1744
2663
  return EXIT.OK;
1745
2664
  },
1746
2665
  },
2666
+ summary: {
2667
+ summary:
2668
+ "The Summary step: write {workflow}-summary.md next to --file with the run's verdict, reasons and next command.",
2669
+ use: "workflow",
2670
+ flags: [
2671
+ { ...WORKFLOW_FLAG, help: "plan | design | build | debug | ship" },
2672
+ {
2673
+ name: "file",
2674
+ type: "string",
2675
+ required: true,
2676
+ help: "the run's docs/plans/{YYYYMM}/logs/{FID}/status.jsonl; the summary is written beside it",
2677
+ },
2678
+ {
2679
+ name: "plan",
2680
+ type: "string",
2681
+ repeatable: true,
2682
+ help: "a plan file the run worked from (default: build reads {FID}-plan.md)",
2683
+ },
2684
+ {
2685
+ name: "pr",
2686
+ type: "string",
2687
+ help: "ship: the PR number; its size comes from gh pr view (left out when gh cannot answer)",
2688
+ },
2689
+ {
2690
+ name: "publish",
2691
+ type: "string",
2692
+ help: "build: true|false, the resolved ending; false writes `Publish: held` and `Docs: not synced` (default true)",
2693
+ },
2694
+ ],
2695
+ output: {
2696
+ verdict: "PASS | CONCERNS | FAIL",
2697
+ failures: "the count of FAIL reasons: 0 on PASS and CONCERNS",
2698
+ reasons: "one line per reason, FAIL reasons first",
2699
+ file: "the summary written, repo-relative",
2700
+ nextStep:
2701
+ "the recommended next command (with the issue ref), or the fixed line when there is none",
2702
+ },
2703
+ exitCodes: {
2704
+ [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
2705
+ [EXIT_NO_RUN]: "status.jsonl has no workflow-started row for --workflow (nothing written)",
2706
+ },
2707
+ run: summaryVerb,
2708
+ },
1747
2709
  },
1748
2710
  };