dsh-memu-memory 1.4.1 → 1.4.3

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 -108
  2. package/CHANGELOG.md +169 -848
  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 -72
  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 -0
  18. package/docs/memory-semantics.md +271 -259
  19. package/docs/pending-work.md +44 -51
  20. package/docs/troubleshooting.md +909 -840
  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 -9648
  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 -1035
  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 -4911
  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 -0
  79. package/lib/preset-mount.js +79 -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 -2518
  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 -1066
  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 +1015 -979
  122. package/package.json +153 -152
  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 -455
  182. package/tests/client-export.test.mjs +521 -520
  183. package/tests/client-render.test.mjs +2008 -1727
  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 +1586 -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 -48
  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 -415
  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 -616
  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 -0
  327. package/tests/preset-mount.test.mjs +124 -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 -23
  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 -221
  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 -212
  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 -414
  388. package/tests/windows-env.test.mjs +89 -89
  389. package/tests/worker-lifecycle.test.mjs +1521 -1429
@@ -1,810 +1,810 @@
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
-
7
- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-tools-'))
8
- process.env.DSH_MEMU_HOME = home
9
-
10
- const { registerTools } = await import('../lib/tools.js')
11
- const state = await import('../lib/state.js')
12
- const { updateSettings } = state
13
- const { redactSecrets } = await import('../lib/paths.js')
14
- const { createHash } = await import('node:crypto')
15
-
16
- test.after(() => {
17
- state.flushState()
18
- try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
19
- })
20
-
21
- function fakeCtx() {
22
- const tools = []
23
- const ctx = {
24
- tools: {
25
- register(tool) {
26
- tools.push(tool)
27
- return () => {}
28
- },
29
- },
30
- logger: { warn() {} },
31
- }
32
- const dispose = registerTools(ctx)
33
- return { ctx, tools, dispose }
34
- }
35
-
36
- const exec = {
37
- agent: { session: { header: { id: 'tools-session', cwd: path.join(home, 'project-tools'), agentPreset: 'coding' } } },
38
- }
39
-
40
- test('all v1 tools register', () => {
41
- const { tools, dispose } = fakeCtx()
42
- const names = tools.map((t) => t.name)
43
- for (const name of [
44
- 'memu_private_link',
45
- 'memu_private_link_suggest',
46
- 'memu_private_remember',
47
- 'memu_private_remember_batch',
48
- 'memu_private_recall',
49
- 'memu_private_list',
50
- 'memu_private_update',
51
- 'memu_private_archive',
52
- 'memu_private_unpin',
53
- 'memu_lexicon_search',
54
- 'memu_lexicon_propose',
55
- 'memu_global_recall',
56
- 'memu_global_list',
57
- 'memu_status',
58
- ]) {
59
- assert.ok(names.includes(name), `missing ${name}`)
60
- }
61
- // Exactly fourteen, not "at least these": a schema the host DSL refuses used to
62
- // abort registerTools() before any register() ran, so counting is the assertion
63
- // that actually catches a total registration failure.
64
- assert.equal(names.length, 14, `expected 14 tools, got ${names.length}: ${names.join(', ')}`)
65
- dispose()
66
- })
67
-
68
- test('batch write applies shared defaults and reports each item', async () => {
69
- const { tools, dispose } = fakeCtx()
70
- const batch = tools.find((t) => t.name === 'memu_private_remember_batch')
71
- const batchExec = {
72
- agent: { session: { header: { id: 'tools-batch-session', cwd: path.join(home, 'project-batch'), agentPreset: 'coding' } } },
73
- }
74
- const reply = await batch.execute({
75
- defaults: { speaker_id: 'user', source: 'user_said', observed_at: '2026-11-06T04:00:00+08:00' },
76
- items: [
77
- { title: '码头见面', content: '明天下午三点在码头见面,别迟到。' },
78
- { title: '带伞', content: '她说码头风大,让我带把伞。' },
79
- ],
80
- }, batchExec)
81
- assert.match(reply, /批量写入完成:新增 2/)
82
- assert.match(reply, /1\. 已写入私有记忆/)
83
- assert.match(reply, /2\. 已写入私有记忆/)
84
- const empty = await batch.execute({ items: [] }, batchExec)
85
- assert.match(empty, /items 为空/)
86
- dispose()
87
- })
88
-
89
- test('status works without an engine', async () => {
90
- const { tools, dispose } = fakeCtx()
91
- const status = await tools.find((t) => t.name === 'memu_status').execute({}, exec)
92
- assert.match(status, /engine:/)
93
- assert.match(status, /library:/)
94
- // The registration count is the visible signal for a refused schema: without it
95
- // a host that rejects the tool and a plugin that never had it look identical.
96
- assert.match(status, /tools: 14\/14 registered/)
97
- dispose()
98
- })
99
-
100
- test('title descriptions explain the permanent index rule', () => {
101
- const { tools, dispose } = fakeCtx()
102
- const remember = tools.find((t) => t.name === 'memu_private_remember')
103
- const update = tools.find((t) => t.name === 'memu_private_update')
104
- for (const tool of [remember, update]) {
105
- const title = tool.parameters.title.description
106
- assert.match(title, /8-40/, `${tool.name} title carries the 8-40 rule`)
107
- assert.match(title, /name the concrete fact|title is a permanent index|anchor shows only titles/, `${tool.name} title says it is an index`)
108
- assert.match(title, /empty label/, `${tool.name} title forbids empty labels`)
109
- }
110
- assert.match(remember.parameters.title.description, /WITHOUT the body/, 'the anchor shows titles without bodies')
111
- const link = tools.find((t) => t.name === 'memu_private_link')
112
- assert.match(link.description, /memu_private_link_suggest/, 'link is named as the adjudication tool for candidates')
113
- assert.match(link.parameters.entity.description, /reused/, 'a named entity can be reused instead of duplicated')
114
- const search = tools.find((t) => t.name === 'memu_lexicon_search')
115
- assert.match(search.description, /ACTIVE/)
116
- assert.match(search.description, /archived entries are excluded/)
117
- const propose = tools.find((t) => t.name === 'memu_lexicon_propose')
118
- assert.match(propose.description, /ACTIVE immediately/)
119
- assert.doesNotMatch(propose.description, /stored as pending|needs human review before/, 'a model proposal is no longer pending')
120
- assert.match(propose.parameters.term.description, /index key/)
121
- assert.match(propose.parameters.meaning.description, /explanation/)
122
- assert.match(tools.find((t) => t.name === 'memu_private_link_suggest').parameters.ids.description, /Required/)
123
- dispose()
124
- })
125
-
126
- test('lexicon propose writes an active entry immediately; search only sees active terms', async () => {
127
- const { tools, dispose } = fakeCtx()
128
- const cwd = path.join(home, 'project-lex')
129
- const execLex = { agent: { session: { header: { id: 'tools-lex', cwd, agentPreset: 'coding' } } } }
130
- const binding = state.ensureSession('tools-lex', { cwd, agentPreset: 'coding' })
131
- const lexicon = await import('../lib/lexicon.js')
132
- const propose = tools.find((t) => t.name === 'memu_lexicon_propose')
133
- const search = tools.find((t) => t.name === 'memu_lexicon_search')
134
-
135
- const written = await propose.execute({ term: '糖刀', kind: 'slang', meaning: '又甜又扎人的说话方式。' }, execLex)
136
- assert.match(written, /status=active/)
137
- assert.doesNotMatch(written, /pending|待审/)
138
- const storedPair = Object.entries(lexicon.loadLexicon(binding.libraryId).terms).find(([, entry]) => entry.term === '糖刀')
139
- const stored = storedPair[1]
140
- assert.equal(stored.status, 'active', 'model-proposal lands as active, no review step')
141
- assert.equal(stored.source, 'model-proposal')
142
-
143
- // Writing the same normalized term again updates the active entry, it does not fork it.
144
- const again = await propose.execute({ term: '糖刀', kind: 'slang', meaning: '又甜又扎人的说话方式。', usage: '撒娇时用。' }, execLex)
145
- assert.match(again, /已更新现有生效词条/)
146
- assert.equal(Object.values(lexicon.loadLexicon(binding.libraryId).terms).filter((entry) => entry.term === '糖刀').length, 1)
147
-
148
- const hit = await search.execute({ query: '糖刀' }, execLex)
149
- assert.match(hit, /糖刀/)
150
-
151
- // Archived terms leave both the search surface and injection.
152
- lexicon.archiveLexiconTerm({ libraryId: binding.libraryId, termId: storedPair[0] })
153
- const archived = await search.execute({ query: '糖刀' }, execLex)
154
- assert.match(archived, /没有命中/)
155
- // Writing the archived term again is not the model's call: it reports the entry was not changed.
156
- const notOwned = await propose.execute({ term: '糖刀', kind: 'slang', meaning: '再次写入。' }, execLex)
157
- assert.match(notOwned, /未改动/)
158
- assert.match(notOwned, /已归档或归用户管理/)
159
- assert.equal(Object.values(lexicon.loadLexicon(binding.libraryId).terms).find((entry) => entry.term === '糖刀').status, 'archived')
160
-
161
- const refused = await propose.execute({ term: '别离开我', kind: 'trigger', meaning: '离别场景的触发词。' }, execLex)
162
- assert.match(refused, /sensitive trigger/, 'a sensitive trigger stays user-managed')
163
- dispose()
164
- })
165
-
166
- function namedEntityFixture(suffix, content, extra = {}) {
167
- const id = 'tools-named-' + suffix
168
- const cwd = path.join(home, id)
169
- const binding = state.ensureSession(id, { cwd, agentPreset: 'rp' })
170
- const namedExec = { agent: { session: { header: { id, cwd, agentPreset: 'rp' } } } }
171
- state.savePrivateIndex(binding.libraryId, { version: 1, entries: {
172
- 'mem-source': { title: '来访记录', content, status: 'active', visibility: 'shared', layer: 'long_term', ...extra },
173
- } })
174
- return { binding, namedExec }
175
- }
176
-
177
- for (const [i, name] of ['忆组件', '主人一', '人一', '主人一说'].entries()) {
178
- test('new named entity rejects an unsupported fragment: ' + name, async () => {
179
- const { tools, dispose } = fakeCtx()
180
- const { binding, namedExec } = namedEntityFixture('fragment-' + i, '记忆组件负责保存资料,主人一说话就会得到回应。')
181
- const link = tools.find(tool => tool.name === 'memu_private_link')
182
- const graph = await import('../lib/graph.js')
183
- try {
184
- const reply = await link.execute({ from: 'mem-source', entity: { name, kind: 'person' }, kind: 'person', note: '原文出现了相同片段,因此把它作为同一人物关联。' }, namedExec)
185
- assert.match(reply, /完整名称|complete name/, 'a substring is not evidence of a complete identity')
186
- assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 0, 'rejection creates no entity')
187
- assert.deepEqual(state.loadPrivateIndex(binding.libraryId).entries['mem-source'].links || [], [], 'rejection creates no link')
188
- } finally { dispose() }
189
- })
190
- }
191
-
192
- test('new named entity validates source and link before creating any entity', async () => {
193
- const { tools, dispose } = fakeCtx()
194
- const link = tools.find(tool => tool.name === 'memu_private_link')
195
- const graph = await import('../lib/graph.js')
196
- const cases = [
197
- { suffix: 'missing', args: { from: 'mem-missing' } },
198
- { suffix: 'secret', extra: { visibility: 'secret' } },
199
- { suffix: 'archived', extra: { status: 'archived' } },
200
- { suffix: 'note', args: { note: 'short' } },
201
- { suffix: 'confidence', args: { confidence: 2 } },
202
- { suffix: 'kind', args: { kind: 'typo' } },
203
- { suffix: 'person-target', args: { entity: { name: '阿兰', kind: 'thing' } } },
204
- { suffix: 'limit', extra: { links: Array.from({ length: 100 }, (_, i) => ({ to: 'mem-limit-' + i, kind: 'event' })) } },
205
- ]
206
- try {
207
- for (const item of cases) {
208
- const { binding, namedExec } = namedEntityFixture(item.suffix, '她叫阿兰,今天来送信。', item.extra)
209
- const reply = await link.execute({ from: 'mem-source', entity: { name: '阿兰', kind: 'person' }, kind: 'person', note: '原文写着她叫阿兰,这封信由她送来。', ...item.args }, namedExec)
210
- assert.match(reply, /error/, item.suffix + ' must be rejected')
211
- assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 0, item.suffix + ' leaves no orphan entity')
212
- }
213
- } finally { dispose() }
214
- })
215
-
216
- test('new named entities require evidence in source memory rather than an invented note', async () => {
217
- const { tools, dispose } = fakeCtx()
218
- const link = tools.find(tool => tool.name === 'memu_private_link')
219
- const graph = await import('../lib/graph.js')
220
- try {
221
- for (const [suffix, name, content] of [
222
- ['note-spoof', '阿兰', '今天由一位邻居送来一封信。'],
223
- ['latin-fragment', 'alice', 'malice appeared in the log.'],
224
- ]) {
225
- const { binding, namedExec } = namedEntityFixture(suffix, content)
226
- const reply = await link.execute({ from: 'mem-source', entity: { name, kind: 'person' }, kind: 'person', note: '据我推测,这位邻居的完整名字是「' + name + '」。' }, namedExec)
227
- assert.match(reply, /完整名称|complete name/)
228
- assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 0)
229
- }
230
- } finally { dispose() }
231
- })
232
-
233
- test('complete quoted and introduced names remain usable and existing aliases are reused', async () => {
234
- const { tools, dispose } = fakeCtx()
235
- const link = tools.find(tool => tool.name === 'memu_private_link')
236
- const graph = await import('../lib/graph.js')
237
- try {
238
- for (const [i, name, content] of [
239
- [0, '阿兰', '她叫阿兰,今天来送信。'],
240
- [1, '小檀', '「小檀」今天来送信。'],
241
- [2, '主人一', '这个角色自称「主人一」,这是完整昵称。'],
242
- [3, 'Alice', 'Alice delivered the letter.'],
243
- [4, 'Old Zhou', 'Old Zhou delivered the letter.'],
244
- ]) {
245
- const { binding, namedExec } = namedEntityFixture('positive-' + i, content)
246
- const reply = await link.execute({ from: 'mem-source', entity: { name, kind: 'person' }, kind: 'person', note: '原文明确写出完整名称 ' + name + ',关联这个同一人物。' }, namedExec)
247
- const result = JSON.parse(reply)
248
- const entity = graph.listEntities({ libraryId: binding.libraryId }).items.find(item => item.id === result.to)
249
- assert.equal(entity.name, name)
250
- assert.equal(entity.status, 'provisional', 'evidence of a full name alone is not user confirmation')
251
- }
252
- const { binding, namedExec } = namedEntityFixture('alias', '这位邻居送来一封信。')
253
- const existing = graph.createEntity({ libraryId: binding.libraryId, name: '周宁', kind: 'person', aliases: ['Old Zhou'], status: 'confirmed' })
254
- graph.linkEntries({ libraryId: binding.libraryId, fromId: 'mem-source', toId: existing.id, kind: 'person', note: '先前已由用户确认这位邻居的身份。' })
255
- const result = JSON.parse(await link.execute({ from: 'mem-source', entity: { name: 'OLD ZHOU', kind: 'person' }, kind: 'person', note: '复用用户此前已经确认的同一人物别名。' }, namedExec))
256
- assert.equal(result.to, existing.id)
257
- assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 1)
258
- } finally { dispose() }
259
- })
260
-
261
- test('link suggest refreshes deterministic mention edges and returns only uncertain candidates', async () => {
262
- const { tools, dispose } = fakeCtx()
263
- const cwd = path.join(home, 'project-links')
264
- const execLinks = { agent: { session: { header: { id: 'tools-links', cwd, agentPreset: 'rp' } } } }
265
- const binding = state.ensureSession('tools-links', { cwd, agentPreset: 'rp' })
266
- const graph = await import('../lib/graph.js')
267
- const yuike = graph.createEntity({ libraryId: binding.libraryId, name: 'yuike', kind: 'person', status: 'confirmed', confirmedBy: 'user' })
268
- state.savePrivateIndex(binding.libraryId, { version: 1, entries: {
269
- 'mem-a': { title: '猫娘yuike', content: 'yuike 是一只住在窗台的猫娘,喜欢晒太阳。', status: 'active', visibility: 'shared', layer: 'long_term' },
270
- 'mem-b': { title: 'yuike名字的由来', content: '这个名字来自小时候养过的一只白猫。', status: 'active', visibility: 'shared', layer: 'long_term' },
271
- } })
272
- const suggest = tools.find((t) => t.name === 'memu_private_link_suggest')
273
- assert.equal(suggest.isConcurrencySafe(), false, 'suggest writes links, so it is not a concurrent read')
274
-
275
- const unbound = await suggest.execute({ ids: ['mem-a'] }, {
276
- agent: { session: { header: { id: 'tools-links-unbound', cwd: path.join(home, 'project-links-unbound') } } },
277
- })
278
- assert.match(unbound, /没有绑定记忆库/)
279
- const empty = await suggest.execute({ ids: [] }, execLinks)
280
- assert.match(empty, /1-20/)
281
-
282
- updateSettings({ autoLinkMode: 'deterministic' })
283
- try {
284
- const payload = JSON.parse(await suggest.execute({ ids: ['mem-a', 'mem-b'] }, execLinks))
285
- assert.deepEqual(Object.keys(payload).sort(), ['autoLinked', 'candidates'], 'the tool answers with the two-field contract only')
286
- assert.deepEqual(payload.candidates, [], 'the yuike pair is a deterministic mention, not an uncertain candidate')
287
- assert.equal(payload.autoLinked.length, 2, 'one mention edge per memory, no lexical pair edge')
288
- for (const edge of payload.autoLinked) {
289
- assert.deepEqual(Object.keys(edge).sort(), ['from', 'kind', 'to'], 'no bodies or notes in the compact payload')
290
- assert.equal(edge.to, yuike.id)
291
- assert.equal(edge.kind, 'person')
292
- }
293
- // The deterministic edge survives into the graph the UI reads.
294
- const view = graph.getGraph({ libraryId: binding.libraryId, focusId: 'mem-a', depth: 1 })
295
- assert.ok(view.edges.some((edge) => edge.from === 'mem-a' && edge.to === yuike.id && edge.source === 'auto'))
296
-
297
- // Running it again is idempotent: no new links, same empty candidate list.
298
- const rerun = JSON.parse(await suggest.execute({ ids: ['mem-a', 'mem-b'] }, execLinks))
299
- assert.deepEqual(rerun.autoLinked, [])
300
- assert.deepEqual(rerun.candidates, [])
301
- } finally {
302
- updateSettings({ autoLinkMode: 'suggest' })
303
- }
304
- dispose()
305
- })
306
-
307
- test('private list stays usable without an active vector profile and says why', async () => {
308
- const { tools, dispose } = fakeCtx()
309
- updateSettings({ memoryBackend: 'api' })
310
- try {
311
- // The conversation must actually be bound: an unbound chat gets the
312
- // "no library" answer instead, and never creates one just by listing.
313
- state.ensureSession('tools-session', { cwd: path.join(home, 'project-tools') })
314
- const text = await tools.find((t) => t.name === 'memu_private_list').execute({}, exec)
315
- // No active generation means MemU cannot answer; the index still can. "Empty"
316
- // on its own reads as lost memories, so the reason travels with the result.
317
- assert.match(text, /私有记忆库 .* 为空。/)
318
- assert.match(text, /本地向量未激活/)
319
- } finally {
320
- updateSettings({ memoryBackend: 'agent' })
321
- dispose()
322
- }
323
- })
324
-
325
- test('private list on an unbound conversation neither creates a library nor errors', async () => {
326
- const { tools, dispose } = fakeCtx()
327
- const before = state.listLibraries().length
328
- const text = await tools.find((t) => t.name === 'memu_private_list').execute({}, {
329
- agent: { session: { header: { id: 'tools-unbound', cwd: path.join(home, 'project-unbound'), agentPreset: 'coding' } } },
330
- })
331
- assert.match(text, /没有绑定记忆库/)
332
- assert.equal(state.listLibraries().length, before, 'listing must not materialize a library')
333
- dispose()
334
- })
335
-
336
- test('private list rows carry the same date label recall prints', async () => {
337
- const { tools, dispose } = fakeCtx()
338
- const cwd = path.join(home, 'project-dates')
339
- const execDates = { agent: { session: { header: { id: 'tools-list-dates', cwd, agentPreset: 'coding' } } } }
340
- state.ensureSession('tools-list-dates', { cwd })
341
- const remember = tools.find((t) => t.name === 'memu_private_remember')
342
- // Two forms of the same field: an appointment keeps its year, a birthday keeps MM-DD.
343
- await remember.execute({ content: '明天要去考驾照。', title: '明天要考驾照', salient_date: '2026-10-29' }, execDates)
344
- await remember.execute({ content: '生日是 10 月 28 日。', title: '生日', salient_date: '10-28' }, execDates)
345
- const list = await tools.find((t) => t.name === 'memu_private_list').execute({}, execDates)
346
- // A date only recall renders reads as "no date" in the list, so the two surfaces
347
- // must agree on the spelling: date= for a one-off, anniversary= for a yearly one.
348
- assert.match(list, /date=2026-10-29/)
349
- assert.match(list, /anniversary=10-28/)
350
- dispose()
351
- })
352
-
353
- test('must_remember requires a pin reason', async () => {
354
- const { tools, dispose } = fakeCtx()
355
- const text = await tools.find((t) => t.name === 'memu_private_remember').execute({
356
- content: 'something worth keeping',
357
- layer: 'must_remember',
358
- }, exec)
359
- assert.match(text, /pin_reason is required/)
360
- dispose()
361
- })
362
-
363
- test('status separates "nobody polled" from "nothing was written"', async () => {
364
- const { tools, dispose } = fakeCtx()
365
- const { dispatch } = await import('../lib/rpc.js')
366
- // A pane polling is what records a beat; a save is what records a write event.
367
- await dispatch({}, 'getSidebarState', { revisionOnly: true })
368
- state.savePrivateIndex('lib-sync', { version: 1, entries: {} })
369
- const unbound = { agent: { session: { header: { id: 'tools-sync', cwd: path.join(home, 'project-sync') } } } }
370
- const text = await tools.find((t) => t.name === 'memu_status').execute({}, unbound)
371
- assert.match(text, /sync: heartbeat \d+s ago, last write private@lib-sync \d+s ago/)
372
- dispose()
373
- })
374
-
375
- test('unpin is the model\'s call, guarded by reason, quota and cooldown', async () => {
376
- const { tools, dispose } = fakeCtx()
377
- const binding = state.ensureSession('tools-session', { cwd: path.join(home, 'project-tools'), agentPreset: 'coding' })
378
- const index = state.loadPrivateIndex(binding.libraryId)
379
- for (const id of ['mem-unpin', 'mem-unpin-2', 'mem-unpin-3']) {
380
- index.entries[id] = {
381
- track: 'memory',
382
- layer: 'must_remember',
383
- title: `A pinned memory ${id}`,
384
- content: 'Something that used to matter.',
385
- status: 'active',
386
- pinSource: 'user_explicit',
387
- pinReason: 'keep this',
388
- createdAt: new Date().toISOString(),
389
- updatedAt: new Date().toISOString(),
390
- }
391
- }
392
- state.savePrivateIndex(binding.libraryId, index)
393
-
394
- const exec = { agent: { session: { header: { id: 'tools-session' } } } }
395
- const unpin = (id, reason) => tools.find((t) => t.name === 'memu_private_unpin').execute({ id, reason }, exec)
396
-
397
- const tooShort = await unpin('mem-unpin', 'let it go')
398
- assert.match(tooShort, /at least 20 characters/)
399
- assert.equal(state.loadPrivateIndex(binding.libraryId).entries['mem-unpin'].layer, 'must_remember')
400
-
401
- const accepted = await unpin('mem-unpin', '那件事已经过去了,我现在能把它当成一件旧事来讲,而不是每次想起都疼。')
402
- assert.match(accepted, /long_term|marginalized|边缘化/)
403
- const after = state.loadPrivateIndex(binding.libraryId).entries['mem-unpin']
404
- assert.equal(after.layer, 'long_term')
405
- assert.equal(after.marginalized, true)
406
- assert.equal(after.unpinnedBy, 'model')
407
- assert.ok(after.originalPinSource !== undefined)
408
-
409
- // Cooldown: a second unpin right after is refused even though quota remains.
410
- const cooldown = await unpin('mem-unpin-2', '这次也一样,我已经能平静地说完了,不再需要一直记着。')
411
- assert.match(cooldown, /cooldown/)
412
- assert.equal(state.loadPrivateIndex(binding.libraryId).entries['mem-unpin-2'].layer, 'must_remember')
413
-
414
- // Quota: once the conversation has spent it, memory stays pinned.
415
- state.setSessionBinding('tools-session', { lastUnpinAt: null, unpinCount: 2 })
416
- const quota = await unpin('mem-unpin-3', '我已经想清楚了,这件事可以放下来,不必再一直提醒自己。')
417
- assert.match(quota, /quota/)
418
- dispose()
419
- })
420
-
421
- let readFixtureNumber = 0
422
- function readFixture(entries = {}, domain = 'coding') {
423
- const sessionId = `tools-read-${++readFixtureNumber}`
424
- const cwd = path.join(home, sessionId)
425
- const binding = state.ensureSession(sessionId, { cwd, agentPreset: domain })
426
- state.setSessionBinding(sessionId, { domainOverride: domain })
427
- const index = { version: 1, entries: Object.fromEntries(Object.entries(entries).map(([id, entry]) => [id, {
428
- id, title: '读取测试', content: '', status: 'active', layer: 'long_term', visibility: 'shared', disclosure: 'can_tell',
429
- source: 'user_said', source_kind: 'user_said', speaker_id: 'user', domain,
430
- createdAt: '2026-11-01T00:00:00.000Z', updatedAt: '2026-11-01T00:00:00.000Z', ...entry,
431
- }])) }
432
- state.savePrivateIndex(binding.libraryId, index)
433
- const registered = fakeCtx()
434
- return { ...registered, sessionId, cwd, binding, exec: { agent: { session: { header: { id: sessionId, cwd } } } },
435
- privateTool: registered.tools.find((tool) => tool.name === 'memu_private_recall'),
436
- globalTool: registered.tools.find((tool) => tool.name === 'memu_global_recall') }
437
- }
438
-
439
- function parsedPage(reply) {
440
- assert.equal(typeof reply, 'string', 'tool receipts remain strings')
441
- const match = reply.match(/pagination: unit=codepoint · offset=(\d+) · returned_chars=(\d+) · total_chars=(\d+) · truncated=(true|false) · next_offset=(\d+|null)/)
442
- assert.ok(match, `missing codepoint pagination: ${reply}`)
443
- const revision = reply.match(/^revision=([a-f0-9]{64})$/m)?.[1]
444
- assert.ok(revision, 'the redacted body SHA256 must be visible')
445
- const body = reply.split('\nbody:\n')[1]?.split(/\n(?:next:|conflict:)/)[0]
446
- assert.notEqual(body, undefined)
447
- return { body, revision, offset: Number(match[1]), returnedChars: Number(match[2]), totalChars: Number(match[3]),
448
- truncated: match[4] === 'true', nextOffset: match[5] === 'null' ? null : Number(match[5]) }
449
- }
450
-
451
- const sha256 = (body) => createHash('sha256').update(body).digest('hex')
452
- const tailBody = (length) => '甲'.repeat(length - 5) + '仅限测试尾'
453
-
454
- test('empty bodies and the exact end offset are valid zero-length pages, not range errors', async () => {
455
- const f = readFixture({ 'mem-empty': { content: '' }, 'mem-end': { content: '😀末尾' } })
456
- try {
457
- const empty = parsedPage(await f.privateTool.execute({ query: 'mem-empty' }, f.exec))
458
- assert.deepEqual([empty.body, empty.totalChars, empty.returnedChars, empty.truncated, empty.nextOffset], ['', 0, 0, false, null])
459
- assert.equal(empty.revision, sha256(''))
460
- const start = parsedPage(await f.privateTool.execute({ query: 'mem-end' }, f.exec))
461
- const end = parsedPage(await f.privateTool.execute({ query: 'mem-end', offset: start.totalChars, revision: start.revision }, f.exec))
462
- assert.equal(end.body, '')
463
- assert.equal(end.returnedChars, 0)
464
- assert.equal(end.nextOffset, null)
465
- assert.match(await f.privateTool.execute({ query: 'mem-empty', offset: 1, revision: empty.revision }, f.exec), /MEMORY_OFFSET_OUT_OF_RANGE/)
466
- } finally { f.dispose() }
467
- })
468
-
469
- test('exact snippet centering reports its actual codepoint coordinates and a resumable next ref', async () => {
470
- const id = 'mem-centered-exact'
471
- const body = '😀'.repeat(200) + id + '🚀'.repeat(200)
472
- const f = readFixture({ [id]: { content: body } })
473
- try {
474
- const reply = await f.privateTool.execute({ query: id, view: 'snippet' }, f.exec)
475
- const page = parsedPage(reply)
476
- assert.equal(page.offset, 160)
477
- assert.equal(page.returnedChars, 160)
478
- assert.equal(page.body, '…' + Array.from(body).slice(160, 320).join('') + '…')
479
- assert.equal(page.nextOffset, 320)
480
- assert.equal(page.totalChars, Array.from(body).length)
481
- const rest = parsedPage(await f.privateTool.execute({ query: id, libraryId: f.binding.libraryId, offset: page.nextOffset, revision: page.revision }, f.exec))
482
- assert.equal(rest.body, Array.from(body).slice(320).join(''))
483
- } finally { f.dispose() }
484
- })
485
-
486
- test('private explicit reads allow secret/disclosure but never open archived or superseded entries', async () => {
487
- const f = readFixture({
488
- 'mem-secret': { content: '显式秘密正文', visibility: 'secret', disclosure: 'never_say' },
489
- 'mem-asked': { content: '仅当被问到的正文', disclosure: 'only_if_asked' },
490
- 'mem-archived': { content: '归档正文不开放', status: 'archived' },
491
- 'mem-superseded': { content: '被替代正文不开放', status: 'superseded' },
492
- 'mem-held': { content: '待复核正文不开放', status: 'pending_review' },
493
- })
494
- try {
495
- assert.equal(parsedPage(await f.privateTool.execute({ query: 'mem-secret' }, f.exec)).body, '显式秘密正文')
496
- assert.equal(parsedPage(await f.privateTool.execute({ query: 'mem-asked' }, f.exec)).body, '仅当被问到的正文')
497
- for (const id of ['mem-archived', 'mem-superseded', 'mem-held']) {
498
- const reply = await f.privateTool.execute({ query: id }, f.exec)
499
- assert.match(reply, /MEMORY_NOT_READABLE/)
500
- assert.doesNotMatch(reply, /正文不开放/)
501
- }
502
- state.setSessionBinding(f.sessionId, { useLibrary: false })
503
- assert.doesNotMatch(await f.privateTool.execute({ query: 'mem-secret' }, f.exec), /显式秘密正文/)
504
- } finally { f.dispose() }
505
- })
506
-
507
- test('global exact reads retain automatic/domain eligibility', async () => {
508
- const f = readFixture()
509
- const saved = state.loadGlobalIndex()
510
- state.saveGlobalIndex({ version: 1, entries: {
511
- 'gmem-good': { content: '合法全局正文', status: 'active', domain: 'coding', source: 'tool' },
512
- 'gmem-secret': { content: '不开放秘密', status: 'active', domain: 'coding', visibility: 'secret' },
513
- 'gmem-never': { content: '不开放披露', status: 'active', domain: 'coding', disclosure: 'never_say' },
514
- 'gmem-asked': { content: '不开放仅问', status: 'active', domain: 'coding', disclosure: 'only_if_asked' },
515
- 'gmem-rp': { content: '不开放异域', status: 'active', domain: 'rp' },
516
- 'gmem-archived': { content: '不开放归档', status: 'archived', domain: 'coding' },
517
- } })
518
- try {
519
- assert.equal(parsedPage(await f.globalTool.execute({ query: 'gmem-good.md' }, f.exec)).body, '合法全局正文')
520
- for (const id of ['gmem-secret', 'gmem-never', 'gmem-asked', 'gmem-rp', 'gmem-archived']) {
521
- const reply = await f.globalTool.execute({ query: id }, f.exec)
522
- assert.match(reply, /MEMORY_NOT_READABLE/)
523
- assert.doesNotMatch(reply, /不开放/)
524
- }
525
- assert.match(await f.globalTool.execute({ query: 'gmem-unknown' }, f.exec), /MEMORY_NOT_FOUND/)
526
- state.setSessionBinding(f.sessionId, { useGlobal: false })
527
- assert.doesNotMatch(await f.globalTool.execute({ query: 'gmem-good' }, f.exec), /合法全局正文/)
528
- } finally { state.saveGlobalIndex(saved); f.dispose() }
529
- })
530
-
531
- test('cross-library same-id reads honor libraryId, domain and opt-in without changing bindings', async () => {
532
- const current = readFixture({ 'mem-same': { content: '本库正文', domain: 'rp' } })
533
- const foreign = readFixture({ 'mem-same': { content: '外库正文' }, 'mem-foreign-rp': { content: '外库异域禁止', domain: 'rp' } })
534
- const different = readFixture({ 'mem-same': { content: '异域库正文禁止' } }, 'rp')
535
- const savedCross = state.getSettings().crossLibraryRecall
536
- try {
537
- updateSettings({ crossLibraryRecall: false })
538
- assert.match(await current.privateTool.execute({ query: 'mem-same', libraryId: foreign.binding.libraryId }, current.exec), /MEMORY_LIBRARY_FORBIDDEN/)
539
- updateSettings({ crossLibraryRecall: true })
540
- const before = JSON.stringify(state.getSessionBinding(current.sessionId))
541
- assert.equal(parsedPage(await current.privateTool.execute({ query: 'mem-same' }, current.exec)).body, '本库正文', 'primary does not domain-filter its own entries')
542
- const directed = await current.privateTool.execute({ query: 'mem-same', libraryId: foreign.binding.libraryId }, current.exec)
543
- assert.equal(parsedPage(directed).body, '外库正文')
544
- assert.ok(directed.includes(`libraryId="${foreign.binding.libraryId}"`))
545
- assert.equal(JSON.stringify(state.getSessionBinding(current.sessionId)), before)
546
- assert.match(await current.privateTool.execute({ query: 'mem-foreign-rp', libraryId: foreign.binding.libraryId }, current.exec), /MEMORY_NOT_READABLE/)
547
- assert.match(await current.privateTool.execute({ query: 'mem-same', libraryId: different.binding.libraryId }, current.exec), /MEMORY_LIBRARY_FORBIDDEN/)
548
- state.setWorkspacePolicy(foreign.cwd, { useLibrary: false })
549
- assert.match(await current.privateTool.execute({ query: 'mem-same', libraryId: foreign.binding.libraryId }, current.exec), /MEMORY_LIBRARY_FORBIDDEN/)
550
- } finally {
551
- updateSettings({ crossLibraryRecall: savedCross })
552
- current.dispose(); foreign.dispose(); different.dispose()
553
- }
554
- })
555
-
556
- test('unbound private/full and global reads never create a binding or library', async () => {
557
- const f = readFixture()
558
- const saved = state.loadGlobalIndex()
559
- const sessionId = 'tools-full-unbound'
560
- const unboundExec = { agent: { session: { header: { id: sessionId, cwd: path.join(home, sessionId) } } } }
561
- state.saveGlobalIndex({ version: 1, entries: { 'gmem-unbound': { title: '通用全局', content: '通用只读正文', domain: 'general', status: 'active' } } })
562
- try {
563
- const libraries = JSON.stringify(state.listLibraries())
564
- assert.match(await f.privateTool.execute({ query: 'mem-unknown' }, unboundExec), /MEMORY_UNBOUND/)
565
- const global = await f.globalTool.execute({ query: 'gmem-unbound' }, unboundExec)
566
- assert.equal(parsedPage(global).body, '通用只读正文')
567
- assert.match(global, /unbound=true/)
568
- assert.equal(state.getSessionBinding(sessionId), null)
569
- assert.equal(JSON.stringify(state.listLibraries()), libraries)
570
- } finally { state.saveGlobalIndex(saved); f.dispose() }
571
- })
572
-
573
- test('natural search keeps snippets, provenance, cross-library refs and explicit truncation flags', async () => {
574
- const f = readFixture({
575
- 'mem-search-long': { title: '码头部署约定', content: '甲'.repeat(200) + '码头部署约定' + '乙'.repeat(200), visibility: 'secret', disclosure: 'never_say' },
576
- 'mem-search-short': { title: '短条咖啡约定', content: '短条咖啡约定:仅供测试。', source: 'tool', source_kind: 'tool' },
577
- })
578
- const foreign = readFixture({ 'mem-search-foreign': { title: '外库专用检索词', content: '外库专用检索词。' } })
579
- const saved = state.loadGlobalIndex()
580
- const savedSettings = state.getSettings()
581
- state.saveGlobalIndex({ version: 1, entries: { 'gmem-search-long': { title: '全局分页检索词', content: '甲'.repeat(200) + '全局分页检索词' + '乙'.repeat(200), status: 'active', domain: 'coding', source: 'tool' } } })
582
- updateSettings({ memoryBackend: 'agent', crossLibraryRecall: false, relevanceThreshold: 0 })
583
- try {
584
- const long = await f.privateTool.execute({ query: '码头部署约定', topK: 1 }, f.exec)
585
- assert.match(long, /1\. \[mem-search-long\]/)
586
- assert.match(long, /view=snippet.*scope=private.*truncated=true/)
587
- assert.match(long, /source=user_said/)
588
- assert.match(long, /visibility=secret/)
589
- assert.match(long, /disclosure=never_say/)
590
- assert.ok(long.includes(`libraryId="${f.binding.libraryId}"`))
591
- assert.doesNotMatch(long, /甲{200}|乙{200}/)
592
- const short = await f.privateTool.execute({ query: '短条咖啡约定', topK: 1 }, f.exec)
593
- assert.match(short, /\[mem-search-short\]/)
594
- assert.match(short, /truncated=false/)
595
- updateSettings({ crossLibraryRecall: true })
596
- const cross = await f.privateTool.execute({ query: '外库专用检索词', topK: 1 }, f.exec)
597
- assert.match(cross, /\[mem-search-foreign\]/)
598
- assert.ok(cross.includes(`libraryId="${foreign.binding.libraryId}"`))
599
- assert.match(cross, /跨库只读/)
600
- const global = await f.globalTool.execute({ query: '全局分页检索词', topK: 1 }, f.exec)
601
- assert.match(global, /1\. \[gmem-search-long\]/)
602
- assert.match(global, /view=snippet.*scope=global.*truncated=true/)
603
- assert.match(global, /source=tool/)
604
- assert.doesNotMatch(global, /甲{200}|乙{200}/)
605
- } finally {
606
- updateSettings({ memoryBackend: savedSettings.memoryBackend, crossLibraryRecall: savedSettings.crossLibraryRecall, relevanceThreshold: savedSettings.relevanceThreshold })
607
- state.saveGlobalIndex(saved)
608
- f.dispose(); foreign.dispose()
609
- }
610
- })
611
-
612
- test('private/global natural search retain degradation warnings with no active engine', async () => {
613
- const f = readFixture({ 'mem-degraded': { title: '降级专用检索词', content: '降级专用检索词。' } })
614
- const savedSettings = state.getSettings()
615
- const savedGlobal = state.loadGlobalIndex()
616
- state.saveGlobalIndex({ version: 1, entries: { 'gmem-degraded': { title: '降级专用检索词', content: '降级专用检索词。', status: 'active', domain: 'coding' } } })
617
- // No active vector generation in this temporary home: preflight rejects before
618
- // retrieve/ensure/engine startup. The local index hit must remain visible.
619
- updateSettings({ memoryBackend: 'api', vectorSource: 'local', crossLibraryRecall: false })
620
- try {
621
- for (const tool of [f.privateTool, f.globalTool]) {
622
- const reply = await tool.execute({ query: '降级专用检索词', topK: 1 }, f.exec)
623
- assert.equal(typeof reply, 'string')
624
- assert.match(reply, /\[(?:g?mem)-degraded\]/)
625
- assert.match(reply, /注意:本次召回已降级:/)
626
- assert.match(reply, /semantic recall failed/)
627
- }
628
- } finally {
629
- updateSettings({ memoryBackend: savedSettings.memoryBackend, vectorSource: savedSettings.vectorSource, crossLibraryRecall: savedSettings.crossLibraryRecall })
630
- state.saveGlobalIndex(savedGlobal)
631
- f.dispose()
632
- }
633
- })
634
-
635
- test('redaction happens before coordinates/revision; changed continuations retain MEMORY_CHANGED', async () => {
636
- const id = 'mem-redacted-page'
637
- const original = '😀开头 sk-fixtureOnly12345678901234567890 尾部🚀' + '乙'.repeat(180)
638
- const safe = redactSecrets(original)
639
- const f = readFixture({ [id]: { content: original } })
640
- try {
641
- const first = parsedPage(await f.privateTool.execute({ query: id, limitChars: 19 }, f.exec))
642
- assert.equal(first.body, Array.from(safe).slice(0, 19).join(''))
643
- assert.equal(first.totalChars, Array.from(safe).length)
644
- assert.equal(first.revision, sha256(safe))
645
- const restReply = await f.privateTool.execute({ query: id, offset: first.nextOffset, revision: first.revision, limitChars: 8000 }, f.exec)
646
- const rest = parsedPage(restReply)
647
- assert.equal(first.body + rest.body, safe)
648
- assert.doesNotMatch(first.body + rest.body, /fixtureOnly/)
649
- assert.match(await f.privateTool.execute({ query: id, offset: first.nextOffset }, f.exec), /REVISION_REQUIRED/)
650
- const index = state.loadPrivateIndex(f.binding.libraryId)
651
- index.entries[id].content += '新版'
652
- state.savePrivateIndex(f.binding.libraryId, index)
653
- const changed = await f.privateTool.execute({ query: id, offset: first.nextOffset, revision: first.revision }, f.exec)
654
- assert.match(changed, /\[MEMORY_CHANGED\]/)
655
- assert.match(changed, /offset 0/)
656
- assert.doesNotMatch(changed, /新版|body:/)
657
- assert.notEqual(parsedPage(await f.privateTool.execute({ query: id }, f.exec)).revision, first.revision)
658
- } finally { f.dispose() }
659
- })
660
-
661
- test('exact snippet stays at 160 codepoints, respects smaller page limits, and never expands conflicts', async () => {
662
- const id = 'mem-exact-snippet'
663
- const f = readFixture({
664
- [id]: { content: tailBody(4000), conflicts_with: 'mem-other-version', visibility: 'secret', disclosure: 'never_say' },
665
- 'mem-other-version': { title: '不得渲染另一正文', content: '第二版秘密正文不得出现在第一版读取中。' },
666
- })
667
- try {
668
- const before = JSON.stringify(state.loadPrivateIndex(f.binding.libraryId))
669
- const reply = await f.privateTool.execute({ query: id, view: 'snippet', topK: 20 }, f.exec)
670
- const page = parsedPage(reply)
671
- assert.equal(page.returnedChars, 160)
672
- assert.equal(page.totalChars, 4000)
673
- assert.equal(page.truncated, true)
674
- assert.equal(page.nextOffset, 160, 'continue after visible text, not the hidden 2000-char API page')
675
- assert.equal(page.body, '甲'.repeat(160) + '…')
676
- assert.match(reply, /view=snippet/)
677
- assert.match(reply, /visibility=secret.*disclosure=never_say/)
678
- assert.match(reply, /conflict: \[mem-other-version\]/)
679
- assert.doesNotMatch(reply, /第二版秘密正文|不得渲染另一正文|仅限测试尾/)
680
- const small = parsedPage(await f.privateTool.execute({ query: id, view: 'snippet', limitChars: 3 }, f.exec))
681
- assert.equal(small.returnedChars, 3)
682
- assert.equal(small.body, '甲'.repeat(3))
683
- assert.equal(small.truncated, true)
684
- assert.equal(small.nextOffset, 3)
685
- const full = parsedPage(await f.privateTool.execute({ query: id, limitChars: 8000 }, f.exec))
686
- assert.equal(full.body, tailBody(4000))
687
- assert.equal(JSON.stringify(state.loadPrivateIndex(f.binding.libraryId)), before, 'exact full/snippet reads are not recall')
688
- } finally { f.dispose() }
689
- })
690
-
691
- test('exact prefixes/.md resolve to full refs; ambiguity and unknown ids never fall back to search', async () => {
692
- const f = readFixture({ 'mem-prefix-unique': { content: '唯一前缀正文' }, 'mem-prefix-two': { content: '另一个版本' } })
693
- try {
694
- const resolved = await f.privateTool.execute({ query: 'mem-prefix-u.md' }, f.exec)
695
- assert.match(resolved, /id="mem-prefix-unique"/)
696
- assert.equal(parsedPage(resolved).body, '唯一前缀正文')
697
- assert.match(await f.privateTool.execute({ query: 'mem-prefix' }, f.exec), /MEMORY_ID_AMBIGUOUS/)
698
- assert.match(await f.privateTool.execute({ query: 'mem-missing' }, f.exec), /MEMORY_NOT_FOUND/)
699
- assert.match(await f.privateTool.execute({ query: '部署限制', view: 'full' }, f.exec), /EXACT_ID_REQUIRED/)
700
- for (const query of [' mem-prefix-unique', 'mem-prefix-unique ', 'mem-prefix-unique\n', 'mem-prefix unique']) {
701
- assert.match(await f.privateTool.execute({ query, view: 'full' }, f.exec), /EXACT_ID_REQUIRED/, 'no whitespace in exact ids')
702
- }
703
- } finally { f.dispose() }
704
- })
705
-
706
- test('recall parser enforces ranges/types and rejects natural-query paging/library targeting', async () => {
707
- const f = readFixture({ 'mem-validation': { content: '校验正文' } })
708
- try {
709
- for (const tool of [f.privateTool, f.globalTool]) {
710
- assert.match(await tool.execute({ query: '自然语言', view: 'full' }, f.exec), /EXACT_ID_REQUIRED/)
711
- for (const topK of [0, 21, 1.5, '2', NaN, Infinity, null]) {
712
- assert.match(await tool.execute({ query: '自然语言', topK }, f.exec), /INVALID_RECALL_ARGUMENT.*topK/)
713
- }
714
- for (const field of ['offset', 'limitChars', 'revision', 'libraryId']) {
715
- assert.match(await tool.execute({ query: '自然语言', [field]: field === 'offset' ? 0 : field === 'limitChars' ? 2000 : 'value' }, f.exec), /INVALID_RECALL_ARGUMENT/)
716
- }
717
- for (const query of ['', ' ', null, 42]) assert.match(await tool.execute({ query }, f.exec), /query is required/)
718
- for (const view of ['object', '', 42, null]) assert.match(await tool.execute({ query: 'mem-validation', view }, f.exec), /INVALID_RECALL_ARGUMENT.*view/)
719
- for (const offset of [-1, 0.5, '1', NaN, Infinity, null]) assert.match(await tool.execute({ query: 'mem-validation', offset }, f.exec), /INVALID_RECALL_ARGUMENT.*offset/)
720
- for (const limitChars of [0, -1, 8001, 1.5, '20', Infinity, null]) assert.match(await tool.execute({ query: 'mem-validation', limitChars }, f.exec), /INVALID_RECALL_ARGUMENT.*limitChars/)
721
- for (const revision of ['', 42, null]) assert.match(await tool.execute({ query: 'mem-validation', revision }, f.exec), /INVALID_RECALL_ARGUMENT.*revision/)
722
- }
723
- const first = parsedPage(await f.privateTool.execute({ query: 'mem-validation', limitChars: 1 }, f.exec))
724
- assert.equal(first.returnedChars, 1)
725
- assert.match(await f.privateTool.execute({ query: 'mem-validation', offset: 99, revision: first.revision }, f.exec), /MEMORY_OFFSET_OUT_OF_RANGE/)
726
- assert.match(await f.globalTool.execute({ query: 'gmem-any', libraryId: f.binding.libraryId }, f.exec), /INVALID_RECALL_ARGUMENT/)
727
- assert.match(await f.privateTool.execute({ query: 'mem-validation', libraryId: '' }, f.exec), /INVALID_RECALL_ARGUMENT/)
728
- } finally { f.dispose() }
729
- })
730
-
731
- for (const scope of ['private', 'global']) {
732
- for (const length of [160, 161, 169]) {
733
- test(`${scope} exact auto/full keeps the tail condition of a ${length}-codepoint body`, async () => {
734
- const id = `${scope === 'private' ? 'mem' : 'gmem'}-tail-${length}`
735
- const body = tailBody(length)
736
- const f = readFixture(scope === 'private' ? { [id]: { content: body } } : {})
737
- const savedGlobal = state.loadGlobalIndex()
738
- if (scope === 'global') state.saveGlobalIndex({ version: 1, entries: { [id]: {
739
- title: '全局尾条件', content: body, status: 'active', domain: 'coding', appliesTo: ['coding'], source: 'tool',
740
- } } })
741
- try {
742
- const tool = scope === 'private' ? f.privateTool : f.globalTool
743
- const before = JSON.stringify(state.loadPrivateIndex(f.binding.libraryId))
744
- for (const view of [undefined, 'auto', 'full']) {
745
- const reply = await tool.execute({ query: id, ...(view ? { view } : {}), topK: 20 }, f.exec)
746
- const page = parsedPage(reply)
747
- assert.equal(page.body, body)
748
- assert.equal(page.totalChars, length)
749
- assert.equal(page.returnedChars, length)
750
- assert.equal(page.truncated, false)
751
- assert.equal(page.nextOffset, null)
752
- assert.equal(page.revision, sha256(body))
753
- assert.match(reply, /view=full/)
754
- assert.match(reply, /source=(user_said|tool)/)
755
- assert.match(reply, new RegExp(`ref: scope=${scope}`))
756
- assert.deepEqual(tool.output.render({}, reply), [{ type: 'text', text: reply }])
757
- }
758
- assert.equal(JSON.stringify(state.loadPrivateIndex(f.binding.libraryId)), before, 'exact reads must not touch search access counters')
759
- } finally {
760
- if (scope === 'global') state.saveGlobalIndex(savedGlobal)
761
- f.dispose()
762
- }
763
- })
764
- }
765
- }
766
-
767
- for (const scope of ['private', 'global']) {
768
- for (const length of [169, 4000]) {
769
- test(`${scope} ${length}-codepoint pagination is continuous and defaults to 2000`, async () => {
770
- const id = `${scope === 'private' ? 'mem' : 'gmem'}-paged-${length}`
771
- const body = '😀甲🚀乙'.repeat(Math.ceil(length / 4))
772
- const expected = Array.from(body).slice(0, length - 5).join('') + '仅限测试尾'
773
- const f = readFixture(scope === 'private' ? { [id]: { content: expected } } : {})
774
- const savedGlobal = state.loadGlobalIndex()
775
- if (scope === 'global') state.saveGlobalIndex({ version: 1, entries: { [id]: { title: '分页', content: expected, status: 'active', domain: 'coding' } } })
776
- try {
777
- const tool = scope === 'private' ? f.privateTool : f.globalTool
778
- const defaultPage = parsedPage(await tool.execute({ query: id }, f.exec))
779
- assert.equal(defaultPage.returnedChars, Math.min(2000, length))
780
- let offset = 0
781
- let revision = null
782
- let assembled = ''
783
- do {
784
- const reply = await tool.execute({ query: id, view: 'full', offset, limitChars: length === 169 ? 61 : 997,
785
- ...(revision ? { revision } : {}) }, f.exec)
786
- const page = parsedPage(reply)
787
- assert.equal(page.offset, offset)
788
- assert.equal(page.totalChars, length)
789
- assert.equal(page.returnedChars, Array.from(page.body).length)
790
- assert.equal(page.revision, sha256(expected))
791
- assert.equal(page.truncated, offset + page.returnedChars < length)
792
- assert.equal(page.body, Array.from(expected).slice(offset, offset + page.returnedChars).join(''))
793
- assert.equal(page.body.isWellFormed(), true, 'never split emoji surrogate pairs')
794
- assembled += page.body
795
- revision = page.revision
796
- offset = page.nextOffset
797
- if (offset !== null) {
798
- assert.match(reply, new RegExp(`next: memu_${scope}_recall query="${id}" view="full"`))
799
- assert.match(reply, new RegExp(`offset=${offset}.*revision="${revision}"`))
800
- if (scope === 'private') assert.ok(reply.includes(`libraryId="${f.binding.libraryId}"`))
801
- } else assert.doesNotMatch(reply, /^next:/m)
802
- } while (offset !== null)
803
- assert.equal(assembled, expected)
804
- } finally {
805
- if (scope === 'global') state.saveGlobalIndex(savedGlobal)
806
- f.dispose()
807
- }
808
- })
809
- }
810
- }
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
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-tools-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const { registerTools } = await import('../lib/tools.js')
11
+ const state = await import('../lib/state.js')
12
+ const { updateSettings } = state
13
+ const { redactSecrets } = await import('../lib/paths.js')
14
+ const { createHash } = await import('node:crypto')
15
+
16
+ test.after(() => {
17
+ state.flushState()
18
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
19
+ })
20
+
21
+ function fakeCtx() {
22
+ const tools = []
23
+ const ctx = {
24
+ tools: {
25
+ register(tool) {
26
+ tools.push(tool)
27
+ return () => {}
28
+ },
29
+ },
30
+ logger: { warn() {} },
31
+ }
32
+ const dispose = registerTools(ctx)
33
+ return { ctx, tools, dispose }
34
+ }
35
+
36
+ const exec = {
37
+ agent: { session: { header: { id: 'tools-session', cwd: path.join(home, 'project-tools'), agentPreset: 'coding' } } },
38
+ }
39
+
40
+ test('all v1 tools register', () => {
41
+ const { tools, dispose } = fakeCtx()
42
+ const names = tools.map((t) => t.name)
43
+ for (const name of [
44
+ 'memu_private_link',
45
+ 'memu_private_link_suggest',
46
+ 'memu_private_remember',
47
+ 'memu_private_remember_batch',
48
+ 'memu_private_recall',
49
+ 'memu_private_list',
50
+ 'memu_private_update',
51
+ 'memu_private_archive',
52
+ 'memu_private_unpin',
53
+ 'memu_lexicon_search',
54
+ 'memu_lexicon_propose',
55
+ 'memu_global_recall',
56
+ 'memu_global_list',
57
+ 'memu_status',
58
+ ]) {
59
+ assert.ok(names.includes(name), `missing ${name}`)
60
+ }
61
+ // Exactly fourteen, not "at least these": a schema the host DSL refuses used to
62
+ // abort registerTools() before any register() ran, so counting is the assertion
63
+ // that actually catches a total registration failure.
64
+ assert.equal(names.length, 14, `expected 14 tools, got ${names.length}: ${names.join(', ')}`)
65
+ dispose()
66
+ })
67
+
68
+ test('batch write applies shared defaults and reports each item', async () => {
69
+ const { tools, dispose } = fakeCtx()
70
+ const batch = tools.find((t) => t.name === 'memu_private_remember_batch')
71
+ const batchExec = {
72
+ agent: { session: { header: { id: 'tools-batch-session', cwd: path.join(home, 'project-batch'), agentPreset: 'coding' } } },
73
+ }
74
+ const reply = await batch.execute({
75
+ defaults: { speaker_id: 'user', source: 'user_said', observed_at: '2026-11-06T04:00:00+08:00' },
76
+ items: [
77
+ { title: '码头见面', content: '明天下午三点在码头见面,别迟到。' },
78
+ { title: '带伞', content: '她说码头风大,让我带把伞。' },
79
+ ],
80
+ }, batchExec)
81
+ assert.match(reply, /批量写入完成:新增 2/)
82
+ assert.match(reply, /1\. 已写入私有记忆/)
83
+ assert.match(reply, /2\. 已写入私有记忆/)
84
+ const empty = await batch.execute({ items: [] }, batchExec)
85
+ assert.match(empty, /items 为空/)
86
+ dispose()
87
+ })
88
+
89
+ test('status works without an engine', async () => {
90
+ const { tools, dispose } = fakeCtx()
91
+ const status = await tools.find((t) => t.name === 'memu_status').execute({}, exec)
92
+ assert.match(status, /engine:/)
93
+ assert.match(status, /library:/)
94
+ // The registration count is the visible signal for a refused schema: without it
95
+ // a host that rejects the tool and a plugin that never had it look identical.
96
+ assert.match(status, /tools: 14\/14 registered/)
97
+ dispose()
98
+ })
99
+
100
+ test('title descriptions explain the permanent index rule', () => {
101
+ const { tools, dispose } = fakeCtx()
102
+ const remember = tools.find((t) => t.name === 'memu_private_remember')
103
+ const update = tools.find((t) => t.name === 'memu_private_update')
104
+ for (const tool of [remember, update]) {
105
+ const title = tool.parameters.title.description
106
+ assert.match(title, /8-40/, `${tool.name} title carries the 8-40 rule`)
107
+ assert.match(title, /name the concrete fact|title is a permanent index|anchor shows only titles/, `${tool.name} title says it is an index`)
108
+ assert.match(title, /empty label/, `${tool.name} title forbids empty labels`)
109
+ }
110
+ assert.match(remember.parameters.title.description, /WITHOUT the body/, 'the anchor shows titles without bodies')
111
+ const link = tools.find((t) => t.name === 'memu_private_link')
112
+ assert.match(link.description, /memu_private_link_suggest/, 'link is named as the adjudication tool for candidates')
113
+ assert.match(link.parameters.entity.description, /reused/, 'a named entity can be reused instead of duplicated')
114
+ const search = tools.find((t) => t.name === 'memu_lexicon_search')
115
+ assert.match(search.description, /ACTIVE/)
116
+ assert.match(search.description, /archived entries are excluded/)
117
+ const propose = tools.find((t) => t.name === 'memu_lexicon_propose')
118
+ assert.match(propose.description, /ACTIVE immediately/)
119
+ assert.doesNotMatch(propose.description, /stored as pending|needs human review before/, 'a model proposal is no longer pending')
120
+ assert.match(propose.parameters.term.description, /index key/)
121
+ assert.match(propose.parameters.meaning.description, /explanation/)
122
+ assert.match(tools.find((t) => t.name === 'memu_private_link_suggest').parameters.ids.description, /Required/)
123
+ dispose()
124
+ })
125
+
126
+ test('lexicon propose writes an active entry immediately; search only sees active terms', async () => {
127
+ const { tools, dispose } = fakeCtx()
128
+ const cwd = path.join(home, 'project-lex')
129
+ const execLex = { agent: { session: { header: { id: 'tools-lex', cwd, agentPreset: 'coding' } } } }
130
+ const binding = state.ensureSession('tools-lex', { cwd, agentPreset: 'coding' })
131
+ const lexicon = await import('../lib/lexicon.js')
132
+ const propose = tools.find((t) => t.name === 'memu_lexicon_propose')
133
+ const search = tools.find((t) => t.name === 'memu_lexicon_search')
134
+
135
+ const written = await propose.execute({ term: '糖刀', kind: 'slang', meaning: '又甜又扎人的说话方式。' }, execLex)
136
+ assert.match(written, /status=active/)
137
+ assert.doesNotMatch(written, /pending|待审/)
138
+ const storedPair = Object.entries(lexicon.loadLexicon(binding.libraryId).terms).find(([, entry]) => entry.term === '糖刀')
139
+ const stored = storedPair[1]
140
+ assert.equal(stored.status, 'active', 'model-proposal lands as active, no review step')
141
+ assert.equal(stored.source, 'model-proposal')
142
+
143
+ // Writing the same normalized term again updates the active entry, it does not fork it.
144
+ const again = await propose.execute({ term: '糖刀', kind: 'slang', meaning: '又甜又扎人的说话方式。', usage: '撒娇时用。' }, execLex)
145
+ assert.match(again, /已更新现有生效词条/)
146
+ assert.equal(Object.values(lexicon.loadLexicon(binding.libraryId).terms).filter((entry) => entry.term === '糖刀').length, 1)
147
+
148
+ const hit = await search.execute({ query: '糖刀' }, execLex)
149
+ assert.match(hit, /糖刀/)
150
+
151
+ // Archived terms leave both the search surface and injection.
152
+ lexicon.archiveLexiconTerm({ libraryId: binding.libraryId, termId: storedPair[0] })
153
+ const archived = await search.execute({ query: '糖刀' }, execLex)
154
+ assert.match(archived, /没有命中/)
155
+ // Writing the archived term again is not the model's call: it reports the entry was not changed.
156
+ const notOwned = await propose.execute({ term: '糖刀', kind: 'slang', meaning: '再次写入。' }, execLex)
157
+ assert.match(notOwned, /未改动/)
158
+ assert.match(notOwned, /已归档或归用户管理/)
159
+ assert.equal(Object.values(lexicon.loadLexicon(binding.libraryId).terms).find((entry) => entry.term === '糖刀').status, 'archived')
160
+
161
+ const refused = await propose.execute({ term: '别离开我', kind: 'trigger', meaning: '离别场景的触发词。' }, execLex)
162
+ assert.match(refused, /sensitive trigger/, 'a sensitive trigger stays user-managed')
163
+ dispose()
164
+ })
165
+
166
+ function namedEntityFixture(suffix, content, extra = {}) {
167
+ const id = 'tools-named-' + suffix
168
+ const cwd = path.join(home, id)
169
+ const binding = state.ensureSession(id, { cwd, agentPreset: 'rp' })
170
+ const namedExec = { agent: { session: { header: { id, cwd, agentPreset: 'rp' } } } }
171
+ state.savePrivateIndex(binding.libraryId, { version: 1, entries: {
172
+ 'mem-source': { title: '来访记录', content, status: 'active', visibility: 'shared', layer: 'long_term', ...extra },
173
+ } })
174
+ return { binding, namedExec }
175
+ }
176
+
177
+ for (const [i, name] of ['忆组件', '主人一', '人一', '主人一说'].entries()) {
178
+ test('new named entity rejects an unsupported fragment: ' + name, async () => {
179
+ const { tools, dispose } = fakeCtx()
180
+ const { binding, namedExec } = namedEntityFixture('fragment-' + i, '记忆组件负责保存资料,主人一说话就会得到回应。')
181
+ const link = tools.find(tool => tool.name === 'memu_private_link')
182
+ const graph = await import('../lib/graph.js')
183
+ try {
184
+ const reply = await link.execute({ from: 'mem-source', entity: { name, kind: 'person' }, kind: 'person', note: '原文出现了相同片段,因此把它作为同一人物关联。' }, namedExec)
185
+ assert.match(reply, /完整名称|complete name/, 'a substring is not evidence of a complete identity')
186
+ assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 0, 'rejection creates no entity')
187
+ assert.deepEqual(state.loadPrivateIndex(binding.libraryId).entries['mem-source'].links || [], [], 'rejection creates no link')
188
+ } finally { dispose() }
189
+ })
190
+ }
191
+
192
+ test('new named entity validates source and link before creating any entity', async () => {
193
+ const { tools, dispose } = fakeCtx()
194
+ const link = tools.find(tool => tool.name === 'memu_private_link')
195
+ const graph = await import('../lib/graph.js')
196
+ const cases = [
197
+ { suffix: 'missing', args: { from: 'mem-missing' } },
198
+ { suffix: 'secret', extra: { visibility: 'secret' } },
199
+ { suffix: 'archived', extra: { status: 'archived' } },
200
+ { suffix: 'note', args: { note: 'short' } },
201
+ { suffix: 'confidence', args: { confidence: 2 } },
202
+ { suffix: 'kind', args: { kind: 'typo' } },
203
+ { suffix: 'person-target', args: { entity: { name: '阿兰', kind: 'thing' } } },
204
+ { suffix: 'limit', extra: { links: Array.from({ length: 100 }, (_, i) => ({ to: 'mem-limit-' + i, kind: 'event' })) } },
205
+ ]
206
+ try {
207
+ for (const item of cases) {
208
+ const { binding, namedExec } = namedEntityFixture(item.suffix, '她叫阿兰,今天来送信。', item.extra)
209
+ const reply = await link.execute({ from: 'mem-source', entity: { name: '阿兰', kind: 'person' }, kind: 'person', note: '原文写着她叫阿兰,这封信由她送来。', ...item.args }, namedExec)
210
+ assert.match(reply, /error/, item.suffix + ' must be rejected')
211
+ assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 0, item.suffix + ' leaves no orphan entity')
212
+ }
213
+ } finally { dispose() }
214
+ })
215
+
216
+ test('new named entities require evidence in source memory rather than an invented note', async () => {
217
+ const { tools, dispose } = fakeCtx()
218
+ const link = tools.find(tool => tool.name === 'memu_private_link')
219
+ const graph = await import('../lib/graph.js')
220
+ try {
221
+ for (const [suffix, name, content] of [
222
+ ['note-spoof', '阿兰', '今天由一位邻居送来一封信。'],
223
+ ['latin-fragment', 'alice', 'malice appeared in the log.'],
224
+ ]) {
225
+ const { binding, namedExec } = namedEntityFixture(suffix, content)
226
+ const reply = await link.execute({ from: 'mem-source', entity: { name, kind: 'person' }, kind: 'person', note: '据我推测,这位邻居的完整名字是「' + name + '」。' }, namedExec)
227
+ assert.match(reply, /完整名称|complete name/)
228
+ assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 0)
229
+ }
230
+ } finally { dispose() }
231
+ })
232
+
233
+ test('complete quoted and introduced names remain usable and existing aliases are reused', async () => {
234
+ const { tools, dispose } = fakeCtx()
235
+ const link = tools.find(tool => tool.name === 'memu_private_link')
236
+ const graph = await import('../lib/graph.js')
237
+ try {
238
+ for (const [i, name, content] of [
239
+ [0, '阿兰', '她叫阿兰,今天来送信。'],
240
+ [1, '小檀', '「小檀」今天来送信。'],
241
+ [2, '主人一', '这个角色自称「主人一」,这是完整昵称。'],
242
+ [3, 'Alice', 'Alice delivered the letter.'],
243
+ [4, 'Old Zhou', 'Old Zhou delivered the letter.'],
244
+ ]) {
245
+ const { binding, namedExec } = namedEntityFixture('positive-' + i, content)
246
+ const reply = await link.execute({ from: 'mem-source', entity: { name, kind: 'person' }, kind: 'person', note: '原文明确写出完整名称 ' + name + ',关联这个同一人物。' }, namedExec)
247
+ const result = JSON.parse(reply)
248
+ const entity = graph.listEntities({ libraryId: binding.libraryId }).items.find(item => item.id === result.to)
249
+ assert.equal(entity.name, name)
250
+ assert.equal(entity.status, 'provisional', 'evidence of a full name alone is not user confirmation')
251
+ }
252
+ const { binding, namedExec } = namedEntityFixture('alias', '这位邻居送来一封信。')
253
+ const existing = graph.createEntity({ libraryId: binding.libraryId, name: '周宁', kind: 'person', aliases: ['Old Zhou'], status: 'confirmed' })
254
+ graph.linkEntries({ libraryId: binding.libraryId, fromId: 'mem-source', toId: existing.id, kind: 'person', note: '先前已由用户确认这位邻居的身份。' })
255
+ const result = JSON.parse(await link.execute({ from: 'mem-source', entity: { name: 'OLD ZHOU', kind: 'person' }, kind: 'person', note: '复用用户此前已经确认的同一人物别名。' }, namedExec))
256
+ assert.equal(result.to, existing.id)
257
+ assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 1)
258
+ } finally { dispose() }
259
+ })
260
+
261
+ test('link suggest refreshes deterministic mention edges and returns only uncertain candidates', async () => {
262
+ const { tools, dispose } = fakeCtx()
263
+ const cwd = path.join(home, 'project-links')
264
+ const execLinks = { agent: { session: { header: { id: 'tools-links', cwd, agentPreset: 'rp' } } } }
265
+ const binding = state.ensureSession('tools-links', { cwd, agentPreset: 'rp' })
266
+ const graph = await import('../lib/graph.js')
267
+ const yuike = graph.createEntity({ libraryId: binding.libraryId, name: 'yuike', kind: 'person', status: 'confirmed', confirmedBy: 'user' })
268
+ state.savePrivateIndex(binding.libraryId, { version: 1, entries: {
269
+ 'mem-a': { title: '猫娘yuike', content: 'yuike 是一只住在窗台的猫娘,喜欢晒太阳。', status: 'active', visibility: 'shared', layer: 'long_term' },
270
+ 'mem-b': { title: 'yuike名字的由来', content: '这个名字来自小时候养过的一只白猫。', status: 'active', visibility: 'shared', layer: 'long_term' },
271
+ } })
272
+ const suggest = tools.find((t) => t.name === 'memu_private_link_suggest')
273
+ assert.equal(suggest.isConcurrencySafe(), false, 'suggest writes links, so it is not a concurrent read')
274
+
275
+ const unbound = await suggest.execute({ ids: ['mem-a'] }, {
276
+ agent: { session: { header: { id: 'tools-links-unbound', cwd: path.join(home, 'project-links-unbound') } } },
277
+ })
278
+ assert.match(unbound, /没有绑定记忆库/)
279
+ const empty = await suggest.execute({ ids: [] }, execLinks)
280
+ assert.match(empty, /1-20/)
281
+
282
+ updateSettings({ autoLinkMode: 'deterministic' })
283
+ try {
284
+ const payload = JSON.parse(await suggest.execute({ ids: ['mem-a', 'mem-b'] }, execLinks))
285
+ assert.deepEqual(Object.keys(payload).sort(), ['autoLinked', 'candidates'], 'the tool answers with the two-field contract only')
286
+ assert.deepEqual(payload.candidates, [], 'the yuike pair is a deterministic mention, not an uncertain candidate')
287
+ assert.equal(payload.autoLinked.length, 2, 'one mention edge per memory, no lexical pair edge')
288
+ for (const edge of payload.autoLinked) {
289
+ assert.deepEqual(Object.keys(edge).sort(), ['from', 'kind', 'to'], 'no bodies or notes in the compact payload')
290
+ assert.equal(edge.to, yuike.id)
291
+ assert.equal(edge.kind, 'person')
292
+ }
293
+ // The deterministic edge survives into the graph the UI reads.
294
+ const view = graph.getGraph({ libraryId: binding.libraryId, focusId: 'mem-a', depth: 1 })
295
+ assert.ok(view.edges.some((edge) => edge.from === 'mem-a' && edge.to === yuike.id && edge.source === 'auto'))
296
+
297
+ // Running it again is idempotent: no new links, same empty candidate list.
298
+ const rerun = JSON.parse(await suggest.execute({ ids: ['mem-a', 'mem-b'] }, execLinks))
299
+ assert.deepEqual(rerun.autoLinked, [])
300
+ assert.deepEqual(rerun.candidates, [])
301
+ } finally {
302
+ updateSettings({ autoLinkMode: 'suggest' })
303
+ }
304
+ dispose()
305
+ })
306
+
307
+ test('private list stays usable without an active vector profile and says why', async () => {
308
+ const { tools, dispose } = fakeCtx()
309
+ updateSettings({ memoryBackend: 'api' })
310
+ try {
311
+ // The conversation must actually be bound: an unbound chat gets the
312
+ // "no library" answer instead, and never creates one just by listing.
313
+ state.ensureSession('tools-session', { cwd: path.join(home, 'project-tools') })
314
+ const text = await tools.find((t) => t.name === 'memu_private_list').execute({}, exec)
315
+ // No active generation means MemU cannot answer; the index still can. "Empty"
316
+ // on its own reads as lost memories, so the reason travels with the result.
317
+ assert.match(text, /私有记忆库 .* 为空。/)
318
+ assert.match(text, /本地向量未激活/)
319
+ } finally {
320
+ updateSettings({ memoryBackend: 'agent' })
321
+ dispose()
322
+ }
323
+ })
324
+
325
+ test('private list on an unbound conversation neither creates a library nor errors', async () => {
326
+ const { tools, dispose } = fakeCtx()
327
+ const before = state.listLibraries().length
328
+ const text = await tools.find((t) => t.name === 'memu_private_list').execute({}, {
329
+ agent: { session: { header: { id: 'tools-unbound', cwd: path.join(home, 'project-unbound'), agentPreset: 'coding' } } },
330
+ })
331
+ assert.match(text, /没有绑定记忆库/)
332
+ assert.equal(state.listLibraries().length, before, 'listing must not materialize a library')
333
+ dispose()
334
+ })
335
+
336
+ test('private list rows carry the same date label recall prints', async () => {
337
+ const { tools, dispose } = fakeCtx()
338
+ const cwd = path.join(home, 'project-dates')
339
+ const execDates = { agent: { session: { header: { id: 'tools-list-dates', cwd, agentPreset: 'coding' } } } }
340
+ state.ensureSession('tools-list-dates', { cwd })
341
+ const remember = tools.find((t) => t.name === 'memu_private_remember')
342
+ // Two forms of the same field: an appointment keeps its year, a birthday keeps MM-DD.
343
+ await remember.execute({ content: '明天要去考驾照。', title: '明天要考驾照', salient_date: '2026-10-29' }, execDates)
344
+ await remember.execute({ content: '生日是 10 月 28 日。', title: '生日', salient_date: '10-28' }, execDates)
345
+ const list = await tools.find((t) => t.name === 'memu_private_list').execute({}, execDates)
346
+ // A date only recall renders reads as "no date" in the list, so the two surfaces
347
+ // must agree on the spelling: date= for a one-off, anniversary= for a yearly one.
348
+ assert.match(list, /date=2026-10-29/)
349
+ assert.match(list, /anniversary=10-28/)
350
+ dispose()
351
+ })
352
+
353
+ test('must_remember requires a pin reason', async () => {
354
+ const { tools, dispose } = fakeCtx()
355
+ const text = await tools.find((t) => t.name === 'memu_private_remember').execute({
356
+ content: 'something worth keeping',
357
+ layer: 'must_remember',
358
+ }, exec)
359
+ assert.match(text, /pin_reason is required/)
360
+ dispose()
361
+ })
362
+
363
+ test('status separates "nobody polled" from "nothing was written"', async () => {
364
+ const { tools, dispose } = fakeCtx()
365
+ const { dispatch } = await import('../lib/rpc.js')
366
+ // A pane polling is what records a beat; a save is what records a write event.
367
+ await dispatch({}, 'getSidebarState', { revisionOnly: true })
368
+ state.savePrivateIndex('lib-sync', { version: 1, entries: {} })
369
+ const unbound = { agent: { session: { header: { id: 'tools-sync', cwd: path.join(home, 'project-sync') } } } }
370
+ const text = await tools.find((t) => t.name === 'memu_status').execute({}, unbound)
371
+ assert.match(text, /sync: heartbeat \d+s ago, last write private@lib-sync \d+s ago/)
372
+ dispose()
373
+ })
374
+
375
+ test('unpin is the model\'s call, guarded by reason, quota and cooldown', async () => {
376
+ const { tools, dispose } = fakeCtx()
377
+ const binding = state.ensureSession('tools-session', { cwd: path.join(home, 'project-tools'), agentPreset: 'coding' })
378
+ const index = state.loadPrivateIndex(binding.libraryId)
379
+ for (const id of ['mem-unpin', 'mem-unpin-2', 'mem-unpin-3']) {
380
+ index.entries[id] = {
381
+ track: 'memory',
382
+ layer: 'must_remember',
383
+ title: `A pinned memory ${id}`,
384
+ content: 'Something that used to matter.',
385
+ status: 'active',
386
+ pinSource: 'user_explicit',
387
+ pinReason: 'keep this',
388
+ createdAt: new Date().toISOString(),
389
+ updatedAt: new Date().toISOString(),
390
+ }
391
+ }
392
+ state.savePrivateIndex(binding.libraryId, index)
393
+
394
+ const exec = { agent: { session: { header: { id: 'tools-session' } } } }
395
+ const unpin = (id, reason) => tools.find((t) => t.name === 'memu_private_unpin').execute({ id, reason }, exec)
396
+
397
+ const tooShort = await unpin('mem-unpin', 'let it go')
398
+ assert.match(tooShort, /at least 20 characters/)
399
+ assert.equal(state.loadPrivateIndex(binding.libraryId).entries['mem-unpin'].layer, 'must_remember')
400
+
401
+ const accepted = await unpin('mem-unpin', '那件事已经过去了,我现在能把它当成一件旧事来讲,而不是每次想起都疼。')
402
+ assert.match(accepted, /long_term|marginalized|边缘化/)
403
+ const after = state.loadPrivateIndex(binding.libraryId).entries['mem-unpin']
404
+ assert.equal(after.layer, 'long_term')
405
+ assert.equal(after.marginalized, true)
406
+ assert.equal(after.unpinnedBy, 'model')
407
+ assert.ok(after.originalPinSource !== undefined)
408
+
409
+ // Cooldown: a second unpin right after is refused even though quota remains.
410
+ const cooldown = await unpin('mem-unpin-2', '这次也一样,我已经能平静地说完了,不再需要一直记着。')
411
+ assert.match(cooldown, /cooldown/)
412
+ assert.equal(state.loadPrivateIndex(binding.libraryId).entries['mem-unpin-2'].layer, 'must_remember')
413
+
414
+ // Quota: once the conversation has spent it, memory stays pinned.
415
+ state.setSessionBinding('tools-session', { lastUnpinAt: null, unpinCount: 2 })
416
+ const quota = await unpin('mem-unpin-3', '我已经想清楚了,这件事可以放下来,不必再一直提醒自己。')
417
+ assert.match(quota, /quota/)
418
+ dispose()
419
+ })
420
+
421
+ let readFixtureNumber = 0
422
+ function readFixture(entries = {}, domain = 'coding') {
423
+ const sessionId = `tools-read-${++readFixtureNumber}`
424
+ const cwd = path.join(home, sessionId)
425
+ const binding = state.ensureSession(sessionId, { cwd, agentPreset: domain })
426
+ state.setSessionBinding(sessionId, { domainOverride: domain })
427
+ const index = { version: 1, entries: Object.fromEntries(Object.entries(entries).map(([id, entry]) => [id, {
428
+ id, title: '读取测试', content: '', status: 'active', layer: 'long_term', visibility: 'shared', disclosure: 'can_tell',
429
+ source: 'user_said', source_kind: 'user_said', speaker_id: 'user', domain,
430
+ createdAt: '2026-11-01T00:00:00.000Z', updatedAt: '2026-11-01T00:00:00.000Z', ...entry,
431
+ }])) }
432
+ state.savePrivateIndex(binding.libraryId, index)
433
+ const registered = fakeCtx()
434
+ return { ...registered, sessionId, cwd, binding, exec: { agent: { session: { header: { id: sessionId, cwd } } } },
435
+ privateTool: registered.tools.find((tool) => tool.name === 'memu_private_recall'),
436
+ globalTool: registered.tools.find((tool) => tool.name === 'memu_global_recall') }
437
+ }
438
+
439
+ function parsedPage(reply) {
440
+ assert.equal(typeof reply, 'string', 'tool receipts remain strings')
441
+ const match = reply.match(/pagination: unit=codepoint · offset=(\d+) · returned_chars=(\d+) · total_chars=(\d+) · truncated=(true|false) · next_offset=(\d+|null)/)
442
+ assert.ok(match, `missing codepoint pagination: ${reply}`)
443
+ const revision = reply.match(/^revision=([a-f0-9]{64})$/m)?.[1]
444
+ assert.ok(revision, 'the redacted body SHA256 must be visible')
445
+ const body = reply.split('\nbody:\n')[1]?.split(/\n(?:next:|conflict:)/)[0]
446
+ assert.notEqual(body, undefined)
447
+ return { body, revision, offset: Number(match[1]), returnedChars: Number(match[2]), totalChars: Number(match[3]),
448
+ truncated: match[4] === 'true', nextOffset: match[5] === 'null' ? null : Number(match[5]) }
449
+ }
450
+
451
+ const sha256 = (body) => createHash('sha256').update(body).digest('hex')
452
+ const tailBody = (length) => '甲'.repeat(length - 5) + '仅限测试尾'
453
+
454
+ test('empty bodies and the exact end offset are valid zero-length pages, not range errors', async () => {
455
+ const f = readFixture({ 'mem-empty': { content: '' }, 'mem-end': { content: '😀末尾' } })
456
+ try {
457
+ const empty = parsedPage(await f.privateTool.execute({ query: 'mem-empty' }, f.exec))
458
+ assert.deepEqual([empty.body, empty.totalChars, empty.returnedChars, empty.truncated, empty.nextOffset], ['', 0, 0, false, null])
459
+ assert.equal(empty.revision, sha256(''))
460
+ const start = parsedPage(await f.privateTool.execute({ query: 'mem-end' }, f.exec))
461
+ const end = parsedPage(await f.privateTool.execute({ query: 'mem-end', offset: start.totalChars, revision: start.revision }, f.exec))
462
+ assert.equal(end.body, '')
463
+ assert.equal(end.returnedChars, 0)
464
+ assert.equal(end.nextOffset, null)
465
+ assert.match(await f.privateTool.execute({ query: 'mem-empty', offset: 1, revision: empty.revision }, f.exec), /MEMORY_OFFSET_OUT_OF_RANGE/)
466
+ } finally { f.dispose() }
467
+ })
468
+
469
+ test('exact snippet centering reports its actual codepoint coordinates and a resumable next ref', async () => {
470
+ const id = 'mem-centered-exact'
471
+ const body = '😀'.repeat(200) + id + '🚀'.repeat(200)
472
+ const f = readFixture({ [id]: { content: body } })
473
+ try {
474
+ const reply = await f.privateTool.execute({ query: id, view: 'snippet' }, f.exec)
475
+ const page = parsedPage(reply)
476
+ assert.equal(page.offset, 160)
477
+ assert.equal(page.returnedChars, 160)
478
+ assert.equal(page.body, '…' + Array.from(body).slice(160, 320).join('') + '…')
479
+ assert.equal(page.nextOffset, 320)
480
+ assert.equal(page.totalChars, Array.from(body).length)
481
+ const rest = parsedPage(await f.privateTool.execute({ query: id, libraryId: f.binding.libraryId, offset: page.nextOffset, revision: page.revision }, f.exec))
482
+ assert.equal(rest.body, Array.from(body).slice(320).join(''))
483
+ } finally { f.dispose() }
484
+ })
485
+
486
+ test('private explicit reads allow secret/disclosure but never open archived or superseded entries', async () => {
487
+ const f = readFixture({
488
+ 'mem-secret': { content: '显式秘密正文', visibility: 'secret', disclosure: 'never_say' },
489
+ 'mem-asked': { content: '仅当被问到的正文', disclosure: 'only_if_asked' },
490
+ 'mem-archived': { content: '归档正文不开放', status: 'archived' },
491
+ 'mem-superseded': { content: '被替代正文不开放', status: 'superseded' },
492
+ 'mem-held': { content: '待复核正文不开放', status: 'pending_review' },
493
+ })
494
+ try {
495
+ assert.equal(parsedPage(await f.privateTool.execute({ query: 'mem-secret' }, f.exec)).body, '显式秘密正文')
496
+ assert.equal(parsedPage(await f.privateTool.execute({ query: 'mem-asked' }, f.exec)).body, '仅当被问到的正文')
497
+ for (const id of ['mem-archived', 'mem-superseded', 'mem-held']) {
498
+ const reply = await f.privateTool.execute({ query: id }, f.exec)
499
+ assert.match(reply, /MEMORY_NOT_READABLE/)
500
+ assert.doesNotMatch(reply, /正文不开放/)
501
+ }
502
+ state.setSessionBinding(f.sessionId, { useLibrary: false })
503
+ assert.doesNotMatch(await f.privateTool.execute({ query: 'mem-secret' }, f.exec), /显式秘密正文/)
504
+ } finally { f.dispose() }
505
+ })
506
+
507
+ test('global exact reads retain automatic/domain eligibility', async () => {
508
+ const f = readFixture()
509
+ const saved = state.loadGlobalIndex()
510
+ state.saveGlobalIndex({ version: 1, entries: {
511
+ 'gmem-good': { content: '合法全局正文', status: 'active', domain: 'coding', source: 'tool' },
512
+ 'gmem-secret': { content: '不开放秘密', status: 'active', domain: 'coding', visibility: 'secret' },
513
+ 'gmem-never': { content: '不开放披露', status: 'active', domain: 'coding', disclosure: 'never_say' },
514
+ 'gmem-asked': { content: '不开放仅问', status: 'active', domain: 'coding', disclosure: 'only_if_asked' },
515
+ 'gmem-rp': { content: '不开放异域', status: 'active', domain: 'rp' },
516
+ 'gmem-archived': { content: '不开放归档', status: 'archived', domain: 'coding' },
517
+ } })
518
+ try {
519
+ assert.equal(parsedPage(await f.globalTool.execute({ query: 'gmem-good.md' }, f.exec)).body, '合法全局正文')
520
+ for (const id of ['gmem-secret', 'gmem-never', 'gmem-asked', 'gmem-rp', 'gmem-archived']) {
521
+ const reply = await f.globalTool.execute({ query: id }, f.exec)
522
+ assert.match(reply, /MEMORY_NOT_READABLE/)
523
+ assert.doesNotMatch(reply, /不开放/)
524
+ }
525
+ assert.match(await f.globalTool.execute({ query: 'gmem-unknown' }, f.exec), /MEMORY_NOT_FOUND/)
526
+ state.setSessionBinding(f.sessionId, { useGlobal: false })
527
+ assert.doesNotMatch(await f.globalTool.execute({ query: 'gmem-good' }, f.exec), /合法全局正文/)
528
+ } finally { state.saveGlobalIndex(saved); f.dispose() }
529
+ })
530
+
531
+ test('cross-library same-id reads honor libraryId, domain and opt-in without changing bindings', async () => {
532
+ const current = readFixture({ 'mem-same': { content: '本库正文', domain: 'rp' } })
533
+ const foreign = readFixture({ 'mem-same': { content: '外库正文' }, 'mem-foreign-rp': { content: '外库异域禁止', domain: 'rp' } })
534
+ const different = readFixture({ 'mem-same': { content: '异域库正文禁止' } }, 'rp')
535
+ const savedCross = state.getSettings().crossLibraryRecall
536
+ try {
537
+ updateSettings({ crossLibraryRecall: false })
538
+ assert.match(await current.privateTool.execute({ query: 'mem-same', libraryId: foreign.binding.libraryId }, current.exec), /MEMORY_LIBRARY_FORBIDDEN/)
539
+ updateSettings({ crossLibraryRecall: true })
540
+ const before = JSON.stringify(state.getSessionBinding(current.sessionId))
541
+ assert.equal(parsedPage(await current.privateTool.execute({ query: 'mem-same' }, current.exec)).body, '本库正文', 'primary does not domain-filter its own entries')
542
+ const directed = await current.privateTool.execute({ query: 'mem-same', libraryId: foreign.binding.libraryId }, current.exec)
543
+ assert.equal(parsedPage(directed).body, '外库正文')
544
+ assert.ok(directed.includes(`libraryId="${foreign.binding.libraryId}"`))
545
+ assert.equal(JSON.stringify(state.getSessionBinding(current.sessionId)), before)
546
+ assert.match(await current.privateTool.execute({ query: 'mem-foreign-rp', libraryId: foreign.binding.libraryId }, current.exec), /MEMORY_NOT_READABLE/)
547
+ assert.match(await current.privateTool.execute({ query: 'mem-same', libraryId: different.binding.libraryId }, current.exec), /MEMORY_LIBRARY_FORBIDDEN/)
548
+ state.setWorkspacePolicy(foreign.cwd, { useLibrary: false })
549
+ assert.match(await current.privateTool.execute({ query: 'mem-same', libraryId: foreign.binding.libraryId }, current.exec), /MEMORY_LIBRARY_FORBIDDEN/)
550
+ } finally {
551
+ updateSettings({ crossLibraryRecall: savedCross })
552
+ current.dispose(); foreign.dispose(); different.dispose()
553
+ }
554
+ })
555
+
556
+ test('unbound private/full and global reads never create a binding or library', async () => {
557
+ const f = readFixture()
558
+ const saved = state.loadGlobalIndex()
559
+ const sessionId = 'tools-full-unbound'
560
+ const unboundExec = { agent: { session: { header: { id: sessionId, cwd: path.join(home, sessionId) } } } }
561
+ state.saveGlobalIndex({ version: 1, entries: { 'gmem-unbound': { title: '通用全局', content: '通用只读正文', domain: 'general', status: 'active' } } })
562
+ try {
563
+ const libraries = JSON.stringify(state.listLibraries())
564
+ assert.match(await f.privateTool.execute({ query: 'mem-unknown' }, unboundExec), /MEMORY_UNBOUND/)
565
+ const global = await f.globalTool.execute({ query: 'gmem-unbound' }, unboundExec)
566
+ assert.equal(parsedPage(global).body, '通用只读正文')
567
+ assert.match(global, /unbound=true/)
568
+ assert.equal(state.getSessionBinding(sessionId), null)
569
+ assert.equal(JSON.stringify(state.listLibraries()), libraries)
570
+ } finally { state.saveGlobalIndex(saved); f.dispose() }
571
+ })
572
+
573
+ test('natural search keeps snippets, provenance, cross-library refs and explicit truncation flags', async () => {
574
+ const f = readFixture({
575
+ 'mem-search-long': { title: '码头部署约定', content: '甲'.repeat(200) + '码头部署约定' + '乙'.repeat(200), visibility: 'secret', disclosure: 'never_say' },
576
+ 'mem-search-short': { title: '短条咖啡约定', content: '短条咖啡约定:仅供测试。', source: 'tool', source_kind: 'tool' },
577
+ })
578
+ const foreign = readFixture({ 'mem-search-foreign': { title: '外库专用检索词', content: '外库专用检索词。' } })
579
+ const saved = state.loadGlobalIndex()
580
+ const savedSettings = state.getSettings()
581
+ state.saveGlobalIndex({ version: 1, entries: { 'gmem-search-long': { title: '全局分页检索词', content: '甲'.repeat(200) + '全局分页检索词' + '乙'.repeat(200), status: 'active', domain: 'coding', source: 'tool' } } })
582
+ updateSettings({ memoryBackend: 'agent', crossLibraryRecall: false, relevanceThreshold: 0 })
583
+ try {
584
+ const long = await f.privateTool.execute({ query: '码头部署约定', topK: 1 }, f.exec)
585
+ assert.match(long, /1\. \[mem-search-long\]/)
586
+ assert.match(long, /view=snippet.*scope=private.*truncated=true/)
587
+ assert.match(long, /source=user_said/)
588
+ assert.match(long, /visibility=secret/)
589
+ assert.match(long, /disclosure=never_say/)
590
+ assert.ok(long.includes(`libraryId="${f.binding.libraryId}"`))
591
+ assert.doesNotMatch(long, /甲{200}|乙{200}/)
592
+ const short = await f.privateTool.execute({ query: '短条咖啡约定', topK: 1 }, f.exec)
593
+ assert.match(short, /\[mem-search-short\]/)
594
+ assert.match(short, /truncated=false/)
595
+ updateSettings({ crossLibraryRecall: true })
596
+ const cross = await f.privateTool.execute({ query: '外库专用检索词', topK: 1 }, f.exec)
597
+ assert.match(cross, /\[mem-search-foreign\]/)
598
+ assert.ok(cross.includes(`libraryId="${foreign.binding.libraryId}"`))
599
+ assert.match(cross, /跨库只读/)
600
+ const global = await f.globalTool.execute({ query: '全局分页检索词', topK: 1 }, f.exec)
601
+ assert.match(global, /1\. \[gmem-search-long\]/)
602
+ assert.match(global, /view=snippet.*scope=global.*truncated=true/)
603
+ assert.match(global, /source=tool/)
604
+ assert.doesNotMatch(global, /甲{200}|乙{200}/)
605
+ } finally {
606
+ updateSettings({ memoryBackend: savedSettings.memoryBackend, crossLibraryRecall: savedSettings.crossLibraryRecall, relevanceThreshold: savedSettings.relevanceThreshold })
607
+ state.saveGlobalIndex(saved)
608
+ f.dispose(); foreign.dispose()
609
+ }
610
+ })
611
+
612
+ test('private/global natural search retain degradation warnings with no active engine', async () => {
613
+ const f = readFixture({ 'mem-degraded': { title: '降级专用检索词', content: '降级专用检索词。' } })
614
+ const savedSettings = state.getSettings()
615
+ const savedGlobal = state.loadGlobalIndex()
616
+ state.saveGlobalIndex({ version: 1, entries: { 'gmem-degraded': { title: '降级专用检索词', content: '降级专用检索词。', status: 'active', domain: 'coding' } } })
617
+ // No active vector generation in this temporary home: preflight rejects before
618
+ // retrieve/ensure/engine startup. The local index hit must remain visible.
619
+ updateSettings({ memoryBackend: 'api', vectorSource: 'local', crossLibraryRecall: false })
620
+ try {
621
+ for (const tool of [f.privateTool, f.globalTool]) {
622
+ const reply = await tool.execute({ query: '降级专用检索词', topK: 1 }, f.exec)
623
+ assert.equal(typeof reply, 'string')
624
+ assert.match(reply, /\[(?:g?mem)-degraded\]/)
625
+ assert.match(reply, /注意:本次召回已降级:/)
626
+ assert.match(reply, /semantic recall failed/)
627
+ }
628
+ } finally {
629
+ updateSettings({ memoryBackend: savedSettings.memoryBackend, vectorSource: savedSettings.vectorSource, crossLibraryRecall: savedSettings.crossLibraryRecall })
630
+ state.saveGlobalIndex(savedGlobal)
631
+ f.dispose()
632
+ }
633
+ })
634
+
635
+ test('redaction happens before coordinates/revision; changed continuations retain MEMORY_CHANGED', async () => {
636
+ const id = 'mem-redacted-page'
637
+ const original = '😀开头 sk-fixtureOnly12345678901234567890 尾部🚀' + '乙'.repeat(180)
638
+ const safe = redactSecrets(original)
639
+ const f = readFixture({ [id]: { content: original } })
640
+ try {
641
+ const first = parsedPage(await f.privateTool.execute({ query: id, limitChars: 19 }, f.exec))
642
+ assert.equal(first.body, Array.from(safe).slice(0, 19).join(''))
643
+ assert.equal(first.totalChars, Array.from(safe).length)
644
+ assert.equal(first.revision, sha256(safe))
645
+ const restReply = await f.privateTool.execute({ query: id, offset: first.nextOffset, revision: first.revision, limitChars: 8000 }, f.exec)
646
+ const rest = parsedPage(restReply)
647
+ assert.equal(first.body + rest.body, safe)
648
+ assert.doesNotMatch(first.body + rest.body, /fixtureOnly/)
649
+ assert.match(await f.privateTool.execute({ query: id, offset: first.nextOffset }, f.exec), /REVISION_REQUIRED/)
650
+ const index = state.loadPrivateIndex(f.binding.libraryId)
651
+ index.entries[id].content += '新版'
652
+ state.savePrivateIndex(f.binding.libraryId, index)
653
+ const changed = await f.privateTool.execute({ query: id, offset: first.nextOffset, revision: first.revision }, f.exec)
654
+ assert.match(changed, /\[MEMORY_CHANGED\]/)
655
+ assert.match(changed, /offset 0/)
656
+ assert.doesNotMatch(changed, /新版|body:/)
657
+ assert.notEqual(parsedPage(await f.privateTool.execute({ query: id }, f.exec)).revision, first.revision)
658
+ } finally { f.dispose() }
659
+ })
660
+
661
+ test('exact snippet stays at 160 codepoints, respects smaller page limits, and never expands conflicts', async () => {
662
+ const id = 'mem-exact-snippet'
663
+ const f = readFixture({
664
+ [id]: { content: tailBody(4000), conflicts_with: 'mem-other-version', visibility: 'secret', disclosure: 'never_say' },
665
+ 'mem-other-version': { title: '不得渲染另一正文', content: '第二版秘密正文不得出现在第一版读取中。' },
666
+ })
667
+ try {
668
+ const before = JSON.stringify(state.loadPrivateIndex(f.binding.libraryId))
669
+ const reply = await f.privateTool.execute({ query: id, view: 'snippet', topK: 20 }, f.exec)
670
+ const page = parsedPage(reply)
671
+ assert.equal(page.returnedChars, 160)
672
+ assert.equal(page.totalChars, 4000)
673
+ assert.equal(page.truncated, true)
674
+ assert.equal(page.nextOffset, 160, 'continue after visible text, not the hidden 2000-char API page')
675
+ assert.equal(page.body, '甲'.repeat(160) + '…')
676
+ assert.match(reply, /view=snippet/)
677
+ assert.match(reply, /visibility=secret.*disclosure=never_say/)
678
+ assert.match(reply, /conflict: \[mem-other-version\]/)
679
+ assert.doesNotMatch(reply, /第二版秘密正文|不得渲染另一正文|仅限测试尾/)
680
+ const small = parsedPage(await f.privateTool.execute({ query: id, view: 'snippet', limitChars: 3 }, f.exec))
681
+ assert.equal(small.returnedChars, 3)
682
+ assert.equal(small.body, '甲'.repeat(3))
683
+ assert.equal(small.truncated, true)
684
+ assert.equal(small.nextOffset, 3)
685
+ const full = parsedPage(await f.privateTool.execute({ query: id, limitChars: 8000 }, f.exec))
686
+ assert.equal(full.body, tailBody(4000))
687
+ assert.equal(JSON.stringify(state.loadPrivateIndex(f.binding.libraryId)), before, 'exact full/snippet reads are not recall')
688
+ } finally { f.dispose() }
689
+ })
690
+
691
+ test('exact prefixes/.md resolve to full refs; ambiguity and unknown ids never fall back to search', async () => {
692
+ const f = readFixture({ 'mem-prefix-unique': { content: '唯一前缀正文' }, 'mem-prefix-two': { content: '另一个版本' } })
693
+ try {
694
+ const resolved = await f.privateTool.execute({ query: 'mem-prefix-u.md' }, f.exec)
695
+ assert.match(resolved, /id="mem-prefix-unique"/)
696
+ assert.equal(parsedPage(resolved).body, '唯一前缀正文')
697
+ assert.match(await f.privateTool.execute({ query: 'mem-prefix' }, f.exec), /MEMORY_ID_AMBIGUOUS/)
698
+ assert.match(await f.privateTool.execute({ query: 'mem-missing' }, f.exec), /MEMORY_NOT_FOUND/)
699
+ assert.match(await f.privateTool.execute({ query: '部署限制', view: 'full' }, f.exec), /EXACT_ID_REQUIRED/)
700
+ for (const query of [' mem-prefix-unique', 'mem-prefix-unique ', 'mem-prefix-unique\n', 'mem-prefix unique']) {
701
+ assert.match(await f.privateTool.execute({ query, view: 'full' }, f.exec), /EXACT_ID_REQUIRED/, 'no whitespace in exact ids')
702
+ }
703
+ } finally { f.dispose() }
704
+ })
705
+
706
+ test('recall parser enforces ranges/types and rejects natural-query paging/library targeting', async () => {
707
+ const f = readFixture({ 'mem-validation': { content: '校验正文' } })
708
+ try {
709
+ for (const tool of [f.privateTool, f.globalTool]) {
710
+ assert.match(await tool.execute({ query: '自然语言', view: 'full' }, f.exec), /EXACT_ID_REQUIRED/)
711
+ for (const topK of [0, 21, 1.5, '2', NaN, Infinity, null]) {
712
+ assert.match(await tool.execute({ query: '自然语言', topK }, f.exec), /INVALID_RECALL_ARGUMENT.*topK/)
713
+ }
714
+ for (const field of ['offset', 'limitChars', 'revision', 'libraryId']) {
715
+ assert.match(await tool.execute({ query: '自然语言', [field]: field === 'offset' ? 0 : field === 'limitChars' ? 2000 : 'value' }, f.exec), /INVALID_RECALL_ARGUMENT/)
716
+ }
717
+ for (const query of ['', ' ', null, 42]) assert.match(await tool.execute({ query }, f.exec), /query is required/)
718
+ for (const view of ['object', '', 42, null]) assert.match(await tool.execute({ query: 'mem-validation', view }, f.exec), /INVALID_RECALL_ARGUMENT.*view/)
719
+ for (const offset of [-1, 0.5, '1', NaN, Infinity, null]) assert.match(await tool.execute({ query: 'mem-validation', offset }, f.exec), /INVALID_RECALL_ARGUMENT.*offset/)
720
+ for (const limitChars of [0, -1, 8001, 1.5, '20', Infinity, null]) assert.match(await tool.execute({ query: 'mem-validation', limitChars }, f.exec), /INVALID_RECALL_ARGUMENT.*limitChars/)
721
+ for (const revision of ['', 42, null]) assert.match(await tool.execute({ query: 'mem-validation', revision }, f.exec), /INVALID_RECALL_ARGUMENT.*revision/)
722
+ }
723
+ const first = parsedPage(await f.privateTool.execute({ query: 'mem-validation', limitChars: 1 }, f.exec))
724
+ assert.equal(first.returnedChars, 1)
725
+ assert.match(await f.privateTool.execute({ query: 'mem-validation', offset: 99, revision: first.revision }, f.exec), /MEMORY_OFFSET_OUT_OF_RANGE/)
726
+ assert.match(await f.globalTool.execute({ query: 'gmem-any', libraryId: f.binding.libraryId }, f.exec), /INVALID_RECALL_ARGUMENT/)
727
+ assert.match(await f.privateTool.execute({ query: 'mem-validation', libraryId: '' }, f.exec), /INVALID_RECALL_ARGUMENT/)
728
+ } finally { f.dispose() }
729
+ })
730
+
731
+ for (const scope of ['private', 'global']) {
732
+ for (const length of [160, 161, 169]) {
733
+ test(`${scope} exact auto/full keeps the tail condition of a ${length}-codepoint body`, async () => {
734
+ const id = `${scope === 'private' ? 'mem' : 'gmem'}-tail-${length}`
735
+ const body = tailBody(length)
736
+ const f = readFixture(scope === 'private' ? { [id]: { content: body } } : {})
737
+ const savedGlobal = state.loadGlobalIndex()
738
+ if (scope === 'global') state.saveGlobalIndex({ version: 1, entries: { [id]: {
739
+ title: '全局尾条件', content: body, status: 'active', domain: 'coding', appliesTo: ['coding'], source: 'tool',
740
+ } } })
741
+ try {
742
+ const tool = scope === 'private' ? f.privateTool : f.globalTool
743
+ const before = JSON.stringify(state.loadPrivateIndex(f.binding.libraryId))
744
+ for (const view of [undefined, 'auto', 'full']) {
745
+ const reply = await tool.execute({ query: id, ...(view ? { view } : {}), topK: 20 }, f.exec)
746
+ const page = parsedPage(reply)
747
+ assert.equal(page.body, body)
748
+ assert.equal(page.totalChars, length)
749
+ assert.equal(page.returnedChars, length)
750
+ assert.equal(page.truncated, false)
751
+ assert.equal(page.nextOffset, null)
752
+ assert.equal(page.revision, sha256(body))
753
+ assert.match(reply, /view=full/)
754
+ assert.match(reply, /source=(user_said|tool)/)
755
+ assert.match(reply, new RegExp(`ref: scope=${scope}`))
756
+ assert.deepEqual(tool.output.render({}, reply), [{ type: 'text', text: reply }])
757
+ }
758
+ assert.equal(JSON.stringify(state.loadPrivateIndex(f.binding.libraryId)), before, 'exact reads must not touch search access counters')
759
+ } finally {
760
+ if (scope === 'global') state.saveGlobalIndex(savedGlobal)
761
+ f.dispose()
762
+ }
763
+ })
764
+ }
765
+ }
766
+
767
+ for (const scope of ['private', 'global']) {
768
+ for (const length of [169, 4000]) {
769
+ test(`${scope} ${length}-codepoint pagination is continuous and defaults to 2000`, async () => {
770
+ const id = `${scope === 'private' ? 'mem' : 'gmem'}-paged-${length}`
771
+ const body = '😀甲🚀乙'.repeat(Math.ceil(length / 4))
772
+ const expected = Array.from(body).slice(0, length - 5).join('') + '仅限测试尾'
773
+ const f = readFixture(scope === 'private' ? { [id]: { content: expected } } : {})
774
+ const savedGlobal = state.loadGlobalIndex()
775
+ if (scope === 'global') state.saveGlobalIndex({ version: 1, entries: { [id]: { title: '分页', content: expected, status: 'active', domain: 'coding' } } })
776
+ try {
777
+ const tool = scope === 'private' ? f.privateTool : f.globalTool
778
+ const defaultPage = parsedPage(await tool.execute({ query: id }, f.exec))
779
+ assert.equal(defaultPage.returnedChars, Math.min(2000, length))
780
+ let offset = 0
781
+ let revision = null
782
+ let assembled = ''
783
+ do {
784
+ const reply = await tool.execute({ query: id, view: 'full', offset, limitChars: length === 169 ? 61 : 997,
785
+ ...(revision ? { revision } : {}) }, f.exec)
786
+ const page = parsedPage(reply)
787
+ assert.equal(page.offset, offset)
788
+ assert.equal(page.totalChars, length)
789
+ assert.equal(page.returnedChars, Array.from(page.body).length)
790
+ assert.equal(page.revision, sha256(expected))
791
+ assert.equal(page.truncated, offset + page.returnedChars < length)
792
+ assert.equal(page.body, Array.from(expected).slice(offset, offset + page.returnedChars).join(''))
793
+ assert.equal(page.body.isWellFormed(), true, 'never split emoji surrogate pairs')
794
+ assembled += page.body
795
+ revision = page.revision
796
+ offset = page.nextOffset
797
+ if (offset !== null) {
798
+ assert.match(reply, new RegExp(`next: memu_${scope}_recall query="${id}" view="full"`))
799
+ assert.match(reply, new RegExp(`offset=${offset}.*revision="${revision}"`))
800
+ if (scope === 'private') assert.ok(reply.includes(`libraryId="${f.binding.libraryId}"`))
801
+ } else assert.doesNotMatch(reply, /^next:/m)
802
+ } while (offset !== null)
803
+ assert.equal(assembled, expected)
804
+ } finally {
805
+ if (scope === 'global') state.saveGlobalIndex(savedGlobal)
806
+ f.dispose()
807
+ }
808
+ })
809
+ }
810
+ }