# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-agent-federation-from-silently-degrading-to-the-weakest-peer-s-policy-during-trust-bootstrap.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-agent-federation-from-silently-degrading-to-the-weakest-peer-s-policy-during-trust-bootstrap.warrant.json
# Markdown SHA-256:   aede45b13b34f598b77a384022619292fcab5cdaf45c1df6dd6b1a7494f7a604
# Code AST SHA-256:   9522fb8b7f42952febfeb276721ec77d2b673dfde9f021b58cb61471d80fcd44
# Verified Classes:   TrustLevel, ConstraintState, HardConstraint, PeerOffer, FederationBootstrapError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class TrustLevel(Enum):
    UNKNOWN = 0
    KNOWN = 1
    VERIFIED = 2
    AUDITED = 3


class ConstraintState(Enum):
    SATISFIES = "satisfies"
    VIOLATES = "violates"
    SILENT = "silent"  # must fail closed


@dataclass(frozen=True)
class HardConstraint:
    name: str
    required_value: Any
    min_trust: TrustLevel


@dataclass
class PeerOffer:
    peer_id: str
    trust: TrustLevel
    values: dict[str, Any] = field(default_factory=dict)
    # absence of a key == SILENT, never permissive


class FederationBootstrapError(RuntimeError):
    """Raised when a federation handshake would silently degrade a hard constraint."""


def evaluate_constraint(c: HardConstraint, offer: PeerOffer) -> ConstraintState:
    if c.name not in offer.values:
        return ConstraintState.SILENT
    if offer.values[c.name] == c.required_value:
        return ConstraintState.SATISFIES
    return ConstraintState.VIOLATES


def negotiate(
    local_floor: list[HardConstraint],
    peer: PeerOffer,
) -> dict[str, Any]:
    """
    Compute a joint policy ONLY after every hard constraint is confirmed
    satisfiable by the peer AT THE PEER'S TRUST LEVEL.
    Silence fails closed. Meet is computed only over preferences.
    """
    joint: dict[str, Any] = {}

    for c in local_floor:
        if peer.trust.value < c.min_trust.value:
            raise FederationBootstrapError(
                f"peer {peer.peer_id} trust={peer.trust.name} below "
                f"min_trust={c.min_trust.name} for constraint '{c.name}'"
            )
        state = evaluate_constraint(c, peer)
        if state is ConstraintState.SILENT:
            raise FederationBootstrapError(
                f"peer {peer.peer_id} is silent on hard constraint "
                f"'{c.name}'; silence must fail closed, not default to permissive"
            )
        if state is ConstraintState.VIOLATES:
            raise FederationBootstrapError(
                f"peer {peer.peer_id} violates hard constraint "
                f"'{c.name}': required={c.required_value!r} "
                f"offered={peer.values[c.name]!r}"
            )
        joint[c.name] = c.required_value

    # Only now may preferences be met/intersected.
    return joint


def bootstrap_federation(
    local_floor: list[HardConstraint],
    peers: list[PeerOffer],
) -> dict[str, Any]:
    """
    Multi-hop: joint policy must remain ⊨ every floor after each hop.
    Degradation is monotone-decreasing, so we re-validate against the
    accumulated floor, not just the immediate peer.
    """
    accumulated = dict(local_floor)
    joint: dict[str, Any] = {}
    for peer in peers:
        hop_floor = list(accumulated.values())
        joint = negotiate(hop_floor, peer)
        # invariant: joint must still satisfy every accumulated constraint
        for c in accumulated.values():
            if joint.get(c.name) != c.required_value:
                raise FederationBootstrapError(
                    f"post-hop invariant broken: constraint '{c.name}' "
                    f"lost after negotiating with {peer.peer_id}"
                )
    return joint
