# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-taint-provenance-at-the-a2a-envelope-boundary-before-delegating-to-a-sub-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-taint-provenance-at-the-a2a-envelope-boundary-before-delegating-to-a-sub-agent.warrant.json
# Markdown SHA-256:   441fe526d33e7b5632602a31ebd8a3eff0c390182a5a13d38fffc82be54e965b
# Code AST SHA-256:   f328c59ec696aacaf395317b6ff217095826da688a11b9becc2e69e5863b2d96
# Verified Classes:   TaintProvenanceError, Envelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintProvenanceError(RuntimeError):
    """Raised when a delegated call would drop or launder taint provenance."""


@dataclass(frozen=True)
class Envelope:
    payload: str
    taint: FrozenSet[str] = field(default_factory=frozenset)


def delegate(orchestrator_taint: FrozenSet[str], upstream: Envelope,
             transport_supports_envelope_taint: bool) -> Envelope:
    # Effective taint is the union of everything inherited plus local.
    effective = frozenset(orchestrator_taint) | upstream.taint

    if effective and not transport_supports_envelope_taint:
        # Cannot carry structured taint downstream: must not delegate.
        raise TaintProvenanceError(
            f"refusing to delegate tainted payload {sorted(effective)}: "
            "transport cannot carry structured envelope taint; "
            "flattening to prose would launder provenance"
        )

    # Rebuild a fresh envelope carrying the accumulated taint.
    return Envelope(payload=upstream.payload, taint=effective)


def enforce_tool_policy(env: Envelope, tool: str) -> None:
    if "external_document" in env.taint and tool.startswith("exfil."):
        raise TaintProvenanceError(
            f"tool {tool} denied under envelope taint {sorted(env.taint)}"
        )
