-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExportManager.ts
More file actions
1092 lines (991 loc) · 36 KB
/
Copy pathExportManager.ts
File metadata and controls
1092 lines (991 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Export Manager with Circuit Breaker Integration
*
* Unified export system that wraps all HoloScript compilers with circuit breaker protection.
* Provides automatic fallback, monitoring, and graceful degradation for 25+ export targets.
*
* Features:
* - Circuit breaker protection per target
* - Automatic fallback to reference implementations
* - Real-time metrics tracking
* - Event emission for monitoring systems
* - Batch export support
* - AgentIdentity RBAC integration ready
* - Gaussian primitive budget warnings per platform (W.034)
*
* @version 1.1.0
* @package @holoscript/core/compiler
*/
import type { HoloComposition } from '../parser/HoloCompositionTypes';
import {
CircuitBreakerRegistry,
CircuitState,
type ExportTarget,
type CircuitBreakerConfig,
type CircuitMetrics,
} from './CircuitBreaker';
import { ReferenceExporterRegistry, usdStageHasGeometry } from './ReferenceExporters';
// Import all compilers
import { URDFCompiler } from './URDFCompiler';
import { SDFCompiler } from './SDFCompiler';
import { UnityCompiler } from './UnityCompiler';
import { UnrealCompiler } from './UnrealCompiler';
import { GodotCompiler } from './GodotCompiler';
import { Canvas2DGameCompiler } from './Canvas2DGameCompilerTarget';
import { WebGPUCompiler } from './WebGPUCompiler';
import { OpenXRCompiler } from './OpenXRCompiler';
import { VRChatCompiler } from './VRChatCompiler';
import { IOSCompiler } from './IOSCompiler';
import { AndroidCompiler } from './AndroidCompiler';
import { AndroidXRCompiler } from './AndroidXRCompiler';
import { QuestCompiler } from './QuestCompiler';
import { VisionOSCompiler } from './VisionOSCompiler';
import { WASMCompiler } from './WASMCompiler';
import { DTDLCompiler } from './DTDLCompiler';
import { IncrementalCompiler } from './IncrementalCompiler';
import { StateCompiler } from './StateCompiler';
import { TraitCompositionCompiler } from './TraitCompositionCompiler';
import { TSLCompiler } from './TSLCompiler';
import { A2AAgentCardCompiler } from './A2AAgentCardCompiler';
import { NIRCompiler } from './NIRCompiler';
import { OpenXRSpatialEntitiesCompiler } from './OpenXRSpatialEntitiesCompiler';
import { USDPhysicsCompiler } from './USDPhysicsCompiler';
import { USDZExportCompiler } from './USDZExportCompiler';
import { GaussianSplattingCompiler } from './GaussianSplattingCompiler';
import { GaussianTrainCompiler } from './GaussianTrainCompiler';
import { CodeEditorCompiler } from './CodeEditorCompiler';
import { SVGCompiler } from './SVGCompiler';
import { HolobCompiler } from './HolobCompiler';
import { OpenAPICompiler } from './OpenAPICompiler';
import { ONNXCompiler } from './ONNXCompiler';
import { FlutterCompiler } from './FlutterCompiler';
import { STLExportCompiler } from './STLExportCompiler';
import { LensStudioCompiler } from './LensStudioCompiler';
import { ColyseusCompiler } from './ColyseusCompiler';
import { AIGlassesCompiler } from './AIGlassesCompiler';
import { SCMCompiler } from './SCMCompiler';
import { NFTMarketplaceCompiler } from './NFTMarketplaceCompiler';
import { EdgeCompiler } from './EdgeCompiler';
import { BotSwarmCompiler } from './BotSwarmCompiler';
import { DungeonInstancePoolCompiler } from './DungeonInstancePoolCompiler';
import { ShardRegistryCompiler } from './ShardRegistryCompiler';
import {
CompilerStateMonitor,
createCompilerStateMonitor,
type MemoryAlert,
type MemoryStats,
type CompilerStateMonitorOptions,
} from './CompilerStateMonitor';
import {
GaussianBudgetAnalyzer,
type GaussianPlatform,
type GaussianBudgetAnalysis,
} from './GaussianBudgetAnalyzer';
import { CompilerDocumentationGenerator } from './CompilerDocumentationGenerator';
import { generateSemanticSceneGraphObject, type JsonLdSceneGraph } from './SemanticSceneGraph';
// =============================================================================
// TYPES
// =============================================================================
export interface ExportOptions {
/** Enable circuit breaker (default: true) */
useCircuitBreaker?: boolean;
/** Use fallback on failure (default: true) */
useFallback?: boolean;
/** Throw errors instead of returning them (default: false) */
throwOnError?: boolean;
/** Custom circuit breaker config */
circuitConfig?: Partial<CircuitBreakerConfig>;
/** Target-specific compiler options */
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Passed to heterogeneous compiler constructors
compilerOptions?: Record<string, any>;
/** Enable memory monitoring (default: true) */
useMemoryMonitoring?: boolean;
/** Custom memory monitor config */
memoryMonitorConfig?: CompilerStateMonitorOptions;
/**
* Enable Gaussian primitive budget analysis (default: true).
* When enabled, compositions containing gaussian_splat traits are checked
* against platform-specific budgets and warnings are emitted.
*/
enableGaussianBudgetWarnings?: boolean;
/**
* Custom Gaussian budget overrides per platform.
* Allows callers to set stricter or looser budgets than the defaults.
*/
gaussianBudgetOverrides?: Partial<Record<GaussianPlatform, number>>;
/**
* Generate triple-output documentation (llms.txt, .well-known/mcp, markdown).
* When enabled, each compilation will produce additional documentation outputs.
* @default false
*/
generateDocs?: boolean;
/**
* Agent identity token for RBAC integration
*/
agentToken?: string;
/**
* Documentation generator options (service URL, version, etc.)
* Only used if generateDocs is true.
*/
docsOptions?: {
serviceUrl?: string;
serviceVersion?: string;
maxLlmsTxtTokens?: number;
includeTraitDocs?: boolean;
includeExamples?: boolean;
mcpTransportType?: string;
contactRepository?: string;
contactDocumentation?: string;
};
}
export interface ExportResult {
target: ExportTarget;
success: boolean;
output?: string;
error?: Error;
usedFallback: boolean;
/**
* TOP-LEVEL signal that the returned output is a degraded, non-equivalent
* reference substitute produced because the real compiler threw — NOT a true
* compile of the composition. Mirrors `usedFallback` but is the unmissable,
* caller-facing flag: any consumer that treats `success: true` as "this is the
* compiled artifact" MUST check `degraded` first. Additive/optional so existing
* consumers do not break. See `warnings` for the human-readable reason.
*/
degraded?: boolean;
circuitState: CircuitState;
warnings: string[];
metrics: CircuitMetrics;
executionTime: number;
/** Memory stats at completion (if memory monitoring enabled) */
memoryStats?: MemoryStats;
/** Gaussian primitive budget analysis (if budget warnings enabled and composition has gaussian_splat traits) */
gaussianBudgetAnalysis?: GaussianBudgetAnalysis;
/**
* Triple-output documentation bundle (if generateDocs enabled)
* Contains llms.txt, .well-known/mcp server card, and markdown documentation
*/
documentation?: {
llmsTxt: string;
wellKnownMcp: Record<string, unknown>;
markdownDocs: string;
};
}
export interface BatchExportResult {
targets: ExportTarget[];
results: ExportResult[];
successCount: number;
failureCount: number;
fallbackCount: number;
totalTime: number;
aggregatedMetrics: ReturnType<CircuitBreakerRegistry['getAggregatedMetrics']>;
}
/**
* Export event types for monitoring
*/
export type ExportEventType =
| 'export:start'
| 'export:success'
| 'export:failure'
| 'export:fallback'
| 'circuit:open'
| 'circuit:close'
| 'circuit:half-open';
export interface ExportEvent {
type: ExportEventType;
target: ExportTarget;
timestamp: number;
data?: unknown;
}
export type ExportEventListener = (event: ExportEvent) => void;
// =============================================================================
// COMPILER FACTORY
// =============================================================================
/**
* Factory for creating compiler instances
*/
class CompilerFactory {
createCompiler(target: ExportTarget, options: Record<string, any> = {}): any {
switch (target) {
case 'urdf':
return new URDFCompiler(options);
case 'sdf':
return new SDFCompiler(options);
case 'unity':
return new UnityCompiler(options);
case 'unreal':
return new UnrealCompiler(options);
case 'godot':
return new GodotCompiler(options);
case 'webgpu':
return new WebGPUCompiler(options);
case 'openxr':
return new OpenXRCompiler(options);
case 'vrchat':
return new VRChatCompiler(options);
case 'ios':
return new IOSCompiler(options);
case 'android':
return new AndroidCompiler(options);
case 'android-xr':
return new AndroidXRCompiler(options);
case 'quest':
return new QuestCompiler(options);
case 'visionos':
return new VisionOSCompiler(options);
case 'wasm':
return new WASMCompiler(options);
case 'dtdl':
return new DTDLCompiler(options);
case 'incremental':
return new IncrementalCompiler(
options as unknown as ConstructorParameters<typeof IncrementalCompiler>[0]
);
case 'state':
return new StateCompiler();
case 'trait-composition':
return new TraitCompositionCompiler(
options as unknown as ConstructorParameters<typeof TraitCompositionCompiler>[0]
);
case 'tsl':
return new TSLCompiler(options);
case 'a2a-agent-card':
return new A2AAgentCardCompiler(options);
case 'nir':
return new NIRCompiler(options);
case 'openxr-spatial-entities':
return new OpenXRSpatialEntitiesCompiler(options);
case 'usd':
return new USDPhysicsCompiler(options);
case 'usdz':
return new USDZExportCompiler(options);
case '3dgs':
return new GaussianSplattingCompiler(options);
case 'gaussian-train':
return new GaussianTrainCompiler(options);
case 'canvas2d-game':
return new Canvas2DGameCompiler(options);
case 'code-editor':
return new CodeEditorCompiler();
case 'svg':
return new SVGCompiler(options);
case 'holob':
return new HolobCompiler(options);
case 'openapi':
return new OpenAPICompiler(options);
case 'onnx':
return new ONNXCompiler(options);
case 'flutter':
return new FlutterCompiler(options);
case 'stl-export':
return new STLExportCompiler(options);
case 'lens-studio':
return new LensStudioCompiler(options);
case 'colyseus':
return new ColyseusCompiler(options);
case 'ai-glasses':
return new AIGlassesCompiler(options);
case 'scm':
return new SCMCompiler(options);
case 'nft-marketplace':
return new NFTMarketplaceCompiler(options);
case 'edge':
return new EdgeCompiler(options);
case 'bot-swarm':
return new BotSwarmCompiler(options);
case 'dungeon-instance':
return new DungeonInstancePoolCompiler(options);
case 'world-shard':
return new ShardRegistryCompiler(options);
default:
throw new Error(`Unknown export target: ${target}`);
}
}
}
// =============================================================================
// GAUSSIAN BUDGET: TARGET-TO-PLATFORM MAPPING
// =============================================================================
/**
* Maps export targets to the Gaussian platform(s) they should be validated against.
*
* Some targets map to a single platform (e.g., 'visionos' -> ['visionos']),
* while others map to multiple platforms when the output could run on
* different hardware (e.g., 'openxr' runs on both Quest 3 and Desktop VR).
*
* Targets that have no Gaussian rendering concern (e.g., 'urdf', 'sdf', 'dtdl')
* are not listed and will skip budget analysis.
*/
const EXPORT_TARGET_TO_GAUSSIAN_PLATFORMS: Partial<Record<ExportTarget, GaussianPlatform[]>> = {
// VR targets
vrchat: ['quest3', 'desktop_vr'],
openxr: ['quest3', 'desktop_vr'],
'openxr-spatial-entities': ['quest3', 'desktop_vr'],
// Mobile VR
'android-xr': ['quest3'],
// Meta Quest (Horizon OS / Meta Spatial SDK) — distinct runtime from Google android-xr
quest: ['quest3'],
// Desktop/Browser rendering
webgpu: ['webgpu'],
wasm: ['webgpu'],
// Native VR/AR platforms
visionos: ['visionos'],
unity: ['quest3', 'desktop_vr', 'visionos'],
unreal: ['quest3', 'desktop_vr'],
godot: ['quest3', 'desktop_vr'],
// Mobile AR (native)
android: ['mobile_ar'],
ios: ['mobile_ar', 'visionos'],
};
// =============================================================================
// EXPORT MANAGER
// =============================================================================
/**
* Main export manager with circuit breaker integration, memory monitoring,
* and Gaussian primitive budget warnings (W.034).
*/
export class ExportManager {
private circuitRegistry: CircuitBreakerRegistry;
private referenceRegistry: ReferenceExporterRegistry;
private compilerFactory: CompilerFactory;
private eventListeners: Map<ExportEventType, Set<ExportEventListener>> = new Map();
private defaultOptions: Required<ExportOptions>;
private memoryMonitor: CompilerStateMonitor | null = null;
/** V11: Content hash per backend to skip unchanged recompilations */
private lastCompositionHash: Map<string, string> = new Map();
constructor(options: Partial<ExportOptions> = {}) {
this.defaultOptions = {
useCircuitBreaker: options.useCircuitBreaker ?? true,
useFallback: options.useFallback ?? true,
throwOnError: options.throwOnError ?? false,
circuitConfig: options.circuitConfig ?? {},
compilerOptions: options.compilerOptions ?? {},
useMemoryMonitoring: options.useMemoryMonitoring ?? true,
memoryMonitorConfig: options.memoryMonitorConfig ?? {},
enableGaussianBudgetWarnings: options.enableGaussianBudgetWarnings ?? true,
gaussianBudgetOverrides: options.gaussianBudgetOverrides ?? {},
generateDocs: options.generateDocs ?? false,
docsOptions: options.docsOptions ?? {},
agentToken: options.agentToken ?? '',
};
this.circuitRegistry = new CircuitBreakerRegistry({
...this.defaultOptions.circuitConfig,
onStateChange: (oldState, newState, target) => {
this.emitEvent({
type: `circuit:${newState.toLowerCase()}` as ExportEventType,
target,
timestamp: Date.now(),
data: { oldState, newState },
});
},
onError: (error, target) => {
this.emitEvent({
type: 'export:failure',
target,
timestamp: Date.now(),
data: { error: error.message },
});
},
});
this.referenceRegistry = new ReferenceExporterRegistry();
this.compilerFactory = new CompilerFactory();
// Initialize memory monitor if enabled
if (this.defaultOptions.useMemoryMonitoring) {
this.memoryMonitor = createCompilerStateMonitor({
enabled: true,
...this.defaultOptions.memoryMonitorConfig,
onAlert: (alert: MemoryAlert) => {
// Log memory alerts
console.warn(
`[ExportManager] Memory Alert [${alert.level}]: ${alert.message}`,
alert.stats
);
// Call user-provided callback if exists
if (this.defaultOptions.memoryMonitorConfig?.onAlert) {
this.defaultOptions.memoryMonitorConfig.onAlert(alert);
}
},
});
}
}
/**
* Get memory monitor instance
*/
getMemoryMonitor(): CompilerStateMonitor | null {
return this.memoryMonitor;
}
/**
* Get current memory statistics
*/
getMemoryStats(): MemoryStats | null {
return this.memoryMonitor?.captureMemoryStats() ?? null;
}
/**
* Dispose export manager and clean up resources
*/
dispose(): void {
this.memoryMonitor?.dispose();
this.eventListeners.clear();
this.lastCompositionHash.clear();
}
/**
* Export composition to a single target
*/
async export(
target: ExportTarget,
composition: HoloComposition,
options: Partial<ExportOptions> = {}
): Promise<ExportResult> {
const opts = { ...this.defaultOptions, ...options };
const startTime = Date.now();
this.emitEvent({
type: 'export:start',
target,
timestamp: startTime,
data: { composition: composition.name },
});
try {
if (opts.useCircuitBreaker) {
return await this.exportWithCircuitBreaker(target, composition, opts, startTime);
} else {
return await this.exportDirect(target, composition, opts, startTime);
}
} catch (error) {
const result: ExportResult = {
target,
success: false,
error: error as Error,
usedFallback: false,
circuitState: CircuitState.CLOSED,
warnings: [(error as Error).message],
metrics: this.circuitRegistry.getBreaker(target).getMetrics(),
executionTime: Date.now() - startTime,
};
if (opts.throwOnError) {
throw error;
}
return result;
}
}
/**
* V11: Compute a stable content hash for a composition.
* Used to detect when a backend's input hasn't changed.
*/
private computeCompositionHash(composition: HoloComposition): string {
const objects =
composition.objects
?.map((o) => o.name)
.sort()
.join(',') || '';
const traitCount =
composition.objects?.reduce((sum, o) => sum + (o.traits?.length || 0), 0) || 0;
return `${composition.name}:${objects}:${traitCount}:${JSON.stringify(composition).length}`;
}
/**
* Export composition to multiple targets in parallel.
* V11: Skips backends whose last compilation matches the current composition.
*/
async batchExport(
targets: ExportTarget[],
composition: HoloComposition,
options: Partial<ExportOptions> = {}
): Promise<BatchExportResult> {
const startTime = Date.now();
const currentHash = this.computeCompositionHash(composition);
// V11: Skip backends whose last compilation matches current composition
const forceRecompile = options.compilerOptions?.forceRecompile;
const needsCompile = forceRecompile
? targets
: targets.filter((t) => this.lastCompositionHash.get(t) !== currentHash);
// Export only changed targets in parallel
const results = await Promise.all(
needsCompile.map((target) => this.export(target, composition, options))
);
// Update hash cache for successful compilations
for (const result of results) {
if (result.success) {
this.lastCompositionHash.set(result.target, currentHash);
}
}
// Calculate statistics (skipped backends count as successes)
const skippedCount = targets.length - needsCompile.length;
const successCount = results.filter((r) => r.success).length + skippedCount;
const failureCount = results.filter((r) => !r.success).length;
const fallbackCount = results.filter((r) => r.usedFallback).length;
return {
targets,
results,
successCount,
failureCount,
fallbackCount,
totalTime: Date.now() - startTime,
aggregatedMetrics: this.circuitRegistry.getAggregatedMetrics(),
};
}
/**
* Get circuit metrics for a target
*/
getMetrics(target: ExportTarget): CircuitMetrics {
return this.circuitRegistry.getBreaker(target).getMetrics();
}
/**
* Get aggregated metrics for all targets
*/
getAllMetrics(): ReturnType<CircuitBreakerRegistry['getAggregatedMetrics']> {
return this.circuitRegistry.getAggregatedMetrics();
}
/**
* Reset circuit breaker for a target
*/
resetCircuit(target: ExportTarget): void {
this.circuitRegistry.reset(target);
}
/**
* Reset all circuit breakers
*/
resetAllCircuits(): void {
this.circuitRegistry.resetAll();
}
/**
* Subscribe to export events
*/
on(eventType: ExportEventType, listener: ExportEventListener): void {
if (!this.eventListeners.has(eventType)) {
this.eventListeners.set(eventType, new Set());
}
this.eventListeners.get(eventType)!.add(listener);
}
/**
* Unsubscribe from export events
*/
off(eventType: ExportEventType, listener: ExportEventListener): void {
this.eventListeners.get(eventType)?.delete(listener);
}
/**
* Get list of all supported export targets
*/
getSupportedTargets(): ExportTarget[] {
return [
'urdf',
'sdf',
'unity',
'unreal',
'godot',
'vrchat',
'openxr',
'android',
'android-xr',
'ios',
'visionos',
'ar',
'babylon',
'webgpu',
'r3f',
'wasm',
'playcanvas',
'usd',
'usdz',
'dtdl',
'vrr',
'multi-layer',
'incremental',
'state',
'trait-composition',
'tsl',
'a2a-agent-card',
'nir',
'openxr-spatial-entities',
'phone-sleeve-vr',
'3dgs',
];
}
/**
* Check if target has reference exporter
*/
hasReferenceExporter(target: ExportTarget): boolean {
return this.referenceRegistry.hasExporter(target);
}
// ─── PRIVATE METHODS ────────────────────────────────────────────────────────
private async exportWithCircuitBreaker(
target: ExportTarget,
composition: HoloComposition,
options: Required<ExportOptions>,
startTime: number
): Promise<ExportResult> {
const breaker = this.circuitRegistry.getBreaker(target);
// Update memory monitor with current AST
if (this.memoryMonitor) {
this.memoryMonitor.setAST(composition);
this.memoryMonitor.checkMemoryStatus();
}
// Generate SSG once and cache for this compilation pass
const sceneGraph = generateSemanticSceneGraphObject(composition);
// Define main export operation
const exportOperation = async () => {
const compiler = this.compilerFactory.createCompiler(target, options.compilerOptions);
// If compiler is IncrementalCompiler, attach memory monitor
if (compiler instanceof IncrementalCompiler && this.memoryMonitor) {
this.memoryMonitor.setIncrementalCompiler(compiler);
}
// Some compilers expose compileComposition() for HoloComposition input
// instead of compile() which expects HSPlusAST.
const asRecord = compiler as Record<string, unknown>;
if (typeof asRecord['compileComposition'] === 'function') {
const compileFn = asRecord['compileComposition'] as (
comp: unknown,
token?: string,
path?: string,
ssg?: JsonLdSceneGraph
) => unknown;
const output = await compileFn.call(
compiler,
composition,
options.agentToken,
undefined,
sceneGraph
);
return output;
}
const output = await compiler.compile(
composition,
undefined as unknown as string,
undefined,
sceneGraph
);
return output;
};
// Define fallback operation (if enabled)
const fallbackOperation = options.useFallback
? async () => {
const result = this.referenceRegistry.export(target, composition);
if (!result) {
throw new Error(`No reference exporter available for target: ${target}`);
}
this.emitEvent({
type: 'export:fallback',
target,
timestamp: Date.now(),
});
return result.output;
}
: undefined;
// Execute with circuit breaker
const circuitResult = await breaker.execute(exportOperation, fallbackOperation);
// Capture memory stats after compilation
const memoryStats = this.memoryMonitor?.captureMemoryStats();
// Run Gaussian budget analysis (W.034)
const budgetResult = this.analyzeGaussianBudget(target, composition, options);
// Generate documentation if enabled
let documentation: ExportResult['documentation'] | undefined;
if (options.generateDocs && circuitResult.success && circuitResult.data) {
const docGen = new CompilerDocumentationGenerator(options.docsOptions);
const outputStr =
typeof circuitResult.data === 'string'
? circuitResult.data
: JSON.stringify(circuitResult.data);
const tripleOutput = docGen.generate(composition, target, outputStr);
documentation = {
llmsTxt: tripleOutput.llmsTxt,
wellKnownMcp: tripleOutput.wellKnownMcp as unknown as Record<string, unknown>,
markdownDocs: tripleOutput.markdownDocs,
};
}
const fallbackOutput = typeof circuitResult.data === 'string' ? circuitResult.data : undefined;
// FAIL-CLOSED for USD/USDZ: a successful circuit-breaker fallback that
// produced a geometry-less stage is never a valid substitute. Demote to a
// failure instead of shipping a green empty scene.
if (circuitResult.success && circuitResult.usedFallback) {
const failClosedError = this.checkFallbackFailClosed(
target,
fallbackOutput ?? '',
circuitResult.error
);
if (failClosedError) {
if (options.throwOnError) throw failClosedError;
return this.buildFailClosedResult(target, failClosedError, startTime);
}
}
const baseWarnings = budgetResult?.warningMessages ?? [];
const warnings =
circuitResult.usedFallback && circuitResult.success
? [this.buildDegradedWarning(target, circuitResult.error), ...baseWarnings]
: baseWarnings;
const result: ExportResult = {
target,
success: circuitResult.success,
output: circuitResult.data as string | undefined,
error: circuitResult.error,
usedFallback: circuitResult.usedFallback,
// TOP-LEVEL unmissable signal: a successful result that used the reference
// fallback is a non-equivalent degraded substitute, not a real compile.
degraded: circuitResult.usedFallback && circuitResult.success ? true : undefined,
circuitState: circuitResult.state,
warnings,
metrics: circuitResult.metrics,
executionTime: Date.now() - startTime,
memoryStats,
gaussianBudgetAnalysis: budgetResult?.analysis,
documentation,
};
if (circuitResult.success) {
this.emitEvent({
type: 'export:success',
target,
timestamp: Date.now(),
data: { usedFallback: circuitResult.usedFallback },
});
}
return result;
}
private async exportDirect(
target: ExportTarget,
composition: HoloComposition,
options: Required<ExportOptions>,
startTime: number
): Promise<ExportResult> {
try {
// Update memory monitor with current AST
if (this.memoryMonitor) {
this.memoryMonitor.setAST(composition);
this.memoryMonitor.checkMemoryStatus();
}
const compiler = this.compilerFactory.createCompiler(target, options.compilerOptions);
// If compiler is IncrementalCompiler, attach memory monitor
if (compiler instanceof IncrementalCompiler && this.memoryMonitor) {
this.memoryMonitor.setIncrementalCompiler(compiler);
}
const output = await compiler.compile(composition);
// Capture memory stats after compilation
const memoryStats = this.memoryMonitor?.captureMemoryStats();
// Run Gaussian budget analysis (W.034)
const budgetResult = this.analyzeGaussianBudget(target, composition, options);
// Generate documentation if enabled
let documentation: ExportResult['documentation'] | undefined;
if (options.generateDocs && output) {
const docGen = new CompilerDocumentationGenerator(options.docsOptions);
const outputStr = typeof output === 'string' ? output : JSON.stringify(output);
const tripleOutput = docGen.generate(composition, target, outputStr);
documentation = {
llmsTxt: tripleOutput.llmsTxt,
wellKnownMcp: tripleOutput.wellKnownMcp as unknown as Record<string, unknown>,
markdownDocs: tripleOutput.markdownDocs,
};
}
const result: ExportResult = {
target,
success: true,
output,
usedFallback: false,
circuitState: CircuitState.CLOSED,
warnings: budgetResult?.warningMessages ?? [],
metrics: this.circuitRegistry.getBreaker(target).getMetrics(),
executionTime: Date.now() - startTime,
memoryStats,
gaussianBudgetAnalysis: budgetResult?.analysis,
documentation,
};
this.emitEvent({
type: 'export:success',
target,
timestamp: Date.now(),
});
return result;
} catch (error) {
// Try fallback if enabled
if (options.useFallback) {
const refResult = this.referenceRegistry.export(target, composition);
if (refResult) {
// FAIL-CLOSED for USD/USDZ: a geometry-less stage is never a valid
// substitute for a real compile. Refuse to ship a green empty scene.
const failClosedError = this.checkFallbackFailClosed(target, refResult.output, error);
if (failClosedError) {
if (options.throwOnError) throw failClosedError;
return this.buildFailClosedResult(target, failClosedError, startTime);
}
this.emitEvent({
type: 'export:fallback',
target,
timestamp: Date.now(),
});
const memoryStats = this.memoryMonitor?.captureMemoryStats();
// Run Gaussian budget analysis even on fallback path (W.034)
const budgetResult = this.analyzeGaussianBudget(target, composition, options);
return {
target,
success: true,
output: refResult.output,
usedFallback: true,
// TOP-LEVEL unmissable signal: this output is a non-equivalent
// reference substitute, NOT a real compile of the composition.
degraded: true,
circuitState: CircuitState.CLOSED,
warnings: [
this.buildDegradedWarning(target, error),
...refResult.warnings,
...(budgetResult?.warningMessages ?? []),
],
metrics: this.circuitRegistry.getBreaker(target).getMetrics(),
executionTime: Date.now() - startTime,
memoryStats,
gaussianBudgetAnalysis: budgetResult?.analysis,
};
}
}
throw error;
}
}
/**
* Build the human-readable warning that accompanies a degraded (fallback)
* export, naming the compiler that failed and that the output is a
* non-equivalent reference substitute.
*/
private buildDegradedWarning(target: ExportTarget, error: unknown): string {
const reason = error instanceof Error ? error.message : String(error);
return (
`DEGRADED: '${target}' compiler failed (${reason}); ` +
`output is a non-equivalent reference substitute, not a real compile.`
);
}
/**
* Fail-closed guard for reference-fallback output. For USD/USDZ specifically,
* a geometry-less stage (Root Xform with no child prims) is NEVER a valid
* substitute for a real compile — returns an Error to surface instead of a
* green empty scene. Returns null when the fallback output is acceptable.
*/
private checkFallbackFailClosed(
target: ExportTarget,
output: string,
originalError: unknown
): Error | null {
if (target === 'usd' || target === 'usdz') {
if (!usdStageHasGeometry(output)) {
const reason =
originalError instanceof Error ? originalError.message : String(originalError);
return new Error(
`${target.toUpperCase()} fallback produced an empty stage (zero geometry) ` +
`after the real compiler failed (${reason}). An empty USD stage is not a ` +
`valid substitute for a compile; failing closed instead of shipping a green empty scene.`
);
}
}
return null;
}
/**
* Construct a non-throwing failed ExportResult for the fail-closed path.
*/
private buildFailClosedResult(
target: ExportTarget,
error: Error,
startTime: number
): ExportResult {
return {
target,
success: false,
error,
usedFallback: true,
degraded: true,
circuitState: CircuitState.CLOSED,
warnings: [error.message],
metrics: this.circuitRegistry.getBreaker(target).getMetrics(),
executionTime: Date.now() - startTime,
};
}
/**
* Run Gaussian primitive budget analysis for the given target and composition.
*
* Determines the relevant platform(s) for the export target, runs the
* GaussianBudgetAnalyzer, and returns the analysis result along with
* formatted warning strings suitable for the ExportResult.warnings array.
*
* Returns null if:
* - Gaussian budget warnings are disabled
* - The target has no Gaussian-relevant platforms
* - The composition has no gaussian_splat traits
*/
private analyzeGaussianBudget(
target: ExportTarget,
composition: HoloComposition,
options: Required<ExportOptions>
): { analysis: GaussianBudgetAnalysis; warningMessages: string[] } | null {
if (!options.enableGaussianBudgetWarnings) return null;
// Determine which platforms this target should be validated against
const platforms = EXPORT_TARGET_TO_GAUSSIAN_PLATFORMS[target];
if (!platforms || platforms.length === 0) return null;
const analyzer = new GaussianBudgetAnalyzer({