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.
- package/CHANGELOG.md +28 -0
- package/README.md +3 -3
- package/README.zh.md +1 -1
- package/docs/contributing.md +14 -2
- package/docs/memory-semantics.md +4 -2
- package/docs/troubleshooting.md +52 -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 +431 -69
- 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/memory.js +81 -0
- package/lib/paths.js +153 -10
- package/lib/private.js +14 -2
- package/lib/rpc.js +66 -2
- 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 +226 -3
- package/tests/diagnostics.test.mjs +257 -0
- package/tests/environment-check.test.mjs +159 -0
- package/tests/global-lifecycle.test.mjs +130 -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 +73 -0
- package/tests/webui.test.mjs +2 -1
|
@@ -0,0 +1,514 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
import { dataDir, ensureDir, redactSecrets, stamp, setLockEventSink } from './paths.js'
|
|
5
|
+
|
|
6
|
+
// 诊断面(§15):插件内部的失败从"只有一行 warn"变成一条可检索、可修复的记录。
|
|
7
|
+
//
|
|
8
|
+
// 刻意与 `logs/activity.jsonl` 分开:activity 是"记忆运行日志"(有 kind/ok/降级语义,
|
|
9
|
+
// 展示在 WebUI 日志页);这里是"插件内部故障档案",只放错误/警告 + 修复线索,独立页面
|
|
10
|
+
// 展示、独立清理。manifest 摘要、运行时目录、死锁这类内部报错**不进**日志页——那条
|
|
11
|
+
// 通道已经够吵,而诊断需要的是"为什么坏、怎么修、能不能一键修"。
|
|
12
|
+
//
|
|
13
|
+
// 另一个刻意的取舍:诊断写入永远不抛错、不 warn(会递归),失败就静默放弃。诊断自己
|
|
14
|
+
// 坏掉不能连累记忆主路径。
|
|
15
|
+
const MAX_BYTES = 2 * 1024 * 1024
|
|
16
|
+
const RING_LIMIT = 500
|
|
17
|
+
const DEDUPE_WINDOW_MS = 60_000
|
|
18
|
+
const MAX_MESSAGE = 2000
|
|
19
|
+
const LEVELS = new Set(['error', 'warn', 'info'])
|
|
20
|
+
|
|
21
|
+
export function diagnosticsDir() {
|
|
22
|
+
return path.join(dataDir(), 'diagnostics')
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function eventsFile() {
|
|
26
|
+
return path.join(diagnosticsDir(), 'events.jsonl')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function rotatedFile() {
|
|
30
|
+
return path.join(diagnosticsDir(), 'events.1.jsonl')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function ackFile() {
|
|
34
|
+
return path.join(diagnosticsDir(), 'acknowledged.json')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// 进程内环形缓冲:最新在后。落盘是为了跨重启仍能回答"上次为什么坏",内存是为了
|
|
38
|
+
// 页面轮询不必每次读盘。
|
|
39
|
+
let ring = []
|
|
40
|
+
let loaded = false
|
|
41
|
+
let bytesCache = null
|
|
42
|
+
const lastByKey = new Map()
|
|
43
|
+
const ack = new Map()
|
|
44
|
+
let ackLoaded = false
|
|
45
|
+
|
|
46
|
+
function keyOf(entry) {
|
|
47
|
+
return [entry.scope, entry.code, entry.message].join('\u0000')
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 稳定短哈希:确认状态按"同一类问题"记账,不按随机事件 id。 */
|
|
51
|
+
export function diagnosticKeyHash(entry) {
|
|
52
|
+
return crypto.createHash('sha256').update([entry?.scope, entry?.code, entry?.message].join('\u0000')).digest('hex').slice(0, 16)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function pruneValue(value, depth) {
|
|
56
|
+
if (depth > 3) return '[depth]'
|
|
57
|
+
if (typeof value === 'string') return redactSecrets(value).slice(0, 2000)
|
|
58
|
+
if (typeof value === 'number' || typeof value === 'boolean' || value === null) return value
|
|
59
|
+
if (value === undefined) return null
|
|
60
|
+
if (Array.isArray(value)) return value.slice(0, 20).map(item => pruneValue(item, depth + 1))
|
|
61
|
+
if (typeof value === 'object') {
|
|
62
|
+
const out = {}
|
|
63
|
+
for (const key of Object.keys(value).slice(0, 40)) out[key] = pruneValue(value[key], depth + 1)
|
|
64
|
+
return out
|
|
65
|
+
}
|
|
66
|
+
return String(value)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 只保留可 JSON 化、已脱敏、已限长的 detail。 */
|
|
70
|
+
export function shapeDetail(detail) {
|
|
71
|
+
if (detail === undefined || detail === null) return null
|
|
72
|
+
try {
|
|
73
|
+
const pruned = pruneValue(detail, 0)
|
|
74
|
+
return pruned && typeof pruned === 'object' ? pruned : { value: pruned }
|
|
75
|
+
} catch {
|
|
76
|
+
return null
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function normalize(input) {
|
|
81
|
+
if (!input || typeof input !== 'object') return null
|
|
82
|
+
const level = LEVELS.has(input.level) ? input.level : 'error'
|
|
83
|
+
const scope = String(input.scope || 'plugin').trim().toLowerCase().replace(/[^a-z0-9_-]/g, '').slice(0, 40) || 'plugin'
|
|
84
|
+
const code = String(input.code || 'MEMU_DIAGNOSTIC').trim().toUpperCase().replace(/[^A-Z0-9_]/g, '_').slice(0, 64) || 'MEMU_DIAGNOSTIC'
|
|
85
|
+
const rawMessage = String(input.message ?? '').trim()
|
|
86
|
+
const message = (redactSecrets(rawMessage || code)).slice(0, MAX_MESSAGE)
|
|
87
|
+
const at = stamp()
|
|
88
|
+
return {
|
|
89
|
+
id: crypto.randomUUID(),
|
|
90
|
+
at,
|
|
91
|
+
lastAt: at,
|
|
92
|
+
level,
|
|
93
|
+
scope,
|
|
94
|
+
code,
|
|
95
|
+
message,
|
|
96
|
+
detail: shapeDetail(input.detail),
|
|
97
|
+
hint: input.hint ? redactSecrets(String(input.hint)).slice(0, 1000) : null,
|
|
98
|
+
repair: input.repair ? String(input.repair).slice(0, 64) : null,
|
|
99
|
+
manual: input.manual === true,
|
|
100
|
+
// 启动弹窗只看 alert 条目:error 默认弹,warn 只有明确要求才弹(避免一开机就一屏)。
|
|
101
|
+
alert: input.alert === undefined ? level === 'error' : input.alert === true,
|
|
102
|
+
count: 1,
|
|
103
|
+
source: input.source ? String(input.source).slice(0, 60) : null,
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function fileBytes() {
|
|
108
|
+
if (bytesCache !== null) return bytesCache
|
|
109
|
+
try { bytesCache = fs.statSync(eventsFile()).size } catch { bytesCache = 0 }
|
|
110
|
+
return bytesCache
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function rotateIfNeeded() {
|
|
114
|
+
if (fileBytes() <= MAX_BYTES) return
|
|
115
|
+
try { fs.renameSync(eventsFile(), rotatedFile()) } catch {}
|
|
116
|
+
bytesCache = 0
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function appendLine(entry) {
|
|
120
|
+
ensureDir(diagnosticsDir())
|
|
121
|
+
rotateIfNeeded()
|
|
122
|
+
const line = JSON.stringify({ ...entry, lastAt: entry.lastAt }) + '\n'
|
|
123
|
+
fs.writeFileSync(eventsFile(), line, { flag: 'a', mode: 0o600 })
|
|
124
|
+
bytesCache = null
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 写一条诊断。同一 (scope, code, message) 在 60 秒内重复只在内存里记 count,
|
|
129
|
+
* 不再追加行——一次召回风暴不该把 2MB 的档案写完。
|
|
130
|
+
*/
|
|
131
|
+
export function recordDiagnostic(input) {
|
|
132
|
+
try {
|
|
133
|
+
const entry = normalize(input)
|
|
134
|
+
if (!entry) return null
|
|
135
|
+
const key = keyOf(entry)
|
|
136
|
+
const nowMs = Date.now()
|
|
137
|
+
const last = lastByKey.get(key)
|
|
138
|
+
if (last && nowMs - last.lastAtMs < DEDUPE_WINDOW_MS) {
|
|
139
|
+
last.count += 1
|
|
140
|
+
last.lastAt = entry.at
|
|
141
|
+
last.lastAtMs = nowMs
|
|
142
|
+
// 内存里的这条已经是环形缓冲的一员(引用),页面下一轮就会看到 count 变大。
|
|
143
|
+
return last
|
|
144
|
+
}
|
|
145
|
+
entry.lastAtMs = nowMs
|
|
146
|
+
appendLine(entry)
|
|
147
|
+
ring.push(entry)
|
|
148
|
+
while (ring.length > RING_LIMIT) ring.shift()
|
|
149
|
+
lastByKey.set(key, entry)
|
|
150
|
+
return entry
|
|
151
|
+
} catch {
|
|
152
|
+
return null
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ---------------------------------------------------------------- 错误归类
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* 已知故障码 → 诊断语义(范围、修复动作、修复提示)。
|
|
160
|
+
*
|
|
161
|
+
* 这张表是"诊断信息"的核心:同一个错误在日志里只是字符串,在这里才回答
|
|
162
|
+
* "这是哪一层坏了、能不能自动修、修之前会不会丢数据"。
|
|
163
|
+
*/
|
|
164
|
+
const KNOWN_CODES = Object.freeze({
|
|
165
|
+
VECTOR_PROFILE_MANIFEST_CHANGED: {
|
|
166
|
+
scope: 'vector',
|
|
167
|
+
repair: 'resign-vector-profile',
|
|
168
|
+
hint: 'The catalog manifest of the active embedding profile changed after it was recorded. When only mirror metadata (runtime/sources) moved, re-signing keeps existing vectors usable; a real artifact change requires a rebuild.',
|
|
169
|
+
},
|
|
170
|
+
VECTOR_PROFILE_FINGERPRINT_MISMATCH: {
|
|
171
|
+
scope: 'vector',
|
|
172
|
+
repair: 'rebuild-vector-index',
|
|
173
|
+
manual: true,
|
|
174
|
+
hint: 'The vector space itself changed (dimension/pooling/prefixes/files). Existing vectors cannot be reused; rebuild the local vector index from the memory index.',
|
|
175
|
+
},
|
|
176
|
+
VECTOR_PROFILE_UNKNOWN: {
|
|
177
|
+
scope: 'vector',
|
|
178
|
+
repair: 'resign-vector-profile',
|
|
179
|
+
hint: 'The active catalog id is no longer defined by this plugin version. Switch the vector profile or reinstall the embedding model bundle.',
|
|
180
|
+
},
|
|
181
|
+
VECTOR_PROFILE_PENDING: {
|
|
182
|
+
scope: 'vector',
|
|
183
|
+
manual: true,
|
|
184
|
+
hint: 'The catalog entry has no verified artifact yet. Download and verify the model before activating it.',
|
|
185
|
+
},
|
|
186
|
+
VECTOR_ACTIVE_CORRUPT: {
|
|
187
|
+
scope: 'vector',
|
|
188
|
+
repair: 'repoint-runtime-dir',
|
|
189
|
+
manual: true,
|
|
190
|
+
hint: 'index/vector-active.json is not valid JSON. It is never overwritten automatically; restore it from index/vector-active.json.bak-* or delete it to re-activate a profile.',
|
|
191
|
+
},
|
|
192
|
+
LOCAL_VECTOR_RUNTIME_UNAVAILABLE: {
|
|
193
|
+
scope: 'vector',
|
|
194
|
+
repair: 'repoint-runtime-dir',
|
|
195
|
+
hint: 'The recorded runtime directory does not contain the pinned onnxruntime artifacts. Point the profile at a complete runtime directory under downloads/runtime instead of downloading at run time.',
|
|
196
|
+
},
|
|
197
|
+
LOCAL_VECTOR_MANIFEST_INCOMPLETE: {
|
|
198
|
+
scope: 'vector',
|
|
199
|
+
repair: 'resign-vector-profile',
|
|
200
|
+
hint: 'The active profile lost its stable model id or dimension; re-signing restores both from the catalog.',
|
|
201
|
+
},
|
|
202
|
+
LOCAL_VECTOR_WORKER_EXITED: {
|
|
203
|
+
scope: 'vector',
|
|
204
|
+
repair: 'reinstall-runtime',
|
|
205
|
+
hint: 'The embedding worker process exited before reporting ready. The last stderr lines are captured under detail.stderrTail; a missing or mismatched native module is the usual cause.',
|
|
206
|
+
},
|
|
207
|
+
LOCAL_VECTOR_BAD_READY: {
|
|
208
|
+
scope: 'vector',
|
|
209
|
+
repair: 'reinstall-runtime',
|
|
210
|
+
hint: 'The worker answered but its readiness line did not match the active profile. Reinstall the runtime so the worker and the profile agree.',
|
|
211
|
+
},
|
|
212
|
+
LOCAL_VECTOR_SPAWN_FAILED: {
|
|
213
|
+
scope: 'vector',
|
|
214
|
+
repair: 'reinstall-runtime',
|
|
215
|
+
hint: 'The worker could not be spawned at all (missing interpreter or blocked executable).',
|
|
216
|
+
},
|
|
217
|
+
LOCAL_VECTOR_START_TIMEOUT: {
|
|
218
|
+
scope: 'vector',
|
|
219
|
+
hint: 'The worker never became ready within the boot timeout. Recall falls back to lexical until it does.',
|
|
220
|
+
},
|
|
221
|
+
LOCAL_VECTOR_RESTART_FUSED: {
|
|
222
|
+
scope: 'vector',
|
|
223
|
+
hint: 'The worker crashed repeatedly inside the restart window and the fuse tripped. Wait for the cooldown, then run the environment check to find the cause.',
|
|
224
|
+
},
|
|
225
|
+
DSH_MEMU_STORE_BUSY: {
|
|
226
|
+
scope: 'store',
|
|
227
|
+
repair: 'release-stale-locks',
|
|
228
|
+
hint: 'A *.lock file is held by a process that no longer exists (or holds an unparseable payload). Releasing stale locks is safe: an owner that is still alive is never touched.',
|
|
229
|
+
},
|
|
230
|
+
ENGINE_MISSING: {
|
|
231
|
+
scope: 'engine',
|
|
232
|
+
repair: 'reinstall-engine',
|
|
233
|
+
hint: 'The managed Python engine directory is gone or empty. Reinstalling rebuilds it under engine/<version>/venv.',
|
|
234
|
+
},
|
|
235
|
+
ENGINE_BROKEN: {
|
|
236
|
+
scope: 'engine',
|
|
237
|
+
repair: 'reinstall-engine',
|
|
238
|
+
hint: 'The engine venv exists but cannot import memu. Reinstalling rebuilds the venv and keeps a backup first.',
|
|
239
|
+
},
|
|
240
|
+
ENGINE_VERSION_MISMATCH: {
|
|
241
|
+
scope: 'engine',
|
|
242
|
+
repair: 'reinstall-engine',
|
|
243
|
+
hint: 'The installed engine is not the version this plugin requires; the next bootstrap switches it.',
|
|
244
|
+
},
|
|
245
|
+
})
|
|
246
|
+
|
|
247
|
+
export function classifyError(error) {
|
|
248
|
+
const code = String(error?.code || error?.name || 'MEMU_ERROR').toUpperCase()
|
|
249
|
+
const known = KNOWN_CODES[code] || null
|
|
250
|
+
const message = String(error?.message || error || 'unknown failure')
|
|
251
|
+
const detail = {}
|
|
252
|
+
if (error?.detail && typeof error.detail === 'object') Object.assign(detail, error.detail)
|
|
253
|
+
// VectorStateError 把 extra 摊在自己身上;只挑诊断需要的几个字段,别把整个 error 塞进去。
|
|
254
|
+
for (const field of ['expected', 'actual', 'changedFields', 'catalogId', 'file', 'lockPath', 'owner', 'ageMs', 'libraryId', 'sessionId', 'stderrTail']) {
|
|
255
|
+
if (error?.[field] !== undefined) detail[field] = error[field]
|
|
256
|
+
}
|
|
257
|
+
return {
|
|
258
|
+
scope: known?.scope || 'plugin',
|
|
259
|
+
code,
|
|
260
|
+
message,
|
|
261
|
+
detail: Object.keys(detail).length ? detail : null,
|
|
262
|
+
hint: known?.hint || null,
|
|
263
|
+
repair: known?.repair || null,
|
|
264
|
+
manual: known?.manual === true,
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** 记一个异常;未知错误也记(诊断页要能看见"没归类"的故障)。 */
|
|
269
|
+
export function recordErrorDiagnostic(error, context = {}) {
|
|
270
|
+
const classified = classifyError(error)
|
|
271
|
+
return recordDiagnostic({
|
|
272
|
+
...classified,
|
|
273
|
+
level: context.level || 'error',
|
|
274
|
+
source: context.source || null,
|
|
275
|
+
detail: { ...(classified.detail || {}), ...(context.detail || {}) },
|
|
276
|
+
hint: context.hint || classified.hint,
|
|
277
|
+
repair: context.repair || classified.repair,
|
|
278
|
+
message: context.message || classified.message,
|
|
279
|
+
})
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ---------------------------------------------------------------- 读取
|
|
283
|
+
|
|
284
|
+
function parseLine(line) {
|
|
285
|
+
const text = String(line || '').trim()
|
|
286
|
+
if (!text) return null
|
|
287
|
+
try {
|
|
288
|
+
const value = JSON.parse(text)
|
|
289
|
+
if (!value || typeof value !== 'object' || !value.code) return null
|
|
290
|
+
return {
|
|
291
|
+
id: value.id || crypto.randomUUID(),
|
|
292
|
+
at: value.at || stamp(),
|
|
293
|
+
lastAt: value.lastAt || value.at || stamp(),
|
|
294
|
+
level: LEVELS.has(value.level) ? value.level : 'error',
|
|
295
|
+
scope: String(value.scope || 'plugin'),
|
|
296
|
+
code: String(value.code),
|
|
297
|
+
message: String(value.message || value.code),
|
|
298
|
+
detail: value.detail ?? null,
|
|
299
|
+
hint: value.hint ?? null,
|
|
300
|
+
repair: value.repair ?? null,
|
|
301
|
+
manual: value.manual === true,
|
|
302
|
+
alert: value.alert === true,
|
|
303
|
+
count: Number.isFinite(value.count) && value.count > 0 ? value.count : 1,
|
|
304
|
+
source: value.source ?? null,
|
|
305
|
+
}
|
|
306
|
+
} catch {
|
|
307
|
+
return null
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function readTail(file, maxBytes = 512 * 1024) {
|
|
312
|
+
try {
|
|
313
|
+
const stat = fs.statSync(file)
|
|
314
|
+
const start = Math.max(0, stat.size - maxBytes)
|
|
315
|
+
const fd = fs.openSync(file, 'r')
|
|
316
|
+
try {
|
|
317
|
+
const length = stat.size - start
|
|
318
|
+
const buffer = Buffer.alloc(length)
|
|
319
|
+
fs.readSync(fd, buffer, 0, length, start)
|
|
320
|
+
return { text: buffer.toString('utf8'), truncated: start > 0 }
|
|
321
|
+
} finally { fs.closeSync(fd) }
|
|
322
|
+
} catch {
|
|
323
|
+
return { text: '', truncated: false }
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function ensureLoaded() {
|
|
328
|
+
if (loaded) return
|
|
329
|
+
loaded = true
|
|
330
|
+
try {
|
|
331
|
+
const current = readTail(eventsFile())
|
|
332
|
+
const lines = current.text.split('\n')
|
|
333
|
+
// 只有真的从中间截断时才丢第一行(那半条 JSON 解析不出来,丢了也不冤)。
|
|
334
|
+
// 早先这里无条件 shift:文件小到能整段读进内存时,第一行是完整的记录,
|
|
335
|
+
// 却因为 split 出来的末位空串让 length > 1 而被丢掉——诊断页于是永远空白。
|
|
336
|
+
if (current.truncated && lines.length > 1) lines.shift()
|
|
337
|
+
const parsed = []
|
|
338
|
+
for (const line of lines) {
|
|
339
|
+
const entry = parseLine(line)
|
|
340
|
+
if (entry) parsed.push(entry)
|
|
341
|
+
}
|
|
342
|
+
const rotated = readTail(rotatedFile(), 128 * 1024).text.split('\n').map(parseLine).filter(Boolean)
|
|
343
|
+
ring = [...rotated, ...parsed].slice(-RING_LIMIT)
|
|
344
|
+
for (const entry of ring) lastByKey.set(keyOf(entry), entry)
|
|
345
|
+
} catch {
|
|
346
|
+
ring = []
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function ensureAckLoaded() {
|
|
351
|
+
if (ackLoaded) return
|
|
352
|
+
ackLoaded = true
|
|
353
|
+
try {
|
|
354
|
+
const value = JSON.parse(fs.readFileSync(ackFile(), 'utf8'))
|
|
355
|
+
for (const [key, count] of Object.entries(value?.counts || {})) {
|
|
356
|
+
if (Number.isFinite(count)) ack.set(key, Number(count))
|
|
357
|
+
}
|
|
358
|
+
} catch {}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function persistAck() {
|
|
362
|
+
try {
|
|
363
|
+
ensureDir(diagnosticsDir())
|
|
364
|
+
const counts = {}
|
|
365
|
+
for (const [key, count] of ack.entries()) counts[key] = count
|
|
366
|
+
fs.writeFileSync(ackFile(), JSON.stringify({ version: 1, counts }, null, 2), { encoding: 'utf8', mode: 0o600 })
|
|
367
|
+
} catch {}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** 最新在前;detail 原样返回(已脱敏、已限长)。 */
|
|
371
|
+
export function listDiagnostics(filter = {}) {
|
|
372
|
+
ensureLoaded()
|
|
373
|
+
const limit = Math.max(1, Math.min(500, Number(filter.limit) || 200))
|
|
374
|
+
const level = LEVELS.has(filter.level) ? filter.level : null
|
|
375
|
+
const scope = filter.scope ? String(filter.scope) : null
|
|
376
|
+
const query = filter.q ? String(filter.q).toLowerCase() : null
|
|
377
|
+
const since = filter.since ? Date.parse(filter.since) : null
|
|
378
|
+
const counts = { error: 0, warn: 0, info: 0 }
|
|
379
|
+
for (const entry of ring) counts[entry.level] = (counts[entry.level] || 0) + 1
|
|
380
|
+
const items = ring
|
|
381
|
+
.filter(entry => (level ? entry.level === level : true))
|
|
382
|
+
.filter(entry => (scope ? entry.scope === scope : true))
|
|
383
|
+
.filter(entry => (since && Number.isFinite(since) ? Date.parse(entry.lastAt || entry.at) >= since : true))
|
|
384
|
+
.filter(entry => (query
|
|
385
|
+
? [entry.code, entry.message, entry.hint, entry.source, entry.scope].join(' ').toLowerCase().includes(query)
|
|
386
|
+
: true))
|
|
387
|
+
.slice(-limit)
|
|
388
|
+
.reverse()
|
|
389
|
+
return { items, total: items.length, counts, capped: ring.length >= RING_LIMIT }
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
export function diagnosticStats() {
|
|
393
|
+
ensureLoaded()
|
|
394
|
+
const counts = { error: 0, warn: 0, info: 0 }
|
|
395
|
+
for (const entry of ring) counts[entry.level] = (counts[entry.level] || 0) + 1
|
|
396
|
+
return {
|
|
397
|
+
total: ring.length,
|
|
398
|
+
counts,
|
|
399
|
+
bytes: fileBytes(),
|
|
400
|
+
maxBytes: MAX_BYTES,
|
|
401
|
+
repaired: ring.filter(entry => entry.repair && entry.code === 'MEMU_DIAGNOSTIC_REPAIRED').length,
|
|
402
|
+
path: diagnosticsDir(),
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* 启动弹窗要看的那几条:error 级、alert 未关,且"出现次数比上次确认时更多"。
|
|
408
|
+
* 一条问题修好后不再重复弹,再次出现才弹——否则用户每天开机都要关一次同一个提示。
|
|
409
|
+
*/
|
|
410
|
+
export function diagnosticAlerts() {
|
|
411
|
+
ensureLoaded()
|
|
412
|
+
ensureAckLoaded()
|
|
413
|
+
const grouped = new Map()
|
|
414
|
+
for (const entry of ring) {
|
|
415
|
+
if (!entry.alert) continue
|
|
416
|
+
if (entry.level !== 'error' && entry.level !== 'warn') continue
|
|
417
|
+
const key = diagnosticKeyHash(entry)
|
|
418
|
+
const current = grouped.get(key)
|
|
419
|
+
if (current) {
|
|
420
|
+
current.count += entry.count
|
|
421
|
+
if (Date.parse(entry.lastAt) > Date.parse(current.lastAt)) current.lastAt = entry.lastAt
|
|
422
|
+
continue
|
|
423
|
+
}
|
|
424
|
+
grouped.set(key, {
|
|
425
|
+
key,
|
|
426
|
+
code: entry.code,
|
|
427
|
+
scope: entry.scope,
|
|
428
|
+
message: entry.message,
|
|
429
|
+
hint: entry.hint,
|
|
430
|
+
repair: entry.repair,
|
|
431
|
+
manual: entry.manual,
|
|
432
|
+
level: entry.level,
|
|
433
|
+
count: entry.count,
|
|
434
|
+
lastAt: entry.lastAt,
|
|
435
|
+
acknowledged: ack.get(key) || 0,
|
|
436
|
+
})
|
|
437
|
+
}
|
|
438
|
+
const alerts = [...grouped.values()].filter(alert => alert.count > alert.acknowledged)
|
|
439
|
+
return { alerts, checkedAt: stamp() }
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** 确认(= 知道这件事了)。按同类问题的当前次数记账,不再弹直到它再次出现。 */
|
|
443
|
+
export function acknowledgeDiagnostics({ keys = [], codes = [] } = {}) {
|
|
444
|
+
ensureLoaded()
|
|
445
|
+
ensureAckLoaded()
|
|
446
|
+
const wantKeys = new Set((Array.isArray(keys) ? keys : []).map(String))
|
|
447
|
+
const wantCodes = new Set((Array.isArray(codes) ? codes : []).map(code => String(code).toUpperCase()))
|
|
448
|
+
let changed = 0
|
|
449
|
+
for (const entry of ring) {
|
|
450
|
+
if (!entry.alert) continue
|
|
451
|
+
const key = diagnosticKeyHash(entry)
|
|
452
|
+
if (wantKeys.size && !wantKeys.has(key)) continue
|
|
453
|
+
if (wantCodes.size && !wantCodes.has(String(entry.code).toUpperCase())) continue
|
|
454
|
+
if (!wantKeys.size && !wantCodes.size) continue
|
|
455
|
+
const previous = ack.get(key) || 0
|
|
456
|
+
if (entry.count > previous) { ack.set(key, entry.count); changed += 1 }
|
|
457
|
+
}
|
|
458
|
+
if (changed) persistAck()
|
|
459
|
+
return { acknowledged: changed, remaining: diagnosticAlerts().alerts.length }
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** 记录一次自动修复的结果——修复本身也要留痕,成功失败都算。 */
|
|
463
|
+
// detail 允许是字符串(修好/没修好的一句话)或对象;字符串直接展开会碎成字符键。
|
|
464
|
+
function detailFields(detail) {
|
|
465
|
+
if (!detail) return {}
|
|
466
|
+
if (typeof detail === 'string') return { message: detail }
|
|
467
|
+
if (typeof detail !== 'object' || Array.isArray(detail)) return { message: String(detail) }
|
|
468
|
+
return detail
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
export function recordRepair({ action, ok, detail, message }) {
|
|
472
|
+
return recordDiagnostic({
|
|
473
|
+
level: ok ? 'info' : 'error',
|
|
474
|
+
scope: 'repair',
|
|
475
|
+
code: ok ? 'MEMU_DIAGNOSTIC_REPAIRED' : 'MEMU_DIAGNOSTIC_REPAIR_FAILED',
|
|
476
|
+
message: message || (ok ? `auto repair applied: ${action}` : `auto repair failed: ${action}`),
|
|
477
|
+
detail: { action, ...detailFields(detail) },
|
|
478
|
+
hint: ok ? null : 'The manual repair entry on the diagnostics page runs the same action; a repeated failure usually means a permission or disk problem.',
|
|
479
|
+
repair: ok ? null : action,
|
|
480
|
+
alert: !ok,
|
|
481
|
+
source: 'repair',
|
|
482
|
+
})
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
export function clearDiagnostics() {
|
|
486
|
+
ensureLoaded()
|
|
487
|
+
const removed = ring.length
|
|
488
|
+
ring = []
|
|
489
|
+
lastByKey.clear()
|
|
490
|
+
ack.clear()
|
|
491
|
+
ackLoaded = true
|
|
492
|
+
persistAck()
|
|
493
|
+
try { fs.rmSync(eventsFile(), { force: true }) } catch {}
|
|
494
|
+
try { fs.rmSync(rotatedFile(), { force: true }) } catch {}
|
|
495
|
+
bytesCache = 0
|
|
496
|
+
return { removed }
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// ---------------------------------------------------------------- 锁事件接线
|
|
500
|
+
|
|
501
|
+
// paths.js 不 import 本模块(否则成环),它只把锁事件扔进 sink,方向永远是单向的。
|
|
502
|
+
setLockEventSink(event => {
|
|
503
|
+
recordDiagnostic({
|
|
504
|
+
level: event?.level || 'warn',
|
|
505
|
+
scope: 'store',
|
|
506
|
+
code: event?.code || 'MEMU_LOCK_EVENT',
|
|
507
|
+
message: event?.message || 'memory store lock event',
|
|
508
|
+
detail: event?.detail || null,
|
|
509
|
+
hint: event?.hint || null,
|
|
510
|
+
repair: event?.repair || null,
|
|
511
|
+
alert: false,
|
|
512
|
+
source: 'paths.withFileLock',
|
|
513
|
+
})
|
|
514
|
+
})
|