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
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { createBoundedCache, estimateBytes } from './bounded-cache.js'
|
|
3
|
+
|
|
4
|
+
export const GRAPH_DETAIL_LIMIT = 3000
|
|
5
|
+
export const GRAPH_CLUSTER_LIMIT = 200
|
|
6
|
+
const CLUSTER_SIZE = 1000
|
|
7
|
+
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0
|
|
8
|
+
const compareEdges = (a, b) => compare(a.from, b.from) || compare(a.to, b.to) || compare(a.kind || '', b.kind || '')
|
|
9
|
+
const digest = ids => createHash('sha256').update(JSON.stringify(ids)).digest('hex').slice(0, 24)
|
|
10
|
+
const canonicalKey = value => Array.isArray(value) ? value.map(canonicalKey)
|
|
11
|
+
: value && typeof value === 'object' ? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonicalKey(value[key])])) : value
|
|
12
|
+
// A compact CSR adjacency avoids one Map + array allocation per node. Accounting
|
|
13
|
+
// includes row/map overhead and variable text; it remains an estimate, not RSS.
|
|
14
|
+
const graphBytes = model => model instanceof Map ? estimateBytes(model)
|
|
15
|
+
: model.nodes.reduce((sum, node) => sum + 224 + String(node.id).length * 2 + String(node.title || '').length * 2, 0)
|
|
16
|
+
+ model.edges.reduce((sum, edge) => sum + 112 + String(edge.note || '').length * 2 + (edge.evidence ? JSON.stringify(edge.evidence).length * 2 : 0), 0)
|
|
17
|
+
+ model.sourceEdges.length * 8 + model.clusters.length * 768 + model.adjacencyOffsets.byteLength + model.adjacencyEdges.byteLength
|
|
18
|
+
const cache = createBoundedCache({ name: 'graph-overview', maxEntries: 32, maxBytes: 48 * 1024 * 1024, ttlMs: 120000, sizeOf: graphBytes })
|
|
19
|
+
const intersects = (a, b) => a.minX <= b.maxX && a.maxX >= b.minX && a.minY <= b.maxY && a.maxY >= b.minY
|
|
20
|
+
const inside = (node, box) => node.x >= box.minX && node.x <= box.maxX && node.y >= box.minY && node.y <= box.maxY
|
|
21
|
+
|
|
22
|
+
// Recall's canonical inverted links share this total budget with overview
|
|
23
|
+
// models. Unversioned caller-owned snapshots are deliberately never retained.
|
|
24
|
+
export function cachedGraphRelations({ key, revision, build }) {
|
|
25
|
+
const cacheKey = JSON.stringify(['relations', key, revision])
|
|
26
|
+
let result = revision ? cache.get(cacheKey) : null
|
|
27
|
+
if (!result) { result = build(); if (revision) cache.set(cacheKey, result) }
|
|
28
|
+
return result
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function pageNumber(value, fallback, name, min, max = Number.MAX_SAFE_INTEGER) {
|
|
32
|
+
if (value === undefined || value === null) return fallback
|
|
33
|
+
if (!['number', 'string'].includes(typeof value) || String(value).trim() === ''
|
|
34
|
+
|| !Number.isFinite(Number(value)) || !Number.isSafeInteger(Math.floor(Number(value)))) throw new Error(`invalid graph ${name}`)
|
|
35
|
+
return Math.min(max, Math.max(min, Math.floor(Number(value))))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function graphBounds(value) {
|
|
39
|
+
if (value === undefined || value === null) return null
|
|
40
|
+
const box = Array.isArray(value) ? { minX: value[0], minY: value[1], maxX: value[2], maxY: value[3] } : value
|
|
41
|
+
if (!box || !['minX', 'minY', 'maxX', 'maxY'].every(key => typeof box[key] === 'number' && Number.isFinite(box[key]))
|
|
42
|
+
|| box.minX > box.maxX || box.minY > box.maxY) throw new Error('bbox must contain finite ordered minX/minY/maxX/maxY')
|
|
43
|
+
return { minX: box.minX, minY: box.minY, maxX: box.maxX, maxY: box.maxY }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function graphQuery({ clusterId, bbox, zoom = 0, limit, offset = 0, focusId, depth = 1, query, layout } = {}) {
|
|
47
|
+
if (query !== undefined && query !== null && (typeof query !== 'string' || query.length > 256)) throw new Error('invalid graph query: expected a string of at most 256 characters')
|
|
48
|
+
const search = (query || '').normalize('NFKC').trim().toLowerCase()
|
|
49
|
+
if (search.length > 256) throw new Error('invalid graph query: normalized length exceeds 256 characters')
|
|
50
|
+
const box = graphBounds(bbox)
|
|
51
|
+
if (!['number', 'string'].includes(typeof zoom) || String(zoom).trim() === '' || !Number.isFinite(Number(zoom))) throw new Error('invalid graph zoom')
|
|
52
|
+
const detail = Boolean(layout === 'classic' || search || clusterId || focusId || (box && Number(zoom) >= 1))
|
|
53
|
+
const max = detail ? GRAPH_DETAIL_LIMIT : GRAPH_CLUSTER_LIMIT
|
|
54
|
+
return { box, detail, search, cap: pageNumber(limit, max, 'limit', 1, max), start: pageNumber(offset, 0, 'offset', 0),
|
|
55
|
+
hops: pageNumber(depth, 1, 'depth', 0, 2) }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Pure derived data. Callers must enforce visibility before handing us a row. */
|
|
59
|
+
export function buildGraphOverview(graph, { revision = null, scope = 'private', positionScope = scope } = {}) {
|
|
60
|
+
const nodes = [...new Map((graph.nodes || []).map(node => [node.id, {
|
|
61
|
+
id: node.id, title: node.title, kind: node.kind, layer: node.layer, strength: node.strength,
|
|
62
|
+
degree: node.degree || 0, missing: Boolean(node.missing), domain: node.domain, status: node.status,
|
|
63
|
+
clusterId: null, componentId: null, x: 0, y: 0,
|
|
64
|
+
}])).values()].sort((a, b) => compare(a.id, b.id))
|
|
65
|
+
const byId = new Map(nodes.map((node, i) => [node.id, i]))
|
|
66
|
+
const parents = Int32Array.from(nodes, (_, i) => i)
|
|
67
|
+
const root = i => {
|
|
68
|
+
while (parents[i] !== i) { parents[i] = parents[parents[i]]; i = parents[i] }
|
|
69
|
+
return i
|
|
70
|
+
}
|
|
71
|
+
// Persistent ordinals refer to extraction order, not the deterministic sort
|
|
72
|
+
// used for components. Both arrays share the same canonical metadata objects.
|
|
73
|
+
const sourceEdges = (graph.edges || []).map(edge => ({ ...edge }))
|
|
74
|
+
const edges = sourceEdges.filter(edge => byId.has(edge.from) && byId.has(edge.to))
|
|
75
|
+
.sort(compareEdges)
|
|
76
|
+
const adjacencyOffsets = new Uint32Array(nodes.length + 1)
|
|
77
|
+
for (const edge of edges) {
|
|
78
|
+
const from = byId.get(edge.from), to = byId.get(edge.to), a = root(from), b = root(to)
|
|
79
|
+
if (a !== b) parents[Math.max(a, b)] = Math.min(a, b)
|
|
80
|
+
adjacencyOffsets[from + 1]++
|
|
81
|
+
if (from !== to) adjacencyOffsets[to + 1]++
|
|
82
|
+
}
|
|
83
|
+
for (let i = 1; i < adjacencyOffsets.length; i++) adjacencyOffsets[i] += adjacencyOffsets[i - 1]
|
|
84
|
+
const adjacencyEdges = new Uint32Array(adjacencyOffsets[nodes.length]), cursor = adjacencyOffsets.slice(0, -1)
|
|
85
|
+
edges.forEach((edge, i) => {
|
|
86
|
+
const from = byId.get(edge.from), to = byId.get(edge.to)
|
|
87
|
+
adjacencyEdges[cursor[from]++] = i
|
|
88
|
+
if (from !== to) adjacencyEdges[cursor[to]++] = i
|
|
89
|
+
})
|
|
90
|
+
const components = new Map()
|
|
91
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
92
|
+
const key = root(i)
|
|
93
|
+
if (!components.has(key)) components.set(key, [])
|
|
94
|
+
components.get(key).push(nodes[i])
|
|
95
|
+
}
|
|
96
|
+
const clusters = [], clusterOf = new Map(), members = new Map()
|
|
97
|
+
for (const list of components.values()) {
|
|
98
|
+
const componentId = `component-${digest(list.map(node => node.id))}`
|
|
99
|
+
for (let start = 0; start < list.length; start += CLUSTER_SIZE) {
|
|
100
|
+
const rows = list.slice(start, start + CLUSTER_SIZE)
|
|
101
|
+
const id = `cluster-${digest(rows.map(node => node.id))}`
|
|
102
|
+
const domains = [...new Set(rows.map(node => node.domain).filter(Boolean))].sort()
|
|
103
|
+
const representative = rows.reduce((best, node) => (node.degree || 0) > (best.degree || 0) ? node : best)
|
|
104
|
+
const strength = rows.reduce((sum, node) => sum + (Number(node.strength) || 0), 0) / rows.length
|
|
105
|
+
const cluster = { id, clusterId: id, componentId, kind: 'cluster', count: rows.length,
|
|
106
|
+
title: representative.title || representative.id, representativeId: representative.id,
|
|
107
|
+
domain: domains.length === 1 ? domains[0] : null, domains, strength, averageDecay: strength }
|
|
108
|
+
clusters.push(cluster); members.set(id, rows)
|
|
109
|
+
for (const node of rows) { node.clusterId = id; node.componentId = componentId; clusterOf.set(node.id, id) }
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
clusters.sort((a, b) => compare(a.id, b.id))
|
|
113
|
+
const columns = Math.max(1, Math.ceil(Math.sqrt(clusters.length)))
|
|
114
|
+
const side = Math.ceil(Math.sqrt(CLUSTER_SIZE)) * 28 + 80
|
|
115
|
+
let maxX = 0, maxY = 0
|
|
116
|
+
clusters.forEach((cluster, i) => {
|
|
117
|
+
cluster.x = (i % columns) * side; cluster.y = Math.floor(i / columns) * side
|
|
118
|
+
const rows = members.get(cluster.id), cols = Math.ceil(Math.sqrt(rows.length))
|
|
119
|
+
const half = Math.max(24, cols * 14)
|
|
120
|
+
cluster.bbox = { minX: cluster.x - half, maxX: cluster.x + half, minY: cluster.y - half, maxY: cluster.y + half }
|
|
121
|
+
maxX = Math.max(maxX, cluster.bbox.maxX); maxY = Math.max(maxY, cluster.bbox.maxY)
|
|
122
|
+
rows.forEach((node, j) => {
|
|
123
|
+
node.x = cluster.x + (j % cols - (cols - 1) / 2) * 28
|
|
124
|
+
node.y = cluster.y + (Math.floor(j / cols) - (Math.ceil(rows.length / cols) - 1) / 2) * 28
|
|
125
|
+
})
|
|
126
|
+
})
|
|
127
|
+
const clusterEdges = new Map()
|
|
128
|
+
for (const edge of edges) {
|
|
129
|
+
const from = clusterOf.get(edge.from), to = clusterOf.get(edge.to)
|
|
130
|
+
if (from === to) continue
|
|
131
|
+
const pair = [from, to].sort(), key = JSON.stringify(pair)
|
|
132
|
+
if (!clusterEdges.has(key)) clusterEdges.set(key, { from: pair[0], to: pair[1], kind: 'aggregate', count: 0, source: 'auto' })
|
|
133
|
+
clusterEdges.get(key).count++
|
|
134
|
+
}
|
|
135
|
+
const totals = { nodes: nodes.length, edges: edges.length, clusters: clusters.length, components: components.size,
|
|
136
|
+
memories: nodes.filter(node => node.kind === 'memory' || node.kind === 'global').length,
|
|
137
|
+
entities: nodes.filter(node => !['memory', 'global'].includes(node.kind) && !node.missing).length,
|
|
138
|
+
missing: nodes.filter(node => node.missing).length }
|
|
139
|
+
return { revision, scope, positionScope, nodes, byId, edges, sourceEdges, adjacencyOffsets, adjacencyEdges, clusters, members,
|
|
140
|
+
clusterEdges: [...clusterEdges.values()], domains: [...(graph.domains || [])], totals,
|
|
141
|
+
bbox: nodes.length ? { minX: -side / 2, minY: -side / 2, maxX, maxY } : null }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function* incidentEdges(model, ids, adjacency = null, outgoingOnly = false) {
|
|
145
|
+
if (adjacency) {
|
|
146
|
+
try {
|
|
147
|
+
const groups = typeof adjacency.selectMany === 'function'
|
|
148
|
+
? [adjacency.selectMany({ outgoing: ids, ...(outgoingOnly ? {} : { incoming: ids }) })]
|
|
149
|
+
: ids.flatMap(id => outgoingOnly ? [adjacency.outgoing(id)] : [adjacency.outgoing(id), adjacency.incoming(id)])
|
|
150
|
+
for (const rows of groups) for (const row of rows) {
|
|
151
|
+
const edge = model.sourceEdges[row.ordinal]
|
|
152
|
+
if (!Number.isSafeInteger(row.ordinal) || row.ordinal < 0 || !edge || edge.from !== row.from
|
|
153
|
+
|| edge.to !== row.to || edge.kind !== row.kind
|
|
154
|
+
|| !model.byId.has(edge.from) || !model.byId.has(edge.to)) throw new Error('topology does not match canonical edge metadata')
|
|
155
|
+
yield edge
|
|
156
|
+
}
|
|
157
|
+
} catch (cause) {
|
|
158
|
+
const error = new Error('graph adjacency selection failed; use canonical topology', { cause })
|
|
159
|
+
error.code = 'GRAPH_ADJACENCY_SELECTION_FAILED'
|
|
160
|
+
throw error
|
|
161
|
+
}
|
|
162
|
+
return
|
|
163
|
+
}
|
|
164
|
+
for (const id of ids) {
|
|
165
|
+
const index = model.byId.get(id)
|
|
166
|
+
if (index === undefined) continue
|
|
167
|
+
for (let i = model.adjacencyOffsets[index]; i < model.adjacencyOffsets[index + 1]; i++) yield model.edges[model.adjacencyEdges[i]]
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const matchesText = (value, query) => String(value ?? '').normalize('NFKC').trim().toLowerCase().includes(query)
|
|
172
|
+
|
|
173
|
+
function matchesEvidence(value, query) {
|
|
174
|
+
if (value === null || value === undefined) return false
|
|
175
|
+
const pending = [value], seen = new WeakSet()
|
|
176
|
+
while (pending.length) {
|
|
177
|
+
const item = pending.pop()
|
|
178
|
+
if (item === null || item === undefined) continue
|
|
179
|
+
if (typeof item !== 'object') { if (matchesText(item, query)) return true; continue }
|
|
180
|
+
if (seen.has(item)) continue
|
|
181
|
+
seen.add(item)
|
|
182
|
+
if (Array.isArray(item)) for (const child of item) pending.push(child)
|
|
183
|
+
else for (const [key, child] of Object.entries(item)) {
|
|
184
|
+
if (matchesText(key, query)) return true
|
|
185
|
+
pending.push(child)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return false
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function searchGraphOverview(model, query, start, cap) {
|
|
192
|
+
// One byte per authorized node, not a second full result graph or a query
|
|
193
|
+
// cache. Scan every match for exact totals while retaining only this page.
|
|
194
|
+
const linked = new Uint8Array(model.nodes.length)
|
|
195
|
+
for (const edge of model.edges) {
|
|
196
|
+
if (![edge.note, edge.kind, edge.source, edge.rule].some(value => value !== null && value !== undefined && matchesText(value, query))
|
|
197
|
+
&& !matchesEvidence(edge.evidence, query)) continue
|
|
198
|
+
linked[model.byId.get(edge.from)] = 1
|
|
199
|
+
linked[model.byId.get(edge.to)] = 1
|
|
200
|
+
}
|
|
201
|
+
const selected = []
|
|
202
|
+
let total = 0
|
|
203
|
+
for (let i = 0; i < model.nodes.length; i++) {
|
|
204
|
+
const node = model.nodes[i]
|
|
205
|
+
if (!linked[i] && !matchesText(node.id, query) && !matchesText(node.title, query)) continue
|
|
206
|
+
linked[i] = 1
|
|
207
|
+
if (total >= start && selected.length < cap) selected.push(node)
|
|
208
|
+
total++
|
|
209
|
+
}
|
|
210
|
+
return { selected, total, matches: linked }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Cache keys include library path and the caller's complete visibility context. */
|
|
214
|
+
export function cachedGraphOverview({ key, revision, build, adjacency: openAdjacency, onAdjacencyError }, args = {}) {
|
|
215
|
+
graphQuery(args)
|
|
216
|
+
const identity = canonicalKey(key), cacheKey = JSON.stringify([identity, revision])
|
|
217
|
+
let model = revision ? cache.get(cacheKey) : null
|
|
218
|
+
let graph, adjacency = null
|
|
219
|
+
const source = () => graph ||= (model ? { nodes: model.nodes, edges: model.sourceEdges, domains: model.domains } : build())
|
|
220
|
+
// Validate the publication on every request, including model-cache hits. A
|
|
221
|
+
// handle can also fall back during a section read if files change afterwards.
|
|
222
|
+
// Complete classic graphs already need the canonical model and its CSR.
|
|
223
|
+
// Reopening a disk adjacency per page adds I/O without reducing that work.
|
|
224
|
+
if (openAdjacency && args.layout !== 'classic') {
|
|
225
|
+
try { adjacency = openAdjacency(source) } catch (error) { onAdjacencyError?.(error) }
|
|
226
|
+
// A rebuild's request-scoped source facade may scan all edges per lookup.
|
|
227
|
+
// The current canonical model already has CSR; use it for this request.
|
|
228
|
+
if (adjacency?.backend === 'source') adjacency = null
|
|
229
|
+
}
|
|
230
|
+
if (!model) {
|
|
231
|
+
model = buildGraphOverview(source(), { revision, scope: args.scope || 'private', positionScope: `graph-${digest(identity)}` })
|
|
232
|
+
if (revision) cache.set(cacheKey, model)
|
|
233
|
+
}
|
|
234
|
+
try { return selectGraphOverview(model, args, adjacency) } catch (error) {
|
|
235
|
+
if (!adjacency || error.code !== 'GRAPH_ADJACENCY_SELECTION_FAILED') throw error
|
|
236
|
+
onAdjacencyError?.(error)
|
|
237
|
+
return selectGraphOverview(model, args)
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export function selectGraphOverview(model, { clusterId, bbox, zoom = 0, limit, offset = 0, focusId, depth = 1, query, layout } = {}, adjacency = null) {
|
|
242
|
+
const classic = layout === 'classic'
|
|
243
|
+
const { box, detail, cap, start, hops, search } = graphQuery({ clusterId, bbox, zoom, limit, offset, focusId, depth, query, layout })
|
|
244
|
+
let candidates, selectedEdges, selected, total, matches
|
|
245
|
+
if (search) {
|
|
246
|
+
({ selected, total, matches } = searchGraphOverview(model, search, start, cap))
|
|
247
|
+
} else if (classic) {
|
|
248
|
+
candidates = model.nodes
|
|
249
|
+
} else if (clusterId) {
|
|
250
|
+
candidates = model.members.get(String(clusterId))
|
|
251
|
+
if (!candidates) throw new Error('unknown or inaccessible graph cluster')
|
|
252
|
+
} else if (focusId) {
|
|
253
|
+
if (!model.byId.has(String(focusId))) throw new Error('unknown or inaccessible graph focus')
|
|
254
|
+
const focus = String(focusId), seen = new Set([focus])
|
|
255
|
+
let frontier = [focus]
|
|
256
|
+
for (let hop = 0; hop < hops && frontier.length; hop++) {
|
|
257
|
+
const next = []
|
|
258
|
+
for (const edge of incidentEdges(model, frontier, adjacency)) {
|
|
259
|
+
for (const id of [edge.from, edge.to]) if (!seen.has(id)) { seen.add(id); next.push(id) }
|
|
260
|
+
}
|
|
261
|
+
frontier = next
|
|
262
|
+
}
|
|
263
|
+
candidates = [focus, ...[...seen].filter(id => id !== focus).sort(compare)].map(id => model.nodes[model.byId.get(id)])
|
|
264
|
+
} else if (detail) {
|
|
265
|
+
candidates = model.clusters.filter(cluster => intersects(cluster.bbox, box)).flatMap(cluster => model.members.get(cluster.id))
|
|
266
|
+
} else candidates = model.clusters
|
|
267
|
+
if (!search) {
|
|
268
|
+
if (box && !classic) candidates = candidates.filter(node => node.kind === 'cluster' ? intersects(node.bbox, box) : inside(node, box))
|
|
269
|
+
total = candidates.length
|
|
270
|
+
selected = candidates.slice(start, start + cap)
|
|
271
|
+
}
|
|
272
|
+
const ids = new Set(selected.map(node => node.id))
|
|
273
|
+
if (detail) {
|
|
274
|
+
const seen = new Set()
|
|
275
|
+
selectedEdges = []
|
|
276
|
+
for (const edge of incidentEdges(model, selected.map(node => node.id), adjacency, true)) {
|
|
277
|
+
// Classic pages are assembled into one complete graph by the client.
|
|
278
|
+
// Keep cross-page edges; every endpoint already belongs to this authorized model.
|
|
279
|
+
const targetSelected = classic ? !search || matches[model.byId.get(edge.to)] : ids.has(edge.to)
|
|
280
|
+
if (ids.has(edge.from) && targetSelected && !seen.has(edge)) { seen.add(edge); selectedEdges.push(edge) }
|
|
281
|
+
}
|
|
282
|
+
selectedEdges.sort(compareEdges)
|
|
283
|
+
} else selectedEdges = model.clusterEdges.filter(edge => ids.has(edge.from) && ids.has(edge.to))
|
|
284
|
+
const next = start + selected.length
|
|
285
|
+
// Detach responses: neither a caller nor a canvas may mutate cached metadata.
|
|
286
|
+
const displayNodes = classic ? selected.map(({ x, y, clusterId, componentId, ...node }) => node) : selected
|
|
287
|
+
return structuredClone({ overview: true, mode: classic ? 'classic' : detail ? 'detail' : 'clusters', revision: model.revision,
|
|
288
|
+
scope: model.scope, positionScope: model.positionScope, nodes: displayNodes, edges: selectedEdges, clusters: detail ? [] : selected,
|
|
289
|
+
totals: model.totals, total, bbox: model.bbox, domains: model.domains,
|
|
290
|
+
limit: cap, offset: start, nextOffset: next < total ? next : null,
|
|
291
|
+
truncated: next < total, clusterId: search || classic ? null : clusterId || null, focusId: search || classic ? null : focusId || null,
|
|
292
|
+
...(search ? { query: search } : {}) })
|
|
293
|
+
}
|