dsh-memu-memory 1.2.8 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +494 -0
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/docs/memory-semantics.md +3 -2
  5. package/lib/backup.js +154 -25
  6. package/lib/binding-diagnostics.js +2 -3
  7. package/lib/budget.js +0 -9
  8. package/lib/client.js +221 -128
  9. package/lib/commitment.js +3 -3
  10. package/lib/consolidation-ledger.js +46 -3
  11. package/lib/consolidation-receipt.js +41 -16
  12. package/lib/consolidation-worker.js +34 -10
  13. package/lib/curator-policy.js +23 -0
  14. package/lib/cycle.js +8 -4
  15. package/lib/embedding-download.js +168 -28
  16. package/lib/embedding-runtime.js +76 -17
  17. package/lib/engine.js +0 -6
  18. package/lib/freshness.js +2 -2
  19. package/lib/graph.js +139 -11
  20. package/lib/index.js +71 -20
  21. package/lib/inject.js +50 -7
  22. package/lib/lexicon.js +61 -16
  23. package/lib/local-vector-service.js +21 -1
  24. package/lib/media.js +49 -12
  25. package/lib/memory.js +662 -116
  26. package/lib/paths.js +0 -7
  27. package/lib/preset-scope.js +6 -1
  28. package/lib/private.js +281 -18
  29. package/lib/prompts/private-consolidation.md +2 -2
  30. package/lib/prompts/private-consolidation.rp.md +3 -2
  31. package/lib/prompts.js +0 -7
  32. package/lib/rpc.js +95 -17
  33. package/lib/snippet.js +18 -2
  34. package/lib/state.js +109 -30
  35. package/lib/stats.js +2 -2
  36. package/lib/temporal.js +19 -0
  37. package/lib/text-retrieval.js +120 -44
  38. package/lib/text-similarity.js +205 -24
  39. package/lib/tokenizer-v2.js +0 -24
  40. package/lib/tools.js +62 -62
  41. package/lib/vector-migration.js +15 -0
  42. package/lib/vector-profile.js +81 -8
  43. package/lib/visibility.js +0 -4
  44. package/lib/webui/standalone.css +17 -22
  45. package/lib/webui/standalone.js +27 -9
  46. package/lib/webui.js +4 -4
  47. package/package.json +3 -2
  48. package/scripts/acceptance-local.mjs +2 -2
  49. package/scripts/check-all.mjs +3 -1
  50. package/scripts/check-i18n.mjs +35 -1
  51. package/scripts/migrate-visibility.mjs +3 -3
  52. package/scripts/prune-sessions.mjs +34 -0
  53. package/scripts/prune-vectors.mjs +24 -0
  54. package/tests/appendix-b.test.mjs +5 -4
  55. package/tests/audit-batch3.test.mjs +247 -0
  56. package/tests/audit-regression.test.mjs +2 -2
  57. package/tests/backup.test.mjs +83 -83
  58. package/tests/browser.test.mjs +6 -1
  59. package/tests/client-render.test.mjs +2 -2
  60. package/tests/consolidation-fork.test.mjs +61 -15
  61. package/tests/consolidation-ledger.test.mjs +64 -3
  62. package/tests/consolidation-snapshot.test.mjs +25 -9
  63. package/tests/curator-clusters.test.mjs +18 -0
  64. package/tests/curator-pairing.test.mjs +59 -16
  65. package/tests/dynamic-rrf.test.mjs +22 -19
  66. package/tests/dynamic-threshold.test.mjs +52 -0
  67. package/tests/fact-version.test.mjs +18 -0
  68. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  69. package/tests/graph-cascade.test.mjs +29 -0
  70. package/tests/graph.test.mjs +45 -0
  71. package/tests/inject-conflict.test.mjs +18 -0
  72. package/tests/injection-chain.test.mjs +2 -2
  73. package/tests/lexical-bm25.test.mjs +171 -0
  74. package/tests/lexicon-frequency.test.mjs +16 -0
  75. package/tests/lexicon-inject.test.mjs +21 -0
  76. package/tests/lexicon-perf.test.mjs +37 -9
  77. package/tests/lexicon-scope.test.mjs +2 -2
  78. package/tests/lexicon-ui.test.mjs +1 -1
  79. package/tests/managed-memory.test.mjs +19 -0
  80. package/tests/ops-hardening.test.mjs +209 -0
  81. package/tests/package-shipping.test.mjs +4 -0
  82. package/tests/prompt-semantics.test.mjs +1 -1
  83. package/tests/prompts.test.mjs +1 -1
  84. package/tests/recall-intent.test.mjs +23 -0
  85. package/tests/slot-similarity.test.mjs +153 -0
  86. package/tests/state-gc.test.mjs +34 -0
  87. package/tests/state.test.mjs +2 -2
  88. package/tests/tokenizer-v2.test.mjs +1 -1
  89. package/tests/vector-gc.test.mjs +37 -0
  90. package/tests/webui.test.mjs +27 -0
@@ -10,7 +10,7 @@ process.env.DSH_MEMU_HOME = home
10
10
  const state = await import('../lib/state.js')
11
11
  const activity = await import('../lib/activity-log.js')
12
12
  const forkModel = await import('../lib/fork-model.js')
13
- const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY, CONSOLIDATION_WINDOW_EVENTS, compactSeedEvents, selectConsolidationWindow, selectTailTurnWindow } = await import('../lib/private.js')
13
+ const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY, CONSOLIDATION_WINDOW_EVENTS, compactSeedEvents, selectConsolidationWindow, selectTailTurnWindow, mustCoverCandidates, mergeMustCover, candidateCovered } = await import('../lib/private.js')
14
14
 
