dsh-memu-memory 1.3.12 → 1.3.14

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/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
@@ -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
 
@@ -1307,7 +1312,9 @@ async function dispatch(ctx, endpoint, payload = {}) {
1307
1312
  if (!getLibrary(id)) throw new Error('library not found')
1308
1313
  if (getLibrary(id).archived !== true) throw new Error('archive the library before deleting it')
1309
1314
  const safety = await backupDatabases()
1310
- const result = deleteLibrary(id)
1315
+ // 绑定会话还在的库默认拒绝删除(state.deleteLibrary 的新守卫)。force 只在用户
1316
+ // 显式确认过时透传:宿主没发 session/disposed 的死绑定不能变成"永远删不掉"。
1317
+ const result = deleteLibrary(id, { force: payload?.confirmed === true && payload?.force === true })
1311
1318
  if (!result.ok) throw new Error(result.error)
1312
1319
  return { ok: true, safety, archived: archivedLibraryView() }
1313
1320
  }
@@ -2205,6 +2212,32 @@ async function dispatch(ctx, endpoint, payload = {}) {
2205
2212
  // single accidental click away.
2206
2213
  if (payload?.confirmed !== true) throw new Error('clearing the activity log requires explicit confirmation')
2207
2214
  return clearEvents()
2215
+ // ---------------------------------------------------------------- 诊断(2026-11-21)
2216
+ // 这一组只服务 WebUI 的"诊断"页:插件内部故障(向量 profile、嵌入 worker、遗留锁、
2217
+ // 引擎环境)的取证面。与活动日志刻意分开——活动日志说的是"记忆发生了什么",
2218
+ // 这里说的是"插件自己哪里坏了、怎么修"。
2219
+ case 'getDiagnostics':
2220
+ return {
2221
+ ...listDiagnostics({ limit: payload?.limit, level: payload?.level, scope: payload?.scope, q: payload?.q, since: payload?.since }),
2222
+ stats: diagnosticStats(),
2223
+ dir: diagnosticsDirectory(),
2224
+ }
2225
+ case 'getDiagnosticAlerts':
2226
+ return diagnosticAlerts()
2227
+ case 'acknowledgeDiagnostics':
2228
+ return acknowledgeDiagnostics({ keys: payload?.keys, codes: payload?.codes })
2229
+ case 'clearDiagnostics':
2230
+ if (payload?.confirmed !== true) throw new Error('clearing diagnostics requires explicit confirmation')
2231
+ return clearDiagnostics()
2232
+ case 'runEnvironmentCheck':
2233
+ return runEnvironmentCheck({ deep: payload?.deep === true })
2234
+ case 'repairEnvironment': {
2235
+ if (payload?.confirmed !== true) throw new Error('repairing the environment requires explicit confirmation')
2236
+ const actions = (Array.isArray(payload?.actions) ? payload.actions : []).map(String).filter(Boolean)
2237
+ return await repairEnvironment({ actions, confirmed: true })
2238
+ }
2239
+ case 'getRepairOptions':
2240
+ return { safe: [...SAFE_REPAIRS], manual: [...MANUAL_REPAIRS], labels: { ...REPAIR_LABELS } }
2208
2241
  default:
2209
2242
  throw new Error(`unknown endpoint: ${endpoint}`)
2210
2243
  }
