""" ARF 3.3.9 Demo - Psychology-Optimized Version Fixed with proper error handling """ import gradio as gr import pandas as pd import numpy as np from datetime import datetime, timedelta import json import time import uuid import hashlib import random import traceback import sys from typing import Dict, List, Any, Tuple, Optional from dataclasses import dataclass from enum import Enum import re print("=" * 70) print("š§ ARF 3.3.9 DEMO - Psychology-Optimized Edition") print("=" * 70) # ============================================================================ # ENUMS AND DATA CLASSES # ============================================================================ class RiskLevel(str, Enum): CRITICAL = "CRITICAL" HIGH = "HIGH" MEDIUM = "MEDIUM" LOW = "LOW" SAFE = "SAFE" class EnforcementLevel(str, Enum): ADVISORY = "ADVISORY" HUMAN_APPROVAL = "HUMAN_APPROVAL" AUTONOMOUS = "AUTONOMOUS" FULL_MECHANICAL = "FULL_MECHANICAL" class LicenseTier(str, Enum): TRIAL = "TRIAL" STARTER = "STARTER" PROFESSIONAL = "PROFESSIONAL" ENTERPRISE = "ENTERPRISE" @dataclass class RiskAssessment: score: float level: RiskLevel confidence: float factors: Dict[str, float] @property def color(self) -> str: return { RiskLevel.CRITICAL: "#D32F2F", RiskLevel.HIGH: "#F44336", RiskLevel.MEDIUM: "#FF9800", RiskLevel.LOW: "#4CAF50", RiskLevel.SAFE: "#2E7D32" }[self.level] @property def icon(self) -> str: return { RiskLevel.CRITICAL: "š„", RiskLevel.HIGH: "ā ļø", RiskLevel.MEDIUM: "š¶", RiskLevel.LOW: "ā ", RiskLevel.SAFE: "š”ļø" }[self.level] @dataclass class GateResult: name: str passed: bool message: str required: bool = True weight: float = 1.0 @property def color(self) -> str: return "#4CAF50" if self.passed else "#F44336" @property def icon(self) -> str: return "ā " if self.passed else "ā" # ============================================================================ # SIMPLIFIED BUT ROBUST ENGINE # ============================================================================ class ARFEngine: """Simplified but robust ARF engine""" def __init__(self): self.stats = { "total_processed": 0, "blocked_actions": 0, "autonomous_executions": 0, "avg_processing_time": 0.0 } print("ā ARF Engine initialized") def assess_action(self, action: str, context: Dict, license_key: str = None) -> Dict: """Assess an action with realistic scoring""" start_time = time.time() # 1. Risk Assessment risk = self._assess_risk(action, context) # 2. Policy Evaluation policy_result = self._evaluate_policies(action, context, risk.score) # 3. License Validation license_info = self._validate_license(license_key) # 4. Gate Evaluation gate_results = self._evaluate_gates(risk, policy_result, license_info) # 5. Generate results processing_time = time.time() - start_time # Update stats self._update_stats(policy_result, gate_results, processing_time) return { "timestamp": datetime.now().isoformat(), "action": action, "risk_assessment": risk, "policy_result": policy_result, "license_info": license_info, "gate_results": gate_results, "processing_time": round(processing_time, 4), "recommendation": self._generate_recommendation(policy_result, gate_results, license_info) } def _assess_risk(self, action: str, context: Dict) -> RiskAssessment: """Assess risk with realistic scoring""" action_lower = action.lower() # Calculate risk factors destructiveness = 0.3 if "drop" in action_lower and "database" in action_lower: destructiveness = 0.95 elif "delete" in action_lower: destructiveness = 0.85 elif "truncate" in action_lower: destructiveness = 0.80 complexity = min(0.8, len(action.split()) * 0.05) env = context.get("environment", "development") environment_risk = { "production": 0.8, "staging": 0.5, "testing": 0.3, "development": 0.2 }.get(env, 0.5) # Weighted risk score risk_score = ( destructiveness * 0.4 + complexity * 0.2 + environment_risk * 0.4 ) # Determine risk level if risk_score >= 0.8: level = RiskLevel.CRITICAL elif risk_score >= 0.6: level = RiskLevel.HIGH elif risk_score >= 0.4: level = RiskLevel.MEDIUM elif risk_score >= 0.2: level = RiskLevel.LOW else: level = RiskLevel.SAFE # Confidence (higher for clear patterns) confidence = 0.8 if "drop database" in action_lower: confidence = 0.95 elif "delete from" in action_lower: confidence = 0.90 return RiskAssessment( score=round(risk_score, 3), level=level, confidence=round(confidence, 3), factors={ "destructiveness": destructiveness, "complexity": complexity, "environment": environment_risk } ) def _evaluate_policies(self, action: str, context: Dict, risk_score: float) -> Dict: """Evaluate against safety policies""" violations = [] # Policy 1: No destructive operations in production without approval if ("drop" in action.lower() or "delete" in action.lower()) and context.get("environment") == "production": violations.append({ "policy": "Destructive Operation Prevention", "severity": "CRITICAL", "action": "BLOCK" }) # Policy 2: High risk actions need review if risk_score > 0.7 and context.get("environment") == "production": violations.append({ "policy": "High Risk Review Required", "severity": "HIGH", "action": "REQUIRE_APPROVAL" }) return { "violations": violations, "blocked": any(v["action"] == "BLOCK" for v in violations), "requires_approval": any(v["action"] == "REQUIRE_APPROVAL" for v in violations), "total_violations": len(violations) } def _validate_license(self, license_key: str = None) -> Dict: """Validate license key""" if not license_key: return { "tier": None, "valid": False, "name": "OSS Edition", "enforcement": "ADVISORY", "message": "šµ Using ARF OSS (Open Source)" } if license_key.startswith("ARF-"): if "TRIAL" in license_key: return { "tier": "TRIAL", "valid": True, "name": "Trial", "enforcement": "ADVISORY", "message": "š Trial License Active (14 days)" } elif "PRO" in license_key: return { "tier": "PROFESSIONAL", "valid": True, "name": "Professional", "enforcement": "AUTONOMOUS", "message": "ā Professional License Active" } return { "tier": None, "valid": False, "name": "Invalid", "enforcement": "ADVISORY", "message": "ā Invalid License Key" } def _evaluate_gates(self, risk: RiskAssessment, policy: Dict, license: Dict) -> List[GateResult]: """Evaluate mechanical gates""" gates = [] # Gate 1: License Validation gates.append(GateResult( name="License Validation", passed=license.get("valid", False), message=license.get("message", "No license"), required=True )) # Gate 2: Risk Threshold risk_threshold = 0.8 if license.get("tier") in ["PROFESSIONAL", "ENTERPRISE"] else 0.7 gates.append(GateResult( name="Risk Assessment", passed=risk.score <= risk_threshold, message=f"Risk {risk.score:.1%} ⤠{risk_threshold:.0%} threshold", required=True )) # Gate 3: Confidence Threshold gates.append(GateResult( name="Confidence Threshold", passed=risk.confidence >= 0.7, message=f"Confidence {risk.confidence:.1%} ā„ 70%", required=True )) # Gate 4: Policy Compliance gates.append(GateResult( name="Policy Compliance", passed=not policy.get("blocked", False), message=f"{policy.get('total_violations', 0)} policy violations", required=True )) return gates def _generate_recommendation(self, policy: Dict, gates: List[GateResult], license: Dict) -> str: """Generate recommendation""" if policy.get("blocked"): return "š« BLOCKED: Action violates safety policies" all_gates_passed = all(g.passed for g in gates if g.required) if not license.get("valid"): return "šµ OSS ADVISORY: Human review recommended" elif all_gates_passed and license.get("tier") in ["PROFESSIONAL", "ENTERPRISE"]: return "š” ENTERPRISE APPROVED: Autonomous execution permitted" elif all_gates_passed and license.get("tier") == "STARTER": return "š¤ HUMAN APPROVAL: Gates passed, awaiting confirmation" else: return "ā ļø REVIEW REQUIRED: Additional validation needed" def _update_stats(self, policy: Dict, gates: List[GateResult], processing_time: float): """Update statistics""" self.stats["total_processed"] += 1 if policy.get("blocked"): self.stats["blocked_actions"] += 1 if all(g.passed for g in gates if g.required): self.stats["autonomous_executions"] += 1 # Update average processing time self.stats["avg_processing_time"] = ( self.stats["avg_processing_time"] * 0.9 + processing_time * 0.1 ) def get_stats(self) -> Dict: """Get statistics with safe defaults""" stats = self.stats.copy() # Calculate derived stats with error handling total = stats.get("total_processed", 0) blocked = stats.get("blocked_actions", 0) autonomous = stats.get("autonomous_executions", 0) stats["blocked_percentage"] = round(blocked / total * 100, 1) if total > 0 else 0.0 stats["autonomous_percentage"] = round(autonomous / total * 100, 1) if total > 0 else 0.0 stats["processing_speed"] = f"{stats.get('avg_processing_time', 0)*1000:.0f}ms" # Add default values for any missing keys defaults = { "risk_distribution": {"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0, "SAFE": 0}, "system_health": "ā Optimal", "license_distribution": {"OSS": 0, "TRIAL": 0, "ENTERPRISE": 0} } for key, value in defaults.items(): if key not in stats: stats[key] = value return stats def generate_trial_license(self, email: str) -> Dict: """Generate trial license""" if not email or "@" not in email: return { "success": False, "message": "Please enter a valid email address" } license_key = f"ARF-TRIAL-{hashlib.sha256(email.encode()).hexdigest()[:8].upper()}" return { "success": True, "license_key": license_key, "message": "š 14-Day Trial License Generated!", "expires": (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d"), "features": [ "Mechanical gate evaluation", "Enterprise dashboard", "Basic audit trail" ] } # ============================================================================ # DEMO DATA # ============================================================================ DEMO_SCENARIOS = [ { "id": "high_risk", "name": "š„ High-Risk Database Operation", "action": "DROP DATABASE production_users CASCADE", "context": {"environment": "production", "criticality": "critical"} }, { "id": "safe_deploy", "name": "ā Safe Service Deployment", "action": "deploy_service payment_api:v2.3.1 to staging with 25% canary", "context": {"environment": "staging", "service": "payment_api", "canary": 25} }, { "id": "config_change", "name": "š§ Configuration Update", "action": "UPDATE config SET timeout_ms=30000 WHERE service='api'", "context": {"environment": "production", "service": "api"} } ] # ============================================================================ # GRADIO INTERFACE # ============================================================================ def create_demo_interface(): """Create the demo interface""" # Initialize engine arf_engine = ARFEngine() # Get initial stats with error handling try: stats = arf_engine.get_stats() except Exception as e: print(f"Error getting stats: {e}") stats = { "total_processed": 0, "blocked_percentage": 0.0, "autonomous_percentage": 0.0, "processing_speed": "0ms" } # Safely get values with defaults total_processed = stats.get("total_processed", 0) blocked_percentage = stats.get("blocked_percentage", 0.0) autonomous_percentage = stats.get("autonomous_percentage", 0.0) processing_speed = stats.get("processing_speed", "0ms") with gr.Blocks( title="ARF 3.3.9 - OSS vs Enterprise Demo", theme=gr.themes.Soft(), css=""" .gradio-container { max-width: 1400px; margin: 0 auto; font-family: -apple-system, BlinkMacSystemFont, sans-serif; } .demo-card { border-radius: 10px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); } .oss-card { border: 2px solid #1E88E5; background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 100%); } .enterprise-card { border: 2px solid #FFB300; background: linear-gradient(135deg, #FFF8E1 0%, #FFECB3 100%); } .stat-card { background: white; padding: 15px; border-radius: 8px; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } .gate-passed { background: #E8F5E9; border-left: 4px solid #4CAF50; padding: 10px; margin: 5px 0; border-radius: 4px; } .gate-failed { background: #FFEBEE; border-left: 4px solid #F44336; padding: 10px; margin: 5px 0; border-radius: 4px; } """ ) as demo: # Header gr.Markdown(""" # š¤ Agentic Reliability Framework (ARF) 3.3.9 ### From Advisory to Mechanical Enforcement """) # Statistics gr.Markdown(f"""
{str(e)}
{result['recommendation']}