# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-sovereignty-boundary-negotiation-deadlock-in-cross-org-agent-federation-the-policy-lattice-non-join-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-sovereignty-boundary-negotiation-deadlock-in-cross-org-agent-federation-the-policy-lattice-non-join-failure.warrant.json
# Markdown SHA-256:   cf8dd63c912cb21f59fe96864a17eb776d9b58949f743d5b00cdc73487fc1481
# Code AST SHA-256:   f830649a080111aaa54679351266ff9515b1aac51988d0c3ab26588eaebf6083
# Verified Classes:   SovereigntyNonJoinableError, Verdict, PolicyProposal, NegotiationState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class SovereigntyNonJoinableError(RuntimeError):
    """Raised when two federated policies cannot be joined in the lattice sense.

    Distinct from a DENY verdict: a DENY is a computed terminal state.
    This error means no terminal state is computable because the two
    policy lattices are non-isomorphic (e.g. permissive vs. prohibitive
    polarity) and share no canonical vocabulary.
    """


class Verdict(Enum):
    ACCEPT = "accept"
    DENY = "deny"
    ESCALATE = "escalate"


@dataclass(frozen=True)
class PolicyProposal:
    """One round's proposal. `atoms` is the set of constraint atoms asserted."""
    atoms: FrozenSet[str]

    def constrains_more_than(self, other: "PolicyProposal") -> bool:
        # A proposal is "more constrained" iff its atom set strictly grows.
        return self.atoms > other.atoms


@dataclass
class NegotiationState:
    seen: set[FrozenSet[str]] = field(default_factory=set)
    frontier: set[str] = field(default_factory=set)
    max_rounds: int = 32
    stagnation_budget: int = 3

    def record(self, proposal: PolicyProposal) -> None:
        self.seen.add(proposal.atoms)


def negotiate(
    local: PolicyProposal,
    remote_proposals: list[PolicyProposal],
) -> Verdict:
    """Drive a bounded negotiation with a SET-membership fixed-point detector.

    Correctness invariant: a two-cycle (A→B→A→B...) must be detected as a
    fixed point even though no two ADJACENT proposals are equal. Adjacent-
    equality checkers miss this and loop forever; set-membership does not.
    """
    state = NegotiationState()
    state.record(local)
    stagnant_rounds = 0
    last_frontier_size = len(state.frontier)

    for round_idx, proposal in enumerate(remote_proposals):
        if round_idx >= state.max_rounds:
            raise SovereigntyNonJoinableError(
                f"exceeded max_rounds={state.max_rounds} without terminal verdict; "
                f"frontier={sorted(state.frontier)}"
            )

        # FIXED-POINT DETECTOR: membership in the SET of all prior proposals,
        # not equality with the immediately preceding one.
        if proposal.atoms in state.seen:
            raise SovereigntyNonJoinableError(
                "policy-lattice non-join: proposal repeats an earlier state "
                f"(atoms={sorted(proposal.atoms)}); lattices are non-isomorphic "
                "and admit no greatest lower bound. Escalate to canonicalization; "
                "do NOT proceed and do NOT retry."
            )
        state.record(proposal)

        # PROGRESS CHECK: frontier must strictly shrink or we are stagnating.
        state.frontier |= proposal.atoms
        if len(state.frontier) >= last_frontier_size:
            stagnant_rounds += 1
            if stagnant_rounds >= state.stagnation_budget:
                raise SovereigntyNonJoinableError(
                    "constraint frontier failed to shrink for "
                    f"{stagnant_rounds} rounds; negotiation is not making "
                    "lattice-theoretic progress."
                )
        else:
            stagnant_rounds = 0
        last_frontier_size = len(state.frontier)

        if not state.frontier:
            return Verdict.ACCEPT

    # Ran out of proposals without a verdict: escalate, never proceed.
    return Verdict.ESCALATE
