@cbartens/bkit 5.5.0 → 6.0.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 (297) hide show
  1. package/.bkit/README.md +30 -20
  2. package/.bkit/core/.agents/docs.md +1 -0
  3. package/.bkit/core/.agents/rules.md +51 -26
  4. package/.bkit/core/.bkit/README.md +29 -19
  5. package/.bkit/core/.bkit/authoring.md +117 -0
  6. package/.bkit/core/.bkit/cloud.md +11 -11
  7. package/.bkit/core/.bkit/comparison.md +5 -5
  8. package/.bkit/core/.bkit/install.md +20 -20
  9. package/.bkit/core/.bkit/jsonl.md +202 -122
  10. package/.bkit/core/.bkit/lite.md +1 -1
  11. package/.bkit/core/.bkit/pipeline.md +49 -52
  12. package/.bkit/core/.bkit/prompts.md +106 -167
  13. package/.bkit/core/.bkit/providers.md +29 -32
  14. package/.bkit/core/.bkit/templates.md +44 -18
  15. package/.bkit/core/.bkit/trackers.md +60 -28
  16. package/.bkit/core/.bkit/workflows.md +399 -359
  17. package/.bkit/core/AGENTS.md +16 -22
  18. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +14 -38
  19. package/.bkit/core/docs/templates/bkit-audit-adoption.md +16 -40
  20. package/.bkit/core/docs/templates/bkit-audit-agents.md +19 -43
  21. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +16 -40
  22. package/.bkit/core/docs/templates/bkit-audit-analytics.md +14 -38
  23. package/.bkit/core/docs/templates/bkit-audit-annotations.md +11 -35
  24. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +15 -39
  25. package/.bkit/core/docs/templates/bkit-audit-app-store.md +12 -36
  26. package/.bkit/core/docs/templates/bkit-audit-architecture.md +16 -40
  27. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +16 -40
  28. package/.bkit/core/docs/templates/bkit-audit-config.md +18 -42
  29. package/.bkit/core/docs/templates/bkit-audit-cost.md +16 -40
  30. package/.bkit/core/docs/templates/bkit-audit-coverage.md +15 -39
  31. package/.bkit/core/docs/templates/bkit-audit-database.md +16 -40
  32. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +15 -39
  33. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +15 -38
  34. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +16 -40
  35. package/.bkit/core/docs/templates/bkit-audit-documentation.md +11 -35
  36. package/.bkit/core/docs/templates/bkit-audit-duplication.md +18 -42
  37. package/.bkit/core/docs/templates/bkit-audit-failures.md +13 -37
  38. package/.bkit/core/docs/templates/bkit-audit-flakes.md +12 -36
  39. package/.bkit/core/docs/templates/bkit-audit-gates.md +14 -38
  40. package/.bkit/core/docs/templates/bkit-audit-issues.md +15 -39
  41. package/.bkit/core/docs/templates/bkit-audit-llm.md +16 -40
  42. package/.bkit/core/docs/templates/bkit-audit-logs.md +14 -38
  43. package/.bkit/core/docs/templates/bkit-audit-models.md +12 -36
  44. package/.bkit/core/docs/templates/bkit-audit-privacy.md +12 -36
  45. package/.bkit/core/docs/templates/bkit-audit-prompts.md +15 -39
  46. package/.bkit/core/docs/templates/bkit-audit-red-team.md +15 -39
  47. package/.bkit/core/docs/templates/bkit-audit-reliability.md +15 -39
  48. package/.bkit/core/docs/templates/bkit-audit-repo.md +12 -36
  49. package/.bkit/core/docs/templates/bkit-audit-security.md +13 -37
  50. package/.bkit/core/docs/templates/bkit-audit-slop.md +14 -38
  51. package/.bkit/core/docs/templates/bkit-audit-testing.md +12 -36
  52. package/.bkit/core/docs/templates/bkit-audit-usability.md +16 -40
  53. package/.bkit/core/docs/templates/bkit-plan.md +97 -226
  54. package/.bkit/core/engine/checks/after/ci-yml.ts +39 -30
  55. package/.bkit/core/engine/checks/after/github.ts +101 -72
  56. package/.bkit/core/engine/checks/after/index.ts +10 -12
  57. package/.bkit/core/engine/checks/after/suppression.ts +8 -5
  58. package/.bkit/core/engine/checks/after/tools.ts +47 -92
  59. package/.bkit/core/engine/checks/before/env.ts +2 -2
  60. package/.bkit/core/engine/checks/before/files.ts +5 -4
  61. package/.bkit/core/engine/checks/before/index.ts +18 -1
  62. package/.bkit/core/engine/checks/before/repo.ts +168 -2
  63. package/.bkit/core/engine/checks/tips/catalogue.ts +16 -5
  64. package/.bkit/core/engine/checks/tips/detect.ts +34 -0
  65. package/.bkit/core/engine/checks/tips/index.ts +10 -7
  66. package/.bkit/core/engine/cli.ts +20 -53
  67. package/.bkit/core/engine/commands/analysis.ts +171 -140
  68. package/.bkit/core/engine/commands/ci/ci.ts +6 -6
  69. package/.bkit/core/engine/commands/comply.ts +77 -103
  70. package/.bkit/core/engine/commands/install/doctor.ts +2 -2
  71. package/.bkit/core/engine/commands/install/install.ts +57 -18
  72. package/.bkit/core/engine/commands/install/uninstall.ts +65 -28
  73. package/.bkit/core/engine/commands/land.ts +18 -12
  74. package/.bkit/core/engine/commands/lib.ts +79 -17
  75. package/.bkit/core/engine/commands/registry.ts +4 -0
  76. package/.bkit/core/engine/commands/setup/setup.ts +7 -7
  77. package/.bkit/core/engine/commands/stats.ts +204 -0
  78. package/.bkit/core/engine/commands/tips.ts +10 -5
  79. package/.bkit/core/engine/commands/workflow/branches.ts +741 -62
  80. package/.bkit/core/engine/commands/workflow/challenge.ts +673 -0
  81. package/.bkit/core/engine/commands/workflow/context.ts +853 -29
  82. package/.bkit/core/engine/commands/workflow/counters.ts +267 -84
  83. package/.bkit/core/engine/commands/workflow/decisions.ts +541 -0
  84. package/.bkit/core/engine/commands/workflow/disk.ts +2 -2
  85. package/.bkit/core/engine/commands/workflow/fids.ts +793 -33
  86. package/.bkit/core/engine/commands/workflow/issues.ts +427 -105
  87. package/.bkit/core/engine/commands/workflow/ledgers.ts +884 -27
  88. package/.bkit/core/engine/commands/workflow/locks.ts +26 -2
  89. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +582 -0
  90. package/.bkit/core/engine/commands/workflow/plan-versions.ts +21 -0
  91. package/.bkit/core/engine/commands/workflow/prs.ts +166 -30
  92. package/.bkit/core/engine/commands/workflow/repo.ts +59 -7
  93. package/.bkit/core/engine/commands/workflow/roadmap.ts +16 -7
  94. package/.bkit/core/engine/commands/workflow/run-facts.ts +501 -0
  95. package/.bkit/core/engine/commands/workflow/runs.ts +179 -49
  96. package/.bkit/core/engine/commands/workflow/runtime.ts +22 -1
  97. package/.bkit/core/engine/commands/workflow/status.ts +142 -29
  98. package/.bkit/core/engine/commands/workflow/step-table.ts +339 -0
  99. package/.bkit/core/engine/commands/workflow/steps.ts +213 -88
  100. package/.bkit/core/engine/commands/workflow/summary.ts +398 -0
  101. package/.bkit/core/engine/commands/workflow/tests.ts +1013 -148
  102. package/.bkit/core/engine/commands/workflow/tracker.ts +1195 -0
  103. package/.bkit/core/engine/commands/workflow/workflows.ts +984 -207
  104. package/.bkit/core/engine/commands/workflow/workstreams.ts +11 -5
  105. package/.bkit/core/engine/commands/workflow/worktrees.ts +276 -22
  106. package/.bkit/core/engine/install/manifest.ts +11 -9
  107. package/.bkit/core/engine/install/modules/cloud.ts +21 -13
  108. package/.bkit/core/engine/install/modules/core.ts +325 -7
  109. package/.bkit/core/engine/install/modules/opencode.ts +2 -2
  110. package/.bkit/core/engine/install/version-file.ts +6 -2
  111. package/.bkit/core/engine/ledgers/migrate.ts +92 -0
  112. package/.bkit/core/engine/ledgers/status.ts +92 -15
  113. package/.bkit/core/engine/ledgers/telemetry.ts +1261 -254
  114. package/.bkit/core/engine/render/hosts.ts +4 -0
  115. package/.bkit/core/engine/render/models.ts +12 -0
  116. package/.bkit/core/engine/shared/branches.ts +4 -1
  117. package/.bkit/core/engine/shared/egress.ts +7 -0
  118. package/.bkit/core/engine/shared/json.ts +25 -7
  119. package/.bkit/core/engine/shared/settings.ts +202 -33
  120. package/.bkit/core/engine/shared/text.ts +361 -0
  121. package/.bkit/core/engine/tools/grammar-density.ts +215 -0
  122. package/.bkit/core/engine/tools/instructions-sources.ts +834 -0
  123. package/.bkit/core/engine/tools/instructions.ts +1751 -0
  124. package/.bkit/core/hooks/gateguard-engine.js +24 -23
  125. package/.bkit/core/hooks/guardrails-shell.js +2 -3
  126. package/.bkit/core/hooks/guardrails-tiers.js +7 -1
  127. package/.bkit/core/hooks/readguard-engine.js +2 -2
  128. package/.bkit/core/prompts/bkit-audit-generate.md +62 -25
  129. package/.bkit/core/prompts/bkit-build-challenge-1.md +40 -17
  130. package/.bkit/core/prompts/bkit-build-challenge-2.md +44 -17
  131. package/.bkit/core/prompts/bkit-build-install-skills.md +26 -13
  132. package/.bkit/core/prompts/bkit-build-plan-convert.md +74 -0
  133. package/.bkit/core/prompts/bkit-build-plan-current.md +26 -13
  134. package/.bkit/core/prompts/bkit-build-plan-execute.md +74 -26
  135. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +64 -23
  136. package/.bkit/core/prompts/bkit-build-plan-verify.md +57 -33
  137. package/.bkit/core/prompts/bkit-debug-abort-handover.md +30 -14
  138. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +34 -14
  139. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +34 -17
  140. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +26 -13
  141. package/.bkit/core/prompts/bkit-debug-failure-soak.md +31 -16
  142. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +21 -11
  143. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +20 -11
  144. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +20 -11
  145. package/.bkit/core/prompts/bkit-design-generate.md +33 -13
  146. package/.bkit/core/prompts/bkit-design-organise.md +25 -12
  147. package/.bkit/core/prompts/bkit-design-review-1.md +31 -15
  148. package/.bkit/core/prompts/bkit-design-review-2.md +28 -13
  149. package/.bkit/core/prompts/bkit-design-spike.md +30 -13
  150. package/.bkit/core/prompts/bkit-design-update.md +33 -19
  151. package/.bkit/core/prompts/bkit-plan-generate.md +75 -19
  152. package/.bkit/core/prompts/bkit-plan-review-1.md +50 -27
  153. package/.bkit/core/prompts/bkit-plan-review-2.md +59 -28
  154. package/.bkit/core/prompts/bkit-plan-scope-check.md +109 -0
  155. package/.bkit/core/prompts/bkit-plan-update.md +61 -24
  156. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +27 -15
  157. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +31 -16
  158. package/.bkit/core/prompts/bkit-ship-update-docs.md +30 -15
  159. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +24 -14
  160. package/.bkit/core/prompts/bkit-utility-update-decisions.md +32 -14
  161. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +29 -14
  162. package/.bkit/core/prompts/bkit-utility-update-documentation.md +28 -13
  163. package/.bkit/core/prompts/bkit-utility-update-failures.md +31 -14
  164. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +33 -14
  165. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +38 -17
  166. package/.bkit/core/prompts/bkit-utility-update-tracker.md +43 -20
  167. package/.bkit/core/workflows/bkit-auto.md +54 -46
  168. package/.bkit/core/workflows/bkit-build.md +577 -458
  169. package/.bkit/core/workflows/bkit-debug.md +348 -333
  170. package/.bkit/core/workflows/bkit-design.md +201 -237
  171. package/.bkit/core/workflows/bkit-plan.md +210 -321
  172. package/.bkit/core/workflows/bkit-ship.md +328 -278
  173. package/.bkit/shared/.bkit/.env.example +2 -2
  174. package/.bkit/shared/.claude/settings.json +11 -0
  175. package/.bkit/shared/.cursor/mcp.json +1 -1
  176. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +1 -1
  177. package/.bkit/shared/.gitattributes +1 -1
  178. package/.bkit/shared/.mcp.json +1 -1
  179. package/.bkit/shared/.opencode/opencode.json +11 -0
  180. package/.bkit/shared/CLAUDE.md +2 -2
  181. package/.bkit/shared/GEMINI.md +2 -2
  182. package/.bkit/shared/docs/architecture.md +1 -1
  183. package/.bkit/shared/docs/data-schema.md +1 -1
  184. package/.bkit/shared/docs/deployments.md +16 -28
  185. package/.bkit/shared/docs/design.md +1 -1
  186. package/.bkit/shared/docs/noise.md +1 -1
  187. package/.bkit/shared/docs/observability.md +2 -2
  188. package/.bkit/shared/docs/security.md +1 -1
  189. package/.bkit/shared/docs/setup.md +1 -1
  190. package/.bkit/shared/docs/technology.md +1 -1
  191. package/.bkit/shared/docs/testing.md +27 -10
  192. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +1 -1
  193. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +26 -5
  194. package/.bkit/templates/.github/workflows/bkit-ci.yml +22 -84
  195. package/.bkit/templates/.github/workflows/bkit-cloud.yml +21 -19
  196. package/.bkit/templates/.husky/pre-push +52 -13
  197. package/.bkit/templates/.prettierignore +7 -0
  198. package/.bkit/templates/scripts/ci/bkit-local-stack-lock.sh +194 -0
  199. package/.bkit/templates/scripts/ci/check-capstone.mjs +2 -4
  200. package/.bkit/templates/scripts/ci/check-capstone.test.mjs +4 -23
  201. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +104 -23
  202. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +103 -6
  203. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +1 -1
  204. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +3 -1
  205. package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +49 -29
  206. package/CHANGELOG.md +142 -0
  207. package/README.md +58 -34
  208. package/dist/checks/after/ci-yml.js +39 -29
  209. package/dist/checks/after/github.js +99 -72
  210. package/dist/checks/after/index.js +11 -13
  211. package/dist/checks/after/suppression.js +8 -5
  212. package/dist/checks/after/tools.js +40 -83
  213. package/dist/checks/before/env.js +2 -2
  214. package/dist/checks/before/files.js +5 -3
  215. package/dist/checks/before/index.js +15 -2
  216. package/dist/checks/before/repo.js +163 -2
  217. package/dist/checks/tips/catalogue.js +14 -5
  218. package/dist/checks/tips/detect.js +32 -0
  219. package/dist/checks/tips/index.js +7 -5
  220. package/dist/cli.js +19 -47
  221. package/dist/commands/analysis.js +109 -100
  222. package/dist/commands/ci/ci.js +6 -6
  223. package/dist/commands/comply.js +54 -91
  224. package/dist/commands/install/doctor.js +2 -2
  225. package/dist/commands/install/install.js +50 -19
  226. package/dist/commands/install/uninstall.js +59 -28
  227. package/dist/commands/land.js +16 -12
  228. package/dist/commands/lib.js +51 -16
  229. package/dist/commands/registry.js +4 -0
  230. package/dist/commands/setup/setup.js +7 -7
  231. package/dist/commands/stats.js +136 -0
  232. package/dist/commands/tips.js +7 -3
  233. package/dist/commands/workflow/branches.js +656 -56
  234. package/dist/commands/workflow/challenge.js +556 -0
  235. package/dist/commands/workflow/context.js +709 -30
  236. package/dist/commands/workflow/counters.js +208 -75
  237. package/dist/commands/workflow/decisions.js +441 -0
  238. package/dist/commands/workflow/disk.js +2 -2
  239. package/dist/commands/workflow/fids.js +689 -33
  240. package/dist/commands/workflow/issues.js +362 -99
  241. package/dist/commands/workflow/ledgers.js +762 -27
  242. package/dist/commands/workflow/locks.js +24 -2
  243. package/dist/commands/workflow/plan-blocks.js +437 -0
  244. package/dist/commands/workflow/plan-versions.js +22 -0
  245. package/dist/commands/workflow/prs.js +142 -32
  246. package/dist/commands/workflow/repo.js +52 -7
  247. package/dist/commands/workflow/roadmap.js +9 -7
  248. package/dist/commands/workflow/run-facts.js +426 -0
  249. package/dist/commands/workflow/runs.js +144 -43
  250. package/dist/commands/workflow/runtime.js +12 -1
  251. package/dist/commands/workflow/status.js +130 -29
  252. package/dist/commands/workflow/step-table.js +276 -0
  253. package/dist/commands/workflow/steps.js +171 -80
  254. package/dist/commands/workflow/summary.js +275 -0
  255. package/dist/commands/workflow/tests.js +834 -136
  256. package/dist/commands/workflow/tracker.js +983 -0
  257. package/dist/commands/workflow/workflows.js +834 -195
  258. package/dist/commands/workflow/workstreams.js +11 -5
  259. package/dist/commands/workflow/worktrees.js +221 -22
  260. package/dist/install/manifest.js +11 -9
  261. package/dist/install/modules/cloud.js +22 -13
  262. package/dist/install/modules/core.js +326 -7
  263. package/dist/install/modules/opencode.js +2 -2
  264. package/dist/install/version-file.js +6 -2
  265. package/dist/ledgers/migrate.js +81 -0
  266. package/dist/ledgers/status.js +61 -8
  267. package/dist/ledgers/telemetry.js +905 -124
  268. package/dist/render/hosts.js +4 -0
  269. package/dist/render/models.js +12 -0
  270. package/dist/shared/branches.js +3 -1
  271. package/dist/shared/egress.js +7 -0
  272. package/dist/shared/json.js +20 -7
  273. package/dist/shared/settings.js +147 -26
  274. package/dist/shared/text.js +333 -0
  275. package/dist/tools/grammar-density.js +183 -0
  276. package/dist/tools/instructions-sources.js +721 -0
  277. package/dist/tools/instructions.js +1579 -0
  278. package/package.json +114 -23
  279. package/.bkit/core/engine/commands/harvest.ts +0 -459
  280. package/.bkit/core/engine/tools/wording.ts +0 -748
  281. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +0 -69
  282. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +0 -71
  283. package/.bkit/core/prompts/bkit-build-challenge-tests.md +0 -74
  284. package/.bkit/core/prompts/bkit-build-summary.md +0 -94
  285. package/.bkit/core/prompts/bkit-debug-summary.md +0 -96
  286. package/.bkit/core/prompts/bkit-design-summary.md +0 -107
  287. package/.bkit/core/prompts/bkit-plan-complexity-check.md +0 -67
  288. package/.bkit/core/prompts/bkit-plan-complexity-split.md +0 -88
  289. package/.bkit/core/prompts/bkit-plan-review-3.md +0 -93
  290. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +0 -85
  291. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +0 -85
  292. package/.bkit/core/prompts/bkit-plan-summary.md +0 -107
  293. package/.bkit/core/prompts/bkit-ship-summary.md +0 -78
  294. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.mjs +0 -138
  295. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.test.mjs +0 -181
  296. package/dist/commands/harvest.js +0 -353
  297. package/dist/tools/wording.js +0 -680
