# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-taint-label-as-surviving-a-tool-call-boundary-and-when-does-label-laundering-force-a-hard-refusal.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-taint-label-as-surviving-a-tool-call-boundary-and-when-does-label-laundering-force-a-hard-refusal.warrant.json
# Markdown SHA-256:   70a579fcec78ba250bff891ce4aae83301a19c6e9d4eb7783a4ae81008f2f918
# Code AST SHA-256:   da2ca43a17d1a156f837565cdf27b262b5afa8efa648ab54092fc9e7c85eb827
# Verified Classes:   TaintLaunderingError, SinkPolicyViolation, ToolSpec
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, FrozenSet

LABELS = frozenset({"TRUSTED", "USER_SUPPLIED", "EXTERNAL_RETRIEVED", "UNTRUSTED"})
FORBIDDEN_FOR_SINK = {
    "post_slack": frozenset({"EXTERNAL_RETRIEVED", "UNTRUSTED"}),
    "shell_exec": frozenset({"USER_SUPPLIED", "EXTERNAL_RETRIEVED", "UNTRUSTED"}),
    "write_file": frozenset({"EXTERNAL_RETRIEVED", "UNTRUSTED"}),
}


class TaintLaunderingError(RuntimeError):
    """Raised when a tool spec would drop a taint label without a proof obligation."""


class SinkPolicyViolation(RuntimeError):
    """Raised when a call's argument labels intersect the sink's forbidden set."""


@dataclass(frozen=True)
class ToolSpec:
    name: str
    taint_fn: Callable[[FrozenSet[str]], FrozenSet[str]]
    llm_mediated: bool
    proof_obligation: str | None = None  # e.g. 'regex:^[0-9]+$'


def _validate_spec(spec: ToolSpec) -> None:
    # Any LLM-mediated tool is a transformer, never a sanitizer.
    if spec.llm_mediated:
        for lbl in LABELS:
            if spec.taint_fn(frozenset({lbl})) != frozenset({lbl}):
                raise TaintLaunderingError(
                    f"tool {spec.name!r} is llm_mediated but taint_fn drops {lbl!r}; "
                    "model-mediated transforms may only propagate"
                )
    # A non-LLM tool may drop labels only with a proof obligation.
    drops = any(
        spec.taint_fn(frozenset({lbl})) == frozenset()
        for lbl in LABELS if lbl != "TRUSTED"
    )
    if drops and not spec.proof_obligation:
        raise TaintLaunderingError(
            f"tool {spec.name!r} drops taint without a proof_obligation; "
            "declare a grammar constraint or set taint_fn=propagate"
        )


def dispatch(spec: ToolSpec, args: dict[str, tuple[object, FrozenSet[str]]]) -> tuple[object, FrozenSet[str]]:
    _validate_spec(spec)

    # Sink check on argument positions, before invocation.
    forbidden = FORBIDDEN_FOR_SINK.get(spec.name)
    if forbidden is not None:
        for argname, (_val, labels) in args.items():
            hit = labels & forbidden
            if hit:
                raise SinkPolicyViolation(
                    f"sink {spec.name!r} arg {argname!r} carries {sorted(hit)}; refusing"
                )

    # Invoke, then compute output labels as the union of taint_fn over inputs,
    # conservatively over-approximated (never intersect, never drop TRUSTED).
    input_labels = frozenset().union(*(lbls for _v, lbls in args.values()))
    out_labels = spec.taint_fn(input_labels)
    if not input_labels.issubset(out_labels | {"TRUSTED"}):
        # Defensive: taint_fn must be monotone; a non-monotone fn is a spec bug.
        raise TaintLaunderingError(
            f"tool {spec.name!r} taint_fn is non-monotone: "
            f"inputs {sorted(input_labels)} not preserved in outputs {sorted(out_labels)}"
        )
    return _invoke(spec, args), out_labels


def _invoke(spec: ToolSpec, args: dict) -> object:
    # Real implementation dispatches to the registered callable; elided here.
    raise NotImplementedError


# Example: the exact bug from the observed trace, now caught at registration.
bad_summarizer = ToolSpec(
    name="summarize",
    taint_fn=lambda labels: frozenset(),  # the laundering
    llm_mediated=True,
)
try:
    _validate_spec(bad_summarizer)
except TaintLaunderingError as e:
    print(f"rejected at startup: {e}")
