@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,24 +17,35 @@
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
  import * as fs from "node:fs";
23
+ import * as os from "node:os";
21
24
  import * as path from "node:path";
22
- import { appendLine, fold, runNumber, runOrStepField, statusTimestamp, } from "../../ledgers/status.js";
23
- import { appendLine as telemetryLine, foldFrom, resolveRepoSlug, validate, workflowTelemetry, } from "../../ledgers/telemetry.js";
24
- import { readBkitVersion } from "../../install/version-file.js";
25
- import { readBkitConfig } from "../../shared/settings.js";
25
+ import { appendLine, fold, lastRun, runNumber, runOrStepField, statusTimestamp, } from "../../ledgers/status.js";
26
+ import { compareTs, foldFrom, normalize, resolveRepoSlug, workflowTelemetry, } from "../../ledgers/telemetry.js";
27
+ import { check as checkCompleteness, deriveContract, parseRows, readCompleteness, } from "../../checks/status-holes.js";
28
+ import { getWorkflowsRoot } from "../../shared/package-roots.js";
29
+ import { ASK_POINTS, readBkitConfig } from "../../shared/settings.js";
26
30
  import { gradeCompliance } from "../comply.js";
27
- import { landDir, pushToDev } from "../land.js";
31
+ import { fetchDev, landDir, pushToDev } from "../land.js";
28
32
  import { CommandError, DEV, EXIT, git, isSharedBranch, parseJson, repoRoot, runGh, runGit, statusLocation, statusRelPath, } from "../lib.js";
29
33
  import { anchorBkitStatus, pushBranch, readAnchor, stampAnchor } from "./branches.js";
30
- import { AUTO_LABEL, AUTO_ROUTE_SUFFIX, buildComment, trackerState, transitionLabels, } from "./issues.js";
31
- import { EXIT_EMPTY, commitBookkeeping, unionLedgers } from "./ledgers.js";
34
+ import { AUTO_LABEL, AUTO_ROUTE_SUFFIX, buildComment, issueParts, parseComments, sortOldestFirst, trackerState, transitionLabels, } from "./issues.js";
35
+ import { EXIT_EMPTY, activeRecord, commitBookkeeping, ownPathCommit, ownSet, removeRecord, appendLedgerRows, runRows, unionLedgers, } from "./ledgers.js";
36
+ import { readIssueTracker } from "./fids.js";
37
+ import { agentContextBlock, buildBlock, chatFingerprint, ciList, claudeTranscripts, hostChat, planBlock, planFiles, runChats, runLines, runStatusRows, stepsBlock, timeBlock, } from "./run-facts.js";
38
+ import { buildSummary, refOf, SUMMARY_WORKFLOWS } from "./summary.js";
39
+ import { parsePlans, parseWorkstreams } from "./plans.js";
32
40
  import { EXIT_REMOVE_FAILED, EXIT_SPLIT_BUCKET, acquireWorkflowLock, owns, readHolder, releaseLock, resolveMonth, workflowLockPath, } from "./locks.js";
41
+ import { highestVersion } from "./plan-versions.js";
33
42
  import { mergePr, probePr } from "./prs.js";
34
43
  import { FEATURE_STATUS } from "./roadmap.js";
35
44
  import { EXIT_NO_STATUS, WORKFLOW_FLAG, positiveInt, readRuns, readStatusEvents, readStatusRows, str, } from "./status.js";
36
- import { writeStepRow } from "./steps.js";
37
- import { removeWorktree } from "./worktrees.js";
45
+ import { COMMENT_FILE_OUTPUT, POST_FLAG, TRACKER_OUTPUT, attempt, commentFileOf, postForVerb, issueRef, readLabels, endedRunActionKey, skipOf, trackerTarget, writeLabels, } from "./tracker.js";
46
+ import { tipsText } from "../tips.js";
47
+ import { EXIT_NO_RECORD, requireRecordOnShared, writeStepRow } from "./steps.js";
48
+ import { addAllButCopied, removeWorktree } from "./worktrees.js";
38
49
  /** Sentinels a workflow leaves in its logs folder; either one existing means a handover is due. */
39
50
  export const SENTINELS = [".rebase-failed", ".deferred-blocked"];
40
51
  /** Exit code (start --lock-held): the lock is missing or belongs to another owner. */
@@ -47,6 +58,12 @@ export const EXIT_PUSH_FAILED = 10;
47
58
  export const EXIT_FLUSH_FAILED = 11;
48
59
  /** Exit code (promote): no versioned draft to promote. */
49
60
  export const EXIT_NO_VERSION = 12;
61
+ /** Exit code (input): a named input file is missing or not in the expected shape. */
62
+ export const EXIT_NO_INPUT = 13;
63
+ /** Exit code (start --branch): the checkout is not on the named branch. */
64
+ export const EXIT_WRONG_BRANCH = 15;
65
+ /** Exit code (summary): the status file has no run of the workflow. */
66
+ export const EXIT_NO_RUN = 16;
50
67
  function workflowName(workflow) {
51
68
  if (!Object.hasOwn(FEATURE_STATUS, workflow))
52
69
  throw new CommandError(EXIT.USAGE, `--workflow must be ${Object.keys(FEATURE_STATUS).join(", ")}`);
@@ -61,6 +78,72 @@ function whereInTree(cwd, o) {
61
78
  return { root, month, tree, status };
62
79
  }
63
80
  const headSha = (cwd) => git(cwd, ["rev-parse", "HEAD"]) ?? "";
81
+ /**
82
+ * Append a `session` row naming the chat that runs this start (`hostChat`), as its
83
+ * fingerprint, unless the current run's latest `session` row already names it. Nothing when
84
+ * the host names no chat. The close and the harvest read the run's chats from these rows.
85
+ */
86
+ export function recordChat(file, workflow, env) {
87
+ const chat = hostChat(env);
88
+ if (chat === undefined)
89
+ return;
90
+ const session = chatFingerprint(chat.platform, chat.id);
91
+ const events = readStatusEvents(file);
92
+ const startAt = lastOfType(events, "workflow-started", workflow)?.at;
93
+ const last = events
94
+ .filter((e) => e.type === "session" &&
95
+ e.workflow === workflow &&
96
+ (startAt === undefined || String(e.at) >= startAt))
97
+ .at(-1);
98
+ if (last?.session === session)
99
+ return;
100
+ const row = {
101
+ type: "session",
102
+ workflow,
103
+ at: statusTimestamp(),
104
+ platform: chat.platform,
105
+ session,
106
+ };
107
+ fs.appendFileSync(file, appendLine(row));
108
+ }
109
+ /**
110
+ * The highest-numbered `{workflow}-decision-{run}-{N}.md` in `logDir` whose header holds
111
+ * `Status: OPEN`, or null. Only the given run's files count, so an earlier run's pause
112
+ * never resurfaces. `file` is relative to `tree`.
113
+ */
114
+ export function openDecision(logDir, tree, workflow, run) {
115
+ if (!fs.existsSync(logDir))
116
+ return null;
117
+ const name = new RegExp(`^${workflow}-decision-${run}-([0-9]+)\\.md$`);
118
+ const found = fs
119
+ .readdirSync(logDir)
120
+ .map((f) => ({ f, m: name.exec(f) }))
121
+ .filter((x) => x.m !== null)
122
+ .map(({ f, m }) => ({ f, n: Number(m[1]) }))
123
+ .sort((a, b) => b.n - a.n);
124
+ for (const { f, n } of found) {
125
+ const text = fs.readFileSync(path.join(logDir, f), "utf-8");
126
+ const field = (key) => new RegExp(`^${key}:[ \\t]*(.+?)[ \\t]*$`, "m").exec(text)?.[1] ?? null;
127
+ if (field("Status") !== "OPEN")
128
+ continue;
129
+ const num = (key) => {
130
+ const v = field(key);
131
+ return v !== null && /^[0-9]+$/.test(v) ? Number(v) : null;
132
+ };
133
+ return {
134
+ file: path.relative(tree, path.join(logDir, f)),
135
+ decision: n,
136
+ question: field("Question"),
137
+ from: field("From"),
138
+ pauseStep: num("Pause step"),
139
+ group: num("Group"),
140
+ verifyAttempt: num("Verify attempt"),
141
+ testAttempt: num("Test attempt"),
142
+ plan: field("Plan"),
143
+ };
144
+ }
145
+ return null;
146
+ }
64
147
  const logDirRel = (month, fid) => path.join("docs", "plans", month, "logs", fid);
65
148
  const list = (v) => v ?? [];
66
149
  // ---------------------------------------------------------------------------
@@ -77,19 +160,25 @@ function checkHeldLock(file, who) {
77
160
  // fail
78
161
  // ---------------------------------------------------------------------------
79
162
  /**
80
- * Abort a rebase left in progress in `tree`. `git rev-parse --git-path X` always
81
- * exits 0 (it only computes the path), so the directory's existence is the test.
163
+ * Abort a rebase or a merge left in progress in `tree` (ship Step 4 leaves a merge
164
+ * of origin/dev in progress for a hand resolution). `git rev-parse --git-path X`
165
+ * always exits 0 (it only computes the path), so the path's existence is the test.
82
166
  */
83
167
  function abortRebase(tree, log) {
84
- const inProgress = ["rebase-merge", "rebase-apply"].some((name) => {
168
+ const present = (name) => {
85
169
  const p = git(tree, ["rev-parse", "--path-format=absolute", "--git-path", name]);
86
170
  return p !== null && fs.existsSync(p);
87
- });
88
- if (!inProgress)
171
+ };
172
+ const op = ["rebase-merge", "rebase-apply"].some(present)
173
+ ? "rebase"
174
+ : present("MERGE_HEAD")
175
+ ? "merge"
176
+ : null;
177
+ if (op === null)
89
178
  return false;
90
- const res = runGit(tree, ["rebase", "--abort"]);
179
+ const res = runGit(tree, [op, "--abort"]);
91
180
  if (!res.ok)
92
- log(`git rebase --abort failed in ${tree}: ${res.stderr}`);
181
+ log(`git ${op} --abort failed in ${tree}: ${res.stderr}`);
93
182
  return res.ok;
94
183
  }
95
184
  /** The workflow-failed state: row, rebase abort, lock release, sentinels. */
@@ -143,9 +232,9 @@ function failState(ctx, workflow, fid) {
143
232
  fs.rmSync(p, { force: true });
144
233
  }
145
234
  }
146
- return { row, rebaseAborted, lock, sentinels, removeFailed, soak };
235
+ return { row, rebaseAborted, lock, sentinels, removeFailed, soak, status };
147
236
  }
148
- function failVerb(ctx) {
237
+ async function failVerb(ctx) {
149
238
  const workflow = workflowName(String(ctx.flags.workflow));
150
239
  // An empty value is a placeholder not held yet (the failure came before it was set).
151
240
  const fid = str(ctx.flags.fid) || undefined;
@@ -162,6 +251,7 @@ function failVerb(ctx) {
162
251
  sentinels: [],
163
252
  removeFailed: false,
164
253
  soak: false,
254
+ status: undefined,
165
255
  }
166
256
  : failState(ctx, workflow, fid);
167
257
  // Labels: bkit:failed added; a ship whose PR already merged also moves to bkit:merged.
@@ -173,11 +263,16 @@ function failVerb(ctx) {
173
263
  }
174
264
  const merged = prState === "MERGED";
175
265
  const transition = merged ? { phase: "merged" } : { failed: true };
266
+ const failedSet = (current) => {
267
+ const labels = transitionLabels(current, transition).labels;
268
+ if (merged && !labels.includes("bkit:failed"))
269
+ labels.push("bkit:failed");
270
+ return labels;
271
+ };
176
272
  const current = list(ctx.flags.label);
177
- const labels = transitionLabels(current, transition).labels;
178
- if (merged && !labels.includes("bkit:failed"))
179
- labels.push("bkit:failed");
273
+ const labels = failedSet(current);
180
274
  const add = labels.filter((l) => !current.includes(l));
275
+ const failedState = trackerState(transition, undefined, readBkitConfig(repoRoot(ctx.cwd)));
181
276
  // The failure comment, when the step is named.
182
277
  let comment = null;
183
278
  const stepNumber = str(ctx.flags.stepNumber);
@@ -193,6 +288,18 @@ function failVerb(ctx) {
193
288
  stderrFile: str(ctx.flags.stderrFile) || undefined,
194
289
  });
195
290
  }
