dsh-memu-memory 1.3.0 → 1.3.2

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 (67) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -1
  4. package/docs/contributing.md +2 -2
  5. package/docs/env-and-commands.md +12 -1
  6. package/docs/memory-semantics.md +8 -2
  7. package/docs/troubleshooting.md +9 -6
  8. package/lib/auto-link/apply.js +249 -0
  9. package/lib/auto-link/candidates.js +155 -0
  10. package/lib/auto-link/decide.js +304 -0
  11. package/lib/auto-link/normalize.js +99 -0
  12. package/lib/auto-link/policy.js +42 -0
  13. package/lib/auto-link/suppression.js +101 -0
  14. package/lib/auto-link/terminology.js +265 -0
  15. package/lib/binding-diagnostics.js +3 -3
  16. package/lib/client.js +1435 -70
  17. package/lib/consolidation-receipt.js +81 -5
  18. package/lib/consolidation-worker.js +57 -25
  19. package/lib/curator.js +91 -11
  20. package/lib/engine.js +13 -3
  21. package/lib/graph.js +326 -39
  22. package/lib/inject.js +35 -15
  23. package/lib/media.js +8 -1
  24. package/lib/memory.js +27 -1
  25. package/lib/memu.js +26 -12
  26. package/lib/private-links.js +105 -137
  27. package/lib/private.js +280 -53
  28. package/lib/prompts/global-curator.md +6 -3
  29. package/lib/prompts/system-guide.md +4 -5
  30. package/lib/prompts.js +27 -1
  31. package/lib/rpc.js +69 -9
  32. package/lib/state.js +23 -4
  33. package/lib/tools.js +199 -67
  34. package/lib/webui/graph-LICENSE.txt +1 -62
  35. package/lib/webui/graph-view.bundle.js +1 -1
  36. package/lib/webui/graph-view.js +891 -124
  37. package/lib/webui/standalone.js +3 -3
  38. package/package.json +1 -2
  39. package/scripts/build-graph.mjs +3 -3
  40. package/scripts/check-graph-browser.mjs +106 -23
  41. package/scripts/rebuild-auto-links.mjs +252 -0
  42. package/tests/audit-regression.test.mjs +11 -8
  43. package/tests/auto-link-candidates.test.mjs +161 -0
  44. package/tests/auto-link-decide.test.mjs +512 -0
  45. package/tests/auto-link-migration.test.mjs +133 -0
  46. package/tests/client-render.test.mjs +7 -6
  47. package/tests/consolidation-credential.test.mjs +2 -2
  48. package/tests/consolidation-fork.test.mjs +188 -9
  49. package/tests/consolidation-ledger.test.mjs +31 -0
  50. package/tests/consolidation-snapshot.test.mjs +9 -8
  51. package/tests/curator-probe.test.mjs +32 -2
  52. package/tests/cycle.test.mjs +1 -1
  53. package/tests/graph-view.test.mjs +163 -21
  54. package/tests/graph.test.mjs +26 -0
  55. package/tests/help-page.test.mjs +3 -3
  56. package/tests/inject-conflict.test.mjs +1 -1
  57. package/tests/inject.test.mjs +1 -1
  58. package/tests/injection-chain.test.mjs +2 -2
  59. package/tests/injection-rollback.test.mjs +1 -1
  60. package/tests/memory-chain.test.mjs +28 -0
  61. package/tests/memu-resident-route.test.mjs +130 -0
  62. package/tests/mock-llm.test.mjs +1 -1
  63. package/tests/private-links.test.mjs +81 -45
  64. package/tests/prompts.test.mjs +1 -1
  65. package/tests/stubs/child-process-spy.mjs +14 -0
  66. package/tests/tool-schema.test.mjs +2 -1
  67. package/tests/tools.test.mjs +49 -21
