# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-caches-a-capability-grant-past-the-policy-epoch-it-was-issued-under.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-caches-a-capability-grant-past-the-policy-epoch-it-was-issued-under.warrant.json
# Markdown SHA-256:   1ff820201c17224d1dba2464a221d1c4319ec59fe6ce516015023d1732fc93ed
# Code AST SHA-256:   5ed74024572225621f1ba7cdade71c861e2a92e39ff22eed38a1e09b2fd14e2e
# Verified Classes:   StaleGrantAdmission, Grant, PolicyEnforcementPoint, AgentRuntime
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleGrantAdmission(RuntimeError):
    """Raised when a cached capability grant is presented at an epoch
    that no longer matches the PEP's current policy epoch."""


@dataclass(frozen=True)
class Grant:
    identity: str
    capability: str
    resource: str
    epoch: int
    ttl_s: float
    issued_at: float


class PolicyEnforcementPoint:
    def __init__(self, current_epoch: int):
        self._epoch = current_epoch

    def advance_epoch(self) -> int:
        self._epoch += 1
        return self._epoch

    @property
    def epoch(self) -> int:
        return self._epoch

    def admit(self, grant: Grant, now: float) -> None:
        # Signature and TTL checks are necessary but not sufficient.
        if now - grant.issued_at > grant.ttl_s:
            raise StaleGrantAdmission(
                f"grant for {grant.capability} on {grant.resource} expired"
            )
        # The invariant: epoch must match at invocation, not just at mint.
        if grant.epoch != self._epoch:
            raise StaleGrantAdmission(
                f"grant minted at epoch {grant.epoch}, PEP at {self._epoch}: "
                f"{grant.capability} on {grant.resource} no longer authorized"
            )


class AgentRuntime:
    def __init__(self, pep: PolicyEnforcementPoint):
        self._pep = pep
        self._cached: Optional[Grant] = None

    def invoke_tool(self, grant: Grant, now: float) -> None:
        # Cache-hit path must run the full admission check, including epoch.
        self._cached = grant
        self._pep.admit(self._cached, now)


if __name__ == "__main__":
    pep = PolicyEnforcementPoint(current_epoch=41)
    grant = Grant("svc-recon-7", "fs.read", "/data/tenant-42/", epoch=41,
                  ttl_s=30.0, issued_at=0.0)
    runtime = AgentRuntime(pep)
    runtime.invoke_tool(grant, now=0.2)          # ok

    pep.advance_epoch()                           # operator revokes scope
    try:
        runtime.invoke_tool(grant, now=4.3)       # cached grant, stale epoch
    except StaleGrantAdmission as e:
        print(f"rejected as expected: {e}")
