dsh-memu-memory 1.2.8 → 1.3.0

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 (90) hide show
  1. package/CHANGELOG.md +494 -0
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/docs/memory-semantics.md +3 -2
  5. package/lib/backup.js +154 -25
  6. package/lib/binding-diagnostics.js +2 -3
  7. package/lib/budget.js +0 -9
  8. package/lib/client.js +221 -128
  9. package/lib/commitment.js +3 -3
  10. package/lib/consolidation-ledger.js +46 -3
  11. package/lib/consolidation-receipt.js +41 -16
  12. package/lib/consolidation-worker.js +34 -10
  13. package/lib/curator-policy.js +23 -0
  14. package/lib/cycle.js +8 -4
  15. package/lib/embedding-download.js +168 -28
  16. package/lib/embedding-runtime.js +76 -17
  17. package/lib/engine.js +0 -6
  18. package/lib/freshness.js +2 -2
  19. package/lib/graph.js +139 -11
  20. package/lib/index.js +71 -20
  21. package/lib/inject.js +50 -7
  22. package/lib/lexicon.js +61 -16
  23. package/lib/local-vector-service.js +21 -1
  24. package/lib/media.js +49 -12
  25. package/lib/memory.js +662 -116
  26. package/lib/paths.js +0 -7
  27. package/lib/preset-scope.js +6 -1
  28. package/lib/private.js +281 -18
  29. package/lib/prompts/private-consolidation.md +2 -2
  30. package/lib/prompts/private-consolidation.rp.md +3 -2
  31. package/lib/prompts.js +0 -7
  32. package/lib/rpc.js +95 -17
  33. package/lib/snippet.js +18 -2
  34. package/lib/state.js +109 -30
  35. package/lib/stats.js +2 -2
  36. package/lib/temporal.js +19 -0
  37. package/lib/text-retrieval.js +120 -44
  38. package/lib/text-similarity.js +205 -24
  39. package/lib/tokenizer-v2.js +0 -24
  40. package/lib/tools.js +62 -62
  41. package/lib/vector-migration.js +15 -0
  42. package/lib/vector-profile.js +81 -8
  43. package/lib/visibility.js +0 -4
  44. package/lib/webui/standalone.css +17 -22
  45. package/lib/webui/standalone.js +27 -9
  46. package/lib/webui.js +4 -4
  47. package/package.json +3 -2
  48. package/scripts/acceptance-local.mjs +2 -2
  49. package/scripts/check-all.mjs +3 -1
  50. package/scripts/check-i18n.mjs +35 -1
  51. package/scripts/migrate-visibility.mjs +3 -3
  52. package/scripts/prune-sessions.mjs +34 -0
  53. package/scripts/prune-vectors.mjs +24 -0
  54. package/tests/appendix-b.test.mjs +5 -4
  55. package/tests/audit-batch3.test.mjs +247 -0
  56. package/tests/audit-regression.test.mjs +2 -2
  57. package/tests/backup.test.mjs +83 -83
  58. package/tests/browser.test.mjs +6 -1
  59. package/tests/client-render.test.mjs +2 -2
  60. package/tests/consolidation-fork.test.mjs +61 -15
  61. package/tests/consolidation-ledger.test.mjs +64 -3
  62. package/tests/consolidation-snapshot.test.mjs +25 -9
  63. package/tests/curator-clusters.test.mjs +18 -0
  64. package/tests/curator-pairing.test.mjs +59 -16
  65. package/tests/dynamic-rrf.test.mjs +22 -19
  66. package/tests/dynamic-threshold.test.mjs +52 -0
  67. package/tests/fact-version.test.mjs +18 -0
  68. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  69. package/tests/graph-cascade.test.mjs +29 -0
  70. package/tests/graph.test.mjs +45 -0
  71. package/tests/inject-conflict.test.mjs +18 -0
  72. package/tests/injection-chain.test.mjs +2 -2
  73. package/tests/lexical-bm25.test.mjs +171 -0
  74. package/tests/lexicon-frequency.test.mjs +16 -0
  75. package/tests/lexicon-inject.test.mjs +21 -0
  76. package/tests/lexicon-perf.test.mjs +37 -9
  77. package/tests/lexicon-scope.test.mjs +2 -2
  78. package/tests/lexicon-ui.test.mjs +1 -1
  79. package/tests/managed-memory.test.mjs +19 -0
  80. package/tests/ops-hardening.test.mjs +209 -0
  81. package/tests/package-shipping.test.mjs +4 -0
  82. package/tests/prompt-semantics.test.mjs +1 -1
  83. package/tests/prompts.test.mjs +1 -1
  84. package/tests/recall-intent.test.mjs +23 -0
  85. package/tests/slot-similarity.test.mjs +153 -0
  86. package/tests/state-gc.test.mjs +34 -0
  87. package/tests/state.test.mjs +2 -2
  88. package/tests/tokenizer-v2.test.mjs +1 -1
  89. package/tests/vector-gc.test.mjs +37 -0
  90. package/tests/webui.test.mjs +27 -0
