@memberjunction/core-entities 6.2.1 → 6.3.0-edge.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/custom/MJUserViewEntityExtended.d.ts +4 -7
  3. package/dist/custom/MJUserViewEntityExtended.d.ts.map +1 -1
  4. package/dist/custom/MJUserViewEntityExtended.js +15 -97
  5. package/dist/custom/MJUserViewEntityExtended.js.map +1 -1
  6. package/dist/engines/CanonGraphEngine.d.ts +122 -0
  7. package/dist/engines/CanonGraphEngine.d.ts.map +1 -0
  8. package/dist/engines/CanonGraphEngine.js +495 -0
  9. package/dist/engines/CanonGraphEngine.js.map +1 -0
  10. package/dist/engines/UserInfoEngine.d.ts.map +1 -1
  11. package/dist/engines/UserInfoEngine.js +12 -7
  12. package/dist/engines/UserInfoEngine.js.map +1 -1
  13. package/dist/engines/conversations.d.ts +159 -10
  14. package/dist/engines/conversations.d.ts.map +1 -1
  15. package/dist/engines/conversations.js +434 -18
  16. package/dist/engines/conversations.js.map +1 -1
  17. package/dist/generated/entities/__mj.d.ts +4237 -899
  18. package/dist/generated/entities/__mj.d.ts.map +1 -1
  19. package/dist/generated/entities/__mj.js +4605 -448
  20. package/dist/generated/entities/__mj.js.map +1 -1
  21. package/dist/generated/queries/__mj.d.ts +269 -0
  22. package/dist/generated/queries/__mj.d.ts.map +1 -0
  23. package/dist/generated/queries/__mj.js +100 -0
  24. package/dist/generated/queries/__mj.js.map +1 -0
  25. package/dist/generated/queries/index.d.ts +2 -0
  26. package/dist/generated/queries/index.d.ts.map +1 -0
  27. package/dist/generated/queries/index.js +4 -0
  28. package/dist/generated/queries/index.js.map +1 -0
  29. package/dist/generated/remote_operations.d.ts +50 -22
  30. package/dist/generated/remote_operations.d.ts.map +1 -1
  31. package/dist/generated/remote_operations.js +3 -3
  32. package/dist/generated/remote_operations.js.map +1 -1
  33. package/dist/graph/BaseGraphEdgeProvider.d.ts +158 -0
  34. package/dist/graph/BaseGraphEdgeProvider.d.ts.map +1 -0
  35. package/dist/graph/BaseGraphEdgeProvider.js +70 -0
  36. package/dist/graph/BaseGraphEdgeProvider.js.map +1 -0
  37. package/dist/graph/GraphEngine.d.ts +255 -0
  38. package/dist/graph/GraphEngine.d.ts.map +1 -0
  39. package/dist/graph/GraphEngine.js +1066 -0
  40. package/dist/graph/GraphEngine.js.map +1 -0
  41. package/dist/graph/GraphExpansion.d.ts +142 -0
  42. package/dist/graph/GraphExpansion.d.ts.map +1 -0
  43. package/dist/graph/GraphExpansion.js +87 -0
  44. package/dist/graph/GraphExpansion.js.map +1 -0
  45. package/dist/graph/index.d.ts +15 -0
  46. package/dist/graph/index.d.ts.map +1 -0
  47. package/dist/graph/index.js +30 -0
  48. package/dist/graph/index.js.map +1 -0
  49. package/dist/graph/providers/AlternateBaseViewEdgeProvider.d.ts +16 -0
  50. package/dist/graph/providers/AlternateBaseViewEdgeProvider.d.ts.map +1 -0
  51. package/dist/graph/providers/AlternateBaseViewEdgeProvider.js +115 -0
  52. package/dist/graph/providers/AlternateBaseViewEdgeProvider.js.map +1 -0
  53. package/dist/graph/providers/EntityMetadataEdgeProvider.d.ts +17 -0
  54. package/dist/graph/providers/EntityMetadataEdgeProvider.d.ts.map +1 -0
  55. package/dist/graph/providers/EntityMetadataEdgeProvider.js +145 -0
  56. package/dist/graph/providers/EntityMetadataEdgeProvider.js.map +1 -0
  57. package/dist/graph/providers/ForeignKeyEdgeProvider.d.ts +25 -0
  58. package/dist/graph/providers/ForeignKeyEdgeProvider.d.ts.map +1 -0
  59. package/dist/graph/providers/ForeignKeyEdgeProvider.js +131 -0
  60. package/dist/graph/providers/ForeignKeyEdgeProvider.js.map +1 -0
  61. package/dist/graph/providers/JoinEntityEdgeProvider.d.ts +37 -0
  62. package/dist/graph/providers/JoinEntityEdgeProvider.d.ts.map +1 -0
  63. package/dist/graph/providers/JoinEntityEdgeProvider.js +170 -0
  64. package/dist/graph/providers/JoinEntityEdgeProvider.js.map +1 -0
  65. package/dist/graph/providers/QueryEdgeProvider.d.ts +33 -0
  66. package/dist/graph/providers/QueryEdgeProvider.d.ts.map +1 -0
  67. package/dist/graph/providers/QueryEdgeProvider.js +120 -0
  68. package/dist/graph/providers/QueryEdgeProvider.js.map +1 -0
  69. package/dist/graph/providers/QueryMetadataEdgeProvider.d.ts +18 -0
  70. package/dist/graph/providers/QueryMetadataEdgeProvider.d.ts.map +1 -0
  71. package/dist/graph/providers/QueryMetadataEdgeProvider.js +163 -0
  72. package/dist/graph/providers/QueryMetadataEdgeProvider.js.map +1 -0
  73. package/dist/graph/providers/RecordLinkEdgeProvider.d.ts +20 -0
  74. package/dist/graph/providers/RecordLinkEdgeProvider.d.ts.map +1 -0
  75. package/dist/graph/providers/RecordLinkEdgeProvider.js +172 -0
  76. package/dist/graph/providers/RecordLinkEdgeProvider.js.map +1 -0
  77. package/dist/index.d.ts +3 -0
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/index.js +5 -0
  80. package/dist/index.js.map +1 -1
  81. package/package.json +6 -6
