dsh-memu-memory 1.2.8 → 1.2.9

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 (78) hide show
  1. package/CHANGELOG.md +472 -0
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/lib/backup.js +154 -25
  5. package/lib/binding-diagnostics.js +1 -2
  6. package/lib/budget.js +0 -9
  7. package/lib/client.js +221 -128
  8. package/lib/commitment.js +3 -3
  9. package/lib/consolidation-ledger.js +5 -2
  10. package/lib/curator-policy.js +23 -0
  11. package/lib/cycle.js +8 -4
  12. package/lib/embedding-download.js +168 -28
  13. package/lib/embedding-runtime.js +76 -17
  14. package/lib/engine.js +0 -6
  15. package/lib/freshness.js +2 -2
  16. package/lib/graph.js +139 -11
  17. package/lib/index.js +71 -20
  18. package/lib/inject.js +50 -7
  19. package/lib/lexicon.js +61 -16
  20. package/lib/local-vector-service.js +21 -1
  21. package/lib/media.js +49 -12
  22. package/lib/memory.js +662 -116
  23. package/lib/paths.js +0 -7
  24. package/lib/preset-scope.js +6 -1
  25. package/lib/private.js +45 -7
  26. package/lib/prompts.js +0 -7
  27. package/lib/rpc.js +95 -17
  28. package/lib/snippet.js +18 -2
  29. package/lib/state.js +109 -30
  30. package/lib/stats.js +2 -2
  31. package/lib/temporal.js +19 -0
  32. package/lib/text-retrieval.js +120 -44
  33. package/lib/text-similarity.js +205 -24
  34. package/lib/tokenizer-v2.js +0 -24
  35. package/lib/vector-migration.js +15 -0
  36. package/lib/vector-profile.js +81 -8
  37. package/lib/visibility.js +0 -4
  38. package/lib/webui/standalone.css +17 -22
  39. package/lib/webui/standalone.js +27 -9
  40. package/lib/webui.js +4 -4
  41. package/package.json +3 -2
  42. package/scripts/acceptance-local.mjs +2 -2
  43. package/scripts/check-all.mjs +3 -1
  44. package/scripts/check-i18n.mjs +35 -1
  45. package/scripts/migrate-visibility.mjs +3 -3
  46. package/scripts/prune-sessions.mjs +34 -0
  47. package/scripts/prune-vectors.mjs +24 -0
  48. package/tests/appendix-b.test.mjs +5 -4
  49. package/tests/audit-batch3.test.mjs +247 -0
  50. package/tests/audit-regression.test.mjs +2 -2
  51. package/tests/backup.test.mjs +83 -83
  52. package/tests/browser.test.mjs +6 -1
  53. package/tests/client-render.test.mjs +2 -2
  54. package/tests/curator-clusters.test.mjs +18 -0
  55. package/tests/curator-pairing.test.mjs +59 -16
  56. package/tests/dynamic-rrf.test.mjs +22 -19
  57. package/tests/dynamic-threshold.test.mjs +52 -0
  58. package/tests/fact-version.test.mjs +18 -0
  59. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  60. package/tests/graph-cascade.test.mjs +29 -0
  61. package/tests/graph.test.mjs +45 -0
  62. package/tests/inject-conflict.test.mjs +18 -0
  63. package/tests/lexical-bm25.test.mjs +171 -0
  64. package/tests/lexicon-frequency.test.mjs +16 -0
  65. package/tests/lexicon-inject.test.mjs +21 -0
  66. package/tests/lexicon-perf.test.mjs +37 -9
  67. package/tests/lexicon-scope.test.mjs +2 -2
  68. package/tests/lexicon-ui.test.mjs +1 -1
  69. package/tests/managed-memory.test.mjs +19 -0
  70. package/tests/ops-hardening.test.mjs +209 -0
  71. package/tests/package-shipping.test.mjs +4 -0
  72. package/tests/recall-intent.test.mjs +23 -0
  73. package/tests/slot-similarity.test.mjs +153 -0
  74. package/tests/state-gc.test.mjs +34 -0
  75. package/tests/state.test.mjs +2 -2
  76. package/tests/tokenizer-v2.test.mjs +1 -1
  77. package/tests/vector-gc.test.mjs +37 -0
  78. package/tests/webui.test.mjs +27 -0
package/lib/graph.js CHANGED
@@ -12,6 +12,43 @@ import { normalizeEntityName } from './private-links.js'
12
12
 
13
13
  export const LINK_KINDS = ['relation', 'commitment', 'event', 'person', 'conflict']
14
14
  const ENTITY_KINDS = ['person', 'place', 'thing', 'org']
