diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,1950 +1,462 @@ """ šŸš€ ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION -With Audit Trail, Incident History, Memory Graph, and Enterprise Features -FIXED VERSION - No Plot Errors +Main entry point - Complex, comprehensive demo using actual OSS components """ import logging -import datetime -import random -import uuid -import json -import tempfile -from typing import Dict, List, Optional, Any, Tuple -from collections import deque -import gradio as gr -import plotly.graph_objects as go -import pandas as pd -import numpy as np -from plotly.subplots import make_subplots +import sys +import traceback +from pathlib import Path -# Import ARF OSS if available -try: - from agentic_reliability_framework.arf_core.models.healing_intent import ( - HealingIntent, - create_scale_out_intent - ) - from agentic_reliability_framework.arf_core.engine.simple_mcp_client import OSSMCPClient - ARF_OSS_AVAILABLE = True -except ImportError: - ARF_OSS_AVAILABLE = False - # Mock classes for demo - class HealingIntent: - def __init__(self, **kwargs): - self.intent_type = kwargs.get("intent_type", "scale_out") - self.parameters = kwargs.get("parameters", {}) - - def to_dict(self) -> Dict[str, Any]: - return { - "intent_type": self.intent_type, - "parameters": self.parameters, - "created_at": datetime.datetime.now().isoformat() - } - - def create_scale_out_intent(resource_type: str, scale_factor: float = 2.0) -> HealingIntent: - return HealingIntent( - intent_type="scale_out", - parameters={ - "resource_type": resource_type, - "scale_factor": scale_factor, - "action": "Increase capacity" - } - ) - - class OSSMCPClient: - def analyze_incident(self, metrics: Dict, pattern: str = "") -> Dict[str, Any]: - return { - "status": "analysis_complete", - "recommendations": [ - "Increase resource allocation", - "Implement monitoring", - "Add circuit breakers", - "Optimize configuration" - ], - "confidence": 0.92 - } +# Add parent directory to path for OSS imports +sys.path.insert(0, str(Path(__file__).parent.parent)) -# Configure logging -logging.basicConfig(level=logging.INFO) +# Configure logging first +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + handlers=[ + logging.StreamHandler(), + logging.FileHandler('arf_demo.log') + ] +) logger = logging.getLogger(__name__) -# =========================================== -# COMPREHENSIVE DATA -# =========================================== - -INCIDENT_SCENARIOS = { - "Cache Miss Storm": { - "description": "Redis cluster experiencing 80% cache miss rate causing database overload", - "severity": "CRITICAL", - "metrics": { - "Cache Hit Rate": "18.5% (Critical)", - "Database Load": "92% (Overloaded)", - "Response Time": "1850ms (Slow)", - "Affected Users": "45,000", - "Eviction Rate": "125/sec" - }, - "impact": { - "Revenue Loss": "$8,500/hour", - "Page Load Time": "+300%", - "Users Impacted": "45,000", - "SLA Violation": "Yes", - "Customer Sat": "-40%" - }, - "oss_analysis": { - "status": "āœ… ARF OSS Analysis Complete", - "recommendations": [ - "Increase Redis cache memory allocation", - "Implement cache warming strategy", - "Optimize key patterns (TTL adjustments)", - "Add circuit breaker for database fallback", - "Deploy monitoring for cache hit rate trends" - ], - "estimated_time": "60+ minutes", - "engineers_needed": "2-3 SREs + 1 DBA", - "manual_effort": "High", - "total_cost": "$8,500", - "healing_intent": "scale_out_cache" - }, - "enterprise_results": { - "actions_completed": [ - "āœ… Auto-scaled Redis cluster: 4GB → 8GB", - "āœ… Deployed intelligent cache warming service", - "āœ… Optimized 12 key patterns with ML recommendations", - "āœ… Implemented circuit breaker with 95% success rate", - "āœ… Validated recovery with automated testing" - ], - "metrics_improvement": { - "Cache Hit Rate": "18.5% → 72%", - "Response Time": "1850ms → 450ms", - "Database Load": "92% → 45%", - "Throughput": "1250 → 2450 req/sec" - }, - "business_impact": { - "Recovery Time": "60 min → 12 min", - "Cost Saved": "$7,200", - "Users Impacted": "45,000 → 0", - "Revenue Protected": "$1,700", - "MTTR Improvement": "80% reduction" - } - } - }, - "Database Connection Pool Exhaustion": { - "description": "Database connection pool exhausted causing API timeouts and user failures", - "severity": "HIGH", - "metrics": { - "Active Connections": "98/100 (Critical)", - "API Latency": "2450ms", - "Error Rate": "15.2%", - "Queue Depth": "1250", - "Connection Wait": "45s" - }, - "impact": { - "Revenue Loss": "$4,200/hour", - "Affected Services": "API Gateway, User Service, Payment", - "SLA Violation": "Yes", - "Partner Impact": "3 external APIs" - } - }, - "Memory Leak in Production": { - "description": "Java service memory leak causing gradual performance degradation", - "severity": "HIGH", - "metrics": { - "Memory Usage": "96% (Critical)", - "GC Pause Time": "4500ms", - "Error Rate": "28.5%", - "Restart Frequency": "12/hour", - "Heap Fragmentation": "42%" - }, - "impact": { - "Revenue Loss": "$5,500/hour", - "Session Loss": "8,500 users", - "Customer Impact": "High", - "Support Tickets": "+300%" - } - }, - "API Rate Limit Exceeded": { - "description": "Global API rate limit exceeded causing 429 errors for external clients", - "severity": "MEDIUM", - "metrics": { - "429 Error Rate": "42.5%", - "Successful Requests": "58.3%", - "API Latency": "120ms", - "Queue Depth": "1250", - "Client Satisfaction": "65/100" - }, - "impact": { - "Revenue Loss": "$1,800/hour", - "Affected Partners": "8", - "Partner SLA Violations": "3", - "Business Impact": "Medium" - } - }, - "Microservice Cascading Failure": { - "description": "Order service failure causing cascading failures in dependent services", - "severity": "CRITICAL", - "metrics": { - "Order Failure Rate": "68.2%", - "Circuit Breakers Open": "4", - "Retry Storm Intensity": "425", - "Error Propagation": "85%", - "System Stability": "15/100" - }, - "impact": { - "Revenue Loss": "$25,000/hour", - "Abandoned Carts": "12,500", - "Affected Users": "75,000", - "Brand Damage": "High" - } - } -} - -# =========================================== -# AUDIT TRAIL & HISTORY MANAGEMENT -# =========================================== - -class AuditTrailManager: - """Manage audit trail and execution history""" - - def __init__(self) -> None: - self.execution_history = deque(maxlen=50) - self.incident_history = deque(maxlen=100) - self._initialize_sample_data() - - def _initialize_sample_data(self) -> None: - """Initialize with sample historical data""" - base_time = datetime.datetime.now() - datetime.timedelta(hours=2) - - # Sample execution history - sample_executions = [ - self._create_execution_entry( - base_time - datetime.timedelta(minutes=90), - "Cache Miss Storm", 4, 7200, "āœ… Executed", "Auto-scaled cache" - ), - self._create_execution_entry( - base_time - datetime.timedelta(minutes=75), - "Memory Leak", 3, 5200, "āœ… Executed", "Fixed memory leak" - ), - self._create_execution_entry( - base_time - datetime.timedelta(minutes=60), - "API Rate Limit", 4, 2800, "āœ… Executed", "Increased rate limits" - ), - self._create_execution_entry( - base_time - datetime.timedelta(minutes=45), - "DB Connection Pool", 4, 3800, "āœ… Executed", "Scaled connection pool" - ), - self._create_execution_entry( - base_time - datetime.timedelta(minutes=30), - "Cascading Failure", 5, 12500, "āœ… Executed", "Isolated services" - ), - self._create_execution_entry( - base_time - datetime.timedelta(minutes=15), - "Cache Miss Storm", 4, 7200, "āœ… Executed", "Optimized cache" - ) - ] - - for execution in sample_executions: - self.execution_history.append(execution) - - # Sample incident history - services = ["API Gateway", "Database", "Cache", "Auth Service", "Payment Service", - "Order Service", "User Service", "Session Service"] - - for _ in range(25): - incident_time = base_time - datetime.timedelta(minutes=random.randint(5, 120)) - self.incident_history.append({ - "timestamp": incident_time, - "time_str": incident_time.strftime("%H:%M"), - "service": random.choice(services), - "type": random.choice(list(INCIDENT_SCENARIOS.keys())), - "severity": random.randint(1, 3), - "description": f"{random.choice(['High latency', 'Connection failed', 'Memory spike', 'Timeout'])} on {random.choice(services)}", - "id": str(uuid.uuid4())[:8] - }) - - def _create_execution_entry(self, timestamp: datetime.datetime, scenario: str, - actions: int, savings: int, status: str, details: str) -> Dict[str, Any]: - """Create an execution history entry""" - return { - "timestamp": timestamp, - "time_str": timestamp.strftime("%H:%M"), - "scenario": scenario, - "actions": str(actions), - "savings": f"${savings:,}", - "status": status, - "details": details, - "id": str(uuid.uuid4())[:8] - } - - def add_execution(self, scenario: str, actions: List[str], - savings: int, approval_required: bool, details: str = "") -> Dict[str, Any]: - """Add new execution to history""" - entry = self._create_execution_entry( - datetime.datetime.now(), - scenario, - len(actions), - savings, - "āœ… Approved & Executed" if approval_required else "āœ… Auto-Executed", - details - ) - self.execution_history.appendleft(entry) # Newest first - return entry - - def add_incident(self, scenario_name: str, metrics: Dict) -> Dict[str, Any]: - """Add incident to history""" - severity = 2 if "MEDIUM" in INCIDENT_SCENARIOS.get(scenario_name, {}).get("severity", "") else 3 - entry = { - "timestamp": datetime.datetime.now(), - "time_str": datetime.datetime.now().strftime("%H:%M"), - "service": "Demo System", - "type": scenario_name, - "severity": severity, - "description": f"Demo incident: {scenario_name}", - "id": str(uuid.uuid4())[:8] - } - self.incident_history.appendleft(entry) - return entry - - def get_execution_history_table(self, limit: int = 10) -> List[List[str]]: - """Get execution history for table display""" - return [ - [entry["time_str"], entry["scenario"], entry["actions"], - entry["status"], entry["savings"], entry["details"]] - for entry in list(self.execution_history)[:limit] - ] - - def get_incident_history_table(self, limit: int = 15) -> List[List[str]]: - """Get incident history for table display""" - return [ - [entry["time_str"], entry["service"], entry["type"], - f"{entry['severity']}/3", entry["description"]] - for entry in list(self.incident_history)[:limit] - ] - - def clear_history(self) -> Tuple[List[List[str]], List[List[str]]]: - """Clear all history""" - self.execution_history.clear() - self.incident_history.clear() - self._initialize_sample_data() # Restore sample data - return self.get_execution_history_table(), self.get_incident_history_table() - - def export_audit_trail(self) -> str: - """Export audit trail as JSON""" - total_savings = 0 - for e in self.execution_history: - if "$" in e["savings"]: - try: - total_savings += int(e["savings"].replace("$", "").replace(",", "")) - except ValueError: - continue - - return json.dumps({ - "executions": list(self.execution_history), - "incidents": list(self.incident_history), - "exported_at": datetime.datetime.now().isoformat(), - "total_executions": len(self.execution_history), - "total_incidents": len(self.incident_history), - "total_savings": total_savings - }, indent=2, default=str) - -# =========================================== -# ENHANCED VISUALIZATION ENGINE (FIXED) -# =========================================== - -class EnhancedVisualizationEngine: - """Enhanced visualization engine with memory graph support""" - - @staticmethod - def create_incident_timeline() -> go.Figure: - """Create interactive incident timeline""" - fig = go.Figure() - - # Create timeline events - now = datetime.datetime.now() - events = [ - {"time": now - datetime.timedelta(minutes=25), "event": "šŸ“‰ Cache hit rate drops to 18.5%", "type": "problem"}, - {"time": now - datetime.timedelta(minutes=22), "event": "āš ļø Alert: Database load hits 92%", "type": "alert"}, - {"time": now - datetime.timedelta(minutes=20), "event": "šŸ¤– ARF detects pattern", "type": "detection"}, - {"time": now - datetime.timedelta(minutes=18), "event": "🧠 Analysis: Cache Miss Storm identified", "type": "analysis"}, - {"time": now - datetime.timedelta(minutes=15), "event": "⚔ Healing actions executed", "type": "action"}, - {"time": now - datetime.timedelta(minutes=12), "event": "āœ… Cache hit rate recovers to 72%", "type": "recovery"}, - {"time": now - datetime.timedelta(minutes=10), "event": "šŸ“Š System stabilized", "type": "stable"} - ] - - color_map = { - "problem": "red", "alert": "orange", "detection": "blue", - "analysis": "purple", "action": "green", "recovery": "lightgreen", - "stable": "darkgreen" - } - - symbol_map = { - "problem": "circle", "alert": "circle", "detection": "diamond", - "analysis": "diamond", "action": "square", "recovery": "star", - "stable": "cross" - } - - # Convert datetime objects to strings for Plotly - times = [event["time"] for event in events] - events_text = [event["event"] for event in events] - event_types = [event["type"] for event in events] - colors = [color_map[event_type] for event_type in event_types] - symbols = [symbol_map[event_type] for event_type in event_types] - - fig.add_trace(go.Scatter( - x=times, - y=[1] * len(events), # Fixed y-position - mode='markers+text', - marker=dict( - size=20, - color=colors, - symbol=symbols, - line=dict(width=2, color='white') - ), - text=events_text, - textposition="top center", - hoverinfo="text", - hovertemplate="%{text}
%{x|%H:%M:%S}", - name="Timeline Events" - )) - - # Add connecting lines - for i in range(len(times) - 1): - fig.add_trace(go.Scatter( - x=[times[i], times[i + 1]], - y=[1, 1], - mode='lines', - line=dict(color='gray', width=1, dash='dash'), - showlegend=False, - hoverinfo='none' - )) - - fig.update_layout( - title="Incident Timeline - Cache Miss Storm Resolution", - xaxis_title="Time →", - yaxis=dict( - title="Event Type", - showticklabels=False, - range=[0.5, 1.5] # Fixed range for better display - ), - height=450, - showlegend=False, - paper_bgcolor='white', - plot_bgcolor='white', - hovermode='closest', - xaxis=dict( - tickformat='%H:%M', - gridcolor='rgba(200,200,200,0.2)', - showgrid=True - ), - yaxis_showgrid=False, - margin=dict(l=50, r=50, t=80, b=50) - ) - - return fig - - @staticmethod - def create_business_dashboard() -> go.Figure: - """Create executive business dashboard""" - fig = make_subplots( - rows=2, cols=2, - subplot_titles=('Annual Cost Impact', 'Team Capacity Shift', - 'MTTR Comparison', 'ROI Analysis'), - vertical_spacing=0.15, - horizontal_spacing=0.15 - ) - - # 1. Cost Impact - categories = ['Without ARF', 'With ARF Enterprise', 'Net Savings'] - values = [2960000, 1000000, 1960000] - - fig.add_trace( - go.Bar( - x=categories, - y=values, - marker_color=['#FF6B6B', '#4ECDC4', '#45B7D1'], - text=[f'${v/1000000:.1f}M' for v in values], - textposition='auto', - name='Cost Impact' - ), - row=1, col=1 - ) - - # 2. Team Capacity Shift - labels = ['Firefighting', 'Innovation', 'Strategic Work'] - before = [60, 20, 20] - after = [10, 60, 30] - - fig.add_trace( - go.Bar( - x=labels, - y=before, - name='Before ARF', - marker_color='#FF6B6B' - ), - row=1, col=2 - ) - - fig.add_trace( - go.Bar( - x=labels, - y=after, - name='After ARF Enterprise', - marker_color='#4ECDC4' - ), - row=1, col=2 - ) - - # 3. MTTR Comparison - mttr_categories = ['Manual', 'Traditional', 'ARF OSS', 'ARF Enterprise'] - mttr_values = [120, 45, 25, 8] - - fig.add_trace( - go.Bar( - x=mttr_categories, - y=mttr_values, - marker_color=['#FF6B6B', '#FFE66D', '#45B7D1', '#4ECDC4'], - text=[f'{v} min' for v in mttr_values], - textposition='auto', - name='MTTR' - ), - row=2, col=1 - ) - - # 4. ROI Gauge - fig.add_trace( - go.Indicator( - mode="gauge+number+delta", - value=5.2, - title={'text': "ROI Multiplier"}, - delta={'reference': 1.0, 'increasing': {'color': "green"}}, - gauge={ - 'axis': {'range': [0, 10], 'tickwidth': 1}, - 'bar': {'color': "#4ECDC4"}, - 'steps': [ - {'range': [0, 2], 'color': "lightgray"}, - {'range': [2, 4], 'color': "gray"}, - {'range': [4, 6], 'color': "lightgreen"}, - {'range': [6, 10], 'color': "green"} - ], - 'threshold': { - 'line': {'color': "red", 'width': 4}, - 'thickness': 0.75, - 'value': 5.2 +try: + # Import demo modules + from demo.core.data_models import ( + IncidentSeverity, Incident, AuditEntry, + EnterpriseLicense, MCPServerConfig + ) + from demo.core.audit_trail import AuditTrailManager + from demo.business.logic import EnhancedBusinessLogic + from demo.business.roi_calculator import ROICalculator + from demo.visualization.engine import EnhancedVisualizationEngine + from demo.ui.components import create_all_tabs + from demo.ui.event_handlers import register_all_handlers + from demo.integration.oss_integration import OSSIntegrationManager + + # Try to import actual OSS components + try: + from agentic_reliability_framework.arf_core.models.healing_intent import ( + HealingIntent, create_scale_out_intent, create_rollback_intent + ) + from agentic_reliability_framework.arf_core.engine.simple_mcp_client import OSSMCPClient + from agentic_reliability_framework.engine.mcp_server import MCPServer, MCPMode + ARF_OSS_AVAILABLE = True + OSS_VERSION = "3.3.6" + logger.info(f"āœ… Successfully imported ARF OSS v{OSS_VERSION}") + + except ImportError as e: + logger.warning(f"Failed to import ARF OSS: {e}") + ARF_OSS_AVAILABLE = False + OSS_VERSION = "Mock 3.3.6" + + # Mock classes for demo + class HealingIntent: + def __init__(self, action, component, parameters, **kwargs): + self.action = action + self.component = component + self.parameters = parameters + self.justification = kwargs.get('justification', '') + self.confidence = kwargs.get('confidence', 0.85) + self.similar_incidents = kwargs.get('similar_incidents', []) + self.rag_similarity_score = kwargs.get('rag_similarity_score') + + def to_enterprise_request(self): + return { + 'action': self.action, + 'component': self.component, + 'parameters': self.parameters, + 'justification': self.justification, + 'confidence': self.confidence, + 'requires_enterprise': True, + 'oss_metadata': { + 'similar_incidents_count': len(self.similar_incidents), + 'rag_used': self.rag_similarity_score is not None } } - ), - row=2, col=2 - ) - - fig.update_layout( - height=700, - showlegend=True, - paper_bgcolor='white', - plot_bgcolor='white', - title_text="Executive Business Dashboard", - barmode='group', - margin=dict(l=50, r=50, t=100, b=50) - ) - - # Update axes - fig.update_xaxes(title_text="Scenario", row=1, col=1) - fig.update_yaxes(title_text="Cost ($)", row=1, col=1) - fig.update_xaxes(title_text="Activity", row=1, col=2) - fig.update_yaxes(title_text="Percentage (%)", row=1, col=2) - fig.update_xaxes(title_text="Approach", row=2, col=1) - fig.update_yaxes(title_text="MTTR (minutes)", row=2, col=1) - - return fig - - @staticmethod - def create_execution_history_chart(audit_manager: AuditTrailManager) -> go.Figure: - """Create execution history visualization""" - executions = list(audit_manager.execution_history)[:10] # Last 10 executions - - if not executions: - fig = go.Figure() - fig.update_layout( - title="No execution history yet", - height=400, - paper_bgcolor='white', - plot_bgcolor='white', - xaxis_showgrid=True, - yaxis_showgrid=True - ) - return fig - - # Extract data - scenarios = [e["scenario"] for e in executions] - savings = [] - for e in executions: - try: - savings.append(int(e["savings"].replace("$", "").replace(",", ""))) - except ValueError: - savings.append(0) - - fig = go.Figure(data=[ - go.Bar( - x=scenarios, - y=savings, - marker_color='#4ECDC4', - text=[f'${s:,.0f}' for s in savings], - textposition='outside', - name='Cost Saved', - hovertemplate="%{x}
Savings: %{text}" - ) - ]) - - fig.update_layout( - title="Execution History - Cost Savings", - xaxis_title="Scenario", - yaxis_title="Cost Saved ($)", - height=500, - paper_bgcolor='white', - plot_bgcolor='white', - showlegend=False, - xaxis_showgrid=True, - yaxis_showgrid=True, - margin=dict(l=50, r=50, t=80, b=100) - ) - - # Rotate x-axis labels if needed - if len(scenarios) > 5: - fig.update_xaxes(tickangle=45) - - return fig - - @staticmethod - def create_memory_graph(audit_manager: AuditTrailManager, graph_type: str = "Force Directed", - show_weights: bool = True, auto_layout: bool = True) -> go.Figure: - """Create interactive memory graph visualization""" - fig = go.Figure() - - # Get incidents from history - incidents = list(audit_manager.incident_history)[:20] # Last 20 incidents - - if not incidents: - # Create a simple placeholder graph - fig.add_trace(go.Scatter( - x=[0, 1, 0.5], - y=[0, 0, 0.866], - mode='markers+text', - marker=dict( - size=[30, 20, 20], - color=['#FF6B6B', '#4ECDC4', '#45B7D1'] - ), - text=['Incident', 'Action', 'Outcome'], - textposition="top center" - )) - - # Add edges - fig.add_trace(go.Scatter( - x=[0, 0.5, 1], - y=[0, 0.866, 0], - mode='lines', - line=dict(color='gray', width=2), - hoverinfo='none' - )) - - fig.update_layout( - title="Incident Memory Graph (Sample)", - showlegend=False, - height=600, - paper_bgcolor='white', - plot_bgcolor='white', - xaxis=dict(showgrid=False, zeroline=False, showticklabels=False, range=[-0.2, 1.2]), - yaxis=dict(showgrid=False, zeroline=False, showticklabels=False, range=[-0.2, 1.2]), - margin=dict(l=20, r=20, t=60, b=20) - ) - return fig - - # Create nodes from actual incidents - nodes = [] - edges = [] - - for i, incident in enumerate(incidents): - node_id = f"Incident_{i}" - nodes.append({ - "id": node_id, - "label": incident["type"][:20], - "type": "incident", - "size": 15 + (incident.get("severity", 2) * 5), - "severity": incident.get("severity", 2) - }) - - # Create edges to previous incidents - if i > 0 and i % 3 == 0: # Connect every 3rd incident - prev_id = f"Incident_{i-1}" - edges.append({ - "source": prev_id, - "target": node_id, - "weight": 0.7, - "label": "related_to" - }) - - # Color mapping - color_map = { - "incident": "#FF6B6B", - "action": "#4ECDC4", - "outcome": "#45B7D1", - "component": "#96CEB4" - } - - # Calculate positions (circular layout) - num_nodes = len(nodes) - if num_nodes > 0: - angles = np.linspace(0, 2 * np.pi, num_nodes, endpoint=False) - radius = 1.0 - node_x = radius * np.cos(angles) - node_y = radius * np.sin(angles) - - # Add nodes - fig.add_trace(go.Scatter( - x=node_x, - y=node_y, - mode='markers+text', - marker=dict( - size=[node.get("size", 15) for node in nodes], - color=[color_map.get(node.get("type", "incident"), "#999999") for node in nodes], - line=dict(width=2, color='white') - ), - text=[node["label"] for node in nodes], - textposition="top center", - hovertext=[f"Type: {node['type']}
Severity: {node.get('severity', 'N/A')}" for node in nodes], - hoverinfo="text", - name="Nodes" - )) - - # Add edges if we have them - if edges: - for edge in edges: - try: - source_idx = int(edge["source"].split("_")[1]) - target_idx = int(edge["target"].split("_")[1]) - - if source_idx < num_nodes and target_idx < num_nodes: - fig.add_trace(go.Scatter( - x=[node_x[source_idx], node_x[target_idx], None], - y=[node_y[source_idx], node_y[target_idx], None], - mode='lines', - line=dict( - width=2 * edge.get("weight", 1.0), - color='rgba(100, 100, 100, 0.5)' - ), - hoverinfo='none', - showlegend=False - )) - except (ValueError, IndexError): - continue - - fig.update_layout( - title=f"Incident Memory Graph ({len(nodes)} nodes)", - showlegend=False, - height=600, - paper_bgcolor='white', - plot_bgcolor='white', - hovermode='closest', - xaxis=dict( - showgrid=False, - zeroline=False, - showticklabels=False, - range=[-1.5, 1.5] - ), - yaxis=dict( - showgrid=False, - zeroline=False, - showticklabels=False, - range=[-1.5, 1.5] - ), - margin=dict(l=50, r=50, t=80, b=50) - ) - - return fig - - @staticmethod - def create_pattern_analysis_chart(analysis_data: Dict[str, Any]) -> go.Figure: - """Create pattern analysis visualization""" - fig = make_subplots( - rows=2, cols=2, - subplot_titles=('Incident Frequency', 'Resolution Times', - 'Success Rates', 'Pattern Correlation'), - vertical_spacing=0.15, - horizontal_spacing=0.15 - ) - - # Sample data - in real app this would come from analysis - patterns = ['Cache Issues', 'DB Connections', 'Memory Leaks', 'API Limits', 'Cascading'] - frequencies = [12, 8, 5, 7, 3] - resolution_times = [8.2, 15.5, 45.2, 5.1, 32.8] - success_rates = [92, 85, 78, 96, 65] - - # Incident Frequency - fig.add_trace( - go.Bar( - x=patterns, - y=frequencies, - name='Frequency', - marker_color='#4ECDC4' - ), - row=1, col=1 - ) - - # Resolution Times - fig.add_trace( - go.Bar( - x=patterns, - y=resolution_times, - name='Resolution Time (min)', - marker_color='#45B7D1' - ), - row=1, col=2 - ) - - # Success Rates - fig.add_trace( - go.Bar( - x=patterns, - y=success_rates, - name='Success Rate %', - marker_color='#96CEB4' - ), - row=2, col=1 - ) - - # Correlation Matrix - corr_matrix = np.array([ - [1.0, 0.3, 0.1, 0.2, 0.05], - [0.3, 1.0, 0.4, 0.1, 0.25], - [0.1, 0.4, 1.0, 0.05, 0.6], - [0.2, 0.1, 0.05, 1.0, 0.1], - [0.05, 0.25, 0.6, 0.1, 1.0] - ]) - - fig.add_trace( - go.Heatmap( - z=corr_matrix, - x=patterns, - y=patterns, - colorscale='Blues', - showscale=True - ), - row=2, col=2 - ) - - fig.update_layout( - height=700, - showlegend=False, - title_text="Pattern Analysis Dashboard", - paper_bgcolor='white', - plot_bgcolor='white' - ) - - # Update axes - fig.update_xaxes(title_text="Pattern Type", row=1, col=1) - fig.update_yaxes(title_text="Frequency", row=1, col=1) - fig.update_xaxes(title_text="Pattern Type", row=1, col=2) - fig.update_yaxes(title_text="Time (minutes)", row=1, col=2) - fig.update_xaxes(title_text="Pattern Type", row=2, col=1) - fig.update_yaxes(title_text="Success Rate (%)", row=2, col=1) - - return fig - -# =========================================== -# ENHANCED BUSINESS LOGIC -# =========================================== + + def mark_as_oss_advisory(self): + return self + + class OSSMCPClient: + def __init__(self): + self.mode = "advisory" + + async def analyze_and_recommend(self, tool_name, component, parameters, context=None): + return HealingIntent( + action=tool_name, + component=component, + parameters=parameters, + justification=f"OSS Analysis: {tool_name} recommended for {component}", + confidence=0.85, + similar_incidents=[ + {"id": "inc_001", "similarity": 0.78, "resolution": "scaled_out"}, + {"id": "inc_045", "similarity": 0.65, "resolution": "restarted"} + ], + rag_similarity_score=0.72 + ) + + class MCPServer: + def __init__(self, mode="advisory"): + self.mode = mode + + async def execute_tool(self, request_dict): + return { + 'status': 'advisory_completed', + 'message': 'Mock OSS analysis complete', + 'executed': False, + 'requires_enterprise': True + } + + MCPMode = type('MCPMode', (), {'ADVISORY': 'advisory', 'APPROVAL': 'approval', 'AUTONOMOUS': 'autonomous'}) -class EnhancedBusinessLogic: - """Enhanced business logic with enterprise features""" - - def __init__(self, audit_manager: AuditTrailManager): - self.audit_manager = audit_manager - self.viz_engine = EnhancedVisualizationEngine() - self.license_info = { - "valid": True, - "customer_name": "Demo Enterprise Corp", - "customer_email": "demo@enterprise.com", - "tier": "ENTERPRISE", - "expires_at": "2024-12-31T23:59:59", - "features": ["autonomous_healing", "compliance", "audit_trail", "multi_cloud"], - "max_services": 100, - "max_incidents_per_month": 1000, - "status": "āœ… Active" - } - self.mcp_mode = "approval" - self.learning_stats = { - "total_incidents": 127, - "resolved_automatically": 89, - "average_resolution_time": "8.2 min", - "success_rate": "92.1%", - "patterns_detected": 24, - "confidence_threshold": 0.85, - "memory_size": "4.7 MB", - "embeddings": 127, - "graph_nodes": 89, - "graph_edges": 245 - } - - def run_oss_analysis(self, scenario_name: str) -> Dict[str, Any]: - """Run OSS analysis""" - scenario = INCIDENT_SCENARIOS.get(scenario_name, {}) - analysis = scenario.get("oss_analysis", {}) - - if not analysis: - analysis = { - "status": "āœ… Analysis Complete", - "recommendations": [ - "Increase resource allocation", - "Implement monitoring", - "Add circuit breakers", - "Optimize configuration" - ], - "estimated_time": "45-60 minutes", - "engineers_needed": "2-3", - "manual_effort": "Required", - "total_cost": "$3,000 - $8,000" + # Import Gradio + import gradio as gr + import plotly.graph_objects as go + + def create_demo_interface(): + """Create the comprehensive demo interface""" + logger.info("Initializing ARF Demo Interface...") + + # Initialize components + audit_manager = AuditTrailManager() + oss_integration = OSSIntegrationManager( + oss_available=ARF_OSS_AVAILABLE, + oss_version=OSS_VERSION + ) + business_logic = EnhancedBusinessLogic( + audit_manager=audit_manager, + oss_integration=oss_integration + ) + roi_calculator = ROICalculator() + viz_engine = EnhancedVisualizationEngine() + + # Create Gradio interface + with gr.Blocks( + title=f"šŸš€ ARF Investor Demo v3.8.0", + theme=gr.themes.Soft( + primary_hue="blue", + secondary_hue="teal", + font=[gr.themes.GoogleFont("Inter"), "Arial", "sans-serif"] + ), + css=""" + .gradio-container { + max-width: 1800px !important; + margin: auto !important; + font-family: 'Inter', sans-serif !important; } - - # Add ARF context - analysis["arf_context"] = { - "oss_available": ARF_OSS_AVAILABLE, - "version": "3.3.6", - "mode": "advisory_only", - "healing_intent": True - } - - # Add to incident history - self.audit_manager.add_incident(scenario_name, scenario.get("metrics", {})) - - return analysis - - def execute_enterprise_healing(self, scenario_name: str, approval_required: bool) -> Tuple[Any, ...]: - """Execute enterprise healing""" - scenario = INCIDENT_SCENARIOS.get(scenario_name, {}) - results = scenario.get("enterprise_results", {}) - - # Use default results if not available - if not results: - results = { - "actions_completed": [ - "āœ… Auto-scaled resources based on ARF healing intent", - "āœ… Implemented optimization recommendations", - "āœ… Deployed monitoring and alerting", - "āœ… Validated recovery with automated testing" - ], - "metrics_improvement": { - "Performance": "Dramatically improved", - "Stability": "Restored", - "Recovery": "Complete" - }, - "business_impact": { - "Recovery Time": f"60 min → {random.randint(5, 15)} min", - "Cost Saved": f"${random.randint(2000, 10000):,}", - "Users Impacted": "45,000 → 0", - "Revenue Protected": f"${random.randint(1000, 5000):,}" - } + h1 { + background: linear-gradient(90deg, #1a365d 0%, #2d3748 100%); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + background-clip: text; + font-weight: 800 !important; + font-size: 2.5rem !important; + margin-bottom: 0.5rem !important; + } + .critical { + color: #FF6B6B !important; + font-weight: 900 !important; + text-shadow: 0 1px 2px rgba(0,0,0,0.1); + } + .success { + color: #4ECDC4 !important; + font-weight: 900 !important; + } + .plot-container { + background: white !important; + border-radius: 12px !important; + padding: 20px !important; + box-shadow: 0 4px 12px rgba(0,0,0,0.08) !important; + border: 1px solid #e2e8f0 !important; + } + .tab-nav { + background: linear-gradient(90deg, #f8fafc 0%, #ffffff 100%) !important; + border-radius: 10px !important; + padding: 5px !important; + margin-bottom: 20px !important; + } + .metric-card { + background: white !important; + border-radius: 10px !important; + padding: 20px !important; + box-shadow: 0 2px 8px rgba(0,0,0,0.06) !important; + border-left: 4px solid #4ECDC4 !important; + margin-bottom: 15px !important; + } + .enterprise-badge { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important; + color: white !important; + padding: 8px 16px !important; + border-radius: 20px !important; + font-weight: 700 !important; + font-size: 0.85rem !important; + display: inline-block !important; + margin: 5px 0 !important; + } + .oss-badge { + background: linear-gradient(135deg, #4299e1 0%, #38b2ac 100%) !important; + color: white !important; + padding: 8px 16px !important; + border-radius: 20px !important; + font-weight: 700 !important; + font-size: 0.85rem !important; + display: inline-block !important; + margin: 5px 0 !important; } - - # Calculate savings - savings = 0 - if "Cost Saved" in results["business_impact"]: - try: - savings_str = results["business_impact"]["Cost Saved"] - savings = int(''.join(filter(str.isdigit, savings_str))) - except (ValueError, TypeError): - savings = random.randint(2000, 10000) - - # Update status - if approval_required: - results["status"] = "āœ… Approved and Executed" - approval_html = self._create_approval_html(scenario_name, True) - else: - results["status"] = "āœ… Auto-Executed" - approval_html = self._create_approval_html(scenario_name, False) - - # Add to audit trail - details = f"{len(results['actions_completed'])} actions executed" - self.audit_manager.add_execution( - scenario_name, - results["actions_completed"], - savings, - approval_required, - details - ) - - # Add enterprise context - results["enterprise_context"] = { - "approval_required": approval_required, - "compliance_mode": "strict", - "audit_trail": "created", - "learning_applied": True, - "roi_measured": True - } - - # Update visualizations - execution_chart = self.viz_engine.create_execution_history_chart(self.audit_manager) - - return ( - approval_html, - {"approval_required": approval_required, "compliance_mode": "strict"}, - results, - execution_chart, - self.audit_manager.get_execution_history_table(), - self.audit_manager.get_incident_history_table() - ) - - def _create_approval_html(self, scenario_name: str, approval_required: bool) -> str: - """Create approval workflow HTML""" - if approval_required: - return f""" -
-

