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,996 @@
1
+ /**
2
+ * Unit tests for per-asset attribution (spec §6.5).
3
+ *
4
+ * Coverage:
5
+ * • `extractAssetLoads` — parses both events.jsonl event objects and
6
+ * verifierStdout substrings (literal `akm show` and tool-call JSON).
7
+ * • `computePerAssetAttribution` — counts pass/fail loads, computes pass
8
+ * rate, sorts by load count then pass rate then ref.
9
+ * • `runMaskedCorpus` — picks top-N, masks each asset from the source
10
+ * fixture, computes marginal contribution. Cost accounting verified
11
+ * against the injected runUtility callable. Source fixture is untouched.
12
+ * • CLI `attribute --top` clamping when top exceeds asset count.
13
+ */
14
+ import { describe, expect, test } from "bun:test";
15
+ import fs from "node:fs";
16
+ import path from "node:path";
17
+ import { runAttributeCli } from "./cli";
18
+ import { computePerAssetAttribution, extractAssetLoads, runMaskedCorpus, } from "./metrics";
19
+ import { renderAttributionTable } from "./report";
20
+ import { benchMkdtemp, benchTmpRoot } from "./tmp";
21
+ function makeRun(overrides = {}) {
22
+ return {
23
+ schemaVersion: 1,
24
+ taskId: "t",
25
+ arm: "akm",
26
+ seed: 0,
27
+ model: "m",
28
+ outcome: "pass",
29
+ tokens: { input: 0, output: 0 },
30
+ wallclockMs: 0,
31
+ trajectory: { correctAssetLoaded: null, feedbackRecorded: null },
32
+ events: [],
33
+ verifierStdout: "",
34
+ verifierExitCode: 0,
35
+ assetsLoaded: [],
36
+ ...overrides,
37
+ };
38
+ }
39
+ function makeReport(akmRuns) {
40
+ return {
41
+ timestamp: "2026-04-27T00:00:00Z",
42
+ branch: "test",
43
+ commit: "abc",
44
+ model: "m",
45
+ corpus: { domains: 1, tasks: 1, slice: "all", seedsPerArm: akmRuns.length },
46
+ aggregateNoakm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
47
+ aggregateAkm: {
48
+ passRate: akmRuns.filter((r) => r.outcome === "pass").length / Math.max(1, akmRuns.length),
49
+ tokensPerPass: null,
50
+ tokensPerRun: null,
51
+ wallclockMs: 0,
52
+ },
53
+ aggregateDelta: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
54
+ trajectoryAkm: { correctAssetLoaded: null, feedbackRecorded: 0 },
55
+ failureModes: { byLabel: {}, byTask: {} },
56
+ tasks: [],
57
+ warnings: [],
58
+ akmRuns,
59
+ };
60
+ }
61
+ describe("extractAssetLoads", () => {
62
+ test("parses literal `akm show <ref>` from verifierStdout", () => {
63
+ const r = makeRun({ verifierStdout: "tool: akm show skill:docker-homelab\nresult: ok\n" });
64
+ expect(extractAssetLoads(r)).toEqual(["skill:docker-homelab"]);
65
+ });
66
+ test('parses tool-call JSON form `args:["show","<ref>"]`', () => {
67
+ const r = makeRun({
68
+ verifierStdout: '{"command":"akm","args":["show","skill:az-cli"]} done',
69
+ });
70
+ expect(extractAssetLoads(r)).toEqual(["skill:az-cli"]);
71
+ });
72
+ test("dedupes refs and preserves first-seen order", () => {
73
+ const r = makeRun({
74
+ verifierStdout: "akm show skill:foo\nakm show skill:bar\nakm show skill:foo\n",
75
+ });
76
+ expect(extractAssetLoads(r)).toEqual(["skill:foo", "skill:bar"]);
77
+ });
78
+ test("parses ref from events.jsonl `show` event", () => {
79
+ const r = makeRun({
80
+ events: [
81
+ {
82
+ schemaVersion: 1,
83
+ id: 0,
84
+ ts: "2026-04-27T00:00:00Z",
85
+ eventType: "show",
86
+ ref: "skill:from-event",
87
+ },
88
+ ],
89
+ });
90
+ expect(extractAssetLoads(r)).toEqual(["skill:from-event"]);
91
+ });
92
+ test("merges events + stdout sources, dedupes across sources", () => {
93
+ const r = makeRun({
94
+ events: [
95
+ {
96
+ schemaVersion: 1,
97
+ id: 0,
98
+ ts: "2026-04-27T00:00:00Z",
99
+ eventType: "show",
100
+ ref: "skill:shared",
101
+ },
102
+ ],
103
+ verifierStdout: "akm show skill:shared\nakm show skill:only-stdout\n",
104
+ });
105
+ expect(extractAssetLoads(r)).toEqual(["skill:shared", "skill:only-stdout"]);
106
+ });
107
+ test("returns empty array when no `akm show` invocations are present", () => {
108
+ const r = makeRun({ verifierStdout: "agent: I will not search\n" });
109
+ expect(extractAssetLoads(r)).toEqual([]);
110
+ });
111
+ test("supports origin-prefixed refs (`team//skill:foo`)", () => {
112
+ const r = makeRun({ verifierStdout: "akm show team//skill:foo\n" });
113
+ expect(extractAssetLoads(r)).toEqual(["team//skill:foo"]);
114
+ });
115
+ });
116
+ describe("computePerAssetAttribution", () => {
117
+ test("counts pass/fail loads and computes pass rate", () => {
118
+ const runs = [
119
+ // skill:a: 2 pass, 1 fail → 0.667
120
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:a"] }),
121
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:a"] }),
122
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:a"] }),
123
+ // skill:b: 0 pass, 2 fail → 0
124
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:b"] }),
125
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:b"] }),
126
+ // skill:c: 1 pass, 0 fail → 1.0
127
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:c"] }),
128
+ ];
129
+ const attr = computePerAssetAttribution(makeReport(runs));
130
+ expect(attr.totalAkmRuns).toBe(6);
131
+ const a = attr.rows.find((r) => r.assetRef === "skill:a");
132
+ expect(a).toMatchObject({ loadCount: 3, loadCountPassing: 2, loadCountFailing: 1 });
133
+ expect(a?.loadPassRate).toBeCloseTo(2 / 3, 5);
134
+ const b = attr.rows.find((r) => r.assetRef === "skill:b");
135
+ expect(b?.loadPassRate).toBe(0);
136
+ const c = attr.rows.find((r) => r.assetRef === "skill:c");
137
+ expect(c?.loadPassRate).toBe(1);
138
+ });
139
+ test("orders rows by load count desc, pass rate desc, ref asc", () => {
140
+ const runs = [
141
+ // skill:high-load-fail — 4 loads, all fail
142
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:high-load-fail"] }),
143
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:high-load-fail"] }),
144
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:high-load-fail"] }),
145
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:high-load-fail"] }),
146
+ // skill:high-load-pass — 4 loads, all pass (same count, higher pass_rate → first)
147
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:high-load-pass"] }),
148
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:high-load-pass"] }),
149
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:high-load-pass"] }),
150
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:high-load-pass"] }),
151
+ // skill:low-load — 1 load, pass
152
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:low-load"] }),
153
+ ];
154
+ const attr = computePerAssetAttribution(makeReport(runs));
155
+ expect(attr.rows.map((r) => r.assetRef)).toEqual([
156
+ "skill:high-load-pass", // count=4, rate=1
157
+ "skill:high-load-fail", // count=4, rate=0
158
+ "skill:low-load", // count=1
159
+ ]);
160
+ });
161
+ test("returns empty rows when no assets were loaded", () => {
162
+ const runs = [makeRun({ outcome: "pass", assetsLoaded: [] })];
163
+ const attr = computePerAssetAttribution(makeReport(runs));
164
+ expect(attr.rows).toEqual([]);
165
+ expect(attr.totalAkmRuns).toBe(1);
166
+ });
167
+ });
168
+ describe("renderAttributionTable", () => {
169
+ test("highlights well-used-and-working vs well-used-and-not-working", () => {
170
+ const attr = {
171
+ totalAkmRuns: 10,
172
+ rows: [
173
+ { assetRef: "skill:works", loadCount: 8, loadCountPassing: 7, loadCountFailing: 1, loadPassRate: 7 / 8 },
174
+ { assetRef: "skill:broken", loadCount: 6, loadCountPassing: 1, loadCountFailing: 5, loadPassRate: 1 / 6 },
175
+ { assetRef: "skill:rare", loadCount: 1, loadCountPassing: 1, loadCountFailing: 0, loadPassRate: 1 },
176
+ ],
177
+ };
178
+ const md = renderAttributionTable(attr);
179
+ expect(md).toContain("Well-used and working");
180
+ expect(md).toContain("`skill:works`");
181
+ expect(md).toContain("Well-used and NOT working");
182
+ expect(md).toContain("`skill:broken`");
183
+ // skill:rare is below the high-load cutoff so should NOT appear in the working callout (only in the table).
184
+ const workingSection = md.split("Well-used and working")[1]?.split("Well-used and NOT working")[0] ?? "";
185
+ expect(workingSection).not.toContain("`skill:rare`");
186
+ });
187
+ test("renders empty-state message when no rows", () => {
188
+ const md = renderAttributionTable({ totalAkmRuns: 0, rows: [] });
189
+ expect(md).toContain("No assets were loaded");
190
+ });
191
+ });
192
+ describe("runMaskedCorpus", () => {
193
+ function makeFixturesRoot() {
194
+ const root = benchMkdtemp("akm-bench-attr-fixtures-");
195
+ // fixture A: two assets in one .stash.json
196
+ const fixA = path.join(root, "fixtureA");
197
+ fs.mkdirSync(path.join(fixA, "skills"), { recursive: true });
198
+ fs.writeFileSync(path.join(fixA, "MANIFEST.json"), JSON.stringify({ name: "fixtureA", description: "x", purpose: "x", assets: { skill: 2 }, consumers: [] }));
199
+ fs.writeFileSync(path.join(fixA, "skills", ".stash.json"), JSON.stringify({
200
+ entries: [
201
+ { name: "alpha", type: "skill", filename: "alpha.md" },
202
+ { name: "beta", type: "skill", filename: "beta.md" },
203
+ ],
204
+ }));
205
+ fs.writeFileSync(path.join(fixA, "skills", "alpha.md"), "# alpha");
206
+ fs.writeFileSync(path.join(fixA, "skills", "beta.md"), "# beta");
207
+ return root;
208
+ }
209
+ function fakeTask(overrides = {}) {
210
+ return {
211
+ id: "fake/t",
212
+ title: "t",
213
+ domain: "fake",
214
+ difficulty: "easy",
215
+ stash: "fixtureA",
216
+ verifier: "regex",
217
+ expectedMatch: "ok",
218
+ budget: { tokens: 100, wallMs: 1000 },
219
+ taskDir: "/tmp",
220
+ ...overrides,
221
+ };
222
+ }
223
+ test("masks top-N assets, calls runUtility once per asset, leaves source fixture intact", async () => {
224
+ const fixturesRoot = makeFixturesRoot();
225
+ const sourceContents = fs.readFileSync(path.join(fixturesRoot, "fixtureA", "skills", "alpha.md"), "utf8");
226
+ const baseRuns = [
227
+ // alpha: 3 pass, 1 fail → load_count 4
228
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
229
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
230
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
231
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:alpha"] }),
232
+ // beta: 1 pass, 1 fail → load_count 2
233
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:beta"] }),
234
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:beta"] }),
235
+ ];
236
+ const baseReport = makeReport(baseRuns);
237
+ baseReport.taskMetadata = [fakeTask()];
238
+ let callCount = 0;
239
+ const seenStashDirs = [];
240
+ const seenStashFieldUnchanged = [];
241
+ const runUtility = async (options) => {
242
+ callCount += 1;
243
+ // Issue #251: masked re-runs receive the tmp dir through the explicit
244
+ // `stashDirOverride` field, NEVER by mutating `task.stash`. Assert
245
+ // both sides of the contract here.
246
+ const task = options.tasks[0];
247
+ seenStashDirs.push(task?.stashDirOverride ?? "");
248
+ seenStashFieldUnchanged.push(task?.stash === "fixtureA");
249
+ // Simulate that masking alpha drops the pass rate, masking beta does nothing.
250
+ const stashDir = task?.stashDirOverride ?? "";
251
+ const alphaMissing = !fs.existsSync(path.join(stashDir, "skills", "alpha.md"));
252
+ const passRate = alphaMissing ? 0.25 : 0.6;
253
+ return {
254
+ ...baseReport,
255
+ aggregateAkm: { passRate, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
256
+ akmRuns: [],
257
+ };
258
+ };
259
+ const result = await runMaskedCorpus({
260
+ baseReport,
261
+ topN: 5, // > 2 assets, should clamp
262
+ runUtility,
263
+ baseOptions: { arms: ["noakm", "akm"], model: "m", seedsPerArm: 1 },
264
+ fixturesRoot,
265
+ });
266
+ // Only 2 unique assets exist in the base report → topN clamped to 2.
267
+ expect(result.runsPerformed).toBe(2);
268
+ expect(callCount).toBe(2);
269
+ expect(result.attributions.length).toBe(2);
270
+ // Asset ranking: alpha first (load_count 4), beta second.
271
+ const alpha = result.attributions[0];
272
+ expect(alpha?.assetRef).toBe("skill:alpha");
273
+ expect(alpha?.basePassRate).toBeCloseTo(4 / 6, 5);
274
+ expect(alpha?.maskedPassRate).toBe(0.25);
275
+ expect(alpha?.marginalContribution).toBeCloseTo(4 / 6 - 0.25, 5);
276
+ const beta = result.attributions[1];
277
+ expect(beta?.assetRef).toBe("skill:beta");
278
+ expect(beta?.maskedPassRate).toBe(0.6);
279
+ // Source fixture content untouched.
280
+ const sourceContentsAfter = fs.readFileSync(path.join(fixturesRoot, "fixtureA", "skills", "alpha.md"), "utf8");
281
+ expect(sourceContentsAfter).toBe(sourceContents);
282
+ // Source .stash.json still has both entries.
283
+ const stashJsonAfter = JSON.parse(fs.readFileSync(path.join(fixturesRoot, "fixtureA", "skills", ".stash.json"), "utf8"));
284
+ expect(stashJsonAfter.entries.length).toBe(2);
285
+ // The two stash dirs the runner saw should be different tmp dirs (not the source).
286
+ expect(new Set(seenStashDirs).size).toBe(2);
287
+ for (const d of seenStashDirs) {
288
+ expect(d.startsWith(benchTmpRoot())).toBe(true);
289
+ }
290
+ // Issue #251: the original `task.stash` field was NEVER mutated.
291
+ expect(seenStashFieldUnchanged.every(Boolean)).toBe(true);
292
+ // The masking strategy + masked refs are surfaced on the result envelope.
293
+ expect(result.maskingStrategy).toBe("leave-one-out");
294
+ expect(result.maskedRefs).toEqual(["skill:alpha", "skill:beta"]);
295
+ fs.rmSync(fixturesRoot, { recursive: true, force: true });
296
+ });
297
+ test("issue #251: regression — runner uses stashDirOverride, NOT __no-stash__ placeholder", async () => {
298
+ // Bug under fix: when runMaskedCorpus mutated `task.stash` and called
299
+ // runUtility with `materialiseStash: false`, the runner was falling back
300
+ // to `path.join(task.taskDir, "__no-stash__")` for the AKM-arm stashDir,
301
+ // because the runner only consulted `task.stash` to call
302
+ // `loadFixtureStash` (which it skipped) — there was no path that
303
+ // forwarded the masked tmp dir to the agent.
304
+ //
305
+ // This test would FAIL before #251: the masked re-run would see the
306
+ // `__no-stash__` placeholder, `alpha.md` would never appear missing, and
307
+ // the marginal contribution would be 0 (false negative).
308
+ const fixturesRoot = makeFixturesRoot();
309
+ const baseRuns = [
310
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
311
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
312
+ ];
313
+ const baseReport = makeReport(baseRuns);
314
+ baseReport.taskMetadata = [fakeTask({ taskDir: "/some/task/dir" })];
315
+ let observedStashDir;
316
+ let observedExistedDuringRun = false;
317
+ let observedAlphaMissing = false;
318
+ let observedBetaPresent = false;
319
+ let observedTaskStashUnchanged = false;
320
+ const result = await runMaskedCorpus({
321
+ baseReport,
322
+ topN: 1,
323
+ runUtility: async (options) => {
324
+ const task = options.tasks[0];
325
+ observedStashDir = task?.stashDirOverride;
326
+ // The runner-equivalent resolution we are guarding: if the override
327
+ // is missing, the bug would have us fall back to `taskDir/__no-stash__`.
328
+ // Capture state INSIDE the runUtility callback because the tmp dir is
329
+ // reaped in `runMaskedCorpus`'s `finally` after this returns.
330
+ if (observedStashDir) {
331
+ observedExistedDuringRun = fs.existsSync(observedStashDir);
332
+ observedAlphaMissing = !fs.existsSync(path.join(observedStashDir, "skills", "alpha.md"));
333
+ observedBetaPresent = fs.existsSync(path.join(observedStashDir, "skills", "beta.md"));
334
+ }
335
+ observedTaskStashUnchanged = task?.stash === "fixtureA";
336
+ return {
337
+ ...baseReport,
338
+ aggregateAkm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
339
+ akmRuns: [],
340
+ };
341
+ },
342
+ baseOptions: { arms: ["akm"], model: "m", seedsPerArm: 1 },
343
+ fixturesRoot,
344
+ });
345
+ expect(result.runsPerformed).toBe(1);
346
+ // The override MUST be set — that is the whole fix.
347
+ expect(observedStashDir).toBeDefined();
348
+ // It must NOT be the `__no-stash__` placeholder the buggy fallback used.
349
+ expect(observedStashDir?.endsWith("__no-stash__")).toBe(false);
350
+ // While the run was active, the override pointed at a real tmp dir with
351
+ // the masked asset removed and the unmasked asset still present.
352
+ expect(observedExistedDuringRun).toBe(true);
353
+ expect(observedAlphaMissing).toBe(true);
354
+ expect(observedBetaPresent).toBe(true);
355
+ // The stash (fixture name) field was NEVER mutated.
356
+ expect(observedTaskStashUnchanged).toBe(true);
357
+ // After the run, the tmp dir is reaped (cleanup contract).
358
+ expect(observedStashDir && fs.existsSync(observedStashDir)).toBe(false);
359
+ fs.rmSync(fixturesRoot, { recursive: true, force: true });
360
+ });
361
+ test("issue #251: source fixture sentinel survives masked-corpus run", async () => {
362
+ // Sentinel-file smoke test (review addendum #251): plant a known file
363
+ // inside the source fixture stash, run a masked-corpus pass, then assert
364
+ // the sentinel is byte-identical. Guards against a recurrence of #243's
365
+ // operator-config-exposure pattern.
366
+ const fixturesRoot = makeFixturesRoot();
367
+ const sentinelPath = path.join(fixturesRoot, "fixtureA", "skills", "__sentinel_251__");
368
+ const sentinelBody = `do-not-touch-${Date.now()}`;
369
+ fs.writeFileSync(sentinelPath, sentinelBody);
370
+ const baseRuns = [
371
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
372
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:beta"] }),
373
+ ];
374
+ const baseReport = makeReport(baseRuns);
375
+ baseReport.taskMetadata = [fakeTask()];
376
+ await runMaskedCorpus({
377
+ baseReport,
378
+ topN: 2,
379
+ runUtility: async () => ({
380
+ ...baseReport,
381
+ aggregateAkm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
382
+ akmRuns: [],
383
+ }),
384
+ baseOptions: { arms: ["akm"], model: "m", seedsPerArm: 1 },
385
+ fixturesRoot,
386
+ });
387
+ // Sentinel survives unchanged.
388
+ expect(fs.existsSync(sentinelPath)).toBe(true);
389
+ expect(fs.readFileSync(sentinelPath, "utf8")).toBe(sentinelBody);
390
+ // The masked entry's source-fixture content is untouched.
391
+ expect(fs.existsSync(path.join(fixturesRoot, "fixtureA", "skills", "alpha.md"))).toBe(true);
392
+ expect(fs.readFileSync(path.join(fixturesRoot, "fixtureA", "skills", "alpha.md"), "utf8")).toBe("# alpha");
393
+ fs.rmSync(fixturesRoot, { recursive: true, force: true });
394
+ });
395
+ test("issue #251: tmp masked stash dirs are cleaned up after success AND failure", async () => {
396
+ // Cleanup contract from acceptance criteria: try/finally guarantees the
397
+ // tmp dirs are reaped whether the injected runner returns normally or
398
+ // throws. Capture observed dirs from inside the injected runner; after
399
+ // the await they must NOT exist.
400
+ const fixturesRoot = makeFixturesRoot();
401
+ const baseRuns = [
402
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
403
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:beta"] }),
404
+ ];
405
+ const baseReport = makeReport(baseRuns);
406
+ baseReport.taskMetadata = [fakeTask()];
407
+ // Success path.
408
+ const successDirs = [];
409
+ await runMaskedCorpus({
410
+ baseReport,
411
+ topN: 2,
412
+ runUtility: async (options) => {
413
+ const dir = options.tasks[0]?.stashDirOverride;
414
+ if (dir)
415
+ successDirs.push(dir);
416
+ return {
417
+ ...baseReport,
418
+ aggregateAkm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
419
+ akmRuns: [],
420
+ };
421
+ },
422
+ baseOptions: { arms: ["akm"], model: "m", seedsPerArm: 1 },
423
+ fixturesRoot,
424
+ });
425
+ expect(successDirs.length).toBe(2);
426
+ for (const d of successDirs) {
427
+ expect(fs.existsSync(d)).toBe(false);
428
+ }
429
+ // Failure path: the injected runner throws on the second call.
430
+ const failureDirs = [];
431
+ let calls = 0;
432
+ await expect(runMaskedCorpus({
433
+ baseReport,
434
+ topN: 2,
435
+ runUtility: async (options) => {
436
+ calls += 1;
437
+ const dir = options.tasks[0]?.stashDirOverride;
438
+ if (dir)
439
+ failureDirs.push(dir);
440
+ if (calls === 2)
441
+ throw new Error("simulated runner failure");
442
+ return {
443
+ ...baseReport,
444
+ aggregateAkm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
445
+ akmRuns: [],
446
+ };
447
+ },
448
+ baseOptions: { arms: ["akm"], model: "m", seedsPerArm: 1 },
449
+ fixturesRoot,
450
+ })).rejects.toThrow("simulated runner failure");
451
+ // Both tmp dirs created so far are reaped (the second call's dir is
452
+ // created in the try-block before the throw, and the finally-block
453
+ // cleans it up).
454
+ for (const d of failureDirs) {
455
+ expect(fs.existsSync(d)).toBe(false);
456
+ }
457
+ fs.rmSync(fixturesRoot, { recursive: true, force: true });
458
+ });
459
+ test("rejects path-traversal asset refs without deleting anything outside the tmp stash", async () => {
460
+ const fixturesRoot = makeFixturesRoot();
461
+ // A sentinel file outside the fixtures tree — if the masker honoured the
462
+ // hostile `..`-laden ref, the deletion target would be computed via
463
+ // `path.join(fixturesRoot/fixtureA/skills/, "..", "..", "..", "sentinel")`
464
+ // and the sentinel would disappear. The validation must block that.
465
+ const sentinelDir = benchMkdtemp("akm-bench-sentinel-");
466
+ const sentinelFile = path.join(sentinelDir, "sentinel.txt");
467
+ fs.writeFileSync(sentinelFile, "do-not-delete");
468
+ const baseRuns = [
469
+ // Hostile ref: name contains `..` segments. Constructed by hand to
470
+ // simulate a prompt-injected agent emitting `akm show "skill:../../../etc"`.
471
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:../../../etc"] }),
472
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:../../../etc"] }),
473
+ ];
474
+ const baseReport = makeReport(baseRuns);
475
+ baseReport.taskMetadata = [fakeTask()];
476
+ let callCount = 0;
477
+ const result = await runMaskedCorpus({
478
+ baseReport,
479
+ topN: 1,
480
+ runUtility: async () => {
481
+ callCount += 1;
482
+ return {
483
+ ...baseReport,
484
+ aggregateAkm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
485
+ };
486
+ },
487
+ baseOptions: { arms: ["akm"], model: "m", seedsPerArm: 1 },
488
+ fixturesRoot,
489
+ });
490
+ // The masker rejects the hostile ref → null → runMaskedCorpus falls back
491
+ // to the original fixture name. The runner is still called (we want the
492
+ // accounting to be honest), but no rmSync is performed against any path
493
+ // resolved from the hostile name.
494
+ expect(result.runsPerformed).toBe(1);
495
+ expect(callCount).toBe(1);
496
+ // Sentinel survives.
497
+ expect(fs.existsSync(sentinelFile)).toBe(true);
498
+ expect(fs.readFileSync(sentinelFile, "utf8")).toBe("do-not-delete");
499
+ // Source fixture files survive.
500
+ expect(fs.existsSync(path.join(fixturesRoot, "fixtureA", "skills", "alpha.md"))).toBe(true);
501
+ expect(fs.existsSync(path.join(fixturesRoot, "fixtureA", "skills", "beta.md"))).toBe(true);
502
+ fs.rmSync(sentinelDir, { recursive: true, force: true });
503
+ fs.rmSync(fixturesRoot, { recursive: true, force: true });
504
+ });
505
+ test("rejects absolute-path asset refs without escaping the tmp stash", async () => {
506
+ const fixturesRoot = makeFixturesRoot();
507
+ const sentinelDir = benchMkdtemp("akm-bench-sentinel-abs-");
508
+ const sentinelFile = path.join(sentinelDir, "sentinel.txt");
509
+ fs.writeFileSync(sentinelFile, "do-not-delete");
510
+ const baseRuns = [
511
+ // Hostile ref: name is an absolute POSIX path.
512
+ makeRun({ outcome: "pass", assetsLoaded: [`skill:${sentinelDir}`] }),
513
+ makeRun({ outcome: "pass", assetsLoaded: [`skill:${sentinelDir}`] }),
514
+ ];
515
+ const baseReport = makeReport(baseRuns);
516
+ baseReport.taskMetadata = [fakeTask()];
517
+ let callCount = 0;
518
+ const result = await runMaskedCorpus({
519
+ baseReport,
520
+ topN: 1,
521
+ runUtility: async () => {
522
+ callCount += 1;
523
+ return {
524
+ ...baseReport,
525
+ aggregateAkm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
526
+ };
527
+ },
528
+ baseOptions: { arms: ["akm"], model: "m", seedsPerArm: 1 },
529
+ fixturesRoot,
530
+ });
531
+ expect(result.runsPerformed).toBe(1);
532
+ expect(callCount).toBe(1);
533
+ expect(fs.existsSync(sentinelFile)).toBe(true);
534
+ expect(fs.readFileSync(sentinelFile, "utf8")).toBe("do-not-delete");
535
+ expect(fs.existsSync(sentinelDir)).toBe(true);
536
+ fs.rmSync(sentinelDir, { recursive: true, force: true });
537
+ fs.rmSync(fixturesRoot, { recursive: true, force: true });
538
+ });
539
+ test("cost accounting: runs N times when N <= asset count", async () => {
540
+ const fixturesRoot = makeFixturesRoot();
541
+ const baseRuns = [
542
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
543
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:beta"] }),
544
+ ];
545
+ const baseReport = makeReport(baseRuns);
546
+ baseReport.taskMetadata = [fakeTask()];
547
+ let callCount = 0;
548
+ const result = await runMaskedCorpus({
549
+ baseReport,
550
+ topN: 1,
551
+ runUtility: async () => {
552
+ callCount += 1;
553
+ return {
554
+ ...baseReport,
555
+ aggregateAkm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
556
+ };
557
+ },
558
+ baseOptions: { arms: ["akm"], model: "m", seedsPerArm: 1 },
559
+ fixturesRoot,
560
+ });
561
+ expect(result.runsPerformed).toBe(1);
562
+ expect(callCount).toBe(1);
563
+ expect(result.attributions.length).toBe(1);
564
+ fs.rmSync(fixturesRoot, { recursive: true, force: true });
565
+ });
566
+ });
567
+ describe("bench attribute --top clamping", () => {
568
+ test("clamps --top when fewer assets exist", async () => {
569
+ // Write a §13.3 envelope to disk with only 2 perAsset rows.
570
+ const tmp = benchMkdtemp("akm-bench-attr-cli-");
571
+ const fixturesRoot = path.join(tmp, "stashes");
572
+ fs.mkdirSync(fixturesRoot, { recursive: true });
573
+ // Two-asset fixture so the masked re-runs find their assets to remove.
574
+ const fixDir = path.join(fixturesRoot, "tiny");
575
+ fs.mkdirSync(path.join(fixDir, "skills"), { recursive: true });
576
+ fs.writeFileSync(path.join(fixDir, "MANIFEST.json"), JSON.stringify({ name: "tiny", description: "x", purpose: "x", assets: { skill: 2 }, consumers: [] }));
577
+ fs.writeFileSync(path.join(fixDir, "skills", ".stash.json"), JSON.stringify({
578
+ entries: [
579
+ { name: "alpha", type: "skill", filename: "alpha.md" },
580
+ { name: "beta", type: "skill", filename: "beta.md" },
581
+ ],
582
+ }));
583
+ fs.writeFileSync(path.join(fixDir, "skills", "alpha.md"), "# alpha");
584
+ fs.writeFileSync(path.join(fixDir, "skills", "beta.md"), "# beta");
585
+ const envelope = {
586
+ schemaVersion: 1,
587
+ track: "utility",
588
+ branch: "test",
589
+ commit: "abc",
590
+ timestamp: "2026-04-27T00:00:00Z",
591
+ agent: { harness: "opencode", model: "test-model" },
592
+ corpus: { domains: 1, tasks: 1, slice: "all", seedsPerArm: 1 },
593
+ aggregate: {
594
+ noakm: { pass_rate: 0, tokens_per_pass: null, wallclock_ms: 0 },
595
+ akm: { pass_rate: 0.5, tokens_per_pass: null, wallclock_ms: 0 },
596
+ delta: { pass_rate: 0.5, tokens_per_pass: null, wallclock_ms: 0 },
597
+ },
598
+ trajectory: { akm: { correct_asset_loaded: null, feedback_recorded: 0 } },
599
+ tasks: [],
600
+ warnings: [],
601
+ perAsset: {
602
+ total_akm_runs: 4,
603
+ rows: [
604
+ {
605
+ asset_ref: "skill:alpha",
606
+ load_count: 2,
607
+ load_count_passing: 1,
608
+ load_count_failing: 1,
609
+ load_pass_rate: 0.5,
610
+ },
611
+ { asset_ref: "skill:beta", load_count: 1, load_count_passing: 1, load_count_failing: 0, load_pass_rate: 1 },
612
+ ],
613
+ },
614
+ };
615
+ const basePath = path.join(tmp, "run.json");
616
+ fs.writeFileSync(basePath, JSON.stringify(envelope));
617
+ let calls = 0;
618
+ const result = await runAttributeCli({
619
+ basePath,
620
+ topN: 5, // > 2 → clamp to 2
621
+ json: true,
622
+ runUtility: async () => {
623
+ calls += 1;
624
+ return {
625
+ timestamp: "2026-04-27T00:00:00Z",
626
+ branch: "test",
627
+ commit: "abc",
628
+ model: "test-model",
629
+ corpus: { domains: 1, tasks: 0, slice: "all", seedsPerArm: 1 },
630
+ aggregateNoakm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
631
+ aggregateAkm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
632
+ aggregateDelta: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
633
+ trajectoryAkm: { correctAssetLoaded: null, feedbackRecorded: 0 },
634
+ failureModes: { byLabel: {}, byTask: {} },
635
+ tasks: [],
636
+ warnings: [],
637
+ };
638
+ },
639
+ fixturesRoot,
640
+ });
641
+ expect(result.exitCode).toBe(0);
642
+ const json = JSON.parse(result.stdout);
643
+ expect(json.runsPerformed).toBe(2);
644
+ expect(json.maskingStrategy).toBe("leave-one-out");
645
+ expect(json.attributions.length).toBe(2);
646
+ expect(calls).toBe(2);
647
+ fs.rmSync(tmp, { recursive: true, force: true });
648
+ });
649
+ });
650
+ describe("runMaskedCorpus marginal_contribution arithmetic", () => {
651
+ // Distinct from the clamp test in `bench attribute --top clamping`, which
652
+ // uses passRate 0 for every masked re-run and so cannot detect a sign
653
+ // error in the marginal-contribution arithmetic. Here we engineer a base
654
+ // pass_rate of 0.8 and two distinct masked pass_rates (0.4 and 0.5) and
655
+ // assert the resulting marginal_contribution = base - masked, with the
656
+ // correct sign and magnitude per masked asset.
657
+ function makeMarginalFixturesRoot() {
658
+ const root = benchMkdtemp("akm-bench-attr-marginal-fixtures-");
659
+ const fixDir = path.join(root, "fixtureMarginal");
660
+ fs.mkdirSync(path.join(fixDir, "skills"), { recursive: true });
661
+ fs.writeFileSync(path.join(fixDir, "MANIFEST.json"), JSON.stringify({ name: "fixtureMarginal", description: "x", purpose: "x", assets: { skill: 2 }, consumers: [] }));
662
+ fs.writeFileSync(path.join(fixDir, "skills", ".stash.json"), JSON.stringify({
663
+ entries: [
664
+ { name: "alpha", type: "skill", filename: "alpha.md" },
665
+ { name: "beta", type: "skill", filename: "beta.md" },
666
+ ],
667
+ }));
668
+ fs.writeFileSync(path.join(fixDir, "skills", "alpha.md"), "# alpha");
669
+ fs.writeFileSync(path.join(fixDir, "skills", "beta.md"), "# beta");
670
+ return root;
671
+ }
672
+ test("computes marginal_contribution = basePassRate - maskedPassRate per asset", async () => {
673
+ const fixturesRoot = makeMarginalFixturesRoot();
674
+ const baseRuns = [
675
+ // alpha: 4 pass, 0 fail → load_count 4
676
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
677
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
678
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
679
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha"] }),
680
+ // beta: 1 pass, 1 fail → load_count 2
681
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:beta"] }),
682
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:beta"] }),
683
+ ];
684
+ const baseReport = {
685
+ timestamp: "2026-04-27T00:00:00Z",
686
+ branch: "test",
687
+ commit: "abc",
688
+ model: "m",
689
+ corpus: { domains: 1, tasks: 1, slice: "all", seedsPerArm: baseRuns.length },
690
+ aggregateNoakm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
691
+ // Engineered base pass rate distinct from the masked rates so the
692
+ // arithmetic is observable.
693
+ aggregateAkm: { passRate: 0.8, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
694
+ aggregateDelta: { passRate: 0.8, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
695
+ trajectoryAkm: { correctAssetLoaded: null, feedbackRecorded: 0 },
696
+ failureModes: { byLabel: {}, byTask: {} },
697
+ tasks: [],
698
+ warnings: [],
699
+ akmRuns: baseRuns,
700
+ taskMetadata: [
701
+ {
702
+ id: "fake/t",
703
+ title: "t",
704
+ domain: "fake",
705
+ difficulty: "easy",
706
+ stash: "fixtureMarginal",
707
+ verifier: "regex",
708
+ expectedMatch: "ok",
709
+ budget: { tokens: 100, wallMs: 1000 },
710
+ taskDir: "/tmp",
711
+ },
712
+ ],
713
+ };
714
+ // Map masked-asset → simulated pass rate. The injected runner inspects
715
+ // the on-disk masked stash to detect which asset is missing.
716
+ const maskedPassRates = {
717
+ "skill:alpha": 0.4,
718
+ "skill:beta": 0.5,
719
+ };
720
+ const result = await runMaskedCorpus({
721
+ baseReport,
722
+ topN: 2,
723
+ runUtility: async (options) => {
724
+ // Issue #251: read the masked tmp dir from the explicit
725
+ // `stashDirOverride` field — the original `task.stash` (fixture
726
+ // name) is intentionally unchanged.
727
+ const stashDir = options.tasks[0]?.stashDirOverride ?? "";
728
+ const alphaMissing = !fs.existsSync(path.join(stashDir, "skills", "alpha.md"));
729
+ const betaMissing = !fs.existsSync(path.join(stashDir, "skills", "beta.md"));
730
+ const masked = alphaMissing ? "skill:alpha" : betaMissing ? "skill:beta" : "none";
731
+ const passRate = maskedPassRates[masked] ?? 0;
732
+ return {
733
+ ...baseReport,
734
+ aggregateAkm: { passRate, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
735
+ akmRuns: [],
736
+ };
737
+ },
738
+ baseOptions: { arms: ["akm"], model: "m", seedsPerArm: 1 },
739
+ fixturesRoot,
740
+ });
741
+ expect(result.runsPerformed).toBe(2);
742
+ expect(result.attributions.length).toBe(2);
743
+ const alpha = result.attributions.find((a) => a.assetRef === "skill:alpha");
744
+ const beta = result.attributions.find((a) => a.assetRef === "skill:beta");
745
+ // Both rows carry the engineered base pass rate.
746
+ expect(alpha?.basePassRate).toBeCloseTo(0.8, 5);
747
+ expect(beta?.basePassRate).toBeCloseTo(0.8, 5);
748
+ // Masked pass rates are the runner-injected values, distinguished per
749
+ // asset (this is the property the vacuous 0 → 0 → 0 fixture above
750
+ // could not exercise).
751
+ expect(alpha?.maskedPassRate).toBeCloseTo(0.4, 5);
752
+ expect(beta?.maskedPassRate).toBeCloseTo(0.5, 5);
753
+ // Marginal contribution = base - masked. Positive sign means masking
754
+ // hurt — the asset was helping. Both must be non-zero.
755
+ expect(alpha?.marginalContribution).toBeCloseTo(0.4, 5);
756
+ expect(beta?.marginalContribution).toBeCloseTo(0.3, 5);
757
+ expect(alpha?.marginalContribution).not.toBe(0);
758
+ expect(beta?.marginalContribution).not.toBe(0);
759
+ fs.rmSync(fixturesRoot, { recursive: true, force: true });
760
+ });
761
+ });
762
+ // ── #249 round-trip: persisted runs[] → attribute → compute paths ──────────
763
+ describe("bench attribute prefers persisted runs[] (#249)", () => {
764
+ test("hydrates persisted runs[] and feeds them to runMaskedCorpus", async () => {
765
+ const tmp = benchMkdtemp("akm-bench-attr-runs-");
766
+ const fixturesRoot = path.join(tmp, "stashes");
767
+ fs.mkdirSync(fixturesRoot, { recursive: true });
768
+ const fixDir = path.join(fixturesRoot, "tiny");
769
+ fs.mkdirSync(path.join(fixDir, "skills"), { recursive: true });
770
+ fs.writeFileSync(path.join(fixDir, "MANIFEST.json"), JSON.stringify({ name: "tiny", description: "x", purpose: "x", assets: { skill: 2 }, consumers: [] }));
771
+ fs.writeFileSync(path.join(fixDir, "skills", ".stash.json"), JSON.stringify({
772
+ entries: [
773
+ { name: "alpha", type: "skill", filename: "alpha.md" },
774
+ { name: "beta", type: "skill", filename: "beta.md" },
775
+ ],
776
+ }));
777
+ fs.writeFileSync(path.join(fixDir, "skills", "alpha.md"), "# alpha");
778
+ fs.writeFileSync(path.join(fixDir, "skills", "beta.md"), "# beta");
779
+ // Build a §13.3 envelope WITH a persisted runs[] array. The compact rows
780
+ // mirror what the runner would have emitted — both arms, multiple seeds.
781
+ const envelope = {
782
+ schemaVersion: 1,
783
+ track: "utility",
784
+ branch: "test",
785
+ commit: "abc",
786
+ timestamp: "2026-04-27T00:00:00Z",
787
+ agent: { harness: "opencode", model: "test-model" },
788
+ corpus: { domains: 1, tasks: 1, slice: "all", seedsPerArm: 2 },
789
+ aggregate: {
790
+ noakm: { pass_rate: 0, tokens_per_pass: null, wallclock_ms: 0 },
791
+ akm: { pass_rate: 0.5, tokens_per_pass: null, wallclock_ms: 0 },
792
+ delta: { pass_rate: 0.5, tokens_per_pass: null, wallclock_ms: 0 },
793
+ },
794
+ trajectory: { akm: { correct_asset_loaded: null, feedback_recorded: 0 } },
795
+ tasks: [],
796
+ warnings: [],
797
+ runs: [
798
+ // noakm — should be filtered out of attribution.
799
+ {
800
+ task_id: "t",
801
+ arm: "noakm",
802
+ seed: 0,
803
+ model: "test-model",
804
+ outcome: "fail",
805
+ tokens: { input: 0, output: 0 },
806
+ wallclock_ms: 0,
807
+ verifier_exit_code: 1,
808
+ trajectory: { correct_asset_loaded: null, feedback_recorded: null },
809
+ assets_loaded: [],
810
+ failure_mode: null,
811
+ },
812
+ // akm — alpha:1pass+1fail, beta:1pass.
813
+ {
814
+ task_id: "t",
815
+ arm: "akm",
816
+ seed: 0,
817
+ model: "test-model",
818
+ outcome: "pass",
819
+ tokens: { input: 1, output: 2 },
820
+ wallclock_ms: 100,
821
+ verifier_exit_code: 0,
822
+ trajectory: { correct_asset_loaded: true, feedback_recorded: false },
823
+ assets_loaded: ["skill:alpha", "skill:beta"],
824
+ failure_mode: null,
825
+ },
826
+ {
827
+ task_id: "t",
828
+ arm: "akm",
829
+ seed: 1,
830
+ model: "test-model",
831
+ outcome: "fail",
832
+ tokens: { input: 3, output: 4 },
833
+ wallclock_ms: 110,
834
+ verifier_exit_code: 1,
835
+ trajectory: { correct_asset_loaded: false, feedback_recorded: false },
836
+ assets_loaded: ["skill:alpha"],
837
+ failure_mode: "wrong_asset",
838
+ },
839
+ ],
840
+ // perAsset is also present (older path) — but the persisted runs[]
841
+ // should take precedence.
842
+ perAsset: {
843
+ total_akm_runs: 2,
844
+ rows: [
845
+ {
846
+ asset_ref: "skill:alpha",
847
+ load_count: 2,
848
+ load_count_passing: 1,
849
+ load_count_failing: 1,
850
+ load_pass_rate: 0.5,
851
+ },
852
+ {
853
+ asset_ref: "skill:beta",
854
+ load_count: 1,
855
+ load_count_passing: 1,
856
+ load_count_failing: 0,
857
+ load_pass_rate: 1,
858
+ },
859
+ ],
860
+ },
861
+ };
862
+ const basePath = path.join(tmp, "run.json");
863
+ fs.writeFileSync(basePath, JSON.stringify(envelope));
864
+ let observedAkmAssetsLoaded = [];
865
+ const result = await runAttributeCli({
866
+ basePath,
867
+ topN: 2,
868
+ json: true,
869
+ runUtility: async (options) => {
870
+ // Capture the akmRuns the masked runner sees so we can prove the
871
+ // hydrated runs[] flowed through unchanged.
872
+ observedAkmAssetsLoaded = options.tasks.map((t) => [t.id]);
873
+ return {
874
+ timestamp: "2026-04-27T00:00:00Z",
875
+ branch: "test",
876
+ commit: "abc",
877
+ model: "test-model",
878
+ corpus: { domains: 1, tasks: 1, slice: "all", seedsPerArm: 2 },
879
+ aggregateNoakm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
880
+ aggregateAkm: { passRate: 0.25, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
881
+ aggregateDelta: { passRate: 0.25, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
882
+ trajectoryAkm: { correctAssetLoaded: null, feedbackRecorded: 0 },
883
+ failureModes: { byLabel: {}, byTask: {} },
884
+ tasks: [],
885
+ warnings: [],
886
+ };
887
+ },
888
+ fixturesRoot,
889
+ });
890
+ expect(result.exitCode).toBe(0);
891
+ const json = JSON.parse(result.stdout);
892
+ // 2 attributions = 2 distinct loaded assets, both came from the persisted
893
+ // runs[] (alpha + beta). The noakm row is excluded.
894
+ expect(json.attributions.length).toBe(2);
895
+ expect(observedAkmAssetsLoaded.length).toBeGreaterThan(0);
896
+ fs.rmSync(tmp, { recursive: true, force: true });
897
+ });
898
+ test("falls back to perAsset synthesis when runs[] is absent (legacy report)", async () => {
899
+ const tmp = benchMkdtemp("akm-bench-attr-legacy-");
900
+ const fixturesRoot = path.join(tmp, "stashes");
901
+ fs.mkdirSync(fixturesRoot, { recursive: true });
902
+ const fixDir = path.join(fixturesRoot, "tiny");
903
+ fs.mkdirSync(path.join(fixDir, "skills"), { recursive: true });
904
+ fs.writeFileSync(path.join(fixDir, "MANIFEST.json"), JSON.stringify({ name: "tiny", description: "x", purpose: "x", assets: { skill: 1 }, consumers: [] }));
905
+ fs.writeFileSync(path.join(fixDir, "skills", ".stash.json"), JSON.stringify({ entries: [{ name: "alpha", type: "skill", filename: "alpha.md" }] }));
906
+ fs.writeFileSync(path.join(fixDir, "skills", "alpha.md"), "# alpha");
907
+ // Legacy envelope: NO runs[] key.
908
+ const envelope = {
909
+ schemaVersion: 1,
910
+ track: "utility",
911
+ branch: "test",
912
+ commit: "abc",
913
+ timestamp: "2026-04-27T00:00:00Z",
914
+ agent: { harness: "opencode", model: "test-model" },
915
+ corpus: { domains: 1, tasks: 0, slice: "all", seedsPerArm: 1 },
916
+ aggregate: {
917
+ noakm: { pass_rate: 0, tokens_per_pass: null, wallclock_ms: 0 },
918
+ akm: { pass_rate: 0.5, tokens_per_pass: null, wallclock_ms: 0 },
919
+ delta: { pass_rate: 0.5, tokens_per_pass: null, wallclock_ms: 0 },
920
+ },
921
+ trajectory: { akm: { correct_asset_loaded: null, feedback_recorded: 0 } },
922
+ tasks: [],
923
+ warnings: [],
924
+ perAsset: {
925
+ total_akm_runs: 2,
926
+ rows: [
927
+ {
928
+ asset_ref: "skill:alpha",
929
+ load_count: 2,
930
+ load_count_passing: 1,
931
+ load_count_failing: 1,
932
+ load_pass_rate: 0.5,
933
+ },
934
+ ],
935
+ },
936
+ };
937
+ const basePath = path.join(tmp, "run.json");
938
+ fs.writeFileSync(basePath, JSON.stringify(envelope));
939
+ let calls = 0;
940
+ const result = await runAttributeCli({
941
+ basePath,
942
+ topN: 5,
943
+ json: true,
944
+ runUtility: async () => {
945
+ calls += 1;
946
+ return {
947
+ timestamp: "2026-04-27T00:00:00Z",
948
+ branch: "test",
949
+ commit: "abc",
950
+ model: "test-model",
951
+ corpus: { domains: 1, tasks: 0, slice: "all", seedsPerArm: 1 },
952
+ aggregateNoakm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
953
+ aggregateAkm: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
954
+ aggregateDelta: { passRate: 0, tokensPerPass: null, tokensPerRun: null, wallclockMs: 0 },
955
+ trajectoryAkm: { correctAssetLoaded: null, feedbackRecorded: 0 },
956
+ failureModes: { byLabel: {}, byTask: {} },
957
+ tasks: [],
958
+ warnings: [],
959
+ };
960
+ },
961
+ fixturesRoot,
962
+ });
963
+ expect(result.exitCode).toBe(0);
964
+ const json = JSON.parse(result.stdout);
965
+ // Legacy path still works: clamps to 1 attribution row from perAsset.
966
+ expect(json.runsPerformed).toBe(1);
967
+ expect(json.attributions.length).toBe(1);
968
+ expect(calls).toBe(1);
969
+ fs.rmSync(tmp, { recursive: true, force: true });
970
+ });
971
+ });
972
+ // ── #249 metrics-level round-trip: aggregate from runs[] + reduce parity ───
973
+ describe("aggregateRunsForReport + rehydrate round-trip (#249)", () => {
974
+ test("recomputes computePerAssetAttribution identically from persisted rows", async () => {
975
+ const { aggregateRunsForReport, rehydrateRunFromSerialized, computePerAssetAttribution: cpa, } = await import("./metrics");
976
+ const original = [
977
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:alpha", "skill:beta"] }),
978
+ makeRun({ outcome: "fail", assetsLoaded: ["skill:alpha"], verifierStdout: "junk" }),
979
+ makeRun({ outcome: "pass", assetsLoaded: ["skill:beta"] }),
980
+ ];
981
+ const reportBefore = makeReport(original);
982
+ const before = cpa(reportBefore);
983
+ // Round-trip through compact persisted rows.
984
+ const rows = aggregateRunsForReport(original);
985
+ const hydrated = rows.map(rehydrateRunFromSerialized);
986
+ const reportAfter = makeReport(hydrated);
987
+ const after = cpa(reportAfter);
988
+ expect(after.totalAkmRuns).toBe(before.totalAkmRuns);
989
+ expect(after.rows.length).toBe(before.rows.length);
990
+ for (let i = 0; i < before.rows.length; i++) {
991
+ expect(after.rows[i]?.assetRef).toBe(before.rows[i]?.assetRef);
992
+ expect(after.rows[i]?.loadCount).toBe(before.rows[i]?.loadCount);
993
+ expect(after.rows[i]?.loadPassRate).toBe(before.rows[i]?.loadPassRate);
994
+ }
995
+ });
996
+ });