dsh-memu-memory 1.4.2 → 1.4.4

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 (389) hide show
  1. package/AGENTS.md +108 -110
  2. package/CHANGELOG.md +173 -868
  3. package/LICENSE +21 -21
  4. package/README.md +368 -374
  5. package/README.zh.md +354 -360
  6. package/assets/icon.svg +7 -7
  7. package/cordis.patch.yml +8 -8
  8. package/docs/active-memory-ab.md +279 -385
  9. package/docs/binding-lifecycle.md +99 -99
  10. package/docs/client-conventions.md +75 -75
  11. package/docs/contributing.md +217 -217
  12. package/docs/emotion-model-spec.md +247 -281
  13. package/docs/env-and-commands.md +149 -152
  14. package/docs/host-adaptation.md +339 -360
  15. package/docs/host-api.md +131 -137
  16. package/docs/host-versions.md +117 -120
  17. package/docs/mcp-porting.md +146 -146
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -854
  21. package/lib/active-memory.js +160 -165
  22. package/lib/activity-log.js +207 -207
  23. package/lib/auto-link/apply.js +248 -249
  24. package/lib/auto-link/candidates.js +163 -163
  25. package/lib/auto-link/decide.js +300 -300
  26. package/lib/auto-link/normalize.js +99 -99
  27. package/lib/auto-link/policy.js +42 -42
  28. package/lib/auto-link/suppression.js +101 -101
  29. package/lib/auto-link/terminology.js +311 -311
  30. package/lib/backup.js +1254 -1254
  31. package/lib/binding-diagnostics.js +634 -634
  32. package/lib/budget.js +118 -118
  33. package/lib/client.js +9820 -9751
  34. package/lib/commitment.js +178 -138
  35. package/lib/consolidation-ledger.js +434 -438
  36. package/lib/consolidation-receipt.js +386 -387
  37. package/lib/consolidation-snapshot.js +420 -405
  38. package/lib/consolidation-worker.js +240 -241
  39. package/lib/context.js +33 -33
  40. package/lib/curator-evidence.js +131 -131
  41. package/lib/curator-policy.js +198 -202
  42. package/lib/curator.js +1813 -1811
  43. package/lib/cycle.js +524 -513
  44. package/lib/diagnostics.js +524 -524
  45. package/lib/embedding-catalog.js +1051 -1055
  46. package/lib/embedding-download.js +637 -607
  47. package/lib/embedding-runtime.js +946 -946
  48. package/lib/engine.js +1103 -1103
  49. package/lib/entity-repair.js +285 -285
  50. package/lib/environment-check.js +394 -394
  51. package/lib/fork-model.js +312 -312
  52. package/lib/freshness.js +128 -121
  53. package/lib/global-graph.js +389 -389
  54. package/lib/graph.js +1193 -1193
  55. package/lib/host-surface.js +30 -30
  56. package/lib/inbound.js +284 -281
  57. package/lib/index.js +506 -511
  58. package/lib/inject.js +2639 -2619
  59. package/lib/lexicon-scope.js +143 -143
  60. package/lib/lexicon.js +1183 -1192
  61. package/lib/lifecycle-audit.js +37 -0
  62. package/lib/local-embedding-entry.js +145 -145
  63. package/lib/local-embedding-manager.js +306 -306
  64. package/lib/local-embedding-protocol.js +210 -210
  65. package/lib/local-embedding-worker.js +682 -682
  66. package/lib/local-vector-service.js +506 -453
  67. package/lib/maintenance-ledger.js +138 -0
  68. package/lib/maintenance-review.js +103 -0
  69. package/lib/maintenance-runner.js +267 -0
  70. package/lib/managed-runtime.js +118 -118
  71. package/lib/media.js +607 -513
  72. package/lib/memory.js +5035 -4941
  73. package/lib/memu-config.js +213 -213
  74. package/lib/memu.js +565 -565
  75. package/lib/migrate.js +200 -200
  76. package/lib/mood.js +300 -300
  77. package/lib/paths.js +453 -457
  78. package/lib/port-surface.js +82 -82
  79. package/lib/preset-mount.js +85 -0
  80. package/lib/preset-scope.js +126 -126
  81. package/lib/private-links.js +567 -567
  82. package/lib/private.js +2198 -2209
  83. package/lib/prompts/global-curator.md +135 -135
  84. package/lib/prompts/image-caption.md +1 -1
  85. package/lib/prompts/private-consolidation.coding.md +39 -39
  86. package/lib/prompts/private-consolidation.md +32 -32
  87. package/lib/prompts/private-consolidation.mixed.md +37 -37
  88. package/lib/prompts/private-consolidation.rp.md +47 -47
  89. package/lib/prompts/private-policy.coding.md +35 -35
  90. package/lib/prompts/private-policy.md +36 -36
  91. package/lib/prompts/private-policy.mixed.md +29 -29
  92. package/lib/prompts/private-policy.rp.md +43 -43
  93. package/lib/prompts/system-guide.coding.md +20 -20
  94. package/lib/prompts/system-guide.md +25 -25
  95. package/lib/prompts/system-guide.mixed.md +22 -22
  96. package/lib/prompts/system-guide.rp.md +23 -23
  97. package/lib/prompts.js +331 -331
  98. package/lib/recall-cache.js +212 -212
  99. package/lib/remote-summary.js +123 -123
  100. package/lib/rpc.js +2531 -2532
  101. package/lib/salient-wake.js +438 -438
  102. package/lib/snippet.js +125 -125
  103. package/lib/state.js +1948 -1928
  104. package/lib/stats.js +236 -236
  105. package/lib/temporal.js +345 -348
  106. package/lib/text-retrieval.js +992 -1001
  107. package/lib/text-similarity.js +305 -305
  108. package/lib/tokenizer-v2.js +271 -271
  109. package/lib/tools.js +1098 -1091
  110. package/lib/turn-log.js +545 -545
  111. package/lib/vector-migration.js +928 -930
  112. package/lib/vector-profile.js +1353 -1359
  113. package/lib/visibility.js +59 -59
  114. package/lib/webui/graph-LICENSE.txt +1 -1
  115. package/lib/webui/graph-view.bundle.js +2 -2
  116. package/lib/webui/graph-view.js +1171 -1175
  117. package/lib/webui/mark.svg +7 -7
  118. package/lib/webui/standalone.css +1178 -1178
  119. package/lib/webui/standalone.js +238 -238
  120. package/lib/webui.js +136 -136
  121. package/lib/worker-pool.js +1020 -979
  122. package/package.json +153 -153
  123. package/requirements.lock +34 -34
  124. package/scripts/acceptance-local.mjs +946 -946
  125. package/scripts/active-memory-ab-live.mjs +653 -655
  126. package/scripts/active-memory-ab.mjs +1302 -1302
  127. package/scripts/audit-memory-lifecycle.mjs +55 -0
  128. package/scripts/bench-recall.mjs +142 -142
  129. package/scripts/build-graph.mjs +44 -45
  130. package/scripts/chain-matrix.mjs +541 -541
  131. package/scripts/check-all.mjs +68 -74
  132. package/scripts/check-doc-drift.mjs +547 -547
  133. package/scripts/check-graph-browser.mjs +261 -261
  134. package/scripts/check-i18n.mjs +81 -83
  135. package/scripts/check-idle-compositing.mjs +61 -61
  136. package/scripts/check-seed-compat.mjs +115 -118
  137. package/scripts/check-text-format.mjs +55 -0
  138. package/scripts/curator-pair-calibrate.mjs +259 -259
  139. package/scripts/diagnose-bindings.mjs +176 -176
  140. package/scripts/drive-session.mjs +863 -864
  141. package/scripts/engine-smoke.mjs +69 -69
  142. package/scripts/entity-dedupe.mjs +110 -110
  143. package/scripts/lexicon-calibrate.mjs +230 -230
  144. package/scripts/lexicon-dedupe.mjs +318 -318
  145. package/scripts/local-runtime-install.mjs +142 -142
  146. package/scripts/local-runtime-verify.mjs +56 -56
  147. package/scripts/local-vector-verify.mjs +93 -93
  148. package/scripts/make-readme-shots.mjs +59 -59
  149. package/scripts/migrate-visibility.mjs +94 -94
  150. package/scripts/mock-llm.mjs +938 -903
  151. package/scripts/preview.mjs +58 -58
  152. package/scripts/prune-sessions.mjs +31 -34
  153. package/scripts/prune-turnlogs.mjs +29 -30
  154. package/scripts/prune-vectors.mjs +24 -24
  155. package/scripts/rebuild-auto-links.mjs +252 -252
  156. package/scripts/recall-bench.mjs +820 -820
  157. package/scripts/repetition-ab-scenarios.mjs +93 -93
  158. package/scripts/repetition-detector-snapshot.mjs +314 -314
  159. package/scripts/repetition-eval-live.mjs +360 -360
  160. package/scripts/repetition-eval.mjs +702 -702
  161. package/scripts/replay.mjs +705 -575
  162. package/scripts/setup.mjs +46 -46
  163. package/scripts/simulate-injection.mjs +299 -301
  164. package/tests/absorb-review.test.mjs +354 -354
  165. package/tests/activation.test.mjs +89 -89
  166. package/tests/active-memory-ab.test.mjs +745 -745
  167. package/tests/active-memory.test.mjs +129 -129
  168. package/tests/activity-log.test.mjs +126 -126
  169. package/tests/activity-wiring.test.mjs +155 -155
  170. package/tests/appendix-b.test.mjs +217 -217
  171. package/tests/appendix-b2.test.mjs +166 -166
  172. package/tests/audit-batch3.test.mjs +247 -247
  173. package/tests/audit-regression.test.mjs +275 -275
  174. package/tests/audit-safety.test.mjs +227 -227
  175. package/tests/auto-link-candidates.test.mjs +245 -245
  176. package/tests/auto-link-decide.test.mjs +512 -512
  177. package/tests/auto-link-migration.test.mjs +133 -133
  178. package/tests/backend-compensation.test.mjs +272 -272
  179. package/tests/backup.test.mjs +793 -793
  180. package/tests/binding-diagnostics.test.mjs +720 -720
  181. package/tests/browser.test.mjs +476 -476
  182. package/tests/client-export.test.mjs +521 -521
  183. package/tests/client-render.test.mjs +2008 -1728
  184. package/tests/coalesce.test.mjs +113 -113
  185. package/tests/commitment.test.mjs +243 -144
  186. package/tests/config.test.mjs +159 -159
  187. package/tests/consolidation-credential.test.mjs +330 -330
  188. package/tests/consolidation-feed.test.mjs +122 -122
  189. package/tests/consolidation-fork.test.mjs +1587 -1539
  190. package/tests/consolidation-ledger.test.mjs +389 -389
  191. package/tests/consolidation-snapshot.test.mjs +567 -505
  192. package/tests/consolidation-value.test.mjs +89 -89
  193. package/tests/context-scope.test.mjs +40 -40
  194. package/tests/cross-library-recall.test.mjs +269 -269
  195. package/tests/cue.test.mjs +58 -58
  196. package/tests/curator-absorb.test.mjs +444 -444
  197. package/tests/curator-calibrate.test.mjs +173 -173
  198. package/tests/curator-clusters.test.mjs +306 -306
  199. package/tests/curator-commit.test.mjs +325 -325
  200. package/tests/curator-contract.test.mjs +191 -191
  201. package/tests/curator-evidence.test.mjs +102 -102
  202. package/tests/curator-link.test.mjs +317 -317
  203. package/tests/curator-pairing.test.mjs +339 -339
  204. package/tests/curator-probe.test.mjs +490 -490
  205. package/tests/curator-review-mode.test.mjs +315 -315
  206. package/tests/curator.test.mjs +152 -152
  207. package/tests/cycle.test.mjs +567 -568
  208. package/tests/diagnostics.test.mjs +278 -278
  209. package/tests/disclosure.test.mjs +249 -249
  210. package/tests/doc-drift.test.mjs +342 -342
  211. package/tests/drive-session.test.mjs +152 -152
  212. package/tests/dynamic-rrf.test.mjs +182 -182
  213. package/tests/dynamic-threshold.test.mjs +52 -52
  214. package/tests/embedding-catalog.test.mjs +374 -374
  215. package/tests/embedding-download.test.mjs +529 -486
  216. package/tests/embedding-runtime.test.mjs +449 -449
  217. package/tests/emotion-chain.test.mjs +84 -84
  218. package/tests/emotion-contract.test.mjs +445 -445
  219. package/tests/engine.test.mjs +108 -108
  220. package/tests/entity-merge.test.mjs +278 -278
  221. package/tests/environment-check.test.mjs +187 -187
  222. package/tests/fact-version.test.mjs +146 -146
  223. package/tests/fixtures/active-memory-ab/README.md +56 -56
  224. package/tests/fixtures/active-memory-ab/cases/01-clean-dense-turn.json +351 -351
  225. package/tests/fixtures/active-memory-ab/cases/02-clean-thin-turn.json +122 -122
  226. package/tests/fixtures/active-memory-ab/cases/03-clean-starved-small.json +125 -125
  227. package/tests/fixtures/active-memory-ab/cases/04-clean-large-thin.json +137 -137
  228. package/tests/fixtures/active-memory-ab/cases/05-clean-half-step.json +166 -166
  229. package/tests/fixtures/active-memory-ab/cases/06-clean-duplicate-reread.json +197 -197
  230. package/tests/fixtures/active-memory-ab/cases/07-clean-recent-recall.json +125 -125
  231. package/tests/fixtures/active-memory-ab/cases/08-global-relevant.json +111 -111
  232. package/tests/fixtures/active-memory-ab/cases/09-global-irrelevant-conflict.json +158 -158
  233. package/tests/fixtures/active-memory-ab/cases/10-no-human-turn.json +97 -97
  234. package/tests/fixtures/active-memory-ab/cases/11-clean-scale-100.json +137 -137
  235. package/tests/fixtures/active-memory-ab/cases/12-clean-scale-1000.json +137 -137
  236. package/tests/fixtures/active-memory-ab/cases/13-clean-scale-5000.json +137 -137
  237. package/tests/fixtures/active-memory-ab/cases/14-clean-scale-20000.json +137 -137
  238. package/tests/fixtures/active-memory-ab/lead-ai-reviewed-reference.json +191 -191
  239. package/tests/fixtures/active-memory-ab/manifest.json +199 -199
  240. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -90
  241. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -15
  242. package/tests/fixtures/lexicon-stub.mjs +284 -284
  243. package/tests/fixtures/mock-llm/reply.txt +1 -1
  244. package/tests/fixtures/recall-bench/01-paraphrase.json +183 -183
  245. package/tests/fixtures/recall-bench/02-exact.json +152 -152
  246. package/tests/fixtures/recall-bench/03-negation.json +172 -172
  247. package/tests/fixtures/recall-bench/04-no-answer.json +161 -161
  248. package/tests/fixtures/recall-bench/05-conflict.json +193 -193
  249. package/tests/fixtures/recall-bench/06-boundary.json +272 -272
  250. package/tests/fixtures/recall-bench/07-secret.json +190 -190
  251. package/tests/fixtures/recall-bench/08-coding.json +163 -163
  252. package/tests/fixtures/recall-bench-gold-candidates/01-paraphrase.json +193 -193
  253. package/tests/fixtures/recall-bench-gold-candidates/02-exact.json +197 -197
  254. package/tests/fixtures/recall-bench-gold-candidates/03-negation.json +244 -244
  255. package/tests/fixtures/recall-bench-gold-candidates/04-no-answer.json +189 -189
  256. package/tests/fixtures/recall-bench-gold-candidates/05-conflict.json +245 -245
  257. package/tests/fixtures/recall-bench-gold-candidates/06-boundary.json +279 -279
  258. package/tests/fixtures/recall-bench-gold-candidates/07-secret.json +224 -224
  259. package/tests/fixtures/recall-bench-gold-candidates/08-coding.json +218 -218
  260. package/tests/fixtures/repetition-eval/01-zh-rp.json +92 -92
  261. package/tests/fixtures/repetition-eval/02-en.json +96 -96
  262. package/tests/fixtures/repetition-eval/03-code.json +90 -90
  263. package/tests/fixtures/repetition-eval/04-names.json +115 -115
  264. package/tests/fixtures/repetition-eval/05-user-quote.json +95 -95
  265. package/tests/fixtures/repetition-eval/06-agreement.json +85 -85
  266. package/tests/fixtures/tokenizer-cases.mjs +27 -27
  267. package/tests/fork-model.test.mjs +345 -345
  268. package/tests/freshness.test.mjs +140 -140
  269. package/tests/global-graph.test.mjs +106 -106
  270. package/tests/global-lifecycle.test.mjs +149 -149
  271. package/tests/graph-cascade.test.mjs +363 -363
  272. package/tests/graph-view.test.mjs +414 -414
  273. package/tests/graph.test.mjs +371 -371
  274. package/tests/help-page.test.mjs +416 -416
  275. package/tests/hook-order.test.mjs +72 -72
  276. package/tests/humanlike.test.mjs +232 -232
  277. package/tests/hybrid-recall.test.mjs +610 -610
  278. package/tests/inbound.test.mjs +441 -441
  279. package/tests/inject-conflict.test.mjs +173 -173
  280. package/tests/inject-guide.test.mjs +513 -513
  281. package/tests/inject.test.mjs +384 -384
  282. package/tests/injection-budget-settings.test.mjs +35 -35
  283. package/tests/injection-budget.test.mjs +165 -165
  284. package/tests/injection-chain.test.mjs +442 -442
  285. package/tests/injection-intent-budget.test.mjs +92 -92
  286. package/tests/injection-rollback.test.mjs +428 -428
  287. package/tests/issue2-chain.test.mjs +169 -169
  288. package/tests/lexical-bm25.test.mjs +171 -171
  289. package/tests/lexicon-calibrate.test.mjs +48 -48
  290. package/tests/lexicon-dedupe.test.mjs +171 -171
  291. package/tests/lexicon-frequency.test.mjs +195 -195
  292. package/tests/lexicon-inject.test.mjs +459 -459
  293. package/tests/lexicon-perf.test.mjs +464 -464
  294. package/tests/lexicon-scope.test.mjs +256 -256
  295. package/tests/lexicon-ui.test.mjs +667 -667
  296. package/tests/lexicon.test.mjs +922 -922
  297. package/tests/lifecycle-audit.test.mjs +56 -0
  298. package/tests/loader-register.mjs +3 -3
  299. package/tests/loader.mjs +17 -17
  300. package/tests/local-embedding-entry.test.mjs +95 -95
  301. package/tests/local-embedding-env.test.mjs +51 -51
  302. package/tests/local-embedding-manager.test.mjs +494 -494
  303. package/tests/local-embedding-protocol.test.mjs +121 -121
  304. package/tests/local-embedding-worker.test.mjs +440 -440
  305. package/tests/local-vector-service.test.mjs +41 -0
  306. package/tests/maintenance-status.test.mjs +77 -0
  307. package/tests/maintenance.test.mjs +438 -0
  308. package/tests/managed-memory.test.mjs +1234 -1234
  309. package/tests/managed-runtime.test.mjs +72 -72
  310. package/tests/media-injection.test.mjs +225 -0
  311. package/tests/media.test.mjs +135 -135
  312. package/tests/memory-chain.test.mjs +169 -169
  313. package/tests/memory-fields.test.mjs +134 -134
  314. package/tests/memu-resident-route.test.mjs +130 -130
  315. package/tests/memu-resident.test.mjs +33 -33
  316. package/tests/migration-payload.test.mjs +40 -42
  317. package/tests/mock-llm.test.mjs +263 -225
  318. package/tests/mood.test.mjs +109 -109
  319. package/tests/multiprocess.test.mjs +29 -29
  320. package/tests/negation-polarity.test.mjs +135 -135
  321. package/tests/new-session-gate.test.mjs +617 -617
  322. package/tests/open-loop-date.test.mjs +416 -416
  323. package/tests/ops-hardening.test.mjs +209 -209
  324. package/tests/package-shipping.test.mjs +88 -88
  325. package/tests/pending-injection.test.mjs +107 -107
  326. package/tests/port-surface.test.mjs +138 -138
  327. package/tests/preset-mount.test.mjs +132 -0
  328. package/tests/preset-scope.test.mjs +212 -212
  329. package/tests/private-links.test.mjs +493 -493
  330. package/tests/prompt-semantics.test.mjs +51 -51
  331. package/tests/prompts.test.mjs +315 -315
  332. package/tests/query-decompose.test.mjs +62 -62
  333. package/tests/react-snapshot.test.mjs +24 -24
  334. package/tests/recall-bench.test.mjs +317 -317
  335. package/tests/recall-cache.test.mjs +292 -292
  336. package/tests/recall-corpus-eligibility.test.mjs +51 -51
  337. package/tests/recall-dedup.test.mjs +446 -446
  338. package/tests/recall-intent.test.mjs +172 -172
  339. package/tests/regression-sweep.test.mjs +311 -311
  340. package/tests/reminder-fairness.test.mjs +55 -0
  341. package/tests/remote.test.mjs +140 -140
  342. package/tests/rename.test.mjs +30 -30
  343. package/tests/repetition-detector-snapshot.test.mjs +231 -231
  344. package/tests/repetition-eval-live.test.mjs +177 -177
  345. package/tests/repetition-eval.test.mjs +373 -373
  346. package/tests/salience-domain.test.mjs +173 -173
  347. package/tests/salient-date.test.mjs +142 -142
  348. package/tests/salient-wake.test.mjs +389 -389
  349. package/tests/settings-beat.test.mjs +222 -222
  350. package/tests/settings-coverage.test.mjs +97 -97
  351. package/tests/settings-plumbing.test.mjs +79 -79
  352. package/tests/short-term.test.mjs +182 -166
  353. package/tests/sidebar-beat.test.mjs +213 -213
  354. package/tests/sidebar-refresh.test.mjs +123 -123
  355. package/tests/sidebar.test.mjs +102 -74
  356. package/tests/simulate-injection.test.mjs +76 -76
  357. package/tests/slot-similarity.test.mjs +153 -153
  358. package/tests/snippet.test.mjs +79 -79
  359. package/tests/source-kind.test.mjs +52 -52
  360. package/tests/speaker-provenance.test.mjs +120 -120
  361. package/tests/stale-maintenance.test.mjs +206 -131
  362. package/tests/state-gc.test.mjs +34 -34
  363. package/tests/state.test.mjs +155 -155
  364. package/tests/stats.test.mjs +112 -112
  365. package/tests/storage.test.mjs +125 -125
  366. package/tests/stubs/child-process-spy.mjs +14 -14
  367. package/tests/stubs/dsh-llm-pi-ai.js +13 -13
  368. package/tests/stubs/dsh-llm.js +5 -5
  369. package/tests/stubs/dsh-schedule.js +140 -140
  370. package/tests/stubs/dsh-session-query.js +26 -26
  371. package/tests/stubs/dsh-session.js +7 -7
  372. package/tests/stubs/dsh-tools.js +101 -101
  373. package/tests/temporal-repair.test.mjs +78 -0
  374. package/tests/temporal.test.mjs +124 -124
  375. package/tests/text-format.test.mjs +24 -0
  376. package/tests/tokenizer-v2.test.mjs +142 -142
  377. package/tests/tool-schema.test.mjs +126 -126
  378. package/tests/tools.test.mjs +810 -810
  379. package/tests/turn-log.test.mjs +487 -487
  380. package/tests/ui-defaults.test.mjs +57 -57
  381. package/tests/update-fields.test.mjs +138 -138
  382. package/tests/vector-gc.test.mjs +37 -37
  383. package/tests/vector-migration.test.mjs +810 -810
  384. package/tests/vector-profile.test.mjs +449 -449
  385. package/tests/visibility-migration.test.mjs +152 -152
  386. package/tests/webui-auth.test.mjs +963 -963
  387. package/tests/webui.test.mjs +421 -421
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1522 -1429
@@ -1,820 +1,820 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Reproducible recall benchmark harness (W6).
4
- *
5
- * This is a SYNTHETIC-DRAFT benchmark, not a gold set. It seeds each sample into
6
- * its own temporary library under os.tmpdir(), uses a fixed clock per sample and a
7
- * seeded PRNG, and never reads or writes the user's memory directory. The production
8
- * ranking code is imported and exercised read-only; no production ordering is changed.
9
- *
10
- * The local lexical backend is the only backend in this harness. Mock/lexical
11
- * vectors only validate the pipeline: they do not establish embedding quality.
12
- */
13
- import fs from 'node:fs'
14
- import os from 'node:os'
15
- import path from 'node:path'
16
- import crypto from 'node:crypto'
17
- import { execFileSync } from 'node:child_process'
18
- import { fileURLToPath, pathToFileURL } from 'node:url'
19
-
20
- const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
21
- export const FIXTURE_DIR = path.join(ROOT, 'tests', 'fixtures', 'recall-bench')
22
- export const CANDIDATE_FIXTURE_DIR = path.join(ROOT, 'tests', 'fixtures', 'recall-bench-gold-candidates')
23
- export const DEFAULT_STATUS = 'synthetic-draft-not-gold'
24
- export const CANDIDATE_STATUS = 'gold-candidate-pending-review'
25
- export const DATASET_STATUSES = Object.freeze([DEFAULT_STATUS, CANDIDATE_STATUS])
26
- export const SUBCLASSES = Object.freeze([
27
- 'paraphrase',
28
- 'exact',
29
- 'negation',
30
- 'no-answer',
31
- 'conflict',
32
- 'boundary',
33
- 'secret',
34
- 'coding',
35
- ])
36
- export const SAMPLE_FIELDS = Object.freeze([
37
- 'id',
38
- 'draft',
39
- 'notGold',
40
- 'subclass',
41
- 'query',
42
- 'context',
43
- 'time',
44
- 'expectedIds',
45
- 'forbiddenIds',
46
- 'noAnswer',
47
- 'library',
48
- ])
49
- export const RUN_CONFIG = Object.freeze({
50
- schemaVersion: 1,
51
- benchmark: 'recall-bench',
52
- status: DEFAULT_STATUS,
53
- seed: 20261029,
54
- candidateTopK: 20,
55
- privateTopK: 3,
56
- turnTokens: 640,
57
- relevanceThreshold: 0.4,
58
- dedupeTurns: 16,
59
- backend: 'local-lexical',
60
- })
61
-
62
- const DAY_MS = 24 * 60 * 60 * 1000
63
-
64
- function fixtureError(message) {
65
- throw new Error(`recall-bench fixture: ${message}`)
66
- }
67
-
68
- function isPlainObject(value) {
69
- return value !== null && typeof value === 'object' && !Array.isArray(value)
70
- }
71
-
72
- function assertString(value, field, where, { nonEmpty = true } = {}) {
73
- if (typeof value !== 'string' || (nonEmpty && !value.trim())) fixtureError(`${where}: ${field} must be a non-empty string`)
74
- return value
75
- }
76
-
77
- function assertStringArray(value, field, where, { allowEmpty = true } = {}) {
78
- if (!Array.isArray(value)) fixtureError(`${where}: ${field} must be an array`)
79
- if (!allowEmpty && value.length === 0) fixtureError(`${where}: ${field} must not be empty`)
80
- if (value.some(item => typeof item !== 'string' || !item.trim())) fixtureError(`${where}: ${field} must contain non-empty strings`)
81
- const unique = new Set(value)
82
- if (unique.size !== value.length) fixtureError(`${where}: ${field} contains duplicate ids`)
83
- return value
84
- }
85
-
86
- export function validateSampleShape(sample, where = 'sample', options = {}) {
87
- if (!isPlainObject(sample)) fixtureError(`${where}: sample must be an object`)
88
- for (const field of SAMPLE_FIELDS) {
89
- if (!Object.hasOwn(sample, field)) fixtureError(`${where}: missing field ${field}`)
90
- }
91
- assertString(sample.id, 'id', where)
92
- if (!/^[a-z0-9][a-z0-9-]{2,80}$/.test(sample.id)) fixtureError(`${where}: invalid sample id ${sample.id}`)
93
- if (sample.draft !== true) fixtureError(`${where}: draft must be true (do not present unconfirmed samples as confirmed)`)
94
- if (sample.notGold !== true) fixtureError(`${where}: notGold must be true (unconfirmed samples are not a gold set)`)
95
- if (options.status === CANDIDATE_STATUS) {
96
- if (sample.status !== CANDIDATE_STATUS) fixtureError(`${where}: candidate sample status must be ${CANDIDATE_STATUS}`)
97
- if (sample.review !== 'pending') fixtureError(`${where}: candidate sample review must be pending`)
98
- }
99
- if (sample.gold === true) fixtureError(`${where}: gold must not be marked before human review`)
100
- if (!SUBCLASSES.includes(sample.subclass)) fixtureError(`${where}: unknown subclass ${sample.subclass}`)
101
- assertString(sample.query, 'query', where)
102
- if (!isPlainObject(sample.context)) fixtureError(`${where}: context must be an object`)
103
- assertString(sample.time, 'time', where)
104
- if (!Number.isFinite(Date.parse(sample.time))) fixtureError(`${where}: time must be an ISO date/time`)
105
- assertStringArray(sample.expectedIds, 'expectedIds', where)
106
- assertStringArray(sample.forbiddenIds, 'forbiddenIds', where)
107
- assertStringArray(sample.library, 'library', where, { allowEmpty: false })
108
- if (sample.library.length > 10) fixtureError(`${where}: library subset is capped at 10 entries`)
109
- if (typeof sample.noAnswer !== 'boolean') fixtureError(`${where}: noAnswer must be boolean`)
110
- if (sample.noAnswer && sample.expectedIds.length > 0) fixtureError(`${where}: noAnswer=true requires expectedIds=[]`)
111
- if (!sample.noAnswer && sample.expectedIds.length === 0) fixtureError(`${where}: answerable sample requires expectedIds`)
112
- for (const id of sample.expectedIds) {
113
- if (!sample.library.includes(id)) fixtureError(`${where}: expected id ${id} is outside the declared library`)
114
- }
115
- for (const id of sample.forbiddenIds) {
116
- if (!sample.library.includes(id)) fixtureError(`${where}: forbidden id ${id} is outside the declared library`)
117
- if (sample.expectedIds.includes(id)) fixtureError(`${where}: id ${id} is both expected and forbidden`)
118
- }
119
- if (sample.explicitExpectedIds !== undefined) {
120
- assertStringArray(sample.explicitExpectedIds, 'explicitExpectedIds', where, { allowEmpty: false })
121
- for (const id of sample.explicitExpectedIds) {
122
- if (!sample.library.includes(id)) fixtureError(`${where}: explicit expected id ${id} is outside the declared library`)
123
- if (!sample.expectedIds.includes(id) && sample.noAnswer !== true) {
124
- // Explicit recall may surface a secret that automatic recall hides, so an
125
- // extra id is allowed; it must still be declared in the subset.
126
- }
127
- }
128
- for (const id of sample.expectedIds) {
129
- if (!sample.explicitExpectedIds.includes(id)) fixtureError(`${where}: explicitExpectedIds must include every expectedId`)
130
- }
131
- }
132
- if (sample.explicitForbiddenIds !== undefined) {
133
- assertStringArray(sample.explicitForbiddenIds, 'explicitForbiddenIds', where)
134
- for (const id of sample.explicitForbiddenIds) {
135
- if (!sample.library.includes(id)) fixtureError(`${where}: explicit forbidden id ${id} is outside the declared library`)
136
- if (sample.explicitExpectedIds?.includes(id)) fixtureError(`${where}: id ${id} is both explicit expected and forbidden`)
137
- }
138
- }
139
- return sample
140
- }
141
-
142
- function validateEntry(entry, id, where) {
143
- if (!isPlainObject(entry)) fixtureError(`${where}: entry ${id} must be an object`)
144
- if (entry.id !== id) fixtureError(`${where}: entry key ${id} must equal entry.id`)
145
- assertString(entry.title, 'title', `${where} entry ${id}`)
146
- assertString(entry.content, 'content', `${where} entry ${id}`)
147
- if (!Number.isFinite(entry.ageDays) || entry.ageDays < 0) fixtureError(`${where} entry ${id}: ageDays must be a non-negative number`)
148
- if (entry.updatedDaysAgo !== undefined && (!Number.isFinite(entry.updatedDaysAgo) || entry.updatedDaysAgo < 0)) {
149
- fixtureError(`${where} entry ${id}: updatedDaysAgo must be a non-negative number`)
150
- }
151
- if (entry.tags !== undefined) assertStringArray(entry.tags, 'tags', `${where} entry ${id}`)
152
- if (entry.visibility !== undefined && !['shared', 'secret'].includes(entry.visibility)) {
153
- fixtureError(`${where} entry ${id}: visibility must be shared or secret`)
154
- }
155
- if (entry.status !== undefined && !['active', 'superseded', 'pending_review', 'archived', 'suppressed', 'expired'].includes(entry.status)) {
156
- fixtureError(`${where} entry ${id}: unknown status ${entry.status}`)
157
- }
158
- if (entry.secret === true) fixtureError(`${where} entry ${id}: secret is a config flag; use visibility=secret for memory entries`)
159
- return entry
160
- }
161
-
162
- function validateFileShape(raw, fileName) {
163
- if (!isPlainObject(raw)) fixtureError(`${fileName}: file must be an object`)
164
- if (raw.draft !== true) fixtureError(`${fileName}: draft must be true`)
165
- if (raw.notGold !== true) fixtureError(`${fileName}: notGold must be true`)
166
- if (!DATASET_STATUSES.includes(raw.status)) fixtureError(`${fileName}: status must be one of ${DATASET_STATUSES.join(', ')}`)
167
- if (raw.status === CANDIDATE_STATUS && raw.review !== 'pending') {
168
- fixtureError(`${fileName}: candidate file review must be pending`)
169
- }
170
- if (raw.gold === true) fixtureError(`${fileName}: gold must not be marked before human review`)
171
- assertString(raw.name, 'name', fileName)
172
- if (!SUBCLASSES.includes(raw.subclass)) fixtureError(`${fileName}: unknown file subclass ${raw.subclass}`)
173
- if (!isPlainObject(raw.entries)) fixtureError(`${fileName}: entries must be an object`)
174
- if (!Array.isArray(raw.samples) || raw.samples.length === 0) fixtureError(`${fileName}: samples must be a non-empty array`)
175
- return { status: raw.status, review: raw.status === CANDIDATE_STATUS ? 'pending' : undefined }
176
- }
177
-
178
- /**
179
- * Load and validate all synthetic fixtures. Validation is intentionally strict:
180
- * a typo in an expected id must fail the benchmark instead of silently becoming
181
- * a zero score.
182
- */
183
- export function loadDataset(fixtureDir = FIXTURE_DIR) {
184
- const dir = path.resolve(fixtureDir)
185
- let names
186
- try {
187
- names = fs.readdirSync(dir).filter(name => name.endsWith('.json')).sort()
188
- } catch (error) {
189
- fixtureError(`cannot read fixture directory ${dir}: ${error?.message || error}`)
190
- }
191
- if (names.length === 0) fixtureError(`no .json fixtures in ${dir}`)
192
-
193
- const entries = new Map()
194
- const samples = []
195
- const files = []
196
- const sampleIds = new Set()
197
- const statuses = new Set()
198
- for (const fileName of names) {
199
- const filePath = path.join(dir, fileName)
200
- let raw
201
- try {
202
- raw = JSON.parse(fs.readFileSync(filePath, 'utf8'))
203
- } catch (error) {
204
- fixtureError(`${fileName}: invalid JSON: ${error?.message || error}`)
205
- }
206
- const fileShape = validateFileShape(raw, fileName)
207
- statuses.add(fileShape.status)
208
- for (const [id, entry] of Object.entries(raw.entries)) {
209
- if (entries.has(id)) fixtureError(`duplicate entry id ${id} across fixture files`)
210
- entries.set(id, validateEntry(entry, id, fileName))
211
- }
212
- for (let index = 0; index < raw.samples.length; index += 1) {
213
- const sample = validateSampleShape(raw.samples[index], `${fileName} samples[${index}]`, { status: fileShape.status })
214
- if (sample.subclass !== raw.subclass) fixtureError(`${fileName}: sample ${sample.id} subclass does not match file subclass`)
215
- if (sampleIds.has(sample.id)) fixtureError(`duplicate sample id ${sample.id}`)
216
- sampleIds.add(sample.id)
217
- samples.push(sample)
218
- }
219
- files.push({ name: fileName, sha256: sha256(fs.readFileSync(filePath)) })
220
- }
221
-
222
- for (const sample of samples) {
223
- for (const id of sample.library) {
224
- if (!entries.has(id)) fixtureError(`sample ${sample.id}: library id ${id} is not defined in any fixture file`)
225
- }
226
- for (const id of sample.expectedIds) {
227
- if (!sample.library.includes(id)) fixtureError(`sample ${sample.id}: expected id ${id} is outside its library`)
228
- }
229
- for (const id of sample.forbiddenIds) {
230
- if (!sample.library.includes(id)) fixtureError(`sample ${sample.id}: forbidden id ${id} is outside its library`)
231
- }
232
- }
233
- if (statuses.size !== 1) fixtureError('fixture directory mixes dataset statuses')
234
- const datasetStatus = [...statuses][0]
235
- if (samples.length < 30 || samples.length > 50) {
236
- fixtureError(`expected 30-50 samples, found ${samples.length}`)
237
- }
238
- for (const subclass of SUBCLASSES) {
239
- if (!samples.some(sample => sample.subclass === subclass)) fixtureError(`missing subclass ${subclass}`)
240
- }
241
-
242
- const digest = crypto.createHash('sha256')
243
- for (const file of files) {
244
- digest.update(file.name)
245
- digest.update('\0')
246
- digest.update(file.sha256)
247
- digest.update('\0')
248
- }
249
- return {
250
- name: datasetStatus === CANDIDATE_STATUS ? 'recall-bench-gold-candidates' : 'recall-bench-synthetic-draft',
251
- status: datasetStatus,
252
- draft: true,
253
- notGold: true,
254
- gold: false,
255
- review: datasetStatus === CANDIDATE_STATUS ? 'pending' : undefined,
256
- dir,
257
- files,
258
- sha256: digest.digest('hex'),
259
- entries,
260
- samples,
261
- }
262
- }
263
-
264
- function sha256(buffer) {
265
- return crypto.createHash('sha256').update(buffer).digest('hex')
266
- }
267
-
268
- function round(value, digits = 6) {
269
- const factor = 10 ** digits
270
- const rounded = Math.round((Number(value) + Number.EPSILON) * factor) / factor
271
- return Object.is(rounded, -0) ? 0 : rounded
272
- }
273
-
274
- function top3Of(ids) {
275
- return Array.isArray(ids) ? ids.slice(0, 3) : []
276
- }
277
-
278
- /**
279
- * Compute the benchmark metrics for one projection (candidate ids, final injected
280
- * ids, or explicit-probe ids).
281
- *
282
- * Definitions and empty-set rules:
283
- * - Recall@3 denominator = answerable samples only. A sample counts as a hit if
284
- * at least one expected id is in the first three positions.
285
- * - allExpectedAt3 denominator = answerable samples only; all expected ids must
286
- * appear in top-3 (sets larger than three cannot score a complete hit).
287
- * - MRR@3 denominator = answerable samples only. The reciprocal rank is 0 when no
288
- * expected id appears in the first three positions.
289
- * - No-answer false-recall denominator = no-answer samples only. It is the fraction
290
- * whose first three positions contain any id at all.
291
- * - Isolation violations = every occurrence of a forbidden id in any scored top-3.
292
- * The requirement is exactly 0; the denominator is reported for transparency.
293
- * - If a denominator is empty, the corresponding rate is reported as 0 with an
294
- * explicit emptySet flag. The harness refuses an empty overall dataset.
295
- */
296
- export function computeMetrics(records) {
297
- let answerable = 0
298
- let hits = 0
299
- let completeHits = 0
300
- let reciprocalRankSum = 0
301
- let noAnswer = 0
302
- let noAnswerFalseRecall = 0
303
- let forbiddenChecked = 0
304
- const violations = []
305
- for (const record of records) {
306
- const top3 = top3Of(record.top3)
307
- if (record.noAnswer === true) {
308
- noAnswer += 1
309
- if (top3.length > 0) noAnswerFalseRecall += 1
310
- } else {
311
- answerable += 1
312
- const expected = [...new Set(record.expectedIds || [])]
313
- if (expected.length > 0 && expected.every(id => top3.includes(id))) completeHits += 1
314
- let rank = 0
315
- for (let index = 0; index < top3.length; index += 1) {
316
- if (record.expectedIds?.includes(top3[index])) {
317
- rank = index + 1
318
- break
319
- }
320
- }
321
- if (rank > 0) {
322
- hits += 1
323
- reciprocalRankSum += 1 / rank
324
- }
325
- }
326
- for (const id of record.forbiddenIds || []) {
327
- forbiddenChecked += 1
328
- if (top3.includes(id)) violations.push({ sampleId: record.id, id, top3: top3.slice() })
329
- }
330
- }
331
- return {
332
- recallAt3: answerable === 0 ? 0 : round(hits / answerable),
333
- allExpectedAt3: answerable === 0 ? 0 : round(completeHits / answerable),
334
- mrrAt3: answerable === 0 ? 0 : round(reciprocalRankSum / answerable),
335
- noAnswerFalseRecallRate: noAnswer === 0 ? 0 : round(noAnswerFalseRecall / noAnswer),
336
- isolationViolations: violations.length,
337
- denominators: {
338
- answerable,
339
- noAnswer,
340
- forbiddenChecked,
341
- },
342
- emptySet: {
343
- recallAt3: answerable === 0,
344
- allExpectedAt3: answerable === 0,
345
- mrrAt3: answerable === 0,
346
- noAnswerFalseRecallRate: noAnswer === 0,
347
- isolationViolations: forbiddenChecked === 0,
348
- },
349
- violations: violations.slice(0, 50),
350
- }
351
- }
352
-
353
- function latencyStats(values) {
354
- const sorted = values.map(Number).filter(Number.isFinite).sort((a, b) => a - b)
355
- if (sorted.length === 0) return { backend: RUN_CONFIG.backend, samples: 0, medianMs: null, p95Ms: null, method: 'no samples' }
356
- const mid = Math.floor(sorted.length / 2)
357
- const median = sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2
358
- const p95Index = Math.max(0, Math.ceil(sorted.length * 0.95) - 1)
359
- return {
360
- backend: RUN_CONFIG.backend,
361
- samples: sorted.length,
362
- medianMs: round(median, 3),
363
- p95Ms: round(sorted[p95Index], 3),
364
- method: 'wall-clock around automatic candidate + buildRecall per sample; single Node process; performance.now(); not service latency',
365
- }
366
- }
367
-
368
- function prepareRoot(workRoot) {
369
- const tmp = path.resolve(os.tmpdir())
370
- let root = workRoot ? path.resolve(workRoot) : fs.mkdtempSync(path.join(tmp, 'dsh-memu-recall-bench-'))
371
- const relative = path.relative(tmp, root)
372
- if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
373
- throw new Error(`recall-bench: workRoot must be a fresh directory under os.tmpdir(): ${root}`)
374
- }
375
- if (fs.existsSync(root)) {
376
- if (!fs.statSync(root).isDirectory()) throw new Error(`recall-bench: workRoot is not a directory: ${root}`)
377
- if (fs.readdirSync(root).length > 0) throw new Error(`recall-bench: workRoot must be empty: ${root}`)
378
- } else {
379
- fs.mkdirSync(root, { recursive: true })
380
- }
381
- return root
382
- }
383
-
384
- function installClock(initialMs) {
385
- const RealDate = Date
386
- let now = Number(initialMs)
387
- class BenchDate extends RealDate {
388
- constructor(...args) {
389
- super(...(args.length === 0 ? [now] : args))
390
- }
391
- static now() {
392
- return now
393
- }
394
- }
395
- globalThis.Date = BenchDate
396
- return {
397
- set(ms) { now = Number(ms) },
398
- restore() { globalThis.Date = RealDate },
399
- }
400
- }
401
-
402
- function installRandom(seed) {
403
- const original = Math.random
404
- let state = Number(seed) >>> 0
405
- if (state === 0) state = 0x9e3779b9
406
- Math.random = () => {
407
- state |= 0
408
- state = (state + 0x6d2b79f5) | 0
409
- let t = Math.imul(state ^ (state >>> 15), 1 | state)
410
- t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
411
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296
412
- }
413
- return { restore() { Math.random = original } }
414
- }
415
-
416
- function entryForSample(source, sample) {
417
- const { id: _id, ageDays = 7, updatedDaysAgo, ...rest } = source
418
- const nowMs = Date.parse(sample.time)
419
- const createdMs = nowMs - Number(ageDays) * DAY_MS
420
- const updatedMs = nowMs - Number(updatedDaysAgo ?? ageDays) * DAY_MS
421
- return {
422
- createdAt: new Date(createdMs).toISOString(),
423
- updatedAt: new Date(updatedMs).toISOString(),
424
- layer: 'long_term',
425
- status: 'active',
426
- visibility: 'shared',
427
- context: {},
428
- confidence: 0.9,
429
- owner: 'user',
430
- source: 'user_said',
431
- accessCount: 0,
432
- injectCount: 0,
433
- tags: [],
434
- ...rest,
435
- }
436
- }
437
-
438
- function seedSample(state, sample, entries, suffix = '') {
439
- const library = state.createLibrary({
440
- name: `bench-${sample.id}${suffix}`,
441
- scopeKey: path.join(os.tmpdir(), 'dsh-memu-recall-bench-identities', `${sample.id}${suffix}`),
442
- })
443
- const index = { version: 1, entries: {} }
444
- for (const id of sample.library) {
445
- const source = entries.get(id)
446
- if (!source) throw new Error(`recall-bench: missing entry ${id}`)
447
- index.entries[id] = entryForSample(source, sample)
448
- }
449
- state.savePrivateIndex(library.id, index)
450
- const sessionId = `bench-session-${sample.id}${suffix}`
451
- state.setSessionBinding(sessionId, {
452
- libraryId: library.id,
453
- scopeKey: library.scopeKey,
454
- useLibrary: true,
455
- useGlobal: false,
456
- memoryContext: { ...sample.context },
457
- memoryOwnerSessionId: sessionId,
458
- domain: sample.subclass === 'coding' ? 'coding' : 'rp',
459
- domainOverride: sample.subclass === 'coding' ? 'coding' : 'rp',
460
- injectedAt: {},
461
- injectedIds: [],
462
- recentQueries: [],
463
- lastInjectedTurn: 0,
464
- })
465
- state.flushState()
466
- return { library, sessionId }
467
- }
468
-
469
- function execFor(sessionId, root) {
470
- return {
471
- agent: {
472
- session: {
473
- header: {
474
- id: sessionId,
475
- cwd: path.join(root, 'cwd'),
476
- agentPreset: 'rp',
477
- },
478
- },
479
- },
480
- }
481
- }
482
-
483
- function gitCommit() {
484
- try {
485
- return execFileSync('git', ['rev-parse', '--short', 'HEAD'], {
486
- cwd: ROOT,
487
- encoding: 'utf8',
488
- stdio: ['ignore', 'pipe', 'ignore'],
489
- timeout: 3000,
490
- }).trim() || null
491
- } catch {
492
- return null
493
- }
494
- }
495
-
496
- function packageVersion() {
497
- try {
498
- return JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version || null
499
- } catch {
500
- return null
501
- }
502
- }
503
-
504
- function buildProjection(records, key, expectedKey, forbiddenKey, { noAnswerEligible = true } = {}) {
505
- const projected = records.map(record => ({
506
- id: record.id,
507
- subclass: record.subclass,
508
- noAnswer: noAnswerEligible ? record.noAnswer : false,
509
- expectedIds: record[expectedKey] || [],
510
- forbiddenIds: record[forbiddenKey] || [],
511
- top3: top3Of(record[key]),
512
- }))
513
- return computeMetrics(projected)
514
- }
515
-
516
- function bySubclass(records) {
517
- const result = {}
518
- for (const subclass of SUBCLASSES) {
519
- const subset = records.filter(record => record.subclass === subclass)
520
- if (subset.length === 0) continue
521
- const candidate = buildProjection(subset, 'candidateTop3', 'expectedIds', 'forbiddenIds')
522
- const finalInjected = buildProjection(subset, 'injectedTop3', 'expectedIds', 'forbiddenIds')
523
- result[subclass] = {
524
- samples: subset.length,
525
- candidateRecallAt3: candidate.recallAt3,
526
- candidateMrrAt3: candidate.mrrAt3,
527
- candidateNoAnswerFalseRecallRate: candidate.noAnswerFalseRecallRate,
528
- candidateIsolationViolations: candidate.isolationViolations,
529
- finalInjectedRecallAt3: finalInjected.recallAt3,
530
- finalInjectedMrrAt3: finalInjected.mrrAt3,
531
- finalInjectedNoAnswerFalseRecallRate: finalInjected.noAnswerFalseRecallRate,
532
- finalInjectedIsolationViolations: finalInjected.isolationViolations,
533
- denominators: finalInjected.denominators,
534
- }
535
- }
536
- return result
537
- }
538
-
539
- function sumEstimate(records) {
540
- return records.reduce((total, record) => total + Number(record.injectedTokenEstimate || 0), 0)
541
- }
542
-
543
- /**
544
- * Run the benchmark. All state lives under a fresh os.tmpdir() root. The env
545
- * overrides are restored in finally, and the root is removed after the report is
546
- * built unless the caller supplied workRoot or --keep for inspection.
547
- */
548
- export async function runBenchmark(options = {}) {
549
- const fixtureDir = path.resolve(options.fixtureDir || FIXTURE_DIR)
550
- const dataset = loadDataset(fixtureDir)
551
- const sampleLimit = options.sampleLimit === undefined ? dataset.samples.length : Number(options.sampleLimit)
552
- if (!Number.isInteger(sampleLimit) || sampleLimit < 1 || sampleLimit > dataset.samples.length) {
553
- throw new Error(`recall-bench: sampleLimit must be 1..${dataset.samples.length}`)
554
- }
555
- const samples = dataset.samples.slice(0, sampleLimit)
556
- const root = prepareRoot(options.workRoot)
557
- const seed = Number.isInteger(options.seed) ? options.seed : RUN_CONFIG.seed
558
- const startedAt = new Date().toISOString()
559
- const clock = installClock(Date.parse(samples[0].time))
560
- const random = installRandom(seed)
561
- const previousHome = process.env.DSH_MEMU_HOME
562
- const previousMemoryHome = process.env.DSH_MEMU_MEMORY_HOME
563
- let state = null
564
- const records = []
565
-
566
- try {
567
- process.env.DSH_MEMU_HOME = path.join(root, 'dsh-memu-home')
568
- process.env.DSH_MEMU_MEMORY_HOME = path.join(root, 'dsh-memu-data')
569
- fs.mkdirSync(process.env.DSH_MEMU_HOME, { recursive: true })
570
- fs.mkdirSync(process.env.DSH_MEMU_MEMORY_HOME, { recursive: true })
571
-
572
- state = await import(pathToFileURL(path.join(ROOT, 'lib', 'state.js')).href)
573
- const memory = await import(pathToFileURL(path.join(ROOT, 'lib', 'memory.js')).href)
574
- const inject = await import(pathToFileURL(path.join(ROOT, 'lib', 'inject.js')).href)
575
- const budget = await import(pathToFileURL(path.join(ROOT, 'lib', 'budget.js')).href)
576
-
577
- for (const sample of samples) {
578
- const sampleNow = Date.parse(sample.time)
579
- clock.set(sampleNow)
580
- const automatic = seedSample(state, sample, dataset.entries, '')
581
- const autoExec = execFor(automatic.sessionId, root)
582
- const settings = {
583
- ...state.getSettings(),
584
- privateTopK: RUN_CONFIG.privateTopK,
585
- turnTokens: RUN_CONFIG.turnTokens,
586
- relevanceThreshold: RUN_CONFIG.relevanceThreshold,
587
- dedupeTurns: RUN_CONFIG.dedupeTurns,
588
- autoInject: 'smart',
589
- globalEveryNTurns: 0,
590
- }
591
-
592
- const started = performance.now()
593
- const candidate = await memory.privateRecall({
594
- exec: autoExec,
595
- query: sample.query,
596
- topK: RUN_CONFIG.candidateTopK,
597
- relevanceThreshold: RUN_CONFIG.relevanceThreshold,
598
- purpose: 'automatic',
599
- })
600
- const candidateIds = (candidate.files || []).map(file => file.name)
601
- const binding = state.getSessionBinding(automatic.sessionId)
602
- if (!binding) throw new Error(`recall-bench: session binding disappeared for ${sample.id}`)
603
- const injected = await inject.buildRecall(binding, sample.query, 1, settings, autoExec, automatic.sessionId)
604
- const latencyMs = performance.now() - started
605
-
606
- const injectedIds = Array.isArray(injected.ids) ? injected.ids.slice() : []
607
- const injectedText = String(injected.text || '')
608
- const injectedTokenEstimate = budget.estTokens(injectedText)
609
-
610
- let explicitIds = []
611
- if (Array.isArray(sample.explicitExpectedIds) && sample.explicitExpectedIds.length > 0) {
612
- const explicit = seedSample(state, sample, dataset.entries, '-explicit')
613
- const explicitExec = execFor(explicit.sessionId, root)
614
- const explicitResult = await memory.privateRecall({
615
- exec: explicitExec,
616
- query: sample.query,
617
- topK: RUN_CONFIG.candidateTopK,
618
- relevanceThreshold: RUN_CONFIG.relevanceThreshold,
619
- purpose: 'explicit',
620
- })
621
- explicitIds = (explicitResult.files || []).map(file => file.name)
622
- }
623
-
624
- records.push({
625
- id: sample.id,
626
- subclass: sample.subclass,
627
- draft: true,
628
- notGold: true,
629
- noAnswer: sample.noAnswer,
630
- query: sample.query,
631
- context: { ...sample.context },
632
- time: sample.time,
633
- expectedIds: sample.expectedIds.slice(),
634
- forbiddenIds: sample.forbiddenIds.slice(),
635
- library: sample.library.slice(),
636
- candidateIds,
637
- candidateRoute: candidate.recallRoute || null,
638
- candidateErrors: Array.isArray(candidate.errors) ? candidate.errors.slice() : [],
639
- candidateFusion: candidate.fusion || null,
640
- candidateTop3: top3Of(candidateIds),
641
- candidateCount: candidateIds.length,
642
- injectedIds,
643
- injectedTop3: top3Of(injectedIds),
644
- injectedOutcome: injected.outcome || null,
645
- injectedErrors: Array.isArray(injected.errors) ? injected.errors.slice() : [],
646
- injectedTextChars: injectedText.length,
647
- injectedTokenEstimate,
648
- explicitIds,
649
- explicitTop3: top3Of(explicitIds),
650
- latencyMs: round(latencyMs, 3),
651
- })
652
- }
653
- state.flushState()
654
-
655
- const candidateMetrics = buildProjection(records, 'candidateTop3', 'expectedIds', 'forbiddenIds')
656
- const injectedMetrics = buildProjection(records, 'injectedTop3', 'expectedIds', 'forbiddenIds')
657
- const explicitRecords = records.filter(record => {
658
- const sample = samples.find(item => item.id === record.id)
659
- return Array.isArray(sample?.explicitExpectedIds) && sample.explicitExpectedIds.length > 0
660
- })
661
- const explicitMetrics = buildProjection(
662
- explicitRecords.map(record => {
663
- const sample = samples.find(item => item.id === record.id)
664
- return {
665
- ...record,
666
- explicitExpectedIds: sample.explicitExpectedIds,
667
- explicitForbiddenIds: sample.explicitForbiddenIds || [],
668
- }
669
- }),
670
- 'explicitTop3',
671
- 'explicitExpectedIds',
672
- 'explicitForbiddenIds',
673
- { noAnswerEligible: false },
674
- )
675
- const candidateViolations = candidateMetrics.violations.map(item => ({ ...item, projection: 'candidate' }))
676
- const injectedViolations = injectedMetrics.violations.map(item => ({ ...item, projection: 'final-injected' }))
677
- const explicitViolations = explicitMetrics.violations.map(item => ({ ...item, projection: 'explicit-probe' }))
678
- const injectedTotalEstimate = sumEstimate(records)
679
- const sampleCount = records.length
680
-
681
- return {
682
- schemaVersion: RUN_CONFIG.schemaVersion,
683
- kind: 'recall-bench',
684
- ok: true,
685
- status: dataset.status,
686
- gold: false,
687
- review: dataset.review,
688
- dataset: {
689
- name: dataset.name,
690
- status: dataset.status,
691
- draft: true,
692
- notGold: true,
693
- gold: false,
694
- review: dataset.review,
695
- sampleCount,
696
- fileCount: dataset.files.length,
697
- sha256: dataset.sha256,
698
- files: dataset.files,
699
- },
700
- code: {
701
- commit: gitCommit(),
702
- packageVersion: packageVersion(),
703
- worktree: 'dirty-or-uncommitted (recorded from current workspace; not a commit)',
704
- },
705
- run: {
706
- startedAt,
707
- root,
708
- clock: 'fixed per sample (Date.now overridden from sample.time)',
709
- randomSeed: seed,
710
- random: 'seeded mulberry32',
711
- sampleLimit,
712
- },
713
- config: {
714
- backend: RUN_CONFIG.backend,
715
- candidateTopK: RUN_CONFIG.candidateTopK,
716
- privateTopK: RUN_CONFIG.privateTopK,
717
- turnTokens: RUN_CONFIG.turnTokens,
718
- relevanceThreshold: RUN_CONFIG.relevanceThreshold,
719
- dedupeTurns: RUN_CONFIG.dedupeTurns,
720
- mockVectors: 'pipeline-only',
721
- vectorPath: 'none (local lexical only)',
722
- note: 'local lexical only; any mock/lexical vector path validates pipeline plumbing, not embedding quality',
723
- },
724
- metrics: {
725
- candidate: candidateMetrics,
726
- finalInjected: injectedMetrics,
727
- explicitProbe: explicitMetrics,
728
- isolation: {
729
- violations: candidateViolations.length + injectedViolations.length + explicitViolations.length,
730
- mustBeZero: true,
731
- candidate: candidateMetrics.isolationViolations,
732
- finalInjected: injectedMetrics.isolationViolations,
733
- explicitProbe: explicitMetrics.isolationViolations,
734
- forbiddenDenominator: candidateMetrics.denominators.forbiddenChecked
735
- + injectedMetrics.denominators.forbiddenChecked
736
- + explicitMetrics.denominators.forbiddenChecked,
737
- details: [...candidateViolations, ...injectedViolations, ...explicitViolations].slice(0, 100),
738
- },
739
- latency: latencyStats(records.map(record => record.latencyMs)),
740
- bySubclass: bySubclass(records),
741
- },
742
- budget: {
743
- estimateOnly: true,
744
- field: 'estimate',
745
- estimate: {
746
- injectedTokenTotal: round(injectedTotalEstimate, 3),
747
- injectedTokenMeanPerSample: sampleCount === 0 ? 0 : round(injectedTotalEstimate / sampleCount, 3),
748
- turnTokens: RUN_CONFIG.turnTokens,
749
- method: 'lib/budget.js estTokens; CJK ~1 token/char, Latin ~3.4 chars/token',
750
- },
751
- method: 'lib/budget.js estTokens; CJK ~1 token/char, Latin ~3.4 chars/token',
752
- turnTokens: RUN_CONFIG.turnTokens,
753
- injectedTokenEstimateTotal: round(injectedTotalEstimate, 3),
754
- injectedTokenEstimateMean: sampleCount === 0 ? 0 : round(injectedTotalEstimate / sampleCount, 3),
755
- note: 'Token estimates only. These are not actual token usage and must not be reported as consumed tokens.',
756
- },
757
- samples: records,
758
- }
759
- } finally {
760
- try {
761
- state?.flushState()
762
- } catch {}
763
- clock.restore()
764
- random.restore()
765
- if (previousHome === undefined) delete process.env.DSH_MEMU_HOME
766
- else process.env.DSH_MEMU_HOME = previousHome
767
- if (previousMemoryHome === undefined) delete process.env.DSH_MEMU_MEMORY_HOME
768
- else process.env.DSH_MEMU_MEMORY_HOME = previousMemoryHome
769
- if (!options.workRoot && !options.keep) {
770
- try { fs.rmSync(root, { recursive: true, force: true }) } catch {}
771
- }
772
- }
773
- }
774
-
775
- export function parseArgs(argv) {
776
- const options = {}
777
- for (let index = 0; index < argv.length; index += 1) {
778
- const arg = argv[index]
779
- if (arg === '--out') options.out = argv[++index]
780
- else if (arg === '--fixture-dir') {
781
- const fixtureDir = argv[++index]
782
- if (!fixtureDir || fixtureDir.startsWith('--')) throw new Error('recall-bench: --fixture-dir requires a directory')
783
- options.fixtureDir = fixtureDir
784
- }
785
- else if (arg === '--work-root') options.workRoot = argv[++index]
786
- else if (arg === '--seed') options.seed = Number(argv[++index])
787
- else if (arg === '--samples') options.sampleLimit = Number(argv[++index])
788
- else if (arg === '--keep') options.keep = true
789
- else if (arg === '--help' || arg === '-h') options.help = true
790
- else throw new Error(`recall-bench: unknown argument ${arg}`)
791
- }
792
- return options
793
- }
794
-
795
- async function main() {
796
- const options = parseArgs(process.argv.slice(2))
797
- if (options.help) {
798
- console.log('Usage: node scripts/recall-bench.mjs [--fixture-dir DIR] [--out report.json] [--work-root DIR] [--seed N] [--samples N] [--keep]')
799
- console.log(' --fixture-dir DIR fixture directory; default tests/fixtures/recall-bench; candidate package tests/fixtures/recall-bench-gold-candidates')
800
- console.log(' --samples N run the first N samples, 1..dataset size; default all samples')
801
- return
802
- }
803
- const report = await runBenchmark(options)
804
- const json = JSON.stringify(report, null, 2)
805
- if (options.out) {
806
- fs.mkdirSync(path.dirname(path.resolve(options.out)), { recursive: true })
807
- fs.writeFileSync(path.resolve(options.out), json.replace(/\r?\n/g, '\r\n'), 'utf8')
808
- console.log(`recall-bench: wrote ${path.resolve(options.out)}`)
809
- } else {
810
- console.log(json)
811
- }
812
- }
813
-
814
- const invoked = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url : false
815
- if (invoked) {
816
- main().catch(error => {
817
- console.error(JSON.stringify({ ok: false, kind: 'recall-bench', error: error?.message || String(error) }, null, 2))
818
- process.exitCode = 1
819
- })
820
- }
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Reproducible recall benchmark harness.
4
+ *
5
+ * This is a SYNTHETIC-DRAFT benchmark, not a gold set. It seeds each sample into
6
+ * its own temporary library under os.tmpdir(), uses a fixed clock per sample and a
7
+ * seeded PRNG, and never reads or writes the user's memory directory. The production
8
+ * ranking code is imported and exercised read-only; no production ordering is changed.
9
+ *
10
+ * The local lexical backend is the only backend in this harness. Mock/lexical
11
+ * vectors only validate the pipeline: they do not establish embedding quality.
12
+ */
13
+ import fs from 'node:fs'
14
+ import os from 'node:os'
15
+ import path from 'node:path'
16
+ import crypto from 'node:crypto'
17
+ import { execFileSync } from 'node:child_process'
18
+ import { fileURLToPath, pathToFileURL } from 'node:url'
19
+
20
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
21
+ export const FIXTURE_DIR = path.join(ROOT, 'tests', 'fixtures', 'recall-bench')
22
+ export const CANDIDATE_FIXTURE_DIR = path.join(ROOT, 'tests', 'fixtures', 'recall-bench-gold-candidates')
23
+ export const DEFAULT_STATUS = 'synthetic-draft-not-gold'
24
+ export const CANDIDATE_STATUS = 'gold-candidate-pending-review'
25
+ export const DATASET_STATUSES = Object.freeze([DEFAULT_STATUS, CANDIDATE_STATUS])
26
+ export const SUBCLASSES = Object.freeze([
27
+ 'paraphrase',
28
+ 'exact',
29
+ 'negation',
30
+ 'no-answer',
31
+ 'conflict',
32
+ 'boundary',
33
+ 'secret',
34
+ 'coding',
35
+ ])
36
+ export const SAMPLE_FIELDS = Object.freeze([
37
+ 'id',
38
+ 'draft',
39
+ 'notGold',
40
+ 'subclass',
41
+ 'query',
42
+ 'context',
43
+ 'time',
44
+ 'expectedIds',
45
+ 'forbiddenIds',
46
+ 'noAnswer',
47
+ 'library',
48
+ ])
49
+ export const RUN_CONFIG = Object.freeze({
50
+ schemaVersion: 1,
51
+ benchmark: 'recall-bench',
52
+ status: DEFAULT_STATUS,
53
+ seed: 20261029,
54
+ candidateTopK: 20,
55
+ privateTopK: 3,
56
+ turnTokens: 640,
57
+ relevanceThreshold: 0.4,
58
+ dedupeTurns: 16,
59
+ backend: 'local-lexical',
60
+ })
61
+
62
+ const DAY_MS = 24 * 60 * 60 * 1000
63
+
64
+ function fixtureError(message) {
65
+ throw new Error(`recall-bench fixture: ${message}`)
66
+ }
67
+
68
+ function isPlainObject(value) {
69
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
70
+ }
71
+
72
+ function assertString(value, field, where, { nonEmpty = true } = {}) {
73
+ if (typeof value !== 'string' || (nonEmpty && !value.trim())) fixtureError(`${where}: ${field} must be a non-empty string`)
74
+ return value
75
+ }
76
+
77
+ function assertStringArray(value, field, where, { allowEmpty = true } = {}) {
78
+ if (!Array.isArray(value)) fixtureError(`${where}: ${field} must be an array`)
79
+ if (!allowEmpty && value.length === 0) fixtureError(`${where}: ${field} must not be empty`)
80
+ if (value.some(item => typeof item !== 'string' || !item.trim())) fixtureError(`${where}: ${field} must contain non-empty strings`)
81
+ const unique = new Set(value)
82
+ if (unique.size !== value.length) fixtureError(`${where}: ${field} contains duplicate ids`)
83
+ return value
84
+ }
85
+
86
+ export function validateSampleShape(sample, where = 'sample', options = {}) {
87
+ if (!isPlainObject(sample)) fixtureError(`${where}: sample must be an object`)
88
+ for (const field of SAMPLE_FIELDS) {
89
+ if (!Object.hasOwn(sample, field)) fixtureError(`${where}: missing field ${field}`)
90
+ }
91
+ assertString(sample.id, 'id', where)
92
+ if (!/^[a-z0-9][a-z0-9-]{2,80}$/.test(sample.id)) fixtureError(`${where}: invalid sample id ${sample.id}`)
93
+ if (sample.draft !== true) fixtureError(`${where}: draft must be true (do not present unconfirmed samples as confirmed)`)
94
+ if (sample.notGold !== true) fixtureError(`${where}: notGold must be true (unconfirmed samples are not a gold set)`)
95
+ if (options.status === CANDIDATE_STATUS) {
96
+ if (sample.status !== CANDIDATE_STATUS) fixtureError(`${where}: candidate sample status must be ${CANDIDATE_STATUS}`)
97
+ if (sample.review !== 'pending') fixtureError(`${where}: candidate sample review must be pending`)
98
+ }
99
+ if (sample.gold === true) fixtureError(`${where}: gold must not be marked before human review`)
100
+ if (!SUBCLASSES.includes(sample.subclass)) fixtureError(`${where}: unknown subclass ${sample.subclass}`)
101
+ assertString(sample.query, 'query', where)
102
+ if (!isPlainObject(sample.context)) fixtureError(`${where}: context must be an object`)
103
+ assertString(sample.time, 'time', where)
104
+ if (!Number.isFinite(Date.parse(sample.time))) fixtureError(`${where}: time must be an ISO date/time`)
105
+ assertStringArray(sample.expectedIds, 'expectedIds', where)
106
+ assertStringArray(sample.forbiddenIds, 'forbiddenIds', where)
107
+ assertStringArray(sample.library, 'library', where, { allowEmpty: false })
108
+ if (sample.library.length > 10) fixtureError(`${where}: library subset is capped at 10 entries`)
109
+ if (typeof sample.noAnswer !== 'boolean') fixtureError(`${where}: noAnswer must be boolean`)
110
+ if (sample.noAnswer && sample.expectedIds.length > 0) fixtureError(`${where}: noAnswer=true requires expectedIds=[]`)
111
+ if (!sample.noAnswer && sample.expectedIds.length === 0) fixtureError(`${where}: answerable sample requires expectedIds`)
112
+ for (const id of sample.expectedIds) {
113
+ if (!sample.library.includes(id)) fixtureError(`${where}: expected id ${id} is outside the declared library`)
114
+ }
115
+ for (const id of sample.forbiddenIds) {
116
+ if (!sample.library.includes(id)) fixtureError(`${where}: forbidden id ${id} is outside the declared library`)
117
+ if (sample.expectedIds.includes(id)) fixtureError(`${where}: id ${id} is both expected and forbidden`)
118
+ }
119
+ if (sample.explicitExpectedIds !== undefined) {
120
+ assertStringArray(sample.explicitExpectedIds, 'explicitExpectedIds', where, { allowEmpty: false })
121
+ for (const id of sample.explicitExpectedIds) {
122
+ if (!sample.library.includes(id)) fixtureError(`${where}: explicit expected id ${id} is outside the declared library`)
123
+ if (!sample.expectedIds.includes(id) && sample.noAnswer !== true) {
124
+ // Explicit recall may surface a secret that automatic recall hides, so an
125
+ // extra id is allowed; it must still be declared in the subset.
126
+ }
127
+ }
128
+ for (const id of sample.expectedIds) {
129
+ if (!sample.explicitExpectedIds.includes(id)) fixtureError(`${where}: explicitExpectedIds must include every expectedId`)
130
+ }
131
+ }
132
+ if (sample.explicitForbiddenIds !== undefined) {
133
+ assertStringArray(sample.explicitForbiddenIds, 'explicitForbiddenIds', where)
134
+ for (const id of sample.explicitForbiddenIds) {
135
+ if (!sample.library.includes(id)) fixtureError(`${where}: explicit forbidden id ${id} is outside the declared library`)
136
+ if (sample.explicitExpectedIds?.includes(id)) fixtureError(`${where}: id ${id} is both explicit expected and forbidden`)
137
+ }
138
+ }
139
+ return sample
140
+ }
141
+
142
+ function validateEntry(entry, id, where) {
143
+ if (!isPlainObject(entry)) fixtureError(`${where}: entry ${id} must be an object`)
144
+ if (entry.id !== id) fixtureError(`${where}: entry key ${id} must equal entry.id`)
145
+ assertString(entry.title, 'title', `${where} entry ${id}`)
146
+ assertString(entry.content, 'content', `${where} entry ${id}`)
147
+ if (!Number.isFinite(entry.ageDays) || entry.ageDays < 0) fixtureError(`${where} entry ${id}: ageDays must be a non-negative number`)
148
+ if (entry.updatedDaysAgo !== undefined && (!Number.isFinite(entry.updatedDaysAgo) || entry.updatedDaysAgo < 0)) {
149
+ fixtureError(`${where} entry ${id}: updatedDaysAgo must be a non-negative number`)
150
+ }
151
+ if (entry.tags !== undefined) assertStringArray(entry.tags, 'tags', `${where} entry ${id}`)
152
+ if (entry.visibility !== undefined && !['shared', 'secret'].includes(entry.visibility)) {
153
+ fixtureError(`${where} entry ${id}: visibility must be shared or secret`)
154
+ }
155
+ if (entry.status !== undefined && !['active', 'superseded', 'pending_review', 'archived', 'suppressed', 'expired'].includes(entry.status)) {
156
+ fixtureError(`${where} entry ${id}: unknown status ${entry.status}`)
157
+ }
158
+ if (entry.secret === true) fixtureError(`${where} entry ${id}: secret is a config flag; use visibility=secret for memory entries`)
159
+ return entry
160
+ }
161
+
162
+ function validateFileShape(raw, fileName) {
163
+ if (!isPlainObject(raw)) fixtureError(`${fileName}: file must be an object`)
164
+ if (raw.draft !== true) fixtureError(`${fileName}: draft must be true`)
165
+ if (raw.notGold !== true) fixtureError(`${fileName}: notGold must be true`)
166
+ if (!DATASET_STATUSES.includes(raw.status)) fixtureError(`${fileName}: status must be one of ${DATASET_STATUSES.join(', ')}`)
167
+ if (raw.status === CANDIDATE_STATUS && raw.review !== 'pending') {
168
+ fixtureError(`${fileName}: candidate file review must be pending`)
169
+ }
170
+ if (raw.gold === true) fixtureError(`${fileName}: gold must not be marked before human review`)
171
+ assertString(raw.name, 'name', fileName)
172
+ if (!SUBCLASSES.includes(raw.subclass)) fixtureError(`${fileName}: unknown file subclass ${raw.subclass}`)
173
+ if (!isPlainObject(raw.entries)) fixtureError(`${fileName}: entries must be an object`)
174
+ if (!Array.isArray(raw.samples) || raw.samples.length === 0) fixtureError(`${fileName}: samples must be a non-empty array`)
175
+ return { status: raw.status, review: raw.status === CANDIDATE_STATUS ? 'pending' : undefined }
176
+ }
177
+
178
+ /**
179
+ * Load and validate all synthetic fixtures. Validation is intentionally strict:
180
+ * a typo in an expected id must fail the benchmark instead of silently becoming
181
+ * a zero score.
182
+ */
183
+ export function loadDataset(fixtureDir = FIXTURE_DIR) {
184
+ const dir = path.resolve(fixtureDir)
185
+ let names
186
+ try {
187
+ names = fs.readdirSync(dir).filter(name => name.endsWith('.json')).sort()
188
+ } catch (error) {
189
+ fixtureError(`cannot read fixture directory ${dir}: ${error?.message || error}`)
190
+ }
191
+ if (names.length === 0) fixtureError(`no .json fixtures in ${dir}`)
192
+
193
+ const entries = new Map()
194
+ const samples = []
195
+ const files = []
196
+ const sampleIds = new Set()
197
+ const statuses = new Set()
198
+ for (const fileName of names) {
199
+ const filePath = path.join(dir, fileName)
200
+ let raw
201
+ try {
202
+ raw = JSON.parse(fs.readFileSync(filePath, 'utf8'))
203
+ } catch (error) {
204
+ fixtureError(`${fileName}: invalid JSON: ${error?.message || error}`)
205
+ }
206
+ const fileShape = validateFileShape(raw, fileName)
207
+ statuses.add(fileShape.status)
208
+ for (const [id, entry] of Object.entries(raw.entries)) {
209
+ if (entries.has(id)) fixtureError(`duplicate entry id ${id} across fixture files`)
210
+ entries.set(id, validateEntry(entry, id, fileName))
211
+ }
212
+ for (let index = 0; index < raw.samples.length; index += 1) {
213
+ const sample = validateSampleShape(raw.samples[index], `${fileName} samples[${index}]`, { status: fileShape.status })
214
+ if (sample.subclass !== raw.subclass) fixtureError(`${fileName}: sample ${sample.id} subclass does not match file subclass`)
215
+ if (sampleIds.has(sample.id)) fixtureError(`duplicate sample id ${sample.id}`)
216
+ sampleIds.add(sample.id)
217
+ samples.push(sample)
218
+ }
219
+ files.push({ name: fileName, sha256: sha256(fs.readFileSync(filePath)) })
220
+ }
221
+
222
+ for (const sample of samples) {
223
+ for (const id of sample.library) {
224
+ if (!entries.has(id)) fixtureError(`sample ${sample.id}: library id ${id} is not defined in any fixture file`)
225
+ }
226
+ for (const id of sample.expectedIds) {
227
+ if (!sample.library.includes(id)) fixtureError(`sample ${sample.id}: expected id ${id} is outside its library`)
228
+ }
229
+ for (const id of sample.forbiddenIds) {
230
+ if (!sample.library.includes(id)) fixtureError(`sample ${sample.id}: forbidden id ${id} is outside its library`)
231
+ }
232
+ }
233
+ if (statuses.size !== 1) fixtureError('fixture directory mixes dataset statuses')
234
+ const datasetStatus = [...statuses][0]
235
+ if (samples.length < 30 || samples.length > 50) {
236
+ fixtureError(`expected 30-50 samples, found ${samples.length}`)
237
+ }
238
+ for (const subclass of SUBCLASSES) {
239
+ if (!samples.some(sample => sample.subclass === subclass)) fixtureError(`missing subclass ${subclass}`)
240
+ }
241
+
242
+ const digest = crypto.createHash('sha256')
243
+ for (const file of files) {
244
+ digest.update(file.name)
245
+ digest.update('\0')
246
+ digest.update(file.sha256)
247
+ digest.update('\0')
248
+ }
249
+ return {
250
+ name: datasetStatus === CANDIDATE_STATUS ? 'recall-bench-gold-candidates' : 'recall-bench-synthetic-draft',
251
+ status: datasetStatus,
252
+ draft: true,
253
+ notGold: true,
254
+ gold: false,
255
+ review: datasetStatus === CANDIDATE_STATUS ? 'pending' : undefined,
256
+ dir,
257
+ files,
258
+ sha256: digest.digest('hex'),
259
+ entries,
260
+ samples,
261
+ }
262
+ }
263
+
264
+ function sha256(buffer) {
265
+ return crypto.createHash('sha256').update(buffer).digest('hex')
266
+ }
267
+
268
+ function round(value, digits = 6) {
269
+ const factor = 10 ** digits
270
+ const rounded = Math.round((Number(value) + Number.EPSILON) * factor) / factor
271
+ return Object.is(rounded, -0) ? 0 : rounded
272
+ }
273
+
274
+ function top3Of(ids) {
275
+ return Array.isArray(ids) ? ids.slice(0, 3) : []
276
+ }
277
+
278
+ /**
279
+ * Compute the benchmark metrics for one projection (candidate ids, final injected
280
+ * ids, or explicit-probe ids).
281
+ *
282
+ * Definitions and empty-set rules:
283
+ * - Recall@3 denominator = answerable samples only. A sample counts as a hit if
284
+ * at least one expected id is in the first three positions.
285
+ * - allExpectedAt3 denominator = answerable samples only; all expected ids must
286
+ * appear in top-3 (sets larger than three cannot score a complete hit).
287
+ * - MRR@3 denominator = answerable samples only. The reciprocal rank is 0 when no
288
+ * expected id appears in the first three positions.
289
+ * - No-answer false-recall denominator = no-answer samples only. It is the fraction
290
+ * whose first three positions contain any id at all.
291
+ * - Isolation violations = every occurrence of a forbidden id in any scored top-3.
292
+ * The requirement is exactly 0; the denominator is reported for transparency.
293
+ * - If a denominator is empty, the corresponding rate is reported as 0 with an
294
+ * explicit emptySet flag. The harness refuses an empty overall dataset.
295
+ */
296
+ export function computeMetrics(records) {
297
+ let answerable = 0
298
+ let hits = 0
299
+ let completeHits = 0
300
+ let reciprocalRankSum = 0
301
+ let noAnswer = 0
302
+ let noAnswerFalseRecall = 0
303
+ let forbiddenChecked = 0
304
+ const violations = []
305
+ for (const record of records) {
306
+ const top3 = top3Of(record.top3)
307
+ if (record.noAnswer === true) {
308
+ noAnswer += 1
309
+ if (top3.length > 0) noAnswerFalseRecall += 1
310
+ } else {
311
+ answerable += 1
312
+ const expected = [...new Set(record.expectedIds || [])]
313
+ if (expected.length > 0 && expected.every(id => top3.includes(id))) completeHits += 1
314
+ let rank = 0
315
+ for (let index = 0; index < top3.length; index += 1) {
316
+ if (record.expectedIds?.includes(top3[index])) {
317
+ rank = index + 1
318
+ break
319
+ }
320
+ }
321
+ if (rank > 0) {
322
+ hits += 1
323
+ reciprocalRankSum += 1 / rank
324
+ }
325
+ }
326
+ for (const id of record.forbiddenIds || []) {
327
+ forbiddenChecked += 1
328
+ if (top3.includes(id)) violations.push({ sampleId: record.id, id, top3: top3.slice() })
329
+ }
330
+ }
331
+ return {
332
+ recallAt3: answerable === 0 ? 0 : round(hits / answerable),
333
+ allExpectedAt3: answerable === 0 ? 0 : round(completeHits / answerable),
334
+ mrrAt3: answerable === 0 ? 0 : round(reciprocalRankSum / answerable),
335
+ noAnswerFalseRecallRate: noAnswer === 0 ? 0 : round(noAnswerFalseRecall / noAnswer),
336
+ isolationViolations: violations.length,
337
+ denominators: {
338
+ answerable,
339
+ noAnswer,
340
+ forbiddenChecked,
341
+ },
342
+ emptySet: {
343
+ recallAt3: answerable === 0,
344
+ allExpectedAt3: answerable === 0,
345
+ mrrAt3: answerable === 0,
346
+ noAnswerFalseRecallRate: noAnswer === 0,
347
+ isolationViolations: forbiddenChecked === 0,
348
+ },
349
+ violations: violations.slice(0, 50),
350
+ }
351
+ }
352
+
353
+ function latencyStats(values) {
354
+ const sorted = values.map(Number).filter(Number.isFinite).sort((a, b) => a - b)
355
+ if (sorted.length === 0) return { backend: RUN_CONFIG.backend, samples: 0, medianMs: null, p95Ms: null, method: 'no samples' }
356
+ const mid = Math.floor(sorted.length / 2)
357
+ const median = sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2
358
+ const p95Index = Math.max(0, Math.ceil(sorted.length * 0.95) - 1)
359
+ return {
360
+ backend: RUN_CONFIG.backend,
361
+ samples: sorted.length,
362
+ medianMs: round(median, 3),
363
+ p95Ms: round(sorted[p95Index], 3),
364
+ method: 'wall-clock around automatic candidate + buildRecall per sample; single Node process; performance.now(); not service latency',
365
+ }
366
+ }
367
+
368
+ function prepareRoot(workRoot) {
369
+ const tmp = path.resolve(os.tmpdir())
370
+ let root = workRoot ? path.resolve(workRoot) : fs.mkdtempSync(path.join(tmp, 'dsh-memu-recall-bench-'))
371
+ const relative = path.relative(tmp, root)
372
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
373
+ throw new Error(`recall-bench: workRoot must be a fresh directory under os.tmpdir(): ${root}`)
374
+ }
375
+ if (fs.existsSync(root)) {
376
+ if (!fs.statSync(root).isDirectory()) throw new Error(`recall-bench: workRoot is not a directory: ${root}`)
377
+ if (fs.readdirSync(root).length > 0) throw new Error(`recall-bench: workRoot must be empty: ${root}`)
378
+ } else {
379
+ fs.mkdirSync(root, { recursive: true })
380
+ }
381
+ return root
382
+ }
383
+
384
+ function installClock(initialMs) {
385
+ const RealDate = Date
386
+ let now = Number(initialMs)
387
+ class BenchDate extends RealDate {
388
+ constructor(...args) {
389
+ super(...(args.length === 0 ? [now] : args))
390
+ }
391
+ static now() {
392
+ return now
393
+ }
394
+ }
395
+ globalThis.Date = BenchDate
396
+ return {
397
+ set(ms) { now = Number(ms) },
398
+ restore() { globalThis.Date = RealDate },
399
+ }
400
+ }
401
+
402
+ function installRandom(seed) {
403
+ const original = Math.random
404
+ let state = Number(seed) >>> 0
405
+ if (state === 0) state = 0x9e3779b9
406
+ Math.random = () => {
407
+ state |= 0
408
+ state = (state + 0x6d2b79f5) | 0
409
+ let t = Math.imul(state ^ (state >>> 15), 1 | state)
410
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
411
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
412
+ }
413
+ return { restore() { Math.random = original } }
414
+ }
415
+
416
+ function entryForSample(source, sample) {
417
+ const { id: _id, ageDays = 7, updatedDaysAgo, ...rest } = source
418
+ const nowMs = Date.parse(sample.time)
419
+ const createdMs = nowMs - Number(ageDays) * DAY_MS
420
+ const updatedMs = nowMs - Number(updatedDaysAgo ?? ageDays) * DAY_MS
421
+ return {
422
+ createdAt: new Date(createdMs).toISOString(),
423
+ updatedAt: new Date(updatedMs).toISOString(),
424
+ layer: 'long_term',
425
+ status: 'active',
426
+ visibility: 'shared',
427
+ context: {},
428
+ confidence: 0.9,
429
+ owner: 'user',
430
+ source: 'user_said',
431
+ accessCount: 0,
432
+ injectCount: 0,
433
+ tags: [],
434
+ ...rest,
435
+ }
436
+ }
437
+
438
+ function seedSample(state, sample, entries, suffix = '') {
439
+ const library = state.createLibrary({
440
+ name: `bench-${sample.id}${suffix}`,
441
+ scopeKey: path.join(os.tmpdir(), 'dsh-memu-recall-bench-identities', `${sample.id}${suffix}`),
442
+ })
443
+ const index = { version: 1, entries: {} }
444
+ for (const id of sample.library) {
445
+ const source = entries.get(id)
446
+ if (!source) throw new Error(`recall-bench: missing entry ${id}`)
447
+ index.entries[id] = entryForSample(source, sample)
448
+ }
449
+ state.savePrivateIndex(library.id, index)
450
+ const sessionId = `bench-session-${sample.id}${suffix}`
451
+ state.setSessionBinding(sessionId, {
452
+ libraryId: library.id,
453
+ scopeKey: library.scopeKey,
454
+ useLibrary: true,
455
+ useGlobal: false,
456
+ memoryContext: { ...sample.context },
457
+ memoryOwnerSessionId: sessionId,
458
+ domain: sample.subclass === 'coding' ? 'coding' : 'rp',
459
+ domainOverride: sample.subclass === 'coding' ? 'coding' : 'rp',
460
+ injectedAt: {},
461
+ injectedIds: [],
462
+ recentQueries: [],
463
+ lastInjectedTurn: 0,
464
+ })
465
+ state.flushState()
466
+ return { library, sessionId }
467
+ }
468
+
469
+ function execFor(sessionId, root) {
470
+ return {
471
+ agent: {
472
+ session: {
473
+ header: {
474
+ id: sessionId,
475
+ cwd: path.join(root, 'cwd'),
476
+ agentPreset: 'rp',
477
+ },
478
+ },
479
+ },
480
+ }
481
+ }
482
+
483
+ function gitCommit() {
484
+ try {
485
+ return execFileSync('git', ['rev-parse', '--short', 'HEAD'], {
486
+ cwd: ROOT,
487
+ encoding: 'utf8',
488
+ stdio: ['ignore', 'pipe', 'ignore'],
489
+ timeout: 3000,
490
+ }).trim() || null
491
+ } catch {
492
+ return null
493
+ }
494
+ }
495
+
496
+ function packageVersion() {
497
+ try {
498
+ return JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version || null
499
+ } catch {
500
+ return null
501
+ }
502
+ }
503
+
504
+ function buildProjection(records, key, expectedKey, forbiddenKey, { noAnswerEligible = true } = {}) {
505
+ const projected = records.map(record => ({
506
+ id: record.id,
507
+ subclass: record.subclass,
508
+ noAnswer: noAnswerEligible ? record.noAnswer : false,
509
+ expectedIds: record[expectedKey] || [],
510
+ forbiddenIds: record[forbiddenKey] || [],
511
+ top3: top3Of(record[key]),
512
+ }))
513
+ return computeMetrics(projected)
514
+ }
515
+
516
+ function bySubclass(records) {
517
+ const result = {}
518
+ for (const subclass of SUBCLASSES) {
519
+ const subset = records.filter(record => record.subclass === subclass)
520
+ if (subset.length === 0) continue
521
+ const candidate = buildProjection(subset, 'candidateTop3', 'expectedIds', 'forbiddenIds')
522
+ const finalInjected = buildProjection(subset, 'injectedTop3', 'expectedIds', 'forbiddenIds')
523
+ result[subclass] = {
524
+ samples: subset.length,
525
+ candidateRecallAt3: candidate.recallAt3,
526
+ candidateMrrAt3: candidate.mrrAt3,
527
+ candidateNoAnswerFalseRecallRate: candidate.noAnswerFalseRecallRate,
528
+ candidateIsolationViolations: candidate.isolationViolations,
529
+ finalInjectedRecallAt3: finalInjected.recallAt3,
530
+ finalInjectedMrrAt3: finalInjected.mrrAt3,
531
+ finalInjectedNoAnswerFalseRecallRate: finalInjected.noAnswerFalseRecallRate,
532
+ finalInjectedIsolationViolations: finalInjected.isolationViolations,
533
+ denominators: finalInjected.denominators,
534
+ }
535
+ }
536
+ return result
537
+ }
538
+
539
+ function sumEstimate(records) {
540
+ return records.reduce((total, record) => total + Number(record.injectedTokenEstimate || 0), 0)
541
+ }
542
+
543
+ /**
544
+ * Run the benchmark. All state lives under a fresh os.tmpdir() root. The env
545
+ * overrides are restored in finally, and the root is removed after the report is
546
+ * built unless the caller supplied workRoot or --keep for inspection.
547
+ */
548
+ export async function runBenchmark(options = {}) {
549
+ const fixtureDir = path.resolve(options.fixtureDir || FIXTURE_DIR)
550
+ const dataset = loadDataset(fixtureDir)
551
+ const sampleLimit = options.sampleLimit === undefined ? dataset.samples.length : Number(options.sampleLimit)
552
+ if (!Number.isInteger(sampleLimit) || sampleLimit < 1 || sampleLimit > dataset.samples.length) {
553
+ throw new Error(`recall-bench: sampleLimit must be 1..${dataset.samples.length}`)
554
+ }
555
+ const samples = dataset.samples.slice(0, sampleLimit)
556
+ const root = prepareRoot(options.workRoot)
557
+ const seed = Number.isInteger(options.seed) ? options.seed : RUN_CONFIG.seed
558
+ const startedAt = new Date().toISOString()
559
+ const clock = installClock(Date.parse(samples[0].time))
560
+ const random = installRandom(seed)
561
+ const previousHome = process.env.DSH_MEMU_HOME
562
+ const previousMemoryHome = process.env.DSH_MEMU_MEMORY_HOME
563
+ let state = null
564
+ const records = []
565
+
566
+ try {
567
+ process.env.DSH_MEMU_HOME = path.join(root, 'dsh-memu-home')
568
+ process.env.DSH_MEMU_MEMORY_HOME = path.join(root, 'dsh-memu-data')
569
+ fs.mkdirSync(process.env.DSH_MEMU_HOME, { recursive: true })
570
+ fs.mkdirSync(process.env.DSH_MEMU_MEMORY_HOME, { recursive: true })
571
+
572
+ state = await import(pathToFileURL(path.join(ROOT, 'lib', 'state.js')).href)
573
+ const memory = await import(pathToFileURL(path.join(ROOT, 'lib', 'memory.js')).href)
574
+ const inject = await import(pathToFileURL(path.join(ROOT, 'lib', 'inject.js')).href)
575
+ const budget = await import(pathToFileURL(path.join(ROOT, 'lib', 'budget.js')).href)
576
+
577
+ for (const sample of samples) {
578
+ const sampleNow = Date.parse(sample.time)
579
+ clock.set(sampleNow)
580
+ const automatic = seedSample(state, sample, dataset.entries, '')
581
+ const autoExec = execFor(automatic.sessionId, root)
582
+ const settings = {
583
+ ...state.getSettings(),
584
+ privateTopK: RUN_CONFIG.privateTopK,
585
+ turnTokens: RUN_CONFIG.turnTokens,
586
+ relevanceThreshold: RUN_CONFIG.relevanceThreshold,
587
+ dedupeTurns: RUN_CONFIG.dedupeTurns,
588
+ autoInject: 'smart',
589
+ globalEveryNTurns: 0,
590
+ }
591
+
592
+ const started = performance.now()
593
+ const candidate = await memory.privateRecall({
594
+ exec: autoExec,
595
+ query: sample.query,
596
+ topK: RUN_CONFIG.candidateTopK,
597
+ relevanceThreshold: RUN_CONFIG.relevanceThreshold,
598
+ purpose: 'automatic',
599
+ })
600
+ const candidateIds = (candidate.files || []).map(file => file.name)
601
+ const binding = state.getSessionBinding(automatic.sessionId)
602
+ if (!binding) throw new Error(`recall-bench: session binding disappeared for ${sample.id}`)
603
+ const injected = await inject.buildRecall(binding, sample.query, 1, settings, autoExec, automatic.sessionId)
604
+ const latencyMs = performance.now() - started
605
+
606
+ const injectedIds = Array.isArray(injected.ids) ? injected.ids.slice() : []
607
+ const injectedText = String(injected.text || '')
608
+ const injectedTokenEstimate = budget.estTokens(injectedText)
609
+
610
+ let explicitIds = []
611
+ if (Array.isArray(sample.explicitExpectedIds) && sample.explicitExpectedIds.length > 0) {
612
+ const explicit = seedSample(state, sample, dataset.entries, '-explicit')
613
+ const explicitExec = execFor(explicit.sessionId, root)
614
+ const explicitResult = await memory.privateRecall({
615
+ exec: explicitExec,
616
+ query: sample.query,
617
+ topK: RUN_CONFIG.candidateTopK,
618
+ relevanceThreshold: RUN_CONFIG.relevanceThreshold,
619
+ purpose: 'explicit',
620
+ })
621
+ explicitIds = (explicitResult.files || []).map(file => file.name)
622
+ }
623
+
624
+ records.push({
625
+ id: sample.id,
626
+ subclass: sample.subclass,
627
+ draft: true,
628
+ notGold: true,
629
+ noAnswer: sample.noAnswer,
630
+ query: sample.query,
631
+ context: { ...sample.context },
632
+ time: sample.time,
633
+ expectedIds: sample.expectedIds.slice(),
634
+ forbiddenIds: sample.forbiddenIds.slice(),
635
+ library: sample.library.slice(),
636
+ candidateIds,
637
+ candidateRoute: candidate.recallRoute || null,
638
+ candidateErrors: Array.isArray(candidate.errors) ? candidate.errors.slice() : [],
639
+ candidateFusion: candidate.fusion || null,
640
+ candidateTop3: top3Of(candidateIds),
641
+ candidateCount: candidateIds.length,
642
+ injectedIds,
643
+ injectedTop3: top3Of(injectedIds),
644
+ injectedOutcome: injected.outcome || null,
645
+ injectedErrors: Array.isArray(injected.errors) ? injected.errors.slice() : [],
646
+ injectedTextChars: injectedText.length,
647
+ injectedTokenEstimate,
648
+ explicitIds,
649
+ explicitTop3: top3Of(explicitIds),
650
+ latencyMs: round(latencyMs, 3),
651
+ })
652
+ }
653
+ state.flushState()
654
+
655
+ const candidateMetrics = buildProjection(records, 'candidateTop3', 'expectedIds', 'forbiddenIds')
656
+ const injectedMetrics = buildProjection(records, 'injectedTop3', 'expectedIds', 'forbiddenIds')
657
+ const explicitRecords = records.filter(record => {
658
+ const sample = samples.find(item => item.id === record.id)
659
+ return Array.isArray(sample?.explicitExpectedIds) && sample.explicitExpectedIds.length > 0
660
+ })
661
+ const explicitMetrics = buildProjection(
662
+ explicitRecords.map(record => {
663
+ const sample = samples.find(item => item.id === record.id)
664
+ return {
665
+ ...record,
666
+ explicitExpectedIds: sample.explicitExpectedIds,
667
+ explicitForbiddenIds: sample.explicitForbiddenIds || [],
668
+ }
669
+ }),
670
+ 'explicitTop3',
671
+ 'explicitExpectedIds',
672
+ 'explicitForbiddenIds',
673
+ { noAnswerEligible: false },
674
+ )
675
+ const candidateViolations = candidateMetrics.violations.map(item => ({ ...item, projection: 'candidate' }))
676
+ const injectedViolations = injectedMetrics.violations.map(item => ({ ...item, projection: 'final-injected' }))
677
+ const explicitViolations = explicitMetrics.violations.map(item => ({ ...item, projection: 'explicit-probe' }))
678
+ const injectedTotalEstimate = sumEstimate(records)
679
+ const sampleCount = records.length
680
+
681
+ return {
682
+ schemaVersion: RUN_CONFIG.schemaVersion,
683
+ kind: 'recall-bench',
684
+ ok: true,
685
+ status: dataset.status,
686
+ gold: false,
687
+ review: dataset.review,
688
+ dataset: {
689
+ name: dataset.name,
690
+ status: dataset.status,
691
+ draft: true,
692
+ notGold: true,
693
+ gold: false,
694
+ review: dataset.review,
695
+ sampleCount,
696
+ fileCount: dataset.files.length,
697
+ sha256: dataset.sha256,
698
+ files: dataset.files,
699
+ },
700
+ code: {
701
+ commit: gitCommit(),
702
+ packageVersion: packageVersion(),
703
+ worktree: 'dirty-or-uncommitted (recorded from current workspace; not a commit)',
704
+ },
705
+ run: {
706
+ startedAt,
707
+ root,
708
+ clock: 'fixed per sample (Date.now overridden from sample.time)',
709
+ randomSeed: seed,
710
+ random: 'seeded mulberry32',
711
+ sampleLimit,
712
+ },
713
+ config: {
714
+ backend: RUN_CONFIG.backend,
715
+ candidateTopK: RUN_CONFIG.candidateTopK,
716
+ privateTopK: RUN_CONFIG.privateTopK,
717
+ turnTokens: RUN_CONFIG.turnTokens,
718
+ relevanceThreshold: RUN_CONFIG.relevanceThreshold,
719
+ dedupeTurns: RUN_CONFIG.dedupeTurns,
720
+ mockVectors: 'pipeline-only',
721
+ vectorPath: 'none (local lexical only)',
722
+ note: 'local lexical only; any mock/lexical vector path validates pipeline plumbing, not embedding quality',
723
+ },
724
+ metrics: {
725
+ candidate: candidateMetrics,
726
+ finalInjected: injectedMetrics,
727
+ explicitProbe: explicitMetrics,
728
+ isolation: {
729
+ violations: candidateViolations.length + injectedViolations.length + explicitViolations.length,
730
+ mustBeZero: true,
731
+ candidate: candidateMetrics.isolationViolations,
732
+ finalInjected: injectedMetrics.isolationViolations,
733
+ explicitProbe: explicitMetrics.isolationViolations,
734
+ forbiddenDenominator: candidateMetrics.denominators.forbiddenChecked
735
+ + injectedMetrics.denominators.forbiddenChecked
736
+ + explicitMetrics.denominators.forbiddenChecked,
737
+ details: [...candidateViolations, ...injectedViolations, ...explicitViolations].slice(0, 100),
738
+ },
739
+ latency: latencyStats(records.map(record => record.latencyMs)),
740
+ bySubclass: bySubclass(records),
741
+ },
742
+ budget: {
743
+ estimateOnly: true,
744
+ field: 'estimate',
745
+ estimate: {
746
+ injectedTokenTotal: round(injectedTotalEstimate, 3),
747
+ injectedTokenMeanPerSample: sampleCount === 0 ? 0 : round(injectedTotalEstimate / sampleCount, 3),
748
+ turnTokens: RUN_CONFIG.turnTokens,
749
+ method: 'lib/budget.js estTokens; CJK ~1 token/char, Latin ~3.4 chars/token',
750
+ },
751
+ method: 'lib/budget.js estTokens; CJK ~1 token/char, Latin ~3.4 chars/token',
752
+ turnTokens: RUN_CONFIG.turnTokens,
753
+ injectedTokenEstimateTotal: round(injectedTotalEstimate, 3),
754
+ injectedTokenEstimateMean: sampleCount === 0 ? 0 : round(injectedTotalEstimate / sampleCount, 3),
755
+ note: 'Token estimates only. These are not actual token usage and must not be reported as consumed tokens.',
756
+ },
757
+ samples: records,
758
+ }
759
+ } finally {
760
+ try {
761
+ state?.flushState()
762
+ } catch {}
763
+ clock.restore()
764
+ random.restore()
765
+ if (previousHome === undefined) delete process.env.DSH_MEMU_HOME
766
+ else process.env.DSH_MEMU_HOME = previousHome
767
+ if (previousMemoryHome === undefined) delete process.env.DSH_MEMU_MEMORY_HOME
768
+ else process.env.DSH_MEMU_MEMORY_HOME = previousMemoryHome
769
+ if (!options.workRoot && !options.keep) {
770
+ try { fs.rmSync(root, { recursive: true, force: true }) } catch {}
771
+ }
772
+ }
773
+ }
774
+
775
+ export function parseArgs(argv) {
776
+ const options = {}
777
+ for (let index = 0; index < argv.length; index += 1) {
778
+ const arg = argv[index]
779
+ if (arg === '--out') options.out = argv[++index]
780
+ else if (arg === '--fixture-dir') {
781
+ const fixtureDir = argv[++index]
782
+ if (!fixtureDir || fixtureDir.startsWith('--')) throw new Error('recall-bench: --fixture-dir requires a directory')
783
+ options.fixtureDir = fixtureDir
784
+ }
785
+ else if (arg === '--work-root') options.workRoot = argv[++index]
786
+ else if (arg === '--seed') options.seed = Number(argv[++index])
787
+ else if (arg === '--samples') options.sampleLimit = Number(argv[++index])
788
+ else if (arg === '--keep') options.keep = true
789
+ else if (arg === '--help' || arg === '-h') options.help = true
790
+ else throw new Error(`recall-bench: unknown argument ${arg}`)
791
+ }
792
+ return options
793
+ }
794
+
795
+ async function main() {
796
+ const options = parseArgs(process.argv.slice(2))
797
+ if (options.help) {
798
+ console.log('Usage: node scripts/recall-bench.mjs [--fixture-dir DIR] [--out report.json] [--work-root DIR] [--seed N] [--samples N] [--keep]')
799
+ console.log(' --fixture-dir DIR fixture directory; default tests/fixtures/recall-bench; candidate package tests/fixtures/recall-bench-gold-candidates')
800
+ console.log(' --samples N run the first N samples, 1..dataset size; default all samples')
801
+ return
802
+ }
803
+ const report = await runBenchmark(options)
804
+ const json = JSON.stringify(report, null, 2)
805
+ if (options.out) {
806
+ fs.mkdirSync(path.dirname(path.resolve(options.out)), { recursive: true })
807
+ fs.writeFileSync(path.resolve(options.out), json.replace(/\r?\n/g, '\r\n'), 'utf8')
808
+ console.log(`recall-bench: wrote ${path.resolve(options.out)}`)
809
+ } else {
810
+ console.log(json)
811
+ }
812
+ }
813
+
814
+ const invoked = process.argv[1] ? pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url : false
815
+ if (invoked) {
816
+ main().catch(error => {
817
+ console.error(JSON.stringify({ ok: false, kind: 'recall-bench', error: error?.message || String(error) }, null, 2))
818
+ process.exitCode = 1
819
+ })
820
+ }