@memberjunction/core-actions 6.3.0-edge.1 → 6.3.0-edge.3

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 (127) hide show
  1. package/README.md +28 -0
  2. package/dist/custom/ai/agent-channel.action.d.ts +29 -0
  3. package/dist/custom/ai/agent-channel.action.d.ts.map +1 -0
  4. package/dist/custom/ai/agent-channel.action.js +843 -0
  5. package/dist/custom/ai/agent-channel.action.js.map +1 -0
  6. package/dist/custom/ai/base-find-actions.action.d.ts +6 -0
  7. package/dist/custom/ai/base-find-actions.action.d.ts.map +1 -1
  8. package/dist/custom/ai/base-find-actions.action.js +11 -0
  9. package/dist/custom/ai/base-find-actions.action.js.map +1 -1
  10. package/dist/custom/ai/chief-of-staff-approval-helper.d.ts +16 -0
  11. package/dist/custom/ai/chief-of-staff-approval-helper.d.ts.map +1 -0
  12. package/dist/custom/ai/chief-of-staff-approval-helper.js +63 -0
  13. package/dist/custom/ai/chief-of-staff-approval-helper.js.map +1 -0
  14. package/dist/custom/ai/chief-of-staff-core-reads.action.d.ts +64 -0
  15. package/dist/custom/ai/chief-of-staff-core-reads.action.d.ts.map +1 -0
  16. package/dist/custom/ai/chief-of-staff-core-reads.action.js +1097 -0
  17. package/dist/custom/ai/chief-of-staff-core-reads.action.js.map +1 -0
  18. package/dist/custom/ai/chief-of-staff-rhythms-suggestions.action.d.ts +28 -0
  19. package/dist/custom/ai/chief-of-staff-rhythms-suggestions.action.d.ts.map +1 -0
  20. package/dist/custom/ai/chief-of-staff-rhythms-suggestions.action.js +817 -0
  21. package/dist/custom/ai/chief-of-staff-rhythms-suggestions.action.js.map +1 -0
  22. package/dist/custom/ai/configure-agent-user-policy.action.d.ts +1 -0
  23. package/dist/custom/ai/configure-agent-user-policy.action.d.ts.map +1 -1
  24. package/dist/custom/ai/configure-agent-user-policy.action.js +5 -1
  25. package/dist/custom/ai/configure-agent-user-policy.action.js.map +1 -1
  26. package/dist/custom/ai/get-skill-details.action.d.ts +6 -0
  27. package/dist/custom/ai/get-skill-details.action.d.ts.map +1 -1
  28. package/dist/custom/ai/get-skill-details.action.js +5 -1
  29. package/dist/custom/ai/get-skill-details.action.js.map +1 -1
  30. package/dist/custom/ai/manage-my-agent-instance.action.d.ts +39 -0
  31. package/dist/custom/ai/manage-my-agent-instance.action.d.ts.map +1 -0
  32. package/dist/custom/ai/manage-my-agent-instance.action.js +758 -0
  33. package/dist/custom/ai/manage-my-agent-instance.action.js.map +1 -0
  34. package/dist/custom/ai/prepare-outbound-call-brief.action.js +1 -1
  35. package/dist/custom/ai/prepare-outbound-call-brief.action.js.map +1 -1
  36. package/dist/custom/ai/schedule-next-agent-wake.action.d.ts +2 -0
  37. package/dist/custom/ai/schedule-next-agent-wake.action.d.ts.map +1 -1
  38. package/dist/custom/ai/schedule-next-agent-wake.action.js +105 -2
  39. package/dist/custom/ai/schedule-next-agent-wake.action.js.map +1 -1
  40. package/dist/custom/ai/send-inter-agent-request.action.d.ts +1 -0
  41. package/dist/custom/ai/send-inter-agent-request.action.d.ts.map +1 -1
  42. package/dist/custom/ai/send-inter-agent-request.action.js +72 -18
  43. package/dist/custom/ai/send-inter-agent-request.action.js.map +1 -1
  44. package/dist/custom/ai/test-runtime-action.action.d.ts +3 -0
  45. package/dist/custom/ai/test-runtime-action.action.d.ts.map +1 -1
  46. package/dist/custom/ai/test-runtime-action.action.js +13 -1
  47. package/dist/custom/ai/test-runtime-action.action.js.map +1 -1
  48. package/dist/custom/ai/trigger-agent-wake.action.d.ts +1 -0
  49. package/dist/custom/ai/trigger-agent-wake.action.d.ts.map +1 -1
  50. package/dist/custom/ai/trigger-agent-wake.action.js +3 -0
  51. package/dist/custom/ai/trigger-agent-wake.action.js.map +1 -1
  52. package/dist/custom/ai/user-scoped-communication.action.d.ts +20 -0
  53. package/dist/custom/ai/user-scoped-communication.action.d.ts.map +1 -1
  54. package/dist/custom/ai/user-scoped-communication.action.js +140 -23
  55. package/dist/custom/ai/user-scoped-communication.action.js.map +1 -1
  56. package/dist/custom/artifacts/list-workspace-artifacts.action.d.ts +1 -0
  57. package/dist/custom/artifacts/list-workspace-artifacts.action.d.ts.map +1 -1
  58. package/dist/custom/artifacts/list-workspace-artifacts.action.js +38 -4
  59. package/dist/custom/artifacts/list-workspace-artifacts.action.js.map +1 -1
  60. package/dist/custom/data/adhoc-sql-gate.d.ts +40 -0
  61. package/dist/custom/data/adhoc-sql-gate.d.ts.map +1 -0
  62. package/dist/custom/data/adhoc-sql-gate.js +102 -0
  63. package/dist/custom/data/adhoc-sql-gate.js.map +1 -0
  64. package/dist/custom/data/data-mapper.action.d.ts +8 -0
  65. package/dist/custom/data/data-mapper.action.d.ts.map +1 -1
  66. package/dist/custom/data/data-mapper.action.js +21 -3
  67. package/dist/custom/data/data-mapper.action.js.map +1 -1
  68. package/dist/custom/data/find-graph-path.action.d.ts +60 -0
  69. package/dist/custom/data/find-graph-path.action.d.ts.map +1 -0
  70. package/dist/custom/data/find-graph-path.action.js +285 -0
  71. package/dist/custom/data/find-graph-path.action.js.map +1 -0
  72. package/dist/custom/data/get-entity-details.action.d.ts.map +1 -1
  73. package/dist/custom/data/get-entity-details.action.js +14 -2
  74. package/dist/custom/data/get-entity-details.action.js.map +1 -1
  75. package/dist/custom/data/get-graph-context.action.d.ts +50 -14
  76. package/dist/custom/data/get-graph-context.action.d.ts.map +1 -1
  77. package/dist/custom/data/get-graph-context.action.js +393 -227
  78. package/dist/custom/data/get-graph-context.action.js.map +1 -1
  79. package/dist/custom/data/graph-action-params.d.ts +89 -0
  80. package/dist/custom/data/graph-action-params.d.ts.map +1 -0
  81. package/dist/custom/data/graph-action-params.js +239 -0
  82. package/dist/custom/data/graph-action-params.js.map +1 -0
  83. package/dist/custom/data/mapping-template-guard.d.ts +18 -0
  84. package/dist/custom/data/mapping-template-guard.d.ts.map +1 -0
  85. package/dist/custom/data/mapping-template-guard.js +106 -0
  86. package/dist/custom/data/mapping-template-guard.js.map +1 -0
  87. package/dist/custom/data/propose-canon-domains.action.d.ts +26 -0
  88. package/dist/custom/data/propose-canon-domains.action.d.ts.map +1 -0
  89. package/dist/custom/data/propose-canon-domains.action.js +105 -0
  90. package/dist/custom/data/propose-canon-domains.action.js.map +1 -0
  91. package/dist/custom/data/run-adhoc-query.action.d.ts +4 -21
  92. package/dist/custom/data/run-adhoc-query.action.d.ts.map +1 -1
  93. package/dist/custom/data/run-adhoc-query.action.js +15 -105
  94. package/dist/custom/data/run-adhoc-query.action.js.map +1 -1
  95. package/dist/custom/files/get-file-content.action.d.ts.map +1 -1
  96. package/dist/custom/files/get-file-content.action.js +2 -1
  97. package/dist/custom/files/get-file-content.action.js.map +1 -1
  98. package/dist/custom/integration/http-request.action.d.ts.map +1 -1
  99. package/dist/custom/integration/http-request.action.js +5 -1
  100. package/dist/custom/integration/http-request.action.js.map +1 -1
  101. package/dist/custom/lists/create-list-from-query.action.d.ts +39 -0
  102. package/dist/custom/lists/create-list-from-query.action.d.ts.map +1 -0
  103. package/dist/custom/lists/create-list-from-query.action.js +179 -0
  104. package/dist/custom/lists/create-list-from-query.action.js.map +1 -0
  105. package/dist/custom/lists/index.d.ts +2 -0
  106. package/dist/custom/lists/index.d.ts.map +1 -1
  107. package/dist/custom/lists/index.js +2 -0
  108. package/dist/custom/lists/index.js.map +1 -1
  109. package/dist/custom/search/scoped-search.action.d.ts +12 -1
  110. package/dist/custom/search/scoped-search.action.d.ts.map +1 -1
  111. package/dist/custom/search/scoped-search.action.js +69 -9
  112. package/dist/custom/search/scoped-search.action.js.map +1 -1
  113. package/dist/custom/search/search-query.util.d.ts +24 -0
  114. package/dist/custom/search/search-query.util.d.ts.map +1 -0
  115. package/dist/custom/search/search-query.util.js +211 -0
  116. package/dist/custom/search/search-query.util.js.map +1 -0
  117. package/dist/custom/search/search.action.js +2 -2
  118. package/dist/custom/search/search.action.js.map +1 -1
  119. package/dist/custom/web/url-link-validator.action.d.ts.map +1 -1
  120. package/dist/custom/web/url-link-validator.action.js +3 -1
  121. package/dist/custom/web/url-link-validator.action.js.map +1 -1
  122. package/dist/index.d.ts +8 -0
  123. package/dist/index.d.ts.map +1 -1
  124. package/dist/index.js +8 -0
  125. package/dist/index.js.map +1 -1
  126. package/dist/tsconfig.tsbuildinfo +1 -1
  127. package/package.json +45 -45
