# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-negotiate-a-brokered-capability-token-after-a-policy-mediated-downgrade-and-when-is-stale-trust-still-valid.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-negotiate-a-brokered-capability-token-after-a-policy-mediated-downgrade-and-when-is-stale-trust-still-valid.warrant.json
# Markdown SHA-256:   fb7fcba7d4b3ac04281a2633668087318b5afe27d3d3d817ba345c2f920acbc0
# Code AST SHA-256:   a99a0d6d963652f9b03f15fa0f6ee6196bcbfdcc3b3234b6d4ca0bc2cbaabda1
# Verified Classes:   StaleBrokeredCapabilityError, BrokeredToken, ProviderPolicy
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleBrokeredCapabilityError(RuntimeError):
    """Raised when a brokered capability token authenticates but no longer
    authorizes the operation under the provider's current policy epoch."""
    pass


@dataclass(frozen=True)
class BrokeredToken:
    token_id: str
    audience: str
    policy_epoch: int          # epoch recorded at broker mint time
    scope: frozenset           # capability claims, e.g. {"read:docs", "classify:internal"}
    expires_at: float          # cryptographic validity (monotonic seconds)


@dataclass(frozen=True)
class ProviderPolicy:
    current_epoch: int
    active_scope: frozenset    # claims valid under current_epoch


def validate_and_authorize(
    token: BrokeredToken,
    policy: ProviderPolicy,
    now: float,
    operation_has_side_effects: bool,
) -> None:
    # 1. Cryptographic validity: authenticity, audience, expiry.
    if now >= token.expires_at:
        raise StaleBrokeredCapabilityError(
            f"token {token.token_id} expired at {token.expires_at}, now={now}"
        )

    # 2. Policy-epoch binding: the token's mint-time epoch must match the
    #    provider's current epoch. A mismatch means the token authenticates
    #    but its scope was defined under a superseded policy.
    if token.policy_epoch != policy.current_epoch:
        # Effective scope under the current epoch, not the mint-time scope.
        effective = token.scope & policy.active_scope
        lost = token.scope - policy.active_scope

        if operation_has_side_effects:
            # Hard boundary: never silently re-scope a side-effecting op.
            raise StaleBrokeredCapabilityError(
                f"token {token.token_id} minted at epoch {token.policy_epoch} "
                f"but provider is at epoch {policy.current_epoch}; "
                f"lost claims {sorted(lost)}; side-effecting op requires "
                f"explicit re-negotiation and escalation, not silent reuse"
            )

        # Idempotent read/classify: re-negotiation is required; refuse to
        # proceed on the stale token even though it authenticates.
        if lost:
            raise StaleBrokeredCapabilityError(
                f"token {token.token_id} authentic but scope downgraded under "
                f"epoch {policy.current_epoch}: lost {sorted(lost)}; "
                f"re-negotiate before reuse"
            )

    # 3. Scope check against the *current* effective scope.
    if not token.scope <= policy.active_scope:
        raise StaleBrokeredCapabilityError(
            f"token {token.token_id} scope {sorted(token.scope)} not a subset "
            f"of active scope {sorted(policy.active_scope)} at epoch "
            f"{policy.current_epoch}"
        )


def consume(
    token: BrokeredToken,
    policy: ProviderPolicy,
    now: float,
    has_side_effects: bool,
) -> None:
    validate_and_authorize(token, policy, now, has_side_effects)
    # ... proceed with brokered invocation ...
