dsh-memu-memory 1.3.15 → 1.4.1

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 (73) hide show
  1. package/AGENTS.md +5 -2
  2. package/CHANGELOG.md +49 -1
  3. package/README.md +4 -1
  4. package/README.zh.md +4 -1
  5. package/docs/client-conventions.md +1 -0
  6. package/docs/host-adaptation.md +52 -36
  7. package/docs/host-versions.md +120 -0
  8. package/docs/memory-semantics.md +4 -2
  9. package/docs/pending-work.md +51 -0
  10. package/docs/troubleshooting.md +41 -2
  11. package/lib/auto-link/candidates.js +4 -1
  12. package/lib/auto-link/decide.js +1 -1
  13. package/lib/auto-link/normalize.js +2 -2
  14. package/lib/auto-link/terminology.js +31 -1
  15. package/lib/binding-diagnostics.js +2 -2
  16. package/lib/client.js +53 -6
  17. package/lib/consolidation-snapshot.js +7 -1
  18. package/lib/consolidation-worker.js +11 -3
  19. package/lib/curator.js +17 -5
  20. package/lib/cycle.js +75 -4
  21. package/lib/diagnostics.js +10 -0
  22. package/lib/entity-repair.js +285 -0
  23. package/lib/environment-check.js +72 -3
  24. package/lib/global-graph.js +11 -2
  25. package/lib/graph.js +32 -8
  26. package/lib/host-surface.js +30 -0
  27. package/lib/index.js +120 -3
  28. package/lib/inject.js +142 -8
  29. package/lib/memory.js +72 -0
  30. package/lib/private-links.js +12 -0
  31. package/lib/private.js +49 -13
  32. package/lib/prompts/private-consolidation.coding.md +3 -1
  33. package/lib/prompts/private-consolidation.md +2 -0
  34. package/lib/prompts/private-consolidation.mixed.md +2 -0
  35. package/lib/prompts/private-consolidation.rp.md +2 -0
  36. package/lib/prompts/system-guide.coding.md +8 -2
  37. package/lib/prompts/system-guide.md +6 -0
  38. package/lib/prompts/system-guide.mixed.md +11 -0
  39. package/lib/prompts/system-guide.rp.md +6 -0
  40. package/lib/rpc.js +48 -10
  41. package/lib/state.js +5 -1
  42. package/lib/turn-log.js +34 -11
  43. package/lib/worker-pool.js +11 -7
  44. package/package.json +16 -1
  45. package/scripts/chain-matrix.mjs +4 -0
  46. package/scripts/check-doc-drift.mjs +194 -0
  47. package/scripts/entity-dedupe.mjs +110 -0
  48. package/tests/auto-link-candidates.test.mjs +22 -9
  49. package/tests/auto-link-decide.test.mjs +59 -59
  50. package/tests/auto-link-migration.test.mjs +4 -4
  51. package/tests/client-render.test.mjs +112 -1
  52. package/tests/consolidation-fork.test.mjs +20 -1
  53. package/tests/curator-probe.test.mjs +19 -1
  54. package/tests/cycle.test.mjs +2 -2
  55. package/tests/diagnostics.test.mjs +21 -0
  56. package/tests/doc-drift.test.mjs +122 -2
  57. package/tests/entity-merge.test.mjs +17 -0
  58. package/tests/environment-check.test.mjs +28 -0
  59. package/tests/global-graph.test.mjs +16 -0
  60. package/tests/global-lifecycle.test.mjs +24 -4
  61. package/tests/graph-cascade.test.mjs +111 -0
  62. package/tests/hybrid-recall.test.mjs +1 -1
  63. package/tests/inject-guide.test.mjs +108 -1
  64. package/tests/managed-memory.test.mjs +7 -7
  65. package/tests/private-links.test.mjs +12 -0
  66. package/tests/prompts.test.mjs +30 -0
  67. package/tests/recall-corpus-eligibility.test.mjs +3 -3
  68. package/tests/salience-domain.test.mjs +34 -0
  69. package/tests/settings-plumbing.test.mjs +2 -0
  70. package/tests/stale-maintenance.test.mjs +131 -0
  71. package/tests/tools.test.mjs +1 -1
  72. package/tests/turn-log.test.mjs +13 -0
  73. package/tests/webui-auth.test.mjs +58 -0
