# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-prompt-injection-taint-tracking-fail-to-propagate-across-a-context-window-eviction-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-prompt-injection-taint-tracking-fail-to-propagate-across-a-context-window-eviction-boundary.warrant.json
# Markdown SHA-256:   ae0fc834a0569f55dae79b883776445fe9ea54ca5dcec649eaf9f20be171cadb
# Code AST SHA-256:   7eeda9b67d916d7baa2408e7f985c27baeab9d3354827f606fb3f992dde5a872
# Verified Classes:   TaintLaunderingError, TaintedSpan
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class TaintLaunderingError(RuntimeError):
    """Raised when a compaction transform would emit derived text without
    propagating the taint of its inputs. Fail-closed by design."""


@dataclass(frozen=True)
class TaintedSpan:
    content: str
    taint: frozenset[str] = field(default_factory=frozenset)

    def digest(self) -> str:
        return hashlib.sha256(self.content.encode("utf-8")).hexdigest()


# Registry of transforms permitted to operate on tainted input.
# A transform must be present here AND declare a propagating rule.
_PROPAGATING_TRANSFORMS: dict[str, bool] = {
    "identity": True,
    "truncate_prefix": True,   # prefix preserves taint of source
    "summarize_llm": False,    # not instrumented -> forbidden on tainted input
}


def compact(spans: list[TaintedSpan], transform: str) -> TaintedSpan:
    """Apply a compaction transform, enforcing taint propagation.

    Invariant: the output taint is the union of all input taints. Any
    transform that cannot guarantee this must not run on tainted input.
    """
    if transform not in _PROPAGATING_TRANSFORMS:
        raise TaintLaunderingError(
            f"unknown transform {transform!r} has no declared taint rule"
        )

    union: set[str] = set()
    for s in spans:
        union |= s.taint

    if union and not _PROPAGATING_TRANSFORMS[transform]:
        raise TaintLaunderingError(
            f"transform {transform!r} is non-propagating but input is tainted "
            f"({sorted(union)}); refusing to launder label across compaction boundary"
        )

    # Concrete transforms would emit real text here; the taint union is the
    # load-bearing output regardless of the text produced.
    emitted = " ".join(s.content for s in spans)
    return TaintedSpan(content=emitted, taint=frozenset(union))


def evaluate_policy(span: TaintedSpan, tool_call: str) -> None:
    """Policy gate: refuse tool calls originating from tainted context."""
    if span.taint and tool_call.startswith("exfiltrate"):
        raise TaintLaunderingError(
            f"blocked {tool_call!r}: originating span tainted by {sorted(span.taint)}"
        )
