dsh-memu-memory 1.4.4 → 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 (180) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +11 -0
  3. package/README.md +33 -14
  4. package/README.zh.md +34 -12
  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/private.js +47 -21
  63. package/lib/recall-cache.js +20 -34
  64. package/lib/retention.js +173 -0
  65. package/lib/rpc.js +135 -52
  66. package/lib/rt-index/builder.js +209 -0
  67. package/lib/rt-index/format.js +231 -0
  68. package/lib/rt-index/manifest.js +105 -0
  69. package/lib/rt-index/reader.js +673 -0
  70. package/lib/rt-index-retention.js +151 -0
  71. package/lib/rt-index-service.js +283 -0
  72. package/lib/rt-index-worker.js +21 -0
  73. package/lib/salient-wake.js +55 -4
  74. package/lib/state.js +195 -24
  75. package/lib/temporal.js +39 -13
  76. package/lib/token-measurement.js +126 -0
  77. package/lib/tools.js +101 -6
  78. package/lib/turn-log.js +108 -3
  79. package/lib/webui/graph-layout-worker.js +68 -0
  80. package/lib/webui/graph-local-physics.js +390 -0
  81. package/lib/webui/graph-spatial-grid.js +64 -0
  82. package/lib/webui/graph-view.bundle.js +6 -1
  83. package/lib/webui/graph-view.js +478 -135
  84. package/lib/webui/graph-webgl-renderer.js +74 -0
  85. package/lib/webui/standalone.js +1 -1
  86. package/lib/worker-pool.js +30 -4
  87. package/package.json +3 -2
  88. package/scripts/acceptance-local.mjs +4 -10
  89. package/scripts/bench-all-libraries.mjs +47 -0
  90. package/scripts/check-classic-graph-browser.mjs +189 -0
  91. package/scripts/check-client-browser.mjs +929 -0
  92. package/scripts/check-graph-browser.mjs +6 -0
  93. package/scripts/check-graph-elastic-browser.mjs +139 -0
  94. package/scripts/check-memory-review-browser.mjs +124 -0
  95. package/scripts/entity-dedupe.mjs +19 -3
  96. package/scripts/graph-artifact-provenance.mjs +30 -0
  97. package/scripts/graph-freeze-manifest.mjs +129 -0
  98. package/scripts/graph-geometry-fixture.mjs +40 -0
  99. package/scripts/graph-physics-bench.mjs +218 -0
  100. package/scripts/graph-scale-bench.mjs +213 -0
  101. package/scripts/graph-scale-memory.mjs +48 -0
  102. package/scripts/graph-service-bench.mjs +72 -0
  103. package/scripts/make-readme-shots.mjs +17 -5
  104. package/scripts/preview.mjs +1 -0
  105. package/scripts/rebuild-rt.mjs +18 -0
  106. package/scripts/scale-bench.mjs +183 -0
  107. package/scripts/simulate-injection.mjs +47 -8
  108. package/scripts/verify-host-fixtures.mjs +108 -0
  109. package/scripts/verify-host-recovery.mjs +565 -0
  110. package/scripts/verify-vector-recovery.mjs +740 -0
  111. package/tests/auto-link-candidates.test.mjs +20 -0
  112. package/tests/browser.test.mjs +16 -2
  113. package/tests/client-export.test.mjs +16 -1
  114. package/tests/client-pagination.test.mjs +1495 -0
  115. package/tests/client-render.test.mjs +223 -28
  116. package/tests/consolidation-fork.test.mjs +93 -10
  117. package/tests/consolidation-ledger.test.mjs +17 -1
  118. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  119. package/tests/diagnostic-report.test.mjs +429 -0
  120. package/tests/diagnostic-wiring.test.mjs +88 -0
  121. package/tests/diagnostics.test.mjs +27 -0
  122. package/tests/embedding-download.test.mjs +44 -0
  123. package/tests/engine-source-settings.test.mjs +69 -0
  124. package/tests/engine-sources.test.mjs +145 -0
  125. package/tests/entity-dedupe.test.mjs +143 -0
  126. package/tests/entity-merge-review.test.mjs +363 -0
  127. package/tests/entity-merge.test.mjs +12 -4
  128. package/tests/entity-review.test.mjs +87 -0
  129. package/tests/environment-check.test.mjs +51 -1
  130. package/tests/feedback.test.mjs +95 -0
  131. package/tests/graph-adjacency-index.test.mjs +536 -0
  132. package/tests/graph-cascade.test.mjs +229 -0
  133. package/tests/graph-import-diagnostic.test.mjs +25 -0
  134. package/tests/graph-overview.test.mjs +709 -0
  135. package/tests/graph-session-authorization.test.mjs +419 -0
  136. package/tests/graph-view-geometry.test.mjs +426 -0
  137. package/tests/graph-view-scale.test.mjs +88 -0
  138. package/tests/graph-view.test.mjs +444 -5
  139. package/tests/graph.test.mjs +43 -0
  140. package/tests/help-page.test.mjs +128 -54
  141. package/tests/inbound.test.mjs +19 -0
  142. package/tests/index-pagination.test.mjs +113 -0
  143. package/tests/index-read-view.test.mjs +212 -0
  144. package/tests/inject-guide.test.mjs +9 -0
  145. package/tests/injection-dedupe.test.mjs +213 -0
  146. package/tests/lexicon-recall.test.mjs +641 -0
  147. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  148. package/tests/lexicon-rt.test.mjs +468 -0
  149. package/tests/local-embedding-worker.test.mjs +38 -0
  150. package/tests/local-vector-service.test.mjs +32 -3
  151. package/tests/maintenance-compat.test.mjs +128 -0
  152. package/tests/maintenance-settlement.test.mjs +1003 -0
  153. package/tests/managed-memory.test.mjs +39 -11
  154. package/tests/managed-runtime.test.mjs +109 -0
  155. package/tests/memory-fields.test.mjs +24 -12
  156. package/tests/observed-evidence.test.mjs +52 -0
  157. package/tests/port-surface.test.mjs +93 -1
  158. package/tests/recall-cache.test.mjs +56 -3
  159. package/tests/recall-dedup.test.mjs +63 -2
  160. package/tests/retention.test.mjs +260 -0
  161. package/tests/rt-index-cross-library.test.mjs +230 -0
  162. package/tests/rt-index-integration.test.mjs +194 -0
  163. package/tests/rt-index-retention.test.mjs +552 -0
  164. package/tests/rt-index-scale.test.mjs +204 -0
  165. package/tests/rt-index.test.mjs +705 -0
  166. package/tests/salient-date-boundaries.test.mjs +121 -0
  167. package/tests/salient-wake.test.mjs +29 -0
  168. package/tests/scale-bench.test.mjs +53 -0
  169. package/tests/settings-plumbing.test.mjs +25 -0
  170. package/tests/simulate-injection.test.mjs +15 -1
  171. package/tests/standalone-navigation.test.mjs +44 -0
  172. package/tests/state.test.mjs +51 -0
  173. package/tests/temporal-precision.test.mjs +102 -0
  174. package/tests/temporal.test.mjs +10 -6
  175. package/tests/token-measurement.test.mjs +98 -0
  176. package/tests/tool-schema.test.mjs +41 -5
  177. package/tests/tools.test.mjs +6 -3
  178. package/tests/turn-token-budget.test.mjs +149 -0
  179. package/tests/webui-auth.test.mjs +57 -1
  180. package/tests/webui.test.mjs +40 -15