@@ -6,294 +6,460 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
6
6
  };
7
7
  var GetGraphContextAction_1;
8
8
  import { BaseAction } from '@memberjunction/actions';
9
- import { LogError } from '@memberjunction/core';
10
- import { CanonGraphEngine, GraphEngine, } from '@memberjunction/core-entities';
11
- import { IndexByUUID, IsPlainObject, RegisterClass } from '@memberjunction/global';
9
+ import { LogError, LogWarning, Metadata } from '@memberjunction/core';
10
+ import { CanonGraphEngine, ComputeTermCoverageScore, GraphEngine, IsConceptEffectiveAsOf, IsGraphConceptStatusVisible, ResolveEffectiveAsOfDate, } from '@memberjunction/core-entities';
11
+ import { UserCache } from '@memberjunction/generic-database-provider';
12
+ import { IndexByUUID, RegisterClass, UUIDMap, UUIDSet } from '@memberjunction/global';
13
+ import { DescribeConceptCandidates, GetGraphActionBoolean, GetGraphActionDate, GetGraphActionNumber, GetGraphActionParam, GetGraphActionString, GetGraphActionWeight, ParseGraphActionItemList, ParseGraphActionStringList, ParseGraphRecordRef, ResolveRequestedGraphScope, SetGraphActionOutput, } from './graph-action-params.js';
14
+ /** Audit Log Type name recorded when `Get Graph Context` resolves to `NO_MATCH`. */
15
+ export const GRAPH_CONTEXT_NO_MATCH_AUDIT_TYPE = 'Graph Context No Match';
16
+ /** Audit Log Type name recorded when `Get Graph Context` resolves to `AMBIGUOUS_CONCEPT`. */
17
+ export const GRAPH_CONTEXT_AMBIGUOUS_AUDIT_TYPE = 'Graph Context Ambiguous Concept';
12
18
  /**
13
- * Action that expands a bounded semantic subgraph from a named graph (`GraphName`, default `'MJ Canon'`)
14
- * starting from a natural-language `Question` (resolved via `CanonGraphEngine.Instance.FindConcepts`)
19
+ * Action that expands a bounded semantic subgraph from the requested graphs (`GraphName` / `GraphNames`;
20
+ * every active Canon graph the caller can see when neither is given — there is no default graph, D52)
21
+ * starting from a natural-language `Question` (resolved via `CanonGraphEngine.Instance.ResolveConcepts`)
15
22
  * and/or explicit `Seeds` (`[{ EntityName, RecordID }]` or concept names).
23
+ *
24
+ * Result codes tell an agent what kind of answer it got:
25
+ * - `SUCCESS`: the inputs resolved and the context is returned.
26
+ * - `AMBIGUOUS_CONCEPT`: the text fits several concepts about equally well (including one name found in
27
+ * several graphs). The context covers all of them and `Candidates` lists them with their graphs, so the
28
+ * agent can ask which one is meant instead of guessing.
29
+ * - `NO_MATCH`: nothing the caller may see matched. This is an answer, not an error.
30
+ * - `ACCESS_DENIED`: the caller does not have permission to read the requested graph; never logged as a gap.
16
31
  */