@@ -212,14 +212,15 @@ test('the settings page renders every page instead of a blank panel', async () =
212
212
  await new Promise((resolve) => setTimeout(resolve, 0))
213
213
  await new Promise((resolve) => setTimeout(resolve, 0))
214
214
 
215
- for (let page = 0; page < 12; page++) {
215
+ // 13 页(含新增的关系图谱 graph:10);help 仍是最后一页,未纳入这轮巡检。
216
+ for (let page = 0; page < 13; page++) {
216
217
  const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, page)
217
218
  const text = treeText(tree)
218
219
  assert.match(String(tree.props?.className), /dshm-root/, `page ${page} did not render the shell`)
219
220
  // The rail is the nav: every page label has to be there. Counting the shared
220
221
  // dshm-nav-item class instead would also pick up the in-page tab strips (memory
221
222
  // backend, prompt scope, browser view), which use the same widget on purpose.
222
- const NAV = ['pageOverview', 'pageConnection', 'pageSettings', 'pageFolders', 'pageLibraries', 'pageBrowser', 'pageGlobal', 'pagePrompts', 'pageStats', 'pageMemories', 'pageLogs', 'pageLexicon']
223
+ const NAV = ['pageOverview', 'pageConnection', 'pageSettings', 'pageFolders', 'pageLibraries', 'pageBrowser', 'pageGlobal', 'pagePrompts', 'pageStats', 'pageMemories', 'pageGraph', 'pageLogs', 'pageLexicon']
223
224
  assert.ok(NAV.every((key) => text.includes(key)), `page ${page} lost a nav entry`)
224
225
  assert.equal((text.match(/dshm-nav-ind/g) || []).length, 1, `page ${page} lost or duplicated its rail indicator`)
225
226
  assert.match(text, /dshm-page/, `page ${page} lost the content pane`)
@@ -938,10 +939,10 @@ test('failed and degraded activity rows are visually distinguished from normal r
938
939
  collectPageHook()
939
940
  for (const effect of first.effects) effect.fn()
940
941
  await new Promise((resolve) => setTimeout(resolve, 0))
941
- const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
942
+ const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
942
943
  for (const effect of mid.effects) effect.fn()
943
944
  await new Promise((resolve) => setTimeout(resolve, 0))
944
- const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
945
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
945
946
  const rows = new Map()
946
947
  const labels = []
947
948
  walkNodes(tree, (node) => {
@@ -998,11 +999,11 @@ test('the log page renders rows with copy, download and locate actions', async (
998
999
  await new Promise((resolve) => setTimeout(resolve, 0))
999
1000
  // The log page's own effect only exists once that page renders, so it needs one
1000
1001
  // more render + effect pass before the data is in the hook.
1001
- const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
1002
+ const mid = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1002
1003
  for (const effect of mid.effects) effect.fn()
1003
1004
  await new Promise((resolve) => setTimeout(resolve, 0))
1004
1005
  await new Promise((resolve) => setTimeout(resolve, 0))
1005
- const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 10)
1006
+ const { tree } = await renderPage(settings.component, { ctx, t: (key) => key }, 11)
1006
1007
  const text = treeText(tree)
1007
1008
  assert.match(text, /整理超时/)
1008
1009
  assert.match(text, /logCopyAll/)
@@ -136,14 +136,14 @@ test('a verified receipt becomes the completion credential and advances the chec
136
136
  assert.equal(ctx.rec.disposed.length, 1)
137
137
  })
138
138
 
139
- test('a worker that reports but gives no receipt is a failure, not a success', async () => {
139
+ test('a worker that claims writes but leaves no receipt or library change is a failure, not a success', async () => {
140
140
  const sessionId = 'cred-no-receipt'
141
141
  state.ensureSession(sessionId, { cwd: path.join(home, 'proj-nr'), agentPreset: 'standard' })
142
142
  const ctx = host({ workerText: '我把能记的都记下来了。' })
143
143
  const result = await requestPrivateConsolidation(ctx, sessionId, { force: true })
144
144
  assert.equal(result.ok, false)
145
145
  assert.equal(result.settled, false)
146
- assert.equal(result.reasonCode, 'receipt-missing')
146
+ assert.equal(result.reasonCode, 'receipt-unverified')
147
147
  assert.match(result.error, /receipt/)
148
148
  assert.equal(state.getSessionBinding(sessionId).lastSleepSeq, undefined, 'without a credential the cursor must not advance')
149
149
  const job = ledger.sessionState(sessionId)
@@ -11,6 +11,8 @@ 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
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()
@@ -526,14 +528,14 @@ test('a PTC session (run_code only header) is consolidated and the worker gets w
526
528
  assert.equal(ctx.rec.created.length, 1, 'the fork is created for the PTC conversation')
527
529
  // 只挂 worker 真正用到的读写面(remember/update/link_suggest/list/recall/status);
528
530
  // 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'])
531
+ assert.deepEqual([...registered].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
530
532
  // 整理结束(finally)必须卸载挂载,不能给这条一次性 worker 留常驻注册。
531
- assert.deepEqual([...disposals].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
533
+ assert.deepEqual([...disposals].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
532
534
  // 全量挂载的活动元数据:attached=实际子集(此处=完整 wanted)、requested=完整 wanted、
533
535
  // partial=false。三件一起钉住"成功路径不再含糊"。
534
536
  const started = startedEntryFor(ctx, 'fork-ptc')
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'])
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'])
537
539
  assert.equal(started.detail.workerToolsPartial, false, 'a full mount is not partial')
538
540
  const followup = ctx.rec.forkFollowups[0]?.message
539
541
  const brief = Array.isArray(followup?.content)
@@ -575,14 +577,14 @@ test('a host registry refusing one write tool leaves a structured partial mount
575
577
  const result = await requestPrivateConsolidation(ctx, 'fork-ptc-partial')
576
578
  assert.equal(result.ok, true, String(result.error || ''))
577
579
  assert.equal(result.settled, true)
578
- assert.deepEqual([...registered].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update', 'memu_status'],
580
+ assert.deepEqual([...registered].sort(), ['memu_private_remember_batch', 'memu_private_update'],
579
581
  'exactly the tools that actually registered are mounted')
580
- assert.deepEqual([...disposals].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update', 'memu_status'],
582
+ assert.deepEqual([...disposals].sort(), ['memu_private_remember_batch', 'memu_private_update'],
581
583
  'dispose unmounts exactly what was mounted')
582
584
  const started = startedEntryFor(ctx, 'fork-ptc-partial')
583
- assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update', 'memu_status'],
585
+ assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_remember_batch', 'memu_private_update'],
584
586
  'the log records the actual subset, not the full wanted list')
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'])
587
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
586
588
  assert.equal(started.detail.workerToolsPartial, true)
587
589
  // 挂载为部分子集时任务书仍带 PTC 调用形态:worker 知道写记忆走 run_code 的 SDK 绑定。
588
590
  const followup = ctx.rec.forkFollowups[0]?.message
@@ -603,7 +605,7 @@ test('a fork context without a tools service records a null mount, the request a
603
605
  assert.equal(result.ok, true, String(result.error || ''))
604
606
  const started = startedEntryFor(ctx, 'fork-ptc-notools')
605
607
  assert.equal(started.detail.workerToolsAttached, null, 'no mount completed, so the log must not claim one')
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'])
608
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
607
609
  assert.equal(started.detail.workerToolsPartial, true)
608
610
  })
609
611
 
@@ -740,3 +742,180 @@ test('a bad host consolidationModel is refused with its own reason, not the pare
740
742
  restoreSettings()
741
743
  }
742
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
+ })
774
+
775
+ // ------------------------------------------------------- surface replacements
776
+ // Mirrors @deepseek-ai/dsh-session 0.2.2-rc.1 Session.create for the fields a
777
+ // consolidation seed touches: seq contiguity plus the surface fold. The host
778
+ // rejects "seed event at index N has seq M" and every dangling replace citation,
779
+ // so the assertion has to replay the fold, not just look at one event.
780
+ const HOST_SURFACE_EVENT_TYPES = new Set(['system/message', 'developer/message', 'user/message', 'assistant/message', 'tool/result'])
781
+ function assertSeedAcceptedByHost(seed, label = 'seed') {
782
+ const nodes = []
783
+ seed.forEach((event, index) => {
784
+ assert.equal(event.seq, index, `${label}: event at index ${index} has seq ${event.seq}`)
785
+ if (!HOST_SURFACE_EVENT_TYPES.has(event.type)) {
786
+ assert.equal(event.surfaceOp, undefined, `${label}: ${event.type} cannot carry surfaceOp`)
787
+ assert.equal(event.sourceEventSeqs, undefined, `${label}: ${event.type} cannot carry sourceEventSeqs`)
788
+ return
789
+ }
790
+ const op = event.surfaceOp
791
+ assert.ok(op !== undefined, `${label}: ${event.type} at ${index} requires a surfaceOp marker`)
792
+ const sources = event.sourceEventSeqs
793
+ if (sources !== undefined) {
794
+ assert.ok(Array.isArray(sources) && sources.length > 0, `${label}: sourceEventSeqs must be a non-empty array`)
795
+ assert.equal(new Set(sources).size, sources.length, `${label}: sourceEventSeqs must not repeat`)
796
+ assert.ok(sources.every(seq => Number.isSafeInteger(seq) && seq < event.seq), `${label}: sourceEventSeqs must reference earlier events`)
797
+ }
798
+ if (op === 'append') {
799
+ nodes.push(event.seq)
800
+ return
801
+ }
802
+ assert.deepEqual(Object.keys(op).sort(), ['endSeq', 'op', 'startSeq'], `${label}: replace markers carry exactly op/startSeq/endSeq`)
803
+ assert.ok(op.startSeq < event.seq && op.endSeq < event.seq, `${label}: surface replace at ${index} must reference earlier events`)
804
+ const startIdx = nodes.indexOf(op.startSeq)
805
+ const endIdx = nodes.indexOf(op.endSeq)
806
+ assert.ok(startIdx >= 0, `${label}: replace start seq ${op.startSeq} is not on the surface`)
807
+ assert.ok(endIdx >= startIdx, `${label}: replace range must be ordered`)
808
+ const shadowed = nodes.slice(startIdx, endIdx + 1)
809
+ if (event.type === 'tool/result') assert.equal(shadowed.length, 1, `${label}: tool/result replacement rewrites exactly one node`)
810
+ assert.ok(Array.isArray(sources), `${label}: replace at ${index} needs sourceEventSeqs`)
811
+ assert.deepEqual(shadowed.filter(seq => !sources.includes(seq)), [], `${label}: replace at ${index} must cite every shadowed node`)
812
+ nodes.splice(startIdx, endIdx - startIdx + 1)
813
+ nodes.push(event.seq)
814
+ })
815
+ }
816
+
817
+ const userEvent = (seq, text, extra = {}) => ({
818
+ seq, type: 'user/message', surfaceOp: 'append',
819
+ data: { source: { kind: 'user' }, content: [{ type: 'text', text }] }, ...extra,
820
+ })
821
+ const assistantEvent = (seq, text) => ({
822
+ seq, type: 'assistant/message', surfaceOp: 'append',
823
+ data: { message: { content: [{ type: 'text', text }] } },
824
+ })
825
+ const toolResultEvent = (seq, text, extra = {}) => ({
826
+ seq, type: 'tool/result', surfaceOp: 'append',
827
+ data: { message: { content: [{ type: 'text', text }] } }, ...extra,
828
+ })
829
+
830
+ test('a surface replace is renumbered into the seed instead of citing original seqs', () => {
831
+ const seed = compactSeedEvents([
832
+ userEvent(0, '记住:周五交房租'),
833
+ assistantEvent(1, '好'),
834
+ toolResultEvent(2, '原始工具输出'),
835
+ toolResultEvent(3, '[已裁剪]', {
836
+ surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 },
837
+ sourceEventSeqs: [2],
838
+ }),
839
+ userEvent(4, '继续'),
840
+ ])
841
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4])
842
+ assert.deepEqual(seed[3].surfaceOp, { op: 'replace', startSeq: 2, endSeq: 2 }, 'the citation follows the surviving node, not its original seq')
843
+ assert.deepEqual(seed[3].sourceEventSeqs, [2])
844
+ assertSeedAcceptedByHost(seed)
845
+ })
846
+
847
+ test('a replace pointing outside the window is dropped and the seed stays contiguous', () => {
848
+ // 窗口从父会话中间切出:seq 4 不在这一窗里;后面的 replace 又引用前面被丢的
849
+ // replace。旧实现先编号后丢弃,留下 seq 空洞,宿主报 index 1 has seq 5。
850
+ const seed = compactSeedEvents([
851
+ userEvent(10, '这一窗的第一句'),
852
+ toolResultEvent(11, '输出'),
853
+ toolResultEvent(12, '[已裁剪]', {
854
+ surfaceOp: { op: 'replace', startSeq: 4, endSeq: 4 },
855
+ sourceEventSeqs: [4],
856
+ }),
857
+ assistantEvent(13, '回答'),
858
+ toolResultEvent(14, '[已裁剪]', {
859
+ surfaceOp: { op: 'replace', startSeq: 12, endSeq: 12 },
860
+ sourceEventSeqs: [12],
861
+ }),
862
+ ])
863
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2], 'dropping a patch must renumber the survivors')
864
+ assert.equal(seed.some(event => event.surfaceOp && typeof event.surfaceOp === 'object'), false)
865
+ assertSeedAcceptedByHost(seed)
866
+ })
867
+
868
+ test('a replacement that cites another replacement keeps both when their targets survive', () => {
869
+ const seed = compactSeedEvents([
870
+ userEvent(0, '开头'),
871
+ toolResultEvent(1, '原始输出'),
872
+ toolResultEvent(2, '[第一次裁剪]', {
873
+ surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 },
874
+ sourceEventSeqs: [1],
875
+ }),
876
+ assistantEvent(3, '中间'),
877
+ toolResultEvent(4, '[第二次裁剪]', {
878
+ surfaceOp: { op: 'replace', startSeq: 2, endSeq: 2 },
879
+ sourceEventSeqs: [2],
880
+ }),
881
+ ])
882
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3, 4])
883
+ assert.deepEqual(seed[2].surfaceOp, { op: 'replace', startSeq: 1, endSeq: 1 })
884
+ assert.deepEqual(seed[4].surfaceOp, { op: 'replace', startSeq: 2, endSeq: 2 })
885
+ assertSeedAcceptedByHost(seed)
886
+ })
887
+
888
+ test('a multi-node replace is remapped when every shadowed node survives', () => {
889
+ const seed = compactSeedEvents([
890
+ userEvent(0, 'A'),
891
+ userEvent(1, 'X'),
892
+ userEvent(2, 'B'),
893
+ userEvent(3, '外层摘要', {
894
+ surfaceOp: { op: 'replace', startSeq: 0, endSeq: 2 },
895
+ sourceEventSeqs: [0, 1, 2],
896
+ }),
897
+ ])
898
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2, 3])
899
+ assert.deepEqual(seed[3].surfaceOp, { op: 'replace', startSeq: 0, endSeq: 2 })
900
+ assert.deepEqual(seed[3].sourceEventSeqs, [0, 1, 2])
901
+ assertSeedAcceptedByHost(seed)
902
+ })
903
+
904
+ test('a replace is dropped when filtering an inner checkpoint reveals a shadowed node', () => {
905
+ // 内层压缩检查点(source.kind 不是 user)会被种子过滤器丢掉;它遮住的 X 因此
906
+ // 重新出现在种子的 surface 上。外层替换写于 X 被遮住期间,引用里没有 X。
907
+ // 宿主会要求外层补上 X 的引用——补不出来就只能丢外层,种子回到纯 append。
908
+ const seed = compactSeedEvents([
909
+ userEvent(0, 'A'),
910
+ userEvent(1, 'X'),
911
+ userEvent(2, 'B'),
912
+ userEvent(3, '内层摘要', { data: { source: { kind: 'compact-checkpoint' }, content: [{ type: 'text', text: '内层摘要' }] }, surfaceOp: { op: 'replace', startSeq: 1, endSeq: 1 }, sourceEventSeqs: [1] }),
913
+ userEvent(4, '外层摘要', {
914
+ surfaceOp: { op: 'replace', startSeq: 0, endSeq: 2 },
915
+ sourceEventSeqs: [0, 2],
916
+ }),
917
+ ])
918
+ assert.deepEqual(seed.map(event => event.seq), [0, 1, 2])
919
+ assert.deepEqual(seed.map(event => event.data.content[0].text), ['A', 'X', 'B'])
920
+ assertSeedAcceptedByHost(seed)
921
+ })
@@ -328,6 +328,37 @@ test('decideCompletion: proof advances, guesswork does not', () => {
328
328
  assert.equal(silent.reasonCode, 'receipt-missing')
329
329
  })
330
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
+
331
362
  test('decideCompletion never settles a silent worker on its own', () => {
332
363
  // 结算空正文的规则已经上移到 private.js 的调用点:那里知道「worker 一个字没说、库里也没
333
364
  // 多出条目」这一种情形(见 tests/consolidation-fork.test.mjs 与 tests/cycle.test.mjs)。
@@ -281,20 +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 the receipt buckets', () => {
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, /每窗最多新增 8 条/)
293
- assert.match(brief, /heldIds/)
294
- // 整理 worker 只挂用得到的 6 个工具:词典/lexicon 不再出现在任务书里。
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/)
295
296
  assert.doesNotMatch(brief, /memu_lexicon|term 是索引键|sensitive trigger/)
296
297
  assert.match(brief, /tools-unavailable/, 'the tools-unavailable contract survives')
297
- assert.match(brief, /没有回执视为本次整理失败/, 'the receipt requirement survives')
298
+ assert.match(brief, /没有回执视为本次整理失败/, 'the receipt requirement survives when auto receipt is off')
298
299
  assert.match(brief, /BRIEF-CONTRACT/)
299
300
  })
300
301
 
@@ -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()
@@ -177,7 +177,7 @@ test('a fork that cannot be created is logged, not dropped silently', async () =
177
177
  },
178
178
  }
179
179
  await cycle.runSleepPass(ctx, { log: (m) => logs.push(m) })
180
- assert.ok(logs.some((m) => /consolidation skipped for cycle-hist: no fork in test env/.test(m)), 'attempt logged: ' + logs.join(' | '))
180
+ assert.ok(logs.some((m) => /consolidation skipped for cycle-hist: .*no fork in test env/.test(m)), 'attempt logged: ' + logs.join(' | '))
181
181
  assert.equal(state.getLastSleepAt('cycle-hist'), null)
182
182
  assert.match(state.getSessionBinding('cycle-hist').lastSleepError, /no fork/)
183
183
  })