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

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 (188) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/custom/AnchoredConversationSecurity.d.ts +10 -1
  3. package/dist/custom/AnchoredConversationSecurity.d.ts.map +1 -1
  4. package/dist/custom/AnchoredConversationSecurity.js +15 -0
  5. package/dist/custom/AnchoredConversationSecurity.js.map +1 -1
  6. package/dist/custom/ArtifactLockValidation.d.ts +28 -0
  7. package/dist/custom/ArtifactLockValidation.d.ts.map +1 -0
  8. package/dist/custom/ArtifactLockValidation.js +867 -0
  9. package/dist/custom/ArtifactLockValidation.js.map +1 -0
  10. package/dist/custom/ArtifactPermissionDelegate.d.ts +267 -0
  11. package/dist/custom/ArtifactPermissionDelegate.d.ts.map +1 -0
  12. package/dist/custom/ArtifactPermissionDelegate.js +1232 -0
  13. package/dist/custom/ArtifactPermissionDelegate.js.map +1 -0
  14. package/dist/custom/ArtifactPreviewSnapshot.d.ts +199 -0
  15. package/dist/custom/ArtifactPreviewSnapshot.d.ts.map +1 -0
  16. package/dist/custom/ArtifactPreviewSnapshot.js +772 -0
  17. package/dist/custom/ArtifactPreviewSnapshot.js.map +1 -0
  18. package/dist/custom/ArtifactSynthesisEngine.d.ts +151 -0
  19. package/dist/custom/ArtifactSynthesisEngine.d.ts.map +1 -0
  20. package/dist/custom/ArtifactSynthesisEngine.js +1124 -0
  21. package/dist/custom/ArtifactSynthesisEngine.js.map +1 -0
  22. package/dist/custom/ConversationWriteAccess.d.ts +27 -0
  23. package/dist/custom/ConversationWriteAccess.d.ts.map +1 -1
  24. package/dist/custom/ConversationWriteAccess.js +53 -0
  25. package/dist/custom/ConversationWriteAccess.js.map +1 -1
  26. package/dist/custom/DocumentLiveBlockEngine.d.ts +612 -0
  27. package/dist/custom/DocumentLiveBlockEngine.d.ts.map +1 -0
  28. package/dist/custom/DocumentLiveBlockEngine.js +2352 -0
  29. package/dist/custom/DocumentLiveBlockEngine.js.map +1 -0
  30. package/dist/custom/MJQueryEntityExtended.d.ts.map +1 -1
  31. package/dist/custom/MJQueryEntityExtended.js +27 -11
  32. package/dist/custom/MJQueryEntityExtended.js.map +1 -1
  33. package/dist/custom/MJUserViewEntityExtended.d.ts +4 -7
  34. package/dist/custom/MJUserViewEntityExtended.d.ts.map +1 -1
  35. package/dist/custom/MJUserViewEntityExtended.js +15 -97
  36. package/dist/custom/MJUserViewEntityExtended.js.map +1 -1
  37. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.d.ts.map +1 -1
  38. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.js +31 -7
  39. package/dist/custom/PermissionProviders/ArtifactPermissionProvider.js.map +1 -1
  40. package/dist/custom/PermissionProviders/CollectionPermissionProvider.d.ts +3 -4
  41. package/dist/custom/PermissionProviders/CollectionPermissionProvider.d.ts.map +1 -1
  42. package/dist/custom/PermissionProviders/CollectionPermissionProvider.js +334 -47
  43. package/dist/custom/PermissionProviders/CollectionPermissionProvider.js.map +1 -1
  44. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts +19 -3
  45. package/dist/custom/Permissions/BaseShareEntityExtended.d.ts.map +1 -1
  46. package/dist/custom/Permissions/BaseShareEntityExtended.js +139 -13
  47. package/dist/custom/Permissions/BaseShareEntityExtended.js.map +1 -1
  48. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts +8 -6
  49. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.d.ts.map +1 -1
  50. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js +93 -41
  51. package/dist/custom/Permissions/MJArtifactPermissionEntityExtended.js.map +1 -1
  52. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts +12 -5
  53. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.d.ts.map +1 -1
  54. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js +240 -37
  55. package/dist/custom/Permissions/MJCollectionPermissionEntityExtended.js.map +1 -1
  56. package/dist/custom/SlideDeckEngine.d.ts +427 -0
  57. package/dist/custom/SlideDeckEngine.d.ts.map +1 -0
  58. package/dist/custom/SlideDeckEngine.js +1669 -0
  59. package/dist/custom/SlideDeckEngine.js.map +1 -0
  60. package/dist/custom/SlideDeckPptxEngine.d.ts +25 -0
  61. package/dist/custom/SlideDeckPptxEngine.d.ts.map +1 -0
  62. package/dist/custom/SlideDeckPptxEngine.js +1237 -0
  63. package/dist/custom/SlideDeckPptxEngine.js.map +1 -0
  64. package/dist/custom/SpreadsheetEngine.d.ts +1370 -0
  65. package/dist/custom/SpreadsheetEngine.d.ts.map +1 -0
  66. package/dist/custom/SpreadsheetEngine.js +17580 -0
  67. package/dist/custom/SpreadsheetEngine.js.map +1 -0
  68. package/dist/custom/approvals.d.ts +7 -1
  69. package/dist/custom/approvals.d.ts.map +1 -1
  70. package/dist/custom/approvals.js +8 -1
  71. package/dist/custom/approvals.js.map +1 -1
  72. package/dist/custom/operations/ArtifactComplianceAuditOperation.d.ts +7 -0
  73. package/dist/custom/operations/ArtifactComplianceAuditOperation.d.ts.map +1 -0
  74. package/dist/custom/operations/ArtifactComplianceAuditOperation.js +7 -0
  75. package/dist/custom/operations/ArtifactComplianceAuditOperation.js.map +1 -0
  76. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.d.ts +7 -0
  77. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.d.ts.map +1 -0
  78. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.js +7 -0
  79. package/dist/custom/operations/ArtifactEvaluateAiFormulaOperation.js.map +1 -0
  80. package/dist/custom/operations/ArtifactGuestShareOperations.d.ts +60 -0
  81. package/dist/custom/operations/ArtifactGuestShareOperations.d.ts.map +1 -0
  82. package/dist/custom/operations/ArtifactGuestShareOperations.js +6 -0
  83. package/dist/custom/operations/ArtifactGuestShareOperations.js.map +1 -0
  84. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.d.ts +7 -0
  85. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.d.ts.map +1 -0
  86. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.js +7 -0
  87. package/dist/custom/operations/SynthesizeArtifactFromSourcesOperation.js.map +1 -0
  88. package/dist/custom/typedQuery.d.ts +162 -0
  89. package/dist/custom/typedQuery.d.ts.map +1 -0
  90. package/dist/custom/typedQuery.js +296 -0
  91. package/dist/custom/typedQuery.js.map +1 -0
  92. package/dist/engines/CanonGraphEngine.d.ts +122 -0
  93. package/dist/engines/CanonGraphEngine.d.ts.map +1 -0
  94. package/dist/engines/CanonGraphEngine.js +500 -0
  95. package/dist/engines/CanonGraphEngine.js.map +1 -0
  96. package/dist/engines/EncryptionEngineBase.js +2 -2
  97. package/dist/engines/EncryptionEngineBase.js.map +1 -1
  98. package/dist/engines/QueryEngine.js +2 -2
  99. package/dist/engines/QueryEngine.js.map +1 -1
  100. package/dist/engines/SearchEngineBase.d.ts +17 -3
  101. package/dist/engines/SearchEngineBase.d.ts.map +1 -1
  102. package/dist/engines/SearchEngineBase.js +100 -28
  103. package/dist/engines/SearchEngineBase.js.map +1 -1
  104. package/dist/engines/UserInfoEngine.d.ts +8 -0
  105. package/dist/engines/UserInfoEngine.d.ts.map +1 -1
  106. package/dist/engines/UserInfoEngine.js +62 -10
  107. package/dist/engines/UserInfoEngine.js.map +1 -1
  108. package/dist/engines/conversations.d.ts +213 -12
  109. package/dist/engines/conversations.d.ts.map +1 -1
  110. package/dist/engines/conversations.js +578 -30
  111. package/dist/engines/conversations.js.map +1 -1
  112. package/dist/generated/entities/__mj.d.ts +4265 -25257
  113. package/dist/generated/entities/__mj.d.ts.map +1 -1
  114. package/dist/generated/entities/__mj.js +3793 -40542
  115. package/dist/generated/entities/__mj.js.map +1 -1
  116. package/dist/generated/queries/__mj.d.ts +269 -0
  117. package/dist/generated/queries/__mj.d.ts.map +1 -0
  118. package/dist/generated/queries/__mj.js +100 -0
  119. package/dist/generated/queries/__mj.js.map +1 -0
  120. package/dist/generated/queries/index.d.ts +2 -0
  121. package/dist/generated/queries/index.d.ts.map +1 -0
  122. package/dist/generated/queries/index.js +4 -0
  123. package/dist/generated/queries/index.js.map +1 -0
  124. package/dist/generated/remote_operations.d.ts +275 -22
  125. package/dist/generated/remote_operations.d.ts.map +1 -1
  126. package/dist/generated/remote_operations.js +98 -3
  127. package/dist/generated/remote_operations.js.map +1 -1
  128. package/dist/generated/schemas/__mj.d.ts +25489 -0
  129. package/dist/generated/schemas/__mj.d.ts.map +1 -0
  130. package/dist/generated/schemas/__mj.js +41768 -0
  131. package/dist/generated/schemas/__mj.js.map +1 -0
  132. package/dist/generated/schemas.d.ts +2 -0
  133. package/dist/generated/schemas.d.ts.map +1 -0
  134. package/dist/generated/schemas.js +2 -0
  135. package/dist/generated/schemas.js.map +1 -0
  136. package/dist/graph/BaseGraphEdgeProvider.d.ts +158 -0
  137. package/dist/graph/BaseGraphEdgeProvider.d.ts.map +1 -0
  138. package/dist/graph/BaseGraphEdgeProvider.js +70 -0
  139. package/dist/graph/BaseGraphEdgeProvider.js.map +1 -0
  140. package/dist/graph/GraphEngine.d.ts +274 -0
  141. package/dist/graph/GraphEngine.d.ts.map +1 -0
  142. package/dist/graph/GraphEngine.js +1156 -0
  143. package/dist/graph/GraphEngine.js.map +1 -0
  144. package/dist/graph/GraphExpansion.d.ts +142 -0
  145. package/dist/graph/GraphExpansion.d.ts.map +1 -0
  146. package/dist/graph/GraphExpansion.js +87 -0
  147. package/dist/graph/GraphExpansion.js.map +1 -0
  148. package/dist/graph/index.d.ts +15 -0
  149. package/dist/graph/index.d.ts.map +1 -0
  150. package/dist/graph/index.js +30 -0
  151. package/dist/graph/index.js.map +1 -0
  152. package/dist/graph/providers/AlternateBaseViewEdgeProvider.d.ts +16 -0
  153. package/dist/graph/providers/AlternateBaseViewEdgeProvider.d.ts.map +1 -0
  154. package/dist/graph/providers/AlternateBaseViewEdgeProvider.js +115 -0
  155. package/dist/graph/providers/AlternateBaseViewEdgeProvider.js.map +1 -0
  156. package/dist/graph/providers/EntityMetadataEdgeProvider.d.ts +17 -0
  157. package/dist/graph/providers/EntityMetadataEdgeProvider.d.ts.map +1 -0
  158. package/dist/graph/providers/EntityMetadataEdgeProvider.js +145 -0
  159. package/dist/graph/providers/EntityMetadataEdgeProvider.js.map +1 -0
  160. package/dist/graph/providers/ForeignKeyEdgeProvider.d.ts +25 -0
  161. package/dist/graph/providers/ForeignKeyEdgeProvider.d.ts.map +1 -0
  162. package/dist/graph/providers/ForeignKeyEdgeProvider.js +131 -0
  163. package/dist/graph/providers/ForeignKeyEdgeProvider.js.map +1 -0
  164. package/dist/graph/providers/JoinEntityEdgeProvider.d.ts +37 -0
  165. package/dist/graph/providers/JoinEntityEdgeProvider.d.ts.map +1 -0
  166. package/dist/graph/providers/JoinEntityEdgeProvider.js +170 -0
  167. package/dist/graph/providers/JoinEntityEdgeProvider.js.map +1 -0
  168. package/dist/graph/providers/QueryEdgeProvider.d.ts +33 -0
  169. package/dist/graph/providers/QueryEdgeProvider.d.ts.map +1 -0
  170. package/dist/graph/providers/QueryEdgeProvider.js +120 -0
  171. package/dist/graph/providers/QueryEdgeProvider.js.map +1 -0
  172. package/dist/graph/providers/QueryMetadataEdgeProvider.d.ts +18 -0
  173. package/dist/graph/providers/QueryMetadataEdgeProvider.d.ts.map +1 -0
  174. package/dist/graph/providers/QueryMetadataEdgeProvider.js +163 -0
  175. package/dist/graph/providers/QueryMetadataEdgeProvider.js.map +1 -0
  176. package/dist/graph/providers/RecordLinkEdgeProvider.d.ts +20 -0
  177. package/dist/graph/providers/RecordLinkEdgeProvider.d.ts.map +1 -0
  178. package/dist/graph/providers/RecordLinkEdgeProvider.js +172 -0
  179. package/dist/graph/providers/RecordLinkEdgeProvider.js.map +1 -0
  180. package/dist/index.d.ts +15 -0
  181. package/dist/index.d.ts.map +1 -1
  182. package/dist/index.js +23 -0
  183. package/dist/index.js.map +1 -1
  184. package/dist/schemas.d.ts +6 -0
  185. package/dist/schemas.d.ts.map +1 -0
  186. package/dist/schemas.js +6 -0
  187. package/dist/schemas.js.map +1 -0
  188. package/package.json +17 -6