@@ -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,27 +17,30 @@
17
17
  // promote design / plan close: the highest versioned draft becomes the
18
18
  // canonical doc (anchor stamped, a superseded canonical archived).
19
19
  // links the feature docs and this workflow's logs on a ref, as markdown links.
20
+ // summary the Summary step: `{workflow}-summary.md` with its verdict, reasons and
21
+ // next command, from the run's rows, logs, plan and ledger rows.
20
22
 
21
23
  import * as fs from "node:fs";
24
+ import * as os from "node:os";
22
25
  import * as path from "node:path";
23
26
 
24
27
  import {
25
28
  appendLine,
26
29
  fold,
30
+ lastRun,
27
31
  runNumber,
28
32
  runOrStepField,
29
33
  statusTimestamp,
30
34
  type StatusEvent,
31
35
  } from "../../ledgers/status.js";
32
36
  import {
33
- appendLine as telemetryLine,
34
37
  foldFrom,
38
+ normalize,
35
39
  resolveRepoSlug,
36
- validate,
37
40
  workflowTelemetry,
38
41
  type CoverageStats,
42
+ type OutcomePayload,
39
43
  } from "../../ledgers/telemetry.js";
40
- import { readBkitVersion } from "../../install/version-file.js";
41
44
  import { readBkitConfig } from "../../shared/settings.js";
42
45
  import { gradeCompliance } from "../comply.js";
43
46
  import { landDir, pushToDev, type DevPush } from "../land.js";
@@ -63,10 +66,43 @@ import {
63
66
  AUTO_LABEL,
64
67
  AUTO_ROUTE_SUFFIX,
65
68
  buildComment,
69
+ issueParts,
70
+ parseComments,
71
+ sortOldestFirst,
66
72
  trackerState,
67
73
  transitionLabels,
74
+ type IssueComment,
75
+ type IssuePart,
68
76
  } from "./issues.js";
69
- import { EXIT_EMPTY, commitBookkeeping, unionLedgers } from "./ledgers.js";
77
+ import {
78
+ EXIT_EMPTY,
79
+ activeRecord,
80
+ commitBookkeeping,
81
+ ownPathCommit,
82
+ ownSet,
83
+ removeRecord,
84
+ appendLedgerRows,
85
+ runRows,
86
+ unionLedgers,
87
+ } from "./ledgers.js";
88
+ import { readIssueTracker } from "./fids.js";
89
+ import {
90
+ agentContextBlock,
91
+ buildBlock,
92
+ chatFingerprint,
93
+ ciList,
94
+ claudeTranscripts,
95
+ hostChat,
96
+ planBlock,
97
+ planFiles,
98
+ runChats,
99
+ runLines,
100
+ runStatusRows,
101
+ stepsBlock,
102
+ timeBlock,
103
+ } from "./run-facts.js";
104
+ import { buildSummary, refOf, SUMMARY_WORKFLOWS, type SummaryWorkflow } from "./summary.js";
105
+ import { parseWorkstreams } from "./workstreams.js";
70
106
  import {
71
107
  EXIT_REMOVE_FAILED,
72
108
  EXIT_SPLIT_BUCKET,
@@ -77,6 +113,7 @@ import {
77
113
  resolveMonth,
78
114
  workflowLockPath,
79
115
  } from "./locks.js";
116
+ import { highestVersion } from "./plan-versions.js";
80
117
  import { mergePr, probePr } from "./prs.js";
81
118
  import { FEATURE_STATUS } from "./roadmap.js";
82
119
  import {
@@ -88,8 +125,25 @@ import {
88
125
  readStatusRows,
89
126
  str,
90
127
  } from "./status.js";
91
- import { writeStepRow } from "./steps.js";
92
- import { removeWorktree, type RemoveResult } from "./worktrees.js";
128
+ import {
129
+ COMMENT_FILE_OUTPUT,
130
+ POST_FLAG,
131
+ TRACKER_OUTPUT,
132
+ attempt,
133
+ commentFileOf,
134
+ postForVerb,
135
+ issueRef,
136
+ readLabels,
137
+ endedRunActionKey,
138
+ skipOf,
139
+ trackerTarget,
140
+ writeLabels,
141
+ type TrackerOutcome,
142
+ } from "./tracker.js";
143
+ import type { TipsContext } from "../../cli.js";
144
+ import { tipsText } from "../tips.js";
145
+ import { EXIT_NO_RECORD, requireRecordOnShared, writeStepRow } from "./steps.js";
146
+ import { addAllButCopied, removeWorktree, type RemoveResult } from "./worktrees.js";
93
147
 
94
148
  /** Sentinels a workflow leaves in its logs folder; either one existing means a handover is due. */
95
149
  export const SENTINELS = [".rebase-failed", ".deferred-blocked"] as const;
@@ -104,6 +158,12 @@ export const EXIT_PUSH_FAILED = 10;
104
158
  export const EXIT_FLUSH_FAILED = 11;
105
159
  /** Exit code (promote): no versioned draft to promote. */
106
160
  export const EXIT_NO_VERSION = 12;
161
+ /** Exit code (input): a named input file is missing or not in the expected shape. */
162
+ export const EXIT_NO_INPUT = 13;
163
+ /** Exit code (start --branch): the checkout is not on the named branch. */
164
+ export const EXIT_WRONG_BRANCH = 15;
165
+ /** Exit code (summary): the status file has no run of the workflow. */
166
+ export const EXIT_NO_RUN = 16;
107
167
 
108
168
  // ---------------------------------------------------------------------------
109
169
  // Where things live
@@ -139,6 +199,92 @@ function whereInTree(
139
199
  }
140
200
 
141
201
  const headSha = (cwd: string) => git(cwd, ["rev-parse", "HEAD"]) ?? "";
202
+
203
+ /**
204
+ * Append a `session` row naming the chat that runs this start (`hostChat`), as its
205
+ * fingerprint, unless the current run's latest `session` row already names it. Nothing when
206
+ * the host names no chat. The close and the harvest read the run's chats from these rows.
207
+ */
208
+ export function recordChat(file: string, workflow: string, env: NodeJS.ProcessEnv): void {
209
+ const chat = hostChat(env);
210
+ if (chat === undefined) return;
211
+ const session = chatFingerprint(chat.platform, chat.id);
212
+ const events = readStatusEvents(file);
213
+ const startAt = lastOfType(events, "workflow-started", workflow)?.at;
214
+ const last = (events as Array<Record<string, unknown>>)
215
+ .filter(
216
+ (e) =>
217
+ e.type === "session" &&
218
+ e.workflow === workflow &&
219
+ (startAt === undefined || String(e.at) >= startAt),
220
+ )
221
+ .at(-1);
222
+ if (last?.session === session) return;
223
+ const row = {
224
+ type: "session",
225
+ workflow,
226
+ at: statusTimestamp(),
227
+ platform: chat.platform,
228
+ session,
229
+ };
230
+ fs.appendFileSync(file, appendLine(row));
231
+ }
232
+
233
+ /** An OPEN Decision Pause file of the current run, as `workflows start` prints it. */
234
+ export interface OpenDecision {
235
+ file: string;
236
+ decision: number;
237
+ question: string | null;
238
+ from: string | null;
239
+ pauseStep: number | null;
240
+ group: number | null;
241
+ verifyAttempt: number | null;
242
+ testAttempt: number | null;
243
+ plan: string | null;
244
+ }
245
+
246
+ /**
247
+ * The highest-numbered `{workflow}-decision-{run}-{N}.md` in `logDir` whose header holds
248
+ * `Status: OPEN`, or null. Only the given run's files count, so an earlier run's pause
249
+ * never resurfaces. `file` is relative to `tree`.
250
+ */
251
+ export function openDecision(
252
+ logDir: string,
253
+ tree: string,
254
+ workflow: string,
255
+ run: number,
256
+ ): OpenDecision | null {
257
+ if (!fs.existsSync(logDir)) return null;
258
+ const name = new RegExp(`^${workflow}-decision-${run}-([0-9]+)\\.md$`);
259
+ const found = fs
260
+ .readdirSync(logDir)
261
+ .map((f) => ({ f, m: name.exec(f) }))
262
+ .filter((x): x is { f: string; m: RegExpExecArray } => x.m !== null)
263
+ .map(({ f, m }) => ({ f, n: Number(m[1]) }))
264
+ .sort((a, b) => b.n - a.n);
265
+ for (const { f, n } of found) {
266
+ const text = fs.readFileSync(path.join(logDir, f), "utf-8");
267
+ const field = (key: string) =>
268
+ new RegExp(`^${key}:[ \\t]*(.+?)[ \\t]*$`, "m").exec(text)?.[1] ?? null;
269
+ if (field("Status") !== "OPEN") continue;
270
+ const num = (key: string) => {
271
+ const v = field(key);
272
+ return v !== null && /^[0-9]+$/.test(v) ? Number(v) : null;
273
+ };
274
+ return {
275
+ file: path.relative(tree, path.join(logDir, f)),
276
+ decision: n,
277
+ question: field("Question"),
278
+ from: field("From"),
279
+ pauseStep: num("Pause step"),
280
+ group: num("Group"),
281
+ verifyAttempt: num("Verify attempt"),
282
+ testAttempt: num("Test attempt"),
283
+ plan: field("Plan"),
284
+ };
285
+ }
286
+ return null;
287
+ }
142
288
  const logDirRel = (month: string, fid: string) => path.join("docs", "plans", month, "logs", fid);
143
289
  const list = (v: FlagValue) => (v as string[] | undefined) ?? [];
144
290
 
@@ -224,10 +370,10 @@ function failState(ctx: RunContext, workflow: string, fid: string) {
224
370
  fs.rmSync(p, { force: true });
225
371
  }
226
372
  }
227
- return { row, rebaseAborted, lock, sentinels, removeFailed, soak };
373
+ return { row, rebaseAborted, lock, sentinels, removeFailed, soak, status };
228
374
  }
