diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,11 +1,18 @@ -# app.py - Complete fixed version with Plotly compatibility AND MODERN COMPONENTS -# šŸš€ ARF Ultimate Investor Demo v3.3.9 - ENTERPRISE EDITION -# Enhanced with clear OSS vs Enterprise boundaries -# UPDATED: Added realism panel integration for enterprise-seasoned SRE experience -# UPDATED: Added dynamic performance metrics for Phase 2 -# SURGICAL FIX: Fixed AsyncRunner.async_to_sync contract violation -# DOCTRINAL FIX: Updated unpacking contract from 24 to 26 values -# MODERN UI: Integrated modern_components.py for enhanced UI foundation +#!/usr/bin/env python3 +""" +ARF v3.3.9 - Agentic Reliability Framework +Enterprise Edition with Modern UI & Complete Psychological Integration + +ARCHITECTURE: OSS advises → Enterprise executes +ENHANCEMENTS: +- Modern UI components with psychological UX +- Complete design token system +- Enhanced security & validation +- State management with undo/redo +- Telemetry & performance monitoring +- Historical evidence dominance +- Formal HealingIntent system +""" import logging import sys @@ -15,11 +22,14 @@ import datetime import asyncio import time import random +import re from pathlib import Path -from typing import Dict, List, Any, Optional, Tuple +from typing import Dict, List, Any, Optional, Tuple, Callable +from dataclasses import dataclass, asdict +from enum import Enum # =========================================== -# CONFIGURE LOGGING FIRST +# ENHANCED CONFIGURATION # =========================================== logging.basicConfig( level=logging.INFO, @@ -30,3126 +40,2362 @@ logging.basicConfig( ] ) logger = logging.getLogger(__name__) +logger.info("šŸš€ ARF v3.3.9 Initializing with Complete Modern Integration") # Add parent directory to path sys.path.insert(0, str(Path(__file__).parent)) # =========================================== -# MODERN UI FEATURE FLAGS +# MODERN COMPONENTS INTEGRATION # =========================================== -# Feature flags configuration for safe rollout -FEATURE_FLAGS = { - 'modern_ui': True, # Use modern components - 'dark_mode': True, # Enable dark mode toggle - 'responsive_design': True, # Use responsive CSS - 'progressive_disclosure': False, # Start disabled - 'keyboard_nav': False, - 'realtime_updates': False -} - -# Check URL parameters for feature flag overrides (placeholder) -def get_feature_flags(): - flags = FEATURE_FLAGS.copy() - # TODO: Add URL parameter parsing if needed - return flags +try: + from ui.modern_components import ( + ObservationGate, SequencingFlow, ProcessDisplay, + HistoricalEvidencePanel, HealingIntentDisplay, + initialize_modern_ui, DESIGN_TOKENS + ) + MODERN_COMPONENTS_AVAILABLE = True + logger.info("āœ… Modern UI components loaded successfully") +except ImportError as e: + MODERN_COMPONENTS_AVAILABLE = False + logger.warning(f"Modern components not available: {e}. Using fallback implementations.") # =========================================== -# FIX FOR ASYNC EVENT LOOP ISSUES - UPDATED FOR SPACES COMPATIBILITY +# PHASE 1: DESIGN TOKENS & CONSTANTS # =========================================== -# CRITICAL FIX: Don't apply nest_asyncio here - let uvicorn handle it -# This fixes the "loop_factory" TypeError -try: - import nest_asyncio - # Only apply if we're NOT in the main thread (detect if uvicorn is running) - # We'll handle this differently in the main() function - logger.info("āœ… nest_asyncio imported but not applied yet") -except ImportError: - logger.warning("āš ļø nest_asyncio not available, async operations may have issues") +class DesignTokens: + """Single source of truth for all design values - INTEGRATED""" + + # Colors (semantic naming) - Aligned with modern components + COLORS = { + # OSS Theme + "oss_primary": "#10b981", + "oss_secondary": "#34d399", + "oss_background": "#f0fdf4", + "oss_border": "#86efac", + + # Enterprise Theme + "enterprise_primary": "#3b82f6", + "enterprise_secondary": "#60a5fa", + "enterprise_background": "#eff6ff", + "enterprise_border": "#93c5fd", + + # Semantic Colors (aligned with modern components) + "success": "#10b981", + "warning": "#f59e0b", + "danger": "#ef4444", + "info": "#3b82f6", + + # Neutral Scale + "neutral_50": "#f8fafc", + "neutral_100": "#f1f5f9", + "neutral_200": "#e2e8f0", + "neutral_300": "#cbd5e1", + "neutral_400": "#94a3b8", + "neutral_500": "#64748b", + "neutral_600": "#475569", + "neutral_700": "#334155", + "neutral_800": "#1e293b", + "neutral_900": "#0f172a", + + # Surface Colors + "surface_light": "#ffffff", + "surface_dark": "#1e293b", + "background_light": "#f8fafc", + "background_dark": "#0f172a" + } + + # CSS Classes (consistent naming) + CLASSES = { + # Buttons + "btn_primary": "btn btn-primary", + "btn_secondary": "btn btn-secondary", + "btn_success": "btn btn-success", + "btn_danger": "btn btn-danger", + "btn_warning": "btn btn-warning", + + # Cards + "card_default": "card", + "card_elevated": "card card-elevated", + "card_outlined": "card card-outlined", + + # Layout + "container": "container mx-auto px-4", + "container_fluid": "container-fluid", + + # Grid + "grid_2": "grid grid-cols-1 md:grid-cols-2 gap-4", + "grid_3": "grid grid-cols-1 md:grid-cols-3 gap-4", + "grid_4": "grid grid-cols-2 md:grid-cols-4 gap-4", + + # Spacing + "spacing_sm": "p-2", + "spacing_md": "p-4", + "spacing_lg": "p-6", + "spacing_xl": "p-8" + } + + # Typography + TYPOGRAPHY = { + "font_family": "system-ui, -apple-system, sans-serif", + "font_size_sm": "0.875rem", + "font_size_base": "1rem", + "font_size_lg": "1.125rem", + "font_size_xl": "1.25rem", + "font_size_2xl": "1.5rem", + "font_size_3xl": "1.875rem", + "font_size_4xl": "2.25rem" + } + + # Borders & Radius + BORDERS = { + "radius_sm": "0.25rem", + "radius_md": "0.5rem", + "radius_lg": "0.75rem", + "radius_xl": "1rem", + "radius_full": "9999px" + } + + # Shadows + SHADOWS = { + "shadow_sm": "0 1px 2px 0 rgb(0 0 0 / 0.05)", + "shadow_md": "0 4px 6px -1px rgb(0 0 0 / 0.1)", + "shadow_lg": "0 10px 15px -3px rgb(0 0 0 / 0.1)", + "shadow_xl": "0 20px 25px -5px rgb(0 0 0 / 0.1)" + } + + # Transitions + TRANSITIONS = { + "fast": "150ms cubic-bezier(0.4, 0, 0.2, 1)", + "normal": "300ms cubic-bezier(0.4, 0, 0.2, 1)", + "slow": "500ms cubic-bezier(0.4, 0, 0.2, 1)" + } + + @classmethod + def get_border_color(cls, component_type: str) -> str: + """Get appropriate border color for component type""" + color_map = { + "oss": cls.COLORS["oss_primary"], + "enterprise": cls.COLORS["enterprise_primary"], + "success": cls.COLORS["success"], + "warning": cls.COLORS["warning"], + "danger": cls.COLORS["danger"], + "default": cls.COLORS["neutral_300"] + } + return color_map.get(component_type, color_map["default"]) + + @classmethod + def get_background_color(cls, component_type: str, dark_mode: bool = False) -> str: + """Get appropriate background color""" + if dark_mode: + return cls.COLORS["surface_dark"] + + bg_map = { + "oss": cls.COLORS["oss_background"], + "enterprise": cls.COLORS["enterprise_background"], + "surface": cls.COLORS["surface_light"], + "background": cls.COLORS["background_light"] + } + return bg_map.get(component_type, bg_map["surface"]) # =========================================== -# IMPORT UTILITY CLASSES FIRST +# PHASE 1: INPUT VALIDATION # =========================================== -from utils.installation import InstallationHelper -from demo.guidance import DemoPsychologyController, get_demo_controller +class InputValidator: + """Validate all user inputs for security and correctness""" + + # Whitelist of allowed scenarios + SCENARIO_WHITELIST = { + "Cache Miss Storm", + "Database Connection Pool Exhaustion", + "Kubernetes Memory Leak", + "API Rate Limit Storm", + "Network Partition", + "Storage I/O Saturation" + } + + # Allowed characters for various inputs + PATTERNS = { + "scenario_name": r'^[a-zA-Z0-9\s\-_]+$', # Alphanumeric, spaces, dashes, underscores + "numeric_id": r'^[0-9]+$', + "safe_text": r'^[a-zA-Z0-9\s\.,!?\-_\(\)]+$' + } + + @classmethod + def validate_scenario(cls, scenario: str) -> Tuple[bool, str]: + """Validate scenario name - returns (is_valid, sanitized_value)""" + if not scenario or not isinstance(scenario, str): + return False, "Cache Miss Storm" + + # Check against whitelist + if scenario in cls.SCENARIO_WHITELIST: + return True, scenario + + # Log attempt for security monitoring + logger.warning(f"Invalid scenario attempt: {scenario}") + + # Return safe default + return False, list(cls.SCENARIO_WHITELIST)[0] + + @classmethod + def validate_numeric_input(cls, value: Any, min_val: float = 0, max_val: float = float('inf')) -> Tuple[bool, float]: + """Validate numeric input with bounds""" + try: + num = float(value) + if min_val <= num <= max_val: + return True, num + else: + logger.warning(f"Numeric input out of bounds: {value}") + return False, max(min_val, min(num, max_val)) + except (ValueError, TypeError): + logger.warning(f"Invalid numeric input: {value}") + return False, min_val + + @classmethod + def sanitize_html(cls, html: str) -> str: + """Basic HTML sanitization""" + if not html: + return "" + + # Remove script tags and event handlers + sanitized = re.sub(r'.*?', '', html, flags=re.IGNORECASE | re.DOTALL) + sanitized = re.sub(r'on\w+="[^"]*"', '', sanitized) + sanitized = re.sub(r'on\w+=\'[^\']*\'', '', sanitized) + + # Limit length + if len(sanitized) > 10000: + sanitized = sanitized[:10000] + "..." + + return sanitized + + @classmethod + def validate_email(cls, email: str) -> bool: + """Simple email validation""" + if not email: + return False + pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' + return bool(re.match(pattern, email)) # =========================================== -# BOUNDARY MANAGEMENT SYSTEM +# PHASE 1: ENHANCED PSYCHOLOGICAL UX # =========================================== -class BoundaryManager: - """Manages clear boundaries between OSS and Enterprise""" +class PsychologicalUX: + """Manage user cognitive load and expectations - MODERN INTEGRATED""" + + class LoadingStage(Enum): + DETECTION = "detection" + RECALL = "recall" + DECISION = "decision" + EXECUTION = "execution" + ANALYSIS = "analysis" + VISUALIZATION = "visualization" @staticmethod - def get_system_boundaries(): - """Get current system boundaries""" - installation = get_installation_status() - - return { - "oss": { - "available": installation["oss_installed"], - "version": installation["oss_version"] or "mock", - "label": installation["badges"]["oss"]["text"], - "color": installation["badges"]["oss"]["color"], - "icon": installation["badges"]["oss"]["icon"], - "capabilities": ["advisory_analysis", "rag_search", "healing_intent"], - "license": "Apache 2.0" + def create_loading_state(stage: LoadingStage, progress: int = 0) -> str: + """Show what's happening during long operations""" + + stage_configs = { + PsychologicalUX.LoadingStage.DETECTION: { + "title": "šŸ” Detecting Patterns", + "description": "Analyzing telemetry for anomaly signatures", + "details": "Comparing against 150+ known patterns", + "color": DesignTokens.COLORS["info"], + "icon": "šŸ”" + }, + PsychologicalUX.LoadingStage.RECALL: { + "title": "🧠 Historical Recall", + "description": "Searching similar incidents in memory", + "details": "Accessing RAG database with 10,000+ incidents", + "color": DesignTokens.COLORS["oss_primary"], + "icon": "🧠" }, - "enterprise": { - "available": installation["enterprise_installed"], - "version": installation["enterprise_version"] or "simulated", - "label": installation["badges"]["enterprise"]["text"], - "color": installation["badges"]["enterprise"]["color"], - "icon": installation["badges"]["enterprise"]["icon"], - "capabilities": ["autonomous_execution", "rollback_guarantee", "mcp_integration", "enterprise_support"], - "license": "Commercial" + PsychologicalUX.LoadingStage.DECISION: { + "title": "šŸŽÆ Decision Making", + "description": "Formulating optimal healing strategy", + "details": "Evaluating 5+ action sequences for safety", + "color": DesignTokens.COLORS["warning"], + "icon": "šŸŽÆ" }, - "demo_mode": { - "active": True, - "architecture": "OSS advises → Enterprise executes", - "boundary_visible": settings.show_boundaries + PsychologicalUX.LoadingStage.EXECUTION: { + "title": "⚔ Safe Execution", + "description": "Executing with rollback guarantees", + "details": "Atomic operations with real-time validation", + "color": DesignTokens.COLORS["enterprise_primary"], + "icon": "⚔" } } - - @staticmethod - def get_boundary_badges() -> str: - """Get HTML badges showing system boundaries""" - boundaries = BoundaryManager.get_system_boundaries() + + config = stage_configs.get(stage, { + "title": "Processing", + "description": "ARF is working...", + "details": "Please wait", + "color": DesignTokens.COLORS["neutral_500"], + "icon": "ā³" + }) + + progress_bar = "" + if progress > 0: + progress_bar = f""" +
+
+
+
+ """ return f""" -
-
-
{boundaries['oss']['icon']}
+
+
+
{config['icon']}
-
- {boundaries['oss']['label']} -
-
- Apache 2.0 • Advisory Intelligence -
+

{config['title']}

+

{config['description']}

-
-
{boundaries['enterprise']['icon']}
-
-
- {boundaries['enterprise']['label']} -
-
- Commercial • Autonomous Execution -
+

{config['details']}

+ {progress_bar} + +
+
+
+
+
- -
-
šŸ—ļø
-
-
- Architecture Boundary -
-
- OSS advises → Enterprise executes +
+ """ + + @staticmethod + def create_success_notification(action: str, duration: str = "2.4s") -> str: + """Create satisfying completion feedback""" + return f""" +
+
+
+
+ āœ“
+
+

Success!

+

{action} completed successfully

+
+
+ {datetime.datetime.now().strftime("%H:%M:%S")} +
""" @staticmethod - def create_boundary_indicator(action: str, is_simulated: bool = True) -> str: - """Create clear execution boundary indicator""" - if is_simulated: - return f""" -
-
šŸŽ­
-

- SIMULATED ENTERPRISE EXECUTION -

-

- Action: {action}
- Mode: Enterprise Simulation (not real execution)
- Boundary: OSS advises → Enterprise would execute -

-
- DEMO BOUNDARY + def create_error_notification(error: str, recovery: str = "") -> str: + """Create helpful error feedback""" + recovery_html = f'

{recovery}

' if recovery else "" + + return f""" +
+
+
+
+ āš ļø +
+
+
+

Operation Failed

+

{error}

+ {recovery_html}
-

- In production, Enterprise edition would execute against real infrastructure -

- """ +
+ """ + + @staticmethod + def create_empty_state(icon: str, title: str, description: str, action: str = "") -> str: + """Create helpful empty state""" + action_html = f'' if action else "" + + return f""" +
+
{icon}
+

{title}

+

{description}

+ {action_html} +
+ """ + + # =========================================== + # MODERN PSYCHOLOGICAL COMPONENTS + # =========================================== + + @staticmethod + def create_observation_gate(confidence: float = 65.0, **kwargs) -> str: + """Create observation gate with modern components""" + # Validate input + is_valid, safe_confidence = InputValidator.validate_numeric_input(confidence, 0, 100) + + # Track usage + from app import telemetry + telemetry.track_user_interaction( + "observation_gate_viewed", + f"confidence_{safe_confidence}" + ) + + # Use modern component if available + if MODERN_COMPONENTS_AVAILABLE: + try: + html = ObservationGate.create(safe_confidence, **kwargs) + except Exception as e: + logger.error(f"Error creating modern observation gate: {e}") + html = PsychologicalUX._create_observation_gate_fallback(safe_confidence, **kwargs) else: - return f""" -
-
⚔
-

- REAL ENTERPRISE EXECUTION -

-

- Action: {action}
- Mode: Enterprise Autonomous
- Boundary: Real execution with safety guarantees -

-
- ENTERPRISE+ -
+ html = PsychologicalUX._create_observation_gate_fallback(safe_confidence, **kwargs) + + # Sanitize and return + return InputValidator.sanitize_html(html) + + @staticmethod + def _create_observation_gate_fallback(confidence: float = 65.0, **kwargs) -> str: + """Fallback observation gate implementation""" + threshold = 70.0 + if confidence < threshold: + status_color = DesignTokens.COLORS["warning"] + status_text = "Observation Gate: Awaiting confirmation" + decision_text = "Decision Intentionally Deferred" + else: + status_color = DesignTokens.COLORS["success"] + status_text = "Observation Gate Cleared" + decision_text = "Proceed with Policy Action" + + return f""" +
+

{status_text}

+

System restraint engaged

+
+

{decision_text}

+

Confidence: {confidence:.1f}% (Threshold: {threshold}%)

- """ - -# =========================================== -# FIXED: AsyncRunner - CONTRACT-PRESERVING VERSION -# =========================================== -class AsyncRunner: - """Enhanced async runner with better error handling - FIXED to preserve return contracts""" +
+ """ @staticmethod - def run_async(coro): - """Run async coroutine in sync context""" - try: - loop = asyncio.get_event_loop() - except RuntimeError: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) + def create_sequencing_panel(**kwargs) -> str: + """Create sequencing visualization with modern components""" + # Track usage + from app import telemetry + telemetry.track_user_interaction("sequencing_viewed", "panel") + + # Use modern component if available + if MODERN_COMPONENTS_AVAILABLE: + try: + html = SequencingFlow.create(**kwargs) + except Exception as e: + logger.error(f"Error creating modern sequencing: {e}") + html = PsychologicalUX._create_sequencing_fallback(**kwargs) + else: + html = PsychologicalUX._create_sequencing_fallback(**kwargs) - try: - return loop.run_until_complete(coro) - except Exception as e: - logger.error(f"Async execution failed: {e}") - # CRITICAL FIX: Return contract-compatible values instead of dict - error_html = f""" -
-
āŒ
-
-

Async Error

-

- Async operation failed -

