dsh-memu-memory 1.3.7 → 1.3.8

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 (54) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +58 -0
  3. package/README.md +7 -7
  4. package/README.zh.md +7 -7
  5. package/docs/client-conventions.md +1 -0
  6. package/docs/contributing.md +2 -2
  7. package/docs/memory-semantics.md +7 -6
  8. package/docs/troubleshooting.md +74 -7
  9. package/lib/binding-diagnostics.js +2 -2
  10. package/lib/client.js +150 -81
  11. package/lib/consolidation-ledger.js +6 -2
  12. package/lib/inbound.js +24 -9
  13. package/lib/inject.js +379 -215
  14. package/lib/memory.js +704 -181
  15. package/lib/paths.js +24 -0
  16. package/lib/private.js +242 -132
  17. package/lib/rpc.js +53 -6
  18. package/lib/snippet.js +49 -28
  19. package/lib/state.js +185 -26
  20. package/lib/tools.js +137 -28
  21. package/lib/webui.js +25 -1
  22. package/lib/worker-pool.js +260 -26
  23. package/package.json +1 -1
  24. package/scripts/check-i18n.mjs +19 -0
  25. package/scripts/recall-bench.mjs +4 -4
  26. package/scripts/simulate-injection.mjs +3 -0
  27. package/tests/activity-wiring.test.mjs +52 -0
  28. package/tests/client-render.test.mjs +207 -0
  29. package/tests/consolidation-feed.test.mjs +26 -0
  30. package/tests/consolidation-fork.test.mjs +587 -26
  31. package/tests/cross-library-recall.test.mjs +156 -0
  32. package/tests/cue.test.mjs +15 -2
  33. package/tests/hybrid-recall.test.mjs +488 -0
  34. package/tests/inbound.test.mjs +49 -4
  35. package/tests/inject-conflict.test.mjs +70 -9
  36. package/tests/inject-guide.test.mjs +13 -1
  37. package/tests/inject.test.mjs +10 -0
  38. package/tests/injection-budget.test.mjs +101 -0
  39. package/tests/injection-chain.test.mjs +37 -0
  40. package/tests/injection-rollback.test.mjs +172 -9
  41. package/tests/issue2-chain.test.mjs +169 -0
  42. package/tests/lexicon-inject.test.mjs +33 -5
  43. package/tests/managed-memory.test.mjs +625 -1
  44. package/tests/media.test.mjs +1 -1
  45. package/tests/new-session-gate.test.mjs +280 -25
  46. package/tests/open-loop-date.test.mjs +11 -1
  47. package/tests/recall-intent.test.mjs +52 -3
  48. package/tests/simulate-injection.test.mjs +4 -4
  49. package/tests/snippet.test.mjs +33 -1
  50. package/tests/state.test.mjs +8 -3
  51. package/tests/tool-schema.test.mjs +52 -0
  52. package/tests/tools.test.mjs +394 -0
  53. package/tests/webui.test.mjs +16 -2
  54. package/tests/worker-lifecycle.test.mjs +419 -36
@@ -12,6 +12,7 @@ process.env.DSH_MEMU_HOME = home
12
12
  process.env.DSH_MEMU_MEMORY_HOME = home
13
13
  const calls = []
14
14
  const warnings = []
15
+ const rebuildProbes = []
15
16
  const backendRows = new Map()
16
17
  const backendKey = (db, name) => JSON.stringify([db, name])
17
18
  let commitHook = null
@@ -47,13 +48,24 @@ globalThis.__managedMemoryTest = {
47
48
  return { deleted: 1, segments: 1 }
48
49
  },
49
50
  async listFiles() { throw new Error('unexpected list engine call') },
51
+ async maybeAutoRebuildVectorGeneration(...args) {
52
+ rebuildProbes.push(args)
53
+ return { stubbed: true }
54
+ },
50
55
  }
56
+ const vectorServiceUrl = 'data:text/javascript,' + encodeURIComponent('export const maybeAutoRebuildVectorGeneration = globalThis.__managedMemoryTest.maybeAutoRebuildVectorGeneration;')
51
57
  const engineSource = 'const bridge = globalThis.__managedMemoryTest; export const commit = bridge.commit, retrieve = bridge.retrieve, forget = bridge.forget, listFiles = bridge.listFiles, closeMemuResident = () => 0, prewarmMemuResident = async () => false;'
52
58
  const hooks = registerHooks({
53
59
  resolve(specifier, context, nextResolve) {
54
60
  if (specifier === './memu.js') {
55
61
  return { url: 'data:text/javascript,' + encodeURIComponent(engineSource), shortCircuit: true }
56
62
  }
63
+ // managedRecall 的缺库分支会动态 import 向量服务做自动追平探测。这里只拦截
64
+ // memory.js 发起的那一次(父 URL 限定),别的模块照常拿真实现——否则空转的
65
+ // force 重建会把嵌入 worker 拉进单元测试。
66
+ if (specifier === './local-vector-service.js' && context.parentURL === new URL('../lib/memory.js', import.meta.url).href) {
67
+ return { url: vectorServiceUrl, shortCircuit: true }
68
+ }
57
69
  return nextResolve(specifier, context)
58
70
  },
59
71
  })
@@ -63,6 +75,7 @@ const paths = await import('../lib/paths.js')
63
75
  const memory = await import('../lib/memory.js')
64
76
  const curator = await import('../lib/curator.js')
65
77
  const activity = await import('../lib/activity-log.js')
78
+ const { buildCorpus, bm25, tokenize } = await import('../lib/text-retrieval.js')
66
79
  const profile = vp.profileFromCatalog('bge-small-zh-v1.5-int8')
67
80
  const activeFile = vp.vectorActiveFile()
68
81
  let serial = 0
@@ -96,10 +109,11 @@ function curated(extra = {}) {
96
109
 
97
110
  test.beforeEach(() => {
98
111
  fs.rmSync(activeFile, { force: true })
99
- state.updateSettings({ memoryBackend: 'api', vectorSource: 'local', relevanceThreshold: 0 })
112
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'local', relevanceThreshold: 0, crossLibraryRecall: false })
100
113
  state.saveGlobalIndex({ entries: {} })
101
114
  calls.length = 0
102
115
  warnings.length = 0
116
+ rebuildProbes.length = 0
103
117
  commitHook = null
104
118
  retrieveHook = null
105
119
  failCommit = false
@@ -147,6 +161,212 @@ test('corrupt managed intent cannot call LLM or legacy API and preserves lexical
147
161
  assert.equal(calls.length, 0)
148
162
  })
149
163
 
