petter2025's picture
Update app.py
c07fad9 verified
raw
history blame
108 kB
#!/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
import traceback
import json
import datetime
import asyncio
import time
import random
import re
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple, Callable
from dataclasses import dataclass, asdict
from enum import Enum
# ===========================================
# ENHANCED CONFIGURATION
# ===========================================
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('arf_demo.log')
]
)
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 COMPONENTS INTEGRATION
# ===========================================
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.")
# ===========================================
# PHASE 1: DESIGN TOKENS & CONSTANTS
# ===========================================
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"])
# ===========================================
# PHASE 1: INPUT VALIDATION
# ===========================================
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'<script.*?>.*?</script>', '', 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))
# ===========================================
# PHASE 1: ENHANCED PSYCHOLOGICAL UX
# ===========================================
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 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": "🧠"
},
PsychologicalUX.LoadingStage.DECISION: {
"title": "🎯 Decision Making",
"description": "Formulating optimal healing strategy",
"details": "Evaluating 5+ action sequences for safety",
"color": DesignTokens.COLORS["warning"],
"icon": "🎯"
},
PsychologicalUX.LoadingStage.EXECUTION: {
"title": "⚑ Safe Execution",
"description": "Executing with rollback guarantees",
"details": "Atomic operations with real-time validation",
"color": DesignTokens.COLORS["enterprise_primary"],
"icon": "⚑"
}
}
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"""
<div class="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-700 mt-3">
<div class="h-2.5 rounded-full"
style="width: {progress}%; background: {config['color']}; transition: width 0.5s ease;">
</div>
</div>
"""
return f"""
<div class="loading-state p-6 rounded-lg border border-gray-200 dark:border-gray-700
bg-white dark:bg-gray-800 animate-pulse">
<div class="flex items-center gap-4 mb-4">
<div class="text-3xl" style="color: {config['color']};">{config['icon']}</div>
<div>
<h4 class="font-semibold text-gray-900 dark:text-white">{config['title']}</h4>
<p class="text-sm text-gray-600 dark:text-gray-400">{config['description']}</p>
</div>
</div>
<p class="text-xs text-gray-500 dark:text-gray-500 mb-2">{config['details']}</p>
{progress_bar}
<div class="mt-4 flex justify-center">
<div class="flex space-x-1">
<div class="w-2 h-2 bg-gray-300 rounded-full animate-bounce" style="animation-delay: 0ms"></div>
<div class="w-2 h-2 bg-gray-300 rounded-full animate-bounce" style="animation-delay: 150ms"></div>
<div class="w-2 h-2 bg-gray-300 rounded-full animate-bounce" style="animation-delay: 300ms"></div>
</div>
</div>
</div>
"""
@staticmethod
def create_success_notification(action: str, duration: str = "2.4s") -> str:
"""Create satisfying completion feedback"""
return f"""
<div class="success-toast animate-in"
style="animation: slideIn 0.3s ease-out, fadeOut {duration} ease-in 2.1s;">
<div class="flex items-center gap-3 p-4 rounded-lg bg-green-50 dark:bg-green-900/20
border border-green-200 dark:border-green-800">
<div class="flex-shrink-0">
<div class="w-8 h-8 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center">
<span class="text-green-600 dark:text-green-400 text-lg">βœ“</span>
</div>
</div>
<div class="flex-1">
<p class="font-medium text-green-800 dark:text-green-300">Success!</p>
<p class="text-sm text-green-700 dark:text-green-400">{action} completed successfully</p>
</div>
<div class="text-xs text-green-600 dark:text-green-500">
{datetime.datetime.now().strftime("%H:%M:%S")}
</div>
</div>
</div>
"""
@staticmethod
def create_error_notification(error: str, recovery: str = "") -> str:
"""Create helpful error feedback"""
recovery_html = f'<p class="text-sm text-amber-700 dark:text-amber-400 mt-1">{recovery}</p>' if recovery else ""
return f"""
<div class="error-notification animate-in" style="animation: slideIn 0.3s ease-out;">
<div class="flex items-center gap-3 p-4 rounded-lg bg-red-50 dark:bg-red-900/20
border border-red-200 dark:border-red-800">
<div class="flex-shrink-0">
<div class="w-8 h-8 bg-red-100 dark:bg-red-900 rounded-full flex items-center justify-center">
<span class="text-red-600 dark:text-red-400 text-lg">⚠️</span>
</div>
</div>
<div class="flex-1">
<p class="font-medium text-red-800 dark:text-red-300">Operation Failed</p>
<p class="text-sm text-red-700 dark:text-red-400">{error}</p>
{recovery_html}
</div>
</div>
</div>
"""
@staticmethod
def create_empty_state(icon: str, title: str, description: str, action: str = "") -> str:
"""Create helpful empty state"""
action_html = f'<button class="mt-4 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">{action}</button>' if action else ""
return f"""
<div class="empty-state text-center py-12">
<div class="text-5xl mb-4 text-gray-400 dark:text-gray-600">{icon}</div>
<h3 class="text-xl font-semibold text-gray-700 dark:text-gray-300 mb-2">{title}</h3>
<p class="text-gray-500 dark:text-gray-500 max-w-md mx-auto">{description}</p>
{action_html}
</div>
"""
# ===========================================
# 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:
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"""
<div class="observation-gate-fallback" style="border-color: {status_color};">
<h3>{status_text}</h3>
<p>System restraint engaged</p>
<div class="decision-message">
<h4>{decision_text}</h4>
<p>Confidence: {confidence:.1f}% (Threshold: {threshold}%)</p>
</div>
</div>
"""
@staticmethod
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)
return InputValidator.sanitize_html(html)
@staticmethod
def _create_sequencing_fallback(**kwargs) -> str:
"""Fallback sequencing implementation"""
return """
<div class="sequencing-fallback">
<h3>πŸ”„ Doctrinal Sequencing: Policy Over Reaction</h3>
<div class="sequencing-steps">
<div class="step">1. Dampening (Required)</div>
<div class="step">2. Concurrency Control (Required)</div>
<div class="step">3. Observe (Required)</div>
<div class="step">4. Scale (Optional)</div>
</div>
</div>
"""
@staticmethod
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:
html = HistoricalEvidencePanel.create(evidence_data, **kwargs)
except Exception as e:
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)
@staticmethod
def _create_historical_evidence_fallback(evidence_data: Dict = None, **kwargs) -> str:
"""Fallback historical evidence implementation"""
return """
<div class="historical-evidence-fallback">
<h3>🧠 Historical Evidence (Why Sequencing Matters)</h3>
<p>Historical evidence outweighs model confidence in decision making.</p>
</div>
"""
@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)
@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"""
<div class="healing-intent-fallback">
<h3>πŸ“ Formal HealingIntent Created</h3>
<div class="confidence">Confidence: {confidence:.1f}%</div>
<div class="action">Action: {action}</div>
</div>
"""
@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"""
<div class="process-display-fallback">
<div class="process-icon">{icon}</div>
<div class="process-title">{title}</div>
<div class="process-status">Status: {status}</div>
</div>
"""
# ===========================================
# FEATURE MANAGEMENT
# ===========================================
FEATURE_FLAGS = {
'modern_ui': True,
'dark_mode': True,
'responsive_design': True,
'loading_animations': True,
'telemetry': True,
'performance_monitoring': True,
'psychological_components': MODERN_COMPONENTS_AVAILABLE
}
def is_feature_enabled(feature: str) -> bool:
"""Simple, transparent feature checking"""
return FEATURE_FLAGS.get(feature, False)
# ===========================================
# PHASE 2: STATE MANAGEMENT
# ===========================================
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()
# ===========================================
# PHASE 2: TELEMETRY & ANALYTICS
# ===========================================
class TelemetryCollector:
"""Anonymous usage analytics and performance monitoring"""
# Singleton instance
_instance = None
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()
# 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
}
# 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
}
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
metric = {
"component": component,
"duration_ms": duration_ms,
"timestamp": datetime.datetime.now().isoformat(),
"metadata": metadata or {}
}
self._performance_metrics.append(metric)
# 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
},
"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()
},
"info"
)
# 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
# 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
# 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)
# 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_"
])]
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()
# ===========================================
# PHASE 2: PERFORMANCE BUDGET MONITOR
# ===========================================
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
}
THRESHOLDS = {
"warning": 0.8, # 80% of budget (warning)
"critical": 0.95 # 95% of budget (critical)
}
@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
return True
@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
@classmethod
def get_budget_status(cls) -> Dict:
"""Get current budget status"""
return {
"budgets": cls.BUDGETS,
"thresholds": cls.THRESHOLDS,
"timestamp": datetime.datetime.now().isoformat()
}
# ===========================================
# PHASE 2: UPDATE OPTIMIZATOR
# ===========================================
class UpdateOptimizer:
"""Prevent unnecessary UI updates and re-renders"""
def __init__(self):
self._component_states = {}
self._update_throttle_ms = 100 # Minimum time between updates
self._last_update_times = {}
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, {})
# Deep compare states
if self._states_equal(old_state, new_state):
logger.debug(f"Skipping update for {component_id} (no state change)")
return False
# Throttle updates
current_time = time.time() * 1000
last_update = self._last_update_times.get(component_id, 0)
if current_time - last_update < self._update_throttle_ms:
logger.debug(f"Throttling update for {component_id}")
return False
# Update tracking
self._component_states[component_id] = new_state
self._last_update_times[component_id] = current_time
return True
def _states_equal(self, state1: Dict, state2: Dict) -> bool:
"""Deep compare two states"""
try:
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
}
# Global optimizer instance
update_optimizer = UpdateOptimizer()
# ===========================================
# ENHANCED CSS LOADING WITH MODERN INTEGRATION
# ===========================================
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()])}
}}
/* Base Styles */
* {{
box-sizing: border-box;
}}
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:
# 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.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;
}
.grid-cols-1 {
grid-template-columns: 1fr !important;
}
.md\\:grid-cols-2 {
grid-template-columns: 1fr !important;
}
.md\\:grid-cols-3 {
grid-template-columns: 1fr !important;
}
.md\\:grid-cols-4 {
grid-template-columns: 1fr !important;
}
}
@media (hover: none) and (pointer: coarse) {
.btn, button, [role="button"] {
min-height: 44px;
min-width: 44px;
padding: 12px 20px;
}
input, select, textarea {
font-size: 16px;
padding: 12px;
}
}
"""
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;
}}
[data-theme="dark"] .gradio-container {{
background: var(--color-background-dark) !important;
}}
/* Smooth theme transitions */
* {{
transition: background-color var(--transition-normal),
border-color var(--transition-normal),
color var(--transition-normal);
}}
"""
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;
}
.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;
}
@keyframes shimmer {
0% { left: -100%; }
100% { left: 100%; }
}
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-10px); }
}
.animate-bounce {
animation: bounce 1s infinite;
}
"""
css_parts.append(animations_css)
# Combine all CSS
css_content = "\n".join(css_parts)
# Check performance budget
is_valid, message = PerformanceBudget.check_css_budget(css_content)
if not is_valid:
logger.warning(f"CSS budget issue: {message}")
# Track performance
load_time = (time.time() - start_time) * 1000
telemetry.track_performance("css_loading", load_time)
logger.info(f"βœ… CSS loaded: {len(css_content)/1024:.1f}KB in {load_time:.0f}ms")
return css_content
# ===========================================
# MODERN UI COMPONENTS WITH ENHANCEMENTS
# ===========================================
class ModernUI:
"""Modern UI component wrappers with validation and telemetry"""
@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"""
<header class="app-header">
<div class="container mx-auto text-center py-8">
<h1 class="text-4xl font-bold text-gray-900 dark:text-white mb-4">
πŸš€ Agentic Reliability Framework v{version_display}
</h1>
<p class="text-lg text-gray-600 dark:text-gray-300 mb-8 max-w-2xl mx-auto">
OSS advises β†’ Enterprise executes β€’ Enhanced with Modern Psychological Components
</p>
<div class="flex flex-wrap justify-center gap-3 mb-6">
<!-- OSS Badge -->
<div class="flex items-center gap-2 px-4 py-2 rounded-full
bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300">
<span class="text-lg">βœ…</span>
<span class="font-semibold">OSS Advisory</span>
<span class="text-xs opacity-75">Apache 2.0</span>
</div>
<!-- Separator -->
<div class="flex items-center text-gray-400">
β†’
</div>
<!-- Enterprise Badge -->
<div class="flex items-center gap-2 px-4 py-2 rounded-full
bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300">
<span class="text-lg">🏒</span>
<span class="font-semibold">Enterprise Execution</span>
<span class="text-xs opacity-75">Commercial</span>
</div>
<!-- Modern UI Badge -->
<div class="px-3 py-2 bg-purple-100 dark:bg-purple-900
text-purple-800 dark:text-purple-300 rounded-full text-sm font-medium">
Modern UI v{version_display}
</div>
<!-- Psychological Components Badge -->
<div class="px-3 py-2 bg-amber-100 dark:bg-amber-900
text-amber-800 dark:text-amber-300 rounded-full text-sm font-medium">
🧠 Psychological UX
</div>
</div>
<!-- Status Indicators -->
<div class="flex justify-center gap-4 text-sm text-gray-500 dark:text-gray-400">
<span class="flex items-center gap-1">
<span class="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
System Ready
</span>
<span>β€’</span>
<span>Modern Components: {'βœ… Active' if MODERN_COMPONENTS_AVAILABLE else '⚠️ Fallback'}</span>
<span>β€’</span>
<span>Performance Budget: OK</span>
</div>
</div>
</header>
"""
@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"""
<div class="metric-card text-center p-6 rounded-xl bg-white dark:bg-gray-800
border border-gray-200 dark:border-gray-700 hover:shadow-md transition-shadow">
{f'<div class="text-3xl mb-3">{icon}</div>' if icon else ''}
<div class="text-4xl font-bold text-gray-900 dark:text-white mb-2">{safe_value}</div>
<div class="text-sm text-gray-600 dark:text-gray-300 mb-1">{safe_label}</div>
{f'<div class="text-sm {trend_class}">{trend_icon}</div>' if trend else ''}
</div>
"""
@staticmethod
def create_scenario_dropdown() -> str:
"""Create validated scenario dropdown"""
options_html = ""
for scenario in InputValidator.SCENARIO_WHITELIST:
options_html += f'<option value="{scenario}">{scenario}</option>'
return f"""
<div class="scenario-selector">
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Select Incident Scenario
</label>
<select class="w-full p-3 border border-gray-300 dark:border-gray-600
rounded-lg bg-white dark:bg-gray-800
text-gray-900 dark:text-gray-100"
onchange="handleScenarioChange(this)">
{options_html}
</select>
<p class="text-xs text-gray-500 dark:text-gray-500 mt-1">
Validated scenarios only β€’ Telemetry active
</p>
</div>
<script>
function handleScenarioChange(select) {{
const scenario = select.value;
console.log('Scenario selected:', scenario);
// In production, this would trigger Gradio update
}}
</script>
"""
# ===========================================
# ENHANCED MAIN APPLICATION
# ===========================================
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
# Track initialization
telemetry.track_event("app_initialization_started")
start_time = time.time()
# Load optimized CSS with modern components
css_content = PerformanceBudget.measure_execution_time(load_css_files, "css_loading")()
# Create the main interface
with gr.Blocks(
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'''
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Agentic Reliability Framework v3.3.9 - Enhanced with modern psychological components">
<script>
// Initialize app state
window.appState = {{
sessionStart: "{datetime.datetime.now().isoformat()}",
telemetryEnabled: {str(is_feature_enabled('telemetry')).lower()},
modernComponents: {str(MODERN_COMPONENTS_AVAILABLE).lower()},
features: {json.dumps(FEATURE_FLAGS)}
}};
// Dark mode toggle
function toggleDarkMode() {{
const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
const icon = document.getElementById('darkModeIcon');
icon.textContent = newTheme === 'dark' ? 'β˜€οΈ' : 'πŸŒ™';
// Track usage
if (window.appState.telemetryEnabled) {{
console.log('Dark mode toggled:', newTheme);
}}
}}
// Initialize theme
document.addEventListener('DOMContentLoaded', function() {{
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const savedTheme = localStorage.getItem('theme');
const theme = savedTheme || (prefersDark ? 'dark' : 'light');
document.documentElement.setAttribute('data-theme', theme);
const icon = document.getElementById('darkModeIcon');
if (icon) {{
icon.textContent = theme === 'dark' ? 'β˜€οΈ' : 'πŸŒ™';
}}
}});
</script>
'''
) as demo:
# ===========================================
# INITIALIZATION
# ===========================================
# Dark mode toggle
dark_mode_html = """
<div id="darkModeToggle" class="fixed bottom-6 right-6 z-50">
<button onclick="toggleDarkMode()"
class="w-12 h-12 rounded-full bg-white dark:bg-gray-800
shadow-lg border border-gray-200 dark:border-gray-700
flex items-center justify-center text-xl hover:scale-110
transition-all duration-300"
aria-label="Toggle dark mode">
<span id="darkModeIcon">πŸŒ™</span>
</button>
</div>
"""
gr.HTML(dark_mode_html)
# ===========================================
# ENHANCED HEADER
# ===========================================
gr.HTML(ModernUI.create_header("3.3.9"))
# ===========================================
# TELEMETRY STATUS INDICATOR
# ===========================================
gr.HTML(f"""
<div class="container mx-auto mb-6">
<div class="flex flex-wrap gap-2 justify-center">
<span class="px-3 py-1 bg-green-100 dark:bg-green-900 text-green-800 dark:text-green-300
rounded-full text-xs font-medium">
βœ… Modern UI: {'Active' if MODERN_COMPONENTS_AVAILABLE else 'Fallback'}
</span>
<span class="px-3 py-1 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-300
rounded-full text-xs font-medium">
πŸ“Š Telemetry: Session {telemetry._session_id[:8]}...
</span>
<span class="px-3 py-1 bg-purple-100 dark:bg-purple-900 text-purple-800 dark:text-purple-300
rounded-full text-xs font-medium">
🧠 Psychological Components
</span>
<span class="px-3 py-1 bg-amber-100 dark:bg-amber-900 text-amber-800 dark:text-amber-300
rounded-full text-xs font-medium">
⚑ Performance Budget: OK
</span>
</div>
</div>
""")
# ===========================================
# MAIN CONTENT CONTAINER
# ===========================================
with gr.Column(elem_classes="container mx-auto px-4"):
# ===========================================
# TAB NAVIGATION WITH STATE MANAGEMENT
# ===========================================
with gr.Tabs(elem_classes="modern-tabs") as tabs:
# 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 ""
tabs.select(on_tab_change)
# 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("<div class='mb-2 text-sm text-gray-600 dark:text-gray-400'>Validated scenarios only:</div>")
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("""
<div class="validation-feedback text-xs text-gray-500 dark:text-gray-500 mt-1">
βœ“ Scenario validated β€’ βœ“ Input sanitized β€’ βœ“ Telemetry active
</div>
""")
# ===========================================
# MODERN PSYCHOLOGICAL COMPONENTS SECTION
# ===========================================
# Historical Evidence Panel (Recall Dominance)
gr.HTML("<h3 class='text-xl font-semibold text-gray-900 dark:text-white mb-4'>🧠 Historical Evidence Dominance</h3>")
# 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("<h3 class='text-xl font-semibold text-gray-900 dark:text-white mb-4'>⏳ Psychological Restraint System</h3>")
observation_gate_html = gr.HTML()
# Sequencing Visualization
gr.HTML("<h3 class='text-xl font-semibold text-gray-900 dark:text-white mb-4'>πŸ”„ Policy Sequencing Logic</h3>")
sequencing_html = gr.HTML()
# Process Workflow
gr.HTML("<h3 class='text-xl font-semibold text-gray-900 dark:text-white mb-4'>πŸ” Policy Process Workflow</h3>")
# 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("<h3 class='text-xl font-semibold text-gray-900 dark:text-white mb-4'>πŸ“ Formal HealingIntent</h3>")
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("""
<h3 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">
πŸ“ˆ Enhanced Performance Metrics
</h3>
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
""")
# 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))
gr.HTML("</div>")
# OSS vs Enterprise with Modern Components
gr.HTML("""
<h3 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">
πŸ—οΈ Modern Architecture Boundary
</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
""")
# 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("</div>")
# 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"""
<div class="state-display text-sm">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<h4 class="font-semibold mb-2">Psychological State:</h4>
<pre class="text-xs bg-gray-100 dark:bg-gray-800 p-2 rounded">
{json.dumps(psych_state, indent=2)}
</pre>
</div>
<div>
<h4 class="font-semibold mb-2">Modern Components:</h4>
<pre class="text-xs bg-gray-100 dark:bg-gray-800 p-2 rounded">
{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)}
</pre>
</div>
</div>
</div>
"""
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"""
<div class="roi-results p-4 bg-white dark:bg-gray-800 rounded-lg border">
<h4 class="font-semibold text-lg mb-3">πŸ“Š ROI Analysis Results</h4>
<div class="grid grid-cols-2 gap-4">
<div class="text-center">
<div class="text-2xl font-bold text-green-600">${potential_savings:,.0f}</div>
<div class="text-sm text-gray-600">Annual Savings</div>
</div>
<div class="text-center">
<div class="text-2xl font-bold text-blue-600">{roi_multiplier:.1f}x</div>
<div class="text-sm text-gray-600">ROI Multiplier</div>
</div>
</div>
<p class="text-xs text-gray-500 mt-3">
Based on {incidents_val} incidents/month β€’ Validated inputs β€’ Telemetry recorded
</p>
</div>
"""
return result_html, fig
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"""
<div class="modern-dashboard space-y-4">
<!-- Modern Features Status -->
<div class="feature-status p-4 bg-white dark:bg-gray-800 rounded-lg border">
<h4 class="font-semibold mb-3">πŸš€ Modern Integration Status</h4>
<div class="grid grid-cols-2 md:grid-cols-4 gap-3">
<div class="text-center p-2 bg-gray-50 dark:bg-gray-900 rounded">
<div class="text-sm font-medium">Modern Components</div>
<div class="text-lg font-bold {'text-green-600' if MODERN_COMPONENTS_AVAILABLE else 'text-yellow-600'}">
{'βœ…' if MODERN_COMPONENTS_AVAILABLE else '⚠️'}
</div>
</div>
<div class="text-center p-2 bg-gray-50 dark:bg-gray-900 rounded">
<div class="text-sm font-medium">Psychological Usage</div>
<div class="text-lg font-bold text-blue-600">{psych_usage_rate:.1f}%</div>
</div>
<div class="text-center p-2 bg-gray-50 dark:bg-gray-900 rounded">
<div class="text-sm font-medium">CSS Size</div>
<div class="text-lg font-bold text-green-600">{len(css_content)/1024:.1f}KB</div>
</div>
<div class="text-center p-2 bg-gray-50 dark:bg-gray-900 rounded">
<div class="text-sm font-medium">Components Tracked</div>
<div class="text-lg font-bold text-purple-600">{optimization_stats.get('tracked_components', 0)}</div>
</div>
</div>
</div>
<!-- Psychological Insights -->
<div class="psych-insights p-4 bg-white dark:bg-gray-800 rounded-lg border">
<h4 class="font-semibold mb-3">🧠 Psychological Component Insights</h4>
<div class="grid grid-cols-2 gap-3">
"""
# 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"""
<div class="text-center p-2 bg-gray-50 dark:bg-gray-900 rounded">
<div class="text-sm font-medium">{component.replace('_', ' ').title()}</div>
<div class="text-lg font-bold">{component_events}</div>
</div>
"""
status_html += """
</div>
</div>
</div>
"""
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"""
<footer class="footer mt-12 pt-8 border-t border-gray-200 dark:border-gray-800">
<div class="container mx-auto px-4">
<!-- Modern Stats Bar -->
<div class="mb-6 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg">
<div class="grid grid-cols-2 md:grid-cols-6 gap-4 text-center">
<div>
<div class="text-2xl font-bold text-blue-600">{app_state.get('user_interactions', 0)}</div>
<div class="text-sm text-gray-600">User Interactions</div>
</div>
<div>
<div class="text-2xl font-bold text-green-600">{app_state.get('analysis_count', 0)}</div>
<div class="text-sm text-gray-600">Modern Analyses</div>
</div>
<div>
<div class="text-2xl font-bold text-purple-600">{app_state.get('execution_count', 0)}</div>
<div class="text-sm text-gray-600">Executions</div>
</div>
<div>
<div class="text-2xl font-bold text-amber-600">{app_state.get('errors_count', 0)}</div>
<div class="text-sm text-gray-600">Errors</div>
</div>
<div>
<div class="text-2xl font-bold text-indigo-600">{'βœ…' if MODERN_COMPONENTS_AVAILABLE else '⚠️'}</div>
<div class="text-sm text-gray-600">Modern UI</div>
</div>
<div>
<div class="text-2xl font-bold text-teal-600">{app_state.get('confidence_level', 65):.0f}%</div>
<div class="text-sm text-gray-600">Confidence</div>
</div>
</div>
</div>
<!-- Main Footer -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-8 mb-8">
<div>
<h4 class="font-semibold text-gray-900 dark:text-white mb-4">Modern ARF v3.3.9</h4>
<p class="text-sm text-gray-600 dark:text-gray-400">
Complete Psychological Integration<br>
Modern UI Components Active<br>
Performance Budget: {len(css_content)/1024:.1f}KB / 50KB
</p>
</div>
<div>
<h4 class="font-semibold text-gray-900 dark:text-white mb-4">Modern Features</h4>
<div class="space-y-2">
<p class="text-sm text-gray-600 dark:text-gray-400">βœ… Modern Psychological Components</p>
<p class="text-sm text-gray-600 dark:text-gray-400">βœ… Design Tokens System</p>
<p class="text-sm text-gray-600 dark:text-gray-400">βœ… Historical Evidence Dominance</p>
<p class="text-sm text-gray-600 dark:text-gray-400">βœ… Observation Gate Restraint</p>
<p class="text-sm text-gray-600 dark:text-gray-400">βœ… Formal HealingIntent System</p>
<p class="text-sm text-gray-600 dark:text-gray-400">βœ… Performance Budgets</p>
</div>
</div>
<div>
<h4 class="font-semibold text-gray-900 dark:text-white mb-4">Modern Status</h4>
<div class="space-y-2">
<p class="text-sm text-gray-600 dark:text-gray-400">🟒 System: Modern Operational</p>
<p class="text-sm text-gray-600 dark:text-gray-400">🟒 Telemetry: Psychological Tracking</p>
<p class="text-sm text-gray-600 dark:text-gray-400">🟒 Validation: 100% Coverage</p>
<p class="text-sm text-gray-600 dark:text-gray-400">🟒 Performance: Optimal</p>
<p class="text-sm text-gray-600 dark:text-gray-400">Session: {telemetry._session_id[:8]}...</p>
</div>
</div>
</div>
<!-- Bottom Bar -->
<div class="py-4 border-t border-gray-200 dark:border-gray-800 text-center">
<p class="text-xs text-gray-500 dark:text-gray-500">
Β© 2024 ARF Technologies β€’ Modern Psychological Edition β€’
Session started: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')} β€’
<span id="live-timer">00:00</span>
</p>
</div>
</div>
</footer>
<!-- Live Timer Script -->
<script>
let startTime = new Date();
function updateTimer() {{
const now = new Date();
const diff = Math.floor((now - startTime) / 1000);
const minutes = Math.floor(diff / 60);
const seconds = diff % 60;
document.getElementById('live-timer').textContent =
minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0');
}}
setInterval(updateTimer, 1000);
updateTimer();
</script>
""")
# ===========================================
# INITIALIZATION COMPLETE
# ===========================================
# 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 (
historical_html, observation_html, sequencing_html,
detection_html, recall_html, decision_html, healing_html
)
# Load initial psychological components
demo.load(
initialize_psychological_components,
inputs=[],
outputs=[
historical_evidence_html, observation_gate_html, sequencing_html,
detection_html, recall_html, decision_html, healing_intent_html
]
)
# 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
# ===========================================
# ENHANCED MAIN EXECUTION
# ===========================================
def main():
"""Enhanced main entry point with modern integration"""
try:
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
port = int(os.getenv("GRADIO_SERVER_PORT", "7860"))
server_name = os.getenv("GRADIO_SERVER_NAME", "0.0.0.0")
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")
# Enable queue if needed (for concurrent requests)
demo.queue() # This enables the queue in Gradio 6.x
# Launch with enhanced configuration
demo.launch(
server_name=server_name,
server_port=port,
share=False,
debug=False,
show_error=True,
quiet=True
)
except KeyboardInterrupt:
print("\nπŸ‘‹ Modern demo stopped by user")
telemetry.track_event("modern_app_shutdown_user")
except Exception as e:
print(f"\n❌ Modern integration error: {e}")
telemetry.track_error(e, "modern_main_execution")
import traceback
traceback.print_exc()
sys.exit(1)
# ===========================================
# 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": "⚠️"}
]
}
# ===========================================
# MODERN SPACES ENTRY POINT
# ===========================================
if __name__ == "__main__":
# Enhanced configuration for Hugging Face Spaces
import os
# Environment configuration with validation
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
os.environ["GRADIO_SERVER_PORT"] = "7860"
os.environ["GRADIO_SERVER_NAME"] = "0.0.0.0"
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')
})
# 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()