# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-implicit-label-laundering-when-a-tainted-value-is-re-derived-by-an-untainted-sub-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-implicit-label-laundering-when-a-tainted-value-is-re-derived-by-an-untainted-sub-agent.warrant.json
# Markdown SHA-256:   6bee981dd47c21ef5afbed40bfa990c6fc78dbbe9472bfaba6da43882086bedf
# Code AST SHA-256:   143b9231d40c52d431fee6b5c65d8f1108f0359a0c1c64b30ef7943781377a02
# Verified Classes:   TaintLaunderingError, Labeled, HandoffEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a value crosses a boundary without carrying its taint label,
    or when a declassification is attempted without a valid downgrade token."""


@dataclass(frozen=True)
class Labeled:
    value: Any
    tainted: bool


@dataclass
class HandoffEnvelope:
    # C1: label is a first-class field on the wire schema.
    payload: Labeled
    origin: str
    downgrade_token: str | None = None


def join(a: bool, b: bool) -> bool:
    return a or b


def receive_handoff(
    env: HandoffEnvelope,
    consumer_was_tainted: bool,
    valid_downgrade_tokens: set[str],
) -> Labeled:
    """Consumer-side join. The producer's declared label is a hint; the consumer
    joins it with its own state and refuses to trust an unlabeled payload."""
    if not isinstance(env.payload, Labeled):
        # C3 violation: a bare value crossed the boundary. This is a laundering
        # attempt (or a schema bug) and must fail closed, not default to clean.
        raise TaintLaunderingError(
            f"handoff from {env.origin!r} carried an unlabeled payload; "
            "refusing to assume taint=⊥"
        )

    declared = env.payload.tainted
    joined = join(declared, consumer_was_tainted)

    if env.downgrade_token is not None:
        if env.downgrade_token not in valid_downgrade_tokens:
            raise TaintLaunderingError(
                f"declassification from {env.origin!r} used an unrecognized "
                f"downgrade token {env.downgrade_token!r}"
            )
        # Declassification is explicit, logged, and value-reviewed elsewhere.
        return Labeled(value=env.payload.value, tainted=False)

    return Labeled(value=env.payload.value, tainted=joined)


def gate_tool_execution(arg: Labeled, tool: str) -> None:
    """Downstream guard: tainted arguments may not reach effectful tools."""
    if arg.tainted:
        raise TaintLaunderingError(
            f"refusing to pass tainted value to effectful tool {tool!r}; "
            "route through an explicit downgrade gate"
        )
