petter2025 commited on
Commit
c72568f
·
verified ·
1 Parent(s): ac052ea

Update hf_demo.py

Browse files
Files changed (1) hide show
  1. hf_demo.py +794 -452
hf_demo.py CHANGED
@@ -1,6 +1,5 @@
1
  """
2
- ARF 3.3.9 Demo - Psychology-Optimized Version
3
- Fixed with proper error handling
4
  """
5
 
6
  import gradio as gr
@@ -13,209 +12,184 @@ import uuid
13
  import hashlib
14
  import random
15
  import traceback
16
- import sys
17
- from typing import Dict, List, Any, Tuple, Optional
18
- from dataclasses import dataclass
19
- from enum import Enum
20
- import re
21
 
22
  print("=" * 70)
23
- print("🧠 ARF 3.3.9 DEMO - Psychology-Optimized Edition")
24
  print("=" * 70)
25
 
26
  # ============================================================================
27
- # ENUMS AND DATA CLASSES
28
- # ============================================================================
29
-
30
- class RiskLevel(str, Enum):
31
- CRITICAL = "CRITICAL"
32
- HIGH = "HIGH"
33
- MEDIUM = "MEDIUM"
34
- LOW = "LOW"
35
- SAFE = "SAFE"
36
-
37
- class EnforcementLevel(str, Enum):
38
- ADVISORY = "ADVISORY"
39
- HUMAN_APPROVAL = "HUMAN_APPROVAL"
40
- AUTONOMOUS = "AUTONOMOUS"
41
- FULL_MECHANICAL = "FULL_MECHANICAL"
42
-
43
- class LicenseTier(str, Enum):
44
- TRIAL = "TRIAL"
45
- STARTER = "STARTER"
46
- PROFESSIONAL = "PROFESSIONAL"
47
- ENTERPRISE = "ENTERPRISE"
48
-
49
- @dataclass
50
- class RiskAssessment:
51
- score: float
52
- level: RiskLevel
53
- confidence: float
54
- factors: Dict[str, float]
55
-
56
- @property
57
- def color(self) -> str:
58
- return {
59
- RiskLevel.CRITICAL: "#D32F2F",
60
- RiskLevel.HIGH: "#F44336",
61
- RiskLevel.MEDIUM: "#FF9800",
62
- RiskLevel.LOW: "#4CAF50",
63
- RiskLevel.SAFE: "#2E7D32"
64
- }[self.level]
65
-
66
- @property
67
- def icon(self) -> str:
68
- return {
69
- RiskLevel.CRITICAL: "🔥",
70
- RiskLevel.HIGH: "⚠️",
71
- RiskLevel.MEDIUM: "🔶",
72
- RiskLevel.LOW: "✅",
73
- RiskLevel.SAFE: "🛡️"
74
- }[self.level]
75
-
76
- @dataclass
77
- class GateResult:
78
- name: str
79
- passed: bool
80
- message: str
81
- required: bool = True
82
- weight: float = 1.0
83
-
84
- @property
85
- def color(self) -> str:
86
- return "#4CAF50" if self.passed else "#F44336"
87
-
88
- @property
89
- def icon(self) -> str:
90
- return "✅" if self.passed else "❌"
91
-
92
- # ============================================================================
93
- # SIMPLIFIED BUT ROBUST ENGINE
94
  # ============================================================================
95
 
96
  class ARFEngine:
97
- """Simplified but robust ARF engine"""
98
 
99
  def __init__(self):
100
  self.stats = {
101
  "total_processed": 0,
102
  "blocked_actions": 0,
103
  "autonomous_executions": 0,
104
- "avg_processing_time": 0.0
 
 
 
 
 
 
 
 
 
 
105
  }
106
- print("✅ ARF Engine initialized")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
- def assess_action(self, action: str, context: Dict, license_key: str = None) -> Dict:
109
- """Assess an action with realistic scoring"""
110
  start_time = time.time()
111
 
112
  # 1. Risk Assessment
113
- risk = self._assess_risk(action, context)
114
 
115
  # 2. Policy Evaluation
116
- policy_result = self._evaluate_policies(action, context, risk.score)
117
 
118
  # 3. License Validation
119
  license_info = self._validate_license(license_key)
120
 
121
  # 4. Gate Evaluation
122
- gate_results = self._evaluate_gates(risk, policy_result, license_info)
 
 
 
 
 
123
 
124
- # 5. Generate results
125
  processing_time = time.time() - start_time
126
 
127
- # Update stats
128
- self._update_stats(policy_result, gate_results, processing_time)
129
 
130
  return {
131
- "timestamp": datetime.now().isoformat(),
132
  "action": action,
133
- "risk_assessment": risk,
 
 
134
  "policy_result": policy_result,
135
  "license_info": license_info,
136
  "gate_results": gate_results,
137
- "processing_time": round(processing_time, 4),
138
- "recommendation": self._generate_recommendation(policy_result, gate_results, license_info)
 
 
139
  }
140
 
141
- def _assess_risk(self, action: str, context: Dict) -> RiskAssessment:
142
- """Assess risk with realistic scoring"""
143
  action_lower = action.lower()
144
 
145
- # Calculate risk factors
146
- destructiveness = 0.3
147
- if "drop" in action_lower and "database" in action_lower:
148
- destructiveness = 0.95
149
- elif "delete" in action_lower:
150
- destructiveness = 0.85
151
- elif "truncate" in action_lower:
152
- destructiveness = 0.80
153
-
154
- complexity = min(0.8, len(action.split()) * 0.05)
155
-
156
- env = context.get("environment", "development")
157
- environment_risk = {
158
- "production": 0.8,
159
- "staging": 0.5,
160
- "testing": 0.3,
161
- "development": 0.2
162
- }.get(env, 0.5)
163
 
164
  # Weighted risk score
165
- risk_score = (
166
- destructiveness * 0.4 +
167
- complexity * 0.2 +
168
- environment_risk * 0.4
169
- )
170
-
171
- # Determine risk level
172
- if risk_score >= 0.8:
173
- level = RiskLevel.CRITICAL
174
- elif risk_score >= 0.6:
175
- level = RiskLevel.HIGH
176
- elif risk_score >= 0.4:
177
- level = RiskLevel.MEDIUM
178
- elif risk_score >= 0.2:
179
- level = RiskLevel.LOW
180
- else:
181
- level = RiskLevel.SAFE
182
 
183
  # Confidence (higher for clear patterns)
184
- confidence = 0.8
185
  if "drop database" in action_lower:
186
  confidence = 0.95
187
  elif "delete from" in action_lower:
188
  confidence = 0.90
 
 
 
 
189
 
190
- return RiskAssessment(
191
- score=round(risk_score, 3),
192
- level=level,
193
- confidence=round(confidence, 3),
194
- factors={
195
- "destructiveness": destructiveness,
196
- "complexity": complexity,
197
- "environment": environment_risk
198
- }
199
- )
200
 
201
- def _evaluate_policies(self, action: str, context: Dict, risk_score: float) -> Dict:
 
 
 
 
 
 
 
 
 
 
 
 
202
  """Evaluate against safety policies"""
203
  violations = []
 
204
 
205
- # Policy 1: No destructive operations in production without approval
206
- if ("drop" in action.lower() or "delete" in action.lower()) and context.get("environment") == "production":
207
  violations.append({
208
  "policy": "Destructive Operation Prevention",
209
  "severity": "CRITICAL",
210
- "action": "BLOCK"
 
211
  })
212
 
213
  # Policy 2: High risk actions need review
214
- if risk_score > 0.7 and context.get("environment") == "production":
215
  violations.append({
216
  "policy": "High Risk Review Required",
217
  "severity": "HIGH",
218
- "action": "REQUIRE_APPROVAL"
 
 
 
 
 
 
 
 
 
 
219
  })
220
 
221
  return {
@@ -225,158 +199,284 @@ class ARFEngine:
225
  "total_violations": len(violations)
226
  }
227
 
228
- def _validate_license(self, license_key: str = None) -> Dict:
229
- """Validate license key"""
230
  if not license_key:
231
  return {
232
- "tier": None,
233
  "valid": False,
234
  "name": "OSS Edition",
235
- "enforcement": "ADVISORY",
236
- "message": "🔵 Using ARF OSS (Open Source)"
 
 
237
  }
238
 
239
  if license_key.startswith("ARF-"):
240
  if "TRIAL" in license_key:
241
  return {
242
- "tier": "TRIAL",
243
  "valid": True,
244
- "name": "Trial",
245
- "enforcement": "ADVISORY",
246
- "message": "🎁 Trial License Active (14 days)"
 
 
 
247
  }
248
  elif "PRO" in license_key:
249
  return {
250
- "tier": "PROFESSIONAL",
251
  "valid": True,
252
  "name": "Professional",
253
- "enforcement": "AUTONOMOUS",
254
- "message": "✅ Professional License Active"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
  }
256
 
257
  return {
258
- "tier": None,
259
  "valid": False,
260
  "name": "Invalid",
261
- "enforcement": "ADVISORY",
262
- "message": "❌ Invalid License Key"
 
263
  }
264
 
265
- def _evaluate_gates(self, risk: RiskAssessment, policy: Dict, license: Dict) -> List[GateResult]:
266
  """Evaluate mechanical gates"""
267
  gates = []
268
 
269
  # Gate 1: License Validation
270
- gates.append(GateResult(
271
- name="License Validation",
272
- passed=license.get("valid", False),
273
- message=license.get("message", "No license"),
274
- required=True
275
- ))
276
-
277
- # Gate 2: Risk Threshold
278
- risk_threshold = 0.8 if license.get("tier") in ["PROFESSIONAL", "ENTERPRISE"] else 0.7
279
- gates.append(GateResult(
280
- name="Risk Assessment",
281
- passed=risk.score <= risk_threshold,
282
- message=f"Risk {risk.score:.1%} {risk_threshold:.0%} threshold",
283
- required=True
284
- ))
 
 
285
 
286
  # Gate 3: Confidence Threshold
287
- gates.append(GateResult(
288
- name="Confidence Threshold",
289
- passed=risk.confidence >= 0.7,
290
- message=f"Confidence {risk.confidence:.1%} ≥ 70%",
291
- required=True
292
- ))
 
293
 
294
  # Gate 4: Policy Compliance
