# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-a-peer-s-capability-envelope-after-a-warrant-rotation-and-why-the-naive-re-negotiation-path-silently-widens-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-a-peer-s-capability-envelope-after-a-warrant-rotation-and-why-the-naive-re-negotiation-path-silently-widens-scope.warrant.json
# Markdown SHA-256:   3baf48b01b09e6389e2e3371775aca3a20e6768717980a529f1e422b44aa8f2b
# Code AST SHA-256:   adb56532ffd0cb3676b335e0be9a2cec8515099031c6eb95982eeb9f1f821033
# Verified Classes:   CapabilityBindingError, Warrant, Manifest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CapabilityBindingError(RuntimeError):
    """Raised when a peer manifest cannot be bound to the caller's held warrant."""
    pass


@dataclass(frozen=True)
class Warrant:
    peer_id: str
    bound_key_fingerprint: str
    permitted: frozenset[str]
    expires_at: float
    revoked: bool = False


@dataclass(frozen=True)
class Manifest:
    peer_id: str
    signer_fingerprint: str
    advertised: frozenset[str]
    signature_valid: bool


def fingerprint(public_key_pem: bytes) -> str:
    return hashlib.sha256(public_key_pem).hexdigest()


def negotiate(warrant: Warrant, manifest: Manifest, now: float) -> frozenset[str]:
    """
    Two-input re-negotiation. Returns the effective envelope as manifest ∩ warrant.
    Fails closed on any identity/warrant mismatch. Never returns a superset of
    the warrant's permitted set, even if the manifest advertises more.
    """
    if warrant.revoked:
        raise CapabilityBindingError(
            f"warrant for {warrant.peer_id} is revoked; refusing re-negotiation"
        )
    if now >= warrant.expires_at:
        raise CapabilityBindingError(
            f"warrant for {warrant.peer_id} expired at {warrant.expires_at}"
        )
    if not manifest.signature_valid:
        raise CapabilityBindingError(
            f"manifest from {manifest.peer_id} has invalid signature"
        )
    if manifest.peer_id != warrant.peer_id:
        raise CapabilityBindingError(
            f"manifest peer {manifest.peer_id} != warrant peer {warrant.peer_id}"
        )
    # The load-bearing check: signer must be the key the warrant names.
    if manifest.signer_fingerprint != warrant.bound_key_fingerprint:
        raise CapabilityBindingError(
            f"rotation gap: manifest signer {manifest.signer_fingerprint} "
            f"!= warrant-bound key {warrant.bound_key_fingerprint} for "
            f"{warrant.peer_id}; re-acquire warrant before proceeding"
        )
    # Envelope is intersection: manifest may narrow, never widen.
    return frozenset(manifest.advertised) & frozenset(warrant.permitted)


def admit_call(warrant: Warrant, manifest: Manifest, tool: str, now: float) -> None:
    envelope = negotiate(warrant, manifest, now)
    if tool not in envelope:
        raise CapabilityBindingError(
            f"tool {tool!r} outside effective envelope {sorted(envelope)} "
            f"for {warrant.peer_id}"
        )