164
+ // 2026-11-18:跨库召回扫到没有向量库的库时,缺库降级的诊断只该属于「有内容」的库。
165
+ // 空库(旧工作区遗留,索引 0 条)local-only 与语义召回的结果都是空——每轮给它刷
166
+ // "向量库未生成" warn 是常驻噪音(group_893418498 空库实测刷满活动日志)。
167
+ function vectorDegradeRows(libraryId) {
168
+ return activity.listEvents({ kind: 'vector', limit: 100 })
169
+ .filter(row => row.message === '向量库未生成,召回降级 local-only' && row.detail?.libraryId === libraryId)
170
+ }
171
+
172
+ async function settleRebuildProbes() {
173
+ // Join the same data-module import and drain its fire-and-forget .then callback.
174
+ // Importing the bridge itself does not call the probe or start a real worker.
175
+ await import(vectorServiceUrl)
176
+ await new Promise(resolve => setImmediate(resolve))
177
+ }
178
+
179
+ function trackIndexAccess(t, files) {
180
+ const access = { clones: 0, stats: new Map(files.map(file => [file, 0])) }
181
+ const clone = globalThis.structuredClone
182
+ t.mock.method(globalThis, 'structuredClone', (value, ...args) => {
183
+ if (value?.entries && !Array.isArray(value.entries)) access.clones += 1
184
+ return clone(value, ...args)
185
+ })
186
+ const stat = fs.statSync
187
+ t.mock.method(fs, 'statSync', (file, ...args) => {
188
+ if (access.stats.has(file)) access.stats.set(file, access.stats.get(file) + 1)
189
+ return stat(file, ...args)
190
+ })
191
+ return access
192
+ }
193
+
194
+ test('an empty library without a vector db recalls silently — no degrade noise, no rebuild probe', async () => {
195
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'local' })
196
+ const empty = fixture({})
197
+ activate([]) // 活跃代际只含全局库:该库的向量库必然缺席
198
+ const result = await memory.privateRecall({ exec: empty.exec, query: 'anything', topK: 5 })
199
+ await settleRebuildProbes()
200
+ assert.equal(result.recallRoute, 'local-fallback')
201
+ assert.deepEqual(result.files, [], 'an empty library has nothing to recall')
202
+ assert.deepEqual(result.errors || [], [])
203
+ assert.deepEqual(warnings, [], 'an empty library must not warn')
204
+ assert.equal(vectorDegradeRows(empty.libraryId).length, 0, 'an empty library must not log the degrade warning')
205
+ assert.equal(rebuildProbes.length, 0, 'an empty library must not probe a rebuild')
206
+ assert.equal(calls.length, 0)
207
+ })
208
+
209
+ test('a library with content but no vector db keeps the degrade diagnostic and probes the rebuild', async () => {
210
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'local' })
211
+ const rich = fixture({ 'mem-rich': entry('needle real content that semantic recall would serve') })
212
+ activate([]) // 同上:库不在代际里,但索引里有内容——这是真正值得诊断的缺库
213
+ const result = await memory.privateRecall({ exec: rich.exec, query: 'needle', topK: 5 })
214
+ await settleRebuildProbes()
215
+ assert.equal(result.recallRoute, 'local-fallback')
216
+ assert.deepEqual(result.files.map(file => file.name), ['mem-rich'])
217
+ assert.deepEqual(result.errors || [], [], 'missing registration is diagnostic, not a recall error')
218
+ assert.equal(warnings.length, 1)
219
+ assert.ok(warnings[0].includes('has no database for library ' + rich.libraryId))
220
+ assert.equal(vectorDegradeRows(rich.libraryId).length, 1, 'content-bearing libraries keep the diagnostic')
221
+ assert.equal(rebuildProbes.length, 1, 'content-bearing libraries probe the rebuild')
222
+ assert.equal(calls.length, 0)
223
+ })
224
+
225
+ test('an empty library resumes missing-db diagnostics after its first index entry is saved', async () => {
226
+ const f = fixture()
227
+ activate([])
228
+ const empty = await memory.privateRecall({ exec: f.exec, query: 'needle', purpose: 'automatic' })
229
+ await settleRebuildProbes()
230
+ assert.deepEqual(empty.files, [])
231
+ assert.deepEqual(warnings, [])
232
+ assert.equal(vectorDegradeRows(f.libraryId).length, 0)
233
+ assert.equal(rebuildProbes.length, 0)
234
+
235
+ // A backfill must invalidate emptiness immediately; no new cache or enrollment.
236
+ state.savePrivateIndex(f.libraryId, { entries: { 'mem-first': entry('needle first backfilled fact') } })
237
+ const filled = await memory.privateRecall({ exec: f.exec, query: 'needle', purpose: 'automatic' })
238
+ await settleRebuildProbes()
239
+ assert.deepEqual(filled.files.map(file => file.name), ['mem-first'])
240
+ assert.equal(filled.recallRoute, 'local-fallback')
241
+ assert.equal(warnings.length, 1)
242
+ assert.ok(warnings[0].includes('has no database for library ' + f.libraryId))
243
+ assert.equal(vectorDegradeRows(f.libraryId).length, 1)
244
+ assert.equal(rebuildProbes.length, 1)
245
+ assert.equal(calls.length, 0)
246
+ })
247
+
248
+ test('missing-db recall reuses loaded indexes on repeated warm-cache calls', async t => {
249
+ const f = fixture({ 'mem-budget': entry('needle snapshot budget') })
250
+ activate([])
251
+ state.loadPrivateIndex(f.libraryId) // Warm the state index cache before spying.
252
+ const indexFile = path.join(paths.indexDir(), f.libraryId + '.json')
253
+ const access = trackIndexAccess(t, [indexFile])
254
+ for (let round = 1; round <= 2; round += 1) {
255
+ const result = await memory.privateRecall({ exec: f.exec, query: 'needle', purpose: 'automatic' })
256
+ await settleRebuildProbes()
257
+ assert.deepEqual(result.files.map(file => file.name), ['mem-budget'])
258
+ // Two source snapshots clone twice each; the one hit also checks the existing
259
+ // relation-inverted-index signature (stat only, no snapshot).
260
+ assert.equal(access.stats.get(indexFile), 3 * round, 'two index reads plus one relation signature stat')
261
+ assert.equal(access.clones, 4 * round, 'no extra full-index clones, regardless of corpus size')
262
+ assert.equal(rebuildProbes.length, round, 'the fallback remains uncached and diagnostic')
263
+ }
264
+ })
265
+
266
+ test('cross-library missing-db diagnostics use the full source before domain filtering without extra snapshots', async t => {
267
+ const current = fixture({ 'mem-current': entry('needle current fact') })
268
+ const foreign = fixture({ 'mem-other-domain': entry('needle other world', { domain: 'rp' }) })
269
+ const empty = fixture()
270
+ const domain = 'project:' + current.sessionId
271
+ for (const f of [current, foreign, empty]) state.setSessionBinding(f.sessionId, { domainOverride: domain })
272
+ state.updateSettings({ crossLibraryRecall: true })
273
+ activate([])
274
+ const indexFiles = [current, foreign, empty].map(f => path.join(paths.indexDir(), f.libraryId + '.json'))
275
+ const access = trackIndexAccess(t, indexFiles)
276
+ const result = await memory.privateRecall({ exec: current.exec, query: 'needle', purpose: 'automatic' })
277
+ await settleRebuildProbes()
278
+ assert.equal(result.recallRoute, 'cross-library')
279
+ assert.deepEqual(new Set(result.libraries), new Set([current.libraryId, foreign.libraryId, empty.libraryId]))
280
+ assert.deepEqual(result.files.map(file => file.name), ['mem-current'], 'the foreign domain contributes no hits')
281
+ assert.deepEqual(result.errors, [])
282
+ assert.equal(warnings.length, 2, 'only the two content-bearing libraries warn')
283
+ for (const f of [current, foreign]) {
284
+ assert.ok(warnings.some(message => message.includes('has no database for library ' + f.libraryId)))
285
+ assert.equal(vectorDegradeRows(f.libraryId).length, 1)
286
+ }
287
+ assert.equal(vectorDegradeRows(empty.libraryId).length, 0)
288
+ assert.equal(rebuildProbes.length, 2, 'a domain-filtered empty view still needs a rebuild probe')
289
+ assert.equal(calls.length, 0)
290
+ assert.deepEqual(indexFiles.map(file => access.stats.get(file)), [3, 1, 1], 'only the primary hit adds a relation signature stat')
291
+ assert.equal(access.clones, 8, 'three source loads plus the existing primary refresh only')
292
+ })
293
+
294
+ test('by-id private recall still short-circuits vector IO and missing-db diagnostics', async t => {
295
+ const f = fixture({ 'mem-byid': entry('needle direct lookup') })
296
+ const databases = activate([])
297
+ const globalDb = vp.resolveVectorPath(databases.global.path)
298
+ fs.rmSync(globalDb)
299
+ const indexFile = path.join(paths.indexDir(), f.libraryId + '.json')
300
+ const access = trackIndexAccess(t, [indexFile, globalDb])
301
+ const read = t.mock.method(fs, 'readFileSync')
302
+ const result = await memory.privateRecall({ exec: f.exec, query: 'mem-byid', purpose: 'automatic' })
303
+ await settleRebuildProbes()
304
+ assert.deepEqual(result.files.map(file => file.name), ['mem-byid'])
305
+ assert.equal(result.recallRoute, 'local')
306
+ assert.deepEqual(warnings, [])
307
+ assert.equal(vectorDegradeRows(f.libraryId).length, 0)
308
+ assert.equal(rebuildProbes.length, 0)
309
+ assert.equal(calls.length, 0)
310
+ assert.equal(read.mock.calls.some(call => call.arguments[0] === activeFile), false, 'by-id does not read vector state')
311
+ assert.equal(access.stats.get(globalDb), 0, 'by-id does not validate vector databases')
312
+ assert.equal(access.stats.get(indexFile), 3, 'two index reads plus the existing relation signature stat')
313
+ assert.equal(access.clones, 4)
314
+ })
315
+
316
+ test('global recall uses the null library route even for an empty index and adds no index snapshots', async t => {
317
+ const f = fixture({ 'mem-private': entry('needle private-only fact') })
318
+ activate([f.libraryId])
319
+ const globalDb = vp.dbPathFor(null)
320
+ const empty = await memory.globalRecall({ exec: f.exec, query: 'needle' })
321
+ assert.deepEqual(empty.files, [])
322
+ assert.equal(empty.recallRoute, 'managed-vector-rrf')
323
+ assert.equal(calls.length, 1, 'an empty index must not suppress an existing vector route')
324
+ assert.equal(calls[0].db, globalDb)
325
+
326
+ state.saveGlobalIndex({ entries: {
327
+ 'gmem-needle': entry('needle global fact', { domain: 'coding' }),
328
+ 'gmem-other': entry('needle other world', { domain: 'rp' }),
329
+ } })
330
+ const indexFile = path.join(paths.indexDir(), 'global.json')
331
+ const access = trackIndexAccess(t, [indexFile])
332
+ const result = await memory.globalRecall({ exec: f.exec, query: 'needle' })
333
+ await settleRebuildProbes()
334
+ assert.deepEqual(result.files.map(file => file.name), ['gmem-needle'])
335
+ assert.equal(result.recallRoute, 'managed-vector-rrf')
336
+ assert.equal(calls.length, 2)
337
+ assert.equal(calls[1].db, globalDb, 'libraryId=null must select global, not private')
338
+ assert.equal(calls[1].route, 'managed-local')
339
+ assert.deepEqual(warnings, [])
340
+ assert.equal(vectorDegradeRows(null).length, 0)
341
+ assert.equal(rebuildProbes.length, 0)
342
+ assert.equal(access.stats.get(indexFile), 2)
343
+ assert.equal(access.clones, 4)
344
+ })
345
+
346
+ for (const content of ['empty', 'other-domain', 'matching']) {
347
+ test(`a physically missing global database remains an error with ${content} content`, async () => {
348
+ const f = fixture()
349
+ const databases = activate([])
350
+ if (content !== 'empty') state.saveGlobalIndex({ entries: {
351
+ 'gmem-needle': entry('needle global fact', { domain: content === 'matching' ? 'coding' : 'rp' }),
352
+ } })
353
+ const globalDb = vp.resolveVectorPath(databases.global.path)
354
+ fs.rmSync(globalDb)
355
+ const result = await memory.globalRecall({ exec: f.exec, query: 'needle' })
356
+ await settleRebuildProbes()
357
+ assert.deepEqual(result.files.map(file => file.name), content === 'matching' ? ['gmem-needle'] : [])
358
+ assert.equal(result.recallRoute, 'local-fallback')
359
+ assert.equal(result.errors.length, 1)
360
+ assert.match(result.errors[0], /a database in the active generation is missing/)
361
+ assert.match(state.getSessionBinding(f.sessionId).lastRecallError, /a database in the active generation is missing/)
362
+ assert.equal(warnings.length, 1)
363
+ assert.ok(warnings[0].includes(path.basename(globalDb)))
364
+ assert.equal(vectorDegradeRows(null).length, 0, 'torn state is not ordinary missing registration')
365
+ assert.equal(rebuildProbes.length, 0)
366
+ assert.equal(calls.length, 0)
367
+ })
368
+ }
369
+
150
370
  test('agent backend stays lexical even when a local profile is active', async () => {
151
371
  const f = fixture({ 'mem-needle': entry('needle local match') })
152
372
  activate([f.libraryId])
@@ -608,3 +828,407 @@ test('deleting an active archived library removes its route without tearing late
608
828
  assert.equal(state.loadPrivateIndex(next.libraryId).entries[remembered.id].content, 'write after deleting another library')
609
829
  assert.equal(vp.activeVectorState().active.databases.libraries[f.libraryId], undefined)
610
830
  })
831
+
832
+ // 2026-11-18 排序修正端到端:RRF 名次归一把词法满分命中压成近平手后,primacy/peakEnd
833
+ // 偏置会把弱相关元记忆顶到第一(运行时实测:lexical 219.5 的完美命中被挤到 #8)。
834
+ // 修复后巨无霸命中保住 #1,弱竞争者落到相对阈值之外。
835
+ test('a dominant lexical hit cannot be buried by primacy/peak-end biases', async () => {
836
+ state.updateSettings({ memoryBackend: 'api', vectorSource: 'local' })
837
+ // 大语料抬高 BM25 的库规模(IDF 随 N 增长,小语料造不出 ≥24 的巨无霸分)。
838
+ const entries = {}
839
+ const alphabet = 'abcdefghijklmnopqrstuvwxyz'
840
+ const token = (n) => alphabet[n % 26] + alphabet[Math.floor(n / 26) % 26]
841
+ const old = '2026-10-01T00:00:00.000Z'
842
+ for (let i = 0; i < 60; i += 1) {
843
+ entries['mem-pad-' + String(i).padStart(2, '0')] = entry('常规条目 ' + token(3 * i) + token(3 * i + 1) + ',归档说明与轮值安排。', {
844
+ createdAt: old, updatedAt: old, strength: 1, arousal: 0.9,
845
+ })
846
+ }
847
+ // meta:最早创建(primacy ×1.2)+ 高唤醒(peakEnd ×1.25)+ strength 1——偏置加成最大;
848
+ // 正文含查询里的常见词元(有/没有),让它也进词法腿,制造名次归一的近平手。
849
+ entries['mem-meta'] = entry('运营值守安排,没有什么特别的说明。', { createdAt: old, updatedAt: old, strength: 1, arousal: 0.9 })
850
+ entries['mem-food'] = entry('主人是云南人,爱吃松茸菌子,在广州吃不到几家做菌子和过桥米线的馆子。', { strength: 0.8, arousal: 0.35 })
851
+ const f = fixture(entries)
852
+ activate([f.libraryId])
853
+ // 语义腿把 meta 排在 food 前面(模拟引擎 embedding 被查询样板带偏的形态):
854
+ // 词法腿 food 满分,RRF 名次归一后两者 retrieval 近平手。
855
+ retrieveHook = () => ({ files: [{ name: 'mem-meta' }, { name: 'mem-food' }], segments: [], resources: [] })
856
+ const result = await memory.privateRecall({ exec: f.exec, query: '松茸的,我云南娃子喜欢吃菌子,还有过桥米线', topK: 5, relevanceThreshold: 0.4 })
857
+ assert.equal(result.files[0]?.name, 'mem-food', 'the dominant lexical hit must rank first, got ' + result.files[0]?.name)
858
+ assert.ok((result.files[0]?.fusion?.lexicalDominant ?? 0) >= 24, 'the dominance must be recorded in fusion metadata')
859
+ assert.ok(!result.files.some((file) => file.name === 'mem-meta'), 'weak competitors fall below the relative threshold')
860
+ retrieveHook = null
861
+ })
862
+
863
+ // Real BM25 regressions: only the semantic boundary is stubbed. Dates deliberately
864
+ // age with now; a future sceneTime must not erase strength/primacy in these cases.
865
+ function rankingEntry(content, extra = {}) {
866
+ const ago = days => new Date(Date.now() - days * 86_400_000).toISOString()
867
+ return entry(content, { createdAt: ago(2), updatedAt: ago(1), ...extra })
868
+ }
869
+
870
+ function rankingWorld(primaryEntries, foreignEntries) {
871
+ const primary = fixture(primaryEntries)
872
+ const foreign = fixture(foreignEntries)
873
+ const domain = 'ranking:' + primary.sessionId
874
+ for (const f of [primary, foreign]) state.setSessionBinding(f.sessionId, { domainOverride: domain })
875
+ state.updateSettings({ crossLibraryRecall: true })
876
+ return { primary, foreign }
877
+ }
878
+
879
+ function realLexical(entries, query) {
880
+ const corpus = buildCorpus(Object.entries(entries).map(([id, row]) => ({
881
+ id, title: row.title,
882
+ content: [row.content, (row.tags || []).join(' '), (row.attachments || []).map(item => `${item.caption || ''} 图片 ${item.kind || 'image'}`).join(' ')].filter(Boolean).join(' '),
883
+ })))
884
+ return new Map([...corpus.docs].map(([id, doc]) => [id, bm25(tokenize(query), doc, corpus)]))
885
+ }
886
+
887
+ async function assertRankingBoundary(expectedRetrieves) {
888
+ await settleRebuildProbes()
889
+ assert.equal(calls.length, expectedRetrieves, 'only the stub semantic retrieve boundary is called')
890
+ assert.ok(calls.every(call => call.op === 'retrieve' && call.route === 'managed-local'))
891
+ assert.deepEqual(rebuildProbes, [], 'ranking regressions must not start a real rebuild/worker')
892
+ assert.deepEqual(warnings, [])
893
+ }
894
+
895
+ const tlsAnswer = 'TLS 服务证书过期,续签后重启代理恢复连接。'
896
+ const tlsTemplate = '请用自然简洁的语气回答。这是通用回复风格,不涉及饮食或服务故障。'
897
+ const pianoNotes = [
898
+ '钢琴练习先慢速弹奏音阶,再练左右手协调。',
899
+ '巴赫赋格练习需要分声部辨认旋律。',
900
+ '踏板练习要注意换踏时机与音色。',
901
+ '周末排练莫扎特奏鸣曲,保持轻巧触键。',
902
+ '视奏练习每天十五分钟,先看拍号与调号。',
903
+ '和弦转位练习强调指法与手腕放松。',
904
+ '节拍器从慢速逐渐加快,避免抢拍。',
905
+ '演出前检查琴凳高度,认真完成热身。',
906
+ ]
907
+ function tlsEntries(template, size = 2) {
908
+ const answerDate = new Date(Date.now() - 4 * 86_400_000).toISOString()
909
+ return {
910
+ 'mem-answer': rankingEntry(tlsAnswer, { createdAt: answerDate, strength: 1, peak: true }),
911
+ 'mem-template': rankingEntry(template, { strength: 0.8 }),
912
+ ...Object.fromEntries(pianoNotes.slice(0, size - 2).map((text, i) => ['mem-piano-' + i, rankingEntry(text)])),
913
+ }
914
+ }
915
+
916
+ for (const crossLibrary of [false, true]) {
917
+ test(`real BM25 short reply style leaves TLS answer first (${crossLibrary ? 'with three foreign piano notes' : 'two-entry library'})`, async () => {
918
+ const entries = tlsEntries(tlsTemplate)
919
+ const world = crossLibrary
920
+ ? rankingWorld(entries, Object.fromEntries(pianoNotes.slice(0, 3).map((text, i) => ['mem-note-' + i, rankingEntry(text)])))
921
+ : null
922
+ const f = world?.primary || fixture(entries)
923
+ activate(world ? [f.libraryId, world.foreign.libraryId] : [f.libraryId])
924
+ retrieveHook = args => ({ files: args.db === vp.dbPathFor(f.libraryId) ? [{ name: 'mem-answer' }, { name: 'mem-template' }] : [], segments: [], resources: [] })
925
+ const result = await memory.privateRecall({ exec: f.exec, query: '请用自然简洁的语气回答。TLS 故障原因?', topK: 5, relevanceThreshold: 0 })
926
+ assert.equal(result.files[0]?.name, 'mem-answer', 'corpus changes must not crown the reply-style template')
927
+ const template = result.files.find(file => file.name === 'mem-template')
928
+ assert.ok(template?.lexical > 0, 'the original lexical score stays observable')
929
+ assert.ok(template.lexicalEvidence < template.lexical, 'style-only overlap is not topical evidence')
930
+ assert.notEqual(result.fusion?.lexicalDominance?.id, 'mem-template')
931
+ assert.equal(result.files[0].entry.content, tlsAnswer)
932
+ if (crossLibrary) assert.equal(result.files[0].libraryId, f.libraryId)
933
+ await assertRankingBoundary(crossLibrary ? 2 : 1)
934
+ })
935
+ }
936
+
937
+ for (const [language, template, query] of [
938
+ ['short Chinese', tlsTemplate, '请用自然简洁的语气回答。TLS 故障原因?'],
939
+ ['Chinese', '请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。', '请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。TLS 故障原因?'],
940
+ ['English', 'Please answer clearly and concisely with accurate context and natural language. Avoid repetition and unnecessary details.', 'Please answer clearly and concisely with accurate context and natural language. Avoid repetition and unnecessary details. What caused TLS failure?'],
941
+ ]) {
942
+ for (const size of [2, 3, 10]) {
943
+ test(`real BM25 ${language} long reply style keeps TLS answer first with ${size} documents`, async () => {
944
+ const f = fixture(tlsEntries(template, size))
945
+ activate([f.libraryId])
946
+ retrieveHook = () => ({ files: [{ name: 'mem-answer' }, { name: 'mem-template' }], segments: [], resources: [] })
947
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.4 })
948
+ assert.ok(result.files.length, 'style removal must not turn a topical query into empty recall')
949
+ assert.equal(result.files[0]?.name, 'mem-answer')
950
+ assert.notEqual(result.fusion?.lexicalDominance?.id, 'mem-template')
951
+ assert.ok(result.files[0].lexical > 0, 'TLS remains an actual lexical hit, not only a semantic rescue')
952
+ await assertRankingBoundary(1)
953
+ })
954
+ }
955
+ }
956
+
957
+ const rankingWords = 'certificate expired renewal proxy restart connection handshake trust chain hostname issuer validity protocol cipher client server clock intermediate root authority verification transport security gateway service outage investigation diagnosis mitigation deployment recovery monitoring incident encryption authentication socket timeout negotiation alert endpoint configuration rotation revocation openssl pem browser response failure latency availability maintenance rollback'.split(' ')
958
+ const foodQuery = '松茸的,我云南娃子喜欢吃菌子,还有过桥米线'
959
+ const foodAnswer = '主人是云南人,爱吃松茸菌子,在广州吃不到几家做菌子和过桥米线的馆子。'
960
+
961
+ test('real BM25 a weak 的 hit is no worse than zero evidence and preserves topical answer order', async () => {
962
+ const topicQuery = '松茸 云南 菌子 过桥米线 广州 馆子'
963
+ const entries = {
964
+ 'mem-food': rankingEntry(foodAnswer, { peak: true, createdAt: new Date(Date.now() - 4 * 86_400_000).toISOString() }),
965
+ 'mem-semantic': rankingEntry('钢琴练习巴赫赋格。', { strength: 0.8 }),
966
+ 'mem-weak': rankingEntry('归档标记:的', { strength: 0.8 }),
967
+ }
968
+ const f = fixture(entries)
969
+ activate([f.libraryId])
970
+ retrieveHook = () => ({ files: [{ name: 'mem-food' }, { name: 'mem-semantic' }], segments: [], resources: [] })
971
+ const result = await memory.privateRecall({ exec: f.exec, query: topicQuery + ' 的', topK: 5, relevanceThreshold: 0 })
972
+ assert.equal(result.files[0]?.name, 'mem-food')
973
+ assert.ok(result.fusion.lexicalDominance?.topLex >= 24, 'the test must exercise dominance, not an inactive branch')
974
+ const weak = result.files.find(file => file.name === 'mem-weak')
975
+ const zero = result.files.find(file => file.name === 'mem-semantic')
976
+ assert.ok(weak?.lexical > 0 && weak.lexical < result.files[0].lexical / 20, '的 is a real but tiny BM25 hit')
977
+ assert.ok(zero, 'the zero-evidence semantic candidate remains observable')
978
+ assert.equal(zero.lexical ?? 0, 0)
979
+ const sigma = 1 / (1 + result.fusion.lexicalDominance.topLex / 50)
980
+ assert.ok(Math.abs(weak.fusion.lexicalDiscount - sigma) < 1e-12, 'tiny evidence is protected by the continuous sigma floor')
981
+ assert.ok(weak.fusion.lexicalDiscount >= zero.fusion.lexicalDiscount, 'a tiny lexical hit cannot be penalized more than no hit')
982
+ const baseline = await memory.privateRecall({ exec: f.exec, query: topicQuery, topK: 5, relevanceThreshold: 0 })
983
+ assert.deepEqual(result.files.filter(file => file.name !== 'mem-weak').map(file => file.name), baseline.files.filter(file => file.name !== 'mem-weak').map(file => file.name))
984
+ await assertRankingBoundary(2)
985
+ })
986
+
987
+ test('real BM25 cross-library same-id facts stay separate and a strong foreign hit is real evidence', async () => {
988
+ state.updateSettings({ memoryBackend: 'agent' })
989
+ const query = rankingWords.slice(0, 38).join(' ')
990
+ const primaryEntries = {
991
+ // 逆序打破逐字包含/核心覆盖探针:两条同 id 事实必须靠身份而不是内容去重存活。
992
+ 'mem-shared': rankingEntry(rankingWords.slice(0, 3).reverse().join(' ')),
993
+ 'mem-secondary': rankingEntry(rankingWords.slice(3, 9).join(' ')),
994
+ }
995
+ const foreignEntries = { 'mem-shared': rankingEntry(query), 'mem-piano': rankingEntry(pianoNotes[0]) }
996
+ const { primary, foreign } = rankingWorld(primaryEntries, foreignEntries)
997
+ const all = await memory.privateRecall({ exec: primary.exec, query, topK: 5, relevanceThreshold: 0 })
998
+ assert.deepEqual(new Set(all.libraries), new Set([primary.libraryId, foreign.libraryId]))
999
+ const twins = all.files.filter(file => file.name === 'mem-shared')
1000
+ assert.equal(twins.length, 2, 'same id in two libraries is two facts, not one folded row')
1001
+ const sharedPrimary = twins.find(file => file.libraryId === primary.libraryId)
1002
+ const sharedForeign = twins.find(file => file.libraryId === foreign.libraryId)
1003
+ assert.equal(sharedPrimary.entry.content, primaryEntries['mem-shared'].content)
1004
+ assert.equal(sharedForeign.entry.content, query)
1005
+ assert.ok(sharedForeign.lexical > sharedPrimary.lexical, 'each twin keeps its own unified-corpus evidence, nothing is inherited')
1006
+ assert.ok(all.files.some(file => file.name === 'mem-secondary' && file.libraryId === primary.libraryId))
1007
+ assert.ok(!all.files.some(file => file.name === 'mem-piano'), 'zero-evidence foreign filler stays out')
1008
+ assert.equal(all.files[0].libraryId, foreign.libraryId, 'the genuinely strong foreign fact outranks weak local rows')
1009
+ assert.equal(all.fusion.crossLibraryLexical, 'unified-bm25')
1010
+ const cut = await memory.privateRecall({ exec: primary.exec, query, topK: 5, relevanceThreshold: 0.8 })
1011
+ assert.deepEqual(cut.files.map(file => [file.libraryId, file.name]), [[foreign.libraryId, 'mem-shared']], 'the 0.8 cut is real competition now, not ghost removal')
1012
+ const evidence = file => file.lexicalEvidence ?? file.lexical ?? 0
1013
+ const ranked = all.files.slice().sort((a, b) => evidence(b) - evidence(a))
1014
+ const dominant = evidence(ranked[0]) >= 24 && evidence(ranked[0]) >= evidence(ranked[1]) * 4
1015
+ assert.equal(Boolean(all.fusion.lexicalDominance), dominant, 'dominance is computed from the surviving unified evidence')
1016
+ if (dominant) assert.equal(all.fusion.lexicalDominance.id, ranked[0].name)
1017
+ for (const file of all.files) {
1018
+ assert.ok(Math.abs(file.retrievalScore - Math.min(1, file.fusion.rawRetrievalScore * (file.fusion.lexicalDiscount ?? 1))) < 1e-12)
1019
+ }
1020
+ await assertRankingBoundary(0)
1021
+ })
1022
+
1023
+ for (const gate of ['disclosure', 'speaker']) {
1024
+ test(`real BM25 ${gate} filtering recomputes dominance from eligible candidates`, async () => {
1025
+ const query = (gate === 'speaker' ? '我说过 ' : '') + rankingWords.join(' ')
1026
+ const entries = {
1027
+ 'mem-hidden': rankingEntry(rankingWords.join(' '), gate === 'disclosure' ? { disclosure: 'only_if_asked' } : { speaker_id: 'assistant' }),
1028
+ 'mem-small': rankingEntry(rankingWords.slice(0, 3).join(' '), { speaker_id: 'user', strength: 0.8 }),
1029
+ 'mem-normal': rankingEntry('钢琴练习已经完成,下一次排练在周末。', { speaker_id: 'user', strength: 0.8 }),
1030
+ }
1031
+ const scores = realLexical(entries, query)
1032
+ assert.ok(scores.get('mem-hidden') >= 24 && scores.get('mem-hidden') >= scores.get('mem-small') * 4)
1033
+ const f = fixture(entries)
1034
+ activate([f.libraryId])
1035
+ retrieveHook = () => ({ files: [{ name: 'mem-normal' }], segments: [], resources: [] })
1036
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8, purpose: 'automatic' })
1037
+ assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-normal', 'mem-small']))
1038
+ assert.equal(result.fusion.lexicalDominance, null, 'the final summary must not retain the excluded top')
1039
+ for (const file of result.files) {
1040
+ assert.equal(file.fusion.lexicalDominant, undefined)
1041
+ assert.equal(file.fusion.lexicalDiscount, undefined)
1042
+ assert.equal(file.retrievalScore, file.fusion.rawRetrievalScore, 'filtered survivors recover their raw RRF share')
1043
+ }
1044
+ await assertRankingBoundary(1)
1045
+ })
1046
+ }
1047
+
1048
+ test('real BM25 nested vector and cross-library RRF applies exactly one sigma to semantic-only recall', async () => {
1049
+ const query = rankingWords.join(' ')
1050
+ const entries = {
1051
+ 'mem-strong': rankingEntry(query),
1052
+ 'mem-mild': rankingEntry('端口8443证书根链验证失败,需要检查中间CA是否被撤销。', { tags: rankingWords.slice(0, 22) }),
1053
+ 'mem-semantic': rankingEntry(pianoNotes.join(' ')),
1054
+ }
1055
+ const scores = realLexical(entries, query)
1056
+ const inner = memory.fuseRecallCandidates({
1057
+ index: { entries },
1058
+ local: ['mem-strong', 'mem-mild'].map(name => ({ name, entry: entries[name], content: entries[name].content, lexical: scores.get(name) })),
1059
+ semantic: [{ name: 'mem-semantic' }, { name: 'mem-strong' }],
1060
+ })
1061
+ assert.deepEqual(inner.files.map(file => file.name), ['mem-strong', 'mem-mild', 'mem-semantic'], 'real lexical evidence changes the discounted inner ordering')
1062
+ assert.ok(inner.files[2].fusion.rawRetrievalScore > inner.files[1].fusion.rawRetrievalScore, 'raw order is semantic before mild, the opposite of discounted order')
1063
+ assert.equal(inner.debug.lexicalDominance.id, 'mem-strong')
1064
+ const { primary, foreign } = rankingWorld(entries, {})
1065
+ activate([primary.libraryId, foreign.libraryId])
1066
+ retrieveHook = args => ({ files: args.db === vp.dbPathFor(primary.libraryId) ? [{ name: 'mem-semantic' }, { name: 'mem-strong' }] : [], segments: [], resources: [] })
1067
+ const result = await memory.privateRecall({ exec: primary.exec, query, topK: 5, relevanceThreshold: 0 })
1068
+ assert.equal(result.recallRoute, 'cross-library')
1069
+ assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-strong', 'mem-mild', 'mem-semantic']))
1070
+ assert.equal(result.fusion.crossLibraryLexical, 'unified-bm25')
1071
+ assert.equal(result.fusion.crossLibrarySemantic, 'rank-only', 'hook files carry no scores, so the vector leg stays rank-only')
1072
+ const strong = result.files.find(file => file.name === 'mem-strong')
1073
+ const semantic = result.files.find(file => file.name === 'mem-semantic')
1074
+ const mild = result.files.find(file => file.name === 'mem-mild')
1075
+ // 统一语料此刻恰好等于主库三文档(外库为空),BM25 值与 realLexical 一致。
1076
+ const topLex = scores.get('mem-strong')
1077
+ assert.ok(topLex >= 24)
1078
+ assert.equal(strong.lexical, topLex)
1079
+ assert.equal(mild.lexical, scores.get('mem-mild'))
1080
+ // 方法间 RRF:词法腿 strong=1 mild=2,向量腿(rank-only)semantic=1 strong=2。
1081
+ const rrfStrong = 1 / 61 + 1 / 62
1082
+ assert.ok(Math.abs(strong.fusion.rawRetrievalScore - 1) < 1e-12)
1083
+ assert.ok(Math.abs(mild.fusion.rawRetrievalScore - (1 / 62) / rrfStrong) < 1e-12)
1084
+ assert.ok(Math.abs(semantic.fusion.rawRetrievalScore - (1 / 61) / rrfStrong) < 1e-12, 'outer RRF is rebuilt from unified leg ranks, not the discounted inner order')
1085
+ assert.equal(strong.fusion.bestRank, 1)
1086
+ assert.equal(mild.fusion.bestRank, 2, 'outer rank comes from the unified lexical leg, not the discounted inner rank of two')
1087
+ assert.equal(semantic.fusion.bestRank, 1)
1088
+ const sigma = 1 / (1 + topLex / 50)
1089
+ const mildDiscount = Math.sqrt(scores.get('mem-mild') / topLex)
1090
+ assert.ok(mildDiscount > sigma, 'the mild fact genuinely exercises the square-root branch')
1091
+ assert.ok(Math.abs(strong.retrievalScore - 1) < 1e-12)
1092
+ assert.ok(Math.abs(mild.retrievalScore - (1 / 62) / rrfStrong * mildDiscount) < 1e-12)
1093
+ assert.ok(Math.abs(semantic.retrievalScore - (1 / 61) / rrfStrong * sigma) < 1e-12, 'exactly one sigma, not multiplied by the inner share')
1094
+ assert.ok(Math.abs(semantic.retrievalScore - (1 / 61) / rrfStrong * sigma * sigma) > 0.01)
1095
+ assert.equal(result.fusion.lexicalDominance.id, 'mem-strong')
1096
+ assert.equal(result.fusion.lexicalDominance.stage, 'eligible')
1097
+ assert.equal(result.fusion.lexicalDominance.topLex, strong.lexical)
1098
+ assert.equal(semantic.fusion.lexicalDominantId, 'mem-strong')
1099
+ assert.equal(semantic.fusion.dominanceStage, 'eligible')
1100
+ assert.equal(calls.filter(call => call.db === vp.dbPathFor(primary.libraryId)).length, 1)
1101
+ assert.equal(calls.filter(call => call.db === vp.dbPathFor(foreign.libraryId)).length, 1)
1102
+ await assertRankingBoundary(2)
1103
+ })
1104
+
1105
+ test('real BM25 two tied genuinely strong topical hits both survive without corpus padding', async () => {
1106
+ const query = rankingWords.join(' ')
1107
+ const entries = {
1108
+ 'mem-tls-a': rankingEntry(rankingWords.slice(0, 26).join(' ')),
1109
+ 'mem-tls-b': rankingEntry(rankingWords.slice(26).join(' ')),
1110
+ }
1111
+ const f = fixture(entries)
1112
+ activate([f.libraryId])
1113
+ retrieveHook = () => ({ files: [{ name: 'mem-tls-a' }, { name: 'mem-tls-b' }], segments: [], resources: [] })
1114
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8 })
1115
+ assert.deepEqual(new Set(result.files.map(file => file.name)), new Set(['mem-tls-a', 'mem-tls-b']))
1116
+ for (const file of result.files) assert.ok(file.lexical >= 24, 'both hits are genuinely strong in this two-row corpus')
1117
+ assert.equal(result.fusion.lexicalDominance, null, 'two near-equal lexical tops do not single out a dominant row')
1118
+ await assertRankingBoundary(1)
1119
+ })
1120
+
1121
+ test('real BM25 QQ private-chat envelope and preference trailer preserve food as the top answer', async () => {
1122
+ const query = '[私聊:1299772830]22:11 Kingxiao(1299772830)[主人] #-100705771 [@咱]:松茸的,我云南娃子喜欢吃菌子,还有过桥米线\n[管理员的长期偏好·优先遵守]请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。\n【本会话是QQ私聊:1299772830。请用自然简洁的语气回答。】'
1123
+ const now = Date.now()
1124
+ const recentCreatedAt = new Date(now - 2 * 86_400_000).toISOString()
1125
+ const f = fixture({
1126
+ 'mem-food': rankingEntry(foodAnswer, { strength: 0.8, createdAt: recentCreatedAt }),
1127
+ 'mem-template': rankingEntry('[管理员的长期偏好·优先遵守]请结合上下文准确理解我的问题,不要机械重复,给出自然简洁且有条理的回复。【本会话是QQ私聊:1299772830。请用自然简洁的语气回答。】', { peak: true, createdAt: new Date(now - 4 * 86_400_000).toISOString() }),
1128
+ 'mem-piano': rankingEntry(pianoNotes[0], { createdAt: recentCreatedAt }),
1129
+ })
1130
+ activate([f.libraryId])
1131
+ retrieveHook = () => ({ files: [{ name: 'mem-template' }, { name: 'mem-food' }], segments: [], resources: [] })
1132
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.4 })
1133
+ assert.equal(result.files[0]?.name, 'mem-food', 'QQ transport text is not evidence of the user topic: ' + JSON.stringify({ fusion: result.fusion, files: result.files.map(({ name, lexical, lexicalEvidence, retrievalScore, score, fusion }) => ({ name, lexical, lexicalEvidence, retrievalScore, score, fusion })) }))
1134
+ assert.ok(result.files[0].lexical > 0 && result.files[0].lexicalEvidence > 0)
1135
+ assert.notEqual(result.fusion.lexicalDominance?.id, 'mem-template')
1136
+ assert.equal(calls[0].query, query, 'the semantic/index-facing query remains the original QQ message')
1137
+ await assertRankingBoundary(1)
1138
+ })
1139
+
1140
+ test('real BM25 same-leg and cross-leg folding retain the absorbed topical lexical evidence', async () => {
1141
+ const topic = rankingWords.join(' ')
1142
+ const query = '请用自然简洁的语气回答。' + topic
1143
+ const body = 'TLS故障已记录,请用自然简洁的语气回答。故障排查统一记录在运维台账。'
1144
+ const entries = {
1145
+ 'mem-a-host': rankingEntry(body, { tags: rankingWords.slice(0, 3) }),
1146
+ 'mem-z-strong': rankingEntry(body, { tags: rankingWords }),
1147
+ 'mem-piano': rankingEntry(pianoNotes[0]),
1148
+ }
1149
+ const originalScores = realLexical(entries, query)
1150
+ const evidenceScores = realLexical(entries, topic)
1151
+ assert.ok(evidenceScores.get('mem-z-strong') >= 24)
1152
+ assert.ok(originalScores.get('mem-z-strong') > originalScores.get('mem-a-host'))
1153
+ assert.ok(originalScores.get('mem-z-strong') > evidenceScores.get('mem-z-strong'), 'raw lexical includes the style overlap but evidence does not')
1154
+ const f = fixture(entries)
1155
+ activate([f.libraryId])
1156
+ retrieveHook = () => ({ files: [{ name: 'mem-a-host' }, { name: 'mem-z-strong' }], segments: [], resources: [] })
1157
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8 })
1158
+ assert.deepEqual(result.files.map(file => file.name), ['mem-a-host'], 'one real fact occupies one recall slot after both folding stages')
1159
+ const host = result.files[0]
1160
+ assert.equal(host.lexical, originalScores.get('mem-z-strong'), 'the absorbed source retains its stronger original BM25 score')
1161
+ assert.equal(host.lexicalEvidence, evidenceScores.get('mem-z-strong'), 'topical BM25 evidence is inherited independently of raw lexical')
1162
+ assert.deepEqual(host.mergedTogether, ['mem-z-strong'])
1163
+ assert.ok(result.fusion.collapsed.some(group => group.kept === 'mem-z-strong' && group.dropped.includes('mem-a-host')), 'within-leg duplicate folding occurred')
1164
+ assert.ok(result.fusion.collapsed.some(group => group.kept === 'mem-a-host' && group.dropped.includes('mem-z-strong')), 'semantic/cross-leg host absorbed the lexical source')
1165
+ assert.equal(result.fusion.lexicalDominance.id, 'mem-a-host', 'the surviving host owns the final dominance trace')
1166
+ assert.equal(result.fusion.lexicalDominance.topLex, host.lexicalEvidence)
1167
+ assert.equal(host.fusion.rawRetrievalScore, 1)
1168
+ await assertRankingBoundary(1)
1169
+ })
1170
+
1171
+ test('real BM25 Python in a request is topical evidence rather than a disposable reply template', async () => {
1172
+ const query = '请用Python回答TLS故障原因'
1173
+ const entries = {
1174
+ 'mem-python': rankingEntry('请用Python回答TLS故障原因:Python ssl 模块报告证书过期。'),
1175
+ 'mem-other': rankingEntry(pianoNotes[0]),
1176
+ }
1177
+ const f = fixture(entries)
1178
+ activate([f.libraryId])
1179
+ retrieveHook = () => ({ files: [], segments: [], resources: [] })
1180
+ const result = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.4 })
1181
+ assert.equal(result.files[0]?.name, 'mem-python', 'a topic-bearing imperative must not be cleared')
1182
+ const hit = result.files[0]
1183
+ assert.equal(hit.lexical, realLexical(entries, query).get('mem-python'))
1184
+ assert.equal(hit.lexicalEvidence ?? hit.lexical, hit.lexical, 'Python/TLS are retained in dominance evidence')
1185
+ assert.equal(calls[0].query, query)
1186
+ await assertRankingBoundary(1)
1187
+ })
1188
+
1189
+ test('automatic recall backfills a sixth qualified hit and reintroduces a changed admitted revision', async () => {
1190
+ state.updateSettings({ hybridRecall: true })
1191
+ const names = Array.from({ length: 6 }, (_, i) => 'mem-replay-' + i)
1192
+ const stamp = new Date(Date.now() - 86400000).toISOString()
1193
+ const entries = Object.fromEntries(names.map((name, i) => [name, rankingEntry(`AtlasReplay 部署备份节点${i}保留14天,每天执行核验。`, { createdAt: stamp, updatedAt: stamp })]))
1194
+ const f = fixture(entries)
1195
+ activate([f.libraryId])
1196
+ retrieveHook = () => ({ files: names.map(name => ({ name })), segments: [], resources: [] })
1197
+ const query = 'AtlasReplay 部署备份保留14天'
1198
+ const initial = await memory.privateRecall({ exec: f.exec, query, topK: 6, relevanceThreshold: 0.8, purpose: 'automatic' })
1199
+ assert.equal(initial.groups.length, 6)
1200
+ const shown = initial.refs.slice(0, 5)
1201
+ state.markInjectedRefs(f.sessionId, shown, 1, { messageId: 'admitted-replay-five', hostTurn: 1 })
1202
+ const excludedRefs = state.recentMemoryRefs(state.getSessionBinding(f.sessionId), 2, 16)
1203
+ const next = await memory.privateRecall({ exec: f.exec, query, topK: 1, relevanceThreshold: 0.8, purpose: 'automatic', excludedRefs })
1204
+ assert.equal(next.groups.length, 1)
1205
+ assert.equal(next.files[0].name, initial.refs[5].id)
1206
+ assert.equal(next.trace.counts.recentRows, 5)
1207
+ const changedId = shown[0].id
1208
+ await state.updatePrivateIndex(f.libraryId, index => { index.entries[changedId].content += ' 已补充副本验证。' })
1209
+ const changed = await memory.privateRecall({ exec: f.exec, query, topK: 1, relevanceThreshold: 0.8, purpose: 'automatic', excludedRefs })
1210
+ assert.equal(changed.files[0].name, changedId)
1211
+ assert.notEqual(changed.refs[0].revision, shown[0].revision)
1212
+ assert.equal(changed.groups[0].reintroducedForRevision, true)
1213
+ await assertRankingBoundary(2)
1214
+ })
1215
+
1216
+ test('automatic recent exclusion cannot promote an unqualified lexical-only noise hit', async () => {
1217
+ state.updateSettings({ hybridRecall: true })
1218
+ const names = Array.from({ length: 5 }, (_, i) => 'mem-qualified-' + i)
1219
+ const stamp = new Date(Date.now() - 86400000).toISOString()
1220
+ const entries = Object.fromEntries(names.map((name, i) => [name, rankingEntry(`AtlasQuiet 部署备份节点${i}保留14天,每天执行核验。`, { createdAt: stamp, updatedAt: stamp })]))
1221
+ entries['mem-quiet-noise'] = rankingEntry('AtlasQuiet 的闲聊杂谈,没有备份安排。', { createdAt: stamp, updatedAt: stamp })
1222
+ const f = fixture(entries)
1223
+ activate([f.libraryId])
1224
+ retrieveHook = () => ({ files: names.map(name => ({ name })), segments: [], resources: [] })
1225
+ const query = 'AtlasQuiet 部署备份保留14天'
1226
+ const initial = await memory.privateRecall({ exec: f.exec, query, topK: 5, relevanceThreshold: 0.8, purpose: 'automatic' })
1227
+ assert.equal(initial.refs.length, 5)
1228
+ state.markInjectedRefs(f.sessionId, initial.refs, 1, { messageId: 'admitted-qualified-five', hostTurn: 1 })
1229
+ const next = await memory.privateRecall({ exec: f.exec, query, topK: 1, relevanceThreshold: 0.8, purpose: 'automatic', excludedRefs: state.recentMemoryRefs(state.getSessionBinding(f.sessionId), 2, 16) })
1230
+ assert.deepEqual(next.files, [])
1231
+ assert.ok(next.trace.counts.weakRows > 0)
1232
+ assert.equal(next.trace.counts.recentRows, 5)
1233
+ await assertRankingBoundary(2)
1234
+ })