šŸ›”ļø Approval Required

-

Action: Scale resources for {scenario_name}

-

Risk Level: Low (auto-rollback available)

-

Blast Radius: Limited to affected service

-

Status: āœ… Approved & Executed

-
""" - else: - return f""" -
-

⚔ Auto-Executed

-

Action: Autonomous healing for {scenario_name}

-

Mode: Fully autonomous (safety guardrails active)

-

Guardrails: Blast radius limits, rollback ready, compliance logging

-

Status: āœ… Successfully completed

+ ) as demo: + + # ============ COMPLEX HEADER ============ + gr.Markdown(f""" +
+

šŸš€ Agentic Reliability Framework

+

Investor Demo v3.8.0 - Enterprise Edition

+ +
+
šŸ¢ Enterprise Features
+
šŸ†“ OSS v{OSS_VERSION}
+
+ šŸ“ˆ 5.2Ɨ Average ROI +
+
+ ⚔ 85% MTTR Reduction +
+
+ +
+ Transform your reliability operations from a cost center + to a profit engine with autonomous incident resolution. + Experience the full spectrum from OSS advisory to Enterprise autonomous healing. +
- """ - - def calculate_roi(self, monthly_incidents: int, avg_impact: int, team_size: int) -> Dict[str, Any]: - """Calculate ROI""" - try: - annual_impact = monthly_incidents * 12 * avg_impact - team_cost = team_size * 150000 # $150k per engineer - savings = annual_impact * 0.82 # 82% savings with ARF + """) - roi_multiplier = savings / team_cost if team_cost > 0 else 0 + # ============ SYSTEM STATUS BAR ============ + with gr.Row(): + with gr.Column(scale=1): + status_html = f""" +
+
+
+

