# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-capability-scopes-when-a-verifiable-credential-s-attenuation-chain-is-valid-at-issuance-but-its-scope-latti.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-capability-scopes-when-a-verifiable-credential-s-attenuation-chain-is-valid-at-issuance-but-its-scope-latti.warrant.json
# Markdown SHA-256:   ae589d5e01c2e347e18d16434631bc31c6081f82d6dc97f42f87a6d1d5d057c2
# Code AST SHA-256:   af68e360e941a3e344a058c77d87b98f1c8305e969e10a447a80a92f7875f9f1
# Verified Classes:   ScopeLatticeCollapseError, Scope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, FrozenSet


class ScopeLatticeCollapseError(RuntimeError):
    """Raised when a delegated capability chain is cryptographically valid
    but its composed denotation exceeds the root grant."""


@dataclass(frozen=True)
class Scope:
    raw: str
    denotation: FrozenSet[tuple]  # (action, resolved_resource) pairs


def verify_delegation_chain(
    chain: list[Scope],
    enforce: Callable[[tuple], bool],
    root_denotation: FrozenSet[tuple],
) -> Scope:
    """Validate a transitive delegation chain under the denotational invariant.

    chain[0] is the root grant; chain[-1] is the leaf the instance will use.
    """
    if not chain:
        raise ScopeLatticeCollapseError("empty delegation chain")

    # 1. Per-hop denotational subset check (NOT string-prefix).
    for i in range(len(chain) - 1):
        parent, child = chain[i], chain[i + 1]
        if not child.denotation.issubset(parent.denotation):
            raise ScopeLatticeCollapseError(
                f"hop {i}->{i+1}: child denotation exceeds parent "
                f"({child.raw!r} not subset of {parent.raw!r})"
            )

    # 2. Compositional closure: the composed grant must stay within root.
    composed = chain[-1].denotation
    if not composed.issubset(root_denotation):
        leaked = composed - root_denotation
        raise ScopeLatticeCollapseError(
            f"composed grant exceeds root denotation; leaked={sorted(leaked)[:5]}"
        )

    # 3. Enforcement-point agreement: every authorized pair must actually
    #    be admitted by the enforcer, and nothing outside the grant may be.
    for pair in composed:
        if not enforce(pair):
            raise ScopeLatticeCollapseError(
                f"enforcer rejects pair {pair} that the chain authorizes; "
                "verifier/enforcer resource models disagree"
            )

    return chain[-1]
