# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tainted-tool-output-from-re-entering-the-reasoning-context-as-trusted-instruction.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tainted-tool-output-from-re-entering-the-reasoning-context-as-trusted-instruction.warrant.json
# Markdown SHA-256:   b4288eaf2a94e25de79be4f4eeb7cb14fac235fec15199580d07c7773b353065
# Code AST SHA-256:   f5a980793b2ea66abc035e2fdfe66deb7e9024fd5d8c800be8e9d4fb07b895fc
# Verified Classes:   TaintViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintViolation(RuntimeError):
    """Raised when a tainted span is placed in a directive position or
    used to derive an argument for a gated capability without declassification."""
    pass


GATED_CAPABILITIES = {"delete_records", "transfer_funds", "send_email_external"}


def reinject(span: dict, target_region: str, runtime) -> dict:
    """
    span: {"text": str, "taint_set": frozenset[str], "source_tool": str}
    target_region: "directive" | "data"
    """
    taint = span["taint_set"]

    # Invariant 1: tainted spans may not occupy directive positions.
    if target_region == "directive" and taint:
        raise TaintViolation(
            f"span from {span['source_tool']} carries taint {sorted(taint)} "
            f"and cannot be placed in a directive region"
        )

    # Invariant 2: placement is recorded so downstream capability gating
    # can consult the taint of the arguments it is asked to execute.
    runtime.record_placement(span_id=span.get("id"), region=target_region, taint=taint)
    return span


def invoke_tool(tool_name: str, args: dict, arg_taint: frozenset[str], runtime) -> dict:
    if tool_name in GATED_CAPABILITIES and arg_taint:
        # Invariant 3: a gated capability cannot be reached by arguments
        # descended from tainted data without out-of-band confirmation.
        if not runtime.has_out_of_band_confirmation(tool_name, args):
            raise TaintViolation(
                f"gated capability {tool_name} invoked with tainted arguments "
                f"{sorted(arg_taint)}; no out-of-band confirmation on record"
            )

    result = runtime.execute(tool_name, args)

    # Invariant 4: taint is monotone under transformation. The output of a
    # tool inherits the union of its inputs' taint; tools may add, never clear.
    result["taint_set"] = frozenset(arg_taint | result.get("taint_set", frozenset()))
    return result
