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.
Files changed (59) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +50 -1
  3. package/docs/binding-lifecycle.md +1 -1
  4. package/docs/client-conventions.md +1 -0
  5. package/docs/host-adaptation.md +58 -16
  6. package/docs/host-versions.md +120 -0
  7. package/docs/memory-semantics.md +4 -1
  8. package/docs/pending-work.md +51 -0
  9. package/docs/troubleshooting.md +16 -3
  10. package/lib/auto-link/candidates.js +4 -1
  11. package/lib/auto-link/decide.js +1 -1
  12. package/lib/auto-link/normalize.js +2 -2
  13. package/lib/auto-link/terminology.js +31 -1
  14. package/lib/binding-diagnostics.js +1 -1
  15. package/lib/client.js +53 -6
  16. package/lib/consolidation-snapshot.js +37 -1
  17. package/lib/curator.js +1 -1
  18. package/lib/cycle.js +5 -0
  19. package/lib/diagnostics.js +10 -0
  20. package/lib/entity-repair.js +285 -0
  21. package/lib/environment-check.js +72 -3
  22. package/lib/global-graph.js +11 -2
  23. package/lib/graph.js +32 -8
  24. package/lib/host-surface.js +30 -0
  25. package/lib/index.js +116 -1
  26. package/lib/inject.js +428 -32
  27. package/lib/private-links.js +12 -0
  28. package/lib/rpc.js +78 -11
  29. package/lib/state.js +78 -1
  30. package/package.json +16 -1
  31. package/scripts/chain-matrix.mjs +4 -0
  32. package/scripts/check-doc-drift.mjs +194 -0
  33. package/scripts/entity-dedupe.mjs +110 -0
  34. package/tests/auto-link-candidates.test.mjs +22 -9
  35. package/tests/auto-link-decide.test.mjs +59 -59
  36. package/tests/auto-link-migration.test.mjs +4 -4
  37. package/tests/client-render.test.mjs +112 -1
  38. package/tests/cue.test.mjs +2 -1
  39. package/tests/cycle.test.mjs +2 -2
  40. package/tests/diagnostics.test.mjs +21 -0
  41. package/tests/doc-drift.test.mjs +122 -2
  42. package/tests/entity-merge.test.mjs +17 -0
  43. package/tests/environment-check.test.mjs +28 -0
  44. package/tests/global-graph.test.mjs +16 -0
  45. package/tests/global-lifecycle.test.mjs +24 -4
  46. package/tests/graph-cascade.test.mjs +111 -0
  47. package/tests/hybrid-recall.test.mjs +1 -1
  48. package/tests/inject.test.mjs +7 -7
  49. package/tests/injection-chain.test.mjs +40 -2
  50. package/tests/injection-rollback.test.mjs +4 -3
  51. package/tests/managed-memory.test.mjs +7 -7
  52. package/tests/media.test.mjs +4 -1
  53. package/tests/memory-chain.test.mjs +4 -3
  54. package/tests/pending-injection.test.mjs +107 -0
  55. package/tests/private-links.test.mjs +12 -0
  56. package/tests/recall-corpus-eligibility.test.mjs +3 -3
  57. package/tests/settings-plumbing.test.mjs +2 -0
  58. package/tests/tools.test.mjs +1 -1
  59. package/tests/webui-auth.test.mjs +58 -0
