# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-capability-token-whose-consent-chain-is-non-monotonic-across-a-scope-narrowing-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-capability-token-whose-consent-chain-is-non-monotonic-across-a-scope-narrowing-hop.warrant.json
# Markdown SHA-256:   e2609be5a86c1fe5d2d0b90d687e8040bc15792afc4188d4029b013294fb304a
# Code AST SHA-256:   70ade329ae2b19841284f4feec2910d1ede9063f052a63e585dc8d8282c62531
# Verified Classes:   NonMonotonicConsentError, Constraint, Token
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class NonMonotonicConsentError(RuntimeError):
    """Raised when a delegated token's constraint chain violates the narrowing order."""


@dataclass(frozen=True)
class Constraint:
    key: str
    value: Any
    # lower is more restrictive for numeric bounds; for allowlists, subset is narrower
    kind: str = "numeric_bound"  # one of: numeric_bound, allowlist, exact


@dataclass(frozen=True)
class Token:
    agent_id: str
    constraints: dict[str, Constraint] = field(default_factory=dict)
    signed_chain: tuple[str, ...] = ()


def _narrows(parent: Constraint, child: Constraint) -> bool:
    if parent.kind == "numeric_bound":
        return child.value <= parent.value
    if parent.kind == "allowlist":
        return set(child.value).issubset(set(parent.value))
    if parent.kind == "exact":
        return child.value == parent.value
    return False


def verify_monotonic_chain(chain: list[Token]) -> None:
    """Verify the full delegation chain narrows monotonically in constraints.

    A hop is valid only if every parent constraint is present in the child
    and at least as restrictive. A missing key is a violation, never a default.
    """
    if not chain:
        raise NonMonotonicConsentError("empty consent chain")
    root = chain[0]
    for hop_index in range(1, len(chain)):
        parent, child = chain[hop_index - 1], chain[hop_index]
        for key, parent_constraint in parent.constraints.items():
            if key not in child.constraints:
                raise NonMonotonicConsentError(
                    f"hop {hop_index} ({parent.agent_id}->{child.agent_id}) "
                    f"dropped constraint {key!r}; a missing key is a violation, "
                    f"not an unconstrained default"
                )
            child_constraint = child.constraints[key]
            if not _narrows(parent_constraint, child_constraint):
                raise NonMonotonicConsentError(
                    f"hop {hop_index} ({parent.agent_id}->{child.agent_id}) "
                    f"relaxed constraint {key!r}: "
                    f"{parent_constraint.value!r} -> {child_constraint.value!r}"
                )
        # child may add constraints, but may not substitute a bound key
        for key in child.constraints:
            if key not in parent.constraints and key in {
                "requires_auditor", "resource_allowlist", "max_ops"
            }:
                # a bound key appearing downstream from nowhere is a substitution
                if key == "requires_auditor" and chain[0].constraints.get(key) is None:
                    raise NonMonotonicConsentError(
                        f"hop {hop_index} introduced bound key {key!r} "
                        f"not present in root consent"
                    )


def authorize_tool_call(chain: list[Token], tool: str, n_ops: int) -> None:
    verify_monotonic_chain(chain)
    leaf = chain[-1]
    cap = leaf.constraints.get("max_ops")
    if cap is not None and n_ops > cap.value:
        raise NonMonotonicConsentError(
            f"tool {tool!r} requested {n_ops} ops, leaf cap is {cap.value}"
        )
    # ... proceed with invocation
