# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-tainted-tool-result-as-a-capability-widening-event-rather-than-a-data-payload.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-tainted-tool-result-as-a-capability-widening-event-rather-than-a-data-payload.warrant.json
# Markdown SHA-256:   d790aad05e7b6fabdddfc9b900fa032133d0c4411d9b52dc3cb4f0228d21e42a
# Code AST SHA-256:   7ed4da96cf6414298ac6d9e274cdab391c673adc3f6513e21c4c5bbe14b0cb31
# Verified Classes:   Capability, TaintViolation, ToolCall, SandboxState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class Capability(Enum):
    READ = 0
    WRITE = 1
    NETWORK = 2
    EXEC = 3
    SPAWN = 4


class TaintViolation(RuntimeError):
    """Raised when a capability-widening call is influenced by untrusted context."""
    pass


@dataclass
class ToolCall:
    tool: str
    capability: Capability
    args: dict
    # provenance: source labels that influenced selection/arguments,
    # including context-level (implicit) influence.
    provenance: set = field(default_factory=set)


@dataclass
class SandboxState:
    untrusted_in_context: bool = False
    last_checkpoint_id: Optional[str] = None

    def observe_untrusted(self, source: str) -> None:
        self.untrusted_in_context = True

    def checkpoint(self, checkpoint_id: str) -> None:
        # Eviction + re-signed context is the ONLY taint-clearing operation.
        self.untrusted_in_context = False
        self.last_checkpoint_id = checkpoint_id


def evaluate_call(state: SandboxState, call: ToolCall, gate) -> None:
    context_tainted = state.untrusted_in_context
    capability_bearing = call.capability.value > Capability.READ.value

    if not (context_tainted and capability_bearing):
        return  # read-plane or clean context: proceed

    # Implicit-flow channel: if untrusted data was in context, treat the
    # call as influenced even when no syntactic dependency exists.
    influenced = bool(call.provenance) or context_tainted

    if influenced:
        approved = gate(call, state)
        if not approved:
            raise TaintViolation(
                f"Capability-widening call {call.tool!r} "
                f"(class={call.capability.name}) influenced by untrusted "
                f"context; provenance={sorted(call.provenance) or 'implicit'}; "
                f"last_checkpoint={state.last_checkpoint_id}. "
                f"Establish a signed checkpoint before retrying."
            )


# --- Reproducing the observed failure ---
state = SandboxState()
state.observe_untrusted("retrieval:doc-7")

call = ToolCall(
    tool="write_file",
    capability=Capability.WRITE,
    args={"path": "/tmp/handoff.txt", "content": "<env dump>"},
    provenance=set(),  # literal args: value-level taint sees nothing
)

deny_all = lambda c, s: False
evaluate_call(state, call, deny_all)  # raises TaintViolation