-
+ return InputValidator.sanitize_html(html) + + @staticmethod + def _create_sequencing_fallback(**kwargs) -> str: + """Fallback sequencing implementation""" + return """ +
+

šŸ”„ Doctrinal Sequencing: Policy Over Reaction

+
+
1. Dampening (Required)
+
2. Concurrency Control (Required)
+
3. Observe (Required)
+
4. Scale (Optional)
- """ - - error_dict = { - "status": "error", - "error": str(e), - "scenario": "Unknown", - "arf_version": "3.3.9", - "boundary_note": "Async execution boundary reached" - } - - error_df = pd.DataFrame(columns=["Error", "Message"]).from_records([ - {"Error": "Async Execution Failed", "Message": str(e)} - ]) - - # šŸ”’ SHAPE CONTRACT ENFORCED: Always return 5-tuple matching expected signature - return error_html, error_html, error_html, error_dict, error_df +
+ """ @staticmethod - def async_to_sync(async_func): - """Decorator to convert async function to sync - FIXED to preserve return contract""" - def wrapper(*args, **kwargs): + def create_historical_evidence_panel(evidence_data: Dict = None, **kwargs) -> str: + """Create historical evidence panel""" + # Track usage + from app import telemetry + telemetry.track_user_interaction("historical_evidence_viewed", "panel") + + if MODERN_COMPONENTS_AVAILABLE: try: - # Direct call to run_async which now preserves contract - result = AsyncRunner.run_async(async_func(*args, **kwargs)) - - # Ensure result is a 5-tuple (contract validation) - if isinstance(result, tuple) and len(result) == 5: - return result - else: - # Contract violation - wrap it properly - logger.warning(f"Contract violation: Expected 5-tuple, got {type(result)}") - error_html = f""" -
-
āš ļø
-
-

Contract Violation

-

- Expected 5-tuple, got {type(result).__name__} -

-
-
- """ - - error_dict = { - "status": "contract_error", - "error": f"Expected 5-tuple, got {type(result)}", - "scenario": args[0] if args else "Unknown", - "arf_version": "3.3.9", - "boundary_note": "Return contract violation" - } - - error_df = pd.DataFrame(columns=["Error", "Message"]).from_records([ - {"Error": "Contract Error", "Message": "Return shape violation"} - ]) - - return error_html, error_html, error_html, error_dict, error_df - + html = HistoricalEvidencePanel.create(evidence_data, **kwargs) except Exception as e: - logger.error(f"Async to sync conversion failed: {e}") - # šŸ”’ SHAPE CONTRACT ENFORCED: Always return 5-tuple - error_html = f""" -
-
āŒ
-
-

Conversion Error

-

- Async to sync failed -

-
-
- """ - - error_dict = { - "status": "error", - "error": str(e), - "scenario": args[0] if args else "Unknown", - "arf_version": "3.3.9", - "boundary_context": "OSS advisory only - execution requires Enterprise" - } - - error_df = pd.DataFrame(columns=["Error", "Message"]).from_records([ - {"Error": "Conversion Failed", "Message": str(e)} - ]) - - # šŸ”’ SHAPE CONTRACT ENFORCED: Always return 5-tuple - return error_html, error_html, error_html, error_dict, error_df - return wrapper - -# =========================================== -# SIMPLE SETTINGS - FIXED: Added missing attributes -# =========================================== -class Settings: - """Simple settings class - FIXED: Added all missing attributes""" - def __init__(self): - self.arf_mode = "demo" - self.use_true_arf = True - self.default_scenario = "Cache Miss Storm" - self.max_history_items = 100 - self.auto_refresh_seconds = 30 - self.show_boundaries = True - self.architectural_honesty = True - self.engineer_annual_cost = 200000 - self.default_savings_rate = 0.25 # FIXED: Added missing attribute - self.cache_miss_impact = 8500 - self.database_impact = 4200 - self.kubernetes_impact = 5500 - self.api_impact = 3800 - self.network_impact = 12000 - self.storage_impact = 6800 - self.telemetry_enabled = True - self.mcp_mode = "simulated" - self.enterprise_features = ["simulated_execution", "rollback_guarantee"] - self.default_savings_rate = 0.25 # FIXED: Ensure it's defined - self.enable_mcp_integration = True # FIXED: Added missing - self.enable_learning_engine = True # FIXED: Added missing - self.max_concurrent_incidents = 5 # FIXED: Added missing - -settings = Settings() - -# =========================================== -# ARF INSTALLATION CHECK - FIXED VERSION -# =========================================== -def check_arf_installation(): - """Check if real ARF packages are installed - Fixed version""" - results = { - "oss_installed": False, - "enterprise_installed": False, - "oss_version": None, - "enterprise_version": None, - "oss_edition": "unknown", - "oss_license": "unknown", - "execution_allowed": False, - "recommendations": [], - "boundaries": { - "oss_can": ["advisory_analysis", "rag_search", "healing_intent"], - "oss_cannot": ["execute", "modify_infra", "autonomous_healing"], - "enterprise_requires": ["license", "infra_access", "safety_controls"] - }, - "badges": { - "oss": {"text": "āš ļø Mock ARF", "color": "#f59e0b", "icon": "āš ļø"}, - "enterprise": {"text": "šŸ”’ Enterprise Required", "color": "#64748b", "icon": "šŸ”’"} - }, - "timestamp": datetime.datetime.now().isoformat() - } + logger.error(f"Error creating modern historical evidence: {e}") + html = PsychologicalUX._create_historical_evidence_fallback(evidence_data, **kwargs) + else: + html = PsychologicalUX._create_historical_evidence_fallback(evidence_data, **kwargs) + + return InputValidator.sanitize_html(html) - # Check OSS package using InstallationHelper - installation_helper = InstallationHelper() - status = installation_helper.check_installation() - - results["oss_installed"] = status["oss_installed"] - results["oss_version"] = status["oss_version"] - results["enterprise_installed"] = status["enterprise_installed"] - results["enterprise_version"] = status["enterprise_version"] - results["recommendations"] = status["recommendations"] - - if results["oss_installed"]: - results["badges"]["oss"] = { - "text": f"āœ… ARF OSS v{results['oss_version']}", - "color": "#10b981", - "icon": "āœ…" - } - logger.info(f"āœ… ARF OSS v{results['oss_version']} detected") - else: - results["badges"]["oss"] = { - "text": "āœ… ARF OSS v3.3.9", - "color": "#10b981", - "icon": "āœ…" - } - logger.info("āœ… ARF OSS v3.3.9 (demo mode)") + @staticmethod + def _create_historical_evidence_fallback(evidence_data: Dict = None, **kwargs) -> str: + """Fallback historical evidence implementation""" + return """ +
+

🧠 Historical Evidence (Why Sequencing Matters)

+

Historical evidence outweighs model confidence in decision making.

+
+ """ - if results["enterprise_installed"]: - results["badges"]["enterprise"] = { - "text": f"šŸš€ Enterprise v{results['enterprise_version']}", - "color": "#8b5cf6", - "icon": "šŸš€" - } - logger.info(f"āœ… ARF Enterprise v{results['enterprise_version']} detected") - else: - results["badges"]["enterprise"] = { - "text": "šŸ¢ Enterprise Edition", # Changed from "šŸ”’ Enterprise Required" - "color": "#3b82f6", # Changed from "#64748b" (gray to blue) - "icon": "šŸ¢" # Changed from "šŸ”’" - } - logger.info("šŸ¢ Enterprise Edition (simulated)") + @staticmethod + def create_healing_intent_display(healing_intent: Dict, **kwargs) -> str: + """Create formal HealingIntent display""" + # Validate input + if not isinstance(healing_intent, dict): + healing_intent = {} + + # Track usage + from app import telemetry + telemetry.track_user_interaction( + "healing_intent_viewed", + f"confidence_{healing_intent.get('confidence', 0)}" + ) + + if MODERN_COMPONENTS_AVAILABLE: + try: + html = HealingIntentDisplay.create(healing_intent, **kwargs) + except Exception as e: + logger.error(f"Error creating modern healing intent: {e}") + html = PsychologicalUX._create_healing_intent_fallback(healing_intent, **kwargs) + else: + html = PsychologicalUX._create_healing_intent_fallback(healing_intent, **kwargs) + + return InputValidator.sanitize_html(html) - return results - -_installation_status = None - -def get_installation_status(): - """Get cached installation status""" - global _installation_status - if _installation_status is None: - _installation_status = check_arf_installation() - return _installation_status + @staticmethod + def _create_healing_intent_fallback(healing_intent: Dict, **kwargs) -> str: + """Fallback healing intent implementation""" + confidence = healing_intent.get('confidence', 0) + action = healing_intent.get('primary_action', 'No action specified') + + return f""" +
+

šŸ“ Formal HealingIntent Created

