# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-and-quarantine-a-taint-laundered-sub-agent-when-provenance-attestations-are-stripped-across-a-two-hop-federated-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-and-quarantine-a-taint-laundered-sub-agent-when-provenance-attestations-are-stripped-across-a-two-hop-federated-handoff.warrant.json
# Markdown SHA-256:   b5f240c068fe46a22a994038dbf373498fb816e58bb1e6e5c40188f79d3a7078
# Code AST SHA-256:   d78410690b271e4105af27652b5ae9352d19923f186eb1c33014f80b18f3b565
# Verified Classes:   TaintLaunderingError, RouteAction, Envelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class TaintLaunderingError(RuntimeError):
    """Raised when a message's provenance chain cannot be proven clean."""


class RouteAction(Enum):
    ROUTE = "route"
    SANDBOX = "sandbox"
    QUARANTINE = "quarantine"
    REJECT = "reject"


@dataclass(frozen=True)
class Envelope:
    sender_id: str
    warrant_valid: bool
    schema_version: int
    content_envelope_present: bool
    taint_label: str | None  # None == field absent, NOT "clean"
    hops: int


TAINT_FIELD_MIN_VERSION = 4  # schema 1.4


def route(env: Envelope, quarantined: set[str]) -> RouteAction:
    if env.sender_id in quarantined:
        return RouteAction.REJECT

    if not env.warrant_valid:
        # Identity failure is not a taint failure; do not quarantine.
        return RouteAction.REJECT

    if not env.content_envelope_present:
        # No signed content lineage: treat payload as fully tainted.
        quarantined.add(env.sender_id)
        raise TaintLaunderingError(
            f"sender {env.sender_id} emitted payload with no content envelope; "
            f"provenance unprovable, quarantining"
        )

    if env.schema_version < TAINT_FIELD_MIN_VERSION:
        # Serializer cannot represent taint; it will silently prune it.
        quarantined.add(env.sender_id)
        raise TaintLaunderingError(
            f"sender {env.sender_id} schema v{env.schema_version} "
            f"< taint field v{TAINT_FIELD_MIN_VERSION}; taint would be laundered"
        )

    if env.taint_label is None:
        # The laundering signature: valid warrant, present envelope, absent label.
        quarantined.add(env.sender_id)
        raise TaintLaunderingError(
            f"sender {env.sender_id} dropped taint label on hop {env.hops}; "
            f"absence-as-taint boundary triggered"
        )

    if env.taint_label != "none":
        return RouteAction.SANDBOX

    return RouteAction.ROUTE


def handle_ingress(env: Envelope, quarantined: set[str]) -> RouteAction:
    try:
        return route(env, quarantined)
    except TaintLaunderingError:
        # Quarantine already recorded; escalate for replay audit.
        raise
