# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-derive-taint-provenance-at-the-tool-call-boundary-rather-than-trusting-the-label-attached-at-retrieval-time.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-re-derive-taint-provenance-at-the-tool-call-boundary-rather-than-trusting-the-label-attached-at-retrieval-time.warrant.json
# Markdown SHA-256:   f8e170db026caf026806c6f293bc494a2ab53468ae4941312aade2a6649bbfc0
# Code AST SHA-256:   8ea1447eb21ffbd396d707e734a8d86b1852831f9ac557e4b9fb02b25d56aac8
# Verified Classes:   TaintProvenanceError, Span, ToolCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintProvenanceError(RuntimeError):
    """Raised when a tool call's security-relevant argument cannot be proven trusted at the PEP."""


@dataclass(frozen=True)
class Span:
    text: str
    trusted: bool


@dataclass
class ToolCall:
    tool: str
    args: dict
    security_relevant: frozenset = field(default_factory=frozenset)


def _provenance_of(value: str, corpus: Iterable[Span]) -> bool:
    """Return True only if value appears in a trusted span and in no untrusted span.

    Verbatim-equality against the labeled corpus is the only cheap positive proof of
    trust available at the enforcement point. Absence from all spans is NOT proof of
    trust: the value may be model-authored from untrusted context.
    """
    seen_trusted = False
    for span in corpus:
        if value and value in span.text:
            if not span.trusted:
                return False
            seen_trusted = True
    return seen_trusted


def enforce(call: ToolCall, corpus: Iterable[Span]) -> None:
    """Re-derive provenance for security-relevant args; block on any unproven field.

    Do NOT read a taint label attached at retrieval time. The label may have been
    dropped by the structured decoder, and the argument may be a paraphrase of
    untrusted content that the label never covered.
    """
    corpus = list(corpus)
    for name in call.security_relevant:
        if name not in call.args:
            continue
        value = call.args[name]
        if not isinstance(value, str):
            raise TaintProvenanceError(
                f"tool={call.tool} arg={name!r}: non-string security-relevant arg "
                f"cannot be proven trusted at PEP"
            )
        if not _provenance_of(value, corpus):
            raise TaintProvenanceError(
                f"tool={call.tool} arg={name!r}: provenance not re-established "
                f"(value absent from trusted spans or present in untrusted span); "
                f"refusing to execute"
            )
