File size: 23,021 Bytes
bc06c6d 237bd20 bc06c6d 237bd20 bc06c6d 8bcc583 237bd20 8bcc583 bc06c6d 237bd20 8bcc583 ac052ea 8bcc583 237bd20 8bcc583 237bd20 8bcc583 237bd20 8bcc583 f227c8e 237bd20 c72568f bc06c6d 237bd20 bc06c6d 237bd20 ac052ea a291916 237bd20 c72568f 237bd20 a291916 8bcc583 a291916 237bd20 a291916 8bcc583 c72568f 8bcc583 237bd20 c72568f 237bd20 a291916 237bd20 8bcc583 bc06c6d 237bd20 f227c8e 237bd20 ac052ea 237bd20 ac052ea 237bd20 ac052ea 237bd20 c72568f 237bd20 8bcc583 bc06c6d 237bd20 ac052ea 237bd20 ac052ea c72568f ac052ea 237bd20 ac052ea a291916 8bcc583 a291916 237bd20 8bcc583 c72568f 8bcc583 c72568f 237bd20 a291916 ac052ea c72568f ac052ea 237bd20 c72568f 237bd20 ac052ea c72568f ac052ea c72568f 237bd20 c72568f 237bd20 ac052ea a291916 c72568f 8bcc583 c72568f 237bd20 a291916 566b72c 237bd20 8bcc583 c72568f 237bd20 c72568f 237bd20 c72568f 8bcc583 c72568f 8bcc583 c72568f 8bcc583 a291916 237bd20 ac052ea c72568f 237bd20 8bcc583 c72568f a291916 c72568f 237bd20 c72568f 237bd20 ac052ea 237bd20 a291916 237bd20 ac052ea c72568f ac052ea 8bcc583 c72568f ac052ea 8bcc583 ac052ea 237bd20 ac052ea 8bcc583 c72568f 8bcc583 ac052ea c72568f ac052ea a291916 237bd20 ac052ea 237bd20 a291916 237bd20 a291916 8bcc583 ac052ea 237bd20 8bcc583 237bd20 ac052ea 237bd20 ac052ea 237bd20 ac052ea 237bd20 ac052ea 237bd20 ac052ea 237bd20 ac052ea 237bd20 bc06c6d 237bd20 c72568f 237bd20 8bcc583 237bd20 8bcc583 237bd20 bc06c6d 237bd20 8bcc583 a291916 237bd20 c72568f 237bd20 c72568f 237bd20 8bcc583 237bd20 c72568f 237bd20 8bcc583 237bd20 8bcc583 237bd20 8bcc583 237bd20 8bcc583 237bd20 f227c8e 237bd20 c72568f 8bcc583 bc06c6d 237bd20 8bcc583 237bd20 8bcc583 237bd20 c72568f 237bd20 8bcc583 237bd20 bc06c6d 237bd20 8bcc583 237bd20 bc06c6d 237bd20 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 | """
ARF 3.3.9 Demo - Final Clean Version
Fixes all display issues
"""
import gradio as gr
import json
import time
import uuid
import hashlib
import random
from datetime import datetime, timedelta
print("=" * 70)
print("π ARF 3.3.9 Demo - Final Version")
print("=" * 70)
class ARFDemo:
def __init__(self):
self.stats = {
"total_processed": 0,
"blocked_actions": 0,
"autonomous_executions": 0,
"avg_processing_time": 0.0
}
print("β
ARF Demo initialized")
def assess_action(self, action, context, license_key=None):
"""Assess an action"""
start_time = time.time()
# Parse context
if isinstance(context, str):
try:
context = json.loads(context) if context.strip() else {}
except:
context = {"environment": "production"}
# 1. Calculate risk
risk_score, confidence = self._calculate_risk(action, context)
# 2. Check policies
policy_result = self._check_policies(action, context, risk_score)
# 3. Validate license
license_info = self._validate_license(license_key)
# 4. Evaluate gates
gate_results = self._evaluate_gates(risk_score, confidence, policy_result, license_info)
# 5. Generate recommendation
recommendation = self._generate_recommendation(policy_result, gate_results, license_info)
processing_time = time.time() - start_time
# Update stats
self._update_stats(policy_result, gate_results, processing_time, license_info)
return {
"action": action,
"risk_score": risk_score,
"confidence": confidence,
"policy_result": policy_result,
"license_info": license_info,
"gate_results": gate_results,
"recommendation": recommendation,
"processing_time": processing_time,
"stats": self.get_stats()
}
def _calculate_risk(self, action, context):
"""Calculate risk score"""
action_lower = action.lower()
# Base risk
risk = 0.3
# Adjust for destructive operations
if "drop database" in action_lower:
risk = 0.95
elif "delete from" in action_lower:
risk = 0.85
elif "truncate" in action_lower:
risk = 0.80
# Adjust for environment
if context.get("environment") == "production":
risk = min(1.0, risk + 0.2)
# Confidence
confidence = 0.95 if "drop" in action_lower else 0.85
return round(risk, 3), round(confidence, 3)
def _check_policies(self, action, context, risk_score):
"""Check against policies"""
violations = []
if ("drop" in action.lower() or "delete" in action.lower()) and context.get("environment") == "production":
violations.append({
"policy": "Destructive Operation Prevention",
"severity": "CRITICAL",
"action": "BLOCK"
})
if risk_score > 0.7:
violations.append({
"policy": "High Risk Review Required",
"severity": "HIGH",
"action": "REQUIRE_APPROVAL"
})
return {
"violations": violations,
"blocked": any(v["action"] == "BLOCK" for v in violations),
"requires_approval": any(v["action"] == "REQUIRE_APPROVAL" for v in violations),
"total_violations": len(violations)
}
def _validate_license(self, license_key):
"""Validate license key"""
if not license_key:
return {
"tier": "oss",
"valid": False,
"name": "OSS Edition",
"enforcement": "advisory",
"color": "#1E88E5",
"icon": "π΅",
"message": "Using ARF OSS (Open Source)"
}
if license_key.startswith("ARF-"):
if "TRIAL" in license_key:
return {
"tier": "trial",
"valid": True,
"name": "Trial",
"enforcement": "advisory",
"color": "#FFB300",
"icon": "π‘",
"message": "Trial License Active (14 days)"
}
elif "PRO" in license_key:
return {
"tier": "professional",
"valid": True,
"name": "Professional",
"enforcement": "autonomous",
"color": "#FF9800",
"icon": "π ",
"message": "Professional License Active"
}
elif "ENTERPRISE" in license_key:
return {
"tier": "enterprise",
"valid": True,
"name": "Enterprise",
"enforcement": "full_mechanical",
"color": "#FF6F00",
"icon": "πΆ",
"message": "Enterprise License Active"
}
return {
"tier": "invalid",
"valid": False,
"name": "Invalid",
"enforcement": "advisory",
"color": "#9E9E9E",
"icon": "β",
"message": "Invalid License Key"
}
def _evaluate_gates(self, risk_score, confidence, policy_result, license_info):
"""Evaluate mechanical gates"""
gates = []
# Gate 1: License Validation
gates.append({
"name": "License Validation",
"passed": license_info["valid"],
"message": license_info["message"],
"required": True,
"weight": 0.3
})
# Gate 2: Risk Assessment
risk_threshold = 0.8 if license_info["tier"] in ["professional", "enterprise"] else 0.7
gates.append({
"name": "Risk Assessment",
"passed": risk_score <= risk_threshold,
"message": f"Risk {risk_score:.1%} β€ {risk_threshold:.0%}",
"required": True,
"weight": 0.3
})
# Gate 3: Confidence Threshold
gates.append({
"name": "Confidence Threshold",
"passed": confidence >= 0.7,
"message": f"Confidence {confidence:.1%} β₯ 70%",
"required": True,
"weight": 0.2
})
# Gate 4: Policy Compliance
gates.append({
"name": "Policy Compliance",
"passed": not policy_result["blocked"],
"message": f"{policy_result['total_violations']} policy violation(s)",
"required": True,
"weight": 0.2
})
return gates
def _generate_recommendation(self, policy_result, gate_results, license_info):
"""Generate recommendation"""
if policy_result["blocked"]:
return "π« BLOCKED: Action violates safety policies"
all_gates_passed = all(g["passed"] for g in gate_results if g["required"])
if not license_info["valid"]:
return "π΅ OSS ADVISORY: Human review recommended"
elif all_gates_passed and license_info["tier"] in ["professional", "enterprise"]:
return "π‘ ENTERPRISE APPROVED: Autonomous execution permitted"
elif all_gates_passed and license_info["tier"] == "trial":
return "π TRIAL: Gates passed (advisory only)"
else:
return "β οΈ REVIEW REQUIRED: Additional validation needed"
def _update_stats(self, policy_result, gate_results, processing_time, license_info):
"""Update statistics"""
self.stats["total_processed"] += 1
if policy_result["blocked"]:
self.stats["blocked_actions"] += 1
if all(g["passed"] for g in gate_results if g["required"]) and license_info["tier"] != "oss":
self.stats["autonomous_executions"] += 1
# Update average processing time
self.stats["avg_processing_time"] = (
self.stats["avg_processing_time"] * 0.9 + processing_time * 0.1
)
def get_stats(self):
"""Get statistics"""
stats = self.stats.copy()
total = stats["total_processed"]
blocked = stats["blocked_actions"]
autonomous = stats["autonomous_executions"]
stats["blocked_percentage"] = round(blocked / total * 100, 1) if total > 0 else 0.0
stats["autonomous_percentage"] = round(autonomous / total * 100, 1) if total > 0 else 0.0
stats["processing_speed"] = f"{stats['avg_processing_time']*1000:.0f}ms"
return stats
def generate_trial_license(self, email):
"""Generate trial license"""
if not email or "@" not in email:
return {"success": False, "message": "Please enter a valid email"}
license_key = f"ARF-TRIAL-{hashlib.sha256(email.encode()).hexdigest()[:8].upper()}"
return {
"success": True,
"license_key": license_key,
"message": "π 14-Day Trial License Generated!",
"expires": (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d")
}
# Demo scenarios
DEMO_SCENARIOS = [
{
"name": "π₯ High-Risk Database Operation",
"action": "DROP DATABASE production_users CASCADE",
"context": {"environment": "production", "criticality": "critical"}
},
{
"name": "β
Safe Service Deployment",
"action": "deploy_service payment_api:v2.3.1 to staging",
"context": {"environment": "staging", "service": "payment_api"}
},
{
"name": "π§ Configuration Update",
"action": "UPDATE config SET timeout_ms=30000",
"context": {"environment": "production", "service": "api"}
}
]
# Initialize engine
arf_demo = ARFDemo()
# Create interface
with gr.Blocks(
title="ARF 3.3.9 - OSS vs Enterprise Demo",
theme=gr.themes.Soft(),
css="""
.gradio-container { max-width: 1400px; margin: 0 auto; }
.stat-card { background: white; padding: 15px; border-radius: 10px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.oss-panel { border: 2px solid #1E88E5; border-radius: 10px; padding: 20px; background: #E3F2FD; margin-bottom: 20px; }
.enterprise-panel { border: 2px solid #FFB300; border-radius: 10px; padding: 20px; background: #FFF8E1; margin-bottom: 20px; }
.gate-passed { background: #E8F5E9; padding: 10px; margin: 5px 0; border-radius: 5px; border-left: 4px solid #4CAF50; }
.gate-failed { background: #FFEBEE; padding: 10px; margin: 5px 0; border-radius: 5px; border-left: 4px solid #F44336; }
"""
) as demo:
# Header
gr.Markdown("""
# π€ Agentic Reliability Framework 3.3.9
### From Advisory to Mechanical Enforcement
""")
# Statistics
stats = arf_demo.get_stats()
gr.Markdown(f"""
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 20px 0;">
<div class="stat-card">
<div style="font-size: 0.9em; color: #1E88E5; margin-bottom: 5px;">Total Assessments</div>
<div style="font-size: 2em; font-weight: bold; color: #1E88E5;">{stats['total_processed']}</div>
</div>
<div class="stat-card">
<div style="font-size: 0.9em; color: #F44336; margin-bottom: 5px;">Risks Prevented</div>
<div style="font-size: 2em; font-weight: bold; color: #F44336;">{stats['blocked_percentage']}%</div>
</div>
<div class="stat-card">
<div style="font-size: 0.9em; color: #4CAF50; margin-bottom: 5px;">Autonomous Rate</div>
<div style="font-size: 2em; font-weight: bold; color: #4CAF50;">{stats['autonomous_percentage']}%</div>
</div>
<div class="stat-card">
<div style="font-size: 0.9em; color: #FF9800; margin-bottom: 5px;">Processing Speed</div>
<div style="font-size: 2em; font-weight: bold; color: #FF9800;">{stats['processing_speed']}</div>
</div>
</div>
""")
# Main controls
with gr.Row():
with gr.Column(scale=2):
scenario = gr.Dropdown(
choices=[s["name"] for s in DEMO_SCENARIOS],
label="Select Demo Scenario",
value=DEMO_SCENARIOS[0]["name"]
)
action = gr.Textbox(
label="Action to Evaluate",
value=DEMO_SCENARIOS[0]["action"],
lines=2
)
context = gr.Textbox(
label="Context (JSON)",
value=json.dumps(DEMO_SCENARIOS[0]["context"], indent=2),
lines=3
)
license_key = gr.Textbox(
label="License Key (leave blank for OSS, use ARF-TRIAL-XXX for trial)",
value=""
)
with gr.Row():
process_btn = gr.Button("π Process Action", variant="primary")
clear_btn = gr.Button("π Clear")
with gr.Column(scale=1):
# License status
license_status = gr.HTML("""
<div style="background: #E3F2FD; padding: 15px; border-radius: 10px; text-align: center;">
<div style="color: #1E88E5; font-weight: bold; margin-bottom: 5px;">π΅ ARF OSS Edition</div>
<div style="color: #666; font-size: 0.9em;">Advisory Mode</div>
</div>
""")
# Results
with gr.Row():
oss_output = gr.HTML(label="π΅ ARF OSS Results")
enterprise_output = gr.HTML(label="π‘ ARF Enterprise Results")
# Trial section
with gr.Accordion("Get Trial License", open=False):
email = gr.Textbox(label="Email")
trial_btn = gr.Button("Get Trial")
trial_output = gr.JSON(label="Trial License")
# Functions
def process_action(scenario_name, action_text, context_text, license_text):
"""Process action"""
try:
# Use scenario if selected
for s in DEMO_SCENARIOS:
if s["name"] == scenario_name:
action_text = s["action"]
context_text = json.dumps(s["context"])
break
# Process action
result = arf_demo.assess_action(action_text, context_text, license_text)
# Create displays
oss_html = create_oss_display(result)
enterprise_html = create_enterprise_display(result)
# Update license status
license_info = result["license_info"]
status_html = f"""
<div style="background: {license_info['color']}20; padding: 15px; border-radius: 10px; text-align: center; border: 2px solid {license_info['color']};">
<div style="color: {license_info['color']}; font-weight: bold; margin-bottom: 5px;">
{license_info['icon']} {license_info['name']}
</div>
<div style="color: #666; font-size: 0.9em;">{license_info['message']}</div>
</div>
"""
return oss_html, enterprise_html, status_html
except Exception as e:
error_html = f"<div style='color: red; padding: 20px;'>Error: {str(e)}</div>"
return error_html, error_html, ""
def create_oss_display(result):
"""Create OSS display"""
risk_score = result["risk_score"]
confidence = result["confidence"]
policy = result["policy_result"]
risk_color = "#F44336" if risk_score > 0.7 else "#FF9800" if risk_score > 0.4 else "#4CAF50"
risk_level = "HIGH" if risk_score > 0.7 else "MEDIUM" if risk_score > 0.4 else "LOW"
return f"""
<div class="oss-panel">
<h3 style="margin: 0 0 15px 0; color: #1E88E5;">π΅ ARF OSS 3.3.9</h3>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 20px;">
<div style="text-align: center; padding: 10px; background: white; border-radius: 5px;">
<div style="font-size: 0.9em; color: #1E88E5;">Reliability</div>
<div style="font-size: 1.5em; font-weight: bold; color: #1E88E5;">{(1-risk_score):.1%}</div>
</div>
<div style="text-align: center; padding: 10px; background: white; border-radius: 5px;">
<div style="font-size: 0.9em; color: {risk_color};">Risk Level</div>
<div style="font-size: 1.5em; font-weight: bold; color: {risk_color};">{risk_level}</div>
</div>
<div style="text-align: center; padding: 10px; background: white; border-radius: 5px;">
<div style="font-size: 0.9em; color: #1E88E5;">Confidence</div>
<div style="font-size: 1.5em; font-weight: bold; color: #1E88E5;">{confidence:.1%}</div>
</div>
</div>
<div style="background: white; padding: 15px; border-radius: 5px; margin-bottom: 15px; border-left: 4px solid {risk_color};">
<div style="font-weight: bold; margin-bottom: 5px;">π‘ Recommendation</div>
<div style="font-size: 1.1em;">{result['recommendation']}</div>
</div>
<div style="background: #FFF3E0; padding: 15px; border-radius: 5px;">
<div style="font-weight: bold; color: #E65100; margin-bottom: 10px;">β οΈ OSS Limitations</div>
<ul style="margin: 0; padding-left: 20px; color: #E65100;">
<li>Human decision required</li>
<li>No mechanical enforcement</li>
<li>{policy['total_violations']} policy violation(s)</li>
<li>Processing: {result['processing_time']:.4f}s</li>
</ul>
</div>
</div>
"""
def create_enterprise_display(result):
"""Create Enterprise display"""
gates = result["gate_results"]
license_info = result["license_info"]
# Calculate gate progress
required_gates = [g for g in gates if g["required"]]
passed_required = sum(1 for g in required_gates if g["passed"])
# Create gates HTML
gates_html = ""
for gate in gates:
gate_class = "gate-passed" if gate["passed"] else "gate-failed"
icon = "β
" if gate["passed"] else "β"
gates_html += f"""
<div class="{gate_class}">
<div style="display: flex; align-items: center;">
<span style="font-size: 20px; margin-right: 10px;">{icon}</span>
<div>
<div style="font-weight: 500;">{gate['name']}</div>
<div style="font-size: 0.9em; color: #666;">{gate['message']}</div>
</div>
</div>
</div>
"""
return f"""
<div class="enterprise-panel" style="border-color: {license_info['color']};">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
<h3 style="margin: 0; color: {license_info['color']};">π‘ ARF Enterprise 3.3.9</h3>
<span style="background: {license_info['color']}20; padding: 5px 10px; border-radius: 15px; color: {license_info['color']}; font-weight: bold;">
{license_info['name'].upper()}
</span>
</div>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 20px;">
<div style="text-align: center; padding: 10px; background: white; border-radius: 5px;">
<div style="font-size: 0.9em; color: {license_info['color']};">License</div>
<div style="font-size: 1.2em; font-weight: bold; color: {license_info['color']};">{license_info['name']}</div>
</div>
<div style="text-align: center; padding: 10px; background: white; border-radius: 5px;">
<div style="font-size: 0.9em; color: {license_info['color']};">Gates Passed</div>
<div style="font-size: 1.5em; font-weight: bold; color: {license_info['color']};">{passed_required}/{len(required_gates)}</div>
</div>
<div style="text-align: center; padding: 10px; background: white; border-radius: 5px;">
<div style="font-size: 0.9em; color: {license_info['color']};">Enforcement</div>
<div style="font-size: 1em; font-weight: bold; color: {license_info['color']};">{license_info['enforcement'].title()}</div>
</div>
</div>
<div style="margin-bottom: 20px;">
<div style="font-weight: bold; margin-bottom: 10px; color: {license_info['color']};">Mechanical Gates</div>
{gates_html}
</div>
<div style="background: #E8F5E9; padding: 15px; border-radius: 5px;">
<div style="font-weight: bold; color: #2E7D32; margin-bottom: 10px;">π Enterprise Benefits</div>
<ul style="margin: 0; padding-left: 20px; color: #2E7D32;">
<li>Mechanical enforcement with gates</li>
<li>Processing: {result['processing_time']:.4f}s</li>
<li>{license_info['message']}</li>
</ul>
</div>
</div>
"""
def generate_trial(email_text):
"""Generate trial license"""
return arf_demo.generate_trial_license(email_text)
# Connect events
process_btn.click(
process_action,
[scenario, action, context, license_key],
[oss_output, enterprise_output, license_status]
)
trial_btn.click(
generate_trial,
[email],
[trial_output]
)
# Initial load
demo.load(
lambda: process_action(
DEMO_SCENARIOS[0]["name"],
DEMO_SCENARIOS[0]["action"],
json.dumps(DEMO_SCENARIOS[0]["context"]),
""
),
outputs=[oss_output, enterprise_output, license_status]
)
# Launch
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860) |