291
+ if (ctx.flags.post === true && comment === null)
292
+ throw new CommandError(EXIT.USAGE, "--post needs --step-number");
293
+ // Once per run and step: an engine-action row where the run's status.jsonl exists.
294
+ const key = endedRunActionKey(state.status, workflow, "failure", stepNumber, str(ctx.flags.subStep) || undefined);
295
+ const tracker = ctx.flags.post === true && comment !== null
296
+ ? await postForVerb(ctx, comment, {
297
+ fid,
298
+ issue: str(ctx.flags.issue),
299
+ ...(key === undefined ? {} : { file: state.status, key }),
300
+ })
301
+ : undefined;
302
+ const labelsWrite = ctx.flags.post === true ? await writeFailedLabels(ctx, fid, failedSet, failedState) : undefined;
196
303
  ctx.emit({
197
304
  row: state.row,
198
305
  rebaseAborted: state.rebaseAborted,
@@ -202,12 +309,36 @@ function failVerb(ctx) {
202
309
  (ctx.flags.maxExceeded === true || state.sentinels.length > 0 || state.soak),
203
310
  add,
204
311
  labels,
205
- trackerState: trackerState(transition, undefined, readBkitConfig(repoRoot(ctx.cwd))),
312
+ trackerState: failedState,
206
313
  prState,
207
314
  comment,
315
+ commentFile: commentFileOf(ctx.cwd, comment),
316
+ ...(tracker === undefined ? {} : { tracker }),
317
+ ...(labelsWrite === undefined ? {} : { labelsWrite }),
318
+ ...sessionRemoval(ctx),
208
319
  });
209
320
  return state.removeFailed ? EXIT_REMOVE_FAILED : EXIT.OK;
210
321
  }
322
+ /**
323
+ * `fail --post`: read the issue's labels, write the failed set and the review state.
324
+ * The set comes from the labels read, not `--label`, so a label added since Step 1 stays.
325
+ */
326
+ async function writeFailedLabels(ctx, fid, failedSet, state) {
327
+ const t = trackerTarget(ctx.cwd, { fid, issue: str(ctx.flags.issue) });
328
+ const skip = skipOf(t);
329
+ if (skip)
330
+ return skip;
331
+ return attempt("labels", ctx.log, async () => {
332
+ const current = await readLabels(t);
333
+ const labels = failedSet(current);
334
+ await writeLabels(t, {
335
+ add: labels.filter((l) => !current.includes(l)),
336
+ remove: current.filter((l) => !labels.includes(l)),
337
+ labels,
338
+ state,
339
+ });
340
+ });
341
+ }
211
342
  /** A text file's content, trailing newlines dropped; a missing file is a usage error. */
