# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-laundering-a-tainted-instruction-through-a-tool-result-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-laundering-a-tainted-instruction-through-a-tool-result-boundary.warrant.json
# Markdown SHA-256:   db81777cb92f9823b78441b6c5e8a119d4aa7bfd7d2ad2a485f80bbe7172118d
# Code AST SHA-256:   ddbe07cd4d3bd4423035efc8d86739bc1d4c4c8e35c645333205e9fe065fde78
# Verified Classes:   TaintEscalation, Segment
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class TaintEscalation(RuntimeError):
    """Raised when tainted content requests instruction authority without declassification."""
    pass

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

def authorize_tool_result(result: Segment, channel: str, requested_authority: str,
                          declassified: bool = False) -> str:
    # I2: authority is a function of taint, not channel. Channel only caps.
    cap = {"system": "instruction", "user": "instruction", "tool": "observation"}[channel]
    if requested_authority == "instruction" and cap != "instruction":
        requested_authority = cap  # channel may cap, never raise

    # I1+join: non-empty taint requesting instruction authority is a gate event.
    if result.taint and requested_authority == "instruction" and not declassified:
        raise TaintEscalation(
            f"tainted segment (taint={sorted(result.taint)}) requested instruction "
            f"authority via channel={channel!r}; declassification required"
        )

    # I3: crossing a boundary never grants authority above provenance permits.
    if result.taint and not declassified:
        return "data"
    return requested_authority

def propagate_taint(inputs: list[Segment], output_text: str) -> Segment:
    # I1: LLM-backed / derived tools must union input taints; empty inputs => top.
    if not inputs:
        return Segment(output_text, frozenset({"__untrusted_top__"}))
    union = frozenset().union(*(s.taint for s in inputs))
    return Segment(output_text, union)
