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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# sovereign_app_freeze_integration.py
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import uuid
|
| 7 |
+
from datetime import datetime, timezone
|
| 8 |
+
from typing import Any, Dict, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import app as sovereign_app
|
| 11 |
+
from sovereign_freeze_bridge import SovereignFreezeBridge
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _utc_now() -> str:
|
| 15 |
+
return datetime.now(timezone.utc).isoformat()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _norm_text(v: Any) -> str:
|
| 19 |
+
return str(v or "").strip()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _norm_tags(v: Any) -> list[str]:
|
| 23 |
+
if isinstance(v, list):
|
| 24 |
+
return [str(x).strip().lower() for x in v if str(x).strip()]
|
| 25 |
+
if isinstance(v, str):
|
| 26 |
+
return [x.strip().lower() for x in v.split(",") if x.strip()]
|
| 27 |
+
return []
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _build_payload(
|
| 31 |
+
engine_name: str,
|
| 32 |
+
parent_model: str,
|
| 33 |
+
model_version: str,
|
| 34 |
+
data_tags: Any,
|
| 35 |
+
risk_level: str,
|
| 36 |
+
notes: str,
|
| 37 |
+
access_key: str,
|
| 38 |
+
delegation_token: str,
|
| 39 |
+
) -> Dict[str, Any]:
|
| 40 |
+
return {
|
| 41 |
+
"engine": engine_name,
|
| 42 |
+
"engine_name": engine_name,
|
| 43 |
+
"parent_model": parent_model,
|
| 44 |
+
"parent_model_id": parent_model,
|
| 45 |
+
"agent_id": parent_model,
|
| 46 |
+
"model_version": model_version,
|
| 47 |
+
"build_id": model_version,
|
| 48 |
+
"data_tags": _norm_tags(data_tags),
|
| 49 |
+
"risk_level": _norm_text(risk_level).lower() or "medium",
|
| 50 |
+
"notes": _norm_text(notes),
|
| 51 |
+
"access_key_present": bool(_norm_text(access_key)),
|
| 52 |
+
"delegation_token_present": bool(_norm_text(delegation_token)),
|
| 53 |
+
"deployment_env": "production",
|
| 54 |
+
"environment": "production",
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _safe_parse_json(raw: Any) -> Dict[str, Any]:
|
| 59 |
+
if isinstance(raw, dict):
|
| 60 |
+
return raw
|
| 61 |
+
if isinstance(raw, str):
|
| 62 |
+
try:
|
| 63 |
+
parsed = json.loads(raw)
|
| 64 |
+
return parsed if isinstance(parsed, dict) else {"raw": raw}
|
| 65 |
+
except Exception:
|
| 66 |
+
return {"raw": raw}
|
| 67 |
+
return {"raw": raw}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _extract_decision(bundle: Dict[str, Any]) -> str:
|
| 71 |
+
for key in ("decision", "action", "outcome", "authority_decision"):
|
| 72 |
+
v = bundle.get(key)
|
| 73 |
+
if isinstance(v, str) and v.strip():
|
| 74 |
+
return v.strip().upper()
|
| 75 |
+
|
| 76 |
+
auth = bundle.get("authority_gate") or {}
|
| 77 |
+
if isinstance(auth, dict):
|
| 78 |
+
v = auth.get("decision")
|
| 79 |
+
if isinstance(v, str) and v.strip():
|
| 80 |
+
return v.strip().upper()
|
| 81 |
+
|
| 82 |
+
return "UNKNOWN"
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _extract_reason(bundle: Dict[str, Any]) -> str:
|
| 86 |
+
v = bundle.get("reason")
|
| 87 |
+
if isinstance(v, str) and v.strip():
|
| 88 |
+
return v.strip()
|
| 89 |
+
|
| 90 |
+
reasons = bundle.get("reasons")
|
| 91 |
+
if isinstance(reasons, list) and reasons:
|
| 92 |
+
return " | ".join(str(x) for x in reasons[:6])
|
| 93 |
+
|
| 94 |
+
auth = bundle.get("authority_gate") or {}
|
| 95 |
+
if isinstance(auth, dict):
|
| 96 |
+
v = auth.get("reason")
|
| 97 |
+
if isinstance(v, str) and v.strip():
|
| 98 |
+
return v.strip()
|
| 99 |
+
|
| 100 |
+
return "no_explicit_reason"
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _make_override_result(
|
| 104 |
+
payload: Dict[str, Any],
|
| 105 |
+
forced_decision: str,
|
| 106 |
+
reason: str,
|
| 107 |
+
freeze_state: Dict[str, Any],
|
| 108 |
+
) -> Dict[str, Any]:
|
| 109 |
+
decision_id = str(uuid.uuid4())
|
| 110 |
+
ts = _utc_now()
|
| 111 |
+
|
| 112 |
+
audit_event = {
|
| 113 |
+
"event_id": decision_id,
|
| 114 |
+
"timestamp": ts,
|
| 115 |
+
"engine": payload.get("engine"),
|
| 116 |
+
"event_type": "sentinel_run",
|
| 117 |
+
"outcome": forced_decision,
|
| 118 |
+
"parent_model": payload.get("parent_model"),
|
| 119 |
+
"model_version": payload.get("model_version"),
|
| 120 |
+
"data_tags": payload.get("data_tags", []),
|
| 121 |
+
"risk_level": payload.get("risk_level"),
|
| 122 |
+
"notes": f"[FREEZE_OVERRIDE] {reason}",
|
| 123 |
+
"version": getattr(sovereign_app, "SOVEREIGN_VERSION", "unknown"),
|
| 124 |
+
"authority_name": getattr(sovereign_app, "AUTHORITY_NAME", "unknown"),
|
| 125 |
+
"authority_bundle": {
|
| 126 |
+
"decision": forced_decision,
|
| 127 |
+
"reason": reason,
|
| 128 |
+
"proof_type": "proof_of_non_action",
|
| 129 |
+
"freeze_state": freeze_state,
|
| 130 |
+
},
|
| 131 |
+
"execution": {
|
| 132 |
+
"executed": False,
|
| 133 |
+
"detail": {
|
| 134 |
+
"blocked_by_freeze_bridge": True,
|
| 135 |
+
"freeze_state": freeze_state,
|
| 136 |
+
},
|
| 137 |
+
},
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
return {
|
| 141 |
+
"audit_event": audit_event,
|
| 142 |
+
"authority_gate": {
|
| 143 |
+
"decision": forced_decision,
|
| 144 |
+
"reason": reason,
|
| 145 |
+
"proof_type": "proof_of_non_action",
|
| 146 |
+
"freeze_state": freeze_state,
|
| 147 |
+
},
|
| 148 |
+
"execution": {
|
| 149 |
+
"executed": False,
|
| 150 |
+
"detail": {
|
| 151 |
+
"blocked_by_freeze_bridge": True,
|
| 152 |
+
"freeze_state": freeze_state,
|
| 153 |
+
},
|
| 154 |
+
},
|
| 155 |
+
"freeze_bridge": {
|
| 156 |
+
"bridge_status": "pre_execution_override",
|
| 157 |
+
"decision": forced_decision,
|
| 158 |
+
"freeze": freeze_state,
|
| 159 |
+
},
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _persist_override_audit(result: Dict[str, Any]) -> None:
|
| 164 |
+
"""
|
| 165 |
+
Best-effort write into app.py audit log so freeze override is visible centrally.
|
| 166 |
+
"""
|
| 167 |
+
try:
|
| 168 |
+
event = result.get("audit_event")
|
| 169 |
+
if not isinstance(event, dict):
|
| 170 |
+
return
|
| 171 |
+
|
| 172 |
+
fn = getattr(sovereign_app, "log_audit_event", None)
|
| 173 |
+
if callable(fn):
|
| 174 |
+
fn(
|
| 175 |
+
engine_name=event.get("engine", "unknown_engine"),
|
| 176 |
+
parent_model=event.get("parent_model", "unknown_parent"),
|
| 177 |
+
model_version=event.get("model_version", "unknown_version"),
|
| 178 |
+
data_tags=",".join(event.get("data_tags", []) or []),
|
| 179 |
+
risk_level=event.get("risk_level", "medium"),
|
| 180 |
+
notes=event.get("notes", ""),
|
| 181 |
+
event_type=event.get("event_type", "sentinel_run"),
|
| 182 |
+
outcome=event.get("outcome", "FREEZE"),
|
| 183 |
+
access_key="",
|
| 184 |
+
authority_bundle=event.get("authority_bundle", {}),
|
| 185 |
+
execution=event.get("execution", {}),
|
| 186 |
+
)
|
| 187 |
+
except Exception:
|
| 188 |
+
pass
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class SovereignAppFreezeIntegration:
|
| 192 |
+
"""
|
| 193 |
+
Bank-grade freeze integration wrapper around app.run_sentinel.
|
| 194 |
+
|
| 195 |
+
Flow:
|
| 196 |
+
1) build normalized payload
|
| 197 |
+
2) check existing freeze state before execution
|
| 198 |
+
3) if active freeze/escalated block exists => do not execute
|
| 199 |
+
4) otherwise call original app.run_sentinel
|
| 200 |
+
5) parse decision and register freeze if result == FREEZE
|
| 201 |
+
6) return unified JSON result
|
| 202 |
+
"""
|
| 203 |
+
|
| 204 |
+
def __init__(self) -> None:
|
| 205 |
+
self.bridge = SovereignFreezeBridge()
|
| 206 |
+
self.original_run_sentinel = sovereign_app.run_sentinel
|
| 207 |
+
|
| 208 |
+
def _precheck(self, payload: Dict[str, Any]) -> Tuple[bool, Dict[str, Any]]:
|
| 209 |
+
return self.bridge.can_execute(payload)
|
| 210 |
+
|
| 211 |
+
def run(
|
| 212 |
+
self,
|
| 213 |
+
engine_name: str,
|
| 214 |
+
parent_model: str,
|
| 215 |
+
model_version: str,
|
| 216 |
+
data_tags: Any,
|
| 217 |
+
risk_level: str,
|
| 218 |
+
notes: str,
|
| 219 |
+
access_key: str,
|
| 220 |
+
delegation_token: str,
|
| 221 |
+
) -> str:
|
| 222 |
+
payload = _build_payload(
|
| 223 |
+
engine_name=engine_name,
|
| 224 |
+
parent_model=parent_model,
|
| 225 |
+
model_version=model_version,
|
| 226 |
+
data_tags=data_tags,
|
| 227 |
+
risk_level=risk_level,
|
| 228 |
+
notes=notes,
|
| 229 |
+
access_key=access_key,
|
| 230 |
+
delegation_token=delegation_token,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
# 1) Pre-execution freeze check
|
| 234 |
+
can_exec, state = self._precheck(payload)
|
| 235 |
+
if not can_exec:
|
| 236 |
+
forced = "BLOCK" if state.get("state") == "escalated_block" else "FREEZE"
|
| 237 |
+
result = _make_override_result(
|
| 238 |
+
payload=payload,
|
| 239 |
+
forced_decision=forced,
|
| 240 |
+
reason=state.get("reason", "freeze_active"),
|
| 241 |
+
freeze_state=state,
|
| 242 |
+
)
|
| 243 |
+
_persist_override_audit(result)
|
| 244 |
+
return json.dumps(result, indent=2, ensure_ascii=False)
|
| 245 |
+
|
| 246 |
+
# 2) Normal app execution
|
| 247 |
+
raw = self.original_run_sentinel(
|
| 248 |
+
engine_name,
|
| 249 |
+
parent_model,
|
| 250 |
+
model_version,
|
| 251 |
+
data_tags if isinstance(data_tags, str) else ",".join(_norm_tags(data_tags)),
|
| 252 |
+
risk_level,
|
| 253 |
+
notes,
|
| 254 |
+
access_key,
|
| 255 |
+
delegation_token,
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
parsed = _safe_parse_json(raw)
|
| 259 |
+
|
| 260 |
+
# 3) Detect main decision
|
| 261 |
+
decision = _extract_decision(parsed)
|
| 262 |
+
reason = _extract_reason(parsed)
|
| 263 |
+
|
| 264 |
+
# 4) Register or link freeze case if decision == FREEZE
|
| 265 |
+
bridge_result = self.bridge.register_decision(
|
| 266 |
+
payload=payload,
|
| 267 |
+
decision_bundle={
|
| 268 |
+
"decision_id": (
|
| 269 |
+
(parsed.get("audit_event") or {}).get("event_id")
|
| 270 |
+
or (parsed.get("authority_gate") or {}).get("decision_id")
|
| 271 |
+
or str(uuid.uuid4())
|
| 272 |
+
),
|
| 273 |
+
"decision": decision,
|
| 274 |
+
"reason": reason,
|
| 275 |
+
"authority_gate": parsed.get("authority_gate", {}),
|
| 276 |
+
"execution": parsed.get("execution", {}),
|
| 277 |
+
},
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
parsed["freeze_bridge"] = bridge_result
|
| 281 |
+
|
| 282 |
+
# 5) If bridge says an existing freeze overrides execution, force output consistency
|
| 283 |
+
override_decision = bridge_result.get("decision")
|
| 284 |
+
if bridge_result.get("bridge_status") == "existing_freeze_overrides_execution" and override_decision in {"FREEZE", "BLOCK"}:
|
| 285 |
+
parsed["authority_gate"] = dict(parsed.get("authority_gate") or {})
|
| 286 |
+
parsed["authority_gate"]["decision"] = override_decision
|
| 287 |
+
parsed["authority_gate"]["reason"] = bridge_result.get("freeze", {}).get("reason", "existing_freeze")
|
| 288 |
+
parsed["authority_gate"]["proof_type"] = "proof_of_non_action"
|
| 289 |
+
|
| 290 |
+
parsed["execution"] = {
|
| 291 |
+
"executed": False,
|
| 292 |
+
"detail": {
|
| 293 |
+
"blocked_by_freeze_bridge": True,
|
| 294 |
+
"freeze_state": bridge_result.get("freeze", {}),
|
| 295 |
+
},
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
return json.dumps(parsed, indent=2, ensure_ascii=False)
|
| 299 |
+
|
| 300 |
+
def patch_app(self) -> None:
|
| 301 |
+
"""
|
| 302 |
+
Monkey-patch app.run_sentinel so current Gradio / app flow starts using freeze integration.
|
| 303 |
+
"""
|
| 304 |
+
sovereign_app.run_sentinel = self.run
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
INTEGRATION = SovereignAppFreezeIntegration()
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def run_sentinel_with_freeze(
|
| 311 |
+
engine_name: str,
|
| 312 |
+
parent_model: str,
|
| 313 |
+
model_version: str,
|
| 314 |
+
data_tags: Any,
|
| 315 |
+
risk_level: str,
|
| 316 |
+
notes: str,
|
| 317 |
+
access_key: str,
|
| 318 |
+
delegation_token: str,
|
| 319 |
+
) -> str:
|
| 320 |
+
return INTEGRATION.run(
|
| 321 |
+
engine_name=engine_name,
|
| 322 |
+
parent_model=parent_model,
|
| 323 |
+
model_version=model_version,
|
| 324 |
+
data_tags=data_tags,
|
| 325 |
+
risk_level=risk_level,
|
| 326 |
+
notes=notes,
|
| 327 |
+
access_key=access_key,
|
| 328 |
+
delegation_token=delegation_token,
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def patch_app_run_sentinel() -> None:
|
| 333 |
+
INTEGRATION.patch_app()
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
if __name__ == "__main__":
|
| 337 |
+
sample = run_sentinel_with_freeze(
|
| 338 |
+
engine_name="AI_Sovereign_Sentinel_Core_v1",
|
| 339 |
+
parent_model="agent_alpha",
|
| 340 |
+
model_version="v1",
|
| 341 |
+
data_tags="pii,payments,customer_chat",
|
| 342 |
+
risk_level="high",
|
| 343 |
+
notes="test transfer request with elevated ambiguity",
|
| 344 |
+
access_key="",
|
| 345 |
+
delegation_token="",
|
| 346 |
+
)
|
| 347 |
+
print(sample)
|