dsh-memu-memory 1.3.11 → 1.3.13

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.
@@ -0,0 +1,325 @@
1
+ /**
2
+ * 环境自检与修复入口(启动自检 + 设置页"诊断"里的手动入口共用)。
3
+ *
4
+ * 为什么要把这件事单独做成一个模块:2026-11-21 那次故障里,三个坏掉的东西
5
+ * (向量 profile 摘要、runtimeDir 指向已删除目录、遗留 0 字节锁文件)全都只表现成
6
+ * "召回降级"或"整理没跑",插件自己既不检查也不报告,只能靠人去翻 node_modules 源码。
7
+ * 这里把"插件跑得起来需要哪些前提"写成可枚举的检查项,每项都带 level / 证据 / 修复动作,
8
+ * 让启动路径能自动修掉安全的部分、把危险的留给设置页按钮。
9
+ *
10
+ * 设计约束:
11
+ * - 检查必须只读、快、绝不抛错:它跑在启动路径上,任何一项失败都只是"这一项不健康"。
12
+ * - 修复必须显式确认(`confirmed === true`)才联网或改 profile;启动路径只自动跑
13
+ * SAFE_REPAIRS 里的动作(释放遗弃锁 / 重签摘要 / 重指 runtime 目录)。
14
+ * - 修复过程本身失败也是诊断(recordRepair 负责落盘),不能静默。
15
+ */
16
+ import fs from 'node:fs'
17
+ import path from 'node:path'
18
+ import { dataDir, ensureDir, scanMemoryLocks, releaseStaleLocks } from './paths.js'
19
+ import { engineStatus, ensureEngine, ENGINE_VERSION } from './engine.js'
20
+ import { getSettings, getMemoryBackend, backupDatabases } from './state.js'
21
+ import {
22
+ activeProfile, requestedProfile, resignVectorProfile, repointVectorRuntimeDir,
23
+ runtimeDirCandidates, vectorActiveFile, VECTOR_ERROR_CODES,
24
+ } from './vector-profile.js'
25
+ import { hasEmbeddingRuntimePackages, installLocalVectorRuntime, downloadLocalVectorModel } from './local-vector-service.js'
26
+ import { embeddingWorkerManager } from './local-embedding-manager.js'
27
+ import { recordRepair } from './diagnostics.js'
28
+
29
+ // 启动路径可以自己跑的修复:都不联网、都不改变制品身份,最坏情况只是白跑一次。
30
+ export const SAFE_REPAIRS = Object.freeze(['release-stale-locks', 'resign-vector-profile', 'repoint-runtime-dir'])
31
+
32
+ // 需要人点按钮(联网下载 / 重算全部向量 / 动引擎目录)的修复。
33
+ export const MANUAL_REPAIRS = Object.freeze(['reinstall-runtime', 'reinstall-model', 'rebuild-vector-index', 'reinstall-engine'])
34
+
35
+ export const REPAIR_LABELS = Object.freeze({
36
+ 'release-stale-locks': '释放遗留锁文件',
37
+ 'resign-vector-profile': '重签向量 profile 摘要',
38
+ 'repoint-runtime-dir': '重指向量运行时目录',
39
+ 'reinstall-runtime': '重新安装向量运行时',
40
+ 'reinstall-model': '重新下载向量模型',
41
+ 'rebuild-vector-index': '重建向量索引',
42
+ 'reinstall-engine': '重新安装 MemU 引擎',
43
+ })
44
+
45
+ const MODEL_REQUIRED_FILES = ['config.json', 'tokenizer.json']
46
+
47
+ function item(id, level, title, extra = {}) {
48
+ return { id, level, ok: level === 'ok' || level === 'skipped', title, detail: '', hint: '', repair: null, auto: false, manual: false, ...extra }
49
+ }
50
+
51
+ /** dataDir 可写:连自检结果都落不了盘的时候,别的检查也没有意义。 */
52
+ function checkDataDir(items) {
53
+ try {
54
+ const dir = dataDir()
55
+ ensureDir(dir)
56
+ const probe = path.join(dir, `.health-${process.pid}-${Date.now()}`)
57
+ fs.writeFileSync(probe, 'ok')
58
+ fs.unlinkSync(probe)
59
+ items.push(item('data-dir', 'ok', '数据目录可读可写', { detail: dir }))
60
+ return true
61
+ } catch (error) {
62
+ items.push(item('data-dir', 'error', '数据目录不可写', {
63
+ detail: String(error?.message || error),
64
+ hint: '检查磁盘权限/剩余空间;$DSH_HOME 指到只读位置时插件无法保存任何记忆。',
65
+ }))
66
+ return false
67
+ }
68
+ }
69
+
70
+ /** 遗留锁:0 字节 / 进程已死 / 事务超龄,都算遗弃(判据在 paths.js 的 inspectLock)。 */
71
+ function checkLocks(items) {
72
+ let scanned = []
73
+ try { scanned = scanMemoryLocks({ root: dataDir() }) } catch (error) {
74
+ items.push(item('locks', 'warn', '无法扫描锁文件', { detail: String(error?.message || error) }))
75
+ return
76
+ }
77
+ const stale = scanned.filter(lock => lock.stale)
78
+ const held = scanned.filter(lock => !lock.stale)
79
+ if (stale.length) {
80
+ const sample = stale[0]
81
+ items.push(item('locks', 'warn', `${stale.length} 个遗弃锁文件挡住了写入路径`, {
82
+ detail: `${sample.rel}(原因 ${sample.reason || 'unknown'}${sample.owner == null ? '' : `,pid ${sample.owner}`}${sample.ageMs == null ? '' : `,已 ${Math.round(sample.ageMs / 1000)}s`})`,
83
+ hint: '持有它的进程已经不在,或内容是空的;释放后整理任务与写入才会恢复。',
84
+ repair: 'release-stale-locks',
85
+ auto: true,
86
+ files: stale.map(lock => lock.rel),
87
+ }))
88
+ } else if (held.length) {
89
+ items.push(item('locks', 'ok', `${held.length} 个锁正被占用(有活进程持有)`, { detail: held.map(lock => lock.rel).join('、') }))
90
+ } else {
91
+ items.push(item('locks', 'ok', '没有遗留锁文件'))
92
+ }
93
+ }
94
+
95
+ function checkEngine(items) {
96
+ let backend
97
+ try { backend = getMemoryBackend() } catch { backend = null }
98
+ if (backend === 'agent') { items.push(item('engine', 'skipped', '本地 agent 模式不依赖 MemU 引擎')); return }
99
+ let status
100
+ try { status = engineStatus() } catch (error) {
101
+ items.push(item('engine', 'error', '读不到引擎状态', { detail: String(error?.message || error), repair: 'reinstall-engine', manual: true }))
102
+ return
103
+ }
104
+ if (status?.status === 'installing') { items.push(item('engine', 'skipped', '引擎正在安装中')); return }
105
+ if (status?.status === 'ready') {
106
+ const version = status.current?.version || ''
107
+ if (version !== ENGINE_VERSION) {
108
+ items.push(item('engine', 'warn', `引擎版本不是当前插件要的 ${ENGINE_VERSION}(现在是 ${version || '未知'})`, {
109
+ detail: status.current?.python || '',
110
+ hint: '版本漂移时召回仍可用,但新命令(search / memorize)会缺失。',
111
+ repair: 'reinstall-engine',
112
+ auto: getSettingsSafe().autoInstallEngine !== false,
113
+ manual: true,
114
+ }))
115
+ } else {
116
+ items.push(item('engine', 'ok', `引擎就绪(${version})`, { detail: status.current?.python || '' }))
117
+ }
118
+ return
119
+ }
120
+ items.push(item('engine', 'error', `引擎不可用(${status?.status || 'unknown'})`, {
121
+ detail: String(status?.error?.message || status?.reason || ''),
122
+ hint: '缺 Python venv 或引擎包损坏时,语义召回与整理都会退化成词法/跳过。',
123
+ repair: 'reinstall-engine',
124
+ auto: getSettingsSafe().autoInstallEngine !== false,
125
+ manual: true,
126
+ }))
127
+ }
128
+
129
+ function getSettingsSafe() {
130
+ try { return getSettings() || {} } catch { return {} }
131
+ }
132
+
133
+ function vectorEnabled() {
134
+ try { return getMemoryBackend() === 'api' && getSettings().vectorSource === 'local' } catch { return false }
135
+ }
136
+
137
+ /**
138
+ * 向量 profile:指纹 / 摘要 / 落盘目录三件事一起看。
139
+ * 摘要只"元数据漂移"时 profile 仍然可用(assertProfileVerified 已放宽),这里只在真的
140
+ * 校验失败时报,避免自检本身制造噪音。
141
+ */
142
+ function checkVectorProfile(items) {
143
+ if (!vectorEnabled()) { items.push(item('vector-profile', 'skipped', '未启用本地向量召回')); return null }
144
+ let profile = null
145
+ try {
146
+ profile = activeProfile()
147
+ } catch (error) {
148
+ const code = String(error?.code || '')
149
+ if (code === VECTOR_ERROR_CODES.PROFILE_PENDING || code === VECTOR_ERROR_CODES.NOT_ACTIVE || code === VECTOR_ERROR_CODES.PROFILE_MISSING) {
150
+ items.push(item('vector-profile', 'skipped', '还没有激活的向量代际(首次使用/未建库属正常)', { detail: code }))
151
+ return null
152
+ }
153
+ const resignable = code === VECTOR_ERROR_CODES.PROFILE_MANIFEST_CHANGED || code === VECTOR_ERROR_CODES.PROFILE_UNKNOWN
154
+ items.push(item('vector-profile', code ? 'error' : 'warn', `向量 profile 校验失败(${code || 'unknown'})`, {
155
+ detail: String(error?.message || error),
156
+ hint: resignable
157
+ ? '制品清单只是元数据变了(镜像源、文案),重签摘要即可,已算好的向量不用重算。'
158
+ : '制品身份变了或索引文件损坏,需要重建向量代际(会重算全部条目)。',
159
+ repair: resignable ? 'resign-vector-profile' : 'rebuild-vector-index',
160
+ auto: resignable,
161
+ manual: true,
162
+ changedFields: Array.isArray(error?.changedFields) ? error.changedFields : undefined,
163
+ }))
164
+ return null
165
+ }
166
+ if (!profile) { items.push(item('vector-profile', 'ok', '没有向量 profile')); return null }
167
+ items.push(item('vector-profile', 'ok', `向量 profile 校验通过(${profile.catalogId},generation ${profile.generation ?? '?'})`, {
168
+ detail: path.basename(String(vectorActiveFile())),
169
+ }))
170
+
171
+ // 运行时目录:profile 记的路径必须真的装着 onnxruntime-node。
172
+ const runtimeDir = profile.runtimeDir || ''
173
+ if (!hasEmbeddingRuntimePackages(runtimeDir)) {
174
+ const candidates = (() => { try { return runtimeDirCandidates() } catch { return [] } })()
175
+ items.push(item('vector-runtime', candidates.length ? 'warn' : 'error', candidates.length
176
+ ? '向量运行时目录失效(本机已有可用目录)'
177
+ : '向量运行时没有安装', {
178
+ detail: runtimeDir ? `${runtimeDir} 里没有 onnxruntime-node` : 'profile 没有记录 runtimeDir',
179
+ hint: candidates.length
180
+ ? `把它重指到已有的运行时目录(${path.basename(candidates[0].dir)})即可,不需要重新下载。`
181
+ : '需要联网下载 pin 住的运行时制品(约 40MB)。',
182
+ repair: candidates.length ? 'repoint-runtime-dir' : 'reinstall-runtime',
183
+ auto: candidates.length > 0,
184
+ manual: true,
185
+ }))
186
+ }
187
+ const modelDir = profile.modelDir || ''
188
+ const missing = MODEL_REQUIRED_FILES.filter(name => {
189
+ try { return !fs.statSync(path.join(modelDir, name)).isFile() } catch { return true }
190
+ })
191
+ if (missing.length) {
192
+ items.push(item('vector-model', 'error', '向量模型文件缺失', {
193
+ detail: modelDir ? `${modelDir} 缺 ${missing.join('、')}` : 'profile 没有记录 modelDir',
194
+ hint: '模型目录被清理或下载中断时需要重新下载;已算好的向量会失效。',
195
+ repair: 'reinstall-model',
196
+ manual: true,
197
+ }))
198
+ }
199
+ return profile
200
+ }
201
+
202
+ function checkWorker(items) {
203
+ let status = null
204
+ try { status = embeddingWorkerManager().status() } catch { status = null }
205
+ if (!status) return
206
+ if (status.tripped) {
207
+ items.push(item('vector-worker', 'warn', '嵌入 worker 反复崩溃已被熔断', {
208
+ detail: '本次会话内不再尝试拉起,召回退化为词法。',
209
+ hint: '看完诊断里的 stderr 尾巴,修好原因后重启 DSH 即可恢复。',
210
+ }))
211
+ return
212
+ }
213
+ if (status.running) items.push(item('vector-worker', 'ok', '嵌入 worker 在运行'))
214
+ }
215
+
216
+ /**
217
+ * 跑一遍自检。
218
+ * @param {{deep?: boolean}} options deep=true 时把引擎 / 运行时状态连"检查命令"一起做。
219
+ */
220
+ export function runEnvironmentCheck({ deep = false } = {}) {
221
+ const items = []
222
+ const writable = checkDataDir(items)
223
+ if (writable) {
224
+ checkLocks(items)
225
+ checkEngine(items)
226
+ const profile = checkVectorProfile(items)
227
+ checkWorker(items)
228
+ if (deep && profile) {
229
+ try {
230
+ const status = engineStatus({ withSize: true })
231
+ items.push(item('engine-size', 'ok', '引擎占用已统计', { detail: `${status?.current?.bytes ?? 0} 字节` }))
232
+ } catch {}
233
+ }
234
+ }
235
+ const counts = { ok: 0, warn: 0, error: 0, skipped: 0 }
236
+ for (const entry of items) counts[entry.level] = (counts[entry.level] || 0) + 1
237
+ const failed = items.filter(entry => entry.level === 'error' || entry.level === 'warn')
238
+ const repairs = []
239
+ for (const entry of failed) if (entry.repair && !repairs.includes(entry.repair)) repairs.push(entry.repair)
240
+ return {
241
+ checkedAt: new Date().toISOString(),
242
+ ok: counts.error === 0,
243
+ attention: failed.length > 0,
244
+ items,
245
+ counts,
246
+ repairs,
247
+ autoRepairs: failed.filter(entry => entry.repair && entry.auto).map(entry => entry.repair),
248
+ manualRepairs: failed.filter(entry => entry.repair && entry.manual).map(entry => entry.repair),
249
+ }
250
+ }
251
+
252
+ async function runRepairAction(action) {
253
+ switch (action) {
254
+ case 'release-stale-locks': {
255
+ const result = releaseStaleLocks({ root: dataDir() })
256
+ return { detail: `释放 ${result.released.length} 个,保留 ${result.kept.length} 个`, data: result }
257
+ }
258
+ case 'resign-vector-profile': {
259
+ const result = resignVectorProfile({})
260
+ if (!result.changed) return { detail: `无需重签(${result.reason})`, data: result }
261
+ return { detail: `重签 ${result.slots.map(slot => slot.slot).join('/')}:${(result.slots[0]?.changedFields || []).join('、') || 'metadata'}`, data: result }
262
+ }
263
+ case 'repoint-runtime-dir': {
264
+ const result = repointVectorRuntimeDir({})
265
+ if (!result.changed) return { detail: `无需重指(${result.reason})`, data: result }
266
+ return { detail: `重指到 ${path.basename(result.next)}`, data: result }
267
+ }
268
+ case 'reinstall-runtime': {
269
+ const result = await installLocalVectorRuntime({ action: 'start', confirmed: true })
270
+ return { detail: `运行时安装 ${result?.status || 'done'}`, data: result }
271
+ }
272
+ case 'reinstall-model': {
273
+ const state = (() => { try { return activeProfile() } catch { return null } })() || (() => { try { return requestedProfile() } catch { return null } })()
274
+ if (!state?.catalogId) throw new Error('没有可重新下载的模型(profile 缺失)')
275
+ const result = await downloadLocalVectorModel(state.catalogId, { confirmed: true })
276
+ return { detail: `模型下载 ${result?.status || 'done'}`, data: result }
277
+ }
278
+ case 'rebuild-vector-index': {
279
+ const { maybeAutoRebuildVectorGeneration } = await import('./local-vector-service.js')
280
+ const result = await maybeAutoRebuildVectorGeneration()
281
+ return { detail: `重建 ${result?.rebuilt ? '已排队' : '未触发'}`, data: result ?? null }
282
+ }
283
+ case 'reinstall-engine': {
284
+ const result = await ensureEngine({ force: true, beforeSwitch: backupDatabases })
285
+ return { detail: `引擎 ${result?.status || 'done'}`, data: result }
286
+ }
287
+ default:
288
+ throw new Error('unknown repair action: ' + action)
289
+ }
290
+ }
291
+
292
+ /**
293
+ * 执行修复。`confirmed === true` 是硬门槛:这些动作会联网、改 profile 或重算向量。
294
+ * 每一步的结果都写进诊断(成功也算),失败时连同错误一起,方便下次直接看见"修过但没好"。
295
+ */
296
+ export async function repairEnvironment({ actions = [], confirmed = false } = {}) {
297
+ if (confirmed !== true) throw new Error('repairEnvironment requires confirmed === true')
298
+ const requested = Array.isArray(actions) && actions.length ? actions : []
299
+ if (!requested.length) return { ok: true, results: [], skipped: 'no-action' }
300
+ const results = []
301
+ for (const action of requested) {
302
+ const startedAt = new Date().toISOString()
303
+ try {
304
+ const result = await runRepairAction(action)
305
+ recordRepair({ action, ok: true, detail: result.detail, message: `repair ${action}: ${result.detail}` })
306
+ results.push({ action, ok: true, detail: result.detail, startedAt })
307
+ } catch (error) {
308
+ const detail = String(error?.message || error)
309
+ recordRepair({ action, ok: false, detail, message: `repair ${action} failed: ${detail}`, error })
310
+ results.push({ action, ok: false, detail, code: String(error?.code || ''), startedAt })
311
+ }
312
+ }
313
+ const after = runEnvironmentCheck()
314
+ return { ok: results.every(result => result.ok), results, after }
315
+ }
316
+
317
+ /** 启动路径用:只跑安全修复,跑完复检一次并返回结论。 */
318
+ export async function autoRepairEnvironment({ actions = null } = {}) {
319
+ const before = runEnvironmentCheck()
320
+ const candidates = (Array.isArray(actions) && actions.length ? actions : before.autoRepairs)
321
+ .filter(action => SAFE_REPAIRS.includes(action))
322
+ if (!candidates.length) return { changed: false, before, after: before, results: [] }
323
+ const outcome = await repairEnvironment({ actions: [...new Set(candidates)], confirmed: true })
324
+ return { changed: true, before, after: outcome.after, results: outcome.results }
325
+ }
package/lib/graph.js CHANGED
@@ -767,6 +767,62 @@ export function suggestEntityMerges({ libraryId } = {}) {
767
767
  return { items: found.slice(0, SUGGEST_LIMIT).map(item => ({ sourceId: item.sourceId, targetId: item.targetId, reason: item.reason })) }
768
768
  }
