# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-injection-taint-labels-through-tool-return-values-rather-than-only-through-tool-arguments.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-injection-taint-labels-through-tool-return-values-rather-than-only-through-tool-arguments.warrant.json
# Markdown SHA-256:   4e1eb855c44618e16ff3944faf13478766d3aca043c2fb1b360062449c89ed20
# Code AST SHA-256:   a8df3f49f83f8d8a12ec8482c89fb4cad0fd5055b02c5dcaa1fb611f84c0b234
# Verified Classes:   TaintLaunderingError, Context
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a side-effecting call's arguments carry no lineage
    for bytes that were derived from a live untrusted source."""
    pass


@dataclass
class Context:
    # Set of untrusted source IDs currently resident in the model context.
    live_untrusted: FrozenSet[str] = frozenset()
    # Arguments the model claims are derived from which sources.
    declared_provenance: dict = field(default_factory=dict)


def check_egress(ctx: Context, tool_name: str, args: dict,
                 side_effecting_tools: FrozenSet[str]) -> None:
    """Conservative-join gate: refuse egress while any untrusted source
    is resident, unless the argument's provenance was verified by a
    non-LLM checker (represented here by exact-span citation)."""
    if tool_name not in side_effecting_tools:
        return
    if not ctx.live_untrusted:
        return
    for arg_name, value in args.items():
        cited = ctx.declared_provenance.get(arg_name, frozenset())
        # A model-declared citation is NOT sufficient: it must be a subset
        # of live sources AND the verifier must have confirmed the span.
        # Absent verifier confirmation, treat as laundered.
        verified = ctx.declared_provenance.get(f"{arg_name}__verified", False)
        if not verified:
            raise TaintLaunderingError(
                f"egress via {tool_name}.{arg_name} while untrusted sources "
                f"{sorted(ctx.live_untrusted)} are resident in context; "
                f"model-declared provenance {sorted(cited)} is unverified. "
                f"Refusing to emit — declassify explicitly or evict context."
            )


def handoff_to_subagent(parent: Context, child: Context) -> Context:
    """Child's live untrusted labels must union into the parent on return,
    or summarization becomes a laundering channel."""
    return Context(
        live_untrusted=parent.live_untrusted | child.live_untrusted,
        declared_provenance={**parent.declared_provenance,
                             **child.declared_provenance},
    )
