@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
@@ -28,7 +28,10 @@ import {
28
28
  TRACKER_OUTPUT,
29
29
  attempt,
30
30
  classifyFailure,
31
+ commentDiagnostic,
31
32
  commentFileOf,
33
+ commentRunProof,
34
+ endedRunActionKey,
32
35
  fetchIssue,
33
36
  moveOnBoard,
34
37
  postForVerb,
@@ -579,6 +582,210 @@ export function headingAnchor(heading: string): string {
579
582
  .replace(/ /g, "-");
580
583
  }
581
584
 
585
+ // ---------------------------------------------------------------------------
586
+ // Audit result — the one validated shape an audit's report header, ledger rows and
587
+ // tracker comment are all derived from. The agent supplies findings and judgments
588
+ // (status, the prior key it judged the same item, coverage gaps); the engine derives
589
+ // the IDs, the severity totals and the ledger payloads, so none can disagree.
590
+ // ---------------------------------------------------------------------------
591
+
592
+ export const AUDIT_SEVERITIES = ["CRITICAL", "HIGH", "MEDIUM", "LOW"] as const;
593
+ export type AuditSeverity = (typeof AUDIT_SEVERITIES)[number];
594
+
595
+ export interface AuditFinding {
596
+ severity: AuditSeverity;
597
+ title: string;
598
+ /** `path:line`. */
599
+ location: string;
600
+ /** The key of an existing ledger entry the agent judged to be this same item. */
601
+ priorKey?: string;
602
+ }
603
+
604
+ export interface AuditResult {
605
+ slug: string;
606
+ status: "COMPLETE" | "STOPPED";
607
+ report: string | null;
608
+ findings: AuditFinding[];
609
+ /** Coverage the audit could not check, one entry each. */
610
+ notChecked: string[];
611
+ stopped?: string;
612
+ overview?: string;
613
+ issue?: string;
614
+ parent?: string;
615
+ }
616
+
617
+ const AUDIT_RESULT_KEYS = [
618
+ "slug",
619
+ "status",
620
+ "report",
621
+ "findings",
622
+ "notChecked",
623
+ "stopped",
624
+ "overview",
625
+ "issue",
626
+ "parent",
627
+ ];
628
+ const AUDIT_FINDING_KEYS = ["severity", "title", "location", "priorKey"];
629
+
630
+ /** The audit result held in `raw`; throws a CommandError (USAGE) naming the first problem. */
631
+ export function parseAuditResult(raw: unknown): AuditResult {
632
+ const bad = (why: string) => new CommandError(EXIT.USAGE, `audit result: ${why}`);
633
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
634
+ throw bad("must be a JSON object");
635
+ const r = raw as Record<string, unknown>;
636
+ for (const k of Object.keys(r))
637
+ if (!AUDIT_RESULT_KEYS.includes(k))
638
+ throw bad(`unknown field "${k}"; totals, counts and IDs are derived from the findings`);
639
+ if (typeof r["slug"] !== "string" || !/^[a-z0-9-]+$/.test(r["slug"]))
640
+ throw bad("slug must be the template slug (a-z, 0-9, -)");
641
+ if (r["status"] !== "COMPLETE" && r["status"] !== "STOPPED")
642
+ throw bad("status must be COMPLETE or STOPPED");
643
+ const report = r["report"] ?? null;
644
+ if (report !== null && (typeof report !== "string" || report === ""))
645
+ throw bad("report must be a path or null");
646
+ // Header-bound values (`Report:`, `Issue:`, `Parent:`) are one line: a line break would forge
647
+ // header lines or an early verdict cut-off.
648
+ for (const name of ["report", "issue", "parent"])
649
+ if (typeof r[name] === "string" && /[\r\n]/.test(r[name]))
650
+ throw bad(`${name} must be a single line`);
651
+ if (!Array.isArray(r["findings"])) throw bad("findings must be an array");
652
+ const priors = new Set<string>();
653
+ const findings = r["findings"].map((f: unknown, i: number): AuditFinding => {
654
+ const at = `finding ${i + 1}`;
655
+ if (f === null || typeof f !== "object" || Array.isArray(f))
656
+ throw bad(`${at} is not an object`);
657
+ const o = f as Record<string, unknown>;
658
+ for (const k of Object.keys(o))
659
+ if (!AUDIT_FINDING_KEYS.includes(k)) throw bad(`${at} has unknown field "${k}"`);
660
+ if (!AUDIT_SEVERITIES.includes(o["severity"] as AuditSeverity))
661
+ throw bad(`${at} severity must be ${AUDIT_SEVERITIES.join("|")}`);
662
+ if (typeof o["title"] !== "string" || o["title"].trim() === "")
663
+ throw bad(`${at} needs a title`);
664
+ if (typeof o["location"] !== "string" || !/^\S+:\d+$/.test(o["location"]))
665
+ throw bad(`${at} location must be path:line`);
666
+ if (o["priorKey"] !== undefined) {
667
+ if (typeof o["priorKey"] !== "string" || o["priorKey"] === "")
668
+ throw bad(`${at} priorKey must be a non-empty string`);
669
+ if (priors.has(o["priorKey"])) throw bad(`${at} repeats priorKey ${o["priorKey"]}`);
670
+ priors.add(o["priorKey"]);
671
+ }
672
+ return {
673
+ severity: o["severity"] as AuditSeverity,
674
+ title: o["title"].trim(),
675
+ location: o["location"],
676
+ ...(o["priorKey"] === undefined ? {} : { priorKey: o["priorKey"] }),
677
+ };
678
+ });
679
+ const notChecked = r["notChecked"] ?? [];
680
+ if (!Array.isArray(notChecked) || notChecked.some((n) => typeof n !== "string" || n === ""))
681
+ throw bad("notChecked must be an array of non-empty strings");
682
+ const text = (name: string): string | undefined => {
683
+ const v = r[name];
684
+ if (v === undefined) return undefined;
685
+ if (typeof v !== "string") throw bad(`${name} must be text`);
686
+ return v;
687
+ };
688
+ return {
689
+ slug: r["slug"],
690
+ status: r["status"],
691
+ report: report as string | null,
692
+ findings,
693
+ notChecked: notChecked as string[],
694
+ ...(text("stopped") === undefined ? {} : { stopped: text("stopped")! }),
695
+ ...(text("overview") === undefined ? {} : { overview: text("overview")! }),
696
+ ...(text("issue") === undefined ? {} : { issue: text("issue")! }),
697
+ ...(text("parent") === undefined ? {} : { parent: text("parent")! }),
698
+ };
699
+ }
700
+
701
+ /** Findings per severity. */
702
+ export function auditTotals(findings: readonly AuditFinding[]): Record<AuditSeverity, number> {
703
+ return Object.fromEntries(
704
+ AUDIT_SEVERITIES.map((s) => [s, findings.filter((f) => f.severity === s).length]),
705
+ ) as Record<AuditSeverity, number>;
706
+ }
707
+
708
+ /** `CRITICAL 0 · HIGH 1 · MEDIUM 0 · LOW 2`, the Findings header value. */
709
+ export const auditFindingsLine = (totals: Record<AuditSeverity, number>): string =>
710
+ AUDIT_SEVERITIES.map((s) => `${s} ${totals[s]}`).join(" \u00b7 ");
711
+
712
+ const kebab = (text: string) =>
713
+ text
714
+ .toLowerCase()
715
+ .replace(/[^a-z0-9]+/g, "-")
716
+ .replace(/^-+|-+$/g, "")
717
+ .slice(0, 48);
718
+
719
+ export interface AuditEntry extends AuditFinding {
720
+ /** Report-local, stable under reordering: `<slug>-<n>` over the severity/location/title order. */
721
+ id: string;
722
+ /** The ledger key: the judged prior key, else derived from the slug and title and unique in the ledger. */
723
+ key: string;
724
+ }
725
+
726
+ /** A ledger row already holding a key: what finding it records, so a re-render can recognise it. */
727
+ export interface HeldRow {
728
+ summary: string;
729
+ locations: readonly string[];
730
+ }
731
+
732
+ /**
733
+ * The findings in their one deterministic order, each with its ID and ledger key. A held key whose
734
+ * row has the same summary and `file:line` is the same finding and is reused; a held key of a
735
+ * different finding is a collision and gets a suffix.
736
+ */
737
+ export function auditEntries(
738
+ result: AuditResult,
739
+ held: ReadonlyMap<string, HeldRow> = new Map(),
740
+ ): AuditEntry[] {
741
+ const rank = (s: AuditSeverity) => AUDIT_SEVERITIES.indexOf(s);
742
+ const ordered = [...result.findings].sort(
743
+ (a, b) =>
744
+ rank(a.severity) - rank(b.severity) ||
745
+ a.location.localeCompare(b.location) ||
746
+ a.title.localeCompare(b.title) ||
747
+ (a.priorKey ?? "").localeCompare(b.priorKey ?? ""),
748
+ );
749
+ const used = new Set(ordered.flatMap((f) => (f.priorKey === undefined ? [] : [f.priorKey])));
750
+ return ordered.map((f, i) => {
751
+ let key = f.priorKey;
752
+ if (key === undefined) {
753
+ const base = `audit-${result.slug}-${kebab(f.title) || "finding"}`;
754
+ key = base;
755
+ const same = (k: string) => {
756
+ const row = held.get(k);
757
+ return row !== undefined && row.summary === f.title && row.locations.includes(f.location);
758
+ };
759
+ for (let n = 2; used.has(key) || (held.has(key) && !same(key)); n += 1) key = `${base}-${n}`;
760
+ used.add(key);
761
+ }
762
+ return { ...f, id: `${result.slug}-${i + 1}`, key };
763
+ });
764
+ }
765
+
766
+ /** One `failure` ledger payload per finding, ready for `bkit ledgers append`. */
767
+ export function auditLedgerRows(
768
+ result: AuditResult,
769
+ held: ReadonlyMap<string, HeldRow> = new Map(),
770
+ ): Array<Record<string, unknown>> {
771
+ return auditEntries(result, held).map((e) => ({
772
+ kind: "failure",
773
+ key: e.key,
774
+ summary: e.title,
775
+ severity: e.severity,
776
+ description: `${e.title} (${e.location}); audit ${result.slug} finding ${e.id}`,
777
+ status: "OPEN",
778
+ }));
779
+ }
780
+
781
+ /** The comment's header fields: the same Status and Findings the report header carries. */
782
+ export function auditHeaderFields(result: AuditResult): Array<[string, string]> {
783
+ return [
784
+ ["Status", result.status],
785
+ ["Findings", auditFindingsLine(auditTotals(result.findings))],
786
+ ];
787
+ }
788
+
582
789
  const KINDS = ["step", "failure", "handover", "audit"];
583
790
 
584
791
  /** The exact comment body; files (`bodyFile`, `sections`, `stderrFile`, `errorFile`) resolve against `cwd`. */
@@ -675,14 +882,38 @@ export function commentBody(ctx: RunContext): string {
675
882
  if (ctx.flags.groupCount !== undefined && ctx.flags.group === undefined) {
676
883
  throw new CommandError(EXIT.USAGE, "--group-count needs --group");
677
884
  }
885
+ const resultFile = str(ctx.flags.resultFile);
886
+ let audit: AuditResult | undefined;
887
+ if (resultFile !== undefined) {
888
+ if (kind !== "audit") throw new CommandError(EXIT.USAGE, "--result-file needs --kind=audit");
889
+ const parsed = parseJson(readInput(ctx.cwd, resultFile, "result-file"));
890
+ if (!parsed.ok) throw new CommandError(EXIT.USAGE, "--result-file is not JSON");
891
+ audit = parseAuditResult(parsed.value);
892
+ const slug = str(ctx.flags.auditSlug);
893
+ if (slug !== undefined && slug !== audit.slug)
894
+ throw new CommandError(
895
+ EXIT.USAGE,
896
+ `conflict: --audit-slug ${slug} is not the result's slug ${audit.slug}`,
897
+ );
898
+ for (const [name] of headerFields(ctx))
899
+ if (name === "Status" || name === "Findings")
900
+ throw new CommandError(
901
+ EXIT.USAGE,
902
+ `conflict: --field ${name} beside --result-file; the result derives it`,
903
+ );
904
+ }
905
+ const given = (ctx.flags.line as string[] | undefined) ?? [];
678
906
  return buildComment(ctx.cwd, {
679
907
  kind: kind as CommentInput["kind"],
680
- auditSlug: str(ctx.flags.auditSlug),
908
+ auditSlug: audit?.slug ?? str(ctx.flags.auditSlug),
681
909
  workflow: str(ctx.flags.workflow),
682
910
  workflowHeading: ctx.flags.workflowHeading === true,
683
911
  stepNumber: str(ctx.flags.stepNumber),
684
912
  stepTitle: str(ctx.flags.stepTitle),
685
- fields: kind === "step" || kind === "audit" ? headerFields(ctx) : [],
913
+ fields: [
914
+ ...(audit === undefined ? [] : auditHeaderFields(audit)),
915
+ ...(kind === "step" || kind === "audit" ? headerFields(ctx) : []),
916
+ ],
686
917
  subStep: str(ctx.flags.subStep),
687
918
  error: str(ctx.flags.error),
688
919
  errorFile: str(ctx.flags.errorFile),
@@ -694,7 +925,7 @@ export function commentBody(ctx: RunContext): string {
694
925
  runId: str(ctx.flags.runId),
695
926
  artifacts: (ctx.flags.artifact as string[] | undefined) ?? [],
696
927
  ref: str(ctx.flags.ref),
697
- lines: (ctx.flags.line as string[] | undefined) ?? [],
928
+ lines: [...(audit?.report == null ? [] : [`Report: ${audit.report}`]), ...given],
698
929
  bodyFile: str(ctx.flags.bodyFile),
699
930
  sections: (ctx.flags.section as string[] | undefined) ?? [],
700
931
  });
@@ -733,7 +964,13 @@ async function fetchVerb(ctx: RunContext): Promise<number> {
733
964
  comments: path.join(dir, "issue-comments.json"),
734
965
  facts: path.join(dir, "issue-facts.json"),
735
966
  };
736
- const facts = { title: issue.title, url: issue.url, state: issue.state, labels: issue.labels };
967
+ const facts = {
968
+ title: issue.title,
969
+ url: issue.url,
970
+ state: issue.state,
971
+ labels: issue.labels,
972
+ terminal: issue.terminal,
973
+ };
737
974
  fs.mkdirSync(dir, { recursive: true });
738
975
  fs.writeFileSync(files.description, issue.body);
739
976
  const comments = sortOldestFirst(issue.comments).comments;
@@ -854,12 +1091,15 @@ export const issuesCommand: CommandSpec = {
854
1091
  title: "issue title",
855
1092
  url: "issue URL",
856
1093
  state: "tracker state name (GitHub: open | closed)",
857
- labels: "label names",
1094
+ labels: "label names (the bkit-cloud.yml router reads bkit:auto here)",
1095
+ terminal:
1096
+ "true when the tracker's state category is finished (GitHub closed, Linear completed / canceled, Jira done), whatever the state is named",
858
1097
  files:
859
- "{description, comments, facts}: raw description, comments oldest first as JSON, {title, url, state, labels} as JSON",
860
- skipped: "no-issue | tracker-none: nothing read, nothing written",
1098
+ "{description, comments, facts}: raw description, comments oldest first as JSON, {title, url, state, labels, terminal} as JSON",
1099
+ skipped:
1100
+ "no-issue | tracker-none: nothing read, nothing written (the bkit-cloud.yml router reads this as skipped)",
861
1101
  reason:
862
- "exit 80: network | auth | scope | rate-limit | not-found | http-<n>; read the issue via the tracker MCP",
1102
+ "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",
863
1103
  },
864
1104
  exitCodes: {},
865
1105
  run: fetchVerb,
@@ -960,11 +1200,21 @@ export const issuesCommand: CommandSpec = {
960
1200
  },
961
1201
  comment: {
962
1202
  summary:
963
- "The exact body of a ###### bkit:generated step, failure, handover, or audit comment.",
1203
+ "The exact body of a ###### bkit:generated step, failure, handover, or audit comment; workflow steps only, never for ad-hoc comments.",
964
1204
  use: "workflow",
965
1205
  flags: [
966
1206
  { name: "kind", type: "string", help: "step (default) | failure | handover | audit" },
1207
+ {
1208
+ name: "purpose",
1209
+ type: "string",
1210
+ help: "routine | attention | terminal; defaults from kind, never from PR metadata",
1211
+ },
967
1212
  { name: "audit-slug", type: "string", help: "audit: template slug, e.g. security" },
1213
+ {
1214
+ name: "result-file",
1215
+ type: "string",
1216
+ 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",
1217
+ },
968
1218
  { name: "step-number", type: "string", help: "step number in the heading" },
969
1219
  { name: "step-title", type: "string", help: "step title in the heading, e.g. Plan Verify" },
970
1220
  { name: "workflow", type: "string", help: "design | plan | build | debug | ship | auto" },
@@ -1019,6 +1269,11 @@ export const issuesCommand: CommandSpec = {
1019
1269
  help: "failure: captured stderr (last 20 lines kept)",
1020
1270
  },
1021
1271
  POST_FLAG,
1272
+ {
1273
+ name: "session-dir",
1274
+ type: "string",
1275
+ help: "explicit repo info session for fileless workflow progress ownership",
1276
+ },
1022
1277
  { name: "fid", type: "string", help: "with --post: the run's FID (names the issue)" },
1023
1278
  { name: "issue", type: "string", help: "with --post: the issue id (instead of --fid)" },
1024
1279
  {
@@ -1028,17 +1283,53 @@ export const issuesCommand: CommandSpec = {
1028
1283
  },
1029
1284
  ],
1030
1285
  output: {
1031
- comment: "the comment body",
1286
+ comment: "the comment body; null when --post source preparation is unavailable",
1032
1287
  commentFile: COMMENT_FILE_OUTPUT,
1033
1288
  tracker: TRACKER_OUTPUT,
1034
1289
  },
1035
1290
  exitCodes: {
1036
1291
  [EXIT_BAD_INPUT]:
1037
- "a --body-file / --section / --stderr-file / --error-file file is missing",
1292
+ "without --post: a --body-file / --section / --stderr-file / --error-file file is missing",
1038
1293
  },
1039
1294
  run: async (ctx) => {
1040
- const comment = commentBody(ctx);
1041
- const commentFile = commentFileOf(ctx.cwd, comment);
1295
+ const explicitPurpose = str(ctx.flags.purpose);
1296
+ if (
1297
+ explicitPurpose !== undefined &&
1298
+ !["routine", "attention", "terminal"].includes(explicitPurpose)
1299
+ )
1300
+ throw new CommandError(EXIT.USAGE, "--purpose must be routine, attention or terminal");
1301
+ const purpose =
1302
+ explicitPurpose ??
1303
+ (["failure", "handover", "audit"].includes(str(ctx.flags.kind) ?? "step")
1304
+ ? "attention"
1305
+ : "routine");
1306
+ if (commentRunProof(ctx) === null)
1307
+ throw new CommandError(
1308
+ EXIT.USAGE,
1309
+ "bkit issues comment is for workflow steps only; post ordinary comments as plain markdown through the tracker MCP",
1310
+ );
1311
+ let comment: string;
1312
+ try {
1313
+ comment = commentBody(ctx);
1314
+ } catch (err) {
1315
+ if (
1316
+ ctx.flags.post !== true ||
1317
+ (err instanceof CommandError && err.code !== EXIT_BAD_INPUT)
1318
+ )
1319
+ throw err;
1320
+ commentDiagnostic(
1321
+ { cwd: ctx.cwd, workflow: str(ctx.flags.workflow), log: (line) => ctx.log(line) },
1322
+ "[bkit-tracker] comment preparation unavailable; continuing workflow",
1323
+ [],
1324
+ );
1325
+ ctx.emit({
1326
+ comment: null,
1327
+ commentFile: null,
1328
+ tracker: { done: false, action: "comment", reason: "preparation" },
1329
+ });
1330
+ return EXIT.OK;
1331
+ }
1332
+ const commentFile = commentFileOf(ctx.cwd, comment, ctx);
1042
1333
  if (ctx.flags.post !== true) {
1043
1334
  ctx.emit({ comment, commentFile });
1044
1335
  return EXIT.OK;
@@ -1046,18 +1337,22 @@ export const issuesCommand: CommandSpec = {
1046
1337
  const file = str(ctx.flags.file)
1047
1338
  ? path.resolve(ctx.cwd, String(ctx.flags.file))
1048
1339
  : undefined;
1049
- const key = runActionKey(
1050
- file,
1051
- str(ctx.flags.workflow),
1340
+ const keyParts = [
1052
1341
  str(ctx.flags.kind) ?? "step",
1053
1342
  str(ctx.flags.stepNumber),
1054
1343
  str(ctx.flags.subStep),
1055
1344
  str(ctx.flags.attempt),
1056
- );
1345
+ ];
1346
+ const workflow = str(ctx.flags.workflow);
1347
+ const key =
1348
+ purpose === "terminal" && workflow !== undefined
1349
+ ? endedRunActionKey(file, workflow, ...keyParts)
1350
+ : runActionKey(file, workflow, ...keyParts);
1057
1351
  const tracker = await postForVerb(ctx, comment, {
1058
1352
  fid: str(ctx.flags.fid),
1059
1353
  issue: str(ctx.flags.issue),
1060
1354
  ...(key === undefined ? {} : { file, key }),
1355
+ purpose,
1061
1356
  });
1062
1357
  ctx.emit({ comment, commentFile, tracker });
1063
1358
  return EXIT.OK;
@@ -0,0 +1,204 @@
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
+
5
+ import { spawnSync } from "node:child_process";
6
+ import * as fs from "node:fs";
7
+ import * as os from "node:os";
8
+ import * as path from "node:path";
9
+
10
+ import { BKIT_TEST_FILE_SCRIPT } from "../../install/manifest.js";
11
+ import { scriptCommand, testCommand } from "../../shared/package-manager.js";
12
+ import {
13
+ classifyLockOutcome,
14
+ LOCK_STATUS_FILE_ENV,
15
+ type LockOutcome,
16
+ type LockStatus,
17
+ lockStatusFile,
18
+ readLockStatus,
19
+ } from "../lib.js";
20
+
21
+ /** The env var naming the JUnit report path `bkit:test:file` must write. */
22
+ export const REPORT_ENV = "BKIT_TEST_REPORT";
23
+
24
+ /**
25
+ * The environment `runToLog` hands its command: the caller's, plus `env`, without
26
+ * pnpm's silent reporter. `pnpm -s` passes `npm_config_reporter=silent` to every
27
+ * child, which leaves out pnpm's own lines (the script run and its failure exit code);
28
+ * the log is the step's evidence, so it keeps them however bkit was started.
29
+ */
30
+ export function logEnv(base: NodeJS.ProcessEnv, env?: Record<string, string>): NodeJS.ProcessEnv {
31
+ const merged = { ...base, ...env };
32
+ if (merged.npm_config_reporter === "silent") delete merged.npm_config_reporter;
33
+ return merged;
34
+ }
35
+
36
+ /**
37
+ * Run argv with stdout and stderr interleaved into `log` (like `> log 2>&1`): a file path, or
38
+ * an open file descriptor such as 2 to pass the output straight on. `base` is the environment
39
+ * `env` is added to. Exit 127 when the binary is missing; 128 + n when killed by signal n.
40
+ */
41
+ export function runToLog(
42
+ argv: string[],
43
+ cwd: string,
44
+ log: string | number,
45
+ env?: Record<string, string>,
46
+ base: NodeJS.ProcessEnv = process.env,
47
+ ): number {
48
+ if (typeof log === "string") fs.mkdirSync(path.dirname(log), { recursive: true });
49
+ const fd = typeof log === "string" ? fs.openSync(log, "w") : log;
50
+ const protectedArgv = testCommand(argv);
51
+ const res = spawnSync(protectedArgv[0]!, protectedArgv.slice(1), {
52
+ cwd,
53
+ stdio: ["ignore", fd, fd],
54
+ env: logEnv(base, env),
55
+ });
56
+ if (typeof log === "string") fs.closeSync(fd);
57
+ if (res.error) {
58
+ const line = `${argv[0]}: not found on PATH (${res.error.message})\n`;
59
+ if (typeof log === "string") fs.appendFileSync(log, line);
60
+ else fs.writeSync(log, line);
61
+ return 127;
62
+ }
63
+ if (res.status !== null) return res.status;
64
+ return 128 + ((res.signal ? os.constants.signals[res.signal] : undefined) ?? 1);
65
+ }
66
+
67
+ /** One run under the tests lock: its exit code, the lock's status file, and the two read together. */
68
+ export interface LockedRun<Code extends number | null = number> {
69
+ /** The run's exit code; null when a caller in between (git running a pre-push hook) collapsed it. */
70
+ exitCode: Code;
71
+ /** What the lock wrapper wrote to its status file, null when it wrote none. */
72
+ status: LockStatus | null;
73
+ /** `gate` the gate's own result, `lock-wait` the wait gave up, `could-not-run` the lock refused or stopped the run. */
74
+ lock: LockOutcome;
75
+ }
76
+
77
+ /**
78
+ * Hand `run` the environment naming a fresh tests-lock status file, then read and delete that
79
+ * file and classify the run. With `forwardStatusTo`, the file is first copied there, for a
80
+ * caller further out that asked for it.
81
+ */
82
+ export function underTestsLock<Code extends number | null>(
83
+ run: (env: Record<string, string>) => Code,
84
+ forwardStatusTo?: string,
85
+ ): LockedRun<Code> {
86
+ const statusPath = lockStatusFile();
87
+ const exitCode = run({ [LOCK_STATUS_FILE_ENV]: statusPath });
88
+ if (forwardStatusTo && fs.statSync(statusPath, { throwIfNoEntry: false })?.isFile())
89
+ fs.copyFileSync(statusPath, forwardStatusTo);
90
+ const status = readLockStatus(statusPath);
91
+ return { exitCode, status, lock: classifyLockOutcome(exitCode, status) };
92
+ }
93
+
94
+ /**
95
+ * Run a gate under the tests lock with its output in `log` (see `runToLog`): the gate's exit
96
+ * code, the lock's status file, and the lock outcome the two give.
97
+ */
98
+ export function runGateUnderLock(
99
+ argv: string[],
100
+ cwd: string,
101
+ log: string | number,
102
+ env: Record<string, string> = {},
103
+ opts: { base?: NodeJS.ProcessEnv; forwardStatusTo?: string } = {},
104
+ ): LockedRun {
105
+ return underTestsLock(
106
+ (lockEnv) => runToLog(argv, cwd, log, { ...env, ...lockEnv }, opts.base),
107
+ opts.forwardStatusTo,
108
+ );
109
+ }
110
+
111
+ /**
112
+ * The failing plus erroring cases across every `*.xml` under `dir`: `[]` for reports with
113
+ * none, null when there is no report.
114
+ */
115
+ export function reportFailures(dir: string): JunitCase[] | null {
116
+ const xml = (fs.readdirSync(dir, { recursive: true }) as string[]).filter(
117
+ (f) => f.endsWith(".xml") && fs.statSync(path.join(dir, f)).isFile(),
118
+ );
119
+ if (xml.length === 0) return null;
120
+ return xml
121
+ .flatMap((f) => parseJunit(fs.readFileSync(path.join(dir, f), "utf-8")))
122
+ .filter((c) => c.state === "failure" || c.state === "error");
123
+ }
124
+
125
+ export type CaseState = "passed" | "failure" | "error" | "skipped";
126
+ export interface JunitCase {
127
+ name: string;
128
+ state: CaseState;
129
+ /** The case's `classname` attribute, null when absent. */
130
+ classname: string | null;
131
+ /** The case's `file` attribute, null when absent. */
132
+ file: string | null;
133
+ /** The failure element's `message` attribute: the runner's one-line summary. */
134
+ message: string;
135
+ /** The failure element's text: the assertion output, where some runners put the detail. */
136
+ detail: string;
137
+ }
138
+
139
+ const XML_ENTITIES: Record<string, string> = {
140
+ amp: "&",
141
+ lt: "<",
142
+ gt: ">",
143
+ quot: '"',
144
+ apos: "'",
145
+ };
146
+
147
+ function decodeXml(s: string): string {
148
+ return s.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi, (whole, e: string) => {
149
+ if (!e.startsWith("#")) return XML_ENTITIES[e.toLowerCase()] ?? whole;
150
+ const cp = /^#x/i.test(e) ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
151
+ return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : whole;
152
+ });
153
+ }
154
+
155
+ const ATTRS = String.raw`((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)`;
156
+
157
+ function attr(attrs: string, name: string): string | undefined {
158
+ const m = new RegExp(String.raw`\s${name}\s*=\s*(?:"([^"]*)"|'([^']*)')`).exec(attrs);
159
+ return m ? decodeXml(m[1] ?? m[2] ?? "") : undefined;
160
+ }
161
+
162
+ /** CDATA text as escaped character data, so a tag inside it never ends an element early. */
163
+ const escapeCdata = (xml: string) =>
164
+ xml.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, (_, text: string) =>
165
+ text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"),
166
+ );
167
+
168
+ /** Every `<testcase>` in a JUnit report: its name, outcome, first failure message and detail. */
169
+ export function parseJunit(xml: string): JunitCase[] {
170
+ const body = escapeCdata(xml).replace(/<!--[\s\S]*?-->/g, "");
171
+ const cases: JunitCase[] = [];
172
+ const testcase = new RegExp(String.raw`<testcase${ATTRS}\s*(?:\/>|>([\s\S]*?)<\/testcase>)`, "g");
173
+ const outcome = new RegExp(
174
+ String.raw`<(failure|error|skipped)${ATTRS}\s*(?:\/>|>([\s\S]*?)<\/\1>)`,
175
+ );
176
+ for (const m of body.matchAll(testcase)) {
177
+ const child = outcome.exec(m[2] ?? "");
178
+ cases.push({
179
+ name: attr(m[1] ?? "", "name") ?? "",
180
+ classname: attr(m[1] ?? "", "classname") ?? null,
181
+ file: attr(m[1] ?? "", "file") ?? null,
182
+ state: child ? (child[1] as CaseState) : "passed",
183
+ message: child ? (attr(child[2] ?? "", "message") ?? "") : "",
184
+ detail: child ? decodeXml((child[3] ?? "").replace(/<[^>]*>/g, "")).trim() : "",
185
+ });
186
+ }
187
+ return cases;
188
+ }
189
+
190
+ /** Run one test file through `bkit:test:file`; the report is read and removed. */
191
+ export function runTestFile(
192
+ top: string,
193
+ test: string,
194
+ log: string,
195
+ ): { exitCode: number; cases: JunitCase[] | null } {
196
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bkit-test-report-"));
197
+ const report = path.join(dir, "junit.xml");
198
+ const exitCode = runToLog([...scriptCommand(BKIT_TEST_FILE_SCRIPT), test], top, log, {
199
+ [REPORT_ENV]: report,
200
+ });
201
+ const cases = fs.existsSync(report) ? parseJunit(fs.readFileSync(report, "utf-8")) : null;
202
+ fs.rmSync(dir, { recursive: true, force: true });
203
+ return { exitCode, cases };
204
+ }