# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-refuse-a-delegated-capability-token-whose-attestation-chain-was-re-anchored-across-a-vendor-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-refuse-a-delegated-capability-token-whose-attestation-chain-was-re-anchored-across-a-vendor-boundary.warrant.json
# Markdown SHA-256:   71c5b60b86645742a96d6faaead00ee291c0a750e18ee9389fee456ee50e5011
# Code AST SHA-256:   f57e03968fbe7795136d5dae476c0810373141509bdcf3fd2c9f9fdcedf472fa
# Verified Classes:   AttestationReAnchorViolation, Hop
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Mapping

class AttestationReAnchorViolation(RuntimeError):
    """Raised when a cross-vendor re-anchor edge widens scope or resets depth."""
    pass

@dataclass(frozen=True)
class Hop:
    issuer: str
    scope: frozenset[str]
    depth: int
    re_anchor_warrant: str | None  # signed by previous issuer; None on first hop

def verify_chain(
    chain: list[Hop],
    trusted_roots: set[str],
    vocab_map: Mapping[tuple[str, str], Callable[[frozenset[str]], frozenset[str]]],
) -> tuple[frozenset[str], int]:
    if not chain:
        raise AttestationReAnchorViolation("empty attestation chain")
    if chain[-1].issuer not in trusted_roots:
        raise AttestationReAnchorViolation(
            f"chain terminates at untrusted root {chain[-1].issuer!r}"
        )

    effective_scope = chain[0].scope
    effective_depth = chain[0].depth

    for prev, cur in zip(chain, chain[1:]):
        edge = (prev.issuer, cur.issuer)
        if cur.re_anchor_warrant is None:
            # first hop is warrantless by definition; any later hop is not
            if prev is not chain[0]:
                raise AttestationReAnchorViolation(
                    f"re-anchor edge {edge} lacks a warrant from {prev.issuer!r}"
                )
        mapper = vocab_map.get(edge)
        if mapper is None:
            raise AttestationReAnchorViolation(
                f"no declared vocabulary map for re-anchor edge {edge}"
            )
        mapped_prev = mapper(prev.scope)
        if not cur.scope <= mapped_prev:
            widened = cur.scope - mapped_prev
            raise AttestationReAnchorViolation(
                f"scope widened across {edge}: unpermitted claims {sorted(widened)}"
            )
        if cur.depth > prev.depth - 1:
            raise AttestationReAnchorViolation(
                f"delegation depth reset across {edge}: "
                f"{prev.depth} -> {cur.depth} (must decrement by >= 1)"
            )
        effective_scope = effective_scope & cur.scope
        effective_depth = min(effective_depth, cur.depth)

    return effective_scope, effective_depth
