# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-a-tool-call-argument-is-derived-from-a-mixture-of-trusted-and-untrusted-context.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-a-tool-call-argument-is-derived-from-a-mixture-of-trusted-and-untrusted-context.warrant.json
# Markdown SHA-256:   3338b9e08a640070e72eeb754ac41dfe0838569698cfe89159cc7f671bf78a2c
# Code AST SHA-256:   04dba7baf86de086c2cf0174c80975be6e9dbc3a905cdba646ebd0021dd69e9b
# Verified Classes:   TaintGateViolation, Provenance, ToolSchema
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintGateViolation(RuntimeError):
    """Raised when a tool-call argument carries untrusted provenance
    that the tool schema does not authorize for that slot."""
    pass


@dataclass(frozen=True)
class Provenance:
    segment_ids: FrozenSet[str]
    untrusted: FrozenSet[str]  # subset of segment_ids that are untrusted


@dataclass
class ToolSchema:
    name: str
    # slot -> set of trusted segment ids allowed to declassify untrusted bytes
    declassify_from: dict = field(default_factory=dict)


def gate_argument(slot: str, prov: Provenance, schema: ToolSchema,
                  context_has_untrusted: bool) -> str:
    tainted = bool(prov.segment_ids & prov.untrusted)
    # Invariant: if any untrusted segment is in the window, model-typed
    # literals are tainted too (they are a function of that context).
    if not tainted and context_has_untrusted and not prov.segment_ids:
        tainted = True
    if not tainted:
        return "ALLOW"
    allowed = schema.declassify_from.get(slot, set())
    if prov.untrusted <= set(allowed):
        return "ALLOW"
    raise TaintGateViolation(
        f"slot {slot!r} on tool {schema.name!r} carries untrusted provenance "
        f"{sorted(prov.untrusted)} with no declassification clause; "
        f"model retries cannot clear taint while untrusted context remains."
    )


def invoke(schema: ToolSchema, args: dict, provenance: dict,
           context_has_untrusted: bool):
    for slot, prov in provenance.items():
        gate_argument(slot, prov, schema, context_has_untrusted)
    # ... dispatch to tool ...
    return {"status": "dispatched", "tool": schema.name, "args": args}
