# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-when-a-tool-output-round-trips-through-summarization-and-re-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-prompt-injection-taint-when-a-tool-output-round-trips-through-summarization-and-re-injection.warrant.json
# Markdown SHA-256:   0e6149be5edbe0fe45c5196217211a98ae71d6691a0118275e895fa9fe90193e
# Code AST SHA-256:   b5739c0a8b69ac5f05a9fad14772f557092f95a34e1caa28d497139a07638a6a
# Verified Classes:   Taint, TaintLossError, Segment, ProvenanceTracker
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class Taint(Enum):
    CLEAN = 0
    UNTRUSTED = 1


def join(a: Taint, b: Taint) -> Taint:
    return Taint(max(a.value, b.value))


class TaintLossError(RuntimeError):
    """Raised when a transformation node would drop taint from its inputs."""


@dataclass
class Segment:
    id: str
    producer: str
    taint: Taint
    inputs: list[str] = field(default_factory=list)


class ProvenanceTracker:
    def __init__(self, producer_policy: dict[str, Taint]):
        self._policy = producer_policy
        self._segments: dict[str, Segment] = {}

    def register_tool_output(self, seg_id: str, tool: str) -> Segment:
        seg = Segment(seg_id, producer=tool, taint=Taint.UNTRUSTED)
        self._segments[seg_id] = seg
        return seg

    def register_transformation(
        self, seg_id: str, producer: str, inputs: list[str]
    ) -> Segment:
        if not inputs:
            raise TaintLossError(
                f"transformation {seg_id} declared no inputs; "
                "closure cannot be computed and taint would be lost"
            )
        missing = [i for i in inputs if i not in self._segments]
        if missing:
            raise TaintLossError(
                f"transformation {seg_id} references unknown inputs {missing}; "
                "provenance graph has a hole at the re-injection seam"
            )
        inherited = Taint.CLEAN
        for i in inputs:
            inherited = join(inherited, self._segments[i].taint)
        producer_taint = self._policy.get(producer, Taint.UNTRUSTED)
        seg = Segment(
            id=seg_id,
            producer=producer,
            taint=join(producer_taint, inherited),
            inputs=list(inputs),
        )
        self._segments[seg_id] = seg
        return seg

    def assert_quarantine(self, seg_id: str, action: str) -> None:
        seg = self._segments[seg_id]
        if seg.taint is Taint.UNTRUSTED:
            raise TaintLossError(
                f"action {action!r} blocked: segment {seg_id} is UNTRUSTED "
                f"(producer={seg.producer}, inputs={seg.inputs})"
            )


def demonstrate_failure() -> None:
    tracker = ProvenanceTracker(
        producer_policy={"model:reasoner": Taint.CLEAN}
    )
    tracker.register_tool_output("S1", tool="tool:retriever")
    # Producer-keyed tracker would assign CLEAN here and lose the taint.
    # Closure-keyed tracker must raise if inputs are undeclared.
    try:
        tracker.register_transformation("S2", producer="model:reasoner", inputs=[])
    except TaintLossError as e:
        print(f"guardrail fired: {e}")

    s2 = tracker.register_transformation(
        "S2", producer="model:reasoner", inputs=["S1"]
    )
    assert s2.taint is Taint.UNTRUSTED, "closure join failed to retain taint"

    try:
        tracker.assert_quarantine("S2", action="env.read(secrets)")
    except TaintLossError as e:
        print(f"planner blocked: {e}")
        return
    raise TaintLossError("planner was not blocked on tainted summary")


if __name__ == "__main__":
    demonstrate_failure()
