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.
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url'
4
4
  import { assertProfileVerified } from './vector-profile.js'
5
5
  import { manifestModelId } from './local-embedding-worker.js'
6
6
  import { prefixesRequireRole } from './embedding-catalog.js'
7
- import { windowsSystemEnv } from './paths.js'
7
+ import { windowsSystemEnv, redactSecrets } from './paths.js'
8
8
 
9
9
  const entry = fileURLToPath(new URL('./local-embedding-entry.js', import.meta.url))
10
10
  const failure = (code, message) => Object.assign(new Error(message), { code, fallback: 'lexical' })
@@ -14,6 +14,20 @@ const EMBEDDINGS_PATH = '/v1/embeddings'
14
14
  const READY_LIMIT = 16_384
15
15
  const TOKEN_BYTES = 32
16
16
  const DEFAULT_WINDOW_MS = 60_000
17
+ // 子进程 stderr 只留尾巴:够看清哪个原生模块缺了,不会把整段加载日志留在内存里。
18
+ const STDERR_TAIL_LIMIT = 4000
19
+
20
+ // 失败可观测性接线(2026-11-21)。abort() 里把带 stderr 尾巴的失败交给 sink,由插件入口
21
+ // 落进诊断档案。默认 null:单测直接 new manager 时不会写任何文件。
22
+ let failureSink = null
23
+
24
+ export function setEmbeddingFailureSink(fn) {
25
+ failureSink = typeof fn === 'function' ? fn : null
26
+ }
27
+
28
+ function noteFailure(payload) {
29
+ try { failureSink?.(payload) } catch {}
30
+ }
17
31
 
18
32
  // The worker needs the OS basics and nothing else. An inherited proxy variable can
19
33
  // reroute the loopback call (§14.6: MEMU_HTTP_PROXY does exist), an inherited
