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,95 @@
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
+ import { feedbackAccessFactor } from '../lib/feedback.js'
7
+
8
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-memu-feedback-'))
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 memory = await import('../lib/memory.js')
13
+ const { registerTools } = await import('../lib/tools.js')
14
+ let serial = 0
15
+ const fixture = (extra = {}) => {
16
+ const sessionId = 'feedback-' + (++serial)
17
+ const binding = state.ensureSession(sessionId, { cwd: path.join(home, sessionId), agentPreset: 'coding' })
18
+ const exec = { agent: { session: { header: { id: sessionId } } } }
19
+ const entry = { title: '反馈合成条目', content: '仅用于独立回归的合成内容。', status: 'active', layer: 'long_term', source: 'user_said', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), ...extra }
20
+ state.updatePrivateIndex(binding.libraryId, index => { index.entries['mem-feedback'] = entry })
21
+ return { binding: { ...binding, sessionId }, exec, entry, read: () => state.loadPrivateIndex(binding.libraryId).entries['mem-feedback'] }
22
+ }
23
+ test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
24
+
25
+ test('feedback multiplier applies confirm, deny and access caps in the same unit', () => {
26
+ assert.equal(feedbackAccessFactor({}), 1)
27
+ assert.ok(Math.abs(feedbackAccessFactor({ accessCount: 100, feedback: { confirm: 100, deny: 100 } }) - 1.2) < 1e-12)
28
+ assert.equal(feedbackAccessFactor({ feedback: { confirm: 2 } }), 1.1)
29
+ assert.equal(feedbackAccessFactor({ feedback: { deny: 1 } }), 0.8)
30
+ })
31
+
32
+ test('confirm changes strength without refreshing factual timestamps, and cache sees direct counter changes', () => {
33
+ const f = fixture()
34
+ const before = memory.decayStrength(f.read())
35
+ const result = memory.privateFeedback({ exec: f.exec, id: 'mem-feedback', verdict: 'confirm', reason: '用户明确确认了这条合成事实。' })
36
+ assert.equal(result.entry.feedback.confirm, 1)
37
+ assert.equal(result.entry.updatedAt, f.entry.updatedAt)
38
+ assert.equal(result.entry.content, f.entry.content)
39
+ assert.ok(memory.decayStrength(f.read()) > before)
40
+ const value = { ...f.read(), feedback: { confirm: 0, deny: 0 } }
41
+ const weak = memory.decayStrength(value)
42
+ value.feedback.confirm = 3
43
+ assert.ok(memory.decayStrength(value) > weak)
44
+ })
45
+
46
+ test('two denials marginalize without deleting, archiving, lowering layer or deleting pin evidence', () => {
47
+ const f = fixture({ layer: 'must_remember', pinReason: '有效的合成约束依据', pinSource: 'user_explicit', recallPenalty: 0.2 })
48
+ for (let index = 0; index < 2; index++) memory.privateFeedback({ exec: f.exec, id: 'mem-feedback', verdict: 'deny', reason: '用户明确否认这条合成事实。' })
49
+ const entry = f.read()
50
+ assert.equal(entry.feedback.deny, 2)
51
+ assert.equal(entry.marginalized, true)
52
+ assert.equal(entry.status, 'active')
53
+ assert.equal(entry.layer, 'must_remember')
54
+ assert.equal(entry.pinReason, f.entry.pinReason)
55
+ assert.equal(entry.recallPenalty, undefined)
56
+ assert.equal(memory.decayStrength(entry), 0.2)
57
+ memory.privateFeedback({ exec: f.exec, id: 'mem-feedback', verdict: 'confirm', reason: '用户后来确认,但并未请求撤销边缘化。' })
58
+ assert.equal(f.read().marginalized, true)
59
+ })
60
+
61
+ test('irrelevant records context feedback without claiming the fact was denied', () => {
62
+ const f = fixture()
63
+ memory.privateFeedback({ exec: f.exec, id: 'mem-feedback', verdict: 'irrelevant', reason: '用户表示此刻谈论另一主题。' })
64
+ assert.equal(f.read().feedback.confirm, 0)
65
+ assert.equal(f.read().feedback.deny, 0)
66
+ assert.equal(f.read().feedback.lastVerdict, 'irrelevant')
67
+ assert.equal(f.read().marginalized, undefined)
68
+ })
69
+
70
+ test('feedback validates input, content CAS, visibility and bound-library scope', () => {
71
+ const f = fixture()
72
+ const saved = structuredClone(f.read())
73
+ const revision = memory.memoryEntryRevision(saved)
74
+ assert.throws(() => memory.privateFeedback({ exec: f.exec, id: 'mem-feedback', verdict: 'invented', reason: 'x' }), /verdict/)
75
+ assert.throws(() => memory.privateFeedback({ exec: f.exec, id: 'mem-feedback', verdict: 'confirm', reason: '' }), /reason/)
76
+ state.updatePrivateIndex(f.binding.libraryId, index => { index.entries['mem-feedback'].title += '已修订' })
77
+ assert.throws(() => memory.privateFeedback({ exec: f.exec, id: 'mem-feedback', verdict: 'deny', reason: '明确否认', expectedRevision: revision }), { code: 'MEMORY_CHANGED' })
78
+ assert.equal(f.read().feedback, undefined)
79
+ state.setSessionBinding(f.binding.sessionId, { useLibrary: false })
80
+ assert.throws(() => memory.privateFeedback({ exec: f.exec, id: 'mem-feedback', verdict: 'deny', reason: '明确否认' }), /off|disabled/)
81
+ assert.throws(() => memory.privateFeedback({ id: 'mem-feedback', verdict: 'deny', reason: '明确否认' }), /bound session/)
82
+ })
83
+
84
+ test('feedback tool is registered and exposes no global or foreign-library write option', async () => {
85
+ const tools = []
86
+ const dispose = registerTools({ tools: { register: tool => { tools.push(tool); return () => {} } }, logger: { warn() {} } })
87
+ try {
88
+ const tool = tools.find(row => row.name === 'memu_private_feedback')
89
+ assert.ok(tool)
90
+ assert.equal(tool.parameters.libraryId, undefined)
91
+ assert.deepEqual(tool.parameters.verdict.enum, ['confirm', 'deny', 'irrelevant'])
92
+ const f = fixture()
93
+ assert.match(await tool.execute({ id: 'mem-feedback', verdict: 'confirm', reason: '用户明确确认了。' }, f.exec), /confirm=1/)
94
+ } finally { dispose() }
95
+ })
@@ -0,0 +1,536 @@
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
+ import crypto from 'node:crypto'
7
+ import { spawnSync } from 'node:child_process'
8
+ import { fileURLToPath } from 'node:url'
9
+
10
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-p4-adjacency-'))
11
+ process.env.DSH_MEMU_HOME = home
12
+ process.env.DSH_MEMU_MEMORY_HOME = home
13
+ const { getGraphAdjacency, graphAdjacencyLocation, graphAdjacencyDiagnostics, clearGraphAdjacencyCache,
14
+ GRAPH_ADJACENCY_LIMITS: limits } = await import('../lib/graph-adjacency-index.js')
15
+ const { setWarnSink } = await import('../lib/paths.js')
16
+ const { listDiagnostics } = await import('../lib/diagnostics.js')
17
+ let sequence = 0
18
+ test.afterEach(() => { clearGraphAdjacencyCache(); setWarnSink(null) })
19
+ test.after(() => fs.rmSync(home, { recursive: true, force: true, maxRetries: 3 }))
20
+
21
+ function graph() {
22
+ return {
23
+ nodes: ['c', 'a', 'b', 'isolated'].map(id => ({ id, title: 'PRIVATE_TITLE', content: 'PRIVATE_BODY', domain: 'SECRET_DOMAIN' })),
24
+ edges: [
25
+ { from: 'a', to: 'b', kind: 'related', note: 'PRIVATE_NOTE', evidence: { quote: 'PRIVATE_EVIDENCE' } },
26
+ { from: 'b', to: 'a', kind: 'causes' },
27
+ { from: 'a', to: 'missing', kind: 'related' },
28
+ { from: 'a', to: 'a', kind: 'related' },
29
+ { from: 'a', to: 'b', kind: 'related' },
30
+ { from: 'c', to: 'b', kind: 'mentions' },
31
+ ],
32
+ }
33
+ }
34
+ function setup(overrides = {}) {
35
+ const data = graph()
36
+ return { directory: path.join(home, `case-${++sequence}`, 'rt', 'graph-adjacency'),
37
+ scope: 'private', libraryId: 'library-a', key: ['session-a', { knownBy: ['alice'], role: 'owner', domain: null }],
38
+ revision: 'source-r1', entityRevision: 'entities-r1', build: () => data, ...overrides }
39
+ }
40
+ function current(options) {
41
+ const location = graphAdjacencyLocation(options)
42
+ const pointer = JSON.parse(fs.readFileSync(location.pointer, 'utf8')).payload
43
+ const slot = path.join(location.root, pointer.slot)
44
+ return { ...location, publication: pointer, slot, index: path.join(slot, 'edges.idx'),
45
+ nodes: path.join(slot, 'nodes.json'), manifest: path.join(slot, 'manifest.json') }
46
+ }
47
+ function persisted(options) {
48
+ const initial = getGraphAdjacency(options)
49
+ assert.equal(initial.backend, 'source'); assert.equal(initial.published, true)
50
+ const result = getGraphAdjacency(options)
51
+ assert.equal(result.backend, 'persistent'); assert.equal(result.fallback, null)
52
+ return result
53
+ }
54
+ function canonical(value) {
55
+ return JSON.stringify(Array.isArray(value) ? value.map(item => JSON.parse(canonical(item)))
56
+ : value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, JSON.parse(canonical(value[key]))])) : value)
57
+ }
58
+ const digest = value => crypto.createHash('sha256').update(value).digest('hex')
59
+ function replacePointer(location, payload) {
60
+ fs.writeFileSync(location.pointer, JSON.stringify({ payload, checksum: digest(canonical(payload)) }))
61
+ }
62
+ function rehash(options, change) {
63
+ const location = current(options)
64
+ const manifest = JSON.parse(fs.readFileSync(location.manifest, 'utf8'))
65
+ change(location, manifest)
66
+ for (const [name, file] of [['nodes.json', location.nodes], ['edges.idx', location.index]]) {
67
+ const bytes = fs.readFileSync(file)
68
+ manifest.files[name] = { bytes: bytes.length, sha256: digest(bytes) }
69
+ }
70
+ const bytes = JSON.stringify(manifest)
71
+ fs.writeFileSync(location.manifest, bytes)
72
+ replacePointer(location, { ...location.publication, manifest: digest(bytes) })
73
+ }
74
+ function tree(directory) {
75
+ return fs.readdirSync(directory, { withFileTypes: true }).flatMap(item => {
76
+ const file = path.join(directory, item.name)
77
+ return item.isDirectory() ? tree(file) : [file]
78
+ })
79
+ }
80
+
81
+ test('real binary publication preserves directed rows, ordinals, duplicates, self-loops and isolated IDs', () => {
82
+ let calls = 0
83
+ const options = setup({ build: () => { calls++; return graph() } })
84
+ const value = persisted(options), location = current(options)
85
+ assert.ok(fs.statSync(location.index).size > 40)
86
+ assert.equal(fs.readFileSync(location.index).toString('ascii', 0, 4), 'DMGA')
87
+ assert.deepEqual(value.nodeIds, ['a', 'b', 'c', 'isolated'])
88
+ assert.equal(value.edgeCount, 5)
89
+ assert.deepEqual(value.outgoing('a').map(row => row.ordinal), [0, 3, 4])
90
+ assert.deepEqual(value.incoming('a').map(row => [row.from, row.to, row.ordinal]), [['b', 'a', 1], ['a', 'a', 3]])
91
+ assert.deepEqual(value.incoming('b').map(row => row.ordinal), [0, 4, 5])
92
+ assert.deepEqual(value.outgoing('isolated'), [])
93
+ assert.deepEqual(value.incoming('absent'), [])
94
+ assert.deepEqual(value.readAll().map(row => row.ordinal), [0, 1, 3, 4, 5])
95
+ assert.equal(calls, 1, 'a persistent query must not scan canonical links')
96
+ const ids = value.nodeIds, rows = value.outgoing('a')
97
+ ids[0] = 'changed'; rows[0].to = 'changed'
98
+ assert.equal(value.nodeIds[0], 'a'); assert.equal(value.outgoing('a')[0].to, 'b')
99
+ })
100
+
101
+ test('restart uses the published topology with a builder that would fail', () => {
102
+ const options = setup()
103
+ persisted(options)
104
+ const moduleUrl = new URL('../lib/graph-adjacency-index.js', import.meta.url).href
105
+ const script = `import {getGraphAdjacency} from ${JSON.stringify(moduleUrl)};
106
+ const options = ${JSON.stringify({ ...options, build: undefined })};
107
+ options.build = () => { throw new Error('source builder must not run after restart') };
108
+ const result = getGraphAdjacency(options);
109
+ console.log(JSON.stringify({backend: result.backend, rows: result.incoming('b'), count: result.edgeCount}));`
110
+ const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', env: { ...process.env }, timeout: 30000 })
111
+ assert.equal(result.status, 0, result.stderr)
112
+ const output = JSON.parse(result.stdout)
113
+ assert.equal(output.backend, 'persistent'); assert.equal(output.count, 5)
114
+ assert.deepEqual(output.rows.map(row => row.ordinal), [0, 4, 5])
115
+ })
116
+
117
+ test('batch selection deduplicates ordinals, preserves source order and validates once per batch', () => {
118
+ const options = setup(), value = persisted(options), original = fs.lstatSync
119
+ let calls = 0
120
+ try {
121
+ fs.lstatSync = function () { calls++; return original.apply(this, arguments) }
122
+ assert.deepEqual(value.selectMany({ outgoing: ['a', 'a', 'c'], incoming: ['a', 'b'] }).map(row => row.ordinal), [0, 1, 3, 4, 5])
123
+ const small = calls; calls = 0
124
+ assert.deepEqual(value.outgoingMany(Array(3000).fill('a')).map(row => row.ordinal), [0, 3, 4])
125
+ assert.ok(calls <= small + 10, `batch stat count grew with IDs: ${calls} vs ${small}`)
126
+ } finally { fs.lstatSync = original }
127
+ assert.deepEqual(value.incomingMany(['a', 'b']).map(row => row.ordinal), [0, 1, 3, 4, 5])
128
+ assert.throws(() => value.selectMany({ outgoing: 'a' }), TypeError)
129
+ })
130
+
131
+ test('a batch detects damage during its record read and returns only current source topology', () => {
132
+ const data = graph(), options = setup({ build: () => data }), value = persisted(options), location = current(options)
133
+ const read = fs.readSync, open = fs.openSync, close = fs.closeSync, fds = new Set()
134
+ let changed = false
135
+ try {
136
+ fs.openSync = function (file) { const fd = open.apply(this, arguments); if (file === location.index) fds.add(fd); return fd }
137
+ fs.closeSync = function (fd) { fds.delete(fd); return close.apply(this, arguments) }
138
+ fs.readSync = function (fd, bytes, offset, length, position) {
139
+ const count = read.apply(this, arguments)
140
+ if (!changed && fds.has(fd)) {
141
+ changed = true
142
+ const edit = fs.openSync(location.index, 'r+')
143
+ try { fs.writeSync(edit, Buffer.from([0xff]), 0, 1, fs.statSync(location.index).size - 1) } finally { fs.closeSync(edit) }
144
+ data.edges = [{ from: 'b', to: 'c', kind: 'current' }]
145
+ }
146
+ return count
147
+ }
148
+ assert.deepEqual(value.selectMany({ outgoing: ['a', 'b'], incoming: ['c'] }), [{ from: 'b', to: 'c', kind: 'current', ordinal: 0 }])
149
+ assert.equal(changed, true); assert.equal(value.backend, 'source'); assert.equal(value.fallback, 'GRAPH_ADJACENCY_CORRUPT')
150
+ } finally { fs.readSync = read; fs.openSync = open; fs.closeSync = close }
151
+ })
152
+
153
+ test('only topology is persisted; raw keys, revision strings and graph text do not enter artifacts or diagnostics', () => {
154
+ const options = setup({ key: ['RAW_PERMISSION_SECRET'], revision: 'RAW_REVISION_SECRET', entityRevision: 'RAW_ENTITY_SECRET' })
155
+ persisted(options)
156
+ const text = tree(options.directory).map(file => fs.readFileSync(file).toString('utf8')).join('\n')
157
+ for (const secret of ['PRIVATE_TITLE', 'PRIVATE_BODY', 'PRIVATE_NOTE', 'PRIVATE_EVIDENCE', 'SECRET_DOMAIN',
158
+ 'RAW_PERMISSION_SECRET', 'RAW_REVISION_SECRET', 'RAW_ENTITY_SECRET', 'library-a']) assert.equal(text.includes(secret), false, secret)
159
+ const diagnostics = JSON.stringify(graphAdjacencyDiagnostics())
160
+ assert.equal(diagnostics.includes(options.directory), false)
161
+ assert.equal(diagnostics.includes('RAW_PERMISSION_SECRET'), false)
162
+ })
163
+
164
+ for (const [label, change] of [
165
+ ['source revision', options => ({ ...options, revision: 'source-r2' })],
166
+ ['entity sidecar signature', options => ({ ...options, entityRevision: 'entities-r2' })],
167
+ ]) test(`${label} invalidates disk data and current request returns current authorized edges`, () => {
168
+ const options = setup()
169
+ persisted(options)
170
+ const next = change(options), data = graph()
171
+ data.edges = [{ from: 'c', to: 'a', kind: 'new' }]
172
+ const result = getGraphAdjacency({ ...next, build: () => data })
173
+ assert.equal(result.backend, 'source'); assert.equal(result.fallback, 'GRAPH_ADJACENCY_STALE'); assert.equal(result.published, true)
174
+ assert.deepEqual(result.readAll(), [{ from: 'c', to: 'a', kind: 'new', ordinal: 0 }])
175
+ assert.deepEqual(getGraphAdjacency(next).readAll(), result.readAll())
176
+ })
177
+
178
+ test('full permission values, domains, scopes and owners have isolated physical publications', () => {
179
+ const base = setup()
180
+ const variants = [base,
181
+ { ...base, key: ['session-a', { knownBy: ['carol'], role: 'owner', domain: null }] },
182
+ { ...base, key: ['session-a', { knownBy: ['alice'], role: 'guest', domain: null }] },
183
+ { ...base, key: ['session-a', { knownBy: ['alice'], role: 'owner', domain: 'rp' }] },
184
+ { ...base, scope: 'global', libraryId: null, entityRevision: 'none' },
185
+ { ...base, libraryId: 'library-b' }]
186
+ const roots = new Set()
187
+ variants.forEach((options, i) => {
188
+ const data = graph(); data.edges = [data.edges[i % data.edges.length]]
189
+ const result = persisted({ ...options, build: () => data })
190
+ roots.add(graphAdjacencyLocation(options).root)
191
+ assert.deepEqual(result.readAll(), getGraphAdjacency({ ...options, build: () => { throw Error('permission cache collision') } }).readAll())
192
+ })
193
+ assert.equal(roots.size, variants.length)
194
+ const reordered = { ...base, key: ['session-a', { domain: null, role: 'owner', knownBy: ['alice'] }] }
195
+ assert.equal(graphAdjacencyLocation(base).root, graphAdjacencyLocation(reordered).root)
196
+ assert.notEqual(graphAdjacencyLocation({ ...base, key: ['a', 'b'] }).root, graphAdjacencyLocation({ ...base, key: ['b', 'a'] }).root)
197
+ })
198
+
199
+ for (const field of ['key', 'revision', 'entityRevision']) test(`absent ${field} never falls into a default persisted identity`, () => {
200
+ const options = setup(); delete options[field]
201
+ assert.throws(() => getGraphAdjacency(options), TypeError)
202
+ assert.equal(fs.existsSync(options.directory), false)
203
+ })
204
+ test('incomplete, cyclic and non-JSON permissions are rejected before filesystem work', () => {
205
+ const cycle = {}; cycle.self = cycle
206
+ for (const key of [null, '', { role: undefined }, { role: NaN }, { role: new Date() }, cycle, [,'x']]) {
207
+ const options = setup({ key })
208
+ assert.throws(() => getGraphAdjacency(options), TypeError)
209
+ assert.equal(fs.existsSync(options.directory), false)
210
+ }
211
+ })
212
+
213
+ for (const warm of [false, true]) test(`${warm ? 'warm handle' : 'cold process cache'} detects same-size corruption with restored mtime, warns and returns current source IDs`, () => {
214
+ let builds = 0
215
+ const data = graph(), options = setup({ build: () => { builds++; return data } }), value = persisted(options), location = current(options)
216
+ if (!warm) clearGraphAdjacencyCache()
217
+ const before = fs.statSync(location.index), bytes = fs.readFileSync(location.index)
218
+ bytes[bytes.length - 1] ^= 1
219
+ fs.writeFileSync(location.index, bytes); fs.utimesSync(location.index, before.atime, before.mtime)
220
+ const messages = []; setWarnSink(message => messages.push(message))
221
+ data.edges = [{ from: 'b', to: 'c', kind: 'recovered' }]
222
+ const result = warm ? value : getGraphAdjacency(options)
223
+ assert.deepEqual(result.outgoing('b'), [{ from: 'b', to: 'c', kind: 'recovered', ordinal: 0 }])
224
+ assert.equal(result.backend, 'source'); assert.equal(result.fallback, 'GRAPH_ADJACENCY_CORRUPT')
225
+ assert.equal(result.published, true); assert.equal(builds, 2)
226
+ assert.ok(messages.some(message => message.includes('GRAPH_ADJACENCY_CORRUPT')))
227
+ assert.ok(listDiagnostics({ scope: 'graph' }).items.some(item => item.code === 'GRAPH_ADJACENCY_CORRUPT'))
228
+ })
229
+
230
+ for (const name of ['edges.idx', 'nodes.json', 'manifest.json', 'current.json']) test(`deleting ${name} from a warm publication falls back during that call and repairs next request`, () => {
231
+ const data = graph(), options = setup({ build: () => data }), value = persisted(options), location = current(options)
232
+ fs.unlinkSync(name === 'current.json' ? location.pointer : path.join(location.slot, name))
233
+ data.edges = [{ from: 'c', to: 'a', kind: 'fresh' }]
234
+ assert.deepEqual(value.incoming('a'), [{ from: 'c', to: 'a', kind: 'fresh', ordinal: 0 }])
235
+ assert.equal(value.backend, 'source'); assert.equal(value.published, true)
236
+ assert.equal(getGraphAdjacency(options).backend, 'persistent')
237
+ })
238
+
239
+ for (const [label, mutate] of [
240
+ ['pointer checksum', options => { const file = current(options).pointer; const item = JSON.parse(fs.readFileSync(file)); item.checksum = '0'.repeat(64); fs.writeFileSync(file, JSON.stringify(item)) }],
241
+ ['pointer identity', options => { const location = current(options); replacePointer(location, { ...location.publication, identity: '0'.repeat(64) }) }],
242
+ ['pointer slot traversal', options => { const location = current(options); replacePointer(location, { ...location.publication, slot: '../outside' }) }],
243
+ ['manifest version', options => rehash(options, (_, manifest) => { manifest.version++ })],
244
+ ['manifest identity', options => rehash(options, (_, manifest) => { manifest.identity = '0'.repeat(64) })],
245
+ ['binary endpoint', options => rehash(options, location => { const bytes = fs.readFileSync(location.index); const edges = bytes.readUInt32LE(12); bytes.writeUInt32LE(9999, bytes.length - edges * 16); fs.writeFileSync(location.index, bytes) })],
246
+ ['binary offsets', options => rehash(options, location => { const bytes = fs.readFileSync(location.index); bytes.writeUInt32LE(1, 32); fs.writeFileSync(location.index, bytes) })],
247
+ ['duplicate node dictionary', options => rehash(options, location => { const metadata = JSON.parse(fs.readFileSync(location.nodes)); metadata.ids[1] = metadata.ids[0]; fs.writeFileSync(location.nodes, JSON.stringify(metadata)) })],
248
+ ]) test(`cold validation rejects ${label} even when outer file checksums are valid`, () => {
249
+ const options = setup(); persisted(options); mutate(options); clearGraphAdjacencyCache()
250
+ const value = getGraphAdjacency(options)
251
+ assert.equal(value.backend, 'source'); assert.equal(value.fallback, 'GRAPH_ADJACENCY_CORRUPT')
252
+ assert.deepEqual(value.readAll().map(row => row.ordinal), [0, 1, 3, 4, 5])
253
+ })
254
+
255
+ for (const operation of ['pointer rename', 'file fsync', 'manifest rename']) test(`${operation} failure preserves old active revision, and retry recovers without growing slots`, () => {
256
+ const options = setup(); persisted(options)
257
+ const location = current(options), oldPointer = fs.readFileSync(location.pointer)
258
+ const data = graph(); data.edges = [{ from: 'c', to: 'a', kind: 'new' }]
259
+ const next = { ...options, revision: 'r2', build: () => data }, rename = fs.renameSync, sync = fs.fsyncSync
260
+ try {
261
+ fs.renameSync = function (from, to) {
262
+ if ((operation === 'pointer rename' && to === location.pointer)
263
+ || (operation === 'manifest rename' && path.basename(to) === 'manifest.json')) throw Object.assign(Error('injected failure'), { code: 'EIO' })
264
+ return rename.apply(this, arguments)
265
+ }
266
+ fs.fsyncSync = function (fd) {
267
+ if (operation === 'file fsync' && fs.fstatSync(fd).isFile()) throw Object.assign(Error('injected fsync'), { code: 'EIO' })
268
+ return sync.apply(this, arguments)
269
+ }
270
+ const value = getGraphAdjacency(next)
271
+ assert.equal(value.backend, 'source'); assert.equal(value.published, false)
272
+ assert.deepEqual(value.readAll(), [{ from: 'c', to: 'a', kind: 'new', ordinal: 0 }])
273
+ } finally { fs.renameSync = rename; fs.fsyncSync = sync }
274
+ assert.deepEqual(fs.readFileSync(location.pointer), oldPointer)
275
+ assert.equal(getGraphAdjacency({ ...options, build: () => { throw Error('old active was lost') } }).backend, 'persistent')
276
+ assert.equal(getGraphAdjacency(next).published, true)
277
+ assert.equal(getGraphAdjacency(next).backend, 'persistent')
278
+ assert.ok(fs.readdirSync(location.root).filter(name => name.startsWith('slot-')).length <= 2)
279
+ })
280
+
281
+ test('first-publication failure leaves bounded reserved files and a later request can rebuild them', () => {
282
+ const options = setup(), rename = fs.renameSync
283
+ try {
284
+ fs.renameSync = function (from, to) {
285
+ if (path.basename(to) === 'manifest.json') throw Object.assign(Error('first publication interrupted'), { code: 'EIO' })
286
+ return rename.apply(this, arguments)
287
+ }
288
+ assert.equal(getGraphAdjacency(options).published, false)
289
+ } finally { fs.renameSync = rename }
290
+ assert.equal(getGraphAdjacency(options).published, true)
291
+ assert.equal(getGraphAdjacency(options).backend, 'persistent')
292
+ })
293
+
294
+ test('publication read-back rejects a silently altered edge write before replacing the active pointer', () => {
295
+ const options = setup(); persisted(options)
296
+ const location = current(options), before = fs.readFileSync(location.pointer), rename = fs.renameSync
297
+ try {
298
+ fs.renameSync = function (from, to) {
299
+ const result = rename.apply(this, arguments)
300
+ if (path.basename(to) === 'edges.idx') {
301
+ const bytes = fs.readFileSync(to); bytes[bytes.length - 1] ^= 1; fs.writeFileSync(to, bytes)
302
+ }
303
+ return result
304
+ }
305
+ const value = getGraphAdjacency({ ...options, revision: 'r2' })
306
+ assert.equal(value.backend, 'source'); assert.equal(value.published, false)
307
+ assert.deepEqual(fs.readFileSync(location.pointer), before)
308
+ } finally { fs.renameSync = rename }
309
+ assert.equal(getGraphAdjacency({ ...options, build: () => { throw Error('old publication was replaced') } }).backend, 'persistent')
310
+ })
311
+
312
+ test('an interrupted namespace ownership fsync can recover only its exact validated pending marker', () => {
313
+ const options = setup(), sync = fs.fsyncSync
314
+ try {
315
+ fs.fsyncSync = function (fd) { if (fs.fstatSync(fd).isFile()) throw Object.assign(Error('bootstrap interrupted'), { code: 'EIO' }); return sync.apply(this, arguments) }
316
+ assert.equal(getGraphAdjacency(options).published, false)
317
+ } finally { fs.fsyncSync = sync }
318
+ assert.equal(getGraphAdjacency(options).published, true)
319
+ assert.equal(getGraphAdjacency(options).backend, 'persistent')
320
+ const unknown = setup()
321
+ fs.mkdirSync(unknown.directory, { recursive: true })
322
+ fs.writeFileSync(path.join(unknown.directory, 'owner.json.next'), '{"unrecognized":true}')
323
+ const value = getGraphAdjacency(unknown)
324
+ assert.equal(value.published, false)
325
+ assert.equal(fs.readFileSync(path.join(unknown.directory, 'owner.json.next'), 'utf8'), '{"unrecognized":true}')
326
+ })
327
+
328
+ test('an interrupted identity-owner rename recovers its exact pending marker under the namespace lock', () => {
329
+ const options = setup(), location = graphAdjacencyLocation(options), rename = fs.renameSync
330
+ try {
331
+ fs.renameSync = function (from, to) {
332
+ if (to === path.join(location.root, 'owner.json')) throw Object.assign(Error('identity owner interrupted'), { code: 'EIO' })
333
+ return rename.apply(this, arguments)
334
+ }
335
+ assert.equal(getGraphAdjacency(options).published, false)
336
+ } finally { fs.renameSync = rename }
337
+ assert.deepEqual(fs.readdirSync(location.root), ['owner.json.next'])
338
+ const recovered = getGraphAdjacency(options)
339
+ assert.equal(recovered.backend, 'source'); assert.equal(recovered.published, true)
340
+ assert.deepEqual(recovered.outgoing('a').map(row => row.ordinal), [0, 3, 4])
341
+ assert.equal(getGraphAdjacency({ ...options, build: () => { throw Error('recovered identity must survive reload') } }).backend, 'persistent')
342
+ })
343
+
344
+ test('pending identity ownership is recovered during inventory but unknown siblings and unmarked empty roots remain unclaimed', () => {
345
+ const options = setup(), location = graphAdjacencyLocation(options), rename = fs.renameSync
346
+ try {
347
+ fs.renameSync = function (from, to) {
348
+ if (to === path.join(location.root, 'owner.json')) throw Object.assign(Error('identity interrupted'), { code: 'EIO' })
349
+ return rename.apply(this, arguments)
350
+ }
351
+ assert.equal(getGraphAdjacency(options).published, false)
352
+ } finally { fs.renameSync = rename }
353
+ assert.equal(getGraphAdjacency({ ...options, key: ['other-permission'] }).published, true)
354
+ assert.equal(fs.existsSync(path.join(location.root, 'owner.json')), true)
355
+ const unknown = setup({ directory: options.directory, key: ['unrecognized-identity'] }), root = graphAdjacencyLocation(unknown).root
356
+ fs.mkdirSync(root)
357
+ assert.equal(getGraphAdjacency(unknown).published, false)
358
+ assert.deepEqual(fs.readdirSync(root), [])
359
+ const pending = JSON.parse(fs.readFileSync(path.join(location.root, 'owner.json')))
360
+ pending.payload.identity = graphAdjacencyLocation(unknown).identity
361
+ pending.checksum = digest(canonical(pending.payload))
362
+ fs.writeFileSync(path.join(root, 'owner.json.next'), JSON.stringify(pending))
363
+ fs.writeFileSync(path.join(root, 'truth'), 'preserve')
364
+ assert.equal(getGraphAdjacency(unknown).published, false)
365
+ assert.equal(fs.existsSync(path.join(root, 'owner.json')), false)
366
+ assert.equal(fs.readFileSync(path.join(root, 'truth'), 'utf8'), 'preserve')
367
+ })
368
+
369
+ test('many revisions reuse exactly two slots and warm queries create no directories', () => {
370
+ const options = setup()
371
+ for (let i = 0; i < 35; i++) {
372
+ const next = { ...options, revision: `r-${i}` }
373
+ assert.equal(getGraphAdjacency(next).published, true)
374
+ assert.equal(getGraphAdjacency(next).backend, 'persistent')
375
+ }
376
+ const location = current(options), before = tree(options.directory).sort()
377
+ for (let i = 0; i < 25; i++) getGraphAdjacency({ ...options, revision: 'r-34' }).outgoing('a')
378
+ assert.deepEqual(tree(options.directory).sort(), before)
379
+ assert.deepEqual(fs.readdirSync(location.root).sort(), ['current.json', 'owner.json', 'slot-0', 'slot-1'])
380
+ assert.ok(tree(options.directory).length <= 10)
381
+ assert.ok(tree(options.directory).reduce((sum, file) => sum + fs.statSync(file).size, 0) < limits.maxDiskBytes)
382
+ })
383
+
384
+ test('permission churn evicts safely owned oldest identities at the namespace cap; old handles recover from current source', () => {
385
+ const options = setup(), value = persisted(options), first = current(options)
386
+ fs.utimesSync(first.pointer, new Date('2001-01-01'), new Date('2001-01-01'))
387
+ for (let i = 1; i < limits.maxIdentities + 8; i++) {
388
+ const next = { ...options, key: ['permission', i] }
389
+ assert.equal(getGraphAdjacency(next).published, true)
390
+ assert.equal(getGraphAdjacency(next).backend, 'persistent')
391
+ assert.ok(fs.readdirSync(options.directory).filter(name => /^[a-f0-9]{64}$/.test(name)).length <= limits.maxIdentities)
392
+ }
393
+ assert.equal(fs.existsSync(first.root), false)
394
+ assert.deepEqual(value.outgoing('a').map(row => row.ordinal), [0, 3, 4])
395
+ assert.equal(value.backend, 'source'); assert.equal(value.published, true)
396
+ assert.ok(graphAdjacencyDiagnostics().evictedIdentities > 0)
397
+ })
398
+
399
+ test('unknown artifacts are preserved and prevent unsafe slot recycling', () => {
400
+ const options = setup(); persisted(options)
401
+ const location = current(options), unknown = path.join(location.root, 'truth.sqlite3')
402
+ fs.writeFileSync(unknown, 'never delete')
403
+ const value = getGraphAdjacency({ ...options, revision: 'r2' })
404
+ assert.equal(value.backend, 'source'); assert.equal(value.published, false)
405
+ assert.equal(fs.readFileSync(unknown, 'utf8'), 'never delete')
406
+ assert.equal(getGraphAdjacency(options).backend, 'persistent')
407
+ })
408
+
409
+ test('a disk budget refusal leaves the active artifact untouched and does not append a new generation', () => {
410
+ const options = setup(); persisted(options)
411
+ const location = current(options)
412
+ fs.truncateSync(location.index, limits.maxDiskBytes)
413
+ const value = getGraphAdjacency({ ...options, revision: 'r2' })
414
+ assert.equal(value.backend, 'source'); assert.equal(value.published, false)
415
+ assert.equal(fs.statSync(location.index).size, limits.maxDiskBytes)
416
+ assert.equal(fs.existsSync(path.join(location.root, 'slot-1', 'edges.idx')), false)
417
+ assert.equal(graphAdjacencyDiagnostics().lastError, 'GRAPH_ADJACENCY_CAPACITY')
418
+ })
419
+
420
+ for (const target of ['namespace', 'identity', 'slot', 'file', 'lock']) test(`${target} link refuses persistence and never follows or deletes target data`, t => {
421
+ const options = setup(); persisted(options)
422
+ const location = current(options), outside = path.join(home, `outside-${++sequence}`)
423
+ fs.mkdirSync(outside); fs.writeFileSync(path.join(outside, 'sentinel'), 'safe')
424
+ let link, destination, kind
425
+ if (target === 'namespace') { link = options.directory; destination = outside; kind = 'junction' }
426
+ else if (target === 'identity') { link = location.root; destination = outside; kind = 'junction' }
427
+ else if (target === 'slot') { link = location.slot; destination = outside; kind = 'junction' }
428
+ else if (target === 'lock') { link = path.join(options.directory, 'publication.lock'); destination = path.join(outside, 'sentinel'); kind = 'file' }
429
+ else { link = location.index; destination = path.join(outside, 'sentinel'); kind = 'file' }
430
+ if (fs.existsSync(link)) fs.renameSync(link, `${link}.saved`)
431
+ try { fs.symlinkSync(destination, link, process.platform === 'win32' ? kind : undefined) } catch (error) {
432
+ if (['EPERM', 'EACCES', 'ENOSYS'].includes(error.code)) { t.skip(`links unavailable: ${error.code}`); return }
433
+ throw error
434
+ }
435
+ const value = getGraphAdjacency(options)
436
+ assert.equal(value.backend, 'source'); assert.equal(value.fallback, 'GRAPH_ADJACENCY_UNSAFE'); assert.equal(value.published, false)
437
+ assert.deepEqual(value.incoming('b').map(row => row.ordinal), [0, 4, 5])
438
+ assert.equal(fs.readFileSync(path.join(outside, 'sentinel'), 'utf8'), 'safe')
439
+ assert.equal(fs.lstatSync(link).isSymbolicLink(), true)
440
+ })
441
+
442
+ test('a hard-linked edge artifact is never trusted or recycled', () => {
443
+ const options = setup(); persisted(options)
444
+ const location = current(options), outside = path.join(home, `hardlink-${++sequence}`)
445
+ fs.linkSync(location.index, outside)
446
+ const before = fs.readFileSync(outside), value = getGraphAdjacency(options)
447
+ assert.equal(value.backend, 'source'); assert.equal(value.published, false)
448
+ assert.equal(value.fallback, 'GRAPH_ADJACENCY_UNSAFE')
449
+ assert.deepEqual(fs.readFileSync(outside), before)
450
+ })
451
+
452
+ test('files are created as 0600 on POSIX; Windows mode does not claim to replace ACLs', t => {
453
+ const options = setup(); persisted(options)
454
+ if (process.platform === 'win32') { t.skip('POSIX mode bits are not a Windows ACL contract'); return }
455
+ for (const file of tree(options.directory)) assert.equal(fs.statSync(file).mode & 0o777, 0o600)
456
+ })
457
+
458
+ test('metadata cache is bounded and caller-held handles do not pin evicted states', () => {
459
+ const values = []
460
+ for (let i = 0; i < 35; i++) values.push(persisted(setup()))
461
+ const snapshot = graphAdjacencyDiagnostics()
462
+ assert.equal(snapshot.cache.maxBytes, 16 * 1024 * 1024)
463
+ assert.equal(snapshot.cache.maxEntries, 32)
464
+ assert.ok(snapshot.cache.size <= 32); assert.ok(snapshot.cache.bytes <= snapshot.cache.maxBytes)
465
+ clearGraphAdjacencyCache()
466
+ assert.equal(graphAdjacencyDiagnostics().cache.bytes, 0)
467
+ assert.equal(values[0].incoming('b').length, 3)
468
+ assert.ok(graphAdjacencyDiagnostics().cache.size <= 1)
469
+ })
470
+
471
+ test('an oversized metadata view is queried correctly without entering the resident cache', () => {
472
+ const ids = Array.from({ length: 90000 }, (_, i) => `n${String(i).padStart(6, '0')}${'x'.repeat(90)}`)
473
+ const options = setup({ build: () => ({ nodes: ids.map(id => ({ id })), edges: [{ from: ids[0], to: ids.at(-1), kind: 'related' }] }) })
474
+ const value = persisted(options)
475
+ assert.deepEqual(value.outgoing(ids[0]), [{ from: ids[0], to: ids.at(-1), kind: 'related', ordinal: 0 }])
476
+ const snapshot = graphAdjacencyDiagnostics()
477
+ assert.equal(snapshot.cache.size, 0); assert.equal(snapshot.cache.bytes, 0); assert.ok(snapshot.cache.oversized > 0)
478
+ })
479
+
480
+ test('builder failure is propagated rather than represented as a successful empty graph', () => {
481
+ const options = setup({ build: () => { throw Error('canonical read failed') } })
482
+ assert.throws(() => getGraphAdjacency(options), /canonical read failed/)
483
+ assert.equal(fs.existsSync(graphAdjacencyLocation(options).root), false)
484
+ })
485
+
486
+ test('empty authorized graphs persist, and malformed source data does not silently become empty', () => {
487
+ const options = setup({ build: () => ({ nodes: [], edges: [] }) }), value = persisted(options)
488
+ assert.deepEqual(value.nodeIds, []); assert.deepEqual(value.readAll(), []); assert.equal(value.edgeCount, 0)
489
+ for (const build of [() => null, () => ({ nodes: [], edges: null }), () => ({ nodes: [{ id: '' }], edges: [] })]) {
490
+ assert.throws(() => getGraphAdjacency(setup({ build })), /invalid authorized graph/)
491
+ }
492
+ })
493
+
494
+ test('actual getGraphOverview service measures a 3k near-view using bounded batch validation', async t => {
495
+ const state = await import('../lib/state.js')
496
+ const { getGraphOverview } = await import('../lib/graph.js')
497
+ const session = `adjacency-3k-${++sequence}`, libraryId = state.ensureSession(session, { cwd: path.join(home, session), agentPreset: 'rp' }).libraryId
498
+ const entries = Object.fromEntries(Array.from({ length: 3000 }, (_, i) => {
499
+ const id = `perf-${String(i).padStart(5, '0')}`
500
+ return [id, { title: `Node ${i}`, status: 'active', visibility: 'shared', strength: .8,
501
+ links: i < 2999 ? [{ to: `perf-${String(i + 1).padStart(5, '0')}`, kind: 'relation' }] : [] }]
502
+ }))
503
+ state.savePrivateIndex(libraryId, { entries })
504
+ const coldStart = performance.now(), overview = getGraphOverview({ libraryId }), coldMs = performance.now() - coldStart
505
+ const query = { libraryId, bbox: overview.bbox, zoom: 1, limit: 3000 }
506
+ const original = fs.lstatSync, samples = [], counts = [], cacheBefore = graphAdjacencyDiagnostics()
507
+ let result, calls = 0
508
+ try {
509
+ fs.lstatSync = function () { calls++; return original.apply(this, arguments) }
510
+ for (let i = 0; i < 3; i++) {
511
+ calls = 0
512
+ const start = performance.now(); result = getGraphOverview(query); samples.push(performance.now() - start); counts.push(calls)
513
+ }
514
+ } finally { fs.lstatSync = original; state.flushState() }
515
+ assert.equal(result.nodes.length, 3000); assert.equal(result.edges.length, 2999)
516
+ assert.ok(result.edges.every(edge => entries[edge.from].links.some(link => link.to === edge.to)))
517
+ const diagnostic = graphAdjacencyDiagnostics()
518
+ assert.equal(diagnostic.fallbacks, cacheBefore.fallbacks)
519
+ assert.ok(diagnostic.hits > cacheBefore.hits)
520
+ assert.ok(counts.every(count => count < 800), `per-node full validation returned: ${JSON.stringify(counts)}`)
521
+ t.diagnostic(JSON.stringify({ measurement: 'getGraphOverview-3k-near-view', coldSourceAndPublishMs: coldMs,
522
+ warmServiceMs: samples, lstatPerService: counts, nodes: result.nodes.length, edges: result.edges.length,
523
+ transientBuffersExcludedFromResidentCap: true }))
524
+ })
525
+
526
+ test('the derived namespace is excluded from truth backups and package runtime payloads', async () => {
527
+ const directory = path.join(home, 'rt', 'graph-adjacency'), options = setup({ directory })
528
+ persisted(options)
529
+ fs.writeFileSync(path.join(home, 'state.json'), JSON.stringify({ version: 1, sessions: {} }))
530
+ const { createBackup } = await import('../lib/backup.js')
531
+ const backup = await createBackup({ label: 'adjacency-exclusion', checkpointMaintenance: () => null })
532
+ const files = tree(backup.dir).map(file => path.relative(backup.dir, file).replaceAll('\\', '/'))
533
+ assert.equal(files.some(file => file.includes('graph-adjacency') || file.endsWith('edges.idx')), false)
534
+ const packageJson = JSON.parse(fs.readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'))
535
+ assert.equal(packageJson.files.some(file => /^(rt|data)(\/|$)/.test(file)), false)
536
+ })