dsh-memu-memory 1.4.4 → 1.4.5

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.
Files changed (180) hide show
  1. package/AGENTS.md +3 -1
  2. package/CHANGELOG.md +11 -0
  3. package/README.md +33 -14
  4. package/README.zh.md +34 -12
  5. package/assets/screenshots/drawer.jpg +0 -0
  6. package/assets/screenshots/libraries.jpg +0 -0
  7. package/assets/screenshots/mobile.jpg +0 -0
  8. package/assets/screenshots/relations.jpg +0 -0
  9. package/assets/screenshots/settings.jpg +0 -0
  10. package/assets/screenshots/webui-dark.jpg +0 -0
  11. package/assets/screenshots/webui-memory.jpg +0 -0
  12. package/docs/client-conventions.md +19 -3
  13. package/docs/contributing.md +4 -2
  14. package/docs/env-and-commands.md +9 -1
  15. package/docs/graph-scale.md +214 -0
  16. package/docs/lexicon-recall.md +100 -0
  17. package/docs/mcp-porting.md +8 -6
  18. package/docs/memory-semantics.md +35 -3
  19. package/docs/pending-work.md +3 -1
  20. package/docs/retention.md +83 -0
  21. package/docs/rt-index.md +452 -0
  22. package/docs/scale-performance.md +101 -0
  23. package/docs/token-budget.md +92 -0
  24. package/docs/troubleshooting.md +50 -11
  25. package/lib/auto-link/apply.js +7 -2
  26. package/lib/auto-link/candidates.js +32 -10
  27. package/lib/backup.js +67 -32
  28. package/lib/binding-diagnostics.js +1 -1
  29. package/lib/bounded-cache.js +80 -0
  30. package/lib/client.js +2096 -409
  31. package/lib/consolidation-ledger.js +21 -4
  32. package/lib/consolidation-worker.js +14 -1
  33. package/lib/cycle.js +16 -11
  34. package/lib/diagnostic-context.js +372 -0
  35. package/lib/diagnostics.js +147 -61
  36. package/lib/embedding-download.js +7 -8
  37. package/lib/engine-sources.js +286 -0
  38. package/lib/engine.js +23 -10
  39. package/lib/entity-repair.js +43 -13
  40. package/lib/entity-review.js +64 -0
  41. package/lib/environment-check.js +348 -36
  42. package/lib/feedback.js +25 -0
  43. package/lib/global-graph.js +46 -2
  44. package/lib/graph-adjacency-index.js +525 -0
  45. package/lib/graph-overview.js +293 -0
  46. package/lib/graph.js +658 -105
  47. package/lib/inbound.js +44 -15
  48. package/lib/index-pages.js +57 -0
  49. package/lib/index.js +44 -6
  50. package/lib/inject.js +119 -50
  51. package/lib/lexicon-rt-source.js +25 -0
  52. package/lib/lexicon-rt-worker.js +26 -0
  53. package/lib/lexicon-rt.js +224 -0
  54. package/lib/lexicon-scope.js +56 -5
  55. package/lib/lexicon.js +143 -54
  56. package/lib/local-vector-service.js +3 -0
  57. package/lib/maintenance-ledger.js +542 -12
  58. package/lib/managed-runtime.js +260 -80
  59. package/lib/media.js +1 -1
  60. package/lib/memory.js +564 -131
  61. package/lib/port-surface.js +96 -11
  62. package/lib/private.js +47 -21
  63. package/lib/recall-cache.js +20 -34
  64. package/lib/retention.js +173 -0
  65. package/lib/rpc.js +135 -52
  66. package/lib/rt-index/builder.js +209 -0
  67. package/lib/rt-index/format.js +231 -0
  68. package/lib/rt-index/manifest.js +105 -0
  69. package/lib/rt-index/reader.js +673 -0
  70. package/lib/rt-index-retention.js +151 -0
  71. package/lib/rt-index-service.js +283 -0
  72. package/lib/rt-index-worker.js +21 -0
  73. package/lib/salient-wake.js +55 -4
  74. package/lib/state.js +195 -24
  75. package/lib/temporal.js +39 -13
  76. package/lib/token-measurement.js +126 -0
  77. package/lib/tools.js +101 -6
  78. package/lib/turn-log.js +108 -3
  79. package/lib/webui/graph-layout-worker.js +68 -0
  80. package/lib/webui/graph-local-physics.js +390 -0
  81. package/lib/webui/graph-spatial-grid.js +64 -0
  82. package/lib/webui/graph-view.bundle.js +6 -1
  83. package/lib/webui/graph-view.js +478 -135
  84. package/lib/webui/graph-webgl-renderer.js +74 -0
  85. package/lib/webui/standalone.js +1 -1
  86. package/lib/worker-pool.js +30 -4
  87. package/package.json +3 -2
  88. package/scripts/acceptance-local.mjs +4 -10
  89. package/scripts/bench-all-libraries.mjs +47 -0
  90. package/scripts/check-classic-graph-browser.mjs +189 -0
  91. package/scripts/check-client-browser.mjs +929 -0
  92. package/scripts/check-graph-browser.mjs +6 -0
  93. package/scripts/check-graph-elastic-browser.mjs +139 -0
  94. package/scripts/check-memory-review-browser.mjs +124 -0
  95. package/scripts/entity-dedupe.mjs +19 -3
  96. package/scripts/graph-artifact-provenance.mjs +30 -0
  97. package/scripts/graph-freeze-manifest.mjs +129 -0
  98. package/scripts/graph-geometry-fixture.mjs +40 -0
  99. package/scripts/graph-physics-bench.mjs +218 -0
  100. package/scripts/graph-scale-bench.mjs +213 -0
  101. package/scripts/graph-scale-memory.mjs +48 -0
  102. package/scripts/graph-service-bench.mjs +72 -0
  103. package/scripts/make-readme-shots.mjs +17 -5
  104. package/scripts/preview.mjs +1 -0
  105. package/scripts/rebuild-rt.mjs +18 -0
  106. package/scripts/scale-bench.mjs +183 -0
  107. package/scripts/simulate-injection.mjs +47 -8
  108. package/scripts/verify-host-fixtures.mjs +108 -0
  109. package/scripts/verify-host-recovery.mjs +565 -0
  110. package/scripts/verify-vector-recovery.mjs +740 -0
  111. package/tests/auto-link-candidates.test.mjs +20 -0
  112. package/tests/browser.test.mjs +16 -2
  113. package/tests/client-export.test.mjs +16 -1
  114. package/tests/client-pagination.test.mjs +1495 -0
  115. package/tests/client-render.test.mjs +223 -28
  116. package/tests/consolidation-fork.test.mjs +93 -10
  117. package/tests/consolidation-ledger.test.mjs +17 -1
  118. package/tests/diagnostic-entity-candidates.test.mjs +54 -0
  119. package/tests/diagnostic-report.test.mjs +429 -0
  120. package/tests/diagnostic-wiring.test.mjs +88 -0
  121. package/tests/diagnostics.test.mjs +27 -0
  122. package/tests/embedding-download.test.mjs +44 -0
  123. package/tests/engine-source-settings.test.mjs +69 -0
  124. package/tests/engine-sources.test.mjs +145 -0
  125. package/tests/entity-dedupe.test.mjs +143 -0
  126. package/tests/entity-merge-review.test.mjs +363 -0
  127. package/tests/entity-merge.test.mjs +12 -4
  128. package/tests/entity-review.test.mjs +87 -0
  129. package/tests/environment-check.test.mjs +51 -1
  130. package/tests/feedback.test.mjs +95 -0
  131. package/tests/graph-adjacency-index.test.mjs +536 -0
  132. package/tests/graph-cascade.test.mjs +229 -0
  133. package/tests/graph-import-diagnostic.test.mjs +25 -0
  134. package/tests/graph-overview.test.mjs +709 -0
  135. package/tests/graph-session-authorization.test.mjs +419 -0
  136. package/tests/graph-view-geometry.test.mjs +426 -0
  137. package/tests/graph-view-scale.test.mjs +88 -0
  138. package/tests/graph-view.test.mjs +444 -5
  139. package/tests/graph.test.mjs +43 -0
  140. package/tests/help-page.test.mjs +128 -54
  141. package/tests/inbound.test.mjs +19 -0
  142. package/tests/index-pagination.test.mjs +113 -0
  143. package/tests/index-read-view.test.mjs +212 -0
  144. package/tests/inject-guide.test.mjs +9 -0
  145. package/tests/injection-dedupe.test.mjs +213 -0
  146. package/tests/lexicon-recall.test.mjs +641 -0
  147. package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
  148. package/tests/lexicon-rt.test.mjs +468 -0
  149. package/tests/local-embedding-worker.test.mjs +38 -0
  150. package/tests/local-vector-service.test.mjs +32 -3
  151. package/tests/maintenance-compat.test.mjs +128 -0
  152. package/tests/maintenance-settlement.test.mjs +1003 -0
  153. package/tests/managed-memory.test.mjs +39 -11
  154. package/tests/managed-runtime.test.mjs +109 -0
  155. package/tests/memory-fields.test.mjs +24 -12
  156. package/tests/observed-evidence.test.mjs +52 -0
  157. package/tests/port-surface.test.mjs +93 -1
  158. package/tests/recall-cache.test.mjs +56 -3
  159. package/tests/recall-dedup.test.mjs +63 -2
  160. package/tests/retention.test.mjs +260 -0
  161. package/tests/rt-index-cross-library.test.mjs +230 -0
  162. package/tests/rt-index-integration.test.mjs +194 -0
  163. package/tests/rt-index-retention.test.mjs +552 -0
  164. package/tests/rt-index-scale.test.mjs +204 -0
  165. package/tests/rt-index.test.mjs +705 -0
  166. package/tests/salient-date-boundaries.test.mjs +121 -0
  167. package/tests/salient-wake.test.mjs +29 -0
  168. package/tests/scale-bench.test.mjs +53 -0
  169. package/tests/settings-plumbing.test.mjs +25 -0
  170. package/tests/simulate-injection.test.mjs +15 -1
  171. package/tests/standalone-navigation.test.mjs +44 -0
  172. package/tests/state.test.mjs +51 -0
  173. package/tests/temporal-precision.test.mjs +102 -0
  174. package/tests/temporal.test.mjs +10 -6
  175. package/tests/token-measurement.test.mjs +98 -0
  176. package/tests/tool-schema.test.mjs +41 -5
  177. package/tests/tools.test.mjs +6 -3
  178. package/tests/turn-token-budget.test.mjs +149 -0
  179. package/tests/webui-auth.test.mjs +57 -1
  180. package/tests/webui.test.mjs +40 -15
