# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-versus-benign-drift-in-long-horizon-agent-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-versus-benign-drift-in-long-horizon-agent-sessions.warrant.json
# Markdown SHA-256:   ca0e083e8e3a71a20a6b7d3734ee944200860fc21c3c872d1113601b2c710147
# Code AST SHA-256:   bfe26d75ea1b9e5e4748ed146ca196b3e1801787a70f5d7252799066f19c9663
# Verified Classes:   SupportMutationError, Episode, SemanticFact
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SupportMutationError(RuntimeError):
    """Raised when a semantic fact's supporting episode hash no longer matches."""
    pass


@dataclass(frozen=True)
class Episode:
    id: str
    content: str
    write_turn: int
    writer_principal: str

    def content_hash(self) -> str:
        return hashlib.sha256(self.content.encode()).hexdigest()


@dataclass(frozen=True)
class SemanticFact:
    claim: str
    deriver_principal: str
    distill_turn: int
    support: tuple[tuple[str, str], ...]  # (episode_id, hash_at_distill_time)


def audit_fact(
    fact: SemanticFact,
    episodes: dict[str, Episode],
    mutation_log: dict[str, tuple[int, str]],  # episode_id -> (turn, principal)
) -> None:
    for ep_id, expected_hash in fact.support:
        ep = episodes.get(ep_id)
        if ep is None:
            raise SupportMutationError(f"support episode {ep_id} missing entirely")
        if ep.content_hash() != expected_hash:
            mut_turn, mut_principal = mutation_log.get(ep_id, (-1, "<unknown>"))
            benign = (
                mut_principal == fact.deriver_principal
                and mut_turn < fact.distill_turn
            )
            if benign:
                # re-summarization before distillation; re-derive, do not fail hard
                continue
            raise SupportMutationError(
                f"poisoned or stale support: episode {ep_id} mutated at turn "
                f"{mut_turn} by {mut_principal}; fact distilled at turn "
                f"{fact.distill_turn} by {fact.deriver_principal}"
            )