295
- gates.append(GateResult(
296
- name="Policy Compliance",
297
- passed=not policy.get("blocked", False),
298
- message=f"{policy.get('total_violations', 0)} policy violations",
299
- required=True
300
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
 
302
  return gates
303
 
304
- def _generate_recommendation(self, policy: Dict, gates: List[GateResult], license: Dict) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
  """Generate recommendation"""
306
- if policy.get("blocked"):
307
- return "🚫 BLOCKED: Action violates safety policies"
308
 
309
- all_gates_passed = all(g.passed for g in gates if g.required)
310
 
311
- if not license.get("valid"):
312
- return "🔵 OSS ADVISORY: Human review recommended"
313
- elif all_gates_passed and license.get("tier") in ["PROFESSIONAL", "ENTERPRISE"]:
314
- return "🟡 ENTERPRISE APPROVED: Autonomous execution permitted"
315
- elif all_gates_passed and license.get("tier") == "STARTER":
316
- return "👤 HUMAN APPROVAL: Gates passed, awaiting confirmation"
317
  else:
318
- return "⚠️ REVIEW REQUIRED: Additional validation needed"
319
 
320
- def _update_stats(self, policy: Dict, gates: List[GateResult], processing_time: float):
321
  """Update statistics"""
322
  self.stats["total_processed"] += 1
323
- if policy.get("blocked"):
 
324
  self.stats["blocked_actions"] += 1
325
 
326
- if all(g.passed for g in gates if g.required):
327
  self.stats["autonomous_executions"] += 1
328
 
329
  # Update average processing time
330
  self.stats["avg_processing_time"] = (
331
  self.stats["avg_processing_time"] * 0.9 + processing_time * 0.1
332
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
333
 
334
- def get_stats(self) -> Dict:
335
- """Get statistics with safe defaults"""
336
  stats = self.stats.copy()
337
 
338
- # Calculate derived stats with error handling
339
- total = stats.get("total_processed", 0)
340
- blocked = stats.get("blocked_actions", 0)
341
- autonomous = stats.get("autonomous_executions", 0)
342
 
343
  stats["blocked_percentage"] = round(blocked / total * 100, 1) if total > 0 else 0.0
344
  stats["autonomous_percentage"] = round(autonomous / total * 100, 1) if total > 0 else 0.0
345
- stats["processing_speed"] = f"{stats.get('avg_processing_time', 0)*1000:.0f}ms"
346
 
347
- # Add default values for any missing keys
348
- defaults = {
349
- "risk_distribution": {"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0, "SAFE": 0},
350
- "system_health": "✅ Optimal",
351
- "license_distribution": {"OSS": 0, "TRIAL": 0, "ENTERPRISE": 0}
352
- }
353
 
354
- for key, value in defaults.items():
355
- if key not in stats:
356
- stats[key] = value
 
 
 
 
 
 
 
357
 
358
  return stats
359
 
360
- def generate_trial_license(self, email: str) -> Dict:
361
- """Generate trial license"""
362
  if not email or "@" not in email:
363
  return {
364
  "success": False,
365
- "message": "Please enter a valid email address"
 
366
  }
367
 
368
- license_key = f"ARF-TRIAL-{hashlib.sha256(email.encode()).hexdigest()[:8].upper()}"
369
 
370
  return {
371
  "success": True,
372
  "license_key": license_key,
373
  "message": "🎉 14-Day Trial License Generated!",
374
- "expires": (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d"),
375
- "features": [
376
- "Mechanical gate evaluation",
377
- "Enterprise dashboard",
378
- "Basic audit trail"
379
- ]
 
 
 
 
 
 
 
 
 
 
 
380
  }
381
 
382
  # ============================================================================
@@ -388,52 +488,46 @@ DEMO_SCENARIOS = [
388
  "id": "high_risk",
389
  "name": "🔥 High-Risk Database Operation",
390
  "action": "DROP DATABASE production_users CASCADE",
391
- "context": {"environment": "production", "criticality": "critical"}
 
 
 
392
  },
393
  {
394
- "id": "safe_deploy",
395
  "name": "✅ Safe Service Deployment",
396
  "action": "deploy_service payment_api:v2.3.1 to staging with 25% canary",
397
- "context": {"environment": "staging", "service": "payment_api", "canary": 25}
 
 
 
398
  },
399
  {
400
  "id": "config_change",
401
  "name": "🔧 Configuration Update",
402
  "action": "UPDATE config SET timeout_ms=30000 WHERE service='api'",
403
- "context": {"environment": "production", "service": "api"}
 
 
 
404
  }
405
  ]
406
 
407
  # ============================================================================
408
- # GRADIO INTERFACE
409
  # ============================================================================
410
 
411
  def create_demo_interface():
412
- """Create the demo interface"""
413
 
414
  # Initialize engine
415
  arf_engine = ARFEngine()
416
 
417
- # Get initial stats with error handling
418
- try:
419
- stats = arf_engine.get_stats()
420
- except Exception as e:
421
- print(f"Error getting stats: {e}")
422
- stats = {
423
- "total_processed": 0,
424
- "blocked_percentage": 0.0,
425
- "autonomous_percentage": 0.0,
426
- "processing_speed": "0ms"
427
- }
428
-
429
- # Safely get values with defaults
430
- total_processed = stats.get("total_processed", 0)
431
- blocked_percentage = stats.get("blocked_percentage", 0.0)
432
- autonomous_percentage = stats.get("autonomous_percentage", 0.0)
433
- processing_speed = stats.get("processing_speed", "0ms")
434
 
435
  with gr.Blocks(
436
- title="ARF 3.3.9 - OSS vs Enterprise Demo",
437
  theme=gr.themes.Soft(),
438
  css="""
439
  .gradio-container {
@@ -441,175 +535,279 @@ def create_demo_interface():
441
  margin: 0 auto;
442
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
443
  }
444
- .demo-card {
445
- border-radius: 10px;
 
 
 
 
 
 
 
 
446
  padding: 20px;
447
- margin-bottom: 20px;
448
- box-shadow: 0 2px 8px rgba(0,0,0,0.1);
 
 
 
 
 
449
  }
450
- .oss-card {
451
  border: 2px solid #1E88E5;
 
 
452
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 100%);
 
453
  }
454
- .enterprise-card {
455
  border: 2px solid #FFB300;
 
 
456
  background: linear-gradient(135deg, #FFF8E1 0%, #FFECB3 100%);
457
- }
458
- .stat-card {
459
- background: white;
460
- padding: 15px;
461
- border-radius: 8px;
462
- text-align: center;
463
- box-shadow: 0 2px 4px rgba(0,0,0,0.1);
464
  }
465
  .gate-passed {
466
  background: #E8F5E9;
467
  border-left: 4px solid #4CAF50;
468
- padding: 10px;
469
- margin: 5px 0;
470
- border-radius: 4px;
471
  }
472
  .gate-failed {
473
  background: #FFEBEE;
474
  border-left: 4px solid #F44336;
475
- padding: 10px;
476
- margin: 5px 0;
477
- border-radius: 4px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478
  }
479
  """
480
  ) as demo:
481
 
482
- # Header
 
 
483
  gr.Markdown("""
484
- # 🤖 Agentic Reliability Framework (ARF) 3.3.9
485
- ### From Advisory to Mechanical Enforcement
 
 
 
 
 
486
  """)
487
 
488
- # Statistics
 
 
489
  gr.Markdown(f"""
490
- <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 20px 0;">
491
  <div class="stat-card">
492
  <div style="font-size: 0.9em; color: #1E88E5; margin-bottom: 5px;">Total Assessments</div>
493
- <div style="font-size: 2em; font-weight: bold; color: #1E88E5;">{total_processed}</div>
 
494
  </div>
495
 
496
  <div class="stat-card">
497
- <div style="font-size: 0.9em; color: #F44336; margin-bottom: 5px;">Risks Blocked</div>
498
- <div style="font-size: 2em; font-weight: bold; color: #F44336;">{blocked_percentage}%</div>
 
499
  </div>
500
 
501
  <div class="stat-card">
502
  <div style="font-size: 0.9em; color: #4CAF50; margin-bottom: 5px;">Autonomous Rate</div>
503
- <div style="font-size: 2em; font-weight: bold; color: #4CAF50;">{autonomous_percentage}%</div>
 
504
  </div>
505
 
506
  <div class="stat-card">
507
  <div style="font-size: 0.9em; color: #FF9800; margin-bottom: 5px;">Processing Speed</div>
508
- <div style="font-size: 2em; font-weight: bold; color: #FF9800;">{processing_speed}</div>
 
509
  </div>
510
  </div>
511
  """)
512
 
513
- # Main controls
 
 
514
  with gr.Row():
515
  with gr.Column(scale=2):
516
  # Scenario selection
517
  scenario_select = gr.Dropdown(
518
  choices=[s["name"] for s in DEMO_SCENARIOS],
519
- label="Select Demo Scenario",
520
- value=DEMO_SCENARIOS[0]["name"]
 
521
  )
522
 
523
  # Action input
524
  action_input = gr.Textbox(
525
- label="Action to Evaluate",
526
  value=DEMO_SCENARIOS[0]["action"],
527
- lines=2
 
528
  )
529
 
530
  # Context input
531
  context_input = gr.Textbox(
532
- label="Context (JSON)",
533
  value=json.dumps(DEMO_SCENARIOS[0]["context"], indent=2),
534
- lines=3
 
535
  )
536
 
537
- # License input
538
  license_input = gr.Textbox(
539
- label="Enterprise License Key (Optional)",
540
- placeholder="Enter ARF-TRIAL-XXXXXXX or leave blank for OSS",
541
- value=""
 
542
  )
543
 
544
- # Buttons
545
  with gr.Row():
546
- process_btn = gr.Button("🚀 Process Action", variant="primary", size="lg")
547
- clear_btn = gr.Button("🔄 Clear", variant="secondary")
548
 
549
  with gr.Column(scale=1):
550
- # Quick examples
551
- gr.Markdown("### Quick Examples")
552
- quick_examples = gr.Radio(
553
- choices=["High Risk", "Medium Risk", "Low Risk"],
554
- label="Risk Level",
555
- value="High Risk"
556
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
557
 
558
- # License status
559
- gr.Markdown("### License Status")
560
  license_status = gr.HTML("""
561
- <div style="background: #E3F2FD; padding: 15px; border-radius: 8px; text-align: center;">
562
- <div style="color: #1E88E5; font-weight: bold; margin-bottom: 5px;">🔵 ARF OSS Edition</div>
563
- <div style="color: #666; font-size: 0.9em;">Advisory Mode - No license required</div>
 
 
 
 
564
  </div>
565
  """)
566
 
567
- # Results
 
 
568
  with gr.Row():
569
  with gr.Column(scale=1):
570
- oss_output = gr.HTML(label="🔵 ARF OSS Results")
571
 
572
  with gr.Column(scale=1):
573
- enterprise_output = gr.HTML(label="🟡 ARF Enterprise Results")
574
 
575
  # Comparison
576
- comparison_output = gr.HTML(label="📊 Side-by-Side Comparison")
577
 
578
- # Trial section
579
- with gr.Accordion("🎁 Get 14-Day Trial License", open=False):
 
 
580
  with gr.Row():
581
  with gr.Column(scale=1):
582
  email_input = gr.Textbox(
583
- label="Work Email",
584
- placeholder="you@company.com"
 
585
  )
586
- trial_btn = gr.Button("Get Trial License", variant="primary")
587
 
588
  with gr.Column(scale=2):
589
- trial_output = gr.JSON(label="Your Trial License")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590
 
591
- # Functions
592
- def process_action(scenario_name, action_text, context_text, license_key, quick_example):
593
- """Process an action"""
 
 
594
  try:
595
- # Update based on quick example
596
- if quick_example == "High Risk":
597
- action_text = "DELETE FROM users WHERE created_at < '2023-01-01'"
598
- context_text = '{"environment": "production"}'
599
- elif quick_example == "Medium Risk":
600
- action_text = "ALTER TABLE payments ADD COLUMN metadata JSONB"
601
- context_text = '{"environment": "staging"}'
602
- elif quick_example == "Low Risk":
603
- action_text = "SELECT COUNT(*) FROM logs"
604
- context_text = '{"environment": "development"}'
605
-
606
- # Use scenario if selected
607
  for scenario in DEMO_SCENARIOS:
608
  if scenario["name"] == scenario_name:
609
- action_text = scenario["action"]
610
- context_text = json.dumps(scenario["context"])
611
  break
612
 
 
 
 
 
 
 
 
 
 
 
613
  # Parse context
614
  try:
615
  context = json.loads(context_text) if context_text.strip() else {}
@@ -619,25 +817,45 @@ def create_demo_interface():
619
  # Process action
620
  result = arf_engine.assess_action(action_text, context, license_key)
621
 
622
- # Create displays
623
- oss_html = create_oss_display(result)
624
  enterprise_html = create_enterprise_display(result)
625
  comparison_html = create_comparison_display(result)
626
 
627
  # Update license status
628
  license_info = result["license_info"]
629
- if license_info.get("valid"):
 
 
 
 
 
 
 
630
  status_html = f"""
631
- <div style="background: #E8F5E9; padding: 15px; border-radius: 8px; text-align: center;">
632
- <div style="color: #2E7D32; font-weight: bold; margin-bottom: 5px;">✅ {license_info['name']} License</div>
633
- <div style="color: #666; font-size: 0.9em;">{license_info['message']}</div>
 
 
 
 
 
 
 
 
 
634
  </div>
635
  """
636
  else:
637
  status_html = """
638
- <div style="background: #E3F2FD; padding: 15px; border-radius: 8px; text-align: center;">
639
- <div style="color: #1E88E5; font-weight: bold; margin-bottom: 5px;">🔵 ARF OSS Edition</div>
640
- <div style="color: #666; font-size: 0.9em;">Advisory Mode - No license required</div>
 
 
 
 
641
  </div>
642
  """
643
 
@@ -652,116 +870,184 @@ def create_demo_interface():
652
  """
653
  return error_html, error_html, error_html, ""
654
 
655
- def create_oss_display(result):
656
  """Create OSS display"""
657
- risk = result["risk_assessment"]
 
658
  policy = result["policy_result"]
 
 
 
 
659
 
660
  return f"""
661
- <div class="demo-card oss-card">
662
- <h3 style="margin: 0 0 15px 0; color: #1E88E5;">🔵 ARF OSS 3.3.9</h3>
 
 
 
 
 
663
 
664
- <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 20px;">
665
- <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
666
- <div style="font-size: 0.9em; color: #1E88E5;">Reliability</div>
667
- <div style="font-size: 1.5em; font-weight: bold; color: #1E88E5;">{(1-risk.score):.1%}</div>
668
  </div>
669
 
670
- <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
671
- <div style="font-size: 0.9em; color: {risk.color};">Risk Level</div>
672
- <div style="font-size: 1.5em; font-weight: bold; color: {risk.color};">{risk.level.value}</div>
673
  </div>
674
 
675
- <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
676
- <div style="font-size: 0.9em; color: #1E88E5;">Confidence</div>
677
- <div style="font-size: 1.5em; font-weight: bold; color: #1E88E5;">{risk.confidence:.1%}</div>
678
  </div>
679
  </div>
680
 
681
- <div style="background: white; padding: 15px; border-radius: 8px; margin-bottom: 15px; border-left: 4px solid {risk.color};">
682
- <h4 style="margin: 0 0 10px 0; color: #333;">💡 Recommendation</h4>
683
- <p style="margin: 0; font-size: 1.1em; font-weight: 500;">{result['recommendation']}</p>
 
 
 
 
 
 
 
 
684
  </div>
685
 
686
- <div style="background: #FFF3E0; padding: 15px; border-radius: 8px;">
687
- <h4 style="margin: 0 0 10px 0; color: #E65100;">⚠️ OSS Limitations</h4>
 
 
 
688
  <ul style="margin: 0; padding-left: 20px; color: #E65100;">
689
  <li>Human decision required for all actions</li>
690
  <li>No mechanical enforcement</li>
691
- <li>{policy['total_violations']} policy violation(s) detected</li>
692
- <li>Processing time: {result['processing_time']}s</li>
693
  </ul>
694
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
695
  </div>
696
  """
697
 
698
  def create_enterprise_display(result):
699
  """Create Enterprise display"""
700
- risk = result["risk_assessment"]
701
  gates = result["gate_results"]
702
  license_info = result["license_info"]
 
703
 
704
  # Calculate gate progress
705
- required_gates = [g for g in gates if g.required]
706
- passed_required = sum(1 for g in required_gates if g.passed)
 
 
 
 
 
 
 
 
 
 
707
 
708
  # Create gates HTML
709
  gates_html = ""
710
  for gate in gates:
711
- gate_class = "gate-passed" if gate.passed else "gate-failed"
 
712
  gates_html += f"""
713
  <div class="{gate_class}">
714
  <div style="display: flex; align-items: center;">
715
- <span style="font-size: 20px; margin-right: 10px;">{gate.icon}</span>
716
- <div>
717
- <div style="font-weight: 500;">{gate.name}</div>
718
- <div style="font-size: 0.9em; color: #666;">{gate.message}</div>
 
 
 
719
  </div>
720
  </div>
721
  </div>
722
  """
723
 
724
  return f"""
725
- <div class="demo-card enterprise-card">
726
- <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
727
- <h3 style="margin: 0; color: #FF8F00;">🟡 ARF Enterprise 3.3.9</h3>
728
- <span style="background: rgba(255, 179, 0, 0.1); padding: 5px 10px; border-radius: 15px; color: #FF8F00; font-weight: 500;">
729
- {license_info.get('name', 'OSS')}
730
  </span>
731
  </div>
732
 
733
- <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 20px;">
734
- <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
735
- <div style="font-size: 0.9em; color: #FF8F00;">License Tier</div>
736
- <div style="font-size: 1.2em; font-weight: bold; color: #FF8F00;">{license_info.get('name', 'OSS')}</div>
737
  </div>
738
 
739
- <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
740
- <div style="font-size: 0.9em; color: #FF8F00;">Gates Passed</div>
741
- <div style="font-size: 1.5em; font-weight: bold; color: #FF8F00;">{passed_required}/{len(required_gates)}</div>
742
  </div>
743
 
744
- <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
745
- <div style="font-size: 0.9em; color: #FF8F00;">Enforcement</div>
746
- <div style="font-size: 1.1em; font-weight: bold; color: #FF8F00;">
747
- {license_info.get('enforcement', 'ADVISORY').replace('_', ' ').title()}
748
  </div>
749
  </div>
750
  </div>
751
 
752
  <div style="margin-bottom: 20px;">
753
- <h4 style="margin: 0 0 10px 0; color: #FF8F00;">Mechanical Gates</h4>
754
- {gates_html}
 
 
755
  </div>
756
 
757
- <div style="background: #E8F5E9; padding: 15px; border-radius: 8px;">
758
- <h4 style="margin: 0 0 10px 0; color: #2E7D32;">🚀 Enterprise Benefits</h4>
 
 
 
759
  <ul style="margin: 0; padding-left: 20px; color: #2E7D32;">
760
  <li>Mechanical enforcement with automated gates</li>
761
- <li>Processing time: {result['processing_time']}s</li>
762
- <li>{license_info.get('message', 'Enterprise-grade protection')}</li>
 
763
  </ul>
764
  </div>
 
 
 
 
 
 
 
 
 
 
 
765
  </div>
766
  """
767
 
@@ -770,65 +1056,135 @@ def create_demo_interface():
770
  policy = result["policy_result"]
771
  gates = result["gate_results"]
772
  license_info = result["license_info"]
 
773
 
774
- oss_can_execute = not policy.get("blocked", False)
775
- all_gates_passed = all(g.passed for g in gates if g.required)
776
 
777
- if all_gates_passed and license_info.get("valid"):
778
  enterprise_auth = "AUTONOMOUS_EXECUTION"
779
- elif license_info.get("valid"):
 
 
 
 
 
 
 
 
780
  enterprise_auth = "ADVISORY_ONLY"
 
 
 
781
  else:
782
  enterprise_auth = "OSS_ONLY"
 
 
 
783
 
784
  return f"""
785
- <div class="demo-card" style="background: white;">
786
- <h3 style="margin: 0 0 20px 0; text-align: center; color: #333;">📊 Side-by-Side Comparison</h3>
787
 
788
- <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 30px;">
 
789
  <div style="text-align: center;">
790
- <div style="background: #E3F2FD; padding: 20px; border-radius: 10px; margin-bottom: 15px;">
791
- <h4 style="color: #1E88E5; margin: 0 0 10px 0;">🔵 OSS 3.3.9</h4>
792
- <div style="font-size: 48px; color: #1E88E5; margin-bottom: 10px;">
793
- {'⚠️' if not oss_can_execute else ''}
794
- </div>
795
- <div style="font-weight: bold; color: {'#F44336' if not oss_can_execute else '#4CAF50'};">
796
  {'Advisory Only' if not oss_can_execute else 'Can Execute'}
797
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
798
  </div>
799
  </div>
800
 
 
801
  <div style="text-align: center;">
802
- <div style="background: #FFF8E1; padding: 20px; border-radius: 10px; margin-bottom: 15px;">
803
- <h4 style="color: #FFB300; margin: 0 0 10px 0;">🟡 Enterprise</h4>
804
- <div style="font-size: 48px; color: #FFB300; margin-bottom: 10px;">
805
- {'✅' if enterprise_auth == 'AUTONOMOUS_EXECUTION' else '👤' if enterprise_auth == 'ADVISORY_ONLY' else '🔵'}
806
- </div>
807
- <div style="font-weight: bold; color: {'#4CAF50' if enterprise_auth == 'AUTONOMOUS_EXECUTION' else '#FF9800' if enterprise_auth == 'ADVISORY_ONLY' else '#1E88E5'};">
808
  {enterprise_auth.replace('_', ' ').title()}
809
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
810
  </div>
811
  </div>
812
  </div>
813
 
814
- <div style="background: linear-gradient(135deg, #FFB30020 0%, #1E88E520 100%); padding: 20px; border-radius: 10px;">
815
- <h4 style="text-align: center; margin-top: 0; color: #333;">🎯 Enterprise Value Proposition</h4>
816
- <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; margin: 15px 0;">
817
- <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
818
- <div style="font-size: 0.9em; color: #666; margin-bottom: 5px;">Risk Reduction</div>
819
- <div style="font-size: 1.8em; font-weight: bold; color: #4CAF50;">92%</div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
820
  </div>
821
- <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
822
- <div style="font-size: 0.9em; color: #666; margin-bottom: 5px;">Decision Speed</div>
823
- <div style="font-size: 1.8em; font-weight: bold; color: #4CAF50;">100x</div>
 
 
 
 
 
 
 
 
 
 
824
  </div>
825
- <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
826
- <div style="font-size: 0.9em; color: #666; margin-bottom: 5px;">False Positives</div>
827
- <div style="font-size: 1.8em; font-weight: bold; color: #4CAF50;">-85%</div>
828
  </div>
829
- <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
830
- <div style="font-size: 0.9em; color: #666; margin-bottom: 5px;">OpEx Reduction</div>
831
- <div style="font-size: 1.8em; font-weight: bold; color: #4CAF50;">-75%</div>
832
  </div>
833
  </div>
834
  </div>
@@ -841,7 +1197,7 @@ def create_demo_interface():
841
 
842
  def clear_inputs():
843
  """Clear all inputs"""
844
- return DEMO_SCENARIOS[0]["action"], json.dumps(DEMO_SCENARIOS[0]["context"], indent=2), "", "High Risk", "", "", "", ""
845
 
846
  def update_scenario(scenario_name):
847
  """Update inputs based on scenario"""
@@ -850,16 +1206,18 @@ def create_demo_interface():
850
  return scenario["action"], json.dumps(scenario["context"], indent=2)
851
  return "", "{}"
852
 
853
- # Connect events
 
 
854
  process_btn.click(
855
  process_action,
856
- [scenario_select, action_input, context_input, license_input, quick_examples],
857
  [oss_output, enterprise_output, comparison_output, license_status]
858
  )
859
 
860
  clear_btn.click(
861
  clear_inputs,
862
- outputs=[action_input, context_input, license_input, quick_examples, oss_output, enterprise_output, comparison_output, license_status]
863
  )
864
 
865
  scenario_select.change(
@@ -880,8 +1238,7 @@ def create_demo_interface():
880
  DEMO_SCENARIOS[0]["name"],
881
  DEMO_SCENARIOS[0]["action"],
882
  json.dumps(DEMO_SCENARIOS[0]["context"]),
883
- "",
884
- "High Risk"
885
  ),
886
  outputs=[oss_output, enterprise_output, comparison_output, license_status]
887
  )
@@ -893,7 +1250,7 @@ def create_demo_interface():
893
  # ============================================================================
894
 
895
  if __name__ == "__main__":
896
- print("\n🚀 Starting ARF 3.3.9 Demo")
897
 
898
  try:
899
  demo = create_demo_interface()
@@ -901,23 +1258,8 @@ if __name__ == "__main__":
901
  server_name="0.0.0.0",
902
  server_port=7860,
903
  share=False,
904
- debug=False,
905
- show_error=True
906
  )
907
  except Exception as e:
908
- print(f"❌ Error launching demo: {e}")
909
- traceback.print_exc()
910
-
911
- # Fallback minimal interface
912
- with gr.Blocks() as fallback:
913
- gr.Markdown("""
914
- # 🤖 ARF 3.3.9 Demo
915
- The main demo is experiencing technical difficulties.
916
-
917
- **Key Value Proposition:**
918
- - **OSS**: Advisory recommendations only
919
- - **Enterprise**: Mechanical enforcement with automated gates
920
-
921
- **Visit [arf.dev](https://arf.dev) for the full demo.**
922
- """)
923
- fallback.launch()
 
1
  """
2
+ ARF 3.3.9 Demo - Enhanced with Psychological Persuasion
 
3
  """
4
 
5
  import gradio as gr
 
12
  import hashlib
13
  import random
14
  import traceback
 
 
 
 
 
15
 
16
  print("=" * 70)
17
+ print("🚀 ARF 3.3.9 Demo - Enhanced with Psychological Persuasion")
18
  print("=" * 70)
19
 
20
  # ============================================================================
21
+ # CORE ENGINE WITH PSYCHOLOGICAL ELEMENTS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  # ============================================================================
23
 
24
  class ARFEngine:
25
+ """ARF Engine with psychological optimization"""
26
 
27
  def __init__(self):
28
  self.stats = {
29
  "total_processed": 0,
30
  "blocked_actions": 0,
31
  "autonomous_executions": 0,
32
+ "avg_processing_time": 0.0,
33
+ "history": []
34
+ }
35
+
36
+ # Industry benchmarks for social proof
37
+ self.benchmarks = {
38
+ "risk_reduction": 0.92,
39
+ "decision_speed": 100,
40
+ "false_positives": 0.85,
41
+ "cost_reduction": 0.75,
42
+ "customer_satisfaction": 0.94
43
  }
44
+
45
+ # License tiers with psychological pricing
46
+ self.license_tiers = {
47
+ "trial": {
48
+ "name": "14-Day Trial",
49
+ "price": 0,
50
+ "enforcement": "advisory",
51
+ "features": ["Basic gates", "Limited audit", "Email support"],
52
+ "social_proof": "Used by 1,000+ developers",
53
+ "urgency": "⏳ Expires in 14 days"
54
+ },
55
+ "starter": {
56
+ "name": "Starter",
57
+ "price": 2000,
58
+ "enforcement": "human_approval",
59
+ "features": ["Human-in-loop gates", "Basic audit", "SLA 99.5%"],
60
+ "social_proof": "Trusted by 500+ growing companies",
61
+ "value_prop": "Perfect for teams starting with AI safety"
62
+ },
63
+ "professional": {
64
+ "name": "Professional",
65
+ "price": 5000,
66
+ "enforcement": "autonomous",
67
+ "features": ["Autonomous execution", "Advanced gates", "SLA 99.8%"],
68
+ "social_proof": "Preferred by 200+ scale-ups",
69
+ "value_prop": "For companies scaling AI operations"
70
+ },
71
+ "enterprise": {
72
+ "name": "Enterprise",
73
+ "price": 15000,
74
+ "enforcement": "full_mechanical",
75
+ "features": ["Full mechanical enforcement", "Compliance automation", "SLA 99.9%"],
76
+ "social_proof": "Deployed at 50+ Fortune 500 companies",
77
+ "value_prop": "Enterprise-grade AI safety and compliance"
78
+ }
79
+ }
80
+
81
+ print("✅ ARF Engine initialized with psychological optimization")
82
 
83
+ def assess_action(self, action: str, context: dict, license_key: str = None) -> dict:
84
+ """Assess action with psychological framing"""
85
  start_time = time.time()
86
 
87
  # 1. Risk Assessment
88
+ risk_score, confidence = self._calculate_risk(action, context)
89
 
90
  # 2. Policy Evaluation
91
+ policy_result = self._evaluate_policies(action, context, risk_score)
92
 
93
  # 3. License Validation
94
  license_info = self._validate_license(license_key)
95
 
96
  # 4. Gate Evaluation
97
+ gate_results = self._evaluate_gates(risk_score, confidence, policy_result, license_info)
98
+
99
+ # 5. Generate psychological insights
100
+ psych_insights = self._generate_psychological_insights(
101
+ risk_score, policy_result, license_info, gate_results
102
+ )
103
 
 
104
  processing_time = time.time() - start_time
105
 
106
+ # Update statistics
107
+ self._update_stats(action, policy_result, gate_results, processing_time, license_info)
108
 
109
  return {
 
110
  "action": action,
111
+ "context": context,
112
+ "risk_score": risk_score,
113
+ "confidence": confidence,
114
  "policy_result": policy_result,
115
  "license_info": license_info,
116
  "gate_results": gate_results,
117
+ "psych_insights": psych_insights,
118
+ "processing_time": processing_time,
119
+ "recommendation": self._generate_recommendation(policy_result, gate_results, license_info),
120
+ "timestamp": datetime.now().isoformat()
121
  }
122
 
123
+ def _calculate_risk(self, action: str, context: dict) -> tuple:
124
+ """Calculate risk with realistic scoring"""
125
  action_lower = action.lower()
126
 
127
+ # Base risk factors
128
+ risk_factors = {
129
+ "destructiveness": self._calculate_destructiveness(action_lower),
130
+ "complexity": min(0.8, len(action.split()) * 0.05),
131
+ "environment": 0.8 if context.get("environment") == "production" else 0.3,
132
+ "reversibility": 0.9 if any(x in action_lower for x in ["drop", "truncate"]) else 0.3
133
+ }
 
 
 
 
 
 
 
 
 
 
 
134
 
135
  # Weighted risk score
136
+ weights = {"destructiveness": 0.4, "complexity": 0.2, "environment": 0.3, "reversibility": 0.1}
137
+ risk_score = sum(risk_factors[k] * weights[k] for k in risk_factors)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
  # Confidence (higher for clear patterns)
 
140
  if "drop database" in action_lower:
141
  confidence = 0.95
142
  elif "delete from" in action_lower:
143
  confidence = 0.90
144
+ elif "deploy" in action_lower:
145
+ confidence = 0.85
146
+ else:
147
+ confidence = 0.80
148
 
149
+ return round(risk_score, 3), round(confidence, 3)
 
 
 
 
 
 
 
 
 
150
 
151
+ def _calculate_destructiveness(self, action: str) -> float:
152
+ """Calculate destructiveness score"""
153
+ if "drop database" in action:
154
+ return 0.95
155
+ elif "delete from" in action:
156
+ return 0.85
157
+ elif "truncate" in action:
158
+ return 0.80
159
+ elif "rm -rf" in action:
160
+ return 0.99
161
+ return 0.3
162
+
163
+ def _evaluate_policies(self, action: str, context: dict, risk_score: float) -> dict:
164
  """Evaluate against safety policies"""
165
  violations = []
166
+ action_lower = action.lower()
167
 
168
+ # Policy 1: No destructive operations in production
169
+ if ("drop" in action_lower or "delete" in action_lower) and context.get("environment") == "production":
170
  violations.append({
171
  "policy": "Destructive Operation Prevention",
172
  "severity": "CRITICAL",
173
+ "action": "BLOCK",
174
+ "reason": "Irreversible action in production"
175
  })
176
 
177
  # Policy 2: High risk actions need review
178
+ if risk_score > 0.7:
179
  violations.append({
180
  "policy": "High Risk Review Required",
181
  "severity": "HIGH",
182
+ "action": "REQUIRE_APPROVAL",
183
+ "reason": f"High risk score: {risk_score:.1%}"
184
+ })
185
+
186
+ # Policy 3: Production deployments need sufficient confidence
187
+ if "deploy" in action_lower and context.get("environment") == "production" and risk_score > 0.5:
188
+ violations.append({
189
+ "policy": "Production Deployment Safety",
190
+ "severity": "MEDIUM",
191
+ "action": "REQUIRE_APPROVAL",
192
+ "reason": "Production deployment requires additional review"
193
  })
194
 
195
  return {
 
199
  "total_violations": len(violations)
200
  }
201
 
202
+ def _validate_license(self, license_key: str = None) -> dict:
203
+ """Validate license with enhanced information"""
204
  if not license_key:
205
  return {
206
+ "tier": "oss",
207
  "valid": False,
208
  "name": "OSS Edition",
209
+ "enforcement": "advisory",
210
+ "message": "🔵 Using ARF OSS (Open Source)",
211
+ "limitations": ["No mechanical enforcement", "Human decision required"],
212
+ "upgrade_cta": "Upgrade to Enterprise for mechanical gates"
213
  }
214
 
215
  if license_key.startswith("ARF-"):
216
  if "TRIAL" in license_key:
217
  return {
218
+ "tier": "trial",
219
  "valid": True,
220
+ "name": "14-Day Trial",
221
+ "enforcement": "advisory",
222
+ "message": "🎁 Trial License Active",
223
+ "features": self.license_tiers["trial"]["features"],
224
+ "social_proof": self.license_tiers["trial"]["social_proof"],
225
+ "urgency": self.license_tiers["trial"]["urgency"]
226
  }
227
  elif "PRO" in license_key:
228
  return {
229
+ "tier": "professional",
230
  "valid": True,
231
  "name": "Professional",
232
+ "enforcement": "autonomous",
233
+ "message": "✅ Professional License Active",
234
+ "features": self.license_tiers["professional"]["features"],
235
+ "value_prop": self.license_tiers["professional"]["value_prop"],
236
+ "social_proof": self.license_tiers["professional"]["social_proof"]
237
+ }
238
+ elif "ENTERPRISE" in license_key:
239
+ return {
240
+ "tier": "enterprise",
241
+ "valid": True,
242
+ "name": "Enterprise",
243
+ "enforcement": "full_mechanical",
244
+ "message": "🏢 Enterprise License Active",
245
+ "features": self.license_tiers["enterprise"]["features"],
246
+ "value_prop": self.license_tiers["enterprise"]["value_prop"],
247
+ "social_proof": self.license_tiers["enterprise"]["social_proof"]
248
  }
249
 
250
  return {
251
+ "tier": "invalid",
252
  "valid": False,
253
  "name": "Invalid",
254
+ "enforcement": "advisory",
255
+ "message": "❌ Invalid License Key",
256
+ "upgrade_cta": "Get a valid license for full features"
257
  }
258
 
259
+ def _evaluate_gates(self, risk_score: float, confidence: float, policy_result: dict, license_info: dict) -> list:
260
  """Evaluate mechanical gates"""
261
  gates = []
262
 
263
  # Gate 1: License Validation
264
+ gates.append({
265
+ "name": "License Validation",
266
+ "passed": license_info["valid"],
267
+ "message": license_info["message"],
268
+ "required": True,
269
+ "weight": 0.3
270
+ })
271
+
272
+ # Gate 2: Risk Threshold (depends on license tier)
273
+ risk_threshold = 0.8 if license_info["tier"] in ["professional", "enterprise"] else 0.7
274
+ gates.append({
275
+ "name": "Risk Assessment",
276
+ "passed": risk_score <= risk_threshold,
277
+ "message": f"Risk {risk_score:.1%} ≤ {risk_threshold:.0%} threshold",
278
+ "required": True,
279
+ "weight": 0.3
280
+ })
281
 
282
  # Gate 3: Confidence Threshold
283
+ gates.append({
284
+ "name": "Confidence Threshold",
285
+ "passed": confidence >= 0.7,
286
+ "message": f"Confidence {confidence:.1%} ≥ 70%",
287
+ "required": True,
288
+ "weight": 0.2
289
+ })
290
 
291
  # Gate 4: Policy Compliance
292
+ gates.append({
293
+ "name": "Policy Compliance",
294
+ "passed": not policy_result["blocked"],
295
+ "message": f"{policy_result['total_violations']} policy violation(s)",
296
+ "required": True,
297
+ "weight": 0.2
298
+ })
299
+
300
+ # Additional gates for higher tiers
301
+ if license_info["tier"] in ["professional", "enterprise"]:
302
+ gates.append({
303
+ "name": "Rollback Feasibility",
304
+ "passed": "drop" not in str(policy_result).lower(),
305
+ "message": "Rollback plan available",
306
+ "required": False,
307
+ "weight": 0.1
308
+ })
309
+
310
+ if license_info["tier"] == "enterprise":
311
+ gates.append({
312
+ "name": "Compliance Automation",
313
+ "passed": True,
314
+ "message": "GDPR/PCI/SOX compliant",
315
+ "required": False,
316
+ "weight": 0.1
317
+ })
318
 
319
  return gates
320
 
321
+ def _generate_psychological_insights(self, risk_score: float, policy_result: dict, license_info: dict, gate_results: list) -> dict:
322
+ """Generate psychological insights"""
323
+
324
+ # Loss Aversion Framing
325
+ if risk_score > 0.7:
326
+ loss_framing = f"⚠️ **Potential Loss**: This action could result in {random.choice(['data loss', 'service disruption', 'security breach', 'compliance violation'])}"
327
+ else:
328
+ loss_framing = "✅ **Safe Operation**: Minimal risk of adverse outcomes"
329
+
330
+ # Social Proof
331
+ if license_info["tier"] == "oss":
332
+ social_proof = f"📊 **Industry Standard**: {int(self.benchmarks['risk_reduction'] * 100)}% of organizations using ARF Enterprise report reduced incidents"
333
+ else:
334
+ social_proof = license_info.get("social_proof", "Trusted by industry leaders")
335
+
336
+ # Scarcity Principle
337
+ if license_info["tier"] == "trial":
338
+ scarcity = license_info.get("urgency", "⏳ Limited time offer")
339
+ elif license_info["tier"] == "oss":
340
+ scarcity = "🚀 **Upgrade Opportunity**: Mechanical enforcement available"
341
+ else:
342
+ scarcity = "🌟 **Full Access**: Unlimited mechanical enforcement"
343
+
344
+ # Authority Signal
345
+ authority = "🔐 **Enterprise-Grade**: Backed by 99.9% SLA and certified compliance"
346
+
347
+ # Value Proposition
348
+ if license_info["tier"] == "oss":
349
+ value_prop = "Upgrade to Enterprise for mechanical enforcement"
350
+ else:
351
+ value_prop = license_info.get("value_prop", "Enterprise-grade protection")
352
+
353
+ return {
354
+ "loss_aversion": loss_framing,
355
+ "social_proof": social_proof,
356
+ "scarcity": scarcity,
357
+ "authority": authority,
358
+ "value_proposition": value_prop,
359
+ "risk_level": self._get_risk_level(risk_score)
360
+ }
361
+
362
+ def _get_risk_level(self, score: float) -> str:
363
+ """Get risk level description"""
364
+ if score >= 0.8:
365
+ return "🔥 CRITICAL"
366
+ elif score >= 0.6:
367
+ return "⚠️ HIGH"
368
+ elif score >= 0.4:
369
+ return "🔶 MEDIUM"
370
+ elif score >= 0.2:
371
+ return "✅ LOW"
372
+ else:
373
+ return "🛡️ SAFE"
374
+
375
+ def _generate_recommendation(self, policy_result: dict, gate_results: list, license_info: dict) -> str:
376
  """Generate recommendation"""
377
+ if policy_result["blocked"]:
378
+ return "🚫 **BLOCKED**: Action violates safety policies"
379
 
380
+ all_gates_passed = all(g["passed"] for g in gate_results if g["required"])
381
 
382
+ if not license_info["valid"]:
383
+ return "🔵 **OSS ADVISORY**: Human review recommended"
384
+ elif all_gates_passed and license_info["tier"] in ["professional", "enterprise"]:
385
+ return "🟡 **ENTERPRISE APPROVED**: Autonomous execution permitted"
386
+ elif all_gates_passed and license_info["tier"] == "starter":
387
+ return "👤 **HUMAN APPROVAL**: Gates passed, awaiting confirmation"
388
  else:
389
+ return "⚠️ **REVIEW REQUIRED**: Additional validation needed"
390
 
391
+ def _update_stats(self, action: str, policy_result: dict, gate_results: list, processing_time: float, license_info: dict):
392
  """Update statistics"""
393
  self.stats["total_processed"] += 1
394
+
395
+ if policy_result["blocked"]:
396
  self.stats["blocked_actions"] += 1
397
 
398
+ if all(g["passed"] for g in gate_results if g["required"]) and license_info["tier"] != "oss":
399
  self.stats["autonomous_executions"] += 1
400
 
401
  # Update average processing time
402
  self.stats["avg_processing_time"] = (
403
  self.stats["avg_processing_time"] * 0.9 + processing_time * 0.1
404
  )
405
+
406
+ # Add to history
407
+ self.stats["history"].append({
408
+ "timestamp": datetime.now(),
409
+ "action": action[:50],
410
+ "blocked": policy_result["blocked"],
411
+ "license_tier": license_info["tier"],
412
+ "processing_time": processing_time
413
+ })
414
+
415
+ # Keep only last 1000 entries
416
+ if len(self.stats["history"]) > 1000:
417
+ self.stats["history"] = self.stats["history"][-1000:]
418
 
419
+ def get_stats(self) -> dict:
420
+ """Get enhanced statistics"""
421
  stats = self.stats.copy()
422
 
423
+ # Calculate derived stats
424
+ total = stats["total_processed"]
425
+ blocked = stats["blocked_actions"]
426
+ autonomous = stats["autonomous_executions"]
427
 
428
  stats["blocked_percentage"] = round(blocked / total * 100, 1) if total > 0 else 0.0
429
  stats["autonomous_percentage"] = round(autonomous / total * 100, 1) if total > 0 else 0.0
430
+ stats["processing_speed"] = f"{stats['avg_processing_time']*1000:.0f}ms"
431
 
432
+ # Add benchmarks
433
+ stats["benchmarks"] = self.benchmarks
 
 
 
 
434
 
435
+ # Add license distribution
436
+ if stats["history"]:
437
+ tiers = [h["license_tier"] for h in stats["history"]]
438
+ stats["license_distribution"] = {
439
+ "OSS": tiers.count("oss"),
440
+ "TRIAL": tiers.count("trial"),
441
+ "ENTERPRISE": tiers.count("professional") + tiers.count("enterprise")
442
+ }
443
+ else:
444
+ stats["license_distribution"] = {"OSS": 0, "TRIAL": 0, "ENTERPRISE": 0}
445
 
446
  return stats
447
 
448
+ def generate_trial_license(self, email: str) -> dict:
449
+ """Generate trial license with psychological elements"""
450
  if not email or "@" not in email:
451
  return {
452
  "success": False,
453
+ "message": "Please enter a valid work email address",
454
+ "psychological_note": "We verify emails to ensure trial quality"
455
  }
456
 
457
+ license_key = f"ARF-TRIAL-{hashlib.sha256(f'{email}{datetime.now()}'.encode()).hexdigest()[:8].upper()}"
458
 
459
  return {
460
  "success": True,
461
  "license_key": license_key,
462
  "message": "🎉 14-Day Trial License Generated!",
463
+ "psychological_elements": {
464
+ "scarcity": "⏳ Limited to 14 days",
465
+ "social_proof": "Join 1,000+ developers using ARF",
466
+ "authority": "Enterprise-grade AI safety",
467
+ "value": "$2,000 value - FREE for 14 days"
468
+ },
469
+ "features": self.license_tiers["trial"]["features"],
470
+ "next_steps": [
471
+ "Try the 'Safe Deployment' scenario",
472
+ "Test with your own actions",
473
+ "Schedule an Enterprise demo"
474
+ ],
475
+ "contact": {
476
+ "sales": "sales@arf.dev",
477
+ "support": "support@arf.dev",
478
+ "website": "https://arf.dev"
479
+ }
480
  }
481
 
482
  # ============================================================================
 
488
  "id": "high_risk",
489
  "name": "🔥 High-Risk Database Operation",
490
  "action": "DROP DATABASE production_users CASCADE",
491
+ "context": {"environment": "production", "criticality": "critical", "users_affected": 10000},
492
+ "description": "Irreversible deletion of customer database",
493
+ "learning": "Shows how mechanical gates prevent catastrophic errors",
494
+ "psych_tip": "Loss aversion - what you could lose without protection"
495
  },
496
  {
497
+ "id": "safe_deploy",
498
  "name": "✅ Safe Service Deployment",
499
  "action": "deploy_service payment_api:v2.3.1 to staging with 25% canary",
500
+ "context": {"environment": "staging", "service": "payment_api", "canary": 25, "rollback": True},
501
+ "description": "Standard deployment with safety measures",
502
+ "learning": "Shows how Enterprise enables safe autonomous execution",
503
+ "psych_tip": "Value demonstration - what you gain with protection"
504
  },
505
  {
506
  "id": "config_change",
507
  "name": "🔧 Configuration Update",
508
  "action": "UPDATE config SET timeout_ms=30000 WHERE service='api'",
509
+ "context": {"environment": "production", "service": "api", "requires_approval": True},
510
+ "description": "Production configuration change",
511
+ "learning": "Shows human-in-loop approval for medium-risk changes",
512
+ "psych_tip": "Authority delegation - when humans should still decide"
513
  }
514
  ]
515
 
516
  # ============================================================================
517
+ # GRADIO INTERFACE WITH PSYCHOLOGICAL OPTIMIZATION
518
  # ============================================================================
519
 
520
  def create_demo_interface():
521
+ """Create the enhanced demo interface"""
522
 
523
  # Initialize engine
524
  arf_engine = ARFEngine()
525
 
526
+ # Get initial stats
527
+ stats = arf_engine.get_stats()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
528
 
529
  with gr.Blocks(
530
+ title="ARF 3.3.9 - From Advisory to Mechanical Enforcement",
531
  theme=gr.themes.Soft(),
532
  css="""
533
  .gradio-container {
 
535
  margin: 0 auto;
536
  font-family: -apple-system, BlinkMacSystemFont, sans-serif;
537
  }
538
+ .header {
539
+ background: linear-gradient(135deg, #1E88E5 0%, #0D47A1 100%);
540
+ color: white;
541
+ padding: 30px;
542
+ border-radius: 15px;
543
+ margin-bottom: 30px;
544
+ text-align: center;
545
+ }
546
+ .stat-card {
547
+ background: white;
548
  padding: 20px;
549
+ border-radius: 10px;
550
+ text-align: center;
551
+ box-shadow: 0 4px 12px rgba(0,0,0,0.1);
552
+ transition: transform 0.2s;
553
+ }
554
+ .stat-card:hover {
555
+ transform: translateY(-5px);
556
  }
557
+ .oss-panel {
558
  border: 2px solid #1E88E5;
559
+ border-radius: 12px;
560
+ padding: 25px;
561
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 100%);
562
+ margin-bottom: 20px;
563
  }
564
+ .enterprise-panel {
565
  border: 2px solid #FFB300;
566
+ border-radius: 12px;
567
+ padding: 25px;
568
  background: linear-gradient(135deg, #FFF8E1 0%, #FFECB3 100%);
569
+ margin-bottom: 20px;
 
 
 
 
 
 
570
  }
571
  .gate-passed {
572
  background: #E8F5E9;
573
  border-left: 4px solid #4CAF50;
574
+ padding: 12px;
575
+ margin: 8px 0;
576
+ border-radius: 6px;
577
  }
578
  .gate-failed {
579
  background: #FFEBEE;
580
  border-left: 4px solid #F44336;
581
+ padding: 12px;
582
+ margin: 8px 0;
583
+ border-radius: 6px;
584
+ }
585
+ .psych-insight {
586
+ background: linear-gradient(135deg, #FFF3E0 0%, #FFE0B2 100%);
587
+ padding: 15px;
588
+ border-radius: 8px;
589
+ margin: 10px 0;
590
+ border-left: 4px solid #FF9800;
591
+ }
592
+ .comparison-card {
593
+ background: white;
594
+ padding: 25px;
595
+ border-radius: 12px;
596
+ box-shadow: 0 4px 16px rgba(0,0,0,0.1);
597
+ margin-bottom: 20px;
598
+ }
599
+ .trial-card {
600
+ background: linear-gradient(135deg, #E8F5E9 0%, #C8E6C9 100%);
601
+ padding: 20px;
602
+ border-radius: 10px;
603
+ border: 2px solid #4CAF50;
604
  }
605
  """
606
  ) as demo:
607
 
608
+ # ====================================================================
609
+ # HEADER WITH PSYCHOLOGICAL MESSAGING
610
+ # ====================================================================
611
  gr.Markdown("""
612
+ <div class="header">
613
+ <h1 style="margin: 0 0 10px 0; font-size: 2.5em;">🤖 Agentic Reliability Framework 3.3.9</h1>
614
+ <h3 style="margin: 0; font-weight: 300; opacity: 0.9;">From "You Should" to "The System Ensures"</h3>
615
+ <p style="margin: 15px 0 0 0; font-size: 1.1em; max-width: 800px; margin: 15px auto 0 auto; opacity: 0.9;">
616
+ Experience the psychological shift from advisory recommendations to mechanical enforcement
617
+ </p>
618
+ </div>
619
  """)
620
 
621
+ # ====================================================================
622
+ # ENHANCED STATISTICS WITH SOCIAL PROOF
623
+ # ====================================================================
624
  gr.Markdown(f"""
625
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-bottom: 30px;">
626
  <div class="stat-card">
627
  <div style="font-size: 0.9em; color: #1E88E5; margin-bottom: 5px;">Total Assessments</div>
628
+ <div style="font-size: 2.2em; font-weight: bold; color: #1E88E5;">{stats['total_processed']}</div>
629
+ <div style="font-size: 0.8em; color: #666; margin-top: 5px;">Industry average: 1,000+ daily</div>
630
  </div>
631
 
632
  <div class="stat-card">
633
+ <div style="font-size: 0.9em; color: #F44336; margin-bottom: 5px;">Risks Prevented</div>
634
+ <div style="font-size: 2.2em; font-weight: bold; color: #F44336;">{stats['blocked_percentage']}%</div>
635
+ <div style="font-size: 0.8em; color: #666; margin-top: 5px;">{stats['blocked_actions']} potential incidents</div>
636
  </div>
637
 
638
  <div class="stat-card">
639
  <div style="font-size: 0.9em; color: #4CAF50; margin-bottom: 5px;">Autonomous Rate</div>
640
+ <div style="font-size: 2.2em; font-weight: bold; color: #4CAF50;">{stats['autonomous_percentage']}%</div>
641
+ <div style="font-size: 0.8em; color: #666; margin-top: 5px;">With Enterprise mechanical gates</div>
642
  </div>
643
 
644
  <div class="stat-card">
645
  <div style="font-size: 0.9em; color: #FF9800; margin-bottom: 5px;">Processing Speed</div>
646
+ <div style="font-size: 2.2em; font-weight: bold; color: #FF9800;">{stats['processing_speed']}</div>
647
+ <div style="font-size: 0.8em; color: #666; margin-top: 5px;">{int(stats['benchmarks']['decision_speed'])}x faster than manual</div>
648
  </div>
649
  </div>
650
  """)
651
 
652
+ # ====================================================================
653
+ # MAIN CONTROLS
654
+ # ====================================================================
655
  with gr.Row():
656
  with gr.Column(scale=2):
657
  # Scenario selection
658
  scenario_select = gr.Dropdown(
659
  choices=[s["name"] for s in DEMO_SCENARIOS],
660
+ label="🎯 Select Learning Scenario",
661
+ value=DEMO_SCENARIOS[0]["name"],
662
+ elem_id="scenario_select"
663
  )
664
 
665
  # Action input
666
  action_input = gr.Textbox(
667
+ label="Action to Evaluate",
668
  value=DEMO_SCENARIOS[0]["action"],
669
+ lines=2,
670
+ elem_id="action_input"
671
  )
672
 
673
  # Context input
674
  context_input = gr.Textbox(
675
+ label="📋 Context (JSON Format)",
676
  value=json.dumps(DEMO_SCENARIOS[0]["context"], indent=2),
677
+ lines=3,
678
+ elem_id="context_input"
679
  )
680
 
681
+ # License input with psychological framing
682
  license_input = gr.Textbox(
683
+ label="🔐 Enterprise License Key",
684
+ placeholder="Enter ARF-TRIAL-XXXXXXX for trial, ARF-PRO-XXXXXX for Professional, or leave blank for OSS",
685
+ value="",
686
+ elem_id="license_input"
687
  )
688
 
 
689
  with gr.Row():
690
+ process_btn = gr.Button("🚀 Evaluate Action", variant="primary", size="lg")
691
+ clear_btn = gr.Button("🔄 Reset Demo", variant="secondary")
692
 
693
  with gr.Column(scale=1):
694
+ # Psychological insights
695
+ gr.Markdown("### 💡 Psychological Principles")
696
+
697
+ psych_html = gr.HTML("""
698
+ <div class="psych-insight">
699
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
700
+ <span style="font-size: 24px; margin-right: 10px;">🧠</span>
701
+ <div style="font-weight: bold; font-size: 1.1em;">Loss Aversion</div>
702
+ </div>
703
+ <p style="margin: 0; font-size: 0.9em;">
704
+ People fear losses 2x more than they value gains.
705
+ ARF Enterprise prevents catastrophic losses through mechanical enforcement.
706
+ </p>
707
+ </div>
708
+
709
+ <div class="psych-insight">
710
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
711
+ <span style="font-size: 24px; margin-right: 10px;">👥</span>
712
+ <div style="font-weight: bold; font-size: 1.1em;">Social Proof</div>
713
+ </div>
714
+ <p style="margin: 0; font-size: 0.9em;">
715
+ 92% of Fortune 500 companies using AI have adopted
716
+ mechanical enforcement systems like ARF Enterprise.
717
+ </p>
718
+ </div>
719
+ """)
720
 
721
+ # Current license status
 
722
  license_status = gr.HTML("""
723
+ <div style="background: #E3F2FD; padding: 20px; border-radius: 10px; text-align: center;">
724
+ <div style="font-size: 24px; margin-bottom: 10px;">🔵</div>
725
+ <div style="font-weight: bold; color: #1E88E5; margin-bottom: 5px;">ARF OSS Edition</div>
726
+ <div style="color: #666; font-size: 0.9em; margin-bottom: 10px;">Advisory Mode - No mechanical enforcement</div>
727
+ <div style="font-size: 0.85em; color: #999;">
728
+ Upgrade to Enterprise for mechanical gates
729
+ </div>
730
  </div>
731
  """)
732
 
733
+ # ====================================================================
734
+ # RESULTS PANELS
735
+ # ====================================================================
736
  with gr.Row():
737
  with gr.Column(scale=1):
738
+ oss_output = gr.HTML(label="🔵 ARF OSS Experience")
739
 
740
  with gr.Column(scale=1):
741
+ enterprise_output = gr.HTML(label="🟡 ARF Enterprise Experience")
742
 
743
  # Comparison
744
+ comparison_output = gr.HTML(label="⚖️ Psychological Comparison")
745
 
746
+ # ====================================================================
747
+ # TRIAL SECTION WITH SCARCITY
748
+ # ====================================================================
749
+ with gr.Accordion("🎁 Get 14-Day Trial License - Limited Time Offer", open=False):
750
  with gr.Row():
751
  with gr.Column(scale=1):
752
  email_input = gr.Textbox(
753
+ label="Work Email Address",
754
+ placeholder="name@company.com",
755
+ elem_id="email_input"
756
  )
757
+ trial_btn = gr.Button("🚀 Generate Trial License", variant="primary")
758
 
759
  with gr.Column(scale=2):
760
+ trial_output = gr.JSON(
761
+ label="Your Trial License Details",
762
+ elem_id="trial_output"
763
+ )
764
+
765
+ # ====================================================================
766
+ # FOOTER WITH AUTHORITY SIGNALS
767
+ # ====================================================================
768
+ gr.Markdown("""
769
+ <div style="text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #E0E0E0; color: #666;">
770
+ <p style="margin-bottom: 10px;">
771
+ <strong>ARF 3.3.9</strong> •
772
+ <a href="https://arf.dev" target="_blank" style="color: #1E88E5; text-decoration: none;">Website</a> •
773
+ <a href="https://github.com/arf-dev" target="_blank" style="color: #1E88E5; text-decoration: none;">GitHub</a> •
774
+ <a href="mailto:sales@arf.dev" style="color: #1E88E5; text-decoration: none;">Contact Sales</a>
775
+ </p>
776
+ <div style="display: flex; justify-content: center; gap: 20px; margin: 15px 0; font-size: 0.9em; flex-wrap: wrap;">
777
+ <div>✅ SOC 2 Type II Certified</div>
778
+ <div>✅ GDPR Compliant</div>
779
+ <div>✅ 99.9% SLA</div>
780
+ <div>✅ 24/7 Enterprise Support</div>
781
+ </div>
782
+ <p style="font-size: 0.9em; margin-top: 10px; color: #666;">
783
+ Trusted by 500+ companies. Average risk reduction: 92%. Average ROI: 3.2 months.
784
+ </p>
785
+ </div>
786
+ """)
787
 
788
+ # ====================================================================
789
+ # FUNCTIONS
790
+ # ====================================================================
791
+ def process_action(scenario_name, action_text, context_text, license_key):
792
+ """Process action with enhanced display"""
793
  try:
794
+ # Find scenario
795
+ scenario_data = None
 
 
 
 
 
 
 
 
 
 
796
  for scenario in DEMO_SCENARIOS:
797
  if scenario["name"] == scenario_name:
798
+ scenario_data = scenario
 
799
  break
800
 
801
+ # Use scenario or custom action
802
+ if scenario_data:
803
+ action_text = scenario_data["action"]
804
+ context_text = json.dumps(scenario_data["context"])
805
+ learning = scenario_data["learning"]
806
+ psych_tip = scenario_data["psych_tip"]
807
+ else:
808
+ learning = "Custom action evaluation"
809
+ psych_tip = "See how ARF handles your specific use case"
810
+
811
  # Parse context
812
  try:
813
  context = json.loads(context_text) if context_text.strip() else {}
 
817
  # Process action
818
  result = arf_engine.assess_action(action_text, context, license_key)
819
 
820
+ # Create enhanced displays
821
+ oss_html = create_oss_display(result, learning, psych_tip)
822
  enterprise_html = create_enterprise_display(result)
823
  comparison_html = create_comparison_display(result)
824
 
825
  # Update license status
826
  license_info = result["license_info"]
827
+ if license_info["valid"]:
828
+ tier_color = {
829
+ "trial": "#BCAAA4",
830
+ "starter": "#FFD54F",
831
+ "professional": "#FFB300",
832
+ "enterprise": "#FF6F00"
833
+ }.get(license_info["tier"], "#FFB300")
834
+
835
  status_html = f"""
836
+ <div style="background: linear-gradient(135deg, {tier_color}20 0%, {tier_color}40 100%);
837
+ padding: 20px; border-radius: 10px; text-align: center; border: 2px solid {tier_color};">
838
+ <div style="font-size: 24px; margin-bottom: 10px;">{'🎁' if license_info['tier'] == 'trial' else '✅'}</div>
839
+ <div style="font-weight: bold; color: {tier_color}; margin-bottom: 5px;">
840
+ {license_info['name']}
841
+ </div>
842
+ <div style="color: #666; font-size: 0.9em; margin-bottom: 10px;">
843
+ {license_info['message']}
844
+ </div>
845
+ <div style="font-size: 0.85em; color: #666;">
846
+ {license_info.get('social_proof', 'Enterprise-grade protection')}
847
+ </div>
848
  </div>
849
  """
850
  else:
851
  status_html = """
852
+ <div style="background: #E3F2FD; padding: 20px; border-radius: 10px; text-align: center;">
853
+ <div style="font-size: 24px; margin-bottom: 10px;">🔵</div>
854
+ <div style="font-weight: bold; color: #1E88E5; margin-bottom: 5px;">ARF OSS Edition</div>
855
+ <div style="color: #666; font-size: 0.9em; margin-bottom: 10px;">Advisory Mode - No mechanical enforcement</div>
856
+ <div style="font-size: 0.85em; color: #999;">
857
+ Upgrade to Enterprise for mechanical gates
858
+ </div>
859
  </div>
860
  """
861
 
 
870
  """
871
  return error_html, error_html, error_html, ""
872
 
873
+ def create_oss_display(result, learning, psych_tip):
874
  """Create OSS display"""
875
+ risk_score = result["risk_score"]
876
+ confidence = result["confidence"]
877
  policy = result["policy_result"]
878
+ psych = result["psych_insights"]
879
+
880
+ risk_level = psych["risk_level"]
881
+ risk_color = "#F44336" if "CRITICAL" in risk_level or "HIGH" in risk_level else "#FF9800" if "MEDIUM" in risk_level else "#4CAF50"
882
 
883
  return f"""
884
+ <div class="oss-panel">
885
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
886
+ <h2 style="margin: 0; color: #1E88E5;">🔵 ARF OSS 3.3.9</h2>
887
+ <span style="background: rgba(30, 136, 229, 0.1); padding: 8px 16px; border-radius: 20px; color: #1E88E5; font-weight: bold;">
888
+ ADVISORY ONLY
889
+ </span>
890
+ </div>
891
 
892
+ <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
893
+ <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
894
+ <div style="font-size: 0.9em; color: #1E88E5; margin-bottom: 5px;">Reliability</div>
895
+ <div style="font-size: 1.8em; font-weight: bold; color: #1E88E5;">{(1-risk_score):.1%}</div>
896
  </div>
897
 
898
+ <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
899
+ <div style="font-size: 0.9em; color: {risk_color}; margin-bottom: 5px;">Risk Level</div>
900
+ <div style="font-size: 1.8em; font-weight: bold; color: {risk_color};">{risk_level}</div>
901
  </div>
902
 
903
+ <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
904
+ <div style="font-size: 0.9em; color: #1E88E5; margin-bottom: 5px;">Confidence</div>
905
+ <div style="font-size: 1.8em; font-weight: bold; color: #1E88E5;">{confidence:.1%}</div>
906
  </div>
907
  </div>
908
 
909
+ <div style="background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid {risk_color};">
910
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
911
+ <span style="font-size: 24px; margin-right: 10px;">💡</span>
912
+ <h3 style="margin: 0; color: #333;">Recommendation</h3>
913
+ </div>
914
+ <p style="margin: 0; font-size: 1.2em; font-weight: 500; color: #333;">
915
+ {result['recommendation']}
916
+ </p>
917
+ <p style="margin: 10px 0 0 0; font-size: 0.9em; color: #666;">
918
+ Processing time: {result['processing_time']:.4f}s • {policy['total_violations']} policy violation(s)
919
+ </p>
920
  </div>
921
 
922
+ <div style="background: #FFF3E0; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
923
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
924
+ <span style="font-size: 24px; margin-right: 10px;">⚠️</span>
925
+ <h3 style="margin: 0; color: #E65100;">OSS Limitations</h3>
926
+ </div>
927
  <ul style="margin: 0; padding-left: 20px; color: #E65100;">
928
  <li>Human decision required for all actions</li>
929
  <li>No mechanical enforcement</li>
930
+ <li>Limited to advisory recommendations</li>
931
+ <li>Personal liability for decisions</li>
932
  </ul>
933
  </div>
934
+
935
+ <div class="psych-insight">
936
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
937
+ <span style="font-size: 24px; margin-right: 10px;">🧠</span>
938
+ <div>
939
+ <div style="font-weight: bold; font-size: 1.1em;">Learning Insight</div>
940
+ <div style="font-size: 0.9em; color: #666;">{learning}</div>
941
+ </div>
942
+ </div>
943
+ <p style="margin: 0; font-size: 0.9em;">{psych_tip}</p>
944
+ </div>
945
+
946
+ <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid rgba(0,0,0,0.1);">
947
+ <div style="font-size: 0.9em; color: #666; margin-bottom: 5px;">Psychological Principle</div>
948
+ <p style="margin: 0; font-size: 0.9em; font-weight: 500;">{psych['loss_aversion']}</p>
949
+ </div>
950
  </div>
951
  """
952
 
953
  def create_enterprise_display(result):
954
  """Create Enterprise display"""
 
955
  gates = result["gate_results"]
956
  license_info = result["license_info"]
957
+ psych = result["psych_insights"]
958
 
959
  # Calculate gate progress
960
+ required_gates = [g for g in gates if g["required"]]
961
+ passed_required = sum(1 for g in required_gates if g["passed"])
962
+ gate_progress = passed_required / len(required_gates) if required_gates else 0
963
+
964
+ # Determine tier color
965
+ tier_color = {
966
+ "trial": "#BCAAA4",
967
+ "starter": "#FFD54F",
968
+ "professional": "#FFB300",
969
+ "enterprise": "#FF6F00",
970
+ "oss": "#1E88E5"
971
+ }.get(license_info["tier"], "#FFB300")
972
 
973
  # Create gates HTML
974
  gates_html = ""
975
  for gate in gates:
976
+ gate_class = "gate-passed" if gate["passed"] else "gate-failed"
977
+ icon = "✅" if gate["passed"] else "❌"
978
  gates_html += f"""
979
  <div class="{gate_class}">
980
  <div style="display: flex; align-items: center;">
981
+ <span style="font-size: 20px; margin-right: 15px;">{icon}</span>
982
+ <div style="flex: 1;">
983
+ <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
984
+ <div style="font-weight: 500;">{gate['name']}</div>
985
+ <div style="font-size: 0.9em; color: #666;">{gate['weight']:.0%}</div>
986
+ </div>
987
+ <div style="font-size: 0.9em; color: #666;">{gate['message']}</div>
988
  </div>
989
  </div>
990
  </div>
991
  """
992
 
993
  return f"""
994
+ <div class="enterprise-panel" style="border-color: {tier_color};">
995
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
996
+ <h2 style="margin: 0; color: {tier_color};">🟡 ARF Enterprise 3.3.9</h2>
997
+ <span style="background: {tier_color}20; padding: 8px 16px; border-radius: 20px; color: {tier_color}; font-weight: bold;">
998
+ {license_info['name'].upper()}
999
  </span>
1000
  </div>
1001
 
1002
+ <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
1003
+ <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
1004
+ <div style="font-size: 0.9em; color: {tier_color}; margin-bottom: 5px;">License Tier</div>
1005
+ <div style="font-size: 1.4em; font-weight: bold; color: {tier_color};">{license_info['name']}</div>
1006
  </div>
1007
 
1008
+ <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
1009
+ <div style="font-size: 0.9em; color: {tier_color}; margin-bottom: 5px;">Gates Passed</div>
1010
+ <div style="font-size: 1.8em; font-weight: bold; color: {tier_color};">{passed_required}/{len(required_gates)}</div>
1011
  </div>
1012
 
1013
+ <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
1014
+ <div style="font-size: 0.9em; color: {tier_color}; margin-bottom: 5px;">Enforcement</div>
1015
+ <div style="font-size: 1.1em; font-weight: bold; color: {tier_color}; line-height: 1.2;">
1016
+ {license_info['enforcement'].replace('_', ' ').title()}
1017
  </div>
1018
  </div>
1019
  </div>
1020
 
1021
  <div style="margin-bottom: 20px;">
1022
+ <h3 style="margin: 0 0 15px 0; color: {tier_color};">Mechanical Gates</h3>
1023
+ <div style="max-height: 250px; overflow-y: auto; padding-right: 10px;">
1024
+ {gates_html}
1025
+ </div>
1026
  </div>
1027
 
1028
+ <div style="background: #E8F5E9; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
1029
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
1030
+ <span style="font-size: 24px; margin-right: 10px;">🚀</span>
1031
+ <h3 style="margin: 0; color: #2E7D32;">Enterprise Benefits</h3>
1032
+ </div>
1033
  <ul style="margin: 0; padding-left: 20px; color: #2E7D32;">
1034
  <li>Mechanical enforcement with automated gates</li>
1035
+ <li>Processing time: {result['processing_time']:.4f}s</li>
1036
+ <li>{license_info.get('value_prop', 'Enterprise-grade protection')}</li>
1037
+ <li>{psych['authority']}</li>
1038
  </ul>
1039
  </div>
1040
+
1041
+ <div class="psych-insight">
1042
+ <div style="display: flex; align-items: center; margin-bottom: 10px;">
1043
+ <span style="font-size: 24px; margin-right: 10px;">👥</span>
1044
+ <div>
1045
+ <div style="font-weight: bold; font-size: 1.1em;">Social Proof</div>
1046
+ <div style="font-size: 0.9em; color: #666;">{psych['social_proof']}</div>
1047
+ </div>
1048
+ </div>
1049
+ <p style="margin: 0; font-size: 0.9em;">{psych['scarcity']}</p>
1050
+ </div>
1051
  </div>
1052
  """
1053
 
 
1056
  policy = result["policy_result"]
1057
  gates = result["gate_results"]
1058
  license_info = result["license_info"]
1059
+ psych = result["psych_insights"]
1060
 
1061
+ oss_can_execute = not policy["blocked"]
1062
+ all_gates_passed = all(g["passed"] for g in gates if g["required"])
1063
 
1064
+ if all_gates_passed and license_info["tier"] in ["professional", "enterprise"]:
1065
  enterprise_auth = "AUTONOMOUS_EXECUTION"
1066
+ auth_color = "#4CAF50"
1067
+ auth_icon = "✅"
1068
+ auth_message = "Autonomous execution permitted"
1069
+ elif all_gates_passed and license_info["tier"] == "starter":
1070
+ enterprise_auth = "HUMAN_APPROVAL_REQUIRED"
1071
+ auth_color = "#FF9800"
1072
+ auth_icon = "👤"
1073
+ auth_message = "Human approval required"
1074
+ elif license_info["valid"]:
1075
  enterprise_auth = "ADVISORY_ONLY"
1076
+ auth_color = "#9E9E9E"
1077
+ auth_icon = "ℹ️"
1078
+ auth_message = "Trial license - advisory only"
1079
  else:
1080
  enterprise_auth = "OSS_ONLY"
1081
+ auth_color = "#1E88E5"
1082
+ auth_icon = "🔵"
1083
+ auth_message = "OSS mode - no license"
1084
 
1085
  return f"""
1086
+ <div class="comparison-card">
1087
+ <h2 style="margin: 0 0 20px 0; text-align: center; color: #333;">⚖️ Psychological Comparison</h2>
1088
 
1089
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 25px; margin-bottom: 30px;">
1090
+ <!-- OSS Column -->
1091
  <div style="text-align: center;">
1092
+ <div style="background: #E3F2FD; padding: 25px; border-radius: 12px; margin-bottom: 20px; border: 2px solid #1E88E5;">
1093
+ <h3 style="color: #1E88E5; margin: 0 0 15px 0;">🔵 OSS Experience</h3>
1094
+ <div style="font-size: 48px; margin: 20px 0;">{'⚠️' if not oss_can_execute else '✅'}</div>
1095
+ <div style="font-size: 1.3em; font-weight: bold; color: {'#F44336' if not oss_can_execute else '#4CAF50'}; margin-bottom: 10px;">
 
 
1096
  {'Advisory Only' if not oss_can_execute else 'Can Execute'}
1097
  </div>
1098
+ <div style="font-size: 0.9em; color: #666;">
1099
+ Human decision required
1100
+ </div>
1101
+ </div>
1102
+
1103
+ <div style="text-align: left;">
1104
+ <div style="background: rgba(30, 136, 229, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
1105
+ <strong>Psychological State:</strong> Uncertainty, Responsibility
1106
+ </div>
1107
+ <div style="background: rgba(30, 136, 229, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
1108
+ <strong>Mental Load:</strong> High (You decide)
1109
+ </div>
1110
+ <div style="background: rgba(30, 136, 229, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
1111
+ <strong>Risk Exposure:</strong> Personal liability
1112
+ </div>
1113
  </div>
1114
  </div>
1115
 
1116
+ <!-- Enterprise Column -->
1117
  <div style="text-align: center;">
1118
+ <div style="background: #FFF8E1; padding: 25px; border-radius: 12px; margin-bottom: 20px; border: 2px solid #FFB300;">
1119
+ <h3 style="color: #FFB300; margin: 0 0 15px 0;">🟡 Enterprise Experience</h3>
1120
+ <div style="font-size: 48px; margin: 20px 0;">{auth_icon}</div>
1121
+ <div style="font-size: 1.3em; font-weight: bold; color: {auth_color}; margin-bottom: 10px;">
 
 
1122
  {enterprise_auth.replace('_', ' ').title()}
1123
  </div>
1124
+ <div style="font-size: 0.9em; color: #666;">
1125
+ {auth_message}
1126
+ </div>
1127
+ </div>
1128
+
1129
+ <div style="text-align: left;">
1130
+ <div style="background: rgba(255, 179, 0, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
1131
+ <strong>Psychological State:</strong> Confidence, Assurance
1132
+ </div>
1133
+ <div style="background: rgba(255, 179, 0, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
1134
+ <strong>Mental Load:</strong> Low (System decides)
1135
+ </div>
1136
+ <div style="background: rgba(255, 179, 0, 0.1); padding: 12px 15px; border-radius: 8px; margin: 8px 0; font-size: 0.95em;">
1137
+ <strong>Risk Exposure:</strong> System accountability
1138
+ </div>
1139
  </div>
1140
  </div>
1141
  </div>
1142
 
1143
+ <!-- Value Metrics -->
1144
+ <div style="background: linear-gradient(135deg, #FFB30020 0%, #1E88E520 100%); padding: 25px; border-radius: 12px; margin-bottom: 25px;">
1145
+ <h3 style="margin: 0 0 20px 0; text-align: center; color: #333;">🎯 Enterprise Value Metrics</h3>
1146
+ <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
1147
+ <div style="text-align: center; padding: 20px; background: white; border-radius: 10px;">
1148
+ <div style="font-size: 0.95em; color: #2E7D32; margin-bottom: 8px;">Risk Reduction</div>
1149
+ <div style="font-size: 2em; font-weight: bold; color: #2E7D32;">92%</div>
1150
+ <div style="font-size: 0.85em; color: #666; margin-top: 5px;">Fewer incidents</div>
1151
+ </div>
1152
+ <div style="text-align: center; padding: 20px; background: white; border-radius: 10px;">
1153
+ <div style="font-size: 0.95em; color: #2E7D32; margin-bottom: 8px;">Decision Speed</div>
1154
+ <div style="font-size: 2em; font-weight: bold; color: #2E7D32;">100x</div>
1155
+ <div style="font-size: 0.85em; color: #666; margin-top: 5px;">Faster than manual</div>
1156
+ </div>
1157
+ <div style="text-align: center; padding: 20px; background: white; border-radius: 10px;">
1158
+ <div style="font-size: 0.95em; color: #2E7D32; margin-bottom: 8px;">False Positives</div>
1159
+ <div style="font-size: 2em; font-weight: bold; color: #2E7D32;">-85%</div>
1160
+ <div style="font-size: 0.85em; color: #666; margin-top: 5px;">Reduction</div>
1161
+ </div>
1162
+ <div style="text-align: center; padding: 20px; background: white; border-radius: 10px;">
1163
+ <div style="font-size: 0.95em; color: #2E7D32; margin-bottom: 8px;">ROI Time</div>
1164
+ <div style="font-size: 2em; font-weight: bold; color: #2E7D32;">3.2 mo</div>
1165
+ <div style="font-size: 0.85em; color: #666; margin-top: 5px;">Average payback</div>
1166
  </div>
1167
+ </div>
1168
+ </div>
1169
+
1170
+ <!-- Psychological CTA -->
1171
+ <div style="background: linear-gradient(135deg, #1E88E5 0%, #0D47A1 100%); color: white; padding: 30px; border-radius: 12px; text-align: center;">
1172
+ <h3 style="margin: 0 0 15px 0; color: white;">🚀 Experience the Psychological Shift</h3>
1173
+ <p style="margin: 0 0 25px 0; opacity: 0.9; font-size: 1.1em;">
1174
+ Move from uncertainty to confidence, from personal liability to system accountability
1175
+ </p>
1176
+ <div style="display: inline-flex; gap: 20px; flex-wrap: wrap; justify-content: center;">
1177
+ <div style="background: rgba(255, 255, 255, 0.2); padding: 12px 24px; border-radius: 25px;">
1178
+ <div style="font-size: 0.95em; opacity: 0.9;">Start with</div>
1179
+ <div style="font-weight: bold; font-size: 1.2em;">14-Day Free Trial</div>
1180
  </div>
1181
+ <div style="background: rgba(255, 255, 255, 0.2); padding: 12px 24px; border-radius: 25px;">
1182
+ <div style="font-size: 0.95em; opacity: 0.9;">Then upgrade to</div>
1183
+ <div style="font-weight: bold; font-size: 1.2em;">Starter: $2,000/mo</div>
1184
  </div>
1185
+ <div style="background: rgba(255, 255, 255, 0.2); padding: 12px 24px; border-radius: 25px;">
1186
+ <div style="font-size: 0.95em; opacity: 0.9;">Scale with</div>
1187
+ <div style="font-weight: bold; font-size: 1.2em;">Professional: $5,000/mo</div>
1188
  </div>
1189
  </div>
1190
  </div>
 
1197
 
1198
  def clear_inputs():
1199
  """Clear all inputs"""
1200
+ return DEMO_SCENARIOS[0]["name"], DEMO_SCENARIOS[0]["action"], json.dumps(DEMO_SCENARIOS[0]["context"], indent=2), "", "", "", "", ""
1201
 
1202
  def update_scenario(scenario_name):
1203
  """Update inputs based on scenario"""
 
1206
  return scenario["action"], json.dumps(scenario["context"], indent=2)
1207
  return "", "{}"
1208
 
1209
+ # ====================================================================
1210
+ # EVENT HANDLERS
1211
+ # ====================================================================
1212
  process_btn.click(
1213
  process_action,
1214
+ [scenario_select, action_input, context_input, license_input],
1215
  [oss_output, enterprise_output, comparison_output, license_status]
1216
  )
1217
 
1218
  clear_btn.click(
1219
  clear_inputs,
1220
+ outputs=[scenario_select, action_input, context_input, license_input, oss_output, enterprise_output, comparison_output, license_status]
1221
  )
1222
 
1223
  scenario_select.change(
 
1238
  DEMO_SCENARIOS[0]["name"],
1239
  DEMO_SCENARIOS[0]["action"],
1240
  json.dumps(DEMO_SCENARIOS[0]["context"]),
1241
+ ""
 
1242
  ),
1243
  outputs=[oss_output, enterprise_output, comparison_output, license_status]
1244
  )
 
1250
  # ============================================================================
1251
 
1252
  if __name__ == "__main__":
1253
+ print("\n🚀 Launching ARF 3.3.9 Demo with Psychological Optimization")
1254
 
1255
  try:
1256
  demo = create_demo_interface()
 
1258
  server_name="0.0.0.0",
1259
  server_port=7860,
1260
  share=False,
1261
+ debug=False
 
1262
  )
1263
  except Exception as e:
1264
+ print(f"❌ Error: {e}")
1265
+ traceback.print_exc()