# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-divergence-during-cross-org-agent-federation-and-why-reputation-exchange-masks-it-until-policy-enforceme.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trust-anchor-divergence-during-cross-org-agent-federation-and-why-reputation-exchange-masks-it-until-policy-enforceme.warrant.json
# Markdown SHA-256:   a9fcc23e5714bc74b7b7e39f3a5145c996b5c7040ce28c881345d24a2939304a
# Code AST SHA-256:   f89c7aee273ea8a37812d9feedea8adac58b1ad8e2aafdb8a9b937c8da3f5c05
# Verified Classes:   AnchorDivergenceError, FederationView
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, Set


class AnchorDivergenceError(RuntimeError):
    """Raised when a peer's pinned anchor set diverges from the federation directory."""
    pass


@dataclass
class FederationView:
    # peer_id -> set of pinned anchor fingerprints
    pins: Dict[str, Set[str]] = field(default_factory=dict)
    # federation directory's published anchor fingerprints
    directory: Set[str] = field(default_factory=set)
    # peer_id -> reputation score (for illustration; deliberately not used for gating)
    reputation: Dict[str, float] = field(default_factory=dict)


def fingerprint(anchor_bytes: bytes) -> str:
    return hashlib.sha256(anchor_bytes).hexdigest()


def check_anchor_agreement(view: FederationView, previous_divergence: Dict[str, int]) -> Dict[str, int]:
    """
    Returns per-peer divergence counts (size of symmetric difference between
    pinned set and directory set). Raises if divergence is growing for any peer
    while reputation appears healthy — the masked-partition condition.
    """
    divergence: Dict[str, int] = {}
    for peer, pinned in view.pins.items():
        diff = pinned.symmetric_difference(view.directory)
        divergence[peer] = len(diff)

    for peer, count in divergence.items():
        prior = previous_divergence.get(peer, 0)
        # Reputation is intentionally NOT consulted as a health gate here.
        if count > 0 and count > prior:
            raise AnchorDivergenceError(
                f"Peer {peer} anchor pin divergence growing ({prior} -> {count}) "
                f"while reputation score is {view.reputation.get(peer, 'n/a')}. "
                f"Reputation convergence is anchor-agnostic; do not treat it as health."
            )
    return divergence


def enforce_cross_org_decision(view: FederationView, previous_divergence: Dict[str, int]) -> None:
    divergence = check_anchor_agreement(view, previous_divergence)
    if any(count > 0 for count in divergence.values()):
        raise AnchorDivergenceError(
            f"Refusing to treat cross-org policy decisions as mutually valid: "
            f"non-empty pin divergence {divergence}. Re-pin before proceeding."
        )
