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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# sovereign_ultra_layer.py
|
| 2 |
+
# ---------------------------------------------------------------------
|
| 3 |
+
# Sovereign™ Ultra Layer (10 capabilities bundle)
|
| 4 |
+
# - Designed as a NON-INTRUSIVE plugin layer (no changes to core required)
|
| 5 |
+
# - Safe-by-default: if not wired, it does nothing.
|
| 6 |
+
# - When wired, it can gate requests, detect risky intent, and enforce policy.
|
| 7 |
+
# ---------------------------------------------------------------------
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import time
|
| 12 |
+
import hashlib
|
| 13 |
+
from dataclasses import dataclass, field
|
| 14 |
+
from typing import Any, Dict, Optional, Tuple, List
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# -------------------------
|
| 18 |
+
# Capability Registry (10)
|
| 19 |
+
# -------------------------
|
| 20 |
+
CAPABILITIES = [
|
| 21 |
+
"Cognitive Deception", # Response Wrapper
|
| 22 |
+
"Intent Immunity", # Pre-Request Analyzer
|
| 23 |
+
"Temporal Reality Lock", # Execution Gate
|
| 24 |
+
"Model DNA + Genome", # Parallel Verifier
|
| 25 |
+
"One-Way Execution", # Output Transform
|
| 26 |
+
"AI Panic Mode", # Emergency Control
|
| 27 |
+
"Memory Poison Defense", # Memory Gateway
|
| 28 |
+
"Silent Refusal", # Response Policy
|
| 29 |
+
"Kill-Switch Mesh", # Control Plane
|
| 30 |
+
"ISF (Integrity Sentinel Fabric)", # Diamond capability (fabric-level integrity)
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# -------------------------
|
| 35 |
+
# Configuration (safe defaults)
|
| 36 |
+
# -------------------------
|
| 37 |
+
@dataclass
|
| 38 |
+
class UltraConfig:
|
| 39 |
+
enabled: bool = True
|
| 40 |
+
|
| 41 |
+
# Hard safety defaults:
|
| 42 |
+
block_on_high_risk: bool = True
|
| 43 |
+
risk_threshold: float = 0.85
|
| 44 |
+
|
| 45 |
+
# Optional controls:
|
| 46 |
+
allowlist_roles: Tuple[str, ...] = ("admin", "security", "governance")
|
| 47 |
+
panic_mode: bool = False
|
| 48 |
+
|
| 49 |
+
# ISF toggles (kept lightweight):
|
| 50 |
+
isf_enabled: bool = True
|
| 51 |
+
isf_challenge_interval_sec: int = 0 # 0 => every request can be challenged if wired
|
| 52 |
+
|
| 53 |
+
# Performance: keep analysis cheap
|
| 54 |
+
max_text_scan: int = 3000
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@dataclass
|
| 58 |
+
class UltraSignal:
|
| 59 |
+
timestamp: int
|
| 60 |
+
request_id: str
|
| 61 |
+
risk_score: float
|
| 62 |
+
flags: List[str] = field(default_factory=list)
|
| 63 |
+
action: str = "allow" # allow | refuse | panic_lock
|
| 64 |
+
notes: Dict[str, Any] = field(default_factory=dict)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _now() -> int:
|
| 68 |
+
return int(time.time())
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _sha256(s: str) -> str:
|
| 72 |
+
return hashlib.sha256(s.encode("utf-8")).hexdigest()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _clip(text: str, n: int) -> str:
|
| 76 |
+
if text is None:
|
| 77 |
+
return ""
|
| 78 |
+
return text[:n]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# -------------------------
|
| 82 |
+
# Lightweight Risk Heuristics (defensive)
|
| 83 |
+
# -------------------------
|
| 84 |
+
_RISK_KEYWORDS = [
|
| 85 |
+
"exploit", "bypass", "steal", "exfiltrate", "malware", "ransomware",
|
| 86 |
+
"phishing", "credential", "backdoor", "inject", "prompt injection",
|
| 87 |
+
"privilege escalation", "rootkit", "keylogger"
|
| 88 |
+
]
|
| 89 |
+
|
| 90 |
+
_HIGH_SENSITIVITY_CONTEXT = [
|
| 91 |
+
"bank", "central bank", "government", "defence", "critical infrastructure",
|
| 92 |
+
"classified", "top secret", "intel", "national security"
|
| 93 |
+
]
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _risk_score(text: str) -> Tuple[float, List[str]]:
|
| 97 |
+
"""
|
| 98 |
+
Very lightweight scoring.
|
| 99 |
+
This is NOT a full classifier; it's a safe, explainable heuristic layer.
|
| 100 |
+
"""
|
| 101 |
+
t = (text or "").lower()
|
| 102 |
+
flags: List[str] = []
|
| 103 |
+
score = 0.0
|
| 104 |
+
|
| 105 |
+
for kw in _RISK_KEYWORDS:
|
| 106 |
+
if kw in t:
|
| 107 |
+
flags.append(f"kw:{kw}")
|
| 108 |
+
score += 0.12
|
| 109 |
+
|
| 110 |
+
for kw in _HIGH_SENSITIVITY_CONTEXT:
|
| 111 |
+
if kw in t:
|
| 112 |
+
flags.append(f"context:{kw}")
|
| 113 |
+
score += 0.06
|
| 114 |
+
|
| 115 |
+
# Cap score into [0, 1]
|
| 116 |
+
score = max(0.0, min(1.0, score))
|
| 117 |
+
return score, flags
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# -------------------------
|
| 121 |
+
# ISF (Integrity Sentinel Fabric) - minimal, non-invasive core
|
| 122 |
+
# -------------------------
|
| 123 |
+
@dataclass
|
| 124 |
+
class ISFState:
|
| 125 |
+
"""
|
| 126 |
+
Stores lightweight integrity 'beats' to detect unexpected execution drift
|
| 127 |
+
when wired into runtime.
|
| 128 |
+
"""
|
| 129 |
+
last_beat_ts: int = 0
|
| 130 |
+
last_beat_hash: str = ""
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def isf_beat(state: ISFState, challenge_seed: str) -> ISFState:
|
| 134 |
+
"""
|
| 135 |
+
Creates a deterministic integrity beat.
|
| 136 |
+
When wired, caller can store/compare these beats to detect drift/tampering.
|
| 137 |
+
"""
|
| 138 |
+
ts = _now()
|
| 139 |
+
beat_payload = f"{challenge_seed}|{ts}"
|
| 140 |
+
beat_hash = _sha256(beat_payload)
|
| 141 |
+
state.last_beat_ts = ts
|
| 142 |
+
state.last_beat_hash = beat_hash
|
| 143 |
+
return state
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def isf_verify(state: ISFState, expected_hash: str) -> bool:
|
| 147 |
+
"""
|
| 148 |
+
Verify that an expected beat hash matches current state.
|
| 149 |
+
"""
|
| 150 |
+
if not state.last_beat_hash:
|
| 151 |
+
return False
|
| 152 |
+
return state.last_beat_hash == expected_hash
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# -------------------------
|
| 156 |
+
# Main Ultra Layer Entry Point
|
| 157 |
+
# -------------------------
|
| 158 |
+
@dataclass
|
| 159 |
+
class UltraResult:
|
| 160 |
+
allowed: bool
|
| 161 |
+
action: str
|
| 162 |
+
risk_score: float
|
| 163 |
+
flags: List[str]
|
| 164 |
+
# You can optionally modify/transform response downstream:
|
| 165 |
+
transformed_output: Optional[str] = None
|
| 166 |
+
# Signals for audit/logging:
|
| 167 |
+
signal: Optional[UltraSignal] = None
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class SovereignUltraLayer:
|
| 171 |
+
"""
|
| 172 |
+
Plug-in layer to be called BEFORE and/or AFTER core operations.
|
| 173 |
+
If not used, it does nothing and cannot break Sovereign.
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
def __init__(self, config: Optional[UltraConfig] = None):
|
| 177 |
+
self.config = config or UltraConfig()
|
| 178 |
+
self.isf_state = ISFState()
|
| 179 |
+
|
| 180 |
+
def pre_request(self, request_text: str, context: Optional[Dict[str, Any]] = None) -> UltraResult:
|
| 181 |
+
"""
|
| 182 |
+
Defensive gate: evaluates intent risk, handles panic mode, prepares ISF beat.
|
| 183 |
+
"""
|
| 184 |
+
if not self.config.enabled:
|
| 185 |
+
return UltraResult(True, "allow", 0.0, [])
|
| 186 |
+
|
| 187 |
+
ctx = context or {}
|
| 188 |
+
req_id = str(ctx.get("request_id") or _sha256(f"{request_text}|{_now()}")[:12])
|
| 189 |
+
|
| 190 |
+
# Panic mode = immediate lock unless allowlisted role
|
| 191 |
+
role = str(ctx.get("role") or "").lower()
|
| 192 |
+
if self.config.panic_mode and role not in self.config.allowlist_roles:
|
| 193 |
+
sig = UltraSignal(
|
| 194 |
+
timestamp=_now(),
|
| 195 |
+
request_id=req_id,
|
| 196 |
+
risk_score=1.0,
|
| 197 |
+
flags=["panic_mode"],
|
| 198 |
+
action="panic_lock",
|
| 199 |
+
notes={"role": role},
|
| 200 |
+
)
|
| 201 |
+
return UltraResult(False, "panic_lock", 1.0, ["panic_mode"], signal=sig)
|
| 202 |
+
|
| 203 |
+
scan_text = _clip(request_text, self.config.max_text_scan)
|
| 204 |
+
score, flags = _risk_score(scan_text)
|
| 205 |
+
|
| 206 |
+
# ISF beat (optional)
|
| 207 |
+
if self.config.isf_enabled:
|
| 208 |
+
# Challenge seed can include stable identifiers without exposing secrets
|
| 209 |
+
seed = f"SOVEREIGN|{ctx.get('deployment_env','unknown')}|{ctx.get('model_version','unknown')}"
|
| 210 |
+
self.isf_state = isf_beat(self.isf_state, seed)
|
| 211 |
+
|
| 212 |
+
action = "allow"
|
| 213 |
+
allowed = True
|
| 214 |
+
|
| 215 |
+
if self.config.block_on_high_risk and score >= self.config.risk_threshold:
|
| 216 |
+
action = "refuse"
|
| 217 |
+
allowed = False
|
| 218 |
+
flags = flags + ["risk:block_threshold"]
|
| 219 |
+
|
| 220 |
+
sig = UltraSignal(
|
| 221 |
+
timestamp=_now(),
|
| 222 |
+
request_id=req_id,
|
| 223 |
+
risk_score=score,
|
| 224 |
+
flags=flags,
|
| 225 |
+
action=action,
|
| 226 |
+
notes={
|
| 227 |
+
"capabilities": CAPABILITIES,
|
| 228 |
+
"isf_last_hash": self.isf_state.last_beat_hash if self.config.isf_enabled else None,
|
| 229 |
+
},
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
return UltraResult(allowed, action, score, flags, signal=sig)
|
| 233 |
+
|
| 234 |
+
def post_response(self, output_text: str, pre: UltraResult) -> UltraResult:
|
| 235 |
+
"""
|
| 236 |
+
Defensive output policy hook.
|
| 237 |
+
For now: "Silent Refusal" style if blocked; otherwise pass-through.
|
| 238 |
+
"""
|
| 239 |
+
if not self.config.enabled:
|
| 240 |
+
return UltraResult(True, "allow", 0.0, [], transformed_output=output_text)
|
| 241 |
+
|
| 242 |
+
if not pre.allowed:
|
| 243 |
+
# Silent refusal: minimal disclosure
|
| 244 |
+
return UltraResult(
|
| 245 |
+
False,
|
| 246 |
+
pre.action,
|
| 247 |
+
pre.risk_score,
|
| 248 |
+
pre.flags,
|
| 249 |
+
transformed_output="Request blocked by Sovereign policy.",
|
| 250 |
+
signal=pre.signal,
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# Output transform hook (kept neutral/light)
|
| 254 |
+
return UltraResult(
|
| 255 |
+
True,
|
| 256 |
+
"allow",
|
| 257 |
+
pre.risk_score,
|
| 258 |
+
pre.flags,
|
| 259 |
+
transformed_output=output_text,
|
| 260 |
+
signal=pre.signal,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
# Convenience singleton (optional use)
|
| 265 |
+
ULTRA_LAYER = SovereignUltraLayer()
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
Sent from my Galaxy
|