@@ -0,0 +1,705 @@
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 { buildCorpus, bm25, tokenize } from '../lib/text-retrieval.js'
7
+ import {
8
+ createRtIndex, createQueryView, openRtIndex, candidatesFromPostings,
9
+ memoryDocumentText, indexLocation, listArtifacts, clearRtIndexCaches, rtIndexCacheStats,
10
+ } from '../lib/rt-index/reader.js'
11
+ import { rebuildRtIndex } from '../lib/rt-index/builder.js'
12
+ import { FORMAT_VERSION, HEADER_BYTES, HEAD_BYTES, POSTING_BYTES, sha256, encodeHeads, decodeHead, validateBinary, encodePostings } from '../lib/rt-index/format.js'
13
+ import { sourceInfo } from '../lib/rt-index/manifest.js'
14
+
15
+ const entry = (content, extra = {}) => ({ title: '', content, status: 'active', layer: 'long_term', visibility: 'shared', createdAt: '2026-11-01T00:00:00Z', updatedAt: '2026-11-01T00:00:00Z', ...extra })
16
+ const truth = (entries, revision = sha256(JSON.stringify(entries))) => ({ index: { version: 1, entries }, revision, fingerprint: `source:${revision}`, count: Object.keys(entries).length })
17
+
18
+ function fixture(t, { entries = { 'mem-apple': entry('orchard apples'), 'mem-stars': entry('星空 海边约定') }, ...overrides } = {}) {
19
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'dmm-rt-test-'))
20
+ const warnings = []
21
+ const signals = []
22
+ const comparisons = []
23
+ const options = { directory, libraryId: 'library-a', mode: 'on', logger: { warn: text => warnings.push(text) }, onSignal: signal => signals.push(signal), onCompare: value => comparisons.push(value), ...overrides }
24
+ const controller = createRtIndex(options)
25
+ const source = truth(entries)
26
+ const visibility = { visibleIds: Object.keys(entries) }
27
+ t.after(() => { clearRtIndexCaches(); fs.rmSync(directory, { recursive: true, force: true }) })
28
+ return { directory, options, controller, source, visibility, warnings, signals, comparisons }
29
+ }
30
+
31
+ function published(f) {
32
+ const { root } = indexLocation(f.options)
33
+ const pointerFile = path.join(root, 'current.json')
34
+ const pointer = JSON.parse(fs.readFileSync(pointerFile, 'utf8'))
35
+ const manifestFile = path.join(root, pointer.generation, 'manifest.json')
36
+ const manifest = JSON.parse(fs.readFileSync(manifestFile, 'utf8'))
37
+ return { root, pointerFile, pointer, manifestFile, manifest }
38
+ }
39
+
40
+ function rewriteManifest(f, change) {
41
+ const info = published(f)
42
+ change(info.manifest)
43
+ const bytes = JSON.stringify(info.manifest)
44
+ fs.writeFileSync(info.manifestFile, bytes)
45
+ fs.writeFileSync(info.pointerFile, JSON.stringify({ ...info.pointer, sha256: sha256(bytes) }))
46
+ }
47
+
48
+ function artifactFile(f, name, segment = 0) {
49
+ const info = published(f)
50
+ return path.join(info.root, 'segments', info.manifest.segments[segment].id, name)
51
+ }
52
+
53
+ function oracle(source, query, visibleIds) {
54
+ const corpus = buildCorpus(visibleIds.map(id => ({ id, title: source.index.entries[id].title || '', content: memoryDocumentText(source.index.entries[id]) })))
55
+ const tokens = Array.isArray(query) ? query : tokenize(query)
56
+ const hits = visibleIds.map(id => ({ id, score: bm25(tokens, corpus.docs.get(id), corpus) }))
57
+ .filter(row => row.score > 0)
58
+ .sort((a, b) => b.score - a.score || String(source.index.entries[b.id].updatedAt || source.index.entries[b.id].createdAt || '').localeCompare(String(source.index.entries[a.id].updatedAt || source.index.entries[a.id].createdAt || '')))
59
+ return { corpus, hits }
60
+ }
61
+
62
+ test('sourceInfo accepts explicit count without enumerating the source or hashing content', () => {
63
+ const entries = new Proxy({}, { ownKeys() { throw new Error('unexpected enumeration') } })
64
+ assert.deepEqual(sourceInfo({ index: { entries }, revision: 'revision', fingerprint: 'fp', count: 100000 }), { revision: 'revision', fingerprint: 'fp', count: 100000 })
65
+ })
66
+
67
+ test('fixed little-endian heads and postings round-trip without content in metadata', () => {
68
+ const head = { id: 'mem-real', domain: 'rp', layer: 'long_term', status: 'active', visibility: 'secret', tokenCount: 7, bodyShard: 2, bodyOffset: 17, bodyLength: 31, attachmentMissing: true, createdAt: 10, updatedAt: 20, strengthBase: 0.75, strengthAt: 30 }
69
+ const encoded = encodeHeads([head])
70
+ assert.equal(encoded.buffer.length, HEADER_BYTES + HEAD_BYTES)
71
+ assert.equal(encoded.buffer.readUInt32LE(4), FORMAT_VERSION)
72
+ assert.deepEqual(decodeHead(encoded.buffer, encoded.metadata, 0), head)
73
+ const posting = encodePostings(new Map([['pear', [2, 65535]], ['apple', [0, 1]]]))
74
+ assert.equal(validateBinary(posting.buffer, 'DMRP', POSTING_BYTES), 2)
75
+ assert.deepEqual(posting.terms, [['apple', 0, 1], ['pear', 1, 1]])
76
+ assert.equal(posting.buffer.readUInt16LE(HEADER_BYTES + POSTING_BYTES + 4), 65535)
77
+ assert.throws(() => encodePostings(new Map([['overflow', [0, 65536]]])), { code: 'RT_TF_OVERFLOW' })
78
+ })
79
+
80
+ test('pure source view selects IDs once and exposes the same reusable score/candidate API', t => {
81
+ const f = fixture(t)
82
+ let calls = 0
83
+ const view = createQueryView(f.source, { isVisible: (_, id) => { calls++; return id === 'mem-stars' } })
84
+ assert.equal(calls, 2)
85
+ assert.deepEqual(view.candidates(['海']), ['mem-stars'])
86
+ assert.deepEqual(view.score(['海']).hits.map(hit => hit.id), ['mem-stars'])
87
+ view.score(['星'])
88
+ assert.equal(calls, 2)
89
+ assert.equal(fs.readdirSync(f.directory).length, 0)
90
+ })
91
+
92
+ test('full build produces disposable artifacts and returns exact source IDs', t => {
93
+ const f = fixture(t)
94
+ const before = JSON.stringify(f.source)
95
+ assert.equal(f.controller.rebuild(f.source).ok, true)
96
+ const result = f.controller.search(f.source, 'apples', f.visibility)
97
+ assert.equal(result.backend, 'rt')
98
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-apple'])
99
+ assert.equal(JSON.stringify(f.source), before)
100
+ const metadata = fs.readFileSync(artifactFile(f, 'metadata.json'), 'utf8')
101
+ assert.ok(!metadata.includes('orchard apples'))
102
+ assert.equal(f.controller.readBody(f.source, 'mem-stars', f.visibility).body, '星空 海边约定')
103
+ assert.equal(f.signals.length, 0)
104
+ })
105
+
106
+ for (const query of ['海', '海边', '星空 海边', 'orchard', ['orchard', 'orchard', 'apples'], '2026-11-30 42 https://example.test/path']) {
107
+ test(`BM25 exact score and ordering parity for ${JSON.stringify(query)}`, t => {
108
+ const f = fixture(t, { entries: {
109
+ 'mem-z': entry('海边 星空 海边 orchard orchard apples 42 https://example.test/path', { title: '2026-11-30' }),
110
+ 'mem-a': entry('海边 orchard apples', { updatedAt: '2026-11-02T00:00:00Z' }),
111
+ 'mem-b': entry('other words', { tags: ['星空'], attachments: [{ caption: '海边', kind: 'photo' }] }),
112
+ } })
113
+ assert.equal(f.controller.rebuild(f.source).ok, true)
114
+ const result = f.controller.search(f.source, query, f.visibility)
115
+ const expected = oracle(f.source, query, f.visibility.visibleIds)
116
+ assert.deepEqual(result.hits, expected.hits)
117
+ assert.equal(result.corpus.size, expected.corpus.size)
118
+ assert.equal(result.corpus.avgdl, expected.corpus.avgdl)
119
+ for (const [term, df] of result.corpus.df) assert.equal(df, expected.corpus.df.get(term))
120
+ })
121
+ }
122
+
123
+ test('default candidates include every single-term posting even above BM25 frequency cap', t => {
124
+ const entries = Object.fromEntries(Array.from({ length: 64 }, (_, i) => [`mem-${i}`, entry(`common term${i}`)]))
125
+ const f = fixture(t, { entries })
126
+ assert.equal(f.controller.rebuild(f.source).ok, true)
127
+ const snapshot = openRtIndex(f.options, f.source)
128
+ const view = createQueryView(f.source, { snapshot, ...f.visibility })
129
+ assert.deepEqual(candidatesFromPostings(view, ['common']), Object.keys(entries))
130
+ assert.deepEqual(view.candidates(['common'], { dfCap: 12 }), [])
131
+ assert.deepEqual(view.candidates(['common', 'term1'], { minShared: 2 }), ['mem-1'])
132
+ assert.deepEqual(view.score(['common']).hits, [])
133
+ assert.equal(view.score(['common']).corpus.df.get('common'), 64)
134
+ })
135
+
136
+ test('score skips zero-contribution document maps while preserving the complete posting union', t => {
137
+ const entries = Object.fromEntries(Array.from({ length: 64 }, (_, i) => [`mem-${i}`, entry(`common term${i}`)]))
138
+ const f = fixture(t, { entries, segmentDocs: 16 })
139
+ assert.equal(f.controller.rebuild(f.source).ok, true)
140
+ const view = f.controller.createView(f.source, f.visibility)
141
+ for (const tokens of [['common'], ['common', 'term1', 'term1'], ['term1']]) {
142
+ const expected = oracle(f.source, tokens, f.visibility.visibleIds)
143
+ const result = view.score(tokens)
144
+ assert.deepEqual(result.hits, expected.hits)
145
+ assert.equal(result.corpus.size, expected.corpus.size)
146
+ assert.equal(result.corpus.avgdl, expected.corpus.avgdl)
147
+ assert.equal(result.stats.candidates, tokens[0] === 'term1' ? 1 : 64)
148
+ assert.equal(result.stats.materialized, tokens.length === 1 && tokens[0] === 'common' ? 0 : 1)
149
+ for (const term of new Set(tokens)) assert.equal(result.corpus.df.get(term), expected.corpus.df.get(term))
150
+ }
151
+ const postings = view.queryPostings(['common', 'term1'])
152
+ assert.equal(postings.docs.size, 64)
153
+ assert.equal(postings.corpus.df.get('common'), 64)
154
+ assert.equal(postings.docs.get('mem-1').tf.get('common'), 1)
155
+ assert.equal(postings.docs.get('mem-1').tf.get('term1'), 1)
156
+ })
157
+
158
+ test('score counts authorized df before the BM25 gate, including its exact boundary', t => {
159
+ const entries = Object.fromEntries(Array.from({ length: 100 }, (_, i) => [`mem-${i}`,
160
+ entry(`${i < 64 ? 'common' : 'neutral'} unique${i}`)]))
161
+ const f = fixture(t, { entries, segmentDocs: 9 })
162
+ assert.equal(f.controller.rebuild(f.source).ok, true)
163
+ for (const common of [11, 12, 13]) {
164
+ const visibleIds = [...Array.from({ length: common }, (_, i) => `mem-${i}`),
165
+ ...Array.from({ length: 40 - common }, (_, i) => `mem-${64 + i}`)]
166
+ const view = f.controller.createView(f.source, { visibleIds })
167
+ const expected = oracle(f.source, ['common', 'common'], visibleIds)
168
+ const result = view.score(['common', 'common'])
169
+ assert.deepEqual(result.hits, expected.hits)
170
+ assert.equal(result.corpus.size, 40)
171
+ assert.equal(result.corpus.avgdl, expected.corpus.avgdl)
172
+ assert.equal(result.corpus.df.get('common'), common)
173
+ assert.equal(result.stats.candidates, common)
174
+ assert.equal(result.stats.materialized, common <= 12 ? common : 0)
175
+ assert.equal(view.queryPostings(['common']).docs.size, common)
176
+ }
177
+ })
178
+
179
+ test('zero-contribution posting rows are still validated and corruption falls back to real source ids', t => {
180
+ const entries = Object.fromEntries(Array.from({ length: 64 }, (_, i) => [`mem-${i}`, entry(`common term${i}`)]))
181
+ const f = fixture(t, { entries })
182
+ assert.equal(f.controller.rebuild(f.source).ok, true)
183
+ const view = f.controller.createView(f.source, f.visibility)
184
+ assert.equal(view.score(['common']).backend, 'rt')
185
+ const original = fs.readSync
186
+ let injected = false
187
+ fs.readSync = function (fd, buffer, offset, length, position) {
188
+ const read = Reflect.apply(original, this, arguments)
189
+ if (!injected && position === HEADER_BYTES && length === 64 * POSTING_BYTES) {
190
+ buffer.writeUInt16LE(0, offset + 4)
191
+ injected = true
192
+ }
193
+ return read
194
+ }
195
+ let result
196
+ try { result = view.score(['common', 'term1']) } finally { fs.readSync = original }
197
+ assert.equal(injected, true)
198
+ assert.equal(result.backend, 'source')
199
+ assert.equal(result.fallback, 'RT_CORRUPT')
200
+ assert.deepEqual(result.hits, oracle(f.source, ['common', 'term1'], f.visibility.visibleIds).hits)
201
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-1'])
202
+ assert.ok(f.signals.some(signal => signal.code === 'RT_CORRUPT'))
203
+ })
204
+
205
+ test('superseded postings cannot gate a term whose active authorized df still scores', t => {
206
+ const entries = Object.fromEntries(Array.from({ length: 40 }, (_, i) => [`mem-${i}`, entry(`common unique${i}`)]))
207
+ const f = fixture(t, { entries, segmentDocs: 16 })
208
+ assert.equal(f.controller.rebuild(f.source).ok, true)
209
+ const next = truth(Object.fromEntries(Object.entries(entries).map(([id, row], i) => [id,
210
+ i < 12 ? row : entry(`replacement unique${i}`)])))
211
+ assert.equal(f.controller.afterCommit({ source: next, previousRevision: f.source.revision,
212
+ changedIds: f.visibility.visibleIds.slice(12), removedIds: [] }).ok, true)
213
+ const result = f.controller.search(next, ['common'], f.visibility)
214
+ assert.deepEqual(result.hits, oracle(next, ['common'], f.visibility.visibleIds).hits)
215
+ assert.equal(result.hits.length, 12)
216
+ assert.equal(result.corpus.df.get('common'), 12)
217
+ assert.equal(result.stats.candidates, 12)
218
+ assert.equal(result.stats.materialized, 12)
219
+ })
220
+
221
+ test('queryPostings retains locally gated terms that contribute under cross-library df', t => {
222
+ const entries = Object.fromEntries(Array.from({ length: 20 }, (_, i) => [`mem-a-${i}`, entry('common')]))
223
+ const f = fixture(t, { entries })
224
+ assert.equal(f.controller.rebuild(f.source).ok, true)
225
+ const view = f.controller.createView(f.source, f.visibility)
226
+ assert.deepEqual(view.score(['common']).hits, [])
227
+ const local = view.queryPostings(['common'])
228
+ const otherSource = truth(Object.fromEntries(Array.from({ length: 80 }, (_, i) => [`mem-b-${i}`, entry(`unique${i}`)])))
229
+ const other = createQueryView(otherSource, { isVisible: () => true }).queryPostings(['common'])
230
+ const size = local.corpus.size + other.corpus.size
231
+ const joint = { size, avgdl: (local.totalLen + other.totalLen) / size,
232
+ df: new Map([['common', (local.corpus.df.get('common') || 0) + (other.corpus.df.get('common') || 0)]]) }
233
+ const expected = buildCorpus(Object.entries({ ...entries, ...otherSource.index.entries })
234
+ .map(([id, row]) => ({ id, title: row.title, content: memoryDocumentText(row) })))
235
+ assert.equal(local.docs.size, 20)
236
+ for (const [id, doc] of local.docs) {
237
+ assert.ok(bm25(['common'], doc, joint) > 0)
238
+ assert.equal(bm25(['common'], doc, joint), bm25(['common'], expected.docs.get(id), expected))
239
+ }
240
+ })
241
+
242
+ test('long queries retain shared BM25 top-IDF term policy and exact frequencies', t => {
243
+ const entries = Object.fromEntries(Array.from({ length: 90 }, (_, i) => [`mem-${i}`, entry(`term${i} stable${i % 5}`)]))
244
+ const f = fixture(t, { entries })
245
+ assert.equal(f.controller.rebuild(f.source).ok, true)
246
+ const query = [...Array.from({ length: 90 }, (_, i) => `term${i}`), 'absent', 'term3']
247
+ assert.deepEqual(f.controller.search(f.source, query, f.visibility).hits, oracle(f.source, query, f.visibility.visibleIds).hits)
248
+ })
249
+
250
+ test('hidden documents never contribute df, N, avgdl or term gating', t => {
251
+ const entries = { 'mem-visible': entry('orchard apples') }
252
+ for (let i = 0; i < 80; i++) entries[`mem-hidden-${i}`] = entry('orchard '.repeat(200), { visibility: 'secret' })
253
+ const f = fixture(t, { entries })
254
+ assert.equal(f.controller.rebuild(f.source).ok, true)
255
+ let calls = 0
256
+ const view = f.controller.createView(f.source, { isVisible: e => { calls++; return e.visibility !== 'secret' } })
257
+ const result = view.score(['orchard'])
258
+ assert.equal(calls, 81)
259
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-visible'])
260
+ assert.equal(result.corpus.size, 1)
261
+ assert.equal(result.corpus.df.get('orchard'), 1)
262
+ assert.equal(result.corpus.avgdl, 2)
263
+ assert.deepEqual(result.hits, oracle(f.source, ['orchard'], ['mem-visible']).hits)
264
+ view.score(['apples'])
265
+ assert.equal(calls, 81)
266
+ })
267
+
268
+ test('same-count role sets and repeated visible IDs stay isolated without permission caching', t => {
269
+ const f = fixture(t, { entries: { 'mem-alice': entry('orchard alice'), 'mem-bob': entry('orchard bob') } })
270
+ assert.equal(f.controller.rebuild(f.source).ok, true)
271
+ for (const id of ['mem-alice', 'mem-bob', 'mem-alice']) {
272
+ const result = f.controller.search(f.source, 'orchard', { visibleIds: [id, id] })
273
+ assert.deepEqual(result.hits.map(hit => hit.id), [id])
274
+ assert.equal(result.corpus.size, 1)
275
+ }
276
+ assert.throws(() => f.controller.search(f.source, 'orchard'), { code: 'RT_VISIBILITY_REQUIRED' })
277
+ assert.throws(() => f.controller.search(f.source, 'orchard', { visibleIds: 'mem-alice' }), { code: 'RT_VISIBILITY_INVALID' })
278
+ })
279
+
280
+ test('default shadow serves source results and compares exact IDs, scores and order', t => {
281
+ const prior = process.env.DSH_MEMU_RT_INDEX
282
+ delete process.env.DSH_MEMU_RT_INDEX
283
+ t.after(() => { if (prior === undefined) delete process.env.DSH_MEMU_RT_INDEX; else process.env.DSH_MEMU_RT_INDEX = prior })
284
+ const f = fixture(t, { mode: undefined })
285
+ assert.equal(f.controller.mode, 'shadow')
286
+ assert.equal(f.controller.rebuild(f.source).ok, true)
287
+ let calls = 0
288
+ const view = f.controller.createView(f.source, { isVisible: () => { calls++; return true } })
289
+ const result = view.score(['orchard'])
290
+ assert.equal(calls, 2)
291
+ assert.equal(result.backend, 'source')
292
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-apple'])
293
+ assert.deepEqual(result.comparison, { expected: 1, actual: 1, missing: 0, extra: 0, agreement: 1, scoreDifferences: 0, orderEqual: true })
294
+ assert.equal(f.comparisons.length, 1)
295
+ })
296
+
297
+ test('off mode never reads or writes derived paths and serves real source IDs', t => {
298
+ const f = fixture(t, { mode: 'off' })
299
+ assert.deepEqual(f.controller.rebuild(f.source), { ok: false, disabled: true })
300
+ assert.equal(f.controller.search(f.source, 'orchard', f.visibility).backend, 'source')
301
+ assert.deepEqual(f.controller.search(f.source, 'orchard', f.visibility).hits.map(hit => hit.id), ['mem-apple'])
302
+ assert.equal(fs.readdirSync(f.directory).length, 0)
303
+ assert.equal(f.signals.length, 0)
304
+ })
305
+
306
+ test('missing first generation falls back with warning, binding signal and rebuild request', t => {
307
+ const f = fixture(t)
308
+ const result = f.controller.search(f.source, 'orchard', f.visibility)
309
+ assert.equal(result.fallback, 'RT_MISSING')
310
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-apple'])
311
+ assert.ok(f.warnings.some(text => text.includes('RT_MISSING')))
312
+ assert.deepEqual(f.signals[0], { code: 'RT_MISSING', operation: 'validate-view', fallback: true, rebuildRequired: true, action: 'schedule-rebuild' })
313
+ })
314
+
315
+ test('cached view detects directory deletion on the very next score, without waiting for TTL', t => {
316
+ const f = fixture(t)
317
+ assert.equal(f.controller.rebuild(f.source).ok, true)
318
+ let calls = 0
319
+ const view = f.controller.createView(f.source, { isVisible: () => { calls++; return true } })
320
+ assert.equal(view.score(['orchard']).backend, 'rt')
321
+ const { root } = indexLocation(f.options)
322
+ fs.rmSync(root, { recursive: true, force: true })
323
+ const result = view.score(['orchard'])
324
+ assert.equal(result.backend, 'source')
325
+ assert.equal(result.fallback, 'RT_MISSING')
326
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-apple'])
327
+ assert.equal(calls, 2)
328
+ assert.equal(view.validate().ok, false)
329
+ assert.equal(f.controller.validate(f.source).ok, false)
330
+ assert.equal(f.controller.rebuild(f.source).ok, true)
331
+ assert.equal(view.score(['orchard']).backend, 'rt')
332
+ })
333
+
334
+ for (const name of ['heads.bin', 'postings.bin', 'metadata.json', 'terms.json', 'terms.bin', 'bodies/00000000.bin']) {
335
+ test(`cold and already-cached artifact corruption falls back with real IDs: ${name}`, t => {
336
+ const f = fixture(t)
337
+ assert.equal(f.controller.rebuild(f.source).ok, true)
338
+ const view = f.controller.createView(f.source, f.visibility)
339
+ assert.equal(view.score(['orchard']).backend, 'rt')
340
+ const file = artifactFile(f, name)
341
+ const bytes = fs.readFileSync(file)
342
+ bytes[bytes.length - 1] ^= 1
343
+ fs.writeFileSync(file, bytes)
344
+ const hot = view.score(['orchard'])
345
+ assert.equal(hot.backend, 'source')
346
+ assert.deepEqual(hot.hits.map(hit => hit.id), ['mem-apple'])
347
+ assert.equal(hot.fallback, 'RT_ARTIFACT_CHANGED')
348
+ clearRtIndexCaches()
349
+ const cold = f.controller.search(f.source, 'orchard', f.visibility)
350
+ assert.equal(cold.fallback, 'RT_CORRUPT')
351
+ assert.deepEqual(cold.hits.map(hit => hit.id), ['mem-apple'])
352
+ assert.equal(f.controller.rebuild(f.source).ok, true)
353
+ assert.equal(view.score(['orchard']).backend, 'rt')
354
+ })
355
+ }
356
+
357
+ for (const [field, value, code] of [
358
+ ['version', 999, 'RT_VERSION_MISMATCH'], ['identity', 'wrong-library', 'RT_IDENTITY_MISMATCH'],
359
+ ['namespace', 'wrong-namespace', 'RT_IDENTITY_MISMATCH'], ['libraryId', 'wrong-library', 'RT_IDENTITY_MISMATCH'],
360
+ ['ruler', 'changed-code', 'RT_RULER_MISMATCH'], ['documentVersion', 'changed-fields', 'RT_RULER_MISMATCH'],
361
+ ]) {
362
+ test(`manifest ${field} mismatch cannot be used as an empty corpus`, t => {
363
+ const f = fixture(t)
364
+ assert.equal(f.controller.rebuild(f.source).ok, true)
365
+ rewriteManifest(f, manifest => { manifest[field] = value })
366
+ const result = f.controller.search(f.source, 'orchard', f.visibility)
367
+ assert.equal(result.fallback, code)
368
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-apple'])
369
+ })
370
+ }
371
+
372
+ test('pointer checksum, path traversal and truncated binary data fail safely', t => {
373
+ const f = fixture(t)
374
+ assert.equal(f.controller.rebuild(f.source).ok, true)
375
+ let info = published(f)
376
+ fs.writeFileSync(info.pointerFile, JSON.stringify({ ...info.pointer, generation: '../../outside' }))
377
+ assert.equal(f.controller.search(f.source, 'orchard', f.visibility).fallback, 'RT_CORRUPT')
378
+ assert.equal(f.controller.rebuild(f.source).ok, true)
379
+ info = published(f)
380
+ fs.appendFileSync(info.manifestFile, ' ')
381
+ assert.equal(f.controller.search(f.source, 'orchard', f.visibility).fallback, 'RT_CORRUPT')
382
+ assert.equal(f.controller.rebuild(f.source).ok, true)
383
+ rewriteManifest(f, manifest => { manifest.segments[0].files['../../outside'] = { size: 0, sha256: sha256('') } })
384
+ assert.equal(f.controller.search(f.source, 'orchard', f.visibility).fallback, 'RT_CORRUPT')
385
+ })
386
+
387
+ test('source revision, explicit fingerprint and count each gate reuse', t => {
388
+ const f = fixture(t)
389
+ assert.equal(f.controller.rebuild(f.source).ok, true)
390
+ for (const [change, code] of [[{ revision: 'r2' }, 'RT_REVISION_MISMATCH'], [{ fingerprint: 'fp2' }, 'RT_FINGERPRINT_MISMATCH'], [{ count: 3 }, 'RT_COUNT_MISMATCH']]) {
391
+ const result = f.controller.search({ ...f.source, ...change }, 'orchard', f.visibility)
392
+ assert.equal(result.fallback, code)
393
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-apple'])
394
+ }
395
+ })
396
+
397
+ test('incremental replacement, insert and remove preserve exact BM25 and body identity', t => {
398
+ let tokenized = 0
399
+ const f = fixture(t, { documentText: e => { tokenized++; return memoryDocumentText(e) }, documentVersion: 'instrumented-v1' })
400
+ assert.equal(f.controller.rebuild(f.source).ok, true)
401
+ assert.equal(tokenized, 2)
402
+ const initialSegments = published(f).manifest.segments
403
+ const next = truth({ 'mem-apple': entry('pear pear newer'), 'mem-new': entry('peach pear') })
404
+ const delta = f.controller.afterCommit({ source: next, previousRevision: f.source.revision, previousFingerprint: f.source.fingerprint, changedIds: ['mem-apple', 'mem-new'], removedIds: ['mem-stars'] })
405
+ assert.equal(delta.ok, true)
406
+ assert.equal(delta.segments, 2)
407
+ assert.equal(tokenized, 4)
408
+ assert.deepEqual(published(f).manifest.segments[0], initialSegments[0])
409
+ const visibility = { visibleIds: Object.keys(next.index.entries) }
410
+ const result = f.controller.search(next, 'pear', visibility)
411
+ assert.deepEqual(result.hits, oracle(next, 'pear', visibility.visibleIds).hits)
412
+ assert.equal(tokenized, 4)
413
+ assert.equal(result.corpus.df.get('pear'), 2)
414
+ assert.equal(f.controller.readBody(next, 'mem-apple', visibility).body, 'pear pear newer')
415
+ assert.deepEqual(f.controller.search(next, 'orchard 星空', visibility).hits, [])
416
+ })
417
+
418
+ test('incremental same-score ties preserve source order rather than posting/segment order', t => {
419
+ const f = fixture(t, { entries: { 'mem-z': entry('pear'), 'mem-a': entry('pear') } })
420
+ assert.equal(f.controller.rebuild(f.source).ok, true)
421
+ const next = truth({ 'mem-z': entry('pear', { domain: 'rp' }), 'mem-a': entry('pear') })
422
+ assert.equal(f.controller.afterCommit({ source: next, previousRevision: f.source.revision, changedIds: ['mem-z'], removedIds: [] }).ok, true)
423
+ assert.deepEqual(f.controller.search(next, 'pear', f.visibility).hits.map(hit => hit.id), ['mem-z', 'mem-a'])
424
+ })
425
+
426
+ test('failed full/delta build leaves previous published generation intact', t => {
427
+ const f = fixture(t, { documentText: e => { if (e.content === 'FAIL') throw new Error('body secret must not leak'); return memoryDocumentText(e) }, documentVersion: 'fault-injection-v1' })
428
+ assert.equal(f.controller.rebuild(f.source).ok, true)
429
+ const prior = published(f).pointer
430
+ const next = truth({ ...f.source.index.entries, 'mem-bad': entry('FAIL') })
431
+ assert.equal(f.controller.rebuild(next).ok, false)
432
+ assert.deepEqual(published(f).pointer, prior)
433
+ assert.equal(f.controller.afterCommit({ source: next, previousRevision: f.source.revision, changedIds: ['mem-bad'], removedIds: [] }).ok, false)
434
+ assert.deepEqual(published(f).pointer, prior)
435
+ assert.equal(f.controller.search(f.source, 'orchard', f.visibility).backend, 'rt')
436
+ assert.ok(!JSON.stringify([f.signals, f.warnings]).includes('body secret'))
437
+ })
438
+
439
+ test('wrong delta base and over-budget builds request rebuild without replacing pointer', t => {
440
+ const f = fixture(t)
441
+ assert.equal(f.controller.rebuild(f.source).ok, true)
442
+ const prior = published(f).pointer
443
+ const next = truth({ ...f.source.index.entries, 'mem-new': entry('peach') })
444
+ const result = f.controller.afterCommit({ source: next, previousRevision: 'wrong', changedIds: ['mem-new'], removedIds: [] })
445
+ assert.equal(result.code, 'RT_REVISION_MISMATCH')
446
+ assert.throws(() => rebuildRtIndex({ ...f.options, maxBuildBytes: 1 }, next), { code: 'RT_BUILD_LIMIT' })
447
+ assert.deepEqual(published(f).pointer, prior)
448
+ })
449
+
450
+ test('segment cap requires explicit compaction and full rebuild recovers', t => {
451
+ const f = fixture(t, { entries: { 'mem-one': entry('fruit0') } })
452
+ let source = f.source
453
+ assert.equal(f.controller.rebuild(source).ok, true)
454
+ for (let i = 1; i < 8; i++) {
455
+ const next = truth({ 'mem-one': entry(`fruit${i}`) })
456
+ assert.equal(f.controller.afterCommit({ source: next, previousRevision: source.revision, changedIds: ['mem-one'], removedIds: [] }).ok, true)
457
+ source = next
458
+ }
459
+ const next = truth({ 'mem-one': entry('fruit8') })
460
+ assert.equal(f.controller.afterCommit({ source: next, previousRevision: source.revision, changedIds: ['mem-one'], removedIds: [] }).code, 'RT_COMPACTION_REQUIRED')
461
+ const fallback = f.controller.search(next, 'fruit8', { visibleIds: ['mem-one'] })
462
+ assert.deepEqual(fallback.hits.map(hit => hit.id), ['mem-one'])
463
+ assert.equal(fallback.backend, 'source')
464
+ assert.equal(f.controller.rebuild(next).segments, 1)
465
+ })
466
+
467
+ test('body shards use byte offsets and preserve multibyte and CRLF content exactly', t => {
468
+ const entries = { 'mem-a': entry('星空\r\n海边'), 'mem-b': entry('中文 English\nnext'), 'mem-c': entry('') }
469
+ const f = fixture(t, { entries, shardBytes: 12 })
470
+ assert.equal(f.controller.rebuild(f.source).ok, true)
471
+ for (const [id, value] of Object.entries(entries)) {
472
+ assert.equal(f.controller.readBody(f.source, id, f.visibility).body, value.content)
473
+ }
474
+ assert.ok(Object.keys(published(f).manifest.segments[0].files).filter(name => name.startsWith('bodies/')).length >= 2)
475
+ assert.equal(f.controller.readBody(f.source, 'mem-a', { isVisible: () => false }).body, null)
476
+ assert.equal(f.controller.readBody(f.source, 'mem-a', { visibleIds: ['mem-b'] }).body, null)
477
+ })
478
+
479
+ test('body corruption falls back to exact source content rather than corrupted text', t => {
480
+ const f = fixture(t)
481
+ assert.equal(f.controller.rebuild(f.source).ok, true)
482
+ assert.equal(f.controller.readBody(f.source, 'mem-apple', f.visibility).backend, 'rt')
483
+ fs.truncateSync(artifactFile(f, 'bodies/00000000.bin'), 1)
484
+ const result = f.controller.readBody(f.source, 'mem-apple', f.visibility)
485
+ assert.equal(result.body, 'orchard apples')
486
+ assert.equal(result.backend, 'source')
487
+ assert.equal(result.fallback, 'RT_ARTIFACT_CHANGED')
488
+ })
489
+
490
+ test('library, global, namespace and root identities cannot share same-ID postings', t => {
491
+ const f = fixture(t, { libraryId: '../../unsafe-as-a-path', entries: { 'mem-same': entry('orchard') } })
492
+ const bOptions = { ...f.options, libraryId: 'library-b' }
493
+ const b = createRtIndex(bOptions)
494
+ const bSource = truth({ 'mem-same': entry('stars') })
495
+ assert.equal(f.controller.rebuild(f.source).ok, true)
496
+ assert.equal(b.rebuild(bSource).ok, true)
497
+ assert.deepEqual(f.controller.search(f.source, 'orchard', f.visibility).hits.map(hit => hit.id), ['mem-same'])
498
+ assert.deepEqual(b.search(bSource, 'orchard', f.visibility).hits, [])
499
+ assert.deepEqual(b.search(bSource, 'stars', f.visibility).hits.map(hit => hit.id), ['mem-same'])
500
+ assert.notEqual(indexLocation(f.options).root, indexLocation({ ...f.options, libraryId: null }).root)
501
+ assert.notEqual(indexLocation(f.options).root, indexLocation({ ...f.options, namespace: 'lexicon' }).root)
502
+ const a = published(f)
503
+ const bInfo = published({ options: bOptions })
504
+ fs.cpSync(path.join(bInfo.root, bInfo.pointer.generation), path.join(a.root, bInfo.pointer.generation), { recursive: true })
505
+ fs.writeFileSync(a.pointerFile, JSON.stringify(bInfo.pointer))
506
+ const result = f.controller.search(f.source, 'orchard', f.visibility)
507
+ assert.equal(result.fallback, 'RT_IDENTITY_MISMATCH')
508
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-same'])
509
+ })
510
+
511
+ test('getSortedHeads projects only requested lightweight fields and carries source revision', t => {
512
+ const f = fixture(t, { entries: {
513
+ 'mem-old': entry('orchard', { title: 'not in head', domain: 'rp', strengthBase: 0.8 }),
514
+ 'mem-new': entry('orchard', { updatedAt: '2026-11-29T00:00:00Z', visibility: 'secret' }),
515
+ 'mem-last': entry('orchard', { updatedAt: '2026-11-30T00:00:00Z', attachmentMissing: true }),
516
+ } })
517
+ assert.equal(f.controller.rebuild(f.source).ok, true)
518
+ const result = f.controller.getSortedHeads(f.source, { isVisible: e => e.visibility !== 'secret', fields: ['id', 'domain', 'attachmentMissing'], limit: 1 })
519
+ assert.deepEqual(result.heads, [{ id: 'mem-last', domain: '', attachmentMissing: true }])
520
+ assert.equal(result.total, 2)
521
+ assert.equal(result.snapshotRevision, f.source.revision)
522
+ assert.equal(result.backend, 'rt')
523
+ const second = f.controller.getSortedHeads(f.source, { ...f.visibility, offset: 1, limit: 1, fields: ['id'] })
524
+ assert.deepEqual(second.heads, [{ id: 'mem-new' }])
525
+ })
526
+
527
+ test('fresh source passed to cached view is used immediately on revision mismatch', t => {
528
+ const f = fixture(t)
529
+ assert.equal(f.controller.rebuild(f.source).ok, true)
530
+ const view = f.controller.createView(f.source, { isVisible: () => true })
531
+ assert.equal(view.score(['orchard']).backend, 'rt')
532
+ const next = truth({ 'mem-current': entry('newword') })
533
+ assert.equal(view.validate(next).ok, false)
534
+ const result = view.score(['newword'])
535
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-current'])
536
+ assert.equal(result.backend, 'source')
537
+ assert.equal(f.controller.rebuild(next).ok, true)
538
+ assert.equal(view.score(['newword']).backend, 'rt')
539
+ })
540
+
541
+ test('logical quarantine invalidates cached views without moving/deleting directories', t => {
542
+ const f = fixture(t)
543
+ assert.equal(f.controller.rebuild(f.source).ok, true)
544
+ const view = f.controller.createView(f.source, f.visibility)
545
+ assert.equal(view.score(['orchard']).backend, 'rt')
546
+ const pointer = published(f).pointer
547
+ assert.equal(f.controller.quarantine().quarantined, true)
548
+ assert.deepEqual(published(f).pointer, pointer)
549
+ assert.equal(f.controller.validate(f.source).code, 'RT_QUARANTINED')
550
+ const result = view.score(['orchard'])
551
+ assert.equal(result.fallback, 'RT_QUARANTINED')
552
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-apple'])
553
+ assert.equal(f.controller.rebuild(f.source).ok, true)
554
+ assert.equal(view.score(['orchard']).backend, 'rt')
555
+ })
556
+
557
+ test('retention inventory identifies unreferenced artifacts but fails safe on broken pointer', t => {
558
+ const f = fixture(t)
559
+ assert.equal(f.controller.listArtifacts().state, 'missing')
560
+ assert.equal(f.controller.rebuild(f.source).ok, true)
561
+ const old = published(f).pointer.generation
562
+ assert.equal(f.controller.rebuild(f.source).ok, true)
563
+ const list = listArtifacts(f.options)
564
+ assert.equal(list.state, 'ready')
565
+ assert.equal(list.artifacts.find(item => item.name === old).referenced, false)
566
+ assert.equal(list.artifacts.filter(item => item.referenced).length, 2)
567
+ const pointer = published(f).pointerFile
568
+ fs.writeFileSync(pointer, 'broken-json')
569
+ const broken = f.controller.listArtifacts()
570
+ assert.equal(broken.state, 'RT_CORRUPT')
571
+ assert.ok(broken.artifacts.every(item => item.referenced === null))
572
+ })
573
+
574
+ test('cache diagnostics are bounded process-wide and expose no IDs, text or source references', t => {
575
+ const f = fixture(t)
576
+ assert.equal(f.controller.rebuild(f.source).ok, true)
577
+ f.controller.search(f.source, 'orchard', f.visibility)
578
+ const stats = rtIndexCacheStats()
579
+ assert.ok(stats.bytes > 0 && stats.bytes <= stats.maxBytes)
580
+ assert.equal(stats.maxBytes, 96 * 1024 * 1024)
581
+ assert.ok(stats.size <= stats.maxEntries)
582
+ assert.ok(!JSON.stringify(f.controller.diagnostics()).includes('mem-apple'))
583
+ assert.ok(!JSON.stringify(f.controller.diagnostics()).includes('orchard'))
584
+ clearRtIndexCaches()
585
+ assert.equal(rtIndexCacheStats().size, 0)
586
+ })
587
+
588
+ test('empty library and empty query do not manufacture a source error or fake IDs', t => {
589
+ const f = fixture(t, { entries: {} })
590
+ assert.equal(f.controller.rebuild(f.source).ok, true)
591
+ const result = f.controller.search(f.source, '', { visibleIds: [] })
592
+ assert.deepEqual(result.hits, [])
593
+ assert.equal(result.corpus.size, 0)
594
+ assert.equal(result.corpus.avgdl, 0)
595
+ assert.equal(result.backend, 'rt')
596
+ assert.equal(result.fallback, null)
597
+ })
598
+
599
+ test('bounded batches and sparse dictionary spans preserve all posting unions without caching whole postings', t => {
600
+ const entries = Object.fromEntries(Array.from({ length: 21 }, (_, i) => [`mem-${i}`, entry(`common token${i} ` + Array.from({ length: 140 }, (_, j) => `word${i}x${j}`).join(' '))]))
601
+ const f = fixture(t, { entries, segmentDocs: 3, maxBuildBytes: 128 * 1024 })
602
+ assert.equal(f.controller.rebuild(f.source).segments, 7)
603
+ const info = published(f)
604
+ assert.equal(info.manifest.namespace, 'memory')
605
+ assert.equal(info.manifest.libraryId, f.options.libraryId)
606
+ const snapshot = openRtIndex(f.options, f.source)
607
+ for (const segment of snapshot.segments) {
608
+ assert.equal(segment.postings, undefined)
609
+ assert.equal(segment.termMap, undefined)
610
+ assert.ok(segment.terms.anchors.length < segment.terms.count)
611
+ }
612
+ const view = f.controller.createView(f.source, f.visibility)
613
+ for (const query of [['common'], ['word0x0', 'word20x139'], ['token8', 'word3x128', 'absent'], ['zzz']]) {
614
+ assert.deepEqual(view.score(query).hits, oracle(f.source, query, f.visibility.visibleIds).hits)
615
+ }
616
+ assert.deepEqual(view.candidates(['common']), Object.keys(entries))
617
+ const before = rtIndexCacheStats().io
618
+ assert.deepEqual(view.score(['word20x139']).hits.map(hit => hit.id), ['mem-20'])
619
+ const after = rtIndexCacheStats().io
620
+ assert.equal(after.admittedBytes, before.admittedBytes)
621
+ assert.equal(after.postingBytes - before.postingBytes, POSTING_BYTES)
622
+ assert.ok(rtIndexCacheStats().termBlocks.bytes <= 8 * 1024 * 1024)
623
+ })
624
+
625
+ test('source fallback tokenizes document-at-a-time and does not cache a second whole corpus', t => {
626
+ let calls = 0
627
+ const f = fixture(t, { mode: 'off', documentText: row => { calls++; return row.content } })
628
+ const view = f.controller.createView(f.source, f.visibility)
629
+ assert.deepEqual(view.score(['orchard']).hits.map(hit => hit.id), ['mem-apple'])
630
+ assert.equal(calls, 2)
631
+ view.score(['星'])
632
+ assert.equal(calls, 4)
633
+ assert.equal(rtIndexCacheStats().size, 0)
634
+ })
635
+
636
+ test('default body shards coalesce beyond 1MiB without changing scores, permissions or body spans', t => {
637
+ const entries = Object.fromEntries(Array.from({ length: 60 }, (_, i) => [`mem-${i}`,
638
+ entry('orchard '.repeat(3000) + `needle${i}`, { visibility: i % 3 === 0 ? 'secret' : 'shared' })]))
639
+ const f = fixture(t, { entries })
640
+ assert.equal(f.controller.rebuild(f.source).ok, true)
641
+ const { manifest } = published(f)
642
+ assert.equal(manifest.segments.length, 1)
643
+ const bodies = Object.entries(manifest.segments[0].files).filter(([name]) => name.startsWith('bodies/'))
644
+ assert.equal(bodies.length, 1)
645
+ assert.ok(bodies[0][1].size > 1024 * 1024 && bodies[0][1].size <= 16 * 1024 * 1024)
646
+ const visibleIds = Object.keys(entries).filter(id => entries[id].visibility !== 'secret')
647
+ const view = f.controller.createView(f.source, { visibleIds })
648
+ for (const query of [['needle1'], ['needle0'], ['orchard'], ['needle59', 'needle31']]) {
649
+ const expected = oracle(f.source, query, visibleIds)
650
+ const actual = view.score(query)
651
+ assert.deepEqual(actual.hits, expected.hits)
652
+ assert.equal(actual.corpus.size, expected.corpus.size)
653
+ assert.equal(actual.corpus.avgdl, expected.corpus.avgdl)
654
+ }
655
+ for (const id of ['mem-0', 'mem-31', 'mem-59']) {
656
+ assert.equal(f.controller.readBody(f.source, id, f.visibility).body, entries[id].content)
657
+ }
658
+ })
659
+
660
+ test('a competing publication during a long build wins without a stale build replacing it', t => {
661
+ const f = fixture(t)
662
+ assert.equal(f.controller.rebuild(f.source).ok, true)
663
+ const newer = truth({ 'mem-current': entry('quartz current') })
664
+ let competed = false
665
+ const builder = createRtIndex({ ...f.options, documentText: row => {
666
+ if (!competed) {
667
+ competed = true
668
+ assert.equal(f.controller.rebuild(newer).ok, true)
669
+ }
670
+ return memoryDocumentText(row)
671
+ } })
672
+ assert.equal(builder.rebuild(f.source).code, 'RT_BUILD_STALE')
673
+ assert.deepEqual(f.controller.search(newer, 'quartz', { visibleIds: ['mem-current'] }).hits.map(row => row.id), ['mem-current'])
674
+ const { root } = indexLocation(f.options)
675
+ assert.ok(!fs.readdirSync(root).some(name => name.startsWith('.build-')))
676
+ })
677
+
678
+ test('missing manifest origin and symbolic segment directories cannot authorize retention', t => {
679
+ const f = fixture(t)
680
+ assert.equal(f.controller.rebuild(f.source).ok, true)
681
+ rewriteManifest(f, manifest => { delete manifest.namespace })
682
+ const result = f.controller.search(f.source, 'orchard', f.visibility)
683
+ assert.equal(result.fallback, 'RT_IDENTITY_MISMATCH')
684
+ assert.deepEqual(result.hits.map(row => row.id), ['mem-apple'])
685
+ assert.ok(f.controller.listArtifacts().artifacts.every(row => row.referenced === null))
686
+ assert.equal(f.controller.rebuild(f.source).ok, true)
687
+ const { root } = indexLocation(f.options)
688
+ const original = path.join(root, 'segments')
689
+ const moved = path.join(root, 'segments-original')
690
+ fs.renameSync(original, moved)
691
+ fs.symlinkSync(moved, original, process.platform === 'win32' ? 'junction' : 'dir')
692
+ assert.equal(f.controller.listArtifacts().state, 'RT_UNSAFE_PATH')
693
+ assert.ok(f.controller.listArtifacts().artifacts.every(row => row.referenced === null))
694
+ })
695
+
696
+ test('oversized declared cold working sets are refused before artifact allocation and serve actual source ids', t => {
697
+ const f = fixture(t)
698
+ assert.equal(f.controller.rebuild(f.source).ok, true)
699
+ const before = rtIndexCacheStats().io.admittedBytes
700
+ rewriteManifest(f, manifest => { manifest.segments[0].files['metadata.json'].size = 32 * 1024 * 1024 })
701
+ const result = f.controller.search(f.source, 'orchard', f.visibility)
702
+ assert.equal(result.fallback, 'RT_READ_LIMIT')
703
+ assert.deepEqual(result.hits.map(hit => hit.id), ['mem-apple'])
704
+ assert.equal(rtIndexCacheStats().io.admittedBytes, before)
705
+ })