# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-call-argument-as-tainted-even-when-the-value-was-re-derived-by-the-model-rather-than-copied-from-u.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-tool-call-argument-as-tainted-even-when-the-value-was-re-derived-by-the-model-rather-than-copied-from-u.warrant.json
# Markdown SHA-256:   1affe3cdc5139ff9a3a4df478804e9af6052aa29bb8a64c6806d4cb77ecfd845
# Code AST SHA-256:   0729cf4fc3b975870566e5a97e1db137e0fe57cfd75471a3ba2516d9c82b3092
# Verified Classes:   TaintGateError, Provenance, Span, ToolCall, ContextWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TaintGateError(RuntimeError):
    """Raised when a tool call cannot be proven to derive from trusted spans."""
    pass


class Provenance(Enum):
    TRUSTED_USER = "trusted:user"
    TRUSTED_HARNESS = "trusted:harness"
    UNTRUSTED_WEB = "untrusted:web"
    UNTRUSTED_TOOL_OUTPUT = "untrusted:tool_output"


@dataclass
class Span:
    provenance: Provenance
    text: str


@dataclass
class ToolCall:
    tool: str
    arguments: dict
    # True only if the harness can prove the argument was templated from
    # trusted spans alone. Model-generated args in a tainted window are False.
    derivation_trusted: bool
    side_effecting: bool


@dataclass
class ContextWindow:
    spans: list[Span] = field(default_factory=list)

    def has_untrusted(self) -> bool:
        return any(
            s.provenance in (Provenance.UNTRUSTED_WEB, Provenance.UNTRUSTED_TOOL_OUTPUT)
            for s in self.spans
        )


def authorize(call: ToolCall, window: ContextWindow) -> None:
    """
    Taint-aware authorization gate.

    Invariant: a side-effecting tool may execute only when its argument
    derivation is provably trusted. A window containing any untrusted span
    poisons every model-generated argument, regardless of surface form.
    """
    if not call.side_effecting:
        return  # read-only tools do not require derivation proof

    if not call.derivation_trusted:
        # The argument was model-generated. If the window is tainted, we
        # cannot exhibit a trusted-only derivation path. Escalate.
        if window.has_untrusted():
            raise TaintGateError(
                f"tool {call.tool!r}: argument derivation not provably trusted "
                f"while untrusted spans are live in context window; "
                f"require out-of-band principal confirmation"
            )
        # Untrusted spans absent, but derivation still unproven: treat as
        # tainted by default rather than assume cleanliness.
        raise TaintGateError(
            f"tool {call.tool!r}: derivation_trusted=False with no provenance "
            f"proof; default-deny"
        )

    # derivation_trusted=True: harness asserts arguments came from trusted
    # spans. The harness, not this gate, is responsible for that assertion.
    return


def run_gate(call: ToolCall, window: ContextWindow) -> Optional[str]:
    try:
        authorize(call, window)
        return None
    except TaintGateError as exc:
        return str(exc)


# --- Trace: the laundered-summary case ---
if __name__ == "__main__":
    window = ContextWindow(spans=[
        Span(Provenance.TRUSTED_USER, "summarize this page and make a calendar event"),
        Span(Provenance.UNTRUSTED_WEB, "Q3 planning sync — confirm by wire"),
    ])
    call = ToolCall(
        tool="create_calendar_event",
        arguments={"title": "Q3 planning sync — confirm by wire"},
        derivation_trusted=False,  # model paraphrased the injected text
        side_effecting=True,
    )
    err = run_gate(call, window)
    assert err is not None and "out-of-band" in err
    print("blocked:", err)