769
769
 
770
+ // Unknown names need a complete source surface. Existing, asserted entities use
771
+ // the broader mention matcher; guessing Chinese word boundaries here would turn
772
+ // title n-grams into identities again. An evidence note is not source evidence.
773
+ function hasCompleteEntityName(name, text) {
774
+ const term = String(name || '').normalize('NFKC').toLowerCase().trim()
775
+ const source = String(text || '').normalize('NFKC').toLowerCase()
776
+ if (!term) return false
777
+ const quoted = /「([^」\n]+)」|『([^』\n]+)』|“([^”\n]+)”|‘([^’\n]+)’|"([^"\n]+)"|'([^'\n]+)'|《([^》\n]+)》/gu
778
+ for (const match of source.matchAll(quoted)) {
779
+ if (match.slice(1).some(value => value !== undefined && value.trim() === term)) return true
780
+ }
781
+ const word = /[\p{L}\p{N}\p{M}_.’'-]/u
782
+ for (let at = source.indexOf(term); at !== -1; at = source.indexOf(term, at + term.length)) {
783
+ const left = source.slice(0, at)
784
+ const right = source.slice(at + term.length)
785
+ const rightBoundary = !right || !word.test([...right][0])
786
+ const leftBoundary = !left || !word.test([...left].at(-1))
787
+ if (leftBoundary && rightBoundary) return true
788
+ if (rightBoundary && /(?:名叫|名字(?:是|叫|为)?|称呼(?:是|叫|为)?|自称|叫|username|nickname)\s*[::=]?\s*$/u.test(left)) return true
789
+ }
790
+ return false
791
+ }
792
+
793
+ function validateLinkArguments(kind, note, confidence) {
794
+ if (!LINK_KINDS.includes(kind)) throw new Error(`link kind must be ${LINK_KINDS.join(', ')}`)
795
+ const reason = String(note || '').trim()
796
+ if (reason.replace(/\s/g, '').length < 8 || reason.length > 500) throw new Error('link note must contain 8-500 characters explaining the evidence')
797
+ if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) throw new Error('link confidence must be between 0 and 1')
798
+ return reason
799
+ }
800
+
801
+ /** Model-named entities stay provisional; manual UI creation is unchanged. */
802
+ export function linkNamedEntity({ exec, libraryId, fromId, entity, kind, note, confidence = 0.7 }) {
803
+ const scope = scopeFor({ exec, libraryId })
804
+ validateLinkArguments(kind, note, confidence)
805
+ const name = String(entity?.name || '').trim()
806
+ const entityKind = entity?.kind || 'person'
807
+ if (!ENTITY_KINDS.includes(entityKind)) throw new Error('invalid entity kind')
808
+ if (!name || name.length > 120 || !normalizeEntityName(name)) throw new Error('entity name must contain 1-120 identifying characters')
809
+ const origin = loadPrivateIndex(scope.libraryId).entries[fromId]
810
+ if (!origin || !allowed(origin, exec)) throw new Error('unknown or inaccessible memory')
811
+ const normalized = normalizeEntityName(name)
812
+ const existing = listEntities({ exec, libraryId: scope.libraryId }).items.find(item => normalizeEntityName(item.name) === normalized
813
+ || (Array.isArray(item.aliases) && item.aliases.some(alias => normalizeEntityName(alias) === normalized)))
814
+ if (existing && existing.kind !== entityKind) throw new Error('entity already exists with a different kind')
815
+ if (kind === 'person' && entityKind !== 'person') throw new Error('person links must target a person entity')
816
+ if (!existing) {
817
+ if ((origin.links || []).length >= 100) throw new Error('memory already has 100 links; review the existing connections first')
818
+ if (!hasCompleteEntityName(name, origin.title) && !hasCompleteEntityName(name, origin.content)) {
819
+ throw new Error('新实体需要来源记忆中的完整名称(complete name);不能用词语碎片、代词推测或关联理由代替。请引用完整称呼,或在界面中手动确认实体。')
820
+ }
821
+ }
822
+ const target = existing || createEntity({ exec, libraryId: scope.libraryId, name, kind: entityKind, status: 'provisional', origin: 'worker' })
823
+ return linkEntries({ exec, libraryId: scope.libraryId, fromId, toId: target.id, kind, note, confidence })
824
+ }
825
+
770
826
  /**
771
827
  * Write one directed link from a memory to a memory or entity.
772
828
  *
@@ -778,10 +834,7 @@ export function suggestEntityMerges({ libraryId } = {}) {
778
834
  */
