# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-a2a-capability-warrant-whose-scope-chain-has-silently-widened-at-a-federation-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-delegated-a2a-capability-warrant-whose-scope-chain-has-silently-widened-at-a-federation-hop.warrant.json
# Markdown SHA-256:   910b788c5fcaa4cc8f78908d3ef2ac37f669e7acb0bac29e8610d1a2682c117d
# Code AST SHA-256:   7b778d79353f41d73fc0a2860fd47ee39976248ecf71435f31f3b01a51c2e455
# Verified Classes:   WarrantWideningError, Hop
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class WarrantWideningError(RuntimeError):
    """Raised when a delegated A2A warrant's transitive scope intersection
    exceeds the originator's root scope, even though every adjacent
    pairwise subset check passed and all signatures verified."""


@dataclass(frozen=True)
class Hop:
    index: int
    scope: frozenset[str]
    signature_valid: bool


def verify_delegation_chain(chain: list[Hop], root_scope: frozenset[str]) -> frozenset[str]:
    if not chain:
        raise WarrantWideningError("empty warrant chain: cannot recover root scope")

    # 1. Every hop must attest; a truncated chain has undefined intersection.
    for expected, hop in enumerate(chain):
        if hop.index != expected:
            raise WarrantWideningError(
                f"hop attestation missing at index {expected}; chain is truncated"
            )
        if not hop.signature_valid:
            raise WarrantWideningError(f"hop {hop.index} signature invalid")

    # 2. Pairwise subset: necessary, NOT sufficient.
    for prev, cur in zip(chain, chain[1:]):
        if not cur.scope.issubset(prev.scope):
            raise WarrantWideningError(
                f"hop {cur.index} scope is not a subset of hop {prev.index}"
            )

    # 3. Transitive intersection must equal the root scope.
    transitive = frozenset.intersection(*(hop.scope for hop in chain))
    if transitive != root_scope:
        widened = transitive - root_scope
        culprit = next(
            (hop.index for hop in chain if not hop.scope.issubset(root_scope)),
            None,
        )
        raise WarrantWideningError(
            f"transitive intersection widened at hop {culprit}: "
            f"unauthorized resources {sorted(widened)}"
        )

    return transitive
