# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-context-through-a-schema-conformant-tool-argument-and-the-sandbox-trusts-the-call-site-instead-of-the-d.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-tainted-context-through-a-schema-conformant-tool-argument-and-the-sandbox-trusts-the-call-site-instead-of-the-d.warrant.json
# Markdown SHA-256:   e6c2afd0dd7428f8d08088987ca1c826b2d2b28772c92f7eea5fc121f02396be
# Code AST SHA-256:   da352656c7a923b90bbb455e3b6ae228a4f28244644af0ee5e9ffd22cd935bc7
# Verified Classes:   TaintLaunderingError, TaintLabel
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a tool call's arguments cannot be proven free of labeled-source derivation."""
    pass


class TaintLabel:
    def __init__(self, source_id: str, span: tuple[int, int]):
        self.source_id = source_id
        self.span = span


def gate_egress_tool_call(
    tool_name: str,
    args: dict,
    labeled_spans: list[TaintLabel],
    sink_policy: dict[str, set[str]],
    derivation_refs: dict[str, list[str]] | None = None,
) -> None:
    """
    Conservative provenance gate for egress tools.

    Sound rule: a free-text argument is ALLOWed only if the model supplied a
    verifiable derivation reference (copy_span primitive) OR the context
    contains no labeled spans contributing to that field.

    If derivation_refs is None (model cannot emit them), any free-text
    argument in a context with labeled spans is treated as tainted.
    """
    free_text_fields = {
        k for k, v in args.items() if isinstance(v, str) and len(v) > 0
    }
    if not free_text_fields:
        return  # structured-only call, no laundering channel

    if not labeled_spans:
        return  # no labeled context, nothing to launder

    if derivation_refs is None:
        # Cannot prove non-derivation: conservative block.
        raise TaintLaunderingError(
            f"tool={tool_name} has free-text fields {sorted(free_text_fields)} "
            f"and context contains {len(labeled_spans)} labeled span(s); "
            f"no derivation references supplied, cannot prove non-derivation"
        )

    for field in free_text_fields:
        refs = derivation_refs.get(field, [])
        for ref in refs:
            if ref not in {lbl.source_id for lbl in labeled_spans}:
                raise TaintLaunderingError(
                    f"field={field} cites derivation {ref!r} not present in labeled spans"
                )
        allowed = sink_policy.get(field, set())
        inherited = {lbl.source_id for lbl in labeled_spans if lbl.source_id in refs}
        if inherited and not inherited.issubset(allowed):
            raise TaintLaunderingError(
                f"field={field} derives from {sorted(inherited)} "
                f"but sink policy permits only {sorted(allowed)}"
            )
    # If we reach here, every free-text field is either unlabeled or
    # explicitly derived from a permitted labeled span.
