# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-a-delegated-consent-chain-rather-than-trust-a-cached-aaif-capability-token.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-a-delegated-consent-chain-rather-than-trust-a-cached-aaif-capability-token.warrant.json
# Markdown SHA-256:   5c17f9a15f03d3d69b0674188b952a106dc4a2b2a0c873b8b34557887afc8293
# Code AST SHA-256:   9701c7fb2f2a6b291a40c94d21618dff98bdfe87e295ce43e77f289b1bd28603
# Verified Classes:   StaleDelegationError, CapabilityToken, ChainState, ScopedCapabilityCache
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from time import monotonic


class StaleDelegationError(RuntimeError):
    """Raised when a cached capability token's grounding chain no longer confers the requested scope."""


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    chain: tuple[str, ...]          # e.g. ("U", "A", "W")
    advertised_scope: frozenset[str]
    minted_at: float                # monotonic seconds
    ttl: float
    signature_valid: bool


@dataclass(frozen=True)
class ChainState:
    """Current scope actually conferred by each principal in the chain, as of now."""
    effective_scope: frozenset[str]
    revoked: bool
    observed_at: float


class ScopedCapabilityCache:
    def __init__(self, revalidation_interval: float, revocation_latency: float):
        if revocation_latency >= revalidation_interval:
            raise StaleDelegationError(
                "revalidation_interval must be <= revocation_propagation_latency; "
                "otherwise cached tokens can outlive their grounding chain"
            )
        self.revalidation_interval = revalidation_interval
        self._cache: dict[str, tuple[CapabilityToken, float]] = {}  # token_id -> (token, last_verified_at)

    def _grounded_scope(self, token: CapabilityToken, chain_state: ChainState) -> frozenset[str]:
        if chain_state.revoked:
            return frozenset()
        # Delegated authority is the intersection of the token's claim and the chain's live scope.
        return token.advertised_scope & chain_state.effective_scope

    def authorize(
        self,
        token: CapabilityToken,
        requested_scope: str,
        now: float,
        chain_state_provider,
    ) -> None:
        if not token.signature_valid:
            raise StaleDelegationError(f"token {token.token_id} signature invalid")

        cached = self._cache.get(token.token_id)
        needs_rederivation = (
            cached is None
            or (now - cached[1]) >= self.revalidation_interval
            or requested_scope not in cached[0].advertised_scope  # escalation since last verify
        )

        if needs_rederivation:
            chain_state: ChainState = chain_state_provider(token.chain)
            grounded = self._grounded_scope(token, chain_state)
            self._cache[token.token_id] = (token, now)
            if requested_scope not in grounded:
                raise StaleDelegationError(
                    f"token {token.token_id} advertises {requested_scope!r} but grounding chain "
                    f"{token.chain} confers only {sorted(grounded)}; re-derivation rejected the call"
                )
        else:
            # Within the revalidation window and not an escalation: cache is sound.
            if requested_scope not in cached[0].advertised_scope:
                raise StaleDelegationError(
                    f"token {token.token_id} does not advertise {requested_scope!r}"
                )

    def invalidate_on_narrowing(self, token_id: str) -> None:
        self._cache.pop(token_id, None)


# Example trigger trace
def _demo() -> None:
    cache = ScopedCapabilityCache(revalidation_interval=10.0, revocation_latency=5.0)
    t_w = CapabilityToken(
        token_id="T_W",
        chain=("U", "A", "W"),
        advertised_scope=frozenset({"read:repo", "write:pr"}),
        minted_at=0.0,
        ttl=30.0,
        signature_valid=True,
    )
    # At t=12, U narrows A to {read:repo, merge:pr}; chain now intersects to {read:repo}.
    narrowed = ChainState(effective_scope=frozenset({"read:repo"}), revoked=False, observed_at=12.0)

    cache.authorize(t_w, "read:repo", now=1.0, chain_state_provider=lambda _c: narrowed)  # ok, cached
    # Escalation to write:pr at t=12 forces re-derivation and must fail.
    try:
        cache.authorize(t_w, "write:pr", now=12.0, chain_state_provider=lambda _c: narrowed)
    except StaleDelegationError as exc:
        print(f"blocked: {exc}")


if __name__ == "__main__":
    _demo()
