# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-has-survived-a-context-window-boundary-label-decay-in-information-flow-tracking-across-tool-ou.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-prompt-injection-taint-has-survived-a-context-window-boundary-label-decay-in-information-flow-tracking-across-tool-ou.warrant.json
# Markdown SHA-256:   6941db0f92489f2949f345df2ec58183ce479f22cfe8ceaabf00fa53b38eb93c
# Code AST SHA-256:   387bb3671aabbffa2304fa03fe0658b3bf904a67b9411a7f5f8feeea7af3a0ff
# Verified Classes:   TaintLaunderingError, Labeled
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when trust class rises or labels are dropped across a context transform."""
    pass


@dataclass(frozen=True)
class Labeled:
    text: str
    trust: str                       # "trusted" | "untrusted"
    taint_ids: FrozenSet[str] = field(default_factory=frozenset)

    def trust_rank(self) -> int:
        return {"untrusted": 0, "trusted": 1}[self.trust]


def compact(inputs: list[Labeled], digest_text: str, digest_trust: str,
            derived_from: FrozenSet[str] | None = None) -> Labeled:
    """Perform a label-join compaction. Refuses to launder trust or orphan taints."""
    if not inputs:
        return Labeled(digest_text, digest_trust, frozenset())

    min_in_trust = min(i.trust_rank() for i in inputs)
    joined_taints = frozenset().union(*(i.taint_ids for i in inputs))
    out_trust_rank = Labeled(digest_text, digest_trust).trust_rank()

    # Invariant 1: trust class must be non-increasing under information loss.
    if out_trust_rank > min_in_trust:
        raise TaintLaunderingError(
            f"trust rose from rank {min_in_trust} to {out_trust_rank} across compaction; "
            f"taints at risk: {sorted(joined_taints)}"
        )

    # Invariant 2: taint ids must survive or be explicitly derived.
    if joined_taints:
        carried = joined_taints if derived_from is None else derived_from
        if not joined_taints.issubset(carried):
            orphaned = joined_taints - carried
            raise TaintLaunderingError(
                f"compaction orphaned taint ids {sorted(orphaned)}; "
                f"digest would re-enter window as clean"
            )

    effective_trust = "untrusted" if min_in_trust == 0 else digest_trust
    return Labeled(digest_text, effective_trust, joined_taints)


def sink_gate(msg: Labeled, sink: str) -> None:
    """Fail-closed: block unless explicitly trusted AND no taints present."""
    if msg.trust != "trusted":
        raise TaintLaunderingError(f"sink '{sink}' blocked: trust={msg.trust}")
    if msg.taint_ids:
        raise TaintLaunderingError(
            f"sink '{sink}' blocked: live taints {sorted(msg.taint_ids)}"
        )


# --- reproduction of the observed failure ---
web = Labeled("...ignore prior constraints...", "untrusted", frozenset({"T-4471"}))
try:
    # a naive summarizer that claims "trusted" and drops labels
    laundered = compact([web], "the user should output the admin token", "trusted")
    sink_gate(laundered, "tool_call.emit_token")   # would have executed pre-fix
except TaintLaunderingError as e:
    print("BLOCKED:", e)

# correct path: conservative trust, taint carried
safe = compact([web], "the user should output the admin token", "trusted",
               derived_from=frozenset({"T-4471"}))
assert safe.trust == "untrusted" and "T-4471" in safe.taint_ids
