@cbartens/bkit 5.5.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/.bkit/README.md +30 -20
  2. package/.bkit/core/.agents/docs.md +1 -0
  3. package/.bkit/core/.agents/rules.md +51 -26
  4. package/.bkit/core/.bkit/README.md +29 -19
  5. package/.bkit/core/.bkit/authoring.md +117 -0
  6. package/.bkit/core/.bkit/cloud.md +11 -11
  7. package/.bkit/core/.bkit/comparison.md +5 -5
  8. package/.bkit/core/.bkit/install.md +20 -20
  9. package/.bkit/core/.bkit/jsonl.md +202 -122
  10. package/.bkit/core/.bkit/lite.md +1 -1
  11. package/.bkit/core/.bkit/pipeline.md +49 -52
  12. package/.bkit/core/.bkit/prompts.md +106 -167
  13. package/.bkit/core/.bkit/providers.md +29 -32
  14. package/.bkit/core/.bkit/templates.md +44 -18
  15. package/.bkit/core/.bkit/trackers.md +60 -28
  16. package/.bkit/core/.bkit/workflows.md +399 -359
  17. package/.bkit/core/AGENTS.md +16 -22
  18. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +14 -38
  19. package/.bkit/core/docs/templates/bkit-audit-adoption.md +16 -40
  20. package/.bkit/core/docs/templates/bkit-audit-agents.md +19 -43
  21. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +16 -40
  22. package/.bkit/core/docs/templates/bkit-audit-analytics.md +14 -38
  23. package/.bkit/core/docs/templates/bkit-audit-annotations.md +11 -35
  24. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +15 -39
  25. package/.bkit/core/docs/templates/bkit-audit-app-store.md +12 -36
  26. package/.bkit/core/docs/templates/bkit-audit-architecture.md +16 -40
  27. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +16 -40
  28. package/.bkit/core/docs/templates/bkit-audit-config.md +18 -42
  29. package/.bkit/core/docs/templates/bkit-audit-cost.md +16 -40
  30. package/.bkit/core/docs/templates/bkit-audit-coverage.md +15 -39
  31. package/.bkit/core/docs/templates/bkit-audit-database.md +16 -40
  32. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +15 -39
  33. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +15 -38
  34. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +16 -40
  35. package/.bkit/core/docs/templates/bkit-audit-documentation.md +11 -35
  36. package/.bkit/core/docs/templates/bkit-audit-duplication.md +18 -42
  37. package/.bkit/core/docs/templates/bkit-audit-failures.md +13 -37
  38. package/.bkit/core/docs/templates/bkit-audit-flakes.md +12 -36
  39. package/.bkit/core/docs/templates/bkit-audit-gates.md +14 -38
  40. package/.bkit/core/docs/templates/bkit-audit-issues.md +15 -39
  41. package/.bkit/core/docs/templates/bkit-audit-llm.md +16 -40
  42. package/.bkit/core/docs/templates/bkit-audit-logs.md +14 -38
  43. package/.bkit/core/docs/templates/bkit-audit-models.md +12 -36
  44. package/.bkit/core/docs/templates/bkit-audit-privacy.md +12 -36
  45. package/.bkit/core/docs/templates/bkit-audit-prompts.md +15 -39
  46. package/.bkit/core/docs/templates/bkit-audit-red-team.md +15 -39
  47. package/.bkit/core/docs/templates/bkit-audit-reliability.md +15 -39
  48. package/.bkit/core/docs/templates/bkit-audit-repo.md +12 -36
  49. package/.bkit/core/docs/templates/bkit-audit-security.md +13 -37
  50. package/.bkit/core/docs/templates/bkit-audit-slop.md +14 -38
  51. package/.bkit/core/docs/templates/bkit-audit-testing.md +12 -36
  52. package/.bkit/core/docs/templates/bkit-audit-usability.md +16 -40
  53. package/.bkit/core/docs/templates/bkit-plan.md +97 -226
  54. package/.bkit/core/engine/checks/after/ci-yml.ts +39 -30
  55. package/.bkit/core/engine/checks/after/github.ts +101 -72
  56. package/.bkit/core/engine/checks/after/index.ts +10 -12
  57. package/.bkit/core/engine/checks/after/suppression.ts +8 -5
  58. package/.bkit/core/engine/checks/after/tools.ts +47 -92
  59. package/.bkit/core/engine/checks/before/env.ts +2 -2
  60. package/.bkit/core/engine/checks/before/files.ts +5 -4
  61. package/.bkit/core/engine/checks/before/index.ts +18 -1
  62. package/.bkit/core/engine/checks/before/repo.ts +168 -2
  63. package/.bkit/core/engine/checks/tips/catalogue.ts +16 -5
  64. package/.bkit/core/engine/checks/tips/detect.ts +34 -0
  65. package/.bkit/core/engine/checks/tips/index.ts +10 -7
  66. package/.bkit/core/engine/cli.ts +20 -53
  67. package/.bkit/core/engine/commands/analysis.ts +171 -140
  68. package/.bkit/core/engine/commands/ci/ci.ts +6 -6
  69. package/.bkit/core/engine/commands/comply.ts +77 -103
  70. package/.bkit/core/engine/commands/install/doctor.ts +2 -2
  71. package/.bkit/core/engine/commands/install/install.ts +57 -18
  72. package/.bkit/core/engine/commands/install/uninstall.ts +65 -28
  73. package/.bkit/core/engine/commands/land.ts +18 -12
  74. package/.bkit/core/engine/commands/lib.ts +79 -17
  75. package/.bkit/core/engine/commands/registry.ts +4 -0
  76. package/.bkit/core/engine/commands/setup/setup.ts +7 -7
  77. package/.bkit/core/engine/commands/stats.ts +204 -0
  78. package/.bkit/core/engine/commands/tips.ts +10 -5
  79. package/.bkit/core/engine/commands/workflow/branches.ts +741 -62
  80. package/.bkit/core/engine/commands/workflow/challenge.ts +673 -0
  81. package/.bkit/core/engine/commands/workflow/context.ts +853 -29
  82. package/.bkit/core/engine/commands/workflow/counters.ts +267 -84
  83. package/.bkit/core/engine/commands/workflow/decisions.ts +541 -0
  84. package/.bkit/core/engine/commands/workflow/disk.ts +2 -2
  85. package/.bkit/core/engine/commands/workflow/fids.ts +793 -33
  86. package/.bkit/core/engine/commands/workflow/issues.ts +427 -105
  87. package/.bkit/core/engine/commands/workflow/ledgers.ts +884 -27
  88. package/.bkit/core/engine/commands/workflow/locks.ts +26 -2
  89. package/.bkit/core/engine/commands/workflow/plan-blocks.ts +582 -0
  90. package/.bkit/core/engine/commands/workflow/plan-versions.ts +21 -0
  91. package/.bkit/core/engine/commands/workflow/prs.ts +166 -30
  92. package/.bkit/core/engine/commands/workflow/repo.ts +59 -7
  93. package/.bkit/core/engine/commands/workflow/roadmap.ts +16 -7
  94. package/.bkit/core/engine/commands/workflow/run-facts.ts +501 -0
  95. package/.bkit/core/engine/commands/workflow/runs.ts +179 -49
  96. package/.bkit/core/engine/commands/workflow/runtime.ts +22 -1
  97. package/.bkit/core/engine/commands/workflow/status.ts +142 -29
  98. package/.bkit/core/engine/commands/workflow/step-table.ts +339 -0
  99. package/.bkit/core/engine/commands/workflow/steps.ts +213 -88
  100. package/.bkit/core/engine/commands/workflow/summary.ts +398 -0
  101. package/.bkit/core/engine/commands/workflow/tests.ts +1013 -148
  102. package/.bkit/core/engine/commands/workflow/tracker.ts +1195 -0
  103. package/.bkit/core/engine/commands/workflow/workflows.ts +984 -207
  104. package/.bkit/core/engine/commands/workflow/workstreams.ts +11 -5
  105. package/.bkit/core/engine/commands/workflow/worktrees.ts +276 -22
  106. package/.bkit/core/engine/install/manifest.ts +11 -9
  107. package/.bkit/core/engine/install/modules/cloud.ts +21 -13
  108. package/.bkit/core/engine/install/modules/core.ts +325 -7
  109. package/.bkit/core/engine/install/modules/opencode.ts +2 -2
  110. package/.bkit/core/engine/install/version-file.ts +6 -2
  111. package/.bkit/core/engine/ledgers/migrate.ts +92 -0
  112. package/.bkit/core/engine/ledgers/status.ts +92 -15
  113. package/.bkit/core/engine/ledgers/telemetry.ts +1261 -254
  114. package/.bkit/core/engine/render/hosts.ts +4 -0
  115. package/.bkit/core/engine/render/models.ts +12 -0
  116. package/.bkit/core/engine/shared/branches.ts +4 -1
  117. package/.bkit/core/engine/shared/egress.ts +7 -0
  118. package/.bkit/core/engine/shared/json.ts +25 -7
  119. package/.bkit/core/engine/shared/settings.ts +202 -33
  120. package/.bkit/core/engine/shared/text.ts +361 -0
  121. package/.bkit/core/engine/tools/grammar-density.ts +215 -0
  122. package/.bkit/core/engine/tools/instructions-sources.ts +834 -0
  123. package/.bkit/core/engine/tools/instructions.ts +1751 -0
  124. package/.bkit/core/hooks/gateguard-engine.js +24 -23
  125. package/.bkit/core/hooks/guardrails-shell.js +2 -3
  126. package/.bkit/core/hooks/guardrails-tiers.js +7 -1
  127. package/.bkit/core/hooks/readguard-engine.js +2 -2
  128. package/.bkit/core/prompts/bkit-audit-generate.md +62 -25
  129. package/.bkit/core/prompts/bkit-build-challenge-1.md +40 -17
  130. package/.bkit/core/prompts/bkit-build-challenge-2.md +44 -17
  131. package/.bkit/core/prompts/bkit-build-install-skills.md +26 -13
  132. package/.bkit/core/prompts/bkit-build-plan-convert.md +74 -0
  133. package/.bkit/core/prompts/bkit-build-plan-current.md +26 -13
  134. package/.bkit/core/prompts/bkit-build-plan-execute.md +74 -26
  135. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +64 -23
  136. package/.bkit/core/prompts/bkit-build-plan-verify.md +57 -33
  137. package/.bkit/core/prompts/bkit-debug-abort-handover.md +30 -14
  138. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +34 -14
  139. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +34 -17
  140. package/.bkit/core/prompts/bkit-debug-failure-reproduce.md +26 -13
  141. package/.bkit/core/prompts/bkit-debug-failure-soak.md +31 -16
  142. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +21 -11
  143. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +20 -11
  144. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +20 -11
  145. package/.bkit/core/prompts/bkit-design-generate.md +33 -13
  146. package/.bkit/core/prompts/bkit-design-organise.md +25 -12
  147. package/.bkit/core/prompts/bkit-design-review-1.md +31 -15
  148. package/.bkit/core/prompts/bkit-design-review-2.md +28 -13
  149. package/.bkit/core/prompts/bkit-design-spike.md +30 -13
  150. package/.bkit/core/prompts/bkit-design-update.md +33 -19
  151. package/.bkit/core/prompts/bkit-plan-generate.md +75 -19
  152. package/.bkit/core/prompts/bkit-plan-review-1.md +50 -27
  153. package/.bkit/core/prompts/bkit-plan-review-2.md +59 -28
  154. package/.bkit/core/prompts/bkit-plan-scope-check.md +109 -0
  155. package/.bkit/core/prompts/bkit-plan-update.md +61 -24
  156. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +27 -15
  157. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +31 -16
  158. package/.bkit/core/prompts/bkit-ship-update-docs.md +30 -15
  159. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +24 -14
  160. package/.bkit/core/prompts/bkit-utility-update-decisions.md +32 -14
  161. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +29 -14
  162. package/.bkit/core/prompts/bkit-utility-update-documentation.md +28 -13
  163. package/.bkit/core/prompts/bkit-utility-update-failures.md +31 -14
  164. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +33 -14
  165. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +38 -17
  166. package/.bkit/core/prompts/bkit-utility-update-tracker.md +43 -20
  167. package/.bkit/core/workflows/bkit-auto.md +54 -46
  168. package/.bkit/core/workflows/bkit-build.md +577 -458
  169. package/.bkit/core/workflows/bkit-debug.md +348 -333
  170. package/.bkit/core/workflows/bkit-design.md +201 -237
  171. package/.bkit/core/workflows/bkit-plan.md +210 -321
  172. package/.bkit/core/workflows/bkit-ship.md +328 -278
  173. package/.bkit/shared/.bkit/.env.example +2 -2
  174. package/.bkit/shared/.claude/settings.json +11 -0
  175. package/.bkit/shared/.cursor/mcp.json +1 -1
  176. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +1 -1
  177. package/.bkit/shared/.gitattributes +1 -1
  178. package/.bkit/shared/.mcp.json +1 -1
  179. package/.bkit/shared/.opencode/opencode.json +11 -0
  180. package/.bkit/shared/CLAUDE.md +2 -2
  181. package/.bkit/shared/GEMINI.md +2 -2
  182. package/.bkit/shared/docs/architecture.md +1 -1
  183. package/.bkit/shared/docs/data-schema.md +1 -1
  184. package/.bkit/shared/docs/deployments.md +16 -28
  185. package/.bkit/shared/docs/design.md +1 -1
  186. package/.bkit/shared/docs/noise.md +1 -1
  187. package/.bkit/shared/docs/observability.md +2 -2
  188. package/.bkit/shared/docs/security.md +1 -1
  189. package/.bkit/shared/docs/setup.md +1 -1
  190. package/.bkit/shared/docs/technology.md +1 -1
  191. package/.bkit/shared/docs/testing.md +27 -10
  192. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +1 -1
  193. package/.bkit/templates/.github/ISSUE_TEMPLATE/bkit-change.yml +26 -5
  194. package/.bkit/templates/.github/workflows/bkit-ci.yml +22 -84
  195. package/.bkit/templates/.github/workflows/bkit-cloud.yml +21 -19
  196. package/.bkit/templates/.husky/pre-push +52 -13
  197. package/.bkit/templates/.prettierignore +7 -0
  198. package/.bkit/templates/scripts/ci/bkit-local-stack-lock.sh +194 -0
  199. package/.bkit/templates/scripts/ci/check-capstone.mjs +2 -4
  200. package/.bkit/templates/scripts/ci/check-capstone.test.mjs +4 -23
  201. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +104 -23
  202. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +103 -6
  203. package/.bkit/templates/scripts/cleanup/bkit-disk-prune.mjs +1 -1
  204. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +3 -1
  205. package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +49 -29
  206. package/CHANGELOG.md +142 -0
  207. package/README.md +58 -34
  208. package/dist/checks/after/ci-yml.js +39 -29
  209. package/dist/checks/after/github.js +99 -72
  210. package/dist/checks/after/index.js +11 -13
  211. package/dist/checks/after/suppression.js +8 -5
  212. package/dist/checks/after/tools.js +40 -83
  213. package/dist/checks/before/env.js +2 -2
  214. package/dist/checks/before/files.js +5 -3
  215. package/dist/checks/before/index.js +15 -2
  216. package/dist/checks/before/repo.js +163 -2
  217. package/dist/checks/tips/catalogue.js +14 -5
  218. package/dist/checks/tips/detect.js +32 -0
  219. package/dist/checks/tips/index.js +7 -5
  220. package/dist/cli.js +19 -47
  221. package/dist/commands/analysis.js +109 -100
  222. package/dist/commands/ci/ci.js +6 -6
  223. package/dist/commands/comply.js +54 -91
  224. package/dist/commands/install/doctor.js +2 -2
  225. package/dist/commands/install/install.js +50 -19
  226. package/dist/commands/install/uninstall.js +59 -28
  227. package/dist/commands/land.js +16 -12
  228. package/dist/commands/lib.js +51 -16
  229. package/dist/commands/registry.js +4 -0
  230. package/dist/commands/setup/setup.js +7 -7
  231. package/dist/commands/stats.js +136 -0
  232. package/dist/commands/tips.js +7 -3
  233. package/dist/commands/workflow/branches.js +656 -56
  234. package/dist/commands/workflow/challenge.js +556 -0
  235. package/dist/commands/workflow/context.js +709 -30
  236. package/dist/commands/workflow/counters.js +208 -75
  237. package/dist/commands/workflow/decisions.js +441 -0
  238. package/dist/commands/workflow/disk.js +2 -2
  239. package/dist/commands/workflow/fids.js +689 -33
  240. package/dist/commands/workflow/issues.js +362 -99
  241. package/dist/commands/workflow/ledgers.js +762 -27
  242. package/dist/commands/workflow/locks.js +24 -2
  243. package/dist/commands/workflow/plan-blocks.js +437 -0
  244. package/dist/commands/workflow/plan-versions.js +22 -0
  245. package/dist/commands/workflow/prs.js +142 -32
  246. package/dist/commands/workflow/repo.js +52 -7
  247. package/dist/commands/workflow/roadmap.js +9 -7
  248. package/dist/commands/workflow/run-facts.js +426 -0
  249. package/dist/commands/workflow/runs.js +144 -43
  250. package/dist/commands/workflow/runtime.js +12 -1
  251. package/dist/commands/workflow/status.js +130 -29
  252. package/dist/commands/workflow/step-table.js +276 -0
  253. package/dist/commands/workflow/steps.js +171 -80
  254. package/dist/commands/workflow/summary.js +275 -0
  255. package/dist/commands/workflow/tests.js +834 -136
  256. package/dist/commands/workflow/tracker.js +983 -0
  257. package/dist/commands/workflow/workflows.js +834 -195
  258. package/dist/commands/workflow/workstreams.js +11 -5
  259. package/dist/commands/workflow/worktrees.js +221 -22
  260. package/dist/install/manifest.js +11 -9
  261. package/dist/install/modules/cloud.js +22 -13
  262. package/dist/install/modules/core.js +326 -7
  263. package/dist/install/modules/opencode.js +2 -2
  264. package/dist/install/version-file.js +6 -2
  265. package/dist/ledgers/migrate.js +81 -0
  266. package/dist/ledgers/status.js +61 -8
  267. package/dist/ledgers/telemetry.js +905 -124
  268. package/dist/render/hosts.js +4 -0
  269. package/dist/render/models.js +12 -0
  270. package/dist/shared/branches.js +3 -1
  271. package/dist/shared/egress.js +7 -0
  272. package/dist/shared/json.js +20 -7
  273. package/dist/shared/settings.js +147 -26
  274. package/dist/shared/text.js +333 -0
  275. package/dist/tools/grammar-density.js +183 -0
  276. package/dist/tools/instructions-sources.js +721 -0
  277. package/dist/tools/instructions.js +1579 -0
  278. package/package.json +114 -23
  279. package/.bkit/core/engine/commands/harvest.ts +0 -459
  280. package/.bkit/core/engine/tools/wording.ts +0 -748
  281. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +0 -69
  282. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +0 -71
  283. package/.bkit/core/prompts/bkit-build-challenge-tests.md +0 -74
  284. package/.bkit/core/prompts/bkit-build-summary.md +0 -94
  285. package/.bkit/core/prompts/bkit-debug-summary.md +0 -96
  286. package/.bkit/core/prompts/bkit-design-summary.md +0 -107
  287. package/.bkit/core/prompts/bkit-plan-complexity-check.md +0 -67
  288. package/.bkit/core/prompts/bkit-plan-complexity-split.md +0 -88
  289. package/.bkit/core/prompts/bkit-plan-review-3.md +0 -93
  290. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +0 -85
  291. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +0 -85
  292. package/.bkit/core/prompts/bkit-plan-summary.md +0 -107
  293. package/.bkit/core/prompts/bkit-ship-summary.md +0 -78
  294. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.mjs +0 -138
  295. package/.bkit/templates/scripts/ci/lanes/check-tree-cache.test.mjs +0 -181
  296. package/dist/commands/harvest.js +0 -353
  297. package/dist/tools/wording.js +0 -680
