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.
- package/AGENTS.md +3 -1
- package/CHANGELOG.md +11 -0
- package/README.md +33 -14
- package/README.zh.md +34 -12
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/libraries.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +19 -3
- package/docs/contributing.md +4 -2
- package/docs/env-and-commands.md +9 -1
- package/docs/graph-scale.md +214 -0
- package/docs/lexicon-recall.md +100 -0
- package/docs/mcp-porting.md +8 -6
- package/docs/memory-semantics.md +35 -3
- package/docs/pending-work.md +3 -1
- package/docs/retention.md +83 -0
- package/docs/rt-index.md +452 -0
- package/docs/scale-performance.md +101 -0
- package/docs/token-budget.md +92 -0
- package/docs/troubleshooting.md +50 -11
- package/lib/auto-link/apply.js +7 -2
- package/lib/auto-link/candidates.js +32 -10
- package/lib/backup.js +67 -32
- package/lib/binding-diagnostics.js +1 -1
- package/lib/bounded-cache.js +80 -0
- package/lib/client.js +2096 -409
- package/lib/consolidation-ledger.js +21 -4
- package/lib/consolidation-worker.js +14 -1
- package/lib/cycle.js +16 -11
- package/lib/diagnostic-context.js +372 -0
- package/lib/diagnostics.js +147 -61
- package/lib/embedding-download.js +7 -8
- package/lib/engine-sources.js +286 -0
- package/lib/engine.js +23 -10
- package/lib/entity-repair.js +43 -13
- package/lib/entity-review.js +64 -0
- package/lib/environment-check.js +348 -36
- package/lib/feedback.js +25 -0
- package/lib/global-graph.js +46 -2
- package/lib/graph-adjacency-index.js +525 -0
- package/lib/graph-overview.js +293 -0
- package/lib/graph.js +658 -105
- package/lib/inbound.js +44 -15
- package/lib/index-pages.js +57 -0
- package/lib/index.js +44 -6
- package/lib/inject.js +119 -50
- package/lib/lexicon-rt-source.js +25 -0
- package/lib/lexicon-rt-worker.js +26 -0
- package/lib/lexicon-rt.js +224 -0
- package/lib/lexicon-scope.js +56 -5
- package/lib/lexicon.js +143 -54
- package/lib/local-vector-service.js +3 -0
- package/lib/maintenance-ledger.js +542 -12
- package/lib/managed-runtime.js +260 -80
- package/lib/media.js +1 -1
- package/lib/memory.js +564 -131
- package/lib/port-surface.js +96 -11
- package/lib/private.js +47 -21
- package/lib/recall-cache.js +20 -34
- package/lib/retention.js +173 -0
- package/lib/rpc.js +135 -52
- package/lib/rt-index/builder.js +209 -0
- package/lib/rt-index/format.js +231 -0
- package/lib/rt-index/manifest.js +105 -0
- package/lib/rt-index/reader.js +673 -0
- package/lib/rt-index-retention.js +151 -0
- package/lib/rt-index-service.js +283 -0
- package/lib/rt-index-worker.js +21 -0
- package/lib/salient-wake.js +55 -4
- package/lib/state.js +195 -24
- package/lib/temporal.js +39 -13
- package/lib/token-measurement.js +126 -0
- package/lib/tools.js +101 -6
- package/lib/turn-log.js +108 -3
- package/lib/webui/graph-layout-worker.js +68 -0
- package/lib/webui/graph-local-physics.js +390 -0
- package/lib/webui/graph-spatial-grid.js +64 -0
- package/lib/webui/graph-view.bundle.js +6 -1
- package/lib/webui/graph-view.js +478 -135
- package/lib/webui/graph-webgl-renderer.js +74 -0
- package/lib/webui/standalone.js +1 -1
- package/lib/worker-pool.js +30 -4
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +4 -10
- package/scripts/bench-all-libraries.mjs +47 -0
- package/scripts/check-classic-graph-browser.mjs +189 -0
- package/scripts/check-client-browser.mjs +929 -0
- package/scripts/check-graph-browser.mjs +6 -0
- package/scripts/check-graph-elastic-browser.mjs +139 -0
- package/scripts/check-memory-review-browser.mjs +124 -0
- package/scripts/entity-dedupe.mjs +19 -3
- package/scripts/graph-artifact-provenance.mjs +30 -0
- package/scripts/graph-freeze-manifest.mjs +129 -0
- package/scripts/graph-geometry-fixture.mjs +40 -0
- package/scripts/graph-physics-bench.mjs +218 -0
- package/scripts/graph-scale-bench.mjs +213 -0
- package/scripts/graph-scale-memory.mjs +48 -0
- package/scripts/graph-service-bench.mjs +72 -0
- package/scripts/make-readme-shots.mjs +17 -5
- package/scripts/preview.mjs +1 -0
- package/scripts/rebuild-rt.mjs +18 -0
- package/scripts/scale-bench.mjs +183 -0
- package/scripts/simulate-injection.mjs +47 -8
- package/scripts/verify-host-fixtures.mjs +108 -0
- package/scripts/verify-host-recovery.mjs +565 -0
- package/scripts/verify-vector-recovery.mjs +740 -0
- package/tests/auto-link-candidates.test.mjs +20 -0
- package/tests/browser.test.mjs +16 -2
- package/tests/client-export.test.mjs +16 -1
- package/tests/client-pagination.test.mjs +1495 -0
- package/tests/client-render.test.mjs +223 -28
- package/tests/consolidation-fork.test.mjs +93 -10
- package/tests/consolidation-ledger.test.mjs +17 -1
- package/tests/diagnostic-entity-candidates.test.mjs +54 -0
- package/tests/diagnostic-report.test.mjs +429 -0
- package/tests/diagnostic-wiring.test.mjs +88 -0
- package/tests/diagnostics.test.mjs +27 -0
- package/tests/embedding-download.test.mjs +44 -0
- package/tests/engine-source-settings.test.mjs +69 -0
- package/tests/engine-sources.test.mjs +145 -0
- package/tests/entity-dedupe.test.mjs +143 -0
- package/tests/entity-merge-review.test.mjs +363 -0
- package/tests/entity-merge.test.mjs +12 -4
- package/tests/entity-review.test.mjs +87 -0
- package/tests/environment-check.test.mjs +51 -1
- package/tests/feedback.test.mjs +95 -0
- package/tests/graph-adjacency-index.test.mjs +536 -0
- package/tests/graph-cascade.test.mjs +229 -0
- package/tests/graph-import-diagnostic.test.mjs +25 -0
- package/tests/graph-overview.test.mjs +709 -0
- package/tests/graph-session-authorization.test.mjs +419 -0
- package/tests/graph-view-geometry.test.mjs +426 -0
- package/tests/graph-view-scale.test.mjs +88 -0
- package/tests/graph-view.test.mjs +444 -5
- package/tests/graph.test.mjs +43 -0
- package/tests/help-page.test.mjs +128 -54
- package/tests/inbound.test.mjs +19 -0
- package/tests/index-pagination.test.mjs +113 -0
- package/tests/index-read-view.test.mjs +212 -0
- package/tests/inject-guide.test.mjs +9 -0
- package/tests/injection-dedupe.test.mjs +213 -0
- package/tests/lexicon-recall.test.mjs +641 -0
- package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
- package/tests/lexicon-rt.test.mjs +468 -0
- package/tests/local-embedding-worker.test.mjs +38 -0
- package/tests/local-vector-service.test.mjs +32 -3
- package/tests/maintenance-compat.test.mjs +128 -0
- package/tests/maintenance-settlement.test.mjs +1003 -0
- package/tests/managed-memory.test.mjs +39 -11
- package/tests/managed-runtime.test.mjs +109 -0
- package/tests/memory-fields.test.mjs +24 -12
- package/tests/observed-evidence.test.mjs +52 -0
- package/tests/port-surface.test.mjs +93 -1
- package/tests/recall-cache.test.mjs +56 -3
- package/tests/recall-dedup.test.mjs +63 -2
- package/tests/retention.test.mjs +260 -0
- package/tests/rt-index-cross-library.test.mjs +230 -0
- package/tests/rt-index-integration.test.mjs +194 -0
- package/tests/rt-index-retention.test.mjs +552 -0
- package/tests/rt-index-scale.test.mjs +204 -0
- package/tests/rt-index.test.mjs +705 -0
- package/tests/salient-date-boundaries.test.mjs +121 -0
- package/tests/salient-wake.test.mjs +29 -0
- package/tests/scale-bench.test.mjs +53 -0
- package/tests/settings-plumbing.test.mjs +25 -0
- package/tests/simulate-injection.test.mjs +15 -1
- package/tests/standalone-navigation.test.mjs +44 -0
- package/tests/state.test.mjs +51 -0
- package/tests/temporal-precision.test.mjs +102 -0
- package/tests/temporal.test.mjs +10 -6
- package/tests/token-measurement.test.mjs +98 -0
- package/tests/tool-schema.test.mjs +41 -5
- package/tests/tools.test.mjs +6 -3
- package/tests/turn-token-budget.test.mjs +149 -0
- package/tests/webui-auth.test.mjs +57 -1
- package/tests/webui.test.mjs +40 -15
package/lib/environment-check.js
CHANGED
|
@@ -15,17 +15,23 @@
|
|
|
15
15
|
*/
|
|
16
16
|
import fs from 'node:fs'
|
|
17
17
|
import path from 'node:path'
|
|
18
|
-
import { dataDir,
|
|
19
|
-
import {
|
|
20
|
-
import { getSettings, getMemoryBackend, backupDatabases, listLibraries, loadPrivateIndex } from './state.js'
|
|
18
|
+
import { dataDir, scanMemoryLocks, releaseStaleLocks, readFailuresUnder } from './paths.js'
|
|
19
|
+
import { ensureEngine, ENGINE_VERSION } from './engine.js'
|
|
20
|
+
import { getSettings, getMemoryBackend, effectiveVectorRoute, backupDatabases, listLibraries, loadPrivateIndex } from './state.js'
|
|
21
21
|
import { planAllRepairs, applyRepairGroups } from './entity-repair.js'
|
|
22
22
|
import {
|
|
23
23
|
activeProfile, requestedProfile, resignVectorProfile, repointVectorRuntimeDir,
|
|
24
24
|
runtimeDirCandidates, vectorActiveFile, VECTOR_ERROR_CODES,
|
|
25
|
+
readVectorState, resolveVectorPath, resolveCatalogEntry, assertProfileVerified,
|
|
26
|
+
manifestDigest, manifestDigestAccepted, manifestDrift,
|
|
25
27
|
} from './vector-profile.js'
|
|
26
28
|
import { hasEmbeddingRuntimePackages, installLocalVectorRuntime, downloadLocalVectorModel } from './local-vector-service.js'
|
|
27
29
|
import { embeddingWorkerManager } from './local-embedding-manager.js'
|
|
28
|
-
import { recordRepair } from './diagnostics.js'
|
|
30
|
+
import { recordRepair, recordDiagnostic, recordErrorDiagnostic, listDiagnostics, diagnosticStats } from './diagnostics.js'
|
|
31
|
+
import { diagnosticText, diagnosticValue, diagnosticDetail, diagnosticGraphAdjacency, diagnosticError, diagnosticPolicy, diagnosticRuntime, diagnosticRef } from './diagnostic-context.js'
|
|
32
|
+
import { rtServiceDiagnostics } from './rt-index-service.js'
|
|
33
|
+
import { lexiconRtDiagnostics } from './lexicon-rt.js'
|
|
34
|
+
import { graphAdjacencyDiagnostics } from './graph-adjacency-index.js'
|
|
29
35
|
|
|
30
36
|
// 启动路径可以自己跑的修复:都不联网、都不改变制品身份,最坏情况只是白跑一次。
|
|
31
37
|
export const SAFE_REPAIRS = Object.freeze(['release-stale-locks', 'resign-vector-profile', 'repoint-runtime-dir'])
|
|
@@ -45,26 +51,107 @@ export const REPAIR_LABELS = Object.freeze({
|
|
|
45
51
|
})
|
|
46
52
|
|
|
47
53
|
const MODEL_REQUIRED_FILES = ['config.json', 'tokenizer.json']
|
|
54
|
+
const metadataVersion = value => typeof value === 'string' && /^v?\d[0-9A-Za-z.+-]{0,79}$/.test(value) ? value : null
|
|
55
|
+
const finiteCount = value => Number.isFinite(value) && value >= 0 ? value : 0
|
|
56
|
+
const failure = (code, message) => diagnosticError(Object.assign(new Error(message), { code }))
|
|
57
|
+
|
|
58
|
+
function readSmallText(file, maxBytes = 128 * 1024) {
|
|
59
|
+
const stat = fs.statSync(file)
|
|
60
|
+
if (!stat.isFile() || stat.size > maxBytes) throw Object.assign(new Error('diagnostic metadata exceeds the read limit'), { code: 'MEMU_METADATA_READ_LIMIT' })
|
|
61
|
+
return fs.readFileSync(file, 'utf8')
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function installedEngineMetadata(venv) {
|
|
65
|
+
let pythonVersion = null, distributionVersion = null, error = null
|
|
66
|
+
try {
|
|
67
|
+
const config = readSmallText(path.join(venv, 'pyvenv.cfg'))
|
|
68
|
+
pythonVersion = metadataVersion(config.match(/^version\s*=\s*([^\r\n]+)$/mi)?.[1]?.trim())
|
|
69
|
+
} catch (caught) { if (caught?.code !== 'ENOENT') error = diagnosticError(caught) }
|
|
70
|
+
const sites = [path.join(venv, 'Lib', 'site-packages')]
|
|
71
|
+
try {
|
|
72
|
+
const entries = fs.readdirSync(path.join(venv, 'lib'), { withFileTypes: true })
|
|
73
|
+
for (const entry of entries.filter(entry => entry.isDirectory() && /^python\d+\.\d+$/.test(entry.name)).slice(0, 4)) sites.push(path.join(venv, 'lib', entry.name, 'site-packages'))
|
|
74
|
+
} catch (caught) { if (caught?.code !== 'ENOENT') error ||= diagnosticError(caught) }
|
|
75
|
+
let distributions = 0
|
|
76
|
+
for (const site of sites) {
|
|
77
|
+
try {
|
|
78
|
+
const entries = fs.readdirSync(site, { withFileTypes: true }).filter(entry => entry.isDirectory() && /^memu_cli-[A-Za-z0-9.+-]+\.dist-info$/i.test(entry.name)).slice(0, 8)
|
|
79
|
+
for (const entry of entries) {
|
|
80
|
+
const metadata = readSmallText(path.join(site, entry.name, 'METADATA'))
|
|
81
|
+
if (!/^Name:\s*memu-cli\s*$/mi.test(metadata)) continue
|
|
82
|
+
distributions++
|
|
83
|
+
distributionVersion ||= metadataVersion(metadata.match(/^Version:\s*([^\r\n]+)$/mi)?.[1]?.trim())
|
|
84
|
+
}
|
|
85
|
+
} catch (caught) { if (caught?.code !== 'ENOENT') error ||= diagnosticError(caught) }
|
|
86
|
+
}
|
|
87
|
+
return { python: { version: pythonVersion, source: 'current venv/pyvenv.cfg' },
|
|
88
|
+
distribution: { name: 'memu-cli', version: distributionVersion, entries: distributions, source: 'current venv site-packages/memu_cli-*.dist-info/METADATA' },
|
|
89
|
+
execution: 'unknown', error }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function readDiagnosticJson(file, maxBytes = 16 * 1024 * 1024) {
|
|
93
|
+
try {
|
|
94
|
+
const stat = fs.statSync(file)
|
|
95
|
+
if (!stat.isFile() || stat.size > maxBytes) throw Object.assign(new Error('diagnostic metadata exceeds the read limit'), { code: 'MEMU_METADATA_READ_LIMIT' })
|
|
96
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
97
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw Object.assign(new Error('invalid JSON metadata object'), { code: 'MEMU_METADATA_INVALID' })
|
|
98
|
+
return { status: 'observed', value }
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (error?.code === 'ENOENT') return { status: 'absent', value: null }
|
|
101
|
+
return { status: 'error', value: null, error: diagnosticError(error) }
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Unlike engineStatus(), this never reconciles installs, deletes files or runs Python. */
|
|
106
|
+
export function readEngineDiagnosticState() {
|
|
107
|
+
const currentRead = readDiagnosticJson(path.join(dataDir(), 'engine', 'current.json'), 256 * 1024)
|
|
108
|
+
const stateRead = readDiagnosticJson(path.join(dataDir(), 'engine', 'state.json'), 256 * 1024)
|
|
109
|
+
const current = currentRead.value
|
|
110
|
+
const state = stateRead.value
|
|
111
|
+
const installStatus = ['ready', 'installing', 'failed', 'error', 'absent'].includes(state?.status) ? state.status : 'unknown'
|
|
112
|
+
const valid = Boolean(current && typeof current.python === 'string' && path.isAbsolute(current.python) && typeof current.venv === 'string' && path.isAbsolute(current.venv))
|
|
113
|
+
let exists = false, executableError = null
|
|
114
|
+
try { exists = valid && fs.statSync(current.python).isFile() } catch (caught) { if (caught?.code !== 'ENOENT') executableError = diagnosticError(caught) }
|
|
115
|
+
const installed = valid ? installedEngineMetadata(current.venv) : null
|
|
116
|
+
const recordedError = state?.error ? diagnosticError(typeof state.error === 'object' ? state.error : new Error(String(state.error))) : null
|
|
117
|
+
const error = currentRead.error || stateRead.error || executableError || (current && !valid ? diagnosticError(Object.assign(new Error('invalid engine metadata'), { code: 'ENGINE_METADATA_INVALID' })) : null)
|
|
118
|
+
return {
|
|
119
|
+
status: error ? 'error' : exists ? 'ready' : installStatus === 'installing' ? 'installing' : valid ? 'missing' : state ? installStatus : 'absent',
|
|
120
|
+
version: metadataVersion(current?.version),
|
|
121
|
+
source: 'engine/current.json + engine/state.json (metadata only; no process health probe)',
|
|
122
|
+
recommendedVersion: ENGINE_VERSION,
|
|
123
|
+
current: valid ? { version: metadataVersion(current.version), python: diagnosticText(current.python), executableExists: exists } : null,
|
|
124
|
+
installed,
|
|
125
|
+
install: { status: installStatus, step: typeof state?.step === 'string' && /^[a-z][a-z0-9-]{0,79}$/.test(state.step) ? state.step : null, error: recordedError },
|
|
126
|
+
error,
|
|
127
|
+
}
|
|
128
|
+
}
|
|
48
129
|
|
|
49
130
|
function item(id, level, title, extra = {}) {
|
|
50
|
-
|
|
131
|
+
const policy = diagnosticPolicy(extra.code || '', id.startsWith('vector') ? 'vector' : id === 'engine' ? 'engine' : 'plugin')
|
|
132
|
+
return { id, level, ok: level === 'ok' || level === 'skipped', title: diagnosticText(title), detail: '', hint: '', repair: null, auto: false, manual: false,
|
|
133
|
+
...extra, ...(extra.detail ? { detail: diagnosticText(extra.detail) } : {}), ...(extra.hint ? { hint: diagnosticText(extra.hint) } : {}),
|
|
134
|
+
layer: policy.layer, retry: policy.retry, action: extra.hint ? diagnosticText(extra.hint) : policy.action,
|
|
135
|
+
}
|
|
51
136
|
}
|
|
52
137
|
|
|
53
138
|
/** dataDir 可写:连自检结果都落不了盘的时候,别的检查也没有意义。 */
|
|
54
139
|
function checkDataDir(items) {
|
|
55
140
|
try {
|
|
56
141
|
const dir = dataDir()
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
fs.
|
|
60
|
-
fs.
|
|
61
|
-
items.push(item('data-dir', 'ok', '
|
|
142
|
+
// A diagnostic read must not create a home or a transient file inside it.
|
|
143
|
+
let parent = dir
|
|
144
|
+
while (!fs.existsSync(parent) && path.dirname(parent) !== parent) parent = path.dirname(parent)
|
|
145
|
+
fs.accessSync(parent, fs.constants.R_OK | fs.constants.W_OK)
|
|
146
|
+
items.push(item('data-dir', 'ok', '数据目录权限可读可写(未执行写探针)', { detail: diagnosticText(dir) }))
|
|
62
147
|
return true
|
|
63
148
|
} catch (error) {
|
|
149
|
+
const shaped = diagnosticError(error)
|
|
64
150
|
items.push(item('data-dir', 'error', '数据目录不可写', {
|
|
65
|
-
detail:
|
|
151
|
+
code: 'STATE_DATA_ACCESS_FAILED', detail: shaped.message, error: shaped,
|
|
66
152
|
hint: '检查磁盘权限/剩余空间;$DSH_HOME 指到只读位置时插件无法保存任何记忆。',
|
|
67
153
|
}))
|
|
154
|
+
recordErrorDiagnostic(error, { code: 'STATE_DATA_ACCESS_FAILED', source: 'environment-check', operation: 'data-dir', alert: false })
|
|
68
155
|
return false
|
|
69
156
|
}
|
|
70
157
|
}
|
|
@@ -73,7 +160,9 @@ function checkDataDir(items) {
|
|
|
73
160
|
function checkLocks(items) {
|
|
74
161
|
let scanned = []
|
|
75
162
|
try { scanned = scanMemoryLocks({ root: dataDir() }) } catch (error) {
|
|
76
|
-
|
|
163
|
+
const shaped = diagnosticError(error)
|
|
164
|
+
items.push(item('locks', 'warn', '无法扫描锁文件', { code: 'STATE_LOCK_SCAN_FAILED', detail: shaped.message, error: shaped }))
|
|
165
|
+
recordErrorDiagnostic(error, { code: 'STATE_LOCK_SCAN_FAILED', source: 'environment-check', operation: 'locks', alert: false })
|
|
77
166
|
return
|
|
78
167
|
}
|
|
79
168
|
const stale = scanned.filter(lock => lock.stale)
|
|
@@ -96,15 +185,22 @@ function checkLocks(items) {
|
|
|
96
185
|
|
|
97
186
|
function checkEngine(items) {
|
|
98
187
|
let backend
|
|
99
|
-
try { backend = getMemoryBackend() } catch {
|
|
188
|
+
try { backend = getMemoryBackend() } catch (error) {
|
|
189
|
+
recordErrorDiagnostic(error, { code: 'STATE_SETTINGS_READ_FAILED', source: 'environment-check', operation: 'engine-backend', alert: false })
|
|
190
|
+
items.push(item('settings', 'error', '无法读取当前引擎路由', { code: 'STATE_SETTINGS_READ_FAILED', error: diagnosticError(error) }))
|
|
191
|
+
backend = null
|
|
192
|
+
}
|
|
100
193
|
if (backend === 'agent') { items.push(item('engine', 'skipped', '本地 agent 模式不依赖 MemU 引擎')); return }
|
|
101
194
|
let status
|
|
102
|
-
try { status =
|
|
103
|
-
|
|
195
|
+
try { status = readEngineDiagnosticState() } catch (error) {
|
|
196
|
+
const shaped = diagnosticError(error)
|
|
197
|
+
items.push(item('engine', 'error', '读不到引擎状态', { code: 'ENGINE_METADATA_READ_FAILED', detail: shaped.message, error: shaped, repair: 'reinstall-engine', manual: true }))
|
|
198
|
+
recordErrorDiagnostic(error, { code: 'ENGINE_METADATA_READ_FAILED', source: 'environment-check', operation: 'engine-metadata', alert: false })
|
|
104
199
|
return
|
|
105
200
|
}
|
|
106
|
-
|
|
107
|
-
if (status
|
|
201
|
+
const layer = reportEngine(status, backend === 'api' ? 'managed-local' : 'unknown')
|
|
202
|
+
if (layer.status === 'installing') { items.push(item('engine', 'skipped', '引擎正在安装中')); return }
|
|
203
|
+
if (status?.status === 'ready' && layer.status !== 'error') {
|
|
108
204
|
const version = status.current?.version || ''
|
|
109
205
|
if (version !== ENGINE_VERSION) {
|
|
110
206
|
items.push(item('engine', 'warn', `引擎版本不是当前插件要的 ${ENGINE_VERSION}(现在是 ${version || '未知'})`, {
|
|
@@ -120,7 +216,7 @@ function checkEngine(items) {
|
|
|
120
216
|
return
|
|
121
217
|
}
|
|
122
218
|
items.push(item('engine', 'error', `引擎不可用(${status?.status || 'unknown'})`, {
|
|
123
|
-
detail:
|
|
219
|
+
code: layer.code, error: layer.error, detail: layer.error?.message || '',
|
|
124
220
|
hint: '缺 Python venv 或引擎包损坏时,语义召回与整理都会退化成词法/跳过。',
|
|
125
221
|
repair: 'reinstall-engine',
|
|
126
222
|
auto: getSettingsSafe().autoInstallEngine !== false,
|
|
@@ -129,11 +225,15 @@ function checkEngine(items) {
|
|
|
129
225
|
}
|
|
130
226
|
|
|
131
227
|
function getSettingsSafe() {
|
|
132
|
-
try { return getSettings() || {} } catch
|
|
228
|
+
try { return getSettings() || {} } catch (error) {
|
|
229
|
+
recordErrorDiagnostic(error, { code: 'STATE_SETTINGS_READ_FAILED', source: 'environment-check', operation: 'engine-backend', alert: false })
|
|
230
|
+
return {}
|
|
231
|
+
}
|
|
133
232
|
}
|
|
134
233
|
|
|
135
234
|
function vectorEnabled() {
|
|
136
|
-
|
|
235
|
+
// The per-check guard reports real settings failures; false means disabled.
|
|
236
|
+
return getMemoryBackend() === 'api' && getSettings().vectorSource === 'local'
|
|
137
237
|
}
|
|
138
238
|
|
|
139
239
|
/**
|
|
@@ -153,8 +253,9 @@ function checkVectorProfile(items) {
|
|
|
153
253
|
return null
|
|
154
254
|
}
|
|
155
255
|
const resignable = code === VECTOR_ERROR_CODES.PROFILE_MANIFEST_CHANGED || code === VECTOR_ERROR_CODES.PROFILE_UNKNOWN
|
|
256
|
+
const shaped = diagnosticError(error)
|
|
156
257
|
items.push(item('vector-profile', code ? 'error' : 'warn', `向量 profile 校验失败(${code || 'unknown'})`, {
|
|
157
|
-
detail:
|
|
258
|
+
code: shaped.code, detail: shaped.message, error: shaped,
|
|
158
259
|
hint: resignable
|
|
159
260
|
? '制品清单只是元数据变了(镜像源、文案),重签摘要即可,已算好的向量不用重算。'
|
|
160
261
|
: '制品身份变了或索引文件损坏,需要重建向量代际(会重算全部条目)。',
|
|
@@ -163,6 +264,7 @@ function checkVectorProfile(items) {
|
|
|
163
264
|
manual: true,
|
|
164
265
|
changedFields: Array.isArray(error?.changedFields) ? error.changedFields : undefined,
|
|
165
266
|
}))
|
|
267
|
+
recordErrorDiagnostic(error, { source: 'environment-check', operation: 'vector-profile', alert: false })
|
|
166
268
|
return null
|
|
167
269
|
}
|
|
168
270
|
if (!profile) { items.push(item('vector-profile', 'ok', '没有向量 profile')); return null }
|
|
@@ -203,7 +305,11 @@ function checkVectorProfile(items) {
|
|
|
203
305
|
|
|
204
306
|
function checkWorker(items) {
|
|
205
307
|
let status = null
|
|
206
|
-
try { status = embeddingWorkerManager().status() } catch {
|
|
308
|
+
try { status = embeddingWorkerManager().status() } catch (error) {
|
|
309
|
+
const shaped = diagnosticError(error)
|
|
310
|
+
items.push(item('vector-worker', 'warn', '无法读取嵌入 worker 状态', { code: 'LOCAL_VECTOR_STATUS_FAILED', detail: shaped.message, error: shaped }))
|
|
311
|
+
recordErrorDiagnostic(error, { code: 'LOCAL_VECTOR_STATUS_FAILED', source: 'environment-check', operation: 'worker-status', alert: false })
|
|
312
|
+
}
|
|
207
313
|
if (!status) return
|
|
208
314
|
if (status.tripped) {
|
|
209
315
|
items.push(item('vector-worker', 'warn', '嵌入 worker 反复崩溃已被熔断', {
|
|
@@ -227,21 +333,35 @@ function checkEntityFragments(items) {
|
|
|
227
333
|
try {
|
|
228
334
|
plan = planAllRepairs({ loadPrivateIndex, listLibraries })
|
|
229
335
|
} catch (error) {
|
|
336
|
+
const shaped = diagnosticError(error)
|
|
230
337
|
items.push(item('entity-fragments', 'warn', '实体碎片检查没跑成', {
|
|
231
|
-
detail:
|
|
338
|
+
code: 'STATE_ENTITY_SCAN_FAILED', detail: shaped.message, error: shaped,
|
|
232
339
|
hint: '检查是只读的;跑不成通常是某个库的实体档案读不出来。可以先跑 scripts/entity-dedupe.mjs 看细节。',
|
|
233
340
|
}))
|
|
341
|
+
recordErrorDiagnostic(error, { code: 'STATE_ENTITY_SCAN_FAILED', source: 'environment-check', operation: 'entity-fragments', alert: false })
|
|
234
342
|
return
|
|
235
343
|
}
|
|
236
344
|
const similar = plan.similar
|
|
237
345
|
const attested = plan.attested
|
|
238
346
|
if (plan.failures.length) {
|
|
239
347
|
for (const failure of plan.failures) {
|
|
240
|
-
|
|
241
|
-
|
|
348
|
+
const shaped = diagnosticError(new Error(String(failure.error)))
|
|
349
|
+
items.push(item('entity-fragments', 'warn', `某个库的碎片检查失败:${diagnosticRef(failure.libraryId)}`, {
|
|
350
|
+
code: 'STATE_ENTITY_SCAN_FAILED', detail: shaped.message, error: shaped, hint: '修好该库的档案后重新检查即可,其它库不受影响。',
|
|
242
351
|
}))
|
|
352
|
+
recordErrorDiagnostic(new Error(String(failure.error)), { code: 'STATE_ENTITY_SCAN_FAILED', source: 'environment-check', operation: 'entity-fragments', context: { libraryId: failure.libraryId }, alert: false })
|
|
243
353
|
}
|
|
244
354
|
}
|
|
355
|
+
if (plan.partial || plan.deferred) {
|
|
356
|
+
items.push(item('entity-fragments', 'warn', '实体碎片规划未完成,不能判定为干净', {
|
|
357
|
+
code: 'ENTITY_REPAIR_DEFERRED', partial: true, deferred: true,
|
|
358
|
+
totalEntities: plan.totalEntities, totalEntitiesExact: plan.totalEntitiesExact,
|
|
359
|
+
scanned: plan.scanned, entityLimit: plan.entityLimit,
|
|
360
|
+
detail: `已进入规划 ${plan.scanned} 个实体,已知实体总数 ${plan.totalEntities};单库同步规划上限 ${plan.entityLimit}。未执行合并。`,
|
|
361
|
+
hint: '请到「图管理」按批核对候选;大库或证据不完整时不会自动合并,未扫描不代表没有碎片。',
|
|
362
|
+
}))
|
|
363
|
+
return
|
|
364
|
+
}
|
|
245
365
|
if (!similar && !attested) {
|
|
246
366
|
items.push(item('entity-fragments', 'ok', '没有待确认的实体碎片候选'))
|
|
247
367
|
return
|
|
@@ -263,22 +383,33 @@ function checkEntityFragments(items) {
|
|
|
263
383
|
|
|
264
384
|
/**
|
|
265
385
|
* 跑一遍自检。
|
|
266
|
-
* @param {{deep?: boolean}} options deep=true
|
|
386
|
+
* @param {{deep?: boolean}} options deep=true 时追加引擎元数据核对,不启动 Python。
|
|
267
387
|
*/
|
|
268
388
|
export function runEnvironmentCheck({ deep = false } = {}) {
|
|
269
389
|
const items = []
|
|
270
390
|
const writable = checkDataDir(items)
|
|
271
391
|
if (writable) {
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
392
|
+
const checked = (id, check) => {
|
|
393
|
+
try { return check(items) } catch (error) {
|
|
394
|
+
const shaped = diagnosticError(error)
|
|
395
|
+
items.push(item(id, 'error', '环境检查失败', { code: 'MEMU_ENVIRONMENT_CHECK_FAILED', detail: shaped.message, error: shaped }))
|
|
396
|
+
recordErrorDiagnostic(error, { code: 'MEMU_ENVIRONMENT_CHECK_FAILED', source: 'environment-check', operation: id, alert: false })
|
|
397
|
+
return null
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
checked('locks', checkLocks)
|
|
401
|
+
checked('engine', checkEngine)
|
|
402
|
+
const profile = checked('vector-profile', checkVectorProfile)
|
|
403
|
+
checked('vector-worker', checkWorker)
|
|
404
|
+
checked('entity-fragments', checkEntityFragments)
|
|
277
405
|
if (deep && profile) {
|
|
278
406
|
try {
|
|
279
|
-
const status =
|
|
280
|
-
items.push(item('engine-
|
|
281
|
-
} catch {
|
|
407
|
+
const status = readEngineDiagnosticState()
|
|
408
|
+
items.push(item('engine-metadata', status.error ? 'warn' : 'ok', '引擎元数据已核对(未启动 Python)', { detail: status.error?.message || status.version || 'unknown' }))
|
|
409
|
+
} catch (error) {
|
|
410
|
+
items.push(item('engine-metadata', 'warn', '引擎元数据核对失败', { detail: diagnosticError(error).message }))
|
|
411
|
+
recordErrorDiagnostic(error, { code: 'ENGINE_METADATA_READ_FAILED', source: 'environment-check', operation: 'engine-metadata', alert: false })
|
|
412
|
+
}
|
|
282
413
|
}
|
|
283
414
|
}
|
|
284
415
|
const counts = { ok: 0, warn: 0, error: 0, skipped: 0 }
|
|
@@ -295,9 +426,169 @@ export function runEnvironmentCheck({ deep = false } = {}) {
|
|
|
295
426
|
repairs,
|
|
296
427
|
autoRepairs: failed.filter(entry => entry.repair && entry.auto).map(entry => entry.repair),
|
|
297
428
|
manualRepairs: failed.filter(entry => entry.repair && entry.manual).map(entry => entry.repair),
|
|
429
|
+
runtime: diagnosticRuntime(),
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function diagnosticLayer(status, source, evidence, code = null, error = null) {
|
|
434
|
+
const policy = diagnosticPolicy(code || '', source)
|
|
435
|
+
return { status, source, evidence, code, error, retry: policy.retry, action: policy.action }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function reportEngine(engine, route) {
|
|
439
|
+
const required = route === 'lexical' ? false : ['managed-local', 'remote-api'].includes(route) ? true : null
|
|
440
|
+
const integrityError = engine.error || engine.installed?.error
|
|
441
|
+
const installFailed = ['error', 'failed'].includes(engine.install.status)
|
|
442
|
+
const installError = installFailed ? { ...(engine.install.error || failure('ENGINE_INSTALL_FAILED', 'engine installation failed')), code: 'ENGINE_INSTALL_FAILED' } : null
|
|
443
|
+
const missing = ['absent', 'missing'].includes(engine.status)
|
|
444
|
+
const drift = Boolean(engine.installed?.distribution.version && engine.current?.version && engine.installed.distribution.version !== engine.current.version)
|
|
445
|
+
const error = integrityError || (required ? installError || (missing ? failure('ENGINE_MISSING', 'engine not installed') : null) : null)
|
|
446
|
+
const warning = drift ? failure('ENGINE_METADATA_VERSION_MISMATCH', 'engine metadata version mismatch') : required && !installFailed ? engine.install.error : null
|
|
447
|
+
const status = error ? 'error' : warning ? 'degraded' : required === false ? 'skipped' : engine.status === 'ready' ? 'observed' : engine.status === 'installing' ? 'installing' : 'unknown'
|
|
448
|
+
const evidence = { ...engine, route, required, affectsCurrentRoute: error || warning ? required : false,
|
|
449
|
+
note: required === false ? 'The current lexical route does not use MemU; missing or failed optional installs do not affect it. Metadata corruption remains visible separately.'
|
|
450
|
+
: required === true ? 'The current route requires MemU. Current executable presence and the latest install result are separate evidence; execution is not probed.'
|
|
451
|
+
: 'The route could not be observed; installed metadata alone does not establish whether MemU is required.',
|
|
452
|
+
}
|
|
453
|
+
return diagnosticLayer(status, 'engine', evidence, error?.code || warning?.code || null, error || warning)
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function reportState() {
|
|
457
|
+
const snapshot = readDiagnosticJson(path.join(dataDir(), 'state.json'))
|
|
458
|
+
if (snapshot.status !== 'observed') return { snapshot, evidence: { sessions: null, libraries: null, recentFailures: [] } }
|
|
459
|
+
const state = snapshot.value
|
|
460
|
+
if (['sessions', 'libraries', 'settings'].some(key => state[key] !== undefined && (!state[key] || typeof state[key] !== 'object' || Array.isArray(state[key])))) {
|
|
461
|
+
return { snapshot: { status: 'error', error: diagnosticError(Object.assign(new Error('invalid JSON state shape'), { code: 'STATE_INVALID' })) }, evidence: { sessions: null, libraries: null, recentFailures: [] } }
|
|
462
|
+
}
|
|
463
|
+
const recentFailures = []
|
|
464
|
+
let workerEpochs = 0
|
|
465
|
+
let recallFailures = 0
|
|
466
|
+
let consolidationFailures = 0
|
|
467
|
+
for (const [sessionId, binding] of Object.entries(state.sessions || {})) {
|
|
468
|
+
if (!binding || typeof binding !== 'object') continue
|
|
469
|
+
if (binding.workerEpoch) workerEpochs++
|
|
470
|
+
if (binding.lastRecallError) recallFailures++
|
|
471
|
+
if (binding.lastSleepError || binding.lastInboundError) consolidationFailures++
|
|
472
|
+
for (const [field, operation] of [['lastRecallError', 'recall'], ['lastSleepError', 'consolidation'], ['lastInboundError', 'inbound']]) {
|
|
473
|
+
if (!binding[field]) continue
|
|
474
|
+
const shaped = diagnosticError(new Error(String(binding[field])))
|
|
475
|
+
recentFailures.push({ sessionRef: diagnosticRef(sessionId), operation, at: typeof binding[field + 'At'] === 'string' ? diagnosticText(binding[field + 'At'], 80) : null, error: shaped })
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
const settings = state.settings || {}
|
|
479
|
+
const route = effectiveVectorRoute(settings)
|
|
480
|
+
return { snapshot, evidence: { sessions: Object.keys(state.sessions || {}).length, libraries: Object.keys(state.libraries || {}).length,
|
|
481
|
+
workerEpochs, recallFailures, consolidationFailures, route, consolidationRunner: ['worker', 'fork'].includes(settings.consolidationRunner) ? settings.consolidationRunner : 'fork',
|
|
482
|
+
recentFailures: recentFailures.slice(-30),
|
|
483
|
+
} }
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function reportVector(route) {
|
|
487
|
+
try {
|
|
488
|
+
const manifestRead = readDiagnosticJson(vectorActiveFile())
|
|
489
|
+
if (manifestRead.status === 'error') return diagnosticLayer('error', 'vector', { route }, manifestRead.error?.name === 'SyntaxError' ? 'VECTOR_ACTIVE_CORRUPT' : 'VECTOR_ACTIVE_UNREADABLE', manifestRead.error)
|
|
490
|
+
const state = readVectorState().state
|
|
491
|
+
if (!state?.active) return diagnosticLayer(route === 'managed-local' ? 'not-built' : 'skipped', 'vector', { route, active: false, pending: Boolean(state?.pending), reason: 'No active database is a normal local-only downgrade, not an error.' })
|
|
492
|
+
const active = state.active
|
|
493
|
+
const profile = active.profile
|
|
494
|
+
let verificationError = null
|
|
495
|
+
let metadataDrift = []
|
|
496
|
+
try {
|
|
497
|
+
const catalog = resolveCatalogEntry(profile?.catalogId)
|
|
498
|
+
if (!catalog) throw Object.assign(new Error('unknown vector profile'), { code: 'VECTOR_PROFILE_UNKNOWN' })
|
|
499
|
+
if (!manifestDigestAccepted(profile.manifestDigest, catalog)) {
|
|
500
|
+
const drift = manifestDrift(profile.manifest, catalog)
|
|
501
|
+
if (!drift.fields.length || drift.identityChanged.length) throw Object.assign(new Error('vector profile manifest changed'), { code: 'VECTOR_PROFILE_MANIFEST_CHANGED' })
|
|
502
|
+
metadataDrift = drift.metadataOnly
|
|
503
|
+
}
|
|
504
|
+
// Verify the exact captured profile, avoiding activeProfile's second read
|
|
505
|
+
// and its metadata-drift warning (which could write diagnostic events).
|
|
506
|
+
assertProfileVerified({ ...profile, manifestDigest: manifestDigest(catalog) })
|
|
507
|
+
} catch (error) { verificationError = diagnosticError(error) }
|
|
508
|
+
const runtimeDir = profile?.runtimeDir
|
|
509
|
+
const runtimePackage = runtimeDir ? readDiagnosticJson(path.join(runtimeDir, 'node_modules', 'onnxruntime-node', 'package.json'), 256 * 1024) : { status: 'absent' }
|
|
510
|
+
const modelMissingFiles = MODEL_REQUIRED_FILES.filter(name => {
|
|
511
|
+
try { return !fs.statSync(path.join(profile?.modelDir || '', name)).isFile() } catch { return true }
|
|
512
|
+
})
|
|
513
|
+
const graphFile = profile?.files?.find(file => file.role === 'graph')
|
|
514
|
+
if (graphFile && (!profile.modelDir || !fs.existsSync(path.join(profile.modelDir, graphFile.path)))) modelMissingFiles.push('graph')
|
|
515
|
+
const databases = [active.databases?.global, ...Object.values(active.databases?.libraries || {})].filter(Boolean)
|
|
516
|
+
let missingDatabases = 0
|
|
517
|
+
for (const db of databases) if (!fs.existsSync(resolveVectorPath(db.path))) missingDatabases++
|
|
518
|
+
const evidence = {
|
|
519
|
+
route, active: true, generation: active.generation, catalogId: resolveCatalogEntry(profile?.catalogId)?.id || null,
|
|
520
|
+
fingerprint: /^[a-f0-9]{64}$/.test(active.fingerprint) ? active.fingerprint : null, dimension: Number(profile?.dimension) || null,
|
|
521
|
+
profileVerification: verificationError ? 'failed' : 'observed', manifestMetadataDrift: metadataDrift,
|
|
522
|
+
runtime: { package: 'onnxruntime-node', version: runtimePackage.value?.name === 'onnxruntime-node' ? metadataVersion(runtimePackage.value.version) : null,
|
|
523
|
+
source: 'active-profile/runtimeDir/node_modules/onnxruntime-node/package.json', installed: Boolean(runtimeDir && hasEmbeddingRuntimePackages(runtimeDir)) },
|
|
524
|
+
model: { source: 'active-profile/modelDir file presence (no weights read)', missingFiles: modelMissingFiles },
|
|
525
|
+
databases: { declared: databases.length, missing: missingDatabases }, pending: Boolean(state.pending),
|
|
526
|
+
}
|
|
527
|
+
const code = verificationError?.code || runtimePackage.error?.code || (!evidence.runtime.installed || runtimePackage.value?.name !== 'onnxruntime-node' ? 'LOCAL_VECTOR_RUNTIME_MISSING' : modelMissingFiles.length ? 'LOCAL_VECTOR_MODEL_MISSING' : missingDatabases ? 'VECTOR_DATABASE_MISSING' : null)
|
|
528
|
+
// Unmapped libraries are a normal downgrade. A *declared* database that has
|
|
529
|
+
// disappeared is artifact loss, not the normal no-database membership case.
|
|
530
|
+
return diagnosticLayer(code ? 'error' : 'observed', 'vector', evidence, code, verificationError || runtimePackage.error || (code ? failure(code, 'local vector artifacts missing') : null))
|
|
531
|
+
} catch (error) {
|
|
532
|
+
const shaped = diagnosticError(error)
|
|
533
|
+
return diagnosticLayer('error', 'vector', { route }, shaped.code, shaped)
|
|
298
534
|
}
|
|
299
535
|
}
|
|
300
536
|
|
|
537
|
+
/** Copyable support report: bounded metadata/counters only, no repair and no provider calls. */
|
|
538
|
+
export function collectDiagnosticReport({ limit = 100 } = {}) {
|
|
539
|
+
const generatedAt = new Date().toISOString()
|
|
540
|
+
const runtime = diagnosticRuntime()
|
|
541
|
+
const state = reportState()
|
|
542
|
+
const engine = readEngineDiagnosticState()
|
|
543
|
+
const vector = reportVector(state.evidence.route || 'unknown')
|
|
544
|
+
const listing = listDiagnostics({ limit: Math.max(1, Math.min(100, Number(limit) || 100)) })
|
|
545
|
+
const exportedItems = listing.items.map(entry => ({ id: entry.id, at: entry.at, lastAt: entry.lastAt, level: entry.level, scope: entry.scope, code: entry.code,
|
|
546
|
+
message: diagnosticError({ message: entry.message, code: entry.code }).message, detail: diagnosticDetail(entry.code, entry.detail), context: diagnosticValue(entry.context),
|
|
547
|
+
hint: entry.hint, repair: entry.repair, manual: entry.manual, alert: entry.alert, count: entry.count, source: entry.source, layer: entry.layer,
|
|
548
|
+
operation: entry.operation, correlationId: entry.correlationId, error: entry.error ? diagnosticError(entry.error) : null, retry: entry.retry, action: entry.action, versions: entry.versions }))
|
|
549
|
+
const recentErrors = exportedItems.filter(entry => entry.level !== 'info')
|
|
550
|
+
const stats = diagnosticStats()
|
|
551
|
+
const protections = readFailuresUnder(dataDir()).slice(0, 30).map(row => ({ file: diagnosticText(row.file), code: diagnosticText(row.code || '', 80), kind: diagnosticText(row.kind || '', 60) }))
|
|
552
|
+
let worker, rt, lexiconRt, graphAdjacency
|
|
553
|
+
try { worker = embeddingWorkerManager().status() } catch (error) { worker = { error: diagnosticError(error) } }
|
|
554
|
+
try { rt = rtServiceDiagnostics() } catch (error) { rt = { error: diagnosticError(error) } }
|
|
555
|
+
try { lexiconRt = lexiconRtDiagnostics() } catch (error) { lexiconRt = { error: diagnosticError(error) } }
|
|
556
|
+
try { graphAdjacency = diagnosticGraphAdjacency(graphAdjacencyDiagnostics()) } catch (error) { graphAdjacency = { error: diagnosticError(error) } }
|
|
557
|
+
const embedding = { running: finiteCount(worker.running), booting: finiteCount(worker.booting), closed: worker.closed === true, tripped: finiteCount(worker.tripped), error: worker.error || null }
|
|
558
|
+
const rtIndex = { mode: ['off', 'shadow', 'on'].includes(rt.mode) ? rt.mode : 'unknown', active: rt.active === true,
|
|
559
|
+
...Object.fromEntries(['builds', 'failedBuilds', 'staleBuilds', 'deltas', 'fallbacks', 'shadowQueries', 'shadowMismatches', 'shadowBodies', 'shadowBodyMismatches', 'pending'].map(key => [key, finiteCount(rt[key])])),
|
|
560
|
+
views: Object.fromEntries(['size', 'bytes', 'maxBytes', 'maxEntries', 'ttlMs', 'hits', 'misses', 'evictions', 'expirations', 'oversized'].map(key => [key, finiteCount(rt.views?.[key])])), error: rt.error || null }
|
|
561
|
+
const rpcFailures = recentErrors.filter(row => row.layer === 'rpc')
|
|
562
|
+
const layers = {
|
|
563
|
+
host: diagnosticLayer(runtime.host.status, 'host', runtime.host),
|
|
564
|
+
plugin: diagnosticLayer(stats.persistence.status === 'failed' ? 'degraded' : 'observed', 'plugin', { ...runtime.plugin, diagnosticPersistence: stats.persistence }),
|
|
565
|
+
engine: reportEngine(engine, state.evidence.route || 'unknown'),
|
|
566
|
+
vector,
|
|
567
|
+
state: diagnosticLayer(state.snapshot.status === 'error' || protections.length ? 'error' : state.snapshot.status, 'state', { ...state.evidence, readProtections: protections }, state.snapshot.error?.code || null, state.snapshot.error || null),
|
|
568
|
+
rpc: diagnosticLayer(rpcFailures.length ? 'degraded' : runtime.host.capabilities.rpcGuard === 'unknown' ? 'unknown' : 'observed', 'rpc', { guard: runtime.host.capabilities.rpcGuard, recentFailures: rpcFailures.length,
|
|
569
|
+
note: 'Capability observation is not an end-to-end RPC health test.' }),
|
|
570
|
+
workers: diagnosticLayer(worker.error || rt.error || lexiconRt.error || graphAdjacency.error || worker.tripped || state.evidence.consolidationFailures ? 'degraded' : worker.running || rt.active || lexiconRt.active ? 'observed' : 'unknown', 'workers', { embedding, rtIndex, lexiconRt, graphAdjacency,
|
|
571
|
+
consolidation: { persistedEpochs: state.evidence.workerEpochs ?? null, recentFailures: state.evidence.consolidationFailures ?? null, processHealth: 'unknown' },
|
|
572
|
+
residentPython: { status: 'unknown', reason: 'No read-only process-health API; installed metadata does not prove the resident is running.' },
|
|
573
|
+
}),
|
|
574
|
+
}
|
|
575
|
+
const items = Object.entries(layers).map(([id, layer]) => ({ id, level: layer.status === 'error' ? 'error' : layer.status === 'degraded' ? 'warn' : layer.status === 'observed' ? 'ok' : 'skipped',
|
|
576
|
+
title: id, ok: ['observed', 'skipped', 'not-built'].includes(layer.status), detail: layer.code || layer.status, hint: layer.action, repair: null }))
|
|
577
|
+
const counts = { ok: 0, warn: 0, error: 0, skipped: 0 }
|
|
578
|
+
for (const entry of items) counts[entry.level]++
|
|
579
|
+
const environment = { checkedAt: generatedAt, ok: counts.error === 0, attention: counts.error + counts.warn > 0, items, counts, repairs: [], autoRepairs: [], manualRepairs: [] }
|
|
580
|
+
const summary = { ...counts, recentErrors: recentErrors.length, diagnostics: stats.total,
|
|
581
|
+
limitations: ['Host version is observational only; compatibility uses capabilities, never version comparisons.', 'Metadata/file presence does not prove Python, model execution, remote providers or end-to-end RPC health.',
|
|
582
|
+
'Only registered diagnostic signals and persisted binding failures are visible; unknown worker states are not reported as healthy.', 'No config/profile secrets, memory text, original dialogue, process argv or environment values are exported.'] }
|
|
583
|
+
const unverified = Object.keys(layers).filter(key => ['unknown', 'absent', 'installing'].includes(layers[key].status))
|
|
584
|
+
const health = { ok: counts.error === 0, attention: counts.error + counts.warn > 0 || recentErrors.length > 0 || state.evidence.recallFailures > 0,
|
|
585
|
+
status: counts.error ? 'error' : counts.warn ? 'degraded' : unverified.length ? 'unknown' : 'observed',
|
|
586
|
+
coverage: { observed: counts.ok, total: items.length, unverified }, counts, limitations: summary.limitations }
|
|
587
|
+
const diagnostics = { items: exportedItems, counts: listing.counts, total: stats.total, returned: listing.total, capped: listing.capped }
|
|
588
|
+
const report = { schemaVersion: 1, schema: 'dsh-memu-memory/diagnostic-report@1', generatedAt, redacted: true, runtime, health, components: layers, environment, diagnostics, layers, recentErrors, summary }
|
|
589
|
+
return { ...report, text: JSON.stringify(report, null, 2) }
|
|
590
|
+
}
|
|
591
|
+
|
|
301
592
|
async function runRepairAction(action) {
|
|
302
593
|
switch (action) {
|
|
303
594
|
case 'release-stale-locks': {
|
|
@@ -336,6 +627,9 @@ async function runRepairAction(action) {
|
|
|
336
627
|
case 'merge-entity-fragments': {
|
|
337
628
|
// 只合"可证明"的那一类;相似候选留给关系图谱里逐个确认。备份在任何写之前。
|
|
338
629
|
const plan = planAllRepairs({ loadPrivateIndex, listLibraries })
|
|
630
|
+
if (plan.partial || plan.deferred) return { partial: true, deferred: true,
|
|
631
|
+
detail: `实体碎片规划未完成,已进入规划 ${plan.scanned} 个、已知总数 ${plan.totalEntities} 个,单库上限 ${plan.entityLimit};未执行合并,请到「图管理」按批核对。`,
|
|
632
|
+
data: plan }
|
|
339
633
|
if (!plan.attested) return { detail: `没有可证明的碎片可合并(相似候选 ${plan.similar} 组需要人工核对)`, data: plan }
|
|
340
634
|
await backupDatabases({ label: 'entity-repair' })
|
|
341
635
|
let merged = 0
|
|
@@ -349,10 +643,19 @@ async function runRepairAction(action) {
|
|
|
349
643
|
for (const failure of applied.failures) failures.push(`${entry.libraryId}/${failure.group}: ${failure.error}`)
|
|
350
644
|
}
|
|
351
645
|
return {
|
|
646
|
+
partial: failures.length > 0, deferred: failures.length > 0,
|
|
352
647
|
detail: `合并 ${merged} 组(新建完整名 ${created} 个),相似候选 ${plan.similar} 组未动${failures.length ? ',失败 ' + failures.length + ' 组' : ''}`,
|
|
353
|
-
data: { merged, created, similar: plan.similar, failures
|
|
648
|
+
data: { merged, created, similar: plan.similar, failures, totalEntities: plan.totalEntities,
|
|
649
|
+
totalEntitiesExact: plan.totalEntitiesExact, scanned: plan.scanned, entityLimit: plan.entityLimit },
|
|
354
650
|
}
|
|
355
651
|
}
|
|
652
|
+
case 'repair-maintenance-journal': {
|
|
653
|
+
// 只在显式点击时执行:锚点与数据对不上同样可能是篡改,读路径必须继续 fail-closed。
|
|
654
|
+
const { repairMaintenanceStore } = await import('./maintenance-ledger.js')
|
|
655
|
+
const repaired = repairMaintenanceStore()
|
|
656
|
+
if (!repaired) throw new Error('维护日志仍无法修复:确认没有其他实例占用该库后重试;原件已另存为 *.repaired-* / *.superseded-*')
|
|
657
|
+
return { detail: '已隔离旧 journal 并按当前数据重新锚定(原件另存为 *.repaired-* / *.superseded-*)', data: { repaired: true } }
|
|
658
|
+
}
|
|
356
659
|
default:
|
|
357
660
|
throw new Error('unknown repair action: ' + action)
|
|
358
661
|
}
|
|
@@ -371,10 +674,19 @@ export async function repairEnvironment({ actions = [], confirmed = false } = {}
|
|
|
371
674
|
const startedAt = new Date().toISOString()
|
|
372
675
|
try {
|
|
373
676
|
const result = await runRepairAction(action)
|
|
677
|
+
if (action === 'merge-entity-fragments' && result.partial) {
|
|
678
|
+
const progress = { partial: true, deferred: true, totalEntities: result.data.totalEntities,
|
|
679
|
+
totalEntitiesExact: result.data.totalEntitiesExact, scanned: result.data.scanned, entityLimit: result.data.entityLimit }
|
|
680
|
+
recordDiagnostic({ level: 'warn', scope: 'graph', code: 'ENTITY_REPAIR_DEFERRED',
|
|
681
|
+
message: result.detail, detail: progress, source: 'repair', operation: action, alert: false,
|
|
682
|
+
hint: '请到「图管理」逐个核对候选;本次修复未完成,不会因部分规划而自动合并。' })
|
|
683
|
+
results.push({ action, ok: false, code: 'ENTITY_REPAIR_DEFERRED', detail: result.detail, ...progress, startedAt })
|
|
684
|
+
continue
|
|
685
|
+
}
|
|
374
686
|
recordRepair({ action, ok: true, detail: result.detail, message: `repair ${action}: ${result.detail}` })
|
|
375
687
|
results.push({ action, ok: true, detail: result.detail, startedAt })
|
|
376
688
|
} catch (error) {
|
|
377
|
-
const detail =
|
|
689
|
+
const detail = diagnosticError(error).message
|
|
378
690
|
recordRepair({ action, ok: false, detail, message: `repair ${action} failed: ${detail}`, error })
|
|
379
691
|
results.push({ action, ok: false, detail, code: String(error?.code || ''), startedAt })
|
|
380
692
|
}
|
package/lib/feedback.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// P7.1: approval changes rehearsal strength; supersede remains a fact relation.
|
|
2
|
+
const count = value => Number.isSafeInteger(value) && value >= 0 ? value : 0
|
|
3
|
+
export const FEEDBACK_VERDICTS = Object.freeze(['confirm', 'deny', 'irrelevant'])
|
|
4
|
+
|
|
5
|
+
export function feedbackAccessFactor(entry) {
|
|
6
|
+
return 1 + Math.min(0.5, count(entry?.accessCount) * 0.05)
|
|
7
|
+
+ Math.min(0.3, count(entry?.feedback?.confirm) * 0.05)
|
|
8
|
+
- Math.min(0.6, count(entry?.feedback?.deny) * 0.2)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function applyMemoryFeedback(entry, verdict, reason, at) {
|
|
12
|
+
if (!FEEDBACK_VERDICTS.includes(verdict)) throw new Error('verdict must be confirm, deny or irrelevant')
|
|
13
|
+
if (typeof reason !== 'string' || !reason.trim()) throw new Error('feedback needs a reason grounded in observed feedback')
|
|
14
|
+
const previous = entry.feedback || {}
|
|
15
|
+
const feedback = {
|
|
16
|
+
confirm: count(previous.confirm), deny: count(previous.deny),
|
|
17
|
+
lastAt: at, lastVerdict: verdict, reason: reason.trim().slice(0, 500),
|
|
18
|
+
}
|
|
19
|
+
if (verdict !== 'irrelevant') feedback[verdict] = Math.min(Number.MAX_SAFE_INTEGER, feedback[verdict] + 1)
|
|
20
|
+
entry.feedback = feedback
|
|
21
|
+
if (feedback.deny >= 2) entry.marginalized = true
|
|
22
|
+
// A confirm never silently reverses an earlier marginalization or unpins a row.
|
|
23
|
+
delete entry.recallPenalty
|
|
24
|
+
return feedback
|
|
25
|
+
}
|