@memberjunction/core-entities 6.3.0-edge.1 → 6.3.0-edge.2

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 (113) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/custom/ArtifactPermissionDelegate.d.ts +27 -6
  3. package/dist/custom/ArtifactPermissionDelegate.d.ts.map +1 -1
  4. package/dist/custom/ArtifactPermissionDelegate.js +845 -298
  5. package/dist/custom/ArtifactPermissionDelegate.js.map +1 -1
  6. package/dist/custom/ConversationWriteAccess.d.ts +9 -0
  7. package/dist/custom/ConversationWriteAccess.d.ts.map +1 -1
  8. package/dist/custom/ConversationWriteAccess.js +56 -1
  9. package/dist/custom/ConversationWriteAccess.js.map +1 -1
  10. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts +9 -0
  11. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts.map +1 -1
  12. package/dist/custom/Permissions/BaseShareEntityExtended.js +11 -0
  13. package/dist/custom/Permissions/BaseShareEntityExtended.js.map +1 -1
  14. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts.map +1 -1
  15. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js +15 -3
  16. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js.map +1 -1
  17. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts +1 -0
  18. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts.map +1 -1
  19. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js +45 -13
  20. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js.map +1 -1
  21. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.d.ts +3 -1
  22. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.d.ts.map +1 -1
  23. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.js +83 -19
  24. package/dist/custom/Permissions/MJDashboardPermissionEntityExtended.js.map +1 -1
  25. package/dist/custom/Permissions/shareNotification.d.ts +14 -1
  26. package/dist/custom/Permissions/shareNotification.d.ts.map +1 -1
  27. package/dist/custom/Permissions/shareNotification.js +62 -8
  28. package/dist/custom/Permissions/shareNotification.js.map +1 -1
  29. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.d.ts.map +1 -1
  30. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js +120 -38
  31. package/dist/custom/ResourcePermissions/MJResourcePermissionEntityExtended.js.map +1 -1
  32. package/dist/custom/SlideDeckEngine.d.ts +45 -3
  33. package/dist/custom/SlideDeckEngine.d.ts.map +1 -1
  34. package/dist/custom/SlideDeckEngine.js +509 -10
  35. package/dist/custom/SlideDeckEngine.js.map +1 -1
  36. package/dist/custom/SlideDeckPptxEngine.d.ts.map +1 -1
  37. package/dist/custom/SlideDeckPptxEngine.js +91 -17
  38. package/dist/custom/SlideDeckPptxEngine.js.map +1 -1
  39. package/dist/custom/SpreadsheetEngine.d.ts +7 -0
  40. package/dist/custom/SpreadsheetEngine.d.ts.map +1 -1
  41. package/dist/custom/SpreadsheetEngine.js +72 -0
  42. package/dist/custom/SpreadsheetEngine.js.map +1 -1
  43. package/dist/custom/approvals.d.ts +24 -0
  44. package/dist/custom/approvals.d.ts.map +1 -1
  45. package/dist/custom/approvals.js +34 -1
  46. package/dist/custom/approvals.js.map +1 -1
  47. package/dist/engines/CanonGraphEngine.d.ts +114 -1
  48. package/dist/engines/CanonGraphEngine.d.ts.map +1 -1
  49. package/dist/engines/CanonGraphEngine.js +240 -20
  50. package/dist/engines/CanonGraphEngine.js.map +1 -1
  51. package/dist/engines/conversations.d.ts +20 -4
  52. package/dist/engines/conversations.d.ts.map +1 -1
  53. package/dist/engines/conversations.js +61 -12
  54. package/dist/engines/conversations.js.map +1 -1
  55. package/dist/generated/entities/__mj.d.ts +6973 -399
  56. package/dist/generated/entities/__mj.d.ts.map +1 -1
  57. package/dist/generated/entities/__mj.js +35452 -27348
  58. package/dist/generated/entities/__mj.js.map +1 -1
  59. package/dist/generated/remote_operations.d.ts +745 -65
  60. package/dist/generated/remote_operations.d.ts.map +1 -1
  61. package/dist/generated/remote_operations.js +248 -8
  62. package/dist/generated/remote_operations.js.map +1 -1
  63. package/dist/generated/schemas/__mj.d.ts +2156 -230
  64. package/dist/generated/schemas/__mj.d.ts.map +1 -1
  65. package/dist/generated/schemas/__mj.js +3385 -26
  66. package/dist/generated/schemas/__mj.js.map +1 -1
  67. package/dist/graph/BaseGraphEdgeProvider.d.ts +33 -1
  68. package/dist/graph/BaseGraphEdgeProvider.d.ts.map +1 -1
  69. package/dist/graph/BaseGraphEdgeProvider.js +18 -3
  70. package/dist/graph/BaseGraphEdgeProvider.js.map +1 -1
  71. package/dist/graph/CanonDocumentRenderer.d.ts +43 -0
  72. package/dist/graph/CanonDocumentRenderer.d.ts.map +1 -0
  73. package/dist/graph/CanonDocumentRenderer.js +627 -0
  74. package/dist/graph/CanonDocumentRenderer.js.map +1 -0
  75. package/dist/graph/DomainClustering.d.ts +88 -0
  76. package/dist/graph/DomainClustering.d.ts.map +1 -0
  77. package/dist/graph/DomainClustering.js +327 -0
  78. package/dist/graph/DomainClustering.js.map +1 -0
  79. package/dist/graph/DomainProposalWriter.d.ts +25 -0
  80. package/dist/graph/DomainProposalWriter.d.ts.map +1 -0
  81. package/dist/graph/DomainProposalWriter.js +107 -0
  82. package/dist/graph/DomainProposalWriter.js.map +1 -0
  83. package/dist/graph/GraphAccessPolicy.d.ts +111 -0
  84. package/dist/graph/GraphAccessPolicy.d.ts.map +1 -0
  85. package/dist/graph/GraphAccessPolicy.js +123 -0
  86. package/dist/graph/GraphAccessPolicy.js.map +1 -0
  87. package/dist/graph/GraphEngine.d.ts +99 -10
  88. package/dist/graph/GraphEngine.d.ts.map +1 -1
  89. package/dist/graph/GraphEngine.js +359 -53
  90. package/dist/graph/GraphEngine.js.map +1 -1
  91. package/dist/graph/RecordRelations.d.ts +52 -0
  92. package/dist/graph/RecordRelations.d.ts.map +1 -0
  93. package/dist/graph/RecordRelations.js +90 -0
  94. package/dist/graph/RecordRelations.js.map +1 -0
  95. package/dist/graph/index.d.ts +9 -1
  96. package/dist/graph/index.d.ts.map +1 -1
  97. package/dist/graph/index.js +13 -1
  98. package/dist/graph/index.js.map +1 -1
  99. package/dist/graph/policies/ProvenanceAccessPolicies.d.ts +56 -0
  100. package/dist/graph/policies/ProvenanceAccessPolicies.d.ts.map +1 -0
  101. package/dist/graph/policies/ProvenanceAccessPolicies.js +228 -0
  102. package/dist/graph/policies/ProvenanceAccessPolicies.js.map +1 -0
  103. package/dist/graph/providers/QueryEdgeProvider.d.ts.map +1 -1
  104. package/dist/graph/providers/QueryEdgeProvider.js +2 -2
  105. package/dist/graph/providers/QueryEdgeProvider.js.map +1 -1
  106. package/dist/graph/providers/RecordLinkEdgeProvider.d.ts.map +1 -1
  107. package/dist/graph/providers/RecordLinkEdgeProvider.js +2 -2
  108. package/dist/graph/providers/RecordLinkEdgeProvider.js.map +1 -1
  109. package/dist/graph/providers/SharedConceptEdgeProvider.d.ts +54 -0
  110. package/dist/graph/providers/SharedConceptEdgeProvider.d.ts.map +1 -0
  111. package/dist/graph/providers/SharedConceptEdgeProvider.js +282 -0
  112. package/dist/graph/providers/SharedConceptEdgeProvider.js.map +1 -0
  113. package/package.json +6 -6