@@ -114,7 +128,7 @@ export function createEmbeddingWorkerManager({ spawnImpl = spawn, executable = p
114
128
  function boot(profile, key, modelDir, runtimeDir) {
115
129
  const token = crypto.randomBytes(TOKEN_BYTES).toString('hex')
116
130
  const expected = { model: manifestModelId(profile.manifest), dimension: Number(profile.dimension), rolesRequired: prefixesRequireRole(profile.manifest) }
117
- const record = { key, child: null, stopping: false, settled: false, endpoint: null, reject: null }
131
+ const record = { key, child: null, stopping: false, settled: false, endpoint: null, reject: null, stderrTail: '' }
118
132
  // Registered before the spawn so a concurrent acquire joins this boot instead of
119
133
  // starting a second child for the same profile.
120
134
  records.set(key, record)
@@ -128,7 +142,18 @@ export function createEmbeddingWorkerManager({ spawnImpl = spawn, executable = p
128
142
  record.settled = true
129
143
  clearTimer()
130
144
  forget()
131
- reject(failure(code, message))
145
+ const error = failure(code, message)
146
+ // 把"查案需要的东西"挂到错误上:缺哪个原生模块、指到哪个目录,全在 stderr 尾巴里。
147
+ // 同时交给 sink 落进诊断档案——父进程原来连 stderr 都丢掉,宿主机上只剩
148
+ // "the local embedding worker exited before it became ready" 这一句可查。
149
+ error.embedding = {
150
+ stderrTail: record.stderrTail,
151
+ modelDir: modelDir ? String(modelDir) : '',
152
+ runtimeDir: runtimeDir ? String(runtimeDir) : '',
153
+ }
154
+ if (record.stderrTail) error.detail = { stderrTail: record.stderrTail }
155
+ noteFailure({ code, message, stderrTail: record.stderrTail, modelDir, runtimeDir })
156
+ reject(error)
132
157
  }
133
158
  // close() rejects an in-flight acquire through this hook, so a caller waiting on
134
159
  // a child that never reports ready fails immediately instead of hanging.
@@ -192,8 +217,17 @@ export function createEmbeddingWorkerManager({ spawnImpl = spawn, executable = p
192
217
  warn('the local embedding worker exited; semantic recall will degrade to lexical')
193
218
  abort('LOCAL_VECTOR_WORKER_EXITED', 'the local embedding worker exited before it became ready')
194
219
  })
195
- // Native stderr may quote request text, so it is read and discarded.
196
- child?.stderr?.on?.('data', () => {})
220
+ // Native stderr may quote request text, so it is never logged verbatim; it is
221
+ // redacted and kept as a short tail, because it is the only place a missing native
222
+ // module or a bad runtime directory ever announces itself. Discarding it entirely
223
+ // (the pre-1.3.13 behaviour) made every worker failure indistinguishable from a
224
+ // silent exit.
225
+ child?.stderr?.on?.('data', chunk => {
226
+ try {
227
+ if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk)) return
228
+ record.stderrTail = redactSecrets(record.stderrTail + String(chunk)).slice(-STDERR_TAIL_LIMIT)
229
+ } catch {}
230
+ })
197
231
  child?.stdout?.on?.('data', chunk => {
198
232
  if (record.settled) return
199
233
  buffer += String(chunk)
package/lib/memory.js CHANGED
@@ -4591,6 +4591,87 @@ export function noteGlobalInjected({ ids = [], at = stamp() }) {
4591
4591
  return touched
4592
4592
  }
4593
4593
 
4594
+ // 全局生命周期是用户管理面动作(与 resolveReview 的全局元数据动作同鉴权口径),
4595
+ // 不是 curator 的内容写入:只改 status。召回/锚点/注入都过 isMemoryEligible,
4596
+ // archived 立即自动排除,向量行无需改动(与 privateArchive 同口径)。
4597
+ export async function globalSetStatus({ id, status }) {
4598
+ const target = String(id || '').trim()
4599
+ if (!target) throw new Error('memory id is required')
4600
+ if (!['active', 'archived'].includes(status)) throw new Error('global lifecycle only supports active and archived')
4601
+ let result = null
4602
+ let changed = false
4603
+ await retryStoreWrite(() => updateGlobalIndex((index) => {
4604
+ const entry = index.entries[target]
4605
+ if (!entry) throw new Error(`unknown global memory: ${target}`)
4606
+ if (status === 'archived') {
4607
+ if (entry.status === 'pending_review') throw new Error('a pending global memory must be resolved in the review queue first')
4608
+ if (entry.status === 'archived') { result = { id: target, entry }; return }
4609
+ } else if (entry.status !== 'archived') {
4610
+ throw new Error('only archived global memories can be restored')
4611
+ }
4612
+ entry.status = status
4613
+ entry.updatedAt = stamp()
4614
+ changed = true
4615
+ result = { id: target, entry }
4616
+ }))
4617
+ if (changed) {
4618
+ record({
4619
+ kind: 'write', scope: 'global', libraryId: null,
4620
+ message: status === 'archived' ? '全局记忆归档(管理面)' : '全局记忆恢复(管理面)',
4621
+ detail: { id: target, status }, refs: [target],
4622
+ })
4623
+ }
4624
+ return result
4625
+ }
4626
+
4627
+ /**
4628
+ * 全局永久删除,与 privateDeleteImpl 同序:先删引擎/向量行(引擎拒绝则索引不动),
4629
+ * 再在单事务里删行并级联清掉他条指向它的 links 与指针字段。合并稿与活跃合并的
4630
+ * 来源拒删——absorbSnapshot 是撤销合并的唯一依据,删掉成员会让撤销悬空。
4631
+ * 安全网是 RPC 层的两段确认 + backupDatabases,与私有单条删除一致。
4632
+ */
4633
+ export async function globalDelete({ id }) {
4634
+ const target = String(id || '').trim()
4635
+ if (!target) throw new Error('memory id is required')
4636
+ const index = loadGlobalIndex()
4637
+ const entry = index.entries[target]
4638
+ if (!entry) throw new Error(`unknown global memory: ${target}`)
4639
+ if (!['archived', 'suppressed', 'expired'].includes(entry.status)) {
4640
+ throw new Error('only archived memories can be deleted permanently; archive it first')
4641
+ }
4642
+ if (Array.isArray(entry.absorbedFrom) && entry.absorbedFrom.length) {
4643
+ throw new Error('this merged memory still carries its absorb snapshot; undo the merge first')
4644
+ }
4645
+ const merged = Object.entries(index.entries).find(([otherId, other]) => otherId !== target
4646
+ && other?.status === 'active' && Array.isArray(other.absorbedFrom) && other.absorbedFrom.includes(target))
4647
+ if (merged) throw new Error(`this memory is a source of merged memory ${merged[0]}; undo the merge first`)
4648
+ const backend = engineRoute()
4649
+ let engine = null
4650
+ if (backend !== 'lexical') {
4651
+ engine = await forget({ route: backend, db: globalDbPath(), name: target })
4652
+ }
4653
+ await retryStoreWrite(() => updateGlobalIndex((fresh) => {
4654
+ if (JSON.stringify(fresh.entries[target]) !== JSON.stringify(entry)) throw new Error('memory changed during deletion; reload and retry')
4655
+ delete fresh.entries[target]
4656
+ for (const other of Object.values(fresh.entries)) {
4657
+ if (Array.isArray(other.links) && other.links.some(link => link?.to === target)) {
4658
+ other.links = other.links.filter(link => link?.to !== target)
4659
+ }
4660
+ if (other.duplicateOf === target) delete other.duplicateOf
4661
+ if (other.relatedTo === target) delete other.relatedTo
4662
+ if (other.conflictingWith === target) delete other.conflictingWith
4663
+ if (other.supersededBy === target) delete other.supersededBy
4664
+ if (other.absorbedBy === target) delete other.absorbedBy
4665
+ }
4666
+ }))
4667
+ record({
4668
+ kind: 'write', scope: 'global', libraryId: null,
4669
+ message: '全局记忆永久删除(管理面)',
4670
+ detail: { id: target, backend }, refs: [target],
4671
+ })
4672
+ return { id: target, libraryId: null, deleted: true, backend, engine }
4673
+ }
4674
+
4594
4675
  // Local calendar day (not UTC): "today" for a reminder is the user's today, the same
4595
4676
  // unit `salientDaysAhead` measures in.
4596
4677
  function localDateKey(date) {
package/lib/paths.js CHANGED
@@ -207,6 +207,135 @@ export function writeJson(file, value) {
207
207
 
208
208
  const heldLocks = new Set()
209
209
 
210
+ // 遗留锁判定阈值(2026-11-21 现场)。这里全部是"同步事务锁":action 只做同步文件 IO,
211
+ // 绝不跨 await(见 docs/contributing.md §5 锁顺序不变式),所以任何锁都不该长寿。
212
+ //
213
+ // 旧实现的致命口子:EEXIST 时把锁内容当 pid 读,只有 `Number.isSafeInteger(owner) && owner > 0`
214
+ // 才进清理分支。一个 0 字节的遗留锁(进程在 openSync 与 writeFileSync 之间被杀)于是永远
215
+ // 清不掉——500ms 后抛 DSH_MEMU_STORE_BUSY,被 safeLedger 吞成 "the consolidation lease could
216
+ // not be persisted",整理任务连坏 84 次而没人知道为什么。
217
+ const LOCK_ACQUIRE_BUDGET_MS = 500
218
+ const LOCK_EMPTY_STALE_MS = 10_000
219
+ const LOCK_MAX_AGE_MS = 60_000
220
+
221
+ // paths.js 不 import diagnostics.js(否则成环):锁事件扔给 sink,方向永远单向。
222
+ let lockEventSink = null
223
+
224
+ export function setLockEventSink(fn) {
225
+ lockEventSink = typeof fn === 'function' ? fn : null
226
+ }
227
+
228
+ function lockEvent(event) {
229
+ try { lockEventSink?.(event) } catch {}
230
+ }
231
+
232
+ /** 锁载荷 = `pid\nISO 时间\n`。旧锁只有一行裸 pid,解析器两种都认。 */
233
+ function parseLockOwner(raw) {
234
+ const lines = String(raw || '').split(/\r?\n/).map(line => line.trim()).filter(Boolean)
235
+ const pid = Number(lines[0])
236
+ const at = lines[1] && Number.isFinite(Date.parse(lines[1])) ? Date.parse(lines[1]) : null
237
+ return { pid: Number.isSafeInteger(pid) && pid > 0 ? pid : null, at, raw: lines[0] || '' }
238
+ }
239
+
240
+ function lockAgeMs(lockPath, now = Date.now()) {
241
+ try { return Math.max(0, now - fs.statSync(lockPath).mtimeMs) } catch { return null }
242
+ }
243
+
244
+ /**
245
+ * 判断一个已存在的锁是不是遗留物;是则返回原因,否则 null(= 真有主,继续等)。
246
+ *
247
+ * 三档判据,都不依赖"锁内容必须像 pid":
248
+ * - 载荷里没有合法 pid(0 字节、被截断、别的格式):扛过 LOCK_EMPTY_STALE_MS 就算遗弃,
249
+ * 因为 open 与 write 之间只有毫秒级窗口;
250
+ * - pid 存活探测:ESRCH 即死主,立刻清;
251
+ * - pid 是本进程但当前没有事务持有它(heldLocks 无记录):说明是上一轮同 pid 进程的残骸;
252
+ * - 任何锁超过 LOCK_MAX_AGE_MS:同步事务不可能持锁这么久,按遗弃处理。
253
+ */
254
+ export function inspectLock(lockPath, now = Date.now()) {
255
+ const ageMs = lockAgeMs(lockPath, now)
256
+ if (ageMs === null) return null
257
+ let raw = ''
258
+ try { raw = fs.readFileSync(lockPath, 'utf8') } catch {}
259
+ const owner = parseLockOwner(raw)
260
+ const detail = { lockPath, owner: owner.pid, raw: owner.raw.slice(0, 40), ageMs }
261
+ if (owner.pid === null) {
262
+ return ageMs >= LOCK_EMPTY_STALE_MS ? { reason: 'unparseable-owner', detail } : null
263
+ }
264
+ // 自己 pid 但内存里没有对应事务:可能是本地遗留,也可能是同一进程里的另一个插件
265
+ // 副本正持有它。只有前者可以破,所以再等 LOCK_EMPTY_STALE_MS 才认——立刻破会把
266
+ // 另一个副本正在写的事务拆掉。
267
+ if (owner.pid === process.pid && !heldLocks.has(lockPath)) {
268
+ return ageMs >= LOCK_EMPTY_STALE_MS ? { reason: 'own-pid-without-transaction', detail } : null
269
+ }
270
+ if (owner.pid !== process.pid) {
271
+ try { process.kill(owner.pid, 0) } catch (probe) {
272
+ if (probe?.code === 'ESRCH') return { reason: 'dead-owner', detail }
273
+ }
274
+ }
275
+ if (ageMs >= LOCK_MAX_AGE_MS) return { reason: 'aged-out', detail }
276
+ return null
277
+ }
278
+
279
+ /** 扫描数据目录下的全部 *.lock(深度 3:index/、libraries/ 一层就到)。 */
280
+ export function scanMemoryLocks({ root = dataDir(), maxDepth = 3, now = Date.now() } = {}) {
281
+ const found = []
282
+ const walk = (dir, depth) => {
283
+ if (depth > maxDepth) return
284
+ let entries = []
285
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }
286
+ for (const entry of entries) {
287
+ const abs = path.join(dir, entry.name)
288
+ let isDir = entry.isDirectory()
289
+ // 符号链接按"不跟随"处理:数据目录里没有需要跟进去的锁。
290
+ if (entry.isSymbolicLink()) continue
291
+ if (isDir) { walk(abs, depth + 1); continue }
292
+ if (!entry.name.endsWith('.lock')) continue
293
+ const stale = inspectLock(abs, now)
294
+ const ageMs = lockAgeMs(abs, now)
295
+ let raw = ''
296
+ try { raw = fs.readFileSync(abs, 'utf8') } catch {}
297
+ found.push({
298
+ path: abs,
299
+ rel: path.relative(root, abs),
300
+ bytes: Buffer.byteLength(raw),
301
+ owner: parseLockOwner(raw).pid,
302
+ ageMs,
303
+ stale: Boolean(stale),
304
+ reason: stale?.reason || null,
305
+ })
306
+ }
307
+ }
308
+ walk(root, 1)
309
+ return found
310
+ }
311
+
312
+ /**
313
+ * 释放遗留锁。force=true 时连"看不出遗弃"的锁也一并清(手动修复入口用它,调用方必须
314
+ * 是显式确认过的操作);默认只清 inspectLock 判定为遗弃的那些。
315
+ */
316
+ export function releaseStaleLocks({ force = false, root, now = Date.now() } = {}) {
317
+ const scanned = scanMemoryLocks({ root, now })
318
+ const released = []
319
+ const kept = []
320
+ for (const lock of scanned) {
321
+ if (!lock.stale && !force) { kept.push(lock); continue }
322
+ try {
323
+ fs.unlinkSync(lock.path)
324
+ released.push({ ...lock, reason: lock.reason || 'forced' })
325
+ lockEvent({
326
+ level: 'info',
327
+ code: 'MEMU_LOCK_RELEASED',
328
+ message: `released a stale memory store lock (${lock.reason || 'forced'}): ${lock.rel}`,
329
+ detail: { lockPath: lock.path, reason: lock.reason || 'forced', owner: lock.owner, ageMs: lock.ageMs },
330
+ repair: 'release-stale-locks',
331
+ })
332
+ } catch (error) {
333
+ kept.push({ ...lock, error: error?.code || String(error?.message || error) })
334
+ }
335
+ }
336
+ return { scanned: scanned.length, released, kept }
337
+ }
338
+
210
339
  export async function retryStoreWrite(action, attempts = 4) {
211
340
  for (let attempt = 0; ; attempt++) {
212
341
  try { return action() } catch (error) {
@@ -221,25 +350,39 @@ export function withFileLock(file, action) {
221
350
  const lock = `${path.resolve(file)}.lock`
222
351
  if (heldLocks.has(lock)) return action()
223
352
  ensureDir(path.dirname(lock))
224
- const until = Date.now() + 500
353
+ const until = Date.now() + LOCK_ACQUIRE_BUDGET_MS
225
354
  let fd
226
355
  while (fd === undefined) {
227
356
  try {
228
357
  fd = fs.openSync(lock, 'wx', 0o600)
229
- fs.writeFileSync(fd, String(process.pid))
358
+ // pid 写在第一行:旧版本只用一行裸 pid,两种载荷的解析器是同一个 parseLockOwner。
359
+ fs.writeFileSync(fd, `${process.pid}\n${new Date().toISOString()}\n`)
230
360
  } catch (error) {
231
361
  if (error?.code !== 'EEXIST') throw error
232
- try {
233
- const owner = Number(fs.readFileSync(lock, 'utf8'))
234
- if (Number.isSafeInteger(owner) && owner > 0) {
235
- try { process.kill(owner, 0) } catch (probe) {
236
- if (probe?.code === 'ESRCH') { fs.unlinkSync(lock); continue }
237
- }
238
- }
239
- } catch {}
362
+ const stale = inspectLock(lock)
363
+ if (stale) {
364
+ // 遗弃锁就地释放并重试:这是"死锁自愈",不需要调用方重来一遍。
365
+ try { fs.unlinkSync(lock) } catch {}
366
+ lockEvent({
367
+ level: 'warn',
368
+ code: 'MEMU_LOCK_BROKEN',
369
+ reason: stale.reason,
370
+ message: `released a stale memory store lock (${stale.reason}): ${path.basename(lock)}`,
371
+ detail: stale.detail,
372
+ hint: 'A lock whose owner process no longer exists (or whose payload was never written) is abandoned. Releasing it is safe: a live owner is never touched.',
373
+ repair: 'release-stale-locks',
374
+ })
375
+ continue
376
+ }
240
377
  if (Date.now() >= until) {
241
378
  const busy = new Error(`memory store is busy: ${path.basename(file)}; retry the operation`)
242
379
  busy.code = 'DSH_MEMU_STORE_BUSY'
380
+ // 诊断要能回答"谁占着、占了多久",光有一句 busy 查不动。
381
+ let owner = null
382
+ try { owner = parseLockOwner(fs.readFileSync(lock, 'utf8')).pid } catch {}
383
+ busy.lockPath = lock
384
+ busy.owner = owner
385
+ busy.ageMs = lockAgeMs(lock)
243
386
  throw busy
244
387
  }
245
388
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10)
package/lib/private.js CHANGED
@@ -78,6 +78,18 @@ export function buildPrivateConsolidationPrompt(sessionId) {
78
78
  ].filter((part) => part && part.trim()).join('\n')
79
79
  }
80
80
 
81
+ /**
82
+ * 一句话说清一个失败原因。
83
+ *
84
+ * 早先这里只写 "... failed" 就返回:诊断页照着这条去查什么也查不到,等于把
85
+ * 报错留在原地。带上 code + message,诊断记录本身就有可复制的证据。
86
+ */
87
+ function describeError(error) {
88
+ if (!error) return 'unknown error'
89
+ const code = typeof error.code === 'string' ? error.code : ''
90
+ const message = String(error.message || error)
91
+ return code && !message.startsWith(code) ? code + ': ' + message : message
92
+ }
81
93
  function noticeMessage(text, summary) {
82
94
  return createUserMessage({
83
95
  content: [{ type: 'text', text }],
@@ -1856,8 +1868,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
1856
1868
  try {
1857
1869
  const queued = handle.agent.followup(noticeMessage(guidance.text, '整理收尾提示'))
1858
1870
  accounting.dispatch(guidance.text, 'wrapup')
1859
- Promise.resolve(queued).catch(() => warn('consolidation wrapup followup failed'))
1860
- } catch { warn('consolidation wrapup followup failed') }
1871
+ Promise.resolve(queued).catch((error) => warn('consolidation wrapup followup failed: ' + describeError(error)))
1872
+ } catch (error) { warn('consolidation wrapup followup failed: ' + describeError(error)) }
1861
1873
  }
1862
1874
  }
1863
1875
  return
package/lib/rpc.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  storageHealth, effectiveScope, summarizeIndex, getPromptDomains, addPromptDomain, removePromptDomain, memoryRevision, memoryStamp, noteMemoryBeat,
9
9
  } from './state.js'
10
10
  import { commit, closeMemuResident, prewarmMemuResident } from './memu.js'
11
- import { privateList, privateUpdate, privateRemember, privateRecall, privateArchive, privateDelete, previewDelete, restoreDeleted, globalList, globalRecall, domainOf, decayStrength, appliesToDomain, importMemories, recordImportBatch, revertImportBatch, resolveMemoryReview, visibleToSession, isMemoryEligible } from './memory.js'
11
+ import { privateList, privateUpdate, privateRemember, privateRecall, privateArchive, privateDelete, previewDelete, restoreDeleted, globalList, globalRecall, globalSetStatus, globalDelete, domainOf, decayStrength, appliesToDomain, importMemories, recordImportBatch, revertImportBatch, resolveMemoryReview, visibleToSession, isMemoryEligible } from './memory.js'
12
12
  import { normalizeMemoryContext } from './context.js'
13
13
  import { requestPrivateConsolidation } from './private.js'
14
14
  import { listHostModelOptions, discoverForkModels, redactConsolidationSettings, disposeConsolidationRoute } from './fork-model.js'
@@ -28,6 +28,11 @@ import { clearSuppression, suppressionSet } from './auto-link/suppression.js'
28
28
  import { getAttachment, attachmentThumbnail, attachmentPreview, exportMediaBundle, importMediaBundle, streamMediaExport, importMediaStream } from './media.js'
29
29
  import { listEvents, logStats, clearEvents, record } from './activity-log.js'
30
30
  import { redactSecrets, warn } from './paths.js'
31
+ import {
32
+ listDiagnostics, diagnosticStats, diagnosticAlerts, acknowledgeDiagnostics, clearDiagnostics,
33
+ diagnosticsDir as diagnosticsDirectory,
34
+ } from './diagnostics.js'
35
+ import { runEnvironmentCheck, repairEnvironment, SAFE_REPAIRS, MANUAL_REPAIRS, REPAIR_LABELS } from './environment-check.js'
31
36
  import { ALL_LEXICON_ID, GLOBAL_LEXICON_ID } from './lexicon.js'
32
37
  import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
33
38
 
@@ -73,7 +78,10 @@ function requireSessionId(payload) {
73
78
  // entry's dispatch consumes `payload.libraryId` — or, for updateMemory and
74
79
  // archiveMemory, falls back to the same persisted session binding that
75
80
  // `routeLibraryId` resolves — so the target authorized here is exactly the
76
- // target dispatch works on. Endpoints that are session- or host-scoped
81
+ // target dispatch works on. updateMemory/archiveMemory/deleteMemory are
82
+ // additionally dual-scope: an explicit `scope:'global'` addresses the global
83
+ // store and is authorized by authorizeGlobalReviewRoute, never as a library.
84
+ // Endpoints that are session- or host-scoped
77
85
  // (getState, getSidebarState, initSession, setLibrary, setFolderPolicy, engine
78
86
  // and settings management, …) are not library-addressed: their credential is
79
87
  // the host's own requestRejection plus, for session-scoped reads, the session
@@ -172,6 +180,13 @@ async function authorizeGlobalLexiconRoute(connection, req, endpoint, payload) {
172
180
  }
173
181
 
174
182
  async function authorizeLibraryRoute(connection, req, endpoint, payload, libraryId = routeLibraryId(endpoint, payload)) {
183
+ // Global lifecycle (archive/restore/delete via scope:'global') is management-plane
184
+ // like the global review queue, never a private-library target: it follows the
185
+ // same credential model, and naming a library alongside it is a scope conflict.
186
+ if (payload?.scope === 'global' && ['archiveMemory', 'updateMemory', 'deleteMemory'].includes(endpoint)) {
187
+ if (String(payload?.libraryId || '').trim()) return false
188
+ return authorizeGlobalReviewRoute(connection, req, endpoint, payload)
189
+ }
175
190
  // Review endpoints are dual-scope: without an explicit libraryId they address
176
191
  // the global curator queue, which follows its own management model.
177
192
  if ((endpoint === 'listReviews' || endpoint === 'resolveReview') && !String(payload?.libraryId || '').trim()) {
@@ -1389,6 +1404,16 @@ async function dispatch(ctx, endpoint, payload = {}) {
1389
1404
  const id = String(payload?.id || '')
1390
1405
  if (!id) throw new Error('id is required')
1391
1406
  const patch = payload?.patch || {}
1407
+ // 全局条目内容仍由 curator 写(硬规则 2):管理面这里只开放「从归档恢复」,
1408
+ // 其余字段一律拒绝,不做静默丢弃。
1409
+ if (payload?.scope === 'global') {
1410
+ if (String(payload?.libraryId || '').trim()) throw new Error('global scope takes no libraryId')
1411
+ const keys = Object.keys(patch)
1412
+ if (keys.length !== 1 || keys[0] !== 'status' || patch.status !== 'active') {
1413
+ throw new Error('global memories only support restoring to active here; content stays curator-written')
1414
+ }
1415
+ return globalSetStatus({ id, status: 'active' })
1416
+ }
1392
1417
  // `layer` is here so the browser can promote a short_term draft to long_term,
1393
1418
  // which is the one upgrade path memory.js supports in place.
1394
1419
  // `source` is writable: correcting provenance is the point of showing it.
@@ -1975,6 +2000,10 @@ async function dispatch(ctx, endpoint, payload = {}) {
1975
2000
  case 'archiveMemory': {
1976
2001
  const id = String(payload?.id || '')
1977
2002
  if (!id) throw new Error('memory id is required')
2003
+ if (payload?.scope === 'global') {
2004
+ if (String(payload?.libraryId || '').trim()) throw new Error('global scope takes no libraryId')
2005
+ return globalSetStatus({ id, status: 'archived' })
2006
+ }
1978
2007
  if (payload?.libraryId) return privateArchive({ libraryId: String(payload.libraryId), id })
1979
2008
  return privateArchive({ exec: execFor(requireSessionId(payload)), id })
1980
2009
  }
@@ -1984,6 +2013,15 @@ async function dispatch(ctx, endpoint, payload = {}) {
1984
2013
  // hallucinated id away from erasing a memory it never read.
1985
2014
  const id = String(payload?.id || '')
1986
2015
  if (!id) throw new Error('memory id is required')
2016
+ // 全局删除走显式 scope:'global'(管理面鉴权):没有私有库目标,也没有
2017
+ // preview/restore 撤销缓冲——安全网是两段确认 + 删除前整库备份。
2018
+ if (payload?.scope === 'global') {
2019
+ if (String(payload?.libraryId || '').trim()) throw new Error('global scope takes no libraryId')
2020
+ if (payload?.preview === true || payload?.restore === true) throw new Error('global delete has no preview/restore buffer; it is guarded by two-step confirmation and a fresh backup')
2021
+ if (payload?.confirmed !== true) throw new Error('permanently deleting a memory requires explicit confirmation')
2022
+ const safety = await backupDatabases()
2023
+ return { ...await globalDelete({ id }), safety }
2024
+ }
1987
2025
  const libraryId = String(payload?.libraryId || '')
1988
2026
  if (!libraryId) throw new Error('libraryId is required')
1989
2027
  if (!getLibrary(libraryId)) throw new Error('library not found')
@@ -2172,6 +2210,32 @@ async function dispatch(ctx, endpoint, payload = {}) {
2172
2210
  // single accidental click away.
2173
2211
  if (payload?.confirmed !== true) throw new Error('clearing the activity log requires explicit confirmation')
2174
2212
  return clearEvents()
2213
+ // ---------------------------------------------------------------- 诊断(2026-11-21)
2214
+ // 这一组只服务 WebUI 的"诊断"页:插件内部故障(向量 profile、嵌入 worker、遗留锁、
2215
+ // 引擎环境)的取证面。与活动日志刻意分开——活动日志说的是"记忆发生了什么",
2216
+ // 这里说的是"插件自己哪里坏了、怎么修"。
2217
+ case 'getDiagnostics':
2218
+ return {
2219
+ ...listDiagnostics({ limit: payload?.limit, level: payload?.level, scope: payload?.scope, q: payload?.q, since: payload?.since }),
2220
+ stats: diagnosticStats(),
2221
+ dir: diagnosticsDirectory(),
2222
+ }
2223
+ case 'getDiagnosticAlerts':
2224
+ return diagnosticAlerts()
2225
+ case 'acknowledgeDiagnostics':
2226
+ return acknowledgeDiagnostics({ keys: payload?.keys, codes: payload?.codes })
2227
+ case 'clearDiagnostics':
2228
+ if (payload?.confirmed !== true) throw new Error('clearing diagnostics requires explicit confirmation')
2229
+ return clearDiagnostics()
2230
+ case 'runEnvironmentCheck':
2231
+ return runEnvironmentCheck({ deep: payload?.deep === true })
2232
+ case 'repairEnvironment': {
2233
+ if (payload?.confirmed !== true) throw new Error('repairing the environment requires explicit confirmation')
2234
+ const actions = (Array.isArray(payload?.actions) ? payload.actions : []).map(String).filter(Boolean)
2235
+ return await repairEnvironment({ actions, confirmed: true })
2236
+ }
2237
+ case 'getRepairOptions':
2238
+ return { safe: [...SAFE_REPAIRS], manual: [...MANUAL_REPAIRS], labels: { ...REPAIR_LABELS } }
2175
2239
  default:
2176
2240
  throw new Error(`unknown endpoint: ${endpoint}`)
2177
2241
  }
package/lib/tools.js CHANGED
@@ -8,8 +8,7 @@ import { engineStatus, ENGINE_VERSION } from './engine.js'
8
8
  import { getMissingVectorLibraries } from './local-vector-service.js'
9
9
  import { centeredSnippetWindow } from './snippet.js'
10
10
  import { redactSecrets } from './paths.js'
11
- import { linkEntries, createEntity, listEntities, updateRelationship } from './graph.js'
12
- import { normalizeEntityName } from './private-links.js'
11
+ import { linkEntries, linkNamedEntity, updateRelationship } from './graph.js'
13
12
  import { autoLinkPrivateMemories } from './private-links.js'
14
13
  import { getSettings, listLibraries, getLibrary, loadPrivateIndex, loadGlobalIndex, storageHealth, syncActivity } from './state.js'
15
14
  import { lexiconSearch, lexiconSources } from './lexicon-scope.js'
@@ -377,7 +376,7 @@ export function registerTools(ctx, { only = null } = {}) {
377
376
  kind: { type: 'string', description: 'relation, commitment, event, person, conflict or supersede; required when linking. supersede marks a newer version replacing an older statement of the same fact.' },
378
377
  note: { type: 'string', required: true, description: '8-500 character reason grounded in the conversation, not a guess. For a memu_private_link_suggest candidate, quote the transcript line that proves the same entity or event.' },
379
378
  confidence: { type: 'number', description: '0-1 confidence, default 0.7.' },
380
- entity: { type: 'object', properties: { name: { type: 'string' }, kind: { type: 'string' } }, additionalProperties: true, description: 'Optional named entity to create and link to instead of to; an entity with the same normalized name is reused (case/width-insensitive). Use only an explicit identity, never infer a person from an ambiguous pronoun.' },
379
+ entity: { type: 'object', properties: { name: { type: 'string' }, kind: { type: 'string' } }, additionalProperties: true, description: 'Optional named entity to create and link to instead of to; an entity with the same normalized name is reused (case/width-insensitive). New names require a complete quoted, introduced, or separately delimited name in the source memory; sentence fragments and a name invented only in the note are rejected. Existing names and aliases are reused. Never infer a person from an ambiguous pronoun.' },
381
380
  relationship: { type: 'object', properties: {
382
381
  fromEntity: { type: 'string' }, toEntity: { type: 'string' },
383
382
  evidenceIds: { type: 'array', items: { type: 'string' } },
@@ -393,23 +392,8 @@ export function registerTools(ctx, { only = null } = {}) {
393
392
  // 完整 history(≤50 版)不进模型上下文:只回一行,需要细节时再查。
394
393
  return `已更新关系 ${r.fromId ?? relation.fromEntity}→${r.toId ?? relation.toEntity} · revision ${r.revision ?? '?'} · evidence ${Array.isArray(r.evidenceIds) ? r.evidenceIds.length : 0}`
395
394
  }
396
- let toId = args.to
397
- if (args.entity) {
398
- const name = String(args.entity.name || '').trim()
399
- const kind = args.entity.kind || 'person'
400
- const normalized = normalizeEntityName(name)
401
- const existing = listEntities({ exec }).items.find((item) => normalizeEntityName(item.name) === normalized
402
- || (Array.isArray(item.aliases) && item.aliases.some((alias) => normalizeEntityName(alias) === normalized)))
403
- if (existing) {
404
- if (existing.kind !== kind) throw new Error(`entity "${name}" already exists as ${existing.kind}; use that kind instead of ${kind}`)
405
- toId = existing.id
406
- } else {
407
- // worker 显式点名只创建实体与一条非 auto 边,不等于确认:
408
- // allowWorkerAssertion 在 v3 是预留开关,确认仍由用户完成。
409
- toId = createEntity({ exec, name, kind, status: 'provisional', origin: 'worker' }).id
410
- }
411
- }
412
- return JSON.stringify(linkEntries({ exec, fromId: args.from, toId, kind: args.kind, note: args.note, confidence: args.confidence }))
395
+ if (args.entity) return JSON.stringify(linkNamedEntity({ exec, fromId: args.from, entity: args.entity, kind: args.kind, note: args.note, confidence: args.confidence }))
396
+ return JSON.stringify(linkEntries({ exec, fromId: args.from, toId: args.to, kind: args.kind, note: args.note, confidence: args.confidence }))
413
397
  },
414
398
  ))
415
399