@@ -26,14 +26,14 @@ export const RUNTIME_RECORD = 'installed.json'
26
26
  export const RUNTIME_ACTIVE = 'active.json'
27
27
  export const RUNTIME_STAGING = '.staging'
28
28
  export const RUNTIME_CACHE = '.cache'
29
- export const RUNTIME_TRASH = '.trash'
30
29
  export const RUNTIME_LAYOUT = 'node_modules'
31
- export const RUNTIME_STATES = Object.freeze(['unknown', 'unsupported', 'absent', 'downloading', 'verifying', 'installing', 'installed', 'failed', 'cancelled'])
32
30
 
33
31
  const DEFAULT_MAX_ARTIFACT_BYTES = 256 * 1024 * 1024
34
32
  const DEFAULT_MAX_FILE_BYTES = 128 * 1024 * 1024
35
33
  const DEFAULT_SMOKE_TIMEOUT_MS = 120_000
36
34
  const DEFAULT_FETCH_TIMEOUT_MS = 600_000
35
+ // 分块 stall 超时:连续这么久没收到任何 chunk 就判定连接半开并 abort(S-1)。
36
+ const DEFAULT_STALL_TIMEOUT_MS = 30_000
37
37
  const READY_LIMIT = 8_192
38
38
 
39
39
  // The child smoke process needs the OS basics and nothing else: an inherited proxy
@@ -49,6 +49,25 @@ function failure(code, message, extra) {
49
49
  return error
50
50
  }
51
51
 
52
+ // S-16:下载前预检目标盘剩余空间,避免下到一半 ENOSPC 留下 .part 占空间。
53
+ // statfsSync 在部分平台/挂载点会抛错或回报 0,此时不拦(fail-open),让写入
54
+ // 路径自己报错,别因为一个探针就挡住本来能装成功的下载。
55
+ function ensureFreeSpace(dir, requiredBytes) {
56
+ if (!Number.isFinite(requiredBytes) || requiredBytes <= 0) return
57
+ let available = null
58
+ try {
59
+ const stat = fs.statfsSync(dir)
60
+ available = Number(stat.bavail) * Number(stat.bsize)
61
+ } catch {
62
+ return
63
+ }
64
+ if (!Number.isFinite(available) || available <= 0) return
65
+ // 留一倍余量给解包与安装副本,别把盘压到 0。
66
+ if (available < requiredBytes * 2) {
67
+ throw failure('LOCAL_VECTOR_RUNTIME_DISK_ERROR', `not enough free space for the managed runtime: need ~${requiredBytes * 2} bytes, only ${available} available`)
68
+ }
69
+ }
70
+
52
71
  function isPlainObject(value) {
53
72
  return !!value && typeof value === 'object' && !Array.isArray(value)
54
73
  }
@@ -248,6 +267,7 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
248
267
  const maxFileBytes = Number.isInteger(options.maxFileBytes) ? options.maxFileBytes : DEFAULT_MAX_FILE_BYTES
249
268
  const smokeTimeoutMs = Number.isInteger(options.smokeTimeoutMs) ? options.smokeTimeoutMs : DEFAULT_SMOKE_TIMEOUT_MS
250
269
  const fetchTimeoutMs = Number.isInteger(options.fetchTimeoutMs) ? options.fetchTimeoutMs : DEFAULT_FETCH_TIMEOUT_MS