System Status

+
+
+ Operational +
+
+
+
OSS Integration
+
+ {"āœ… Connected" if ARF_OSS_AVAILABLE else "āš ļø Mock Mode"} +
+
+
+
+ """ + gr.HTML(status_html) + + with gr.Column(scale=2): + performance_html = """ +
+
+
+

Performance Metrics

+
+
+
Auto-Heal Rate
+
81.7%
+
+
+
Avg Resolution
+
8.2 min
+
+
+
Cost Savings
+
$6.2M/yr
+
+
+
+
+
+ """ + gr.HTML(performance_html) + + with gr.Column(scale=1): + license_html = """ +
+

License Status

+
+
+
ENTERPRISE
+
Active • Expires 2024-12-31
+
+
+ āœ… Valid +
+
+
+ """ + gr.HTML(license_html) - if roi_multiplier >= 5.0: - recommendation = "šŸš€ Excellent fit for ARF Enterprise" - icon = "šŸš€" - elif roi_multiplier >= 2.0: - recommendation = "āœ… Good ROI with ARF Enterprise" - icon = "āœ…" - elif roi_multiplier >= 1.0: - recommendation = "āš ļø Consider ARF OSS edition first" - icon = "ā„¹ļø" - else: - recommendation = "šŸ†“ Start with ARF OSS (free)" - icon = "šŸ†“" + # ============ MAIN TABS ============ + logger.info("Creating main tabs...") + tabs_components = create_all_tabs( + business_logic=business_logic, + viz_engine=viz_engine, + audit_manager=audit_manager, + roi_calculator=roi_calculator, + oss_available=ARF_OSS_AVAILABLE, + oss_version=OSS_VERSION + ) - payback = (team_cost / (savings / 12)) if savings > 0 else 0 + # ============ EVENT HANDLERS ============ + logger.info("Registering event handlers...") + register_all_handlers( + demo=demo, + components=tabs_components, + business_logic=business_logic, + viz_engine=viz_engine, + audit_manager=audit_manager, + roi_calculator=roi_calculator + ) - return { - "analysis": { - "your_annual_impact": f"${annual_impact:,.0f}", - "your_team_cost": f"${team_cost:,.0f}", - "potential_savings": f"${savings:,.0f}", - "your_roi_multiplier": f"{roi_multiplier:.1f}Ɨ", - "vs_industry_average": "5.2Ɨ average ROI", - "recommendation": f"{icon} {recommendation}", - "payback_period": f"{payback:.1f} months" if savings > 0 else "N/A", - "annual_savings_potential": f"${savings - team_cost:,.0f}" if savings > team_cost else "$0" - } - } - except Exception as e: - return {"error": f"Calculation error: {str(e)}"} - - def validate_license(self) -> Dict[str, Any]: - """Validate current license""" - # Simulate license validation - self.license_info["last_validated"] = datetime.datetime.now().isoformat() - self.license_info["validation_code"] = f"VAL-{random.randint(1000, 9999)}" - return self.license_info - - def start_trial(self) -> Dict[str, Any]: - """Start 30-day trial""" - expires = datetime.datetime.now() + datetime.timedelta(days=30) - - self.license_info.update({ - "tier": "TRIAL", - "expires_at": expires.isoformat(), - "features": ["autonomous_healing", "compliance", "audit_trail"], - "max_services": 10, - "max_incidents_per_month": 100, - "status": "šŸ†“ Trial Active", - "trial_started": datetime.datetime.now().isoformat(), - "days_remaining": 30 - }) - - return self.license_info - - def upgrade_license(self) -> Dict[str, Any]: - """Upgrade license tier""" - tiers = ["STARTER", "PROFESSIONAL", "ENTERPRISE", "PLATFORM"] - current_tier = self.license_info.get("tier", "STARTER") - current_idx = tiers.index(current_tier) if current_tier in tiers else 0 - - if current_idx < len(tiers) - 1: - new_tier = tiers[current_idx + 1] - self.license_info["tier"] = new_tier - self.license_info["status"] = f"āœ… Upgraded to {new_tier}" - - return self.license_info - - def update_mcp_mode(self, mode: str) -> Dict[str, Any]: - """Update MCP execution mode""" - self.mcp_mode = mode - - # Update configuration - config = { - "mcp_mode": mode, - "approval_required": mode == "approval", - "autonomous": mode == "autonomous", - "safety_guardrails": True, - "rollback_enabled": True, - "compliance_mode": "strict" - } - - return config - - def get_learning_stats(self) -> Dict[str, Any]: - """Get current learning engine statistics""" - # Update stats based on history - total_incidents = len(self.audit_manager.incident_history) - resolved = len([e for e in self.audit_manager.execution_history - if "Executed" in e.get("status", "")]) - - if total_incidents > 0: - success_rate = (resolved / total_incidents) * 100 - self.learning_stats.update({ - "total_incidents": total_incidents, - "resolved_automatically": resolved, - "success_rate": f"{success_rate:.1f}%", - "graph_nodes": total_incidents, - "graph_edges": total_incidents * 2 # Rough estimate - }) - - return self.learning_stats - - def update_learning_stats(self) -> Dict[str, Any]: - """Update and return learning stats""" - return self.get_learning_stats() - - def analyze_patterns(self) -> Dict[str, Any]: - """Analyze patterns in incident history""" - incidents = list(self.audit_manager.incident_history) - - if not incidents: - return {"status": "No incidents to analyze"} - - # Analyze incident types - type_counts = {} - severity_counts = {1: 0, 2: 0, 3: 0} - - for incident in incidents: - inc_type = incident.get("type", "Unknown") - type_counts[inc_type] = type_counts.get(inc_type, 0) + 1 - severity_counts[incident.get("severity", 2)] += 1 - - # Find most common incidents - most_common = sorted(type_counts.items(), key=lambda x: x[1], reverse=True)[:5] - - # Calculate metrics - total_incidents = len(incidents) - avg_severity = sum(severity_counts.values()) / total_incidents if total_incidents > 0 else 0 - - return { - "total_incidents_analyzed": total_incidents, - "most_common_incidents": dict(most_common), - "severity_distribution": severity_counts, - "average_severity": f"{avg_severity:.2f}", - "time_period_covered": "Last 24 hours", - "recommendations": [ - f"Focus on resolving {most_common[0][0]} incidents (most frequent)" if most_common else "No patterns found", - "Implement proactive monitoring for high-severity patterns", - "Review incident resolution times for optimization", - "Update runbooks based on frequent patterns" - ] - } - - def search_similar_incidents(self, query: str) -> List[List[str]]: - """Search for similar incidents""" - if not query.strip(): - return [] - - # Mock search - in real app this would use embeddings - incidents = list(self.audit_manager.incident_history)[:10] - - results = [] - for i, incident in enumerate(incidents[:5]): # Return top 5 - similarity = 0.7 + (i * 0.05) # Mock similarity score - results.append([ - incident.get("type", "Unknown"), - f"{similarity:.0%}", - "āœ… Resolved" if i % 2 == 0 else "āš ļø Pending", - f"{random.randint(1, 5)} actions" - ]) + # ============ COMPLEX FOOTER ============ + gr.Markdown(""" +
+
+
+

