# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-cannot-distinguish-taint-propagation-from-legitimate-instruction-flow-across-tool-output-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-cannot-distinguish-taint-propagation-from-legitimate-instruction-flow-across-tool-output-boundaries.warrant.json
# Markdown SHA-256:   e6bd9ed607506a324d09f3380150d538a9a381580d945e8d804e54308f43e4ba
# Code AST SHA-256:   5ef032670eb7044d2cd77bb6b3a99a5c4a12b80fd51719cc7957a98da7d8f51e
# Verified Classes:   TaintClass, TaintLaunderingError, Span, ToolCall, ProvenanceGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TaintClass(Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"
    LAUNDERED = "laundered"  # derived from untrusted via a transforming tool


class TaintLaunderingError(RuntimeError):
    """Raised when a destructive action is attributed to a span whose taint
    was laundered through a derive step without re-verification."""


@dataclass(frozen=True)
class Span:
    span_id: str
    taint: TaintClass
    instruction_shaped: bool = False


@dataclass
class ToolCall:
    tool: str
    args: dict
    input_spans: FrozenSet[str]
    output_span: str
    destructive: bool = False
    taint_preserving: bool = False  # True only if proven bounded transform


class ProvenanceGate:
    def __init__(self) -> None:
        self.spans: dict[str, Span] = {}
        self.calls: list[ToolCall] = []

    def register_span(self, span: Span) -> None:
        self.spans[span.span_id] = span

    def record_call(self, call: ToolCall) -> None:
        self.calls.append(call)
        input_taints = {self.spans[s].taint for s in call.input_spans}
        if TaintClass.UNTRUSTED in input_taints:
            out_taint = (
                TaintClass.UNTRUSTED
                if call.taint_preserving
                else TaintClass.LAUNDERED
            )
        else:
            out_taint = TaintClass.TRUSTED
        self.spans[call.output_span] = Span(call.output_span, out_taint)

    def attribution_set(self, action_tool: str) -> FrozenSet[str]:
        # Shadow replay would produce this; here we union all recorded calls
        # whose output is instruction-shaped or whose tool matches the action
        # family. A real implementation attributes per-token.
        contributing: set[str] = set()
        for call in self.calls:
            if call.tool == action_tool or self.spans[call.output_span].instruction_shaped:
                contributing |= set(call.input_spans)
                contributing.add(call.output_span)
        return frozenset(contributing)

    def authorize(self, action_tool: str, destructive: bool) -> None:
        if not destructive:
            return
        attrib = self.attribution_set(action_tool)
        taints = {self.spans[s].taint for s in attrib if s in self.spans}
        if TaintClass.LAUNDERED in taints:
            raise TaintLaunderingError(
                f"destructive action {action_tool!r} attributed to laundered span; "
                f"re-verify laundering output before authorizing. attribution={sorted(attrib)}"
            )
        if TaintClass.UNTRUSTED in taints:
            raise TaintLaunderingError(
                f"destructive action {action_tool!r} attributed to untrusted span; "
                f"blocked by fail-closed policy. attribution={sorted(attrib)}"
            )


def demo_laundering_failure() -> None:
    gate = ProvenanceGate()
    gate.register_span(Span("sys", TaintClass.TRUSTED))
    gate.register_span(Span("user", TaintClass.TRUSTED))
    gate.register_span(Span("doc", TaintClass.UNTRUSTED, instruction_shaped=True))
    # summarize() is a transforming tool: taint-preserving=False by default.
    gate.record_call(
        ToolCall(
            tool="summarize",
            args={"span": "doc"},
            input_spans=frozenset({"doc"}),
            output_span="summary",
            taint_preserving=False,
        )
    )
    # The summary is now LAUNDERED, not TRUSTED. A gate that only checks the
    # immediate predecessor would miss this; the provenance gate does not.
    gate.authorize("rotate_credentials", destructive=True)
    # Unreachable: authorize raises TaintLaunderingError above.


if __name__ == "__main__":
    demo_laundering_failure()