270
+ const stallTimeoutMs = Number.isInteger(options.stallTimeoutMs) ? options.stallTimeoutMs : DEFAULT_STALL_TIMEOUT_MS
251
271
  const extract = typeof options.extract === 'function' ? options.extract : defaultExtract
252
272
  const smoke = typeof options.smoke === 'function' ? options.smoke : defaultSmoke
253
273
  const resolveEntry = typeof options.resolveEntry === 'function' ? options.resolveEntry : id => (id ? getEmbeddingModel(String(id)) : null)
@@ -516,11 +536,41 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
516
536
  }
517
537
  const headers = { 'accept-encoding': 'identity' }
518
538
  if (existing > 0) headers.Range = `bytes=${existing}-`
539
+ // S-1:fetch 总超时 + 分块 stall 超时。任一触发都中断响应体流,避免 CDN 半开
540
+ // 连接让 for-await 永久 pending;超时单独记账,别被 install() 误判成用户取消。
541
+ let timedOut = false
542
+ const totalSignal = AbortSignal.timeout(fetchTimeoutMs)
543
+ totalSignal.addEventListener('abort', () => { timedOut = true }, { once: true })
544
+ const stallController = new AbortController()
545
+ let stallTimer = null
546
+ const armStall = () => {
547
+ if (stallTimer) clearTimeout(stallTimer)
548
+ stallTimer = setTimeout(() => { timedOut = true; stallController.abort() }, stallTimeoutMs)
549
+ stallTimer.unref?.()
550
+ }
551
+ const clearStall = () => { if (stallTimer) { clearTimeout(stallTimer); stallTimer = null } }
552
+ const timeoutFailure = cause => failure('LOCAL_VECTOR_RUNTIME_DOWNLOAD_TIMEOUT', `${artifact.name} download timed out (total ${fetchTimeoutMs}ms / stall ${stallTimeoutMs}ms)`, { cause })
553
+ const abortedFailure = cause => failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted', { cause })
554
+ // for-await 被 signal 中断时抛原生 AbortError,按来源还原成明确失败码;
555
+ // 磁盘写失败(ENOSPC/EIO/...)清掉 .part,别让半成品占着空间(S-16)。
556
+ let removePart = false
557
+ const streamFailure = error => {
558
+ if (timedOut && !controller.signal.aborted) return timeoutFailure(error)
559
+ if (error?.name === 'AbortError' || error?.code === 'ABORT_ERR' || error?.code === 'UND_ERR_ABORTED') return abortedFailure(error)
560
+ if (['ENOSPC', 'EIO', 'EROFS', 'EDQUOT', 'EFBIG'].includes(String(error?.code || ''))) {
561
+ removePart = true
562
+ return failure('LOCAL_VECTOR_RUNTIME_DISK_ERROR', `${artifact.name} download failed with ${error.code}; partial download removed`, { cause: error })
563
+ }
564
+ return error
565
+ }
566
+ armStall()
567
+ const signal = AbortSignal.any([controller.signal, totalSignal, stallController.signal])
519
568
  let response
520
569
  try {
521
- response = await fetchImpl(url, { signal: controller.signal, redirect: 'follow', headers })
570
+ response = await fetchImpl(url, { signal, redirect: 'follow', headers })
522
571
  } catch (error) {
523
- if (isAbort(error, controller.signal)) throw failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted', { cause: error })
572
+ if (timedOut && !controller.signal.aborted) throw timeoutFailure(error)
573
+ if (isAbort(error, controller.signal)) throw abortedFailure(error)
524
574
  throw failure('LOCAL_VECTOR_RUNTIME_NETWORK_ERROR', `cannot fetch ${artifact.name}: ${error?.message || error}`, { cause: error })
525
575
  }
526
576
  if (!response || !response.ok) throw failure('LOCAL_VECTOR_RUNTIME_HTTP_ERROR', `registry returned ${response?.status ?? 'no response'} for ${artifact.name}`)
