# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-mcp-tool-response-before-it-enters-the-reasoning-trace-rather-than-after.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-mcp-tool-response-before-it-enters-the-reasoning-trace-rather-than-after.warrant.json
# Markdown SHA-256:   13eb90717976dcce9ae685a7f9c417a48f605906e4f9e854040f9c1a7a4c3a51
# Code AST SHA-256:   7c87997d04de49c64287c35ffc7ba5ed1badcd02e1b5ae45eb9bbb1e528f8a24
# Verified Classes:   TaintLaunderingError, Span, QuarantineTrace
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Literal


class TaintLaunderingError(RuntimeError):
    """Raised when a derivation attempts to consume a quarantined span
    without an explicit, justified declassification."""


@dataclass
class Span:
    origin: Literal["model", "tool"]
    text: str
    tainted: bool
    span_id: str = field(default="")

    def __post_init__(self) -> None:
        if not self.span_id:
            self.span_id = hashlib.sha256(
                f"{self.origin}:{self.text}".encode()
            ).hexdigest()[:16]


class QuarantineTrace:
    """Ingest-boundary quarantine: tainted tool spans never enter the trace
    proper. Derivations must declassify explicitly, and the derivative
    inherits taint unless the declassification is justified and logged."""

    def __init__(self) -> None:
        self.trace: list[Span] = []
        self.quarantine: dict[str, Span] = {}
        self.admissions: list[tuple[str, str]] = []

    def ingest_tool_response(self, text: str) -> Span:
        span = Span(origin="tool", text=text, tainted=True)
        self.quarantine[span.span_id] = span
        return span

    def append_model_span(self, text: str) -> Span:
        span = Span(origin="model", text=text, tainted=False)
        self.trace.append(span)
        return span

    def derive_from_quarantine(
        self, span_id: str, justification: str, derived_text: str
    ) -> Span:
        if span_id not in self.quarantine:
            raise TaintLaunderingError(
                f"span {span_id} is not in quarantine; cannot derive"
            )
        if not justification or not justification.strip():
            raise TaintLaunderingError(
                f"declassification of {span_id} requires a typed justification; "
                "refusing to admit into reasoning trace"
            )
        # Derivative inherits taint by construction: it is a restatement of a
        # tainted span, so it is quarantined, not admitted.
        derivative = Span(origin="tool", text=derived_text, tainted=True)
        self.quarantine[derivative.span_id] = derivative
        self.admissions.append((span_id, justification))
        return derivative

    def read_for_planning(self) -> list[Span]:
        # Only untainted trace spans are visible to the planner. No raw tool
        # text, and no untagged paraphrase of it, can reach the model here.
        for span in self.trace:
            if span.tainted:
                raise TaintLaunderingError(
                    f"tainted span {span.span_id} found in trace proper"
                )
        return list(self.trace)


def plan_against_tool_output(trace: QuarantineTrace, span_id: str) -> list[Span]:
    # A reflection step that wants to reason about a tool response must
    # declassify first; a bare derivation is refused.
    if span_id in trace.quarantine:
        raise TaintLaunderingError(
            f"planner attempted to consume quarantined span {span_id} "
            "without declassification; this is the laundering path"
        )
    return trace.read_for_planning()
