# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-authorized-mid-session-still-execute-a-tool-the-policy-engine-has-since-revoked.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-authorized-mid-session-still-execute-a-tool-the-policy-engine-has-since-revoked.warrant.json
# Markdown SHA-256:   a8df5ec7551a1f8d513b090a473ba0efb35f425786079755037dfe34f8429598
# Code AST SHA-256:   8c92e499df41cb0409309f07b464cf49d8b528149bf9513c28054db5fbd2b571
# Verified Classes:   CapabilityStaleError, CapabilityToken, PolicyStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class CapabilityStaleError(RuntimeError):
    """Raised when a cached capability token may predate a policy mutation
    affecting its scope, and the token's remaining lease exceeds the
    acceptable revocation latency. The agent MUST checkpoint and re-handshake;
    retrying with the same token is a loop against a withdrawn grant."""
    pass


@dataclass
class CapabilityToken:
    tools: frozenset[str]
    roots: frozenset[str]
    issued_at: float
    exp: float


@dataclass
class PolicyStore:
    # scope_key -> last mutation timestamp
    mutations: dict[str, float] = field(default_factory=dict)

    def last_mutation_for(self, scopes: frozenset[str]) -> float:
        return max((self.mutations.get(s, 0.0) for s in scopes), default=0.0)


MAX_REVOCATION_LATENCY_S = 5.0


def enforce_per_call(
    token: CapabilityToken,
    tool: str,
    path: str,
    store: PolicyStore,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    # 1. Basic scope membership against the token snapshot.
    if tool not in token.tools:
        raise CapabilityStaleError(f"tool {tool!r} not in token scope")
    if not any(path.startswith(r) for r in token.roots):
        raise CapabilityStaleError(f"path {path!r} outside token roots")

    # 2. Freshness invariant: token must not predate any policy mutation
    #    touching its scopes, unless its remaining lease is within the
    #    acceptable revocation latency.
    scopes = token.tools | token.roots
    last_mut = store.last_mutation_for(scopes)
    remaining = token.exp - now

    if token.issued_at < last_mut and remaining > MAX_REVOCATION_LATENCY_S:
        raise CapabilityStaleError(
            f"token issued_at={token.issued_at:.3f} predates policy mutation "
            f"at={last_mut:.3f} for scopes {sorted(scopes)}; "
            f"remaining lease {remaining:.1f}s exceeds "
            f"MAX_REVOCATION_LATENCY_S={MAX_REVOCATION_LATENCY_S}s. "
            f"Checkpoint and re-handshake."
        )
