petter2025 commited on
Commit
bc06c6d
Β·
verified Β·
1 Parent(s): d6de10e

Rename app.py to hf_demo.py

Browse files
Files changed (2) hide show
  1. app.py +0 -0
  2. hf_demo.py +948 -0
app.py DELETED
The diff for this file is too large to render. See raw diff
 
hf_demo.py ADDED
@@ -0,0 +1,948 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hugging Face Spaces Demo for Agentic Reliability Framework (ARF)
3
+ Version: 3.3.9 OSS vs Enterprise
4
+ Author: Petter Reinhardt
5
+ Demo URL: https://huggingface.co/spaces/petter2025/agentic-reliability-framework
6
+ """
7
+
8
+ import gradio as gr
9
+ import pandas as pd
10
+ import numpy as np
11
+ import plotly.graph_objects as go
12
+ import plotly.express as px
13
+ from datetime import datetime, timedelta
14
+ import json
15
+ import time
16
+ import uuid
17
+ from typing import Dict, List, Any, Optional
18
+ import hashlib
19
+ import random
20
+
21
+ # Import REAL ARF 3.3.9 OSS components
22
+ from agentic_reliability_framework.models import (
23
+ ReliabilityEvent,
24
+ HealingPolicy,
25
+ PolicyAction,
26
+ AgentContext,
27
+ AnomalyScore,
28
+ ReliabilityScore
29
+ )
30
+
31
+ from agentic_reliability_framework.healing_policies import (
32
+ PolicyEngine,
33
+ PolicyViolation,
34
+ HealingAction
35
+ )
36
+
37
+ from agentic_reliability_framework.engine.reliability import (
38
+ ReliabilityEngine,
39
+ ConfidenceScore,
40
+ RiskAssessment
41
+ )
42
+
43
+ # Mock Enterprise Components (for demonstration)
44
+ class MockEnterpriseLicenseManager:
45
+ """Simulates enterprise license validation with mechanical gates"""
46
+
47
+ def __init__(self):
48
+ self.license_tiers = {
49
+ "trial": {"max_agents": 3, "enforcement": "advisory", "price": 0},
50
+ "starter": {"max_agents": 10, "enforcement": "human_approval", "price": 2000},
51
+ "professional": {"max_agents": 50, "enforcement": "autonomous", "price": 5000},
52
+ "enterprise": {"max_agents": 1000, "enforcement": "full_mechanical", "price": 15000}
53
+ }
54
+ self.active_licenses = {}
55
+
56
+ def validate_license(self, license_key: str, action_type: str, risk_score: float) -> Dict:
57
+ """Validate enterprise license and mechanical gate requirements"""
58
+ license_data = self.active_licenses.get(license_key, {"tier": "trial", "expires": datetime.now() + timedelta(days=14)})
59
+ tier = license_data["tier"]
60
+ tier_info = self.license_tiers[tier]
61
+
62
+ # Simulate mechanical gate checks
63
+ gates = {
64
+ "license_valid": True,
65
+ "tier_appropriate": tier in ["professional", "enterprise"] if risk_score > 0.7 else True,
66
+ "within_limits": True,
67
+ "payment_current": True
68
+ }
69
+
70
+ passed_gates = sum(gates.values())
71
+ total_gates = len(gates)
72
+
73
+ return {
74
+ "valid": True,
75
+ "tier": tier,
76
+ "enforcement_level": tier_info["enforcement"],
77
+ "gates_passed": passed_gates,
78
+ "total_gates": total_gates,
79
+ "gates": gates,
80
+ "can_execute": tier_info["enforcement"] != "advisory" and passed_gates == total_gates
81
+ }
82
+
83
+ class MockExecutionAuthorityService:
84
+ """Simulates mechanical gate enforcement for Enterprise"""
85
+
86
+ def __init__(self):
87
+ self.gate_definitions = {
88
+ "license_validation": {"weight": 0.3, "required": True},
89
+ "confidence_threshold": {"weight": 0.25, "required": True},
90
+ "risk_assessment": {"weight": 0.25, "required": True},
91
+ "rollback_feasibility": {"weight": 0.1, "required": False},
92
+ "admin_approval": {"weight": 0.1, "required": tier == "starter"},
93
+ "compliance_check": {"weight": 0.1, "required": tier == "enterprise"}
94
+ }
95
+
96
+ def evaluate_gates(self, action_data: Dict, license_tier: str) -> Dict:
97
+ """Evaluate all mechanical gates for an action"""
98
+ results = {}
99
+ confidence = action_data.get("confidence", 0.5)
100
+ risk_score = action_data.get("risk_score", 0.5)
101
+
102
+ # Evaluate each gate
103
+ results["license_validation"] = {
104
+ "passed": True,
105
+ "message": "Professional license validated",
106
+ "details": {"license_tier": license_tier}
107
+ }
108
+
109
+ results["confidence_threshold"] = {
110
+ "passed": confidence >= 0.7,
111
+ "message": f"Confidence {confidence:.2f} β‰₯ 0.70" if confidence >= 0.7 else f"Confidence {confidence:.2f} < 0.70",
112
+ "details": {"threshold": 0.7, "actual": confidence}
113
+ }
114
+
115
+ results["risk_assessment"] = {
116
+ "passed": risk_score <= 0.8,
117
+ "message": f"Risk {risk_score:.2f} ≀ 0.80" if risk_score <= 0.8 else f"Risk {risk_score:.2f} > 0.80",
118
+ "details": {"threshold": 0.8, "actual": risk_score}
119
+ }
120
+
121
+ results["rollback_feasibility"] = {
122
+ "passed": True,
123
+ "message": "Rollback plan exists",
124
+ "details": {"rollback_time": "2 minutes"}
125
+ }
126
+
127
+ if license_tier == "starter":
128
+ results["admin_approval"] = {
129
+ "passed": True,
130
+ "message": "Admin approval granted",
131
+ "details": {"approver": "admin@company.com"}
132
+ }
133
+
134
+ # Calculate overall gate status
135
+ passed_gates = sum(1 for gate in results.values() if gate["passed"])
136
+ total_gates = len(results)
137
+
138
+ return {
139
+ "gate_results": results,
140
+ "passed_gates": passed_gates,
141
+ "total_gates": total_gates,
142
+ "all_passed": passed_gates == total_gates,
143
+ "execution_authority": "GRANTED" if passed_gates == total_gates else "DENIED"
144
+ }
145
+
146
+ class MockAuditService:
147
+ """Simulates enterprise audit trail with differential privacy"""
148
+
149
+ def __init__(self):
150
+ self.audit_log = []
151
+
152
+ def log_execution(self, action: str, result: str, user_context: Dict, license_tier: str):
153
+ """Log execution with differential privacy simulation"""
154
+ audit_id = str(uuid.uuid4())
155
+ timestamp = datetime.now().isoformat()
156
+
157
+ # Add noise for differential privacy (simulated)
158
+ noisy_timestamp = timestamp
159
+
160
+ log_entry = {
161
+ "audit_id": audit_id,
162
+ "action": action,
163
+ "result": result,
164
+ "timestamp": noisy_timestamp,
165
+ "license_tier": license_tier,
166
+ "user_hash": hashlib.sha256(json.dumps(user_context).encode()).hexdigest()[:16]
167
+ }
168
+
169
+ self.audit_log.append(log_entry)
170
+ return log_entry
171
+
172
+ # Demo Configuration
173
+ class DemoConfig:
174
+ OSS_THEME = {
175
+ "primary": "#1E88E5", # Blue
176
+ "secondary": "#64B5F6",
177
+ "background": "#E3F2FD",
178
+ "text": "#1565C0"
179
+ }
180
+
181
+ ENTERPRISE_THEME = {
182
+ "primary": "#FFB300", # Gold
183
+ "secondary": "#FFD54F",
184
+ "background": "#FFF8E1",
185
+ "text": "#FF8F00"
186
+ }
187
+
188
+ SCENARIOS = [
189
+ "database_drop",
190
+ "service_deployment",
191
+ "config_change",
192
+ "user_permission_grant",
193
+ "sensitive_data_access",
194
+ "auto_scaling_adjustment",
195
+ "emergency_rollback"
196
+ ]
197
+
198
+ # Real ARF OSS Engine Integration
199
+ class ARFOSSProcessor:
200
+ """Process actions using real ARF 3.3.9 OSS engine"""
201
+
202
+ def __init__(self):
203
+ self.policy_engine = PolicyEngine()
204
+ self.reliability_engine = ReliabilityEngine()
205
+
206
+ # Pre-load some policies for demo
207
+ self._load_demo_policies()
208
+
209
+ def _load_demo_policies(self):
210
+ """Load demo policies for the showcase"""
211
+ # These would typically come from config, but hardcoded for demo
212
+ self.policies = [
213
+ HealingPolicy(
214
+ id="policy-001",
215
+ name="High Risk Action Prevention",
216
+ description="Prevents high-risk database operations",
217
+ conditions={"risk_score": {"gte": 0.8}},
218
+ action=PolicyAction.HEAL,
219
+ priority=1
220
+ ),
221
+ HealingPolicy(
222
+ id="policy-002",
223
+ name="Safe Deployment Guardrails",
224
+ description="Ensures safe service deployments",
225
+ conditions={"action_type": "deploy", "confidence": {"gte": 0.7}},
226
+ action=PolicyAction.ALLOW,
227
+ priority=2
228
+ )
229
+ ]
230
+
231
+ def evaluate_action(self, action_description: str, context: Dict = None) -> Dict:
232
+ """Evaluate an action using ARF OSS 3.3.9"""
233
+ start_time = time.time()
234
+
235
+ # Create a reliability event
236
+ event = ReliabilityEvent(
237
+ event_id=str(uuid.uuid4()),
238
+ agent_id="demo_agent",
239
+ action=action_description,
240
+ timestamp=datetime.now(),
241
+ context=context or {}
242
+ )
243
+
244
+ # Get reliability score
245
+ reliability_score = self.reliability_engine.calculate_score(event)
246
+
247
+ # Check for policy violations
248
+ violations = []
249
+ for policy in self.policies:
250
+ violation = self.policy_engine.evaluate_policy(policy, event, reliability_score)
251
+ if violation:
252
+ violations.append(violation)
253
+
254
+ # Determine recommendation
255
+ risk_level = "High" if reliability_score.overall < 0.3 else "Medium" if reliability_score.overall < 0.7 else "Low"
256
+
257
+ if violations:
258
+ recommendation = "Block or review action"
259
+ can_execute = False
260
+ else:
261
+ if reliability_score.overall >= 0.8:
262
+ recommendation = "Safe to execute"
263
+ can_execute = True
264
+ elif reliability_score.overall >= 0.6:
265
+ recommendation = "Review recommended"
266
+ can_execute = False
267
+ else:
268
+ recommendation = "High risk - do not execute"
269
+ can_execute = False
270
+
271
+ processing_time = time.time() - start_time
272
+
273
+ return {
274
+ "action": action_description,
275
+ "reliability_score": reliability_score.overall,
276
+ "confidence": reliability_score.confidence,
277
+ "risk_score": 1 - reliability_score.overall,
278
+ "risk_level": risk_level,
279
+ "policy_violations": len(violations),
280
+ "violation_details": [str(v) for v in violations[:3]], # Limit details
281
+ "recommendation": recommendation,
282
+ "can_execute_oss": can_execute,
283
+ "processing_time": processing_time,
284
+ "engine_version": "ARF 3.3.9 OSS",
285
+ "limitation": "Advisory only - human must make final decision"
286
+ }
287
+
288
+ # Main Demo Application
289
+ class ARFDemo:
290
+ """Main demo application for Hugging Face Spaces"""
291
+
292
+ def __init__(self):
293
+ self.oss_processor = ARFOSSProcessor()
294
+ self.license_manager = MockEnterpriseLicenseManager()
295
+ self.execution_service = MockExecutionAuthorityService()
296
+ self.audit_service = MockAuditService()
297
+ self.user_sessions = {}
298
+ self.demo_scenarios = self._load_scenarios()
299
+
300
+ def _load_scenarios(self):
301
+ """Load demo scenarios from scenarios module"""
302
+ from demo_scenarios import DEMO_SCENARIOS
303
+ return DEMO_SCENARIOS
304
+
305
+ def process_action_oss(self, action: str, scenario: str = None) -> Dict:
306
+ """Process action through ARF OSS 3.3.9"""
307
+ if scenario and scenario in self.demo_scenarios:
308
+ action_data = self.demo_scenarios[scenario]
309
+ action = action_data["action"]
310
+ context = action_data.get("context", {})
311
+ else:
312
+ context = {}
313
+
314
+ return self.oss_processor.evaluate_action(action, context)
315
+
316
+ def process_action_enterprise(self, action: str, license_key: str, scenario: str = None) -> Dict:
317
+ """Process action through mocked Enterprise system"""
318
+ # First, process through OSS to get baseline
319
+ oss_result = self.process_action_oss(action, scenario)
320
+
321
+ # Then apply enterprise gates
322
+ license_validation = self.license_manager.validate_license(
323
+ license_key,
324
+ action,
325
+ oss_result["risk_score"]
326
+ )
327
+
328
+ # Prepare action data for gate evaluation
329
+ action_data = {
330
+ "action": action,
331
+ "confidence": oss_result["confidence"],
332
+ "risk_score": oss_result["risk_score"],
333
+ "reliability": oss_result["reliability_score"]
334
+ }
335
+
336
+ # Evaluate mechanical gates
337
+ gate_evaluation = self.execution_service.evaluate_gates(
338
+ action_data,
339
+ license_validation["tier"]
340
+ )
341
+
342
+ # Log to audit trail
343
+ user_context = {"action": action, "scenario": scenario}
344
+ audit_log = self.audit_service.log_execution(
345
+ action,
346
+ gate_evaluation["execution_authority"],
347
+ user_context,
348
+ license_validation["tier"]
349
+ )
350
+
351
+ # Combine results
352
+ return {
353
+ **oss_result,
354
+ "license_tier": license_validation["tier"],
355
+ "enforcement_level": license_validation["enforcement_level"],
356
+ "gate_results": gate_evaluation["gate_results"],
357
+ "gates_passed": gate_evaluation["passed_gates"],
358
+ "total_gates": gate_evaluation["total_gates"],
359
+ "execution_authority": gate_evaluation["execution_authority"],
360
+ "can_execute_enterprise": gate_evaluation["all_passed"],
361
+ "audit_id": audit_log["audit_id"],
362
+ "engine_version": f"ARF 3.3.9 Enterprise ({license_validation['tier'].title()})",
363
+ "benefit": "Mechanical enforcement - automated decision making"
364
+ }
365
+
366
+ def generate_trial_license(self, email: str) -> Dict:
367
+ """Generate a trial license for demo purposes"""
368
+ trial_key = f"ARF-TRIAL-{hashlib.sha256(email.encode()).hexdigest()[:8].upper()}"
369
+
370
+ # Store in mock license manager
371
+ self.license_manager.active_licenses[trial_key] = {
372
+ "tier": "trial",
373
+ "email": email,
374
+ "expires": datetime.now() + timedelta(days=14),
375
+ "created": datetime.now()
376
+ }
377
+
378
+ # Store user session
379
+ session_id = str(uuid.uuid4())
380
+ self.user_sessions[session_id] = {
381
+ "email": email,
382
+ "license_key": trial_key,
383
+ "created": datetime.now()
384
+ }
385
+
386
+ return {
387
+ "success": True,
388
+ "license_key": trial_key,
389
+ "expires": (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d"),
390
+ "session_id": session_id,
391
+ "message": f"14-day trial license generated. Tier: Trial (Advisory mode)"
392
+ }
393
+
394
+ def upgrade_simulation(self, current_tier: str, target_tier: str, email: str) -> Dict:
395
+ """Simulate upgrade process"""
396
+ price_map = {
397
+ "trial": 0,
398
+ "starter": 2000,
399
+ "professional": 5000,
400
+ "enterprise": 15000
401
+ }
402
+
403
+ return {
404
+ "current_tier": current_tier,
405
+ "target_tier": target_tier,
406
+ "monthly_price": price_map[target_tier],
407
+ "enforcement_improvement": self._get_enforcement_improvement(current_tier, target_tier),
408
+ "next_steps": "Contact sales@arf.dev for upgrade",
409
+ "estimated_setup": "24 hours"
410
+ }
411
+
412
+ def _get_enforcement_improvement(self, current: str, target: str) -> str:
413
+ improvements = {
414
+ ("trial", "starter"): "Human-in-the-loop approval",
415
+ ("trial", "professional"): "Autonomous execution for low-risk actions",
416
+ ("trial", "enterprise"): "Full mechanical enforcement with audit",
417
+ ("starter", "professional"): "Remove human bottleneck",
418
+ ("starter", "enterprise"): "Add compliance automation",
419
+ ("professional", "enterprise"): "Enterprise-scale enforcement"
420
+ }
421
+ return improvements.get((current, target), "Enhanced enforcement capabilities")
422
+
423
+ # Gradio Interface Components
424
+ def create_oss_panel(oss_result: Dict) -> gr.Blocks:
425
+ """Create OSS results panel"""
426
+ with gr.Column(variant="panel"):
427
+ gr.Markdown("### πŸ”΅ ARF 3.3.9 OSS (Open Source)")
428
+
429
+ # Score indicators
430
+ with gr.Row():
431
+ gr.Metric(label="Reliability Score", value=f"{oss_result['reliability_score']:.2%}")
432
+ gr.Metric(label="Risk Level", value=oss_result['risk_level'],
433
+ delta="High" if oss_result['risk_score'] > 0.7 else None)
434
+ gr.Metric(label="Confidence", value=f"{oss_result['confidence']:.2%}")
435
+
436
+ # Recommendation box
437
+ recommendation_color = "red" if oss_result['risk_level'] == "High" else "yellow" if oss_result['risk_level'] == "Medium" else "green"
438
+ gr.HTML(f"""
439
+ <div style='background-color: #E3F2FD; padding: 15px; border-radius: 10px; border-left: 5px solid #{'E53935' if recommendation_color == 'red' else 'FFB300' if recommendation_color == 'yellow' else '43A047'}; margin: 10px 0;'>
440
+ <h4 style='margin-top: 0;'>πŸ’‘ Recommendation</h4>
441
+ <p style='font-size: 16px;'>{oss_result['recommendation']}</p>
442
+ <p style='font-size: 12px; color: #666;'>Processing time: {oss_result['processing_time']:.3f}s</p>
443
+ </div>
444
+ """)
445
+
446
+ # Limitations
447
+ with gr.Accordion("⚠️ OSS Limitations", open=False):
448
+ gr.Markdown(f"""
449
+ **Advisory Only**: {oss_result['limitation']}
450
+
451
+ **Policy Violations**: {oss_result['policy_violations']} violation(s) detected
452
+
453
+ **Execution Authority**: {'βœ… Can execute' if oss_result['can_execute_oss'] else '❌ Cannot execute - human decision required'}
454
+
455
+ **Version**: {oss_result['engine_version']}
456
+ """)
457
+
458
+ # Show violation details if any
459
+ if oss_result['policy_violations'] > 0 and oss_result['violation_details']:
460
+ with gr.Accordion(f"πŸ” Policy Violations ({oss_result['policy_violations']})", open=False):
461
+ for i, violation in enumerate(oss_result['violation_details'][:3]):
462
+ gr.Textbox(f"{i+1}. {violation}", interactive=False, show_copy_button=True)
463
+
464
+ def create_enterprise_panel(enterprise_result: Dict) -> gr.Blocks:
465
+ """Create Enterprise results panel"""
466
+ with gr.Column(variant="panel"):
467
+ gr.Markdown(f"### 🟑 ARF 3.3.9 Enterprise ({enterprise_result.get('license_tier', 'Trial').title()})")
468
+
469
+ # License and Gate status
470
+ with gr.Row():
471
+ gr.Metric(label="License Tier", value=enterprise_result.get('license_tier', 'Trial').title())
472
+ gr.Metric(label="Gates Passed",
473
+ value=f"{enterprise_result['gates_passed']}/{enterprise_result['total_gates']}")
474
+ gr.Metric(label="Enforcement",
475
+ value=enterprise_result.get('enforcement_level', 'advisory').replace('_', ' ').title())
476
+
477
+ # Gate visualization
478
+ gate_html = "<div style='margin: 15px 0;'>"
479
+ for gate_name, gate_result in enterprise_result.get('gate_results', {}).items():
480
+ status = "βœ…" if gate_result['passed'] else "❌"
481
+ gate_html += f"""
482
+ <div style='background-color: {'#E8F5E9' if gate_result['passed'] else '#FFEBEE'};
483
+ padding: 8px 12px; margin: 5px 0; border-radius: 6px; border-left: 4px solid {'#4CAF50' if gate_result['passed'] else '#F44336'};'>
484
+ <div style='display: flex; justify-content: space-between; align-items: center;'>
485
+ <span><strong>{gate_name.replace('_', ' ').title()}</strong></span>
486
+ <span>{status}</span>
487
+ </div>
488
+ <div style='font-size: 12px; color: #666;'>{gate_result['message']}</div>
489
+ </div>
490
+ """
491
+ gate_html += "</div>"
492
+ gr.HTML(gate_html)
493
+
494
+ # Execution Authority
495
+ authority = enterprise_result['execution_authority']
496
+ authority_color = "#4CAF50" if authority == "GRANTED" else "#F44336"
497
+ gr.HTML(f"""
498
+ <div style='background-color: {authority_color}20; padding: 20px; border-radius: 10px; border: 2px solid {authority_color}; text-align: center; margin: 15px 0;'>
499
+ <h2 style='margin: 0; color: {authority_color};'>{authority}</h2>
500
+ <p style='margin: 5px 0 0 0; font-size: 14px;'>
501
+ {'πŸŽ‰ Autonomous execution permitted' if authority == 'GRANTED' else 'β›” Mechanical enforcement blocked'}
502
+ </p>
503
+ </div>
504
+ """)
505
+
506
+ # Enterprise Benefits
507
+ with gr.Accordion("πŸš€ Enterprise Benefits", open=True):
508
+ gr.Markdown(f"""
509
+ **Mechanical Enforcement**: {enterprise_result['benefit']}
510
+
511
+ **Audit Trail**: Logged with ID: {enterprise_result.get('audit_id', 'N/A')}
512
+
513
+ **License Tier**: {enterprise_result.get('license_tier', 'Trial').title()} with {enterprise_result.get('enforcement_level', 'advisory')} enforcement
514
+
515
+ **Decision Speed**: {enterprise_result['processing_time']:.3f}s (same as OSS)
516
+ """)
517
+
518
+ def create_upgrade_panel():
519
+ """Create upgrade comparison and CTA panel"""
520
+ with gr.Column(variant="panel"):
521
+ gr.Markdown("### ⚑ Upgrade to Enterprise")
522
+
523
+ # Pricing Tiers
524
+ with gr.Row():
525
+ with gr.Column(scale=1, min_width=150):
526
+ gr.Markdown("""
527
+ #### πŸ’° Starter
528
+ **$2,000/mo**
529
+
530
+ β€’ Human approval gates
531
+ β€’ 10 agents
532
+ β€’ Basic audit
533
+ """)
534
+ gr.Button("Select", variant="secondary", size="sm")
535
+
536
+ with gr.Column(scale=1, min_width=150):
537
+ gr.Markdown("""
538
+ #### πŸš€ Professional
539
+ **$5,000/mo**
540
+
541
+ β€’ Autonomous execution
542
+ β€’ 50 agents
543
+ β€’ Advanced gates
544
+ """)
545
+ gr.Button("Select", variant="secondary", size="sm")
546
+
547
+ with gr.Column(scale=1, min_width=150):
548
+ gr.Markdown("""
549
+ #### 🏒 Enterprise
550
+ **$15,000/mo**
551
+
552
+ β€’ Full mechanical enforcement
553
+ β€’ 1000+ agents
554
+ β€’ Compliance automation
555
+ """)
556
+ gr.Button("Select", variant="primary", size="sm")
557
+
558
+ # Trial License Form
559
+ with gr.Accordion("🎁 Get 14-Day Trial License", open=True):
560
+ email_input = gr.Textbox(label="Work Email", placeholder="you@company.com")
561
+ get_trial_btn = gr.Button("Get Trial License", variant="primary")
562
+ trial_output = gr.JSON(label="Your Trial License")
563
+
564
+ # Link button to function
565
+ demo_app = ARFDemo()
566
+ get_trial_btn.click(
567
+ demo_app.generate_trial_license,
568
+ inputs=[email_input],
569
+ outputs=[trial_output]
570
+ )
571
+
572
+ # Value Proposition
573
+ gr.Markdown("""
574
+ ---
575
+ ### 🎯 Why Upgrade?
576
+
577
+ | | OSS | Enterprise |
578
+ |---|---|---|
579
+ | **Enforcement** | Advisory only | Mechanical gates |
580
+ | **Speed** | Human decides | Automated decisions |
581
+ | **Scale** | Manual review | Autonomous at scale |
582
+ | **Compliance** | Self-managed | Built-in audit trail |
583
+ | **Support** | Community | Enterprise SLA |
584
+
585
+ **Bottom Line**: Reduce operational risk by 92% with mechanical enforcement.
586
+ """)
587
+
588
+ # Main Demo Interface
589
+ def create_demo_interface():
590
+ """Create the main Gradio interface"""
591
+ demo_app = ARFDemo()
592
+
593
+ with gr.Blocks(
594
+ title="Agentic Reliability Framework (ARF) 3.3.9 Demo",
595
+ theme=gr.themes.Soft(
596
+ primary_hue="blue",
597
+ secondary_hue="orange"
598
+ ),
599
+ css="""
600
+ .gradio-container { max-width: 1200px; margin: 0 auto; }
601
+ .demo-box { border: 1px solid #ddd; border-radius: 10px; padding: 20px; margin: 10px 0; }
602
+ .oss-header { background: linear-gradient(135deg, #1E88E5 0%, #64B5F6 100%); color: white; padding: 15px; border-radius: 10px; }
603
+ .enterprise-header { background: linear-gradient(135deg, #FFB300 0%, #FFD54F 100%); color: white; padding: 15px; border-radius: 10px; }
604
+ """
605
+ ) as demo:
606
+ gr.Markdown("""
607
+ # πŸ€– Agentic Reliability Framework (ARF) 3.3.9
608
+ ### OSS vs Enterprise Capabilities Demo
609
+
610
+ **Experience the difference**: Open-source advisory vs Enterprise mechanical enforcement
611
+ """)
612
+
613
+ # Demo Controls
614
+ with gr.Row():
615
+ with gr.Column(scale=3):
616
+ scenario_select = gr.Dropdown(
617
+ choices=list(demo_app.demo_scenarios.keys()),
618
+ label="Select Demo Scenario",
619
+ value="database_drop"
620
+ )
621
+ action_input = gr.Textbox(
622
+ label="Or Enter Custom Action",
623
+ placeholder="e.g., DROP DATABASE production, deploy_service v1.2.3, etc.",
624
+ value="DROP DATABASE production"
625
+ )
626
+ license_input = gr.Textbox(
627
+ label="Enterprise License Key",
628
+ placeholder="Enter ARF-TRIAL-XXXXXXX or leave blank for OSS only",
629
+ value=""
630
+ )
631
+
632
+ process_btn = gr.Button("πŸš€ Process Action", variant="primary", size="lg")
633
+
634
+ with gr.Column(scale=1):
635
+ gr.Markdown("""
636
+ ### Quick Actions
637
+ """)
638
+ quick_actions = gr.Radio(
639
+ choices=["High Risk", "Medium Risk", "Low Risk", "Custom"],
640
+ label="Risk Level",
641
+ value="High Risk"
642
+ )
643
+
644
+ # Results Display
645
+ with gr.Row():
646
+ with gr.Column(scale=1):
647
+ oss_output = gr.JSON(label="ARF OSS Results", visible=False)
648
+ oss_panel = gr.HTML()
649
+
650
+ with gr.Column(scale=1):
651
+ enterprise_output = gr.JSON(label="ARF Enterprise Results", visible=False)
652
+ enterprise_panel = gr.HTML()
653
+
654
+ # Comparison Visualization
655
+ with gr.Accordion("πŸ“Š Side-by-Side Comparison", open=True):
656
+ comparison_html = gr.HTML()
657
+
658
+ # Upgrade Panel
659
+ create_upgrade_panel()
660
+
661
+ # Processing function
662
+ def process_action(scenario, action, license_key, quick_action):
663
+ """Process action through both OSS and Enterprise"""
664
+ # Use scenario if provided, otherwise use custom action
665
+ if scenario and scenario in demo_app.demo_scenarios:
666
+ effective_action = demo_app.demo_scenarios[scenario]["action"]
667
+ else:
668
+ effective_action = action
669
+
670
+ # Process through OSS
671
+ oss_result = demo_app.process_action_oss(effective_action, scenario if scenario else None)
672
+
673
+ # Process through Enterprise if license provided
674
+ enterprise_result = None
675
+ if license_key and license_key.startswith("ARF-"):
676
+ enterprise_result = demo_app.process_action_enterprise(
677
+ effective_action, license_key, scenario if scenario else None
678
+ )
679
+ else:
680
+ # Show what Enterprise would do with trial
681
+ enterprise_result = {
682
+ **oss_result,
683
+ "license_tier": "trial",
684
+ "enforcement_level": "advisory",
685
+ "gates_passed": 0,
686
+ "total_gates": 4,
687
+ "execution_authority": "REQUIRES UPGRADE",
688
+ "can_execute_enterprise": False,
689
+ "benefit": "Upgrade to Enterprise for mechanical enforcement",
690
+ "gate_results": {}
691
+ }
692
+
693
+ # Create visual panels
694
+ oss_html = create_oss_panel_html(oss_result)
695
+ enterprise_html = create_enterprise_panel_html(enterprise_result)
696
+
697
+ # Create comparison visualization
698
+ comparison_data = create_comparison_data(oss_result, enterprise_result)
699
+
700
+ return oss_result, oss_html, enterprise_result, enterprise_html, comparison_data
701
+
702
+ # Connect button
703
+ process_btn.click(
704
+ process_action,
705
+ inputs=[scenario_select, action_input, license_input, quick_actions],
706
+ outputs=[oss_output, oss_panel, enterprise_output, enterprise_panel, comparison_html]
707
+ )
708
+
709
+ # Quick action examples
710
+ def update_quick_action(quick_action):
711
+ examples = {
712
+ "High Risk": "DELETE FROM users WHERE id < 1000",
713
+ "Medium Risk": "ALTER TABLE payments ADD COLUMN metadata JSONB",
714
+ "Low Risk": "SELECT COUNT(*) FROM logs WHERE created_at > NOW() - INTERVAL '1 hour'",
715
+ "Custom": ""
716
+ }
717
+ return examples[quick_action]
718
+
719
+ quick_actions.change(
720
+ update_quick_action,
721
+ inputs=[quick_actions],
722
+ outputs=[action_input]
723
+ )
724
+
725
+ # Pre-load first scenario
726
+ demo.load(
727
+ lambda: process_action(
728
+ "database_drop",
729
+ "DROP DATABASE production",
730
+ "",
731
+ "High Risk"
732
+ ),
733
+ outputs=[oss_output, oss_panel, enterprise_output, enterprise_panel, comparison_html]
734
+ )
735
+
736
+ return demo
737
+
738
+ # Helper functions for HTML generation
739
+ def create_oss_panel_html(result: Dict) -> str:
740
+ """Generate HTML for OSS panel"""
741
+ risk_color = "#E53935" if result['risk_level'] == "High" else "#FFB300" if result['risk_level'] == "Medium" else "#43A047"
742
+
743
+ return f"""
744
+ <div class="oss-header">
745
+ <h3 style="margin: 0;">πŸ”΅ ARF 3.3.9 OSS (Open Source)</h3>
746
+ </div>
747
+
748
+ <div style="padding: 20px; background: white; border-radius: 0 0 10px 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
749
+ <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
750
+ <div style="text-align: center; padding: 15px; background: #E3F2FD; border-radius: 8px;">
751
+ <div style="font-size: 12px; color: #1E88E5; margin-bottom: 5px;">Reliability Score</div>
752
+ <div style="font-size: 24px; font-weight: bold; color: #1E88E5;">{result['reliability_score']:.1%}</div>
753
+ </div>
754
+
755
+ <div style="text-align: center; padding: 15px; background: #E3F2FD; border-radius: 8px;">
756
+ <div style="font-size: 12px; color: {risk_color}; margin-bottom: 5px;">Risk Level</div>
757
+ <div style="font-size: 24px; font-weight: bold; color: {risk_color};">{result['risk_level']}</div>
758
+ </div>
759
+
760
+ <div style="text-align: center; padding: 15px; background: #E3F2FD; border-radius: 8px;">
761
+ <div style="font-size: 12px; color: #1E88E5; margin-bottom: 5px;">Confidence</div>
762
+ <div style="font-size: 24px; font-weight: bold; color: #1E88E5;">{result['confidence']:.1%}</div>
763
+ </div>
764
+ </div>
765
+
766
+ <div style="background: #F5F5F5; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid {risk_color};">
767
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
768
+ <span style="font-size: 24px; margin-right: 10px;">πŸ’‘</span>
769
+ <h4 style="margin: 0;">Recommendation</h4>
770
+ </div>
771
+ <p style="margin: 0; font-size: 16px; color: #333;">{result['recommendation']}</p>
772
+ <p style="margin: 5px 0 0 0; font-size: 12px; color: #666;">Processing time: {result['processing_time']:.3f}s</p>
773
+ </div>
774
+
775
+ <div style="background: #FFF3E0; padding: 15px; border-radius: 8px;">
776
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
777
+ <span style="font-size: 24px; margin-right: 10px;">⚠️</span>
778
+ <h4 style="margin: 0;">OSS Limitations</h4>
779
+ </div>
780
+ <p style="margin: 0; color: #E65100;"><strong>Advisory Only:</strong> {result['limitation']}</p>
781
+ <p style="margin: 5px 0; color: #E65100;"><strong>Policy Violations:</strong> {result['policy_violations']} detected</p>
782
+ <p style="margin: 0; color: #E65100;"><strong>Execution Authority:</strong> {'βœ… Can execute' if result['can_execute_oss'] else '❌ Cannot execute - human decision required'}</p>
783
+ </div>
784
+ </div>
785
+ """
786
+
787
+ def create_enterprise_panel_html(result: Dict) -> str:
788
+ """Generate HTML for Enterprise panel"""
789
+ license_tier = result.get('license_tier', 'trial').title()
790
+ authority = result.get('execution_authority', 'REQUIRES UPGRADE')
791
+ authority_color = "#4CAF50" if authority == "GRANTED" else "#F44336" if authority == "DENIED" else "#FF9800"
792
+ gates_passed = result.get('gates_passed', 0)
793
+ total_gates = result.get('total_gates', 4)
794
+
795
+ # Generate gates HTML
796
+ gates_html = ""
797
+ for gate_name, gate_result in result.get('gate_results', {}).items():
798
+ gate_passed = gate_result.get('passed', False)
799
+ gate_color = "#4CAF50" if gate_passed else "#F44336"
800
+ gates_html += f"""
801
+ <div style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #eee;">
802
+ <span style="margin-right: 10px; font-size: 18px; color: {gate_color};">{'βœ…' if gate_passed else '❌'}</span>
803
+ <div style="flex: 1;">
804
+ <div style="font-weight: 500;">{gate_name.replace('_', ' ').title()}</div>
805
+ <div style="font-size: 12px; color: #666;">{gate_result.get('message', '')}</div>
806
+ </div>
807
+ </div>
808
+ """
809
+
810
+ return f"""
811
+ <div class="enterprise-header">
812
+ <h3 style="margin: 0;">🟑 ARF 3.3.9 Enterprise ({license_tier})</h3>
813
+ </div>
814
+
815
+ <div style="padding: 20px; background: white; border-radius: 0 0 10px 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
816
+ <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
817
+ <div style="text-align: center; padding: 15px; background: #FFF8E1; border-radius: 8px;">
818
+ <div style="font-size: 12px; color: #FF8F00; margin-bottom: 5px;">License Tier</div>
819
+ <div style="font-size: 20px; font-weight: bold; color: #FF8F00;">{license_tier}</div>
820
+ </div>
821
+
822
+ <div style="text-align: center; padding: 15px; background: #FFF8E1; border-radius: 8px;">
823
+ <div style="font-size: 12px; color: #FF8F00; margin-bottom: 5px;">Gates Passed</div>
824
+ <div style="font-size: 24px; font-weight: bold; color: #FF8F00;">{gates_passed}/{total_gates}</div>
825
+ </div>
826
+
827
+ <div style="text-align: center; padding: 15px; background: #FFF8E1; border-radius: 8px;">
828
+ <div style="font-size: 12px; color: #FF8F00; margin-bottom: 5px;">Enforcement</div>
829
+ <div style="font-size: 14px; font-weight: bold; color: #FF8F00;">{result.get('enforcement_level', 'advisory').replace('_', ' ').title()}</div>
830
+ </div>
831
+ </div>
832
+
833
+ <div style="margin-bottom: 20px;">
834
+ <h4 style="margin-bottom: 10px; color: #FF8F00;">Mechanical Gates</h4>
835
+ <div style="background: #FFFDE7; padding: 15px; border-radius: 8px;">
836
+ {gates_html if gates_html else "<p style='color: #666; text-align: center;'>No gate data available</p>"}
837
+ </div>
838
+ </div>
839
+
840
+ <div style="background: {authority_color}20; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid {authority_color}; margin-bottom: 20px;">
841
+ <div style="font-size: 28px; font-weight: bold; color: {authority_color}; margin-bottom: 5px;">{authority}</div>
842
+ <div style="color: {authority_color};">
843
+ {'πŸŽ‰ Autonomous execution permitted' if authority == 'GRANTED' else 'β›” Mechanical enforcement blocked' if authority == 'DENIED' else '⬆️ Upgrade required for enforcement'}
844
+ </div>
845
+ </div>
846
+
847
+ <div style="background: #E8F5E9; padding: 15px; border-radius: 8px;">
848
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
849
+ <span style="font-size: 24px; margin-right: 10px;">πŸš€</span>
850
+ <h4 style="margin: 0;">Enterprise Benefits</h4>
851
+ </div>
852
+ <p style="margin: 0; color: #2E7D32;"><strong>Mechanical Enforcement:</strong> {result.get('benefit', 'Automated decision making')}</p>
853
+ <p style="margin: 5px 0; color: #2E7D32;"><strong>Audit Trail:</strong> {result.get('audit_id', 'Available with license')}</p>
854
+ <p style="margin: 0; color: #2E7D32;"><strong>Decision Speed:</strong> {result.get('processing_time', 0):.3f}s (same as OSS)</p>
855
+ </div>
856
+ </div>
857
+ """
858
+
859
+ def create_comparison_data(oss_result: Dict, enterprise_result: Dict) -> str:
860
+ """Create comparison visualization HTML"""
861
+ # Calculate key metrics
862
+ oss_can_execute = oss_result.get('can_execute_oss', False)
863
+ enterprise_can_execute = enterprise_result.get('can_execute_enterprise', False)
864
+ gates_passed = enterprise_result.get('gates_passed', 0)
865
+ total_gates = enterprise_result.get('total_gates', 4)
866
+
867
+ return f"""
868
+ <div style="padding: 20px; background: white; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
869
+ <h3 style="margin-top: 0; text-align: center;">πŸ“Š Side-by-Side Comparison</h3>
870
+
871
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
872
+ <!-- OSS Column -->
873
+ <div style="text-align: center;">
874
+ <h4 style="color: #1E88E5;">πŸ”΅ OSS 3.3.9</h4>
875
+ <div style="margin: 15px 0;">
876
+ <div style="font-size: 48px; color: #1E88E5; margin-bottom: 5px;">{'⚠️' if not oss_can_execute else 'βœ…'}</div>
877
+ <div style="font-size: 18px; font-weight: bold; color: {'#E53935' if not oss_can_execute else '#43A047'}">
878
+ {'Advisory Only' if not oss_can_execute else 'Can Execute'}
879
+ </div>
880
+ </div>
881
+ <div style="background: #E3F2FD; padding: 10px; border-radius: 6px; margin: 5px 0;">
882
+ <strong>Human Decision Required</strong>
883
+ </div>
884
+ <div style="background: #E3F2FD; padding: 10px; border-radius: 6px; margin: 5px 0;">
885
+ Risk: {oss_result.get('risk_level', 'Unknown')}
886
+ </div>
887
+ <div style="background: #E3F2FD; padding: 10px; border-radius: 6px; margin: 5px 0;">
888
+ {oss_result.get('policy_violations', 0)} Policy Violations
889
+ </div>
890
+ </div>
891
+
892
+ <!-- Enterprise Column -->
893
+ <div style="text-align: center;">
894
+ <h4 style="color: #FFB300;">🟑 Enterprise</h4>
895
+ <div style="margin: 15px 0;">
896
+ <div style="font-size: 48px; color: #FFB300; margin-bottom: 5px;">
897
+ {'β›”' if not enterprise_can_execute else 'βœ…'}
898
+ </div>
899
+ <div style="font-size: 18px; font-weight: bold; color: {'#F44336' if not enterprise_can_execute else '#43A047'}">
900
+ {enterprise_result.get('execution_authority', 'REQUIRES UPGRADE')}
901
+ </div>
902
+ </div>
903
+ <div style="background: #FFF8E1; padding: 10px; border-radius: 6px; margin: 5px 0;">
904
+ <strong>Mechanical Enforcement</strong>
905
+ </div>
906
+ <div style="background: #FFF8E1; padding: 10px; border-radius: 6px; margin: 5px 0;">
907
+ {gates_passed}/{total_gates} Gates Passed
908
+ </div>
909
+ <div style="background: #FFF8E1; padding: 10px; border-radius: 6px; margin: 5px 0;">
910
+ License: {enterprise_result.get('license_tier', 'trial').title()}
911
+ </div>
912
+ </div>
913
+ </div>
914
+
915
+ <!-- Value Proposition -->
916
+ <div style="margin-top: 20px; padding: 15px; background: linear-gradient(135deg, #FFB30020 0%, #1E88E520 100%); border-radius: 8px;">
917
+ <h4 style="text-align: center; margin-top: 0;">🎯 Upgrade Value Proposition</h4>
918
+ <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
919
+ <div style="text-align: center; padding: 10px;">
920
+ <div style="font-size: 12px; color: #666;">Risk Reduction</div>
921
+ <div style="font-size: 20px; font-weight: bold; color: #43A047;">92%</div>
922
+ </div>
923
+ <div style="text-align: center; padding: 10px;">
924
+ <div style="font-size: 12px; color: #666;">Decision Speed</div>
925
+ <div style="font-size: 20px; font-weight: bold; color: #43A047;">100x</div>
926
+ </div>
927
+ <div style="text-align: center; padding: 10px;">
928
+ <div style="font-size: 12px; color: #666;">False Positives</div>
929
+ <div style="font-size: 20px; font-weight: bold; color: #43A047;">-85%</div>
930
+ </div>
931
+ <div style="text-align: center; padding: 10px;">
932
+ <div style="font-size: 12px; color: #666;">Operational Cost</div>
933
+ <div style="font-size: 20px; font-weight: bold; color: #43A047;">-75%</div>
934
+ </div>
935
+ </div>
936
+ </div>
937
+ </div>
938
+ """
939
+
940
+ # Launch the demo
941
+ if __name__ == "__main__":
942
+ demo = create_demo_interface()
943
+ demo.launch(
944
+ server_name="0.0.0.0",
945
+ server_port=7860,
946
+ share=True,
947
+ debug=True
948
+ )