# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-delegation-chain-when-every-signature-in-an-aaif-warrant-verifies-but-the-authorization-scope-silently-widened.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-broken-delegation-chain-when-every-signature-in-an-aaif-warrant-verifies-but-the-authorization-scope-silently-widened.warrant.json
# Markdown SHA-256:   1b6d65b7ca0aa8560d9b2f53ea255a82477faacad203d50f597e9b53716ca8a1
# Code AST SHA-256:   b4d0d9cb30ddd42367a19cb4db552031d3551a4f8d3ed5a35542a29e8215803a
# Verified Classes:   DelegationScopeWidening, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class DelegationScopeWidening(RuntimeError):
    """Raised when a delegated warrant's declared scope exceeds the
    effective (running-intersection) scope of its parent hop."""


@dataclass
class Warrant:
    hop_index: int
    declared_scope: frozenset
    parent_hash: str
    signature_valid: bool = True


def verify_chain(chain: list[Warrant], policy_required: frozenset) -> frozenset:
    """Recompute effective scope top-down; reject on any widening.

    Returns the leaf's effective scope on success. Raises
    DelegationScopeWidening if any hop's declared scope is not a subset
    of the running effective scope, or if the leaf's effective scope
    does not satisfy the verifier's policy.
    """
    if not chain:
        raise DelegationScopeWidening("empty delegation chain")

    effective = chain[0].declared_scope
    if not chain[0].signature_valid:
        raise DelegationScopeWidening("root signature invalid")

    for hop in chain[1:]:
        if not hop.signature_valid:
            raise DelegationScopeWidening(
                f"hop {hop.hop_index}: signature invalid"
            )
        extra = hop.declared_scope - effective
        if extra:
            # Do NOT fall back to root scope. Ancestor presence is not
            # authorization; it is the laundering signal.
            raise DelegationScopeWidening(
                f"hop {hop.hop_index}: declared scope widens effective "
                f"scope by {sorted(extra)}; parent effective scope was "
                f"{sorted(effective)}"
            )
        effective = effective & hop.declared_scope

    missing = policy_required - effective
    if missing:
        raise DelegationScopeWidening(
            f"leaf effective scope {sorted(effective)} does not satisfy "
            f"verifier policy; missing {sorted(missing)}"
        )
    return effective


# Reproduction of the observed failure: B narrows, C re-widens to root.
root = Warrant(0, frozenset({"read:repo", "write:branch:feature/*", "invoke:ci-runner"}), "genesis")
auditor = Warrant(1, frozenset({"read:repo", "invoke:ci-runner"}), "hash(root)")
child = Warrant(2, frozenset({"read:repo", "write:branch:feature/*", "invoke:ci-runner"}), "hash(auditor)")

try:
    verify_chain([root, auditor, child], frozenset({"read:repo"}))
except DelegationScopeWidening as e:
    print(f"rejected as expected: {e}")
