# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-keeps-executing-under-a-revoked-capability-token-because-revocation-propagates-only-to-the-next-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-keeps-executing-under-a-revoked-capability-token-because-revocation-propagates-only-to-the-next-tool-call-boundary.warrant.json
# Markdown SHA-256:   d5fed9edbbe861dc66dbc632c18e6a891c8464433e6b09539a594789e1b2ce29
# Code AST SHA-256:   59eaae69222cd384f74d8c0c9c49f535406a087a5220d21650542e8d10e721cb
# Verified Classes:   RevocationPropagationError, RejectionClass, CapabilityToken, PendingWarrant, AgentContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class RevocationPropagationError(RuntimeError):
    """Raised when an agent attempts to exercise authority under a token
    whose revocation has not yet been reconciled into the agent's context."""


class RejectionClass(Enum):
    TRANSIENT = "transient"      # retryable: token refresh race, gateway blip
    TERMINAL = "terminal"        # non-retryable: token revoked, scope withdrawn


@dataclass
class CapabilityToken:
    token_id: str
    scopes: frozenset[str]
    revoked_at: Optional[float] = None

    def is_revoked(self, now: Optional[float] = None) -> bool:
        return self.revoked_at is not None and (now or time.time()) >= self.revoked_at


@dataclass
class PendingWarrant:
    """A sub-warrant minted locally, NOT yet admitted. Must not be durable
    until promoted by a successful admission against a live parent."""
    warrant_id: str
    parent_token_id: str
    scopes: frozenset[str]
    promoted: bool = False


@dataclass
class AgentContext:
    """The model's belief-state. Note: scopes are materialized here, which is
    precisely why revocation must be reconciled here, not only at the gateway."""
    believed_scopes: frozenset[str]
    revocation_bulletins: list[str] = field(default_factory=list)
    pending_warrants: list[PendingWarrant] = field(default_factory=list)

    def apply_bulletin(self, scope: str) -> None:
        self.revocation_bulletins.append(f"scope {scope} revoked; abandon dependent plans")
        self.believed_scopes = self.believed_scopes - {scope}


def admission_check(
    token: CapabilityToken,
    requested_scope: str,
    context: AgentContext,
    now: Optional[float] = None,
) -> RejectionClass:
    if token.is_revoked(now):
        # Invariant: a revoked token must never be admitted, and the model's
        # context must be reconciled before the next reasoning step proceeds.
        if requested_scope in context.believed_scopes:
            raise RevocationPropagationError(
                f"token {token.token_id} revoked but scope {requested_scope} "
                f"still believed valid in agent context; bulletin not applied"
            )
        return RejectionClass.TERMINAL
    return RejectionClass.TRANSIENT if token.token_id not in context.believed_scopes else RejectionClass.TERMINAL


def reconcile_revocation(
    token: CapabilityToken,
    context: AgentContext,
    now: Optional[float] = None,
) -> None:
    """Called at every reasoning-step boundary. Injects revocation bulletins
    and demotes any pending warrants whose parent is now revoked."""
    if not token.is_revoked(now):
        return
    for scope in token.scopes:
        if scope in context.believed_scopes:
            context.apply_bulletin(scope)
    for w in context.pending_warrants:
        if w.parent_token_id == token.token_id and not w.promoted:
            # Demote: pending warrant dies with its parent; do not promote.
            context.pending_warrants.remove(w)


def mint_sub_warrant(
    parent: CapabilityToken,
    scopes: frozenset[str],
    context: AgentContext,
    now: Optional[float] = None,
) -> PendingWarrant:
    if parent.is_revoked(now):
        raise RevocationPropagationError(
            f"cannot mint sub-warrant from revoked parent {parent.token_id}"
        )
    w = PendingWarrant(
        warrant_id=f"w-{parent.token_id}-{len(context.pending_warrants)}",
        parent_token_id=parent.token_id,
        scopes=scopes,
    )
    context.pending_warrants.append(w)
    return w


def promote_warrant(w: PendingWarrant, admitted: bool) -> None:
    if not admitted:
        raise RevocationPropagationError(
            f"warrant {w.warrant_id} not admitted; must not become durable"
        )
    w.promoted = True
