# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-confinement-when-a-tool-result-is-re-entered-through-the-model-s-own-summarization-pass.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-confinement-when-a-tool-result-is-re-entered-through-the-model-s-own-summarization-pass.warrant.json
# Markdown SHA-256:   d10de2cef28ee5814f48f431920f99dc70603e82e1923568fe93c40031378341
# Code AST SHA-256:   e045b83d6362099ca431a32cecef6bba67554e3e27601e1ef22ffa8b0dc4c64c
# Verified Classes:   Origin, TaintLaunderingError, Envelope, ProvenanceStore
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class Origin(str, Enum):
    USER = "user"
    TOOL = "tool"
    ASSISTANT = "assistant"
    COMPACTION = "compaction"


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged capability is invoked from an instruction
    whose derivation chain includes tainted content that was not propagated."""


@dataclass
class Envelope:
    msg_id: str
    origin: Origin
    tainted: bool
    derived_from: list[str] = field(default_factory=list)


class ProvenanceStore:
    def __init__(self) -> None:
        self._by_id: dict[str, Envelope] = {}

    def register(self, env: Envelope) -> None:
        self._by_id[env.msg_id] = env

    def ancestry_tainted(self, msg_id: str, _seen: Optional[set[str]] = None) -> bool:
        seen = _seen if _seen is not None else set()
        if msg_id in seen:
            return False
        seen.add(msg_id)
        env = self._by_id[msg_id]
        if env.tainted:
            return True
        return any(self.ancestry_tainted(p, seen) for p in env.derived_from)


def compact(store: ProvenanceStore, source_ids: list[str], out_id: str) -> Envelope:
    """The ONLY permitted producer of derived messages. It must propagate
    taint from every source, including through prior compactions."""
    sources = [store._by_id[s] for s in source_ids]
    derived_tainted = any(store.ancestry_tainted(s.msg_id) for s in sources)
    env = Envelope(
        msg_id=out_id,
        origin=Origin.COMPACTION,
        tainted=derived_tainted,  # structural, not model-decided
        derived_from=[s.msg_id for s in sources],
    )
    store.register(env)
    return env


def invoke_privileged(
    store: ProvenanceStore, instruction_id: str, capability: str
) -> None:
    if store.ancestry_tainted(instruction_id):
        raise TaintLaunderingError(
            f"capability '{capability}' refused: instruction {instruction_id} "
            f"has tainted ancestry (laundered through compaction?)"
        )
    # capability dispatch proceeds only for clean ancestry


# --- failure trace reproduction ---
store = ProvenanceStore()
store.register(Envelope("u1", Origin.USER, tainted=False))
store.register(Envelope("t1", Origin.TOOL, tainted=True))  # contract body w/ embedded directive

# Correct path: compaction propagates taint -> privileged call refused.
compact(store, ["t1"], "c1")
try:
    invoke_privileged(store, "c1", "send_email")
except TaintLaunderingError as e:
    print("CONTAINED:", e)

# Buggy path: a naive summarizer emits a fresh clean assistant message.
store.register(Envelope("a1", Origin.ASSISTANT, tainted=False, derived_from=[]))
invoke_privileged(store, "a1", "send_email")  # fires — this is the laundering hole
