# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-the-aaif-delegation-chain-scope-narrowing-drift-that-silently-grants-over-broad-authority-after-a-credential-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-the-aaif-delegation-chain-scope-narrowing-drift-that-silently-grants-over-broad-authority-after-a-credential-refresh.warrant.json
# Markdown SHA-256:   d8bfcce9dcc7ed330ecb1d8ddfb50c2e5f19092c6e0f8dd32efd7a243c5f6ee9
# Code AST SHA-256:   46680aa68508ddab019cab2b986a9611cc615d63c7f72ebfb5ac3bf89533705a
# Verified Classes:   DelegationScopeViolation, Credential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class DelegationScopeViolation(RuntimeError):
    """Raised when a presented credential's scope exceeds the live effective scope of its ancestor chain."""


@dataclass(frozen=True)
class Credential:
    agent_id: str
    scopes: FrozenSet[str]
    parent_scope_hash: str          # provenance commitment to parent state at mint time
    revoked: bool = False
    superseded: bool = False


def resolve_live_ancestors(leaf: Credential, chain: list[Credential]) -> list[Credential]:
    """Resolve the ancestor chain to live (non-revoked, non-superseded) state.

    chain is ordered root-first, ending with the leaf's direct parent.
    """
    live = []
    for cred in chain:
        if cred.revoked or cred.superseded:
            raise DelegationScopeViolation(
                f"ancestor {cred.agent_id} is revoked/superseded; descendant subtree invalid"
            )
        live.append(cred)
    return live


def verify_presented_scope(leaf: Credential, chain: list[Credential]) -> None:
    """Enforce that leaf.scopes is a subset of the intersection of live ancestor scopes.

    The parent_scope_hash is checked separately as a provenance commitment; it is NOT
    used as the authority source. Authority comes only from the live intersection.
    """
    live = resolve_live_ancestors(leaf, chain)
    if not live:
        raise DelegationScopeViolation(f"leaf {leaf.agent_id} has no resolvable ancestor chain")

    effective = frozenset.intersection(*(c.scopes for c in live))
    excess = leaf.scopes - effective
    if excess:
        raise DelegationScopeViolation(
            f"leaf {leaf.agent_id} presents scopes {sorted(excess)} not held by live ancestor "
            f"intersection {sorted(effective)}; parent_scope_hash matched a stale snapshot"
        )


# Reproduction of the observed failure:
root = Credential("A", frozenset({"read:repo"}), parent_scope_hash="", superseded=True)  # trimmed at T0+15m
mid  = Credential("B", frozenset({"read:repo"}), parent_scope_hash="h_A_old")
leaf = Credential("C", frozenset({"write:repo"}), parent_scope_hash="h_B_old")  # minted at T0+2m, never re-issued

try:
    verify_presented_scope(leaf, [root, mid])
except DelegationScopeViolation as exc:
    print(f"BLOCKED: {exc}")
