@cbartens/bkit 6.1.0 → 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 (317) 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 +43 -33
  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 +99 -36
  15. package/.bkit/core/.bkit/templates.md +167 -37
  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 +161 -37
  64. package/.bkit/core/engine/checks/after/index.ts +18 -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 +124 -19
  74. package/.bkit/core/engine/commands/ci/push-gate.ts +101 -43
  75. package/.bkit/core/engine/commands/install/doctor.ts +5 -5
  76. package/.bkit/core/engine/commands/install/install.ts +28 -25
  77. package/.bkit/core/engine/commands/install/uninstall.ts +42 -30
  78. package/.bkit/core/engine/commands/install/upgrade.ts +14 -2
  79. package/.bkit/core/engine/commands/land.ts +2 -3
  80. package/.bkit/core/engine/commands/lib.ts +394 -39
  81. package/.bkit/core/engine/commands/registry.ts +1 -1
  82. package/.bkit/core/engine/commands/workflow/branches.ts +351 -78
  83. package/.bkit/core/engine/commands/workflow/challenge.ts +63 -14
  84. package/.bkit/core/engine/commands/workflow/context.ts +71 -10
  85. package/.bkit/core/engine/commands/workflow/counters.ts +298 -23
  86. package/.bkit/core/engine/commands/workflow/decisions.ts +260 -125
  87. package/.bkit/core/engine/commands/workflow/disk.ts +2 -1
  88. package/.bkit/core/engine/commands/workflow/feature-base.ts +66 -0
  89. package/.bkit/core/engine/commands/workflow/issues.ts +312 -17
  90. package/.bkit/core/engine/commands/workflow/junit.ts +204 -0
  91. package/.bkit/core/engine/commands/workflow/ledgers.ts +904 -99
  92. package/.bkit/core/engine/commands/workflow/locks.ts +186 -29
  93. package/.bkit/core/engine/commands/workflow/loops.ts +87 -0
  94. package/.bkit/core/engine/commands/workflow/open-decision.ts +251 -0
  95. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +8 -0
  96. package/.bkit/core/engine/commands/workflow/plans.ts +1 -1
  97. package/.bkit/core/engine/commands/workflow/prs.ts +311 -16
  98. package/.bkit/core/engine/commands/workflow/repo.ts +1 -1
  99. package/.bkit/core/engine/commands/workflow/run-facts.ts +6 -0
  100. package/.bkit/core/engine/commands/workflow/runs.ts +877 -174
  101. package/.bkit/core/engine/commands/workflow/runtime.ts +12 -4
  102. package/.bkit/core/engine/commands/workflow/status.ts +324 -11
  103. package/.bkit/core/engine/commands/workflow/step-table.ts +41 -15
  104. package/.bkit/core/engine/commands/workflow/steps.ts +604 -29
  105. package/.bkit/core/engine/commands/workflow/summary-findings.ts +1 -1
  106. package/.bkit/core/engine/commands/workflow/summary.ts +314 -8
  107. package/.bkit/core/engine/commands/workflow/tasks.ts +400 -27
  108. package/.bkit/core/engine/commands/workflow/tests-base.ts +319 -0
  109. package/.bkit/core/engine/commands/workflow/tests-changed.ts +138 -74
  110. package/.bkit/core/engine/commands/workflow/tests-jump.ts +93 -0
  111. package/.bkit/core/engine/commands/workflow/tests.ts +815 -182
  112. package/.bkit/core/engine/commands/workflow/tracker.ts +1134 -137
  113. package/.bkit/core/engine/commands/workflow/workflows.ts +100 -72
  114. package/.bkit/core/engine/commands/workflow/worktrees.ts +421 -57
  115. package/.bkit/core/engine/install/cloud-env.ts +38 -10
  116. package/.bkit/core/engine/install/managed-block.ts +105 -0
  117. package/.bkit/core/engine/install/manifest.ts +7 -1
  118. package/.bkit/core/engine/install/modules/claude.ts +6 -2
  119. package/.bkit/core/engine/install/modules/cloud.ts +84 -95
  120. package/.bkit/core/engine/install/modules/codex.ts +10 -2
  121. package/.bkit/core/engine/install/modules/core.ts +202 -26
  122. package/.bkit/core/engine/install/modules/opencode.ts +18 -23
  123. package/.bkit/core/engine/install/network-allowlist.ts +8 -3
  124. package/.bkit/core/engine/install/project-docs.ts +650 -0
  125. package/.bkit/core/engine/install/template-copies.ts +58 -5
  126. package/.bkit/core/engine/install/write.ts +128 -7
  127. package/.bkit/core/engine/ledgers/journal.ts +18 -10
  128. package/.bkit/core/engine/ledgers/migrate.ts +20 -8
  129. package/.bkit/core/engine/ledgers/status.ts +604 -8
  130. package/.bkit/core/engine/ledgers/telemetry.ts +115 -13
  131. package/.bkit/core/engine/render/trackers.ts +46 -11
  132. package/.bkit/core/engine/shared/package-manager.ts +7 -3
  133. package/.bkit/core/engine/shared/settings.ts +12 -1
  134. package/.bkit/core/engine/shared/text.ts +14 -0
  135. package/.bkit/core/engine/tools/instructions-sources.ts +1 -0
  136. package/.bkit/core/engine/tools/instructions.ts +116 -20
  137. package/.bkit/core/hooks/antigravity-hook.js +20 -4
  138. package/.bkit/core/hooks/gateguard-edit-payload.js +8 -5
  139. package/.bkit/core/hooks/gateguard-engine.js +249 -23
  140. package/.bkit/core/hooks/guardrails-deny.js +167 -0
  141. package/.bkit/core/hooks/guardrails-read.js +3 -3
  142. package/.bkit/core/hooks/guardrails-shell.js +1122 -167
  143. package/.bkit/core/hooks/guardrails-tiers.js +247 -176
  144. package/.bkit/core/hooks/preflight-tracker.sh +219 -0
  145. package/.bkit/core/prompts/bkit-audit-generate.md +23 -6
  146. package/.bkit/core/prompts/bkit-build-challenge-1.md +5 -4
  147. package/.bkit/core/prompts/bkit-build-challenge-2.md +6 -5
  148. package/.bkit/core/prompts/bkit-build-install-skills.md +2 -2
  149. package/.bkit/core/prompts/bkit-build-plan-convert.md +21 -7
  150. package/.bkit/core/prompts/bkit-build-plan-current.md +5 -4
  151. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +22 -17
  152. package/.bkit/core/prompts/bkit-build-plan-tasks.md +16 -12
  153. package/.bkit/core/prompts/bkit-build-plan-tests.md +14 -10
  154. package/.bkit/core/prompts/bkit-build-plan-verify.md +21 -8
  155. package/.bkit/core/prompts/bkit-debug-abort-handover.md +10 -5
  156. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +22 -6
  157. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +19 -3
  158. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +22 -6
  159. package/.bkit/core/prompts/bkit-debug-failure-soak.md +10 -7
  160. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +3 -3
  161. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +4 -4
  162. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +3 -3
  163. package/.bkit/core/prompts/bkit-design-generate.md +6 -4
  164. package/.bkit/core/prompts/bkit-design-organise.md +4 -3
  165. package/.bkit/core/prompts/bkit-design-review-1.md +5 -4
  166. package/.bkit/core/prompts/bkit-design-review-2.md +6 -5
  167. package/.bkit/core/prompts/bkit-design-spike.md +4 -3
  168. package/.bkit/core/prompts/bkit-design-update.md +6 -4
  169. package/.bkit/core/prompts/bkit-plan-generate.md +35 -14
  170. package/.bkit/core/prompts/bkit-plan-review-1.md +9 -7
  171. package/.bkit/core/prompts/bkit-plan-review-2.md +9 -7
  172. package/.bkit/core/prompts/bkit-plan-scope-check.md +8 -6
  173. package/.bkit/core/prompts/bkit-plan-update.md +22 -8
  174. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +11 -8
  175. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +9 -5
  176. package/.bkit/core/prompts/bkit-ship-update-docs.md +26 -4
  177. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +3 -3
  178. package/.bkit/core/prompts/bkit-utility-update-decisions.md +10 -7
  179. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +8 -5
  180. package/.bkit/core/prompts/bkit-utility-update-documentation.md +31 -7
  181. package/.bkit/core/prompts/bkit-utility-update-failures.md +8 -5
  182. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +10 -7
  183. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +4 -4
  184. package/.bkit/core/prompts/bkit-utility-update-tracker.md +4 -4
  185. package/.bkit/core/workflows/bkit-auto.md +23 -11
  186. package/.bkit/core/workflows/bkit-build.md +331 -100
  187. package/.bkit/core/workflows/bkit-debug.md +135 -64
  188. package/.bkit/core/workflows/bkit-design.md +58 -32
  189. package/.bkit/core/workflows/bkit-plan.md +73 -45
  190. package/.bkit/core/workflows/bkit-ship.md +233 -167
  191. package/.bkit/shared/.agents/plugins/bkit/hooks.json +1 -1
  192. package/.bkit/shared/.bkit/.env.example +5 -0
  193. package/.bkit/shared/.claude/bkit-cloud.md +7 -7
  194. package/.bkit/shared/.claude/settings.json +5 -1
  195. package/.bkit/shared/.cursor/bkit-cloud.md +1 -1
  196. package/.bkit/shared/.cursor/hooks.json +1 -1
  197. package/.bkit/shared/.opencode/opencode.json +11 -2
  198. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +27 -0
  199. package/.bkit/templates/.cursor/Dockerfile +7 -7
  200. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-idea.yml +1 -1
  201. package/.bkit/templates/.github/dependabot.yml +5 -0
  202. package/.bkit/templates/.github/renovate.json5 +5 -3
  203. package/.bkit/templates/.github/workflows/bkit-ci.yml +11 -11
  204. package/.bkit/templates/.github/workflows/bkit-cloud.yml +525 -161
  205. package/.bkit/templates/.github/workflows/bkit-renovate.yml +2 -2
  206. package/.bkit/templates/.husky/pre-push +123 -6
  207. package/.bkit/templates/context/bkit-serena.md +1 -1
  208. package/.bkit/templates/context/bkit-vercel.md +103 -59
  209. package/.bkit/templates/docs/architecture.md +98 -0
  210. package/.bkit/templates/docs/capabilities.md +33 -37
  211. package/.bkit/templates/docs/components.md +142 -0
  212. package/.bkit/templates/docs/data-schema.md +87 -0
  213. package/.bkit/{shared → templates}/docs/deployments.md +128 -142
  214. package/.bkit/templates/docs/design.md +117 -0
  215. package/.bkit/templates/docs/noise.md +54 -0
  216. package/.bkit/templates/docs/observability.md +99 -0
  217. package/.bkit/templates/docs/security.md +137 -0
  218. package/.bkit/templates/docs/setup.md +93 -0
  219. package/.bkit/templates/docs/technology.md +70 -0
  220. package/.bkit/{shared → templates}/docs/testing.md +200 -87
  221. package/.bkit/templates/scripts/ci/bkit-check-accepted-divergences.mjs +1 -6
  222. package/.bkit/templates/scripts/ci/bkit-machine-lock.sh +511 -103
  223. package/.bkit/templates/scripts/ci/bkit-test-awake.mjs +314 -28
  224. package/.bkit/templates/scripts/ci/bkit-test-awake.test.mjs +500 -1
  225. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +1 -1
  226. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +91 -62
  227. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +59 -11
  228. package/.bkit/templates/slop-scan.config.json +2 -0
  229. package/CHANGELOG.md +79 -0
  230. package/DETAILS.md +661 -0
  231. package/README.md +73 -604
  232. package/dist/checks/after/auth.js +114 -46
  233. package/dist/checks/after/github.js +138 -35
  234. package/dist/checks/after/index.js +16 -4
  235. package/dist/checks/after/tools.js +224 -1
  236. package/dist/checks/before/files.js +59 -1
  237. package/dist/checks/before/index.js +7 -1
  238. package/dist/checks/status-holes.js +20 -21
  239. package/dist/checks/tips/catalogue.js +99 -10
  240. package/dist/checks/tips/detect.js +35 -3
  241. package/dist/checks/tips/index.js +1 -1
  242. package/dist/cli.js +13 -13
  243. package/dist/commands/ci/ci.js +113 -20
  244. package/dist/commands/ci/push-gate.js +79 -44
  245. package/dist/commands/install/doctor.js +5 -5
  246. package/dist/commands/install/install.js +23 -22
  247. package/dist/commands/install/uninstall.js +36 -30
  248. package/dist/commands/install/upgrade.js +10 -2
  249. package/dist/commands/land.js +2 -3
  250. package/dist/commands/lib.js +323 -25
  251. package/dist/commands/workflow/branches.js +312 -72
  252. package/dist/commands/workflow/challenge.js +66 -13
  253. package/dist/commands/workflow/context.js +46 -10
  254. package/dist/commands/workflow/counters.js +231 -23
  255. package/dist/commands/workflow/decisions.js +221 -106
  256. package/dist/commands/workflow/disk.js +2 -1
  257. package/dist/commands/workflow/feature-base.js +60 -0
  258. package/dist/commands/workflow/issues.js +243 -15
  259. package/dist/commands/workflow/junit.js +137 -0
  260. package/dist/commands/workflow/ledgers.js +726 -112
  261. package/dist/commands/workflow/locks.js +150 -29
  262. package/dist/commands/workflow/loops.js +67 -0
  263. package/dist/commands/workflow/open-decision.js +199 -0
  264. package/dist/commands/workflow/plan-blocks.js +6 -0
  265. package/dist/commands/workflow/plans.js +1 -1
  266. package/dist/commands/workflow/prs.js +272 -16
  267. package/dist/commands/workflow/repo.js +1 -1
  268. package/dist/commands/workflow/run-facts.js +6 -0
  269. package/dist/commands/workflow/runs.js +747 -155
  270. package/dist/commands/workflow/runtime.js +8 -4
  271. package/dist/commands/workflow/status.js +259 -13
  272. package/dist/commands/workflow/step-table.js +41 -15
  273. package/dist/commands/workflow/steps.js +530 -26
  274. package/dist/commands/workflow/summary-findings.js +1 -1
  275. package/dist/commands/workflow/summary.js +289 -8
  276. package/dist/commands/workflow/tasks.js +294 -27
  277. package/dist/commands/workflow/tests-base.js +266 -0
  278. package/dist/commands/workflow/tests-changed.js +130 -56
  279. package/dist/commands/workflow/tests-jump.js +77 -0
  280. package/dist/commands/workflow/tests.js +608 -131
  281. package/dist/commands/workflow/tracker.js +920 -112
  282. package/dist/commands/workflow/workflows.js +80 -59
  283. package/dist/commands/workflow/worktrees.js +387 -58
  284. package/dist/install/cloud-env.js +32 -10
  285. package/dist/install/managed-block.js +101 -0
  286. package/dist/install/manifest.js +7 -1
  287. package/dist/install/modules/claude.js +6 -2
  288. package/dist/install/modules/cloud.js +73 -86
  289. package/dist/install/modules/codex.js +9 -2
  290. package/dist/install/modules/core.js +190 -27
  291. package/dist/install/modules/opencode.js +18 -23
  292. package/dist/install/network-allowlist.js +8 -3
  293. package/dist/install/project-docs.js +551 -0
  294. package/dist/install/template-copies.js +55 -5
  295. package/dist/install/write.js +117 -5
  296. package/dist/ledgers/journal.js +10 -8
  297. package/dist/ledgers/migrate.js +20 -9
  298. package/dist/ledgers/status.js +461 -8
  299. package/dist/ledgers/telemetry.js +71 -13
  300. package/dist/render/trackers.js +21 -12
  301. package/dist/shared/package-manager.js +7 -2
  302. package/dist/shared/settings.js +8 -0
  303. package/dist/shared/text.js +13 -0
  304. package/dist/tools/instructions-sources.js +1 -0
  305. package/dist/tools/instructions.js +97 -24
  306. package/package.json +23 -15
  307. package/.bkit/core/hooks/preflight-linear.sh +0 -73
  308. package/.bkit/shared/docs/architecture.md +0 -16
  309. package/.bkit/shared/docs/data-schema.md +0 -16
  310. package/.bkit/shared/docs/design.md +0 -38
  311. package/.bkit/shared/docs/noise.md +0 -20
  312. package/.bkit/shared/docs/observability.md +0 -22
  313. package/.bkit/shared/docs/security.md +0 -62
  314. package/.bkit/shared/docs/setup.md +0 -52
  315. package/.bkit/shared/docs/technology.md +0 -15
  316. /package/.bkit/templates/{.lintstagedrc.json → lintstagedrc.example.json} +0 -0
  317. /package/.bkit/templates/{.prettierignore → prettierignore.example} +0 -0
