# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-peer-s-capability-claim-before-schema-binding-the-capability-claim-under-observation-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-peer-s-capability-claim-before-schema-binding-the-capability-claim-under-observation-invariant.warrant.json
# Markdown SHA-256:   f8443f6d70e86a172736efeb072e681ce47f3fcf34e795a951c4c268499b4b24
# Code AST SHA-256:   33a4e56688dfa4b1f8b7050ade012a02a502d65635d71dcb92b4f6da8d9c7e34
# Verified Classes:   CapabilityClaimViolation, PeerCapability
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class CapabilityClaimViolation(RuntimeError):
    """Raised when an agent binds to a peer capability without behavioral evidence."""
    pass


class PeerCapability:
    def __init__(self, peer_id: str, schema_hash: str, claims: dict):
        self.peer_id = peer_id
        self.schema_hash = schema_hash
        self.claims = claims  # e.g. {"ordering": "score_desc", "freshness_s": 3600}
        self.probe_passed = False
        self.observations = 0


def bind_capability(
    peer: PeerCapability,
    input_class: str,
    downstream_idempotent: bool,
    canary_verified: bool,
    n_min: int = 1,
) -> None:
    """Bind to a peer capability only if the behavioral invariant holds.

    The invariant: under partial observability, a non-idempotent consumer
    of a peer's output whose schema asserts an unverifiable distributional
    property must have a passing canary probe before binding.
    """
    if downstream_idempotent:
        # Cheap to undo; schema match is sufficient.
        peer.probe_passed = True
        return

    if peer.observations < n_min and not canary_verified:
        raise CapabilityClaimViolation(
            f"Refusing to bind {peer.peer_id}::{input_class}: "
            f"observations={peer.observations} < n_min={n_min} and no "
            f"canary verification. Schema hash {peer.schema_hash} matches, "
            f"but claims {peer.claims!r} are unproven on this input class. "
            f"Binding now would promote a hypothesis to episodic fact."
        )

    peer.probe_passed = True


def revalidate_if_due(peer: PeerCapability, calls_since_probe: int, max_calls: int = 10) -> bool:
    """Force re-probe before a peer's behavioral belief hardens."""
    if calls_since_probe >= max_calls:
        peer.probe_passed = False
        peer.observations = 0
        return True
    return False
