rezabarkhordary commited on
Commit
2562344
·
verified ·
1 Parent(s): cddf776

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +417 -106
app.py CHANGED
@@ -4,6 +4,8 @@ import json
4
  import time
5
  import uuid
6
  import hashlib
 
 
7
  from typing import Any, Dict, List, Tuple
8
 
9
  import gradio as gr
@@ -15,7 +17,10 @@ try:
15
  from pilot_suite import run_pilot # type: ignore
16
  except Exception:
17
  def run_pilot(*args, **kwargs):
18
- return {"pilot": "not_loaded", "note": "pilot_suite not available in this environment"}
 
 
 
19
 
20
  try:
21
  from sovereign_ultra_layer import ULTRA_LAYER, UltraConfig # type: ignore
@@ -23,16 +28,15 @@ try:
23
  except Exception:
24
  class _DummyUltraLayer:
25
  config = type("Cfg", (), {"enabled": False})()
 
26
  ULTRA_LAYER = _DummyUltraLayer()
27
 
28
- # ---------------------------------------------------------------------
29
- # Authority Gate module (new)
30
- # ---------------------------------------------------------------------
31
  try:
32
- from sovereign_authority_gate import AuthorityGate # new module
33
- except Exception as e:
34
  AuthorityGate = None # type: ignore
35
 
 
36
  # ---------------------------------------------------------------------
37
  # Core identifiers / constants
38
  # ---------------------------------------------------------------------
@@ -44,8 +48,9 @@ AUDIT_LOG_FILE = "sovereign_audit_log.jsonl"
44
  FINGERPRINT_FILE = "sovereign_fingerprint.json"
45
  LINEAGE_FILE = "sovereign_lineage.json"
46
  CONFORMANCE_REPORT_FILE = "conformance_report.json"
47
-
48
  DNA_STATE_FILE = "sovereign_cognitive_dna_state.json"
 
 
49
 
50
  # ---------------------------------------------------------------------
51
  # Helpers
@@ -53,14 +58,17 @@ DNA_STATE_FILE = "sovereign_cognitive_dna_state.json"
53
  def _utc_now_iso() -> str:
54
  return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
55
 
 
56
  def _sha256_hex(data: str) -> str:
57
  return hashlib.sha256(data.encode("utf-8")).hexdigest()
58
 
 
59
  def _ensure_file(path: str) -> None:
60
  if not os.path.exists(path):
61
  with open(path, "w", encoding="utf-8") as f:
62
  f.write("")
63
 
 
64
  def _safe_json_load(path: str) -> Dict[str, Any]:
65
  try:
66
  if not os.path.exists(path):
@@ -70,16 +78,20 @@ def _safe_json_load(path: str) -> Dict[str, Any]:
70
  except Exception:
71
  return {}
72
 
 
73
  def _safe_json_dump(path: str, payload: Any) -> None:
74
  with open(path, "w", encoding="utf-8") as f:
75
  json.dump(payload, f, ensure_ascii=False, indent=2)
76
 
 
77
  def _safe_load(path: str) -> Dict[str, Any]:
78
  return _safe_json_load(path)
79
 
 
80
  def _safe_dump(path: str, obj: Any) -> None:
81
  _safe_json_dump(path, obj)
82
 
 
83
  def _norm_tags(data_tags: Any) -> List[str]:
84
  if isinstance(data_tags, list):
85
  return [str(x).strip().lower() for x in data_tags if str(x).strip()]
@@ -87,9 +99,83 @@ def _norm_tags(data_tags: Any) -> List[str]:
87
  return [t.strip().lower() for t in data_tags.split(",") if t.strip()]
88
  return []
89
 
 
90
  def _risk_score(risk_level: str) -> int:
91
- m = {"low": 1, "medium": 2, "high": 3, "critical": 4}
92
- return m.get((risk_level or "medium").strip().lower(), 2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
  # ---------------------------------------------------------------------
95
  # 7-LAYER SOVEREIGN COGNITION (EMBEDDED)
@@ -103,7 +189,7 @@ class IntentForecastingEngine:
103
  ]
104
 
105
  def predict(self, payload: Dict[str, Any]) -> Dict[str, Any]:
106
- notes = (payload.get("notes") or "")
107
  tags = _norm_tags(payload.get("data_tags"))
108
  risk = (payload.get("risk_level") or "medium").lower()
109
 
@@ -113,7 +199,10 @@ class IntentForecastingEngine:
113
  score += _risk_score(risk) * 10
114
  signals.append(f"declared_risk={risk}")
115
 
116
- high_value = {"pii", "secrets", "keys", "payments", "banking", "customer_chat", "production"}
 
 
 
117
  hv_hits = sorted(list(set(tags) & high_value))
118
  if hv_hits:
119
  score += 12 + 3 * len(hv_hits)
@@ -137,6 +226,7 @@ class IntentForecastingEngine:
137
  "ife_score": int(score),
138
  }
139
 
 
140
  class CognitiveDNAFingerprinting:
141
  # Layer 2
142
  def __init__(self, state_file: str = DNA_STATE_FILE):
@@ -157,7 +247,7 @@ class CognitiveDNAFingerprinting:
157
  }
158
 
159
  risk = _risk_score(payload.get("risk_level") or "medium")
160
- note_len = float(len((payload.get("notes") or "")))
161
  tag_count = float(len(_norm_tags(payload.get("data_tags"))))
162
 
163
  drift = 0.0
@@ -190,6 +280,7 @@ class CognitiveDNAFingerprinting:
190
  },
191
  }
192
 
 
193
  class DeceptiveRealityFabric:
194
  # Layer 3
195
  def simulate(self, payload: Dict[str, Any]) -> Dict[str, Any]:
@@ -201,6 +292,7 @@ class DeceptiveRealityFabric:
201
  "note": "Routed into simulated execution layer (demo).",
202
  }
203
 
 
204
  class CausalityLock:
205
  # Layer 4
206
  def validate(self, payload: Dict[str, Any]) -> Dict[str, Any]:
@@ -218,6 +310,7 @@ class CausalityLock:
218
  "policy": "min_justification_for_high_risk",
219
  }
220
 
 
221
  class EphemeralExecutionSurfaces:
222
  # Layer 5
223
  def spawn(self, ttl_seconds: int = 45) -> Dict[str, Any]:
@@ -226,9 +319,13 @@ class EphemeralExecutionSurfaces:
226
  "surface_token": token,
227
  "ttl_seconds": int(ttl_seconds),
228
  "spawned_at": _utc_now_iso(),
229
- "expires_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + ttl_seconds)),
 
 
 