779
835
  export function linkEntries({ exec, libraryId, fromId, toId, kind, note, confidence = 0.7, source }) {
780
836
  const scope = scopeFor({ exec, libraryId })
781
- if (!LINK_KINDS.includes(kind)) throw new Error(`link kind must be ${LINK_KINDS.join(', ')}`)
782
- const reason = String(note || '').trim()
783
- if (reason.replace(/\s/g, '').length < 8 || reason.length > 500) throw new Error('link note must contain 8-500 characters explaining the evidence')
784
- if (!Number.isFinite(confidence) || confidence < 0 || confidence > 1) throw new Error('link confidence must be between 0 and 1')
837
+ const reason = validateLinkArguments(kind, note, confidence)
785
838
  if (fromId === toId) throw new Error('a memory cannot link to itself')
786
839
  const linkSource = source === 'auto' || source === 'user' ? source : null
787
840
  const entities = readEntities(scope.libraryId).entities
@@ -873,19 +926,34 @@ export function unlinkEntry({ libraryId, fromId, toId, kind }) {
873
926
  return { removed }
874
927
  }
875
928
 
876
- export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 200, includeOrphans = false }) {
929
+ // Graph filtering is read-only: normalize legacy stamps without rewriting them.
930
+ function graphDomain(value) { return String(value ?? '').normalize('NFKC').trim().toLowerCase() }
931
+
932
+ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 200, includeOrphans = false, offset, domain }) {
877
933
  const scope = scopeFor({ exec, libraryId })
878
934
  const index = loadPrivateIndex(scope.libraryId)
879
935
  const entities = readEntities(scope.libraryId).entities
880
936
  const cap = Math.max(1, Math.min(200, Math.floor(Number(limit) || 200)))
881
937
  const hops = Math.max(0, Math.min(2, Math.floor(Number(depth) || 0)))
882
- const visible = new Set(Object.entries(index.entries).filter(([, entry]) => allowed(entry, exec)).map(([id]) => id))
938
+ const domainFilter = graphDomain(domain)
939
+ const domains = new Set()
940
+ const visible = new Map()
941
+ for (const [id, entry] of Object.entries(index.entries)) {
942
+ if (!allowed(entry, exec)) continue
943
+ const normalized = graphDomain(entry?.domain) || 'general'
944
+ domains.add(normalized)
945
+ if (!domainFilter || normalized === domainFilter) visible.set(id, normalized)
946
+ }
947
+ const paged = !focusId && offset !== undefined
948
+ const start = paged ? Number(offset) : 0
949
+ const pageStart = Number.isFinite(start) ? Math.max(0, Math.floor(start)) : 0
883
950
  const edges = []
884
951
  const adjacency = new Map()
885
- for (const from of visible) {
952
+ for (const from of visible.keys()) {
886
953
  for (const link of index.entries[from].links || []) {
887
954
  if (!LINK_KINDS.includes(link.kind)) continue
888
- // A deleted target gets a placeholder; an inaccessible target gets no hint.
955
+ // A deleted target gets a placeholder; an inaccessible or other-domain
956
+ // memory gets no hint. Filter before building either edges or adjacency.
889
957
  if (index.entries[link.to] && !visible.has(link.to)) continue
890
958
  // source is display metadata only ('auto' edges get a badge in the graph
891
959
  // view); an older link without the field reports null instead of undefined.
@@ -907,8 +975,9 @@ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 2
907
975
  }
908
976
  }
909
977
  }
910
- if (focusId && !visible.has(focusId) && !adjacency.has(focusId) && (!entities[focusId] || sessionIdOf(exec))) throw new Error('unknown or inaccessible graph focus')
978
+ if (focusId && !visible.has(focusId) && !adjacency.has(focusId) && (!entities[focusId] || sessionIdOf(exec) || domainFilter)) throw new Error('unknown or inaccessible graph focus')
911
979
  const selected = new Set()
980
+ const candidates = new Set()
912
981
  if (focusId) {
913
982
  let frontier = [focusId]
914
983
  for (let hop = 0; hop <= hops; hop += 1) {
@@ -921,27 +990,31 @@ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 2
921
990
  frontier = next
922
991
  }
923
992
  } else {
924
- // Orphan entities — no edge from any visible entry — are hidden by default.
925
- // After the permanent-delete cascade and pruneOrphanEntities they should not
926
- // exist on disk at all; a leftover from old data is invisible weight, and a
927
- // session-scoped viewer already never saw them (the check below). Pass
928
- // includeOrphans to see what an old entities.json still holds. An explicit
929
- // focusId always wins: asking for a node by id is intent, not browsing.
930
- for (const id of [...visible, ...Object.keys(entities), ...adjacency.keys()]) {
931
- if (selected.size >= cap) break
993
+ // Build every qualifying candidate before slicing. Memories retain their
994
+ // original order, but later entities can no longer starve across pages.
995
+ // A domain never includes unrelated orphan entities, even on explicit opt-in.
996
+ for (const id of [...visible.keys(), ...Object.keys(entities), ...adjacency.keys()]) {
932
997
  if (sessionIdOf(exec) && !visible.has(id) && !adjacency.has(id)) continue
933
- if (!includeOrphans && entities[id] && !adjacency.has(id)) continue
934
- selected.add(id)
998
+ if ((!includeOrphans || domainFilter) && entities[id] && !adjacency.has(id)) continue
999
+ candidates.add(id)
935
1000
  }
1001
+ for (const id of [...candidates].slice(pageStart, pageStart + cap)) selected.add(id)
936
1002
  }
937
1003
  const nodes = [...selected].map(id => {
938
1004
  const entry = index.entries[id]
939
1005
  const entity = entities[id]
940
1006
  return { id, title: entry?.title || entity?.name || '[deleted]', layer: entry?.layer || null,
941
1007
  kind: entity?.kind || 'memory', strength: entry ? decayStrength(entry) : 0.5,
942
- degree: adjacency.get(id)?.size || 0, missing: !entry && !entity }
1008
+ degree: adjacency.get(id)?.size || 0, missing: !entry && !entity,
1009
+ ...(entry ? { domain: visible.get(id) } : {}),
1010
+ ...(entity ? { status: ENTITY_STATUS.includes(entity.status) ? entity.status : 'provisional' } : {}) }
943
1011
  })
944
- return { nodes, edges: edges.filter(edge => selected.has(edge.from) && selected.has(edge.to)), limit: cap, truncated: selected.size >= cap, focusId }
1012
+ const remaining = pageStart + selected.size < candidates.size
1013
+ return {
1014
+ nodes, edges: edges.filter(edge => selected.has(edge.from) && (paged ? candidates.has(edge.to) : selected.has(edge.to))),
1015
+ limit: cap, truncated: paged ? remaining : selected.size >= cap, focusId, domains: [...domains].sort(),
1016
+ ...(paged ? { total: candidates.size, nextOffset: remaining ? pageStart + selected.size : null } : {}),
1017
+ }
945
1018
  }
