dsh-memu-memory 1.4.3 → 1.4.5

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 (183) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +15 -0
  3. package/README.md +34 -15
  4. package/README.zh.md +35 -13
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/libraries.jpg +0 -0
  7. package/assets/screenshots/mobile.jpg +0 -0
  8. package/assets/screenshots/relations.jpg +0 -0
  9. package/assets/screenshots/settings.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +19 -3
  13. package/docs/contributing.md +4 -2
  14. package/docs/env-and-commands.md +9 -1
  15. package/docs/graph-scale.md +214 -0
  16. package/docs/lexicon-recall.md +100 -0
  17. package/docs/mcp-porting.md +8 -6
  18. package/docs/memory-semantics.md +35 -3
  19. package/docs/pending-work.md +3 -1
  20. package/docs/retention.md +83 -0
  21. package/docs/rt-index.md +452 -0
  22. package/docs/scale-performance.md +101 -0
  23. package/docs/token-budget.md +92 -0
  24. package/docs/troubleshooting.md +50 -11
  25. package/lib/auto-link/apply.js +7 -2
  26. package/lib/auto-link/candidates.js +32 -10
  27. package/lib/backup.js +67 -32
  28. package/lib/binding-diagnostics.js +1 -1
  29. package/lib/bounded-cache.js +80 -0
  30. package/lib/client.js +2096 -409
  31. package/lib/consolidation-ledger.js +21 -4
  32. package/lib/consolidation-worker.js +14 -1
  33. package/lib/cycle.js +16 -11
  34. package/lib/diagnostic-context.js +372 -0
  35. package/lib/diagnostics.js +147 -61
  36. package/lib/embedding-download.js +7 -8
  37. package/lib/engine-sources.js +286 -0
  38. package/lib/engine.js +23 -10
  39. package/lib/entity-repair.js +43 -13
  40. package/lib/entity-review.js +64 -0
  41. package/lib/environment-check.js +348 -36
  42. package/lib/feedback.js +25 -0
  43. package/lib/global-graph.js +46 -2
  44. package/lib/graph-adjacency-index.js +525 -0
  45. package/lib/graph-overview.js +293 -0
  46. package/lib/graph.js +658 -105
  47. package/lib/inbound.js +44 -15
  48. package/lib/index-pages.js +57 -0
  49. package/lib/index.js +44 -6
  50. package/lib/inject.js +119 -50
  51. package/lib/lexicon-rt-source.js +25 -0
  52. package/lib/lexicon-rt-worker.js +26 -0
  53. package/lib/lexicon-rt.js +224 -0
  54. package/lib/lexicon-scope.js +56 -5
  55. package/lib/lexicon.js +143 -54
  56. package/lib/local-vector-service.js +3 -0
  57. package/lib/maintenance-ledger.js +542 -12
  58. package/lib/managed-runtime.js +260 -80
  59. package/lib/media.js +1 -1
  60. package/lib/memory.js +564 -131
  61. package/lib/port-surface.js +96 -11
  62. package/lib/preset-mount.js +13 -7
  63. package/lib/private.js +47 -21
  64. package/lib/recall-cache.js +20 -34
  65. package/lib/retention.js +173 -0
  66. package/lib/rpc.js +135 -52
  67. package/lib/rt-index/builder.js +209 -0
  68. package/lib/rt-index/format.js +231 -0
  69. package/lib/rt-index/manifest.js +105 -0
  70. package/lib/rt-index/reader.js +673 -0
  71. package/lib/rt-index-retention.js +151 -0
  72. package/lib/rt-index-service.js +283 -0
  73. package/lib/rt-index-worker.js +21 -0
  74. package/lib/salient-wake.js +55 -4
  75. package/lib/state.js +195 -24
  76. package/lib/temporal.js +39 -13
  77. package/lib/token-measurement.js +126 -0
  78. package/lib/tools.js +101 -6
  79. package/lib/turn-log.js +108 -3
  80. package/lib/webui/graph-layout-worker.js +68 -0
  81. package/lib/webui/graph-local-physics.js +390 -0
  82. package/lib/webui/graph-spatial-grid.js +64 -0
  83. package/lib/webui/graph-view.bundle.js +6 -1
  84. package/lib/webui/graph-view.js +478 -135
  85. package/lib/webui/graph-webgl-renderer.js +74 -0
  86. package/lib/webui/standalone.js +1 -1
  87. package/lib/worker-pool.js +38 -7
  88. package/package.json +3 -2
  89. package/scripts/acceptance-local.mjs +4 -10
  90. package/scripts/bench-all-libraries.mjs +47 -0
  91. package/scripts/check-classic-graph-browser.mjs +189 -0
  92. package/scripts/check-client-browser.mjs +929 -0
  93. package/scripts/check-graph-browser.mjs +6 -0
  94. package/scripts/check-graph-elastic-browser.mjs +139 -0
  95. package/scripts/check-memory-review-browser.mjs +124 -0
  96. package/scripts/entity-dedupe.mjs +19 -3
  97. package/scripts/graph-artifact-provenance.mjs +30 -0
  98. package/scripts/graph-freeze-manifest.mjs +129 -0
  99. package/scripts/graph-geometry-fixture.mjs +40 -0
  100. package/scripts/graph-physics-bench.mjs +218 -0
  101. package/scripts/graph-scale-bench.mjs +213 -0
  102. package/scripts/graph-scale-memory.mjs +48 -0
  103. package/scripts/graph-service-bench.mjs +72 -0
  104. package/scripts/make-readme-shots.mjs +17 -5
  105. package/scripts/preview.mjs +1 -0
  106. package/scripts/rebuild-rt.mjs +18 -0
  107. package/scripts/scale-bench.mjs +183 -0
  108. package/scripts/simulate-injection.mjs +47 -8
  109. package/scripts/verify-host-fixtures.mjs +108 -0
  110. package/scripts/verify-host-recovery.mjs +565 -0
  111. package/scripts/verify-vector-recovery.mjs +740 -0
  112. package/tests/auto-link-candidates.test.mjs +20 -0
  113. package/tests/browser.test.mjs +16 -2
  114. package/tests/client-export.test.mjs +16 -1
  115. package/tests/client-pagination.test.mjs +1495 -0
  116. package/tests/client-render.test.mjs +223 -28
  117. package/tests/consolidation-fork.test.mjs +97 -13
  118. package/tests/consolidation-ledger.test.mjs +17 -1
  119. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  120. package/tests/diagnostic-report.test.mjs +429 -0
  121. package/tests/diagnostic-wiring.test.mjs +88 -0
  122. package/tests/diagnostics.test.mjs +27 -0
  123. package/tests/embedding-download.test.mjs +44 -0
  124. package/tests/engine-source-settings.test.mjs +69 -0
  125. package/tests/engine-sources.test.mjs +145 -0
  126. package/tests/entity-dedupe.test.mjs +143 -0
  127. package/tests/entity-merge-review.test.mjs +363 -0
  128. package/tests/entity-merge.test.mjs +12 -4
  129. package/tests/entity-review.test.mjs +87 -0
  130. package/tests/environment-check.test.mjs +51 -1
  131. package/tests/feedback.test.mjs +95 -0
  132. package/tests/graph-adjacency-index.test.mjs +536 -0
  133. package/tests/graph-cascade.test.mjs +229 -0
  134. package/tests/graph-import-diagnostic.test.mjs +25 -0
  135. package/tests/graph-overview.test.mjs +709 -0
  136. package/tests/graph-session-authorization.test.mjs +419 -0
  137. package/tests/graph-view-geometry.test.mjs +426 -0
  138. package/tests/graph-view-scale.test.mjs +88 -0
  139. package/tests/graph-view.test.mjs +444 -5
  140. package/tests/graph.test.mjs +43 -0
  141. package/tests/help-page.test.mjs +128 -54
  142. package/tests/inbound.test.mjs +19 -0
  143. package/tests/index-pagination.test.mjs +113 -0
  144. package/tests/index-read-view.test.mjs +212 -0
  145. package/tests/inject-guide.test.mjs +9 -0
  146. package/tests/injection-dedupe.test.mjs +213 -0
  147. package/tests/lexicon-recall.test.mjs +641 -0
  148. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  149. package/tests/lexicon-rt.test.mjs +468 -0
  150. package/tests/local-embedding-worker.test.mjs +38 -0
  151. package/tests/local-vector-service.test.mjs +32 -3
  152. package/tests/maintenance-compat.test.mjs +128 -0
  153. package/tests/maintenance-settlement.test.mjs +1003 -0
  154. package/tests/managed-memory.test.mjs +39 -11
  155. package/tests/managed-runtime.test.mjs +109 -0
  156. package/tests/memory-fields.test.mjs +24 -12
  157. package/tests/observed-evidence.test.mjs +52 -0
  158. package/tests/port-surface.test.mjs +93 -1
  159. package/tests/preset-mount.test.mjs +12 -4
  160. package/tests/recall-cache.test.mjs +56 -3
  161. package/tests/recall-dedup.test.mjs +63 -2
  162. package/tests/retention.test.mjs +260 -0
  163. package/tests/rt-index-cross-library.test.mjs +230 -0
  164. package/tests/rt-index-integration.test.mjs +194 -0
  165. package/tests/rt-index-retention.test.mjs +552 -0
  166. package/tests/rt-index-scale.test.mjs +204 -0
  167. package/tests/rt-index.test.mjs +705 -0
  168. package/tests/salient-date-boundaries.test.mjs +121 -0
  169. package/tests/salient-wake.test.mjs +29 -0
  170. package/tests/scale-bench.test.mjs +53 -0
  171. package/tests/settings-plumbing.test.mjs +25 -0
  172. package/tests/simulate-injection.test.mjs +15 -1
  173. package/tests/standalone-navigation.test.mjs +44 -0
  174. package/tests/state.test.mjs +51 -0
  175. package/tests/temporal-precision.test.mjs +102 -0
  176. package/tests/temporal.test.mjs +10 -6
  177. package/tests/token-measurement.test.mjs +98 -0
  178. package/tests/tool-schema.test.mjs +41 -5
  179. package/tests/tools.test.mjs +6 -3
  180. package/tests/turn-token-budget.test.mjs +149 -0
  181. package/tests/webui-auth.test.mjs +57 -1
  182. package/tests/webui.test.mjs +40 -15
  183. package/tests/worker-lifecycle.test.mjs +2 -1
