dsh-memu-memory 1.3.15 → 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.
Files changed (48) hide show
  1. package/AGENTS.md +5 -2
  2. package/CHANGELOG.md +33 -1
  3. package/docs/client-conventions.md +1 -0
  4. package/docs/host-adaptation.md +52 -36
  5. package/docs/host-versions.md +120 -0
  6. package/docs/pending-work.md +51 -0
  7. package/docs/troubleshooting.md +15 -2
  8. package/lib/auto-link/candidates.js +4 -1
  9. package/lib/auto-link/decide.js +1 -1
  10. package/lib/auto-link/normalize.js +2 -2
  11. package/lib/auto-link/terminology.js +31 -1
  12. package/lib/binding-diagnostics.js +1 -1
  13. package/lib/client.js +53 -6
  14. package/lib/consolidation-snapshot.js +7 -1
  15. package/lib/curator.js +1 -1
  16. package/lib/diagnostics.js +10 -0
  17. package/lib/entity-repair.js +285 -0
  18. package/lib/environment-check.js +72 -3
  19. package/lib/global-graph.js +11 -2
  20. package/lib/graph.js +32 -8
  21. package/lib/host-surface.js +30 -0
  22. package/lib/index.js +116 -1
  23. package/lib/private-links.js +12 -0
  24. package/lib/rpc.js +48 -10
  25. package/lib/state.js +5 -1
  26. package/package.json +16 -1
  27. package/scripts/chain-matrix.mjs +4 -0
  28. package/scripts/check-doc-drift.mjs +194 -0
  29. package/scripts/entity-dedupe.mjs +110 -0
  30. package/tests/auto-link-candidates.test.mjs +22 -9
  31. package/tests/auto-link-decide.test.mjs +59 -59
  32. package/tests/auto-link-migration.test.mjs +4 -4
  33. package/tests/client-render.test.mjs +112 -1
  34. package/tests/cycle.test.mjs +2 -2
  35. package/tests/diagnostics.test.mjs +21 -0
  36. package/tests/doc-drift.test.mjs +122 -2
  37. package/tests/entity-merge.test.mjs +17 -0
  38. package/tests/environment-check.test.mjs +28 -0
  39. package/tests/global-graph.test.mjs +16 -0
  40. package/tests/global-lifecycle.test.mjs +24 -4
  41. package/tests/graph-cascade.test.mjs +111 -0
  42. package/tests/hybrid-recall.test.mjs +1 -1
  43. package/tests/managed-memory.test.mjs +7 -7
  44. package/tests/private-links.test.mjs +12 -0
  45. package/tests/recall-corpus-eligibility.test.mjs +3 -3
  46. package/tests/settings-plumbing.test.mjs +2 -0
  47. package/tests/tools.test.mjs +1 -1
  48. package/tests/webui-auth.test.mjs +58 -0
@@ -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 }
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') {
@@ -286,7 +286,19 @@ export function suggestPrivateLinks({
286
286
  }
287
287
  }
288
288
  const analyses = new Map()
