"""FedMart Glyph Telemetry Integration. Provides real-time telemetry emission when glyphs activate: - emit_glyph_activation() - Emit telemetry on glyph activation - emit_superpower_usage() - Emit telemetry on superpower usage - emit_compressed_execution() - Emit telemetry on compressed execution (GlyphMart) - GlyphActivationEvent - Event structure for glyph activations """ import json import time from datetime import datetime from typing import Dict, Any, List, Optional from pathlib import Path class GlyphActivationEvent: """Represents a glyph activation event.""" def __init__( self, glyph_id: str, superpower_ids: List[int], specialized_type: str, metrics: Dict[str, Any], context: Dict[str, Any] = None ): self.glyph_id = glyph_id self.superpower_ids = superpower_ids self.specialized_type = specialized_type self.metrics = metrics self.context = context or {} self.timestamp = datetime.utcnow().isoformat() + "Z" self.run_id = f"glyph_{int(time.time() * 1000)}" def to_dict(self) -> Dict[str, Any]: """Convert to telemetry dict.""" return { "event_type": "glyph.activation", "timestamp": self.timestamp, "run_id": self.run_id, "glyph_id": self.glyph_id, "superpower_ids": self.superpower_ids, "superpower_count": len(self.superpower_ids), "specialized_type": self.specialized_type, "metrics": self.metrics, "resonance_score": self.calculate_resonance(), "context": self.context, } def calculate_resonance(self) -> float: """Calculate resonance score from metrics.""" if not self.metrics: return 0.0 values = [ self.metrics.get("power", 50), self.metrics.get("resonance", 50), self.metrics.get("stability", 50), self.metrics.get("connectivity", 50), ] avg = sum(values) / len(values) return round(avg / 100, 4) class FedMartGlyphAdapter: """Adapter for glyph telemetry → FedMart integration.""" def __init__(self, endpoint: Optional[str] = None, local_mode: bool = False): """Initialize FedMart glyph adapter. Args: endpoint: FedMart ingestion endpoint local_mode: If True, buffer telemetry locally """ self.endpoint = endpoint or "http://localhost:8000/fedmart/ingest/xic" self.local_mode = local_mode self.telemetry_buffer: List[Dict[str, Any]] = [] def emit_glyph_activation(self, event: GlyphActivationEvent) -> bool: """Emit glyph activation telemetry. Args: event: GlyphActivationEvent Returns: True if successful """ telemetry = event.to_dict() if self.local_mode: self.telemetry_buffer.append(telemetry) print(f"[FEDMART-GLYPH] Telemetry buffered: {event.glyph_id}") return True return self._send_to_fedmart(telemetry) def emit_superpower_usage( self, glyph_id: str, superpower_id: int, superpower_name: str, context: Dict[str, Any] = None ) -> bool: """Emit superpower usage telemetry. Args: glyph_id: Glyph ID superpower_id: Superpower ID superpower_name: Superpower name context: Optional context Returns: True if successful """ telemetry = { "event_type": "superpower.usage", "timestamp": datetime.utcnow().isoformat() + "Z", "glyph_id": glyph_id, "superpower_id": superpower_id, "superpower_name": superpower_name, "context": context or {}, } if self.local_mode: self.telemetry_buffer.append(telemetry) return True return self._send_to_fedmart(telemetry) def _send_to_fedmart(self, telemetry: Dict[str, Any]) -> bool: """Send telemetry to FedMart endpoint.""" try: import requests response = requests.post( self.endpoint, json=telemetry, timeout=2 ) return response.status_code in (200, 202, 204) except Exception as e: print(f"[FEDMART-GLYPH] Error sending telemetry: {e}") return False def get_telemetry_buffer(self) -> List[Dict[str, Any]]: """Get buffered telemetry (local mode only).""" return self.telemetry_buffer.copy() def clear_buffer(self) -> None: """Clear telemetry buffer.""" self.telemetry_buffer.clear() def emit_compressed_execution( gx_path: str, segment_count: int, traces_count: int, compressed_size: int, status: str = "success" ) -> bool: """Emit GlyphMart compressed execution telemetry. Args: gx_path: Path to executed GX file segment_count: Number of segments executed traces_count: Number of execution traces compressed_size: Size of compressed payload status: Execution status Returns: True if successful """ adapter = get_adapter() telemetry = { "event_type": "compressed_execution", "timestamp": datetime.utcnow().isoformat() + "Z", "run_id": f"glyphmart_{int(time.time() * 1000)}", "gx_path": gx_path, "segment_count": segment_count, "traces_count": traces_count, "compressed_size": compressed_size, "status": status } if adapter.local_mode: adapter.telemetry_buffer.append(telemetry) return True return adapter._send_to_fedmart(telemetry) # Global singleton instance _adapter_instance: Optional[FedMartGlyphAdapter] = None def get_adapter(local_mode: bool = True) -> FedMartGlyphAdapter: """Get or create global FedMart glyph adapter. Args: local_mode: Buffer locally by default Returns: FedMartGlyphAdapter singleton """ global _adapter_instance if _adapter_instance is None: _adapter_instance = FedMartGlyphAdapter(local_mode=local_mode) return _adapter_instance def emit_glyph_activation( glyph_id: str, superpower_ids: List[int], specialized_type: str, metrics: Dict[str, Any], context: Dict[str, Any] = None ) -> bool: """Convenience function to emit glyph activation. Args: glyph_id: Glyph ID superpower_ids: List of superpower IDs specialized_type: Specialized type name metrics: Glyph metrics context: Optional context Returns: True if successful """ adapter = get_adapter() event = GlyphActivationEvent(glyph_id, superpower_ids, specialized_type, metrics, context) return adapter.emit_glyph_activation(event) def emit_superpower_usage( glyph_id: str, superpower_id: int, superpower_name: str, context: Dict[str, Any] = None ) -> bool: """Convenience function to emit superpower usage. Args: glyph_id: Glyph ID superpower_id: Superpower ID superpower_name: Superpower name context: Optional context Returns: True if successful """ adapter = get_adapter() return adapter.emit_superpower_usage(glyph_id, superpower_id, superpower_name, context)