# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-result-as-tainted-provenance-label-propagation-across-agent-tool-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-result-as-tainted-provenance-label-propagation-across-agent-tool-boundaries.warrant.json
# Markdown SHA-256:   9d00afe554e33f85b9f0e7979c894db51a99040b2d413cb8244804dc77714ff4
# Code AST SHA-256:   f1f137a3b081ba5441f234cd32b171361df37ef17bd959014cd43a135b973289
# Verified Classes:   TaintLaunderingError, Labeled, Declassification
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a tool returns a clean label from tainted inputs
    without an explicit, value-bound declassification event."""


@dataclass(frozen=True)
class Labeled:
    value: object
    taint: FrozenSet[str] = field(default_factory=frozenset)

    def is_tainted(self) -> bool:
        return bool(self.taint)


def _value_hash(value: object) -> str:
    return hashlib.sha256(repr(value).encode()).hexdigest()


@dataclass(frozen=True)
class Declassification:
    value_hash: str
    principal: str  # human principal, never the agent itself
    reason: str


def apply_tool(
    tool_name: str,
    declared_clean: bool,
    args: list[Labeled],
    result_value: object,
    declassifications: Optional[list[Declassification]] = None,
) -> Labeled:
    """Compute the output label for a tool result under causal-origin
    preservation. The output inherits the union of input taints unless a
    declassification bound to this exact value is presented by a human
    principal."""
    inherited = frozenset().union(*(a.taint for a in args))
    if not inherited:
        return Labeled(result_value, frozenset())

    declassifications = declassifications or []
    h = _value_hash(result_value)
    for d in declassifications:
        if d.value_hash == h and d.principal != "agent":
            return Labeled(result_value, frozenset())

    if declared_clean:
        # The tool claims clean output from tainted input. This is the
        # laundering boundary: reject unless declassified above.
        raise TaintLaunderingError(
            f"tool {tool_name!r} declared clean output from tainted inputs "
            f"{sorted(inherited)}; value_hash={h[:12]} has no human "
            f"declassification. Register the tool as label-preserving."
        )

    return Labeled(result_value, inherited)


def check_sink(sink_name: str, value: Labeled) -> None:
    """Single enforcement point. Refuse tainted values at effectful sinks."""
    if value.is_tainted():
        raise TaintLaunderingError(
            f"sink {sink_name!r} refused tainted value "
            f"(labels={sorted(value.taint)})"
        )
