# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-trust-brokered-capability-grant-when-the-broker-s-warrant-chain-exceeds-the-delegated-scope-of-the-origina.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-trust-brokered-capability-grant-when-the-broker-s-warrant-chain-exceeds-the-delegated-scope-of-the-origina.warrant.json
# Markdown SHA-256:   560e66f53848fda2d99424d265687731e1cb4b1c60e334e1e108debcb43c0f3f
# Code AST SHA-256:   8a9ed375ca62012988d9dec8e67c1fd2b6370a7e132479ccb97aba52c9d518da
# Verified Classes:   WarrantScopeUnverifiable, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class WarrantScopeUnverifiable(RuntimeError):
    """Raised when a leaf cannot prove scope containment against the root principal."""


@dataclass
class Warrant:
    issuer: str
    subject: str
    capability: str
    resource: str
    constraints: dict
    norm_version: str
    signature_valid: bool


def _denote(w: Warrant, normalize: Callable[[str, dict], frozenset]) -> frozenset:
    try:
        return normalize(w.resource, w.constraints)
    except KeyError as e:
        # Unknown constraint token: unbounded, not ignorable.
        raise WarrantScopeUnverifiable(
            f"unknown constraint token {e} in warrant from {w.issuer}"
        )


def verify_chain(chain: list[Warrant], normalize: Callable[[str, dict], frozenset]) -> None:
    if not chain:
        raise WarrantScopeUnverifiable("empty warrant chain")

    root, leaf = chain[0], chain[-1]

    for w in chain:
        if not w.signature_valid:
            raise WarrantScopeUnverifiable(f"invalid signature at hop {w.issuer}")
        if w.norm_version != root.norm_version:
            raise WarrantScopeUnverifiable(
                f"normalization mismatch: {w.issuer}={w.norm_version} root={root.norm_version}"
            )

    root_den = _denote(root, normalize)
    leaf_den = _denote(leaf, normalize)

    # Direct containment against ROOT, not immediate parent:
    # subset is transitive only if all parsers agree, which we do not assume.
    if not leaf_den.issubset(root_den):
        escaped = leaf_den - root_den
        raise WarrantScopeUnverifiable(
            f"scope amplification: leaf exceeds root by {sorted(escaped)[:5]}"
        )


def execute_capability(chain: list[Warrant], requested_path: str,
                       normalize: Callable[[str, dict], frozenset],
                       normalize_path: Callable[[str], str]) -> str:
    verify_chain(chain, normalize)
    # Normalize BEFORE constraint check, and consume the normalized form.
    resolved = normalize_path(requested_path)
    leaf_den = _denote(chain[-1], normalize)
    if resolved not in leaf_den:
        raise WarrantScopeUnverifiable(
            f"resolved path {resolved} not in leaf denotation"
        )
    return resolved