@@ -14,6 +14,14 @@ test.after(async () => {
14
14
 
15
15
  import { defineTool } from './stubs/dsh-tools.js'
16
16
 
17
+ const SHIPPED_TOOL_NAMES = [
18
+ 'memu_private_link', 'memu_private_link_suggest', 'memu_private_entity_merge_suggest', 'memu_private_entity_merge_decide',
19
+ 'memu_private_remember', 'memu_private_remember_batch',
20
+ 'memu_private_recall', 'memu_private_list', 'memu_private_update', 'memu_private_feedback',
21
+ 'memu_private_archive', 'memu_private_unpin', 'memu_lexicon_search', 'memu_lexicon_propose',
22
+ 'memu_global_recall', 'memu_global_list', 'memu_status',
23
+ ]
24
+
17
25
  // The stub compiles tool schemas with the host's value-schema DSL rules. These
18
26
  // cases pin the two shapes that the real host refused in production — the reason
19
27
  // all ten memu tools were missing from the tool surface while every test passed:
@@ -79,17 +87,19 @@ test('the shipped tool surface compiles under the host rules', async () => {
79
87
  tools: { register: (tool) => { registered.push(tool.name); return () => {} } },
80
88
  logger: { warn: (message) => { throw new Error(`unexpected registration warning: ${message}`) } },
81
89
  })
82
- assert.equal(registered.length, 14, `registered ${registered.join(', ')}`)
83
- assert.ok(registered.includes('memu_private_remember_batch'), 'the batch write tool compiles under the host rules')
84
- dispose()
90
+ try {
91
+ assert.equal(registered.length, 17, `registered ${registered.join(', ')}`)
92
+ assert.deepEqual([...registered].sort(), [...SHIPPED_TOOL_NAMES].sort(), 'the exact tool surface compiles, with no missing or duplicate tool')
93
+ } finally { dispose() }
85
94
  })
