# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-at-the-llm-mediation-boundary-when-a-tool-returns-data-the-model-paraphrases-rather-than-quotes.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-at-the-llm-mediation-boundary-when-a-tool-returns-data-the-model-paraphrases-rather-than-quotes.warrant.json
# Markdown SHA-256:   422e33049c7cea1ee6225d0c858ec40f42d3a030c3c3ee408210151d13fb7081
# Code AST SHA-256:   9b92a946c50c4877f0933ef34628181343311454685461f1a7cccea54e9afa31
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a generated tool argument escapes span-level taint tracking."""
    pass


GENERATIVE_TOOLS = {"shell", "python_exec", "send_message", "fetch_url"}


def check_taint_propagation(
    episode_tainted: bool,
    tool_name: str,
    argument: str,
    tainted_spans: list[str],
    provenance_rederivable: bool,
) -> None:
    """
    Enforce the sticky-context invariant at the LLM-mediation boundary.

    Span matching alone is unsound when the model paraphrases tainted
    content into a generative tool argument. If the episode is tainted
    and the tool is generative, we require either (a) the argument is
    re-derivable from labeled-clean context, or (b) an explicit warrant.
    """
    if not episode_tainted:
        return

    if tool_name not in GENERATIVE_TOOLS:
        # Selection-only tools: span matching is adequate.
        return

    span_overlap = any(span and span in argument for span in tainted_spans)

    if span_overlap:
        raise TaintLaunderingError(
            f"Verbatim tainted content in {tool_name} argument; blocked."
        )

    if not provenance_rederivable:
        # No overlap, but the episode is tainted and the argument is
        # generated. Span matching cannot prove independence. This is
        # the laundering boundary: refuse rather than pass.
        raise TaintLaunderingError(
            f"{tool_name} argument is generated from a tainted episode "
            f"and is not re-derivable from clean context. "
            f"Span matching reports no overlap, but causal influence "
            f"cannot be excluded. Require warrant or clean episode."
        )


def guarded_tool_call(
    episode_tainted: bool,
    tool_name: str,
    argument: str,
    tainted_spans: list[str],
    provenance_rederivable: bool,
) -> str:
    check_taint_propagation(
        episode_tainted, tool_name, argument, tainted_spans, provenance_rederivable
    )
    return f"executed:{tool_name}"
