# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-scope-narrowing-forgery-in-delegated-aaif-credential-chains-before-executing-a-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-scope-narrowing-forgery-in-delegated-aaif-credential-chains-before-executing-a-tool-call.warrant.json
# Markdown SHA-256:   cedef8e3a8a5e598411f9458f0f28b43e7f8eb24f9bca47445cd458fe48620df
# Code AST SHA-256:   c58ad1a066089e8b615202e180e838d64b94e1e43f81b19026cc766841aadc8b
# Verified Classes:   ScopeWideningError, ChainResolutionError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping

class ScopeWideningError(RuntimeError):
    """Raised when a delegated warrant claims a scope not contained in its parent's effective scope."""

class ChainResolutionError(RuntimeError):
    """Raised when an ancestor warrant cannot be resolved to a signature-verified body."""

@dataclass(frozen=True)
class Warrant:
    subject: str
    scopes: frozenset[str]
    parent_attestation: str | None
    body_digest: str

def effective_scope(chain: list[Warrant]) -> frozenset[str]:
    """Chain is ordered leaf-first. Returns intersection of all warrant scopes."""
    if not chain:
        raise ChainResolutionError("empty warrant chain")
    effective = chain[0].scopes
    for child, parent in zip(chain, chain[1:]):
        if child.parent_attestation != parent.body_digest:
            raise ChainResolutionError(
                f"attestation mismatch: {child.subject} -> {parent.subject}"
            )
        if not child.scopes <= parent.scopes:
            raise ScopeWideningError(
                f"{child.subject} claims {sorted(child.scopes - parent.scopes)} "
                f"not delegated by {parent.subject}"
            )
        effective &= parent.scopes
    return effective

def authorize_tool_call(chain: list[Warrant], required: frozenset[str]) -> None:
    effective = effective_scope(chain)
    if not required <= effective:
        raise ScopeWideningError(
            f"tool requires {sorted(required - effective)} beyond effective scope"
        )
    # proceed to emit the tool call
