# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-scoped-capability-token-as-revoked-when-the-issuing-authority-s-consent-graph-diverges-from-the-token-s-emb.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-scoped-capability-token-as-revoked-when-the-issuing-authority-s-consent-graph-diverges-from-the-token-s-emb.warrant.json
# Markdown SHA-256:   d0ce73b2ab311cc2fee634397735cef1f97d1735d2fd7b25e289cda46375818c
# Code AST SHA-256:   a8ec2c24ddef16fe1d3539ce60c6dcdc461360a61101a8db2f0fe52479f47315
# Verified Classes:   ConsentGraphDivergenceError, DelegationEdge, ConsentAuthority, ScopedToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ConsentGraphDivergenceError(RuntimeError):
    """Raised when a token's embedded delegation chain no longer exists in the live consent graph."""
    pass


@dataclass
class DelegationEdge:
    parent: str
    child: str
    scope: str
    consent_epoch: int


class ConsentAuthority:
    def __init__(self) -> None:
        self.edges: dict[tuple[str, str], DelegationEdge] = {}
        self.epoch: int = 0

    def add_edge(self, parent: str, child: str, scope: str) -> None:
        self.epoch += 1
        self.edges[(parent, child)] = DelegationEdge(parent, child, scope, self.epoch)

    def sever(self, parent: str, child: str) -> None:
        if (parent, child) in self.edges:
            del self.edges[(parent, child)]
            self.epoch += 1

    def path_exists(self, chain: list[tuple[str, str]], required_scope: str) -> bool:
        for parent, child in chain:
            edge = self.edges.get((parent, child))
            if edge is None:
                return False
            if not required_scope.startswith(edge.scope.rstrip("*")):
                return False
        return True


@dataclass
class ScopedToken:
    chain: list[tuple[str, str]]
    scope: str
    consent_epoch: int
    expires_at: float


def authorize(
    token: ScopedToken,
    authority: ConsentAuthority,
    requested_scope: str,
    freshness_bound_s: float = 60.0,
    last_graph_check: float | None = None,
) -> None:
    now = time.time()
    if now > token.expires_at:
        raise ConsentGraphDivergenceError("token expired")

    if not requested_scope.startswith(token.scope.rstrip("*")):
        raise ConsentGraphDivergenceError("requested scope exceeds token scope")

    # Fast path: epoch matches, embedded chain is guaranteed current.
    if token.consent_epoch == authority.epoch:
        return

    # Epoch diverged: the graph moved since issuance. Re-validate against live graph.
    if last_graph_check is not None and (now - last_graph_check) <= freshness_bound_s:
        # Within freshness bound but epoch stale — still must confirm path.
        pass

    if not authority.path_exists(token.chain, token.scope):
        raise ConsentGraphDivergenceError(
            f"delegation chain {token.chain} no longer exists in live consent graph "
            f"(token epoch {token.consent_epoch}, authority epoch {authority.epoch})"
        )
