# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-stale-capability-grants-from-surviving-revocation-across-agent-handoff-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-stale-capability-grants-from-surviving-revocation-across-agent-handoff-chains.warrant.json
# Markdown SHA-256:   0045b7e119bdf5c374c720d253fa4d2633151cb452332eb6d45978c8db0268ac
# Code AST SHA-256:   394da23184db2cab5bfebac07ff6f25b7c4013cac72838d8398329a3eba574bd
# Verified Classes:   StaleCapabilityError, Warrant, Issuer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class StaleCapabilityError(RuntimeError):
    """Raised when a warrant's ancestor was revoked but the verifier only checked local integrity."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    parent_id: str | None
    scope_budget: int
    epoch: int
    revoked: bool = False


def _h(s: str) -> str:
    return hashlib.sha256(s.encode()).hexdigest()[:16]


class Issuer:
    def __init__(self) -> None:
        self._warrants: dict[str, Warrant] = {}
        self._revoked_roots: set[str] = set()
        self.epoch: int = 1

    def register(self, w: Warrant) -> None:
        self._warrants[w.warrant_id] = w

    def revoke(self, warrant_id: str) -> None:
        # Revoking a node revokes its entire signed subtree, indexed by derivation-root.
        self._warrants[warrant_id].revoked = True
        self._revoked_roots.add(_h(warrant_id))
        self.epoch += 1

    def is_ancestor_revoked(self, w: Warrant) -> bool:
        cur: Warrant | None = w
        while cur is not None:
            if cur.revoked or _h(cur.warrant_id) in self._revoked_roots:
                return True
            cur = self._warrants.get(cur.parent_id) if cur.parent_id else None
        return False


def verify_and_execute(issuer: Issuer, w: Warrant, amount: int, epoch_tolerance: int = 0) -> str:
    # Local integrity checks (Design A) — necessary, not sufficient.
    if amount > w.scope_budget:
        raise StaleCapabilityError(f"scope violation: {amount} > {w.scope_budget}")

    # Liveness resolution (Design B) — the invariant that bounds revocation.
    if issuer.is_ancestor_revoked(w):
        raise StaleCapabilityError(
            f"warrant {w.warrant_id} has a revoked ancestor; bearer handoff hid revocation"
        )
    if issuer.epoch > w.epoch + epoch_tolerance:
        raise StaleCapabilityError(
            f"warrant {w.warrant_id} minted at epoch {w.epoch}, issuer at {issuer.epoch}; "
            f"policy generation advanced, re-validation required"
        )

    return f"executed {amount} under {w.warrant_id}"


# --- Reproduction of the observed failure ---
issuer = Issuer()
root = Warrant("W_root", None, 500, epoch=1)
w1 = Warrant("W_1", "W_root", 200, epoch=1)
w2 = Warrant("W_2", "W_1", 50, epoch=1)  # handed to B as opaque bearer
for w in (root, w1, w2):
    issuer.register(w)

issuer.revoke("W_1")  # A compromised; revocation lands at issuer and P

# B executes 40ms later. Local checks pass; liveness check fires.
try:
    verify_and_execute(issuer, w2, amount=48)
except StaleCapabilityError as e:
    print("BLOCKED:", e)
    # Without the liveness clause, this would have printed "executed 48 under W_2".
