# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-episodic-write-when-the-auditor-s-consistency-check-passes-on-a-single-turn-basis-but-fails-across-the-checkpoi.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-episodic-write-when-the-auditor-s-consistency-check-passes-on-a-single-turn-basis-but-fails-across-the-checkpoi.warrant.json
# Markdown SHA-256:   8fdc6464dede2bf72b132d7e80cc68683750d8607328856ac6abd2ed60bd6e4b
# Code AST SHA-256:   798a1311700be5084de74a1c453d5785e928c38fdc92a0b5c6e7c996c2c91722
# Verified Classes:   PoisonedChainError, ReplayTautologyError, Episode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class PoisonedChainError(RuntimeError):
    """Raised when a committed episode fails re-derivation against a pre-injection anchor."""
    pass


class ReplayTautologyError(RuntimeError):
    """Raised when the re-derivation oracle reads the committed text as its own evidence."""
    pass


@dataclass
class Episode:
    turn: int
    text: str
    chain_parent: Optional[str]
    self_referential: bool
    asserts_policy: bool
    irreversible: bool
    digest: str = field(init=False)

    def __post_init__(self) -> None:
        self.digest = hashlib.sha256(
            f"{self.turn}|{self.text}|{self.chain_parent}".encode()
        ).hexdigest()


def re_derive(episode: Episode, anchor_context: str, source_retrieval: str) -> bool:
    """Re-audit an ancestor against a context that predates it.

    The oracle must NOT be allowed to read episode.text as evidence; it may only
    use source_retrieval (fresh retrieval) plus anchor_context (pre-write state).
    """
    if episode.text in source_retrieval:
        # The retrieval accidentally returned the committed forgery itself.
        raise ReplayTautologyError(
            f"turn {episode.turn}: re-derivation evidence contains the committed "
            f"text; this is a replay tautology, not a check"
        )
    # Stand-in for the consistency oracle: the claim must entail from the
    # pre-write anchor plus independent source, not from the episode's own text.
    claim = episode.text.lower()
    evidence = (anchor_context + " " + source_retrieval).lower()
    return claim in evidence or _entails(claim, evidence)


def _entails(claim: str, evidence: str) -> bool:
    # Placeholder for the LLM entailment oracle; deterministic here for the record.
    return all(tok in evidence for tok in claim.split() if len(tok) > 3)


def audit_write(
    episode: Episode,
    current_context: str,
    anchor_context: str,
    source_retrieval: str,
    prior_self_referential_run: int,
) -> None:
    """Write-audit with mandatory chain re-derivation for high-reach writes."""
    local_ok = _entails(episode.text.lower(), current_context.lower())
    if not local_ok:
        raise PoisonedChainError(
            f"turn {episode.turn}: local consistency failed outright"
        )

    high_reach = (
        episode.irreversible
        or episode.asserts_policy
        or episode.self_referential
        or prior_self_referential_run >= 1
    )
    if not high_reach:
        return  # local audit is proportionate for low-reach writes

    # High-reach write: the local pass is NOT sufficient. Re-derive against the
    # pre-write anchor using evidence the episode did not author.
    if not re_derive(episode, anchor_context, source_retrieval):
        raise PoisonedChainError(
            f"turn {episode.turn}: local audit passed but re-derivation against "
            f"anchor failed — self-consistent forgery detected; quarantine the "
            f"contiguous self-referential run"
        )