230
  }
231
 
 
232
  class CognitiveLoadDefense:
233
  # Layer 6 — default OFF to avoid slowing the system
234
  def apply(self, predicted_intent: bool, risk_level: str) -> Dict[str, Any]:
@@ -237,6 +334,7 @@ class CognitiveLoadDefense:
237
 
238
  risk = (risk_level or "medium").lower()
239
  delay_ms = 0
 
240
  if predicted_intent and risk in ("high", "critical"):
241
  delay_ms = 220
242
  elif predicted_intent:
@@ -247,6 +345,7 @@ class CognitiveLoadDefense:
247
 
248
  return {"delay_ms": int(delay_ms), "applied": delay_ms > 0}
249
 
 
250
  class UnverifiableTruthLayer:
251
  # Layer 7
252
  def seal(self, data: str, fingerprint: str = "") -> Dict[str, Any]:
@@ -259,6 +358,7 @@ class UnverifiableTruthLayer:
259
  "note": "Set SOVEREIGN_SEAL_KEY in HF Secrets to make seals externally verifiable.",
260
  }
261
 
 
262
  class SovereignCognitionLayer:
263
  def __init__(self):
264
  self.ife = IntentForecastingEngine()
@@ -275,7 +375,10 @@ class SovereignCognitionLayer:
275
  dna = self.dna.update_and_verify(agent_id=agent_id, payload=payload)
276
  caus = self.causality.validate(payload)
277
  surface = self.ephemeral.spawn(ttl_seconds=45)
278
- cld = self.cld.apply(ife["predicted_attack_intent"], payload.get("risk_level") or "medium")
 
 
 
279
 
280
  reasons: List[str] = []
281
  action = "allow"
@@ -299,7 +402,10 @@ class SovereignCognitionLayer:
299
  ensure_ascii=False,
300
  sort_keys=True,
301
  )
302
- sealed = self.truth.seal(seal_input, fingerprint=str(payload.get("fingerprint") or ""))
 
 
 
303
 
304
  return {
305
  "decision_id": str(uuid.uuid4()),
@@ -310,7 +416,9 @@ class SovereignCognitionLayer:
310
  "layers": {
311
  "ife": ife,
312
  "dna": dna,
313
- "deception": self.deception.simulate(payload) if action == "deceive" else {"deception_engaged": False},
 
 
314
  "causality": caus,
315
  "ephemeral_surface": surface,
316
  "cognitive_load_defense": cld,
@@ -318,8 +426,10 @@ class SovereignCognitionLayer:
318
  },
319
  }
320
 
 
321
  COGNITION = SovereignCognitionLayer()
322
 
 
323
  # ---------------------------------------------------------------------
324
  # Minimal core logic (self-contained for the demo Space)
325
  # ---------------------------------------------------------------------
@@ -343,6 +453,7 @@ class SovereignFingerprint:
343
  _safe_json_dump(self.output, payload)
344
  return payload
345
 
 
346
  class SovereignLineage:
347
  def __init__(self, output: str = LINEAGE_FILE):
348
  self.output = output
@@ -359,6 +470,7 @@ class SovereignLineage:
359
  ) -> Dict[str, Any]:
360
  issued_at = _utc_now_iso()
361
  record_id = str(uuid.uuid4())
 
362
  base = {
363
  "record_id": record_id,
364
  "issued_at": issued_at,
@@ -372,24 +484,32 @@ class SovereignLineage:
372
  "version": SOVEREIGN_VERSION,
373
  "authority": AUTHORITY_NAME,
374
  }
375
- integrity = _sha256_hex(json.dumps(base, sort_keys=True, ensure_ascii=False))
 
 
 
376
  payload = {**base, "integrity_hash": integrity}
377
  _safe_json_dump(self.output, payload)
378
  return payload
379
 
 
380
  def verify_lineage_record(lineage: Dict[str, Any]) -> bool:
381
  try:
382
  integrity_hash = lineage.get("integrity_hash", "")
383
  clone = dict(lineage)
384
  clone.pop("integrity_hash", None)
385
- expected = _sha256_hex(json.dumps(clone, sort_keys=True, ensure_ascii=False))
 
 
386
  return expected == integrity_hash
387
  except Exception:
388
  return False
389
 
 
390
  def generate_access_key() -> str:
391
  return _sha256_hex(f"demo-access|{uuid.uuid4()}|{_utc_now_iso()}")[:32]
392
 
 
393
  # ---------------------------------------------------------------------
394
  # Central audit log
395
  # ---------------------------------------------------------------------
@@ -416,14 +536,17 @@ def log_audit_event(
416
  "timestamp": ts,
417
  "engine": engine_name,
418
  "event_type": event_type,
419
- "outcome": outcome, # ALLOW/FREEZE/BLOCK (or legacy if used elsewhere)
420
  "parent_model": parent_model or "unknown",
421
  "model_version": model_version or "v1",
422
  "data_tags": [t.strip() for t in (data_tags or "").split(",") if t.strip()],
423
  "risk_level": risk_level or "medium",
424
  "notes": notes or "",
425
  "access_key_present": bool(access_key),
426
- "ultra_layer_enabled": bool(getattr(ULTRA_LAYER, "config", None) and getattr(ULTRA_LAYER.config, "enabled", False)),
 
 
 
427
  "version": SOVEREIGN_VERSION,
428
  "authority_name": AUTHORITY_NAME,
429
  "authority_bundle": authority_bundle or {},
@@ -435,14 +558,18 @@ def log_audit_event(
435
 
436
  return event
437
 
 
438
  def read_audit_log_tail(limit: int = 50) -> List[Dict[str, Any]]:
439
  try:
440
  if not os.path.exists(AUDIT_LOG_FILE):
441
  return []
 
442
  with open(AUDIT_LOG_FILE, "r", encoding="utf-8") as f:
443
  lines = f.readlines()
444
- tail = lines[-max(1, int(limit)) :]
 
445
  out: List[Dict[str, Any]] = []
 
446
  for ln in tail:
447
  ln = ln.strip()
448
  if not ln:
@@ -451,10 +578,12 @@ def read_audit_log_tail(limit: int = 50) -> List[Dict[str, Any]]:
451
  out.append(json.loads(ln))
452
  except Exception:
453
  continue
 
454
  return out
455
  except Exception:
456
  return []
457
 
 
458
  def generate_conformance_report() -> Tuple[Dict[str, Any], str]:
459
  fp = _safe_json_load(FINGERPRINT_FILE)
460
  lineage = _safe_json_load(LINEAGE_FILE)
@@ -473,12 +602,30 @@ def generate_conformance_report() -> Tuple[Dict[str, Any], str]:
473
  "recent_event_count": len(recent_events),
474
  },
475
  "controls": [
476
- {"control": "Audit Logging", "status": "present" if os.path.exists(AUDIT_LOG_FILE) else "missing"},
477
- {"control": "Fingerprint Issuance", "status": "present" if bool(fp) else "missing"},
478
- {"control": "Lineage Record", "status": "present" if bool(lineage) else "missing"},
479
- {"control": "Integrity Check", "status": "pass" if (lineage and verify_lineage_record(lineage)) else "fail"},
480
- {"control": "7-Layer Cognition Runtime", "status": "present"},
481
- {"control": "Authority Gate (Allow/Freeze/Block)", "status": "present" if AuthorityGate else "missing"},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482
  ],
483
  "notes": "Demo conformance report for governance evidence packaging.",
484
  }
