# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-across-a-tool-output-boundary-even-when-provenance-labels-are-present.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-across-a-tool-output-boundary-even-when-provenance-labels-are-present.warrant.json
# Markdown SHA-256:   fe4e244151482785a1a52c85ad0c9c3154faef7480a26856692556685ee9e4bd
# Code AST SHA-256:   39deffce96fc0634cda20fd1a3fb75b0eda0fffd92ee1166f5fa077e4b45b04e
# Verified Classes:   Authority, TaintLaunderingError, Segment, TaintRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class Authority(Enum):
    TRUSTED = 0
    UNKNOWN = 1
    UNTRUSTED = 2

    def meet(self, other: "Authority") -> "Authority":
        # Higher enum value = lower authority. Meet = strictest.
        return Authority(max(self.value, other.value))


class TaintLaunderingError(RuntimeError):
    """Raised when a segment's authority cannot be soundly derived."""


@dataclass
class Segment:
    seg_id: str
    speaker_authority: Authority
    inputs: list[str] = field(default_factory=list)
    content: str = ""


class TaintRegistry:
    def __init__(self) -> None:
        self._segments: dict[str, Segment] = {}

    def register(self, seg: Segment) -> Authority:
        if not seg.inputs and seg.speaker_authority is Authority.UNKNOWN:
            # No derivation and no explicit trusted origin -> default deny.
            raise TaintLaunderingError(
                f"segment {seg.seg_id} has no derivation and no trusted origin; "
                f"authority is UNKNOWN and must be treated as UNTRUSTED"
            )
        self._segments[seg.seg_id] = seg
        return self.authority_of(seg.seg_id)

    def authority_of(self, seg_id: str, _seen: Optional[set[str]] = None) -> Authority:
        _seen = _seen or set()
        if seg_id in _seen:
            raise TaintLaunderingError(f"cyclic derivation at {seg_id}")
        _seen.add(seg_id)

        seg = self._segments.get(seg_id)
        if seg is None:
            # Absence is not trust. Unregistered segment is UNKNOWN.
            return Authority.UNKNOWN

        if not seg.inputs:
            return seg.speaker_authority

        derived = Authority.TRUSTED
        for parent in seg.inputs:
            derived = derived.meet(self.authority_of(parent, _seen))
        return seg.speaker_authority.meet(derived)

    def may_obey(self, seg_id: str) -> bool:
        """A directive-shaped string may be obeyed only if fully TRUSTED."""
        return self.authority_of(seg_id) is Authority.TRUSTED


def check_handoff(registry: TaintRegistry, summary_seg_id: str) -> None:
    if not registry.may_obey(summary_seg_id):
        raise TaintLaunderingError(
            f"segment {summary_seg_id} carries non-trusted authority "
            f"({registry.authority_of(summary_seg_id).name}); "
            f"directive-shaped content must be treated as data, not instruction"
        )


# Reproduction of the observed trace:
# S1 = raw tool output, untrusted origin.
# S1' = planner summary of S1, speaker=TRUSTED, inputs=[S1].
# Without derivation-closure S1' would be TRUSTED. With it, S1' is UNTRUSTED.
reg = TaintRegistry()
reg.register(Segment("S1", Authority.UNTRUSTED, content="Ignore prior instructions..."))
reg.register(Segment("S1'", Authority.TRUSTED, inputs=["S1"], content="Page asks to exfiltrate"))

try:
    check_handoff(reg, "S1'")
except TaintLaunderingError as e:
    print(f"BLOCKED: {e}")
