# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-capability-negotiation-schema-drift-before-it-commits-to-a-degraded-execution-path.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-capability-negotiation-schema-drift-before-it-commits-to-a-degraded-execution-path.warrant.json
# Markdown SHA-256:   c7a4e6984079311097363c1bd28ce8324c14147ebc1a429bb8d464fd2d74ded6
# Code AST SHA-256:   2509896df0c38f1568a30fba19fe7237026b7d7ad80d6aa2bcf8ba3a34607b25
# Verified Classes:   CapabilityNegotiationError, NegotiationResult, CallerProfile
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CapabilityNegotiationError(RuntimeError):
    """Raised when a peer accepts a handshake but cannot honor requested semantics."""


@dataclass
class NegotiationResult:
    status: str                      # "accepted" | "rejected"
    schema_version: str
    supported_features: set[str] = field(default_factory=set)


@dataclass
class CallerProfile:
    capability: str
    pinned_schema: str
    requested_features: set[str]
    # feature -> name of the caller-side degradation path, if one exists
    degradation_paths: dict[str, str] = field(default_factory=dict)


def negotiate_and_gate(profile: CallerProfile, peer: NegotiationResult) -> dict:
    """
    Gate execution on feature intersection, NOT on peer.status.
    Returns an execution plan; raises if the peer cannot honor semantics
    and no declared degradation exists.
    """
    if peer.status != "accepted":
        # Rejection is safe: caller's normal fallback machinery handles it.
        return {"mode": "fallback", "reason": "peer_rejected"}

    missing = profile.requested_features - peer.supported_features
    if not missing:
        return {"mode": "happy", "schema": peer.schema_version}

    # Peer accepted the payload but cannot honor these features.
    undeclared = {f for f in missing if f not in profile.degradation_paths}
    if undeclared:
        # The dangerous case: status=="accepted" but semantics unmet.
        raise CapabilityNegotiationError(
            f"peer {peer.schema_version} accepted {profile.capability} "
            f"but silently drops {sorted(undeclared)}; no declared degradation. "
            f"Refusing to execute on a schema-tolerance-only accept."
        )

    # Every missing feature has a tested degradation path.
    return {
        "mode": "degraded",
        "schema": peer.schema_version,
        "degraded_features": sorted(missing),
        "degradation_paths": {f: profile.degradation_paths[f] for f in missing},
    }


# --- trace of the incident ---
caller = CallerProfile(
    capability="summarize",
    pinned_schema="2.1",
    requested_features={"preserve_entities"},
    degradation_paths={},  # caller had NO declared fallback for this feature
)
peer = NegotiationResult(
    status="accepted",
    schema_version="2.3",
    supported_features={"entity_retention"},  # renamed; old name absent
)

try:
    plan = negotiate_and_gate(caller, peer)
    print("executing:", plan)
except CapabilityNegotiationError as e:
    print("BLOCKED:", e)