289
+ // A sliding window must not name an entity while the longer window it lives in
290
+ // groups at least as many memories: `南宫晚` and `宫晚晴` point at exactly the same
291
+ // pair as `南宫晚晴`, and only the 4-char form is a name. `星港` survives because the
292
+ // longer `星港夜班` appears in a single memory.
293
+ const hubGroups = [...groups.values()]
294
+ const subsumed = new Set(hubGroups
295
+ .filter(group => hubGroups.some(other => other !== group
296
+ && other.token.length > group.token.length
297
+ && other.entries.length >= group.entries.length
298
+ && other.token.includes(group.token)))
299
+ .map(group => group.token))
289
300
  for (const [key, group] of groups) {
301
+ if (subsumed.has(group.token)) continue
290
302
  if (group.entries.length < 2) continue
291
303
  if (!group.entries.some(item => wantedSet.has(item.id))) continue
292
304
  const kind = inferEntityKind(group.entries.map(item => item.entry), group.token)
package/lib/rpc.js CHANGED
@@ -12,7 +12,9 @@ import { privateList, privateUpdate, privateRemember, privateRecall, privateArch
12
12
  import { normalizeMemoryContext } from './context.js'
13
13
  import { requestPrivateConsolidation } from './private.js'
14
14
  import { listHostModelOptions, discoverForkModels, redactConsolidationSettings, disposeConsolidationRoute } from './fork-model.js'
15
- import { startGlobalCuration, getCurationJob, cancelCurationJob, listCurationJobs, undoGlobalAbsorb } from './curator.js'
15
+ import { startGlobalCuration, getCurationJob, cancelCurationJob, listCurationJobs, undoGlobalAbsorb, activationUsesFlatSpec } from './curator.js'
16
+ import { scheduleFlavor } from './salient-wake.js'
17
+ import { hostSurface, noteHostSurface } from './host-surface.js'
16
18
  import { maybeMigrateLibraries } from './migrate.js'
17
19
  import { getPromptStates, savePromptOverride, resetPrompt, resetAllPrompts } from './prompts.js'
18
20
  import { statsView } from './stats.js'
@@ -20,7 +22,7 @@ import { recallCacheStats } from './recall-cache.js'
20
22
  import { getMemuConfig, saveMemuConfig, setEmbeddingSource, testMemuConfig, getSummaryConfig, getVisionConfig } from './memu-config.js'
21
23
  import { getLocalVectorState, downloadLocalVectorModel, installLocalVectorRuntime, selectLocalVectorModel, switchLocalVectorProfile, rollbackLocalVectorProfile, abortLocalVectorMigration, testLocalVector } from './local-vector-service.js'
22
24
  import { webUiHtml, WEBUI_PATH, standaloneHtml, standaloneAssetResponse, SETTINGS_PATH } from './webui.js'
23
- import { getGraph, listEntities, createEntity, confirmEntities, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, purgeAutoLinks, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
25
+ import { getGraph, graphDomain, listEntities, createEntity, confirmEntities, renameEntity, deleteEntity, mergeEntities, suggestEntityMerges, linkEntries, unlinkEntry, purgeAutoLinks, getRelationship, updateRelationship, graphExport, restoreGraphData } from './graph.js'
24
26
  import { generateAnchorCandidates, resetAnchorCandidatesCache } from './auto-link/candidates.js'
25
27
  import { refreshPrivateAutoLinks } from './private-links.js'
26
28
  import { refreshEntityMentions } from './auto-link/apply.js'
@@ -41,6 +43,13 @@ let rejectionGuardWarned = false
41
43
  function requestRejectionOf(connection, req) {
42
44
  try {
43
45
  if (typeof connection?.requestRejection === 'function') return connection.requestRejection(req)
46
+ // 0.2.3-alpha.1 起 requestRejection 从 connection 服务上移除,公开面换成
47
+ // `admit(request): { peer } | { rejection }`。上一版这里只试 isTrustedApiRequest,
48
+ // 而它是模块级函数、不挂在服务上,所以两级探测在新宿主上同时落空,守卫静默失效。
49
+ if (typeof connection?.admit === 'function') {
50
+ const admission = connection.admit(req)
51
+ return admission && typeof admission === 'object' && 'rejection' in admission ? admission.rejection : undefined
52
+ }
44
53
  if (typeof connection?.isTrustedApiRequest === 'function') {
45
54
  return connection.isTrustedApiRequest(req) === true ? undefined : 401
46
55
  }
@@ -48,11 +57,12 @@ function requestRejectionOf(connection, req) {
48
57
  if (!rejectionGuardWarned) {
49
58
  rejectionGuardWarned = true
50
59
  try {
51
- warn('dsh-memu-memory: host exposes no request-rejection guard on connection; falling back to loopback-only admission for the memory RPC')
60
+ warn('dsh-memu-memory: host exposes no request-admission guard on connection (neither requestRejection nor admit); RPC routes stay open and rely on per-library authorization only')
52
61
  } catch {}
53
62
  }
54
63
  // 没有守卫能力时保持原语义(放行):仓库的取舍是「宁可降级并留一行日志,也不 fail
55
- // closed」,而逐条库授权(authorizeLibrary)仍在每次请求里生效。风险写进诊断,不静默。
64
+ // closed」。逐条库授权只在宿主实现 authorizeLibrary 时才生效,而它在任何已核对的宿主上
65
+ // 都不存在——所以这一行 warn 是本插件唯一的越权信号,不能省。
56
66
  return undefined
57
67
  }
58
68
 
@@ -149,15 +159,16 @@ function rpcErrorMessage(error) {
149
159
  try { return redactSecrets(raw).slice(0, RPC_ERROR_MAX_CHARS) } catch { return raw.slice(0, RPC_ERROR_MAX_CHARS) }
150
160
  }
151
161
 
152
- // One capability gate for both routes: absent callback falls back to the HTTP
153
- // boundary (requestRejection) and warns once; a present callback is strict true.
154
- // Keeping one helper makes the session-first / capability-second order identical
155
- // in the global queue and the library routes.
162
+ // One capability gate for both routes: an absent callback returns true and warns once —
163
+ // the HTTP boundary (requestRejection / admit) is what actually rejects then. Keeping one
164
+ // helper makes the session-first / capability-second order identical in the global queue
165
+ // and the library routes. No verified host implements authorizeLibrary, so this is a
166
+ // forward-looking hook, not a guard the plugin can count on.
156
167
  async function authorizeWithCapability(connection, req, { libraryId, operation, label }) {
157
168
  if (typeof connection?.authorizeLibrary !== 'function') {
158
169
  if (!capabilityAbsentWarned) {
159
170
  capabilityAbsentWarned = true
160
- try { warn(`dsh-memu-memory: host does not implement connection.authorizeLibrary; ${label} falls back to the HTTP boundary (requestRejection)`) } catch {}
171
+ try { warn(`dsh-memu-memory: host does not implement connection.authorizeLibrary; ${label} relies on the HTTP admission guard alone (requestRejection or admit)`) } catch {}
161
172
  }
162
173
  return true
163
174
  }
@@ -488,6 +499,7 @@ async function privateListView(scope, { limit = null, previewChars = 4000 } = {}
488
499
  libraryId: fileLibraryId,
489
500
  ...(libraryName ? { libraryName } : {}),
490
501
  title: e?.title || '',
502
+ domain: graphDomain(e?.domain) || 'general',
491
503
  layer: e?.layer || 'long_term',
492
504
  status: e?.status || 'active',
493
505
  marginalized: e?.marginalized === true,
@@ -830,6 +842,8 @@ async function dispatch(ctx, endpoint, payload = {}) {
830
842
  globalCount: globalEntries.filter((e) => (e.status || 'active') === 'active').length,
831
843
  jobs: listCurationJobs().slice(-10),
832
844
  recallCache: recallCacheStats(),
845
+ // docs/host-versions.md §13.6:真机核对台账指纹用的旁证,不参与任何判断。
846
+ hostSurface: hostSurface(),
833
847
  }
834
848
  }
835
849
  case 'diagnoseSession': {
@@ -1146,6 +1160,8 @@ async function dispatch(ctx, endpoint, payload = {}) {
1146
1160
  'consolidationTurnLog', 'consolidationTurnLogTools',
1147
1161
  // 整理执行器(T1 §10.2):恢复默认 = 回到 'fork'(现状每窗新 fork)。
1148
1162
  'consolidationRunner',
1163
+ // 升级后的一次性实体碎片自愈:恢复默认 = 开(只合可证明的那一类)。
1164
+ 'autoRepairEntityFragments',
1149
1165
  ]) patch[key] = DEFAULT_SETTINGS[key]
1150
1166
  return redactConsolidationSettings(updateSettings(patch))
1151
1167
  }
@@ -1182,6 +1198,9 @@ async function dispatch(ctx, endpoint, payload = {}) {
1182
1198
  'consolidationTurnLog', 'consolidationTurnLogTools',
1183
1199
  // 整理执行器(T1 §10.2):'fork'(默认,现状)/ 'worker'(持久整理 worker)。
1184
1200
  'consolidationRunner',
1201
+ // 升级自愈的可写 kill switch:不在名单里,设置页那句「可关」就是空头承诺
1202
+ // (1.3.15 的 midTurnRecall 教训)。
1203
+ 'autoRepairEntityFragments',
1185
1204
  ])
1186
1205
  const clean = {}
1187
1206
  for (const [k, v] of Object.entries(patch)) if (allowed.has(k)) clean[k] = v
@@ -1570,13 +1589,22 @@ async function dispatch(ctx, endpoint, payload = {}) {
1570
1589
  const libraryId = payload?.libraryId ? String(payload.libraryId) : null
1571
1590
  const libraries = libraryId ? [getLibrary(libraryId)] : listLibraries()
1572
1591
  if (libraries.some(library => !library)) throw new Error('library not found')
1592
+ const domainFilter = graphDomain(payload?.domain)
1573
1593
  const items = []
1594
+ const domains = new Set()
1574
1595
  const errors = []
1575
1596
  const collect = (index, lib) => {
1576
1597
  for (const [id, entry] of Object.entries(index.entries || {})) {
1598
+ // An unstamped legacy entry reads as `general` in the private graph and
1599
+ // `unknown` in the global one (graph.js / listGlobal). The wall shows both
1600
+ // scopes side by side, so it keeps that split instead of inventing a third.
1601
+ const domain = graphDomain(entry.domain) || (lib ? 'general' : 'unknown')
1602
+ domains.add(domain)
1603
+ if (domainFilter && domain !== domainFilter) continue
1577
1604
  items.push({
1578
1605
  id, title: entry.title || '', preview: String(entry.content || '').slice(0, 180),
1579
1606
  libraryId: lib?.id || null, libraryName: lib?.name || 'global',
1607
+ domain,
1580
1608
  layer: entry.layer || 'long_term', status: entry.status || 'active',
1581
1609
  source: entry.source || 'inferred', confidence: entry.confidence ?? null,
1582
1610
  accuracy: entry.accuracy ?? null, createdAt: entry.createdAt || null, updatedAt: entry.updatedAt || null,
@@ -1611,7 +1639,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1611
1639
  try { collect(loadGlobalIndex(), null) } catch { errors.push({ libraryId: null, error: 'global index unavailable' }) }
1612
1640
  items.sort((a, b) => String(b.updatedAt || b.createdAt || '').localeCompare(String(a.updatedAt || a.createdAt || '')))
1613
1641
  const limit = Math.max(1, Math.min(1000, Number(payload?.limit) || 300))
1614
- return { items: items.slice(0, limit), total: items.length, libraries, errors }
1642
+ return { items: items.slice(0, limit), total: items.length, domains: [...domains].sort(), libraries, errors }
1615
1643
  }
1616
1644
  case 'getGraph':
1617
1645
  // Reuse the private graph endpoint instead of adding a second read method:
@@ -2270,6 +2298,16 @@ async function dispatch(ctx, endpoint, payload = {}) {
2270
2298
  export function registerRpc(ctx) {
2271
2299
  try {
2272
2300
  ctx.inject(['connection', 'webServer'], (c) => {
2301
+ // §13.6 结构指纹:把这次装载实际命中的宿主形状记一行,供真机核对台账
2302
+ // (docs/host-versions.md §13.1)。全部来自既有探测,不做判断、不比版本号。
2303
+ try {
2304
+ noteHostSurface('rpcGuard', typeof c.connection?.requestRejection === 'function' ? 'requestRejection'
2305
+ : typeof c.connection?.admit === 'function' ? 'admit'
2306
+ : typeof c.connection?.isTrustedApiRequest === 'function' ? 'isTrustedApiRequest' : 'none')
2307
+ noteHostSurface('schedule', scheduleFlavor(typeof ctx.get === 'function' ? ctx.get('schedule') : null) || 'none')
2308
+ const subagents = typeof ctx.get === 'function' ? ctx.get('subagents') : null
2309
+ noteHostSurface('activation', subagents?.startActivation ? (activationUsesFlatSpec(subagents) ? 'flat' : 'nested') : 'none')
2310
+ } catch { /* 指纹只是旁证,探测失败不得影响装载 */ }
2273
2311
  c.effect(
2274
2312
  () => {
2275
2313
  const route = {
package/lib/state.js CHANGED
@@ -165,6 +165,10 @@ export const DEFAULT_SETTINGS = {
165
165
  consolidationTurnLogTools: 'none',
166
166
  // A positive age marks cleanup candidates; deletion always needs a user action.
167
167
  purgeArchivedAfterDays: 0,
168
+ // 升级后的一次性实体碎片自愈(lib/index.js startEntityRepairPass)。默认开,但它**只**合并
169
+ // 可证明的那一类(窗口片段重建出正文里出现过的完整名);"只是相似"的候选永远等人工确认。
170
+ // 关掉它 = 连可证明的也不动,全部留在诊断页的手动按钮上。写入前一律先备份。
171
+ autoRepairEntityFragments: true,
168
172
  // 回合中途补充召回(inject.js midTurnPolicy):默认开。这些键必须注册在这里——
169
173
  // updateSettings 对 DEFAULT_SETTINGS 之外的键静默丢弃,文档里「midTurnRecall: false
170
174
  // 可关」的承诺只有落了默认值与白名单才成立。阈值口径见 docs/memory-semantics.md §8.4。
@@ -687,7 +691,7 @@ export function deleteLibrary(id, { force = false } = {}) {
687
691
  if (state.libraries[id].archived !== true) return { ok: false, error: 'archive the library before deleting it' }
688
692
  // 只拦「危险归档 + 仍在用」:扫描误归档的那一类才有一键删掉全部记忆的风险。
689
693
  // 用户主动归档仍有绑定会话时照旧允许(删除会连同绑定一起清掉,这是既有语义);
690
- // 冷数据的旧归档同理放行,否则本机 rp / ai中转站 这类库会变成"永远删不掉"。
694
+ // 冷数据的旧归档同理放行,否则本机 rp / 另一个工作区库 这类库会变成"永远删不掉"。
691
695
  if (!force && archivedWhileInUse(state.libraries[id], { inUse: inUseLibraryIds(state).has(id) })) {
692
696
  return { ok: false, error: 'this library was archived while a conversation still uses it; unbind or delete those sessions first (force overrides)' }
693
697
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-memu-memory",
3
3
  "icon": "./assets/icon.png",
4
- "version": "1.3.15",
4
+ "version": "1.4.0",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -71,6 +71,21 @@
71
71
  "dsh": ">=0.2.0-rc.1"
72
72
  },
73
73
  "dsh": {
74
+ "compatibility": {
75
+ "dshReleases": [
76
+ "0.2.0-rc.1",
77
+ "0.2.1-rc.3",
78
+ "0.2.1-rc.5",
79
+ "0.2.2-alpha.3",
80
+ "0.2.2-rc.1",
81
+ "0.2.2-rc.2",
82
+ "0.2.2-rc.3",
83
+ "0.2.2-rc.4",
84
+ "0.2.2-rc.5",
85
+ "0.2.3-alpha.1",
86
+ "0.2.3-alpha.2"
87
+ ]
88
+ },
74
89
  "bundle": {
75
90
  "patch": "./cordis.patch.yml"
76
91
  },