akm-cli 0.6.1 → 0.7.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 (333) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/dist/{cli.js → src/cli.js} +712 -34
  3. package/dist/{commands → src/commands}/config-cli.js +47 -4
  4. package/dist/src/commands/distill.js +283 -0
  5. package/dist/src/commands/events.js +108 -0
  6. package/dist/src/commands/history.js +191 -0
  7. package/dist/{commands → src/commands}/installed-stashes.js +1 -1
  8. package/dist/src/commands/proposal.js +119 -0
  9. package/dist/src/commands/propose.js +171 -0
  10. package/dist/src/commands/reflect.js +193 -0
  11. package/dist/{commands → src/commands}/registry-search.js +71 -7
  12. package/dist/{commands → src/commands}/remember.js +12 -0
  13. package/dist/{commands → src/commands}/search.js +104 -4
  14. package/dist/{commands → src/commands}/self-update.js +4 -3
  15. package/dist/{commands → src/commands}/show.js +73 -0
  16. package/dist/{commands → src/commands}/source-add.js +5 -1
  17. package/dist/{commands → src/commands}/source-manage.js +7 -1
  18. package/dist/{core → src/core}/asset-ref.js +5 -5
  19. package/dist/{core → src/core}/asset-spec.js +12 -0
  20. package/dist/{core → src/core}/common.js +1 -1
  21. package/dist/{core → src/core}/config.js +203 -121
  22. package/dist/{core → src/core}/errors.js +4 -0
  23. package/dist/src/core/events.js +239 -0
  24. package/dist/src/core/lesson-lint.js +86 -0
  25. package/dist/src/core/proposals.js +406 -0
  26. package/dist/src/core/warn.js +72 -0
  27. package/dist/{core → src/core}/write-source.js +80 -5
  28. package/dist/{indexer → src/indexer}/db-search.js +114 -24
  29. package/dist/{indexer → src/indexer}/db.js +76 -23
  30. package/dist/{indexer → src/indexer}/file-context.js +0 -3
  31. package/dist/src/indexer/graph-boost.js +179 -0
  32. package/dist/src/indexer/graph-extraction.js +212 -0
  33. package/dist/{indexer → src/indexer}/indexer.js +88 -7
  34. package/dist/{indexer → src/indexer}/matchers.js +1 -1
  35. package/dist/src/indexer/memory-inference.js +263 -0
  36. package/dist/{indexer → src/indexer}/metadata.js +111 -3
  37. package/dist/{indexer → src/indexer}/search-source.js +4 -2
  38. package/dist/src/integrations/agent/config.js +292 -0
  39. package/dist/src/integrations/agent/detect.js +94 -0
  40. package/dist/src/integrations/agent/index.js +17 -0
  41. package/dist/src/integrations/agent/profiles.js +65 -0
  42. package/dist/src/integrations/agent/prompts.js +167 -0
  43. package/dist/src/integrations/agent/spawn.js +272 -0
  44. package/dist/{integrations → src/integrations}/github.js +9 -3
  45. package/dist/{integrations → src/integrations}/lockfile.js +0 -26
  46. package/dist/{llm → src/llm}/client.js +33 -2
  47. package/dist/{llm → src/llm}/embedders/remote.js +37 -3
  48. package/dist/src/llm/feature-gate.js +108 -0
  49. package/dist/src/llm/graph-extract.js +107 -0
  50. package/dist/src/llm/index-passes.js +35 -0
  51. package/dist/src/llm/memory-infer.js +86 -0
  52. package/dist/{output → src/output}/cli-hints.js +15 -2
  53. package/dist/{output → src/output}/renderers.js +63 -2
  54. package/dist/src/output/shapes.js +523 -0
  55. package/dist/src/output/text.js +1116 -0
  56. package/dist/{registry → src/registry}/build-index.js +19 -8
  57. package/dist/{registry → src/registry}/factory.js +0 -8
  58. package/dist/{registry → src/registry}/providers/static-index.js +6 -3
  59. package/dist/{registry → src/registry}/resolve.js +68 -2
  60. package/dist/{setup → src/setup}/setup.js +52 -5
  61. package/dist/{sources → src/sources}/providers/git.js +7 -15
  62. package/dist/{wiki → src/wiki}/wiki.js +54 -6
  63. package/dist/{workflows → src/workflows}/runs.js +37 -3
  64. package/dist/tests/add-website-source.test.js +119 -0
  65. package/dist/tests/agent/agent-config-loader.test.js +70 -0
  66. package/dist/tests/agent/agent-config.test.js +221 -0
  67. package/dist/tests/agent/agent-detect.test.js +100 -0
  68. package/dist/tests/agent/agent-spawn.test.js +234 -0
  69. package/dist/tests/agent-output.test.js +186 -0
  70. package/dist/tests/architecture/agent-no-llm-sdk-guard.test.js +103 -0
  71. package/dist/tests/architecture/agent-spawn-seam.test.js +193 -0
  72. package/dist/tests/architecture/llm-stateless-seam.test.js +112 -0
  73. package/dist/tests/asset-ref.test.js +192 -0
  74. package/dist/tests/asset-registry.test.js +103 -0
  75. package/dist/tests/asset-spec.test.js +241 -0
  76. package/dist/tests/bench/attribution.test.js +996 -0
  77. package/dist/tests/bench/cleanup-sigint.test.js +83 -0
  78. package/dist/tests/bench/cleanup.js +234 -0
  79. package/dist/tests/bench/cleanup.test.js +166 -0
  80. package/dist/tests/bench/cli.js +1018 -0
  81. package/dist/tests/bench/cli.test.js +445 -0
  82. package/dist/tests/bench/compare.test.js +556 -0
  83. package/dist/tests/bench/corpus.js +317 -0
  84. package/dist/tests/bench/corpus.test.js +258 -0
  85. package/dist/tests/bench/doctor.js +525 -0
  86. package/dist/tests/bench/driver.js +401 -0
  87. package/dist/tests/bench/driver.test.js +584 -0
  88. package/dist/tests/bench/environment.js +233 -0
  89. package/dist/tests/bench/environment.test.js +199 -0
  90. package/dist/tests/bench/evolve-metrics.js +179 -0
  91. package/dist/tests/bench/evolve-metrics.test.js +187 -0
  92. package/dist/tests/bench/evolve.js +647 -0
  93. package/dist/tests/bench/evolve.test.js +624 -0
  94. package/dist/tests/bench/failure-modes.test.js +349 -0
  95. package/dist/tests/bench/feedback-integrity.test.js +457 -0
  96. package/dist/tests/bench/leakage.test.js +228 -0
  97. package/dist/tests/bench/learning-curve.test.js +134 -0
  98. package/dist/tests/bench/metrics.js +2395 -0
  99. package/dist/tests/bench/metrics.test.js +1150 -0
  100. package/dist/tests/bench/no-os-tmpdir-invariant.test.js +43 -0
  101. package/dist/tests/bench/opencode-config.js +194 -0
  102. package/dist/tests/bench/opencode-config.test.js +370 -0
  103. package/dist/tests/bench/report.js +1885 -0
  104. package/dist/tests/bench/report.test.js +1038 -0
  105. package/dist/tests/bench/run-config.js +355 -0
  106. package/dist/tests/bench/run-config.test.js +298 -0
  107. package/dist/tests/bench/run-curate-test.js +32 -0
  108. package/dist/tests/bench/run-failing-tasks.js +56 -0
  109. package/dist/tests/bench/run-full-bench.js +51 -0
  110. package/dist/tests/bench/run-items36-targeted.js +69 -0
  111. package/dist/tests/bench/run-nano-quick.js +42 -0
  112. package/dist/tests/bench/run-waveg-targeted.js +62 -0
  113. package/dist/tests/bench/runner.js +699 -0
  114. package/dist/tests/bench/runner.test.js +958 -0
  115. package/dist/tests/bench/search-bridge.test.js +331 -0
  116. package/dist/tests/bench/tmp.js +131 -0
  117. package/dist/tests/bench/trajectory.js +116 -0
  118. package/dist/tests/bench/trajectory.test.js +127 -0
  119. package/dist/tests/bench/verifier.js +114 -0
  120. package/dist/tests/bench/verifier.test.js +118 -0
  121. package/dist/tests/bench/workflow-evaluator.js +557 -0
  122. package/dist/tests/bench/workflow-evaluator.test.js +421 -0
  123. package/dist/tests/bench/workflow-spec.js +345 -0
  124. package/dist/tests/bench/workflow-spec.test.js +363 -0
  125. package/dist/tests/bench/workflow-trace.js +472 -0
  126. package/dist/tests/bench/workflow-trace.test.js +254 -0
  127. package/dist/tests/benchmark-search-quality.js +536 -0
  128. package/dist/tests/benchmark-suite.js +1441 -0
  129. package/dist/tests/capture-cli.test.js +112 -0
  130. package/dist/tests/cli-errors.test.js +204 -0
  131. package/dist/tests/commands/events.test.js +370 -0
  132. package/dist/tests/commands/history.test.js +418 -0
  133. package/dist/tests/commands/import.test.js +103 -0
  134. package/dist/tests/commands/proposal-cli.test.js +209 -0
  135. package/dist/tests/commands/reflect-propose-cli.test.js +333 -0
  136. package/dist/tests/commands/remember.test.js +97 -0
  137. package/dist/tests/commands/scope-flags.test.js +300 -0
  138. package/dist/tests/commands/search.test.js +537 -0
  139. package/dist/tests/commands/show-indexer-parity.test.js +117 -0
  140. package/dist/tests/commands/show.test.js +294 -0
  141. package/dist/tests/common.test.js +266 -0
  142. package/dist/tests/completions.test.js +142 -0
  143. package/dist/tests/config-cli.test.js +193 -0
  144. package/dist/tests/config-llm-features.test.js +139 -0
  145. package/dist/tests/config.test.js +569 -0
  146. package/dist/tests/contracts/migration-baseline.test.js +43 -0
  147. package/dist/tests/contracts/reflect-propose-envelope.test.js +139 -0
  148. package/dist/tests/contracts/spec-helpers.js +46 -0
  149. package/dist/tests/contracts/v1-spec-section-11-proposal-queue.test.js +228 -0
  150. package/dist/tests/contracts/v1-spec-section-12-agent-config.test.js +56 -0
  151. package/dist/tests/contracts/v1-spec-section-13-lesson-type.test.js +34 -0
  152. package/dist/tests/contracts/v1-spec-section-14-llm-features.test.js +94 -0
  153. package/dist/tests/contracts/v1-spec-section-4-1-asset-types.test.js +39 -0
  154. package/dist/tests/contracts/v1-spec-section-4-2-quality-rules.test.js +44 -0
  155. package/dist/tests/contracts/v1-spec-section-5-configuration.test.js +47 -0
  156. package/dist/tests/contracts/v1-spec-section-6-orchestration.test.js +40 -0
  157. package/dist/tests/contracts/v1-spec-section-7-module-layout.test.js +58 -0
  158. package/dist/tests/contracts/v1-spec-section-8-extension-points.test.js +34 -0
  159. package/dist/tests/contracts/v1-spec-section-9-4-cli-surface.test.js +75 -0
  160. package/dist/tests/contracts/v1-spec-section-9-7-llm-agent-boundary.test.js +36 -0
  161. package/dist/tests/core/write-source.test.js +366 -0
  162. package/dist/tests/curate-command.test.js +87 -0
  163. package/dist/tests/db-scoring.test.js +201 -0
  164. package/dist/tests/db.test.js +654 -0
  165. package/dist/tests/distill-cli-flag.test.js +208 -0
  166. package/dist/tests/distill.test.js +515 -0
  167. package/dist/tests/docker-install.test.js +120 -0
  168. package/dist/tests/e2e.test.js +1419 -0
  169. package/dist/tests/embedder.test.js +340 -0
  170. package/dist/tests/embedding-model-config.test.js +379 -0
  171. package/dist/tests/feedback-command.test.js +172 -0
  172. package/dist/tests/file-context.test.js +552 -0
  173. package/dist/tests/fixtures/scripts/git/summarize-diff.js +9 -0
  174. package/dist/tests/fixtures/scripts/lint/eslint-check.js +7 -0
  175. package/dist/tests/fixtures/stashes/load.js +166 -0
  176. package/dist/tests/fixtures/stashes/load.test.js +97 -0
  177. package/dist/tests/fixtures/stashes/ranking-baseline/scripts/mem0-search.js +12 -0
  178. package/dist/tests/frontmatter.test.js +190 -0
  179. package/dist/tests/fts-field-weighting.test.js +254 -0
  180. package/dist/tests/fuzzy-search.test.js +230 -0
  181. package/dist/tests/git-provider-clone.test.js +45 -0
  182. package/dist/tests/github.test.js +161 -0
  183. package/dist/tests/graph-boost-ranking.test.js +305 -0
  184. package/dist/tests/graph-extraction.test.js +282 -0
  185. package/dist/tests/helpers/usage-events.js +8 -0
  186. package/dist/tests/index-pass-llm.test.js +161 -0
  187. package/dist/tests/indexer.test.js +570 -0
  188. package/dist/tests/info-command.test.js +166 -0
  189. package/dist/tests/init.test.js +69 -0
  190. package/dist/tests/install-script.test.js +246 -0
  191. package/dist/tests/integration/agent-real-profile.test.js +94 -0
  192. package/dist/tests/issue-36-repro.test.js +304 -0
  193. package/dist/tests/issues-191-194.test.js +160 -0
  194. package/dist/tests/lesson-lint.test.js +111 -0
  195. package/dist/tests/llm-client.test.js +115 -0
  196. package/dist/tests/llm-feature-gate.test.js +151 -0
  197. package/dist/tests/llm.test.js +139 -0
  198. package/dist/tests/lockfile.test.js +216 -0
  199. package/dist/tests/manifest.test.js +205 -0
  200. package/dist/tests/markdown.test.js +126 -0
  201. package/dist/tests/matchers-unit.test.js +189 -0
  202. package/dist/tests/memory-inference.test.js +299 -0
  203. package/dist/tests/merge-scoring.test.js +136 -0
  204. package/dist/tests/metadata.test.js +313 -0
  205. package/dist/tests/migration-help.test.js +89 -0
  206. package/dist/tests/origin-resolve.test.js +124 -0
  207. package/dist/tests/output-baseline.test.js +218 -0
  208. package/dist/tests/output-shapes-unit.test.js +478 -0
  209. package/dist/tests/parallel-search.test.js +272 -0
  210. package/dist/tests/parameter-metadata.test.js +365 -0
  211. package/dist/tests/paths.test.js +177 -0
  212. package/dist/tests/progressive-disclosure.test.js +280 -0
  213. package/dist/tests/proposals.test.js +279 -0
  214. package/dist/tests/proposed-quality.test.js +271 -0
  215. package/dist/tests/provider-registry.test.js +32 -0
  216. package/dist/tests/ranking-regression.test.js +548 -0
  217. package/dist/tests/reflect-propose.test.js +455 -0
  218. package/dist/tests/registry-build-index.test.js +394 -0
  219. package/dist/tests/registry-cli.test.js +290 -0
  220. package/dist/tests/registry-index-v2.test.js +430 -0
  221. package/dist/tests/registry-install.test.js +728 -0
  222. package/dist/tests/registry-providers/parity.test.js +189 -0
  223. package/dist/tests/registry-providers/skills-sh.test.js +309 -0
  224. package/dist/tests/registry-providers/static-index.test.js +238 -0
  225. package/dist/tests/registry-resolve.test.js +126 -0
  226. package/dist/tests/registry-search.test.js +923 -0
  227. package/dist/tests/remember-frontmatter.test.js +378 -0
  228. package/dist/tests/remember-unit.test.js +123 -0
  229. package/dist/tests/ripgrep-install.test.js +251 -0
  230. package/dist/tests/ripgrep-resolve.test.js +108 -0
  231. package/dist/tests/ripgrep.test.js +163 -0
  232. package/dist/tests/save-command.test.js +94 -0
  233. package/dist/tests/save-trust-qa-fixes.test.js +270 -0
  234. package/dist/tests/scoring-pipeline.test.js +648 -0
  235. package/dist/tests/search-include-proposed-cli.test.js +118 -0
  236. package/dist/tests/self-update.test.js +442 -0
  237. package/dist/tests/semantic-search-e2e.test.js +512 -0
  238. package/dist/tests/semantic-status.test.js +471 -0
  239. package/dist/tests/setup-run.integration.js +877 -0
  240. package/dist/tests/setup-wizard.test.js +198 -0
  241. package/dist/tests/setup.test.js +131 -0
  242. package/dist/tests/source-add.test.js +11 -0
  243. package/dist/tests/source-clone.test.js +254 -0
  244. package/dist/tests/source-manage.test.js +366 -0
  245. package/dist/tests/source-providers/filesystem.test.js +82 -0
  246. package/dist/tests/source-providers/git.test.js +252 -0
  247. package/dist/tests/source-providers/website.test.js +128 -0
  248. package/dist/tests/source-qa-fixes.test.js +286 -0
  249. package/dist/tests/source-registry.test.js +350 -0
  250. package/dist/tests/source-resolve.test.js +100 -0
  251. package/dist/tests/source-source.test.js +281 -0
  252. package/dist/tests/source.test.js +533 -0
  253. package/dist/tests/tar-utils-scan.test.js +73 -0
  254. package/dist/tests/toggle-components.test.js +73 -0
  255. package/dist/tests/usage-telemetry.test.js +265 -0
  256. package/dist/tests/utility-scoring.test.js +558 -0
  257. package/dist/tests/vault-load-error.test.js +78 -0
  258. package/dist/tests/vault-qa-fixes.test.js +194 -0
  259. package/dist/tests/vault.test.js +429 -0
  260. package/dist/tests/vector-search.test.js +608 -0
  261. package/dist/tests/walker.test.js +252 -0
  262. package/dist/tests/wave2-cluster-bc.test.js +228 -0
  263. package/dist/tests/wave2-cluster-d.test.js +180 -0
  264. package/dist/tests/wave2-cluster-e.test.js +179 -0
  265. package/dist/tests/wiki-qa-fixes.test.js +270 -0
  266. package/dist/tests/wiki.test.js +529 -0
  267. package/dist/tests/workflow-cli.test.js +271 -0
  268. package/dist/tests/workflow-markdown.test.js +171 -0
  269. package/dist/tests/workflow-path-escape.test.js +132 -0
  270. package/dist/tests/workflow-qa-fixes.test.js +395 -0
  271. package/dist/tests/workflows/indexer-rejection.test.js +213 -0
  272. package/docs/README.md +8 -0
  273. package/docs/migration/release-notes/0.7.0.md +244 -0
  274. package/package.json +2 -2
  275. package/dist/core/warn.js +0 -27
  276. package/dist/output/shapes.js +0 -212
  277. package/dist/output/text.js +0 -520
  278. /package/dist/{commands → src/commands}/completions.js +0 -0
  279. /package/dist/{commands → src/commands}/curate.js +0 -0
  280. /package/dist/{commands → src/commands}/info.js +0 -0
  281. /package/dist/{commands → src/commands}/init.js +0 -0
  282. /package/dist/{commands → src/commands}/install-audit.js +0 -0
  283. /package/dist/{commands → src/commands}/migration-help.js +0 -0
  284. /package/dist/{commands → src/commands}/source-clone.js +0 -0
  285. /package/dist/{commands → src/commands}/vault.js +0 -0
  286. /package/dist/{core → src/core}/asset-registry.js +0 -0
  287. /package/dist/{core → src/core}/frontmatter.js +0 -0
  288. /package/dist/{core → src/core}/markdown.js +0 -0
  289. /package/dist/{core → src/core}/paths.js +0 -0
  290. /package/dist/{indexer → src/indexer}/manifest.js +0 -0
  291. /package/dist/{indexer → src/indexer}/search-fields.js +0 -0
  292. /package/dist/{indexer → src/indexer}/semantic-status.js +0 -0
  293. /package/dist/{indexer → src/indexer}/usage-events.js +0 -0
  294. /package/dist/{indexer → src/indexer}/walker.js +0 -0
  295. /package/dist/{llm → src/llm}/embedder.js +0 -0
  296. /package/dist/{llm → src/llm}/embedders/cache.js +0 -0
  297. /package/dist/{llm → src/llm}/embedders/local.js +0 -0
  298. /package/dist/{llm → src/llm}/embedders/types.js +0 -0
  299. /package/dist/{llm → src/llm}/metadata-enhance.js +0 -0
  300. /package/dist/{output → src/output}/context.js +0 -0
  301. /package/dist/{registry → src/registry}/create-provider-registry.js +0 -0
  302. /package/dist/{registry → src/registry}/origin-resolve.js +0 -0
  303. /package/dist/{registry → src/registry}/providers/index.js +0 -0
  304. /package/dist/{registry → src/registry}/providers/skills-sh.js +0 -0
  305. /package/dist/{registry → src/registry}/providers/types.js +0 -0
  306. /package/dist/{registry → src/registry}/types.js +0 -0
  307. /package/dist/{setup → src/setup}/detect.js +0 -0
  308. /package/dist/{setup → src/setup}/ripgrep-install.js +0 -0
  309. /package/dist/{setup → src/setup}/ripgrep-resolve.js +0 -0
  310. /package/dist/{setup → src/setup}/steps.js +0 -0
  311. /package/dist/{sources → src/sources}/include.js +0 -0
  312. /package/dist/{sources → src/sources}/provider-factory.js +0 -0
  313. /package/dist/{sources → src/sources}/provider.js +0 -0
  314. /package/dist/{sources → src/sources}/providers/filesystem.js +0 -0
  315. /package/dist/{sources → src/sources}/providers/index.js +0 -0
  316. /package/dist/{sources → src/sources}/providers/install-types.js +0 -0
  317. /package/dist/{sources → src/sources}/providers/npm.js +0 -0
  318. /package/dist/{sources → src/sources}/providers/provider-utils.js +0 -0
  319. /package/dist/{sources → src/sources}/providers/sync-from-ref.js +0 -0
  320. /package/dist/{sources → src/sources}/providers/tar-utils.js +0 -0
  321. /package/dist/{sources → src/sources}/providers/website.js +0 -0
  322. /package/dist/{sources → src/sources}/resolve.js +0 -0
  323. /package/dist/{sources → src/sources}/types.js +0 -0
  324. /package/dist/{templates → src/templates}/wiki-templates.js +0 -0
  325. /package/dist/{version.js → src/version.js} +0 -0
  326. /package/dist/{workflows → src/workflows}/authoring.js +0 -0
  327. /package/dist/{workflows → src/workflows}/cli.js +0 -0
  328. /package/dist/{workflows → src/workflows}/db.js +0 -0
  329. /package/dist/{workflows → src/workflows}/document-cache.js +0 -0
  330. /package/dist/{workflows → src/workflows}/parser.js +0 -0
  331. /package/dist/{workflows → src/workflows}/renderer.js +0 -0
  332. /package/dist/{workflows → src/workflows}/schema.js +0 -0
  333. /package/dist/{workflows → src/workflows}/validator.js +0 -0
