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,224 @@
1
+ import path from 'node:path'
2
+ import { Worker } from 'node:worker_threads'
3
+ import { createRtIndex } from './rt-index/reader.js'
4
+ import { createBoundedCache, estimateBytes } from './bounded-cache.js'
5
+ import { warn } from './paths.js'
6
+ import { childEnvironment } from './local-embedding-manager.js'
7
+ import { LEXICON_DOCUMENT_VERSION, lexiconDocumentText } from './lexicon-rt-source.js'
8
+
9
+ const counters = { viewBuilds: 0, queries: 0, sourceQueries: 0, rtQueries: 0, postingsVisited: 0,
10
+ fallbacks: 0, signals: 0, builds: 0, skippedBuilds: 0, failedBuilds: 0, staleBuilds: 0,
11
+ shadowQueries: 0, shadowMismatches: 0, largestViewBytes: 0, lastError: null }
12
+ const controllers = createBoundedCache({ name: 'lexiconRtControllers', maxBytes: 256 * 1024,
13
+ maxEntries: 32, ttlMs: 300000, sizeOf: () => 4096 })
14
+ let viewsByOwner = new WeakMap()
15
+ const views = createBoundedCache({ name: 'lexiconRecall', maxBytes: 8 * 1024 * 1024,
16
+ maxEntries: 64, ttlMs: 60000,
17
+ sizeOf(value, key) {
18
+ counters.largestViewBytes = Math.max(counters.largestViewBytes, value.bytes + estimateBytes(key))
19
+ return value.bytes
20
+ },
21
+ onEvict(key, value) { const owner = value.owner.deref(); if (owner) viewsByOwner.get(owner)?.delete(key) },
22
+ })
23
+ const pending = createBoundedCache({ name: 'lexiconRtQueue', maxBytes: 128 * 1024, maxEntries: 32, ttlMs: 120000 })
24
+ let active = null
25
+ let timer = null
26
+ let suspended = false
27
+
28
+ export const lexiconRtMode = () => ['off', 'shadow', 'on'].includes(process.env.DSH_MEMU_RT_INDEX) ? process.env.DSH_MEMU_RT_INDEX : 'shadow'
29
+ const identity = (directory, libraryId, mode) => JSON.stringify([directory, libraryId, mode])
30
+ const codeOf = code => /^RT_[A-Z_]+$/.test(code || '') ? code : 'RT_BUILD_FAILED'
31
+
32
+ function signal(state, code) {
33
+ code = codeOf(code)
34
+ counters.signals++
35
+ counters.lastError = code
36
+ if (state.lastCode !== code || Date.now() - state.lastAt >= 60000) {
37
+ state.lastCode = code
38
+ state.lastAt = Date.now()
39
+ warn(`lexicon derived recall ${code}; using canonical source; rebuild requested`)
40
+ }
41
+ }
42
+
43
+ function controllerFor(directory, libraryId, mode) {
44
+ const key = identity(directory, libraryId, mode)
45
+ let state = controllers.get(key)
46
+ if (state) return state
47
+ state = { lastCode: null, lastAt: 0, nextBuildAt: 0 }
48
+ state.controller = createRtIndex({ directory, libraryId, namespace: 'lexicon', mode,
49
+ documentVersion: LEXICON_DOCUMENT_VERSION, documentText: lexiconDocumentText,
50
+ logger: { warn() {} }, onSignal: event => signal(state, event.code) })
51
+ if (!suspended) controllers.set(key, state)
52
+ return state
53
+ }
54
+
55
+ function schedule() {
56
+ if (suspended || timer || active || !pending.size) return
57
+ timer = setTimeout(() => { timer = null; launchNext() }, 50)
58
+ timer.unref?.()
59
+ }
60
+
61
+ function enqueue(job, state) {
62
+ if (suspended || lexiconRtMode() === 'off' || Date.now() < (state?.nextBuildAt || 0)) return
63
+ const key = identity(job.directory, job.libraryId, 'build')
64
+ if (active?.key === key && active.job.revision === job.revision && (!job.force || active.job.force)) return
65
+ const queued = pending.get(key)
66
+ pending.set(key, { ...job, force: job.force === true || queued?.force === true })
67
+ schedule()
68
+ }
69
+
70
+ function launchNext() {
71
+ if (suspended || active || !pending.size) return
72
+ if (lexiconRtMode() === 'off') { pending.clear(); return }
73
+ const key = pending.keys().next().value
74
+ const job = pending.get(key)
75
+ pending.delete(key)
76
+ if (!job) { schedule(); return }
77
+ const state = controllerFor(job.directory, job.libraryId, lexiconRtMode())
78
+ let worker
79
+ try {
80
+ worker = new Worker(new URL('./lexicon-rt-worker.js', import.meta.url), {
81
+ workerData: job, env: childEnvironment(), execArgv: [],
82
+ resourceLimits: { maxOldGenerationSizeMb: 256 },
83
+ })
84
+ } catch {
85
+ counters.failedBuilds++
86
+ state.nextBuildAt = Date.now() + 30000
87
+ signal(state, 'RT_WORKER_START_FAILED')
88
+ schedule()
89
+ return
90
+ }
91
+ const run = { key, job, worker, timeout: null }
92
+ active = run
93
+ let replied = false
94
+ function finish(result) {
95
+ if (replied || active !== run) return
96
+ replied = true
97
+ clearTimeout(run.timeout)
98
+ if (result?.ok) {
99
+ if (result.skipped) counters.skippedBuilds++
100
+ else counters.builds++
101
+ } else if (result?.code === 'RT_SOURCE_CHANGED' && typeof result.revision === 'string') {
102
+ counters.staleBuilds++
103
+ enqueue({ ...job, revision: result.revision }, state)
104
+ } else {
105
+ counters.failedBuilds++
106
+ state.nextBuildAt = Date.now() + 30000
107
+ signal(state, result?.code)
108
+ }
109
+ }
110
+ worker.on('message', finish)
111
+ worker.on('error', () => finish({ ok: false, code: 'RT_WORKER_FAILED' }))
112
+ worker.on('exit', () => {
113
+ if (!replied) finish({ ok: false, code: 'RT_WORKER_EXIT' })
114
+ clearTimeout(run.timeout)
115
+ if (active === run) { active = null; schedule() }
116
+ })
117
+ run.timeout = setTimeout(() => {
118
+ finish({ ok: false, code: 'RT_WORKER_TIMEOUT' })
119
+ void worker.terminate()
120
+ }, 60000)
121
+ run.timeout.unref?.()
122
+ worker.unref()
123
+ }
124
+
125
+ function forgetView(key, record) {
126
+ const owner = record?.owner.deref()
127
+ if (owner) viewsByOwner.get(owner)?.delete(key)
128
+ views.delete(key)
129
+ }
130
+
131
+ export function invalidateLexiconRtViews(file) {
132
+ for (const [key, record] of views) if (key.startsWith(`${file}\0`)) forgetView(key, record)
133
+ }
134
+
135
+ /** Only compact permission selections are retained; truth is weakly owned. */
136
+ export function lexiconRtPostings({ file, libraryId, owner, source, cacheKey, isVisible, tokens }) {
137
+ const mode = suspended ? 'off' : lexiconRtMode()
138
+ const home = path.dirname(path.dirname(file))
139
+ const directory = path.join(home, 'rt')
140
+ const key = `${file}\0${JSON.stringify([owner.signature, cacheKey, mode])}`
141
+ const record = cacheKey ? views.get(key) : undefined
142
+ let value = record?.ref.deref()
143
+ if (!value) {
144
+ if (record) forgetView(key, record)
145
+ const state = controllerFor(directory, libraryId, mode)
146
+ const view = state.controller.createView(source, { isVisible })
147
+ value = { view, controller: state.controller, state }
148
+ counters.viewBuilds++
149
+ if (!suspended && cacheKey && owner.signature) {
150
+ let owned = viewsByOwner.get(owner)
151
+ if (!owned) { owned = new Map(); viewsByOwner.set(owner, owned) }
152
+ owned.set(key, value)
153
+ // Includes the source view's ID/order maps and transient derived view's
154
+ // selection maps. Binary snapshots stay in the shared RT cache budget.
155
+ views.set(key, { owner: new WeakRef(owner), ref: new WeakRef(value), bytes: view.size * 768 + 8192 })
156
+ if (![...views.keys()].includes(key)) owned.delete(key)
157
+ }
158
+ }
159
+ counters.queries++
160
+ const data = value.view.size ? value.view.queryPostings(tokens)
161
+ : { docs: new Map(), corpus: { size: 0, avgdl: 0, df: new Map() }, visited: 0, backend: 'source', fallback: null, shadow: null }
162
+ counters[data.backend === 'rt' ? 'rtQueries' : 'sourceQueries']++
163
+ counters.postingsVisited += data.visited || 0
164
+ if (data.fallback) {
165
+ counters.fallbacks++
166
+ // A logical quarantine can outlive the first queued request/backoff. A fresh
167
+ // worker must not validate and skip that same rejected generation forever.
168
+ enqueue({ home, directory, libraryId, revision: source.revision, force: data.fallback === 'RT_QUARANTINED' }, value.state)
169
+ }
170
+ return { ...data,
171
+ compareFinal(expected, actual) {
172
+ const comparison = value.controller.compareFinal(expected, actual)
173
+ counters.shadowQueries++
174
+ if (comparison.agreement !== 1 || comparison.scoreDifferences || !comparison.orderEqual) {
175
+ counters.shadowMismatches++
176
+ value.controller.invalidate('RT_SHADOW_MISMATCH')
177
+ enqueue({ home, directory, libraryId, revision: source.revision, force: true }, value.state)
178
+ }
179
+ return comparison
180
+ },
181
+ }
182
+ }
183
+
184
+ /** The process-global plugin owner resumes lazy work and owns its unload fence. */
185
+ export function startLexiconRt() {
186
+ suspended = false
187
+ return () => closeLexiconRt({ suspend: true })
188
+ }
189
+
190
+ /** Reset isolated callers, or fence late recalls until the next owner activation. */
191
+ export async function closeLexiconRt({ suspend = false } = {}) {
192
+ if (suspend) suspended = true
193
+ if (timer) clearTimeout(timer)
194
+ timer = null
195
+ pending.clear()
196
+ const run = active
197
+ active = null
198
+ if (run) clearTimeout(run.timeout)
199
+ views.clear()
200
+ viewsByOwner = new WeakMap()
201
+ controllers.clear()
202
+ if (run) await run.worker.terminate()
203
+ }
204
+
205
+ export async function waitForLexiconRt({ timeoutMs = 20000 } = {}) {
206
+ const deadline = Date.now() + timeoutMs
207
+ while (active || pending.size || timer) {
208
+ if (Date.now() >= deadline) throw Object.assign(new Error('lexicon background rebuild timed out'), { code: 'RT_DRAIN_TIMEOUT' })
209
+ await new Promise(resolve => setTimeout(resolve, 25))
210
+ }
211
+ return lexiconRtDiagnostics()
212
+ }
213
+
214
+ /** Estimates and counts only; no paths, queries, terms, contexts or definitions. */
215
+ export function lexiconRtDiagnostics() {
216
+ const controller = controllers.stats()
217
+ const concept = views.stats()
218
+ const queue = pending.stats()
219
+ const activeBytes = active ? estimateBytes(active.job) + 4096 : 0
220
+ return { ...counters, mode: lexiconRtMode(), suspended, controller, concept, queue,
221
+ active: Boolean(active), activeBytes,
222
+ derivedEstimatedBytes: controller.bytes + concept.bytes + queue.bytes + activeBytes,
223
+ derivedCacheCapBytes: controller.maxBytes + concept.maxBytes + queue.maxBytes }
224
+ }
@@ -22,7 +22,8 @@ import {
22
22
  } from './state.js'
