@cbartens/bkit 6.1.1 → 6.2.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 (313) hide show
  1. package/.bkit/README.md +14 -12
  2. package/.bkit/core/.agents/docs.md +1 -11
  3. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-gateguard.cjs +30 -9
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +25 -27
  5. package/.bkit/core/.agents/rules.md +22 -9
  6. package/.bkit/core/.bkit/README.md +13 -11
  7. package/.bkit/core/.bkit/authoring.md +58 -13
  8. package/.bkit/core/.bkit/cli.md +42 -32
  9. package/.bkit/core/.bkit/cloud.md +93 -30
  10. package/.bkit/core/.bkit/install.md +55 -16
  11. package/.bkit/core/.bkit/jsonl.md +24 -7
  12. package/.bkit/core/.bkit/pipeline.md +8 -8
  13. package/.bkit/core/.bkit/prompts.md +160 -43
  14. package/.bkit/core/.bkit/providers.md +97 -36
  15. package/.bkit/core/.bkit/templates.md +162 -34
  16. package/.bkit/core/.bkit/trackers.md +39 -6
  17. package/.bkit/core/.bkit/workflows.md +344 -136
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +50 -27
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +11 -11
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +13 -8
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +14 -25
  22. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +20 -9
  23. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +8 -8
  24. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +14 -4
  25. package/.bkit/core/.opencode/plugin/bkit-guardrails.js +114 -0
  26. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +1 -1
  27. package/.bkit/core/docs/templates/bkit-audit-adoption.md +30 -6
  28. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  29. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  30. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  31. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  32. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +1 -1
  33. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  34. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  35. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +2 -2
  36. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  37. package/.bkit/core/docs/templates/bkit-audit-cost.md +1 -1
  38. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  39. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -3
  40. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +1 -1
  41. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  42. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +3 -3
  43. package/.bkit/core/docs/templates/bkit-audit-documentation.md +32 -2
  44. package/.bkit/core/docs/templates/bkit-audit-duplication.md +1 -1
  45. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  46. package/.bkit/core/docs/templates/bkit-audit-flakes.md +2 -2
  47. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -3
  48. package/.bkit/core/docs/templates/bkit-audit-issues.md +1 -1
  49. package/.bkit/core/docs/templates/bkit-audit-llm.md +2 -2
  50. package/.bkit/core/docs/templates/bkit-audit-logs.md +1 -1
  51. package/.bkit/core/docs/templates/bkit-audit-models.md +2 -2
  52. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  53. package/.bkit/core/docs/templates/bkit-audit-prompts.md +1 -1
  54. package/.bkit/core/docs/templates/bkit-audit-red-team.md +2 -2
  55. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  56. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  57. package/.bkit/core/docs/templates/bkit-audit-security.md +1 -1
  58. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  59. package/.bkit/core/docs/templates/bkit-audit-testing.md +3 -2
  60. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  61. package/.bkit/core/docs/templates/bkit-plan.md +38 -8
  62. package/.bkit/core/engine/checks/after/auth.ts +118 -47
  63. package/.bkit/core/engine/checks/after/github.ts +89 -37
  64. package/.bkit/core/engine/checks/after/index.ts +15 -3
  65. package/.bkit/core/engine/checks/after/tools.ts +245 -1
  66. package/.bkit/core/engine/checks/before/files.ts +59 -1
  67. package/.bkit/core/engine/checks/before/index.ts +8 -0
  68. package/.bkit/core/engine/checks/status-holes.ts +20 -26
  69. package/.bkit/core/engine/checks/tips/catalogue.ts +107 -10
  70. package/.bkit/core/engine/checks/tips/detect.ts +36 -3
  71. package/.bkit/core/engine/checks/tips/index.ts +1 -1
  72. package/.bkit/core/engine/cli.ts +13 -13
  73. package/.bkit/core/engine/commands/ci/ci.ts +64 -11
  74. package/.bkit/core/engine/commands/ci/push-gate.ts +101 -43
  75. package/.bkit/core/engine/commands/install/install.ts +28 -25
  76. package/.bkit/core/engine/commands/install/uninstall.ts +42 -30
  77. package/.bkit/core/engine/commands/install/upgrade.ts +14 -2
  78. package/.bkit/core/engine/commands/land.ts +2 -3
  79. package/.bkit/core/engine/commands/lib.ts +394 -39
  80. package/.bkit/core/engine/commands/registry.ts +1 -1
  81. package/.bkit/core/engine/commands/workflow/branches.ts +351 -78
  82. package/.bkit/core/engine/commands/workflow/challenge.ts +63 -14
  83. package/.bkit/core/engine/commands/workflow/context.ts +71 -10
  84. package/.bkit/core/engine/commands/workflow/counters.ts +298 -23
  85. package/.bkit/core/engine/commands/workflow/decisions.ts +260 -125
  86. package/.bkit/core/engine/commands/workflow/disk.ts +2 -1
  87. package/.bkit/core/engine/commands/workflow/feature-base.ts +66 -0
  88. package/.bkit/core/engine/commands/workflow/issues.ts +312 -17
  89. package/.bkit/core/engine/commands/workflow/junit.ts +204 -0
  90. package/.bkit/core/engine/commands/workflow/ledgers.ts +904 -99
  91. package/.bkit/core/engine/commands/workflow/locks.ts +186 -29
  92. package/.bkit/core/engine/commands/workflow/loops.ts +87 -0
  93. package/.bkit/core/engine/commands/workflow/open-decision.ts +251 -0
  94. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +8 -0
  95. package/.bkit/core/engine/commands/workflow/plans.ts +1 -1
  96. package/.bkit/core/engine/commands/workflow/prs.ts +311 -16
  97. package/.bkit/core/engine/commands/workflow/repo.ts +1 -1
  98. package/.bkit/core/engine/commands/workflow/run-facts.ts +6 -0
  99. package/.bkit/core/engine/commands/workflow/runs.ts +877 -174
  100. package/.bkit/core/engine/commands/workflow/runtime.ts +12 -4
  101. package/.bkit/core/engine/commands/workflow/status.ts +324 -11
  102. package/.bkit/core/engine/commands/workflow/step-table.ts +41 -15
  103. package/.bkit/core/engine/commands/workflow/steps.ts +604 -29
  104. package/.bkit/core/engine/commands/workflow/summary-findings.ts +1 -1
  105. package/.bkit/core/engine/commands/workflow/summary.ts +314 -8
  106. package/.bkit/core/engine/commands/workflow/tasks.ts +400 -27
  107. package/.bkit/core/engine/commands/workflow/tests-base.ts +319 -0
  108. package/.bkit/core/engine/commands/workflow/tests-changed.ts +138 -74
  109. package/.bkit/core/engine/commands/workflow/tests-jump.ts +93 -0
  110. package/.bkit/core/engine/commands/workflow/tests.ts +815 -182
  111. package/.bkit/core/engine/commands/workflow/tracker.ts +1134 -137
  112. package/.bkit/core/engine/commands/workflow/workflows.ts +100 -72
  113. package/.bkit/core/engine/commands/workflow/worktrees.ts +421 -57
  114. package/.bkit/core/engine/install/cloud-env.ts +38 -10
  115. package/.bkit/core/engine/install/managed-block.ts +105 -0
  116. package/.bkit/core/engine/install/manifest.ts +7 -1
  117. package/.bkit/core/engine/install/modules/claude.ts +6 -2
  118. package/.bkit/core/engine/install/modules/cloud.ts +84 -95
  119. package/.bkit/core/engine/install/modules/codex.ts +10 -2
  120. package/.bkit/core/engine/install/modules/core.ts +148 -14
  121. package/.bkit/core/engine/install/modules/opencode.ts +18 -23
  122. package/.bkit/core/engine/install/network-allowlist.ts +8 -3
  123. package/.bkit/core/engine/install/project-docs.ts +650 -0
  124. package/.bkit/core/engine/install/template-copies.ts +58 -5
  125. package/.bkit/core/engine/install/write.ts +128 -7
  126. package/.bkit/core/engine/ledgers/journal.ts +18 -10
  127. package/.bkit/core/engine/ledgers/migrate.ts +20 -8
  128. package/.bkit/core/engine/ledgers/status.ts +604 -8
  129. package/.bkit/core/engine/ledgers/telemetry.ts +115 -13
  130. package/.bkit/core/engine/render/trackers.ts +3 -1
  131. package/.bkit/core/engine/shared/package-manager.ts +7 -3
  132. package/.bkit/core/engine/shared/settings.ts +12 -1
  133. package/.bkit/core/engine/shared/text.ts +14 -0
  134. package/.bkit/core/engine/tools/instructions-sources.ts +1 -0
  135. package/.bkit/core/engine/tools/instructions.ts +116 -20
  136. package/.bkit/core/hooks/antigravity-hook.js +20 -4
  137. package/.bkit/core/hooks/gateguard-edit-payload.js +8 -5
  138. package/.bkit/core/hooks/gateguard-engine.js +249 -23
  139. package/.bkit/core/hooks/guardrails-deny.js +167 -0
  140. package/.bkit/core/hooks/guardrails-read.js +3 -3
  141. package/.bkit/core/hooks/guardrails-shell.js +1122 -167
  142. package/.bkit/core/hooks/guardrails-tiers.js +247 -176
  143. package/.bkit/core/hooks/preflight-tracker.sh +219 -0
  144. package/.bkit/core/prompts/bkit-audit-generate.md +23 -6
  145. package/.bkit/core/prompts/bkit-build-challenge-1.md +5 -4
  146. package/.bkit/core/prompts/bkit-build-challenge-2.md +6 -5
  147. package/.bkit/core/prompts/bkit-build-install-skills.md +2 -2
  148. package/.bkit/core/prompts/bkit-build-plan-convert.md +21 -7
  149. package/.bkit/core/prompts/bkit-build-plan-current.md +5 -4
  150. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +22 -17
  151. package/.bkit/core/prompts/bkit-build-plan-tasks.md +16 -12
  152. package/.bkit/core/prompts/bkit-build-plan-tests.md +14 -10
  153. package/.bkit/core/prompts/bkit-build-plan-verify.md +21 -8
  154. package/.bkit/core/prompts/bkit-debug-abort-handover.md +10 -5
  155. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +22 -6
  156. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +19 -3
  157. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +22 -6
  158. package/.bkit/core/prompts/bkit-debug-failure-soak.md +10 -7
  159. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +3 -3
  160. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +4 -4
  161. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +3 -3
  162. package/.bkit/core/prompts/bkit-design-generate.md +6 -4
  163. package/.bkit/core/prompts/bkit-design-organise.md +4 -3
  164. package/.bkit/core/prompts/bkit-design-review-1.md +5 -4
  165. package/.bkit/core/prompts/bkit-design-review-2.md +6 -5
  166. package/.bkit/core/prompts/bkit-design-spike.md +4 -3
  167. package/.bkit/core/prompts/bkit-design-update.md +6 -4
  168. package/.bkit/core/prompts/bkit-plan-generate.md +35 -14
  169. package/.bkit/core/prompts/bkit-plan-review-1.md +9 -7
  170. package/.bkit/core/prompts/bkit-plan-review-2.md +9 -7
  171. package/.bkit/core/prompts/bkit-plan-scope-check.md +8 -6
  172. package/.bkit/core/prompts/bkit-plan-update.md +22 -8
  173. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +11 -8
  174. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +9 -5
  175. package/.bkit/core/prompts/bkit-ship-update-docs.md +26 -4
  176. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +3 -3
  177. package/.bkit/core/prompts/bkit-utility-update-decisions.md +10 -7
  178. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +8 -5
  179. package/.bkit/core/prompts/bkit-utility-update-documentation.md +31 -7
  180. package/.bkit/core/prompts/bkit-utility-update-failures.md +8 -5
  181. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +10 -7
  182. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +4 -4
  183. package/.bkit/core/prompts/bkit-utility-update-tracker.md +4 -4
  184. package/.bkit/core/workflows/bkit-auto.md +23 -11
  185. package/.bkit/core/workflows/bkit-build.md +331 -100
  186. package/.bkit/core/workflows/bkit-debug.md +135 -64
  187. package/.bkit/core/workflows/bkit-design.md +58 -32
  188. package/.bkit/core/workflows/bkit-plan.md +73 -45
  189. package/.bkit/core/workflows/bkit-ship.md +233 -167
  190. package/.bkit/shared/.agents/plugins/bkit/hooks.json +1 -1
  191. package/.bkit/shared/.bkit/.env.example +5 -0
  192. package/.bkit/shared/.claude/bkit-cloud.md +7 -7
  193. package/.bkit/shared/.claude/settings.json +5 -1
  194. package/.bkit/shared/.cursor/bkit-cloud.md +1 -1
  195. package/.bkit/shared/.cursor/hooks.json +1 -1
  196. package/.bkit/shared/.opencode/opencode.json +11 -2
  197. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +27 -0
  198. package/.bkit/templates/.cursor/Dockerfile +7 -7
  199. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +1 -1
  200. package/.bkit/templates/.github/dependabot.yml +5 -0
  201. package/.bkit/templates/.github/renovate.json5 +5 -3
  202. package/.bkit/templates/.github/workflows/bkit-ci.yml +11 -11
  203. package/.bkit/templates/.github/workflows/bkit-cloud.yml +525 -161
  204. package/.bkit/templates/.github/workflows/bkit-renovate.yml +2 -2
  205. package/.bkit/templates/.husky/pre-push +123 -6
  206. package/.bkit/templates/context/bkit-serena.md +1 -1
  207. package/.bkit/templates/docs/architecture.md +98 -0
  208. package/.bkit/templates/docs/capabilities.md +33 -37
  209. package/.bkit/templates/docs/components.md +142 -0
  210. package/.bkit/templates/docs/data-schema.md +87 -0
  211. package/.bkit/{shared → templates}/docs/deployments.md +128 -142
  212. package/.bkit/templates/docs/design.md +117 -0
  213. package/.bkit/templates/docs/noise.md +54 -0
  214. package/.bkit/templates/docs/observability.md +99 -0
  215. package/.bkit/templates/docs/security.md +137 -0
  216. package/.bkit/templates/docs/setup.md +93 -0
  217. package/.bkit/templates/docs/technology.md +70 -0
  218. package/.bkit/{shared → templates}/docs/testing.md +200 -87
  219. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +511 -103
  220. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +228 -35
  221. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +270 -2
  222. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  223. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +92 -63
  224. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +59 -11
  225. package/.bkit/templates/slop-scan.config.json +2 -0
  226. package/CHANGELOG.md +64 -0
  227. package/DETAILS.md +24 -19
  228. package/README.md +1 -1
  229. package/dist/checks/after/auth.js +114 -46
  230. package/dist/checks/after/github.js +77 -35
  231. package/dist/checks/after/index.js +12 -3
  232. package/dist/checks/after/tools.js +224 -1
  233. package/dist/checks/before/files.js +59 -1
  234. package/dist/checks/before/index.js +7 -1
  235. package/dist/checks/status-holes.js +20 -21
  236. package/dist/checks/tips/catalogue.js +99 -10
  237. package/dist/checks/tips/detect.js +35 -3
  238. package/dist/checks/tips/index.js +1 -1
  239. package/dist/cli.js +13 -13
  240. package/dist/commands/ci/ci.js +56 -12
  241. package/dist/commands/ci/push-gate.js +79 -44
  242. package/dist/commands/install/install.js +23 -22
  243. package/dist/commands/install/uninstall.js +36 -30
  244. package/dist/commands/install/upgrade.js +10 -2
  245. package/dist/commands/land.js +2 -3
  246. package/dist/commands/lib.js +323 -25
  247. package/dist/commands/workflow/branches.js +312 -72
  248. package/dist/commands/workflow/challenge.js +66 -13
  249. package/dist/commands/workflow/context.js +46 -10
  250. package/dist/commands/workflow/counters.js +231 -23
  251. package/dist/commands/workflow/decisions.js +221 -106
  252. package/dist/commands/workflow/disk.js +2 -1
  253. package/dist/commands/workflow/feature-base.js +60 -0
  254. package/dist/commands/workflow/issues.js +243 -15
  255. package/dist/commands/workflow/junit.js +137 -0
  256. package/dist/commands/workflow/ledgers.js +726 -112
  257. package/dist/commands/workflow/locks.js +150 -29
  258. package/dist/commands/workflow/loops.js +67 -0
  259. package/dist/commands/workflow/open-decision.js +199 -0
  260. package/dist/commands/workflow/plan-blocks.js +6 -0
  261. package/dist/commands/workflow/plans.js +1 -1
  262. package/dist/commands/workflow/prs.js +272 -16
  263. package/dist/commands/workflow/repo.js +1 -1
  264. package/dist/commands/workflow/run-facts.js +6 -0
  265. package/dist/commands/workflow/runs.js +747 -155
  266. package/dist/commands/workflow/runtime.js +8 -4
  267. package/dist/commands/workflow/status.js +259 -13
  268. package/dist/commands/workflow/step-table.js +41 -15
  269. package/dist/commands/workflow/steps.js +530 -26
  270. package/dist/commands/workflow/summary-findings.js +1 -1
  271. package/dist/commands/workflow/summary.js +289 -8
  272. package/dist/commands/workflow/tasks.js +294 -27
  273. package/dist/commands/workflow/tests-base.js +266 -0
  274. package/dist/commands/workflow/tests-changed.js +130 -56
  275. package/dist/commands/workflow/tests-jump.js +77 -0
  276. package/dist/commands/workflow/tests.js +608 -131
  277. package/dist/commands/workflow/tracker.js +920 -112
  278. package/dist/commands/workflow/workflows.js +80 -59
  279. package/dist/commands/workflow/worktrees.js +387 -58
  280. package/dist/install/cloud-env.js +32 -10
  281. package/dist/install/managed-block.js +101 -0
  282. package/dist/install/manifest.js +7 -1
  283. package/dist/install/modules/claude.js +6 -2
  284. package/dist/install/modules/cloud.js +73 -86
  285. package/dist/install/modules/codex.js +9 -2
  286. package/dist/install/modules/core.js +133 -14
  287. package/dist/install/modules/opencode.js +18 -23
  288. package/dist/install/network-allowlist.js +8 -3
  289. package/dist/install/project-docs.js +551 -0
  290. package/dist/install/template-copies.js +55 -5
  291. package/dist/install/write.js +117 -5
  292. package/dist/ledgers/journal.js +10 -8
  293. package/dist/ledgers/migrate.js +20 -9
  294. package/dist/ledgers/status.js +461 -8
  295. package/dist/ledgers/telemetry.js +71 -13
  296. package/dist/render/trackers.js +3 -1
  297. package/dist/shared/package-manager.js +7 -2
  298. package/dist/shared/settings.js +8 -0
  299. package/dist/shared/text.js +13 -0
  300. package/dist/tools/instructions-sources.js +1 -0
  301. package/dist/tools/instructions.js +97 -24
  302. package/package.json +22 -15
  303. package/.bkit/core/hooks/preflight-linear.sh +0 -73
  304. package/.bkit/shared/docs/architecture.md +0 -16
  305. package/.bkit/shared/docs/data-schema.md +0 -16
  306. package/.bkit/shared/docs/design.md +0 -38
  307. package/.bkit/shared/docs/noise.md +0 -20
  308. package/.bkit/shared/docs/observability.md +0 -22
  309. package/.bkit/shared/docs/security.md +0 -62
  310. package/.bkit/shared/docs/setup.md +0 -52
  311. package/.bkit/shared/docs/technology.md +0 -15
  312. /package/.bkit/templates/{.lintstagedrc.json → lintstagedrc.example.json} +0 -0
  313. /package/.bkit/templates/{.prettierignore → prettierignore.example} +0 -0
