# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-s-delegated-warrant-when-the-trust-anchor-chain-re-anchors-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-federated-peer-s-delegated-warrant-when-the-trust-anchor-chain-re-anchors-mid-handoff.warrant.json
# Markdown SHA-256:   56aab1bc119e312400157cd1a531349a42d4a5bdabc50e7932a2eacd6d5d5386
# Code AST SHA-256:   8c71fdfb3acf517b14989ef9acb5c45de4989ec698890dc5d6f2e4a994f628ee
# Verified Classes:   EpochState, EpochContiguityError, Link, WarrantChain
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class EpochState(Enum):
    ACTIVE = "active"
    RETIRING = "retiring"
    UNKNOWN = "unknown"


class EpochContiguityError(RuntimeError):
    """Raised when a delegated warrant chain is not epoch-homogeneous at verification time."""
    pass


@dataclass
class Link:
    issuer: str
    subject: str
    epoch: str
    scope: str


@dataclass
class WarrantChain:
    links: list[Link]
    cross_signed_overlap: Optional[Link] = None


def verify_epoch_contiguity(
    chain: WarrantChain,
    trust_store: dict[str, EpochState],
) -> None:
    """
    Enforce the epoch-contiguity invariant across a delegated warrant chain.
    Rejects heterogeneous chains, retiring/unknown epochs, and broken derivations.
    """
    if not chain.links:
        raise EpochContiguityError("empty warrant chain: no derivable authority")

    epochs = {link.epoch for link in chain.links}
    if len(epochs) > 1:
        # Heterogeneous chain: only acceptable if a cross-signed overlap covers the full scope.
        if chain.cross_signed_overlap is None:
            raise EpochContiguityError(
                f"epoch-heterogeneous chain {sorted(epochs)} with no cross-signed overlap; "
                f"reject and renegotiate, do not continue on surviving leaf"
            )
        overlap_scope = chain.cross_signed_overlap.scope
        for link in chain.links:
            if link.scope != overlap_scope:
                raise EpochContiguityError(
                    f"cross-signed overlap scope {overlap_scope!r} does not cover "
                    f"link scope {link.scope!r}"
                )

    for link in chain.links:
        state = trust_store.get(link.epoch, EpochState.UNKNOWN)
        if state is not EpochState.ACTIVE:
            raise EpochContiguityError(
                f"link {link.issuer}->{link.subject} anchored to epoch {link.epoch!r} "
                f"in state {state.value}; a valid leaf under a non-active parent "
                f"is a trust-widening hazard, not a degraded credential"
            )


def attempt_handoff(
    chain: WarrantChain,
    trust_store: dict[str, EpochState],
    pending_scope: str,
) -> bool:
    verify_epoch_contiguity(chain, trust_store)
    leaf = chain.links[-1]
    if not leaf.scope.startswith(pending_scope.split(":")[0]):
        raise EpochContiguityError(
            f"leaf scope {leaf.scope!r} does not authorize pending operation {pending_scope!r}"
        )
    return True


# Replay of the observed failure: re-anchor mid-handoff, v3 retiring, v4 propagated to peer only.
trust_store = {"acme-v3": EpochState.RETIRING, "acme-v4": EpochState.UNKNOWN}
chain = WarrantChain(
    links=[
        Link("planner", "executor", "acme-v3", "write:ledger"),
        Link("executor", "worker-7", "acme-v4", "write:ledger"),
    ],
    cross_signed_overlap=None,
)
attempt_handoff(chain, trust_store, "write:ledger")  # raises EpochContiguityError