946
1019
 
947
1020
  // D9:recallRelations 只需要「与这条记忆相连的边」,旧实现却每次全库扫
package/lib/index.js CHANGED
@@ -9,11 +9,13 @@ import { getSettings, getMemoryBackend, backupDatabases, flushState, listLibrari
9
9
  import { buildTurnRecords, recordTurn, deleteTurnLog } from './turn-log.js'
10
10
  import { pruneOrphanEntitiesAll } from './graph.js'
11
11
  import { pruneDeletedStores } from './memory.js'
12
- import { closeEmbeddingWorkers } from './local-embedding-manager.js'
12
+ import { closeEmbeddingWorkers, setEmbeddingFailureSink } from './local-embedding-manager.js'
13
13
  import { bootstrapLocalVector, closeLocalVectorService } from './local-vector-service.js'
14
14
  import { closeMemuResident, prewarmMemuResident } from './memu.js'
15
15
  import { vectorStatus } from './vector-profile.js'
16
16
  import { setWarnSink, warn } from './paths.js'
17
+ import { recordDiagnostic, recordErrorDiagnostic } from './diagnostics.js'
18
+ import { autoRepairEnvironment, runEnvironmentCheck } from './environment-check.js'
17
19
 
18
20
  export const name = 'dsh-memu-memory'
19
21
  // `timer` backs ctx.interval, used by the idle/auto-curation sweep. Reading an
@@ -73,6 +75,7 @@ function startLocalVectorBootstrap(ctx) {
73
75
  try { ctx.logger?.info?.(`dsh-memu-memory: managed local embedding runtime ready (${String(ready?.model || catalogId)} ${Number(ready?.dimension) || '?'}d)`) } catch {}
74
76
  }).catch((error) => {
75
77
  try { ctx.logger?.warn?.(`dsh-memu-memory: local embedding bootstrap skipped: ${error?.message || error}`) } catch {}
78
+ recordErrorDiagnostic(error, { source: 'vector-bootstrap' })
76
79
  })
