# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-tool-output-re-enters-the-context-window-as-plain-text.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-tool-output-re-enters-the-context-window-as-plain-text.warrant.json
# Markdown SHA-256:   c33b4bd8409bc324b0f50aed040001fc827cf05f65038d2f8686d2d8357bfd54
# Code AST SHA-256:   195fad3efffa489419d32e9a160fd1d5dfffea04383ea84e8063eee4ca2b6ae1
# Verified Classes:   TaintLaunderingError, Message, TaintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when tainted content reaches a sink via a model-authored
    transformation whose provenance was not conserved."""


@dataclass
class Message:
    msg_id: str
    author: str                 # "tool" | "assistant" | "user"
    text: str
    taint: bool = False
    derived_from: list[str] = field(default_factory=list)
    declassified: bool = False


class TaintLedger:
    """Out-of-band provenance ledger. The model never touches this."""

    def __init__(self) -> None:
        self.messages: dict[str, Message] = {}
        self.tainted_literals: set[str] = set()

    def ingest_tool_output(self, msg_id: str, text: str, literals: set[str]) -> None:
        self.messages[msg_id] = Message(msg_id, "tool", text, taint=True)
        self.tainted_literals |= literals

    def record_derivation(
        self, derived_id: str, source_ids: list[str], text: str, literals: set[str]
    ) -> None:
        # Core rule: a model-authored message inherits the UNION of its
        # sources' taint. The model cannot self-declassify by omission.
        inherited = any(self.messages[s].taint for s in source_ids)
        self.messages[derived_id] = Message(
            derived_id, "assistant", text, taint=inherited,
            derived_from=list(source_ids),
        )
        if inherited:
            self.tainted_literals |= literals

    def declassify(self, msg_id: str, approver: str) -> None:
        if approver == "model":
            raise TaintLaunderingError(
                f"model attempted to self-declassify {msg_id}; "
                "declassification requires an out-of-band approver"
            )
        self.messages[msg_id].declassified = True
        self.messages[msg_id].taint = False

    def check_sink(self, tool_name: str, args: dict[str, object]) -> None:
        for key, val in args.items():
            literal = str(val)
            if literal in self.tainted_literals:
                raise TaintLaunderingError(
                    f"sink {tool_name}.{key}={literal!r} is derived from tainted "
                    "content via an untracked summarization hop; block and "
                    "request explicit declassification"
                )


def run_turn(ledger: TaintLedger, tool_name: str, args: dict[str, object]) -> None:
    ledger.check_sink(tool_name, args)
    # ... execute ...
