# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-launder-a-tainted-fact-across-an-a2a-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-launder-a-tainted-fact-across-an-a2a-handoff.warrant.json
# Markdown SHA-256:   c7c6ff47bba15ad9c0ed9889623a90873a3f864b5e555fa5cbf4576bf29e82a2
# Code AST SHA-256:   bc88cf17e22632ceca3945ae44602d680b37162dfc4c0f174a664dc5556c9518
# Verified Classes:   TaintError, Trust, Fact, HandoffEnvelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Any


class TaintError(RuntimeError):
    """Raised when a handoff would launder taint or violate monotonicity."""


class Trust(IntEnum):
    # Ordered so that join() is max() and "unknown" outranks "first_party"
    # only in the sense that it must be treated as untrusted downstream.
    FIRST_PARTY = 0
    UNKNOWN = 1
    UNTRUSTED = 2


def join_taint(*levels: Trust) -> Trust:
    """Least upper bound: a derived value inherits the worst input taint.

    UNKNOWN is deliberately >= FIRST_PARTY so that an unlabeled input cannot
    be promoted; callers must treat UNKNOWN as UNTRUSTED at the receiver.
    """
    if not levels:
        return Trust.UNKNOWN
    return Trust(max(int(l) for l in levels))


@dataclass
class Fact:
    value: Any
    taint: Trust
    derived_from: tuple[str, ...] = field(default_factory=tuple)


@dataclass
class HandoffEnvelope:
    task_id: str
    result: Fact
    sender_id: str


def emit_handoff(
    sender_id: str,
    task_id: str,
    inputs: list[Fact],
    transformed_value: Any,
    envelope_supports_taint: bool,
) -> HandoffEnvelope:
    """Sender-side guard: refuse to emit a transformed result that would
    launder taint across a boundary that cannot carry it."""
    result_taint = join_taint(*(f.taint for f in inputs))
    if not envelope_supports_taint and result_taint is not Trust.FIRST_PARTY:
        raise TaintError(
            f"agent {sender_id!r} cannot emit task {task_id!r}: derived result "
            f"carries taint={result_taint.name} but the A2A envelope has no "
            f"taint channel; emitting would launder provenance"
        )
    return HandoffEnvelope(
        task_id=task_id,
        result=Fact(
            value=transformed_value,
            taint=result_taint,
            derived_from=tuple(f.value if isinstance(f.value, str) else repr(f.value) for f in inputs),
        ),
        sender_id=sender_id,
    )


def receive_handoff(
    env: HandoffEnvelope,
    as_instruction: bool,
    rederived_independently: bool,
) -> Fact:
    """Receiver-side guard: default-closed. UNKNOWN is treated as UNTRUSTED,
    and an untrusted fact may never be promoted to instruction."""
    effective = Trust.UNTRUSTED if env.result.taint is Trust.UNKNOWN else env.result.taint

    if effective is Trust.UNTRUSTED and as_instruction and not rederived_independently:
        raise TaintError(
            f"agent received task {env.task_id!r} from {env.sender_id!r} with "
            f"taint={effective.name}; refusing to treat as instruction without "
            f"independent re-derivation"
        )

    promoted = effective
    if rederived_independently and effective is Trust.UNTRUSTED:
        promoted = Trust.FIRST_PARTY  # only a genuine re-derivation may promote

    return Fact(value=env.result.value, taint=promoted, derived_from=env.result.derived_from)
