# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-delegation-chain-whose-aaif-warrant-scope-narrows-below-the-capability-it-was-invoked-under.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-delegation-chain-whose-aaif-warrant-scope-narrows-below-the-capability-it-was-invoked-under.warrant.json
# Markdown SHA-256:   c65e5fbc48051c662c576fec97ff3812b66c7d7962ed4e542e5ad91f1eb957c6
# Code AST SHA-256:   a739070cfed9f807003ba2e91400ddf02ef47a37b8b64dd29e837fc213954cc6
# Verified Classes:   DelegationScopeDivergence, UnparseableScopeExtension, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class DelegationScopeDivergence(RuntimeError):
    """Raised when recomputed chain scope disagrees with the presented leaf claim."""
    pass


class UnparseableScopeExtension(DelegationScopeDivergence):
    """Raised when a warrant carries a scope-bearing extension the verifier cannot interpret."""
    pass


@dataclass
class Warrant:
    issuer: str
    subject: str
    scope: frozenset[str]
    extensions: dict[str, Any] = field(default_factory=dict)
    profile: str = "aaif/1.2"


# Fields defined by the AAIF profile as scope-bearing. Anything else in
# `extensions` that claims to be scope-bearing but is not in this set must
# fail closed, because we cannot bound its effect.
SCOPE_BEARING_EXTENSIONS = {"attenuation", "scope_reduction", "deny_set"}


def recompute_effective_scope(chain: list[Warrant]) -> frozenset[str]:
    """Intersect scope across every warrant in the chain, over all recognized
    scope-bearing fields. Any unrecognized scope-bearing extension collapses
    the intersection to the empty set (fail-closed)."""
    effective: frozenset[str] | None = None
    for w in chain:
        hop = set(w.scope)
        for name, value in w.extensions.items():
            if name in SCOPE_BEARING_EXTENSIONS:
                # attenuation lists capabilities removed at this hop
                hop -= set(value)
            elif isinstance(value, dict) and value.get("scope_bearing"):
                # declares itself scope-bearing but we do not know its semantics
                raise UnparseableScopeExtension(
                    f"warrant from {w.issuer} carries unparseable "
                    f"scope-bearing extension {name!r}; refusing to bound scope"
                )
        hop_fs = frozenset(hop)
        effective = hop_fs if effective is None else (effective & hop_fs)
    return effective if effective is not None else frozenset()


def authorize_invocation(
    chain: list[Warrant],
    invoked_capability: str,
    presented_leaf_scope: frozenset[str],
) -> str:
    recomputed = recompute_effective_scope(chain)

    if recomputed != presented_leaf_scope:
        # caller's mental model diverges from the chain's true authority
        divergence = recomputed ^ presented_leaf_scope
        if invoked_capability not in recomputed:
            raise DelegationScopeDivergence(
                f"invoked {invoked_capability!r} not in recomputed scope "
                f"{sorted(recomputed)}; presented claim {sorted(presented_leaf_scope)} "
                f"diverges on {sorted(divergence)}"
            )
        return "proceed_scope_narrowed"

    if invoked_capability not in recomputed:
        raise DelegationScopeDivergence(
            f"invoked {invoked_capability!r} absent from effective scope "
            f"{sorted(recomputed)}"
        )
    return "proceed"
