dsh-memu-memory 1.2.9 → 1.3.1

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 (42) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/docs/memory-semantics.md +4 -3
  5. package/lib/binding-diagnostics.js +3 -3
  6. package/lib/client.js +23 -1
  7. package/lib/consolidation-ledger.js +41 -1
  8. package/lib/consolidation-receipt.js +122 -21
  9. package/lib/consolidation-worker.js +81 -25
  10. package/lib/curator.js +91 -11
  11. package/lib/engine.js +13 -3
  12. package/lib/graph.js +57 -21
  13. package/lib/inject.js +35 -15
  14. package/lib/media.js +8 -1
  15. package/lib/memory.js +16 -1
  16. package/lib/memu.js +19 -6
  17. package/lib/private.js +374 -22
  18. package/lib/prompts/global-curator.md +6 -3
  19. package/lib/prompts/private-consolidation.md +2 -2
  20. package/lib/prompts/private-consolidation.rp.md +3 -2
  21. package/lib/prompts/system-guide.md +4 -5
  22. package/lib/prompts.js +27 -1
  23. package/lib/rpc.js +2 -2
  24. package/lib/state.js +17 -3
  25. package/lib/tools.js +257 -127
  26. package/package.json +1 -1
  27. package/tests/consolidation-credential.test.mjs +2 -2
  28. package/tests/consolidation-fork.test.mjs +92 -15
  29. package/tests/consolidation-ledger.test.mjs +95 -3
  30. package/tests/consolidation-snapshot.test.mjs +30 -13
  31. package/tests/curator-probe.test.mjs +32 -2
  32. package/tests/graph.test.mjs +21 -0
  33. package/tests/inject-conflict.test.mjs +1 -1
  34. package/tests/inject.test.mjs +1 -1
  35. package/tests/injection-chain.test.mjs +4 -4
  36. package/tests/injection-rollback.test.mjs +1 -1
  37. package/tests/memory-chain.test.mjs +28 -0
  38. package/tests/mock-llm.test.mjs +1 -1
  39. package/tests/prompt-semantics.test.mjs +1 -1
  40. package/tests/prompts.test.mjs +1 -1
  41. package/tests/tool-schema.test.mjs +2 -1
  42. package/tests/tools.test.mjs +25 -3
@@ -10,7 +10,9 @@ 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
+ // 这些用例验证“路由继承”,不是推理强度;默认 medium 由 config 测试单独覆盖。
15
+ state.updateSettings({ consolidationReasoningEffort: 'inherit' })
14
16
 
