dsh-memu-memory 1.2.1 → 1.2.3

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 (105) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +23 -8
  3. package/README.zh.md +16 -6
  4. package/docs/client-conventions.md +1 -0
  5. package/docs/contributing.md +18 -4
  6. package/docs/emotion-model-spec.md +2 -2
  7. package/docs/env-and-commands.md +20 -0
  8. package/docs/host-api.md +22 -1
  9. package/docs/memory-semantics.md +30 -2
  10. package/docs/troubleshooting.md +76 -5
  11. package/lib/activity-log.js +1 -1
  12. package/lib/backup.js +24 -2
  13. package/lib/binding-diagnostics.js +2 -2
  14. package/lib/client.js +1511 -153
  15. package/lib/consolidation-worker.js +30 -8
  16. package/lib/curator-evidence.js +131 -0
  17. package/lib/curator-policy.js +81 -0
  18. package/lib/curator.js +1252 -91
  19. package/lib/cycle.js +12 -1
  20. package/lib/embedding-download.js +39 -4
  21. package/lib/engine.js +6 -3
  22. package/lib/freshness.js +97 -0
  23. package/lib/global-graph.js +282 -0
  24. package/lib/graph.js +295 -11
  25. package/lib/inbound.js +19 -0
  26. package/lib/inject.js +396 -25
  27. package/lib/lexicon.js +1115 -0
  28. package/lib/local-vector-service.js +8 -6
  29. package/lib/managed-runtime.js +33 -2
  30. package/lib/memory.js +365 -34
  31. package/lib/memu.js +2 -2
  32. package/lib/migrate.js +83 -2
  33. package/lib/private-links.js +587 -0
  34. package/lib/private.js +32 -3
  35. package/lib/prompts/global-curator.md +76 -19
  36. package/lib/prompts/private-consolidation.coding.md +4 -1
  37. package/lib/prompts/private-consolidation.md +3 -1
  38. package/lib/prompts/private-consolidation.mixed.md +3 -1
  39. package/lib/prompts/private-consolidation.rp.md +3 -1
  40. package/lib/prompts.js +1 -1
  41. package/lib/rpc.js +589 -10
  42. package/lib/salient-wake.js +402 -0
  43. package/lib/state.js +95 -1
  44. package/lib/text-retrieval.js +661 -0
  45. package/lib/text-similarity.js +36 -18
  46. package/lib/tools.js +168 -10
  47. package/lib/webui/standalone.css +17 -0
  48. package/lib/webui/standalone.js +2 -0
  49. package/package.json +1 -1
  50. package/scripts/acceptance-local.mjs +8 -5
  51. package/scripts/curator-pair-calibrate.mjs +259 -0
  52. package/scripts/drive-session.mjs +853 -0
  53. package/scripts/lexicon-calibrate.mjs +230 -0
  54. package/scripts/lexicon-dedupe.mjs +318 -0
  55. package/scripts/mock-llm.mjs +903 -0
  56. package/tests/absorb-review.test.mjs +353 -0
  57. package/tests/appendix-b2.test.mjs +2 -2
  58. package/tests/client-export.test.mjs +520 -0
  59. package/tests/client-render.test.mjs +32 -4
  60. package/tests/consolidation-fork.test.mjs +14 -12
  61. package/tests/consolidation-snapshot.test.mjs +39 -0
  62. package/tests/curator-absorb.test.mjs +443 -0
  63. package/tests/curator-calibrate.test.mjs +173 -0
  64. package/tests/curator-clusters.test.mjs +281 -0
  65. package/tests/curator-commit.test.mjs +52 -5
  66. package/tests/curator-evidence.test.mjs +102 -0
  67. package/tests/curator-link.test.mjs +316 -0
  68. package/tests/curator-pairing.test.mjs +252 -0
  69. package/tests/curator-probe.test.mjs +15 -6
  70. package/tests/curator-review-mode.test.mjs +314 -0
  71. package/tests/disclosure.test.mjs +2 -1
  72. package/tests/entity-merge.test.mjs +261 -0
  73. package/tests/fixtures/curator-pairs/labeled.v1.jsonl +90 -0
  74. package/tests/fixtures/lexicon-stub-hooks.mjs +15 -0
  75. package/tests/fixtures/lexicon-stub.mjs +284 -0
  76. package/tests/fixtures/mock-llm/reply.txt +1 -0
  77. package/tests/freshness.test.mjs +140 -0
  78. package/tests/graph-cascade.test.mjs +35 -2
  79. package/tests/graph.test.mjs +96 -0
  80. package/tests/help-page.test.mjs +415 -0
  81. package/tests/inbound.test.mjs +6 -3
  82. package/tests/inject-guide.test.mjs +28 -0
  83. package/tests/inject.test.mjs +157 -5
  84. package/tests/injection-chain.test.mjs +176 -0
  85. package/tests/lexicon-calibrate.test.mjs +48 -0
  86. package/tests/lexicon-dedupe.test.mjs +171 -0
  87. package/tests/lexicon-frequency.test.mjs +179 -0
  88. package/tests/lexicon-inject.test.mjs +410 -0
  89. package/tests/lexicon-perf.test.mjs +436 -0
  90. package/tests/lexicon-ui.test.mjs +547 -0
  91. package/tests/lexicon.test.mjs +922 -0
  92. package/tests/managed-runtime.test.mjs +32 -0
  93. package/tests/mock-llm.test.mjs +225 -0
  94. package/tests/open-loop-date.test.mjs +406 -0
  95. package/tests/private-links.test.mjs +445 -0
  96. package/tests/prompts.test.mjs +35 -0
  97. package/tests/recall-dedup.test.mjs +33 -4
  98. package/tests/salient-wake.test.mjs +362 -0
  99. package/tests/settings-plumbing.test.mjs +76 -0
  100. package/tests/sidebar.test.mjs +5 -1
  101. package/tests/stubs/dsh-schedule.js +105 -0
  102. package/tests/tool-schema.test.mjs +1 -1
  103. package/tests/tools.test.mjs +112 -3
  104. package/tests/webui-auth.test.mjs +352 -2
  105. package/tests/webui.test.mjs +188 -0
