# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-taint-label-to-clear-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-taint-label-to-clear-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   c671f50e4aecb5961a1409e622fd52fe776b1d63d860110580687b6b380fc7a0
# Code AST SHA-256:   657ab5c5997a772a9df0dddd1f9ec9714bf482b631be42331de62233ccf11732
# Verified Classes:   TaintLaunderingError, ProvenanceHandle, InterceptorState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaintLaunderingError(RuntimeError):
    """Raised when an agent-invocable state mutation alters a taint label
    without a corresponding out-of-band approval event."""


@dataclass
class ProvenanceHandle:
    token: str
    taint: str            # "clean" | "untrusted"
    source: str


@dataclass
class InterceptorState:
    # Held outside the agent's write reach; agent sees only opaque tokens.
    handles: dict[str, ProvenanceHandle] = field(default_factory=dict)
    label_writes: list[tuple[str, str, str]] = field(default_factory=list)


def issue_handle(state: InterceptorState, taint: str, source: str) -> str:
    token = hashlib.sha256(f"{taint}:{source}:{len(state.handles)}".encode()).hexdigest()[:16]
    state.handles[token] = ProvenanceHandle(token=token, taint=taint, source=source)
    return token


def assert_mutation_preserves_taint(
    state: InterceptorState,
    before: dict[str, str],
    after: dict[str, str],
    approval_event: str | None,
) -> None:
    """Invariant: a mutation primitive (checkpoint/restore/compact/distill)
    must not change any handle's taint unless an approval event is present."""
    for token, prior_taint in before.items():
        current = state.handles.get(token)
        if current is None:
            raise TaintLaunderingError(
                f"mutation dropped provenance handle {token} (source={before.get(token)!r}); "
                "handle loss is treated as taint laundering"
            )
        if current.taint != prior_taint and approval_event is None:
            raise TaintLaunderingError(
                f"handle {token} taint changed {prior_taint!r}->{current.taint!r} "
                f"without approval; source={current.source!r}"
            )
    if approval_event is not None:
        state.label_writes.append(("approved_clear", approval_event, "audit"))


def gate_tool_call(
    state: InterceptorState,
    tool: str,
    arg_tokens: list[str],
    side_effecting: set[str],
) -> None:
    """Boundary check: evaluate provenance of the *arguments*, not a scalar
    agent label. Tainted arguments block side-effecting tools outright."""
    if tool not in side_effecting:
        return
    for token in arg_tokens:
        handle = state.handles.get(token)
        if handle is None:
            raise TaintLaunderingError(f"tool {tool!r} called with unknown provenance token {token!r}")
        if handle.taint == "untrusted":
            raise TaintLaunderingError(
                f"denied {tool!r}: argument token {token} carries untrusted "
                f"provenance from {handle.source!r}"
            )