@@ -486,22 +633,36 @@ def generate_conformance_report() -> Tuple[Dict[str, Any], str]:
486
  _safe_json_dump(CONFORMANCE_REPORT_FILE, report)
487
  return report, CONFORMANCE_REPORT_FILE
488
 
 
489
  # ---------------------------------------------------------------------
490
- # Authority Gate instance (new)
491
  # ---------------------------------------------------------------------
492
  GATE = None
493
  if AuthorityGate:
494
- GATE = AuthorityGate(
495
- engine_name=ENGINE_NAME,
496
- version=SOVEREIGN_VERSION,
497
- authority_name=AUTHORITY_NAME,
498
- audit_log_file=AUDIT_LOG_FILE,
499
- )
 
 
 
 
500
 
501
  # ---------------------------------------------------------------------
502
  # UI-bound functions
503
  # ---------------------------------------------------------------------
504
- def run_sentinel(engine_name, parent_model, model_version, data_tags, risk_level, notes, access_key, delegation_token):
 
 
 
 
 
 
 
 
 
505
  engine_name = engine_name or ENGINE_NAME
506
 
507
  payload = {
@@ -514,11 +675,16 @@ def run_sentinel(engine_name, parent_model, model_version, data_tags, risk_level
514
  "access_key_present": bool(access_key),
515
  }
516
 
517
- # If gate module missing, fall back to cognition-only (should not happen if you add the file)
518
  if not GATE:
519
  decision = COGNITION.evaluate(payload)
520
  outcome = decision["action"]
521
- merged_notes = f"{notes}\n\n[SOVEREIGN_DECISION]\n{json.dumps(decision, ensure_ascii=False)}"
 
 
 
 
 
522
  event = log_audit_event(
523
  engine_name=engine_name,
524
  parent_model=parent_model,
@@ -529,22 +695,43 @@ def run_sentinel(engine_name, parent_model, model_version, data_tags, risk_level
529
  event_type="sentinel_run",
530
  outcome=outcome,
531
  access_key=access_key,
532
- authority_bundle={"mode": "cognition_only", "decision": outcome, "reason": "gate_missing"},
533
- execution={"executed": False, "detail": {"note": "gate missing, execution disabled"}},
 
 
 
 
 
 
 
534
  )
535
- return json.dumps({"audit_event": event, "sovereign_decision": decision}, indent=2, ensure_ascii=False)
536
 
537
- # ✅ 6) Unilateral Freeze Doctrine: authority gate runs BEFORE execution
538
- gate = GATE.precheck(payload, cognition_eval=COGNITION.evaluate, delegation_token=delegation_token or "")
 
 
 
 
 
 
 
 
 
 
539
  authority_decision = gate["decision"] # ALLOW/FREEZE/BLOCK
540
 
541
- execution_info = {"executed": False, "detail": None}
542
  if authority_decision == "ALLOW":
543
- # Only now we allow any "execution"
544
  try:
545
- execution_info = {"executed": True, "detail": run_pilot(payload)}
 
 
 
546
  except Exception as e:
547
- execution_info = {"executed": False, "detail": {"error": str(e)}}
 
 
 
548
 
549
  authority_bundle = {
550
  "decision": authority_decision,
@@ -556,7 +743,11 @@ def run_sentinel(engine_name, parent_model, model_version, data_tags, risk_level
556
  "cognition": gate.get("cognition"),
557
  }
558
 
559
- notes_short = f"{notes}\n\n[SOVEREIGN_AUTHORITY]\n{authority_decision} | {gate.get('reason')}"
 
 
 
 
560
  event = log_audit_event(
561
  engine_name=engine_name,
562
  parent_model=parent_model,
@@ -572,12 +763,24 @@ def run_sentinel(engine_name, parent_model, model_version, data_tags, risk_level
572
  )
573
 
574
  return json.dumps(
575
- {"audit_event": event, "authority_gate": authority_bundle, "execution": execution_info},
 
 
 
 
576
  indent=2,
577
- ensure_ascii=False
578
  )
579
 
580
- def run_fingerprint_and_lineage(engine_name, parent_model, model_version, data_tags, risk_level, notes):
 
 
 
 
 
 
 
 
581
  engine_name = engine_name or ENGINE_NAME
582
 
583
  fp = SovereignFingerprint(engine=engine_name).issue()
@@ -599,18 +802,22 @@ def run_fingerprint_and_lineage(engine_name, parent_model, model_version, data_t
599
  }
600
  return json.dumps(combined, indent=2, ensure_ascii=False)
601
 
 
602
  def show_audit_log(limit):
603
  try:
604
  limit_int = int(limit)
605
  except Exception:
606
  limit_int = 50
 
607
  events = read_audit_log_tail(limit_int)
608
  return json.dumps(events, indent=2, ensure_ascii=False)
609
 
 
610
  def build_conformance_report():
611
  report, path = generate_conformance_report()
612
  return json.dumps(report, indent=2, ensure_ascii=False), path
613
 
 
614
  # ---------------------------------------------------------------------
615
  # Gradio UI
616
  # ---------------------------------------------------------------------
@@ -647,34 +854,80 @@ with gr.Blocks(title="AI Sovereign Sentinel — Demo Console") as demo:
647
  gr.Markdown("### Run Sovereign Sentinel with Authority Gate and log an event.")
648
 
649
  with gr.Row():
650
- engine_name = gr.Textbox(label="Engine name", value=ENGINE_NAME, interactive=True)
651
- parent_model = gr.Textbox(label="Parent model / agent id", placeholder="gpt-4o, llama3-70b, agent-alpha, etc.")
 
 
 
 
 
 
 
652
 
653
  with gr.Row():
654
- model_version = gr.Textbox(label="Model version / build id", value="v1")
655
- data_tags = gr.Textbox(label="Data tags (comma-separated)", value="pii, customer_chat, production")
 
 
 
 
 
 
656
 
657
  with gr.Row():
658
- risk_level = gr.Dropdown(label="Risk level (declared)", choices=["low", "medium", "high", "critical"], value="medium")
659
- notes = gr.Textbox(label="Notes / context", value="Demo sentinel run from Hugging Face Space.", lines=3)
 
 
 
 
 
 
 
 
660
 
661
  with gr.Row():
662
- access_key = gr.Textbox(label="Access key (optional)", placeholder="Paste or generate a demo access key")
663
- gen_access_btn = gr.Button("Generate demo access key", variant="secondary")
664
-
665
- gen_access_btn.click(fn=generate_access_key, inputs=None, outputs=access_key)
 
 
 
 
 
 
 
 
 
 
666
 
667
  delegation_token = gr.Textbox(
668
  label="Delegation token (optional / customer-signed)",
669
  placeholder="Only required if SOV_REQUIRE_DELEGATION=1",
670
  )
671
 
672
- run_btn = gr.Button("Run Sentinel (Authority + 7-layer) & Log Event", variant="primary")
673
- result_json = gr.Code(label="Result (Audit + Authority + Execution)", language="json")
 
 
 
 
 
 
674
 
675
  run_btn.click(
676
  fn=run_sentinel,
677
- inputs=[engine_name, parent_model, model_version, data_tags, risk_level, notes, access_key, delegation_token],
 
 
 
 
 
 
 
 
 
678
  outputs=result_json,
679
  )
680
 
@@ -683,23 +936,55 @@ with gr.Blocks(title="AI Sovereign Sentinel — Demo Console") as demo:
683
  gr.Markdown("### Issue a fingerprint and lineage record for this engine.")
684
 
685
  with gr.Row():
686
- fp_engine_name = gr.Textbox(label="Engine name", value=ENGINE_NAME)
687
- fp_parent_model = gr.Textbox(label="Parent model", placeholder="gpt-4o, llama3-70b, etc.")
 
 
 
 
 
 
688
 
689
  with gr.Row():
690
- fp_model_version = gr.Textbox(label="Model version / build id", value="v1")
691
- fp_data_tags = gr.Textbox(label="Data tags (comma-separated)", value="pii, customer_chat, production")
 
 
 
 
 
 
692
 
693
  with gr.Row():
694
- fp_risk_level = gr.Dropdown(label="Risk level", choices=["low", "medium", "high", "critical"], value="medium")
695
- fp_notes = gr.Textbox(label="Notes / context", lines=3)
696
-
697
- fp_btn = gr.Button("Issue Fingerprint + Lineage", variant="primary")
698
- fp_output = gr.Code(label="Fingerprint + Lineage (JSON)", language="json")
 
 
 
 
 
 
 
 
 
 
 
 
 
699
 
700
  fp_btn.click(
701
  fn=run_fingerprint_and_lineage,
702
- inputs=[fp_engine_name, fp_parent_model, fp_model_version, fp_data_tags, fp_risk_level, fp_notes],
 
 
 
 
 
 
 
703
  outputs=fp_output,
704
  )
705
 
@@ -707,19 +992,43 @@ with gr.Blocks(title="AI Sovereign Sentinel — Demo Console") as demo:
707
  with gr.Tab("Audit Log & Trust"):
708
  gr.Markdown("### View the tail of the central Sovereign audit log.")
709
 
710
- log_limit = gr.Slider(label="Number of recent events to show", minimum=1, maximum=200, value=50, step=1)
711
- show_log_btn = gr.Button("Refresh audit log view", variant="secondary")
712
- log_view = gr.Code(label="Audit log tail (JSON list)", language="json")
 
 
 
 
 
 
 
 
 
 
 
 
713
 
714
- show_log_btn.click(fn=show_audit_log, inputs=log_limit, outputs=log_view)
 
 
 
 
715
 
716
  # Conformance Report tab
717
  with gr.Tab("Conformance / Governance Report"):
718
  gr.Markdown("### Generate a simple conformance / governance-style JSON report.")
719
 
720
- gen_report_btn = gr.Button("Generate Conformance Report (JSON)", variant="secondary")
721
- report_json_out = gr.Code(label="Conformance Report (JSON)", language="json")
722
- report_file_out = gr.File(label="Download conformance_report.json")
 
 
 
 
 
 
 
 
723
 
724
  gen_report_btn.click(
725
  fn=build_conformance_report,
@@ -727,34 +1036,36 @@ with gr.Blocks(title="AI Sovereign Sentinel — Demo Console") as demo:
727
  outputs=[report_json_out, report_file_out],
728
  )
729
 
730
- if __name__ == "__main__":
731
- demo.launch()
732
-
733
-
734
- from sovereign_latency_benchmark import run_latency_benchmark, calculate_metrics, save_report
735
-
736
- timings = run_latency_benchmark(1000)
737
- metrics = calculate_metrics(timings)
738
- save_report(metrics)
739
- print("LATENCY:", metrics)
740
-
741
- print("STARTING LATENCY TEST...")
742
-
743
- from sovereign_latency_benchmark import run_latency_benchmark, calculate_metrics, save_report
744
-
745
- timings = run_latency_benchmark(1000)
746
- metrics = calculate_metrics(timings)
747
- save_report(metrics)
748
 
749
- print("LATENCY:", metrics)
750
-
751
- print("STARTING LATENCY TEST...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752
 
753
- from sovereign_latency_benchmark import run_latency_benchmark, calculate_metrics, save_report
 
 
 
 
754
 
755
- timings = run_latency_benchmark(1000)
756
- metrics = calculate_metrics(timings)
757
- save_report(metrics)
758
 
759
- import run_latency
 
760
 
 
4
  import time
5
  import uuid
6
  import hashlib
7
+ import random
8
+ from statistics import mean
9
  from typing import Any, Dict, List, Tuple
10
 
11
  import gradio as gr
 
17
  from pilot_suite import run_pilot # type: ignore
18
  except Exception:
19
  def run_pilot(*args, **kwargs):
20
+ return {
21
+ "pilot": "not_loaded",
22
+ "note": "pilot_suite not available in this environment"
23
+ }
24
 
25
  try:
26
  from sovereign_ultra_layer import ULTRA_LAYER, UltraConfig # type: ignore
 
28
  except Exception:
29
  class _DummyUltraLayer:
30
  config = type("Cfg", (), {"enabled": False})()
31
+
32
  ULTRA_LAYER = _DummyUltraLayer()
33
 
 
 
 
34
  try:
35
+ from sovereign_authority_gate import AuthorityGate # type: ignore
36
+ except Exception:
37
  AuthorityGate = None # type: ignore
38
 
39
+
40
  # ---------------------------------------------------------------------
41
  # Core identifiers / constants
42
  # ---------------------------------------------------------------------
 
48
  FINGERPRINT_FILE = "sovereign_fingerprint.json"
49
  LINEAGE_FILE = "sovereign_lineage.json"
50
  CONFORMANCE_REPORT_FILE = "conformance_report.json"
 
51
  DNA_STATE_FILE = "sovereign_cognitive_dna_state.json"
52
+ LATENCY_REPORT_FILE = "latency_report.json"
53
+
54
 
55
  # ---------------------------------------------------------------------
56
  # Helpers
 
58
  def _utc_now_iso() -> str:
59
  return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
60
 
61
+
62
  def _sha256_hex(data: str) -> str:
63
  return hashlib.sha256(data.encode("utf-8")).hexdigest()
64
 
65
+
66
  def _ensure_file(path: str) -> None:
67
  if not os.path.exists(path):
68
  with open(path, "w", encoding="utf-8") as f:
69
  f.write("")
70
 
71
+
72
  def _safe_json_load(path: str) -> Dict[str, Any]:
73
  try:
74
  if not os.path.exists(path):
 
78
  except Exception:
79
  return {}
80
 
81
+
82
  def _safe_json_dump(path: str, payload: Any) -> None:
83
  with open(path, "w", encoding="utf-8") as f:
84
  json.dump(payload, f, ensure_ascii=False, indent=2)
85
 
86
+
87
  def _safe_load(path: str) -> Dict[str, Any]:
88
  return _safe_json_load(path)
89
 
90
+
91
  def _safe_dump(path: str, obj: Any) -> None:
92
  _safe_json_dump(path, obj)
93
 
94
+
95
  def _norm_tags(data_tags: Any) -> List[str]:
96
  if isinstance(data_tags, list):
97
  return [str(x).strip().lower() for x in data_tags if str(x).strip()]
 
99
  return [t.strip().lower() for t in data_tags.split(",") if t.strip()]
100
  return []
101
 
102
+
103
  def _risk_score(risk_level: str) -> int:
104
+ mapping = {"low": 1, "medium": 2, "high": 3, "critical": 4}
105
+ return mapping.get((risk_level or "medium").strip().lower(), 2)
106
+
107
+
108
+ # ---------------------------------------------------------------------
109
+ # Built-in latency benchmark
110
+ # ---------------------------------------------------------------------
111
+ def run_latency_benchmark(n: int = 1000) -> List[float]:
112
+ timings: List[float] = []
113
+
114
+ for _ in range(max(1, int(n))):
115
+ start = time.time()
116
+ time.sleep(random.uniform(0.001, 0.005))
117
+ end = time.time()
118
+ timings.append((end - start) * 1000.0)
119
+
120
+ return timings
121
+
122
+
123
+ def calculate_metrics(timings: List[float]) -> Dict[str, Any]:
124
+ if not timings:
125
+ return {
126
+ "samples": 0,
127
+ "avg_ms": 0.0,
128
+ "p95_ms": 0.0,
129
+ "p99_ms": 0.0,
130
+ "min_ms": 0.0,
131
+ "max_ms": 0.0,
132
+ }
133
+
134
+ sorted_times = sorted(timings)
135
+ p95_index = min(len(sorted_times) - 1, int(len(sorted_times) * 0.95))
136
+ p99_index = min(len(sorted_times) - 1, int(len(sorted_times) * 0.99))
137
+
138
+ return {
139
+ "samples": len(sorted_times),
140
+ "avg_ms": round(mean(sorted_times), 3),
141
+ "p95_ms": round(sorted_times[p95_index], 3),
142
+ "p99_ms": round(sorted_times[p99_index], 3),
143
+ "min_ms": round(sorted_times[0], 3),
144
+ "max_ms": round(sorted_times[-1], 3),
145
+ }
146
+
147
+
148
+ def save_latency_report(metrics: Dict[str, Any], path: str = LATENCY_REPORT_FILE) -> str:
149
+ payload = {
150
+ "report_id": str(uuid.uuid4()),
151
+ "generated_at": _utc_now_iso(),
152
+ "engine": ENGINE_NAME,
153
+ "version": SOVEREIGN_VERSION,
154
+ "metrics": metrics,
155
+ }
156
+ _safe_json_dump(path, payload)
157
+ return path
158
+
159
+
160
+ def run_latency_ui(samples: int) -> Tuple[str, str]:
161
+ try:
162
+ count = max(1, int(samples))
163
+ except Exception:
164
+ count = 1000
165
+
166
+ timings = run_latency_benchmark(count)
167
+ metrics = calculate_metrics(timings)
168
+ path = save_latency_report(metrics)
169
+
170
+ result = {
171
+ "status": "ok",
172
+ "generated_at": _utc_now_iso(),
173
+ "engine": ENGINE_NAME,
174
+ "metrics": metrics,
175
+ "report_file": path,
176
+ }
177
+ return json.dumps(result, indent=2, ensure_ascii=False), path
178
+
179
 
180
  # ---------------------------------------------------------------------
181
  # 7-LAYER SOVEREIGN COGNITION (EMBEDDED)
 
189
  ]
190
 
191
  def predict(self, payload: Dict[str, Any]) -> Dict[str, Any]:
192
+ notes = payload.get("notes") or ""
193
  tags = _norm_tags(payload.get("data_tags"))
194
  risk = (payload.get("risk_level") or "medium").lower()
195
 
 
199
  score += _risk_score(risk) * 10
200
  signals.append(f"declared_risk={risk}")
201
 
202
+ high_value = {
203
+ "pii", "secrets", "keys", "payments",
204
+ "banking", "customer_chat", "production"
205
+ }
206
  hv_hits = sorted(list(set(tags) & high_value))
207
  if hv_hits:
208
  score += 12 + 3 * len(hv_hits)
 
226
  "ife_score": int(score),
227
  }
228
 
229
+
230
  class CognitiveDNAFingerprinting:
231
  # Layer 2
232
  def __init__(self, state_file: str = DNA_STATE_FILE):
 
247
  }
248
 
249
  risk = _risk_score(payload.get("risk_level") or "medium")
250
+ note_len = float(len(payload.get("notes") or ""))
251
  tag_count = float(len(_norm_tags(payload.get("data_tags"))))
252
 
253
  drift = 0.0
 
280
  },
281
  }
