@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
@@ -0,0 +1,627 @@
1
+ import { RunView } from '@memberjunction/core';
2
+ import { EscapeSQLString, UUIDMap, UUIDSet } from '@memberjunction/global';
3
+ import { QueryEngine } from '../engines/QueryEngine.js';
4
+ import { IsGraphDataProvider, } from './BaseGraphEdgeProvider.js';
5
+ import { CanUserReadEntity, GraphEngine, IsFieldReadableByAll, IsGraphConceptStatusVisible, NeutralGraphNodeLabel, } from './GraphEngine.js';
6
+ const ENTITY_GRAPH_CONCEPTS = 'MJ: Graph Concepts';
7
+ const ENTITY_GRAPH_EDGES = 'MJ: Graph Edges';
8
+ const ENTITY_ENTITIES = 'MJ: Entities';
9
+ const ENTITY_ENTITY_FIELDS = 'MJ: Entity Fields';
10
+ const ENTITY_ALTERNATE_BASE_VIEWS = 'MJ: Entity Alternate Base Views';
11
+ const ENTITY_QUERIES = 'MJ: Queries';
12
+ /** Seeded edge types rendered in Section 1 (Precedence & Equivalence). */
13
+ const PRECEDENCE_EDGE_TYPES = new Set([
14
+ 'Preferred Over',
15
+ 'Supersedes',
16
+ 'Contradicts',
17
+ 'Same As',
18
+ ]);
19
+ /** Seeded artifact → concept edge types (source = artifact, target = concept, per MJ #6842). */
20
+ const ARTIFACT_TO_CONCEPT_EDGE_TYPES = new Set([
21
+ 'Defines',
22
+ 'Measures',
23
+ 'Describes',
24
+ 'Implements',
25
+ ]);
26
+ /** Seeded concept-to-concept relationship edge types shown under concept definitions. */
27
+ const CONCEPT_RELATION_EDGE_TYPES = new Set([
28
+ 'BroaderThan',
29
+ 'Governs',
30
+ 'DependsOn',
31
+ 'RelatedTo',
32
+ 'Same As',
33
+ 'Supersedes',
34
+ 'Preferred Over',
35
+ ]);
36
+ /**
37
+ * Render a governed Canon graph (or a question/subgraph slice of it) into a deterministic
38
+ * Markdown document. All reads are checked as `user` and every principal in `AudienceReaders`.
39
+ */
40
+ export async function RenderCanonDocumentMarkdown(graphName, user, options, resolveQuestionSubgraph) {
41
+ if (!user) {
42
+ return '';
43
+ }
44
+ const engine = GraphEngine.Instance;
45
+ const provider = options.Provider ?? engine.ProviderToUse;
46
+ if (!IsGraphDataProvider(provider)) {
47
+ return '';
48
+ }
49
+ const graph = engine.GetGraph(graphName);
50
+ if (!graph) {
51
+ return '';
52
+ }
53
+ const principals = [user, ...(options.AudienceReaders ?? [])];
54
+ const includeProposed = options.IncludeProposed === true;
55
+ const includeSpecs = options.IncludeSpecifications !== false;
56
+ const entityFilterSet = options.EntityNames?.length
57
+ ? new Set(options.EntityNames.map((n) => n.trim().toLowerCase()).filter(Boolean))
58
+ : null;
59
+ const conceptTypeFilterSet = options.ConceptTypes?.length
60
+ ? new Set(options.ConceptTypes.map((t) => t.trim().toLowerCase()).filter(Boolean))
61
+ : null;
62
+ const ownerIndex = buildMetadataOwnerIndex(provider);
63
+ let subgraph = options.Subgraph ?? null;
64
+ if (!subgraph && options.Question?.trim()) {
65
+ subgraph = await resolveQuestionSubgraph(options.Question.trim(), graph.Name);
66
+ }
67
+ let resolvedEdges;
68
+ let visibleConcepts;
69
+ let scope = null;
70
+ if (subgraph) {
71
+ scope = buildScopeFromSubgraph(subgraph, provider, ownerIndex);
72
+ resolvedEdges = resolveEdgesFromSubgraph(subgraph);
73
+ const conceptIDs = Array.from(scope.ConceptIDs);
74
+ visibleConcepts = await readVisibleConcepts(graph.ID, conceptIDs, includeProposed, user, principals, options.AudienceReaders, provider);
75
+ }
76
+ else {
77
+ const storedRows = await readGraphStoredEdgesAsPrincipals(graph.ID, includeProposed, principals, provider);
78
+ resolvedEdges = await resolveStoredEdgesForPrincipals(graph.Name, storedRows, includeProposed, user, principals, options.AudienceReaders, provider);
79
+ visibleConcepts = await readVisibleConcepts(graph.ID, null, includeProposed, user, principals, options.AudienceReaders, provider);
80
+ }
81
+ const sections = [
82
+ `# Organizational Canon & Domain Knowledge (${graph.Name})`,
83
+ ];
84
+ const precedenceSection = renderPrecedenceSection(resolvedEdges, entityFilterSet, provider, ownerIndex);
85
+ if (precedenceSection) {
86
+ sections.push(precedenceSection);
87
+ }
88
+ const conceptsSection = renderConceptsSection(visibleConcepts, resolvedEdges, conceptTypeFilterSet, entityFilterSet, includeSpecs, principals, provider, ownerIndex);
89
+ if (conceptsSection) {
90
+ sections.push(conceptsSection);
91
+ }
92
+ const abvSection = renderAlternateBaseViewsSection(resolvedEdges, entityFilterSet, scope, principals, provider);
93
+ if (abvSection) {
94
+ sections.push(abvSection);
95
+ }
96
+ const queriesSection = renderGovernedQueriesSection(resolvedEdges, entityFilterSet, scope, principals);
97
+ if (queriesSection) {
98
+ sections.push(queriesSection);
99
+ }
100
+ let document = sections.join('\n\n');
101
+ if (options.MaxChars && options.MaxChars > 0 && document.length > options.MaxChars) {
102
+ document = `${document.slice(0, options.MaxChars)}\n\n...[truncated to ${options.MaxChars} chars]`;
103
+ }
104
+ return document;
105
+ }
106
+ // ─── Data Loading (Caller + Audience RLS, FLS, & Graph Access Policies) ──────
107
+ async function readGraphStoredEdgesAsPrincipals(graphID, includeProposed, principals, provider) {
108
+ const edgeEntity = provider.EntityByName(ENTITY_GRAPH_EDGES);
109
+ if (edgeEntity && !principals.every((p) => CanUserReadEntity(edgeEntity, p))) {
110
+ return [];
111
+ }
112
+ const statuses = includeProposed ? `'Approved', 'Proposed'` : `'Approved'`;
113
+ const params = {
114
+ EntityName: ENTITY_GRAPH_EDGES,
115
+ ExtraFilter: `[GraphID] = '${EscapeSQLString(graphID)}' AND [Status] IN (${statuses})`,
116
+ Fields: [
117
+ 'ID',
118
+ 'EdgeTypeID',
119
+ 'EdgeType',
120
+ 'SourceEntityID',
121
+ 'SourceEntity',
122
+ 'SourceRecordID',
123
+ 'TargetEntityID',
124
+ 'TargetEntity',
125
+ 'TargetRecordID',
126
+ 'Description',
127
+ 'Origin',
128
+ 'Status',
129
+ 'Weight',
130
+ ],
131
+ ResultType: 'simple',
132
+ };
133
+ const rv = RunView.FromMetadataProvider(provider);
134
+ const results = await Promise.all(principals.map((p) => rv.RunView(params, p)));
135
+ let rows = null;
136
+ for (const res of results) {
137
+ if (!res.Success) {
138
+ return [];
139
+ }
140
+ const ids = new UUIDSet(res.Results.map((r) => r.ID));
141
+ rows = rows === null ? res.Results : rows.filter((r) => ids.Has(r.ID));
142
+ }
143
+ return rows ?? [];
144
+ }
145
+ async function resolveStoredEdgesForPrincipals(graphName, rows, includeProposed, user, principals, audienceReaders, provider) {
146
+ if (rows.length === 0) {
147
+ return [];
148
+ }
149
+ const engine = GraphEngine.Instance;
150
+ const edgeEntity = provider.EntityByName(ENTITY_GRAPH_EDGES);
151
+ const canReadEdgeDesc = !edgeEntity || IsFieldReadableByAll(edgeEntity, 'Description', principals);
152
+ const edgeTypesByID = new UUIDMap(engine.EdgeTypes.map((et) => [et.ID, et]));
153
+ const refs = [];
154
+ const seenKeys = new Set();
155
+ const collectRef = (entityID, entityNameFallback, recordID) => {
156
+ const entityName = (entityNameFallback || provider.EntityByID(entityID)?.Name || '').trim();
157
+ if (!entityName || !recordID) {
158
+ return null;
159
+ }
160
+ const ref = { EntityName: entityName, EntityID: entityID, RecordID: recordID };
161
+ const key = engine.GetNodeKey(ref);
162
+ if (!seenKeys.has(key)) {
163
+ seenKeys.add(key);
164
+ refs.push(ref);
165
+ }
166
+ return ref;
167
+ };
168
+ const edgeViews = [];
169
+ for (const row of rows) {
170
+ const src = collectRef(row.SourceEntityID, row.SourceEntity, row.SourceRecordID);
171
+ const tgt = collectRef(row.TargetEntityID, row.TargetEntity, row.TargetRecordID);
172
+ if (!src || !tgt) {
173
+ continue;
174
+ }
175
+ const et = edgeTypesByID.Get(row.EdgeTypeID);
176
+ const typeName = (et?.Name ?? row.EdgeType ?? '').trim();
177
+ if (!typeName) {
178
+ continue;
179
+ }
180
+ edgeViews.push({
181
+ ID: row.ID,
182
+ GraphName: graphName,
183
+ TypeName: typeName,
184
+ InverseTypeName: et?.InverseName ?? null,
185
+ IsDirected: et?.IsDirected !== false,
186
+ Source: src,
187
+ Target: tgt,
188
+ Weight: typeof row.Weight === 'number' ? row.Weight : 1,
189
+ Description: canReadEdgeDesc ? (row.Description ?? null) : null,
190
+ Attributes: null,
191
+ Origin: row.Origin === 'Inferred' ? 'Inferred' : 'Declared',
192
+ Status: row.Status === 'Proposed' ? 'Proposed' : 'Approved',
193
+ Confidence: null,
194
+ });
195
+ }
196
+ const [visibleNodes, policyAllowedEdges] = await Promise.all([
197
+ engine.FilterNodesForUser(refs, user, audienceReaders, {
198
+ IncludeProposed: includeProposed,
199
+ Provider: provider,
200
+ }),
201
+ engine.FilterEdgesForUser(edgeViews, user, audienceReaders, {
202
+ IncludeProposed: includeProposed,
203
+ Provider: provider,
204
+ }),
205
+ ]);
206
+ const resolved = [];
207
+ for (const edge of policyAllowedEdges) {
208
+ const srcView = visibleNodes.get(engine.GetNodeKey(edge.Source));
209
+ const tgtView = visibleNodes.get(engine.GetNodeKey(edge.Target));
210
+ if (!srcView || !tgtView) {
211
+ continue;
212
+ }
213
+ resolved.push({
214
+ TypeName: edge.TypeName,
215
+ Source: srcView,
216
+ Target: tgtView,
217
+ Description: edge.Description,
218
+ });
219
+ }
220
+ return resolved;
221
+ }
222
+ function resolveEdgesFromSubgraph(subgraph) {
223
+ const engine = GraphEngine.Instance;
224
+ const nodeByKey = new Map(subgraph.Nodes.map((n) => [n.Key, n]));
225
+ const resolved = [];
226
+ for (const edge of subgraph.Edges) {
227
+ const src = nodeByKey.get(engine.GetNodeKey(edge.Source));
228
+ const tgt = nodeByKey.get(engine.GetNodeKey(edge.Target));
229
+ if (!src || !tgt) {
230
+ continue;
231
+ }
232
+ resolved.push({
233
+ TypeName: edge.TypeName,
234
+ Source: src,
235
+ Target: tgt,
236
+ Description: edge.Description,
237
+ });
238
+ }
239
+ return resolved;
240
+ }
241
+ async function readVisibleConcepts(graphID, conceptIDs, includeProposed, user, principals, audienceReaders, provider) {
242
+ if (conceptIDs !== null && conceptIDs.length === 0) {
243
+ return [];
244
+ }
245
+ const conceptEntity = provider.EntityByName(ENTITY_GRAPH_CONCEPTS);
246
+ if (conceptEntity && !principals.every((p) => CanUserReadEntity(conceptEntity, p))) {
247
+ return [];
248
+ }
249
+ const canReadName = !conceptEntity || IsFieldReadableByAll(conceptEntity, 'Name', principals);
250
+ const statuses = includeProposed ? `'Approved', 'Proposed'` : `'Approved'`;
251
+ const idClause = conceptIDs !== null
252
+ ? ` AND [ID] IN (${conceptIDs.map((id) => `'${EscapeSQLString(id)}'`).join(', ')})`
253
+ : '';
254
+ const params = {
255
+ EntityName: ENTITY_GRAPH_CONCEPTS,
256
+ ExtraFilter: `[GraphID] = '${EscapeSQLString(graphID)}' AND [Status] IN (${statuses})${idClause}`,
257
+ Fields: ['ID', 'Name', 'ConceptType', 'Description', 'Specification', 'Synonyms', 'AuthorityTier', 'Status'],
258
+ ResultType: 'simple',
259
+ };
260
+ const rv = RunView.FromMetadataProvider(provider);
261
+ const results = await Promise.all(principals.map((p) => rv.RunView(params, p)));
262
+ let rows = null;
263
+ for (const res of results) {
264
+ if (!res.Success) {
265
+ return [];
266
+ }
267
+ const ids = new UUIDSet(res.Results.map((r) => r.ID));
268
+ rows = rows === null ? res.Results : rows.filter((r) => ids.Has(r.ID));
269
+ }
270
+ const allowedIDs = conceptIDs !== null ? new UUIDSet(conceptIDs) : null;
271
+ const candidates = (rows ?? []).filter((r) => IsGraphConceptStatusVisible(r.Status, includeProposed) &&
272
+ (allowedIDs === null || allowedIDs.Has(r.ID)));
273
+ if (candidates.length === 0) {
274
+ return [];
275
+ }
276
+ const refs = candidates.map((c) => ({ EntityName: ENTITY_GRAPH_CONCEPTS, RecordID: c.ID }));
277
+ const visible = await GraphEngine.Instance.FilterNodesForUser(refs, user, audienceReaders, {
278
+ IncludeProposed: includeProposed,
279
+ Provider: provider,
280
+ });
281
+ const sanitized = [];
282
+ for (const c of candidates) {
283
+ const key = GraphEngine.Instance.GetNodeKey({ EntityName: ENTITY_GRAPH_CONCEPTS, RecordID: c.ID });
284
+ const view = visible.get(key);
285
+ if (!view) {
286
+ continue;
287
+ }
288
+ const neutralLabel = NeutralGraphNodeLabel(ENTITY_GRAPH_CONCEPTS, c.ID);
289
+ const isRedacted = !canReadName || (view.Label === neutralLabel && c.Name !== neutralLabel);
290
+ if (isRedacted) {
291
+ sanitized.push({
292
+ ...c,
293
+ Name: view.Label,
294
+ Description: null,
295
+ Specification: null,
296
+ Synonyms: null,
297
+ AuthorityTier: null,
298
+ });
299
+ }
300
+ else {
301
+ sanitized.push(c);
302
+ }
303
+ }
304
+ return sanitized.sort((a, b) => a.Name.localeCompare(b.Name) || compareText(a.ID, b.ID));
305
+ }
306
+ // ─── Scope & Metadata Indexing ───────────────────────────────────────────────
307
+ function buildMetadataOwnerIndex(provider) {
308
+ const fieldMap = new UUIDMap();
309
+ const abvMap = new UUIDMap();
310
+ for (const ent of provider.Entities) {
311
+ for (const f of ent.Fields) {
312
+ fieldMap.Set(f.ID, ent.Name);
313
+ }
314
+ for (const abv of ent.AlternateBaseViews ?? []) {
315
+ abvMap.Set(abv.ID, ent.Name);
316
+ }
317
+ }
318
+ return { FieldEntityNameByID: fieldMap, AbvEntityNameByID: abvMap };
319
+ }
320
+ function buildScopeFromSubgraph(subgraph, provider, ownerIndex) {
321
+ const scope = {
322
+ ConceptIDs: new UUIDSet(),
323
+ EntityNamesLower: new Set(),
324
+ AbvIDs: new UUIDSet(),
325
+ QueryIDs: new UUIDSet(),
326
+ };
327
+ for (const node of subgraph.Nodes) {
328
+ addNodeToScope(node.EntityName, node.RecordID, scope, provider, ownerIndex);
329
+ }
330
+ return scope;
331
+ }
332
+ function addNodeToScope(entityName, recordID, scope, provider, ownerIndex) {
333
+ const lower = entityName.trim().toLowerCase();
334
+ if (lower === ENTITY_GRAPH_CONCEPTS.toLowerCase()) {
335
+ scope.ConceptIDs.Add(recordID);
336
+ return;
337
+ }
338
+ if (lower === ENTITY_ENTITIES.toLowerCase()) {
339
+ const ent = provider.EntityByID(recordID);
340
+ if (ent) {
341
+ scope.EntityNamesLower.add(ent.Name.trim().toLowerCase());
342
+ }
343
+ return;
344
+ }
345
+ if (lower === ENTITY_ENTITY_FIELDS.toLowerCase()) {
346
+ const owner = ownerIndex.FieldEntityNameByID.Get(recordID);
347
+ if (owner) {
348
+ scope.EntityNamesLower.add(owner.trim().toLowerCase());
349
+ }
350
+ return;
351
+ }
352
+ if (lower === ENTITY_ALTERNATE_BASE_VIEWS.toLowerCase()) {
353
+ scope.AbvIDs.Add(recordID);
354
+ const owner = ownerIndex.AbvEntityNameByID.Get(recordID);
355
+ if (owner) {
356
+ scope.EntityNamesLower.add(owner.trim().toLowerCase());
357
+ }
358
+ return;
359
+ }
360
+ if (lower === ENTITY_QUERIES.toLowerCase()) {
361
+ scope.QueryIDs.Add(recordID);
362
+ }
363
+ }
364
+ // ─── Section Renderers ───────────────────────────────────────────────────────
365
+ function renderPrecedenceSection(edges, entityFilterSet, provider, ownerIndex) {
366
+ const matching = edges
367
+ .filter((e) => PRECEDENCE_EDGE_TYPES.has(e.TypeName))
368
+ .filter((e) => {
369
+ if (!entityFilterSet) {
370
+ return true;
371
+ }
372
+ const srcOwner = owningEntityName(e.Source, provider, ownerIndex);
373
+ const tgtOwner = owningEntityName(e.Target, provider, ownerIndex);
374
+ return ((srcOwner !== null && entityFilterSet.has(srcOwner.toLowerCase())) ||
375
+ (tgtOwner !== null && entityFilterSet.has(tgtOwner.toLowerCase())));
376
+ })
377
+ .sort((a, b) => a.TypeName.localeCompare(b.TypeName) ||
378
+ a.Source.Label.localeCompare(b.Source.Label) ||
379
+ a.Target.Label.localeCompare(b.Target.Label));
380
+ if (matching.length === 0) {
381
+ return null;
382
+ }
383
+ const lines = ['## 1. Precedence & Deprecation Rules'];
384
+ for (const edge of matching) {
385
+ const verb = formatPrecedenceVerb(edge.TypeName);
386
+ const reason = edge.Description?.trim() ? ` — ${edge.Description.trim()}` : '';
387
+ lines.push(`- **${edge.Source.Label}** ${verb} **${edge.Target.Label}**${reason}`);
388
+ }
389
+ return lines.join('\n');
390
+ }
391
+ function formatPrecedenceVerb(edgeType) {
392
+ switch (edgeType) {
393
+ case 'Preferred Over':
394
+ return 'is PREFERRED OVER';
395
+ case 'Supersedes':
396
+ return 'SUPERSEDES';
397
+ case 'Contradicts':
398
+ return 'CONTRADICTS';
399
+ case 'Same As':
400
+ return 'is SAME AS';
401
+ default:
402
+ return edgeType.toUpperCase();
403
+ }
404
+ }
405
+ function indexConceptEdges(edges) {
406
+ const artifactMap = new UUIDMap();
407
+ const relatedMap = new UUIDMap();
408
+ const conceptEntityLower = ENTITY_GRAPH_CONCEPTS.toLowerCase();
409
+ for (const e of edges) {
410
+ const srcIsConcept = e.Source.EntityName.trim().toLowerCase() === conceptEntityLower;
411
+ const tgtIsConcept = e.Target.EntityName.trim().toLowerCase() === conceptEntityLower;
412
+ // Per MJ #6842: Defines, Measures, Describes, Implements are artifact → concept
413
+ if (ARTIFACT_TO_CONCEPT_EDGE_TYPES.has(e.TypeName) && tgtIsConcept) {
414
+ const list = artifactMap.Get(e.Target.RecordID) ?? [];
415
+ list.push(e);
416
+ artifactMap.Set(e.Target.RecordID, list);
417
+ }
418
+ if (CONCEPT_RELATION_EDGE_TYPES.has(e.TypeName) && srcIsConcept && tgtIsConcept) {
419
+ const sortKey = `${e.TypeName}\0${e.Source.Label}\0${e.Target.Label}`;
420
+ const outList = relatedMap.Get(e.Source.RecordID) ?? [];
421
+ outList.push({ SortKey: sortKey, Text: `${e.TypeName} → ${e.Target.Label}` });
422
+ relatedMap.Set(e.Source.RecordID, outList);
423
+ if (e.Source.Key !== e.Target.Key) {
424
+ const inList = relatedMap.Get(e.Target.RecordID) ?? [];
425
+ inList.push({ SortKey: sortKey, Text: `${e.Source.Label} → ${e.TypeName}` });
426
+ relatedMap.Set(e.Target.RecordID, inList);
427
+ }
428
+ }
429
+ }
430
+ return { ArtifactEdgesByConceptID: artifactMap, RelatedItemsByConceptID: relatedMap };
431
+ }
432
+ function renderConceptsSection(concepts, edges, conceptTypeFilterSet, entityFilterSet, includeSpecifications, principals, provider, ownerIndex) {
433
+ const conceptEntity = provider.EntityByName(ENTITY_GRAPH_CONCEPTS);
434
+ const canReadDesc = !conceptEntity || IsFieldReadableByAll(conceptEntity, 'Description', principals);
435
+ const canReadSpec = !conceptEntity || IsFieldReadableByAll(conceptEntity, 'Specification', principals);
436
+ const canReadSynonyms = !conceptEntity || IsFieldReadableByAll(conceptEntity, 'Synonyms', principals);
437
+ const canReadAuthority = !conceptEntity || IsFieldReadableByAll(conceptEntity, 'AuthorityTier', principals);
438
+ const edgeIndex = indexConceptEdges(edges);
439
+ const blocks = [];
440
+ for (const concept of concepts) {
441
+ if (conceptTypeFilterSet && !conceptTypeFilterSet.has((concept.ConceptType || '').trim().toLowerCase())) {
442
+ continue;
443
+ }
444
+ const artifactEdges = [...(edgeIndex.ArtifactEdgesByConceptID.Get(concept.ID) ?? [])].sort((a, b) => a.TypeName.localeCompare(b.TypeName) || a.Source.Label.localeCompare(b.Source.Label));
445
+ if (entityFilterSet) {
446
+ const touchesEntity = artifactEdges.some((e) => {
447
+ const owner = owningEntityName(e.Source, provider, ownerIndex);
448
+ return owner !== null && entityFilterSet.has(owner.toLowerCase());
449
+ });
450
+ if (!touchesEntity) {
451
+ continue;
452
+ }
453
+ }
454
+ const relatedItems = [...(edgeIndex.RelatedItemsByConceptID.Get(concept.ID) ?? [])].sort((a, b) => compareText(a.SortKey, b.SortKey));
455
+ const authorityLabel = canReadAuthority && concept.AuthorityTier ? ` — Authority: ${concept.AuthorityTier}` : '';
456
+ const statusBadge = concept.Status === 'Proposed' ? ' [Proposed]' : '';
457
+ const entry = [`### ${concept.Name} (${concept.ConceptType || 'Term'})${authorityLabel}${statusBadge}`];
458
+ if (canReadSynonyms) {
459
+ const synonyms = parseSynonyms(concept.Synonyms);
460
+ if (synonyms.length > 0) {
461
+ entry.push(`- **Synonyms:** ${synonyms.join(', ')}`);
462
+ }
463
+ }
464
+ if (canReadDesc && concept.Description?.trim()) {
465
+ entry.push(`- **Definition:** ${concept.Description.trim()}`);
466
+ }
467
+ if (includeSpecifications && canReadSpec && concept.Specification?.trim()) {
468
+ entry.push(`- **Specification:** ${concept.Specification.trim()}`);
469
+ }
470
+ if (artifactEdges.length > 0) {
471
+ const formatted = artifactEdges.map((e) => `${e.Source.Label} (${e.TypeName})`);
472
+ entry.push(`- **Grounded By:** ${formatted.join('; ')}`);
473
+ }
474
+ if (relatedItems.length > 0) {
475
+ entry.push(`- **Related Concepts:** ${relatedItems.map((i) => i.Text).join('; ')}`);
476
+ }
477
+ blocks.push(entry.join('\n'));
478
+ }
479
+ if (blocks.length === 0) {
480
+ return null;
481
+ }
482
+ return `## 2. Domain Concepts & Definitions\n\n${blocks.join('\n\n')}`;
483
+ }
484
+ function indexArtifactConceptRoles(edges, sourceEntityLower, allowedTypes) {
485
+ const bySourceID = new UUIDMap();
486
+ const conceptEntityLower = ENTITY_GRAPH_CONCEPTS.toLowerCase();
487
+ for (const e of edges) {
488
+ if (allowedTypes.has(e.TypeName) &&
489
+ e.Source.EntityName.trim().toLowerCase() === sourceEntityLower &&
490
+ e.Target.EntityName.trim().toLowerCase() === conceptEntityLower) {
491
+ const list = bySourceID.Get(e.Source.RecordID) ?? [];
492
+ list.push(`${e.TypeName}: ${e.Target.Label}`);
493
+ bySourceID.Set(e.Source.RecordID, list);
494
+ }
495
+ }
496
+ return bySourceID;
497
+ }
498
+ function renderAlternateBaseViewsSection(edges, entityFilterSet, scope, principals, provider) {
499
+ const entities = [...provider.Entities]
500
+ .filter((e) => principals.every((p) => CanUserReadEntity(e, p)))
501
+ .sort((a, b) => a.Name.localeCompare(b.Name));
502
+ // Per MJ #6842: ABV --Defines/Measures--> Concept
503
+ const rolesByAbvID = indexArtifactConceptRoles(edges, ENTITY_ALTERNATE_BASE_VIEWS.toLowerCase(), new Set(['Defines', 'Measures']));
504
+ const lines = ['## 3. Canonical Alternate Base Views'];
505
+ for (const entity of entities) {
506
+ if (entityFilterSet && !entityFilterSet.has(entity.Name.trim().toLowerCase())) {
507
+ continue;
508
+ }
509
+ const activeAbvs = [...(entity.AlternateBaseViews ?? [])]
510
+ .filter((v) => v.Status === 'Active')
511
+ .sort((a, b) => a.ViewName.localeCompare(b.ViewName));
512
+ for (const abv of activeAbvs) {
513
+ if (scope &&
514
+ !scope.AbvIDs.Has(abv.ID) &&
515
+ !scope.EntityNamesLower.has(entity.Name.trim().toLowerCase())) {
516
+ continue;
517
+ }
518
+ const linkedConcepts = [...(rolesByAbvID.Get(abv.ID) ?? [])].sort();
519
+ const viewName = abv.ViewName || abv.Name;
520
+ const viewRef = entity.SchemaName
521
+ ? `\`[${entity.SchemaName}].[${viewName}]\``
522
+ : `\`${viewName}\``;
523
+ const desc = abv.Description?.trim() ? ` — ${abv.Description.trim()}` : '';
524
+ lines.push(`- **${entity.Name} → ${abv.Name}** (${viewRef})${desc}`);
525
+ if (linkedConcepts.length > 0) {
526
+ lines.push(` - **Canon Role:** ${linkedConcepts.join('; ')}`);
527
+ }
528
+ }
529
+ }
530
+ return lines.length > 1 ? lines.join('\n') : null;
531
+ }
532
+ function renderGovernedQueriesSection(edges, entityFilterSet, scope, principals) {
533
+ const queries = [...(QueryEngine.Instance.Queries ?? [])].sort((a, b) => {
534
+ const pathA = a.CategoryPath ? `${a.CategoryPath}/${a.Name}` : a.Name;
535
+ const pathB = b.CategoryPath ? `${b.CategoryPath}/${b.Name}` : b.Name;
536
+ return pathA.localeCompare(pathB) || compareText(a.ID, b.ID);
537
+ });
538
+ const queriesByID = new UUIDMap(queries.map((q) => [q.ID, q]));
539
+ const queryEntitiesByQueryID = new UUIDMap();
540
+ for (const qe of QueryEngine.Instance.QueryEntities ?? []) {
541
+ const list = queryEntitiesByQueryID.Get(qe.QueryID) ?? [];
542
+ list.push(qe);
543
+ queryEntitiesByQueryID.Set(qe.QueryID, list);
544
+ }
545
+ const depsByQueryID = new UUIDMap();
546
+ for (const dep of QueryEngine.Instance.QueryDependencies ?? []) {
547
+ const list = depsByQueryID.Get(dep.QueryID) ?? [];
548
+ list.push(dep);
549
+ depsByQueryID.Set(dep.QueryID, list);
550
+ }
551
+ // Per MJ #6842: Query --Measures/Defines--> Concept
552
+ const rolesByQueryID = indexArtifactConceptRoles(edges, ENTITY_QUERIES.toLowerCase(), new Set(['Measures', 'Defines']));
553
+ const lines = ['## 4. Governed Ground-Truth Queries'];
554
+ for (const query of queries) {
555
+ if (query.Status !== 'Approved') {
556
+ continue;
557
+ }
558
+ if (!principals.every((p) => query.UserCanRun(p).canRun)) {
559
+ continue;
560
+ }
561
+ const qEntities = queryEntitiesByQueryID.Get(query.ID) ?? [];
562
+ if (entityFilterSet &&
563
+ !qEntities.some((qe) => entityFilterSet.has((qe.Entity ?? '').trim().toLowerCase()))) {
564
+ continue;
565
+ }
566
+ if (scope &&
567
+ !scope.QueryIDs.Has(query.ID) &&
568
+ !qEntities.some((qe) => scope.EntityNamesLower.has((qe.Entity ?? '').trim().toLowerCase()))) {
569
+ continue;
570
+ }
571
+ const measuredConcepts = [...(rolesByQueryID.Get(query.ID) ?? [])].sort();
572
+ const readTargets = qEntities
573
+ .map((qe) => (qe.AlternateBaseView ? `${qe.Entity}.${qe.AlternateBaseView}` : qe.Entity || qe.EntityID))
574
+ .filter(Boolean)
575
+ .sort();
576
+ const composedTargets = (depsByQueryID.Get(query.ID) ?? [])
577
+ .map((d) => queriesByID.Get(d.DependsOnQueryID)?.Name ?? d.DependsOnQuery ?? d.ReferencePath)
578
+ .filter(Boolean)
579
+ .sort();
580
+ const fullPath = query.CategoryPath ? `${query.CategoryPath}/${query.Name}` : query.Name;
581
+ const desc = query.Description?.trim() ? ` — ${query.Description.trim()}` : '';
582
+ lines.push(`- **\`${fullPath}\`**${desc}`);
583
+ if (measuredConcepts.length > 0) {
584
+ lines.push(` - **Canon Role:** ${measuredConcepts.join('; ')}`);
585
+ }
586
+ if (readTargets.length > 0) {
587
+ lines.push(` - **Reads:** ${readTargets.map((r) => `\`${r}\``).join(', ')}`);
588
+ }
589
+ if (composedTargets.length > 0) {
590
+ lines.push(` - **Composes:** ${composedTargets.map((c) => `\`${c}\``).join(', ')}`);
591
+ }
592
+ }
593
+ return lines.length > 1 ? lines.join('\n') : null;
594
+ }
595
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
596
+ function owningEntityName(node, provider, ownerIndex) {
597
+ const lower = node.EntityName.trim().toLowerCase();
598
+ if (lower === ENTITY_ENTITIES.toLowerCase()) {
599
+ return provider.EntityByID(node.RecordID)?.Name ?? node.Label;
600
+ }
601
+ if (lower === ENTITY_ENTITY_FIELDS.toLowerCase()) {
602
+ return ownerIndex.FieldEntityNameByID.Get(node.RecordID) ?? null;
603
+ }
604
+ if (lower === ENTITY_ALTERNATE_BASE_VIEWS.toLowerCase()) {
605
+ return ownerIndex.AbvEntityNameByID.Get(node.RecordID) ?? null;
606
+ }
607
+ return null;
608
+ }
609
+ function parseSynonyms(raw) {
610
+ if (!raw) {
611
+ return [];
612
+ }
613
+ try {
614
+ const parsed = JSON.parse(raw);
615
+ if (Array.isArray(parsed)) {
616
+ return parsed.map((item) => String(item).trim()).filter(Boolean);
617
+ }
618
+ }
619
+ catch {
620
+ return raw.split(',').map((s) => s.trim()).filter(Boolean);
621
+ }
622
+ return [];
623
+ }
624
+ function compareText(a, b) {
625
+ return a < b ? -1 : a > b ? 1 : 0;
626
+ }
627
+ //# sourceMappingURL=CanonDocumentRenderer.js.map