@@ -552,22 +602,29 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
552
602
  try {
553
603
  const body = response.body
554
604
  if (body && typeof body[Symbol.asyncIterator] === 'function') {
555
- for await (const chunk of body) {
556
- if (controller.signal.aborted) throw failure('LOCAL_VECTOR_RUNTIME_ABORTED', 'the managed runtime install was aborted')
557
- size += chunk.length
558
- if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
559
- fs.writeSync(fd, chunk)
560
- bump(chunk.length)
561
- }
605
+ try {
606
+ for await (const chunk of body) {
607
+ if (controller.signal.aborted) throw abortedFailure(null)
608
+ armStall()
609
+ size += chunk.length
610
+ if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
611
+ fs.writeSync(fd, chunk)
612
+ bump(chunk.length)
613
+ }
614
+ } catch (error) { throw streamFailure(error) }
562
615
  } else {
563
- const buffer = Buffer.from(await response.arrayBuffer())
564
- size += buffer.length
565
- if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
566
- fs.writeSync(fd, buffer)
567
- bump(buffer.length)
616
+ try {
617
+ const buffer = Buffer.from(await response.arrayBuffer())
618
+ size += buffer.length
619
+ if (size > artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} exceeded the pinned ${artifact.bytes} bytes`)
620
+ fs.writeSync(fd, buffer)
621
+ bump(buffer.length)
622
+ } catch (error) { throw streamFailure(error) }
568
623
  }
569
624
  } finally {
570
- fs.closeSync(fd)
625
+ clearStall()
626
+ try { fs.closeSync(fd) } catch {}
627
+ if (removePart) { try { fs.rmSync(paths.part, { force: true }) } catch {} }
571
628
  }
572
629
  if (size !== artifact.bytes) throw failure('LOCAL_VECTOR_RUNTIME_SIZE_MISMATCH', `${artifact.name} is ${size} bytes, expected ${artifact.bytes}`)
573
630
  const digest = await sha256File(paths.part)
@@ -643,6 +700,8 @@ export function createEmbeddingRuntimeInstaller(options = {}) {
643
700
  job = null
644
701
  return { status: 'installed', ready: true, reused: true, key: plan.key, platform: plan.platform, path: existing.dir, engine: plan.engine, version: plan.version, abi: plan.abi, installedAt: existing.record.installedAt || null, verifiedAt: existing.record.verifiedAt || null, checks: Array.isArray(existing.record.checks) ? existing.record.checks : [], artifacts: plan.artifacts.map(item => ({ name: item.name, version: item.version, bytes: item.bytes, sha256: item.sha256 })), smoke: existing.record.smoke || null }
645
702
  }
703
+ // S-16:下载前预检磁盘空间,避免 ENOSPC 留下 .part 占空间。
704
+ ensureFreeSpace(baseDir, totalBytes)
646
705
  // Pick up a partial download from an interrupted process. Old installers kept
647
706
  // the tarball inside their own staging dir; this stable cache is what makes a
648
707
  // restart resume instead of re-downloading 115 MB.
package/lib/engine.js CHANGED
@@ -973,9 +973,3 @@ export async function ensureEngine({ force = false, log = null, beforeSwitch = n
973
973
  return installEngine({ force: true, log, beforeSwitch })
974
974
  }
975
975
 
976
- export function startBackgroundInstall({ log = null } = {}) {
977
- const status = engineStatus()
978
- if (status.status === 'installing') return status
979
- void ensureEngine({ log }).catch(() => {})
980
- return engineStatus()
981
- }
package/lib/freshness.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // The word list is fixed on purpose — exposing it as a setting would create a second
12
12
  // vocabulary system, and this is a nudge, not a filter.
13
13
 
14
+ import { localCalendarDay } from './temporal.js'
14
15
  const DAY_MS = 86_400_000
15
16
  const DEFAULT_FRESHNESS_DAYS = 30
16
17
  // Fixed first-version vocabulary (plan D.2). Keep it separate from the lexicon.
@@ -52,8 +53,7 @@ function timestampMs(value) {
52
53
  }
53
54
 
54
55
  function localDateKey(now) {
55
- const at = new Date(baseTime(now))
56
- return `${at.getFullYear()}-${String(at.getMonth() + 1).padStart(2, '0')}-${String(at.getDate()).padStart(2, '0')}`
56
+ return localCalendarDay(baseTime(now))
57
57
  }
58
58
 
59
59
  /**
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