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