package/lib/state.js CHANGED
@@ -661,11 +661,21 @@ export function libraryScopeMissing(lib) {
661
661
 
662
662
  // Hard delete: the sqlite store and its sidecar index leave with the state entry.
663
663
  // Only ever called on an already-archived library, so the caller had to confirm twice.
664
- export function deleteLibrary(id) {
664
+ // `force` exists for the one legitimate case the state cannot see: the caller already
665
+ // unbound every session and knows it. Without it, a library that a live conversation
666
+ // still points at cannot be deleted — the sweep used to be able to put an in-use
667
+ // library into the only state `deleteLibrary` accepts (2026-11-21 外部报告).
668
+ export function deleteLibrary(id, { force = false } = {}) {
665
669
  if (!isSafeId(id)) throw new Error('invalid library id')
666
670
  const state = loadState()
667
671
  if (!state.libraries[id]) return { ok: false, error: 'library not found' }
668
672
  if (state.libraries[id].archived !== true) return { ok: false, error: 'archive the library before deleting it' }
673
+ // 只拦「危险归档 + 仍在用」:扫描误归档的那一类才有一键删掉全部记忆的风险。
674
+ // 用户主动归档仍有绑定会话时照旧允许(删除会连同绑定一起清掉,这是既有语义);
675
+ // 冷数据的旧归档同理放行,否则本机 rp / ai中转站 这类库会变成"永远删不掉"。
676
+ if (!force && archivedWhileInUse(state.libraries[id], { inUse: inUseLibraryIds(state).has(id) })) {
677
+ return { ok: false, error: 'this library was archived while a conversation still uses it; unbind or delete those sessions first (force overrides)' }
678
+ }
669
679
  const activeVectorDb = removeActiveLibrary(id)
670
680
  const legacyVectorDb = path.join(librariesDir(), id + '.sqlite3')
671
681
  delete state.libraries[id]
@@ -788,11 +798,60 @@ export function adoptDefaultLibrary(libraryId, cwd) {
788
798
  return { id: libraryId, ...lib, adopted: true }
789
799
  }
790
800
 
791
- export function archiveLibrary(id) {
801
+ /**
802
+ * 哪些库正被真实会话使用:有存活绑定(`sessionGone !== true`)指向它即算在用。
803
+ *
804
+ * 为什么需要这个判据:归档扫描(cycle.js `runLibraryHousekeeping`)以前只看
805
+ * workspaceRegistry 里注册的目录。IM 插件数据目录、profile 下的目录这类 scope 永远不在
806
+ * 注册表里,于是「建库 → 176 秒后被归档 → 绑定会话继续读写 9 小时」这种自相矛盾的状态
807
+ * 会稳定发生(2026-11-21 外部报告:归档后 172 条活动、6 次召回全部成功,而 UI 里库已经
808
+ * 消失,且它恰好处于 `deleteLibrary` 唯一允许删除的状态)。
809
+ *
810
+ * 只认绑定关系、不掺时间窗口:过期时间会让「刚打开就被归档」在边界上复现,而绑定关系是
811
+ * 确定的事实。传 state 进来是为了让 sweep 一次读盘、只算一次。
812
+ */
813
+ export function inUseLibraryIds(state = null) {
814
+ const snapshot = state || loadState()
815
+ const ids = new Set()
816
+ for (const binding of Object.values(snapshot.sessions || {})) {
817
+ if (!binding || binding.sessionGone === true) continue
818
+ const libraryId = binding.libraryId
819
+ if (!libraryId || !snapshot.libraries?.[libraryId]) continue
820
+ ids.add(libraryId)
821
+ }
822
+ return ids
823
+ }
824
+
825
+ export function isLibraryInUse(id) {
826
+ return Boolean(id) && inUseLibraryIds().has(id)
827
+ }
828
+
829
+ // 1.3.13 及更早的归档没有 `archivedBy`:分不清是用户点的归档还是老扫描误归档。
830
+ // 对这类库只认「还热」的(lastUsedAt 在 14 天内),冷归档按用户意图对待。
831
+ export const ARCHIVE_REVIVE_FRESH_MS = 14 * 86_400_000
832
+
833
+ /**
834
+ * 「归档了但其实还在用」——扫描误归档的判据,同时也是删除守卫的判据。
835
+ *
836
+ * 用户主动归档(`archivedBy === 'user'`)永远不算;扫描归档的(`'sweep'`)永远算;
837
+ * 旧数据按 lastUsedAt 的新鲜度判。两处共用同一个函数,避免"扫描复活、删除又放行"这种
838
+ * 两套口径各说各话。
839
+ */
840
+ export function archivedWhileInUse(lib, { inUse = false, now = Date.now() } = {}) {
841
+ if (!inUse || !lib) return false
842
+ if (lib.archivedBy === 'user') return false
843
+ if (lib.archivedBy === 'sweep') return true
844
+ const lastUsed = Date.parse(lib.lastUsedAt || '') || 0
845
+ return lastUsed > 0 && now - lastUsed <= ARCHIVE_REVIVE_FRESH_MS
846
+ }
847
+
848
+ /** `by` 记录是谁归档的:用户的主动归档不该被扫描悄悄复活。 */
849
+ export function archiveLibrary(id, { by = 'user' } = {}) {
792
850
  const state = loadState()
793
851
  if (!state.libraries[id]) return false
794
852
  state.libraries[id].archived = true
795
853
  state.libraries[id].archivedAt = stamp()
854
+ state.libraries[id].archivedBy = by
796
855
  saveState(state)
797
856
  return true
798
857
  }
@@ -807,6 +866,7 @@ export function restoreLibrary(id) {
807
866
  if (!lib) return { ok: false, error: 'library not found' }
808
867
  lib.archived = false
809
868
  lib.archivedAt = null
869
+ lib.archivedBy = null
810
870
  lib.revivedAt = stamp()
811
871
  lib.lastUsedAt = stamp()
812
872
  saveState(state)
@@ -842,6 +902,15 @@ export function ensureSession(sessionId, { cwd, agentPreset, libraryId = null, c
842
902
  const previous = initial.sessions[sessionId]
843
903
  if (previous?.libraryId && initial.libraries[previous.libraryId]) {
844
904
  const boundLibrary = initial.libraries[previous.libraryId]
905
+ // 一个正在被这个会话读写的库不该停在 archived:归档的语义是「隐藏、准备清理」,
906
+ // 而在用的库既不该消失,也不该落进 `deleteLibrary` 唯一允许删除的状态。旧版扫描
907
+ // 只要 scope 不在 workspaceRegistry 就归档,而这条快路径从不复活,于是库能一边
908
+ // 「归档」一边长数据 9 小时。用户主动归档(archivedBy === 'user')除外。
909
+ if (boundLibrary.archived === true && boundLibrary.archivedBy !== 'user') {
910
+ restoreLibrary(previous.libraryId)
911
+ const revived = loadState().sessions[sessionId]
912
+ if (revived) return revived
913
+ }
845
914
  const libraryScope = normalizeCwd(boundLibrary.scopeKey || '')
846
915
  // Repair the old placeholder bucket as soon as the live conversation reveals
847
916
  // its folder. Without this, every historical Default library stays mislabelled
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