17
32
  let GetGraphContextAction = class GetGraphContextAction extends BaseAction {
18
33
  static { GetGraphContextAction_1 = this; }
19
- static { this.DEFAULT_GRAPH_NAME = 'MJ Canon'; }
20
34
  static { this.DEFAULT_DEPTH = 2; }
21
35
  static { this.MAX_DEPTH = 4; }
22
36
  static { this.DEFAULT_MAX_NODES = 50; }
23
37
  static { this.MAX_NODES_CAP = 200; }
38
+ static { this.QUESTION_SEEDS = 5; }
39
+ static { this.SEED_TEXT_MATCHES = 3; }
40
+ static { this.MAX_AUDIT_DESCRIPTION_LENGTH = 1000; } // Caps summary length in AuditLog.Description
41
+ static { this.MAX_AUDIT_QUESTION_LENGTH = 500; } // Caps stored caller question text written as System user so untrusted input cannot bloat AuditLog.Details
42
+ static { this.GAP_ALERT_WRITE_TIMEOUT_MS = 2000; } // Bounds inline wait for gap-alert audit writes so slow inserts never stall action responses
24
43
  async InternalRunAction(params) {
25
44
  try {
26
45
  if (!params.ContextUser) {
27
- return {
28
- Success: false,
29
- ResultCode: 'MISSING_PARAMETER',
30
- Message: 'ContextUser is required to run Get Graph Context.',
31
- };
46
+ return { Success: false, ResultCode: 'MISSING_PARAMETER', Message: 'ContextUser is required to run Get Graph Context.' };
32
47
  }
33
- // GraphEngine is lazily configured; on a server it loads as the system user, and every node it
34
- // returns is checked as ContextUser at the hop it is reached.
48
+ // GraphEngine is lazily configured; on a server it loads as the system user, and every graph
49
+ // and node it returns is checked as ContextUser.
35
50
  await CanonGraphEngine.Instance.EnsureConfigured(params.ContextUser, params.Provider);
36
- const graphName = this.getStringParam(params, 'GraphName')?.trim() || GetGraphContextAction_1.DEFAULT_GRAPH_NAME;
37
- const graph = GraphEngine.Instance.GetGraph(graphName);
38
- if (!graph) {
51
+ const scope = ResolveRequestedGraphScope(params);
52
+ if (scope.Explicit) {
53
+ if (scope.Names.length === 0) {
54
+ return {
55
+ Success: false,
56
+ ResultCode: 'GRAPH_NOT_FOUND',
57
+ Message: 'No active graph names were provided.',
58
+ };
59
+ }
60
+ const provider = params.Provider ?? Metadata.Provider;
61
+ const graphsEntity = provider?.EntityByName('MJ: Graphs');
62
+ const canReadGraphsEntity = graphsEntity ? Boolean(graphsEntity.GetUserPermisions(params.ContextUser)?.CanRead) : true;
63
+ if (!canReadGraphsEntity) {
64
+ const emptySubgraph = { Nodes: [], Edges: [] };
65
+ SetGraphActionOutput(params, 'Subgraph', emptySubgraph);
66
+ SetGraphActionOutput(params, 'PromptText', '');
67
+ SetGraphActionOutput(params, 'NodeCount', 0);
68
+ SetGraphActionOutput(params, 'EdgeCount', 0);
69
+ SetGraphActionOutput(params, 'Candidates', []);
70
+ SetGraphActionOutput(params, 'Resolution', 'NoAccess');
71
+ return {
72
+ Success: true,
73
+ ResultCode: 'ACCESS_DENIED',
74
+ Resolution: 'NoAccess',
75
+ Subgraph: emptySubgraph,
76
+ PromptText: '',
77
+ NodeCount: 0,
78
+ EdgeCount: 0,
79
+ Candidates: [],
80
+ Message: `Caller does not have permission to read requested graph(s): ${scope.Names.join(', ')}.`,
81
+ };
82
+ }
83
+ for (const name of scope.Names) {
84
+ if (!(await GraphEngine.Instance.GetGraphForUser(name, params.ContextUser, undefined, params.Provider, 'Read'))) {
85
+ return { Success: false, ResultCode: 'GRAPH_NOT_FOUND', Message: `Graph '${name}' was not found or is not active.` };
86
+ }
87
+ }
88
+ }
89
+ const question = GetGraphActionString(params, 'Question');
90
+ const rawSeeds = GetGraphActionParam(params, 'Seeds');
91
+ if (!question && ParseGraphActionItemList(rawSeeds).length === 0) {
92
+ return { Success: false, ResultCode: 'MISSING_PARAMETER', Message: 'Either Question or Seeds must be provided to Get Graph Context.' };
93
+ }
94
+ const asOfDate = GetGraphActionDate(params, 'AsOfDate');
95
+ if (asOfDate.Provided && !asOfDate.Valid) {
39
96
  return {
40
97
  Success: false,
41
- ResultCode: 'GRAPH_NOT_FOUND',
42
- Message: `Graph '${graphName}' was not found or is not active.`,
98
+ ResultCode: 'INVALID_PARAMETER',
99
+ Message: "Parameter 'AsOfDate' must be a valid ISO date or timestamp with timezone offset (for example, '2024-06-15' or '2024-06-15T00:00:00Z').",
43
100
  };
44
101
  }
45
- const question = this.getStringParam(params, 'Question')?.trim();
46
- const rawSeeds = this.getParamValue(params, 'Seeds');
47
- const requestedDepth = this.getNumericParam(params, 'Depth', GetGraphContextAction_1.DEFAULT_DEPTH);
48
- const depth = Math.max(1, Math.min(GetGraphContextAction_1.MAX_DEPTH, Math.floor(requestedDepth)));
49
- const requestedMaxNodes = this.getNumericParam(params, 'MaxNodes', GetGraphContextAction_1.DEFAULT_MAX_NODES);
50
- const maxNodes = Math.max(1, Math.min(GetGraphContextAction_1.MAX_NODES_CAP, Math.floor(requestedMaxNodes)));
51
- const edgeTypes = this.parseEdgeTypesParam(this.getParamValue(params, 'EdgeTypes'));
52
- const minWeightRaw = this.getParamValue(params, 'MinWeight');
53
- const minWeight = minWeightRaw != null && Number.isFinite(Number(minWeightRaw))
54
- ? Math.max(0, Math.min(1, Number(minWeightRaw)))
55
- : undefined;
56
- const includeProposed = this.getBooleanParam(params, 'IncludeProposed', false);
57
- const seeds = await this.resolveSeeds(question, rawSeeds, graph.Name, includeProposed, params);
58
- if (!question && seeds.length === 0) {
102
+ // Findings 247 & 249: resolve "now" ONCE per action call when AsOfDate is omitted, and preserve
103
+ // date-only strings verbatim so action and engine agree on whole-UTC-day overlap semantics.
104
+ const effectiveAsOf = asOfDate.Provided && asOfDate.AsOfValue !== undefined
105
+ ? asOfDate.AsOfValue
106
+ : ResolveEffectiveAsOfDate(undefined);
107
+ const visibleGraphs = await CanonGraphEngine.Instance.ResolveReadableActiveGraphs(scope.Explicit ? scope.Names : undefined, params.ContextUser, { Provider: params.Provider });
108
+ if (visibleGraphs.length === 0) {
109
+ const emptySubgraph = { Nodes: [], Edges: [] };
110
+ SetGraphActionOutput(params, 'Subgraph', emptySubgraph);
111
+ SetGraphActionOutput(params, 'PromptText', '');
112
+ SetGraphActionOutput(params, 'NodeCount', 0);
113
+ SetGraphActionOutput(params, 'EdgeCount', 0);
114
+ SetGraphActionOutput(params, 'Candidates', []);
115
+ if (!scope.Explicit) {
116
+ const hasSemanticProvider = CanonGraphEngine.Instance.GetSemanticSearchProvider() !== null;
117
+ SetGraphActionOutput(params, 'Resolution', 'NoMatch');
118
+ if (hasSemanticProvider) {
119
+ SetGraphActionOutput(params, 'CoverageScore', 0);
120
+ }
121
+ return {
122
+ Success: true,
123
+ ResultCode: 'NO_MATCH',
124
+ Resolution: 'NoMatch',
125
+ Subgraph: emptySubgraph,
126
+ PromptText: '',
127
+ NodeCount: 0,
128
+ EdgeCount: 0,
129
+ Candidates: [],
130
+ ...(hasSemanticProvider ? { CoverageScore: 0 } : {}),
131
+ Message: 'No matching graph nodes found for the supplied inputs.',
132
+ };
133
+ }
134
+ const deniedNames = scope.Names.join(', ');
135
+ SetGraphActionOutput(params, 'Resolution', 'NoAccess');
59
136
  return {
60
- Success: false,
61
- ResultCode: 'MISSING_PARAMETER',
62
- Message: 'Either Question or Seeds must be provided to Get Graph Context.',
137
+ Success: true,
138
+ ResultCode: 'ACCESS_DENIED',
139
+ Resolution: 'NoAccess',
140
+ Subgraph: emptySubgraph,
141
+ PromptText: '',
142
+ NodeCount: 0,
143
+ EdgeCount: 0,
144
+ Candidates: [],
145
+ Message: `Caller does not have access to graph '${deniedNames}'.`,
63
146
  };
64
147
  }
65
- const options = {
66
- Depth: depth,
67
- MaxNodes: maxNodes,
68
- Direction: 'Both',
69
- EdgeTypes: edgeTypes,
70
- MinWeight: minWeight,
71
- IncludeProposed: includeProposed,
72
- };
73
- const subgraph = seeds.length > 0
74
- ? await GraphEngine.Instance.Subgraph(graph.Name, seeds, options, params.ContextUser, params.Provider)
75
- : { Nodes: [], Edges: [] };
76
- const promptText = GraphEngine.Instance.DescribeForPrompt(subgraph);
77
- const nodeCount = subgraph.Nodes.length;
78
- const edgeCount = subgraph.Edges.length;
79
- this.addOutputParam(params, 'Subgraph', subgraph);
80
- this.addOutputParam(params, 'PromptText', promptText);
81
- this.addOutputParam(params, 'NodeCount', nodeCount);
82
- this.addOutputParam(params, 'EdgeCount', edgeCount);
83
- return {
84
- Success: true,
85
- ResultCode: 'SUCCESS',
86
- Message: nodeCount > 0
87
- ? promptText
88
- : `No matching graph nodes found in '${graph.Name}' for the supplied inputs.${subgraph.Message ? ` ${subgraph.Message}` : ''}`,
89
- Subgraph: subgraph,
90
- PromptText: promptText,
91
- NodeCount: nodeCount,
92
- EdgeCount: edgeCount,
148
+ const options = this.buildTraversalOptions(params, effectiveAsOf);
149
+ const visibleGraphNames = visibleGraphs.map((g) => g.Name);
150
+ const conceptSearch = {
151
+ GraphNames: visibleGraphNames,
152
+ IncludeProposed: options.IncludeProposed === true,
153
+ AsOfDate: effectiveAsOf,
154
+ provider: params.Provider,
93
155
  };
156
+ const visibleGraphIds = new UUIDSet(visibleGraphs.map((g) => g.ID));
157
+ const resolved = await this.resolveSeeds(visibleGraphIds, question, rawSeeds, conceptSearch, params);
158
+ const subgraph = await this.expandVisibleGraphs(visibleGraphs, resolved.Seeds, options, params);
159
+ const explicitLabel = scope.Explicit ? scope.Names.join(', ') : undefined;
160
+ const result = this.buildResult(params, explicitLabel, question, subgraph, resolved);
161
+ await this.logGapAlertBounded(result, this.selectGapAlertGraph(result, visibleGraphs), question, params.ContextUser, params.Provider);
162
+ return result;
94
163
  }
95
164
  catch (error) {
96
165
  const msg = error instanceof Error ? error.message : String(error);
97
166
  LogError(`GetGraphContextAction failed: ${msg}`);
98
- return {
99
- Success: false,
100
- ResultCode: 'UNEXPECTED_ERROR',
101
- Message: `Get Graph Context failed: ${msg}`,
102
- };
167
+ return { Success: false, ResultCode: 'UNEXPECTED_ERROR', Message: `Get Graph Context failed: ${msg}` };
103
168
  }
104
169
  }
105
170
  /**
106
- * Seeds from the question (concept matches the caller can see, in `graphName`) and from explicit
107
- * `Seeds` (record references, or concept names/IDs). Every seed is checked again as the caller when
108
- * the traversal admits it.
171
+ * The graph a gap alert is recorded against. With several graphs in scope no graph is preferred (D52):
172
+ * an ambiguous result is recorded against the graph of its first candidate, and anything else against
173
+ * the first graph the request covered.
109
174
  */
110
- async resolveSeeds(question, rawSeeds, graphName, includeProposed, params) {
111
- const user = params.ContextUser;
112
- const resolved = [];
113
- const seenKeys = new Set();
114
- const pushSeed = (ref) => {
115
- const key = `${ref.EntityName.trim().toLowerCase()}:${ref.RecordID.trim().toLowerCase()}`;
116
- if (!seenKeys.has(key)) {
117
- seenKeys.add(key);
118
- resolved.push(ref);
175
+ selectGapAlertGraph(result, visibleGraphs) {
176
+ const byId = new UUIDMap();
177
+ for (const g of visibleGraphs) {
178
+ byId.Set(g.ID, g);
179
+ }
180
+ for (const candidate of result.Candidates ?? []) {
181
+ const graph = candidate.GraphID ? byId.Get(candidate.GraphID) : undefined;
182
+ if (graph) {
183
+ return graph;
119
184
  }
185
+ }
186
+ return visibleGraphs[0];
187
+ }
188
+ buildTraversalOptions(params, asOfDate) {
189
+ const depth = GetGraphActionNumber(params, 'Depth', GetGraphContextAction_1.DEFAULT_DEPTH);
190
+ const maxNodes = GetGraphActionNumber(params, 'MaxNodes', GetGraphContextAction_1.DEFAULT_MAX_NODES);
191
+ return {
192
+ Depth: Math.max(1, Math.min(GetGraphContextAction_1.MAX_DEPTH, Math.floor(depth))),
193
+ MaxNodes: Math.max(1, Math.min(GetGraphContextAction_1.MAX_NODES_CAP, Math.floor(maxNodes))),
194
+ Direction: 'Both',
195
+ EdgeTypes: ParseGraphActionStringList(GetGraphActionParam(params, 'EdgeTypes')),
196
+ MinWeight: GetGraphActionWeight(params, 'MinWeight'),
197
+ IncludeProposed: GetGraphActionBoolean(params, 'IncludeProposed', false),
198
+ ...(asOfDate !== undefined ? { AsOfDate: asOfDate } : {}),
120
199
  };
121
- const conceptSearch = { GraphNames: [graphName], IncludeProposed: includeProposed, provider: params.Provider };
122
- if (question && question.length > 0) {
123
- const matched = await CanonGraphEngine.Instance.FindConcepts(question, user, conceptSearch);
124
- for (const c of matched.slice(0, 5)) {
125
- pushSeed({
126
- EntityName: c.EntityName,
127
- EntityID: c.EntityID,
128
- RecordID: c.RecordID,
129
- });
130
- }
200
+ }
201
+ buildResult(params, explicitGraphLabel, question, subgraph, resolved) {
202
+ const promptText = GraphEngine.Instance.DescribeForPrompt(subgraph);
203
+ const nodeCount = subgraph.Nodes.length;
204
+ const edgeCount = subgraph.Edges.length;
205
+ const resolution = resolved.Ambiguous.length > 0 ? 'Ambiguous' : nodeCount > 0 ? 'Matched' : 'NoMatch';
206
+ const semanticResolutions = resolved.Resolutions.filter((r) => r.CoverageScore !== undefined);
207
+ const coverageScore = semanticResolutions.length === 0
208
+ ? undefined
209
+ : semanticResolutions.length === 1
210
+ ? semanticResolutions[0].CoverageScore
211
+ : ComputeTermCoverageScore(semanticResolutions);
212
+ SetGraphActionOutput(params, 'Subgraph', subgraph);
213
+ SetGraphActionOutput(params, 'PromptText', promptText);
214
+ SetGraphActionOutput(params, 'NodeCount', nodeCount);
215
+ SetGraphActionOutput(params, 'EdgeCount', edgeCount);
216
+ SetGraphActionOutput(params, 'Resolution', resolution);
217
+ SetGraphActionOutput(params, 'Candidates', DescribeConceptCandidates(resolved.Ambiguous));
218
+ if (coverageScore !== undefined) {
219
+ SetGraphActionOutput(params, 'CoverageScore', coverageScore);
131
220
  }
132
- const parsedList = this.parseRawSeedList(rawSeeds);
133
- const concepts = GraphEngine.Instance.Concepts;
134
- const conceptsById = IndexByUUID(concepts);
135
- const conceptsByName = new Map(concepts.map((c) => [c.Name.trim().toLowerCase(), c]));
136
- for (const item of parsedList) {
137
- if (typeof item === 'string') {
138
- const trimmed = item.trim();
139
- if (!trimmed) {
140
- continue;
141
- }
142
- const lower = trimmed.toLowerCase();
143
- const exactConcept = conceptsByName.get(lower) ?? conceptsById.Get(trimmed);
144
- if (exactConcept) {
145
- pushSeed({
146
- EntityName: 'MJ: Graph Concepts',
147
- RecordID: exactConcept.ID,
148
- });
149
- }
150
- else {
151
- const fuzzyConcepts = await CanonGraphEngine.Instance.FindConcepts(trimmed, user, conceptSearch);
152
- for (const fc of fuzzyConcepts.slice(0, 3)) {
153
- pushSeed({
154
- EntityName: fc.EntityName,
155
- EntityID: fc.EntityID,
156
- RecordID: fc.RecordID,
157
- });
158
- }
159
- }
160
- }
161
- else if (IsPlainObject(item)) {
162
- const entityName = typeof item['EntityName'] === 'string'
163
- ? item['EntityName'].trim()
164
- : typeof item['entityName'] === 'string'
165
- ? item['entityName'].trim()
166
- : '';
167
- const recordId = item['RecordID'] != null
168
- ? String(item['RecordID']).trim()
169
- : item['recordId'] != null
170
- ? String(item['recordId']).trim()
171
- : '';
172
- if (entityName && recordId) {
173
- pushSeed({
174
- EntityName: entityName,
175
- EntityID: typeof item['EntityID'] === 'string' ? item['EntityID'] : undefined,
176
- RecordID: recordId,
177
- });
178
- }
179
- }
221
+ const base = {
222
+ Subgraph: subgraph,
223
+ PromptText: promptText,
224
+ NodeCount: nodeCount,
225
+ EdgeCount: edgeCount,
226
+ Resolution: resolution,
227
+ Candidates: resolved.Ambiguous,
228
+ ...(coverageScore !== undefined ? { CoverageScore: coverageScore } : {}),
229
+ };
230
+ if (resolution === 'Ambiguous') {
231
+ const names = resolved.Ambiguous.map((c) => `"${c.Node.Label}"`).join(', ');
232
+ const subject = question ? `"${question}"` : 'A concept seed';
233
+ return {
234
+ ...base,
235
+ Success: true,
236
+ ResultCode: 'AMBIGUOUS_CONCEPT',
237
+ Message: `${subject} fits several concepts about equally well: ${names}. The context below covers all of them. ` +
238
+ `Ask which one is meant, or call again with Seeds set to the chosen candidate's concept ID (RecordID) or specify GraphName.\n\n${promptText}`,
239
+ };
240
+ }
241
+ if (resolution === 'NoMatch') {
242
+ const scopeSuffix = explicitGraphLabel ? ` in '${explicitGraphLabel}'` : '';
243
+ const unavailableSuffix = resolved.UnavailableReasons.length > 0 ? ` ${resolved.UnavailableReasons[0]}` : '';
244
+ return {
245
+ ...base,
246
+ Success: true,
247
+ ResultCode: 'NO_MATCH',
248
+ Message: `No matching graph nodes found${scopeSuffix} for the supplied inputs.${subgraph.Message ? ` ${subgraph.Message}` : ''}${unavailableSuffix}`,
249
+ };
180
250
  }
181
- return resolved;
251
+ return { ...base, Success: true, ResultCode: 'SUCCESS', Message: promptText };
182
252
  }
183
- parseRawSeedList(rawSeeds) {
184
- if (rawSeeds == null) {
185
- return [];
253
+ async expandVisibleGraphs(visibleGraphs, seeds, options, params) {
254
+ if (seeds.length === 0) {
255
+ return { Nodes: [], Edges: [] };
186
256
  }
187
- if (Array.isArray(rawSeeds)) {
188
- return rawSeeds;
257
+ if (visibleGraphs.length === 1) {
258
+ return GraphEngine.Instance.Subgraph(visibleGraphs[0].Name, [...seeds], options, params.ContextUser, params.Provider);
189
259
  }
190
- if (typeof rawSeeds === 'string') {
191
- const trimmed = rawSeeds.trim();
192
- if (!trimmed) {
193
- return [];
260
+ const conceptById = IndexByUUID(GraphEngine.Instance.Concepts);
261
+ const unscopedSeeds = [];
262
+ const seedsByGraphId = new UUIDMap();
263
+ for (const seed of seeds) {
264
+ const concept = seed.EntityName.trim().toLowerCase() === 'mj: graph concepts' ? conceptById.Get(seed.RecordID) : undefined;
265
+ if (!concept) {
266
+ unscopedSeeds.push(seed);
194
267
  }
195
- if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
196
- try {
197
- const parsed = JSON.parse(trimmed);
198
- return Array.isArray(parsed) ? parsed : [parsed];
199
- }
200
- catch {
201
- return [trimmed];
202
- }
268
+ else {
269
+ const list = seedsByGraphId.Get(concept.GraphID) ?? [];
270
+ list.push(seed);
271
+ seedsByGraphId.Set(concept.GraphID, list);
203
272
  }
204
- return trimmed
205
- .split(',')
206
- .map((s) => s.trim())
207
- .filter(Boolean);
208
273
  }
209
- if (typeof rawSeeds === 'object') {
210
- return [rawSeeds];
274
+ const subgraphs = [];
275
+ for (const g of visibleGraphs) {
276
+ const graphSeeds = [...unscopedSeeds, ...(seedsByGraphId.Get(g.ID) ?? [])];
277
+ if (graphSeeds.length > 0) {
278
+ subgraphs.push(await GraphEngine.Instance.Subgraph(g.Name, graphSeeds, options, params.ContextUser, params.Provider));
279
+ }
211
280
  }
212
- return [];
213
- }
214
- parseEdgeTypesParam(raw) {
215
- if (raw == null) {
216
- return undefined;
281
+ if (subgraphs.length === 0) {
282
+ return { Nodes: [], Edges: [] };
217
283
  }
218
- if (Array.isArray(raw)) {
219
- const list = raw.map((x) => String(x).trim()).filter(Boolean);
220
- return list.length > 0 ? list : undefined;
284
+ if (subgraphs.length === 1) {
285
+ return subgraphs[0];
221
286
  }
222
- if (typeof raw === 'string') {
223
- const trimmed = raw.trim();
224
- if (!trimmed) {
225
- return undefined;
287
+ const nodeMap = new Map(subgraphs.flatMap((sg) => sg.Nodes.map((n) => [n.Key, n])));
288
+ const edgeMap = new Map(subgraphs.flatMap((sg) => sg.Edges.map((e) => [e.ID, e])));
289
+ const messages = subgraphs.map((sg) => sg.Message).filter((m) => Boolean(m));
290
+ return {
291
+ Nodes: Array.from(nodeMap.values()),
292
+ Edges: Array.from(edgeMap.values()),
293
+ ...(messages.length > 0 ? { Message: messages.join(' ') } : {}),
294
+ };
295
+ }
296
+ async resolveSeeds(graphIds, question, rawSeeds, conceptSearch, params) {
297
+ const result = { Seeds: [], Ambiguous: [], Resolutions: [], UnavailableReasons: [] };
298
+ const seenKeys = new Set();
299
+ const pushSeed = (ref) => {
300
+ const key = `${ref.EntityName.trim().toLowerCase()}:${ref.RecordID.trim().toLowerCase()}`;
301
+ if (!seenKeys.has(key)) {
302
+ seenKeys.add(key);
303
+ result.Seeds.push(ref);
226
304
  }
227
- if (trimmed.startsWith('[')) {
228
- try {
229
- const parsed = JSON.parse(trimmed);
230
- if (Array.isArray(parsed)) {
231
- const list = parsed.map((x) => String(x).trim()).filter(Boolean);
232
- return list.length > 0 ? list : undefined;
305
+ };
306
+ if (question) {
307
+ await this.addTextSeeds(question, GetGraphContextAction_1.QUESTION_SEEDS, conceptSearch, params, result, pushSeed);
308
+ }
309
+ const allConceptsById = IndexByUUID(GraphEngine.Instance.Concepts);
310
+ const conceptsById = IndexByUUID(GraphEngine.Instance.Concepts.filter((c) => graphIds.Has(c.GraphID)));
311
+ for (const item of ParseGraphActionItemList(rawSeeds)) {
312
+ const record = ParseGraphRecordRef(item);
313
+ if (record) {
314
+ if (record.EntityName.trim().toLowerCase() === 'mj: graph concepts') {
315
+ const owning = allConceptsById.Get(record.RecordID);
316
+ if (owning && !graphIds.Has(owning.GraphID)) {
317
+ continue;
318
+ }
319
+ }
320
+ pushSeed(record);
321
+ }
322
+ else if (typeof item === 'string' && item.trim()) {
323
+ const text = item.trim();
324
+ const byId = conceptsById.Get(text);
325
+ if (byId) {
326
+ if (IsGraphConceptStatusVisible(byId.Status, conceptSearch.IncludeProposed === true) &&
327
+ IsConceptEffectiveAsOf(byId.EffectiveFrom, byId.EffectiveTo, conceptSearch.AsOfDate)) {
328
+ pushSeed({ EntityName: 'MJ: Graph Concepts', RecordID: byId.ID });
233
329
  }
234
330
  }
235
- catch {
236
- // fall through to CSV split
331
+ else {
332
+ await this.addTextSeeds(text, GetGraphContextAction_1.SEED_TEXT_MATCHES, conceptSearch, params, result, pushSeed);
237
333
  }
238
334
  }
239
- const list = trimmed
240
- .split(',')
241
- .map((s) => s.trim())
242
- .filter(Boolean);
243
- return list.length > 0 ? list : undefined;
244
335
  }
245
- return undefined;
246
- }
247
- getParamValue(params, name) {
248
- const lower = name.trim().toLowerCase();
249
- const found = params.Params?.find((p) => p.Name.trim().toLowerCase() === lower);
250
- return found?.Value;
251
- }
252
- getStringParam(params, name) {
253
- const val = this.getParamValue(params, name);
254
- return val != null ? String(val) : undefined;
336
+ return result;
255
337
  }
256
- getNumericParam(params, name, defaultValue) {
257
- const val = this.getParamValue(params, name);
258
- if (val != null) {
259
- const num = Number(val);
260
- if (Number.isFinite(num)) {
261
- return num;
262
- }
338
+ /** Seed from concepts matching `text`: the tied candidates when ambiguous, else the best `limit`. */
339
+ async addTextSeeds(text, limit, conceptSearch, params, result, pushSeed) {
340
+ const useSemantic = CanonGraphEngine.Instance.GetSemanticSearchProvider() !== null;
341
+ const resolution = useSemantic
342
+ ? await CanonGraphEngine.Instance.ResolveConceptsSemantic(text, params.ContextUser, conceptSearch.Provider ?? conceptSearch.provider, {
343
+ GraphName: conceptSearch.GraphName,
344
+ GraphNames: conceptSearch.GraphNames,
345
+ AudienceReaders: conceptSearch.AudienceReaders,
346
+ IncludeProposed: conceptSearch.IncludeProposed,
347
+ ...(conceptSearch.AsOfDate !== undefined ? { AsOfDate: conceptSearch.AsOfDate } : {}),
348
+ })
349
+ : await CanonGraphEngine.Instance.ResolveConcepts(text, params.ContextUser, conceptSearch);
350
+ result.Resolutions.push(resolution);
351
+ if (resolution.UnavailableReason) {
352
+ result.UnavailableReasons.push(resolution.UnavailableReason);
353
+ }
354
+ const chosen = resolution.Status === 'Ambiguous' ? resolution.Candidates : resolution.Matches.slice(0, limit);
355
+ if (resolution.Status === 'Ambiguous') {
356
+ result.Ambiguous.push(...resolution.Candidates);
357
+ }
358
+ for (const match of chosen) {
359
+ pushSeed({ EntityName: match.Node.EntityName, EntityID: match.Node.EntityID, RecordID: match.Node.RecordID });
263
360
  }
264
- return defaultValue;
265
361
  }
266
- getBooleanParam(params, name, defaultValue) {
267
- const val = this.getParamValue(params, name);
268
- if (typeof val === 'boolean') {
269
- return val;
362
+ /**
363
+ * Runs {@link logGapAlertIfNeeded} with a bounded inline wait so a slow audit-log insert
364
+ * cannot stall the action response while normal/fast inserts still complete deterministically.
365
+ */
366
+ async logGapAlertBounded(result, graph, question, contextUser, actionProvider) {
367
+ if (result.ResultCode !== 'NO_MATCH' && result.ResultCode !== 'AMBIGUOUS_CONCEPT') {
368
+ return;
270
369
  }
271
- if (val != null) {
272
- const str = String(val).trim().toLowerCase();
273
- if (str === 'true' || str === '1' || str === 'yes') {
274
- return true;
370
+ const writePromise = this.logGapAlertIfNeeded(result, graph, question, contextUser, actionProvider).catch((error) => {
371
+ const msg = error instanceof Error ? error.message : String(error);
372
+ LogWarning(`GetGraphContextAction gap alert failed: ${msg}`);
373
+ });
374
+ let timer;
375
+ const timeoutPromise = new Promise((resolve) => {
376
+ timer = setTimeout(() => {
377
+ LogWarning(`GetGraphContextAction gap alert exceeded ${GetGraphContextAction_1.GAP_ALERT_WRITE_TIMEOUT_MS}ms; detaching audit write so response is not delayed.`);
378
+ resolve();
379
+ }, GetGraphContextAction_1.GAP_ALERT_WRITE_TIMEOUT_MS);
380
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer && typeof timer.unref === 'function') {
381
+ timer.unref();
275
382
  }
276
- if (str === 'false' || str === '0' || str === 'no') {
277
- return false;
383
+ });
384
+ try {
385
+ await Promise.race([writePromise, timeoutPromise]);
386
+ }
387
+ finally {
388
+ if (timer !== undefined) {
389
+ clearTimeout(timer);
278
390
  }
279
391
  }
280
- return defaultValue;
281
392
  }
282
- addOutputParam(params, name, value) {
283
- if (!params.Params) {
393
+ /**
394
+ * Emits a fault-isolated `MJ: Audit Logs` gap alert when `Get Graph Context` returns `NO_MATCH`
395
+ * or `AMBIGUOUS_CONCEPT`. Failures in metadata lookup or persistence log a warning and never
396
+ * fail or alter the action result.
397
+ */
398
+ async logGapAlertIfNeeded(result, graph, question, contextUser, actionProvider) {
399
+ if (result.ResultCode !== 'NO_MATCH' && result.ResultCode !== 'AMBIGUOUS_CONCEPT') {
284
400
  return;
285
401
  }
286
- const existing = params.Params.find((p) => p.Name.trim().toLowerCase() === name.trim().toLowerCase() && p.Type === 'Output');
287
- if (existing) {
288
- existing.Value = value;
402
+ const gapResolution = result.ResultCode;
403
+ const auditTypeName = gapResolution === 'NO_MATCH' ? GRAPH_CONTEXT_NO_MATCH_AUDIT_TYPE : GRAPH_CONTEXT_AMBIGUOUS_AUDIT_TYPE;
404
+ try {
405
+ const provider = actionProvider ?? Metadata.Provider;
406
+ if (!provider) {
407
+ LogWarning(`GetGraphContextAction gap alert skipped (${auditTypeName}): no metadata provider available.`);
408
+ return;
409
+ }
410
+ const normalizedTypeName = auditTypeName.trim().toLowerCase();
411
+ const auditType = provider.AuditLogTypes?.find((t) => (t.Name ?? '').trim().toLowerCase() === normalizedTypeName);
412
+ if (!auditType) {
413
+ LogWarning(`GetGraphContextAction gap alert skipped: AuditLogType '${auditTypeName}' is not seeded in metadata.`);
414
+ return;
415
+ }
416
+ const writer = UserCache.Instance.GetSystemUser() ?? contextUser;
417
+ const auditLog = await provider.GetEntityObject('MJ: Audit Logs', writer);
418
+ if (!auditLog) {
419
+ LogWarning(`GetGraphContextAction gap alert skipped (${auditTypeName}): GetEntityObject returned null.`);
420
+ return;
421
+ }
422
+ const candidates = result.Candidates ?? [];
423
+ const cappedQuestion = this.capAuditQuestion(question);
424
+ auditLog.NewRecord();
425
+ auditLog.UserID = contextUser.ID;
426
+ auditLog.AuditLogTypeID = auditType.ID;
427
+ auditLog.Status = 'Success';
428
+ auditLog.EntityID = provider.EntityByName('MJ: Graphs')?.ID ?? null;
429
+ auditLog.RecordID = graph.ID;
430
+ auditLog.Description = this.buildGapAlertDescription(gapResolution, graph.Name, cappedQuestion, candidates.length);
431
+ auditLog.Details = JSON.stringify(this.buildGapAlertDetails(graph.Name, cappedQuestion, gapResolution, candidates, contextUser.ID));
432
+ const saved = await auditLog.Save();
433
+ if (!saved) {
434
+ LogWarning(`GetGraphContextAction gap alert save failed (${auditTypeName}): ${auditLog.LatestResult?.CompleteMessage ?? 'unknown save error'}`);
435
+ }
436
+ }
437
+ catch (error) {
438
+ const msg = error instanceof Error ? error.message : String(error);
439
+ LogWarning(`GetGraphContextAction gap alert failed (${auditTypeName}): ${msg}`);
289
440
  }
290
- else {
291
- params.Params.push({
292
- Name: name,
293
- Value: value,
294
- Type: 'Output',
295
- });
441
+ }
442
+ capAuditQuestion(question) {
443
+ if (!question) {
444
+ return null;
296
445
  }
446
+ return question.length > GetGraphContextAction_1.MAX_AUDIT_QUESTION_LENGTH
447
+ ? question.slice(0, GetGraphContextAction_1.MAX_AUDIT_QUESTION_LENGTH)
448
+ : question;
449
+ }
450
+ buildGapAlertDetails(graphName, question, resolution, candidates, userId) {
451
+ return {
452
+ graphName,
453
+ question,
454
+ resolution,
455
+ candidates: candidates.map((c) => ({ RecordID: c.Node.RecordID, Score: c.Score })),
456
+ userId,
457
+ };
458
+ }
459
+ buildGapAlertDescription(resolution, graphName, question, candidateCount) {
460
+ const subject = question ? `question "${question}"` : 'explicit seeds';
461
+ const candidateSuffix = resolution === 'AMBIGUOUS_CONCEPT' ? ` (${candidateCount} candidates)` : '';
462
+ return `Canon gap alert (${resolution}) in '${graphName}'${candidateSuffix} for ${subject}`.slice(0, GetGraphContextAction_1.MAX_AUDIT_DESCRIPTION_LENGTH);
297
463
  }
298
464
  };
299
465
  GetGraphContextAction = GetGraphContextAction_1 = __decorate([