229
375
 
230
- function failVerb(ctx: RunContext): number {
376
+ async function failVerb(ctx: RunContext): Promise<number> {
231
377
  const workflow = workflowName(String(ctx.flags.workflow));
232
378
  // An empty value is a placeholder not held yet (the failure came before it was set).
233
379
  const fid = str(ctx.flags.fid) || undefined;
@@ -246,6 +392,7 @@ function failVerb(ctx: RunContext): number {
246
392
  sentinels: [],
247
393
  removeFailed: false,
248
394
  soak: false,
395
+ status: undefined,
249
396
  }
250
397
  : failState(ctx, workflow, fid);
251
398
 
@@ -258,10 +405,15 @@ function failVerb(ctx: RunContext): number {
258
405
  }
259
406
  const merged = prState === "MERGED";
260
407
  const transition = merged ? { phase: "merged" } : { failed: true };
408
+ const failedSet = (current: string[]) => {
409
+ const labels = transitionLabels(current, transition).labels;
410
+ if (merged && !labels.includes("bkit:failed")) labels.push("bkit:failed");
411
+ return labels;
412
+ };
261
413
  const current = list(ctx.flags.label);
262
- const labels = transitionLabels(current, transition).labels;
263
- if (merged && !labels.includes("bkit:failed")) labels.push("bkit:failed");
414
+ const labels = failedSet(current);
264
415
  const add = labels.filter((l) => !current.includes(l));
416
+ const failedState = trackerState(transition, undefined, readBkitConfig(repoRoot(ctx.cwd)));
265
417
 
266
418
  // The failure comment, when the step is named.
267
419
  let comment: string | null = null;
@@ -279,6 +431,26 @@ function failVerb(ctx: RunContext): number {
279
431
  stderrFile: str(ctx.flags.stderrFile) || undefined,
280
432
  });
281
433
  }
434
+ if (ctx.flags.post === true && comment === null)
435
+ throw new CommandError(EXIT.USAGE, "--post needs --step-number");
436
+ // Once per run and step: an engine-action row where the run's status.jsonl exists.
437
+ const key = endedRunActionKey(
438
+ state.status,
439
+ workflow,
440
+ "failure",
441
+ stepNumber,
442
+ str(ctx.flags.subStep) || undefined,
443
+ );
444
+ const tracker =
445
+ ctx.flags.post === true && comment !== null
446
+ ? await postForVerb(ctx, comment, {
447
+ fid,
448
+ issue: str(ctx.flags.issue),
449
+ ...(key === undefined ? {} : { file: state.status, key }),
450
+ })
451
+ : undefined;
452
+ const labelsWrite =
453
+ ctx.flags.post === true ? await writeFailedLabels(ctx, fid, failedSet, failedState) : undefined;
282
454
 
283
455
  ctx.emit({
284
456
  row: state.row,
@@ -290,13 +462,42 @@ function failVerb(ctx: RunContext): number {
290
462
  (ctx.flags.maxExceeded === true || state.sentinels.length > 0 || state.soak),
291
463
  add,
292
464
  labels,
293
- trackerState: trackerState(transition, undefined, readBkitConfig(repoRoot(ctx.cwd))),
465
+ trackerState: failedState,
294
466
  prState,
295
467
  comment,
468
+ commentFile: commentFileOf(ctx.cwd, comment),
469
+ ...(tracker === undefined ? {} : { tracker }),
470
+ ...(labelsWrite === undefined ? {} : { labelsWrite }),
471
+ ...sessionRemoval(ctx),
296
472
  });
297
473
  return state.removeFailed ? EXIT_REMOVE_FAILED : EXIT.OK;
298
474
  }
299
475
 
476
+ /**
477
+ * `fail --post`: read the issue's labels, write the failed set and the review state.
478
+ * The set comes from the labels read, not `--label`, so a label added since Step 1 stays.
479
+ */
480
+ async function writeFailedLabels(
481
+ ctx: RunContext,
482
+ fid: string | undefined,
483
+ failedSet: (current: string[]) => string[],
484
+ state: string | null,
485
+ ): Promise<TrackerOutcome> {
486
+ const t = trackerTarget(ctx.cwd, { fid, issue: str(ctx.flags.issue) });
487
+ const skip = skipOf(t);
488
+ if (skip) return skip;
489
+ return attempt("labels", ctx.log, async () => {
490
+ const current = await readLabels(t);
491
+ const labels = failedSet(current);
492
+ await writeLabels(t, {
493
+ add: labels.filter((l) => !current.includes(l)),
494
+ remove: current.filter((l) => !labels.includes(l)),
495
+ labels,
496
+ state,
497
+ });
498
+ });
499
+ }
500
+
300
501
  /** A text file's content, trailing newlines dropped; a missing file is a usage error. */