@@ -0,0 +1,140 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { freshnessSignals } from '../lib/freshness.js'
5
+
6
+ const DAY_MS = 86_400_000
7
+ // Local noon on 2026-11-15, so "today" is unambiguous in every timezone.
8
+ const NOW = new Date(2026, 10, 15, 12, 0, 0)
9
+ const daysAgo = (days) => new Date(NOW.getTime() - days * DAY_MS).toISOString()
10
+
11
+ function entry(patch = {}) {
12
+ return { title: '普通记忆', content: '窗外的雨停了。', updatedAt: daysAgo(0), ...patch }
13
+ }
14
+
15
+ test('a one-off date is stale only after its local day has passed', () => {
16
+ const cases = [
17
+ ['2026-11-14', true, 'dated-past:2026-11-14'],
18
+ ['2025-12-31', true, 'dated-past:2025-12-31'],
19
+ ['2026-11-15', false],
20
+ ['2026-11-16', false],
21
+ // Annual MM-DD is a birthday, not an expiry — even when that day already passed.
22
+ ['10-29', false],
23
+ ['02-29', false],
24
+ // Impossible or non-date-only values are ignored, never "expired".
25
+ ['2026-02-30', false],
26
+ ['2026-13-01', false],
27
+ ['2026-11-14T00:00:00', false],
28
+ ['', false],
29
+ [null, false],
30
+ [undefined, false],
31
+ ]
32
+ for (const [salientDate, stale, reason] of cases) {
33
+ const result = freshnessSignals(entry({ salientDate }), { now: NOW })
34
+ assert.equal(result.stale, stale, `salientDate=${String(salientDate)}`)
35
+ if (stale) assert.deepEqual(result.reasons, [reason])
36
+ else assert.deepEqual(result.reasons, [])
37
+ }
38
+ })
39
+
40
+ test('the fixed freshness vocabulary matches title and content', () => {
41
+ const terms = ['最新', '最近', '现在', '目前', '今年', '版本', '价格', '天气', '新闻', '比分', '汇率']
42
+ for (const term of terms) {
43
+ const inTitle = freshnessSignals(entry({ title: `关于${term}的记录` }), { now: NOW })
44
+ assert.equal(inTitle.stale, true, `${term} in title`)
45
+ assert.deepEqual(inTitle.reasons, [`freshness-term:${term}`])
46
+
47
+ const inContent = freshnessSignals(entry({ title: '记录', content: `这条提到${term}。` }), { now: NOW })
48
+ assert.equal(inContent.stale, true, `${term} in content`)
49
+ assert.deepEqual(inContent.reasons, [`freshness-term:${term}`])
50
+ }
51
+
52
+ const both = freshnessSignals(entry({ title: '最新价格' }), { now: NOW })
53
+ assert.deepEqual(both.reasons, ['freshness-term:最新', 'freshness-term:价格'])
54
+
55
+ assert.deepEqual(freshnessSignals(entry({ title: 'latest price' }), { now: NOW }), { stale: false, reasons: [] })
56
+ })
57
+
58
+ test('age comes from updatedAt first and ignores project facts', () => {
59
+ assert.deepEqual(
60
+ freshnessSignals(entry({ updatedAt: daysAgo(45) }), { now: NOW }).reasons,
61
+ ['age-days:45'],
62
+ )
63
+ // updatedAt wins over an older createdAt: an edited entry is current again.
64
+ assert.deepEqual(
65
+ freshnessSignals(entry({ updatedAt: daysAgo(1), createdAt: daysAgo(400) }), { now: NOW }).reasons,
66
+ [],
67
+ )
68
+ assert.deepEqual(
69
+ freshnessSignals(entry({ updatedAt: undefined, createdAt: daysAgo(45) }), { now: NOW }).reasons,
70
+ ['age-days:45'],
71
+ )
72
+ // Project conclusions may age too, but a coding library where every card says
73
+ // "old" is noise; the age leg stays off for them.
74
+ assert.deepEqual(
75
+ freshnessSignals(entry({ owner: 'about_project', updatedAt: daysAgo(400) }), { now: NOW }).reasons,
76
+ [],
77
+ )
78
+ // Only the age leg is excluded: time-sensitive wording still counts.
79
+ assert.deepEqual(
80
+ freshnessSignals(entry({ owner: 'about_project', title: '版本', updatedAt: daysAgo(400) }), { now: NOW }).reasons,
81
+ ['freshness-term:版本'],
82
+ )
83
+ })
84
+
85
+ test('missing, invalid and future timestamps are not age signals', () => {
86
+ const cases = [
87
+ { updatedAt: undefined, createdAt: undefined },
88
+ { updatedAt: null, createdAt: null },
89
+ { updatedAt: '', createdAt: '' },
90
+ { updatedAt: 'not-a-date', createdAt: 'also-not-a-date' },
91
+ { updatedAt: NaN, createdAt: NaN },
92
+ { updatedAt: daysAgo(-10), createdAt: daysAgo(-10) },
93
+ ]
94
+ for (const patch of cases) {
95
+ assert.deepEqual(freshnessSignals(entry(patch), { now: NOW }), { stale: false, reasons: [] })
96
+ }
97
+ })
98
+
99
+ test('the age boundary is inclusive at freshnessDays', () => {
100
+ const exact = freshnessSignals({ updatedAt: new Date(NOW.getTime() - 30 * DAY_MS).toISOString() }, { now: NOW })
101
+ assert.equal(exact.stale, true)
102
+ assert.deepEqual(exact.reasons, ['age-days:30'])
103
+
104
+ const justUnder = freshnessSignals({ updatedAt: new Date(NOW.getTime() - (30 * DAY_MS - 1)).toISOString() }, { now: NOW })
105
+ assert.deepEqual(justUnder, { stale: false, reasons: [] })
106
+
107
+ assert.equal(freshnessSignals({ updatedAt: daysAgo(89) }, { now: NOW, freshnessDays: 90 }).stale, false)
108
+ assert.equal(freshnessSignals({ updatedAt: daysAgo(90) }, { now: NOW, freshnessDays: 90 }).stale, true)
109
+
110
+ // An unusable threshold falls back to 30, not to "everything is stale".
111
+ assert.equal(freshnessSignals({ updatedAt: daysAgo(31) }, { now: NOW, freshnessDays: NaN }).stale, true)
112
+ assert.equal(freshnessSignals({ updatedAt: daysAgo(29) }, { now: NOW, freshnessDays: 'nope' }).stale, false)
113
+ })
114
+
115
+ test('signals compose and the reasons list names every one of them', () => {
116
+ const all = freshnessSignals({
117
+ title: '最新价格',
118
+ content: '汇率也变了。',
119
+ salientDate: '2026-11-01',
120
+ updatedAt: daysAgo(60),
121
+ }, { now: NOW })
122
+ assert.equal(all.stale, true)
123
+ assert.deepEqual(all.reasons, [
124
+ 'dated-past:2026-11-01',
125
+ 'freshness-term:最新',
126
+ 'freshness-term:价格',
127
+ 'freshness-term:汇率',
128
+ 'age-days:60',
129
+ ])
130
+ })
131
+
132
+ test('bad entries and bad clocks never throw', () => {
133
+ for (const value of [null, undefined, 42, 'memory']) {
134
+ assert.deepEqual(freshnessSignals(value), { stale: false, reasons: [] })
135
+ }
136
+ for (const now of [NaN, 'not-a-date', new Date(NaN)]) {
137
+ const result = freshnessSignals({ updatedAt: '2000-01-01T00:00:00Z' }, { now })
138
+ assert.equal(result.stale, true, `now=${String(now)} must fall back to the wall clock`)
139
+ }
140
+ })
@@ -165,8 +165,7 @@ test('getGraph hides orphan entities by default and reveals them on includeOrpha
165
165
  graph.deleteEntity({ libraryId, entityId: lonely.id })
166
166
  })
