# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-delegates-a-task-through-a-chain-of-sub-agents-whose-capability-attestations-were-minted-against-a-stale-registry-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-delegates-a-task-through-a-chain-of-sub-agents-whose-capability-attestations-were-minted-against-a-stale-registry-epoch.warrant.json
# Markdown SHA-256:   e6c81263a18524dd25c77f0be26fab7e511528b135ca4cfa5c3f32da0aef9212
# Code AST SHA-256:   c2ae708801963acc53cc571487f87ac96f23f6c47d7e67bdeb02d694919b8486
# Verified Classes:   StaleEpochDelegationError, Warrant, Registry
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class StaleEpochDelegationError(RuntimeError):
    """Raised when a delegation would grant capabilities the parent no longer holds at the current registry epoch."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    capabilities: FrozenSet[str]
    issuer_chain: tuple[str, ...]
    minted_epoch: int
    expiry_epoch: int


class Registry:
    def __init__(self, epoch: int, grants: dict[str, FrozenSet[str]]):
        self.epoch = epoch
        self._grants = grants

    def resolve(self, principal: str, epoch: int | None = None) -> FrozenSet[str]:
        # Live resolution; callers must pass current epoch, never a cached one.
        if epoch is not None and epoch != self.epoch:
            raise StaleEpochDelegationError(
                f"resolve called with epoch {epoch} but registry is at {self.epoch}"
            )
        return self._grants.get(principal, frozenset())


def delegate(
    parent: str,
    child_warrant: Warrant,
    registry: Registry,
    now_epoch: int,
) -> None:
    if child_warrant.expiry_epoch <= now_epoch:
        raise StaleEpochDelegationError(
            f"warrant for {child_warrant.subject} expired at epoch {child_warrant.expiry_epoch}"
        )

    # Re-resolve the FULL issuer chain against the live epoch, not the minted epoch.
    for issuer in child_warrant.issuer_chain:
        if not registry.resolve(issuer, epoch=now_epoch):
            raise StaleEpochDelegationError(
                f"issuer {issuer} holds no authority at epoch {now_epoch}; "
                f"warrant was minted at epoch {child_warrant.minted_epoch}"
            )

    parent_live = registry.resolve(parent, epoch=now_epoch)
    if not child_warrant.capabilities <= parent_live:
        missing = child_warrant.capabilities - parent_live
        raise StaleEpochDelegationError(
            f"delegation from {parent} to {child_warrant.subject} at epoch {now_epoch} "
            f"would grant {sorted(missing)} which parent no longer holds "
            f"(warrant minted at epoch {child_warrant.minted_epoch})"
        )