@@ -12,6 +12,7 @@ import * as fs from "node:fs";
12
12
  import * as path from "node:path";
13
13
 
14
14
  import type { IssueTracker } from "../../install/manifest.js";
15
+ import { appendFrictionRow, frictionRow } from "../../ledgers/journal.js";
15
16
  import {
16
17
  actionHash,
17
18
  actionKey,
@@ -24,11 +25,24 @@ import { resolveRepoSlug } from "../../ledgers/telemetry.js";
24
25
  import { readBkitConfig, type BkitConfig } from "../../shared/settings.js";
25
26
  import { git, parseJson, runGh, type FlagSpec, type GhResult, type RunContext } from "../lib.js";
26
27
  import { issueIdOf, readIssueTracker } from "./fids.js";
27
- import { readRunsLenient } from "./locks.js";
28
+ import { acquirePublicationLock, readRunsLenient, releasePublicationLock } from "./locks.js";
28
29
 
29
- /** Jira Cloud's comment limit; longer bodies post as consecutive parts. */
30
+ /** Conservative full Markdown UTF-16 budget, including markers and part labels. */
30
31
  export const JIRA_COMMENT_LIMIT = 32_767;
31
32
 
33
+ /**
34
+ * Live contract evidence v1 (2026-11-05): GitHub accepts 262,144 UTF-8 body bytes
35
+ * and rejects the next byte; Linear accepts 100,000 Unicode scalars and rejects
36
+ * the next scalar. Jira's Markdown conversion makes its raw boundary dependent
37
+ * on formatting; both ASCII and non-BMP payloads pass at this safe UTF-16 budget.
38
+ * Keep the selected budgets conservative, rather than promising provider maxima.
39
+ */
40
+ const COMMENT_BODY_BUDGETS = {
41
+ github: 65_536,
42
+ linear: 100_000,
43
+ jira: JIRA_COMMENT_LIMIT,
44
+ } as const;
45
+
32
46
  export const JIRA_MCP_URL = "https://mcp.atlassian.com/v2/mcp";
33
47
  export const LINEAR_API_URL = "https://api.linear.app/graphql";
34
48
 
@@ -47,6 +61,24 @@ export const JIRA_TOOLS = {
47
61
  // Cloudflare in front of Atlassian answers error 1010 to a default library User-Agent.
48
62
  const USER_AGENT = "bkit-engine (+https://github.com/cbartens/bkit)";
49
63
  const TIMEOUT_MS = 30_000;
64
+ interface DeliveryBudget {
65
+ deadline: number;
66
+ duration: number;
67
+ pages: number;
68
+ writes: number;
69
+ reserve: boolean;
70
+ }
71
+ function timeLeft(budget?: DeliveryBudget): number {
72
+ if (!budget) return TIMEOUT_MS;
73
+ if (budget.deadline === 0) budget.deadline = performance.now() + budget.duration;
74
+ const remaining = budget.deadline - performance.now();
75
+ if (remaining <= 0) throw new TrackerError("network", "publication timeout");
76
+ return Math.max(1, Math.floor(Math.min(TIMEOUT_MS, remaining / (budget.reserve ? 2 : 1))));
77
+ }
78
+ function charge(budget: DeliveryBudget | undefined, kind: "pages" | "writes"): void {
79
+ if (budget && ++budget[kind] > (kind === "pages" ? 10 : 3))
80
+ throw new TrackerError("network", `publication ${kind} limit`);
81
+ }
50
82
  const SECRET_KEYS = ["BKIT_GH_TOKEN", "BKIT_LINEAR_API_KEY", "BKIT_JIRA_API_KEY"] as const;
51
83
 
52
84
  // ---------------------------------------------------------------------------
@@ -184,8 +216,13 @@ export function ghEnv(): Record<string, string> {
184
216
  }
185
217
 
186
218
  /** `gh` for a tracker call; a failure throws its reason. */
187
- export function gh(t: TrackerTarget, args: string[], input?: string): string {
188
- const res = runGh(t.cwd, args, input, ghEnv());
219
+ export function gh(
220
+ t: TrackerTarget,
221
+ args: string[],
222
+ input?: string,
223
+ budget?: DeliveryBudget,
224
+ ): string {
225
+ const res = runGh(t.cwd, args, input, ghEnv(), budget ? { timeoutMs: timeLeft(budget) } : {});
189
226
  if (!res.ok) throw new TrackerError(ghReason(res), `gh ${args[0] ?? ""}: ${res.stderr}`);
190
227
  return res.stdout;
191
228
  }
@@ -201,7 +238,7 @@ async function post(
201
238
  url: string,
202
239
  headers: Record<string, string>,
203
240
  body: unknown,
204
- o: { keepErrors?: boolean } = {},
241
+ o: { keepErrors?: boolean; budget?: DeliveryBudget } = {},
205
242
  ): Promise<{ ok: boolean; status: number; headers: Headers; text: string }> {
206
243
  let res: Response;
207
244
  try {
@@ -209,7 +246,7 @@ async function post(
209
246
  method: "POST",
210
247
  headers: { "content-type": "application/json", "user-agent": USER_AGENT, ...headers },
211
248
  body: JSON.stringify(body),
212
- signal: AbortSignal.timeout(TIMEOUT_MS),
249
+ signal: AbortSignal.timeout(timeLeft(o.budget)),
213
250
  });
214
251
  } catch (err) {
215
252
  throw networkError(err);
@@ -237,13 +274,17 @@ const LINEAR_CODES: Record<string, FailureReason> = {
237
274
  * One Linear GraphQL call. GraphQL errors map to a reason by `extensions.code` — Linear
238
275
  * answers rate limits and auth failures with HTTP 400 and the code in the body.
239
276
  */
240
- export async function linearGql(query: string, variables: Record<string, unknown>) {
277
+ export async function linearGql(
278
+ query: string,
279
+ variables: Record<string, unknown>,
280
+ budget?: DeliveryBudget,
281
+ ) {
241
282
  const key = secret("BKIT_LINEAR_API_KEY");
242
283
  const res = await post(
243
284
  LINEAR_API_URL,
244
285
  { authorization: key },
245
286
  { query, variables },
246
- { keepErrors: true },
287
+ { keepErrors: true, budget },
247
288
  );
248
289
  const parsed = parseJson(res.text);
249
290
  const doc = asRecord(parsed.ok ? parsed.value : null);
@@ -298,10 +339,13 @@ function jiraReason(text: string): FailureReason {
298
339
  export class JiraSession {
299
340
  private id = 1;
300
341
  private session: string | null = null;
301
- constructor(private readonly key: string) {}
342
+ constructor(
343
+ private readonly key: string,
344
+ private readonly budget?: DeliveryBudget,
345
+ ) {}
302
346
 
303
- static open(): JiraSession {
304
- return new JiraSession(secret("BKIT_JIRA_API_KEY"));
347
+ static open(budget?: DeliveryBudget): JiraSession {
348
+ return new JiraSession(secret("BKIT_JIRA_API_KEY"), budget);
305
349
  }
306
350
 
307
351
  private headers(): Record<string, string> {
@@ -314,34 +358,49 @@ export class JiraSession {
314
358
 
315
359
  private async start(): Promise<void> {
316
360
  if (this.session !== null) return;
317
- const res = await post(JIRA_MCP_URL, this.headers(), {
318
- jsonrpc: "2.0",
319
- id: this.id,
320
- method: "initialize",
321
- params: {
322
- protocolVersion: "2025-06-18",
323
- capabilities: {},
324
- clientInfo: { name: "bkit", version: "engine" },
361
+ const res = await post(
362
+ JIRA_MCP_URL,
363
+ this.headers(),
364
+ {
365
+ jsonrpc: "2.0",
366
+ id: this.id,
367
+ method: "initialize",
368
+ params: {
369
+ protocolVersion: "2025-06-18",
370
+ capabilities: {},
371
+ clientInfo: { name: "bkit", version: "engine" },
372
+ },
325
373
  },
326
- });
374
+ { budget: this.budget },
375
+ );
327
376
  rpcMessage(res.text, res.headers.get("content-type") ?? "", this.id);
328
377
  this.session = res.headers.get("mcp-session-id") ?? "";
329
- await post(JIRA_MCP_URL, this.headers(), {
330
- jsonrpc: "2.0",
331
- method: "notifications/initialized",
332
- });
378
+ await post(
379
+ JIRA_MCP_URL,
380
+ this.headers(),
381
+ {
382
+ jsonrpc: "2.0",
383
+ method: "notifications/initialized",
384
+ },
385
+ { budget: this.budget },
386
+ );
333
387
  }
334
388
 
335
389
  /** `tools/call` one tool; returns its text content parsed as JSON when it is JSON. */
336
390
  async call(name: string, args: Record<string, unknown>): Promise<unknown> {
337
391
  await this.start();
338
392
  const id = ++this.id;
339
- const res = await post(JIRA_MCP_URL, this.headers(), {
340
- jsonrpc: "2.0",
341
- id,
342
- method: "tools/call",
343
- params: { name, arguments: args },
344
- });
393
+ const res = await post(
394
+ JIRA_MCP_URL,
395
+ this.headers(),
396
+ {
397
+ jsonrpc: "2.0",
398
+ id,
399
+ method: "tools/call",
400
+ params: { name, arguments: args },
401
+ },
402
+ { budget: this.budget },
403
+ );
345
404
  const msg = rpcMessage(res.text, res.headers.get("content-type") ?? "", id);
346
405
  if (msg.error) {
347
406
  const message = String(asRecord(msg.error).message ?? "");
@@ -411,92 +470,256 @@ export function writeBodyFile(cwd: string, kind: "comment" | "pr-body", body: st
411
470
  * a split body opens with the body's first line when it is the generated marker,
412
471
  * then `_(part i/n)_`; a single line longer than a part is cut hard.
413
472
  */
414
- export function splitAt(body: string, limit: number): string[] {
473
+ export function splitAt(
474
+ body: string,
475
+ limit: number,
476
+ opts: { verifiedBudget?: boolean; compact?: boolean } = {},
477
+ ): string[] {
478
+ if (opts.verifiedBudget === false) return [body];
415
479
  if (body.length <= limit) return [body];
480
+ if (opts.compact) {
481
+ const marker = body.startsWith("###### ") ? body.split("\n", 1)[0]! : "";
482
+ let rest = marker ? body.slice(marker.length + 1) : body;
483
+ const room = limit - marker.length - 64;
484
+ if (room <= 1) throw new TrackerError("http-400", "comment limit cannot fit one code point");
485
+ const chunks: string[] = [];
486
+ while (rest.length) {
487
+ const cut = /[\uD800-\uDBFF]/.test(rest[room - 1] ?? "") ? room - 1 : room;
488
+ chunks.push(rest.slice(0, cut));
489
+ rest = rest.slice(cut);
490
+ }
491
+ return chunks.map(
492
+ (part, i) => `${marker ? `${marker}\n` : ""}_(part ${i + 1}/${chunks.length})_\n${part}`,
493
+ );
494
+ }
416
495
  const lines = body.split("\n");
417
496
  const marker = lines[0]?.startsWith("###### ") ? lines.shift()! : null;
418
- const headerRoom = (marker ? marker.length + 1 : 0) + "_(part 99/99)_\n".length;
419
- const room = limit - headerRoom;
420
- const chunks: string[] = [];
421
- let cur = "";
422
- const flush = () => {
423
- if (cur !== "") chunks.push(cur);
424
- cur = "";
425
- };
426
- for (const raw of lines) {
427
- let line = raw;
428
- while (line.length > room) {
429
- flush();
430
- chunks.push(line.slice(0, room));
431
- line = line.slice(room);
497
+ let digits = 2;
498
+ for (;;) {
499
+ const widestPart = "9".repeat(digits);
500
+ const headerRoom =
501
+ (marker ? marker.length + 1 : 0) + `_(part ${widestPart}/${widestPart})_\n`.length;
502
+ const room = limit - headerRoom;
503
+ const chunks: string[] = [];
504
+ let cur = "";
505
+ const flush = () => {
506
+ if (cur !== "") chunks.push(cur);
507
+ cur = "";
508
+ };
509
+ for (const raw of lines) {
510
+ let line = raw;
511
+ while (line.length > room) {
512
+ flush();
513
+ const cut = room > 0 && /[\uD800-\uDBFF]/.test(line[room - 1] ?? "") ? room - 1 : room;
514
+ if (cut <= 0) throw new TrackerError("http-400", "comment limit cannot fit one code point");
515
+ chunks.push(line.slice(0, cut));
516
+ line = line.slice(cut);
517
+ }
518
+ const next = cur === "" ? line : `${cur}\n${line}`;
519
+ if (next.length > room) {
520
+ flush();
521
+ cur = line;
522
+ } else cur = next;
432
523
  }
433
- const next = cur === "" ? line : `${cur}\n${line}`;
434
- if (next.length > room) {
435
- flush();
436
- cur = line;
437
- } else cur = next;
524
+ flush();
525
+ const requiredDigits = String(chunks.length).length;
526
+ if (requiredDigits > digits) {
527
+ digits = requiredDigits;
528
+ continue;
529
+ }
530
+ return chunks.map((c, i) =>
531
+ [...(marker ? [marker] : []), `_(part ${i + 1}/${chunks.length})_`, c].join("\n"),
532
+ );
438
533
  }
439
- flush();
440
- return chunks.map((c, i) =>
441
- [...(marker ? [marker] : []), `_(part ${i + 1}/${chunks.length})_`, c].join("\n"),
442
- );
443
534
  }
444
535
 
445
536
  export interface PostedComment {
446
537
  url: string | null;
447
538
  /** How many comments the body went out as (Jira splits long bodies). */
448
539
  parts: number;
540
+ evidence?: CommentEvidence;
541
+ }
542
+
543
+ export interface CommentEvidence {
544
+ id: string;
545
+ authorId: string | null;
546
+ createdAt: string;
547
+ updatedAt: string;
548
+ fingerprint: string;
549
+ representation: "markdown";
550
+ sectionIds: string[];
551
+ }
552
+
553
+ function commentEvidence(raw: Record<string, unknown>): CommentEvidence | undefined {
554
+ const author = asRecord(raw.user ?? raw.author);
555
+ const id = raw.databaseId ?? raw.id;
556
+ const authorId = author.databaseId ?? author.accountId ?? author.id;
557
+ const createdAt = raw.created_at ?? raw.createdAt ?? raw.created;
558
+ const updatedAt = raw.updated_at ?? raw.updatedAt ?? raw.updated;
559
+ if (
560
+ (typeof id !== "string" && typeof id !== "number") ||
561
+ String(id).trim() === "" ||
562
+ typeof createdAt !== "string" ||
563
+ typeof updatedAt !== "string" ||
564
+ !Number.isFinite(Date.parse(createdAt)) ||
565
+ !Number.isFinite(Date.parse(updatedAt)) ||
566
+ typeof raw.body !== "string"
567
+ )
568
+ return undefined;
569
+ return {
570
+ id: String(id),
571
+ authorId:
572
+ (typeof authorId === "string" || typeof authorId === "number") &&
573
+ String(authorId).trim() !== ""
574
+ ? String(authorId)
575
+ : null,
576
+ createdAt,
577
+ updatedAt,
578
+ fingerprint: actionHash(raw.body),
579
+ representation: "markdown",
580
+ sectionIds: [
581
+ ...raw.body.matchAll(/(?:######[ \t]+|<h6\b[^>]*>\s*)bkit:section v1 ([a-f0-9]{64})\b/g),
582
+ ].map((match) => match[1]!),
583
+ };
449
584
  }
450
585
 
451
- /** Post `body` as a new comment on the target issue. Throws `TrackerError` on failure. */
452
- export async function postComment(t: TrackerTarget, body: string): Promise<PostedComment> {
586
+ /** Create a comment, or edit the supplied verified ID. Throws `TrackerError` on failure. */
587
+ export async function postComment(
588
+ t: TrackerTarget,
589
+ body: string,
590
+ opts: { commentId?: string; evidence?: CommentEvidence; budget?: DeliveryBudget } = {},
591
+ ): Promise<PostedComment> {
453
592
  if (t.issue === null) throw new TrackerError("not-found", "no issue");
593
+ const limit =
594
+ t.tracker === "linear"
595
+ ? COMMENT_BODY_BUDGETS.linear
596
+ : t.tracker === "github"
597
+ ? COMMENT_BODY_BUDGETS.github
598
+ : COMMENT_BODY_BUDGETS.jira;
599
+ if (!opts.commentId && t.tracker !== "jira" && body.length > limit) {
600
+ const parts = splitAt(body, limit, { compact: true });
601
+ let last: PostedComment | undefined;
602
+ for (const part of parts) last = await postComment(t, part, opts);
603
+ if (!last) throw new TrackerError("network", "no comment parts");
604
+ return { url: last.url, parts: parts.length };
605
+ }
454
606
  if (t.tracker === "github") {
607
+ charge(opts.budget, "writes");
455
608
  const out = gh(
456
609
  t,
457
610
  [
458
611
  "api",
459
- `repos/${t.ownerRepo}/issues/${t.issue}/comments`,
612
+ opts.commentId
613
+ ? `repos/${t.ownerRepo}/issues/comments/${encodeURIComponent(opts.commentId)}`
614
+ : `repos/${t.ownerRepo}/issues/${t.issue}/comments`,
460
615
  "--method",
461
- "POST",
616
+ opts.commentId ? "PATCH" : "POST",
462
617
  "--input",
463
618
  "-",
464
619
  ],
465
620
  JSON.stringify({ body }),
621
+ opts.budget,
466
622
  );
467
623
  const parsed = parseJson(out);
468
- const url = asRecord(parsed.ok ? parsed.value : null).html_url;
469
- return { url: typeof url === "string" ? url : null, parts: 1 };
624
+ const raw = asRecord(parsed.ok ? parsed.value : null);
625
+ const url = raw.html_url;
626
+ const evidence = commentEvidence(raw);
627
+ return {
628
+ url: typeof url === "string" ? url : null,
629
+ parts: 1,
630
+ ...(evidence ? { evidence } : {}),
631
+ };
470
632
  }
471
633
  if (t.tracker === "linear") {
634
+ charge(opts.budget, "writes");
472
635
  const data = await linearGql(
473
- "mutation($input: CommentCreateInput!) { commentCreate(input: $input) { success comment { url } } }",
474
- { input: { issueId: t.issue, body } },
636
+ opts.commentId
637
+ ? "mutation($id: String!, $input: CommentUpdateInput!) { commentUpdate(id: $id, input: $input) { success comment { id body url createdAt updatedAt user { id } } } }"
638
+ : "mutation($input: CommentCreateInput!) { commentCreate(input: $input) { success comment { id body url createdAt updatedAt user { id } } } }",
639
+ opts.commentId
640
+ ? { id: opts.commentId, input: { body } }
641
+ : { input: { issueId: t.issue, body } },
642
+ opts.budget,
475
643
  );
476
- const created = asRecord(data.commentCreate);
644
+ const created = asRecord(opts.commentId ? data.commentUpdate : data.commentCreate);
477
645
  if (created.success !== true)
478
- throw new TrackerError("http-400", "linear: commentCreate failed");
479
- const url = asRecord(created.comment).url;
480
- return { url: typeof url === "string" ? url : null, parts: 1 };
646
+ throw new TrackerError("http-400", "linear: comment mutation failed");
647
+ const raw = asRecord(created.comment);
648
+ const url = raw.url;
649
+ const evidence = commentEvidence(raw);
650
+ return {
651
+ url: typeof url === "string" ? url : null,
652
+ parts: 1,
653
+ ...(evidence ? { evidence } : {}),
654
+ };
481
655
  }
482
656
  if (t.tracker === "jira") {
657
+ if (
658
+ opts.commentId &&
659
+ (!opts.evidence ||
660
+ opts.evidence.id !== opts.commentId ||
661
+ !opts.evidence.authorId ||
662
+ opts.evidence.representation !== "markdown" ||
663
+ !/^[a-f0-9]{64}$/.test(opts.evidence.fingerprint) ||
664
+ !Number.isFinite(Date.parse(opts.evidence.createdAt)) ||
665
+ !Number.isFinite(Date.parse(opts.evidence.updatedAt)))
666
+ )
667
+ throw new TrackerError("unsupported", "jira: comment edit requires verified evidence");
483
668
  const site = jiraSite(t);
484
- const jira = JiraSession.open();
669
+ const jira = JiraSession.open(opts.budget);
485
670
  const parts = splitAt(body, JIRA_COMMENT_LIMIT);
671
+ if (opts.commentId && parts.length !== 1)
672
+ throw new TrackerError("unsupported", "jira: split bodies require new comments");
486
673
  let id: unknown;
674
+ let observed = false;
675
+ let returnedBody: string | undefined;
487
676
  for (const part of parts) {
488
- const res = await jira.call(JIRA_TOOLS.comment, {
489
- cloudId: site,
490
- issueIdOrKey: t.issue,
491
- commentBody: part,
492
- });
493
- id = asRecord(res).id;
677
+ charge(opts.budget, "writes");
678
+ const res = asRecord(
679
+ await jira.call(JIRA_TOOLS.comment, {
680
+ cloudId: site,
681
+ issueIdOrKey: t.issue,
682
+ commentBody: part,
683
+ ...(opts.commentId
684
+ ? {
685
+ commentId: opts.commentId,
686
+ contentFormat: "markdown",
687
+ responseContentFormat: "markdown",
688
+ }
689
+ : {}),
690
+ }),
691
+ );
692
+ const raw = res.data === undefined ? res : asRecord(res.data);
693
+ id = raw.commentId ?? raw.id;
694
+ observed = typeof raw.commentId === "string";
695
+ returnedBody =
696
+ raw.appliedContentFormat === "markdown" && typeof raw.body === "string"
697
+ ? raw.body
698
+ : undefined;
494
699
  }
495
700
  const base = `${site}/browse/${t.issue}`;
496
- return {
701
+ const posted = {
497
702
  url: id === undefined ? base : `${base}?focusedCommentId=${String(id)}`,
498
703
  parts: parts.length,
499
704
  };
705
+ if (observed && parts.length === 1) {
706
+ try {
707
+ const latest = await jiraComments(t, 1, jira, opts.budget);
708
+ const evidence = latest.find(
709
+ (comment) =>
710
+ comment.evidence !== undefined &&
711
+ comment.evidence.id === id &&
712
+ returnedBody !== undefined &&
713
+ comment.evidence.fingerprint === actionHash(returnedBody) &&
714
+ (!opts.evidence || comment.evidence.authorId === opts.evidence.authorId),
715
+ )?.evidence;
716
+ return { ...posted, ...(evidence ? { evidence } : {}) };
717
+ } catch {
718
+ // An acknowledged mutation stays successful when optional evidence is unavailable.
719
+ return posted;
720
+ }
721
+ }
722
+ return posted;
500
723
  }
501
724
  throw new TrackerError("not-found", "issue tracker none");
502
725
  }
@@ -505,34 +728,149 @@ export async function postComment(t: TrackerTarget, body: string): Promise<Poste
505
728
  export async function recentComments(
506
729
  t: TrackerTarget,
507
730
  n: number,
508
- ): Promise<Array<{ body: string; url: string | null }>> {
509
- if (t.issue === null) return [];
731
+ budget?: DeliveryBudget,
732
+ ): Promise<Array<{ body: string; url: string | null; evidence?: CommentEvidence }>> {
733
+ if (t.issue === null || !Number.isInteger(n) || n <= 0) return [];
510
734
  if (t.tracker === "github") {
511
735
  const [owner, name] = t.ownerRepo.split("/");
512
- const out = gh(t, [
513
- "api",
514
- "graphql",
515
- "-f",
516
- `query=query($o:String!,$r:String!,$n:Int!){repository(owner:$o,name:$r){issue(number:$n){comments(last:${n}){nodes{body url}}}}}`,
517
- "-F",
518
- `o=${owner ?? ""}`,
519
- "-F",
520
- `r=${name ?? ""}`,
521
- "-F",
522
- `n=${t.issue}`,
523
- ]);
524
- const parsed = parseJson(out);
525
- const nodes = asRecord(
526
- asRecord(asRecord(asRecord(asRecord(parsed.ok ? parsed.value : null).data).repository).issue)
527
- .comments,
528
- ).nodes;
529
- return (Array.isArray(nodes) ? nodes : []).map((c) => {
736
+ const nodes: unknown[] = [];
737
+ const cursors = new Set<string>();
738
+ let before: string | undefined;
739
+ for (let page = 0; page < 10; page++) {
740
+ charge(budget, "pages");
741
+ const out = gh(
742
+ t,
743
+ [
744
+ "api",
745
+ "graphql",
746
+ "-f",
747
+ `query=query($o:String!,$r:String!,$n:Int!,$before:String){repository(owner:$o,name:$r){issue(number:$n){comments(last:${Math.min(n, 100)},before:$before){nodes{id databaseId body url author{__typename ... on User{id databaseId} ... on Bot{id databaseId}} createdAt updatedAt} pageInfo{hasPreviousPage startCursor}}}}}`,
748
+ "-F",
749
+ `o=${owner ?? ""}`,
750
+ "-F",
751
+ `r=${name ?? ""}`,
752
+ "-F",
753
+ `n=${t.issue}`,
754
+ ...(before ? ["-f", `before=${before}`] : []),
755
+ ],
756
+ undefined,
757
+ budget,
758
+ );
759
+ const parsed = parseJson(out);
760
+ const comments = asRecord(
761
+ asRecord(
762
+ asRecord(asRecord(asRecord(parsed.ok ? parsed.value : null).data).repository).issue,
763
+ ).comments,
764
+ );
765
+ if (!Array.isArray(comments.nodes))
766
+ throw new TrackerError("http-200", "github: comment page returned no nodes");
767
+ nodes.unshift(...comments.nodes);
768
+ const info = asRecord(comments.pageInfo);
769
+ if (info.hasPreviousPage !== true || nodes.length >= n) break;
770
+ const cursor = info.startCursor;
771
+ if (typeof cursor !== "string" || cursor === "" || cursors.has(cursor) || page === 9)
772
+ throw new TrackerError("http-200", "github: comment pagination is incomplete");
773
+ cursors.add(cursor);
774
+ before = cursor;
775
+ }
776
+ return nodes.map((c) => {
530
777
  const r = asRecord(c);
531
- return { body: String(r.body ?? ""), url: typeof r.url === "string" ? r.url : null };
778
+ const evidence = commentEvidence(r);
779
+ return {
780
+ body: String(r.body ?? ""),
781
+ url: typeof r.url === "string" ? r.url : null,
782
+ ...(evidence ? { evidence } : {}),
783
+ };
532
784
  });
533
785
  }
534
- const issue = await fetchIssue(t);
535
- return issue.comments.slice(-n).map((c) => ({ body: c.body, url: null }));
786
+ if (t.tracker === "linear") {
787
+ const nodes: unknown[] = [];
788
+ const cursors = new Set<string>();
789
+ let after: string | null = null;
790
+ for (let page = 0; page < 10; page++) {
791
+ charge(budget, "pages");
792
+ const data = await linearGql(
793
+ "query($id: String!, $after: String) { issue(id: $id) { comments(first: 100, after: $after) { nodes { id body url createdAt updatedAt user { id } } pageInfo { hasNextPage endCursor } } } }",
794
+ { id: t.issue, after },
795
+ budget,
796
+ );
797
+ const comments = asRecord(asRecord(data.issue).comments);
798
+ if (!Array.isArray(comments.nodes))
799
+ throw new TrackerError("http-200", "linear: comment page returned no nodes");
800
+ nodes.push(...comments.nodes);
801
+ const info = asRecord(comments.pageInfo);
802
+ if (info.hasNextPage !== true) break;
803
+ const cursor = info.endCursor;
804
+ if (typeof cursor !== "string" || cursor === "" || cursors.has(cursor) || page === 9)
805
+ throw new TrackerError("http-200", "linear: comment pagination is incomplete");
806
+ cursors.add(cursor);
807
+ after = cursor;
808
+ }
809
+ const ordered = nodes.map((raw) => {
810
+ const comment = asRecord(raw);
811
+ const created = typeof comment.createdAt === "string" ? Date.parse(comment.createdAt) : NaN;
812
+ if (!Number.isFinite(created))
813
+ throw new TrackerError("http-200", "linear: comment creation ordering is incomplete");
814
+ return { comment, created };
815
+ });
816
+ return ordered
817
+ .sort((a, b) => a.created - b.created)
818
+ .slice(-n)
819
+ .map(({ comment: raw }) => {
820
+ const evidence = commentEvidence(raw);
821
+ return {
822
+ body: str(raw.body),
823
+ url: typeof raw.url === "string" ? raw.url : null,
824
+ ...(evidence ? { evidence } : {}),
825
+ };
826
+ });
827
+ }
828
+ if (t.tracker === "jira") return jiraComments(t, n, JiraSession.open(budget), budget);
829
+ return [];
830
+ }
831
+
832
+ async function jiraComments(
833
+ t: TrackerTarget,
834
+ n: number,
835
+ jira: JiraSession,
836
+ budget?: DeliveryBudget,
837
+ ): Promise<Array<{ body: string; url: string | null; evidence?: CommentEvidence }>> {
838
+ const site = jiraSite(t);
839
+ const comments: Array<{ body: string; url: string | null; evidence?: CommentEvidence }> = [];
840
+ for (let page = 0; page < 10; page++) {
841
+ charge(budget, "pages");
842
+ const response = asRecord(
843
+ await jira.call(JIRA_TOOLS.comments, {
844
+ cloudId: site,
845
+ issueIdOrKey: t.issue,
846
+ startAt: comments.length,
847
+ maxResults: Math.min(n - comments.length, 100),
848
+ orderBy: "-created",
849
+ responseContentFormat: "markdown",
850
+ view: "evidence",
851
+ }),
852
+ );
853
+ const data = response.data === undefined ? response : asRecord(response.data);
854
+ if (!Array.isArray(data.comments))
855
+ throw new TrackerError("http-200", "jira: comment page returned no comments");
856
+ for (const item of data.comments) {
857
+ const raw = asRecord(item);
858
+ const candidate = data.appliedContentFormat === "markdown" ? commentEvidence(raw) : undefined;
859
+ const evidence = candidate?.authorId ? candidate : undefined;
860
+ comments.push({
861
+ body: textOf(raw.body),
862
+ url:
863
+ typeof raw.id === "string"
864
+ ? `${site}/browse/${t.issue}?focusedCommentId=${raw.id}`
865
+ : null,
866
+ ...(evidence ? { evidence } : {}),
867
+ });
868
+ }
869
+ if (data.isLast !== false || comments.length >= n) return comments.slice(0, n).reverse();
870
+ if (data.comments.length === 0)
871
+ throw new TrackerError("http-200", "jira: comment pagination is incomplete");
872
+ }
873
+ throw new TrackerError("http-200", "jira: comment pagination is incomplete");
536
874
  }
537
875
 
538
876
  export interface FetchedIssue {
@@ -540,6 +878,8 @@ export interface FetchedIssue {
540
878
  url: string;
541
879
  state: string;
542
880
  labels: string[];
881
+ /** Finished by the tracker's state category (never by state name). */
882
+ terminal: boolean;
543
883
  /** The description, raw. */
544
884
  body: string;
545
885
  /** In the order the tracker returned them; callers sort. */
@@ -548,6 +888,17 @@ export interface FetchedIssue {
548
888
 
549
889
  const str = (v: unknown): string => (typeof v === "string" ? v : "");
550
890
 
891
+ /**
892
+ * One terminal judgement for every tracker, by state category: GitHub `closed`, Linear
893
+ * state type `completed` / `canceled`, Jira status category `done`. Renamed states
894
+ * stay judged right because the name is never read.
895
+ */
896
+ function isTerminal(tracker: "github" | "linear" | "jira", state: string, category: string) {
897
+ if (tracker === "github") return state === "closed";
898
+ if (tracker === "linear") return category === "completed" || category === "canceled";
899
+ return category === "done";
900
+ }
901
+
551
902
  // ADF nodes whose children are inline text; every other node's children are blocks, one per line.
552
903
  const ADF_INLINE = new Set(["paragraph", "heading", "codeBlock", "mediaSingle"]);
553
904
 
@@ -605,6 +956,7 @@ export async function fetchIssue(t: TrackerTarget): Promise<FetchedIssue> {
605
956
  labels: (Array.isArray(issue.labels) ? issue.labels : []).map((l) =>
606
957
  typeof l === "string" ? l : str(asRecord(l).name),
607
958
  ),
959
+ terminal: isTerminal("github", str(issue.state), ""),
608
960
  body: str(issue.body),
609
961
  comments,
610
962
  };
@@ -612,7 +964,7 @@ export async function fetchIssue(t: TrackerTarget): Promise<FetchedIssue> {
612
964
  if (t.tracker === "linear") {
613
965
  const page = "nodes { body createdAt } pageInfo { hasNextPage endCursor }";
614
966
  const data = await linearGql(
615
- `query($id: String!) { issue(id: $id) { identifier title url description state { name } labels { nodes { name } } comments(first: 250) { ${page} } } }`,
967
+ `query($id: String!) { issue(id: $id) { identifier title url description state { name type } labels { nodes { name } } comments(first: 250) { ${page} } } }`,
616
968
  { id: t.issue },
617
969
  );
618
970
  const issue = asRecord(data.issue);
@@ -637,6 +989,7 @@ export async function fetchIssue(t: TrackerTarget): Promise<FetchedIssue> {
637
989
  url: str(issue.url),
638
990
  state: str(asRecord(issue.state).name),
639
991
  labels: nodes(issue.labels).map((l) => str(asRecord(l).name)),
992
+ terminal: isTerminal("linear", "", str(asRecord(issue.state).type)),
640
993
  body: str(issue.description),
641
994
  comments,
642
995
  };
@@ -648,6 +1001,7 @@ export async function fetchIssue(t: TrackerTarget): Promise<FetchedIssue> {
648
1001
  await jira.call(JIRA_TOOLS.getIssue, {
649
1002
  cloudId: site,
650
1003
  issueIdOrKey: t.issue,
1004
+ // The evidence view carries `fields.status` with its `statusCategory`, read below.
651
1005
  view: "evidence",
652
1006
  }),
653
1007
  );
@@ -686,6 +1040,7 @@ export async function fetchIssue(t: TrackerTarget): Promise<FetchedIssue> {
686
1040
  url: `${site}/browse/${t.issue}`,
687
1041
  state: str(asRecord(fields.status).name),
688
1042
  labels: (Array.isArray(fields.labels) ? fields.labels : []).map((l) => String(l)),
1043
+ terminal: isTerminal("jira", "", str(asRecord(asRecord(fields.status).statusCategory).key)),
689
1044
  body: textOf(description),
690
1045
  comments,
691
1046
  };
@@ -885,7 +1240,7 @@ export async function readBlockers(t: TrackerTarget): Promise<Blocker[]> {
885
1240
  const numbers = parseBlockedBy(str(asRecord(parsed.ok ? parsed.value : null).body));
886
1241
  return numbers.map((n) => {
887
1242
  const state = gh(t, ["api", `repos/${t.ownerRepo}/issues/${n}`, "--jq", ".state"]).trim();
888
- return { id: `#${n}`, state, open: state !== "closed" };
1243
+ return { id: `#${n}`, state, open: !isTerminal("github", state, "") };
889
1244
  });
890
1245
  }
891
1246
  if (t.tracker === "linear") {
@@ -904,7 +1259,7 @@ export async function readBlockers(t: TrackerTarget): Promise<Blocker[]> {
904
1259
  return {
905
1260
  id: str(issue.identifier),
906
1261
  state: str(state.name),
907
- open: !["completed", "canceled"].includes(str(state.type)),
1262
+ open: !isTerminal("linear", "", str(state.type)),
908
1263
  };
909
1264
  });
910
1265
  }
@@ -924,7 +1279,7 @@ export async function readBlockers(t: TrackerTarget): Promise<Blocker[]> {
924
1279
  return {
925
1280
  id: str(issue.key),
926
1281
  state: str(status.name),
927
- open: str(asRecord(status.statusCategory).key) !== "done",
1282
+ open: !isTerminal("jira", "", str(asRecord(status.statusCategory).key)),
928
1283
  };
929
1284
  });
930
1285
  }
@@ -1037,10 +1392,262 @@ export interface OnceOptions {
1037
1392
  * so the text never compares. A body without a stamped marker compares as text.
1038
1393
  */
1039
1394
  recent?: number;
1395
+ purpose?: string;
1396
+ publication?: RunContext["publication"];
1397
+ workflow?: string;
1398
+ /** Diagnostic attribution supplied by the publishing boundary. */
1399
+ cwd?: string;
1400
+ knownUrl?: string | null;
1401
+ budgetMs?: number;
1040
1402
  /** Where the redacted failure detail goes (stderr). */
1041
1403
  log: (line: string) => void;
1042
1404
  }
1043
1405
 
1406
+ interface ProgressSource {
1407
+ version: 1;
1408
+ target: string;
1409
+ invocation: string;
1410
+ workflow: string;
1411
+ source: string;
1412
+ comment: { url: string | null; evidence: CommentEvidence };
1413
+ sections: Array<{ id: string; key: string; hash: string; at?: string }>;
1414
+ }
1415
+
1416
+ interface ProgressBinding {
1417
+ target: string;
1418
+ invocation: string;
1419
+ workflow: string;
1420
+ file: string;
1421
+ at?: string;
1422
+ priorDelivery: boolean;
1423
+ }
1424
+
1425
+ function progressBinding(t: TrackerTarget, o: OnceOptions): ProgressBinding | "conflict" | null {
1426
+ const common = git(t.cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
1427
+ if (!common) return null;
1428
+ const target = [t.tracker, t.ownerRepo || t.jiraSite || t.linearTeam || "", t.issue].join("/");
1429
+ if (o.publication && o.key) {
1430
+ const { invocation, workflow } = o.publication;
1431
+ return {
1432
+ target,
1433
+ invocation,
1434
+ workflow,
1435
+ file: path.join(
1436
+ common,
1437
+ "bkit-outbox",
1438
+ "progress",
1439
+ `${actionHash(`${target}\0${invocation}`)}.json`,
1440
+ ),
1441
+ priorDelivery: false,
1442
+ };
1443
+ }
1444
+ if (!o.file || !o.key) return null;
1445
+ const [workflow, runText, step, group, attempt] = o.key.split("/");
1446
+ if (!workflow || !/^\d+$/.test(runText ?? "")) return null;
1447
+ if (step === "failure") return null;
1448
+ const runs = readRunsLenient(o.file).filter((run) => run.workflow === workflow);
1449
+ const run = runs[Number(runText) - 1];
1450
+ if (!run) return null;
1451
+ const fid = path.basename(path.dirname(o.file));
1452
+ const issue = issueIdOf(fid, t.tracker);
1453
+ if (issue !== null && issue !== t.issue) return "conflict";
1454
+ if (issue === null) return null;
1455
+ let invocation = actionHash([path.resolve(o.file), workflow, runText, run.startedAt].join("\0"));
1456
+ const association = runPublicationFile(common, o.file, workflow, run.startedAt);
1457
+ if (fs.existsSync(association)) {
1458
+ const parsed = parseJson(fs.readFileSync(association, "utf-8"));
1459
+ const saved = asRecord(parsed.ok ? parsed.value : null);
1460
+ if (saved.version === 1 && saved.workflow === workflow && typeof saved.invocation === "string")
1461
+ invocation = saved.invocation;
1462
+ }
1463
+ const at = run.steps.find(
1464
+ (row) =>
1465
+ row.step === step &&
1466
+ (group === "-" || row.group === Number(group)) &&
1467
+ (attempt === "-" || row.attempt === Number(attempt)),
1468
+ )?.at;
1469
+ const prefix = `${workflow}/${runText}/`;
1470
+ const priorDelivery = fs
1471
+ .readFileSync(o.file, "utf-8")
1472
+ .split("\n")
1473
+ .some((line) => {
1474
+ const parsed = parseJson(line);
1475
+ const row = asRecord(parsed.ok ? parsed.value : null);
1476
+ return (
1477
+ row.type === "engine-action" && typeof row.key === "string" && row.key.startsWith(prefix)
1478
+ );
1479
+ });
1480
+ return {
1481
+ target,
1482
+ invocation,
1483
+ workflow,
1484
+ file: path.join(
1485
+ common,
1486
+ "bkit-outbox",
1487
+ "progress",
1488
+ `${actionHash(`${target}\0${invocation}`)}.json`,
1489
+ ),
1490
+ ...(at && Number.isFinite(Date.parse(at)) ? { at } : {}),
1491
+ priorDelivery,
1492
+ };
1493
+ }
1494
+
1495
+ function readProgress(binding: ProgressBinding): ProgressSource | null {
1496
+ if (!fs.existsSync(binding.file)) return null;
1497
+ const parsed = parseJson(fs.readFileSync(binding.file, "utf-8"));
1498
+ const raw = asRecord(parsed.ok ? parsed.value : null);
1499
+ const comment = asRecord(raw.comment);
1500
+ const evidence = asRecord(comment.evidence);
1501
+ if (
1502
+ raw.version !== 1 ||
1503
+ raw.target !== binding.target ||
1504
+ raw.invocation !== binding.invocation ||
1505
+ raw.workflow !== binding.workflow ||
1506
+ typeof raw.source !== "string" ||
1507
+ !Array.isArray(raw.sections) ||
1508
+ typeof evidence.id !== "string" ||
1509
+ typeof evidence.authorId !== "string" ||
1510
+ typeof evidence.fingerprint !== "string" ||
1511
+ typeof evidence.createdAt !== "string" ||
1512
+ typeof evidence.updatedAt !== "string" ||
1513
+ evidence.representation !== "markdown" ||
1514
+ !Array.isArray(evidence.sectionIds) ||
1515
+ !evidence.sectionIds.every((id) => typeof id === "string") ||
1516
+ (comment.url !== null && typeof comment.url !== "string")
1517
+ )
1518
+ return null;
1519
+ const sections: ProgressSource["sections"] = [];
1520
+ for (const value of raw.sections) {
1521
+ const section = asRecord(value);
1522
+ if (
1523
+ typeof section.id !== "string" ||
1524
+ typeof section.key !== "string" ||
1525
+ typeof section.hash !== "string" ||
1526
+ (section.at !== undefined && typeof section.at !== "string")
1527
+ )
1528
+ return null;
1529
+ sections.push({
1530
+ id: section.id,
1531
+ key: section.key,
1532
+ hash: section.hash,
1533
+ ...(typeof section.at === "string" ? { at: section.at } : {}),
1534
+ });
1535
+ }
1536
+ return {
1537
+ version: 1,
1538
+ target: binding.target,
1539
+ invocation: binding.invocation,
1540
+ workflow: binding.workflow,
1541
+ source: raw.source,
1542
+ comment: {
1543
+ url: comment.url,
1544
+ evidence: {
1545
+ id: evidence.id,
1546
+ authorId: evidence.authorId,
1547
+ fingerprint: evidence.fingerprint,
1548
+ createdAt: evidence.createdAt,
1549
+ updatedAt: evidence.updatedAt,
1550
+ representation: "markdown",
1551
+ sectionIds: evidence.sectionIds,
1552
+ },
1553
+ },
1554
+ sections,
1555
+ };
1556
+ }
1557
+
1558
+ function progressSection(body: string, binding: ProgressBinding, key: string) {
1559
+ const hash = actionHash(body);
1560
+ const section = {
1561
+ id: actionHash(`${key}\0${hash}`),
1562
+ key,
1563
+ hash,
1564
+ ...(binding.at ? { at: binding.at } : {}),
1565
+ };
1566
+ const rest = body.split("\n").slice(1).join("\n");
1567
+ const source = stampMarker(
1568
+ [
1569
+ GENERATED_MARKER,
1570
+ `###### bkit:progress v1 ${binding.invocation} 1 1`,
1571
+ `###### bkit:section v1 ${section.id} 1/1`,
1572
+ ...(binding.at ? [`Reported at ${binding.at}`, ""] : []),
1573
+ rest,
1574
+ ].join("\n"),
1575
+ );
1576
+ return { section, source };
1577
+ }
1578
+
1579
+ function saveProgress(
1580
+ binding: ProgressBinding,
1581
+ source: string,
1582
+ section: ProgressSource["sections"][number],
1583
+ posted: PostedComment,
1584
+ priorSections: ProgressSource["sections"] = [],
1585
+ ): void {
1586
+ if (!posted.evidence?.authorId) return;
1587
+ const state: ProgressSource = {
1588
+ version: 1,
1589
+ target: binding.target,
1590
+ invocation: binding.invocation,
1591
+ workflow: binding.workflow,
1592
+ source,
1593
+ comment: { url: posted.url, evidence: posted.evidence },
1594
+ sections: [...priorSections, section],
1595
+ };
1596
+ fs.mkdirSync(path.dirname(binding.file), { recursive: true });
1597
+ fs.writeFileSync(binding.file, JSON.stringify(state), { mode: 0o600 });
1598
+ }
1599
+
1600
+ export function commentDiagnostic(o: OnceOptions, text: string, warnings: string[]): void {
1601
+ const detail = redact(text);
1602
+ try {
1603
+ o.log(detail);
1604
+ } catch {
1605
+ warnings.push(`${detail}; comment diagnostic unavailable`);
1606
+ }
1607
+ const workflow = o.publication?.workflow ?? o.workflow ?? o.key?.split("/")[0];
1608
+ if (
1609
+ !o.cwd ||
1610
+ !workflow ||
1611
+ !["design", "plan", "build", "debug", "ship", "auto"].includes(workflow)
1612
+ )
1613
+ return;
1614
+ const stage = /receipt|engine-action/.test(text)
1615
+ ? "receipt"
1616
+ : /lock/.test(text)
1617
+ ? "lock"
1618
+ : /recognition|reconciliation|postflight/.test(text)
1619
+ ? "reconciliation"
1620
+ : /source|cache/.test(text)
1621
+ ? "source"
1622
+ : /association/.test(text)
1623
+ ? "association"
1624
+ : "delivery";
1625
+ try {
1626
+ const root = git(o.cwd, ["rev-parse", "--show-toplevel"]) ?? o.cwd;
1627
+ const row = frictionRow({
1628
+ workflow,
1629
+ step: `comment-${stage}`,
1630
+ noun: "tracker",
1631
+ verb: "comment",
1632
+ code: null,
1633
+ bookRoot: root,
1634
+ });
1635
+ row.summary = `Workflow comment ${stage} unavailable`;
1636
+ row.description = `${workflow} comment reporting encountered an exhausted ${stage} problem; substantive workflow work continues.`;
1637
+ row.remediation =
1638
+ "Inspect tracker availability or local comment state; delivery may start a fresh comment.";
1639
+ if (o.knownUrl) row.references = [o.knownUrl];
1640
+ if (appendFrictionRow(root, row).ok) return;
1641
+ } catch {
1642
+ warnings.push("[bkit-tracker] comment friction unavailable");
1643
+ }
1644
+ try {
1645
+ o.log("[bkit-tracker] comment friction unavailable; continuing workflow");
1646
+ } catch {
1647
+ warnings.push("[bkit-tracker] friction diagnostic unavailable");
1648
+ }
1649
+ }
1650
+
1044
1651
  /** The latest of `recent` that is `body` posted before: same marker hash, else same text. */
1045
1652
  function samePosted<T extends { body: string }>(recent: T[], body: string): T | undefined {
1046
1653
  const hash = markerHashOf(body);
@@ -1060,38 +1667,246 @@ export async function postCommentOnce(
1060
1667
  body: string,
1061
1668
  o: OnceOptions,
1062
1669
  ): Promise<TrackerOutcome> {
1670
+ o = { ...o, cwd: t.cwd };
1063
1671
  const skip = skipOf(t);
1064
1672
  if (skip) return skip;
1065
1673
  const action = "comment";
1066
1674
  const hash = actionHash(body);
1067
- let posted: PostedComment;
1068
- try {
1069
- if (o.file && o.key) {
1070
- const prior = alreadyDone(o.file, o.key, hash);
1071
- if (prior) return { done: true, action, url: prior.ref, deduped: true };
1072
- }
1073
- if (o.recent) {
1074
- const same = samePosted(await recentComments(t, o.recent), body);
1075
- if (same) return { done: true, action, url: same.url, deduped: true };
1675
+ let posted: PostedComment | undefined;
1676
+ let binding: ProgressBinding | "conflict" | null = null;
1677
+ let outgoing = body;
1678
+ let section: ProgressSource["sections"][number] | undefined;
1679
+ const warnings: string[] = [];
1680
+ let cached: ProgressSource | null = null;
1681
+ let lock: Awaited<ReturnType<typeof acquirePublicationLock>> = null;
1682
+ const routine = o.purpose === "routine";
1683
+ let aggregate = false;
1684
+ const budget: DeliveryBudget = {
1685
+ deadline: 0,
1686
+ duration: Math.max(1, Math.min(60_000, o.budgetMs ?? 60_000)),
1687
+ pages: 0,
1688
+ writes: 0,
1689
+ reserve: true,
1690
+ };
1691
+ const seal = () => {
1692
+ if (binding && binding !== "conflict") {
1693
+ try {
1694
+ fs.rmSync(binding.file, { force: true });
1695
+ } catch {
1696
+ commentDiagnostic(o, "[bkit-tracker] progress seal unavailable", warnings);
1697
+ }
1076
1698
  }
1077
- posted = await postComment(t, body);
1078
- } catch (err) {
1079
- const reason = classifyFailure(err);
1080
- o.log(redact(`tracker ${action} failed (${reason}): ${(err as Error).message ?? String(err)}`));
1081
- return { done: false, action, reason };
1082
- }
1083
- if (o.file && o.key) {
1699
+ };
1700
+ let retain = true;
1701
+ try {
1084
1702
  try {
1085
- recordAction(o.file, { action, key: o.key, hash, ref: posted.url });
1703
+ try {
1704
+ binding = progressBinding(t, o);
1705
+ } catch {
1706
+ commentDiagnostic(
1707
+ o,
1708
+ "[bkit-tracker] progress association unavailable; creating standalone comment",
1709
+ warnings,
1710
+ );
1711
+ }
1712
+ if (o.file && o.key && binding !== "conflict") {
1713
+ try {
1714
+ const prior = alreadyDone(o.file, o.key, hash);
1715
+ if (prior) return { done: true, action, url: prior.ref, deduped: true };
1716
+ } catch {
1717
+ commentDiagnostic(
1718
+ o,
1719
+ "[bkit-tracker] comment receipt unavailable; creating standalone comment",
1720
+ warnings,
1721
+ );
1722
+ }
1723
+ }
1724
+ if (o.purpose === "attention" || o.purpose === "terminal") seal();
1725
+ if (
1726
+ binding &&
1727
+ binding !== "conflict" &&
1728
+ o.key &&
1729
+ markerHashOf(body) &&
1730
+ o.purpose !== "attention" &&
1731
+ o.purpose !== "terminal"
1732
+ ) {
1733
+ try {
1734
+ cached = readProgress(binding);
1735
+ if (cached === null && fs.existsSync(binding.file))
1736
+ commentDiagnostic(
1737
+ o,
1738
+ "[bkit-tracker] progress source unavailable; creating standalone comment",
1739
+ warnings,
1740
+ );
1741
+ if (cached) o.knownUrl = cached.comment.url;
1742
+ const rendered = progressSection(body, binding, o.key);
1743
+ section = rendered.section;
1744
+ if (routine) {
1745
+ lock = await acquirePublicationLock(t.cwd, {
1746
+ target: binding.target,
1747
+ invocation: binding.invocation,
1748
+ timeoutMs: Math.min(30_000, budget.duration / 2),
1749
+ });
1750
+ if (!lock) {
1751
+ cached = null;
1752
+ commentDiagnostic(
1753
+ o,
1754
+ "[bkit-tracker] aggregation unavailable: publication lock",
1755
+ warnings,
1756
+ );
1757
+ } else {
1758
+ cached = readProgress(binding);
1759
+ if (cached && budget.duration < 1000) {
1760
+ // With a short caller allowance, reserve the transport for standalone delivery.
1761
+ outgoing = body;
1762
+ } else if (cached) {
1763
+ const newest = (await recentComments(t, 1, budget)).at(-1);
1764
+ const actual = newest?.evidence;
1765
+ const saved = cached.comment.evidence;
1766
+ if (
1767
+ actual?.authorId &&
1768
+ actual.id === saved.id &&
1769
+ actual.authorId === saved.authorId &&
1770
+ actual.fingerprint === saved.fingerprint &&
1771
+ actual.updatedAt === saved.updatedAt &&
1772
+ actual.createdAt === saved.createdAt &&
1773
+ actual.representation === saved.representation
1774
+ ) {
1775
+ const known = cached.sections.find((s) => s.id === rendered.section.id);
1776
+ if (known && actual.sectionIds.includes(known.id))
1777
+ return {
1778
+ done: true,
1779
+ action,
1780
+ url: newest?.url ?? cached.comment.url,
1781
+ deduped: true,
1782
+ };
1783
+ outgoing = `${cached.source}\n\n${rendered.source.split("\n").slice(2).join("\n")}`;
1784
+ const limit =
1785
+ t.tracker === "linear"
1786
+ ? COMMENT_BODY_BUDGETS.linear
1787
+ : t.tracker === "jira"
1788
+ ? COMMENT_BODY_BUDGETS.jira
1789
+ : COMMENT_BODY_BUDGETS.github;
1790
+ if (outgoing.length <= limit) aggregate = true;
1791
+ else outgoing = body;
1792
+ } else outgoing = body;
1793
+ } else if (!binding.priorDelivery) outgoing = rendered.source;
1794
+ }
1795
+ } else if (cached || !binding.priorDelivery) outgoing = rendered.source;
1796
+ } catch {
1797
+ outgoing = body;
1798
+ aggregate = false;
1799
+ commentDiagnostic(
1800
+ o,
1801
+ "[bkit-tracker] progress source unavailable; creating standalone comment",
1802
+ warnings,
1803
+ );
1804
+ }
1805
+ }
1806
+ if (routine && (!binding || binding === "conflict"))
1807
+ commentDiagnostic(
1808
+ o,
1809
+ "[bkit-tracker] aggregation unavailable: progress association unavailable",
1810
+ warnings,
1811
+ );
1812
+ if (o.recent) {
1813
+ try {
1814
+ const same = samePosted(await recentComments(t, o.recent, budget), body);
1815
+ if (same) return { done: true, action, url: same.url, deduped: true };
1816
+ } catch {
1817
+ commentDiagnostic(
1818
+ o,
1819
+ "[bkit-tracker] comment lookup unavailable; creating standalone comment",
1820
+ warnings,
1821
+ );
1822
+ outgoing = body;
1823
+ }
1824
+ }
1825
+ if (aggregate && cached) {
1826
+ try {
1827
+ posted = await postComment(t, outgoing, {
1828
+ commentId: cached.comment.evidence.id,
1829
+ evidence: cached.comment.evidence,
1830
+ budget,
1831
+ });
1832
+ } catch {
1833
+ try {
1834
+ const latest = (await recentComments(t, 1, budget)).at(-1);
1835
+ if (
1836
+ latest?.evidence?.id === cached.comment.evidence.id &&
1837
+ latest.evidence.authorId === cached.comment.evidence.authorId &&
1838
+ section &&
1839
+ latest.evidence.sectionIds.includes(section.id)
1840
+ ) {
1841
+ posted = { url: latest.url, parts: 1, evidence: latest.evidence };
1842
+ // A section proves delivery, not authority to overwrite a changed revision.
1843
+ retain = latest.evidence.fingerprint === actionHash(outgoing);
1844
+ }
1845
+ } catch {
1846
+ commentDiagnostic(o, "[bkit-tracker] append recognition unavailable", warnings);
1847
+ }
1848
+ if (!posted) {
1849
+ outgoing = body;
1850
+ aggregate = false;
1851
+ seal();
1852
+ }
1853
+ }
1854
+ }
1855
+ if (!posted) {
1856
+ budget.reserve = false;
1857
+ posted = await postComment(t, outgoing, { budget });
1858
+ }
1086
1859
  } catch (err) {
1087
- const warning = redact(
1088
- `posted, but the engine-action row was not written to ${o.file}: ${(err as Error).message ?? String(err)}`,
1089
- );
1090
- o.log(warning);
1091
- return { done: true, action, url: posted.url, warning };
1860
+ const reason = classifyFailure(err);
1861
+ commentDiagnostic(o, `tracker ${action} failed (${reason}); delivery unavailable`, warnings);
1862
+ seal();
1863
+ return { done: false, action, reason };
1864
+ }
1865
+ if (aggregate && posted.evidence) {
1866
+ try {
1867
+ const latest = (await recentComments(t, 1, budget)).at(-1)?.evidence;
1868
+ retain =
1869
+ retain &&
1870
+ latest?.id === posted.evidence.id &&
1871
+ latest.fingerprint === posted.evidence.fingerprint &&
1872
+ latest.authorId === posted.evidence.authorId &&
1873
+ latest.updatedAt === posted.evidence.updatedAt;
1874
+ } catch {
1875
+ retain = false;
1876
+ commentDiagnostic(o, "[bkit-tracker] postflight reconciliation unavailable", warnings);
1877
+ }
1878
+ if (!retain) seal();
1879
+ }
1880
+ if (retain && binding && binding !== "conflict" && section) {
1881
+ try {
1882
+ saveProgress(binding, outgoing, section, posted, aggregate ? cached?.sections : []);
1883
+ } catch {
1884
+ const warning = "[bkit-tracker] posted, but progress source could not be saved";
1885
+ commentDiagnostic(o, warning, warnings);
1886
+ warnings.push(warning);
1887
+ }
1888
+ }
1889
+ if (o.file && o.key && binding !== "conflict") {
1890
+ try {
1891
+ recordAction(o.file, { action, key: o.key, hash, ref: posted.url });
1892
+ } catch (err) {
1893
+ const warning = redact(
1894
+ `posted, but the engine-action row was not written to ${o.file}: ${(err as Error).message ?? String(err)}`,
1895
+ );
1896
+ commentDiagnostic(o, warning, warnings);
1897
+ warnings.push(warning);
1898
+ }
1092
1899
  }
1900
+ return {
1901
+ done: true,
1902
+ action,
1903
+ url: posted.url,
1904
+ ...(warnings.length ? { warning: warnings.join("; ") } : {}),
1905
+ };
1906
+ } finally {
1907
+ if (lock && !(await releasePublicationLock(lock)))
1908
+ commentDiagnostic(o, "[bkit-tracker] publication lock release unavailable", warnings);
1093
1909
  }
1094
- return { done: true, action, url: posted.url };
1095
1910
  }
1096
1911
 
1097
1912
  /** Run one tracker write as `action`: `done: true`, or `done: false` with the reason (logged, redacted). */
@@ -1127,14 +1942,148 @@ export const TRACKER_OUTPUT =
1127
1942
 
1128
1943
  /** The `commentFile` output key's meaning, shared by every verb that prints a comment. */
1129
1944
  export const COMMENT_FILE_OUTPUT =
1130
- "absolute path of a file holding `comment` byte-for-byte (the MCP fallback reads it); null when comment is null";
1945
+ "absolute path of a file holding `comment` byte-for-byte (the MCP fallback reads it); null when comment is null or its source file is unavailable";
1131
1946
 
1132
1947
  /** How many of the issue's latest comments a re-run checks for the same marker hash. */
1133
1948
  export const RECENT_COMMENTS = 5;
1134
1949
 
1135
1950
  /** `comment` written to its body file, or null for no comment. */
1136
- export const commentFileOf = (cwd: string, comment: string | null): string | null =>
1137
- comment === null ? null : writeBodyFile(cwd, "comment", comment);
1951
+ export function commentFileOf(
1952
+ cwd: string,
1953
+ comment: string | null,
1954
+ ctx?: Pick<RunContext, "flags" | "publication" | "log">,
1955
+ ): string | null {
1956
+ if (comment === null) return null;
1957
+ try {
1958
+ return writeBodyFile(cwd, "comment", comment);
1959
+ } catch {
1960
+ commentDiagnostic(
1961
+ {
1962
+ cwd,
1963
+ workflow: ctx?.publication?.workflow ?? str(ctx?.flags.workflow),
1964
+ log: (line) => ctx?.log(line),
1965
+ },
1966
+ "[bkit-tracker] fallback source unavailable; continuing workflow",
1967
+ [],
1968
+ );
1969
+ return null;
1970
+ }
1971
+ }
1972
+
1973
+ /** This repository's private outbox `sessions/` folder; null outside a Git repository. */
1974
+ export function sessionsRoot(cwd: string): string | null {
1975
+ const common = git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
1976
+ return common ? path.join(common, "bkit-outbox", "sessions") : null;
1977
+ }
1978
+
1979
+ /** The real path of `p`, resolving its nearest existing ancestor when `p` itself is gone. */
1980
+ function canonicalPath(p: string): string {
1981
+ const abs = path.resolve(p);
1982
+ const tail: string[] = [];
1983
+ let head = abs;
1984
+ while (!fs.existsSync(head)) {
1985
+ const parent = path.dirname(head);
1986
+ if (parent === head) return abs;
1987
+ tail.unshift(path.basename(head));
1988
+ head = parent;
1989
+ }
1990
+ return path.join(fs.realpathSync(head), ...tail);
1991
+ }
1992
+
1993
+ /**
1994
+ * Proof that a workflow or audit run is making a `bkit issues comment` call: a session
1995
+ * folder directly under the outbox `sessions/` folder (it may be deleted by now), a
1996
+ * status file holding a run, or an audit body file in its own audit outbox folder.
1997
+ * Null with no proof or on any lookup error.
1998
+ */
1999
+ export function commentRunProof(ctx: RunContext): "session" | "status" | "audit" | null {
2000
+ try {
2001
+ const session = str(ctx.flags.sessionDir);
2002
+ if (session !== undefined) {
2003
+ const root = sessionsRoot(ctx.cwd);
2004
+ if (
2005
+ root &&
2006
+ path.dirname(canonicalPath(path.resolve(ctx.cwd, session))) === canonicalPath(root)
2007
+ )
2008
+ return "session";
2009
+ }
2010
+ const file = str(ctx.flags.file);
2011
+ if (file !== undefined) {
2012
+ const abs = path.resolve(ctx.cwd, file);
2013
+ if (
2014
+ fs.statSync(abs).isFile() &&
2015
+ endedRunActionKey(abs, str(ctx.flags.workflow) || undefined, "proof") !== undefined
2016
+ )
2017
+ return "status";
2018
+ }
2019
+ const slug = str(ctx.flags.auditSlug);
2020
+ const body = str(ctx.flags.bodyFile);
2021
+ if (str(ctx.flags.kind) === "audit" && slug !== undefined && body !== undefined) {
2022
+ const root = sessionsRoot(ctx.cwd);
2023
+ if (
2024
+ root &&
2025
+ path.dirname(canonicalPath(path.resolve(ctx.cwd, body))) ===
2026
+ path.join(canonicalPath(path.dirname(root)), `audit-${slug}`)
2027
+ )
2028
+ return "audit";
2029
+ }
2030
+ return null;
2031
+ } catch {
2032
+ return null;
2033
+ }
2034
+ }
2035
+
2036
+ /** Optional session ownership, validated against this repository's private outbox. */
2037
+ export function sessionPublication(
2038
+ cwd: string,
2039
+ session: string | undefined,
2040
+ workflow: string | undefined,
2041
+ ): RunContext["publication"] {
2042
+ if (!session || !workflow) return undefined;
2043
+ const sessions = sessionsRoot(cwd);
2044
+ if (!sessions) throw new Error("session association repository unavailable");
2045
+ const dir = fs.realpathSync(path.resolve(cwd, session));
2046
+ if (path.dirname(dir) !== fs.realpathSync(sessions) || !fs.statSync(dir).isDirectory())
2047
+ throw new Error("session association directory unavailable");
2048
+ return { invocation: actionHash(`${dir}\0${workflow}`), workflow };
2049
+ }
2050
+
2051
+ function runPublicationFile(common: string, file: string, workflow: string, at: string): string {
2052
+ return path.join(
2053
+ common,
2054
+ "bkit-outbox",
2055
+ "invocations",
2056
+ `${actionHash([path.resolve(file), workflow, at].join("\0"))}.json`,
2057
+ );
2058
+ }
2059
+
2060
+ /** Bind only the exact run opened by workflows start; loss of this cache is harmless. */
2061
+ export function bindRunPublication(
2062
+ ctx: RunContext,
2063
+ file: string,
2064
+ workflow: string,
2065
+ run: number,
2066
+ ): void {
2067
+ try {
2068
+ const publication = sessionPublication(ctx.cwd, str(ctx.flags.sessionDir), workflow);
2069
+ const current = readRunsLenient(file).filter((r) => r.workflow === workflow)[run - 1];
2070
+ const common = git(ctx.cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
2071
+ if (!publication || !current || !common) return;
2072
+ const destination = runPublicationFile(common, file, workflow, current.startedAt);
2073
+ if (fs.existsSync(destination)) return;
2074
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
2075
+ fs.writeFileSync(destination, JSON.stringify({ version: 1, ...publication }), {
2076
+ mode: 0o600,
2077
+ flag: "wx",
2078
+ });
2079
+ } catch {
2080
+ commentDiagnostic(
2081
+ { cwd: ctx.cwd, workflow, log: (line) => ctx.log(line) },
2082
+ "[bkit-tracker] invocation association unavailable; progress may start fresh",
2083
+ [],
2084
+ );
2085
+ }
2086
+ }
1138
2087
 
1139
2088
  /**
1140
2089
  * The engine-action key of a comment in `file`'s current run of `workflow` (the
@@ -1154,7 +2103,7 @@ export function runActionKey(
1154
2103
  */
1155
2104
  export function endedRunActionKey(
1156
2105
  file: string | undefined,
1157
- workflow: string,
2106
+ workflow: string | undefined,
1158
2107
  ...parts: Array<string | number | undefined | null>
1159
2108
  ): string | undefined {
1160
2109
  const latest = (runs: WorkflowRun[], name: string) =>
@@ -1180,16 +2129,64 @@ function commentKey(
1180
2129
  * Post `body` for a verb's `--post`: once per key in `file` when both are given,
1181
2130
  * else once per marker hash among the issue's latest comments.
1182
2131
  */
1183
- export function postForVerb(
2132
+ export async function postForVerb(
1184
2133
  ctx: RunContext,
1185
2134
  body: string,
1186
- o: { fid?: string; issue?: string; file?: string; key?: string },
2135
+ o: {
2136
+ fid?: string;
2137
+ issue?: string;
2138
+ file?: string;
2139
+ key?: string;
2140
+ purpose?: OnceOptions["purpose"];
2141
+ },
1187
2142
  ): Promise<TrackerOutcome> {
1188
- const t = trackerTarget(ctx.cwd, { fid: o.fid, issue: o.issue });
1189
- return postCommentOnce(t, body, {
1190
- file: o.file,
1191
- key: o.key,
1192
- recent: o.file && o.key ? undefined : RECENT_COMMENTS,
1193
- log: (line) => ctx.log(line),
1194
- });
2143
+ try {
2144
+ const t = trackerTarget(ctx.cwd, { fid: o.fid, issue: o.issue });
2145
+ let publication = ctx.publication;
2146
+ if (!o.file && !publication) {
2147
+ try {
2148
+ publication = sessionPublication(
2149
+ ctx.cwd,
2150
+ str(ctx.flags.sessionDir),
2151
+ str(ctx.flags.workflow),
2152
+ );
2153
+ } catch {
2154
+ commentDiagnostic(
2155
+ { cwd: ctx.cwd, workflow: str(ctx.flags.workflow), log: (line) => ctx.log(line) },
2156
+ "[bkit-tracker] invocation association unavailable; progress may start fresh",
2157
+ [],
2158
+ );
2159
+ publication = undefined;
2160
+ }
2161
+ }
2162
+ const key =
2163
+ o.key ??
2164
+ (publication
2165
+ ? actionKey(
2166
+ publication.workflow,
2167
+ 1,
2168
+ "step",
2169
+ str(ctx.flags.stepNumber),
2170
+ str(ctx.flags.subStep),
2171
+ str(ctx.flags.attempt),
2172
+ "comment",
2173
+ )
2174
+ : undefined);
2175
+ return await postCommentOnce(t, body, {
2176
+ file: o.file,
2177
+ key,
2178
+ publication,
2179
+ workflow: str(ctx.flags.workflow),
2180
+ purpose: o.purpose ?? (str(ctx.flags.workflow) ? "routine" : undefined),
2181
+ recent: key ? undefined : RECENT_COMMENTS,
2182
+ log: (line) => ctx.log(line),
2183
+ });
2184
+ } catch {
2185
+ commentDiagnostic(
2186
+ { cwd: ctx.cwd, workflow: str(ctx.flags.workflow), log: (line) => ctx.log(line) },
2187
+ "[bkit-tracker] comment preparation unavailable; continuing workflow",
2188
+ [],
2189
+ );
2190
+ return { done: false, action: "comment", reason: "preparation" };
2191
+ }
1195
2192
  }