# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-a-peer-s-policy-warrant-after-a-federation-trust-anchor-rotation-rather-than-reusing-the-cached-attestation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-a-peer-s-policy-warrant-after-a-federation-trust-anchor-rotation-rather-than-reusing-the-cached-attestation-chain.warrant.json
# Markdown SHA-256:   e25fb16d90b80453612571cf1661dd3ecbd5426aa68b7dd67004adeed77f8e56
# Code AST SHA-256:   6dd5495ffd07e69c765f422ac849ba77e66379f95c68d1aa0c825e4ef76ad135
# Verified Classes:   AnchorState, ProvenanceDriftError, CachedWarrant, PeerPolicyState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class AnchorState(Enum):
    CURRENT = "current"
    RETIRED = "retired"
    REVOKED = "revoked"


class ProvenanceDriftError(RuntimeError):
    """Raised when a cached warrant's policy authority no longer matches the peer's live epoch."""
    pass


@dataclass
class CachedWarrant:
    warrant_id: str
    issuing_epoch: int
    verifying_anchor: str
    scope: str


@dataclass
class PeerPolicyState:
    current_anchor: str
    anchor_states: dict          # anchor_id -> AnchorState
    current_policy_epoch: int
    narrowing_directives: list   # list of scopes narrowed under old epochs
    continuity_asserted: bool    # peer asserts old-epoch warrants semantically unchanged


def must_rederive(w: CachedWarrant, p: PeerPolicyState, is_write: bool) -> bool:
    if w.issuing_epoch != p.current_policy_epoch:
        return True
    if p.anchor_states.get(w.verifying_anchor) == AnchorState.RETIRED and not p.continuity_asserted:
        return True
    if w.scope in p.narrowing_directives:
        return True
    if is_write and p.anchor_states.get(w.verifying_anchor) != AnchorState.CURRENT:
        return True
    return False


def use_warrant(w: CachedWarrant, p: PeerPolicyState, is_write: bool, rederive_fn):
    if must_rederive(w, p, is_write):
        fresh = rederive_fn(w.warrant_id)
        if fresh is None:
            raise ProvenanceDriftError(
                f"warrant {w.warrant_id} could not be re-derived under anchor "
                f"{p.current_anchor} epoch {p.current_policy_epoch}; "
                f"cached chain verified against retired anchor {w.verifying_anchor} "
                f"but policy currency is not established"
            )
        return fresh
    return w