15
17
  test.after(() => {
16
18
  forkModel.disposeConsolidationRoute()
@@ -431,7 +433,48 @@ test('a manual re-check starts at a complete turn instead of mid-step', () => {
431
433
  assert.equal(window.throughSeq, 4, 'the window ends on a closed turn')
432
434
  })
433
435
 
434
- test('the same failed snapshot stops re-forking after the failure cap', async () => {
436
+ test('must-cover candidates keep the high-signal turn and its seq range', () => {
437
+ const events = [
438
+ { seq: 0, type: 'turn/start', data: {} },
439
+ { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '说好周末拿给阿兰换伞骨,记得带过去。' }] } },
440
+ { seq: 2, type: 'turn/end', data: {} },
441
+ { seq: 3, type: 'turn/start', data: {} },
442
+ { seq: 4, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: '今天天气不错。' }] } },
443
+ { seq: 5, type: 'turn/end', data: {} },
444
+ ]
445
+ const rows = mustCoverCandidates(events, { max: 4 })
446
+ assert.equal(rows.length, 1, 'a low-signal turn is not a must-cover candidate')
447
+ assert.equal(rows[0].fromSeq, 0)
448
+ assert.equal(rows[0].throughSeq, 2)
449
+ assert.equal(rows[0].tag, '人物/关系')
450
+ assert.match(rows[0].text, /阿兰/)
451
+ })
452
+
453
+ test('mergeMustCover puts carried candidates first and reserves room for fresh ones', () => {
454
+ const carry = Array.from({ length: 6 }, (_, i) => ({ text: 'carry' + i, fromSeq: i, throughSeq: i, tag: '事实' }))
455
+ const fresh = Array.from({ length: 6 }, (_, i) => ({ text: 'fresh' + i, fromSeq: i, throughSeq: i, tag: '事实' }))
456
+ const merged = mergeMustCover(carry, fresh)
457
+ assert.equal(merged.length, 8)
458
+ assert.deepEqual(merged.slice(0, 4).map((row) => row.text), ['carry0', 'carry1', 'carry2', 'carry3'])
459
+ assert.deepEqual(merged.slice(4).map((row) => row.text), ['fresh0', 'fresh1', 'fresh2', 'fresh3'])
460
+ assert.ok(merged.slice(0, 4).every((row) => row.carried === true))
461
+ assert.equal(mergeMustCover([{ text: 'same' }], [{ text: 'same' }]).length, 1, 'duplicates are dropped')
462
+ })
463
+
464
+ test('a candidate is covered only when a written entry carries the fact', () => {
465
+ const index = {
466
+ entries: {
467
+ 'mem-1': { title: '楼下修伞的阿兰', content: '说好周末拿折伞给她换伞骨,布不用动。' },
468
+ 'mem-2': { title: '同事叶楠生日是八月十八号', content: '叶楠生日八月十八号。' },
469
+ },
470
+ }
471
+ assert.equal(candidateCovered({ text: '说好周末拿给阿兰换伞骨' }, ['mem-1'], index), true)
472
+ assert.equal(candidateCovered({ text: '叶楠生日八月十八号' }, ['mem-2'], index), true)
473
+ assert.equal(candidateCovered({ text: '父亲不吃芹菜' }, ['mem-1'], index), false)
474
+ assert.equal(candidateCovered({ text: '父亲不吃芹菜' }, [], index), false, 'no writes means no coverage')
475
+ })
476
+
477
+ test('the same failed snapshot stops automatic re-forking after the failure cap', async () => {
435
478
  state.ensureSession('fork-failcap', { cwd: path.join(home, 'proj-failcap'), agentPreset: 'coding' })
436
479
  const ctx = host({ live: true, turnReason: { kind: 'error', error: { message: 'provider refused' } } })
437
480
  const first = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
@@ -439,10 +482,15 @@ test('the same failed snapshot stops re-forking after the failure cap', async ()
439
482
  assert.equal(first.ok, false)
440
483
  assert.equal(second.ok, false)
441
484
  assert.equal(ctx.rec.created.length, 2, 'two real attempts happen')
442
- const third = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
485
+ // 自动路径仍然受上限约束:同一快照连续失败 2 次后不再付第三次 fork 成本。
486
+ const third = await requestPrivateConsolidation(ctx, 'fork-failcap')
443
487
  assert.equal(third.ok, true)
444
488
  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')
489
+ assert.equal(ctx.rec.created.length, 2, 'the automatic call does not pay for the same snapshot again')
490
+ // 手动整理是明确的一次再决定:force 不受上限约束(否则冻结回放/用户重试会被永久卡住)。
491
+ const forcedAgain = await requestPrivateConsolidation(ctx, 'fork-failcap', { force: true })
492
+ assert.equal(forcedAgain.ok, false)
493
+ assert.equal(ctx.rec.created.length, 3, 'a manual retry is allowed past the cap')
446
494
  })
447
495
 
448
496
  // ---------------------------------------------------------------- PTC 兼容
@@ -478,16 +526,16 @@ test('a PTC session (run_code only header) is consolidated and the worker gets w
478
526
  assert.equal(result.ok, true, 'a run_code header must not block consolidation: ' + String(result.error || ''))
479
527
  assert.equal(result.settled, true)
480
528
  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'])
529
+ // 只挂 worker 真正用到的读写面(remember/update/link_suggest/list/recall/status);
530
+ // lexicon、private_link、archive/delete/unpin 这些用不到或破坏性的工具不进 worker 面。
531
+ assert.deepEqual([...registered].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
484
532
  // 整理结束(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'])
533
+ assert.deepEqual([...disposals].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
486
534
  // 全量挂载的活动元数据:attached=实际子集(此处=完整 wanted)、requested=完整 wanted、
487
535
  // partial=false。三件一起钉住"成功路径不再含糊"。
488
536
  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'])
537
+ assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
538
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
491
539
  assert.equal(started.detail.workerToolsPartial, false, 'a full mount is not partial')
492
540
  const followup = ctx.rec.forkFollowups[0]?.message
493
541
  const brief = Array.isArray(followup?.content)
@@ -529,14 +577,14 @@ test('a host registry refusing one write tool leaves a structured partial mount
529
577
  const result = await requestPrivateConsolidation(ctx, 'fork-ptc-partial')
530
578
  assert.equal(result.ok, true, String(result.error || ''))
531
579
  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'],
580
+ assert.deepEqual([...registered].sort(), ['memu_private_remember_batch', 'memu_private_update'],
533
581
  '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'],
582
+ assert.deepEqual([...disposals].sort(), ['memu_private_remember_batch', 'memu_private_update'],
535
583
  'dispose unmounts exactly what was mounted')
536
584
  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'],
585
+ assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_remember_batch', 'memu_private_update'],
538
586
  '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'])
587
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
540
588
  assert.equal(started.detail.workerToolsPartial, true)
541
589
  // 挂载为部分子集时任务书仍带 PTC 调用形态:worker 知道写记忆走 run_code 的 SDK 绑定。
542
590
  const followup = ctx.rec.forkFollowups[0]?.message
@@ -557,7 +605,7 @@ test('a fork context without a tools service records a null mount, the request a
557
605
  assert.equal(result.ok, true, String(result.error || ''))
558
606
  const started = startedEntryFor(ctx, 'fork-ptc-notools')
559
607
  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'])
608
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
561
609
  assert.equal(started.detail.workerToolsPartial, true)
562
610
  })
563
611
 
@@ -694,3 +742,32 @@ test('a bad host consolidationModel is refused with its own reason, not the pare
694
742
  restoreSettings()
695
743
  }
696
744
  })
