# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-trust-score-exchange-across-heterogeneous-runtimes-with-mismatched-score-semantics.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-trust-score-exchange-across-heterogeneous-runtimes-with-mismatched-score-semantics.warrant.json
# Markdown SHA-256:   c9e44b5b1f12cba5f32f7056a089450bad00fbfd89d6e75a3dee21be2013ea85
# Code AST SHA-256:   ec764373160d81aa537870d249b7460337547dbaa8687aabd726f11c29b6ed1c
# Verified Classes:   TrustPolarityMismatch, TrustClaim
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal

Polarity = Literal["confidence", "risk"]

class TrustPolarityMismatch(RuntimeError):
    """Raised when an exchanged trust scalar's orientation cannot be reconciled
    with the receiver's admission convention. Must fail closed: reject the
    negotiation, NOT the peer, and do not write a trust demotion."""
    pass

@dataclass(frozen=True)
class TrustClaim:
    value: float
    polarity: Polarity
    reference_class: str

def admit(claim: TrustClaim, receiver_polarity: Polarity,
          threshold: float) -> bool:
    if not (0.0 <= claim.value <= 1.0):
        raise TrustPolarityMismatch(f"out-of-range trust value {claim.value}")
    if claim.reference_class != "contract_satisfaction":
        raise TrustPolarityMismatch(
            f"unknown reference_class {claim.reference_class!r}; "
            "refusing to compare across reference classes")
    if claim.polarity != receiver_polarity:
        # Do NOT flip silently. A silent flip is how inversion loops start.
        raise TrustPolarityMismatch(
            f"peer polarity={claim.polarity!r} != receiver "
            f"polarity={receiver_polarity!r}; negotiation rejected, "
            "no demotion recorded")
    # Same orientation: comparison direction is now well-defined.
    if receiver_polarity == "confidence":
        return claim.value >= threshold
    else:  # risk: admit when risk is at or below threshold
        return claim.value <= threshold

def negotiate(claim: TrustClaim, receiver_polarity: Polarity,
              threshold: float, peer_id: str) -> bool:
    try:
        return admit(claim, receiver_polarity, threshold)
    except TrustPolarityMismatch as e:
        # Fail closed on the negotiation; leave the trust ledger untouched.
        raise TrustPolarityMismatch(
            f"negotiation with {peer_id} aborted: {e}") from e
