# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-delegated-agent-token-revocation-as-a-distributed-consensus-problem-rather-than-a-local-cache-invalidation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-delegated-agent-token-revocation-as-a-distributed-consensus-problem-rather-than-a-local-cache-invalidation.warrant.json
# Markdown SHA-256:   73319a890d7521786b7af78e911889fa9d78b38fbba33f9567abbb305d1410de
# Code AST SHA-256:   5d1da2ebbe87cb3e463a518f5a728e036918c32e4d6bdb623b6870d3a1fc4d32
# Verified Classes:   RevocationConvergenceError, DelegatedCredential, PlanState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class RevocationConvergenceError(RuntimeError):
    """Raised when a plan attempts to proceed on authority that the refresh
    path has signaled as revoked, or when the bounded-authority window is
    violated. This is terminal: the plan must abort, not retry, not fall back."""


@dataclass
class DelegatedCredential:
    token: str
    jti: str
    expires_at: float          # epoch seconds
    claim_ttl: float           # declared cache lifetime, MUST be < token lifetime
    cached_claims: Optional[dict] = None
    cached_at: Optional[float] = None


@dataclass
class PlanState:
    executed_under_authority: list = field(default_factory=list)
    aborted: bool = False
    abort_reason: Optional[str] = None


# Refresh outcomes as classified by the STS response.
REFRESH_OK = "ok"
REFRESH_TERMINAL = "terminal_revocation"   # invalid_grant / invalid_token / 401
REFRESH_TRANSIENT = "transient_infra"      # 5xx / timeout / temporarily_unavailable


def classify_refresh(status_code: int, error_code: Optional[str]) -> str:
    if status_code == 200:
        return REFRESH_OK
    if error_code in ("invalid_grant", "invalid_token", "consent_withdrawn"):
        return REFRESH_TERMINAL
    if status_code in (401, 403) and error_code is None:
        # Bare 401 with no body: treat as terminal. Fail closed.
        return REFRESH_TERMINAL
    return REFRESH_TRANSIENT


def claims_valid(cred: DelegatedCredential, now: float) -> bool:
    if cred.cached_claims is None or cred.cached_at is None:
        return False
    # Cache lifetime is the declared claim_ttl, NOT the token exp.
    return (now - cred.cached_at) < cred.claim_ttl


def execute_step(
    cred: DelegatedCredential,
    plan: PlanState,
    refresh_fn,
    tool_call_fn,
    now: Optional[float] = None,
) -> dict:
    now = time.time() if now is None else now

    if plan.aborted:
        raise RevocationConvergenceError(
            f"plan already aborted: {plan.abort_reason}"
        )

    # Step 1: refresh / re-validate before consuming delegated authority.
    status_code, error_code, fresh_claims = refresh_fn(cred.jti)
    outcome = classify_refresh(status_code, error_code)

    if outcome == REFRESH_TERMINAL:
        plan.aborted = True
        plan.abort_reason = f"revocation signaled (error={error_code})"
        raise RevocationConvergenceError(
            f"delegation {cred.jti} revoked mid-plan; "
            f"{len(plan.executed_under_authority)} calls already executed under "
            f"possibly-revoked authority. Aborting, NOT falling back to cache."
        )

    if outcome == REFRESH_TRANSIENT:
        # Transient infra failure: suspend the plan. Do NOT degrade to the
        # cached credential; stale authority is not evidence of authority.
        plan.aborted = True
        plan.abort_reason = f"transient refresh failure (status={status_code})"
        raise RevocationConvergenceError(
            f"refresh for {cred.jti} failed transiently; suspending plan rather "
            f"than proceeding on cached credential. Exposure window unverified."
        )

    # Step 2: adopt FRESH claims, even if narrower than cache. A 200 that
    # returns reduced scope is a revocation signal in disguise.
    cred.cached_claims = fresh_claims
    cred.cached_at = now

    if not claims_valid(cred, now):
        raise RevocationConvergenceError(
            f"claims for {cred.jti} not valid at {now}; claim_ttl exceeded"
        )

    # Step 3: consume authority.
    result = tool_call_fn(cred.token, cred.cached_claims)
    plan.executed_under_authority.append(cred.jti)
    return result


def compute_exposure_window(cache_ttls: list, clock_skews: list) -> float:
    """Worst-case post-revocation authority on the delegation chain.
    Must be reported to the revoking party alongside every delegation."""
    if not cache_ttls:
        raise RevocationConvergenceError(
            "no cache TTLs declared on delegation chain; exposure window unbounded"
        )
    return max(cache_ttls) + max(clock_skews or [0.0])
