# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trust-broker-divergence-in-cross-org-agent-federation-policy-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trust-broker-divergence-in-cross-org-agent-federation-policy-exchange.warrant.json
# Markdown SHA-256:   ff6ceb9381b7ee16e16e048411b1c126bbc9249aaf80173b8a0a635efa5fb130
# Code AST SHA-256:   a6066f0fa59cd14ecfd83be1a9200dc65c2615f99d0ea6d34f0abd6175c412af
# Verified Classes:   TrustBrokerDivergenceError, PolicyVersion, GrantAck
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class TrustBrokerDivergenceError(RuntimeError):
    """Raised when broker projection and relying-party policy have diverged."""


@dataclass(frozen=True)
class PolicyVersion:
    org: str
    policy_id: str
    version: int


@dataclass(frozen=True)
class GrantAck:
    grant_id: str
    relying_party: PolicyVersion
    acknowledged: bool


def check_convergence(
    broker_view: PolicyVersion,
    ack: GrantAck,
    max_lag_generations: int = 1,
) -> None:
    """
    Enforce that a grant acknowledgment proves policy convergence, not merely receipt.
    Raises TrustBrokerDivergenceError when the relying party's acknowledged policy
    version has drifted from the broker's projection beyond the allowed lag.
    """
    if not ack.acknowledged:
        # Receipt-only acks do not prove convergence; treat as divergence-in-progress.
        raise TrustBrokerDivergenceError(
            f"grant {ack.grant_id}: acknowledgment does not carry policy version; "
            "convergence unproven"
        )

    if ack.relying_party.org != broker_view.org:
        raise TrustBrokerDivergenceError(
            f"grant {ack.grant_id}: ack org {ack.relying_party.org!r} "
            f"!= broker org {broker_view.org!r}"
        )

    if ack.relying_party.policy_id != broker_view.policy_id:
        raise TrustBrokerDivergenceError(
            f"grant {ack.grant_id}: policy_id mismatch "
            f"({ack.relying_party.policy_id!r} vs {broker_view.policy_id!r})"
        )

    lag = abs(broker_view.version - ack.relying_party.version)
    if lag > max_lag_generations:
        raise TrustBrokerDivergenceError(
            f"grant {ack.grant_id}: policy version lag {lag} exceeds "
            f"max {max_lag_generations} "
            f"(broker={broker_view.version}, relying={ack.relying_party.version})"
        )
