# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-indirect-prompt-injection-taint-at-the-retrieval-reasoning-boundary-without-trusting-the-retrieved-content-to-describe-its.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-indirect-prompt-injection-taint-at-the-retrieval-reasoning-boundary-without-trusting-the-retrieved-content-to-describe-its.warrant.json
# Markdown SHA-256:   39b1fb2f16d7ba6b323516eee63c0b2b99455a5eb6d31a4397bf59e99d3074cf
# Code AST SHA-256:   b7b263fdfe7f3a1bb602ae8c2e1f54d04049387d0c71eef3057a2600798c976c
# Verified Classes:   TaintResolutionError, Span, ProvenanceGraph
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintResolutionError(RuntimeError):
    """Raised when an action's provenance cannot be resolved to a trust class."""
    pass


class Span:
    def __init__(self, span_id, source_id, trust, inputs=None):
        self.span_id = span_id
        self.source_id = source_id
        self.trust = trust            # "trusted" | "untrusted"
        self.inputs = inputs or []    # span_ids this span was derived from


class ProvenanceGraph:
    def __init__(self):
        self.spans = {}

    def add(self, span):
        self.spans[span.span_id] = span

    def resolve_trust(self, span_id, _seen=None):
        _seen = _seen or set()
        if span_id in _seen:
            raise TaintResolutionError(f"cycle in provenance at {span_id}")
        _seen.add(span_id)
        span = self.spans.get(span_id)
        if span is None:
            # Unresolvable edge: cannot prove clean, so cannot permit action.
            raise TaintResolutionError(f"unknown span {span_id}; taint unresolvable")
        if span.trust == "untrusted":
            return "untrusted"
        if not span.inputs:
            return span.trust
        # Derived span inherits the join of its inputs.
        trusts = {self.resolve_trust(i, _seen) for i in span.inputs}
        return "untrusted" if "untrusted" in trusts else "trusted"


SIDE_EFFECT_ACTIONS = {"transfer_funds", "send_email", "delete_record"}


def gate_action(graph, action_name, cited_span_ids):
    if action_name not in SIDE_EFFECT_ACTIONS:
        return "permitted"
    if not cited_span_ids:
        # Uncited side-effect action: no provenance to resolve -> escalate.
        raise TaintResolutionError(
            f"action {action_name} emitted with no cited spans; cannot resolve taint"
        )
    for sid in cited_span_ids:
        if graph.resolve_trust(sid) == "untrusted":
            return "escalate"
    return "permitted"
