dsh-memu-memory 1.2.4 → 1.2.6

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 (57) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +9 -9
  3. package/README.zh.md +6 -6
  4. package/docs/binding-lifecycle.md +1 -1
  5. package/docs/env-and-commands.md +4 -1
  6. package/docs/host-adaptation.md +318 -0
  7. package/docs/host-api.md +29 -5
  8. package/docs/memory-semantics.md +45 -9
  9. package/docs/troubleshooting.md +27 -8
  10. package/lib/binding-diagnostics.js +2 -2
  11. package/lib/client.js +246 -56
  12. package/lib/consolidation-ledger.js +46 -1
  13. package/lib/consolidation-worker.js +1 -0
  14. package/lib/cycle.js +51 -17
  15. package/lib/embedding-catalog.js +14 -0
  16. package/lib/embedding-runtime.js +202 -25
  17. package/lib/global-graph.js +99 -1
  18. package/lib/index.js +8 -0
  19. package/lib/inject.js +71 -33
  20. package/lib/lexicon-scope.js +143 -0
  21. package/lib/lexicon.js +31 -4
  22. package/lib/local-vector-service.js +82 -6
  23. package/lib/memory.js +186 -12
  24. package/lib/memu.js +318 -3
  25. package/lib/private.js +310 -67
  26. package/lib/rpc.js +183 -23
  27. package/lib/salient-wake.js +38 -2
  28. package/lib/state.js +7 -5
  29. package/lib/tools.js +40 -17
  30. package/lib/vector-migration.js +13 -1
  31. package/lib/webui/graph-view.bundle.js +1 -1
  32. package/lib/webui/graph-view.js +4 -1
  33. package/package.json +1 -1
  34. package/tests/absorb-review.test.mjs +2 -1
  35. package/tests/backend-compensation.test.mjs +1 -1
  36. package/tests/browser.test.mjs +58 -1
  37. package/tests/client-render.test.mjs +39 -0
  38. package/tests/consolidation-fork.test.mjs +81 -6
  39. package/tests/cross-library-recall.test.mjs +113 -0
  40. package/tests/curator-absorb.test.mjs +2 -1
  41. package/tests/curator-clusters.test.mjs +2 -1
  42. package/tests/curator-commit.test.mjs +2 -1
  43. package/tests/curator-link.test.mjs +2 -1
  44. package/tests/curator-review-mode.test.mjs +2 -1
  45. package/tests/cycle.test.mjs +2 -2
  46. package/tests/embedding-runtime.test.mjs +53 -1
  47. package/tests/global-graph.test.mjs +90 -0
  48. package/tests/lexicon-scope.test.mjs +256 -0
  49. package/tests/lexicon-ui.test.mjs +23 -0
  50. package/tests/managed-memory.test.mjs +1 -1
  51. package/tests/recall-dedup.test.mjs +1 -1
  52. package/tests/salient-wake.test.mjs +28 -1
  53. package/tests/settings-plumbing.test.mjs +1 -0
  54. package/tests/stubs/dsh-schedule.js +35 -0
  55. package/tests/ui-defaults.test.mjs +1 -1
  56. package/tests/vector-migration.test.mjs +20 -0
  57. package/tests/webui-auth.test.mjs +28 -0
@@ -25,7 +25,7 @@
25
25
 
26
26
  import { createHash } from 'node:crypto'
27
27
  import { record } from './activity-log.js'
28
- import { updateGlobalIndex } from './state.js'
28
+ import { loadGlobalIndex, updateGlobalIndex } from './state.js'
29
29
  import { redactSecrets } from './paths.js'
30
30
  import { groundEvidence, groundLinkNote } from './curator-evidence.js'
31
31
  import { globalConflictCheck } from './text-retrieval.js'
