# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-grant-against-a-peer-s-policy-revision-it-has-not-yet-observed.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-capability-grant-against-a-peer-s-policy-revision-it-has-not-yet-observed.warrant.json
# Markdown SHA-256:   526de0456b6194c4e0b7e087944416caa4480917645c3168f2f14a753d4181cd
# Code AST SHA-256:   aa2a5a39744268241def8c7444c68326ae4b10971677593fa3016b0d2f4a7ac3
# Verified Classes:   PolicyRevisionSkewError, Grant, PolicyRevision
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class PolicyRevisionSkewError(RuntimeError):
    """Raised when a capability grant's policy_rev is stale relative to the
    enforcement point's current policy revision and scope cannot be safely
    intersected (non-monotone revision or unknown narrowing)."""


@dataclass(frozen=True)
class Grant:
    resource: str
    principal: str
    scope: FrozenSet[str]
    policy_rev: int
    exp: int


@dataclass(frozen=True)
class PolicyRevision:
    rev: int
    permitted_scope: FrozenSet[str]
    monotone_narrowing: bool  # True iff this rev only removes scope vs. prior


def enforce(grant: Grant, current: PolicyRevision, now: int) -> FrozenSet[str]:
    """Return the effective scope under which the grant may be honored.

    Raises PolicyRevisionSkewError if the grant was minted under an older
    revision and the current revision is not provably narrowing, so the
    intersection cannot be trusted as sound.
    """
    if now >= grant.exp:
        raise PolicyRevisionSkewError(
            f"grant expired at {grant.exp}, now={now}"
        )

    if grant.policy_rev == current.rev:
        return grant.scope

    if grant.policy_rev > current.rev:
        # Grant claims a future revision the enforcement point has not seen.
        raise PolicyRevisionSkewError(
            f"grant policy_rev={grant.policy_rev} ahead of current={current.rev}"
        )

    # grant.policy_rev < current.rev: revision skew.
    if not current.monotone_narrowing:
        raise PolicyRevisionSkewError(
            f"skew grant_rev={grant.policy_rev} current_rev={current.rev} "
            f"under non-monotone revision; cannot intersect soundly"
        )

    effective = grant.scope & current.permitted_scope
    if effective != grant.scope:
        # Narrowing removed scope the holder believed it had. Do not silently
        # proceed; surface the divergence so the holder re-plans.
        raise PolicyRevisionSkewError(
            f"skew grant_rev={grant.policy_rev} current_rev={current.rev} "
            f"narrowed scope from {sorted(grant.scope)} to {sorted(effective)}"
        )
    return effective
