# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-capability-whose-revocation-epoch-has-already-advanced-past-the-grant-s-witnessed-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-capability-whose-revocation-epoch-has-already-advanced-past-the-grant-s-witnessed-epoch.warrant.json
# Markdown SHA-256:   d713f8f0c35468a572cc22d5146b5c6b99dbf126021c14f867083b0e9bda6002
# Code AST SHA-256:   74a251c3facde09ca2c31484749cec1d82940558f028e19c926b3288c58c9107
# Verified Classes:   StaleDelegationEpoch, Grant
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class StaleDelegationEpoch(RuntimeError):
    """Raised when a delegated grant's witnessed epoch no longer matches
    the authorizing resource's current revocation epoch."""
    pass


@dataclass(frozen=True)
class Grant:
    grant_id: str
    caps: frozenset
    resources: frozenset
    expiry: int
    witnessed_epoch: int


def admit_chain(
    chain: Sequence[Grant],
    observed_epoch: int,
    now: int,
    revoked_ids: frozenset,
) -> None:
    """Validate a delegation chain at the resource.

    chain[0] is the root grant minted by the original authority;
    chain[-1] is the leaf presented by the executing agent.
    """
    if not chain:
        raise StaleDelegationEpoch("empty delegation chain")

    root = chain[0]

    # Temporal invariant: the root's witnessed epoch must equal the
    # resource's current epoch. Intermediate caches are irrelevant.
    if root.witnessed_epoch != observed_epoch:
        raise StaleDelegationEpoch(
            f"root grant {root.grant_id} witnessed epoch "
            f"{root.witnessed_epoch} != current epoch {observed_epoch}; "
            f"re-validate against fresh revocation state"
        )

    # Monotonic invariant: no link may claim a future epoch.
    for g in chain:
        if g.witnessed_epoch > observed_epoch:
            raise StaleDelegationEpoch(
                f"grant {g.grant_id} witnessed future epoch "
                f"{g.witnessed_epoch} > {observed_epoch}; forged or replayed"
            )

    # Structural attenuation, checked pairwise down the chain.
    for parent, child in zip(chain, chain[1:]):
        if not child.caps <= parent.caps:
            raise StaleDelegationEpoch(
                f"attenuation violated: {child.grant_id} caps exceed parent"
            )
        if not child.resources <= parent.resources:
            raise StaleDelegationEpoch(
                f"attenuation violated: {child.grant_id} resources exceed parent"
            )
        if child.expiry > parent.expiry:
            raise StaleDelegationEpoch(
                f"attenuation violated: {child.grant_id} outlives parent"
            )

    # Chain-specific revocation, after freshness is established.
    for g in chain:
        if g.grant_id in revoked_ids:
            raise StaleDelegationEpoch(
                f"grant {g.grant_id} is revoked in epoch {observed_epoch}"
            )
        if g.expiry <= now:
            raise StaleDelegationEpoch(
                f"grant {g.grant_id} expired at {g.expiry}, now {now}"
            )