@@ -243,6 +243,104 @@ export function applyGlobalLinks(entries, writes, { now = new Date().toISOString
243
243
  return { applied, skipped }
244
244
  }
245
245
 
246
+ const GRAPH_HIDDEN_STATUS = new Set(['suppressed', 'expired'])
247
+
248
+ /**
249
+ * getGlobalGraph({ focusId, depth, limit }) — read-only node graph over the
250
+ * global index. Private memory has getGraph in graph.js; global edges live in
251
+ * entries[id].links[] and have no entity store, so this mirrors the same
252
+ * node/edge contract without entities or merge candidates.
253
+ *
254
+ * Suppressed/expired entries are hidden; a deleted target keeps a placeholder
255
+ * node so the edge does not silently disappear, while an existing hidden target
256
+ * gets no hint at all (same rule as the private graph).
257
+ */
258
+ export function getGlobalGraph({ focusId = null, depth = 1, limit = 200 } = {}) {
259
+ const index = loadGlobalIndex()
260
+ const entries = index.entries || {}
261
+ const cap = Math.max(1, Math.min(200, Math.floor(Number(limit) || 200)))
262
+ const hops = Math.max(0, Math.min(2, Math.floor(Number(depth) || 0)))
263
+ const visible = new Set(Object.entries(entries)
264
+ .filter(([, entry]) => entry && !GRAPH_HIDDEN_STATUS.has(entry.status || 'active'))
265
+ .map(([id]) => id))
266
+ const edges = []
267
+ const adjacency = new Map()
268
+ // Symmetric `related` edges are stored on both ends under one link id; without
269
+ // this set the canvas would draw the same line twice and the list twice.
270
+ const seenEdges = new Set()
271
+ for (const from of visible) {
272
+ for (const link of entries[from].links || []) {
273
+ if (!GLOBAL_LINK_KINDS.includes(link?.kind)) continue
274
+ const to = String(link?.to || '')
275
+ if (!to) continue
276
+ if (entries[to] && !visible.has(to)) continue
277
+ const edgeId = link.id || `${from}|${link.kind}|${to}`
278
+ if (seenEdges.has(edgeId)) continue
279
+ seenEdges.add(edgeId)
280
+ // `related` is symmetric: sort the endpoints so the same edge reads the
281
+ // same way whichever end happened to be visited first.
282
+ const [edgeFrom, edgeTo] = link.kind === 'related' ? [from, to].sort() : [from, to]
283
+ edges.push({
284
+ from: edgeFrom,
285
+ to: edgeTo,
286
+ kind: link.kind,
287
+ note: link.note,
288
+ confidence: Number.isFinite(Number(link.confidence)) ? Number(link.confidence) : 0.7,
289
+ source: link.source || null,
290
+ })
291
+ for (const [a, b] of [[from, to], [to, from]]) {
292
+ if (!adjacency.has(a)) adjacency.set(a, new Set())
293
+ adjacency.get(a).add(b)
294
+ }
295
+ }
296
+ }
297
+ const selected = new Set()
298
+ if (focusId) {
299
+ const id = String(focusId)
300
+ if (!visible.has(id) && !adjacency.has(id)) throw new Error('unknown or inaccessible global graph focus')
301
+ let frontier = [id]
302
+ for (let hop = 0; hop <= hops; hop += 1) {
303
+ const next = []
304
+ for (const nodeId of frontier) {
305
+ if (selected.size >= cap || selected.has(nodeId)) continue
306
+ selected.add(nodeId)
307
+ if (hop < hops) next.push(...(adjacency.get(nodeId) || []))
308
+ }
309
+ frontier = next
310
+ }
311
+ } else {
312
+ for (const id of [...visible, ...adjacency.keys()]) {
313
+ if (selected.size >= cap) break
314
+ selected.add(id)
315
+ }
316
+ }
317
+ const nodes = [...selected].map((id) => {
318
+ const entry = entries[id]
319
+ const strength = Number(entry?.strength ?? entry?.confidence ?? 0.5)
320
+ return {
321
+ id,
322
+ title: entry?.title || '[deleted]',
323
+ layer: entry?.layer || null,
324
+ // 'global' is distinct from private 'memory' so the canvas can colour it;
325
+ // domain/status are display metadata for the tooltip and audit.
326
+ kind: 'global',
327
+ domain: entry?.domain || null,
328
+ status: entry?.status || 'active',
329
+ strength: Number.isFinite(strength) ? Math.max(0, Math.min(1, strength)) : 0.5,
330
+ degree: adjacency.get(id)?.size || 0,
331
+ missing: !entry,
332
+ }
333
+ })
334
+ return {
335
+ nodes,
336
+ edges: edges.filter((edge) => selected.has(edge.from) && selected.has(edge.to)),
337
+ limit: cap,
338
+ truncated: selected.size >= cap,
339
+ focusId: focusId || null,
340
+ scope: 'global',
341
+ }
342
+ }
343
+
246
344
  /**
247
345
  * removeGlobalLink({ linkId, kind? }) — deletes the edge's records from every
248
346
  * entry carrying that id (symmetric edges die on both ends at once). Metadata
package/lib/index.js CHANGED
@@ -9,6 +9,7 @@ import { getSettings, getMemoryBackend, backupDatabases, flushState, listLibrari
9
9
  import { pruneOrphanEntitiesAll } from './graph.js'
10
10
  import { closeEmbeddingWorkers } from './local-embedding-manager.js'
11
11
  import { bootstrapLocalVector } from './local-vector-service.js'
12
+ import { closeMemuResident, prewarmMemuResident } from './memu.js'
12
13
  import { vectorStatus } from './vector-profile.js'
13
14
  import { setWarnSink } from './paths.js'
14
15
 
@@ -30,6 +31,10 @@ function startLocalVectorBootstrap(ctx) {
30
31
  const catalogId = state?.active?.profile?.catalogId || state?.requested?.catalogId || null
31
32
  if (!catalogId) return
32
33
  const timer = setTimeout(() => {
34
+ // The resident interpreter only pays the MemU import once; it does not wait
35
+ // for the embedding worker, so warming it in parallel with the runtime
36
+ // bootstrap is safe and keeps the first recall from paying the cold start.
37
+ void prewarmMemuResident()
33
38
  void bootstrapLocalVector({ confirmed: false }).then((ready) => {
34
39
  try { ctx.logger?.info?.(`dsh-memu-memory: managed local embedding runtime ready (${String(ready?.model || catalogId)} ${Number(ready?.dimension) || '?'}d)`) } catch {}
35
40
  }).catch((error) => {
@@ -162,6 +167,9 @@ export function apply(ctx, config) {
162
167
  // afterwards instead of failing.
163
168
  if (!inPreset && typeof ctx.effect === 'function') {
164
169
  ctx.effect(() => () => { closeEmbeddingWorkers() }, 'dsh-memu-memory: embedding workers')
170
+ // The resident interpreter is also process-global; leaving it behind would keep
171
+ // a Python process (and its sqlite handles) alive after this plugin unloads.
172
+ ctx.effect(() => () => { closeMemuResident() }, 'dsh-memu-memory: memu resident engine')
165
173
  }
166
174
 
167
175
  const disposeCycle = inPreset ? null : registerCycle(ctx, {
package/lib/inject.js CHANGED
@@ -27,9 +27,10 @@ import {
27
27
  nativeInboundMessage, inboundUserTexts,
28
28
  } from './inbound.js'
29
29
  import {
30
- lexiconAnchorSummary, matchLexiconHits, cooldownAndBudget, lexiconRecordHits, lexiconMarkInjected,
30
+ lexiconAnchorLines, cooldownAndBudget, lexiconRecordHits, lexiconMarkInjected,
31
31
  lexiconTurnLine,
32
32
  } from './lexicon.js'
33
+ import { lexiconHitLibraryId, lexiconMatch, lexiconScopeAllowed, lexiconVisibleTerms } from './lexicon-scope.js'
33
34
 
34
35
  const ANCHOR_SENTINEL = '__anchor__'
35
36
  const PLUGIN = 'dsh-memu-memory'
@@ -571,16 +572,21 @@ export function buildAnchor(binding, settings = getSettings(), sessionId = null)
571
572
  const LEXICON_ANCHOR_TOKEN_CAP = 300
572
573
 
573
574
  /**
574
- * 锚点段追加的词典摘要:可见高强度词条 top8,敏感词条单列 ≤2。
575
- * 行由 lexiconAnchorSummary 按强度排好;这里只按预算从头收,超预算丢尾部——
576
- * 丢的永远是最弱的一条。300 token 硬上限,超了整节放弃也不挤占记忆预算。
575
+ * 锚点段追加的词典摘要:本会话可见的高强度词条 top8,敏感词条单列 ≤2。
576
+ * 可见范围由 lib/lexicon-scope.js 决定(当前库 + 全局词典 + 开关打开后的同域库),
577
+ * 渲染与取舍仍是词典核心那一把尺(lexiconAnchorLines)。
578
+ * 行已按强度排好;这里只按预算从头收,超预算丢尾部——丢的永远是最弱的一条。
579
+ * 300 token 硬上限,超了整节放弃也不挤占记忆预算。
577
580
  */
578
581
  export function buildLexiconAnchor(binding, sessionId = null, cap = LEXICON_ANCHOR_TOKEN_CAP) {
579
- if (!binding?.libraryId || binding.useLibrary === false) return { text: '', ids: [] }
580
- const summary = lexiconAnchorSummary(binding.libraryId, binding.memoryContext)
582
+ if (!lexiconScopeAllowed(binding)) return { text: '', ids: [] }
583
+ const { terms, errors } = lexiconVisibleTerms(binding)
584
+ // 坏掉的辅源只降级不换形状:没有 errors 时返回体与单库时代逐字节一致。
585
+ const degraded = errors.length ? { errors } : {}
586
+ const summary = lexiconAnchorLines(terms)
581
587
  const dataLines = summary.lines.map(line => `- ${line}`)
582
588
  const sensitiveLines = summary.sensitiveTriggers.map(line => `- ${line}`)
583
- if (dataLines.length === 0 && sensitiveLines.length === 0) return { text: '', ids: [] }
589
+ if (dataLines.length === 0 && sensitiveLines.length === 0) return { text: '', ids: [], ...degraded }
584
590
  const budget = Math.max(0, Math.min(Number(cap) || 0, LEXICON_ANCHOR_TOKEN_CAP))
585
591
  // 头部成本先记账,剩余预算给数据行;敏感词没有空间就整段丢(不截半句)。
586
592
  const headerCost = estTokens(dataLines.length ? '[lexicon · 词典] 这些词在你所处的场景里有约定含义。' : '')
@@ -600,11 +606,11 @@ export function buildLexiconAnchor(binding, sessionId = null, cap = LEXICON_ANCH
600
606
  used += cost
601
607
  keptSensitive.push(line)
602
608
  }
603
- if (keptData.length === 0 && keptSensitive.length === 0) return { text: '', ids: [] }
609
+ if (keptData.length === 0 && keptSensitive.length === 0) return { text: '', ids: [], ...degraded }
604
610
  const lines = []
605
611
  if (keptData.length) lines.push('[lexicon · 词典] 这些词在你所处的场景里有约定含义。', ...keptData)
606
612
  if (keptSensitive.length) lines.push('[lexicon · 敏感词] 这些是敏感词,谨慎处理,不要主动展开。', ...keptSensitive)
607
- return { text: lines.join('\n'), ids: [] }
613
+ return { text: lines.join('\n'), ids: [], ...degraded }
608
614
  }
609
615
 
610
616
  /**
@@ -618,18 +624,22 @@ export function buildLexiconAnchor(binding, sessionId = null, cap = LEXICON_ANCH
618
624
  * 本函数只读(match → cooldown/budget → render),不写任何状态:injection 计数
619
625
  * 和冷却标记在文本真的进入消息之后由 commitLexiconTurn 记,预算挤掉的那次不算
620
626
  * 注入过。
627
+ *
628
+ * 匹配跨本词典:当前库 + 全局词典 +(开关打开时)同域其它库,见 lexicon-scope.js。
621
629
  */
622
630
  export function injectLexiconTurn({ binding, sessionId, userTexts, tokenBudget }) {
623
631
  const empty = { text: '', ids: [], hits: [], selected: [], onCooldown: [] }
624
- if (!binding?.libraryId || binding.useLibrary === false) return empty
632
+ if (!lexiconScopeAllowed(binding)) return empty
625
633
  const joined = (Array.isArray(userTexts) ? userTexts : [])
626
634
  .filter(text => typeof text === 'string' && text.trim())
627
635
  .join('\n')
628
636
  if (!joined.trim()) return empty
629
- const hits = matchLexiconHits(binding.libraryId, joined, binding.memoryContext)
630
- if (hits.length === 0) return { ...empty, hits }
637
+ const { hits, errors } = lexiconMatch(binding, joined)
638
+ // 与锚点段同口径:坏掉的辅源只多带一个 errors,不改既有返回形状。
639
+ const degraded = errors.length ? { errors } : {}
640
+ if (hits.length === 0) return { ...empty, hits, ...degraded }
631
641
  const { selected, onCooldown } = cooldownAndBudget(hits, sessionId, tokenBudget)
632
- if (selected.length === 0) return { text: '', ids: [], hits, selected, onCooldown }
642
+ if (selected.length === 0) return { text: '', ids: [], hits, selected, onCooldown, ...degraded }
633
643
  const lines = selected.map(hit => `- ${lexiconTurnLine(hit)}`)
634
644
  const text = [
635
645
  '<memory-lexicon>',
@@ -637,24 +647,45 @@ export function injectLexiconTurn({ binding, sessionId, userTexts, tokenBudget }
637
647
  ...lines,
638
648
  '</memory-lexicon>',
639
649
  ].join('\n')
640
- return { text, ids: [], hits, selected, onCooldown }
650
+ return { text, ids: [], hits, selected, onCooldown, ...degraded }
641
651
  }
642
652
 
643
653
  /**
644
654
  * B 通道的事后记账:candidate 给所有检索撞见过的词条(冷却内的也算——冷却只抑制
645
655
  * 注入,不抑制计数),injection 只给真的注入了的,冷却标记同步写。
656
+ * 计数按词条所属的词典分组落库——跨库命中记到当前库会让别的库的热度永远为 0,
657
+ * 也让 `effective` 的频率先验读到假数据(与记忆侧 touchAccessMany 分组同口径)。
646
658
  */
647
659
  export function commitLexiconTurn({ libraryId, sessionId, hits = [], selected = [] }) {
648
- if (!libraryId) return
649
- try {
650
- const candidateIds = [...new Set(hits.map(hit => hit.termId))].slice(0, 8)
651
- if (candidateIds.length) lexiconRecordHits(libraryId, candidateIds, 'candidate')
652
- } catch {}
653
- if (!selected.length) return
654
- try {
655
- lexiconRecordHits(libraryId, selected.map(hit => hit.termId), 'injection')
656
- lexiconMarkInjected(sessionId, selected.map(hit => hit.termId))
657
- } catch {}
660
+ const byLibrary = new Map()
661
+ const group = (row, kindOfHit) => {
662
+ const owner = lexiconHitLibraryId(row, libraryId)
663
+ if (!owner) return
664
+ if (!byLibrary.has(owner)) byLibrary.set(owner, { candidate: new Set(), injection: new Set() })
665
+ byLibrary.get(owner)[kindOfHit].add(row.termId)
666
+ }
667
+ // candidate 仍是「去重后的前 8 个命中」,只是这次按词条所属的库分组落账。
668
+ const seenIds = new Set()
669
+ let counted = 0
670
+ for (const hit of hits) {
671
+ if (seenIds.has(hit.termId)) continue
672
+ seenIds.add(hit.termId)
673
+ group(hit, 'candidate')
674
+ if (++counted >= 8) break
675
+ }
676
+ for (const row of selected) group(row, 'injection')
677
+ if (!byLibrary.size) return
678
+ for (const [owner, sets] of byLibrary) {
679
+ const candidateIds = [...sets.candidate]
680
+ if (candidateIds.length) {
681
+ try { lexiconRecordHits(owner, candidateIds, 'candidate') } catch {}
682
+ }
683
+ if (!sets.injection.size) continue
684
+ const injectionIds = [...sets.injection]
685
+ try { lexiconRecordHits(owner, injectionIds, 'injection') } catch {}
686
+ }
687
+ // 冷却按会话记,与词条属于哪本库无关。
688
+ if (selected.length) lexiconMarkInjected(sessionId, selected.map(hit => hit.termId))
658
689
  }
659
690
 
660
691
  // ── compaction replay ─────────────────────────────────────────────────────────
@@ -1222,14 +1253,20 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
1222
1253
  parts.push(clipped)
1223
1254
  ids.push(...candidateIds.filter(id => clipped.includes(`[${id}]`)))
1224
1255
  }
1256
+ // 词典失败收集器:只 warn + lastRecallError,绝不进 errors(那会整批重试)。
1257
+ // 必须声明在第一次使用之前:旧版把它写在锚点段之后,锚点一抛就撞进 TDZ,
1258
+ // fail-open 自己变成 ReferenceError。
1259
+ let lexiconError = null
1225
1260
  if (anchorNeeded && totalRoom() >= 160) {
1226
1261
  const anchor = buildAnchor(effective, { ...settings, anchorTokens: Math.min(Number(settings.anchorTokens || 700), Math.floor(turnBudget / 2), totalRoom()) }, sessionId)
1227
1262
  appendBounded(anchor.text, anchor.ids)
1228
1263
  // 锚点段追加词典摘要(§3.3 通道 A)。异常进 lexiconError,fail-open。
1229
- if (effective.useLibrary !== false && effective.libraryId && totalRoom() >= 60) {
1264
+ // 作用域按词典自己的尺子判(私有关掉时全局词典仍要读),不是 useLibrary。
1265
+ if (lexiconScopeAllowed(effective) && totalRoom() >= 60) {
1230
1266
  try {
1231
1267
  const lexAnchor = buildLexiconAnchor(effective, sessionId, Math.min(LEXICON_ANCHOR_TOKEN_CAP, totalRoom()))
1232
1268
  appendBounded(lexAnchor.text)
1269
+ if (lexAnchor.errors?.length) lexiconError = `degraded lexicon sources: ${lexAnchor.errors.join('; ')}`
1233
1270
  } catch (error) {
1234
1271
  lexiconError = `anchor summary failed: ${error?.message || error}`
1235
1272
  }
@@ -1240,8 +1277,6 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
1240
1277
  const text = ['<memory-media>', truncateToTokens(lines, Math.min(140, Math.floor(totalRoom() / 3))), '图片引用不是视觉证据;attachments 只接受 sha256。', '</memory-media>'].join('\n')
1241
1278
  appendBounded(text)
1242
1279
  }
1243
- // 词典失败收集器:只 warn + lastRecallError,绝不进 errors(那会整批重试)。
1244
- let lexiconError = null
1245
1280
  // B 通道文本源:本批 admissible 的真实用户消息(已过 scope/context 准入)。
1246
1281
  const lexiconUserTexts = admissible.map(item => imageTurn(item).query).filter(Boolean)
1247
1282
  let outcome = 'anchor-only'
@@ -1269,9 +1304,10 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
1269
1304
  // B 通道(§3.3):本批真实用户消息命中词条 → term→meaning,最多 2 条、带冷却。
1270
1305
  // 刻意放在召回错误检查之后——召回错误走整批重试,词典不搭车,也不给一段永远
1271
1306
  // 不会被发出去的文本记 injection/冷却。
1272
- if (settings.autoInject !== 'anchor-only' && effective.useLibrary !== false && effective.libraryId) {
1307
+ if (settings.autoInject !== 'anchor-only' && lexiconScopeAllowed(effective)) {
1273
1308
  try {
1274
1309
  const lexTurn = injectLexiconTurn({ binding: effective, sessionId, userTexts: lexiconUserTexts, tokenBudget: totalRoom() })
1310
+ if (lexTurn.errors?.length) lexiconError = [lexiconError, `degraded lexicon sources: ${lexTurn.errors.join('; ')}`].filter(Boolean).join('; ')
1275
1311
  if (lexTurn.text && estTokens(lexTurn.text) <= totalRoom()) {
1276
1312
  parts.push(lexTurn.text)
1277
1313
  commitLexiconTurn({ libraryId: effective.libraryId, sessionId, hits: lexTurn.hits, selected: lexTurn.selected })
@@ -1279,7 +1315,7 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
1279
1315
  commitLexiconTurn({ libraryId: effective.libraryId, sessionId, hits: lexTurn.hits, selected: [] })
1280
1316
  }
1281
1317
  } catch (error) {
1282
- lexiconError = `turn match failed: ${error?.message || error}`
1318
+ lexiconError = [lexiconError, `turn match failed: ${error?.message || error}`].filter(Boolean).join('; ')
1283
1319
  }
1284
1320
  }
1285
1321
  if (lexiconError) {
@@ -1425,9 +1461,10 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
1425
1461
  }
1426
1462
  // 锚点段追加词典摘要(§3.3 通道 A)。词典异常延迟到 recall 之后的统一
1427
1463
  // fail-open 处理,这里只吞掉占位。
1428
- if (effective.useLibrary !== false && effective.libraryId && totalRoom() >= 60) {
1464
+ if (lexiconScopeAllowed(effective) && totalRoom() >= 60) {
1429
1465
  try {
1430
1466
  const lexAnchor = buildLexiconAnchor(effective, sessionId, Math.min(LEXICON_ANCHOR_TOKEN_CAP, totalRoom()))
1467
+ if (lexAnchor.errors?.length) lexiconError = `degraded lexicon sources: ${lexAnchor.errors.join('; ')}`
1431
1468
  if (lexAnchor.text && estTokens(lexAnchor.text) <= totalRoom()) parts.push(lexAnchor.text)
1432
1469
  } catch (error) {
1433
1470
  lexiconError = `anchor summary failed: ${error?.message || error}`
@@ -1495,13 +1532,14 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
1495
1532
  // B 通道(§3.3):用户消息命中词条 → term→meaning,最多 LEXICON_MAX_PER_TURN 条,
1496
1533
  // 每条过冷却。刻意不受 tooShort 门控——"糖刀"这类两个字的词面命中恰恰是词典
1497
1534
  // 的主场景,minUserChars 挡的是向量召回的成本,不是确定性词面检索。
1498
- // fail-open:matchLexiconHits 抛错(含词典损坏的 typed error)只记 lexiconError。
1535
+ // fail-open:lexiconMatch 抛错(含词典损坏的 typed error)只记 lexiconError。
1499
1536
  // 记账(candidate/injection/冷却)推迟到 snapshot 复检通过之后:回合中途换了
1500
1537
  // 库/上下文时整条消息都会被丢弃,不能给一段没发出去的文本记冷却。
1501
1538
  let lexiconTurnCommit = null
1502
- if (!reinject && settings.autoInject !== 'anchor-only' && effective.useLibrary !== false && effective.libraryId) {
1539
+ if (!reinject && settings.autoInject !== 'anchor-only' && lexiconScopeAllowed(effective)) {
1503
1540
  try {
1504
1541
  const lexTurn = injectLexiconTurn({ binding: effective, sessionId, userTexts: lexiconUserTexts, tokenBudget: totalRoom() })
1542
+ if (lexTurn.errors?.length) lexiconError = [lexiconError, `degraded lexicon sources: ${lexTurn.errors.join('; ')}`].filter(Boolean).join('; ')
1505
1543
  if (lexTurn.text && estTokens(lexTurn.text) <= totalRoom()) {
1506
1544
  parts.push(lexTurn.text)
1507
1545
  lexiconTurnCommit = { hits: lexTurn.hits, selected: lexTurn.selected }
@@ -1509,7 +1547,7 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
1509
1547
  lexiconTurnCommit = { hits: lexTurn.hits, selected: [] }
1510
1548
  }
1511
1549
  } catch (error) {
1512
- lexiconError = `turn match failed: ${error?.message || error}`
1550
+ lexiconError = [lexiconError, `turn match failed: ${error?.message || error}`].filter(Boolean).join('; ')
1513
1551
  }
1514
1552
  }
1515
1553
  if (lexiconError) {
@@ -0,0 +1,143 @@
1
+ // ── 词典读取作用域(§8.13 / §8.15):一个会话读哪几本词典 ──────────────────────────
2
+ // 记忆侧的跨库召回(`crossLibraryRecall`)只管 `privateRecall` / `privateList`,词典
3
+ // 走的是另一条链(锚点摘要、B 通道匹配、模型检索)。两条链必须回答同一个「我看得见
4
+ // 哪些词条」,否则同一个开关下记忆跨库、词典不跨库,用户读到的是半套同步。
5
+ //
6
+ // 三份数据、三种过滤,全部沿用记忆侧已有的尺子:
7
+ // * 当前绑定库:主源,条目**不**按 domain 过滤(保持旧行为,§8.15「当前绑定库始终参与」)。
8
+ // * 其它同领域库:只有 `settings.crossLibraryRecall === true` 才进候选,资格判定直接
9
+ // 复用 memory.js 的 `crossLibrarySources`(同领域、非整理 fork、文件夹没关私有记忆、
10
+ // 未归档),条目再按 `entry.domain` 过滤——旧词条没有 domain 时放行。
11
+ // * 全局词典:与全局记忆同构(`global.json` 的词条版)。不看跨库开关,只受
12
+ // `useGlobal` 天花板约束;条目过滤复用 `appliesToDomain`(universal/personal 恒可见,
13
+ // 其余要等于当前领域)。
14
+ //
15
+ // 写入不在本模块:模型与整理链路只写当前绑定库,全局词典只有用户能从管理面写
16
+ // (§1 硬规则二「主 agent 只读全局」)。
17
+ //
18
+ // 失败口径:主源读失败继续抛(调用方按 §1.10 fail-open 留可观测信号);辅源(同域库、
19
+ // 全局)读失败只降级成 `errors`,一本坏掉的词典不该把整段词典注入带走。
20
+ import {
21
+ getSettings, getLibrary, effectiveScope,
22
+ } from './state.js'
23
+ import { appliesToDomain, crossLibrarySources, domainOf } from './memory.js'
24
+ import {
25
+ GLOBAL_LEXICON_ID, matchLexiconHits, rankLexiconHits, searchLexicon, visibleLexiconTerms,
26
+ } from './lexicon.js'
27
+
28
+ // 同域其它库的条目过滤:与 memory.js domainScopedIndex 同口径——没有 domain 的旧词条
29
+ // 依赖「该库的绑定会话领域已匹配」放行,带 domain 的必须等于当前领域。
30
+ function privateEntryVisible(entry, domain, { primary }) {
31
+ if (primary) return true
32
+ return !entry?.domain || entry.domain === domain
33
+ }
34
+
35
+ // 全局词条的过滤与全局记忆同一条尺(universal / personal / project:<name> / appliesTo)。
36
+ // 没有 domain 的词条按「通用」处理:全局词典由用户在管理面手写,不写领域,
37
+ // 拿全局记忆的 `unknown → 不可见` 直接套上去会把既有词条全隐藏掉。
38
+ function globalEntryVisible(entry, binding) {
39
+ if (!entry?.domain) return true
40
+ return appliesToDomain(entry, binding)
41
+ }
42
+
43
+ /**
44
+ * 这个会话到底读不读词典。私有记忆关掉时全局词典仍然要读(全局记忆同理),
45
+ * 所以不能沿用 `binding.libraryId && useLibrary` 那把旧尺。
46
+ */
47
+ export function lexiconScopeAllowed(binding) {
48
+ return lexiconSources(binding).length > 0
49
+ }
50
+
51
+ /**
52
+ * 这个会话看得见哪几本词典。顺序即优先级:当前库 → 同域其它库 → 全局词典
53
+ * (「私有优先、全局补充」)。`primary` 只给当前绑定库——它是唯一不参与
54
+ * domain 过滤的来源,也是唯一可写的库。
55
+ */
56
+ export function lexiconSources(binding, { settings = getSettings() } = {}) {
57
+ const domain = domainOf(binding)
58
+ const scope = effectiveScope(binding)
59
+ const hasPrivate = Boolean(binding?.libraryId) && scope.useLibrary !== false
60
+ const candidates = !hasPrivate
61
+ ? []
62
+ : (settings.crossLibraryRecall === true
63
+ ? crossLibrarySources(binding, domain)
64
+ : [{ libraryId: binding.libraryId, primary: true }])
65
+ const sources = candidates.map((source) => ({
66
+ libraryId: source.libraryId,
67
+ scope: 'private',
68
+ primary: source.primary === true,
69
+ name: getLibrary(source.libraryId)?.name || source.libraryId,
70
+ }))
71
+ if (scope.useGlobal !== false) {
72
+ sources.push({ libraryId: GLOBAL_LEXICON_ID, scope: 'global', primary: false, name: null })
73
+ }
74
+ return sources
75
+ }
76
+
77
+ /**
78
+ * 逐源读取的公共骨架:按优先级读每本词典 → 作用域过滤 → 打来源标 → 按词面去重。
79
+ * `read(source)` 返回该源的可见行(带 termId),去重保留第一个来源的副本,所以同词面
80
+ * 在私有库与全局词典里各有一份时,私有那份胜出(与记忆侧的冲突口径一致)。
81
+ */
82
+ function eachSource(binding, sources, read) {
83
+ const domain = domainOf(binding)
84
+ const rows = []
85
+ const errors = []
86
+ const seen = new Set()
87
+ // 单源不换路:一本词典内部本来允许同词面跨 scope 共存(findScopeCollision 只在
88
+ // sameFactContext 内判重),去重只有跨源才有意义。
89
+ const dedupe = sources.length > 1
90
+ for (const source of sources) {
91
+ let found = []
92
+ try {
93
+ found = read(source) || []
94
+ } catch (error) {
95
+ if (source.primary) throw error
96
+ errors.push(`${source.libraryId}: ${error?.message || error}`)
97
+ continue
98
+ }
99
+ const keep = source.scope === 'global'
100
+ ? (entry) => globalEntryVisible(entry, binding)
101
+ : (entry) => privateEntryVisible(entry, domain, { primary: source.primary })
102
+ for (const entry of found) {
103
+ if (!keep(entry)) continue
104
+ const surface = entry?.normalizedTerm || entry?.term
105
+ if (dedupe && surface) {
106
+ if (seen.has(surface)) continue
107
+ seen.add(surface)
108
+ }
109
+ rows.push({ ...entry, libraryId: source.libraryId, lexiconScope: source.scope, libraryName: source.name })
110
+ }
111
+ }
112
+ return { rows, errors }
113
+ }
114
+
115
+ /** 锚点摘要的数据面:本会话可见的全部词条(active、context 可见、按源去重)。 */
116
+ export function lexiconVisibleTerms(binding, { includeArchived = false } = {}) {
117
+ const sources = lexiconSources(binding)
118
+ const { rows, errors } = eachSource(binding, sources, (source) => visibleLexiconTerms(source.libraryId, binding?.memoryContext || {}, { includeArchived }))
119
+ return { terms: rows, errors, sources }
120
+ }
121
+
122
+ /**
123
+ * B 通道匹配面:跨源命中用核心的 `rankLexiconHits` 重排——排序尺子只有一把,
124
+ * 在核心里,合并方不自定顺序。
125
+ */
126
+ export function lexiconMatch(binding, text) {
127
+ 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 }
130
+ }
131
+
132
+ /** 模型检索面(memu_lexicon_search):核心已按 matchedBy 排过,合并只保留优先级序。 */
133
+ export function lexiconSearch(binding, query, { includeArchived = false } = {}) {
134
+ const sources = lexiconSources(binding)
135
+ const { rows, errors } = eachSource(binding, sources,
136
+ (source) => searchLexicon({ libraryId: source.libraryId, query, memoryContext: binding?.memoryContext || {} }, { includeArchived }))
137
+ return { items: rows, errors, sources }
138
+ }
139
+
140
+ /** 这一条命中/候选属于哪本词典:计数必须落在词条所在的库,不能全记到当前库。 */
141
+ export function lexiconHitLibraryId(hit, fallback) {
142
+ return hit?.libraryId || fallback || null
143
+ }
package/lib/lexicon.js CHANGED
@@ -92,6 +92,11 @@ function lexiconDir() {
92
92
  return path.join(dataDir(), 'lexicon')
93
93
  }
94
94
 
95
+ // 全局词典与私有词典同格式、同锁、同缓存,只是占一个保留的存储名。
96
+ // 私有库 id 一律是 `lib_<hex>`(state.js libraryIdForScope),所以 `global` 不可能
97
+ // 是某本私有库——`data/lexicon/global.json` 与 `index/global.json`(全局记忆)对齐。
98
+ export const GLOBAL_LEXICON_ID = 'global'
99
+
95
100
  function lexiconFile(libraryId) {
96
101
  // isSafeId 只放行 [A-Za-z0-9._-]{1,128} 且拒绝 . / ..:绝对路径、反斜杠、
97
102
  // ../ 和任意文件名在这里就死掉,不会拼进路径。
@@ -400,11 +405,13 @@ function sensitiveDelta(existing, next) {
400
405
  * 撞上 legacy revision 草稿(revisionOf):非用户不复活(notOwned)。
401
406
  * * 同规范词(term)在 sameFactContext 作用域内唯一;别名撞线仍是
402
407
  * LEXICON_ALIAS_CONFLICT(不静默合并——合并会改写别人的记录)。
408
+ * * `domain` 是写入会话的领域戳(跨库召回判同域用,§8.15):给了就覆盖,没给就
409
+ * 保留既有条目的原值。归档 / 恢复 / 删除这些生命周期动作不碰它。
403
410
  */
404
411
  export function upsertLexiconTerm({
405
412
  libraryId, term, kind = 'term', meaning = '', usage = '', aliases = [], examples = [],
406
413
  context = {}, knownBy = [], visibility = 'shared', sensitivity, confidence, strength,
407
- evidence = [], source = 'user', status,
414
+ evidence = [], source = 'user', status, domain,
408
415
  }) {
409
416
  if (!SOURCES.includes(source)) throw lexiconError('LEXICON_INVALID_SOURCE', `lexicon source must be one of ${SOURCES.join(', ')}`)
410
417
  const isUser = source === 'user'
@@ -455,6 +462,12 @@ export function upsertLexiconTerm({
455
462
  evidence: normalizeEvidence(evidence),
456
463
  }
457
464
 
465
+ // domain 是「哪个领域写得了这条词」的戳,跨库召回靠它判是否同域(§8.15)。
466
+ // 它不是敏感字段(不进 SENSITIVE_FIELDS):非用户来源也能带它落库;未提供时
467
+ // 保留既有条目的原值,绝不清空。
468
+ const normalizedDomain = String(domain ?? '').trim().slice(0, 40)
469
+ const domainStamp = normalizedDomain ? { domain: normalizedDomain } : null
470
+
458
471
  return mutateLexicon(libraryId, (lex) => {
459
472
  const terms = lex.terms
460
473
  // 同 fingerprint 的 model-proposal 再来 → 直接拒绝(§2.3):rejected 留指纹就是
@@ -497,6 +510,7 @@ export function upsertLexiconTerm({
497
510
  }
498
511
  const next = {
499
512
  ...entry, ...fields, updatedAt: now, strength: resolvedStrength ?? (Number(entry.strength) || 0.6),
513
+ ...(domainStamp || {}),
500
514
  }
501
515
  // 敏感字段变化 → typed 拒绝(§2.1:不再生成 pending revision 等人审)。
502
516
  const changedSensitive = sensitiveDelta(entry, next)
@@ -521,6 +535,7 @@ export function upsertLexiconTerm({
521
535
  status: userStatus,
522
536
  normalizedTerm,
523
537
  fingerprint,
538
+ ...(domainStamp || {}),
524
539
  }
525
540
  delete next.revisionOf
526
541
  delete next.previousRevision
@@ -561,6 +576,7 @@ export function upsertLexiconTerm({
561
576
  reviewReason: null,
562
577
  hitCounts: { candidate: 0, injection: 0, query: 0 },
563
578
  lastInjectedAt: null,
579
+ ...(domainStamp || {}),
564
580
  }
565
581
  terms[termId] = entry
566
582
  return { term: withTermId(entry, termId), created: true }
@@ -1051,6 +1067,11 @@ export function lexiconRecordHits(libraryId, termIds, kindOfHit) {
1051
1067
  })
1052
1068
  }
1053
1069
 
1070
+ /** §3.2 稳定排序的对外出口:跨源合并后必须用同一把尺重排,不许调用方自定排序。 */
1071
+ export function rankLexiconHits(hits) {
1072
+ return stableRank(hits)
1073
+ }
1074
+
1054
1075
  /**
1055
1076
  * 锚点摘要(§3.3 通道 A 的数据面):top 8 by strength;敏感词条单列且 ≤2。
1056
1077
  * 行已按优先级排好——inject.js 超 300 token 时从尾部丢,丢的永远是最弱的一条。
@@ -1058,10 +1079,12 @@ export function lexiconRecordHits(libraryId, termIds, kindOfHit) {
1058
1079
  * visibility 与记忆同一套语义(lib/memory.js visibleToSession 的契约:secret 只是
1059
1080
  * "不主动浮出",不改变"被点名时"的可见性):锚点是主动浮出,secret 词条不进摘要;
1060
1081
  * B 通道是用户消息点到了词面(等价于按词点名),secret 词条仍然命中并解释。
1082
+ *
1083
+ * 入参是「已按可见性过滤好的词条」,所以单库摘要与跨源合并摘要共用同一份渲染与
1084
+ * 取舍规则(lexiconAnchorSummary 是本函数在单库上的包装)。
1061
1085
  */
1062
- export function lexiconAnchorSummary(libraryId, memoryContext) {
1063
- const visible = visibleLexiconTerms(libraryId, memoryContext)
1064
- const anchorable = visible.filter(entry => entry.visibility !== 'secret')
1086
+ export function lexiconAnchorLines(entries) {
1087
+ const anchorable = (Array.isArray(entries) ? entries : []).filter(entry => entry.visibility !== 'secret')
1065
1088
  const sensitive = anchorable.filter(entry => entry.sensitivity === 'sensitive')
1066
1089
  const normal = anchorable.filter(entry => entry.sensitivity !== 'sensitive')
1067
1090
  const line = entry => `「${clip(String(entry.term || ''), 40)}」(${entry.kind})${entry.meaning ? ` ${clip(String(entry.meaning), 80)}` : ''}`
@@ -1074,6 +1097,10 @@ export function lexiconAnchorSummary(libraryId, memoryContext) {
1074
1097
  }
1075
1098
  }
1076
1099
 
1100
+ export function lexiconAnchorSummary(libraryId, memoryContext) {
1101
+ return lexiconAnchorLines(visibleLexiconTerms(libraryId, memoryContext))
1102
+ }
1103
+
1077
1104
  /**
1078
1105
  * legacy 生命周期迁移(§2.1):旧版 pending 在当前生命周期不再存在,读到就跑一次收口。
1079
1106
  * * pending 且 !revisionOf(老提案)→ active;敏感词 → archived(敏感词只能由用户