301
502
  function readText(cwd: string, rel: string): string {
302
503
  const abs = path.resolve(cwd, rel);
@@ -353,12 +554,54 @@ const SHARED_LEDGERS = [
353
554
  ":(exclude).bkit/issues.jsonl",
354
555
  ];
355
556
 
557
+ /**
558
+ * Kinds no workflow run writes: bkit's harvest script writes them to `harvest/`, and a
559
+ * `run` row names any feature's workflow (`.bkit/jsonl.md` § Ledgers & Writers).
560
+ */
561
+ const NOT_A_RUNS_OWN_KIND = new Set(["chat", "run"]);
562
+
563
+ /** HEAD and every `parentSha` the run's status rows of `workflow` carry: the shas its `run.parentSha` can name. */
564
+ function runShas(src: string, status: string, workflow: string): Set<string> {
565
+ const shas = new Set<string>([headSha(src)]);
566
+ for (const e of fs.existsSync(status) ? readStatusEvents(status) : []) {
567
+ const sha = (e as Record<string, unknown>).parentSha;
568
+ if (e.workflow === workflow && typeof sha === "string") shas.add(sha);
569
+ }
570
+ shas.delete("");
571
+ return shas;
572
+ }
573
+
574
+ /** A feature id in `references`: a bare number or `{N}-{slug}`. */
575
+ const FEATURE_REF = /^\d+(-[a-z0-9-]+)?$/;
576
+
577
+ /**
578
+ * A shared-ledger row (normalized) of THIS run: a row of `workflow` at or after its
579
+ * start, never a kind no run writes. A row with `run.parentSha` (compliance, counter,
580
+ * outcome) must name one of the run's shas; any other row must not point at a
581
+ * different feature in its `references`.
582
+ */
583
+ function isRunsOwnRow(
584
+ row: Record<string, unknown>,
585
+ o: { fid: string; workflow: string; startMs: number | undefined },
586
+ shas: Set<string>,
587
+ ): boolean {
588
+ if (byWorkflow(row) !== o.workflow || !(Number(row.ts) >= o.startMs!)) return false;
589
+ if (NOT_A_RUNS_OWN_KIND.has(String(row.kind))) return false;
590
+ const sha = (row.run as Record<string, unknown> | undefined)?.parentSha;
591
+ if (sha !== undefined) return typeof sha === "string" && shas.has(sha);
592
+ const features = (Array.isArray(row.references) ? row.references : [])
593
+ .map(String)
594
+ .filter((r) => FEATURE_REF.test(r));
595
+ const n = /^(\d+)-/.exec(o.fid)?.[1];
596
+ return features.length === 0 || features.some((r) => r === o.fid || r === n);
597
+ }
598
+
356
599
  /**
357
600
  * Carry ONLY the run's own record out of a dev / main / detached checkout, which
358
601
  * other sessions and local-only commits share: the `.md` logs it wrote in its log
359
602
  * folder; the lines of that folder's `.jsonl` files its HEAD lacks; and, from the
360
- * shared ledgers, lines its HEAD lacks that are rows of `workflow` at or after
361
- * the run's start (`startMs`). No start known → no shared-ledger row is carried.
603
+ * shared ledgers, lines its HEAD lacks that are this run's rows ({@link isRunsOwnRow}).
604
+ * No start known → no shared-ledger row is carried.
362
605
  */
363
606
  function carryOwnBook(
364
607
  src: string,
@@ -368,12 +611,9 @@ function carryOwnBook(
368
611
  ): Carried {
369
612
  const rel = logDirRel(o.month, o.fid);
370
613
  const carried: Carried = { files: carryLogs(src, dst, rel), lines: new Map() };
371
- const uncommitted = (file: string) => {
372
- const head = new Set(textLines(git(src, ["show", `HEAD:${file}`]) ?? "").map((l) => l.trim()));
373
- return textLines(fs.readFileSync(path.join(src, file), "utf-8")).filter(
374
- (l) => !head.has(l.trim()),
375
- );
376
- };
614
+ // Rows the run appended; on a shared checkout, recorded foreign rows are never carried.
615
+ const rec = activeRecord(src, o.fid);
616
+ const uncommitted = (file: string) => runRows(src, file, rec);
377
617
  const add = (file: string, lines: string[]) => {
378
618
  const to = path.join(dst, file);
379
619
  const existing = fs.existsSync(to) ? fs.readFileSync(to, "utf-8") : "";
@@ -395,11 +635,11 @@ function carryOwnBook(
395
635
  log(`no ${o.workflow} start row for ${o.fid} — no shared-ledger row carried`);
396
636
  return carried;
397
637
  }
638
+ const shas = runShas(src, path.join(src, statusRelPath(o.month, o.fid)), o.workflow);
398
639
  for (const file of listed(SHARED_LEDGERS)) {
399
640
  const own = uncommitted(file).filter((l) => {
400
- const parsed = parseJson(l);
401
- const row = parsed.ok ? (parsed.value as Record<string, unknown> | null) : null;
402
- return row?.workflow === o.workflow && Number(row.ts) >= o.startMs!;
641
+ const row = parseObject(l);
642
+ return row !== undefined && isRunsOwnRow(normalize(row), o, shas);
403
643
  });
404
644
  if (own.length > 0) add(file, own);
405
645
  }
@@ -412,14 +652,23 @@ function carryOwnBook(
412
652
  * log identical to the landed copy is removed when untracked, or returns to HEAD
413
653
  * when tracked. A carried ledger loses exactly the carried lines; it returns to
414
654
  * HEAD when that leaves it equal, and an untracked one left empty is removed.
415
- * Anything staged, or a log changed since it landed, stays and is named.
655
+ * Anything staged, or a log changed since it landed, stays and is named. A path
656
+ * the shared-checkout record lists is never reset or removed.
416
657
  */
417
- function handBack(tree: string, sha: string, carried: Carried, log: (line: string) => void): void {
658
+ function handBack(
659
+ tree: string,
660
+ sha: string,
661
+ carried: Carried,
662
+ log: (line: string) => void,
663
+ recorded: ReadonlySet<string> = new Set(),
664
+ ): void {
418
665
  const back: string[] = [];
419
666
  const kept: string[] = [];
420
667
  const staged = (rel: string) => !runGit(tree, ["diff", "--cached", "--quiet", "--", rel]).ok;
421
668
  const tracked = (rel: string) => runGit(tree, ["ls-files", "--error-unmatch", "--", rel]).ok;
422
669
  for (const rel of carried.files) {
670
+ // A path that was dirty before the run started is not the run's to reset.
671
+ if (recorded.has(rel)) continue;
423
672
  const abs = path.join(tree, rel);
424
673
  const landed = runGit(tree, ["show", `${sha}:${rel}`]);
425
674
  const same =
@@ -566,6 +815,20 @@ async function landFailedRecord(
566
815
  }
567
816
  }
568
817
 
818
+ /**
819
+ * What `handover --push` would sweep into the abort commit besides the run's own
820
+ * logs: tracked files with changes, and untracked files (each one listed, not its folder).
821
+ */
822
+ function strayPaths(tree: string, logDir: string): { modified: string[]; untracked: string[] } {
823
+ const outside = (out: string | null) =>
824
+ (out ?? "").split("\0").filter((p) => p !== "" && p !== logDir && !p.startsWith(`${logDir}/`));
825
+ return {
826
+ // Staged and unstaged changes alike, against HEAD.
827
+ modified: outside(git(tree, ["diff", "--name-only", "-z", "--no-renames", "HEAD"])),
828
+ untracked: outside(git(tree, ["ls-files", "-z", "--others", "--exclude-standard"])),
829
+ };
830
+ }
831
+
569
832
  async function handoverVerb(ctx: RunContext): Promise<number> {
570
833
  const workflow = workflowName(String(ctx.flags.workflow));
571
834
  const fid = String(ctx.flags.fid);
@@ -589,7 +852,17 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
589
852
  const branch = git(tree, ["branch", "--show-current"]) ?? "";
590
853
  // A dev / main / detached checkout is shared: only the run's own record leaves it.
591
854
  const shared = branch === "" || isSharedBranch(branch);
855
+ if (ctx.flags.listStray === true) {
856
+ if (push || flush || ctx.flags.post === true)
857
+ throw new CommandError(
858
+ EXIT.USAGE,
859
+ "--list-stray only lists: drop --push, --flush and --post",
860
+ );
861
+ ctx.emit({ shared, ...strayPaths(tree, logDirRel(month, fid)) });
862
+ return EXIT.OK;
863
+ }
592
864
  let handed: { sha: string; carried: Carried } | undefined;
865
+ const rec = shared && (push || flush) ? activeRecord(tree, fid) : null;
593
866
  if (push && shared) {
594
867
  const r = await landFailedRecord(ctx, { workflow, fid, month, book: tree, shared });
595
868
  if (r.sha !== undefined && r.carried !== undefined) handed = { sha: r.sha, carried: r.carried };
@@ -598,10 +871,10 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
598
871
  ref = r.ref;
599
872
  skipped = r.skipped;
600
873
  } else if (push) {
601
- runGit(tree, ["add", "-A"]);
874
+ addAllButCopied(tree);
602
875
  const made = runGit(tree, ["commit", "-m", `docs(${fid}): ${workflow} aborted bkit [skip ci]`]);
603
876
  if (!made.ok) ctx.log(`abort commit: ${made.stderr || made.stdout}`);
604
- const r = pushBranch(tree, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
877
+ const r = await pushBranch(tree, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
605
878
  if (r.code === EXIT.USE_MCP) return r.code;
606
879
  pushed = r.out.pushed;
607
880
  ref = r.out.ref;
@@ -631,13 +904,23 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
631
904
  bodyFile: artifact,
632
905
  })
633
906
  : null;
634
- if (handed !== undefined) handBack(tree, handed.sha, handed.carried, ctx.log);
907
+ if (handed !== undefined) {
908
+ handBack(tree, handed.sha, handed.carried, ctx.log, new Set(rec?.paths.map((p) => p.path)));
909
+ }
910
+ // The run is over once its record is handed back: the next run starts a fresh one.
911
+ if (rec !== null) removeRecord(tree, fid);
912
+ const tracker =
913
+ ctx.flags.post === true && comment !== null
914
+ ? await postForVerb(ctx, comment, { fid })
915
+ : undefined;
635
916
  ctx.emit({
636
917
  handover: present ? artifact : null,
637
918
  pushed,
638
919
  ref: pushed ? ref : null,
639
920
  skipped,
640
921
  comment,
922
+ commentFile: commentFileOf(ctx.cwd, comment),
923
+ ...(tracker === undefined ? {} : { tracker }),
641
924
  });
642
925
  return code;
643
926
  }
@@ -646,16 +929,14 @@ async function handoverVerb(ctx: RunContext): Promise<number> {
646
929
  // close
647
930
  // ---------------------------------------------------------------------------
648
931
 
649
- interface Ledgers {
650
- frictionAdded?: number;
651
- deferralsAdded?: number;
652
- failuresAdded?: number;
653
- deferrals: number;
654
- failures: number;
655
- }
932
+ type Ledgers = OutcomePayload["ledgers"];
933
+
934
+ /** The row's `by.workflow`, on a row already normalized. */
935
+ const byWorkflow = (r: Record<string, unknown>) =>
936
+ (r.by as Record<string, unknown> | undefined)?.workflow;
656
937
 
657
938
  /** Rows of a JSONL ledger; malformed lines are skipped, a missing file is empty. */
658
- function ledgerRows(file: string): Array<Record<string, unknown>> {
939
+ export function ledgerRows(file: string): Array<Record<string, unknown>> {
659
940
  if (!fs.existsSync(file)) return [];
660
941
  return fs
661
942
  .readFileSync(file, "utf-8")
@@ -688,49 +969,31 @@ const distinctKeys = (rows: Array<Record<string, unknown>>) =>
688
969
  * counting the ledger's whole history as this run's.
689
970
  */
690
971
  function ledgerCounts(tree: string, workflow: string, startMs: number | undefined): Ledgers {
691
- const deferrals = ledgerRows(path.join(tree, "docs", "deferrals.jsonl"));
692
- const failures = ledgerRows(path.join(tree, "docs", "failures.jsonl"));
693
- const friction = ledgerRows(path.join(tree, ".bkit", "friction.jsonl"));
972
+ const read = (file: string) => ledgerRows(file).map((r) => normalize(r));
973
+ const deferrals = read(path.join(tree, "docs", "deferrals.jsonl"));
974
+ const failures = read(path.join(tree, "docs", "failures.jsonl"));
975
+ const friction = read(path.join(tree, ".bkit", "friction.jsonl"));
694
976
  const added = (rows: Array<Record<string, unknown>>) =>
695
- distinctKeys(rows.filter((r) => r.workflow === workflow && Number(r.ts) >= startMs!));
696
- return {
697
- deferrals: distinctKeys(deferrals.filter((r) => r.kind === "deferral")),
698
- failures: distinctKeys(failures.filter((r) => r.kind === "failure")),
699
- ...(startMs === undefined
977
+ startMs === undefined
700
978
  ? {}
701
979
  : {
702
- frictionAdded: added(friction),
703
- deferralsAdded: added(deferrals),
704
- failuresAdded: added(failures),
705
- }),
706
- };
707
- }
708
-
709
- /** `git diff --shortstat` numbers; 0 for anything absent or a range git rejects. */
710
- export function diffStat(cwd: string, range: string) {
711
- const out = runGit(cwd, ["diff", "--shortstat", range]).stdout;
712
- const num = (re: RegExp) => Number(re.exec(out)?.[1] ?? 0);
713
- const linesAdded = num(/(\d+) insertions?\(/);
714
- const linesDeleted = num(/(\d+) deletions?\(/);
980
+ added: distinctKeys(
981
+ rows.filter((r) => byWorkflow(r) === workflow && Number(r.ts) >= startMs),
982
+ ),
983
+ };
715
984
  return {
716
- linesAdded,
717
- linesDeleted,
718
- linesChanged: linesAdded + linesDeleted,
719
- filesChanged: num(/(\d+) files? changed/),
985
+ deferrals: {
986
+ repo: distinctKeys(deferrals.filter((r) => r.kind === "deferral")),
987
+ ...added(deferrals),
988
+ },
989
+ failures: {
990
+ repo: distinctKeys(failures.filter((r) => r.kind === "failure")),
991
+ ...added(failures),
992
+ },
993
+ friction: added(friction),
720
994
  };
721
995
  }
722
996
 
723
- /** Checklist items (`- [`) across the feature's plan and sub-plans. */
724
- function taskCount(tree: string, month: string, fid: string): number {
725
- const dir = path.join(tree, "docs", "plans", month);
726
- if (!fs.existsSync(dir)) return 0;
727
- return fs
728
- .readdirSync(dir)
729
- .filter((f) => f.startsWith(`${fid}-plan`) && f.endsWith(".md"))
730
- .flatMap((f) => fs.readFileSync(path.join(dir, f), "utf-8").split("\n"))
731
- .filter((l) => l.startsWith("- [")).length;
732
- }
733
-
734
997
  /** Per-tier coverage from `coverage/{tier}/coverage-summary.json`; undefined when none. */
735
998
  function coverage(tree: string): Record<string, CoverageStats> | undefined {
736
999
  const out: Record<string, CoverageStats> = {};
@@ -758,20 +1021,14 @@ function lastOfType(events: StatusEvent[], type: string, workflow: string) {
758
1021
  .at(-1) as (StatusEvent & Record<string, unknown>) | undefined;
759
1022
  }
760
1023
 
761
- /** Append telemetry rows; best-effort, so a bad path is logged and never fails the close. */
762
- function appendStats(file: string, rows: Array<Record<string, unknown>>, log: (m: string) => void) {
763
- const valid = rows.filter((r) => {
764
- const v = validate(r);
765
- if (!v.ok) log(`[bkit-telemetry] ${String(r.kind)} row invalid, not written: ${v.reason}`);
766
- return v.ok;
767
- });
768
- if (valid.length === 0) return false;
1024
+ /** Append the close's stats rows; best-effort, so a refused row or a bad path is logged and never fails the close. */
1025
+ function appendStats(tree: string, rows: Array<Record<string, unknown>>, log: (m: string) => void) {
769
1026
  try {
770
- fs.appendFileSync(file, valid.map((r) => `${telemetryLine(r as never)}\n`).join(""));
1027
+ appendLedgerRows(tree, "stats", rows);
771
1028
  return true;
772
1029
  } catch (err) {
773
- // Telemetry never gates a close: report the failed append and carry on.
774
- log(`[bkit-telemetry] append failed: ${file} — ${(err as Error).message}`);
1030
+ // Telemetry never gates a close: report the refused append and carry on.
1031
+ log(`[bkit-telemetry] stats rows not written: ${(err as Error).message}`);
775
1032
  return false;
776
1033
  }
777
1034
  }
@@ -851,7 +1108,8 @@ export interface CloseInput {
851
1108
  * Grade compliance, append the workflow-done row (and, with `recordStep`, the
852
1109
  * close step's row first), the counter and outcome telemetry rows, and build the
853
1110
  * report and artifact links; with `outbox`, write them for the close comment; with
854
- * `message`, commit everything (`git add -A`) in the tree.
1111
+ * `message`, commit everything (`git add -A`, minus the `bkit.workflows.worktree.copy` entries) in the tree, or, in an in-place run
1112
+ * on a shared branch, only the run's own paths.
855
1113
  */
856
1114
  export function closeWorkflow(
857
1115
  cwd: string,
@@ -864,10 +1122,18 @@ export function closeWorkflow(
864
1122
  if (o.squashSha !== undefined && !/^[0-9a-f]{7,40}$/.test(o.squashSha))
865
1123
  throw new CommandError(EXIT.USAGE, `--squash-sha "${o.squashSha}" is not a commit sha`);
866
1124
 
867
- // Graded first, so the report below carries this run's grade.
868
- const violations = gradeCompliance(where.tree, workflow, log, o.squashSha);
1125
+ // An in-place run on a shared branch commits its own paths only; a refusal
1126
+ // comes before any row is appended, so the re-run after the human's fix writes each row once.
1127
+ const rec = o.message === undefined ? null : activeRecord(where.tree, o.fid);
1128
+ if (o.message !== undefined) requireRecordOnShared(where.tree, workflow, rec);
1129
+ if (rec !== null) ownSet(where.tree, rec);
869
1130
 
870
1131
  const step = `${workflow}-close-workflow`;
1132
+ // The run's join key: every row of this run carries HEAD at close as `run.parentSha`.
1133
+ const parentSha = headSha(where.tree);
1134
+ // Graded first, so the report below carries this run's grade.
1135
+ const violations = gradeCompliance(where.tree, workflow, log, o.squashSha, { parentSha, step });
1136
+
871
1137
  if (o.recordStep === true) {
872
1138
  writeStepRow(
873
1139
  where.tree,
@@ -875,70 +1141,85 @@ export function closeWorkflow(
875
1141
  log,
876
1142
  );
877
1143
  }
878
- const row = { type: "workflow-done" as const, workflow, at: statusTimestamp() };
1144
+ const endAt = statusTimestamp();
1145
+ const row = { type: "workflow-done" as const, workflow, at: endAt, parentSha };
879
1146
  fs.appendFileSync(where.status, appendLine(row));
880
1147
 
881
1148
  const repo = resolveRepoSlug(where.root) || "unknown/repo";
882
- const bkitVersion =
883
- readBkitVersion(path.join(where.root, ".bkit", "version"))?.pinnedVersion || "unknown";
884
- const parentSha = headSha(where.tree);
885
1149
  const started = lastOfType(events, "workflow-started", workflow);
886
1150
  const startAt = started?.at;
887
1151
  const startMs = startAt ? Date.parse(startAt) : NaN;
888
1152
  const startKnown = Number.isFinite(startMs) ? startMs : undefined;
889
- const planSource = events
890
- .filter(
891
- (e) =>
892
- e.type === "workflow-meta" &&
893
- e.workflow === workflow &&
894
- (startAt === undefined || e.at >= startAt) &&
895
- (e as Record<string, unknown>).planSource,
896
- )
897
- .at(-1) as Record<string, unknown> | undefined;
1153
+ const runRowsOf =
1154
+ startAt === undefined ? [] : runStatusRows(readStatusEvents(where.status), workflow, startAt);
898
1155
  const base = typeof started?.parentSha === "string" ? started.parentSha : "";
899
- const range = o.squashSha
900
- ? `${o.squashSha}^..${o.squashSha}`
901
- : base
902
- ? `${base}..HEAD`
903
- : "origin/dev...HEAD";
904
- const durationSeconds =
905
- startKnown === undefined ? 0 : Math.max(0, Math.floor((Date.now() - startKnown) / 1000));
1156
+ const lines = o.squashSha
1157
+ ? runLines(where.tree, `${o.squashSha}^`, o.squashSha)
1158
+ : runLines(where.tree, base, parentSha);
906
1159
  const startedRows = new Set(
907
1160
  events.filter((e) => e.type === "workflow-started" && e.workflow === workflow).map((e) => e.at),
908
1161
  ).size;
909
- const ts = Date.now();
1162
+ const logDir = path.join(where.tree, logDirRel(where.month, o.fid));
1163
+ const by = { workflow, step };
910
1164
 
911
1165
  const counterRow = {
912
- ts,
913
1166
  kind: "counter",
914
- workflow,
915
- repo,
916
- bkitVersion,
917
- step,
918
- counterName: `${workflow.toUpperCase()}_ATTEMPT`,
919
- counterValue: Math.max(1, startedRows),
920
- counterSource: "shell-bus",
921
- parentSha,
1167
+ by,
1168
+ run: { parentSha },
1169
+ counter: {
1170
+ name: `${workflow.toUpperCase()}_ATTEMPT`,
1171
+ value: Math.max(1, startedRows),
1172
+ source: "shell-bus",
1173
+ },
922
1174
  };
923
1175
  const cov = workflow === "ship" ? coverage(where.tree) : undefined;
1176
+ const ci = ciList(runRowsOf);
1177
+ const plan = ["plan", "build", "ship"].includes(workflow)
1178
+ ? planBlock(where.tree, where.month, o.fid, events)
1179
+ : undefined;
1180
+ const endMs = Date.parse(endAt);
1181
+ /** This run's `docs/deferrals.jsonl` rows; none when its start is unknown. */
1182
+ const runDeferrals = () =>
1183
+ startKnown === undefined
1184
+ ? []
1185
+ : ledgerRows(path.join(where.tree, "docs", "deferrals.jsonl"))
1186
+ .map((r) => normalize(r))
1187
+ .filter((r) => byWorkflow(r) === workflow && Number(r.ts) >= startKnown);
1188
+ const context =
1189
+ startKnown === undefined
1190
+ ? undefined
1191
+ : agentContextBlock(
1192
+ startKnown,
1193
+ endMs,
1194
+ claudeTranscripts(process.env, os.homedir()),
1195
+ runChats(runRowsOf),
1196
+ );
924
1197
  const outcomeRow = {
925
- ts: ts + 1,
926
1198
  kind: "outcome",
927
- workflow,
928
- repo,
929
- bkitVersion,
930
- step,
931
- parentSha,
932
- ...(o.prNumber === undefined ? {} : { prNumber: o.prNumber }),
933
- ...diffStat(where.tree, range),
934
- taskCount: taskCount(where.tree, where.month, o.fid),
935
- durationSeconds,
936
- ...ledgerCounts(where.tree, workflow, startKnown),
937
- ...(planSource?.planSource ? { planSource: planSource.planSource } : {}),
938
- ...(cov ? { coverage: cov } : {}),
1199
+ by,
1200
+ run: { parentSha, ...(o.prNumber === undefined ? {} : { pr: o.prNumber }) },
1201
+ time: startKnown === undefined ? null : timeBlock(startKnown, Math.max(startKnown, endMs)),
1202
+ ending: "done",
1203
+ lines,
1204
+ ...(runRowsOf.length > 0 ? { steps: stepsBlock(runRowsOf) } : {}),
1205
+ ...(ci.length > 0 ? { ci } : {}),
1206
+ ledgers: ledgerCounts(where.tree, workflow, startKnown),
1207
+ ...(plan === undefined ? {} : { plan }),
1208
+ ...(workflow === "build"
1209
+ ? {
1210
+ build: buildBlock(
1211
+ runRowsOf,
1212
+ logDir,
1213
+ planFiles(where.tree, where.month, o.fid),
1214
+ runDeferrals(),
1215
+ ),
1216
+ }
1217
+ : {}),
1218
+ ...(context === undefined ? {} : { context }),
1219
+ ...(cov ? { ship: { coverage: cov } } : {}),
939
1220
  };
940
1221
  const stats = path.join(where.tree, ".bkit", "stats.jsonl");
941
- const telemetryWritten = appendStats(stats, [counterRow, outcomeRow], log);
1222
+ const telemetryWritten = appendStats(where.tree, [counterRow, outcomeRow], log);
942
1223
 
943
1224
  const report = fs.existsSync(stats)
944
1225
  ? workflowTelemetry(foldFrom([stats]), workflow).lines
@@ -988,17 +1269,23 @@ export function closeWorkflow(
988
1269
  )
989
1270
  message += " bkit [verbose ci]";
990
1271
  if ((o.labels ?? []).includes(AUTO_LABEL)) message += AUTO_ROUTE_SUFFIX;
991
- const add = runGit(where.tree, ["add", "-A"]);
992
- const made = add.ok ? runGit(where.tree, ["commit", "--allow-empty", "-m", message]) : add;
993
- if (!made.ok)
994
- throw new CommandError(EXIT.NO, `close commit failed: ${made.stderr || made.stdout}`);
1272
+ if (rec !== null) {
1273
+ const made = ownPathCommit(where.tree, rec, message, { allowEmpty: true });
1274
+ if (!made.ok) throw new CommandError(EXIT.NO, `close commit failed: ${made.error}`);
1275
+ } else {
1276
+ const add = addAllButCopied(where.tree);
1277
+ const made = add.ok ? runGit(where.tree, ["commit", "--allow-empty", "-m", message]) : add;
1278
+ if (!made.ok)
1279
+ throw new CommandError(EXIT.NO, `close commit failed: ${made.stderr || made.stdout}`);
1280
+ }
995
1281
  commit = headSha(where.tree);
996
1282
  }
997
1283
 
998
1284
  return {
999
1285
  row,
1000
- counterRow: validate(counterRow).ok ? counterRow : null,
1001
- outcomeRow: validate(outcomeRow).ok ? outcomeRow : null,
1286
+ // The rows as drafted; the ledger copies add the top section `ledgers append` fills.
1287
+ counterRow: telemetryWritten ? counterRow : null,
1288
+ outcomeRow: telemetryWritten ? outcomeRow : null,
1002
1289
  telemetryWritten,
1003
1290
  compliance: violations === null ? null : violations.length,
1004
1291
  report,
@@ -1165,20 +1452,6 @@ async function shipClose(
1165
1452
  // promote
1166
1453
  // ---------------------------------------------------------------------------
1167
1454
 
1168
- /** The highest `{workflow}-v{N}-*.md` draft (sub-plan children `-v{N}-{k}.md` excluded), or null. */
1169
- export function highestVersion(dir: string, workflow: string): { file: string; n: number } | null {
1170
- if (!fs.existsSync(dir)) return null;
1171
- const re = new RegExp(`^${workflow}-v([0-9]+)-(.+)\\.md$`);
1172
- let best: { file: string; n: number } | null = null;
1173
- for (const f of fs.readdirSync(dir).sort()) {
1174
- const m = re.exec(f);
1175
- if (!m || /^[0-9]+$/.test(m[2]!)) continue;
1176
- const n = Number(m[1]);
1177
- if (best === null || n > best.n) best = { file: f, n };
1178
- }
1179
- return best;
1180
- }
1181
-
1182
1455
  /** Stamp `file`'s anchor when a base commit is known (plan: with its design's own anchor; both: the bkit release). */
1183
1456
  function stamp(cwd: string, file: string, baseSha: string, design?: string): void {
1184
1457
  if (baseSha === "") return;
@@ -1208,7 +1481,7 @@ function promoteVerb(ctx: RunContext): number {
1208
1481
  }
1209
1482
  const final = path.join(logs, best.file);
1210
1483
  if (ctx.flags.resolve === true) {
1211
- ctx.emit({ final, canonical: null, archived: [], subPlans: [], baseSha: null });
1484
+ ctx.emit({ final, canonical: null, archived: [], baseSha: null });
1212
1485
  return EXIT.OK;
1213
1486
  }
1214
1487
 
@@ -1229,15 +1502,8 @@ function promoteVerb(ctx: RunContext): number {
1229
1502
  const bucket = path.join("docs", "plans", month);
1230
1503
  const canonical = path.join(bucket, `${fid}-${workflow}.md`);
1231
1504
  stamp(ctx.cwd, final, baseSha, design);
1232
- const children =
1233
- workflow === "plan"
1234
- ? fs
1235
- .readdirSync(path.resolve(ctx.cwd, logs))
1236
- .filter((f) => new RegExp(`^plan-v${best.n}-[0-9]+\\.md$`).test(f))
1237
- .sort()
1238
- : [];
1239
-
1240
- // A changed canonical moves to archive/ first — plan moves the whole set under one timestamp.
1505
+
1506
+ // A changed canonical moves to archive/ first.
1241
1507
  const archived: string[] = [];
1242
1508
  const canonicalAbs = path.resolve(ctx.cwd, canonical);
1243
1509
  if (
@@ -1250,47 +1516,116 @@ function promoteVerb(ctx: RunContext): number {
1250
1516
  .replace(/\.\d+Z$/, "Z");
1251
1517
  const archive = path.join(bucket, "archive");
1252
1518
  fs.mkdirSync(path.resolve(ctx.cwd, archive), { recursive: true });
1253
- const set = fs
1254
- .readdirSync(path.resolve(ctx.cwd, bucket))
1255
- .filter((f) =>
1256
- workflow === "plan"
1257
- ? f === `${fid}-plan.md` || new RegExp(`^${fid}-plan-[0-9]+\\.md$`).test(f)
1258
- : f === `${fid}-design.md`,
1259
- );
1260
- for (const f of set) {
1261
- const to = path.join(archive, `${ts}-${f}`);
1262
- fs.renameSync(path.resolve(ctx.cwd, bucket, f), path.resolve(ctx.cwd, to));
1263
- archived.push(to);
1264
- }
1519
+ const to = path.join(archive, `${ts}-${fid}-${workflow}.md`);
1520
+ fs.renameSync(canonicalAbs, path.resolve(ctx.cwd, to));
1521
+ archived.push(to);
1265
1522
  }
1266
1523
  fs.mkdirSync(path.resolve(ctx.cwd, bucket), { recursive: true });
1267
1524
  fs.copyFileSync(path.resolve(ctx.cwd, final), canonicalAbs);
1268
- const subPlans: string[] = [];
1269
- for (const child of children) {
1270
- const k = /-([0-9]+)\.md$/.exec(child)![1]!;
1271
- stamp(ctx.cwd, path.join(logs, child), baseSha, design);
1272
- const to = path.join(bucket, `${fid}-plan-${k}.md`);
1273
- fs.copyFileSync(path.resolve(ctx.cwd, logs, child), path.resolve(ctx.cwd, to));
1274
- subPlans.push(to);
1275
- }
1276
- if (workflow === "plan") {
1277
- // Working names in the copies become the canonical names.
1278
- for (const f of [canonical, ...subPlans]) {
1279
- const abs = path.resolve(ctx.cwd, f);
1280
- fs.writeFileSync(
1281
- abs,
1282
- fs
1283
- .readFileSync(abs, "utf-8")
1284
- .replace(/plan-v[0-9]+-split\.md/g, `${fid}-plan.md`)
1285
- .replace(/plan-v[0-9]+-([0-9]+)\.md/g, `${fid}-plan-$1.md`),
1286
- );
1287
- }
1288
- }
1289
1525
  if (fs.statSync(canonicalAbs).size === 0) {
1290
1526
  ctx.log(`canonical empty: ${canonical}`);
1291
1527
  return EXIT_NO_VERSION;
1292
1528
  }
1293
- ctx.emit({ final, canonical, archived, subPlans, baseSha: baseSha || null });
1529
+ ctx.emit({ final, canonical, archived, baseSha: baseSha || null });
1530
+ return EXIT.OK;
1531
+ }
1532
+
1533
+ // ---------------------------------------------------------------------------
1534
+ // summary
1535
+ // ---------------------------------------------------------------------------
1536
+
1537
+ /** ship: the PR's size from `gh pr view`; undefined (logged) when gh cannot answer. */
1538
+ function prSize(cwd: string, pr: number, log: (m: string) => void) {
1539
+ const res = runGh(cwd, ["pr", "view", String(pr), "--json", "additions,deletions,changedFiles"]);
1540
+ const parsed = res.ok ? parseJson(res.stdout) : undefined;
1541
+ const v = parsed?.ok === true ? (parsed.value as Record<string, unknown>) : undefined;
1542
+ if (
1543
+ typeof v?.additions !== "number" ||
1544
+ typeof v.deletions !== "number" ||
1545
+ typeof v.changedFiles !== "number"
1546
+ ) {
1547
+ log(`gh pr view ${pr} gave no size; the summary leaves the PR line out`);
1548
+ return undefined;
1549
+ }
1550
+ return {
1551
+ number: pr,
1552
+ additions: v.additions,
1553
+ deletions: v.deletions,
1554
+ changedFiles: v.changedFiles,
1555
+ };
1556
+ }
1557
+
1558
+ function summaryVerb(ctx: RunContext): number {
1559
+ const workflow = String(ctx.flags.workflow);
1560
+ if (!(SUMMARY_WORKFLOWS as readonly string[]).includes(workflow))
1561
+ throw new CommandError(EXIT.USAGE, `--workflow must be ${SUMMARY_WORKFLOWS.join(", ")}`);
1562
+ const file = path.resolve(ctx.cwd, String(ctx.flags.file));
1563
+ const logDir = path.dirname(file);
1564
+ const fid = path.basename(logDir);
1565
+ const month = path.basename(path.dirname(path.dirname(logDir)));
1566
+ const tree = path.resolve(logDir, "..", "..", "..", "..", "..");
1567
+ if (!/^[0-9]{6}$/.test(month) || path.join(tree, logDirRel(month, fid)) !== logDir)
1568
+ throw new CommandError(
1569
+ EXIT.USAGE,
1570
+ `--file must be docs/plans/{YYYYMM}/logs/{FID}/status.jsonl, got ${file}`,
1571
+ );
1572
+
1573
+ const events = readStatusEvents(file);
1574
+ const started = lastOfType(events, "workflow-started", workflow);
1575
+ if (started === undefined)
1576
+ throw new CommandError(EXIT_NO_RUN, `${file} has no ${workflow} run (no workflow-started row)`);
1577
+ const rows = runStatusRows(events, workflow, started.at);
1578
+ const startMs = Date.parse(started.at);
1579
+ const rel = (abs: string) => path.relative(tree, abs).split(path.sep).join("/");
1580
+ const given = list(ctx.flags.plan).map((p) => path.resolve(ctx.cwd, p));
1581
+ const plans = given.length > 0 ? given : workflow === "build" ? planFiles(tree, month, fid) : [];
1582
+ const read = (r: string) => {
1583
+ const abs = path.resolve(tree, r);
1584
+ return fs.existsSync(abs) && fs.statSync(abs).isFile() ? fs.readFileSync(abs, "utf-8") : null;
1585
+ };
1586
+ const deferrals = ledgerRows(path.join(tree, "docs", "deferrals.jsonl"))
1587
+ .map((r) => normalize(r))
1588
+ .filter((r) => byWorkflow(r) === workflow && Number(r.ts) >= startMs);
1589
+ const organisedPath = path.join(logDir, "design-v3-organised.md");
1590
+ const organised =
1591
+ workflow === "design" && fs.existsSync(organisedPath)
1592
+ ? fs.readFileSync(organisedPath, "utf-8")
1593
+ : undefined;
1594
+ const prNumber = positiveInt(ctx.flags.pr, "pr");
1595
+
1596
+ const summary = buildSummary({
1597
+ workflow: workflow as SummaryWorkflow,
1598
+ fid,
1599
+ ref: refOf(fid, readIssueTracker(tree)),
1600
+ rows,
1601
+ plans: plans.map((p) => ({ path: rel(p), text: fs.readFileSync(p, "utf-8") })),
1602
+ deferrals,
1603
+ deferralsAdded: ledgerCounts(tree, workflow, startMs).deferrals.added ?? 0,
1604
+ decisionFiles:
1605
+ (workflow === "build" || workflow === "ship") && fs.existsSync(logDir)
1606
+ ? fs
1607
+ .readdirSync(logDir)
1608
+ .filter((f) => /^build-decision-.*\.md$/.test(f))
1609
+ .sort()
1610
+ .map((f) => rel(path.join(logDir, f)))
1611
+ : [],
1612
+ read,
1613
+ workstreams: organised === undefined ? undefined : parseWorkstreams(organised),
1614
+ organised,
1615
+ pr:
1616
+ workflow === "ship" && prNumber !== undefined
1617
+ ? prSize(ctx.cwd, prNumber, ctx.log)
1618
+ : undefined,
1619
+ });
1620
+ const out = path.join(logDir, `${workflow}-summary.md`);
1621
+ fs.writeFileSync(out, summary.markdown);
1622
+ ctx.emit({
1623
+ verdict: summary.verdict,
1624
+ failures: summary.failures,
1625
+ reasons: summary.reasons,
1626
+ file: rel(out),
1627
+ nextStep: summary.nextStep,
1628
+ });
1294
1629
  return EXIT.OK;
1295
1630
  }
1296
1631
 
@@ -1322,11 +1657,247 @@ const OWNER_REPO_FLAG: FlagSpec = {
1322
1657
  const COMMENT_FLAGS: FlagSpec[] = [
1323
1658
  { name: "number", type: "string", help: "step number: print the close comment (needs --outbox)" },
1324
1659
  { name: "title", type: "string", help: "step title of the close comment" },
1660
+ {
1661
+ ...POST_FLAG,
1662
+ 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`",
1663
+ },
1325
1664
  ];
1326
1665
 
1666
+ const SESSION_DIR_FLAG: FlagSpec = {
1667
+ name: "session-dir",
1668
+ type: "string",
1669
+ help: "the run's session folder (`repo info` sessionDir): deleted once this run ends",
1670
+ };
1671
+ const SESSION_REMOVED_OUTPUT =
1672
+ "with --session-dir: the folder was deleted (false: not under <git common dir>/bkit-outbox/sessions/, kept)";
1673
+
1674
+ /**
1675
+ * `--session-dir`: delete the run's session folder. Only a folder directly under
1676
+ * `<git common dir>/bkit-outbox/sessions/` is deleted; any other path is kept and logged.
1677
+ */
1678
+ function sessionRemoval(ctx: RunContext): { sessionRemoved?: boolean } {
1679
+ const given = str(ctx.flags.sessionDir);
1680
+ if (!given) return {};
1681
+ const common = git(ctx.cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
1682
+ const real = (p: string) => (fs.existsSync(p) ? fs.realpathSync(p) : p);
1683
+ const sessions = common === null ? null : real(path.join(common, "bkit-outbox", "sessions"));
1684
+ const abs = path.resolve(ctx.cwd, given);
1685
+ if (sessions === null || real(path.dirname(abs)) !== sessions) {
1686
+ ctx.log(
1687
+ `--session-dir ${given} is not a session folder under ${sessions ?? "the outbox"}; kept`,
1688
+ );
1689
+ return { sessionRemoved: false };
1690
+ }
1691
+ fs.rmSync(abs, { recursive: true, force: true });
1692
+ return { sessionRemoved: true };
1693
+ }
1694
+
1695
+ const PLAIN_ENGLISH_REPLY =
1696
+ "Would you like me to explain any of this in plain English? Then write 'yes, explain in plain english'.";
1697
+
1698
+ /**
1699
+ * `--final-return`: the run's last message, read up front (the close may remove the tree
1700
+ * holding the summary, and `--session-dir` the issue facts). Tips are added at print time.
1701
+ */
1702
+ function finalReturnParts(ctx: RunContext, fid: string): string[] | null {
1703
+ if (ctx.flags.finalReturn !== true) return null;
1704
+ const summaryFile = str(ctx.flags.summaryFile);
1705
+ const summary = str(ctx.flags.summary);
1706
+ if (summaryFile !== undefined && summary !== undefined)
1707
+ throw new CommandError(EXIT.USAGE, "give --summary-file or --summary, not both");
1708
+ if (!summaryFile && !summary)
1709
+ throw new CommandError(EXIT.USAGE, "--final-return needs --summary-file or --summary");
1710
+ const parts: string[] = [];
1711
+ const warning = str(ctx.flags.warning);
1712
+ if (warning) parts.push(warning);
1713
+ parts.push(
1714
+ summary ? summaryOrMissing(ctx, summary) : inputText(ctx.cwd, summaryFile!, "summary-file"),
1715
+ );
1716
+ parts.push(...list(ctx.flags.line));
1717
+ const session = str(ctx.flags.sessionDir);
1718
+ const factsFile = session ? path.resolve(ctx.cwd, session, "issue-facts.json") : "";
1719
+ if (factsFile && fs.existsSync(factsFile)) {
1720
+ const parsed = parseJson(fs.readFileSync(factsFile, "utf-8"));
1721
+ const facts = (parsed.ok ? parsed.value : {}) as { title?: unknown; url?: unknown };
1722
+ const t = trackerTarget(ctx.cwd, { fid });
1723
+ const title = typeof facts.title === "string" ? facts.title : "";
1724
+ const label = [issueRef(t.issue, t.tracker), title].filter(Boolean).join(" ");
1725
+ if (typeof facts.url === "string" && facts.url) parts.push(`[${label}](${facts.url})`);
1726
+ }
1727
+ parts.push("## Suggested Replies", ...list(ctx.flags.suggest), PLAIN_ENGLISH_REPLY);
1728
+ return parts;
1729
+ }
1730
+
1731
+ /**
1732
+ * `--summary`: the summary file's text, or the `--summary-missing` line when the
1733
+ * file is absent; with `--outbox`, the text is also kept there under the file's
1734
+ * name, outside the tree the close may remove.
1735
+ */
1736
+ function summaryOrMissing(ctx: RunContext, rel: string): string {
1737
+ const missing = str(ctx.flags.summaryMissing);
1738
+ if (!missing) throw new CommandError(EXIT.USAGE, "--summary needs --summary-missing");
1739
+ const abs = path.resolve(ctx.cwd, rel);
1740
+ const text = fs.existsSync(abs) ? fs.readFileSync(abs, "utf-8").replace(/\s+$/, "") : missing;
1741
+ const outbox = str(ctx.flags.outbox);
1742
+ if (outbox) {
1743
+ const dir = path.resolve(ctx.cwd, outbox);
1744
+ fs.mkdirSync(dir, { recursive: true });
1745
+ fs.writeFileSync(path.join(dir, path.basename(abs)), `${text}\n`);
1746
+ }
1747
+ return text;
1748
+ }
1749
+
1750
+ function finalReturnText(
1751
+ ctx: RunContext,
1752
+ workflow: string,
1753
+ parts: string[] | null,
1754
+ ): {
1755
+ finalReturn?: string;
1756
+ } {
1757
+ if (parts === null) return {};
1758
+ const tips = tipsText(false, workflow as TipsContext, ctx.cwd);
1759
+ return { finalReturn: [...parts, ...(tips ? ["## bkit Tips", tips] : [])].join("\n\n") };
1760
+ }
1761
+
1762
+ // ---------------------------------------------------------------------------
1763
+ // input
1764
+ // ---------------------------------------------------------------------------
1765
+
1766
+ /** A required input file's text, trailing newlines dropped; missing exits EXIT_NO_INPUT. */
1767
+ function inputText(cwd: string, rel: string, flag: string): string {
1768
+ const abs = path.resolve(cwd, rel);
1769
+ if (!fs.existsSync(abs)) throw new CommandError(EXIT_NO_INPUT, `--${flag} ${rel} does not exist`);
1770
+ return fs.readFileSync(abs, "utf-8").replace(/\s+$/, "");
1771
+ }
1772
+
1773
+ /** The run's issue parts from `issues fetch`'s files, oldest first; none for a run with no issue. */
1774
+ function inputIssueParts(ctx: RunContext): IssuePart[] {
1775
+ const descFile = str(ctx.flags.descriptionFile);
1776
+ const commentsFile = str(ctx.flags.commentsFile);
1777
+ const description = descFile ? inputText(ctx.cwd, descFile, "description-file") : "";
1778
+ let comments: IssueComment[] = [];
1779
+ if (commentsFile) {
1780
+ const parsed = parseJson(inputText(ctx.cwd, commentsFile, "comments-file"));
1781
+ const list = parsed.ok ? parseComments(parsed.value) : null;
1782
+ if (list === null)
1783
+ throw new CommandError(
1784
+ EXIT_NO_INPUT,
1785
+ `--comments-file ${commentsFile} is not a list of comments`,
1786
+ );
1787
+ comments = sortOldestFirst(list).comments;
1788
+ }
1789
+ return issueParts(description, comments);
1790
+ }
1791
+
1792
+ /** An ISO-8601 time in UTC, or undefined when it does not parse. */
1793
+ function utc(at: string | undefined): string | undefined {
1794
+ const t = at === undefined ? NaN : Date.parse(at);
1795
+ return Number.isNaN(t) ? undefined : new Date(t).toISOString();
1796
+ }
1797
+
1798
+ /**
1799
+ * When a design or plan file last changed: the author date of its last commit (a
1800
+ * rebase keeps it, unlike the committer date), or undefined (newer than any commit) when the file
1801
+ * has uncommitted changes or no commit.
1802
+ */
1803
+ function committedAt(cwd: string, rel: string): string | undefined {
1804
+ if ((git(cwd, ["status", "--porcelain", "--", rel]) ?? "") !== "") return undefined;
1805
+ return utc(git(cwd, ["log", "-1", "--format=%aI", "--", rel]) || undefined);
1806
+ }
1807
+
1808
+ const fileDate = (cwd: string, rel: string) => {
1809
+ const at = committedAt(cwd, rel);
1810
+ return at === undefined ? "uncommitted changes, newer than any commit" : `last committed ${at}`;
1811
+ };
1812
+
1813
+ function issueHeading(part: IssuePart): string {
1814
+ if (part.kind === "description") return "Issue description — oldest";
1815
+ const at = utc(part.createdAt);
1816
+ return at === undefined
1817
+ ? "Issue comment — no date, counts as oldest"
1818
+ : `Issue comment — posted ${at}`;
1819
+ }
1820
+
1821
+ /** Comments posted after the plan's last commit; none when the plan is missing or uncommitted. */
1822
+ function newerThanPlan(cwd: string, plan: string | undefined, parts: IssuePart[]): number {
1823
+ if (!plan || !fs.existsSync(path.resolve(cwd, plan))) return 0;
1824
+ const since = committedAt(cwd, plan);
1825
+ if (since === undefined) return 0;
1826
+ return parts.filter((p) => {
1827
+ const at = utc(p.createdAt);
1828
+ return p.kind === "comment" && at !== undefined && at > since;
1829
+ }).length;
1830
+ }
1831
+
1832
+ function inputVerb(ctx: RunContext): number {
1833
+ const workflow = workflowName(String(ctx.flags.workflow));
1834
+ const fid = String(ctx.flags.fid);
1835
+ const run = positiveInt(ctx.flags.run, "run")!;
1836
+ const file = str(ctx.flags.file);
1837
+ const status = file
1838
+ ? path.resolve(ctx.cwd, file)
1839
+ : statusLocation({
1840
+ cwd: ctx.cwd,
1841
+ workflow,
1842
+ fid,
1843
+ month: resolveMonth(repoRoot(ctx.cwd), fid, str(ctx.flags.month) || undefined),
1844
+ }).path;
1845
+ const sections: Array<[string, string]> = [
1846
+ [
1847
+ "Session Prompt — this run's, newer than everything below",
1848
+ inputText(ctx.cwd, String(ctx.flags.promptFile), "prompt-file"),
1849
+ ],
1850
+ ];
1851
+ const issue = inputIssueParts(ctx);
1852
+ for (const part of issue) sections.push([issueHeading(part), part.text]);
1853
+ const plan = str(ctx.flags.plan);
1854
+ if (plan && fs.existsSync(path.resolve(ctx.cwd, plan)))
1855
+ sections.push([
1856
+ `Plan — ${plan} — ${fileDate(ctx.cwd, plan)}`,
1857
+ inputText(ctx.cwd, plan, "plan"),
1858
+ ]);
1859
+ const design = str(ctx.flags.design);
1860
+ if (design) {
1861
+ const text = inputText(ctx.cwd, design, "design");
1862
+ sections.push([`Design — ${design} — ${fileDate(ctx.cwd, design)}`, text]);
1863
+ }
1864
+ for (const audit of list(ctx.flags.audit)) {
1865
+ const text = inputText(ctx.cwd, audit, "audit");
1866
+ sections.push([`Audit Report — ${audit} — ${fileDate(ctx.cwd, audit)}`, text]);
1867
+ }
1868
+ const body = sections.map(([h, text]) => `## ${h}\n\n${text}\n`).join("\n");
1869
+ const abs = path.join(path.dirname(status), `${workflow}-input-${run}.md`);
1870
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
1871
+ fs.writeFileSync(abs, body);
1872
+ ctx.emit({
1873
+ path: path.relative(ctx.cwd, abs),
1874
+ bytes: Buffer.byteLength(body),
1875
+ newerThanPlan: newerThanPlan(ctx.cwd, plan, issue),
1876
+ });
1877
+ return EXIT.OK;
1878
+ }
1879
+
1880
+ /**
1881
+ * Close / links output gains `commentFile`; with `--post`, the close comment once,
1882
+ * deduped by marker hash against the issue's latest comments (the close commit is
1883
+ * already made, so no engine-action row can land in it).
1884
+ */
1885
+ async function postClose(
1886
+ ctx: RunContext,
1887
+ fid: string,
1888
+ out: Record<string, unknown>,
1889
+ ): Promise<Record<string, unknown>> {
1890
+ const comment = typeof out.comment === "string" ? out.comment : null;
1891
+ const withFile = { ...out, commentFile: commentFileOf(ctx.cwd, comment) };
1892
+ if (ctx.flags.post !== true) return withFile;
1893
+ if (comment === null) throw new CommandError(EXIT.USAGE, "--post needs --number");
1894
+ return { ...withFile, tracker: await postForVerb(ctx, comment, { fid }) };
1895
+ }
1896
+
1327
1897
  export const workflowsCommand: CommandSpec = {
1328
1898
  noun: "workflows",
1329
- summary: "Start, fail, hand over and close a phase workflow run; promote and link its documents.",
1899
+ summary:
1900
+ "Start, fail, hand over, summarize and close a phase workflow run; promote and link its documents.",
1330
1901
  verbs: {
1331
1902
  start: {
1332
1903
  summary: "Take the feature lock and open a run (workflow-started unless resuming).",
@@ -1341,6 +1912,11 @@ export const workflowsCommand: CommandSpec = {
1341
1912
  help: "Step 1 already took the lock: check it is ours instead of acquiring",
1342
1913
  },
1343
1914
  TOKEN_FLAG,
1915
+ {
1916
+ name: "branch",
1917
+ type: "string",
1918
+ help: "the branch the checkout must be on; refuse (15) before anything is written when it is not",
1919
+ },
1344
1920
  ],
1345
1921
  output: {
1346
1922
  lock: "{path, month, token, reclaimed} of the lock taken, or {path} with --lock-held",
@@ -1348,11 +1924,16 @@ export const workflowsCommand: CommandSpec = {
1348
1924
  resumed: "the latest run was this workflow, IN_PROGRESS: no new row",
1349
1925
  row: "the appended workflow-started row, or null when resuming",
1350
1926
  run: "which run of the workflow this is (1-based)",
1927
+ lastDoneStep: "the current run's last DONE step: resume after it (null on a new run)",
1928
+ openDecision:
1929
+ "{file, decision, question, from, pauseStep, group, verifyAttempt, testAttempt, plan} of the current run's highest {workflow}-decision-{run}-{N}.md holding Status: OPEN, else null",
1351
1930
  },
1931
+ textOmit: ["row"],
1352
1932
  exitCodes: {
1353
1933
  [EXIT_NO_STATUS]: "status.jsonl is not valid",
1354
1934
  [EXIT_SPLIT_BUCKET]: "the feature has logs in more than one month bucket",
1355
1935
  [EXIT_LOCK_NOT_HELD]: "--lock-held: the lock is missing or belongs to another owner",
1936
+ [EXIT_WRONG_BRANCH]: "--branch: the checkout is on another branch",
1356
1937
  },
1357
1938
  run: (ctx) => {
1358
1939
  const workflow = workflowName(String(ctx.flags.workflow));
@@ -1360,6 +1941,14 @@ export const workflowsCommand: CommandSpec = {
1360
1941
  const token = str(ctx.flags.token);
1361
1942
  if (token !== undefined && ctx.flags.lockHeld !== true)
1362
1943
  throw new CommandError(EXIT.USAGE, "--token applies with --lock-held only");
1944
+ const branch = str(ctx.flags.branch);
1945
+ if (branch !== undefined) {
1946
+ const on = git(ctx.cwd, ["branch", "--show-current"]) ?? "";
1947
+ if (on !== branch) {
1948
+ ctx.log(`[bkit-${workflow}] not on ${branch} in ${ctx.cwd} (on '${on}')`);
1949
+ return EXIT_WRONG_BRANCH;
1950
+ }
1951
+ }
1363
1952
  const where = whereInTree(ctx.cwd, {
1364
1953
  workflow,
1365
1954
  fid,
@@ -1387,6 +1976,15 @@ export const workflowsCommand: CommandSpec = {
1387
1976
  const file = where.status;
1388
1977
  fs.mkdirSync(path.dirname(file), { recursive: true });
1389
1978
  if (!fs.existsSync(file)) fs.writeFileSync(file, "");
1979
+ // A ship decides its handover afresh: a sentinel an earlier run left is stale.
1980
+ if (workflow === "ship") {
1981
+ for (const name of SENTINELS) {
1982
+ const p = path.join(path.dirname(file), name);
1983
+ if (!fs.existsSync(p)) continue;
1984
+ fs.rmSync(p, { force: true });
1985
+ ctx.log(`cleared stale ${name}`);
1986
+ }
1987
+ }
1390
1988
 
1391
1989
  const latest = fold(readStatusEvents(file)).at(-1);
1392
1990
  const resumed = latest?.workflow === workflow && latest.status === "IN_PROGRESS";
@@ -1400,12 +1998,20 @@ export const workflowsCommand: CommandSpec = {
1400
1998
  };
1401
1999
  fs.appendFileSync(file, appendLine(row as StatusEvent));
1402
2000
  }
2001
+ recordChat(file, workflow, process.env);
2002
+ const runs = fold(readStatusEvents(file));
2003
+ const run = runNumber(runs, workflow);
2004
+ const current = resumed ? lastRun(runs, workflow) : undefined;
1403
2005
  ctx.emit({
1404
2006
  lock,
1405
2007
  file,
1406
2008
  resumed,
1407
2009
  row,
1408
- run: runNumber(fold(readStatusEvents(file)), workflow),
2010
+ run,
2011
+ lastDoneStep: current?.steps.filter((s) => s.status === "DONE").at(-1)?.step ?? null,
2012
+ openDecision: resumed
2013
+ ? openDecision(path.dirname(file), where.tree, workflow, run)
2014
+ : null,
1409
2015
  });
1410
2016
  return EXIT.OK;
1411
2017
  },
@@ -1456,6 +2062,16 @@ export const workflowsCommand: CommandSpec = {
1456
2062
  type: "string",
1457
2063
  help: "the failed shell command's stderr (last 20 lines kept)",
1458
2064
  },
2065
+ {
2066
+ ...POST_FLAG,
2067
+ help: "post the failure comment (needs --step-number) to the --fid / --issue issue and write its failed labels; prints `tracker` and `labelsWrite`",
2068
+ },
2069
+ {
2070
+ name: "issue",
2071
+ type: "string",
2072
+ help: "with --post: the issue id when there is no --fid yet",
2073
+ },
2074
+ SESSION_DIR_FLAG,
1459
2075
  ],
1460
2076
  output: {
1461
2077
  row: "the appended workflow-failed row, or null (no --token, or no status.jsonl)",
@@ -1470,7 +2086,13 @@ export const workflowsCommand: CommandSpec = {
1470
2086
  trackerState: "the Linear or Jira state for the failed issue (null under github, none)",
1471
2087
  prState: "the --pr PR's state, or null",
1472
2088
  comment: "the failure comment body (with --step-number), else null",
2089
+ commentFile: COMMENT_FILE_OUTPUT,
2090
+ tracker: TRACKER_OUTPUT,
2091
+ labelsWrite:
2092
+ "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}",
2093
+ sessionRemoved: SESSION_REMOVED_OUTPUT,
1473
2094
  },
2095
+ textOmit: ["row"],
1474
2096
  exitCodes: {
1475
2097
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1476
2098
  [EXIT_REMOVE_FAILED]:
@@ -1488,7 +2110,7 @@ export const workflowsCommand: CommandSpec = {
1488
2110
  {
1489
2111
  name: "push",
1490
2112
  type: "boolean",
1491
- help: "feature branch: git add -A, commit `docs({fid}): {workflow} aborted bkit [skip ci]`, push --mode=abort; dev / main / detached: lands like --flush, the checkout untouched",
2113
+ help: "feature branch: git add -A (minus bkit.workflows.worktree.copy entries), commit `docs({fid}): {workflow} aborted bkit [skip ci]`, push --mode=abort; dev / main / detached: lands like --flush, the checkout untouched",
1492
2114
  },
1493
2115
  {
1494
2116
  name: "flush",
@@ -1501,12 +2123,18 @@ export const workflowsCommand: CommandSpec = {
1501
2123
  help: "--push: the open-PR answer from MCP (a number, or none) instead of asking gh",
1502
2124
  },
1503
2125
  { name: "ref", type: "string", help: "link the handover at this ref (no push / flush)" },
2126
+ {
2127
+ name: "list-stray",
2128
+ type: "boolean",
2129
+ help: "only list what --push would sweep in besides the run's logs (modified, untracked) and whether the checkout is shared; writes nothing",
2130
+ },
1504
2131
  {
1505
2132
  name: "worktree",
1506
2133
  type: "string",
1507
2134
  help: "the run's tree: holds the handover and the logs, and is where --push commits (default: cwd's checkout)",
1508
2135
  },
1509
2136
  OWNER_REPO_FLAG,
2137
+ { ...POST_FLAG, help: "post the handover comment to the FID's issue; prints `tracker`" },
1510
2138
  ],
1511
2139
  output: {
1512
2140
  handover: "the handover artifact, or null when absent",
@@ -1515,6 +2143,11 @@ export const workflowsCommand: CommandSpec = {
1515
2143
  skipped: "why nothing was pushed: open-pr | skip-ci | nothing-to-commit (null otherwise)",
1516
2144
  comment:
1517
2145
  "the handover comment body (null when there is no handover); links only when pushed",
2146
+ commentFile: COMMENT_FILE_OUTPUT,
2147
+ tracker: `${TRACKER_OUTPUT}; absent when there is no handover`,
2148
+ shared: "--list-stray: the checkout is dev / main / detached (remove nothing)",
2149
+ modified: "--list-stray: tracked paths with changes, outside the run's logs",
2150
+ untracked: "--list-stray: untracked paths, outside the run's logs",
1518
2151
  },
1519
2152
  exitCodes: {
1520
2153
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
@@ -1564,7 +2197,7 @@ export const workflowsCommand: CommandSpec = {
1564
2197
  {
1565
2198
  name: "message",
1566
2199
  type: "string",
1567
- help: "then git add -A and commit with this message in the tree",
2200
+ help: "then git add -A (minus bkit.workflows.worktree.copy entries) and commit with this message in the tree",
1568
2201
  },
1569
2202
  {
1570
2203
  name: "label",
@@ -1590,6 +2223,40 @@ export const workflowsCommand: CommandSpec = {
1590
2223
  type: "string",
1591
2224
  help: "--flush: the shipped branch, deleted locally and on origin with the worktree once the close is on dev",
1592
2225
  },
2226
+ SESSION_DIR_FLAG,
2227
+ {
2228
+ name: "final-return",
2229
+ type: "boolean",
2230
+ help: "print finalReturn: the run's last message to the person (needs --summary-file)",
2231
+ },
2232
+ {
2233
+ name: "summary-file",
2234
+ type: "string",
2235
+ help: "--final-return: the summary shown verbatim (read before the close runs)",
2236
+ },
2237
+ {
2238
+ name: "summary",
2239
+ type: "string",
2240
+ help: "--final-return: like --summary-file, but a missing file shows --summary-missing; a copy is kept in --outbox",
2241
+ },
2242
+ {
2243
+ name: "summary-missing",
2244
+ type: "string",
2245
+ help: "--summary: the line shown when the summary file does not exist",
2246
+ },
2247
+ { name: "warning", type: "string", help: "--final-return: line 1, before the summary" },
2248
+ {
2249
+ name: "line",
2250
+ type: "string",
2251
+ repeatable: true,
2252
+ help: "--final-return: a line after the summary, before the issue link",
2253
+ },
2254
+ {
2255
+ name: "suggest",
2256
+ type: "string",
2257
+ repeatable: true,
2258
+ help: "--final-return: a suggested reply, before the plain-English offer",
2259
+ },
1593
2260
  ],
1594
2261
  output: {
1595
2262
  row: "the appended workflow-done row",
@@ -1606,20 +2273,29 @@ export const workflowsCommand: CommandSpec = {
1606
2273
  parentSha: "HEAD before the --message commit (the close step's parentSha)",
1607
2274
  commit: "the --message commit, or null",
1608
2275
  comment: "the close comment (--number with --outbox), else null",
2276
+ commentFile: COMMENT_FILE_OUTPUT,
2277
+ tracker: TRACKER_OUTPUT,
1609
2278
  roadmapFoldNeeded:
1610
2279
  "always true: append the feature row and re-render the board (not run here)",
1611
2280
  featureStatus: "roadmap status this close moves the feature to",
1612
2281
  landed: "--flush: {ref, via: head-push | close-pr | close-pr-open}",
1613
2282
  worktree:
1614
2283
  "--flush: the `bkit worktrees remove` result once the close is on dev; null while the close PR is unmerged or the removal failed",
2284
+ sessionRemoved: SESSION_REMOVED_OUTPUT,
2285
+ finalReturn:
2286
+ "--final-return: the warning, the summary verbatim, the issue link from {session-dir}/issue-facts.json, `## Suggested Replies` (each --suggest, then the plain-English offer) and `## bkit Tips` (what `bkit tips --workflow` prints, when anything)",
1615
2287
  },
2288
+ textOmit: ["row", "counterRow", "outcomeRow"],
1616
2289
  exitCodes: {
1617
2290
  [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
2291
+ [EXIT_NO_INPUT]: "--final-return: --summary-file does not exist (nothing written)",
1618
2292
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1619
2293
  [EXIT_PUSH_FAILED]:
1620
- "--flush: dev moved before every push, or the push failed without a server answer; the lock is kept",
2294
+ "--flush: dev moved before every push, or the push failed without a server answer; the lock is kept. Without --flush, --message in an in-place run: a path that was dirty before the run changed during it (EXIT_FOREIGN_PATH) — no row written, nothing committed",
1621
2295
  [EXIT_FLUSH_FAILED]:
1622
2296
  "--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",
2297
+ [EXIT_NO_RECORD]:
2298
+ "--message in a debug run on dev/main with no shared-checkout record: no row written, nothing committed",
1623
2299
  },
1624
2300
  run: async (ctx) => {
1625
2301
  const f = ctx.flags;
@@ -1641,19 +2317,80 @@ export const workflowsCommand: CommandSpec = {
1641
2317
  title: str(f.title),
1642
2318
  tree: str(f.tree),
1643
2319
  };
2320
+ const finalParts = finalReturnParts(ctx, input.fid);
1644
2321
  if (f.flush === true) {
1645
2322
  if (input.workflow !== "ship") throw new CommandError(EXIT.USAGE, "--flush is ship only");
1646
2323
  const r = await shipClose(ctx, { ...input, branch: str(f.branch) }, str(f.token));
1647
- if (r.out) ctx.emit(r.out);
2324
+ if (r.out) {
2325
+ const out = r.out as Record<string, unknown>;
2326
+ const posted =
2327
+ typeof out.comment === "string"
2328
+ ? await postClose(ctx, input.fid, out)
2329
+ : { ...out, commentFile: null };
2330
+ const final = finalReturnText(ctx, input.workflow, finalParts);
2331
+ ctx.emit({ ...posted, ...final, ...sessionRemoval(ctx) });
2332
+ }
1648
2333
  return r.code;
1649
2334
  }
1650
- ctx.emit(closeWorkflow(ctx.cwd, input, ctx.log));
2335
+ const out = await postClose(ctx, input.fid, { ...closeWorkflow(ctx.cwd, input, ctx.log) });
2336
+ const final = finalReturnText(ctx, input.workflow, finalParts);
2337
+ ctx.emit({ ...out, ...final, ...sessionRemoval(ctx) });
1651
2338
  return EXIT.OK;
1652
2339
  },
1653
2340
  },
2341
+ input: {
2342
+ summary:
2343
+ "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.",
2344
+ flags: [
2345
+ WORKFLOW_FLAG,
2346
+ FID_FLAG,
2347
+ MONTH_FLAG,
2348
+ {
2349
+ ...STATUS_FILE_FLAG,
2350
+ help: "status.jsonl: the input file goes beside it (default: derived)",
2351
+ },
2352
+ { name: "run", type: "string", required: true, help: "the run number ({RUN})" },
2353
+ {
2354
+ name: "prompt-file",
2355
+ type: "string",
2356
+ required: true,
2357
+ help: "the session prompt ({SESSION_DIR}/prompt.md)",
2358
+ },
2359
+ {
2360
+ name: "description-file",
2361
+ type: "string",
2362
+ help: "issue-description.md from `issues fetch` (omit for a run with no issue)",
2363
+ },
2364
+ {
2365
+ name: "comments-file",
2366
+ type: "string",
2367
+ help: "issue-comments.json from `issues fetch`: bkit:generated comments dropped, the ignore-earlier cut applied",
2368
+ },
2369
+ { name: "plan", type: "string", help: "appended under `## Plan — <path>` when it exists" },
2370
+ { name: "design", type: "string", help: "plan: the parent design, appended (must exist)" },
2371
+ {
2372
+ name: "audit",
2373
+ type: "string",
2374
+ repeatable: true,
2375
+ help: "plan: an audit report, appended in flag order (must exist)",
2376
+ },
2377
+ ],
2378
+ output: {
2379
+ path: "the input file written, relative to cwd",
2380
+ bytes: "its size in bytes",
2381
+ newerThanPlan:
2382
+ "issue comments posted after the plan's last commit (0 with no plan, or one with uncommitted changes)",
2383
+ },
2384
+ exitCodes: {
2385
+ [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
2386
+ [EXIT_NO_INPUT]:
2387
+ "the prompt, description, comments, design or an audit file is missing, or the comments are not a list",
2388
+ },
2389
+ run: inputVerb,
2390
+ },
1654
2391
  promote: {
1655
2392
  summary:
1656
- "Design / plan close: the highest versioned draft becomes the canonical doc (anchor stamped, a changed canonical archived, plan sub-plans copied).",
2393
+ "Design / plan close: the highest versioned draft becomes the canonical doc (anchor stamped, a changed canonical archived).",
1657
2394
  flags: [
1658
2395
  { ...WORKFLOW_FLAG, help: "design | plan" },
1659
2396
  FID_FLAG,
@@ -1673,8 +2410,7 @@ export const workflowsCommand: CommandSpec = {
1673
2410
  final:
1674
2411
  "the highest versioned draft, e.g. docs/plans/202610/logs/12-x/design-v3-organised.md",
1675
2412
  canonical: "the canonical doc written, or null with --resolve",
1676
- archived: "superseded canonical docs moved to archive/",
1677
- subPlans: "plan: the canonical sub-plans written",
2413
+ archived: "the superseded canonical doc moved to archive/, if any",
1678
2414
  baseSha: "the base commit stamped into the anchor, or null when none was recorded",
1679
2415
  },
1680
2416
  exitCodes: {
@@ -1708,11 +2444,13 @@ export const workflowsCommand: CommandSpec = {
1708
2444
  artifactLinks: "the same as markdown `- [name](url)` lines",
1709
2445
  comment:
1710
2446
  "the close comment (--number with --outbox): Artifacts and Telemetry sections, else null",
2447
+ commentFile: COMMENT_FILE_OUTPUT,
2448
+ tracker: TRACKER_OUTPUT,
1711
2449
  },
1712
2450
  exitCodes: {
1713
2451
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1714
2452
  },
1715
- run: (ctx) => {
2453
+ run: async (ctx) => {
1716
2454
  const workflow = workflowName(String(ctx.flags.workflow));
1717
2455
  const fid = String(ctx.flags.fid);
1718
2456
  const root = repoRoot(ctx.cwd);
@@ -1740,9 +2478,48 @@ export const workflowsCommand: CommandSpec = {
1740
2478
  } else if (ctx.flags.number !== undefined) {
1741
2479
  throw new CommandError(EXIT.USAGE, "--number needs --outbox");
1742
2480
  }
1743
- ctx.emit({ artifacts, artifactLinks: linkLines(artifacts), comment });
2481
+ ctx.emit(
2482
+ await postClose(ctx, fid, { artifacts, artifactLinks: linkLines(artifacts), comment }),
2483
+ );
1744
2484
  return EXIT.OK;
1745
2485
  },
1746
2486
  },
2487
+ summary: {
2488
+ summary:
2489
+ "The Summary step: write {workflow}-summary.md next to --file with the run's verdict, reasons and next command.",
2490
+ flags: [
2491
+ { ...WORKFLOW_FLAG, help: "plan | design | build | debug | ship" },
2492
+ {
2493
+ name: "file",
2494
+ type: "string",
2495
+ required: true,
2496
+ help: "the run's docs/plans/{YYYYMM}/logs/{FID}/status.jsonl; the summary is written beside it",
2497
+ },
2498
+ {
2499
+ name: "plan",
2500
+ type: "string",
2501
+ repeatable: true,
2502
+ help: "a plan file the run worked from (default: build reads {FID}-plan.md)",
2503
+ },
2504
+ {
2505
+ name: "pr",
2506
+ type: "string",
2507
+ help: "ship: the PR number; its size comes from gh pr view (left out when gh cannot answer)",
2508
+ },
2509
+ ],
2510
+ output: {
2511
+ verdict: "PASS | CONCERNS | FAIL",
2512
+ failures: "the count of FAIL reasons: 0 on PASS and CONCERNS",
2513
+ reasons: "one line per reason, FAIL reasons first",
2514
+ file: "the summary written, repo-relative",
2515
+ nextStep:
2516
+ "the recommended next command (with the issue ref), or the fixed line when there is none",
2517
+ },
2518
+ exitCodes: {
2519
+ [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
2520
+ [EXIT_NO_RUN]: "status.jsonl has no workflow-started row for --workflow (nothing written)",
2521
+ },
2522
+ run: summaryVerb,
2523
+ },
1747
2524
  },
1748
2525
  };