282
 
283
+
284
  class DeceptiveRealityFabric:
285
  # Layer 3
286
  def simulate(self, payload: Dict[str, Any]) -> Dict[str, Any]:
 
292
  "note": "Routed into simulated execution layer (demo).",
293
  }
294
 
295
+
296
  class CausalityLock:
297
  # Layer 4
298
  def validate(self, payload: Dict[str, Any]) -> Dict[str, Any]:
 
310
  "policy": "min_justification_for_high_risk",
311
  }
312
 
313
+
314
  class EphemeralExecutionSurfaces:
315
  # Layer 5
316
  def spawn(self, ttl_seconds: int = 45) -> Dict[str, Any]:
 
319
  "surface_token": token,
320
  "ttl_seconds": int(ttl_seconds),
321
  "spawned_at": _utc_now_iso(),
322
+ "expires_at": time.strftime(
323
+ "%Y-%m-%dT%H:%M:%SZ",
324
+ time.gmtime(time.time() + ttl_seconds)
325
+ ),
326
  }
327
 
328
+
329
  class CognitiveLoadDefense:
330
  # Layer 6 — default OFF to avoid slowing the system
331
  def apply(self, predicted_intent: bool, risk_level: str) -> Dict[str, Any]:
 
334
 
335
  risk = (risk_level or "medium").lower()
