# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-mcp-tool-result-before-it-re-enters-the-reasoning-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-mcp-tool-result-before-it-re-enters-the-reasoning-loop.warrant.json
# Markdown SHA-256:   0cafdf71317d26ce7eddd4df673b660b5758161bd6eff4d3c660af9edf0f462a
# Code AST SHA-256:   5c0790635710f7a552f496e89449476de6e5ce6f8ff5590a3278833d0fc7c83e
# Verified Classes:   TaintViolation, TaintedValue, ToolCall, TaintRuntime
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal


class TaintViolation(RuntimeError):
    """Raised when a tainted MCP response reaches an executing sink."""
    pass


Origin = Literal["trusted", "untrusted"]
ToolClass = Literal["executes", "read-only-inert"]


@dataclass
class TaintedValue:
    payload: str
    origin: Origin
    lineage: frozenset[str] = field(default_factory=frozenset)  # source ids


@dataclass
class ToolCall:
    tool: str
    tool_class: ToolClass
    args: dict[str, str]


class TaintRuntime:
    def __init__(self, trust_allowlist: set[str]):
        self.trust_allowlist = trust_allowlist
        self.taint_sources: set[str] = set()

    def ingest(self, server_id: str, body: str) -> TaintedValue:
        origin: Origin = "trusted" if server_id in self.trust_allowlist else "untrusted"
        if origin == "untrusted":
            self.taint_sources.add(server_id)
        return TaintedValue(payload=body, origin=origin, lineage=frozenset({server_id}))

    def _is_tainted_reachable(self, arg: str) -> bool:
        # Reachability by substring against any tainted source body.
        # In production this is a provenance graph, not substring matching;
        # the point is that the check is provenance-based, not content-based.
        return any(src in arg for src in self.taint_sources)

    def emit(self, call: ToolCall) -> ToolCall:
        if call.tool_class == "executes":
            for name, value in call.args.items():
                if self._is_tainted_reachable(value):
                    raise TaintViolation(
                        f"tool '{call.tool}' arg '{name}' is taint-reachable; "
                        f"quarantined pending explicit declassification"
                    )
        return call

    def declassify(self, value: TaintedValue, approver: str) -> TaintedValue:
        if not approver:
            raise TaintViolation("declassification requires a logged approver")
        # Explicit, auditable declassification — never model self-assertion.
        return TaintedValue(payload=value.payload, origin="trusted", lineage=value.lineage)


def run_turn(runtime: TaintRuntime, server_id: str, body: str, call: ToolCall) -> ToolCall:
    tainted = runtime.ingest(server_id, body)
    if tainted.origin == "untrusted":
        # Model may reason over tainted text, but the sink check below decides execution.
        pass
    return runtime.emit(call)