@@ -10,6 +10,7 @@
10
10
  // headers, derive the attempt, check what the gate checks, write the row, commit,
11
11
  // and print the step's tracker comment.
12
12
 
13
+ import { createHash } from "node:crypto";
13
14
  import * as fs from "node:fs";
14
15
  import * as path from "node:path";
15
16
 
@@ -26,7 +27,7 @@ import {
26
27
  } from "../../ledgers/status.js";
27
28
  import { clampLogPath, readRecords } from "../../ledgers/clamp-log.js";
28
29
  import { appendFrictionRow, frictionRow, journalEnabled } from "../../ledgers/journal.js";
29
- import { resolveRepoSlug } from "../../ledgers/telemetry.js";
30
+ import { queryLedger, resolveRepoSlug } from "../../ledgers/telemetry.js";
30
31
  import { getPromptsRoot } from "../../shared/package-roots.js";
31
32
  import { readTextFile } from "../../shared/json.js";
32
33
  import {
@@ -46,9 +47,25 @@ import { activeRunStart, savedPointLimit } from "./counters.js";
46
47
  import type { AskPoint } from "../../shared/settings.js";
47
48
  import { isResumable, runProgress, WORKFLOW_STEPS } from "./step-table.js";
48
49
  import { planFiles } from "./run-facts.js";
49
- import { mergeFindings, parseFindings } from "./challenge.js";
50
+ import { skipProblem } from "./open-decision.js";
51
+ import {
52
+ mergeFindings,
53
+ parseFindings,
54
+ renderFindingsLog,
55
+ structuredFindings,
56
+ type Finding,
57
+ } from "./challenge.js";
50
58
  import { fidProblem, normaliseFid, readIssueTracker } from "./fids.js";
51
- import { buildComment } from "./issues.js";
59
+ import {
60
+ auditEntries,
61
+ auditFindingsLine,
62
+ auditLedgerRows,
63
+ auditTotals,
64
+ buildComment,
65
+ parseAuditResult,
66
+ type AuditResult,
67
+ type HeldRow,
68
+ } from "./issues.js";
52
69
  import {
53
70
  EXIT_FOREIGN_PATH,
54
71
  activeRecord,
@@ -82,7 +99,16 @@ import {
82
99
  type TrackerOutcome,
83
100
  } from "./tracker.js";
84
101
  import { parsePlanBlocks } from "./plan-blocks.js";
85
- import { PLAN_TASKS_STEP, readTestFirst, touchedTests } from "./tests.js";
102
+ import {
103
+ blockedTests,
104
+ PLAN_TASKS_STEP,
105
+ readTestFirst,
106
+ runPlanPath,
107
+ sameTestName,
108
+ touchedTests,
109
+ baselineDiff,
110
+ } from "./tests.js";
111
+ import { addTakeoverTasks, type TakeoverEntry } from "./tasks.js";
86
112
  import { addAllButCopied } from "./worktrees.js";
87
113
 
88
114
  /**
@@ -134,6 +160,8 @@ export const EXIT_SOURCE_TOUCHED = 15;
134
160
  export const PLAN_TESTS_STEP = "build-plan-tests";
135
161
  /** The step whose subagent closes the group's verification gaps: a code step, like plan-execute. */
136
162
  export const PLAN_REMEDIATE_STEP = "build-plan-gaps-remediate";
163
+ /** The step whose subagent closes the whole-feature verification gaps, across every group. */
164
+ export const PLAN_REMEDIATE_HOLISTIC_STEP = "build-plan-gaps-remediate-holistic";
137
165
 
138
166
  /** Where `finish` puts the derived attempt in `--artifact` / `--message` / `--clamp-log`. */
139
167
  export const ATTEMPT_TOKEN = "<attempt>";
@@ -215,6 +243,8 @@ export function readHeader(
215
243
  const m = /^([A-Z][A-Za-z ]*):\s*(.*)$/.exec(line.trim());
216
244
  if (m && !(m[1]! in fields)) fields[m[1]!] = m[2]!.trim();
217
245
  }
246
+ const stale = fingerprintProblem(file, lines, end, fields);
247
+ if (stale !== null) return { ok: false, code: EXIT_INVALID, problem: stale };
218
248
  const pending = Object.entries(fields).filter(([, v]) => /\bPENDING\b/.test(v));
219
249
  if (pending.length > 0) {
220
250
  return {
@@ -263,6 +293,32 @@ export function readHeader(
263
293
  return { ok: true, verdict, fields };
264
294
  }
265
295
 
296
+ /** Header field that fingerprints a generated artifact's header and body. */
297
+ const FINGERPRINT = "Fingerprint";
298
+
299
+ /** sha256 of an artifact's header (without its Fingerprint line) and everything below it. */
300
+ export function artifactFingerprint(lines: readonly string[], end: number): string {
301
+ const head = lines.slice(0, end).filter((l) => !l.startsWith(`${FINGERPRINT}:`));
302
+ const body = lines.slice(end + 1);
303
+ return createHash("sha256")
304
+ .update(`${head.join("\n")}\n${VERDICT_END}\n${body.join("\n")}`)
305
+ .digest("hex");
306
+ }
307
+
308
+ /** Why a generated artifact no longer matches what the engine rendered, or null (hand-written ones carry no fingerprint). */
309
+ function fingerprintProblem(
310
+ file: string,
311
+ lines: readonly string[],
312
+ end: number,
313
+ fields: Record<string, string>,
314
+ ): string | null {
315
+ const given = fields[FINGERPRINT];
316
+ if (given === undefined) return null;
317
+ return artifactFingerprint(lines, end) === given
318
+ ? null
319
+ : `${file}: stale; its header or body changed after the engine rendered it (Fingerprint mismatch) — regenerate it from the result file`;
320
+ }
321
+
266
322
  /** Lines left as a stub placeholder: a bare `PENDING`, or a field whose whole value is `PENDING`. */
267
323
  export function placeholderLines(file: string): number[] {
268
324
  return fs
@@ -362,6 +418,8 @@ export const ROW_FIELDS: Record<string, readonly RowField[]> = {
362
418
  "build/build-group-gate": ["attempt", "scope"],
363
419
  "build/build-plan-gaps-remediate": ["attempt", "strategy"],
364
420
  "build/build-plan-verify-holistic": ["attempt"],
421
+ "build/build-holistic-gate": ["attempt", "scope"],
422
+ "build/build-plan-gaps-remediate-holistic": ["attempt", "strategy"],
365
423
  "build/build-challenge": ["attempt"],
366
424
  "build/build-decision": ["attempt"],
367
425
  "build/build-run-tests": ["attempt", "scope"],
@@ -378,8 +436,6 @@ export const ROW_FIELDS: Record<string, readonly RowField[]> = {
378
436
  "debug/debug-summary": ["attempt"],
379
437
  "ship/ship-summary": ["attempt"],
380
438
  "ship/ship-merge-pr": ["attempt"],
381
- "ship/ship-failure-diagnose": ["attempt"],
382
- "ship/ship-failure-remediate": ["attempt", "strategy"],
383
439
  };
384
440
 
385
441
  /** The required fields missing (absent or empty) from a row. */
@@ -433,11 +489,7 @@ function progressPoint(workflow: string, step: string, soak: boolean): AskPoint
433
489
  if (["debug-run-tests", "debug-failure-diagnose", "debug-failure-remediate"].includes(step))
434
490
  return "debug.fix";
435
491
  }
436
- if (
437
- workflow === "ship" &&
438
- ["ship-merge-pr", "ship-failure-diagnose", "ship-failure-remediate"].includes(step)
439
- )
440
- return "ship.merge";
492
+ if (workflow === "ship" && ["ship-merge-pr"].includes(step)) return "ship.merge";
441
493
  return undefined;
442
494
  }
443
495
 
@@ -597,6 +649,16 @@ function restoreIndex(snap: IndexSnapshot): string | null {
597
649
  return null;
598
650
  }
599
651
 
652
+ /** The `--field` extras; `changedTests` is written by the planned-test lock alone. */
653
+ function fieldExtras(specs: string[]): Record<string, unknown> {
654
+ if (specs.some((x) => x.startsWith("changedTests=")))
655
+ throw new CommandError(
656
+ EXIT.USAGE,
657
+ "--field cannot set changedTests; only the planned-test lock in `steps finish` writes it",
658
+ );
659
+ return Object.fromEntries(specs.map(extraField));
660
+ }
661
+
600
662
  /**
601
663
  * Append one `step-done` row, then commit (parentSha first, the row, then the
602
664
  * commit — the order the fold's de-dup relies on). Returns the row and the new
@@ -1037,6 +1099,22 @@ const fill = (s: string, attempt: number | undefined) =>
1037
1099
 
1038
1100
  const list = (v: FlagValue) => (v as string[] | undefined) ?? [];
1039
1101
 
1102
+ /**
1103
+ * A build decision row may say `route=continue` only when `bkit decisions skip` would pass
1104
+ * its decision file (the step's first artifact): the same `skipProblem` rule, read here.
1105
+ */
1106
+ function continueCheck(cwd: string, decisionFile: string | undefined): Check {
1107
+ const check = "route=continue";
1108
+ if (decisionFile === undefined)
1109
+ return { check, ok: false, detail: "no decision file: pass it as the first --artifact" };
1110
+ const read = readTextFile(path.resolve(cwd, decisionFile));
1111
+ if (!read.ok) return { check, ok: false, detail: `${decisionFile} is missing or unreadable` };
1112
+ const problem = skipProblem(read.text);
1113
+ return problem === null
1114
+ ? { check, ok: true, detail: `${decisionFile} passes decisions skip` }
1115
+ : { check, ok: false, detail: `${decisionFile}: ${problem}` };
1116
+ }
1117
+
1040
1118
  async function finish(ctx: RunContext): Promise<number> {
1041
1119
  const f = ctx.flags;
1042
1120
  const file = statusFile(ctx);
@@ -1059,7 +1137,7 @@ async function finish(ctx: RunContext): Promise<number> {
1059
1137
  } else {
1060
1138
  attempt = nonNegativeInt(f.attempt, "attempt");
1061
1139
  }
1062
- const extras: Record<string, unknown> = Object.fromEntries(list(f.field).map(extraField));
1140
+ const extras: Record<string, unknown> = fieldExtras(list(f.field));
1063
1141
  for (const spec of list(f.countField)) {
1064
1142
  const eq = spec.indexOf("=");
1065
1143
  if (eq <= 0)
@@ -1191,7 +1269,9 @@ async function finish(ctx: RunContext): Promise<number> {
1191
1269
  extras.source === "ci" &&
1192
1270
  extras.ciGeneration === active.ciGeneration &&
1193
1271
  verdict === "FAIL" &&
1194
- failures === undefined &&
1272
+ (typeof round.failures === "number"
1273
+ ? failures === round.failures
1274
+ : failures === undefined) &&
1195
1275
  extras.scope === round.scope &&
1196
1276
  artifacts.includes(String(round.artifact));
1197
1277
  if (!matching)
@@ -1237,6 +1317,8 @@ async function finish(ctx: RunContext): Promise<number> {
1237
1317
  });
1238
1318
  if (missing.length)
1239
1319
  pre.push({ check: "status row", ok: false, detail: `row would miss ${missing.join(", ")}` });
1320
+ if (workflow === "build" && step === "build-decision" && extras.route === "continue")
1321
+ pre.push(continueCheck(ctx.cwd, artifacts[0]));
1240
1322
  if (pre.some((c) => !c.ok)) {
1241
1323
  for (const c of pre.filter((x) => !x.ok)) ctx.log(`${c.check}: ${c.detail}`);
1242
1324
  ctx.emit({ pass: false, checks: pre });
@@ -1249,18 +1331,150 @@ async function finish(ctx: RunContext): Promise<number> {
1249
1331
 
1250
1332
  // A code step never edits a planned test case: each one's own lines must still be the
1251
1333
  // lines the group's tests step recorded at its red. Every other edit to the file is
1252
- // ordinary code-step work the verifier reads in the diff.
1334
+ // ordinary code-step work the verifier reads in the diff. The holistic fix spans every group.
1253
1335
  if (
1254
1336
  workflow === "build" &&
1255
- (step === PLAN_TASKS_STEP || step === PLAN_REMEDIATE_STEP) &&
1256
- group !== undefined
1337
+ (step === PLAN_TASKS_STEP ||
1338
+ step === PLAN_REMEDIATE_STEP ||
1339
+ step === PLAN_REMEDIATE_HOLISTIC_STEP)
1257
1340
  ) {
1258
1341
  const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? ctx.cwd;
1259
- const tests = touchedTests(top, file, workflow, group);
1342
+ const planArg = str(f.plan);
1343
+ const planFile =
1344
+ planArg === undefined
1345
+ ? runPlanPath(path.resolve(ctx.cwd, file))
1346
+ : path.resolve(ctx.cwd, planArg);
1347
+ const plan = fs.existsSync(planFile) ? fs.readFileSync(planFile, "utf-8") : undefined;
1348
+ const changed = touchedTests(top, file, workflow, plan);
1349
+ // A BLOCKED line of the step's log naming a changed test lets it through (recorded on the
1350
+ // row), unless an earlier record of that test already carries the line's reason.
1351
+ const logRead = artifacts[0] ? readTextFile(path.resolve(ctx.cwd, artifacts[0])) : undefined;
1352
+ const blocked = logRead?.ok ? blockedTests(logRead.text) : [];
1353
+ const changedTests: Array<Record<string, unknown>> = [];
1354
+ const tests: Array<{ test: string; name: string }> = [];
1355
+ /** Why each refused test is refused, in step with `tests`. */
1356
+ const why: Array<{ fromChange: boolean; removed: boolean; reused: string | null }> = [];
1357
+ /**
1358
+ * Refused tests a later task contradicts: a BLOCKED line names the test, the change removes
1359
+ * lines, and the owning task's box is ticked. One entry per test, from its latest owner
1360
+ * (a chain of takeovers gives every owner the same baseline).
1361
+ */
1362
+ const latestOwner = new Map<string, TakeoverEntry>();
1363
+ const ticked = new Set(
1364
+ parsePlanBlocks(plan ?? "")
1365
+ .tasks.filter((t) => t.done)
1366
+ .map((t) => t.task),
1367
+ );
1368
+ for (const c of changed) {
1369
+ const last = c.name.split(">").pop()!.trim();
1370
+ const naming = blocked.filter(
1371
+ (b) => b.test === c.test && (b.name === c.name || b.name === last),
1372
+ );
1373
+ const line = naming.find((b) => !c.reasons.includes(b.reason));
1374
+ const diff = line === undefined ? null : baselineDiff(top, c.text, c.test, c.name);
1375
+ // A test gone from the file (or renamed) against a recorded baseline removes its lines.
1376
+ const removes = diff === null ? c.text !== null : !diff.additive;
1377
+ if (line === undefined || removes) {
1378
+ if (!tests.some((t) => t.test === c.test && t.name === c.name)) {
1379
+ tests.push({ test: c.test, name: c.name });
1380
+ why.push({
1381
+ fromChange: c.fromChange,
1382
+ removed: line !== undefined,
1383
+ reused: line === undefined ? (naming[0]?.reason ?? null) : null,
1384
+ });
1385
+ }
1386
+ const key = `${c.test}\0${c.name}`;
1387
+ if (line !== undefined && ticked.has(c.task) && c.task > (latestOwner.get(key)?.from ?? 0))
1388
+ latestOwner.set(key, {
1389
+ test: c.test,
1390
+ name: c.name,
1391
+ from: c.task,
1392
+ task: line.task,
1393
+ reason: line.reason,
1394
+ });
1395
+ } else {
1396
+ const after = git(top, ["hash-object", "-w", "--", c.test]);
1397
+ changedTests.push({
1398
+ task: c.task,
1399
+ test: c.test,
1400
+ testName: c.name,
1401
+ block: c.block,
1402
+ reason: line.reason,
1403
+ blob: c.text,
1404
+ ...(after === null ? {} : { after }),
1405
+ });
1406
+ }
1407
+ }
1408
+ if (tests.length === 0 && changedTests.length > 0) extras.changedTests = changedTests;
1260
1409
  if (tests.length > 0) {
1261
1410
  const touched = [...new Set(tests.map((t) => t.test))];
1262
- const named = tests.map((t) => `\`${t.test}\` "${t.name}"`).join(", ");
1263
- const problem = `${named} differ${tests.length === 1 ? "s" : ""} from what the group's tests step recorded at its red: a code step never edits a planned test case — put ${tests.length === 1 ? "that test" : "those tests"} back as the tests step left ${tests.length === 1 ? "it" : "them"} (other edits to the file stay), or log the task BLOCKED naming the test and what it gets wrong (nothing written)`;
1411
+ const nameOf = (t: { test: string; name: string }) => `\`${t.test}\` "${t.name}"`;
1412
+ const named = tests.map(nameOf).join(", ");
1413
+ // The build hands each contradicted test to a takeover task before it re-asks.
1414
+ const entries = [...latestOwner.values()];
1415
+ // An entry needs a ticked owner, so the plan exists whenever there is one.
1416
+ const takeovers = addTakeoverTasks(
1417
+ ctx.cwd,
1418
+ planFile,
1419
+ path.resolve(ctx.cwd, file),
1420
+ entries,
1421
+ ctx.log,
1422
+ );
1423
+ const contradicts = entries.map((e, i) => ({
1424
+ test: e.test,
1425
+ name: e.name,
1426
+ from: e.from,
1427
+ task: e.task,
1428
+ takeover: takeovers[i]!,
1429
+ }));
1430
+ const isContradicted = (t: { test: string; name: string }) =>
1431
+ contradicts.some((x) => x.test === t.test && x.name === t.name);
1432
+ const contradictedPart = () => {
1433
+ if (contradicts.length === 0) return "";
1434
+ const many = contradicts.length > 1;
1435
+ const them = many ? "them" : "it";
1436
+ const owners = contradicts.map((x) => `TASK ${x.from}`).join(", ");
1437
+ const added = [...new Set(contradicts.map((x) => x.takeover))].join(", ");
1438
+ return `${contradicts.map(nameOf).join(", ")} ${many ? "are" : "is"} owned by an earlier, ticked task (${owners}) and this change contradicts ${them}: the build added takeover TASK ${added}, which rewrites ${them} in its own tests step — put ${them} back as the tests step left ${them} (other edits to the file stay); a BLOCKED line does not keep ${them}, so the keep-the-edit choice does not apply to ${them}`;
1439
+ };
1440
+ const logLines = (list: typeof tests) =>
1441
+ list.map((t) => `BLOCKED — TASK {N}: test \`${t.test}\` \`${t.name}\` — {why}`).join("; ");
1442
+ const part = (fromChange: boolean) => {
1443
+ const list = tests.filter(
1444
+ (t, i) => why[i]!.fromChange === fromChange && !isContradicted(t),
1445
+ );
1446
+ if (list.length === 0) return "";
1447
+ const many = list.length > 1;
1448
+ const subject = `${list.map(nameOf).join(", ")} differ${many ? "" : "s"} from`;
1449
+ const them = many ? "those tests" : "that test";
1450
+ const it = many ? "them" : "it";
1451
+ return fromChange
1452
+ ? `${subject} the change a code step already recorded for ${many ? "them" : "it"} (changedTests): put ${them} back as that recorded change left ${it}, or keep the edit and log one line per test in the step's log: ${logLines(list)}`
1453
+ : `${subject} what the group's tests step recorded at its red: a code step never edits a planned test case — put ${them} back as the tests step left ${it} (other edits to the file stay), or keep the edit and log one line per test in the step's log: ${logLines(list)}`;
1454
+ };
1455
+ const notes: string[] = [];
1456
+ for (const [i, t] of tests.entries()) {
1457
+ const w = why[i]!;
1458
+ if (isContradicted(t)) continue;
1459
+ if (w.removed)
1460
+ notes.push(
1461
+ `${nameOf(t)}: the engine refuses a BLOCKED-named change that removes a line of a planned test; it lets through only a change that adds lines, and verify reads every added line`,
1462
+ );
1463
+ if (w.reused !== null)
1464
+ notes.push(
1465
+ `${nameOf(t)}: the BLOCKED line's reason "${w.reused}" is already recorded for that test — log a new reason`,
1466
+ );
1467
+ }
1468
+ const refused = [part(false), part(true)].filter(Boolean);
1469
+ const refusedText =
1470
+ refused.length > 0
1471
+ ? `${refused.join(" | ")}${notes.length ? ` (${notes.join("; ")})` : ""} (Gap {N} in a gaps fix)`
1472
+ : "";
1473
+ const written =
1474
+ contradicts.length > 0
1475
+ ? "(no step row written; the plan and its build-takeover rows are)"
1476
+ : "(nothing written)";
1477
+ const problem = `${[contradictedPart(), refusedText].filter(Boolean).join(" | ")} ${written}`;
1264
1478
  ctx.log(problem);
1265
1479
  recordTestLockFriction(top, step, named);
1266
1480
  ctx.emit({
@@ -1269,6 +1483,7 @@ async function finish(ctx: RunContext): Promise<number> {
1269
1483
  problem,
1270
1484
  touched,
1271
1485
  tests,
1486
+ contradicts,
1272
1487
  });
1273
1488
  return EXIT_TESTS_TOUCHED;
1274
1489
  }
@@ -1294,6 +1509,39 @@ async function finish(ctx: RunContext): Promise<number> {
1294
1509
  ctx.emit({ pass: false, source });
1295
1510
  return EXIT_SOURCE_TOUCHED;
1296
1511
  }
1512
+ // An earlier task's planned test stays as its baseline left it, unless an open task of
1513
+ // this group names it (its own test, or one it takes over).
1514
+ const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? ctx.cwd;
1515
+ const planPath = path.resolve(ctx.cwd, planArg);
1516
+ const planText = fs.existsSync(planPath) ? fs.readFileSync(planPath, "utf-8") : undefined;
1517
+ const planTasks = parsePlanBlocks(planText ?? "").tasks;
1518
+ const done = new Set(planTasks.filter((t) => t.done).map((t) => t.task));
1519
+ const inGroup = new Set(planTasks.filter((t) => t.group === group).map((t) => t.task));
1520
+ const mine = readTestFirst(planText ?? "", group).flatMap((s) =>
1521
+ s.kind === "test" && !done.has(s.task) ? s.tests : [],
1522
+ );
1523
+ // Only a per-test lock binds here: an earlier group's test held by its whole file's blob
1524
+ // (no line carries its name, or the file was missing) cannot tell this group's own new
1525
+ // tests in that file from an edit to it.
1526
+ const tests = touchedTests(top, file, workflow, planText)
1527
+ .filter((c) => !c.wholeFile || inGroup.has(c.task))
1528
+ .filter((c) => !mine.some((m) => m.test === c.test && sameTestName(m.name, c.name)))
1529
+ .map((c) => ({ test: c.test, name: c.name }));
1530
+ if (tests.length > 0) {
1531
+ const touched = [...new Set(tests.map((t) => t.test))];
1532
+ const named = tests.map((t) => `\`${t.test}\` "${t.name}"`).join(", ");
1533
+ const problem = `${named} ${tests.length > 1 ? "are" : "is"} an earlier task's planned test that no open task of group ${group} names: the tests step never changes it — put it back as the earlier task's red left it (other edits to the file stay); to change what it asserts, the plan names it on this group's task TEST FIRST (a takeover) (nothing written)`;
1534
+ ctx.log(problem);
1535
+ recordTestLockFriction(top, step, named);
1536
+ ctx.emit({
1537
+ pass: false,
1538
+ reask: agents.length ? { agent: agents[0], artifact: artifacts[0] } : null,
1539
+ problem,
1540
+ touched,
1541
+ tests,
1542
+ });
1543
+ return EXIT_TESTS_TOUCHED;
1544
+ }
1297
1545
  }
1298
1546
 
1299
1547
  // The attempt finished is the latest one this run saved artifacts for.
@@ -1415,7 +1663,15 @@ async function finish(ctx: RunContext): Promise<number> {
1415
1663
  attempt,
1416
1664
  "comment",
1417
1665
  );
1418
- tracker = await postForVerb(ctx, comment, { fid: fidOfStatusFile(file), file, key });
1666
+ tracker = await postForVerb(ctx, comment, {
1667
+ fid: fidOfStatusFile(file),
1668
+ file,
1669
+ key,
1670
+ purpose:
1671
+ step.endsWith("-decision") || verdict === "FAIL" || verdict === "HANDOVER"
1672
+ ? "attention"
1673
+ : "routine",
1674
+ });
1419
1675
  }
1420
1676
 
1421
1677
  const written = writeStepRow(
@@ -1464,13 +1720,225 @@ async function finish(ctx: RunContext): Promise<number> {
1464
1720
  checks,
1465
1721
  comment,
1466
1722
  // Written after the step's commit, so the commit never carries it.
1467
- commentFile: commentFileOf(ctx.cwd, comment),
1723
+ commentFile: commentFileOf(ctx.cwd, comment, ctx),
1468
1724
  ...(tracker === undefined ? {} : { tracker }),
1469
1725
  });
1470
1726
  if (written.code !== EXIT.OK) return written.code;
1471
1727
  return pass ? EXIT.OK : EXIT.NO;
1472
1728
  }
1473
1729
 
1730
+ // ---------------------------------------------------------------------------
1731
+ // stub --result-file — an artifact rendered from one structured result
1732
+ // ---------------------------------------------------------------------------
1733
+
1734
+ /**
1735
+ * Header fields the engine computes from the findings; every other declared field is a
1736
+ * judgment the result must supply (the evidence-dependent ones: Tasks, Redesign, Strategy ...).
1737
+ */
1738
+ const DERIVED_FIELDS: Record<string, (findings: Finding[]) => string> = {
1739
+ Failures: (f) => String(f.length),
1740
+ // `true` when any gap is fixable (the plan-verify header contract), `false` for none.
1741
+ Fixable: (f) => String(f.some((x) => x.fixable)),
1742
+ };
1743
+
1744
+ /** The agent whose header is the audit summary (Status / Report / Findings), not a Verdict header. */
1745
+ const AUDIT_AGENT = "bkit-audit-generate";
1746
+
1747
+ export interface Rendered {
1748
+ text: string;
1749
+ fingerprint: string;
1750
+ extra: Record<string, unknown>;
1751
+ }
1752
+
1753
+ const withFingerprint = (head: string[], body: string): Rendered["text"] => {
1754
+ const unsigned = `${head.join("\n")}\n${VERDICT_END}\n\n${body}`;
1755
+ const lines = unsigned.split("\n");
1756
+ const fingerprint = artifactFingerprint(lines, head.length);
1757
+ return `${head.join("\n")}\n${FINGERPRINT}: ${fingerprint}\n${VERDICT_END}\n\n${body}`;
1758
+ };
1759
+
1760
+ const fingerprintOf = (text: string): string =>
1761
+ artifactFingerprint(text.split("\n"), text.split("\n").indexOf(VERDICT_END));
1762
+
1763
+ /**
1764
+ * Every key the failures ledger (the working directory's `docs/failures.jsonl`, the file
1765
+ * `ledgers append` and `ledgers query` use) already holds, with the finding each row records,
1766
+ * so a derived audit key never lands on a different finding's row.
1767
+ */
1768
+ function ledgerKeys(cwd: string): Map<string, HeldRow> {
1769
+ const file = path.resolve(cwd, "docs", "failures.jsonl");
1770
+ const held = new Map<string, HeldRow>();
1771
+ if (!fs.existsSync(file)) return held;
1772
+ for (const row of queryLedger(fs.readFileSync(file, "utf8")).rows) {
1773
+ const r: Record<string, unknown> = { ...row };
1774
+ if (typeof r["key"] !== "string") continue;
1775
+ const locations = Array.isArray(r["references"])
1776
+ ? r["references"].filter((x): x is string => typeof x === "string")
1777
+ : [];
1778
+ const text = typeof r["description"] === "string" ? r["description"] : "";
1779
+ const fromText = /\((\S+:\d+)\);/.exec(text);
1780
+ if (fromText?.[1] !== undefined) locations.push(fromText[1]);
1781
+ held.set(r["key"], {
1782
+ summary: typeof r["summary"] === "string" ? r["summary"] : "",
1783
+ locations,
1784
+ });
1785
+ }
1786
+ return held;
1787
+ }
1788
+
1789
+ function renderAudit(cwd: string, result: AuditResult): Rendered {
1790
+ const held = ledgerKeys(cwd);
1791
+ const entries = auditEntries(result, held);
1792
+ const totals = auditTotals(result.findings);
1793
+ const head = [
1794
+ `Status: ${result.status}`,
1795
+ `Report: ${result.report ?? "None"}`,
1796
+ `Findings: ${auditFindingsLine(totals)}`,
1797
+ `Issue: ${result.issue ?? "None"}`,
1798
+ `Parent: ${result.parent ?? "None"}`,
1799
+ ];
1800
+ const cell = (t: string) => t.replace(/\|/g, "\\|");
1801
+ const list = (items: string[]) => (items.length ? items.map((i) => `- ${i}`).join("\n") : "None");
1802
+ const body = [
1803
+ `# Audit Summary: ${result.slug}`,
1804
+ "",
1805
+ "## Stopped",
1806
+ "",
1807
+ result.stopped ?? "None",
1808
+ "",
1809
+ "## Overview",
1810
+ "",
1811
+ result.overview ?? "None",
1812
+ "",
1813
+ "## Suggested Issues",
1814
+ "",
1815
+ ...(entries.length
1816
+ ? [
1817
+ "| ID | Severity | Title | Location | Prior key |",
1818
+ "| --- | --- | --- | --- | --- |",
1819
+ ...entries.map(
1820
+ (e) =>
1821
+ `| ${e.id} | ${e.severity} | ${cell(e.title)} | \`${e.location}\` | ${e.priorKey ?? "none"} |`,
1822
+ ),
1823
+ ]
1824
+ : ["None"]),
1825
+ "",
1826
+ "## Not Checked",
1827
+ "",
1828
+ list(result.notChecked),
1829
+ "",
1830
+ "## Ledger",
1831
+ "",
1832
+ list(entries.map((e) => `\`${e.key}\` ${e.severity} OPEN`)),
1833
+ "",
1834
+ ].join("\n");
1835
+ const text = withFingerprint(head, body);
1836
+ return {
1837
+ text,
1838
+ fingerprint: fingerprintOf(text),
1839
+ extra: {
1840
+ ids: entries.map((e) => e.id),
1841
+ totals,
1842
+ ledgerRows: auditLedgerRows(result, held),
1843
+ },
1844
+ };
1845
+ }
1846
+
1847
+ /**
1848
+ * The artifact for `agent` rendered from a structured result `{findings, judgments, body,
1849
+ * evidenceComplete}`: counts and booleans derived from the findings, judged fields passed
1850
+ * through and checked, a Fingerprint over the header and body. Throws a CommandError
1851
+ * (EXIT_INVALID) and writes nothing on any disagreement.
1852
+ */
1853
+ export function renderResult(cwd: string, agent: string, raw: unknown): Rendered {
1854
+ const bad = (why: string) => new CommandError(EXIT_INVALID, `result: ${why}`);
1855
+ if (agent === AUDIT_AGENT) {
1856
+ try {
1857
+ return renderAudit(cwd, parseAuditResult(raw));
1858
+ } catch (err) {
1859
+ throw err instanceof CommandError ? bad(err.message) : err;
1860
+ }
1861
+ }
1862
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
1863
+ throw bad("must be a JSON object");
1864
+ const r = raw as Record<string, unknown>;
1865
+ for (const k of Object.keys(r))
1866
+ if (!["findings", "judgments", "body", "evidenceComplete"].includes(k))
1867
+ throw bad(`unknown field "${k}"`);
1868
+ let findings: Finding[];
1869
+ try {
1870
+ findings = structuredFindings(r["findings"] ?? [], cwd);
1871
+ } catch (err) {
1872
+ throw err instanceof CommandError ? bad(err.message) : err;
1873
+ }
1874
+ const judgments = r["judgments"] ?? {};
1875
+ if (judgments === null || typeof judgments !== "object" || Array.isArray(judgments))
1876
+ throw bad("judgments must be an object");
1877
+ const judged = new Map<string, string>();
1878
+ for (const [k, v] of Object.entries(judgments)) {
1879
+ if (typeof v !== "string" && typeof v !== "number" && typeof v !== "boolean")
1880
+ throw bad(`judgment ${k} must be text, a number or a boolean`);
1881
+ // A judgment renders into one header line: a line break would forge header lines.
1882
+ if (/[\r\n]/.test(String(v))) throw bad(`judgment ${k} must be a single line`);
1883
+ judged.set(k, String(v));
1884
+ }
1885
+ const declared = promptHeader(agent);
1886
+ const names = new Set(["Verdict", ...declared.fields.map((f) => f.name)]);
1887
+ for (const k of judged.keys()) {
1888
+ if (!names.has(k)) throw bad(`judgment ${k} is not a header field of ${agent}`);
1889
+ if (k in DERIVED_FIELDS) throw bad(`${k} is derived from the findings and cannot be supplied`);
1890
+ }
1891
+ if (typeof r["evidenceComplete"] !== "boolean")
1892
+ throw bad("evidenceComplete must be stated as true or false");
1893
+ const evidenceComplete = r["evidenceComplete"];
1894
+ const arithmetic =
1895
+ findings.length > 0
1896
+ ? "FAIL"
1897
+ : !evidenceComplete
1898
+ ? declared.verdicts.includes("CONCERNS")
1899
+ ? "CONCERNS"
1900
+ : "FAIL"
1901
+ : "PASS";
1902
+ const verdict = judged.get("Verdict") ?? arithmetic;
1903
+ if (!declared.verdicts.includes(verdict))
1904
+ throw bad(`Verdict ${verdict} is not ${declared.verdicts.join("|")}`);
1905
+ if (verdict === "PASS" && arithmetic !== "PASS")
1906
+ throw bad(
1907
+ findings.length > 0
1908
+ ? `Verdict PASS contradicts ${findings.length} finding(s)`
1909
+ : "Verdict PASS contradicts incomplete evidence",
1910
+ );
1911
+ const head = [`Verdict: ${verdict}`];
1912
+ for (const f of declared.fields) {
1913
+ const value = DERIVED_FIELDS[f.name]?.(findings) ?? judged.get(f.name);
1914
+ if (value === undefined) throw bad(`${f.name} is a judgment the result must supply`);
1915
+ if (f.values && !f.values.includes(value))
1916
+ throw bad(`${f.name} ${value} is not ${f.values.join("|")}`);
1917
+ if (f.integer && !/^[0-9]+$/.test(value))
1918
+ throw bad(`${f.name} ${value} is not a non-negative integer`);
1919
+ head.push(`${f.name}: ${value}`);
1920
+ }
1921
+ const given = r["body"] ?? "";
1922
+ if (typeof given !== "string") throw bad("body must be text");
1923
+ if (verdict === "PASS" && given.trim() === "") throw bad("a PASS result needs a non-empty body");
1924
+ if (given.split("\n").includes(VERDICT_END)) throw bad(`body holds a ${VERDICT_END} line`);
1925
+ const log =
1926
+ findings.length > 0 && !/^## Findings Log\b/m.test(given)
1927
+ ? `\n${renderFindingsLog(findings)}\n`
1928
+ : "";
1929
+ const body = `${given.replace(/\n+$/, "")}\n${log}`;
1930
+ const text = withFingerprint(head, body.replace(/^\n+/, ""));
1931
+ return { text, fingerprint: fingerprintOf(text), extra: { findings: findings.length } };
1932
+ }
1933
+
1934
+ function readResult(cwd: string, file: string): unknown {
1935
+ const abs = path.resolve(cwd, file);
1936
+ if (!fs.existsSync(abs)) throw new CommandError(EXIT_INVALID, `result: ${file} does not exist`);
1937
+ const parsed = parseJson(fs.readFileSync(abs, "utf-8"));
1938
+ if (!parsed.ok) throw new CommandError(EXIT_INVALID, `result: ${file} is not JSON`);
1939
+ return parsed.value;
1940
+ }
1941
+
1474
1942
  // ---------------------------------------------------------------------------
1475
1943
  // stub
1476
1944
  // ---------------------------------------------------------------------------
@@ -1611,7 +2079,7 @@ export const stepsCommand: CommandSpec = {
1611
2079
  group,
1612
2080
  strategy,
1613
2081
  artifacts,
1614
- extras: Object.fromEntries(list(f.field).map(extraField)),
2082
+ extras: fieldExtras(list(f.field)),
1615
2083
  parentSha: str(f.parentSha),
1616
2084
  commit: commit as "auto" | "none",
1617
2085
  message: str(f.message),
@@ -1628,7 +2096,7 @@ export const stepsCommand: CommandSpec = {
1628
2096
  },
1629
2097
  finish: {
1630
2098
  summary:
1631
- "End a step: read the verdict header(s), derive the attempt, check the gate, write the row, commit, print the tracker comment.",
2099
+ "End a step: read the verdict header(s), derive the attempt, check the gate, write the row, commit, print the tracker comment. Exit 11 on a build tests step that changed an earlier task's recorded test no open task of the group names, and on a code step that changed a planned test; for each BLOCKED test a ticked task owns, a code step first adds a takeover task to the plan and its build-takeover row, and prints them under contradicts.",
1632
2100
  use: "workflow",
1633
2101
  flags: [
1634
2102
  { ...FILE_FLAG, help: "path to status.jsonl (created if absent)" },
@@ -1701,7 +2169,7 @@ export const stepsCommand: CommandSpec = {
1701
2169
  {
1702
2170
  name: "plan",
1703
2171
  type: "string",
1704
- help: `${PLAN_TESTS_STEP}: the plan file whose TEST FIRST lines bound the step's commit (required there with --commit=auto)`,
2172
+ help: `${PLAN_TESTS_STEP}: the plan file whose TEST FIRST lines bound the step's commit (required there with --commit=auto); the code steps: the plan whose TEST FIRST lines name the planned tests the lock checks (default: the plan beside the status file)`,
1705
2173
  },
1706
2174
  ...COMMIT_FLAGS.map((c) =>
1707
2175
  c.name === "message"
@@ -1771,6 +2239,8 @@ export const stepsCommand: CommandSpec = {
1771
2239
  "why the verdict read failed, or which planned tests the code step touched (exit 4 / 5 / 6 / 11 only)",
1772
2240
  touched:
1773
2241
  "planned test files of the group that differ from the blob its tests step recorded (exit 11 only)",
2242
+ contradicts:
2243
+ "[{test, name, from, task, takeover}] the refused tests a ticked task `from` owns that this change contradicts, each with the takeover task the engine added (exit 11 on a code step only)",
1774
2244
  source:
1775
2245
  "files the tests step's commit would change that are not the group's TEST FIRST files, or add although a CREATE line names them (exit 15 only)",
1776
2246
  later: "artifacts of a later attempt this run saved (exit 12 only)",
@@ -1795,7 +2265,7 @@ export const stepsCommand: CommandSpec = {
1795
2265
  [EXIT_OUTSIDE_DOCS]:
1796
2266
  "--docs-only and the step staged a file outside the artifact tree (nothing written)",
1797
2267
  [EXIT_TESTS_TOUCHED]:
1798
- "build plan-execute / plan-gaps-remediate: a planned test case of the group differs from the lines its tests step recorded in status.jsonl (`tests`: [{test, name}]; `touched`: their files) — re-ask `reask.agent` to put that test back or log the task BLOCKED; other edits to the file stay (nothing written; an agent-rework friction row is appended)",
2268
+ "build plan-execute / plan-gaps-remediate: a planned test case (of any group) differs from the lines recorded in status.jsonl (`tests`: [{test, name}]; `touched`: their files) — re-ask `reask.agent` to put that test back, or to keep the edit and log ``BLOCKED — TASK {N}: test `{file}` `{name}` — {why}`` (Gap {N} in a gaps fix) in the step's log, which lets that change through and records it in the row's `changedTests`; other edits to the file stay (nothing written; an agent-rework friction row is appended). A BLOCKED test that removes lines of a ticked task's planned test is contradicted instead: no BLOCKED line keeps it, the engine adds a takeover task and its build-takeover row (once per test, however often the finish runs) and lists it in `contradicts`; the agent puts it back",
1799
2269
  [EXIT_LATER_ATTEMPT]:
1800
2270
  "this run saved an artifact of a later attempt (`later`) than the one finished (nothing written)",
1801
2271
  [EXIT_WORKFLOWS_CHANGED]:
@@ -1817,13 +2287,18 @@ export const stepsCommand: CommandSpec = {
1817
2287
  repeatable: true,
1818
2288
  help: "header field that must be present, e.g. Failures",
1819
2289
  },
2290
+ {
2291
+ name: "result-file",
2292
+ type: "string",
2293
+ help: "with --agent: also require the artifact to be the render of this result (a changed result is stale)",
2294
+ },
1820
2295
  ],
1821
2296
  output: { verdict: "the Verdict value", fields: "every Key: value header field" },
1822
2297
  exitCodes: {
1823
2298
  [EXIT_EMPTY]: "artifact missing or empty",
1824
2299
  [EXIT_PENDING]: "a header field is still PENDING",
1825
2300
  [EXIT_INVALID]:
1826
- "no verdict:end line, Verdict outside the allowed set, or a required field missing — re-prompt the subagent",
2301
+ "no verdict:end line, Verdict outside the allowed set, a required field missing, or a generated artifact whose Fingerprint no longer matches its header and body (stale) — re-prompt the subagent or regenerate it",
1827
2302
  },
1828
2303
  run: (ctx) => {
1829
2304
  const header = readHeader(
@@ -1835,6 +2310,27 @@ export const stepsCommand: CommandSpec = {
1835
2310
  ctx.log(header.problem);
1836
2311
  return header.code;
1837
2312
  }
2313
+ if (ctx.flags.resultFile !== undefined) {
2314
+ if (ctx.flags.agent === undefined)
2315
+ throw new CommandError(EXIT.USAGE, "--result-file needs --agent");
2316
+ try {
2317
+ const rendered = renderResult(
2318
+ ctx.cwd,
2319
+ String(ctx.flags.agent),
2320
+ readResult(ctx.cwd, String(ctx.flags.resultFile)),
2321
+ );
2322
+ if (header.fields[FINGERPRINT] !== rendered.fingerprint) {
2323
+ ctx.log(
2324
+ `${String(ctx.flags.file)}: stale; it is not the render of ${String(ctx.flags.resultFile)} (Fingerprint mismatch)`,
2325
+ );
2326
+ return EXIT_INVALID;
2327
+ }
2328
+ } catch (err) {
2329
+ if (!(err instanceof CommandError) || err.code !== EXIT_INVALID) throw err;
2330
+ ctx.log(err.message);
2331
+ return EXIT_INVALID;
2332
+ }
2333
+ }
1838
2334
  ctx.emit({ verdict: header.verdict, fields: header.fields });
1839
2335
  return EXIT.OK;
1840
2336
  },
@@ -2018,17 +2514,96 @@ export const stepsCommand: CommandSpec = {
2018
2514
  "Seed a versioned artifact: copy the prior version, then put a PENDING verdict header on top.",
2019
2515
  use: "workflow",
2020
2516
  flags: [
2021
- { name: "from", type: "string", required: true, help: "the prior versioned artifact" },
2517
+ { name: "from", type: "string", help: "the prior versioned artifact (copy mode)" },
2022
2518
  { name: "to", type: "string", required: true, help: "the artifact to create" },
2519
+ {
2520
+ name: "agent",
2521
+ type: "string",
2522
+ help: "with --result-file: the subagent whose header the result renders",
2523
+ },
2524
+ {
2525
+ name: "result-file",
2526
+ type: "string",
2527
+ help: "render the artifact from this structured result JSON {findings, judgments, body, evidenceComplete} (audit: the audit result) instead of copying --from",
2528
+ },
2529
+ {
2530
+ name: "invocation",
2531
+ type: "string",
2532
+ unresolved: true,
2533
+ help: "with --result-file: the invocation id this step runs under; a result that names another invocation is stale and refused (exit 6, nothing written)",
2534
+ },
2023
2535
  {
2024
2536
  name: "strip-header",
2025
2537
  type: "boolean",
2026
2538
  help: "drop the prior version's own header (everything down to its <!-- verdict:end -->)",
2027
2539
  },
2028
2540
  ],
2029
- output: { file: "the artifact written", stripped: "the prior header was dropped" },
2030
- exitCodes: { [EXIT_EMPTY]: "--from is missing or empty" },
2541
+ output: {
2542
+ file: "the artifact written (an audit summary whose --to already holds a report goes to <result-file>.summary.md)",
2543
+ reportKept: "audit result: the existing report at --to, left untouched",
2544
+ stripped: "the prior header was dropped (copy mode)",
2545
+ fingerprint: "with --result-file: the Fingerprint header value",
2546
+ ids: "audit result: the report-local finding IDs, in report order",
2547
+ totals: "audit result: findings per severity",
2548
+ ledgerRows:
2549
+ "audit result: one failure ledger payload per finding, for `bkit ledgers append`",
2550
+ findings: "other results: the finding count",
2551
+ },
2552
+ exitCodes: {
2553
+ [EXIT_EMPTY]: "--from is missing or empty",
2554
+ [EXIT_INVALID]:
2555
+ "--result-file is unreadable or invalid, or a judgment contradicts the findings (nothing written)",
2556
+ },
2031
2557
  run: (ctx) => {
2558
+ if (ctx.flags.resultFile !== undefined) {
2559
+ if (ctx.flags.from !== undefined)
2560
+ throw new CommandError(EXIT.USAGE, "give --from or --result-file, not both");
2561
+ if (ctx.flags.agent === undefined)
2562
+ throw new CommandError(EXIT.USAGE, "--result-file needs --agent");
2563
+ try {
2564
+ const result = readResult(ctx.cwd, String(ctx.flags.resultFile));
2565
+ const issued = str(ctx.flags.invocation);
2566
+ const carried =
2567
+ typeof result === "object" && result !== null && !Array.isArray(result)
2568
+ ? (result as Record<string, unknown>).invocation
2569
+ : undefined;
2570
+ // A result written under another invocation is left over from an earlier round or run.
2571
+ if (issued !== undefined && carried !== undefined && carried !== issued)
2572
+ throw new CommandError(
2573
+ EXIT_INVALID,
2574
+ `result: ${String(ctx.flags.resultFile)} was written under invocation ${String(carried)}, not ${issued}; it is a stale result from an earlier round or run (nothing written)`,
2575
+ );
2576
+ const rendered = renderResult(ctx.cwd, String(ctx.flags.agent), result);
2577
+ const requested = path.resolve(ctx.cwd, String(ctx.flags.to));
2578
+ // An audit's --to is the finished report; the summary never replaces it.
2579
+ const keepsReport =
2580
+ ctx.flags.agent === AUDIT_AGENT &&
2581
+ fs.existsSync(requested) &&
2582
+ fs.statSync(requested).size > 0;
2583
+ const resultFile = path.resolve(ctx.cwd, String(ctx.flags.resultFile));
2584
+ const to = keepsReport
2585
+ ? path.join(
2586
+ path.dirname(resultFile),
2587
+ `${path.basename(resultFile, path.extname(resultFile))}.summary.md`,
2588
+ )
2589
+ : requested;
2590
+ fs.mkdirSync(path.dirname(to), { recursive: true });
2591
+ fs.writeFileSync(to, rendered.text);
2592
+ ctx.emit({
2593
+ file: keepsReport ? path.relative(ctx.cwd, to) : String(ctx.flags.to),
2594
+ ...(keepsReport ? { reportKept: String(ctx.flags.to) } : {}),
2595
+ fingerprint: rendered.fingerprint,
2596
+ ...rendered.extra,
2597
+ });
2598
+ return EXIT.OK;
2599
+ } catch (err) {
2600
+ if (!(err instanceof CommandError) || err.code !== EXIT_INVALID) throw err;
2601
+ ctx.log(err.message);
2602
+ return EXIT_INVALID;
2603
+ }
2604
+ }
2605
+ if (ctx.flags.from === undefined)
2606
+ throw new CommandError(EXIT.USAGE, "give --from (copy) or --result-file");
2032
2607
  const from = path.resolve(ctx.cwd, String(ctx.flags.from));
2033
2608
  if (!fs.existsSync(from) || fs.statSync(from).size === 0) {
2034
2609
  ctx.log(`${String(ctx.flags.from)} is missing or empty`);