# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-a-tool-sandbox-boundary-and-why-egress-filters-keyed-on-content-alone-miss-it.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-a-tool-sandbox-boundary-and-why-egress-filters-keyed-on-content-alone-miss-it.warrant.json
# Markdown SHA-256:   98e928a8e445c16058715048d3cad7cd6e96a7736ead959fd293a51602673a0d
# Code AST SHA-256:   d57075cc80848024826a0124d16457b95acaaa71a0e611ae207553c0a107ccdb
# Verified Classes:   TaintLaunderingDetected, SourceSpan, EgressCall
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingDetected(RuntimeError):
    """Raised when an egress argument's derivation reaches an untrusted
    source that the content-label filter did not match."""


@dataclass(frozen=True)
class SourceSpan:
    source_id: str
    untrusted: bool


@dataclass
class EgressCall:
    tool: str
    argument: str
    # source ids the sandbox observed entering the context window
    context_sources: FrozenSet[str] = field(default_factory=frozenset)
    # source ids the content filter actually matched in `argument`
    matched_sources: FrozenSet[str] = field(default_factory=frozenset)


def enforce_derivation_invariant(
    call: EgressCall,
    registry: dict[str, SourceSpan],
    privileged_tools: FrozenSet[str],
) -> None:
    if call.tool not in privileged_tools:
        return

    reachable_untrusted = frozenset(
        sid for sid in call.context_sources
        if registry.get(sid) and registry[sid].untrusted
    )

    # Divergence: untrusted data was in scope, but the filter matched none of it.
    # The argument is either genuinely clean or laundered; we cannot distinguish,
    # so we must refuse.
    unmatched = reachable_untrusted - call.matched_sources
    if unmatched:
        raise TaintLaunderingDetected(
            f"egress '{call.tool}' reached untrusted sources {sorted(unmatched)} "
            f"but content filter matched none of them; derivation collapsed "
            f"inside a generative step — refusing egress"
        )

    # Schema-constraint check: privileged egress must not carry free text
    # derived from tainted context. Callers pass a pre-validated argument;
    # an unconstrained free-text channel is itself a laundering vector.
    if len(call.argument) > 0 and not call.matched_sources and reachable_untrusted:
        raise TaintLaunderingDetected(
            f"egress '{call.tool}' carries unconstrained free text while "
            f"untrusted sources are in scope"
        )
