# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-laundering-across-tool-call-boundaries-via-re-serialized-tool-output.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-laundering-across-tool-call-boundaries-via-re-serialized-tool-output.warrant.json
# Markdown SHA-256:   4fbecca00eb92496ff8015ad39a9d5c281205bd1bb9c1819399e2fb749f81db9
# Code AST SHA-256:   522f9220b859e3b72cd283bb8269e2011371d6ad41bd1e3baa0a166f756dec87
# Verified Classes:   TaintLaunderingError, TaintedText
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class TaintLaunderingError(RuntimeError):
    """Raised when a taint label fails to survive a serialization boundary."""
    pass


@dataclass(frozen=True)
class TaintedText:
    text: str
    # intervals are (start, end, label) over self.text
    intervals: tuple[tuple[int, int, str], ...] = field(default_factory=tuple)

    def labels_at(self, start: int, end: int) -> set[str]:
        return {
            lbl for (s, e, lbl) in self.intervals
            if s < end and e > start
        }

    def derive(self, transform: Callable[[str], str], out: str) -> "TaintedText":
        # Derivation closure: any output of a transform over tainted input
        # inherits the union of input labels across the whole output span.
        inherited = {lbl for (_, _, lbl) in self.intervals}
        if inherited and not out:
            raise TaintLaunderingError(
                "transform consumed tainted input but produced empty output; "
                "label cannot be anchored to a byte range"
            )
        new_intervals = tuple((0, len(out), lbl) for lbl in inherited)
        return TaintedText(text=out, intervals=new_intervals)


def serialize_boundary(tt: TaintedText, dumps: Callable[[str], str]) -> TaintedText:
    """Re-serialization must preserve interval labels over the new byte stream."""
    serialized = dumps(tt.text)
    if tt.intervals and not serialized:
        raise TaintLaunderingError("serialization dropped tainted bytes")
    # Map each original interval into the serialized stream by locating the
    # escaped substring; if it cannot be located, the label is lost -> fail closed.
    new_intervals = []
    for (s, e, lbl) in tt.intervals:
        frag = dumps(tt.text[s:e])
        idx = serialized.find(frag)
        if idx < 0:
            raise TaintLaunderingError(
                f"taint interval [{s},{e}) label={lbl} not re-anchorable after serialization"
            )
        new_intervals.append((idx, idx + len(frag), lbl))
    return TaintedText(text=serialized, intervals=tuple(new_intervals))


def enforce_sink(arg_lineage: TaintedText, untrusted_label: str = "EXTERNAL_UNTRUSTED") -> None:
    """Sink-edge check: refuse if any argument byte traces to untrusted origin."""
    if arg_lineage.labels_at(0, len(arg_lineage.text)) & {untrusted_label}:
        raise TaintLaunderingError(
            "side-effecting call arguments trace to untrusted origin; "
            "no human warrant attached — refusing execution"
        )