@@ -232,6 +232,7 @@ export function rankCandidates(entries, stats, { policy = AUTOLINK_POLICY_V3, le
232
232
  const size = Math.max(1, entries.length)
233
233
  const tier1 = []
234
234
  const tier2 = []
235
+ const rows = []
235
236
  for (const stat of stats.values()) {
236
237
  const term = stat.term
237
238
  if (stat.df < policy.minDf) continue
@@ -266,7 +267,36 @@ export function rankCandidates(entries, stats, { policy = AUTOLINK_POLICY_V3, le
266
267
  intro: isIntro,
267
268
  lexicon: lexiconTier1 ? 'user' : (lexiconModelHit ? 'model-proposal' : null),
268
269
  }
269
- if (isQuoted || isMixed || isIntro || lexiconTier1) tier1.push(row)
270
+ rows.push({ row, evidenced: isQuoted || isMixed || isIntro || lexiconTier1 })
271
+ }
272
+ // A sliding-window fragment is only noise while the longer surface it lives in
273
+ // is at least as well attested: `南宫晚` and `宫晚晴` carry exactly the documents
274
+ // `南宫晚晴` does, so the 4-char form wins and the two windows never reach the
275
+ // queue. A short name that also stands on its own (`星港`, whose 4-char neighbours
276
+ // appear in a single memory) keeps the higher df and survives. Terms with direct
277
+ // surface evidence (quote / identifier / name-intro / user lexicon) are never
278
+ // dropped here — that is evidence, not a statistic.
279
+ // Indexed by fragment instead of compared pairwise: a big library has tens of
280
+ // thousands of candidate n-grams and O(n²) `includes` does not belong in a sweep.
281
+ const statistical = rows.filter((item) => !item.evidenced)
282
+ const longestAttested = new Map()
283
+ for (const { row } of statistical) {
284
+ const chars = [...row.term]
285
+ for (let start = 0; start < chars.length; start += 1) {
286
+ for (let size = 1; start + size <= chars.length; size += 1) {
287
+ if (start === 0 && size === chars.length) continue // only proper substrings count as fragments
288
+ const fragment = chars.slice(start, start + size).join('')
289
+ const known = longestAttested.get(fragment)
290
+ if (known === undefined || row.df > known) longestAttested.set(fragment, row.df)
291
+ }
292
+ }
293
+ }
294
+ const subsumed = new Set(statistical
295
+ .filter(({ row }) => (longestAttested.get(row.term) || 0) >= row.df)
296
+ .map(({ row }) => row.term))
297
+ for (const { row, evidenced } of rows) {
298
+ if (subsumed.has(row.term)) continue
299
+ if (evidenced) tier1.push(row)
270
300
  else tier2.push(row)
271
301
  }
272
302
  const byScore = (a, b) => b.score - a.score || a.term.localeCompare(b.term)
@@ -56,7 +56,7 @@ export const RUNTIME_STATE = Object.freeze([
56
56
  { layer: 'temporary-map', file: 'lib/media.js:19', name: 'captures', keyedBy: 'sessionId', clearedBy: 'capture settle' },
57
57
  { layer: 'temporary-map', file: 'lib/private.js:1040', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
58
58
  { layer: 'temporary-map', file: 'lib/curator.js:56', name: 'jobs', keyedBy: 'job id', clearedBy: 'curation settle' },
59
- { layer: 'cache', file: 'lib/state.js:1461', name: 'indexCache', keyedBy: 'libraryId', clearedBy: 'next load / external write' },
59
+ { layer: 'cache', file: 'lib/state.js:1538', name: 'indexCache', keyedBy: 'libraryId', clearedBy: 'next load / external write' },
60
60
  { layer: 'cache', file: 'lib/paths.js:52', name: 'readFailures', keyedBy: 'absolute file', clearedBy: 'a later successful read' },
61
61
  ])
62
62
 
package/lib/client.js CHANGED
@@ -206,6 +206,8 @@ window.__ModuleLoader__.load({
206
206
  pageDiagnostics: '诊断',
207
207
  descDiagnostics: '插件内部的故障与修复记录(含 stderr、目录、修复动作),与活动日志分开存放',
208
208
  diagEnvTitle: '环境自检',
209
+ diagHostSurface: '宿主形状:',
210
+ diagHostSurfaceHint: '这些值来自本插件的宿主能力探测,用于核对 docs/host-versions.md 的台账行;插件不据此分支,也不读宿主版本号。',
209
211
  diagEnvDesc: '启动时与打开本页时各检查一次:数据目录、遗留锁、引擎、向量档案、运行时、模型文件',
210
212
  diagEventsTitle: '诊断记录',
211
213
  diagEventsDesc: '只放插件自己出错的信息,不进 WebUI 常规日志;同一条重复出现只累加次数',
@@ -283,6 +285,9 @@ window.__ModuleLoader__.load({
283
285
  wallFilterScope: '范围',
284
286
  wallFilterStatus: '状态',
285
287
  wallFilterLayer: '层级',
288
+ wallFilterDomain: '域',
289
+ wallDomainAll: '全部域',
290
+ wallDomainHint: '这条记忆属于哪个域。没有标记的旧私有条目按「通用」显示,全局条目按「未知」显示。',
286
291
  wallAllLayers: '全部层级',
287
292
  multiSelect: '多选',
288
293
  wallSelected: '已选 {n} 条',
@@ -301,6 +306,7 @@ window.__ModuleLoader__.load({
301
306
  entityMergeConflict: '({n} 条关系快照与主节点侧冲突,保留主节点侧)',
302
307
  mergeReasonContainment: '名称包含',
303
308
  mergeReasonDistance: '写法相近',
309
+ mergeReasonNameCore: '同一名字的不同写法',
304
310
  openMemu: '打开 MemU WebUI',
305
311
  openGraphStudio: '打开关系图谱',
306
312
  openGraphStudioHint: '在 WebUI 中打开完整关系图谱(浏览器拦下新标签页时在应用内打开)',
@@ -984,6 +990,8 @@ window.__ModuleLoader__.load({
984
990
  autoLinkDeterministic: '确定性写边',
985
991
  autoLinkOff: '关闭',
986
992
  autoLinkHint: '“只出候选”不会写任何边;“确定性写边”只写两类边:已确认实体的提及,以及 conflicts_with / supersedes / 同 fact_key 的字段证据。词面相似度与向量永远不建边。',
993
+ autoRepairEntityFragments: '升级后自动合并名字碎片',
994
+ autoRepairEntityFragmentsHint: '旧版本把中文名的滑窗片段当成了独立人物(两个节点其实是同一个人)。本版本首次启动会扫一遍并在**写入前备份**,但只合并可证明的那一类:片段能首尾重叠重建成一个在正文里出现过的完整名,或短名在正文里从未独立于长名出现。只是名字相近(编辑距离、共同字)的候选一律不动,只在「设置 · 诊断」里报数,由你点「需确认」的按钮处理。关闭此项 = 连可证明的也不动。',
987
995
  firstRunTitle: '先建一个记忆库',
988
996
  firstRunDesc: '还没有任何记忆库。新建一个私有库后,会话里的记忆才有地方落。',
989
997
  firstRunGoLibraries: '去新建库',
@@ -1187,6 +1195,8 @@ window.__ModuleLoader__.load({
1187
1195
  pageDiagnostics: 'Diagnostics',
1188
1196
  descDiagnostics: 'Internal faults and repairs (stderr, paths, repair actions), kept apart from the activity log',
1189
1197
  diagEnvTitle: 'Environment check',
1198
+ diagHostSurface: 'Host shapes:',
1199
+ diagHostSurfaceHint: 'These values come from this plugin\u2019s host capability probes and let you verify a row of the docs/host-versions.md ledger. The plugin never branches on them and never reads a host version.',
1190
1200
  diagEnvDesc: 'Runs at startup and when this page opens: data dir, stale locks, engine, vector profile, runtime, model files',
1191
1201
  diagEventsTitle: 'Diagnostic records',
1192
1202
  diagEventsDesc: 'Plugin-internal errors only, never in the regular WebUI log; repeats bump a counter instead of adding rows',
@@ -1264,6 +1274,9 @@ window.__ModuleLoader__.load({
1264
1274
  wallFilterScope: 'Scope',
1265
1275
  wallFilterStatus: 'Status',
1266
1276
  wallFilterLayer: 'Layer',
1277
+ wallFilterDomain: 'Domain',
1278
+ wallDomainAll: 'All domains',
1279
+ wallDomainHint: 'Which domain this memory belongs to. Older private entries with no stamp show as General, global ones as Unknown.',
1267
1280
  wallAllLayers: 'All layers',
1268
1281
  multiSelect: 'Multi-select',
1269
1282
  wallSelected: '{n} selected',
@@ -1282,6 +1295,7 @@ window.__ModuleLoader__.load({
1282
1295
  entityMergeConflict: '({n} relationship snapshots clashed with the target side and were dropped)',
1283
1296
  mergeReasonContainment: 'Name contained',
1284
1297
  mergeReasonDistance: 'Similar spelling',
1298
+ mergeReasonNameCore: 'Same name, different form',
1285
1299
  openMemu: 'Open MemU WebUI',
1286
1300
  openGraphStudio: 'Open relationship graph',
1287
1301
  openGraphStudioHint: 'Open the full relationship graph in the WebUI (opens in-app when the browser blocks a new tab)',
@@ -1964,6 +1978,8 @@ window.__ModuleLoader__.load({
1964
1978
  autoLinkDeterministic: 'Deterministic edges',
1965
1979
  autoLinkOff: 'Off',
1966
1980
  autoLinkHint: '"Candidates only" writes no edges. "Deterministic edges" writes exactly two kinds: mentions of confirmed entities, and field evidence from conflicts_with / supersedes / the same fact_key. Lexical similarity and vectors never create an edge.',
1981
+ autoRepairEntityFragments: 'Auto-merge name fragments after upgrade',
1982
+ autoRepairEntityFragmentsHint: 'Older versions turned sliding windows of a Chinese name into separate entities, so one person ended up as two nodes. On the first start after an upgrade the plugin scans once and backs up before writing, but merges only the provable class: fragments that overlap head-to-tail into a longer name which actually appears in a memory body, or a short name that never appears outside a longer one anywhere in the library. Merely similar names (edit distance, a shared character) are never touched - they are only counted on Settings / Diagnostics behind a "needs confirmation" button. Off means even the provable class waits for you.',
1967
1983
  firstRunTitle: 'Create a memory library first',
1968
1984
  firstRunDesc: 'There are no libraries yet. Memories from your conversations need one to land in.',
1969
1985
  firstRunGoLibraries: 'Create a library',
@@ -2979,6 +2995,8 @@ html[data-standalone]:has(.dshm-root.is-graph-navless) .stage{padding-left:28px;
2979
2995
  // memory quietly claiming to be a quote.
2980
2996
  const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred', imagined: 'sourceImagined', told: 'sourceTold' }
2981
2997
  const DOMAIN_LABELS = { general: 'dmGeneral', coding: 'dmCoding', rp: 'dmRp', mixed: 'dmMixed', universal: 'dmUniversal', personal: 'dmPersonal', other: 'dmOther', unknown: 'dmUnknown' }
2998
+ // suggestEntityMerges 的三种理由;新增理由必须同时加键,否则界面只显示英文原词。
2999
+ const MERGE_REASON_LABEL_KEYS = { containment: 'mergeReasonContainment', 'edit-distance': 'mergeReasonDistance', 'name-core': 'mergeReasonNameCore' }
2982
3000
  const INJECT_LABELS = { smart: 'modeSmart', 'anchor-only': 'modeAnchor', 'per-turn': 'modePerTurn', off: 'modeOff' }
2983
3001
 
2984
3002
  // Unknown values fall through verbatim: a newer host enum must stay readable
@@ -3524,7 +3542,8 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
3524
3542
  setError(failures.length ? t('gsLoadPartial') + failures.join(', ') : '')
3525
3543
  } else {
3526
3544
  const value = showGlobal
3527
- ? await call('getGraph', { scope: 'global', focusId: focus || null, depth: 2, limit: 200 })
3545
+ ? await call('getGraph', { scope: 'global', focusId: focus || null, depth: 2, limit: 200,
3546
+ domain: graphDomain || undefined })
3528
3547
  : await readLibrary(graphLibrary)
3529
3548
  if (!alive) return
3530
3549
  setGraph(value && Array.isArray(value.nodes)
@@ -3877,6 +3896,8 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
3877
3896
  h('div', { className: 'dshm-gs-tags' },
3878
3897
  h('span', { className: 'dshm-gs-tag' }, String(selected.kind || 'memory')),
3879
3898
  selected.layer ? h('span', { className: 'dshm-gs-tag neutral' }, String(selected.layer)) : null,
3899
+ // Memory nodes carry their domain from the server; entity nodes do not.
3900
+ selected.domain ? h('span', { className: 'dshm-gs-tag neutral' }, domainText(t, selected.domain)) : null,
3880
3901
  selected.status === 'provisional' ? h('span', { className: 'dshm-gs-tag warn' }, t('gsPending')) : null))),
3881
3902
  h('dl', { className: 'dshm-gs-kv' },
3882
3903
  h('dt', null, 'ID'), h('dd', null, String(selected.rawId || selected.id)),
@@ -4410,7 +4431,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4410
4431
  const key = 'merge:' + item.sourceId + '>' + item.targetId
4411
4432
  return h('div', { key, className: 'dshm-graph-tools' },
4412
4433
  h('span', { style: { minWidth: 0, overflowWrap: 'anywhere' } }, entityLabel(item.sourceId) + ' → ' + entityLabel(item.targetId)),
4413
- h(Tag, { tone: 'info' }, item.reason === 'containment' ? t('mergeReasonContainment') : t('mergeReasonDistance')),
4434
+ h(Tag, { tone: 'info' }, t(MERGE_REASON_LABEL_KEYS[item.reason] || 'mergeReasonDistance')),
4414
4435
  h(Button, {
4415
4436
  style: armed === key ? { ...S.btn, color: V.danger, borderColor: V.danger } : S.btn,
4416
4437
  title: t('entityMergeHint'),
@@ -4539,6 +4560,8 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4539
4560
  const [multiBlocked, setMultiBlocked] = React.useState(false)
4540
4561
  const [pool, setPool] = React.useState('active')
4541
4562
  const [layer, setLayer] = React.useState('all')
4563
+ // 域筛选交给服务端:browseWall 一次最多回 300 条,客户端筛完再看计数会骗人。
4564
+ const [wallDomain, setWallDomain] = React.useState('')
4542
4565
  const [query, setQuery] = React.useState('')
4543
4566
  const [error, setError] = React.useState('')
4544
4567
  const [version, setVersion] = React.useState(0)
@@ -4581,7 +4604,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4581
4604
  const current = () => alive && requestId === browseRequest.current
4582
4605
  const load = async () => {
4583
4606
  try {
4584
- const value = await call('browseWall', { libraryId: libraryId || null, limit: 300 })
4607
+ const value = await call('browseWall', { libraryId: libraryId || null, limit: 300, domain: wallDomain || undefined })
4585
4608
  if (!current()) return
4586
4609
  setData(value)
4587
4610
  setError('')
@@ -4593,7 +4616,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4593
4616
  // 不再整页空。用户可手动切换库;多库选项保留为禁用。
4594
4617
  if (!libraryId && firstLibraryId && /forbidden|403/i.test(message)) {
4595
4618
  try {
4596
- const value = await call('browseWall', { libraryId: firstLibraryId, limit: 300 })
4619
+ const value = await call('browseWall', { libraryId: firstLibraryId, limit: 300, domain: wallDomain || undefined })
4597
4620
  // A newer selection owns the wall now; do not force the reader
4598
4621
  // back to the first library from a fallback they did not ask for.
4599
4622
  if (!current()) return
@@ -4612,7 +4635,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4612
4635
  }
4613
4636
  void load()
4614
4637
  return () => { alive = false }
4615
- }, [call, libraryId, revision, stamp, version, firstLibraryId])
4638
+ }, [call, libraryId, revision, stamp, version, firstLibraryId, wallDomain])
4616
4639
  React.useEffect(() => {
4617
4640
  if (!detail) return undefined
4618
4641
  const onKey = (event) => { if (event.key === 'Escape') setDetail(null) }
@@ -4896,6 +4919,9 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
4896
4919
  h(Tag, { tone: shown.source === 'imagined' ? 'warn' : (shown.source === 'user_said' ? 'info' : undefined) },
4897
4920
  enumText(t, SOURCE_LABELS, shown.source)),
4898
4921
  h(Tag, null, enumText(t, STATUS_LABELS, shown.status)),
4922
+ // 「这条记忆来自哪个域」是用户判断它为什么会出现在这里的第一线索;
4923
+ // 私有条目取 browseWall 的归一值,全局条目取 listGlobal 的 stamp 或 unknown。
4924
+ h(Tag, { title: t('wallDomainHint') }, domainText(t, shown.domain || detail.item?.domain || 'general')),
4899
4925
  // 这条记忆有没有进向量库,直接写在条目上(remember 提交成功后落盘)。
4900
4926
  shown.vector
4901
4927
  ? h(Tag, { tone: 'info' }, `${t('vectorIndexedTag')}${shown.vector.model ? ' · ' + shown.vector.model : ''}${shown.vector.generation ? ' · g' + shown.vector.generation : ''}`)
@@ -5007,6 +5033,17 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
5007
5033
  h('option', { value: '', disabled: multiBlocked }, t('allLibraries')),
5008
5034
  libraries.map((lib) => h('option', { key: lib.id, value: lib.id }, libraryOptionLabel(lib, libraries))))
5009
5035
  : null
5036
+ // 域候选来自服务端的完整并集(不受当前筛选影响),所以选了某个域之后仍能换。
5037
+ const domainOptions = [...new Set([...(Array.isArray(data?.domains) ? data.domains : []), wallDomain].filter(Boolean))].sort()
5038
+ const domainSelect = h('select', {
5039
+ value: wallDomain,
5040
+ title: t('wallDomainHint'),
5041
+ 'aria-label': t('wallFilterDomain'),
5042
+ style: { ...S.input, flex: '0 1 150px', minWidth: 130, maxWidth: 220 },
5043
+ onChange: (event) => setWallDomain(event.target.value),
5044
+ },
5045
+ h('option', { value: '' }, t('wallDomainAll')),
5046
+ domainOptions.map(value => h('option', { key: value, value }, domainText(t, value))))
5010
5047
  const hasOptionControls = true
5011
5048
  const multiToggle = h(Button, {
5012
5049
  'aria-pressed': multi,
@@ -5057,7 +5094,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
5057
5094
  multiBlocked && scope === 'private' ? h('span', { style: S.muted, role: 'status' }, t('wallAllBlocked')) : null,
5058
5095
  data?.total > items.length ? h('span', { style: S.muted }, t('wallLimit') + ` (${items.length}/${data.total})`) : null) : null,
5059
5096
  wallTabGroup(poolItems, pool, setPool, { label: t('wallFilterStatus'), marginTop: 12 }),
5060
- wallTabGroup(layerItems, layer, setLayer, { label: t('wallFilterLayer'), marginTop: 10 }),
5097
+ wallTabGroup(layerItems, layer, setLayer, { label: t('wallFilterLayer'), marginTop: 10, extra: domainSelect }),
5061
5098
  visible.length ? h('div', { className: 'dshm-wall-grid' }, visible.map(item =>
5062
5099
  h('button', {
5063
5100
  key: keyOf(item), type: 'button', className: 'dshm-wall-item' + (multi && selectedIds.has(keyOf(item)) ? ' is-selected' : ''),
@@ -5078,6 +5115,8 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
5078
5115
  h('p', null, item.preview),
5079
5116
  h('div', { className: 'dshm-wall-tags' },
5080
5117
  h(Tag, null, enumText(t, SOURCE_LABELS, item.source)),
5118
+ // 域筛选关着时才在卡面出域;筛完每张卡同一个域,再写一遍只是噪音。
5119
+ !wallDomain ? h(Tag, { title: t('wallDomainHint') }, domainText(t, item.domain || 'general')) : null,
5081
5120
  item.status !== 'active' ? h(Tag, { tone: 'warn' }, enumText(t, STATUS_LABELS, item.status)) : null,
5082
5121
  item.openLoop ? h(Tag, null, t('openLoopTag')) : null,
5083
5122
  item.attachmentCount ? h(Tag, null, '▧ ' + item.attachmentCount) : null),
@@ -7435,6 +7474,9 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
7435
7474
  h('option', { value: 'deterministic' }, t('autoLinkDeterministic')),
7436
7475
  h('option', { value: 'off' }, t('autoLinkOff')))),
7437
7476
  h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('autoLinkHint')),
7477
+ // 升级后的一次性碎片自愈。默认开,但只合"可证明"的那一类;相似候选永远等人工确认。
7478
+ h(Field, { label: t('autoRepairEntityFragments') }, h(Toggle, { checked: settings.autoRepairEntityFragments !== false, label: t('autoRepairEntityFragments'), onChange: value => setSetting('autoRepairEntityFragments', value) })),
7479
+ h('div', { className: 'dshm-settings-note', style: { ...S.muted, marginTop: 6, lineHeight: 1.55 } }, t('autoRepairEntityFragmentsHint')),
7438
7480
  h(Field, { label: h('span', { style: { color: V.danger } }, t('consolidationRunner'), h('span', { style: { marginLeft: 6, fontWeight: 600 } }, t('consolidationRunnerExperimental'))) },
7439
7481
  h('select', { style: S.input, value: settings.consolidationRunner || 'fork', onChange: (e) => setSetting('consolidationRunner', e.target.value) },
7440
7482
  h('option', { value: 'fork' }, t('consolidationRunnerFork')),
@@ -8527,6 +8569,11 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
8527
8569
  right: diagButtons,
8528
8570
  },
8529
8571
  diagNotice ? h('div', { style: { ...S.muted, marginBottom: 8, color: V.accent } }, diagNotice) : null,
8572
+ // docs/host-versions.md §13.6:把本机实际命中的宿主形状摆在页面上,核对台账一行只要看一眼。
8573
+ state?.hostSurface ? h('div', {
8574
+ style: { ...S.muted, marginBottom: 8, fontFamily: 'monospace', fontSize: 12, overflowWrap: 'anywhere' },
8575
+ title: t('diagHostSurfaceHint'),
8576
+ }, `${t('diagHostSurface')} ${Object.entries(state.hostSurface).map(([name, value]) => `${name}=${value}`).join(' ')}`) : null,
8530
8577
  diagEnvList)
8531
8578
  const diagEventRow = (entry) => h('div', { key: entry.id, style: S.item },
8532
8579
  h('div', { style: { display: 'flex', justifyContent: 'space-between', gap: 8, alignItems: 'center' } },
@@ -1,5 +1,7 @@
1
1
  import crypto from 'node:crypto'
2
2
  import { stamp } from './paths.js'
3
+ import { recordDiagnostic } from './diagnostics.js'
4
+ import { noteHostSurface } from './host-surface.js'
3
5
 
4
6
  // C 包:把「读一份会话」从一个隐式的整段读盘,变成一个显式的、有身份的固定快照。
5
7
  //
@@ -188,8 +190,42 @@ function rememberColdProbe(sessionId, liveLast, coldLast) {
188
190
  if (oldest !== undefined) coldProbeCache.delete(oldest)
189
191
  }
190
192
 
193
+ // 冷读模块按**能力探测**取,不写版本比较:0.2.2-rc.x 由
194
+ // `@deepseek-ai/dsh-session-query` 提供 `readColdSessionLog`;0.2.3-alpha.2 起
195
+ // 该包在新源码里整体消失(packages 下已无 session-query,也没有任何同义导出)。
196
+ // 降级必须留信号(硬规则 10):否则「快照落后于持久日志」会永久静默,整理悄悄漏掉尾部。
197
+ const COLD_LOG_MODULES = ['@deepseek-ai/dsh-session-query', '@deepseek-ai/dsh-session']
198
+ let coldLogGapNoted = false
199
+
200
+ function noteColdLogGap(detail) {
201
+ if (coldLogGapNoted) return
202
+ coldLogGapNoted = true
203
+ try {
204
+ recordDiagnostic({
205
+ level: 'warn', scope: 'storage', code: 'COLD_LOG_READER_UNAVAILABLE', alert: false,
206
+ message: '会话冷读不可用:没有可用的 readColdSessionLog,整理快照只取活视图',
207
+ hint: '宿主升级后可能移除了 @deepseek-ai/dsh-session-query。此时外部追加的历史不会被整理看到(可能漏掉尾部),但不会写坏数据。',
208
+ detail,
209
+ })
210
+ } catch {}
211
+ }
212
+
191
213
  async function defaultLoadColdLogModule() {
192
- return import('@deepseek-ai/dsh-session-query')
214
+ const tried = []
215
+ for (const spec of COLD_LOG_MODULES) {
216
+ try {
217
+ const mod = await import(spec)
218
+ if (typeof mod?.readColdSessionLog === 'function') {
219
+ // §13.6 结构指纹:记下真正命中的模块,供真机核对台账的 coldLog 一项。
220
+ noteHostSurface('coldLog', COLD_LOG_MODULES.indexOf(spec) === 0 ? 'session-query' : 'session')
221
+ return mod
222
+ }
223
+ tried.push(spec + ': no readColdSessionLog')
224
+ } catch (error) { tried.push(spec + ': ' + (error?.code || error?.message || 'import failed')) }
225
+ }
226
+ noteHostSurface('coldLog', 'none')
227
+ noteColdLogGap({ modules: tried })
228
+ return {}
193
229
  }
194
230
 
195
231
  /**
package/lib/curator.js CHANGED
@@ -1631,7 +1631,7 @@ export async function undoGlobalAbsorb({ id } = {}) {
1631
1631
  // 顶层,无 request 外层)同批在 SubagentService 上新增了树内省方法 rootOf/namesOf/
1632
1632
  // resolveName/waitForTreeWork(0.2.1-rc.5 与 0.2.2-rc.1 上四者均不存在)。用标记方法
1633
1633
  // 探测形态:真实宿主上一次命中,无多余字段、无异常噪音。
1634
- function activationUsesFlatSpec(subagents) {
1634
+ export function activationUsesFlatSpec(subagents) {
1635
1635
  return typeof subagents?.rootOf === 'function' || typeof subagents?.namesOf === 'function'
1636
1636
  }
1637
1637
 
package/lib/cycle.js CHANGED
@@ -94,10 +94,15 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
94
94
  // 在候选阶段直接 continue:不占 budget 名额、不计失败、不推进游标。空注册表 =
95
95
  // 无成员信息,与 rpc.js 的读法一致,不当成「全是归档」。
96
96
  const archived = archivedSessionIdsOf(ctx)
97
+ // 归档库同样不该再整理:宿主侧 archivedSessionIds 只覆盖「会话被归档」,拿不到
98
+ // workspaceRegistry 时它为空集,等于完全不过滤;库被归档后仍照旧整理,会把新内容
99
+ // 写进一个用户以为已经收起来的库(本机实测有这种会话在整理)。
100
+ const libraries = new Map(listLibrariesAll().map(lib => [lib.id, lib]))
97
101
  const candidates = []
98
102
  for (const binding of listSessionBindings()) {
99
103
  if (binding.consolidationFork || !binding.lastTurnAt) continue
100
104
  if (binding.sessionGone) continue
105
+ if (binding.libraryId && libraries.get(binding.libraryId)?.archived === true) continue
101
106
  if (archived?.size && archived.has(String(binding.sessionId))) continue
102
107
  const lastSleepAt = getLastSleepAt(binding.sessionId)
103
108
  const activeAt = Math.max(Date.parse(binding.lastTurnAt) || 0, Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastAgentIdleAt) || 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
+ }