@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
@@ -0,0 +1,1195 @@
1
+ // commands/workflow/tracker.ts — the engine's own tracker client.
2
+ //
3
+ // bkit verbs read and write the issue tracker themselves: GitHub through `gh`
4
+ // (BKIT_GH_TOKEN as GH_TOKEN when set), Linear through its GraphQL API
5
+ // (BKIT_LINEAR_API_KEY), Jira through the Atlassian Rovo MCP server spoken over
6
+ // HTTP (BKIT_JIRA_API_KEY). A call that fails throws a `TrackerError` carrying
7
+ // one short reason; the verb prints `tracker: {done: false, action, reason}` and
8
+ // the workflow falls back to the tracker MCP. No token value ever reaches a
9
+ // thrown message, a log line or stdout.
10
+
11
+ import * as fs from "node:fs";
12
+ import * as path from "node:path";
13
+
14
+ import type { IssueTracker } from "../../install/manifest.js";
15
+ import {
16
+ actionHash,
17
+ actionKey,
18
+ alreadyDone,
19
+ recordAction,
20
+ runNumber,
21
+ type WorkflowRun,
22
+ } from "../../ledgers/status.js";
23
+ import { resolveRepoSlug } from "../../ledgers/telemetry.js";
24
+ import { readBkitConfig, type BkitConfig } from "../../shared/settings.js";
25
+ import { git, parseJson, runGh, type FlagSpec, type GhResult, type RunContext } from "../lib.js";
26
+ import { issueIdOf, readIssueTracker } from "./fids.js";
27
+ import { readRunsLenient } from "./locks.js";
28
+
29
+ /** Jira Cloud's comment limit; longer bodies post as consecutive parts. */
30
+ export const JIRA_COMMENT_LIMIT = 32_767;
31
+
32
+ export const JIRA_MCP_URL = "https://mcp.atlassian.com/v2/mcp";
33
+ export const LINEAR_API_URL = "https://api.linear.app/graphql";
34
+
35
+ /** Rovo MCP tools the engine calls; `.bkit/trackers.md` names each. */
36
+ export const JIRA_TOOLS = {
37
+ getIssue: "getJiraIssue",
38
+ read: "executeRead",
39
+ comments: "listJiraIssueComments",
40
+ transitions: "listJiraIssueTransitions",
41
+ transition: "transitionJiraIssue",
42
+ comment: "addOrEditJiraIssueComment",
43
+ edit: "editJiraIssue",
44
+ search: "searchJiraIssuesUsingJql",
45
+ } as const;
46
+
47
+ // Cloudflare in front of Atlassian answers error 1010 to a default library User-Agent.
48
+ const USER_AGENT = "bkit-engine (+https://github.com/cbartens/bkit)";
49
+ const TIMEOUT_MS = 30_000;
50
+ const SECRET_KEYS = ["BKIT_GH_TOKEN", "BKIT_LINEAR_API_KEY", "BKIT_JIRA_API_KEY"] as const;
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // failure reasons
54
+ // ---------------------------------------------------------------------------
55
+
56
+ /** Why a tracker call failed: network | auth | scope | rate-limit | not-found | http-<n>. */
57
+ export type FailureReason = string;
58
+
59
+ export class TrackerError extends Error {
60
+ constructor(
61
+ readonly reason: FailureReason,
62
+ detail: string,
63
+ ) {
64
+ super(redact(detail));
65
+ this.name = "TrackerError";
66
+ }
67
+ }
68
+
69
+ /** Replace every configured tracker secret's value in `text`. */
70
+ export function redact(text: string): string {
71
+ let out = text;
72
+ for (const k of SECRET_KEYS) {
73
+ const v = process.env[k];
74
+ if (v && v.length >= 4) out = out.split(v).join(`<${k}>`);
75
+ }
76
+ return out;
77
+ }
78
+
79
+ /** The reason an HTTP status (plus its response text) maps to. */
80
+ export function classifyStatus(status: number, text = ""): FailureReason {
81
+ if (status === 401) return "auth";
82
+ if (status === 403) return /rate limit/i.test(text) ? "rate-limit" : "scope";
83
+ if (status === 404) return "not-found";
84
+ if (status === 429) return "rate-limit";
85
+ return `http-${status}`;
86
+ }
87
+
88
+ const NETWORK_CODES = /\b(ENOTFOUND|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|EHOSTUNREACH)\b/;
89
+
90
+ /** The reason any thrown value maps to; anything not a `TrackerError` or HTTP failure is network. */
91
+ export function classifyFailure(err: unknown): FailureReason {
92
+ if (err instanceof TrackerError) return err.reason;
93
+ return "network";
94
+ }
95
+
96
+ /** A `fetch` rejection (DNS, refused, timeout) as a network TrackerError. */
97
+ function networkError(err: unknown): TrackerError {
98
+ const e = err as { name?: string; message?: string; cause?: { code?: string; message?: string } };
99
+ const text = [e.name, e.message, e.cause?.code, e.cause?.message].filter(Boolean).join(" ");
100
+ const kind = /TimeoutError|AbortError/.test(text)
101
+ ? "timeout"
102
+ : (NETWORK_CODES.exec(text)?.[1] ?? "fetch failed");
103
+ return new TrackerError("network", kind);
104
+ }
105
+
106
+ /** The reason a failed `gh` call maps to. */
107
+ export function ghReason(res: GhResult): FailureReason {
108
+ if (res.missing || res.status === 4) return "auth";
109
+ const http = /\bHTTP (\d{3})\b/.exec(res.stderr);
110
+ if (http) return classifyStatus(Number(http[1]), res.stderr);
111
+ if (/rate limit/i.test(res.stderr)) return "rate-limit";
112
+ if (/connect|timeout|resolve|dial tcp|no such host/i.test(res.stderr)) return "network";
113
+ return `http-${res.status ?? 0}`;
114
+ }
115
+
116
+ // ---------------------------------------------------------------------------
117
+ // target
118
+ // ---------------------------------------------------------------------------
119
+
120
+ export interface TrackerTarget {
121
+ tracker: IssueTracker;
122
+ /** Issue number (GitHub) or key (Linear, Jira); null = the run has no issue. */
123
+ issue: string | null;
124
+ cwd: string;
125
+ /** `owner/repo` of `origin` (GitHub). */
126
+ ownerRepo: string;
127
+ linearTeam: string | null;
128
+ jiraSite: string | null;
129
+ config: BkitConfig;
130
+ }
131
+
132
+ /**
133
+ * The issue as a workflow argument: `#N` on GitHub, the key uppercased on Linear /
134
+ * Jira, verbatim (empty included) with no tracker.
135
+ */
136
+ export function issueRef(issue: string | null, tracker: IssueTracker): string {
137
+ if (issue === null || issue === "") return "";
138
+ if (tracker === "github") return `#${issue.replace(/^#/, "")}`;
139
+ if (tracker === "none") return issue;
140
+ return issue.toUpperCase();
141
+ }
142
+
143
+ /** The main checkout's root, from any worktree; `cwd` outside git. */
144
+ function mainRoot(cwd: string): string {
145
+ const common = git(cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
146
+ return common ? path.dirname(common) : cwd;
147
+ }
148
+
149
+ /**
150
+ * Where a tracker action goes: the configured tracker and the issue an explicit
151
+ * `issue` (`#` stripped) names, else the one the FID embeds.
152
+ */
153
+ export function trackerTarget(cwd: string, o: { fid?: string; issue?: string }): TrackerTarget {
154
+ const tracker = readIssueTracker(cwd);
155
+ const config = readBkitConfig(mainRoot(cwd));
156
+ const given = o.issue?.trim().replace(/^#/, "");
157
+ const issue =
158
+ given !== undefined
159
+ ? given === ""
160
+ ? null
161
+ : given.toUpperCase()
162
+ : o.fid && tracker !== "none"
163
+ ? issueIdOf(o.fid, tracker)
164
+ : null;
165
+ return {
166
+ tracker,
167
+ issue,
168
+ cwd,
169
+ ownerRepo: tracker === "github" ? resolveRepoSlug(cwd) : "",
170
+ linearTeam: config.linear.team,
171
+ jiraSite: config.jira.site,
172
+ config,
173
+ };
174
+ }
175
+
176
+ // ---------------------------------------------------------------------------
177
+ // transport
178
+ // ---------------------------------------------------------------------------
179
+
180
+ /** The env `gh` runs with: BKIT_GH_TOKEN as GH_TOKEN when set. */
181
+ export function ghEnv(): Record<string, string> {
182
+ const t = process.env.BKIT_GH_TOKEN;
183
+ return t ? { GH_TOKEN: t } : {};
184
+ }
185
+
186
+ /** `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());
189
+ if (!res.ok) throw new TrackerError(ghReason(res), `gh ${args[0] ?? ""}: ${res.stderr}`);
190
+ return res.stdout;
191
+ }
192
+
193
+ function secret(key: (typeof SECRET_KEYS)[number]): string {
194
+ const v = process.env[key];
195
+ if (!v) throw new TrackerError("auth", `${key} is not set`);
196
+ return v;
197
+ }
198
+
199
+ /** POST JSON; a non-2xx answer throws its reason unless `o.keepErrors` hands it back to read. */
200
+ async function post(
201
+ url: string,
202
+ headers: Record<string, string>,
203
+ body: unknown,
204
+ o: { keepErrors?: boolean } = {},
205
+ ): Promise<{ ok: boolean; status: number; headers: Headers; text: string }> {
206
+ let res: Response;
207
+ try {
208
+ res = await fetch(url, {
209
+ method: "POST",
210
+ headers: { "content-type": "application/json", "user-agent": USER_AGENT, ...headers },
211
+ body: JSON.stringify(body),
212
+ signal: AbortSignal.timeout(TIMEOUT_MS),
213
+ });
214
+ } catch (err) {
215
+ throw networkError(err);
216
+ }
217
+ const text = await res.text();
218
+ if (!res.ok && o.keepErrors !== true)
219
+ throw new TrackerError(classifyStatus(res.status, text), `HTTP ${res.status}`);
220
+ return { ok: res.ok, status: res.status, headers: res.headers, text };
221
+ }
222
+
223
+ const asRecord = (v: unknown): Record<string, unknown> =>
224
+ v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
225
+
226
+ // ---------------------------------------------------------------------------
227
+ // linear
228
+ // ---------------------------------------------------------------------------
229
+
230
+ const LINEAR_CODES: Record<string, FailureReason> = {
231
+ RATELIMITED: "rate-limit",
232
+ AUTHENTICATION_ERROR: "auth",
233
+ FORBIDDEN: "scope",
234
+ };
235
+
236
+ /**
237
+ * One Linear GraphQL call. GraphQL errors map to a reason by `extensions.code` — Linear
238
+ * answers rate limits and auth failures with HTTP 400 and the code in the body.
239
+ */
240
+ export async function linearGql(query: string, variables: Record<string, unknown>) {
241
+ const key = secret("BKIT_LINEAR_API_KEY");
242
+ const res = await post(
243
+ LINEAR_API_URL,
244
+ { authorization: key },
245
+ { query, variables },
246
+ { keepErrors: true },
247
+ );
248
+ const parsed = parseJson(res.text);
249
+ const doc = asRecord(parsed.ok ? parsed.value : null);
250
+ const errors = Array.isArray(doc.errors) ? (doc.errors as Array<Record<string, unknown>>) : [];
251
+ if (errors.length > 0) {
252
+ const first = errors[0]!;
253
+ const code = String(asRecord(first.extensions).code ?? "");
254
+ const message = String(first.message ?? "");
255
+ const reason =
256
+ LINEAR_CODES[code] ??
257
+ (/not found|could not find/i.test(message)
258
+ ? "not-found"
259
+ : res.ok
260
+ ? "http-400"
261
+ : classifyStatus(res.status, res.text));
262
+ throw new TrackerError(reason, `linear: ${message}`);
263
+ }
264
+ if (!res.ok) throw new TrackerError(classifyStatus(res.status, res.text), `HTTP ${res.status}`);
265
+ if (!parsed.ok) throw new TrackerError(`http-${res.status}`, "linear: response is not JSON");
266
+ return asRecord(doc.data);
267
+ }
268
+
269
+ // ---------------------------------------------------------------------------
270
+ // jira (Rovo MCP over streamable HTTP)
271
+ // ---------------------------------------------------------------------------
272
+
273
+ /** The JSON-RPC message answering `id` in a JSON or event-stream response body. */
274
+ function rpcMessage(text: string, contentType: string, id: number): Record<string, unknown> {
275
+ const candidates = /event-stream/.test(contentType)
276
+ ? text
277
+ .split("\n")
278
+ .filter((l) => l.startsWith("data:"))
279
+ .map((l) => l.slice(5).trim())
280
+ : [text];
281
+ for (const c of candidates) {
282
+ const parsed = parseJson(c);
283
+ const msg = asRecord(parsed.ok ? parsed.value : null);
284
+ if (msg.id === id) return msg;
285
+ }
286
+ throw new TrackerError("http-200", "jira: no JSON-RPC answer in the response");
287
+ }
288
+
289
+ /** A Jira tool error's reason, from its text. */
290
+ function jiraReason(text: string): FailureReason {
291
+ if (/does not exist|not found|no issue/i.test(text)) return "not-found";
292
+ if (/rate limit|too many/i.test(text)) return "rate-limit";
293
+ if (/unauthori[sz]ed|authenticat/i.test(text)) return "auth";
294
+ if (/permission|forbidden|scope/i.test(text)) return "scope";
295
+ return "http-400";
296
+ }
297
+
298
+ export class JiraSession {
299
+ private id = 1;
300
+ private session: string | null = null;
301
+ constructor(private readonly key: string) {}
302
+
303
+ static open(): JiraSession {
304
+ return new JiraSession(secret("BKIT_JIRA_API_KEY"));
305
+ }
306
+
307
+ private headers(): Record<string, string> {
308
+ return {
309
+ authorization: `Bearer ${this.key}`,
310
+ accept: "application/json, text/event-stream",
311
+ ...(this.session ? { "mcp-session-id": this.session } : {}),
312
+ };
313
+ }
314
+
315
+ private async start(): Promise<void> {
316
+ 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" },
325
+ },
326
+ });
327
+ rpcMessage(res.text, res.headers.get("content-type") ?? "", this.id);
328
+ 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
+ });
333
+ }
334
+
335
+ /** `tools/call` one tool; returns its text content parsed as JSON when it is JSON. */
336
+ async call(name: string, args: Record<string, unknown>): Promise<unknown> {
337
+ await this.start();
338
+ 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
+ });
345
+ const msg = rpcMessage(res.text, res.headers.get("content-type") ?? "", id);
346
+ if (msg.error) {
347
+ const message = String(asRecord(msg.error).message ?? "");
348
+ throw new TrackerError(jiraReason(message), `jira ${name}: ${message}`);
349
+ }
350
+ const result = asRecord(msg.result);
351
+ const content = Array.isArray(result.content) ? (result.content as unknown[]) : [];
352
+ const text = content
353
+ .map((c) => asRecord(c))
354
+ .filter((c) => c.type === "text")
355
+ .map((c) => String(c.text ?? ""))
356
+ .join("\n");
357
+ if (result.isError === true) throw new TrackerError(jiraReason(text), `jira ${name}: ${text}`);
358
+ const parsed = parseJson(text);
359
+ return parsed.ok ? parsed.value : text;
360
+ }
361
+ }
362
+
363
+ function jiraSite(t: TrackerTarget): string {
364
+ if (!t.jiraSite) throw new TrackerError("not-found", "bkit.tracker.jira.site is not set");
365
+ return t.jiraSite;
366
+ }
367
+
368
+ // ---------------------------------------------------------------------------
369
+ // comments
370
+ // ---------------------------------------------------------------------------
371
+
372
+ /** First line of every comment bkit posts; such comments are never workflow input. */
373
+ export const GENERATED_MARKER = "###### bkit:generated";
374
+
375
+ /** The 12-hex sha256 prefix a stamped marker carries for `rest`, the body below it. */
376
+ const markerHash = (rest: string): string => actionHash(rest).slice(0, 12);
377
+
378
+ /**
379
+ * `body` with a bare first-line marker stamped `###### bkit:generated {hash}`, the
380
+ * hash of everything below it; any other body unchanged.
381
+ */
382
+ export function stampMarker(body: string): string {
383
+ const nl = body.indexOf("\n");
384
+ if ((nl === -1 ? body : body.slice(0, nl)) !== GENERATED_MARKER) return body;
385
+ const rest = nl === -1 ? "" : body.slice(nl + 1);
386
+ return `${GENERATED_MARKER} ${markerHash(rest)}${nl === -1 ? "" : `\n${rest}`}`;
387
+ }
388
+
389
+ /** The hash a comment's first-line marker carries, as markdown or as Jira's HTML `<h6>`; null without one. */
390
+ export function markerHashOf(body: string): string | null {
391
+ const first = body.replace(/^\s+/, "").split(/\r?\n/, 1)[0] ?? "";
392
+ return (
393
+ /^(?:######[ \t]+|<h6\b[^>]*>\s*)bkit:generated[ \t]+([0-9a-f]{12})\b/.exec(first)?.[1] ?? null
394
+ );
395
+ }
396
+
397
+ /**
398
+ * Write `body` byte-for-byte to `tmp/bkit-{kind}-{hash}.md` in the checkout `cwd`
399
+ * sits in, for an MCP fallback to read verbatim; returns the absolute path.
400
+ */
401
+ export function writeBodyFile(cwd: string, kind: "comment" | "pr-body", body: string): string {
402
+ const top = git(cwd, ["rev-parse", "--show-toplevel"]) ?? cwd;
403
+ const file = path.join(top, "tmp", `bkit-${kind}-${actionHash(body).slice(0, 12)}.md`);
404
+ fs.mkdirSync(path.dirname(file), { recursive: true });
405
+ fs.writeFileSync(file, body);
406
+ return file;
407
+ }
408
+
409
+ /**
410
+ * `body` cut at line breaks into parts of at most `limit` characters. Each part of
411
+ * a split body opens with the body's first line when it is the generated marker,
412
+ * then `_(part i/n)_`; a single line longer than a part is cut hard.
413
+ */
414
+ export function splitAt(body: string, limit: number): string[] {
415
+ if (body.length <= limit) return [body];
416
+ const lines = body.split("\n");
417
+ 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);
432
+ }
433
+ const next = cur === "" ? line : `${cur}\n${line}`;
434
+ if (next.length > room) {
435
+ flush();
436
+ cur = line;
437
+ } else cur = next;
438
+ }
439
+ flush();
440
+ return chunks.map((c, i) =>
441
+ [...(marker ? [marker] : []), `_(part ${i + 1}/${chunks.length})_`, c].join("\n"),
442
+ );
443
+ }
444
+
445
+ export interface PostedComment {
446
+ url: string | null;
447
+ /** How many comments the body went out as (Jira splits long bodies). */
448
+ parts: number;
449
+ }
450
+
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> {
453
+ if (t.issue === null) throw new TrackerError("not-found", "no issue");
454
+ if (t.tracker === "github") {
455
+ const out = gh(
456
+ t,
457
+ [
458
+ "api",
459
+ `repos/${t.ownerRepo}/issues/${t.issue}/comments`,
460
+ "--method",
461
+ "POST",
462
+ "--input",
463
+ "-",
464
+ ],
465
+ JSON.stringify({ body }),
466
+ );
467
+ 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 };
470
+ }
471
+ if (t.tracker === "linear") {
472
+ const data = await linearGql(
473
+ "mutation($input: CommentCreateInput!) { commentCreate(input: $input) { success comment { url } } }",
474
+ { input: { issueId: t.issue, body } },
475
+ );
476
+ const created = asRecord(data.commentCreate);
477
+ 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 };
481
+ }
482
+ if (t.tracker === "jira") {
483
+ const site = jiraSite(t);
484
+ const jira = JiraSession.open();
485
+ const parts = splitAt(body, JIRA_COMMENT_LIMIT);
486
+ let id: unknown;
487
+ 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;
494
+ }
495
+ const base = `${site}/browse/${t.issue}`;
496
+ return {
497
+ url: id === undefined ? base : `${base}?focusedCommentId=${String(id)}`,
498
+ parts: parts.length,
499
+ };
500
+ }
501
+ throw new TrackerError("not-found", "issue tracker none");
502
+ }
503
+
504
+ /** The issue's latest `n` comments (body + url), newest last. */
505
+ export async function recentComments(
506
+ t: TrackerTarget,
507
+ n: number,
508
+ ): Promise<Array<{ body: string; url: string | null }>> {
509
+ if (t.issue === null) return [];
510
+ if (t.tracker === "github") {
511
+ 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) => {
530
+ const r = asRecord(c);
531
+ return { body: String(r.body ?? ""), url: typeof r.url === "string" ? r.url : null };
532
+ });
533
+ }
534
+ const issue = await fetchIssue(t);
535
+ return issue.comments.slice(-n).map((c) => ({ body: c.body, url: null }));
536
+ }
537
+
538
+ export interface FetchedIssue {
539
+ title: string;
540
+ url: string;
541
+ state: string;
542
+ labels: string[];
543
+ /** The description, raw. */
544
+ body: string;
545
+ /** In the order the tracker returned them; callers sort. */
546
+ comments: Array<{ body: string; createdAt?: string }>;
547
+ }
548
+
549
+ const str = (v: unknown): string => (typeof v === "string" ? v : "");
550
+
551
+ // ADF nodes whose children are inline text; every other node's children are blocks, one per line.
552
+ const ADF_INLINE = new Set(["paragraph", "heading", "codeBlock", "mediaSingle"]);
553
+
554
+ /** An Atlassian Document Format node as text: headings as `#` lines, blocks one per line. */
555
+ function adfText(node: unknown): string {
556
+ if (typeof node === "string") return node;
557
+ const n = asRecord(node);
558
+ if (n.type === "text") return str(n.text);
559
+ if (n.type === "hardBreak") return "\n";
560
+ const children = Array.isArray(n.content) ? n.content.map(adfText) : [];
561
+ if (!ADF_INLINE.has(str(n.type))) return children.join("\n");
562
+ const text = children.join("");
563
+ if (n.type !== "heading") return text;
564
+ const level = Math.min(6, Math.max(1, Number(asRecord(n.attrs).level) || 1));
565
+ return `${"#".repeat(level)} ${text}`;
566
+ }
567
+
568
+ /** A tracker text field as a string: a string verbatim, a document node (ADF) as its text. */
569
+ const textOf = (v: unknown): string =>
570
+ typeof v === "string" ? v : v === null || v === undefined ? "" : adfText(v);
571
+
572
+ const commentOf = (raw: unknown, at: string) => {
573
+ const r = asRecord(raw);
574
+ const created = r[at];
575
+ return {
576
+ body: textOf(r.body),
577
+ ...(typeof created === "string" ? { createdAt: created } : {}),
578
+ };
579
+ };
580
+
581
+ /** The issue's facts, description and every comment. Throws `TrackerError` on failure. */
582
+ export async function fetchIssue(t: TrackerTarget): Promise<FetchedIssue> {
583
+ if (t.issue === null) throw new TrackerError("not-found", "no issue");
584
+ if (t.tracker === "github") {
585
+ const parsed = parseJson(gh(t, ["api", `repos/${t.ownerRepo}/issues/${t.issue}`]));
586
+ const issue = asRecord(parsed.ok ? parsed.value : null);
587
+ const lines = gh(t, [
588
+ "api",
589
+ "--paginate",
590
+ `repos/${t.ownerRepo}/issues/${t.issue}/comments?per_page=100`,
591
+ "--jq",
592
+ ".[] | {body, created_at}",
593
+ ]);
594
+ const comments = lines
595
+ .split("\n")
596
+ .filter((l) => l.trim() !== "")
597
+ .map((l) => {
598
+ const c = parseJson(l);
599
+ return commentOf(c.ok ? c.value : null, "created_at");
600
+ });
601
+ return {
602
+ title: str(issue.title),
603
+ url: str(issue.html_url),
604
+ state: str(issue.state),
605
+ labels: (Array.isArray(issue.labels) ? issue.labels : []).map((l) =>
606
+ typeof l === "string" ? l : str(asRecord(l).name),
607
+ ),
608
+ body: str(issue.body),
609
+ comments,
610
+ };
611
+ }
612
+ if (t.tracker === "linear") {
613
+ const page = "nodes { body createdAt } pageInfo { hasNextPage endCursor }";
614
+ const data = await linearGql(
615
+ `query($id: String!) { issue(id: $id) { identifier title url description state { name } labels { nodes { name } } comments(first: 250) { ${page} } } }`,
616
+ { id: t.issue },
617
+ );
618
+ const issue = asRecord(data.issue);
619
+ if (!data.issue) throw new TrackerError("not-found", `linear: ${t.issue} not found`);
620
+ const nodes = (o: unknown) => {
621
+ const n = asRecord(o).nodes;
622
+ return Array.isArray(n) ? n : [];
623
+ };
624
+ const comments = nodes(issue.comments).map((c) => commentOf(c, "createdAt"));
625
+ for (let info = asRecord(asRecord(issue.comments).pageInfo); info.hasNextPage === true;) {
626
+ const next = await linearGql(
627
+ `query($id: String!, $after: String!) { issue(id: $id) { comments(first: 250, after: $after) { ${page} } } }`,
628
+ { id: t.issue, after: str(info.endCursor) },
629
+ );
630
+ const more = asRecord(asRecord(next.issue).comments);
631
+ const list = nodes(more);
632
+ comments.push(...list.map((c) => commentOf(c, "createdAt")));
633
+ info = list.length === 0 ? {} : asRecord(more.pageInfo);
634
+ }
635
+ return {
636
+ title: str(issue.title),
637
+ url: str(issue.url),
638
+ state: str(asRecord(issue.state).name),
639
+ labels: nodes(issue.labels).map((l) => str(asRecord(l).name)),
640
+ body: str(issue.description),
641
+ comments,
642
+ };
643
+ }
644
+ if (t.tracker === "jira") {
645
+ const site = jiraSite(t);
646
+ const jira = JiraSession.open();
647
+ const raw = asRecord(
648
+ await jira.call(JIRA_TOOLS.getIssue, {
649
+ cloudId: site,
650
+ issueIdOrKey: t.issue,
651
+ view: "evidence",
652
+ }),
653
+ );
654
+ const fields = asRecord(raw.fields);
655
+ const description = fields.description;
656
+ const comments: FetchedIssue["comments"] = [];
657
+ for (let startAt = 0; ;) {
658
+ const page = asRecord(
659
+ await jira.call(JIRA_TOOLS.read, {
660
+ cloudId: site,
661
+ name: JIRA_TOOLS.comments,
662
+ inputs: { issueIdOrKey: t.issue, maxResults: 100, startAt },
663
+ }),
664
+ );
665
+ const list = Array.isArray(page.comments) ? page.comments : [];
666
+ if (page.appliedContentFormat === "html") {
667
+ // One comment Jira cannot express as markdown turns its whole page HTML; read
668
+ // alone, every other comment on it comes back as markdown.
669
+ for (const [i, c] of list.entries()) {
670
+ const one = asRecord(
671
+ await jira.call(JIRA_TOOLS.read, {
672
+ cloudId: site,
673
+ name: JIRA_TOOLS.comments,
674
+ inputs: { issueIdOrKey: t.issue, maxResults: 1, startAt: startAt + i },
675
+ }),
676
+ );
677
+ const alone = Array.isArray(one.comments) ? one.comments[0] : undefined;
678
+ comments.push(commentOf(alone ?? c, "created"));
679
+ }
680
+ } else comments.push(...list.map((c) => commentOf(c, "created")));
681
+ if (page.isLast !== false || list.length === 0) break;
682
+ startAt += list.length;
683
+ }
684
+ return {
685
+ title: str(fields.summary),
686
+ url: `${site}/browse/${t.issue}`,
687
+ state: str(asRecord(fields.status).name),
688
+ labels: (Array.isArray(fields.labels) ? fields.labels : []).map((l) => String(l)),
689
+ body: textOf(description),
690
+ comments,
691
+ };
692
+ }
693
+ throw new TrackerError("not-found", "issue tracker none");
694
+ }
695
+
696
+ // ---------------------------------------------------------------------------
697
+ // labels, state and board
698
+ // ---------------------------------------------------------------------------
699
+
700
+ /** The issue's current label names. Throws `TrackerError` on failure. */
701
+ export async function readLabels(t: TrackerTarget): Promise<string[]> {
702
+ if (t.issue === null) throw new TrackerError("not-found", "no issue");
703
+ if (t.tracker === "github") {
704
+ const out = gh(t, [
705
+ "api",
706
+ `repos/${t.ownerRepo}/issues/${t.issue}`,
707
+ "--jq",
708
+ "[.labels[].name]",
709
+ ]);
710
+ const parsed = parseJson(out);
711
+ const names = parsed.ok ? parsed.value : null;
712
+ return Array.isArray(names) ? names.map((n) => String(n)) : [];
713
+ }
714
+ if (t.tracker === "linear") {
715
+ const data = await linearGql(
716
+ "query($id: String!) { issue(id: $id) { labels { nodes { name } } } }",
717
+ {
718
+ id: t.issue,
719
+ },
720
+ );
721
+ if (!data.issue) throw new TrackerError("not-found", `linear: ${t.issue} not found`);
722
+ const nodes = asRecord(asRecord(data.issue).labels).nodes;
723
+ return (Array.isArray(nodes) ? nodes : []).map((n) => str(asRecord(n).name));
724
+ }
725
+ if (t.tracker === "jira") {
726
+ const raw = asRecord(
727
+ await JiraSession.open().call(JIRA_TOOLS.getIssue, {
728
+ cloudId: jiraSite(t),
729
+ issueIdOrKey: t.issue,
730
+ view: "evidence",
731
+ }),
732
+ );
733
+ const labels = asRecord(raw.fields).labels;
734
+ return (Array.isArray(labels) ? labels : []).map((l) => String(l));
735
+ }
736
+ throw new TrackerError("not-found", "issue tracker none");
737
+ }
738
+
739
+ export interface LabelWrite {
740
+ add: string[];
741
+ remove: string[];
742
+ /** The full set after the write (Jira replaces the whole set). */
743
+ labels: string[];
744
+ /** Linear / Jira state name to move to, or null. */
745
+ state: string | null;
746
+ }
747
+
748
+ /**
749
+ * Write a label transition (and, on Linear / Jira, the state). Labels land before
750
+ * the state: a state name the team or project lacks throws after them, with the
751
+ * labels written. Throws `TrackerError` on failure.
752
+ */
753
+ export async function writeLabels(t: TrackerTarget, w: LabelWrite): Promise<void> {
754
+ if (t.issue === null) throw new TrackerError("not-found", "no issue");
755
+ if (t.tracker === "github") {
756
+ const base = `repos/${t.ownerRepo}/issues/${t.issue}/labels`;
757
+ if (w.add.length > 0)
758
+ gh(t, ["api", base, "--method", "POST", "--input", "-"], JSON.stringify({ labels: w.add }));
759
+ for (const l of w.remove)
760
+ gh(t, ["api", `${base}/${encodeURIComponent(l)}`, "--method", "DELETE"]);
761
+ return;
762
+ }
763
+ if (t.tracker === "linear") {
764
+ const data = await linearGql(
765
+ "query($id: String!, $names: [String!]!) { issue(id: $id) { id team { id states { nodes { id name } } } } issueLabels(first: 250, filter: { name: { in: $names } }) { nodes { id name team { id } } } }",
766
+ { id: t.issue, names: [...w.add, ...w.remove] },
767
+ );
768
+ const issue = asRecord(data.issue);
769
+ if (!data.issue) throw new TrackerError("not-found", `linear: ${t.issue} not found`);
770
+ const team = asRecord(issue.team);
771
+ const teamId = str(team.id);
772
+ const known = (
773
+ Array.isArray(asRecord(data.issueLabels).nodes)
774
+ ? (asRecord(data.issueLabels).nodes as unknown[])
775
+ : []
776
+ )
777
+ .map((n) => asRecord(n))
778
+ // A team's own label wins over a workspace label of the same name.
779
+ .filter((n) => n.team === null || n.team === undefined || str(asRecord(n.team).id) === teamId)
780
+ .sort((a, b) => Number(Boolean(b.team)) - Number(Boolean(a.team)));
781
+ const idOf = (name: string) => known.find((n) => n.name === name)?.id as string | undefined;
782
+ const added: string[] = [];
783
+ for (const name of w.add) {
784
+ const id = idOf(name);
785
+ if (id) {
786
+ added.push(id);
787
+ continue;
788
+ }
789
+ const created = asRecord(
790
+ (
791
+ await linearGql(
792
+ "mutation($input: IssueLabelCreateInput!) { issueLabelCreate(input: $input) { success issueLabel { id } } }",
793
+ { input: { name, teamId } },
794
+ )
795
+ ).issueLabelCreate,
796
+ );
797
+ added.push(str(asRecord(created.issueLabel).id));
798
+ }
799
+ const removed = w.remove.map(idOf).filter((id): id is string => Boolean(id));
800
+ if (added.length + removed.length > 0) {
801
+ await linearGql(
802
+ "mutation($id: String!, $input: IssueUpdateInput!) { issueUpdate(id: $id, input: $input) { success } }",
803
+ { id: str(issue.id) || t.issue, input: { addedLabelIds: added, removedLabelIds: removed } },
804
+ );
805
+ }
806
+ if (w.state !== null) {
807
+ const states = asRecord(team.states).nodes;
808
+ const state = (Array.isArray(states) ? states : [])
809
+ .map((s) => asRecord(s))
810
+ .find((s) => s.name === w.state);
811
+ if (!state) throw new TrackerError("not-found", `linear: no state "${w.state}"`);
812
+ await linearGql(
813
+ "mutation($id: String!, $input: IssueUpdateInput!) { issueUpdate(id: $id, input: $input) { success } }",
814
+ { id: str(issue.id) || t.issue, input: { stateId: str(state.id) } },
815
+ );
816
+ }
817
+ return;
818
+ }
819
+ if (t.tracker === "jira") {
820
+ const site = jiraSite(t);
821
+ const jira = JiraSession.open();
822
+ if (w.add.length + w.remove.length > 0) {
823
+ await jira.call(JIRA_TOOLS.edit, {
824
+ cloudId: site,
825
+ issueIdOrKey: t.issue,
826
+ fields: { labels: w.labels },
827
+ });
828
+ }
829
+ if (w.state !== null) {
830
+ const listed = asRecord(
831
+ await jira.call(JIRA_TOOLS.read, {
832
+ cloudId: site,
833
+ name: JIRA_TOOLS.transitions,
834
+ inputs: { issueIdOrKey: t.issue },
835
+ }),
836
+ );
837
+ const all = Array.isArray(listed.transitions) ? listed.transitions : [];
838
+ const hit = all.map((x) => asRecord(x)).find((x) => asRecord(x.to).name === w.state);
839
+ if (!hit) throw new TrackerError("not-found", `jira: no transition to "${w.state}"`);
840
+ await jira.call(JIRA_TOOLS.transition, {
841
+ cloudId: site,
842
+ issueIdOrKey: t.issue,
843
+ transitionId: String(hit.id),
844
+ });
845
+ }
846
+ return;
847
+ }
848
+ throw new TrackerError("not-found", "issue tracker none");
849
+ }
850
+
851
+ const BLOCKED_START = /^[ \t]*###### bkit:blocked-by start[ \t]*\r?$/;
852
+ const BLOCKED_END = /^[ \t]*###### bkit:blocked-by end[ \t]*\r?$/;
853
+
854
+ /** The `- #N` lines of a body's whole-line `###### bkit:blocked-by start` … `end` block, as numbers. */
855
+ export function parseBlockedBy(body: string): string[] {
856
+ const lines = body.split("\n");
857
+ const start = lines.findIndex((l) => BLOCKED_START.test(l));
858
+ if (start === -1) return [];
859
+ const out: string[] = [];
860
+ for (const line of lines.slice(start + 1)) {
861
+ if (BLOCKED_END.test(line)) break;
862
+ const m = /^[ \t]*[-*][ \t]+#([0-9]+)\b/.exec(line);
863
+ if (m) out.push(m[1]!);
864
+ }
865
+ return out;
866
+ }
867
+
868
+ export interface Blocker {
869
+ /** `#N` on GitHub, the key on Linear / Jira. */
870
+ id: string;
871
+ state: string;
872
+ /** Not closed / done / canceled. */
873
+ open: boolean;
874
+ }
875
+
876
+ /**
877
+ * The issues blocking the target: GitHub from the body's blocked-by block, Linear
878
+ * from `blocks` relations pointing at it, Jira from `is blocked by` links. Throws
879
+ * `TrackerError` on failure.
880
+ */
881
+ export async function readBlockers(t: TrackerTarget): Promise<Blocker[]> {
882
+ if (t.issue === null) throw new TrackerError("not-found", "no issue");
883
+ if (t.tracker === "github") {
884
+ const parsed = parseJson(gh(t, ["api", `repos/${t.ownerRepo}/issues/${t.issue}`]));
885
+ const numbers = parseBlockedBy(str(asRecord(parsed.ok ? parsed.value : null).body));
886
+ return numbers.map((n) => {
887
+ const state = gh(t, ["api", `repos/${t.ownerRepo}/issues/${n}`, "--jq", ".state"]).trim();
888
+ return { id: `#${n}`, state, open: state !== "closed" };
889
+ });
890
+ }
891
+ if (t.tracker === "linear") {
892
+ const data = await linearGql(
893
+ "query($id: String!) { issue(id: $id) { inverseRelations(first: 100) { nodes { type issue { identifier state { name type } } } } } }",
894
+ { id: t.issue },
895
+ );
896
+ if (!data.issue) throw new TrackerError("not-found", `linear: ${t.issue} not found`);
897
+ const nodes = asRecord(asRecord(data.issue).inverseRelations).nodes;
898
+ return (Array.isArray(nodes) ? nodes : [])
899
+ .map((n) => asRecord(n))
900
+ .filter((n) => n.type === "blocks")
901
+ .map((n) => {
902
+ const issue = asRecord(n.issue);
903
+ const state = asRecord(issue.state);
904
+ return {
905
+ id: str(issue.identifier),
906
+ state: str(state.name),
907
+ open: !["completed", "canceled"].includes(str(state.type)),
908
+ };
909
+ });
910
+ }
911
+ if (t.tracker === "jira") {
912
+ const res = asRecord(
913
+ await JiraSession.open().call(JIRA_TOOLS.search, {
914
+ cloudId: jiraSite(t),
915
+ jql: `issue in linkedIssues('${t.issue}', 'is blocked by')`,
916
+ fields: ["status"],
917
+ maxResults: 100,
918
+ }),
919
+ );
920
+ const issues = Array.isArray(res.issues) ? res.issues : [];
921
+ return issues.map((i) => {
922
+ const issue = asRecord(i);
923
+ const status = asRecord(asRecord(issue.fields).status);
924
+ return {
925
+ id: str(issue.key),
926
+ state: str(status.name),
927
+ open: str(asRecord(status.statusCategory).key) !== "done",
928
+ };
929
+ });
930
+ }
931
+ throw new TrackerError("not-found", "issue tracker none");
932
+ }
933
+
934
+ /** A Projects v2 board from `bkit.tracker.github.project`. */
935
+ export interface Board {
936
+ owner: string;
937
+ number: number;
938
+ /** The Status option name to set. */
939
+ status: string;
940
+ }
941
+
942
+ /**
943
+ * Put the issue on the Projects v2 board and set its Status. Adding an item that is
944
+ * already on the board returns that item, so a repeat is harmless. Throws
945
+ * `TrackerError` on failure (a token without `project` scope fails as `scope`).
946
+ */
947
+ export async function moveOnBoard(t: TrackerTarget, b: Board): Promise<void> {
948
+ if (t.issue === null) throw new TrackerError("not-found", "no issue");
949
+ const [owner, name] = t.ownerRepo.split("/");
950
+ const field =
951
+ 'projectV2(number: $p) { id field(name: "Status") { ... on ProjectV2SingleSelectField { id options { id name } } } }';
952
+ const looked = parseJson(
953
+ gh(t, [
954
+ "api",
955
+ "graphql",
956
+ "-f",
957
+ `query=query($o: String!, $r: String!, $n: Int!, $login: String!, $p: Int!) { repository(owner: $o, name: $r) { issue(number: $n) { id } } repositoryOwner(login: $login) { ... on User { ${field} } ... on Organization { ${field} } } }`,
958
+ "-F",
959
+ `o=${owner ?? ""}`,
960
+ "-F",
961
+ `r=${name ?? ""}`,
962
+ "-F",
963
+ `n=${t.issue}`,
964
+ "-F",
965
+ `login=${b.owner}`,
966
+ "-F",
967
+ `p=${b.number}`,
968
+ ]),
969
+ );
970
+ const data = asRecord(asRecord(looked.ok ? looked.value : null).data);
971
+ const issueId = str(asRecord(asRecord(data.repository).issue).id);
972
+ const project = asRecord(asRecord(data.repositoryOwner).projectV2);
973
+ const status = asRecord(project.field);
974
+ const options = Array.isArray(status.options) ? status.options : [];
975
+ const option = options.map((o) => asRecord(o)).find((o) => o.name === b.status);
976
+ if (!issueId || !project.id)
977
+ throw new TrackerError("scope", "github: the issue or the board is not visible to this token");
978
+ if (!status.id || !option)
979
+ throw new TrackerError("not-found", `github: the board has no Status option "${b.status}"`);
980
+ const added = parseJson(
981
+ gh(t, [
982
+ "api",
983
+ "graphql",
984
+ "-f",
985
+ "query=mutation($p: ID!, $c: ID!) { addProjectV2ItemById(input: { projectId: $p, contentId: $c }) { item { id } } }",
986
+ "-F",
987
+ `p=${str(project.id)}`,
988
+ "-F",
989
+ `c=${issueId}`,
990
+ ]),
991
+ );
992
+ const itemId = str(
993
+ asRecord(
994
+ asRecord(asRecord(asRecord(added.ok ? added.value : null).data).addProjectV2ItemById).item,
995
+ ).id,
996
+ );
997
+ if (!itemId) throw new TrackerError("http-200", "github: addProjectV2ItemById returned no item");
998
+ gh(t, [
999
+ "api",
1000
+ "graphql",
1001
+ "-f",
1002
+ "query=mutation($p: ID!, $i: ID!, $f: ID!, $o: String!) { updateProjectV2ItemFieldValue(input: { projectId: $p, itemId: $i, fieldId: $f, value: { singleSelectOptionId: $o } }) { projectV2Item { id } } }",
1003
+ "-F",
1004
+ `p=${str(project.id)}`,
1005
+ "-F",
1006
+ `i=${itemId}`,
1007
+ "-F",
1008
+ `f=${str(status.id)}`,
1009
+ "-F",
1010
+ `o=${str(option.id)}`,
1011
+ ]);
1012
+ }
1013
+
1014
+ // ---------------------------------------------------------------------------
1015
+ // the `tracker` field verbs print
1016
+ // ---------------------------------------------------------------------------
1017
+
1018
+ export type TrackerOutcome =
1019
+ | { done: true; action: string; url: string | null; deduped?: true; warning?: string }
1020
+ | { done: false; action: string; reason: FailureReason }
1021
+ | { skipped: "no-issue" | "tracker-none" };
1022
+
1023
+ /** The skip a target calls for, or null when the action can go ahead. */
1024
+ export function skipOf(t: TrackerTarget): TrackerOutcome | null {
1025
+ if (t.tracker === "none") return { skipped: "tracker-none" };
1026
+ if (t.issue === null) return { skipped: "no-issue" };
1027
+ return null;
1028
+ }
1029
+
1030
+ export interface OnceOptions {
1031
+ /** status.jsonl to record and check the engine-action row in; with `key`. */
1032
+ file?: string;
1033
+ key?: string;
1034
+ /**
1035
+ * Instead of a row: a comment among the issue's last `recent` carrying the same
1036
+ * marker hash counts as done — trackers rewrite markdown and Jira adds part lines,
1037
+ * so the text never compares. A body without a stamped marker compares as text.
1038
+ */
1039
+ recent?: number;
1040
+ /** Where the redacted failure detail goes (stderr). */
1041
+ log: (line: string) => void;
1042
+ }
1043
+
1044
+ /** The latest of `recent` that is `body` posted before: same marker hash, else same text. */
1045
+ function samePosted<T extends { body: string }>(recent: T[], body: string): T | undefined {
1046
+ const hash = markerHashOf(body);
1047
+ return recent
1048
+ .filter((c) => (hash === null ? c.body.trim() === body.trim() : markerHashOf(c.body) === hash))
1049
+ .at(-1);
1050
+ }
1051
+
1052
+ /**
1053
+ * Post `body` once. A recorded engine-action row with the same key and body, or a
1054
+ * recent comment with the same marker hash, is `deduped: true` without posting; a
1055
+ * failure is `done: false` with its reason, never a throw. A row that cannot be
1056
+ * written after a successful post is `done: true` with a `warning`.
1057
+ */
1058
+ export async function postCommentOnce(
1059
+ t: TrackerTarget,
1060
+ body: string,
1061
+ o: OnceOptions,
1062
+ ): Promise<TrackerOutcome> {
1063
+ const skip = skipOf(t);
1064
+ if (skip) return skip;
1065
+ const action = "comment";
1066
+ 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 };
1076
+ }
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) {
1084
+ try {
1085
+ recordAction(o.file, { action, key: o.key, hash, ref: posted.url });
1086
+ } 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 };
1092
+ }
1093
+ }
1094
+ return { done: true, action, url: posted.url };
1095
+ }
1096
+
1097
+ /** Run one tracker write as `action`: `done: true`, or `done: false` with the reason (logged, redacted). */
1098
+ export async function attempt(
1099
+ action: string,
1100
+ log: (line: string) => void,
1101
+ fn: () => Promise<void>,
1102
+ ): Promise<TrackerOutcome> {
1103
+ try {
1104
+ await fn();
1105
+ return { done: true, action, url: null };
1106
+ } catch (err) {
1107
+ const reason = classifyFailure(err);
1108
+ log(redact(`tracker ${action} failed (${reason}): ${(err as Error).message ?? String(err)}`));
1109
+ return { done: false, action, reason };
1110
+ }
1111
+ }
1112
+
1113
+ // ---------------------------------------------------------------------------
1114
+ // verb glue
1115
+ // ---------------------------------------------------------------------------
1116
+
1117
+ /** `--post` on a verb that builds a comment. */
1118
+ export const POST_FLAG: FlagSpec = {
1119
+ name: "post",
1120
+ type: "boolean",
1121
+ help: "post the comment to the run's issue through the engine; prints `tracker`",
1122
+ };
1123
+
1124
+ /** The `tracker` output key's meaning, shared by every `--post` verb. */
1125
+ export const TRACKER_OUTPUT =
1126
+ "with --post: {done: true, action, url, deduped?, warning?} | {done: false, action, reason} (post `commentFile` verbatim via the tracker MCP) | {skipped: no-issue | tracker-none}; absent without --post";
1127
+
1128
+ /** The `commentFile` output key's meaning, shared by every verb that prints a comment. */
1129
+ 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";
1131
+
1132
+ /** How many of the issue's latest comments a re-run checks for the same marker hash. */
1133
+ export const RECENT_COMMENTS = 5;
1134
+
1135
+ /** `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);
1138
+
1139
+ /**
1140
+ * The engine-action key of a comment in `file`'s current run of `workflow` (the
1141
+ * latest run's workflow when omitted); undefined with no status.jsonl or no run.
1142
+ */
1143
+ export function runActionKey(
1144
+ file: string | undefined,
1145
+ workflow: string | undefined,
1146
+ ...parts: Array<string | number | undefined | null>
1147
+ ): string | undefined {
1148
+ return commentKey(file, workflow, runNumber, parts);
1149
+ }
1150
+
1151
+ /**
1152
+ * The same key for the latest run of `workflow` once it has ended (a failure
1153
+ * comment written after the workflow-failed row): that run's number, not the next.
1154
+ */
1155
+ export function endedRunActionKey(
1156
+ file: string | undefined,
1157
+ workflow: string,
1158
+ ...parts: Array<string | number | undefined | null>
1159
+ ): string | undefined {
1160
+ const latest = (runs: WorkflowRun[], name: string) =>
1161
+ runs.filter((r) => r.workflow === name).length;
1162
+ return commentKey(file, workflow, latest, parts);
1163
+ }
1164
+
1165
+ function commentKey(
1166
+ file: string | undefined,
1167
+ workflow: string | undefined,
1168
+ numberOf: (runs: WorkflowRun[], name: string) => number,
1169
+ parts: Array<string | number | undefined | null>,
1170
+ ): string | undefined {
1171
+ if (file === undefined || !fs.existsSync(file)) return undefined;
1172
+ const runs = readRunsLenient(file);
1173
+ const name = workflow ?? runs.at(-1)?.workflow;
1174
+ if (name === undefined) return undefined;
1175
+ const n = numberOf(runs, name);
1176
+ return n === 0 ? undefined : actionKey(name, n, ...parts, "comment");
1177
+ }
1178
+
1179
+ /**
1180
+ * Post `body` for a verb's `--post`: once per key in `file` when both are given,
1181
+ * else once per marker hash among the issue's latest comments.
1182
+ */
1183
+ export function postForVerb(
1184
+ ctx: RunContext,
1185
+ body: string,
1186
+ o: { fid?: string; issue?: string; file?: string; key?: string },
1187
+ ): 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
+ });
1195
+ }