15
+ // Relationship revisions are audit history, not an ever-growing data store. A
16
+ // long-lived role-play can update one relation hundreds of times; keeping all of
17
+ // it made every recall re-parse a multi-MB sidecar. The current state and its
18
+ // evidence stay intact; only the old snapshots are capped.
19
+ const RELATIONSHIP_HISTORY_LIMIT = 50
20
+ // Relationship retention is metadata, not structure: the edge stays, only its
21
+ // confidence in the sidebar/recall can fade, freeze or revive. Parameters follow
22
+ // the local, wall-clock policy used by the audit comparison; no LLM, no text.
23
+ const RELATIONSHIP_HALF_LIFE_HOURS = 24
24
+ const RELATIONSHIP_ACCESS_ALPHA = 0.05
25
+ const RELATIONSHIP_ACCESS_COOLDOWN_MS = 3_600_000
26
+
27
+ function hoursBetween(from, to) {
28
+ const start = Date.parse(String(from || ''))
29
+ const end = Date.parse(String(to || ''))
30
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return 0
31
+ return Math.max(0, (end - start) / 3_600_000)
32
+ }
33
+
34
+ /** Exponential retention at a wall-clock instant; clock rollback never boosts it. */
35
+ export function relationshipRetentionAt(strength, elapsedHours, halfLifeHours = RELATIONSHIP_HALF_LIFE_HOURS) {
36
+ const base = Number(strength)
37
+ const hours = Number(elapsedHours)
38
+ const halfLife = Number(halfLifeHours)
39
+ if (!Number.isFinite(base) || base <= 0) return 0
40
+ if (!Number.isFinite(hours) || hours <= 0 || !Number.isFinite(halfLife) || halfLife <= 0) return Math.min(1, base)
41
+ return Math.min(1, base * Math.pow(0.5, hours / halfLife))
42
+ }
43
+
44
+ /** A recall/access reinforces without jumping to 1. */
45
+ export function accessRelationship(strength, { cooldownMs = RELATIONSHIP_ACCESS_COOLDOWN_MS, lastAccessAt = null, now = Date.now() } = {}) {
46
+ const base = Math.min(1, Math.max(0, Number(strength) || 0))
47
+ const last = Date.parse(String(lastAccessAt || ''))
48
+ if (Number.isFinite(last) && Number(now) - last < cooldownMs) return base
49
+ return Math.min(1, base + (1 - base) * RELATIONSHIP_ACCESS_ALPHA)
50
+ }
51
+
15
52
  function entitiesPath(libraryId) { return path.join(indexDir(), `${libraryId}.entities.json`) }
16
53
 