@@ -0,0 +1,1066 @@
1
+ import { BaseEngine, EntityPermissionType, LogError, LogStatus, RunView, } from '@memberjunction/core';
2
+ import { EscapeSQLString, IndexByUUID, MJGlobal, UUIDMap, UUIDSet, UUIDsEqual } from '@memberjunction/global';
3
+ import { MJGraphEdgeEntity, MJGraphEntity, } from '../generated/entity_subclasses.js';
4
+ import { QueryEngine } from '../engines/QueryEngine.js';
5
+ import { BaseGraphEdgeProvider, FormatGraphNodeKey, IsGraphDataProvider, MatchesEdgeTypeFilter, } from './BaseGraphEdgeProvider.js';
6
+ /** Depth used when the caller gives none. */
7
+ export const GRAPH_DEFAULT_DEPTH = 2;
8
+ /** Hard upper bound on traversal depth. */
9
+ export const GRAPH_MAX_DEPTH = 4;
10
+ /** Node budget used when the caller gives none. */
11
+ export const GRAPH_DEFAULT_MAX_NODES = 50;
12
+ /** Hard upper bound on nodes a traversal returns. */
13
+ export const GRAPH_MAX_NODES = 200;
14
+ /** Row cap on the stored edges one expansion step reads on demand. */
15
+ export const GRAPH_MAX_STORED_EDGES_PER_STEP = 1000;
16
+ /**
17
+ * Server operation key (`ServerOperationScopeManager`) under which the Content Pipeline `Graph` stage
18
+ * saves the `Inferred` edges its content source's `GraphOverlay` policy approves (every
19
+ * `ConceptTaxonomyMode` except `propose-only`). `MJGraphEdgeEntityServer` lets a new `Inferred` edge
20
+ * start `Approved` without `Graph: Approve Edges` only inside this scope. Client CRUD entry points
21
+ * (GraphQL, REST, transaction groups) run inside a client CRUD boundary that masks every outer scope,
22
+ * so an API caller cannot enter it; only server code that names this key can.
23
+ */
24
+ export const GRAPH_PIPELINE_EDGE_APPROVAL_OPERATION = 'ContentPipeline.GraphStage.ApproveInferredEdges';
25
+ /** Per-hop decay applied to best-first path scores, so near nodes outrank far ones. */
26
+ const HOP_DECAY = 0.85;
27
+ const GRAPH_EDGES_ENTITY = 'MJ: Graph Edges';
28
+ const GRAPHS_ENTITY = 'MJ: Graphs';
29
+ const GRAPH_CONCEPTS_ENTITY = 'MJ: Graph Concepts';
30
+ const STORED_EDGE_FIELDS = [
31
+ 'ID',
32
+ 'GraphID',
33
+ 'Graph',
34
+ 'EdgeTypeID',
35
+ 'EdgeType',
36
+ 'SourceEntityID',
37
+ 'SourceEntity',
38
+ 'SourceRecordID',
39
+ 'TargetEntityID',
40
+ 'TargetEntity',
41
+ 'TargetRecordID',
42
+ 'Weight',
43
+ 'Description',
44
+ 'Attributes',
45
+ 'Origin',
46
+ 'Status',
47
+ 'Confidence',
48
+ ];
49
+ /**
50
+ * Semantic Graph Engine (`WS-4.2` / `plans/canon-semantic-graph.md`).
51
+ *
52
+ * Caches graph metadata (graphs, edge types, endpoints, providers, concepts, lookup tables) and,
53
+ * for `Preload` graphs only, their approved stored edges, loaded per graph on its first traversal
54
+ * and reloaded per graph after a change. `OnDemand` graphs read stored edges per expansion step with
55
+ * one bounded RunView. Derived edges come from the graph's active `MJ: Graph Edge Providers`.
56
+ *
57
+ * **Lazily configured.** Nothing loads at startup; the first caller of `Config` pays for it.
58
+ *
59
+ * **Whose data the cache holds.** On a server `BaseEngine` loads every config as the MJ system user,
60
+ * so the shared cache never takes the first caller's scope. Nothing cached is handed to a caller
61
+ * unchecked: every node returned is checked AS THE CALLER (and as every audience reader) at the hop
62
+ * it is reached, with one batched `RunViews` per principal per hop (`[pk] IN (...)` per entity, so
63
+ * entity permissions and row-level security apply), and cached stored edges are used only for a
64
+ * principal who could read every one of them anyway.
65
+ */
66
+ export class GraphEngine extends BaseEngine {
67
+ constructor() {
68
+ super(...arguments);
69
+ this._graphs = [];
70
+ this._graphTypes = [];
71
+ this._edgeTypes = [];
72
+ this._edgeTypeEndpoints = [];
73
+ this._edgeProviders = [];
74
+ this._concepts = [];
75
+ this._conceptTypes = [];
76
+ this._authorityTiers = [];
77
+ /**
78
+ * Approved stored edges of the `Preload` graphs traversed so far, one entry per graph, loaded on a
79
+ * graph's first traversal. A change drops only the entries it affects (see
80
+ * {@link HandleIndividualBaseEntityEvent}); the next traversal of that graph reloads it alone.
81
+ */
82
+ this.preloadedEdges = new UUIDMap();
83
+ /** In-flight preload reads by graph ID, so concurrent traversals share one read per graph. */
84
+ this.preloadReads = new UUIDMap();
85
+ /** Bumped by every invalidation, so a read that started before one is not cached after it. */
86
+ this.preloadGeneration = 0;
87
+ /** Field and alternate-view lookups for metadata nodes; rebuilt when the provider's entity list changes. */
88
+ this.metadataNodeIndex = null;
89
+ }
90
+ static get Instance() {
91
+ return super.getInstance();
92
+ }
93
+ async Config(forceRefresh, contextUser, provider) {
94
+ const configs = [
95
+ { Type: 'entity', EntityName: 'MJ: Graphs', PropertyName: '_graphs', CacheLocal: true },
96
+ { Type: 'entity', EntityName: 'MJ: Graph Types', PropertyName: '_graphTypes', CacheLocal: true },
97
+ { Type: 'entity', EntityName: 'MJ: Graph Edge Types', PropertyName: '_edgeTypes', CacheLocal: true },
98
+ { Type: 'entity', EntityName: 'MJ: Graph Edge Type Endpoints', PropertyName: '_edgeTypeEndpoints', CacheLocal: true },
99
+ { Type: 'entity', EntityName: 'MJ: Graph Edge Providers', PropertyName: '_edgeProviders', CacheLocal: true },
100
+ { Type: 'entity', EntityName: GRAPH_CONCEPTS_ENTITY, PropertyName: '_concepts', CacheLocal: true },
101
+ { Type: 'entity', EntityName: 'MJ: Graph Concept Types', PropertyName: '_conceptTypes', CacheLocal: true },
102
+ { Type: 'entity', EntityName: 'MJ: Graph Authority Tiers', PropertyName: '_authorityTiers', CacheLocal: true },
103
+ ];
104
+ await this.Load(configs, provider, forceRefresh, contextUser);
105
+ }
106
+ /** A first or forced (re)load also drops every preloaded graph; each reloads on its next traversal. */
107
+ async Load(configs, provider, forceRefresh = false, contextUser) {
108
+ if (forceRefresh || !this.Loaded) {
109
+ this.invalidatePreloadedEdges(null);
110
+ }
111
+ return super.Load(configs, provider, forceRefresh, contextUser);
112
+ }
113
+ /**
114
+ * Drops the preload entries a change affects, and nothing else.
115
+ *
116
+ * There is deliberately no `AdditionalLoading` override: `BaseEngine` turns off in-place cache
117
+ * updates for an engine that has one, so every concept or edge-type save would reload that whole
118
+ * config and then every Preload graph's edges. Without it, the cached configs update in place and
119
+ * stored edges load per graph, lazily:
120
+ * - a `MJ: Graph Edges` save or delete drops the edge's graph, and any graph whose entry holds that
121
+ * edge ID (an edge moved to another graph);
122
+ * - a `MJ: Graphs` save or delete drops that graph (its `LoadMode` or `Status` may have changed);
123
+ * - a change that does not say which row (a remote invalidation) drops every entry.
124
+ */
125
+ async HandleIndividualBaseEntityEvent(event) {
126
+ const entityName = (event.baseEntity?.EntityInfo?.Name ?? event.entityName ?? '').trim().toLowerCase();
127
+ const changed = event.type === 'save' || event.type === 'delete' || event.type === 'remote-invalidate';
128
+ if (changed && entityName === GRAPH_EDGES_ENTITY.toLowerCase()) {
129
+ const edge = event.baseEntity instanceof MJGraphEdgeEntity ? event.baseEntity : null;
130
+ this.invalidatePreloadedEdges(edge ? (graph) => UUIDsEqual(graph, edge.GraphID) || this.preloadHoldsEdge(graph, edge.ID) : null);
131
+ }
132
+ else if (changed && entityName === GRAPHS_ENTITY.toLowerCase()) {
133
+ const graphRow = event.baseEntity instanceof MJGraphEntity ? event.baseEntity : null;
134
+ this.invalidatePreloadedEdges(graphRow ? (graph) => UUIDsEqual(graph, graphRow.ID) : null);
135
+ }
136
+ return super.HandleIndividualBaseEntityEvent(event);
137
+ }
138
+ /** Drops the preload entries whose graph ID matches `affects` (every entry when `null`). */
139
+ invalidatePreloadedEdges(affects) {
140
+ this.preloadGeneration++;
141
+ for (const map of [this.preloadedEdges, this.preloadReads]) {
142
+ for (const graphId of Array.from(map.Keys())) {
143
+ if (affects === null || affects(graphId)) {
144
+ map.Delete(graphId);
145
+ }
146
+ }
147
+ }
148
+ }
149
+ preloadHoldsEdge(graphId, edgeId) {
150
+ return this.preloadedEdges.Get(graphId)?.EdgeIds.Has(edgeId) === true;
151
+ }
152
+ get Graphs() {
153
+ return this.GetConfigData('_graphs') ?? this._graphs;
154
+ }
155
+ get GraphTypes() {
156
+ return this.GetConfigData('_graphTypes') ?? this._graphTypes;
157
+ }
158
+ get EdgeTypes() {
159
+ return this.GetConfigData('_edgeTypes') ?? this._edgeTypes;
160
+ }
161
+ get EdgeTypeEndpoints() {
162
+ return this.GetConfigData('_edgeTypeEndpoints') ?? this._edgeTypeEndpoints;
163
+ }
164
+ get EdgeProviders() {
165
+ return this.GetConfigData('_edgeProviders') ?? this._edgeProviders;
166
+ }
167
+ /**
168
+ * Every cached concept, loaded as the engine's identity. Never hand these to a caller directly:
169
+ * check them with {@link FilterNodesForUser} first (as `CanonGraphEngine.FindConcepts` does).
170
+ */
171
+ get Concepts() {
172
+ return this.GetConfigData('_concepts') ?? this._concepts;
173
+ }
174
+ get ConceptTypes() {
175
+ return this.GetConfigData('_conceptTypes') ?? this._conceptTypes;
176
+ }
177
+ get AuthorityTiers() {
178
+ return this.GetConfigData('_authorityTiers') ?? this._authorityTiers;
179
+ }
180
+ /**
181
+ * Find an ACTIVE `MJ: Graphs` row by `Name` (case-insensitive) or `ID`. An unknown or disabled
182
+ * graph returns `undefined`; traversal of it returns nothing.
183
+ */
184
+ GetGraph(graphNameOrId) {
185
+ const trimmed = graphNameOrId?.trim();
186
+ if (!trimmed) {
187
+ return undefined;
188
+ }
189
+ const lower = trimmed.toLowerCase();
190
+ return this.Graphs.find((g) => g.Status === 'Active' && (g.Name.trim().toLowerCase() === lower || UUIDsEqual(g.ID, trimmed)));
191
+ }
192
+ /**
193
+ * Validate whether `entityId` is permitted on `side` (`'Source'` or `'Target'`) of `edgeTypeId`
194
+ * according to `MJ: Graph Edge Type Endpoints`. When no endpoint rows exist for `(edgeTypeId, side)`,
195
+ * any entity is permitted.
196
+ */
197
+ ValidateEdgeEndpoint(edgeTypeId, side, entityId) {
198
+ const constraints = this.EdgeTypeEndpoints.filter((ep) => UUIDsEqual(ep.EdgeTypeID, edgeTypeId) && ep.Side === side);
199
+ if (constraints.length === 0) {
200
+ return true;
201
+ }
202
+ return constraints.some((ep) => UUIDsEqual(ep.EntityID, entityId));
203
+ }
204
+ /**
205
+ * The canonical key of a node (`<entityID>|<recordID>`), resolving the entity through metadata.
206
+ */
207
+ GetNodeKey(node) {
208
+ return this.nodeKey(node, this.graphProvider());
209
+ }
210
+ /**
211
+ * The nodes in `nodes` that `user` — and every one of `audienceReaders` — may see, with display
212
+ * labels, keyed by node key. Data records (including concepts) are read as each principal with one
213
+ * batched `RunViews` per principal, so entity permissions and row-level security apply; metadata
214
+ * nodes use entity `CanRead`, `UserCanRun` (queries) and `CanRead` + `IsUsable` (alternate views).
215
+ * A concept appears only when {@link IsGraphConceptStatusVisible} for `options.IncludeProposed`.
216
+ */
217
+ async FilterNodesForUser(nodes, user, audienceReaders, options = {}) {
218
+ if (!user || !nodes || nodes.length === 0) {
219
+ return new Map();
220
+ }
221
+ const provider = this.graphProvider(options.Provider);
222
+ return this.resolveVisibleNodes(nodes, this.principals(user, audienceReaders), provider, options.IncludeProposed === true);
223
+ }
224
+ /**
225
+ * Stored and derived edges incident to `node` in `graphName` whose endpoints the caller (and any
226
+ * `options.AudienceReaders`) may see. An unknown or inactive graph yields no edges. Every read made
227
+ * for the caller goes through `provider` when one is given (see {@link Subgraph}).
228
+ */
229
+ async GetEdges(graphName, node, options, user, provider) {
230
+ const graph = this.GetGraph(graphName);
231
+ if (!user || !graph) {
232
+ return [];
233
+ }
234
+ const dataProvider = this.graphProvider(provider);
235
+ const principals = this.principals(user, options.AudienceReaders);
236
+ const start = this.normalizeNodeRef(node, dataProvider);
237
+ const rawEdges = await this.getEdgesForFrontier(graph, [start], options, principals, dataProvider);
238
+ if (rawEdges.length === 0) {
239
+ return [];
240
+ }
241
+ const endpoints = [start];
242
+ for (const edge of rawEdges) {
243
+ endpoints.push(edge.Source, edge.Target);
244
+ }
245
+ const visible = await this.resolveVisibleNodes(endpoints, principals, dataProvider, options.IncludeProposed === true);
246
+ return rawEdges.filter((edge) => visible.has(this.nodeKey(edge.Source, dataProvider)) && visible.has(this.nodeKey(edge.Target, dataProvider)));
247
+ }
248
+ /**
249
+ * Best-first bounded expansion around `seeds` in `graphName`.
250
+ *
251
+ * Each step reads the frontier's edges, ranks candidate neighbors by path score (product of edge
252
+ * weights, decayed per hop; ties broken by node key then edge ID), checks the candidates'
253
+ * visibility for the caller and every audience reader in one batch, and admits visible ones until
254
+ * `MaxNodes`. Only admitted nodes are expanded, so traversal never crosses a node some principal
255
+ * cannot see. Every admitted node carries the path that reached it.
256
+ *
257
+ * An unknown or inactive graph returns an empty subgraph with a `Message`.
258
+ *
259
+ * `provider`, when given, carries every read made for the caller and the readers (node visibility,
260
+ * on-demand stored edges, derived-edge providers), e.g. the request's own provider on a server. The
261
+ * engine's cached metadata and Preload edges still come from the provider the engine was configured
262
+ * with.
263
+ */
264
+ async Subgraph(graphName, seeds, options, user, provider) {
265
+ if (!user || !seeds || seeds.length === 0) {
266
+ return { Nodes: [], Edges: [] };
267
+ }
268
+ const graph = this.GetGraph(graphName);
269
+ if (!graph) {
270
+ return { Nodes: [], Edges: [], Message: `Graph "${graphName}" was not found or is not active.` };
271
+ }
272
+ const dataProvider = this.graphProvider(provider);
273
+ const principals = this.principals(user, options.AudienceReaders);
274
+ const maxDepth = ClampGraphDepth(options.Depth ?? options.MaxDepth);
275
+ const maxNodes = ClampGraphMaxNodes(options.MaxNodes);
276
+ const minWeight = options.MinWeight ?? 0;
277
+ const includeProposed = options.IncludeProposed === true;
278
+ const discovered = new Map();
279
+ const visibleByKey = new Map();
280
+ let frontier = await this.admitSeeds(seeds, principals, maxNodes, dataProvider, includeProposed, discovered, visibleByKey);
281
+ let capped = false;
282
+ for (let hop = 1; hop <= maxDepth && frontier.length > 0; hop++) {
283
+ const stepEdges = await this.getEdgesForFrontier(graph, frontier.map((f) => f.Node), options, principals, dataProvider);
284
+ const candidates = this.rankCandidates(stepEdges, frontier, discovered, minWeight, hop, dataProvider);
285
+ const visible = await this.resolveVisibleNodes(this.uniqueNeighborRefs(candidates), principals, dataProvider, includeProposed);
286
+ const admitted = this.admitCandidates(candidates, visible, maxNodes, hop, discovered, visibleByKey);
287
+ capped = capped || admitted.Capped;
288
+ frontier = admitted.Next;
289
+ }
290
+ const edges = new Map((await this.collectEdgesBetween(graph, discovered, options, principals, dataProvider)).map((e) => [e.ID, e]));
291
+ const nodes = [];
292
+ for (const d of discovered.values()) {
293
+ const view = visibleByKey.get(d.Key);
294
+ if (view) {
295
+ nodes.push({ ...view, Hop: d.Hop, PathWeight: d.PathWeight, ParentKey: d.ParentKey, ViaEdgeID: d.ViaEdge?.ID ?? null });
296
+ }
297
+ if (d.ViaEdge && !edges.has(d.ViaEdge.ID)) {
298
+ edges.set(d.ViaEdge.ID, d.ViaEdge); // the path edge, even if the final read was capped
299
+ }
300
+ }
301
+ return {
302
+ Nodes: nodes,
303
+ Edges: Array.from(edges.values()).sort((a, b) => compareStrings(a.ID, b.ID)),
304
+ Message: capped ? `Expansion stopped at the ${maxNodes}-node limit.` : undefined,
305
+ };
306
+ }
307
+ /**
308
+ * Alias for {@link Subgraph} used by RAG and pipeline callers.
309
+ */
310
+ async Expand(graphName, seeds, options, user, provider) {
311
+ return this.Subgraph(graphName, seeds, options, user, provider);
312
+ }
313
+ /**
314
+ * Render a {@link GraphSubgraph} as a compact, deterministic Markdown block for LLM prompt injection.
315
+ */
316
+ DescribeForPrompt(subgraph) {
317
+ if (subgraph.Nodes.length === 0 && subgraph.Edges.length === 0) {
318
+ return subgraph.Message ? `No semantic graph context found. ${subgraph.Message}` : 'No semantic graph context found.';
319
+ }
320
+ const provider = this.graphProvider();
321
+ const nodeByKey = new Map();
322
+ for (const node of subgraph.Nodes) {
323
+ nodeByKey.set(node.Key, node);
324
+ }
325
+ const lines = ['### Semantic Graph Context'];
326
+ if (subgraph.Nodes.length > 0) {
327
+ lines.push('**Nodes:**');
328
+ for (const n of subgraph.Nodes) {
329
+ const descSuffix = n.Description ? ` — ${n.Description}` : '';
330
+ lines.push(`- **[${n.EntityName}] ${n.Label}** (\`${n.RecordID}\`)${descSuffix}`);
331
+ }
332
+ }
333
+ if (subgraph.Edges.length > 0) {
334
+ lines.push('');
335
+ lines.push('**Relationships:**');
336
+ for (const e of subgraph.Edges) {
337
+ const sLabel = nodeByKey.get(this.nodeKey(e.Source, provider))?.Label ?? `${e.Source.EntityName}:${e.Source.RecordID}`;
338
+ const tLabel = nodeByKey.get(this.nodeKey(e.Target, provider))?.Label ?? `${e.Target.EntityName}:${e.Target.RecordID}`;
339
+ const arrow = e.IsDirected ? '-->' : '<-->';
340
+ const desc = e.Description ? ` (${e.Description})` : '';
341
+ lines.push(`- "${sLabel}" --[${e.TypeName} (${e.Weight.toFixed(2)})]${arrow} "${tLabel}"${desc}`);
342
+ }
343
+ }
344
+ if (subgraph.Message) {
345
+ lines.push('', `_${subgraph.Message}_`);
346
+ }
347
+ return lines.join('\n');
348
+ }
349
+ // ----- Provider + principals ------------------------------------------------
350
+ /** `requested` when it can serve graph reads, else the provider the engine is bound to. */
351
+ graphProvider(requested) {
352
+ if (requested && IsGraphDataProvider(requested)) {
353
+ return requested;
354
+ }
355
+ const p = this.ProviderToUse;
356
+ if (IsGraphDataProvider(p)) {
357
+ return p;
358
+ }
359
+ throw new Error('GraphEngine: the bound provider does not implement metadata, RunView and RunQuery.');
360
+ }
361
+ /** `[user, ...readers]` with each user once (by ID) and the caller first. */
362
+ principals(user, audienceReaders) {
363
+ const seen = new UUIDSet(user.ID ? [user.ID] : []);
364
+ const result = [user];
365
+ for (const reader of audienceReaders ?? []) {
366
+ if (!reader) {
367
+ continue;
368
+ }
369
+ if (reader.ID && seen.Has(reader.ID)) {
370
+ continue;
371
+ }
372
+ if (reader.ID) {
373
+ seen.Add(reader.ID);
374
+ }
375
+ result.push(reader);
376
+ }
377
+ return result;
378
+ }
379
+ // ----- Traversal steps ------------------------------------------------------
380
+ async admitSeeds(seeds, principals, maxNodes, provider, includeProposed, discovered, visibleByKey) {
381
+ const normalized = seeds.map((s) => this.normalizeNodeRef(s, provider));
382
+ const visible = await this.resolveVisibleNodes(normalized, principals, provider, includeProposed);
383
+ const frontier = [];
384
+ for (const seed of normalized) {
385
+ const key = this.nodeKey(seed, provider);
386
+ const view = visible.get(key);
387
+ if (!view || discovered.has(key) || discovered.size >= maxNodes) {
388
+ continue;
389
+ }
390
+ const node = { Node: seed, Key: key, PathWeight: 1.0, Hop: 0, ParentKey: null, ViaEdge: null };
391
+ discovered.set(key, node);
392
+ visibleByKey.set(key, view);
393
+ frontier.push(node);
394
+ }
395
+ return frontier;
396
+ }
397
+ /** Candidate neighbors of the frontier, best first, with a deterministic tie-break. */
398
+ rankCandidates(stepEdges, frontier, discovered, minWeight, hop, provider) {
399
+ const frontierByKey = new Map(frontier.map((f) => [f.Key, f]));
400
+ const decay = Math.pow(HOP_DECAY, hop - 1);
401
+ const candidates = [];
402
+ for (const edge of stepEdges) {
403
+ if (edge.Weight < minWeight) {
404
+ continue;
405
+ }
406
+ const sourceKey = this.nodeKey(edge.Source, provider);
407
+ const targetKey = this.nodeKey(edge.Target, provider);
408
+ const fromSource = frontierByKey.get(sourceKey);
409
+ const fromTarget = frontierByKey.get(targetKey);
410
+ if (fromSource && !discovered.has(targetKey)) {
411
+ candidates.push({ Edge: edge, Parent: fromSource, Neighbor: edge.Target, NeighborKey: targetKey, Score: fromSource.PathWeight * edge.Weight * decay });
412
+ }
413
+ else if (fromTarget && !discovered.has(sourceKey)) {
414
+ candidates.push({ Edge: edge, Parent: fromTarget, Neighbor: edge.Source, NeighborKey: sourceKey, Score: fromTarget.PathWeight * edge.Weight * decay });
415
+ }
416
+ }
417
+ return candidates.sort((a, b) => b.Score - a.Score || compareStrings(a.NeighborKey, b.NeighborKey) || compareStrings(a.Edge.ID, b.Edge.ID));
418
+ }
419
+ uniqueNeighborRefs(candidates) {
420
+ const byKey = new Map();
421
+ for (const c of candidates) {
422
+ if (!byKey.has(c.NeighborKey)) {
423
+ byKey.set(c.NeighborKey, c.Neighbor);
424
+ }
425
+ }
426
+ return Array.from(byKey.values());
427
+ }
428
+ /** Admit visible candidates in rank order until `maxNodes`; the best path to each node wins. */
429
+ admitCandidates(candidates, visible, maxNodes, hop, discovered, visibleByKey) {
430
+ const next = [];
431
+ let capped = false;
432
+ for (const c of candidates) {
433
+ const view = visible.get(c.NeighborKey);
434
+ if (!view || discovered.has(c.NeighborKey)) {
435
+ continue; // invisible to some principal, or already reached by a better path
436
+ }
437
+ if (discovered.size >= maxNodes) {
438
+ capped = true;
439
+ break;
440
+ }
441
+ const node = {
442
+ Node: c.Neighbor,
443
+ Key: c.NeighborKey,
444
+ PathWeight: c.Score,
445
+ Hop: hop,
446
+ ParentKey: c.Parent.Key,
447
+ ViaEdge: c.Edge,
448
+ };
449
+ discovered.set(c.NeighborKey, node);
450
+ visibleByKey.set(c.NeighborKey, view);
451
+ next.push(node);
452
+ }
453
+ return { Next: next, Capped: capped };
454
+ }
455
+ /**
456
+ * Every edge (that the traversal options allow) between two admitted nodes. Reads the admitted
457
+ * set's edges once more so edges among nodes reached on different branches are included.
458
+ */
459
+ async collectEdgesBetween(graph, discovered, options, principals, provider) {
460
+ if (discovered.size < 2) {
461
+ return [];
462
+ }
463
+ const nodes = Array.from(discovered.values()).map((d) => d.Node);
464
+ const edges = await this.getEdgesForFrontier(graph, nodes, options, principals, provider);
465
+ return edges.filter((e) => discovered.has(this.nodeKey(e.Source, provider)) && discovered.has(this.nodeKey(e.Target, provider)));
466
+ }
467
+ // ----- Edges for one step -----------------------------------------------------
468
+ async getEdgesForFrontier(graph, frontier, options, principals, provider) {
469
+ const normalizedFrontier = frontier.map((n) => this.normalizeNodeRef(n, provider));
470
+ const frontierKeys = new Set(normalizedFrontier.map((n) => this.nodeKey(n, provider)));
471
+ const direction = options.Direction ?? 'Both';
472
+ const minWeight = options.MinWeight ?? 0;
473
+ const results = new Map();
474
+ const storedRows = await this.loadStoredEdges(graph, normalizedFrontier, frontierKeys, options, principals, provider);
475
+ const edgeTypesById = IndexByUUID(this.EdgeTypes);
476
+ const textReadable = this.storedEdgeTextReadable(principals, provider);
477
+ for (const row of storedRows) {
478
+ const view = this.toStoredEdgeView(row, graph, options, frontierKeys, provider, edgeTypesById, textReadable);
479
+ if (view) {
480
+ results.set(view.ID, view);
481
+ }
482
+ }
483
+ const derived = await this.derivedEdgesForEveryPrincipal(graph, normalizedFrontier, options, principals, provider);
484
+ for (const edge of derived) {
485
+ if (edge.Weight < minWeight || !MatchesEdgeTypeFilter(edge.TypeName, options.EdgeTypes)) {
486
+ continue;
487
+ }
488
+ if (this.touchesFrontier(edge, frontierKeys, direction, provider)) {
489
+ results.set(edge.ID, edge);
490
+ }
491
+ }
492
+ return Array.from(results.values()).sort((a, b) => compareStrings(a.ID, b.ID));
493
+ }
494
+ touchesFrontier(edge, frontierKeys, direction, provider) {
495
+ const sKey = this.nodeKey(edge.Source, provider);
496
+ const tKey = this.nodeKey(edge.Target, provider);
497
+ const wantOut = direction === 'Out' || direction === 'Both';
498
+ const wantIn = direction === 'In' || direction === 'Both';
499
+ return ((wantOut && frontierKeys.has(sKey)) ||
500
+ (wantIn && frontierKeys.has(tKey)) ||
501
+ (!edge.IsDirected && (frontierKeys.has(sKey) || frontierKeys.has(tKey))));
502
+ }
503
+ toStoredEdgeView(row, graph, options, frontierKeys, provider, edgeTypesById, textReadable) {
504
+ if (!UUIDsEqual(row.GraphID, graph.ID) || row.Status === 'Rejected') {
505
+ return null;
506
+ }
507
+ if (row.Status === 'Proposed' && options.IncludeProposed !== true) {
508
+ return null;
509
+ }
510
+ const edgeType = edgeTypesById.Get(row.EdgeTypeID);
511
+ const typeName = edgeType?.Name ?? row.EdgeType ?? 'Related To';
512
+ const weight = typeof row.Weight === 'number' ? row.Weight : (edgeType?.DefaultWeight ?? 1.0);
513
+ if (!MatchesEdgeTypeFilter(typeName, options.EdgeTypes) || weight < (options.MinWeight ?? 0)) {
514
+ return null;
515
+ }
516
+ if (edgeType &&
517
+ (!this.ValidateEdgeEndpoint(edgeType.ID, 'Source', row.SourceEntityID) ||
518
+ !this.ValidateEdgeEndpoint(edgeType.ID, 'Target', row.TargetEntityID))) {
519
+ return null;
520
+ }
521
+ const source = this.normalizeNodeRef({ EntityName: row.SourceEntity ?? '', EntityID: row.SourceEntityID, RecordID: String(row.SourceRecordID) }, provider);
522
+ const target = this.normalizeNodeRef({ EntityName: row.TargetEntity ?? '', EntityID: row.TargetEntityID, RecordID: String(row.TargetRecordID) }, provider);
523
+ const isDirected = edgeType ? edgeType.IsDirected : true;
524
+ if (!this.touchesFrontier({ Source: source, Target: target, IsDirected: isDirected }, frontierKeys, options.Direction ?? 'Both', provider)) {
525
+ return null;
526
+ }
527
+ return {
528
+ ID: row.ID,
529
+ GraphName: graph.Name,
530
+ TypeName: typeName,
531
+ InverseTypeName: edgeType?.InverseName ?? null,
532
+ Source: source,
533
+ Target: target,
534
+ IsDirected: isDirected,
535
+ Weight: weight,
536
+ Description: textReadable.Description ? (row.Description ?? null) : null,
537
+ Attributes: textReadable.Attributes ? parseJsonObject(row.Attributes) : null,
538
+ Origin: row.Origin,
539
+ Status: row.Status,
540
+ Confidence: row.Confidence ?? null,
541
+ };
542
+ }
543
+ /**
544
+ * Whether every principal may read a stored edge's `Description` and `Attributes`. A field-level
545
+ * denial still returns the row (only the column is dropped), and the preload cache holds every
546
+ * column, so an edge's text is shown only when no principal is denied it.
547
+ */
548
+ storedEdgeTextReadable(principals, provider) {
549
+ const edgeEntity = provider.EntityByName(GRAPH_EDGES_ENTITY);
550
+ return {
551
+ Description: edgeEntity != null && IsFieldReadableByAll(edgeEntity, 'Description', principals),
552
+ Attributes: edgeEntity != null && IsFieldReadableByAll(edgeEntity, 'Attributes', principals),
553
+ };
554
+ }
555
+ /**
556
+ * Stored edges incident to the frontier, as every principal may read them.
557
+ *
558
+ * Served from the preload cache only for an active `Preload` graph, approved edges only, and only
559
+ * when every principal can read `MJ: Graph Edges` with no row-level filter (so the cache, loaded
560
+ * as the engine's identity, holds exactly what each of them could read). Otherwise each principal
561
+ * reads the frontier's edges itself — one bounded, ordered RunView per principal — and an edge is
562
+ * kept only if every principal read it.
563
+ */
564
+ async loadStoredEdges(graph, frontier, frontierKeys, options, principals, provider) {
565
+ const edgeEntity = provider.EntityByName(GRAPH_EDGES_ENTITY);
566
+ if (!edgeEntity || !principals.every((p) => CanUserReadEntity(edgeEntity, p))) {
567
+ return [];
568
+ }
569
+ const includeProposed = options.IncludeProposed === true;
570
+ const cacheServesEveryone = principals.every((p) => edgeEntity.UserExemptFromRowLevelSecurity(p, EntityPermissionType.Read));
571
+ if (graph.LoadMode === 'Preload' && !includeProposed && cacheServesEveryone) {
572
+ const preloaded = await this.preloadedEdgesOf(graph);
573
+ if (preloaded) {
574
+ return this.preloadEdgesFor(preloaded, frontierKeys);
575
+ }
576
+ }
577
+ return this.readStoredEdgesAsPrincipals(graph, frontier, options, principals, provider);
578
+ }
579
+ preloadEdgesFor(preloaded, frontierKeys) {
580
+ const byId = new Map();
581
+ for (const key of frontierKeys) {
582
+ for (const row of preloaded.ByNodeKey.get(key) ?? []) {
583
+ byId.set(row.ID, row);
584
+ }
585
+ }
586
+ return Array.from(byId.values());
587
+ }
588
+ async readStoredEdgesAsPrincipals(graph, frontier, options, principals, provider) {
589
+ const params = this.buildStoredEdgeParams(graph, frontier, options, provider);
590
+ if (!params) {
591
+ return [];
592
+ }
593
+ const rv = RunView.FromMetadataProvider(provider);
594
+ const perPrincipal = await Promise.all(principals.map((p) => rv.RunView(params, p)));
595
+ let rows = null;
596
+ for (const res of perPrincipal) {
597
+ if (!res.Success) {
598
+ LogError(`GraphEngine: reading stored edges of graph "${graph.Name}" failed: ${res.ErrorMessage}`);
599
+ return [];
600
+ }
601
+ if (res.Results.length >= GRAPH_MAX_STORED_EDGES_PER_STEP) {
602
+ LogStatus(`GraphEngine: an expansion step of graph "${graph.Name}" reached the ${GRAPH_MAX_STORED_EDGES_PER_STEP}-row stored-edge cap; the step may be missing edges.`);
603
+ }
604
+ const ids = new UUIDSet(res.Results.map((r) => r.ID));
605
+ rows = rows === null ? res.Results : rows.filter((r) => ids.Has(r.ID));
606
+ }
607
+ return rows ?? [];
608
+ }
609
+ buildStoredEdgeParams(graph, frontier, options, provider) {
610
+ const idsByEntityId = new UUIDMap();
611
+ for (const node of frontier) {
612
+ const recordId = node.RecordID.trim();
613
+ const entityId = node.EntityID ?? provider.EntityByName(node.EntityName)?.ID;
614
+ if (!recordId || !entityId) {
615
+ continue; // a node with no resolvable entity cannot be matched safely on RecordID alone
616
+ }
617
+ const set = idsByEntityId.Get(entityId) ?? new Set();
618
+ set.add(recordId);
619
+ idsByEntityId.Set(entityId, set);
620
+ }
621
+ if (idsByEntityId.Size === 0) {
622
+ return null;
623
+ }
624
+ const side = (entityCol, recordCol) => {
625
+ const parts = [];
626
+ for (const [entityId, recordIds] of idsByEntityId) {
627
+ const quoted = Array.from(recordIds)
628
+ .sort()
629
+ .map((id) => `'${EscapeSQLString(id)}'`)
630
+ .join(', ');
631
+ parts.push(`([${entityCol}] = '${EscapeSQLString(entityId)}' AND [${recordCol}] IN (${quoted}))`);
632
+ }
633
+ return parts;
634
+ };
635
+ // Both sides are read; direction is applied per edge after the read (an undirected edge matches either side).
636
+ const clauses = [...side('SourceEntityID', 'SourceRecordID'), ...side('TargetEntityID', 'TargetRecordID')];
637
+ const statuses = options.IncludeProposed === true ? `'Approved', 'Proposed'` : `'Approved'`;
638
+ return {
639
+ EntityName: GRAPH_EDGES_ENTITY,
640
+ ExtraFilter: `[GraphID] = '${EscapeSQLString(graph.ID)}' AND [Status] IN (${statuses}) AND (${clauses.join(' OR ')})`,
641
+ Fields: STORED_EDGE_FIELDS,
642
+ OrderBy: '[ID]',
643
+ MaxRows: GRAPH_MAX_STORED_EDGES_PER_STEP,
644
+ ResultType: 'simple',
645
+ };
646
+ }
647
+ /**
648
+ * The approved stored edges of one `Preload` graph, loaded on first use as the engine's own identity
649
+ * (the system user on a server) and kept until a change drops them. `null` when the read fails: the
650
+ * caller then reads on demand as each principal.
651
+ */
652
+ async preloadedEdgesOf(graph) {
653
+ const cached = this.preloadedEdges.Get(graph.ID);
654
+ if (cached) {
655
+ return cached;
656
+ }
657
+ const inFlight = this.preloadReads.Get(graph.ID);
658
+ if (inFlight) {
659
+ return inFlight;
660
+ }
661
+ const generation = this.preloadGeneration;
662
+ const read = this.readPreloadedEdges(graph).then((loaded) => {
663
+ if (this.preloadReads.Get(graph.ID) === read) {
664
+ this.preloadReads.Delete(graph.ID);
665
+ }
666
+ if (loaded && generation === this.preloadGeneration) {
667
+ this.preloadedEdges.Set(graph.ID, loaded); // not cached if a change arrived mid-read
668
+ }
669
+ return loaded;
670
+ });
671
+ this.preloadReads.Set(graph.ID, read);
672
+ return read;
673
+ }
674
+ async readPreloadedEdges(graph) {
675
+ const provider = this.ProviderToUse;
676
+ if (!IsGraphDataProvider(provider)) {
677
+ return null;
678
+ }
679
+ const res = await RunView.FromMetadataProvider(provider).RunView({
680
+ EntityName: GRAPH_EDGES_ENTITY,
681
+ ExtraFilter: `[GraphID] = '${EscapeSQLString(graph.ID)}' AND [Status] = 'Approved'`,
682
+ Fields: STORED_EDGE_FIELDS,
683
+ OrderBy: '[ID]',
684
+ ResultType: 'simple',
685
+ }, this.ContextUser);
686
+ if (!res.Success) {
687
+ LogError(`GraphEngine: loading stored edges of Preload graph "${graph.Name}" failed; reading them on demand until a reload succeeds: ${res.ErrorMessage}`);
688
+ return null;
689
+ }
690
+ const loaded = { ByNodeKey: new Map(), EdgeIds: new UUIDSet() };
691
+ for (const row of res.Results) {
692
+ loaded.EdgeIds.Add(row.ID);
693
+ for (const key of [FormatGraphNodeKey(row.SourceEntityID, String(row.SourceRecordID)), FormatGraphNodeKey(row.TargetEntityID, String(row.TargetRecordID))]) {
694
+ const list = loaded.ByNodeKey.get(key);
695
+ if (list) {
696
+ list.push(row);
697
+ }
698
+ else {
699
+ loaded.ByNodeKey.set(key, [row]);
700
+ }
701
+ }
702
+ }
703
+ return loaded;
704
+ }
705
+ /**
706
+ * Derived edges every principal derives. Data-scale providers read as the user they run for, so an
707
+ * edge one principal derives from a row another cannot read (a membership, a link) would reveal that
708
+ * row; each principal runs the providers and only edges all of them produce are kept. Each read
709
+ * also applied that principal's field-level security, so an edge keeps only the text every
710
+ * principal's version carries (see {@link sharedEdgeText}).
711
+ */
712
+ async derivedEdgesForEveryPrincipal(graph, frontier, options, principals, provider) {
713
+ const perPrincipal = await Promise.all(principals.map((p) => this.runDerivedProviders(graph, frontier, options, p, provider)));
714
+ const [callerEdges, ...others] = perPrincipal;
715
+ if (others.length === 0) {
716
+ return callerEdges;
717
+ }
718
+ const otherById = others.map((edges) => new Map(edges.map((e) => [e.ID, e])));
719
+ const shared = [];
720
+ for (const edge of callerEdges) {
721
+ const versions = otherById.map((byId) => byId.get(edge.ID));
722
+ if (versions.every((v) => v !== undefined)) {
723
+ shared.push(sharedEdgeText(edge, versions.filter((v) => v !== undefined)));
724
+ }
725
+ }
726
+ return shared;
727
+ }
728
+ /** Derived edges from the graph's active providers, read as `caller`. */
729
+ async runDerivedProviders(graph, frontier, options, caller, provider) {
730
+ const active = this.EdgeProviders.filter((ep) => ep.IsActive && UUIDsEqual(ep.GraphID, graph.ID)).sort((a, b) => a.Sequence - b.Sequence || compareStrings(a.ID, b.ID));
731
+ const request = { Nodes: frontier, Direction: options.Direction ?? 'Both', EdgeTypes: options.EdgeTypes };
732
+ const edges = [];
733
+ for (const row of active) {
734
+ const instance = MJGlobal.Instance.ClassFactory.CreateInstance(BaseGraphEdgeProvider, row.DriverClass);
735
+ if (!instance) {
736
+ LogError(`GraphEngine: no BaseGraphEdgeProvider is registered as "${row.DriverClass}" (graph "${graph.Name}").`);
737
+ continue;
738
+ }
739
+ try {
740
+ const config = parseJsonObject(row.Configuration) ?? {};
741
+ edges.push(...(await instance.GetEdges(request, { Graph: graph, Config: config, User: caller, Provider: provider })));
742
+ }
743
+ catch (err) {
744
+ const msg = err instanceof Error ? err.message : String(err);
745
+ LogError(`GraphEngine: derived edge provider '${row.DriverClass}' failed on graph '${graph.Name}': ${msg}`);
746
+ }
747
+ }
748
+ return edges;
749
+ }
750
+ // ----- Node visibility ------------------------------------------------------
751
+ /** Nodes visible to EVERY principal; labels come from the caller's read. */
752
+ async resolveVisibleNodes(candidates, principals, provider, includeProposed) {
753
+ if (candidates.length === 0 || principals.length === 0) {
754
+ return new Map();
755
+ }
756
+ const normalized = candidates.map((c) => this.normalizeNodeRef(c, provider));
757
+ const perPrincipal = await Promise.all(principals.map((p) => this.resolveNodesForPrincipal(normalized, p, provider, includeProposed)));
758
+ const visible = perPrincipal[0];
759
+ for (const other of perPrincipal.slice(1)) {
760
+ for (const key of Array.from(visible.keys())) {
761
+ if (!other.has(key)) {
762
+ visible.delete(key);
763
+ }
764
+ }
765
+ }
766
+ if (principals.length > 1) {
767
+ this.neutralizeUnsharedText(visible, principals, provider);
768
+ }
769
+ return visible;
770
+ }
771
+ /**
772
+ * Data-node labels and descriptions come from the caller's read. Field-level security drops a
773
+ * denied column but still returns the row, so a reader denied the name field still counts the node
774
+ * as visible; its label and description are shown only when EVERY principal may read the field,
775
+ * and otherwise replaced by the neutral `<entity name> <record ID>` label and no description.
776
+ * (Metadata nodes take their text from metadata, which entity permissions already gate.)
777
+ */
778
+ neutralizeUnsharedText(visible, principals, provider) {
779
+ const readableByEntity = new Map();
780
+ for (const [key, view] of visible) {
781
+ if (metadataNodeKind(view.EntityName)) {
782
+ continue;
783
+ }
784
+ const entity = provider.EntityByName(view.EntityName);
785
+ if (!entity) {
786
+ continue;
787
+ }
788
+ let readable = readableByEntity.get(entity.Name);
789
+ if (!readable) {
790
+ const nameField = entity.NameField?.Name;
791
+ readable = {
792
+ Name: nameField != null && IsFieldReadableByAll(entity, nameField, principals),
793
+ Description: IsFieldReadableByAll(entity, 'Description', principals),
794
+ };
795
+ readableByEntity.set(entity.Name, readable);
796
+ }
797
+ if (!readable.Name || !readable.Description) {
798
+ visible.set(key, {
799
+ ...view,
800
+ Label: readable.Name ? view.Label : NeutralGraphNodeLabel(entity.Name, view.RecordID),
801
+ Description: readable.Description ? view.Description : null,
802
+ });
803
+ }
804
+ }
805
+ }
806
+ /**
807
+ * Nodes `principal` may see. Metadata nodes are checked against metadata; every data record —
808
+ * concepts included — is read as `principal` in one batched `RunViews` (`[pk] IN (...)` per
809
+ * entity), and a record that does not come back is invisible. A concept whose `Status` (as this
810
+ * principal read it) is not {@link IsGraphConceptStatusVisible} is invisible too.
811
+ */
812
+ async resolveNodesForPrincipal(nodes, principal, provider, includeProposed) {
813
+ const visible = new Map();
814
+ const buckets = new Map();
815
+ const seen = new Set();
816
+ for (const node of nodes) {
817
+ const key = this.nodeKey(node, provider);
818
+ if (seen.has(key)) {
819
+ continue;
820
+ }
821
+ seen.add(key);
822
+ const kind = metadataNodeKind(node.EntityName);
823
+ if (kind) {
824
+ const view = this.resolveMetadataNode(kind, node, key, principal, provider);
825
+ if (view) {
826
+ visible.set(key, view);
827
+ }
828
+ continue;
829
+ }
830
+ const entity = provider.EntityByName(node.EntityName);
831
+ if (!entity || !CanUserReadEntity(entity, principal)) {
832
+ continue;
833
+ }
834
+ const bucket = buckets.get(entity.Name) ?? { Entity: entity, Nodes: [] };
835
+ bucket.Nodes.push({ Ref: node, Key: key });
836
+ buckets.set(entity.Name, bucket);
837
+ }
838
+ await this.resolveDataNodes(Array.from(buckets.values()), principal, provider, includeProposed, visible);
839
+ return visible;
840
+ }
841
+ resolveMetadataNode(kind, node, key, principal, provider) {
842
+ const base = { Key: key, EntityName: kind, EntityID: provider.EntityByName(kind)?.ID ?? node.EntityID };
843
+ if (kind === 'MJ: Entities') {
844
+ const target = provider.EntityByID(node.RecordID);
845
+ return target && CanUserReadEntity(target, principal)
846
+ ? { ...base, RecordID: target.ID, Label: target.DisplayNameOrName || target.Name, Icon: target.Icon || null, Description: target.Description || null }
847
+ : null;
848
+ }
849
+ if (kind === 'MJ: Entity Fields') {
850
+ const entry = this.metadataIndex(provider).FieldsById.Get(node.RecordID);
851
+ return entry && CanUserReadEntity(entry.Entity, principal)
852
+ ? { ...base, RecordID: entry.Field.ID, Label: `${entry.Entity.Name}.${entry.Field.Name}`, Icon: entry.Entity.Icon || null, Description: entry.Field.Description || null }
853
+ : null;
854
+ }
855
+ if (kind === 'MJ: Entity Alternate Base Views') {
856
+ const entry = this.metadataIndex(provider).ViewsById.Get(node.RecordID);
857
+ // "UserCanUse": read permission on the owning entity, and the view must be usable.
858
+ return entry && CanUserReadEntity(entry.Entity, principal) && entry.View.IsUsable
859
+ ? { ...base, RecordID: entry.View.ID, Label: `${entry.Entity.Name}.${entry.View.Name}`, Icon: entry.Entity.Icon || null, Description: entry.View.Description || null }
860
+ : null;
861
+ }
862
+ const query = QueryEngine.Instance.FindQueryByID(node.RecordID);
863
+ // UserCanRun returns { canRun, deniedEntities }; the object itself is always truthy.
864
+ return query && query.UserCanRun(principal).canRun
865
+ ? { ...base, RecordID: query.ID, Label: query.Name, Icon: 'fa-solid fa-terminal', Description: query.Description || null }
866
+ : null;
867
+ }
868
+ metadataIndex(provider) {
869
+ const entities = provider.Entities ?? [];
870
+ if (this.metadataNodeIndex && this.metadataNodeIndex.Source === entities) {
871
+ return this.metadataNodeIndex;
872
+ }
873
+ const index = { Source: entities, FieldsById: new UUIDMap(), ViewsById: new UUIDMap() };
874
+ for (const entity of entities) {
875
+ for (const field of entity.Fields ?? []) {
876
+ index.FieldsById.Set(field.ID, { Entity: entity, Field: field });
877
+ }
878
+ for (const view of entity.AlternateBaseViews ?? []) {
879
+ if (view.ID) {
880
+ index.ViewsById.Set(view.ID, { Entity: entity, View: view });
881
+ }
882
+ }
883
+ }
884
+ this.metadataNodeIndex = index;
885
+ return index;
886
+ }
887
+ async resolveDataNodes(buckets, principal, provider, includeProposed, visible) {
888
+ if (buckets.length === 0) {
889
+ return;
890
+ }
891
+ const params = buckets.map((b) => this.buildNodeReadParams(b));
892
+ const results = await RunView.FromMetadataProvider(provider).RunViews(params, principal);
893
+ for (let i = 0; i < buckets.length; i++) {
894
+ const res = results[i];
895
+ if (!res?.Success) {
896
+ LogError(`GraphEngine: reading ${buckets[i].Entity.Name} nodes failed: ${res?.ErrorMessage ?? 'no result'}`);
897
+ continue; // unreadable means invisible
898
+ }
899
+ this.addReturnedRows(buckets[i], res.Results, includeProposed, visible);
900
+ }
901
+ }
902
+ buildNodeReadParams(bucket) {
903
+ const pkField = bucket.Entity.FirstPrimaryKey.Name; // first-pk-ok: Graph node keys address single-PK or URL-segment records via FirstPrimaryKey
904
+ const fields = new Set([pkField]);
905
+ const nameField = bucket.Entity.NameField?.Name;
906
+ if (nameField) {
907
+ fields.add(nameField);
908
+ }
909
+ if (isConceptEntity(bucket.Entity)) {
910
+ fields.add('Status'); // a concept's visibility depends on its review status
911
+ if (bucket.Entity.Fields?.some((f) => f.Name === 'Description')) {
912
+ fields.add('Description');
913
+ }
914
+ }
915
+ const ids = Array.from(new Set(bucket.Nodes.map((n) => n.Ref.RecordID))).sort();
916
+ return {
917
+ EntityName: bucket.Entity.Name,
918
+ ExtraFilter: `[${pkField}] IN (${ids.map((id) => `'${EscapeSQLString(id)}'`).join(', ')})`,
919
+ Fields: Array.from(fields),
920
+ OrderBy: `[${pkField}]`,
921
+ ResultType: 'simple',
922
+ };
923
+ }
924
+ addReturnedRows(bucket, rows, includeProposed, visible) {
925
+ const pkField = bucket.Entity.FirstPrimaryKey.Name; // first-pk-ok: Graph node keys address single-PK or URL-segment records via FirstPrimaryKey
926
+ const nameField = bucket.Entity.NameField?.Name;
927
+ const isConcept = isConceptEntity(bucket.Entity);
928
+ const rowByKey = new Map();
929
+ for (const row of rows) {
930
+ const id = row[pkField];
931
+ if (id != null) {
932
+ rowByKey.set(FormatGraphNodeKey(bucket.Entity.ID, String(id)), row);
933
+ }
934
+ }
935
+ for (const item of bucket.Nodes) {
936
+ const row = rowByKey.get(item.Key);
937
+ if (!row) {
938
+ continue; // not returned to this principal: entity permission or row-level security
939
+ }
940
+ if (isConcept && !IsGraphConceptStatusVisible(row['Status'], includeProposed)) {
941
+ continue; // an unreviewed (Draft/Proposed) or Deprecated concept is not canon
942
+ }
943
+ const label = nameField && row[nameField] != null ? String(row[nameField]) : NeutralGraphNodeLabel(bucket.Entity.Name, item.Ref.RecordID);
944
+ const description = row['Description'];
945
+ visible.set(item.Key, {
946
+ Key: item.Key,
947
+ EntityName: bucket.Entity.Name,
948
+ EntityID: bucket.Entity.ID,
949
+ RecordID: item.Ref.RecordID,
950
+ Label: label,
951
+ Icon: bucket.Entity.Icon || null,
952
+ Description: typeof description === 'string' && description.length > 0 ? description : null,
953
+ });
954
+ }
955
+ }
956
+ // ----- Node references ------------------------------------------------------
957
+ normalizeNodeRef(node, provider) {
958
+ const recordId = String(node.RecordID).trim();
959
+ const byName = node.EntityName ? provider.EntityByName(node.EntityName) : undefined;
960
+ if (byName) {
961
+ return { EntityName: byName.Name, EntityID: byName.ID, RecordID: recordId };
962
+ }
963
+ const byId = node.EntityID ? provider.EntityByID(node.EntityID) : undefined;
964
+ if (byId) {
965
+ return { EntityName: byId.Name, EntityID: byId.ID, RecordID: recordId };
966
+ }
967
+ return { EntityName: (node.EntityName ?? '').trim(), EntityID: node.EntityID, RecordID: recordId };
968
+ }
969
+ nodeKey(node, provider) {
970
+ const normalized = this.normalizeNodeRef(node, provider);
971
+ return FormatGraphNodeKey(normalized.EntityID ?? normalized.EntityName, normalized.RecordID);
972
+ }
973
+ }
974
+ /** The label a node gets when its name field may not be shown: the entity name and the record key. */
975
+ export function NeutralGraphNodeLabel(entityName, recordId) {
976
+ return `${entityName} ${recordId}`;
977
+ }
978
+ /** True when every principal may read `fieldName` on `entity` (MJ field-level security). */
979
+ export function IsFieldReadableByAll(entity, fieldName, principals) {
980
+ return principals.every((p) => entity.IsFieldReadableByUser(fieldName, p));
981
+ }
982
+ /**
983
+ * `edge` (the caller's version of a derived edge) with only the text every principal's version
984
+ * carries: its `Description` when every version has the same one, and the `Attributes` keys whose
985
+ * values every version shares. A value a principal's field-level security dropped is missing from
986
+ * that principal's version, so it is dropped here too.
987
+ */
988
+ function sharedEdgeText(edge, others) {
989
+ const description = others.every((o) => o.Description === edge.Description) ? edge.Description : null;
990
+ let attributes = null;
991
+ if (edge.Attributes) {
992
+ const kept = {};
993
+ for (const [key, value] of Object.entries(edge.Attributes)) {
994
+ const serialized = JSON.stringify(value);
995
+ if (others.every((o) => o.Attributes != null && key in o.Attributes && JSON.stringify(o.Attributes[key]) === serialized)) {
996
+ kept[key] = value;
997
+ }
998
+ }
999
+ attributes = Object.keys(kept).length > 0 ? kept : null;
1000
+ }
1001
+ return { ...edge, Description: description, Attributes: attributes };
1002
+ }
1003
+ function isConceptEntity(entity) {
1004
+ return entity.Name.trim().toLowerCase() === GRAPH_CONCEPTS_ENTITY.toLowerCase();
1005
+ }
1006
+ /**
1007
+ * Whether a concept with this `Status` may seed a traversal or appear in one. Only `Approved`
1008
+ * concepts are canon; `Proposed` ones appear only when the caller asked for proposed content
1009
+ * (`IncludeProposed`); `Draft` (the column default: still being written) and `Deprecated` never do.
1010
+ * Anything else, including a status the reader could not read, is not visible.
1011
+ */
1012
+ export function IsGraphConceptStatusVisible(status, includeProposed) {
1013
+ const approved = 'Approved';
1014
+ const proposed = 'Proposed';
1015
+ return status === approved || (includeProposed && status === proposed);
1016
+ }
1017
+ function metadataNodeKind(entityName) {
1018
+ switch (entityName.trim().toLowerCase()) {
1019
+ case 'mj: entities':
1020
+ return 'MJ: Entities';
1021
+ case 'mj: entity fields':
1022
+ return 'MJ: Entity Fields';
1023
+ case 'mj: entity alternate base views':
1024
+ return 'MJ: Entity Alternate Base Views';
1025
+ case 'mj: queries':
1026
+ return 'MJ: Queries';
1027
+ default:
1028
+ return null;
1029
+ }
1030
+ }
1031
+ /**
1032
+ * Entity read permission with MJ's own semantics (`EntityInfo.GetUserPermisions`): role-based allow
1033
+ * minus deny, no bypass for any user type. Anything unknown is denied.
1034
+ */
1035
+ export function CanUserReadEntity(entity, user) {
1036
+ if (!entity || !user || !Array.isArray(user.UserRoles)) {
1037
+ return false;
1038
+ }
1039
+ return entity.GetUserPermisions(user)?.CanRead === true;
1040
+ }
1041
+ /** Clamp a requested traversal depth to `1..4` (default `2`). */
1042
+ export function ClampGraphDepth(requested) {
1043
+ const value = requested != null && Number.isFinite(requested) ? Math.floor(requested) : GRAPH_DEFAULT_DEPTH;
1044
+ return Math.max(1, Math.min(GRAPH_MAX_DEPTH, value));
1045
+ }
1046
+ /** Clamp a requested node budget to `1..200` (default `50`, or `fallback`). */
1047
+ export function ClampGraphMaxNodes(requested, fallback = GRAPH_DEFAULT_MAX_NODES) {
1048
+ const value = requested != null && Number.isFinite(requested) ? Math.floor(requested) : fallback;
1049
+ return Math.max(1, Math.min(GRAPH_MAX_NODES, value));
1050
+ }
1051
+ function compareStrings(a, b) {
1052
+ return a < b ? -1 : a > b ? 1 : 0;
1053
+ }
1054
+ function parseJsonObject(raw) {
1055
+ if (!raw) {
1056
+ return null;
1057
+ }
1058
+ try {
1059
+ const parsed = JSON.parse(raw);
1060
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
1061
+ }
1062
+ catch {
1063
+ return null;
1064
+ }
1065
+ }
1066
+ //# sourceMappingURL=GraphEngine.js.map