@@ -0,0 +1,1018 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * akm-bench CLI dispatcher.
4
+ *
5
+ * Subcommands:
6
+ * • `utility` — paired noakm vs akm utility benchmark (Track A).
7
+ * • `compare` — diff two report JSON files; refuses on hash/model mismatch.
8
+ * • `attribute` — per-asset marginal contribution via leave-one-out masking.
9
+ * • `evolve` — longitudinal evolution loop (Track B). Stub.
10
+ * • `kill` — send SIGTERM to a running bench process (reads bench.pid).
11
+ *
12
+ * Implementation status and validity rules live in `tests/bench/BENCH.md`.
13
+ *
14
+ * NOTE: The bench binary is intentionally argv-light. citty is the project's
15
+ * CLI framework but the bench is not part of the public CLI surface, so a
16
+ * hand-rolled parser keeps the dependency graph tight.
17
+ */
18
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+ import process from "node:process";
21
+ import { getCacheDir } from "../../src/core/paths";
22
+ import { listTasks } from "./corpus";
23
+ import { runEvolve } from "./evolve";
24
+ import { compareReports, rehydrateRunFromSerialized, runMaskedCorpus, } from "./metrics";
25
+ import { BenchConfigError, loadOpencodeProviders } from "./opencode-config";
26
+ import { renderAttributionTable, renderCompareMarkdown, renderEvolveReport, renderUtilityReport, } from "./report";
27
+ import { loadBenchRunConfig } from "./run-config";
28
+ import { runUtility } from "./runner";
29
+ import { isPidRunning, readBenchPid, writeBenchPid } from "./tmp";
30
+ const HELP = `akm-bench — agent-plus-akm evaluation framework
31
+
32
+ Usage:
33
+ bun run tests/bench/cli.ts <config.json> [--json] [--seeds N] [--parallel N] [--tasks <list>]
34
+ bun run tests/bench/cli.ts <subcommand> [...flags]
35
+
36
+ Config-file mode (recommended):
37
+ Pass a path to a tests/bench/configs/*.json file as the first argument.
38
+ See tests/bench/BENCH.md for the run-config schema and provider
39
+ discovery chain (BENCH_OPENCODE_CONFIG → providers/providersRef →
40
+ ~/.config/akm/bench-providers.json).
41
+
42
+ Subcommands (legacy; still supported):
43
+ utility Track A: paired noakm vs akm utility benchmark.
44
+ evolve Track B: longitudinal feedback → distill → propose loop.
45
+ compare Diff two report JSON files (refuses cross-model diffs).
46
+ attribute Per-asset marginal pass-rate contribution.
47
+ kill Send SIGTERM to a running bench process (reads bench.pid).
48
+ clean Remove all bench tmp dirs under \${AKM_CACHE_DIR}/bench/.
49
+
50
+ utility flags:
51
+ --tasks <slice> train | eval | all (default: all)
52
+ --seeds <N> seeds per arm (default: 5)
53
+ --budget-tokens <N> per-run token cap (default: 30000)
54
+ --budget-wall-ms <N> per-run wallclock cap in ms (default: 120000)
55
+ --parallel <N> number of (task, arm, seed) triples to run concurrently
56
+ (default: 1 — sequential). Clamped to [1, 8]. Values > 4
57
+ print a warning unless --force-parallel is also set.
58
+ --force-parallel suppress the high-parallelism warning when --parallel > 4.
59
+ --no-noakm exclude the noakm baseline arm (default: included). The noakm arm is
60
+ the control condition — pass_rate(akm) − pass_rate(noakm) is the
61
+ primary utility metric. Omit only when you are measuring workflow
62
+ compliance rather than marginal utility.
63
+ --include-synthetic add a third 'synthetic' arm where the model writes/uses its own
64
+ scratch notes (no AKM stash). Reports akm_over_synthetic_lift so
65
+ operators can see whether AKM beats a self-notes baseline.
66
+ --opencode-config <path> path to a bench opencode providers JSON file. Auto-discovered
67
+ from BENCH_OPENCODE_CONFIG env var or the fixture defaults when
68
+ omitted. See BENCH.md for the discovery order.
69
+ --json suppress the markdown summary on stderr (machine-readable only).
70
+ Without --json, JSON still goes to stdout and the markdown
71
+ summary is also written to stderr for human-friendly reads.
72
+ -h, --help show this message.
73
+
74
+ evolve flags:
75
+ --tasks <domain> domain id (e.g., docker-homelab) or 'all'. REQUIRED.
76
+ --seeds <N> seeds per arm (default: 5)
77
+ --budget-tokens <N> per-run token cap (default: 30000)
78
+ --budget-wall-ms <N> per-run wallclock cap in ms (default: 120000)
79
+ --parallel <N> same as utility --parallel (default: 1).
80
+ --force-parallel suppress the high-parallelism warning when --parallel > 4.
81
+ --negative-threshold-count <N> absolute negative-feedback count to evolve (default: 2)
82
+ --negative-threshold-ratio <R> ratio of negatives to total feedback (default: 0.5)
83
+ --opencode-config <path> path to a bench opencode providers JSON file (same as utility).
84
+ --json suppress the markdown summary on stderr.
85
+
86
+ compare flags:
87
+ --base <path> path to baseline UtilityRunReport JSON file. REQUIRED.
88
+ --current <path> path to current UtilityRunReport JSON file. REQUIRED.
89
+ --json emit the structured CompareResult JSON to stdout instead
90
+ of a markdown diff.
91
+ --allow-corpus-mismatch proceed even when the two reports disagree on the
92
+ selected task IDs / taskCorpusHash. The diff is
93
+ rendered with a warning instead of being refused.
94
+ --allow-fixture-mismatch proceed even when the two reports disagree on the
95
+ fixtureContentHash. Renders a warning instead of
96
+ refusing.
97
+ Exit codes: 0 on successful diff, 1 on refusal (model/corpus/fixture-hash/schema/track mismatch),
98
+ 2 on input errors (missing files, malformed JSON, unknown flags).
99
+
100
+ attribute flags:
101
+ --base <path> path to a §13.3 utility run JSON (required).
102
+ --top <N> number of top-loaded assets to mask (default: 5; clamped).
103
+ --opencode-config <path> path to a bench opencode providers JSON file (same as utility).
104
+ --json suppress the markdown summary on stderr.
105
+
106
+ kill flags:
107
+ (none) Reads \${AKM_CACHE_DIR}/bench/bench.pid and sends SIGTERM.
108
+ Prints "no bench running" and exits 0 when the PID file is absent.
109
+ Run again (or press Ctrl-C) to escalate to SIGKILL.
110
+
111
+ Environment:
112
+ BENCH_OPENCODE_MODEL model id stamped into every RunResult. REQUIRED for utility/evolve
113
+ unless the loaded providers file supplies a defaultModel.
114
+ BENCH_OPENCODE_CONFIG path to the bench opencode providers JSON file. Overrides the
115
+ default fixture; overridden by --opencode-config flag.
116
+
117
+ Auto-discovery order for --opencode-config (first existing file wins):
118
+ 1. --opencode-config <path> flag value
119
+ 2. BENCH_OPENCODE_CONFIG env var
120
+ 3. tests/fixtures/bench/opencode-providers.local.json (gitignored operator overlay)
121
+ 4. tests/fixtures/bench/opencode-providers.json (committed fixture)
122
+ 5. None found → empty isolated dir, opencode uses cloud-provider defaults.
123
+
124
+ See tests/bench/BENCH.md for the operator guide.
125
+ `;
126
+ function parseArgs(argv) {
127
+ const flags = new Map();
128
+ const bool = new Set();
129
+ const positional = [];
130
+ const subcommand = argv[0] ?? "";
131
+ for (let i = 1; i < argv.length; i++) {
132
+ const arg = argv[i];
133
+ if (arg === "--help" || arg === "-h") {
134
+ bool.add("help");
135
+ continue;
136
+ }
137
+ if (arg === "--json") {
138
+ bool.add("json");
139
+ continue;
140
+ }
141
+ if (arg.startsWith("--")) {
142
+ const eq = arg.indexOf("=");
143
+ if (eq !== -1) {
144
+ flags.set(arg.slice(2, eq), arg.slice(eq + 1));
145
+ }
146
+ else {
147
+ const next = argv[i + 1];
148
+ if (next === undefined || next.startsWith("--")) {
149
+ bool.add(arg.slice(2));
150
+ }
151
+ else {
152
+ flags.set(arg.slice(2), next);
153
+ i += 1;
154
+ }
155
+ }
156
+ continue;
157
+ }
158
+ positional.push(arg);
159
+ }
160
+ return { subcommand, flags, bool, positional };
161
+ }
162
+ /**
163
+ * Absolute path to the committed default bench opencode providers fixture.
164
+ * Used as the final fallback in the auto-discovery chain.
165
+ */
166
+ const DEFAULT_PROVIDERS_PATH = path.resolve(__dirname, "..", "fixtures", "bench", "opencode-providers.json");
167
+ /**
168
+ * Absolute path to the gitignored operator overlay. Takes precedence over
169
+ * the committed fixture when it exists.
170
+ */
171
+ const LOCAL_PROVIDERS_PATH = path.resolve(__dirname, "..", "fixtures", "bench", "opencode-providers.local.json");
172
+ /**
173
+ * Auto-discover and load the bench opencode providers file.
174
+ *
175
+ * Discovery order (first existing file wins):
176
+ * 1. `flagPath` — `--opencode-config` flag value (already resolved by caller).
177
+ * 2. `BENCH_OPENCODE_CONFIG` env var.
178
+ * 3. `tests/fixtures/bench/opencode-providers.local.json` (gitignored overlay).
179
+ * 4. `tests/fixtures/bench/opencode-providers.json` (committed fixture).
180
+ * 5. None found → returns `undefined` (empty isolated dir, cloud-provider fallback).
181
+ *
182
+ * When a file is found but fails to load, the BenchConfigError is re-thrown
183
+ * so the caller can map it to the correct exit code.
184
+ */
185
+ export function discoverOpencodeProviders(flagPath) {
186
+ const candidates = [
187
+ flagPath,
188
+ getEnv("BENCH_OPENCODE_CONFIG"),
189
+ LOCAL_PROVIDERS_PATH,
190
+ DEFAULT_PROVIDERS_PATH,
191
+ ];
192
+ for (const candidate of candidates) {
193
+ if (!candidate)
194
+ continue;
195
+ const absPath = path.isAbsolute(candidate) ? candidate : path.resolve(candidate);
196
+ if (fs.existsSync(absPath)) {
197
+ // Throws BenchConfigError on validation failure; callers propagate it.
198
+ return loadOpencodeProviders(absPath);
199
+ }
200
+ // When a flag or env-var path was given explicitly but doesn't exist,
201
+ // treat it as a usage error rather than silently skipping to the next
202
+ // candidate. Only the auto-discovered defaults (local + committed) are
203
+ // silently skipped when absent.
204
+ if (candidate === flagPath && flagPath) {
205
+ // This throws with isUsageError: true (file not found).
206
+ return loadOpencodeProviders(absPath);
207
+ }
208
+ if (candidate === getEnv("BENCH_OPENCODE_CONFIG") && candidate) {
209
+ return loadOpencodeProviders(absPath);
210
+ }
211
+ }
212
+ return undefined;
213
+ }
214
+ /**
215
+ * `utility` subcommand. Walks the corpus, runs K seeds per arm per task,
216
+ * and produces the §13.3 report.
217
+ *
218
+ * Returns rather than mutates process to keep this unit-testable. The
219
+ * `main()` driver below maps the result onto the actual stdout/stderr/exit.
220
+ */
221
+ export async function runUtilityCli(options) {
222
+ const sliceFilter = options.slice === "all" ? undefined : options.slice;
223
+ const tasks = listTasks(sliceFilter ? { slice: sliceFilter } : {});
224
+ // noakm arm is included by default: it is the control condition for the
225
+ // primary utility metric (pass_rate(akm) − pass_rate(noakm), spec §4).
226
+ // Pass --no-noakm (options.includeNoakm === false) to exclude it.
227
+ const arms = options.includeNoakm === false ? ["akm"] : ["noakm", "akm"];
228
+ const report = await runUtility({
229
+ tasks,
230
+ arms,
231
+ model: options.model,
232
+ seedsPerArm: options.seedsPerArm,
233
+ budgetTokens: options.budgetTokens,
234
+ budgetWallMs: options.budgetWallMs,
235
+ slice: options.slice,
236
+ // #261: thread the synthetic-arm gate. Default off — the envelope shape
237
+ // is byte-identical to the pre-#261 output unless the operator opts in.
238
+ ...(options.includeSynthetic ? { includeSynthetic: true } : {}),
239
+ ...(options.parallel !== undefined ? { parallel: options.parallel } : {}),
240
+ ...(options.forceParallel ? { forceParallel: true } : {}),
241
+ ...(options.branch !== undefined ? { branch: options.branch } : {}),
242
+ ...(options.commit !== undefined ? { commit: options.commit } : {}),
243
+ ...(options.timestamp !== undefined ? { timestamp: options.timestamp } : {}),
244
+ ...(options.opencodeProviders ? { opencodeProviders: options.opencodeProviders } : {}),
245
+ });
246
+ const { json, markdown } = renderUtilityReport(report);
247
+ const jsonText = `${JSON.stringify(json, null, 2)}\n`;
248
+ const markdownText = `${markdown}\n`;
249
+ // JSON ALWAYS goes to stdout. This is the bench's machine-readable
250
+ // contract (matches `tests/benchmark-suite.ts` and the future `bench
251
+ // compare`/`attribute` subcommands). The `--json` flag means
252
+ // "suppress the human-friendly markdown summary on stderr"; without it,
253
+ // both the JSON envelope (stdout) and the markdown summary (stderr) are
254
+ // emitted so an operator running it interactively gets both views.
255
+ const stdout = jsonText;
256
+ let stderr = options.json ? "" : markdownText;
257
+ stderr += `tasks discovered: ${tasks.length} (slice=${options.slice})\n`;
258
+ if (tasks.length === 0) {
259
+ stderr += "no tasks found — corpus is empty or the slice filter excluded all tasks\n";
260
+ }
261
+ return { exitCode: 0, stdout, stderr };
262
+ }
263
+ /**
264
+ * `compare` subcommand. Reads two UtilityRunReport JSON files from disk,
265
+ * dispatches to `compareReports`, and renders either markdown (default) or
266
+ * the structured JSON envelope to stdout.
267
+ *
268
+ * Exit-code shape:
269
+ * • 0 on a successful diff (regardless of whether the diff shows wins).
270
+ * • 1 on a refusal (model/hash/schema/track mismatch).
271
+ * • 2 on input errors (file missing, malformed JSON).
272
+ *
273
+ * Returned `UtilityCliResult` keeps this unit-testable; the `main()` driver
274
+ * splices the result onto the actual process.
275
+ */
276
+ export function runCompareCli(options) {
277
+ let baseRaw;
278
+ let currentRaw;
279
+ try {
280
+ baseRaw = fs.readFileSync(options.basePath, "utf8");
281
+ }
282
+ catch (err) {
283
+ return {
284
+ exitCode: 2,
285
+ stdout: "",
286
+ stderr: `bench compare: cannot read --base ${options.basePath}: ${err.message}\n`,
287
+ };
288
+ }
289
+ try {
290
+ currentRaw = fs.readFileSync(options.currentPath, "utf8");
291
+ }
292
+ catch (err) {
293
+ return {
294
+ exitCode: 2,
295
+ stdout: "",
296
+ stderr: `bench compare: cannot read --current ${options.currentPath}: ${err.message}\n`,
297
+ };
298
+ }
299
+ let base;
300
+ let current;
301
+ try {
302
+ base = JSON.parse(baseRaw);
303
+ }
304
+ catch (err) {
305
+ return { exitCode: 2, stdout: "", stderr: `bench compare: malformed JSON in --base: ${err.message}\n` };
306
+ }
307
+ try {
308
+ current = JSON.parse(currentRaw);
309
+ }
310
+ catch (err) {
311
+ return {
312
+ exitCode: 2,
313
+ stdout: "",
314
+ stderr: `bench compare: malformed JSON in --current: ${err.message}\n`,
315
+ };
316
+ }
317
+ const result = compareReports(base, current, {
318
+ ...(options.allowCorpusMismatch ? { allowCorpusMismatch: true } : {}),
319
+ ...(options.allowFixtureMismatch ? { allowFixtureMismatch: true } : {}),
320
+ });
321
+ const stdout = options.json ? `${JSON.stringify(result, null, 2)}\n` : `${renderCompareMarkdown(result)}\n`;
322
+ let stderr = "";
323
+ if (!result.ok) {
324
+ stderr = `bench compare: ${result.message}\n`;
325
+ return { exitCode: 1, stdout, stderr };
326
+ }
327
+ // One-line summary on stderr so an interactive operator sees it without
328
+ // having to scan the markdown body.
329
+ const agg = result.aggregate;
330
+ stderr = `bench compare: pass_rate Δ=${agg.passRateDelta.toFixed(2)} (${agg.passRateSign}); ${result.perTask.length} tasks compared.\n`;
331
+ for (const w of result.warnings)
332
+ stderr += `warning: ${w}\n`;
333
+ return { exitCode: 0, stdout, stderr };
334
+ }
335
+ /**
336
+ * `attribute` subcommand. Loads a base utility report, picks the top-N
337
+ * most-loaded assets, masks each in turn, re-runs the corpus, and emits a
338
+ * marginal-contribution report.
339
+ *
340
+ * Cost: N × (tasks × arms × seedsPerArm) re-runs. Reported to stderr up
341
+ * front so the operator can abort if the projection is too expensive.
342
+ */
343
+ export async function runAttributeCli(options) {
344
+ if (!fs.existsSync(options.basePath)) {
345
+ return {
346
+ exitCode: 2,
347
+ stdout: "",
348
+ stderr: `bench attribute: base report not found: ${options.basePath}\n`,
349
+ };
350
+ }
351
+ let baseEnvelope;
352
+ try {
353
+ baseEnvelope = JSON.parse(fs.readFileSync(options.basePath, "utf8"));
354
+ }
355
+ catch (err) {
356
+ return {
357
+ exitCode: 2,
358
+ stdout: "",
359
+ stderr: `bench attribute: failed to parse ${options.basePath}: ${err instanceof Error ? err.message : String(err)}\n`,
360
+ };
361
+ }
362
+ const corpus = (baseEnvelope.corpus ?? {});
363
+ const sliceRaw = (corpus.slice ?? "all");
364
+ const slice = sliceRaw === "train" || sliceRaw === "eval" ? sliceRaw : "all";
365
+ const sliceFilter = slice === "all" ? undefined : slice;
366
+ const tasks = listTasks(sliceFilter ? { slice: sliceFilter } : {});
367
+ const seedsPerArm = typeof corpus.seedsPerArm === "number" ? corpus.seedsPerArm : 5;
368
+ const agent = (baseEnvelope.agent ?? {});
369
+ const model = options.modelOverride ?? (typeof agent.model === "string" ? agent.model : "unknown");
370
+ // The stored envelope's perAsset is in snake_case. Convert it back to the
371
+ // PerAssetAttribution shape the metrics module expects so we can pass it
372
+ // through to runMaskedCorpus.
373
+ const perAssetSerialised = baseEnvelope.perAsset;
374
+ const perAsset = {
375
+ totalAkmRuns: perAssetSerialised?.total_akm_runs ?? 0,
376
+ rows: (perAssetSerialised?.rows ?? []).map((r) => ({
377
+ assetRef: String(r.asset_ref ?? ""),
378
+ loadCount: Number(r.load_count ?? 0),
379
+ loadCountPassing: Number(r.load_count_passing ?? 0),
380
+ loadCountFailing: Number(r.load_count_failing ?? 0),
381
+ loadPassRate: r.load_pass_rate === null ? null : Number(r.load_pass_rate),
382
+ })),
383
+ };
384
+ if (perAsset.rows.length === 0) {
385
+ return {
386
+ exitCode: 2,
387
+ stdout: "",
388
+ stderr: "bench attribute: base report has no per-asset attribution rows (no assets loaded). Re-run `bench utility` first.\n",
389
+ };
390
+ }
391
+ const desired = Math.max(1, options.topN);
392
+ const clamped = Math.min(desired, perAsset.rows.length);
393
+ // Prefer the persisted `runs[]` array (#249). When the report carries
394
+ // serialised raw runs we hydrate them back into RunResult shape and feed
395
+ // them to `runMaskedCorpus` directly — that keeps attribution faithful to
396
+ // the original (task, arm, seed) bag instead of synthesising stubs from
397
+ // the per-asset aggregate. Falls back to the legacy aggregate path when
398
+ // the report pre-dates the `runs[]` field.
399
+ const persistedRuns = readPersistedRuns(baseEnvelope);
400
+ const akmRuns = persistedRuns !== null ? persistedRuns.filter((r) => r.arm === "akm") : synthesiseAkmRunsFromAttribution(perAsset);
401
+ const baseReport = {
402
+ timestamp: String(baseEnvelope.timestamp ?? ""),
403
+ branch: String(baseEnvelope.branch ?? ""),
404
+ commit: String(baseEnvelope.commit ?? ""),
405
+ model,
406
+ corpus: {
407
+ domains: typeof corpus.domains === "number" ? corpus.domains : 0,
408
+ tasks: typeof corpus.tasks === "number" ? corpus.tasks : tasks.length,
409
+ slice,
410
+ seedsPerArm,
411
+ },
412
+ aggregateNoakm: extractCorpusMetrics(baseEnvelope, "noakm"),
413
+ aggregateAkm: extractCorpusMetrics(baseEnvelope, "akm"),
414
+ aggregateDelta: extractCorpusMetrics(baseEnvelope, "delta"),
415
+ trajectoryAkm: { correctAssetLoaded: null, feedbackRecorded: 0 },
416
+ failureModes: { byLabel: {}, byTask: {} },
417
+ tasks: [],
418
+ warnings: [],
419
+ perAsset,
420
+ akmRuns,
421
+ taskMetadata: tasks,
422
+ };
423
+ const projection = clamped * tasks.length * 2 * seedsPerArm;
424
+ let stderr = `bench attribute: masking top ${clamped} of ${perAsset.rows.length} assets; ${clamped} × ${tasks.length} tasks × 2 arms × ${seedsPerArm} seeds = ${projection} re-runs.\n`;
425
+ const baseOptions = {
426
+ arms: ["noakm", "akm"],
427
+ model,
428
+ seedsPerArm,
429
+ };
430
+ const maskedRunner = options.runUtility ?? defaultMaskedRunner;
431
+ let maskedResult;
432
+ try {
433
+ maskedResult = await runMaskedCorpus({
434
+ baseReport,
435
+ topN: clamped,
436
+ runUtility: maskedRunner,
437
+ baseOptions,
438
+ ...(options.fixturesRoot ? { fixturesRoot: options.fixturesRoot } : {}),
439
+ });
440
+ }
441
+ catch (err) {
442
+ return {
443
+ exitCode: 1,
444
+ stdout: "",
445
+ stderr: `${stderr}bench attribute: masked-corpus run failed: ${err instanceof Error ? err.message : String(err)}\n`,
446
+ };
447
+ }
448
+ const json = {
449
+ schemaVersion: 1,
450
+ track: "attribute",
451
+ base: { path: options.basePath, model },
452
+ // Issue #251: surface the masking strategy + the exact masked refs in
453
+ // the JSON envelope so operators can audit the marginal-contribution
454
+ // numbers without re-running the masker. The `maskedRefs` order matches
455
+ // `attributions[]`. Strategy is currently always `"leave-one-out"`;
456
+ // future strategies extend the union in `MaskedCorpusResult`.
457
+ attribution: {
458
+ maskingStrategy: maskedResult.maskingStrategy,
459
+ maskedRefs: maskedResult.maskedRefs,
460
+ },
461
+ maskingStrategy: maskedResult.maskingStrategy,
462
+ runsPerformed: maskedResult.runsPerformed,
463
+ perAsset: {
464
+ total_akm_runs: perAsset.totalAkmRuns,
465
+ rows: perAsset.rows.map((r) => ({
466
+ asset_ref: r.assetRef,
467
+ load_count: r.loadCount,
468
+ load_count_passing: r.loadCountPassing,
469
+ load_count_failing: r.loadCountFailing,
470
+ load_pass_rate: r.loadPassRate,
471
+ })),
472
+ },
473
+ attributions: maskedResult.attributions.map((a) => ({
474
+ asset_ref: a.assetRef,
475
+ base_pass_rate: a.basePassRate,
476
+ masked_pass_rate: a.maskedPassRate,
477
+ marginal_contribution: a.marginalContribution,
478
+ })),
479
+ };
480
+ const stdout = `${JSON.stringify(json, null, 2)}\n`;
481
+ if (!options.json) {
482
+ stderr += `${renderAttributionTable(perAsset)}\n`;
483
+ stderr += `\n## Marginal contributions (leave-one-out)\n\n`;
484
+ stderr += `| asset_ref | base_pass_rate | masked_pass_rate | marginal_contribution |\n`;
485
+ stderr += `|-----------|----------------|------------------|-----------------------|\n`;
486
+ for (const a of maskedResult.attributions) {
487
+ stderr += `| \`${a.assetRef}\` | ${a.basePassRate.toFixed(2)} | ${a.maskedPassRate.toFixed(2)} | ${signed(a.marginalContribution.toFixed(2))} |\n`;
488
+ }
489
+ }
490
+ return { exitCode: 0, stdout, stderr };
491
+ }
492
+ /** Default real-runner wrapper for masked re-runs. */
493
+ async function defaultMaskedRunner(options) {
494
+ const arms = options.arms;
495
+ return runUtility({
496
+ tasks: options.tasks,
497
+ arms,
498
+ model: options.model,
499
+ ...(options.seedsPerArm !== undefined ? { seedsPerArm: options.seedsPerArm } : {}),
500
+ ...(options.budgetTokens !== undefined ? { budgetTokens: options.budgetTokens } : {}),
501
+ ...(options.budgetWallMs !== undefined ? { budgetWallMs: options.budgetWallMs } : {}),
502
+ ...(options.slice !== undefined ? { slice: options.slice } : {}),
503
+ ...(options.timestamp !== undefined ? { timestamp: options.timestamp } : {}),
504
+ ...(options.branch !== undefined ? { branch: options.branch } : {}),
505
+ ...(options.commit !== undefined ? { commit: options.commit } : {}),
506
+ ...(options.spawn ? { spawn: options.spawn } : {}),
507
+ ...(options.materialiseStash !== undefined ? { materialiseStash: options.materialiseStash } : {}),
508
+ });
509
+ }
510
+ /**
511
+ * Best-effort extractor for `aggregate.<arm>` corpus metrics from the
512
+ * persisted §13.3 envelope. The envelope keys are snake-cased.
513
+ */
514
+ function extractCorpusMetrics(envelope, key) {
515
+ const aggregate = (envelope.aggregate ?? {});
516
+ const node = (aggregate[key] ?? {});
517
+ return {
518
+ passRate: typeof node.pass_rate === "number" ? node.pass_rate : 0,
519
+ tokensPerPass: node.tokens_per_pass === null ? null : typeof node.tokens_per_pass === "number" ? node.tokens_per_pass : null,
520
+ tokensPerRun: node.tokens_per_run === null ? null : typeof node.tokens_per_run === "number" ? node.tokens_per_run : null,
521
+ wallclockMs: typeof node.wallclock_ms === "number" ? node.wallclock_ms : 0,
522
+ };
523
+ }
524
+ /**
525
+ * Read the persisted `runs[]` array (#249) from a §13.3 envelope and hydrate
526
+ * each row back into the in-memory `RunResult` shape. Returns `null` when the
527
+ * envelope pre-dates the field (legacy reports) so callers can fall back to
528
+ * the aggregate-only path.
529
+ *
530
+ * Structurally validates each row: rows that don't carry the required keys
531
+ * are skipped silently. We intentionally avoid throwing — older envelopes
532
+ * with partial shapes still want to flow through the legacy path.
533
+ */
534
+ function readPersistedRuns(envelope) {
535
+ const raw = envelope.runs;
536
+ if (!Array.isArray(raw))
537
+ return null;
538
+ const out = [];
539
+ for (const r of raw) {
540
+ if (!r || typeof r !== "object")
541
+ continue;
542
+ const row = r;
543
+ if (typeof row.task_id !== "string")
544
+ continue;
545
+ if (typeof row.arm !== "string")
546
+ continue;
547
+ if (typeof row.seed !== "number")
548
+ continue;
549
+ if (typeof row.outcome !== "string")
550
+ continue;
551
+ // Trajectory shape: tolerate missing/partial sub-object so we don't
552
+ // reject otherwise-valid rows.
553
+ const traj = (row.trajectory ?? {});
554
+ const normalised = {
555
+ task_id: row.task_id,
556
+ arm: row.arm,
557
+ seed: row.seed,
558
+ model: typeof row.model === "string" ? row.model : "unknown",
559
+ outcome: row.outcome,
560
+ tokens: row.tokens ?? { input: 0, output: 0 },
561
+ wallclock_ms: typeof row.wallclock_ms === "number" ? row.wallclock_ms : 0,
562
+ verifier_exit_code: typeof row.verifier_exit_code === "number" ? row.verifier_exit_code : 0,
563
+ trajectory: {
564
+ correct_asset_loaded: traj.correct_asset_loaded ?? null,
565
+ feedback_recorded: traj.feedback_recorded ?? null,
566
+ },
567
+ assets_loaded: Array.isArray(row.assets_loaded) ? row.assets_loaded : [],
568
+ failure_mode: typeof row.failure_mode === "string" ? row.failure_mode : null,
569
+ };
570
+ out.push(rehydrateRunFromSerialized(normalised));
571
+ }
572
+ return out;
573
+ }
574
+ /**
575
+ * Build a synthetic akm-arm RunResult bag from a previously-computed
576
+ * attribution table. Used when we load a §13.3 envelope from disk: the
577
+ * envelope doesn't carry raw RunResults, but the attribution table is
578
+ * lossless w.r.t. (asset, pass/fail) counts — which is all
579
+ * `computePerAssetAttribution` needs to reproduce the top-N ranking.
580
+ *
581
+ * Each synthetic run loads exactly one asset. This over-counts the run
582
+ * total but keeps the per-asset counts faithful to the original table. The
583
+ * synthesised runs are NOT consumed by `runMaskedCorpus` for the masked
584
+ * runs themselves — those go through the injected runner — they only seed
585
+ * `report.akmRuns` so that recomputing the attribution gives back the
586
+ * same top-N ordering.
587
+ */
588
+ function synthesiseAkmRunsFromAttribution(perAsset) {
589
+ const out = [];
590
+ for (const row of perAsset.rows) {
591
+ for (let i = 0; i < row.loadCountPassing; i++) {
592
+ out.push(makeSyntheticRun("pass", row.assetRef));
593
+ }
594
+ for (let i = 0; i < row.loadCountFailing; i++) {
595
+ out.push(makeSyntheticRun("fail", row.assetRef));
596
+ }
597
+ }
598
+ return out;
599
+ }
600
+ function makeSyntheticRun(outcome, ref) {
601
+ return {
602
+ schemaVersion: 1,
603
+ taskId: "synthetic",
604
+ arm: "akm",
605
+ seed: 0,
606
+ model: "synthetic",
607
+ outcome,
608
+ tokens: { input: 0, output: 0 },
609
+ wallclockMs: 0,
610
+ trajectory: { correctAssetLoaded: null, feedbackRecorded: null },
611
+ events: [],
612
+ verifierStdout: "",
613
+ verifierExitCode: outcome === "pass" ? 0 : 1,
614
+ assetsLoaded: [ref],
615
+ };
616
+ }
617
+ function signed(text) {
618
+ if (text.startsWith("-"))
619
+ return text;
620
+ if (text === "0" || text === "0.00" || text === "0.0")
621
+ return text;
622
+ return `+${text}`;
623
+ }
624
+ function getEnv(name) {
625
+ const value = process.env[name];
626
+ return value && value.length > 0 ? value : undefined;
627
+ }
628
+ function parseInt32(text, fallback) {
629
+ if (text === undefined)
630
+ return fallback;
631
+ const n = Number.parseInt(text, 10);
632
+ if (!Number.isFinite(n) || n <= 0)
633
+ return fallback;
634
+ return n;
635
+ }
636
+ function parseFloatArg(text, fallback) {
637
+ if (text === undefined)
638
+ return fallback;
639
+ const n = Number.parseFloat(text);
640
+ if (!Number.isFinite(n) || n < 0)
641
+ return fallback;
642
+ return n;
643
+ }
644
+ /**
645
+ * Set of obsolete-flag names that have already emitted their stderr
646
+ * warning during this process. Used by `warnObsolete` to dedupe.
647
+ *
648
+ * Exported as a test seam so unit tests can clear the cache between
649
+ * cases without restarting the process.
650
+ */
651
+ export const obsoleteFlagWarned = new Set();
652
+ /**
653
+ * Emit a one-line `[obsolete] ...` warning on stderr the FIRST time the
654
+ * named flag is used in this process. Subsequent calls with the same
655
+ * `name` are silent so a single invocation never emits the same warning
656
+ * twice. Internal: wired into the existing utility/evolve dispatch
657
+ * branches; the new config-file path never triggers these.
658
+ */
659
+ function warnObsolete(name, replacement) {
660
+ if (obsoleteFlagWarned.has(name))
661
+ return;
662
+ obsoleteFlagWarned.add(name);
663
+ process.stderr.write(`[obsolete] ${name} → ${replacement}\n`);
664
+ }
665
+ /**
666
+ * Detect whether the user supplied any of the flags marked obsolete in
667
+ * BENCH.md §G and emit one warning per used flag. The flags continue to
668
+ * function — the warning is the only behavior change.
669
+ */
670
+ function warnIfObsoleteFlagsUsed(parsed) {
671
+ if (parsed.bool.has("no-noakm")) {
672
+ warnObsolete("--no-noakm", 'use `arms: ["akm"]` in a run config');
673
+ }
674
+ if (parsed.bool.has("include-synthetic")) {
675
+ warnObsolete("--include-synthetic", 'use `arms: [..., "synthetic"]` in a run config');
676
+ }
677
+ if (parsed.flags.has("opencode-config")) {
678
+ warnObsolete("--opencode-config", "use `providersRef` in a run config, BENCH_OPENCODE_CONFIG, or ~/.config/akm/bench-providers.json");
679
+ }
680
+ if (parsed.flags.has("budget-tokens")) {
681
+ warnObsolete("--budget-tokens", "use `budgetTokens` in a run config");
682
+ }
683
+ if (parsed.flags.has("budget-wall-ms")) {
684
+ warnObsolete("--budget-wall-ms", "use `budgetWallMs` in a run config");
685
+ }
686
+ }
687
+ /**
688
+ * `<config.json>` dispatch — load a bench run config, resolve providers
689
+ * and tasks, invoke `runUtility`, and emit the §13.3 envelope on stdout.
690
+ *
691
+ * Behaves identically to `runUtilityCli` from a stdout/stderr/exit-code
692
+ * standpoint: JSON on stdout, optional markdown summary on stderr,
693
+ * returns 0/2/78 mirroring the existing semantics.
694
+ */
695
+ export async function runConfigCli(options) {
696
+ let resolved;
697
+ try {
698
+ const overrides = {};
699
+ if (options.tasksList)
700
+ overrides.tasksList = options.tasksList;
701
+ if (options.seedsPerArm !== undefined)
702
+ overrides.seedsPerArm = options.seedsPerArm;
703
+ if (options.parallel !== undefined)
704
+ overrides.parallel = options.parallel;
705
+ resolved = loadBenchRunConfig(options.configPath, overrides);
706
+ }
707
+ catch (err) {
708
+ const exitCode = err instanceof BenchConfigError && err.isUsageError ? 2 : 78;
709
+ return {
710
+ exitCode,
711
+ stdout: "",
712
+ stderr: `bench: ${err instanceof Error ? err.message : String(err)}\n`,
713
+ };
714
+ }
715
+ const report = await runUtility({
716
+ tasks: resolved.tasks,
717
+ arms: resolved.arms,
718
+ model: resolved.model,
719
+ slice: resolved.slice,
720
+ ...(resolved.seedsPerArm !== undefined ? { seedsPerArm: resolved.seedsPerArm } : {}),
721
+ ...(resolved.budgetTokens !== undefined ? { budgetTokens: resolved.budgetTokens } : {}),
722
+ ...(resolved.budgetWallMs !== undefined ? { budgetWallMs: resolved.budgetWallMs } : {}),
723
+ ...(resolved.parallel !== undefined ? { parallel: resolved.parallel } : {}),
724
+ ...(resolved.forceParallel ? { forceParallel: true } : {}),
725
+ ...(resolved.baselineByTaskId ? { baselineByTaskId: resolved.baselineByTaskId } : {}),
726
+ ...(options.timestamp !== undefined ? { timestamp: options.timestamp } : {}),
727
+ ...(options.branch !== undefined ? { branch: options.branch } : {}),
728
+ ...(options.commit !== undefined ? { commit: options.commit } : {}),
729
+ opencodeProviders: resolved.providers,
730
+ // Synthetic arm follows from `arms` containing "synthetic".
731
+ ...(resolved.arms.includes("synthetic") ? { includeSynthetic: true } : {}),
732
+ });
733
+ const { json, markdown } = renderUtilityReport(report);
734
+ const stdout = `${JSON.stringify(json, null, 2)}\n`;
735
+ let stderr = options.json ? "" : `${markdown}\n`;
736
+ stderr += `bench: config=${resolved.name} tasks=${resolved.tasks.length} arms=${resolved.arms.join(",")} model=${resolved.model}\n`;
737
+ return { exitCode: 0, stdout, stderr };
738
+ }
739
+ /**
740
+ * `evolve` subcommand. Filters the corpus to one domain (or `all`), then
741
+ * dispatches `runEvolve` and renders the §6.3+§6.4 envelope.
742
+ */
743
+ export async function runEvolveCli(options) {
744
+ // Discover all tasks then filter on domain.
745
+ const allTasks = listTasks();
746
+ const tasks = options.domain === "all" ? allTasks : allTasks.filter((t) => t.domain === options.domain);
747
+ if (tasks.length === 0) {
748
+ return {
749
+ exitCode: 2,
750
+ stdout: "",
751
+ stderr: `bench evolve: no tasks matched domain "${options.domain}".\n`,
752
+ };
753
+ }
754
+ const report = await runEvolve({
755
+ tasks,
756
+ model: options.model,
757
+ seedsPerArm: options.seedsPerArm,
758
+ budgetTokens: options.budgetTokens,
759
+ budgetWallMs: options.budgetWallMs,
760
+ negativeThreshold: options.negativeThreshold,
761
+ ...(options.branch !== undefined ? { branch: options.branch } : {}),
762
+ ...(options.commit !== undefined ? { commit: options.commit } : {}),
763
+ ...(options.timestamp !== undefined ? { timestamp: options.timestamp } : {}),
764
+ });
765
+ const { json, markdown } = renderEvolveReport(report);
766
+ const stdout = `${JSON.stringify(json, null, 2)}\n`;
767
+ let stderr = options.json ? "" : `${markdown}\n`;
768
+ stderr += `tasks discovered: ${tasks.length} (domain=${options.domain})\n`;
769
+ return { exitCode: 0, stdout, stderr };
770
+ }
771
+ async function main(argv) {
772
+ const parsed = parseArgs(argv);
773
+ if (parsed.bool.has("help") || parsed.subcommand === "" || parsed.subcommand === "help") {
774
+ process.stdout.write(HELP);
775
+ return parsed.subcommand === "" ? 2 : 0;
776
+ }
777
+ // Config-file dispatch: when argv[0] looks like a JSON path that exists,
778
+ // route to `runConfigCli`. This is the new common-case entry point —
779
+ // existing subcommand-style invocations are untouched.
780
+ if (parsed.subcommand.endsWith(".json") && fs.existsSync(parsed.subcommand)) {
781
+ const tasksRaw = parsed.flags.get("tasks");
782
+ const tasksList = tasksRaw
783
+ ? tasksRaw
784
+ .split(",")
785
+ .map((s) => s.trim())
786
+ .filter((s) => s.length > 0)
787
+ : undefined;
788
+ const seedsRaw = parsed.flags.get("seeds");
789
+ const parallelRaw = parsed.flags.get("parallel");
790
+ const removePid = writeBenchPid();
791
+ let result;
792
+ try {
793
+ result = await runConfigCli({
794
+ configPath: parsed.subcommand,
795
+ json: parsed.bool.has("json"),
796
+ ...(tasksList ? { tasksList } : {}),
797
+ ...(seedsRaw !== undefined ? { seedsPerArm: parseInt32(seedsRaw, 5) } : {}),
798
+ ...(parallelRaw !== undefined ? { parallel: parseInt32(parallelRaw, 1) } : {}),
799
+ });
800
+ }
801
+ finally {
802
+ removePid();
803
+ }
804
+ if (result.stdout)
805
+ process.stdout.write(result.stdout);
806
+ if (result.stderr)
807
+ process.stderr.write(result.stderr);
808
+ return result.exitCode;
809
+ }
810
+ // Emit obsolete-flag warnings for the legacy subcommand path. The new
811
+ // config-file path above never reaches this code so config-mode runs
812
+ // never spuriously warn.
813
+ warnIfObsoleteFlagsUsed(parsed);
814
+ switch (parsed.subcommand) {
815
+ case "utility": {
816
+ const sliceRaw = parsed.flags.get("tasks") ?? "all";
817
+ if (sliceRaw !== "train" && sliceRaw !== "eval" && sliceRaw !== "all") {
818
+ process.stderr.write(`bench utility: invalid --tasks value "${sliceRaw}"; expected one of: all, train, eval.\n`);
819
+ return 2;
820
+ }
821
+ const slice = sliceRaw;
822
+ // Load provider config at CLI startup (before any runs).
823
+ let opencodeProviders;
824
+ try {
825
+ opencodeProviders = discoverOpencodeProviders(parsed.flags.get("opencode-config"));
826
+ }
827
+ catch (err) {
828
+ const exitCode = err instanceof BenchConfigError && err.isUsageError ? 2 : 78;
829
+ process.stderr.write(`bench utility: ${err instanceof Error ? err.message : String(err)}\n`);
830
+ return exitCode;
831
+ }
832
+ // BENCH_OPENCODE_MODEL: flag → env var → loaded.defaultModel → error exit 2.
833
+ const model = getEnv("BENCH_OPENCODE_MODEL") ?? opencodeProviders?.defaultModel;
834
+ if (!model) {
835
+ process.stderr.write("bench utility: BENCH_OPENCODE_MODEL environment variable is required.\n");
836
+ return 2;
837
+ }
838
+ // Write PID file so `bench kill` can terminate this run.
839
+ const removePid = writeBenchPid();
840
+ let result;
841
+ try {
842
+ result = await runUtilityCli({
843
+ slice,
844
+ json: parsed.bool.has("json"),
845
+ seedsPerArm: parseInt32(parsed.flags.get("seeds"), 5),
846
+ budgetTokens: parseInt32(parsed.flags.get("budget-tokens"), 30000),
847
+ budgetWallMs: parseInt32(parsed.flags.get("budget-wall-ms"), 120000),
848
+ model,
849
+ parallel: parseInt32(parsed.flags.get("parallel"), 1),
850
+ ...(parsed.bool.has("force-parallel") ? { forceParallel: true } : {}),
851
+ ...(parsed.bool.has("include-synthetic") ? { includeSynthetic: true } : {}),
852
+ ...(parsed.bool.has("no-noakm") ? { includeNoakm: false } : {}),
853
+ ...(opencodeProviders ? { opencodeProviders } : {}),
854
+ });
855
+ }
856
+ finally {
857
+ removePid();
858
+ }
859
+ if (result.stdout)
860
+ process.stdout.write(result.stdout);
861
+ if (result.stderr)
862
+ process.stderr.write(result.stderr);
863
+ return result.exitCode;
864
+ }
865
+ case "evolve": {
866
+ const domain = parsed.flags.get("tasks");
867
+ if (!domain) {
868
+ process.stderr.write("bench evolve: --tasks <domain> is required (use --tasks all to run the full corpus).\n");
869
+ return 2;
870
+ }
871
+ // Load provider config at CLI startup (before any runs).
872
+ let opencodeProvidersEvolve;
873
+ try {
874
+ opencodeProvidersEvolve = discoverOpencodeProviders(parsed.flags.get("opencode-config"));
875
+ }
876
+ catch (err) {
877
+ const exitCode = err instanceof BenchConfigError && err.isUsageError ? 2 : 78;
878
+ process.stderr.write(`bench evolve: ${err instanceof Error ? err.message : String(err)}\n`);
879
+ return exitCode;
880
+ }
881
+ const model = getEnv("BENCH_OPENCODE_MODEL") ?? opencodeProvidersEvolve?.defaultModel;
882
+ if (!model) {
883
+ process.stderr.write("bench evolve: BENCH_OPENCODE_MODEL environment variable is required.\n");
884
+ return 2;
885
+ }
886
+ // Write PID file so `bench kill` can terminate this run.
887
+ const removePidEvolve = writeBenchPid();
888
+ let resultEvolve;
889
+ try {
890
+ resultEvolve = await runEvolveCli({
891
+ domain,
892
+ json: parsed.bool.has("json"),
893
+ seedsPerArm: parseInt32(parsed.flags.get("seeds"), 5),
894
+ budgetTokens: parseInt32(parsed.flags.get("budget-tokens"), 30000),
895
+ budgetWallMs: parseInt32(parsed.flags.get("budget-wall-ms"), 120000),
896
+ model,
897
+ parallel: parseInt32(parsed.flags.get("parallel"), 1),
898
+ ...(parsed.bool.has("force-parallel") ? { forceParallel: true } : {}),
899
+ negativeThreshold: {
900
+ absoluteCount: parseInt32(parsed.flags.get("negative-threshold-count"), 2),
901
+ ratio: parseFloatArg(parsed.flags.get("negative-threshold-ratio"), 0.5),
902
+ },
903
+ ...(opencodeProvidersEvolve ? { opencodeProviders: opencodeProvidersEvolve } : {}),
904
+ });
905
+ }
906
+ finally {
907
+ removePidEvolve();
908
+ }
909
+ if (resultEvolve.stdout)
910
+ process.stdout.write(resultEvolve.stdout);
911
+ if (resultEvolve.stderr)
912
+ process.stderr.write(resultEvolve.stderr);
913
+ return resultEvolve.exitCode;
914
+ }
915
+ case "compare": {
916
+ const basePath = parsed.flags.get("base");
917
+ const currentPath = parsed.flags.get("current");
918
+ if (!basePath || !currentPath) {
919
+ process.stderr.write("bench compare: --base and --current are both required.\n");
920
+ return 2;
921
+ }
922
+ const result = runCompareCli({
923
+ basePath,
924
+ currentPath,
925
+ json: parsed.bool.has("json"),
926
+ allowCorpusMismatch: parsed.bool.has("allow-corpus-mismatch"),
927
+ allowFixtureMismatch: parsed.bool.has("allow-fixture-mismatch"),
928
+ });
929
+ if (result.stdout)
930
+ process.stdout.write(result.stdout);
931
+ if (result.stderr)
932
+ process.stderr.write(result.stderr);
933
+ return result.exitCode;
934
+ }
935
+ case "attribute": {
936
+ const basePath = parsed.flags.get("base");
937
+ if (!basePath) {
938
+ process.stderr.write("bench attribute: --base <path> is required.\n");
939
+ return 2;
940
+ }
941
+ // Load provider config for parity (attribute re-runs use the same model + provider).
942
+ let opencodeProvidersAttr;
943
+ try {
944
+ opencodeProvidersAttr = discoverOpencodeProviders(parsed.flags.get("opencode-config"));
945
+ }
946
+ catch (err) {
947
+ const exitCode = err instanceof BenchConfigError && err.isUsageError ? 2 : 78;
948
+ process.stderr.write(`bench attribute: ${err instanceof Error ? err.message : String(err)}\n`);
949
+ return exitCode;
950
+ }
951
+ // Suppress unused variable warning — opencodeProvidersAttr is exposed for
952
+ // future wiring when runMaskedCorpus accepts it. For now it only validates.
953
+ void opencodeProvidersAttr;
954
+ const topN = parseInt32(parsed.flags.get("top"), 5);
955
+ const result = await runAttributeCli({
956
+ basePath,
957
+ topN,
958
+ json: parsed.bool.has("json"),
959
+ });
960
+ if (result.stdout)
961
+ process.stdout.write(result.stdout);
962
+ if (result.stderr)
963
+ process.stderr.write(result.stderr);
964
+ return result.exitCode;
965
+ }
966
+ case "kill": {
967
+ const pid = readBenchPid();
968
+ if (pid === undefined) {
969
+ process.stdout.write("no bench running\n");
970
+ return 0;
971
+ }
972
+ if (!isPidRunning(pid)) {
973
+ process.stdout.write(`no bench running (stale PID file for PID ${pid} — cleaning up)\n`);
974
+ try {
975
+ const { benchPidPath } = await import("./tmp");
976
+ const { default: nodeFs } = await import("node:fs");
977
+ nodeFs.rmSync(benchPidPath(), { force: true });
978
+ }
979
+ catch {
980
+ /* best-effort */
981
+ }
982
+ return 0;
983
+ }
984
+ try {
985
+ process.kill(pid, "SIGTERM");
986
+ process.stdout.write(`sent SIGTERM to bench process ${pid}\n`);
987
+ process.stdout.write("run `bench kill` again to escalate to SIGKILL if the process does not exit.\n");
988
+ }
989
+ catch (err) {
990
+ process.stderr.write(`bench kill: failed to signal PID ${pid}: ${err instanceof Error ? err.message : String(err)}\n`);
991
+ return 1;
992
+ }
993
+ return 0;
994
+ }
995
+ case "clean": {
996
+ const benchRoot = path.join(getCacheDir(), "bench");
997
+ try {
998
+ fs.rmSync(benchRoot, { recursive: true, force: true });
999
+ process.stderr.write(`bench clean: removed ${benchRoot}\n`);
1000
+ }
1001
+ catch (err) {
1002
+ process.stderr.write(`bench clean: failed to remove ${benchRoot}: ${err.message}\n`);
1003
+ return 1;
1004
+ }
1005
+ return 0;
1006
+ }
1007
+ default:
1008
+ process.stderr.write(`unknown subcommand: ${parsed.subcommand}\n`);
1009
+ process.stderr.write(HELP);
1010
+ return 2;
1011
+ }
1012
+ }
1013
+ // Only execute when invoked directly. The exported `runUtilityCli` is callable
1014
+ // from tests without triggering process.exit.
1015
+ if (import.meta.main) {
1016
+ const code = await main(process.argv.slice(2));
1017
+ process.exit(code);
1018
+ }