# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-semantic-convention-baggage-is-dropped-at-a-federated-agent-hop-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-semantic-convention-baggage-is-dropped-at-a-federated-agent-hop-boundary.warrant.json
# Markdown SHA-256:   56847175850753f3f5bf52e4f4eab5ce3b3cd5e19ed87592f4c6c961d79b2914
# Code AST SHA-256:   8770f05e9a41a22512488bd016557d1a9dffc5732073e1b6aaa91d1bd559fce6
# Verified Classes:   BaggagePropagationError, Envelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class BaggagePropagationError(RuntimeError):
    """Raised when an intermediate hop severs semantic-convention baggage."""


# Keys that are security/tenancy-relevant and MUST survive every hop.
MANDATORY_KEYS = frozenset({"agent.tenant", "agent.taint", "traceparent"})
# Keys an intermediate is explicitly permitted to drop (with logging).
DROPPABLE_KEYS = frozenset({"gen_ai.usage.input_tokens"})


@dataclass
class Envelope:
    payload: dict
    baggage: dict = field(default_factory=dict)


def forward_hop(inbound: Envelope, outbound_payload: dict) -> Envelope:
    """Reconstruct an outbound envelope, enforcing baggage continuity."""
    inbound_keys = set(inbound.baggage)
    outbound = Envelope(payload=outbound_payload, baggage=dict(inbound.baggage))

    missing = inbound_keys - set(outbound.baggage)
    severed = {k for k in missing if k not in DROPPABLE_KEYS}
    if severed:
        raise BaggagePropagationError(
            f"hop severed mandatory baggage keys: {sorted(severed)}"
        )

    lost_mandatory = MANDATORY_KEYS - set(outbound.baggage)
    if lost_mandatory:
        raise BaggagePropagationError(
            f"outbound envelope missing mandatory keys: {sorted(lost_mandatory)}"
        )
    return outbound


def receive_hop(inbound: Envelope) -> dict:
    """Fail-closed interpretation of absent security baggage at the receiver."""
    if "agent.taint" not in inbound.baggage:
        # absent != untainted; treat as unknown and refuse privileged action
        raise BaggagePropagationError(
            "agent.taint absent on wire; refusing to assume untainted"
        )
    return inbound.payload
