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,1234 +1,1234 @@
1
- import test from 'node:test'
2
- import assert from 'node:assert/strict'
3
- import fs from 'node:fs'
4
- import os from 'node:os'
5
- import path from 'node:path'
6
- import { registerHooks } from 'node:module'
7
-
8
- // No engine, worker, download or real library is used: all stores live here and
9
- // the engine boundary is replaced before either production module is imported.
10
- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-managed-memory-'))
11
- process.env.DSH_MEMU_HOME = home
12
- process.env.DSH_MEMU_MEMORY_HOME = home
13
- const calls = []
14
- const warnings = []
15
- const rebuildProbes = []
16
- const backendRows = new Map()
17
- const backendKey = (db, name) => JSON.stringify([db, name])
18
- let commitHook = null
19
- let retrieveHook = null
20
- let failCommit = false
21
- let failForget = false
22
- let forgetHook = null
23
- let vp
24
-
25
- globalThis.__managedMemoryTest = {
26
- async commit(args) {
27
- calls.push({ op: 'commit', ...args })
28
- // The lease invariant only exists while there is a generation to protect. A
29
- // requested-but-never-migrated profile writes without vectors on purpose.
30
- if (args.route === 'managed-local' && vp.hasActiveVectorGeneration()) {
31
- assert.ok(Object.keys(vp.activeVectorState().writeGuard.leases).length, 'lease spans MemU await')
32
- }
33
- if (commitHook) await commitHook(args)
34
- if (failCommit) throw new Error('mock managed commit failed')
35
- for (const row of args.payload.recall_files) backendRows.set(backendKey(args.db, row.name), structuredClone(row))
36
- return { ok: true }
37
- },
38
- async retrieve(args) {
39
- calls.push({ op: 'retrieve', ...args })
40
- return retrieveHook ? retrieveHook(args) : { files: [], segments: [], resources: [], raw: null }
41
- },
42
- async forget(args) {
43
- calls.push({ op: 'forget', ...args })
44
- if (args.route === 'managed-local' && vp.hasActiveVectorGeneration()) assert.ok(Object.keys(vp.activeVectorState().writeGuard.leases).length)
45
- if (forgetHook) return forgetHook(args)
46
- if (failForget) throw new Error('mock managed forget failed')
47
- backendRows.delete(backendKey(args.db, args.name))
48
- return { deleted: 1, segments: 1 }
49
- },
50
- async listFiles() { throw new Error('unexpected list engine call') },
51
- async maybeAutoRebuildVectorGeneration(...args) {
52
- rebuildProbes.push(args)
53
- return { stubbed: true }
54
- },
55
- }
56
- const vectorServiceUrl = 'data:text/javascript,' + encodeURIComponent('export const maybeAutoRebuildVectorGeneration = globalThis.__managedMemoryTest.maybeAutoRebuildVectorGeneration;')
57
- const engineSource = 'const bridge = globalThis.__managedMemoryTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles, closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
58
- const hooks = registerHooks({
59
- resolve(specifier, context, nextResolve) {
60
- if (specifier === './memu.js') {
61
- return { url: 'data:text/javascript,' + encodeURIComponent(engineSource), shortCircuit: true }
62
- }
63
- // managedRecall 的缺库分支会动态 import 向量服务做自动追平探测。这里只拦截
64
- // memory.js 发起的那一次(父 URL 限定),别的模块照常拿真实现——否则空转的
65
- // force 重建会把嵌入 worker 拉进单元测试。
66
- if (specifier === './local-vector-service.js' && context.parentURL === new URL('../lib/memory.js', import.meta.url).href) {
67
- return { url: vectorServiceUrl, shortCircuit: true }
68
- }
69
- return nextResolve(specifier, context)
70
- },
71
- })
72
- const state = await import('../lib/state.js')
73
- vp = await import('../lib/vector-profile.js')
74
- const paths = await import('../lib/paths.js')
75
- const memory = await import('../lib/memory.js')
76
- const curator = await import('../lib/curator.js')
77
- const activity = await import('../lib/activity-log.js')
78
- const { buildCorpus, bm25, tokenize } = await import('../lib/text-retrieval.js')
79
- const profile = vp.profileFromCatalog('bge-small-zh-v1.5-int8')
80
- const activeFile = vp.vectorActiveFile()
81
- let serial = 0
82
-
83
- function entry(content, extra = {}) {
84
- return { status: 'active', title: content, content, layer: 'long_term', strength: 1,
85
- createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ...extra }
86
- }
87
- function fixture(entries = {}) {
88
- serial += 1
89
- const sessionId = 'managed-' + serial
90
- const cwd = path.join(home, 'project-' + serial)
91
- const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
92
- state.setSessionBinding(sessionId, { useLibrary: true, useGlobal: true, domainOverride: 'coding' })
93
- state.savePrivateIndex(binding.libraryId, { entries })
94
- return { sessionId, libraryId: binding.libraryId, exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } } }
95
- }
96
- function activate(libraryIds = []) {
97
- const databases = vp.buildDatabaseSet({ profile, generation: 1, libraryIds })
98
- fs.mkdirSync(path.join(home, 'libraries'), { recursive: true })
99
- for (const row of [databases.global, ...Object.values(databases.libraries)]) fs.writeFileSync(vp.resolveVectorPath(row.path), '')
100
- vp.updateVectorStateSync(current => ({ ...current, generation: 1, requested: null, pending: null,
101
- active: { status: 'active', generation: 1, fingerprint: profile.fingerprint, profile, databases } }))
102
- return databases
103
- }
104
- function job() { return { step: '', abort: new AbortController() } }
105
- function curated(extra = {}) {
106
- return { op: 'create', domain: 'coding', title: 'global decision', content: 'global implementation decision',
107
- evidence: [{ session_id: 'source-session', quote: 'explicit decision' }], ...extra }
108
- }
109
-
110
- test.beforeEach(() => {
111
- fs.rmSync(activeFile, { force: true })
112
- state.updateSettings({ memoryBackend: 'api', vectorSource: 'local', relevanceThreshold: 0, crossLibraryRecall: false })
113
- state.saveGlobalIndex({ entries: {} })
114
- calls.length = 0
115
- warnings.length = 0
116
- rebuildProbes.length = 0
117
- commitHook = null
118
- retrieveHook = null
119
- failCommit = false
120
- failForget = false
121
- forgetHook = null
122
- backendRows.clear()
123
- paths.setWarnSink(message => warnings.push(String(message)))
124
- })
125
- test.after(() => {
126
- hooks.deregister()
127
- delete globalThis.__managedMemoryTest
128
- paths.setWarnSink(null)
129
- fs.rmSync(home, { recursive: true, force: true })
130
- })
131
-
132
- test('fresh defaults disable all vector routes while retaining local as the selected source', () => {
133
- assert.equal(state.DEFAULT_SETTINGS.memoryBackend, 'agent')
134
- assert.equal(state.DEFAULT_SETTINGS.vectorSource, 'local')
135
- // 2026-10-30:用户要求召回默认 5/5(原来是 3/2)。
136
- assert.equal(state.DEFAULT_SETTINGS.privateTopK, 5)
137
- assert.equal(state.DEFAULT_SETTINGS.globalTopK, 5)
138
- assert.equal(state.effectiveVectorRoute(state.DEFAULT_SETTINGS), 'lexical')
139
- assert.equal(state.vectorBackendEnabled(state.DEFAULT_SETTINGS), false)
140
- })
141
-
142
- test('managed local private recall fuses real lexical and vector ids without LLM', async () => {
143
- const f = fixture({ 'mem-needle': entry('needle local match'), 'mem-orbit': entry('orbital mechanics') })
144
- activate([f.libraryId])
145
- retrieveHook = () => ({ files: [{ name: 'mem-orbit' }], segments: [], resources: [] })
146
- const result = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8 })
147
- assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-needle', 'mem-orbit']))
148
- assert.equal(result.recallRoute, 'managed-vector-rrf')
149
- assert.equal(calls[0].db, vp.dbPathFor(f.libraryId))
150
- })
151
-
152
- test('corrupt managed intent cannot call LLM or legacy API and preserves lexical ids', async () => {
153
- const f = fixture({ 'mem-needle': entry('needle local match') })
154
- state.updateSettings({ memoryBackend: 'api' })
155
- fs.writeFileSync(activeFile, '{bad-json')
156
- const result = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8 })
157
- assert.deepEqual(result.files.map(file => file.name), ['mem-needle'])
158
- assert.equal(result.recallRoute, 'local-fallback')
159
- assert.match(state.getSessionBinding(f.sessionId).lastRecallError, /not valid JSON/)
160
- assert.ok(warnings.length)
161
- assert.equal(calls.length, 0)
162
- })
163
-
164
- // 2026-11-18:跨库召回扫到没有向量库的库时,缺库降级的诊断只该属于「有内容」的库。
165
- // 空库(旧工作区遗留,索引 0 条)local-only 与语义召回的结果都是空——每轮给它刷
166
- // "向量库未生成" warn 是常驻噪音(group_893418498 空库实测刷满活动日志)。
167
- function vectorDegradeRows(libraryId) {
168
- return activity.listEvents({ kind: 'vector', limit: 100 })
169
- .filter(row => row.message === '向量库未生成,召回降级 local-only' && row.detail?.libraryId === libraryId)
170
- }
171
-
172
- async function settleRebuildProbes() {
173
- // Join the same data-module import and drain its fire-and-forget .then callback.
174
- // Importing the bridge itself does not call the probe or start a real worker.
175
- await import(vectorServiceUrl)
176
- await new Promise(resolve => setImmediate(resolve))
177
- }
178
-
179
- function trackIndexAccess(t, files) {
180
- const access = { clones: 0, stats: new Map(files.map(file => [file, 0])) }
181
- const clone = globalThis.structuredClone
182
- t.mock.method(globalThis, 'structuredClone', (value, ...args) => {
183
- if (value?.entries && !Array.isArray(value.entries)) access.clones += 1
184
- return clone(value, ...args)
185
- })
186
- const stat = fs.statSync
187
- t.mock.method(fs, 'statSync', (file, ...args) => {
188
- if (access.stats.has(file)) access.stats.set(file, access.stats.get(file) + 1)
189
- return stat(file, ...args)
190
- })
191
- return access
192
- }
193
-
194
- test('an empty library without a vector db recalls silently — no degrade noise, no rebuild probe', async () => {
195
- state.updateSettings({ memoryBackend: 'api', vectorSource: 'local' })
196
- const empty = fixture({})
197
- activate([]) // 活跃代际只含全局库:该库的向量库必然缺席
198
- const result = await memory.privateRecall({ exec: empty.exec, query: 'anything', topK: 5 })
199
- await settleRebuildProbes()
200
- assert.equal(result.recallRoute, 'local-fallback')
201
- assert.deepEqual(result.files, [], 'an empty library has nothing to recall')
202
- assert.deepEqual(result.errors || [], [])
203
- assert.deepEqual(warnings, [], 'an empty library must not warn')
204
- assert.equal(vectorDegradeRows(empty.libraryId).length, 0, 'an empty library must not log the degrade warning')
205
- assert.equal(rebuildProbes.length, 0, 'an empty library must not probe a rebuild')
206
- assert.equal(calls.length, 0)
207
- })
208
-
209
- test('a library with content but no vector db keeps the degrade diagnostic and probes the rebuild', async () => {
210
- state.updateSettings({ memoryBackend: 'api', vectorSource: 'local' })
211
- const rich = fixture({ 'mem-rich': entry('needle real content that semantic recall would serve') })
212
- activate([]) // 同上:库不在代际里,但索引里有内容——这是真正值得诊断的缺库
213
- const result = await memory.privateRecall({ exec: rich.exec, query: 'needle', topK: 5 })
214
- await settleRebuildProbes()
215
- assert.equal(result.recallRoute, 'local-fallback')
216
- assert.deepEqual(result.files.map(file => file.name), ['mem-rich'])
217
- assert.deepEqual(result.errors || [], [], 'missing registration is diagnostic, not a recall error')
218
- assert.equal(warnings.length, 1)
219
- assert.ok(warnings[0].includes('has no database for library ' + rich.libraryId))
220
- assert.equal(vectorDegradeRows(rich.libraryId).length, 1, 'content-bearing libraries keep the diagnostic')
221
- assert.equal(rebuildProbes.length, 1, 'content-bearing libraries probe the rebuild')
222
- assert.equal(calls.length, 0)
223
- })
224
-
225
- test('an empty library resumes missing-db diagnostics after its first index entry is saved', async () => {
226
- const f = fixture()
227
- activate([])
228
- const empty = await memory.privateRecall({ exec: f.exec, query: 'needle', purpose: 'automatic' })
229
- await settleRebuildProbes()
230
- assert.deepEqual(empty.files, [])
231
- assert.deepEqual(warnings, [])
232
- assert.equal(vectorDegradeRows(f.libraryId).length, 0)
233
- assert.equal(rebuildProbes.length, 0)
234
-
235
- // A backfill must invalidate emptiness immediately; no new cache or enrollment.
236
- state.savePrivateIndex(f.libraryId, { entries: { 'mem-first': entry('needle first backfilled fact') } })
237
- const filled = await memory.privateRecall({ exec: f.exec, query: 'needle', purpose: 'automatic' })
238
- await settleRebuildProbes()
239
- assert.deepEqual(filled.files.map(file => file.name), ['mem-first'])
240
- assert.equal(filled.recallRoute, 'local-fallback')
241
- assert.equal(warnings.length, 1)
242
- assert.ok(warnings[0].includes('has no database for library ' + f.libraryId))
243
- assert.equal(vectorDegradeRows(f.libraryId).length, 1)
244
- assert.equal(rebuildProbes.length, 1)
245
- assert.equal(calls.length, 0)
246
- })
247
-
248
- test('missing-db recall reuses loaded indexes on repeated warm-cache calls', async t => {
249
- const f = fixture({ 'mem-budget': entry('needle snapshot budget') })
250
- activate([])
251
- state.loadPrivateIndex(f.libraryId) // Warm the state index cache before spying.
252
- const indexFile = path.join(paths.indexDir(), f.libraryId + '.json')
253
- const access = trackIndexAccess(t, [indexFile])
254
- for (let round = 1; round <= 2; round += 1) {
255
- const result = await memory.privateRecall({ exec: f.exec, query: 'needle', purpose: 'automatic' })
256
- await settleRebuildProbes()
257
- assert.deepEqual(result.files.map(file => file.name), ['mem-budget'])
258
- // Two source snapshots clone twice each; the one hit also checks the existing
259
- // relation-inverted-index signature (stat only, no snapshot).
260
- assert.equal(access.stats.get(indexFile), 3 * round, 'two index reads plus one relation signature stat')
261
- assert.equal(access.clones, 4 * round, 'no extra full-index clones, regardless of corpus size')
262
- assert.equal(rebuildProbes.length, round, 'the fallback remains uncached and diagnostic')
263
- }
264
- })
265
-
266
- test('cross-library missing-db diagnostics use the full source before domain filtering without extra snapshots', async t => {
267
- const current = fixture({ 'mem-current': entry('needle current fact') })
268
- const foreign = fixture({ 'mem-other-domain': entry('needle other world', { domain: 'rp' }) })
269
- const empty = fixture()
270
- const domain = 'project:' + current.sessionId
271
- for (const f of [current, foreign, empty]) state.setSessionBinding(f.sessionId, { domainOverride: domain })
272
- state.updateSettings({ crossLibraryRecall: true })
273
- activate([])
274
- const indexFiles = [current, foreign, empty].map(f => path.join(paths.indexDir(), f.libraryId + '.json'))
275
- const access = trackIndexAccess(t, indexFiles)
276
- const result = await memory.privateRecall({ exec: current.exec, query: 'needle', purpose: 'automatic' })
277
- await settleRebuildProbes()
278
- assert.equal(result.recallRoute, 'cross-library')
279
- assert.deepEqual(new Set(result.libraries), new Set([current.libraryId, foreign.libraryId, empty.libraryId]))
280
- assert.deepEqual(result.files.map(file => file.name), ['mem-current'], 'the foreign domain contributes no hits')
281
- assert.deepEqual(result.errors, [])
282
- assert.equal(warnings.length, 2, 'only the two content-bearing libraries warn')
283
- for (const f of [current, foreign]) {
284
- assert.ok(warnings.some(message => message.includes('has no database for library ' + f.libraryId)))
285
- assert.equal(vectorDegradeRows(f.libraryId).length, 1)
286
- }
287
- assert.equal(vectorDegradeRows(empty.libraryId).length, 0)
288
- assert.equal(rebuildProbes.length, 2, 'a domain-filtered empty view still needs a rebuild probe')
289
- assert.equal(calls.length, 0)
290
- assert.deepEqual(indexFiles.map(file => access.stats.get(file)), [3, 1, 1], 'only the primary hit adds a relation signature stat')
291
- assert.equal(access.clones, 8, 'three source loads plus the existing primary refresh only')
292
- })
293
-
294
- test('by-id private recall still short-circuits vector IO and missing-db diagnostics', async t => {
295
- const f = fixture({ 'mem-byid': entry('needle direct lookup') })
296
- const databases = activate([])
297
- const globalDb = vp.resolveVectorPath(databases.global.path)
298
- fs.rmSync(globalDb)
299
- const indexFile = path.join(paths.indexDir(), f.libraryId + '.json')
300
- const access = trackIndexAccess(t, [indexFile, globalDb])
301
- const read = t.mock.method(fs, 'readFileSync')
302
- const result = await memory.privateRecall({ exec: f.exec, query: 'mem-byid', purpose: 'automatic' })
303
- await settleRebuildProbes()
304
- assert.deepEqual(result.files.map(file => file.name), ['mem-byid'])
305
- assert.equal(result.recallRoute, 'local')
306
- assert.deepEqual(warnings, [])
307
- assert.equal(vectorDegradeRows(f.libraryId).length, 0)
308
- assert.equal(rebuildProbes.length, 0)
309
- assert.equal(calls.length, 0)
310
- assert.equal(read.mock.calls.some(call => call.arguments[0] === activeFile), false, 'by-id does not read vector state')
311
- assert.equal(access.stats.get(globalDb), 0, 'by-id does not validate vector databases')
312
- assert.equal(access.stats.get(indexFile), 3, 'two index reads plus the existing relation signature stat')
313
- assert.equal(access.clones, 4)
314
- })
315
-
316
- test('global recall uses the null library route even for an empty index and adds no index snapshots', async t => {
317
- const f = fixture({ 'mem-private': entry('needle private-only fact') })
318
- activate([f.libraryId])
319
- const globalDb = vp.dbPathFor(null)
320
- const empty = await memory.globalRecall({ exec: f.exec, query: 'needle' })
321
- assert.deepEqual(empty.files, [])
322
- assert.equal(empty.recallRoute, 'managed-vector-rrf')
323
- assert.equal(calls.length, 1, 'an empty index must not suppress an existing vector route')
324
- assert.equal(calls[0].db, globalDb)
325
-
326
- state.saveGlobalIndex({ entries: {
327
- 'gmem-needle': entry('needle global fact', { domain: 'coding' }),
328
- 'gmem-other': entry('needle other world', { domain: 'rp' }),
329
- } })
330
- const indexFile = path.join(paths.indexDir(), 'global.json')
331
- const access = trackIndexAccess(t, [indexFile])
332
- const result = await memory.globalRecall({ exec: f.exec, query: 'needle' })
333
- await settleRebuildProbes()
334
- assert.deepEqual(result.files.map(file => file.name), ['gmem-needle'])
335
- assert.equal(result.recallRoute, 'managed-vector-rrf')
336
- assert.equal(calls.length, 2)
337
- assert.equal(calls[1].db, globalDb, 'libraryId=null must select global, not private')
338
- assert.equal(calls[1].route, 'managed-local')
339
- assert.deepEqual(warnings, [])
340
- assert.equal(vectorDegradeRows(null).length, 0)
341
- assert.equal(rebuildProbes.length, 0)
342
- assert.equal(access.stats.get(indexFile), 2)
343
- assert.equal(access.clones, 4)
344
- })
345
-
346
- for (const content of ['empty', 'other-domain', 'matching']) {
347
- test(`a physically missing global database remains an error with ${content} content`, async () => {
348
- const f = fixture()
349
- const databases = activate([])
350
- if (content !== 'empty') state.saveGlobalIndex({ entries: {
351
- 'gmem-needle': entry('needle global fact', { domain: content === 'matching' ? 'coding' : 'rp' }),
352
- } })
353
- const globalDb = vp.resolveVectorPath(databases.global.path)
354
- fs.rmSync(globalDb)
355
- const result = await memory.globalRecall({ exec: f.exec, query: 'needle' })
356
- await settleRebuildProbes()
357
- assert.deepEqual(result.files.map(file => file.name), content === 'matching' ? ['gmem-needle'] : [])
358
- assert.equal(result.recallRoute, 'local-fallback')
359
- assert.equal(result.errors.length, 1)
360
- assert.match(result.errors[0], /a database in the active generation is missing/)
361
- assert.match(state.getSessionBinding(f.sessionId).lastRecallError, /a database in the active generation is missing/)
362
- assert.equal(warnings.length, 1)
363
- assert.ok(warnings[0].includes(path.basename(globalDb)))
364
- assert.equal(vectorDegradeRows(null).length, 0, 'torn state is not ordinary missing registration')
365
- assert.equal(rebuildProbes.length, 0)
366
- assert.equal(calls.length, 0)
367
- })
368
- }
369
-
370
- test('agent backend stays lexical even when a local profile is active', async () => {
371
- const f = fixture({ 'mem-needle': entry('needle local match') })
372
- activate([f.libraryId])
373
- state.updateSettings({ memoryBackend: 'agent', vectorSource: 'local' })
374
- retrieveHook = () => { throw new Error('agent route must not call MemU') }
375
- const result = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8 })
376
- assert.deepEqual(result.files.map(file => file.name), ['mem-needle'])
377
- assert.equal(result.recallRoute, 'local')
378
- assert.equal(calls.length, 0)
379
- assert.equal(state.effectiveVectorRoute(), 'lexical')
380
- assert.equal(state.vectorBackendEnabled(), false)
381
- })
382
-
383
- test('remote-api ignores an active local profile and passes explicit remote route', async () => {
384
- const f = fixture({ 'mem-needle': entry('needle local match') })
385
- activate([f.libraryId])
386
- state.updateSettings({ memoryBackend: 'api', vectorSource: 'api' })
387
- retrieveHook = () => ({ files: [{ name: 'mem-needle' }], segments: [], resources: [] })
388
- const result = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8 })
389
- assert.equal(result.recallRoute, 'managed-vector-rrf')
390
- assert.equal(calls[0].route, 'remote-api')
391
- assert.notEqual(calls[0].db, vp.dbPathFor(f.libraryId))
392
- })
393
-
394
- test('invalid profile is a managed lexical fallback, never a remote fallback', async () => {
395
- const f = fixture({ 'mem-needle': entry('needle local match') })
396
- activate([f.libraryId])
397
- vp.updateVectorStateSync(current => ({ ...current, active: { ...current.active,
398
- profile: { ...current.active.profile, catalogId: 'missing-catalog-entry' } } }))
399
- const result = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8 })
400
- assert.deepEqual(result.files.map(file => file.name), ['mem-needle'])
401
- assert.match(state.getSessionBinding(f.sessionId).lastRecallError, /catalog/)
402
- assert.equal(calls.length, 0)
403
- })
404
-
405
- test('global managed recall fuses by domain and records semantic errors despite lexical hits', async () => {
406
- const f = fixture()
407
- activate([f.libraryId])
408
- state.saveGlobalIndex({ entries: { 'gmem-needle': entry('needle global match', { domain: 'coding' }),
409
- 'gmem-orbit': entry('orbital mechanics', { domain: 'coding' }), 'gmem-other': entry('needle other world', { domain: 'rp' }) } })
410
- retrieveHook = () => { throw new Error('worker unavailable') }
411
- const failed = await memory.globalRecall({ exec: f.exec, query: 'needle', topK: 8 })
412
- assert.deepEqual(failed.files.map(file => file.name), ['gmem-needle'])
413
- assert.equal(failed.recallRoute, 'local-fallback')
414
- assert.match(state.getSessionBinding(f.sessionId).lastRecallError, /worker unavailable/)
415
- retrieveHook = () => ({ files: [{ name: 'gmem-orbit' }, { name: 'gmem-other' }] })
416
- const healthy = await memory.globalRecall({ exec: f.exec, query: 'needle', topK: 8 })
417
- assert.deepEqual(new Set(healthy.files.map(file => file.name)), new Set(['gmem-needle', 'gmem-orbit']))
418
- assert.equal(healthy.recallRoute, 'managed-vector-rrf')
419
- assert.equal(state.getSessionBinding(f.sessionId).lastRecallError, undefined)
420
- })
421
-
422
- test('new library enrolls inside lease before first managed commit and lease spans index write', async () => {
423
- const f = fixture()
424
- activate()
425
- let entered
426
- let release
427
- const started = new Promise(resolve => { entered = resolve })
428
- const gate = new Promise(resolve => { release = resolve })
429
- commitHook = async args => {
430
- assert.equal(args.db, vp.dbPathFor(f.libraryId))
431
- assert.equal(Object.keys(state.loadPrivateIndex(f.libraryId).entries).length, 0)
432
- entered()
433
- await gate
434
- }
435
- const writing = memory.privateRemember({ exec: f.exec, content: 'new managed fact', title: 'new managed fact' })
436
- await started
437
- await assert.rejects(vp.withVectorWriteFreeze(() => {}), { code: 'VECTOR_WRITE_BUSY' })
438
- release()
439
- const result = await writing
440
- assert.equal(state.loadPrivateIndex(f.libraryId).entries[result.id].content, 'new managed fact')
441
- assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
442
- assert.ok(vp.activeVectorState().active.databases.libraries[f.libraryId])
443
- })
444
-
445
- test('nonempty old library must rebuild rather than silently enroll an empty vector DB', async () => {
446
- const f = fixture({ 'mem-existing': entry('old stored fact') })
447
- activate()
448
- await assert.rejects(memory.privateRemember({ exec: f.exec, content: 'new different fact' }), { code: 'VECTOR_LIBRARY_REBUILD_REQUIRED' })
449
- assert.equal(calls.length, 0)
450
- assert.deepEqual(Object.keys(state.loadPrivateIndex(f.libraryId).entries), ['mem-existing'])
451
- })
452
-
453
- test('freeze rejects every async write before engine or index mutation', async () => {
454
- const f = fixture({ 'mem-live': entry('live fact'), 'mem-held': entry('held claim', { status: 'pending_review' }),
455
- 'mem-archived': entry('old archived', { status: 'archived' }) })
456
- activate([f.libraryId])
457
- const before = JSON.stringify(state.loadPrivateIndex(f.libraryId))
458
- await vp.withVectorWriteFreeze(async () => {
459
- const writes = [
460
- () => memory.privateRemember({ exec: f.exec, content: 'new fact' }),
461
- () => memory.importMemories({ libraryId: f.libraryId, memories: [{ content: 'restored fact' }] }),
462
- () => memory.privateUpdate({ exec: f.exec, id: 'mem-live', content: 'updated fact' }),
463
- () => memory.privateDelete({ exec: f.exec, id: 'mem-archived' }),
464
- () => memory.resolveMemoryReview({ libraryId: f.libraryId, id: 'mem-held', action: 'accept' }),
465
- () => curator.commitCuratorOutput({ memories: [curated()] }, { job: job() }),
466
- ]
467
- for (const write of writes) await assert.rejects(write(), { code: 'VECTOR_WRITE_FROZEN' })
468
- })
469
- assert.equal(JSON.stringify(state.loadPrivateIndex(f.libraryId)), before)
470
- assert.equal(calls.length, 0)
471
- assert.deepEqual(state.loadGlobalIndex().entries, {})
472
- })
473
-
474
- test('managed agent update import delete and review call engine under lease; held edits stay index-only', async () => {
475
- const f = fixture({ 'mem-live': entry('live fact'), 'mem-held': entry('held claim', { status: 'pending_review' }),
476
- 'mem-archived': entry('old archived', { status: 'archived' }) })
477
- activate([f.libraryId])
478
- await memory.privateUpdate({ exec: f.exec, id: 'mem-live', content: 'new implementation fact' })
479
- await memory.privateUpdate({ exec: f.exec, id: 'mem-held', content: 'edited held claim' })
480
- assert.equal(calls.length, 1, 'pending_review edit never commits')
481
- await memory.resolveMemoryReview({ libraryId: f.libraryId, id: 'mem-held', action: 'accept' })
482
- await memory.importMemories({ libraryId: f.libraryId, memories: [{ content: 'restored unique observation' }] })
483
- await memory.privateDelete({ exec: f.exec, id: 'mem-archived' })
484
- assert.deepEqual(calls.map(call => call.op), ['commit', 'commit', 'commit', 'forget'])
485
- assert.equal(state.loadPrivateIndex(f.libraryId).entries['mem-archived'], undefined)
486
- })
487
-
488
- test('post-CAS remember failure compensates the newly committed backend row', async () => {
489
- const f = fixture()
490
- activate([f.libraryId])
491
- commitHook = async () => state.setSessionBinding(f.sessionId, { libraryId: 'rebound-library' })
492
- await assert.rejects(
493
- memory.privateRemember({ exec: f.exec, content: 'must compensate', title: 'must compensate' }),
494
- /memory scope changed during write; retry/,
495
- )
496
- assert.deepEqual(calls.map(call => call.op), ['commit', 'forget'])
497
- assert.equal(calls[1].db, calls[0].db, 'cleanup uses the captured database after rebind')
498
- assert.equal(calls[1].name, calls[0].payload.recall_files[0].name)
499
- assert.equal(backendRows.size, 0, 'no orphan survives in the fake backend')
500
- assert.deepEqual(state.loadPrivateIndex(f.libraryId).entries, {})
501
- assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
502
- })
503
-
504
- test('post-CAS update failure deletes the new row and restores the old backend payload', async () => {
505
- const old = entry('old backend fact', { title: 'old title' })
506
- const f = fixture({ 'mem-live': old })
507
- activate([f.libraryId])
508
- commitHook = async () => state.setSessionBinding(f.sessionId, { libraryId: 'rebound-library' })
509
- await assert.rejects(
510
- memory.privateUpdate({ exec: f.exec, id: 'mem-live', content: 'new backend fact', title: 'new title' }),
511
- /memory scope changed during update; retry/,
512
- )
513
- assert.deepEqual(calls.map(call => call.op), ['commit', 'forget', 'commit'])
514
- assert.equal(calls[2].payload.recall_files[0].content, old.content)
515
- assert.equal(calls[2].payload.recall_files[0].description, old.title)
516
- assert.equal(calls[1].db, calls[0].db)
517
- assert.equal(calls[2].db, calls[0].db)
518
- assert.equal(backendRows.get(backendKey(calls[0].db, 'mem-live')).content, old.content)
519
- assert.deepEqual(state.loadPrivateIndex(f.libraryId).entries['mem-live'], old)
520
- assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
521
- })
522
-
523
- test('uncertain backend compensation is visible instead of reported as a successful write', async () => {
524
- const f = fixture()
525
- activate([f.libraryId])
526
- commitHook = async () => state.setSessionBinding(f.sessionId, { libraryId: 'rebound-library' })
527
- failForget = true
528
- await assert.rejects(
529
- memory.privateRemember({ exec: f.exec, content: 'uncertain backend state' }),
530
- error => error?.code === 'PRIVATE_BACKEND_COMPENSATION_FAILED' && /compensation uncertain/.test(error.message)
531
- && /memory scope changed/.test(error.cause?.message) && /mock managed forget failed/.test(error.compensationError?.message),
532
- )
533
- assert.deepEqual(calls.map(call => call.op), ['commit', 'forget'])
534
- })
535
-
536
- test('a failed restore is reported as uncertain and never erases the authoritative index', async () => {
537
- const f = fixture({ 'mem-live': entry('original backend payload') })
538
- activate([f.libraryId])
539
- const original = state.loadPrivateIndex(f.libraryId).entries['mem-live']
540
- let count = 0
541
- commitHook = async () => {
542
- if (++count > 1) throw new Error('restore unavailable')
543
- state.setSessionBinding(f.sessionId, { useLibrary: false })
544
- }
545
- await assert.rejects(memory.privateUpdate({ exec: f.exec, id: 'mem-live', content: 'rejected edit' }), error => {
546
- assert.equal(error.code, 'PRIVATE_BACKEND_COMPENSATION_FAILED')
547
- assert.match(error.compensationError.message, /restore unavailable/)
548
- return true
549
- })
550
- assert.deepEqual(calls.map(call => call.op), ['commit', 'forget', 'commit'])
551
- assert.deepEqual(state.loadPrivateIndex(f.libraryId).entries['mem-live'], original)
552
- assert.ok(warnings.some(warning => /compensation uncertain/.test(warning)))
553
- })
554
-
555
- test('unparseable compensation acknowledgement is visibly uncertain', async () => {
556
- const f = fixture()
557
- activate([f.libraryId])
558
- commitHook = async () => state.setSessionBinding(f.sessionId, { useLibrary: false })
559
- forgetHook = async () => ({ deleted: 0, parseWarning: 'mock non-JSON acknowledgement' })
560
- await assert.rejects(memory.privateRemember({ exec: f.exec, content: 'rejected new payload' }), {
561
- code: 'PRIVATE_BACKEND_COMPENSATION_FAILED',
562
- })
563
- assert.equal(backendRows.size, 1, 'uncertain cleanup is not claimed to remove the orphan')
564
- assert.deepEqual(state.loadPrivateIndex(f.libraryId).entries, {})
565
- forgetHook = async () => ({ ok: true })
566
- state.setSessionBinding(f.sessionId, { useLibrary: true })
567
- await assert.rejects(memory.privateRemember({ exec: f.exec, content: 'malformed delete acknowledgement' }), {
568
- code: 'PRIVATE_BACKEND_COMPENSATION_FAILED',
569
- })
570
- })
571
-
572
- test('a concurrently replaced index refuses destructive compensation', async () => {
573
- const f = fixture({ 'mem-live': entry('original backend payload') })
574
- activate([f.libraryId])
575
- commitHook = async () => state.updatePrivateIndex(f.libraryId, index => {
576
- index.entries['mem-live'].content = 'externally replaced authoritative value'
577
- })
578
- await assert.rejects(memory.privateUpdate({ exec: f.exec, id: 'mem-live', content: 'rejected edit' }), error => {
579
- assert.equal(error.code, 'PRIVATE_BACKEND_COMPENSATION_FAILED')
580
- assert.match(error.cause.message, /memory changed concurrently/)
581
- assert.match(error.compensationError.message, /changed before backend compensation/)
582
- return true
583
- })
584
- assert.deepEqual(calls.map(call => call.op), ['commit'], 'do not delete a newer same-name backend row')
585
- assert.equal(state.loadPrivateIndex(f.libraryId).entries['mem-live'].content, 'externally replaced authoritative value')
586
- })
587
-
588
- test('library queue spans compensation across routes and releases after failure', async () => {
589
- const f = fixture()
590
- activate([f.libraryId])
591
- let entered
592
- let release
593
- const started = new Promise(resolve => { entered = resolve })
594
- const gate = new Promise(resolve => { release = resolve })
595
- commitHook = async () => {
596
- commitHook = null
597
- state.setSessionBinding(f.sessionId, { useLibrary: false })
598
- }
599
- forgetHook = async args => {
600
- entered()
601
- await gate
602
- backendRows.delete(backendKey(args.db, args.name))
603
- return { deleted: 1 }
604
- }
605
- const first = memory.privateRemember({ exec: f.exec, content: 'first write must roll back' })
606
- const rejected = assert.rejects(first, /private memory is turned off/)
607
- await started
608
- // A remote writer to the same library must wait for managed compensation.
609
- state.updateSettings({ vectorSource: 'api' })
610
- const second = memory.importMemories({ libraryId: f.libraryId, memories: [{ content: 'later remote write' }] })
611
- await new Promise(resolve => setImmediate(resolve))
612
- assert.deepEqual(calls.map(call => call.op), ['commit', 'forget'])
613
- assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 1)
614
- release()
615
- await rejected
616
- const imported = await second
617
- assert.equal(imported.imported, 1)
618
- assert.equal(calls[2].route, 'remote-api')
619
- assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
620
- assert.equal(backendRows.size, 1)
621
- })
622
-
623
- test('managed vector commit failure defers to index-only instead of losing the write', async () => {
624
- const f = fixture()
625
- activate([f.libraryId])
626
- failCommit = true
627
- const written = await memory.privateRemember({ exec: f.exec, content: 'deferred write survives', title: 'deferred' })
628
- let entry = state.loadPrivateIndex(f.libraryId).entries[written.id]
629
- assert.equal(entry.content, 'deferred write survives')
630
- assert.equal(entry.vectorPending, true)
631
- assert.equal(entry.vector, undefined)
632
- assert.equal(backendRows.size, 0, 'nothing was falsely recorded as committed')
633
- assert.ok(warnings.some(message => /deferred/.test(message)), 'the degradation must be observable')
634
-
635
- failCommit = false
636
- await memory.privateUpdate({ exec: f.exec, id: written.id, content: 'deferred write now committed' })
637
- entry = state.loadPrivateIndex(f.libraryId).entries[written.id]
638
- assert.equal(entry.vectorPending, undefined, 'a later successful commit clears the pending flag')
639
- assert.equal(entry.vector.route, 'managed-local')
640
- })
641
-
642
- test('managed import failure rejects without index-first false success', async () => {
643
- const f = fixture()
644
- activate([f.libraryId])
645
- failCommit = true
646
- await assert.rejects(memory.importMemories({ libraryId: f.libraryId, memories: [{ content: 'restored unique fact' }] }), /mock managed commit failed/)
647
- assert.deepEqual(state.loadPrivateIndex(f.libraryId).entries, {})
648
- assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
649
- })
650
-
651
- test('a write under an active generation records which vector space it entered', async () => {
652
- const f = fixture()
653
- activate([f.libraryId])
654
- const written = await memory.privateRemember({ exec: f.exec, content: '这条应该记下向量归属', title: '向量归属' })
655
- const entry = state.loadPrivateIndex(f.libraryId).entries[written.id]
656
- assert.equal(entry.vector.model, 'bge-small-zh-v1.5-int8')
657
- assert.equal(entry.vector.generation, 1)
658
- assert.equal(entry.vector.route, 'managed-local')
659
- assert.match(entry.vector.fingerprint, /^[0-9a-f]{8}$/)
660
-
661
- // 没有代际(降级写)时不允许写字面上的"已入向量库"。
662
- fs.rmSync(activeFile, { force: true })
663
- const plain = await memory.privateRemember({ exec: f.exec, content: '降级写不应带向量归属', title: '降级' })
664
- assert.equal(state.loadPrivateIndex(f.libraryId).entries[plain.id].vector, undefined)
665
- })
666
-
667
- test('the vector count follows reality: writes stamp, review/import/curator stamp, deletes shrink', async () => {
668
- // 现场事故(2026-10-31):设置页"当前已入向量库 N 条"只数迁移账本 —— 账本在切换
669
- // 那一刻写完就再也不更新,聊天里新写的记忆永远不进计数。membership = 账本腿(迁移
670
- // 写入,扣除已删除)+ 戳腿(迁移后写入)。每条迁移后写入路径都必须落戳,否则漏数。
671
- const vm = await import('../lib/vector-migration.js')
672
- const f = fixture({
673
- 'mem-migrated': entry('迁移时就有的记忆'),
674
- 'mem-held': entry('待审的主张', { status: 'pending_review' }),
675
- })
676
- activate([f.libraryId])
677
- // 预置"切换时写入 1/1"的账本快照:mem-migrated 在迁移时进了向量库(索引故意无戳)。
678
- const { ledger } = vm.loadLedger(profile.fingerprint, 1)
679
- ledger.libraries[f.libraryId] = { items: { 'mem-migrated': { hash: 'seed', at: new Date().toISOString() } }, tombstones: {}, snapshot: null }
680
- vm.saveLedger(ledger)
681
- const migrator = vm.createVectorMigrator({
682
- listLibraries: () => state.listLibraries().map(item => item.id),
683
- loadIndex: libraryId => libraryId == null ? state.loadGlobalIndex() : state.loadPrivateIndex(libraryId),
684
- commit: async () => {}, forget: async () => {}, listFiles: async () => [],
685
- })
686
- const idsOf = scope => (migrator.membership()[scope] || []).sort()
687
- assert.deepEqual(idsOf(f.libraryId), ['mem-migrated'], 'starts at the migration count — the reported bug state')
688
-
689
- // 聊天写入:戳腿接管,计数跟着涨。
690
- const written = await memory.privateRemember({ exec: f.exec, content: '切换后新写的记忆', title: '新记忆' })
691
- assert.equal(state.loadPrivateIndex(f.libraryId).entries[written.id].vector.generation, 1)
692
- assert.deepEqual(idsOf(f.libraryId), ['mem-migrated', written.id])
693
-
694
- // 编辑重提交:行被重写进当前空间,戳刷新到当前代际。
695
- await memory.privateUpdate({ exec: f.exec, id: written.id, content: '更新后的记忆内容' })
696
- const updated = state.loadPrivateIndex(f.libraryId).entries[written.id]
697
- assert.equal(updated.vector.generation, 1)
698
- assert.equal(updated.vector.route, 'managed-local')
699
- assert.deepEqual(idsOf(f.libraryId), ['mem-migrated', written.id])
700
-
701
- // 批量恢复与评审接受:此前完全不落戳,是计数漏数的另外两条路。
702
- await memory.importMemories({ libraryId: f.libraryId, memories: [{ content: '恢复回来的独特观察' }] })
703
- const imported = Object.entries(state.loadPrivateIndex(f.libraryId).entries).find(([, item]) => item.content === '恢复回来的独特观察')[0]
704
- assert.equal(state.loadPrivateIndex(f.libraryId).entries[imported].vector.generation, 1)
705
- await memory.resolveMemoryReview({ libraryId: f.libraryId, id: 'mem-held', action: 'accept' })
706
- assert.equal(state.loadPrivateIndex(f.libraryId).entries['mem-held'].vector.generation, 1)
707
- assert.ok(idsOf(f.libraryId).includes(imported) && idsOf(f.libraryId).includes('mem-held'))
708
-
709
- // 永久删除:引擎行先删、索引行后删,账本不知道 —— membership 必须把它扣掉。
710
- await memory.privateArchive({ exec: f.exec, id: 'mem-migrated' })
711
- await memory.privateDelete({ exec: f.exec, id: 'mem-migrated' })
712
- assert.equal(idsOf(f.libraryId).includes('mem-migrated'), false, 'a permanently deleted migration item leaves the count')
713
-
714
- // 全局整理:同样的口径,提交成功即落戳。
715
- const clean = await curator.commitCuratorOutput({ memories: [curated()] }, { job: job() })
716
- assert.equal(clean.created, 1)
717
- const curatedId = Object.keys(state.loadGlobalIndex().entries)[0]
718
- assert.equal(state.loadGlobalIndex().entries[curatedId].vector.route, 'managed-local')
719
- assert.deepEqual((migrator.membership().global || []), [curatedId])
720
- })
721
-
722
- test('managed curator clean output commits under lease and held output is index-only', async () => {
723
- activate()
724
- const clean = await curator.commitCuratorOutput({ memories: [curated()] }, { job: job() })
725
- assert.equal(clean.created, 1)
726
- assert.equal(calls.length, 1)
727
- assert.equal(calls[0].db, vp.dbPathFor(null))
728
- const held = await curator.commitCuratorOutput({ memories: [curated({ title: 'held conflict', op: 'conflict' })] }, { job: job() })
729
- assert.equal(held.pending, 1)
730
- assert.equal(calls.length, 1)
731
- assert.ok(Object.values(state.loadGlobalIndex().entries).some(item => item.status === 'pending_review'))
732
- assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
733
- })
734
-
735
- // 现场事故(2026-10-29):下载完模型、点了选择,但迁移没跑完 —— vector-active 只有
736
- // requested,没有 active。写入路径当时直接抛 VECTOR_NOT_ACTIVE,整理 fork 跑完却一条
737
- // 记忆都没落下,而最后睡眠标记照样前进。写入必须和召回一样降级,不能整体失败。
738
- test('a requested-but-never-migrated profile degrades writes instead of failing them', async () => {
739
- const f = fixture()
740
- assert.equal(vp.hasActiveVectorGeneration(), false)
741
- fs.writeFileSync(activeFile, JSON.stringify({
742
- version: 1,
743
- generation: 0,
744
- requested: { status: 'requested', catalogId: 'bge-small-zh-v1.5-int8', fingerprint: profile.fingerprint },
745
- }))
746
- const private1 = await memory.privateRemember({ exec: f.exec, content: 'degraded private write must land', title: 'degraded private write' })
747
- assert.equal(state.loadPrivateIndex(f.libraryId).entries[private1.id].content, 'degraded private write must land')
748
- // No generation means no embedding environment, so MemU cannot take a commit at
749
- // all (envFor refuses managed-local). Index-only is the honest degradation; the
750
- // record is re-embedded by the next migration.
751
- assert.deepEqual(calls.map(call => call.op), [], 'a vectorless profile must not call the engine')
752
- assert.ok(warnings.some(message => /no active vector generation/.test(message)), 'the degradation is logged: ' + warnings.join(' | '))
753
- assert.ok(activity.listEvents({ kind: 'vector' }).length >= 1, 'the degradation is visible in the activity log')
754
-
755
- const curatedResult = await curator.commitCuratorOutput({ memories: [curated()] }, { job: job() })
756
- assert.equal(curatedResult.created, 1, 'global curation must not be thrown away either')
757
- assert.match(Object.keys(state.loadGlobalIndex().entries).join(','), /gmem-/, 'the global index still receives it')
758
- assert.deepEqual(calls.map(call => call.op), [], 'global curation degrades the same way')
759
- })
760
-
761
- test('archive stays index-only; deleting is what removes the vector row', async () => {
762
- const f = fixture({ 'mem-arch': entry('to archive') })
763
- activate([f.libraryId])
764
- await memory.privateArchive({ exec: f.exec, id: 'mem-arch' })
765
- assert.equal(state.loadPrivateIndex(f.libraryId).entries['mem-arch'].status, 'archived')
766
- assert.deepEqual(calls.map(call => call.op), [], 'archiving must not start the engine; it only flips the index status')
767
- await memory.privateDelete({ exec: f.exec, id: 'mem-arch' })
768
- assert.deepEqual(calls.map(call => call.op), ['forget'], 'permanent delete is what removes the MemU row')
769
- })
770
-
771
- test('UI listings read the index even when vectors are active', async () => {
772
- const f = fixture()
773
- activate([f.libraryId])
774
- // 列表走引擎意味着起 Python + embedding worker(秒级)。索引是权威,UI 刷新不该等它。
775
- const privateView = await memory.privateList({ libraryId: f.libraryId, preferIndex: true })
776
- assert.equal(privateView.source, 'index')
777
- assert.ok(privateView.files.length >= 0)
778
- const globalView = await memory.globalList({ exec: { agent: null }, preferIndex: true })
779
- assert.equal(globalView.source, 'index')
780
- assert.deepEqual(calls.map(call => call.op).filter(op => op === 'listFiles'), [], 'no engine list call')
781
- })
782
-
783
- test('global list degrades to the index when no vector generation is active', async () => {
784
- fs.writeFileSync(activeFile, JSON.stringify({
785
- version: 1,
786
- generation: 0,
787
- requested: { status: 'requested', catalogId: 'bge-small-zh-v1.5-int8', fingerprint: profile.fingerprint },
788
- }))
789
- state.saveGlobalIndex({ entries: { 'gmem-1': entry('global fact', { domain: 'coding' }) } })
790
- // 全局记忆页原先会闪一下 "managed local vector profile is not active" 再消失:
791
- // globalList 走了引擎路由,没有代际就必抛。列表本身能答,就按索引答。
792
- const result = await memory.globalList({ exec: { agent: null } })
793
- assert.equal(result.source, 'index')
794
- assert.deepEqual(result.files.map(file => file.name), ['gmem-1'])
795
- assert.match(result.warning, /本地向量未激活/)
796
- })
797
-
798
- test('an existing but torn generation still refuses writes loudly', async () => {
799
- const f = fixture()
800
- activate([f.libraryId])
801
- assert.equal(vp.hasActiveVectorGeneration(), true)
802
- const dbPath = vp.resolveVectorPath(vp.activeVectorState().active.databases.libraries[f.libraryId].path)
803
- fs.rmSync(dbPath, { force: true })
804
- await assert.rejects(
805
- memory.privateRemember({ exec: f.exec, content: 'must not be silently split', title: 'torn generation' }),
806
- { code: 'VECTOR_TORN_STATE' },
807
- )
808
- assert.deepEqual(Object.keys(state.loadPrivateIndex(f.libraryId).entries), [], 'a torn generation must not leave an index-only entry behind')
809
- })
810
-
811
- test('deleting an active archived library removes its route without tearing later writes', async () => {
812
- const f = fixture()
813
- const databases = activate([f.libraryId])
814
- const activeDb = vp.resolveVectorPath(databases.libraries[f.libraryId].path)
815
- fs.writeFileSync(path.join(home, 'libraries', f.libraryId + '.old.g1.sqlite3'), '')
816
- state.archiveLibrary(f.libraryId)
817
- await vp.withVectorWrite(async () => {
818
- assert.throws(() => state.deleteLibrary(f.libraryId), { code: 'VECTOR_WRITE_BUSY' })
819
- })
820
- const result = state.deleteLibrary(f.libraryId)
821
- assert.equal(result.ok, true)
822
- assert.equal(vp.activeVectorState().active.databases.libraries[f.libraryId], undefined)
823
- assert.equal(fs.existsSync(activeDb), false)
824
- assert.equal(fs.existsSync(path.join(home, 'libraries', f.libraryId + '.old.g1.sqlite3')), false)
825
-
826
- const next = fixture()
827
- const remembered = await memory.privateRemember({ exec: next.exec, content: 'write after deleting another library', title: 'route remains healthy' })
828
- assert.equal(state.loadPrivateIndex(next.libraryId).entries[remembered.id].content, 'write after deleting another library')
829
- assert.equal(vp.activeVectorState().active.databases.libraries[f.libraryId], undefined)
830
- })
831
-
832
- // 2026-11-18 排序修正端到端:RRF 名次归一把词法满分命中压成近平手后,primacy/peakEnd
833
- // 偏置会把弱相关元记忆顶到第一(运行时实测:lexical 219.5 的完美命中被挤到 #8)。
834
- // 修复后巨无霸命中保住 #1,弱竞争者落到相对阈值之外。
835
- test('a dominant lexical hit cannot be buried by primacy/peak-end biases', async () => {
836
- state.updateSettings({ memoryBackend: 'api', vectorSource: 'local' })
837
- // 大语料抬高 BM25 的库规模(IDF 随 N 增长,小语料造不出 ≥24 的巨无霸分)。
838
- const entries = {}
839
- const alphabet = 'abcdefghijklmnopqrstuvwxyz'
840
- const token = (n) => alphabet[n % 26] + alphabet[Math.floor(n / 26) % 26]
841
- const old = '2026-10-01T00:00:00.000Z'
842
- for (let i = 0; i < 60; i += 1) {
843
- entries['mem-pad-' + String(i).padStart(2, '0')] = entry('常规条目 ' + token(3 * i) + token(3 * i + 1) + ',归档说明与轮值安排。', {
844
- createdAt: old, updatedAt: old, strength: 1, arousal: 0.9,
845
- })
846
- }
847
- // meta:最早创建(primacy ×1.2)+ 高唤醒(peakEnd ×1.25)+ strength 1——偏置加成最大;
848
- // 正文含查询里的常见词元(有/没有),让它也进词法腿,制造名次归一的近平手。
849
- entries['mem-meta'] = entry('运营值守安排,没有什么特别的说明。', { createdAt: old, updatedAt: old, strength: 1, arousal: 0.9 })
850
- entries['mem-food'] = entry('主人是江南人,爱吃桂花糖糕,在杭州吃不到几家做糖糕和豆沙米糕的铺子。', { strength: 0.8, arousal: 0.35 })
851
- const f = fixture(entries)
852
- activate([f.libraryId])
853
- // 语义腿把 meta 排在 food 前面(模拟引擎 embedding 被查询样板带偏的形态):
854
- // 词法腿 food 满分,RRF 名次归一后两者 retrieval 近平手。
855
- retrieveHook = () => ({ files: [{ name: 'mem-meta' }, { name: 'mem-food' }], segments: [], resources: [] })
856
- const result = await memory.privateRecall({ exec: f.exec, query: '桂花的,我江南小囡喜欢吃糖糕,还有豆沙米糕', topK: 5, relevanceThreshold: 0.4 })
857
- assert.equal(result.files[0]?.name, 'mem-food', 'the dominant lexical hit must rank first, got ' + result.files[0]?.name)
858
- assert.ok((result.files[0]?.fusion?.lexicalDominant ?? 0) >= 24, 'the dominance must be recorded in fusion metadata')
859
- assert.ok(!result.files.some((file) => file.name === 'mem-meta'), 'weak competitors fall below the relative threshold')
860
- retrieveHook = null
861
- })
862
-
863
- // Real BM25 regressions: only the semantic boundary is stubbed. Dates deliberately
864
- // age with now; a future sceneTime must not erase strength/primacy in these cases.
865
- function rankingEntry(content, extra = {}) {
866
- const ago = days => new Date(Date.now() - days * 86_400_000).toISOString()
867
- return entry(content, { createdAt: ago(2), updatedAt: ago(1), ...extra })
868
- }
869
-
870
- function rankingWorld(primaryEntries, foreignEntries) {
871
- const primary = fixture(primaryEntries)
872
- const foreign = fixture(foreignEntries)
873
- const domain = 'ranking:' + primary.sessionId
874
- for (const f of [primary, foreign]) state.setSessionBinding(f.sessionId, { domainOverride: domain })
875
- state.updateSettings({ crossLibraryRecall: true })
876
- return { primary, foreign }
877
- }
878
-
879
- function realLexical(entries, query) {
880
- const corpus = buildCorpus(Object.entries(entries).map(([id, row]) => ({
881
- id, title: row.title,
882
- content: [row.content, (row.tags || []).join(' '), (row.attachments || []).map(item => `${item.caption || ''} 图片 ${item.kind || 'image'}`).join(' ')].filter(Boolean).join(' '),
883
- })))
884
- return new Map([...corpus.docs].map(([id, doc]) => [id, bm25(tokenize(query), doc, corpus)]))
885
- }
886
-
887
- async function assertRankingBoundary(expectedRetrieves) {
888
- await settleRebuildProbes()
889
- assert.equal(calls.length, expectedRetrieves, 'only the stub semantic retrieve boundary is called')
890
- assert.ok(calls.every(call => call.op === 'retrieve' && call.route === 'managed-local'))
891
- assert.deepEqual(rebuildProbes, [], 'ranking regressions must not start a real rebuild/worker')
892
- assert.deepEqual(warnings, [])
893
- }
894
-
895
- const tlsAnswer = 'TLS 服务证书过期,续签后重启代理恢复连接。'
896
- const tlsTemplate = '请用自然简洁的语气回答。这是通用回复风格,不涉及饮食或服务故障。'
897
- const pianoNotes = [
898
- '钢琴练习先慢速弹奏音阶,再练左右手协调。',
899
- '巴赫赋格练习需要分声部辨认旋律。',
900
- '踏板练习要注意换踏时机与音色。',
901
- '周末排练莫扎特奏鸣曲,保持轻巧触键。',
902
- '视奏练习每天十五分钟,先看拍号与调号。',
903
- '和弦转位练习强调指法与手腕放松。',
904
- '节拍器从慢速逐渐加快,避免抢拍。',
905
- '演出前检查琴凳高度,认真完成热身。',
906
- ]
907
- function tlsEntries(template, size = 2) {
908
- const answerDate = new Date(Date.now() - 4 * 86_400_000).toISOString()
909
- return {
910
- 'mem-answer': rankingEntry(tlsAnswer, { createdAt: answerDate, strength: 1, peak: true }),
911
- 'mem-template': rankingEntry(template, { strength: 0.8 }),
912
- ...Object.fromEntries(pianoNotes.slice(0, size - 2).map((text, i) => ['mem-piano-' + i, rankingEntry(text)])),
913
- }
914
- }
915
-
916
- for (const crossLibrary of [false, true]) {
917
- test(`real BM25 short reply style leaves TLS answer first (${crossLibrary ? 'with three foreign piano notes' : 'two-entry library'})`, async () => {
918
- const entries = tlsEntries(tlsTemplate)
919
- const world = crossLibrary
920
- ? rankingWorld(entries, Object.fromEntries(pianoNotes.slice(0, 3).map((text, i) => ['mem-note-' + i, rankingEntry(text)])))
921
- : null
922
- const f = world?.primary || fixture(entries)
923
- activate(world ? [f.libraryId, world.foreign.libraryId] : [f.libraryId])
924
- retrieveHook = args => ({ files: args.db === vp.dbPathFor(f.libraryId) ? [{ name: 'mem-answer' }, { name: 'mem-template' }] : [], segments: [], resources: [] })
925
- const result = await memory.privateRecall({ exec: f.exec, query: '请用自然简洁的语气回答。TLS 故障原因?', topK: 5, relevanceThreshold: 0 })
926
- assert.equal(result.files[0]?.name, 'mem-answer', 'corpus changes must not crown the reply-style template')
927
- const template = result.files.find(file => file.name === 'mem-template')
928
- assert.ok(template?.lexical > 0, 'the original lexical score stays observable')
929
- assert.ok(template.lexicalEvidence < template.lexical, 'style-only overlap is not topical evidence')
930
- assert.notEqual(result.fusion?.lexicalDominance?.id, 'mem-template')
931
- assert.equal(result.files[0].entry.content, tlsAnswer)
932
- if (crossLibrary) assert.equal(result.files[0].libraryId, f.libraryId)
933
- await assertRankingBoundary(crossLibrary ? 2 : 1)
934
- })
935
- }
936
-
937
- for (const [language, template, query] of [
938
- ['short Chinese', tlsTemplate, '请用自然简洁的语气回答。TLS 故障原因?'],
939
- ['Chinese', '请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。', '请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。TLS 故障原因?'],
940
- ['English', 'Please answer clearly and concisely with accurate context and natural language. Avoid repetition and unnecessary details.', 'Please answer clearly and concisely with accurate context and natural language. Avoid repetition and unnecessary details. What caused TLS failure?'],
941
- ]) {
942
- for (const size of [2, 3, 10]) {
943
- test(`real BM25 ${language} long reply style keeps TLS answer first with ${size} documents`, async () => {
944
- const f = fixture(tlsEntries(template, size))
945
- activate([f.libraryId])
946
- retrieveHook = () => ({ files: [{ name: 'mem-answer' }, { name: 'mem-template' }], segments: [], resources: [] })
947
- const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.4 })
948
- assert.ok(result.files.length, 'style removal must not turn a topical query into empty recall')
949
- assert.equal(result.files[0]?.name, 'mem-answer')
950
- assert.notEqual(result.fusion?.lexicalDominance?.id, 'mem-template')
951
- assert.ok(result.files[0].lexical > 0, 'TLS remains an actual lexical hit, not only a semantic rescue')
952
- await assertRankingBoundary(1)
953
- })
954
- }
955
- }
956
-
957
- const rankingWords = 'certificate expired renewal proxy restart connection handshake trust chain hostname issuer validity protocol cipher client server clock intermediate root authority verification transport security gateway service outage investigation diagnosis mitigation deployment recovery monitoring incident encryption authentication socket timeout negotiation alert endpoint configuration rotation revocation openssl pem browser response failure latency availability maintenance rollback'.split(' ')
958
- const foodQuery = '桂花的,我江南小囡喜欢吃糖糕,还有豆沙米糕'
959
- const foodAnswer = '主人是江南人,爱吃桂花糖糕,在杭州吃不到几家做糖糕和豆沙米糕的铺子。'
960
-
961
- test('real BM25 a weak 的 hit is no worse than zero evidence and preserves topical answer order', async () => {
962
- const topicQuery = '桂花 江南 糖糕 豆沙米糕 杭州 铺子'
963
- const entries = {
964
- 'mem-food': rankingEntry(foodAnswer, { peak: true, createdAt: new Date(Date.now() - 4 * 86_400_000).toISOString() }),
965
- 'mem-semantic': rankingEntry('钢琴练习巴赫赋格。', { strength: 0.8 }),
966
- 'mem-weak': rankingEntry('归档标记:的', { strength: 0.8 }),
967
- }
968
- const f = fixture(entries)
969
- activate([f.libraryId])
970
- retrieveHook = () => ({ files: [{ name: 'mem-food' }, { name: 'mem-semantic' }], segments: [], resources: [] })
971
- const result = await memory.privateRecall({ exec: f.exec, query: topicQuery + ' 的', topK: 5, relevanceThreshold: 0 })
972
- assert.equal(result.files[0]?.name, 'mem-food')
973
- assert.ok(result.fusion.lexicalDominance?.topLex >= 24, 'the test must exercise dominance, not an inactive branch')
974
- const weak = result.files.find(file => file.name === 'mem-weak')
975
- const zero = result.files.find(file => file.name === 'mem-semantic')
976
- assert.ok(weak?.lexical > 0 && weak.lexical < result.files[0].lexical / 20, '的 is a real but tiny BM25 hit')
977
- assert.ok(zero, 'the zero-evidence semantic candidate remains observable')
978
- assert.equal(zero.lexical ?? 0, 0)
979
- const sigma = 1 / (1 + result.fusion.lexicalDominance.topLex / 50)
980
- assert.ok(Math.abs(weak.fusion.lexicalDiscount - sigma) < 1e-12, 'tiny evidence is protected by the continuous sigma floor')
981
- assert.ok(weak.fusion.lexicalDiscount >= zero.fusion.lexicalDiscount, 'a tiny lexical hit cannot be penalized more than no hit')
982
- const baseline = await memory.privateRecall({ exec: f.exec, query: topicQuery, topK: 5, relevanceThreshold: 0 })
983
- assert.deepEqual(result.files.filter(file => file.name !== 'mem-weak').map(file => file.name), baseline.files.filter(file => file.name !== 'mem-weak').map(file => file.name))
984
- await assertRankingBoundary(2)
985
- })
986
-
987
- test('real BM25 cross-library same-id facts stay separate and a strong foreign hit is real evidence', async () => {
988
- state.updateSettings({ memoryBackend: 'agent' })
989
- const query = rankingWords.slice(0, 38).join(' ')
990
- const primaryEntries = {
991
- // 逆序打破逐字包含/核心覆盖探针:两条同 id 事实必须靠身份而不是内容去重存活。
992
- 'mem-shared': rankingEntry(rankingWords.slice(0, 3).reverse().join(' ')),
993
- 'mem-secondary': rankingEntry(rankingWords.slice(3, 9).join(' ')),
994
- }
995
- const foreignEntries = { 'mem-shared': rankingEntry(query), 'mem-piano': rankingEntry(pianoNotes[0]) }
996
- const { primary, foreign } = rankingWorld(primaryEntries, foreignEntries)
997
- const all = await memory.privateRecall({ exec: primary.exec, query, topK: 5, relevanceThreshold: 0 })
998
- assert.deepEqual(new Set(all.libraries), new Set([primary.libraryId, foreign.libraryId]))
999
- const twins = all.files.filter(file => file.name === 'mem-shared')
1000
- assert.equal(twins.length, 2, 'same id in two libraries is two facts, not one folded row')
1001
- const sharedPrimary = twins.find(file => file.libraryId === primary.libraryId)
1002
- const sharedForeign = twins.find(file => file.libraryId === foreign.libraryId)
1003
- assert.equal(sharedPrimary.entry.content, primaryEntries['mem-shared'].content)
1004
- assert.equal(sharedForeign.entry.content, query)
1005
- assert.ok(sharedForeign.lexical > sharedPrimary.lexical, 'each twin keeps its own unified-corpus evidence, nothing is inherited')
1006
- assert.ok(all.files.some(file => file.name === 'mem-secondary' && file.libraryId === primary.libraryId))
1007
- assert.ok(!all.files.some(file => file.name === 'mem-piano'), 'zero-evidence foreign filler stays out')
1008
- assert.equal(all.files[0].libraryId, foreign.libraryId, 'the genuinely strong foreign fact outranks weak local rows')
1009
- assert.equal(all.fusion.crossLibraryLexical, 'unified-bm25')
1010
- const cut = await memory.privateRecall({ exec: primary.exec, query, topK: 5, relevanceThreshold: 0.8 })
1011
- assert.deepEqual(cut.files.map(file => [file.libraryId, file.name]), [[foreign.libraryId, 'mem-shared']], 'the 0.8 cut is real competition now, not ghost removal')
1012
- const evidence = file => file.lexicalEvidence ?? file.lexical ?? 0
1013
- const ranked = all.files.slice().sort((a, b) => evidence(b) - evidence(a))
1014
- const dominant = evidence(ranked[0]) >= 24 && evidence(ranked[0]) >= evidence(ranked[1]) * 4
1015
- assert.equal(Boolean(all.fusion.lexicalDominance), dominant, 'dominance is computed from the surviving unified evidence')
1016
- if (dominant) assert.equal(all.fusion.lexicalDominance.id, ranked[0].name)
1017
- for (const file of all.files) {
1018
- assert.ok(Math.abs(file.retrievalScore - Math.min(1, file.fusion.rawRetrievalScore * (file.fusion.lexicalDiscount ?? 1))) < 1e-12)
1019
- }
1020
- await assertRankingBoundary(0)
1021
- })
1022
-
1023
- for (const gate of ['disclosure', 'speaker']) {
1024
- test(`real BM25 ${gate} filtering recomputes dominance from eligible candidates`, async () => {
1025
- const query = (gate === 'speaker' ? '我说过 ' : '') + rankingWords.join(' ')
1026
- const entries = {
1027
- 'mem-hidden': rankingEntry(rankingWords.join(' '), gate === 'disclosure' ? { disclosure: 'only_if_asked' } : { speaker_id: 'assistant' }),
1028
- 'mem-small': rankingEntry(rankingWords.slice(0, 3).join(' '), { speaker_id: 'user', strength: 0.8 }),
1029
- 'mem-normal': rankingEntry('钢琴练习已经完成,下一次排练在周末。', { speaker_id: 'user', strength: 0.8 }),
1030
- }
1031
- const scores = realLexical(entries, query)
1032
- assert.ok(scores.get('mem-hidden') >= 24 && scores.get('mem-hidden') >= scores.get('mem-small') * 4)
1033
- const f = fixture(entries)
1034
- activate([f.libraryId])
1035
- retrieveHook = () => ({ files: [{ name: 'mem-normal' }], segments: [], resources: [] })
1036
- const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8, purpose: 'automatic' })
1037
- assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-normal', 'mem-small']))
1038
- assert.equal(result.fusion.lexicalDominance, null, 'the final summary must not retain the excluded top')
1039
- for (const file of result.files) {
1040
- assert.equal(file.fusion.lexicalDominant, undefined)
1041
- assert.equal(file.fusion.lexicalDiscount, undefined)
1042
- assert.equal(file.retrievalScore, file.fusion.rawRetrievalScore, 'filtered survivors recover their raw RRF share')
1043
- }
1044
- await assertRankingBoundary(1)
1045
- })
1046
- }
1047
-
1048
- test('real BM25 nested vector and cross-library RRF applies exactly one sigma to semantic-only recall', async () => {
1049
- const query = rankingWords.join(' ')
1050
- const entries = {
1051
- 'mem-strong': rankingEntry(query),
1052
- 'mem-mild': rankingEntry('端口8443证书根链验证失败,需要检查中间CA是否被撤销。', { tags: rankingWords.slice(0, 22) }),
1053
- 'mem-semantic': rankingEntry(pianoNotes.join(' ')),
1054
- }
1055
- const scores = realLexical(entries, query)
1056
- const inner = memory.fuseRecallCandidates({
1057
- index: { entries },
1058
- local: ['mem-strong', 'mem-mild'].map(name => ({ name, entry: entries[name], content: entries[name].content, lexical: scores.get(name) })),
1059
- semantic: [{ name: 'mem-semantic' }, { name: 'mem-strong' }],
1060
- })
1061
- assert.deepEqual(inner.files.map(file => file.name), ['mem-strong', 'mem-mild', 'mem-semantic'], 'real lexical evidence changes the discounted inner ordering')
1062
- assert.ok(inner.files[2].fusion.rawRetrievalScore > inner.files[1].fusion.rawRetrievalScore, 'raw order is semantic before mild, the opposite of discounted order')
1063
- assert.equal(inner.debug.lexicalDominance.id, 'mem-strong')
1064
- const { primary, foreign } = rankingWorld(entries, {})
1065
- activate([primary.libraryId, foreign.libraryId])
1066
- retrieveHook = args => ({ files: args.db === vp.dbPathFor(primary.libraryId) ? [{ name: 'mem-semantic' }, { name: 'mem-strong' }] : [], segments: [], resources: [] })
1067
- const result = await memory.privateRecall({ exec: primary.exec, query, topK: 5, relevanceThreshold: 0 })
1068
- assert.equal(result.recallRoute, 'cross-library')
1069
- assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-strong', 'mem-mild', 'mem-semantic']))
1070
- assert.equal(result.fusion.crossLibraryLexical, 'unified-bm25')
1071
- assert.equal(result.fusion.crossLibrarySemantic, 'rank-only', 'hook files carry no scores, so the vector leg stays rank-only')
1072
- const strong = result.files.find(file => file.name === 'mem-strong')
1073
- const semantic = result.files.find(file => file.name === 'mem-semantic')
1074
- const mild = result.files.find(file => file.name === 'mem-mild')
1075
- // 统一语料此刻恰好等于主库三文档(外库为空),BM25 值与 realLexical 一致。
1076
- const topLex = scores.get('mem-strong')
1077
- assert.ok(topLex >= 24)
1078
- assert.equal(strong.lexical, topLex)
1079
- assert.equal(mild.lexical, scores.get('mem-mild'))
1080
- // 方法间 RRF:词法腿 strong=1 mild=2,向量腿(rank-only)semantic=1 strong=2。
1081
- const rrfStrong = 1 / 61 + 1 / 62
1082
- assert.ok(Math.abs(strong.fusion.rawRetrievalScore - 1) < 1e-12)
1083
- assert.ok(Math.abs(mild.fusion.rawRetrievalScore - (1 / 62) / rrfStrong) < 1e-12)
1084
- assert.ok(Math.abs(semantic.fusion.rawRetrievalScore - (1 / 61) / rrfStrong) < 1e-12, 'outer RRF is rebuilt from unified leg ranks, not the discounted inner order')
1085
- assert.equal(strong.fusion.bestRank, 1)
1086
- assert.equal(mild.fusion.bestRank, 2, 'outer rank comes from the unified lexical leg, not the discounted inner rank of two')
1087
- assert.equal(semantic.fusion.bestRank, 1)
1088
- const sigma = 1 / (1 + topLex / 50)
1089
- const mildDiscount = Math.sqrt(scores.get('mem-mild') / topLex)
1090
- assert.ok(mildDiscount > sigma, 'the mild fact genuinely exercises the square-root branch')
1091
- assert.ok(Math.abs(strong.retrievalScore - 1) < 1e-12)
1092
- assert.ok(Math.abs(mild.retrievalScore - (1 / 62) / rrfStrong * mildDiscount) < 1e-12)
1093
- assert.ok(Math.abs(semantic.retrievalScore - (1 / 61) / rrfStrong * sigma) < 1e-12, 'exactly one sigma, not multiplied by the inner share')
1094
- assert.ok(Math.abs(semantic.retrievalScore - (1 / 61) / rrfStrong * sigma * sigma) > 0.01)
1095
- assert.equal(result.fusion.lexicalDominance.id, 'mem-strong')
1096
- assert.equal(result.fusion.lexicalDominance.stage, 'eligible')
1097
- assert.equal(result.fusion.lexicalDominance.topLex, strong.lexical)
1098
- assert.equal(semantic.fusion.lexicalDominantId, 'mem-strong')
1099
- assert.equal(semantic.fusion.dominanceStage, 'eligible')
1100
- assert.equal(calls.filter(call => call.db === vp.dbPathFor(primary.libraryId)).length, 1)
1101
- assert.equal(calls.filter(call => call.db === vp.dbPathFor(foreign.libraryId)).length, 1)
1102
- await assertRankingBoundary(2)
1103
- })
1104
-
1105
- test('real BM25 two tied genuinely strong topical hits both survive without corpus padding', async () => {
1106
- const query = rankingWords.join(' ')
1107
- const entries = {
1108
- 'mem-tls-a': rankingEntry(rankingWords.slice(0, 26).join(' ')),
1109
- 'mem-tls-b': rankingEntry(rankingWords.slice(26).join(' ')),
1110
- }
1111
- const f = fixture(entries)
1112
- activate([f.libraryId])
1113
- retrieveHook = () => ({ files: [{ name: 'mem-tls-a' }, { name: 'mem-tls-b' }], segments: [], resources: [] })
1114
- const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8 })
1115
- assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-tls-a', 'mem-tls-b']))
1116
- for (const file of result.files) assert.ok(file.lexical >= 24, 'both hits are genuinely strong in this two-row corpus')
1117
- assert.equal(result.fusion.lexicalDominance, null, 'two near-equal lexical tops do not single out a dominant row')
1118
- await assertRankingBoundary(1)
1119
- })
1120
-
1121
- test('real BM25 QQ private-chat envelope and preference trailer preserve food as the top answer', async () => {
1122
- const query = '[私聊:900000001]22:11 Linxiu(900000001)[主人] #-100000001 [@咱]:桂花的,我江南小囡喜欢吃糖糕,还有豆沙米糕\n[管理员的长期偏好·优先遵守]请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。\n【本会话是QQ私聊:900000001。请用自然简洁的语气回答。】'
1123
- const now = Date.now()
1124
- const recentCreatedAt = new Date(now - 2 * 86_400_000).toISOString()
1125
- const f = fixture({
1126
- 'mem-food': rankingEntry(foodAnswer, { strength: 0.8, createdAt: recentCreatedAt }),
1127
- 'mem-template': rankingEntry('[管理员的长期偏好·优先遵守]请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。【本会话是QQ私聊:900000001。请用自然简洁的语气回答。】', { peak: true, createdAt: new Date(now - 4 * 86_400_000).toISOString() }),
1128
- 'mem-piano': rankingEntry(pianoNotes[0], { createdAt: recentCreatedAt }),
1129
- })
1130
- activate([f.libraryId])
1131
- retrieveHook = () => ({ files: [{ name: 'mem-template' }, { name: 'mem-food' }], segments: [], resources: [] })
1132
- const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.4 })
1133
- assert.equal(result.files[0]?.name, 'mem-food', 'QQ transport text is not evidence of the user topic: ' + JSON.stringify({ fusion: result.fusion, files: result.files.map(({ name, lexical, lexicalEvidence, retrievalScore, score, fusion }) => ({ name, lexical, lexicalEvidence, retrievalScore, score, fusion })) }))
1134
- assert.ok(result.files[0].lexical > 0 && result.files[0].lexicalEvidence > 0)
1135
- assert.notEqual(result.fusion.lexicalDominance?.id, 'mem-template')
1136
- assert.equal(calls[0].query, query, 'the semantic/index-facing query remains the original QQ message')
1137
- await assertRankingBoundary(1)
1138
- })
1139
-
1140
- test('real BM25 same-leg and cross-leg folding retain the absorbed topical lexical evidence', async () => {
1141
- const topic = rankingWords.join(' ')
1142
- const query = '请用自然简洁的语气回答。' + topic
1143
- const body = 'TLS故障已记录,请用自然简洁的语气回答。故障排查统一记录在运维台账。'
1144
- const entries = {
1145
- 'mem-a-host': rankingEntry(body, { tags: rankingWords.slice(0, 3) }),
1146
- 'mem-z-strong': rankingEntry(body, { tags: rankingWords }),
1147
- 'mem-piano': rankingEntry(pianoNotes[0]),
1148
- }
1149
- const originalScores = realLexical(entries, query)
1150
- const evidenceScores = realLexical(entries, topic)
1151
- assert.ok(evidenceScores.get('mem-z-strong') >= 24)
1152
- assert.ok(originalScores.get('mem-z-strong') > originalScores.get('mem-a-host'))
1153
- assert.ok(originalScores.get('mem-z-strong') > evidenceScores.get('mem-z-strong'), 'raw lexical includes the style overlap but evidence does not')
1154
- const f = fixture(entries)
1155
- activate([f.libraryId])
1156
- retrieveHook = () => ({ files: [{ name: 'mem-a-host' }, { name: 'mem-z-strong' }], segments: [], resources: [] })
1157
- const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8 })
1158
- assert.deepEqual(result.files.map(file => file.name), ['mem-a-host'], 'one real fact occupies one recall slot after both folding stages')
1159
- const host = result.files[0]
1160
- assert.equal(host.lexical, originalScores.get('mem-z-strong'), 'the absorbed source retains its stronger original BM25 score')
1161
- assert.equal(host.lexicalEvidence, evidenceScores.get('mem-z-strong'), 'topical BM25 evidence is inherited independently of raw lexical')
1162
- assert.deepEqual(host.mergedTogether, ['mem-z-strong'])
1163
- assert.ok(result.fusion.collapsed.some(group => group.kept === 'mem-z-strong' && group.dropped.includes('mem-a-host')), 'within-leg duplicate folding occurred')
1164
- assert.ok(result.fusion.collapsed.some(group => group.kept === 'mem-a-host' && group.dropped.includes('mem-z-strong')), 'semantic/cross-leg host absorbed the lexical source')
1165
- assert.equal(result.fusion.lexicalDominance.id, 'mem-a-host', 'the surviving host owns the final dominance trace')
1166
- assert.equal(result.fusion.lexicalDominance.topLex, host.lexicalEvidence)
1167
- assert.equal(host.fusion.rawRetrievalScore, 1)
1168
- await assertRankingBoundary(1)
1169
- })
1170
-
1171
- test('real BM25 Python in a request is topical evidence rather than a disposable reply template', async () => {
1172
- const query = '请用Python回答TLS故障原因'
1173
- const entries = {
1174
- 'mem-python': rankingEntry('请用Python回答TLS故障原因:Python ssl 模块报告证书过期。'),
1175
- 'mem-other': rankingEntry(pianoNotes[0]),
1176
- }
1177
- const f = fixture(entries)
1178
- activate([f.libraryId])
1179
- retrieveHook = () => ({ files: [], segments: [], resources: [] })
1180
- const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.4 })
1181
- assert.equal(result.files[0]?.name, 'mem-python', 'a topic-bearing imperative must not be cleared')
1182
- const hit = result.files[0]
1183
- assert.equal(hit.lexical, realLexical(entries, query).get('mem-python'))
1184
- assert.equal(hit.lexicalEvidence ?? hit.lexical, hit.lexical, 'Python/TLS are retained in dominance evidence')
1185
- assert.equal(calls[0].query, query)
1186
- await assertRankingBoundary(1)
1187
- })
1188
-
1189
- test('automatic recall backfills a sixth qualified hit and reintroduces a changed admitted revision', async () => {
1190
- state.updateSettings({ hybridRecall: true })
1191
- const names = Array.from({ length: 6 }, (_, i) => 'mem-replay-' + i)
1192
- const stamp = new Date(Date.now() - 86400000).toISOString()
1193
- const entries = Object.fromEntries(names.map((name, i) => [name, rankingEntry(`AtlasReplay 部署备份节点${i}保留14天,每天执行核验。`, { createdAt: stamp, updatedAt: stamp })]))
1194
- const f = fixture(entries)
1195
- activate([f.libraryId])
1196
- retrieveHook = () => ({ files: names.map(name => ({ name })), segments: [], resources: [] })
1197
- const query = 'AtlasReplay 部署备份保留14天'
1198
- const initial = await memory.privateRecall({ exec: f.exec, query, topK: 6, relevanceThreshold: 0.8, purpose: 'automatic' })
1199
- assert.equal(initial.groups.length, 6)
1200
- const shown = initial.refs.slice(0, 5)
1201
- state.markInjectedRefs(f.sessionId, shown, 1, { messageId: 'admitted-replay-five', hostTurn: 1 })
1202
- const excludedRefs = state.recentMemoryRefs(state.getSessionBinding(f.sessionId), 2, 16)
1203
- const next = await memory.privateRecall({ exec: f.exec, query, topK: 1, relevanceThreshold: 0.8, purpose: 'automatic', excludedRefs })
1204
- assert.equal(next.groups.length, 1)
1205
- assert.equal(next.files[0].name, initial.refs[5].id)
1206
- assert.equal(next.trace.counts.recentRows, 5)
1207
- const changedId = shown[0].id
1208
- await state.updatePrivateIndex(f.libraryId, index => { index.entries[changedId].content += ' 已补充副本验证。' })
1209
- const changed = await memory.privateRecall({ exec: f.exec, query, topK: 1, relevanceThreshold: 0.8, purpose: 'automatic', excludedRefs })
1210
- assert.equal(changed.files[0].name, changedId)
1211
- assert.notEqual(changed.refs[0].revision, shown[0].revision)
1212
- assert.equal(changed.groups[0].reintroducedForRevision, true)
1213
- await assertRankingBoundary(2)
1214
- })
1215
-
1216
- test('automatic recent exclusion cannot promote an unqualified lexical-only noise hit', async () => {
1217
- state.updateSettings({ hybridRecall: true })
1218
- const names = Array.from({ length: 5 }, (_, i) => 'mem-qualified-' + i)
1219
- const stamp = new Date(Date.now() - 86400000).toISOString()
1220
- const entries = Object.fromEntries(names.map((name, i) => [name, rankingEntry(`AtlasQuiet 部署备份节点${i}保留14天,每天执行核验。`, { createdAt: stamp, updatedAt: stamp })]))
1221
- entries['mem-quiet-noise'] = rankingEntry('AtlasQuiet 的闲聊杂谈,没有备份安排。', { createdAt: stamp, updatedAt: stamp })
1222
- const f = fixture(entries)
1223
- activate([f.libraryId])
1224
- retrieveHook = () => ({ files: names.map(name => ({ name })), segments: [], resources: [] })
1225
- const query = 'AtlasQuiet 部署备份保留14天'
1226
- const initial = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8, purpose: 'automatic' })
1227
- assert.equal(initial.refs.length, 5)
1228
- state.markInjectedRefs(f.sessionId, initial.refs, 1, { messageId: 'admitted-qualified-five', hostTurn: 1 })
1229
- const next = await memory.privateRecall({ exec: f.exec, query, topK: 1, relevanceThreshold: 0.8, purpose: 'automatic', excludedRefs: state.recentMemoryRefs(state.getSessionBinding(f.sessionId), 2, 16) })
1230
- assert.deepEqual(next.files, [])
1231
- assert.ok(next.trace.counts.weakRows > 0)
1232
- assert.equal(next.trace.counts.recentRows, 5)
1233
- await assertRankingBoundary(2)
1234
- })
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+ import { registerHooks } from 'node:module'
7
+
8
+ // No engine, worker, download or real library is used: all stores live here and
9
+ // the engine boundary is replaced before either production module is imported.
10
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-managed-memory-'))
11
+ process.env.DSH_MEMU_HOME = home
12
+ process.env.DSH_MEMU_MEMORY_HOME = home
13
+ const calls = []
14
+ const warnings = []
15
+ const rebuildProbes = []
16
+ const backendRows = new Map()
17
+ const backendKey = (db, name) => JSON.stringify([db, name])
18
+ let commitHook = null
19
+ let retrieveHook = null
20
+ let failCommit = false
21
+ let failForget = false
22
+ let forgetHook = null
23
+ let vp
24
+
25
+ globalThis.__managedMemoryTest = {
26
+ async commit(args) {
27
+ calls.push({ op: 'commit', ...args })
28
+ // The lease invariant only exists while there is a generation to protect. A
29
+ // requested-but-never-migrated profile writes without vectors on purpose.
30
+ if (args.route === 'managed-local' && vp.hasActiveVectorGeneration()) {
31
+ assert.ok(Object.keys(vp.activeVectorState().writeGuard.leases).length, 'lease spans MemU await')
32
+ }
33
+ if (commitHook) await commitHook(args)
34
+ if (failCommit) throw new Error('mock managed commit failed')
35
+ for (const row of args.payload.recall_files) backendRows.set(backendKey(args.db, row.name), structuredClone(row))
36
+ return { ok: true }
37
+ },
38
+ async retrieve(args) {
39
+ calls.push({ op: 'retrieve', ...args })
40
+ return retrieveHook ? retrieveHook(args) : { files: [], segments: [], resources: [], raw: null }
41
+ },
42
+ async forget(args) {
43
+ calls.push({ op: 'forget', ...args })
44
+ if (args.route === 'managed-local' && vp.hasActiveVectorGeneration()) assert.ok(Object.keys(vp.activeVectorState().writeGuard.leases).length)
45
+ if (forgetHook) return forgetHook(args)
46
+ if (failForget) throw new Error('mock managed forget failed')
47
+ backendRows.delete(backendKey(args.db, args.name))
48
+ return { deleted: 1, segments: 1 }
49
+ },
50
+ async listFiles() { throw new Error('unexpected list engine call') },
51
+ async maybeAutoRebuildVectorGeneration(...args) {
52
+ rebuildProbes.push(args)
53
+ return { stubbed: true }
54
+ },
55
+ }
56
+ const vectorServiceUrl = 'data:text/javascript,' + encodeURIComponent('export const maybeAutoRebuildVectorGeneration = globalThis.__managedMemoryTest.maybeAutoRebuildVectorGeneration;')
57
+ const engineSource = 'const bridge = globalThis.__managedMemoryTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles, closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
58
+ const hooks = registerHooks({
59
+ resolve(specifier, context, nextResolve) {
60
+ if (specifier === './memu.js') {
61
+ return { url: 'data:text/javascript,' + encodeURIComponent(engineSource), shortCircuit: true }
62
+ }
63
+ // managedRecall 的缺库分支会动态 import 向量服务做自动追平探测。这里只拦截
64
+ // memory.js 发起的那一次(父 URL 限定),别的模块照常拿真实现——否则空转的
65
+ // force 重建会把嵌入 worker 拉进单元测试。
66
+ if (specifier === './local-vector-service.js' && context.parentURL === new URL('../lib/memory.js', import.meta.url).href) {
67
+ return { url: vectorServiceUrl, shortCircuit: true }
68
+ }
69
+ return nextResolve(specifier, context)
70
+ },
71
+ })
72
+ const state = await import('../lib/state.js')
73
+ vp = await import('../lib/vector-profile.js')
74
+ const paths = await import('../lib/paths.js')
75
+ const memory = await import('../lib/memory.js')
76
+ const curator = await import('../lib/curator.js')
77
+ const activity = await import('../lib/activity-log.js')
78
+ const { buildCorpus, bm25, tokenize } = await import('../lib/text-retrieval.js')
79
+ const profile = vp.profileFromCatalog('bge-small-zh-v1.5-int8')
80
+ const activeFile = vp.vectorActiveFile()
81
+ let serial = 0
82
+
83
+ function entry(content, extra = {}) {
84
+ return { status: 'active', title: content, content, layer: 'long_term', strength: 1,
85
+ createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ...extra }
86
+ }
87
+ function fixture(entries = {}) {
88
+ serial += 1
89
+ const sessionId = 'managed-' + serial
90
+ const cwd = path.join(home, 'project-' + serial)
91
+ const binding = state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
92
+ state.setSessionBinding(sessionId, { useLibrary: true, useGlobal: true, domainOverride: 'coding' })
93
+ state.savePrivateIndex(binding.libraryId, { entries })
94
+ return { sessionId, libraryId: binding.libraryId, exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } } }
95
+ }
96
+ function activate(libraryIds = []) {
97
+ const databases = vp.buildDatabaseSet({ profile, generation: 1, libraryIds })
98
+ fs.mkdirSync(path.join(home, 'libraries'), { recursive: true })
99
+ for (const row of [databases.global, ...Object.values(databases.libraries)]) fs.writeFileSync(vp.resolveVectorPath(row.path), '')
100
+ vp.updateVectorStateSync(current => ({ ...current, generation: 1, requested: null, pending: null,
101
+ active: { status: 'active', generation: 1, fingerprint: profile.fingerprint, profile, databases } }))
102
+ return databases
103
+ }
104
+ function job() { return { step: '', abort: new AbortController() } }
105
+ function curated(extra = {}) {
106
+ return { op: 'create', domain: 'coding', title: 'global decision', content: 'global implementation decision',
107
+ evidence: [{ session_id: 'source-session', quote: 'explicit decision' }], ...extra }
108
+ }
109
+
110
+ test.beforeEach(() => {
111
+ fs.rmSync(activeFile, { force: true })
112
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'local', relevanceThreshold: 0, crossLibraryRecall: false })
113
+ state.saveGlobalIndex({ entries: {} })
114
+ calls.length = 0
115
+ warnings.length = 0
116
+ rebuildProbes.length = 0
117
+ commitHook = null
118
+ retrieveHook = null
119
+ failCommit = false
120
+ failForget = false
121
+ forgetHook = null
122
+ backendRows.clear()
123
+ paths.setWarnSink(message => warnings.push(String(message)))
124
+ })
125
+ test.after(() => {
126
+ hooks.deregister()
127
+ delete globalThis.__managedMemoryTest
128
+ paths.setWarnSink(null)
129
+ fs.rmSync(home, { recursive: true, force: true })
130
+ })
131
+
132
+ test('fresh defaults disable all vector routes while retaining local as the selected source', () => {
133
+ assert.equal(state.DEFAULT_SETTINGS.memoryBackend, 'agent')
134
+ assert.equal(state.DEFAULT_SETTINGS.vectorSource, 'local')
135
+ // 召回默认值为 5/5(原来是 3/2)。
136
+ assert.equal(state.DEFAULT_SETTINGS.privateTopK, 5)
137
+ assert.equal(state.DEFAULT_SETTINGS.globalTopK, 5)
138
+ assert.equal(state.effectiveVectorRoute(state.DEFAULT_SETTINGS), 'lexical')
139
+ assert.equal(state.vectorBackendEnabled(state.DEFAULT_SETTINGS), false)
140
+ })
141
+
142
+ test('managed local private recall fuses real lexical and vector ids without LLM', async () => {
143
+ const f = fixture({ 'mem-needle': entry('needle local match'), 'mem-orbit': entry('orbital mechanics') })
144
+ activate([f.libraryId])
145
+ retrieveHook = () => ({ files: [{ name: 'mem-orbit' }], segments: [], resources: [] })
146
+ const result = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8 })
147
+ assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-needle', 'mem-orbit']))
148
+ assert.equal(result.recallRoute, 'managed-vector-rrf')
149
+ assert.equal(calls[0].db, vp.dbPathFor(f.libraryId))
150
+ })
151
+
152
+ test('corrupt managed intent cannot call LLM or legacy API and preserves lexical ids', async () => {
153
+ const f = fixture({ 'mem-needle': entry('needle local match') })
154
+ state.updateSettings({ memoryBackend: 'api' })
155
+ fs.writeFileSync(activeFile, '{bad-json')
156
+ const result = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8 })
157
+ assert.deepEqual(result.files.map(file => file.name), ['mem-needle'])
158
+ assert.equal(result.recallRoute, 'local-fallback')
159
+ assert.match(state.getSessionBinding(f.sessionId).lastRecallError, /not valid JSON/)
160
+ assert.ok(warnings.length)
161
+ assert.equal(calls.length, 0)
162
+ })
163
+
164
+ // 跨库召回遇到没有向量库的库时,缺库诊断只适用于有内容的库。
165
+ // 空库(旧工作区遗留,索引 0 条)local-only 与语义召回的结果都是空——每轮给它刷
166
+ // "向量库未生成" warn 会产生重复噪音。
167
+ function vectorDegradeRows(libraryId) {
168
+ return activity.listEvents({ kind: 'vector', limit: 100 })
169
+ .filter(row => row.message === '向量库未生成,召回降级 local-only' && row.detail?.libraryId === libraryId)
170
+ }
171
+
172
+ async function settleRebuildProbes() {
173
+ // Join the same data-module import and drain its fire-and-forget .then callback.
174
+ // Importing the bridge itself does not call the probe or start a real worker.
175
+ await import(vectorServiceUrl)
176
+ await new Promise(resolve => setImmediate(resolve))
177
+ }
178
+
179
+ function trackIndexAccess(t, files) {
180
+ const access = { clones: 0, stats: new Map(files.map(file => [file, 0])) }
181
+ const clone = globalThis.structuredClone
182
+ t.mock.method(globalThis, 'structuredClone', (value, ...args) => {
183
+ if (value?.entries && !Array.isArray(value.entries)) access.clones += 1
184
+ return clone(value, ...args)
185
+ })
186
+ const stat = fs.statSync
187
+ t.mock.method(fs, 'statSync', (file, ...args) => {
188
+ if (access.stats.has(file)) access.stats.set(file, access.stats.get(file) + 1)
189
+ return stat(file, ...args)
190
+ })
191
+ return access
192
+ }
193
+
194
+ test('an empty library without a vector db recalls silently — no degrade noise, no rebuild probe', async () => {
195
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'local' })
196
+ const empty = fixture({})
197
+ activate([]) // 活跃代际只含全局库:该库的向量库必然缺席
198
+ const result = await memory.privateRecall({ exec: empty.exec, query: 'anything', topK: 5 })
199
+ await settleRebuildProbes()
200
+ assert.equal(result.recallRoute, 'local-fallback')
201
+ assert.deepEqual(result.files, [], 'an empty library has nothing to recall')
202
+ assert.deepEqual(result.errors || [], [])
203
+ assert.deepEqual(warnings, [], 'an empty library must not warn')
204
+ assert.equal(vectorDegradeRows(empty.libraryId).length, 0, 'an empty library must not log the degrade warning')
205
+ assert.equal(rebuildProbes.length, 0, 'an empty library must not probe a rebuild')
206
+ assert.equal(calls.length, 0)
207
+ })
208
+
209
+ test('a library with content but no vector db keeps the degrade diagnostic and probes the rebuild', async () => {
210
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'local' })
211
+ const rich = fixture({ 'mem-rich': entry('needle real content that semantic recall would serve') })
212
+ activate([]) // 同上:库不在代际里,但索引里有内容——这是真正值得诊断的缺库
213
+ const result = await memory.privateRecall({ exec: rich.exec, query: 'needle', topK: 5 })
214
+ await settleRebuildProbes()
215
+ assert.equal(result.recallRoute, 'local-fallback')
216
+ assert.deepEqual(result.files.map(file => file.name), ['mem-rich'])
217
+ assert.deepEqual(result.errors || [], [], 'missing registration is diagnostic, not a recall error')
218
+ assert.equal(warnings.length, 1)
219
+ assert.ok(warnings[0].includes('has no database for library ' + rich.libraryId))
220
+ assert.equal(vectorDegradeRows(rich.libraryId).length, 1, 'content-bearing libraries keep the diagnostic')
221
+ assert.equal(rebuildProbes.length, 1, 'content-bearing libraries probe the rebuild')
222
+ assert.equal(calls.length, 0)
223
+ })
224
+
225
+ test('an empty library resumes missing-db diagnostics after its first index entry is saved', async () => {
226
+ const f = fixture()
227
+ activate([])
228
+ const empty = await memory.privateRecall({ exec: f.exec, query: 'needle', purpose: 'automatic' })
229
+ await settleRebuildProbes()
230
+ assert.deepEqual(empty.files, [])
231
+ assert.deepEqual(warnings, [])
232
+ assert.equal(vectorDegradeRows(f.libraryId).length, 0)
233
+ assert.equal(rebuildProbes.length, 0)
234
+
235
+ // A backfill must invalidate emptiness immediately; no new cache or enrollment.
236
+ state.savePrivateIndex(f.libraryId, { entries: { 'mem-first': entry('needle first backfilled fact') } })
237
+ const filled = await memory.privateRecall({ exec: f.exec, query: 'needle', purpose: 'automatic' })
238
+ await settleRebuildProbes()
239
+ assert.deepEqual(filled.files.map(file => file.name), ['mem-first'])
240
+ assert.equal(filled.recallRoute, 'local-fallback')
241
+ assert.equal(warnings.length, 1)
242
+ assert.ok(warnings[0].includes('has no database for library ' + f.libraryId))
243
+ assert.equal(vectorDegradeRows(f.libraryId).length, 1)
244
+ assert.equal(rebuildProbes.length, 1)
245
+ assert.equal(calls.length, 0)
246
+ })
247
+
248
+ test('missing-db recall reuses loaded indexes on repeated warm-cache calls', async t => {
249
+ const f = fixture({ 'mem-budget': entry('needle snapshot budget') })
250
+ activate([])
251
+ state.loadPrivateIndex(f.libraryId) // Warm the state index cache before spying.
252
+ const indexFile = path.join(paths.indexDir(), f.libraryId + '.json')
253
+ const access = trackIndexAccess(t, [indexFile])
254
+ for (let round = 1; round <= 2; round += 1) {
255
+ const result = await memory.privateRecall({ exec: f.exec, query: 'needle', purpose: 'automatic' })
256
+ await settleRebuildProbes()
257
+ assert.deepEqual(result.files.map(file => file.name), ['mem-budget'])
258
+ // Two source snapshots clone twice each; the one hit also checks the existing
259
+ // relation-inverted-index signature (stat only, no snapshot).
260
+ assert.equal(access.stats.get(indexFile), 3 * round, 'two index reads plus one relation signature stat')
261
+ assert.equal(access.clones, 4 * round, 'no extra full-index clones, regardless of corpus size')
262
+ assert.equal(rebuildProbes.length, round, 'the fallback remains uncached and diagnostic')
263
+ }
264
+ })
265
+
266
+ test('cross-library missing-db diagnostics use the full source before domain filtering without extra snapshots', async t => {
267
+ const current = fixture({ 'mem-current': entry('needle current fact') })
268
+ const foreign = fixture({ 'mem-other-domain': entry('needle other world', { domain: 'rp' }) })
269
+ const empty = fixture()
270
+ const domain = 'project:' + current.sessionId
271
+ for (const f of [current, foreign, empty]) state.setSessionBinding(f.sessionId, { domainOverride: domain })
272
+ state.updateSettings({ crossLibraryRecall: true })
273
+ activate([])
274
+ const indexFiles = [current, foreign, empty].map(f => path.join(paths.indexDir(), f.libraryId + '.json'))
275
+ const access = trackIndexAccess(t, indexFiles)
276
+ const result = await memory.privateRecall({ exec: current.exec, query: 'needle', purpose: 'automatic' })
277
+ await settleRebuildProbes()
278
+ assert.equal(result.recallRoute, 'cross-library')
279
+ assert.deepEqual(new Set(result.libraries), new Set([current.libraryId, foreign.libraryId, empty.libraryId]))
280
+ assert.deepEqual(result.files.map(file => file.name), ['mem-current'], 'the foreign domain contributes no hits')
281
+ assert.deepEqual(result.errors, [])
282
+ assert.equal(warnings.length, 2, 'only the two content-bearing libraries warn')
283
+ for (const f of [current, foreign]) {
284
+ assert.ok(warnings.some(message => message.includes('has no database for library ' + f.libraryId)))
285
+ assert.equal(vectorDegradeRows(f.libraryId).length, 1)
286
+ }
287
+ assert.equal(vectorDegradeRows(empty.libraryId).length, 0)
288
+ assert.equal(rebuildProbes.length, 2, 'a domain-filtered empty view still needs a rebuild probe')
289
+ assert.equal(calls.length, 0)
290
+ assert.deepEqual(indexFiles.map(file => access.stats.get(file)), [3, 1, 1], 'only the primary hit adds a relation signature stat')
291
+ assert.equal(access.clones, 8, 'three source loads plus the existing primary refresh only')
292
+ })
293
+
294
+ test('by-id private recall still short-circuits vector IO and missing-db diagnostics', async t => {
295
+ const f = fixture({ 'mem-byid': entry('needle direct lookup') })
296
+ const databases = activate([])
297
+ const globalDb = vp.resolveVectorPath(databases.global.path)
298
+ fs.rmSync(globalDb)
299
+ const indexFile = path.join(paths.indexDir(), f.libraryId + '.json')
300
+ const access = trackIndexAccess(t, [indexFile, globalDb])
301
+ const read = t.mock.method(fs, 'readFileSync')
302
+ const result = await memory.privateRecall({ exec: f.exec, query: 'mem-byid', purpose: 'automatic' })
303
+ await settleRebuildProbes()
304
+ assert.deepEqual(result.files.map(file => file.name), ['mem-byid'])
305
+ assert.equal(result.recallRoute, 'local')
306
+ assert.deepEqual(warnings, [])
307
+ assert.equal(vectorDegradeRows(f.libraryId).length, 0)
308
+ assert.equal(rebuildProbes.length, 0)
309
+ assert.equal(calls.length, 0)
310
+ assert.equal(read.mock.calls.some(call => call.arguments[0] === activeFile), false, 'by-id does not read vector state')
311
+ assert.equal(access.stats.get(globalDb), 0, 'by-id does not validate vector databases')
312
+ assert.equal(access.stats.get(indexFile), 3, 'two index reads plus the existing relation signature stat')
313
+ assert.equal(access.clones, 4)
314
+ })
315
+
316
+ test('global recall uses the null library route even for an empty index and adds no index snapshots', async t => {
317
+ const f = fixture({ 'mem-private': entry('needle private-only fact') })
318
+ activate([f.libraryId])
319
+ const globalDb = vp.dbPathFor(null)
320
+ const empty = await memory.globalRecall({ exec: f.exec, query: 'needle' })
321
+ assert.deepEqual(empty.files, [])
322
+ assert.equal(empty.recallRoute, 'managed-vector-rrf')
323
+ assert.equal(calls.length, 1, 'an empty index must not suppress an existing vector route')
324
+ assert.equal(calls[0].db, globalDb)
325
+
326
+ state.saveGlobalIndex({ entries: {
327
+ 'gmem-needle': entry('needle global fact', { domain: 'coding' }),
328
+ 'gmem-other': entry('needle other world', { domain: 'rp' }),
329
+ } })
330
+ const indexFile = path.join(paths.indexDir(), 'global.json')
331
+ const access = trackIndexAccess(t, [indexFile])
332
+ const result = await memory.globalRecall({ exec: f.exec, query: 'needle' })
333
+ await settleRebuildProbes()
334
+ assert.deepEqual(result.files.map(file => file.name), ['gmem-needle'])
335
+ assert.equal(result.recallRoute, 'managed-vector-rrf')
336
+ assert.equal(calls.length, 2)
337
+ assert.equal(calls[1].db, globalDb, 'libraryId=null must select global, not private')
338
+ assert.equal(calls[1].route, 'managed-local')
339
+ assert.deepEqual(warnings, [])
340
+ assert.equal(vectorDegradeRows(null).length, 0)
341
+ assert.equal(rebuildProbes.length, 0)
342
+ assert.equal(access.stats.get(indexFile), 2)
343
+ assert.equal(access.clones, 4)
344
+ })
345
+
346
+ for (const content of ['empty', 'other-domain', 'matching']) {
347
+ test(`a physically missing global database remains an error with ${content} content`, async () => {
348
+ const f = fixture()
349
+ const databases = activate([])
350
+ if (content !== 'empty') state.saveGlobalIndex({ entries: {
351
+ 'gmem-needle': entry('needle global fact', { domain: content === 'matching' ? 'coding' : 'rp' }),
352
+ } })
353
+ const globalDb = vp.resolveVectorPath(databases.global.path)
354
+ fs.rmSync(globalDb)
355
+ const result = await memory.globalRecall({ exec: f.exec, query: 'needle' })
356
+ await settleRebuildProbes()
357
+ assert.deepEqual(result.files.map(file => file.name), content === 'matching' ? ['gmem-needle'] : [])
358
+ assert.equal(result.recallRoute, 'local-fallback')
359
+ assert.equal(result.errors.length, 1)
360
+ assert.match(result.errors[0], /a database in the active generation is missing/)
361
+ assert.match(state.getSessionBinding(f.sessionId).lastRecallError, /a database in the active generation is missing/)
362
+ assert.equal(warnings.length, 1)
363
+ assert.ok(warnings[0].includes(path.basename(globalDb)))
364
+ assert.equal(vectorDegradeRows(null).length, 0, 'torn state is not ordinary missing registration')
365
+ assert.equal(rebuildProbes.length, 0)
366
+ assert.equal(calls.length, 0)
367
+ })
368
+ }
369
+
370
+ test('agent backend stays lexical even when a local profile is active', async () => {
371
+ const f = fixture({ 'mem-needle': entry('needle local match') })
372
+ activate([f.libraryId])
373
+ state.updateSettings({ memoryBackend: 'agent', vectorSource: 'local' })
374
+ retrieveHook = () => { throw new Error('agent route must not call MemU') }
375
+ const result = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8 })
376
+ assert.deepEqual(result.files.map(file => file.name), ['mem-needle'])
377
+ assert.equal(result.recallRoute, 'local')
378
+ assert.equal(calls.length, 0)
379
+ assert.equal(state.effectiveVectorRoute(), 'lexical')
380
+ assert.equal(state.vectorBackendEnabled(), false)
381
+ })
382
+
383
+ test('remote-api ignores an active local profile and passes explicit remote route', async () => {
384
+ const f = fixture({ 'mem-needle': entry('needle local match') })
385
+ activate([f.libraryId])
386
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'api' })
387
+ retrieveHook = () => ({ files: [{ name: 'mem-needle' }], segments: [], resources: [] })
388
+ const result = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8 })
389
+ assert.equal(result.recallRoute, 'managed-vector-rrf')
390
+ assert.equal(calls[0].route, 'remote-api')
391
+ assert.notEqual(calls[0].db, vp.dbPathFor(f.libraryId))
392
+ })
393
+
394
+ test('invalid profile is a managed lexical fallback, never a remote fallback', async () => {
395
+ const f = fixture({ 'mem-needle': entry('needle local match') })
396
+ activate([f.libraryId])
397
+ vp.updateVectorStateSync(current => ({ ...current, active: { ...current.active,
398
+ profile: { ...current.active.profile, catalogId: 'missing-catalog-entry' } } }))
399
+ const result = await memory.privateRecall({ exec: f.exec, query: 'needle', topK: 8 })
400
+ assert.deepEqual(result.files.map(file => file.name), ['mem-needle'])
401
+ assert.match(state.getSessionBinding(f.sessionId).lastRecallError, /catalog/)
402
+ assert.equal(calls.length, 0)
403
+ })
404
+
405
+ test('global managed recall fuses by domain and records semantic errors despite lexical hits', async () => {
406
+ const f = fixture()
407
+ activate([f.libraryId])
408
+ state.saveGlobalIndex({ entries: { 'gmem-needle': entry('needle global match', { domain: 'coding' }),
409
+ 'gmem-orbit': entry('orbital mechanics', { domain: 'coding' }), 'gmem-other': entry('needle other world', { domain: 'rp' }) } })
410
+ retrieveHook = () => { throw new Error('worker unavailable') }
411
+ const failed = await memory.globalRecall({ exec: f.exec, query: 'needle', topK: 8 })
412
+ assert.deepEqual(failed.files.map(file => file.name), ['gmem-needle'])
413
+ assert.equal(failed.recallRoute, 'local-fallback')
414
+ assert.match(state.getSessionBinding(f.sessionId).lastRecallError, /worker unavailable/)
415
+ retrieveHook = () => ({ files: [{ name: 'gmem-orbit' }, { name: 'gmem-other' }] })
416
+ const healthy = await memory.globalRecall({ exec: f.exec, query: 'needle', topK: 8 })
417
+ assert.deepEqual(new Set(healthy.files.map(file => file.name)), new Set(['gmem-needle', 'gmem-orbit']))
418
+ assert.equal(healthy.recallRoute, 'managed-vector-rrf')
419
+ assert.equal(state.getSessionBinding(f.sessionId).lastRecallError, undefined)
420
+ })
421
+
422
+ test('new library enrolls inside lease before first managed commit and lease spans index write', async () => {
423
+ const f = fixture()
424
+ activate()
425
+ let entered
426
+ let release
427
+ const started = new Promise(resolve => { entered = resolve })
428
+ const gate = new Promise(resolve => { release = resolve })
429
+ commitHook = async args => {
430
+ assert.equal(args.db, vp.dbPathFor(f.libraryId))
431
+ assert.equal(Object.keys(state.loadPrivateIndex(f.libraryId).entries).length, 0)
432
+ entered()
433
+ await gate
434
+ }
435
+ const writing = memory.privateRemember({ exec: f.exec, content: 'new managed fact', title: 'new managed fact' })
436
+ await started
437
+ await assert.rejects(vp.withVectorWriteFreeze(() => {}), { code: 'VECTOR_WRITE_BUSY' })
438
+ release()
439
+ const result = await writing
440
+ assert.equal(state.loadPrivateIndex(f.libraryId).entries[result.id].content, 'new managed fact')
441
+ assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
442
+ assert.ok(vp.activeVectorState().active.databases.libraries[f.libraryId])
443
+ })
444
+
445
+ test('nonempty old library must rebuild rather than silently enroll an empty vector DB', async () => {
446
+ const f = fixture({ 'mem-existing': entry('old stored fact') })
447
+ activate()
448
+ await assert.rejects(memory.privateRemember({ exec: f.exec, content: 'new different fact' }), { code: 'VECTOR_LIBRARY_REBUILD_REQUIRED' })
449
+ assert.equal(calls.length, 0)
450
+ assert.deepEqual(Object.keys(state.loadPrivateIndex(f.libraryId).entries), ['mem-existing'])
451
+ })
452
+
453
+ test('freeze rejects every async write before engine or index mutation', async () => {
454
+ const f = fixture({ 'mem-live': entry('live fact'), 'mem-held': entry('held claim', { status: 'pending_review' }),
455
+ 'mem-archived': entry('old archived', { status: 'archived' }) })
456
+ activate([f.libraryId])
457
+ const before = JSON.stringify(state.loadPrivateIndex(f.libraryId))
458
+ await vp.withVectorWriteFreeze(async () => {
459
+ const writes = [
460
+ () => memory.privateRemember({ exec: f.exec, content: 'new fact' }),
461
+ () => memory.importMemories({ libraryId: f.libraryId, memories: [{ content: 'restored fact' }] }),
462
+ () => memory.privateUpdate({ exec: f.exec, id: 'mem-live', content: 'updated fact' }),
463
+ () => memory.privateDelete({ exec: f.exec, id: 'mem-archived' }),
464
+ () => memory.resolveMemoryReview({ libraryId: f.libraryId, id: 'mem-held', action: 'accept' }),
465
+ () => curator.commitCuratorOutput({ memories: [curated()] }, { job: job() }),
466
+ ]
467
+ for (const write of writes) await assert.rejects(write(), { code: 'VECTOR_WRITE_FROZEN' })
468
+ })
469
+ assert.equal(JSON.stringify(state.loadPrivateIndex(f.libraryId)), before)
470
+ assert.equal(calls.length, 0)
471
+ assert.deepEqual(state.loadGlobalIndex().entries, {})
472
+ })
473
+
474
+ test('managed agent update import delete and review call engine under lease; held edits stay index-only', async () => {
475
+ const f = fixture({ 'mem-live': entry('live fact'), 'mem-held': entry('held claim', { status: 'pending_review' }),
476
+ 'mem-archived': entry('old archived', { status: 'archived' }) })
477
+ activate([f.libraryId])
478
+ await memory.privateUpdate({ exec: f.exec, id: 'mem-live', content: 'new implementation fact' })
479
+ await memory.privateUpdate({ exec: f.exec, id: 'mem-held', content: 'edited held claim' })
480
+ assert.equal(calls.length, 1, 'pending_review edit never commits')
481
+ await memory.resolveMemoryReview({ libraryId: f.libraryId, id: 'mem-held', action: 'accept' })
482
+ await memory.importMemories({ libraryId: f.libraryId, memories: [{ content: 'restored unique observation' }] })
483
+ await memory.privateDelete({ exec: f.exec, id: 'mem-archived' })
484
+ assert.deepEqual(calls.map(call => call.op), ['commit', 'commit', 'commit', 'forget'])
485
+ assert.equal(state.loadPrivateIndex(f.libraryId).entries['mem-archived'], undefined)
486
+ })
487
+
488
+ test('post-CAS remember failure compensates the newly committed backend row', async () => {
489
+ const f = fixture()
490
+ activate([f.libraryId])
491
+ commitHook = async () => state.setSessionBinding(f.sessionId, { libraryId: 'rebound-library' })
492
+ await assert.rejects(
493
+ memory.privateRemember({ exec: f.exec, content: 'must compensate', title: 'must compensate' }),
494
+ /memory scope changed during write; retry/,
495
+ )
496
+ assert.deepEqual(calls.map(call => call.op), ['commit', 'forget'])
497
+ assert.equal(calls[1].db, calls[0].db, 'cleanup uses the captured database after rebind')
498
+ assert.equal(calls[1].name, calls[0].payload.recall_files[0].name)
499
+ assert.equal(backendRows.size, 0, 'no orphan survives in the fake backend')
500
+ assert.deepEqual(state.loadPrivateIndex(f.libraryId).entries, {})
501
+ assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
502
+ })
503
+
504
+ test('post-CAS update failure deletes the new row and restores the old backend payload', async () => {
505
+ const old = entry('old backend fact', { title: 'old title' })
506
+ const f = fixture({ 'mem-live': old })
507
+ activate([f.libraryId])
508
+ commitHook = async () => state.setSessionBinding(f.sessionId, { libraryId: 'rebound-library' })
509
+ await assert.rejects(
510
+ memory.privateUpdate({ exec: f.exec, id: 'mem-live', content: 'new backend fact', title: 'new title' }),
511
+ /memory scope changed during update; retry/,
512
+ )
513
+ assert.deepEqual(calls.map(call => call.op), ['commit', 'forget', 'commit'])
514
+ assert.equal(calls[2].payload.recall_files[0].content, old.content)
515
+ assert.equal(calls[2].payload.recall_files[0].description, old.title)
516
+ assert.equal(calls[1].db, calls[0].db)
517
+ assert.equal(calls[2].db, calls[0].db)
518
+ assert.equal(backendRows.get(backendKey(calls[0].db, 'mem-live')).content, old.content)
519
+ assert.deepEqual(state.loadPrivateIndex(f.libraryId).entries['mem-live'], old)
520
+ assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
521
+ })
522
+
523
+ test('uncertain backend compensation is visible instead of reported as a successful write', async () => {
524
+ const f = fixture()
525
+ activate([f.libraryId])
526
+ commitHook = async () => state.setSessionBinding(f.sessionId, { libraryId: 'rebound-library' })
527
+ failForget = true
528
+ await assert.rejects(
529
+ memory.privateRemember({ exec: f.exec, content: 'uncertain backend state' }),
530
+ error => error?.code === 'PRIVATE_BACKEND_COMPENSATION_FAILED' && /compensation uncertain/.test(error.message)
531
+ && /memory scope changed/.test(error.cause?.message) && /mock managed forget failed/.test(error.compensationError?.message),
532
+ )
533
+ assert.deepEqual(calls.map(call => call.op), ['commit', 'forget'])
534
+ })
535
+
536
+ test('a failed restore is reported as uncertain and never erases the authoritative index', async () => {
537
+ const f = fixture({ 'mem-live': entry('original backend payload') })
538
+ activate([f.libraryId])
539
+ const original = state.loadPrivateIndex(f.libraryId).entries['mem-live']
540
+ let count = 0
541
+ commitHook = async () => {
542
+ if (++count > 1) throw new Error('restore unavailable')
543
+ state.setSessionBinding(f.sessionId, { useLibrary: false })
544
+ }
545
+ await assert.rejects(memory.privateUpdate({ exec: f.exec, id: 'mem-live', content: 'rejected edit' }), error => {
546
+ assert.equal(error.code, 'PRIVATE_BACKEND_COMPENSATION_FAILED')
547
+ assert.match(error.compensationError.message, /restore unavailable/)
548
+ return true
549
+ })
550
+ assert.deepEqual(calls.map(call => call.op), ['commit', 'forget', 'commit'])
551
+ assert.deepEqual(state.loadPrivateIndex(f.libraryId).entries['mem-live'], original)
552
+ assert.ok(warnings.some(warning => /compensation uncertain/.test(warning)))
553
+ })
554
+
555
+ test('unparseable compensation acknowledgement is visibly uncertain', async () => {
556
+ const f = fixture()
557
+ activate([f.libraryId])
558
+ commitHook = async () => state.setSessionBinding(f.sessionId, { useLibrary: false })
559
+ forgetHook = async () => ({ deleted: 0, parseWarning: 'mock non-JSON acknowledgement' })
560
+ await assert.rejects(memory.privateRemember({ exec: f.exec, content: 'rejected new payload' }), {
561
+ code: 'PRIVATE_BACKEND_COMPENSATION_FAILED',
562
+ })
563
+ assert.equal(backendRows.size, 1, 'uncertain cleanup is not claimed to remove the orphan')
564
+ assert.deepEqual(state.loadPrivateIndex(f.libraryId).entries, {})
565
+ forgetHook = async () => ({ ok: true })
566
+ state.setSessionBinding(f.sessionId, { useLibrary: true })
567
+ await assert.rejects(memory.privateRemember({ exec: f.exec, content: 'malformed delete acknowledgement' }), {
568
+ code: 'PRIVATE_BACKEND_COMPENSATION_FAILED',
569
+ })
570
+ })
571
+
572
+ test('a concurrently replaced index refuses destructive compensation', async () => {
573
+ const f = fixture({ 'mem-live': entry('original backend payload') })
574
+ activate([f.libraryId])
575
+ commitHook = async () => state.updatePrivateIndex(f.libraryId, index => {
576
+ index.entries['mem-live'].content = 'externally replaced authoritative value'
577
+ })
578
+ await assert.rejects(memory.privateUpdate({ exec: f.exec, id: 'mem-live', content: 'rejected edit' }), error => {
579
+ assert.equal(error.code, 'PRIVATE_BACKEND_COMPENSATION_FAILED')
580
+ assert.match(error.cause.message, /memory changed concurrently/)
581
+ assert.match(error.compensationError.message, /changed before backend compensation/)
582
+ return true
583
+ })
584
+ assert.deepEqual(calls.map(call => call.op), ['commit'], 'do not delete a newer same-name backend row')
585
+ assert.equal(state.loadPrivateIndex(f.libraryId).entries['mem-live'].content, 'externally replaced authoritative value')
586
+ })
587
+
588
+ test('library queue spans compensation across routes and releases after failure', async () => {
589
+ const f = fixture()
590
+ activate([f.libraryId])
591
+ let entered
592
+ let release
593
+ const started = new Promise(resolve => { entered = resolve })
594
+ const gate = new Promise(resolve => { release = resolve })
595
+ commitHook = async () => {
596
+ commitHook = null
597
+ state.setSessionBinding(f.sessionId, { useLibrary: false })
598
+ }
599
+ forgetHook = async args => {
600
+ entered()
601
+ await gate
602
+ backendRows.delete(backendKey(args.db, args.name))
603
+ return { deleted: 1 }
604
+ }
605
+ const first = memory.privateRemember({ exec: f.exec, content: 'first write must roll back' })
606
+ const rejected = assert.rejects(first, /private memory is turned off/)
607
+ await started
608
+ // A remote writer to the same library must wait for managed compensation.
609
+ state.updateSettings({ vectorSource: 'api' })
610
+ const second = memory.importMemories({ libraryId: f.libraryId, memories: [{ content: 'later remote write' }] })
611
+ await new Promise(resolve => setImmediate(resolve))
612
+ assert.deepEqual(calls.map(call => call.op), ['commit', 'forget'])
613
+ assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 1)
614
+ release()
615
+ await rejected
616
+ const imported = await second
617
+ assert.equal(imported.imported, 1)
618
+ assert.equal(calls[2].route, 'remote-api')
619
+ assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
620
+ assert.equal(backendRows.size, 1)
621
+ })
622
+
623
+ test('managed vector commit failure defers to index-only instead of losing the write', async () => {
624
+ const f = fixture()
625
+ activate([f.libraryId])
626
+ failCommit = true
627
+ const written = await memory.privateRemember({ exec: f.exec, content: 'deferred write survives', title: 'deferred' })
628
+ let entry = state.loadPrivateIndex(f.libraryId).entries[written.id]
629
+ assert.equal(entry.content, 'deferred write survives')
630
+ assert.equal(entry.vectorPending, true)
631
+ assert.equal(entry.vector, undefined)
632
+ assert.equal(backendRows.size, 0, 'nothing was falsely recorded as committed')
633
+ assert.ok(warnings.some(message => /deferred/.test(message)), 'the degradation must be observable')
634
+
635
+ failCommit = false
636
+ await memory.privateUpdate({ exec: f.exec, id: written.id, content: 'deferred write now committed' })
637
+ entry = state.loadPrivateIndex(f.libraryId).entries[written.id]
638
+ assert.equal(entry.vectorPending, undefined, 'a later successful commit clears the pending flag')
639
+ assert.equal(entry.vector.route, 'managed-local')
640
+ })
641
+
642
+ test('managed import failure rejects without index-first false success', async () => {
643
+ const f = fixture()
644
+ activate([f.libraryId])
645
+ failCommit = true
646
+ await assert.rejects(memory.importMemories({ libraryId: f.libraryId, memories: [{ content: 'restored unique fact' }] }), /mock managed commit failed/)
647
+ assert.deepEqual(state.loadPrivateIndex(f.libraryId).entries, {})
648
+ assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
649
+ })
650
+
651
+ test('a write under an active generation records which vector space it entered', async () => {
652
+ const f = fixture()
653
+ activate([f.libraryId])
654
+ const written = await memory.privateRemember({ exec: f.exec, content: '这条应该记下向量归属', title: '向量归属' })
655
+ const entry = state.loadPrivateIndex(f.libraryId).entries[written.id]
656
+ assert.equal(entry.vector.model, 'bge-small-zh-v1.5-int8')
657
+ assert.equal(entry.vector.generation, 1)
658
+ assert.equal(entry.vector.route, 'managed-local')
659
+ assert.match(entry.vector.fingerprint, /^[0-9a-f]{8}$/)
660
+
661
+ // 没有代际(降级写)时不允许写字面上的"已入向量库"。
662
+ fs.rmSync(activeFile, { force: true })
663
+ const plain = await memory.privateRemember({ exec: f.exec, content: '降级写不应带向量归属', title: '降级' })
664
+ assert.equal(state.loadPrivateIndex(f.libraryId).entries[plain.id].vector, undefined)
665
+ })
666
+
667
+ test('the vector count follows reality: writes stamp, review/import/curator stamp, deletes shrink', async () => {
668
+ // 设置页"当前已入向量库 N 条"不能只数迁移账本:账本在切换
669
+ // 那一刻写完就再也不更新,聊天里新写的记忆永远不进计数。membership = 账本腿(迁移
670
+ // 写入,扣除已删除)+ 戳腿(迁移后写入)。每条迁移后写入路径都必须落戳,否则漏数。
671
+ const vm = await import('../lib/vector-migration.js')
672
+ const f = fixture({
673
+ 'mem-migrated': entry('迁移时就有的记忆'),
674
+ 'mem-held': entry('待审的主张', { status: 'pending_review' }),
675
+ })
676
+ activate([f.libraryId])
677
+ // 预置"切换时写入 1/1"的账本快照:mem-migrated 在迁移时进了向量库(索引故意无戳)。
678
+ const { ledger } = vm.loadLedger(profile.fingerprint, 1)
679
+ ledger.libraries[f.libraryId] = { items: { 'mem-migrated': { hash: 'seed', at: new Date().toISOString() } }, tombstones: {}, snapshot: null }
680
+ vm.saveLedger(ledger)
681
+ const migrator = vm.createVectorMigrator({
682
+ listLibraries: () => state.listLibraries().map(item => item.id),
683
+ loadIndex: libraryId => libraryId == null ? state.loadGlobalIndex() : state.loadPrivateIndex(libraryId),
684
+ commit: async () => {}, forget: async () => {}, listFiles: async () => [],
685
+ })
686
+ const idsOf = scope => (migrator.membership()[scope] || []).sort()
687
+ assert.deepEqual(idsOf(f.libraryId), ['mem-migrated'], 'starts at the migration count — the reported bug state')
688
+
689
+ // 聊天写入:戳腿接管,计数跟着涨。
690
+ const written = await memory.privateRemember({ exec: f.exec, content: '切换后新写的记忆', title: '新记忆' })
691
+ assert.equal(state.loadPrivateIndex(f.libraryId).entries[written.id].vector.generation, 1)
692
+ assert.deepEqual(idsOf(f.libraryId), ['mem-migrated', written.id])
693
+
694
+ // 编辑重提交:行被重写进当前空间,戳刷新到当前代际。
695
+ await memory.privateUpdate({ exec: f.exec, id: written.id, content: '更新后的记忆内容' })
696
+ const updated = state.loadPrivateIndex(f.libraryId).entries[written.id]
697
+ assert.equal(updated.vector.generation, 1)
698
+ assert.equal(updated.vector.route, 'managed-local')
699
+ assert.deepEqual(idsOf(f.libraryId), ['mem-migrated', written.id])
700
+
701
+ // 批量恢复与评审接受:此前完全不落戳,是计数漏数的另外两条路。
702
+ await memory.importMemories({ libraryId: f.libraryId, memories: [{ content: '恢复回来的独特观察' }] })
703
+ const imported = Object.entries(state.loadPrivateIndex(f.libraryId).entries).find(([, item]) => item.content === '恢复回来的独特观察')[0]
704
+ assert.equal(state.loadPrivateIndex(f.libraryId).entries[imported].vector.generation, 1)
705
+ await memory.resolveMemoryReview({ libraryId: f.libraryId, id: 'mem-held', action: 'accept' })
706
+ assert.equal(state.loadPrivateIndex(f.libraryId).entries['mem-held'].vector.generation, 1)
707
+ assert.ok(idsOf(f.libraryId).includes(imported) && idsOf(f.libraryId).includes('mem-held'))
708
+
709
+ // 永久删除:引擎行先删、索引行后删,账本不知道 —— membership 必须把它扣掉。
710
+ await memory.privateArchive({ exec: f.exec, id: 'mem-migrated' })
711
+ await memory.privateDelete({ exec: f.exec, id: 'mem-migrated' })
712
+ assert.equal(idsOf(f.libraryId).includes('mem-migrated'), false, 'a permanently deleted migration item leaves the count')
713
+
714
+ // 全局整理:同样的口径,提交成功即落戳。
715
+ const clean = await curator.commitCuratorOutput({ memories: [curated()] }, { job: job() })
716
+ assert.equal(clean.created, 1)
717
+ const curatedId = Object.keys(state.loadGlobalIndex().entries)[0]
718
+ assert.equal(state.loadGlobalIndex().entries[curatedId].vector.route, 'managed-local')
719
+ assert.deepEqual((migrator.membership().global || []), [curatedId])
720
+ })
721
+
722
+ test('managed curator clean output commits under lease and held output is index-only', async () => {
723
+ activate()
724
+ const clean = await curator.commitCuratorOutput({ memories: [curated()] }, { job: job() })
725
+ assert.equal(clean.created, 1)
726
+ assert.equal(calls.length, 1)
727
+ assert.equal(calls[0].db, vp.dbPathFor(null))
728
+ const held = await curator.commitCuratorOutput({ memories: [curated({ title: 'held conflict', op: 'conflict' })] }, { job: job() })
729
+ assert.equal(held.pending, 1)
730
+ assert.equal(calls.length, 1)
731
+ assert.ok(Object.values(state.loadGlobalIndex().entries).some(item => item.status === 'pending_review'))
732
+ assert.equal(Object.keys(vp.activeVectorState().writeGuard.leases).length, 0)
733
+ })
734
+
735
+ // 模型已选定但迁移未完成时,vector-active 只有
736
+ // requested,没有 active。写入路径当时直接抛 VECTOR_NOT_ACTIVE,整理 fork 跑完却一条
737
+ // 记忆都没落下,而最后睡眠标记照样前进。写入必须和召回一样降级,不能整体失败。
738
+ test('a requested-but-never-migrated profile degrades writes instead of failing them', async () => {
739
+ const f = fixture()
740
+ assert.equal(vp.hasActiveVectorGeneration(), false)
741
+ fs.writeFileSync(activeFile, JSON.stringify({
742
+ version: 1,
743
+ generation: 0,
744
+ requested: { status: 'requested', catalogId: 'bge-small-zh-v1.5-int8', fingerprint: profile.fingerprint },
745
+ }))
746
+ const private1 = await memory.privateRemember({ exec: f.exec, content: 'degraded private write must land', title: 'degraded private write' })
747
+ assert.equal(state.loadPrivateIndex(f.libraryId).entries[private1.id].content, 'degraded private write must land')
748
+ // No generation means no embedding environment, so MemU cannot take a commit at
749
+ // all (envFor refuses managed-local). Index-only is the honest degradation; the
750
+ // record is re-embedded by the next migration.
751
+ assert.deepEqual(calls.map(call => call.op), [], 'a vectorless profile must not call the engine')
752
+ assert.ok(warnings.some(message => /no active vector generation/.test(message)), 'the degradation is logged: ' + warnings.join(' | '))
753
+ assert.ok(activity.listEvents({ kind: 'vector' }).length >= 1, 'the degradation is visible in the activity log')
754
+
755
+ const curatedResult = await curator.commitCuratorOutput({ memories: [curated()] }, { job: job() })
756
+ assert.equal(curatedResult.created, 1, 'global curation must not be thrown away either')
757
+ assert.match(Object.keys(state.loadGlobalIndex().entries).join(','), /gmem-/, 'the global index still receives it')
758
+ assert.deepEqual(calls.map(call => call.op), [], 'global curation degrades the same way')
759
+ })
760
+
761
+ test('archive stays index-only; deleting is what removes the vector row', async () => {
762
+ const f = fixture({ 'mem-arch': entry('to archive') })
763
+ activate([f.libraryId])
764
+ await memory.privateArchive({ exec: f.exec, id: 'mem-arch' })
765
+ assert.equal(state.loadPrivateIndex(f.libraryId).entries['mem-arch'].status, 'archived')
766
+ assert.deepEqual(calls.map(call => call.op), [], 'archiving must not start the engine; it only flips the index status')
767
+ await memory.privateDelete({ exec: f.exec, id: 'mem-arch' })
768
+ assert.deepEqual(calls.map(call => call.op), ['forget'], 'permanent delete is what removes the MemU row')
769
+ })
770
+
771
+ test('UI listings read the index even when vectors are active', async () => {
772
+ const f = fixture()
773
+ activate([f.libraryId])
774
+ // 列表走引擎意味着起 Python + embedding worker(秒级)。索引是权威,UI 刷新不该等它。
775
+ const privateView = await memory.privateList({ libraryId: f.libraryId, preferIndex: true })
776
+ assert.equal(privateView.source, 'index')
777
+ assert.ok(privateView.files.length >= 0)
778
+ const globalView = await memory.globalList({ exec: { agent: null }, preferIndex: true })
779
+ assert.equal(globalView.source, 'index')
780
+ assert.deepEqual(calls.map(call => call.op).filter(op => op === 'listFiles'), [], 'no engine list call')
781
+ })
782
+
783
+ test('global list degrades to the index when no vector generation is active', async () => {
784
+ fs.writeFileSync(activeFile, JSON.stringify({
785
+ version: 1,
786
+ generation: 0,
787
+ requested: { status: 'requested', catalogId: 'bge-small-zh-v1.5-int8', fingerprint: profile.fingerprint },
788
+ }))
789
+ state.saveGlobalIndex({ entries: { 'gmem-1': entry('global fact', { domain: 'coding' }) } })
790
+ // 全局记忆页原先会闪一下 "managed local vector profile is not active" 再消失:
791
+ // globalList 走了引擎路由,没有代际就必抛。列表本身能答,就按索引答。
792
+ const result = await memory.globalList({ exec: { agent: null } })
793
+ assert.equal(result.source, 'index')
794
+ assert.deepEqual(result.files.map(file => file.name), ['gmem-1'])
795
+ assert.match(result.warning, /本地向量未激活/)
796
+ })
797
+
798
+ test('an existing but torn generation still refuses writes loudly', async () => {
799
+ const f = fixture()
800
+ activate([f.libraryId])
801
+ assert.equal(vp.hasActiveVectorGeneration(), true)
802
+ const dbPath = vp.resolveVectorPath(vp.activeVectorState().active.databases.libraries[f.libraryId].path)
803
+ fs.rmSync(dbPath, { force: true })
804
+ await assert.rejects(
805
+ memory.privateRemember({ exec: f.exec, content: 'must not be silently split', title: 'torn generation' }),
806
+ { code: 'VECTOR_TORN_STATE' },
807
+ )
808
+ assert.deepEqual(Object.keys(state.loadPrivateIndex(f.libraryId).entries), [], 'a torn generation must not leave an index-only entry behind')
809
+ })
810
+
811
+ test('deleting an active archived library removes its route without tearing later writes', async () => {
812
+ const f = fixture()
813
+ const databases = activate([f.libraryId])
814
+ const activeDb = vp.resolveVectorPath(databases.libraries[f.libraryId].path)
815
+ fs.writeFileSync(path.join(home, 'libraries', f.libraryId + '.old.g1.sqlite3'), '')
816
+ state.archiveLibrary(f.libraryId)
817
+ await vp.withVectorWrite(async () => {
818
+ assert.throws(() => state.deleteLibrary(f.libraryId), { code: 'VECTOR_WRITE_BUSY' })
819
+ })
820
+ const result = state.deleteLibrary(f.libraryId)
821
+ assert.equal(result.ok, true)
822
+ assert.equal(vp.activeVectorState().active.databases.libraries[f.libraryId], undefined)
823
+ assert.equal(fs.existsSync(activeDb), false)
824
+ assert.equal(fs.existsSync(path.join(home, 'libraries', f.libraryId + '.old.g1.sqlite3')), false)
825
+
826
+ const next = fixture()
827
+ const remembered = await memory.privateRemember({ exec: next.exec, content: 'write after deleting another library', title: 'route remains healthy' })
828
+ assert.equal(state.loadPrivateIndex(next.libraryId).entries[remembered.id].content, 'write after deleting another library')
829
+ assert.equal(vp.activeVectorState().active.databases.libraries[f.libraryId], undefined)
830
+ })
831
+
832
+ // RRF 名次归一把词法满分命中压成近平手后,primacy/peakEnd
833
+ // 偏置可能将弱相关元记忆排在精确命中之前。
834
+ // 修复后巨无霸命中保住 #1,弱竞争者落到相对阈值之外。
835
+ test('a dominant lexical hit cannot be buried by primacy/peak-end biases', async () => {
836
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'local' })
837
+ // 大语料抬高 BM25 的库规模(IDF 随 N 增长,小语料造不出 ≥24 的巨无霸分)。
838
+ const entries = {}
839
+ const alphabet = 'abcdefghijklmnopqrstuvwxyz'
840
+ const token = (n) => alphabet[n % 26] + alphabet[Math.floor(n / 26) % 26]
841
+ const old = '2026-10-01T00:00:00.000Z'
842
+ for (let i = 0; i < 60; i += 1) {
843
+ entries['mem-pad-' + String(i).padStart(2, '0')] = entry('常规条目 ' + token(3 * i) + token(3 * i + 1) + ',归档说明与轮值安排。', {
844
+ createdAt: old, updatedAt: old, strength: 1, arousal: 0.9,
845
+ })
846
+ }
847
+ // meta:最早创建(primacy ×1.2)+ 高唤醒(peakEnd ×1.25)+ strength 1——偏置加成最大;
848
+ // 正文含查询里的常见词元(有/没有),让它也进词法腿,制造名次归一的近平手。
849
+ entries['mem-meta'] = entry('运营值守安排,没有什么特别的说明。', { createdAt: old, updatedAt: old, strength: 1, arousal: 0.9 })
850
+ entries['mem-food'] = entry('主人是江南人,爱吃桂花糖糕,在杭州吃不到几家做糖糕和豆沙米糕的铺子。', { strength: 0.8, arousal: 0.35 })
851
+ const f = fixture(entries)
852
+ activate([f.libraryId])
853
+ // 语义腿把 meta 排在 food 前面(模拟引擎 embedding 被查询样板带偏的形态):
854
+ // 词法腿 food 满分,RRF 名次归一后两者 retrieval 近平手。
855
+ retrieveHook = () => ({ files: [{ name: 'mem-meta' }, { name: 'mem-food' }], segments: [], resources: [] })
856
+ const result = await memory.privateRecall({ exec: f.exec, query: '桂花的,我江南小囡喜欢吃糖糕,还有豆沙米糕', topK: 5, relevanceThreshold: 0.4 })
857
+ assert.equal(result.files[0]?.name, 'mem-food', 'the dominant lexical hit must rank first, got ' + result.files[0]?.name)
858
+ assert.ok((result.files[0]?.fusion?.lexicalDominant ?? 0) >= 24, 'the dominance must be recorded in fusion metadata')
859
+ assert.ok(!result.files.some((file) => file.name === 'mem-meta'), 'weak competitors fall below the relative threshold')
860
+ retrieveHook = null
861
+ })
862
+
863
+ // Real BM25 regressions: only the semantic boundary is stubbed. Dates deliberately
864
+ // age with now; a future sceneTime must not erase strength/primacy in these cases.
865
+ function rankingEntry(content, extra = {}) {
866
+ const ago = days => new Date(Date.now() - days * 86_400_000).toISOString()
867
+ return entry(content, { createdAt: ago(2), updatedAt: ago(1), ...extra })
868
+ }
869
+
870
+ function rankingWorld(primaryEntries, foreignEntries) {
871
+ const primary = fixture(primaryEntries)
872
+ const foreign = fixture(foreignEntries)
873
+ const domain = 'ranking:' + primary.sessionId
874
+ for (const f of [primary, foreign]) state.setSessionBinding(f.sessionId, { domainOverride: domain })
875
+ state.updateSettings({ crossLibraryRecall: true })
876
+ return { primary, foreign }
877
+ }
878
+
879
+ function realLexical(entries, query) {
880
+ const corpus = buildCorpus(Object.entries(entries).map(([id, row]) => ({
881
+ id, title: row.title,
882
+ content: [row.content, (row.tags || []).join(' '), (row.attachments || []).map(item => `${item.caption || ''} 图片 ${item.kind || 'image'}`).join(' ')].filter(Boolean).join(' '),
883
+ })))
884
+ return new Map([...corpus.docs].map(([id, doc]) => [id, bm25(tokenize(query), doc, corpus)]))
885
+ }
886
+
887
+ async function assertRankingBoundary(expectedRetrieves) {
888
+ await settleRebuildProbes()
889
+ assert.equal(calls.length, expectedRetrieves, 'only the stub semantic retrieve boundary is called')
890
+ assert.ok(calls.every(call => call.op === 'retrieve' && call.route === 'managed-local'))
891
+ assert.deepEqual(rebuildProbes, [], 'ranking regressions must not start a real rebuild/worker')
892
+ assert.deepEqual(warnings, [])
893
+ }
894
+
895
+ const tlsAnswer = 'TLS 服务证书过期,续签后重启代理恢复连接。'
896
+ const tlsTemplate = '请用自然简洁的语气回答。这是通用回复风格,不涉及饮食或服务故障。'
897
+ const pianoNotes = [
898
+ '钢琴练习先慢速弹奏音阶,再练左右手协调。',
899
+ '巴赫赋格练习需要分声部辨认旋律。',
900
+ '踏板练习要注意换踏时机与音色。',
901
+ '周末排练莫扎特奏鸣曲,保持轻巧触键。',
902
+ '视奏练习每天十五分钟,先看拍号与调号。',
903
+ '和弦转位练习强调指法与手腕放松。',
904
+ '节拍器从慢速逐渐加快,避免抢拍。',
905
+ '演出前检查琴凳高度,认真完成热身。',
906
+ ]
907
+ function tlsEntries(template, size = 2) {
908
+ const answerDate = new Date(Date.now() - 4 * 86_400_000).toISOString()
909
+ return {
910
+ 'mem-answer': rankingEntry(tlsAnswer, { createdAt: answerDate, strength: 1, peak: true }),
911
+ 'mem-template': rankingEntry(template, { strength: 0.8 }),
912
+ ...Object.fromEntries(pianoNotes.slice(0, size - 2).map((text, i) => ['mem-piano-' + i, rankingEntry(text)])),
913
+ }
914
+ }
915
+
916
+ for (const crossLibrary of [false, true]) {
917
+ test(`real BM25 short reply style leaves TLS answer first (${crossLibrary ? 'with three foreign piano notes' : 'two-entry library'})`, async () => {
918
+ const entries = tlsEntries(tlsTemplate)
919
+ const world = crossLibrary
920
+ ? rankingWorld(entries, Object.fromEntries(pianoNotes.slice(0, 3).map((text, i) => ['mem-note-' + i, rankingEntry(text)])))
921
+ : null
922
+ const f = world?.primary || fixture(entries)
923
+ activate(world ? [f.libraryId, world.foreign.libraryId] : [f.libraryId])
924
+ retrieveHook = args => ({ files: args.db === vp.dbPathFor(f.libraryId) ? [{ name: 'mem-answer' }, { name: 'mem-template' }] : [], segments: [], resources: [] })
925
+ const result = await memory.privateRecall({ exec: f.exec, query: '请用自然简洁的语气回答。TLS 故障原因?', topK: 5, relevanceThreshold: 0 })
926
+ assert.equal(result.files[0]?.name, 'mem-answer', 'corpus changes must not crown the reply-style template')
927
+ const template = result.files.find(file => file.name === 'mem-template')
928
+ assert.ok(template?.lexical > 0, 'the original lexical score stays observable')
929
+ assert.ok(template.lexicalEvidence < template.lexical, 'style-only overlap is not topical evidence')
930
+ assert.notEqual(result.fusion?.lexicalDominance?.id, 'mem-template')
931
+ assert.equal(result.files[0].entry.content, tlsAnswer)
932
+ if (crossLibrary) assert.equal(result.files[0].libraryId, f.libraryId)
933
+ await assertRankingBoundary(crossLibrary ? 2 : 1)
934
+ })
935
+ }
936
+
937
+ for (const [language, template, query] of [
938
+ ['short Chinese', tlsTemplate, '请用自然简洁的语气回答。TLS 故障原因?'],
939
+ ['Chinese', '请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。', '请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。TLS 故障原因?'],
940
+ ['English', 'Please answer clearly and concisely with accurate context and natural language. Avoid repetition and unnecessary details.', 'Please answer clearly and concisely with accurate context and natural language. Avoid repetition and unnecessary details. What caused TLS failure?'],
941
+ ]) {
942
+ for (const size of [2, 3, 10]) {
943
+ test(`real BM25 ${language} long reply style keeps TLS answer first with ${size} documents`, async () => {
944
+ const f = fixture(tlsEntries(template, size))
945
+ activate([f.libraryId])
946
+ retrieveHook = () => ({ files: [{ name: 'mem-answer' }, { name: 'mem-template' }], segments: [], resources: [] })
947
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.4 })
948
+ assert.ok(result.files.length, 'style removal must not turn a topical query into empty recall')
949
+ assert.equal(result.files[0]?.name, 'mem-answer')
950
+ assert.notEqual(result.fusion?.lexicalDominance?.id, 'mem-template')
951
+ assert.ok(result.files[0].lexical > 0, 'TLS remains an actual lexical hit, not only a semantic rescue')
952
+ await assertRankingBoundary(1)
953
+ })
954
+ }
955
+ }
956
+
957
+ const rankingWords = 'certificate expired renewal proxy restart connection handshake trust chain hostname issuer validity protocol cipher client server clock intermediate root authority verification transport security gateway service outage investigation diagnosis mitigation deployment recovery monitoring incident encryption authentication socket timeout negotiation alert endpoint configuration rotation revocation openssl pem browser response failure latency availability maintenance rollback'.split(' ')
958
+ const foodQuery = '桂花的,我江南小囡喜欢吃糖糕,还有豆沙米糕'
959
+ const foodAnswer = '主人是江南人,爱吃桂花糖糕,在杭州吃不到几家做糖糕和豆沙米糕的铺子。'
960
+
961
+ test('real BM25 a weak 的 hit is no worse than zero evidence and preserves topical answer order', async () => {
962
+ const topicQuery = '桂花 江南 糖糕 豆沙米糕 杭州 铺子'
963
+ const entries = {
964
+ 'mem-food': rankingEntry(foodAnswer, { peak: true, createdAt: new Date(Date.now() - 4 * 86_400_000).toISOString() }),
965
+ 'mem-semantic': rankingEntry('钢琴练习巴赫赋格。', { strength: 0.8 }),
966
+ 'mem-weak': rankingEntry('归档标记:的', { strength: 0.8 }),
967
+ }
968
+ const f = fixture(entries)
969
+ activate([f.libraryId])
970
+ retrieveHook = () => ({ files: [{ name: 'mem-food' }, { name: 'mem-semantic' }], segments: [], resources: [] })
971
+ const result = await memory.privateRecall({ exec: f.exec, query: topicQuery + ' 的', topK: 5, relevanceThreshold: 0 })
972
+ assert.equal(result.files[0]?.name, 'mem-food')
973
+ assert.ok(result.fusion.lexicalDominance?.topLex >= 24, 'the test must exercise dominance, not an inactive branch')
974
+ const weak = result.files.find(file => file.name === 'mem-weak')
975
+ const zero = result.files.find(file => file.name === 'mem-semantic')
976
+ assert.ok(weak?.lexical > 0 && weak.lexical < result.files[0].lexical / 20, '的 is a real but tiny BM25 hit')
977
+ assert.ok(zero, 'the zero-evidence semantic candidate remains observable')
978
+ assert.equal(zero.lexical ?? 0, 0)
979
+ const sigma = 1 / (1 + result.fusion.lexicalDominance.topLex / 50)
980
+ assert.ok(Math.abs(weak.fusion.lexicalDiscount - sigma) < 1e-12, 'tiny evidence is protected by the continuous sigma floor')
981
+ assert.ok(weak.fusion.lexicalDiscount >= zero.fusion.lexicalDiscount, 'a tiny lexical hit cannot be penalized more than no hit')
982
+ const baseline = await memory.privateRecall({ exec: f.exec, query: topicQuery, topK: 5, relevanceThreshold: 0 })
983
+ assert.deepEqual(result.files.filter(file => file.name !== 'mem-weak').map(file => file.name), baseline.files.filter(file => file.name !== 'mem-weak').map(file => file.name))
984
+ await assertRankingBoundary(2)
985
+ })
986
+
987
+ test('real BM25 cross-library same-id facts stay separate and a strong foreign hit is real evidence', async () => {
988
+ state.updateSettings({ memoryBackend: 'agent' })
989
+ const query = rankingWords.slice(0, 38).join(' ')
990
+ const primaryEntries = {
991
+ // 逆序打破逐字包含/核心覆盖探针:两条同 id 事实必须靠身份而不是内容去重存活。
992
+ 'mem-shared': rankingEntry(rankingWords.slice(0, 3).reverse().join(' ')),
993
+ 'mem-secondary': rankingEntry(rankingWords.slice(3, 9).join(' ')),
994
+ }
995
+ const foreignEntries = { 'mem-shared': rankingEntry(query), 'mem-piano': rankingEntry(pianoNotes[0]) }
996
+ const { primary, foreign } = rankingWorld(primaryEntries, foreignEntries)
997
+ const all = await memory.privateRecall({ exec: primary.exec, query, topK: 5, relevanceThreshold: 0 })
998
+ assert.deepEqual(new Set(all.libraries), new Set([primary.libraryId, foreign.libraryId]))
999
+ const twins = all.files.filter(file => file.name === 'mem-shared')
1000
+ assert.equal(twins.length, 2, 'same id in two libraries is two facts, not one folded row')
1001
+ const sharedPrimary = twins.find(file => file.libraryId === primary.libraryId)
1002
+ const sharedForeign = twins.find(file => file.libraryId === foreign.libraryId)
1003
+ assert.equal(sharedPrimary.entry.content, primaryEntries['mem-shared'].content)
1004
+ assert.equal(sharedForeign.entry.content, query)
1005
+ assert.ok(sharedForeign.lexical > sharedPrimary.lexical, 'each twin keeps its own unified-corpus evidence, nothing is inherited')
1006
+ assert.ok(all.files.some(file => file.name === 'mem-secondary' && file.libraryId === primary.libraryId))
1007
+ assert.ok(!all.files.some(file => file.name === 'mem-piano'), 'zero-evidence foreign filler stays out')
1008
+ assert.equal(all.files[0].libraryId, foreign.libraryId, 'the genuinely strong foreign fact outranks weak local rows')
1009
+ assert.equal(all.fusion.crossLibraryLexical, 'unified-bm25')
1010
+ const cut = await memory.privateRecall({ exec: primary.exec, query, topK: 5, relevanceThreshold: 0.8 })
1011
+ assert.deepEqual(cut.files.map(file => [file.libraryId, file.name]), [[foreign.libraryId, 'mem-shared']], 'the 0.8 cut is real competition now, not ghost removal')
1012
+ const evidence = file => file.lexicalEvidence ?? file.lexical ?? 0
1013
+ const ranked = all.files.slice().sort((a, b) => evidence(b) - evidence(a))
1014
+ const dominant = evidence(ranked[0]) >= 24 && evidence(ranked[0]) >= evidence(ranked[1]) * 4
1015
+ assert.equal(Boolean(all.fusion.lexicalDominance), dominant, 'dominance is computed from the surviving unified evidence')
1016
+ if (dominant) assert.equal(all.fusion.lexicalDominance.id, ranked[0].name)
1017
+ for (const file of all.files) {
1018
+ assert.ok(Math.abs(file.retrievalScore - Math.min(1, file.fusion.rawRetrievalScore * (file.fusion.lexicalDiscount ?? 1))) < 1e-12)
1019
+ }
1020
+ await assertRankingBoundary(0)
1021
+ })
1022
+
1023
+ for (const gate of ['disclosure', 'speaker']) {
1024
+ test(`real BM25 ${gate} filtering recomputes dominance from eligible candidates`, async () => {
1025
+ const query = (gate === 'speaker' ? '我说过 ' : '') + rankingWords.join(' ')
1026
+ const entries = {
1027
+ 'mem-hidden': rankingEntry(rankingWords.join(' '), gate === 'disclosure' ? { disclosure: 'only_if_asked' } : { speaker_id: 'assistant' }),
1028
+ 'mem-small': rankingEntry(rankingWords.slice(0, 3).join(' '), { speaker_id: 'user', strength: 0.8 }),
1029
+ 'mem-normal': rankingEntry('钢琴练习已经完成,下一次排练在周末。', { speaker_id: 'user', strength: 0.8 }),
1030
+ }
1031
+ const scores = realLexical(entries, query)
1032
+ assert.ok(scores.get('mem-hidden') >= 24 && scores.get('mem-hidden') >= scores.get('mem-small') * 4)
1033
+ const f = fixture(entries)
1034
+ activate([f.libraryId])
1035
+ retrieveHook = () => ({ files: [{ name: 'mem-normal' }], segments: [], resources: [] })
1036
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8, purpose: 'automatic' })
1037
+ assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-normal', 'mem-small']))
1038
+ assert.equal(result.fusion.lexicalDominance, null, 'the final summary must not retain the excluded top')
1039
+ for (const file of result.files) {
1040
+ assert.equal(file.fusion.lexicalDominant, undefined)
1041
+ assert.equal(file.fusion.lexicalDiscount, undefined)
1042
+ assert.equal(file.retrievalScore, file.fusion.rawRetrievalScore, 'filtered survivors recover their raw RRF share')
1043
+ }
1044
+ await assertRankingBoundary(1)
1045
+ })
1046
+ }
1047
+
1048
+ test('real BM25 nested vector and cross-library RRF applies exactly one sigma to semantic-only recall', async () => {
1049
+ const query = rankingWords.join(' ')
1050
+ const entries = {
1051
+ 'mem-strong': rankingEntry(query),
1052
+ 'mem-mild': rankingEntry('端口8443证书根链验证失败,需要检查中间CA是否被撤销。', { tags: rankingWords.slice(0, 22) }),
1053
+ 'mem-semantic': rankingEntry(pianoNotes.join(' ')),
1054
+ }
1055
+ const scores = realLexical(entries, query)
1056
+ const inner = memory.fuseRecallCandidates({
1057
+ index: { entries },
1058
+ local: ['mem-strong', 'mem-mild'].map(name => ({ name, entry: entries[name], content: entries[name].content, lexical: scores.get(name) })),
1059
+ semantic: [{ name: 'mem-semantic' }, { name: 'mem-strong' }],
1060
+ })
1061
+ assert.deepEqual(inner.files.map(file => file.name), ['mem-strong', 'mem-mild', 'mem-semantic'], 'real lexical evidence changes the discounted inner ordering')
1062
+ assert.ok(inner.files[2].fusion.rawRetrievalScore > inner.files[1].fusion.rawRetrievalScore, 'raw order is semantic before mild, the opposite of discounted order')
1063
+ assert.equal(inner.debug.lexicalDominance.id, 'mem-strong')
1064
+ const { primary, foreign } = rankingWorld(entries, {})
1065
+ activate([primary.libraryId, foreign.libraryId])
1066
+ retrieveHook = args => ({ files: args.db === vp.dbPathFor(primary.libraryId) ? [{ name: 'mem-semantic' }, { name: 'mem-strong' }] : [], segments: [], resources: [] })
1067
+ const result = await memory.privateRecall({ exec: primary.exec, query, topK: 5, relevanceThreshold: 0 })
1068
+ assert.equal(result.recallRoute, 'cross-library')
1069
+ assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-strong', 'mem-mild', 'mem-semantic']))
1070
+ assert.equal(result.fusion.crossLibraryLexical, 'unified-bm25')
1071
+ assert.equal(result.fusion.crossLibrarySemantic, 'rank-only', 'hook files carry no scores, so the vector leg stays rank-only')
1072
+ const strong = result.files.find(file => file.name === 'mem-strong')
1073
+ const semantic = result.files.find(file => file.name === 'mem-semantic')
1074
+ const mild = result.files.find(file => file.name === 'mem-mild')
1075
+ // 统一语料此刻恰好等于主库三文档(外库为空),BM25 值与 realLexical 一致。
1076
+ const topLex = scores.get('mem-strong')
1077
+ assert.ok(topLex >= 24)
1078
+ assert.equal(strong.lexical, topLex)
1079
+ assert.equal(mild.lexical, scores.get('mem-mild'))
1080
+ // 方法间 RRF:词法腿 strong=1 mild=2,向量腿(rank-only)semantic=1 strong=2。
1081
+ const rrfStrong = 1 / 61 + 1 / 62
1082
+ assert.ok(Math.abs(strong.fusion.rawRetrievalScore - 1) < 1e-12)
1083
+ assert.ok(Math.abs(mild.fusion.rawRetrievalScore - (1 / 62) / rrfStrong) < 1e-12)
1084
+ assert.ok(Math.abs(semantic.fusion.rawRetrievalScore - (1 / 61) / rrfStrong) < 1e-12, 'outer RRF is rebuilt from unified leg ranks, not the discounted inner order')
1085
+ assert.equal(strong.fusion.bestRank, 1)
1086
+ assert.equal(mild.fusion.bestRank, 2, 'outer rank comes from the unified lexical leg, not the discounted inner rank of two')
1087
+ assert.equal(semantic.fusion.bestRank, 1)
1088
+ const sigma = 1 / (1 + topLex / 50)
1089
+ const mildDiscount = Math.sqrt(scores.get('mem-mild') / topLex)
1090
+ assert.ok(mildDiscount > sigma, 'the mild fact genuinely exercises the square-root branch')
1091
+ assert.ok(Math.abs(strong.retrievalScore - 1) < 1e-12)
1092
+ assert.ok(Math.abs(mild.retrievalScore - (1 / 62) / rrfStrong * mildDiscount) < 1e-12)
1093
+ assert.ok(Math.abs(semantic.retrievalScore - (1 / 61) / rrfStrong * sigma) < 1e-12, 'exactly one sigma, not multiplied by the inner share')
1094
+ assert.ok(Math.abs(semantic.retrievalScore - (1 / 61) / rrfStrong * sigma * sigma) > 0.01)
1095
+ assert.equal(result.fusion.lexicalDominance.id, 'mem-strong')
1096
+ assert.equal(result.fusion.lexicalDominance.stage, 'eligible')
1097
+ assert.equal(result.fusion.lexicalDominance.topLex, strong.lexical)
1098
+ assert.equal(semantic.fusion.lexicalDominantId, 'mem-strong')
1099
+ assert.equal(semantic.fusion.dominanceStage, 'eligible')
1100
+ assert.equal(calls.filter(call => call.db === vp.dbPathFor(primary.libraryId)).length, 1)
1101
+ assert.equal(calls.filter(call => call.db === vp.dbPathFor(foreign.libraryId)).length, 1)
1102
+ await assertRankingBoundary(2)
1103
+ })
1104
+
1105
+ test('real BM25 two tied genuinely strong topical hits both survive without corpus padding', async () => {
1106
+ const query = rankingWords.join(' ')
1107
+ const entries = {
1108
+ 'mem-tls-a': rankingEntry(rankingWords.slice(0, 26).join(' ')),
1109
+ 'mem-tls-b': rankingEntry(rankingWords.slice(26).join(' ')),
1110
+ }
1111
+ const f = fixture(entries)
1112
+ activate([f.libraryId])
1113
+ retrieveHook = () => ({ files: [{ name: 'mem-tls-a' }, { name: 'mem-tls-b' }], segments: [], resources: [] })
1114
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8 })
1115
+ assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-tls-a', 'mem-tls-b']))
1116
+ for (const file of result.files) assert.ok(file.lexical >= 24, 'both hits are genuinely strong in this two-row corpus')
1117
+ assert.equal(result.fusion.lexicalDominance, null, 'two near-equal lexical tops do not single out a dominant row')
1118
+ await assertRankingBoundary(1)
1119
+ })
1120
+
1121
+ test('real BM25 QQ private-chat envelope and preference trailer preserve food as the top answer', async () => {
1122
+ const query = '[私聊:900000001]22:11 Linxiu(900000001)[主人] #-100000001 [@咱]:桂花的,我江南小囡喜欢吃糖糕,还有豆沙米糕\n[管理员的长期偏好·优先遵守]请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。\n【本会话是QQ私聊:900000001。请用自然简洁的语气回答。】'
1123
+ const now = Date.now()
1124
+ const recentCreatedAt = new Date(now - 2 * 86_400_000).toISOString()
1125
+ const f = fixture({
1126
+ 'mem-food': rankingEntry(foodAnswer, { strength: 0.8, createdAt: recentCreatedAt }),
1127
+ 'mem-template': rankingEntry('[管理员的长期偏好·优先遵守]请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。【本会话是QQ私聊:900000001。请用自然简洁的语气回答。】', { peak: true, createdAt: new Date(now - 4 * 86_400_000).toISOString() }),
1128
+ 'mem-piano': rankingEntry(pianoNotes[0], { createdAt: recentCreatedAt }),
1129
+ })
1130
+ activate([f.libraryId])
1131
+ retrieveHook = () => ({ files: [{ name: 'mem-template' }, { name: 'mem-food' }], segments: [], resources: [] })
1132
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.4 })
1133
+ assert.equal(result.files[0]?.name, 'mem-food', 'QQ transport text is not evidence of the user topic: ' + JSON.stringify({ fusion: result.fusion, files: result.files.map(({ name, lexical, lexicalEvidence, retrievalScore, score, fusion }) => ({ name, lexical, lexicalEvidence, retrievalScore, score, fusion })) }))
1134
+ assert.ok(result.files[0].lexical > 0 && result.files[0].lexicalEvidence > 0)
1135
+ assert.notEqual(result.fusion.lexicalDominance?.id, 'mem-template')
1136
+ assert.equal(calls[0].query, query, 'the semantic/index-facing query remains the original QQ message')
1137
+ await assertRankingBoundary(1)
1138
+ })
1139
+
1140
+ test('real BM25 same-leg and cross-leg folding retain the absorbed topical lexical evidence', async () => {
1141
+ const topic = rankingWords.join(' ')
1142
+ const query = '请用自然简洁的语气回答。' + topic
1143
+ const body = 'TLS故障已记录,请用自然简洁的语气回答。故障排查统一记录在运维台账。'
1144
+ const entries = {
1145
+ 'mem-a-host': rankingEntry(body, { tags: rankingWords.slice(0, 3) }),
1146
+ 'mem-z-strong': rankingEntry(body, { tags: rankingWords }),
1147
+ 'mem-piano': rankingEntry(pianoNotes[0]),
1148
+ }
1149
+ const originalScores = realLexical(entries, query)
1150
+ const evidenceScores = realLexical(entries, topic)
1151
+ assert.ok(evidenceScores.get('mem-z-strong') >= 24)
1152
+ assert.ok(originalScores.get('mem-z-strong') > originalScores.get('mem-a-host'))
1153
+ assert.ok(originalScores.get('mem-z-strong') > evidenceScores.get('mem-z-strong'), 'raw lexical includes the style overlap but evidence does not')
1154
+ const f = fixture(entries)
1155
+ activate([f.libraryId])
1156
+ retrieveHook = () => ({ files: [{ name: 'mem-a-host' }, { name: 'mem-z-strong' }], segments: [], resources: [] })
1157
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8 })
1158
+ assert.deepEqual(result.files.map(file => file.name), ['mem-a-host'], 'one real fact occupies one recall slot after both folding stages')
1159
+ const host = result.files[0]
1160
+ assert.equal(host.lexical, originalScores.get('mem-z-strong'), 'the absorbed source retains its stronger original BM25 score')
1161
+ assert.equal(host.lexicalEvidence, evidenceScores.get('mem-z-strong'), 'topical BM25 evidence is inherited independently of raw lexical')
1162
+ assert.deepEqual(host.mergedTogether, ['mem-z-strong'])
1163
+ assert.ok(result.fusion.collapsed.some(group => group.kept === 'mem-z-strong' && group.dropped.includes('mem-a-host')), 'within-leg duplicate folding occurred')
1164
+ assert.ok(result.fusion.collapsed.some(group => group.kept === 'mem-a-host' && group.dropped.includes('mem-z-strong')), 'semantic/cross-leg host absorbed the lexical source')
1165
+ assert.equal(result.fusion.lexicalDominance.id, 'mem-a-host', 'the surviving host owns the final dominance trace')
1166
+ assert.equal(result.fusion.lexicalDominance.topLex, host.lexicalEvidence)
1167
+ assert.equal(host.fusion.rawRetrievalScore, 1)
1168
+ await assertRankingBoundary(1)
1169
+ })
1170
+
1171
+ test('real BM25 Python in a request is topical evidence rather than a disposable reply template', async () => {
1172
+ const query = '请用Python回答TLS故障原因'
1173
+ const entries = {
1174
+ 'mem-python': rankingEntry('请用Python回答TLS故障原因:Python ssl 模块报告证书过期。'),
1175
+ 'mem-other': rankingEntry(pianoNotes[0]),
1176
+ }
1177
+ const f = fixture(entries)
1178
+ activate([f.libraryId])
1179
+ retrieveHook = () => ({ files: [], segments: [], resources: [] })
1180
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.4 })
1181
+ assert.equal(result.files[0]?.name, 'mem-python', 'a topic-bearing imperative must not be cleared')
1182
+ const hit = result.files[0]
1183
+ assert.equal(hit.lexical, realLexical(entries, query).get('mem-python'))
1184
+ assert.equal(hit.lexicalEvidence ?? hit.lexical, hit.lexical, 'Python/TLS are retained in dominance evidence')
1185
+ assert.equal(calls[0].query, query)
1186
+ await assertRankingBoundary(1)
1187
+ })
1188
+
1189
+ test('automatic recall backfills a sixth qualified hit and reintroduces a changed admitted revision', async () => {
1190
+ state.updateSettings({ hybridRecall: true })
1191
+ const names = Array.from({ length: 6 }, (_, i) => 'mem-replay-' + i)
1192
+ const stamp = new Date(Date.now() - 86400000).toISOString()
1193
+ const entries = Object.fromEntries(names.map((name, i) => [name, rankingEntry(`AtlasReplay 部署备份节点${i}保留14天,每天执行核验。`, { createdAt: stamp, updatedAt: stamp })]))
1194
+ const f = fixture(entries)
1195
+ activate([f.libraryId])
1196
+ retrieveHook = () => ({ files: names.map(name => ({ name })), segments: [], resources: [] })
1197
+ const query = 'AtlasReplay 部署备份保留14天'
1198
+ const initial = await memory.privateRecall({ exec: f.exec, query, topK: 6, relevanceThreshold: 0.8, purpose: 'automatic' })
1199
+ assert.equal(initial.groups.length, 6)
1200
+ const shown = initial.refs.slice(0, 5)
1201
+ state.markInjectedRefs(f.sessionId, shown, 1, { messageId: 'admitted-replay-five', hostTurn: 1 })
1202
+ const excludedRefs = state.recentMemoryRefs(state.getSessionBinding(f.sessionId), 2, 16)
1203
+ const next = await memory.privateRecall({ exec: f.exec, query, topK: 1, relevanceThreshold: 0.8, purpose: 'automatic', excludedRefs })
1204
+ assert.equal(next.groups.length, 1)
1205
+ assert.equal(next.files[0].name, initial.refs[5].id)
1206
+ assert.equal(next.trace.counts.recentRows, 5)
1207
+ const changedId = shown[0].id
1208
+ await state.updatePrivateIndex(f.libraryId, index => { index.entries[changedId].content += ' 已补充副本验证。' })
1209
+ const changed = await memory.privateRecall({ exec: f.exec, query, topK: 1, relevanceThreshold: 0.8, purpose: 'automatic', excludedRefs })
1210
+ assert.equal(changed.files[0].name, changedId)
1211
+ assert.notEqual(changed.refs[0].revision, shown[0].revision)
1212
+ assert.equal(changed.groups[0].reintroducedForRevision, true)
1213
+ await assertRankingBoundary(2)
1214
+ })
1215
+
1216
+ test('automatic recent exclusion cannot promote an unqualified lexical-only noise hit', async () => {
1217
+ state.updateSettings({ hybridRecall: true })
1218
+ const names = Array.from({ length: 5 }, (_, i) => 'mem-qualified-' + i)
1219
+ const stamp = new Date(Date.now() - 86400000).toISOString()
1220
+ const entries = Object.fromEntries(names.map((name, i) => [name, rankingEntry(`AtlasQuiet 部署备份节点${i}保留14天,每天执行核验。`, { createdAt: stamp, updatedAt: stamp })]))
1221
+ entries['mem-quiet-noise'] = rankingEntry('AtlasQuiet 的闲聊杂谈,没有备份安排。', { createdAt: stamp, updatedAt: stamp })
1222
+ const f = fixture(entries)
1223
+ activate([f.libraryId])
1224
+ retrieveHook = () => ({ files: names.map(name => ({ name })), segments: [], resources: [] })
1225
+ const query = 'AtlasQuiet 部署备份保留14天'
1226
+ const initial = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8, purpose: 'automatic' })
1227
+ assert.equal(initial.refs.length, 5)
1228
+ state.markInjectedRefs(f.sessionId, initial.refs, 1, { messageId: 'admitted-qualified-five', hostTurn: 1 })
1229
+ const next = await memory.privateRecall({ exec: f.exec, query, topK: 1, relevanceThreshold: 0.8, purpose: 'automatic', excludedRefs: state.recentMemoryRefs(state.getSessionBinding(f.sessionId), 2, 16) })
1230
+ assert.deepEqual(next.files, [])
1231
+ assert.ok(next.trace.counts.weakRows > 0)
1232
+ assert.equal(next.trace.counts.recentRows, 5)
1233
+ await assertRankingBoundary(2)
1234
+ })