# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-delegated-aaif-warrant-whose-chain-contains-an-unverifiable-epoch-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-honor-a-delegated-aaif-warrant-whose-chain-contains-an-unverifiable-epoch-boundary.warrant.json
# Markdown SHA-256:   0a1a5a788f097b974505117b876216fe1dc63364cca17ebf79790af2b2a32291
# Code AST SHA-256:   d45976d9593edcc61b3b86d1aaffaf9219a03237e6e3125703a19768f729d41f
# Verified Classes:   AuthorityOrphanError, Epoch, Link
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AuthorityOrphanError(RuntimeError):
    """Raised when a warrant link's signing epoch no longer holds the authority it delegated."""


@dataclass(frozen=True)
class Epoch:
    delegator: str
    version: int
    granted_scope: frozenset


@dataclass(frozen=True)
class Link:
    delegator: str
    signer_epoch: int
    delegated_scope: frozenset
    signature_valid: bool


def verify_chain(links: list[Link], truststore: dict[str, dict[int, Epoch]]) -> None:
    """Two-pass AAIF chain verification: signatures, then epoch-authority containment."""
    # Pass 1: cryptographic and attenuation checks.
    prev_scope: Optional[frozenset] = None
    for link in links:
        if not link.signature_valid:
            raise AuthorityOrphanError(
                f"signature invalid on link from {link.delegator}@{link.signer_epoch}"
            )
        if prev_scope is not None and not link.delegated_scope <= prev_scope:
            raise AuthorityOrphanError(
                f"scope escalation on link from {link.delegator}@{link.signer_epoch}"
            )
        prev_scope = link.delegated_scope

    # Pass 2: epoch-authority containment. This is the pass most verifiers omit.
    for link in links:
        epochs = truststore.get(link.delegator)
        if not epochs:
            raise AuthorityOrphanError(
                f"delegator {link.delegator} unknown to trust store"
            )
        signing_epoch = epochs.get(link.signer_epoch)
        if signing_epoch is None:
            raise AuthorityOrphanError(
                f"epoch {link.delegator}@{link.signer_epoch} not resolvable; fail-closed"
            )
        current = max(epochs.values(), key=lambda e: e.version)
        if current.version > link.signer_epoch:
            # A transition occurred. Honor only if it was additive for this scope.
            if not link.delegated_scope <= current.granted_scope:
                raise AuthorityOrphanError(
                    f"authority-orphaned link: {link.delegator}@{link.signer_epoch} "
                    f"delegated {sorted(link.delegated_scope)} but "
                    f"{link.delegator}@{current.version} holds only "
                    f"{sorted(current.granted_scope)}; re-attestation required"
                )
        elif current.version < link.signer_epoch:
            raise AuthorityOrphanError(
                f"future epoch {link.delegator}@{link.signer_epoch} exceeds "
                f"trust store head {current.version}; cannot vouch"
            )


def invoke_tool(chain: list[Link], truststore: dict[str, dict[int, Epoch]], tool: str) -> str:
    verify_chain(chain, truststore)
    return f"executed {tool}"
