# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-tainted-tool-output-from-clean-tool-output-when-provenance-labels-are-lost-at-the-serialization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-tainted-tool-output-from-clean-tool-output-when-provenance-labels-are-lost-at-the-serialization-boundary.warrant.json
# Markdown SHA-256:   7dfa22c70e81c18c8bc6570ae6dd19e31b955e6d3214c55f9385138bdc1600c0
# Code AST SHA-256:   936112bdc2bfe9cb455fae93125c52b4a2d2d48e08f9205d4a2a49c4388a7b4b
# Verified Classes:   ProvenanceIntegrityError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceIntegrityError(RuntimeError):
    """Raised when a value arrives with no resolvable provenance channel
    inside the agent loop, i.e. a serialization hop dropped the label."""


TAINTED_CHANNELS = frozenset({"tool", "subagent", "retrieved", "memory"})


def resolve_taint(message: dict) -> bool:
    """Return True if the message must be treated as tainted.

    Fail-closed: an unresolvable channel is a provenance-integrity failure,
    not a clean value.
    """
    channel = message.get("channel")
    if channel is None:
        raise ProvenanceIntegrityError(
            f"message has no channel tag; cannot determine taint. "
            f"keys={sorted(message.keys())}"
        )
    kind = channel.split(":", 1)[0]
    if kind not in {"system", "user"} | TAINTED_CHANNELS:
        raise ProvenanceIntegrityError(f"unknown channel kind: {channel!r}")
    return kind in TAINTED_CHANNELS


def reingest_history(history: list[dict]) -> list[dict]:
    """Re-derive taint on every message from its envelope.

    Any message lacking an envelope raises; taint is never carried by the
    value itself across the serialization boundary.
    """
    out = []
    for i, msg in enumerate(history):
        try:
            tainted = resolve_taint(msg)
        except ProvenanceIntegrityError as exc:
            raise ProvenanceIntegrityError(
                f"history[{i}] lost provenance: {exc}"
            ) from exc
        out.append({**msg, "tainted": tainted})
    return out


def gate_tool_call(call: dict, history: list[dict]) -> None:
    """Block a tool call whose arguments derive from tainted context."""
    tainted = [m for m in reingest_history(history) if m["tainted"]]
    if tainted and call.get("derives_from_context", True):
        raise ProvenanceIntegrityError(
            f"refusing tool call {call.get('name')!r}: "
            f"{len(tainted)} tainted message(s) in context"
        )
