# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-result-as-tainted-and-where-does-provenance-laundering-occur-across-mcp-a2a-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-tool-result-as-tainted-and-where-does-provenance-laundering-occur-across-mcp-a2a-hops.warrant.json
# Markdown SHA-256:   6ab5d2dee0a68a00afc9367e2aab97a0123180be893b453153485770402039fc
# Code AST SHA-256:   76b68befdc3503e2ff88c14a28ece0294a7991e684c4ae0f593b95869b2ee894
# Verified Classes:   Taint, TaintLaunderingError, Labeled
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Any


class Taint(IntEnum):
    TRUSTED = 0
    INTERNAL = 1
    EXTERNAL = 2

    def join(self, other: "Taint") -> "Taint":
        return Taint(max(int(self), int(other)))


class TaintLaunderingError(RuntimeError):
    """Raised when a cross-boundary hop drops, downgrades, or fails to carry taint."""


@dataclass(frozen=True)
class Labeled:
    value: Any
    taint: Taint
    sanitizer: str | None = None


REGISTERED_SANITIZERS: dict[str, Taint] = {
    # name -> maximum output taint this transform is permitted to produce
    "extract_numeric_v1": Taint.TRUSTED,
    "extract_json_schema_v1": Taint.INTERNAL,
}


def carry_across_a2a(label: Labeled, wire_meta: dict[str, Any] | None) -> Labeled:
    """Reconstruct taint from an inbound A2A/MCP message.

    Absent or unverifiable provenance is EXTERNAL (fail-closed).
    """
    if wire_meta is None or "taint" not in wire_meta:
        return Labeled(value=label.value, taint=Taint.EXTERNAL)
    try:
        carried = Taint(int(wire_meta["taint"]))
    except (TypeError, ValueError) as exc:
        raise TaintLaunderingError(
            f"unparseable taint label on inbound hop: {wire_meta.get('taint')!r}"
        ) from exc
    # Never let a hop lower taint; join with the locally-known floor.
    return Labeled(value=label.value, taint=label.taint.join(carried))


def apply_sanitizer(label: Labeled, name: str) -> Labeled:
    if name not in REGISTERED_SANITIZERS:
        raise TaintLaunderingError(
            f"unregistered sanitizer {name!r}; model paraphrase is not a sanitizer"
        )
    ceiling = REGISTERED_SANITIZERS[name]
    if ceiling > label.taint:
        # A sanitizer cannot raise taint; that would be fabrication.
        raise TaintLaunderingError(
            f"sanitizer {name!r} declares ceiling {ceiling.name} above input {label.taint.name}"
        )
    return Labeled(value=label.value, taint=ceiling, sanitizer=name)


def verify_monotonic(input_label: Labeled, output_label: Labeled) -> None:
    """A remote agent's output taint must dominate its input taint, unless a
    registered sanitizer is named on the output."""
    if output_label.sanitizer is not None:
        if output_label.sanitizer not in REGISTERED_SANITIZERS:
            raise TaintLaunderingError(
                f"remote claimed unregistered sanitizer {output_label.sanitizer!r}"
            )
        return
    if output_label.taint < input_label.taint:
        raise TaintLaunderingError(
            f"taint downgrade across hop: {input_label.taint.name} -> "
            f"{output_label.taint.name} with no declared sanitizer"
        )


def gate_side_effect(tool: str, args: list[Labeled]) -> None:
    joined = Taint.TRUSTED
    for a in args:
        joined = joined.join(a.taint)
    if tool in {"write_file", "send_email", "exec_shell"} and joined >= Taint.EXTERNAL:
        raise TaintLaunderingError(
            f"side-effecting tool {tool!r} invoked with joined taint {joined.name}"
        )