167
167
 
168
- test('apply() schedules the sweep late, and a corrupt store only warns instead of blocking load', async () => {
169
- const badLib = state.ensureSession('sweep-bad', { cwd: path.join(home, 'ws-bad'), agentPreset: 'coding' }).libraryId
168
+ test('apply() schedules the sweep late, and a corrupt store only warns instead of blocking load', async () => { const badLib = state.ensureSession('sweep-bad', { cwd: path.join(home, 'ws-bad'), agentPreset: 'coding' }).libraryId
170
169
  fs.writeFileSync(path.join(indexDir(), `${badLib}.entities.json`), '{ still not json')
171
170
  const info = []
172
171
  const warn = []
@@ -188,3 +187,37 @@ test('apply() schedules the sweep late, and a corrupt store only warns instead o
188
187
  assert.ok(warn.some(message => message.includes(`orphan entity sweep skipped ${badLib}`)), 'the sweep reports the corrupt library')
189
188
  assert.equal(warn.some(message => message.includes('orphan entity sweep failed')), false, 'per-library failures stay contained')
190
189
  })
190
+
191
+ // ---- §6.4 包 D:linked 派生字段与删除路径的一致性 ----
192
+ // 只有 relationship、没有 memory link 的实体是历史,不是孤儿——linked 必须为
193
+ // true,启动 prune 也必须放行它;判定口径与 pruneOrphanEntities 完全一致。
194
+
195
+ test('a relationship-only entity is linked, not an orphan, and prune agrees', () => {
196
+ const soloA = graph.createEntity({ libraryId, name: 'RelOnlyA' })
197
+ const soloB = graph.createEntity({ libraryId, name: 'RelOnlyB' })
198
+ graph.updateRelationship({ libraryId, fromId: soloA.id, toId: soloB.id, state: { familiarity: 0.4 }, evidenceIds: ['mem-free'], reason: 'The free scene is explicit evidence.' })
199
+ const rows = graph.listEntities({ libraryId }).items
200
+ const rowA = rows.find(entity => entity.id === soloA.id)
201
+ const rowB = rows.find(entity => entity.id === soloB.id)
202
+ assert.ok(rowA && rowB, 'no session means the pair comes back with everyone else')
203
+ assert.equal(rowA.linked, true, 'a snapshot endpoint is a reference even without any memory link')
204
+ assert.equal(rowB.linked, true)
205
+ const pruned = graph.pruneOrphanEntities(libraryId)
206
+ assert.ok(!pruned.removed.includes(soloA.id) && !pruned.removed.includes(soloB.id),
207
+ 'the prune must share the linked judgement, never collect snapshot-referenced entities')
208
+ })
209
+
210
+ test('the linked flag tracks a refused delete through force, and cleanup drops the row', () => {
211
+ const kept = graph.createEntity({ libraryId, name: 'FlagKept' })
212
+ graph.linkEntries({ libraryId, fromId: 'mem-free', toId: kept.id, kind: 'person', note: 'FlagKept is the person this scene is about.' })
213
+ let row = graph.listEntities({ libraryId }).items.find(entity => entity.id === kept.id)
214
+ assert.equal(row.linked, true, 'an inbound link shows up as linked before any delete')
215
+ assert.throws(() => graph.deleteEntity({ libraryId, entityId: kept.id }), /still referenced/, 'the refusal keeps both the row and its link')
216
+ assert.ok(graph.listEntities({ libraryId }).items.some(entity => entity.id === kept.id))
217
+ const forced = graph.deleteEntity({ libraryId, entityId: kept.id, force: true })
218
+ assert.equal(forced.deleted, true)
219
+ assert.equal(forced.removedLinks, 1, 'force sweeps the inbound link')
220
+ assert.ok(state.loadPrivateIndex(libraryId).entries['mem-free'].links.every(link => link.to !== kept.id), 'the forced delete sweeps the inbound link of this entity')
221
+ row = graph.listEntities({ libraryId }).items.find(entity => entity.id === kept.id)
222
+ assert.equal(row, undefined, 'after the force delete the entity is gone from the listing too')
223
+ })
@@ -49,6 +49,44 @@ test('invalid kinds, empty reasons and out-of-scope private links are rejected',
49
49
  assert.ok(!JSON.stringify(graph.getGraph({ exec })).includes('private title'))
50
50
  })
51
51
 
52
+ test('an explicit link source persists on the record and surfaces on graph edges', () => {
53
+ state.updatePrivateIndex(libraryId, index => {
54
+ index.entries['mem-src-a'] = { title: 'alpha note', content: 'alpha body', status: 'active', visibility: 'shared' }
55
+ index.entries['mem-src-b'] = { title: 'beta note', content: 'beta body', status: 'active', visibility: 'shared' }
56
+ index.entries['mem-src-c'] = { title: 'gamma note', content: 'gamma body', status: 'active', visibility: 'shared' }
57
+ })
58
+ const linked = graph.linkEntries({
59
+ libraryId, fromId: 'mem-src-a', toId: 'mem-src-b', kind: 'relation',
60
+ note: 'Auto-linked because both memories share the stable name Alpha.', source: 'auto',
61
+ })
62
+ assert.equal(linked.source, 'auto')
63
+ const stored = () => state.loadPrivateIndex(libraryId).entries['mem-src-a'].links
64
+ assert.equal(stored().find(link => link.to === 'mem-src-b').source, 'auto', 'auto is persisted, not only returned')
65
+
66
+ // Replacement stays idempotent and the source survives the rewrite.
67
+ graph.linkEntries({
68
+ libraryId, fromId: 'mem-src-a', toId: 'mem-src-b', kind: 'relation',
69
+ note: 'Re-linked after a rerun with the same evidence.', source: 'auto',
70
+ })
71
+ const replaced = stored().filter(link => link.to === 'mem-src-b')
72
+ assert.equal(replaced.length, 1, 'the same (to, kind) pair is replaced in place')
73
+ assert.equal(replaced[0].source, 'auto')
74
+
75
+ // Only auto/user are meaningful; anything else is omitted rather than stored.
76
+ graph.linkEntries({
77
+ libraryId, fromId: 'mem-src-b', toId: 'mem-src-c', kind: 'event',
78
+ note: 'The same event seen from another side.', source: 'robot',
79
+ })
80
+ assert.equal(state.loadPrivateIndex(libraryId).entries['mem-src-b'].links[0].source, undefined)
81
+
82
+ const view = graph.getGraph({ libraryId, focusId: 'mem-src-b', depth: 1 })
83
+ const autoEdge = view.edges.find(edge => edge.from === 'mem-src-a' && edge.to === 'mem-src-b')
84
+ assert.equal(autoEdge.source, 'auto', 'the UI can tag an auto link')
85
+ assert.equal(autoEdge.kind, 'relation', 'link semantics are unchanged')
86
+ const plainEdge = view.edges.find(edge => edge.from === 'mem-src-b')
87
+ assert.equal(plainEdge.source, null, 'a link without a source reports null, not undefined')
88
+ })
89
+
52
90
  test('graphs cap nodes at 200 and the recall carries at most two pointers', async () => {
53
91
  state.updatePrivateIndex(libraryId, index => {
54
92
  for (let i = 10; i < 400; i++) index.entries[`mem-${i}`] = { title: `node ${i}`, status: 'active', content: 'node' }
@@ -92,3 +130,61 @@ test('a dangling edge is reported as missing, matching the graph view placeholde
92
130
  const healthy = graph.recallRelations(libraryId, state.loadPrivateIndex(libraryId), 'mem-2', null)
93
131
  assert.equal(healthy.find(item => item.id === zhou.id).missing, false)
94
132
  })
133
+
134
+ // ---- §6.4 包 D:listEntities 的 linked 派生字段与孤立判定 ----
135
+ // 前提(合并稿 0.2 纠正):无 session 本来就返回全部实体——不"放开过滤",
136
+ // 只加 linked 标记;有 session 才按可见引用收窄。
137
+
138
+ test('listEntities: without a session every entity returns, with a correct derived linked flag', () => {
139
+ const binding = state.ensureSession('vis-all', { cwd: path.join(home, 'ws-vis-all'), agentPreset: 'rp' })
140
+ const lib = binding.libraryId
141
+ const anchored = graph.createEntity({ libraryId: lib, name: 'Anchored' })
142
+ const drifting = graph.createEntity({ libraryId: lib, name: 'Drifting' })
143
+ state.savePrivateIndex(lib, { entries: {
144
+ 'mem-anchored': { title: 'anchored', content: 'scene', layer: 'long_term', status: 'active', visibility: 'shared',
145
+ links: [{ to: anchored.id, kind: 'person', note: 'Anchored is the person this scene is about.', confidence: 0.9 }] },
146
+ } })
147
+ const all = graph.listEntities({ libraryId: lib })
148
+ assert.equal(all.items.length, 2, 'without a session the full entity list comes back')
149
+ assert.equal(all.total, 2)
150
+ const anchoredRow = all.items.find(entity => entity.id === anchored.id)
151
+ const driftingRow = all.items.find(entity => entity.id === drifting.id)
152
+ assert.equal(anchoredRow.linked, true, 'a link target is linked')
153
+ assert.equal(driftingRow.linked, false, 'an entity nothing points at is unlinked')
154
+ // linked 是运行时派生字段:实体文件里绝不出现它,启动 prune 的判定不受污染。
155
+ assert.equal(graph.graphExport(lib).entities[drifting.id].linked, undefined, 'the derived flag is never written back')
156
+ })
157
+
158
+ test('listEntities: with a session only visible references count, and relationship evidence is session-filtered too', () => {
159
+ const binding = state.ensureSession('vis-scoped', { cwd: path.join(home, 'ws-vis-scoped'), agentPreset: 'rp' })
160
+ const lib = binding.libraryId
161
+ const exec = { agent: { session: { header: { id: 'vis-scoped' } } } }
162
+ const linked = graph.createEntity({ libraryId: lib, name: 'Linked' })
163
+ const secretTarget = graph.createEntity({ libraryId: lib, name: 'SecretTarget' })
164
+ const relVisible = graph.createEntity({ libraryId: lib, name: 'RelVisible' })
165
+ const relHidden = graph.createEntity({ libraryId: lib, name: 'RelHidden' })
166
+ const lonely = graph.createEntity({ libraryId: lib, name: 'Lonely' })
167
+ state.savePrivateIndex(lib, { entries: {
168
+ 'mem-open': { title: 'open', content: 'open scene', layer: 'long_term', status: 'active', visibility: 'shared',
169
+ links: [{ to: linked.id, kind: 'person', note: 'Linked is the person this scene is about.', confidence: 0.9 }] },
170
+ 'mem-hidden': { title: 'hidden', content: 'secret scene', layer: 'long_term', status: 'active', visibility: 'secret', context: { characterId: 'other' },
171
+ links: [{ to: secretTarget.id, kind: 'person', note: 'Secret is the person this scene is about.', confidence: 0.9 }] },
172
+ } })
173
+ // 关系快照也算引用:evidence 指向本会话可见记忆的算,指不可见记忆的不算。
174
+ graph.updateRelationship({ libraryId: lib, fromId: linked.id, toId: relVisible.id, state: { trust: 0.5 }, evidenceIds: ['mem-open'], reason: 'The open scene is explicit evidence.' })
175
+ graph.updateRelationship({ libraryId: lib, fromId: secretTarget.id, toId: relHidden.id, state: { trust: 0.5 }, evidenceIds: ['mem-hidden'], reason: 'The hidden scene is the only evidence here.' })
176
+ const scoped = graph.listEntities({ exec, libraryId: lib })
177
+ const ids = scoped.items.map(entity => entity.id).sort()
178
+ assert.deepEqual(ids, [linked.id, relVisible.id].sort(),
179
+ 'a visible entry link and a relationship with visible evidence both count; secret-referenced and orphan entities do not')
180
+ assert.ok(scoped.items.every(entity => entity.linked === true), 'every session-visible row is linked by construction')
181
+ // 无 session:全量计入(两条快照都算引用),Linked/RelVisible/SecretTarget/RelHidden
182
+ // 都是 linked=true,只有 Lonely 是孤立。
183
+ const all = graph.listEntities({ libraryId: lib })
184
+ assert.equal(all.items.length, 5, 'no session means every entity, referenced or not')
185
+ const linkedMap = Object.fromEntries(all.items.map(entity => [entity.id, entity.linked]))
186
+ for (const entity of [linked, relVisible, secretTarget, relHidden]) {
187
+ assert.equal(linkedMap[entity.id], true, `${entity.name} is referenced and must not be misjudged as an orphan`)
188
+ }
189
+ assert.equal(linkedMap[lonely.id], false, 'the untouched entity stays unlinked')
190
+ })