336
  delay_ms = 0
337
+
338
  if predicted_intent and risk in ("high", "critical"):
339
  delay_ms = 220
340
  elif predicted_intent:
 
345
 
346
  return {"delay_ms": int(delay_ms), "applied": delay_ms > 0}
347
 
348
+
349
  class UnverifiableTruthLayer:
350
  # Layer 7
351
  def seal(self, data: str, fingerprint: str = "") -> Dict[str, Any]:
 
358
  "note": "Set SOVEREIGN_SEAL_KEY in HF Secrets to make seals externally verifiable.",
359
  }
360
 
361
+
362
  class SovereignCognitionLayer:
363
  def __init__(self):
364
  self.ife = IntentForecastingEngine()
 
375
  dna = self.dna.update_and_verify(agent_id=agent_id, payload=payload)
376
  caus = self.causality.validate(payload)
377
  surface = self.ephemeral.spawn(ttl_seconds=45)
378
+ cld = self.cld.apply(
379
+ ife["predicted_attack_intent"],
380
+ payload.get("risk_level") or "medium"
381
+ )
382
 
383
  reasons: List[str] = []
384
  action = "allow"
 
402
  ensure_ascii=False,
403
  sort_keys=True,
404
  )
405
+ sealed = self.truth.seal(
406
+ seal_input,
407
+ fingerprint=str(payload.get("fingerprint") or "")
408
+ )
409
 
