# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-brokered-capability-token-whose-issuer-chain-re-enters-its-own-trust-domain.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-brokered-capability-token-whose-issuer-chain-re-enters-its-own-trust-domain.warrant.json
# Markdown SHA-256:   a78416402a9cb16531d4cbd8cb51d88b82b6b5a1666f4e085cf20072279f48eb
# Code AST SHA-256:   a9d6c1bcd947024debbe2602e283fe5007d957121142ad95d201b9ba8c6f7620
# Verified Classes:   ReentrantChainViolation, Link
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, List, Optional


class ReentrantChainViolation(RuntimeError):
    """Raised when a brokered capability chain re-enters the verifier's trust domain
    without a fresh epoch attestation and without monotonic capability narrowing."""


@dataclass(frozen=True)
class Link:
    issuer: str
    subject: str
    domain: str
    capabilities: FrozenSet[str]
    epoch: int


def verify_chain(
    chain: List[Link],
    verifier_domain: str,
    root_capabilities: FrozenSet[str],
    current_epoch: int,
    epoch_attestation: Optional[int] = None,
) -> FrozenSet[str]:
    if not chain:
        raise ReentrantChainViolation("empty capability chain")
    if len(chain) == 1:
        return chain[0].capabilities

    terminal = chain[-1]
    composed = chain[0].capabilities
    for link in chain[1:]:
        composed = composed & link.capabilities

    reenters = terminal.domain == verifier_domain
    if reenters:
        has_fresh_attestation = (
            epoch_attestation is not None and epoch_attestation > chain[0].epoch
        )
        widened = not composed.issubset(root_capabilities)
        if widened and not has_fresh_attestation:
            raise ReentrantChainViolation(
                f"chain re-enters domain {verifier_domain} at hop {len(chain) - 1} "
                f"with widened capability set {sorted(composed - root_capabilities)} "
                f"and no epoch attestation fresher than root epoch {chain[0].epoch}"
            )
        if has_fresh_attestation and epoch_attestation < current_epoch:
            raise ReentrantChainViolation(
                f"epoch attestation {epoch_attestation} predates current epoch "
                f"{current_epoch}; stale re-entry proof"
            )
    return composed
