# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-aaif-attestation-refresh-windows-that-silently-outlive-the-authorization-scope-they-certify.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-aaif-attestation-refresh-windows-that-silently-outlive-the-authorization-scope-they-certify.warrant.json
# Markdown SHA-256:   a338573e38dcae2b12ac560acb210d2835c13a4e847c73f8f1e87bb0df7ce9e0
# Code AST SHA-256:   707f56b4e77c6a439d39c828e80eb895facc97dc212d94d91a5990612a6e9895
# Verified Classes:   AttestationScopeDecoherence, Grant, Attestation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AttestationScopeDecoherence(RuntimeError):
    """Raised when a fresh attestation certifies a superseded authorization scope."""
    pass


@dataclass
class Grant:
    grant_id: str
    scope_version: int
    scopes: frozenset[str]


@dataclass
class Attestation:
    grant_ref: str
    scope_version: int
    scopes: frozenset[str]
    exp: float
    signature_valid: bool


def admit_tool_call(
    attestation: Attestation,
    grant_store: dict[str, Grant],
    required_scope: str,
    now: float,
    store_available: bool = True,
) -> bool:
    # Liveness: token must be unexpired and correctly signed.
    if not attestation.signature_valid:
        raise AttestationScopeDecoherence("attestation signature invalid")
    if attestation.exp <= now:
        raise AttestationScopeDecoherence("attestation expired")

    # Fail closed if the authority source cannot be consulted.
    if not store_available:
        raise AttestationScopeDecoherence(
            "grant store unavailable; refusing to admit on attestation alone"
        )

    grant: Optional[Grant] = grant_store.get(attestation.grant_ref)
    if grant is None:
        raise AttestationScopeDecoherence(
            f"grant_ref {attestation.grant_ref!r} does not resolve (revoked)"
        )

    # The invariant: attestation scope version must equal current grant version.
    if attestation.scope_version != grant.scope_version:
        raise AttestationScopeDecoherence(
            f"scope version skew: attestation={attestation.scope_version} "
            f"grant={grant.scope_version} for {grant.grant_id!r}; "
            f"attestation certifies a superseded scope set"
        )

    # Authority is decided by the grant, not by the attestation's scope claims.
    if required_scope not in grant.scopes:
        raise AttestationScopeDecoherence(
            f"scope {required_scope!r} not present in current grant {grant.grant_id!r}"
        )
    return True
