"""Symbolic Engine: Glyph Activation & Resonance. Core symbolic layer that: - Activates glyphs based on user intent - Calculates resonance from superpower combinations - Emits FedMart telemetry on activation - Routes to computational layer via dual-layer router Usage: from dual_layer.symbolic_engine import SymbolicEngine engine = SymbolicEngine() result = engine.activate_from_intent( user_intent="I need creative image generation", metrics={"power": 80, "resonance": 75, ...} ) """ import logging import os from typing import Dict, List, Any, Optional from pathlib import Path from glyphs.superpower_registry import ( load_all_superpowers, get_superpower, calculate_boost, super_stats, ) from glyphs.superpower_assigner import assign_superpowers, calculate_power_count from glyphs.specialized_types import get_specialized_type from dual_layer.router import route_glyph_activation, RoutingResult from dual_layer.vram_manager import get_vram_manager, VRAMManager from integrations.fedmart.glyph_telemetry import ( emit_glyph_activation, GlyphActivationEvent, get_adapter, ) logger = logging.getLogger(__name__) class SymbolicEngine: """Symbolic cognition engine for dual-layer system.""" def __init__(self): self.vram_manager = get_vram_manager() self._glyph_cache: Dict[str, Dict[str, Any]] = {} self._load_glyph_cache() def _load_glyph_cache(self): """Load glyph data from supercharged_glyphs.json.""" cache_path = Path("/home/dave/superdave/glyphs/supercharged_glyphs.json") if cache_path.exists(): import json with open(cache_path) as f: data = json.load(f) for glyph in data.get("glyphs", []): self._glyph_cache[glyph.get("id")] = glyph logger.info(f"Loaded {len(self._glyph_cache)} glyphs into cache") def get_glyph_info(self, glyph_id: str) -> Optional[Dict[str, Any]]: """Get glyph information from cache.""" return self._glyph_cache.get(glyph_id) async def activate_from_intent( self, user_intent: str, metrics: Optional[Dict[str, Any]] = None, request_type: str = "chat" ) -> Optional[RoutingResult]: """Activate glyph from user intent. Args: user_intent: User's request/intent string metrics: Optional metrics dict (auto-calculated if None) request_type: Type of request (chat, image, video, vision) Returns: RoutingResult if activation successful, None if failed """ # Load superpowers if not loaded try: load_all_superpowers() except FileNotFoundError: logger.error("Superpowers file not found") return None # Determine which glyph to activate glyph_id, metrics = self._select_glyph_for_intent( user_intent, metrics, request_type ) if not glyph_id: logger.warning("No suitable glyph found for intent") return None # Get glyph info glyph_info = self.get_glyph_info(glyph_id) # Assign superpowers superpower_ids = assign_superpowers( glyph_id, metrics, glyph_info.get("specializedType") if glyph_info else "", glyph_info.get("category") if glyph_info else "" ) if not superpower_ids: logger.error(f"Failed to assign superpowers to {glyph_id}") return None # Calculate power boost power_boost = calculate_boost(superpower_ids) # Get specialized type specialized_type = get_specialized_type( glyph_id, metrics, glyph_info.get("category") if glyph_info else "" ) # Route to computational layer routing_result = route_glyph_activation( glyph_id=glyph_id, superpower_ids=superpower_ids, specialized_type=specialized_type, power_boost=power_boost, request_type=request_type ) # Check VRAM and activate can_activate, reason = self.vram_manager.can_activate_glyph( glyph_id, routing_result.model, routing_result.vram_budget, routing_result.priority ) if not can_activate: logger.error(f"VRAM manager rejected activation: {reason}") # Emit telemetry for failed activation self._emit_activation_event( glyph_id, superpower_ids, specialized_type, metrics, success=False, failure_reason=reason ) return None # Activate in VRAM manager (async) activated = await self.vram_manager.activate_glyph( glyph_id=glyph_id, specialized_type=specialized_type, model=routing_result.model, vram_budget=routing_result.vram_budget, resonance_score=routing_result.resonance_score, power_boost=power_boost, priority=routing_result.priority ) if not activated: logger.error("VRAM manager activation failed") return None # Emit telemetry self._emit_activation_event( glyph_id, superpower_ids, specialized_type, metrics, success=True ) logger.info( f"✅ Symbolic activation complete: {glyph_id} " f"({specialized_type}) → {routing_result.model} " f"with {len(superpower_ids)} superpowers, " f"{power_boost:.2f}x boost, " f"{routing_result.resonance_score:.1f} resonance" ) return routing_result def _select_glyph_for_intent( self, user_intent: str, metrics: Optional[Dict[str, Any]], request_type: str ) -> Tuple[Optional[str], Dict[str, Any]]: """Select best glyph for user intent. Priority: 1. G001 (Ledo) for high-authority requests 2. Specialized types matching request_type 3. Default based on metrics Returns: (glyph_id, metrics) """ # Default metrics if not provided if metrics is None: metrics = { "power": 50, "resonance": 50, "stability": 50, "connectivity": 50, "affinity": 50, } # Check for G001 activation keywords g001_keywords = [ "root", "authority", "override", "primordial", "aether", "ledo", "system", "all powers" ] intent_lower = user_intent.lower() if any(keyword in intent_lower for keyword in g001_keywords): # Boost metrics for G001 metrics = { "power": 100, "resonance": 100, "stability": 100, "connectivity": 100, "affinity": 100, } return "G001", metrics # Select based on request type if request_type == "image": # Prefer star_bloom_creativity metrics["power"] = max(metrics.get("power", 50), 80) metrics["complexity"] = max(metrics.get("complexity", 50), 75) elif request_type == "video": # Prefer orbital_thread_network metrics["connectivity"] = max(metrics.get("connectivity", 50), 85) elif request_type == "vision": # Prefer mirror_weave_reasoning metrics["power"] = max(metrics.get("power", 50), 75) metrics["connectivity"] = max(metrics.get("connectivity", 50), 80) # Get specialized type from metrics specialized_type = get_specialized_type("G001", metrics) # Find first glyph with this type (skip G001) for glyph_id, glyph_info in self._glyph_cache.items(): if glyph_id == "G001": continue if glyph_info.get("specializedType") == specialized_type: return glyph_id, metrics # Fallback to G002 return "G002", metrics def _emit_activation_event( self, glyph_id: str, superpower_ids: List[int], specialized_type: str, metrics: Dict[str, Any], success: bool, failure_reason: str = "" ): """Emit glyph activation telemetry.""" # Use external FedMart endpoint if configured, otherwise local mode external_endpoint = os.getenv("FEDMART_ENDPOINT") adapter = get_adapter(local_mode=external_endpoint is None) context = { "success": success, "failure_reason": failure_reason, } event = GlyphActivationEvent( glyph_id=glyph_id, superpower_ids=superpower_ids, specialized_type=specialized_type, metrics=metrics, context=context ) adapter.emit_glyph_activation(event) async def get_status(self) -> Dict[str, Any]: """Get symbolic engine status.""" stats = super_stats() vram_status = await self.vram_manager.get_vram_status() resonance_summary = self.vram_manager.get_resonance_summary() return { "superpowers_loaded": stats.get("loaded", False), "superpowers_total": stats.get("total", 0), "glyphs_cached": len(self._glyph_cache), "active_glyphs": vram_status.get("active_glyphs", 0), "vram_usage_gb": vram_status.get("used_vram_gb", 0), "vram_available_gb": vram_status.get("available_vram_gb", 0), "total_resonance": resonance_summary.get("total_resonance", 0), "average_resonance": resonance_summary.get("average_resonance", 0), "highest_priority_glyph": resonance_summary.get("highest_priority_glyph"), } async def deactivate_glyph(self, glyph_id: str) -> bool: """Deactivate a glyph (async).""" return await self.vram_manager.deactivate_glyph(glyph_id) def get_active_glyphs(self) -> List[Dict[str, Any]]: """Get list of active glyphs.""" return self.vram_manager.get_active_glyphs() # Global singleton instance _symbolic_engine: Optional[SymbolicEngine] = None def get_symbolic_engine() -> SymbolicEngine: """Get global symbolic engine instance.""" global _symbolic_engine if _symbolic_engine is None: _symbolic_engine = SymbolicEngine() return _symbolic_engine