# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-degradation-when-heterogeneous-agent-protocols-negotiate-under-partial-observability.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-degradation-when-heterogeneous-agent-protocols-negotiate-under-partial-observability.warrant.json
# Markdown SHA-256:   332ec6dc29f30a96bb142bad5cfed65573295dad2eef20e418c139fb661ec670
# Code AST SHA-256:   7dca7f1eaf0a5f10bfcfbb65a39ad9be6b02b4ee36776e7921bd086242a1d430
# Verified Classes:   CapabilityDegradationError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CapabilityDegradationError(RuntimeError):
    """Raised when a negotiation acknowledgment fails the closed-world echo invariant."""
    pass


LOAD_BEARING_FIELDS = ("idempotent_retry", "error_semantics", "min_context_guarantee")


def validate_negotiation(request_envelope: dict, ack_envelope: dict) -> dict:
    """
    Enforce: every load-bearing field the caller depends on must be explicitly
    echoed with the same value in the ack. Absence is a denial, never a grant.
    """
    if not ack_envelope.get("accepted", False):
        raise CapabilityDegradationError(
            f"peer refused negotiation: {ack_envelope.get('reason', 'no reason given')}"
        )

    echoed = ack_envelope.get("capabilities", {})
    missing = []
    for field in LOAD_BEARING_FIELDS:
        if field not in request_envelope:
            continue
        if field not in echoed:
            missing.append(field)
        elif echoed[field] != request_envelope[field]:
            raise CapabilityDegradationError(
                f"capability mismatch on {field!r}: "
                f"requested {request_envelope[field]!r}, peer grants {echoed[field]!r}"
            )

    if missing:
        # Peer returned a structurally valid ack that silently dropped fields
        # it could not represent (e.g. older protocol version). This is the
        # exact condition that produces undetected duplicate side effects.
        raise CapabilityDegradationError(
            f"silent downgrade: peer did not echo load-bearing fields {missing!r}; "
            f"refusing dispatch rather than degrading"
        )

    return echoed


def negotiate_or_escalate(request_envelope: dict, peer_ack: dict) -> dict:
    try:
        return validate_negotiation(request_envelope, peer_ack)
    except CapabilityDegradationError as exc:
        # Escalate to a compatible peer / shim; never proceed on a hollow ack.
        raise CapabilityDegradationError(
            f"negotiation with peer failed invariant check, escalating: {exc}"
        ) from exc