@@ -1,7 +1,10 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import crypto from 'node:crypto'
4
- import { dataDir, ensureDir, redactSecrets, stamp, setLockEventSink } from './paths.js'
4
+ import { dataDir, ensureDir, stamp, setLockEventSink } from './paths.js'
5
+ import { diagnosticText, diagnosticValue, diagnosticDetail, diagnosticError, diagnosticPolicy, diagnosticRuntime, diagnosticRef } from './diagnostic-context.js'
6
+
7
+ export { diagnosticRuntime } from './diagnostic-context.js'
5
8
 
6
9
  // 诊断面(§15):插件内部的失败从"只有一行 warn"变成一条可检索、可修复的记录。
7
10
  //
@@ -17,6 +20,15 @@ const RING_LIMIT = 500
17
20
  const DEDUPE_WINDOW_MS = 60_000
18
21
  const MAX_MESSAGE = 2000
19
22
  const LEVELS = new Set(['error', 'warn', 'info'])
23
+ const REPAIRS = new Set(['release-stale-locks', 'resign-vector-profile', 'repoint-runtime-dir', 'reinstall-runtime', 'reinstall-model', 'rebuild-vector-index', 'reinstall-engine', 'merge-entity-fragments', 'repair-maintenance-journal'])
24
+ const SCOPES = new Set(['plugin', 'host', 'engine', 'vector', 'state', 'rpc', 'workers', 'store', 'storage', 'graph', 'repair', 'token-budget'])
25
+ const technicalId = (value, fallback = null) => /^[A-Za-z0-9_.:/-]{1,100}$/.test(String(value || '')) ? String(value) : fallback
26
+ const errorCode = value => /^[A-Z][A-Z0-9_]{0,63}$/.test(String(value || '')) ? String(value) : 'MEMU_DIAGNOSTIC'
27
+ const retryInfo = (value, policy) => {
28
+ const retryable = typeof value?.retryable === 'boolean' ? value.retryable : policy.retryable
29
+ return { retryable, afterMs: !retryable ? null : Number.isFinite(value?.afterMs) && value.afterMs >= 0 ? Math.min(value.afterMs, 86400000) : policy.afterMs }
30
+ }
31
+ const persistedLabel = (key, value) => value == null ? null : diagnosticValue({ [key]: value })?.[key] || diagnosticRef(value)
20
32
 
