# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-capability-revocation-when-a-tool-grant-is-attenuated-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-capability-revocation-when-a-tool-grant-is-attenuated-mid-flight.warrant.json
# Markdown SHA-256:   dbb2879f00b6fb5bb8cd145ff861896e15011a34a7c530630b8b4ddad4c448a2
# Code AST SHA-256:   03ff33e1618182399357ccc9278ec479fa5ed9103013282232a3c89b11d2efcb
# Verified Classes:   CapabilitySuperseded, EpochFenceViolation, Capability, Authority
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class CapabilitySuperseded(RuntimeError):
    """Raised when a tool call is attempted under a grant epoch that has been
    narrowed or revoked by the authority. Fail-closed: the effect must not commit."""


class EpochFenceViolation(RuntimeError):
    """Raised when the authority attempts to advance the epoch while a fenced
    effect is in flight, or when a fence is released without a commit/abort."""


@dataclass(frozen=True)
class Capability:
    grant_id: str
    caveat: str          # e.g. "path ~ /workspace/build/*"
    issued_epoch: int    # E_tok at mint time
    ttl_s: int


class Authority:
    """Monotonic revocation epoch. Narrowing a grant advances the epoch and
    records the superseded grant ids."""

    def __init__(self) -> None:
        self._epoch: int = 0
        self._revoked: dict[str, int] = {}   # grant_id -> epoch at which revoked
        self._fenced: int = 0

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

    def narrow(self, grant_id: str) -> None:
        if self._fenced > 0:
            raise EpochFenceViolation(
                f"cannot advance epoch to revoke {grant_id!r}: "
                f"{self._fenced} fenced effect(s) in flight"
            )
        self._epoch += 1
        self._revoked[grant_id] = self._epoch

    def is_superseded(self, cap: Capability) -> bool:
        rev = self._revoked.get(cap.grant_id)
        return rev is not None and cap.issued_epoch < rev

    def fence(self) -> None:
        self._fenced += 1

    def unfence(self) -> None:
        if self._fenced <= 0:
            raise EpochFenceViolation("unfence without matching fence")
        self._fenced -= 1


def admit_and_commit(authority: Authority, cap: Capability, path: str, effect) -> None:
    """Two-phase admit: verify against current epoch, fence the epoch, commit.

    The fence guarantees no attenuation can interleave between verification
    and commit. If the grant was superseded before we fenced, we fail closed.
    """
    authority.fence()
    try:
        if authority.is_superseded(cap):
            raise CapabilitySuperseded(
                f"grant {cap.grant_id!r} issued at epoch {cap.issued_epoch} "
                f"was superseded at epoch {authority._revoked[cap.grant_id]} "
                f"(current epoch {authority.epoch}); refusing {path!r}"
            )
        # caveat check omitted for brevity; must run here, inside the fence,
        # against the same epoch we just validated.
        effect(path)
    finally:
        authority.unfence()


# Trace reproducing the observed failure, now closed:
if __name__ == "__main__":
    auth = Authority()
    cap = Capability(grant_id="g1", caveat="path ~ /workspace/build/*",
                     issued_epoch=auth.epoch, ttl_s=900)

    def write(p: str) -> None:
        print(f"committed write: {p}")

    # Operator narrows the grant before the agent's next call.
    auth.narrow("g1")

    try:
        admit_and_commit(auth, cap, "/workspace/build/scratch/state.json", write)
    except CapabilitySuperseded as e:
        # Agent must re-plan from the new grant, NOT retry the same call.
        print(f"fail-closed: {e}")
