# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-capabilities-against-a-stale-trust-anchor-the-silent-widening-of-the-accepted-capability-set.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-capabilities-against-a-stale-trust-anchor-the-silent-widening-of-the-accepted-capability-set.warrant.json
# Markdown SHA-256:   741d467fd091aedd7a4805eccbfa47ec178f68ab8d612468436c87dbed907d55
# Code AST SHA-256:   49b4d88d8c7a78001cc1f2221f8175428cba9c6f694d6203ba9639099b7bd197
# Verified Classes:   StaleTrustAnchorError, PeerAnchorState, NegotiatedCapability
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleTrustAnchorError(RuntimeError):
    """Raised when a peer's anchor epoch is behind the locally known epoch,
    or is absent, meaning the negotiated capability set may be widened
    relative to the peer's current revocation state."""


@dataclass(frozen=True)
class PeerAnchorState:
    peer_id: str
    anchor_epoch: int | None   # None means the peer did not publish one


@dataclass(frozen=True)
class NegotiatedCapability:
    name: str
    sensitive: bool


def admit_capability(
    peer: PeerAnchorState,
    local_known_epoch: int,
    cap: NegotiatedCapability,
) -> bool:
    """
    Admit a negotiated capability only when the peer's anchor epoch is
    provably at least as new as our locally known epoch. An absent epoch
    is treated as stale, never as fresh.
    """
    if peer.anchor_epoch is None:
        raise StaleTrustAnchorError(
            f"peer {peer.peer_id!r} did not publish an anchor epoch; "
            f"cannot prove capability {cap.name!r} is not widened"
        )

    if peer.anchor_epoch < local_known_epoch:
        raise StaleTrustAnchorError(
            f"peer {peer.peer_id!r} anchor epoch {peer.anchor_epoch} is behind "
            f"local known epoch {local_known_epoch}; capability {cap.name!r} "
            f"may be revoked at the peer"
        )

    # Epoch is current; sensitive capabilities still require a live re-check
    # at request time, but negotiation admission is safe here.
    return True


def negotiate(
    peer: PeerAnchorState,
    local_known_epoch: int,
    declared: list[NegotiatedCapability],
) -> list[NegotiatedCapability]:
    admitted: list[NegotiatedCapability] = []
    for cap in declared:
        if admit_capability(peer, local_known_epoch, cap):
            admitted.append(cap)
    return admitted