+
Confidence: {confidence:.1f}%
+
Action: {action}
+
+ """ + + @staticmethod + def create_process_display(process_type: str, data: Dict) -> str: + """Create process display (detection, recall, decision)""" + # Validate process type + valid_types = ['detection', 'recall', 'decision', 'safety', 'execution', 'learning'] + if process_type not in valid_types: + process_type = 'detection' + + # Track usage + from app import telemetry + telemetry.track_user_interaction(f"process_{process_type}_viewed", "display") + + if MODERN_COMPONENTS_AVAILABLE: + try: + html = ProcessDisplay.create(process_type, data) + except Exception as e: + logger.error(f"Error creating modern process display: {e}") + html = PsychologicalUX._create_process_display_fallback(process_type, data) + else: + html = PsychologicalUX._create_process_display_fallback(process_type, data) + + return InputValidator.sanitize_html(html) + + @staticmethod + def _create_process_display_fallback(process_type: str, data: Dict) -> str: + """Fallback process display implementation""" + icons = { + 'detection': 'šŸ•µļøā€ā™‚ļø', + 'recall': '🧠', + 'decision': 'šŸŽÆ', + 'safety': 'šŸ›”ļø', + 'execution': '⚔', + 'learning': 'šŸ“š' + } + + icon = icons.get(process_type, 'šŸ“Š') + title = process_type.title() + status = data.get('status', 'inactive') + + return f""" +
+
{icon}
+
{title}
+
Status: {status}
+
+ """ # =========================================== -# PLOTLY CONFIGURATION FOR GRADIO COMPATIBILITY +# FEATURE MANAGEMENT # =========================================== -import plotly.graph_objects as go -import plotly.express as px -import plotly.io as pio -import pandas as pd -import numpy as np +FEATURE_FLAGS = { + 'modern_ui': True, + 'dark_mode': True, + 'responsive_design': True, + 'loading_animations': True, + 'telemetry': True, + 'performance_monitoring': True, + 'psychological_components': MODERN_COMPONENTS_AVAILABLE +} -# Configure Plotly for Gradio compatibility -pio.templates.default = "plotly_white" -logger.info("āœ… Plotly configured for Gradio compatibility") +def is_feature_enabled(feature: str) -> bool: + """Simple, transparent feature checking""" + return FEATURE_FLAGS.get(feature, False) # =========================================== -# MODERN UI COMPONENTS IMPORT +# PHASE 2: STATE MANAGEMENT # =========================================== -# Import modern components with fallback -try: - from ui.modern_components import ( - initialize_modern_ui, - Card, Grid, ObservationGate, - SequencingFlow, ProcessDisplay, - DESIGN_TOKENS, Button, Badge, - ResponsiveUtils, Accessibility, DarkMode, - create_example_dashboard - ) - MODERN_UI_AVAILABLE = True - logger.info("āœ… Modern UI components loaded successfully") -except ImportError as e: - MODERN_UI_AVAILABLE = False - logger.warning(f"āš ļø Modern UI components not available: {e}") - - # Create minimal fallback classes - class Card: - @staticmethod - def create(content, **kwargs): - return f"
{content}
" - - class ObservationGate: - @staticmethod - def create(confidence=65.0, **kwargs): - return f"
Observation Gate: {confidence}%
" +class AppState: + """Centralized state management with history""" + + def __init__(self): + self._state = {} + self._history = [] + self._subscribers = [] + self._max_history = 50 + + # Initialize with defaults including psychological state + self._state.update({ + "theme": "system", + "last_scenario": "Cache Miss Storm", + "user_interactions": 0, + "errors_count": 0, + "loading": False, + "dark_mode": False, + # Psychological state + "confidence_level": 65.0, + "observation_gate_active": True, + "sequencing_stage": "dampening", + "historical_evidence_weight": 0.85, + "healing_intent_confidence": 87.3 + }) + + def set(self, key: str, value: Any, track_history: bool = True): + """Set state with optional history tracking""" + old_value = self._state.get(key) + + if track_history and old_value != value: + # Save to history (limited size) + self._history.append({**self._state}) + if len(self._history) > self._max_history: + self._history.pop(0) + + self._state[key] = value + self._notify(key, old_value, value) + + def get(self, key: str, default=None): + """Get state value""" + return self._state.get(key, default) + + def update(self, updates: Dict[str, Any], track_history: bool = True): + """Update multiple state values at once""" + if track_history: + self._history.append({**self._state}) + if len(self._history) > self._max_history: + self._history.pop(0) + + self._state.update(updates) + for key in updates: + self._notify(key, None, updates[key]) + + def undo(self) -> bool: + """Revert to previous state""" + if not self._history: + return False + + self._state = self._history.pop() + self._notify_all() + return True + + def subscribe(self, callback: Callable[[str, Any, Any], None]): + """Subscribe to state changes""" + if callback not in self._subscribers: + self._subscribers.append(callback) + + def unsubscribe(self, callback: Callable): + """Unsubscribe from state changes""" + if callback in self._subscribers: + self._subscribers.remove(callback) + + def _notify(self, key: str, old_value: Any, new_value: Any): + """Notify subscribers of state change""" + for callback in self._subscribers: + try: + callback(key, old_value, new_value) + except Exception as e: + logger.error(f"State subscriber error: {e}") + + def _notify_all(self): + """Notify all keys changed""" + for key in self._state: + self._notify(key, None, self._state[key]) + + def get_snapshot(self) -> Dict: + """Get complete state snapshot""" + return {**self._state} + + def restore_snapshot(self, snapshot: Dict): + """Restore from snapshot""" + self._history.append({**self._state}) + self._state = {**snapshot} + self._notify_all() + +# Global state instance +app_state = AppState() # =========================================== -# CSS LOADING FUNCTION +# PHASE 2: TELEMETRY & ANALYTICS # =========================================== -def load_css_files(): - """Load CSS files for modern UI with fallback - ENHANCED""" - css_content = "" +class TelemetryCollector: + """Anonymous usage analytics and performance monitoring""" - # Feature flag check - flags = get_feature_flags() + # Singleton instance + _instance = None - if flags.get('modern_ui', True): # Default to True - try: - # Load modern.css - with open("styles/modern.css", "r") as f: - css_content += f.read() + "\n" - logger.info("āœ… Loaded modern.css") - except FileNotFoundError: - logger.warning("āš ļø modern.css not found, using fallback") - css_content += """ - /* Modern CSS Fallback */ - :root { - --color-primary: #3b82f6; - --color-success: #10b981; - --color-warning: #f59e0b; - --color-danger: #ef4444; - --color-bg: #ffffff; - --color-text: #1e293b; - --color-border: #e2e8f0; - } - - .container { - width: 100%; - max-width: 1200px; - margin: 0 auto; - padding: 0 1rem; - } - - .card { - background: white; - border-radius: 0.75rem; - border: 1px solid var(--color-border); - padding: 1.5rem; - box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1); - } - """ + def __new__(cls): + if cls._instance is None: + cls._instance = super().__new__(cls) + cls._instance._initialize() + return cls._instance + + def _initialize(self): + """Initialize telemetry collector""" + self._session_id = self._generate_session_id() + self._events = [] + self._performance_metrics = [] + self._start_time = time.time() - if flags.get('responsive_design', True): - try: - # Load responsive.css - with open("styles/responsive.css", "r") as f: - css_content += f.read() + "\n" - logger.info("āœ… Loaded responsive.css") - except FileNotFoundError: - logger.warning("āš ļø responsive.css not found, using fallback") - css_content += """ - /* Responsive Fallback */ - @media (max-width: 768px) { - .grid-2, .grid-3, .grid-4 { - grid-template-columns: 1fr !important; - } - - .card { - padding: 1rem; - } - } - """ - - # Add dark mode toggle CSS - if flags.get('dark_mode', True): - css_content += """ - /* Dark Mode Toggle */ - .dark-mode-toggle { - position: fixed; - bottom: 20px; - right: 20px; - z-index: 1000; - background: white; - border: 2px solid var(--color-border); - border-radius: 50%; - width: 48px; - height: 48px; - display: flex; - align-items: center; - justify-content: center; - cursor: pointer; - box-shadow: 0 4px 12px rgba(0,0,0,0.1); - transition: all 0.3s ease; - } - - .dark-mode-toggle:hover { - transform: scale(1.1); - box-shadow: 0 6px 16px rgba(0,0,0,0.15); - } - - [data-theme="dark"] { - --color-bg: #0f172a; - --color-text: #f1f5f9; - --color-border: #334155; - } - - [data-theme="dark"] .card { - background: #1e293b; - } - """ - else: - # Minimal CSS - css_content = """ - :root { - --color-primary: #3b82f6; - --color-bg: #ffffff; - --color-text: #1e293b; + # Default consent (anonymous, no PII) + self._consent_given = True + self._max_events = 1000 + + logger.info(f"Telemetry initialized with session: {self._session_id[:8]}...") + + @staticmethod + def _generate_session_id() -> str: + """Generate anonymous session ID""" + import hashlib + import uuid + + # Create deterministic but anonymous session ID + unique_str = f"{uuid.getnode()}{datetime.datetime.now().timestamp():.0f}" + return hashlib.sha256(unique_str.encode()).hexdigest()[:16] + + def track_event(self, event: str, metadata: Dict = None, severity: str = "info"): + """Track user interactions and system events""" + if not is_feature_enabled('telemetry'): + return + + event_data = { + "event": event, + "timestamp": datetime.datetime.now().isoformat(), + "session_id": self._session_id, + "metadata": metadata or {}, + "severity": severity } - body { - font-family: system-ui, -apple-system, sans-serif; + # Store locally (in production, this would send to backend) + self._events.append(event_data) + if len(self._events) > self._max_events: + self._events.pop(0) + + # Log based on severity + log_methods = { + "error": logger.error, + "warning": logger.warning, + "info": logger.info, + "debug": logger.debug } - """ - - return css_content - -# =========================================== -# ENHANCED VISUALIZATION FUNCTIONS WITH GRADIO COMPATIBILITY -# =========================================== -def create_simple_telemetry_plot(scenario_name: str, is_real_arf: bool = True) -> go.Figure: - """ - FIXED: Enhanced for Gradio compatibility with better error handling - """ - try: - # Generate sample telemetry data - times = pd.date_range(start=datetime.datetime.now() - datetime.timedelta(minutes=10), - end=datetime.datetime.now(), - periods=60) - - # Different patterns based on scenario - if "Cache" in scenario_name: - normal_values = np.random.normal(30, 5, 30).tolist() - anomaly_values = np.random.normal(85, 10, 30).tolist() - data = normal_values + anomaly_values - title = f"Cache Hit Rate: {scenario_name}" - y_label = "Hit Rate (%)" - threshold = 75 - elif "Database" in scenario_name: - normal_values = np.random.normal(15, 3, 30).tolist() - anomaly_values = np.random.normal(95, 5, 30).tolist() - data = normal_values + anomaly_values - title = f"Database Connections: {scenario_name}" - y_label = "Connections (%)" - threshold = 90 - elif "Kubernetes" in scenario_name: - normal_values = np.random.normal(40, 8, 30).tolist() - anomaly_values = np.random.normal(95, 2, 30).tolist() - data = normal_values + anomaly_values - title = f"Memory Usage: {scenario_name}" - y_label = "Memory (%)" - threshold = 85 - else: - normal_values = np.random.normal(50, 10, 30).tolist() - anomaly_values = np.random.normal(90, 5, 30).tolist() - data = normal_values + anomaly_values - title = f"System Metrics: {scenario_name}" - y_label = "Metric (%)" - threshold = 80 - - # Create Plotly figure - fig = go.Figure() - - # Add normal region - fig.add_trace(go.Scatter( - x=times[:30], - y=data[:30], - mode='lines', - name='Normal', - line=dict(color='#10b981', width=3), - fill='tozeroy', - fillcolor='rgba(16, 185, 129, 0.1)' - )) - - # Add anomaly region - fig.add_trace(go.Scatter( - x=times[30:], - y=data[30:], - mode='lines', - name='Anomaly', - line=dict(color='#ef4444', width=3) - )) - - # Add threshold line - fig.add_hline(y=threshold, line_dash="dash", - line_color="#f59e0b", - annotation_text="Alert Threshold", - annotation_position="top right") - - # Update layout - FIXED: Simplified for Gradio compatibility - fig.update_layout( - title={ - 'text': title, - 'font': dict(size=18, color='#1e293b', family="Arial, sans-serif"), - 'x': 0.5 - }, - xaxis_title="Time", - yaxis_title=y_label, - height=300, - margin=dict(l=40, r=20, t=50, b=40), - plot_bgcolor='white', - paper_bgcolor='white', - showlegend=True, - hovermode='x unified' - ) - logger.info(f"āœ… Created telemetry plot for {scenario_name}") - return fig + log_method = log_methods.get(severity, logger.info) + log_method(f"Telemetry[{severity}]: {event}") + + def track_performance(self, component: str, duration_ms: float, metadata: Dict = None): + """Track component performance metrics""" + if not is_feature_enabled('performance_monitoring'): + return - except Exception as e: - logger.error(f"Error creating telemetry plot: {e}") - # Return a simple valid Plotly figure as fallback - fig = go.Figure() - fig.add_trace(go.Scatter(x=[0, 1], y=[0, 1], mode='lines', name='Fallback')) - fig.update_layout( - title=f"Telemetry: {scenario_name}", - height=300, - plot_bgcolor='white' - ) - return fig - -def create_simple_impact_plot(scenario_name: str, is_real_arf: bool = True) -> go.Figure: - """ - FIXED: Enhanced for Gradio compatibility - """ - try: - # Impact values based on scenario - impact_values = { - "Cache Miss Storm": 8500, - "Database Connection Pool Exhaustion": 4200, - "Kubernetes Memory Leak": 5500, - "API Rate Limit Storm": 3800, - "Network Partition": 12000, - "Storage I/O Saturation": 6800 + metric = { + "component": component, + "duration_ms": duration_ms, + "timestamp": datetime.datetime.now().isoformat(), + "metadata": metadata or {} } - impact = impact_values.get(scenario_name, 5000) + self._performance_metrics.append(metric) - # Create gauge chart - FIXED: Enhanced for Gradio - fig = go.Figure(go.Indicator( - mode="gauge+number", - value=impact, - domain={'x': [0, 1], 'y': [0, 1]}, - title={ - 'text': f"Revenue Impact: ${impact:,}/hour", - 'font': dict(size=16, family="Arial, sans-serif") + # Alert on slow components + if duration_ms > 1000: + self.track_event( + f"slow_component_{component}", + {"duration_ms": duration_ms}, + "warning" + ) + logger.warning(f"Slow component: {component} took {duration_ms:.0f}ms") + + def track_error(self, error: Exception, context: str = ""): + """Track errors with context""" + self.track_event( + f"error_{context}", + { + "error_type": type(error).__name__, + "error_message": str(error), + "context": context }, - number={ - 'prefix': "$", - 'suffix': "/hour", - 'font': dict(size=28, family="Arial, sans-serif") + "error" + ) + + def track_user_interaction(self, interaction: str, element: str = ""): + """Track user interactions for UX analysis""" + self.track_event( + f"user_interaction_{interaction}", + { + "element": element, + "timestamp": datetime.datetime.now().isoformat() }, - gauge={ - 'axis': {'range': [None, impact * 1.2], 'tickwidth': 1}, - 'bar': {'color': "#ef4444"}, - 'bgcolor': "white", - 'borderwidth': 2, - 'bordercolor': "gray", - 'steps': [ - {'range': [0, impact * 0.3], 'color': '#10b981'}, - {'range': [impact * 0.3, impact * 0.7], 'color': '#f59e0b'}, - {'range': [impact * 0.7, impact], 'color': '#ef4444'} - ], - 'threshold': { - 'line': {'color': "black", 'width': 4}, - 'thickness': 0.75, - 'value': impact - } - } - )) - - # Update layout - FIXED: Enhanced for Gradio - fig.update_layout( - height=400, - margin=dict(l=30, r=30, t=70, b=30), - paper_bgcolor='white', - font=dict(family="Arial, sans-serif") + "info" ) - logger.info(f"āœ… Created impact plot for {scenario_name}") - return fig - - except Exception as e: - logger.error(f"Error creating impact plot: {e}") - # Return a simple valid gauge as fallback - fig = go.Figure(go.Indicator( - mode="gauge", - value=0, - title={'text': "Impact (fallback)"} - )) - fig.update_layout(height=400) - return fig - -def create_empty_plot(title: str, is_real_arf: bool = True) -> go.Figure: - """ - FIXED: Enhanced for Gradio compatibility - """ - try: - fig = go.Figure() - - # Add text annotation - FIXED: Enhanced - fig.add_annotation( - x=0.5, y=0.5, - text=title, - showarrow=False, - font=dict(size=18, color="#64748b", family="Arial, sans-serif"), - xref="paper", - yref="paper" - ) + # Update app state + app_state.set("user_interactions", app_state.get("user_interactions", 0) + 1) + + def get_session_summary(self) -> Dict: + """Get telemetry summary for current session""" + session_duration = time.time() - self._start_time - # Add boundary indicator if needed - if is_real_arf: - fig.add_annotation( - x=0.02, y=0.98, - text="āœ… REAL ARF", - showarrow=False, - font=dict(size=12, color="#10b981", family="Arial, sans-serif"), - xref="paper", - yref="paper", - bgcolor="white", - bordercolor="#10b981", - borderwidth=1, - borderpad=4 - ) + # Count events by severity + severity_counts = {} + for event in self._events: + severity = event.get("severity", "info") + severity_counts[severity] = severity_counts.get(severity, 0) + 1 - fig.update_layout( - title={ - 'text': "Visualization Placeholder", - 'font': dict(size=14, color="#94a3b8", family="Arial, sans-serif") - }, - height=300, - plot_bgcolor='white', - paper_bgcolor='white', - xaxis={'visible': False}, - yaxis={'visible': False}, - margin=dict(l=20, r=20, t=50, b=20) - ) + # Calculate average performance + avg_performance = 0 + if self._performance_metrics: + avg_performance = sum(m["duration_ms"] for m in self._performance_metrics) / len(self._performance_metrics) - return fig + # Psychological component usage + psych_events = [e for e in self._events if any(keyword in e["event"] for keyword in [ + "observation_gate", "sequencing", "historical_evidence", "healing_intent", "process_" + ])] - except Exception as e: - logger.error(f"Error creating empty plot: {e}") - # Ultra-simple fallback - fig = go.Figure() - fig.update_layout(height=300) - return fig + return { + "session_id": self._session_id, + "session_duration_seconds": round(session_duration, 1), + "total_events": len(self._events), + "event_counts_by_severity": severity_counts, + "psychological_component_events": len(psych_events), + "performance_metrics_count": len(self._performance_metrics), + "average_component_time_ms": round(avg_performance, 1), + "user_interactions": app_state.get("user_interactions", 0), + "errors_count": app_state.get("errors_count", 0) + } + + def export_data(self, format: str = "json") -> str: + """Export telemetry data (for debugging)""" + if format == "json": + return json.dumps({ + "session_summary": self.get_session_summary(), + "recent_events": self._events[-100:], # Last 100 events + "recent_performance": self._performance_metrics[-50:] # Last 50 metrics + }, indent=2) + return "" + +# Global telemetry instance +telemetry = TelemetryCollector() # =========================================== -# ARF OSS UI ADAPTER - DOCTRINALLY PURE IMPLEMENTATION +# PHASE 2: PERFORMANCE BUDGET MONITOR # =========================================== - -def transform_arf_output_for_ui(raw_result: dict, scenario_name: str) -> dict: - """ - TRANSLATOR FUNCTION - NOT AN ANALYST - - Extracts existing intelligence from real ARF OSS output and transforms - to UI-expected format. Does not compute, infer, or enhance. - - Rules: - 1. Source of truth: raw_result["oss_analysis"]["analysis"] - 2. Extract only what exists - 3. Derive UI fields mechanically from existing data - 4. Never invent intelligence - 5. Defaults must be visibly conservative, not plausible - 6. Status must reflect contribution, not invocation - - Returns: UI-compatible dict with populated analysis and agents fields - """ +class PerformanceBudget: + """Enforce performance budgets and prevent regression""" + + BUDGETS = { + "css_size_kb": 50, # Max CSS size + "initial_load_time_ms": 3000, # Time to interactive + "component_render_ms": 100, # Max component render time + "api_response_ms": 500, # Max API response time + "animation_duration_ms": 300 # Max animation duration + } - # =================================================== - # STEP 1: DETERMINE INPUT MODE AND SOURCE DATA - # =================================================== + THRESHOLDS = { + "warning": 0.8, # 80% of budget (warning) + "critical": 0.95 # 95% of budget (critical) + } - # Mode 1: Real OSS Mode (has oss_analysis) - if "oss_analysis" in raw_result and raw_result["oss_analysis"]: - oss_analysis = raw_result["oss_analysis"] - source_analysis = oss_analysis.get("analysis", {}) if isinstance(oss_analysis, dict) else {} - is_real_oss = True - - # Mode 2: Mock/Fallback Mode (already has analysis at root) - elif "analysis" in raw_result and raw_result["analysis"]: - source_analysis = raw_result["analysis"] - is_real_oss = False + @classmethod + def check_css_budget(cls, css_content: str) -> Tuple[bool, str]: + """Check if CSS exceeds budget""" + size_kb = len(css_content) / 1024 + budget = cls.BUDGETS["css_size_kb"] + + if size_kb > budget: + message = f"CSS budget exceeded: {size_kb:.1f}KB > {budget}KB" + logger.error(message) + telemetry.track_event("css_budget_exceeded", {"size_kb": size_kb}, "error") + return False, message + + # Check thresholds + ratio = size_kb / budget + if ratio > cls.THRESHOLDS["critical"]: + logger.warning(f"CSS near critical: {size_kb:.1f}KB ({ratio:.0%} of budget)") + elif ratio > cls.THRESHOLDS["warning"]: + logger.info(f"CSS near warning: {size_kb:.1f}KB ({ratio:.0%} of budget)") + + return True, f"CSS OK: {size_kb:.1f}KB" + + @classmethod + def check_component_performance(cls, component_name: str, render_time_ms: float) -> bool: + """Check component render performance""" + budget = cls.BUDGETS["component_render_ms"] + + if render_time_ms > budget: + telemetry.track_performance(component_name, render_time_ms) + telemetry.track_event( + f"component_slow_{component_name}", + {"render_time_ms": render_time_ms}, + "warning" + ) + return False - # Mode 3: Error/Failure Mode - else: - # Return minimal UI-safe structure to prevent UI breakage - return { - "status": raw_result.get("status", "error"), - "scenario": scenario_name, - "arf_version": raw_result.get("arf_version", "3.3.9"), - "analysis": { - "detected": False, - "confidence": 0, # VISIBLY CONSERVATIVE - "similar_incidents": 0, # VISIBLY CONSERVATIVE - "healing_intent_created": False, - "recommended_action": "Check OSS analysis output", - "estimated_recovery": "Unknown" # VISIBLY CONSERVATIVE - }, - "agents": { - "detection": {"status": "error", "confidence": 0}, - "recall": {"status": "error", "similar_incidents": 0}, - "decision": {"status": "error", "healing_intent_created": False} - }, - "boundary_note": "OSS analysis output malformed", - "installation": { - "oss_installed": True, - "version": "3.3.9", - "edition": "oss" - } - } + return True - # =================================================== - # STEP 2: EXTRACT ANALYSIS DATA (SOURCE OF TRUTH ONLY) - # =================================================== - - # Extract detection data - MUST EXIST IN SOURCE - detection_data = source_analysis.get("detection", {}) if isinstance(source_analysis, dict) else {} - recall_data = source_analysis.get("recall", {}) if isinstance(source_analysis, dict) else {} - decision_data = source_analysis.get("decision", {}) if isinstance(source_analysis, dict) else {} - - # =================================================== - # STEP 3: BUILD UI ANALYSIS (DERIVED, NOT INFERRED) - # =================================================== - - # DOCTRINALLY PURE: detection only when OSS explicitly signals it - detected = False - if isinstance(detection_data, dict): - if "anomaly_detected" in detection_data: - detected = bool(detection_data["anomaly_detected"]) - elif "detected" in detection_data: - detected = bool(detection_data["detected"]) - - # CORRECTED: confidence = 0 if not in source (visibly conservative) - confidence = 0 # VISIBLY CONSERVATIVE DEFAULT - # Confidence must come from detection if anomaly detected - if detected and isinstance(detection_data, dict) and "confidence" in detection_data: - confidence = detection_data["confidence"] - elif isinstance(decision_data, dict) and "confidence" in decision_data: - confidence = decision_data["confidence"] - - # CORRECTED: similar_incidents = 0 if not in source (visibly conservative) - similar_incidents = 0 # VISIBLY CONSERVATIVE DEFAULT - if isinstance(recall_data, dict) and "results" in recall_data: - if isinstance(recall_data["results"], list): - similar_incidents = len(recall_data["results"]) - elif "similar_incidents" in recall_data: - similar_incidents = recall_data["similar_incidents"] - - # DOCTRINALLY PURE: healing intent only when explicitly true in OSS output - healing_intent_created = False - if isinstance(decision_data, dict): - # Healing intent exists if explicitly marked OR an action is present - healing_intent_created = bool( - decision_data.get("healing_intent_created", False) - or decision_data.get("action") - or decision_data.get("recommended_action") - ) + @classmethod + def measure_execution_time(cls, func: Callable, context: str = "") -> Any: + """Decorator to measure execution time""" + def wrapper(*args, **kwargs): + start_time = time.time() + try: + result = func(*args, **kwargs) + execution_time = (time.time() - start_time) * 1000 # Convert to ms + + # Check against budget + cls.check_component_performance(context or func.__name__, execution_time) + + # Track performance + telemetry.track_performance(context or func.__name__, execution_time) + + return result + except Exception as e: + execution_time = (time.time() - start_time) * 1000 + telemetry.track_error(e, f"perf_measure_{context}") + raise + + return wrapper - # Rule: recommended_action = pass through existing decision action text - recommended_action = "No actionable intelligence found" # VISIBLY CONSERVATIVE - if isinstance(decision_data, dict): - if "action" in decision_data: - recommended_action = decision_data["action"] - elif "recommended_action" in decision_data: - recommended_action = decision_data["recommended_action"] - - # CORRECTED: estimated_recovery = "Unknown" (do not calculate or imply) - estimated_recovery = "Unknown" - - # =================================================== - # STEP 4: BUILD UI AGENTS (CONTRIBUTION-BASED STATUS) - # =================================================== - - # REFINED: Agent status reflects actual contribution, not mere invocation - # Detection agent: "active" only if detection actually occurred - detection_status = "active" if detected else "inactive" - - # Recall agent: "active" only if similar incidents were found - recall_status = "active" if similar_incidents > 0 else "inactive" - - # Decision agent: "active" only if healing intent was created - decision_status = "active" if healing_intent_created else "inactive" - - # Override status to "error" if OSS status is error - if raw_result.get("status") == "error": - detection_status = "error" - recall_status = "error" - decision_status = "error" - - # =================================================== - # STEP 5: ASSEMBLE FINAL UI-COMPATIBLE RESULT - # =================================================== - - result = { - "status": raw_result.get("status", "success"), - "scenario": raw_result.get("scenario", scenario_name), - "arf_version": raw_result.get("arf_version", "3.3.9"), - "analysis": { - "detected": detected, - "confidence": confidence, - "similar_incidents": similar_incidents, - "healing_intent_created": healing_intent_created, - "recommended_action": recommended_action, - "estimated_recovery": estimated_recovery - }, - "agents": { - "detection": { - "status": detection_status, - "confidence": confidence if detection_status == "active" else 0 - }, - "recall": { - "status": recall_status, - "similar_incidents": similar_incidents if recall_status == "active" else 0 - }, - "decision": { - "status": decision_status, - "healing_intent_created": healing_intent_created if decision_status == "active" else False - } - }, - "boundary_note": raw_result.get("boundary_note", - "Real ARF OSS 3.3.9 analysis complete → Ready for Enterprise execution"), - "installation": { - "oss_installed": True, - "version": "3.3.9", - "edition": "oss" + @classmethod + def get_budget_status(cls) -> Dict: + """Get current budget status""" + return { + "budgets": cls.BUDGETS, + "thresholds": cls.THRESHOLDS, + "timestamp": datetime.datetime.now().isoformat() } - } - - # Preserve original oss_analysis for debugging (optional) - if is_real_oss: - result["_original_oss_analysis"] = raw_result.get("oss_analysis") - - return result - + # =========================================== -# UPDATED: run_true_arf_analysis() - DOCTRINALLY PURE +# PHASE 2: UPDATE OPTIMIZATOR # =========================================== - -@AsyncRunner.async_to_sync -async def run_true_arf_analysis(scenario_name: str) -> tuple: - """ - DOCTRINALLY PURE VERSION: Adapter transforms ARF OSS output with epistemic honesty - Returns exactly 5 values as expected by UI: - 1. detection_html (HTML string) - 2. recall_html (HTML string) - 3. decision_html (HTML string) - 4. oss_results_dict (Python dict for JSON display) - 5. incident_df (DataFrame for Gradio DataFrame component) - """ +class UpdateOptimizer: + """Prevent unnecessary UI updates and re-renders""" - components = get_components() - installation = get_installation_status() - boundaries = BoundaryManager.get_system_boundaries() - - logger.info(f"šŸ” Running True ARF analysis for: {scenario_name}") + def __init__(self): + self._component_states = {} + self._update_throttle_ms = 100 # Minimum time between updates + self._last_update_times = {} - try: - # Get orchestrator - orchestrator = components["DemoOrchestrator"]() - - # Get scenario data - scenarios = components["INCIDENT_SCENARIOS"] - scenario_data = scenarios.get(scenario_name, {}) - - # ====================================================== - # DOCTRINAL FIX POINT: CALL REAL ARF OSS - # ====================================================== - raw_result = await orchestrator.analyze_incident(scenario_name, scenario_data) - - # ====================================================== - # DOCTRINAL ADAPTER: TRANSFORM WITH EPISTEMIC HONESTY - # ====================================================== - transformed_result = transform_arf_output_for_ui(raw_result, scenario_name) - - # ====================================================== - # EXISTING UI INTEGRATION (PRESERVED) - # ====================================================== - # Add to audit trail - get_audit_manager().add_incident(scenario_name, transformed_result) - - # Create HTML for active agents using transformed result - boundary_color = boundaries["oss"]["color"] - - # Extract data from transformed result - analysis = transformed_result.get("analysis", {}) - agents = transformed_result.get("agents", {}) - - # Get data for HTML templates - confidence = analysis.get("confidence", 0) # CONSERVATIVE DEFAULT - similar_incidents = analysis.get("similar_incidents", 0) # CONSERVATIVE DEFAULT - detection_agent = agents.get("detection", {}) - recall_agent = agents.get("recall", {}) - decision_agent = agents.get("decision", {}) - - # Detection Agent HTML - Now truthfully reflects actual detection - detection_status = detection_agent.get("status", "inactive") - detection_status_text = detection_status.capitalize() - - # REFINED: Badge text reflects actual contribution state - if detection_status == "active": - detection_badge = "DETECTED" - confidence_text = f"Anomaly detected with {confidence}% confidence" - elif detection_status == "inactive": - detection_badge = "ANALYZING" - confidence_text = "No anomaly signal found" - else: - detection_badge = "ERROR" - confidence_text = "Detection analysis failed" - - detection_html = f""" -
-
šŸ•µļøā€ā™‚ļø
-
-

Detection Process

-

- {confidence_text} -

-
- - Status: {detection_status_text} - -
-
- {detection_badge} -
-
-
- """ + def should_update_component(self, component_id: str, new_state: Dict) -> bool: + """Check if component update is necessary""" + old_state = self._component_states.get(component_id, {}) - # Recall Agent HTML - Now truthfully reflects actual recall - recall_status = recall_agent.get("status", "inactive") - recall_status_text = recall_status.capitalize() - - # REFINED: Badge text reflects actual contribution state - if recall_status == "active": - recall_badge = "RECALLED" - recall_text = f"Found {similar_incidents} similar incident{'s' if similar_incidents != 1 else ''}" - elif recall_status == "inactive": - recall_badge = "SEARCHING" - recall_text = "No similar incidents found" - else: - recall_badge = "ERROR" - recall_text = "Recall analysis failed" - - recall_html = f""" -
-
🧠
-
-

Recall Process

-

- {recall_text} -

-
- - Status: {recall_status_text} - -
-
- {recall_badge} -
-
-
- """ + # Deep compare states + if self._states_equal(old_state, new_state): + logger.debug(f"Skipping update for {component_id} (no state change)") + return False - # Decision Agent HTML - Now truthfully reflects actual decision - decision_status = decision_agent.get("status", "inactive") - decision_status_text = decision_status.capitalize() - - # REFINED: Badge text reflects actual contribution state - if decision_status == "active": - decision_badge = "DECIDED" - decision_text = analysis.get('recommended_action', 'Action recommended') - elif decision_status == "inactive": - decision_badge = "EVALUATING" - decision_text = "No action recommended" - else: - decision_badge = "ERROR" - decision_text = "Decision analysis failed" - - decision_html = f""" -
-
šŸŽÆ
-
-

Decision Process

-

- {decision_text} -

-
- - Status: {decision_status_text} - -
-
- {decision_badge} -
-
-
- """ - - # OSS Results Dict for JSON display (using transformed result) - oss_results_dict = transformed_result - - # Incident DataFrame - incident_df = get_audit_manager().get_incident_dataframe() - - logger.info(f"āœ… True ARF analysis complete for {scenario_name}") - logger.info(f" Detection: {'ACTIVE' if detection_status == 'active' else 'INACTIVE'} (confidence: {confidence})") - logger.info(f" Recall: {'ACTIVE' if recall_status == 'active' else 'INACTIVE'} (incidents: {similar_incidents})") - logger.info(f" Decision: {'ACTIVE' if decision_status == 'active' else 'INACTIVE'}") - - return detection_html, recall_html, decision_html, oss_results_dict, incident_df - - except Exception as e: - logger.error(f"True ARF analysis failed: {e}") - - # Return error state with proper types - error_html = f""" -
-
āŒ
-
-

Analysis Error

-

- Failed to analyze incident -

-
- - Status: Error - -
-
-
- """ + # Throttle updates + current_time = time.time() * 1000 + last_update = self._last_update_times.get(component_id, 0) - error_dict = { - "status": "error", - "error": str(e), - "scenario": scenario_name, - "arf_version": "3.3.9", - "analysis": { - "detected": False, - "confidence": 0, - "similar_incidents": 0, - "healing_intent_created": False, - "recommended_action": "Check ARF installation", - "estimated_recovery": "Unknown" - }, - "agents": { - "detection": {"status": "error", "confidence": 0}, - "recall": {"status": "error", "similar_incidents": 0}, - "decision": {"status": "error", "healing_intent_created": False} - } - } + if current_time - last_update < self._update_throttle_ms: + logger.debug(f"Throttling update for {component_id}") + return False - # Return empty DataFrame on error - error_df = pd.DataFrame(columns=["Error", "Message"]).from_records([ - {"Error": "Analysis Failed", "Message": str(e)} - ]) + # Update tracking + self._component_states[component_id] = new_state + self._last_update_times[component_id] = current_time - return error_html, error_html, error_html, error_dict, error_df - -# =========================================== -# IMPORT MODULAR COMPONENTS - FIXED: Added MockEnhancedROICalculator -# =========================================== -def import_components() -> Dict[str, Any]: - """Safely import all components with proper error handling - FIXED: Added mock ROI calculator""" - components = { - "all_available": False, - "error": None, - "get_styles": lambda: "", - "show_boundaries": settings.show_boundaries, - } + return True - try: - logger.info("Starting component import...") - - # First, import gradio - import gradio as gr - components["gr"] = gr - - # Import UI styles - from ui.styles import get_styles - components["get_styles"] = get_styles - - # Import UI components - IMPORTANT: Now includes create_realism_panel AND update_performance_metrics - from ui.components import ( - create_header, create_status_bar, create_tab1_incident_demo, - create_tab2_business_roi, create_tab3_enterprise_features, - create_tab4_audit_trail, create_tab5_learning_engine, - create_footer, create_realism_panel, update_performance_metrics # Added update_performance_metrics - ) - - components.update({ - "create_header": create_header, - "create_status_bar": create_status_bar, - "create_tab1_incident_demo": create_tab1_incident_demo, - "create_tab2_business_roi": create_tab2_business_roi, - "create_tab3_enterprise_features": create_tab3_enterprise_features, - "create_tab4_audit_trail": create_tab4_audit_trail, - "create_tab5_learning_engine": create_tab5_learning_engine, - "create_footer": create_footer, - "create_realism_panel": create_realism_panel, - "update_performance_metrics": update_performance_metrics # Added for dynamic metrics - }) - - # Import scenarios - from demo.scenarios import INCIDENT_SCENARIOS - components["INCIDENT_SCENARIOS"] = INCIDENT_SCENARIOS - - # Try to import TrueARFOrchestrator (renamed for version consistency) - try: - from core.true_arf_orchestrator import TrueARFOrchestrator - components["DemoOrchestrator"] = TrueARFOrchestrator - except ImportError: - # Fallback to old name for compatibility during transition - try: - from core.true_arf_orchestrator import TrueARF337Orchestrator - components["DemoOrchestrator"] = TrueARF337Orchestrator - logger.warning("āš ļø Using TrueARF337Orchestrator - rename to TrueARFOrchestrator for version consistency") - except ImportError: - # Fallback to real ARF integration - try: - from core.real_arf_integration import RealARFIntegration - components["DemoOrchestrator"] = RealARFIntegration - except ImportError: - # Create a minimal mock orchestrator - class MockOrchestrator: - async def analyze_incident(self, scenario_name, scenario_data): - return { - "status": "mock", - "scenario": scenario_name, - "message": "Mock analysis (no real ARF available)", - "boundary_note": "OSS advisory mode - execution requires Enterprise", - "demo_display": { - "real_arf_version": "mock", - "true_oss_used": False, - "enterprise_simulated": True, - "architectural_boundary": "OSS advises → Enterprise would execute" - } - } - async def execute_healing(self, scenario_name, mode="autonomous"): - return { - "status": "mock", - "scenario": scenario_name, - "message": "Mock execution (no real ARF available)", - "boundary_note": "Simulated Enterprise execution - real execution requires infrastructure", - "enterprise_features_used": ["simulated_execution", "mock_rollback", "demo_mode"] - } - components["DemoOrchestrator"] = MockOrchestrator - - # FIXED: EnhancedROICalculator with proper mock fallback - try: - from core.calculators import EnhancedROICalculator - components["EnhancedROICalculator"] = EnhancedROICalculator() - logger.info("āœ… Real EnhancedROICalculator loaded") - except ImportError: - # Create comprehensive mock ROI calculator - class MockEnhancedROICalculator: - """Mock ROI calculator for demo purposes - FIXED to prevent KeyError""" - - def calculate_comprehensive_roi(self, scenario_name=None, monthly_incidents=15, team_size=5, **kwargs): - """Calculate comprehensive ROI metrics with realistic mock data""" - from datetime import datetime - - # Mock ROI calculation with realistic values - impact_map = { - "Cache Miss Storm": 8500, - "Database Connection Pool Exhaustion": 4200, - "Kubernetes Memory Leak": 5500, - "API Rate Limit Storm": 3800, - "Network Partition": 12000, - "Storage I/O Saturation": 6800 - } - - impact_per_incident = impact_map.get(scenario_name or "Cache Miss Storm", 5000) - annual_impact = impact_per_incident * monthly_incidents * 12 - potential_savings = int(annual_impact * 0.82) - enterprise_cost = 625000 - roi_multiplier = round(potential_savings / enterprise_cost, 1) - payback_months = round((enterprise_cost / (potential_savings / 12)), 1) - - return { - "status": "āœ… Calculated Successfully", - "scenario": scenario_name or "Cache Miss Storm", - "timestamp": datetime.now().isoformat(), - "calculator": "MockEnhancedROICalculator", - "summary": { - "your_annual_impact": f"${annual_impact:,}", - "potential_savings": f"${potential_savings:,}", - "enterprise_cost": f"${enterprise_cost:,}", - "roi_multiplier": f"{roi_multiplier}Ɨ", - "payback_months": f"{payback_months}", - "annual_roi_percentage": f"{int((potential_savings - enterprise_cost) / enterprise_cost * 100)}%", - "boundary_context": "Based on OSS analysis + simulated Enterprise execution" - }, - "breakdown": { - "direct_cost_savings": f"${int(potential_savings * 0.7):,}", - "productivity_gains": f"${int(potential_savings * 0.2):,}", - "risk_reduction": f"${int(potential_savings * 0.1):,}" - }, - "annual_projection": { - "incidents_prevented": monthly_incidents * 12, - "annual_savings": f"${potential_savings:,}", - "roi": f"{roi_multiplier}Ɨ" - }, - "notes": [ - "šŸ“Š ROI calculation using mock data", - "šŸ’” Real enterprise ROI includes additional factors", - "šŸ”’ Full ROI requires Enterprise edition", - f"šŸ“ˆ Based on {monthly_incidents} incidents/month" - ] - } - - def get_roi_visualization_data(self): - """Get data for ROI visualization""" - return { - "labels": ["Direct Savings", "Productivity", "Risk Reduction", "Upsell"], - "values": [65, 20, 10, 5], - "colors": ["#10b981", "#3b82f6", "#8b5cf6", "#f59e0b"] - } - - components["EnhancedROICalculator"] = MockEnhancedROICalculator() - logger.info("āœ… Mock EnhancedROICalculator created (preventing KeyError)") - - # Try to import visualization engine + def _states_equal(self, state1: Dict, state2: Dict) -> bool: + """Deep compare two states""" try: - from core.visualizations import EnhancedVisualizationEngine - components["EnhancedVisualizationEngine"] = EnhancedVisualizationEngine() - except ImportError: - class MockVisualizationEngine: - def create_executive_dashboard(self, data=None, is_real_arf=True): - return create_empty_plot("Executive Dashboard", is_real_arf) - def create_telemetry_plot(self, scenario_name, anomaly_detected=True, is_real_arf=True): - return create_simple_telemetry_plot(scenario_name, is_real_arf) - def create_impact_gauge(self, scenario_name, is_real_arf=True): - return create_simple_impact_plot(scenario_name, is_real_arf) - def create_timeline_comparison(self, is_real_arf=True): - return create_empty_plot("Timeline Comparison", is_real_arf) - components["EnhancedVisualizationEngine"] = MockVisualizationEngine() - - components["all_available"] = True - components["error"] = None - logger.info("āœ… Successfully imported all modular components including update_performance_metrics") - - except Exception as e: - logger.error(f"āŒ IMPORT ERROR: {e}") - components["error"] = str(e) - components["all_available"] = False - - # Ensure we have minimal components - if "gr" not in components: - import gradio as gr - components["gr"] = gr - - if "INCIDENT_SCENARIOS" not in components: - components["INCIDENT_SCENARIOS"] = { - "Cache Miss Storm": { - "component": "Redis Cache Cluster", - "severity": "HIGH", - "business_impact": {"revenue_loss_per_hour": 8500}, - "boundary_note": "OSS analysis only - execution requires Enterprise" - } - } - - # Ensure EnhancedROICalculator exists - if "EnhancedROICalculator" not in components: - class MinimalROICalculator: - def calculate_comprehensive_roi(self, **kwargs): - return { - "status": "āœ… Minimal ROI Calculation", - "summary": {"roi_multiplier": "5.2Ɨ"} - } - components["EnhancedROICalculator"] = MinimalROICalculator() - - # Ensure update_performance_metrics exists - if "update_performance_metrics" not in components: - def fallback_performance_metrics(scenario_name: str): - """Fallback function if the real one fails""" - logger.warning(f"Using fallback performance metrics for {scenario_name}") - return ( - """
-
ā±ļø
-
-

Detection Time

-

42s

-

↓ 90% faster than average

-
-
""", - """
-
⚔
-
-

Mean Time to Resolve

-

14m

-

↓ 70% faster than manual

-
-
""", - """
-
šŸ¤–
-
-

Auto-Heal Rate

-

78.9%

-

↑ 5.0Ɨ industry average

-
-
""", - """
-
šŸ’°
-
-

Cost Saved

-

$7.2K

-

Per incident avoided

-
-
""" - ) - components["update_performance_metrics"] = fallback_performance_metrics - - return components - -_components = None -_audit_manager = None + return json.dumps(state1, sort_keys=True) == json.dumps(state2, sort_keys=True) + except: + # Fallback for non-serializable states + return str(state1) == str(state2) + + def clear_component_state(self, component_id: str): + """Clear cached state for component""" + if component_id in self._component_states: + del self._component_states[component_id] + if component_id in self._last_update_times: + del self._last_update_times[component_id] + + def get_optimization_stats(self) -> Dict: + """Get optimization statistics""" + return { + "tracked_components": len(self._component_states), + "throttle_ms": self._update_throttle_ms, + "memory_usage_kb": sys.getsizeof(self._component_states) / 1024 + } -def get_components() -> Dict[str, Any]: - """Lazy load components singleton""" - global _components - if _components is None: - _components = import_components() - return _components +# Global optimizer instance +update_optimizer = UpdateOptimizer() # =========================================== -# AUDIT TRAIL MANAGER - FIXED: Returns DataFrames instead of HTML +# ENHANCED CSS LOADING WITH MODERN INTEGRATION # =========================================== -class AuditTrailManager: - """Enhanced audit trail manager with boundary tracking - FIXED to return DataFrames""" +def load_css_files() -> str: + """Load and optimize CSS files with modern components integration""" + css_parts = [] + + # Start performance measurement + start_time = time.time() + + # Load base design tokens + base_css = f""" + :root {{ + /* Design Tokens */ + {chr(10).join([f'--color-{k.replace("_", "-")}: {v};' for k, v in DesignTokens.COLORS.items()])} + {chr(10).join([f'--font-{k.replace("_", "-")}: {v};' for k, v in DesignTokens.TYPOGRAPHY.items()])} + {chr(10).join([f'--radius-{k.replace("_", "-")}: {v};' for k, v in DesignTokens.BORDERS.items()])} + {chr(10).join([f'--shadow-{k.replace("_", "-")}: {v};' for k, v in DesignTokens.SHADOWS.items()])} + {chr(10).join([f'--transition-{k.replace("_", "-")}: {v};' for k, v in DesignTokens.TRANSITIONS.items()])} + }} - def __init__(self): - self.executions = [] - self.incidents = [] - self.boundary_crossings = [] - self.max_items = settings.max_history_items - - def add_execution(self, scenario_name: str, mode: str, result: Dict): - """Add an execution record""" - record = { - "timestamp": datetime.datetime.now().isoformat(), - "scenario": scenario_name, - "mode": mode, - "result": result, - "boundary_context": "Enterprise execution simulated" if "simulated" in str(result) else "OSS advisory" - } - self.executions.insert(0, record) - if len(self.executions) > self.max_items: - self.executions = self.executions[:self.max_items] - - # Track boundary crossing - if "enterprise" in mode.lower(): - self.boundary_crossings.append({ - "timestamp": record["timestamp"], - "from": "OSS", - "to": "Enterprise", - "action": scenario_name - }) - - logger.info(f"šŸ“ Execution recorded: {scenario_name} ({mode})") - return record - - def add_incident(self, scenario_name: str, analysis_result: Dict): - """Add an incident analysis record""" - record = { - "timestamp": datetime.datetime.now().isoformat(), - "scenario": scenario_name, - "analysis": analysis_result, - "boundary_context": analysis_result.get("boundary_note", "OSS analysis") - } - self.incidents.insert(0, record) - if len(self.incidents) > self.max_items: - self.incidents = self.incidents[:self.max_items] - - logger.info(f"šŸ“ Incident analysis recorded: {scenario_name}") - return record + /* Base Styles */ + * {{ + box-sizing: border-box; + }} - def get_execution_dataframe(self) -> pd.DataFrame: - """ - FIXED: Robust pandas DataFrame creation for Gradio DataFrame component - """ + body {{ + font-family: var(--font-family); + color: var(--color-neutral-900); + background: var(--color-background-light); + margin: 0; + padding: 0; + line-height: 1.5; + }} + + [data-theme="dark"] {{ + color: var(--color-neutral-100); + background: var(--color-background-dark); + }} + + /* Container */ + .container {{ + width: 100%; + max-width: 1200px; + margin: 0 auto; + padding: 0 1rem; + }} + """ + + css_parts.append(base_css) + + # Load modern components CSS if available + if MODERN_COMPONENTS_AVAILABLE and is_feature_enabled('modern_ui'): try: - if not self.executions: - # Return empty DataFrame with correct columns - return pd.DataFrame(columns=[ - "Execution ID", "Scenario", "Status", "Mode", - "Start Time", "End Time", "Duration", "Boundary" - ]) - - # Build DataFrame from executions with safe access - data = [] - for i, execution in enumerate(self.executions): - try: - # Safe access to nested dictionaries - result = execution.get("result", {}) - - # Execution ID - safe extraction with fallback - exec_id = result.get("execution_id", f"exec_{i:03d}") - - # Status determination with multiple fallbacks - status_text = "Unknown" - if isinstance(result, dict): - status_lower = str(result.get("status", "")).lower() - if "success" in status_lower: - status_text = "Success" - elif "failed" in status_lower or "error" in status_lower: - status_text = "Failed" - else: - # Check if there's an error key - if result.get("error"): - status_text = "Failed" - else: - status_text = "Success" - - # Mode extraction - mode = execution.get("mode", "unknown") - - # Scenario extraction - scenario = execution.get("scenario", "Unknown") - - # Timestamp formatting with validation - timestamp = execution.get("timestamp", "") - start_time = "" - if timestamp and len(timestamp) > 10: - try: - # Format: YYYY-MM-DD HH:MM:SS - start_time = timestamp[:19] - except Exception: - start_time = timestamp # Fallback to raw string - - # End time extraction from telemetry - end_time = "" - telemetry = result.get("telemetry", {}) - if telemetry: - end_timestamp = telemetry.get("end_time", "") - if end_timestamp and len(end_timestamp) > 10: - try: - end_time = end_timestamp[:19] - except Exception: - end_time = end_timestamp # Fallback - - # Duration - mock or extract from execution - duration = "12m" # Default mock duration - if telemetry and "estimated_duration" in telemetry: - duration = telemetry.get("estimated_duration", "12m") - - # Boundary context - boundary = execution.get("boundary_context", "Unknown") - - data.append({ - "Execution ID": exec_id, - "Scenario": scenario, - "Status": status_text, - "Mode": mode, - "Start Time": start_time, - "End Time": end_time, - "Duration": duration, - "Boundary": boundary - }) - - except Exception as row_error: - logger.warning(f"Error processing execution row {i}: {row_error}") - # Add error row for debugging - data.append({ - "Execution ID": f"error_{i}", - "Scenario": "Error", - "Status": "Failed", - "Mode": "error", - "Start Time": datetime.datetime.now().isoformat()[:19], - "End Time": "", - "Duration": "0m", - "Boundary": "Error processing" - }) - - if not data: - logger.warning("No valid execution data found, returning empty DataFrame") - return pd.DataFrame(columns=[ - "Execution ID", "Scenario", "Status", "Mode", - "Start Time", "End Time", "Duration", "Boundary" - ]) - - # Create DataFrame - df = pd.DataFrame(data) - - # Safe sorting - only if we have valid Start Time data - if not df.empty and "Start Time" in df.columns: - # Check if Start Time column has valid data - valid_times = df["Start Time"].apply( - lambda x: isinstance(x, str) and len(x) > 0 and x != "None" - ) - - if valid_times.any(): - try: - # Sort by time (newest first) - df = df.sort_values("Start Time", ascending=False) - except Exception as sort_error: - logger.warning(f"Could not sort DataFrame: {sort_error}") - # Keep unsorted if sorting fails - else: - logger.debug("No valid timestamps for sorting") - - logger.info(f"āœ… Created execution DataFrame with {len(df)} rows") - return df - + # Import the CSS generation function + from ui.modern_components import create_component_styles + modern_css = create_component_styles() + css_parts.append(modern_css) + logger.info("āœ… Modern component styles loaded") except Exception as e: - logger.error(f"āŒ Error creating execution DataFrame: {e}") - # Return informative error DataFrame - error_df = pd.DataFrame(columns=[ - "Error", "Message", "Timestamp" - ]).from_records([{ - "Error": "DataFrame Creation Failed", - "Message": str(e), - "Timestamp": datetime.datetime.now().isoformat()[:19] - }]) - return error_df - - def get_incident_dataframe(self) -> pd.DataFrame: - """ - FIXED: Robust pandas DataFrame creation for Gradio DataFrame component - """ - try: - if not self.incidents: - # Return empty DataFrame with correct columns - return pd.DataFrame(columns=[ - "Scenario", "Status", "Boundary", "Time", - "Confidence", "Action", "Target" - ]) - - # Build DataFrame from incidents with safe access - data = [] - for i, incident in enumerate(self.incidents): - try: - # Safe extraction of basic fields - scenario = incident.get("scenario", "Unknown") - boundary = incident.get("boundary_context", "OSS analysis") - - # Analysis data extraction - analysis = incident.get("analysis", {}) - - # Status determination - status = "Analyzed" - if isinstance(analysis, dict): - analysis_status = analysis.get("status", "").lower() - if analysis_status: - status = analysis_status.capitalize() - else: - # Fallback status determination - if analysis.get("error"): - status = "Error" - elif analysis.get("analysis") or analysis.get("oss_analysis"): - status = "Success" - - # Timestamp formatting - timestamp = incident.get("timestamp", "") - time_display = "" - if timestamp and len(timestamp) > 10: - try: - # Extract HH:MM:SS - time_display = timestamp[11:19] - except Exception: - time_display = timestamp[:8] if len(timestamp) >= 8 else timestamp - - # Extract healing intent details with multiple fallback paths - confidence = 0.85 # Default confidence - action = "Analysis" - target = "system" - - # Try multiple paths to find healing intent - healing_intent = None - - # Path 1: oss_analysis -> analysis -> decision - oss_analysis = analysis.get("oss_analysis", {}) - if isinstance(oss_analysis, dict): - oss_analysis_inner = oss_analysis.get("analysis", {}) - if isinstance(oss_analysis_inner, dict): - healing_intent = oss_analysis_inner.get("decision", {}) - - # Path 2: direct analysis -> decision - if not healing_intent and isinstance(analysis.get("analysis", {}), dict): - healing_intent = analysis["analysis"].get("decision", {}) - - # Path 3: direct healing_intent - if not healing_intent: - healing_intent = analysis.get("healing_intent", {}) - - if healing_intent and isinstance(healing_intent, dict): - confidence = healing_intent.get("confidence", 0.85) - action = healing_intent.get("action", "Analysis") - target = healing_intent.get("target", "system") - - # Format confidence as percentage - confidence_display = f"{confidence * 100:.1f}%" - - data.append({ - "Scenario": scenario, - "Status": status, - "Boundary": boundary, - "Time": time_display, - "Confidence": confidence_display, - "Action": action[:50], # Limit action length - "Target": target[:30] # Limit target length - }) - - except Exception as row_error: - logger.warning(f"Error processing incident row {i}: {row_error}") - # Add error row for debugging - data.append({ - "Scenario": "Error", - "Status": "Failed", - "Boundary": "Error processing", - "Time": datetime.datetime.now().isoformat()[11:19], - "Confidence": "0.0%", - "Action": "Error", - "Target": "system" - }) - - if not data: - logger.warning("No valid incident data found, returning empty DataFrame") - return pd.DataFrame(columns=[ - "Scenario", "Status", "Boundary", "Time", - "Confidence", "Action", "Target" - ]) + logger.warning(f"Could not load modern component styles: {e}") + + # Load responsive utilities if enabled + if is_feature_enabled('responsive_design'): + responsive_css = """ + /* Responsive Utilities */ + @media (max-width: 768px) { + .container { + padding: 0 0.75rem; + } - # Create DataFrame - df = pd.DataFrame(data) + .grid-cols-1 { + grid-template-columns: 1fr !important; + } - # Safe sorting - only if we have valid Time data - if not df.empty and "Time" in df.columns: - # Check if Time column has valid data - valid_times = df["Time"].apply( - lambda x: isinstance(x, str) and len(x) > 0 and x != "None" - ) - - if valid_times.any(): - try: - # Sort by time (newest first) - df = df.sort_values("Time", ascending=False) - except Exception as sort_error: - logger.warning(f"Could not sort incident DataFrame: {sort_error}") - # Keep unsorted if sorting fails - else: - logger.debug("No valid timestamps for sorting in incident DataFrame") + .md\\:grid-cols-2 { + grid-template-columns: 1fr !important; + } - logger.info(f"āœ… Created incident DataFrame with {len(df)} rows") - return df + .md\\:grid-cols-3 { + grid-template-columns: 1fr !important; + } - except Exception as e: - logger.error(f"āŒ Error creating incident DataFrame: {e}") - # Return informative error DataFrame - error_df = pd.DataFrame(columns=[ - "Error", "Message", "Timestamp" - ]).from_records([{ - "Error": "DataFrame Creation Failed", - "Message": str(e), - "Timestamp": datetime.datetime.now().isoformat()[:19] - }]) - return error_df - - def get_execution_table_html(self): - """Legacy HTML method for backward compatibility""" - if not self.executions: - return """ -
-
šŸ“­
-

No executions yet

-

Run scenarios to see execution history

-
- """ + .md\\:grid-cols-4 { + grid-template-columns: 1fr !important; + } + } - rows = [] - for i, exec in enumerate(self.executions[:10]): - status = "āœ…" if "success" in exec["result"].get("status", "").lower() else "āš ļø" - boundary = exec["boundary_context"] - boundary_color = "#10b981" if "OSS" in boundary else "#8b5cf6" + @media (hover: none) and (pointer: coarse) { + .btn, button, [role="button"] { + min-height: 44px; + min-width: 44px; + padding: 12px 20px; + } - rows.append(f""" - - - {status} {exec["scenario"]} - - - {exec["mode"]} - - -
- {boundary} -
- - - {exec["timestamp"][11:19]} - - - """) - - return f""" -
- - - - - - - - - - - {''.join(rows)} - -
ScenarioModeBoundaryTime
-
+ input, select, textarea { + font-size: 16px; + padding: 12px; + } + } """ - - def get_incident_table_html(self): - """Legacy HTML method for backward compatibility""" - if not self.incidents: - return """ -
-
šŸ“­
-

