@cbartens/bkit 6.1.1 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (313) hide show
  1. package/.bkit/README.md +14 -12
  2. package/.bkit/core/.agents/docs.md +1 -11
  3. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-gateguard.cjs +30 -9
  4. package/.bkit/core/.agents/plugins/bkit/hooks/bkit-guardrails.cjs +25 -27
  5. package/.bkit/core/.agents/rules.md +22 -9
  6. package/.bkit/core/.bkit/README.md +13 -11
  7. package/.bkit/core/.bkit/authoring.md +58 -13
  8. package/.bkit/core/.bkit/cli.md +42 -32
  9. package/.bkit/core/.bkit/cloud.md +93 -30
  10. package/.bkit/core/.bkit/install.md +55 -16
  11. package/.bkit/core/.bkit/jsonl.md +24 -7
  12. package/.bkit/core/.bkit/pipeline.md +8 -8
  13. package/.bkit/core/.bkit/prompts.md +160 -43
  14. package/.bkit/core/.bkit/providers.md +97 -36
  15. package/.bkit/core/.bkit/templates.md +162 -34
  16. package/.bkit/core/.bkit/trackers.md +39 -6
  17. package/.bkit/core/.bkit/workflows.md +344 -136
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +50 -27
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +11 -11
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +13 -8
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +14 -25
  22. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +20 -9
  23. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +8 -8
  24. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +14 -4
  25. package/.bkit/core/.opencode/plugin/bkit-guardrails.js +114 -0
  26. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +1 -1
  27. package/.bkit/core/docs/templates/bkit-audit-adoption.md +30 -6
  28. package/.bkit/core/docs/templates/bkit-audit-agents.md +1 -1
  29. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +1 -1
  30. package/.bkit/core/docs/templates/bkit-audit-analytics.md +1 -1
  31. package/.bkit/core/docs/templates/bkit-audit-annotations.md +1 -1
  32. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +1 -1
  33. package/.bkit/core/docs/templates/bkit-audit-app-store.md +1 -1
  34. package/.bkit/core/docs/templates/bkit-audit-architecture.md +1 -1
  35. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +2 -2
  36. package/.bkit/core/docs/templates/bkit-audit-config.md +3 -2
  37. package/.bkit/core/docs/templates/bkit-audit-cost.md +1 -1
  38. package/.bkit/core/docs/templates/bkit-audit-coverage.md +1 -1
  39. package/.bkit/core/docs/templates/bkit-audit-database.md +3 -3
  40. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +1 -1
  41. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +1 -1
  42. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +3 -3
  43. package/.bkit/core/docs/templates/bkit-audit-documentation.md +32 -2
  44. package/.bkit/core/docs/templates/bkit-audit-duplication.md +1 -1
  45. package/.bkit/core/docs/templates/bkit-audit-failures.md +1 -1
  46. package/.bkit/core/docs/templates/bkit-audit-flakes.md +2 -2
  47. package/.bkit/core/docs/templates/bkit-audit-gates.md +5 -3
  48. package/.bkit/core/docs/templates/bkit-audit-issues.md +1 -1
  49. package/.bkit/core/docs/templates/bkit-audit-llm.md +2 -2
  50. package/.bkit/core/docs/templates/bkit-audit-logs.md +1 -1
  51. package/.bkit/core/docs/templates/bkit-audit-models.md +2 -2
  52. package/.bkit/core/docs/templates/bkit-audit-privacy.md +1 -1
  53. package/.bkit/core/docs/templates/bkit-audit-prompts.md +1 -1
  54. package/.bkit/core/docs/templates/bkit-audit-red-team.md +2 -2
  55. package/.bkit/core/docs/templates/bkit-audit-reliability.md +3 -2
  56. package/.bkit/core/docs/templates/bkit-audit-repo.md +1 -1
  57. package/.bkit/core/docs/templates/bkit-audit-security.md +1 -1
  58. package/.bkit/core/docs/templates/bkit-audit-slop.md +1 -1
  59. package/.bkit/core/docs/templates/bkit-audit-testing.md +3 -2
  60. package/.bkit/core/docs/templates/bkit-audit-usability.md +1 -1
  61. package/.bkit/core/docs/templates/bkit-plan.md +38 -8
  62. package/.bkit/core/engine/checks/after/auth.ts +118 -47
  63. package/.bkit/core/engine/checks/after/github.ts +89 -37
  64. package/.bkit/core/engine/checks/after/index.ts +15 -3
  65. package/.bkit/core/engine/checks/after/tools.ts +245 -1
  66. package/.bkit/core/engine/checks/before/files.ts +59 -1
  67. package/.bkit/core/engine/checks/before/index.ts +8 -0
  68. package/.bkit/core/engine/checks/status-holes.ts +20 -26
  69. package/.bkit/core/engine/checks/tips/catalogue.ts +107 -10
  70. package/.bkit/core/engine/checks/tips/detect.ts +36 -3
  71. package/.bkit/core/engine/checks/tips/index.ts +1 -1
  72. package/.bkit/core/engine/cli.ts +13 -13
  73. package/.bkit/core/engine/commands/ci/ci.ts +64 -11
  74. package/.bkit/core/engine/commands/ci/push-gate.ts +101 -43
  75. package/.bkit/core/engine/commands/install/install.ts +28 -25
  76. package/.bkit/core/engine/commands/install/uninstall.ts +42 -30
  77. package/.bkit/core/engine/commands/install/upgrade.ts +14 -2
  78. package/.bkit/core/engine/commands/land.ts +2 -3
  79. package/.bkit/core/engine/commands/lib.ts +394 -39
  80. package/.bkit/core/engine/commands/registry.ts +1 -1
  81. package/.bkit/core/engine/commands/workflow/branches.ts +351 -78
  82. package/.bkit/core/engine/commands/workflow/challenge.ts +63 -14
  83. package/.bkit/core/engine/commands/workflow/context.ts +71 -10
  84. package/.bkit/core/engine/commands/workflow/counters.ts +298 -23
  85. package/.bkit/core/engine/commands/workflow/decisions.ts +260 -125
  86. package/.bkit/core/engine/commands/workflow/disk.ts +2 -1
  87. package/.bkit/core/engine/commands/workflow/feature-base.ts +66 -0
  88. package/.bkit/core/engine/commands/workflow/issues.ts +312 -17
  89. package/.bkit/core/engine/commands/workflow/junit.ts +204 -0
  90. package/.bkit/core/engine/commands/workflow/ledgers.ts +904 -99
  91. package/.bkit/core/engine/commands/workflow/locks.ts +186 -29
  92. package/.bkit/core/engine/commands/workflow/loops.ts +87 -0
  93. package/.bkit/core/engine/commands/workflow/open-decision.ts +251 -0
  94. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +8 -0
  95. package/.bkit/core/engine/commands/workflow/plans.ts +1 -1
  96. package/.bkit/core/engine/commands/workflow/prs.ts +311 -16
  97. package/.bkit/core/engine/commands/workflow/repo.ts +1 -1
  98. package/.bkit/core/engine/commands/workflow/run-facts.ts +6 -0
  99. package/.bkit/core/engine/commands/workflow/runs.ts +877 -174
  100. package/.bkit/core/engine/commands/workflow/runtime.ts +12 -4
  101. package/.bkit/core/engine/commands/workflow/status.ts +324 -11
  102. package/.bkit/core/engine/commands/workflow/step-table.ts +41 -15
  103. package/.bkit/core/engine/commands/workflow/steps.ts +604 -29
  104. package/.bkit/core/engine/commands/workflow/summary-findings.ts +1 -1
  105. package/.bkit/core/engine/commands/workflow/summary.ts +314 -8
  106. package/.bkit/core/engine/commands/workflow/tasks.ts +400 -27
  107. package/.bkit/core/engine/commands/workflow/tests-base.ts +319 -0
  108. package/.bkit/core/engine/commands/workflow/tests-changed.ts +138 -74
  109. package/.bkit/core/engine/commands/workflow/tests-jump.ts +93 -0
  110. package/.bkit/core/engine/commands/workflow/tests.ts +815 -182
  111. package/.bkit/core/engine/commands/workflow/tracker.ts +1134 -137
  112. package/.bkit/core/engine/commands/workflow/workflows.ts +100 -72
  113. package/.bkit/core/engine/commands/workflow/worktrees.ts +421 -57
  114. package/.bkit/core/engine/install/cloud-env.ts +38 -10
  115. package/.bkit/core/engine/install/managed-block.ts +105 -0
  116. package/.bkit/core/engine/install/manifest.ts +7 -1
  117. package/.bkit/core/engine/install/modules/claude.ts +6 -2
  118. package/.bkit/core/engine/install/modules/cloud.ts +84 -95
  119. package/.bkit/core/engine/install/modules/codex.ts +10 -2
  120. package/.bkit/core/engine/install/modules/core.ts +148 -14
  121. package/.bkit/core/engine/install/modules/opencode.ts +18 -23
  122. package/.bkit/core/engine/install/network-allowlist.ts +8 -3
  123. package/.bkit/core/engine/install/project-docs.ts +650 -0
  124. package/.bkit/core/engine/install/template-copies.ts +58 -5
  125. package/.bkit/core/engine/install/write.ts +128 -7
  126. package/.bkit/core/engine/ledgers/journal.ts +18 -10
  127. package/.bkit/core/engine/ledgers/migrate.ts +20 -8
  128. package/.bkit/core/engine/ledgers/status.ts +604 -8
  129. package/.bkit/core/engine/ledgers/telemetry.ts +115 -13
  130. package/.bkit/core/engine/render/trackers.ts +3 -1
  131. package/.bkit/core/engine/shared/package-manager.ts +7 -3
  132. package/.bkit/core/engine/shared/settings.ts +12 -1
  133. package/.bkit/core/engine/shared/text.ts +14 -0
  134. package/.bkit/core/engine/tools/instructions-sources.ts +1 -0
  135. package/.bkit/core/engine/tools/instructions.ts +116 -20
  136. package/.bkit/core/hooks/antigravity-hook.js +20 -4
  137. package/.bkit/core/hooks/gateguard-edit-payload.js +8 -5
  138. package/.bkit/core/hooks/gateguard-engine.js +249 -23
  139. package/.bkit/core/hooks/guardrails-deny.js +167 -0
  140. package/.bkit/core/hooks/guardrails-read.js +3 -3
  141. package/.bkit/core/hooks/guardrails-shell.js +1122 -167
  142. package/.bkit/core/hooks/guardrails-tiers.js +247 -176
  143. package/.bkit/core/hooks/preflight-tracker.sh +219 -0
  144. package/.bkit/core/prompts/bkit-audit-generate.md +23 -6
  145. package/.bkit/core/prompts/bkit-build-challenge-1.md +5 -4
  146. package/.bkit/core/prompts/bkit-build-challenge-2.md +6 -5
  147. package/.bkit/core/prompts/bkit-build-install-skills.md +2 -2
  148. package/.bkit/core/prompts/bkit-build-plan-convert.md +21 -7
  149. package/.bkit/core/prompts/bkit-build-plan-current.md +5 -4
  150. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +22 -17
  151. package/.bkit/core/prompts/bkit-build-plan-tasks.md +16 -12
  152. package/.bkit/core/prompts/bkit-build-plan-tests.md +14 -10
  153. package/.bkit/core/prompts/bkit-build-plan-verify.md +21 -8
  154. package/.bkit/core/prompts/bkit-debug-abort-handover.md +10 -5
  155. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +22 -6
  156. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +19 -3
  157. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +22 -6
  158. package/.bkit/core/prompts/bkit-debug-failure-soak.md +10 -7
  159. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +3 -3
  160. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +4 -4
  161. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +3 -3
  162. package/.bkit/core/prompts/bkit-design-generate.md +6 -4
  163. package/.bkit/core/prompts/bkit-design-organise.md +4 -3
  164. package/.bkit/core/prompts/bkit-design-review-1.md +5 -4
  165. package/.bkit/core/prompts/bkit-design-review-2.md +6 -5
  166. package/.bkit/core/prompts/bkit-design-spike.md +4 -3
  167. package/.bkit/core/prompts/bkit-design-update.md +6 -4
  168. package/.bkit/core/prompts/bkit-plan-generate.md +35 -14
  169. package/.bkit/core/prompts/bkit-plan-review-1.md +9 -7
  170. package/.bkit/core/prompts/bkit-plan-review-2.md +9 -7
  171. package/.bkit/core/prompts/bkit-plan-scope-check.md +8 -6
  172. package/.bkit/core/prompts/bkit-plan-update.md +22 -8
  173. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +11 -8
  174. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +9 -5
  175. package/.bkit/core/prompts/bkit-ship-update-docs.md +26 -4
  176. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +3 -3
  177. package/.bkit/core/prompts/bkit-utility-update-decisions.md +10 -7
  178. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +8 -5
  179. package/.bkit/core/prompts/bkit-utility-update-documentation.md +31 -7
  180. package/.bkit/core/prompts/bkit-utility-update-failures.md +8 -5
  181. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +10 -7
  182. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +4 -4
  183. package/.bkit/core/prompts/bkit-utility-update-tracker.md +4 -4
  184. package/.bkit/core/workflows/bkit-auto.md +23 -11
  185. package/.bkit/core/workflows/bkit-build.md +331 -100
  186. package/.bkit/core/workflows/bkit-debug.md +135 -64
  187. package/.bkit/core/workflows/bkit-design.md +58 -32
  188. package/.bkit/core/workflows/bkit-plan.md +73 -45
  189. package/.bkit/core/workflows/bkit-ship.md +233 -167
  190. package/.bkit/shared/.agents/plugins/bkit/hooks.json +1 -1
  191. package/.bkit/shared/.bkit/.env.example +5 -0
  192. package/.bkit/shared/.claude/bkit-cloud.md +7 -7
  193. package/.bkit/shared/.claude/settings.json +5 -1
  194. package/.bkit/shared/.cursor/bkit-cloud.md +1 -1
  195. package/.bkit/shared/.cursor/hooks.json +1 -1
  196. package/.bkit/shared/.opencode/opencode.json +11 -2
  197. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +27 -0
  198. package/.bkit/templates/.cursor/Dockerfile +7 -7
  199. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +1 -1
  200. package/.bkit/templates/.github/dependabot.yml +5 -0
  201. package/.bkit/templates/.github/renovate.json5 +5 -3
  202. package/.bkit/templates/.github/workflows/bkit-ci.yml +11 -11
  203. package/.bkit/templates/.github/workflows/bkit-cloud.yml +525 -161
  204. package/.bkit/templates/.github/workflows/bkit-renovate.yml +2 -2
  205. package/.bkit/templates/.husky/pre-push +123 -6
  206. package/.bkit/templates/context/bkit-serena.md +1 -1
  207. package/.bkit/templates/docs/architecture.md +98 -0
  208. package/.bkit/templates/docs/capabilities.md +33 -37
  209. package/.bkit/templates/docs/components.md +142 -0
  210. package/.bkit/templates/docs/data-schema.md +87 -0
  211. package/.bkit/{shared → templates}/docs/deployments.md +128 -142
  212. package/.bkit/templates/docs/design.md +117 -0
  213. package/.bkit/templates/docs/noise.md +54 -0
  214. package/.bkit/templates/docs/observability.md +99 -0
  215. package/.bkit/templates/docs/security.md +137 -0
  216. package/.bkit/templates/docs/setup.md +93 -0
  217. package/.bkit/templates/docs/technology.md +70 -0
  218. package/.bkit/{shared → templates}/docs/testing.md +200 -87
  219. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +511 -103
  220. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +228 -35
  221. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +270 -2
  222. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  223. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +92 -63
  224. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +59 -11
  225. package/.bkit/templates/slop-scan.config.json +2 -0
  226. package/CHANGELOG.md +64 -0
  227. package/DETAILS.md +24 -19
  228. package/README.md +1 -1
  229. package/dist/checks/after/auth.js +114 -46
  230. package/dist/checks/after/github.js +77 -35
  231. package/dist/checks/after/index.js +12 -3
  232. package/dist/checks/after/tools.js +224 -1
  233. package/dist/checks/before/files.js +59 -1
  234. package/dist/checks/before/index.js +7 -1
  235. package/dist/checks/status-holes.js +20 -21
  236. package/dist/checks/tips/catalogue.js +99 -10
  237. package/dist/checks/tips/detect.js +35 -3
  238. package/dist/checks/tips/index.js +1 -1
  239. package/dist/cli.js +13 -13
  240. package/dist/commands/ci/ci.js +56 -12
  241. package/dist/commands/ci/push-gate.js +79 -44
  242. package/dist/commands/install/install.js +23 -22
  243. package/dist/commands/install/uninstall.js +36 -30
  244. package/dist/commands/install/upgrade.js +10 -2
  245. package/dist/commands/land.js +2 -3
  246. package/dist/commands/lib.js +323 -25
  247. package/dist/commands/workflow/branches.js +312 -72
  248. package/dist/commands/workflow/challenge.js +66 -13
  249. package/dist/commands/workflow/context.js +46 -10
  250. package/dist/commands/workflow/counters.js +231 -23
  251. package/dist/commands/workflow/decisions.js +221 -106
  252. package/dist/commands/workflow/disk.js +2 -1
  253. package/dist/commands/workflow/feature-base.js +60 -0
  254. package/dist/commands/workflow/issues.js +243 -15
  255. package/dist/commands/workflow/junit.js +137 -0
  256. package/dist/commands/workflow/ledgers.js +726 -112
  257. package/dist/commands/workflow/locks.js +150 -29
  258. package/dist/commands/workflow/loops.js +67 -0
  259. package/dist/commands/workflow/open-decision.js +199 -0
  260. package/dist/commands/workflow/plan-blocks.js +6 -0
  261. package/dist/commands/workflow/plans.js +1 -1
  262. package/dist/commands/workflow/prs.js +272 -16
  263. package/dist/commands/workflow/repo.js +1 -1
  264. package/dist/commands/workflow/run-facts.js +6 -0
  265. package/dist/commands/workflow/runs.js +747 -155
  266. package/dist/commands/workflow/runtime.js +8 -4
  267. package/dist/commands/workflow/status.js +259 -13
  268. package/dist/commands/workflow/step-table.js +41 -15
  269. package/dist/commands/workflow/steps.js +530 -26
  270. package/dist/commands/workflow/summary-findings.js +1 -1
  271. package/dist/commands/workflow/summary.js +289 -8
  272. package/dist/commands/workflow/tasks.js +294 -27
  273. package/dist/commands/workflow/tests-base.js +266 -0
  274. package/dist/commands/workflow/tests-changed.js +130 -56
  275. package/dist/commands/workflow/tests-jump.js +77 -0
  276. package/dist/commands/workflow/tests.js +608 -131
  277. package/dist/commands/workflow/tracker.js +920 -112
  278. package/dist/commands/workflow/workflows.js +80 -59
  279. package/dist/commands/workflow/worktrees.js +387 -58
  280. package/dist/install/cloud-env.js +32 -10
  281. package/dist/install/managed-block.js +101 -0
  282. package/dist/install/manifest.js +7 -1
  283. package/dist/install/modules/claude.js +6 -2
  284. package/dist/install/modules/cloud.js +73 -86
  285. package/dist/install/modules/codex.js +9 -2
  286. package/dist/install/modules/core.js +133 -14
  287. package/dist/install/modules/opencode.js +18 -23
  288. package/dist/install/network-allowlist.js +8 -3
  289. package/dist/install/project-docs.js +551 -0
  290. package/dist/install/template-copies.js +55 -5
  291. package/dist/install/write.js +117 -5
  292. package/dist/ledgers/journal.js +10 -8
  293. package/dist/ledgers/migrate.js +20 -9
  294. package/dist/ledgers/status.js +461 -8
  295. package/dist/ledgers/telemetry.js +71 -13
  296. package/dist/render/trackers.js +3 -1
  297. package/dist/shared/package-manager.js +7 -2
  298. package/dist/shared/settings.js +8 -0
  299. package/dist/shared/text.js +13 -0
  300. package/dist/tools/instructions-sources.js +1 -0
  301. package/dist/tools/instructions.js +97 -24
  302. package/package.json +22 -15
  303. package/.bkit/core/hooks/preflight-linear.sh +0 -73
  304. package/.bkit/shared/docs/architecture.md +0 -16
  305. package/.bkit/shared/docs/data-schema.md +0 -16
  306. package/.bkit/shared/docs/design.md +0 -38
  307. package/.bkit/shared/docs/noise.md +0 -20
  308. package/.bkit/shared/docs/observability.md +0 -22
  309. package/.bkit/shared/docs/security.md +0 -62
  310. package/.bkit/shared/docs/setup.md +0 -52
  311. package/.bkit/shared/docs/technology.md +0 -15
  312. /package/.bkit/templates/{.lintstagedrc.json → lintstagedrc.example.json} +0 -0
  313. /package/.bkit/templates/{.prettierignore → prettierignore.example} +0 -0
