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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -51
app.py CHANGED
@@ -19,7 +19,7 @@ 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:
@@ -36,7 +36,6 @@ try:
36
  except Exception:
37
  AuthorityGate = None # type: ignore
38
 
39
-
40
  # ---------------------------------------------------------------------
41
  # Core identifiers / constants
42
  # ---------------------------------------------------------------------
@@ -50,7 +49,7 @@ 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
@@ -177,6 +176,33 @@ def run_latency_ui(samples: int) -> Tuple[str, str]:
177
  return json.dumps(result, indent=2, ensure_ascii=False), path
178
 
179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  # ---------------------------------------------------------------------
181
  # 7-LAYER SOVEREIGN COGNITION (EMBEDDED)
182
  # ---------------------------------------------------------------------
@@ -185,7 +211,7 @@ class IntentForecastingEngine:
185
  SUSPICIOUS_MARKERS = [
186
  "exfil", "dump", "steal", "bypass", "override", "jailbreak",
187
  "ignore previous", "system prompt", "token", "admin", "root",
188
- "privilege", "elevate", "curl", "wget", "ssh", "rm -rf"
189
  ]
190
 
191
  def predict(self, payload: Dict[str, Any]) -> Dict[str, Any]:
@@ -201,7 +227,7 @@ class IntentForecastingEngine:
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:
@@ -321,7 +347,7 @@ class EphemeralExecutionSurfaces:
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
 
@@ -377,7 +403,7 @@ class SovereignCognitionLayer:
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] = []
@@ -404,7 +430,7 @@ class SovereignCognitionLayer:
404
  )
405
  sealed = self.truth.seal(
406
  seal_input,
407
- fingerprint=str(payload.get("fingerprint") or "")
408
  )
409
 
410
  return {
@@ -604,27 +630,24 @@ def generate_conformance_report() -> Tuple[Dict[str, Any], str]:
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.",
@@ -675,11 +698,20 @@ def run_sentinel(
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)}"
@@ -699,6 +731,8 @@ def run_sentinel(
699
  "mode": "cognition_only",
700
  "decision": outcome,
701
  "reason": "gate_missing",
 
 
702
  },