@@ -0,0 +1,1124 @@
1
+ import { LogError } from '@memberjunction/core';
2
+ import { BaseSingleton, UUIDsEqual } from '@memberjunction/global';
3
+ import { DocumentLiveBlockEngine, } from './DocumentLiveBlockEngine.js';
4
+ import { SlideDeckEngine, } from './SlideDeckEngine.js';
5
+ import { SpreadsheetEngine } from './SpreadsheetEngine.js';
6
+ /**
7
+ * Canonical `MJ: Artifact Types.Name` values corresponding to {@link ArtifactSynthesisTargetKind}.
8
+ */
9
+ export const SYNTHESIS_TARGET_TYPE_NAME_MAP = {
10
+ presentation: 'Presentation',
11
+ document: 'Markdown Document',
12
+ spreadsheet: 'Excel Spreadsheet',
13
+ };
14
+ const VALID_SLIDE_LAYOUTS = new Set([
15
+ 'Title',
16
+ 'SectionHeader',
17
+ 'TitleAndBody',
18
+ 'TwoColumn',
19
+ 'Comparison',
20
+ 'LiveDataSlide',
21
+ 'ChartAndText',
22
+ 'Quote',
23
+ 'BigNumber',
24
+ 'FullBleedImage',
25
+ 'Blank',
26
+ ]);
27
+ const VALID_REGION_KINDS = new Set([
28
+ 'rich-text',
29
+ 'mj-block',
30
+ 'callout',
31
+ 'table',
32
+ 'image',
33
+ 'big-number',
34
+ 'quote',
35
+ ]);
36
+ /**
37
+ * Headless engine responsible for extracting structured digests across heterogeneous MJ artifacts
38
+ * (Markdown Documents, Spreadsheets, Presentations, Whiteboards, JSON/CSV/SQL data artifacts),
39
+ * constructing token-bounded synthesis prompts with live chart/range link hints, and normalizing +
40
+ * permission-filtering AI synthesis outputs into valid serialized artifact payloads.
41
+ */
42
+ export class ArtifactSynthesisEngine extends BaseSingleton {
43
+ constructor() {
44
+ super();
45
+ this._blockSequence = 0;
46
+ }
47
+ static get Instance() {
48
+ return super.getInstance();
49
+ }
50
+ /**
51
+ * Resolves any common target alias (`'presentation' | 'slides' | 'deck'`, `'document' | 'doc' | 'markdown'`,
52
+ * `'spreadsheet' | 'sheet' | 'excel'`) into a canonical {@link ArtifactSynthesisTargetKind}.
53
+ */
54
+ NormalizeTargetKind(rawKind) {
55
+ const norm = (rawKind ?? '').trim().toLowerCase();
56
+ if (norm === 'document' || norm === 'doc' || norm === 'markdown' || norm === 'markdown document') {
57
+ return 'document';
58
+ }
59
+ if (norm === 'spreadsheet' ||
60
+ norm === 'sheet' ||
61
+ norm === 'sheets' ||
62
+ norm === 'excel' ||
63
+ norm === 'excel spreadsheet') {
64
+ return 'spreadsheet';
65
+ }
66
+ return 'presentation';
67
+ }
68
+ /**
69
+ * Extracts a compact, structured digest from any supported source artifact without leaking
70
+ * raw internal fence JSON (`mj-block`) or exceeding `maxChars`.
71
+ * Always passes `{ SkipEvaluate: true }` so untrusted formulas are never evaluated on the main thread (`R8-3`).
72
+ */
73
+ ExtractSourceDigest(source, maxChars = 6000) {
74
+ return this.extractSourceDigestInternal(source, maxChars);
75
+ }
76
+ /**
77
+ * Isolated async counterpart to {@link ExtractSourceDigest}: for spreadsheets, parses and evaluates
78
+ * via {@link SpreadsheetEngine.ParseWorkbookIsolated} (using server `worker_threads` isolation when
79
+ * registered) so computed formula values appear safely in the digest (`R8-3`).
80
+ */
81
+ async ExtractSourceDigestIsolated(source, maxChars = 6000) {
82
+ const normType = (source.ArtifactType ?? '').trim().toLowerCase();
83
+ const raw = typeof source.Content === 'string' ? source.Content : '';
84
+ const isBinaryPlaceholder = source.ContentMode === 'File' || (!raw.trim() && Boolean(source.Description));
85
+ let preparsedWorkbook;
86
+ if (!isBinaryPlaceholder && (normType.includes('spreadsheet') || normType === 'excel')) {
87
+ try {
88
+ preparsedWorkbook = await SpreadsheetEngine.Instance.ParseWorkbookIsolated(raw, source.Configuration);
89
+ }
90
+ catch (err) {
91
+ const msg = err instanceof Error ? err.message : String(err);
92
+ LogError(`ArtifactSynthesisEngine.ExtractSourceDigestIsolated failed for artifact '${source.ArtifactID}': ${msg}`);
93
+ throw err;
94
+ }
95
+ }
96
+ return this.extractSourceDigestInternal(source, maxChars, preparsedWorkbook);
97
+ }
98
+ extractSourceDigestInternal(source, maxChars = 6000, preparsedWorkbook) {
99
+ const normType = (source.ArtifactType ?? '').trim().toLowerCase();
100
+ const raw = typeof source.Content === 'string' ? source.Content : '';
101
+ const sections = [];
102
+ const embeddedCharts = [];
103
+ const summaryParts = [];
104
+ if (source.ContentMode === 'File' || (!raw.trim() && source.Description)) {
105
+ summaryParts.push(`Binary/File Artifact (${source.MimeType || source.ArtifactType})${source.Description ? `: ${source.Description}` : ''}`);
106
+ }
107
+ else if (normType.includes('spreadsheet') || normType === 'excel') {
108
+ this.digestSpreadsheet(source, raw, summaryParts, sections, embeddedCharts, preparsedWorkbook);
109
+ }
110
+ else if (normType.includes('presentation') || normType.includes('slide')) {
111
+ this.digestPresentation(source, raw, summaryParts, sections);
112
+ }
113
+ else if (normType.includes('whiteboard')) {
114
+ this.digestWhiteboard(raw, summaryParts, sections);
115
+ }
116
+ else if (normType.includes('markdown') || normType === 'text' || normType === 'document') {
117
+ this.digestMarkdown(raw, summaryParts, sections);
118
+ }
119
+ else {
120
+ this.digestGenericStructured(source, raw, summaryParts, sections);
121
+ }
122
+ const combined = summaryParts.join('\n').trim() || source.Description?.trim() || '(Empty artifact)';
123
+ const bounded = combined.length > maxChars
124
+ ? `${combined.slice(0, Math.max(0, maxChars - 18))}\n...[truncated]`
125
+ : combined;
126
+ return {
127
+ ArtifactID: source.ArtifactID,
128
+ Name: source.Name,
129
+ ArtifactType: source.ArtifactType,
130
+ VersionNumber: source.VersionNumber,
131
+ SummaryText: bounded,
132
+ Sections: sections.slice(0, 25),
133
+ EmbeddedCharts: embeddedCharts,
134
+ CharCount: bounded.length,
135
+ };
136
+ }
137
+ /**
138
+ * Constructs the system & user prompt pair for multi-artifact synthesis.
139
+ */
140
+ BuildSynthesisPrompts(options) {
141
+ const linkCharts = options.LinkChartsAndRanges !== false;
142
+ const chartCatalog = [];
143
+ for (const d of options.Digests) {
144
+ for (const c of d.EmbeddedCharts) {
145
+ chartCatalog.push(c);
146
+ }
147
+ }
148
+ const schemaGuidance = this.buildSchemaGuidanceForTarget(options.TargetKind, linkCharts ? chartCatalog : []);
149
+ const systemPrompt = [
150
+ 'You are MemberJunction Multi-Artifact Synthesis AI.',
151
+ 'Your task is to combine facts, metrics, and insights across multiple governed source artifacts into one cohesive, executive-ready target artifact.',
152
+ 'Respond ONLY with a single valid JSON object matching the target schema below (no prose preamble or trailing explanation outside JSON).',
153
+ 'Never fabricate metrics or ArtifactIDs. Cite only verified values from the provided source digests.',
154
+ schemaGuidance,
155
+ ].join('\n\n');
156
+ const sourceBlocks = options.Digests.map((d, index) => {
157
+ const verLabel = d.VersionNumber != null ? ` v${d.VersionNumber}` : '';
158
+ const chartLines = d.EmbeddedCharts.length > 0
159
+ ? `\nAvailable Live Charts:\n${d.EmbeddedCharts.map((c) => ` - ChartID="${c.ChartID}" Sheet="${c.WorksheetName}" Range="${c.RangeAddress}" Title="${c.ChartTitle}" (ArtifactID=${c.ArtifactID})`).join('\n')}`
160
+ : '';
161
+ return [
162
+ `### Source ${index + 1}: "${d.Name}" (${d.ArtifactType}${verLabel}) [ArtifactID: ${d.ArtifactID}]`,
163
+ d.SummaryText,
164
+ chartLines,
165
+ ]
166
+ .filter(Boolean)
167
+ .join('\n');
168
+ }).join('\n\n---\n\n');
169
+ const userPrompt = [
170
+ `Target Format: ${SYNTHESIS_TARGET_TYPE_NAME_MAP[options.TargetKind]}`,
171
+ options.Title ? `Requested Title: ${options.Title}` : '',
172
+ `Synthesis Goal / Instructions:\n${options.Goal.trim() || 'Synthesize key insights, metrics, and recommendations across the source artifacts.'}`,
173
+ linkCharts && chartCatalog.length > 0
174
+ ? 'Preserve live data links: embed verified source Spreadsheet ChartID/Range references using the ArtifactID values provided in the digests.'
175
+ : '',
176
+ `Source Artifacts (${options.Digests.length}):\n\n${sourceBlocks}`,
177
+ ]
178
+ .filter(Boolean)
179
+ .join('\n\n');
180
+ return { SystemPrompt: systemPrompt, UserPrompt: userPrompt };
181
+ }
182
+ /**
183
+ * Parses, normalizes, and permission-filters raw model output into a clean, ready-to-save
184
+ * artifact payload (`SlideDeckSpec` JSON, Markdown, or `WorkbookSpec` JSON).
185
+ */
186
+ NormalizeSynthesizedOutput(options) {
187
+ const warnings = [];
188
+ const fallbackTitle = (options.FallbackTitle ?? '').trim() || 'Synthesized Artifact';
189
+ const allowedSet = options.AllowedSourceArtifactIds;
190
+ const stripped = this.stripJsonFence(options.RawOutput);
191
+ const targetTypeName = SYNTHESIS_TARGET_TYPE_NAME_MAP[options.TargetKind];
192
+ let parsedObj = null;
193
+ if (stripped.startsWith('{') || stripped.startsWith('[')) {
194
+ try {
195
+ const candidate = JSON.parse(stripped);
196
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
197
+ parsedObj = candidate;
198
+ }
199
+ else if (Array.isArray(candidate) && options.TargetKind === 'presentation') {
200
+ parsedObj = { slides: candidate };
201
+ }
202
+ }
203
+ catch {
204
+ parsedObj = null;
205
+ }
206
+ }
207
+ if (options.TargetKind === 'presentation') {
208
+ return this.normalizePresentationResult(parsedObj, stripped, fallbackTitle, allowedSet, warnings);
209
+ }
210
+ if (options.TargetKind === 'spreadsheet') {
211
+ return this.normalizeSpreadsheetResult(parsedObj, fallbackTitle, targetTypeName, warnings).artifact;
212
+ }
213
+ return this.normalizeDocumentResult(parsedObj, stripped, fallbackTitle, targetTypeName, allowedSet, warnings);
214
+ }
215
+ /**
216
+ * Worker-isolated async counterpart to {@link NormalizeSynthesizedOutput} (`R9-2`):
217
+ * builds synthesized spreadsheet workbooks with `recalculate = false` and evaluates
218
+ * via {@link SpreadsheetEngine.EvaluateWorkbookIsolated}.
219
+ */
220
+ async NormalizeSynthesizedOutputIsolated(options) {
221
+ const warnings = [];
222
+ const fallbackTitle = (options.FallbackTitle ?? '').trim() || 'Synthesized Artifact';
223
+ const allowedSet = options.AllowedSourceArtifactIds;
224
+ const stripped = this.stripJsonFence(options.RawOutput);
225
+ const targetTypeName = SYNTHESIS_TARGET_TYPE_NAME_MAP[options.TargetKind];
226
+ let parsedObj = null;
227
+ if (stripped.startsWith('{') || stripped.startsWith('[')) {
228
+ try {
229
+ const candidate = JSON.parse(stripped);
230
+ if (candidate && typeof candidate === 'object' && !Array.isArray(candidate)) {
231
+ parsedObj = candidate;
232
+ }
233
+ else if (Array.isArray(candidate) && options.TargetKind === 'presentation') {
234
+ parsedObj = { slides: candidate };
235
+ }
236
+ }
237
+ catch {
238
+ parsedObj = null;
239
+ }
240
+ }
241
+ if (options.TargetKind === 'presentation') {
242
+ return this.normalizePresentationResult(parsedObj, stripped, fallbackTitle, allowedSet, warnings);
243
+ }
244
+ if (options.TargetKind === 'spreadsheet') {
245
+ const { artifact, workbook } = this.normalizeSpreadsheetResult(parsedObj, fallbackTitle, targetTypeName, warnings, true);
246
+ if (workbook) {
247
+ await SpreadsheetEngine.Instance.EvaluateWorkbookIsolated(workbook);
248
+ artifact.Content = SpreadsheetEngine.Instance.SerializeWorkbook(workbook);
249
+ }
250
+ return artifact;
251
+ }
252
+ return this.normalizeDocumentResult(parsedObj, stripped, fallbackTitle, targetTypeName, allowedSet, warnings);
253
+ }
254
+ /**
255
+ * Produces a deterministic, clean baseline synthesis directly from digests (used when an AI
256
+ * provider fails structured output or in offline synthesis smoke/unit checks).
257
+ */
258
+ BuildDeterministicFallbackSynthesis(digests, targetKind, title, goal, linkChartsAndRanges = true) {
259
+ const cleanTitle = title.trim() || `Synthesized ${SYNTHESIS_TARGET_TYPE_NAME_MAP[targetKind]}`;
260
+ const allCharts = linkChartsAndRanges ? digests.flatMap((d) => d.EmbeddedCharts) : [];
261
+ if (targetKind === 'presentation') {
262
+ const deck = SlideDeckEngine.Instance.CreateDefaultDeck(cleanTitle);
263
+ const slides = [
264
+ {
265
+ SlideID: 'slide-1',
266
+ SlideNumber: 1,
267
+ Layout: 'Title',
268
+ Title: cleanTitle,
269
+ Subtitle: goal.trim() || `Synthesized from ${digests.length} Library artifacts`,
270
+ Regions: [
271
+ {
272
+ RegionID: 'subtitle',
273
+ Label: 'Overview',
274
+ Kind: 'rich-text',
275
+ MarkdownContent: `Combined insights from ${digests.map((d) => `**${d.Name}**`).join(', ')}.`,
276
+ },
277
+ ],
278
+ SpeakerNotes: `Executive overview covering ${digests.length} source artifacts.`,
279
+ Transition: 'fade',
280
+ },
281
+ ];
282
+ let idx = 2;
283
+ const usedIds = new Set();
284
+ for (const d of digests) {
285
+ const chart = linkChartsAndRanges ? d.EmbeddedCharts[0] : undefined;
286
+ if (chart) {
287
+ const blockSpec = {
288
+ BlockID: this.mintUniqueBlockId('chart-blk', undefined, usedIds),
289
+ Kind: 'Artifact',
290
+ Mode: 'Live',
291
+ EmbedMode: 'Inline',
292
+ ArtifactID: chart.ArtifactID,
293
+ ArtifactType: 'Excel Spreadsheet',
294
+ SheetID: chart.WorksheetName,
295
+ SheetChartID: chart.ChartID,
296
+ SheetRange: chart.RangeAddress,
297
+ Title: chart.ChartTitle,
298
+ };
299
+ slides.push({
300
+ SlideID: `slide-${idx}`,
301
+ SlideNumber: idx,
302
+ Layout: 'ChartAndText',
303
+ Title: `${d.Name} — ${chart.ChartTitle}`,
304
+ Subtitle: `Live chart linked from ${d.ArtifactType}`,
305
+ Regions: [
306
+ {
307
+ RegionID: 'chart',
308
+ Label: 'Linked Chart',
309
+ Kind: 'mj-block',
310
+ MarkdownContent: DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(blockSpec),
311
+ BlockSpec: blockSpec,
312
+ },
313
+ {
314
+ RegionID: 'narrative',
315
+ Label: 'Key Takeaways',
316
+ Kind: 'rich-text',
317
+ MarkdownContent: this.toBulletSummary(d.SummaryText),
318
+ },
319
+ ],
320
+ SpeakerNotes: `Live-linked data from ${d.Name} (${chart.WorksheetName}).`,
321
+ Transition: 'slide',
322
+ });
323
+ }
324
+ else {
325
+ slides.push({
326
+ SlideID: `slide-${idx}`,
327
+ SlideNumber: idx,
328
+ Layout: 'TitleAndBody',
329
+ Title: d.Name,
330
+ Subtitle: d.ArtifactType,
331
+ Regions: [
332
+ {
333
+ RegionID: 'body',
334
+ Label: 'Summary',
335
+ Kind: 'rich-text',
336
+ MarkdownContent: this.toBulletSummary(d.SummaryText),
337
+ },
338
+ ],
339
+ SpeakerNotes: `Summary of ${d.Name}.`,
340
+ Transition: 'slide',
341
+ });
342
+ }
343
+ idx++;
344
+ }
345
+ const finalDeck = {
346
+ ...deck,
347
+ Title: cleanTitle,
348
+ Subtitle: goal.trim() || deck.Subtitle,
349
+ Slides: slides,
350
+ UpdatedAt: new Date().toISOString(),
351
+ };
352
+ return {
353
+ TargetKind: 'presentation',
354
+ ArtifactTypeName: SYNTHESIS_TARGET_TYPE_NAME_MAP.presentation,
355
+ Title: cleanTitle,
356
+ Description: `Synthesized from ${digests.length} artifacts`,
357
+ Content: SlideDeckEngine.Instance.SerializeDeckSpec(finalDeck),
358
+ LinkedChartCount: allCharts.length > 0 ? Math.min(allCharts.length, digests.filter((d) => d.EmbeddedCharts.length > 0).length) : 0,
359
+ Warnings: [],
360
+ };
361
+ }
362
+ if (targetKind === 'spreadsheet') {
363
+ const wb = SpreadsheetEngine.Instance.CreateEmptyWorkbook(cleanTitle);
364
+ const firstSheet = wb.Worksheets[0];
365
+ SpreadsheetEngine.Instance.RenameWorksheet(wb, firstSheet.SheetID, 'Synthesis Index', false);
366
+ SpreadsheetEngine.Instance.SetCell(wb, firstSheet.SheetID, 'A1', { Value: 'Source Artifact', Formula: null }, false);
367
+ SpreadsheetEngine.Instance.SetCell(wb, firstSheet.SheetID, 'B1', { Value: 'Type', Formula: null }, false);
368
+ SpreadsheetEngine.Instance.SetCell(wb, firstSheet.SheetID, 'C1', { Value: 'Summary Highlights', Formula: null }, false);
369
+ digests.forEach((d, rowOffset) => {
370
+ const row = rowOffset + 2;
371
+ SpreadsheetEngine.Instance.SetCell(wb, firstSheet.SheetID, `A${row}`, { Value: d.Name, Formula: null }, false);
372
+ SpreadsheetEngine.Instance.SetCell(wb, firstSheet.SheetID, `B${row}`, { Value: d.ArtifactType, Formula: null }, false);
373
+ SpreadsheetEngine.Instance.SetCell(wb, firstSheet.SheetID, `C${row}`, { Value: d.SummaryText.replace(/\s+/g, ' ').slice(0, 220), Formula: null }, false);
374
+ });
375
+ return {
376
+ TargetKind: 'spreadsheet',
377
+ ArtifactTypeName: SYNTHESIS_TARGET_TYPE_NAME_MAP.spreadsheet,
378
+ Title: cleanTitle,
379
+ Description: `Consolidated index across ${digests.length} artifacts`,
380
+ Content: SpreadsheetEngine.Instance.SerializeWorkbook(wb),
381
+ LinkedChartCount: 0,
382
+ Warnings: [],
383
+ };
384
+ }
385
+ const lines = [
386
+ `# ${cleanTitle}`,
387
+ '',
388
+ goal.trim() ? `> ${goal.trim()}` : `> Synthesized across ${digests.length} Library artifacts.`,
389
+ '',
390
+ ];
391
+ let linkedCount = 0;
392
+ const usedDocIds = new Set();
393
+ for (const d of digests) {
394
+ lines.push(`## ${d.Name} (${d.ArtifactType})`);
395
+ lines.push('');
396
+ lines.push(this.toBulletSummary(d.SummaryText));
397
+ lines.push('');
398
+ if (linkChartsAndRanges && d.EmbeddedCharts.length > 0) {
399
+ const chart = d.EmbeddedCharts[0];
400
+ const spec = {
401
+ BlockID: this.mintUniqueBlockId('chart-blk', undefined, usedDocIds),
402
+ Kind: 'Artifact',
403
+ Mode: 'Live',
404
+ EmbedMode: 'Inline',
405
+ ArtifactID: chart.ArtifactID,
406
+ ArtifactType: 'Excel Spreadsheet',
407
+ SheetID: chart.WorksheetName,
408
+ SheetChartID: chart.ChartID,
409
+ SheetRange: chart.RangeAddress,
410
+ Title: chart.ChartTitle,
411
+ };
412
+ lines.push(DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(spec));
413
+ lines.push('');
414
+ linkedCount++;
415
+ }
416
+ }
417
+ return {
418
+ TargetKind: 'document',
419
+ ArtifactTypeName: SYNTHESIS_TARGET_TYPE_NAME_MAP.document,
420
+ Title: cleanTitle,
421
+ Description: `Synthesized report combining ${digests.length} artifacts`,
422
+ Content: lines.join('\n').trim(),
423
+ LinkedChartCount: linkedCount,
424
+ Warnings: [],
425
+ };
426
+ }
427
+ // -------------------------------------------------------------------------
428
+ // Source Digesters
429
+ // -------------------------------------------------------------------------
430
+ digestSpreadsheet(source, raw, summaryParts, sections, embeddedCharts, preparsedWorkbook) {
431
+ try {
432
+ const wb = preparsedWorkbook ??
433
+ SpreadsheetEngine.Instance.ParseWorkbook(raw, source.Configuration, { SkipEvaluate: true });
434
+ const maxSheets = 12;
435
+ for (const sheet of wb.Worksheets.slice(0, maxSheets)) {
436
+ sections.push(sheet.Name);
437
+ const cellEntries = Object.entries(sheet.Cells ?? {});
438
+ const previewRows = [];
439
+ const rowsMap = new Map();
440
+ const summaryOrFormulaRows = new Set();
441
+ for (const [addr, cell] of cellEntries) {
442
+ const m = /^([A-Za-z]+)(\d+)$/.exec(addr);
443
+ if (!m)
444
+ continue;
445
+ const rowNum = Number(m[2]);
446
+ const colNum = this.colLettersToNumber(m[1]);
447
+ const rawVal = cell.ComputedValue !== undefined ? cell.ComputedValue : cell.RawValue;
448
+ const strVal = rawVal != null ? String(rawVal).trim() : '';
449
+ if (!strVal)
450
+ continue;
451
+ const rowArr = rowsMap.get(rowNum) ?? [];
452
+ rowArr.push({ col: colNum, val: strVal.slice(0, 60) });
453
+ rowsMap.set(rowNum, rowArr);
454
+ if ((typeof cell.Formula === 'string' && cell.Formula.trim().length > 0) ||
455
+ /\b(?:total|subtotal|grand|summary|net|balance)\b/i.test(strVal)) {
456
+ summaryOrFormulaRows.add(rowNum);
457
+ }
458
+ }
459
+ const sortedRows = Array.from(rowsMap.keys()).sort((a, b) => a - b);
460
+ const headRows = sortedRows.slice(0, 12);
461
+ const tailRows = sortedRows.slice(-8);
462
+ const lastHeadRow = headRows.length > 0 ? headRows[headRows.length - 1] : 0;
463
+ const selectedSet = new Set(headRows);
464
+ for (const r of sortedRows) {
465
+ if (summaryOrFormulaRows.has(r) && r > lastHeadRow) {
466
+ selectedSet.add(r);
467
+ }
468
+ }
469
+ for (const r of tailRows) {
470
+ selectedSet.add(r);
471
+ }
472
+ const selectedRows = Array.from(selectedSet).sort((a, b) => a - b);
473
+ let prevSelectedRow = 0;
474
+ for (const r of selectedRows) {
475
+ if (prevSelectedRow > 0 && r > prevSelectedRow + 1 && prevSelectedRow <= lastHeadRow) {
476
+ previewRows.push('... (summary & trailing rows) ...');
477
+ }
478
+ const cells = rowsMap.get(r).sort((a, b) => a.col - b.col);
479
+ previewRows.push(`Row ${r}: ${cells.map((c) => c.val).join(' | ')}`);
480
+ prevSelectedRow = r;
481
+ }
482
+ summaryParts.push(`Worksheet "${sheet.Name}" (${cellEntries.length} non-empty cells):` +
483
+ (previewRows.length > 0 ? `\n${previewRows.join('\n')}` : ' (no sample rows)'));
484
+ for (const chart of sheet.Charts ?? []) {
485
+ embeddedCharts.push({
486
+ ArtifactID: source.ArtifactID,
487
+ ArtifactName: source.Name,
488
+ VersionNumber: source.VersionNumber,
489
+ WorksheetName: sheet.Name,
490
+ ChartID: chart.ChartID,
491
+ ChartTitle: chart.Title || `${sheet.Name} Chart`,
492
+ RangeAddress: chart.SourceRange || 'A1:B10',
493
+ });
494
+ }
495
+ }
496
+ if (wb.Worksheets.length > maxSheets) {
497
+ const omitted = wb.Worksheets.slice(maxSheets).map((w) => w.Name).join(', ');
498
+ summaryParts.push(`Additional worksheets (${wb.Worksheets.length - maxSheets}): ${omitted}`);
499
+ }
500
+ }
501
+ catch {
502
+ this.digestGenericStructured(source, raw, summaryParts, sections);
503
+ }
504
+ }
505
+ digestPresentation(source, raw, summaryParts, sections) {
506
+ try {
507
+ const deck = SlideDeckEngine.Instance.ParseDeckSpec(raw, source.Name, source.ArtifactID);
508
+ summaryParts.push(`Presentation "${deck.Title}" (${deck.Slides.length} slides):`);
509
+ for (const slide of deck.Slides.slice(0, 20)) {
510
+ sections.push(slide.Title);
511
+ const regionSnippets = slide.Regions.map((r) => {
512
+ if (r.Kind === 'big-number' && (r.BigNumberValue || r.BigNumberLabel)) {
513
+ return `${r.BigNumberLabel ?? 'KPI'}: ${r.BigNumberValue ?? ''} ${r.BigNumberDelta ?? ''}`.trim();
514
+ }
515
+ if (r.Kind === 'mj-block') {
516
+ return `[Live Block: ${r.BlockSpec?.Title || r.BlockSpec?.Kind || r.Label}]`;
517
+ }
518
+ return r.MarkdownContent.replace(/\s+/g, ' ').trim().slice(0, 240);
519
+ }).filter(Boolean);
520
+ summaryParts.push(`- Slide ${slide.SlideNumber} (${slide.Layout}): ${slide.Title}` +
521
+ (regionSnippets.length > 0 ? ` — ${regionSnippets.join(' / ')}` : ''));
522
+ }
523
+ }
524
+ catch {
525
+ this.digestGenericStructured(source, raw, summaryParts, sections);
526
+ }
527
+ }
528
+ digestWhiteboard(raw, summaryParts, sections) {
529
+ try {
530
+ const parsed = JSON.parse(raw);
531
+ const texts = [];
532
+ if (parsed && typeof parsed === 'object') {
533
+ const obj = parsed;
534
+ const pages = Array.isArray(obj['pages']) ? obj['pages'] : [];
535
+ for (const p of pages) {
536
+ if (!p || typeof p !== 'object')
537
+ continue;
538
+ const pageObj = p;
539
+ const name = typeof pageObj['name'] === 'string' ? pageObj['name'] : 'Page';
540
+ sections.push(name);
541
+ const items = Array.isArray(pageObj['items']) ? pageObj['items'] : [];
542
+ for (const item of items) {
543
+ if (!item || typeof item !== 'object')
544
+ continue;
545
+ const it = item;
546
+ for (const key of ['Label', 'Text', 'Sub']) {
547
+ const val = it[key];
548
+ if (typeof val === 'string' && val.trim()) {
549
+ texts.push(val.trim());
550
+ }
551
+ }
552
+ }
553
+ }
554
+ const legacyElements = Array.isArray(obj['Elements'])
555
+ ? obj['Elements']
556
+ : Array.isArray(obj['elements'])
557
+ ? obj['elements']
558
+ : [];
559
+ for (const el of legacyElements) {
560
+ if (!el || typeof el !== 'object')
561
+ continue;
562
+ const rec = el;
563
+ for (const key of ['Text', 'text', 'Label', 'label']) {
564
+ const val = rec[key];
565
+ if (typeof val === 'string' && val.trim()) {
566
+ texts.push(val.trim());
567
+ }
568
+ }
569
+ }
570
+ }
571
+ summaryParts.push(texts.length > 0
572
+ ? `Whiteboard elements:\n- ${texts.slice(0, 40).join('\n- ')}`
573
+ : 'Whiteboard diagram (graphical ink/shapes with no text labels).');
574
+ }
575
+ catch {
576
+ summaryParts.push('Whiteboard artifact');
577
+ }
578
+ }
579
+ digestMarkdown(raw, summaryParts, sections) {
580
+ const segments = DocumentLiveBlockEngine.Instance.ParseMarkdownDirectives(raw);
581
+ for (const seg of segments) {
582
+ if (seg.Type === 'mj-block' && seg.BlockSpec) {
583
+ summaryParts.push(`[Embedded Block (${seg.BlockSpec.Kind}): ${seg.BlockSpec.Title || seg.BlockSpec.EntityName || seg.BlockSpec.QueryName || seg.BlockSpec.BlockID}]`);
584
+ continue;
585
+ }
586
+ const lines = seg.RawText.split('\n');
587
+ for (const line of lines) {
588
+ const trimmedLine = line.trim();
589
+ if (trimmedLine.startsWith('#')) {
590
+ let hashes = 0;
591
+ while (hashes < trimmedLine.length && hashes < 4 && trimmedLine[hashes] === '#') {
592
+ hashes++;
593
+ }
594
+ if (hashes >= 1 &&
595
+ hashes <= 3 &&
596
+ hashes < trimmedLine.length &&
597
+ /\s/.test(trimmedLine[hashes])) {
598
+ const headingText = trimmedLine.slice(hashes + 1).trim();
599
+ if (headingText) {
600
+ sections.push(headingText);
601
+ }
602
+ }
603
+ }
604
+ }
605
+ const cleaned = seg.RawText.trim();
606
+ if (cleaned) {
607
+ summaryParts.push(cleaned);
608
+ }
609
+ }
610
+ }
611
+ digestGenericStructured(source, raw, summaryParts, sections) {
612
+ const trimmed = raw.trim();
613
+ if (!trimmed) {
614
+ if (source.Description) {
615
+ summaryParts.push(source.Description);
616
+ }
617
+ return;
618
+ }
619
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
620
+ try {
621
+ const parsed = JSON.parse(trimmed);
622
+ if (Array.isArray(parsed)) {
623
+ const keys = parsed[0] && typeof parsed[0] === 'object'
624
+ ? Object.keys(parsed[0]).slice(0, 12)
625
+ : [];
626
+ if (keys.length > 0)
627
+ sections.push(...keys);
628
+ summaryParts.push(`Structured dataset (${parsed.length} rows, columns: ${keys.join(', ') || 'values'}). Sample rows:\n${JSON.stringify(parsed.slice(0, 8), null, 2)}`);
629
+ return;
630
+ }
631
+ }
632
+ catch {
633
+ // fall back to trimmed plain text
634
+ }
635
+ }
636
+ summaryParts.push(trimmed);
637
+ }
638
+ // -------------------------------------------------------------------------
639
+ // Prompt & Output Helpers
640
+ // -------------------------------------------------------------------------
641
+ buildSchemaGuidanceForTarget(targetKind, charts) {
642
+ if (targetKind === 'presentation') {
643
+ const chartHint = charts.length > 0
644
+ ? `For live charts, emit a slide with Layout="ChartAndText" and include a region {"RegionID":"chart","Label":"Chart","Kind":"mj-block","BlockSpec":{"BlockID":"chart-blk-1","Kind":"Artifact","Mode":"Live","EmbedMode":"Inline","ArtifactID":"<verified source ArtifactID>","ArtifactType":"Excel Spreadsheet","SheetID":"<WorksheetName>","SheetChartID":"<ChartID>","SheetRange":"<RangeAddress>","Title":"<ChartTitle>"}}.`
645
+ : '';
646
+ return [
647
+ 'Return JSON with shape:',
648
+ '{"title": string, "description": string, "slides": [{"Title": string, "Subtitle"?: string, "Layout": "Title"|"SectionHeader"|"TitleAndBody"|"TwoColumn"|"BigNumber"|"ChartAndText"|"Comparison"|"Quote", "Regions": [{"RegionID": string, "Label": string, "Kind": "rich-text"|"big-number"|"callout"|"quote"|"mj-block", "MarkdownContent": string, "BigNumberValue"?: string, "BigNumberLabel"?: string, "BigNumberDelta"?: string, "BlockSpec"?: object}], "SpeakerNotes": string}]}',
649
+ 'Create 4 to 8 crisp, executive slides starting with a Title slide.',
650
+ chartHint,
651
+ ]
652
+ .filter(Boolean)
653
+ .join('\n');
654
+ }
655
+ if (targetKind === 'spreadsheet') {
656
+ return [
657
+ 'Return JSON with shape:',
658
+ '{"title": string, "description": string, "worksheets": [{"Name": string, "Headers": string[], "Rows": Array<Array<string|number|boolean|null>>}]}',
659
+ 'Create 1 to 4 clean worksheets (max 31 chars per Name). Use real Excel formulas (e.g. "=SUM(B2:B10)") in summary rows where numeric totals make sense.',
660
+ ].join('\n');
661
+ }
662
+ const docChartHint = charts.length > 0
663
+ ? 'To embed a live source chart in Markdown, place a directive block:\n:::mj-block\n{"BlockID":"chart-1","Kind":"Artifact","Mode":"Live","EmbedMode":"Inline","ArtifactID":"<verified ArtifactID>","ArtifactType":"Excel Spreadsheet","SheetID":"<WorksheetName>","SheetChartID":"<ChartID>","SheetRange":"<RangeAddress>","Title":"<ChartTitle>"}\n:::'
664
+ : '';
665
+ return [
666
+ 'Return JSON with shape:',
667
+ '{"title": string, "description": string, "markdown": string}',
668
+ 'Use clean Markdown headings (# Title, ## Section), concise bullet insights, and summary tables.',
669
+ docChartHint,
670
+ ]
671
+ .filter(Boolean)
672
+ .join('\n');
673
+ }
674
+ normalizePresentationResult(parsedObj, strippedRaw, fallbackTitle, allowedSourceArtifactIds, warnings) {
675
+ const title = this.readStringField(parsedObj, 'title', 'Title') || fallbackTitle;
676
+ const description = this.readStringField(parsedObj, 'description', 'Description') || 'AI-synthesized presentation';
677
+ const rawSlides = this.readArrayField(parsedObj, 'slides', 'Slides');
678
+ if (rawSlides.length === 0) {
679
+ if (strippedRaw && !strippedRaw.startsWith('{')) {
680
+ const converted = SlideDeckEngine.Instance.ConvertMarkdownToSlideDeck(strippedRaw, title);
681
+ const sanitized = this.filterUnauthorizedDeckBlocks(converted, allowedSourceArtifactIds, warnings);
682
+ return {
683
+ TargetKind: 'presentation',
684
+ ArtifactTypeName: SYNTHESIS_TARGET_TYPE_NAME_MAP.presentation,
685
+ Title: title,
686
+ Description: description,
687
+ Content: SlideDeckEngine.Instance.SerializeDeckSpec(sanitized.Deck),
688
+ LinkedChartCount: sanitized.LinkedChartCount,
689
+ Warnings: warnings,
690
+ };
691
+ }
692
+ const fallback = SlideDeckEngine.Instance.CreateDefaultDeck(title);
693
+ warnings.push('Model output contained no slides array; initialized default deck structure.');
694
+ return {
695
+ TargetKind: 'presentation',
696
+ ArtifactTypeName: SYNTHESIS_TARGET_TYPE_NAME_MAP.presentation,
697
+ Title: title,
698
+ Description: description,
699
+ Content: SlideDeckEngine.Instance.SerializeDeckSpec(fallback),
700
+ LinkedChartCount: 0,
701
+ Warnings: warnings,
702
+ };
703
+ }
704
+ const baseDeck = SlideDeckEngine.Instance.CreateDefaultDeck(title);
705
+ const normalizedSlides = [];
706
+ const usedBlockIds = new Set();
707
+ let linkedCharts = 0;
708
+ rawSlides.forEach((rawSlide, index) => {
709
+ if (!rawSlide || typeof rawSlide !== 'object')
710
+ return;
711
+ const s = rawSlide;
712
+ const rawLayout = typeof s['Layout'] === 'string' ? s['Layout'] : 'TitleAndBody';
713
+ const layout = VALID_SLIDE_LAYOUTS.has(rawLayout) ? rawLayout : 'TitleAndBody';
714
+ const slideTitle = (typeof s['Title'] === 'string' && s['Title'].trim()) || `Slide ${index + 1}`;
715
+ const subtitle = typeof s['Subtitle'] === 'string' ? s['Subtitle'] : undefined;
716
+ const speakerNotes = typeof s['SpeakerNotes'] === 'string' ? s['SpeakerNotes'] : '';
717
+ const rawRegions = Array.isArray(s['Regions']) ? s['Regions'] : [];
718
+ const regions = [];
719
+ rawRegions.forEach((rawReg, regIdx) => {
720
+ if (!rawReg || typeof rawReg !== 'object')
721
+ return;
722
+ const r = rawReg;
723
+ const rawKind = typeof r['Kind'] === 'string' ? r['Kind'] : 'rich-text';
724
+ const kind = VALID_REGION_KINDS.has(rawKind) ? rawKind : 'rich-text';
725
+ let markdownContent = typeof r['MarkdownContent'] === 'string' ? r['MarkdownContent'] : '';
726
+ let blockSpec;
727
+ if (kind === 'mj-block' && r['BlockSpec'] && typeof r['BlockSpec'] === 'object') {
728
+ const candidateSpec = r['BlockSpec'];
729
+ const verified = this.sanitizeArtifactBlockSpec(candidateSpec, allowedSourceArtifactIds, warnings, usedBlockIds);
730
+ if (!verified) {
731
+ return;
732
+ }
733
+ blockSpec = verified;
734
+ markdownContent = DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(verified);
735
+ if (verified.Kind === 'Artifact') {
736
+ linkedCharts++;
737
+ }
738
+ }
739
+ else if (markdownContent) {
740
+ const sanitizedMd = this.stripUnauthorizedMarkdownArtifactBlocks(markdownContent, allowedSourceArtifactIds, warnings, usedBlockIds);
741
+ markdownContent = sanitizedMd.Markdown;
742
+ }
743
+ regions.push({
744
+ RegionID: (typeof r['RegionID'] === 'string' && r['RegionID'].trim()) ||
745
+ `region-${regIdx + 1}`,
746
+ Label: (typeof r['Label'] === 'string' && r['Label'].trim()) ||
747
+ `Section ${regIdx + 1}`,
748
+ Kind: kind,
749
+ MarkdownContent: markdownContent,
750
+ BlockSpec: blockSpec,
751
+ BigNumberValue: typeof r['BigNumberValue'] === 'string' ? r['BigNumberValue'] : undefined,
752
+ BigNumberLabel: typeof r['BigNumberLabel'] === 'string' ? r['BigNumberLabel'] : undefined,
753
+ BigNumberDelta: typeof r['BigNumberDelta'] === 'string' ? r['BigNumberDelta'] : undefined,
754
+ QuoteAttribution: typeof r['QuoteAttribution'] === 'string' ? r['QuoteAttribution'] : undefined,
755
+ });
756
+ });
757
+ normalizedSlides.push({
758
+ SlideID: `slide-${index + 1}`,
759
+ SlideNumber: index + 1,
760
+ Layout: layout,
761
+ Title: slideTitle,
762
+ Subtitle: subtitle,
763
+ Regions: regions.length > 0 ? regions : SlideDeckEngine.Instance.BuildRegionsForLayout(layout),
764
+ SpeakerNotes: speakerNotes,
765
+ Transition: index === 0 ? 'fade' : 'slide',
766
+ });
767
+ });
768
+ const finalDeck = {
769
+ ...baseDeck,
770
+ Title: title,
771
+ Slides: normalizedSlides.length > 0 ? normalizedSlides : baseDeck.Slides,
772
+ UpdatedAt: new Date().toISOString(),
773
+ };
774
+ return {
775
+ TargetKind: 'presentation',
776
+ ArtifactTypeName: SYNTHESIS_TARGET_TYPE_NAME_MAP.presentation,
777
+ Title: title,
778
+ Description: description,
779
+ Content: SlideDeckEngine.Instance.SerializeDeckSpec(finalDeck),
780
+ LinkedChartCount: linkedCharts,
781
+ Warnings: warnings,
782
+ };
783
+ }
784
+ normalizeSpreadsheetResult(parsedObj, fallbackTitle, targetTypeName, warnings, skipEvaluate = false) {
785
+ const title = this.readStringField(parsedObj, 'title', 'Title') || fallbackTitle;
786
+ const description = this.readStringField(parsedObj, 'description', 'Description') || 'AI-synthesized spreadsheet';
787
+ const wb = SpreadsheetEngine.Instance.CreateEmptyWorkbook(title);
788
+ const rawSheets = this.readArrayField(parsedObj, 'worksheets', 'Worksheets');
789
+ if (rawSheets.length === 0) {
790
+ warnings.push('Model output contained no worksheets array; initialized blank workbook.');
791
+ return {
792
+ artifact: {
793
+ TargetKind: 'spreadsheet',
794
+ ArtifactTypeName: targetTypeName,
795
+ Title: title,
796
+ Description: description,
797
+ Content: SpreadsheetEngine.Instance.SerializeWorkbook(wb),
798
+ LinkedChartCount: 0,
799
+ Warnings: warnings,
800
+ },
801
+ };
802
+ }
803
+ rawSheets.forEach((rawSheet, idx) => {
804
+ if (!rawSheet || typeof rawSheet !== 'object')
805
+ return;
806
+ const sh = rawSheet;
807
+ const rawName = typeof sh['Name'] === 'string' ? sh['Name'].trim() : `Sheet ${idx + 1}`;
808
+ const safeName = rawName.slice(0, 31) || `Sheet ${idx + 1}`;
809
+ const targetSheet = idx === 0
810
+ ? wb.Worksheets[0]
811
+ : SpreadsheetEngine.Instance.AddWorksheet(wb, safeName);
812
+ if (idx === 0) {
813
+ SpreadsheetEngine.Instance.RenameWorksheet(wb, targetSheet.SheetID, safeName, !skipEvaluate);
814
+ }
815
+ const headers = Array.isArray(sh['Headers']) ? sh['Headers'] : [];
816
+ headers.forEach((h, cIdx) => {
817
+ const addr = `${this.numberToColLetters(cIdx + 1)}1`;
818
+ SpreadsheetEngine.Instance.SetCell(wb, targetSheet.SheetID, addr, {
819
+ Value: h != null ? String(h) : '',
820
+ Formula: null,
821
+ }, false);
822
+ });
823
+ const rows = Array.isArray(sh['Rows']) ? sh['Rows'] : [];
824
+ const rowStart = headers.length > 0 ? 2 : 1;
825
+ rows.forEach((rawRow, rIdx) => {
826
+ if (!Array.isArray(rawRow))
827
+ return;
828
+ rawRow.forEach((cellVal, cIdx) => {
829
+ const addr = `${this.numberToColLetters(cIdx + 1)}${rowStart + rIdx}`;
830
+ if (typeof cellVal === 'string' && this.containsDisallowedMjFormula(cellVal)) {
831
+ warnings.push(`Blocked disallowed MJ.* live formula in synthesized cell ${safeName}!${addr}.`);
832
+ const strippedBody = cellVal.trim().replace(/^[=+\-@\s]+/, '');
833
+ SpreadsheetEngine.Instance.SetCell(wb, targetSheet.SheetID, addr, {
834
+ Value: `[Blocked formula] ${strippedBody}`,
835
+ Formula: null,
836
+ Literal: true,
837
+ }, false);
838
+ }
839
+ else if (typeof cellVal === 'string' && cellVal.trim().startsWith('=')) {
840
+ SpreadsheetEngine.Instance.SetCell(wb, targetSheet.SheetID, addr, {
841
+ Formula: cellVal.trim(),
842
+ }, false);
843
+ }
844
+ else {
845
+ const normalizedCell = this.toSpreadsheetCellValue(cellVal);
846
+ SpreadsheetEngine.Instance.SetCell(wb, targetSheet.SheetID, addr, {
847
+ Value: normalizedCell,
848
+ Formula: null,
849
+ }, false);
850
+ }
851
+ });
852
+ });
853
+ });
854
+ if (!skipEvaluate) {
855
+ SpreadsheetEngine.Instance.EvaluateWorkbook(wb);
856
+ }
857
+ return {
858
+ workbook: wb,
859
+ artifact: {
860
+ TargetKind: 'spreadsheet',
861
+ ArtifactTypeName: targetTypeName,
862
+ Title: title,
863
+ Description: description,
864
+ Content: skipEvaluate ? '' : SpreadsheetEngine.Instance.SerializeWorkbook(wb),
865
+ LinkedChartCount: 0,
866
+ Warnings: warnings,
867
+ },
868
+ };
869
+ }
870
+ normalizeDocumentResult(parsedObj, strippedRaw, fallbackTitle, targetTypeName, allowedSourceArtifactIds, warnings) {
871
+ const title = this.readStringField(parsedObj, 'title', 'Title') || fallbackTitle;
872
+ const description = this.readStringField(parsedObj, 'description', 'Description') || 'AI-synthesized document';
873
+ let rawMarkdown = this.readRawStringField(parsedObj, 'markdown', 'Markdown', 'content', 'Content');
874
+ if (!rawMarkdown) {
875
+ if (!parsedObj && strippedRaw) {
876
+ rawMarkdown = strippedRaw;
877
+ }
878
+ else {
879
+ rawMarkdown = `# ${title}\n\n`;
880
+ }
881
+ }
882
+ const sanitized = this.stripUnauthorizedMarkdownArtifactBlocks(rawMarkdown, allowedSourceArtifactIds, warnings);
883
+ let finalMarkdown = sanitized.Markdown.trim();
884
+ if (!finalMarkdown.startsWith('#')) {
885
+ finalMarkdown = `# ${title}\n\n${finalMarkdown}`;
886
+ }
887
+ return {
888
+ TargetKind: 'document',
889
+ ArtifactTypeName: targetTypeName,
890
+ Title: title,
891
+ Description: description,
892
+ Content: finalMarkdown,
893
+ LinkedChartCount: sanitized.VerifiedArtifactBlockCount,
894
+ Warnings: warnings,
895
+ };
896
+ }
897
+ mintUniqueBlockId(prefix, candidate, usedBlockIds) {
898
+ const trimmed = (candidate ?? '').trim();
899
+ if (trimmed && (!usedBlockIds || !usedBlockIds.has(trimmed))) {
900
+ usedBlockIds?.add(trimmed);
901
+ return trimmed;
902
+ }
903
+ let generated = `${prefix}-${Date.now()}-${++this._blockSequence}`;
904
+ while (usedBlockIds?.has(generated)) {
905
+ generated = `${prefix}-${Date.now()}-${++this._blockSequence}`;
906
+ }
907
+ usedBlockIds?.add(generated);
908
+ return generated;
909
+ }
910
+ containsDisallowedMjFormula(rawCell) {
911
+ const trimmed = rawCell.trim();
912
+ if (!trimmed || !/^[=+\-@]/.test(trimmed)) {
913
+ return false;
914
+ }
915
+ // Strip quoted string literals (including Excel "" escapes) so unquoted MJ.* calls anywhere
916
+ // in the formula expression (direct, +MJ.*, @MJ.*, _xll.MJ.*, or nested in IF/CONCAT) are detected.
917
+ const unquoted = trimmed.replace(/"(?:[^"]|"")*"/g, '""');
918
+ return /\b(?:_xll\s*\.\s*)?MJ\s*\.\s*(?:VIEW|QUERY|AI|IMPORTRANGE)\b/i.test(unquoted);
919
+ }
920
+ filterUnauthorizedDeckBlocks(deck, allowedSourceArtifactIds, warnings) {
921
+ let linked = 0;
922
+ const usedBlockIds = new Set();
923
+ const slides = deck.Slides.map((slide) => ({
924
+ ...slide,
925
+ Regions: slide.Regions.map((region) => {
926
+ if (region.BlockSpec) {
927
+ const checked = this.sanitizeArtifactBlockSpec(region.BlockSpec, allowedSourceArtifactIds, warnings, usedBlockIds);
928
+ if (!checked) {
929
+ return { ...region, Kind: 'rich-text', BlockSpec: undefined, MarkdownContent: '' };
930
+ }
931
+ if (checked.Kind === 'Artifact')
932
+ linked++;
933
+ const cleanedMarkdown = typeof region.MarkdownContent === 'string' &&
934
+ (region.MarkdownContent.includes(':::mj-block') || region.MarkdownContent.includes('FrozenSnapshot'))
935
+ ? DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(checked)
936
+ : region.MarkdownContent;
937
+ return {
938
+ ...region,
939
+ BlockSpec: checked,
940
+ MarkdownContent: cleanedMarkdown,
941
+ };
942
+ }
943
+ if (typeof region.MarkdownContent === 'string' && region.MarkdownContent.includes(':::mj-block')) {
944
+ const stripped = this.stripUnauthorizedMarkdownArtifactBlocks(region.MarkdownContent, allowedSourceArtifactIds, warnings, usedBlockIds);
945
+ return {
946
+ ...region,
947
+ MarkdownContent: stripped.Markdown,
948
+ };
949
+ }
950
+ return region;
951
+ }),
952
+ }));
953
+ return { Deck: { ...deck, Slides: slides }, LinkedChartCount: linked };
954
+ }
955
+ sanitizeArtifactBlockSpec(raw, allowedSourceArtifactIds, warnings, usedBlockIds) {
956
+ const kind = raw.Kind;
957
+ if (kind !== 'Artifact') {
958
+ warnings.push(`Removed disallowed synthesized block of kind "${String(kind ?? 'unspecified')}": only Kind="Artifact" embeds referencing verified source artifacts are allowed.`);
959
+ return null;
960
+ }
961
+ const targetId = (raw.ArtifactID ?? '').trim();
962
+ const isAllowed = targetId.length > 0 && allowedSourceArtifactIds.some((id) => UUIDsEqual(id, targetId));
963
+ if (!isAllowed) {
964
+ warnings.push(`Removed unverified Artifact reference "${targetId || 'unspecified'}".`);
965
+ return null;
966
+ }
967
+ const cleaned = {
968
+ ...raw,
969
+ BlockID: this.mintUniqueBlockId('synth-blk', raw.BlockID, usedBlockIds),
970
+ Kind: 'Artifact',
971
+ Mode: 'Live',
972
+ };
973
+ delete cleaned.FrozenSnapshot;
974
+ return cleaned;
975
+ }
976
+ normalizeBacktickMjBlockFences(markdown, allowedSourceArtifactIds, warnings, usedBlockIds) {
977
+ const lines = (markdown ?? '').replace(/\r\n/g, '\n').split('\n');
978
+ const out = [];
979
+ let i = 0;
980
+ while (i < lines.length) {
981
+ const openMatch = /^\s*(`{3,}|~{3,})\s*mj-block\b/i.exec(lines[i]);
982
+ if (!openMatch) {
983
+ out.push(lines[i]);
984
+ i++;
985
+ continue;
986
+ }
987
+ const fenceChar = openMatch[1][0];
988
+ const fenceLen = openMatch[1].length;
989
+ const closeRe = new RegExp(`^\\s*${fenceChar}{${fenceLen},}\\s*$`);
990
+ let closeIdx = -1;
991
+ for (let j = i + 1; j < lines.length; j++) {
992
+ if (closeRe.test(lines[j])) {
993
+ closeIdx = j;
994
+ break;
995
+ }
996
+ }
997
+ if (closeIdx < 0) {
998
+ // Unterminated backtick mj-block fence — strip from output
999
+ warnings.push('Removed malformed backtick mj-block fence from synthesized markdown.');
1000
+ break;
1001
+ }
1002
+ const innerJson = lines.slice(i + 1, closeIdx).join('\n').trim();
1003
+ try {
1004
+ const candidate = JSON.parse(innerJson);
1005
+ const verified = this.sanitizeArtifactBlockSpec(candidate, allowedSourceArtifactIds, warnings, usedBlockIds);
1006
+ if (verified) {
1007
+ out.push(DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(verified));
1008
+ }
1009
+ }
1010
+ catch {
1011
+ warnings.push('Removed invalid JSON inside backtick mj-block fence from synthesized markdown.');
1012
+ }
1013
+ i = closeIdx + 1;
1014
+ }
1015
+ return out.join('\n');
1016
+ }
1017
+ stripUnauthorizedMarkdownArtifactBlocks(markdown, allowedSourceArtifactIds, warnings, usedBlockIds = new Set()) {
1018
+ const normalizedMarkdown = this.normalizeBacktickMjBlockFences(markdown, allowedSourceArtifactIds, warnings, usedBlockIds);
1019
+ const segments = DocumentLiveBlockEngine.Instance.ParseMarkdownDirectives(normalizedMarkdown);
1020
+ let verifiedCount = 0;
1021
+ const rebuilt = [];
1022
+ for (const seg of segments) {
1023
+ if (seg.Type !== 'mj-block' || !seg.BlockSpec) {
1024
+ rebuilt.push(seg.RawText);
1025
+ continue;
1026
+ }
1027
+ const verified = this.sanitizeArtifactBlockSpec(seg.BlockSpec, allowedSourceArtifactIds, warnings, usedBlockIds);
1028
+ if (!verified) {
1029
+ continue;
1030
+ }
1031
+ if (verified.Kind === 'Artifact') {
1032
+ verifiedCount++;
1033
+ }
1034
+ rebuilt.push(DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(verified));
1035
+ }
1036
+ return { Markdown: rebuilt.join('\n'), VerifiedArtifactBlockCount: verifiedCount };
1037
+ }
1038
+ readStringField(obj, ...args) {
1039
+ if (!obj)
1040
+ return '';
1041
+ for (const key of args) {
1042
+ const val = obj[key];
1043
+ if (typeof val === 'string' && val.trim().length > 0) {
1044
+ return val.trim();
1045
+ }
1046
+ }
1047
+ return '';
1048
+ }
1049
+ readRawStringField(obj, ...keys) {
1050
+ if (!obj)
1051
+ return '';
1052
+ for (const key of keys) {
1053
+ const val = obj[key];
1054
+ if (typeof val === 'string' && val.length > 0) {
1055
+ return val;
1056
+ }
1057
+ }
1058
+ return '';
1059
+ }
1060
+ readArrayField(obj, ...keys) {
1061
+ if (!obj)
1062
+ return [];
1063
+ for (const key of keys) {
1064
+ const val = obj[key];
1065
+ if (Array.isArray(val))
1066
+ return val;
1067
+ }
1068
+ return [];
1069
+ }
1070
+ stripJsonFence(raw) {
1071
+ const trimmed = (raw ?? '').trim();
1072
+ if (!trimmed.startsWith('```') || !trimmed.endsWith('```')) {
1073
+ return trimmed;
1074
+ }
1075
+ const firstNewline = trimmed.indexOf('\n');
1076
+ const lastNewline = trimmed.lastIndexOf('\n');
1077
+ if (firstNewline === -1 || lastNewline <= firstNewline) {
1078
+ return trimmed;
1079
+ }
1080
+ const header = trimmed.slice(3, firstNewline).trim().toLowerCase();
1081
+ const footer = trimmed.slice(lastNewline + 1).trim();
1082
+ if ((header === '' || header === 'json' || header === 'markdown' || header === 'md') && footer === '```') {
1083
+ return trimmed.slice(firstNewline + 1, lastNewline).trim();
1084
+ }
1085
+ return trimmed;
1086
+ }
1087
+ toBulletSummary(summaryText) {
1088
+ const lines = summaryText
1089
+ .split('\n')
1090
+ .map((l) => l.trim())
1091
+ .filter((l) => l.length > 0 && !l.startsWith('...'))
1092
+ .slice(0, 6);
1093
+ if (lines.length === 0)
1094
+ return '- Source highlights pending review.';
1095
+ return lines.map((l) => (l.startsWith('- ') || l.startsWith('* ') ? l : `- ${l}`)).join('\n');
1096
+ }
1097
+ toSpreadsheetCellValue(value) {
1098
+ if (value === null || value === undefined)
1099
+ return null;
1100
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
1101
+ return value;
1102
+ }
1103
+ return String(value);
1104
+ }
1105
+ colLettersToNumber(letters) {
1106
+ let num = 0;
1107
+ const upper = letters.toUpperCase();
1108
+ for (let i = 0; i < upper.length; i++) {
1109
+ num = num * 26 + (upper.charCodeAt(i) - 64);
1110
+ }
1111
+ return num;
1112
+ }
1113
+ numberToColLetters(colNum) {
1114
+ let n = colNum;
1115
+ let out = '';
1116
+ while (n > 0) {
1117
+ const rem = (n - 1) % 26;
1118
+ out = String.fromCharCode(65 + rem) + out;
1119
+ n = Math.floor((n - 1) / 26);
1120
+ }
1121
+ return out || 'A';
1122
+ }
1123
+ }
1124
+ //# sourceMappingURL=ArtifactSynthesisEngine.js.map