# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-when-quorum-attestation-masks-a-divergent-commitment-set-during-byzantine-agent-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-when-quorum-attestation-masks-a-divergent-commitment-set-during-byzantine-agent-consensus.warrant.json
# Markdown SHA-256:   77afce8dfcafe5aeb1145ce3f558254d0d17399ba50ef9174da1ef0599d1d273
# Code AST SHA-256:   1b4b1d61d4b7a4bf2b63f46985bcd1c52050cdc107a6720afea7f9b939a815e7
# Verified Classes:   CommitmentDivergence, Commitment
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable

class CommitmentDivergence(RuntimeError):
    """Raised when an honest intersection node observes two semantically
    incompatible commitments in the same view, despite distinct hashes."""
    pass

@dataclass(frozen=True)
class Commitment:
    view: int
    scope: str          # canonical normal form, e.g. structured scope expression
    shard_assignments: tuple[tuple[str, str], ...]  # sorted (shard, agent)

    def canonical_hash(self) -> str:
        # Deterministic: sorted shards, normalized scope whitespace.
        norm_scope = " ".join(self.scope.split())
        parts = [f"v={self.view}", f"s={norm_scope}"]
        parts += [f"{k}:{v}" for k, v in sorted(self.shard_assignments)]
        return "|".join(parts)

def sign_commitment(
    candidate: Commitment,
    signed_in_view: Iterable[Commitment],
) -> str:
    """Signing predicate. Refuses to sign a commitment that diverges
    semantically from any prior commitment in the same view."""
    canon = candidate.canonical_hash()
    for prior in signed_in_view:
        if prior.view != candidate.view:
            continue
        if prior.canonical_hash() == canon:
            continue  # benign idempotent retry
        # Distinct hash in same view: must verify semantic compatibility.
        if _semantically_incompatible(prior, candidate):
            raise CommitmentDivergence(
                f"view {candidate.view}: candidate {canon!r} diverges from "
                f"prior {prior.canonical_hash()!r}; halting, not signing"
            )
    return canon

def _semantically_incompatible(a: Commitment, b: Commitment) -> bool:
    # Scope normal form comparison; shard assignment conflicts count as divergence.
    if " ".join(a.scope.split()) != " ".join(b.scope.split()):
        return True
    if dict(a.shard_assignments) != dict(b.shard_assignments):
        return True
    return False
