# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-tainted-capability-into-a-clean-sub-agent-through-mcp-tool-result-re-serialization.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-tainted-capability-into-a-clean-sub-agent-through-mcp-tool-result-re-serialization.warrant.json
# Markdown SHA-256:   f78d1382c81a188c92ef256c31bf29226deb6dd921ceaeeb867a81076b82e50f
# Code AST SHA-256:   0a49cb5a8e761dbd5013abf4ef4bd7088bc5b52e0472ac52011b770a60c0ec11
# Verified Classes:   TaintLaunderingError, Tainted
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any, Literal

Taint = Literal["CLEAN", "UNTRUSTED"]

class TaintLaunderingError(RuntimeError):
    """Raised when a tainted value crosses a serialization edge without its tag."""

@dataclass(frozen=True)
class Tainted:
    value: Any
    taint: Taint

    def to_wire(self) -> dict:
        # In-band tag: survives every copy and serialization.
        return {"value": self.value, "taint": self.taint}

def deserialize_wire(payload: dict) -> Tainted:
    # Fail-closed: a missing tag is treated as UNTRUSTED, never CLEAN.
    tag = payload.get("taint")
    if tag not in ("CLEAN", "UNTRUSTED"):
        return Tainted(payload.get("value"), "UNTRUSTED")
    return Tainted(payload["value"], tag)

def enforce_warrant(arg: Tainted, operation: str, allowed_taint: set[Taint]) -> None:
    if operation == "http.post" and arg.taint not in allowed_taint:
        raise TaintLaunderingError(
            f"operation {operation!r} denied: argument taint={arg.taint!r} "
            f"not in allowed {allowed_taint!r}; label may have been laundered"
        )

def handoff_to_subagent(raw_payload: dict, operation: str) -> None:
    arg = deserialize_wire(raw_payload)
    # Data-constrained warrant: egress only for CLEAN bodies.
    enforce_warrant(arg, operation, allowed_taint={"CLEAN"})
