# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-prompt-injection-taint-across-tool-call-boundaries-and-why-per-message-provenance-is-the-wrong-granularity.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-prompt-injection-taint-across-tool-call-boundaries-and-why-per-message-provenance-is-the-wrong-granularity.warrant.json
# Markdown SHA-256:   ce1863ec04b1609f0f8f66c85037ae1b86c9049fbea39e1dc95e1d69ec758022
# Code AST SHA-256:   6046669670d4b4186caa48202714eb441ae82b77ddd98ec29c2b74a9465abc14
# Verified Classes:   Trust, TaintViolation, Span, TaintGraph
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Trust(IntEnum):
    UNTRUSTED = 0
    DERIVED = 1
    TRUSTED = 2


class TaintViolation(RuntimeError):
    """Raised when a span is written with trust exceeding its input lineage
    without a registered, audited declassification record."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    trust: Trust
    lineage: tuple[str, ...] = field(default_factory=tuple)


class TaintGraph:
    def __init__(self) -> None:
        self._spans: dict[str, Span] = {}
        self._declassifiers: set[str] = set()

    def register_declassifier(self, name: str) -> None:
        self._declassifiers.add(name)

    def ingest(self, span_id: str, trust: Trust) -> Span:
        span = Span(span_id=span_id, trust=trust, lineage=(span_id,))
        self._spans[span_id] = span
        return span

    def transform(
        self,
        out_id: str,
        inputs: Iterable[str],
        declared_trust: Trust,
        transform_name: str,
        declassification_rule: str | None = None,
    ) -> Span:
        input_spans = [self._spans[i] for i in inputs]
        if not input_spans:
            raise TaintViolation(f"transform {transform_name!r} has no inputs")

        # The meet: output trust may not exceed the least-trusted input.
        floor = Trust(min(s.trust for s in input_spans))
        lineage = tuple(sorted({sid for s in input_spans for sid in s.lineage}))

        if declared_trust > floor:
            # Raising trust is only legal via a named, audited declassifier.
            if transform_name not in self._declassifiers or not declassification_rule:
                raise TaintViolation(
                    f"transform {transform_name!r} attempted to write "
                    f"{out_id!r} at trust={declared_trust.name} from "
                    f"lineage floor={floor.name} with no declassification record"
                )
            # Declassification record is emitted by the caller's audit sink;
            # its presence is the precondition, its absence fails closed above.

        span = Span(span_id=out_id, trust=declared_trust, lineage=lineage)
        self._spans[out_id] = span
        return span

    def require_gate(self, span_id: str, gate: str) -> None:
        """Side-effecting tool calls whose args trace to derived/untrusted
        lineage must pass the confirmation gate regardless of surface text."""
        span = self._spans[span_id]
        if span.trust < Trust.TRUSTED and not gate_passed(gate):
            raise TaintViolation(
                f"action on {span_id!r} (trust={span.trust.name}, "
                f"lineage={span.lineage}) blocked: gate {gate!r} not satisfied"
            )


def gate_passed(gate: str) -> bool:
    # Placeholder: real implementation checks an out-of-band confirmation
    # token that the model cannot mint.
    return False


# --- Reproduction of the observed trace -----------------------------------

def run_trace() -> None:
    g = TaintGraph()
    g.ingest("doc_1", Trust.UNTRUSTED)

    # Step 2: summarizer is first-party but reads untrusted input.
    # It tries to persist as TRUSTED without registering as a declassifier.
    g.transform(
        out_id="summary_1",
        inputs=["doc_1"],
        declared_trust=Trust.TRUSTED,
        transform_name="summarize",
    )


if __name__ == "__main__":
    try:
        run_trace()
    except TaintViolation as e:
        print(f"BLOCKED at transform boundary: {e}")
