# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-does-not-survive-provenance-label-propagation-across-tool-output-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-does-not-survive-provenance-label-propagation-across-tool-output-boundaries.warrant.json
# Markdown SHA-256:   8fdb94cffc2d66ad3d0a5a76b74aa73cb4da37c20e9e38aa76f3e252959bb117
# Code AST SHA-256:   ff6eb8b20d3e4a1e746802717b2dfb5086124f322e34b2c7b8ccc9c49df26151
# Verified Classes:   TaintLaunderingError, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a consequential action is justified by model-derived
    content whose derivation ancestry is missing or reaches an untrusted span."""
    pass


@dataclass
class Span:
    span_id: str
    label: str                      # e.g. "trusted:user", "untrusted:tool_output", "derived:model"
    derived_from: list[str] = field(default_factory=list)  # ancestry edge list


def certify_untainted(span: Span, spans: dict[str, Span], _seen: Optional[set] = None) -> bool:
    """Return True only if the span's full derivation ancestry is present and
    contains no untrusted source. Fails closed on missing ancestry."""
    seen = _seen if _seen is not None else set()
    if span.span_id in seen:
        return True  # cycle guard; already validated on this path
    seen.add(span.span_id)

    if span.label == "untrusted:tool_output":
        return False

    if span.label == "derived:model":
        if not span.derived_from:
            # Compaction dropped the derivation graph: cannot prove cleanliness.
            raise TaintLaunderingError(
                f"span {span.span_id!r} is model-derived with no ancestry; "
                "taint status unprovable (fail closed)"
            )
        for parent_id in span.derived_from:
            parent = spans.get(parent_id)
            if parent is None:
                raise TaintLaunderingError(
                    f"span {span.span_id!r} references missing ancestor {parent_id!r}; "
                    "ancestry incomplete after compaction"
                )
            if not certify_untainted(parent, spans, seen):
                return False
        return True

    return True  # trusted:user or explicitly declassified labels


def gate_action(action: str, justification: Span, spans: dict[str, Span]) -> None:
    if action in {"transfer_funds", "write_file", "send_email"}:
        if not certify_untainted(justification, spans):
            raise TaintLaunderingError(
                f"action {action!r} justified by tainted or unprovable span "
                f"{justification.span_id!r}; blocked"
            )
