# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-a-tool-boundary-when-the-exfiltration-channel-is-a-semantically-valid-taint-cleared-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-a-tool-boundary-when-the-exfiltration-channel-is-a-semantically-valid-taint-cleared-tool-call.warrant.json
# Markdown SHA-256:   bc35d11045a8cee19b8502fef7f73c2808d4293f88f735cf2568b9448083f281
# Code AST SHA-256:   88711d39f4eefdf157e3930a98cc8394ae1f0d76e78dcba7e789bb4c9c1c65bf
# Verified Classes:   TaintLaunderingError, Label, Value
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class TaintLaunderingError(RuntimeError):
    """Raised when a taint-clearing tool returns bytes that survive from tainted input."""


class Label(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"


@dataclass
class Value:
    data: str
    label: Label


# Tools permitted to clear taint are declared, but clearing is decided per call.
CLEARING_TOOLS = {"summarize", "format_json", "translate"}
IDENTITY_MODES = {"verbatim", "echo", "raw"}


def _tainted_spans_survive(tainted_input: str, output: str, min_span: int = 8) -> bool:
    """Containment test: does any tainted span of sufficient length appear in output?"""
    for i in range(len(tainted_input) - min_span + 1):
        span = tainted_input[i : i + min_span]
        if span in output:
            return True
    return False


def invoke_clearing_tool(
    tool: str,
    params: dict,
    arg: Value,
    tool_fn,
) -> Value:
    if tool not in CLEARING_TOOLS:
        raise TaintLaunderingError(f"tool {tool!r} is not authorized to clear taint")

    # Identity modes are structurally incapable of destroying taint.
    mode = str(params.get("mode", "")).lower()
    if mode in IDENTITY_MODES:
        raise TaintLaunderingError(
            f"tool {tool!r} invoked with identity mode {mode!r}; "
            "identity transforms may not clear taint"
        )

    output = tool_fn(arg.data, **params)

    if arg.label is Label.UNTRUSTED and _tainted_spans_survive(arg.data, output):
        raise TaintLaunderingError(
            f"tool {tool!r} returned output containing a surviving tainted span; "
            "refusing to relabel as TRUSTED"
        )

    return Value(data=output, label=Label.TRUSTED)


def egress(sink_value: Value) -> None:
    if sink_value.label is Label.UNTRUSTED:
        raise TaintLaunderingError("egress blocked: value still carries UNTRUSTED label")
    # ... post to webhook ...
