# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-sandboxed-tool-returns-a-value-through-a-serialization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-sandboxed-tool-returns-a-value-through-a-serialization-boundary.warrant.json
# Markdown SHA-256:   44026c01b8b40dbe1414de38c53ad8ffcbe79e486b67d6caa8c5e9e0e1470652
# Code AST SHA-256:   b70bfc62ae63501feab4cd6fe244862cb6352718d2aacafd085e9eb0d310dac8
# Verified Classes:   TaintLaunderingError, Taint, ToolResult, TaintLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any
import json


class TaintLaunderingError(RuntimeError):
    """Raised when a trusted result is constructed from an untrusted call."""


@dataclass(frozen=True)
class Taint:
    untrusted: bool
    sources: frozenset = field(default_factory=frozenset)

    def join(self, other: "Taint") -> "Taint":
        return Taint(
            untrusted=self.untrusted or other.untrusted,
            sources=self.sources | other.sources,
        )


TRUSTED = Taint(untrusted=False)
UNTRUSTED = Taint(untrusted=True, sources=frozenset({"call_site"}))


@dataclass
class ToolResult:
    value: Any
    taint: Taint

    def __post_init__(self):
        # Fail-closed: a result must carry an explicit taint.
        if self.taint is None:
            raise TaintLaunderingError(
                "ToolResult constructed with taint=None; default-trusted is a fail-open"
            )


class TaintLedger:
    """Call-id -> taint, written before dispatch, joined after deserialization."""

    def __init__(self):
        self._pending: dict[str, Taint] = {}

    def register(self, call_id: str, arg_taint: Taint) -> None:
        # Result is at least as tainted as the call site and its arguments.
        self._pending[call_id] = UNTRUSTED.join(arg_taint)

    def join_on_return(self, call_id: str, raw_stdout: bytes) -> ToolResult:
        if call_id not in self._pending:
            # Unknown call-id: fail closed, do not trust the payload.
            call_taint = UNTRUSTED
        else:
            call_taint = self._pending.pop(call_id)
        try:
            value = json.loads(raw_stdout)
        except json.JSONDecodeError as e:
            raise TaintLaunderingError(f"unparseable tool output: {e}") from e
        # Content is never inspected for taint; provenance is the only source.
        return ToolResult(value=value, taint=call_taint)


def planner_construct_command(result: ToolResult) -> ToolResult:
    """Derived values must inherit the join of all inputs."""
    if not isinstance(result.value, dict) or "cmd" not in result.value:
        raise TaintLaunderingError("unexpected tool result shape")
    # The derived command is tainted by the input; formatting does not launder.
    return ToolResult(value={"cmd": str(result.value["cmd"])}, taint=result.taint)


def dispatch_to_privileged_sink(cmd: ToolResult) -> None:
    if cmd.taint.untrusted:
        raise TaintLaunderingError(
            f"refusing to execute tainted command from sources={sorted(cmd.taint.sources)}"
        )
    # ... execute ...