@@ -1,8 +1,10 @@
1
1
  import { BaseEngine, EntityPermissionType, LogError, LogStatus, RunView, } from '@memberjunction/core';
2
2
  import { EscapeSQLString, IndexByUUID, MJGlobal, UUIDMap, UUIDSet, UUIDsEqual } from '@memberjunction/global';
3
+ import { EvaluateAuthorizationChecks } from '../custom/operations/EvaluateAuthorizationChecks.js';
3
4
  import { MJGraphEdgeEntity, MJGraphEntity, } from '../generated/entity_subclasses.js';
4
5
  import { QueryEngine } from '../engines/QueryEngine.js';
5
- import { BaseGraphEdgeProvider, FormatGraphNodeKey, IsGraphDataProvider, MatchesEdgeTypeFilter, } from './BaseGraphEdgeProvider.js';
6
+ import { GraphAccessPolicyRegistry, } from './GraphAccessPolicy.js';
7
+ import { BaseGraphEdgeProvider, FormatGraphNodeKey, IsGraphDataProvider, MatchesEdgeTypeFilter, GRAPH_DEFAULT_EDGE_TYPE, } from './BaseGraphEdgeProvider.js';
6
8
  /** Depth used when the caller gives none. */
7
9
  export const GRAPH_DEFAULT_DEPTH = 2;
8
10
  /** Hard upper bound on traversal depth. */
@@ -13,25 +15,63 @@ export const GRAPH_DEFAULT_MAX_NODES = 50;
13
15
  export const GRAPH_MAX_NODES = 200;
14
16
  /** Row cap on the stored edges one expansion step reads on demand. */
15
17
  export const GRAPH_MAX_STORED_EDGES_PER_STEP = 1000;
18
+ /**
19
+ * Named `MJ: Authorizations` grant required for every approval, rejection/deprecation, edit-of-approved,
20
+ * or delete-of-approved decision on `MJ: Graph Edges` and `MJ: Graph Concepts`.
21
+ */
22
+ export const GRAPH_APPROVE_EDGES_AUTHORIZATION = 'Graph: Approve Edges';
16
23
  /**
17
24
  * 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.
25
+ * saves the newly synthesized `Approved` `MJ: Graph Concepts` and `Inferred` + `Approved`
26
+ * `MJ: Graph Edges` that its content source's `GraphOverlay` policy approves (every
27
+ * `ConceptTaxonomyMode` except `propose-only`). `MJGraphEdgeEntityServer` and
28
+ * `MJGraphConceptEntityServer` let a newly created policy-approved row start `Approved` without
29
+ * `Graph: Approve Edges` only inside this scope (never edits, deprecations, or status transitions on
30
+ * existing concepts). Client CRUD entry points (GraphQL, REST, transaction groups) run inside a client
31
+ * CRUD boundary that masks every outer scope, so an API caller cannot enter it; only server code
32
+ * that names this key can.
23
33
  */