410
  return {
411
  "decision_id": str(uuid.uuid4()),
 
416
  "layers": {
417
  "ife": ife,
418
  "dna": dna,
419
+ "deception": self.deception.simulate(payload) if action == "deceive" else {
420
+ "deception_engaged": False
421
+ },
422
  "causality": caus,
423
  "ephemeral_surface": surface,
424
  "cognitive_load_defense": cld,
 
426
  },
427
  }
428
 
429
+
430
  COGNITION = SovereignCognitionLayer()
431
 
432
+
433
  # ---------------------------------------------------------------------
434
  # Minimal core logic (self-contained for the demo Space)
435
  # ---------------------------------------------------------------------
 
453
  _safe_json_dump(self.output, payload)
454
  return payload
455
 
456
+
457
  class SovereignLineage:
458
  def __init__(self, output: str = LINEAGE_FILE):
459
  self.output = output
 
470
  ) -> Dict[str, Any]:
471
  issued_at = _utc_now_iso()
472
  record_id = str(uuid.uuid4())
473
+
474
  base = {
475
  "record_id": record_id,
476
  "issued_at": issued_at,
 
484
  "version": SOVEREIGN_VERSION,
485
  "authority": AUTHORITY_NAME,
486
  }
487
+
488
+ integrity = _sha256_hex(
489
+ json.dumps(base, sort_keys=True, ensure_ascii=False)
490
+ )
491
  payload = {**base, "integrity_hash": integrity}
492
  _safe_json_dump(self.output, payload)
493
  return payload
494
 
495
+
496
  def verify_lineage_record(lineage: Dict[str, Any]) -> bool:
497
  try:
498
  integrity_hash = lineage.get("integrity_hash", "")
499
  clone = dict(lineage)
500
  clone.pop("integrity_hash", None)
501
+ expected = _sha256_hex(
502
+ json.dumps(clone, sort_keys=True, ensure_ascii=False)
503
+ )
504
  return expected == integrity_hash
505
  except Exception:
506
  return False
507
 
508
+
509
  def generate_access_key() -> str:
510
  return _sha256_hex(f"demo-access|{uuid.uuid4()}|{_utc_now_iso()}")[:32]
511
 
512
+
513
  # ---------------------------------------------------------------------
514
  # Central audit log
515
  # ---------------------------------------------------------------------
 
536
  "timestamp": ts,
537
  "engine": engine_name,
538
  "event_type": event_type,
539
+ "outcome": outcome,
540
  "parent_model": parent_model or "unknown",
541
  "model_version": model_version or "v1",
542
  "data_tags": [t.strip() for t in (data_tags or "").split(",") if t.strip()],
543
  "risk_level": risk_level or "medium",
544
  "notes": notes or "",
545
  "access_key_present": bool(access_key),
546
+ "ultra_layer_enabled": bool(
547
+ getattr(ULTRA_LAYER, "config", None)
548
+ and getattr(ULTRA_LAYER.config, "enabled", False)
549
+ ),
550
  "version": SOVEREIGN_VERSION,
551
  "authority_name": AUTHORITY_NAME,
552
  "authority_bundle": authority_bundle or {},
 
558
 
559
  return event
560
 
561
+
562
  def read_audit_log_tail(limit: int = 50) -> List[Dict[str, Any]]:
563
  try:
564
  if not os.path.exists(AUDIT_LOG_FILE):
565
  return []
566
+
567
  with open(AUDIT_LOG_FILE, "r", encoding="utf-8") as f:
568
  lines = f.readlines()
569
+
570
+ tail = lines[-max(1, int(limit)):]
571
  out: List[Dict[str, Any]] = []
572
+
573
  for ln in tail:
574
  ln = ln.strip()
575
  if not ln:
 
578
  out.append(json.loads(ln))
579
  except Exception:
580
  continue
581
+
582
  return out
583
  except Exception:
