@cbartens/bkit 5.5.1 → 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 (288) 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 +35 -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 +19 -18
  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 +91 -167
  13. package/.bkit/core/.bkit/providers.md +29 -32
  14. package/.bkit/core/.bkit/templates.md +12 -11
  15. package/.bkit/core/.bkit/trackers.md +51 -28
  16. package/.bkit/core/.bkit/workflows.md +394 -355
  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 -29
  55. package/.bkit/core/engine/checks/after/github.ts +95 -17
  56. package/.bkit/core/engine/checks/after/index.ts +10 -7
  57. package/.bkit/core/engine/checks/after/suppression.ts +8 -5
  58. package/.bkit/core/engine/checks/after/tools.ts +46 -91
  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 +6 -6
  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 +407 -64
  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 +58 -8
  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 +185 -8
  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 +250 -3
  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 +157 -20
  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 +29 -15
  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 +32 -14
  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 +72 -18
  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 +29 -14
  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 +27 -12
  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 +41 -18
  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 +11 -11
  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 +16 -7
  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 +1 -1
  195. package/.bkit/templates/.github/workflows/bkit-cloud.yml +21 -19
  196. package/.bkit/templates/.husky/pre-push +4 -4
  197. package/.bkit/templates/.prettierignore +7 -0
  198. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +1 -1
  199. package/CHANGELOG.md +112 -0
  200. package/README.md +50 -35
  201. package/dist/checks/after/ci-yml.js +39 -28
  202. package/dist/checks/after/github.js +91 -17
  203. package/dist/checks/after/index.js +11 -8
  204. package/dist/checks/after/suppression.js +8 -5
  205. package/dist/checks/after/tools.js +39 -82
  206. package/dist/checks/before/env.js +2 -2
  207. package/dist/checks/before/files.js +5 -3
  208. package/dist/checks/before/index.js +15 -2
  209. package/dist/checks/before/repo.js +163 -2
  210. package/dist/checks/tips/catalogue.js +14 -5
  211. package/dist/checks/tips/detect.js +32 -0
  212. package/dist/checks/tips/index.js +4 -4
  213. package/dist/cli.js +19 -47
  214. package/dist/commands/analysis.js +109 -100
  215. package/dist/commands/ci/ci.js +6 -6
  216. package/dist/commands/comply.js +54 -91
  217. package/dist/commands/install/doctor.js +2 -2
  218. package/dist/commands/install/install.js +50 -19
  219. package/dist/commands/install/uninstall.js +59 -28
  220. package/dist/commands/land.js +16 -12
  221. package/dist/commands/lib.js +51 -16
  222. package/dist/commands/registry.js +4 -0
  223. package/dist/commands/setup/setup.js +7 -7
  224. package/dist/commands/stats.js +136 -0
  225. package/dist/commands/tips.js +7 -3
  226. package/dist/commands/workflow/branches.js +656 -56
  227. package/dist/commands/workflow/challenge.js +556 -0
  228. package/dist/commands/workflow/context.js +709 -30
  229. package/dist/commands/workflow/counters.js +208 -75
  230. package/dist/commands/workflow/decisions.js +441 -0
  231. package/dist/commands/workflow/disk.js +2 -2
  232. package/dist/commands/workflow/fids.js +689 -33
  233. package/dist/commands/workflow/issues.js +343 -59
  234. package/dist/commands/workflow/ledgers.js +762 -27
  235. package/dist/commands/workflow/locks.js +24 -2
  236. package/dist/commands/workflow/plan-blocks.js +437 -0
  237. package/dist/commands/workflow/plan-versions.js +22 -0
  238. package/dist/commands/workflow/prs.js +142 -32
  239. package/dist/commands/workflow/repo.js +52 -8
  240. package/dist/commands/workflow/roadmap.js +9 -7
  241. package/dist/commands/workflow/run-facts.js +426 -0
  242. package/dist/commands/workflow/runs.js +144 -43
  243. package/dist/commands/workflow/runtime.js +12 -1
  244. package/dist/commands/workflow/status.js +130 -29
  245. package/dist/commands/workflow/step-table.js +276 -0
  246. package/dist/commands/workflow/steps.js +171 -80
  247. package/dist/commands/workflow/summary.js +275 -0
  248. package/dist/commands/workflow/tests.js +834 -136
  249. package/dist/commands/workflow/tracker.js +983 -0
  250. package/dist/commands/workflow/workflows.js +834 -195
  251. package/dist/commands/workflow/workstreams.js +11 -5
  252. package/dist/commands/workflow/worktrees.js +147 -9
  253. package/dist/install/manifest.js +11 -9
  254. package/dist/install/modules/cloud.js +22 -13
  255. package/dist/install/modules/core.js +247 -3
  256. package/dist/install/modules/opencode.js +2 -2
  257. package/dist/install/version-file.js +6 -2
  258. package/dist/ledgers/migrate.js +81 -0
  259. package/dist/ledgers/status.js +61 -8
  260. package/dist/ledgers/telemetry.js +905 -124
  261. package/dist/render/hosts.js +4 -0
  262. package/dist/render/models.js +12 -0
  263. package/dist/shared/branches.js +3 -1
  264. package/dist/shared/egress.js +7 -0
  265. package/dist/shared/json.js +20 -7
  266. package/dist/shared/settings.js +125 -17
  267. package/dist/shared/text.js +333 -0
  268. package/dist/tools/grammar-density.js +183 -0
  269. package/dist/tools/instructions-sources.js +721 -0
  270. package/dist/tools/instructions.js +1579 -0
  271. package/package.json +113 -24
  272. package/.bkit/core/engine/commands/harvest.ts +0 -459
  273. package/.bkit/core/engine/tools/wording.ts +0 -748
  274. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +0 -69
  275. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +0 -71
  276. package/.bkit/core/prompts/bkit-build-challenge-tests.md +0 -74
  277. package/.bkit/core/prompts/bkit-build-summary.md +0 -94
  278. package/.bkit/core/prompts/bkit-debug-summary.md +0 -96
  279. package/.bkit/core/prompts/bkit-design-summary.md +0 -107
  280. package/.bkit/core/prompts/bkit-plan-complexity-check.md +0 -67
  281. package/.bkit/core/prompts/bkit-plan-complexity-split.md +0 -88
  282. package/.bkit/core/prompts/bkit-plan-review-3.md +0 -93
  283. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +0 -85
  284. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +0 -85
  285. package/.bkit/core/prompts/bkit-plan-summary.md +0 -107
  286. package/.bkit/core/prompts/bkit-ship-summary.md +0 -78
  287. package/dist/commands/harvest.js +0 -353
  288. 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,24 +17,33 @@
17
17
  // promote design / plan close: the highest versioned draft becomes the
18
18
  // canonical doc (anchor stamped, a superseded canonical archived).
19
19
  // links the feature docs and this workflow's logs on a ref, as markdown links.
20
+ // summary the Summary step: `{workflow}-summary.md` with its verdict, reasons and
21
+ // next command, from the run's rows, logs, plan and ledger rows.
20
22
  import * as fs from "node:fs";
23
+ import * as os from "node:os";
21
24
  import * as path from "node:path";
22
- import { appendLine, fold, runNumber, runOrStepField, statusTimestamp, } from "../../ledgers/status.js";
23
- import { appendLine as telemetryLine, foldFrom, resolveRepoSlug, validate, workflowTelemetry, } from "../../ledgers/telemetry.js";
24
- import { readBkitVersion } from "../../install/version-file.js";
25
+ import { appendLine, fold, lastRun, runNumber, runOrStepField, statusTimestamp, } from "../../ledgers/status.js";
26
+ import { foldFrom, normalize, resolveRepoSlug, workflowTelemetry, } from "../../ledgers/telemetry.js";
25
27
  import { readBkitConfig } from "../../shared/settings.js";
26
28
  import { gradeCompliance } from "../comply.js";
27
29
  import { landDir, pushToDev } from "../land.js";
28
30
  import { CommandError, DEV, EXIT, git, isSharedBranch, parseJson, repoRoot, runGh, runGit, statusLocation, statusRelPath, } from "../lib.js";
29
31
  import { anchorBkitStatus, pushBranch, readAnchor, stampAnchor } from "./branches.js";
30
- import { AUTO_LABEL, AUTO_ROUTE_SUFFIX, buildComment, trackerState, transitionLabels, } from "./issues.js";
31
- import { EXIT_EMPTY, commitBookkeeping, unionLedgers } from "./ledgers.js";
32
+ import { AUTO_LABEL, AUTO_ROUTE_SUFFIX, buildComment, issueParts, parseComments, sortOldestFirst, trackerState, transitionLabels, } from "./issues.js";
33
+ import { EXIT_EMPTY, activeRecord, commitBookkeeping, ownPathCommit, ownSet, removeRecord, appendLedgerRows, runRows, unionLedgers, } from "./ledgers.js";
34
+ import { readIssueTracker } from "./fids.js";
35
+ import { agentContextBlock, buildBlock, chatFingerprint, ciList, claudeTranscripts, hostChat, planBlock, planFiles, runChats, runLines, runStatusRows, stepsBlock, timeBlock, } from "./run-facts.js";
36
+ import { buildSummary, refOf, SUMMARY_WORKFLOWS } from "./summary.js";
37
+ import { parseWorkstreams } from "./workstreams.js";
32
38
  import { EXIT_REMOVE_FAILED, EXIT_SPLIT_BUCKET, acquireWorkflowLock, owns, readHolder, releaseLock, resolveMonth, workflowLockPath, } from "./locks.js";
39
+ import { highestVersion } from "./plan-versions.js";
33
40
  import { mergePr, probePr } from "./prs.js";
34
41
  import { FEATURE_STATUS } from "./roadmap.js";
35
42
  import { EXIT_NO_STATUS, WORKFLOW_FLAG, positiveInt, readRuns, readStatusEvents, readStatusRows, str, } from "./status.js";
36
- import { writeStepRow } from "./steps.js";
37
- import { removeWorktree } from "./worktrees.js";
43
+ import { COMMENT_FILE_OUTPUT, POST_FLAG, TRACKER_OUTPUT, attempt, commentFileOf, postForVerb, issueRef, readLabels, endedRunActionKey, skipOf, trackerTarget, writeLabels, } from "./tracker.js";
44
+ import { tipsText } from "../tips.js";
45
+ import { EXIT_NO_RECORD, requireRecordOnShared, writeStepRow } from "./steps.js";
46
+ import { addAllButCopied, removeWorktree } from "./worktrees.js";
38
47
  /** Sentinels a workflow leaves in its logs folder; either one existing means a handover is due. */
39
48
  export const SENTINELS = [".rebase-failed", ".deferred-blocked"];
40
49
  /** Exit code (start --lock-held): the lock is missing or belongs to another owner. */
@@ -47,6 +56,12 @@ export const EXIT_PUSH_FAILED = 10;
47
56
  export const EXIT_FLUSH_FAILED = 11;
48
57
  /** Exit code (promote): no versioned draft to promote. */
49
58
  export const EXIT_NO_VERSION = 12;
