# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-federated-capability-registry-diverge-from-its-peers-after-a-partition-heals-and-how-do-you-detect-it-before-routing-agents.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-federated-capability-registry-diverge-from-its-peers-after-a-partition-heals-and-how-do-you-detect-it-before-routing-agents.warrant.json
# Markdown SHA-256:   e9d551241b334533a4a6b1beeff8bcb1c1a9b93e203f7b4a158612029114ddb6
# Code AST SHA-256:   e2ef9747378234600a25e96451901537d551a1a3c15e4d418d5f52f2885f95fc
# Verified Classes:   CapabilityResurrectionError, Manifest, Registry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

"""Guard against capability resurrection in a federated registry merge.

Enforces remove-wins semantics for authority-bearing manifest fields:
a tombstone (revocation) dominates any non-tombstone write for the same
key until the origin re-creates the key with a strictly greater
authority_epoch. Advisory fields (description, tags) may still use
wall-clock last-writer-wins.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Optional


class CapabilityResurrectionError(RuntimeError):
    """Raised when a merge would re-advertise a revoked capability."""


@dataclass(frozen=True)
class Manifest:
    key: str
    version: int
    authority_epoch: int          # monotonic, incremented only by origin
    revoked: bool
    wall_clock: float             # advisory ordering only
    endpoint: Optional[str] = None
    description: str = ""


@dataclass
class Registry:
    # key -> winning manifest (authority-bearing section)
    _authority: dict[str, Manifest] = field(default_factory=dict)
    # key -> advisory fields, wall-clock LWW
    _advisory: dict[str, tuple[float, str]] = field(default_factory=dict)

    def merge(self, incoming: Manifest, *, origin_id: str) -> Manifest:
        """Merge an incoming manifest from a peer. Returns the winning view.

        Raises CapabilityResurrectionError if the merge would resurrect a
        revoked capability from a non-origin peer.
        """
        current = self._authority.get(incoming.key)

        if current is not None and current.revoked:
            # Remove-wins: only the origin may un-revoke, and only with a
            # strictly greater authority_epoch.
            if not incoming.revoked:
                if origin_id != incoming.key.split(":", 1)[0]:
                    raise CapabilityResurrectionError(
                        f"peer {origin_id!r} attempted to resurrect revoked "
                        f"capability {incoming.key!r} (epoch "
                        f"{incoming.authority_epoch} <= "
                        f"{current.authority_epoch})"
                    )
                if incoming.authority_epoch <= current.authority_epoch:
                    raise CapabilityResurrectionError(
                        f"origin {origin_id!r} re-created {incoming.key!r} "
                        f"without advancing authority_epoch "
                        f"({incoming.authority_epoch} <= "
                        f"{current.authority_epoch})"
                    )

        # Authority-bearing section: highest authority_epoch wins; ties are
        # resolved by revocation (tombstone dominates).
        if current is None or (
            incoming.authority_epoch,
            incoming.revoked,
        ) > (current.authority_epoch, current.revoked):
            self._authority[incoming.key] = incoming

        # Advisory section: wall-clock LWW is safe here (no dispatch effect).
        prev = self._advisory.get(incoming.key)
        if prev is None or incoming.wall_clock > prev[0]:
            self._advisory[incoming.key] = (
                incoming.wall_clock,
                incoming.description,
            )

        return self._authority[incoming.key]

    def authority_lag(self, key: str, origin_epoch: int) -> int:
        """Non-zero means this replica is behind the origin's authority epoch
        for the key, even if state hashes match."""
        m = self._authority.get(key)
        if m is None:
            return origin_epoch
        return max(0, origin_epoch - m.authority_epoch)


def route_agent(registry: Registry, key: str, origin_id: str) -> str:
    """Resolve a capability for dispatch; refuse if authority-lagged."""
    m = registry._authority.get(key)
    if m is None or m.revoked:
        raise CapabilityResurrectionError(
            f"capability {key!r} is absent or revoked; refusing dispatch"
        )
    if registry.authority_lag(key, m.authority_epoch) > 0:
        raise CapabilityResurrectionError(
            f"capability {key!r} is authority-lagged; refusing dispatch "
            f"to potentially stale endpoint {m.endpoint!r}"
        )
    if m.endpoint is None:
        raise CapabilityResurrectionError(
            f"capability {key!r} has no endpoint; refusing dispatch"
        )
    return m.endpoint
