# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-delegated-credential-was-silently-narrowed-by-an-upstream-warrant-revocation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-delegated-credential-was-silently-narrowed-by-an-upstream-warrant-revocation.warrant.json
# Markdown SHA-256:   97d6b6a30d6cf52487fa50d5c7fc53d7bb006a899960bd1a3e91e618c53ea9cb
# Code AST SHA-256:   87544ca0f7bd3b722b04cda46c5b23f23e5b0906c331bf4d50606863c836131d
# Verified Classes:   ChainFreshnessError, AncestorRevokedError, Warrant, IssuerStore
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class ChainFreshnessError(RuntimeError):
    """Raised when a mutating action is attempted without a fresh, unrevoked ancestor chain."""
    pass


class AncestorRevokedError(ChainFreshnessError):
    """An ancestor warrant in the delegation chain is revoked or attenuated below the action's scope."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    parent_id: str | None
    scope: frozenset[str]
    expires_at: float
    revoked: bool = False


@dataclass
class IssuerStore:
    """Authoritative, current-state view of all warrants. The only source of truth for revocation/attenuation."""
    warrants: dict[str, Warrant] = field(default_factory=dict)

    def get(self, warrant_id: str) -> Warrant | None:
        return self.warrants.get(warrant_id)


# Staleness budget per action class. Mutating actions get zero tolerance.
STALENESS_BUDGET = {"read": 300.0, "write": 0.0, "spawn": 0.0}


def effective_scope(leaf: Warrant, store: IssuerStore) -> frozenset[str]:
    """Intersection of scopes along the full ancestor chain, using CURRENT issuer state."""
    scope = leaf.scope
    node = leaf
    seen: set[str] = set()
    while node.parent_id is not None:
        if node.parent_id in seen:
            raise ChainFreshnessError(f"cycle in chain at {node.parent_id}")
        seen.add(node.parent_id)
        parent = store.get(node.parent_id)
        if parent is None:
            raise ChainFreshnessError(f"ancestor {node.parent_id} unresolvable")
        if parent.revoked:
            raise AncestorRevokedError(f"ancestor {parent.warrant_id} revoked")
        scope = scope & parent.scope  # attenuation narrows; intersection is the truth
        node = parent
    return scope


def authorize_action(
    leaf: Warrant,
    store: IssuerStore,
    action_scope: str,
    action_class: str,
    last_verified_at: float,
) -> None:
    """Gate a single action. Re-walks the chain when the action class demands freshness."""
    now = time.time()

    if leaf.revoked:
        raise AncestorRevokedError(f"leaf {leaf.warrant_id} revoked")
    if now >= leaf.expires_at:
        raise ChainFreshnessError(f"leaf {leaf.warrant_id} expired")

    budget = STALENESS_BUDGET[action_class]
    if now - last_verified_at > budget:
        # Mutating/spawn actions (budget 0) always land here: re-walk required.
        try:
            current = effective_scope(leaf, store)
        except ChainFreshnessError:
            # Fail closed: unreachable/unresolvable chain demotes authority to nothing.
            raise ChainFreshnessError(
                f"cannot re-walk chain for {action_class} action; failing closed"
            )
    else:
        current = leaf.scope  # cached projection, acceptable only for read class

    if action_scope not in current:
        raise AncestorRevokedError(
            f"action '{action_scope}' not covered by effective scope "
            f"{sorted(current)} for {action_class} action; "
            f"leaf scope {sorted(leaf.scope)} is stale or narrowed"
        )
