# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-resolve-a-peer-s-identity-when-the-trust-anchor-is-itself-a-delegated-agent-whose-warrant-expires-mid-handshake.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-resolve-a-peer-s-identity-when-the-trust-anchor-is-itself-a-delegated-agent-whose-warrant-expires-mid-handshake.warrant.json
# Markdown SHA-256:   afcc1c43c19bf550767b2aae1c48be1337a91988910cccb47856bfcf3c975f7a
# Code AST SHA-256:   18e7eb65f20d21c6f71716d8d5f805be155381023f92ffe02c8b6d32ad6a11e3
# Verified Classes:   ChainCoherenceError, Warrant, ChainValidityToken
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ChainCoherenceError(RuntimeError):
    """Raised when a delegated-trust chain is not valid at a single instant."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    issuer: str
    not_before: float
    not_after: float
    anchor_epoch: int


@dataclass(frozen=True)
class ChainValidityToken:
    chain_id: str
    lo: float
    hi: float
    anchor_epoch: int


def resolve_chain(chain: list[Warrant], current_anchor_epoch: int) -> ChainValidityToken:
    """Compute the atomic intersection interval; reject empty or stale-epoch chains."""
    if not chain:
        raise ChainCoherenceError("empty chain has no validity interval")

    epochs = {w.anchor_epoch for w in chain}
    if epochs != {current_anchor_epoch}:
        raise ChainCoherenceError(
            f"chain spans anchor epochs {sorted(epochs)}, current is {current_anchor_epoch}"
        )

    lo = max(w.not_before for w in chain)
    hi = min(w.not_after for w in chain)
    if lo >= hi:
        raise ChainCoherenceError(
            f"empty intersection interval [{lo}, {hi}]: chain never valid at one instant"
        )
    return ChainValidityToken(
        chain_id="|".join(w.subject for w in chain),
        lo=lo,
        hi=hi,
        anchor_epoch=current_anchor_epoch,
    )


def assert_authorized_for_action(
    token: ChainValidityToken, action_instant: float, current_anchor_epoch: int
) -> None:
    """Use-time validity check: the predicate must hold at the action instant."""
    if token.anchor_epoch != current_anchor_epoch:
        raise ChainCoherenceError(
            f"anchor epoch rotated {token.anchor_epoch}->{current_anchor_epoch}; "
            "warrant superseded, revoke delegatee"
        )
    if not (token.lo <= action_instant <= token.hi):
        raise ChainCoherenceError(
            f"action at t={action_instant} outside chain interval "
            f"[{token.lo}, {token.hi}]: zombie delegatee refused"
        )


# Failure trace reproduced: anchor expires between resolve and action.
anchor_epoch = 7
o7 = Warrant("orchestrator-7", "supervisor", not_before=0.0, not_after=0.02, anchor_epoch=7)
w3 = Warrant("worker-3", "orchestrator-7", not_before=0.0, not_after=3600.0, anchor_epoch=7)

token = resolve_chain([w3, o7], current_anchor_epoch=anchor_epoch)  # lo=0.0, hi=0.02
assert_authorized_for_action(token, action_instant=time.monotonic() if False else 0.01, current_anchor_epoch=7)

# The bug the article dissects: action at t=0.03 is past the anchor's not_after.
assert_authorized_for_action(token, action_instant=0.03, current_anchor_epoch=7)  # raises
