# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-agent-handoffs-when-an-auditor-agent-re-derives-provenance-from-tool-output-rather-than-from-the-warr.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-agent-handoffs-when-an-auditor-agent-re-derives-provenance-from-tool-output-rather-than-from-the-warr.warrant.json
# Markdown SHA-256:   8b268e316249253284e3c7f4ea585b22b50cb5dd92ba228d4d5298118e88faf8
# Code AST SHA-256:   c8a73a60c3b59017e2e2706e0c76bbf91ee4ec3b7abcc5be32e2e5405f7ffe11
# Verified Classes:   TaintMonotonicityError, Envelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintMonotonicityError(RuntimeError):
    """Raised when an agent emits an artifact whose declared taint
    under-approximates the join of its declared inputs (taint laundering)."""


@dataclass(frozen=True)
class Envelope:
    sender: str
    declared_inputs: FrozenSet[str]   # labels of all inputs the sender consumed
    declared_taint: FrozenSet[str]    # label the sender claims for its output
    payload: str = ""


def join(labels: FrozenSet[str]) -> FrozenSet[str]:
    # Taint join is set union; a label is never removed except by explicit declassify.
    return frozenset(labels)


def admit(env: Envelope, *, allow_declassify: bool = False) -> Envelope:
    required = join(env.declared_inputs)
    if not allow_declassify and not required.issubset(env.declared_taint):
        raise TaintMonotonicityError(
            f"agent {env.sender!r} emitted taint {sorted(env.declared_taint)} "
            f"but consumed inputs requiring {sorted(required)}; "
            f"laundered labels: {sorted(required - env.declared_taint)}"
        )
    return env


def executor_receive(env: Envelope, capability_scope: str) -> Envelope:
    # Privileged actions require clean taint; tainted envelopes are quarantined.
    env = admit(env)
    if env.declared_taint:
        raise TaintMonotonicityError(
            f"executor refused {capability_scope!r}: envelope tainted "
            f"{sorted(env.declared_taint)}; declassify explicitly before privileged write"
        )
    return env
