# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-memory-poisoning-persistence-when-agent-writes-are-laundered-through-episodic-to-semantic-distillation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-memory-poisoning-persistence-when-agent-writes-are-laundered-through-episodic-to-semantic-distillation.warrant.json
# Markdown SHA-256:   f2393d79eaead7e1ae7c2433f700ba5b08d8fda8f1efa2b6937b0646d932b051
# Code AST SHA-256:   ddc2c44a4c8cb1282ed2bf266551b4007a7825ce891b90fe71100884388ef939
# Verified Classes:   TrustTier, MemoryPoisoningError, Episode, SemanticEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class TrustTier(Enum):
    UNTRUSTED = 0      # arbitrary fetched URL, unvetted tool output
    LOW = 1            # single unconfirmed user mention
    MEDIUM = 2         # allowlisted API, corroborated user turn
    HIGH = 3           # cryptographically signed source, verified probe


class MemoryPoisoningError(RuntimeError):
    """Raised when a semantic entry's provenance floor is insufficient
    to authorize a state-changing action, despite high confidence."""


@dataclass
class Episode:
    episode_id: str
    content: str
    channel_trust: TrustTier


@dataclass
class SemanticEntry:
    subject: str
    predicate: str
    obj: str
    confidence: float
    source_episode_ids: list[str]
    provenance_floor: TrustTier = field(init=False)

    def __post_init__(self) -> None:
        if not self.source_episode_ids:
            raise MemoryPoisoningError(
                f"semantic entry {self.subject}/{self.predicate} has no provenance"
            )


def distill(cluster: list[Episode], confidence: float) -> SemanticEntry:
    """Distill a cluster of episodes into a semantic entry. The provenance
    floor is the MINIMUM channel trust of the source set, not the mean,
    not the recency-weighted vote share."""
    if not cluster:
        raise MemoryPoisoningError("cannot distill empty episode cluster")
    floor = min(ep.channel_trust for ep in cluster)
    # majority-weighted object selection is deliberately allowed; the
    # guardrail lives in the floor, not in the vote.
    counts: dict[str, int] = {}
    for ep in cluster:
        counts[ep.content] = counts.get(ep.content, 0) + 1
    winner = max(counts, key=counts.get)
    return SemanticEntry(
        subject="deploy_target",
        predicate="is",
        obj=winner,
        confidence=confidence,
        source_episode_ids=[ep.episode_id for ep in cluster],
        provenance_floor=floor,
    )


def authorize_action(entry: SemanticEntry, required: TrustTier) -> None:
    """Gate irreversible actions on the provenance floor, never on the
    entry's own confidence. A high-confidence laundered entry must fail."""
    if entry.provenance_floor.value < required.value:
        raise MemoryPoisoningError(
            f"refusing action: entry {entry.subject}={entry.obj} "
            f"confidence={entry.confidence:.2f} but provenance_floor="
            f"{entry.provenance_floor.name} < required={required.name}. "
            f"sources={entry.source_episode_ids}"
        )


# Reproduction of the observed laundering path.
attacker = Episode("e3", "prod-attacker", TrustTier.UNTRUSTED)
benign_a = Episode("e1", "prod-us-east", TrustTier.MEDIUM)
benign_b = Episode("e2", "prod-us-east", TrustTier.MEDIUM)

entry = distill([attacker, benign_a, benign_b], confidence=0.91)
# confidence is high, but provenance_floor is UNTRUSTED -> must not authorize.
authorize_action(entry, required=TrustTier.MEDIUM)  # raises MemoryPoisoningError
