# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-negotiated-capability-grant-as-void-when-the-granting-peer-s-policy-attestation-expires-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-negotiated-capability-grant-as-void-when-the-granting-peer-s-policy-attestation-expires-mid-handoff.warrant.json
# Markdown SHA-256:   d48084b62f20b3238692135f87348224390ed2ef67d69a5413986d7565825f80
# Code AST SHA-256:   8056fde5f82a37bfb576587de9b27f47ffddaa2efa53e8a32c77c0d1372dbee1
# Verified Classes:   ZombieScopeError, Warrant, Grant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ZombieScopeError(RuntimeError):
    """Grant token is unexpired but its policy warrant has lapsed or been revoked."""
    pass


@dataclass
class Warrant:
    attestation_id: str
    not_after: float
    revoked: bool = False


@dataclass
class Grant:
    scope: str
    grantee: str
    not_after: float
    warrant: Warrant


def validate_for_handoff(grant: Grant, now: float | None = None) -> None:
    """Called at every re-delegation and checkpoint-resume, not just handshake."""
    now = time.time() if now is None else now

    if grant.warrant.revoked:
        raise ZombieScopeError(
            f"warrant {grant.warrant.attestation_id} revoked; scope {grant.scope!r} "
            f"must not be forwarded to {grant.grantee!r}"
        )

    chain_min_expiry = min(grant.not_after, grant.warrant.not_after)
    if now >= chain_min_expiry:
        # Distinguish the two failure shapes for the audit log.
        if now < grant.not_after:
            raise ZombieScopeError(
                f"zombie scope: token live until {grant.not_after}, "
                f"warrant dead since {grant.warrant.not_after}; "
                f"scope {grant.scope!r} for {grant.grantee!r} is void"
            )
        raise ZombieScopeError(
            f"grant {grant.scope!r} expired at {grant.not_after}"
        )


def resume_from_checkpoint(blob: dict, now: float | None = None) -> Grant:
    grant = Grant(
        scope=blob["scope"],
        grantee=blob["grantee"],
        not_after=blob["token_not_after"],
        warrant=Warrant(
            attestation_id=blob["attestation_id"],
            not_after=blob["attestation_not_after"],
            revoked=blob.get("revoked", False),
        ),
    )
    # Re-validate the full chain; do not trust the persisted token alone.
    validate_for_handoff(grant, now=now)
    return grant