86
95
 
87
- test('recall schemas retain required query, supported enums and integer paging; all 14 outputs stay string', async () => {
96
+ test('recall schemas retain required query, supported enums and integer paging; all 17 outputs stay string', async () => {
88
97
  const { registerTools } = await import('../lib/tools.js')
89
98
  const tools = []
90
99
  const dispose = registerTools({ tools: { register: (tool) => { tools.push(tool); return () => {} } }, logger: { warn() {} } })
91
100
  try {
92
- assert.equal(tools.length, 14)
101
+ assert.equal(tools.length, 17)
102
+ assert.deepEqual(tools.map(tool => tool.name).sort(), [...SHIPPED_TOOL_NAMES].sort())
93
103
  for (const tool of tools) {
94
104
  assert.deepEqual(tool.output.schema, { type: 'string' })
95
105
  assert.deepEqual(tool.output.render({}, 'receipt'), [{ type: 'text', text: 'receipt' }])
@@ -119,6 +129,32 @@ test('recall schemas retain required query, supported enums and integer paging;
119
129
  } finally { dispose() }
120
130
  })
121
131
 
132
+ test('feedback schema requires id, supported verdict and reason, with only an optional revision', async () => {
133
+ const { registerTools } = await import('../lib/tools.js')
134
+ const tools = []
135
+ const warnings = []
136
+ const dispose = registerTools({ tools: { register: tool => { tools.push(tool); return () => {} } },
137
+ logger: { warn: message => warnings.push(String(message)) } })
138
+ try {
139
+ assert.deepEqual(warnings, [])
140
+ const tool = tools.find(item => item.name === 'memu_private_feedback')
141
+ assert.ok(tool, 'feedback must register under the host DSL')
142
+ const p = tool.parameters
143
+ assert.deepEqual(Object.keys(p).sort(), ['id', 'reason', 'revision', 'verdict'])
144
+ for (const name of ['id', 'verdict', 'reason']) {
145
+ assert.equal(p[name].type, 'string', name)
146
+ assert.equal(p[name].required, true, name)
147
+ }
148
+ assert.deepEqual(p.verdict.enum, ['confirm', 'deny', 'irrelevant'])
149
+ assert.equal(p.revision.type, 'string')
150
+ assert.equal(Object.hasOwn(p.revision, 'required'), false)
151
+ assert.equal(Object.hasOwn(p, 'libraryId'), false, 'feedback cannot widen its write library')
152
+ assert.equal(Object.hasOwn(p, 'scope'), false, 'feedback cannot request a global write')
153
+ assert.equal(tool.isConcurrencySafe(), false)
154
+ assert.deepEqual(tool.output.schema, { type: 'string' })
155
+ } finally { dispose() }
156
+ })
157
+
122
158
  test('host DSL rejects numeric bounds: recall ranges must stay in execute validation', () => {
123
159
  for (const bound of ['minimum', 'maximum']) {
124
160
  assert.throws(() => defineTool(good({ offset: { type: 'integer', [bound]: 0 } })), /not supported by the value schema DSL/)
@@ -43,11 +43,14 @@ test('all v1 tools register', () => {
43
43
  for (const name of [
44
44
  'memu_private_link',
45
45
  'memu_private_link_suggest',
46
+ 'memu_private_entity_merge_suggest',
47
+ 'memu_private_entity_merge_decide',
46
48
  'memu_private_remember',
47
49
  'memu_private_remember_batch',
48
50
  'memu_private_recall',
49
51
  'memu_private_list',
50
52
  'memu_private_update',
53
+ 'memu_private_feedback',
51
54
  'memu_private_archive',
52
55
  'memu_private_unpin',
53
56
  'memu_lexicon_search',
@@ -58,10 +61,10 @@ test('all v1 tools register', () => {
58
61
  ]) {
59
62
  assert.ok(names.includes(name), `missing ${name}`)
60
63
  }
61
- // Exactly fourteen, not "at least these": a schema the host DSL refuses used to
64
+ // Exactly seventeen, not "at least these": a schema the host DSL refuses used to
62
65
  // abort registerTools() before any register() ran, so counting is the assertion
63
66
  // that actually catches a total registration failure.
64
- assert.equal(names.length, 14, `expected 14 tools, got ${names.length}: ${names.join(', ')}`)
67
+ assert.equal(names.length, 17, `expected 17 tools, got ${names.length}: ${names.join(', ')}`)
65
68
  dispose()
66
69
  })
67
70
 
@@ -93,7 +96,7 @@ test('status works without an engine', async () => {
93
96
  assert.match(status, /library:/)
94
97
  // The registration count is the visible signal for a refused schema: without it
95
98
  // a host that rejects the tool and a plugin that never had it look identical.
96
- assert.match(status, /tools: 14\/14 registered/)
99
+ assert.match(status, /tools: 17\/17 registered/)
97
100
  dispose()
98
101
  })
99
102
 
@@ -0,0 +1,149 @@
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-turn-tokens-'))
8
+ process.env.DSH_HOME = home
9
+ process.env.DSH_MEMU_HOME = home
10
+ process.env.DSH_MEMU_MEMORY_HOME = home
11
+ const state = await import('../lib/state.js')
12
+ const inject = await import('../lib/inject.js')
13
+ const { estTokens } = await import('../lib/budget.js')
14
+ const { listDiagnostics } = await import('../lib/diagnostics.js')
15
+ const workers = await import('../lib/worker-pool.js')
16
+ const handlers = new Map()
17
+ const warns = []
18
+ const dispose = inject.registerInjection({ on: (topic, fn) => { handlers.set(topic, fn); return () => {} }, get: () => undefined, logger: { warn: message => warns.push(message) } })
19
+ test.after(() => { dispose(); state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
20
+ const textOf = message => (message.content || []).map(block => block.text || '').join('\n')
21
+ const memoryMessages = messages => messages.filter(message => message.source?.kind === 'plugin:dsh-memu-memory')
22
+ function fixture(id) {
23
+ state.updateSettings({ autoInject: 'smart', injectionTotalTokens: 2000, turnTokens: 640, randomCueChance: 0, habitsInjection: false, midTurnRecall: true, midTurnCooldownMs: 0 })
24
+ const cwd = path.join(home, id)
25
+ const binding = state.ensureSession(id, { cwd, agentPreset: 'coding' })
26
+ state.setSessionBinding(id, { useGlobal: false })
27
+ const index = state.loadPrivateIndex(binding.libraryId)
28
+ index.entries['mem-token-budget'] = { track: 'memory', layer: 'long_term', title: 'deploy staging script', content: 'The deploy staging script lives in tools/deploy.ps1. Run the staging smoke test before deployment.', status: 'active', confidence: 0.9, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() }
29
+ state.savePrivateIndex(binding.libraryId, index)
30
+ const user = { id: id + '-user', role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'where is the deploy staging script' }] }
31
+ const agent = { session: { header: { id, cwd, agentPreset: 'coding', origin: 'user' }, messages: [] } }
32
+ const pre = (messages, turn = 1, step = 1) => handlers.get('agent/pre-step')({ agent, turn, step, signal: { aborted: false } }, async () => ({ kind: 'enter', messages }))
33
+ const emit = event => handlers.get('session/event')(agent.session, event)
34
+ return { id, agent, user, pre, emit }
35
+ }
36
+ async function accept(f, messages) {
37
+ for (const message of messages) {
38
+ f.agent.session.messages.push(message)
39
+ await f.emit({ type: 'user/message', data: message })
40
+ }
41
+ }
42
+ const tools = seed => Array.from({ length: 3 }, (_, i) => ({ id: `${seed}-${i}`, role: 'tool', source: { kind: 'tool' }, content: [{ type: 'text', text: 'x'.repeat(150) + seed + i }] }))
43
+
44
+ test('first-step + guide + two possible mid-turn hints share one total, even with delta-only tool batches', async () => {
45
+ const f = fixture('shared-allowance')
46
+ const first = await f.pre([f.user])
47
+ const initial = memoryMessages(first.messages)
48
+ assert.ok(initial.some(message => textOf(message).includes('<memory-guide')), 'guide marker intact')
49
+ assert.ok(initial.some(message => textOf(message).includes('[mem-token-budget]')), 'real recalled id retained')
50
+ await accept(f, first.messages)
51
+ const used = initial.reduce((sum, message) => sum + estTokens(textOf(message)), 0)
52
+ assert.equal(inject.injectionTokenDiagnostics(f.id, 1).estimated, used)
53
+ const hint = '[回合中途补充 · 这不是用户新说的话 · 本回合已跑 5 步]\n如果你需要更早的上下文,可以调用 memu_private_recall 按关键词查。'
54
+ const total = used + estTokens(hint) + 1
55
+ state.updateSettings({ injectionTotalTokens: total })
56
+ const mid = await f.pre(tools('a'), 1, 5)
57
+ const hints = memoryMessages(mid.messages)
58
+ assert.equal(hints.length, 1)
59
+ assert.equal(textOf(hints[0]), hint, 'semantic hint card was not cut')
60
+ await accept(f, hints)
61
+ const mid2 = await f.pre(tools('b'), 1, 9)
62
+ assert.equal(memoryMessages(mid2.messages).length, 0, 'second hint cannot spend the first step allowance twice')
63
+ const metrics = inject.injectionTokenDiagnostics(f.id, 1)
64
+ assert.ok(metrics.estimated <= total)
65
+ assert.equal(metrics.admittedEstimated, metrics.estimated)
66
+ const nextTurn = await f.pre(tools('next'), 2, 5)
67
+ assert.equal(memoryMessages(nextTurn.messages).length, 1, 'new host turn gets a fresh budget')
68
+ })
69
+
70
+ test('hint is omitted whole when first-step allowance has only ten tokens left', async () => {
71
+ const f = fixture('hint-no-room')
72
+ const first = await f.pre([f.user])
73
+ await accept(f, first.messages)
74
+ const before = inject.injectionTokenDiagnostics(f.id, 1).estimated
75
+ state.updateSettings({ injectionTotalTokens: before + 10 })
76
+ const mid = await f.pre(tools('no-room'), 1, 5)
77
+ assert.equal(memoryMessages(mid.messages).length, 0)
78
+ assert.equal(inject.injectionTokenDiagnostics(f.id, 1).estimated, before)
79
+ await f.emit({ type: 'compaction/end', data: {} })
80
+ assert.equal(inject.injectionTokenDiagnostics(f.id, 1).estimated, before, 'compaction cannot replenish same-turn allowance')
81
+ state.setSessionBinding(f.id, { domainOverride: 'general' })
82
+ const retry = await f.pre([f.user], 1, 1)
83
+ assert.equal(memoryMessages(retry.messages).length, 0, 'scope change cannot replenish allowance')
84
+ assert.equal(inject.injectionTokenDiagnostics(f.id, 1).estimated, before)
85
+ })
86
+
87
+ test('unadmitted rollback releases reservation and accepted retry remains charged', async () => {
88
+ const f = fixture('reservation-rollback')
89
+ const first = await f.pre([f.user])
90
+ const proposed = inject.injectionTokenDiagnostics(f.id, 1)
91
+ assert.ok(proposed.estimated > 0)
92
+ assert.equal(proposed.admittedEstimated, 0)
93
+ await f.emit({ type: 'turn/end', data: { turn: 1, reason: { kind: 'error' } } })
94
+ assert.equal(inject.injectionTokenDiagnostics(f.id, 1).estimated, 0)
95
+ const retry = await f.pre([f.user], 1, 1)
96
+ assert.ok(memoryMessages(retry.messages).length > 0)
97
+ await accept(f, retry.messages)
98
+ const accepted = inject.injectionTokenDiagnostics(f.id, 1).estimated
99
+ await f.emit({ type: 'turn/end', data: { turn: 1, reason: { kind: 'error' } } })
100
+ assert.equal(inject.injectionTokenDiagnostics(f.id, 1).estimated, accepted)
101
+ const duplicated = await f.pre([f.user], 1, 1)
102
+ assert.equal(memoryMessages(duplicated.messages).length, 0)
103
+ assert.equal(inject.injectionTokenDiagnostics(f.id, 1).estimated, accepted)
104
+ assert.ok(first.messages.length > 1)
105
+ })
106
+
107
+ test('public request usage produces privacy-safe diagnostics without memory attribution', async () => {
108
+ const f = fixture('usage-observation')
109
+ const out = await f.pre([f.user])
110
+ await accept(f, out.messages)
111
+ await f.emit({ type: 'assistant/message', seq: 100, data: { turn: 1, step: 1, usage: { inputTokens: 1000, cacheReadTokens: 500, cacheWriteTokens: 0, outputTokens: 30 } } })
112
+ const metrics = inject.injectionTokenDiagnostics(f.id, 1)
113
+ assert.equal(metrics.requestUsage.last.promptTokens, 1500)
114
+ assert.equal(metrics.memoryActual, null)
115
+ assert.equal(metrics.calibration, 'unverified')
116
+ await f.emit({ type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } })
117
+ const diagnostics = listDiagnostics({ code: 'MEMU_TOKEN_BUDGET' })
118
+ const serialized = JSON.stringify(diagnostics)
119
+ assert.ok(serialized.includes('whole-request'))
120
+ assert.ok(serialized.includes('unverified'))
121
+ assert.ok(!serialized.includes('tools/deploy.ps1'))
122
+ assert.ok(!serialized.includes('where is the deploy'))
123
+ })
124
+
125
+ test('recordEpochProgress learns complete character windows by domain, ignoring legacy/partial/late data', () => {
126
+ const id = 'worker-factor-integration'
127
+ state.ensureSession(id, { cwd: home, agentPreset: 'coding' })
128
+ const domain = 'factor-integration'
129
+ state.setSessionBinding(id, { domainOverride: domain, workerEpoch: { forkSessionId: 'factor-child', chars: 0, windows: 0, outputFactorDomain: domain } })
130
+ const binding = () => ({ ...state.getSessionBinding(id), sessionId: id })
131
+ const measurement = { serializationErrors: 0, dispatched: { inputChars: 100, estimatedTokens: 30 }, observed: { outputTextChars: 100, toolArgumentsChars: 0, toolResultsChars: 0, estimatedTokens: 30 }, usage: { inputTokens: 1000000, outputTokens: 1, cacheReadTokens: null, cacheWriteTokens: null, reasoningTokens: null } }
132
+ assert.equal(workers.workerOutputFactor(domain).factor, 3)
133
+ const pending = workers.recordEpochProgress(binding(), { measurement })
134
+ assert.equal(workers.workerOutputFactor(domain).factor, 3, 'progress alone is not a settled sample')
135
+ assert.equal(pending.outputFactorPending.inputChars, 100)
136
+ workers.recordEpochProgress(binding(), { settled: true, progress: false })
137
+ workers.recordEpochProgress(binding(), { settled: true, progress: false })
138
+ assert.equal(workers.workerOutputFactor(domain).factor, 2)
139
+ assert.equal(workers.workerOutputFactor('another-domain').factor, 3)
140
+ workers.recordEpochProgress(binding(), { incrementChars: 100, workerOutputChars: 10000, settled: true })
141
+ workers.recordEpochProgress(binding(), { measurement: { ...measurement, serializationErrors: 1 }, settled: true })
142
+ workers.recordEpochProgress(binding(), { measurement, settled: true, countWindow: false })
143
+ workers.recordEpochProgress(binding(), { measurement, settled: true, timeout: true })
144
+ assert.equal(workers.workerOutputFactor(domain).samples, 1)
145
+ const result = workers.recordEpochProgress(binding(), { measurement: { ...measurement, observed: { ...measurement.observed, outputTextChars: 900 } }, settled: true })
146
+ assert.equal(result.outputFactor.factor, 3, 'mean of clamped 2 and 4')
147
+ assert.equal(result.outputFactor.samples, 2)
148
+ assert.equal(workers.budgetFit({ chars: 0, outputFactorDomain: domain }, 100, { workerEpochCharLimit: 250 }), false)
149
+ })
@@ -17,6 +17,7 @@ process.env.DSH_MEMU_HOME = home
17
17
  const state = await import('../lib/state.js')
18
18
  const { registerRpc } = await import('../lib/rpc.js')
19
19
  const { standaloneHtml, standaloneAsset } = await import('../lib/webui.js')
20
+ const graph = await import('../lib/graph.js')
20
21
 
21
22
  test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
22
23
 
@@ -169,7 +170,8 @@ const RPC_IMPORT_SENTINEL = 'RPC-IMPORT-SENTINEL-4c8e11'
169
170
 
170
171
  const library = state.createLibrary({ name: 'auth-matrix', cwd: path.join(home, 'auth-matrix') })
171
172
  const sessionId = 'auth-session'
172
- state.setSessionBinding(sessionId, { libraryId: library.id, useLibrary: true, scopeKey: library.scopeKey })
173
+ state.setSessionBinding(sessionId, { libraryId: library.id, useLibrary: true, useGlobal: true, scopeKey: library.scopeKey,
174
+ memoryContext: { characterId: 'auth-character' } })
173
175
  state.updatePrivateIndex(library.id, (index) => {
174
176
  index.entries['mem-auth-sentinel'] = {
175
177
  title: 'auth sentinel', content: SENTINEL, status: 'active', layer: 'long_term',
@@ -179,6 +181,58 @@ state.updatePrivateIndex(library.id, (index) => {
179
181
  })
180
182
  state.flushState()
181
183
 
184
+ test('graph entity RPCs preserve session scope and filter secret/context-only references over HTTP', async () => {
185
+ const now = new Date().toISOString()
186
+ const seed = (id, visibility, context = undefined) => {
187
+ state.updatePrivateIndex(library.id, index => {
188
+ index.entries[id] = { title: id, content: 'graph authorization fixture', status: 'active', layer: 'long_term',
189
+ visibility, disclosure: 'can_tell', source: 'user_said', ...(context ? { context } : {}),
190
+ createdAt: now, updatedAt: now }
191
+ })
192
+ }
193
+ seed('mem-graph-auth-visible', 'shared')
194
+ seed('mem-graph-auth-secret', 'secret')
195
+ seed('mem-graph-auth-context', 'shared', { characterId: 'other-character' })
196
+ const visible = graph.createEntity({ libraryId: library.id, name: 'Visible graph entity', aliases: ['visible-alias'], status: 'confirmed' })
197
+ const secret = graph.createEntity({ libraryId: library.id, name: 'Secret-only graph entity', aliases: ['secret-alias'], status: 'confirmed' })
198
+ const hidden = graph.createEntity({ libraryId: library.id, name: 'Context-only graph entity', aliases: ['context-alias'], status: 'confirmed' })
199
+ for (const [memoryId, entity] of [['mem-graph-auth-visible', visible], ['mem-graph-auth-secret', secret], ['mem-graph-auth-context', hidden]]) {
200
+ graph.linkEntries({ libraryId: library.id, fromId: memoryId, toId: entity.id, kind: 'person', note: 'Authorization fixture edge.' })
201
+ }
202
+
203
+ for (const prefix of prefixes) {
204
+ const post = payload => send(prefix.route, prefix.base + '/listEntities', {
205
+ method: 'POST', body: envelope('listEntities', payload),
206
+ })
207
+ const authorized = await post({ libraryId: library.id, sessionId, entityId: secret.id })
208
+ assert.equal(authorized.res.status, 200)
209
+ const result = JSON.parse(authorized.res.text).result
210
+ assert.equal(result.ok, true)
211
+ assert.deepEqual(result.value.items, [], `${prefix.name}: exact reads must not reveal entities referenced only by secret memory`)
212
+
213
+ const contextHidden = await post({ libraryId: library.id, sessionId, entityId: hidden.id })
214
+ assert.equal(JSON.parse(contextHidden.res.text).result.value.items.length, 0,
215
+ `${prefix.name}: exact reads must honor the bound conversation context`)
216
+
217
+ const allowed = await post({ libraryId: library.id, sessionId, entityId: visible.id })
218
+ const visibleItems = JSON.parse(allowed.res.text).result.value.items
219
+ assert.equal(visibleItems.length, 1)
220
+ assert.equal(visibleItems[0].id, visible.id)
221
+ assert.deepEqual(visibleItems[0].aliases, ['visible-alias'])
222
+
223
+ state.setSessionBinding(sessionId, { useLibrary: false })
224
+ const disabled = await post({ libraryId: library.id, sessionId, entityId: visible.id })
225
+ state.setSessionBinding(sessionId, { useLibrary: true })
226
+ const disabledResult = JSON.parse(disabled.res.text).result
227
+ assert.equal(disabledResult.ok, false, `${prefix.name}: private-memory off cannot degrade to unscoped management`)
228
+ assert.match(disabledResult.error.message, /disabled|off|enable|private|memory/i)
229
+
230
+ // Explicit session-less management remains a separate capability-authorized path.
231
+ const managed = await post({ libraryId: library.id, entityId: secret.id })
232
+ assert.deepEqual(JSON.parse(managed.res.text).result.value.items.map(row => row.id), [secret.id])
233
+ }
234
+ })
235
+
182
236
  test('UI and assets: both registered prefixes authorize, and 401/403 never serve or read', async () => {
183
237
  const cases = [
184
238
  { route: '/ui', expected: html, type: /text\/html/ },
@@ -525,7 +579,9 @@ const matrixRows = [
525
579
  // 工单 F:实体合并的读写面。合并矩阵只验证路由授权:不存在的实体在 200
526
580
  // 业务信封里报 unknown entity,403 必须在 dispatch 之前发生。
527
581
  { endpoint: 'suggestEntityMerges', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
582
+ { endpoint: 'listEntityMergeReviews', operation: 'read', payload: (lib) => ({ libraryId: lib.id, limit: 20 }) },
528
583
  { endpoint: 'mergeEntities', operation: 'write', payload: (lib) => ({ libraryId: lib.id, targetId: 'ent-matrix-target', sourceIds: ['ent-matrix-source'] }) },
584
+ { endpoint: 'setEntityMergeRejection', operation: 'write', payload: (lib) => ({ libraryId: lib.id, sourceId: 'ent-matrix-source', targetId: 'ent-matrix-target', rejected: true, confirmed: true }) },
529
585
  { endpoint: 'addMemory', operation: 'write', payload: (lib) => ({ libraryId: lib.id, content: 'matrix write body' }) },
530
586
  { endpoint: 'updateMemory', operation: 'write', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch', patch: { title: 'matrix retitled' } }) },
531
587
  { endpoint: 'archiveMemory', operation: 'archive', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch' }) },
@@ -76,13 +76,23 @@ test('the wall uses one bounded preview RPC, not N full-body requests', async ()
76
76
  state.updatePrivateIndex(library.id, index => {
77
77
  for (let i = 0; i < 500; i++) index.entries['mem-' + i] = { title: 't' + i, content: 'x'.repeat(1000), status: 'active', source: 'imagined' }
78
78
  })
79
- const response = await dispatch({}, 'browseWall', {})
79
+ const response = await dispatch({}, 'browseWall', { limit: 60, offset: 0 })
80
80
  assert.equal(response.total, 500)
81
- assert.equal(response.items.length, 300)
82
- assert.ok(response.items.every(item => item.preview.length <= 180 && !Object.hasOwn(item, 'content')))
81
+ assert.equal(response.items.length, 60, 'the first screen has a bounded preview page')
82
+ assert.ok(response.snapshotRevision)
83
+ const next = await dispatch({}, 'browseWall', { limit: 300, offset: 60, snapshotRevision: response.snapshotRevision })
84
+ assert.equal(next.total, response.total)
85
+ assert.equal(next.offset, 60)
86
+ assert.equal(next.snapshotRevision, response.snapshotRevision)
87
+ assert.equal(next.items.length, 300)
88
+ const loaded = [...response.items, ...next.items]
89
+ assert.equal(new Set(loaded.map(item => item.id)).size, 360, 'continuations do not overlap the first screen')
90
+ assert.ok(loaded.every(item => item.preview.length <= 180 && !Object.hasOwn(item, 'content')))
83
91
  const source = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
84
- assert.match(source, /call\('browseWall'/)
85
- assert.match(source, /function MemoryWallPanel/)
92
+ const wall = source.slice(source.indexOf('function MemoryWallPanel('), source.indexOf('function LexiconPanel('))
93
+ assert.match(wall, /useMemoryPages\(\{ call, method: 'browseWall', rowsKey: 'items'/)
94
+ assert.match(wall, /h\(MemoryPageMore, \{ pager, loaded: items.length, t \}\)/, 'continuation is reader-driven')
95
+ assert.ok(!wall.includes('const stream ='), 'mounting the wall cannot drain every page')
86
96
  })
87
97
  test('wall pools include review and inactive states; anchor is a view, not a fourth stored layer', () => {
88
98
  const source = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
@@ -159,11 +169,15 @@ test('fullscreen wall avoids the WebView2 compositor traps that dropped cards',
159
169
  assert.ok(!/backdrop-filter\s*:/.test(overlay), 'the overlay wrapper must not blur the host behind the iframe')
160
170
  assert.match(overlay, /background:var\(--dsw-alias-bg-base, #f4f5f9\)/, 'the iframe stays opaque while its page paints')
161
171
  // Late replies must not repaint the wall/browser after a newer library was picked.
162
- assert.match(client, /const requestId = \+\+browseRequest\.current/)
163
- assert.match(client, /const requestId = \+\+browseLibraryRequest\.current/)
172
+ const pager = client.slice(client.indexOf('function useMemoryPages('), client.indexOf('function MemoryPageMore('))
173
+ assert.match(client, /useMemoryPages\(\{ call, method: 'browseWall'/)
174
+ assert.match(client, /useMemoryPages\(\{ call, method: 'browseLibrary'/)
175
+ assert.match(pager, /if \(runtime\.current\?\.key !== key\) runtime\.current = null/, 'selector changes invalidate old replies during render')
176
+ assert.match(pager, /runtime\.current === page && page\.key === key/, 'only the current snapshot may publish')
177
+ assert.match(pager, /return \(\) => \{ runtime\.current = null \}/, 'unmount invalidates pending reads')
164
178
  assert.match(client, /const requestId = \+\+statsRequest\.current/)
165
179
  assert.match(client, /const requestId = \+\+reviewsRequest\.current/)
166
- assert.match(client, /if \(!current\(\)\) return/, 'stale browseWall replies are dropped')
180
+ assert.match(pager, /if \(!current\(\)\) return/, 'stale wall and library replies are dropped')
167
181
 
168
182
  const css = fs.readFileSync(new URL('../lib/webui/standalone.css', import.meta.url), 'utf8')
169
183
  const start = css.indexOf('html[data-standalone] .dshm-wall-item {')
@@ -200,13 +214,17 @@ test('single-library browseWall still carries global rows and F1/F2 metadata', a
200
214
 
201
215
  const wall = await dispatch({}, 'browseWall', { libraryId: library.id })
202
216
  assert.ok(wall.items.some((item) => item.id === 'mem-private-merge'), 'the authorized private row is present')
203
- // 记忆墙按 offset 逐批读完整库:分页不得改变 total,也不得重排(新到旧)。
204
- const wallPage = await dispatch({}, 'browseWall', { libraryId: library.id, limit: 1, offset: 1 })
217
+ // 单库墙的私有/全局混排必须在同一快照中续读,F1/F2 不因分页而丢失。
218
+ const wallFirst = await dispatch({}, 'browseWall', { libraryId: library.id, limit: 1, offset: 0 })
219
+ const wallPage = await dispatch({}, 'browseWall', { libraryId: library.id, limit: 1, offset: 1, snapshotRevision: wallFirst.snapshotRevision })
205
220
  assert.equal(wallPage.offset, 1)
206
221
  assert.equal(wallPage.total, wall.total, 'paging must not change the total')
222
+ assert.equal(wallFirst.total, wall.total)
223
+ assert.equal(wallPage.snapshotRevision, wallFirst.snapshotRevision)
207
224
  assert.equal(wallPage.items.length, 1)
208
- assert.equal(wallPage.items[0].id, wall.items[1].id, 'offset continues the same sorted list')
209
- const globalRow = wall.items.find((item) => item.id === 'gmem-linked')
225
+ const pagedItems = [...wallFirst.items, ...wallPage.items]
226
+ assert.deepEqual(pagedItems.map(item => item.id), wall.items.map(item => item.id), 'offset continues the same sorted private/global list')
227
+ const globalRow = pagedItems.find((item) => item.id === 'gmem-linked')
210
228
  assert.ok(globalRow, 'a single-library wall must keep the shared global scope')
211
229
  assert.equal(globalRow.libraryId, null)
212
230
  assert.equal(globalRow.links.length, 1)
@@ -218,11 +236,18 @@ test('single-library browseWall still carries global rows and F1/F2 metadata', a
218
236
  assert.equal(globalFile.links.length, 1)
219
237
  assert.deepEqual(globalFile.absorbedFrom, ['gmem-a', 'gmem-b'])
220
238
 
239
+ state.updatePrivateIndex(library.id, index => { index.entries['mem-private-merge'].title = 'changed after first page' })
240
+ await assert.rejects(() => dispatch({}, 'browseWall', { libraryId: library.id, limit: 1, offset: 1,
241
+ snapshotRevision: wallFirst.snapshotRevision }), error => error.code === 'MEMORY_CHANGED' && /MEMORY_CHANGED/.test(error.message),
242
+ 'a library write rejects the old private/global snapshot instead of silently skipping rows')
243
+
221
244
  const source = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
245
+ const clientWall = source.slice(source.indexOf('function MemoryWallPanel('), source.indexOf('function LexiconPanel('))
222
246
  assert.match(source, /wallAllBlocked/, 'the single-library fallback explains itself')
223
- assert.match(source, /const stream = async \(targetLibraryId\)/, 'the wall reads the library in batches')
224
- assert.match(source, /await stream\(firstLibraryId\)/, 'the wall retries the first library after an all-libraries 403')
225
- assert.match(source, /setMultiBlocked\(true\)/, 'the fallback disables the all-libraries option')
247
+ assert.match(clientWall, /useMemoryPages\(\{ call, method: 'browseWall'/, 'the wall uses snapshot-aware paging')
248
+ assert.match(clientWall, /onFailure: failure =>[\s\S]*403[\s\S]*setMultiBlocked\(true\); setLibraryId\(firstLibraryId\)/,
249
+ 'an aggregate 403 switches the shared pager to the first library and disables aggregate reads')
250
+ assert.match(clientWall, /h\(MemoryPageMore, \{ pager, loaded: items.length, t \}\)/, 'the fallback still pages only on demand')
226
251
  })
227
252
  test('the settings button preserves the host SPA and links to individual pages', () => {
228
253
  const client = fs.readFileSync(new URL('../lib/client.js', import.meta.url), 'utf8')
@@ -217,7 +217,8 @@ function host({
217
217
  headers.set(spec.sessionId, { cwd: spec.meta?.cwd || cwd })
218
218
  const record = makeRecord(spec.sessionId, spec.agentOptions)
219
219
  registry.set(spec.sessionId, record)
220
- await spec.setup?.(record.agent.ctx, record.agent)
220
+ const setupCommit = await spec.setup?.(record.agent.ctx, record.agent)
221
+ setupCommit?.commit()
221
222
  return record
222
223
  },
223
224
  }