# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-cross-boundary-taint-laundering-when-provenance-labels-survive-a-tool-call-but-not-a-re-serialization.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-cross-boundary-taint-laundering-when-provenance-labels-survive-a-tool-call-but-not-a-re-serialization.warrant.json
# Markdown SHA-256:   8e38d0d48d4e6b040fceb2f2df2488eba497137b8434e2ac374e48d4edd7d5d6
# Code AST SHA-256:   f06a2573e34c936b51f4ca9322c9439459678925ab509cb12252269c9bdf1282
# Verified Classes:   TaintLaunderingError, Segment, Context
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

TRUSTED = frozenset({"trusted:user", "trusted:assistant", "trusted:tool"})
UNTRUSTED_PREFIX = "untrusted:"


class TaintLaunderingError(RuntimeError):
    """Raised when a side-effecting call carries derived content whose
    provenance labels were re-bound to a trusted channel at a boundary
    (assistant re-emission, trusted-utility tool return, or sub-agent
    handoff), violating taint-closure-under-derivation."""


@dataclass
class Segment:
    text: str
    labels: FrozenSet[str]

    @property
    def is_tainted(self) -> bool:
        return any(lbl.startswith(UNTRUSTED_PREFIX) for lbl in self.labels)


@dataclass
class Context:
    segments: list = field(default_factory=list)

    def taint_union(self) -> FrozenSet[str]:
        out = set()
        for seg in self.segments:
            out |= seg.labels
        return frozenset(out)

    def any_tainted(self) -> bool:
        return any(seg.is_tainted for seg in self.segments)


def propagate_tool_output(tool_name: str, inputs: list, output_text: str) -> Segment:
    """Enforce output_taint = max(input_taint). A 'trusted' tool that echoes
    input must not launder it. If any input segment is tainted, the output
    inherits every untrusted label from the inputs."""
    inherited = set()
    for seg in inputs:
        inherited |= {lbl for lbl in seg.labels if lbl.startswith(UNTRUSTED_PREFIX)}
    if inherited:
        # The tool's declared trust class is overridden by dataflow.
        return Segment(text=output_text, labels=frozenset(inherited))
    return Segment(text=output_text, labels=frozenset({"trusted:tool"}))


def gate_side_effect(ctx: Context, action: str, args: dict) -> None:
    """Block side-effecting calls whose arguments derive from tainted data,
    even when the envelope carrying them is labeled trusted. The envelope
    label is necessary but not sufficient; the derivation chain is the
    authority."""
    # Reconstruct derivation: any tainted segment whose text appears in args
    # (verbatim or paraphrased — here we conservatively flag any tainted
    # segment present in-window, since span attribution is unavailable).
    tainted_present = [
        seg for seg in ctx.segments
        if seg.is_tainted and any(tok in str(args) for tok in seg.text.split()[:8])
    ]
    envelope_claims_trust = all(
        lbl in TRUSTED for lbl in ctx.taint_union()
    )
    if tainted_present and envelope_claims_trust:
        raise TaintLaunderingError(
            f"action={action!r}: arguments derive from untrusted segment(s) "
            f"{[s.labels for s in tainted_present]} but envelope is labeled "
            f"trusted {sorted(ctx.taint_union())}. Provenance was re-bound at "
            f"a derivation boundary; refusing side effect."
        )
    if ctx.any_tainted() and action in {"send_email", "exec", "write_file"}:
        raise TaintLaunderingError(
            f"action={action!r}: tainted context present "
            f"({sorted(ctx.taint_union())}); side effect requires "
            f"out-of-band confirmation, not envelope trust."
        )
