# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-sandboxed-tool-result-as-tainted-after-the-sandbox-reports-success.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-sandboxed-tool-result-as-tainted-after-the-sandbox-reports-success.warrant.json
# Markdown SHA-256:   d1d871c2bb77fb2dd099af1fab72dda81af891e9cf4338bb660c08fbaeaab8b5
# Code AST SHA-256:   dafe0d6c468391e7f9f85db767470fd46f5f59186fa9b15a999a03d546a725f8
# Verified Classes:   TaintLaunderingError, Tainted
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when an open-text tool result reaches the instruction channel
    without surviving provenance through a type-erasure boundary."""
    pass


class Tainted:
    """A payload with provenance that must survive serialization hops."""
    def __init__(self, value, source: str, open_text: bool):
        self.value = value
        self.source = source
        self.open_text = open_text
        self.tainted = True

    def to_wire(self) -> dict:
        # Provenance is serialized, not dropped.
        return {"value": self.value, "source": self.source,
                "open_text": self.open_text, "tainted": self.tainted}

    @classmethod
    def from_wire(cls, wire: dict) -> "Tainted":
        if "tainted" not in wire:
            # Missing provenance is not "clean" -- it is unknown, fail closed.
            raise TaintLaunderingError(
                f"sandbox return from {wire.get('source', '?')} "
                f"lost taint metadata at serialization boundary")
        return cls(wire["value"], wire["source"], wire["open_text"])


def admit_to_instruction_channel(result: dict, sandbox_violations: list):
    """Admit a sandboxed tool result into the planner's instruction channel.
    A clean sandbox run (violations == []) is NOT sufficient for open text."""
    payload = Tainted.from_wire(result)

    if payload.open_text and payload.tainted:
        # Containment succeeded, but the bytes can still carry instructions.
        raise TaintLaunderingError(
            f"open-text output from {payload.source} is still tainted "
            f"(sandbox_violations={sandbox_violations}); "
            f"route to quarantined data context, not instruction channel")
    return payload.value