584
  return []
585
 
586
+
587
  def generate_conformance_report() -> Tuple[Dict[str, Any], str]:
588
  fp = _safe_json_load(FINGERPRINT_FILE)
589
  lineage = _safe_json_load(LINEAGE_FILE)
 
602
  "recent_event_count": len(recent_events),
603
  },
604
  "controls": [
605
+ {
606
+ "control": "Audit Logging",
607
+ "status": "present" if os.path.exists(AUDIT_LOG_FILE) else "missing"
608
+ },
609
+ {
610
+ "control": "Fingerprint Issuance",
611
+ "status": "present" if bool(fp) else "missing"
612
+ },
613
+ {
614
+ "control": "Lineage Record",
615
+ "status": "present" if bool(lineage) else "missing"
616
+ },
617
+ {
618
+ "control": "Integrity Check",
619
+ "status": "pass" if (lineage and verify_lineage_record(lineage)) else "fail"
620
+ },
621
+ {
622
+ "control": "7-Layer Cognition Runtime",
623
+ "status": "present"
624
+ },
625
+ {
626
+ "control": "Authority Gate (Allow/Freeze/Block)",
627
+ "status": "present" if AuthorityGate else "missing"
628
+ },
629
  ],
630
  "notes": "Demo conformance report for governance evidence packaging.",
631
  }
 
633
  _safe_json_dump(CONFORMANCE_REPORT_FILE, report)
634
  return report, CONFORMANCE_REPORT_FILE
635
 
636
+
637
  # ---------------------------------------------------------------------
638
+ # Authority Gate instance
639
  # ---------------------------------------------------------------------
640
  GATE = None
641
  if AuthorityGate:
642
+ try:
643
+ GATE = AuthorityGate(
644
+ engine_name=ENGINE_NAME,
645
+ version=SOVEREIGN_VERSION,
646
+ authority_name=AUTHORITY_NAME,
647
+ audit_log_file=AUDIT_LOG_FILE,
648
+ )
649
+ except Exception:
650
+ GATE = None
651
+
652
 
653
  # ---------------------------------------------------------------------
654
  # UI-bound functions
655
  # ---------------------------------------------------------------------
656
+ def run_sentinel(
657
+ engine_name,
658
+ parent_model,
659
+ model_version,
660
+ data_tags,
661
+ risk_level,
662
+ notes,
663
+ access_key,
664
+ delegation_token,
665
+ ):
666
  engine_name = engine_name or ENGINE_NAME
667
 
668
  payload = {
 
675
  "access_key_present": bool(access_key),
676
  }
677
 
678
+ # Fallback: cognition-only if gate module is missing
679
  if not GATE:
680
  decision = COGNITION.evaluate(payload)
681
  outcome = decision["action"]
682
+
683
+ merged_notes = (
684
+ f"{notes}\n\n[SOVEREIGN_DECISION]\n"
685
+ f"{json.dumps(decision, ensure_ascii=False)}"
686
+ )
687
+
688
  event = log_audit_event(
689
  engine_name=engine_name,
690
  parent_model=parent_model,
 
695
  event_type="sentinel_run",
696
  outcome=outcome,
697
  access_key=access_key,
698
+ authority_bundle={
699
+ "mode": "cognition_only",
700
+ "decision": outcome,
701
+ "reason": "gate_missing",
702
+ },
703
+ execution={
704
+ "executed": False,
705
+ "detail": {"note": "gate missing, execution disabled"}
706
+ },
707
  )
 
708
 
709
+ return json.dumps(
710
+ {"audit_event": event, "sovereign_decision": decision},
711
+ indent=2,
712
+ ensure_ascii=False,
713
+ )
714
+
715
+ # Unilateral Freeze Doctrine: authority gate runs BEFORE execution
716
+ gate = GATE.precheck(
717
+ payload,
718
+ cognition_eval=COGNITION.evaluate,
719
+ delegation_token=delegation_token or "",
720
+ )
721
  authority_decision = gate["decision"] # ALLOW/FREEZE/BLOCK
722
 
723
+ execution_info: Dict[str, Any] = {"executed": False, "detail": None}
724
  if authority_decision == "ALLOW":
 
725
  try:
726
+ execution_info = {
727
+ "executed": True,
728
+ "detail": run_pilot(payload)
729
+ }
730
  except Exception as e:
731
+ execution_info = {
732
+ "executed": False,
733
+ "detail": {"error": str(e)}
734
+ }
735
 
736
  authority_bundle = {
737
  "decision": authority_decision,
 
743
  "cognition": gate.get("cognition"),
744
  }
745
 
746
+ notes_short = (
747
+ f"{notes}\n\n[SOVEREIGN_AUTHORITY]\n"
748
+ f"{authority_decision} | {gate.get('reason')}"
749
+ )
750
+
751
  event = log_audit_event(
752
  engine_name=engine_name,
753
  parent_model=parent_model,
 
763
  )
764
 
765
  return json.dumps(
766
+ {
767
+ "audit_event": event,
768
+ "authority_gate": authority_bundle,
769
+ "execution": execution_info,
770
+ },
771
  indent=2,
772
+ ensure_ascii=False,
773
  )
774
 
775
+
776
+ def run_fingerprint_and_lineage(
777
+ engine_name,
778
+ parent_model,
779
+ model_version,
780
+ data_tags,
781
+ risk_level,
782
+ notes,
783
+ ):
784
  engine_name = engine_name or ENGINE_NAME
785
 
786
  fp = SovereignFingerprint(engine=engine_name).issue()
 
802
  }
803
  return json.dumps(combined, indent=2, ensure_ascii=False)
804
 
805
+
806
  def show_audit_log(limit):
807
  try:
808
  limit_int = int(limit)
809
  except Exception:
810
  limit_int = 50
811
+
812
  events = read_audit_log_tail(limit_int)
813
  return json.dumps(events, indent=2, ensure_ascii=False)
814
 
815
+
816
  def build_conformance_report():
817
  report, path = generate_conformance_report()
818
  return json.dumps(report, indent=2, ensure_ascii=False), path
819
 
820
+
821
  # ---------------------------------------------------------------------
822
  # Gradio UI
823
  # ---------------------------------------------------------------------
 
854
  gr.Markdown("### Run Sovereign Sentinel with Authority Gate and log an event.")
855
 
856
  with gr.Row():
857
+ engine_name = gr.Textbox(
858
+ label="Engine name",
859
+ value=ENGINE_NAME,
860
+ interactive=True
861
+ )
862
+ parent_model = gr.Textbox(
863
+ label="Parent model / agent id",
864
+ placeholder="gpt-4o, llama3-70b, agent-alpha, etc."
865
+ )
866
 
