# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-credential-attestation-from-outliving-the-agent-s-actual-authority-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-credential-attestation-from-outliving-the-agent-s-actual-authority-chain.warrant.json
# Markdown SHA-256:   e26d43346a0ebbd9570fb15c14c400c8e6354ce3c8ed827013084ac715916ea6
# Code AST SHA-256:   6f5b062d5f298ec9d22d8f38e8397f1459c3c001c821d3745402316ab19802f9
# Verified Classes:   GhostAuthorityError, EpochOracleUnreachable, Attestation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class GhostAuthorityError(RuntimeError):
    """Raised when an attestation's embedded authority chain no longer matches live state."""
    pass


class EpochOracleUnreachable(RuntimeError):
    """Raised when the verifier cannot reach the live epoch oracle; must fail closed."""
    pass


@dataclass(frozen=True)
class Attestation:
    issuer: str
    scope: frozenset
    exp: float
    epoch_chain: tuple  # ordered hash of ancestor epochs, root-first


def verify_attestation(
    token: Attestation,
    request_scope: frozenset,
    now: float,
    live_epoch_chain: Mapping[str, tuple],
    oracle_reachable: bool,
) -> bool:
    # Identity freshness: TTL is necessary but never sufficient.
    if now >= token.exp:
        raise GhostAuthorityError(
            f"attestation from {token.issuer} expired at {token.exp}, now={now}"
        )

    if not request_scope.issubset(token.scope):
        raise GhostAuthorityError(
            f"requested {request_scope} exceeds granted {token.scope}"
        )

    # Fail closed: no live epoch, no authority. Never fall back to frozen claim.
    if not oracle_reachable:
        raise EpochOracleUnreachable(
            f"cannot validate epoch chain for {token.issuer}; denying per invariant"
        )

    live = live_epoch_chain.get(token.issuer)
    if live is None:
        raise GhostAuthorityError(
            f"issuer {token.issuer} absent from live epoch chain (revoked entirely?)"
        )

    # The load-bearing clause: frozen authority must equal live authority.
    if tuple(token.epoch_chain) != tuple(live):
        raise GhostAuthorityError(
            f"ghost authority: token epoch_chain={token.epoch_chain} "
            f"!= live={live} for issuer {token.issuer}"
        )

    return True
