# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-value-that-re-enters-through-a-tool-s-return-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-tainted-value-that-re-enters-through-a-tool-s-return-channel.warrant.json
# Markdown SHA-256:   3297f10173652839ae62bf16df3f08ca901886ab85e445e70e62e8100ae2d3c4
# Code AST SHA-256:   4587426a515cf6725ef7f2931c826e57e09b285fe8b5d58b3b1a8cf1c6b30e34
# Verified Classes:   Provenance, TaintLaunderingError, LabeledValue
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class Provenance(Enum):
    TRUSTED = 0
    UNTRUSTED = 1

    def join(self, other: "Provenance") -> "Provenance":
        # Least upper bound: UNTRUSTED dominates.
        return Provenance(max(self.value, other.value))


class TaintLaunderingError(RuntimeError):
    """Raised when a tool return drops provenance and would re-enter as trusted."""


@dataclass
class LabeledValue:
    value: str
    provenance: Provenance


def invoke_tool(tool_name: str, args: list[LabeledValue], raw_return: str,
                return_declares_provenance: bool) -> LabeledValue:
    arg_join = Provenance.TRUSTED
    for a in args:
        arg_join = arg_join.join(a.provenance)

    if return_declares_provenance:
        # Tool carried its own label; join with args (monotone).
        return LabeledValue(raw_return, arg_join)

    # Tool return schema is label-blind. Fail closed: inherit arg taint.
    if arg_join is Provenance.UNTRUSTED:
        raise TaintLaunderingError(
            f"tool '{tool_name}' returned unlabeled value derived from "
            f"UNTRUSTED args; refusing to re-enter as TRUSTED. "
            f"Wrap tool or add provenance field to return schema."
        )
    return LabeledValue(raw_return, Provenance.TRUSTED)


def action_gate(value: LabeledValue, side_effecting: bool) -> None:
    if side_effecting and value.provenance is Provenance.UNTRUSTED:
        raise TaintLaunderingError(
            "refusing side-effecting action on UNTRUSTED-derived value"
        )