24
34
  export const GRAPH_PIPELINE_EDGE_APPROVAL_OPERATION = 'ContentPipeline.GraphStage.ApproveInferredEdges';
35
+ /**
36
+ * Server operation key under which the Content Pipeline retracts the evidence of a chunk it is
37
+ * deleting: the `Inferred` edges that have that chunk as an endpoint. Deleting an `Approved` edge is
38
+ * otherwise a review decision that needs `Graph: Approve Edges`, but an edge whose evidence is gone
39
+ * is not one a person decided to keep, so `MJGraphEdgeEntityServer` allows deleting an `Inferred`
40
+ * edge inside this scope. A `Declared` edge is never covered. Like the approval scope, no API caller
41
+ * can enter it.
42
+ */
43
+ export const GRAPH_PIPELINE_EVIDENCE_RETRACTION_OPERATION = 'ContentPipeline.Delete.RetractInferredEdges';
44
+ /**
45
+ * How deeply access policies may nest (a concept's visibility following its chunks', a chunk's
46
+ * following its document's). Past this depth every node is hidden, so a cycle cannot recurse forever.
47
+ */
48
+ const MAX_POLICY_DEPTH = 6;
25
49
  /** Per-hop decay applied to best-first path scores, so near nodes outrank far ones. */
26
50
  const HOP_DECAY = 0.85;
27
51
  const GRAPH_EDGES_ENTITY = 'MJ: Graph Edges';
28
52
  const GRAPHS_ENTITY = 'MJ: Graphs';
29
53
  const GRAPH_TYPES_ENTITY = 'MJ: Graph Types';
30
54
  const GRAPH_CONCEPTS_ENTITY = 'MJ: Graph Concepts';
31
- const CANON_PRIMARY_GRAPH_NAME_LOWER = 'mj canon';
32
- /** True when a graph belongs to a Canon graph type or carries the primary Canon graph name. */
55
+ /**
56
+ * True when a graph belongs to a graph type with `IsCanon = 1`. Whether a graph is Canon is metadata:
57
+ * neither the graph's name nor its type's name decides it.
58
+ */
33
59
  export function IsCanonGraph(graph, canonTypeIds) {
34
- return canonTypeIds.Has(graph.GraphTypeID) || graph.Name.trim().toLowerCase() === CANON_PRIMARY_GRAPH_NAME_LOWER;
60
+ return canonTypeIds.Has(graph.GraphTypeID);
61
+ }
62
+ /**
63
+ * Whether `entityId` may sit on `side` of an edge of type `edgeTypeId`, according to `endpoints`
64
+ * (`MJ: Graph Edge Type Endpoints` rows). With no row for that type and side, any entity may.
65
+ *
66
+ * The one rule behind {@link GraphEngine.ValidateEdgeEndpoint} (read path and the edge server
67
+ * subclass) and every proposer that checks an edge before writing it, so they cannot disagree.
68
+ */
69
+ export function GraphEdgeEndpointAllows(endpoints, edgeTypeId, side, entityId) {
70
+ const constraints = endpoints.filter((ep) => UUIDsEqual(ep.EdgeTypeID, edgeTypeId) && ep.Side === side);
71
+ if (constraints.length === 0) {
72
+ return true;
73
+ }
74
+ return constraints.some((ep) => UUIDsEqual(ep.EntityID, entityId));
35
75
  }
