# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-context-before-re-entering-a-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-provenance-tainted-context-before-re-entering-a-tool-boundary.warrant.json
# Markdown SHA-256:   034b31e17a744097b6589014fa94ce328168a10a77ba93899598f427fc7a8e6d
# Code AST SHA-256:   723464330b60a230674c86c153678f35274996708cf7192ff9232df6193bc05e
# Verified Classes:   Provenance, TaintLaunderingError, ToolReturn
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum
from typing import Iterable


class Provenance(IntEnum):
    CLEAN = 0
    DERIVED_FROM_UNTRUSTED = 1
    UNTRUSTED = 2


def join(labels: Iterable[Provenance]) -> Provenance:
    return max(labels, default=Provenance.CLEAN)


class TaintLaunderingError(RuntimeError):
    """Raised when a tool return would downgrade provenance without a valid certificate."""


@dataclass(frozen=True)
class ToolReturn:
    span_id: str
    text: str
    provenance: Provenance
    certified_downgrade: bool = False


def admit_tool_return(
    inputs: Iterable[Provenance],
    output: ToolReturn,
    tool_certified_preserving: bool,
) -> Provenance:
    """
    Enforce the return-edge join invariant. Returns the provenance the
    output span may be admitted under, or raises if the harness tried to
    launder taint via an uncertified transformation.
    """
    expected = join(inputs)

    if output.provenance == Provenance.CLEAN and expected != Provenance.CLEAN:
        if not (tool_certified_preserving and output.certified_downgrade):
            raise TaintLaunderingError(
                f"span {output.span_id!r}: tool return claims CLEAN but input join "
                f"is {expected.name}; no certified provenance-preserving downgrade"
            )
        # Certified downgrade: only valid because the tool spec excludes
        # instruction-bearing free text. Still recorded for audit.
        return Provenance.CLEAN

    if output.provenance < expected:
        raise TaintLaunderingError(
            f"span {output.span_id!r}: return provenance {output.provenance.name} "
            f"is below input join {expected.name}"
        )

    return output.provenance


def gate_action_argument(arg_provenance: Provenance, declassified: bool) -> None:
    """Block side-effecting calls whose arguments are tainted and undeclassified."""
    if arg_provenance != Provenance.CLEAN and not declassified:
        raise TaintLaunderingError(
            f"action argument carries {arg_provenance.name} provenance; "
            "explicit declassification required before side effect"
        )