745
+
746
+ test('compactSeedEvents accepts the catalog and local recall as two read-only preludes', () => {
747
+ const user = {
748
+ seq: 10,
749
+ type: 'user/message',
750
+ time: 1,
751
+ sceneTime: '2026-11-06T04:00:00+08:00',
752
+ data: { source: { kind: 'user' }, content: [{ type: 'text', text: '明天码头见' }] },
753
+ }
754
+ const catalog = {
755
+ seq: 0,
756
+ type: 'user/message',
757
+ time: 1,
758
+ data: { source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-catalog' }, content: [{ type: 'text', text: '[memory-catalog]' }] },
759
+ }
760
+ const recall = {
761
+ seq: 0,
762
+ type: 'user/message',
763
+ time: 1,
764
+ data: { source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-recall' }, content: [{ type: 'text', text: '[memory-recall] [mem-1] 码头' }] },
765
+ }
766
+ const seed = compactSeedEvents([user], [catalog, recall])
767
+ assert.equal(seed.length, 3)
768
+ assert.deepEqual(seed.map((event) => event.seq), [0, 1, 2])
769
+ assert.equal(seed[0].data.source.summary, 'memory-catalog')
770
+ assert.equal(seed[1].data.source.summary, 'memory-recall')
771
+ assert.equal(seed[2].type, 'user/message')
772
+ assert.match(seed[2].data.content[0].text, /事件时间/)
773
+ })
@@ -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', () => {
@@ -285,6 +328,37 @@ test('decideCompletion: proof advances, guesswork does not', () => {
285
328
  assert.equal(silent.reasonCode, 'receipt-missing')
286
329
  })
287
330
 
331
+ test('auto receipt synthesizes a verified receipt from the library diff', () => {
332
+ const autoReceipt = { jobId: 'cons-auto-1', snapshotHash: 'a'.repeat(64), checkedRange: { fromSeq: 0, throughSeq: 9 } }
333
+ const index = { entries: { 'mem-7': { status: 'active', content: 'new' } } }
334
+ const created = receipt.decideCompletion({
335
+ text: '整理完成,新增一条。', wrote: 1, index, beforeIds: new Set(), autoReceipt,
336
+ })
337
+ assert.equal(created.advance, true)
338
+ assert.equal(created.outcome, 'created')
339
+ assert.deepEqual(created.counted, { created: 1, updated: 0, held: 0 })
340
+ assert.equal(created.receipt.jobId, 'cons-auto-1')
341
+ assert.equal(created.receipt.checkedRange.throughSeq, 9)
342
+
343
+ const none = receipt.decideCompletion({
344
+ text: '这窗没有值得新增的内容。', wrote: 0, index: { entries: {} }, beforeIds: new Set(), autoReceipt,
345
+ })
346
+ assert.equal(none.advance, true)
347
+ assert.equal(none.outcome, 'no_value')
348
+
349
+ const unavailable = receipt.decideCompletion({
350
+ text: 'tools-unavailable: 没有写记忆工具。', wrote: 0, index: { entries: {} }, beforeIds: new Set(), autoReceipt,
351
+ })
352
+ assert.equal(unavailable.advance, false)
353
+ assert.equal(unavailable.reasonCode, 'tools-unavailable')
354
+
355
+ const silent = receipt.decideCompletion({
356
+ text: '', wrote: 0, index: { entries: {} }, beforeIds: new Set(), autoReceipt,
357
+ })
358
+ assert.equal(silent.advance, false)
359
+ assert.equal(silent.reasonCode, 'receipt-missing')
360
+ })
361
+
288
362
  test('decideCompletion never settles a silent worker on its own', () => {
289
363
  // 结算空正文的规则已经上移到 private.js 的调用点:那里知道「worker 一个字没说、库里也没
290
364
  // 多出条目」这一种情形(见 tests/consolidation-fork.test.mjs 与 tests/cycle.test.mjs)。
@@ -295,4 +369,22 @@ test('decideCompletion never settles a silent worker on its own', () => {
295
369
  const unattributed = receipt.decideCompletion({ text: '', wrote: 2 })
296
370
  assert.equal(unattributed.advance, false)
297
371
  assert.match(unattributed.error, /receipt|cannot settle/i)
372
+ })
373
+
374
+ test('carry candidates survive the ledger round-trip and stay bounded', () => {
375
+ ledger.setCarryCandidates('carry-1', [
376
+ { fromSeq: 1080, throughSeq: 1085, tag: '人物/关系', text: '说好周末拿给阿兰换伞骨', observedAt: '2026-05-17T12:00:00+08:00' },
377
+ { fromSeq: 1152, throughSeq: 1163, tag: '人物/关系', text: '普法折页:小圆先登记,后换阿梁接手' },
378
+ ])
379
+ const rows = ledger.readCarryCandidates('carry-1')
380
+ assert.equal(rows.length, 2)
381
+ assert.deepEqual(rows[0], {
382
+ fromSeq: 1080, throughSeq: 1085, score: 0, tag: '人物/关系',
383
+ text: '说好周末拿给阿兰换伞骨', observedAt: '2026-05-17T12:00:00+08:00',
384
+ })
385
+ const many = Array.from({ length: 12 }, (_, i) => ({ text: '候选 ' + i }))
386
+ ledger.setCarryCandidates('carry-1', many)
387
+ assert.equal(ledger.readCarryCandidates('carry-1').length, ledger.CARRY_LIMIT, 'the carry list is capped')
388
+ ledger.setCarryCandidates('carry-1', [])
389
+ assert.deepEqual(ledger.readCarryCandidates('carry-1'), [], 'a covered window clears the carry')
298
390
  })
@@ -281,23 +281,21 @@ 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 direct writes with the injected catalog and the receipt buckets', () => {
285
285
  const brief = buildWorkerBrief({
286
286
  snapshot: { fromSeq: 0, throughSeq: 5, eventCount: 6, hash: 'brief01' },
287
- probe: { tools: ['memu_private_remember', 'memu_private_update', 'memu_private_link_suggest', 'memu_lexicon_propose'] },
287
+ probe: { tools: ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'] },
288
288
  contract: 'BRIEF-CONTRACT',
289
289
  })
290
- assert.match(brief, /memu_private_link_suggest\(\{ids:\[\.\.\.\]\}\)/, 'the call shape is spelled out')
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/)
290
+ assert.match(brief, /memu_private_remember_batch\(\{items:\[\.\.\.\]\}\)/, 'the batch call shape is spelled out')
291
+ assert.match(brief, /目录和召回命中已经给出/, 'catalog and local recall replace the read round')
292
+ assert.match(brief, /不要再检索/, 'the worker must not open a list/recall round')
293
+ assert.match(brief, /总数仍不超过 8 条/)
294
+ assert.doesNotMatch(brief, /heldIds/, 'the auto receipt owns the id buckets')
295
+ assert.doesNotMatch(brief, /memu_private_link_suggest|memu_private_recall|memu_private_list/)
296
+ assert.doesNotMatch(brief, /memu_lexicon|term 是索引键|sensitive trigger/)
299
297
  assert.match(brief, /tools-unavailable/, 'the tools-unavailable contract survives')
300
- assert.match(brief, /没有回执视为本次整理失败/, 'the receipt requirement survives')
298
+ assert.match(brief, /没有回执视为本次整理失败/, 'the receipt requirement survives when auto receipt is off')
301
299
  assert.match(brief, /BRIEF-CONTRACT/)
302
300
  })
303
301
 
@@ -346,7 +344,7 @@ test('a mixed surface (run_code beside native memu_*) proves write ability and k
346
344
  probe,
347
345
  contract: 'MIXED-CONTRACT',
348
346
  })
349
- assert.match(brief, /run_code, memu_private_remember, memu_private_update/, 'the brief lists the native names')
347
+ assert.match(brief, /memu_private_remember, memu_private_update/, 'the brief lists the allowed native names')
350
348
  assert.match(brief, /await tools\.memu_private_remember/, 'the brief keeps the PTC SDK invocation shape on a mixed surface')
351
349
  assert.match(brief, /MIXED-CONTRACT/)
352
350
  })
