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,196 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-lexicon-rt-lifecycle-'))
8
+ process.env.DSH_HOME = home
9
+ process.env.DSH_MEMU_HOME = home
10
+ process.env.DSH_MEMU_MEMORY_HOME = home
11
+ process.env.DSH_MEMU_RT_INDEX = 'on'
12
+ const state = await import('../lib/state.js')
13
+ const lexicon = await import('../lib/lexicon.js')
14
+ const rt = await import('../lib/lexicon-rt.js')
15
+ const plugin = await import('../lib/index.js')
16
+ const paths = await import('../lib/paths.js')
17
+ const { dispatch } = await import('../lib/rpc.js')
18
+ const { indexLocation } = await import('../lib/rt-index/reader.js')
19
+ const label = 'dsh-memu-memory: lexicon RT'
20
+
21
+ test.beforeEach(async () => {
22
+ await rt.closeLexiconRt()
23
+ rt.startLexiconRt()
24
+ process.env.DSH_MEMU_RT_INDEX = 'on'
25
+ state.updateSettings({ memoryBackend: 'agent', autoInstallEngine: false, crossLibraryRecall: false })
26
+ })
27
+ test.after(async () => {
28
+ await rt.closeLexiconRt({ suspend: true })
29
+ state.flushState()
30
+ paths.setWarnSink(null)
31
+ fs.rmSync(home, { recursive: true, force: true })
32
+ })
33
+
34
+ function host() {
35
+ const disposers = new Map()
36
+ const ctx = {
37
+ effect(factory, name) { const dispose = factory(); if (typeof dispose === 'function') disposers.set(name, dispose) },
38
+ inject(_dependencies, callback) { callback(ctx) },
39
+ tools: { register() { return () => {} } },
40
+ webServer: { register() { return () => {} } },
41
+ connection: { requestRejection() {} },
42
+ on() { return () => {} },
43
+ get() {},
44
+ timeout() { return () => {} },
45
+ interval() { return () => {} },
46
+ logger: { info() {}, warn() {} },
47
+ }
48
+ return { ctx, disposers, async dispose() {
49
+ const owned = [...disposers.values()].reverse()
50
+ disposers.clear()
51
+ for (const dispose of owned) await dispose()
52
+ } }
53
+ }
54
+
55
+ let serial = 0
56
+ function fixture() {
57
+ const id = `lexicon-lifecycle-${++serial}`
58
+ const binding = state.ensureSession(id, { cwd: path.join(home, id), agentPreset: 'coding' })
59
+ const file = path.join(home, 'lexicon', `${binding.libraryId}.json`)
60
+ paths.writeJson(file, { version: 1, revision: 1, libraryId: binding.libraryId, terms: {
61
+ 'lex-lifecycle': { term: 'private-surface-sentinel', normalizedTerm: 'private-surface-sentinel',
62
+ meaning: 'quartz private-definition-sentinel', usage: 'private-usage-sentinel', examples: ['private-example-sentinel'],
63
+ status: 'active', kind: 'term', sensitivity: 'normal', context: {} },
64
+ } })
65
+ const root = indexLocation({ directory: path.join(home, 'rt'), namespace: 'lexicon', libraryId: binding.libraryId }).root
66
+ return { libraryId: binding.libraryId, file, root }
67
+ }
68
+ const hits = f => lexicon.lexiconConceptHits(f.libraryId, 'quartz', {}, { scopeKey: 'lifecycle' })
69
+ const values = rows => rows.map(row => [row.termId, row.score])
70
+ const pause = ms => new Promise(resolve => setTimeout(resolve, ms))
71
+ async function until(predicate) {
72
+ const deadline = Date.now() + 5000
73
+ while (!predicate()) {
74
+ assert.ok(Date.now() < deadline, 'a real lexicon worker must become active before disposal')
75
+ await pause(5)
76
+ }
77
+ }
78
+ function assertEmpty() {
79
+ const stats = rt.lexiconRtDiagnostics()
80
+ assert.equal(stats.suspended, true)
81
+ assert.equal(stats.active, false)
82
+ assert.equal(stats.activeBytes, 0)
83
+ assert.equal(stats.derivedEstimatedBytes, 0)
84
+ for (const key of ['controller', 'concept', 'queue']) {
85
+ assert.equal(stats[key].size, 0, key)
86
+ assert.equal(stats[key].bytes, 0, key)
87
+ }
88
+ }
89
+
90
+ test('plugin owner disposal cancels queued lexicon work, fences late recalls and reactivation resumes it', async t => {
91
+ const owner = host()
92
+ t.after(() => owner.dispose())
93
+ plugin.apply(owner.ctx)
94
+ assert.equal(typeof owner.disposers.get(label), 'function', 'real apply must register an independent lexicon RT disposer')
95
+ const f = fixture()
96
+ const expected = values(hits(f))
97
+ assert.deepEqual(expected.map(([id]) => id), ['lex-lifecycle'])
98
+ assert.equal(rt.lexiconRtDiagnostics().queue.size, 1)
99
+ const closing = owner.disposers.get(label)()
100
+ assert.equal(typeof closing?.then, 'function', 'the host must be able to await worker shutdown')
101
+ assertEmpty()
102
+ await closing
103
+ assert.deepEqual(values(hits(f)), expected, 'late recall still returns canonical scores')
104
+ assertEmpty()
105
+ await pause(100)
106
+ assert.equal(fs.existsSync(f.root), false, 'the cancelled timer must not publish after unload')
107
+ await owner.dispose()
108
+
109
+ const next = host()
110
+ t.after(() => next.dispose())
111
+ plugin.apply(next.ctx)
112
+ assert.equal(rt.lexiconRtDiagnostics().suspended, false)
113
+ assert.deepEqual(values(hits(f)), expected)
114
+ await rt.waitForLexiconRt()
115
+ assert.equal(fs.existsSync(path.join(f.root, 'current.json')), true)
116
+ const before = rt.lexiconRtDiagnostics().rtQueries
117
+ assert.deepEqual(values(hits(f)), expected)
118
+ assert.equal(rt.lexiconRtDiagnostics().rtQueries, before + 1)
119
+ })
120
+
121
+ test('plugin owner disposal awaits an active real worker and discards its remaining queue', async t => {
122
+ const owner = host()
123
+ t.after(() => owner.dispose())
124
+ plugin.apply(owner.ctx)
125
+ const active = fixture()
126
+ const queued = fixture()
127
+ const beforeTruth = fs.readFileSync(active.file)
128
+ hits(active)
129
+ await until(() => rt.lexiconRtDiagnostics().active)
130
+ hits(queued)
131
+ assert.equal(rt.lexiconRtDiagnostics().queue.size, 1)
132
+ await owner.disposers.get(label)()
133
+ assertEmpty()
134
+ const settled = rt.lexiconRtDiagnostics()
135
+ assert.deepEqual(values(hits(queued)).map(([id]) => id), ['lex-lifecycle'])
136
+ await pause(100)
137
+ assertEmpty()
138
+ assert.equal(rt.lexiconRtDiagnostics().builds, settled.builds)
139
+ assert.equal(rt.lexiconRtDiagnostics().failedBuilds, settled.failedBuilds, 'intentional termination is not a rebuild failure')
140
+ assert.equal(fs.existsSync(queued.root), false)
141
+ assert.deepEqual(fs.readFileSync(active.file), beforeTruth, 'worker termination never writes canonical truth')
142
+ })
143
+
144
+ test('preset unload cannot suspend or clear the process-global lexicon worker owner', async t => {
145
+ const owner = host()
146
+ const preset = host()
147
+ t.after(() => owner.dispose())
148
+ t.after(() => preset.dispose())
149
+ plugin.apply(owner.ctx)
150
+ plugin.apply(preset.ctx, { preset: true })
151
+ assert.equal(preset.disposers.has(label), false)
152
+ const f = fixture()
153
+ hits(f)
154
+ await preset.dispose()
155
+ assert.equal(rt.lexiconRtDiagnostics().suspended, false)
156
+ assert.equal(rt.lexiconRtDiagnostics().queue.size, 1)
157
+ await rt.waitForLexiconRt()
158
+ assert.equal(fs.existsSync(path.join(f.root, 'current.json')), true)
159
+ })
160
+
161
+ test('getState and the copyable diagnostic report expose bounded numeric lexicon service statistics only', async () => {
162
+ process.env.DSH_MEMU_RT_INDEX = 'off'
163
+ const f = fixture()
164
+ assert.deepEqual(hits(f).map(row => row.termId), ['lex-lifecycle'])
165
+ const expected = rt.lexiconRtDiagnostics()
166
+ const current = await dispatch({}, 'getState', {})
167
+ assert.deepEqual(current.lexiconRt, expected)
168
+ assert.ok(current.rtIndex, 'the separate memory RT service remains present')
169
+ const before = fs.readFileSync(f.file)
170
+ const report = await dispatch({}, 'getDiagnosticReport', {})
171
+ const actual = report.components.workers.evidence.lexiconRt
172
+ assert.deepEqual(actual, expected)
173
+ assert.deepEqual(JSON.parse(report.text).components.workers.evidence.lexiconRt, actual)
174
+ assert.ok(report.components.workers.evidence.rtIndex, 'the report retains the memory RT statistics')
175
+ const numeric = ['viewBuilds', 'queries', 'sourceQueries', 'rtQueries', 'postingsVisited', 'fallbacks', 'signals',
176
+ 'builds', 'skippedBuilds', 'failedBuilds', 'staleBuilds', 'shadowQueries', 'shadowMismatches', 'largestViewBytes',
177
+ 'activeBytes', 'derivedEstimatedBytes', 'derivedCacheCapBytes']
178
+ assert.deepEqual(Object.keys(actual).sort(), [...numeric, 'mode', 'suspended', 'active', 'lastError', 'controller', 'concept', 'queue'].sort())
179
+ for (const key of numeric) assert.ok(Number.isFinite(actual[key]) && actual[key] >= 0, key)
180
+ assert.equal(actual.derivedCacheCapBytes, (8 + 0.25 + 0.125) * 1024 * 1024)
181
+ for (const name of ['controller', 'concept', 'queue']) {
182
+ const cache = actual[name]
183
+ assert.equal(cache.byteAccounting, 'estimate')
184
+ for (const key of ['size', 'bytes', 'maxBytes', 'maxEntries', 'ttlMs', 'hits', 'misses', 'evictions', 'expirations', 'oversized']) {
185
+ assert.ok(Number.isFinite(cache[key]) && cache[key] >= 0, `${name}.${key}`)
186
+ }
187
+ assert.ok(cache.bytes <= cache.maxBytes)
188
+ }
189
+ for (const forbidden of ['private-surface-sentinel', 'private-definition-sentinel', 'private-usage-sentinel',
190
+ 'private-example-sentinel', 'lex-lifecycle', 'quartz', f.libraryId, home]) {
191
+ assert.ok(!JSON.stringify(current.lexiconRt).includes(forbidden), forbidden)
192
+ assert.ok(!report.text.includes(forbidden), forbidden)
193
+ }
194
+ assert.deepEqual(fs.readFileSync(f.file), before)
195
+ assert.equal(fs.existsSync(f.root), false, 'reading numeric diagnostics must not start a rebuild')
196
+ })
@@ -0,0 +1,468 @@
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 { pathToFileURL } from 'node:url'
9
+
10
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-lexicon-rt-'))
11
+ process.env.DSH_HOME = home
12
+ process.env.DSH_MEMU_HOME = home
13
+ process.env.DSH_MEMU_MEMORY_HOME = home
14
+ process.env.DSH_MEMU_RT_INDEX = 'on'
15
+ const state = await import('../lib/state.js')
16
+ const lexicon = await import('../lib/lexicon.js')
17
+ const scope = await import('../lib/lexicon-scope.js')
18
+ const inject = await import('../lib/inject.js')
19
+ const service = await import('../lib/lexicon-rt.js')
20
+ const paths = await import('../lib/paths.js')
21
+ const { createRtIndex, indexLocation } = await import('../lib/rt-index/reader.js')
22
+ const { LEXICON_DOCUMENT_VERSION, lexiconDocumentText } = await import('../lib/lexicon-rt-source.js')
23
+ const { buildCorpus, bm25, tokenize } = await import('../lib/text-retrieval.js')
24
+ const { BM25_DF_MIN_POOL, BM25_DF_RATIO, BM25_MAX_QUERY_TERMS } = await import('../lib/curator-policy.js')
25
+ const warnings = []
26
+ paths.setWarnSink(message => warnings.push(message))
27
+ test.beforeEach(async () => { await service.closeLexiconRt(); process.env.DSH_MEMU_RT_INDEX = 'on' })
28
+ test.after(async () => {
29
+ await service.closeLexiconRt()
30
+ state.flushState()
31
+ paths.setWarnSink(null)
32
+ fs.rmSync(home, { recursive: true, force: true })
33
+ })
34
+
35
+ let serial = 0
36
+ const entry = (term, meaning, extra = {}) => ({ term, normalizedTerm: lexicon.normalizeLexeme(term), meaning,
37
+ status: 'active', kind: 'term', sensitivity: 'normal', context: {}, strength: 0.5, confidence: 0.7,
38
+ hitCounts: { candidate: 0, injection: 0, query: 0 }, ...extra })
39
+ function fixture(terms = {
40
+ 'lex-a': entry('Moon door', 'quartz resonance resonance', { aliases: ['lunar gate'] }),
41
+ 'lex-b': entry('Blue house', 'quartz resonance distant astronomy signal'),
42
+ 'lex-c': entry('Green lake', 'orchid garden'),
43
+ }, domain = 'coding') {
44
+ const id = `lexicon-rt-${++serial}`
45
+ const cwd = path.join(home, id)
46
+ state.updateSettings({ memoryBackend: 'agent', crossLibraryRecall: false, autoLinkMode: 'off' })
47
+ const initial = state.ensureSession(id, { cwd, agentPreset: domain })
48
+ state.setSessionBinding(id, { useGlobal: false, useLibrary: true, domainOverride: domain })
49
+ const libraryId = initial.libraryId
50
+ const file = path.join(home, 'lexicon', `${libraryId}.json`)
51
+ paths.writeJson(file, { version: 1, revision: 1, libraryId, terms })
52
+ const root = indexLocation({ directory: path.join(home, 'rt'), namespace: 'lexicon', libraryId }).root
53
+ return { id, cwd, libraryId, file, root, binding: () => state.getSessionBinding(id) }
54
+ }
55
+ const hits = (f, query = 'quartz resonance', options = {}) => lexicon.lexiconConceptHits(f.libraryId, query,
56
+ options.context || {}, { scopeKey: 'rt-test', ...options })
57
+ const values = rows => rows.map(hit => [hit.termId, hit.score])
58
+ const published = f => {
59
+ const pointer = JSON.parse(fs.readFileSync(path.join(f.root, 'current.json'), 'utf8'))
60
+ return JSON.parse(fs.readFileSync(path.join(f.root, pointer.generation, 'manifest.json'), 'utf8'))
61
+ }
62
+ async function ready(f, query = 'quartz resonance', options = {}) {
63
+ const expected = values(hits(f, query, options))
64
+ await service.waitForLexiconRt()
65
+ assert.deepEqual(values(hits(f, query, options)), expected)
66
+ return expected
67
+ }
68
+ function oracle(f, query, ids = Object.keys(lexicon.loadLexicon(f.libraryId).terms)) {
69
+ const terms = lexicon.loadLexicon(f.libraryId).terms
70
+ const corpus = buildCorpus(ids.map(id => ({ id,
71
+ title: [terms[id].term, ...(terms[id].aliases || [])].join(' '),
72
+ content: [terms[id].meaning, terms[id].usage, ...(terms[id].examples || [])].filter(Boolean).join('\n') })))
73
+ const cap = Math.max(BM25_DF_MIN_POOL, Math.ceil(BM25_DF_RATIO * corpus.size))
74
+ const tokens = tokenize(query).filter(token => [...token].length > 1 && (corpus.df.get(token) || 0) > 0 && corpus.df.get(token) <= cap)
75
+ .sort((a, b) => corpus.df.get(a) - corpus.df.get(b) || a.localeCompare(b)).slice(0, BM25_MAX_QUERY_TERMS)
76
+ return ids.map(id => [id, bm25(tokens, corpus.docs.get(id), corpus)]).filter(([, score]) => score > 0)
77
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, lexicon.LEXICON_MAX_TERMS)
78
+ }
79
+
80
+ test('missing lexicon postings fail open with exact canonical scores, signal and an asynchronous isolated build', async () => {
81
+ const f = fixture()
82
+ const before = service.lexiconRtDiagnostics()
83
+ const result = scope.recallLexicon(f.binding(), 'quartz resonance')
84
+ assert.deepEqual(values(hits(f)), oracle(f, 'quartz resonance'))
85
+ assert.deepEqual(result.lexicon.map(hit => hit.termId), ['lex-a', 'lex-b'])
86
+ assert.ok(result.errors.some(error => /lexicon RT_MISSING/.test(error)))
87
+ assert.ok(warnings.some(message => /lexicon derived recall RT_MISSING/.test(message)))
88
+ assert.equal(service.lexiconRtDiagnostics().builds, before.builds, 'no rebuild is allowed inside a synchronous hot query')
89
+ assert.equal(fs.existsSync(path.join(f.root, 'current.json')), false)
90
+ await service.waitForLexiconRt()
91
+ const manifest = published(f)
92
+ assert.equal(manifest.namespace, 'lexicon')
93
+ assert.equal(manifest.documentVersion, LEXICON_DOCUMENT_VERSION)
94
+ assert.equal(manifest.source.count, 3)
95
+ assert.notEqual(f.root, indexLocation({ directory: path.join(home, 'rt'), namespace: 'memory', libraryId: f.libraryId }).root)
96
+ const indexed = service.lexiconRtDiagnostics()
97
+ assert.deepEqual(values(hits(f)), oracle(f, 'quartz resonance'))
98
+ assert.equal(service.lexiconRtDiagnostics().rtQueries, indexed.rtQueries + 1)
99
+ assert.deepEqual(scope.recallLexicon(f.binding(), 'quartz resonance').errors, [])
100
+ })
101
+
102
+ test('off, default shadow and on preserve actual IDs, score bits and order across term/meaning/usage/examples', async () => {
103
+ const f = fixture({
104
+ 'lex-z': entry('Aster', 'quartz resonance resonance', { usage: 'distant astronomy', examples: ['lunar prism'] }),
105
+ 'lex-a': entry('Aster twin', 'quartz resonance resonance', { usage: 'distant astronomy', examples: ['lunar prism'] }),
106
+ 'lex-b': entry('Blank', 'orchid garden'),
107
+ })
108
+ await ready(f)
109
+ const before = service.lexiconRtDiagnostics()
110
+ for (const query of ['quartz resonance', 'distant astronomy', 'lunar prism', 'Aster']) {
111
+ const expected = oracle(f, query)
112
+ for (const mode of ['off', undefined, 'on']) {
113
+ if (mode === undefined) delete process.env.DSH_MEMU_RT_INDEX
114
+ else process.env.DSH_MEMU_RT_INDEX = mode
115
+ assert.deepEqual(values(hits(f, query)), expected, `${mode || 'default shadow'}: ${query}`)
116
+ }
117
+ }
118
+ const after = service.lexiconRtDiagnostics()
119
+ assert.equal(after.shadowQueries - before.shadowQueries, 4)
120
+ assert.equal(after.shadowMismatches, before.shadowMismatches)
121
+ process.env.DSH_MEMU_RT_INDEX = 'invalid-value'
122
+ assert.equal(service.lexiconRtMode(), 'shadow')
123
+ })
124
+
125
+ test('off mode builds no artifacts and schedules no worker', async () => {
126
+ process.env.DSH_MEMU_RT_INDEX = 'off'
127
+ const f = fixture()
128
+ assert.deepEqual(values(hits(f)), oracle(f, 'quartz resonance'))
129
+ await service.waitForLexiconRt()
130
+ assert.equal(fs.existsSync(f.root), false)
131
+ assert.equal(service.lexiconRtDiagnostics().queue.size, 0)
132
+ assert.equal(service.lexiconRtDiagnostics().active, false)
133
+ })
134
+
135
+ test('persistent postings survive controller restart and a fresh process without any query rebuild', async () => {
136
+ const f = fixture()
137
+ const expected = await ready(f)
138
+ const generation = published(f).generation
139
+ await service.closeLexiconRt()
140
+ const before = service.lexiconRtDiagnostics()
141
+ assert.deepEqual(values(hits(f)), expected)
142
+ assert.equal(service.lexiconRtDiagnostics().rtQueries, before.rtQueries + 1)
143
+ assert.equal(service.lexiconRtDiagnostics().queue.size, 0)
144
+ const moduleUrl = pathToFileURL(path.resolve('lib/lexicon.js')).href
145
+ const serviceUrl = pathToFileURL(path.resolve('lib/lexicon-rt.js')).href
146
+ const source = `const lex = await import(${JSON.stringify(moduleUrl)}); const rt = await import(${JSON.stringify(serviceUrl)}); const rows = lex.lexiconConceptHits(${JSON.stringify(f.libraryId)}, 'quartz resonance', {}, {scopeKey:'restart'}); console.log(JSON.stringify({rows:rows.map(row=>[row.termId,row.score]),diagnostics:rt.lexiconRtDiagnostics()})); await rt.closeLexiconRt()`
147
+ const child = spawnSync(process.execPath, ['--input-type=module', '-e', source], {
148
+ encoding: 'utf8', env: { ...process.env, DSH_MEMU_HOME: home, DSH_MEMU_MEMORY_HOME: home }, timeout: 20000,
149
+ })
150
+ assert.equal(child.status, 0, child.stderr)
151
+ const actual = JSON.parse(child.stdout.trim())
152
+ assert.deepEqual(actual.rows, expected)
153
+ assert.equal(actual.diagnostics.rtQueries, 1)
154
+ assert.equal(actual.diagnostics.builds, 0)
155
+ assert.equal(actual.diagnostics.queue.size, 0)
156
+ assert.equal(published(f).generation, generation)
157
+ })
158
+
159
+ test('same-size corruption with restored mtime falls back on a warm view and rebuilds real postings', async () => {
160
+ const f = fixture()
161
+ const expected = await ready(f)
162
+ const manifest = published(f)
163
+ const file = path.join(f.root, 'segments', manifest.segments[0].id, 'postings.bin')
164
+ const stat = fs.statSync(file)
165
+ const bytes = fs.readFileSync(file)
166
+ bytes[bytes.length - 1] ^= 1
167
+ fs.writeFileSync(file, bytes)
168
+ fs.utimesSync(file, stat.atime, stat.mtime)
169
+ const before = service.lexiconRtDiagnostics()
170
+ assert.deepEqual(values(hits(f)), expected)
171
+ assert.equal(service.lexiconRtDiagnostics().sourceQueries, before.sourceQueries + 1)
172
+ assert.ok(service.lexiconRtDiagnostics().fallbacks > before.fallbacks)
173
+ await service.waitForLexiconRt()
174
+ assert.notEqual(published(f).generation, manifest.generation)
175
+ const afterBuild = service.lexiconRtDiagnostics()
176
+ assert.deepEqual(values(hits(f)), expected)
177
+ assert.equal(service.lexiconRtDiagnostics().rtQueries, afterBuild.rtQueries + 1)
178
+ })
179
+
180
+ test('deleted derived directories preserve canonical bytes and enqueue recovery', async () => {
181
+ const f = fixture()
182
+ const expected = await ready(f)
183
+ const canonical = fs.readFileSync(f.file)
184
+ assert.ok(f.root.startsWith(path.resolve(home) + path.sep))
185
+ fs.rmSync(f.root, { recursive: true, force: true })
186
+ assert.deepEqual(values(hits(f)), expected)
187
+ await service.waitForLexiconRt()
188
+ assert.ok(fs.existsSync(path.join(f.root, 'current.json')))
189
+ assert.deepEqual(fs.readFileSync(f.file), canonical)
190
+ assert.deepEqual(values(hits(f)), expected)
191
+ })
192
+
193
+ test('hit-counter and privacy-only writes reuse document revision while fresh eligibility still applies', async () => {
194
+ const f = fixture()
195
+ await ready(f)
196
+ const manifest = published(f)
197
+ lexicon.lexiconRecordHits(f.libraryId, ['lex-a'], 'candidate')
198
+ lexicon.lexiconRecordHits(f.libraryId, ['lex-a'], 'injection')
199
+ assert.equal(lexicon.loadLexiconRtSource(f.libraryId).revision, manifest.source.revision)
200
+ assert.deepEqual(values(hits(f)), oracle(f, 'quartz resonance'))
201
+ const data = lexicon.loadLexicon(f.libraryId)
202
+ data.terms['lex-a'].visibility = 'secret'
203
+ paths.writeJson(f.file, data)
204
+ assert.equal(lexicon.loadLexiconRtSource(f.libraryId).revision, manifest.source.revision)
205
+ assert.deepEqual(values(hits(f)), oracle(f, 'quartz resonance', ['lex-b', 'lex-c']))
206
+ assert.equal(published(f).generation, manifest.generation)
207
+ assert.equal(service.lexiconRtDiagnostics().queue.size, 0)
208
+ })
209
+
210
+ test('external equal-length text replacement invalidates source and never returns stale concept IDs', async () => {
211
+ const f = fixture({ 'lex-a': entry('Door', 'quartz') })
212
+ await ready(f, 'quartz')
213
+ const original = published(f)
214
+ const stat = fs.statSync(f.file)
215
+ fs.writeFileSync(f.file, fs.readFileSync(f.file, 'utf8').replace('quartz', 'violet'))
216
+ fs.utimesSync(f.file, stat.atime, stat.mtime)
217
+ assert.deepEqual(hits(f, 'quartz'), [])
218
+ assert.deepEqual(hits(f, 'violet').map(hit => hit.termId), ['lex-a'])
219
+ await service.waitForLexiconRt()
220
+ assert.notEqual(published(f).source.revision, original.source.revision)
221
+ assert.deepEqual(values(hits(f, 'violet')), oracle(f, 'violet'))
222
+ assert.deepEqual(hits(f, 'quartz'), [])
223
+ })
224
+
225
+ test('a queued worker never treats corrupt canonical JSON as an empty successful build', async () => {
226
+ const f = fixture()
227
+ const canonical = fs.readFileSync(f.file)
228
+ hits(f)
229
+ fs.writeFileSync(f.file, '{invalid json')
230
+ const before = service.lexiconRtDiagnostics()
231
+ await service.waitForLexiconRt()
232
+ assert.ok(service.lexiconRtDiagnostics().failedBuilds > before.failedBuilds)
233
+ assert.equal(service.lexiconRtDiagnostics().lastError, 'RT_CANONICAL_READ_FAILED')
234
+ assert.equal(fs.existsSync(path.join(f.root, 'current.json')), false)
235
+ assert.equal(fs.readFileSync(f.file, 'utf8'), '{invalid json')
236
+ assert.throws(() => hits(f), error => /^LEXICON_/.test(error.code))
237
+ fs.writeFileSync(f.file, canonical)
238
+ await service.closeLexiconRt()
239
+ await ready(f)
240
+ })
241
+
242
+ test('a stale queued revision is replaced by a fresh strict worker source', async () => {
243
+ const f = fixture({ 'lex-a': entry('Door', 'quartz') })
244
+ hits(f, 'quartz')
245
+ const raw = lexicon.loadLexicon(f.libraryId)
246
+ raw.terms['lex-a'].meaning = 'violet'
247
+ paths.writeJson(f.file, raw)
248
+ const before = service.lexiconRtDiagnostics()
249
+ await service.waitForLexiconRt()
250
+ assert.ok(service.lexiconRtDiagnostics().staleBuilds > before.staleBuilds)
251
+ assert.equal(published(f).source.revision, lexicon.loadLexiconRtSource(f.libraryId).revision)
252
+ assert.deepEqual(hits(f, 'quartz'), [])
253
+ assert.deepEqual(values(hits(f, 'violet')), oracle(f, 'violet'))
254
+ })
255
+
256
+ test('indexed privacy gates exclude secret, world, role, knownBy and archived rows before every corpus statistic', async () => {
257
+ const f = fixture({ 'lex-a': entry('Visible', 'quartz resonance') })
258
+ const expected = await ready(f)
259
+ const raw = lexicon.loadLexicon(f.libraryId)
260
+ Object.assign(raw.terms, {
261
+ 'lex-secret': entry('Secret', 'quartz resonance', { visibility: 'secret' }),
262
+ 'lex-world': entry('Elsewhere', 'quartz resonance', { context: { worldId: 'other' } }),
263
+ 'lex-role': entry('Bob', 'quartz resonance', { context: { characterId: 'bob' } }),
264
+ 'lex-known': entry('Known', 'quartz resonance', { knownBy: ['bob'] }),
265
+ 'lex-old': entry('Archived', 'quartz resonance', { status: 'archived' }),
266
+ 'lex-pending': entry('Pending', 'quartz resonance', { status: 'pending' }),
267
+ })
268
+ paths.writeJson(f.file, raw)
269
+ await ready(f)
270
+ for (const mode of ['off', 'shadow', 'on']) {
271
+ process.env.DSH_MEMU_RT_INDEX = mode
272
+ assert.deepEqual(values(hits(f)), expected, `hidden statistics in ${mode}`)
273
+ const bob = hits(f, 'quartz resonance', { context: { characterId: 'bob' } })
274
+ assert.deepEqual(new Set(bob.map(hit => hit.termId)), new Set(['lex-a', 'lex-role', 'lex-known']))
275
+ assert.deepEqual(values(hits(f)), expected, `role-specific cached view cannot leak in ${mode}`)
276
+ }
277
+ })
278
+
279
+ test('sensitive meaning/usage/examples/aliases/evidence never leave indexed automatic hits or anchors', async () => {
280
+ const marker = 'quartz sensitive-meaning-marker'
281
+ const f = fixture({
282
+ 'lex-sensitive': entry('Pause', marker, { sensitivity: 'sensitive', usage: 'private-usage-marker', examples: ['private-example-marker'],
283
+ aliases: ['private-alias-marker'], evidence: [{ quote: 'private-evidence-marker' }] }),
284
+ 'lex-secret': entry('SecretSurfaceMarker', marker, { visibility: 'secret' }),
285
+ 'lex-legacy': entry('Stop', marker, { kind: 'trigger', sensitivity: undefined }),
286
+ })
287
+ await ready(f)
288
+ for (const mode of ['off', 'shadow', 'on']) {
289
+ process.env.DSH_MEMU_RT_INDEX = mode
290
+ const automatic = scope.recallLexicon(f.binding(), 'quartz')
291
+ assert.deepEqual(new Set(automatic.lexicon.map(hit => hit.termId)), new Set(['lex-sensitive', 'lex-legacy']))
292
+ const proposal = inject.injectLexiconTurn({ binding: f.binding(), sessionId: f.id, userTexts: ['quartz'], tokenBudget: 800 })
293
+ const anchor = inject.buildLexiconAnchor(f.binding()).text
294
+ for (const output of [JSON.stringify(automatic), JSON.stringify(proposal), anchor]) {
295
+ assert.doesNotMatch(output, /meaning-marker|usage-marker|example-marker|alias-marker|evidence-marker|SecretSurfaceMarker|lex-secret/)
296
+ }
297
+ assert.ok(proposal.text.includes('[lex:lex-sensitive]'))
298
+ assert.ok(hits(f, 'quartz', { automatic: false }).some(hit => hit.meaning === marker))
299
+ }
300
+ })
301
+
302
+ test('same-domain cross-library and global selection use persistent namespaces with existing source priority', async () => {
303
+ const a = fixture({ 'lex-local': entry('Local', 'terbiumdomain') })
304
+ const b = fixture({ 'lex-peer': entry('Peer', 'terbiumdomain', { domain: 'coding' }), 'lex-foreign-entry': entry('Foreign stamp', 'terbiumdomain', { domain: 'rp' }) })
305
+ const foreign = fixture({ 'lex-foreign-library': entry('Foreign library', 'terbiumdomain') }, 'rp')
306
+ const global = { file: path.join(home, 'lexicon', 'global.json'), libraryId: 'global',
307
+ root: indexLocation({ directory: path.join(home, 'rt'), namespace: 'lexicon', libraryId: 'global' }).root }
308
+ paths.writeJson(global.file, { version: 1, revision: 1, terms: {
309
+ 'lex-global': entry('Global', 'terbiumdomain', { domain: 'universal' }),
310
+ 'lex-global-rp': entry('Global other domain', 'terbiumdomain', { domain: 'rp' }),
311
+ } })
312
+ for (const f of [a, b, foreign, global]) await ready(f, 'terbiumdomain')
313
+ state.updateSettings({ crossLibraryRecall: true })
314
+ state.setSessionBinding(a.id, { useGlobal: true })
315
+ // Earlier fixtures are also registered same-domain libraries; their empty
316
+ // postings may legitimately require a first background build on this scan.
317
+ scope.recallLexicon(a.binding(), 'terbiumdomain')
318
+ await service.waitForLexiconRt()
319
+ const result = scope.recallLexicon(a.binding(), 'terbiumdomain')
320
+ assert.deepEqual(new Set(result.hits.map(hit => hit.termId)), new Set(['lex-local', 'lex-peer', 'lex-global']))
321
+ assert.ok(result.lexicon.length <= 2)
322
+ assert.deepEqual(result.errors, [])
323
+ state.setSessionBinding(a.id, { useLibrary: false })
324
+ assert.deepEqual(scope.recallLexicon(a.binding(), 'terbiumdomain').hits.map(hit => hit.termId), ['lex-global'])
325
+ state.setSessionBinding(a.id, { useGlobal: false })
326
+ assert.deepEqual(scope.recallLexicon(a.binding(), 'terbiumdomain').hits, [])
327
+ })
328
+
329
+ test('controller cache is bounded and diagnostics contain no source, query, role or definition', () => {
330
+ process.env.DSH_MEMU_RT_INDEX = 'off'
331
+ const before = service.lexiconRtDiagnostics()
332
+ for (let i = 0; i < 40; i++) {
333
+ const f = fixture({ [`lex-private-${i}`]: entry(`PrivateSurface${i}`, 'quartz private-definition-marker') })
334
+ assert.equal(hits(f, 'quartz', { context: { characterId: 'private-character-marker' } })[0].termId, `lex-private-${i}`)
335
+ }
336
+ const result = service.lexiconRtDiagnostics()
337
+ assert.equal(result.controller.maxBytes, 256 * 1024)
338
+ assert.ok(result.controller.size <= 32)
339
+ assert.ok(result.controller.bytes <= result.controller.maxBytes)
340
+ assert.ok(result.controller.evictions > before.controller.evictions)
341
+ assert.equal(result.derivedCacheCapBytes, 8.375 * 1024 * 1024)
342
+ assert.doesNotMatch(JSON.stringify(result), /private-definition-marker|private-character-marker|PrivateSurface|lex-private|[A-Z]:\\|quartz/)
343
+ })
344
+
345
+ test('5000-term cap and real permission-view byte eviction preserve actual recall', async () => {
346
+ process.env.DSH_MEMU_RT_INDEX = 'off'
347
+ const terms = Object.fromEntries(Array.from({ length: 5000 }, (_, i) => [`lex-cap-${i}`, entry(`Label ${i}`, `inventory${i}`)]))
348
+ const f = fixture(terms)
349
+ const before = service.lexiconRtDiagnostics()
350
+ const rssBefore = process.memoryUsage().rss
351
+ for (let i = 0; i < 4; i++) {
352
+ assert.deepEqual(hits(f, 'inventory1701', { context: { characterId: `role-${i}` } }).map(hit => hit.termId), ['lex-cap-1701'])
353
+ }
354
+ const after = service.lexiconRtDiagnostics()
355
+ assert.ok(after.concept.evictions > before.concept.evictions, 'three real 5000-ID permission views exceed the byte budget')
356
+ assert.ok(after.concept.bytes <= after.concept.maxBytes)
357
+ assert.ok(after.derivedEstimatedBytes <= after.derivedCacheCapBytes)
358
+ assert.throws(() => lexicon.upsertLexiconTerm({ libraryId: f.libraryId, term: 'one-too-many', meaning: 'overflow', kind: 'term', source: 'user' }),
359
+ error => error.code === 'LEXICON_CAP_REACHED')
360
+ assert.equal(Object.keys(lexicon.loadLexicon(f.libraryId).terms).length, 5000)
361
+ console.info(JSON.stringify({ case: 'lexicon-rt-real-view-capacity', rows: 5000, queries: 4,
362
+ derivedEstimatedBytes: after.derivedEstimatedBytes, derivedCacheCapBytes: after.derivedCacheCapBytes,
363
+ truthEstimatedBytes: lexicon.lexiconRecallDiagnostics().index.bytes,
364
+ processRssBefore: rssBefore, processRssAfter: process.memoryUsage().rss }))
365
+ })
366
+
367
+ test('the base lexicon document contract reproduces the shared scorer without importing memory text', () => {
368
+ const f = fixture({ 'lex-a': entry('Aster', 'quartz', { title: 'forbidden-memory-title', content: 'forbidden-memory-body', tags: ['forbidden-memory-tag'] }) })
369
+ const source = lexicon.loadLexiconRtSource(f.libraryId)
370
+ const controller = createRtIndex({ directory: path.join(home, 'rt'), libraryId: f.libraryId, namespace: 'lexicon', mode: 'off',
371
+ documentVersion: LEXICON_DOCUMENT_VERSION, documentText: lexiconDocumentText })
372
+ const view = controller.createView(source, { visibleIds: ['lex-a'] })
373
+ assert.deepEqual(view.score('forbidden-memory-title forbidden-memory-body forbidden-memory-tag').hits, [])
374
+ assert.deepEqual(view.score('quartz').hits.map(hit => [hit.id, hit.score]), oracle(f, 'quartz'))
375
+ })
376
+
377
+ test('direct calls without a scope key never cache a caller predicate across requests', async () => {
378
+ const f = fixture()
379
+ await ready(f)
380
+ const read = term => lexicon.lexiconConceptHits(f.libraryId, 'quartz resonance', {}, { acceptEntry: entry => entry.term === term })
381
+ assert.deepEqual(read('Moon door').map(hit => hit.termId), ['lex-a'])
382
+ assert.deepEqual(read('Blue house').map(hit => hit.termId), ['lex-b'])
383
+ assert.deepEqual(read('Moon door').map(hit => hit.termId), ['lex-a'])
384
+ })
385
+
386
+ test('wide queries preserve the existing frequency gate and 64-token selection with exact scores', async () => {
387
+ const terms = { 'lex-hit': entry('Needle', Array.from({ length: 100 }, (_, i) => `mineral${i}`).join(' ')) }
388
+ for (let i = 0; i < 20; i++) terms[`lex-noise-${i}`] = entry(`Noise ${i}`, `commonmineral stock${i}`)
389
+ const f = fixture(terms)
390
+ const query = ['commonmineral', ...Array.from({ length: 150 }, (_, i) => `unknown${i}`),
391
+ ...Array.from({ length: 100 }, (_, i) => `mineral${i}`)].join(' ')
392
+ const expected = oracle(f, query)
393
+ assert.deepEqual(expected.map(([id]) => id), ['lex-hit'])
394
+ await ready(f, query)
395
+ for (const mode of ['off', 'shadow', 'on']) {
396
+ process.env.DSH_MEMU_RT_INDEX = mode
397
+ assert.deepEqual(values(hits(f, query)), expected)
398
+ assert.deepEqual(hits(f, 'commonmineral'), [], 'high-df rows are not retained as zero-score candidates')
399
+ }
400
+ })
401
+
402
+ test('RT retention cannot delete current lexicon artifacts or canonical truth', async () => {
403
+ const f = fixture()
404
+ const expected = await ready(f)
405
+ const manifest = published(f)
406
+ const canonical = fs.readFileSync(f.file)
407
+ const { pruneRtArtifacts } = await import('../lib/rt-index-retention.js')
408
+ assert.ok(f.root.startsWith(path.resolve(home) + path.sep))
409
+ const result = pruneRtArtifacts({ dryRun: false, now: Date.now() + 8 * 86400000, olderThanDays: 7 })
410
+ assert.ok(result.removed.every(item => item.identity !== path.basename(f.root)))
411
+ assert.equal(published(f).generation, manifest.generation)
412
+ assert.deepEqual(fs.readFileSync(f.file), canonical)
413
+ assert.deepEqual(values(hits(f)), expected)
414
+ })
415
+
416
+ test('a deleted canonical file never gets recreated by a previously queued lexicon build', async () => {
417
+ const f = fixture()
418
+ hits(f)
419
+ assert.ok(f.file.startsWith(path.resolve(home) + path.sep))
420
+ fs.unlinkSync(f.file)
421
+ const before = service.lexiconRtDiagnostics()
422
+ await service.waitForLexiconRt()
423
+ assert.equal(fs.existsSync(f.file), false)
424
+ assert.equal(fs.existsSync(f.root), false)
425
+ assert.equal(service.lexiconRtDiagnostics().builds, before.builds)
426
+ assert.deepEqual(hits(f), [])
427
+ })
428
+
429
+ test('a checksummed but semantically wrong shadow generation forces a genuine rebuild', async () => {
430
+ const f = fixture()
431
+ const expected = await ready(f, 'quartz')
432
+ const manifest = published(f)
433
+ const segment = manifest.segments[0]
434
+ const directory = path.join(f.root, 'segments', segment.id)
435
+ const term = fs.readFileSync(path.join(directory, 'terms.bin'), 'utf8').trimEnd().split('\n')
436
+ .map(row => JSON.parse(row)).find(row => row[0] === 'quartz')
437
+ assert.ok(term)
438
+ const { HEADER_BYTES, POSTING_BYTES } = await import('../lib/rt-index/format.js')
439
+ const file = path.join(directory, 'postings.bin')
440
+ const bytes = fs.readFileSync(file)
441
+ const offset = HEADER_BYTES + term[1] * POSTING_BYTES + 4
442
+ bytes.writeUInt16LE(bytes.readUInt16LE(offset) + 2, offset)
443
+ fs.writeFileSync(file, bytes)
444
+ const digest = value => crypto.createHash('sha256').update(value).digest('hex')
445
+ segment.files['postings.bin'].sha256 = digest(bytes)
446
+ const manifestBytes = Buffer.from(JSON.stringify(manifest))
447
+ fs.writeFileSync(path.join(f.root, manifest.generation, 'manifest.json'), manifestBytes)
448
+ const pointerFile = path.join(f.root, 'current.json')
449
+ const pointer = JSON.parse(fs.readFileSync(pointerFile, 'utf8'))
450
+ pointer.sha256 = digest(manifestBytes)
451
+ paths.writeJson(pointerFile, pointer)
452
+ process.env.DSH_MEMU_RT_INDEX = 'shadow'
453
+ const before = service.lexiconRtDiagnostics()
454
+ const result = scope.recallLexicon(f.binding(), 'quartz')
455
+ assert.deepEqual(values(result.lexicon), expected, 'the canonical result survives shadow mismatch')
456
+ assert.ok(result.errors.some(error => /RT_SHADOW_MISMATCH/.test(error)))
457
+ assert.ok(service.lexiconRtDiagnostics().shadowMismatches > before.shadowMismatches)
458
+ assert.deepEqual(values(hits(f, 'quartz')), expected, 'quarantined source fallback cannot downgrade the queued force flag')
459
+ await service.waitForLexiconRt()
460
+ assert.notEqual(published(f).generation, manifest.generation, 'validate alone must not skip this forced rebuild')
461
+ assert.ok(service.lexiconRtDiagnostics().builds > before.builds)
462
+ const after = service.lexiconRtDiagnostics()
463
+ assert.deepEqual(values(hits(f, 'quartz')), expected)
464
+ assert.equal(service.lexiconRtDiagnostics().shadowMismatches, after.shadowMismatches)
465
+ assert.deepEqual(scope.recallLexicon(f.binding(), 'quartz').errors, [])
466
+ process.env.DSH_MEMU_RT_INDEX = 'on'
467
+ assert.deepEqual(values(hits(f, 'quartz')), expected)
468
+ })