# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-cross-org-agent-federation-deadlock-when-trust-score-routing-and-policy-negotiated-capability-exchange-are-applied-to-a-mutual.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-cross-org-agent-federation-deadlock-when-trust-score-routing-and-policy-negotiated-capability-exchange-are-applied-to-a-mutual.warrant.json
# Markdown SHA-256:   2e3df59b9d8b0c31fe695d0db41def285910a734c4650006f07baa14c54dd2af
# Code AST SHA-256:   151cbf39d5df427708f0fb4a8f3abbe55fa8892aa6e742b7fae148e947c209be
# Verified Classes:   FederationCycleError, FederationPolicy
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class FederationCycleError(RuntimeError):
    """Raised when the admission predicate graph contains a cycle.

    A cycle exists when admitting a request requires a trust score that can
    only be raised by completing that same request. This is the cold-start
    deadlock described in the record above; it must be detected at
    configuration time, never at request time.
    """


@dataclass(frozen=True)
class FederationPolicy:
    trust_threshold: float
    init_trust: float
    negotiation_exempt_from_trust_gate: bool
    trust_seeded_from_attestation: bool
    manifests_exchanged_at_join: bool
    # Edges in the admission dependency graph: (request_class -> required_predicate)
    admission_edges: tuple[tuple[str, str], ...] = field(default_factory=tuple)


def _reachable(edges: tuple[tuple[str, str], ...], start: str) -> set[str]:
    seen: set[str] = set()
    frontier = [start]
    while frontier:
        node = frontier.pop()
        for src, dst in edges:
            if src == node and dst not in seen:
                seen.add(dst)
                frontier.append(dst)
    return seen


def validate_federation_policy(policy: FederationPolicy) -> None:
    """Reject policies whose admission graph closes the cold-start cycle.

    The cycle is: admit(negotiate) -> trust -> successful_exchange -> admit(negotiate).
    Any policy that re-introduces this edge without a declared break point is
    rejected. This function is the enforcement of the decision boundary.
    """
    # A policy is safe iff at least one of the four cycle-break conditions holds.
    breaks = (
        policy.negotiation_exempt_from_trust_gate,          # breaks C1
        policy.trust_seeded_from_attestation,               # breaks C2
        policy.manifests_exchanged_at_join,                 # breaks C3
        policy.trust_threshold <= policy.init_trust,        # degenerate but safe
    )
    if any(breaks):
        return

    # No break point declared: check whether the graph actually closes the cycle.
    cycle_edges = policy.admission_edges
    if "negotiate" in _reachable(cycle_edges, "admit_negotiate"):
        raise FederationCycleError(
            "Admission graph contains the cold-start deadlock cycle: "
            "admit(negotiate) -> trust -> successful_exchange -> admit(negotiate). "
            f"trust_threshold={policy.trust_threshold} > init_trust={policy.init_trust}, "
            "negotiation is trust-gated, trust is history-derived, and manifests are "
            "not exchanged at join. Declare exactly one cycle-break: exempt "
            "negotiation from the trust gate, seed trust from attestation, or "
            "exchange manifests at join. Do NOT lower the threshold globally."
        )


def admit_request(policy: FederationPolicy, request_class: str, peer_trust: float) -> bool:
    """Admission gate. Negotiation traffic is exempt iff the policy declares it."""
    if request_class == "negotiate" and policy.negotiation_exempt_from_trust_gate:
        return True
    if peer_trust < policy.trust_threshold:
        # Note: this rejection is the silent drop that hides the deadlock.
        # It must be logged at the admission layer, not the broker layer.
        return False
    return True


# Example: a policy that re-introduces the deadlock is rejected at config time.
bad_policy = FederationPolicy(
    trust_threshold=0.6,
    init_trust=0.0,
    negotiation_exempt_from_trust_gate=False,
    trust_seeded_from_attestation=False,
    manifests_exchanged_at_join=False,
    admission_edges=(
        ("admit_negotiate", "trust"),
        ("trust", "successful_exchange"),
        ("successful_exchange", "admit_negotiate"),
    ),
)

validate_federation_policy(bad_policy)  # raises FederationCycleError
