# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-attenuate-a-delegated-capability-token-whose-scope-predicate-is-non-monotone.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-attenuate-a-delegated-capability-token-whose-scope-predicate-is-non-monotone.warrant.json
# Markdown SHA-256:   b4f5c6860d2bbe80bf4ea20118bc7d089aecadb92a8b716e73043ca9db74e4cf
# Code AST SHA-256:   bd5ca394e84bfd58dda2091672d8cc96a539e71160bfe0d1bf5fc3b5d54f5993
# Verified Classes:   AttenuationRefused, Scope
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Callable


class AttenuationRefused(RuntimeError):
    """Raised when a child scope cannot be proven a subset of its parent."""


@dataclass
class Scope:
    action: list[str]
    resource: dict[str, Any]
    ttl: int
    audience: str
    negated_keys: frozenset[str] = field(default_factory=frozenset)

    def has_negation_over(self, key: str) -> bool:
        return key in self.negated_keys


# Declared matcher registry published by the resource server.
# Each matcher names the scope keys it consumes; keys outside this set are dropped.
MATCHER_REGISTRY: dict[str, frozenset[str]] = {
    "default": frozenset({"tenant", "id"}),
    "classified": frozenset({"tenant", "classification"}),
}


def select_matcher(scope: Scope) -> str:
    if "classification" in scope.resource:
        return "classified"
    return "default"


def _negations_survive(parent: Scope, child: Scope, matcher: str) -> bool:
    consumed = MATCHER_REGISTRY[matcher]
    for key in parent.negated_keys:
        if key in consumed and key not in child.negated_keys:
            # The child's matcher path would drop the parent's exclusion.
            return False
    return True


def attenuate(parent: Scope, child: Scope) -> Scope:
    # 1. Monotone parent, or negation over a key the child cannot rebind.
    if parent.negated_keys:
        parent_matcher = select_matcher(parent)
        child_matcher = select_matcher(child)
        if parent_matcher != child_matcher:
            raise AttenuationRefused(
                f"matcher path changed {parent_matcher!r} -> {child_matcher!r}; "
                f"parent negations {sorted(parent.negated_keys)} may be dropped"
            )
        if not _negations_survive(parent, child, child_matcher):
            raise AttenuationRefused(
                f"child does not re-assert parent negations {sorted(parent.negated_keys)} "
                f"at matcher {child_matcher!r}"
            )

    # 2. Shape stability: child must not introduce keys the matcher drops.
    consumed = MATCHER_REGISTRY[select_matcher(child)]
    dropped = set(child.resource) - consumed
    if dropped and parent.negated_keys:
        raise AttenuationRefused(
            f"child adds keys {sorted(dropped)} that matcher "
            f"{select_matcher(child)!r} discards; subset unprovable"
        )

    # 3. Plain attenuation checks (necessary, not sufficient).
    if not set(child.action).issubset(parent.action):
        raise AttenuationRefused("child action set is not a subset of parent")
    if child.ttl > parent.ttl:
        raise AttenuationRefused("child TTL exceeds parent TTL")
    if not child.audience.startswith(parent.audience.rstrip("*")):
        raise AttenuationRefused("child audience not within parent audience")

    return child


def mint_child(parent: Scope, requested: Scope) -> Scope:
    try:
        return attenuate(parent, requested)
    except AttenuationRefused as exc:
        # Escalate rather than optimistically mint.
        raise AttenuationRefused(
            f"refusing to attenuate; re-request monotone parent: {exc}"
        ) from exc
