# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-capability-token-whose-delegation-chain-is-length-valid-but-warrant-non-monotonic.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-capability-token-whose-delegation-chain-is-length-valid-but-warrant-non-monotonic.warrant.json
# Markdown SHA-256:   14dce6e18dd286df0c6b5da411fb758797e028e3c11610012ebbbc381f42bf56
# Code AST SHA-256:   946137203ed7c51201d5a46e4d17c1f81c1b57eb124344cb521999084ef58362
# Verified Classes:   WarrantNonMonotonicError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Mapping


class WarrantNonMonotonicError(RuntimeError):
    """Raised when a delegated token's effective warrant is not a subset of its parent's."""


@dataclass(frozen=True)
class Warrant:
    schema: str
    tools: FrozenSet[str]
    fs_globs: FrozenSet[str]
    spend_ceiling: int


# Proven non-widening normalizers. Absence of a pair => unverifiable chain.
_NORMALIZERS: Mapping[tuple, callable] = {
    ("aaif-warrant/2", "aaif-warrant/1"): lambda w: Warrant(
        schema="aaif-warrant/1",
        tools=frozenset(t for t in w.tools if t in {"search", "read"}),  # truncate, never add
        fs_globs=frozenset(g for g in w.fs_globs if g.startswith("/data/")),
        spend_ceiling=w.spend_ceiling,
    ),
}


def _normalize(child: Warrant, parent: Warrant) -> Warrant:
    if child.schema == parent.schema:
        return child
    key = (child.schema, parent.schema)
    if key not in _NORMALIZERS:
        raise WarrantNonMonotonicError(
            f"no proven non-widening normalizer for {key}; chain unverifiable"
        )
    normalized = _NORMALIZERS[key](child)
    if len(normalized.tools) > len(child.tools) or len(normalized.fs_globs) > len(child.fs_globs):
        raise WarrantNonMonotonicError(f"normalizer widened warrant under {key}")
    return normalized


def verify_edge(parent: Warrant, child: Warrant) -> None:
    eff_child = _normalize(child, parent)
    if not eff_child.tools <= parent.tools:
        raise WarrantNonMonotonicError(
            f"tool escalation: {eff_child.tools - parent.tools} not in parent"
        )
    if not eff_child.fs_globs <= parent.fs_globs:
        raise WarrantNonMonotonicError(
            f"fs escalation: {eff_child.fs_globs - parent.fs_globs} not in parent"
        )
    if eff_child.spend_ceiling > parent.spend_ceiling:
        raise WarrantNonMonotonicError(
            f"spend escalation: {eff_child.spend_ceiling} > {parent.spend_ceiling}"
        )


def verify_chain(chain: list[Warrant]) -> None:
    for parent, child in zip(chain, chain[1:]):
        verify_edge(parent, child)
