# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-tainted-argument-provenance-before-a-tool-call-rather-than-sanitize-the-payload-in-place.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-tainted-argument-provenance-before-a-tool-call-rather-than-sanitize-the-payload-in-place.warrant.json
# Markdown SHA-256:   c59154e5ec66180bba7aba79fa5884d874691bb2fd26c37d08cdaca9f8796ec6
# Code AST SHA-256:   0e3945054be27696fc016b456bb9112ef9d27ed1cf8a5a8ec6244b6c32ed0fa4
# Verified Classes:   TaintedArgumentEgress, TaintLabel, ArgGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintedArgumentEgress(RuntimeError):
    """Raised when a tainted value reaches an unenumerable tool parameter slot."""
    pass


@dataclass
class TaintLabel:
    origin: str
    closed: bool = False  # True only if sanitizer proved this branch clean


@dataclass
class ArgGraph:
    values: dict[str, Any] = field(default_factory=dict)
    taint: dict[str, TaintLabel] = field(default_factory=dict)

    def bind(self, slot: str, value: Any, label: TaintLabel | None) -> None:
        self.values[slot] = value
        if label is not None and not label.closed:
            self.taint[slot] = label


OPEN_SLOTS = {"metadata", "extra", "note", "kwargs"}


def gate_tool_call(tool_name: str, graph: ArgGraph, schema: dict[str, str]) -> None:
    # Enumerate every slot the schema declares; anything not declared is open.
    declared = set(schema.keys())
    open_present = [s for s in graph.values if s not in declared or s in OPEN_SLOTS]

    for slot, label in graph.taint.items():
        if slot in open_present:
            raise TaintedArgumentEgress(
                f"tool={tool_name!r} slot={slot!r} carries taint from "
                f"{label.origin!r} into an unenumerable parameter; quarantine "
                f"required, in-place sanitization is unsound here"
            )
        # Even a declared slot is unsafe if the sanitizer only cleared a copy.
        if not label.closed and slot not in schema.get("__sanitized__", set()):
            raise TaintedArgumentEgress(
                f"tool={tool_name!r} slot={slot!r} taint from {label.origin!r} "
                f"was never cleared at the flow level"
            )


# Failure trace from the record:
g = ArgGraph()
g.bind("path", "/reports/summary.md", None)
g.bind("content", "clean text", TaintLabel("document_body", closed=True))  # sanitized copy
g.bind("metadata", {"source": "https://evil.example/x"}, TaintLabel("document_body"))

gate_tool_call(
    "write_file",
    g,
    {"path": "str", "content": "str", "metadata": "dict"},
)
# raises TaintedArgumentEgress: metadata carries document_body taint into an
# unenumerable parameter; the sanitizer cleared content but not the origin.
