# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-after-a-trust-broker-rotation-the-warrant-lineage-gap-in-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-after-a-trust-broker-rotation-the-warrant-lineage-gap-in-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   59d5b8f9e21e9aa16df90d5c7056a9ebd7ed6daf19619f461e2e0f6f34f90f13
# Code AST SHA-256:   f62fbcafce126aa8e7ca59b616a0fb1cf43c8aca5a2c8c8ad467c601604d1d00
# Verified Classes:   ChainUnanchoredError, AnchorVerdict, WarrantChain
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class ChainUnanchoredError(RuntimeError):
    """Raised when a delegation chain cannot be anchored under any live epoch."""


class AnchorVerdict(Enum):
    ANCHORED = "anchored"
    ROTATED_REPAIRABLE = "rotated_repairable"
    ROTATED_UNREPAIRABLE = "rotated_unrepairable"


@dataclass(frozen=True)
class WarrantChain:
    leaf_id: str
    # anchor_epoch of every link, leaf-first
    link_epochs: tuple
    delegator_has_broker_channel: bool


def classify_chain(
    chain: WarrantChain,
    live_anchor_epochs: FrozenSet[int],
    known_retired_epochs: FrozenSet[int],
) -> AnchorVerdict:
    if not chain.link_epochs:
        raise ChainUnanchoredError(
            f"warrant {chain.leaf_id} has empty delegation chain"
        )

    # Invariant: every link must share one anchor epoch.
    if len(set(chain.link_epochs)) != 1:
        raise ChainUnanchoredError(
            f"warrant {chain.leaf_id} spans multiple anchor epochs "
            f"{sorted(set(chain.link_epochs))}; chain is not single-anchored"
        )

    epoch = chain.link_epochs[0]

    if epoch in live_anchor_epochs:
        return AnchorVerdict.ANCHORED

    if epoch in known_retired_epochs:
        if chain.delegator_has_broker_channel:
            return AnchorVerdict.ROTATED_REPAIRABLE
        return AnchorVerdict.ROTATED_UNREPAIRABLE

    # Epoch is neither live nor known-retired: metadata sync incomplete.
    raise ChainUnanchoredError(
        f"warrant {chain.leaf_id} anchors at unknown epoch {epoch}; "
        f"live={sorted(live_anchor_epochs)} retired={sorted(known_retired_epochs)}"
    )


def dispatch_tool_call(
    chain: WarrantChain,
    live_anchor_epochs: FrozenSet[int],
    known_retired_epochs: FrozenSet[int],
    repair_attempts: int,
    max_repair_attempts: int = 2,
) -> str:
    verdict = classify_chain(chain, live_anchor_epochs, known_retired_epochs)

    if verdict is AnchorVerdict.ANCHORED:
        return "proceed"

    if verdict is AnchorVerdict.ROTATED_REPAIRABLE:
        if repair_attempts >= max_repair_attempts:
            raise ChainUnanchoredError(
                f"warrant {chain.leaf_id}: repair budget exhausted "
                f"({repair_attempts}/{max_repair_attempts}) at epoch "
                f"{chain.link_epochs[0]}"
            )
        return "repair:invalidate_grant_and_rederive_root"

    # ROTATED_UNREPAIRABLE
    raise ChainUnanchoredError(
        f"warrant {chain.leaf_id}: chain anchored at retired epoch "
        f"{chain.link_epochs[0]} with no broker channel; abort to orchestrator"
    )
