# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-a-sandboxed-retrieval-boundary-and-why-provenance-labels-decay-at-the-summarizer-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-a-sandboxed-retrieval-boundary-and-why-provenance-labels-decay-at-the-summarizer-handoff.warrant.json
# Markdown SHA-256:   bd2c38ed32825faaf9ba08427805b6f40e7dea2540e34fe219e8999501ec1374
# Code AST SHA-256:   6f1bf5d9aa9686599e95034bb262d37ad844af159de4d3bfe3b0fab75e238973
# Verified Classes:   TaintLaunderingError, Span, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged tool call receives an argument whose
    provenance reaches a tainted span without a declassification record."""


@dataclass
class Span:
    span_id: str
    taint: str  # "trusted" | "untrusted"
    parents: list[str] = field(default_factory=list)
    declassified_by: Optional[str] = None  # principal, if declassified


@dataclass
class ToolCall:
    tool: str
    privileged: bool
    arg_span_ids: list[str]


PRIVILEGED_TOOLS = {
    "update_payout_account",
    "send_email",
    "write_credential",
    "network_egress",
}


def _tainted_ancestor(span_id: str, spans: dict[str, Span], seen: set[str]) -> Optional[str]:
    """Return the id of the nearest tainted ancestor reachable from span_id,
    stopping at a declassification event. Returns None if the lineage is clean."""
    if span_id in seen:
        return None
    seen.add(span_id)
    span = spans[span_id]
    if span.declassified_by is not None:
        return None
    if span.taint == "untrusted":
        return span_id
    for parent_id in span.parents:
        hit = _tainted_ancestor(parent_id, spans, seen)
        if hit is not None:
            return hit
    return None


def enforce_taint_gate(call: ToolCall, spans: dict[str, Span]) -> None:
    """Admit, quarantine, or require declassification for a tool call.

    Invariant: a privileged call's arguments must have no tainted ancestor
    reachable without an intervening declassification record.
    """
    if not call.privileged and call.tool not in PRIVILEGED_TOOLS:
        return  # non-privileged: admit, output re-tainted by caller

    for arg_id in call.arg_span_ids:
        if arg_id not in spans:
            raise TaintLaunderingError(
                f"tool {call.tool!r} references unknown span {arg_id!r}; "
                "cannot verify lineage"
            )
        hit = _tainted_ancestor(arg_id, spans, set())
        if hit is not None:
            path = _lineage_path(hit, arg_id, spans)
            raise TaintLaunderingError(
                f"quarantine: privileged tool {call.tool!r} argument {arg_id!r} "
                f"reaches tainted span {hit!r} with no declassification; "
                f"path={path}"
            )


def _lineage_path(ancestor: str, descendant: str, spans: dict[str, Span]) -> list[str]:
    """Best-effort path reconstruction for the quarantine record."""
    if ancestor == descendant:
        return [descendant]
    for parent_id in spans[descendant].parents:
        sub = _lineage_path(ancestor, parent_id, spans)
        if sub:
            return sub + [descendant]
    return []


# --- trace from the observed incident ---
spans = {
    "pdf#chunk7": Span("pdf#chunk7", "untrusted"),
    "summary#span22": Span("summary#span22", "trusted", parents=["pdf#chunk7"]),
    "arg#iban": Span("arg#iban", "trusted", parents=["summary#span22"]),
}

call = ToolCall(
    tool="update_payout_account",
    privileged=True,
    arg_span_ids=["arg#iban"],
)

try:
    enforce_taint_gate(call, spans)
except TaintLaunderingError as e:
    print(f"BLOCKED: {e}")
    # -> BLOCKED: quarantine: privileged tool 'update_payout_account'
    #    argument 'arg#iban' reaches tainted span 'pdf#chunk7' with no
    #    declassification; path=['pdf#chunk7', 'summary#span22', 'arg#iban']