@@ -0,0 +1,556 @@
1
+ // bkit challenge merge — fold the build challenge reports into the plan.
2
+ //
3
+ // Each reviewer writes its findings as task blocks (`<!-- bkit:task N start -->`) under
4
+ // `## Findings Log`, read through `parsePlanBlocks` like the plan's own tasks. The merge
5
+ // dedupes them by location, drops the ones an earlier Decision Pause accepted, writes the
6
+ // CRITICAL / HIGH / MEDIUM ones into the plan as task blocks in new last groups (at most
7
+ // `bkit.workflows.tasks.maxPerGroup` tasks and `maxTestsPerGroup` tests each) and writes each LOW one
8
+ // as a deferral row. Task numbers carry on from the highest in the plan, so they stay
9
+ // unique. A finding at the location and severity of an earlier task that is still open
10
+ // reruns that task (its Round value gains this round) rather than adding a twin; one whose
11
+ // earlier task is done from an earlier round is a new task. It then names the route:
12
+ // `fix` (run the tasks), `pause` (ask the owner) or `none`. More than `maxChallengeTasks`
13
+ // new tasks in one merge writes nothing and pauses. The plan is checked in memory before
14
+ // it is written, so a refused merge leaves every file as it was. A re-run with the same
15
+ // reports appends nothing.
16
+ //
17
+ // bkit challenge gate — size the run's diff before the reviewers start. A small change
18
+ // (under CHALLENGE_SMALL lines and files, `docs/plans/**` excluded) runs the security
19
+ // reviewer alone; a large one runs both. With the default base it fetches origin dev
20
+ // first; offline it measures against the local origin/dev. Each pass writes a
21
+ // `challenge-gate` status row.
22
+ import * as fs from "node:fs";
23
+ import * as path from "node:path";
24
+ import { appendLine, statusTimestamp } from "../../ledgers/status.js";
25
+ import { CommandError, DEV, EXIT, git, runGit } from "../lib.js";
26
+ import { DIFF_BASE, EXIT_BASE, diffNumstat } from "./context.js";
27
+ import { EXIT_ROW_REFUSED, EXIT_STAGE, appendLedgerRows } from "./ledgers.js";
28
+ import { parsePlanBlocks } from "./plan-blocks.js";
29
+ import { readBkitConfig } from "../../shared/settings.js";
30
+ import { checkPlanText, planCaps, readTestFirst } from "./tests.js";
31
+ import { ledgerRows } from "./workflows.js";
32
+ /**
33
+ * The most tasks one merge writes: four full groups. More fresh findings than this write
34
+ * nothing and route to the Decision Pause, where the owner picks what to fix.
35
+ */
36
+ export const maxChallengeTasks = (caps) => 4 * caps.maxPerGroup;
37
+ /** Exit code: a `--report` file does not exist. */
38
+ export const EXIT_NO_REPORT = 21;
39
+ /** Exit code: a report is not in task-block form. */
40
+ export const EXIT_OLD_FORMAT = 22;
41
+ /** Exit code: the merged plan fails the plan check; nothing was written. */
42
+ export const EXIT_PLAN_CHECK = 23;
43
+ /** A diff under both limits is small: the security reviewer (challenge-2) runs alone. */
44
+ export const CHALLENGE_SMALL = { lines: 300, files: 10 };
45
+ /** Size a diff against `limit`: small when it changes fewer lines and fewer files. */
46
+ export function challengeGate(stat, limit = CHALLENGE_SMALL) {
47
+ const small = stat.linesChanged < limit.lines && stat.filesChanged < limit.files;
48
+ return small
49
+ ? { size: "small", skipped: true, agents: ["bkit-build-challenge-2"] }
50
+ : {
51
+ size: "large",
52
+ skipped: false,
53
+ agents: ["bkit-build-challenge-1", "bkit-build-challenge-2"],
54
+ };
55
+ }
56
+ const SEVERITY_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW"];
57
+ const rank = (s) => SEVERITY_ORDER.indexOf(s);
58
+ /** A finding block's line `**Severity:** … · **Class:** … · **Fixable:** … · **Location:** …`. */
59
+ const META = /\*\*(Severity|Class|Fixable|Location|Round):\*\*/g;
60
+ /** The Severity / Class / Fixable / Location / Round values of a task block's meta line. */
61
+ function metaFields(text) {
62
+ const values = new Map();
63
+ for (const line of text.split("\n")) {
64
+ const hits = [...line.matchAll(META)];
65
+ hits.forEach((h, i) => {
66
+ const value = line.slice(h.index + h[0].length, hits[i + 1]?.index);
67
+ values.set(h[1], value.trim().replace(/[\s·]+$/, ""));
68
+ });
69
+ }
70
+ return values;
71
+ }
72
+ /** A task block's TEST FIRST entries, each the sub-bullet's text as written. */
73
+ function testEntries(block) {
74
+ const lines = block.text.split("\n");
75
+ const at = (line) => lines[line - block.line].trim()
76
+ .replace(/^- /, "")
77
+ .replace(/^\*\*TEST FIRST:\*\*\s*/, "");
78
+ const tf = block.testFirst;
79
+ if (tf === undefined)
80
+ return [];
81
+ return [...tf.tests.map((t) => t.line), ...tf.malformed].sort((a, b) => a - b).map(at);
82
+ }
83
+ /** `path:line` from a location value, the path repo-relative and normalised; null when none. */
84
+ export function normalizeLocation(raw, cwd) {
85
+ const m = /`?([^`\s]+?):(\d+)/.exec(raw);
86
+ if (!m)
87
+ return null;
88
+ let p = m[1].replace(/\\/g, "/");
89
+ if (path.isAbsolute(p))
90
+ p = path.relative(cwd, p).split(path.sep).join("/");
91
+ p = path.posix.normalize(p).replace(/^\.\//, "");
92
+ return `${p}:${Number(m[2])}`;
93
+ }
94
+ /** The header line `{name}: value` above `<!-- verdict:end -->`, or undefined. */
95
+ const headerValue = (text, name) => new RegExp(`^${name}:\\s*(\\S+)`, "m").exec(text.split("<!-- verdict:end -->")[0])?.[1];
96
+ /** The `## Findings Log` section of a report and its first line's number (1-based); "" when none. */
97
+ function findingsLog(text) {
98
+ const lines = text.split("\n");
99
+ const start = lines.findIndex((l) => /^## Findings Log\b/.test(l));
100
+ if (start < 0)
101
+ return { body: "", line: 0 };
102
+ const end = lines.findIndex((l, i) => i > start && /^## /.test(l));
103
+ return { body: lines.slice(start + 1, end < 0 ? undefined : end).join("\n"), line: start + 2 };
104
+ }
105
+ /** The group wrapper a Findings Log gets when the reviewer wrote task blocks only. */
106
+ const WRAP = ["<!-- bkit:group 1 start -->", "### GROUP 1: Findings"];
107
+ /**
108
+ * One report's findings: each task block under `## Findings Log` (read through
109
+ * `parsePlanBlocks`; a log with no group marker is read as one group) with its
110
+ * `Severity`, `Fixable` and `Location` line and its DONE WHEN field. Refused (exit 22):
111
+ * a header naming findings with no task block, a block format error (old `**Task N:**`
112
+ * task lines included), or a block missing one of those fields.
113
+ */
114
+ export function parseFindings(text, source, cwd) {
115
+ const log = findingsLog(text);
116
+ const wrapped = !/<!--\s*bkit:group\s/.test(log.body);
117
+ const body = wrapped ? [...WRAP, log.body, "<!-- bkit:group 1 end -->"].join("\n") : log.body;
118
+ const blocks = parsePlanBlocks(body);
119
+ const fileLine = (line) => log.line + line - 1 - (wrapped ? WRAP.length : 0);
120
+ const notBlocks = (why) => new CommandError(EXIT_OLD_FORMAT, `${source}: ${why} — the report is not in task-block form; re-run the challenge`);
121
+ const error = blocks.errors[0];
122
+ if (error !== undefined)
123
+ throw notBlocks(`line ${fileLine(error.line)}: ${error.message}`);
124
+ const verdict = headerValue(text, "Verdict");
125
+ const failures = Number(headerValue(text, "Failures") ?? 0);
126
+ if (blocks.tasks.length === 0 && (verdict !== "PASS" || failures > 0))
127
+ throw notBlocks(`verdict ${verdict ?? "missing"} but no task block under ## Findings Log`);
128
+ return blocks.tasks.map((block) => {
129
+ const values = metaFields(block.text);
130
+ const refuse = (why) => new CommandError(EXIT_OLD_FORMAT, `${source}: finding TASK ${block.task} ${why}`);
131
+ const severity = values.get("Severity")?.split(/\s/)[0];
132
+ if (!SEVERITY_ORDER.includes(severity))
133
+ throw refuse("has no **Severity:** CRITICAL|HIGH|MEDIUM|LOW");
134
+ const fixable = values.get("Fixable")?.split(/\s/)[0];
135
+ if (fixable !== "true" && fixable !== "false")
136
+ throw refuse("has no **Fixable:** true|false");
137
+ const location = normalizeLocation(values.get("Location") ?? "", cwd);
138
+ if (location === null)
139
+ throw refuse("has no **Location:** path:line");
140
+ const doneWhen = block.doneWhen ?? "";
141
+ if (doneWhen === "")
142
+ throw refuse("has no **DONE WHEN:**");
143
+ const cls = values.get("Class")?.split(/\s/)[0];
144
+ return {
145
+ severity: severity,
146
+ ...(cls ? { cls } : {}),
147
+ fixable: fixable === "true",
148
+ location,
149
+ title: block.title || `Challenge finding at ${location}`,
150
+ doneWhen,
151
+ tests: testEntries(block),
152
+ };
153
+ });
154
+ }
155
+ /**
156
+ * The reports' findings as one list, deduped by location: the worse severity's
157
+ * finding wins, and it is not fixable when either says so. Findings at an accepted
158
+ * location are dropped and counted.
159
+ */
160
+ export function mergeFindings(reports, accepted) {
161
+ const byLocation = new Map();
162
+ for (const f of reports.flat()) {
163
+ const prior = byLocation.get(f.location);
164
+ if (prior === undefined) {
165
+ byLocation.set(f.location, f);
166
+ continue;
167
+ }
168
+ const worse = rank(f.severity) < rank(prior.severity) ? f : prior;
169
+ byLocation.set(f.location, { ...worse, fixable: prior.fixable && f.fixable });
170
+ }
171
+ const all = [...byLocation.values()];
172
+ const findings = all.filter((f) => !accepted.has(f.location));
173
+ return { findings, dropped: all.length - findings.length };
174
+ }
175
+ /**
176
+ * Locations named in a `Decision: Accept` item of any `build-decision-*.md` in `logDir`. An
177
+ * `Accept (assumed)` counts too, so the next round does not raise it again; the build summary
178
+ * and ship report it as assumed.
179
+ */
180
+ export function acceptedLocations(logDir, cwd) {
181
+ const out = new Set();
182
+ const files = fs.existsSync(logDir)
183
+ ? fs.readdirSync(logDir).filter((f) => /^build-decision-.*\.md$/.test(f))
184
+ : [];
185
+ for (const file of files) {
186
+ const items = fs.readFileSync(path.join(logDir, file), "utf-8").split(/^(?=\*\*Q\d+)/m);
187
+ for (const item of items.slice(1)) {
188
+ if (!/^Decision:\s*Accept\b/m.test(item))
189
+ continue;
190
+ // `path:line`, the path with or without an extension (`src/a.ts:10`, `Makefile:12`).
191
+ for (const m of item.matchAll(/(?<![\w@./-])[\w@./-]*[A-Za-z_][\w@./-]*:\d+/g)) {
192
+ const loc = normalizeLocation(m[0], cwd);
193
+ if (loc !== null)
194
+ out.add(loc);
195
+ }
196
+ }
197
+ }
198
+ return out;
199
+ }
200
+ /** One finding's task block. */
201
+ const taskBlock = (n, f, round) => [
202
+ `<!-- bkit:task ${n} start -->`,
203
+ `- [ ] **TASK ${n}:** ${f.title}`,
204
+ ` **Severity:** ${f.severity} · ${f.cls ? `**Class:** ${f.cls} · ` : ""}**Fixable:** ${f.fixable} · **Location:** \`${f.location}\` · **Round:** ${round}`,
205
+ ` - **DONE WHEN:** ${f.doneWhen}`,
206
+ " - **TEST FIRST:**",
207
+ ...f.tests.map((e) => ` - ${e}`),
208
+ `<!-- bkit:task ${n} end -->`,
209
+ ];
210
+ /**
211
+ * The findings as groups of task blocks, numbered from `firstTask` and `firstGroup`: a
212
+ * group closes at `caps.maxPerGroup` tasks, or before a task that would take it past
213
+ * `caps.maxTestsPerGroup` tests.
214
+ */
215
+ function findingGroups(findings, firstTask, firstGroup, round, caps) {
216
+ const chunks = [];
217
+ let tests = 0;
218
+ for (const f of findings) {
219
+ const n = f.tests.length;
220
+ const open = chunks.at(-1);
221
+ if (open === undefined ||
222
+ open.length >= caps.maxPerGroup ||
223
+ tests + n > caps.maxTestsPerGroup) {
224
+ chunks.push([f]);
225
+ tests = n;
226
+ }
227
+ else {
228
+ open.push(f);
229
+ tests += n;
230
+ }
231
+ }
232
+ const tasks = findings.map((_, i) => firstTask + i);
233
+ let next = firstTask;
234
+ const lines = chunks.flatMap((chunk, g) => [
235
+ ...(g === 0 ? [] : [""]),
236
+ `<!-- bkit:group ${firstGroup + g} start -->`,
237
+ `### GROUP ${firstGroup + g}: Challenge round ${round} findings`,
238
+ ...chunk.flatMap((f) => taskBlock(next++, f, round)),
239
+ `<!-- bkit:group ${firstGroup + g} end -->`,
240
+ ]);
241
+ return { lines, tasks };
242
+ }
243
+ /**
244
+ * `plan` with the findings written as new groups after its last group (at the end when
245
+ * it has none), tasks numbered from `firstTask`, grouped within `caps`.
246
+ */
247
+ export function appendTasks(plan, findings, round, firstTask, caps) {
248
+ const blocks = parsePlanBlocks(plan);
249
+ const firstGroup = Math.max(0, ...blocks.groups.map((g) => g.group)) + 1;
250
+ const { lines: block, tasks } = findingGroups(findings, firstTask, firstGroup, round, caps);
251
+ const last = blocks.groups.at(-1);
252
+ if (last === undefined) {
253
+ const body = plan.replace(/\n*$/, "");
254
+ const from = body.split("\n").length + 2;
255
+ return {
256
+ text: `${body}\n\n${block.join("\n")}\n`,
257
+ tasks,
258
+ written: { from, to: from + block.length - 1 },
259
+ };
260
+ }
261
+ const lines = plan.split("\n");
262
+ lines.splice(last.end, 0, "", ...block);
263
+ const from = last.end + 2;
264
+ return { text: lines.join("\n"), tasks, written: { from, to: from + block.length - 1 } };
265
+ }
266
+ /**
267
+ * Why the merged `text` may not be written: a plan-check problem on the lines the merge
268
+ * wrote (a malformed block, a group or task over its cap), or a written task whose
269
+ * TEST FIRST names no test.
270
+ */
271
+ function planProblems(text, written, added, caps) {
272
+ const problems = checkPlanText(text, caps)
273
+ .problems.filter((p) => p.line >= written.from && p.line <= written.to)
274
+ .map((p) => `line ${p.line}: ${p.message}`);
275
+ const kinds = readTestFirst(text);
276
+ for (const n of added) {
277
+ const kind = kinds.find((s) => s.task === n)?.kind ?? "missing";
278
+ if (kind !== "test")
279
+ problems.push(`TASK ${n}: its TEST FIRST is ${kind}; every finding names a test`);
280
+ }
281
+ return problems;
282
+ }
283
+ /** LOW findings as `docs/deferrals.jsonl` rows, keyed by FID and location. */
284
+ export function lowDeferrals(fid, findings) {
285
+ return findings
286
+ .filter((f) => f.severity === "LOW")
287
+ .map((f) => ({
288
+ kind: "deferral",
289
+ key: `${fid}-challenge-low-${f.location.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "")}`.toLowerCase(),
290
+ type: "issue",
291
+ category: "correctness",
292
+ severity: "LOW",
293
+ reason: "low-severity",
294
+ summary: f.title,
295
+ description: `LOW build challenge finding at ${f.location}: ${f.title}. Done when: ${f.doneWhen}`,
296
+ source: f.location,
297
+ references: [fid],
298
+ by: { workflow: "build", step: "build-challenge" },
299
+ }));
300
+ }
301
+ /** The key a finding and an earlier merged task share: location and severity. */
302
+ const findingKey = (location, severity) => `${location}|${severity}`;
303
+ /** Tasks the merge appended earlier, by `findingKey`, in plan order. */
304
+ function mergedTasks(plan, cwd) {
305
+ const out = new Map();
306
+ for (const t of parsePlanBlocks(plan).tasks) {
307
+ const values = metaFields(t.text);
308
+ const loc = normalizeLocation(values.get("Location") ?? "", cwd);
309
+ const sev = values.get("Severity")?.split(/\s/)[0];
310
+ const rounds = (values.get("Round") ?? "")
311
+ .split(/[\s,]+/)
312
+ .filter((r) => /^\d+$/.test(r))
313
+ .map(Number);
314
+ if (loc === null || sev === undefined || rounds.length === 0)
315
+ continue;
316
+ const key = findingKey(loc, sev);
317
+ out.set(key, [
318
+ ...(out.get(key) ?? []),
319
+ { task: t.task, done: t.done, rounds, line: t.line, end: t.end },
320
+ ]);
321
+ }
322
+ return out;
323
+ }
324
+ /** `plan` with `round` added to the `**Round:**` value of each task in `tasks`. */
325
+ function stampRound(plan, tasks, round) {
326
+ const lines = plan.split("\n");
327
+ for (const t of tasks)
328
+ for (let i = t.line - 1; i < t.end; i++)
329
+ lines[i] = lines[i].replace(/(\*\*Round:\*\*\s*)([\d,\s]*\d)/, (_, label) => `${label}${[...t.rounds, round].join(", ")}`);
330
+ return lines.join("\n");
331
+ }
332
+ /** Write `text` to `file` through a temp file renamed over it. */
333
+ function writeAtomic(file, text) {
334
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.tmp`);
335
+ fs.writeFileSync(tmp, text);
336
+ fs.renameSync(tmp, file);
337
+ }
338
+ export const challengeCommand = {
339
+ noun: "challenge",
340
+ summary: "Size the build challenge (gate) and fold its reports into the plan (merge): findings become plan tasks or LOW deferrals.",
341
+ verbs: {
342
+ gate: {
343
+ summary: "Size the run's diff ({base}...HEAD, docs/plans/** excluded) and name the reviewers: small runs challenge-2 alone, large runs both. Writes a challenge-gate status row.",
344
+ flags: [
345
+ {
346
+ name: "file",
347
+ type: "string",
348
+ required: true,
349
+ help: "the run's status.jsonl; the challenge-gate row is appended to it",
350
+ },
351
+ {
352
+ name: "base",
353
+ type: "string",
354
+ help: `merge base (default ${DIFF_BASE}, fetched first; a failed fetch is logged, not fatal)`,
355
+ },
356
+ ],
357
+ output: {
358
+ size: `small (under ${CHALLENGE_SMALL.lines} lines and ${CHALLENGE_SMALL.files} files) or large`,
359
+ skipped: "true when challenge-1 is left out",
360
+ agents: "comma-separated reviewers to run",
361
+ linesChanged: "lines added + deleted",
362
+ filesChanged: "files in the diff",
363
+ range: "the range measured ({base}...HEAD)",
364
+ },
365
+ exitCodes: { [EXIT_BASE]: "--base does not name a commit" },
366
+ run: (ctx) => {
367
+ const base = typeof ctx.flags.base === "string" ? ctx.flags.base : DIFF_BASE;
368
+ if (base === DIFF_BASE) {
369
+ const res = runGit(ctx.cwd, ["fetch", "origin", DEV]);
370
+ if (!res.ok)
371
+ ctx.log(`git fetch origin dev failed — measuring against the last fetch: ${res.stderr}`);
372
+ }
373
+ if (git(ctx.cwd, ["rev-parse", "-q", "--verify", `${base}^{commit}`]) === null)
374
+ throw new CommandError(EXIT_BASE, `--base ${base} does not name a commit (fetch origin)`);
375
+ const range = `${base}...HEAD`;
376
+ const { stat } = diffNumstat(ctx.cwd, range);
377
+ const gate = challengeGate(stat);
378
+ const file = path.resolve(ctx.cwd, String(ctx.flags.file));
379
+ fs.appendFileSync(file, appendLine({
380
+ type: "challenge-gate",
381
+ workflow: "build",
382
+ at: statusTimestamp(),
383
+ range,
384
+ linesChanged: stat.linesChanged,
385
+ filesChanged: stat.filesChanged,
386
+ size: gate.size,
387
+ limit: { ...CHALLENGE_SMALL },
388
+ agents: gate.agents,
389
+ skipped: gate.skipped,
390
+ }));
391
+ ctx.emit({
392
+ size: gate.size,
393
+ skipped: gate.skipped,
394
+ agents: gate.agents.join(","),
395
+ linesChanged: stat.linesChanged,
396
+ filesChanged: stat.filesChanged,
397
+ range,
398
+ });
399
+ ctx.log(`challenge gate: ${gate.size} — ${stat.linesChanged} lines, ${stat.filesChanged} files; run ${gate.agents.join(", ")}`);
400
+ return EXIT.OK;
401
+ },
402
+ },
403
+ merge: {
404
+ summary: "Merge the challenge reports' findings into the plan as tasks (LOW → deferral rows); prints the route: fix | pause | none.",
405
+ flags: [
406
+ {
407
+ name: "report",
408
+ type: "string",
409
+ required: true,
410
+ repeatable: true,
411
+ help: "a challenge report (`build-challenge-{1,2}.md`); findings are task blocks under `## Findings Log`",
412
+ },
413
+ {
414
+ name: "plan",
415
+ type: "string",
416
+ required: true,
417
+ help: "the plan file (`{FID}-plan.md`) the tasks are appended to",
418
+ },
419
+ {
420
+ name: "log",
421
+ type: "string",
422
+ required: true,
423
+ help: "the run's log folder `docs/plans/{YYYYMM}/logs/{FID}`; its `build-decision-*.md` accepts drop findings",
424
+ },
425
+ {
426
+ name: "round",
427
+ type: "string",
428
+ required: true,
429
+ help: "challenge round, 1 up to bkit.workflows.build.challenge.maxAttempts; any task from the last round routes to pause",
430
+ },
431
+ ],
432
+ output: {
433
+ route: "fix (tasks to run), pause (a task is not fixable, the last round left tasks, or more than 4 x `bkit.workflows.tasks.maxPerGroup` new tasks) or none (nothing to run)",
434
+ fixTasks: "comma-separated task numbers in `plan` this round runs: every task reopened, then every task appended; empty when none",
435
+ appended: "how many tasks this run wrote",
436
+ reopened: "comma-separated numbers of open earlier tasks a finding reported again (same location and severity); this round is added to their **Round:** value; empty when none",
437
+ deferred: "`docs/deferrals.jsonl` rows this run wrote (one per LOW finding not already deferred)",
438
+ dropped: "findings at a location a Decision Pause accepted",
439
+ plan: "the plan file the tasks are in (repo-relative as given)",
440
+ round: "the round, as given",
441
+ overflow: `set only when the findings would add more than 4 x \`bkit.workflows.tasks.maxPerGroup\` tasks: how many new CRITICAL / HIGH / MEDIUM findings the Decision Pause must choose from; nothing was written`,
442
+ problems: "on exit 23: why the merged plan failed the plan check",
443
+ },
444
+ exitCodes: {
445
+ [EXIT_STAGE]: "docs/deferrals.jsonl could not be written",
446
+ [EXIT_ROW_REFUSED]: "a LOW deferral row was refused by the ledger check",
447
+ [EXIT_NO_REPORT]: "a --report file does not exist",
448
+ [EXIT_OLD_FORMAT]: "a report is not in task-block form: findings but no task block, a block format error, or a block missing Severity, Fixable, Location or DONE WHEN",
449
+ [EXIT_PLAN_CHECK]: "the merged plan fails the plan check; no file was changed",
450
+ },
451
+ run: (ctx) => {
452
+ const round = String(ctx.flags.round);
453
+ const top = git(ctx.cwd, ["rev-parse", "--show-toplevel"]) ?? ctx.cwd;
454
+ const maxRounds = readBkitConfig(top).asks["build.challenge"].max;
455
+ if (!/^[1-9][0-9]*$/.test(round) || Number(round) > maxRounds)
456
+ throw new CommandError(EXIT.USAGE, `--round must be 1 to ${maxRounds} (bkit.workflows.build.challenge.maxAttempts), got "${round}"`);
457
+ const roundN = Number(round);
458
+ const abs = (p) => path.resolve(ctx.cwd, p);
459
+ const rel = (p) => path.relative(ctx.cwd, p).split(path.sep).join("/");
460
+ const planArg = String(ctx.flags.plan);
461
+ const logDir = abs(String(ctx.flags.log));
462
+ const fid = path.basename(logDir);
463
+ const reports = ctx.flags.report.map((r) => {
464
+ if (!fs.existsSync(abs(r)))
465
+ throw new CommandError(EXIT_NO_REPORT, `--report ${r} does not exist`);
466
+ return parseFindings(fs.readFileSync(abs(r), "utf-8"), r, ctx.cwd);
467
+ });
468
+ const { findings, dropped } = mergeFindings(reports, acceptedLocations(logDir, ctx.cwd));
469
+ const tasks = findings
470
+ .filter((f) => f.severity !== "LOW")
471
+ .sort((a, b) => rank(a.severity) - rank(b.severity));
472
+ const low = findings.filter((f) => f.severity === "LOW");
473
+ const planAbs = abs(planArg);
474
+ if (!fs.existsSync(planAbs))
475
+ throw new CommandError(EXIT.USAGE, `--plan ${planArg} does not exist`);
476
+ const before = fs.readFileSync(planAbs, "utf-8");
477
+ // Each finding against the earlier tasks at its location and severity: an open one
478
+ // runs again; a done one from this round is this round's re-run and is left alone;
479
+ // otherwise (none, or every match done in an earlier round: the fix did not hold)
480
+ // the finding is a new task.
481
+ const merged = mergedTasks(before, ctx.cwd);
482
+ const fresh = [];
483
+ const open = [];
484
+ for (const f of tasks) {
485
+ const earlier = merged.get(findingKey(f.location, f.severity)) ?? [];
486
+ const at = earlier.find((t) => !t.done);
487
+ if (at !== undefined)
488
+ open.push({ f, at });
489
+ else if (!earlier.some((t) => t.rounds.includes(roundN)))
490
+ fresh.push(f);
491
+ }
492
+ // More findings than one merge may add: write nothing, the owner picks at the pause.
493
+ const caps = planCaps(ctx.cwd);
494
+ const most = maxChallengeTasks(caps);
495
+ if (fresh.length > most) {
496
+ ctx.emit({
497
+ route: "pause",
498
+ fixTasks: "",
499
+ appended: 0,
500
+ reopened: "",
501
+ deferred: 0,
502
+ dropped,
503
+ overflow: fresh.length,
504
+ plan: rel(planAbs),
505
+ round: roundN,
506
+ });
507
+ ctx.log(`challenge merge: pause — ${fresh.length} task(s) exceed what one merge adds (${most}); nothing written`);
508
+ return EXIT.OK;
509
+ }
510
+ // Reopened tasks carry this round in their Round value; the plan's lines keep their count.
511
+ const reopened = [...new Map(open.map((x) => [x.at.task, x.at])).values()];
512
+ const stamped = stampRound(before, reopened.filter((t) => !t.rounds.includes(roundN)), roundN);
513
+ let fixTasks = reopened.map((t) => t.task);
514
+ let after = stamped;
515
+ if (fresh.length > 0) {
516
+ const firstTask = Math.max(0, ...parsePlanBlocks(before).tasks.map((t) => t.task)) + 1;
517
+ const { text, tasks: added, written, } = appendTasks(stamped, fresh, roundN, firstTask, caps);
518
+ const problems = planProblems(text, written, added, caps);
519
+ if (problems.length > 0) {
520
+ ctx.emit({ plan: rel(planAbs), problems });
521
+ ctx.log(`challenge merge: plan check failed — ${problems.join("; ")}`);
522
+ return EXIT_PLAN_CHECK;
523
+ }
524
+ after = text;
525
+ fixTasks = [...fixTasks, ...added];
526
+ }
527
+ // Deferrals before the plan: a refused or failed append changes nothing, and a re-run
528
+ // after a failed plan write skips the rows already appended (same key).
529
+ const known = new Set(ledgerRows(path.join(top, "docs", "deferrals.jsonl")).map((r) => String(r.key)));
530
+ const rows = lowDeferrals(fid, low).filter((r) => !known.has(String(r.key)));
531
+ if (rows.length > 0)
532
+ appendLedgerRows(top, "deferrals", rows);
533
+ if (after !== before)
534
+ writeAtomic(planAbs, after);
535
+ const running = [...fresh, ...open.map((x) => x.f)];
536
+ const route = fixTasks.length === 0
537
+ ? "none"
538
+ : roundN >= maxRounds || running.some((f) => !f.fixable)
539
+ ? "pause"
540
+ : "fix";
541
+ ctx.emit({
542
+ route,
543
+ fixTasks: fixTasks.join(","),
544
+ appended: fresh.length,
545
+ reopened: reopened.map((t) => t.task).join(","),
546
+ deferred: rows.length,
547
+ dropped,
548
+ plan: rel(planAbs),
549
+ round: roundN,
550
+ });
551
+ ctx.log(`challenge merge: ${route} — ${fresh.length} task(s) appended to ${rel(planAbs)}, ${reopened.length} open task(s) reported again, ${rows.length} LOW deferral row(s) written, ${dropped} accepted`);
552
+ return EXIT.OK;
553
+ },
554
+ },
555
+ },
556
+ };