15
15
  test.after(() => {
16
16
  forkModel.disposeConsolidationRoute()
@@ -431,7 +431,48 @@ test('a manual re-check starts at a complete turn instead of mid-step', () => {
431
431
  assert.equal(window.throughSeq, 4, 'the window ends on a closed turn')
432
432
  })
433
433
 
434
- test('the same failed snapshot stops re-forking after the failure cap', async () => {
434
+ test('must-cover candidates keep the high-signal turn and its seq range', () => {
435
+ const events = [
436
+ { seq: 0, type: 'turn/start', data: {} },
437
+ { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '说好周末拿给阿兰换伞骨,记得带过去。' }] } },
438
+ { seq: 2, type: 'turn/end', data: {} },
439
+ { seq: 3, type: 'turn/start', data: {} },
440
+ { seq: 4, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '今天天气不错。' }] } },
441
+ { seq: 5, type: 'turn/end', data: {} },
442
+ ]
443
+ const rows = mustCoverCandidates(events, { max: 4 })
444
+ assert.equal(rows.length, 1, 'a low-signal turn is not a must-cover candidate')
445
+ assert.equal(rows[0].fromSeq, 0)
446
+ assert.equal(rows[0].throughSeq, 2)
447
+ assert.equal(rows[0].tag, '人物/关系')
448
+ assert.match(rows[0].text, /阿兰/)
449
+ })
450
+
451
+ test('mergeMustCover puts carried candidates first and reserves room for fresh ones', () => {
452
+ const carry = Array.from({ length: 6 }, (_, i) => ({ text: 'carry' + i, fromSeq: i, throughSeq: i, tag: '事实' }))
453
+ const fresh = Array.from({ length: 6 }, (_, i) => ({ text: 'fresh' + i, fromSeq: i, throughSeq: i, tag: '事实' }))
454
+ const merged = mergeMustCover(carry, fresh)
455
+ assert.equal(merged.length, 8)
456
+ assert.deepEqual(merged.slice(0, 4).map((row) => row.text), ['carry0', 'carry1', 'carry2', 'carry3'])
457
+ assert.deepEqual(merged.slice(4).map((row) => row.text), ['fresh0', 'fresh1', 'fresh2', 'fresh3'])
458
+ assert.ok(merged.slice(0, 4).every((row) => row.carried === true))
459
+ assert.equal(mergeMustCover([{ text: 'same' }], [{ text: 'same' }]).length, 1, 'duplicates are dropped')
460
+ })
461
+
462
+ test('a candidate is covered only when a written entry carries the fact', () => {
463
+ const index = {
464
+ entries: {
465
+ 'mem-1': { title: '楼下修伞的阿兰', content: '说好周末拿折伞给她换伞骨,布不用动。' },
466
+ 'mem-2': { title: '同事叶楠生日是八月十八号', content: '叶楠生日八月十八号。' },
467
+ },
468
+ }
469
+ assert.equal(candidateCovered({ text: '说好周末拿给阿兰换伞骨' }, ['mem-1'], index), true)
470
+ assert.equal(candidateCovered({ text: '叶楠生日八月十八号' }, ['mem-2'], index), true)
471
+ assert.equal(candidateCovered({ text: '父亲不吃芹菜' }, ['mem-1'], index), false)
472
+ assert.equal(candidateCovered({ text: '父亲不吃芹菜' }, [], index), false, 'no writes means no coverage')
473
+ })
474
+
475
+ test('the same failed snapshot stops automatic re-forking after the failure cap', async () => {
435
476
  state.ensureSession('fork-failcap', { cwd: path.join(home, 'proj-failcap'), agentPreset: 'coding' })
436
477
  const ctx = host({ live: true, turnReason: { kind: 'error', error: { message: 'provider refused' } } })
437
478
  const first = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
@@ -439,10 +480,15 @@ test('the same failed snapshot stops re-forking after the failure cap', async ()
439
480
  assert.equal(first.ok, false)
440
481
  assert.equal(second.ok, false)
441
482
  assert.equal(ctx.rec.created.length, 2, 'two real attempts happen')
442
- const third = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
483
+ // 自动路径仍然受上限约束:同一快照连续失败 2 次后不再付第三次 fork 成本。
484
+ const third = await requestPrivateConsolidation(ctx, 'fork-failcap')
443
485
  assert.equal(third.ok, true)
444
486
  assert.equal(third.skipped, 'snapshot-failed')
445
- assert.equal(ctx.rec.created.length, 2, 'the third call does not pay for the same snapshot again')
487
+ assert.equal(ctx.rec.created.length, 2, 'the automatic call does not pay for the same snapshot again')
488
+ // 手动整理是明确的一次再决定:force 不受上限约束(否则冻结回放/用户重试会被永久卡住)。
489
+ const forcedAgain = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
490
+ assert.equal(forcedAgain.ok, false)
491
+ assert.equal(ctx.rec.created.length, 3, 'a manual retry is allowed past the cap')
446
492
  })
447
493
 
448
494
  // ---------------------------------------------------------------- PTC 兼容
@@ -478,16 +524,16 @@ test('a PTC session (run_code only header) is consolidated and the worker gets w
478
524
  assert.equal(result.ok, true, 'a run_code header must not block consolidation: ' + String(result.error || ''))
479
525
  assert.equal(result.settled, true)
480
526
  assert.equal(ctx.rec.created.length, 1, 'the fork is created for the PTC conversation')
481
- // 只挂 worker 的读写面(记忆读写 + 关联裁决/候选 + 词典检索/写入);
482
- // archive/delete/unpin 这些破坏性工具不得进 worker 的工具面。
483
- assert.deepEqual([...registered].sort(), ['memu_lexicon_propose', 'memu_lexicon_search', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update'])
527
+ // 只挂 worker 真正用到的读写面(remember/update/link_suggest/list/recall/status);
528
+ // lexicon、private_link、archive/delete/unpin 这些用不到或破坏性的工具不进 worker 面。
529
+ assert.deepEqual([...registered].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
484
530
  // 整理结束(finally)必须卸载挂载,不能给这条一次性 worker 留常驻注册。
485
- assert.deepEqual([...disposals].sort(), ['memu_lexicon_propose', 'memu_lexicon_search', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update'])
531
+ assert.deepEqual([...disposals].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
486
532
  // 全量挂载的活动元数据:attached=实际子集(此处=完整 wanted)、requested=完整 wanted、
487
533
  // partial=false。三件一起钉住"成功路径不再含糊"。
488
534
  const started = startedEntryFor(ctx, 'fork-ptc')
489
- assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_lexicon_propose', 'memu_lexicon_search', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update'])
490
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_lexicon_propose', 'memu_lexicon_search', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update'])
535
+ assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
536
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
491
537
  assert.equal(started.detail.workerToolsPartial, false, 'a full mount is not partial')
492
538
  const followup = ctx.rec.forkFollowups[0]?.message
493
539
  const brief = Array.isArray(followup?.content)
@@ -529,14 +575,14 @@ test('a host registry refusing one write tool leaves a structured partial mount
529
575
  const result = await requestPrivateConsolidation(ctx, 'fork-ptc-partial')
530
576
  assert.equal(result.ok, true, String(result.error || ''))
531
577
  assert.equal(result.settled, true)
532
- assert.deepEqual([...registered].sort(), ['memu_lexicon_propose', 'memu_lexicon_search', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update'],
578
+ assert.deepEqual([...registered].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update', 'memu_status'],
533
579
  'exactly the tools that actually registered are mounted')
534
- assert.deepEqual([...disposals].sort(), ['memu_lexicon_propose', 'memu_lexicon_search', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update'],
580
+ assert.deepEqual([...disposals].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update', 'memu_status'],
535
581
  'dispose unmounts exactly what was mounted')
536
582
  const started = startedEntryFor(ctx, 'fork-ptc-partial')
537
- assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_lexicon_propose', 'memu_lexicon_search', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update'],
583
+ assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update', 'memu_status'],
538
584
  'the log records the actual subset, not the full wanted list')
539
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_lexicon_propose', 'memu_lexicon_search', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update'])
585
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
540
586
  assert.equal(started.detail.workerToolsPartial, true)
541
587
  // 挂载为部分子集时任务书仍带 PTC 调用形态:worker 知道写记忆走 run_code 的 SDK 绑定。
542
588
  const followup = ctx.rec.forkFollowups[0]?.message
@@ -557,7 +603,7 @@ test('a fork context without a tools service records a null mount, the request a
557
603
  assert.equal(result.ok, true, String(result.error || ''))
558
604
  const started = startedEntryFor(ctx, 'fork-ptc-notools')
559
605
  assert.equal(started.detail.workerToolsAttached, null, 'no mount completed, so the log must not claim one')
560
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_lexicon_propose', 'memu_lexicon_search', 'memu_private_link', 'memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update'])
606
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
561
607
  assert.equal(started.detail.workerToolsPartial, true)
562
608
  })
563
609
 
@@ -260,12 +260,55 @@ test('an unchanged existing id cannot prove an update', () => {
260
260
  assert.match(reconciled.problems.join(' '), /no verified post-worker change/)
261
261
  })
262
262
 
263
- test('a held id must really be pending_review', () => {
263
+ test('a held claim on an active entry is ignored, not fatal', () => {
264
264
  const index = { entries: { 'mem-1': { status: 'active' } } }
265
265
  const parsed = receipt.parseReceipt(fence({ status: 'completed', outcome: 'no_value', heldIds: ['mem-1'], checkedRange: { fromSeq: 0, throughSeq: 4 } }))
266
266
  const reconciled = receipt.reconcileReceipt({ receipt: parsed.receipt, index })
267
- assert.equal(reconciled.ok, false)
268
- assert.match(reconciled.problems.join(' '), /not pending_review/)
267
+ // 库是权威:worker 说「暂扣」但条目正常落库时,不把整份回执退回。
268
+ assert.equal(reconciled.ok, true)
269
+ assert.deepEqual(reconciled.heldIds, [])
270
+ })
271
+
272
+ test('a held claim is accepted when the entry carries a conflict marker', () => {
273
+ const index = { entries: { 'mem-1': { status: 'active', conflictingWith: 'mem-2', reviewReason: '说法相反' } } }
274
+ const parsed = receipt.parseReceipt(fence({ status: 'completed', outcome: 'no_value', heldIds: ['mem-1'], checkedRange: { fromSeq: 0, throughSeq: 4 } }))
275
+ const reconciled = receipt.reconcileReceipt({ receipt: parsed.receipt, index })
276
+ assert.equal(reconciled.ok, true)
277
+ assert.deepEqual(reconciled.heldIds, ['mem-1'])
278
+ })
279
+
280
+ test('a memory created and updated in the same window is a create, not a failed update', () => {
281
+ const index = { entries: { 'mem-new': { status: 'active', content: 'final' }, 'mem-old': { status: 'active', content: 'same' } } }
282
+ const parsed = receipt.parseReceipt(fence({
283
+ status: 'completed', outcome: 'mixed', createdIds: ['mem-new'], updatedIds: ['mem-new', 'mem-old'], checkedRange: { fromSeq: 0, throughSeq: 4 },
284
+ }))
285
+ const reconciled = receipt.reconcileReceipt({
286
+ receipt: parsed.receipt,
287
+ index,
288
+ beforeIds: new Set(['mem-old']),
289
+ beforeEntries: { 'mem-old': receipt.entryFingerprint({ status: 'active', content: 'same' }) },
290
+ })
291
+ assert.equal(reconciled.ok, true)
292
+ assert.deepEqual(reconciled.createdIds, ['mem-new'])
293
+ assert.deepEqual(reconciled.updatedIds, [])
294
+ assert.equal(reconciled.outcome, 'created')
295
+ })
296
+
297
+ test('a retry may report a previous attempt write as created without failing', () => {
298
+ const index = { entries: { 'mem-prev': { status: 'active', content: 'v2' } } }
299
+ const parsed = receipt.parseReceipt(fence({
300
+ status: 'completed', outcome: 'created', createdIds: ['mem-prev'], checkedRange: { fromSeq: 0, throughSeq: 4 },
301
+ }))
302
+ const reconciled = receipt.reconcileReceipt({
303
+ receipt: parsed.receipt,
304
+ index,
305
+ beforeIds: new Set(['mem-prev']),
306
+ beforeEntries: { 'mem-prev': receipt.entryFingerprint({ status: 'active', content: 'v1' }) },
307
+ })
308
+ assert.equal(reconciled.ok, true)
309
+ assert.deepEqual(reconciled.duplicateIds, ['mem-prev'])
310
+ assert.deepEqual(reconciled.updatedIds, ['mem-prev'])
311
+ assert.equal(reconciled.outcome, 'updated')
269
312
  })
270
313
 
271
314
  test('decideCompletion: proof advances, guesswork does not', () => {
@@ -295,4 +338,22 @@ test('decideCompletion never settles a silent worker on its own', () => {
295
338
  const unattributed = receipt.decideCompletion({ text: '', wrote: 2 })
296
339
  assert.equal(unattributed.advance, false)
297
340
  assert.match(unattributed.error, /receipt|cannot settle/i)
341
+ })
342
+
343
+ test('carry candidates survive the ledger round-trip and stay bounded', () => {
344
+ ledger.setCarryCandidates('carry-1', [
345
+ { fromSeq: 1080, throughSeq: 1085, tag: '人物/关系', text: '说好周末拿给阿兰换伞骨', observedAt: '2026-05-17T12:00:00+08:00' },
346
+ { fromSeq: 1152, throughSeq: 1163, tag: '人物/关系', text: '普法折页:小圆先登记,后换阿梁接手' },
347
+ ])
348
+ const rows = ledger.readCarryCandidates('carry-1')
349
+ assert.equal(rows.length, 2)
350
+ assert.deepEqual(rows[0], {
351
+ fromSeq: 1080, throughSeq: 1085, score: 0, tag: '人物/关系',
352
+ text: '说好周末拿给阿兰换伞骨', observedAt: '2026-05-17T12:00:00+08:00',
353
+ })
354
+ const many = Array.from({ length: 12 }, (_, i) => ({ text: '候选 ' + i }))
355
+ ledger.setCarryCandidates('carry-1', many)
356
+ assert.equal(ledger.readCarryCandidates('carry-1').length, ledger.CARRY_LIMIT, 'the carry list is capped')
357
+ ledger.setCarryCandidates('carry-1', [])
358
+ assert.deepEqual(ledger.readCarryCandidates('carry-1'), [], 'a covered window clears the carry')
298
359
  })
@@ -281,7 +281,7 @@ test('auxiliary link and lexicon tools alone do not prove the worker can write m
281
281
  assert.equal(probe.hasWrite, false)
282
282
  })
283
283
 
284
- test('the brief teaches the suggest-then-adjudicate loop and lexicon extraction', () => {
284
+ test('the brief teaches the suggest-then-adjudicate loop and the receipt buckets', () => {
285
285
  const brief = buildWorkerBrief({
286
286
  snapshot: { fromSeq: 0, throughSeq: 5, eventCount: 6, hash: 'brief01' },
287
287
  probe: { tools: ['memu_private_remember', 'memu_private_update', 'memu_private_link_suggest', 'memu_lexicon_propose'] },
@@ -289,13 +289,10 @@ test('the brief teaches the suggest-then-adjudicate loop and lexicon extraction'
289
289
  })
290
290
  assert.match(brief, /memu_private_link_suggest\(\{ids:\[\.\.\.\]\}\)/, 'the call shape is spelled out')
291
291
  assert.match(brief, /已经自动连好/, 'high-confidence links are applied before the worker sees candidates')
292
- assert.match(brief, /每轮最多确认 5 条/)
293
- assert.match(brief, /noop/)
294
- assert.match(brief, /conflict/)
295
- assert.match(brief, /memu_lexicon_search/)
296
- assert.match(brief, /memu_lexicon_propose/)
297
- assert.match(brief, /term 是索引键/)
298
- assert.match(brief, /sensitive trigger/)
292
+ assert.match(brief, /每窗最多新增 8 条/)
293
+ assert.match(brief, /heldIds/)
294
+ // 整理 worker 只挂用得到的 6 个工具:词典/lexicon 不再出现在任务书里。
295
+ assert.doesNotMatch(brief, /memu_lexicon|term 是索引键|sensitive trigger/)
299
296
  assert.match(brief, /tools-unavailable/, 'the tools-unavailable contract survives')
300
297
  assert.match(brief, /没有回执视为本次整理失败/, 'the receipt requirement survives')
301
298
  assert.match(brief, /BRIEF-CONTRACT/)
@@ -346,7 +343,7 @@ test('a mixed surface (run_code beside native memu_*) proves write ability and k
346
343
  probe,
347
344
  contract: 'MIXED-CONTRACT',
348
345
  })
349
- assert.match(brief, /run_code, memu_private_remember, memu_private_update/, 'the brief lists the native names')
346
+ assert.match(brief, /memu_private_remember, memu_private_update/, 'the brief lists the allowed native names')
350
347
  assert.match(brief, /await tools\.memu_private_remember/, 'the brief keeps the PTC SDK invocation shape on a mixed surface')
351
348
  assert.match(brief, /MIXED-CONTRACT/)
352
349
  })
@@ -396,4 +393,23 @@ test('the worker brief carries the range, the tools and the receipt contract', (
396
393
  assert.match(brief, /RECEIPT-CONTRACT-MARKER/)
397
394
  assert.match(brief, /手动/)
398
395
  assert.match(brief, /tools-unavailable/)
396
+ })
397
+
398
+ test('the worker brief renders the must-cover checklist with seq ranges', () => {
399
+ const brief = buildWorkerBrief({
400
+ snapshot: { fromSeq: 998, throughSeq: 1211, eventCount: 214, hash: 'opt6' },
401
+ probe: { tools: ['memu_private_remember'] },
402
+ contract: '',
403
+ mustCover: [
404
+ { fromSeq: 1080, throughSeq: 1085, tag: '人物/关系', text: '说好周末拿给阿兰换伞骨' },
405
+ { fromSeq: 1152, throughSeq: 1157, tag: '人物/关系', text: '普法折页,小圆负责入口登记' },
406
+ { fromSeq: 0, throughSeq: 0, tag: '事实', text: '父亲不吃芹菜', carried: true, observedAt: '2026-05-17T12:00:00+08:00' },
407
+ ],
408
+ })
409
+ assert.match(brief, /本窗必写候选/)
410
+ assert.match(brief, /第 1080–1085 条 · 人物\/关系/)
411
+ assert.match(brief, /阿兰/)
412
+ assert.match(brief, /小圆负责入口登记/)
413
+ assert.match(brief, /顺延 · 事件时间 2026-05-17/)
414
+ assert.match(brief, /来自之前窗口/)
399
415
  })
@@ -4,6 +4,7 @@ import fs from 'node:fs'
4
4
  import os from 'node:os'
5
5
  import path from 'node:path'
6
6
  import { registerHooks } from 'node:module'
7
+ import { performance } from 'node:perf_hooks'
7
8
 
8
9
  // Candidate clusters (spec §4.4) + curator context packing (§4.5).
9
10
  //
@@ -107,6 +108,23 @@ test('N=301 switches to inverted blocking: the same pair shares only 1 token and
107
108
  assert.equal(clusters.length, 0, 'shared token count 1 < blockMinShared 2 keeps the pair out')
108
109
  })
109
110
 
111
+ test('N=800 blocking with corpus-wide shared text stays well under 3s (dfCap prunes postings first)', () => {
112
+ // 复现 A-1 的病态形态:每条都带一段完全相同的中文闲聊,再各带一个独有的
113
+ // 后缀。旧实现把每个高频 bigram 的 posting 展开成 800²/2 个对,再对 32 万个
114
+ // 对跑 similarityDetail + 双向 BM25(实测 N=500 需 5.8s)。dfCap 在倒排层
115
+ // 跳过这些 posting,共享 token 预筛再挡掉 0 共享的对。
116
+ const chatter = '今晚的雾夜灯桥边茶铺霜露未散他忽然提起那些旧梗台词接得毫无痕迹我们笑作一团后来月影移过柳岸鹤鸣惊起溪桥下打盹的猫谁也没接话只是把茶续上'
117
+ const entries = []
118
+ for (let i = 0; i < 800; i += 1) {
119
+ entries.push(entryOf(`bulk-${i}`, 'x', `${chatter}第${i}号独有后缀`))
120
+ }
121
+ const started = performance.now()
122
+ const result = buildCandidateClusters(index(entries))
123
+ const elapsed = performance.now() - started
124
+ assert.equal(result.scanned, 800)
125
+ assert.ok(elapsed < 3000, `N=800 took ${elapsed.toFixed(0)}ms (regression bound 3000ms)`)
126
+ })
127
+
110
128
  // —— all-pairs clique growth ——
111
129
 
112
130
  // A-B ≈0.68, B-C ≈0.82, A-C ≈0.39: whichever edge seeds the cluster, the third
@@ -13,6 +13,7 @@ import {
13
13
  tokenize,
14
14
  } from '../lib/text-retrieval.js'
15
15
  import { similarityDetail, similarTexts, bigrams, dice } from '../lib/text-similarity.js'
16
+ import { RRF_K, RRF_W_BM25, RRF_W_DICE, RRF_W_ENTITY } from '../lib/curator-policy.js'
16
17
 
17
18
  // —— §4.1 tokenize ——
18
19
 
@@ -82,6 +83,34 @@ test('bm25: queries wider than 64 terms keep the matching terms (junk never evic
82
83
  assert.equal(bm25(query, corpus.docs.get('b'), corpus), bm25(hits, corpus.docs.get('b'), corpus))
83
84
  assert.ok(bm25(hits, corpus.docs.get('b'), corpus) > 0)
84
85
  })
86
+ test('bm25: a corpus-wide high-frequency character is dropped from the query instead of pulling the whole library in', () => {
87
+ const entries = []
88
+ for (let i = 1; i <= 40; i += 1) {
89
+ entries.push({
90
+ id: `freq-${i}`,
91
+ title: `记录 ${i}`,
92
+ content: `第 ${i} 条记录的内容里都带着这个高频字:的。${i === 1 ? '另外还有一个独角兽专属词。' : ''}`,
93
+ })
94
+ }
95
+ const corpus = buildCorpus(entries)
96
+ assert.ok(corpus.df.get('的') >= 40, 'the fixture must make 的 a corpus-wide term')
97
+ const doc = corpus.docs.get('freq-1')
98
+ // A-2:df > dfCap 的 term 整条不参与打分。旧实现给出一个很小的正数,于是
99
+ // 查「的」能把全库都拉进候选池;现在它不产生任何分数。
100
+ assert.equal(bm25(tokenize('的'), doc, corpus), 0)
101
+ // 真正的稀有 term 不受影响——闸门只剔高频词,不改正常词的分值口径。
102
+ assert.ok(bm25(tokenize('独角兽'), doc, corpus) > 0)
103
+ })
104
+
105
+ test('bm25: query term frequency is preserved (qtf multiplies that term\'s contribution)', () => {
106
+ const corpus = corpusFor()
107
+ const doc = corpus.docs.get('b')
108
+ const once = bm25(['缓存'], doc, corpus)
109
+ const twice = bm25(['缓存', '缓存'], doc, corpus)
110
+ assert.ok(once > 0)
111
+ assert.ok(Math.abs(twice - 2 * once) < 1e-12, `qtf=2 must double the contribution: ${once} -> ${twice}`)
112
+ })
113
+
85
114
  // —— §4.2 similarityDetail / pairFeatures / pairScore ——
86
115
 
87
116
  test('similarityDetail: length-comparable pairs report dice, pruned pairs report the containment floor', () => {
@@ -240,37 +269,51 @@ test('rankPairCandidates: deterministic — same input, same output', () => {
240
269
 
241
270
  // —— §4.3 边界带(P0-1 回归修复的守卫):代理切分 → pairScore 真尺终选 ——
242
271
  //
243
- // 手算秩结构(可复现 fixture,文本两两相同造成 bm25/dice 精确并列,en 路由的
244
- // containment tiebreak 由 cand-c/d 的逐字包含 0.92 垫高):
245
- // cand-a: bm1, di1, en4 → rrf = 0.5/61 + 0.3/61 + 0.2/64 = 1.6240e-2(rank 1,切点)
246
- // cand-b: bm2, di2, en1 → rrf = 0.5/62 + 0.3/62 + 0.2/61 = 1.6183e-2(rank 2,带内:
247
- // 与切点差 (0.5+0.3)×(1/61−1/62) − 0.2×(1/61−1/64) = 5.78e-5 ≤ RRF_SLICE_BAND)
248
- // cand-c/d: rrf 更低,带外(仅作 en 路由 containment 垫脚)。
249
- // pairScore:cand-b 0.9894(entity 匹配)≫ cand-a 0.8394(appliesTo 不相交)。
250
- // 修复前 pre-cut=limit=1 只评分 cand-a,返回 ['cand-a'];边界带把 cand-b 并入
251
- // 评分集,真尺终选翻到 cand-b——准入从 RRF 代理换成 pairScore 真尺的直接证据。
272
+ // 手算秩结构(A-12 之后并列共享名次,fixture 不再靠 id tiebreak 制造分差):
273
+ // cand-a: 与 proposal 文本全同、appliesTo 不相交 → bm1, di1, en2
274
+ // rrf = 0.5/61 + 0.3/61 + 0.2/62(切点)
275
+ // cand-b: 文本只多一个词、appliesTo 相同 → bm2, di2, en1
276
+ // rrf = 0.5/62 + 0.3/62 + 0.2/61
277
+ // 差值 = 0.6×(1/61−1/62) = 1.58e-4 ≤ RRF_SLICE_BAND(2.5e-4),所以 b 落在带内。
278
+ // pairScore:b(entity 1.0)明显高于 a(entity 0)——pre-cut=limit=1 只评分 a,
279
+ // 边界带把 b 并入评分集后真尺终选翻到 b:准入从 RRF 代理换成 pairScore 真尺。
252
280
  test('rankPairCandidates: the slice boundary band admits a better-pairScore candidate the RRF proxy dropped', () => {
253
- const twin = 'Redis 缓存统一设置 30 秒过期,命中直接返回。Redis 缓存统一设置 30 秒过期,命中直接返回。'
254
- const tail = '。另有运维值班轮换表与告警升级路径的完整说明,这里补足长度让长度剪枝生效并保持逐字包含。'
255
281
  const proposal = { title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回。', appliesTo: ['deploy'], track: 'memory', domain: 'general' }
256
282
  const corpus = buildCorpus([
257
- { id: 'cand-a', title: '缓存过期', content: twin, appliesTo: [], track: 'memory', domain: 'general' },
258
- { id: 'cand-b', title: '缓存过期', content: twin, appliesTo: ['deploy'], track: 'memory', domain: 'general' },
259
- { id: 'cand-c', title: '缓存过期', content: proposal.content + tail, appliesTo: [], track: 'memory', domain: 'general' },
260
- { id: 'cand-d', title: '缓存过期', content: proposal.content + tail, appliesTo: [], track: 'memory', domain: 'general' },
283
+ { id: 'cand-a', title: '缓存过期', content: proposal.content, appliesTo: [], track: 'memory', domain: 'general' },
284
+ { id: 'cand-b', title: '缓存过期', content: 'Redis 缓存统一设置 30 秒过期,命中直接返回数据。', appliesTo: ['deploy'], track: 'memory', domain: 'general' },
261
285
  ])
262
286
  const found = rankPairCandidates({ corpus, proposal, limit: 1 })
263
287
  // 真尺终选:数量语义不变(≤max),赢家是带内 rescue 的高 pairScore 候选
264
288
  assert.equal(found.length, 1)
265
289
  assert.equal(found[0].id, 'cand-b')
266
290
  // 赢家的 rrf 严格低于切点(cand-a 的手算 rrf)——证明它来自边界带而非 pre-cut
267
- const cutRrf = 0.5 / (60 + 1) + 0.3 / (60 + 1) + 0.2 / (60 + 4)
291
+ const cutRrf = (RRF_W_BM25 + RRF_W_DICE) / (RRF_K + 1) + RRF_W_ENTITY / (RRF_K + 2)
268
292
  assert.ok(found[0].rrf < cutRrf, `winner rrf ${found[0].rrf} must sit below the pre-cut line ${cutRrf}`)
293
+ assert.ok(cutRrf - found[0].rrf <= 2.5e-4, 'and the gap must stay inside the slice band')
269
294
  // 被切掉的 cand-a 在真尺上确实更差(低 pairScore 者按 pairScore 出局)
270
295
  const loserScore = pairScore(pairFeatures(proposal, corpus.docs.get('cand-a').entry))
271
296
  assert.ok(found[0].score > loserScore, `band winner ${found[0].score} must beat the displaced candidate ${loserScore}`)
272
297
  })
273
298
 
299
+ // —— A-12:同分文档共享名次,RRF 贡献相等 ——
300
+ test('rankPairCandidates: two tied documents contribute the same RRF (competition ranking)', () => {
301
+ const text = 'Redis 缓存统一设置 30 秒过期,命中直接返回。'
302
+ const proposal = { title: '缓存过期', content: text, appliesTo: [], track: 'memory', domain: 'general' }
303
+ const corpus = buildCorpus([
304
+ { id: 'twin-b', title: '缓存过期', content: text, appliesTo: [], track: 'memory', domain: 'general' },
305
+ { id: 'twin-a', title: '缓存过期', content: text, appliesTo: [], track: 'memory', domain: 'general' },
306
+ ])
307
+ const found = rankPairCandidates({ corpus, proposal, limit: 20 })
308
+ const a = found.find((item) => item.id === 'twin-a')
309
+ const b = found.find((item) => item.id === 'twin-b')
310
+ assert.ok(a && b)
311
+ // 三路全部并列 rank 1:rrf = (0.5+0.3+0.2)/(K+1)。旧实现给同分者 1/2 名,
312
+ // 两者的 rrf 会不相等(1/61 vs 1/62)。
313
+ assert.equal(a.rrf, b.rrf)
314
+ assert.ok(Math.abs(a.rrf - (RRF_W_BM25 + RRF_W_DICE + RRF_W_ENTITY) / (RRF_K + 1)) < 1e-15)
315
+ })
316
+
274
317
  // —— §4.8 全局冲突预筛 ——
275
318
 
276
319
  test('globalConflictCheck: same title + different body is same_title; negation flips conflict', () => {
@@ -119,34 +119,37 @@ function recentCorpus() {
119
119
  ])
120
120
  }
121
121
 
122
- test('recency 查询下 updatedAt 更新的候选相对提升:rrf 差距收窄、新者增益为正、旧者为负', () => {
122
+ test('recency 查询下同分文档共享三路名次,recency 第四路成为唯一区分信号', () => {
123
123
  const corpus = recentCorpus()
124
124
  const proposal = { track: 'memory', domain: 'general', title: '缓存过期', content: '昨天 缓存过期提醒每日检查' }
125
125
  const found = rankPairCandidates({ corpus, proposal, limit: 20 })
126
126
  assert.equal(found.length, 2)
127
- // 文本全同 → 三路 tie 由 idAsc 定序:a-old 三路 rank1、b-new rank2;
128
- // recency 通道按 updatedAt 降序:b-new rank1、a-old rank2。
129
- const rrfOld = found.find((c) => c.id === 'a-old').rrf
130
- const rrfNew = found.find((c) => c.id === 'b-new').rrf
131
- // 静态口径的期望值(同一表达式、rank 1/2)
132
- const statOld = RRF_W_BM25 / (RRF_K + 1) + RRF_W_DICE / (RRF_K + 1) + RRF_W_ENTITY / (RRF_K + 1)
133
- const statNew = RRF_W_BM25 / (RRF_K + 2) + RRF_W_DICE / (RRF_K + 2) + RRF_W_ENTITY / (RRF_K + 2)
134
- // 新者的 rrf 相对静态严格提升,旧者严格下降 → 相对排名提升
135
- assert.ok(rrfNew > statNew, `新者应增益:${rrfNew} > ${statNew}`)
136
- assert.ok(rrfOld < statOld, `旧者应减益:${rrfOld} < ${statOld}`)
137
- // 两者差距收窄(0.8δ → 0.6δ),即 recency 把新者往前拉
138
- assert.ok(rrfOld - rrfNew < statOld - statNew)
139
- // recency 权重不足以翻转文本三路的合计优势(0.6δ > 0),排序仍稳定
140
- assert.equal(found[0].id, 'a-old')
141
- assert.equal(found[1].id, 'b-new')
127
+ // A-12:文本全同 → bm25/dice/entity 三路并列,竞赛排名下都取 rank 1(旧实现
128
+ // 用 idAsc 把它们拆成 rank 1/2,凭空制造分差)。recency 是唯一区分通道:
129
+ // b-new updatedAt 更新 → rank 1,a-old rank 2。
130
+ const w = computeRRFWeights(proposal, corpus)
131
+ assert.ok(w.recency != null, 'fixture must take the recency route')
132
+ const textRoutes = w.bm25 / (RRF_K + 1) + w.dice / (RRF_K + 1) + w.entity / (RRF_K + 1)
133
+ const rrfNew = textRoutes + w.recency / (RRF_K + 1)
134
+ const rrfOld = textRoutes + w.recency / (RRF_K + 2)
135
+ assert.ok(Math.abs(found.find((c) => c.id === 'b-new').rrf - rrfNew) < 1e-15)
136
+ assert.ok(Math.abs(found.find((c) => c.id === 'a-old').rrf - rrfOld) < 1e-15)
137
+ // 文本三路不提供任何区分,recency 足以把更新的文档推到前面。
138
+ assert.ok(rrfNew > rrfOld)
139
+ assert.equal(found[0].id, 'b-new')
140
+ assert.equal(found[1].id, 'a-old')
142
141
  })
143
142
 
144
- test('非近期查询下同一 corpus 不受 recency 影响:rrf 与静态公式逐位相等', () => {
143
+ test('非近期查询下同一 corpus 不受 recency 影响:同分同 rrf,输出按 id 稳定', () => {
145
144
  const corpus = recentCorpus()
146
145
  const proposal = { track: 'memory', domain: 'general', title: '缓存过期', content: '缓存过期提醒每日检查' }
147
146
  const found = rankPairCandidates({ corpus, proposal, limit: 20 })
148
- assert.equal(found[0].rrf, RRF_W_BM25 / (RRF_K + 1) + RRF_W_DICE / (RRF_K + 1) + RRF_W_ENTITY / (RRF_K + 1))
149
- assert.equal(found[1].rrf, RRF_W_BM25 / (RRF_K + 2) + RRF_W_DICE / (RRF_K + 2) + RRF_W_ENTITY / (RRF_K + 2))
147
+ // 文本全同 → 三路并列 rank 1,A-12 后两条 rrf 相等(旧实现是 1/61 与 1/62)。
148
+ const tied = (RRF_W_BM25 + RRF_W_DICE + RRF_W_ENTITY) / (RRF_K + 1)
149
+ assert.equal(found[0].rrf, tied)
150
+ assert.equal(found[1].rrf, tied)
151
+ assert.equal(found[0].id, 'a-old', 'equal rrf falls back to idAsc')
152
+ assert.equal(found[1].id, 'b-new')
150
153
  })
151
154
 
152
155
  test('结果确定性:同输入两次 rankPairCandidates / computeRRFWeights 完全一致', () => {
@@ -0,0 +1,52 @@
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-percentile-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+
10
+ const state = await import('../lib/state.js')
11
+ const memory = await import('../lib/memory.js')
12
+
13
+ test.after(() => {
14
+ delete process.env.DSH_MEMU_RECALL_PERCENTILE
15
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
16
+ })
17
+
18
+ function fixture() {
19
+ const sessionId = 'percentile'
20
+ const cwd = path.join(home, 'ws-percentile')
21
+ state.ensureSession(sessionId, { cwd, agentPreset: 'coding' })
22
+ const binding = state.getSessionBinding(sessionId)
23
+ const index = state.loadPrivateIndex(binding.libraryId)
24
+ const now = new Date().toISOString()
25
+ const topics = ['预算', '排期', '招聘', '客户投诉', '机房迁移', '季度目标', '培训', '安全审计', '值班表', '产品路线']
26
+ for (const [i, topic] of topics.entries()) {
27
+ index.entries[`mem-p${i}`] = {
28
+ title: `会议记录 ${i}`,
29
+ content: `会议主要讨论${topic},结论是下周继续跟进,负责人单独确认。`,
30
+ status: 'active', layer: 'long_term', createdAt: now, updatedAt: now,
31
+ }
32
+ }
33
+ state.savePrivateIndex(binding.libraryId, index)
34
+ return { exec: { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'coding' } } } } }
35
+ }
36
+
37
+ test('percentile cut is off by default and never pads a minimum result count', async () => {
38
+ const { exec } = fixture()
39
+ delete process.env.DSH_MEMU_RECALL_PERCENTILE
40
+ const normal = await memory.privateRecall({ exec, query: '会议', topK: 10, relevanceThreshold: 0 })
41
+ assert.equal(normal.files.length, 10, 'default keeps the requested topK')
42
+
43
+ process.env.DSH_MEMU_RECALL_PERCENTILE = '1'
44
+ const narrowed = await memory.privateRecall({ exec, query: '会议', topK: 10, relevanceThreshold: 0 })
45
+ assert.ok(narrowed.files.length > 0 && narrowed.files.length < normal.files.length, 'percentile must narrow, not pad')
46
+ assert.equal(narrowed.files.length, Math.ceil(normal.files.length * 0.25))
47
+ assert.equal(narrowed.files[0].name, normal.files[0].name, 'the best hit is preserved')
48
+ delete process.env.DSH_MEMU_RECALL_PERCENTILE
49
+
50
+ const none = await memory.privateRecall({ exec, query: 'qqqqzzzz', topK: 10, relevanceThreshold: 0 })
51
+ assert.equal(none.files.length, 0, 'a no-match stays empty')
52
+ })
@@ -120,6 +120,24 @@ test('relation targets must exist, be active and share the scope', async () => {
120
120
  assert.ok(!Object.values(stored).some((entry) => entry.title === '坏目标'), 'nothing is written when the target is invalid')
121
121
  })
122
122
 
123
+ test('explicit provenance derives local authority and evidence without extra card text', async () => {
124
+ const { exec } = session('fact-authority')
125
+ const quoted = await memory.privateRemember({
126
+ exec, title: '报价确认', content: '他确认报价是三十万。',
127
+ source: 'user_said', quoteSpan: { seq: 8, turn: 2, textHash: 'abc' },
128
+ })
129
+ assert.equal(quoted.entry.fact_authority, 3)
130
+ assert.deepEqual(quoted.entry.fact_evidence, { seq: 8, turn: 2, textHash: 'abc' })
131
+
132
+ const guessed = await memory.privateRemember({
133
+ exec, title: '报价猜测', content: '我猜报价大概是三十万。',
134
+ })
135
+ assert.equal(guessed.entry.fact_authority, 1)
136
+
137
+ const corrected = await memory.privateUpdate({ exec, id: guessed.id, source: 'user_said' })
138
+ assert.equal(corrected.entry.fact_authority, 3, 'correcting provenance re-derives authority')
139
+ })
140
+
123
141
  test('a derived fact_key is stored even without an explicit key', async () => {
124
142
  const { exec } = session('fact-derived')
125
143
  const { entry } = await memory.privateRemember({ exec, title: '窗台的绿萝', content: '窗台有一盆绿萝。' })
@@ -0,0 +1,27 @@
1
+ // 分词器的测试场景清单。
2
+ //
3
+ // 这些是测试语料,不是分词器的能力,所以它们住在 tests/ 而不是 lib/:
4
+ // 生产模块导出一份永远只有测试用的常量,等于给打包产物塞了一份无人使用的
5
+ // 字符串表,也让「lib 里每个 export 都有业务调用方」这条自查失效。
6
+
7
+ /**
8
+ * Test cases for different scenarios
9
+ */
10
+ export const TEST_CASES = [
11
+ {
12
+ input: '人工智能是一种技术',
13
+ description: '纯中文短句',
14
+ },
15
+ {
16
+ input: '2026-11-05 AI 技术在快速发展',
17
+ description: '混合日期、英文缩写和中文',
18
+ },
19
+ {
20
+ input: 'Qwen3-Embedding 在 2026 年发布',
21
+ description: '混合产品名、年份和中文',
22
+ },
23
+ {
24
+ input: 'user@example.com 访问 https://example.com',
25
+ description: '邮箱和 URL',
26
+ },
27
+ ]
@@ -81,6 +81,35 @@ test('deleteEntity deletes an unreferenced entity and refuses a referenced one u
81
81
  assert.equal(readStore().entities[kept.id], undefined)
82
82
  })
83
83
 
84
+ test('deleteEntity tolerates a corrupt relationship key and never loses a readable snapshot', () => {
85
+ const target = graph.createEntity({ libraryId, name: 'CorruptTarget' })
86
+ const other = graph.createEntity({ libraryId, name: 'CorruptOther' })
87
+ const outsider = graph.createEntity({ libraryId, name: 'CorruptOutsider' })
88
+ const targetKey = JSON.stringify([target.id, other.id])
89
+ const unrelatedKey = JSON.stringify([other.id, outsider.id])
90
+ const corruptKey = 'not-json\u0000relationship'
91
+ const store = readStore()
92
+ store.relationships[targetKey] = { fromId: target.id, toId: other.id, state: { trust: 0.5 }, history: [], evidenceIds: ['mem-free'] }
93
+ store.relationships[unrelatedKey] = { fromId: other.id, toId: outsider.id, state: { trust: 0.4 }, history: [], evidenceIds: ['mem-free'] }
94
+ store.relationships[corruptKey] = { fromId: 'x', toId: 'y', state: {}, history: [], evidenceIds: [] }
95
+ fs.writeFileSync(entitiesFile, JSON.stringify(store))
96
+ // 未 force:损坏 key 只是读不懂的历史,不能把「仍被引用」的拒绝变成 SyntaxError。
97
+ assert.throws(() => graph.deleteEntity({ libraryId, entityId: target.id }), /relationship snapshot/)
98
+ // force:只删除可读且真的指向 target 的快照;损坏 key 与无关好边原样保留。
99
+ const forced = graph.deleteEntity({ libraryId, entityId: target.id, force: true })
100
+ assert.equal(forced.removedRelationships, 1)
101
+ const after = readStore()
102
+ assert.equal(after.relationships[targetKey], undefined, 'the readable edge to the target is gone')
103
+ assert.ok(after.relationships[unrelatedKey], 'an unrelated readable edge is never silently dropped')
104
+ assert.ok(after.relationships[corruptKey], 'the corrupt key is preserved, not deleted as a side effect')
105
+ // 清理,避免坏 key 影响本文件后续的 prune/list 断言。
106
+ delete after.relationships[unrelatedKey]
107
+ delete after.relationships[corruptKey]
108
+ delete after.entities[other.id]
109
+ delete after.entities[outsider.id]
110
+ fs.writeFileSync(entitiesFile, JSON.stringify(after))
111
+ })
112
+
84
113
  test('force-delete drops relationship snapshots with the entity, and the freed endpoint is collectable', () => {
85
114
  const p = graph.createEntity({ libraryId, name: 'P' })
86
115
  const q = graph.createEntity({ libraryId, name: 'Q' })