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
@@ -0,0 +1,419 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import crypto from 'node:crypto'
4
+ import fs from 'node:fs'
5
+ import os from 'node:os'
6
+ import path from 'node:path'
7
+
8
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-graph-session-auth-'))
9
+ process.env.DSH_MEMU_HOME = home
10
+ process.env.DSH_MEMU_MEMORY_HOME = home
11
+
12
+ const state = await import('../lib/state.js')
13
+ const graph = await import('../lib/graph.js')
14
+ const suppression = await import('../lib/auto-link/suppression.js')
15
+ const { registerRpc } = await import('../lib/rpc.js')
16
+ const { indexDir } = await import('../lib/paths.js')
17
+
18
+ const routes = []
19
+ const authorization = { calls: 0, requests: [], allowed: true }
20
+ registerRpc({
21
+ inject: (_deps, build) => build({
22
+ effect: fn => { const dispose = fn(); return typeof dispose === 'function' ? dispose : () => {} },
23
+ webServer: { register: route => { routes.push(route); return () => {} } },
24
+ connection: {
25
+ requestRejection: () => undefined,
26
+ authorizeLibrary: async (_request, details) => {
27
+ authorization.calls += 1
28
+ authorization.requests.push(details)
29
+ return authorization.allowed
30
+ },
31
+ },
32
+ logger: {},
33
+ }),
34
+ })
35
+ const route = routes.find(item => item.path === '/dsh-memu-memory')
36
+ assert.equal(typeof route?.handler, 'function')
37
+
38
+ test.after(() => {
39
+ try { state.flushState() } finally { fs.rmSync(home, { recursive: true, force: true }) }
40
+ })
41
+
42
+ function response() {
43
+ const chunks = []
44
+ let finish
45
+ const done = new Promise(resolve => { finish = resolve })
46
+ return {
47
+ status: 0,
48
+ headersSent: false,
49
+ done,
50
+ writeHead(status, headers = {}) { this.status = status; this.headersSent = true; this.headers = headers },
51
+ write(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); return true },
52
+ end(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); finish() },
53
+ get text() { return Buffer.concat(chunks).toString('utf8') },
54
+ }
55
+ }
56
+
57
+ async function post(method, payload) {
58
+ const res = response()
59
+ const envelope = { type: 'client-request', rpcId: crypto.randomUUID(), method, payload }
60
+ const req = {
61
+ method: 'POST', url: `/dsh-memu-memory/${method}`, headers: {},
62
+ async *[Symbol.asyncIterator]() { yield Buffer.from(JSON.stringify(envelope)) },
63
+ }
64
+ await route.handler(req, res)
65
+ await res.done
66
+ assert.equal(res.status, 200, `${method} uses the registered HTTP RPC route`)
67
+ return JSON.parse(res.text).result
68
+ }
69
+
70
+ function entityFile(libraryId) { return path.join(indexDir(), `${libraryId}.entities.json`) }
71
+ function privateIndexFile(libraryId) { return path.join(indexDir(), `${libraryId}.json`) }
72
+ function suppressionFile(libraryId) { return path.join(indexDir(), `${libraryId}.link-suppression.json`) }
73
+
74
+ function snapshot(libraryId) {
75
+ return Object.fromEntries([entityFile(libraryId), privateIndexFile(libraryId), suppressionFile(libraryId)].map(file => [
76
+ path.basename(file), fs.existsSync(file) ? fs.readFileSync(file) : null,
77
+ ]))
78
+ }
79
+
80
+ function assertSnapshot(libraryId, before, message) {
81
+ const after = snapshot(libraryId)
82
+ for (const file of Object.keys(before)) {
83
+ if (before[file] === null) assert.equal(after[file], null, `${message}: ${file} remains absent`)
84
+ else assert.deepEqual(after[file], before[file], `${message}: ${file} bytes are unchanged`)
85
+ }
86
+ }
87
+
88
+ function memory(title, content, { visibility = 'shared', context, links = [] } = {}) {
89
+ return {
90
+ title, content, status: 'active', layer: 'long_term', domain: 'rp', visibility,
91
+ disclosure: 'can_tell', source: 'user_said', ...(context ? { context } : {}), links,
92
+ createdAt: '2026-11-30T00:00:00.000Z', updatedAt: '2026-11-30T00:00:00.000Z',
93
+ }
94
+ }
95
+
96
+ function makeLink(to, source = 'user') {
97
+ return { to, kind: 'person', note: 'Synthetic authorization fixture reference.', confidence: 0.9, source }
98
+ }
99
+
100
+ function makeFixture(label = 'fixture') {
101
+ const library = state.createLibrary({ name: `graph-session-auth-${label}`, cwd: path.join(home, label) })
102
+ const sessionId = `graph-auth-session-${crypto.randomUUID()}`
103
+ state.setSessionBinding(sessionId, {
104
+ libraryId: library.id, scopeKey: library.scopeKey, useLibrary: true, useGlobal: false,
105
+ domainOverride: 'rp', memoryContext: { characterId: 'authorized-character' },
106
+ })
107
+ const makePair = (prefix, names, status = 'confirmed') => names.map(name => graph.createEntity({
108
+ libraryId: library.id, name, kind: 'person', status, confirmedBy: 'user', origin: 'user',
109
+ }))
110
+ const visible = makePair('visible', ['Visible Harbor', 'Visible Harbor Annex'])
111
+ const secret = makePair('secret', ['Secret Harbor', 'Secret Harbor Annex'], 'provisional')
112
+ const context = makePair('context', ['Context Harbor', 'Context Harbor Annex'], 'provisional')
113
+ const linkAll = (memoryId, entities) => entities.forEach(entity => graph.linkEntries({
114
+ libraryId: library.id, fromId: memoryId, toId: entity.id, kind: 'person', note: 'Synthetic authorization fixture reference.', source: 'user',
115
+ }))
116
+ const entries = {
117
+ 'mem-visible-source': memory('Visible Harbor and Visible Harbor Annex', 'Visible Harbor met Visible Harbor Annex.', { links: visible.map(entity => makeLink(entity.id)) }),
118
+ 'mem-secret-source': memory('Secret Harbor and Secret Harbor Annex', 'Secret Harbor met Secret Harbor Annex.', { visibility: 'secret', links: secret.map(entity => makeLink(entity.id)) }),
119
+ 'mem-context-source': memory('Context Harbor and Context Harbor Annex', 'Context Harbor met Context Harbor Annex.', {
120
+ context: { characterId: 'other-character' }, links: context.map(entity => makeLink(entity.id)),
121
+ }),
122
+ 'mem-visible-auto': memory('Visible automatic edge', 'A visible automatic link exists.', {
123
+ links: [makeLink(visible[0].id, 'auto')],
124
+ }),
125
+ }
126
+ state.savePrivateIndex(library.id, { version: 1, entries })
127
+ suppression.addSuppression(library.id, [{ from: 'mem-visible-source', to: visible[0].id, kind: 'person', rule: 'fixture' }])
128
+ return { library, libraryId: library.id, sessionId, visible, secret, context }
129
+ }
130
+
131
+ function sessionPayload(fixture, extra = {}) {
132
+ return { libraryId: fixture.libraryId, sessionId: fixture.sessionId, ...extra }
133
+ }
134
+
135
+ function assertGenericDenied(actual, missing, label) {
136
+ assert.equal(actual.ok, false, `${label}: hidden target is rejected`)
137
+ assert.equal(missing.ok, false, `${label}: missing target is rejected`)
138
+ assert.deepEqual(actual.error, missing.error, `${label}: hidden and missing targets have equivalent errors`)
139
+ }
140
+
141
+ for (const group of ['secret', 'context']) {
142
+ test(`${group}-only entity ids cannot be renamed, force-deleted, confirmed, merged or reviewed`, async t => {
143
+ for (const operation of ['rename', 'force-delete', 'confirm', 'merge-source', 'merge-target', 'rejection']) {
144
+ await t.test(operation, async () => {
145
+ const fixture = makeFixture(`${group}-${operation}`)
146
+ const hidden = fixture[group]
147
+ const pair = graph.suggestEntityMerges({ libraryId: fixture.libraryId }).items
148
+ .find(item => hidden.some(entity => entity.id === item.sourceId) && hidden.some(entity => entity.id === item.targetId))
149
+ assert.ok(pair, `${group} review pair is a valid synthetic candidate`)
150
+ const before = snapshot(fixture.libraryId)
151
+ let method, hiddenPayload, missingPayload
152
+ const missingId = 'ent-not-present-regression'
153
+ if (operation === 'rename') {
154
+ method = 'renameEntity'
155
+ hiddenPayload = sessionPayload(fixture, { entityId: hidden[0].id, name: 'Unauthorized Rename' })
156
+ missingPayload = sessionPayload(fixture, { entityId: missingId, name: 'Unauthorized Rename' })
157
+ } else if (operation === 'force-delete') {
158
+ method = 'deleteEntity'
159
+ hiddenPayload = sessionPayload(fixture, { entityId: hidden[0].id, force: true })
160
+ missingPayload = sessionPayload(fixture, { entityId: missingId, force: true })
161
+ } else if (operation === 'confirm') {
162
+ method = 'confirmEntities'
163
+ hiddenPayload = sessionPayload(fixture, { entityIds: [hidden[0].id] })
164
+ missingPayload = sessionPayload(fixture, { entityIds: [missingId] })
165
+ } else if (operation === 'merge-source') {
166
+ method = 'mergeEntities'
167
+ hiddenPayload = sessionPayload(fixture, { targetId: fixture.visible[0].id, sourceIds: [hidden[0].id] })
168
+ missingPayload = sessionPayload(fixture, { targetId: fixture.visible[0].id, sourceIds: [missingId] })
169
+ } else if (operation === 'merge-target') {
170
+ method = 'mergeEntities'
171
+ hiddenPayload = sessionPayload(fixture, { targetId: hidden[1].id, sourceIds: [fixture.visible[0].id] })
172
+ missingPayload = sessionPayload(fixture, { targetId: missingId, sourceIds: [fixture.visible[0].id] })
173
+ } else {
174
+ method = 'setEntityMergeRejection'
175
+ hiddenPayload = sessionPayload(fixture, { sourceId: pair.sourceId, targetId: pair.targetId, reviewToken: pair.reviewToken, rejected: true, confirmed: true })
176
+ missingPayload = sessionPayload(fixture, { sourceId: pair.sourceId, targetId: missingId, reviewToken: pair.reviewToken, rejected: true, confirmed: true })
177
+ }
178
+ const denied = await post(method, hiddenPayload)
179
+ const unknown = await post(method, missingPayload)
180
+ assertGenericDenied(denied, unknown, `${group} ${operation}`)
181
+ assertSnapshot(fixture.libraryId, before, `${group} ${operation} denial`)
182
+ })
183
+ }
184
+ })
185
+ }
186
+
187
+ test('a visible memory cannot be linked to an entity visible only through hidden memory', async t => {
188
+ for (const group of ['secret', 'context']) {
189
+ await t.test(group, async () => {
190
+ const fixture = makeFixture(`link-hidden-${group}`)
191
+ const before = snapshot(fixture.libraryId)
192
+ const payload = targetId => sessionPayload(fixture, {
193
+ fromId: 'mem-visible-source', toId: targetId, kind: 'person',
194
+ note: 'Synthetic authorization fixture link.', confidence: 0.8,
195
+ })
196
+ const denied = await post('linkEntries', payload(fixture[group][0].id))
197
+ const unknown = await post('linkEntries', payload('ent-not-present-regression'))
198
+ assertGenericDenied(denied, unknown, `${group} entity link`)
199
+ assertSnapshot(fixture.libraryId, before, `${group} entity link denial`)
200
+ })
201
+ }
202
+ })
203
+
204
+ test('session graph and entity-list reads never publish hidden entity ids or names', async () => {
205
+ const fixture = makeFixture('graph-read-filter')
206
+ const hidden = [...fixture.secret, ...fixture.context]
207
+ for (const method of ['listEntities', 'getGraph', 'getGraphOverview', 'suggestEntityMerges']) {
208
+ const payload = sessionPayload(fixture, { includeOrphans: true, limit: 200,
209
+ ...(method === 'getGraphOverview' ? { overview: true } : {}) })
210
+ const result = await post(method === 'getGraphOverview' ? 'getGraph' : method, payload)
211
+ assert.equal(result.ok, true, `${method} remains available to the bound session`)
212
+ const serialized = JSON.stringify(result.value)
213
+ for (const entity of hidden) {
214
+ assert.equal(serialized.includes(entity.id), false, `${method} must not reveal hidden id ${entity.id}`)
215
+ assert.equal(serialized.includes(entity.name), false, `${method} must not reveal hidden name ${entity.name}`)
216
+ }
217
+ }
218
+ })
219
+
220
+ test('visible evidence cannot create a session relationship to a hidden or missing entity', async () => {
221
+ const fixture = makeFixture('relationship-write-filter')
222
+ const before = snapshot(fixture.libraryId)
223
+ const payload = toId => sessionPayload(fixture, {
224
+ fromId: fixture.visible[0].id, toId, state: { trust: 0.7 },
225
+ evidenceIds: ['mem-visible-source'], reason: 'Visible source memory supports this relation.',
226
+ })
227
+ const hidden = await post('updateRelationship', payload(fixture.secret[0].id))
228
+ const missing = await post('updateRelationship', payload('ent-not-present-regression'))
229
+ assertGenericDenied(hidden, missing, 'relationship endpoint')
230
+ assertSnapshot(fixture.libraryId, before, 'relationship endpoint denial')
231
+ })
232
+
233
+ test('force delete and merge refuse to rewrite hidden-memory references', async () => {
234
+ const fixture = makeFixture('hidden-inbound-reference')
235
+ graph.linkEntries({ libraryId: fixture.libraryId, fromId: 'mem-secret-source', toId: fixture.visible[0].id,
236
+ kind: 'person', note: 'Hidden memory also references this visible entity.' })
237
+ const before = snapshot(fixture.libraryId)
238
+ const deleted = await post('deleteEntity', sessionPayload(fixture, { entityId: fixture.visible[0].id, force: true }))
239
+ assert.equal(deleted.ok, false, 'force cannot cascade through a session-invisible memory')
240
+ assertSnapshot(fixture.libraryId, before, 'force delete preserves hidden references')
241
+ const merged = await post('mergeEntities', sessionPayload(fixture, {
242
+ targetId: fixture.visible[1].id, sourceIds: [fixture.visible[0].id],
243
+ }))
244
+ assert.equal(merged.ok, false, 'merge cannot remap a hidden memory reference')
245
+ assertSnapshot(fixture.libraryId, before, 'merge preserves hidden references')
246
+ })
247
+
248
+ test('relationship reads hide either endpoint when it is not visible to the session', async t => {
249
+ for (const group of ['secret', 'context']) {
250
+ await t.test(group, async () => {
251
+ const fixture = makeFixture(`relationship-${group}`)
252
+ const visibleEntity = fixture.visible[0]
253
+ const hiddenEntity = fixture[group][0]
254
+ const args = { libraryId: fixture.libraryId, fromId: visibleEntity.id, toId: hiddenEntity.id,
255
+ state: { trust: 0.7 }, evidenceIds: ['mem-visible-source'], reason: 'Synthetic visible evidence.' }
256
+ graph.updateRelationship(args)
257
+ const result = await post('getRelationship', sessionPayload(fixture, { fromId: args.fromId, toId: args.toId }))
258
+ assert.equal(result.ok, true)
259
+ assert.equal(result.value.relationship, null, `${group} endpoint must not expose a relationship snapshot`)
260
+ })
261
+ }
262
+ })
263
+
264
+ test('session relationship reads omit history whose evidence is not visible', async () => {
265
+ const fixture = makeFixture('relationship-history-filter')
266
+ const [from, to] = fixture.visible
267
+ graph.updateRelationship({ libraryId: fixture.libraryId, fromId: from.id, toId: to.id,
268
+ state: { trust: 0.2 }, evidenceIds: ['mem-secret-source'], reason: 'Secret-only relationship evidence.' })
269
+ const update = patch => post('updateRelationship', sessionPayload(fixture, {
270
+ fromId: from.id, toId: to.id, state: { trust: patch }, evidenceIds: ['mem-visible-source'],
271
+ reason: 'Visible relationship evidence supports this state.',
272
+ }))
273
+ assert.equal((await update(0.6)).ok, true)
274
+ assert.equal((await update(0.8)).ok, true)
275
+ const result = await post('getRelationship', sessionPayload(fixture, { fromId: from.id, toId: to.id }))
276
+ assert.equal(result.ok, true)
277
+ assert.equal(result.value.relationship.history.length, 1, 'visible historical snapshots remain available')
278
+ const serialized = JSON.stringify(result.value.relationship)
279
+ assert.equal(serialized.includes('mem-secret-source'), false)
280
+ assert.equal(serialized.includes('Secret-only relationship evidence.'), false)
281
+ })
282
+
283
+ test('session relationship reads omit history with hidden endpoints even when its evidence is visible', async () => {
284
+ const fixture = makeFixture('relationship-history-hidden-endpoint')
285
+ const [from, to] = fixture.visible
286
+ const hidden = fixture.secret[0]
287
+ graph.updateRelationship({ libraryId: fixture.libraryId, fromId: from.id, toId: to.id,
288
+ state: { trust: 0.8 }, evidenceIds: ['mem-visible-source'], reason: 'Current visible relationship evidence.' })
289
+ const file = entityFile(fixture.libraryId)
290
+ const store = JSON.parse(fs.readFileSync(file, 'utf8'))
291
+ store.relationships[JSON.stringify([from.id, to.id])].history = [{
292
+ fromId: from.id, toId: hidden.id, state: { trust: 0.99, boundaries: ['hidden historical boundary'] },
293
+ evidenceIds: ['mem-visible-source'], reason: 'Hidden historical relationship reason.',
294
+ }]
295
+ fs.writeFileSync(file, JSON.stringify(store, null, 2))
296
+
297
+ const result = await post('getRelationship', sessionPayload(fixture, { fromId: from.id, toId: to.id }))
298
+ assert.equal(result.ok, true)
299
+ assert.deepEqual(result.value.relationship.history, [], 'a historical snapshot with a hidden endpoint is omitted')
300
+ const serialized = JSON.stringify(result.value.relationship)
301
+ for (const secret of [hidden.id, '0.99', 'hidden historical boundary', 'Hidden historical relationship reason.']) {
302
+ assert.equal(serialized.includes(secret), false, `hidden historical value ${secret} must not leak`)
303
+ }
304
+ })
305
+
306
+ test('session global graph follows the effective useGlobal ceiling', async () => {
307
+ const fixture = makeFixture('global-graph-scope')
308
+ state.saveGlobalIndex({ version: 1, entries: {
309
+ 'mem-global-graph-scope': memory('Visible global graph fixture', 'Global graph body.'),
310
+ } })
311
+ const payload = sessionPayload(fixture, { scope: 'global', limit: 20 })
312
+ const denied = await post('getGraph', payload)
313
+ assert.equal(denied.ok, false, 'useGlobal=false must deny a session global graph read')
314
+ state.setSessionBinding(fixture.sessionId, { useGlobal: true })
315
+ const allowed = await post('getGraph', payload)
316
+ assert.equal(allowed.ok, true)
317
+ assert.ok(allowed.value.nodes.some(node => node.id === 'mem-global-graph-scope'))
318
+ })
319
+
320
+ test('creating an entity in a session never refreshes context-hidden memories', async () => {
321
+ const fixture = makeFixture('create-entity-refresh-scope')
322
+ const beforeSettings = state.getSettings()
323
+ state.updateSettings({ autoLinkMode: 'deterministic' })
324
+ try {
325
+ const index = state.loadPrivateIndex(fixture.libraryId)
326
+ index.entries['mem-context-source'].title = 'Created Harbor appears only in another context'
327
+ index.entries['mem-context-source'].content = 'Created Harbor is mentioned only by a context-hidden memory.'
328
+ state.savePrivateIndex(fixture.libraryId, index)
329
+ const result = await post('createEntity', sessionPayload(fixture, { name: 'Created Harbor', kind: 'person' }))
330
+ assert.equal(result.ok, true)
331
+ const hidden = state.loadPrivateIndex(fixture.libraryId).entries['mem-context-source']
332
+ assert.equal((hidden.links || []).some(link => link.to === result.value.id), false)
333
+ assert.equal(result.value.createdBySession, fixture.sessionId)
334
+ } finally {
335
+ state.updateSettings({ autoLinkMode: beforeSettings.autoLinkMode })
336
+ }
337
+ })
338
+
339
+ test('a merge colliding with a hidden relationship is rejected before any write', async () => {
340
+ const fixture = makeFixture('merge-hidden-relationship-collision')
341
+ const other = graph.createEntity({ libraryId: fixture.libraryId, name: 'Visible Harbor Third', kind: 'person', status: 'confirmed' })
342
+ graph.linkEntries({ libraryId: fixture.libraryId, fromId: 'mem-visible-source', toId: other.id,
343
+ kind: 'person', note: 'Synthetic visible authorization fixture reference.' })
344
+ graph.updateRelationship({ libraryId: fixture.libraryId, fromId: fixture.visible[0].id, toId: other.id,
345
+ state: { trust: 0.4 }, evidenceIds: ['mem-visible-source'], reason: 'Visible source evidence for this relation.' })
346
+ graph.updateRelationship({ libraryId: fixture.libraryId, fromId: fixture.visible[1].id, toId: other.id,
347
+ state: { trust: 0.9 }, evidenceIds: ['mem-secret-source'], reason: 'Hidden target evidence for this relation.' })
348
+ const before = snapshot(fixture.libraryId)
349
+ const result = await post('mergeEntities', sessionPayload(fixture, {
350
+ targetId: fixture.visible[1].id, sourceIds: [fixture.visible[0].id],
351
+ }))
352
+ assert.equal(result.ok, false)
353
+ assertSnapshot(fixture.libraryId, before, 'merge collision authorization denial')
354
+ })
355
+
356
+ for (const group of ['secret', 'context']) {
357
+ test(`unlink refuses a ${group}-only source memory without changing graph bytes`, async () => {
358
+ const fixture = makeFixture(`unlink-${group}`)
359
+ const before = snapshot(fixture.libraryId)
360
+ const payload = fromId => sessionPayload(fixture, { fromId, toId: fixture.visible[0].id, kind: 'person' })
361
+ const denied = await post('unlinkEntry', payload(`mem-${group}-source`))
362
+ const unknown = await post('unlinkEntry', payload('mem-not-present-regression'))
363
+ assertGenericDenied(denied, unknown, `${group} source unlink`)
364
+ assertSnapshot(fixture.libraryId, before, `${group} source unlink denial`)
365
+ })
366
+ }
367
+
368
+ test('unlink does not distinguish a hidden entity target from a missing target', async () => {
369
+ const fixture = makeFixture('unlink-hidden-target')
370
+ const before = snapshot(fixture.libraryId)
371
+ const payload = toId => sessionPayload(fixture, { fromId: 'mem-visible-source', toId, kind: 'person' })
372
+ const hidden = await post('unlinkEntry', payload(fixture.secret[0].id))
373
+ const missing = await post('unlinkEntry', payload('ent-not-present-regression'))
374
+ assertGenericDenied(hidden, missing, 'unlink target')
375
+ assertSnapshot(fixture.libraryId, before, 'unlink target denial')
376
+ })
377
+
378
+ test('session-bound bulk purge and suppression clear are denied without mutation', async t => {
379
+ for (const method of ['purgeAutoLinks', 'clearLinkSuppression']) {
380
+ await t.test(method, async () => {
381
+ const fixture = makeFixture(`session-bulk-${method}`)
382
+ const before = snapshot(fixture.libraryId)
383
+ const result = await post(method, sessionPayload(fixture))
384
+ assert.equal(result.ok, false, `${method} is whole-library management, not a session-scoped graph mutation`)
385
+ assertSnapshot(fixture.libraryId, before, `${method} session denial`)
386
+ })
387
+ }
388
+ })
389
+
390
+ test('session candidate queues contain only visible memories and visible entity candidates', async () => {
391
+ const fixture = makeFixture('candidate-filter')
392
+ const merges = await post('suggestEntityMerges', sessionPayload(fixture))
393
+ assert.equal(merges.ok, true)
394
+ const pairIds = merges.value.items.flatMap(item => [item.sourceId, item.targetId])
395
+ assert.ok(pairIds.includes(fixture.visible[0].id) && pairIds.includes(fixture.visible[1].id), 'visible candidate pair remains available')
396
+ for (const hidden of [...fixture.secret, ...fixture.context]) assert.equal(pairIds.includes(hidden.id), false, `hidden entity id ${hidden.id} must be filtered`)
397
+ const candidates = await post('getAnchorCandidates', sessionPayload(fixture, { force: true }))
398
+ assert.equal(candidates.ok, true)
399
+ const serialized = JSON.stringify(candidates.value)
400
+ for (const hidden of [...fixture.secret, ...fixture.context]) {
401
+ assert.equal(serialized.includes(hidden.id), false, `hidden entity id ${hidden.id} must not enter anchor suggestions`)
402
+ assert.equal(serialized.includes(hidden.name), false, `hidden entity name ${hidden.name} must not enter anchor suggestions`)
403
+ }
404
+ assert.equal(serialized.includes('Secret Harbor'), false)
405
+ assert.equal(serialized.includes('Context Harbor'), false)
406
+ })
407
+
408
+ test('explicit session-less library management still uses the host capability', async () => {
409
+ const fixture = makeFixture('standalone-management')
410
+ authorization.calls = 0
411
+ authorization.requests.length = 0
412
+ const result = await post('renameEntity', {
413
+ libraryId: fixture.libraryId, entityId: fixture.secret[0].id, name: 'Managed Secret Harbor', aliases: [],
414
+ })
415
+ assert.equal(result.ok, true, 'an explicit management request remains able to edit a hidden/unlinked graph row')
416
+ assert.equal(authorization.calls, 1)
417
+ assert.deepEqual(authorization.requests.at(-1), { libraryId: fixture.libraryId, operation: 'write' })
418
+ assert.equal(graph.graphExport(fixture.libraryId).entities[fixture.secret[0].id].name, 'Managed Secret Harbor')
419
+ })