# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-validate-a-delegated-capability-token-when-the-signing-principal-is-itself-an-agent-whose-authority-was-attenuated-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-validate-a-delegated-capability-token-when-the-signing-principal-is-itself-an-agent-whose-authority-was-attenuated-mid-handoff.warrant.json
# Markdown SHA-256:   19d53090d52347a435f5939827060afa5b402059154a7cce34677d40e596e079
# Code AST SHA-256:   e6bdba383ecf2fa08a798ca1cf8085f67118517f1fe3de98eb12d11473f27acf
# Verified Classes:   DelegationAttenuationError, CapabilityToken, AuthorityView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class DelegationAttenuationError(RuntimeError):
    """Raised when a delegated capability token cannot be soundly validated."""
    pass


@dataclass
class CapabilityToken:
    jti: str
    issuer: str
    scopes: frozenset
    parent_digest: Optional[str]
    ancestor_jtis: tuple = ()          # full chain of ancestor jti values
    revocation_epoch: Optional[int] = None
    not_after: float = 0.0
    minted_at: float = 0.0


@dataclass
class AuthorityView:
    """An agent's local, possibly stale, view of its own authority."""
    epoch: int
    revoked_jtis: frozenset
    last_sync: float
    max_staleness: float = 5.0

    def is_fresh(self) -> bool:
        return (time.time() - self.last_sync) <= self.max_staleness


def validate_delegated_chain(
    leaf: CapabilityToken,
    issuer_revoked: frozenset,
    issuer_epoch: int,
    view: AuthorityView,
) -> None:
    now = time.time()

    if now > leaf.not_after:
        raise DelegationAttenuationError(f"token {leaf.jti} expired")

    # Invariant 1: chain must expose ancestors so revocation is checkable.
    if leaf.parent_digest is not None and not leaf.ancestor_jtis:
        raise DelegationAttenuationError(
            f"token {leaf.jti} has parent_digest but no ancestor_jtis; "
            "revocation state is unverifiable"
        )

    # Invariant 2: every ancestor must be unrevoked at current epoch.
    revoked_hits = set(leaf.ancestor_jtis) & issuer_revoked
    if revoked_hits:
        raise DelegationAttenuationError(
            f"token {leaf.jti} descends from revoked ancestor(s) {sorted(revoked_hits)}"
        )

    # Invariant 3: the minting agent's authority view must be fresh.
    if not view.is_fresh():
        raise DelegationAttenuationError(
            f"authority view stale by {now - view.last_sync:.2f}s "
            f"(max {view.max_staleness}s); refusing to trust delegated scopes"
        )

    # Invariant 4: re-delegation must not outrun the issuer's epoch.
    if leaf.revocation_epoch is None or leaf.revocation_epoch < issuer_epoch:
        raise DelegationAttenuationError(
            f"token {leaf.jti} epoch {leaf.revocation_epoch} predates issuer epoch "
            f"{issuer_epoch}; attenuation subset relation may be stale"
        )


def admit_write(leaf: CapabilityToken, issuer_revoked: frozenset,
                issuer_epoch: int, view: AuthorityView) -> bool:
    validate_delegated_chain(leaf, issuer_revoked, issuer_epoch, view)
    return "write:repo" in leaf.scopes
