dsh-memu-memory 1.3.12 → 1.3.14

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.
@@ -0,0 +1,159 @@
1
+ // 环境自检与修复动作的回归测试。
2
+ // 这套代码的价值全在"故障可见 + 修得动":检查项漏报等于故障继续静默,
3
+ // 修复动作乱进安全名单等于半夜动用户数据。所以两条都要钉住。
4
+ import test from 'node:test'
5
+ import assert from 'node:assert/strict'
6
+ import fs from 'node:fs'
7
+ import os from 'node:os'
8
+ import path from 'node:path'
9
+
10
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-memory-envcheck-'))
11
+ process.env.DSH_MEMU_HOME = home
12
+ process.env.DSH_MEMU_MEMORY_HOME = home
13
+
14
+ const env = await import('../lib/environment-check.js')
15
+ const diag = await import('../lib/diagnostics.js')
16
+ const paths = await import('../lib/paths.js')
17
+
18
+ test.after(() => {
19
+ try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
20
+ })
21
+
22
+ test.beforeEach(() => {
23
+ diag.clearDiagnostics()
24
+ paths.setLockEventSink(null)
25
+ paths.setWarnSink(null)
26
+ // 上一个用例留下的锁文件会被"整个数据目录"的扫描看见,先清干净再断言。
27
+ try { fs.rmSync(path.join(home, 'locks'), { recursive: true, force: true }) } catch {}
28
+ })
29
+
30
+ function lockFile(name, payload, ageMs = 0) {
31
+ const dir = path.join(home, 'locks')
32
+ fs.mkdirSync(dir, { recursive: true })
33
+ const file = path.join(dir, `${name}.lock`)
34
+ fs.writeFileSync(file, payload)
35
+ if (ageMs) {
36
+ const when = new Date(Date.now() - ageMs)
37
+ fs.utimesSync(file, when, when)
38
+ }
39
+ return file
40
+ }
41
+
42
+ // ---------------------------------------------------------------- 检查项
43
+
44
+ test('every item carries the shape the diagnostics page renders', () => {
45
+ const report = env.runEnvironmentCheck()
46
+ assert.ok(Array.isArray(report.items) && report.items.length > 0, 'a check must produce items')
47
+ for (const entry of report.items) {
48
+ assert.ok(entry.id, 'item without id')
49
+ assert.ok(typeof entry.title === 'string' && entry.title.length > 0, `${entry.id} has no title`)
50
+ assert.ok(['ok', 'warn', 'error', 'skipped'].includes(entry.level), `${entry.id} has level ${entry.level}`)
51
+ assert.equal(typeof entry.ok, 'boolean')
52
+ }
53
+ assert.equal(typeof report.ok, 'boolean')
54
+ assert.equal(typeof report.checkedAt, 'string')
55
+ assert.ok(report.counts && typeof report.counts.ok === 'number')
56
+ })
57
+
58
+ test('a writable data dir is reported ok, so the check itself is not the alarm', () => {
59
+ const report = env.runEnvironmentCheck()
60
+ const dataDir = report.items.find(entry => entry.id === 'data-dir')
61
+ assert.ok(dataDir, 'data-dir must always be checked first')
62
+ assert.equal(dataDir.ok, true)
63
+ })
64
+
65
+ test('an abandoned lock is reported with the repair that clears it', () => {
66
+ lockFile('abandoned', '', 30_000)
67
+ const report = env.runEnvironmentCheck()
68
+ const locks = report.items.find(entry => entry.id === 'locks')
69
+ assert.ok(locks, 'locks must be checked')
70
+ assert.equal(locks.ok, false)
71
+ assert.equal(locks.level, 'warn')
72
+ assert.equal(locks.repair, 'release-stale-locks')
73
+ assert.equal(locks.auto, true, 'clearing provably abandoned locks is safe enough to run at startup')
74
+ assert.match(locks.detail, /abandoned\.lock/)
75
+ assert.ok(report.repairs.includes('release-stale-locks'))
76
+ })
77
+
78
+ test('a healthy live lock is not reported as a problem', () => {
79
+ lockFile('live', `${process.ppid}\n` + new Date().toISOString())
80
+ const report = env.runEnvironmentCheck()
81
+ const locks = report.items.find(entry => entry.id === 'locks')
82
+ assert.ok(locks)
83
+ assert.equal(locks.ok, true)
84
+ })
85
+
86
+ // ---------------------------------------------------------------- 修复门禁
87
+
88
+ test('repairEnvironment refuses to run without an explicit confirmation', async () => {
89
+ await assert.rejects(
90
+ () => env.repairEnvironment({ actions: ['release-stale-locks'] }),
91
+ /confirmed === true/,
92
+ )
93
+ })
94
+
95
+ test('a repair that runs is recorded, and the report reflects the new state', async () => {
96
+ const abandoned = lockFile('abandoned', '', 30_000)
97
+ const outcome = await env.repairEnvironment({ actions: ['release-stale-locks'], confirmed: true })
98
+ assert.equal(outcome.ok, true)
99
+ assert.equal(outcome.results.length, 1)
100
+ assert.equal(fs.existsSync(abandoned), false, 'the repair must actually remove the lock')
101
+ const repaired = diag.listDiagnostics({}).items.find(row => row.code === 'MEMU_DIAGNOSTIC_REPAIRED')
102
+ assert.ok(repaired, 'a successful repair is recorded in diagnostics')
103
+ assert.equal(repaired.detail.action, 'release-stale-locks')
104
+ const locks = outcome.after.items.find(entry => entry.id === 'locks')
105
+ assert.equal(locks.ok, true, 'the post-repair check must show the fix')
106
+ })
107
+
108
+ test('a repair that fails is still recorded, with the error', async () => {
109
+ const outcome = await env.repairEnvironment({ actions: ['not-a-real-action'], confirmed: true })
110
+ assert.equal(outcome.ok, false)
111
+ assert.equal(outcome.results[0].ok, false)
112
+ assert.match(outcome.results[0].detail, /unknown repair action/)
113
+ const failed = diag.listDiagnostics({}).items.find(row => row.code === 'MEMU_DIAGNOSTIC_REPAIR_FAILED')
114
+ assert.ok(failed, 'a failed repair must not disappear')
115
+ assert.equal(failed.level, 'error')
116
+ assert.equal(failed.detail.action, 'not-a-real-action')
117
+ })
118
+
119
+ test('startup auto-repair only touches the safe list', async () => {
120
+ assert.deepEqual([...env.SAFE_REPAIRS].sort(), ['release-stale-locks', 'repoint-runtime-dir', 'resign-vector-profile'])
121
+ for (const action of env.MANUAL_REPAIRS) {
122
+ assert.ok(!env.SAFE_REPAIRS.includes(action), `${action} must never run automatically`)
123
+ }
124
+ const blocked = await env.autoRepairEnvironment({ actions: ['reinstall-engine'] })
125
+ assert.equal(blocked.changed, false)
126
+ assert.deepEqual(blocked.results, [], 'a manual action asked for by mistake must be ignored, not run')
127
+ })
128
+
129
+ test('every repair action has a label, so the page never shows a bare slug', () => {
130
+ for (const action of [...env.SAFE_REPAIRS, ...env.MANUAL_REPAIRS]) {
131
+ assert.ok(env.REPAIR_LABELS[action], `${action} has no label`)
132
+ }
133
+ })
134
+
135
+ // ---------------------------------------------------------------- 运行时目录发现
136
+
137
+ test('the managed runtime root is discovered where the service actually installs it', async () => {
138
+ // 真实布局是 downloads/embeddings/runtime/<key>(与模型同级)。早先这里只看
139
+ // downloads/runtime,于是"运行时明明装着"也会报"没有安装",把用户推去重下 40MB。
140
+ const vp = await import('../lib/vector-profile.js')
141
+ const managed = path.join(home, 'downloads', 'embeddings', 'runtime', 'onnxruntime-node@test@napi-v6@win32-x64-abc')
142
+ const legacy = path.join(home, 'downloads', 'runtime', 'onnxruntime-node@test@napi-v6@win32-x64-def')
143
+ for (const dir of [managed, legacy]) {
144
+ fs.mkdirSync(path.join(dir, 'node_modules', 'onnxruntime-node'), { recursive: true })
145
+ fs.writeFileSync(path.join(dir, 'node_modules', 'onnxruntime-node', 'package.json'), '{"name":"onnxruntime-node"}')
146
+ }
147
+ const candidates = vp.runtimeDirCandidates().map(entry => path.resolve(entry.dir))
148
+ assert.ok(candidates.includes(path.resolve(managed)), 'the managed root must be scanned')
149
+ assert.ok(candidates.includes(path.resolve(legacy)), 'the legacy root keeps working')
150
+ })
151
+
152
+ test('a runtime directory without its package.json is not offered as a candidate', async () => {
153
+ // 真实事故:运行时目录只剩 bin/,package.json 与 lib/ 都没了 → 重指过去仍然 MODULE_NOT_FOUND。
154
+ const vp = await import('../lib/vector-profile.js')
155
+ const hollow = path.join(home, 'downloads', 'embeddings', 'runtime', 'hollow-key')
156
+ fs.mkdirSync(path.join(hollow, 'node_modules', 'onnxruntime-node', 'bin'), { recursive: true })
157
+ const candidates = vp.runtimeDirCandidates().map(entry => path.resolve(entry.dir))
158
+ assert.ok(!candidates.includes(path.resolve(hollow)))
159
+ })
@@ -41,13 +41,13 @@ test('disconnected 200-node layout stays finite, separated and framed without bo
41
41
  layout.dispose()
42
42
  })
