# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-advertised-capability-set-as-a-stale-snapshot-rather-than-a-live-contract-during-a2a-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-s-advertised-capability-set-as-a-stale-snapshot-rather-than-a-live-contract-during-a2a-negotiation.warrant.json
# Markdown SHA-256:   aff02adf568289ab6bbf720354d2a4c4584c8e96225aa3f99334fa3663e6950c
# Code AST SHA-256:   9ba8d21ad5f097781c651c908c3df73eadea473dc92a61d19ed607034440c0ff
# Verified Classes:   StaleCapabilityError, ProvenanceToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import hmac


class StaleCapabilityError(RuntimeError):
    """Raised when a peer's response lacks valid provenance for a claimed capability."""
    pass


class ProvenanceToken:
    def __init__(self, peer_key: bytes, request_nonce: str, capability: str, payload: bytes):
        self.peer_key = peer_key
        self.request_nonce = request_nonce
        self.capability = capability
        self.payload = payload

    def sign(self) -> str:
        msg = f"{self.request_nonce}:{self.capability}:{hashlib.sha256(self.payload).hexdigest()}"
        return hmac.new(self.peer_key, msg.encode(), hashlib.sha256).hexdigest()


def dispatch_with_provenance_check(
    peer_response: dict,
    expected_capability: str,
    request_nonce: str,
    peer_key: bytes,
    manifest_ttl_expired: bool,
) -> dict:
    # Side-effecting capabilities require provenance regardless of manifest freshness.
    side_effecting = {"execute_python", "write_file", "send_message"}
    requires_provenance = expected_capability in side_effecting or manifest_ttl_expired

    if not requires_provenance:
        return peer_response

    token = peer_response.get("provenance")
    if token is None:
        # Peer claimed the capability but produced no execution attestation.
        # This is the stale-manifest signature: plausible output, no trace.
        raise StaleCapabilityError(
            f"peer returned {expected_capability!r} response without provenance token; "
            f"capability set may have changed since manifest fetch (nonce={request_nonce})"
        )

    expected = ProvenanceToken(
        peer_key=peer_key,
        request_nonce=request_nonce,
        capability=expected_capability,
        payload=peer_response["payload"].encode(),
    ).sign()

    if not hmac.compare_digest(token, expected):
        # Token present but does not bind to this request: replay or forgery.
        raise StaleCapabilityError(
            f"provenance token mismatch for {expected_capability!r}; "
            f"token not bound to nonce={request_nonce} — possible replay from prior call"
        )

    return peer_response
