# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-aware-tool-sandboxing-when-a-single-injected-span-silently-reclassifies-an-entire-context-window-as-untrusted.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-aware-tool-sandboxing-when-a-single-injected-span-silently-reclassifies-an-entire-context-window-as-untrusted.warrant.json
# Markdown SHA-256:   ece60c008aa3b37a14efe4d61a49a09960fc4de15d15f7164681a771d3b7c6b9
# Code AST SHA-256:   14bd8cf035f023902835ff17271bed95d02b475accc8e112a04846ed89b29707
# Verified Classes:   TaintViolationError, Span, DerivationGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

TRUSTED = "trusted"
UNTRUSTED = "untrusted"

DESTRUCTIVE_CAPABILITIES = frozenset({"crm_write", "transfer_funds", "exec", "send_email"})


class TaintViolationError(RuntimeError):
    """Raised when a tool call's derivation set contains untrusted spans
    but the call targets a destructive capability."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    taint: FrozenSet[str]
    inputs: FrozenSet[str] = field(default_factory=frozenset)


@dataclass
class DerivationGraph:
    spans: dict = field(default_factory=dict)

    def add(self, span: Span) -> None:
        # Invariant: taint(span) must equal the join of taint over its inputs.
        expected = frozenset()
        for parent_id in span.inputs:
            expected = expected | self.spans[parent_id].taint
        if span.taint != expected:
            raise TaintViolationError(
                f"span {span.span_id} declares taint {set(span.taint)} "
                f"but its inputs imply {set(expected)}; taint is not monotone"
            )
        self.spans[span.span_id] = span

    def transitive_taint(self, span_id: str) -> FrozenSet[str]:
        seen, stack, acc = set(), [span_id], set()
        while stack:
            sid = stack.pop()
            if sid in seen:
                continue
            seen.add(sid)
            span = self.spans[sid]
            acc |= span.taint
            stack.extend(span.inputs)
        return frozenset(acc)


def gate_tool_call(graph: DerivationGraph, capability: str, argument_span_ids: list) -> str:
    taint = frozenset()
    for sid in argument_span_ids:
        taint = taint | graph.transitive_taint(sid)

    if not taint:
        return "admit"
    if capability in DESTRUCTIVE_CAPABILITIES:
        raise TaintViolationError(
            f"destructive capability {capability!r} invoked with arguments derived from "
            f"untrusted spans {sorted(taint)}; rejecting and escalating to review"
        )
    return "quarantine"


# Reproduction of the observed failure, now contained:
g = DerivationGraph()
g.add(Span("pdf_extract", frozenset({UNTRUSTED})))
# Summarizer consumes untrusted text: taint must propagate, not reset.
g.add(Span("summarize", frozenset({UNTRUSTED}), frozenset({"pdf_extract"})))
g.add(Span("plan_tool_call", frozenset({UNTRUSTED}), frozenset({"summarize"})))

# The old gate labeled `summarize` trusted and admitted; the invariant gate rejects.
gate_tool_call(g, "crm_write", ["plan_tool_call"])  # raises TaintViolationError
