# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-an-over-broad-delegation-grant-when-an-aaif-credential-chain-is-valid-at-every-hop-but-the-effective-scope-silently-widens.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-an-over-broad-delegation-grant-when-an-aaif-credential-chain-is-valid-at-every-hop-but-the-effective-scope-silently-widens.warrant.json
# Markdown SHA-256:   28bf585ae8806b82f3ba44b49d35b8ea9c7f8f3312dbe28624a4c3e264e4ead1
# Code AST SHA-256:   7d89bb242cbdf3482f11e29a624741fa178f1049bdca06310bb221f6626039ac
# Verified Classes:   ScopeWideningError, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a delegation chain's terminal scope exceeds the running intersection."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    delegate: str
    scope: FrozenSet[str]


def verify_chain(chain: list[Warrant], requested_op: str) -> FrozenSet[str]:
    if not chain:
        raise ScopeWideningError("empty delegation chain")

    # Running intersection starts at the root issuer's grant.
    effective = chain[0].scope

    for i, w in enumerate(chain):
        if i > 0:
            prev = chain[i - 1]
            if not w.scope.issubset(prev.scope):
                # The issuer emitted a grant broader than it held.
                raise ScopeWideningError(
                    f"hop {i}: {w.issuer} granted {sorted(w.scope - prev.scope)} "
                    f"which it does not hold (held {sorted(prev.scope)})"
                )
        effective = effective & w.scope

    if requested_op not in effective:
        raise ScopeWideningError(
            f"operation {requested_op!r} not in effective scope "
            f"{sorted(effective)}; terminal warrant advertised it but "
            f"intersection across chain excludes it"
        )
    return effective


# Observed failing chain: P widens beyond its own grant.
chain = [
    Warrant("O", "P", frozenset({"read:repo", "write:repo"})),
    Warrant("P", "E", frozenset({"read:repo", "write:repo", "deploy:staging"})),
]

try:
    verify_chain(chain, "deploy:staging")
except ScopeWideningError as e:
    print(f"DENIED: {e}")