59
+ /** Exit code (input): a named input file is missing or not in the expected shape. */
60
+ export const EXIT_NO_INPUT = 13;
61
+ /** Exit code (start --branch): the checkout is not on the named branch. */
62
+ export const EXIT_WRONG_BRANCH = 15;
63
+ /** Exit code (summary): the status file has no run of the workflow. */
64
+ export const EXIT_NO_RUN = 16;
50
65
  function workflowName(workflow) {
51
66
  if (!Object.hasOwn(FEATURE_STATUS, workflow))
52
67
  throw new CommandError(EXIT.USAGE, `--workflow must be ${Object.keys(FEATURE_STATUS).join(", ")}`);
@@ -61,6 +76,72 @@ function whereInTree(cwd, o) {
61
76
  return { root, month, tree, status };
62
77
  }
63
78
  const headSha = (cwd) => git(cwd, ["rev-parse", "HEAD"]) ?? "";
79
+ /**
80
+ * Append a `session` row naming the chat that runs this start (`hostChat`), as its
81
+ * fingerprint, unless the current run's latest `session` row already names it. Nothing when
82
+ * the host names no chat. The close and the harvest read the run's chats from these rows.
83
+ */
84
+ export function recordChat(file, workflow, env) {
85
+ const chat = hostChat(env);
86
+ if (chat === undefined)
87
+ return;
88
+ const session = chatFingerprint(chat.platform, chat.id);
89
+ const events = readStatusEvents(file);
90
+ const startAt = lastOfType(events, "workflow-started", workflow)?.at;
91
+ const last = events
92
+ .filter((e) => e.type === "session" &&
93
+ e.workflow === workflow &&
94
+ (startAt === undefined || String(e.at) >= startAt))
95
+ .at(-1);
96
+ if (last?.session === session)
97
+ return;
98
+ const row = {
99
+ type: "session",
100
+ workflow,
101
+ at: statusTimestamp(),
102
+ platform: chat.platform,
103
+ session,
104
+ };
105
+ fs.appendFileSync(file, appendLine(row));
106
+ }
107
+ /**
108
+ * The highest-numbered `{workflow}-decision-{run}-{N}.md` in `logDir` whose header holds
109
+ * `Status: OPEN`, or null. Only the given run's files count, so an earlier run's pause
110
+ * never resurfaces. `file` is relative to `tree`.
111
+ */
112
+ export function openDecision(logDir, tree, workflow, run) {
113
+ if (!fs.existsSync(logDir))
114
+ return null;
115
+ const name = new RegExp(`^${workflow}-decision-${run}-([0-9]+)\\.md$`);
116
+ const found = fs
117
+ .readdirSync(logDir)
118
+ .map((f) => ({ f, m: name.exec(f) }))
119
+ .filter((x) => x.m !== null)
120
+ .map(({ f, m }) => ({ f, n: Number(m[1]) }))
121
+ .sort((a, b) => b.n - a.n);
122
+ for (const { f, n } of found) {
123
+ const text = fs.readFileSync(path.join(logDir, f), "utf-8");
124
+ const field = (key) => new RegExp(`^${key}:[ \\t]*(.+?)[ \\t]*$`, "m").exec(text)?.[1] ?? null;
125
+ if (field("Status") !== "OPEN")
126
+ continue;
127
+ const num = (key) => {
128
+ const v = field(key);
129
+ return v !== null && /^[0-9]+$/.test(v) ? Number(v) : null;
130
+ };
131
+ return {
132
+ file: path.relative(tree, path.join(logDir, f)),
133
+ decision: n,
134
+ question: field("Question"),
135
+ from: field("From"),
136
+ pauseStep: num("Pause step"),
137
+ group: num("Group"),
138
+ verifyAttempt: num("Verify attempt"),
139
+ testAttempt: num("Test attempt"),
140
+ plan: field("Plan"),
141
+ };
142
+ }
143
+ return null;
144
+ }
64
145
  const logDirRel = (month, fid) => path.join("docs", "plans", month, "logs", fid);
65
146
  const list = (v) => v ?? [];
66
147
  // ---------------------------------------------------------------------------
@@ -143,9 +224,9 @@ function failState(ctx, workflow, fid) {
143
224
  fs.rmSync(p, { force: true });
144
225
  }
145
226
  }
146
- return { row, rebaseAborted, lock, sentinels, removeFailed, soak };
227
+ return { row, rebaseAborted, lock, sentinels, removeFailed, soak, status };
147
228
  }
148
- function failVerb(ctx) {
229
+ async function failVerb(ctx) {
149
230
  const workflow = workflowName(String(ctx.flags.workflow));
150
231
  // An empty value is a placeholder not held yet (the failure came before it was set).
151
232
  const fid = str(ctx.flags.fid) || undefined;
@@ -162,6 +243,7 @@ function failVerb(ctx) {
162
243
  sentinels: [],
163
244
  removeFailed: false,
164
245
  soak: false,
246
+ status: undefined,
165
247
  }
166
248
  : failState(ctx, workflow, fid);
167
249
  // Labels: bkit:failed added; a ship whose PR already merged also moves to bkit:merged.
@@ -173,11 +255,16 @@ function failVerb(ctx) {
173
255
  }
174
256
  const merged = prState === "MERGED";
175
257
  const transition = merged ? { phase: "merged" } : { failed: true };
258
+ const failedSet = (current) => {
259
+ const labels = transitionLabels(current, transition).labels;
260
+ if (merged && !labels.includes("bkit:failed"))
261
+ labels.push("bkit:failed");
262
+ return labels;
263
+ };
176
264
  const current = list(ctx.flags.label);
177
- const labels = transitionLabels(current, transition).labels;
178
- if (merged && !labels.includes("bkit:failed"))
179
- labels.push("bkit:failed");
265
+ const labels = failedSet(current);
180
266
  const add = labels.filter((l) => !current.includes(l));
267
+ const failedState = trackerState(transition, undefined, readBkitConfig(repoRoot(ctx.cwd)));
181
268
  // The failure comment, when the step is named.
182
269
  let comment = null;
183
270
  const stepNumber = str(ctx.flags.stepNumber);
@@ -193,6 +280,18 @@ function failVerb(ctx) {
193
280
  stderrFile: str(ctx.flags.stderrFile) || undefined,
194
281
  });
195
282
  }
283
+ if (ctx.flags.post === true && comment === null)
284
+ throw new CommandError(EXIT.USAGE, "--post needs --step-number");
285
+ // Once per run and step: an engine-action row where the run's status.jsonl exists.
286
+ const key = endedRunActionKey(state.status, workflow, "failure", stepNumber, str(ctx.flags.subStep) || undefined);
287
+ const tracker = ctx.flags.post === true && comment !== null
288
+ ? await postForVerb(ctx, comment, {
289
+ fid,
290
+ issue: str(ctx.flags.issue),
291
+ ...(key === undefined ? {} : { file: state.status, key }),
292
+ })
293
+ : undefined;
294
+ const labelsWrite = ctx.flags.post === true ? await writeFailedLabels(ctx, fid, failedSet, failedState) : undefined;
196
295
  ctx.emit({
197
296
  row: state.row,
198
297
  rebaseAborted: state.rebaseAborted,
@@ -202,12 +301,36 @@ function failVerb(ctx) {
202
301
  (ctx.flags.maxExceeded === true || state.sentinels.length > 0 || state.soak),
203
302
  add,
204
303
  labels,
205
- trackerState: trackerState(transition, undefined, readBkitConfig(repoRoot(ctx.cwd))),
304
+ trackerState: failedState,
206
305
  prState,
207
306
  comment,
307
+ commentFile: commentFileOf(ctx.cwd, comment),
308
+ ...(tracker === undefined ? {} : { tracker }),
309
+ ...(labelsWrite === undefined ? {} : { labelsWrite }),
310
+ ...sessionRemoval(ctx),
208
311
  });
209
312
  return state.removeFailed ? EXIT_REMOVE_FAILED : EXIT.OK;
210
313
  }
314
+ /**
315
+ * `fail --post`: read the issue's labels, write the failed set and the review state.
316
+ * The set comes from the labels read, not `--label`, so a label added since Step 1 stays.
317
+ */
318
+ async function writeFailedLabels(ctx, fid, failedSet, state) {
319
+ const t = trackerTarget(ctx.cwd, { fid, issue: str(ctx.flags.issue) });
320
+ const skip = skipOf(t);
321
+ if (skip)
322
+ return skip;
323
+ return attempt("labels", ctx.log, async () => {
324
+ const current = await readLabels(t);
325
+ const labels = failedSet(current);
326
+ await writeLabels(t, {
327
+ add: labels.filter((l) => !current.includes(l)),
328
+ remove: current.filter((l) => !labels.includes(l)),
329
+ labels,
330
+ state,
331
+ });
332
+ });
333
+ }
211
334
  /** A text file's content, trailing newlines dropped; a missing file is a usage error. */
