# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-context-before-tool-invocation-and-when-is-taint-propagation-falsely-conservative.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-context-before-tool-invocation-and-when-is-taint-propagation-falsely-conservative.warrant.json
# Markdown SHA-256:   bab7efb91eb0e07e87d783909e67f98a694042d064de5efc38c0708f2f7299eb
# Code AST SHA-256:   2d9144b04d4526cecfe88a2d422f1c251ddb92fa6da83b99fab1090101aa0a9c
# Verified Classes:   Taint, Transform, ProvenanceViolation, Span, ToolCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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

class Taint(Enum):
    TRUSTED = 0
    UNTRUSTED_EXTERNAL = 1
    DERIVED_FROM_UNTRUSTED = 2

class Transform(Enum):
    COPY = "copy"
    NORMALIZE = "normalize"
    SUMMARIZE = "summarize"
    RECOMBINE = "recombine"

class ProvenanceViolation(RuntimeError):
    """Raised when a tool call's selection lineage carries untrusted instruction-flow."""

@dataclass(frozen=True)
class Span:
    text: str
    taint: Taint
    transform: Transform = Transform.COPY

@dataclass
class ToolCall:
    name: str
    args: dict
    mutating: bool
    selection_spans: FrozenSet[Span] = field(default_factory=frozenset)
    argument_spans: FrozenSet[Span] = field(default_factory=frozenset)

READ_ONLY_ALLOWLIST = {"fetch_url", "search", "read_file"}

def gate(call: ToolCall) -> str:
    # Instruction-flow: any untrusted span that shaped *selection* via a
    # non-copy/normalize transform taints the decision itself.
    inst_tainted = any(
        s.taint is Taint.UNTRUSTED_EXTERNAL
        and s.transform in (Transform.SUMMARIZE, Transform.RECOMBINE)
        for s in call.selection_spans
    )
    if call.mutating and inst_tainted:
        raise ProvenanceViolation(
            f"mutating tool {call.name!r} selected under untrusted instruction-flow; "
            f"quarantine and re-plan from trusted context"
        )
    if inst_tainted and call.name not in READ_ONLY_ALLOWLIST:
        raise ProvenanceViolation(
            f"{call.name!r} not on read-only allowlist but selection is tainted"
        )
    # Operand-flow: untrusted *content* as argument value is permitted for
    # read-only tools, but must be logged; never silently cleared.
    operand_tainted = any(
        s.taint is not Taint.TRUSTED for s in call.argument_spans
    )
    if operand_tainted and call.name not in READ_ONLY_ALLOWLIST:
        raise ProvenanceViolation(
            f"{call.name!r} consumes untrusted operand-flow but is state-mutating"
        )
    return "permitted" if not operand_tainted else "permitted_with_lineage_log"

# Trace from the record: refund selected via summarized untrusted ticket,
# argument order_id copied from a trusted record.
bad = ToolCall(
    name="refund",
    args={"order_id": "A-1042"},
    mutating=True,
    selection_spans=frozenset({
        Span("intent: customer requests refund courtesy",
             Taint.DERIVED_FROM_UNTRUSTED, Transform.SUMMARIZE),
    }),
    argument_spans=frozenset({Span("A-1042", Taint.TRUSTED)}),
)
gate(bad)  # raises ProvenanceViolation despite clean arguments
