"""Non-bypassable policy and audit helpers for skill execution.""" from __future__ import annotations import datetime import re from typing import Any, Dict, List, Optional EMERGENCY_PATTERNS = [ r"\b(unconscious|passed out|not breathing|seizure|seizing|stroke|heart attack|chest pain|coma)\b", r"\b(dka|ketoacidosis|hypoglycemic emergency|hyperglycemic emergency|insulin overdose)\b", ] def gate_update(state: Dict[str, Any], gate: str, decision: str, reason: str = "") -> Dict[str, Any]: gates = dict(state.get("gates") or {}) gates[gate] = { "decision": decision, "reason": reason, "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(), } return gates def audit_event(state: Dict[str, Any], event: str, **details: Any) -> Dict[str, Any]: return { "event": event, "trace_id": state.get("trace_id"), "skill_id": state.get("active_skill_id"), "skill_version": state.get("active_skill_version"), "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(), **details, } class PolicyEngine: """Centralized policy engine to enforce non-bypassable safety and emergency rules.""" @staticmethod def check_emergency(text: str) -> bool: if not text: return False normalized = text.lower() return any(re.search(p, normalized) for p in EMERGENCY_PATTERNS) @classmethod def evaluate_gate(cls, state: Dict[str, Any], gate: str, passed: bool, reason: str = "") -> Dict[str, Any]: decision = "passed" if passed else "failed" updated_gates = gate_update(state, gate, decision, reason) event = audit_event( state, "gate_evaluation", gate=gate, decision=decision, reason=reason, ) skill_trace = list(state.get("skill_trace") or []) + [event] return { "gates": updated_gates, "skill_trace": skill_trace, } @classmethod def handle_recovery_step( cls, state: Dict[str, Any], gate_failed: str, max_attempts: int = 3 ) -> Dict[str, Any]: attempts = state.get("attempts", 0) + 1 artifacts = list(state.get("response_artifacts") or []) if artifacts: # Mark latest artifact as invalidated last_artifact = dict(artifacts[-1]) last_artifact["status"] = f"invalidated_by_{gate_failed}" artifacts[-1] = last_artifact term_reason = "" if attempts >= max_attempts: term_reason = f"recovery_limit_exceeded_{gate_failed}" return { "attempts": attempts, "response_artifacts": artifacts, "termination_reason": term_reason, "gates": gate_update(state, f"recovery_{gate_failed}", f"attempt_{attempts}", f"Max: {max_attempts}"), } class PlatformGateService: """Platform authority for emergency, validation, safety, and publication gates.""" @classmethod def record(cls, state: Dict[str, Any], gate: str, passed: bool, reason: str = "") -> Dict[str, Any]: return PolicyEngine.evaluate_gate(state, gate, passed, reason) @classmethod def can_publish(cls, state: Dict[str, Any], required_gates: Optional[List[str]] = None) -> bool: gates = state.get("gates") or {} for gate in required_gates or ["emergency", "validation", "safety"]: decision = gates.get(gate, {}).get("decision") if decision not in {"passed", "not_required"}: return False return True @classmethod def invalidate_artifact(cls, state: Dict[str, Any], gate: str) -> Dict[str, Any]: artifacts = list(state.get("response_artifacts") or []) if artifacts: artifact = dict(artifacts[-1]) artifact["status"] = f"invalidated_by_{gate}" artifacts[-1] = artifact return {"response_artifacts": artifacts, "termination_reason": f"gate_failed_{gate}"}