# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-capability-attestation-as-stale-the-moment-its-own-tool-surface-changes-mid-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-peer-s-capability-attestation-as-stale-the-moment-its-own-tool-surface-changes-mid-negotiation.warrant.json
# Markdown SHA-256:   95953b7fa9b84cf1fbe8c6ca820b60c279d5a237cf0f030729505e764518da5b
# Code AST SHA-256:   b114efb07bd034736bfb02dfea6b7267c60aa717a9d704637e3527ad2f861123
# Verified Classes:   StaleAttestationError, Attestation, NegotiationState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import FrozenSet


class StaleAttestationError(RuntimeError):
    """Raised when a cached peer attestation is no longer applicable
    to the current local tool surface, regardless of TTL remaining."""


@dataclass(frozen=True)
class Attestation:
    peer_id: str
    capabilities: FrozenSet[str]
    constraints: FrozenSet[str]          # e.g. {"no_shell_peers"}
    negotiated_against_surface_hash: str
    issued_at: float
    ttl: float


@dataclass
class NegotiationState:
    local_surface: FrozenSet[str]
    cached: Attestation | None = None
    stale_but_inert: bool = False

    def surface_hash(self) -> str:
        return hashlib.sha256(
            "|".join(sorted(self.local_surface)).encode()
        ).hexdigest()


def advance_trust_tier(state: NegotiationState, peer: Attestation, now: float) -> str:
    if peer.issued_at + peer.ttl <= now:
        raise StaleAttestationError(
            f"attestation for {peer.peer_id} expired by wall clock"
        )

    current_hash = state.surface_hash()
    if peer.negotiated_against_surface_hash != current_hash:
        # Surface moved since attestation was minted. Determine whether the
        # delta touches the peer's constraints or the plan's required caps.
        delta = state.local_surface.symmetric_difference(
            _surface_from_hash(peer.negotiated_against_surface_hash, state)
        )
        if delta & peer.constraints:
            raise StaleAttestationError(
                f"attestation for {peer.peer_id} stale: surface delta {delta} "
                f"intersects peer constraints {peer.constraints}; "
                f"re-attestation required before trust advance"
            )
        # Delta is inert w.r.t. constraints; allow but mark.
        state.stale_but_inert = True

    state.cached = peer
    return "provisional"


def _surface_from_hash(h: str, state: NegotiationState) -> FrozenSet[str]:
    # In a real system the previous surface is retained in the transcript.
    # Here we conservatively return the current surface so that an
    # unattributable hash forces the strict branch above.
    return state.local_surface
