# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-authorization-mid-task-when-its-capability-wallet-refreshes-a-short-lived-credential.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-authorization-mid-task-when-its-capability-wallet-refreshes-a-short-lived-credential.warrant.json
# Markdown SHA-256:   47b1e24f2098a015edfb478fee665ad7653f38328b55bcbe5150f048ddb23c9b
# Code AST SHA-256:   b222cbaa2038c011437324808215f1014a5e5dfbec6fb63c044e3b71930bcf4e
# Verified Classes:   StaleCapabilityError, EntitlementRevokedError, CapabilityToken, CapabilityWallet
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleCapabilityError(RuntimeError):
    """Raised when a side-effecting call would use a token whose remaining
    lifetime is below the freshness floor, or whose last refresh failed."""


class EntitlementRevokedError(RuntimeError):
    """Raised by the issuer when the underlying grant no longer exists."""


@dataclass
class CapabilityToken:
    scope: str
    minted_at: float
    ttl: float
    last_refresh_ok: bool = True

    def remaining(self, now: float) -> float:
        return (self.minted_at + self.ttl) - now


@dataclass
class CapabilityWallet:
    issuer: object
    scope: str
    ttl: float = 45.0
    freshness_floor: float = 15.0
    token: CapabilityToken = field(default=None)

    def _mint(self) -> CapabilityToken:
        now = time.monotonic()
        try:
            self.issuer.mint(self.scope)  # raises if entitlement gone
        except EntitlementRevokedError:
            if self.token is not None:
                self.token.last_refresh_ok = False
            raise
        return CapabilityToken(scope=self.scope, minted_at=now, ttl=self.ttl)

    def token_for_use(self, side_effecting: bool) -> CapabilityToken:
        now = time.monotonic()
        if self.token is None:
            self.token = self._mint()
        if side_effecting:
            if not self.token.last_refresh_ok:
                raise StaleCapabilityError(
                    f"scope={self.scope!r} last refresh failed; refusing write"
                )
            if self.token.remaining(now) < self.freshness_floor:
                # use-driven refresh: force re-derivation from entitlement
                self.token = self._mint()
                if self.token.remaining(time.monotonic()) < self.freshness_floor:
                    raise StaleCapabilityError(
                        f"scope={self.scope!r} refreshed token still below floor"
                    )
        return self.token


def execute_write(wallet: CapabilityWallet, store, payload: dict) -> None:
    token = wallet.token_for_use(side_effecting=True)
    if token.scope != "write:store":
        raise StaleCapabilityError(
            f"token scope {token.scope!r} does not cover write:store"
        )
    store.commit(payload)  # only reached with a fresh, entitled token