77
80
  })
78
81
  } catch (error) {
@@ -94,6 +97,7 @@ function startEngineBootstrap(ctx) {
94
97
  return scheduleStartup(ctx, 1500, 'engine bootstrap', () => {
95
98
  void ensureEngine({ beforeSwitch: backupDatabases }).catch((error) => {
96
99
  try { ctx.logger?.warn?.(`dsh-memu-memory: engine bootstrap failed: ${error?.message || error}`) } catch {}
100
+ recordErrorDiagnostic(error, { source: 'engine-bootstrap' })
97
101
  })
98
102
  })
99
103
  } catch (error) {
@@ -205,6 +209,50 @@ export function registerTurnLogRecorder(ctx) {
205
209
  }
206
210
  }
207
211
 
212
+ // 启动自检(§14.14):把"插件能不能正常工作"的前提逐项查一遍。
213
+ //
214
+ // 排在三个引导之后(6s)是刻意的:引擎引导可能正在装、向量引导可能正在拉起 worker,
215
+ // 自检要看到它们的结果才有意义。安全修复(释放遗弃锁 / 重签摘要 / 重指运行时目录)
216
+ // 直接做——它们不联网、不改制品身份;其余的只写诊断,等她在诊断页点按钮。
217
+ // 之所以不再往 WebUI 的活动日志里塞:那里的每一条都是"记忆活动",故障取证需要
218
+ // stderr 尾巴、目录、修复动作,那是诊断页的内容。
219
+ function startEnvironmentHealthCheck(ctx) {
220
+ try {
221
+ return scheduleStartup(ctx, 6000, 'environment health check', () => {
222
+ // 自检永远跑(它只读),但"自动动手"跟着 autoInstallEngine 开关走:
223
+ // 关掉自动准备引擎的用户,通常也不想让插件在启动时替他们清锁/改 profile。
224
+ let autoRepair = true
225
+ try { autoRepair = getSettings()?.autoInstallEngine !== false } catch {}
226
+ const pass = autoRepair
227
+ ? autoRepairEnvironment()
228
+ : Promise.resolve({ changed: false, results: [], before: runEnvironmentCheck(), after: null })
229
+ void pass.then((outcome) => {
230
+ for (const result of outcome.results) {
231
+ try { ctx.logger?.warn?.(`dsh-memu-memory: ${result.ok ? 'repaired' : 'repair failed'}: ${result.action} (${result.detail})`) } catch {}
232
+ }
233
+ const after = outcome.after || outcome.before
234
+ for (const entry of after.items || []) {
235
+ if (entry.level !== 'error' && entry.level !== 'warn') continue
236
+ recordDiagnostic({
237
+ level: entry.level,
238
+ scope: 'environment',
239
+ code: `ENV_${String(entry.id).toUpperCase().replace(/[^A-Z0-9]+/g, '_')}`,
240
+ message: entry.title,
241
+ detail: { detail: entry.detail, repair: entry.repair, files: entry.files },
242
+ hint: entry.hint,
243
+ repair: entry.repair,
244
+ manual: entry.manual,
245
+ source: 'startup-check',
246
+ })
247
+ }
248
+ }).catch((error) => { recordErrorDiagnostic(error, { source: 'startup-check' }) })
249
+ })
250
+ } catch (error) {
251
+ try { ctx.logger?.warn?.(`dsh-memu-memory: environment health check skipped: ${error?.message || error}`) } catch {}
252
+ return null
253
+ }
254
+ }
255
+
208
256
  export function apply(ctx, config) {
209
257
  // A conversation that names an agent preset composes its model-facing plugin set from
210
258
  // that preset's cordis.yml alone, and that subtree never delivers `agent/pre-step` to
@@ -223,7 +271,26 @@ export function apply(ctx, config) {
223
271
  }
224
272
  applied.add(ctx)
225
273
 
226
- setWarnSink((message) => { try { ctx.logger?.warn?.(`dsh-memu-memory: ${message}`) } catch {} })
274
+ setWarnSink((message) => {
275
+ try { ctx.logger?.warn?.(`dsh-memu-memory: ${message}`) } catch {}
276
+ // 同一条 warn 也进诊断档案:活动日志记的是"记忆活动",插件内部故障需要集中取证。
277
+ // recordDiagnostic 自己做 60 秒去重,反复出现的同一句只累加 count。
278
+ recordDiagnostic({ level: 'warn', scope: 'plugin', code: 'MEMU_WARNING', message, source: 'warn-sink' })
279
+ })
280
+
281
+ // 嵌入 worker 的失败以前只剩一句"worker exited before it became ready"(stderr 被整个
282
+ // 丢掉)。接进诊断后,那条记录带着 stderr 尾巴与两个目录,能直接看出是缺原生模块
283
+ // 还是 runtimeDir 指错了。
284
+ setEmbeddingFailureSink((payload) => {
285
+ const error = Object.assign(new Error(payload?.message || 'embedding worker failed'), {
286
+ code: payload?.code || 'LOCAL_VECTOR_WORKER_EXITED',
287
+ detail: { stderrTail: payload?.stderrTail || '' },
288
+ })
289
+ recordErrorDiagnostic(error, {
290
+ source: 'embedding-worker',
291
+ detail: { modelDir: payload?.modelDir || '', runtimeDir: payload?.runtimeDir || '' },
292
+ })
293
+ })
227
294
 
228
295
  // Bookkeeping writes are coalesced on a 50ms timer (P0-4). Anything still
229
296
  // pending has to reach disk before the process goes away.
@@ -270,6 +337,7 @@ export function apply(ctx, config) {
270
337
  startEngineBootstrap(ctx),
271
338
  startLocalVectorBootstrap(ctx),
272
339
  startOrphanEntitySweep(ctx),
340
+ startEnvironmentHealthCheck(ctx),
273
341
  ].filter(Boolean)
274
342
  if (typeof ctx.effect === 'function') {
275
343
  ctx.effect(() => () => {