dsh-memu-memory 1.3.12 → 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.
- package/CHANGELOG.md +17 -0
- package/README.md +2 -2
- package/docs/contributing.md +14 -2
- package/docs/memory-semantics.md +2 -2
- package/docs/troubleshooting.md +43 -1
- package/lib/auto-link/candidates.js +10 -5
- package/lib/auto-link/terminology.js +34 -18
- package/lib/binding-diagnostics.js +1 -1
- package/lib/client.js +335 -36
- package/lib/diagnostics.js +514 -0
- package/lib/environment-check.js +325 -0
- package/lib/graph.js +94 -21
- package/lib/index.js +70 -2
- package/lib/local-embedding-manager.js +39 -5
- package/lib/paths.js +153 -10
- package/lib/private.js +14 -2
- package/lib/rpc.js +31 -0
- package/lib/tools.js +4 -20
- package/lib/vector-profile.js +302 -8
- package/lib/webui/graph-view.bundle.js +1 -1
- package/lib/webui/graph-view.js +1 -2
- package/lib/webui/standalone.js +2 -2
- package/package.json +1 -1
- package/tests/auto-link-candidates.test.mjs +71 -0
- package/tests/client-render.test.mjs +116 -3
- package/tests/diagnostics.test.mjs +257 -0
- package/tests/environment-check.test.mjs +159 -0
- package/tests/graph-view.test.mjs +31 -3
- package/tests/graph.test.mjs +110 -0
- package/tests/tools.test.mjs +95 -0
- package/tests/webui-auth.test.mjs +1 -0
|
@@ -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
|
-
|
|
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
|
|
196
|
-
|
|
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() +
|
|
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
|
-
|
|
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
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
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
|
|
|
@@ -2205,6 +2210,32 @@ async function dispatch(ctx, endpoint, payload = {}) {
|
|
|
2205
2210
|
// single accidental click away.
|
|
2206
2211
|
if (payload?.confirmed !== true) throw new Error('clearing the activity log requires explicit confirmation')
|
|
2207
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 } }
|
|
2208
2239
|
default:
|
|
2209
2240
|
throw new Error(`unknown endpoint: ${endpoint}`)
|
|
2210
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,
|
|
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).
|
|
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
|
-
|
|
397
|
-
|
|
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
|
|