# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-aware-tool-call-gating-when-the-taint-label-itself-is-laundered-through-a-summarization-step.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-aware-tool-call-gating-when-the-taint-label-itself-is-laundered-through-a-summarization-step.warrant.json
# Markdown SHA-256:   1ed3d7cb2c329562c8f5c78c975993f223be7c9398183b06ddd3082f1e58c783
# Code AST SHA-256:   f8cc4cd519d3ef04cded8940c2998f5eaaa3d15d6164550986c5818cab1d1527
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when an irreversible egress call has tainted ancestry without declassification."""
    pass


TAINTED = ("tainted:web", "tainted:peer", "tainted:tool", "tainted:transitive")
IRREVERSIBLE_EGRESS = {"post_json", "send_email", "run_shell", "http_request"}


def gate_tool_call(
    tool_name: str,
    arg_spans: list[dict],
    turn_ancestry: set[str],
    declassifications: list[dict],
) -> None:
    """
    arg_spans: [{"span_id": ..., "labels": set[str], "source": "model_literal"|"tool_output"|...}]
    turn_ancestry: union of taint labels across all spans in this turn's causal ancestry,
                   including spans produced by model-mediated transforms (summarize, plan, extract).
    declassifications: [{"destination": "host", "payload_class": "report", "approved_by": "..."}]
    """
    if tool_name not in IRREVERSIBLE_EGRESS:
        return  # reversible egress is audited downstream, not gated here

    ancestry_tainted = any(lbl in TAINTED for lbl in turn_ancestry)
    span_tainted = any(
        any(lbl in TAINTED for lbl in span.get("labels", set())) for span in arg_spans
    )

    if not (ancestry_tainted or span_tainted):
        return

    # A tainted-ancestry egress call is permitted only under an explicit,
    # pre-registered declassification covering destination and payload class.
    destination = _extract_destination(arg_spans)
    payload_class = _classify_payload(arg_spans)
    for d in declassifications:
        if d.get("destination") == destination and d.get("payload_class") == payload_class:
            return  # sanctioned laundering path; audit log already records it

    raise TaintLaunderingError(
        f"irreversible egress '{tool_name}' to {destination!r} "
        f"(payload_class={payload_class!r}) has tainted causal ancestry "
        f"{sorted(turn_ancestry)} with no matching declassification. "
        f"Span-level labels alone would have missed this: "
        f"ancestry_tainted={ancestry_tainted}, span_tainted={span_tainted}."
    )


def _extract_destination(arg_spans: list[dict]) -> str:
    for span in arg_spans:
        if span.get("role") == "url":
            return span.get("value", "")
    return "<unknown>"


def _classify_payload(arg_spans: list[dict]) -> str:
    for span in arg_spans:
        if span.get("role") == "body":
            return span.get("payload_class", "opaque")
    return "opaque"
