# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-federated-trust-anchor-ratchet-is-silently-downgrading-policy-across-agent-orgs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-federated-trust-anchor-ratchet-is-silently-downgrading-policy-across-agent-orgs.warrant.json
# Markdown SHA-256:   23168234bc9b3450d793324664bb2e589a02261ab153db8829edbdb32c21a34f
# Code AST SHA-256:   81a4492167b8a4eecbdd970a9295ad737a64c83ec3f0eaec8a3e98eec133c94f
# Verified Classes:   PolicyRatchetError, PolicyBundle
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Mapping, FrozenSet


class PolicyRatchetError(RuntimeError):
    """Raised when a federated policy merge would silently widen a grant."""


@dataclass(frozen=True)
class PolicyBundle:
    org: str
    schema_version: int
    allow: Mapping[str, FrozenSet[str]]   # axis -> permitted values
    deny: Mapping[str, FrozenSet[str]]    # axis -> forbidden values
    explicit_wildcard: FrozenSet[str] = field(default_factory=frozenset)


MANDATORY_AXES = frozenset({"tools", "egress_domains"})
SCHEMA_FLOOR = 3


def reconcile(bundles: list[PolicyBundle]) -> dict[str, FrozenSet[str]]:
    if not bundles:
        raise PolicyRatchetError("empty federation: no bundles to reconcile")

    # Guard 1: schema floor + mandatory-axis completeness, per bundle, before merge.
    for b in bundles:
        if b.schema_version < SCHEMA_FLOOR:
            raise PolicyRatchetError(
                f"stale peer {b.org!r}: schema_version {b.schema_version} "
                f"< floor {SCHEMA_FLOOR}; refusing to merge"
            )
        present = set(b.allow) | b.explicit_wildcard
        missing = MANDATORY_AXES - present
        if missing:
            # Absent != unconstrained. This is the ratchet's entry point.
            raise PolicyRatchetError(
                f"peer {b.org!r} omits mandatory axes {sorted(missing)}; "
                f"absence is not consent"
            )

    # Guard 2: lattice-typed meet. Allow-axes intersect, deny-axes union.
    axes = set().union(*(set(b.allow) for b in bundles))
    effective: dict[str, FrozenSet[str]] = {}
    for axis in axes:
        universe = None
        for b in bundles:
            if axis in b.explicit_wildcard:
                continue  # explicit wildcard contributes full universe
            vals = b.allow.get(axis)
            if vals is None:
                raise PolicyRatchetError(
                    f"axis {axis!r} absent in {b.org!r} mid-merge"
                )
            universe = vals if universe is None else (universe & vals)
        if universe is None:
            universe = frozenset()  # all peers wildcarded; empty after deny below
        denied: FrozenSet[str] = frozenset().union(
            *(b.deny.get(axis, frozenset()) for b in bundles)
        )
        effective[axis] = universe - denied

    # Guard 3: commutativity probe on a synthetic fixture.
    _assert_commutative(bundles)
    return effective


def _assert_commutative(bundles: list[PolicyBundle]) -> None:
    if len(bundles) < 2:
        return
    a, b = bundles[0], bundles[1]
    fwd = _meet_pair(a, b)
    rev = _meet_pair(b, a)
    if fwd != rev:
        raise PolicyRatchetError(
            f"non-commutative merge between {a.org!r} and {b.org!r}: "
            f"order-dependent grant is a ratchet signature"
        )


def _meet_pair(a: PolicyBundle, b: PolicyBundle) -> dict[str, FrozenSet[str]]:
    out: dict[str, FrozenSet[str]] = {}
    for axis in set(a.allow) & set(b.allow):
        out[axis] = a.allow[axis] & b.allow[axis]
    return out
