# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-warrant-whose-chain-re-verifies-but-whose-attenuation-steps-are-non-monotonic-across-a.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-warrant-whose-chain-re-verifies-but-whose-attenuation-steps-are-non-monotonic-across-a.warrant.json
# Markdown SHA-256:   ea93956239dd4696a39ed5d4a1d5f981e5072fae27993724c37e7813b738ad4a
# Code AST SHA-256:   153291b9e6223c693b890e929780422077589bfff2843f1c404aa771a4ef7e24
# Verified Classes:   NonMonotonicAttenuationError, Hop
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class NonMonotonicAttenuationError(RuntimeError):
    """Raised when a re-verified AAIF chain widens authority at any hop."""


@dataclass(frozen=True)
class Hop:
    delegate_id: str
    held: frozenset[str]          # capabilities this hop claims to hold
    signature_valid: bool         # result of local crypto re-verification


def verify_delegation_chain(chain: list[Hop]) -> frozenset[str]:
    """Re-verify an AAIF chain and return the subject's effective capability set.

    Enforces per-hop attenuation monotonicity: held(h[i+1]) must be a subset
    of held(h[i]) for every consecutive pair. Signature validity and terminal
    intersection are checked but are NOT sufficient on their own.
    """
    if not chain:
        raise NonMonotonicAttenuationError("empty delegation chain")

    for i, hop in enumerate(chain):
        if not hop.signature_valid:
            raise NonMonotonicAttenuationError(
                f"hop {i} ({hop.delegate_id}) failed signature re-verification"
            )

    for i in range(1, len(chain)):
        prev, cur = chain[i - 1], chain[i]
        excess = cur.held - prev.held
        if excess:
            # Widening at this hop, even if a later hop narrows it back.
            raise NonMonotonicAttenuationError(
                f"hop {i} ({cur.delegate_id}) holds capabilities not granted by "
                f"hop {i - 1} ({prev.delegate_id}): {sorted(excess)}"
            )

    return chain[-1].held


def consume_warrant(chain: list[Hop], required: frozenset[str]) -> None:
    effective = verify_delegation_chain(chain)
    missing = required - effective
    if missing:
        raise NonMonotonicAttenuationError(
            f"subject lacks required capabilities: {sorted(missing)}"
        )
