dsh-memu-memory 1.2.7 → 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.
- package/AGENTS.md +1 -1
- package/CHANGELOG.md +472 -0
- package/README.md +10 -15
- package/README.zh.md +10 -15
- package/docs/memory-semantics.md +23 -3
- package/lib/backup.js +155 -26
- package/lib/binding-diagnostics.js +1 -2
- package/lib/budget.js +31 -9
- package/lib/client.js +221 -128
- package/lib/commitment.js +138 -0
- package/lib/consolidation-ledger.js +5 -2
- package/lib/consolidation-receipt.js +2 -0
- package/lib/consolidation-worker.js +3 -0
- package/lib/curator-policy.js +23 -0
- package/lib/cycle.js +8 -4
- package/lib/embedding-download.js +168 -28
- package/lib/embedding-runtime.js +76 -17
- package/lib/engine.js +0 -6
- package/lib/freshness.js +24 -0
- package/lib/graph.js +139 -11
- package/lib/index.js +71 -20
- package/lib/inject.js +167 -17
- package/lib/lexicon.js +62 -17
- package/lib/local-vector-service.js +25 -2
- package/lib/media.js +49 -12
- package/lib/memory.js +1202 -123
- package/lib/memu.js +4 -0
- package/lib/paths.js +0 -7
- package/lib/preset-scope.js +6 -1
- package/lib/private.js +50 -10
- package/lib/prompts/private-consolidation.mixed.md +2 -2
- package/lib/prompts/private-consolidation.rp.md +6 -1
- package/lib/prompts/private-policy.rp.md +4 -0
- package/lib/prompts/system-guide.rp.md +3 -0
- package/lib/prompts.js +0 -7
- package/lib/recall-cache.js +10 -2
- package/lib/rpc.js +104 -19
- package/lib/snippet.js +41 -0
- package/lib/state.js +109 -30
- package/lib/stats.js +2 -2
- package/lib/temporal.js +348 -0
- package/lib/text-retrieval.js +191 -44
- package/lib/text-similarity.js +205 -24
- package/lib/tokenizer-v2.js +0 -24
- package/lib/tools.js +81 -4
- package/lib/vector-migration.js +15 -0
- package/lib/vector-profile.js +81 -8
- package/lib/visibility.js +0 -4
- package/lib/webui/standalone.css +17 -22
- package/lib/webui/standalone.js +27 -9
- package/lib/webui.js +4 -4
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +2 -2
- package/scripts/bench-recall.mjs +2 -2
- package/scripts/check-all.mjs +3 -1
- package/scripts/check-i18n.mjs +35 -1
- package/scripts/check-seed-compat.mjs +1 -1
- package/scripts/migrate-visibility.mjs +3 -3
- package/scripts/prune-sessions.mjs +34 -0
- package/scripts/prune-vectors.mjs +24 -0
- package/tests/appendix-b.test.mjs +5 -4
- package/tests/audit-batch3.test.mjs +247 -0
- package/tests/audit-regression.test.mjs +2 -2
- package/tests/backup.test.mjs +85 -85
- package/tests/browser.test.mjs +6 -1
- package/tests/client-render.test.mjs +2 -2
- package/tests/commitment.test.mjs +144 -0
- package/tests/consolidation-fork.test.mjs +3 -3
- package/tests/curator-clusters.test.mjs +18 -0
- package/tests/curator-pairing.test.mjs +59 -16
- package/tests/disclosure.test.mjs +34 -17
- package/tests/dynamic-rrf.test.mjs +22 -19
- package/tests/dynamic-threshold.test.mjs +52 -0
- package/tests/fact-version.test.mjs +146 -0
- package/tests/fixtures/tokenizer-cases.mjs +27 -0
- package/tests/graph-cascade.test.mjs +29 -0
- package/tests/graph.test.mjs +45 -0
- package/tests/help-page.test.mjs +1 -1
- package/tests/inject-conflict.test.mjs +112 -0
- package/tests/inject-guide.test.mjs +5 -3
- package/tests/inject.test.mjs +2 -2
- package/tests/injection-intent-budget.test.mjs +92 -0
- package/tests/lexical-bm25.test.mjs +171 -0
- package/tests/lexicon-frequency.test.mjs +17 -1
- package/tests/lexicon-inject.test.mjs +21 -0
- package/tests/lexicon-perf.test.mjs +37 -9
- package/tests/lexicon-scope.test.mjs +2 -2
- package/tests/lexicon-ui.test.mjs +1 -1
- package/tests/managed-memory.test.mjs +19 -0
- package/tests/memory-chain.test.mjs +140 -0
- package/tests/memory-fields.test.mjs +134 -0
- package/tests/memu-resident.test.mjs +33 -0
- package/tests/ops-hardening.test.mjs +209 -0
- package/tests/package-shipping.test.mjs +4 -0
- package/tests/prompt-semantics.test.mjs +51 -0
- package/tests/query-decompose.test.mjs +62 -0
- package/tests/recall-cache.test.mjs +4 -2
- package/tests/recall-intent.test.mjs +123 -0
- package/tests/slot-similarity.test.mjs +153 -0
- package/tests/speaker-provenance.test.mjs +120 -0
- package/tests/state-gc.test.mjs +34 -0
- package/tests/state.test.mjs +2 -2
- package/tests/temporal.test.mjs +124 -0
- package/tests/tokenizer-v2.test.mjs +1 -1
- package/tests/vector-gc.test.mjs +37 -0
- package/tests/webui.test.mjs +27 -0
package/lib/embedding-runtime.js
CHANGED
|
@@ -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
|
|
570
|
+
response = await fetchImpl(url, { signal, redirect: 'follow', headers })
|
|
522
571
|
} catch (error) {
|
|
523
|
-
if (
|
|
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
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
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
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
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
|
-
|
|
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.
|
|
@@ -51,6 +52,29 @@ function timestampMs(value) {
|
|
|
51
52
|
return Number.isFinite(at) ? at : null
|
|
52
53
|
}
|
|
53
54
|
|
|
55
|
+
function localDateKey(now) {
|
|
56
|
+
return localCalendarDay(baseTime(now))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* S1 的有效窗口:`valid_from <= scene day <= valid_to`。两个字段缺失都不影响召回
|
|
61
|
+
* (旧数据没有它们);只有显式写下的窗口才能把条目挡在召回之外。
|
|
62
|
+
* 返回的 reasons 用于活动日志/测试,调用方只关心 valid。
|
|
63
|
+
*/
|
|
64
|
+
export function validitySignals(entry, { now = Date.now() } = {}) {
|
|
65
|
+
const reasons = []
|
|
66
|
+
if (!entry || typeof entry !== 'object') return { valid: true, reasons }
|
|
67
|
+
const today = localDateKey(now)
|
|
68
|
+
// S1 用 snake_case;旧复核路径写过 validFrom/validTo,两个都要认。
|
|
69
|
+
const from = datedValue(entry.valid_from ?? entry.validFrom)
|
|
70
|
+
const to = datedValue(entry.valid_to ?? entry.validTo)
|
|
71
|
+
// An unfinished/invalid window is ignored rather than treated as "always valid":
|
|
72
|
+
// a repair should never make a memory vanish for the rest of the day.
|
|
73
|
+
if (from && today < from.text) reasons.push(`valid-from-future:${from.text}`)
|
|
74
|
+
if (to && today > to.text) reasons.push(`valid-to-past:${to.text}`)
|
|
75
|
+
return { valid: reasons.length === 0, reasons }
|
|
76
|
+
}
|
|
77
|
+
|
|
54
78
|
function thresholdDays(value) {
|
|
55
79
|
const days = Number(value)
|
|
56
80
|
return Number.isFinite(days) && days >= 0 ? days : DEFAULT_FRESHNESS_DAYS
|
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
|
-
|
|
77
|
-
|
|
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
|
-
|
|
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 => {
|
|
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
|
|
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({
|
|
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
|
-
|
|
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)
|
|
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:
|
|
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
|
-
|
|
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
|
-
}
|
|
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
|
-
|
|
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
|
-
}
|
|
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
|
-
|
|
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
|
-
}
|
|
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
|
-
|
|
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, {
|