# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-capability-grant-when-the-trust-anchor-bridge-and-the-policy-translation-gateway-disagree-on.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-capability-grant-when-the-trust-anchor-bridge-and-the-policy-translation-gateway-disagree-on.warrant.json
# Markdown SHA-256:   c2d1cc9077b660b7d0bb08cfca137e1a26a917cd8aa335d97789324ec9c1101d
# Code AST SHA-256:   71d3ad3a5b0468e12fb616dbb072d99aa5d26632f4517e3ca4b2cf6505c34e33
# Verified Classes:   FederatedScopeDivergence, Grant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class FederatedScopeDivergence(RuntimeError):
    """Raised when a federated capability grant's effective scope is not a
    monotone restriction of its trust-anchor-validated nominal scope, or when
    the two validators were evaluated in different federation epochs."""


@dataclass(frozen=True)
class Grant:
    warrant_id: str
    nominal_scope: FrozenSet[str]      # from trust-anchor bridge
    effective_scope: FrozenSet[str]    # from policy-translation gateway
    tab_epoch: int
    ptg_epoch: int
    tab_valid: bool
    ptg_translated: bool


def admit_federated_grant(grant: Grant) -> FrozenSet[str]:
    if not grant.tab_valid:
        raise FederatedScopeDivergence(
            f"{grant.warrant_id}: trust-anchor bridge did not validate warrant"
        )
    if not grant.ptg_translated:
        raise FederatedScopeDivergence(
            f"{grant.warrant_id}: policy-translation gateway did not produce a scope"
        )
    if grant.tab_epoch != grant.ptg_epoch:
        raise FederatedScopeDivergence(
            f"{grant.warrant_id}: epoch skew TAB={grant.tab_epoch} "
            f"PTG={grant.ptg_epoch}; scope pair never simultaneously valid"
        )

    widening = grant.effective_scope - grant.nominal_scope
    if widening:
        # Translation widened scope: refuse, do not silently intersect.
        raise FederatedScopeDivergence(
            f"{grant.warrant_id}: non-monotone translation, effective scope "
            f"exceeds nominal by {sorted(widening)}"
        )

    # Admissible: effective scope is a subset of nominal scope, same epoch.
    return grant.effective_scope


def handle_inbound_grant(grant: Grant) -> FrozenSet[str]:
    try:
        return admit_federated_grant(grant)
    except FederatedScopeDivergence as exc:
        # Hard refusal, structured divergence report for crosswalk reconciliation.
        raise FederatedScopeDivergence(
            f"REFUSED {grant.warrant_id}: {exc}; escalate to inter-org "
            f"policy owner, do not execute"
        ) from exc
