# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-composed-tool-call-chains-when-each-hop-is-individually-sandboxed.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-composed-tool-call-chains-when-each-hop-is-individually-sandboxed.warrant.json
# Markdown SHA-256:   55a6f771cc7157ea8918b27407154e0a2fa654b8a95dbbb60360f1cdc8f84d46
# Code AST SHA-256:   5cf9da2227ad5deb6052eee19eb73a8982c3be1c9582ce9f2590bde4f1400c6c
# Verified Classes:   TaintLaunderingError, Envelope, Hop
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class TaintLaunderingError(RuntimeError):
    """Raised when a value reaches an egress sink without a transitively
    closed taint envelope, i.e. a composed chain would exfiltrate."""
    pass

UNTRUSTED_EXTERNAL = "UNTRUSTED_EXTERNAL"
TRUSTED_INTERNAL = "TRUSTED_INTERNAL"

@dataclass(frozen=True)
class Envelope:
    labels: FrozenSet[str]
    derivation: str  # hash of transform chain, for audit

@dataclass
class Hop:
    name: str
    has_egress_tool: bool
    can_influence_egress_params: bool  # the load-bearing flag
    is_declassifier: bool = False

def handoff(src: Hop, value: Envelope, dst: Hop) -> Envelope:
    # A semantic transform (summarizer) that is NOT a declassifier
    # propagates the union of labels; it does not launder them.
    if dst.is_declassifier:
        return Envelope(frozenset({TRUSTED_INTERNAL}), value.derivation + "|declass")
    return Envelope(value.labels, value.derivation + f"|{dst.name}")

def assert_chain_safe(chain: list[Hop], initial: Envelope) -> None:
    env = initial
    for hop in chain:
        env = handoff(hop, env, hop)
        # Invariant: any hop that can influence egress params is treated
        # as an egress sink for taint purposes, even without an egress tool.
        reaches_sink = hop.has_egress_tool or hop.can_influence_egress_params
        if reaches_sink and UNTRUSTED_EXTERNAL in env.labels:
            raise TaintLaunderingError(
                f"hop '{hop.name}' can influence egress with untrusted "
                f"labels {sorted(env.labels)}; derivation={env.derivation}. "
                "Insert a declassifier or reject the chain."
            )

# The observed failure, encoded: R fetches (untrusted), S summarizes
# (no egress tool but CAN influence egress params via recipient field),
# E emails. This must raise, not silently pass three green sandboxes.
def replay_observed_chain() -> None:
    chain = [
        Hop("R", has_egress_tool=False, can_influence_egress_params=False),
        Hop("S", has_egress_tool=False, can_influence_egress_params=True),
        Hop("E", has_egress_tool=True,  can_influence_egress_params=True),
    ]
    assert_chain_safe(chain, Envelope(frozenset({UNTRUSTED_EXTERNAL}), "fetch:doc"))

if __name__ == "__main__":
    replay_observed_chain()  # raises TaintLaunderingError at hop 'S'