@@ -396,4 +394,23 @@ test('the worker brief carries the range, the tools and the receipt contract', (
396
394
  assert.match(brief, /RECEIPT-CONTRACT-MARKER/)
397
395
  assert.match(brief, /手动/)
398
396
  assert.match(brief, /tools-unavailable/)
397
+ })
398
+
399
+ test('the worker brief renders the must-cover checklist with seq ranges', () => {
400
+ const brief = buildWorkerBrief({
401
+ snapshot: { fromSeq: 998, throughSeq: 1211, eventCount: 214, hash: 'opt6' },
402
+ probe: { tools: ['memu_private_remember'] },
403
+ contract: '',
404
+ mustCover: [
405
+ { fromSeq: 1080, throughSeq: 1085, tag: '人物/关系', text: '说好周末拿给阿兰换伞骨' },
406
+ { fromSeq: 1152, throughSeq: 1157, tag: '人物/关系', text: '普法折页,小圆负责入口登记' },
407
+ { fromSeq: 0, throughSeq: 0, tag: '事实', text: '父亲不吃芹菜', carried: true, observedAt: '2026-05-17T12:00:00+08:00' },
408
+ ],
409
+ })
410
+ assert.match(brief, /本窗必写候选/)
411
+ assert.match(brief, /第 1080–1085 条 · 人物\/关系/)
412
+ assert.match(brief, /阿兰/)
413
+ assert.match(brief, /小圆负责入口登记/)
414
+ assert.match(brief, /顺延 · 事件时间 2026-05-17/)
415
+ assert.match(brief, /来自之前窗口/)
399
416
  })