@@ -12,7 +12,7 @@ import { CommandError, EXIT, parseJson, repoRoot, } from "../lib.js";
12
12
  import { readBkitConfig } from "../../shared/settings.js";
13
13
  import { str } from "./status.js";
14
14
  import { isCloudOrCi } from "../../checks/before/env.js";
15
- import { COMMENT_FILE_OUTPUT, GENERATED_MARKER, POST_FLAG, TRACKER_OUTPUT, attempt, classifyFailure, commentFileOf, fetchIssue, moveOnBoard, postForVerb, readBlockers, readLabels, redact, runActionKey, skipOf, stampMarker, trackerTarget, writeLabels, } from "./tracker.js";
15
+ import { COMMENT_FILE_OUTPUT, GENERATED_MARKER, POST_FLAG, TRACKER_OUTPUT, attempt, classifyFailure, commentDiagnostic, commentFileOf, commentRunProof, endedRunActionKey, fetchIssue, moveOnBoard, postForVerb, readBlockers, readLabels, redact, runActionKey, skipOf, stampMarker, trackerTarget, writeLabels, } from "./tracker.js";
16
16
  /** Exit code: an input file is missing or not in the expected shape. */
17
17
  export const EXIT_BAD_INPUT = 3;
18
18
  function readInput(cwd, file, flag) {
@@ -457,6 +457,157 @@ export function headingAnchor(heading) {
457
457
  .replace(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, "")
458
458
  .replace(/ /g, "-");
459
459
  }
460
+ // ---------------------------------------------------------------------------
461
+ // Audit result — the one validated shape an audit's report header, ledger rows and
462
+ // tracker comment are all derived from. The agent supplies findings and judgments
463
+ // (status, the prior key it judged the same item, coverage gaps); the engine derives
464
+ // the IDs, the severity totals and the ledger payloads, so none can disagree.
465
+ // ---------------------------------------------------------------------------
466
+ export const AUDIT_SEVERITIES = ["CRITICAL", "HIGH", "MEDIUM", "LOW"];
467
+ const AUDIT_RESULT_KEYS = [
468
+ "slug",
469
+ "status",
470
+ "report",
471
+ "findings",
472
+ "notChecked",
473
+ "stopped",
474
+ "overview",
475
+ "issue",
476
+ "parent",
477
+ ];
478
+ const AUDIT_FINDING_KEYS = ["severity", "title", "location", "priorKey"];
479
+ /** The audit result held in `raw`; throws a CommandError (USAGE) naming the first problem. */
480
+ export function parseAuditResult(raw) {
481
+ const bad = (why) => new CommandError(EXIT.USAGE, `audit result: ${why}`);
482
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
483
+ throw bad("must be a JSON object");
484
+ const r = raw;
485
+ for (const k of Object.keys(r))
486
+ if (!AUDIT_RESULT_KEYS.includes(k))
487
+ throw bad(`unknown field "${k}"; totals, counts and IDs are derived from the findings`);
488
+ if (typeof r["slug"] !== "string" || !/^[a-z0-9-]+$/.test(r["slug"]))
489
+ throw bad("slug must be the template slug (a-z, 0-9, -)");
490
+ if (r["status"] !== "COMPLETE" && r["status"] !== "STOPPED")
491
+ throw bad("status must be COMPLETE or STOPPED");
492
+ const report = r["report"] ?? null;
493
+ if (report !== null && (typeof report !== "string" || report === ""))
494
+ throw bad("report must be a path or null");
495
+ // Header-bound values (`Report:`, `Issue:`, `Parent:`) are one line: a line break would forge
496
+ // header lines or an early verdict cut-off.
497
+ for (const name of ["report", "issue", "parent"])
498
+ if (typeof r[name] === "string" && /[\r\n]/.test(r[name]))
499
+ throw bad(`${name} must be a single line`);
500
+ if (!Array.isArray(r["findings"]))
501
+ throw bad("findings must be an array");
502
+ const priors = new Set();
503
+ const findings = r["findings"].map((f, i) => {
504
+ const at = `finding ${i + 1}`;
505
+ if (f === null || typeof f !== "object" || Array.isArray(f))
506
+ throw bad(`${at} is not an object`);
507
+ const o = f;
508
+ for (const k of Object.keys(o))
509
+ if (!AUDIT_FINDING_KEYS.includes(k))
510
+ throw bad(`${at} has unknown field "${k}"`);
511
+ if (!AUDIT_SEVERITIES.includes(o["severity"]))
512
+ throw bad(`${at} severity must be ${AUDIT_SEVERITIES.join("|")}`);
513
+ if (typeof o["title"] !== "string" || o["title"].trim() === "")
514
+ throw bad(`${at} needs a title`);
515
+ if (typeof o["location"] !== "string" || !/^\S+:\d+$/.test(o["location"]))
516
+ throw bad(`${at} location must be path:line`);
517
+ if (o["priorKey"] !== undefined) {
518
+ if (typeof o["priorKey"] !== "string" || o["priorKey"] === "")
519
+ throw bad(`${at} priorKey must be a non-empty string`);
520
+ if (priors.has(o["priorKey"]))
521
+ throw bad(`${at} repeats priorKey ${o["priorKey"]}`);
522
+ priors.add(o["priorKey"]);
523
+ }
524
+ return {
525
+ severity: o["severity"],
526
+ title: o["title"].trim(),
527
+ location: o["location"],
528
+ ...(o["priorKey"] === undefined ? {} : { priorKey: o["priorKey"] }),
529
+ };
530
+ });
531
+ const notChecked = r["notChecked"] ?? [];
532
+ if (!Array.isArray(notChecked) || notChecked.some((n) => typeof n !== "string" || n === ""))
533
+ throw bad("notChecked must be an array of non-empty strings");
534
+ const text = (name) => {
535
+ const v = r[name];
536
+ if (v === undefined)
537
+ return undefined;
538
+ if (typeof v !== "string")
539
+ throw bad(`${name} must be text`);
540
+ return v;
541
+ };
542
+ return {
543
+ slug: r["slug"],
544
+ status: r["status"],
545
+ report: report,
546
+ findings,
547
+ notChecked: notChecked,
548
+ ...(text("stopped") === undefined ? {} : { stopped: text("stopped") }),
549
+ ...(text("overview") === undefined ? {} : { overview: text("overview") }),
550
+ ...(text("issue") === undefined ? {} : { issue: text("issue") }),
551
+ ...(text("parent") === undefined ? {} : { parent: text("parent") }),
552
+ };
553
+ }
554
+ /** Findings per severity. */
555
+ export function auditTotals(findings) {
556
+ return Object.fromEntries(AUDIT_SEVERITIES.map((s) => [s, findings.filter((f) => f.severity === s).length]));
557
+ }
558
+ /** `CRITICAL 0 · HIGH 1 · MEDIUM 0 · LOW 2`, the Findings header value. */
559
+ export const auditFindingsLine = (totals) => AUDIT_SEVERITIES.map((s) => `${s} ${totals[s]}`).join(" \u00b7 ");
560
+ const kebab = (text) => text
561
+ .toLowerCase()
562
+ .replace(/[^a-z0-9]+/g, "-")
563
+ .replace(/^-+|-+$/g, "")
564
+ .slice(0, 48);
565
+ /**
566
+ * The findings in their one deterministic order, each with its ID and ledger key. A held key whose
567
+ * row has the same summary and `file:line` is the same finding and is reused; a held key of a
568
+ * different finding is a collision and gets a suffix.
569
+ */
570
+ export function auditEntries(result, held = new Map()) {
571
+ const rank = (s) => AUDIT_SEVERITIES.indexOf(s);
572
+ const ordered = [...result.findings].sort((a, b) => rank(a.severity) - rank(b.severity) ||
573
+ a.location.localeCompare(b.location) ||
574
+ a.title.localeCompare(b.title) ||
575
+ (a.priorKey ?? "").localeCompare(b.priorKey ?? ""));
576
+ const used = new Set(ordered.flatMap((f) => (f.priorKey === undefined ? [] : [f.priorKey])));
577
+ return ordered.map((f, i) => {
578
+ let key = f.priorKey;
579
+ if (key === undefined) {
580
+ const base = `audit-${result.slug}-${kebab(f.title) || "finding"}`;
581
+ key = base;
582
+ const same = (k) => {
583
+ const row = held.get(k);
584
+ return row !== undefined && row.summary === f.title && row.locations.includes(f.location);
585
+ };
586
+ for (let n = 2; used.has(key) || (held.has(key) && !same(key)); n += 1)
587
+ key = `${base}-${n}`;
588
+ used.add(key);
589
+ }
590
+ return { ...f, id: `${result.slug}-${i + 1}`, key };
591
+ });
592
+ }
593
+ /** One `failure` ledger payload per finding, ready for `bkit ledgers append`. */
594
+ export function auditLedgerRows(result, held = new Map()) {
595
+ return auditEntries(result, held).map((e) => ({
596
+ kind: "failure",
597
+ key: e.key,
598
+ summary: e.title,
599
+ severity: e.severity,
600
+ description: `${e.title} (${e.location}); audit ${result.slug} finding ${e.id}`,
601
+ status: "OPEN",
602
+ }));
603
+ }
604
+ /** The comment's header fields: the same Status and Findings the report header carries. */
605
+ export function auditHeaderFields(result) {
606
+ return [
607
+ ["Status", result.status],
608
+ ["Findings", auditFindingsLine(auditTotals(result.findings))],
609
+ ];
610
+ }
460
611
  const KINDS = ["step", "failure", "handover", "audit"];
461
612
  /** The exact comment body; files (`bodyFile`, `sections`, `stderrFile`, `errorFile`) resolve against `cwd`. */
462
613
  export function buildComment(cwd, o) {
@@ -534,14 +685,34 @@ export function commentBody(ctx) {
534
685
  if (ctx.flags.groupCount !== undefined && ctx.flags.group === undefined) {
535
686
  throw new CommandError(EXIT.USAGE, "--group-count needs --group");
536
687
  }
688
+ const resultFile = str(ctx.flags.resultFile);
689
+ let audit;
690
+ if (resultFile !== undefined) {
691
+ if (kind !== "audit")
692
+ throw new CommandError(EXIT.USAGE, "--result-file needs --kind=audit");
693
+ const parsed = parseJson(readInput(ctx.cwd, resultFile, "result-file"));
694
+ if (!parsed.ok)
695
+ throw new CommandError(EXIT.USAGE, "--result-file is not JSON");
696
+ audit = parseAuditResult(parsed.value);
697
+ const slug = str(ctx.flags.auditSlug);
698
+ if (slug !== undefined && slug !== audit.slug)
699
+ throw new CommandError(EXIT.USAGE, `conflict: --audit-slug ${slug} is not the result's slug ${audit.slug}`);
700
+ for (const [name] of headerFields(ctx))
701
+ if (name === "Status" || name === "Findings")
702
+ throw new CommandError(EXIT.USAGE, `conflict: --field ${name} beside --result-file; the result derives it`);
703
+ }
704
+ const given = ctx.flags.line ?? [];
537
705
  return buildComment(ctx.cwd, {
538
706
  kind: kind,
539
- auditSlug: str(ctx.flags.auditSlug),
707
+ auditSlug: audit?.slug ?? str(ctx.flags.auditSlug),
540
708
  workflow: str(ctx.flags.workflow),
541
709
  workflowHeading: ctx.flags.workflowHeading === true,
542
710
  stepNumber: str(ctx.flags.stepNumber),
543
711
  stepTitle: str(ctx.flags.stepTitle),
544
- fields: kind === "step" || kind === "audit" ? headerFields(ctx) : [],
712
+ fields: [
713
+ ...(audit === undefined ? [] : auditHeaderFields(audit)),
714
+ ...(kind === "step" || kind === "audit" ? headerFields(ctx) : []),
715
+ ],
545
716
  subStep: str(ctx.flags.subStep),
546
717
  error: str(ctx.flags.error),
547
718
  errorFile: str(ctx.flags.errorFile),
@@ -553,7 +724,7 @@ export function commentBody(ctx) {
553
724
  runId: str(ctx.flags.runId),
554
725
  artifacts: ctx.flags.artifact ?? [],
555
726
  ref: str(ctx.flags.ref),
556
- lines: ctx.flags.line ?? [],
727
+ lines: [...(audit?.report == null ? [] : [`Report: ${audit.report}`]), ...given],
557
728
  bodyFile: str(ctx.flags.bodyFile),
558
729
  sections: ctx.flags.section ?? [],
559
730
  });
@@ -591,7 +762,13 @@ async function fetchVerb(ctx) {
591
762
  comments: path.join(dir, "issue-comments.json"),
592
763
  facts: path.join(dir, "issue-facts.json"),
593
764
  };
594
- const facts = { title: issue.title, url: issue.url, state: issue.state, labels: issue.labels };
765
+ const facts = {
766
+ title: issue.title,
767
+ url: issue.url,
768
+ state: issue.state,
769
+ labels: issue.labels,
770
+ terminal: issue.terminal,
771
+ };
595
772
  fs.mkdirSync(dir, { recursive: true });
596
773
  fs.writeFileSync(files.description, issue.body);
597
774
  const comments = sortOldestFirst(issue.comments).comments;
@@ -708,10 +885,11 @@ export const issuesCommand = {
708
885
  title: "issue title",
709
886
  url: "issue URL",
710
887
  state: "tracker state name (GitHub: open | closed)",
711
- labels: "label names",
712
- files: "{description, comments, facts}: raw description, comments oldest first as JSON, {title, url, state, labels} as JSON",
713
- skipped: "no-issue | tracker-none: nothing read, nothing written",
714
- reason: "exit 80: network | auth | scope | rate-limit | not-found | http-<n>; read the issue via the tracker MCP",
888
+ labels: "label names (the bkit-cloud.yml router reads bkit:auto here)",
889
+ terminal: "true when the tracker's state category is finished (GitHub closed, Linear completed / canceled, Jira done), whatever the state is named",
890
+ files: "{description, comments, facts}: raw description, comments oldest first as JSON, {title, url, state, labels, terminal} as JSON",
891
+ skipped: "no-issue | tracker-none: nothing read, nothing written (the bkit-cloud.yml router reads this as skipped)",
892
+ reason: "exit 80 (the bkit-cloud.yml router fails closed on it): network | auth | scope | rate-limit | not-found | http-<n>; read the issue via the tracker MCP",
715
893
  },
716
894
  exitCodes: {},
717
895
  run: fetchVerb,
@@ -804,11 +982,21 @@ export const issuesCommand = {
804
982
  run: labelsVerb,
805
983
  },
806
984
  comment: {
807
- summary: "The exact body of a ###### bkit:generated step, failure, handover, or audit comment.",
985
+ summary: "The exact body of a ###### bkit:generated step, failure, handover, or audit comment; workflow steps only, never for ad-hoc comments.",
808
986
  use: "workflow",
809
987
  flags: [
810
988
  { name: "kind", type: "string", help: "step (default) | failure | handover | audit" },
989
+ {
990
+ name: "purpose",
991
+ type: "string",
992
+ help: "routine | attention | terminal; defaults from kind, never from PR metadata",
993
+ },
811
994
  { name: "audit-slug", type: "string", help: "audit: template slug, e.g. security" },
995
+ {
996
+ name: "result-file",
997
+ type: "string",
998
+ help: "audit: the structured audit result JSON; derives the Status and Findings fields and the Report line, and refuses a hand-written Status or Findings field",
999
+ },
812
1000
  { name: "step-number", type: "string", help: "step number in the heading" },
813
1001
  { name: "step-title", type: "string", help: "step title in the heading, e.g. Plan Verify" },
814
1002
  { name: "workflow", type: "string", help: "design | plan | build | debug | ship | auto" },
@@ -863,6 +1051,11 @@ export const issuesCommand = {
863
1051
  help: "failure: captured stderr (last 20 lines kept)",
864
1052
  },
865
1053
  POST_FLAG,
1054
+ {
1055
+ name: "session-dir",
1056
+ type: "string",
1057
+ help: "explicit repo info session for fileless workflow progress ownership",
1058
+ },
866
1059
  { name: "fid", type: "string", help: "with --post: the run's FID (names the issue)" },
867
1060
  { name: "issue", type: "string", help: "with --post: the issue id (instead of --fid)" },
868
1061
  {
@@ -872,16 +1065,41 @@ export const issuesCommand = {
872
1065
  },
873
1066
  ],
874
1067
  output: {
875
- comment: "the comment body",
1068
+ comment: "the comment body; null when --post source preparation is unavailable",
876
1069
  commentFile: COMMENT_FILE_OUTPUT,
877
1070
  tracker: TRACKER_OUTPUT,
878
1071
  },
879
1072
  exitCodes: {
880
- [EXIT_BAD_INPUT]: "a --body-file / --section / --stderr-file / --error-file file is missing",
1073
+ [EXIT_BAD_INPUT]: "without --post: a --body-file / --section / --stderr-file / --error-file file is missing",
881
1074
  },
882
1075
  run: async (ctx) => {
883
- const comment = commentBody(ctx);
884
- const commentFile = commentFileOf(ctx.cwd, comment);
1076
+ const explicitPurpose = str(ctx.flags.purpose);
1077
+ if (explicitPurpose !== undefined &&
1078
+ !["routine", "attention", "terminal"].includes(explicitPurpose))
1079
+ throw new CommandError(EXIT.USAGE, "--purpose must be routine, attention or terminal");
1080
+ const purpose = explicitPurpose ??
1081
+ (["failure", "handover", "audit"].includes(str(ctx.flags.kind) ?? "step")
1082
+ ? "attention"
1083
+ : "routine");
1084
+ if (commentRunProof(ctx) === null)
1085
+ throw new CommandError(EXIT.USAGE, "bkit issues comment is for workflow steps only; post ordinary comments as plain markdown through the tracker MCP");
1086
+ let comment;
1087
+ try {
1088
+ comment = commentBody(ctx);
1089
+ }
1090
+ catch (err) {
1091
+ if (ctx.flags.post !== true ||
1092
+ (err instanceof CommandError && err.code !== EXIT_BAD_INPUT))
1093
+ throw err;
1094
+ commentDiagnostic({ cwd: ctx.cwd, workflow: str(ctx.flags.workflow), log: (line) => ctx.log(line) }, "[bkit-tracker] comment preparation unavailable; continuing workflow", []);
1095
+ ctx.emit({
1096
+ comment: null,
1097
+ commentFile: null,
1098
+ tracker: { done: false, action: "comment", reason: "preparation" },
1099
+ });
1100
+ return EXIT.OK;
1101
+ }
1102
+ const commentFile = commentFileOf(ctx.cwd, comment, ctx);
885
1103
  if (ctx.flags.post !== true) {
886
1104
  ctx.emit({ comment, commentFile });
887
1105
  return EXIT.OK;
@@ -889,11 +1107,21 @@ export const issuesCommand = {
889
1107
  const file = str(ctx.flags.file)
890
1108
  ? path.resolve(ctx.cwd, String(ctx.flags.file))
891
1109
  : undefined;
892
- const key = runActionKey(file, str(ctx.flags.workflow), str(ctx.flags.kind) ?? "step", str(ctx.flags.stepNumber), str(ctx.flags.subStep), str(ctx.flags.attempt));
1110
+ const keyParts = [
1111
+ str(ctx.flags.kind) ?? "step",
1112
+ str(ctx.flags.stepNumber),
1113
+ str(ctx.flags.subStep),
1114
+ str(ctx.flags.attempt),
1115
+ ];
1116
+ const workflow = str(ctx.flags.workflow);
1117
+ const key = purpose === "terminal" && workflow !== undefined
1118
+ ? endedRunActionKey(file, workflow, ...keyParts)
1119
+ : runActionKey(file, workflow, ...keyParts);
893
1120
  const tracker = await postForVerb(ctx, comment, {
894
1121
  fid: str(ctx.flags.fid),
895
1122
  issue: str(ctx.flags.issue),
896
1123
  ...(key === undefined ? {} : { file, key }),
1124
+ purpose,
897
1125
  });
898
1126
  ctx.emit({ comment, commentFile, tracker });
899
1127
  return EXIT.OK;
@@ -0,0 +1,137 @@
1
+ // JUnit reading, the one-file test runner and the one gate runner under the tests lock
2
+ // (`runGateUnderLock`, its status-file half `underTestsLock`). A leaf module: it imports none of
3
+ // `tests.ts`, `steps.ts` or `runs.ts`, so any of them may import it.
4
+ import { spawnSync } from "node:child_process";
5
+ import * as fs from "node:fs";
6
+ import * as os from "node:os";
7
+ import * as path from "node:path";
8
+ import { BKIT_TEST_FILE_SCRIPT } from "../../install/manifest.js";
9
+ import { scriptCommand, testCommand } from "../../shared/package-manager.js";
10
+ import { classifyLockOutcome, LOCK_STATUS_FILE_ENV, lockStatusFile, readLockStatus, } from "../lib.js";
11
+ /** The env var naming the JUnit report path `bkit:test:file` must write. */
12
+ export const REPORT_ENV = "BKIT_TEST_REPORT";
13
+ /**
14
+ * The environment `runToLog` hands its command: the caller's, plus `env`, without
15
+ * pnpm's silent reporter. `pnpm -s` passes `npm_config_reporter=silent` to every
16
+ * child, which leaves out pnpm's own lines (the script run and its failure exit code);
17
+ * the log is the step's evidence, so it keeps them however bkit was started.
18
+ */
19
+ export function logEnv(base, env) {
20
+ const merged = { ...base, ...env };
21
+ if (merged.npm_config_reporter === "silent")
22
+ delete merged.npm_config_reporter;
23
+ return merged;
24
+ }
25
+ /**
26
+ * Run argv with stdout and stderr interleaved into `log` (like `> log 2>&1`): a file path, or
27
+ * an open file descriptor such as 2 to pass the output straight on. `base` is the environment
28
+ * `env` is added to. Exit 127 when the binary is missing; 128 + n when killed by signal n.
29
+ */
30
+ export function runToLog(argv, cwd, log, env, base = process.env) {
31
+ if (typeof log === "string")
32
+ fs.mkdirSync(path.dirname(log), { recursive: true });
33
+ const fd = typeof log === "string" ? fs.openSync(log, "w") : log;
34
+ const protectedArgv = testCommand(argv);
35
+ const res = spawnSync(protectedArgv[0], protectedArgv.slice(1), {
36
+ cwd,
37
+ stdio: ["ignore", fd, fd],
38
+ env: logEnv(base, env),
39
+ });
40
+ if (typeof log === "string")
41
+ fs.closeSync(fd);
42
+ if (res.error) {
43
+ const line = `${argv[0]}: not found on PATH (${res.error.message})\n`;
44
+ if (typeof log === "string")
45
+ fs.appendFileSync(log, line);
46
+ else
47
+ fs.writeSync(log, line);
48
+ return 127;
49
+ }
50
+ if (res.status !== null)
51
+ return res.status;
52
+ return 128 + ((res.signal ? os.constants.signals[res.signal] : undefined) ?? 1);
53
+ }
54
+ /**
55
+ * Hand `run` the environment naming a fresh tests-lock status file, then read and delete that
56
+ * file and classify the run. With `forwardStatusTo`, the file is first copied there, for a
57
+ * caller further out that asked for it.
58
+ */
59
+ export function underTestsLock(run, forwardStatusTo) {
60
+ const statusPath = lockStatusFile();
61
+ const exitCode = run({ [LOCK_STATUS_FILE_ENV]: statusPath });
62
+ if (forwardStatusTo && fs.statSync(statusPath, { throwIfNoEntry: false })?.isFile())
63
+ fs.copyFileSync(statusPath, forwardStatusTo);
64
+ const status = readLockStatus(statusPath);
65
+ return { exitCode, status, lock: classifyLockOutcome(exitCode, status) };
66
+ }
67
+ /**
68
+ * Run a gate under the tests lock with its output in `log` (see `runToLog`): the gate's exit
69
+ * code, the lock's status file, and the lock outcome the two give.
70
+ */
71
+ export function runGateUnderLock(argv, cwd, log, env = {}, opts = {}) {
72
+ return underTestsLock((lockEnv) => runToLog(argv, cwd, log, { ...env, ...lockEnv }, opts.base), opts.forwardStatusTo);
73
+ }
74
+ /**
75
+ * The failing plus erroring cases across every `*.xml` under `dir`: `[]` for reports with
76
+ * none, null when there is no report.
77
+ */
78
+ export function reportFailures(dir) {
79
+ const xml = fs.readdirSync(dir, { recursive: true }).filter((f) => f.endsWith(".xml") && fs.statSync(path.join(dir, f)).isFile());
80
+ if (xml.length === 0)
81
+ return null;
82
+ return xml
83
+ .flatMap((f) => parseJunit(fs.readFileSync(path.join(dir, f), "utf-8")))
84
+ .filter((c) => c.state === "failure" || c.state === "error");
85
+ }
86
+ const XML_ENTITIES = {
87
+ amp: "&",
88
+ lt: "<",
89
+ gt: ">",
90
+ quot: '"',
91
+ apos: "'",
92
+ };
93
+ function decodeXml(s) {
94
+ return s.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, e) => {
95
+ if (!e.startsWith("#"))
96
+ return XML_ENTITIES[e.toLowerCase()] ?? whole;
97
+ const cp = /^#x/i.test(e) ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
98
+ return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : whole;
99
+ });
100
+ }
101
+ const ATTRS = String.raw `((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)`;
102
+ function attr(attrs, name) {
103
+ const m = new RegExp(String.raw `\s${name}\s*=\s*(?:"([^"]*)"|'([^']*)')`).exec(attrs);
104
+ return m ? decodeXml(m[1] ?? m[2] ?? "") : undefined;
105
+ }
106
+ /** CDATA text as escaped character data, so a tag inside it never ends an element early. */
107
+ const escapeCdata = (xml) => xml.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, (_, text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"));
108
+ /** Every `<testcase>` in a JUnit report: its name, outcome, first failure message and detail. */
109
+ export function parseJunit(xml) {
110
+ const body = escapeCdata(xml).replace(/<!--[\s\S]*?-->/g, "");
111
+ const cases = [];
112
+ const testcase = new RegExp(String.raw `<testcase${ATTRS}\s*(?:\/>|>([\s\S]*?)<\/testcase>)`, "g");
113
+ const outcome = new RegExp(String.raw `<(failure|error|skipped)${ATTRS}\s*(?:\/>|>([\s\S]*?)<\/\1>)`);
114
+ for (const m of body.matchAll(testcase)) {
115
+ const child = outcome.exec(m[2] ?? "");
116
+ cases.push({
117
+ name: attr(m[1] ?? "", "name") ?? "",
118
+ classname: attr(m[1] ?? "", "classname") ?? null,
119
+ file: attr(m[1] ?? "", "file") ?? null,
120
+ state: child ? child[1] : "passed",
121
+ message: child ? (attr(child[2] ?? "", "message") ?? "") : "",
122
+ detail: child ? decodeXml((child[3] ?? "").replace(/<[^>]*>/g, "")).trim() : "",
123
+ });
124
+ }
125
+ return cases;
126
+ }
127
+ /** Run one test file through `bkit:test:file`; the report is read and removed. */
128
+ export function runTestFile(top, test, log) {
129
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bkit-test-report-"));
130
+ const report = path.join(dir, "junit.xml");
131
+ const exitCode = runToLog([...scriptCommand(BKIT_TEST_FILE_SCRIPT), test], top, log, {
132
+ [REPORT_ENV]: report,
133
+ });
134
+ const cases = fs.existsSync(report) ? parseJunit(fs.readFileSync(report, "utf-8")) : null;
135
+ fs.rmSync(dir, { recursive: true, force: true });
136
+ return { exitCode, cases };
137
+ }