23
23
  import { appliesToDomain, crossLibrarySources, domainOf } from './memory.js'
24
24
  import {
25
- GLOBAL_LEXICON_ID, matchLexiconHits, rankLexiconHits, searchLexicon, visibleLexiconTerms,
25
+ GLOBAL_LEXICON_ID, LEXICON_MAX_PER_TURN, lexiconConceptHits, lexiconRecallHit,
26
+ matchLexiconHits, normalizeLexeme, rankLexiconHits, searchLexicon, visibleLexiconTerms,
26
27
  } from './lexicon.js'
27
28
 
28
29
  // 同域其它库的条目过滤:与 memory.js domainScopedIndex 同口径——没有 domain 的旧词条
@@ -40,6 +41,11 @@ function globalEntryVisible(entry, binding) {
40
41
  return appliesToDomain(entry, binding)
41
42
  }
42
43
 
44
+ function sourceEntryVisible(entry, source, binding) {
45
+ return source.scope === 'global' ? globalEntryVisible(entry, binding)
46
+ : privateEntryVisible(entry, domainOf(binding), { primary: source.primary })
47
+ }
48
+
43
49
  /**
44
50
  * 这个会话到底读不读词典。私有记忆关掉时全局词典仍然要读(全局记忆同理),
45
51
  * 所以不能沿用 `binding.libraryId && useLibrary` 那把旧尺。
@@ -101,7 +107,7 @@ function eachSource(binding, sources, read) {
101
107
  : (entry) => privateEntryVisible(entry, domain, { primary: source.primary })
102
108
  for (const entry of found) {
103
109
  if (!keep(entry)) continue
104
- const surface = entry?.normalizedTerm || entry?.term
110
+ const surface = entry?.normalizedTerm || normalizeLexeme(entry?.term)
105
111
  if (dedupe && surface) {
106
112
  if (seen.has(surface)) continue
107
113
  seen.add(surface)
@@ -123,10 +129,55 @@ export function lexiconVisibleTerms(binding, { includeArchived = false } = {}) {
123
129
  * B 通道匹配面:跨源命中用核心的 `rankLexiconHits` 重排——排序尺子只有一把,
124
130
  * 在核心里,合并方不自定顺序。
125
131
  */