212
343
  function readText(cwd, rel) {
213
344
  const abs = path.resolve(cwd, rel);
@@ -253,20 +384,57 @@ const SHARED_LEDGERS = [
253
384
  ":(glob).bkit/*.jsonl",
254
385
  ":(exclude).bkit/issues.jsonl",
255
386
  ];
387
+ /**
388
+ * Kinds no workflow run writes: bkit's harvest script writes them to `harvest/`, and a
389
+ * `run` row names any feature's workflow (`.bkit/jsonl.md` § Ledgers & Writers).
390
+ */
391
+ const NOT_A_RUNS_OWN_KIND = new Set(["chat", "run"]);
392
+ /** HEAD and every `parentSha` the run's status rows of `workflow` carry: the shas its `run.parentSha` can name. */
393
+ function runShas(src, status, workflow) {
394
+ const shas = new Set([headSha(src)]);
395
+ for (const e of fs.existsSync(status) ? readStatusEvents(status) : []) {
396
+ const sha = e.parentSha;
397
+ if (e.workflow === workflow && typeof sha === "string")
398
+ shas.add(sha);
399
+ }
400
+ shas.delete("");
401
+ return shas;
402
+ }
403
+ /** A feature id in `references`: a bare number or `{N}-{slug}`. */
404
+ const FEATURE_REF = /^\d+(-[a-z0-9-]+)?$/;
405
+ /**
406
+ * A shared-ledger row (normalized) of THIS run: a row of `workflow` at or after its
407
+ * start, never a kind no run writes. A row with `run.parentSha` (compliance, counter,
408
+ * outcome) must name one of the run's shas; any other row must not point at a
409
+ * different feature in its `references`.
410
+ */
411
+ function isRunsOwnRow(row, o, shas) {
412
+ if (byWorkflow(row) !== o.workflow || !(Number(row.ts) >= o.startMs))
413
+ return false;
414
+ if (NOT_A_RUNS_OWN_KIND.has(String(row.kind)))
415
+ return false;
416
+ const sha = row.run?.parentSha;
417
+ if (sha !== undefined)
418
+ return typeof sha === "string" && shas.has(sha);
419
+ const features = (Array.isArray(row.references) ? row.references : [])
420
+ .map(String)
421
+ .filter((r) => FEATURE_REF.test(r));
422
+ const n = /^(\d+)-/.exec(o.fid)?.[1];
423
+ return features.length === 0 || features.some((r) => r === o.fid || r === n);
424
+ }
256
425
  /**
257
426
  * Carry ONLY the run's own record out of a dev / main / detached checkout, which
258
427
  * other sessions and local-only commits share: the `.md` logs it wrote in its log
259
428
  * folder; the lines of that folder's `.jsonl` files its HEAD lacks; and, from the
260
- * shared ledgers, lines its HEAD lacks that are rows of `workflow` at or after
261
- * the run's start (`startMs`). No start known → no shared-ledger row is carried.
429
+ * shared ledgers, lines its HEAD lacks that are this run's rows ({@link isRunsOwnRow}).
430
+ * No start known → no shared-ledger row is carried.
262
431
  */
263
432
  function carryOwnBook(src, dst, o, log) {
264
433
  const rel = logDirRel(o.month, o.fid);
265
434
  const carried = { files: carryLogs(src, dst, rel), lines: new Map() };
266
- const uncommitted = (file) => {
267
- const head = new Set(textLines(git(src, ["show", `HEAD:${file}`]) ?? "").map((l) => l.trim()));
268
- return textLines(fs.readFileSync(path.join(src, file), "utf-8")).filter((l) => !head.has(l.trim()));
269
- };
435
+ // Rows the run appended; on a shared checkout, recorded foreign rows are never carried.
436
+ const rec = activeRecord(src, o.fid);
437
+ const uncommitted = (file) => runRows(src, file, rec);
270
438
  const add = (file, lines) => {
271
439
  const to = path.join(dst, file);
272
440
  const existing = fs.existsSync(to) ? fs.readFileSync(to, "utf-8") : "";
@@ -288,11 +456,11 @@ function carryOwnBook(src, dst, o, log) {
288
456
  log(`no ${o.workflow} start row for ${o.fid} — no shared-ledger row carried`);
289
457
  return carried;
290
458
  }
459
+ const shas = runShas(src, path.join(src, statusRelPath(o.month, o.fid)), o.workflow);
291
460
  for (const file of listed(SHARED_LEDGERS)) {
292
461
  const own = uncommitted(file).filter((l) => {
293
- const parsed = parseJson(l);
294
- const row = parsed.ok ? parsed.value : null;
295
- return row?.workflow === o.workflow && Number(row.ts) >= o.startMs;
462
+ const row = parseObject(l);
463
+ return row !== undefined && isRunsOwnRow(normalize(row), o, shas);
296
464
  });
297
465
  if (own.length > 0)
298
466
  add(file, own);
@@ -305,14 +473,18 @@ function carryOwnBook(src, dst, o, log) {
305
473
  * log identical to the landed copy is removed when untracked, or returns to HEAD
306
474
  * when tracked. A carried ledger loses exactly the carried lines; it returns to
307
475
  * HEAD when that leaves it equal, and an untracked one left empty is removed.
308
- * Anything staged, or a log changed since it landed, stays and is named.
476
+ * Anything staged, or a log changed since it landed, stays and is named. A path
477
+ * the shared-checkout record lists is never reset or removed.
309
478
  */
310
- function handBack(tree, sha, carried, log) {
479
+ function handBack(tree, sha, carried, log, recorded = new Set()) {
311
480
  const back = [];
312
481
  const kept = [];
313
482
  const staged = (rel) => !runGit(tree, ["diff", "--cached", "--quiet", "--", rel]).ok;
314
483
  const tracked = (rel) => runGit(tree, ["ls-files", "--error-unmatch", "--", rel]).ok;
315
484
  for (const rel of carried.files) {
485
+ // A path that was dirty before the run started is not the run's to reset.
486
+ if (recorded.has(rel))
487
+ continue;
316
488
  const abs = path.join(tree, rel);
317
489
  const landed = runGit(tree, ["show", `${sha}:${rel}`]);
318
490
  const same = landed.ok && fs.existsSync(abs) && fs.readFileSync(abs, "utf-8").trim() === landed.stdout;
@@ -451,6 +623,18 @@ async function landFailedRecord(ctx, o) {
451
623
  return stop(EXIT_FLUSH_FAILED, `throwaway checkout failed: ${res.stderr}`);
452
624
  }
453
625
  }
626
+ /**
627
+ * What `handover --push` would sweep into the abort commit besides the run's own
628
+ * logs: tracked files with changes, and untracked files (each one listed, not its folder).
629
+ */
630
+ function strayPaths(tree, logDir) {
631
+ const outside = (out) => (out ?? "").split("\0").filter((p) => p !== "" && p !== logDir && !p.startsWith(`${logDir}/`));
632
+ return {
633
+ // Staged and unstaged changes alike, against HEAD.
634
+ modified: outside(git(tree, ["diff", "--name-only", "-z", "--no-renames", "HEAD"])),
635
+ untracked: outside(git(tree, ["ls-files", "-z", "--others", "--exclude-standard"])),
636
+ };
637
+ }
454
638
  async function handoverVerb(ctx) {
455
639
  const workflow = workflowName(String(ctx.flags.workflow));
456
640
  const fid = String(ctx.flags.fid);
@@ -474,7 +658,14 @@ async function handoverVerb(ctx) {
474
658
  const branch = git(tree, ["branch", "--show-current"]) ?? "";
475
659
  // A dev / main / detached checkout is shared: only the run's own record leaves it.
476
660
  const shared = branch === "" || isSharedBranch(branch);
661
+ if (ctx.flags.listStray === true) {
662
+ if (push || flush || ctx.flags.post === true)
663
+ throw new CommandError(EXIT.USAGE, "--list-stray only lists: drop --push, --flush and --post");
664
+ ctx.emit({ shared, ...strayPaths(tree, logDirRel(month, fid)) });
665
+ return EXIT.OK;
666
+ }
477
667
  let handed;
668
+ const rec = shared && (push || flush) ? activeRecord(tree, fid) : null;
478
669
  if (push && shared) {
479
670
  const r = await landFailedRecord(ctx, { workflow, fid, month, book: tree, shared });
480
671
  if (r.sha !== undefined && r.carried !== undefined)
@@ -485,11 +676,13 @@ async function handoverVerb(ctx) {
485
676
  skipped = r.skipped;
486
677
  }
487
678
  else if (push) {
488
- runGit(tree, ["add", "-A"]);
679
+ const added = addAllButCopied(tree);
680
+ if (!added.ok)
681
+ ctx.log(`abort commit: git add failed: ${added.stderr}`);
489
682
  const made = runGit(tree, ["commit", "-m", `docs(${fid}): ${workflow} aborted bkit [skip ci]`]);
490
683
  if (!made.ok)
491
684
  ctx.log(`abort commit: ${made.stderr || made.stdout}`);
492
- const r = pushBranch(tree, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
685
+ const r = await pushBranch(tree, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
493
686
  if (r.code === EXIT.USE_MCP)
494
687
  return r.code;
495
688
  pushed = r.out.pushed;
@@ -521,19 +714,30 @@ async function handoverVerb(ctx) {
521
714
  bodyFile: artifact,
522
715
  })
523
716
  : null;
524
- if (handed !== undefined)
525
- handBack(tree, handed.sha, handed.carried, ctx.log);
717
+ if (handed !== undefined) {
718
+ handBack(tree, handed.sha, handed.carried, ctx.log, new Set(rec?.paths.map((p) => p.path)));
719
+ }
720
+ // The run is over once its record is handed back: the next run starts a fresh one.
721
+ if (rec !== null)
722
+ removeRecord(tree, fid);
723
+ const tracker = ctx.flags.post === true && comment !== null
724
+ ? await postForVerb(ctx, comment, { fid })
725
+ : undefined;
526
726
  ctx.emit({
527
727
  handover: present ? artifact : null,
528
728
  pushed,
529
729
  ref: pushed ? ref : null,
530
730
  skipped,
531
731
  comment,
732
+ commentFile: commentFileOf(ctx.cwd, comment),
733
+ ...(tracker === undefined ? {} : { tracker }),
532
734
  });
533
735
  return code;
534
736
  }
737
+ /** The row's `by.workflow`, on a row already normalized. */
738
+ const byWorkflow = (r) => r.by?.workflow;
535
739
  /** Rows of a JSONL ledger; malformed lines are skipped, a missing file is empty. */
536
- function ledgerRows(file) {
740
+ export function ledgerRows(file) {
537
741
  if (!fs.existsSync(file))
538
742
  return [];
539
743
  return fs
@@ -562,46 +766,27 @@ const distinctKeys = (rows) => new Set(rows.filter((r) => r.key !== undefined).m
562
766
  * counting the ledger's whole history as this run's.
563
767
  */
564
768
  function ledgerCounts(tree, workflow, startMs) {
565
- const deferrals = ledgerRows(path.join(tree, "docs", "deferrals.jsonl"));
566
- const failures = ledgerRows(path.join(tree, "docs", "failures.jsonl"));
567
- const friction = ledgerRows(path.join(tree, ".bkit", "friction.jsonl"));
568
- const added = (rows) => distinctKeys(rows.filter((r) => r.workflow === workflow && Number(r.ts) >= startMs));
769
+ const read = (file) => ledgerRows(file).map((r) => normalize(r));
770
+ const deferrals = read(path.join(tree, "docs", "deferrals.jsonl"));
771
+ const failures = read(path.join(tree, "docs", "failures.jsonl"));
772
+ const friction = read(path.join(tree, ".bkit", "friction.jsonl"));
773
+ const added = (rows) => startMs === undefined
774
+ ? {}
775
+ : {
776
+ added: distinctKeys(rows.filter((r) => byWorkflow(r) === workflow && Number(r.ts) >= startMs)),
777
+ };
569
778
  return {
570
- deferrals: distinctKeys(deferrals.filter((r) => r.kind === "deferral")),
571
- failures: distinctKeys(failures.filter((r) => r.kind === "failure")),
572
- ...(startMs === undefined
573
- ? {}
574
- : {
575
- frictionAdded: added(friction),
576
- deferralsAdded: added(deferrals),
577
- failuresAdded: added(failures),
578
- }),
579
- };
580
- }
581
- /** `git diff --shortstat` numbers; 0 for anything absent or a range git rejects. */
582
- export function diffStat(cwd, range) {
583
- const out = runGit(cwd, ["diff", "--shortstat", range]).stdout;
584
- const num = (re) => Number(re.exec(out)?.[1] ?? 0);
585
- const linesAdded = num(/(\d+) insertions?\(/);
586
- const linesDeleted = num(/(\d+) deletions?\(/);
587
- return {
588
- linesAdded,
589
- linesDeleted,
590
- linesChanged: linesAdded + linesDeleted,
591
- filesChanged: num(/(\d+) files? changed/),
779
+ deferrals: {
780
+ repo: distinctKeys(deferrals.filter((r) => r.kind === "deferral")),
781
+ ...added(deferrals),
782
+ },
783
+ failures: {
784
+ repo: distinctKeys(failures.filter((r) => r.kind === "failure")),
785
+ ...added(failures),
786
+ },
787
+ friction: added(friction),
592
788
  };
593
789
  }
594
- /** Checklist items (`- [`) across the feature's plan and sub-plans. */
595
- function taskCount(tree, month, fid) {
596
- const dir = path.join(tree, "docs", "plans", month);
597
- if (!fs.existsSync(dir))
598
- return 0;
599
- return fs
600
- .readdirSync(dir)
601
- .filter((f) => f.startsWith(`${fid}-plan`) && f.endsWith(".md"))
602
- .flatMap((f) => fs.readFileSync(path.join(dir, f), "utf-8").split("\n"))
603
- .filter((l) => l.startsWith("- [")).length;
604
- }
605
790
  /** Per-tier coverage from `coverage/{tier}/coverage-summary.json`; undefined when none. */
606
791
  function coverage(tree) {
607
792
  const out = {};
@@ -629,26 +814,95 @@ function lastOfType(events, type, workflow) {
629
814
  .sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0))
630
815
  .at(-1);
631
816
  }
632
- /** Append telemetry rows; best-effort, so a bad path is logged and never fails the close. */
633
- function appendStats(file, rows, log) {
634
- const valid = rows.filter((r) => {
635
- const v = validate(r);
636
- if (!v.ok)
637
- log(`[bkit-telemetry] ${String(r.kind)} row invalid, not written: ${v.reason}`);
638
- return v.ok;
639
- });
640
- if (valid.length === 0)
641
- return false;
817
+ /** Append the close's stats rows; best-effort, so a refused row or a bad path is logged and never fails the close. */
818
+ function appendStats(tree, rows, log) {
642
819
  try {
643
- fs.appendFileSync(file, valid.map((r) => `${telemetryLine(r)}\n`).join(""));
820
+ appendLedgerRows(tree, "stats", rows);
644
821
  return true;
645
822
  }
646
823
  catch (err) {
647
- // Telemetry never gates a close: report the failed append and carry on.
648
- log(`[bkit-telemetry] append failed: ${file} — ${err.message}`);
824
+ // Telemetry never gates a close: report the refused append and carry on.
825
+ log(`[bkit-telemetry] stats rows not written: ${err.message}`);
649
826
  return false;
650
827
  }
651
828
  }
829
+ /**
830
+ * The rows of `workflow`'s `nth` run in `file` (the last when omitted), in time order;
831
+ * unreadable lines skipped. Runs split as `fold` splits them: rows ordered by `at`, file
832
+ * order on a tie, each new `workflow-started` opening a run, so a previous run's rows in
833
+ * the same second as this run's start stay with the previous run.
834
+ */
835
+ function runRowsOf(file, workflow, nth = -1) {
836
+ const at = (r) => (typeof r["at"] === "string" ? r["at"] : "");
837
+ const ordered = parseRows(fs.readFileSync(file, "utf-8"))
838
+ .map((r, i) => ({ r, i }))
839
+ .filter(({ r }) => r.workflow === workflow)
840
+ .sort((a, b) => (at(a.r) < at(b.r) ? -1 : at(a.r) > at(b.r) ? 1 : a.i - b.i))
841
+ .map(({ r }) => r);
842
+ const runs = [];
843
+ const starts = new Set();
844
+ for (const r of ordered) {
845
+ if (r.type === "workflow-started" && !starts.has(at(r))) {
846
+ starts.add(at(r));
847
+ runs.push([]);
848
+ }
849
+ else if (runs.length === 0 && r.type === "step-done") {
850
+ runs.push([]);
851
+ }
852
+ runs.at(-1)?.push(r);
853
+ }
854
+ return runs.at(nth) ?? [];
855
+ }
856
+ /** The contract of `workflow`, derived from its shipped markdown rendered for the tracker `cwd` is configured with. */
857
+ const contractOf = (workflow, cwd) => deriveContract(fs.readFileSync(path.join(getWorkflowsRoot(), `bkit-${workflow}.md`), "utf-8"), workflow, readIssueTracker(cwd));
858
+ /**
859
+ * Appends the close's `completeness` row for `workflow`'s last run. Advisory:
860
+ * a failure of the check or of the write is logged in one line and never fails the close.
861
+ * `journalSuspect` is set here only: the closing engine journals itself.
862
+ */
863
+ function writeCompletenessRow(file, workflow, parentSha, log) {
864
+ try {
865
+ const verdict = checkCompleteness(runRowsOf(file, workflow), contractOf(workflow, path.dirname(file)), {
866
+ journalSuspect: true,
867
+ });
868
+ const row = { type: "completeness", ...verdict, at: statusTimestamp(), parentSha };
869
+ fs.appendFileSync(file, appendLine(row));
870
+ if (verdict.journalSuspect) {
871
+ log("[bkit-telemetry] journal looks dead at close: no engine-call rows for this run; the completeness verdict cannot be trusted");
872
+ }
873
+ }
874
+ catch (err) {
875
+ // The check is advisory: report the failure and close without the row.
876
+ log(`[bkit-telemetry] completeness row not written: ${err.message}`);
877
+ }
878
+ }
879
+ /**
880
+ * The warning line for the run before the one being started (or resumed) when that run
881
+ * was holey; `null` when it is clean, absent or unreadable. Never throws.
882
+ */
883
+ function previousRunWarning(file, resumed) {
884
+ try {
885
+ const events = readStatusEvents(file);
886
+ const runs = fold(events);
887
+ const at = runs.length - (resumed ? 2 : 1);
888
+ const prev = runs[at];
889
+ if (prev === undefined)
890
+ return null;
891
+ const number = runs.slice(0, at + 1).filter((r) => r.workflow === prev.workflow).length;
892
+ const own = runRowsOf(file, prev.workflow, number - 1);
893
+ const { verdict } = readCompleteness(own, contractOf(prev.workflow, path.dirname(file)));
894
+ if (!verdict.holey)
895
+ return null;
896
+ const closed = own.filter((e) => e.type === "workflow-done").at(-1)?.["at"] ?? "never";
897
+ return (`[bkit-workflows] previous run (${prev.workflow} run ${number}, closed ${closed}) was incomplete: ` +
898
+ `${verdict.evidenceHoles.length} evidence hole(s), ${verdict.stepHoles.length} step hole(s); ` +
899
+ `see: bkit completeness check --workflow=${prev.workflow} --file=${path.relative(process.cwd(), file) || file}`);
900
+ }
901
+ catch {
902
+ // Advisory: an unreadable run or checker failure degrades to no warning.
903
+ return null;
904
+ }
905
+ }
652
906
  /** Markdown link per feature doc and per log of this workflow, as on `ref`. */
653
907
  export function artifactLinks(root, ref, month, fid, workflow, ownerRepo) {
654
908
  const list = (dir) => (git(root, ["ls-tree", "-r", "--name-only", ref, "--", dir]) ?? "").split("\n").filter(Boolean);
@@ -679,11 +933,25 @@ function closeComment(cwd, outbox, o) {
679
933
  sections,
680
934
  });
681
935
  }
936
+ /** `--ending` / `--publish` of the close verb, validated. */
937
+ function closeEnding(f) {
938
+ const ending = str(f.ending);
939
+ if (ending !== undefined && ending !== "done" && ending !== "held")
940
+ throw new CommandError(EXIT.USAGE, `--ending must be done or held, got ${ending}`);
941
+ const publish = str(f.publish);
942
+ if (publish !== undefined && publish !== "true" && publish !== "false")
943
+ throw new CommandError(EXIT.USAGE, `--publish must be true or false, got ${publish}`);
944
+ return {
945
+ ...(ending === undefined ? {} : { ending }),
946
+ ...(publish === undefined ? {} : { publish: publish === "true" }),
947
+ };
948
+ }
682
949
  /**
683
950
  * Grade compliance, append the workflow-done row (and, with `recordStep`, the
684
951
  * close step's row first), the counter and outcome telemetry rows, and build the
685
952
  * report and artifact links; with `outbox`, write them for the close comment; with
686
- * `message`, commit everything (`git add -A`) in the tree.
953
+ * `message`, commit everything (`git add -A`, minus the `bkit.workflows.worktree.copy` entries) in the tree, or, in an in-place run
954
+ * on a shared branch, only the run's own paths.
687
955
  */
688
956
  export function closeWorkflow(cwd, o, log) {
689
957
  const workflow = workflowName(o.workflow);
@@ -691,67 +959,94 @@ export function closeWorkflow(cwd, o, log) {
691
959
  const events = readStatusEvents(where.status);
692
960
  if (o.squashSha !== undefined && !/^[0-9a-f]{7,40}$/.test(o.squashSha))
693
961
  throw new CommandError(EXIT.USAGE, `--squash-sha "${o.squashSha}" is not a commit sha`);
694
- // Graded first, so the report below carries this run's grade.
695
- const violations = gradeCompliance(where.tree, workflow, log, o.squashSha);
962
+ // An in-place run on a shared branch commits its own paths only; a refusal
963
+ // comes before any row is appended, so the re-run after the human's fix writes each row once.
964
+ const rec = o.message === undefined ? null : activeRecord(where.tree, o.fid);
965
+ if (o.message !== undefined)
966
+ requireRecordOnShared(where.tree, workflow, rec);
967
+ if (rec !== null)
968
+ ownSet(where.tree, rec);
696
969
  const step = `${workflow}-close-workflow`;
970
+ // The run's join key: every row of this run carries HEAD at close as `run.parentSha`.
971
+ const parentSha = headSha(where.tree);
972
+ // Graded first, so the report below carries this run's grade.
973
+ const violations = gradeCompliance(where.tree, workflow, log, o.squashSha, { parentSha, step });
974
+ let progressLine;
697
975
  if (o.recordStep === true) {
698
- writeStepRow(where.tree, { file: where.status, workflow, step, artifacts: [], commit: "none" }, log);
976
+ const written = writeStepRow(where.tree, { file: where.status, workflow, step, artifacts: [], commit: "none" }, log);
977
+ progressLine = written.progressLine;
699
978
  }
700
- const row = { type: "workflow-done", workflow, at: statusTimestamp() };
979
+ writeCompletenessRow(where.status, workflow, parentSha, log);
980
+ const endAt = statusTimestamp();
981
+ const ending = o.ending ?? "done";
982
+ const row = {
983
+ type: "workflow-done",
984
+ workflow,
985
+ at: endAt,
986
+ parentSha,
987
+ ending,
988
+ ...(o.publish === undefined ? {} : { publish: o.publish }),
989
+ };
701
990
  fs.appendFileSync(where.status, appendLine(row));
702
991
  const repo = resolveRepoSlug(where.root) || "unknown/repo";
703
- const bkitVersion = readBkitVersion(path.join(where.root, ".bkit", "version"))?.pinnedVersion || "unknown";
704
- const parentSha = headSha(where.tree);
705
992
  const started = lastOfType(events, "workflow-started", workflow);
706
993
  const startAt = started?.at;
707
994
  const startMs = startAt ? Date.parse(startAt) : NaN;
708
995
  const startKnown = Number.isFinite(startMs) ? startMs : undefined;
709
- const planSource = events
710
- .filter((e) => e.type === "workflow-meta" &&
711
- e.workflow === workflow &&
712
- (startAt === undefined || e.at >= startAt) &&
713
- e.planSource)
714
- .at(-1);
996
+ const runRowsOf = startAt === undefined ? [] : runStatusRows(readStatusEvents(where.status), workflow, startAt);
715
997
  const base = typeof started?.parentSha === "string" ? started.parentSha : "";
716
- const range = o.squashSha
717
- ? `${o.squashSha}^..${o.squashSha}`
718
- : base
719
- ? `${base}..HEAD`
720
- : "origin/dev...HEAD";
721
- const durationSeconds = startKnown === undefined ? 0 : Math.max(0, Math.floor((Date.now() - startKnown) / 1000));
998
+ const lines = o.squashSha
999
+ ? runLines(where.tree, `${o.squashSha}^`, o.squashSha)
1000
+ : runLines(where.tree, base, parentSha);
722
1001
  const startedRows = new Set(events.filter((e) => e.type === "workflow-started" && e.workflow === workflow).map((e) => e.at)).size;
723
- const ts = Date.now();
1002
+ const by = { workflow, step };
724
1003
  const counterRow = {
725
- ts,
726
1004
  kind: "counter",
727
- workflow,
728
- repo,
729
- bkitVersion,
730
- step,
731
- counterName: `${workflow.toUpperCase()}_ATTEMPT`,
732
- counterValue: Math.max(1, startedRows),
733
- counterSource: "shell-bus",
734
- parentSha,
1005
+ by,
1006
+ run: { parentSha },
1007
+ counter: {
1008
+ name: `${workflow.toUpperCase()}_ATTEMPT`,
1009
+ value: Math.max(1, startedRows),
1010
+ source: "shell-bus",
1011
+ },
735
1012
  };
736
1013
  const cov = workflow === "ship" ? coverage(where.tree) : undefined;
1014
+ const ci = ciList(runRowsOf);
1015
+ const plan = ["plan", "build", "ship"].includes(workflow)
1016
+ ? planBlock(where.tree, where.month, o.fid, events)
1017
+ : undefined;
1018
+ const endMs = Date.parse(endAt);
1019
+ /** This run's `docs/deferrals.jsonl` rows; none when its start is unknown. */
1020
+ const runDeferrals = () => startKnown === undefined
1021
+ ? []
1022
+ : ledgerRows(path.join(where.tree, "docs", "deferrals.jsonl"))
1023
+ .map((r) => normalize(r))
1024
+ .filter((r) => byWorkflow(r) === workflow && Number(r.ts) >= startKnown);
1025
+ const context = startKnown === undefined
1026
+ ? undefined
1027
+ : agentContextBlock(startKnown, endMs, claudeTranscripts(process.env, os.homedir()), runChats(runRowsOf));
737
1028
  const outcomeRow = {
738
- ts: ts + 1,
739
1029
  kind: "outcome",
740
- workflow,
741
- repo,
742
- bkitVersion,
743
- step,
744
- parentSha,
745
- ...(o.prNumber === undefined ? {} : { prNumber: o.prNumber }),
746
- ...diffStat(where.tree, range),
747
- taskCount: taskCount(where.tree, where.month, o.fid),
748
- durationSeconds,
749
- ...ledgerCounts(where.tree, workflow, startKnown),
750
- ...(planSource?.planSource ? { planSource: planSource.planSource } : {}),
751
- ...(cov ? { coverage: cov } : {}),
1030
+ by,
1031
+ run: { parentSha, ...(o.prNumber === undefined ? {} : { pr: o.prNumber }) },
1032
+ time: startKnown === undefined ? null : timeBlock(startKnown, Math.max(startKnown, endMs)),
1033
+ ending,
1034
+ ...(o.publish === undefined ? {} : { publish: o.publish }),
1035
+ lines,
1036
+ ...(runRowsOf.length > 0 ? { steps: stepsBlock(runRowsOf) } : {}),
1037
+ ...(ci.length > 0 ? { ci } : {}),
1038
+ ledgers: ledgerCounts(where.tree, workflow, startKnown),
1039
+ ...(plan === undefined ? {} : { plan }),
1040
+ ...(workflow === "build"
1041
+ ? {
1042
+ build: buildBlock(runRowsOf, planFiles(where.tree, where.month, o.fid), runDeferrals()),
1043
+ }
1044
+ : {}),
1045
+ ...(context === undefined ? {} : { context }),
1046
+ ...(cov ? { ship: { coverage: cov } } : {}),
752
1047
  };
753
1048
  const stats = path.join(where.tree, ".bkit", "stats.jsonl");
754
- const telemetryWritten = appendStats(stats, [counterRow, outcomeRow], log);
1049
+ const telemetryWritten = appendStats(where.tree, [counterRow, outcomeRow], log);
755
1050
  const report = fs.existsSync(stats)
756
1051
  ? workflowTelemetry(foldFrom([stats]), workflow).lines
757
1052
  : ["[bkit-telemetry] stats.jsonl not found — no telemetry rows yet"];
@@ -788,16 +1083,24 @@ export function closeWorkflow(cwd, o, log) {
788
1083
  message += " bkit [verbose ci]";
789
1084
  if ((o.labels ?? []).includes(AUTO_LABEL))
790
1085
  message += AUTO_ROUTE_SUFFIX;
791
- const add = runGit(where.tree, ["add", "-A"]);
792
- const made = add.ok ? runGit(where.tree, ["commit", "--allow-empty", "-m", message]) : add;
793
- if (!made.ok)
794
- throw new CommandError(EXIT.NO, `close commit failed: ${made.stderr || made.stdout}`);
1086
+ if (rec !== null) {
1087
+ const made = ownPathCommit(where.tree, rec, message, { allowEmpty: true });
1088
+ if (!made.ok)
1089
+ throw new CommandError(EXIT.NO, `close commit failed: ${made.error}`);
1090
+ }
1091
+ else {
1092
+ const add = addAllButCopied(where.tree);
1093
+ const made = add.ok ? runGit(where.tree, ["commit", "--allow-empty", "-m", message]) : add;
1094
+ if (!made.ok)
1095
+ throw new CommandError(EXIT.NO, `close commit failed: ${made.stderr || made.stdout}`);
1096
+ }
795
1097
  commit = headSha(where.tree);
796
1098
  }
797
1099
  return {
798
1100
  row,
799
- counterRow: validate(counterRow).ok ? counterRow : null,
800
- outcomeRow: validate(outcomeRow).ok ? outcomeRow : null,
1101
+ // The rows as drafted; the ledger copies add the top section `ledgers append` fills.
1102
+ counterRow: telemetryWritten ? counterRow : null,
1103
+ outcomeRow: telemetryWritten ? outcomeRow : null,
801
1104
  telemetryWritten,
802
1105
  compliance: violations === null ? null : violations.length,
803
1106
  report,
@@ -808,6 +1111,7 @@ export function closeWorkflow(cwd, o, log) {
808
1111
  comment,
809
1112
  roadmapFoldNeeded: true,
810
1113
  featureStatus: FEATURE_STATUS[workflow],
1114
+ ...(progressLine === undefined ? {} : { progressLine }),
811
1115
  };
812
1116
  }
813
1117
  /**
@@ -847,8 +1151,8 @@ function closePr(ctx, dir, fid, subject) {
847
1151
  * checkout): the close rows there, then ONE `docs({fid}): ship DONE bkit [skip ci]`
848
1152
  * commit built in a throwaway origin/dev checkout carrying the run's book and
849
1153
  * landed on dev — a refused push publishes it through a `ship-close/{fid}` PR.
850
- * Only a close that landed (or opened its PR) releases the workflow lock; once
851
- * the close is on dev, the feature worktree and `branch` are removed. A close
1154
+ * Once the close is on dev, the feature worktree and `branch` are removed; then
1155
+ * a close that landed (or opened its PR) releases the workflow lock. A close
852
1156
  * that did not land keeps the lock for the Failure Path.
853
1157
  */
854
1158
  async function shipClose(ctx, o, token) {
@@ -916,22 +1220,14 @@ async function shipClose(ctx, o, token) {
916
1220
  ctx.log(`throwaway checkout failed: ${res.stderr} — ${kept}`);
917
1221
  return { code: EXIT_FLUSH_FAILED, out: null };
918
1222
  }
919
- const released = releaseLock(workflowLockPath(root, month, o.fid), {
920
- workflow: "ship",
921
- fid: o.fid,
922
- token,
923
- });
924
- if (released.removeFailed) {
925
- ctx.log("Lock removal failed");
926
- return { code: EXIT_FLUSH_FAILED, out: null };
927
- }
928
- // The book is on dev only once the close landed or its PR merged.
1223
+ // The book is on dev only once the close landed or its PR merged. The worktree
1224
+ // goes while the lock is still held, so no run of this FID resumes into it.
929
1225
  let worktree = null;
930
1226
  if (landed.via === "close-pr-open") {
931
1227
  ctx.log(`close PR not merged — ${kept} until it is`);
932
1228
  }
933
1229
  else {
934
- if (landed.via === "close-pr" && !runGit(root, ["fetch", "origin", DEV]).ok)
1230
+ if (landed.via === "close-pr" && !fetchDev(root).ok)
935
1231
  ctx.log(`fetch of dev after the close PR failed — origin/${DEV} is stale until the next fetch`);
936
1232
  try {
937
1233
  worktree = removeWorktree(root, o.fid, o.branch, ctx.log);
@@ -940,27 +1236,20 @@ async function shipClose(ctx, o, token) {
940
1236
  ctx.log(`${err.message} — remove ${book} by hand`);
941
1237
  }
942
1238
  }
1239
+ const released = releaseLock(workflowLockPath(root, month, o.fid), {
1240
+ workflow: "ship",
1241
+ fid: o.fid,
1242
+ token,
1243
+ });
1244
+ if (released.removeFailed) {
1245
+ ctx.log("Lock removal failed");
1246
+ return { code: EXIT_FLUSH_FAILED, out: null };
1247
+ }
943
1248
  return { code: EXIT.OK, out: { ...out, landed, worktree } };
944
1249
  }
945
1250
  // ---------------------------------------------------------------------------
946
1251
  // promote
947
1252
  // ---------------------------------------------------------------------------
948
- /** The highest `{workflow}-v{N}-*.md` draft (sub-plan children `-v{N}-{k}.md` excluded), or null. */
949
- export function highestVersion(dir, workflow) {
950
- if (!fs.existsSync(dir))
951
- return null;
952
- const re = new RegExp(`^${workflow}-v([0-9]+)-(.+)\\.md$`);
953
- let best = null;
954
- for (const f of fs.readdirSync(dir).sort()) {
955
- const m = re.exec(f);
956
- if (!m || /^[0-9]+$/.test(m[2]))
957
- continue;
958
- const n = Number(m[1]);
959
- if (best === null || n > best.n)
960
- best = { file: f, n };
961
- }
962
- return best;
963
- }
964
1253
  /** Stamp `file`'s anchor when a base commit is known (plan: with its design's own anchor; both: the bkit release). */
965
1254
  function stamp(cwd, file, baseSha, design) {
966
1255
  if (baseSha === "")
@@ -989,7 +1278,7 @@ function promoteVerb(ctx) {
989
1278
  }
990
1279
  const final = path.join(logs, best.file);
991
1280
  if (ctx.flags.resolve === true) {
992
- ctx.emit({ final, canonical: null, archived: [], subPlans: [], baseSha: null });
1281
+ ctx.emit({ final, canonical: null, archived: [], baseSha: null });
993
1282
  return EXIT.OK;
994
1283
  }
995
1284
  // The base commit Step 2 recorded on the runtime-resolved row.
@@ -1007,13 +1296,7 @@ function promoteVerb(ctx) {
1007
1296
  const bucket = path.join("docs", "plans", month);
1008
1297
  const canonical = path.join(bucket, `${fid}-${workflow}.md`);
1009
1298
  stamp(ctx.cwd, final, baseSha, design);
1010
- const children = workflow === "plan"
1011
- ? fs
1012
- .readdirSync(path.resolve(ctx.cwd, logs))
1013
- .filter((f) => new RegExp(`^plan-v${best.n}-[0-9]+\\.md$`).test(f))
1014
- .sort()
1015
- : [];
1016
- // A changed canonical moves to archive/ first — plan moves the whole set under one timestamp.
1299
+ // A changed canonical moves to archive/ first.
1017
1300
  const archived = [];
1018
1301
  const canonicalAbs = path.resolve(ctx.cwd, canonical);
1019
1302
  if (fs.existsSync(canonicalAbs) &&
@@ -1024,42 +1307,112 @@ function promoteVerb(ctx) {
1024
1307
  .replace(/\.\d+Z$/, "Z");
1025
1308
  const archive = path.join(bucket, "archive");
1026
1309
  fs.mkdirSync(path.resolve(ctx.cwd, archive), { recursive: true });
1027
- const set = fs
1028
- .readdirSync(path.resolve(ctx.cwd, bucket))
1029
- .filter((f) => workflow === "plan"
1030
- ? f === `${fid}-plan.md` || new RegExp(`^${fid}-plan-[0-9]+\\.md$`).test(f)
1031
- : f === `${fid}-design.md`);
1032
- for (const f of set) {
1033
- const to = path.join(archive, `${ts}-${f}`);
1034
- fs.renameSync(path.resolve(ctx.cwd, bucket, f), path.resolve(ctx.cwd, to));
1035
- archived.push(to);
1036
- }
1310
+ const to = path.join(archive, `${ts}-${fid}-${workflow}.md`);
1311
+ fs.renameSync(canonicalAbs, path.resolve(ctx.cwd, to));
1312
+ archived.push(to);
1037
1313
  }
1038
1314
  fs.mkdirSync(path.resolve(ctx.cwd, bucket), { recursive: true });
1039
1315
  fs.copyFileSync(path.resolve(ctx.cwd, final), canonicalAbs);
1040
- const subPlans = [];
1041
- for (const child of children) {
1042
- const k = /-([0-9]+)\.md$/.exec(child)[1];
1043
- stamp(ctx.cwd, path.join(logs, child), baseSha, design);
1044
- const to = path.join(bucket, `${fid}-plan-${k}.md`);
1045
- fs.copyFileSync(path.resolve(ctx.cwd, logs, child), path.resolve(ctx.cwd, to));
1046
- subPlans.push(to);
1047
- }
1048
- if (workflow === "plan") {
1049
- // Working names in the copies become the canonical names.
1050
- for (const f of [canonical, ...subPlans]) {
1051
- const abs = path.resolve(ctx.cwd, f);
1052
- fs.writeFileSync(abs, fs
1053
- .readFileSync(abs, "utf-8")
1054
- .replace(/plan-v[0-9]+-split\.md/g, `${fid}-plan.md`)
1055
- .replace(/plan-v[0-9]+-([0-9]+)\.md/g, `${fid}-plan-$1.md`));
1056
- }
1057
- }
1058
1316
  if (fs.statSync(canonicalAbs).size === 0) {
1059
1317
  ctx.log(`canonical empty: ${canonical}`);
1060
1318
  return EXIT_NO_VERSION;
1061
1319
  }
1062
- ctx.emit({ final, canonical, archived, subPlans, baseSha: baseSha || null });
1320
+ ctx.emit({ final, canonical, archived, baseSha: baseSha || null });
1321
+ return EXIT.OK;
1322
+ }
1323
+ // ---------------------------------------------------------------------------
1324
+ // summary
1325
+ // ---------------------------------------------------------------------------
1326
+ /** ship: the PR's size from `gh pr view`; undefined (logged) when gh cannot answer. */
1327
+ function prSize(cwd, pr, log) {
1328
+ const res = runGh(cwd, ["pr", "view", String(pr), "--json", "additions,deletions,changedFiles"]);
1329
+ const parsed = res.ok ? parseJson(res.stdout) : undefined;
1330
+ const v = parsed?.ok === true ? parsed.value : undefined;
1331
+ if (typeof v?.additions !== "number" ||
1332
+ typeof v.deletions !== "number" ||
1333
+ typeof v.changedFiles !== "number") {
1334
+ log(`gh pr view ${pr} gave no size; the summary leaves the PR line out`);
1335
+ return undefined;
1336
+ }
1337
+ return {
1338
+ number: pr,
1339
+ additions: v.additions,
1340
+ deletions: v.deletions,
1341
+ changedFiles: v.changedFiles,
1342
+ };
1343
+ }
1344
+ function summaryVerb(ctx) {
1345
+ const workflow = String(ctx.flags.workflow);
1346
+ if (!SUMMARY_WORKFLOWS.includes(workflow))
1347
+ throw new CommandError(EXIT.USAGE, `--workflow must be ${SUMMARY_WORKFLOWS.join(", ")}`);
1348
+ const file = path.resolve(ctx.cwd, String(ctx.flags.file));
1349
+ const logDir = path.dirname(file);
1350
+ const fid = path.basename(logDir);
1351
+ const month = path.basename(path.dirname(path.dirname(logDir)));
1352
+ const tree = path.resolve(logDir, "..", "..", "..", "..", "..");
1353
+ if (!/^[0-9]{6}$/.test(month) || path.join(tree, logDirRel(month, fid)) !== logDir)
1354
+ throw new CommandError(EXIT.USAGE, `--file must be docs/plans/{YYYYMM}/logs/{FID}/status.jsonl, got ${file}`);
1355
+ const events = readStatusEvents(file);
1356
+ const started = lastOfType(events, "workflow-started", workflow);
1357
+ if (started === undefined)
1358
+ throw new CommandError(EXIT_NO_RUN, `${file} has no ${workflow} run (no workflow-started row)`);
1359
+ const rows = runStatusRows(events, workflow, started.at);
1360
+ const startMs = Date.parse(started.at);
1361
+ const rel = (abs) => path.relative(tree, abs).split(path.sep).join("/");
1362
+ const given = list(ctx.flags.plan).map((p) => path.resolve(ctx.cwd, p));
1363
+ const plans = given.length > 0 ? given : workflow === "build" ? planFiles(tree, month, fid) : [];
1364
+ const read = (r) => {
1365
+ const abs = path.resolve(tree, r);
1366
+ return fs.existsSync(abs) && fs.statSync(abs).isFile() ? fs.readFileSync(abs, "utf-8") : null;
1367
+ };
1368
+ const deferralHistory = ledgerRows(path.join(tree, "docs", "deferrals.jsonl")).map((r) => normalize(r));
1369
+ const runDeferralKeys = new Set(deferralHistory
1370
+ .filter((r) => isRunsOwnRow(r, { fid, workflow, startMs }, new Set()))
1371
+ .map((r) => r.key));
1372
+ const currentDeferrals = new Map(deferralHistory.sort((a, b) => compareTs({ ts: a.ts }, { ts: b.ts })).map((r) => [r.key, r]));
1373
+ const deferrals = [...currentDeferrals.values()].filter((r) => runDeferralKeys.has(r.key));
1374
+ const organisedPath = path.join(logDir, "design-v3-organised.md");
1375
+ const organised = workflow === "design" && fs.existsSync(organisedPath)
1376
+ ? fs.readFileSync(organisedPath, "utf-8")
1377
+ : undefined;
1378
+ const prNumber = positiveInt(ctx.flags.pr, "pr");
1379
+ const publishFlag = str(ctx.flags.publish);
1380
+ if (publishFlag !== undefined && publishFlag !== "true" && publishFlag !== "false")
1381
+ throw new CommandError(EXIT.USAGE, `--publish must be true or false, got ${publishFlag}`);
1382
+ const summary = buildSummary({
1383
+ root: tree,
1384
+ publish: publishFlag === undefined ? undefined : publishFlag === "true",
1385
+ workflow: workflow,
1386
+ fid,
1387
+ ref: refOf(fid, readIssueTracker(tree)),
1388
+ rows,
1389
+ plans: plans.map((p) => ({ path: rel(p), text: fs.readFileSync(p, "utf-8") })),
1390
+ deferrals,
1391
+ deferralsAdded: deferrals.filter((r) => r.status !== "CLOSED").length,
1392
+ decisionFiles: (workflow === "build" || workflow === "ship") && fs.existsSync(logDir)
1393
+ ? fs
1394
+ .readdirSync(logDir)
1395
+ .filter((f) => /^build-decision-.*\.md$/.test(f))
1396
+ .sort()
1397
+ .map((f) => rel(path.join(logDir, f)))
1398
+ : [],
1399
+ read,
1400
+ workstreams: organised === undefined ? undefined : parseWorkstreams(organised),
1401
+ suggestedPlans: organised === undefined ? undefined : parsePlans(organised),
1402
+ organised,
1403
+ pr: workflow === "ship" && prNumber !== undefined
1404
+ ? prSize(ctx.cwd, prNumber, ctx.log)
1405
+ : undefined,
1406
+ });
1407
+ const out = path.join(logDir, `${workflow}-summary.md`);
1408
+ fs.writeFileSync(out, summary.markdown);
1409
+ ctx.emit({
1410
+ verdict: summary.verdict,
1411
+ failures: summary.failures,
1412
+ reasons: summary.reasons,
1413
+ file: rel(out),
1414
+ nextStep: summary.nextStep,
1415
+ });
1063
1416
  return EXIT.OK;
1064
1417
  }
1065
1418
  // ---------------------------------------------------------------------------
@@ -1089,13 +1442,228 @@ const OWNER_REPO_FLAG = {
1089
1442
  const COMMENT_FLAGS = [
1090
1443
  { name: "number", type: "string", help: "step number: print the close comment (needs --outbox)" },
1091
1444
  { name: "title", type: "string", help: "step title of the close comment" },
1445
+ {
1446
+ ...POST_FLAG,
1447
+ 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`",
1448
+ },
1092
1449
  ];
1450
+ const SESSION_DIR_FLAG = {
1451
+ name: "session-dir",
1452
+ type: "string",
1453
+ help: "the run's session folder (`repo info` sessionDir): deleted once this run ends",
1454
+ };
1455
+ const SESSION_REMOVED_OUTPUT = "with --session-dir: the folder was deleted (false: not under <git common dir>/bkit-outbox/sessions/, kept)";
1456
+ /**
1457
+ * `--session-dir`: delete the run's session folder. Only a folder directly under
1458
+ * `<git common dir>/bkit-outbox/sessions/` is deleted; any other path is kept and logged.
1459
+ */
1460
+ function sessionRemoval(ctx) {
1461
+ const given = str(ctx.flags.sessionDir);
1462
+ if (!given)
1463
+ return {};
1464
+ const common = git(ctx.cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
1465
+ const real = (p) => (fs.existsSync(p) ? fs.realpathSync(p) : p);
1466
+ const sessions = common === null ? null : real(path.join(common, "bkit-outbox", "sessions"));
1467
+ const abs = path.resolve(ctx.cwd, given);
1468
+ if (sessions === null || real(path.dirname(abs)) !== sessions) {
1469
+ ctx.log(`--session-dir ${given} is not a session folder under ${sessions ?? "the outbox"}; kept`);
1470
+ return { sessionRemoved: false };
1471
+ }
1472
+ fs.rmSync(abs, { recursive: true, force: true });
1473
+ return { sessionRemoved: true };
1474
+ }
1475
+ const PLAIN_ENGLISH_REPLY = "Would you like me to explain any of this in plain English? Then write 'yes, explain in plain english'.";
1476
+ /**
1477
+ * `--final-return`: the run's last message, read up front (the close may remove the tree
1478
+ * holding the summary, and `--session-dir` the issue facts). Tips are added at print time.
1479
+ */
1480
+ function finalReturnParts(ctx, fid) {
1481
+ if (ctx.flags.finalReturn !== true)
1482
+ return null;
1483
+ const summaryFile = str(ctx.flags.summaryFile);
1484
+ const summary = str(ctx.flags.summary);
1485
+ if (summaryFile !== undefined && summary !== undefined)
1486
+ throw new CommandError(EXIT.USAGE, "give --summary-file or --summary, not both");
1487
+ if (!summaryFile && !summary)
1488
+ throw new CommandError(EXIT.USAGE, "--final-return needs --summary-file or --summary");
1489
+ const parts = [];
1490
+ const warning = str(ctx.flags.warning);
1491
+ if (warning)
1492
+ parts.push(warning);
1493
+ parts.push(summary ? summaryOrMissing(ctx, summary) : inputText(ctx.cwd, summaryFile, "summary-file"));
1494
+ parts.push(...list(ctx.flags.line));
1495
+ const session = str(ctx.flags.sessionDir);
1496
+ const factsFile = session ? path.resolve(ctx.cwd, session, "issue-facts.json") : "";
1497
+ if (factsFile && fs.existsSync(factsFile)) {
1498
+ const parsed = parseJson(fs.readFileSync(factsFile, "utf-8"));
1499
+ const facts = (parsed.ok ? parsed.value : {});
1500
+ const t = trackerTarget(ctx.cwd, { fid });
1501
+ const title = typeof facts.title === "string" ? facts.title : "";
1502
+ const label = [issueRef(t.issue, t.tracker), title].filter(Boolean).join(" ");
1503
+ if (typeof facts.url === "string" && facts.url)
1504
+ parts.push(`[${label}](${facts.url})`);
1505
+ }
1506
+ parts.push("## Suggested Replies", ...list(ctx.flags.suggest), PLAIN_ENGLISH_REPLY);
1507
+ return parts;
1508
+ }
1509
+ /**
1510
+ * `--summary`: the summary file's text, or the `--summary-missing` line when the
1511
+ * file is absent; with `--outbox`, the text is also kept there under the file's
1512
+ * name, outside the tree the close may remove.
1513
+ */
1514
+ function summaryOrMissing(ctx, rel) {
1515
+ const missing = str(ctx.flags.summaryMissing);
1516
+ if (!missing)
1517
+ throw new CommandError(EXIT.USAGE, "--summary needs --summary-missing");
1518
+ const abs = path.resolve(ctx.cwd, rel);
1519
+ const text = fs.existsSync(abs) ? fs.readFileSync(abs, "utf-8").replace(/\s+$/, "") : missing;
1520
+ const outbox = str(ctx.flags.outbox);
1521
+ if (outbox) {
1522
+ const dir = path.resolve(ctx.cwd, outbox);
1523
+ fs.mkdirSync(dir, { recursive: true });
1524
+ fs.writeFileSync(path.join(dir, path.basename(abs)), `${text}\n`);
1525
+ }
1526
+ return text;
1527
+ }
1528
+ function finalReturnText(ctx, workflow, parts) {
1529
+ if (parts === null)
1530
+ return {};
1531
+ const tips = tipsText(false, workflow, ctx.cwd);
1532
+ return { finalReturn: [...parts, ...(tips ? ["## bkit Tips", tips] : [])].join("\n\n") };
1533
+ }
1534
+ // ---------------------------------------------------------------------------
1535
+ // input
1536
+ // ---------------------------------------------------------------------------
1537
+ /** A required input file's text, trailing newlines dropped; missing exits EXIT_NO_INPUT. */
1538
+ function inputText(cwd, rel, flag) {
1539
+ const abs = path.resolve(cwd, rel);
1540
+ if (!fs.existsSync(abs))
1541
+ throw new CommandError(EXIT_NO_INPUT, `--${flag} ${rel} does not exist`);
1542
+ return fs.readFileSync(abs, "utf-8").replace(/\s+$/, "");
1543
+ }
1544
+ /** The run's issue parts from `issues fetch`'s files, oldest first; none for a run with no issue. */
1545
+ function inputIssueParts(ctx) {
1546
+ const descFile = str(ctx.flags.descriptionFile);
1547
+ const commentsFile = str(ctx.flags.commentsFile);
1548
+ const description = descFile ? inputText(ctx.cwd, descFile, "description-file") : "";
1549
+ let comments = [];
1550
+ if (commentsFile) {
1551
+ const parsed = parseJson(inputText(ctx.cwd, commentsFile, "comments-file"));
1552
+ const list = parsed.ok ? parseComments(parsed.value) : null;
1553
+ if (list === null)
1554
+ throw new CommandError(EXIT_NO_INPUT, `--comments-file ${commentsFile} is not a list of comments`);
1555
+ comments = sortOldestFirst(list).comments;
1556
+ }
1557
+ return issueParts(description, comments);
1558
+ }
1559
+ /** An ISO-8601 time in UTC, or undefined when it does not parse. */
1560
+ function utc(at) {
1561
+ const t = at === undefined ? NaN : Date.parse(at);
1562
+ return Number.isNaN(t) ? undefined : new Date(t).toISOString();
1563
+ }
1564
+ /**
1565
+ * When a design or plan file last changed: the author date of its last commit (a
1566
+ * rebase keeps it, unlike the committer date), or undefined (newer than any commit) when the file
1567
+ * has uncommitted changes or no commit.
1568
+ */
1569
+ function committedAt(cwd, rel) {
1570
+ if ((git(cwd, ["status", "--porcelain", "--", rel]) ?? "") !== "")
1571
+ return undefined;
1572
+ return utc(git(cwd, ["log", "-1", "--format=%aI", "--", rel]) || undefined);
1573
+ }
1574
+ const fileDate = (cwd, rel) => {
1575
+ const at = committedAt(cwd, rel);
1576
+ return at === undefined ? "uncommitted changes, newer than any commit" : `last committed ${at}`;
1577
+ };
1578
+ function issueHeading(part) {
1579
+ if (part.kind === "description")
1580
+ return "Issue description — oldest";
1581
+ const at = utc(part.createdAt);
1582
+ return at === undefined
1583
+ ? "Issue comment — no date, counts as oldest"
1584
+ : `Issue comment — posted ${at}`;
1585
+ }
1586
+ /** Comments posted after the plan's last commit; none when the plan is missing or uncommitted. */
1587
+ function newerThanPlan(cwd, plan, parts) {
1588
+ if (!plan || !fs.existsSync(path.resolve(cwd, plan)))
1589
+ return 0;
1590
+ const since = committedAt(cwd, plan);
1591
+ if (since === undefined)
1592
+ return 0;
1593
+ return parts.filter((p) => {
1594
+ const at = utc(p.createdAt);
1595
+ return p.kind === "comment" && at !== undefined && at > since;
1596
+ }).length;
1597
+ }
1598
+ function inputVerb(ctx) {
1599
+ const workflow = workflowName(String(ctx.flags.workflow));
1600
+ const fid = String(ctx.flags.fid);
1601
+ const run = positiveInt(ctx.flags.run, "run");
1602
+ const file = str(ctx.flags.file);
1603
+ const status = file
1604
+ ? path.resolve(ctx.cwd, file)
1605
+ : statusLocation({
1606
+ cwd: ctx.cwd,
1607
+ workflow,
1608
+ fid,
1609
+ month: resolveMonth(repoRoot(ctx.cwd), fid, str(ctx.flags.month) || undefined),
1610
+ }).path;
1611
+ const sections = [
1612
+ [
1613
+ "Session Prompt — this run's, newer than everything below",
1614
+ inputText(ctx.cwd, String(ctx.flags.promptFile), "prompt-file"),
1615
+ ],
1616
+ ];
1617
+ const issue = inputIssueParts(ctx);
1618
+ for (const part of issue)
1619
+ sections.push([issueHeading(part), part.text]);
1620
+ const plan = str(ctx.flags.plan);
1621
+ if (plan && fs.existsSync(path.resolve(ctx.cwd, plan)))
1622
+ sections.push([
1623
+ `Plan — ${plan} — ${fileDate(ctx.cwd, plan)}`,
1624
+ inputText(ctx.cwd, plan, "plan"),
1625
+ ]);
1626
+ const design = str(ctx.flags.design);
1627
+ if (design) {
1628
+ const text = inputText(ctx.cwd, design, "design");
1629
+ sections.push([`Design — ${design} — ${fileDate(ctx.cwd, design)}`, text]);
1630
+ }
1631
+ for (const audit of list(ctx.flags.audit)) {
1632
+ const text = inputText(ctx.cwd, audit, "audit");
1633
+ sections.push([`Audit Report — ${audit} — ${fileDate(ctx.cwd, audit)}`, text]);
1634
+ }
1635
+ const body = sections.map(([h, text]) => `## ${h}\n\n${text}\n`).join("\n");
1636
+ const abs = path.join(path.dirname(status), `${workflow}-input-${run}.md`);
1637
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
1638
+ fs.writeFileSync(abs, body);
1639
+ ctx.emit({
1640
+ path: path.relative(ctx.cwd, abs),
1641
+ bytes: Buffer.byteLength(body),
1642
+ newerThanPlan: newerThanPlan(ctx.cwd, plan, issue),
1643
+ });
1644
+ return EXIT.OK;
1645
+ }
1646
+ /**
1647
+ * Close / links output gains `commentFile`; with `--post`, the close comment once,
1648
+ * deduped by marker hash against the issue's latest comments (the close commit is
1649
+ * already made, so no engine-action row can land in it).
1650
+ */
1651
+ async function postClose(ctx, fid, out) {
1652
+ const comment = typeof out.comment === "string" ? out.comment : null;
1653
+ const withFile = { ...out, commentFile: commentFileOf(ctx.cwd, comment) };
1654
+ if (ctx.flags.post !== true)
1655
+ return withFile;
1656
+ if (comment === null)
1657
+ throw new CommandError(EXIT.USAGE, "--post needs --number");
1658
+ return { ...withFile, tracker: await postForVerb(ctx, comment, { fid }) };
1659
+ }
1093
1660
  export const workflowsCommand = {
1094
1661
  noun: "workflows",
1095
- summary: "Start, fail, hand over and close a phase workflow run; promote and link its documents.",
1662
+ summary: "Start, fail, hand over, summarize and close a phase workflow run; promote and link its documents.",
1096
1663
  verbs: {
1097
1664
  start: {
1098
1665
  summary: "Take the feature lock and open a run (workflow-started unless resuming).",
1666
+ use: "workflow",
1099
1667
  flags: [
1100
1668
  WORKFLOW_FLAG,
1101
1669
  FID_FLAG,
@@ -1107,18 +1675,27 @@ export const workflowsCommand = {
1107
1675
  help: "Step 1 already took the lock: check it is ours instead of acquiring",
1108
1676
  },
1109
1677
  TOKEN_FLAG,
1678
+ {
1679
+ name: "branch",
1680
+ type: "string",
1681
+ help: "the branch the checkout must be on; refuse (15) before anything is written when it is not",
1682
+ },
1110
1683
  ],
1111
1684
  output: {
1112
1685
  lock: "{path, month, token, reclaimed} of the lock taken, or {path} with --lock-held",
1113
1686
  file: "absolute path to status.jsonl",
1114
1687
  resumed: "the latest run was this workflow, IN_PROGRESS: no new row",
1115
- row: "the appended workflow-started row, or null when resuming",
1688
+ row: "the appended workflow-started row, with `limits` (the workflow's ask points from bkit.workflows, frozen for the run), or null when resuming",
1116
1689
  run: "which run of the workflow this is (1-based)",
1690
+ lastDoneStep: "the current run's last DONE step: resume after it (null on a new run)",
1691
+ openDecision: "{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",
1117
1692
  },
1693
+ textOmit: ["row"],
1118
1694
  exitCodes: {
1119
1695
  [EXIT_NO_STATUS]: "status.jsonl is not valid",
1120
1696
  [EXIT_SPLIT_BUCKET]: "the feature has logs in more than one month bucket",
1121
1697
  [EXIT_LOCK_NOT_HELD]: "--lock-held: the lock is missing or belongs to another owner",
1698
+ [EXIT_WRONG_BRANCH]: "--branch: the checkout is on another branch",
1122
1699
  },
1123
1700
  run: (ctx) => {
1124
1701
  const workflow = workflowName(String(ctx.flags.workflow));
@@ -1126,6 +1703,14 @@ export const workflowsCommand = {
1126
1703
  const token = str(ctx.flags.token);
1127
1704
  if (token !== undefined && ctx.flags.lockHeld !== true)
1128
1705
  throw new CommandError(EXIT.USAGE, "--token applies with --lock-held only");
1706
+ const branch = str(ctx.flags.branch);
1707
+ if (branch !== undefined) {
1708
+ const on = git(ctx.cwd, ["branch", "--show-current"]) ?? "";
1709
+ if (on !== branch) {
1710
+ ctx.log(`[bkit-${workflow}] not on ${branch} in ${ctx.cwd} (on '${on}')`);
1711
+ return EXIT_WRONG_BRANCH;
1712
+ }
1713
+ }
1129
1714
  const where = whereInTree(ctx.cwd, {
1130
1715
  workflow,
1131
1716
  fid,
@@ -1153,30 +1738,55 @@ export const workflowsCommand = {
1153
1738
  fs.mkdirSync(path.dirname(file), { recursive: true });
1154
1739
  if (!fs.existsSync(file))
1155
1740
  fs.writeFileSync(file, "");
1156
- const latest = fold(readStatusEvents(file)).at(-1);
1157
- const resumed = latest?.workflow === workflow && latest.status === "IN_PROGRESS";
1741
+ // A ship decides its handover afresh: a sentinel an earlier run left is stale.
1742
+ if (workflow === "ship") {
1743
+ for (const name of SENTINELS) {
1744
+ const p = path.join(path.dirname(file), name);
1745
+ if (!fs.existsSync(p))
1746
+ continue;
1747
+ fs.rmSync(p, { force: true });
1748
+ ctx.log(`cleared stale ${name}`);
1749
+ }
1750
+ }
1751
+ const resumed = lastRun(fold(readStatusEvents(file)), workflow)?.status === "IN_PROGRESS";
1752
+ const holeyWarning = previousRunWarning(file, resumed);
1753
+ if (holeyWarning !== null)
1754
+ ctx.log(holeyWarning);
1158
1755
  let row = null;
1159
1756
  if (!resumed) {
1757
+ // The run's limits, frozen here: `counters route` reads them for the whole run.
1758
+ const asks = readBkitConfig(where.tree).asks;
1759
+ const limits = Object.fromEntries(ASK_POINTS.filter((p) => p.startsWith(`${workflow}.`)).map((p) => [p, asks[p]]));
1160
1760
  row = {
1161
1761
  type: "workflow-started",
1162
1762
  workflow,
1163
1763
  at: statusTimestamp(),
1164
1764
  parentSha: headSha(path.dirname(file)),
1765
+ ...(Object.keys(limits).length === 0 ? {} : { limits }),
1165
1766
  };
1166
1767
  fs.appendFileSync(file, appendLine(row));
1167
1768
  }
1769
+ recordChat(file, workflow, process.env);
1770
+ const runs = fold(readStatusEvents(file));
1771
+ const run = runNumber(runs, workflow);
1772
+ const current = resumed ? lastRun(runs, workflow) : undefined;
1168
1773
  ctx.emit({
1169
1774
  lock,
1170
1775
  file,
1171
1776
  resumed,
1172
1777
  row,
1173
- run: runNumber(fold(readStatusEvents(file)), workflow),
1778
+ run,
1779
+ lastDoneStep: current?.steps.filter((s) => s.status === "DONE").at(-1)?.step ?? null,
1780
+ openDecision: resumed
1781
+ ? openDecision(path.dirname(file), where.tree, workflow, run)
1782
+ : null,
1174
1783
  });
1175
1784
  return EXIT.OK;
1176
1785
  },
1177
1786
  },
1178
1787
  fail: {
1179
1788
  summary: "Failure Path: workflow-failed row, abort rebase, release lock, clear sentinels (with --token); the bkit:failed labels and the failure comment.",
1789
+ use: "workflow",
1180
1790
  flags: [
1181
1791
  WORKFLOW_FLAG,
1182
1792
  { ...FID_FLAG, required: false, help: "feature id (needed with --token)" },
@@ -1220,10 +1830,20 @@ export const workflowsCommand = {
1220
1830
  type: "string",
1221
1831
  help: "the failed shell command's stderr (last 20 lines kept)",
1222
1832
  },
1833
+ {
1834
+ ...POST_FLAG,
1835
+ help: "post the failure comment (needs --step-number) to the --fid / --issue issue and write its failed labels; prints `tracker` and `labelsWrite`",
1836
+ },
1837
+ {
1838
+ name: "issue",
1839
+ type: "string",
1840
+ help: "with --post: the issue id when there is no --fid yet",
1841
+ },
1842
+ SESSION_DIR_FLAG,
1223
1843
  ],
1224
1844
  output: {
1225
1845
  row: "the appended workflow-failed row, or null (no --token, or no status.jsonl)",
1226
- rebaseAborted: "an in-progress rebase was found and aborted",
1846
+ rebaseAborted: "an in-progress rebase or merge was found and aborted",
1227
1847
  lock: "{path, existed, released, heldBy}: heldBy is another owner's lock line, left in place; null without --token",
1228
1848
  sentinels: "[{name, path}] sentinels that existed before this call removed them",
1229
1849
  handoverNeeded: "--max-exceeded, a sentinel existed, or a debug run in SOAK mode: write the abort handover",
@@ -1232,7 +1852,12 @@ export const workflowsCommand = {
1232
1852
  trackerState: "the Linear or Jira state for the failed issue (null under github, none)",
1233
1853
  prState: "the --pr PR's state, or null",
1234
1854
  comment: "the failure comment body (with --step-number), else null",
1855
+ commentFile: COMMENT_FILE_OUTPUT,
1856
+ tracker: TRACKER_OUTPUT,
1857
+ labelsWrite: "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}",
1858
+ sessionRemoved: SESSION_REMOVED_OUTPUT,
1235
1859
  },
1860
+ textOmit: ["row"],
1236
1861
  exitCodes: {
1237
1862
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1238
1863
  [EXIT_REMOVE_FAILED]: "the lock file is still there after removing it (everything else was done; the comment says so)",
@@ -1241,6 +1866,7 @@ export const workflowsCommand = {
1241
1866
  },
1242
1867
  handover: {
1243
1868
  summary: "Keep a failed run's record: commit and push it on the feature branch, or land its logs and ledgers on dev (--push from dev / main, ship's --flush); print the handover comment.",
1869
+ use: "workflow",
1244
1870
  flags: [
1245
1871
  WORKFLOW_FLAG,
1246
1872
  FID_FLAG,
@@ -1248,7 +1874,7 @@ export const workflowsCommand = {
1248
1874
  {
1249
1875
  name: "push",
1250
1876
  type: "boolean",
1251
- help: "feature branch: git add -A, commit `docs({fid}): {workflow} aborted bkit [skip ci]`, push --mode=abort; dev / main / detached: lands like --flush, the checkout untouched",
1877
+ 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",
1252
1878
  },
1253
1879
  {
1254
1880
  name: "flush",
@@ -1261,12 +1887,18 @@ export const workflowsCommand = {
1261
1887
  help: "--push: the open-PR answer from MCP (a number, or none) instead of asking gh",
1262
1888
  },
1263
1889
  { name: "ref", type: "string", help: "link the handover at this ref (no push / flush)" },
1890
+ {
1891
+ name: "list-stray",
1892
+ type: "boolean",
1893
+ help: "only list what --push would sweep in besides the run's logs (modified, untracked) and whether the checkout is shared; writes nothing",
1894
+ },
1264
1895
  {
1265
1896
  name: "worktree",
1266
1897
  type: "string",
1267
1898
  help: "the run's tree: holds the handover and the logs, and is where --push commits (default: cwd's checkout)",
1268
1899
  },
1269
1900
  OWNER_REPO_FLAG,
1901
+ { ...POST_FLAG, help: "post the handover comment to the FID's issue; prints `tracker`" },
1270
1902
  ],
1271
1903
  output: {
1272
1904
  handover: "the handover artifact, or null when absent",
@@ -1274,6 +1906,11 @@ export const workflowsCommand = {
1274
1906
  ref: "where the handover now lives, or null when nothing was pushed",
1275
1907
  skipped: "why nothing was pushed: open-pr | skip-ci | nothing-to-commit (null otherwise)",
1276
1908
  comment: "the handover comment body (null when there is no handover); links only when pushed",
1909
+ commentFile: COMMENT_FILE_OUTPUT,
1910
+ tracker: `${TRACKER_OUTPUT}; absent when there is no handover`,
1911
+ shared: "--list-stray: the checkout is dev / main / detached (remove nothing)",
1912
+ modified: "--list-stray: tracked paths with changes, outside the run's logs",
1913
+ untracked: "--list-stray: untracked paths, outside the run's logs",
1277
1914
  },
1278
1915
  exitCodes: {
1279
1916
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
@@ -1285,6 +1922,7 @@ export const workflowsCommand = {
1285
1922
  },
1286
1923
  close: {
1287
1924
  summary: "Grade compliance, workflow-done row, counter + outcome telemetry, report, artifact links; --flush lands ship's close on dev.",
1925
+ use: "workflow",
1288
1926
  flags: [
1289
1927
  WORKFLOW_FLAG,
1290
1928
  FID_FLAG,
@@ -1319,7 +1957,7 @@ export const workflowsCommand = {
1319
1957
  {
1320
1958
  name: "message",
1321
1959
  type: "string",
1322
- help: "then git add -A and commit with this message in the tree",
1960
+ help: "then git add -A (minus bkit.workflows.worktree.copy entries) and commit with this message in the tree",
1323
1961
  },
1324
1962
  {
1325
1963
  name: "label",
@@ -1334,6 +1972,16 @@ export const workflowsCommand = {
1334
1972
  },
1335
1973
  ...COMMENT_FLAGS,
1336
1974
  { name: "tree", type: "string", help: "the close comment links the tree of this ref" },
1975
+ {
1976
+ name: "ending",
1977
+ type: "string",
1978
+ help: "done|held (default done); held = a local build that published nothing",
1979
+ },
1980
+ {
1981
+ name: "publish",
1982
+ type: "string",
1983
+ help: "build: true|false, the resolved publish value; recorded on the workflow-done and outcome rows",
1984
+ },
1337
1985
  {
1338
1986
  name: "flush",
1339
1987
  type: "boolean",
@@ -1345,6 +1993,40 @@ export const workflowsCommand = {
1345
1993
  type: "string",
1346
1994
  help: "--flush: the shipped branch, deleted locally and on origin with the worktree once the close is on dev",
1347
1995
  },
1996
+ SESSION_DIR_FLAG,
1997
+ {
1998
+ name: "final-return",
1999
+ type: "boolean",
2000
+ help: "print finalReturn: the run's last message to the person (needs --summary-file)",
2001
+ },
2002
+ {
2003
+ name: "summary-file",
2004
+ type: "string",
2005
+ help: "--final-return: the summary shown verbatim (read before the close runs)",
2006
+ },
2007
+ {
2008
+ name: "summary",
2009
+ type: "string",
2010
+ help: "--final-return: like --summary-file, but a missing file shows --summary-missing; a copy is kept in --outbox",
2011
+ },
2012
+ {
2013
+ name: "summary-missing",
2014
+ type: "string",
2015
+ help: "--summary: the line shown when the summary file does not exist",
2016
+ },
2017
+ { name: "warning", type: "string", help: "--final-return: line 1, before the summary" },
2018
+ {
2019
+ name: "line",
2020
+ type: "string",
2021
+ repeatable: true,
2022
+ help: "--final-return: a line after the summary, before the issue link",
2023
+ },
2024
+ {
2025
+ name: "suggest",
2026
+ type: "string",
2027
+ repeatable: true,
2028
+ help: "--final-return: a suggested reply, before the plain-English offer",
2029
+ },
1348
2030
  ],
1349
2031
  output: {
1350
2032
  row: "the appended workflow-done row",
@@ -1358,16 +2040,24 @@ export const workflowsCommand = {
1358
2040
  parentSha: "HEAD before the --message commit (the close step's parentSha)",
1359
2041
  commit: "the --message commit, or null",
1360
2042
  comment: "the close comment (--number with --outbox), else null",
2043
+ commentFile: COMMENT_FILE_OUTPUT,
2044
+ tracker: TRACKER_OUTPUT,
1361
2045
  roadmapFoldNeeded: "always true: append the feature row and re-render the board (not run here)",
1362
2046
  featureStatus: "roadmap status this close moves the feature to",
2047
+ progressLine: "--record-step: the exact chat progress line after a numbered completion is recorded",
1363
2048
  landed: "--flush: {ref, via: head-push | close-pr | close-pr-open}",
1364
2049
  worktree: "--flush: the `bkit worktrees remove` result once the close is on dev; null while the close PR is unmerged or the removal failed",
2050
+ sessionRemoved: SESSION_REMOVED_OUTPUT,
2051
+ finalReturn: "--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)",
1365
2052
  },
2053
+ textOmit: ["row", "counterRow", "outcomeRow"],
1366
2054
  exitCodes: {
1367
2055
  [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
2056
+ [EXIT_NO_INPUT]: "--final-return: --summary-file does not exist (nothing written)",
1368
2057
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1369
- [EXIT_PUSH_FAILED]: "--flush: dev moved before every push, or the push failed without a server answer; the lock is kept",
2058
+ [EXIT_PUSH_FAILED]: "--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",
1370
2059
  [EXIT_FLUSH_FAILED]: "--flush: the dev fetch, the throwaway checkout or the close commit failed, the close PR could not be opened (the lock is kept), or the lock could not be removed",
2060
+ [EXIT_NO_RECORD]: "--message in a debug run on dev/main with no shared-checkout record: no row written, nothing committed",
1371
2061
  },
1372
2062
  run: async (ctx) => {
1373
2063
  const f = ctx.flags;
@@ -1388,21 +2078,80 @@ export const workflowsCommand = {
1388
2078
  number: str(f.number),
1389
2079
  title: str(f.title),
1390
2080
  tree: str(f.tree),
2081
+ ...closeEnding(f),
1391
2082
  };
2083
+ const finalParts = finalReturnParts(ctx, input.fid);
1392
2084
  if (f.flush === true) {
1393
2085
  if (input.workflow !== "ship")
1394
2086
  throw new CommandError(EXIT.USAGE, "--flush is ship only");
1395
2087
  const r = await shipClose(ctx, { ...input, branch: str(f.branch) }, str(f.token));
1396
- if (r.out)
1397
- ctx.emit(r.out);
2088
+ if (r.out) {
2089
+ const out = r.out;
2090
+ const posted = typeof out.comment === "string"
2091
+ ? await postClose(ctx, input.fid, out)
2092
+ : { ...out, commentFile: null };
2093
+ const final = finalReturnText(ctx, input.workflow, finalParts);
2094
+ ctx.emit({ ...posted, ...final, ...sessionRemoval(ctx) });
2095
+ }
1398
2096
  return r.code;
1399
2097
  }
1400
- ctx.emit(closeWorkflow(ctx.cwd, input, ctx.log));
2098
+ const out = await postClose(ctx, input.fid, { ...closeWorkflow(ctx.cwd, input, ctx.log) });
2099
+ const final = finalReturnText(ctx, input.workflow, finalParts);
2100
+ ctx.emit({ ...out, ...final, ...sessionRemoval(ctx) });
1401
2101
  return EXIT.OK;
1402
2102
  },
1403
2103
  },
2104
+ input: {
2105
+ summary: "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.",
2106
+ use: "workflow",
2107
+ flags: [
2108
+ WORKFLOW_FLAG,
2109
+ FID_FLAG,
2110
+ MONTH_FLAG,
2111
+ {
2112
+ ...STATUS_FILE_FLAG,
2113
+ help: "status.jsonl: the input file goes beside it (default: derived)",
2114
+ },
2115
+ { name: "run", type: "string", required: true, help: "the run number ({RUN})" },
2116
+ {
2117
+ name: "prompt-file",
2118
+ type: "string",
2119
+ required: true,
2120
+ help: "the session prompt ({SESSION_DIR}/prompt.md)",
2121
+ },
2122
+ {
2123
+ name: "description-file",
2124
+ type: "string",
2125
+ help: "issue-description.md from `issues fetch` (omit for a run with no issue)",
2126
+ },
2127
+ {
2128
+ name: "comments-file",
2129
+ type: "string",
2130
+ help: "issue-comments.json from `issues fetch`: bkit:generated comments dropped, the ignore-earlier cut applied",
2131
+ },
2132
+ { name: "plan", type: "string", help: "appended under `## Plan — <path>` when it exists" },
2133
+ { name: "design", type: "string", help: "plan: the parent design, appended (must exist)" },
2134
+ {
2135
+ name: "audit",
2136
+ type: "string",
2137
+ repeatable: true,
2138
+ help: "plan: an audit report, appended in flag order (must exist)",
2139
+ },
2140
+ ],
2141
+ output: {
2142
+ path: "the input file written, relative to cwd",
2143
+ bytes: "its size in bytes",
2144
+ newerThanPlan: "issue comments posted after the plan's last commit (0 with no plan, or one with uncommitted changes)",
2145
+ },
2146
+ exitCodes: {
2147
+ [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
2148
+ [EXIT_NO_INPUT]: "the prompt, description, comments, design or an audit file is missing, or the comments are not a list",
2149
+ },
2150
+ run: inputVerb,
2151
+ },
1404
2152
  promote: {
1405
- summary: "Design / plan close: the highest versioned draft becomes the canonical doc (anchor stamped, a changed canonical archived, plan sub-plans copied).",
2153
+ summary: "Design / plan close: the highest versioned draft becomes the canonical doc (anchor stamped, a changed canonical archived).",
2154
+ use: "workflow",
1406
2155
  flags: [
1407
2156
  { ...WORKFLOW_FLAG, help: "design | plan" },
1408
2157
  FID_FLAG,
@@ -1421,8 +2170,7 @@ export const workflowsCommand = {
1421
2170
  output: {
1422
2171
  final: "the highest versioned draft, e.g. docs/plans/202610/logs/12-x/design-v3-organised.md",
1423
2172
  canonical: "the canonical doc written, or null with --resolve",
1424
- archived: "superseded canonical docs moved to archive/",
1425
- subPlans: "plan: the canonical sub-plans written",
2173
+ archived: "the superseded canonical doc moved to archive/, if any",
1426
2174
  baseSha: "the base commit stamped into the anchor, or null when none was recorded",
1427
2175
  },
1428
2176
  exitCodes: {
@@ -1433,6 +2181,7 @@ export const workflowsCommand = {
1433
2181
  },
1434
2182
  links: {
1435
2183
  summary: "The feature's docs and this workflow's logs on a ref as markdown links; optionally the close comment.",
2184
+ use: "workflow",
1436
2185
  flags: [
1437
2186
  WORKFLOW_FLAG,
1438
2187
  FID_FLAG,
@@ -1454,11 +2203,13 @@ export const workflowsCommand = {
1454
2203
  artifacts: "[{name, path, url}]",
1455
2204
  artifactLinks: "the same as markdown `- [name](url)` lines",
1456
2205
  comment: "the close comment (--number with --outbox): Artifacts and Telemetry sections, else null",
2206
+ commentFile: COMMENT_FILE_OUTPUT,
2207
+ tracker: TRACKER_OUTPUT,
1457
2208
  },
1458
2209
  exitCodes: {
1459
2210
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1460
2211
  },
1461
- run: (ctx) => {
2212
+ run: async (ctx) => {
1462
2213
  const workflow = workflowName(String(ctx.flags.workflow));
1463
2214
  const fid = String(ctx.flags.fid);
1464
2215
  const root = repoRoot(ctx.cwd);
@@ -1481,9 +2232,50 @@ export const workflowsCommand = {
1481
2232
  else if (ctx.flags.number !== undefined) {
1482
2233
  throw new CommandError(EXIT.USAGE, "--number needs --outbox");
1483
2234
  }
1484
- ctx.emit({ artifacts, artifactLinks: linkLines(artifacts), comment });
2235
+ ctx.emit(await postClose(ctx, fid, { artifacts, artifactLinks: linkLines(artifacts), comment }));
1485
2236
  return EXIT.OK;
1486
2237
  },
1487
2238
  },
2239
+ summary: {
2240
+ summary: "The Summary step: write {workflow}-summary.md next to --file with the run's verdict, reasons and next command.",
2241
+ use: "workflow",
2242
+ flags: [
2243
+ { ...WORKFLOW_FLAG, help: "plan | design | build | debug | ship" },
2244
+ {
2245
+ name: "file",
2246
+ type: "string",
2247
+ required: true,
2248
+ help: "the run's docs/plans/{YYYYMM}/logs/{FID}/status.jsonl; the summary is written beside it",
2249
+ },
2250
+ {
2251
+ name: "plan",
2252
+ type: "string",
2253
+ repeatable: true,
2254
+ help: "a plan file the run worked from (default: build reads {FID}-plan.md)",
2255
+ },
2256
+ {
2257
+ name: "pr",
2258
+ type: "string",
2259
+ help: "ship: the PR number; its size comes from gh pr view (left out when gh cannot answer)",
2260
+ },
2261
+ {
2262
+ name: "publish",
2263
+ type: "string",
2264
+ help: "build: true|false, the resolved ending; false writes `Publish: held` and `Docs: not synced` (default true)",
2265
+ },
2266
+ ],
2267
+ output: {
2268
+ verdict: "PASS | CONCERNS | FAIL",
2269
+ failures: "the count of FAIL reasons: 0 on PASS and CONCERNS",
2270
+ reasons: "one line per reason, FAIL reasons first",
2271
+ file: "the summary written, repo-relative",
2272
+ nextStep: "the recommended next command (with the issue ref), or the fixed line when there is none",
2273
+ },
2274
+ exitCodes: {
2275
+ [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
2276
+ [EXIT_NO_RUN]: "status.jsonl has no workflow-started row for --workflow (nothing written)",
2277
+ },
2278
+ run: summaryVerb,
2279
+ },
1488
2280
  },
1489
2281
  };