# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-peer-s-did-anchored-agent-credential-after-a-key-rotation-mid-session-and-why-does-the-cached-trust-anchor-silently.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-peer-s-did-anchored-agent-credential-after-a-key-rotation-mid-session-and-why-does-the-cached-trust-anchor-silently.warrant.json
# Markdown SHA-256:   449d53c69fcc72778875431fee0162c016f9e3f7ac5c2831014e910123f3c804
# Code AST SHA-256:   a3106029ac7bd37a4c547de3b2e099aebaee83109c224b7d7a3b1b9c72bfc987
# Verified Classes:   AnchorStaleError, TrustAnchor, Session
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class AnchorStaleError(RuntimeError):
    """Raised when a session's cached DID trust anchor is older than the
    admissible freshness bound, or when re-resolution shows the anchoring
    verification method is no longer active."""
    pass


@dataclass
class TrustAnchor:
    peer_did: str
    verification_method_id: str
    public_key: bytes
    resolved_at: float
    delta_seconds: float  # admissible staleness bound

    def is_fresh(self, now: float) -> bool:
        return (now - self.resolved_at) <= self.delta_seconds


@dataclass
class Session:
    anchor: TrustAnchor
    privileged_actions: list = field(default_factory=list)


def resolve_did_active_method(peer_did: str) -> str:
    # Network call to the DID resolver. Returns the currently active
    # assertion verificationMethod id. In production this hits did:web /
    # did:ion resolution; here it is a stub representing the authoritative
    # source of truth.
    raise NotImplementedError("wire to DID resolver")


def authorize_privileged_action(session: Session, now: float) -> None:
    anchor = session.anchor

    # Fast path: anchor is within freshness bound.
    if anchor.is_fresh(now):
        session.privileged_actions.append(now)
        return

    # Freshness lapsed mid-session: must re-resolve before trusting.
    active_method = resolve_did_active_method(anchor.peer_did)

    if active_method != anchor.verification_method_id:
        # The key we anchored the session to has been rotated or revoked.
        # Freeze: do not authorize, do not silently continue.
        raise AnchorStaleError(
            f"Session anchored to {anchor.verification_method_id} on "
            f"{anchor.peer_did}, but authoritative active method is now "
            f"{active_method}. Re-attestation required before privileged "
            f"action at t={now}."
        )

    # Same key still active: refresh the anchor timestamp and proceed.
    anchor.resolved_at = now
    session.privileged_actions.append(now)
