# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-despite-a-valid-trust-broker-attestation-the-policy-negotiation-idempotency-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-despite-a-valid-trust-broker-attestation-the-policy-negotiation-idempotency-gap.warrant.json
# Markdown SHA-256:   a3219b24ca5a86be03c0f7ce0163f9bb04cdc252e6e47c3c8a5aef9863d1f27c
# Code AST SHA-256:   7bee5eb5dde1da8aeb238401981dd311d6fe60a33b1c292a6da08fe83a45a402
# Verified Classes:   NegotiationEpochDivergence
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class NegotiationEpochDivergence(RuntimeError):
    """Raised when a federated capability grant's negotiation epoch is stale
    relative to the receiver's local epoch AND the intervening epoch delta
    narrowed the requested capability set. A valid broker attestation does
    not override this condition."""
    pass


def admit_federated_grant(grant, local_state, broker_attestation):
    # Attestation validity is necessary but NOT sufficient.
    if not broker_attestation.verify(grant):
        raise NegotiationEpochDivergence(
            f"broker attestation failed verification for grant {grant.id}"
        )

    local_epoch = local_state.epoch_for(grant.peer_org)
    if local_epoch is None:
        # First contact: no epoch to compare; defer to normal policy eval.
        return local_state.evaluate_policy(grant.capabilities)

    if grant.epoch == local_epoch:
        return local_state.evaluate_policy(grant.capabilities)

    if grant.epoch > local_epoch:
        # Receiver state loss; distinct recovery path, not a refusal.
        raise NegotiationEpochDivergence(
            f"grant epoch {grant.epoch} ahead of local {local_epoch}; "
            f"receiver state may be lost"
        )

    # grant.epoch < local_epoch: check whether the delta narrowed capabilities.
    delta = local_state.epoch_delta(grant.peer_org, grant.epoch, local_epoch)
    if delta is None:
        # Delta history unavailable: fail closed, force renegotiation.
        raise NegotiationEpochDivergence(
            f"cannot verify narrowing for epoch delta "
            f"{grant.epoch}->{local_epoch} on peer {grant.peer_org}; "
            f"refusing stale grant {grant.id}"
        )

    narrowed = delta.narrowed_capabilities & set(grant.capabilities)
    if narrowed:
        raise NegotiationEpochDivergence(
            f"stale grant {grant.id} at epoch {grant.epoch} re-asserts "
            f"capabilities narrowed at epoch {local_epoch}: {sorted(narrowed)}"
        )

    # Stale but non-narrowing: safe to admit under current policy.
    return local_state.evaluate_policy(grant.capabilities)
