# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-a-delegated-aaif-credential-chain-when-scope-narrowing-is-non-monotonic-across-a-re-delegation-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-a-delegated-aaif-credential-chain-when-scope-narrowing-is-non-monotonic-across-a-re-delegation-hop.warrant.json
# Markdown SHA-256:   ad4cacf14538d0d359df36e8380f1c5d3c6f67b771d377b34c679966bc66612d
# Code AST SHA-256:   2a20a4678c6dcdce5d4301bd8cc5a5d5b73c11969198100576b248e39a2494b8
# Verified Classes:   NonMonotonicDelegationError, ScopedToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Sequence


class NonMonotonicDelegationError(RuntimeError):
    """Raised when a child predicate cannot be proven to imply its parent's."""


@dataclass(frozen=True)
class ScopedToken:
    scope_ids: frozenset[str]
    predicate: Callable[[str], bool]
    predicate_repr: str


def mint_child(
    parent: ScopedToken,
    child_scope_ids: frozenset[str],
    child_predicate: Callable[[str], bool],
    child_predicate_repr: str,
    implication_prover: Callable[[str, str], bool] | None,
) -> ScopedToken:
    # Fast pre-filter: vocabulary containment. Necessary, not sufficient.
    if not child_scope_ids <= parent.scope_ids:
        raise NonMonotonicDelegationError(
            f"scope vocabulary escape: {child_scope_ids - parent.scope_ids}"
        )
    # Predicate narrowing must be proven, never asserted.
    if implication_prover is None:
        raise NonMonotonicDelegationError(
            "no implication prover available; refusing to mint unproven narrowing"
        )
    if not implication_prover(child_predicate_repr, parent.predicate_repr):
        raise NonMonotonicDelegationError(
            f"child predicate {child_predicate_repr!r} does not imply "
            f"parent predicate {parent.predicate_repr!r}"
        )
    return ScopedToken(child_scope_ids, child_predicate, child_predicate_repr)


def authorize(chain: Sequence[ScopedToken], resource: str) -> bool:
    # Fold: request must satisfy every hop's predicate, not just the leaf.
    for i, token in enumerate(chain):
        if resource not in token.scope_ids and not any(
            s.startswith("read:") for s in token.scope_ids
        ):
            return False
        if not token.predicate(resource):
            raise NonMonotonicDelegationError(
                f"request {resource!r} violates predicate at hop {i}: "
                f"{token.predicate_repr!r}"
            )
    return True