212
335
  function readText(cwd, rel) {
213
336
  const abs = path.resolve(cwd, rel);
@@ -253,20 +376,57 @@ const SHARED_LEDGERS = [
253
376
  ":(glob).bkit/*.jsonl",
254
377
  ":(exclude).bkit/issues.jsonl",
255
378
  ];
379
+ /**
380
+ * Kinds no workflow run writes: bkit's harvest script writes them to `harvest/`, and a
381
+ * `run` row names any feature's workflow (`.bkit/jsonl.md` § Ledgers & Writers).
382
+ */
383
+ const NOT_A_RUNS_OWN_KIND = new Set(["chat", "run"]);
384
+ /** HEAD and every `parentSha` the run's status rows of `workflow` carry: the shas its `run.parentSha` can name. */
385
+ function runShas(src, status, workflow) {
386
+ const shas = new Set([headSha(src)]);
387
+ for (const e of fs.existsSync(status) ? readStatusEvents(status) : []) {
388
+ const sha = e.parentSha;
389
+ if (e.workflow === workflow && typeof sha === "string")
390
+ shas.add(sha);
391
+ }
392
+ shas.delete("");
393
+ return shas;
394
+ }
395
+ /** A feature id in `references`: a bare number or `{N}-{slug}`. */
396
+ const FEATURE_REF = /^\d+(-[a-z0-9-]+)?$/;
397
+ /**
398
+ * A shared-ledger row (normalized) of THIS run: a row of `workflow` at or after its
399
+ * start, never a kind no run writes. A row with `run.parentSha` (compliance, counter,
400
+ * outcome) must name one of the run's shas; any other row must not point at a
401
+ * different feature in its `references`.
402
+ */
403
+ function isRunsOwnRow(row, o, shas) {
404
+ if (byWorkflow(row) !== o.workflow || !(Number(row.ts) >= o.startMs))
405
+ return false;
406
+ if (NOT_A_RUNS_OWN_KIND.has(String(row.kind)))
407
+ return false;
408
+ const sha = row.run?.parentSha;
409
+ if (sha !== undefined)
410
+ return typeof sha === "string" && shas.has(sha);
411
+ const features = (Array.isArray(row.references) ? row.references : [])
412
+ .map(String)
413
+ .filter((r) => FEATURE_REF.test(r));
414
+ const n = /^(\d+)-/.exec(o.fid)?.[1];
415
+ return features.length === 0 || features.some((r) => r === o.fid || r === n);
416
+ }
256
417
  /**
257
418
  * Carry ONLY the run's own record out of a dev / main / detached checkout, which
258
419
  * other sessions and local-only commits share: the `.md` logs it wrote in its log
259
420
  * folder; the lines of that folder's `.jsonl` files its HEAD lacks; and, from the
260
- * shared ledgers, lines its HEAD lacks that are rows of `workflow` at or after
261
- * the run's start (`startMs`). No start known → no shared-ledger row is carried.
421
+ * shared ledgers, lines its HEAD lacks that are this run's rows ({@link isRunsOwnRow}).
422
+ * No start known → no shared-ledger row is carried.
262
423
  */
263
424
  function carryOwnBook(src, dst, o, log) {
264
425
  const rel = logDirRel(o.month, o.fid);
265
426
  const carried = { files: carryLogs(src, dst, rel), lines: new Map() };
266
- const uncommitted = (file) => {
267
- const head = new Set(textLines(git(src, ["show", `HEAD:${file}`]) ?? "").map((l) => l.trim()));
268
- return textLines(fs.readFileSync(path.join(src, file), "utf-8")).filter((l) => !head.has(l.trim()));
269
- };
427
+ // Rows the run appended; on a shared checkout, recorded foreign rows are never carried.
428
+ const rec = activeRecord(src, o.fid);
429
+ const uncommitted = (file) => runRows(src, file, rec);
270
430
  const add = (file, lines) => {
271
431
  const to = path.join(dst, file);
272
432
  const existing = fs.existsSync(to) ? fs.readFileSync(to, "utf-8") : "";
@@ -288,11 +448,11 @@ function carryOwnBook(src, dst, o, log) {
288
448
  log(`no ${o.workflow} start row for ${o.fid} — no shared-ledger row carried`);
289
449
  return carried;
290
450
  }
451
+ const shas = runShas(src, path.join(src, statusRelPath(o.month, o.fid)), o.workflow);
291
452
  for (const file of listed(SHARED_LEDGERS)) {
292
453
  const own = uncommitted(file).filter((l) => {
293
- const parsed = parseJson(l);
294
- const row = parsed.ok ? parsed.value : null;
295
- return row?.workflow === o.workflow && Number(row.ts) >= o.startMs;
454
+ const row = parseObject(l);
455
+ return row !== undefined && isRunsOwnRow(normalize(row), o, shas);
296
456
  });
297
457
  if (own.length > 0)
298
458
  add(file, own);
@@ -305,14 +465,18 @@ function carryOwnBook(src, dst, o, log) {
305
465
  * log identical to the landed copy is removed when untracked, or returns to HEAD
306
466
  * when tracked. A carried ledger loses exactly the carried lines; it returns to
307
467
  * HEAD when that leaves it equal, and an untracked one left empty is removed.
308
- * Anything staged, or a log changed since it landed, stays and is named.
468
+ * Anything staged, or a log changed since it landed, stays and is named. A path
469
+ * the shared-checkout record lists is never reset or removed.
309
470
  */
310
- function handBack(tree, sha, carried, log) {
471
+ function handBack(tree, sha, carried, log, recorded = new Set()) {
311
472
  const back = [];
312
473
  const kept = [];
313
474
  const staged = (rel) => !runGit(tree, ["diff", "--cached", "--quiet", "--", rel]).ok;
314
475
  const tracked = (rel) => runGit(tree, ["ls-files", "--error-unmatch", "--", rel]).ok;
315
476
  for (const rel of carried.files) {
477
+ // A path that was dirty before the run started is not the run's to reset.
478
+ if (recorded.has(rel))
479
+ continue;
316
480
  const abs = path.join(tree, rel);
317
481
  const landed = runGit(tree, ["show", `${sha}:${rel}`]);
318
482
  const same = landed.ok && fs.existsSync(abs) && fs.readFileSync(abs, "utf-8").trim() === landed.stdout;
@@ -451,6 +615,18 @@ async function landFailedRecord(ctx, o) {
451
615
  return stop(EXIT_FLUSH_FAILED, `throwaway checkout failed: ${res.stderr}`);
452
616
  }
453
617
  }
618
+ /**
619
+ * What `handover --push` would sweep into the abort commit besides the run's own
620
+ * logs: tracked files with changes, and untracked files (each one listed, not its folder).
621
+ */
622
+ function strayPaths(tree, logDir) {
623
+ const outside = (out) => (out ?? "").split("\0").filter((p) => p !== "" && p !== logDir && !p.startsWith(`${logDir}/`));
624
+ return {
625
+ // Staged and unstaged changes alike, against HEAD.
626
+ modified: outside(git(tree, ["diff", "--name-only", "-z", "--no-renames", "HEAD"])),
627
+ untracked: outside(git(tree, ["ls-files", "-z", "--others", "--exclude-standard"])),
628
+ };
629
+ }
454
630
  async function handoverVerb(ctx) {
455
631
  const workflow = workflowName(String(ctx.flags.workflow));
456
632
  const fid = String(ctx.flags.fid);
@@ -474,7 +650,14 @@ async function handoverVerb(ctx) {
474
650
  const branch = git(tree, ["branch", "--show-current"]) ?? "";
475
651
  // A dev / main / detached checkout is shared: only the run's own record leaves it.
476
652
  const shared = branch === "" || isSharedBranch(branch);
653
+ if (ctx.flags.listStray === true) {
654
+ if (push || flush || ctx.flags.post === true)
655
+ throw new CommandError(EXIT.USAGE, "--list-stray only lists: drop --push, --flush and --post");
656
+ ctx.emit({ shared, ...strayPaths(tree, logDirRel(month, fid)) });
657
+ return EXIT.OK;
658
+ }
477
659
  let handed;
660
+ const rec = shared && (push || flush) ? activeRecord(tree, fid) : null;
478
661
  if (push && shared) {
479
662
  const r = await landFailedRecord(ctx, { workflow, fid, month, book: tree, shared });
480
663
  if (r.sha !== undefined && r.carried !== undefined)
@@ -485,11 +668,11 @@ async function handoverVerb(ctx) {
485
668
  skipped = r.skipped;
486
669
  }
487
670
  else if (push) {
488
- runGit(tree, ["add", "-A"]);
671
+ addAllButCopied(tree);
489
672
  const made = runGit(tree, ["commit", "-m", `docs(${fid}): ${workflow} aborted bkit [skip ci]`]);
490
673
  if (!made.ok)
491
674
  ctx.log(`abort commit: ${made.stderr || made.stdout}`);
492
- const r = pushBranch(tree, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
675
+ const r = await pushBranch(tree, { mode: "abort", openPr: str(ctx.flags.openPr) }, ctx.log);
493
676
  if (r.code === EXIT.USE_MCP)
494
677
  return r.code;
495
678
  pushed = r.out.pushed;
@@ -521,19 +704,30 @@ async function handoverVerb(ctx) {
521
704
  bodyFile: artifact,
522
705
  })
523
706
  : null;
524
- if (handed !== undefined)
525
- handBack(tree, handed.sha, handed.carried, ctx.log);
707
+ if (handed !== undefined) {
708
+ handBack(tree, handed.sha, handed.carried, ctx.log, new Set(rec?.paths.map((p) => p.path)));
709
+ }
710
+ // The run is over once its record is handed back: the next run starts a fresh one.
711
+ if (rec !== null)
712
+ removeRecord(tree, fid);
713
+ const tracker = ctx.flags.post === true && comment !== null
714
+ ? await postForVerb(ctx, comment, { fid })
715
+ : undefined;
526
716
  ctx.emit({
527
717
  handover: present ? artifact : null,
528
718
  pushed,
529
719
  ref: pushed ? ref : null,
530
720
  skipped,
531
721
  comment,
722
+ commentFile: commentFileOf(ctx.cwd, comment),
723
+ ...(tracker === undefined ? {} : { tracker }),
532
724
  });
533
725
  return code;
534
726
  }
727
+ /** The row's `by.workflow`, on a row already normalized. */
728
+ const byWorkflow = (r) => r.by?.workflow;
535
729
  /** Rows of a JSONL ledger; malformed lines are skipped, a missing file is empty. */
536
- function ledgerRows(file) {
730
+ export function ledgerRows(file) {
537
731
  if (!fs.existsSync(file))
538
732
  return [];
539
733
  return fs
@@ -562,46 +756,27 @@ const distinctKeys = (rows) => new Set(rows.filter((r) => r.key !== undefined).m
562
756
  * counting the ledger's whole history as this run's.
563
757
  */
564
758
  function ledgerCounts(tree, workflow, startMs) {
565
- const deferrals = ledgerRows(path.join(tree, "docs", "deferrals.jsonl"));
566
- const failures = ledgerRows(path.join(tree, "docs", "failures.jsonl"));
567
- const friction = ledgerRows(path.join(tree, ".bkit", "friction.jsonl"));
568
- const added = (rows) => distinctKeys(rows.filter((r) => r.workflow === workflow && Number(r.ts) >= startMs));
569
- return {
570
- deferrals: distinctKeys(deferrals.filter((r) => r.kind === "deferral")),
571
- failures: distinctKeys(failures.filter((r) => r.kind === "failure")),
572
- ...(startMs === undefined
573
- ? {}
574
- : {
575
- frictionAdded: added(friction),
576
- deferralsAdded: added(deferrals),
577
- failuresAdded: added(failures),
578
- }),
579
- };
580
- }
581
- /** `git diff --shortstat` numbers; 0 for anything absent or a range git rejects. */
582
- export function diffStat(cwd, range) {
583
- const out = runGit(cwd, ["diff", "--shortstat", range]).stdout;
584
- const num = (re) => Number(re.exec(out)?.[1] ?? 0);
585
- const linesAdded = num(/(\d+) insertions?\(/);
586
- const linesDeleted = num(/(\d+) deletions?\(/);
759
+ const read = (file) => ledgerRows(file).map((r) => normalize(r));
760
+ const deferrals = read(path.join(tree, "docs", "deferrals.jsonl"));
761
+ const failures = read(path.join(tree, "docs", "failures.jsonl"));
762
+ const friction = read(path.join(tree, ".bkit", "friction.jsonl"));
763
+ const added = (rows) => startMs === undefined
764
+ ? {}
765
+ : {
766
+ added: distinctKeys(rows.filter((r) => byWorkflow(r) === workflow && Number(r.ts) >= startMs)),
767
+ };
587
768
  return {
588
- linesAdded,
589
- linesDeleted,
590
- linesChanged: linesAdded + linesDeleted,
591
- filesChanged: num(/(\d+) files? changed/),
769
+ deferrals: {
770
+ repo: distinctKeys(deferrals.filter((r) => r.kind === "deferral")),
771
+ ...added(deferrals),
772
+ },
773
+ failures: {
774
+ repo: distinctKeys(failures.filter((r) => r.kind === "failure")),
775
+ ...added(failures),
776
+ },
777
+ friction: added(friction),
592
778
  };
593
779
  }
594
- /** Checklist items (`- [`) across the feature's plan and sub-plans. */
595
- function taskCount(tree, month, fid) {
596
- const dir = path.join(tree, "docs", "plans", month);
597
- if (!fs.existsSync(dir))
598
- return 0;
599
- return fs
600
- .readdirSync(dir)
601
- .filter((f) => f.startsWith(`${fid}-plan`) && f.endsWith(".md"))
602
- .flatMap((f) => fs.readFileSync(path.join(dir, f), "utf-8").split("\n"))
603
- .filter((l) => l.startsWith("- [")).length;
604
- }
605
780
  /** Per-tier coverage from `coverage/{tier}/coverage-summary.json`; undefined when none. */
606
781
  function coverage(tree) {
607
782
  const out = {};
@@ -629,23 +804,15 @@ function lastOfType(events, type, workflow) {
629
804
  .sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0))
630
805
  .at(-1);
631
806
  }
632
- /** Append telemetry rows; best-effort, so a bad path is logged and never fails the close. */
633
- function appendStats(file, rows, log) {
634
- const valid = rows.filter((r) => {
635
- const v = validate(r);
636
- if (!v.ok)
637
- log(`[bkit-telemetry] ${String(r.kind)} row invalid, not written: ${v.reason}`);
638
- return v.ok;
639
- });
640
- if (valid.length === 0)
641
- return false;
807
+ /** Append the close's stats rows; best-effort, so a refused row or a bad path is logged and never fails the close. */
808
+ function appendStats(tree, rows, log) {
642
809
  try {
643
- fs.appendFileSync(file, valid.map((r) => `${telemetryLine(r)}\n`).join(""));
810
+ appendLedgerRows(tree, "stats", rows);
644
811
  return true;
645
812
  }
646
813
  catch (err) {
647
- // Telemetry never gates a close: report the failed append and carry on.
648
- log(`[bkit-telemetry] append failed: ${file} — ${err.message}`);
814
+ // Telemetry never gates a close: report the refused append and carry on.
815
+ log(`[bkit-telemetry] stats rows not written: ${err.message}`);
649
816
  return false;
650
817
  }
651
818
  }
@@ -683,7 +850,8 @@ function closeComment(cwd, outbox, o) {
683
850
  * Grade compliance, append the workflow-done row (and, with `recordStep`, the
684
851
  * close step's row first), the counter and outcome telemetry rows, and build the
685
852
  * report and artifact links; with `outbox`, write them for the close comment; with
686
- * `message`, commit everything (`git add -A`) in the tree.
853
+ * `message`, commit everything (`git add -A`, minus the `bkit.workflows.worktree.copy` entries) in the tree, or, in an in-place run
854
+ * on a shared branch, only the run's own paths.
687
855
  */
688
856
  export function closeWorkflow(cwd, o, log) {
689
857
  const workflow = workflowName(o.workflow);
@@ -691,67 +859,83 @@ export function closeWorkflow(cwd, o, log) {
691
859
  const events = readStatusEvents(where.status);
692
860
  if (o.squashSha !== undefined && !/^[0-9a-f]{7,40}$/.test(o.squashSha))
693
861
  throw new CommandError(EXIT.USAGE, `--squash-sha "${o.squashSha}" is not a commit sha`);
694
- // Graded first, so the report below carries this run's grade.
695
- const violations = gradeCompliance(where.tree, workflow, log, o.squashSha);
862
+ // An in-place run on a shared branch commits its own paths only; a refusal
863
+ // comes before any row is appended, so the re-run after the human's fix writes each row once.
864
+ const rec = o.message === undefined ? null : activeRecord(where.tree, o.fid);
865
+ if (o.message !== undefined)
866
+ requireRecordOnShared(where.tree, workflow, rec);
867
+ if (rec !== null)
868
+ ownSet(where.tree, rec);
696
869
  const step = `${workflow}-close-workflow`;
870
+ // The run's join key: every row of this run carries HEAD at close as `run.parentSha`.
871
+ const parentSha = headSha(where.tree);
872
+ // Graded first, so the report below carries this run's grade.
873
+ const violations = gradeCompliance(where.tree, workflow, log, o.squashSha, { parentSha, step });
697
874
  if (o.recordStep === true) {
698
875
  writeStepRow(where.tree, { file: where.status, workflow, step, artifacts: [], commit: "none" }, log);
699
876
  }
700
- const row = { type: "workflow-done", workflow, at: statusTimestamp() };
877
+ const endAt = statusTimestamp();
878
+ const row = { type: "workflow-done", workflow, at: endAt, parentSha };
701
879
  fs.appendFileSync(where.status, appendLine(row));
702
880
  const repo = resolveRepoSlug(where.root) || "unknown/repo";
703
- const bkitVersion = readBkitVersion(path.join(where.root, ".bkit", "version"))?.pinnedVersion || "unknown";
704
- const parentSha = headSha(where.tree);
705
881
  const started = lastOfType(events, "workflow-started", workflow);
706
882
  const startAt = started?.at;
707
883
  const startMs = startAt ? Date.parse(startAt) : NaN;
708
884
  const startKnown = Number.isFinite(startMs) ? startMs : undefined;
709
- const planSource = events
710
- .filter((e) => e.type === "workflow-meta" &&
711
- e.workflow === workflow &&
712
- (startAt === undefined || e.at >= startAt) &&
713
- e.planSource)
714
- .at(-1);
885
+ const runRowsOf = startAt === undefined ? [] : runStatusRows(readStatusEvents(where.status), workflow, startAt);
715
886
  const base = typeof started?.parentSha === "string" ? started.parentSha : "";
716
- const range = o.squashSha
717
- ? `${o.squashSha}^..${o.squashSha}`
718
- : base
719
- ? `${base}..HEAD`
720
- : "origin/dev...HEAD";
721
- const durationSeconds = startKnown === undefined ? 0 : Math.max(0, Math.floor((Date.now() - startKnown) / 1000));
887
+ const lines = o.squashSha
888
+ ? runLines(where.tree, `${o.squashSha}^`, o.squashSha)
889
+ : runLines(where.tree, base, parentSha);
722
890
  const startedRows = new Set(events.filter((e) => e.type === "workflow-started" && e.workflow === workflow).map((e) => e.at)).size;
723
- const ts = Date.now();
891
+ const logDir = path.join(where.tree, logDirRel(where.month, o.fid));
892
+ const by = { workflow, step };
724
893
  const counterRow = {
725
- ts,
726
894
  kind: "counter",
727
- workflow,
728
- repo,
729
- bkitVersion,
730
- step,
731
- counterName: `${workflow.toUpperCase()}_ATTEMPT`,
732
- counterValue: Math.max(1, startedRows),
733
- counterSource: "shell-bus",
734
- parentSha,
895
+ by,
896
+ run: { parentSha },
897
+ counter: {
898
+ name: `${workflow.toUpperCase()}_ATTEMPT`,
899
+ value: Math.max(1, startedRows),
900
+ source: "shell-bus",
901
+ },
735
902
  };
736
903
  const cov = workflow === "ship" ? coverage(where.tree) : undefined;
904
+ const ci = ciList(runRowsOf);
905
+ const plan = ["plan", "build", "ship"].includes(workflow)
906
+ ? planBlock(where.tree, where.month, o.fid, events)
907
+ : undefined;
908
+ const endMs = Date.parse(endAt);
909
+ /** This run's `docs/deferrals.jsonl` rows; none when its start is unknown. */
910
+ const runDeferrals = () => startKnown === undefined
911
+ ? []
912
+ : ledgerRows(path.join(where.tree, "docs", "deferrals.jsonl"))
913
+ .map((r) => normalize(r))
914
+ .filter((r) => byWorkflow(r) === workflow && Number(r.ts) >= startKnown);
915
+ const context = startKnown === undefined
916
+ ? undefined
917
+ : agentContextBlock(startKnown, endMs, claudeTranscripts(process.env, os.homedir()), runChats(runRowsOf));
737
918
  const outcomeRow = {
738
- ts: ts + 1,
739
919
  kind: "outcome",
740
- workflow,
741
- repo,
742
- bkitVersion,
743
- step,
744
- parentSha,
745
- ...(o.prNumber === undefined ? {} : { prNumber: o.prNumber }),
746
- ...diffStat(where.tree, range),
747
- taskCount: taskCount(where.tree, where.month, o.fid),
748
- durationSeconds,
749
- ...ledgerCounts(where.tree, workflow, startKnown),
750
- ...(planSource?.planSource ? { planSource: planSource.planSource } : {}),
751
- ...(cov ? { coverage: cov } : {}),
920
+ by,
921
+ run: { parentSha, ...(o.prNumber === undefined ? {} : { pr: o.prNumber }) },
922
+ time: startKnown === undefined ? null : timeBlock(startKnown, Math.max(startKnown, endMs)),
923
+ ending: "done",
924
+ lines,
925
+ ...(runRowsOf.length > 0 ? { steps: stepsBlock(runRowsOf) } : {}),
926
+ ...(ci.length > 0 ? { ci } : {}),
927
+ ledgers: ledgerCounts(where.tree, workflow, startKnown),
928
+ ...(plan === undefined ? {} : { plan }),
929
+ ...(workflow === "build"
930
+ ? {
931
+ build: buildBlock(runRowsOf, logDir, planFiles(where.tree, where.month, o.fid), runDeferrals()),
932
+ }
933
+ : {}),
934
+ ...(context === undefined ? {} : { context }),
935
+ ...(cov ? { ship: { coverage: cov } } : {}),
752
936
  };
753
937
  const stats = path.join(where.tree, ".bkit", "stats.jsonl");
754
- const telemetryWritten = appendStats(stats, [counterRow, outcomeRow], log);
938
+ const telemetryWritten = appendStats(where.tree, [counterRow, outcomeRow], log);
755
939
  const report = fs.existsSync(stats)
756
940
  ? workflowTelemetry(foldFrom([stats]), workflow).lines
757
941
  : ["[bkit-telemetry] stats.jsonl not found — no telemetry rows yet"];
@@ -788,16 +972,24 @@ export function closeWorkflow(cwd, o, log) {
788
972
  message += " bkit [verbose ci]";
789
973
  if ((o.labels ?? []).includes(AUTO_LABEL))
790
974
  message += AUTO_ROUTE_SUFFIX;
791
- const add = runGit(where.tree, ["add", "-A"]);
792
- const made = add.ok ? runGit(where.tree, ["commit", "--allow-empty", "-m", message]) : add;
793
- if (!made.ok)
794
- throw new CommandError(EXIT.NO, `close commit failed: ${made.stderr || made.stdout}`);
975
+ if (rec !== null) {
976
+ const made = ownPathCommit(where.tree, rec, message, { allowEmpty: true });
977
+ if (!made.ok)
978
+ throw new CommandError(EXIT.NO, `close commit failed: ${made.error}`);
979
+ }
980
+ else {
981
+ const add = addAllButCopied(where.tree);
982
+ const made = add.ok ? runGit(where.tree, ["commit", "--allow-empty", "-m", message]) : add;
983
+ if (!made.ok)
984
+ throw new CommandError(EXIT.NO, `close commit failed: ${made.stderr || made.stdout}`);
985
+ }
795
986
  commit = headSha(where.tree);
796
987
  }
797
988
  return {
798
989
  row,
799
- counterRow: validate(counterRow).ok ? counterRow : null,
800
- outcomeRow: validate(outcomeRow).ok ? outcomeRow : null,
990
+ // The rows as drafted; the ledger copies add the top section `ledgers append` fills.
991
+ counterRow: telemetryWritten ? counterRow : null,
992
+ outcomeRow: telemetryWritten ? outcomeRow : null,
801
993
  telemetryWritten,
802
994
  compliance: violations === null ? null : violations.length,
803
995
  report,
@@ -945,22 +1137,6 @@ async function shipClose(ctx, o, token) {
945
1137
  // ---------------------------------------------------------------------------
946
1138
  // promote
947
1139
  // ---------------------------------------------------------------------------
948
- /** The highest `{workflow}-v{N}-*.md` draft (sub-plan children `-v{N}-{k}.md` excluded), or null. */
949
- export function highestVersion(dir, workflow) {
950
- if (!fs.existsSync(dir))
951
- return null;
952
- const re = new RegExp(`^${workflow}-v([0-9]+)-(.+)\\.md$`);
953
- let best = null;
954
- for (const f of fs.readdirSync(dir).sort()) {
955
- const m = re.exec(f);
956
- if (!m || /^[0-9]+$/.test(m[2]))
957
- continue;
958
- const n = Number(m[1]);
959
- if (best === null || n > best.n)
960
- best = { file: f, n };
961
- }
962
- return best;
963
- }
964
1140
  /** Stamp `file`'s anchor when a base commit is known (plan: with its design's own anchor; both: the bkit release). */
965
1141
  function stamp(cwd, file, baseSha, design) {
966
1142
  if (baseSha === "")
@@ -989,7 +1165,7 @@ function promoteVerb(ctx) {
989
1165
  }
990
1166
  const final = path.join(logs, best.file);
991
1167
  if (ctx.flags.resolve === true) {
992
- ctx.emit({ final, canonical: null, archived: [], subPlans: [], baseSha: null });
1168
+ ctx.emit({ final, canonical: null, archived: [], baseSha: null });
993
1169
  return EXIT.OK;
994
1170
  }
995
1171
  // The base commit Step 2 recorded on the runtime-resolved row.
@@ -1007,13 +1183,7 @@ function promoteVerb(ctx) {
1007
1183
  const bucket = path.join("docs", "plans", month);
1008
1184
  const canonical = path.join(bucket, `${fid}-${workflow}.md`);
1009
1185
  stamp(ctx.cwd, final, baseSha, design);
1010
- const children = workflow === "plan"
1011
- ? fs
1012
- .readdirSync(path.resolve(ctx.cwd, logs))
1013
- .filter((f) => new RegExp(`^plan-v${best.n}-[0-9]+\\.md$`).test(f))
1014
- .sort()
1015
- : [];
1016
- // A changed canonical moves to archive/ first — plan moves the whole set under one timestamp.
1186
+ // A changed canonical moves to archive/ first.
1017
1187
  const archived = [];
1018
1188
  const canonicalAbs = path.resolve(ctx.cwd, canonical);
1019
1189
  if (fs.existsSync(canonicalAbs) &&
@@ -1024,42 +1194,103 @@ function promoteVerb(ctx) {
1024
1194
  .replace(/\.\d+Z$/, "Z");
1025
1195
  const archive = path.join(bucket, "archive");
1026
1196
  fs.mkdirSync(path.resolve(ctx.cwd, archive), { recursive: true });
1027
- const set = fs
1028
- .readdirSync(path.resolve(ctx.cwd, bucket))
1029
- .filter((f) => workflow === "plan"
1030
- ? f === `${fid}-plan.md` || new RegExp(`^${fid}-plan-[0-9]+\\.md$`).test(f)
1031
- : f === `${fid}-design.md`);
1032
- for (const f of set) {
1033
- const to = path.join(archive, `${ts}-${f}`);
1034
- fs.renameSync(path.resolve(ctx.cwd, bucket, f), path.resolve(ctx.cwd, to));
1035
- archived.push(to);
1036
- }
1197
+ const to = path.join(archive, `${ts}-${fid}-${workflow}.md`);
1198
+ fs.renameSync(canonicalAbs, path.resolve(ctx.cwd, to));
1199
+ archived.push(to);
1037
1200
  }
1038
1201
  fs.mkdirSync(path.resolve(ctx.cwd, bucket), { recursive: true });
1039
1202
  fs.copyFileSync(path.resolve(ctx.cwd, final), canonicalAbs);
1040
- const subPlans = [];
1041
- for (const child of children) {
1042
- const k = /-([0-9]+)\.md$/.exec(child)[1];
1043
- stamp(ctx.cwd, path.join(logs, child), baseSha, design);
1044
- const to = path.join(bucket, `${fid}-plan-${k}.md`);
1045
- fs.copyFileSync(path.resolve(ctx.cwd, logs, child), path.resolve(ctx.cwd, to));
1046
- subPlans.push(to);
1047
- }
1048
- if (workflow === "plan") {
1049
- // Working names in the copies become the canonical names.
1050
- for (const f of [canonical, ...subPlans]) {
1051
- const abs = path.resolve(ctx.cwd, f);
1052
- fs.writeFileSync(abs, fs
1053
- .readFileSync(abs, "utf-8")
1054
- .replace(/plan-v[0-9]+-split\.md/g, `${fid}-plan.md`)
1055
- .replace(/plan-v[0-9]+-([0-9]+)\.md/g, `${fid}-plan-$1.md`));
1056
- }
1057
- }
1058
1203
  if (fs.statSync(canonicalAbs).size === 0) {
1059
1204
  ctx.log(`canonical empty: ${canonical}`);
1060
1205
  return EXIT_NO_VERSION;
1061
1206
  }
1062
- ctx.emit({ final, canonical, archived, subPlans, baseSha: baseSha || null });
1207
+ ctx.emit({ final, canonical, archived, baseSha: baseSha || null });
1208
+ return EXIT.OK;
1209
+ }
1210
+ // ---------------------------------------------------------------------------
1211
+ // summary
1212
+ // ---------------------------------------------------------------------------
1213
+ /** ship: the PR's size from `gh pr view`; undefined (logged) when gh cannot answer. */
1214
+ function prSize(cwd, pr, log) {
1215
+ const res = runGh(cwd, ["pr", "view", String(pr), "--json", "additions,deletions,changedFiles"]);
1216
+ const parsed = res.ok ? parseJson(res.stdout) : undefined;
1217
+ const v = parsed?.ok === true ? parsed.value : undefined;
1218
+ if (typeof v?.additions !== "number" ||
1219
+ typeof v.deletions !== "number" ||
1220
+ typeof v.changedFiles !== "number") {
1221
+ log(`gh pr view ${pr} gave no size; the summary leaves the PR line out`);
1222
+ return undefined;
1223
+ }
1224
+ return {
1225
+ number: pr,
1226
+ additions: v.additions,
1227
+ deletions: v.deletions,
1228
+ changedFiles: v.changedFiles,
1229
+ };
1230
+ }
1231
+ function summaryVerb(ctx) {
1232
+ const workflow = String(ctx.flags.workflow);
1233
+ if (!SUMMARY_WORKFLOWS.includes(workflow))
1234
+ throw new CommandError(EXIT.USAGE, `--workflow must be ${SUMMARY_WORKFLOWS.join(", ")}`);
1235
+ const file = path.resolve(ctx.cwd, String(ctx.flags.file));
1236
+ const logDir = path.dirname(file);
1237
+ const fid = path.basename(logDir);
1238
+ const month = path.basename(path.dirname(path.dirname(logDir)));
1239
+ const tree = path.resolve(logDir, "..", "..", "..", "..", "..");
1240
+ if (!/^[0-9]{6}$/.test(month) || path.join(tree, logDirRel(month, fid)) !== logDir)
1241
+ throw new CommandError(EXIT.USAGE, `--file must be docs/plans/{YYYYMM}/logs/{FID}/status.jsonl, got ${file}`);
1242
+ const events = readStatusEvents(file);
1243
+ const started = lastOfType(events, "workflow-started", workflow);
1244
+ if (started === undefined)
1245
+ throw new CommandError(EXIT_NO_RUN, `${file} has no ${workflow} run (no workflow-started row)`);
1246
+ const rows = runStatusRows(events, workflow, started.at);
1247
+ const startMs = Date.parse(started.at);
1248
+ const rel = (abs) => path.relative(tree, abs).split(path.sep).join("/");
1249
+ const given = list(ctx.flags.plan).map((p) => path.resolve(ctx.cwd, p));
1250
+ const plans = given.length > 0 ? given : workflow === "build" ? planFiles(tree, month, fid) : [];
1251
+ const read = (r) => {
1252
+ const abs = path.resolve(tree, r);
1253
+ return fs.existsSync(abs) && fs.statSync(abs).isFile() ? fs.readFileSync(abs, "utf-8") : null;
1254
+ };
1255
+ const deferrals = ledgerRows(path.join(tree, "docs", "deferrals.jsonl"))
1256
+ .map((r) => normalize(r))
1257
+ .filter((r) => byWorkflow(r) === workflow && Number(r.ts) >= startMs);
1258
+ const organisedPath = path.join(logDir, "design-v3-organised.md");
1259
+ const organised = workflow === "design" && fs.existsSync(organisedPath)
1260
+ ? fs.readFileSync(organisedPath, "utf-8")
1261
+ : undefined;
1262
+ const prNumber = positiveInt(ctx.flags.pr, "pr");
1263
+ const summary = buildSummary({
1264
+ workflow: workflow,
1265
+ fid,
1266
+ ref: refOf(fid, readIssueTracker(tree)),
1267
+ rows,
1268
+ plans: plans.map((p) => ({ path: rel(p), text: fs.readFileSync(p, "utf-8") })),
1269
+ deferrals,
1270
+ deferralsAdded: ledgerCounts(tree, workflow, startMs).deferrals.added ?? 0,
1271
+ decisionFiles: (workflow === "build" || workflow === "ship") && fs.existsSync(logDir)
1272
+ ? fs
1273
+ .readdirSync(logDir)
1274
+ .filter((f) => /^build-decision-.*\.md$/.test(f))
1275
+ .sort()
1276
+ .map((f) => rel(path.join(logDir, f)))
1277
+ : [],
1278
+ read,
1279
+ workstreams: organised === undefined ? undefined : parseWorkstreams(organised),
1280
+ organised,
1281
+ pr: workflow === "ship" && prNumber !== undefined
1282
+ ? prSize(ctx.cwd, prNumber, ctx.log)
1283
+ : undefined,
1284
+ });
1285
+ const out = path.join(logDir, `${workflow}-summary.md`);
1286
+ fs.writeFileSync(out, summary.markdown);
1287
+ ctx.emit({
1288
+ verdict: summary.verdict,
1289
+ failures: summary.failures,
1290
+ reasons: summary.reasons,
1291
+ file: rel(out),
1292
+ nextStep: summary.nextStep,
1293
+ });
1063
1294
  return EXIT.OK;
1064
1295
  }
1065
1296
  // ---------------------------------------------------------------------------
@@ -1089,10 +1320,224 @@ const OWNER_REPO_FLAG = {
1089
1320
  const COMMENT_FLAGS = [
1090
1321
  { name: "number", type: "string", help: "step number: print the close comment (needs --outbox)" },
1091
1322
  { name: "title", type: "string", help: "step title of the close comment" },
1323
+ {
1324
+ ...POST_FLAG,
1325
+ 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`",
1326
+ },
1092
1327
  ];
1328
+ const SESSION_DIR_FLAG = {
1329
+ name: "session-dir",
1330
+ type: "string",
1331
+ help: "the run's session folder (`repo info` sessionDir): deleted once this run ends",
1332
+ };
1333
+ const SESSION_REMOVED_OUTPUT = "with --session-dir: the folder was deleted (false: not under <git common dir>/bkit-outbox/sessions/, kept)";
1334
+ /**
1335
+ * `--session-dir`: delete the run's session folder. Only a folder directly under
1336
+ * `<git common dir>/bkit-outbox/sessions/` is deleted; any other path is kept and logged.
1337
+ */
1338
+ function sessionRemoval(ctx) {
1339
+ const given = str(ctx.flags.sessionDir);
1340
+ if (!given)
1341
+ return {};
1342
+ const common = git(ctx.cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
1343
+ const real = (p) => (fs.existsSync(p) ? fs.realpathSync(p) : p);
1344
+ const sessions = common === null ? null : real(path.join(common, "bkit-outbox", "sessions"));
1345
+ const abs = path.resolve(ctx.cwd, given);
1346
+ if (sessions === null || real(path.dirname(abs)) !== sessions) {
1347
+ ctx.log(`--session-dir ${given} is not a session folder under ${sessions ?? "the outbox"}; kept`);
1348
+ return { sessionRemoved: false };
1349
+ }
1350
+ fs.rmSync(abs, { recursive: true, force: true });
1351
+ return { sessionRemoved: true };
1352
+ }
1353
+ const PLAIN_ENGLISH_REPLY = "Would you like me to explain any of this in plain English? Then write 'yes, explain in plain english'.";
1354
+ /**
1355
+ * `--final-return`: the run's last message, read up front (the close may remove the tree
1356
+ * holding the summary, and `--session-dir` the issue facts). Tips are added at print time.
1357
+ */
1358
+ function finalReturnParts(ctx, fid) {
1359
+ if (ctx.flags.finalReturn !== true)
1360
+ return null;
1361
+ const summaryFile = str(ctx.flags.summaryFile);
1362
+ const summary = str(ctx.flags.summary);
1363
+ if (summaryFile !== undefined && summary !== undefined)
1364
+ throw new CommandError(EXIT.USAGE, "give --summary-file or --summary, not both");
1365
+ if (!summaryFile && !summary)
1366
+ throw new CommandError(EXIT.USAGE, "--final-return needs --summary-file or --summary");
1367
+ const parts = [];
1368
+ const warning = str(ctx.flags.warning);
1369
+ if (warning)
1370
+ parts.push(warning);
1371
+ parts.push(summary ? summaryOrMissing(ctx, summary) : inputText(ctx.cwd, summaryFile, "summary-file"));
1372
+ parts.push(...list(ctx.flags.line));
1373
+ const session = str(ctx.flags.sessionDir);
1374
+ const factsFile = session ? path.resolve(ctx.cwd, session, "issue-facts.json") : "";
1375
+ if (factsFile && fs.existsSync(factsFile)) {
1376
+ const parsed = parseJson(fs.readFileSync(factsFile, "utf-8"));
1377
+ const facts = (parsed.ok ? parsed.value : {});
1378
+ const t = trackerTarget(ctx.cwd, { fid });
1379
+ const title = typeof facts.title === "string" ? facts.title : "";
1380
+ const label = [issueRef(t.issue, t.tracker), title].filter(Boolean).join(" ");
1381
+ if (typeof facts.url === "string" && facts.url)
1382
+ parts.push(`[${label}](${facts.url})`);
1383
+ }
1384
+ parts.push("## Suggested Replies", ...list(ctx.flags.suggest), PLAIN_ENGLISH_REPLY);
1385
+ return parts;
1386
+ }
1387
+ /**
1388
+ * `--summary`: the summary file's text, or the `--summary-missing` line when the
1389
+ * file is absent; with `--outbox`, the text is also kept there under the file's
1390
+ * name, outside the tree the close may remove.
1391
+ */
1392
+ function summaryOrMissing(ctx, rel) {
1393
+ const missing = str(ctx.flags.summaryMissing);
1394
+ if (!missing)
1395
+ throw new CommandError(EXIT.USAGE, "--summary needs --summary-missing");
1396
+ const abs = path.resolve(ctx.cwd, rel);
1397
+ const text = fs.existsSync(abs) ? fs.readFileSync(abs, "utf-8").replace(/\s+$/, "") : missing;
1398
+ const outbox = str(ctx.flags.outbox);
1399
+ if (outbox) {
1400
+ const dir = path.resolve(ctx.cwd, outbox);
1401
+ fs.mkdirSync(dir, { recursive: true });
1402
+ fs.writeFileSync(path.join(dir, path.basename(abs)), `${text}\n`);
1403
+ }
1404
+ return text;
1405
+ }
1406
+ function finalReturnText(ctx, workflow, parts) {
1407
+ if (parts === null)
1408
+ return {};
1409
+ const tips = tipsText(false, workflow, ctx.cwd);
1410
+ return { finalReturn: [...parts, ...(tips ? ["## bkit Tips", tips] : [])].join("\n\n") };
1411
+ }
1412
+ // ---------------------------------------------------------------------------
1413
+ // input
1414
+ // ---------------------------------------------------------------------------
1415
+ /** A required input file's text, trailing newlines dropped; missing exits EXIT_NO_INPUT. */
1416
+ function inputText(cwd, rel, flag) {
1417
+ const abs = path.resolve(cwd, rel);
1418
+ if (!fs.existsSync(abs))
1419
+ throw new CommandError(EXIT_NO_INPUT, `--${flag} ${rel} does not exist`);
1420
+ return fs.readFileSync(abs, "utf-8").replace(/\s+$/, "");
1421
+ }
1422
+ /** The run's issue parts from `issues fetch`'s files, oldest first; none for a run with no issue. */
1423
+ function inputIssueParts(ctx) {
1424
+ const descFile = str(ctx.flags.descriptionFile);
1425
+ const commentsFile = str(ctx.flags.commentsFile);
1426
+ const description = descFile ? inputText(ctx.cwd, descFile, "description-file") : "";
1427
+ let comments = [];
1428
+ if (commentsFile) {
1429
+ const parsed = parseJson(inputText(ctx.cwd, commentsFile, "comments-file"));
1430
+ const list = parsed.ok ? parseComments(parsed.value) : null;
1431
+ if (list === null)
1432
+ throw new CommandError(EXIT_NO_INPUT, `--comments-file ${commentsFile} is not a list of comments`);
1433
+ comments = sortOldestFirst(list).comments;
1434
+ }
1435
+ return issueParts(description, comments);
1436
+ }
1437
+ /** An ISO-8601 time in UTC, or undefined when it does not parse. */
1438
+ function utc(at) {
1439
+ const t = at === undefined ? NaN : Date.parse(at);
1440
+ return Number.isNaN(t) ? undefined : new Date(t).toISOString();
1441
+ }
1442
+ /**
1443
+ * When a design or plan file last changed: the author date of its last commit (a
1444
+ * rebase keeps it, unlike the committer date), or undefined (newer than any commit) when the file
1445
+ * has uncommitted changes or no commit.
1446
+ */
1447
+ function committedAt(cwd, rel) {
1448
+ if ((git(cwd, ["status", "--porcelain", "--", rel]) ?? "") !== "")
1449
+ return undefined;
1450
+ return utc(git(cwd, ["log", "-1", "--format=%aI", "--", rel]) || undefined);
1451
+ }
1452
+ const fileDate = (cwd, rel) => {
1453
+ const at = committedAt(cwd, rel);
1454
+ return at === undefined ? "uncommitted changes, newer than any commit" : `last committed ${at}`;
1455
+ };
1456
+ function issueHeading(part) {
1457
+ if (part.kind === "description")
1458
+ return "Issue description — oldest";
1459
+ const at = utc(part.createdAt);
1460
+ return at === undefined
1461
+ ? "Issue comment — no date, counts as oldest"
1462
+ : `Issue comment — posted ${at}`;
1463
+ }
1464
+ /** Comments posted after the plan's last commit; none when the plan is missing or uncommitted. */
1465
+ function newerThanPlan(cwd, plan, parts) {
1466
+ if (!plan || !fs.existsSync(path.resolve(cwd, plan)))
1467
+ return 0;
1468
+ const since = committedAt(cwd, plan);
1469
+ if (since === undefined)
1470
+ return 0;
1471
+ return parts.filter((p) => {
1472
+ const at = utc(p.createdAt);
1473
+ return p.kind === "comment" && at !== undefined && at > since;
1474
+ }).length;
1475
+ }
1476
+ function inputVerb(ctx) {
1477
+ const workflow = workflowName(String(ctx.flags.workflow));
1478
+ const fid = String(ctx.flags.fid);
1479
+ const run = positiveInt(ctx.flags.run, "run");
1480
+ const file = str(ctx.flags.file);
1481
+ const status = file
1482
+ ? path.resolve(ctx.cwd, file)
1483
+ : statusLocation({
1484
+ cwd: ctx.cwd,
1485
+ workflow,
1486
+ fid,
1487
+ month: resolveMonth(repoRoot(ctx.cwd), fid, str(ctx.flags.month) || undefined),
1488
+ }).path;
1489
+ const sections = [
1490
+ [
1491
+ "Session Prompt — this run's, newer than everything below",
1492
+ inputText(ctx.cwd, String(ctx.flags.promptFile), "prompt-file"),
1493
+ ],
1494
+ ];
1495
+ const issue = inputIssueParts(ctx);
1496
+ for (const part of issue)
1497
+ sections.push([issueHeading(part), part.text]);
1498
+ const plan = str(ctx.flags.plan);
1499
+ if (plan && fs.existsSync(path.resolve(ctx.cwd, plan)))
1500
+ sections.push([
1501
+ `Plan — ${plan} — ${fileDate(ctx.cwd, plan)}`,
1502
+ inputText(ctx.cwd, plan, "plan"),
1503
+ ]);
1504
+ const design = str(ctx.flags.design);
1505
+ if (design) {
1506
+ const text = inputText(ctx.cwd, design, "design");
1507
+ sections.push([`Design — ${design} — ${fileDate(ctx.cwd, design)}`, text]);
1508
+ }
1509
+ for (const audit of list(ctx.flags.audit)) {
1510
+ const text = inputText(ctx.cwd, audit, "audit");
1511
+ sections.push([`Audit Report — ${audit} — ${fileDate(ctx.cwd, audit)}`, text]);
1512
+ }
1513
+ const body = sections.map(([h, text]) => `## ${h}\n\n${text}\n`).join("\n");
1514
+ const abs = path.join(path.dirname(status), `${workflow}-input-${run}.md`);
1515
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
1516
+ fs.writeFileSync(abs, body);
1517
+ ctx.emit({
1518
+ path: path.relative(ctx.cwd, abs),
1519
+ bytes: Buffer.byteLength(body),
1520
+ newerThanPlan: newerThanPlan(ctx.cwd, plan, issue),
1521
+ });
1522
+ return EXIT.OK;
1523
+ }
1524
+ /**
1525
+ * Close / links output gains `commentFile`; with `--post`, the close comment once,
1526
+ * deduped by marker hash against the issue's latest comments (the close commit is
1527
+ * already made, so no engine-action row can land in it).
1528
+ */
1529
+ async function postClose(ctx, fid, out) {
1530
+ const comment = typeof out.comment === "string" ? out.comment : null;
1531
+ const withFile = { ...out, commentFile: commentFileOf(ctx.cwd, comment) };
1532
+ if (ctx.flags.post !== true)
1533
+ return withFile;
1534
+ if (comment === null)
1535
+ throw new CommandError(EXIT.USAGE, "--post needs --number");
1536
+ return { ...withFile, tracker: await postForVerb(ctx, comment, { fid }) };
1537
+ }
1093
1538
  export const workflowsCommand = {
1094
1539
  noun: "workflows",
1095
- summary: "Start, fail, hand over and close a phase workflow run; promote and link its documents.",
1540
+ summary: "Start, fail, hand over, summarize and close a phase workflow run; promote and link its documents.",
1096
1541
  verbs: {
1097
1542
  start: {
1098
1543
  summary: "Take the feature lock and open a run (workflow-started unless resuming).",
@@ -1107,6 +1552,11 @@ export const workflowsCommand = {
1107
1552
  help: "Step 1 already took the lock: check it is ours instead of acquiring",
1108
1553
  },
1109
1554
  TOKEN_FLAG,
1555
+ {
1556
+ name: "branch",
1557
+ type: "string",
1558
+ help: "the branch the checkout must be on; refuse (15) before anything is written when it is not",
1559
+ },
1110
1560
  ],
1111
1561
  output: {
1112
1562
  lock: "{path, month, token, reclaimed} of the lock taken, or {path} with --lock-held",
@@ -1114,11 +1564,15 @@ export const workflowsCommand = {
1114
1564
  resumed: "the latest run was this workflow, IN_PROGRESS: no new row",
1115
1565
  row: "the appended workflow-started row, or null when resuming",
1116
1566
  run: "which run of the workflow this is (1-based)",
1567
+ lastDoneStep: "the current run's last DONE step: resume after it (null on a new run)",
1568
+ openDecision: "{file, decision, question, from, pauseStep, group, verifyAttempt, testAttempt, plan} of the current run's highest {workflow}-decision-{run}-{N}.md holding Status: OPEN, else null",
1117
1569
  },
1570
+ textOmit: ["row"],
1118
1571
  exitCodes: {
1119
1572
  [EXIT_NO_STATUS]: "status.jsonl is not valid",
1120
1573
  [EXIT_SPLIT_BUCKET]: "the feature has logs in more than one month bucket",
1121
1574
  [EXIT_LOCK_NOT_HELD]: "--lock-held: the lock is missing or belongs to another owner",
1575
+ [EXIT_WRONG_BRANCH]: "--branch: the checkout is on another branch",
1122
1576
  },
1123
1577
  run: (ctx) => {
1124
1578
  const workflow = workflowName(String(ctx.flags.workflow));
@@ -1126,6 +1580,14 @@ export const workflowsCommand = {
1126
1580
  const token = str(ctx.flags.token);
1127
1581
  if (token !== undefined && ctx.flags.lockHeld !== true)
1128
1582
  throw new CommandError(EXIT.USAGE, "--token applies with --lock-held only");
1583
+ const branch = str(ctx.flags.branch);
1584
+ if (branch !== undefined) {
1585
+ const on = git(ctx.cwd, ["branch", "--show-current"]) ?? "";
1586
+ if (on !== branch) {
1587
+ ctx.log(`[bkit-${workflow}] not on ${branch} in ${ctx.cwd} (on '${on}')`);
1588
+ return EXIT_WRONG_BRANCH;
1589
+ }
1590
+ }
1129
1591
  const where = whereInTree(ctx.cwd, {
1130
1592
  workflow,
1131
1593
  fid,
@@ -1153,6 +1615,16 @@ export const workflowsCommand = {
1153
1615
  fs.mkdirSync(path.dirname(file), { recursive: true });
1154
1616
  if (!fs.existsSync(file))
1155
1617
  fs.writeFileSync(file, "");
1618
+ // A ship decides its handover afresh: a sentinel an earlier run left is stale.
1619
+ if (workflow === "ship") {
1620
+ for (const name of SENTINELS) {
1621
+ const p = path.join(path.dirname(file), name);
1622
+ if (!fs.existsSync(p))
1623
+ continue;
1624
+ fs.rmSync(p, { force: true });
1625
+ ctx.log(`cleared stale ${name}`);
1626
+ }
1627
+ }
1156
1628
  const latest = fold(readStatusEvents(file)).at(-1);
1157
1629
  const resumed = latest?.workflow === workflow && latest.status === "IN_PROGRESS";
1158
1630
  let row = null;
@@ -1165,12 +1637,20 @@ export const workflowsCommand = {
1165
1637
  };
1166
1638
  fs.appendFileSync(file, appendLine(row));
1167
1639
  }
1640
+ recordChat(file, workflow, process.env);
1641
+ const runs = fold(readStatusEvents(file));
1642
+ const run = runNumber(runs, workflow);
1643
+ const current = resumed ? lastRun(runs, workflow) : undefined;
1168
1644
  ctx.emit({
1169
1645
  lock,
1170
1646
  file,
1171
1647
  resumed,
1172
1648
  row,
1173
- run: runNumber(fold(readStatusEvents(file)), workflow),
1649
+ run,
1650
+ lastDoneStep: current?.steps.filter((s) => s.status === "DONE").at(-1)?.step ?? null,
1651
+ openDecision: resumed
1652
+ ? openDecision(path.dirname(file), where.tree, workflow, run)
1653
+ : null,
1174
1654
  });
1175
1655
  return EXIT.OK;
1176
1656
  },
@@ -1220,6 +1700,16 @@ export const workflowsCommand = {
1220
1700
  type: "string",
1221
1701
  help: "the failed shell command's stderr (last 20 lines kept)",
1222
1702
  },
1703
+ {
1704
+ ...POST_FLAG,
1705
+ help: "post the failure comment (needs --step-number) to the --fid / --issue issue and write its failed labels; prints `tracker` and `labelsWrite`",
1706
+ },
1707
+ {
1708
+ name: "issue",
1709
+ type: "string",
1710
+ help: "with --post: the issue id when there is no --fid yet",
1711
+ },
1712
+ SESSION_DIR_FLAG,
1223
1713
  ],
1224
1714
  output: {
1225
1715
  row: "the appended workflow-failed row, or null (no --token, or no status.jsonl)",
@@ -1232,7 +1722,12 @@ export const workflowsCommand = {
1232
1722
  trackerState: "the Linear or Jira state for the failed issue (null under github, none)",
1233
1723
  prState: "the --pr PR's state, or null",
1234
1724
  comment: "the failure comment body (with --step-number), else null",
1725
+ commentFile: COMMENT_FILE_OUTPUT,
1726
+ tracker: TRACKER_OUTPUT,
1727
+ labelsWrite: "with --post: the label and state write, read fresh from the issue: {done: true, action: labels} | {done: false, action, reason} (write `labels` / `trackerState` via the tracker MCP) | {skipped}",
1728
+ sessionRemoved: SESSION_REMOVED_OUTPUT,
1235
1729
  },
1730
+ textOmit: ["row"],
1236
1731
  exitCodes: {
1237
1732
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1238
1733
  [EXIT_REMOVE_FAILED]: "the lock file is still there after removing it (everything else was done; the comment says so)",
@@ -1248,7 +1743,7 @@ export const workflowsCommand = {
1248
1743
  {
1249
1744
  name: "push",
1250
1745
  type: "boolean",
1251
- help: "feature branch: git add -A, commit `docs({fid}): {workflow} aborted bkit [skip ci]`, push --mode=abort; dev / main / detached: lands like --flush, the checkout untouched",
1746
+ help: "feature branch: git add -A (minus bkit.workflows.worktree.copy entries), commit `docs({fid}): {workflow} aborted bkit [skip ci]`, push --mode=abort; dev / main / detached: lands like --flush, the checkout untouched",
1252
1747
  },
1253
1748
  {
1254
1749
  name: "flush",
@@ -1261,12 +1756,18 @@ export const workflowsCommand = {
1261
1756
  help: "--push: the open-PR answer from MCP (a number, or none) instead of asking gh",
1262
1757
  },
1263
1758
  { name: "ref", type: "string", help: "link the handover at this ref (no push / flush)" },
1759
+ {
1760
+ name: "list-stray",
1761
+ type: "boolean",
1762
+ help: "only list what --push would sweep in besides the run's logs (modified, untracked) and whether the checkout is shared; writes nothing",
1763
+ },
1264
1764
  {
1265
1765
  name: "worktree",
1266
1766
  type: "string",
1267
1767
  help: "the run's tree: holds the handover and the logs, and is where --push commits (default: cwd's checkout)",
1268
1768
  },
1269
1769
  OWNER_REPO_FLAG,
1770
+ { ...POST_FLAG, help: "post the handover comment to the FID's issue; prints `tracker`" },
1270
1771
  ],
1271
1772
  output: {
1272
1773
  handover: "the handover artifact, or null when absent",
@@ -1274,6 +1775,11 @@ export const workflowsCommand = {
1274
1775
  ref: "where the handover now lives, or null when nothing was pushed",
1275
1776
  skipped: "why nothing was pushed: open-pr | skip-ci | nothing-to-commit (null otherwise)",
1276
1777
  comment: "the handover comment body (null when there is no handover); links only when pushed",
1778
+ commentFile: COMMENT_FILE_OUTPUT,
1779
+ tracker: `${TRACKER_OUTPUT}; absent when there is no handover`,
1780
+ shared: "--list-stray: the checkout is dev / main / detached (remove nothing)",
1781
+ modified: "--list-stray: tracked paths with changes, outside the run's logs",
1782
+ untracked: "--list-stray: untracked paths, outside the run's logs",
1277
1783
  },
1278
1784
  exitCodes: {
1279
1785
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
@@ -1319,7 +1825,7 @@ export const workflowsCommand = {
1319
1825
  {
1320
1826
  name: "message",
1321
1827
  type: "string",
1322
- help: "then git add -A and commit with this message in the tree",
1828
+ help: "then git add -A (minus bkit.workflows.worktree.copy entries) and commit with this message in the tree",
1323
1829
  },
1324
1830
  {
1325
1831
  name: "label",
@@ -1345,6 +1851,40 @@ export const workflowsCommand = {
1345
1851
  type: "string",
1346
1852
  help: "--flush: the shipped branch, deleted locally and on origin with the worktree once the close is on dev",
1347
1853
  },
1854
+ SESSION_DIR_FLAG,
1855
+ {
1856
+ name: "final-return",
1857
+ type: "boolean",
1858
+ help: "print finalReturn: the run's last message to the person (needs --summary-file)",
1859
+ },
1860
+ {
1861
+ name: "summary-file",
1862
+ type: "string",
1863
+ help: "--final-return: the summary shown verbatim (read before the close runs)",
1864
+ },
1865
+ {
1866
+ name: "summary",
1867
+ type: "string",
1868
+ help: "--final-return: like --summary-file, but a missing file shows --summary-missing; a copy is kept in --outbox",
1869
+ },
1870
+ {
1871
+ name: "summary-missing",
1872
+ type: "string",
1873
+ help: "--summary: the line shown when the summary file does not exist",
1874
+ },
1875
+ { name: "warning", type: "string", help: "--final-return: line 1, before the summary" },
1876
+ {
1877
+ name: "line",
1878
+ type: "string",
1879
+ repeatable: true,
1880
+ help: "--final-return: a line after the summary, before the issue link",
1881
+ },
1882
+ {
1883
+ name: "suggest",
1884
+ type: "string",
1885
+ repeatable: true,
1886
+ help: "--final-return: a suggested reply, before the plain-English offer",
1887
+ },
1348
1888
  ],
1349
1889
  output: {
1350
1890
  row: "the appended workflow-done row",
@@ -1358,16 +1898,23 @@ export const workflowsCommand = {
1358
1898
  parentSha: "HEAD before the --message commit (the close step's parentSha)",
1359
1899
  commit: "the --message commit, or null",
1360
1900
  comment: "the close comment (--number with --outbox), else null",
1901
+ commentFile: COMMENT_FILE_OUTPUT,
1902
+ tracker: TRACKER_OUTPUT,
1361
1903
  roadmapFoldNeeded: "always true: append the feature row and re-render the board (not run here)",
1362
1904
  featureStatus: "roadmap status this close moves the feature to",
1363
1905
  landed: "--flush: {ref, via: head-push | close-pr | close-pr-open}",
1364
1906
  worktree: "--flush: the `bkit worktrees remove` result once the close is on dev; null while the close PR is unmerged or the removal failed",
1907
+ sessionRemoved: SESSION_REMOVED_OUTPUT,
1908
+ finalReturn: "--final-return: the warning, the summary verbatim, the issue link from {session-dir}/issue-facts.json, `## Suggested Replies` (each --suggest, then the plain-English offer) and `## bkit Tips` (what `bkit tips --workflow` prints, when anything)",
1365
1909
  },
1910
+ textOmit: ["row", "counterRow", "outcomeRow"],
1366
1911
  exitCodes: {
1367
1912
  [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
1913
+ [EXIT_NO_INPUT]: "--final-return: --summary-file does not exist (nothing written)",
1368
1914
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1369
- [EXIT_PUSH_FAILED]: "--flush: dev moved before every push, or the push failed without a server answer; the lock is kept",
1915
+ [EXIT_PUSH_FAILED]: "--flush: dev moved before every push, or the push failed without a server answer; the lock is kept. Without --flush, --message in an in-place run: a path that was dirty before the run changed during it (EXIT_FOREIGN_PATH) — no row written, nothing committed",
1370
1916
  [EXIT_FLUSH_FAILED]: "--flush: the dev fetch, the throwaway checkout or the close commit failed, the close PR could not be opened (the lock is kept), or the lock could not be removed",
1917
+ [EXIT_NO_RECORD]: "--message in a debug run on dev/main with no shared-checkout record: no row written, nothing committed",
1371
1918
  },
1372
1919
  run: async (ctx) => {
1373
1920
  const f = ctx.flags;
@@ -1389,20 +1936,76 @@ export const workflowsCommand = {
1389
1936
  title: str(f.title),
1390
1937
  tree: str(f.tree),
1391
1938
  };
1939
+ const finalParts = finalReturnParts(ctx, input.fid);
1392
1940
  if (f.flush === true) {
1393
1941
  if (input.workflow !== "ship")
1394
1942
  throw new CommandError(EXIT.USAGE, "--flush is ship only");
1395
1943
  const r = await shipClose(ctx, { ...input, branch: str(f.branch) }, str(f.token));
1396
- if (r.out)
1397
- ctx.emit(r.out);
1944
+ if (r.out) {
1945
+ const out = r.out;
1946
+ const posted = typeof out.comment === "string"
1947
+ ? await postClose(ctx, input.fid, out)
1948
+ : { ...out, commentFile: null };
1949
+ const final = finalReturnText(ctx, input.workflow, finalParts);
1950
+ ctx.emit({ ...posted, ...final, ...sessionRemoval(ctx) });
1951
+ }
1398
1952
  return r.code;
1399
1953
  }
1400
- ctx.emit(closeWorkflow(ctx.cwd, input, ctx.log));
1954
+ const out = await postClose(ctx, input.fid, { ...closeWorkflow(ctx.cwd, input, ctx.log) });
1955
+ const final = finalReturnText(ctx, input.workflow, finalParts);
1956
+ ctx.emit({ ...out, ...final, ...sessionRemoval(ctx) });
1401
1957
  return EXIT.OK;
1402
1958
  },
1403
1959
  },
1960
+ input: {
1961
+ summary: "Write logs/{FID}/{workflow}-input-{run}.md: the session prompt, the issue description and each human comment, then the plan, design and audit reports, each section dated.",
1962
+ flags: [
1963
+ WORKFLOW_FLAG,
1964
+ FID_FLAG,
1965
+ MONTH_FLAG,
1966
+ {
1967
+ ...STATUS_FILE_FLAG,
1968
+ help: "status.jsonl: the input file goes beside it (default: derived)",
1969
+ },
1970
+ { name: "run", type: "string", required: true, help: "the run number ({RUN})" },
1971
+ {
1972
+ name: "prompt-file",
1973
+ type: "string",
1974
+ required: true,
1975
+ help: "the session prompt ({SESSION_DIR}/prompt.md)",
1976
+ },
1977
+ {
1978
+ name: "description-file",
1979
+ type: "string",
1980
+ help: "issue-description.md from `issues fetch` (omit for a run with no issue)",
1981
+ },
1982
+ {
1983
+ name: "comments-file",
1984
+ type: "string",
1985
+ help: "issue-comments.json from `issues fetch`: bkit:generated comments dropped, the ignore-earlier cut applied",
1986
+ },
1987
+ { name: "plan", type: "string", help: "appended under `## Plan — <path>` when it exists" },
1988
+ { name: "design", type: "string", help: "plan: the parent design, appended (must exist)" },
1989
+ {
1990
+ name: "audit",
1991
+ type: "string",
1992
+ repeatable: true,
1993
+ help: "plan: an audit report, appended in flag order (must exist)",
1994
+ },
1995
+ ],
1996
+ output: {
1997
+ path: "the input file written, relative to cwd",
1998
+ bytes: "its size in bytes",
1999
+ newerThanPlan: "issue comments posted after the plan's last commit (0 with no plan, or one with uncommitted changes)",
2000
+ },
2001
+ exitCodes: {
2002
+ [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
2003
+ [EXIT_NO_INPUT]: "the prompt, description, comments, design or an audit file is missing, or the comments are not a list",
2004
+ },
2005
+ run: inputVerb,
2006
+ },
1404
2007
  promote: {
1405
- summary: "Design / plan close: the highest versioned draft becomes the canonical doc (anchor stamped, a changed canonical archived, plan sub-plans copied).",
2008
+ summary: "Design / plan close: the highest versioned draft becomes the canonical doc (anchor stamped, a changed canonical archived).",
1406
2009
  flags: [
1407
2010
  { ...WORKFLOW_FLAG, help: "design | plan" },
1408
2011
  FID_FLAG,
@@ -1421,8 +2024,7 @@ export const workflowsCommand = {
1421
2024
  output: {
1422
2025
  final: "the highest versioned draft, e.g. docs/plans/202610/logs/12-x/design-v3-organised.md",
1423
2026
  canonical: "the canonical doc written, or null with --resolve",
1424
- archived: "superseded canonical docs moved to archive/",
1425
- subPlans: "plan: the canonical sub-plans written",
2027
+ archived: "the superseded canonical doc moved to archive/, if any",
1426
2028
  baseSha: "the base commit stamped into the anchor, or null when none was recorded",
1427
2029
  },
1428
2030
  exitCodes: {
@@ -1454,11 +2056,13 @@ export const workflowsCommand = {
1454
2056
  artifacts: "[{name, path, url}]",
1455
2057
  artifactLinks: "the same as markdown `- [name](url)` lines",
1456
2058
  comment: "the close comment (--number with --outbox): Artifacts and Telemetry sections, else null",
2059
+ commentFile: COMMENT_FILE_OUTPUT,
2060
+ tracker: TRACKER_OUTPUT,
1457
2061
  },
1458
2062
  exitCodes: {
1459
2063
  [EXIT_SPLIT_BUCKET]: "no --month and the feature has logs in more than one month bucket",
1460
2064
  },
1461
- run: (ctx) => {
2065
+ run: async (ctx) => {
1462
2066
  const workflow = workflowName(String(ctx.flags.workflow));
1463
2067
  const fid = String(ctx.flags.fid);
1464
2068
  const root = repoRoot(ctx.cwd);
@@ -1481,9 +2085,44 @@ export const workflowsCommand = {
1481
2085
  else if (ctx.flags.number !== undefined) {
1482
2086
  throw new CommandError(EXIT.USAGE, "--number needs --outbox");
1483
2087
  }
1484
- ctx.emit({ artifacts, artifactLinks: linkLines(artifacts), comment });
2088
+ ctx.emit(await postClose(ctx, fid, { artifacts, artifactLinks: linkLines(artifacts), comment }));
1485
2089
  return EXIT.OK;
1486
2090
  },
1487
2091
  },
2092
+ summary: {
2093
+ summary: "The Summary step: write {workflow}-summary.md next to --file with the run's verdict, reasons and next command.",
2094
+ flags: [
2095
+ { ...WORKFLOW_FLAG, help: "plan | design | build | debug | ship" },
2096
+ {
2097
+ name: "file",
2098
+ type: "string",
2099
+ required: true,
2100
+ help: "the run's docs/plans/{YYYYMM}/logs/{FID}/status.jsonl; the summary is written beside it",
2101
+ },
2102
+ {
2103
+ name: "plan",
2104
+ type: "string",
2105
+ repeatable: true,
2106
+ help: "a plan file the run worked from (default: build reads {FID}-plan.md)",
2107
+ },
2108
+ {
2109
+ name: "pr",
2110
+ type: "string",
2111
+ help: "ship: the PR number; its size comes from gh pr view (left out when gh cannot answer)",
2112
+ },
2113
+ ],
2114
+ output: {
2115
+ verdict: "PASS | CONCERNS | FAIL",
2116
+ failures: "the count of FAIL reasons: 0 on PASS and CONCERNS",
2117
+ reasons: "one line per reason, FAIL reasons first",
2118
+ file: "the summary written, repo-relative",
2119
+ nextStep: "the recommended next command (with the issue ref), or the fixed line when there is none",
2120
+ },
2121
+ exitCodes: {
2122
+ [EXIT_NO_STATUS]: "status.jsonl missing, unreadable, or not valid NDJSON (nothing written)",
2123
+ [EXIT_NO_RUN]: "status.jsonl has no workflow-started row for --workflow (nothing written)",
2124
+ },
2125
+ run: summaryVerb,
2126
+ },
1488
2127
  },
1489
2128
  };