43
43
 
44
- test('invalid/self edges are ignored, input bounded, node order deterministic', () => {
44
+ test('invalid/self edges are ignored, all unique nodes retained, node order deterministic', () => {
45
45
  const data = graph(250, false)
46
46
  data.edges.push({ from: 'missing', to: 'n000' }, { from: 'n000', to: 'n000' })
47
47
  const a = createForceLayout(), b = createForceLayout()
48
48
  a.update(data)
49
- b.update({ nodes: [...data.nodes.slice(0, 200)].reverse(), edges: [] })
50
- assert.equal(a.nodes.length, 200); assert.equal(a.edges.length, 0)
49
+ b.update({ nodes: [...data.nodes, data.nodes[0]].reverse(), edges: [] })
50
+ assert.equal(a.nodes.length, 250); assert.equal(b.nodes.length, 250); assert.equal(a.edges.length, 0)
51
51
  a.settle(); b.settle()
52
52
  assert.deepEqual(a.nodes.map(n => [n.id, n.x, n.y]), b.nodes.map(n => [n.id, n.x, n.y]),
53
53
  'the jitter must be deterministic, never Math.random')
@@ -226,6 +226,30 @@ function harness(reducedMotion = true) {
226
226
  return { view, flush, emit, arcs, texts, frames, focuses, handlers, windowHandlers, getPaints: () => paints }
227
227
  }
228
228
 
229
+ test('view snapshots retain multiple clusters and entities beyond the first 200 nodes', () => {
230
+ const data = graph(250, false)
231
+ for (let i = 0; i < 249; i++) {
232
+ if (i !== 119) data.edges.push({ from: data.nodes[i].id, to: data.nodes[i + 1].id })
233
+ }
234
+ for (const [id, from] of [['ent-first', 'n119'], ['ent-last', 'n249']]) {
235
+ data.nodes.push({ id, title: id, kind: 'person', strength: .5 })
236
+ data.edges.push({ from, to: id })
237
+ }
238
+ const h = harness()
239
+ h.view.update(data); h.flush()
240
+ const snapshot = h.view.snapshot()
241
+ assert.equal(snapshot.length, 252)
242
+ assert.deepEqual(new Set(snapshot.map(node => node.id)), new Set(data.nodes.map(node => node.id)))
243
+ for (const id of ['ent-first', 'ent-last']) {
244
+ const entity = snapshot.find(node => node.id === id)
245
+ assert.equal(entity.degree, 1, 'late entity links must survive canvas ingestion')
246
+ assert.ok(Number.isFinite(entity.x) && Number.isFinite(entity.y))
247
+ }
248
+ h.view.update({ nodes: [...data.nodes, data.nodes[0]].reverse(), edges: [...data.edges].reverse() }); h.flush()
249
+ assert.deepEqual(h.view.snapshot(), snapshot, 'equivalent refreshed input preserves every node and its position')
250
+ h.view.dispose()
251
+ })
252
+
229
253
  test('the detailed layer actually paints labels and the label switch silences them', () => {
230
254
  const h = harness()
231
255
  h.view.update(graph(10)); h.flush()
@@ -383,4 +407,8 @@ test('shipped browser bundle exposes the controller with no runtime npm imports'
383
407
  assert.equal(typeof api.placeLabels, 'function')
384
408
  assert.equal(api.DEFAULT_OPTIONS.center, 0)
385
409
  assert.equal(api.DEFAULT_OPTIONS.clusterScope, true)
410
+ const layout = api.createForceLayout()
411
+ layout.update(graph(251, false))
412
+ assert.equal(layout.nodes.length, 251, 'the shipped browser bundle must retain nodes beyond 200')
413
+ layout.dispose()
386
414
  })
@@ -102,6 +102,116 @@ test('graphs cap nodes at 200 and the recall carries at most two pointers', asyn
102
102
  assert.ok((await memory.privateRecall({ exec, query: 'mem-2' })).files[0].related.length <= 2)
103
103
  })
104
104
 
105
+ test('graph pagination reaches entities after 200 memories and returns each cross-page edge once', () => {
106
+ const { libraryId } = state.ensureSession('graph-pages', { cwd: path.join(home, 'rp-pages'), agentPreset: 'rp' })
107
+ const confirmed = graph.createEntity({ libraryId, name: 'Late confirmed', status: 'confirmed' })
108
+ const provisional = graph.createEntity({ libraryId, name: 'Late provisional' })
109
+ const entries = Object.fromEntries(Array.from({ length: 205 }, (_, i) => [
110
+ `mem-${i}`, { title: `node ${i}`, status: 'active', visibility: 'shared', domain: 'pages' },
111
+ ]))
112
+ entries['mem-0'].links = [{ to: 'mem-204', kind: 'event' }, { to: confirmed.id, kind: 'person' }]
113
+ entries['mem-204'].links = [{ to: 'mem-0', kind: 'relation' }, { to: provisional.id, kind: 'person' }]
114
+ state.savePrivateIndex(libraryId, { entries })
115
+ const edgePairs = page => page.edges.map(edge => [edge.from, edge.to])
116
+ const legacy = graph.getGraph({ libraryId, limit: 5000 })
117
+ assert.equal(legacy.nodes.length, 200)
118
+ assert.equal(legacy.limit, 200)
119
+ assert.equal(legacy.truncated, true)
120
+ assert.equal(legacy.total, undefined)
121
+ assert.equal(legacy.nextOffset, undefined)
122
+ assert.deepEqual(legacy.edges, [], 'legacy edges still require both endpoints in the result')
123
+
124
+ const first = graph.getGraph({ libraryId, offset: 0, limit: 5000 })
125
+ assert.deepEqual(first.nodes.map(node => node.id), legacy.nodes.map(node => node.id))
126
+ assert.equal(first.total, 207)
127
+ assert.equal(first.nextOffset, 200)
128
+ assert.equal(first.truncated, true)
129
+ assert.deepEqual(edgePairs(first), [['mem-0', 'mem-204'], ['mem-0', confirmed.id]])
130
+
131
+ const last = graph.getGraph({ libraryId, offset: first.nextOffset })
132
+ assert.equal(last.nodes.length, 7)
133
+ assert.equal(last.total, first.total)
134
+ assert.equal(last.nextOffset, null)
135
+ assert.equal(last.truncated, false)
136
+ assert.deepEqual(last.nodes.filter(node => node.kind === 'person').map(node => [node.id, node.status]), [
137
+ [confirmed.id, 'confirmed'], [provisional.id, 'provisional'],
138
+ ])
139
+ assert.deepEqual(edgePairs(last), [['mem-204', 'mem-0'], ['mem-204', provisional.id]])
140
+ assert.equal(new Set([...first.nodes, ...last.nodes].map(node => node.id)).size, first.total)
141
+
142
+ const fullLast = graph.getGraph({ libraryId, offset: 205, limit: 2 })
143
+ assert.equal(fullLast.nodes.length, 2)
144
+ assert.equal(fullLast.nextOffset, null)
145
+ assert.equal(fullLast.truncated, false, 'a full final page has no remainder')
146
+ const beyond = graph.getGraph({ libraryId, offset: 500 })
147
+ assert.deepEqual([beyond.nodes, beyond.edges, beyond.total, beyond.nextOffset, beyond.truncated], [[], [], 207, null, false])
148
+
149
+ const focused = graph.getGraph({ libraryId, focusId: 'mem-0', offset: 500, depth: 1 })
150
+ assert.deepEqual(focused.nodes.map(node => node.id), ['mem-0', 'mem-204', confirmed.id])
151
+ assert.equal(focused.nextOffset, undefined, 'offset never changes bounded focus traversal')
152
+ })
153
+
154
+ test('graph domain matches normalized exact memory domains and derives only their linked entities', () => {
155
+ const { libraryId } = state.ensureSession('graph-domains', { cwd: path.join(home, 'rp-domains'), agentPreset: 'rp' })
156
+ const coding = graph.createEntity({ libraryId, name: 'Coding contact' })
157
+ const other = graph.createEntity({ libraryId, name: 'Other contact' })
158
+ const orphan = graph.createEntity({ libraryId, name: 'Unrelated orphan' })
159
+ state.savePrivateIndex(libraryId, { entries: {
160
+ 'mem-code': { title: 'coding', domain: ' Coding ', links: [
161
+ { to: coding.id, kind: 'person' }, { to: 'mem-code-2', kind: 'event' },
162
+ { to: 'mem-legacy', kind: 'relation', note: 'cross-domain evidence' }, { to: 'mem-other', kind: 'event' },
163
+ { to: 'mem-removed', kind: 'relation' },
164
+ ] },
165
+ 'mem-code-2': { title: 'also coding', domain: 'CODING' },
166
+ 'mem-legacy': { title: 'legacy' },
167
+ 'mem-other': { title: 'other', domain: 'coding-extra', links: [
168
+ { to: other.id, kind: 'person' }, { to: 'mem-code', kind: 'event' },
169
+ ] },
170
+ } })
171
+ const page = graph.getGraph({ libraryId, offset: 0, domain: ' CoDinG ', includeOrphans: true })
172
+ assert.deepEqual(page.domains, ['coding', 'coding-extra', 'general'])
173
+ assert.deepEqual(page.nodes.map(node => node.id), ['mem-code', 'mem-code-2', coding.id, 'mem-removed'])
174
+ assert.deepEqual(page.nodes.map(node => node.domain), ['coding', 'coding', undefined, undefined])
175
+ assert.equal(page.nodes.find(node => node.id === 'mem-removed').missing, true, 'genuine dangling links still have placeholders')
176
+ assert.equal(page.nodes.find(node => node.id === 'mem-code').degree, 3, 'out-of-domain neighbors do not even affect degree')
177
+ assert.deepEqual(page.edges.map(edge => edge.to), [coding.id, 'mem-code-2', 'mem-removed'])
178
+ assert.ok(!JSON.stringify(page).includes('cross-domain evidence'))
179
+ assert.deepEqual(graph.getGraph({ libraryId, domain: ' GENERAL ' }).nodes.map(node => [node.id, node.domain]), [['mem-legacy', 'general']])
180
+ assert.ok(graph.getGraph({ libraryId, domain: '  ', includeOrphans: true }).nodes.some(node => node.id === orphan.id))
181
+ assert.throws(() => graph.getGraph({ libraryId, focusId: orphan.id, domain: 'coding' }), /unknown or inaccessible graph focus/)
182
+ assert.throws(() => graph.getGraph({ libraryId, focusId: 'mem-other', domain: 'coding' }), /unknown or inaccessible graph focus/)
183
+ const none = graph.getGraph({ libraryId, offset: 0, domain: 'unknown', includeOrphans: true })
184
+ assert.deepEqual([none.nodes, none.edges, none.total, none.nextOffset, none.truncated], [[], [], 0, null, false])
185
+ assert.deepEqual(none.domains, page.domains, 'suggestions are gathered before applying the selected domain')
186
+ })
187
+
188
+ test('paged graph keeps bound-library, session eligibility and context checks before collecting domains or edges', () => {
189
+ const { libraryId } = state.ensureSession('graph-page-session', { cwd: path.join(home, 'rp-page-session'), agentPreset: 'rp' })
190
+ const exec = { agent: { session: { header: { id: 'graph-page-session' } } } }
191
+ const visible = graph.createEntity({ libraryId, name: 'Visible contact' })
192
+ const hidden = graph.createEntity({ libraryId, name: 'Hidden contact' })
193
+ state.savePrivateIndex(libraryId, { entries: {
194
+ 'mem-visible': { title: 'visible', status: 'active', visibility: 'shared', domain: 'coding', links: [
195
+ { to: visible.id, kind: 'person' }, { to: 'mem-secret', kind: 'relation' },
196
+ { to: 'mem-other-context', kind: 'relation' }, { to: 'mem-archived', kind: 'relation' },
197
+ ] },
198
+ 'mem-secret': { title: 'secret', status: 'active', visibility: 'secret', domain: 'secret-domain', links: [{ to: hidden.id, kind: 'person' }] },
199
+ 'mem-other-context': { title: 'private context', status: 'active', visibility: 'shared', domain: 'coding', context: { characterId: 'other' } },
200
+ 'mem-archived': { title: 'archived', status: 'archived', visibility: 'shared', domain: 'coding' },
201
+ } })
202
+ const page = graph.getGraph({ exec, libraryId, offset: 0, limit: 1, domain: 'coding', includeOrphans: true })
203
+ assert.deepEqual(page.nodes.map(node => node.id), ['mem-visible'])
204
+ assert.deepEqual(page.domains, ['coding'])
205
+ assert.deepEqual(page.edges.map(edge => edge.to), [visible.id])
206
+ assert.equal(page.total, 2)
207
+ const last = graph.getGraph({ exec, libraryId, offset: page.nextOffset, limit: 1, domain: 'coding', includeOrphans: true })
208
+ assert.deepEqual(last.nodes.map(node => node.id), [visible.id])
209
+ assert.equal(last.nextOffset, null)
210
+ assert.throws(() => graph.getGraph({ exec, libraryId, focusId: hidden.id, offset: 0 }), /unknown or inaccessible graph focus/)
211
+ const otherLibrary = state.ensureSession('graph-page-unbound', { cwd: path.join(home, 'rp-page-unbound'), agentPreset: 'rp' }).libraryId
212
+ assert.throws(() => graph.getGraph({ exec, libraryId: otherLibrary, offset: 0 }), /library is not bound to this conversation/)
213
+ })
214
+
105
215
  test('relationship snapshots preserve unknowns, evidence, boundaries and previous versions', () => {
106
216
  const a = graph.createEntity({ libraryId, name: 'A' })
107
217
  const b = graph.createEntity({ libraryId, name: 'B' })
@@ -163,6 +163,101 @@ test('lexicon propose writes an active entry immediately; search only sees activ
163
163
  dispose()
164
164
  })
165
165
 
166
+ function namedEntityFixture(suffix, content, extra = {}) {
167
+ const id = 'tools-named-' + suffix
168
+ const cwd = path.join(home, id)
169
+ const binding = state.ensureSession(id, { cwd, agentPreset: 'rp' })
170
+ const namedExec = { agent: { session: { header: { id, cwd, agentPreset: 'rp' } } } }
171
+ state.savePrivateIndex(binding.libraryId, { version: 1, entries: {
172
+ 'mem-source': { title: '来访记录', content, status: 'active', visibility: 'shared', layer: 'long_term', ...extra },
173
+ } })
174
+ return { binding, namedExec }
175
+ }
176
+
177
+ for (const [i, name] of ['忆组件', '主人一', '人一', '主人一说'].entries()) {
178
+ test('new named entity rejects an unsupported fragment: ' + name, async () => {
179
+ const { tools, dispose } = fakeCtx()
180
+ const { binding, namedExec } = namedEntityFixture('fragment-' + i, '记忆组件负责保存资料,主人一说话就会得到回应。')
181
+ const link = tools.find(tool => tool.name === 'memu_private_link')
182
+ const graph = await import('../lib/graph.js')
183
+ try {
184
+ const reply = await link.execute({ from: 'mem-source', entity: { name, kind: 'person' }, kind: 'person', note: '原文出现了相同片段,因此把它作为同一人物关联。' }, namedExec)
185
+ assert.match(reply, /完整名称|complete name/, 'a substring is not evidence of a complete identity')
186
+ assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 0, 'rejection creates no entity')
187
+ assert.deepEqual(state.loadPrivateIndex(binding.libraryId).entries['mem-source'].links || [], [], 'rejection creates no link')
188
+ } finally { dispose() }
189
+ })
190
+ }
191
+
192
+ test('new named entity validates source and link before creating any entity', async () => {
193
+ const { tools, dispose } = fakeCtx()
194
+ const link = tools.find(tool => tool.name === 'memu_private_link')
195
+ const graph = await import('../lib/graph.js')
196
+ const cases = [
197
+ { suffix: 'missing', args: { from: 'mem-missing' } },
198
+ { suffix: 'secret', extra: { visibility: 'secret' } },
199
+ { suffix: 'archived', extra: { status: 'archived' } },
200
+ { suffix: 'note', args: { note: 'short' } },
201
+ { suffix: 'confidence', args: { confidence: 2 } },
202
+ { suffix: 'kind', args: { kind: 'typo' } },
203
+ { suffix: 'person-target', args: { entity: { name: '阿兰', kind: 'thing' } } },
204
+ { suffix: 'limit', extra: { links: Array.from({ length: 100 }, (_, i) => ({ to: 'mem-limit-' + i, kind: 'event' })) } },
205
+ ]
206
+ try {
207
+ for (const item of cases) {
208
+ const { binding, namedExec } = namedEntityFixture(item.suffix, '她叫阿兰,今天来送信。', item.extra)
209
+ const reply = await link.execute({ from: 'mem-source', entity: { name: '阿兰', kind: 'person' }, kind: 'person', note: '原文写着她叫阿兰,这封信由她送来。', ...item.args }, namedExec)
210
+ assert.match(reply, /error/, item.suffix + ' must be rejected')
211
+ assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 0, item.suffix + ' leaves no orphan entity')
212
+ }
213
+ } finally { dispose() }
214
+ })
215
+
216
+ test('new named entities require evidence in source memory rather than an invented note', async () => {
217
+ const { tools, dispose } = fakeCtx()
218
+ const link = tools.find(tool => tool.name === 'memu_private_link')
219
+ const graph = await import('../lib/graph.js')
220
+ try {
221
+ for (const [suffix, name, content] of [
222
+ ['note-spoof', '阿兰', '今天由一位邻居送来一封信。'],
223
+ ['latin-fragment', 'alice', 'malice appeared in the log.'],
224
+ ]) {
225
+ const { binding, namedExec } = namedEntityFixture(suffix, content)
226
+ const reply = await link.execute({ from: 'mem-source', entity: { name, kind: 'person' }, kind: 'person', note: '据我推测,这位邻居的完整名字是「' + name + '」。' }, namedExec)
227
+ assert.match(reply, /完整名称|complete name/)
228
+ assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 0)
229
+ }
230
+ } finally { dispose() }
231
+ })
232
+
233
+ test('complete quoted and introduced names remain usable and existing aliases are reused', async () => {
234
+ const { tools, dispose } = fakeCtx()
235
+ const link = tools.find(tool => tool.name === 'memu_private_link')
236
+ const graph = await import('../lib/graph.js')
237
+ try {
238
+ for (const [i, name, content] of [
239
+ [0, '阿兰', '她叫阿兰,今天来送信。'],
240
+ [1, '小柚', '「小柚」今天来送信。'],
241
+ [2, '主人一', '这个角色自称「主人一」,这是完整昵称。'],
242
+ [3, 'Alice', 'Alice delivered the letter.'],
243
+ [4, 'Old Zhou', 'Old Zhou delivered the letter.'],
244
+ ]) {
245
+ const { binding, namedExec } = namedEntityFixture('positive-' + i, content)
246
+ const reply = await link.execute({ from: 'mem-source', entity: { name, kind: 'person' }, kind: 'person', note: '原文明确写出完整名称 ' + name + ',关联这个同一人物。' }, namedExec)
247
+ const result = JSON.parse(reply)
248
+ const entity = graph.listEntities({ libraryId: binding.libraryId }).items.find(item => item.id === result.to)
249
+ assert.equal(entity.name, name)
250
+ assert.equal(entity.status, 'provisional', 'evidence of a full name alone is not user confirmation')
251
+ }
252
+ const { binding, namedExec } = namedEntityFixture('alias', '这位邻居送来一封信。')
253
+ const existing = graph.createEntity({ libraryId: binding.libraryId, name: '周宁', kind: 'person', aliases: ['Old Zhou'], status: 'confirmed' })
254
+ graph.linkEntries({ libraryId: binding.libraryId, fromId: 'mem-source', toId: existing.id, kind: 'person', note: '先前已由用户确认这位邻居的身份。' })
255
+ const result = JSON.parse(await link.execute({ from: 'mem-source', entity: { name: 'OLD ZHOU', kind: 'person' }, kind: 'person', note: '复用用户此前已经确认的同一人物别名。' }, namedExec))
256
+ assert.equal(result.to, existing.id)
257
+ assert.equal(graph.listEntities({ libraryId: binding.libraryId }).total, 1)
258
+ } finally { dispose() }
259
+ })
260
+
166
261
  test('link suggest refreshes deterministic mention edges and returns only uncertain candidates', async () => {
167
262
  const { tools, dispose } = fakeCtx()
168
263
  const cwd = path.join(home, 'project-links')
@@ -520,6 +520,7 @@ const MATRIX_SHA = 'a'.repeat(64)
520
520
  const matrixRows = [
521
521
  { endpoint: 'getMemory', operation: 'read', payload: (lib) => ({ libraryId: lib.id, id: 'mem-matrix-scratch' }) },
522
522
  { endpoint: 'browseWall', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
523
+ { endpoint: 'getGraph', operation: 'read', payload: (lib) => ({ libraryId: lib.id, offset: 0, domain: 'coding' }) },
523
524
  { endpoint: 'getStats', operation: 'read', payload: (lib) => ({ libraryId: lib.id }) },
524
525
  // 工单 F:实体合并的读写面。合并矩阵只验证路由授权:不存在的实体在 200
525
526
  // 业务信封里报 unknown entity,403 必须在 dispatch 之前发生。