@@ -188,8 +188,8 @@ function ctxFor(events, onActivation) {
188
188
  }
189
189
 
190
190
  function promptInput(prompt) {
191
- // The template ends with the pretty-printed JSON input.
192
- const start = prompt.lastIndexOf('{\n "sessions"')
191
+ // The template ends with the compact JSON input (C2 no longer pretty-prints).
192
+ const start = prompt.lastIndexOf('{"sessions"')
193
193
  assert.ok(start >= 0, 'the curator prompt should embed the JSON input')
194
194
  return JSON.parse(prompt.slice(start))
195
195
  }
@@ -242,6 +242,36 @@ test('condenseEvents keeps user/assistant/tool shapes and drops every plugin mes
242
242
  assert.ok(!transcript.includes(M.toolTail), 'tool results are cut at 400 chars')
243
243
  })
244
244
 
245
+ test('condenseEvents prefers tool/call events over duplicated assistant tool-call blocks', () => {
246
+ const marker = 'TOOLCALL-DEDUPE-1f9c'
247
+ const args = JSON.stringify({ query: marker })
248
+ const byId = condenseEvents([
249
+ { type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', id: 'call-1', name: 'memu_private_recall', arguments: args }] } } },
250
+ { type: 'tool/call', data: { callId: 'call-1', name: 'memu_private_recall', arguments: args } },
251
+ ])
252
+ assert.equal((byId.match(new RegExp(marker, 'g')) || []).length, 1, 'callId pairs the block with its event')
253
+ const bySignature = condenseEvents([
254
+ { type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', name: 'some_tool', arguments: '{"v":1}' }] } } },
255
+ { type: 'tool/call', data: { name: 'some_tool', arguments: '{"v":1}' } },
256
+ ])
257
+ assert.equal((bySignature.match(/Tool call:/g) || []).length, 1, 'without ids, name+arguments pairs the block')
258
+ const unpaired = condenseEvents([
259
+ { type: 'assistant/message', data: { message: { content: [{ type: 'tool-call', id: 'call-2', name: 'some_tool', arguments: '{"v":2}' }] } } },
260
+ ])
261
+ assert.match(unpaired, /Tool call: some_tool/, 'a block with no matching event stays')
262
+ })
263
+
264
+ test('condenseEvents stops at the token budget while keeping the first line', () => {
265
+ const events = Array.from({ length: 100 }, (_, i) => ({
266
+ type: 'user/message',
267
+ data: { source: { kind: 'user' }, content: [{ type: 'text', text: `LINE-${i} ` + '长'.repeat(20) }] },
268
+ }))
269
+ const text = condenseEvents(events, 200000, { maxTokens: 20 })
270
+ assert.match(text, /truncated .* over token budget 20/)
271
+ assert.match(text, /LINE-0/)
272
+ assert.doesNotMatch(text, /LINE-99/)
273
+ })
274
+
245
275
  test('six channels, layer by layer: transcript -> prompt -> simulated output -> committed index', async (t) => {
246
276
  seedGlobalIndex()
247
277
  const events = probeEvents()
@@ -200,6 +200,27 @@ test('listEntities: without a session every entity returns, with a correct deriv
200
200
  assert.equal(graph.graphExport(lib).entities[drifting.id].linked, undefined, 'the derived flag is never written back')
201
201
  })
202
202
 
203
+ test('recallRelations reuses its inverted index until the index file changes', () => {
204
+ const binding = state.ensureSession('graph-cache', { cwd: path.join(home, 'rp-cache'), agentPreset: 'rp' })
205
+ const lib = binding.libraryId
206
+ const entity = graph.createEntity({ libraryId: lib, name: 'CacheEntity' })
207
+ state.savePrivateIndex(lib, { entries: {
208
+ 'mem-cache-a': { title: 'a', content: 'a', status: 'active', visibility: 'shared',
209
+ links: [{ to: entity.id, kind: 'person', note: 'CacheEntity is the person in this scene.', confidence: 0.8 }] },
210
+ } })
211
+ const first = graph.recallRelations(lib, state.loadPrivateIndex(lib), 'mem-cache-a', null)
212
+ const second = graph.recallRelations(lib, state.loadPrivateIndex(lib), 'mem-cache-a', null)
213
+ assert.deepEqual(second, first, 'an unchanged index returns the same edges')
214
+ state.updatePrivateIndex(lib, index => {
215
+ index.entries['mem-cache-b'] = { title: 'b', content: 'b', status: 'active', visibility: 'shared',
216
+ links: [{ to: 'mem-cache-a', kind: 'event', note: 'The same event seen from another side.', confidence: 0.9 }] }
217
+ })
218
+ const refreshed = graph.recallRelations(lib, state.loadPrivateIndex(lib), 'mem-cache-a', null)
219
+ assert.equal(refreshed.length, 2, 'a new index write invalidates the cached inverted index')
220
+ assert.ok(refreshed.some(item => item.id === 'mem-cache-b'))
221
+ assert.ok(refreshed.some(item => item.id === entity.id))
222
+ })
223
+
203
224
  test('listEntities: with a session only visible references count, and relationship evidence is session-filtered too', () => {
204
225
  const binding = state.ensureSession('vis-scoped', { cwd: path.join(home, 'ws-vis-scoped'), agentPreset: 'rp' })
205
226
  const lib = binding.libraryId
@@ -102,7 +102,7 @@ test('a conflict card that cannot fit falls back to the ordinary title cards', a
102
102
  const binding = state.getSessionBinding(sessionId)
103
103
  // The card's fact_key + two long titles cannot fit; a one-line title card still can.
104
104
  const build = await inject.buildRecall(binding, '旅行目的地', 1, {
105
- ...state.getSettings(), privateTopK: 5, relevanceThreshold: 0, turnTokens: 150,
105
+ ...state.getSettings(), privateTopK: 5, relevanceThreshold: 0, turnTokens: 110,
106
106
  }, exec, sessionId)
107
107
  assert.deepEqual(build.errors, [])
108
108
  assert.equal(build.text.includes('冲突 ·'), false)
@@ -238,7 +238,7 @@ test('buildRecall injects the title card, not the body', async () => {
238
238
  assert.ok(recall.ids.includes('mem-recall-title'))
239
239
  assert.ok(recall.text.includes('部署脚本的位置'), 'the title is the card')
240
240
  assert.ok(recall.text.includes('[mem-recall-title]'), 'the id stays quotable')
241
- assert.match(recall.text, /条目是标题卡/, 'the block tells the model how to use a title card')
241
+ assert.match(recall.text, /标题卡/, 'the block tells the model how to use a title card')
242
242
  assert.ok(recall.text.includes('memu_private_recall'), 'and which tool returns the body')
243
243
  assert.equal(recall.text.includes('RECALL-BODY-ONLY'), false,
244
244
  'memu_private_recall still returns full text; the turn block does not')
@@ -187,8 +187,8 @@ test('every consolidation prompt tells the model how to write the field', () =>
187
187
 
188
188
  test('the remember tool tells the model to resolve a relative day', () => {
189
189
  const source = fs.readFileSync(fileURLToPath(new URL('../lib/tools.js', import.meta.url)), 'utf8')
190
- assert.ok(source.includes('A relative day'), 'the tool description must mention relative days')
191
- assert.ok(source.includes('turns one appointment into a yearly reminder'), 'and why it matters')
190
+ assert.ok(source.includes('Resolve 今天/明天/下周 to the absolute date'), 'the tool description must mention relative days')
191
+ assert.ok(source.includes('never send a bare MM-DD for a one-off'), 'and why it matters')
192
192
  })
193
193
 
194
194
  // ------------------------------------- D: freshness hint is conditional and bounded
@@ -240,7 +240,7 @@ test('a stale recalled memory appends exactly one freshness hint after the close
240
240
  assert.ok(recall.ids.includes('mem-fresh-deploy'))
241
241
  assert.ok(recall.ids.includes('mem-fresh-release'))
242
242
  assert.equal((recall.text.match(/<memory-freshness>/g) || []).length, 1, 'the hint appears exactly once')
243
- assert.ok(recall.text.includes('上面有 2 条记忆带时间敏感信号'), 'N counts the unique stale entries')
243
+ assert.ok(recall.text.includes('2 条可能过时'), 'N counts the unique stale entries')
244
244
  assert.ok(recall.text.indexOf('<memory-freshness>') > recall.text.lastIndexOf('</memory-context>'),
245
245
  'the hint follows the last closed context block')
246
246
  assert.equal((recall.text.match(/<memory-context\b/g) || []).length, 1, 'recall still has one context block')
@@ -343,7 +343,7 @@ test('the hint is dropped when turnTokens cannot fit it, and the recall still su
343
343
 
344
344
  // The smallest budget that still fits the card cannot also fit the footnote.
345
345
  let squeezed = null
346
- for (let extra = 0; extra <= 12 && !squeezed; extra += 1) {
346
+ for (let extra = 0; extra <= 40 && !squeezed; extra += 1) {
347
347
  const turnTokens = needed + extra
348
348
  const attempt = await recallFor('chain-freshness-budget', binding, '部署脚本放在哪里', { turnTokens })
349
349
  if (attempt.text) squeezed = { attempt, turnTokens }
@@ -82,7 +82,7 @@ const facts = (id) => {
82
82
  const binding = state.getSessionBinding(id) || {}
83
83
  return {
84
84
  guide: binding.guideRulesKey || null,
85
- anchor: (binding.injectedIds || []).includes(inject.ANCHOR_SENTINEL),
85
+ anchor: binding.anchorPushed === true || (binding.injectedIds || []).includes(inject.ANCHOR_SENTINEL),
86
86
  rollback: binding.injectionRollback || null,
87
87
  injected: (binding.injectedIds || []).filter((entry) => entry !== inject.ANCHOR_SENTINEL).length,
88
88
  }
@@ -11,6 +11,7 @@ const { registerTools } = await import('../lib/tools.js')
11
11
  const state = await import('../lib/state.js')
12
12
  const inject = await import('../lib/inject.js')
13
13
  const { dispatch } = await import('../lib/rpc.js')
14
+ const { memoryRecallEvent } = await import('../lib/private.js')
14
15
 
15
16
  test.after(() => {
16
17
  try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
@@ -138,3 +139,30 @@ test('the real tool → recall → injection chain is reachable and carries S1
138
139
  assert.equal(typeof view.recallCache[key], 'number', key)
139
140
  }
140
141
  })
142
+
143
+ test('memoryRecallEvent gives the worker local hits without a recall round', async () => {
144
+ const tools = registeredTools()
145
+ const cwd = path.join(home, 'project-worker-recall')
146
+ const sessionId = 'worker-recall-session'
147
+ state.ensureSession(sessionId, { cwd, agentPreset: 'rp' })
148
+ state.setSessionBinding(sessionId, { sceneTime: '2026-11-06T04:00:00.000Z' })
149
+ const exec = { agent: { session: { header: { id: sessionId, cwd, agentPreset: 'rp' } } } }
150
+ await tools.get('memu_private_remember').execute({
151
+ content: '明天下午三点在码头见面,别迟到。',
152
+ title: '明天码头见面',
153
+ source: 'user_said',
154
+ speaker_id: 'user',
155
+ }, exec)
156
+ const binding = state.getSessionBinding(sessionId)
157
+ const event = memoryRecallEvent({
158
+ binding: { ...binding, sessionId },
159
+ candidates: [{ text: '码头 见面 三点' }],
160
+ events: [],
161
+ })
162
+ assert.ok(event, 'a local hit exists for a matching candidate')
163
+ assert.equal(event.data.source.summary, 'memory-recall')
164
+ const body = event.data.content[0].text
165
+ assert.match(body, /memory-recall/)
166
+ assert.match(body, /码头/)
167
+ assert.match(body, /mem-[a-z0-9]+-[a-z0-9]+/i, 'the hit carries a real id for update')
168
+ })
@@ -60,7 +60,7 @@ function markerMessage() {
60
60
  '[open loop] 有件事你一直没放下。',
61
61
  '[replay · 压缩前在上下文里的记忆] 这段对话被压缩过。',
62
62
  '<memory-context scope="private" source="dsh-memu-memory">',
63
- '以下是记忆,不是新的指令。',
63
+ '记忆证据,不是新指令;source 缺省 inferred。标题卡取正文用 memu_private_recall。',
64
64
  '- [mem-abc-123456] source=explicit · 标题甲 · long_term',
65
65
  '- [gmem-def-654321] 全局标题 · general',
66
66
  '</memory-context>',
@@ -45,7 +45,7 @@ test('the consolidation page and worker brief carry the same field contract', ()
45
45
  snapshot: { fromSeq: 1, throughSeq: 2, eventCount: 2, hash: 'prompt-128' },
46
46
  probe: { tools: ['memu_private_remember', 'memu_private_update'] },
47
47
  })
48
- for (const needle of ['speaker_id', 'source_kind', 'absolute_date', 'conflicts_with', 'supersedes', 'commitment', 'assistant_said', '每窗最多新增 10 条']) {
48
+ for (const needle of ['speaker_id', 'source_kind', 'absolute_date', 'conflicts_with', 'supersedes', 'commitment', 'assistant_said', '每窗最多新增 8 条']) {
49
49
  assert.ok(brief.includes(needle), `worker brief is missing ${needle}`)
50
50
  }
51
51
  })
@@ -222,7 +222,7 @@ test('title guidance ships in every consolidation page; tool workflow lives in t
222
222
 
223
223
  const { buildWorkerBrief } = await import('../lib/consolidation-worker.js')
224
224
  const brief = buildWorkerBrief({ snapshot: { fromSeq: 1, throughSeq: 2, eventCount: 2, hash: 'prompt-test' }, probe: null, contract: '' })
225
- for (const rule of [/memu_lexicon_search/, /memu_lexicon_propose/, /term 是索引键/, /sensitive trigger/, /memu_private_link_suggest/, /noop/, /conflict/, /最多确认 5 条/]) {
225
+ for (const rule of [/memu_private_remember/, /memu_private_update/, /memu_private_remember_batch/, /总数仍不超过 8 条/]) {
226
226
  assert.match(brief, rule, 'the local worker brief owns the tool workflow')
227
227
  }
228
228
  assert.match(prompts.CONSOLIDATION_CONTRACTS.remote, /8-40字/, 'the remote JSON contract uses the same title length')
@@ -68,6 +68,7 @@ test('the shipped tool surface compiles under the host rules', async () => {
68
68
  tools: { register: (tool) => { registered.push(tool.name); return () => {} } },
69
69
  logger: { warn: (message) => { throw new Error(`unexpected registration warning: ${message}`) } },
70
70
  })
71
- assert.equal(registered.length, 13, `registered ${registered.join(', ')}`)
71
+ assert.equal(registered.length, 14, `registered ${registered.join(', ')}`)
72
+ assert.ok(registered.includes('memu_private_remember_batch'), 'the batch write tool compiles under the host rules')
72
73
  dispose()
73
74
  })
@@ -41,6 +41,7 @@ test('all v1 tools register', () => {
41
41
  'memu_private_link',
42
42
  'memu_private_link_suggest',
43
43
  'memu_private_remember',
44
+ 'memu_private_remember_batch',
44
45
  'memu_private_recall',
45
46
  'memu_private_list',
46
47
  'memu_private_update',
@@ -54,10 +55,31 @@ test('all v1 tools register', () => {
54
55
  ]) {
55
56
  assert.ok(names.includes(name), `missing ${name}`)
56
57
  }
57
- // Exactly thirteen, not "at least these twelve": a schema the host DSL refuses used to
58
+ // Exactly fourteen, not "at least these": a schema the host DSL refuses used to
58
59
  // abort registerTools() before any register() ran, so counting is the assertion
59
60
  // that actually catches a total registration failure.
60
- assert.equal(names.length, 13, `expected 13 tools, got ${names.length}: ${names.join(', ')}`)
61
+ assert.equal(names.length, 14, `expected 14 tools, got ${names.length}: ${names.join(', ')}`)
62
+ dispose()
63
+ })
64
+
65
+ test('batch write applies shared defaults and reports each item', async () => {
66
+ const { tools, dispose } = fakeCtx()
67
+ const batch = tools.find((t) => t.name === 'memu_private_remember_batch')
68
+ const batchExec = {
69
+ agent: { session: { header: { id: 'tools-batch-session', cwd: path.join(home, 'project-batch'), agentPreset: 'coding' } } },
70
+ }
71
+ const reply = await batch.execute({
72
+ defaults: { speaker_id: 'user', source: 'user_said', observed_at: '2026-11-06T04:00:00+08:00' },
73
+ items: [
74
+ { title: '码头见面', content: '明天下午三点在码头见面,别迟到。' },
75
+ { title: '带伞', content: '她说码头风大,让我带把伞。' },
76
+ ],
77
+ }, batchExec)
78
+ assert.match(reply, /批量写入完成:新增 2/)
79
+ assert.match(reply, /1\. 已写入私有记忆/)
80
+ assert.match(reply, /2\. 已写入私有记忆/)
81
+ const empty = await batch.execute({ items: [] }, batchExec)
82
+ assert.match(empty, /items 为空/)
61
83
  dispose()
62
84
  })
63
85
 
@@ -68,7 +90,7 @@ test('status works without an engine', async () => {
68
90
  assert.match(status, /library:/)
69
91
  // The registration count is the visible signal for a refused schema: without it
70
92
  // a host that rejects the tool and a plugin that never had it look identical.
71
- assert.match(status, /tools: 13\/13 registered/)
93
+ assert.match(status, /tools: 14\/14 registered/)
72
94
  dispose()
73
95
  })
74
96