17
54
  function readEntities(libraryId) {
@@ -73,14 +110,23 @@ export function graphExport(libraryId) {
73
110
  return readEntities(scope.libraryId)
74
111
  }
75
112
 
76
- export function restoreGraphData(libraryId, data, memoryIdMap) {
77
- if (!data?.entities) return
113
+ /**
114
+ * Rebuild the entity/relationship store a memory package came with.
115
+ *
116
+ * Returns the ids of entities this call actually created, tagged with `origin` (the
117
+ * import batch). A revert needs that list: it is the difference between "remove what
118
+ * the package brought" and "remove a person the user already knew".
119
+ */
120
+ export function restoreGraphData(libraryId, data, memoryIdMap, { origin = null } = {}) {
121
+ if (!data?.entities) return { createdEntityIds: [] }
78
122
  const scope = scopeFor({ libraryId })
79
123
  const entityMap = {}
124
+ const createdEntityIds = []
80
125
  for (const [oldId, entity] of Object.entries(data.entities).slice(0, 2000)) {
81
126
  if (!/^ent[-_][a-z0-9_-]+$/i.test(oldId)) continue
82
- const restored = createEntity({ libraryId: scope.libraryId, name: entity.name, kind: entity.kind, aliases: entity.aliases || [] })
127
+ const restored = createEntity({ libraryId: scope.libraryId, name: entity.name, kind: entity.kind, aliases: entity.aliases || [], origin })
83
128
  entityMap[oldId] = restored.id
129
+ if (origin && restored.origin === origin) createdEntityIds.push(restored.id)
84
130
  }
85
131
  const remap = { ...entityMap, ...memoryIdMap }
86
132
  updatePrivateIndex(libraryId, index => {
@@ -106,9 +152,38 @@ export function restoreGraphData(libraryId, data, memoryIdMap) {
106
152
  } catch (error) {
107
153
  warn(`orphan entity prune after graph restore skipped: ${error?.message || error}`)
108
154
  }
155
+ return { createdEntityIds }
156
+ }
157
+
158
+ /**
159
+ * Undo `restoreGraphData` for one import batch: delete exactly the entities that call
160
+ * created. Relationships hang off those entities, so `deleteEntity` cascades them; an
161
+ * entity the user already had is untagged and therefore untouched. A failure is
162
+ * reported per id rather than thrown, because a revert that removed the memories has
163
+ * already done its job and half a graph is still better than an exception the caller
164
+ * cannot act on.
165
+ */
166
+ export function revertGraphData({ libraryId, entityIds = [] }) {
167
+ const removed = []
168
+ const failed = []
169
+ for (const entityId of entityIds) {
170
+ try {
171
+ deleteEntity({ libraryId, entityId, force: true })
172
+ removed.push(entityId)
173
+ } catch (error) {
174
+ failed.push({ entityId, error: String(error?.message || error) })
175
+ }
176
+ }
177
+ return { removed, failed }
109
178
  }
110
179
 
111
- export function createEntity({ exec, libraryId, name, kind = 'person', aliases = [] }) {
180
+ /**
181
+ * `origin` tags an entity that somebody else created on this user's behalf — an
182
+ * imported memory package, say. It exists so the import can be undone: an entity
183
+ * that already existed before the import is returned as-is and stays untagged, so a
184
+ * revert can never delete a person the user had added themselves.
185
+ */
186
+ export function createEntity({ exec, libraryId, name, kind = 'person', aliases = [], origin = null }) {
112
187
  const scope = scopeFor({ exec, libraryId })
113
188
  if (!ENTITY_KINDS.includes(kind)) throw new Error(`entity kind must be ${ENTITY_KINDS.join(', ')}`)
114
189
  const clean = String(name || '').trim()
@@ -119,7 +194,7 @@ export function createEntity({ exec, libraryId, name, kind = 'person', aliases =
119
194
  const existing = Object.values(store.entities).find(entity => entity.name === clean && entity.kind === kind)
120
195
  if (existing) return existing
121
196
  const id = newMemoryId('ent')
122
- const entity = { id, name: clean, kind, aliases: normalizeAliases(aliases), createdAt: stamp(), updatedAt: stamp() }
197
+ const entity = { id, name: clean, kind, aliases: normalizeAliases(aliases), createdAt: stamp(), updatedAt: stamp(), ...(origin ? { origin: String(origin) } : {}) }
123
198
  store.entities[id] = entity
124
199
  writeJson(file, store)
125
200
  return entity
@@ -240,8 +315,18 @@ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
240
315
  for (const entry of Object.values(index.entries || {})) {
241
316
  for (const link of entry.links || []) if (link.to === entityId) inbound += 1
242
317
  }
318
+ // 关系快照的 key 是 JSON.stringify([fromId, toId])。旧数据、备份恢复或手写
319
+ // 导入都可能带非 JSON key——这里必须和 mergeEntities 同口径地跳过损坏 key,
320
+ // 否则一个坏 key 会让整次删除抛 SyntaxError(RPC 直接失败),而它本来只是
321
+ // 一条读不懂的历史。跳过 = 保留:损坏 key 不参与删除,也就不会被静默丢掉。
243
322
  const relationshipKeys = Object.keys(store.relationships || {})
244
- .filter(key => { const [from, to] = JSON.parse(key); return from === entityId || to === entityId })
323
+ .filter(key => {
324
+ let endpoints
325
+ try { endpoints = JSON.parse(key) } catch { return false }
326
+ if (!Array.isArray(endpoints) || endpoints.length !== 2) return false
327
+ const [from, to] = endpoints
328
+ return from === entityId || to === entityId
329
+ })
245
330
  if ((inbound || relationshipKeys.length) && !force) {
246
331
  const parts = []
247
332
  if (inbound) parts.push(`${inbound} link(s) point at it`)
@@ -612,7 +697,21 @@ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 2
612
697
  }
613
698
 
614
699
  export function recallRelations(libraryId, index, id, sessionId) {
615
- const entities = readEntities(libraryId).entities
700
+ const store = readEntities(libraryId)
701
+ const entities = store.entities
702
+ // 关系衰减是写入侧算的(updateRelationship 每次更新都把 retention_strength 折一次),
703
+ // 但读取侧从来没用过它——一条半年没人碰过的关系,和一条昨天刚更新的关系,扩展
704
+ // 时的分量完全一样。这里把「这个实体背后最强的活跃关系还剩多少」带出去,让调用方
705
+ // 能按它排序和过滤。记忆型目标不归关系衰减管,retention 留 null。
706
+ const retentionOf = new Map()
707
+ for (const relationship of Object.values(store.relationships || {})) {
708
+ const value = Number.isFinite(Number(relationship?.retention_strength)) ? Number(relationship.retention_strength) : 1
709
+ for (const entityId of [relationship?.fromId, relationship?.toId]) {
710
+ if (!entityId) continue
711
+ const current = retentionOf.get(entityId)
712
+ if (current === undefined || value > current) retentionOf.set(entityId, value)
713
+ }
714
+ }
616
715
  const out = []
617
716
  for (const [from, entry] of Object.entries(index.entries || {})) {
618
717
  if (!isMemoryEligible(entry, { automatic: true }) || !visibleToSession(entry, sessionId)) continue
@@ -626,10 +725,21 @@ export function recallRelations(libraryId, index, id, sessionId) {
626
725
  // the two views disagreed. Both now report the edge and mark it `missing`;
627
726
  // the caller filters if it wants the old silence back.
628
727
  const missing = !target && !entities[to]
629
- out.push({ id: to, title: target?.title || entities[to]?.name || '[deleted]', kind: link.kind, note: String(link.note || '').slice(0, 80), confidence: link.confidence ?? 0.7, missing })
728
+ out.push({
729
+ id: to,
730
+ title: target?.title || entities[to]?.name || '[deleted]',
731
+ kind: link.kind,
732
+ note: String(link.note || '').slice(0, 80),
733
+ confidence: link.confidence ?? 0.7,
734
+ missing,
735
+ retention: target ? null : (retentionOf.has(to) ? retentionOf.get(to) : 1),
736
+ })
630
737
  }
631
738
  }
632
- return out.sort((a, b) => b.confidence - a.confidence).slice(0, 2)
739
+ // Confidence is the write-time claim; retention is how much of it survived. An
740
+ // entity link pays both, a memory link only pays confidence.
741
+ const weightOf = (link) => (link.retention == null ? 1 : link.retention) * (Number(link.confidence) || 0)
742
+ return out.sort((a, b) => weightOf(b) - weightOf(a) || b.confidence - a.confidence).slice(0, 2)
633
743
  }
634
744
 
635
745
  export function getRelationship({ exec, libraryId, fromId, toId }) {
@@ -667,11 +777,29 @@ export function updateRelationship({ exec, libraryId, fromId, toId, state, evide
667
777
  if (!store.entities[fromId] || !store.entities[toId]) throw new Error('relationship endpoints must be existing entities')
668
778
  const key = JSON.stringify([fromId, toId])
669
779
  const previous = store.relationships[key]
780
+ const at = stamp()
670
781
  const history = [...(previous?.history || [])]
671
- if (previous) history.push({ state: previous.state, evidenceIds: previous.evidenceIds, reason: previous.reason, validFrom: previous.validFrom, validTo: stamp() })
782
+ if (previous) {
783
+ history.push({
784
+ state: previous.state, evidenceIds: previous.evidenceIds, reason: previous.reason,
785
+ validFrom: previous.validFrom, validTo: at,
786
+ retention_strength: previous.retention_strength ?? 1,
787
+ })
788
+ }
789
+ if (history.length > RELATIONSHIP_HISTORY_LIMIT) history.splice(0, history.length - RELATIONSHIP_HISTORY_LIMIT)
790
+ const decayed = relationshipRetentionAt(
791
+ previous?.retention_strength ?? 1,
792
+ hoursBetween(previous?.last_access_at || previous?.validFrom, at),
793
+ )
794
+ const retention = previous
795
+ ? accessRelationship(decayed, { lastAccessAt: previous.last_access_at, now: Date.parse(at) })
796
+ : 1
672
797
  const relationship = {
673
798
  fromId, toId, state: snapshot, evidenceIds: [...new Set(evidenceIds)],
674
- reason: String(reason).trim().slice(0, 1000), validFrom: stamp(), revision: (previous?.revision || 0) + 1,
799
+ reason: String(reason).trim().slice(0, 1000), validFrom: previous?.validFrom || at, revision: (previous?.revision || 0) + 1,
800
+ retention_strength: retention,
801
+ last_access_at: at,
802
+ next_review_at: new Date(Date.parse(at) + RELATIONSHIP_HALF_LIFE_HOURS * 3_600_000).toISOString(),
675
803
  history,
676
804
  }
677
805
  store.relationships[key] = relationship
package/lib/index.js CHANGED
@@ -7,8 +7,9 @@ import { syncPromptDefaults } from './prompts.js'
7
7
  import { ensureEngine, engineStatus, ENGINE_VERSION } from './engine.js'
8
8
  import { getSettings, getMemoryBackend, backupDatabases, flushState, listLibraries } from './state.js'
9
9
  import { pruneOrphanEntitiesAll } from './graph.js'
10
+ import { pruneDeletedStores } from './memory.js'
10
11
  import { closeEmbeddingWorkers } from './local-embedding-manager.js'
11
- import { bootstrapLocalVector } from './local-vector-service.js'
12
+ import { bootstrapLocalVector, closeLocalVectorService } from './local-vector-service.js'
12
13
  import { closeMemuResident, prewarmMemuResident } from './memu.js'
13
14
  import { vectorStatus } from './vector-profile.js'
14
15
  import { setWarnSink } from './paths.js'
@@ -20,17 +21,49 @@ export const inject = ['tools', 'timer']
20
21
 
21
22
  const applied = new WeakSet()
22
23
 
24
+ /**
25
+ * Defer startup work without leaking it past unload.
26
+ *
27
+ * Activation must not block — an engine install can take minutes and the vector
28
+ * bootstrap touches a native runtime — so all three sweeps below run on a delay. A
29
+ * bare `setTimeout` is not enough: `unref()` only stops the timer from keeping the
30
+ * process alive, it does not cancel the callback, so a plugin unloaded inside the
31
+ * window still ran engine installs and vector bootstraps against a disposed fiber.
32
+ * The host's own guidance is the cordis timer service, which it disposes with the
33
+ * plugin; the raw fallback is unref'd *and* returns a canceller the caller registers
34
+ * through `ctx.effect`.
35
+ */
36
+ function scheduleStartup(ctx, delay, label, run) {
37
+ const guarded = () => {
38
+ try { run() } catch (error) {
39
+ try { ctx.logger?.warn?.(`dsh-memu-memory: ${label} failed: ${error?.message || error}`) } catch {}
40
+ }
41
+ }
42
+ // Property access on an uninjected service throws in cordis, so the probe is guarded.
43
+ let scoped = null
44
+ try { scoped = typeof ctx.timeout === 'function' ? ctx : null } catch { scoped = null }
45
+ if (scoped) {
46
+ try {
47
+ scoped.timeout(guarded, delay)
48
+ return () => {}
49
+ } catch {}
50
+ }
51
+ const timer = setTimeout(guarded, delay)
52
+ timer.unref?.()
53
+ return () => { try { clearTimeout(timer) } catch {} }
54
+ }
55
+
23
56
  // 首用引导(§14.13):本地向量模式且已有(或待切换)受管模型时,启动后把受管运行时复用起来、
24
57
  // 拉起 loopback worker 并健康检查 /v1/embeddings。这里不下载:没有确认的联网动作留给她在
25
58
  // 设置页点按钮,启动路径只做 reuse + 健康检查。失败只 warn(召回照旧退词法)。
26
59
  function startLocalVectorBootstrap(ctx) {
27
60
  try {
28
- if (getMemoryBackend() !== 'api') return
29
- if (getSettings().vectorSource !== 'local') return
61
+ if (getMemoryBackend() !== 'api') return null
62
+ if (getSettings().vectorSource !== 'local') return null
30
63
  const state = vectorStatus()
31
64
  const catalogId = state?.active?.profile?.catalogId || state?.requested?.catalogId || null
32
- if (!catalogId) return
33
- const timer = setTimeout(() => {
65
+ if (!catalogId) return null
66
+ return scheduleStartup(ctx, 2500, 'local embedding bootstrap', () => {
34
67
  // The resident interpreter only pays the MemU import once; it does not wait
35
68
  // for the embedding worker, so warming it in parallel with the runtime
36
69
  // bootstrap is safe and keeps the first recall from paying the cold start.
@@ -40,10 +73,10 @@ function startLocalVectorBootstrap(ctx) {
40
73
  }).catch((error) => {
41
74
  try { ctx.logger?.warn?.(`dsh-memu-memory: local embedding bootstrap skipped: ${error?.message || error}`) } catch {}
42
75
  })
43
- }, 2500)
44
- timer.unref?.()
76
+ })
45
77
  } catch (error) {
46
78
  try { ctx.logger?.warn?.(`dsh-memu-memory: local embedding bootstrap skipped: ${error?.message || error}`) } catch {}
79
+ return null
47
80
  }
48
81
  }
49
82
 
@@ -52,19 +85,19 @@ function startEngineBootstrap(ctx) {
52
85
  const settings = getSettings()
53
86
  // Local agent mode reads and writes the JSON index directly; installing a
54
87
  // Python/MemU runtime would only burn time and disk for nothing.
55
- if (getMemoryBackend() === 'agent') return
56
- if (settings.autoInstallEngine === false) return
88
+ if (getMemoryBackend() === 'agent') return null
89
+ if (settings.autoInstallEngine === false) return null
57
90
  const status = engineStatus()
58
- if (status.status === 'ready' && status.current?.version === ENGINE_VERSION) return
59
- if (status.status === 'installing') return
60
- const timer = setTimeout(() => {
91
+ if (status.status === 'ready' && status.current?.version === ENGINE_VERSION) return null
92
+ if (status.status === 'installing') return null
93
+ return scheduleStartup(ctx, 1500, 'engine bootstrap', () => {
61
94
  void ensureEngine({ beforeSwitch: backupDatabases }).catch((error) => {
62
95
  try { ctx.logger?.warn?.(`dsh-memu-memory: engine bootstrap failed: ${error?.message || error}`) } catch {}
63
96
  })
64
- }, 1500)
65
- timer.unref?.()
97
+ })
66
98
  } catch (error) {
67
99
  try { ctx.logger?.warn?.(`dsh-memu-memory: engine bootstrap skipped: ${error?.message || error}`) } catch {}
100
+ return null
68
101
  }
69
102
  }
70
103
 
@@ -78,8 +111,12 @@ function startEngineBootstrap(ctx) {
78
111
  // 单库失败只收集不抛出,整段失败只 warn —— 加载绝不能被一次清理绊倒。
79
112
  function startOrphanEntitySweep(ctx) {
80
113
  try {
81
- const timer = setTimeout(() => {
114
+ return scheduleStartup(ctx, 4000, 'orphan entity sweep', () => {
82
115
  try {
116
+ const deleted = pruneDeletedStores()
117
+ for (const failure of deleted.failed) {
118
+ try { ctx.logger?.warn?.(`dsh-memu-memory: deleted stash sweep skipped ${failure.libraryId}: ${failure.error}`) } catch {}
119
+ }
83
120
  const result = pruneOrphanEntitiesAll()
84
121
  for (const failure of result.failed) {
85
122
  try { ctx.logger?.warn?.(`dsh-memu-memory: orphan entity sweep skipped ${failure.libraryId}: ${failure.error}`) } catch {}
@@ -90,10 +127,10 @@ function startOrphanEntitySweep(ctx) {
90
127
  } catch (error) {
91
128
  try { ctx.logger?.warn?.(`dsh-memu-memory: orphan entity sweep failed: ${error?.message || error}`) } catch {}
92
129
  }
93
- }, 4000)
94
- timer.unref?.()
130
+ })
95
131
  } catch (error) {
96
132
  try { ctx.logger?.warn?.(`dsh-memu-memory: orphan entity sweep skipped: ${error?.message || error}`) } catch {}
133
+ return null
97
134
  }
98
135
  }
99
136
 
@@ -154,10 +191,20 @@ export function apply(ctx, config) {
154
191
 
155
192
  if (!inPreset) {
156
193
  registerRpc(ctx)
157
- startEngineBootstrap(ctx)
158
- startLocalVectorBootstrap(ctx)
159
194
  // 进程级清理:preset 挂载共享同一个数据目录,只由拥有全局表面的实例扫一次。
160
- startOrphanEntitySweep(ctx)
195
+ // Each starter returns either a canceller (raw timer fallback) or a no-op (the
196
+ // cordis timer service already cancels with the fiber); unload inside the delay
197
+ // window must not run any of them against a disposed context.
198
+ const startupCancels = [
199
+ startEngineBootstrap(ctx),
200
+ startLocalVectorBootstrap(ctx),
201
+ startOrphanEntitySweep(ctx),
202
+ ].filter(Boolean)
203
+ if (typeof ctx.effect === 'function') {
204
+ ctx.effect(() => () => {
205
+ for (const cancel of startupCancels) { try { cancel() } catch {} }
206
+ }, 'dsh-memu-memory: startup timers')
207
+ }
161
208
  }
162
209
 
163
210
  // The embedding worker is a process-global singleton, so it outlives any single
@@ -170,6 +217,10 @@ export function apply(ctx, config) {
170
217
  // The resident interpreter is also process-global; leaving it behind would keep
171
218
  // a Python process (and its sqlite handles) alive after this plugin unloads.
172
219
  ctx.effect(() => () => { closeMemuResident() }, 'dsh-memu-memory: memu resident engine')
220
+ // The download/install service owned a loopback port and an in-flight job queue
221
+ // with no close call site at all: after an unload it kept downloading, and the
222
+ // BUSY state then refused a restart from the next instance.
223
+ ctx.effect(() => () => { try { closeLocalVectorService() } catch (error) { try { ctx.logger?.warn?.(`dsh-memu-memory: closing the local vector service failed: ${error?.message || error}`) } catch {} } }, 'dsh-memu-memory: local vector service')
173
224
  }
174
225
 
175
226
  const disposeCycle = inPreset ? null : registerCycle(ctx, {
package/lib/inject.js CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  import { commitmentDueDate, isOpenThread } from './commitment.js'
18
18
  import { record, clipQuery } from './activity-log.js'
19
19
  import { readMood } from './mood.js'
20
+ import { jaccard } from './text-similarity.js'
20
21
  import { loadPromptForDomain } from './prompts.js'
21
22
  import { estTokens, packToBudget, truncateToTokens } from './budget.js'
22
23
  import { freshnessSignals } from './freshness.js'
@@ -58,6 +59,32 @@ function cueId() {
58
59
 
59
60
  // The eight fixed lines are the fallback, not the source: a library with something to
60
61
  // echo should never be served a generic sentence.
62
+ // Sessions already told about an empty recall. One line per session, not per turn: a
63
+ // new library is empty by definition, and repeating the note every turn would train
64
+ // the reader to ignore it — the same failure as saying nothing.
65
+ const emptyRecallNoted = new Set()
66
+
67
+ function noteEmptyRecall(sessionId, { log = null, turn = null } = {}) {
68
+ const key = String(sessionId || 'unknown')
69
+ if (emptyRecallNoted.has(key)) return
70
+ emptyRecallNoted.add(key)
71
+ const why = 'no candidate matched and nothing failed: the store may be empty, the '
72
+ + 'message may be below minUserChars, or every hit may have been filtered by scope/disclosure'
73
+ try { log?.(`recall empty (session ${key}, turn ${turn ?? '?'}): ${why}`) } catch {}
74
+ try { warn(`inject: empty recall for session ${key} — ${why}`) } catch {}
75
+ try {
76
+ record({
77
+ kind: 'recall',
78
+ scope: 'private',
79
+ sessionId: sessionId || null,
80
+ ok: true,
81
+ message: '召回为空:0 候选且无异常',
82
+ detail: { turn: turn ?? null, reason: 'no-match' },
83
+ refs: [],
84
+ })
85
+ } catch {}
86
+ }
87
+
61
88
  export function makeCue() {
62
89
  const text = CUE_TEXTS[crypto.randomInt(0, CUE_TEXTS.length)]
63
90
  return { id: cueId(), text, sourceId: null, recallQuery: null }
@@ -850,12 +877,9 @@ function bigrams(text) {
850
877
  return grams
851
878
  }
852
879
 
853
- function jaccard(a, b) {
854
- if (a.size === 0 || b.size === 0) return 0
855
- let shared = 0
856
- for (const gram of a) if (b.has(gram)) shared += 1
857
- return shared / (a.size + b.size - shared)
858
- }
880
+ // 话题漂移的 bigram 集本文件自己造(要容忍 {text} 形状、只去空白、不做大小写与
881
+ // 标点归一,这是有意的:它比的是「最近的问法」而不是「同一个事实」),但 Jaccard
882
+ // 这个公式全仓只该有一份,所以从 text-similarity.js 取。
859
883
 
860
884
  function topicShifted(binding, query, settings) {
861
885
  const history = Array.isArray(binding?.recentQueries) ? binding.recentQueries : []
@@ -1631,8 +1655,18 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
1631
1655
  if (recall.errors.length > 0) {
1632
1656
  setRecallError(sessionId, recall.errors.join('; '))
1633
1657
  try { log?.(`recall degraded: ${recall.errors.join('; ')}`) } catch {}
1634
- } else {
1658
+ } else if ((recall.candidateCount || 0) > 0) {
1659
+ // Nothing failed and something was found. This is the only state that proves a
1660
+ // previous failure is over, so it is the only state allowed to clear the signal.
1661
+ emptyRecallNoted.delete(String(sessionId || ''))
1635
1662
  setRecallError(sessionId, null)
1663
+ } else {
1664
+ // Empty and error-free. Clearing the signal here erased the evidence of whatever
1665
+ // went wrong the last time (a failed inbound write, a degraded engine, a scope
1666
+ // that had just been narrowed) and left the sidebar with nothing at all — the
1667
+ // most common shape of "memory is not working" with no trace to follow. Keep the
1668
+ // previous signal, and say once per session why this turn produced nothing.
1669
+ noteEmptyRecall(sessionId, { log, turn })
1636
1670
  }
1637
1671
  }
1638
1672
 
@@ -1694,6 +1728,15 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
1694
1728
  const rewritten = [...decision.messages]
1695
1729
  const index = rewritten.indexOf(lastUser)
1696
1730
  if (index < 0) return decision
1731
+ // 位置口径(审计 A-16):记忆块**插在这一步最后一条真实用户消息之前**,
1732
+ // 因为它是「回应用户之前先想起来的上下文」,放在用户消息之后会被读成回应的
1733
+ // 一部分。guide / inbound 两处在末尾追加,那是另外两种东西(常驻说明、外来
1734
+ // 消息),不是同一类内容,所以这里不强行统一。
1735
+ //
1736
+ // 关于缓存:v1 审计曾说前插会破坏宿主 KV cache——已证伪。agent/pre-step 是
1737
+ // waterfall,`payload.messages` 是「这一步从收件箱里新取出的一批」,已缓存的
1738
+ // 历史前缀逐字未动;createUserMessage 也是新建一条冻结消息,不改旧消息。前插
1739
+ // 只改变这一批内部的顺序。
1697
1740
  rewritten.splice(index, 0, message)
1698
1741
  markInjected(sessionId, ids, memoryClock)
1699
1742
  // An overdue dated promise is repeated on its own interval; that clock only starts
package/lib/lexicon.js CHANGED
@@ -689,9 +689,20 @@ function clamp01(value) {
689
689
  }
690
690
 
691
691
  /**
692
- * Wilson 下界(§6.3 包 C 的有界频率先验):hitCounts 三计数(candidate/injection/
693
- * query)→ 95% Wilson 置信下界。n=candidate 是分母(候选池大小),成功 =
694
- * injection+query(真的注入了 / 被显式查过),恒 ≤ n。设计约束:
692
+ * Wilson 下界(§6.3 包 C 的有界频率先验,A-13:同源分子/分母)。
693
+ *
694
+ * 分母 n 优先取 priorAttempts——「该词条被召回的总尝试次数」这一同源计数;
695
+ * 成功数 success = injection + query,即「被召回后确实被注入/查询命中」的
696
+ * 同源事件。旧实现把 candidate(候选池大小,另一条计数通道)当分母,再把
697
+ * injection+query clamp 到它,两个不相干的计数被硬凑成一个比例,口径不严谨
698
+ * (虽然有界、不会 runaway)。
699
+ *
700
+ * 兼容近似:当前写入路径还没有记录 priorAttempts,缺失(或非正数)时退回
701
+ * candidate 作为分母,并在此文档化这一假设——candidate 是「进过匹配结果」的
702
+ * 次数,是现有数据里与「被召回」最接近的代理;success 仍被 min(n, ...) 钳住,
703
+ * 公式保持有界。写入侧按同源事件补上 priorAttempts 后,先验自动切换到严格口径。
704
+ *
705
+ * 设计约束不变:
695
706
  * * n=0 → 0(从未候选过的词条没有任何频率证据,因子取下限 0.85)。
696
707
  * * 1/1 的下界 ≈ 0.207,因子最多 ~3% 差距——一条偶发命中压不过长期稳定使用的词。
697
708
  * * 100/120 的下界明显更高——长期被真正使用的词条温和提升。
@@ -699,7 +710,8 @@ function clamp01(value) {
699
710
  * (0.85 + 0.15 * lb) 后 effective 因子恒在 [0.85,1.00],不 runaway。
700
711
  */
701
712
  export function usageLowerBound(counts) {
702
- const n = Math.max(0, Math.floor(Number(counts?.candidate) || 0))
713
+ const attempts = Math.max(0, Math.floor(Number(counts?.priorAttempts) || 0))
714
+ const n = attempts > 0 ? attempts : Math.max(0, Math.floor(Number(counts?.candidate) || 0))
703
715
  if (n === 0) return 0
704
716
  const success = Math.min(n, Math.max(0, (Number(counts?.injection) || 0) + (Number(counts?.query) || 0)))
705
717
  const p = success / n
@@ -761,8 +773,17 @@ function scopeSpecificity(context) {
761
773
  return ['channelId', 'speakerId', 'characterId', 'worldId', 'branchId'].filter(key => context[key]).length
762
774
  }
763
775
 
764
- /** 文本侧:穷举 BUCKET_WIDTH 字符窗口,按出现顺序去重,上限 MAX_BUCKETS。 */
765
- function textBuckets(normalizedText, maxBuckets = LEXICON_MAX_BUCKETS) {
776
+ /**
777
+ * 文本侧窗口(A-8):穷举 BUCKET_WIDTH 字符窗口并去重,按「该窗口在前缀桶里
778
+ * 命中的词条数」降序取 top-N。旧实现按出现顺序取前 16 个窗口:长文本里真正
779
+ * 含错字变体的窗口(例如 40 字闲聊末尾的「糖刀文雪」)常常落在第 17 个之后,
780
+ * 模糊层连候选都收不到——召不回不是因为 Dice 不够,而是窗口根本没被展开。
781
+ * 命中数相同的窗口保持出现顺序(sort 稳定),输出可复现。
782
+ *
783
+ * 命中数取索引里该桶的全量大小(含 archived/pending):窗口排序只是「哪些窗口
784
+ * 值得展开」的成本决策,可见性仍由逐候选的 isVisible 复核,不会被这里放宽。
785
+ */
786
+ function textBuckets(normalizedText, index, maxBuckets = LEXICON_MAX_BUCKETS) {
766
787
  const keys = []
767
788
  const seen = new Set()
768
789
  for (let i = 0; i + BUCKET_WIDTH <= normalizedText.length; i++) {
@@ -770,9 +791,12 @@ function textBuckets(normalizedText, maxBuckets = LEXICON_MAX_BUCKETS) {
770
791
  if (seen.has(key)) continue
771
792
  seen.add(key)
772
793
  keys.push(key)
773
- if (keys.length >= maxBuckets) break
774
794
  }
775
795
  return keys
796
+ .map((key, order) => ({ key, order, hits: index?.prefixBuckets?.get(key)?.size || 0 }))
797
+ .sort((a, b) => b.hits - a.hits || a.order - b.order)
798
+ .slice(0, maxBuckets)
799
+ .map((item) => item.key)
776
800
  }
777
801
 
778
802
  /**
@@ -836,7 +860,9 @@ function hitOf(entry, termId, kindOfHit, score) {
836
860
  * 全部走 revision-keyed 索引(§10 P1):等值 O(1) 查 Map;包含层用「词面 ⊆ 文本
837
861
  * ⇒ 词面前缀 = 文本某个 2 字窗口」的性质从前缀桶收候选(窗口穷举不设 16 上限——
838
862
  * 16 上限只属于 dice 候选,精确层语义从来没有窗口上限);dice 兜底仍按桶扫且
839
- * C ≤ 64 不变(§6)。可见性(status + contextVisible)在收候选时逐个复核。
863
+ * C ≤ 64 不变(§6),但窗口按命中词条数排序、候选按与 query 的共享 gram 数
864
+ * 排序(A-8:候选准入看相关性,不看 strength)。可见性(status +
865
+ * contextVisible)在收候选时逐个复核。
840
866
  */
841
867
  export function matchLexiconHits(libraryId, userText, memoryContext) {
842
868
  const normalizedText = normalizeLexeme(userText)
@@ -878,17 +904,36 @@ export function matchLexiconHits(libraryId, userText, memoryContext) {
878
904
  hits.push(hitOf(entry, termId, matched.via === 'term' ? 'exact-term' : 'exact-alias', 1))
879
905
  }
880
906
  }
881
- // dice 候选:仍按 textBuckets 的 16 窗口上限收(§4.2 的 C≤64 语义不变)。
882
- const candidateIds = []
883
- for (const key of textBuckets(normalizedText)) {
907
+ // dice 候选:窗口数仍以 LEXICON_MAX_BUCKETS 封顶(§4.2 的 C≤64 语义不变),
908
+ // 但窗口与候选都按「与 query 的相关性」排:窗口按命中词条数降序(见
909
+ // textBuckets),候选按与 query 共享的 gram 数降序。旧实现把候选按
910
+ // strength×confidence 取前 64——候选池被一批不一定相关的强词条占满,真正
911
+ // 只差一个字的弱词条反而进不了 diceFallback。strength 与 termId 只做确定性
912
+ // tiebreak(与 diceFallback 的末位排序同口径)。
913
+ const candidateIds = new Set()
914
+ for (const key of textBuckets(normalizedText, index)) {
884
915
  for (const termId of index.prefixBuckets.get(key) || []) {
885
- if (exactIds.has(termId) || candidateIds.includes(termId) || !isVisible(termId)) continue
886
- candidateIds.push(termId)
916
+ if (exactIds.has(termId) || !isVisible(termId)) continue
917
+ candidateIds.add(termId)
887
918
  }
888
919
  }
889
- const candidates = candidateIds
890
- .map(termId => hitOf(data.terms[termId], termId, 'dice', 0))
891
- .sort((a, b) => (Number(b.strength) || 0) * (Number(b.confidence) || 0) - (Number(a.strength) || 0) * (Number(a.confidence) || 0))
920
+ const textGrams = bigrams(normalizedText)
921
+ const sharedGramCount = termId => {
922
+ let best = 0
923
+ for (const { surface } of index.surfacesByTerm.get(termId) || []) {
924
+ let shared = 0
925
+ for (const gram of bigrams(surface)) if (textGrams.has(gram)) shared += 1
926
+ if (shared > best) best = shared
927
+ }
928
+ return best
929
+ }
930
+ const weightOf = termId => (Number(data.terms[termId].strength) || 0) * (Number(data.terms[termId].confidence) || 0)
931
+ const candidates = [...candidateIds]
932
+ .map(termId => ({ termId, shared: sharedGramCount(termId) }))
933
+ .sort((a, b) => b.shared - a.shared
934
+ || weightOf(b.termId) - weightOf(a.termId)
935
+ || String(a.termId).localeCompare(String(b.termId)))
936
+ .map(({ termId }) => hitOf(data.terms[termId], termId, 'dice', 0))
892
937
  const fuzzy = diceFallback(normalizedText, candidates)
893
938
  // stableRank 的末位 tie-break 是唯一 termId,命中顺序不影响最终排序。
894
939
  return stableRank([...hits, ...fuzzy])
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import { downloadsDir, warn } from './paths.js'
4
- import { listLibraries, loadPrivateIndex, loadGlobalIndex } from './state.js'
4
+ import { listLibraries, loadPrivateIndex, loadGlobalIndex, saveGlobalIndex, updatePrivateIndex } from './state.js'
5
5
  import { commit as memuCommit, listFiles as memuListFiles, forget as memuForget } from './memu.js'
6
6
  import { getEmbeddingCatalog, prefixesRequireRole, resolveEmbeddingSources } from './embedding-catalog.js'
7
7
  import { createEmbeddingDownloadManager } from './embedding-download.js'
@@ -217,6 +217,26 @@ function migratorFor() {
217
217
  assertProfileVerified(profile)
218
218
  return memuListFiles({ db, vectorProfile: profile, route: 'managed-local' })
219
219
  },
220
+ clearVectorPending: ({ libraryId, ids }) => {
221
+ const wanted = new Set((Array.isArray(ids) ? ids : []).map(String).filter(Boolean))
222
+ if (!wanted.size) return
223
+ const clear = (index) => {
224
+ let touched = 0
225
+ for (const id of wanted) {
226
+ const entry = index.entries?.[id]
227
+ if (entry && entry.vectorPending) { delete entry.vectorPending; touched += 1 }
228
+ }
229
+ return touched
230
+ }
231
+ // The global layer is its own index file; a private library has one each. Nothing
232
+ // crosses between them, so the scope decides which write path to take.
233
+ if (libraryId == null) {
234
+ const index = loadGlobalIndex()
235
+ if (clear(index)) saveGlobalIndex(index)
236
+ return
237
+ }
238
+ updatePrivateIndex(libraryId, (index) => { clear(index) })
239
+ },
220
240
  })
221
241
  }
222
242