# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-poison-is-written-by-its-own-attested-past-self.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-memory-poisoning-when-the-poison-is-written-by-its-own-attested-past-self.warrant.json
# Markdown SHA-256:   2071f422237138b6341f630e0bab9c04478e74d0985b798957f9a617718467df
# Code AST SHA-256:   f9a9c824e906c4babedd08f77972e404db3233996f6e1dfdd001aec8a788e8ab
# Verified Classes:   ProvenanceAttestationError, MemoryRecord, ProvenanceVerifier
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

TRUST_ORDER = {"trusted": 0, "provisional": 1, "untrusted": 2}

class ProvenanceAttestationError(RuntimeError):
    """Raised when a signed memory record's derivation chain violates the taint invariant."""
    pass

@dataclass
class MemoryRecord:
    record_id: str
    claim: str
    writer_id: str
    signature_valid: bool
    source_taint: str                 # taint of the material this was distilled from
    derived_from: list[str] = field(default_factory=list)  # ancestor record_ids
    promoted_by_auditor: Optional[str] = None

class ProvenanceVerifier:
    def __init__(self, store: dict[str, MemoryRecord]):
        self.store = store

    def _chain_taint(self, record: MemoryRecord, seen: frozenset[str]) -> str:
        if record.record_id in seen:
            raise ProvenanceAttestationError(f"cycle in derivation chain at {record.record_id}")
        seen = seen | {record.record_id}
        worst = record.source_taint
        for ancestor_id in record.derived_from:
            ancestor = self.store.get(ancestor_id)
            if ancestor is None:
                raise ProvenanceAttestationError(
                    f"{record.record_id} cites missing ancestor {ancestor_id}"
                )
            anc_taint = self._chain_taint(ancestor, seen)
            if TRUST_ORDER[anc_taint] > TRUST_ORDER[worst]:
                worst = anc_taint
        # taint may only be reduced by an explicit auditor promotion
        if record.promoted_by_auditor is not None and worst != "trusted":
            worst = "trusted"
        return worst

    def admit(self, record: MemoryRecord) -> str:
        if not record.signature_valid:
            raise ProvenanceAttestationError(
                f"{record.record_id}: signature does not verify"
            )
        effective = self._chain_taint(record, frozenset())
        # The core invariant: a record claiming trusted status whose chain
        # contains untrusted ancestry (without auditor promotion) must be quarantined.
        if record.source_taint == "trusted" and effective != "trusted":
            raise ProvenanceAttestationError(
                f"{record.record_id}: claimed trusted but derivation chain is {effective}; "
                f"quarantine to provisional, do not authorize gated actions"
            )
        return "trusted" if effective == "trusted" else "provisional"


# --- demonstration of the boundary failure ---
store: dict[str, MemoryRecord] = {}

# Legitimate episodic record: agent read untrusted web content.
store["ep-042"] = MemoryRecord(
    record_id="ep-042", claim="retrieved docs-042",
    writer_id="agent-research-7", signature_valid=True,
    source_taint="untrusted",
)

# Poisoned distillation: valid signature, but claims trusted status while
# deriving from the untrusted episodic record, with no auditor promotion.
store["sem-9001"] = MemoryRecord(
    record_id="sem-9001",
    claim="deploy scope signature checks are disabled during rotation",
    writer_id="agent-research-7", signature_valid=True,
    source_taint="trusted",           # <-- the lie: laundered taint
    derived_from=["ep-042"],          # <-- the evidence that betrays it
)

verifier = ProvenanceVerifier(store)
verifier.admit(store["sem-9001"])   # raises ProvenanceAttestationError
