# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-cross-org-capability-revocation-as-a-tombstone-rather-than-a-deletion-and-why-the-distinction-collapses-witho.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-cross-org-capability-revocation-as-a-tombstone-rather-than-a-deletion-and-why-the-distinction-collapses-witho.warrant.json
# Markdown SHA-256:   76e84030fae791ee7f0964f0c30b796dfabb78a1369830b876a9f6b1a1054bec
# Code AST SHA-256:   978add459810430b8f54a1be2ddfe5fece1f34ce0c0f76b7a7cd18d933c93aa6
# Verified Classes:   StaleCapabilityAssertion, CapabilityAssertion, EpochLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class StaleCapabilityAssertion(RuntimeError):
    """Raised when an agent is asked to act on a capability assertion whose
    delegation epoch is below the highest epoch it has already observed for
    that (holder, capability) pair, or which carries no epoch at all."""
    pass


@dataclass
class CapabilityAssertion:
    holder: str
    capability: str
    epoch: Optional[int]      # None means the issuer failed to stamp it
    valid: bool               # True = granted, False = revoked/narrowed


@dataclass
class EpochLedger:
    """Persisted per-agent high-water mark. Must survive checkpoint/resume and
    must be transferred in any peer handoff payload."""
    high_water: dict = field(default_factory=dict)

    def _key(self, holder: str, capability: str) -> tuple:
        return (holder, capability)

    def observe(self, a: CapabilityAssertion) -> None:
        if a.epoch is None:
            # An epoch-less assertion never advances the ledger. It is a
            # non-assertion and must not be used to authorize side effects.
            return
        k = self._key(a.holder, a.capability)
        if a.epoch > self.high_water.get(k, -1):
            self.high_water[k] = a.epoch

    def check(self, a: CapabilityAssertion) -> bool:
        """Returns True iff the agent may proceed on this assertion.
        Raises StaleCapabilityAssertion on any regression or missing epoch."""
        if a.epoch is None:
            raise StaleCapabilityAssertion(
                f"epoch-less assertion for {a.capability} from {a.holder}; "
                f"refusing to authorize side effects"
            )
        k = self._key(a.holder, a.capability)
        hw = self.high_water.get(k, -1)
        if a.epoch < hw:
            raise StaleCapabilityAssertion(
                f"stale assertion for {a.capability} from {a.holder}: "
                f"epoch {a.epoch} < high-water {hw}; discard and re-query"
            )
        if a.epoch == hw and not a.valid:
            # Same-epoch revocation is authoritative; do not retry.
            self.observe(a)
            return False
        if not a.valid:
            self.observe(a)
            return False
        self.observe(a)
        return True


def authorize_write(ledger: EpochLedger, a: CapabilityAssertion) -> None:
    if not ledger.check(a):
        raise StaleCapabilityAssertion(
            f"capability {a.capability} revoked at epoch {a.epoch} "
            f"for {a.holder}; halting task rather than retrying"
        )
    # proceed with the side-effecting write
