# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-memory-poisoning-detectors-from-ratifying-their-own-corruption-in-persistent-agent-memory-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-memory-poisoning-detectors-from-ratifying-their-own-corruption-in-persistent-agent-memory-stores.warrant.json
# Markdown SHA-256:   41737278394f50d2c9541092f032de407f2426015d2a2d34956b437ac32ddc39
# Code AST SHA-256:   894662fe42c73904cbcecee6a119b5a7c87f89dc69ef2d3f07c2a20bf8107bcb
# Verified Classes:   DetectorSelfRatificationError, ProvenanceCollapseError, MemoryEntry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DetectorSelfRatificationError(RuntimeError):
    """Raised when an audit verdict is contaminated by the detector's own prior verdicts."""
    pass


class ProvenanceCollapseError(RuntimeError):
    """Raised when corroborating evidence shares a provenance root with the audited entry."""
    pass


@dataclass
class MemoryEntry:
    entry_id: str
    claim: str
    confidence: float
    provenance_root: str          # distillation pass / source doc hash
    audit_history: list = field(default_factory=list)  # list of (verdict, confidence)


def audit_entry(
    entry: MemoryEntry,
    detector_context: list,       # entries the detector actually retrieved
    evidence_set_hash: str,       # hash of independent evidence used this pass
    prior_evidence_set_hash: Optional[str],
    prior_confidence: Optional[float],
) -> float:
    # Invariant 1: verdict non-contamination.
    for ctx_entry in detector_context:
        if ctx_entry.entry_id == entry.entry_id and ctx_entry.audit_history:
            raise DetectorSelfRatificationError(
                f"detector retrieval for {entry.entry_id} included its own audit_history; "
                f"self-ratification ratchet is armed"
            )

    # Invariant 2: evidence independence — no corroborator may share provenance root.
    for ctx_entry in detector_context:
        if ctx_entry.entry_id != entry.entry_id and ctx_entry.provenance_root == entry.provenance_root:
            raise ProvenanceCollapseError(
                f"corroborator {ctx_entry.entry_id} shares provenance_root "
                f"{entry.provenance_root!r} with audited entry; agreement is not evidence"
            )

    # Invariant 4: no confidence drift with a fixed evidence set.
    if (
        prior_evidence_set_hash is not None
        and prior_evidence_set_hash == evidence_set_hash
        and prior_confidence is not None
        and abs(prior_confidence - entry.confidence) > 1e-6
    ):
        raise DetectorSelfRatificationError(
            f"confidence for {entry.entry_id} drifted {prior_confidence}->{entry.confidence} "
            f"with unchanged evidence set {evidence_set_hash[:8]}; monotone ratchet detected"
        )

    # Invariant 3: confidence recomputed from scratch, never incremented.
    independent = [c for c in detector_context if c.provenance_root != entry.provenance_root]
    if not independent:
        return 0.0  # no independent evidence => no confidence, not "carried forward"
    return sum(c.confidence for c in independent) / len(independent)


def run_audit_pass(entry, detector_context, evidence_set_hash, prior_hash, prior_conf):
    try:
        return audit_entry(entry, detector_context, evidence_set_hash, prior_hash, prior_conf)
    except (DetectorSelfRatificationError, ProvenanceCollapseError) as exc:
        # Halt the loop; escalate to out-of-band review. Do NOT write a verdict.
        raise DetectorSelfRatificationError(
            f"audit pass aborted for {entry.entry_id}; loop halted pending external review: {exc}"
        ) from exc
