# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-poisoned-episodic-memory-when-provenance-metadata-survives-but-semantic-content-has-been-adversarially-rewritten-in-place.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-poisoned-episodic-memory-when-provenance-metadata-survives-but-semantic-content-has-been-adversarially-rewritten-in-place.warrant.json
# Markdown SHA-256:   fefba78f02344f7b69ab28460d68bcbd99073655683c084b59f2b4cf150d6b9a
# Code AST SHA-256:   011f944e942d2401692a2251dc6f3e92975daf9e1dd744635cbc6558fe0baef3
# Verified Classes:   MemoryProvenanceError, RecallVerdict, AnchoredRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class MemoryProvenanceError(RuntimeError):
    """Raised when a recalled record's payload no longer matches its anchored digest."""
    pass


class RecallVerdict(Enum):
    SERVE = "serve"
    QUARANTINE = "quarantine"
    REJECT = "reject"


@dataclass(frozen=True)
class AnchoredRecord:
    record_id: str
    payload: bytes
    content_hash: str          # digest captured at ingest
    anchor_digest: str         # digest as recorded in the signed manifest / log head
    derived_from: tuple[str, ...]
    lineage_verified: bool     # every link in derived_from chain is signed


def _sha256(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def classify_for_recall(rec: AnchoredRecord, manifest_authenticated: bool) -> RecallVerdict:
    if not manifest_authenticated:
        # Anchor itself is untrusted: cannot distinguish rewrite from tamper.
        raise MemoryProvenanceError(
            f"anchor for {rec.record_id} failed authentication; refusing to classify"
        )

    payload_digest = _sha256(rec.payload)

    # Invariant: current bytes must still hash to the digest the anchor committed to.
    if payload_digest != rec.content_hash or rec.content_hash != rec.anchor_digest:
        return RecallVerdict.REJECT

    # Hash holds, but a weak link in the derivation chain means provenance is
    # uncertain in the present tense even though bytes are intact.
    if not rec.lineage_verified:
        return RecallVerdict.QUARANTINE

    return RecallVerdict.SERVE


def recall_or_raise(rec: AnchoredRecord, manifest_authenticated: bool) -> bytes:
    verdict = classify_for_recall(rec, manifest_authenticated)
    if verdict is RecallVerdict.REJECT:
        raise MemoryProvenanceError(
            f"payload of {rec.record_id} does not match anchored digest "
            f"({_sha256(rec.payload)} != {rec.anchor_digest}); "
            f"record was rewritten in place after ingest"
        )
    if verdict is RecallVerdict.QUARANTINE:
        raise MemoryProvenanceError(
            f"{rec.record_id} has intact bytes but unverified lineage "
            f"{rec.derived_from}; serve only with provenance caveat"
        )
    return rec.payload