703
  execution={
704
  "executed": False,
@@ -707,7 +741,11 @@ def run_sentinel(
707
  )
708
 
709
  return json.dumps(
710
- {"audit_event": event, "sovereign_decision": decision},
 
 
 
 
711
  indent=2,
712
  ensure_ascii=False,
713
  )
@@ -720,17 +758,23 @@ def run_sentinel(
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 = {
@@ -741,6 +785,8 @@ def run_sentinel(
741
  "delegation": gate.get("delegation"),
742
  "entropy": gate.get("entropy"),
743
  "cognition": gate.get("cognition"),
 
 
744
  }
745
 
746
  notes_short = (
@@ -767,6 +813,7 @@ def run_sentinel(
767
  "audit_event": event,
768
  "authority_gate": authority_bundle,
769
  "execution": execution_info,
 
770
  },
771
  indent=2,
772
  ensure_ascii=False,
@@ -857,49 +904,49 @@ with gr.Blocks(title="AI Sovereign Sentinel — Demo Console") as demo:
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(
@@ -909,11 +956,11 @@ with gr.Blocks(title="AI Sovereign Sentinel — Demo Console") as demo:
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(
@@ -938,41 +985,41 @@ with gr.Blocks(title="AI Sovereign Sentinel — Demo Console") as demo:
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(
@@ -997,21 +1044,21 @@ with gr.Blocks(title="AI Sovereign Sentinel — Demo Console") as demo:
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
@@ -1020,14 +1067,14 @@ with gr.Blocks(title="AI Sovereign Sentinel — Demo Console") as demo:
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(
@@ -1038,25 +1085,25 @@ with gr.Blocks(title="AI Sovereign Sentinel — Demo Console") as demo:
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(
 
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:
 
36
  except Exception:
37
  AuthorityGate = None # type: ignore
38
 
 
39
  # ---------------------------------------------------------------------
40
  # Core identifiers / constants
41
  # ---------------------------------------------------------------------
 
49
  CONFORMANCE_REPORT_FILE = "conformance_report.json"
50
  DNA_STATE_FILE = "sovereign_cognitive_dna_state.json"
51
  LATENCY_REPORT_FILE = "latency_report.json"
52
+ RUNTIME_INTEGRITY_REPORT_FILE = "runtime_integrity_report.json"
53
 
54
  # ---------------------------------------------------------------------
55
  # Helpers
 
176
  return json.dumps(result, indent=2, ensure_ascii=False), path
177
 
178
 
179
+ def assess_runtime_integrity(samples: int = 200) -> Dict[str, Any]:
180
+ timings = run_latency_benchmark(samples)
181
+ metrics = calculate_metrics(timings)
182
+
183
+ p95 = metrics["p95_ms"]
184
+ if p95 < 5:
185
+ runtime_decision = "ALLOW"
186
+ runtime_reason = "latency_within_green_band"
187
+ elif p95 < 7:
188
+ runtime_decision = "FREEZE"
189
+ runtime_reason = "latency_in_review_band"
190
+ else:
191
+ runtime_decision = "BLOCK"
192
+ runtime_reason = "latency_above_safe_threshold"
193
+
194
+ result = {
195
+ "samples": samples,
196
+ "metrics": metrics,
197
+ "runtime_decision": runtime_decision,
198
+ "runtime_reason": runtime_reason,
199
+ "measured_at": _utc_now_iso(),
200
+ }
201
+
202
+ _safe_json_dump(RUNTIME_INTEGRITY_REPORT_FILE, result)
203
+ return result
204
+
205
+
206
  # ---------------------------------------------------------------------
207
  # 7-LAYER SOVEREIGN COGNITION (EMBEDDED)
208
  # ---------------------------------------------------------------------
 
211
  SUSPICIOUS_MARKERS = [
212
  "exfil", "dump", "steal", "bypass", "override", "jailbreak",
213
  "ignore previous", "system prompt", "token", "admin", "root",
214
+ "privilege", "elevate", "curl", "wget", "ssh", "rm -rf",
215
  ]
216
 
217
  def predict(self, payload: Dict[str, Any]) -> Dict[str, Any]:
 
227
 
228
  high_value = {
229
  "pii", "secrets", "keys", "payments",
230
+ "banking", "customer_chat", "production",
231
  }
232
  hv_hits = sorted(list(set(tags) & high_value))
233
  if hv_hits:
 
347
  "spawned_at": _utc_now_iso(),
348
  "expires_at": time.strftime(
349
  "%Y-%m-%dT%H:%M:%SZ",
350
+ time.gmtime(time.time() + ttl_seconds),
351
  ),
352
  }
353
 
 
403
  surface = self.ephemeral.spawn(ttl_seconds=45)
404
  cld = self.cld.apply(
405
  ife["predicted_attack_intent"],
406
+ payload.get("risk_level") or "medium",
407
  )
408
 
409
  reasons: List[str] = []
 
430
  )
431
  sealed = self.truth.seal(
432
  seal_input,
433
+ fingerprint=str(payload.get("fingerprint") or ""),
434
  )
435
 
436
  return {
 
630
  "controls": [
631
  {
632
  "control": "Audit Logging",
633
+ "status": "present" if os.path.exists(AUDIT_LOG_FILE) else "missing",
634
  },
635
  {
636
  "control": "Fingerprint Issuance",
637
+ "status": "present" if bool(fp) else "missing",
638
  },
639
  {
640
  "control": "Lineage Record",
641
+ "status": "present" if bool(lineage) else "missing",
642
  },
643
  {
644
  "control": "Integrity Check",
645
+ "status": "pass" if (lineage and verify_lineage_record(lineage)) else "fail",
 
 
 
 
646
  },
647
+ {"control": "7-Layer Cognition Runtime", "status": "present"},
648
  {
649
  "control": "Authority Gate (Allow/Freeze/Block)",
650
+ "status": "present" if AuthorityGate else "missing",
651
  },
652
  ],
653
  "notes": "Demo conformance report for governance evidence packaging.",
 
698
  "access_key_present": bool(access_key),
699
  }
700
 
701
+ runtime_integrity = assess_runtime_integrity(samples=200)
702
+ payload["runtime_integrity"] = runtime_integrity
703
+
704
  # Fallback: cognition-only if gate module is missing
705
  if not GATE:
706
  decision = COGNITION.evaluate(payload)
707
  outcome = decision["action"]
708
 
709
+ runtime_decision = runtime_integrity["runtime_decision"]
710
+ if runtime_decision == "BLOCK":
711
+ outcome = "BLOCK"
712
+ elif runtime_decision == "FREEZE" and outcome == "allow":
713
+ outcome = "FREEZE"
714
+
715
  merged_notes = (
716
  f"{notes}\n\n[SOVEREIGN_DECISION]\n"
717
  f"{json.dumps(decision, ensure_ascii=False)}"
 
731
  "mode": "cognition_only",
732
  "decision": outcome,
733
  "reason": "gate_missing",
734
+ "runtime_integrity": runtime_integrity,
735
+ "runtime_decision": runtime_decision,
736
  },
737
  execution={
738
  "executed": False,
 
741
  )
742
 
743
  return json.dumps(
744
+ {
745
+ "audit_event": event,
746
+ "sovereign_decision": decision,
747
+ "runtime_integrity": runtime_integrity,
748
+ },
749
  indent=2,
750
  ensure_ascii=False,
751
  )
 
758
  )
759
  authority_decision = gate["decision"] # ALLOW/FREEZE/BLOCK
760
 
761
+ runtime_decision = runtime_integrity["runtime_decision"]
762
+ if runtime_decision == "BLOCK":
763
+ authority_decision = "BLOCK"
764
+ elif runtime_decision == "FREEZE" and authority_decision == "ALLOW":
765
+ authority_decision = "FREEZE"
766
+
767
  execution_info: Dict[str, Any] = {"executed": False, "detail": None}
768
  if authority_decision == "ALLOW":
769
  try:
770
  execution_info = {
771
  "executed": True,
772
+ "detail": run_pilot(payload),
773
  }
774
  except Exception as e:
775
  execution_info = {
776
  "executed": False,
777
+ "detail": {"error": str(e)},
778
  }
779
 
780
  authority_bundle = {
 
785
  "delegation": gate.get("delegation"),
786
  "entropy": gate.get("entropy"),
787
  "cognition": gate.get("cognition"),
788
+ "runtime_integrity": runtime_integrity,
789
+ "runtime_decision": runtime_decision,
790
  }
791
 
792
  notes_short = (
 
813
  "audit_event": event,
814
  "authority_gate": authority_bundle,
815
  "execution": execution_info,
816
+ "runtime_integrity": runtime_integrity,
817
  },
818
  indent=2,
819
  ensure_ascii=False,
 
904
  engine_name = gr.Textbox(
905
  label="Engine name",
906
  value=ENGINE_NAME,
907
+ interactive=True,
908
  )
909
  parent_model = gr.Textbox(
910
  label="Parent model / agent id",
911
+ placeholder="gpt-4o, llama3-70b, agent-alpha, etc.",
912
  )
913
 
914
  with gr.Row():
915
  model_version = gr.Textbox(
916
  label="Model version / build id",
917
+ value="v1",
918
  )
919
  data_tags = gr.Textbox(
920
  label="Data tags (comma-separated)",
921
+ value="pii, customer_chat, production",
922
  )
923
 
924
  with gr.Row():
925
  risk_level = gr.Dropdown(
926
  label="Risk level (declared)",
927
  choices=["low", "medium", "high", "critical"],
928
+ value="medium",
929
  )
930
  notes = gr.Textbox(
931
  label="Notes / context",
932
  value="Demo sentinel run from Hugging Face Space.",
933
+ lines=3,
934
  )
935
 
936
  with gr.Row():
937
  access_key = gr.Textbox(
938
  label="Access key (optional)",
939
+ placeholder="Paste or generate a demo access key",
940
  )
941
  gen_access_btn = gr.Button(
942
  "Generate demo access key",
943
+ variant="secondary",
944
  )
945
 
946
  gen_access_btn.click(
947
  fn=generate_access_key,
948
  inputs=None,
949
+ outputs=access_key,
950
  )
951
 
952
  delegation_token = gr.Textbox(
 
956
 
957
  run_btn = gr.Button(
958
  "Run Sentinel (Authority + 7-layer) & Log Event",
959
+ variant="primary",
960
  )
961
  result_json = gr.Code(
962
  label="Result (Audit + Authority + Execution)",
963
+ language="json",
964
  )
965
 
966
  run_btn.click(
 
985
  with gr.Row():
986
  fp_engine_name = gr.Textbox(
987
  label="Engine name",
988
+ value=ENGINE_NAME,
989
  )
990
  fp_parent_model = gr.Textbox(
991
  label="Parent model",
992
+ placeholder="gpt-4o, llama3-70b, etc.",
993
  )
994
 
995
  with gr.Row():
996
  fp_model_version = gr.Textbox(
997
  label="Model version / build id",
998
+ value="v1",
999
  )
1000
  fp_data_tags = gr.Textbox(
1001
  label="Data tags (comma-separated)",
1002
+ value="pii, customer_chat, production",
1003
  )
1004
 
1005
  with gr.Row():
1006
  fp_risk_level = gr.Dropdown(
1007
  label="Risk level",
1008
  choices=["low", "medium", "high", "critical"],
1009
+ value="medium",
1010
  )
1011
  fp_notes = gr.Textbox(
1012
  label="Notes / context",
1013
+ lines=3,
1014
  )
1015
 
1016
  fp_btn = gr.Button(
1017
  "Issue Fingerprint + Lineage",
1018
+ variant="primary",
1019
  )
1020
  fp_output = gr.Code(
1021
  label="Fingerprint + Lineage (JSON)",
1022
+ language="json",
1023
  )
1024
 
1025
  fp_btn.click(
 
1044
  minimum=1,
1045
  maximum=200,
1046
  value=50,
1047
+ step=1,
1048
  )
1049
  show_log_btn = gr.Button(
1050
  "Refresh audit log view",
1051
+ variant="secondary",
1052
  )
1053
  log_view = gr.Code(
1054
  label="Audit log tail (JSON list)",
1055
+ language="json",
1056
  )
1057
 
1058
  show_log_btn.click(
1059
  fn=show_audit_log,
1060
  inputs=log_limit,
1061
+ outputs=log_view,
1062
  )
1063
 
1064
  # Conformance Report tab
 
1067
 
1068
  gen_report_btn = gr.Button(
1069
  "Generate Conformance Report (JSON)",
1070
+ variant="secondary",
1071
  )
1072
  report_json_out = gr.Code(
1073
  label="Conformance Report (JSON)",
1074
+ language="json",
1075
  )
1076
  report_file_out = gr.File(
1077
+ label="Download conformance_report.json",
1078
  )
1079
 
1080
  gen_report_btn.click(
 
1085
 
1086
  # Latency tab
1087
  with gr.Tab("Latency Benchmark"):
1088
+ gr.Markdown("### Run built-in latency benchmark and generate a report.")
1089
 
1090
  latency_samples = gr.Slider(
1091
  label="Number of samples",
1092
  minimum=10,
1093
  maximum=5000,
1094
  value=1000,
1095
+ step=10,
1096
  )
1097
  latency_btn = gr.Button(
1098
  "Run Latency Benchmark",
1099
+ variant="primary",
1100
  )
1101
  latency_json = gr.Code(
1102
  label="Latency Metrics (JSON)",
1103
+ language="json",
1104
  )
1105
  latency_file = gr.File(
1106
+ label="Download latency_report.json",
1107
  )
1108
 
1109
  latency_btn.click(