126
- export function lexiconMatch(binding, text) {
132
+ export function lexiconMatch(binding, text, { automatic = false } = {}) {
133
+ const sources = lexiconSources(binding)
134
+ const { rows, errors } = eachSource(binding, sources, (source) => matchLexiconHits(source.libraryId, text, binding?.memoryContext || {}, {
135
+ acceptEntry: entry => sourceEntryVisible(entry, source, binding) && (!automatic || entry.visibility !== 'secret'),
136
+ }))
137
+ return { hits: rankLexiconHits(rows).map(hit => ({ ...lexiconRecallHit(hit, { automatic }),
138
+ libraryId: hit.libraryId, libraryName: hit.libraryName, lexiconScope: hit.lexiconScope })), errors, sources }
139
+ }
140
+
141
+ /** Independent lexicon slots. RRF ranks surfaces and concepts without entering memory MMR. */
142
+ export function recallLexicon(binding, query, { automatic = true } = {}) {
127
143
  const sources = lexiconSources(binding)
128
- const { rows, errors } = eachSource(binding, sources, (source) => matchLexiconHits(source.libraryId, text, binding?.memoryContext || {}))
129
- return { hits: rankLexiconHits(rows), errors, sources }
144
+ const context = binding?.memoryContext || {}
145
+ const derivedErrors = []
146
+ const surfaces = eachSource(binding, sources, source => matchLexiconHits(source.libraryId, query, context, {
147
+ acceptEntry: entry => sourceEntryVisible(entry, source, binding) && (!automatic || entry.visibility !== 'secret'),
148
+ }))
149
+ const concepts = eachSource(binding, sources, source => lexiconConceptHits(source.libraryId, query, context, {
150
+ automatic, acceptEntry: entry => sourceEntryVisible(entry, source, binding),
151
+ scopeKey: JSON.stringify([domainOf(binding), source.scope, source.primary]),
152
+ onFallback: code => derivedErrors.push(`${source.libraryId}: lexicon ${code}`),
153
+ }))
154
+ // Source priority applies to the union: a global concept must not duplicate a private surface hit.
155
+ const sourceRanks = new Map(sources.map((source, rank) => [source.libraryId, rank]))
156
+ const preferred = new Map()
157
+ for (const row of [...surfaces.rows, ...concepts.rows]) {
158
+ const surface = row.normalizedTerm || normalizeLexeme(row.term)
159
+ const owner = preferred.get(surface)
160
+ if (!owner || sourceRanks.get(row.libraryId) < sourceRanks.get(owner)) preferred.set(surface, row.libraryId)
161
+ }
162
+ const preferredSource = row => preferred.get(row.normalizedTerm || normalizeLexeme(row.term)) === row.libraryId
163
+ const ranked = new Map()
164
+ for (const [channel, rows] of [['surface', rankLexiconHits(surfaces.rows.filter(preferredSource))],
165
+ ['bm25', concepts.rows.filter(preferredSource).sort((a, b) => b.score - a.score || a.termId.localeCompare(b.termId))]]) {
166
+ rows.forEach((row, index) => {
167
+ const key = JSON.stringify([row.libraryId, row.termId])
168
+ let hit = ranked.get(key)
169
+ if (!hit) { hit = { ...row, rrfScore: 0, ranks: {} }; ranked.set(key, hit) }
170
+ hit.rrfScore += 1 / (60 + index + 1)
171
+ hit.ranks[channel] = index + 1
172
+ })
173
+ }
174
+ const hits = [...ranked.values()].sort((a, b) => b.rrfScore - a.rrfScore
175
+ || (a.ranks.surface || Infinity) - (b.ranks.surface || Infinity)
176
+ || a.termId.localeCompare(b.termId)).map(row => ({
177
+ ...lexiconRecallHit(row, { automatic }), libraryId: row.libraryId, libraryName: row.libraryName,
178
+ lexiconScope: row.lexiconScope, rrfScore: row.rrfScore, ranks: row.ranks,
179
+ }))
180
+ return { lexicon: hits.slice(0, LEXICON_MAX_PER_TURN), hits, errors: [...new Set([...surfaces.errors, ...concepts.errors, ...derivedErrors])], sources }
130
181
  }
131
182
 
132
183
  /** 模型检索面(memu_lexicon_search):核心已按 matchedBy 排过,合并只保留优先级序。 */
package/lib/lexicon.js CHANGED
@@ -20,10 +20,15 @@
20
20
  // lexiconIndexCache 的注释——JSON 是唯一主事实,索引永远是可重建的派生物。
21
21
  import fs from 'node:fs'
22
22
  import path from 'node:path'
23
- import { dataDir, readJsonStrict, readFailure, writeJson, withFileLock, isSafeId, shortHash, warn, stamp } from './paths.js'
23
+ import { dataDir, readJsonStrict, readFailure, writeJson, withFileLock, isSafeId, shortHash, warn, stamp, redactSecrets } from './paths.js'
24
24
  import { normalizeMemoryContext, contextVisible, sameFactContext } from './context.js'
25
25
  import { bigrams, dice } from './text-similarity.js'
26
26
  import { estTokens } from './budget.js'
27
+ import { bm25, tokenize } from './text-retrieval.js'
28
+ import { createBoundedCache } from './bounded-cache.js'
29
+ import { BM25_DF_MIN_POOL, BM25_DF_RATIO, BM25_MAX_QUERY_TERMS } from './curator-policy.js'
30
+ import { createLexiconRtSource } from './lexicon-rt-source.js'
31
+ import { lexiconRtPostings, invalidateLexiconRtViews, lexiconRtDiagnostics } from './lexicon-rt.js'
27
32
 
28
33
  // 容量与长度上限(§1.2)。刻意不接 settings:容量是存储安全边界,不该被运行时配置放宽。
29
34
  export const LEXICON_CAP = 5000
@@ -55,6 +60,7 @@ const BUCKET_WIDTH = 2
55
60
  export const LEXICON_RECALL_COOLDOWN_MINUTES = 30
56
61
  export const LEXICON_MAX_PER_TURN = 2
57
62
  export const lexiconCooldownStore = new Map() // key: sessionKey → Map(termId → lastInjectedAt ms)
63
+ const lexiconTurnCounts = new Map()
58
64
 
59
65
  // 频率先验:三计数的写入上限与 Wilson 下界的 z 值。上限挡住
60
66
  // 病态数据把 effective 因子顶出 [0.85,1.00] 的界;z=1.96 即 95% 单侧置信。
@@ -78,6 +84,10 @@ function clip(text, max) {
78
84
  return s.length > max ? s.slice(0, max) : s
79
85
  }
80
86
 
87
+ function sensitiveLexiconEntry(entry) {
88
+ return entry.sensitivity === 'sensitive' || (entry.kind === 'trigger' && !entry.sensitivity)
89
+ }
90
+
81
91
  /**
82
92
  * 词条词面的统一规范化:NFKC → 大小写折叠 → 去空白/标点/符号。
83
93
  * 与 lib/text-similarity.js clean()(memory.js 矛盾检测的既有预处理)同风格,
@@ -89,7 +99,7 @@ export function normalizeLexeme(text) {
89
99
  }
90
100
 
91
101
  function lexiconDir() {
92
- return path.join(dataDir(), 'lexicon')
102
+ return path.resolve(dataDir(), 'lexicon')
93
103
  }
94
104
 
95
105
  // 全局词典与私有词典同格式、同锁、同缓存,只是占一个保留的存储名。
@@ -150,7 +160,8 @@ function readLexiconStrict(file, libraryId) {
150
160
  }
151
161
 
152
162
  // ── revision-keyed 内存索引(§10 P1 / §8.2 的 O(N) 优化项)───────────────────
153
- // 每本词典在进程内保留一份「读取快照 + 派生索引」,key = `${libraryId}@${revision}`:
163
+ // 每本词典在进程内保留一份「读取快照 + 派生索引」,以绝对文件路径定位、revision
164
+ // 与文件指纹判新;全进程 LRU 受条数、估算字节与非滑动 TTL 三重约束:
154
165
  // data 严格读取出的词典对象(JSON 永远是主事实,快照只是派生物)
155
166
  // activeEntries / archivedEntries / pendingEntries 构建时分好 status 并按展示序
156
167
  // 排好的词条;archived 里可能包含 legacy revision 草稿(带 revisionOf,
@@ -163,17 +174,37 @@ function readLexiconStrict(file, libraryId) {
163
174
  //
164
175
  // 失效策略(正确性红线:任何绕过本进程的文件改动不得让缓存返回旧数据):
165
176
  // * 进程内一切写都走 mutateLexicon → 写成功后立即用刚落盘的对象重建快照
166
- // (revision 已 +1,旧 key 随之作废)。
177
+ // (revision 已 +1,旧的概念 postings 缓存同步失效)。
167
178
  // * 进程外的改动(测试直写 paths.writeJson、backup 恢复、手工修复文件):缓存
168
- // 命中前对文件 stat 一次并比对 mtimeMs + size。一次 stat(µs 级)远比全量
169
- // JSON.parse(N=5k 时 ms 级)便宜;mtime 与 size 同时不变的覆写只剩「同毫秒内
170
- // 等字节覆写」一条理论缝,在 NTFS/APFS/ext4(亚毫秒 mtime 精度)上实际不可达。
179
+ // 命中前比对高精度 mtimeNs/ctimeNs/size/ino,等长覆写并恢复 mtime 仍会失效。
171
180
  // 选 stat 比对而不是 revision 校验:revision 在 JSON 内部,读它就得先 parse,
172
- // 等于放弃缓存。quarantine 把文件挪走 → stat 失败 → 必然 miss 回严格读取,
181
+ // 等于放弃缓存。quarantine 把文件挪走 → stat 缺失 → 必然 miss 回严格读取,
173
182
  // typed error 语义不变。
174
183
  // * 文件缺失(空库)不缓存:外部新建的文件必须立刻被下一次读取看见。
175
- const lexiconIndexCache = new Map() // key: `${libraryId}@${revision}` → snapshot
176
- const lexiconIndexHint = new Map() // libraryId → { key, mtimeMs, size }
184
+ const recallDiagnostics = { builds: 0, invalidations: 0, readFailures: 0, conceptBuilds: 0, largestConceptBytes: 0, queries: 0, candidates: 0 }
185
+ const lexiconIndexCache = createBoundedCache({ name: 'lexiconIndex', maxBytes: 64 * 1024 * 1024, maxEntries: 32, ttlMs: 300_000 })
186
+
187
+ function fileSignature(file) {
188
+ try {
189
+ const stat = fs.statSync(file, { bigint: true })
190
+ return `${stat.mtimeNs}:${stat.ctimeNs}:${stat.size}:${stat.ino}`
191
+ } catch (error) {
192
+ if (error?.code === 'ENOENT') return null
193
+ throw error
194
+ }
195
+ }
196
+
197
+ function invalidateLexicon(file) {
198
+ if (lexiconIndexCache.delete(file)) recallDiagnostics.invalidations++
199
+ invalidateLexiconRtViews(file)
200
+ }
201
+
202
+ /** Numeric diagnostics only: no queries, library ids, context or definitions. */
203
+ export function lexiconRecallDiagnostics() {
204
+ const rt = lexiconRtDiagnostics()
205
+ return { ...recallDiagnostics, conceptBuilds: rt.viewBuilds, largestConceptBytes: rt.largestViewBytes,
206
+ index: lexiconIndexCache.stats(), concept: rt.concept, rt }
207
+ }
177
208
 
178
209
  // 展示序:strength → updatedAt → termId(构建索引与 merged 列表共用同一把尺)。
179
210
  function displayRank(a, b) {
@@ -229,23 +260,19 @@ function buildLexiconIndex(data) {
229
260
  activeEntries.sort(displayRank)
230
261
  archivedEntries.sort(displayRank)
231
262
  pendingEntries.sort(displayRank)
232
- return { data, activeEntries, archivedEntries, pendingEntries, byNormalizedTerm, byAlias, prefixBuckets, grams, surfacesByTerm }
263
+ return { data, activeEntries, archivedEntries, pendingEntries, byNormalizedTerm, byAlias, prefixBuckets, grams, surfacesByTerm,
264
+ rtSource: createLexiconRtSource(data) }
233
265
  }
234
266
 
267
+ /** Strict canonical source for the isolated lexicon postings worker. */
268
+ export function loadLexiconRtSource(libraryId) { return lexiconIndex(libraryId).rtSource }
269
+
235
270
  function storeLexiconIndex(libraryId, file, data) {
236
271
  const snapshot = buildLexiconIndex(data)
237
- const key = `${libraryId}@${data.revision}`
238
- const previous = lexiconIndexHint.get(libraryId)
239
- if (previous) lexiconIndexCache.delete(previous.key)
240
- let stat = null
241
- try { stat = fs.statSync(file) } catch {}
242
- if (stat) {
243
- lexiconIndexCache.set(key, snapshot)
244
- lexiconIndexHint.set(libraryId, { key, mtimeMs: stat.mtimeMs, size: stat.size })
245
- } else {
246
- // 空库(文件还不存在)不缓存缺失状态。
247
- lexiconIndexHint.delete(libraryId)
248
- }
272
+ invalidateLexicon(file)
273
+ recallDiagnostics.builds++
274
+ snapshot.signature = fileSignature(file)
275
+ if (snapshot.signature) lexiconIndexCache.set(file, snapshot)
249
276
  return snapshot
250
277
  }
251
278
 
@@ -255,19 +282,20 @@ function lexiconIndex(libraryId) {
255
282
  // quarantine(读失败保护)优先于一切缓存:曾 quarantined 的库必须继续 typed error。
256
283
  const failure = readFailure(file)
257
284
  if (failure) {
285
+ invalidateLexicon(file)
286
+ recallDiagnostics.readFailures++
258
287
  throw lexiconError('LEXICON_READ_FAILED', `lexicon ${libraryId} is write-protected by an earlier read failure (${failure.code || failure.message})`)
259
288
  }
260
- const hint = lexiconIndexHint.get(libraryId)
261
- if (hint) {
262
- let stat = null
263
- try { stat = fs.statSync(file) } catch {}
264
- if (stat && stat.mtimeMs === hint.mtimeMs && stat.size === hint.size) {
265
- const snapshot = lexiconIndexCache.get(hint.key)
266
- if (snapshot) return snapshot
267
- }
289
+ const snapshot = lexiconIndexCache.get(file)
290
+ try {
291
+ if (snapshot && snapshot.signature === fileSignature(file)) return snapshot
292
+ const data = readLexiconStrict(file, libraryId)
293
+ return storeLexiconIndex(libraryId, file, data)
294
+ } catch (error) {
295
+ invalidateLexicon(file)
296
+ recallDiagnostics.readFailures++
297
+ throw error
268
298
  }
269
- const data = readLexiconStrict(file, libraryId)
270
- return storeLexiconIndex(libraryId, file, data)
271
299
  }
272
300
 
273
301
  /**
@@ -672,12 +700,12 @@ export function visibleLexiconTerms(libraryId, memoryContext, { includeArchived
672
700
  const index = lexiconIndex(libraryId)
673
701
  const out = []
674
702
  for (const { termId, entry } of index.activeEntries) {
675
- if (!contextVisible(entry.context, memoryContext)) continue
703
+ if (!contextVisible(entry.context, memoryContext) || !contextVisible({ knownBy: entry.knownBy }, memoryContext)) continue
676
704
  out.push(withTermId(entry, termId))
677
705
  }
678
706
  if (includeArchived) {
679
707
  for (const { termId, entry } of index.archivedEntries) {
680
- if (!contextVisible(entry.context, memoryContext)) continue
708
+ if (!contextVisible(entry.context, memoryContext) || !contextVisible({ knownBy: entry.knownBy }, memoryContext)) continue
681
709
  out.push(withTermId(entry, termId))
682
710
  }
683
711
  out.sort((a, b) => (Number(b.strength) || 0) - (Number(a.strength) || 0)
@@ -836,7 +864,7 @@ function hitOf(entry, termId, kindOfHit, score) {
836
864
  kind: entry.kind,
837
865
  meaning: entry.meaning,
838
866
  usage: entry.usage,
839
- sensitivity: entry.sensitivity,
867
+ sensitivity: entry.sensitivity || (entry.kind === 'trigger' ? 'sensitive' : 'normal'),
840
868
  strength: entry.strength,
841
869
  confidence: entry.confidence,
842
870
  // 频率先验(§6.3)的输入:stableRank 的 effective 因子按三计数算 Wilson 下界。
@@ -862,7 +890,7 @@ function hitOf(entry, termId, kindOfHit, score) {
862
890
  * 排序(A-8:候选准入看相关性,不看 strength)。可见性(status +
863
891
  * contextVisible)在收候选时逐个复核。
864
892
  */
865
- export function matchLexiconHits(libraryId, userText, memoryContext) {
893
+ export function matchLexiconHits(libraryId, userText, memoryContext, { acceptEntry = null } = {}) {
866
894
  const normalizedText = normalizeLexeme(userText)
867
895
  if (!normalizedText) return []
868
896
  const index = lexiconIndex(libraryId)
@@ -870,6 +898,7 @@ export function matchLexiconHits(libraryId, userText, memoryContext) {
870
898
  const isVisible = termId => {
871
899
  const entry = data.terms[termId]
872
900
  return Boolean(entry) && (entry.status || 'active') === 'active' && contextVisible(entry.context, memoryContext)
901
+ && contextVisible({ knownBy: entry.knownBy }, memoryContext) && (!acceptEntry || acceptEntry(entry))
873
902
  }
874
903
  // 精确层·等值:Map 直查(同库同词面可有多条跨 scope 词条,值是 termId 列表)。
875
904
  const hits = []
@@ -935,6 +964,58 @@ export function matchLexiconHits(libraryId, userText, memoryContext) {
935
964
  return stableRank([...hits, ...fuzzy])
936
965
  }
937
966
 
967
+ /** Concept retrieval has its own corpus. Eligibility precedes df/avgdl and postings. */
968
+ export function lexiconConceptHits(libraryId, query, memoryContext, { automatic = true, acceptEntry = null, scopeKey = '', onFallback = null } = {}) {
969
+ // A shared CJK character alone is not evidence of the same convention.
970
+ const tokens = tokenize(query).filter(token => [...token].length > 1)
971
+ if (!tokens.length) return []
972
+ const index = lexiconIndex(libraryId)
973
+ const file = lexiconFile(libraryId)
974
+ const data = lexiconRtPostings({ file, libraryId, owner: index, source: index.rtSource, tokens,
975
+ cacheKey: scopeKey ? JSON.stringify([memoryContext || {}, automatic, scopeKey]) : '',
976
+ isVisible: (document) => {
977
+ const entry = document.lexicon
978
+ return (entry.status || 'active') === 'active' && contextVisible(entry.context, memoryContext)
979
+ && contextVisible({ knownBy: entry.knownBy }, memoryContext)
980
+ && (!automatic || entry.visibility !== 'secret') && (!acceptEntry || acceptEntry(entry))
981
+ },
982
+ })
983
+ if (data.fallback) onFallback?.(data.fallback)
984
+ recallDiagnostics.queries++
985
+ function rank(postings, countCandidates = false) {
986
+ const { corpus } = postings
987
+ const dfCap = Math.max(BM25_DF_MIN_POOL, Math.ceil(BM25_DF_RATIO * corpus.size))
988
+ const queryTokens = tokens.filter(token => (corpus.df.get(token) || 0) > 0 && corpus.df.get(token) <= dfCap)
989
+ .sort((a, b) => corpus.df.get(a) - corpus.df.get(b) || a.localeCompare(b)).slice(0, BM25_MAX_QUERY_TERMS)
990
+ const hits = []
991
+ for (const [termId, doc] of postings.docs) {
992
+ if (!queryTokens.some(token => doc.tf.has(token))) continue
993
+ if (countCandidates) recallDiagnostics.candidates++
994
+ const score = bm25(queryTokens, doc, corpus)
995
+ if (score > 0) hits.push({ ...hitOf(index.data.terms[termId], termId, 'recall-bm25', score), matchedBy: 'recall-bm25' })
996
+ }
997
+ return hits.sort((a, b) => b.score - a.score || effectiveWeight(b) - effectiveWeight(a)
998
+ || a.termId.localeCompare(b.termId)).slice(0, LEXICON_MAX_TERMS)
999
+ }
1000
+ const hits = rank(data, true)
1001
+ if (data.shadow) {
1002
+ const comparable = rows => rows.map(hit => ({ id: hit.termId, score: hit.score }))
1003
+ const comparison = data.compareFinal(comparable(hits), comparable(rank(data.shadow)))
1004
+ if (comparison.agreement !== 1 || comparison.scoreDifferences || !comparison.orderEqual) onFallback?.('RT_SHADOW_MISMATCH')
1005
+ }
1006
+ return hits.map(hit => lexiconRecallHit(hit, { automatic }))
1007
+ }
1008
+
1009
+ /** Automatic surfaces expose sensitive terms through a strict allowlist. */
1010
+ export function lexiconRecallHit(hit, { automatic = true } = {}) {
1011
+ const matchedBy = hit.matchedBy || hit.kindOfHit
1012
+ const ref = `[lex:${hit.termId}]`
1013
+ if (automatic && sensitiveLexiconEntry(hit)) return {
1014
+ termId: hit.termId, term: hit.term, sensitivity: 'sensitive', matchedBy, kindOfHit: hit.kindOfHit, score: hit.score, ref,
1015
+ }
1016
+ return { ...hit, matchedBy, ref }
1017
+ }
1018
+
938
1019
  /**
939
1020
  * 精确层检索(§3.3 通道 C 的数据面):等值 + includes,不做 dice、不做语义。
940
1021
  * 默认只回 active;`includeArchived: true` 让管理面/浏览器显式看到归档词条。
@@ -1019,8 +1100,8 @@ export function searchLexicon({ libraryId, query, memoryContext }, { includeArch
1019
1100
  * 不展开 usage/examples——注入行永远是「标题 + 短释义」。
1020
1101
  */
1021
1102
  export function lexiconTurnLine(hit) {
1022
- const body = clip(String(hit.meaning || hit.usage || ''), 80)
1023
- return `「${clip(String(hit.term || ''), 40)}」${body ? `:${body}` : ''}`
1103
+ const body = sensitiveLexiconEntry(hit) ? '' : clip(redactSecrets(hit.meaning || hit.usage || ''), 80)
1104
+ return `「${clip(redactSecrets(hit.term || ''), 40)}」${body ? `:${body}` : ''}${hit.termId ? ` [lex:${hit.termId}]` : ''}${hit.matchedBy ? ` · matchedBy=${hit.matchedBy}` : ''}`
1024
1105
  }
1025
1106
 
1026
1107
  /**
@@ -1028,11 +1109,13 @@ export function lexiconTurnLine(hit) {
1028
1109
  * 但不进 selected(不计 injection)。预算按渲染行的 estTokens 顺序扣,扣不动就停。
1029
1110
  * bindingState 传 sessionId(string)或带 sessionId 的 binding 对象。
1030
1111
  */
1031
- export function cooldownAndBudget(hits, bindingState, tokenBudget) {
1112
+ export function cooldownAndBudget(hits, bindingState, tokenBudget, { turn = null } = {}) {
1032
1113
  const sessionKey = typeof bindingState === 'string' ? bindingState : String(bindingState?.sessionId || '')
1033
1114
  const now = Date.now()
1034
1115
  const cooldownMs = LEXICON_RECALL_COOLDOWN_MINUTES * 60_000
1035
1116
  const last = lexiconCooldownStore.get(sessionKey)
1117
+ const priorTurn = lexiconTurnCounts.get(sessionKey)
1118
+ const remaining = Math.max(0, LEXICON_MAX_PER_TURN - (turn !== null && priorTurn?.turn === turn ? priorTurn.count : 0))
1036
1119
  const selected = []
1037
1120
  const onCooldown = []
1038
1121
  let used = 0
@@ -1040,8 +1123,8 @@ export function cooldownAndBudget(hits, bindingState, tokenBudget) {
1040
1123
  for (const hit of hits) {
1041
1124
  const injectedAt = last?.get(hit.termId) || 0
1042
1125
  if (injectedAt && now - injectedAt < cooldownMs) { onCooldown.push(hit); continue }
1043
- if (selected.length >= LEXICON_MAX_PER_TURN) continue
1044
- const cost = estTokens(lexiconTurnLine(hit)) + (selected.length ? 1 : 0)
1126
+ if (selected.length >= remaining) continue
1127
+ const cost = estTokens(`- ${lexiconTurnLine(hit)}`) + 1
1045
1128
  if (used + cost > budget) continue
1046
1129
  used += cost
1047
1130
  selected.push(hit)
@@ -1050,19 +1133,22 @@ export function cooldownAndBudget(hits, bindingState, tokenBudget) {
1050
1133
  }
1051
1134
 
1052
1135
  /** 注入真的发生之后才调用:记冷却,下一次同词在冷却窗口内只做 candidate。 */
1053
- export function lexiconMarkInjected(bindingKey, termIds, now = Date.now()) {
1136
+ export function lexiconMarkInjected(bindingKey, termIds, now = Date.now(), { turn = null } = {}) {
1054
1137
  const sessionKey = String(bindingKey || '')
1055
1138
  if (!sessionKey || !Array.isArray(termIds) || termIds.length === 0) return
1056
1139
  let last = lexiconCooldownStore.get(sessionKey)
1057
1140
  if (!last) { last = new Map(); lexiconCooldownStore.set(sessionKey, last) }
1058
1141
  for (const termId of termIds) last.set(termId, now)
1059
- // Map 只增不减会陪着进程活着变大;词条冷却窗口 30 分钟,过期键在读取时本就无效,
1060
- // 这里顺手把整本已过期的 session 键清掉,成本 O(sessions)。
1061
- if (lexiconCooldownStore.size > 512) {
1062
- for (const [key, value] of lexiconCooldownStore) {
1063
- const freshest = Math.max(...value.values())
1064
- if (now - freshest >= cooldownWindowMs()) lexiconCooldownStore.delete(key)
1065
- }
1142
+ for (const [id, at] of last) if (now - at >= cooldownWindowMs()) last.delete(id)
1143
+ while (last.size > 512) last.delete(last.keys().next().value)
1144
+ lexiconCooldownStore.delete(sessionKey)
1145
+ lexiconCooldownStore.set(sessionKey, last)
1146
+ while (lexiconCooldownStore.size > 512) lexiconCooldownStore.delete(lexiconCooldownStore.keys().next().value)
1147
+ if (turn !== null) {
1148
+ const prior = lexiconTurnCounts.get(sessionKey)
1149
+ lexiconTurnCounts.delete(sessionKey)
1150
+ lexiconTurnCounts.set(sessionKey, { turn, count: (prior?.turn === turn ? prior.count : 0) + termIds.length })
1151
+ while (lexiconTurnCounts.size > 512) lexiconTurnCounts.delete(lexiconTurnCounts.keys().next().value)
1066
1152
  }
1067
1153
  }
1068
1154
 
@@ -1119,16 +1205,19 @@ export function rankLexiconHits(hits) {
1119
1205
  *
1120
1206
  * visibility 与记忆同一套语义(lib/memory.js visibleToSession 的契约:secret 只是
1121
1207
  * "不主动浮出",不改变"被点名时"的可见性):锚点是主动浮出,secret 词条不进摘要;
1122
- * B 通道是用户消息点到了词面(等价于按词点名),secret 词条仍然命中并解释。
1208
+ * 自动词典块与锚点都不浮出 secret;显式检索仍保留原有读取能力。
1123
1209
  *
1124
1210
  * 入参是「已按可见性过滤好的词条」,所以单库摘要与跨源合并摘要共用同一份渲染与
1125
1211
  * 取舍规则(lexiconAnchorSummary 是本函数在单库上的包装)。
1126
1212
  */
1127
1213
  export function lexiconAnchorLines(entries) {
1128
1214
  const anchorable = (Array.isArray(entries) ? entries : []).filter(entry => entry.visibility !== 'secret')
1129
- const sensitive = anchorable.filter(entry => entry.sensitivity === 'sensitive')
1130
- const normal = anchorable.filter(entry => entry.sensitivity !== 'sensitive')
1131
- const line = entry => `「${clip(String(entry.term || ''), 40)}」(${entry.kind})${entry.meaning ? ` ${clip(String(entry.meaning), 80)}` : ''}`
1215
+ const isSensitive = sensitiveLexiconEntry
1216
+ const sensitive = anchorable.filter(isSensitive)
1217
+ const normal = anchorable.filter(entry => !isSensitive(entry))
1218
+ const line = entry => isSensitive(entry)
1219
+ ? `「${clip(redactSecrets(entry.term || ''), 40)}」`
1220
+ : `「${clip(redactSecrets(entry.term || ''), 40)}」(${entry.kind})${entry.meaning ? ` ${clip(redactSecrets(entry.meaning), 80)}` : ''}`
1132
1221
  const byStrength = list => [...list].sort((a, b) => (Number(b.strength) || 0) - (Number(a.strength) || 0)
1133
1222
  || String(b.updatedAt || '').localeCompare(String(a.updatedAt || ''))
1134
1223
  || String(a.termId).localeCompare(String(b.termId)))