# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-policy-negotiation-downgrade-during-cross-org-agent-federation-handshake-when-capability-attestations-are-cached-asymmet.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-policy-negotiation-downgrade-during-cross-org-agent-federation-handshake-when-capability-attestations-are-cached-asymmet.warrant.json
# Markdown SHA-256:   dcadbb4b19bce8eb16a657f9506640fe1f916ea24fd8ff1a656d5e621704055c
# Code AST SHA-256:   a1f4a8f07f86d2e30a775fb8d52a9d11eabda1ee0dcc0ec64517f8aa587b2cdf
# Verified Classes:   PolicySnapshotDivergence, Envelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class PolicySnapshotDivergence(RuntimeError):
    """Raised when a federation handshake would proceed under mismatched policy snapshots."""
    pass


@dataclass(frozen=True)
class Envelope:
    org: str
    snapshot_ref: str          # e.g. "sha:4a71..."
    allowed_tiers: frozenset
    required_warrants: dict    # tier -> required warrant predicate names

    def ref(self) -> str:
        return self.snapshot_ref


def negotiate_handshake(
    local: Envelope,
    peer_presented_ref: str,
    peer_requested_tiers: frozenset,
    peer_envelope_cache: Envelope,   # our cached view of peer — used ONLY for identity check
) -> frozenset:
    """
    Enforce the snapshot-identity invariant before granting scope.

    Invariant: the peer's presented snapshot_ref must equal the snapshot_ref
    our enforcement layer will consult (local.ref()). A superseded ref is a
    divergence, not a hint. Constraints are sourced from LOCAL envelope only.
    """
    if peer_presented_ref != local.ref():
        raise PolicySnapshotDivergence(
            f"peer presented snapshot {peer_presented_ref!r} but local enforcement "
            f"uses {local.ref()!r}; re-negotiation required against live envelope"
        )

    # Defense in depth: our cache of the peer must not be used to relax OUR constraints.
    if peer_envelope_cache.org != local.org and peer_envelope_cache.ref() == local.ref():
        # Cached peer view claims to be us — treat as cache poisoning / identity confusion.
        raise PolicySnapshotDivergence(
            f"peer cache for org {peer_envelope_cache.org} carries our snapshot ref; "
            f"refusing to source constraints from peer-held view"
        )

    granted = peer_requested_tiers & local.allowed_tiers
    # Apply LOCAL warrant requirements to every granted tier.
    for tier in granted:
        if tier in local.required_warrants:
            # Caller must attach the named warrant; negotiation only records the obligation.
            pass
    return frozenset(granted)


def bind_session(local: Envelope, peer_ref: str, granted: frozenset) -> dict:
    if peer_ref != local.ref():
        raise PolicySnapshotDivergence("cannot bind session to divergent snapshots")
    pair_id = hashlib.sha256(f"{local.ref()}|{peer_ref}".encode()).hexdigest()[:16]
    return {"session_snapshot_pair": pair_id, "granted_tiers": granted}