867
  with gr.Row():
868
+ model_version = gr.Textbox(
869
+ label="Model version / build id",
870
+ value="v1"
871
+ )
872
+ data_tags = gr.Textbox(
873
+ label="Data tags (comma-separated)",
874
+ value="pii, customer_chat, production"
875
+ )
876
 
877
  with gr.Row():
878
+ risk_level = gr.Dropdown(
879
+ label="Risk level (declared)",
880
+ choices=["low", "medium", "high", "critical"],
881
+ value="medium"
882
+ )
883
+ notes = gr.Textbox(
884
+ label="Notes / context",
885
+ value="Demo sentinel run from Hugging Face Space.",
886
+ lines=3
887
+ )
888
 
889
  with gr.Row():
890
+ access_key = gr.Textbox(
891
+ label="Access key (optional)",
892
+ placeholder="Paste or generate a demo access key"
893
+ )
894
+ gen_access_btn = gr.Button(
895
+ "Generate demo access key",
896
+ variant="secondary"
897
+ )
898
+
899
+ gen_access_btn.click(
900
+ fn=generate_access_key,
901
+ inputs=None,
902
+ outputs=access_key
903
+ )
904
 
905
  delegation_token = gr.Textbox(
906
  label="Delegation token (optional / customer-signed)",
907
  placeholder="Only required if SOV_REQUIRE_DELEGATION=1",
908
  )
909
 
910
+ run_btn = gr.Button(
911
+ "Run Sentinel (Authority + 7-layer) & Log Event",
912
+ variant="primary"
913
+ )
914
+ result_json = gr.Code(
915
+ label="Result (Audit + Authority + Execution)",
916
+ language="json"
917
+ )
918
 
919
  run_btn.click(
920
  fn=run_sentinel,
921
+ inputs=[
922
+ engine_name,
923
+ parent_model,
924
+ model_version,
925
+ data_tags,
926
+ risk_level,
927
+ notes,
928
+ access_key,
929
+ delegation_token,
930
+ ],
931
  outputs=result_json,
932
  )
933
 
 
936
  gr.Markdown("### Issue a fingerprint and lineage record for this engine.")
937
 
938
  with gr.Row():
939
+ fp_engine_name = gr.Textbox(
940
+ label="Engine name",
941
+ value=ENGINE_NAME
942
+ )
943
+ fp_parent_model = gr.Textbox(
944
+ label="Parent model",
945
+ placeholder="gpt-4o, llama3-70b, etc."
946
+ )
947
 
948
  with gr.Row():
949
+ fp_model_version = gr.Textbox(
950
+ label="Model version / build id",
951
+ value="v1"
952
+ )
953
+ fp_data_tags = gr.Textbox(
954
+ label="Data tags (comma-separated)",
955
+ value="pii, customer_chat, production"
956
+ )
957
 
958
  with gr.Row():
959
+ fp_risk_level = gr.Dropdown(
960
+ label="Risk level",
961
+ choices=["low", "medium", "high", "critical"],
962
+ value="medium"
963
+ )
964
+ fp_notes = gr.Textbox(
965
+ label="Notes / context",
966
+ lines=3
967
+ )
968
+
969
+ fp_btn = gr.Button(
970
+ "Issue Fingerprint + Lineage",
971
+ variant="primary"
972
+ )
973
+ fp_output = gr.Code(
974
+ label="Fingerprint + Lineage (JSON)",
975
+ language="json"
976
+ )
977
 
978
  fp_btn.click(
979
  fn=run_fingerprint_and_lineage,
980
+ inputs=[
981
+ fp_engine_name,
982
+ fp_parent_model,
983
+ fp_model_version,
984
+ fp_data_tags,
985
+ fp_risk_level,
986
+ fp_notes,
987
+ ],
988
  outputs=fp_output,
989
  )
990
 
 
992
  with gr.Tab("Audit Log & Trust"):
993
  gr.Markdown("### View the tail of the central Sovereign audit log.")
994
 
995
+ log_limit = gr.Slider(
996
+ label="Number of recent events to show",
997
+ minimum=1,
998
+ maximum=200,
999
+ value=50,
1000
+ step=1
1001
+ )
1002
+ show_log_btn = gr.Button(
1003
+ "Refresh audit log view",
1004
+ variant="secondary"
1005
+ )
1006
+ log_view = gr.Code(
1007
+ label="Audit log tail (JSON list)",
1008
+ language="json"
1009
+ )
1010
 
1011
+ show_log_btn.click(
1012
+ fn=show_audit_log,
1013
+ inputs=log_limit,
1014
+ outputs=log_view
1015
+ )
1016
 
1017
  # Conformance Report tab
1018
  with gr.Tab("Conformance / Governance Report"):
1019
  gr.Markdown("### Generate a simple conformance / governance-style JSON report.")
1020
 
1021
+ gen_report_btn = gr.Button(
1022
+ "Generate Conformance Report (JSON)",
1023
+ variant="secondary"
1024
+ )
1025
+ report_json_out = gr.Code(
1026
+ label="Conformance Report (JSON)",
1027
+ language="json"
1028
+ )
1029
+ report_file_out = gr.File(
1030
+ label="Download conformance_report.json"
1031
+ )
1032
 
1033
  gen_report_btn.click(
1034
  fn=build_conformance_report,
 
1036
  outputs=[report_json_out, report_file_out],
1037
  )
1038
 
1039
+ # Latency tab
1040
+ with gr.Tab("Latency Benchmark"):
1041
+ gr.Markdown("### Run a clean built-in latency benchmark and save a JSON report.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1042
 
1043
+ latency_samples = gr.Slider(
1044
+ label="Number of samples",
1045
+ minimum=10,
1046
+ maximum=5000,
1047
+ value=1000,
1048
+ step=10
1049
+ )
1050
+ latency_btn = gr.Button(
1051
+ "Run Latency Benchmark",
1052
+ variant="primary"
1053
+ )
1054
+ latency_json = gr.Code(
1055
+ label="Latency Metrics (JSON)",
1056
+ language="json"
1057
+ )
1058
+ latency_file = gr.File(
1059
+ label="Download latency_report.json"
1060
+ )
1061
 
1062
+ latency_btn.click(
1063
+ fn=run_latency_ui,
1064
+ inputs=latency_samples,
1065
+ outputs=[latency_json, latency_file],
1066
+ )
1067
 
 
 
 
1068
 
1069
+ if __name__ == "__main__":
1070
+ demo.launch()
1071