36
76
  const STORED_EDGE_FIELDS = [
37
77
  'ID',
@@ -162,21 +202,16 @@ export class GraphEngine extends BaseEngine {
162
202
  const activeGraphs = (graphsRes.Results ?? []).filter((g) => g.Status === 'Active');
163
203
  let hasActive = false;
164
204
  if (activeGraphs.length > 0) {
165
- if (activeGraphs.some((g) => IsCanonGraph(g, new UUIDSet()))) {
166
- hasActive = true;
167
- }
168
- else {
169
- const typesRes = await rv.RunView({
170
- EntityName: GRAPH_TYPES_ENTITY,
171
- Fields: ['ID', 'IsCanon'],
172
- ResultType: 'simple',
173
- }, contextUser);
174
- if (!typesRes.Success) {
175
- return true;
176
- }
177
- const canonTypeIds = new UUIDSet((typesRes.Results ?? []).filter((gt) => Boolean(gt.IsCanon)).map((gt) => gt.ID));
178
- hasActive = activeGraphs.some((g) => IsCanonGraph(g, canonTypeIds));
205
+ const typesRes = await rv.RunView({
206
+ EntityName: GRAPH_TYPES_ENTITY,
207
+ Fields: ['ID', 'IsCanon'],
208
+ ResultType: 'simple',
209
+ }, contextUser);
210
+ if (!typesRes.Success) {
211
+ return true;
179
212
  }
213
+ const canonTypeIds = new UUIDSet((typesRes.Results ?? []).filter((gt) => Boolean(gt.IsCanon)).map((gt) => gt.ID));
214
+ hasActive = activeGraphs.some((g) => IsCanonGraph(g, canonTypeIds));
180
215
  }
181
216
  const rlsExempt = !contextUser || graphsMeta.UserExemptFromRowLevelSecurity(contextUser, EntityPermissionType.Read);
182
217
  if (rlsExempt && generation === this.activeCanonProbeGeneration) {
@@ -285,11 +320,7 @@ export class GraphEngine extends BaseEngine {
285
320
  * any entity is permitted.
286
321
  */
287
322
  ValidateEdgeEndpoint(edgeTypeId, side, entityId) {
288
- const constraints = this.EdgeTypeEndpoints.filter((ep) => UUIDsEqual(ep.EdgeTypeID, edgeTypeId) && ep.Side === side);
289
- if (constraints.length === 0) {
290
- return true;
291
- }
292
- return constraints.some((ep) => UUIDsEqual(ep.EntityID, entityId));
323
+ return GraphEdgeEndpointAllows(this.EdgeTypeEndpoints, edgeTypeId, side, entityId);
293
324
  }
294
325
  /**
295
326
  * The canonical key of a node (`<entityID>|<recordID>`), resolving the entity through metadata.
@@ -311,6 +342,18 @@ export class GraphEngine extends BaseEngine {
311
342
  const provider = this.graphProvider(options.Provider);
312
343
  return this.resolveVisibleNodes(nodes, this.principals(user, audienceReaders), provider, options.IncludeProposed === true);
313
344
  }
345
+ /**
346
+ * Runs registered {@link BaseGraphEdgeAccessPolicy} checks over `edges` for `user` and every
347
+ * `audienceReaders` principal. An edge survives only when every principal's policy allows it;
348
+ * edge types with no registered policy pass through unchanged.
349
+ */
350
+ async FilterEdgesForUser(edges, user, audienceReaders, options = {}) {
351
+ if (!user || !edges || edges.length === 0) {
352
+ return [];
353
+ }
354
+ const provider = this.graphProvider(options.Provider);
355
+ return this.applyEdgePolicies(edges, this.principals(user, audienceReaders), provider, options.IncludeProposed === true);
356
+ }
314
357
  /**
315
358
  * Stored and derived edges incident to `node` in `graphName` whose endpoints the caller (and any
316
359
  * `options.AudienceReaders`) may see. An unknown or inactive graph yields no edges. Every read made
@@ -359,24 +402,7 @@ export class GraphEngine extends BaseEngine {
359
402
  if (!graph) {
360
403
  return { Nodes: [], Edges: [], Message: `Graph "${graphName}" was not found or is not active.` };
361
404
  }
362
- const dataProvider = this.graphProvider(provider);
363
- const principals = this.principals(user, options.AudienceReaders);
364
- const maxDepth = ClampGraphDepth(options.Depth ?? options.MaxDepth);
365
- const maxNodes = ClampGraphMaxNodes(options.MaxNodes);
366
- const minWeight = options.MinWeight ?? 0;
367
- const includeProposed = options.IncludeProposed === true;
368
- const discovered = new Map();
369
- const visibleByKey = new Map();
370
- let frontier = await this.admitSeeds(seeds, principals, maxNodes, dataProvider, includeProposed, discovered, visibleByKey);
371
- let capped = false;
372
- for (let hop = 1; hop <= maxDepth && frontier.length > 0; hop++) {
373
- const stepEdges = await this.getEdgesForFrontier(graph, frontier.map((f) => f.Node), options, principals, dataProvider);
374
- const candidates = this.rankCandidates(stepEdges, frontier, discovered, minWeight, hop, dataProvider);
375
- const visible = await this.resolveVisibleNodes(this.uniqueNeighborRefs(candidates), principals, dataProvider, includeProposed);
376
- const admitted = this.admitCandidates(candidates, visible, maxNodes, hop, discovered, visibleByKey);
377
- capped = capped || admitted.Capped;
378
- frontier = admitted.Next;
379
- }
405
+ const { discovered, visibleByKey, capped, maxNodes, principals, dataProvider } = await this.traverse(graph, seeds, options, { MaxDepth: ClampGraphDepth(options.Depth ?? options.MaxDepth), MaxNodes: ClampGraphMaxNodes(options.MaxNodes) }, user, provider);
380
406
  const edges = new Map((await this.collectEdgesBetween(graph, discovered, options, principals, dataProvider)).map((e) => [e.ID, e]));
381
407
  const nodes = [];
382
408
  for (const d of discovered.values()) {
@@ -400,6 +426,101 @@ export class GraphEngine extends BaseEngine {
400
426
  async Expand(graphName, seeds, options, user, provider) {
401
427
  return this.Subgraph(graphName, seeds, options, user, provider);
402
428
  }
429
+ /**
430
+ * The fewest-hop path from `from` to `to` in `graphName` that the caller (and every
431
+ * `options.AudienceReaders`) may see, with the best path weight among paths of that length.
432
+ *
433
+ * The search is the same best-first, permission-checked expansion as {@link Subgraph}, started at
434
+ * `from` and stopped the moment `to` is admitted, so a path never runs through a node some
435
+ * principal cannot see. `Depth` defaults to the maximum (4) and `MaxNodes` to the cap (200),
436
+ * because a path search usually needs the reach that a neighborhood read does not.
437
+ *
438
+ * A node the caller cannot see (either endpoint included) and a node that is not connected give
439
+ * the same answer, `Found: false` with a `Message`, so the result never reveals that a record exists.
440
+ */
441
+ async FindPath(graphName, from, to, options, user, provider) {
442
+ const graph = this.GetGraph(graphName);
443
+ if (!graph) {
444
+ return notFoundPath(`Graph "${graphName}" was not found or is not active.`);
445
+ }
446
+ if (!user || !from || !to) {
447
+ return notFoundPath('Both a start node and an end node are required.');
448
+ }
449
+ const maxDepth = ClampGraphDepth(options.Depth ?? options.MaxDepth ?? GRAPH_MAX_DEPTH);
450
+ const maxNodes = ClampGraphMaxNodes(options.MaxNodes, GRAPH_MAX_NODES);
451
+ const stopAtKey = this.nodeKey(this.normalizeNodeRef(to, this.graphProvider(provider)), this.graphProvider(provider));
452
+ const run = await this.traverse(graph, [from], options, { MaxDepth: maxDepth, MaxNodes: maxNodes, StopAtKey: stopAtKey }, user, provider);
453
+ if (!run.discovered.has(stopAtKey)) {
454
+ const limit = run.capped ? ` (the search stopped at the ${maxNodes}-node limit)` : '';
455
+ return notFoundPath(`No path found within ${maxDepth} hop${maxDepth === 1 ? '' : 's'}${limit}.`);
456
+ }
457
+ return this.buildPath(stopAtKey, run);
458
+ }
459
+ /**
460
+ * Render a {@link GraphPath} as one Markdown line per hop for LLM prompt injection. Each edge is
461
+ * shown in its own direction, so a hop taken against an edge reads `<--`.
462
+ */
463
+ DescribePathForPrompt(path, provider) {
464
+ if (!path.Found || path.Nodes.length === 0) {
465
+ return path.Message ? `No graph path found. ${path.Message}` : 'No graph path found.';
466
+ }
467
+ const resolvedProvider = this.graphProvider(provider);
468
+ const lines = [`### Graph Path (${path.Edges.length} hop${path.Edges.length === 1 ? '' : 's'}, weight ${path.PathWeight.toFixed(2)})`];
469
+ lines.push(`- **[${path.Nodes[0].EntityName}] ${path.Nodes[0].Label}**`);
470
+ for (let i = 0; i < path.Edges.length; i++) {
471
+ const edge = path.Edges[i];
472
+ const next = path.Nodes[i + 1];
473
+ const forward = this.nodeKey(edge.Source, resolvedProvider) === path.Nodes[i].Key;
474
+ const arrow = !edge.IsDirected ? '<-->' : forward ? '-->' : '<--';
475
+ const desc = edge.Description ? ` (${edge.Description})` : '';
476
+ lines.push(` ${arrow} [${edge.TypeName} (${edge.Weight.toFixed(2)})]${desc} **[${next.EntityName}] ${next.Label}**`);
477
+ }
478
+ return lines.join('\n');
479
+ }
480
+ /**
481
+ * Best-first bounded expansion shared by {@link Subgraph} and {@link FindPath}: admit the visible
482
+ * seeds, then expand hop by hop, checking every candidate's visibility for every principal before
483
+ * admitting it, until the depth or node limit is reached or `limits.StopAtKey` is admitted.
484
+ */
485
+ async traverse(graph, seeds, options, limits, user, provider) {
486
+ const dataProvider = this.graphProvider(provider);
487
+ const principals = this.principals(user, options.AudienceReaders);
488
+ const minWeight = options.MinWeight ?? 0;
489
+ const includeProposed = options.IncludeProposed === true;
490
+ const discovered = new Map();
491
+ const visibleByKey = new Map();
492
+ const maxNodes = limits.MaxNodes;
493
+ let frontier = await this.admitSeeds(seeds, principals, maxNodes, dataProvider, includeProposed, discovered, visibleByKey);
494
+ let capped = false;
495
+ const reachedStop = () => limits.StopAtKey != null && discovered.has(limits.StopAtKey);
496
+ for (let hop = 1; hop <= limits.MaxDepth && frontier.length > 0 && !reachedStop(); hop++) {
497
+ const stepEdges = await this.getEdgesForFrontier(graph, frontier.map((f) => f.Node), options, principals, dataProvider);
498
+ const candidates = this.rankCandidates(stepEdges, frontier, discovered, minWeight, hop, dataProvider);
499
+ const visible = await this.resolveVisibleNodes(this.uniqueNeighborRefs(candidates), principals, dataProvider, includeProposed);
500
+ const admitted = this.admitCandidates(candidates, visible, maxNodes, hop, discovered, visibleByKey);
501
+ capped = capped || admitted.Capped;
502
+ frontier = admitted.Next;
503
+ }
504
+ return { discovered, visibleByKey, capped, maxNodes, principals, dataProvider };
505
+ }
506
+ /** Walk back from `targetKey` through each node's parent to the seed, and return the path in order. */
507
+ buildPath(targetKey, run) {
508
+ const nodes = [];
509
+ const edges = [];
510
+ let current = run.discovered.get(targetKey);
511
+ const pathWeight = current?.PathWeight ?? 0;
512
+ while (current) {
513
+ const view = run.visibleByKey.get(current.Key);
514
+ if (view) {
515
+ nodes.push({ ...view, Hop: current.Hop, PathWeight: current.PathWeight, ParentKey: current.ParentKey, ViaEdgeID: current.ViaEdge?.ID ?? null });
516
+ }
517
+ if (current.ViaEdge) {
518
+ edges.push(current.ViaEdge);
519
+ }
520
+ current = current.ParentKey ? run.discovered.get(current.ParentKey) : undefined;
521
+ }
522
+ return { Found: true, Nodes: nodes.reverse(), Edges: edges.reverse(), PathWeight: pathWeight };
523
+ }
403
524
  /**
404
525
  * Render a {@link GraphSubgraph} as a compact, deterministic Markdown block for LLM prompt injection.
405
526
  */
@@ -579,7 +700,47 @@ export class GraphEngine extends BaseEngine {
579
700
  results.set(edge.ID, edge);
580
701
  }
581
702
  }
582
- return Array.from(results.values()).sort((a, b) => compareStrings(a.ID, b.ID));
703
+ const allowed = await this.applyEdgePolicies(Array.from(results.values()), principals, provider, options.IncludeProposed === true);
704
+ return allowed.sort((a, b) => compareStrings(a.ID, b.ID));
705
+ }
706
+ /**
707
+ * Runs each edge type's access policy, for every principal: an edge survives only if every
708
+ * principal's policy allows it. Edge types with no policy pass through. A policy that throws hides
709
+ * every edge it governs.
710
+ */
711
+ async applyEdgePolicies(edges, principals, provider, includeProposed) {
712
+ const byType = new Map();
713
+ for (const edge of edges) {
714
+ const list = byType.get(edge.TypeName) ?? [];
715
+ list.push(edge);
716
+ byType.set(edge.TypeName, list);
717
+ }
718
+ const hidden = new Set();
719
+ for (const [typeName, typeEdges] of byType) {
720
+ const policy = GraphAccessPolicyRegistry.GetEdgePolicy(typeName);
721
+ if (!policy) {
722
+ continue;
723
+ }
724
+ for (const principal of principals) {
725
+ const allowed = await this.allowedEdges(typeName, policy, typeEdges, principal, provider, includeProposed);
726
+ for (const e of typeEdges) {
727
+ if (!allowed.has(e.ID)) {
728
+ hidden.add(e.ID);
729
+ }
730
+ }
731
+ }
732
+ }
733
+ return edges.filter((e) => !hidden.has(e.ID));
734
+ }
735
+ async allowedEdges(typeName, policy, edges, principal, provider, includeProposed) {
736
+ try {
737
+ return await policy.FilterEdges(edges, this.policyContext(principal, provider, includeProposed, 0));
738
+ }
739
+ catch (err) {
740
+ const msg = err instanceof Error ? err.message : String(err);
741
+ LogError(`GraphEngine: the access policy for edge type '${typeName}' failed; hiding its edges: ${msg}`);
742
+ return new Set();
743
+ }
583
744
  }
584
745
  touchesFrontier(edge, frontierKeys, direction, provider) {
585
746
  const sKey = this.nodeKey(edge.Source, provider);
@@ -598,7 +759,7 @@ export class GraphEngine extends BaseEngine {
598
759
  return null;
599
760
  }
600
761
  const edgeType = edgeTypesById.Get(row.EdgeTypeID);
601
- const typeName = edgeType?.Name ?? row.EdgeType ?? 'Related To';
762
+ const typeName = edgeType?.Name ?? row.EdgeType ?? GRAPH_DEFAULT_EDGE_TYPE;
602
763
  const weight = typeof row.Weight === 'number' ? row.Weight : (edgeType?.DefaultWeight ?? 1.0);
603
764
  if (!MatchesEdgeTypeFilter(typeName, options.EdgeTypes) || weight < (options.MinWeight ?? 0)) {
604
765
  return null;
@@ -818,7 +979,12 @@ export class GraphEngine extends BaseEngine {
818
979
  /** Derived edges from the graph's active providers, read as `caller`. */
819
980
  async runDerivedProviders(graph, frontier, options, caller, provider) {
820
981
  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));
821
- const request = { Nodes: frontier, Direction: options.Direction ?? 'Both', EdgeTypes: options.EdgeTypes };
982
+ const request = {
983
+ Nodes: frontier,
984
+ Direction: options.Direction ?? 'Both',
985
+ EdgeTypes: options.EdgeTypes,
986
+ IncludeProposed: options.IncludeProposed === true,
987
+ };
822
988
  const edges = [];
823
989
  for (const row of active) {
824
990
  const instance = MJGlobal.Instance.ClassFactory.CreateInstance(BaseGraphEdgeProvider, row.DriverClass);
@@ -847,10 +1013,14 @@ export class GraphEngine extends BaseEngine {
847
1013
  const perPrincipal = await Promise.all(principals.map((p) => this.resolveNodesForPrincipal(normalized, p, provider, includeProposed)));
848
1014
  const visible = perPrincipal[0];
849
1015
  for (const other of perPrincipal.slice(1)) {
850
- for (const key of Array.from(visible.keys())) {
851
- if (!other.has(key)) {
1016
+ for (const [key, view] of Array.from(visible)) {
1017
+ const otherView = other.get(key);
1018
+ if (!otherView) {
852
1019
  visible.delete(key);
853
1020
  }
1021
+ else {
1022
+ visible.set(key, sharedNodeText(view, otherView));
1023
+ }
854
1024
  }
855
1025
  }
856
1026
  if (principals.length > 1) {
@@ -899,9 +1069,14 @@ export class GraphEngine extends BaseEngine {
899
1069
  * entity), and a record that does not come back is invisible. A concept whose `Status` (as this
900
1070
  * principal read it) is not {@link IsGraphConceptStatusVisible} is invisible too.
901
1071
  */
902
- async resolveNodesForPrincipal(nodes, principal, provider, includeProposed) {
1072
+ async resolveNodesForPrincipal(nodes, principal, provider, includeProposed, policyDepth = 0) {
903
1073
  const visible = new Map();
1074
+ if (policyDepth > MAX_POLICY_DEPTH) {
1075
+ LogError(`GraphEngine: access policies nested more than ${MAX_POLICY_DEPTH} deep; hiding ${nodes.length} node(s).`);
1076
+ return visible;
1077
+ }
904
1078
  const buckets = new Map();
1079
+ const replaced = new Map();
905
1080
  const seen = new Set();
906
1081
  for (const node of nodes) {
907
1082
  const key = this.nodeKey(node, provider);
@@ -918,7 +1093,17 @@ export class GraphEngine extends BaseEngine {
918
1093
  continue;
919
1094
  }
920
1095
  const entity = provider.EntityByName(node.EntityName);
921
- if (!entity || !CanUserReadEntity(entity, principal)) {
1096
+ if (!entity) {
1097
+ continue;
1098
+ }
1099
+ const policy = GraphAccessPolicyRegistry.GetNodePolicy(entity.Name);
1100
+ if (policy?.Mode === 'Replace') {
1101
+ const group = replaced.get(entity.Name) ?? { Policy: policy, Nodes: [] };
1102
+ group.Nodes.push({ Key: key, Ref: node });
1103
+ replaced.set(entity.Name, group);
1104
+ continue;
1105
+ }
1106
+ if (!CanUserReadEntity(entity, principal)) {
922
1107
  continue;
923
1108
  }
924
1109
  const bucket = buckets.get(entity.Name) ?? { Entity: entity, Nodes: [] };
@@ -926,8 +1111,103 @@ export class GraphEngine extends BaseEngine {
926
1111
  buckets.set(entity.Name, bucket);
927
1112
  }
928
1113
  await this.resolveDataNodes(Array.from(buckets.values()), principal, provider, includeProposed, visible);
1114
+ const ctx = this.policyContext(principal, provider, includeProposed, policyDepth);
1115
+ await this.readReplacedNodes(replaced, ctx, visible);
1116
+ await this.applyNodePolicies(nodes, ctx, visible);
929
1117
  return visible;
930
1118
  }
1119
+ /** What a policy may use while deciding for `principal`; nested checks run one level deeper. */
1120
+ policyContext(principal, provider, includeProposed, policyDepth) {
1121
+ return {
1122
+ Principal: principal,
1123
+ Provider: provider,
1124
+ IncludeProposed: includeProposed,
1125
+ NodeKey: (node) => this.nodeKey(node, provider),
1126
+ IsCanonGraph: (graphID) => this.isCanonGraphID(graphID),
1127
+ ResolveVisibleKeys: async (refs) => {
1128
+ const normalized = refs.map((r) => this.normalizeNodeRef(r, provider));
1129
+ const found = await this.resolveNodesForPrincipal(normalized, principal, provider, includeProposed, policyDepth + 1);
1130
+ return new Set(found.keys());
1131
+ },
1132
+ };
1133
+ }
1134
+ /** `Replace` policies read their own nodes; a policy that throws hides its nodes. */
1135
+ async readReplacedNodes(replaced, ctx, visible) {
1136
+ for (const [entityName, group] of replaced) {
1137
+ try {
1138
+ const views = await group.Policy.ReadNodes(group.Nodes, ctx);
1139
+ for (const n of group.Nodes) {
1140
+ const view = views.get(n.Key);
1141
+ if (view) {
1142
+ visible.set(n.Key, view);
1143
+ }
1144
+ }
1145
+ }
1146
+ catch (err) {
1147
+ const msg = err instanceof Error ? err.message : String(err);
1148
+ LogError(`GraphEngine: the Replace access policy for '${entityName}' failed; hiding its nodes: ${msg}`);
1149
+ }
1150
+ }
1151
+ }
1152
+ /**
1153
+ * Runs each visible node's entity policy over it. `Hidden` (or a missing decision) removes the
1154
+ * node; `Redacted` keeps it with the neutral label and no description. A policy that throws hides
1155
+ * every node it governs.
1156
+ */
1157
+ async applyNodePolicies(nodes, ctx, visible) {
1158
+ const groups = new Map();
1159
+ for (const node of nodes) {
1160
+ const key = ctx.NodeKey(node);
1161
+ const view = visible.get(key);
1162
+ if (!view || metadataNodeKind(view.EntityName)) {
1163
+ continue;
1164
+ }
1165
+ const policy = GraphAccessPolicyRegistry.GetNodePolicy(view.EntityName);
1166
+ if (!policy) {
1167
+ continue;
1168
+ }
1169
+ const group = groups.get(view.EntityName) ?? { Policy: policy, Nodes: [] };
1170
+ if (!group.Nodes.some((n) => n.Key === key)) {
1171
+ group.Nodes.push({ Key: key, Ref: node, View: view });
1172
+ }
1173
+ groups.set(view.EntityName, group);
1174
+ }
1175
+ for (const [entityName, group] of groups) {
1176
+ const decisions = await this.decideNodes(entityName, group.Policy, group.Nodes, ctx);
1177
+ for (const n of group.Nodes) {
1178
+ this.applyNodeDecision(n, decisions.get(n.Key) ?? 'Hidden', visible);
1179
+ }
1180
+ }
1181
+ }
1182
+ async decideNodes(entityName, policy, nodes, ctx) {
1183
+ try {
1184
+ return await policy.FilterNodes(nodes, ctx);
1185
+ }
1186
+ catch (err) {
1187
+ const msg = err instanceof Error ? err.message : String(err);
1188
+ LogError(`GraphEngine: the access policy for '${entityName}' failed; hiding its nodes: ${msg}`);
1189
+ return new Map();
1190
+ }
1191
+ }
1192
+ applyNodeDecision(node, decision, visible) {
1193
+ if (decision === 'Hidden') {
1194
+ visible.delete(node.Key);
1195
+ return;
1196
+ }
1197
+ const view = visible.get(node.Key);
1198
+ if (decision === 'Redacted' && view) {
1199
+ visible.set(node.Key, { ...view, Label: NeutralGraphNodeLabel(view.EntityName, view.RecordID), Description: null });
1200
+ }
1201
+ }
1202
+ /** `true` when `graphID` is an active graph whose graph type has `IsCanon = 1`. */
1203
+ isCanonGraphID(graphID) {
1204
+ const graph = this.Graphs.find((g) => UUIDsEqual(g.ID, graphID));
1205
+ if (!graph || graph.Status !== 'Active') {
1206
+ return false;
1207
+ }
1208
+ const graphType = this.GraphTypes.find((t) => UUIDsEqual(t.ID, graph.GraphTypeID));
1209
+ return graphType?.IsCanon === true;
1210
+ }
931
1211
  resolveMetadataNode(kind, node, key, principal, provider) {
932
1212
  const base = { Key: key, EntityName: kind, EntityID: provider.EntityByName(kind)?.ID ?? node.EntityID };
933
1213
  if (kind === 'MJ: Entities') {
@@ -1090,6 +1370,16 @@ function sharedEdgeText(edge, others) {
1090
1370
  }
1091
1371
  return { ...edge, Description: description, Attributes: attributes };
1092
1372
  }
1373
+ /**
1374
+ * The text two principals may both see on one node. A node an access policy redacted for one of them
1375
+ * comes back with the neutral label and no description, so any difference means one reader may not
1376
+ * see the other's text: the label falls back to the neutral label and the description to none.
1377
+ */
1378
+ function sharedNodeText(view, other) {
1379
+ const label = view.Label === other.Label ? view.Label : NeutralGraphNodeLabel(view.EntityName, view.RecordID);
1380
+ const description = view.Description === other.Description ? view.Description : null;
1381
+ return label === view.Label && description === view.Description ? view : { ...view, Label: label, Description: description };
1382
+ }
1093
1383
  function isConceptEntity(entity) {
1094
1384
  return entity.Name.trim().toLowerCase() === GRAPH_CONCEPTS_ENTITY.toLowerCase();
1095
1385
  }
@@ -1128,6 +1418,18 @@ export function CanUserReadEntity(entity, user) {
1128
1418
  }
1129
1419
  return entity.GetUserPermisions(user)?.CanRead === true;
1130
1420
  }
1421
+ /**
1422
+ * True only when `user` holds the `Graph: Approve Edges` authorization (directly or via an
1423
+ * ancestor authorization) in `authorizations`. Fails closed when `user`, `authorizations`, or the
1424
+ * seeded `Graph: Approve Edges` authorization is missing.
1425
+ */
1426
+ export function CanUserApproveGraph(user, authorizations) {
1427
+ if (!user || !Array.isArray(authorizations) || authorizations.length === 0) {
1428
+ return false;
1429
+ }
1430
+ const [check] = EvaluateAuthorizationChecks([GRAPH_APPROVE_EDGES_AUTHORIZATION], user, authorizations);
1431
+ return check != null && !check.Unknown && check.Allowed === true;
1432
+ }
1131
1433
  /** Clamp a requested traversal depth to `1..4` (default `2`). */
1132
1434
  export function ClampGraphDepth(requested) {
1133
1435
  const value = requested != null && Number.isFinite(requested) ? Math.floor(requested) : GRAPH_DEFAULT_DEPTH;
@@ -1138,6 +1440,10 @@ export function ClampGraphMaxNodes(requested, fallback = GRAPH_DEFAULT_MAX_NODES
1138
1440
  const value = requested != null && Number.isFinite(requested) ? Math.floor(requested) : fallback;
1139
1441
  return Math.max(1, Math.min(GRAPH_MAX_NODES, value));
1140
1442
  }
1443
+ /** A {@link GraphPath} that found nothing, with the reason. */
1444
+ function notFoundPath(message) {
1445
+ return { Found: false, Nodes: [], Edges: [], PathWeight: 0, Message: message };
1446
+ }
1141
1447
  function compareStrings(a, b) {
1142
1448
  return a < b ? -1 : a > b ? 1 : 0;
1143
1449
  }