21
33
  export function diagnosticsDir() {
22
34
  return path.join(dataDir(), 'diagnostics')
@@ -42,6 +54,7 @@ let bytesCache = null
42
54
  const lastByKey = new Map()
43
55
  const ack = new Map()
44
56
  let ackLoaded = false
57
+ let persistenceFailure = null
45
58
 
46
59
  function keyOf(entry) {
47
60
  return [entry.scope, entry.code, entry.message].join('\u0000')
@@ -52,38 +65,50 @@ export function diagnosticKeyHash(entry) {
52
65
  return crypto.createHash('sha256').update([entry?.scope, entry?.code, entry?.message].join('\u0000')).digest('hex').slice(0, 16)
53
66
  }
54
67
 
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
68
  /** 只保留可 JSON 化、已脱敏、已限长的 detail。 */
70
- export function shapeDetail(detail) {
69
+ export function shapeDetail(detail, code = null) {
71
70
  if (detail === undefined || detail === null) return null
72
71
  try {
73
- const pruned = pruneValue(detail, 0)
72
+ const pruned = diagnosticDetail(code, detail)
74
73
  return pruned && typeof pruned === 'object' ? pruned : { value: pruned }
75
74
  } catch {
76
75
  return null
77
76
  }
78
77
  }
79
78
 
79
+ function storedDetail(detail, code) {
80
+ if (code !== 'ENTITY_FRAGMENT_SUSPECTED' || !detail || typeof detail !== 'object' || Array.isArray(detail)) {
81
+ return shapeDetail(detail, code)
82
+ }
83
+ const count = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined
84
+ return shapeDetail({
85
+ ...(count(detail.similar) !== undefined ? { similar: count(detail.similar) } : {}),
86
+ ...(count(detail.libraries) !== undefined ? { libraries: count(detail.libraries) } : {}),
87
+ }, code)
88
+ }
89
+
80
90
  function normalize(input) {
81
91
  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'
92
+ let level = LEVELS.has(input.level) ? input.level : 'error'
93
+ let scope = String(input.scope || 'plugin').trim().toLowerCase().replace(/[^a-z0-9_-]/g, '').slice(0, 40) || 'plugin'
94
+ let code = String(input.code || 'MEMU_DIAGNOSTIC').trim().toUpperCase().replace(/[^A-Z0-9_]/g, '_').slice(0, 64) || 'MEMU_DIAGNOSTIC'
85
95
  const rawMessage = String(input.message ?? '').trim()
86
- const message = (redactSecrets(rawMessage || code)).slice(0, MAX_MESSAGE)
96
+ if (code === 'MEMU_WARNING') {
97
+ const observed = rawMessage.match(/\b(?:LOCAL_VECTOR|VECTOR|RT|MEMU|DSH_MEMU|ENGINE|RPC|HOST)_[A-Z0-9_]+\b/)
98
+ if (observed) code = observed[0]
99
+ if (/no (?:active vector generation|database)|no-database|未建库|首次使用/i.test(rawMessage)) {
100
+ level = 'info'
101
+ code = 'VECTOR_NOT_BUILT'
102
+ }
103
+ scope = diagnosticPolicy(code, scope).layer
104
+ }
105
+ const message = input.source === 'warn-sink'
106
+ ? diagnosticError({ message: rawMessage || code, code }).message
107
+ : diagnosticText(rawMessage || code, MAX_MESSAGE)
108
+ const policy = diagnosticPolicy(code, scope)
109
+ const context = diagnosticValue(input.context || {}) || {}
110
+ for (const field of ['sessionId', 'libraryId']) if (input[field] != null) context[field.replace('Id', 'Ref')] = diagnosticRef(input[field])
111
+ const runtime = diagnosticRuntime()
87
112
  const at = stamp()
88
113
  return {
89
114
  id: crypto.randomUUID(),
@@ -93,14 +118,22 @@ function normalize(input) {
93
118
  scope,
94
119
  code,
95
120
  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,
121
+ detail: storedDetail(input.detail, code),
122
+ hint: input.hint ? diagnosticText(input.hint, 1000) : null,
123
+ repair: REPAIRS.has(input.repair) ? input.repair : null,
99
124
  manual: input.manual === true,
100
125
  // 启动弹窗只看 alert 条目:error 默认弹,warn 只有明确要求才弹(避免一开机就一屏)。
101
126
  alert: input.alert === undefined ? level === 'error' : input.alert === true,
102
127
  count: 1,
103
- source: input.source ? String(input.source).slice(0, 60) : null,
128
+ source: technicalId(input.source),
129
+ layer: policy.layer,
130
+ operation: technicalId(input.operation),
131
+ correlationId: input.correlationId ? diagnosticRef(input.correlationId) : null,
132
+ context,
133
+ error: input.error ? diagnosticError(input.error) : null,
134
+ retry: retryInfo(input.retry, policy.retry),
135
+ action: input.action ? diagnosticText(input.action, 1000) : policy.action,
136
+ versions: { host: runtime.host.version, plugin: runtime.plugin.version, node: runtime.node.version },
104
137
  }
105
138
  }
106
139
 
@@ -130,6 +163,7 @@ function appendLine(entry) {
130
163
  */
131
164
  export function recordDiagnostic(input) {
132
165
  try {
166
+ ensureLoaded()
133
167
  const entry = normalize(input)
134
168
  if (!entry) return null
135
169
  const key = keyOf(entry)
@@ -139,13 +173,24 @@ export function recordDiagnostic(input) {
139
173
  last.count += 1
140
174
  last.lastAt = entry.at
141
175
  last.lastAtMs = nowMs
176
+ last.context = entry.context
177
+ last.error = entry.error || last.error
178
+ last.operation = entry.operation || last.operation
179
+ last.correlationId = entry.correlationId || last.correlationId
142
180
  // 内存里的这条已经是环形缓冲的一员(引用),页面下一轮就会看到 count 变大。
143
181
  return last
144
182
  }
145
183
  entry.lastAtMs = nowMs
146
- appendLine(entry)
184
+ try { appendLine(entry); persistenceFailure = null } catch (error) {
185
+ // Keep the evidence in memory even when the very store being diagnosed is
186
+ // unwritable. Reporting this failure must not recurse into warn-sink.
187
+ persistenceFailure = diagnosticError(error)
188
+ }
147
189
  ring.push(entry)
148
- while (ring.length > RING_LIMIT) ring.shift()
190
+ while (ring.length > RING_LIMIT) {
191
+ const oldest = ring.shift()
192
+ if (lastByKey.get(keyOf(oldest)) === oldest) lastByKey.delete(keyOf(oldest))
193
+ }
149
194
  lastByKey.set(key, entry)
150
195
  return entry
151
196
  } catch {
@@ -204,6 +249,12 @@ const KNOWN_CODES = Object.freeze({
204
249
  repair: 'repoint-runtime-dir',
205
250
  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.',
206
251
  },
252
+ LOCAL_VECTOR_RUNTIME_ABSENT: {
253
+ scope: 'vector',
254
+ repair: 'reinstall-runtime',
255
+ manual: true,
256
+ hint: 'The startup reuse check found no verified managed runtime. Install the pinned runtime in local vector settings. A successful embedding health check clears this historical alert automatically.',
257
+ },
207
258
  LOCAL_VECTOR_MANIFEST_INCOMPLETE: {
208
259
  scope: 'vector',
209
260
  repair: 'resign-vector-profile',
@@ -255,9 +306,10 @@ const KNOWN_CODES = Object.freeze({
255
306
  })
256
307
 
257
308
  export function classifyError(error) {
309
+ const shaped = diagnosticError(error)
258
310
  const code = String(error?.code || error?.name || 'MEMU_ERROR').toUpperCase()
259
311
  const known = KNOWN_CODES[code] || null
260
- const message = String(error?.message || error || 'unknown failure')
312
+ const message = shaped.message
261
313
  const detail = {}
262
314
  if (error?.detail && typeof error.detail === 'object') Object.assign(detail, error.detail)
263
315
  // VectorStateError 把 extra 摊在自己身上;只挑诊断需要的几个字段,别把整个 error 塞进去。
@@ -265,28 +317,42 @@ export function classifyError(error) {
265
317
  if (error?.[field] !== undefined) detail[field] = error[field]
266
318
  }
267
319
  return {
268
- scope: known?.scope || 'plugin',
320
+ scope: known?.scope || diagnosticPolicy(code).layer,
269
321
  code,
270
322
  message,
271
323
  detail: Object.keys(detail).length ? detail : null,
272
324
  hint: known?.hint || null,
273
325
  repair: known?.repair || null,
274
326
  manual: known?.manual === true,
327
+ error: shaped,
275
328
  }
276
329
  }
277
330
 
278
331
  /** 记一个异常;未知错误也记(诊断页要能看见"没归类"的故障)。 */
279
332
  export function recordErrorDiagnostic(error, context = {}) {
280
- const classified = classifyError(error)
281
- return recordDiagnostic({
282
- ...classified,
283
- level: context.level || 'error',
284
- source: context.source || null,
285
- detail: { ...(classified.detail || {}), ...(context.detail || {}) },
286
- hint: context.hint || classified.hint,
287
- repair: context.repair || classified.repair,
288
- message: context.message || classified.message,
289
- })
333
+ try {
334
+ const classified = classifyError(error)
335
+ const sourceScope = /^(?:embedding-worker|vector-bootstrap)$/.test(context.source) ? 'vector' : context.source === 'engine-bootstrap' ? 'engine' : /^rpc(?:[./-]|$)/.test(context.source) ? 'rpc' : classified.scope
336
+ return recordDiagnostic({
337
+ ...classified,
338
+ code: context.code || classified.code,
339
+ scope: context.scope || sourceScope,
340
+ level: context.level || 'error',
341
+ source: context.source || null,
342
+ detail: { ...(classified.detail || {}), ...(context.detail || {}) },
343
+ hint: context.hint || classified.hint,
344
+ repair: context.repair || classified.repair,
345
+ message: context.message || classified.message,
346
+ operation: context.operation,
347
+ correlationId: context.correlationId,
348
+ context: context.context,
349
+ retry: context.retry,
350
+ action: context.action,
351
+ alert: context.alert,
352
+ })
353
+ } catch {
354
+ return recordDiagnostic({ code: 'MEMU_DIAGNOSTIC_UNINSPECTABLE', message: 'Exception could not be inspected safely', alert: false })
355
+ }
290
356
  }
291
357
 
292
358
  // ---------------------------------------------------------------- 读取
@@ -297,21 +363,33 @@ function parseLine(line) {
297
363
  try {
298
364
  const value = JSON.parse(text)
299
365
  if (!value || typeof value !== 'object' || !value.code) return null
366
+ const code = errorCode(value.code)
367
+ const scope = SCOPES.has(value.scope) ? value.scope : 'plugin'
368
+ const policy = diagnosticPolicy(code, scope)
369
+ const timestamp = value => typeof value === 'string' && /^\d{4}-\d\d-\d\dT[0-9:.+-]+Z?$/.test(value) ? value.slice(0, 40) : stamp()
300
370
  return {
301
- id: value.id || crypto.randomUUID(),
302
- at: value.at || stamp(),
303
- lastAt: value.lastAt || value.at || stamp(),
371
+ id: /^[a-f0-9-]{36}$/.test(value.id) ? value.id : crypto.randomUUID(),
372
+ at: timestamp(value.at),
373
+ lastAt: timestamp(value.lastAt || value.at),
304
374
  level: LEVELS.has(value.level) ? value.level : 'error',
305
- scope: String(value.scope || 'plugin'),
306
- code: String(value.code),
307
- message: String(value.message || value.code),
308
- detail: value.detail ?? null,
309
- hint: value.hint ?? null,
310
- repair: value.repair ?? null,
375
+ scope,
376
+ code,
377
+ message: diagnosticError({ message: value.message || code, code }).message,
378
+ detail: storedDetail(value.detail, code),
379
+ hint: KNOWN_CODES[code]?.hint || null,
380
+ repair: REPAIRS.has(value.repair) ? value.repair : null,
311
381
  manual: value.manual === true,
312
382
  alert: value.alert === true,
313
383
  count: Number.isFinite(value.count) && value.count > 0 ? value.count : 1,
314
- source: value.source ?? null,
384
+ source: persistedLabel('source', value.source),
385
+ layer: policy.layer,
386
+ operation: persistedLabel('operation', value.operation),
387
+ correlationId: value.correlationId ? diagnosticRef(value.correlationId) : null,
388
+ context: diagnosticValue(value.context || {}),
389
+ error: value.error ? diagnosticError(value.error) : null,
390
+ retry: retryInfo(value.retry, policy.retry),
391
+ action: policy.action,
392
+ versions: diagnosticValue(value.versions || null),
315
393
  }
316
394
  } catch {
317
395
  return null
@@ -329,7 +407,8 @@ function readTail(file, maxBytes = 512 * 1024) {
329
407
  fs.readSync(fd, buffer, 0, length, start)
330
408
  return { text: buffer.toString('utf8'), truncated: start > 0 }
331
409
  } finally { fs.closeSync(fd) }
332
- } catch {
410
+ } catch (error) {
411
+ if (error?.code !== 'ENOENT') persistenceFailure = diagnosticError(error)
333
412
  return { text: '', truncated: false }
334
413
  }
335
414
  }
@@ -410,6 +489,7 @@ export function diagnosticStats() {
410
489
  maxBytes: MAX_BYTES,
411
490
  repaired: ring.filter(entry => entry.repair && entry.code === 'MEMU_DIAGNOSTIC_REPAIRED').length,
412
491
  path: diagnosticsDir(),
492
+ persistence: { status: persistenceFailure ? 'failed' : 'observed', error: persistenceFailure },
413
493
  }
414
494
  }
415
495
 
@@ -417,13 +497,15 @@ export function diagnosticStats() {
417
497
  * 启动弹窗要看的那几条:error 级、alert 未关,且"出现次数比上次确认时更多"。
418
498
  * 一条问题修好后不再重复弹,再次出现才弹——否则用户每天开机都要关一次同一个提示。
419
499
  */
420
- export function diagnosticAlerts() {
500
+ function groupedDiagnosticAlerts(before = null) {
421
501
  ensureLoaded()
422
502
  ensureAckLoaded()
503
+ const cutoff = before == null ? null : Date.parse(before)
423
504
  const grouped = new Map()
424
505
  for (const entry of ring) {
425
506
  if (!entry.alert) continue
426
507
  if (entry.level !== 'error' && entry.level !== 'warn') continue
508
+ if (Number.isFinite(cutoff) && Date.parse(entry.lastAt || entry.at) > cutoff) continue
427
509
  const key = diagnosticKeyHash(entry)
428
510
  const current = grouped.get(key)
429
511
  if (current) {
@@ -445,20 +527,21 @@ export function diagnosticAlerts() {
445
527
  acknowledged: ack.get(key) || 0,
446
528
  })
447
529
  }
448
- const alerts = [...grouped.values()].filter(alert => alert.count > alert.acknowledged)
530
+ return [...grouped.values()]
531
+ }
532
+
533
+ export function diagnosticAlerts() {
534
+ const alerts = groupedDiagnosticAlerts().filter(alert => alert.count > alert.acknowledged)
449
535
  return { alerts, checkedAt: stamp() }
450
536
  }
451
537
 
452
538
  /** 确认(= 知道这件事了)。按同类问题的当前次数记账,不再弹直到它再次出现。 */
453
- export function acknowledgeDiagnostics({ keys = [], codes = [] } = {}) {
454
- ensureLoaded()
455
- ensureAckLoaded()
539
+ export function acknowledgeDiagnostics({ keys = [], codes = [], before = null } = {}) {
456
540
  const wantKeys = new Set((Array.isArray(keys) ? keys : []).map(String))
457
541
  const wantCodes = new Set((Array.isArray(codes) ? codes : []).map(code => String(code).toUpperCase()))
458
542
  let changed = 0
459
- for (const entry of ring) {
460
- if (!entry.alert) continue
461
- const key = diagnosticKeyHash(entry)
543
+ for (const entry of groupedDiagnosticAlerts(before)) {
544
+ const key = entry.key
462
545
  if (wantKeys.size && !wantKeys.has(key)) continue
463
546
  if (wantCodes.size && !wantCodes.has(String(entry.code).toUpperCase())) continue
464
547
  if (!wantKeys.size && !wantCodes.size) continue
@@ -478,17 +561,20 @@ function detailFields(detail) {
478
561
  return detail
479
562
  }
480
563
 
481
- export function recordRepair({ action, ok, detail, message }) {
564
+ export function recordRepair({ action, ok, detail, message, error }) {
565
+ const safeAction = REPAIRS.has(action) ? action : 'unknown-action'
482
566
  return recordDiagnostic({
483
567
  level: ok ? 'info' : 'error',
484
568
  scope: 'repair',
485
569
  code: ok ? 'MEMU_DIAGNOSTIC_REPAIRED' : 'MEMU_DIAGNOSTIC_REPAIR_FAILED',
486
- message: message || (ok ? `auto repair applied: ${action}` : `auto repair failed: ${action}`),
570
+ message: REPAIRS.has(action) && message ? diagnosticText(message) : (ok ? `auto repair applied: ${safeAction}` : `auto repair failed: ${safeAction}`),
487
571
  detail: { action, ...detailFields(detail) },
488
572
  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.',
489
- repair: ok ? null : action,
573
+ repair: ok ? null : safeAction,
490
574
  alert: !ok,
491
575
  source: 'repair',
576
+ operation: safeAction,
577
+ error: error ? diagnosticError(error) : null,
492
578
  })
493
579
  }
494
580
 
@@ -277,13 +277,11 @@ export function createEmbeddingDownloadManager(options = {}) {
277
277
  const target = modelFileTarget(dir, file.path)
278
278
  if (!target || !isRegularNonSymlink(target)) return null
279
279
  let stat
280
- try { stat = fs.lstatSync(target) } catch { return null }
281
- // readInstall 已经查过 size;这里再查一次是因为缓存要能识别「同尺寸换内容」以外
282
- // 的一切改动,而 mtime 只在真有写入时才变。
283
- if (stat.size !== file.bytes) return null
284
- // ino/ctimeMs 一起进指纹:同尺寸 + 同 mtime 的「整体替换」(tar 还原、touch -r、
285
- // FAT 的 2s 粒度)靠这两项才抓得住。
286
- parts.push(`${file.path}\u0000${file.bytes}\u0000${stat.mtimeMs}\u0000${stat.ctimeMs}\u0000${stat.ino}\u0000${file.sha256}`)
280
+ try { stat = fs.lstatSync(target, { bigint: true }) } catch { return null }
281
+ if (stat.size !== BigInt(file.bytes)) return null
282
+ // 纳秒时间戳避免 Number 毫秒值在连续同尺寸写入时丢失精度。
283
+ // ino 仍识别整体替换;安装记录的 hash 同时参与缓存键。
284
+ parts.push(`${file.path}\u0000${file.bytes}\u0000${stat.mtimeNs}\u0000${stat.ctimeNs}\u0000${stat.ino}\u0000${file.sha256}`)
287
285
  }
288
286
  return parts.join('\u0001')
289
287
  }
@@ -306,7 +304,8 @@ export function createEmbeddingDownloadManager(options = {}) {
306
304
  }
307
305
  if (hash !== file.sha256) { verdict = false; break }
308
306
  }
309
- deepVerdicts.set(entry.id, { key, verdict })
307
+ if (verdict) deepVerdicts.set(entry.id, { key, verdict: true })
308
+ else deepVerdicts.delete(entry.id) // 失败不缓存:低精度文件系统上的修复也能立即复检。
310
309
  return verdict
311
310
  }
312
311