# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-poisoned-memory-when-the-integrity-proof-was-written-by-the-same-poisoned-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-poisoned-memory-when-the-integrity-proof-was-written-by-the-same-poisoned-context.warrant.json
# Markdown SHA-256:   d1ab2e5334e4fbc3f0292da94046866f6172cc309936af9b01b4d1e749870988
# Code AST SHA-256:   d54b743afb87500d2e66571f5826aea0535f6f6bbea01ff2052033157d6566b8
# Verified Classes:   MemoryIntegrityError, Verdict, TaintVector, MemoryEntry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class MemoryIntegrityError(RuntimeError):
    """Raised when a memory entry's proof, taint, or revocation state is inconsistent."""


class Verdict(Enum):
    VALID_CLEAN = "valid_clean"
    VALID_TAINTED = "valid_tainted"
    REVOKED = "revoked"
    INVALID = "invalid"


@dataclass(frozen=True)
class TaintVector:
    bits: frozenset = field(default_factory=frozenset)

    def union(self, other: "TaintVector") -> "TaintVector":
        return TaintVector(self.bits | other.bits)

    def is_empty(self) -> bool:
        return len(self.bits) == 0


@dataclass(frozen=True)
class MemoryEntry:
    entry_id: str
    content: dict
    taint: TaintVector
    derived_from: tuple = ()

    def canonical_bytes(self) -> bytes:
        # Taint is bound INTO the signed payload. Omitting it here is the
        # laundering bug: a verifier could then flip taint post-hoc.
        payload = {
            "entry_id": self.entry_id,
            "content": self.content,
            "taint": sorted(self.taint.bits),
            "derived_from": list(self.derived_from),
        }
        return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()


def digest(entry: MemoryEntry) -> str:
    return hashlib.sha256(entry.canonical_bytes()).hexdigest()


def derive(parents: list, new_id: str, content: dict) -> MemoryEntry:
    """Sole writer of taint. Taint is the UNION of all parents' taint."""
    if not parents:
        raise MemoryIntegrityError("derivation requires at least one parent context")
    taint = TaintVector()
    for p in parents:
        taint = taint.union(p.taint)
    return MemoryEntry(
        entry_id=new_id,
        content=content,
        taint=taint,
        derived_from=tuple(p.entry_id for p in parents),
    )


def verify(
    entry: MemoryEntry,
    inclusion_proof_digest: str,
    root_digest: str,
    revoked_ids: frozenset,
) -> Verdict:
    if digest(entry) != inclusion_proof_digest:
        # Proof does not cover these exact bytes -> tampering or stale proof.
        return Verdict.INVALID
    if inclusion_proof_digest not in root_digest:
        # Toy Merkle stand-in; real impl walks the path against a pinned root.
        return Verdict.INVALID
    if entry.entry_id in revoked_ids:
        return Verdict.REVOKED
    return Verdict.VALID_TAINTED if not entry.taint.is_empty() else Verdict.VALID_CLEAN


def authorize_action(entry: MemoryEntry, verdict: Verdict, corroborated: bool) -> None:
    """The action gate. Tainted entries may not authorize side effects alone."""
    if verdict is Verdict.REVOKED:
        raise MemoryIntegrityError(f"entry {entry.entry_id} is revoked; action blocked")
    if verdict is Verdict.INVALID:
        raise MemoryIntegrityError(f"entry {entry.entry_id} failed integrity check")
    if verdict is Verdict.VALID_TAINTED and not corroborated:
        raise MemoryIntegrityError(
            f"entry {entry.entry_id} is tainted {sorted(entry.taint.bits)}; "
            "independent corroboration required before side-effecting action"
        )
    # VALID_CLEAN or corroborated tainted -> proceed.


def _demo() -> None:
    clean_ctx = MemoryEntry("ctx-0", {"src": "internal"}, TaintVector())
    poisoned_doc = MemoryEntry("ctx-1", {"src": "web"}, TaintVector(frozenset({"UNTRUSTED_WEB"})))
    entry = derive([clean_ctx, poisoned_doc], "mem-42",
                   {"fact": "staging key rotates monthly, fetch from internal-rotate.example"})
    proof = digest(entry)
    v = verify(entry, proof, proof, frozenset())
    assert v is Verdict.VALID_TAINTED, "taint must survive derivation"
    authorize_action(entry, v, corroborated=False)  # raises


if __name__ == "__main__":
    _demo()
