# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-aware-tool-gating-when-the-policy-decision-point-and-the-tool-executor-disagree-about-the-provenance-of-a-value.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-aware-tool-gating-when-the-policy-decision-point-and-the-tool-executor-disagree-about-the-provenance-of-a-value.warrant.json
# Markdown SHA-256:   25ba57ea419a2d91b197adc73a9c000f7f022e0f85c891455409674bfe226328
# Code AST SHA-256:   8d2aabf1cb84c22c1293d06bdebb128a163ecc66636633cc57ce203558d2bb0a
# Verified Classes:   TaintGateError, Label, ValueHandle, ToolCall
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TaintGateError(RuntimeError):
    """Raised when a tool invocation's provenance cannot be soundly resolved."""


class Label(Enum):
    UNTAINTED = "untainted"
    EXTERNAL_UNTRUSTED = "external_untrusted"
    UNRESOLVED = "unresolved"  # derived from unmodeled transform or tainted context


@dataclass
class ValueHandle:
    id: str
    label: Label
    context_sources: frozenset = field(default_factory=frozenset)


@dataclass
class ToolCall:
    tool: str
    args: dict  # arg name -> ValueHandle


DECLASSIFIERS = {
    # name -> (input_label_allowed, output_label)
    "extract_hostname_v1": (Label.EXTERNAL_UNTRUSTED, Label.UNTAINTED),
    "extract_ipv4_v1": (Label.EXTERNAL_UNTRUSTED, Label.UNTAINTED),
}


def apply_declassifier(name: str, src: ValueHandle) -> ValueHandle:
    if name not in DECLASSIFIERS:
        raise TaintGateError(f"unknown declassifier {name!r}")
    allowed_in, out = DECLASSIFIERS[name]
    if src.label != allowed_in:
        raise TaintGateError(
            f"declassifier {name} cannot clear label {src.label}"
        )
    return ValueHandle(id=f"{src.id}->{name}", label=out)


def model_generate(prompt_handles: list, output_id: str) -> ValueHandle:
    """Model output inherits the join of its context taint. This is the
    missing edge that caused the laundering gap."""
    joined = frozenset(h.id for h in prompt_handles)
    if any(h.label in (Label.EXTERNAL_UNTRUSTED, Label.UNRESOLVED)
           for h in prompt_handles):
        return ValueHandle(output_id, Label.UNRESOLVED, joined)
    return ValueHandle(output_id, Label.UNTAINTED, joined)


def gate(call: ToolCall, require_approval_on: set) -> str:
    """Returns 'allow' | 'deny' | 'escalate'. Fails closed on unresolved."""
    for name, handle in call.args.items():
        if handle.label == Label.UNRESOLVED:
            # C4: unknown provenance never auto-allows
            return "escalate"
        if handle.label in require_approval_on:
            return "escalate"
    return "allow"


# --- Demonstration of the failure and the fix ---
def demo():
    fetched = ValueHandle("v_17", Label.EXTERNAL_UNTRUSTED)
    # Old (broken) behavior: summary treated as untainted MODEL_GENERATED.
    broken_summary = ValueHandle("v_18", Label.UNTAINTED)
    broken_call = ToolCall("shell.exec", {"cmd": broken_summary})
    assert gate(broken_call, {Label.EXTERNAL_UNTRUSTED}) == "allow"  # bypass

    # Corrected behavior: summary inherits context taint.
    summary = model_generate([fetched], "v_18")
    if summary.label != Label.UNRESOLVED:
        raise TaintGateError("context-taint join failed to propagate")
    fixed_call = ToolCall("shell.exec", {"cmd": summary})
    decision = gate(fixed_call, {Label.EXTERNAL_UNTRUSTED})
    if decision != "escalate":
        raise TaintGateError(
            f"gate allowed unresolved provenance: {decision}"
        )

    # Only a validated declassifier may clear taint.
    host = apply_declassifier("extract_hostname_v1", fetched)
    safe_call = ToolCall("dns.resolve", {"host": host})
    assert gate(safe_call, {Label.EXTERNAL_UNTRUSTED}) == "allow"


if __name__ == "__main__":
    demo()