No incidents analyzed yet

-

Run OSS analysis to see incident history

-
- """ + css_parts.append(responsive_css) + + # Load dark mode enhancements + if is_feature_enabled('dark_mode'): + dark_mode_css = f""" + /* Dark Mode Enhancements */ + [data-theme="dark"] {{ + color-scheme: dark; + }} - rows = [] - for i, incident in enumerate(self.incidents[:10]): - scenario = incident["scenario"] - analysis = incident["analysis"] - boundary = incident["boundary_context"] - boundary_color = "#10b981" if "OSS" in boundary else "#8b5cf6" - - rows.append(f""" - - - {scenario} - - - {analysis.get('status', 'analyzed')} - - -
- {boundary} -
- - - {incident["timestamp"][11:19]} - - - """) + [data-theme="dark"] .gradio-container {{ + background: var(--color-background-dark) !important; + }} - return f""" -
- - - - - - - - - - - {''.join(rows)} - -
ScenarioStatusBoundaryTime
-
+ /* Smooth theme transitions */ + * {{ + transition: background-color var(--transition-normal), + border-color var(--transition-normal), + color var(--transition-normal); + }} """ - - def clear(self): - """Clear all audit trails""" - self.executions = [] - self.incidents = [] - self.boundary_crossings = [] - logger.info("🧹 Audit trail cleared") - - def export_json(self): - """Export audit trail as JSON""" - return { - "executions": self.executions, - "incidents": self.incidents, - "boundary_crossings": self.boundary_crossings, - "export_time": datetime.datetime.now().isoformat(), - "version": "3.3.9", - "architecture": "OSS advises → Enterprise executes" + css_parts.append(dark_mode_css) + + # Load animations if enabled + if is_feature_enabled('loading_animations'): + animations_css = """ + /* Loading Animations */ + .loading-state { + position: relative; + overflow: hidden; } - -def get_audit_manager() -> AuditTrailManager: - """Lazy load audit manager singleton""" - global _audit_manager - if _audit_manager is None: - _audit_manager = AuditTrailManager() - return _audit_manager - -# =========================================== -# HELPER FUNCTIONS -# =========================================== -def get_scenario_impact(scenario_name: str) -> float: - """Get average impact for a given scenario""" - impact_map = { - "Cache Miss Storm": 8500, - "Database Connection Pool Exhaustion": 4200, - "Kubernetes Memory Leak": 5500, - "API Rate Limit Storm": 3800, - "Network Partition": 12000, - "Storage I/O Saturation": 6800 - } - return impact_map.get(scenario_name, 5000) - -def extract_roi_multiplier(roi_result: Dict) -> float: - """Extract ROI multiplier from EnhancedROICalculator result""" - try: - if "summary" in roi_result and "roi_multiplier" in roi_result["summary"]: - roi_str = roi_result["summary"]["roi_multiplier"] - if "Ɨ" in roi_str: - return float(roi_str.replace("Ɨ", "")) - return float(roi_str) - return 5.2 - except Exception as e: - logger.warning(f"Failed to extract ROI multiplier: {e}") - return 5.2 - -# =========================================== -# SURGICAL FIX: update_scenario_display() - ENHANCED WITH REALISM PANEL -# =========================================== -def update_scenario_display(scenario_name: str) -> tuple: - """ - ENHANCED: Returns Plotly figures AND realism panel - Returns 5 values: (scenario_card_html, telemetry_fig, impact_fig, timeline_fig, realism_html) - """ - components = get_components() - scenarios = components["INCIDENT_SCENARIOS"] - - scenario = scenarios.get(scenario_name, { - "component": "Unknown System", - "severity": "MEDIUM", - "business_impact": {"revenue_loss_per_hour": 5000}, - "boundary_note": "Scenario not found" - }) - - # Create scenario card HTML (MODERN: Use Card component if available) - if get_feature_flags().get('modern_ui', False) and MODERN_UI_AVAILABLE: - # Use modern Card component - scenario_card_html = Card.create( - title=scenario_name, - content=f""" -
-
-
- {scenario["severity"]} SEVERITY -
-
- {scenario["component"]} -
-
- -
- Boundary Context: {scenario.get('boundary_note', 'OSS analyzes, Enterprise executes')} -
-
- """, - footer=f"Revenue Impact: ${scenario['business_impact'].get('revenue_loss_per_hour', get_scenario_impact(scenario_name)):,}/hour" - ) - else: - # Legacy scenario card - severity_colors = { - "HIGH": "#ef4444", - "MEDIUM": "#f59e0b", - "LOW": "#10b981" + + .loading-state::after { + content: ''; + position: absolute; + top: 0; + left: -100%; + width: 100%; + height: 100%; + background: linear-gradient( + 90deg, + transparent, + rgba(255, 255, 255, 0.2), + transparent + ); + animation: shimmer 1.5s infinite; } - severity_color = severity_colors.get(scenario["severity"], "#64748b") - impact = scenario["business_impact"].get("revenue_loss_per_hour", get_scenario_impact(scenario_name)) + @keyframes shimmer { + 0% { left: -100%; } + 100% { left: 100%; } + } - scenario_card_html = f""" -
- -
-
-

- {scenario_name} -

-
-
- {scenario["severity"]} SEVERITY -
-
- {scenario["component"]} -
-
-
- -
-
- ${impact:,} -
-
- Revenue Loss/Hour -
-
-
- - -
-
- Business Impact Analysis -
-
-
-
45 min
-
Without ARF
-
-
-
12 min
-
With ARF
-
-
-
${int(impact * 0.85):,}
-
Savings
-
-
-
- - -
- Boundary Context: {scenario.get('boundary_note', 'OSS analyzes, Enterprise executes')} -
-
+ @keyframes bounce { + 0%, 100% { transform: translateY(0); } + 50% { transform: translateY(-10px); } + } + + .animate-bounce { + animation: bounce 1s infinite; + } """ + css_parts.append(animations_css) - # Get visualizations as Plotly figures (ENHANCED) - telemetry_fig = create_simple_telemetry_plot(scenario_name, settings.use_true_arf) - impact_fig = create_simple_impact_plot(scenario_name, settings.use_true_arf) - timeline_fig = create_empty_plot(f"Timeline: {scenario_name}", settings.use_true_arf) + # Combine all CSS + css_content = "\n".join(css_parts) - # ============ NEW: Create realism panel ============ - try: - # Use the imported create_realism_panel function - realism_html = components["create_realism_panel"](scenario, scenario_name) - except (ImportError, KeyError): - # Fallback if realism function isn't available yet - realism_html = """ -
-
šŸ”§
-

Realism Panel Loading...

-

- Trade-offs, risk assessments, and ranked actions will appear here -

-
- """ - - logger.info(f"āœ… Updated scenario display for {scenario_name} with realism panel") + # Check performance budget + is_valid, message = PerformanceBudget.check_css_budget(css_content) + if not is_valid: + logger.warning(f"CSS budget issue: {message}") - # ============ CHANGE HERE: Add realism_html to return tuple ============ - return scenario_card_html, telemetry_fig, impact_fig, timeline_fig, realism_html - -# =========================================== -# ENHANCED: Combined update function for scenario display + performance metrics -# =========================================== - -def update_scenario_display_with_metrics(scenario_name: str) -> tuple: - """Combined update function - doctrinally compliant""" - # Get scenario display components (5 outputs) - scenario_card, telemetry_fig, impact_fig, timeline_fig, _ = update_scenario_display(scenario_name) + # Track performance + load_time = (time.time() - start_time) * 1000 + telemetry.track_performance("css_loading", load_time) - # Get doctrinally compliant performance metrics (4 outputs) - components = get_components() - detection_time, recall_quality, confidence_score, sequencing_stage = components["update_performance_metrics"](scenario_name) + logger.info(f"āœ… CSS loaded: {len(css_content)/1024:.1f}KB in {load_time:.0f}ms") - return (scenario_card, telemetry_fig, impact_fig, timeline_fig, - detection_time, recall_quality, confidence_score, sequencing_stage) # Changed + return css_content # =========================================== -# FIXED EXECUTION FUNCTION - Returns DataFrames +# MODERN UI COMPONENTS WITH ENHANCEMENTS # =========================================== -def execute_enterprise_healing(scenario_name, approval_required, mcp_mode_value): - """ - MINIMAL FIX: Returns proper data types matching UI expectations - FIXED: Returns DataFrame instead of HTML for execution table - """ - import gradio as gr - - components = get_components() - installation = get_installation_status() - boundaries = BoundaryManager.get_system_boundaries() - - logger.info(f"⚔ Executing enterprise healing for: {scenario_name}") - - # Check if Enterprise is actually available - is_real_enterprise = installation["enterprise_installed"] - is_simulated = not is_real_enterprise - - # Get scenario impact - scenario = components["INCIDENT_SCENARIOS"].get(scenario_name, {}) - impact = scenario.get("business_impact", {}) - revenue_loss = impact.get("revenue_loss_per_hour", get_scenario_impact(scenario_name)) - savings = int(revenue_loss * 0.85) - - # Create approval display HTML - if approval_required: - approval_display = """ -
-
ā³
-

- HUMAN APPROVAL REQUIRED -

-

- Based on your safety settings, this execution requires human approval. -

-
- """ - else: - approval_display = """ -
-
⚔
-

- AUTONOMOUS APPROVAL GRANTED -

-

- Proceeding with autonomous execution. -

-
- """ - - # Execute healing (async) - @AsyncRunner.async_to_sync - async def execute_async(): - try: - orchestrator = components["DemoOrchestrator"]() - execution_result = await orchestrator.execute_healing(scenario_name, "autonomous") - - # Add to audit trail - get_audit_manager().add_execution(scenario_name, "enterprise_autonomous", execution_result) - - return execution_result - - except Exception as e: - logger.error(f"Execution failed: {e}") - return { - "status": "failed", - "error": str(e), - "boundary_note": "Execution boundary reached" - } - - execution_result = execute_async() - - # Create results dict for JSON display - if is_real_enterprise: - enterprise_results = { - "demo_mode": "Real Enterprise", - "scenario": scenario_name, - "arf_version": boundaries["enterprise"]["version"], - "execution_mode": "autonomous" if not approval_required else "human_approved", - "results": { - "recovery_time": "12 minutes", - "cost_saved": f"${savings:,}", - "users_protected": "45,000" - }, - "safety_features": [ - "Rollback guarantee: 100%", - "Atomic execution", - "MCP validation" - ] - } - else: - enterprise_results = { - "demo_mode": "Enterprise Simulation", - "scenario": scenario_name, - "arf_version": boundaries["enterprise"]["version"], - "execution_mode": "simulated_autonomous", - "results": { - "recovery_time": "12 minutes (simulated)", - "cost_saved": f"${savings:,} (simulated)", - "users_protected": "45,000 (simulated)" - }, - "safety_features": [ - "Rollback guarantee: 100% (simulated)", - "Atomic execution (simulated)" - ] - } - - # Get execution DataFrame (FIXED: Returns DataFrame instead of HTML) - execution_df = get_audit_manager().get_execution_dataframe() +class ModernUI: + """Modern UI component wrappers with validation and telemetry""" - return approval_display, enterprise_results, execution_df - -# =========================================== -# FIXED ROI FUNCTION - Enhanced for Gradio -# =========================================== -def calculate_roi(scenario_name, monthly_incidents, team_size): - """ - ENHANCED: Returns (JSON/dict, Plotly figure) for ROI calculation with Gradio compatibility - """ - components = get_components() + @staticmethod + def create_header(version: str) -> str: + """Create modern header with validation""" + # Validate version + is_valid, safe_version = InputValidator.validate_numeric_input(version.replace(".", ""), 100, 999) + version_display = f"{int(safe_version)//100}.{int(safe_version)%100}" if is_valid else "3.3.9" + + # Track usage + telemetry.track_user_interaction("view_header", "header") + + return f""" +
+
+

+ šŸš€ Agentic Reliability Framework v{version_display} +

+ +

+ OSS advises → Enterprise executes • Enhanced with Modern Psychological Components +

+ +
+ +
+ āœ… + OSS Advisory + Apache 2.0 +
+ + +
+ → +
+ + +
+ šŸ¢ + Enterprise Execution + Commercial +
+ + +
+ Modern UI v{version_display} +
+ + +
+ 🧠 Psychological UX +
+
+ + +
+ + + System Ready + + • + Modern Components: {'āœ… Active' if MODERN_COMPONENTS_AVAILABLE else 'āš ļø Fallback'} + • + Performance Budget: OK +
+
+
+ """ - try: - # Try to use real ROI calculator - calculator = components["EnhancedROICalculator"] - roi_result = calculator.calculate_comprehensive_roi( - scenario_name=scenario_name, - monthly_incidents=monthly_incidents, - team_size=team_size - ) - except Exception as e: - logger.warning(f"ROI calculation failed, using mock: {e}") - # Mock ROI calculation - impact_per_incident = get_scenario_impact(scenario_name) - annual_impact = impact_per_incident * monthly_incidents * 12 - potential_savings = int(annual_impact * 0.82) - enterprise_cost = 625000 - roi_multiplier = round(potential_savings / enterprise_cost, 1) - payback_months = round((enterprise_cost / (potential_savings / 12)), 1) - - roi_result = { - "status": "āœ… Calculated Successfully", - "summary": { - "your_annual_impact": f"${annual_impact:,}", - "potential_savings": f"${potential_savings:,}", - "enterprise_cost": f"${enterprise_cost:,}", - "roi_multiplier": f"{roi_multiplier}Ɨ", - "payback_months": f"{payback_months}", - "annual_roi_percentage": f"{int((potential_savings - enterprise_cost) / enterprise_cost * 100)}%", - "boundary_context": "Based on OSS analysis + simulated Enterprise execution" - }, - "boundary_note": "ROI calculation includes OSS advisory value and simulated Enterprise execution benefits" + @staticmethod + def create_metric_card(value: str, label: str, icon: str = "", trend: str = "") -> str: + """Create validated metric card with modern styling""" + # Sanitize inputs + safe_value = InputValidator.sanitize_html(value) + safe_label = InputValidator.sanitize_html(label) + + # Track usage + telemetry.track_user_interaction("metric_card_viewed", label) + + trend_classes = { + "up": "text-green-600 dark:text-green-400", + "down": "text-red-600 dark:text-red-400", + "neutral": "text-gray-600 dark:text-gray-400" } + + trend_icon = {"up": "↗", "down": "ā†˜", "neutral": "→"}.get(trend, "") + trend_class = trend_classes.get(trend, "") + + return f""" +
+ {f'
{icon}
' if icon else ''} +
{safe_value}
+
{safe_label}
+ {f'
{trend_icon}
' if trend else ''} +
+ """ - # Create ROI chart as Plotly figure (ENHANCED for Gradio) - categories = ['Without ARF', 'With ARF', 'Net Savings'] - annual_impact_val = impact_per_incident * monthly_incidents * 12 if 'impact_per_incident' in locals() else 1000000 - potential_savings_val = potential_savings if 'potential_savings' in locals() else 820000 - enterprise_cost_val = enterprise_cost if 'enterprise_cost' in locals() else 625000 - - values = [annual_impact_val, annual_impact_val - potential_savings_val, potential_savings_val - enterprise_cost_val] - - fig = go.Figure(data=[ - go.Bar( - name='Cost', - x=categories, - y=values, - marker_color=['#ef4444', '#10b981', '#8b5cf6'] - ) - ]) - - fig.update_layout( - title={ - 'text': f"ROI Analysis: {scenario_name}", - 'font': dict(size=18, color='#1e293b', family="Arial, sans-serif") - }, - height=400, - plot_bgcolor='white', - paper_bgcolor='white', - showlegend=False, - margin=dict(l=40, r=20, t=60, b=40) - ) - - logger.info(f"āœ… Created ROI plot for {scenario_name}") - - # Return both the dict and the Plotly figure - return roi_result, fig + @staticmethod + def create_scenario_dropdown() -> str: + """Create validated scenario dropdown""" + options_html = "" + for scenario in InputValidator.SCENARIO_WHITELIST: + options_html += f'' + + return f""" +
+ + +

+ Validated scenarios only • Telemetry active +

+
+ + + """ # =========================================== -# CREATE DEMO INTERFACE - UPDATED WITH MODERN UI INTEGRATION +# ENHANCED MAIN APPLICATION # =========================================== -def create_demo_interface(): - """Create demo interface using modular components with boundary awareness and modern UI""" +def create_enhanced_demo_interface(): + """Create enhanced demo interface with modern psychological components""" import gradio as gr + import pandas as pd + import numpy as np + import plotly.graph_objects as go + import plotly.express as px - # Get components - components = get_components() + # Track initialization + telemetry.track_event("app_initialization_started") + start_time = time.time() - # Get feature flags - flags = get_feature_flags() + # Load optimized CSS with modern components + css_content = PerformanceBudget.measure_execution_time(load_css_files, "css_loading")() - # Create interface WITHOUT css parameter (fixes Gradio 6.0 warning) + # Create the main interface with gr.Blocks( - title=f"šŸš€ ARF Investor Demo v3.3.9 - TRUE ARF OSS Integration" - ) as demo: - - # MODERN UI INITIALIZATION - if flags.get('modern_ui', True) and MODERN_UI_AVAILABLE: - try: - # Initialize modern UI with theme support - modern_ui_init = gr.HTML(initialize_modern_ui()) - logger.info("āœ… Modern UI initialized") - except Exception as e: - logger.warning(f"āš ļø Modern UI initialization failed: {e}") - modern_ui_init = gr.HTML("") - else: - modern_ui_init = gr.HTML("") - - # Add dark mode toggle if enabled - if flags.get('dark_mode', True): - dark_mode_toggle = gr.HTML(create_dark_mode_toggle()) - logger.info("āœ… Dark mode toggle added") - - # Header - header_html = components["create_header"]("3.3.9") - - # Status bar with boundary badges - status_html = components["create_status_bar"]() - - - # ============ 5 TABS ============ - with gr.Tabs(elem_classes="tab-nav"): - - # TAB 1: Live Incident Demo - NOW WITH MODERN COMPONENTS - with gr.TabItem("šŸ”„ Live Incident Demo", id="tab1"): - # ===== SURGICAL FIX: SAFE UNPACKING WITH ERROR HANDLING ===== - try: - logger.info("šŸ”§ Extracting Tab1 components with safe unpacking...") - - # Get the raw result tuple - tab1_result = components["create_tab1_incident_demo"]() - - # Debug logging for contract verification - logger.info(f"šŸ“Š Tab1 result type: {type(tab1_result)}") - if hasattr(tab1_result, '__len__'): - logger.info(f"šŸ“Š Tab1 result length: {len(tab1_result)}") - for i, item in enumerate(tab1_result): - item_type = type(item).__name__ if hasattr(item, '__name__') else type(item) - logger.debug(f" Index {i}: {item_type}") - - # MANUAL INDEX-BASED UNPACKING (CONTRACT ENFORCEMENT) - # Indices verified against components.py return statement - scenario_dropdown = tab1_result[0] - historical_panel = tab1_result[1] - scenario_card = tab1_result[2] - telemetry_viz = tab1_result[3] - impact_viz = tab1_result[4] - observation_gate_placeholder = tab1_result[5] - sequencing_panel = tab1_result[6] - workflow_header = tab1_result[7] - detection_process = tab1_result[8] - recall_process = tab1_result[9] - decision_process = tab1_result[10] - oss_section = tab1_result[11] - enterprise_section = tab1_result[12] - oss_btn = tab1_result[13] - enterprise_btn = tab1_result[14] - approval_toggle = tab1_result[15] - mcp_mode = tab1_result[16] - timeline_viz = tab1_result[17] - detection_time = tab1_result[18] - recall_quality = tab1_result[19] # ← CRITICAL: WAS mttr - confidence_score = tab1_result[20] # ← CRITICAL: WAS auto_heal - sequencing_stage = tab1_result[21] # ← CRITICAL: WAS savings - oss_results_display = tab1_result[22] - enterprise_results_display = tab1_result[23] - approval_display = tab1_result[24] - demo_btn = tab1_result[25] # ← CRITICAL: Index 25 MUST be demo_btn - - logger.info("āœ… Tab1 components successfully extracted with correct contract") - - except Exception as e: - logger.error(f"āŒ Tab1 component extraction failed: {e}") - logger.error("šŸ”„ Creating fallback components to maintain system integrity...") - - # FALLBACK CREATION (Minimal viable components) - import gradio as gr - - # Create minimal placeholder components - scenario_dropdown = gr.Dropdown(choices=["Error Mode"], value="Error Mode") - historical_panel = gr.DataFrame(value=[["System in recovery mode"]]) - scenario_card = gr.Markdown("### System Initialization Issue") - telemetry_viz = gr.Plot() - impact_viz = gr.Plot() - observation_gate_placeholder = gr.Markdown("**Observation Gate:** System integrity check") - sequencing_panel = gr.Markdown("**Sequencing:** Initializing...") - workflow_header = gr.Markdown("### Policy Recovery Mode") - detection_process = gr.Textbox(value="DETECTION: ERROR") - recall_process = gr.Textbox(value="RECALL: ERROR") - decision_process = gr.Textbox(value="DECISION: ERROR") - oss_section = gr.Markdown("#### OSS: Unavailable") - enterprise_section = gr.Markdown("#### Enterprise: Unavailable") - oss_btn = gr.Button("Unavailable", variant="secondary") - enterprise_btn = gr.Button("Unavailable", variant="secondary") - approval_toggle = gr.Checkbox(label="Approval: Error", value=False) - mcp_mode = gr.Radio(choices=["Error"], value="Error") - timeline_viz = gr.Plot() - detection_time = gr.Number(value=0) - recall_quality = gr.Number(value=0) # ← CORRECT VARIABLE NAME - confidence_score = gr.Number(value=0) # ← CORRECT VARIABLE NAME - sequencing_stage = gr.Textbox(value="Error") # ← CORRECT VARIABLE NAME - oss_results_display = gr.Markdown("### Results: Unavailable") - enterprise_results_display = gr.Markdown("### Results: Unavailable") - approval_display = gr.Markdown("**Status:** System recovery in progress") - demo_btn = gr.Button("šŸ”„ System Recovery Required", variant="secondary", size="lg") - - logger.warning("āš ļø Using fallback components - full functionality limited") - # ===== END SURGICAL FIX ===== + title="šŸš€ ARF v3.3.9 - Modern Psychological Edition", + css=css_content, + theme=gr.themes.Soft( + primary_hue="blue", + secondary_hue="purple", + neutral_hue="slate" + ), + head=f''' + + + + ''' + ) as demo: # =========================================== - # FIXED: OSS Analysis Button Connection - SIMPLE PASSTHROUGH + # INITIALIZATION # =========================================== - def run_oss_analysis_real_arf(scenario_name: str) -> tuple: - """ - Simple passthrough to run_true_arf_analysis() - The decorator now handles contract preservation - """ - logger.info(f"šŸš€ Running TRUE ARF OSS analysis for: {scenario_name}") - return run_true_arf_analysis(scenario_name) - # Run OSS Analysis - FIXED: Simple passthrough - oss_btn.click( - fn=run_oss_analysis_real_arf, - inputs=[scenario_dropdown], - outputs=[ - detection_process, recall_process, decision_process, - oss_results_display, incident_table - ] - ) + # Dark mode toggle + dark_mode_html = """ +
+ +
+ """ - # Execute Enterprise Healing - FIXED: Now returns DataFrame for execution_table - enterprise_btn.click( - fn=execute_enterprise_healing, - inputs=[scenario_dropdown, approval_toggle, mcp_mode], - outputs=[approval_display, enterprise_results_display, execution_table] - ) + gr.HTML(dark_mode_html) - # Run Complete Demo with boundary progression - @AsyncRunner.async_to_sync - async def run_complete_demo_async(scenario_name): - """Run a complete demo walkthrough with true ARF and boundary awareness""" - # Step 1: Update scenario with metrics - update_result = update_scenario_display_with_metrics(scenario_name) - - # Step 2: Run OSS analysis using TRUE ARF OSS function - oss_result = run_oss_analysis_real_arf(scenario_name) - - # Step 3: Execute Enterprise (simulation) with boundary context - await asyncio.sleep(1) - - scenario = components["INCIDENT_SCENARIOS"].get(scenario_name, {}) - impact = scenario.get("business_impact", {}) - revenue_loss = impact.get("revenue_loss_per_hour", get_scenario_impact(scenario_name)) - savings_amount = int(revenue_loss * 0.85) - - # Get boundary context - boundaries = BoundaryManager.get_system_boundaries() - - # Get orchestrator for execution simulation - orchestrator = components["DemoOrchestrator"]() - execution_result = await orchestrator.execute_healing(scenario_name, "autonomous") - - enterprise_results = { - "demo_mode": "Complete Walkthrough", - "scenario": scenario_name, - "arf_version": "3.3.9", - "true_oss_used": True, - "enterprise_simulated": True, - "boundary_progression": [ - f"1. Incident detected - {boundaries['oss']['label']}", - f"2. OSS analysis completed - {boundaries['oss']['label']}", - f"3. HealingIntent created - {boundaries['oss']['label']}", - f"4. Enterprise license validated ({boundaries['enterprise']['label']})", - f"5. Autonomous execution simulated ({boundaries['enterprise']['label']}+)", - f"6. Outcome recorded in RAG memory" - ], - "execution_result": execution_result, - "outcome": { - "recovery_time": "12 minutes", - "manual_comparison": "45 minutes", - "cost_saved": f"${savings_amount:,}", - "users_protected": "45,000", - "learning": "Pattern added to RAG memory" - }, - "architectural_summary": f"This demonstrates the complete ARF v3.3.9 architecture: {boundaries['oss']['label']} for advisory analysis → {boundaries['enterprise']['label']} for autonomous execution" - } + # =========================================== + # ENHANCED HEADER + # =========================================== + gr.HTML(ModernUI.create_header("3.3.9")) + + # =========================================== + # TELEMETRY STATUS INDICATOR + # =========================================== + gr.HTML(f""" +
+
+ + āœ… Modern UI: {'Active' if MODERN_COMPONENTS_AVAILABLE else 'Fallback'} + + + šŸ“Š Telemetry: Session {telemetry._session_id[:8]}... + + + 🧠 Psychological Components + + + ⚔ Performance Budget: OK + +
+
+ """) + + # =========================================== + # MAIN CONTENT CONTAINER + # =========================================== + with gr.Column(elem_classes="container mx-auto px-4"): - # Create demo completion message with enhanced boundary context - demo_message = f""" -
+ # =========================================== + # TAB NAVIGATION WITH STATE MANAGEMENT + # =========================================== + with gr.Tabs(elem_classes="modern-tabs") as tabs: - -
-
-

- āœ… Complete Demo: Architecture Validated -

-

- ARF v3.3.9 • OSS advises → Enterprise executes -

-
-
- - BOUNDARY VALIDATED - -
-
+ # Subscribe tab changes to state + def on_tab_change(evt: gr.SelectData): + telemetry.track_user_interaction("tab_switch", f"tab{evt.index + 1}") + app_state.set("current_tab", evt.index) + return "" - -
- -
-
- - {boundaries['oss']['label']} -
-
- • Anomaly detected in 45s
- • 3 similar incidents recalled
- • 94% confidence healing plan
- • Apache 2.0 license validated -
-
- - -
-
- - {boundaries['enterprise']['label']} -
-
- • Autonomous execution simulated
- • Rollback guarantee: 100%
- • 12min vs 45min recovery
- • ${savings_amount:,} saved -
-
-
+ tabs.select(on_tab_change) - -
-
- šŸ—ļø Architecture Flow -
-
- -
-
OSS Advisory
-
Apache 2.0
+ # TAB 1: ENHANCED LIVE DEMO WITH PSYCHOLOGICAL COMPONENTS + with gr.TabItem("🧠 Enhanced Live Demo", elem_id="tab1"): + with gr.Column(elem_classes="space-y-6"): + + # Scenario Selection with Validation + gr.HTML("
Validated scenarios only:
") + scenario_dropdown = gr.Dropdown( + choices=list(InputValidator.SCENARIO_WHITELIST), + value="Cache Miss Storm", + label="Incident Scenario", + elem_classes="w-full p-3" + ) + + # Validation feedback + gr.HTML(""" +
+ āœ“ Scenario validated • āœ“ Input sanitized • āœ“ Telemetry active
+ """) + + # =========================================== + # MODERN PSYCHOLOGICAL COMPONENTS SECTION + # =========================================== + + # Historical Evidence Panel (Recall Dominance) + gr.HTML("

🧠 Historical Evidence Dominance

") + + # Create example historical evidence data + evidence_data = { + "scaling_failures": [ + { + "date": "2024-11-15", + "environment": "prod-east", + "action": "Scale during retry storm", + "outcome": "Amplification increased 300%", + "lesson": "Scaling during amplification worsens the problem" + } + ], + "dampening_successes": [ + { + "date": "2024-12-03", + "environment": "prod-west", + "action": "Request coalescing + backoff", + "outcome": "Resolved in 8 min, $5.1K saved", + "lesson": "Dampening broke amplification cycle" + } + ] + } + + historical_evidence_html = gr.HTML() + + # Observation Gate + gr.HTML("

ā³ Psychological Restraint System

") + + observation_gate_html = gr.HTML() + + # Sequencing Visualization + gr.HTML("

šŸ”„ Policy Sequencing Logic

") + + sequencing_html = gr.HTML() + + # Process Workflow + gr.HTML("

šŸ” Policy Process Workflow

") + + # Detection Process + detection_data = { + "status": "active", + "title": "Detection Process", + "description": "Telemetry analysis & pattern recognition", + "metrics": { + "Pattern Match": "Retry Amplification", + "Confidence": "92.7%", + "Detection Time": "0.8 seconds" + }, + "content": "āœ… Detected: Retry amplification pattern with exponential growth", + "next_step": "Activate recall process" + } + + detection_html = gr.HTML() + + # Recall Process + recall_data = { + "status": "active", + "title": "Recall Process", + "description": "Historical evidence & pattern matching", + "metrics": { + "Incidents Matched": "8", + "Failure Rate": "76%", + "Evidence Weight": "85%" + }, + "content": "🧠 Historical evidence dominates predictive confidence", + "next_step": "Generate formal HealingIntent" + } + + recall_html = gr.HTML() + + # Decision Process + decision_data = { + "status": "active", + "title": "Decision Process", + "description": "HealingIntent creation & sequencing", + "metrics": { + "Confidence": "87.3%", + "Sequencing": "Dampening-first", + "Reversibility": "100%" + }, + "content": "šŸŽÆ Formal HealingIntent created with safety constraints", + "next_step": "Await observation gate clearance" + } + + decision_html = gr.HTML() + + # HealingIntent Display + gr.HTML("

šŸ“ Formal HealingIntent

") + + healing_intent_data = { + "confidence": 87.3, + "primary_action": "Implement request coalescing with exponential backoff (jitter: 25%)", + "sequencing_rule": "dampening_first_then_observe_then_optional_scale", + "preconditions": [ + "Retry amplification detected", + "Confidence > 70%", + "No scaling contraindicated" + ], + "contraindications": [ + "Scale during retry storm", + "Add capacity during amplification" + ], + "reversibility_statement": "Backoff can be adjusted, coalescing can be disabled, no stateful changes", + "historical_evidence": [ + "Similar incident resolved with dampening (87% success rate)", + "Scaling-first failed 76% of time during amplification" + ] + } + + healing_intent_html = gr.HTML() + + # Performance Metrics with Modern Styling + gr.HTML(""" +

+ šŸ“ˆ Enhanced Performance Metrics +

+
+ """) + + # Create metric cards using ModernUI + metrics = [ + {"value": "42s", "label": "Detection Time", "icon": "ā±ļø", "trend": "down"}, + {"value": "94%", "label": "Recall Quality", "icon": "🧠", "trend": "up"}, + {"value": "87%", "label": "Confidence Score", "icon": "šŸŽÆ", "trend": "neutral"}, + {"value": "Stage 2", "label": "Sequencing", "icon": "šŸ”„", "trend": "up"} + ] + + for i, metric in enumerate(metrics): + gr.HTML(ModernUI.create_metric_card(**metric)) - -
-
-
- advises + gr.HTML("
") + + # OSS vs Enterprise with Modern Components + gr.HTML(""" +

+ šŸ—ļø Modern Architecture Boundary +

+
+ """) + + # OSS Section + with gr.Column(): + gr.Markdown("### 🟢 OSS Advisory Layer", elem_classes="text-lg font-semibold mb-3") + gr.Markdown(""" + **Modern Psychological Capabilities:** + - āœ… Historical evidence dominance + - āœ… Observation gate restraint + - āœ… Formal HealingIntent creation + - āœ… Sequencing policy enforcement + + **State:** Modern Active + **Telemetry:** Recording psychological patterns + """, elem_classes="text-sm") + + def run_modern_oss_analysis(): + """Run OSS analysis with modern psychological components""" + telemetry.track_user_interaction("modern_oss_analysis", "button") + + # Show loading state + loading_html = PsychologicalUX.create_loading_state( + PsychologicalUX.LoadingStage.ANALYSIS + ) + + # Update psychological components + historical_html = PsychologicalUX.create_historical_evidence_panel(evidence_data) + observation_html = PsychologicalUX.create_observation_gate(65.0) + sequencing_html = PsychologicalUX.create_sequencing_panel() + detection_html = PsychologicalUX.create_process_display('detection', detection_data) + recall_html = PsychologicalUX.create_process_display('recall', recall_data) + decision_html = PsychologicalUX.create_process_display('decision', decision_data) + healing_html = PsychologicalUX.create_healing_intent_display(healing_intent_data) + + # Simulate analysis + time.sleep(1) + + # Show success + success_html = PsychologicalUX.create_success_notification( + "Modern OSS analysis completed with psychological insights" + ) + + # Update state + app_state.set("last_analysis", datetime.datetime.now().isoformat()) + app_state.set("analysis_count", app_state.get("analysis_count", 0) + 1) + app_state.set("psychological_components_used", True) + + return ( + historical_html, observation_html, sequencing_html, + detection_html, recall_html, decision_html, healing_html, + loading_html + success_html + ) + + oss_btn = gr.Button( + "Run Modern Analysis", + elem_classes="btn btn-success mt-4" + ) + oss_output = gr.HTML() + oss_btn.click( + run_modern_oss_analysis, + outputs=[ + historical_evidence_html, observation_gate_html, sequencing_html, + detection_html, recall_html, decision_html, healing_intent_html, + oss_output + ] + ) + + # Enterprise Section + with gr.Column(): + gr.Markdown("### 🟣 Modern Enterprise Execution", elem_classes="text-lg font-semibold mb-3") + gr.Markdown(""" + **Enhanced Capabilities:** + - āœ… Autonomous execution with psychological safety + - āœ… Rollback guarantee with observation gates + - āœ… MCP integration with sequencing policies + - āœ… Commercial license with modern components + + **State:** Modern Ready + **Safety:** Psychological constraints enabled + """, elem_classes="text-sm") + + def execute_modern_enterprise(): + """Execute with modern psychological components""" + telemetry.track_user_interaction("modern_enterprise_execution", "button") + + # Validate execution conditions + if app_state.get("errors_count", 0) > 5: + error_html = PsychologicalUX.create_error_notification( + "Too many errors", + "Reset application state" + ) + return error_html + + # Show execution loading with psychological context + execution_html = PsychologicalUX.create_loading_state( + PsychologicalUX.LoadingStage.EXECUTION, + progress=50 + ) + + # Simulate execution with modern components + time.sleep(1.5) + + # Update observation gate to show cleared state + observation_html = PsychologicalUX.create_observation_gate(85.0) + + # Update sequencing to show progress + sequencing_html = PsychologicalUX.create_sequencing_panel(current_step=3) + + # Track success + telemetry.track_event("modern_enterprise_execution_success") + app_state.set("execution_count", app_state.get("execution_count", 0) + 1) + app_state.set("confidence_level", 85.0) + app_state.set("observation_gate_active", False) + + success_html = PsychologicalUX.create_success_notification( + "Modern enterprise execution completed with psychological safety checks" + ) + + return observation_html, sequencing_html, execution_html + success_html + + enterprise_btn = gr.Button( + "Execute with Modern Safety", + elem_classes="btn btn-primary mt-4" + ) + enterprise_observation_output = gr.HTML() + enterprise_sequencing_output = gr.HTML() + enterprise_output = gr.HTML() + enterprise_btn.click( + execute_modern_enterprise, + outputs=[enterprise_observation_output, enterprise_sequencing_output, enterprise_output] + ) + + gr.HTML("
") + + # State Management with Modern Integration + with gr.Row(elem_classes="mt-6 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg"): + gr.Markdown("### 🧠 Modern State Management", elem_classes="text-lg font-semibold") + + def show_modern_state(): + """Display current app state with psychological context""" + state_snapshot = app_state.get_snapshot() + telemetry_state = telemetry.get_session_summary() + + # Filter psychological state + psych_state = {k: v for k, v in state_snapshot.items() if any( + keyword in k for keyword in [ + 'confidence', 'observation', 'sequencing', 'historical', 'healing' + ])} + + state_html = f""" +
+
+
+

Psychological State:

+
+{json.dumps(psych_state, indent=2)}
+                                            
+
+
+

Modern Components:

+
+{json.dumps({
+    "modern_components_available": MODERN_COMPONENTS_AVAILABLE,
+    "psychological_events": telemetry_state.get("psychological_component_events", 0),
+    "features_enabled": {k: v for k, v in FEATURE_FLAGS.items() if v}
+}, indent=2)}
+                                            
+
+
+
+ """ + return state_html + + def clear_modern_state(): + """Reset application state with psychological defaults""" + app_state._state = {} + app_state._history = [] + + # Reset with psychological defaults + app_state.update({ + "theme": "system", + "last_scenario": "Cache Miss Storm", + "user_interactions": 0, + "errors_count": 0, + "loading": False, + "dark_mode": False, + # Psychological state defaults + "confidence_level": 65.0, + "observation_gate_active": True, + "sequencing_stage": "dampening", + "historical_evidence_weight": 0.85, + "healing_intent_confidence": 87.3 + }) + + telemetry.track_event("modern_state_cleared") + return "Modern state cleared with psychological defaults" + + state_btn = gr.Button("Show Modern State", elem_classes="btn btn-secondary") + clear_btn = gr.Button("Clear Modern State", elem_classes="btn btn-danger") + state_output = gr.HTML() + + state_btn.click(show_modern_state, outputs=[state_output]) + clear_btn.click(clear_modern_state, outputs=[state_output]) + + # TAB 2: ENHANCED ROI CALCULATOR + with gr.TabItem("šŸ’° Enhanced ROI Calculator"): + with gr.Column(elem_classes="space-y-6"): + + # Input Validation Example + with gr.Row(elem_classes="grid grid-cols-1 md:grid-cols-3 gap-4"): + incidents_input = gr.Slider( + minimum=1, + maximum=100, + value=15, + label="Incidents/Month", + elem_classes="w-full" + ) + + team_input = gr.Slider( + minimum=1, + maximum=50, + value=5, + label="Team Size", + elem_classes="w-full" + ) + + cost_input = gr.Number( + value=200000, + label="Engineer Cost/Year ($)", + elem_classes="w-full" + ) + + def calculate_enhanced_roi(incidents, team_size, engineer_cost): + """Calculate ROI with validation and telemetry""" + # Validate inputs + is_valid_incidents, incidents_val = InputValidator.validate_numeric_input(incidents, 1, 1000) + is_valid_team, team_val = InputValidator.validate_numeric_input(team_size, 1, 100) + is_valid_cost, cost_val = InputValidator.validate_numeric_input(engineer_cost, 50000, 1000000) + + if not all([is_valid_incidents, is_valid_team, is_valid_cost]): + telemetry.track_event("roi_calculation_invalid_input") + return PsychologicalUX.create_error_notification( + "Invalid input values", + "Using safe defaults" + ) + + # Track calculation + telemetry.track_user_interaction("roi_calculation", "button") + + # Calculate ROI + monthly_impact = incidents_val * 8500 # Average impact per incident + annual_impact = monthly_impact * 12 + team_cost = team_val * cost_val + potential_savings = annual_impact * 0.82 + roi_multiplier = potential_savings / (team_cost * 0.3) # ARF cost is 30% of team + + # Create visualization + fig = go.Figure(data=[ + go.Bar( + name='Without ARF', + x=['Cost'], + y=[annual_impact], + marker_color=DesignTokens.COLORS["danger"] + ), + go.Bar( + name='With ARF', + x=['Cost'], + y=[annual_impact - potential_savings], + marker_color=DesignTokens.COLORS["success"] + ) + ]) + + fig.update_layout( + title=f"ROI Analysis: {roi_multiplier:.1f}x Return", + showlegend=True, + height=300 + ) + + # Create result display + result_html = f""" +
+

šŸ“Š ROI Analysis Results

+
+
+
${potential_savings:,.0f}
+
Annual Savings
+
+
+
{roi_multiplier:.1f}x
+
ROI Multiplier
+
+
+

+ Based on {incidents_val} incidents/month • Validated inputs • Telemetry recorded +

-
+ """ + + return result_html, fig - -
-
Enterprise
-
Commercial
-
-
-
+ calculate_btn = gr.Button( + "Calculate Enhanced ROI", + elem_classes="btn btn-primary" + ) + roi_output = gr.HTML() + roi_chart = gr.Plot() + + calculate_btn.click( + calculate_enhanced_roi, + inputs=[incidents_input, team_input, cost_input], + outputs=[roi_output, roi_chart] + ) - -
-
+ # TAB 3: MODERN PERFORMANCE DASHBOARD + with gr.TabItem("šŸ“Š Modern Dashboard"): + with gr.Column(elem_classes="space-y-6"): + + # Performance Budget Status + gr.Markdown("### ⚔ Modern Performance Budget Status", elem_classes="text-xl font-semibold") + + def get_modern_performance_status(): + """Get current performance status with modern integration""" + budget_status = PerformanceBudget.get_budget_status() + telemetry_summary = telemetry.get_session_summary() + optimization_stats = update_optimizer.get_optimization_stats() + + # Calculate psychological component performance + psych_events = telemetry_summary.get("psychological_component_events", 0) + total_events = telemetry_summary.get("total_events", 1) + psych_usage_rate = (psych_events / total_events * 100) if total_events > 0 else 0 + + status_html = f""" +
+ +
+

šŸš€ Modern Integration Status

+
+
+
Modern Components
+
+ {'āœ…' if MODERN_COMPONENTS_AVAILABLE else 'āš ļø'} +
+
+
+
Psychological Usage
+
{psych_usage_rate:.1f}%
+
+
+
CSS Size
+
{len(css_content)/1024:.1f}KB
+
+
+
Components Tracked
+
{optimization_stats.get('tracked_components', 0)}
+
+
+
+ + +
+

🧠 Psychological Component Insights

+
+ """ + + # Add psychological component stats + psych_components = ["observation_gate", "sequencing", "historical_evidence", "healing_intent"] + for component in psych_components: + component_events = len([e for e in telemetry._events if component in e["event"]]) + status_html += f""" +
+
{component.replace('_', ' ').title()}
+
{component_events}
+
+ """ + + status_html += """ +
+
+
+ """ + + return status_html + + refresh_btn = gr.Button( + "šŸ”„ Refresh Modern Dashboard", + elem_classes="btn btn-secondary" + ) + dashboard_output = gr.HTML() + + refresh_btn.click(get_modern_performance_status, outputs=[dashboard_output]) + + # Export Modern Telemetry Data + def export_modern_telemetry_data(): + """Export telemetry data with psychological insights""" + telemetry.track_user_interaction("export_modern_telemetry", "button") + data = telemetry.export_data() + return data + + export_btn = gr.Button( + "šŸ’¾ Export Modern Telemetry", + elem_classes="btn btn-primary" + ) + export_output = gr.Textbox( + label="Modern Telemetry Data (JSON)", + lines=10, + elem_classes="w-full" + ) + + export_btn.click(export_modern_telemetry_data, outputs=[export_output]) + + # =========================================== + # ENHANCED FOOTER WITH MODERN STATUS + # =========================================== + gr.HTML(f""" +
+
+ +
+
+
+
{app_state.get('user_interactions', 0)}
+
User Interactions
+
+
+
{app_state.get('analysis_count', 0)}
+
Modern Analyses
+
+
+
{app_state.get('execution_count', 0)}
+
Executions
+
-
Time Saved
-
73%
+
{app_state.get('errors_count', 0)}
+
Errors
-
Cost Saved
-
${savings_amount:,}
+
{'āœ…' if MODERN_COMPONENTS_AVAILABLE else 'āš ļø'}
+
Modern UI
-
ROI Multiplier
-
5.2Ɨ
+
{app_state.get('confidence_level', 65):.0f}%
+
Confidence
- -
-
-
āœ…
-
-
- Architecture Successfully Validated -
-
- Clear separation maintained: OSS for advisory intelligence, Enterprise for autonomous execution -
+ +
+
+

Modern ARF v3.3.9

+

+ Complete Psychological Integration
+ Modern UI Components Active
+ Performance Budget: {len(css_content)/1024:.1f}KB / 50KB +

+
+ +
+

Modern Features

+
+

āœ… Modern Psychological Components

+

āœ… Design Tokens System

+

āœ… Historical Evidence Dominance

+

āœ… Observation Gate Restraint

+

āœ… Formal HealingIntent System

+

āœ… Performance Budgets

+
+
+ +
+

Modern Status

+
+

🟢 System: Modern Operational

+

🟢 Telemetry: Psychological Tracking

+

🟢 Validation: 100% Coverage

+

🟢 Performance: Optimal

+

Session: {telemetry._session_id[:8]}...

- -
- Ready for production? - Install ARF Enterprise → + +
+

+ Ā© 2024 ARF Technologies • Modern Psychological Edition • + Session started: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')} • + 00:00 +

- """ - - # Update the enterprise_results_display to include demo completion info - enterprise_results["demo_completion_message"] = demo_message - - # Get updated DataFrames (FIXED: Returns DataFrames) - incident_df = get_audit_manager().get_incident_dataframe() - execution_df = get_audit_manager().get_execution_dataframe() - - # Combine all results - return ( - *update_result, # 8 outputs: scenario_card, telemetry_viz, impact_viz, timeline_viz, detection_time, recall_quality, confidence_score, sequencing_stage - *oss_result[:3], # 3 outputs: detection_process, recall_process, decision_process - oss_result[3], # 1 output: oss_results_display - enterprise_results, # 1 output: enterprise_results_display - demo_message, # 1 output: approval_display - incident_df, # 1 output: incident_table (DataFrame) - execution_df # 1 output: execution_table (DataFrame) - ) - - # FIXED: demo_btn.click with correct output count - demo_btn.click( - fn=run_complete_demo_async, - inputs=[scenario_dropdown], - outputs=[ - scenario_card, telemetry_viz, impact_viz, timeline_viz, - detection_time, recall_quality, confidence_score, sequencing_stage, # 8 - detection_process, recall_process, decision_process, # 3 - oss_results_display, # 1 - enterprise_results_display, # 1 - approval_display, # 1 - incident_table, # 1 - execution_table # 1 - ] - ) - - # ROI Calculation - calculate_btn.click( - fn=calculate_roi, - inputs=[roi_scenario_dropdown, monthly_slider, team_slider], - outputs=[roi_output, roi_chart] - ) - - # Update ROI scenario - FIXED: Use the EnhancedROICalculator - roi_scenario_dropdown.change( - fn=lambda x: get_components()["EnhancedROICalculator"].calculate_comprehensive_roi(scenario_name=x), - inputs=[roi_scenario_dropdown], - outputs=[roi_output] - ) - - # Update ROI chart - monthly_slider.change( - fn=lambda x, y: calculate_roi(roi_scenario_dropdown.value, x, y)[1], - inputs=[monthly_slider, team_slider], - outputs=[roi_chart] - ) +
+ + + + """) - team_slider.change( - fn=lambda x, y: calculate_roi(roi_scenario_dropdown.value, x, y)[1], - inputs=[monthly_slider, team_slider], - outputs=[roi_chart] - ) + # =========================================== + # INITIALIZATION COMPLETE + # =========================================== - # Audit Trail Functions - FIXED: Returns DataFrames - def refresh_audit_trail(): - """Refresh audit trail tables - FIXED to return DataFrames""" + # Initialize psychological components on startup + def initialize_psychological_components(): + """Initialize psychological components with current state""" + confidence = app_state.get("confidence_level", 65.0) + + historical_html = PsychologicalUX.create_historical_evidence_panel(evidence_data) + observation_html = PsychologicalUX.create_observation_gate(confidence) + sequencing_html = PsychologicalUX.create_sequencing_panel() + detection_html = PsychologicalUX.create_process_display('detection', detection_data) + recall_html = PsychologicalUX.create_process_display('recall', recall_data) + decision_html = PsychologicalUX.create_process_display('decision', decision_data) + healing_html = PsychologicalUX.create_healing_intent_display(healing_intent_data) + return ( - get_audit_manager().get_execution_dataframe(), # DataFrame - get_audit_manager().get_incident_dataframe() # DataFrame + historical_html, observation_html, sequencing_html, + detection_html, recall_html, decision_html, healing_html ) - def clear_audit_trail(): - """Clear audit trail - FIXED to return empty DataFrames""" - get_audit_manager().clear() - # Return empty DataFrames with correct columns - exec_df = pd.DataFrame(columns=["Execution ID", "Scenario", "Status", "Mode", "Start Time"]) - incident_df = pd.DataFrame(columns=["Scenario", "Status", "Boundary", "Time"]) - return exec_df, incident_df - - def export_audit_trail(): - """Export audit trail as JSON""" - audit_data = { - "executions": get_audit_manager().executions, - "incidents": get_audit_manager().incidents, - "boundary_crossings": get_audit_manager().boundary_crossings, - "export_time": datetime.datetime.now().isoformat(), - "arf_version": "3.3.9", - "architecture": "OSS advises → Enterprise executes" - } - return json.dumps(audit_data, indent=2) - - refresh_btn.click( - fn=refresh_audit_trail, - inputs=[], - outputs=[execution_table, incident_table] - ) - - clear_btn.click( - fn=clear_audit_trail, - inputs=[], - outputs=[execution_table, incident_table] - ) - - export_btn.click( - fn=export_audit_trail, - inputs=[], - outputs=[export_text] - ) - - # Enterprise Features - def validate_license(): - """Validate enterprise license with boundary context""" - boundaries = BoundaryManager.get_system_boundaries() - - if boundaries["enterprise"]["available"]: - return { - "status": "āœ… Valid License", - "license_type": "Enterprise", - "version": boundaries["enterprise"]["version"], - "expires": "2025-12-31", - "capabilities": boundaries["enterprise"]["capabilities"], - "boundary_context": f"Real {boundaries['enterprise']['label']} detected" - } - else: - return { - "status": "āš ļø Demo Mode", - "license_type": "Simulated", - "version": boundaries["enterprise"]["version"], - "expires": "Demo only", - "capabilities": boundaries["enterprise"]["capabilities"], - "boundary_context": f"Simulating {boundaries['enterprise']['label']} - requires license", - "contact": "sales@arf.dev" - } - - validate_btn.click( - fn=validate_license, - inputs=[], - outputs=[license_display] - ) - - # Load default scenario - UPDATE outputs without realism_panel + # Load initial psychological components demo.load( - fn=lambda: update_scenario_display_with_metrics(settings.default_scenario), + initialize_psychological_components, inputs=[], outputs=[ - scenario_card, telemetry_viz, impact_viz, timeline_viz, - detection_time, recall_quality, confidence_score, sequencing_stage + historical_evidence_html, observation_gate_html, sequencing_html, + detection_html, recall_html, decision_html, healing_intent_html ] ) - # Load ROI data - demo.load( - fn=lambda: calculate_roi(settings.default_scenario, 15, 5), - inputs=[], - outputs=[roi_output, roi_chart] - ) - - logger.info("āœ… Demo interface created successfully with modern UI integration") + # Track successful initialization + init_time = (time.time() - start_time) * 1000 + telemetry.track_event("modern_app_initialization_complete", { + "init_time_ms": init_time, + "modern_components": MODERN_COMPONENTS_AVAILABLE, + "css_size_kb": len(css_content)/1024 + }) + telemetry.track_performance("modern_app_initialization", init_time) + + logger.info(f"āœ… Modern demo interface created in {init_time:.0f}ms") + logger.info(f"šŸ“Š Modern components: {'āœ… Active' if MODERN_COMPONENTS_AVAILABLE else 'āš ļø Fallback'}") + + # Initialize app state with modern data + app_state.update({ + "init_time_ms": init_time, + "telemetry_session": telemetry._session_id, + "performance_budgets": PerformanceBudget.get_budget_status(), + "modern_components_available": MODERN_COMPONENTS_AVAILABLE, + "psychological_features_enabled": is_feature_enabled('psychological_components') + }) return demo # =========================================== -# DARK MODE TOGGLE FUNCTION -# =========================================== - -def create_dark_mode_toggle(): - """Create a dark mode toggle button with JavaScript""" - return f""" -
- šŸŒ™ -
- - - """ - -# =========================================== -# MAIN EXECUTION - CRITICAL: THIS LAUNCHES THE APP - UPDATED FOR SPACES +# ENHANCED MAIN EXECUTION # =========================================== - def main(): - """Main entry point that actually launches the Gradio app""" + """Enhanced main entry point with modern integration""" try: - logger.info("šŸš€ ARF Ultimate Investor Demo v3.3.9 - ENTERPRISE EDITION") - logger.info("=" * 60) - logger.info("Enhanced with clear OSS vs Enterprise boundaries") - logger.info("DOCTRINAL COMPLIANCE: Historical Evidence, Observation Gate, Sequencing") - logger.info("PHASE 2: Dynamic Performance Metrics by Scenario") - logger.info(f"Modern UI: {'Enabled' if get_feature_flags().get('modern_ui', True) else 'Disabled'}") - logger.info(f"True ARF OSS v3.3.9 integration with simulated Enterprise execution") - logger.info("=" * 60) - - # Create the demo interface - demo = create_demo_interface() - - print("\n" + "="*60) - print("šŸš€ ARF Ultimate Investor Demo v3.3.9 - ENTERPRISE EDITION") - print("šŸ“Š Architecture: OSS advises → Enterprise executes") - print("šŸŽ­ DOCTRINAL: Historical Evidence + Observation Gate + Sequencing") - print("šŸŽØ MODERN UI: Design system with responsive components") - print("="*60 + "\n") - - # ============ HUGGING FACE SPACES SPECIFIC ============ - # Spaces handles ports differently - use their system + print("\n" + "="*70) + print("šŸš€ ARF v3.3.9 - Modern Psychological Edition") + print("="*70) + print("šŸŽÆ MODERN INTEGRATION STATUS:") + print(f" • Modern UI Components: {'āœ… ACTIVE' if MODERN_COMPONENTS_AVAILABLE else 'āš ļø FALLBACK'}") + print(f" • Psychological Features: {'āœ… ENABLED' if is_feature_enabled('psychological_components') else 'āŒ DISABLED'}") + print() + print("🧠 PSYCHOLOGICAL COMPONENTS IMPLEMENTED:") + print(" • Observation Gate System (Active restraint display)") + print(" • Sequencing Visualization (Policy over reaction)") + print(" • Historical Evidence Panel (Recall dominance)") + print(" • Formal HealingIntent Display (Professional documentation)") + print(" • Process Workflow (Detection → Recall → Decision)") + print() + print("šŸ“Š ENTERPRISE FEATURES:") + print(f" • Telemetry: {'āœ…' if is_feature_enabled('telemetry') else 'āŒ'}") + print(f" • Performance Monitoring: {'āœ…' if is_feature_enabled('performance_monitoring') else 'āŒ'}") + print(f" • Modern Design System: {'āœ…' if is_feature_enabled('modern_ui') else 'āŒ'}") + print(f" • Dark Mode: {'āœ…' if is_feature_enabled('dark_mode') else 'āŒ'}") + print("="*70 + "\n") + + # Create and launch the enhanced demo + demo = create_enhanced_demo_interface() + + # Get configuration import os - - # Get port from environment (Spaces sets this) port = int(os.getenv("GRADIO_SERVER_PORT", "7860")) server_name = os.getenv("GRADIO_SERVER_NAME", "0.0.0.0") - # Get CSS - css_styles = load_css_files() - - logger.info(f"šŸš€ Launching on {server_name}:{port}") - print(f"🌐 Starting on http://{server_name}:{port}") - - # SIMPLE LAUNCH FOR SPACES COMPATIBILITY + print(f"🌐 Launching on http://{server_name}:{port}") + print("🧠 Psychology: Historical evidence dominance enabled") + print("ā³ Restraint: Observation gate system active") + print("šŸ”„ Sequencing: Policy-enforced action sequences") + print("šŸ“Š Telemetry: Psychological pattern tracking") + print("\nšŸ’” MODERN TIPS:") + print(" - Check 'Modern Dashboard' tab for psychological insights") + print(" - Try OSS analysis to see historical evidence dominance") + print(" - Watch observation gate change with confidence levels") + print(" - Export telemetry to see psychological component usage") + + # Launch with enhanced configuration demo.launch( - css=css_styles, # CSS moved to launch() - fixes Gradio 6.0 warning server_name=server_name, server_port=port, share=False, debug=False, show_error=True, - quiet=True # Reduce log noise + quiet=True, + enable_queue=True, + max_threads=10 ) except KeyboardInterrupt: - logger.info("šŸ‘‹ Demo stopped by user") + print("\nšŸ‘‹ Modern demo stopped by user") + telemetry.track_event("modern_app_shutdown_user") except Exception as e: - logger.error(f"āŒ Fatal error: {e}", exc_info=True) - print(f"\nāŒ ERROR: {e}") - print("Please check the logs for more details.") + print(f"\nāŒ Modern integration error: {e}") + telemetry.track_error(e, "modern_main_execution") + import traceback + traceback.print_exc() sys.exit(1) # =========================================== -# HUGGING FACE SPACES COMPATIBILITY - UPDATED +# INSTALLATION STATUS FUNCTION # =========================================== +def get_installation_status() -> Dict[str, Any]: + """Get installation status for modern components""" + try: + # Try to import ARF package + import pkg_resources + try: + arf_version = pkg_resources.get_distribution("agentic-reliability-framework").version + oss_installed = True + except pkg_resources.DistributionNotFound: + arf_version = None + oss_installed = False + + return { + "oss_installed": oss_installed, + "oss_version": arf_version, + "enterprise_installed": False, # Placeholder for enterprise check + "enterprise_version": None, + "execution_allowed": False, + "recommendations": [ + "Modern UI components integrated successfully", + "Psychological features active" if MODERN_COMPONENTS_AVAILABLE else "Using fallback psychological components" + ], + "badges": [ + {"text": "Modern UI", "color": "purple", "icon": "šŸŽØ"}, + {"text": "Psychological", "color": "amber", "icon": "🧠"}, + {"text": f"Components: {'āœ… Modern' if MODERN_COMPONENTS_AVAILABLE else 'āš ļø Fallback'}", "color": "blue", "icon": "⚔"} + ] + } + except Exception as e: + logger.error(f"Installation check failed: {e}") + return { + "oss_installed": False, + "oss_version": None, + "recommendations": ["Run 'pip install agentic-reliability-framework'"], + "badges": [ + {"text": "Demo Mode", "color": "gray", "icon": "āš ļø"} + ] + } -# This is the entry point that Hugging Face Spaces will use +# =========================================== +# MODERN SPACES ENTRY POINT +# =========================================== if __name__ == "__main__": - # For Hugging Face Spaces, we need to ensure the app stays alive + # Enhanced configuration for Hugging Face Spaces import os - # ============ CRITICAL FIXES FOR HUGGING FACE SPACES ============ - - # 1. Set environment variables for Hugging Face Spaces compatibility + # Environment configuration with validation os.environ["GRADIO_ANALYTICS_ENABLED"] = "False" - os.environ["GRADIO_SERVER_PORT"] = "7860" # Spaces will override this if needed + os.environ["GRADIO_SERVER_PORT"] = "7860" os.environ["GRADIO_SERVER_NAME"] = "0.0.0.0" - os.environ["GRADIO_HOT_RELOAD"] = "False" # Disable hot reload in Spaces - os.environ["GRADIO_QUEUE_ENABLED"] = "True" # Enable queue for stability - - # 2. Additional fixes for uvicorn warnings - os.environ["UVICORN_LOG_LEVEL"] = "warning" # Reduce uvicorn log noise - os.environ["UVICORN_ACCESS_LOG"] = "False" # Disable access logs - - print("\n" + "="*60) - print("šŸš€ ARF Demo Starting on Hugging Face Spaces") - print(f"šŸ“ Working directory: {os.getcwd()}") - print(f"šŸ“Š Python version: {sys.version}") - print("="*60 + "\n") - - # 3. Detect if we're running in Hugging Face Spaces - is_huggingface_space = "SPACE_ID" in os.environ or "HF_SPACE" in os.environ - if is_huggingface_space: - print("āœ… Hugging Face Spaces environment detected") - print("šŸ¤– Using Spaces-optimized configuration") - - # 4. Check for required files with better error handling - required_files = ["styles/modern.css", "styles/responsive.css", "ui/components.py"] - missing_files = [] - - for file in required_files: - if not os.path.exists(file): - missing_files.append(file) - print(f"āš ļø Warning: {file} not found") - - if missing_files: - print(f"āš ļø Missing {len(missing_files)} required files") - print("āš ļø Some features may not work correctly") - # Create minimal fallback CSS files if missing - for css_file in ["styles/modern.css", "styles/responsive.css"]: - if css_file in missing_files: - try: - os.makedirs(os.path.dirname(css_file), exist_ok=True) - with open(css_file, "w") as f: - if "modern.css" in css_file: - f.write("/* Modern CSS Fallback */\n:root { --color-primary: #3b82f6; }\n") - else: - f.write("/* Responsive CSS Fallback */\n@media (max-width: 768px) { .container { padding: 1rem; } }\n") - print(f"āœ… Created fallback {css_file}") - except Exception as e: - print(f"āš ļø Could not create {css_file}: {e}") - - # 5. Import gradio early to prevent threading issues - try: - import gradio as gr - logger.info(f"āœ… Gradio {gr.__version__} loaded successfully") - except Exception as e: - logger.error(f"āŒ Failed to load gradio: {e}") - print("āŒ CRITICAL: Gradio failed to load") - raise + os.environ["GRADIO_QUEUE_ENABLED"] = "True" + os.environ["UVICORN_LOG_LEVEL"] = "warning" + + # Validate environment + required_vars = ["GRADIO_SERVER_PORT", "GRADIO_SERVER_NAME"] + for var in required_vars: + if var not in os.environ: + logger.warning(f"Environment variable {var} not set, using default") + + # Check if running in Spaces + is_space = "SPACE_ID" in os.environ or "HF_SPACE" in os.environ + + print(f"\n{'='*70}") + print(f"{'šŸ¤— Hugging Face Spaces - Modern Edition' if is_space else 'šŸš€ Local Deployment - Modern Edition'}") + print(f"{'='*70}") + + # Record startup telemetry with modern context + telemetry.track_event("modern_app_startup", { + "environment": "spaces" if is_space else "local", + "modern_components": MODERN_COMPONENTS_AVAILABLE, + "psychological_features": is_feature_enabled('psychological_components') + }) - # 6. Start the main application with better error handling - try: - main() - except Exception as e: - logger.error(f"āŒ Main application crashed: {e}", exc_info=True) - print(f"\nāŒ FATAL ERROR: {e}") - print("šŸ’” Troubleshooting tips:") - print("1. Check all required files exist") - print("2. Verify Python package versions") - print("3. Check Hugging Face Spaces logs for details") - - # Try a minimal fallback launch if main() fails - try: - print("\nšŸ”„ Attempting minimal fallback launch...") - import gradio as gr - - def fallback_app(): - with gr.Blocks(title="ARF Fallback") as demo: - gr.Markdown("# 🚨 ARF System Recovery") - gr.Markdown("The main application failed, but the system is still running.") - gr.Markdown("**Error:** " + str(e)) - return demo - - demo = fallback_app() - demo.launch( - server_name="0.0.0.0", - server_port=7860, - quiet=True, - show_error=False - ) - except Exception as fallback_error: - print(f"āŒ Fallback also failed: {fallback_error}") - sys.exit(1) \ No newline at end of file + # Initialize app state with modern context + app_state.update({ + "environment": "spaces" if is_space else "local", + "startup_time": datetime.datetime.now().isoformat(), + "python_version": sys.version, + "modern_integration": True, + "psychological_components_version": "3.3.9+modern" + }) + + # Run the enhanced modern application + main() \ No newline at end of file