dsh-memu-memory 1.3.14 → 1.4.0
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 +6 -3
- package/CHANGELOG.md +50 -1
- package/docs/binding-lifecycle.md +1 -1
- package/docs/client-conventions.md +1 -0
- package/docs/host-adaptation.md +58 -16
- package/docs/host-versions.md +120 -0
- package/docs/memory-semantics.md +4 -1
- package/docs/pending-work.md +51 -0
- package/docs/troubleshooting.md +16 -3
- package/lib/auto-link/candidates.js +4 -1
- package/lib/auto-link/decide.js +1 -1
- package/lib/auto-link/normalize.js +2 -2
- package/lib/auto-link/terminology.js +31 -1
- package/lib/binding-diagnostics.js +1 -1
- package/lib/client.js +53 -6
- package/lib/consolidation-snapshot.js +37 -1
- package/lib/curator.js +1 -1
- package/lib/cycle.js +5 -0
- package/lib/diagnostics.js +10 -0
- package/lib/entity-repair.js +285 -0
- package/lib/environment-check.js +72 -3
- package/lib/global-graph.js +11 -2
- package/lib/graph.js +32 -8
- package/lib/host-surface.js +30 -0
- package/lib/index.js +116 -1
- package/lib/inject.js +428 -32
- package/lib/private-links.js +12 -0
- package/lib/rpc.js +78 -11
- package/lib/state.js +78 -1
- package/package.json +16 -1
- package/scripts/chain-matrix.mjs +4 -0
- package/scripts/check-doc-drift.mjs +194 -0
- package/scripts/entity-dedupe.mjs +110 -0
- package/tests/auto-link-candidates.test.mjs +22 -9
- package/tests/auto-link-decide.test.mjs +59 -59
- package/tests/auto-link-migration.test.mjs +4 -4
- package/tests/client-render.test.mjs +112 -1
- package/tests/cue.test.mjs +2 -1
- package/tests/cycle.test.mjs +2 -2
- package/tests/diagnostics.test.mjs +21 -0
- package/tests/doc-drift.test.mjs +122 -2
- package/tests/entity-merge.test.mjs +17 -0
- package/tests/environment-check.test.mjs +28 -0
- package/tests/global-graph.test.mjs +16 -0
- package/tests/global-lifecycle.test.mjs +24 -4
- package/tests/graph-cascade.test.mjs +111 -0
- package/tests/hybrid-recall.test.mjs +1 -1
- package/tests/inject.test.mjs +7 -7
- package/tests/injection-chain.test.mjs +40 -2
- package/tests/injection-rollback.test.mjs +4 -3
- package/tests/managed-memory.test.mjs +7 -7
- package/tests/media.test.mjs +4 -1
- package/tests/memory-chain.test.mjs +4 -3
- package/tests/pending-injection.test.mjs +107 -0
- package/tests/private-links.test.mjs +12 -0
- package/tests/recall-corpus-eligibility.test.mjs +3 -3
- package/tests/settings-plumbing.test.mjs +2 -0
- package/tests/tools.test.mjs +1 -1
- package/tests/webui-auth.test.mjs +58 -0
package/lib/environment-check.js
CHANGED
|
@@ -17,7 +17,8 @@ import fs from 'node:fs'
|
|
|
17
17
|
import path from 'node:path'
|
|
18
18
|
import { dataDir, ensureDir, scanMemoryLocks, releaseStaleLocks } from './paths.js'
|
|
19
19
|
import { engineStatus, ensureEngine, ENGINE_VERSION } from './engine.js'
|
|
20
|
-
import { getSettings, getMemoryBackend, backupDatabases } from './state.js'
|
|
20
|
+
import { getSettings, getMemoryBackend, backupDatabases, listLibraries, loadPrivateIndex } from './state.js'
|
|
21
|
+
import { planAllRepairs, applyRepairGroups } from './entity-repair.js'
|
|
21
22
|
import {
|
|
22
23
|
activeProfile, requestedProfile, resignVectorProfile, repointVectorRuntimeDir,
|
|
23
24
|
runtimeDirCandidates, vectorActiveFile, VECTOR_ERROR_CODES,
|
|
@@ -29,8 +30,8 @@ import { recordRepair } from './diagnostics.js'
|
|
|
29
30
|
// 启动路径可以自己跑的修复:都不联网、都不改变制品身份,最坏情况只是白跑一次。
|
|
30
31
|
export const SAFE_REPAIRS = Object.freeze(['release-stale-locks', 'resign-vector-profile', 'repoint-runtime-dir'])
|
|
31
32
|
|
|
32
|
-
// 需要人点按钮(联网下载 / 重算全部向量 /
|
|
33
|
-
export const MANUAL_REPAIRS = Object.freeze(['reinstall-runtime', 'reinstall-model', 'rebuild-vector-index', 'reinstall-engine'])
|
|
33
|
+
// 需要人点按钮(联网下载 / 重算全部向量 / 动引擎目录 / 改实体图)的修复。
|
|
34
|
+
export const MANUAL_REPAIRS = Object.freeze(['reinstall-runtime', 'reinstall-model', 'rebuild-vector-index', 'reinstall-engine', 'merge-entity-fragments'])
|
|
34
35
|
|
|
35
36
|
export const REPAIR_LABELS = Object.freeze({
|
|
36
37
|
'release-stale-locks': '释放遗留锁文件',
|
|
@@ -40,6 +41,7 @@ export const REPAIR_LABELS = Object.freeze({
|
|
|
40
41
|
'reinstall-model': '重新下载向量模型',
|
|
41
42
|
'rebuild-vector-index': '重建向量索引',
|
|
42
43
|
'reinstall-engine': '重新安装 MemU 引擎',
|
|
44
|
+
'merge-entity-fragments': '合并可证明的实体名字碎片',
|
|
43
45
|
})
|
|
44
46
|
|
|
45
47
|
const MODEL_REQUIRED_FILES = ['config.json', 'tokenizer.json']
|
|
@@ -213,6 +215,52 @@ function checkWorker(items) {
|
|
|
213
215
|
if (status.running) items.push(item('vector-worker', 'ok', '嵌入 worker 在运行'))
|
|
214
216
|
}
|
|
215
217
|
|
|
218
|
+
/**
|
|
219
|
+
* 实体名字碎片(docs/pending-work.md §14.2 P7)。
|
|
220
|
+
*
|
|
221
|
+
* 启动时的一次性修复只处理**可证明**的那一类(窗口重建 + 正文里出现过完整名)。剩下的是
|
|
222
|
+
* "只是相似":编辑距离 ≤2 或名字核重合——`顾清欢` 与 `顾清悦` 就是被编辑距离撞到一起的。
|
|
223
|
+
* 这类绝不自动写:只在这里报数,按钮标"需确认"(MANUAL_REPAIRS),由人核对。
|
|
224
|
+
*/
|
|
225
|
+
function checkEntityFragments(items) {
|
|
226
|
+
let plan = null
|
|
227
|
+
try {
|
|
228
|
+
plan = planAllRepairs({ loadPrivateIndex, listLibraries })
|
|
229
|
+
} catch (error) {
|
|
230
|
+
items.push(item('entity-fragments', 'warn', '实体碎片检查没跑成', {
|
|
231
|
+
detail: String(error?.message || error),
|
|
232
|
+
hint: '检查是只读的;跑不成通常是某个库的实体档案读不出来。可以先跑 scripts/entity-dedupe.mjs 看细节。',
|
|
233
|
+
}))
|
|
234
|
+
return
|
|
235
|
+
}
|
|
236
|
+
const similar = plan.similar
|
|
237
|
+
const attested = plan.attested
|
|
238
|
+
if (plan.failures.length) {
|
|
239
|
+
for (const failure of plan.failures) {
|
|
240
|
+
items.push(item('entity-fragments', 'warn', `某个库的碎片检查失败:${failure.libraryId}`, {
|
|
241
|
+
detail: failure.error, hint: '修好该库的档案后重新检查即可,其它库不受影响。',
|
|
242
|
+
}))
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
if (!similar && !attested) {
|
|
246
|
+
items.push(item('entity-fragments', 'ok', '没有待确认的实体碎片候选'))
|
|
247
|
+
return
|
|
248
|
+
}
|
|
249
|
+
if (!similar) {
|
|
250
|
+
items.push(item('entity-fragments', 'warn', `发现 ${attested} 组可证明的名字碎片,等启动自愈或手动合并`, {
|
|
251
|
+
detail: '这些片段的每一次出现都在更长的名字里面,且那个长名字在正文里出现过。',
|
|
252
|
+
hint: '升级到本版本后的第一次启动会自动合并(先备份);不想等可以点下面的修复。',
|
|
253
|
+
repair: 'merge-entity-fragments', manual: true,
|
|
254
|
+
}))
|
|
255
|
+
return
|
|
256
|
+
}
|
|
257
|
+
items.push(item('entity-fragments', 'warn', `发现 ${similar} 组实体只是名字相似,未自动合并`, {
|
|
258
|
+
detail: attested ? `另有 ${attested} 组可证明的碎片。` : '相似不等于同一人:可能是两个不同的称呼。',
|
|
259
|
+
hint: '请到关系图谱逐个核对候选再合并;批量按钮只处理可证明的那一类,不会按编辑距离替你决定谁是谁。',
|
|
260
|
+
repair: 'merge-entity-fragments', manual: true,
|
|
261
|
+
}))
|
|
262
|
+
}
|
|
263
|
+
|
|
216
264
|
/**
|
|
217
265
|
* 跑一遍自检。
|
|
218
266
|
* @param {{deep?: boolean}} options deep=true 时把引擎 / 运行时状态连"检查命令"一起做。
|
|
@@ -225,6 +273,7 @@ export function runEnvironmentCheck({ deep = false } = {}) {
|
|
|
225
273
|
checkEngine(items)
|
|
226
274
|
const profile = checkVectorProfile(items)
|
|
227
275
|
checkWorker(items)
|
|
276
|
+
checkEntityFragments(items)
|
|
228
277
|
if (deep && profile) {
|
|
229
278
|
try {
|
|
230
279
|
const status = engineStatus({ withSize: true })
|
|
@@ -284,6 +333,26 @@ async function runRepairAction(action) {
|
|
|
284
333
|
const result = await ensureEngine({ force: true, beforeSwitch: backupDatabases })
|
|
285
334
|
return { detail: `引擎 ${result?.status || 'done'}`, data: result }
|
|
286
335
|
}
|
|
336
|
+
case 'merge-entity-fragments': {
|
|
337
|
+
// 只合"可证明"的那一类;相似候选留给关系图谱里逐个确认。备份在任何写之前。
|
|
338
|
+
const plan = planAllRepairs({ loadPrivateIndex, listLibraries })
|
|
339
|
+
if (!plan.attested) return { detail: `没有可证明的碎片可合并(相似候选 ${plan.similar} 组需要人工核对)`, data: plan }
|
|
340
|
+
await backupDatabases({ label: 'entity-repair' })
|
|
341
|
+
let merged = 0
|
|
342
|
+
let created = 0
|
|
343
|
+
const failures = []
|
|
344
|
+
for (const entry of plan.plans) {
|
|
345
|
+
if (!entry.groups.length) continue
|
|
346
|
+
const applied = applyRepairGroups(entry.libraryId, entry.groups)
|
|
347
|
+
merged += applied.merged
|
|
348
|
+
created += applied.created
|
|
349
|
+
for (const failure of applied.failures) failures.push(`${entry.libraryId}/${failure.group}: ${failure.error}`)
|
|
350
|
+
}
|
|
351
|
+
return {
|
|
352
|
+
detail: `合并 ${merged} 组(新建完整名 ${created} 个),相似候选 ${plan.similar} 组未动${failures.length ? ',失败 ' + failures.length + ' 组' : ''}`,
|
|
353
|
+
data: { merged, created, similar: plan.similar, failures },
|
|
354
|
+
}
|
|
355
|
+
}
|
|
287
356
|
default:
|
|
288
357
|
throw new Error('unknown repair action: ' + action)
|
|
289
358
|
}
|
package/lib/global-graph.js
CHANGED
|
@@ -29,6 +29,7 @@ import { loadGlobalIndex, updateGlobalIndex } from './state.js'
|
|
|
29
29
|
import { redactSecrets } from './paths.js'
|
|
30
30
|
import { groundEvidence, groundLinkNote } from './curator-evidence.js'
|
|
31
31
|
import { globalConflictCheck } from './text-retrieval.js'
|
|
32
|
+
import { graphDomain } from './graph.js'
|
|
32
33
|
import {
|
|
33
34
|
GLOBAL_LINK_KINDS,
|
|
34
35
|
LINK_CONFIDENCE_MIN,
|
|
@@ -255,13 +256,20 @@ const GRAPH_HIDDEN_STATUS = new Set(['suppressed', 'expired'])
|
|
|
255
256
|
* node so the edge does not silently disappear, while an existing hidden target
|
|
256
257
|
* gets no hint at all (same rule as the private graph).
|
|
257
258
|
*/
|
|
258
|
-
export function getGlobalGraph({ focusId = null, depth = 1, limit = 200 } = {}) {
|
|
259
|
+
export function getGlobalGraph({ focusId = null, depth = 1, limit = 200, domain } = {}) {
|
|
259
260
|
const index = loadGlobalIndex()
|
|
260
261
|
const entries = index.entries || {}
|
|
261
262
|
const cap = Math.max(1, Math.min(200, Math.floor(Number(limit) || 200)))
|
|
262
263
|
const hops = Math.max(0, Math.min(2, Math.floor(Number(depth) || 0)))
|
|
264
|
+
const domainFilter = graphDomain(domain)
|
|
265
|
+
const domains = new Set()
|
|
263
266
|
const visible = new Set(Object.entries(entries)
|
|
264
267
|
.filter(([, entry]) => entry && !GRAPH_HIDDEN_STATUS.has(entry.status || 'active'))
|
|
268
|
+
.filter(([, entry]) => {
|
|
269
|
+
const normalized = graphDomain(entry?.domain) || 'unknown'
|
|
270
|
+
domains.add(normalized)
|
|
271
|
+
return !domainFilter || normalized === domainFilter
|
|
272
|
+
})
|
|
265
273
|
.map(([id]) => id))
|
|
266
274
|
const edges = []
|
|
267
275
|
const adjacency = new Map()
|
|
@@ -324,7 +332,7 @@ export function getGlobalGraph({ focusId = null, depth = 1, limit = 200 } = {})
|
|
|
324
332
|
// 'global' is distinct from private 'memory' so the canvas can colour it;
|
|
325
333
|
// domain/status are display metadata for the tooltip and audit.
|
|
326
334
|
kind: 'global',
|
|
327
|
-
domain: entry
|
|
335
|
+
domain: entry ? graphDomain(entry.domain) || 'unknown' : null,
|
|
328
336
|
status: entry?.status || 'active',
|
|
329
337
|
strength: Number.isFinite(strength) ? Math.max(0, Math.min(1, strength)) : 0.5,
|
|
330
338
|
degree: adjacency.get(id)?.size || 0,
|
|
@@ -337,6 +345,7 @@ export function getGlobalGraph({ focusId = null, depth = 1, limit = 200 } = {})
|
|
|
337
345
|
limit: cap,
|
|
338
346
|
truncated: selected.size >= cap,
|
|
339
347
|
focusId: focusId || null,
|
|
348
|
+
domains: [...domains].sort(),
|
|
340
349
|
scope: 'global',
|
|
341
350
|
}
|
|
342
351
|
}
|
package/lib/graph.js
CHANGED
|
@@ -720,19 +720,41 @@ function withinEditDistance(a, b, max) {
|
|
|
720
720
|
return previous[b.length] <= max
|
|
721
721
|
}
|
|
722
722
|
|
|
723
|
+
/** Pure-read helper: does this CJK pair look like one name written two ways? */
|
|
724
|
+
// 同一个人常被写成全称、昵称和单字称呼(顾清欢 / 欢欢 / 晴),三种表面互不包含、
|
|
725
|
+
// 编辑距离又太远,于是各自成节点。只在「一端收尾、另一端起头」的共享字串上提议合并,
|
|
726
|
+
// 并要求较长一侧去掉重叠后还剩两个字——空气/气候这种共用一个字的词对不提议。
|
|
727
|
+
// 永远是候选,由用户点两次确认,绝不自动合并。
|
|
728
|
+
function isNameCorePair(shorter, longer) {
|
|
729
|
+
const cjkOnly = value => /^[\u3400-\u9fff\uf900-\ufaff]+$/u.test(value)
|
|
730
|
+
if (!cjkOnly(shorter) || !cjkOnly(longer)) return false
|
|
731
|
+
if (longer.length > 5) return false
|
|
732
|
+
if (shorter.length === 1) return longer.includes(shorter)
|
|
733
|
+
const overlap = (first, second) => {
|
|
734
|
+
for (let size = Math.min(first.length, second.length); size >= 1; size -= 1) {
|
|
735
|
+
if (first.slice(-size) === second.slice(0, size)) return size
|
|
736
|
+
}
|
|
737
|
+
return 0
|
|
738
|
+
}
|
|
739
|
+
const shared = Math.max(overlap(shorter, longer), overlap(longer, shorter))
|
|
740
|
+
return shared >= 1 && longer.length - shared >= 2
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
const MERGE_REASON_ORDER = { containment: 0, 'edit-distance': 1, 'name-core': 2 }
|
|
744
|
+
|
|
723
745
|
/**
|
|
724
746
|
* Pure read: candidate entity merges inside one library. Never writes and never
|
|
725
747
|
* merges — the caller shows the pair and the user confirms.
|
|
726
|
-
*
|
|
727
748
|
* Names are folded with normalizeEntityName (NFKC / case / whitespace /
|
|
728
749
|
* punctuation), identical folded names are skipped (that duplicate is handled by
|
|
729
750
|
* createEntity or an explicit merge), and only same-kind pairs qualify. A pair
|
|
730
751
|
* is a candidate when the shorter normalized name is contained in the longer one
|
|
731
|
-
* and has >= 2 characters,
|
|
732
|
-
*
|
|
733
|
-
*
|
|
734
|
-
*
|
|
735
|
-
*
|
|
752
|
+
* and has >= 2 characters, when both names have >= 3 characters and sit at most
|
|
753
|
+
* 2 edits apart, or (CJK only) when they look like the same name written in full
|
|
754
|
+
* and in short — see isNameCorePair. The longer name is the target (the hub the
|
|
755
|
+
* shorter one folds into); on equal length the older id wins, which keeps the
|
|
756
|
+
* direction stable across calls. Results are sorted by reason then names then ids,
|
|
757
|
+
* and capped at 20.
|
|
736
758
|
*/
|
|
737
759
|
export function suggestEntityMerges({ libraryId } = {}) {
|
|
738
760
|
const scope = scopeFor({ libraryId })
|
|
@@ -755,11 +777,12 @@ export function suggestEntityMerges({ libraryId } = {}) {
|
|
|
755
777
|
else if (shorter.key.length >= 3
|
|
756
778
|
&& longer.key.length - shorter.key.length <= 2
|
|
757
779
|
&& withinEditDistance(shorter.key, longer.key, 2)) reason = 'edit-distance'
|
|
780
|
+
else if (isNameCorePair(shorter.key, longer.key)) reason = 'name-core'
|
|
758
781
|
if (!reason) continue
|
|
759
782
|
found.push({ sourceId: shorter.id, targetId: longer.id, reason, sourceKey: shorter.key, targetKey: longer.key })
|
|
760
783
|
}
|
|
761
784
|
}
|
|
762
|
-
found.sort((x, y) => (x.reason
|
|
785
|
+
found.sort((x, y) => (MERGE_REASON_ORDER[x.reason] - MERGE_REASON_ORDER[y.reason])
|
|
763
786
|
|| compareText(x.targetKey, y.targetKey)
|
|
764
787
|
|| compareText(x.sourceKey, y.sourceKey)
|
|
765
788
|
|| compareText(x.targetId, y.targetId)
|
|
@@ -927,7 +950,8 @@ export function unlinkEntry({ libraryId, fromId, toId, kind }) {
|
|
|
927
950
|
}
|
|
928
951
|
|
|
929
952
|
// Graph filtering is read-only: normalize legacy stamps without rewriting them.
|
|
930
|
-
|
|
953
|
+
// Shared with the global graph so both sides agree on what "same domain" means.
|
|
954
|
+
export function graphDomain(value) { return String(value ?? '').normalize('NFKC').trim().toLowerCase() }
|
|
931
955
|
|
|
932
956
|
export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 200, includeOrphans = false, offset, domain }) {
|
|
933
957
|
const scope = scopeFor({ exec, libraryId })
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// §13.6 运行时结构指纹。
|
|
2
|
+
//
|
|
3
|
+
// `docs/host-versions.md` §13.1 的台账每行都带一个结构指纹;这一模块就是那个指纹的
|
|
4
|
+
// 运行时对应物——在真机上读一眼 `getState().hostSurface`,就能核对台账那一行是真是假。
|
|
5
|
+
//
|
|
6
|
+
// 纪律:这里**不做任何判断,也不读宿主版本号**(AGENTS.md §1 规则 1)。每个值都由既有
|
|
7
|
+
// 探测函数在真正用到它的时候顺手记一次,缺项显示 `unknown`。宿主差异一律走结构探测,
|
|
8
|
+
// 本模块只是把已经发生过的探测结果聚合成一行可核对的文本。
|
|
9
|
+
const SURFACES = ['rpcGuard', 'schedule', 'activation', 'coldLog']
|
|
10
|
+
|
|
11
|
+
const resolved = Object.fromEntries(SURFACES.map((name) => [name, 'unknown']))
|
|
12
|
+
|
|
13
|
+
/** Record what a probe actually saw. Unknown surface names are ignored on purpose:
|
|
14
|
+
* a stale call site must not be able to invent a new ledger key. */
|
|
15
|
+
export function noteHostSurface(surface, value) {
|
|
16
|
+
if (!SURFACES.includes(surface)) return
|
|
17
|
+
const text = String(value ?? '').trim()
|
|
18
|
+
if (text) resolved[surface] = text
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function hostSurface() {
|
|
22
|
+
return { ...resolved }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** One-line form, matching the 指纹 column of the ledger. */
|
|
26
|
+
export function hostSurfaceLine() {
|
|
27
|
+
return SURFACES.map((name) => `${name}=${resolved[name]}`).join(' ')
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export { SURFACES as HOST_SURFACES }
|
package/lib/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import { registerRpc } from './rpc.js'
|
|
|
5
5
|
import { registerCycle } from './cycle.js'
|
|
6
6
|
import { syncPromptDefaults } from './prompts.js'
|
|
7
7
|
import { ensureEngine, engineStatus, ENGINE_VERSION } from './engine.js'
|
|
8
|
-
import { getSettings, getMemoryBackend, backupDatabases, flushState, listLibraries, getSessionBinding } from './state.js'
|
|
8
|
+
import { getSettings, getMemoryBackend, backupDatabases, flushState, listLibraries, getSessionBinding, getCycleState, setCycleState, loadPrivateIndex } from './state.js'
|
|
9
9
|
import { buildTurnRecords, recordTurn, deleteTurnLog } from './turn-log.js'
|
|
10
10
|
import { pruneOrphanEntitiesAll } from './graph.js'
|
|
11
11
|
import { pruneDeletedStores } from './memory.js'
|
|
@@ -16,6 +16,7 @@ import { vectorStatus } from './vector-profile.js'
|
|
|
16
16
|
import { setWarnSink, warn } from './paths.js'
|
|
17
17
|
import { recordDiagnostic, recordErrorDiagnostic } from './diagnostics.js'
|
|
18
18
|
import { autoRepairEnvironment, runEnvironmentCheck } from './environment-check.js'
|
|
19
|
+
import { planAllRepairs, applyRepairGroups } from './entity-repair.js'
|
|
19
20
|
|
|
20
21
|
export const name = 'dsh-memu-memory'
|
|
21
22
|
// `timer` backs ctx.interval, used by the idle/auto-curation sweep. Reading an
|
|
@@ -139,6 +140,119 @@ function startOrphanEntitySweep(ctx) {
|
|
|
139
140
|
}
|
|
140
141
|
}
|
|
141
142
|
|
|
143
|
+
// 一次性实体碎片修复(docs/pending-work.md §14.2 P7):老版本把 n-gram 滑窗的窗口片段当成
|
|
144
|
+
// 人名建了节点(`南宫晚` / `宫晚晴` 其实是 `南宫晚晴`)。提名侧已修,但已落盘的碎片不会自己合,
|
|
145
|
+
// 也不会因为升级就变干净——所以新版本启动后自动跑一次。
|
|
146
|
+
//
|
|
147
|
+
// 界线(本函数唯一需要守住的):
|
|
148
|
+
// · attested(可证明)——窗口首尾重叠重建出的完整名**在正文里出现过**,或短名在全库正文里
|
|
149
|
+
// 从未独立于某个更长名字出现 → 自动合并。
|
|
150
|
+
// · similar(只是相似)——编辑距离 ≤2 或名字核重合(`顾清欢` 与 `顾清悦` 就是这么撞上的)→
|
|
151
|
+
// **一律不动**,只在诊断页报数并给一个「需确认」的修复按钮(environment-check 的 MANUAL 面)。
|
|
152
|
+
//
|
|
153
|
+
// 只跑一次:标记写进 `state.cycle.entityRepairVersion`(与 lastCurateAt 同族,不新造机制)。
|
|
154
|
+
// 幂等:合过的库第二次规划不出 attested 组;no-op 时一个字节都不写。
|
|
155
|
+
// 写入前先备份(合并级联不改记忆正文,但撤销要靠这份快照)。任何失败只 warn/记诊断,
|
|
156
|
+
// 加载绝不能被它绊住(硬规则 10:降级必须留可见信号)。
|
|
157
|
+
const ENTITY_REPAIR_VERSION = 1
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* 升级自愈的执行体。单独导出是为了让测试能不开定时器、不装假 ctx 就直接跑同一段代码
|
|
161
|
+
* (startEntityRepairPass 只负责"延迟 5 秒 + 只跑一次"这两件事)。
|
|
162
|
+
*/
|
|
163
|
+
export async function runEntityRepairPass({ note = () => {}, warn = () => {}, diagnose = () => {} } = {}) {
|
|
164
|
+
let settings = null
|
|
165
|
+
try { settings = getSettings() } catch {}
|
|
166
|
+
let cycle = null
|
|
167
|
+
try { cycle = getCycleState() } catch {}
|
|
168
|
+
if (Number(cycle?.entityRepairVersion || 0) >= ENTITY_REPAIR_VERSION) return { skipped: 'done' }
|
|
169
|
+
if (settings?.autoRepairEntityFragments === false) {
|
|
170
|
+
note('entity repair skipped (autoRepairEntityFragments=off)')
|
|
171
|
+
return { skipped: 'setting' }
|
|
172
|
+
}
|
|
173
|
+
const plan = planAllRepairs({ listLibraries, loadPrivateIndex })
|
|
174
|
+
if (!plan.attested && !plan.similar && !plan.failures.length) {
|
|
175
|
+
setCycleState({ entityRepairVersion: ENTITY_REPAIR_VERSION, entityRepairAt: new Date().toISOString() })
|
|
176
|
+
return { skipped: 'clean', plan }
|
|
177
|
+
}
|
|
178
|
+
const results = []
|
|
179
|
+
let deferred = false
|
|
180
|
+
if (plan.attested > 0) {
|
|
181
|
+
// 备份失败就一个字节都不写:合并级联会改实体指向,没有可撤销的快照就不许动手。
|
|
182
|
+
// 标记此时保持未写,下次启动再试一次。
|
|
183
|
+
let backedUp = true
|
|
184
|
+
try {
|
|
185
|
+
await backupDatabases({ label: 'entity-repair' })
|
|
186
|
+
} catch (error) {
|
|
187
|
+
backedUp = false
|
|
188
|
+
deferred = true
|
|
189
|
+
warn(`entity repair deferred: no backup available (${error?.code || error?.message || error})`)
|
|
190
|
+
diagnose({
|
|
191
|
+
level: 'warn', scope: 'graph', code: 'ENTITY_REPAIR_DEFERRED', alert: false,
|
|
192
|
+
message: '实体碎片修复顺延:图备份没成功',
|
|
193
|
+
hint: '备份可用后(下一次启动,或诊断页手动触发)再合并;本次没有写入任何改动。',
|
|
194
|
+
detail: { attested: plan.attested, similar: plan.similar },
|
|
195
|
+
source: 'entity-repair',
|
|
196
|
+
})
|
|
197
|
+
}
|
|
198
|
+
if (backedUp) {
|
|
199
|
+
for (const entry of plan.plans) {
|
|
200
|
+
if (!entry.groups.length) continue
|
|
201
|
+
results.push(applyRepairGroups(entry.libraryId, entry.groups))
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const merged = results.reduce((total, row) => total + row.merged, 0)
|
|
206
|
+
const created = results.reduce((total, row) => total + row.created, 0)
|
|
207
|
+
const protectedRows = results.reduce((total, row) => total + row.restored, 0)
|
|
208
|
+
const failures = [...plan.failures, ...results.flatMap((row) => row.failures || [])]
|
|
209
|
+
if (!deferred) {
|
|
210
|
+
setCycleState({
|
|
211
|
+
entityRepairVersion: ENTITY_REPAIR_VERSION,
|
|
212
|
+
entityRepairAt: new Date().toISOString(),
|
|
213
|
+
entityRepairMerged: merged,
|
|
214
|
+
entityRepairPending: plan.similar,
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
if (merged || created) {
|
|
218
|
+
note(`entity repair merged ${merged} group(s), created ${created} reconstructed node(s)`)
|
|
219
|
+
diagnose({
|
|
220
|
+
level: 'warn', scope: 'graph', code: 'ENTITY_FRAGMENT_REPAIRED', alert: true,
|
|
221
|
+
message: `升级后自动合并了 ${merged} 组名字碎片(其中 ${created} 组新建了正文里出现过的完整名)`,
|
|
222
|
+
hint: '原图已先行备份;记忆正文与条目本身没有被修改,只改了实体指向。',
|
|
223
|
+
detail: { merged, created, protectedRows, libraries: results.map((row) => row.libraryId) },
|
|
224
|
+
source: 'entity-repair',
|
|
225
|
+
})
|
|
226
|
+
}
|
|
227
|
+
if (plan.similar > 0) {
|
|
228
|
+
diagnose({
|
|
229
|
+
level: 'warn', scope: 'graph', code: 'ENTITY_FRAGMENT_SUSPECTED', alert: true, manual: true,
|
|
230
|
+
repair: 'merge-entity-fragments',
|
|
231
|
+
message: `另有 ${plan.similar} 组实体只是名字相似,未自动合并`,
|
|
232
|
+
hint: '相似不等于同一人:请到「设置 · 诊断」核对候选,确认后手动触发合并。',
|
|
233
|
+
detail: { similar: plan.similar, libraries: plan.plans.filter((entry) => entry.ambiguous.length).length },
|
|
234
|
+
source: 'entity-repair',
|
|
235
|
+
})
|
|
236
|
+
}
|
|
237
|
+
for (const failure of failures) warn(`entity repair skipped ${failure.libraryId || ''} ${failure.group || ''}: ${failure.error}`)
|
|
238
|
+
return { merged, created, protectedRows, similar: plan.similar, failures, deferred }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function startEntityRepairPass(ctx) {
|
|
242
|
+
try {
|
|
243
|
+
return scheduleStartup(ctx, 5000, 'entity repair pass', () => {
|
|
244
|
+
void runEntityRepairPass({
|
|
245
|
+
note: (message) => { try { ctx.logger?.info?.(`dsh-memu-memory: ${message}`) } catch {} },
|
|
246
|
+
warn: (message) => { try { ctx.logger?.warn?.(`dsh-memu-memory: ${message}`) } catch {} },
|
|
247
|
+
diagnose: recordDiagnostic,
|
|
248
|
+
}).catch((error) => { recordErrorDiagnostic(error, { source: 'entity-repair' }) })
|
|
249
|
+
})
|
|
250
|
+
} catch (error) {
|
|
251
|
+
try { ctx.logger?.warn?.(`dsh-memu-memory: entity repair pass skipped: ${error?.message || error}`) } catch {}
|
|
252
|
+
return null
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
142
256
|
// T0 构件 1(设计文档 §3.2):增量回合日志的订阅接线。纯旁路记录器——任何失败只
|
|
143
257
|
// warn,绝不改变或阻断现有整理行为;正确性永远由宿主转录 + 缺口重建兜底。
|
|
144
258
|
//
|
|
@@ -337,6 +451,7 @@ export function apply(ctx, config) {
|
|
|
337
451
|
startEngineBootstrap(ctx),
|
|
338
452
|
startLocalVectorBootstrap(ctx),
|
|
339
453
|
startOrphanEntitySweep(ctx),
|
|
454
|
+
startEntityRepairPass(ctx),
|
|
340
455
|
startEnvironmentHealthCheck(ctx),
|
|
341
456
|
].filter(Boolean)
|
|
342
457
|
if (typeof ctx.effect === 'function') {
|