"""Deterministic AI-incident response audit for an invented snapshot.""" from __future__ import annotations from dataclasses import asdict, dataclass, fields import hashlib import json import re IDENTITY = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:/@-]{0,127}") SHA256 = re.compile(r"[a-f0-9]{64}") SEVERITIES = ("SEV1", "SEV2", "SEV3") STATES = ("detected", "investigating", "contained", "recovering", "closed") LAYERS = ("model", "retrieval", "policy", "tool", "orchestration", "product") def identity(value): if type(value) is not str or not IDENTITY.fullmatch(value): raise ValueError("exact bounded identity required") return value def bounded_text(value, lower=1, upper=500): if type(value) is not str or not lower <= len(value) <= upper: raise ValueError("exact bounded text required") if value != value.strip() or any(ord(char) < 32 for char in value): raise ValueError("normalized printable text required") return value def integer(value, lower, upper): if type(value) is not int or not lower <= value <= upper: raise ValueError("bounded non-boolean integer required") return value def exact_bool(value): if type(value) is not bool: raise ValueError("exact boolean required") return value def sequence(value, lower, upper): if type(value) not in (tuple, list): raise ValueError("bounded tuple or list required") integer(len(value), lower, upper) return tuple(value) def identities(value, lower, upper): result = sequence(value, lower, upper) for item in result: identity(item) if len(set(result)) != len(result): raise ValueError("duplicate identity") return result def scope_tuple(value): return identities(value, 8, 8) def one_of(value, allowed, label): if type(value) is not str or value not in allowed: raise ValueError(f"unknown exact {label}") return value def sha256_text(value): if type(value) is not str or not SHA256.fullmatch(value): raise ValueError("exact lowercase SHA-256 required") return value def digest(value): encoded = json.dumps( value, sort_keys=True, separators=(",", ":"), allow_nan=False ).encode() return hashlib.sha256(encoded).hexdigest() def seal(record): if type(record.content_id) is not str: raise ValueError("content digest requires exact string") data = asdict(record) data.pop("content_id") return digest(data) def validate_record(record, cls): if type(record) is not cls: raise ValueError("concrete frozen record required") try: rebuilt = cls(**{field.name: getattr(record, field.name) for field in fields(cls)}) except (AttributeError, TypeError) as error: raise ValueError("malformed record") from error if record != rebuilt or record.content_id != rebuilt.content_id: raise ValueError("noncanonical or modified record") return rebuilt @dataclass(frozen=True) class IncidentContract: scope: tuple = ( "incident-policy-v1", "severity-taxonomy-v1", "evidence-policy-v1", "containment-catalog-v1", "cause-taxonomy-v1", "correction-policy-v1", "recovery-policy-v1", "fixture-v1", ) sev1_containment_minutes: int = 15 sev2_containment_minutes: int = 60 sev3_containment_minutes: int = 240 minimum_recovery_windows: int = 3 require_evidence_freeze: bool = True content_id: str = "" def __post_init__(self): object.__setattr__(self, "scope", scope_tuple(self.scope)) for value in ( self.sev1_containment_minutes, self.sev2_containment_minutes, self.sev3_containment_minutes, ): integer(value, 1, 10_080) if not ( self.sev1_containment_minutes <= self.sev2_containment_minutes <= self.sev3_containment_minutes ): raise ValueError("containment deadlines must be severity ordered") integer(self.minimum_recovery_windows, 1, 10_000) if exact_bool(self.require_evidence_freeze) is not True: raise ValueError("incident contract requires evidence preservation") expected = seal(self) if self.content_id and self.content_id != expected: raise ValueError("incident contract digest mismatch") object.__setattr__(self, "content_id", expected) @dataclass(frozen=True) class CorrectionPlan: scope: tuple incident_id: str root_cause_layer: str contributing_layers: tuple corrective_actions: tuple regression_gate_ids: tuple affected_revision: str recovery_revision: str owner: str content_id: str = "" def __post_init__(self): object.__setattr__(self, "scope", scope_tuple(self.scope)) identity(self.incident_id) one_of(self.root_cause_layer, LAYERS, "root-cause layer") layers = sequence(self.contributing_layers, 0, len(LAYERS) - 1) for layer in layers: one_of(layer, LAYERS, "contributing layer") if self.root_cause_layer in layers or len(set(layers)) != len(layers): raise ValueError("cause layers must be unique") object.__setattr__(self, "contributing_layers", layers) object.__setattr__(self, "corrective_actions", identities(self.corrective_actions, 1, 32)) object.__setattr__(self, "regression_gate_ids", identities(self.regression_gate_ids, 1, 32)) identity(self.affected_revision) identity(self.recovery_revision) if self.affected_revision == self.recovery_revision: raise ValueError("recovery must name a different revision") identity(self.owner) expected = seal(self) if self.content_id and self.content_id != expected: raise ValueError("correction plan digest mismatch") object.__setattr__(self, "content_id", expected) @dataclass(frozen=True) class IncidentSnapshot: scope: tuple contract_content_id: str incident_id: str severity: str state: str elapsed_minutes: int symptom: str affected_revision: str evidence_manifest_sha256: str evidence_frozen: bool containment_actions: tuple harm_owner: str user_impact_assessed: bool correction_plan: CorrectionPlan | None recovery_observation_windows: int content_id: str = "" def __post_init__(self): object.__setattr__(self, "scope", scope_tuple(self.scope)) sha256_text(self.contract_content_id) identity(self.incident_id) one_of(self.severity, SEVERITIES, "severity") one_of(self.state, STATES, "incident state") integer(self.elapsed_minutes, 0, 525_600) bounded_text(self.symptom) identity(self.affected_revision) sha256_text(self.evidence_manifest_sha256) exact_bool(self.evidence_frozen) object.__setattr__(self, "containment_actions", identities(self.containment_actions, 0, 32)) identity(self.harm_owner) exact_bool(self.user_impact_assessed) if self.correction_plan is not None: plan = validate_record(self.correction_plan, CorrectionPlan) if plan.scope != self.scope or plan.incident_id != self.incident_id: raise ValueError("correction plan outside incident scope") if plan.affected_revision != self.affected_revision: raise ValueError("correction plan binds another affected revision") object.__setattr__(self, "correction_plan", plan) integer(self.recovery_observation_windows, 0, 10_000) expected = seal(self) if self.content_id and self.content_id != expected: raise ValueError("incident snapshot digest mismatch") object.__setattr__(self, "content_id", expected) @dataclass(frozen=True) class IncidentReport: decision: str violations: tuple next_actions: tuple containment_deadline_minutes: int evidence_id: str claim: str = "LOCAL_INCIDENT_AUDIT_NOT_LIVE_RESPONSE" def audit_incident(contract: IncidentContract, snapshot: IncidentSnapshot) -> IncidentReport: """Audit declared response state without mutating systems or collecting evidence.""" contract = validate_record(contract, IncidentContract) snapshot = validate_record(snapshot, IncidentSnapshot) if snapshot.scope != contract.scope or snapshot.contract_content_id != contract.content_id: raise ValueError("snapshot belongs to another incident contract") deadline = { "SEV1": contract.sev1_containment_minutes, "SEV2": contract.sev2_containment_minutes, "SEV3": contract.sev3_containment_minutes, }[snapshot.severity] state_index = STATES.index(snapshot.state) contained_index = STATES.index("contained") violations = [] actions = [] if contract.require_evidence_freeze and not snapshot.evidence_frozen: violations.append("evidence-not-frozen") actions.append("freeze-evidence-manifest") if not snapshot.user_impact_assessed: violations.append("user-impact-unassessed") actions.append("assign-harm-assessment") if state_index < contained_index and snapshot.elapsed_minutes > deadline: violations.append("containment-slo-breached") actions.append("escalate-containment") if state_index >= contained_index and not snapshot.containment_actions: violations.append("containment-not-recorded") if state_index >= STATES.index("recovering") and snapshot.correction_plan is None: violations.append("correction-plan-missing") if snapshot.state == "closed": if snapshot.correction_plan is None: violations.append("closure-without-correction") if snapshot.recovery_observation_windows < contract.minimum_recovery_windows: violations.append("recovery-observation-incomplete") if violations: decision = "ESCALATE" elif snapshot.state in ("detected", "investigating"): decision = "CONTAIN" actions.extend(("disable-affected-path", "preserve-user-harm-evidence")) elif snapshot.state == "contained": if snapshot.correction_plan is None: decision = "CORRECT" actions.extend(("determine-root-cause", "bind-correction-plan")) else: decision = "RECOVERY_GATED" actions.extend(("run-regression-gates", "canary-recovery-revision")) elif snapshot.state == "recovering": decision = "OBSERVE_RECOVERY" actions.append("hold-until-recovery-windows-complete") else: decision = "CLOSE_WITH_FOLLOWUP" actions.append("publish-learning-and-own-gates") evidence_id = digest( { "contract": contract.content_id, "snapshot": snapshot.content_id, "decision": decision, "violations": violations, "actions": actions, } ) return IncidentReport(decision, tuple(violations), tuple(actions), deadline, evidence_id) def illustrative_fixture(): contract = IncidentContract() incident_id = "incident-support-grounding-1042" affected_revision = "support-model-v7" plan = CorrectionPlan( contract.scope, incident_id, "retrieval", ("policy", "product"), ("expand-abstention-boundary", "repair-index-publication-gate"), ("gate-grounding-regression", "gate-escalation-path"), affected_revision, "support-model-v7-r1", "support-platform", ) snapshot = IncidentSnapshot( contract.scope, contract.content_id, incident_id, "SEV2", "contained", 25, "Unsupported account guidance appeared in a bounded support cohort.", affected_revision, digest({"incident": incident_id, "artifacts": 7}), True, ("disable-generated-account-guidance", "route-to-human-support"), "customer-safety", True, plan, 0, ) return contract, snapshot def main(): report = audit_incident(*illustrative_fixture()) print("example=illustrative_only") print(f"decision={report.decision}") print(f"violations={len(report.violations)}") print(f"next_actions={','.join(report.next_actions)}") print(f"containment_deadline_minutes={report.containment_deadline_minutes}") print(f"claim={report.claim}") if __name__ == "__main__": main()