@@ -162,6 +162,16 @@ export function recordDiagnostic(input) {
162
162
  * "这是哪一层坏了、能不能自动修、修之前会不会丢数据"。
163
163
  */
164
164
  const KNOWN_CODES = Object.freeze({
165
+ ENTITY_FRAGMENT_SUSPECTED: {
166
+ scope: 'graph',
167
+ repair: 'merge-entity-fragments',
168
+ manual: true,
169
+ hint: 'Entity names that are merely similar (edit distance / shared name core) are never merged automatically: two nicknames can name two different beings. The repair button only folds provable n-gram windows; review the rest in the graph panel.',
170
+ },
171
+ ENTITY_FRAGMENT_REPAIRED: {
172
+ scope: 'graph',
173
+ hint: 'Provable n-gram fragments were folded into one entity after an upgrade (a graph backup was taken first). Memory bodies and entries were not touched - only entity rows and their links.',
174
+ },
165
175
  VECTOR_PROFILE_MANIFEST_CHANGED: {
166
176
  scope: 'vector',
167
177
  repair: 'resign-vector-profile',
@@ -0,0 +1,285 @@
1
+ // 实体碎片修复:规划 + 执行(docs/pending-work.md §14.2 P7、docs/host-versions.md §13 之外的数据侧)
2
+ //
3
+ // 为什么需要它:n-gram 滑窗曾把「一个名字的窗口片段」当成人物名建了节点(`南宫晚` /
4
+ // `宫晚晴` 其实是 `南宫晚晴`)。提名侧已修(lib/auto-link/terminology.js、
5
+ // lib/private-links.js),但**已落盘的碎片不会自己合**,而用户不会为了这件事去开终端跑脚本。
6
+ //
7
+ // 两类结论,处理方式完全不同(这是本模块唯一需要守住的界线):
8
+ // · attested —— 可证明:窗口片段首尾重叠重建出的更长名字**在正文里真的出现过**,或短名在
9
+ // 全库正文里**从未**独立于某个更长名字出现过。这类可以自动合并。
10
+ // · similar —— 只是相似:编辑距离 ≤2 或名字核重合(`顾清欢` 与 `顾清悦` 就是这么撞上的)。
11
+ // 这类**绝不自动写**,只在诊断页报数,由人点「需确认」的修复按钮。
12
+ //
13
+ // 写入只走 lib/graph.js 的 mergeEntities(别名并集、links 改指、evidence 改指、继承 confirmed、
14
+ // 清孤儿都在那条级联里),本模块不自建第二条写路径。合并前的全库备份由调用方负责。
15
+
16
+ import fs from 'node:fs'
17
+ import path from 'node:path'
18
+ import { indexDir, readJsonStrict, withFileLock, writeJson } from './paths.js'
19
+ import * as defaultGraph from './graph.js'
20
+ import { listLibraries as defaultListLibraries, loadPrivateIndex as defaultLoadPrivateIndex } from './state.js'
21
+
22
+ // mergeEntities 末尾的 pruneOrphanEntities 是全库清扫:它会把**任何**没被引用的实体删掉,
23
+ // 包括本次修复根本没碰的节点。修复不能顺手删东西,所以写入前后各读一次快照,把计划外的
24
+ // 行原样写回(硬规则 5)。
25
+ const ENTITIES_FILE = (libraryId) => path.join(indexDir(), `${libraryId}.entities.json`)
26
+ // 正文扫描上限:单库超过这个条目数时只取最近的这些,并在结论里标 `partial`。
27
+ const CORPUS_ENTRY_CAP = 3000
28
+
29
+ const normalized = (value) => String(value ?? '').normalize('NFKC').toLowerCase().trim()
30
+
31
+ function readEntityStore(file) {
32
+ const result = readJsonStrict(file)
33
+ if (result.missing) return { entities: {} }
34
+ if (!result.ok) throw new Error('实体档案读不出来:' + (result.error?.code || result.kind || 'read failed'))
35
+ const value = result.value && typeof result.value === 'object' ? result.value : {}
36
+ if (!value.entities || typeof value.entities !== 'object' || Array.isArray(value.entities)) value.entities = {}
37
+ return value
38
+ }
39
+
40
+ /** Overlap-merge two surfaces: `南宫晚` + `宫晚晴` → `南宫晚晴` (suffix equals prefix). */
41
+ function overlapJoin(left, right) {
42
+ for (let size = Math.min(left.length, right.length); size >= 1; size -= 1) {
43
+ if (left.slice(-size) === right.slice(0, size)) return left + right.slice(size)
44
+ }
45
+ return null
46
+ }
47
+
48
+ /** 全库正文(标题 + 正文,NFKC + 小写)。返回 {texts, partial}。 */
49
+ function corpusTexts(loadPrivateIndex, libraryId) {
50
+ const entries = Object.values(loadPrivateIndex(libraryId).entries || {})
51
+ .filter((entry) => entry && typeof entry === 'object')
52
+ const sorted = entries.length > CORPUS_ENTRY_CAP
53
+ ? [...entries].sort((a, b) => String(b.updatedAt || b.createdAt || '').localeCompare(String(a.updatedAt || a.createdAt || ''))).slice(0, CORPUS_ENTRY_CAP)
54
+ : entries
55
+ return {
56
+ texts: sorted.map((entry) => `${entry.title || ''}\n${entry.content || ''}`.normalize('NFKC').toLowerCase()),
57
+ partial: entries.length > CORPUS_ENTRY_CAP,
58
+ }
59
+ }
60
+
61
+ /**
62
+ * 短名是否只是长名的窗口:短名在正文里的**每一次**出现都被某个长名覆盖。
63
+ * 只要有一次独立出现(`化学` 单独出现在讲化学的句子里),就不能断定它是碎片。
64
+ */
65
+ function onlyInsideCorpus(term, superstrings, texts) {
66
+ const supersets = superstrings.filter((other) => other.length > term.length && other.includes(term))
67
+ if (!supersets.length) return false
68
+ let seen = 0
69
+ for (const text of texts) {
70
+ for (let at = text.indexOf(term); at !== -1; at = text.indexOf(term, at + term.length)) {
71
+ seen += 1
72
+ const covered = supersets.some((other) => {
73
+ for (let start = Math.max(0, at - other.length + 1); start <= at; start += 1) {
74
+ if (text.slice(start, start + other.length) === other) return true
75
+ }
76
+ return false
77
+ })
78
+ if (!covered) return false
79
+ }
80
+ }
81
+ return seen > 0
82
+ }
83
+
84
+ function unionFind(ids) {
85
+ const parent = new Map(ids.map((id) => [id, id]))
86
+ const find = (id) => {
87
+ let current = id
88
+ while (parent.get(current) !== current) current = parent.get(current)
89
+ let walk = id
90
+ while (parent.get(walk) !== walk) { const next = parent.get(walk); parent.set(walk, current); walk = next }
91
+ return current
92
+ }
93
+ const union = (a, b) => {
94
+ const left = find(a)
95
+ const right = find(b)
96
+ if (left !== right) parent.set(left, right)
97
+ }
98
+ return { find, union }
99
+ }
100
+
101
+ /**
102
+ * 规划一个库的修复。纯读:不开文件锁、不写任何字节。
103
+ *
104
+ * @param {string} libraryId
105
+ * @param {{graph: object, loadPrivateIndex: Function}} deps 注入便于测试与脚本复用
106
+ */
107
+ export function planLibraryRepair(libraryId, { graph = defaultGraph, loadPrivateIndex = defaultLoadPrivateIndex } = {}) {
108
+ const listed = graph.listEntities({ libraryId }).items
109
+ .filter((entity) => entity && entity.id && String(entity.status || 'provisional') !== 'archived')
110
+ if (listed.length < 2) return { libraryId, groups: [], ambiguous: [], scanned: listed.length, partial: false }
111
+ const { texts, partial } = corpusTexts(loadPrivateIndex, libraryId)
112
+ const index = new Map(listed.map((entity) => [entity.id, entity]))
113
+ const { find, union } = unionFind(listed.map((entity) => entity.id))
114
+ const evidenceOf = new Map()
115
+
116
+ for (const shorter of listed) {
117
+ const key = normalized(shorter.name)
118
+ if (key.length < 2) continue
119
+ const longer = listed.find((entity) => entity !== shorter && entity.kind === shorter.kind
120
+ && normalized(entity.name).length > key.length && normalized(entity.name).includes(key))
121
+ if (!longer) continue
122
+ union(shorter.id, longer.id)
123
+ evidenceOf.set(shorter.id + '>' + longer.id, onlyInsideCorpus(key, [normalized(longer.name)], texts) ? 'attested' : 'similar')
124
+ }
125
+ for (const item of graph.suggestEntityMerges({ libraryId }).items) {
126
+ if (!index.has(item.sourceId) || !index.has(item.targetId)) continue
127
+ union(item.sourceId, item.targetId)
128
+ if (!evidenceOf.has(item.sourceId + '>' + item.targetId)) evidenceOf.set(item.sourceId + '>' + item.targetId, 'similar')
129
+ }
130
+
131
+ const components = new Map()
132
+ for (const entity of listed) {
133
+ const root = find(entity.id)
134
+ if (!components.has(root)) components.set(root, [])
135
+ components.get(root).push(entity)
136
+ }
137
+
138
+ const groups = []
139
+ const ambiguous = []
140
+ for (const members of components.values()) {
141
+ if (members.length < 2) continue
142
+ const ordered = [...members].sort((a, b) => normalized(b.name).length - normalized(a.name).length
143
+ || String(a.id).localeCompare(String(b.id)))
144
+ const names = ordered.map((entity) => String(entity.name || ''))
145
+ // 已经有完整名节点:直接把碎片并进去(前提是每个碎片都只是它的窗口)。
146
+ const container = ordered.find((entity) => names.every((other) => other === entity.name
147
+ || normalized(entity.name).includes(normalized(other))))
148
+ if (container) {
149
+ const allAttested = ordered
150
+ .filter((entity) => entity.id !== container.id)
151
+ .every((entity) => evidenceOf.get(entity.id + '>' + container.id) === 'attested'
152
+ || onlyInsideCorpus(normalized(entity.name), [normalized(container.name)], texts))
153
+ const group = {
154
+ target: { id: container.id, name: container.name, kind: container.kind },
155
+ sources: ordered.filter((entity) => entity.id !== container.id),
156
+ creates: false,
157
+ evidence: allAttested ? 'attested' : 'similar',
158
+ }
159
+ ;(group.evidence === 'attested' ? groups : ambiguous).push(group)
160
+ continue
161
+ }
162
+ // 没有完整名节点:首尾重叠重建一个,并在正文里验到才算 attested。
163
+ let rebuilt = null
164
+ if (ordered[0].kind === 'person') {
165
+ let best = null
166
+ const extend = (used, current) => {
167
+ if (current.length > 16) return
168
+ if (used.size === names.length) {
169
+ if (!best || current.length > best.length) best = current
170
+ return
171
+ }
172
+ for (const name of names) {
173
+ if (used.has(name)) continue
174
+ const joined = overlapJoin(current, name)
175
+ if (joined) { used.add(name); extend(used, joined); used.delete(name) }
176
+ }
177
+ }
178
+ for (const name of names) extend(new Set([name]), name)
179
+ if (best && best.length > Math.max(...names.map((name) => name.length))) {
180
+ const needle = normalized(best)
181
+ if (texts.some((text) => text.includes(needle))) rebuilt = best
182
+ }
183
+ }
184
+ if (rebuilt) {
185
+ groups.push({
186
+ target: { id: null, name: rebuilt, kind: ordered[0].kind },
187
+ sources: ordered,
188
+ creates: true,
189
+ evidence: 'attested',
190
+ })
191
+ continue
192
+ }
193
+ ambiguous.push({
194
+ target: { id: ordered[0].id, name: ordered[0].name, kind: ordered[0].kind },
195
+ sources: ordered.slice(1),
196
+ creates: false,
197
+ evidence: 'similar',
198
+ })
199
+ }
200
+ return { libraryId, groups, ambiguous, scanned: listed.length, partial }
201
+ }
202
+
203
+ /** 所有未归档库的规划汇总。 */
204
+ export function planAllRepairs({ graph = defaultGraph, listLibraries = defaultListLibraries, loadPrivateIndex = defaultLoadPrivateIndex, libraryId = null } = {}) {
205
+ const targets = libraryId ? [libraryId] : listLibraries().filter((library) => !library.archivedAt).map((library) => library.id)
206
+ const plans = []
207
+ const failures = []
208
+ for (const id of targets) {
209
+ try {
210
+ plans.push(planLibraryRepair(id, { graph, loadPrivateIndex }))
211
+ } catch (error) {
212
+ failures.push({ libraryId: id, error: String(error?.message || error) })
213
+ }
214
+ }
215
+ return {
216
+ plans,
217
+ failures,
218
+ attested: plans.reduce((total, plan) => total + plan.groups.length, 0),
219
+ similar: plans.reduce((total, plan) => total + plan.ambiguous.length, 0),
220
+ }
221
+ }
222
+
223
+ /**
224
+ * 执行一组计划。`groups` 只应包含 attested 类(调用方负责筛掉 similar);
225
+ * 写入前后各读一次实体快照,把 mergeEntities 级联清扫掉的计划外实体写回。
226
+ */
227
+ export function applyRepairGroups(libraryId, groups, { graph = defaultGraph, merge = true } = {}) {
228
+ const report = { libraryId, merged: 0, created: 0, restored: 0, failures: [] }
229
+ if (!merge) return report
230
+ for (const group of groups) {
231
+ let before = { entities: {} }
232
+ try {
233
+ before = readEntityStore(ENTITIES_FILE(libraryId))
234
+ } catch (error) {
235
+ report.failures.push({ group: group.target.name, error: String(error?.message || error) })
236
+ continue
237
+ }
238
+ try {
239
+ let targetId = group.target.id
240
+ if (group.creates) {
241
+ const created = graph.createEntity({ libraryId, name: group.target.name, kind: group.target.kind, status: 'confirmed', confirmedBy: 'user' })
242
+ targetId = created.id
243
+ report.created += 1
244
+ }
245
+ graph.mergeEntities({ libraryId, targetId, sourceIds: group.sources.map((entity) => entity.id) })
246
+ report.merged += 1
247
+ report.restored += restoreSweptRows(libraryId, before, group)
248
+ } catch (error) {
249
+ report.failures.push({ group: group.target.name, error: String(error?.message || error) })
250
+ }
251
+ }
252
+ return report
253
+ }
254
+
255
+ function restoreSweptRows(libraryId, before, group) {
256
+ const file = ENTITIES_FILE(libraryId)
257
+ const excluded = new Set([group.target.id, ...group.sources.map((entity) => entity.id)])
258
+ return withFileLock(file, () => {
259
+ const store = readEntityStore(file)
260
+ const lost = Object.values(before.entities || {})
261
+ .filter((entity) => entity && entity.id && !excluded.has(entity.id) && !store.entities[entity.id])
262
+ .map((entity) => entity.id)
263
+ for (const id of lost) store.entities[id] = before.entities[id]
264
+ if (lost.length) writeJson(file, store)
265
+ return lost.length
266
+ })
267
+ }
268
+
269
+ /** 一份人类可读的规划摘要(诊断页与脚本共用,正文里没有真实记忆内容)。 */
270
+ export function summarizePlan(plan) {
271
+ const lines = []
272
+ for (const group of [...(plan.groups || []), ...(plan.ambiguous || [])]) {
273
+ lines.push(`${group.target.name}${group.creates ? '(新建,正文里出现过)' : ''} ← `
274
+ + group.sources.map((entity) => entity.name).join(' / ') + ` [${group.evidence}]`)
275
+ }
276
+ return lines
277
+ }
278
+
279
+ export function entityFileExists(libraryId) {
280
+ try {
281
+ return fs.existsSync(ENTITIES_FILE(libraryId))
282
+ } catch {
283
+ return false
284
+ }
285
+ }
@@ -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
  }
@@ -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?.domain || null,
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, or when both names have >= 3 characters and sit at
732
- * most 2 edits apart. The longer name is the target (the hub the shorter one
733
- * folds into); on equal length the older id wins, which keeps the direction
734
- * stable across calls. Results are sorted by reason then names then ids, and
735
- * capped at 20.
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 === y.reason ? 0 : x.reason === 'containment' ? -1 : 1)
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
- function graphDomain(value) { return String(value ?? '').normalize('NFKC').trim().toLowerCase() }
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 }