# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-quarantine-a-tool-result-before-taint-propagation-collapses-the-trust-lattice.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-quarantine-a-tool-result-before-taint-propagation-collapses-the-trust-lattice.warrant.json
# Markdown SHA-256:   45e6bff2a5b1cb10a928c532739c211e46039ecbcd80cf68ccc79b30f0373d84
# Code AST SHA-256:   5539f2b1fd33ea9fb208ccdab6b63fe9ed12592f82ffaf20472c8325f9f861d6
# Verified Classes:   TrustLabel, TaintPromotionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from enum import IntEnum


class TrustLabel(IntEnum):
    UNTRUSTED_EXTERNAL = 0
    UNTRUSTED_INTERNAL = 1
    TRUSTED_LOCAL = 2
    TRUSTED_SYSTEM = 3


class TaintPromotionError(RuntimeError):
    """Raised when a taint edge would promote a value across a trust boundary."""


def propagate_taint(source_label: TrustLabel,
                    dest_arg_annotation: TrustLabel | None,
                    dest_tool_default: TrustLabel) -> TrustLabel:
    # Fail-closed: an unannotated argument is treated as external.
    effective_dest = (dest_arg_annotation
                      if dest_arg_annotation is not None
                      else TrustLabel.UNTRUSTED_EXTERNAL)

    # Transition-based check: promotion is the trigger, not the endpoints.
    if effective_dest > source_label:
        raise TaintPromotionError(
            f"taint promotion blocked: source={source_label.name} "
            f"dest_arg={effective_dest.name} "
            f"tool_default={dest_tool_default.name}; "
            f"quarantine required before serialization"
        )

    # Monotonic: propagated label never exceeds the source label.
    return min(source_label, effective_dest)


def route_tool_call(source_label: TrustLabel,
                    dest_arg_annotation: TrustLabel | None,
                    dest_tool_default: TrustLabel,
                    declassify_warrant: bool = False) -> TrustLabel:
    try:
        return propagate_taint(source_label, dest_arg_annotation, dest_tool_default)
    except TaintPromotionError:
        if declassify_warrant and dest_arg_annotation == TrustLabel.UNTRUSTED_EXTERNAL:
            # Explicit sanitizer warrant: output is declassified, not promoted.
            return TrustLabel.UNTRUSTED_EXTERNAL
        raise
