# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-aware-tool-allow-deny-policy-when-a-single-tool-call-both-consumes-tainted-input-and-emits-untainted-looking-outp.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-aware-tool-allow-deny-policy-when-a-single-tool-call-both-consumes-tainted-input-and-emits-untainted-looking-outp.warrant.json
# Markdown SHA-256:   4ae0e23d49aeea5685a2c097772dc8515a02b0294c8d5690e20a7b89d9713354
# Code AST SHA-256:   c1b0bec3c003db2e27f983a7f106e10f1d2cace9dd7286380c732399eb8eec2e
# Verified Classes:   TaintPolicyViolation, Label, ToolPolicy
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintPolicyViolation(RuntimeError):
    """Raised when a tool call would launder taint or violate the derivation invariant."""
    pass


@dataclass(frozen=True)
class Label:
    sources: frozenset[str]  # e.g. {"untrusted:web"}

    def join(self, other: "Label") -> "Label":
        return Label(self.sources | other.sources)

    @property
    def is_trusted(self) -> bool:
        return not self.sources


TRUSTED = Label(frozenset())


@dataclass
class ToolPolicy:
    name: str
    requires_trusted_args: bool
    # Sanitizers must be registered explicitly with a justification.
    sanitizer_justification: str | None = None
    sanitizer_reduces_to: Label | None = None


def derive_output_label(policy: ToolPolicy, arg_labels: list[Label]) -> Label:
    """Conservative output-taint derivation.

    Default: output taint is the join of all input taints.
    Exception: a tool registered as a sanitizer with a justification may
    reduce taint to a declared level. Schema shape is irrelevant here.
    """
    joined = TRUSTED
    for lbl in arg_labels:
        joined = joined.join(lbl)

    if policy.sanitizer_justification is None:
        return joined  # no laundering permitted

    if policy.sanitizer_reduces_to is None:
        raise TaintPolicyViolation(
            f"sanitizer {policy.name!r} registered without a declared reduction target"
        )
    # Sanitizer may only reduce taint, never increase it.
    if not policy.sanitizer_reduces_to.sources.issubset(joined.sources):
        raise TaintPolicyViolation(
            f"sanitizer {policy.name!r} declares reduction to labels not present in input"
        )
    return policy.sanitizer_reduces_to


def invoke_tool(policy: ToolPolicy, args: dict[str, Any], arg_labels: dict[str, Label]) -> tuple[Any, Label]:
    """Gate the call on argument taint, then derive output taint conservatively."""
    if policy.requires_trusted_args:
        for name, lbl in arg_labels.items():
            if not lbl.is_trusted:
                raise TaintPolicyViolation(
                    f"tool {policy.name!r} requires trusted args; "
                    f"arg {name!r} carries taint {sorted(lbl.sources)}"
                )

    output_label = derive_output_label(policy, list(arg_labels.values()))

    # A structured return type is NOT evidence of sanitization.
    result = _execute(policy.name, args)
    return result, output_label


def _execute(name: str, args: dict[str, Any]) -> Any:
    # Placeholder for the actual tool dispatch.
    return {"ok": True, "tool": name}


def check_downstream_use(value_label: Label, target_policy: ToolPolicy) -> None:
    """Enforce that a derived value is not used where trusted provenance is required."""
    if target_policy.requires_trusted_args and not value_label.is_trusted:
        raise TaintPolicyViolation(
            f"downstream tool {target_policy.name!r} requires trusted input; "
            f"received value tainted by {sorted(value_label.sources)}"
        )
