dsh-memu-memory 1.4.3 → 1.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +3 -1
- package/CHANGELOG.md +15 -0
- package/README.md +34 -15
- package/README.zh.md +35 -13
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/libraries.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +19 -3
- package/docs/contributing.md +4 -2
- package/docs/env-and-commands.md +9 -1
- package/docs/graph-scale.md +214 -0
- package/docs/lexicon-recall.md +100 -0
- package/docs/mcp-porting.md +8 -6
- package/docs/memory-semantics.md +35 -3
- package/docs/pending-work.md +3 -1
- package/docs/retention.md +83 -0
- package/docs/rt-index.md +452 -0
- package/docs/scale-performance.md +101 -0
- package/docs/token-budget.md +92 -0
- package/docs/troubleshooting.md +50 -11
- package/lib/auto-link/apply.js +7 -2
- package/lib/auto-link/candidates.js +32 -10
- package/lib/backup.js +67 -32
- package/lib/binding-diagnostics.js +1 -1
- package/lib/bounded-cache.js +80 -0
- package/lib/client.js +2096 -409
- package/lib/consolidation-ledger.js +21 -4
- package/lib/consolidation-worker.js +14 -1
- package/lib/cycle.js +16 -11
- package/lib/diagnostic-context.js +372 -0
- package/lib/diagnostics.js +147 -61
- package/lib/embedding-download.js +7 -8
- package/lib/engine-sources.js +286 -0
- package/lib/engine.js +23 -10
- package/lib/entity-repair.js +43 -13
- package/lib/entity-review.js +64 -0
- package/lib/environment-check.js +348 -36
- package/lib/feedback.js +25 -0
- package/lib/global-graph.js +46 -2
- package/lib/graph-adjacency-index.js +525 -0
- package/lib/graph-overview.js +293 -0
- package/lib/graph.js +658 -105
- package/lib/inbound.js +44 -15
- package/lib/index-pages.js +57 -0
- package/lib/index.js +44 -6
- package/lib/inject.js +119 -50
- package/lib/lexicon-rt-source.js +25 -0
- package/lib/lexicon-rt-worker.js +26 -0
- package/lib/lexicon-rt.js +224 -0
- package/lib/lexicon-scope.js +56 -5
- package/lib/lexicon.js +143 -54
- package/lib/local-vector-service.js +3 -0
- package/lib/maintenance-ledger.js +542 -12
- package/lib/managed-runtime.js +260 -80
- package/lib/media.js +1 -1
- package/lib/memory.js +564 -131
- package/lib/port-surface.js +96 -11
- package/lib/preset-mount.js +13 -7
- package/lib/private.js +47 -21
- package/lib/recall-cache.js +20 -34
- package/lib/retention.js +173 -0
- package/lib/rpc.js +135 -52
- package/lib/rt-index/builder.js +209 -0
- package/lib/rt-index/format.js +231 -0
- package/lib/rt-index/manifest.js +105 -0
- package/lib/rt-index/reader.js +673 -0
- package/lib/rt-index-retention.js +151 -0
- package/lib/rt-index-service.js +283 -0
- package/lib/rt-index-worker.js +21 -0
- package/lib/salient-wake.js +55 -4
- package/lib/state.js +195 -24
- package/lib/temporal.js +39 -13
- package/lib/token-measurement.js +126 -0
- package/lib/tools.js +101 -6
- package/lib/turn-log.js +108 -3
- package/lib/webui/graph-layout-worker.js +68 -0
- package/lib/webui/graph-local-physics.js +390 -0
- package/lib/webui/graph-spatial-grid.js +64 -0
- package/lib/webui/graph-view.bundle.js +6 -1
- package/lib/webui/graph-view.js +478 -135
- package/lib/webui/graph-webgl-renderer.js +74 -0
- package/lib/webui/standalone.js +1 -1
- package/lib/worker-pool.js +38 -7
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +4 -10
- package/scripts/bench-all-libraries.mjs +47 -0
- package/scripts/check-classic-graph-browser.mjs +189 -0
- package/scripts/check-client-browser.mjs +929 -0
- package/scripts/check-graph-browser.mjs +6 -0
- package/scripts/check-graph-elastic-browser.mjs +139 -0
- package/scripts/check-memory-review-browser.mjs +124 -0
- package/scripts/entity-dedupe.mjs +19 -3
- package/scripts/graph-artifact-provenance.mjs +30 -0
- package/scripts/graph-freeze-manifest.mjs +129 -0
- package/scripts/graph-geometry-fixture.mjs +40 -0
- package/scripts/graph-physics-bench.mjs +218 -0
- package/scripts/graph-scale-bench.mjs +213 -0
- package/scripts/graph-scale-memory.mjs +48 -0
- package/scripts/graph-service-bench.mjs +72 -0
- package/scripts/make-readme-shots.mjs +17 -5
- package/scripts/preview.mjs +1 -0
- package/scripts/rebuild-rt.mjs +18 -0
- package/scripts/scale-bench.mjs +183 -0
- package/scripts/simulate-injection.mjs +47 -8
- package/scripts/verify-host-fixtures.mjs +108 -0
- package/scripts/verify-host-recovery.mjs +565 -0
- package/scripts/verify-vector-recovery.mjs +740 -0
- package/tests/auto-link-candidates.test.mjs +20 -0
- package/tests/browser.test.mjs +16 -2
- package/tests/client-export.test.mjs +16 -1
- package/tests/client-pagination.test.mjs +1495 -0
- package/tests/client-render.test.mjs +223 -28
- package/tests/consolidation-fork.test.mjs +97 -13
- package/tests/consolidation-ledger.test.mjs +17 -1
- package/tests/diagnostic-entity-candidates.test.mjs +54 -0
- package/tests/diagnostic-report.test.mjs +429 -0
- package/tests/diagnostic-wiring.test.mjs +88 -0
- package/tests/diagnostics.test.mjs +27 -0
- package/tests/embedding-download.test.mjs +44 -0
- package/tests/engine-source-settings.test.mjs +69 -0
- package/tests/engine-sources.test.mjs +145 -0
- package/tests/entity-dedupe.test.mjs +143 -0
- package/tests/entity-merge-review.test.mjs +363 -0
- package/tests/entity-merge.test.mjs +12 -4
- package/tests/entity-review.test.mjs +87 -0
- package/tests/environment-check.test.mjs +51 -1
- package/tests/feedback.test.mjs +95 -0
- package/tests/graph-adjacency-index.test.mjs +536 -0
- package/tests/graph-cascade.test.mjs +229 -0
- package/tests/graph-import-diagnostic.test.mjs +25 -0
- package/tests/graph-overview.test.mjs +709 -0
- package/tests/graph-session-authorization.test.mjs +419 -0
- package/tests/graph-view-geometry.test.mjs +426 -0
- package/tests/graph-view-scale.test.mjs +88 -0
- package/tests/graph-view.test.mjs +444 -5
- package/tests/graph.test.mjs +43 -0
- package/tests/help-page.test.mjs +128 -54
- package/tests/inbound.test.mjs +19 -0
- package/tests/index-pagination.test.mjs +113 -0
- package/tests/index-read-view.test.mjs +212 -0
- package/tests/inject-guide.test.mjs +9 -0
- package/tests/injection-dedupe.test.mjs +213 -0
- package/tests/lexicon-recall.test.mjs +641 -0
- package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
- package/tests/lexicon-rt.test.mjs +468 -0
- package/tests/local-embedding-worker.test.mjs +38 -0
- package/tests/local-vector-service.test.mjs +32 -3
- package/tests/maintenance-compat.test.mjs +128 -0
- package/tests/maintenance-settlement.test.mjs +1003 -0
- package/tests/managed-memory.test.mjs +39 -11
- package/tests/managed-runtime.test.mjs +109 -0
- package/tests/memory-fields.test.mjs +24 -12
- package/tests/observed-evidence.test.mjs +52 -0
- package/tests/port-surface.test.mjs +93 -1
- package/tests/preset-mount.test.mjs +12 -4
- package/tests/recall-cache.test.mjs +56 -3
- package/tests/recall-dedup.test.mjs +63 -2
- package/tests/retention.test.mjs +260 -0
- package/tests/rt-index-cross-library.test.mjs +230 -0
- package/tests/rt-index-integration.test.mjs +194 -0
- package/tests/rt-index-retention.test.mjs +552 -0
- package/tests/rt-index-scale.test.mjs +204 -0
- package/tests/rt-index.test.mjs +705 -0
- package/tests/salient-date-boundaries.test.mjs +121 -0
- package/tests/salient-wake.test.mjs +29 -0
- package/tests/scale-bench.test.mjs +53 -0
- package/tests/settings-plumbing.test.mjs +25 -0
- package/tests/simulate-injection.test.mjs +15 -1
- package/tests/standalone-navigation.test.mjs +44 -0
- package/tests/state.test.mjs +51 -0
- package/tests/temporal-precision.test.mjs +102 -0
- package/tests/temporal.test.mjs +10 -6
- package/tests/token-measurement.test.mjs +98 -0
- package/tests/tool-schema.test.mjs +41 -5
- package/tests/tools.test.mjs +6 -3
- package/tests/turn-token-budget.test.mjs +149 -0
- package/tests/webui-auth.test.mjs +57 -1
- package/tests/webui.test.mjs +40 -15
- package/tests/worker-lifecycle.test.mjs +2 -1
package/lib/graph.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import fs from 'node:fs'
|
|
2
2
|
import path from 'node:path'
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { createHash } from 'node:crypto'
|
|
4
|
+
import { indexDir, readJsonStrict, readFailure, writeJson, withFileLock, stamp, warn, redactSecrets } from './paths.js'
|
|
5
|
+
import { loadPrivateIndex, readPrivateIndex, indexReadRevision, updatePrivateIndex, newMemoryId, listLibraries } from './state.js'
|
|
5
6
|
import { resolveLibrary, sessionIdOf, visibleToSession, isMemoryEligible, decayStrength } from './memory.js'
|
|
6
7
|
import { record } from './activity-log.js'
|
|
7
8
|
// Entity merge suggestions reuse the exact folding rule auto-linking already
|
|
@@ -13,6 +14,8 @@ import { normalizeEntityName } from './private-links.js'
|
|
|
13
14
|
import { refreshEntityMentions } from './auto-link/apply.js'
|
|
14
15
|
import { addSuppression, suppressionSet } from './auto-link/suppression.js'
|
|
15
16
|
import { ENTITY_STATUS } from './auto-link/policy.js'
|
|
17
|
+
import { cachedGraphOverview, cachedGraphRelations } from './graph-overview.js'
|
|
18
|
+
import { getGraphAdjacency } from './graph-adjacency-index.js'
|
|
16
19
|
|
|
17
20
|
export const LINK_KINDS = ['relation', 'commitment', 'event', 'person', 'conflict', 'supersede']
|
|
18
21
|
const ENTITY_KINDS = ['person', 'place', 'thing', 'org']
|
|
@@ -66,15 +69,65 @@ function readEntities(libraryId) {
|
|
|
66
69
|
}
|
|
67
70
|
|
|
68
71
|
function scopeFor(args) { return resolveLibrary({ ...args, readOnly: true }) }
|
|
69
|
-
function allowed(entry, exec) {
|
|
70
|
-
return !sessionIdOf(exec) || (isMemoryEligible(entry, { automatic: true }) && visibleToSession(entry, sessionIdOf(exec)))
|
|
72
|
+
function allowed(entry, exec, binding = undefined) {
|
|
73
|
+
return !sessionIdOf(exec) || (isMemoryEligible(entry, { automatic: true }) && visibleToSession(entry, sessionIdOf(exec), binding))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function visibleEntityIds({ exec, sessionId = sessionIdOf(exec), binding, index, entities, relationships = {} }) {
|
|
77
|
+
if (!sessionId) return new Set(Object.keys(entities || {}))
|
|
78
|
+
const visible = new Set(Object.values(entities || {}).filter(entity => entity?.createdBySession === sessionId).map(entity => entity.id))
|
|
79
|
+
const hiddenReferences = new Set()
|
|
80
|
+
for (const entry of Object.values(index?.entries || {})) {
|
|
81
|
+
const canRead = allowed(entry, exec, binding)
|
|
82
|
+
for (const link of entry.links || []) {
|
|
83
|
+
if (!Object.hasOwn(entities || {}, link?.to)) continue
|
|
84
|
+
if (canRead) visible.add(link.to)
|
|
85
|
+
else hiddenReferences.add(link.to)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
for (const relationship of Object.values(relationships || {})) {
|
|
89
|
+
if (!Array.isArray(relationship?.evidenceIds) || !relationship.evidenceIds.length
|
|
90
|
+
|| relationship.evidenceIds.some(id => !index?.entries?.[id] || !allowed(index.entries[id], exec, binding))) continue
|
|
91
|
+
const endpoints = [relationship.fromId, relationship.toId]
|
|
92
|
+
if (endpoints.some(id => hiddenReferences.has(id) && !visible.has(id))) continue
|
|
93
|
+
for (const id of endpoints) if (Object.hasOwn(entities || {}, id)) visible.add(id)
|
|
94
|
+
}
|
|
95
|
+
return visible
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function requireVisibleEntities({ exec, binding, index, entities, relationships, ids }) {
|
|
99
|
+
if (!sessionIdOf(exec)) return
|
|
100
|
+
const visible = visibleEntityIds({ exec, binding, index, entities, relationships })
|
|
101
|
+
if (ids.some(id => !visible.has(id))) throw new Error('unknown or inaccessible entity')
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function relationshipVisible(relationship, { exec, binding, index, entities, relationships, visibleEntities = null }) {
|
|
105
|
+
if (!relationship) return false
|
|
106
|
+
if (!sessionIdOf(exec)) return true
|
|
107
|
+
if (!Array.isArray(relationship.evidenceIds) || !relationship.evidenceIds.length) return false
|
|
108
|
+
if (relationship.evidenceIds.some(id => !index.entries[id] || !allowed(index.entries[id], exec, binding))) return false
|
|
109
|
+
const visible = visibleEntities || visibleEntityIds({ exec, binding, index, entities, relationships })
|
|
110
|
+
return visible.has(relationship.fromId) && visible.has(relationship.toId)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function relationshipForSession(relationship, { exec, binding, index, entities, relationships }) {
|
|
114
|
+
const visibleEntities = visibleEntityIds({ exec, binding, index, entities, relationships })
|
|
115
|
+
const history = (Array.isArray(relationship.history) ? relationship.history : []).filter(item => {
|
|
116
|
+
if (!Array.isArray(item?.evidenceIds) || !item.evidenceIds.length
|
|
117
|
+
|| !item.evidenceIds.every(id => index.entries[id] && allowed(index.entries[id], exec, binding))) return false
|
|
118
|
+
const fromId = item.fromId ?? relationship.fromId
|
|
119
|
+
const toId = item.toId ?? relationship.toId
|
|
120
|
+
return visibleEntities.has(fromId) && visibleEntities.has(toId)
|
|
121
|
+
})
|
|
122
|
+
return { ...relationship, history }
|
|
71
123
|
}
|
|
72
124
|
|
|
73
125
|
/**
|
|
74
126
|
* Entity listing with the derived `linked` flag. The visibility rule
|
|
75
|
-
* is unchanged: without a session every entity
|
|
76
|
-
*
|
|
77
|
-
*
|
|
127
|
+
* is unchanged: management without a session can see every entity; a session
|
|
128
|
+
* sees entities linked from visible memories or supported by visible-evidence
|
|
129
|
+
* relationship snapshots, unless hidden memories also reference that entity.
|
|
130
|
+
* What is new is the classification:
|
|
78
131
|
* * `linked` = referenced by an entry's links[] OR by a relationship snapshot.
|
|
79
132
|
* A snapshot counts — an entity with only a relationship and no memory link
|
|
80
133
|
* is history, not an orphan, and must not be misjudged as one.
|
|
@@ -83,28 +136,31 @@ function allowed(entry, exec) {
|
|
|
83
136
|
* counts (there is nobody to hide it from).
|
|
84
137
|
* `linked` is derived on the fly and never written back to the entities file —
|
|
85
138
|
* the startup prune (pruneOrphanEntitiesAll) stays the sole collector.
|
|
139
|
+
* Optional entityId limits the response to one exact authorized row. It never
|
|
140
|
+
* bypasses reference visibility or broadens the caller's library scope.
|
|
86
141
|
*/
|
|
87
142
|
export function listEntities(args) {
|
|
88
143
|
const scope = scopeFor(args)
|
|
144
|
+
const entityId = args?.entityId
|
|
145
|
+
if (entityId !== undefined && (typeof entityId !== 'string' || !entityId.trim() || entityId.length > 256)) throw new Error('entityId must contain 1-256 characters')
|
|
89
146
|
const store = readEntities(scope.libraryId)
|
|
90
147
|
const index = loadPrivateIndex(scope.libraryId)
|
|
91
148
|
const sessionId = sessionIdOf(args.exec)
|
|
149
|
+
const visibleEntities = visibleEntityIds({ exec: args.exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships })
|
|
92
150
|
const linked = new Set()
|
|
93
151
|
for (const entry of Object.values(index.entries)) {
|
|
94
152
|
if (!allowed(entry, args.exec)) continue
|
|
95
|
-
for (const link of entry.links || []) linked.add(link.to)
|
|
153
|
+
for (const link of entry.links || []) if (Object.hasOwn(store.entities, link?.to)) linked.add(link.to)
|
|
96
154
|
}
|
|
97
155
|
for (const rel of Object.values(store.relationships || {})) {
|
|
98
|
-
if (sessionId)
|
|
99
|
-
const evidenceVisible = (Array.isArray(rel?.evidenceIds) ? rel.evidenceIds : [])
|
|
100
|
-
.some(id => { const entry = index.entries[id]; return Boolean(entry) && allowed(entry, args.exec) })
|
|
101
|
-
if (!evidenceVisible) continue
|
|
102
|
-
}
|
|
156
|
+
if (sessionId && !relationshipVisible(rel, { exec: args.exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships, visibleEntities })) continue
|
|
103
157
|
if (rel?.fromId) linked.add(rel.fromId)
|
|
104
158
|
if (rel?.toId) linked.add(rel.toId)
|
|
105
159
|
}
|
|
106
|
-
const
|
|
107
|
-
.
|
|
160
|
+
const selected = entityId === undefined ? Object.values(store.entities)
|
|
161
|
+
: Object.hasOwn(store.entities, entityId) ? [store.entities[entityId]] : []
|
|
162
|
+
const items = selected
|
|
163
|
+
.filter(entity => !sessionId || visibleEntities.has(entity.id))
|
|
108
164
|
.map(entity => ({
|
|
109
165
|
...entity,
|
|
110
166
|
// Legacy rows have no status; they read as provisional, never confirmed.
|
|
@@ -116,7 +172,9 @@ export function listEntities(args) {
|
|
|
116
172
|
|
|
117
173
|
export function graphExport(libraryId) {
|
|
118
174
|
const scope = scopeFor({ libraryId })
|
|
119
|
-
|
|
175
|
+
const { mergeRejections, mergeHolds, ...graph } = readEntities(scope.libraryId)
|
|
176
|
+
// Review decisions belong to this library; whole-home backups preserve them.
|
|
177
|
+
return graph
|
|
120
178
|
}
|
|
121
179
|
|
|
122
180
|
/**
|
|
@@ -131,7 +189,15 @@ export function restoreGraphData(libraryId, data, memoryIdMap, { origin = null }
|
|
|
131
189
|
const scope = scopeFor({ libraryId })
|
|
132
190
|
const entityMap = {}
|
|
133
191
|
const createdEntityIds = []
|
|
134
|
-
|
|
192
|
+
const entities = Object.entries(data.entities)
|
|
193
|
+
if (entities.length > 2000) {
|
|
194
|
+
// Import's existing cap remains; report counts without entity names/bodies.
|
|
195
|
+
const detail = { code: 'GRAPH_IMPORT_TRUNCATED', received: entities.length, limit: 2000, dropped: entities.length - 2000 }
|
|
196
|
+
warn(`graph import truncated: ${detail.received} entities exceed limit ${detail.limit}; ${detail.dropped} skipped`)
|
|
197
|
+
record({ kind: 'system', level: 'warn', ok: false, scope: 'private', libraryId: scope.libraryId,
|
|
198
|
+
message: '图谱导入超过实体上限,部分实体未导入', detail })
|
|
199
|
+
}
|
|
200
|
+
for (const [oldId, entity] of entities.slice(0, 2000)) {
|
|
135
201
|
if (!/^ent[-_][a-z0-9_-]+$/i.test(oldId)) continue
|
|
136
202
|
// An import is a user action: rows without a status come back confirmed, and
|
|
137
203
|
// an explicit status travels with the backup unchanged.
|
|
@@ -213,13 +279,18 @@ export function createEntity({ exec, libraryId, name, kind = 'person', aliases =
|
|
|
213
279
|
const file = entitiesPath(scope.libraryId)
|
|
214
280
|
return withFileLock(file, () => {
|
|
215
281
|
const store = readEntities(scope.libraryId)
|
|
216
|
-
const
|
|
282
|
+
const sessionId = sessionIdOf(exec)
|
|
283
|
+
const index = sessionId ? loadPrivateIndex(scope.libraryId) : null
|
|
284
|
+
const visible = sessionId ? visibleEntityIds({ exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships }) : null
|
|
285
|
+
const existing = Object.values(store.entities).find(entity => entity.name === clean && entity.kind === kind
|
|
286
|
+
&& (!visible || visible.has(entity.id)))
|
|
217
287
|
if (existing) return existing
|
|
218
288
|
const id = newMemoryId('ent')
|
|
219
289
|
const at = stamp()
|
|
220
290
|
const entity = {
|
|
221
291
|
id, name: clean, kind, aliases: normalizeAliases(aliases), status,
|
|
222
292
|
createdAt: at, updatedAt: at,
|
|
293
|
+
...(sessionId ? { createdBySession: sessionId } : {}),
|
|
223
294
|
...(origin ? { origin: String(origin) } : {}),
|
|
224
295
|
...(status === 'confirmed' ? { confirmedAt: at, confirmedBy: String(confirmedBy || 'user') } : {}),
|
|
225
296
|
}
|
|
@@ -248,6 +319,8 @@ export function confirmEntities({ exec, libraryId, entityIds, by = 'user' }) {
|
|
|
248
319
|
const refreshTargets = []
|
|
249
320
|
withFileLock(file, () => {
|
|
250
321
|
const store = readEntities(scope.libraryId)
|
|
322
|
+
const index = loadPrivateIndex(scope.libraryId)
|
|
323
|
+
requireVisibleEntities({ exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships, ids })
|
|
251
324
|
const at = stamp()
|
|
252
325
|
for (const id of ids) {
|
|
253
326
|
const entity = store.entities[id]
|
|
@@ -269,7 +342,7 @@ export function confirmEntities({ exec, libraryId, entityIds, by = 'user' }) {
|
|
|
269
342
|
let entities = 0
|
|
270
343
|
for (const entity of refreshTargets) {
|
|
271
344
|
try {
|
|
272
|
-
const result = refreshEntityMentions({ libraryId: scope.libraryId, entity, suppression })
|
|
345
|
+
const result = refreshEntityMentions({ libraryId: scope.libraryId, entity, suppression, sessionId: sessionIdOf(exec) })
|
|
273
346
|
entities += result.added + result.updated
|
|
274
347
|
} catch (error) {
|
|
275
348
|
warn(`mention refresh after entity confirmation skipped: ${error?.message || error}`)
|
|
@@ -329,13 +402,15 @@ function normalizeAliases(aliases) {
|
|
|
329
402
|
return [...new Set(aliases.map(alias => alias.trim()).filter(Boolean))].slice(0, 30).map(alias => alias.slice(0, 120))
|
|
330
403
|
}
|
|
331
404
|
|
|
332
|
-
export function renameEntity({ libraryId, entityId, name, aliases = [] }) {
|
|
333
|
-
const scope = scopeFor({ libraryId })
|
|
405
|
+
export function renameEntity({ exec, libraryId, entityId, name, aliases = [] }) {
|
|
406
|
+
const scope = scopeFor({ exec, libraryId })
|
|
334
407
|
const clean = String(name || '').trim()
|
|
335
408
|
if (!clean || clean.length > 120) throw new Error('entity name must contain 1-120 characters')
|
|
336
409
|
const file = entitiesPath(scope.libraryId)
|
|
337
410
|
const entity = withFileLock(file, () => {
|
|
338
411
|
const store = readEntities(scope.libraryId)
|
|
412
|
+
const index = loadPrivateIndex(scope.libraryId)
|
|
413
|
+
requireVisibleEntities({ exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships, ids: [entityId] })
|
|
339
414
|
const row = store.entities[entityId]
|
|
340
415
|
if (!row) throw new Error('unknown entity')
|
|
341
416
|
row.name = clean
|
|
@@ -350,7 +425,7 @@ export function renameEntity({ libraryId, entityId, name, aliases = [] }) {
|
|
|
350
425
|
let suppression = null
|
|
351
426
|
try { suppression = suppressionSet(scope.libraryId) } catch {}
|
|
352
427
|
try {
|
|
353
|
-
refreshEntityMentions({ libraryId: scope.libraryId, entity, suppression, operation: 'auto-link-rename' })
|
|
428
|
+
refreshEntityMentions({ libraryId: scope.libraryId, entity, suppression, sessionId: sessionIdOf(exec), operation: 'auto-link-rename' })
|
|
354
429
|
} catch (error) {
|
|
355
430
|
warn(`mention refresh after entity rename skipped: ${error?.message || error}`)
|
|
356
431
|
}
|
|
@@ -443,13 +518,18 @@ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
|
|
|
443
518
|
if (!entityId || typeof entityId !== 'string') throw new Error('entityId is required')
|
|
444
519
|
const file = entitiesPath(scope.libraryId)
|
|
445
520
|
const removedAuto = []
|
|
446
|
-
const result = withFileLock(file, () => {
|
|
521
|
+
const result = withFileLock(file, () => withFileLock(path.join(indexDir(), `${scope.libraryId}.json`), () => {
|
|
447
522
|
const store = readEntities(scope.libraryId)
|
|
448
|
-
if (!store.entities[entityId]) throw new Error('unknown entity')
|
|
449
523
|
const index = loadPrivateIndex(scope.libraryId)
|
|
524
|
+
requireVisibleEntities({ exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships, ids: [entityId] })
|
|
525
|
+
if (!store.entities[entityId]) throw new Error(sessionIdOf(exec) ? 'unknown or inaccessible entity' : 'unknown entity')
|
|
450
526
|
let inbound = 0
|
|
527
|
+
let inaccessibleInbound = false
|
|
451
528
|
for (const entry of Object.values(index.entries || {})) {
|
|
452
|
-
for (const link of entry.links || []) if (link.to === entityId)
|
|
529
|
+
for (const link of entry.links || []) if (link.to === entityId) {
|
|
530
|
+
inbound += 1
|
|
531
|
+
if (sessionIdOf(exec) && !allowed(entry, exec, scope.binding)) inaccessibleInbound = true
|
|
532
|
+
}
|
|
453
533
|
}
|
|
454
534
|
// 关系快照的 key 是 JSON.stringify([fromId, toId])。旧数据、备份恢复或手写
|
|
455
535
|
// 导入都可能带非 JSON key——这里必须和 mergeEntities 同口径地跳过损坏 key,
|
|
@@ -463,6 +543,11 @@ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
|
|
|
463
543
|
const [from, to] = endpoints
|
|
464
544
|
return from === entityId || to === entityId
|
|
465
545
|
})
|
|
546
|
+
if (sessionIdOf(exec)) {
|
|
547
|
+
if (inaccessibleInbound || relationshipKeys.some(key => !relationshipVisible(store.relationships[key], {
|
|
548
|
+
exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships,
|
|
549
|
+
}))) throw new Error('entity has inaccessible references')
|
|
550
|
+
}
|
|
466
551
|
if ((inbound || relationshipKeys.length) && !force) {
|
|
467
552
|
const parts = []
|
|
468
553
|
if (inbound) parts.push(`${inbound} link(s) point at it`)
|
|
@@ -474,6 +559,7 @@ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
|
|
|
474
559
|
updatePrivateIndex(scope.libraryId, fresh => {
|
|
475
560
|
for (const [fromId, entry] of Object.entries(fresh.entries)) {
|
|
476
561
|
if (!Array.isArray(entry.links) || !entry.links.some(link => link.to === entityId)) continue
|
|
562
|
+
if (sessionIdOf(exec) && !allowed(entry, exec, scope.binding)) throw new Error('entity has inaccessible references')
|
|
477
563
|
const kept = entry.links.filter(link => {
|
|
478
564
|
if (link.to !== entityId) return true
|
|
479
565
|
if (link.source === 'auto') {
|
|
@@ -493,7 +579,7 @@ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
|
|
|
493
579
|
delete store.entities[entityId]
|
|
494
580
|
writeJson(file, store)
|
|
495
581
|
return { entityId, deleted: true, removedLinks, removedRelationships: relationshipKeys.length }
|
|
496
|
-
})
|
|
582
|
+
}))
|
|
497
583
|
// Revoking an entity must not let the next consolidation resurrect its auto
|
|
498
584
|
// edges; the exact edge keys go into the suppression table.
|
|
499
585
|
if (removedAuto.length) {
|
|
@@ -522,7 +608,7 @@ export function deleteEntity({ exec, libraryId, entityId, force = false }) {
|
|
|
522
608
|
* snapshots are re-keyed on the target; an existing target-side snapshot wins
|
|
523
609
|
* and the discarded source key is reported in `relationships.conflicts`.
|
|
524
610
|
*/
|
|
525
|
-
export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
|
|
611
|
+
export function mergeEntities({ exec, libraryId, targetId, sourceIds, reviewToken } = {}) {
|
|
526
612
|
const scope = scopeFor({ exec, libraryId })
|
|
527
613
|
if (typeof targetId !== 'string' || !targetId.trim()) throw new Error('targetId is required')
|
|
528
614
|
const target = targetId.trim()
|
|
@@ -541,20 +627,50 @@ export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
|
|
|
541
627
|
const file = entitiesPath(scope.libraryId)
|
|
542
628
|
let targetName = target
|
|
543
629
|
let mergedEntity = null
|
|
544
|
-
const result = withFileLock(file, () => {
|
|
630
|
+
const result = withFileLock(file, () => withFileLock(path.join(indexDir(), `${scope.libraryId}.json`), () => {
|
|
545
631
|
const store = readEntities(scope.libraryId)
|
|
632
|
+
const index = loadPrivateIndex(scope.libraryId)
|
|
633
|
+
requireVisibleEntities({ exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships, ids: [target, ...sources] })
|
|
546
634
|
const targetEntity = store.entities[target]
|
|
547
|
-
if (!targetEntity || typeof targetEntity !== 'object') throw new Error(`unknown entity: ${target}`)
|
|
635
|
+
if (!targetEntity || typeof targetEntity !== 'object') throw new Error(sessionIdOf(exec) ? 'unknown or inaccessible entity' : `unknown entity: ${target}`)
|
|
548
636
|
targetName = String(targetEntity.name || target)
|
|
549
637
|
const sourceEntities = []
|
|
550
638
|
for (const id of sources) {
|
|
551
639
|
const entity = store.entities[id]
|
|
552
|
-
if (!entity || typeof entity !== 'object') throw new Error(`unknown entity: ${id}`)
|
|
640
|
+
if (!entity || typeof entity !== 'object') throw new Error(sessionIdOf(exec) ? 'unknown or inaccessible entity' : `unknown entity: ${id}`)
|
|
553
641
|
if (entity.kind !== targetEntity.kind) {
|
|
554
642
|
throw new Error(`cannot merge entities of different kinds: ${targetEntity.kind || 'unknown'} vs ${entity.kind || 'unknown'}`)
|
|
555
643
|
}
|
|
556
644
|
sourceEntities.push(entity)
|
|
557
645
|
}
|
|
646
|
+
if (sessionIdOf(exec)) {
|
|
647
|
+
const sourceSet = new Set(sources)
|
|
648
|
+
if (Object.values(index.entries || {}).some(entry =>
|
|
649
|
+
(entry.links || []).some(link => sourceSet.has(link?.to)) && !allowed(entry, exec, scope.binding))) {
|
|
650
|
+
throw new Error('entities have inaccessible references')
|
|
651
|
+
}
|
|
652
|
+
if (Object.values(store.relationships || {}).some(relationship =>
|
|
653
|
+
(sourceSet.has(relationship?.fromId) || sourceSet.has(relationship?.toId))
|
|
654
|
+
&& !relationshipVisible(relationship, { exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships }))) {
|
|
655
|
+
throw new Error('entities have inaccessible references')
|
|
656
|
+
}
|
|
657
|
+
for (const [key, relationship] of Object.entries(store.relationships || {})) {
|
|
658
|
+
if (!relationship || typeof relationship !== 'object') continue
|
|
659
|
+
let endpoints
|
|
660
|
+
try { endpoints = JSON.parse(key) } catch { continue }
|
|
661
|
+
if (!Array.isArray(endpoints) || endpoints.length !== 2 || !endpoints.some(id => sourceSet.has(id))) continue
|
|
662
|
+
const next = endpoints.map(id => sourceSet.has(id) ? target : id)
|
|
663
|
+
if (next[0] === next[1]) continue
|
|
664
|
+
const existing = store.relationships[JSON.stringify(next)]
|
|
665
|
+
if (existing && !relationshipVisible(existing, {
|
|
666
|
+
exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships,
|
|
667
|
+
})) throw new Error('entities have inaccessible references')
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
if (reviewToken !== undefined) {
|
|
671
|
+
if (sourceEntities.length !== 1) throw new Error('a candidate review token requires exactly one source entity')
|
|
672
|
+
assertMergeReviewToken(scope.libraryId, mergeReviewRow(sourceEntities[0]), mergeReviewRow(targetEntity), reviewToken)
|
|
673
|
+
}
|
|
558
674
|
|
|
559
675
|
// Union of names: the target's own name stays the display name, every
|
|
560
676
|
// source name becomes an alias, and the shared normalizer trims, dedupes
|
|
@@ -571,6 +687,10 @@ export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
|
|
|
571
687
|
let remappedLinks = 0
|
|
572
688
|
let duplicateLinks = 0
|
|
573
689
|
updatePrivateIndex(scope.libraryId, index => {
|
|
690
|
+
if (sessionIdOf(exec) && Object.values(index.entries || {}).some(entry =>
|
|
691
|
+
(entry.links || []).some(link => sourceSet.has(link?.to)) && !allowed(entry, exec, scope.binding))) {
|
|
692
|
+
throw new Error('entities have inaccessible references')
|
|
693
|
+
}
|
|
574
694
|
for (const entry of Object.values(index.entries || {})) {
|
|
575
695
|
const links = Array.isArray(entry.links) ? entry.links : null
|
|
576
696
|
if (!links || !links.some(link => link && sourceSet.has(link.to))) continue
|
|
@@ -621,16 +741,18 @@ export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
|
|
|
621
741
|
if (!sourceSet.has(fromId) && !sourceSet.has(toId)) continue
|
|
622
742
|
const nextFrom = sourceSet.has(fromId) ? target : fromId
|
|
623
743
|
const nextTo = sourceSet.has(toId) ? target : toId
|
|
624
|
-
delete store.relationships[key]
|
|
625
744
|
if (nextFrom === nextTo) {
|
|
745
|
+
delete store.relationships[key]
|
|
626
746
|
relationships.conflicts.push({ key, reason: 'self' })
|
|
627
747
|
continue
|
|
628
748
|
}
|
|
629
749
|
const nextKey = JSON.stringify([nextFrom, nextTo])
|
|
630
750
|
if (store.relationships[nextKey]) {
|
|
751
|
+
delete store.relationships[key]
|
|
631
752
|
relationships.conflicts.push({ key, reason: 'existing-target', keptKey: nextKey })
|
|
632
753
|
continue
|
|
633
754
|
}
|
|
755
|
+
delete store.relationships[key]
|
|
634
756
|
store.relationships[nextKey] = { ...snapshot, fromId: nextFrom, toId: nextTo }
|
|
635
757
|
relationships.moved += 1
|
|
636
758
|
}
|
|
@@ -661,7 +783,7 @@ export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
|
|
|
661
783
|
}
|
|
662
784
|
mergedEntity = targetEntity
|
|
663
785
|
return { targetId: target, merged: sources, aliases, droppedAliases, remappedLinks, duplicateLinks, relationships }
|
|
664
|
-
})
|
|
786
|
+
}))
|
|
665
787
|
|
|
666
788
|
// The merged row now owns the union of names; recompute its mention edges so
|
|
667
789
|
// citations point at the surviving entity and new aliases take effect.
|
|
@@ -670,7 +792,7 @@ export function mergeEntities({ exec, libraryId, targetId, sourceIds } = {}) {
|
|
|
670
792
|
try { suppression = suppressionSet(scope.libraryId) } catch {}
|
|
671
793
|
try {
|
|
672
794
|
result.mentionRefresh = refreshEntityMentions({
|
|
673
|
-
libraryId: scope.libraryId, entity: mergedEntity, suppression, operation: 'auto-link-merge',
|
|
795
|
+
libraryId: scope.libraryId, entity: mergedEntity, suppression, sessionId: sessionIdOf(exec), operation: 'auto-link-merge',
|
|
674
796
|
})
|
|
675
797
|
} catch (error) {
|
|
676
798
|
warn(`mention refresh after entity merge skipped: ${error?.message || error}`)
|
|
@@ -741,6 +863,182 @@ function isNameCorePair(shorter, longer) {
|
|
|
741
863
|
}
|
|
742
864
|
|
|
743
865
|
const MERGE_REASON_ORDER = { containment: 0, 'edit-distance': 1, 'name-core': 2 }
|
|
866
|
+
const MERGE_REJECTION_LIMIT = 1000
|
|
867
|
+
export const MERGE_SCAN_PAIR_LIMIT = 4096
|
|
868
|
+
|
|
869
|
+
function entityMergePair(a, b) {
|
|
870
|
+
if (a.kind !== b.kind || a.key === b.key) return null
|
|
871
|
+
const aIsLonger = a.key.length > b.key.length || (a.key.length === b.key.length && a.id < b.id)
|
|
872
|
+
const longer = aIsLonger ? a : b
|
|
873
|
+
const shorter = aIsLonger ? b : a
|
|
874
|
+
let reason = null
|
|
875
|
+
if (shorter.key.length >= 2 && longer.key.includes(shorter.key)) reason = 'containment'
|
|
876
|
+
else if (shorter.key.length >= 3 && longer.key.length - shorter.key.length <= 2
|
|
877
|
+
&& withinEditDistance(shorter.key, longer.key, 2)) reason = 'edit-distance'
|
|
878
|
+
else if (isNameCorePair(shorter.key, longer.key)) reason = 'name-core'
|
|
879
|
+
return reason ? { sourceId: shorter.id, targetId: longer.id, reason, sourceKey: shorter.key, targetKey: longer.key } : null
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
function mergeReviewIdentity(a, b) {
|
|
883
|
+
const rows = [a, b].sort((x, y) => compareText(x.id, y.id))
|
|
884
|
+
return {
|
|
885
|
+
key: JSON.stringify(rows.map(row => row.id)),
|
|
886
|
+
signature: createHash('sha256').update(JSON.stringify(rows.map(row => [row.id, row.kind, row.key]))).digest('hex'),
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
function mergeReviewToken(libraryId, signature) {
|
|
891
|
+
return createHash('sha256').update(JSON.stringify([libraryId, signature])).digest('hex')
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
function assertMergeReviewToken(libraryId, a, b, token) {
|
|
895
|
+
if (!a || !b || typeof token !== 'string' || !/^[a-f0-9]{64}$/.test(token)
|
|
896
|
+
|| token !== mergeReviewToken(libraryId, mergeReviewIdentity(a, b).signature)) {
|
|
897
|
+
throw Object.assign(new Error('entity merge candidate changed; refresh before confirming'), { code: 'ENTITY_MERGE_CANDIDATE_CHANGED' })
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
function mergeReviewRow(entity) {
|
|
902
|
+
if (!entity || typeof entity !== 'object' || typeof entity.id !== 'string') return null
|
|
903
|
+
const key = normalizeEntityName(entity.name)
|
|
904
|
+
return key ? { id: entity.id, kind: String(entity.kind || ''), key } : null
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
function currentMergeRejections(store) {
|
|
908
|
+
const valid = Object.create(null)
|
|
909
|
+
if (!store.mergeRejections || typeof store.mergeRejections !== 'object' || Array.isArray(store.mergeRejections)) return valid
|
|
910
|
+
for (const [key, record] of Object.entries(store.mergeRejections)) {
|
|
911
|
+
if (!record || typeof record !== 'object') continue
|
|
912
|
+
const a = Object.hasOwn(store.entities, record.sourceId) ? mergeReviewRow(store.entities[record.sourceId]) : null
|
|
913
|
+
const b = Object.hasOwn(store.entities, record.targetId) ? mergeReviewRow(store.entities[record.targetId]) : null
|
|
914
|
+
if (!a || !b || a.id === b.id || !entityMergePair(a, b)) continue
|
|
915
|
+
const identity = mergeReviewIdentity(a, b)
|
|
916
|
+
if (identity.key === key && identity.signature === record.signature) valid[key] = record
|
|
917
|
+
}
|
|
918
|
+
return valid
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
// Hash linked evidence once per snapshot so a hold expires when its evidence
|
|
922
|
+
// changes, without comparing every held pair against every memory again.
|
|
923
|
+
function mergeHoldEvidence(index, store) {
|
|
924
|
+
const byEntity = new Map()
|
|
925
|
+
const add = (id, row) => {
|
|
926
|
+
if (!byEntity.has(id)) byEntity.set(id, [])
|
|
927
|
+
byEntity.get(id).push(row)
|
|
928
|
+
}
|
|
929
|
+
for (const [id, entry] of Object.entries(index.entries || {})) {
|
|
930
|
+
const entities = [...new Set((entry.links || []).map(link => link?.to).filter(to => store.entities[to]))]
|
|
931
|
+
if (!entities.length) continue
|
|
932
|
+
const { title, content, status, domain, visibility, context, storyline_id, branch_id, known_by, links } = entry
|
|
933
|
+
const hash = createHash('sha256').update(JSON.stringify({ title, content, status, domain, visibility,
|
|
934
|
+
context, storyline_id, branch_id, known_by, links })).digest('hex')
|
|
935
|
+
for (const to of entities) add(to, ['memory', id, hash])
|
|
936
|
+
}
|
|
937
|
+
for (const [id, relation] of Object.entries(store.relationships || {})) {
|
|
938
|
+
const { fromId, toId, state, reason, evidenceIds, status } = relation
|
|
939
|
+
const hash = createHash('sha256').update(JSON.stringify({ fromId, toId, state, reason, evidenceIds, status })).digest('hex')
|
|
940
|
+
for (const to of new Set([relation.fromId, relation.toId])) add(to, ['relationship', id, hash])
|
|
941
|
+
}
|
|
942
|
+
return ids => {
|
|
943
|
+
const rows = new Map()
|
|
944
|
+
for (const id of ids) for (const row of byEntity.get(id) || []) rows.set(JSON.stringify(row.slice(0, 2)), row)
|
|
945
|
+
const evidence = [...rows.values()].sort((a, b) => compareText(JSON.stringify(a), JSON.stringify(b)))
|
|
946
|
+
const entities = ids.slice().sort(compareText).map(id => {
|
|
947
|
+
const entity = store.entities[id]
|
|
948
|
+
return [id, entity?.name, entity?.kind, entity?.aliases, entity?.status]
|
|
949
|
+
})
|
|
950
|
+
return { signature: createHash('sha256').update(JSON.stringify([entities, evidence])).digest('hex'),
|
|
951
|
+
evidenceIds: [...new Set([...evidence.filter(row => row[0] === 'memory').map(row => row[1]),
|
|
952
|
+
...evidence.filter(row => row[0] === 'relationship').flatMap(row => store.relationships[row[1]]?.evidenceIds || [])])] }
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
function currentMergeHolds(store, index, exec, binding) {
|
|
957
|
+
const valid = Object.create(null)
|
|
958
|
+
if (!store.mergeHolds || typeof store.mergeHolds !== 'object' || Array.isArray(store.mergeHolds)) return valid
|
|
959
|
+
const fingerprint = mergeHoldEvidence(index, store)
|
|
960
|
+
for (const [key, hold] of Object.entries(store.mergeHolds)) {
|
|
961
|
+
if (!hold || !Array.isArray(hold.evidenceIds)) continue
|
|
962
|
+
const rows = [hold.sourceId, hold.targetId].map(id => Object.hasOwn(store.entities, id) ? mergeReviewRow(store.entities[id]) : null)
|
|
963
|
+
if (rows.some(row => !row) || !entityMergePair(...rows)) continue
|
|
964
|
+
const identity = mergeReviewIdentity(...rows)
|
|
965
|
+
if (identity.key !== key || identity.signature !== hold.signature
|
|
966
|
+
|| fingerprint([hold.sourceId, hold.targetId]).signature !== hold.evidenceSignature) continue
|
|
967
|
+
// A reason written in another context is visible only while all evidence
|
|
968
|
+
// used there is also visible here. Management may inspect all local holds.
|
|
969
|
+
if (sessionIdOf(exec) && hold.evidenceIds.some(id => !index.entries[id] || !allowed(index.entries[id], exec, binding))) continue
|
|
970
|
+
valid[key] = hold
|
|
971
|
+
}
|
|
972
|
+
return valid
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
export function holdEntityMergeReview({ exec, libraryId, sourceId, targetId, reviewToken, reason, confidence } = {}) {
|
|
976
|
+
const scope = scopeFor({ exec, libraryId })
|
|
977
|
+
const file = entitiesPath(scope.libraryId)
|
|
978
|
+
return withFileLock(file, () => {
|
|
979
|
+
const store = readEntities(scope.libraryId), index = loadPrivateIndex(scope.libraryId)
|
|
980
|
+
const ids = [sourceId, targetId]
|
|
981
|
+
requireVisibleEntities({ exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships, ids })
|
|
982
|
+
const rows = ids.map(id => Object.hasOwn(store.entities, id) ? mergeReviewRow(store.entities[id]) : null)
|
|
983
|
+
assertMergeReviewToken(scope.libraryId, ...rows, reviewToken)
|
|
984
|
+
if (!entityMergePair(...rows)) throw new Error('entities are no longer a merge candidate; refresh the graph')
|
|
985
|
+
const identity = mergeReviewIdentity(...rows)
|
|
986
|
+
const holds = currentMergeHolds(store, index)
|
|
987
|
+
if (!holds[identity.key] && Object.keys(holds).length >= MERGE_REJECTION_LIMIT) throw new Error('entity review holds reached the 1000-pair limit')
|
|
988
|
+
const evidence = mergeHoldEvidence(index, store)(ids)
|
|
989
|
+
holds[identity.key] = { sourceId, targetId, signature: identity.signature, evidenceSignature: evidence.signature,
|
|
990
|
+
evidenceIds: evidence.evidenceIds.filter(id => index.entries[id] && allowed(index.entries[id], exec, scope.binding)),
|
|
991
|
+
reason: redactSecrets(String(reason || '')).slice(0, 500), confidence, updatedAt: stamp() }
|
|
992
|
+
store.mergeHolds = holds
|
|
993
|
+
writeJson(file, store)
|
|
994
|
+
return { ok: true, decision: 'hold', pendingUserReview: true, sourceId, targetId }
|
|
995
|
+
})
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
export function pendingEntityReviewPairs({ exec, libraryId, pairs = [] } = {}) {
|
|
999
|
+
const scope = scopeFor({ exec, libraryId }), store = readEntities(scope.libraryId), index = loadPrivateIndex(scope.libraryId)
|
|
1000
|
+
const visible = visibleEntityIds({ exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships })
|
|
1001
|
+
const holds = currentMergeHolds(store, index, exec, scope.binding), rejected = currentMergeRejections(store)
|
|
1002
|
+
return pairs.filter(pair => {
|
|
1003
|
+
const rows = [pair.sourceId, pair.targetId].map(id => visible.has(id) ? mergeReviewRow(store.entities[id]) : null)
|
|
1004
|
+
if (rows.some(row => !row) || !entityMergePair(...rows)) return false
|
|
1005
|
+
const key = mergeReviewIdentity(...rows).key
|
|
1006
|
+
return !holds[key] && !rejected[key]
|
|
1007
|
+
})
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/** A reversible user decision about one pair, never a merge or memory deletion. */
|
|
1011
|
+
export function setEntityMergeRejection({ exec, libraryId, sourceId, targetId, rejected, confirmed, reviewToken } = {}) {
|
|
1012
|
+
if (confirmed !== true) throw new Error('reviewing an entity merge candidate requires explicit confirmation')
|
|
1013
|
+
if (typeof rejected !== 'boolean') throw new Error('rejected must be a boolean')
|
|
1014
|
+
if (typeof reviewToken !== 'string' || !/^[a-f0-9]{64}$/.test(reviewToken)) throw new Error('reviewToken is required; refresh the entity merge candidates')
|
|
1015
|
+
const ids = [sourceId, targetId].map(id => typeof id === 'string' ? id.trim() : '')
|
|
1016
|
+
if (ids.some(id => !/^ent[-_][a-z0-9_-]{1,150}$/i.test(id)) || ids[0] === ids[1]) throw new Error('two distinct entity ids are required')
|
|
1017
|
+
const scope = scopeFor({ exec, libraryId })
|
|
1018
|
+
const file = entitiesPath(scope.libraryId)
|
|
1019
|
+
return withFileLock(file, () => {
|
|
1020
|
+
const store = readEntities(scope.libraryId)
|
|
1021
|
+
const index = loadPrivateIndex(scope.libraryId)
|
|
1022
|
+
requireVisibleEntities({ exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships, ids })
|
|
1023
|
+
const rows = ids.map(id => Object.hasOwn(store.entities, id) ? mergeReviewRow(store.entities[id]) : null)
|
|
1024
|
+
if (rows.some(row => !row)) throw new Error('unknown entity merge candidate')
|
|
1025
|
+
if (rejected && !entityMergePair(...rows)) throw new Error('entities are no longer a merge candidate; refresh the graph')
|
|
1026
|
+
const identity = mergeReviewIdentity(...rows)
|
|
1027
|
+
assertMergeReviewToken(scope.libraryId, ...rows, reviewToken)
|
|
1028
|
+
const reviews = currentMergeRejections(store)
|
|
1029
|
+
const existed = Object.hasOwn(reviews, identity.key)
|
|
1030
|
+
if (rejected && !existed && Object.keys(reviews).length >= MERGE_REJECTION_LIMIT) {
|
|
1031
|
+
throw new Error('entity merge exclusions reached the 1000-pair limit; restore an exclusion before adding another')
|
|
1032
|
+
}
|
|
1033
|
+
if (rejected) reviews[identity.key] = { sourceId: ids[0], targetId: ids[1], signature: identity.signature, updatedAt: stamp() }
|
|
1034
|
+
else delete reviews[identity.key]
|
|
1035
|
+
if (rejected !== existed || Object.keys(reviews).length !== Object.keys(store.mergeRejections || {}).length) {
|
|
1036
|
+
store.mergeRejections = reviews
|
|
1037
|
+
writeJson(file, store)
|
|
1038
|
+
}
|
|
1039
|
+
return { ok: true, sourceId: ids[0], targetId: ids[1], rejected }
|
|
1040
|
+
})
|
|
1041
|
+
}
|
|
744
1042
|
|
|
745
1043
|
/**
|
|
746
1044
|
* Pure read: candidate entity merges inside one library. Never writes and never
|
|
@@ -753,41 +1051,203 @@ const MERGE_REASON_ORDER = { containment: 0, 'edit-distance': 1, 'name-core': 2
|
|
|
753
1051
|
* 2 edits apart, or (CJK only) when they look like the same name written in full
|
|
754
1052
|
* and in short — see isNameCorePair. The longer name is the target (the hub the
|
|
755
1053
|
* shorter one folds into); on equal length the older id wins, which keeps the
|
|
756
|
-
* direction stable across calls.
|
|
757
|
-
* and
|
|
1054
|
+
* direction stable across calls. Small scans sort the complete candidate set;
|
|
1055
|
+
* large scans compare at most 4096 pairs and return a continuation after at most
|
|
1056
|
+
* 20 matches. A partial traversal never claims an exact library-wide total.
|
|
758
1057
|
*/
|
|
759
|
-
export function suggestEntityMerges({ libraryId } = {}) {
|
|
760
|
-
|
|
1058
|
+
export function suggestEntityMerges({ exec, libraryId, cursor, reviewState = 'all' } = {}) {
|
|
1059
|
+
if (!['all', 'model', 'human'].includes(reviewState)) throw new Error('reviewState must be all, model or human')
|
|
1060
|
+
const scope = scopeFor({ exec, libraryId })
|
|
761
1061
|
const store = readEntities(scope.libraryId)
|
|
762
|
-
const
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
.filter(
|
|
1062
|
+
const index = loadPrivateIndex(scope.libraryId)
|
|
1063
|
+
const visibleEntities = visibleEntityIds({ exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships })
|
|
1064
|
+
const rows = Object.values(store.entities || {}).filter(entity => visibleEntities.has(entity?.id))
|
|
1065
|
+
.map(mergeReviewRow).filter(Boolean).sort((a, b) => compareText(a.id, b.id))
|
|
1066
|
+
const allRejections = currentMergeRejections(store)
|
|
1067
|
+
const rowsById = new Map(rows.map(row => [row.id, row]))
|
|
1068
|
+
const rejections = Object.fromEntries(Object.entries(allRejections)
|
|
1069
|
+
.filter(([, record]) => rowsById.has(record.sourceId) && rowsById.has(record.targetId)))
|
|
1070
|
+
const holds = reviewState === 'all' ? {} : currentMergeHolds(store, index, exec, scope.binding)
|
|
1071
|
+
const revision = createHash('sha256').update(JSON.stringify([scope.libraryId, rows,
|
|
1072
|
+
Object.keys(rejections).sort().map(key => [key, rejections[key].signature]),
|
|
1073
|
+
reviewState, Object.keys(holds).sort().map(key => [key, holds[key].evidenceSignature])])).digest('hex')
|
|
1074
|
+
const pairSpace = rows.length * (rows.length - 1) / 2
|
|
1075
|
+
let i = 0
|
|
1076
|
+
let j = 1
|
|
1077
|
+
if (cursor !== undefined && cursor !== null && cursor !== '') {
|
|
1078
|
+
const match = typeof cursor === 'string' && cursor.length <= 180 ? cursor.match(/^m1\.([a-f0-9]{64})\.(\d{1,9})\.(\d{1,9})$/) : null
|
|
1079
|
+
if (!match || match[1] !== revision || Number(match[2]) >= rows.length - 1
|
|
1080
|
+
|| Number(match[3]) <= Number(match[2]) || Number(match[3]) >= rows.length) {
|
|
1081
|
+
throw Object.assign(new Error('entity merge scan changed or cursor is invalid; restart the scan'), { code: 'ENTITY_MERGE_SCAN_STALE' })
|
|
1082
|
+
}
|
|
1083
|
+
i = Number(match[2]); j = Number(match[3])
|
|
1084
|
+
}
|
|
1085
|
+
const scanStart = i * (2 * rows.length - i - 1) / 2 + Math.max(0, j - i - 1)
|
|
766
1086
|
const found = []
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
1087
|
+
const rejected = []
|
|
1088
|
+
let total = 0
|
|
1089
|
+
const comparePairs = (x, y) => (MERGE_REASON_ORDER[x.reason] - MERGE_REASON_ORDER[y.reason])
|
|
1090
|
+
|| compareText(x.targetKey, y.targetKey) || compareText(x.sourceKey, y.sourceKey)
|
|
1091
|
+
|| compareText(x.targetId, y.targetId) || compareText(x.sourceId, y.sourceId)
|
|
1092
|
+
const retain = (list, pair) => {
|
|
1093
|
+
if (list.length === SUGGEST_LIMIT && comparePairs(pair, list.at(-1)) >= 0) return
|
|
1094
|
+
list.push(pair)
|
|
1095
|
+
list.sort(comparePairs)
|
|
1096
|
+
if (list.length > SUGGEST_LIMIT) list.pop()
|
|
1097
|
+
}
|
|
1098
|
+
for (const record of Object.values(rejections)) {
|
|
1099
|
+
retain(rejected, entityMergePair(rowsById.get(record.sourceId), rowsById.get(record.targetId)))
|
|
1100
|
+
}
|
|
1101
|
+
let batchComparisons = 0
|
|
1102
|
+
// Large reviews are traversal batches, not an unbounded global sort. Every
|
|
1103
|
+
// returned cursor resumes after the last compared pair in this exact snapshot.
|
|
1104
|
+
while (i < rows.length - 1 && batchComparisons < MERGE_SCAN_PAIR_LIMIT) {
|
|
1105
|
+
const a = rows[i]
|
|
1106
|
+
const b = rows[j]
|
|
1107
|
+
batchComparisons += 1
|
|
1108
|
+
j += 1
|
|
1109
|
+
if (j >= rows.length) { i += 1; j = i + 1 }
|
|
1110
|
+
const pair = entityMergePair(a, b)
|
|
1111
|
+
if (!pair) continue
|
|
1112
|
+
const key = JSON.stringify([a.id, b.id].sort(compareText))
|
|
1113
|
+
if (Object.hasOwn(rejections, key)) continue
|
|
1114
|
+
if (reviewState === 'human' && !Object.hasOwn(holds, key) || reviewState === 'model' && Object.hasOwn(holds, key)) continue
|
|
1115
|
+
total += 1
|
|
1116
|
+
retain(found, pair)
|
|
1117
|
+
if (pairSpace > MERGE_SCAN_PAIR_LIMIT && total >= SUGGEST_LIMIT) break
|
|
1118
|
+
}
|
|
1119
|
+
const scanComplete = i >= rows.length - 1
|
|
1120
|
+
const totalExact = scanStart === 0 && scanComplete
|
|
1121
|
+
const rejectedTotal = Object.keys(rejections).length
|
|
1122
|
+
const project = item => ({ sourceId: item.sourceId, targetId: item.targetId, reason: item.reason,
|
|
1123
|
+
reviewToken: mergeReviewToken(scope.libraryId, mergeReviewIdentity(rowsById.get(item.sourceId), rowsById.get(item.targetId)).signature) })
|
|
1124
|
+
return { items: found.map(project), total: totalExact ? total : null, totalExact, discoveredTotal: total,
|
|
1125
|
+
scanComplete, nextCursor: scanComplete ? null : `m1.${revision}.${i}.${j}`,
|
|
1126
|
+
scanStart, scannedPairs: scanStart + batchComparisons, batchComparisons, pairSpace,
|
|
1127
|
+
truncated: total > SUGGEST_LIMIT,
|
|
1128
|
+
rejectedItems: rejected.map(project), rejectedTotal,
|
|
1129
|
+
rejectedTruncated: rejectedTotal > SUGGEST_LIMIT, limit: SUGGEST_LIMIT }
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
const MERGE_REVIEW_MEMORY_LIMIT = 6
|
|
1133
|
+
const MERGE_REVIEW_PREVIEW_CHARS = 180
|
|
1134
|
+
|
|
1135
|
+
function reviewMemory(entry, id) {
|
|
1136
|
+
if (!entry || typeof entry !== 'object') return null
|
|
1137
|
+
const content = String(entry.content || '').replace(/\s+/gu, ' ').trim()
|
|
1138
|
+
return {
|
|
1139
|
+
id,
|
|
1140
|
+
title: redactSecrets(String(entry.title || '').trim() || '(untitled)'),
|
|
1141
|
+
preview: redactSecrets(content.length > MERGE_REVIEW_PREVIEW_CHARS
|
|
1142
|
+
? content.slice(0, MERGE_REVIEW_PREVIEW_CHARS - 1) + '…'
|
|
1143
|
+
: content),
|
|
1144
|
+
domain: graphDomain(entry.domain) || 'general',
|
|
1145
|
+
observedAt: entry.observedAt || entry.createdAt || null,
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
function mergeReviewEvidence({ exec, binding, index, store, entityId }) {
|
|
1150
|
+
const rows = []
|
|
1151
|
+
for (const [id, entry] of Object.entries(index.entries || {})) {
|
|
1152
|
+
if (!allowed(entry, exec, binding)) continue
|
|
1153
|
+
if (!(entry.links || []).some(link => link?.to === entityId)) continue
|
|
1154
|
+
const row = reviewMemory(entry, id)
|
|
1155
|
+
if (row) rows.push({ ...row, _updatedAt: entry.updatedAt || entry.createdAt || '' })
|
|
1156
|
+
}
|
|
1157
|
+
rows.sort((a, b) => String(b._updatedAt).localeCompare(String(a._updatedAt)) || compareText(a.id, b.id))
|
|
1158
|
+
return { total: rows.length, items: rows.slice(0, MERGE_REVIEW_MEMORY_LIMIT).map(({ _updatedAt, ...row }) => row) }
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
function mergeReviewRelationships({ exec, binding, index, store, entityId, visibleEntities }) {
|
|
1162
|
+
const rows = []
|
|
1163
|
+
for (const relationship of Object.values(store.relationships || {})) {
|
|
1164
|
+
if (!relationship || (relationship.fromId !== entityId && relationship.toId !== entityId)) continue
|
|
1165
|
+
if (!relationshipVisible(relationship, { exec, binding, index, entities: store.entities,
|
|
1166
|
+
relationships: store.relationships, visibleEntities })) continue
|
|
1167
|
+
const otherId = relationship.fromId === entityId ? relationship.toId : relationship.fromId
|
|
1168
|
+
const other = store.entities[otherId]
|
|
1169
|
+
if (!other) continue
|
|
1170
|
+
const evidence = (Array.isArray(relationship.evidenceIds) ? relationship.evidenceIds : [])
|
|
1171
|
+
.slice(0, MERGE_REVIEW_MEMORY_LIMIT)
|
|
1172
|
+
.map(id => reviewMemory(index.entries[id], id)).filter(Boolean)
|
|
1173
|
+
const state = relationship.state && typeof relationship.state === 'object' ? relationship.state : {}
|
|
1174
|
+
rows.push({ kind: 'relationship', otherEntityId: otherId, otherName: redactSecrets(String(other.name || otherId)),
|
|
1175
|
+
reason: redactSecrets(String(relationship.reason || '')).slice(0, MERGE_REVIEW_PREVIEW_CHARS),
|
|
1176
|
+
dimensions: ['familiarity', 'trust', 'warmth'].filter(key => state[key] !== null && state[key] !== undefined),
|
|
1177
|
+
evidence, evidenceCount: Array.isArray(relationship.evidenceIds) ? relationship.evidenceIds.length : 0 })
|
|
1178
|
+
}
|
|
1179
|
+
return rows.slice(0, MERGE_REVIEW_MEMORY_LIMIT)
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
function detailedMergeEntity(entity, { exec, binding, index, store, visibleEntities }) {
|
|
1183
|
+
const evidence = mergeReviewEvidence({ exec, binding, index, store, entityId: entity.id })
|
|
1184
|
+
const relationships = mergeReviewRelationships({ exec, binding, index, store, entityId: entity.id, visibleEntities })
|
|
1185
|
+
return {
|
|
1186
|
+
id: entity.id,
|
|
1187
|
+
name: String(store.entities[entity.id]?.name || entity.key),
|
|
1188
|
+
kind: entity.kind,
|
|
1189
|
+
status: ENTITY_STATUS.includes(store.entities[entity.id]?.status) ? store.entities[entity.id].status : 'provisional',
|
|
1190
|
+
aliases: Array.isArray(store.entities[entity.id]?.aliases) ? store.entities[entity.id].aliases.slice(0, 30) : [],
|
|
1191
|
+
memories: evidence.items,
|
|
1192
|
+
memoryCount: evidence.total,
|
|
1193
|
+
memoriesTruncated: evidence.total > evidence.items.length,
|
|
1194
|
+
relationships,
|
|
1195
|
+
relationshipCount: relationships.length,
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
/**
|
|
1200
|
+
* Read-only, evidence-rich entity merge reviews for the memory page and the
|
|
1201
|
+
* consolidation worker. It deliberately builds on the bounded candidate scan;
|
|
1202
|
+
* names remain a discovery signal, while memory and relationship evidence are
|
|
1203
|
+
* shown to the caller so an AI or user can make the actual identity decision.
|
|
1204
|
+
*/
|
|
1205
|
+
export function suggestEntityMergeReviews({ exec, libraryId, cursor, reviewState = 'all', pairs } = {}) {
|
|
1206
|
+
const scope = scopeFor({ exec, libraryId })
|
|
1207
|
+
// Frozen maintenance batches must remain readable after an earlier decision
|
|
1208
|
+
// changes the scan order. Only still-visible, undecided pairs are projected.
|
|
1209
|
+
const scheduled = Array.isArray(pairs)
|
|
1210
|
+
? pendingEntityReviewPairs({ exec, libraryId: scope.libraryId, pairs: pairs.slice(0, SUGGEST_LIMIT) }) : null
|
|
1211
|
+
const base = scheduled ? { items: scheduled, rejectedItems: [], total: scheduled.length, totalExact: true,
|
|
1212
|
+
scanComplete: true, nextCursor: null, limit: SUGGEST_LIMIT }
|
|
1213
|
+
: suggestEntityMerges({ exec, libraryId: scope.libraryId, cursor, reviewState })
|
|
1214
|
+
const store = readEntities(scope.libraryId)
|
|
1215
|
+
const index = loadPrivateIndex(scope.libraryId)
|
|
1216
|
+
const holds = currentMergeHolds(store, index, exec, scope.binding)
|
|
1217
|
+
const visibleEntities = visibleEntityIds({ exec, binding: scope.binding, index,
|
|
1218
|
+
entities: store.entities, relationships: store.relationships })
|
|
1219
|
+
const byId = new Map(Object.values(store.entities || {}).map(entity => [entity.id, entity]))
|
|
1220
|
+
const detail = (pair) => {
|
|
1221
|
+
const source = byId.get(pair.sourceId)
|
|
1222
|
+
const target = byId.get(pair.targetId)
|
|
1223
|
+
if (!source || !target) return null
|
|
1224
|
+
const currentPair = entityMergePair(mergeReviewRow(source), mergeReviewRow(target))
|
|
1225
|
+
const currentToken = currentPair && mergeReviewToken(scope.libraryId,
|
|
1226
|
+
mergeReviewIdentity(mergeReviewRow(source), mergeReviewRow(target)).signature)
|
|
1227
|
+
if (!currentPair || currentToken !== pair.reviewToken) {
|
|
1228
|
+
throw Object.assign(new Error('entity merge candidate changed while reading evidence; retry the review list'),
|
|
1229
|
+
{ code: 'ENTITY_MERGE_SCAN_STALE' })
|
|
783
1230
|
}
|
|
1231
|
+
const hold = holds[mergeReviewIdentity(mergeReviewRow(source), mergeReviewRow(target)).key]
|
|
1232
|
+
return {
|
|
1233
|
+
libraryId: scope.libraryId,
|
|
1234
|
+
source: detailedMergeEntity(mergeReviewRow(source), { exec, binding: scope.binding, index, store, visibleEntities }),
|
|
1235
|
+
target: detailedMergeEntity(mergeReviewRow(target), { exec, binding: scope.binding, index, store, visibleEntities }),
|
|
1236
|
+
reason: pair.reason,
|
|
1237
|
+
reviewToken: pair.reviewToken,
|
|
1238
|
+
reviewState: hold ? 'human' : 'model',
|
|
1239
|
+
reviewReason: hold?.reason || '',
|
|
1240
|
+
risk: pair.reason === 'edit-distance' || pair.reason === 'name-core' ? 'identity-sensitive' : 'review-required',
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
return {
|
|
1244
|
+
...base,
|
|
1245
|
+
items: base.items.map(detail).filter(Boolean),
|
|
1246
|
+
rejectedItems: base.rejectedItems.map(detail).filter(Boolean),
|
|
1247
|
+
evidenceLimited: true,
|
|
1248
|
+
memoryLimit: MERGE_REVIEW_MEMORY_LIMIT,
|
|
1249
|
+
previewChars: MERGE_REVIEW_PREVIEW_CHARS,
|
|
784
1250
|
}
|
|
785
|
-
found.sort((x, y) => (MERGE_REASON_ORDER[x.reason] - MERGE_REASON_ORDER[y.reason])
|
|
786
|
-
|| compareText(x.targetKey, y.targetKey)
|
|
787
|
-
|| compareText(x.sourceKey, y.sourceKey)
|
|
788
|
-
|| compareText(x.targetId, y.targetId)
|
|
789
|
-
|| compareText(x.sourceId, y.sourceId))
|
|
790
|
-
return { items: found.slice(0, SUGGEST_LIMIT).map(item => ({ sourceId: item.sourceId, targetId: item.targetId, reason: item.reason })) }
|
|
791
1251
|
}
|
|
792
1252
|
|
|
793
1253
|
// Unknown names need a complete source surface. Existing, asserted entities use
|
|
@@ -843,7 +1303,8 @@ export function linkNamedEntity({ exec, libraryId, fromId, entity, kind, note, c
|
|
|
843
1303
|
}
|
|
844
1304
|
}
|
|
845
1305
|
const target = existing || createEntity({ exec, libraryId: scope.libraryId, name, kind: entityKind, status: 'provisional', origin: 'worker' })
|
|
846
|
-
return
|
|
1306
|
+
return linkEntriesWithTrustedEntity({ exec, libraryId: scope.libraryId, fromId, toId: target.id, kind, note, confidence },
|
|
1307
|
+
existing ? null : target.id)
|
|
847
1308
|
}
|
|
848
1309
|
|
|
849
1310
|
/**
|
|
@@ -855,18 +1316,25 @@ export function linkNamedEntity({ exec, libraryId, fromId, entity, kind, note, c
|
|
|
855
1316
|
* reading as a model/user link. Replacement stays idempotent: the same
|
|
856
1317
|
* (to, kind) pair is overwritten in place instead of appended.
|
|
857
1318
|
*/
|
|
858
|
-
export function linkEntries({
|
|
1319
|
+
export function linkEntries(args) { return linkEntriesWithTrustedEntity(args) }
|
|
1320
|
+
|
|
1321
|
+
function linkEntriesWithTrustedEntity({ exec, libraryId, fromId, toId, kind, note, confidence = 0.7, source }, trustedEntityId = null) {
|
|
859
1322
|
const scope = scopeFor({ exec, libraryId })
|
|
860
1323
|
const reason = validateLinkArguments(kind, note, confidence)
|
|
861
1324
|
if (fromId === toId) throw new Error('a memory cannot link to itself')
|
|
862
1325
|
const linkSource = source === 'auto' || source === 'user' ? source : null
|
|
863
|
-
const
|
|
1326
|
+
const entityStore = readEntities(scope.libraryId)
|
|
1327
|
+
const entities = entityStore.entities
|
|
864
1328
|
let result
|
|
865
1329
|
updatePrivateIndex(scope.libraryId, index => {
|
|
866
1330
|
const origin = index.entries[fromId]
|
|
867
1331
|
const target = index.entries[toId]
|
|
868
1332
|
if (!origin || !allowed(origin, exec) || target && !allowed(target, exec)) throw new Error('unknown or inaccessible memory')
|
|
869
|
-
if (!target && !entities[toId]) throw new Error('link target must be an existing memory or entity')
|
|
1333
|
+
if (!target && !entities[toId]) throw new Error(sessionIdOf(exec) ? 'unknown or inaccessible memory' : 'link target must be an existing memory or entity')
|
|
1334
|
+
if (!target && sessionIdOf(exec) && trustedEntityId !== toId
|
|
1335
|
+
&& !visibleEntityIds({ exec, binding: scope.binding, index, entities, relationships: entityStore.relationships }).has(toId)) {
|
|
1336
|
+
throw new Error('unknown or inaccessible memory')
|
|
1337
|
+
}
|
|
870
1338
|
if (kind === 'person' && entities[toId]?.kind !== 'person') throw new Error('person links must target a person entity')
|
|
871
1339
|
const links = Array.isArray(origin.links) ? origin.links : []
|
|
872
1340
|
result = { to: toId, kind, note: reason, confidence, createdAt: stamp() }
|
|
@@ -888,8 +1356,9 @@ export function linkEntries({ exec, libraryId, fromId, toId, kind, note, confide
|
|
|
888
1356
|
* deterministic layer cannot recreate it (P6). Used by the graph page's
|
|
889
1357
|
* "remove all auto edges" action and by operators cleaning a legacy library.
|
|
890
1358
|
*/
|
|
891
|
-
export function purgeAutoLinks({ libraryId } = {}) {
|
|
892
|
-
const scope = scopeFor({ libraryId })
|
|
1359
|
+
export function purgeAutoLinks({ exec, libraryId } = {}) {
|
|
1360
|
+
const scope = scopeFor({ exec, libraryId })
|
|
1361
|
+
if (sessionIdOf(exec)) throw new Error('whole-library link maintenance requires explicit management access')
|
|
893
1362
|
const removed = []
|
|
894
1363
|
updatePrivateIndex(scope.libraryId, index => {
|
|
895
1364
|
for (const [fromId, entry] of Object.entries(index.entries || {})) {
|
|
@@ -921,13 +1390,23 @@ export function purgeAutoLinks({ libraryId } = {}) {
|
|
|
921
1390
|
return { removed: removed.length }
|
|
922
1391
|
}
|
|
923
1392
|
|
|
924
|
-
export function unlinkEntry({ libraryId, fromId, toId, kind }) {
|
|
925
|
-
const scope = scopeFor({ libraryId })
|
|
1393
|
+
export function unlinkEntry({ exec, libraryId, fromId, toId, kind }) {
|
|
1394
|
+
const scope = scopeFor({ exec, libraryId })
|
|
1395
|
+
const entityStore = readEntities(scope.libraryId)
|
|
1396
|
+
const entities = entityStore.entities
|
|
926
1397
|
let removed = 0
|
|
927
1398
|
const removedAuto = []
|
|
928
1399
|
updatePrivateIndex(scope.libraryId, index => {
|
|
929
1400
|
const entry = index.entries[fromId]
|
|
930
|
-
if (!entry) throw new Error('unknown memory')
|
|
1401
|
+
if (!entry || !allowed(entry, exec)) throw new Error('unknown or inaccessible memory')
|
|
1402
|
+
if (sessionIdOf(exec)) {
|
|
1403
|
+
const visibleEntities = visibleEntityIds({ exec, binding: scope.binding, index, entities, relationships: entityStore.relationships })
|
|
1404
|
+
if (index.entries[toId] ? !allowed(index.entries[toId], exec) : entities[toId] ? !visibleEntities.has(toId) : true) {
|
|
1405
|
+
throw new Error('unknown or inaccessible memory')
|
|
1406
|
+
}
|
|
1407
|
+
} else if (index.entries[toId] && !allowed(index.entries[toId], exec)) {
|
|
1408
|
+
throw new Error('unknown or inaccessible memory')
|
|
1409
|
+
}
|
|
931
1410
|
entry.links = (entry.links || []).filter(link => {
|
|
932
1411
|
const drop = link.to === toId && (!kind || link.kind === kind)
|
|
933
1412
|
if (drop) {
|
|
@@ -953,10 +1432,73 @@ export function unlinkEntry({ libraryId, fromId, toId, kind }) {
|
|
|
953
1432
|
// Shared with the global graph so both sides agree on what "same domain" means.
|
|
954
1433
|
export function graphDomain(value) { return String(value ?? '').normalize('NFKC').trim().toLowerCase() }
|
|
955
1434
|
|
|
1435
|
+
export function getGraphOverview(args = {}) {
|
|
1436
|
+
const { exec, domain, includeOrphans = false } = args
|
|
1437
|
+
const scope = scopeFor(args)
|
|
1438
|
+
const index = readPrivateIndex(scope.libraryId)
|
|
1439
|
+
if (readFailure(path.join(indexDir(), `${scope.libraryId}.json`))) throw new Error('cannot read graph index; restore it before reading')
|
|
1440
|
+
const entityStamp = () => {
|
|
1441
|
+
try {
|
|
1442
|
+
const stat = fs.statSync(entitiesPath(scope.libraryId), { bigint: true })
|
|
1443
|
+
return `${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.ino}`
|
|
1444
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; return 'missing' }
|
|
1445
|
+
}
|
|
1446
|
+
const entityRevision = entityStamp()
|
|
1447
|
+
const revision = indexReadRevision(index)
|
|
1448
|
+
const domainFilter = graphDomain(domain)
|
|
1449
|
+
const key = [indexDir(), scope.libraryId, sessionIdOf(exec) || null, scope.binding?.memoryContext || null, domainFilter, includeOrphans]
|
|
1450
|
+
return cachedGraphOverview({
|
|
1451
|
+
key,
|
|
1452
|
+
revision: revision ? `${revision}:${entityRevision}` : null,
|
|
1453
|
+
adjacency: revision ? build => getGraphAdjacency({ scope: 'private', libraryId: scope.libraryId,
|
|
1454
|
+
key, revision, entityRevision, build }) : null,
|
|
1455
|
+
onAdjacencyError: () => warn('graph adjacency read failed; using canonical graph topology'),
|
|
1456
|
+
build: () => {
|
|
1457
|
+
const entityStore = readEntities(scope.libraryId)
|
|
1458
|
+
const entities = entityStore.entities
|
|
1459
|
+
if (entityStamp() !== entityRevision) throw new Error('graph entity store changed during read; retry the request')
|
|
1460
|
+
const visibleEntities = visibleEntityIds({ exec, binding: scope.binding, index, entities, relationships: entityStore.relationships })
|
|
1461
|
+
const visible = new Map(), domains = new Set(), nodes = new Map(), edges = []
|
|
1462
|
+
for (const [id, entry] of Object.entries(index.entries)) {
|
|
1463
|
+
if (!allowed(entry, exec, scope.binding)) continue
|
|
1464
|
+
const normalized = graphDomain(entry?.domain) || 'general'
|
|
1465
|
+
domains.add(normalized)
|
|
1466
|
+
if (!domainFilter || normalized === domainFilter) visible.set(id, normalized)
|
|
1467
|
+
}
|
|
1468
|
+
const add = id => {
|
|
1469
|
+
if (nodes.has(id)) return
|
|
1470
|
+
const entry = index.entries[id], entity = entities[id]
|
|
1471
|
+
nodes.set(id, { id, title: entry?.title || entity?.name || '[deleted]', layer: entry?.layer || null,
|
|
1472
|
+
kind: entity?.kind || 'memory', strength: entry ? decayStrength(entry) : .5,
|
|
1473
|
+
degree: 0, missing: !entry && !entity,
|
|
1474
|
+
...(entry ? { status: entry.status || 'active' } : {}),
|
|
1475
|
+
...(entry ? { domain: visible.get(id) } : {}),
|
|
1476
|
+
...(entity ? { status: ENTITY_STATUS.includes(entity.status) ? entity.status : 'provisional' } : {}) })
|
|
1477
|
+
}
|
|
1478
|
+
for (const from of visible.keys()) {
|
|
1479
|
+
add(from)
|
|
1480
|
+
for (const link of index.entries[from].links || []) {
|
|
1481
|
+
if (!LINK_KINDS.includes(link?.kind) || !link.to || (index.entries[link.to] && !visible.has(link.to))) continue
|
|
1482
|
+
if (entities[link.to] && sessionIdOf(exec) && !visibleEntities.has(link.to)) continue
|
|
1483
|
+
add(link.to)
|
|
1484
|
+
nodes.get(from).degree++; nodes.get(link.to).degree++
|
|
1485
|
+
edges.push({ from, to: link.to, kind: link.kind, note: link.note, confidence: link.confidence ?? .7,
|
|
1486
|
+
source: link.source || null, rule: link.evidence?.rule || (link.source === 'auto' ? 'auto' : null), evidence: link.evidence || null })
|
|
1487
|
+
}
|
|
1488
|
+
}
|
|
1489
|
+
if (includeOrphans && !sessionIdOf(exec) && !domainFilter) for (const id of Object.keys(entities)) add(id)
|
|
1490
|
+
return { nodes: [...nodes.values()], edges, domains: [...domains].sort() }
|
|
1491
|
+
},
|
|
1492
|
+
}, { ...args, scope: 'private' })
|
|
1493
|
+
}
|
|
1494
|
+
|
|
956
1495
|
export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 200, includeOrphans = false, offset, domain }) {
|
|
957
1496
|
const scope = scopeFor({ exec, libraryId })
|
|
958
1497
|
const index = loadPrivateIndex(scope.libraryId)
|
|
959
|
-
|
|
1498
|
+
if (readFailure(path.join(indexDir(), `${scope.libraryId}.json`))) throw new Error('cannot read graph index; restore it before reading')
|
|
1499
|
+
const entityStore = readEntities(scope.libraryId)
|
|
1500
|
+
const entities = entityStore.entities
|
|
1501
|
+
const visibleEntities = visibleEntityIds({ exec, binding: scope.binding, index, entities, relationships: entityStore.relationships })
|
|
960
1502
|
const cap = Math.max(1, Math.min(200, Math.floor(Number(limit) || 200)))
|
|
961
1503
|
const hops = Math.max(0, Math.min(2, Math.floor(Number(depth) || 0)))
|
|
962
1504
|
const domainFilter = graphDomain(domain)
|
|
@@ -979,6 +1521,7 @@ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 2
|
|
|
979
1521
|
// A deleted target gets a placeholder; an inaccessible or other-domain
|
|
980
1522
|
// memory gets no hint. Filter before building either edges or adjacency.
|
|
981
1523
|
if (index.entries[link.to] && !visible.has(link.to)) continue
|
|
1524
|
+
if (entities[link.to] && sessionIdOf(exec) && !visibleEntities.has(link.to)) continue
|
|
982
1525
|
// source is display metadata only ('auto' edges get a badge in the graph
|
|
983
1526
|
// view); an older link without the field reports null instead of undefined.
|
|
984
1527
|
// evidence.rule / surface / field let the graph say WHY an edge exists.
|
|
@@ -999,7 +1542,10 @@ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 2
|
|
|
999
1542
|
}
|
|
1000
1543
|
}
|
|
1001
1544
|
}
|
|
1002
|
-
if (focusId && !visible.has(focusId) && !adjacency.has(focusId)
|
|
1545
|
+
if (focusId && !visible.has(focusId) && !adjacency.has(focusId)
|
|
1546
|
+
&& (!entities[focusId] || (sessionIdOf(exec) && !visibleEntities.has(focusId)) || domainFilter)) {
|
|
1547
|
+
throw new Error('unknown or inaccessible graph focus')
|
|
1548
|
+
}
|
|
1003
1549
|
const selected = new Set()
|
|
1004
1550
|
const candidates = new Set()
|
|
1005
1551
|
if (focusId) {
|
|
@@ -1018,7 +1564,7 @@ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 2
|
|
|
1018
1564
|
// original order, but later entities can no longer starve across pages.
|
|
1019
1565
|
// A domain never includes unrelated orphan entities, even on explicit opt-in.
|
|
1020
1566
|
for (const id of [...visible.keys(), ...Object.keys(entities), ...adjacency.keys()]) {
|
|
1021
|
-
if (sessionIdOf(exec) && !visible.has(id) && !adjacency.has(id)) continue
|
|
1567
|
+
if (sessionIdOf(exec) && !visible.has(id) && !adjacency.has(id) && !visibleEntities.has(id)) continue
|
|
1022
1568
|
if ((!includeOrphans || domainFilter) && entities[id] && !adjacency.has(id)) continue
|
|
1023
1569
|
candidates.add(id)
|
|
1024
1570
|
}
|
|
@@ -1030,6 +1576,7 @@ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 2
|
|
|
1030
1576
|
return { id, title: entry?.title || entity?.name || '[deleted]', layer: entry?.layer || null,
|
|
1031
1577
|
kind: entity?.kind || 'memory', strength: entry ? decayStrength(entry) : 0.5,
|
|
1032
1578
|
degree: adjacency.get(id)?.size || 0, missing: !entry && !entity,
|
|
1579
|
+
...(entry ? { status: entry.status || 'active' } : {}),
|
|
1033
1580
|
...(entry ? { domain: visible.get(id) } : {}),
|
|
1034
1581
|
...(entity ? { status: ENTITY_STATUS.includes(entity.status) ? entity.status : 'provisional' } : {}) }
|
|
1035
1582
|
})
|
|
@@ -1042,47 +1589,42 @@ export function getGraph({ exec, libraryId, focusId = null, depth = 1, limit = 2
|
|
|
1042
1589
|
}
|
|
1043
1590
|
|
|
1044
1591
|
// recallRelations 只需要与指定记忆相连的边,避免每次全库扫描
|
|
1045
|
-
// entries × links
|
|
1046
|
-
//
|
|
1047
|
-
const relationInvertedCache = new Map()
|
|
1048
|
-
|
|
1592
|
+
// entries × links。只按经过校验的完整索引 revision 复用;同长外改、恢复
|
|
1593
|
+
// mtime 也必须失效。与 overview 共用 48MiB 总预算,纯内存快照不缓存。
|
|
1049
1594
|
function relationInvertedIndex(libraryId, index) {
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
const
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
const inverted = new Map()
|
|
1058
|
-
const push = (key, row) => {
|
|
1059
|
-
if (!key) return
|
|
1060
|
-
let rows = inverted.get(key)
|
|
1061
|
-
if (!rows) inverted.set(key, rows = [])
|
|
1062
|
-
rows.push(row)
|
|
1063
|
-
}
|
|
1064
|
-
for (const [from, entry] of Object.entries(index?.entries || {})) {
|
|
1065
|
-
for (const link of entry?.links || []) {
|
|
1066
|
-
if (!link || !link.to) continue
|
|
1067
|
-
const row = { from, link }
|
|
1068
|
-
push(from, row)
|
|
1069
|
-
// 自环(link.to === from)只存一份,避免查询看到同一行两次。
|
|
1070
|
-
if (link.to !== from) push(link.to, row)
|
|
1595
|
+
return cachedGraphRelations({ key: [indexDir(), libraryId], revision: indexReadRevision(index), build: () => {
|
|
1596
|
+
const inverted = new Map()
|
|
1597
|
+
const push = (key, row) => {
|
|
1598
|
+
if (!key) return
|
|
1599
|
+
let rows = inverted.get(key)
|
|
1600
|
+
if (!rows) inverted.set(key, rows = [])
|
|
1601
|
+
rows.push(row)
|
|
1071
1602
|
}
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1603
|
+
for (const [from, entry] of Object.entries(index?.entries || {})) {
|
|
1604
|
+
for (const link of entry?.links || []) {
|
|
1605
|
+
if (!link || !link.to) continue
|
|
1606
|
+
const row = { from, link }
|
|
1607
|
+
push(from, row)
|
|
1608
|
+
// 自环(link.to === from)只存一份,避免查询看到同一行两次。
|
|
1609
|
+
if (link.to !== from) push(link.to, row)
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
return inverted
|
|
1613
|
+
} })
|
|
1075
1614
|
}
|
|
1076
1615
|
|
|
1077
1616
|
export function recallRelations(libraryId, index, id, sessionId) {
|
|
1078
1617
|
const store = readEntities(libraryId)
|
|
1079
1618
|
const entities = store.entities
|
|
1619
|
+
const exec = sessionId ? { agent: { session: { header: { id: sessionId } } } } : null
|
|
1620
|
+
const visibleEntities = visibleEntityIds({ exec, sessionId, index, entities, relationships: store.relationships })
|
|
1080
1621
|
// 关系衰减是写入侧算的(updateRelationship 每次更新都把 retention_strength 折一次),
|
|
1081
1622
|
// 但读取侧从来没用过它——一条半年没人碰过的关系,和一条昨天刚更新的关系,扩展
|
|
1082
1623
|
// 时的分量完全一样。这里把「这个实体背后最强的活跃关系还剩多少」带出去,让调用方
|
|
1083
1624
|
// 能按它排序和过滤。记忆型目标不归关系衰减管,retention 留 null。
|
|
1084
1625
|
const retentionOf = new Map()
|
|
1085
1626
|
for (const relationship of Object.values(store.relationships || {})) {
|
|
1627
|
+
if (!relationshipVisible(relationship, { exec, index, entities, relationships: store.relationships, visibleEntities })) continue
|
|
1086
1628
|
const value = Number.isFinite(Number(relationship?.retention_strength)) ? Number(relationship.retention_strength) : 1
|
|
1087
1629
|
for (const entityId of [relationship?.fromId, relationship?.toId]) {
|
|
1088
1630
|
if (!entityId) continue
|
|
@@ -1105,6 +1647,7 @@ export function recallRelations(libraryId, index, id, sessionId) {
|
|
|
1105
1647
|
const to = from === id ? link.to : from
|
|
1106
1648
|
const target = index.entries[to]
|
|
1107
1649
|
if (target && (!isMemoryEligible(target, { automatic: true }) || !visibleToSession(target, sessionId))) continue
|
|
1650
|
+
if (entities[to] && sessionId && !visibleEntities.has(to)) continue
|
|
1108
1651
|
// A dangling edge (entry and entity both gone) used to be dropped here
|
|
1109
1652
|
// while getGraph rendered the same disk state as a [deleted] placeholder —
|
|
1110
1653
|
// the two views disagreed. Both now report the edge and mark it `missing`;
|
|
@@ -1132,8 +1675,10 @@ export function getRelationship({ exec, libraryId, fromId, toId }) {
|
|
|
1132
1675
|
const relationship = store.relationships[JSON.stringify([fromId, toId])]
|
|
1133
1676
|
if (!relationship) return { relationship: null }
|
|
1134
1677
|
const index = loadPrivateIndex(scope.libraryId)
|
|
1135
|
-
if (
|
|
1136
|
-
return { relationship
|
|
1678
|
+
if (!relationshipVisible(relationship, { exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships })) return { relationship: null }
|
|
1679
|
+
return { relationship: sessionIdOf(exec)
|
|
1680
|
+
? relationshipForSession(relationship, { exec, binding: scope.binding, index, entities: store.entities, relationships: store.relationships })
|
|
1681
|
+
: relationship }
|
|
1137
1682
|
}
|
|
1138
1683
|
|
|
1139
1684
|
export function updateRelationship({ exec, libraryId, fromId, toId, state, evidenceIds, reason }) {
|
|
@@ -1155,10 +1700,18 @@ export function updateRelationship({ exec, libraryId, fromId, toId, state, evide
|
|
|
1155
1700
|
}
|
|
1156
1701
|
const index = loadPrivateIndex(scope.libraryId)
|
|
1157
1702
|
if (evidenceIds.some(id => !index.entries[id] || !allowed(index.entries[id], exec))) throw new Error('relationship evidence is not visible in this conversation')
|
|
1703
|
+
const entityStore = readEntities(scope.libraryId)
|
|
1704
|
+
const entities = entityStore.entities
|
|
1705
|
+
requireVisibleEntities({ exec, binding: scope.binding, index, entities, relationships: entityStore.relationships, ids: [fromId, toId] })
|
|
1158
1706
|
const file = entitiesPath(scope.libraryId)
|
|
1159
1707
|
return withFileLock(file, () => {
|
|
1160
1708
|
const store = readEntities(scope.libraryId)
|
|
1161
1709
|
if (!store.entities[fromId] || !store.entities[toId]) throw new Error('relationship endpoints must be existing entities')
|
|
1710
|
+
const currentIndex = loadPrivateIndex(scope.libraryId)
|
|
1711
|
+
requireVisibleEntities({ exec, binding: scope.binding, index: currentIndex, entities: store.entities, relationships: store.relationships, ids: [fromId, toId] })
|
|
1712
|
+
if (evidenceIds.some(id => !currentIndex.entries[id] || !allowed(currentIndex.entries[id], exec, scope.binding))) {
|
|
1713
|
+
throw new Error('relationship evidence is not visible in this conversation')
|
|
1714
|
+
}
|
|
1162
1715
|
const key = JSON.stringify([fromId, toId])
|
|
1163
1716
|
const previous = store.relationships[key]
|
|
1164
1717
|
const at = stamp()
|