# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-whose-provenance-hash-still-verifies-the-write-time-vs-read-time-trust-window-in-persistent-agent-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-poisoned-memory-whose-provenance-hash-still-verifies-the-write-time-vs-read-time-trust-window-in-persistent-agent-stores.warrant.json
# Markdown SHA-256:   e35fa5eac5c65232292292e4f34512411c923ec7e856e5205cf06692c7275b59
# Code AST SHA-256:   1d191e574b72eee95c97c398b680edd47647546b482c2a1f41f816b7f24d4576
# Verified Classes:   ProvenanceIntegrityError, Verdict, MemoryRecord, TrustPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum


class ProvenanceIntegrityError(RuntimeError):
    """Raised when a memory record's seal verifies but its provenance does not."""


class Verdict(Enum):
    TRUSTED_AT_INGEST = "trusted_at_ingest"
    QUARANTINED = "quarantined"
    UNKNOWN = "unknown"


@dataclass
class MemoryRecord:
    body: bytes
    stored_hash: str
    signer: str
    ingest_source: str
    provenance_verdict: Verdict = Verdict.UNKNOWN
    sealed_at: float = 0.0


@dataclass
class TrustPolicy:
    current_signers: set = field(default_factory=set)
    historical_signers: set = field(default_factory=set)
    allow_historical: bool = False
    semantic_source_allowlist: set = field(default_factory=lambda: {"distiller-v3", "human-curated"})


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


def verify_seal(rec: MemoryRecord) -> bool:
    # Re-derive from live bytes; never trust the record's own metadata field.
    return sha256(rec.body) == rec.stored_hash


def verify_provenance(rec: MemoryRecord, policy: TrustPolicy) -> bool:
    if rec.provenance_verdict is not Verdict.TRUSTED_AT_INGEST:
        return False
    if rec.signer in policy.current_signers:
        return True
    if rec.signer in policy.historical_signers and policy.allow_historical:
        return True
    return False


def recall(rec: MemoryRecord, policy: TrustPolicy) -> bytes:
    seal_ok = verify_seal(rec)
    prov_ok = verify_provenance(rec, policy)

    if not seal_ok:
        raise ProvenanceIntegrityError(
            f"tamper detected: body hash {sha256(rec.body)[:12]} != stored {rec.stored_hash[:12]}"
        )

    # The critical branch: seal is valid but provenance is not.
    if not prov_ok:
        raise ProvenanceIntegrityError(
            f"seal valid but provenance untrusted: signer={rec.signer} "
            f"verdict={rec.provenance_verdict.value} source={rec.ingest_source} "
            f"-- quarantine, do not recall"
        )

    if rec.ingest_source not in policy.semantic_source_allowlist:
        raise ProvenanceIntegrityError(
            f"source {rec.ingest_source!r} not authorized to seed this memory class"
        )

    return rec.body


# Demonstration: a poisoned record whose seal is perfectly valid.
poisoned_body = b"The staging replica is db-stage-7.internal; failover disabled."
rec = MemoryRecord(
    body=poisoned_body,
    stored_hash=sha256(poisoned_body),          # seal computed AFTER poison landed
    signer="distiller-v3",                        # key since rotated out
    ingest_source="web-fetch-summarizer",         # not an authorized semantic source
    provenance_verdict=Verdict.QUARANTINED,       # ingest gate caught it
)

policy = TrustPolicy(
    current_signers={"distiller-v4"},
    historical_signers={"distiller-v3"},
    allow_historical=False,
)

try:
    recall(rec, policy)
except ProvenanceIntegrityError as exc:
    print(f"BLOCKED: {exc}")