šŸ“Š Enterprise Features

+
    +
  • āœ… Autonomous Healing Engine
  • +
  • āœ… Compliance Automation
  • +
  • āœ… Learning & Optimization
  • +
  • āœ… Multi-Cloud Support
  • +
  • āœ… Executive Dashboards
  • +
+
+
+

šŸ”§ Integration

+
    +
  • AWS • Azure • GCP
  • +
  • Datadog • New Relic
  • +
  • PagerDuty • ServiceNow
  • +
  • Slack • Microsoft Teams
  • +
  • GitHub • GitLab • Jira
  • +
+
+
+

šŸ“ˆ Business Impact

+
    +
  • 5.2Ɨ Average ROI
  • +
  • 85% MTTR Reduction
  • +
  • $6.2M Annual Savings
  • +
  • 325+ Hours Reclaimed
  • +
  • 60% Innovation Increase
  • +
+
+
+ +
+
+ + šŸš€ Start 30-Day Trial + + + šŸ“š Documentation + + + šŸ’¬ Join Community + +
+ +
+

Ā© 2024 Agentic Reliability Framework. Demo v3.8.0 Enterprise Edition.

+

This is a demonstration of capabilities. Actual results may vary based on implementation.

+
+
+
+ """) - return results + logger.info("Demo interface created successfully") + return demo - def export_graph_data(self) -> str: - """Export graph data""" - # Mock export - temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.json') - temp_file.write(json.dumps({ - "nodes": len(self.audit_manager.incident_history), - "edges": len(self.audit_manager.incident_history) * 2, - "exported_at": datetime.datetime.now().isoformat(), - "incidents": list(self.audit_manager.incident_history)[:10] - }, default=str).encode()) - temp_file.close() - return temp_file.name - - def export_embeddings(self) -> str: - """Export embeddings""" - # Mock export - temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.bin') - temp_file.write(b"Mock embeddings data") - temp_file.close() - return temp_file.name - -# =========================================== -# MAIN INTERFACE (FIXED) -# =========================================== + # Create and return the interface + return create_demo_interface() -def create_interface() -> gr.Blocks: - """Create the comprehensive Gradio interface""" - - # Initialize managers - audit_manager = AuditTrailManager() - business_logic = EnhancedBusinessLogic(audit_manager) - viz_engine = EnhancedVisualizationEngine() +except Exception as e: + logger.error(f"Failed to create demo interface: {e}") + logger.error(traceback.format_exc()) - custom_css = """ - .gradio-container { max-width: 1400px !important; margin: auto !important; } - h1, h2, h3 { color: #1a365d !important; } - .critical { color: #FF6B6B !important; font-weight: bold; } - .success { color: #4ECDC4 !important; font-weight: bold; } - .plot-container { background: white !important; border-radius: 10px; padding: 10px; } - """ + # Fallback minimal interface + import gradio as gr - with gr.Blocks( - title="šŸš€ ARF Investor Demo v3.8.0", - theme=gr.themes.Soft(primary_hue="blue", secondary_hue="teal"), - css=custom_css - ) as demo: - - # ============ HEADER ============ - arf_status = "āœ… ARF OSS v3.3.6" if ARF_OSS_AVAILABLE else "āš ļø Simulation Mode" - + with gr.Blocks(title="šŸš€ ARF Demo - Error Recovery") as demo: gr.Markdown(f""" - # šŸš€ Agentic Reliability Framework - Investor Demo v3.8.0 - ## From Cost Center to Profit Engine: 5.2Ɨ ROI with Autonomous Reliability - -
- {arf_status} | Experience: OSS (Advisory) ↔ Enterprise (Autonomous) -
- """) - - # ============ MAIN TABS ============ - with gr.Tabs(): - - # TAB 1: LIVE INCIDENT DEMO - with gr.TabItem("šŸ”„ Live Incident Demo"): - with gr.Row(): - # Left Panel - with gr.Column(scale=1): - gr.Markdown("### šŸŽ¬ Incident Scenario") - scenario_dropdown = gr.Dropdown( - choices=list(INCIDENT_SCENARIOS.keys()), - value="Cache Miss Storm", - label="Select critical incident:" - ) - - # Scenario description - scenario_description = gr.Markdown( - value=INCIDENT_SCENARIOS["Cache Miss Storm"]["description"] - ) - - gr.Markdown("### šŸ“Š Current Crisis Metrics") - metrics_display = gr.JSON( - value=INCIDENT_SCENARIOS["Cache Miss Storm"]["metrics"], - label="Live Metrics" - ) - - gr.Markdown("### šŸ’° Business Impact") - impact_display = gr.JSON( - value=INCIDENT_SCENARIOS["Cache Miss Storm"]["impact"], - label="Impact Analysis" - ) - - # Right Panel - with gr.Column(scale=2): - # Visualization - gr.Markdown("### šŸ“ˆ Incident Timeline") - timeline_output = gr.Plot( - value=viz_engine.create_incident_timeline(), - label="Timeline Visualization" - ) - - # Action Section - gr.Markdown("### ⚔ Take Action") - with gr.Row(): - oss_btn = gr.Button("šŸ†“ Run OSS Analysis", variant="secondary") - enterprise_btn = gr.Button("šŸš€ Execute Enterprise Healing", variant="primary") - - # Approval Controls - with gr.Row(): - approval_toggle = gr.Checkbox( - label="šŸ” Require Manual Approval", - value=True, - info="Toggle to show approval workflow vs auto-execution" - ) - demo_mode_btn = gr.Button("⚔ Quick Demo", variant="secondary", size="sm") - - # Approval Display - approval_display = gr.HTML( - value="
Approval status will appear here
" - ) - - # Configuration - config_display = gr.JSON( - label="āš™ļø Enterprise Configuration", - value={"approval_required": True, "compliance_mode": "strict"} - ) - - # Results - results_display = gr.JSON( - label="šŸŽÆ Execution Results", - value={"status": "Ready for execution..."} - ) - - # TAB 2: BUSINESS IMPACT & ROI - with gr.TabItem("šŸ’° Business Impact & ROI"): - with gr.Column(): - # Business Dashboard - gr.Markdown("### šŸ“Š Executive Business Dashboard") - dashboard_output = gr.Plot( - value=viz_engine.create_business_dashboard(), - label="Business Dashboard" - ) - - # ROI Calculator - gr.Markdown("### 🧮 Interactive ROI Calculator") - with gr.Row(): - with gr.Column(scale=1): - monthly_slider = gr.Slider( - 1, 100, value=15, step=1, - label="Monthly incidents" - ) - impact_slider = gr.Slider( - 1000, 50000, value=8500, step=500, - label="Average incident impact ($)" - ) - team_slider = gr.Slider( - 1, 20, value=5, step=1, - label="Reliability team size" - ) - calculate_btn = gr.Button("Calculate My ROI", variant="primary") - - with gr.Column(scale=2): - roi_output = gr.JSON( - label="Your ROI Analysis", - value={"analysis": "Adjust sliders and click Calculate"} - ) - - # ROI Metrics - with gr.Row(): - with gr.Column(): - gr.Markdown(""" - **šŸ“ˆ ARF Enterprise ROI Metrics** - - **Average ROI:** 5.2Ɨ first year - - **Payback Period:** 2-3 months - - **Auto-Heal Rate:** 81.7% - - **MTTR Reduction:** 85% - - **Cost Savings:** $6.2M average annually - """) - with gr.Column(): - gr.Markdown(""" - **šŸŽÆ Business Impact** - - **Engineer Time:** 325+ hours reclaimed annually - - **SLA Compliance:** 99.9% maintained - - **Customer Satisfaction:** +40% improvement - - **Revenue Protection:** $8,500+/hour saved - - **Innovation Capacity:** 60% increase - """) - - # TAB 3: AUDIT TRAIL & HISTORY - with gr.TabItem("šŸ“œ Audit Trail & History"): - with gr.Row(): - # Left Column - Execution History - with gr.Column(scale=1): - gr.Markdown("### šŸ“‹ Execution History (Audit Trail)") - - # Controls - with gr.Row(): - refresh_btn = gr.Button("šŸ”„ Refresh", variant="secondary", size="sm") - clear_btn = gr.Button("šŸ—‘ļø Clear History", variant="stop", size="sm") - export_btn = gr.Button("šŸ“„ Export JSON", variant="secondary", size="sm") - analyze_btn = gr.Button("🧠 AI Analysis", variant="primary", size="sm") - - # Execution Table - execution_table = gr.Dataframe( - headers=["Time", "Scenario", "Actions", "Status", "Savings", "Details"], - value=audit_manager.get_execution_history_table(), - label="šŸ“‹ Execution History", - interactive=False, - wrap=True, - datatype=["str", "str", "str", "str", "str", "str"] - ) - - gr.Markdown("### šŸ“ˆ Visual History") - execution_chart = gr.Plot( - value=viz_engine.create_execution_history_chart(audit_manager), - label="Cost Savings Chart" - ) - - # AI Analysis Results - gr.Markdown("### 🧠 AI Pattern Analysis") - ai_analysis = gr.JSON( - value={"status": "Click 'AI Analysis' to run pattern detection"}, - label="Pattern Recognition Results" - ) - - # Right Column - Incident History - with gr.Column(scale=1): - gr.Markdown("### šŸ“Š Incident History") - - incident_table = gr.Dataframe( - headers=["Time", "Service", "Type", "Severity", "Description"], - value=audit_manager.get_incident_history_table(), - label="šŸ“Š Incident History", - interactive=False, - wrap=True - ) - - # Memory Graph Visualization - gr.Markdown("### 🧠 Memory Graph") - memory_graph = gr.Plot( - value=viz_engine.create_memory_graph(audit_manager), - label="Memory Graph" - ) - - # Export Area - gr.Markdown("### šŸ“¤ Export & Analytics") - export_text = gr.Textbox( - label="Full Audit Trail (JSON)", - value=audit_manager.export_audit_trail(), - lines=10, - max_lines=15 - ) - - with gr.Row(): - download_btn = gr.Button("šŸ’¾ Download JSON", variant="secondary") - compliance_btn = gr.Button("šŸ“‹ Generate Compliance Report", variant="secondary") - - # TAB 4: ENTERPRISE FEATURES & LICENSE - with gr.TabItem("šŸ¢ Enterprise Features"): - with gr.Row(): - # Left Column - License Management - with gr.Column(scale=1): - gr.Markdown("### šŸ” License Management") - - # License Info Display - license_display = gr.JSON( - value=business_logic.license_info, - label="License Information" - ) - - # License Controls - with gr.Row(): - validate_btn = gr.Button("šŸ” Validate License", variant="secondary") - trial_btn = gr.Button("šŸ†“ Start 30-Day Trial", variant="primary") - upgrade_btn = gr.Button("šŸš€ Upgrade Tier", variant="secondary") - - # Feature Comparison - gr.Markdown("### ⚔ Feature Matrix") - - features_data = [ - ["šŸ¤– Autonomous Healing", "āŒ", "āœ… Auto", "Enterprise Only"], - ["šŸ“Š Executive Dashboards", "Basic", "Advanced", "āœ… Comprehensive"], - ["šŸ” Compliance Automation", "āŒ", "āœ…", "āœ… SOC2/GDPR"], - ["šŸ“ˆ Predictive Analytics", "āŒ", "Basic", "āœ… ML-Powered"], - ["šŸ”„ Auto-Remediation", "Manual", "āœ… Auto", "āœ… AI-Driven"], - ["šŸŽÆ SLA Guarantees", "āŒ", "āŒ", "āœ… 99.9%"], - ["šŸ“Š Cost Optimization", "Basic", "Advanced", "āœ… AI-Optimized"], - ["šŸ”’ Role-Based Access", "āŒ", "āœ…", "āœ… Granular"], - ["šŸ“ Audit Trail", "Basic", "āœ…", "āœ… Comprehensive"], - ["šŸ”„ Multi-Cloud", "āŒ", "āŒ", "āœ… Native"], - ["🧠 Learning Engine", "āŒ", "Basic", "āœ… Continuous"], - ["šŸ“‹ Compliance Reports", "āŒ", "āŒ", "āœ… Automated"], - ] - - features_table = gr.Dataframe( - value=features_data, - headers=["Feature", "OSS", "Starter", "Enterprise"], - label="Feature Comparison Matrix", - interactive=False, - wrap=True - ) - - # Right Column - Compliance & Integration - with gr.Column(scale=1): - # Compliance Status - gr.Markdown("### šŸ“‹ Compliance Status") - - compliance_status = gr.JSON( - value={ - "SOC2": {"status": "āœ… Certified", "expires": "2025-06-30"}, - "GDPR": {"status": "āœ… Compliant", "last_audit": "2024-10-15"}, - "HIPAA": {"status": "🟔 In Progress", "eta": "2024-12-31"}, - "ISO27001": {"status": "āœ… Certified", "cert_id": "ISO-2024-001"}, - "FedRAMP": {"status": "šŸ”„ Moderate Pending", "phase": "Assessment"}, - "CCPA": {"status": "āœ… Compliant", "verified": True} - }, - label="Compliance Certifications" - ) - - # Integration Status - gr.Markdown("### šŸ”— Integration Hub") - - integrations_data = [ - ["AWS", "CloudWatch, S3, Lambda", "āœ… Connected", "Last sync: 5min ago"], - ["Azure", "Monitor, Log Analytics", "āœ… Connected", "Last sync: 8min ago"], - ["GCP", "Operations, BigQuery", "āœ… Connected", "Last sync: 3min ago"], - ["Datadog", "Metrics, Logs, APM", "āœ… Connected", "Active"], - ["New Relic", "Full-stack", "āœ… Connected", "Active"], - ["PagerDuty", "Incident Response", "āœ… Connected", "On-call active"], - ["ServiceNow", "ITSM & CMDB", "āœ… Connected", "Last sync: 15min ago"], - ["Slack", "Notifications", "āœ… Connected", "#arf-alerts"], - ["Teams", "Notifications", "āœ… Connected", "General channel"], - ["Jira", "Issue Tracking", "āœ… Connected", "ARF project"], - ["GitHub", "CI/CD", "āœ… Connected", "Webhooks active"], - ["GitLab", "CI/CD", "āœ… Connected", "Pipelines active"], - ] - - integrations_table = gr.Dataframe( - value=integrations_data, - headers=["Platform", "Services", "Status", "Details"], - label="Active Integrations", - interactive=False, - wrap=True - ) - - # MCP Mode Selector - gr.Markdown("### āš™ļø MCP Execution Mode") - mcp_mode = gr.Radio( - choices=["advisory", "approval", "autonomous"], - value="approval", - label="Select MCP Mode:", - info="Controls how healing actions are executed" - ) - - update_mode_btn = gr.Button("šŸ”„ Update Mode", variant="secondary") - - # TAB 5: MEMORY & LEARNING ENGINE - with gr.TabItem("🧠 Memory & Learning"): - with gr.Row(): - # Left Column - Memory Graph - with gr.Column(scale=2): - gr.Markdown("### 🧠 Incident Memory Graph") - - # Graph Controls - with gr.Row(): - graph_type = gr.Radio( - choices=["Force Directed", "Hierarchical", "Timeline"], - value="Force Directed", - label="Graph Type" - ) - show_weights = gr.Checkbox(label="Show Edge Weights", value=True) - auto_layout = gr.Checkbox(label="Auto-Layout", value=True) - - # Graph Visualization - memory_graph_plot = gr.Plot( - value=viz_engine.create_memory_graph(audit_manager), - label="Memory Graph Visualization" - ) - - # Node Details - gr.Markdown("### šŸ” Selected Node Details") - node_details = gr.JSON( - value={"select": "a node in the graph to see details"}, - label="Node Information" - ) - - # Right Column - Learning Engine - with gr.Column(scale=1): - # Similarity Search - gr.Markdown("### šŸ”Ž Similarity Search") - - search_query = gr.Textbox( - label="Search for similar incidents", - placeholder="Describe incident or paste metrics...", - lines=3 - ) - - with gr.Row(): - search_btn = gr.Button("šŸ” Search Memory", variant="primary") - clear_search_btn = gr.Button("Clear", variant="secondary") - - search_results = gr.Dataframe( - headers=["Incident", "Similarity", "Resolution", "Actions"], - value=[], - label="Search Results", - interactive=False - ) - - # Learning Statistics - gr.Markdown("### šŸ“Š Learning Engine Stats") - - learning_stats = gr.JSON( - value=business_logic.learning_stats, - label="Learning Engine Statistics" - ) - - # Export Learning Data - gr.Markdown("### šŸ“¤ Export Learning Data") - with gr.Row(): - export_graph_btn = gr.Button("šŸ’¾ Export Graph", variant="secondary") - export_embeddings_btn = gr.Button("šŸ’¾ Export Embeddings", variant="secondary") - - export_status = gr.Textbox( - label="Export Status", - value="Ready for export...", - interactive=False - ) - - # =========================================== - # EVENT HANDLERS - # =========================================== - - def update_scenario(scenario_name: str) -> Tuple[str, Dict, Dict, go.Figure, Dict]: - """Update scenario display""" - scenario = INCIDENT_SCENARIOS.get(scenario_name, {}) - return ( - f"### {scenario_name}\n{scenario.get('description', 'No description')}", - scenario.get("metrics", {}), - scenario.get("impact", {}), - viz_engine.create_incident_timeline(), - {"status": "Ready to analyze..."} - ) - - scenario_dropdown.change( - fn=update_scenario, - inputs=[scenario_dropdown], - outputs=[scenario_description, metrics_display, impact_display, timeline_output, results_display] - ) - - def run_oss_analysis(scenario_name: str) -> Tuple[Dict, List[List[str]], go.Figure]: - """Run OSS analysis""" - analysis = business_logic.run_oss_analysis(scenario_name) - incident_table_data = audit_manager.get_incident_history_table() - graph_plot = viz_engine.create_memory_graph(audit_manager) - - return analysis, incident_table_data, graph_plot + # āš ļø ARF Demo Initialization Error - oss_btn.click( - fn=run_oss_analysis, - inputs=[scenario_dropdown], - outputs=[results_display, incident_table, memory_graph] - ) - - def execute_healing(scenario_name: str, approval_required: bool) -> Tuple[str, Dict, Dict, go.Figure, List[List[str]], List[List[str]], Dict]: - """Execute enterprise healing""" - results = business_logic.execute_enterprise_healing(scenario_name, approval_required) - new_stats = business_logic.update_learning_stats() - - return results + (new_stats,) - - enterprise_btn.click( - fn=execute_healing, - inputs=[scenario_dropdown, approval_toggle], - outputs=[ - approval_display, config_display, results_display, - execution_chart, execution_table, incident_table, - learning_stats - ] - ) - - def run_quick_demo() -> Tuple[str, Dict, Dict, str, Dict, go.Figure, List[List[str]], List[List[str]], go.Figure, gr.Checkbox, Dict, go.Figure]: - """Run quick demo""" - analysis = business_logic.run_oss_analysis("Cache Miss Storm") - results = business_logic.execute_enterprise_healing("Cache Miss Storm", False) - new_stats = business_logic.update_learning_stats() - - return ( - "
" - "⚔ Quick Demo Completed!
" - "1. āœ… OSS Analysis Completed
" - "2. āœ… Enterprise Healing Executed
" - "3. āœ… Audit Trail Updated
" - "4. āœ… ROI Calculated
" - "5. āœ… Learning Engine Updated" - "
", - {"status": "demo_completed", "mode": "autonomous"}, - analysis, - results[0], - results[2], - viz_engine.create_execution_history_chart(audit_manager), - audit_manager.get_execution_history_table(), - audit_manager.get_incident_history_table(), - viz_engine.create_incident_timeline(), - approval_toggle.update(value=False), - new_stats, - viz_engine.create_memory_graph(audit_manager) - ) - - demo_mode_btn.click( - fn=run_quick_demo, - outputs=[ - scenario_description, - config_display, - results_display, - approval_display, - results_display, - execution_chart, - execution_table, - incident_table, - timeline_output, - approval_toggle, - learning_stats, - memory_graph - ] - ) - - def calculate_roi(monthly_incidents: int, avg_impact: int, team_size: int) -> Dict: - """Calculate ROI""" - return business_logic.calculate_roi(monthly_incidents, avg_impact, team_size) - - calculate_btn.click( - fn=calculate_roi, - inputs=[monthly_slider, impact_slider, team_slider], - outputs=[roi_output] - ) - - # Slider updates - for slider in [monthly_slider, impact_slider, team_slider]: - slider.change( - fn=calculate_roi, - inputs=[monthly_slider, impact_slider, team_slider], - outputs=[roi_output] - ) - - # Tab 3: Audit Trail Handlers - def refresh_history() -> Tuple[List[List[str]], List[List[str]], go.Figure, str, go.Figure]: - """Refresh history display""" - return ( - audit_manager.get_execution_history_table(), - audit_manager.get_incident_history_table(), - viz_engine.create_execution_history_chart(audit_manager), - audit_manager.export_audit_trail(), - viz_engine.create_memory_graph(audit_manager) - ) - - refresh_btn.click( - fn=refresh_history, - outputs=[execution_table, incident_table, execution_chart, export_text, memory_graph] - ) - - def clear_history() -> Tuple[List[List[str]], List[List[str]], go.Figure, str, go.Figure]: - """Clear history""" - execution_table_data, incident_table_data = audit_manager.clear_history() - return ( - execution_table_data, - incident_table_data, - viz_engine.create_execution_history_chart(audit_manager), - audit_manager.export_audit_trail(), - viz_engine.create_memory_graph(audit_manager) - ) - - clear_btn.click( - fn=clear_history, - outputs=[execution_table, incident_table, execution_chart, export_text, memory_graph] - ) - - def run_ai_analysis() -> Tuple[Dict, go.Figure]: - """Run AI pattern analysis""" - analysis = business_logic.analyze_patterns() - pattern_chart = viz_engine.create_pattern_analysis_chart(analysis) - return analysis, pattern_chart - - analyze_btn.click( - fn=run_ai_analysis, - outputs=[ai_analysis, execution_chart] - ) - - def update_export() -> str: - """Update export text""" - return audit_manager.export_audit_trail() + An error occurred while initializing the demo: - export_btn.click( - fn=update_export, - outputs=[export_text] - ) - - # Tab 4: Enterprise Features Handlers - def validate_license() -> Dict: - """Validate license""" - return business_logic.validate_license() - - validate_btn.click( - fn=validate_license, - outputs=[license_display] - ) - - def start_trial() -> Dict: - """Start trial""" - return business_logic.start_trial() + ```python + {str(e)} + ``` - trial_btn.click( - fn=start_trial, - outputs=[license_display] - ) - - def upgrade_tier() -> Dict: - """Upgrade license tier""" - return business_logic.upgrade_license() - - upgrade_btn.click( - fn=upgrade_tier, - outputs=[license_display] - ) - - def update_mcp_mode(mode: str) -> Dict: - """Update MCP mode""" - return business_logic.update_mcp_mode(mode) - - update_mode_btn.click( - fn=update_mcp_mode, - inputs=[mcp_mode], - outputs=[config_display] - ) - - # Tab 5: Memory & Learning Handlers - def update_graph_view(graph_type: str, show_weights: bool, auto_layout: bool) -> go.Figure: - """Update graph view""" - return viz_engine.create_memory_graph( - audit_manager, - graph_type=graph_type, - show_weights=show_weights, - auto_layout=auto_layout - ) - - # Connect all graph controls - graph_type.change( - fn=update_graph_view, - inputs=[graph_type, show_weights, auto_layout], - outputs=[memory_graph_plot] - ) - - show_weights.change( - fn=update_graph_view, - inputs=[graph_type, show_weights, auto_layout], - outputs=[memory_graph_plot] - ) - - auto_layout.change( - fn=update_graph_view, - inputs=[graph_type, show_weights, auto_layout], - outputs=[memory_graph_plot] - ) - - def search_memory(query: str) -> Tuple[List[List[str]], str]: - """Search memory""" - if not query.strip(): - return [], "Enter a search query" - - results = business_logic.search_similar_incidents(query) - return results, f"Found {len(results)} similar incidents" - - search_btn.click( - fn=search_memory, - inputs=[search_query], - outputs=[search_results, export_status] - ) - - def clear_search() -> Tuple[List, str]: - """Clear search""" - return [], "Search cleared" - - clear_search_btn.click( - fn=clear_search, - outputs=[search_results, export_status] - ) - - def export_graph_data() -> str: - """Export graph data""" - export_path = business_logic.export_graph_data() - return f"Graph exported to: {export_path}" - - export_graph_btn.click( - fn=export_graph_data, - outputs=[export_status] - ) - - def export_embeddings() -> str: - """Export embeddings""" - export_path = business_logic.export_embeddings() - return f"Embeddings exported to: {export_path}" - - export_embeddings_btn.click( - fn=export_embeddings, - outputs=[export_status] - ) - - # =========================================== - # INITIALIZATION - FIXED - # =========================================== - - # Initialize with default visualizations - demo.load( - fn=lambda: ( - viz_engine.create_business_dashboard(), - viz_engine.create_incident_timeline(), - viz_engine.create_execution_history_chart(audit_manager), - viz_engine.create_memory_graph(audit_manager), - business_logic.get_learning_stats() - ), - outputs=[dashboard_output, timeline_output, execution_chart, memory_graph_plot, learning_stats] - ) - - # ============ FOOTER ============ - gr.Markdown(""" - --- - ### šŸš€ ARF Enterprise Platform - - **Tabs Overview:** - 1. **šŸ”„ Live Incident Demo** - Experience OSS vs Enterprise healing - 2. **šŸ’° Business Impact & ROI** - Calculate your savings potential - 3. **šŸ“œ Audit Trail & History** - Complete compliance logging - 4. **šŸ¢ Enterprise Features** - License & compliance management - 5. **🧠 Memory & Learning** - AI-powered incident memory - - **Get Started:** - • **Free Trial:** 30-day enterprise trial - • **Contact:** sales@arfinvestor.com - • **Docs:** docs.arfinvestor.com/enterprise - • **Slack:** Join 2,500+ engineers - -
- Ā© 2024 Agentic Reliability Framework. Demo v3.8.0 Enterprise Edition -
+ Please check the logs for more details. """) return demo -# =========================================== -# MAIN EXECUTION -# =========================================== + +def main(): + """Main entry point""" + try: + print("šŸš€ Starting ARF Ultimate Investor Demo v3.8.0...") + print("=" * 70) + print("šŸ“Š Features:") + print(" • 5 Comprehensive Tabs with Advanced Visualizations") + print(" • Memory Graph & Learning Engine") + print(" • Enterprise License Management") + print(" • OSS Integration & HealingIntent Orchestration") + print(" • ROI Calculator & Business Impact Analysis") + print("=" * 70) + print("\nInitializing components...") + + # Create the demo + demo = create_demo_interface() + + # Launch with comprehensive configuration + demo.launch( + server_name="0.0.0.0", + server_port=7860, + share=False, + debug=True, + show_error=True, + quiet=False, + favicon_path=None, + ssl_verify=True, + max_file_size="100MB", + auth=None, + auth_message=None, + prevent_thread_lock=False, + show_api=True, + allowed_paths=["./"], + block_thread=True, + ssl_keyfile=None, + ssl_certfile=None, + ssl_keyfile_password=None, + root_path=None, + _frontend=False + ) + + except KeyboardInterrupt: + print("\n\nšŸ‘‹ Demo stopped by user") + except Exception as e: + print(f"\nāŒ Fatal error: {e}") + print(traceback.format_exc()) + sys.exit(1) + if __name__ == "__main__": - print("šŸš€ Starting ARF Ultimate Investor Demo v3.8.0 (Enterprise Edition)...") - print("šŸ“Š Features: 5 Tabs, Memory Graph, License Management, Compliance") - print("🧠 Learning Engine: Pattern Analysis, Similarity Search") - print("🌐 Opening web interface...") - - demo = create_interface() - demo.launch( - server_name="0.0.0.0", - server_port=7860, - share=False, - debug=True - ) \ No newline at end of file + main() \ No newline at end of file