# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-delegated-capability-attenuation-bypass-across-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-delegated-capability-attenuation-bypass-across-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   cb6949b5254bfe0308e7dfc6b1cdda97cbf565c132c6477a2153c0a25d51e1bf
# Code AST SHA-256:   f6f64b9ebda40a5240d73acc4592398a05bbff3d93d8c216889d47b496688781
# Verified Classes:   AttenuationBypassError, DelegatedToken, PolicyBundle
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class AttenuationBypassError(RuntimeError):
    """Raised when a delegated token's scope is not re-validated against live receiving-org policy."""
    pass


@dataclass(frozen=True)
class DelegatedToken:
    scope: FrozenSet[str]
    audience: str
    policy_version_pin: int | None
    expires_at: float


@dataclass(frozen=True)
class PolicyBundle:
    version: int
    allowed_actions: FrozenSet[str]


def dispatch(
    token: DelegatedToken,
    action: str,
    receiving_org: str,
    live_policy: PolicyBundle,
    now: float,
    max_policy_staleness: float = 60.0,
    minted_at: float = 0.0,
) -> None:
    if token.audience != receiving_org:
        raise AttenuationBypassError(f"audience mismatch: token aud={token.audience} org={receiving_org}")
    if now >= token.expires_at:
        raise AttenuationBypassError("token expired")

    # Version-pin agreement is the continuity invariant.
    if token.policy_version_pin is not None:
        if token.policy_version_pin != live_policy.version:
            effective = token.scope & live_policy.allowed_actions
            if action not in effective:
                raise AttenuationBypassError(
                    f"policy skew: token pinned v{token.policy_version_pin}, "
                    f"live v{live_policy.version}; action '{action}' excluded by re-intersection"
                )
    else:
        if now - minted_at > max_policy_staleness:
            raise AttenuationBypassError(
                f"unpinned token older than {max_policy_staleness}s; force policy re-fetch"
            )

    effective_scope = token.scope & live_policy.allowed_actions
    if action not in effective_scope:
        raise AttenuationBypassError(
            f"action '{action}' not in effective scope {sorted(effective_scope)} "
            f"under policy v{live_policy.version}"
        )
