# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-an-a2a-policy-negotiation-when-extension-schema-capability-claims-pass-structural-validation-but-diverge-at-t.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-an-a2a-policy-negotiation-when-extension-schema-capability-claims-pass-structural-validation-but-diverge-at-t.warrant.json
# Markdown SHA-256:   36cd5a611390233652289b19c0179df287ed985b3a98624cc64ec88750d7f1f9
# Code AST SHA-256:   0c87c296e7756a06eda4e3f910b80932d029678f4f34aa7e7c7f33ccedd8ad81
# Verified Classes:   SemanticNegotiationDivergence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SemanticNegotiationDivergence(RuntimeError):
    """Raised when an A2A extension handshake passes structural validation
    but the peers' required/optional partitions imply incompatible
    commitment semantics for a field the local agent treats as invariant."""


def negotiate_extension(
    local_required: set[str],
    local_optional: set[str],
    peer_required: set[str],
    peer_optional: set[str],
    locally_invariant_fields: set[str],
    degradation_contract_present: bool,
) -> dict:
    """Validate a single shared extension negotiation.

    Returns a commitment record on success. Aborts when the peer's required
    set is a strict subset of ours AND the missing fields are locally
    invariant AND no degradation contract pins the meaning of omission.
    """
    if not peer_required.issubset(local_required):
        # Peer requires something we don't advertise: structural reject.
        raise SemanticNegotiationDivergence(
            f"peer requires fields we do not advertise: {peer_required - local_required}"
        )

    partition_diverges = peer_required != local_required
    invariant_gap = (local_required - peer_required) & locally_invariant_fields

    if partition_diverges and invariant_gap and not degradation_contract_present:
        raise SemanticNegotiationDivergence(
            "structural pass but semantic divergence: peer treats "
            f"{sorted(invariant_gap)} as optional while local logic treats "
            "them as invariants, and no degradation contract pins omission "
            "semantics. Aborting negotiation to prevent delayed, "
            "misattributed downstream corruption."
        )

    # Safe path: record exactly which optional fields we treated as
    # guaranteed and on what authority (contract vs. peer-required).
    guarantees = {
        field: ("peer_required" if field in peer_required else "degradation_contract")
        for field in locally_invariant_fields
        if field in peer_required or degradation_contract_present
    }
    return {
        "extension_agreed": True,
        "guaranteed_fields": guarantees,
        "unpinned_optional": sorted(local_optional & peer_optional),
    }
