# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-it-cannot-attenuate-the-scope-narrowing-invariant-in-aaif.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-it-cannot-attenuate-the-scope-narrowing-invariant-in-aaif.warrant.json
# Markdown SHA-256:   91045a4f9ad60e067be340f9a9ed6167ee69be0926b35490760167f81230fd93
# Code AST SHA-256:   586ddf227688a6a15b147592cf6c0dff4919d468434d36b535e189835d10387a
# Verified Classes:   UnattenuableCapabilityError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnattenuableCapabilityError(RuntimeError):
    """Raised when an instance cannot prove a child token is a subset of its parent."""
    pass


# Constraint grammars this instance's evaluator can fully interpret.
# A constraint whose grammar is not in this set cannot be soundly narrowed.
_LOCALLY_EVALUABLE_GRAMMARS = frozenset({"aaif-core-v1", "aaif-core-v2"})


def attenuate(parent_token, requested_child_constraints, local_evaluator):
    """
    Mint a child capability token from a parent, or refuse.

    Returns the child token only if every constraint on the parent is
    expressible in a grammar this instance can evaluate AND the requested
    child constraints are provably a subset under that evaluation.
    """
    if not parent_token.is_valid():
        raise UnattenuableCapabilityError(
            "parent token failed validity checks; cannot attenuate"
        )

    opaque = [
        c for c in parent_token.constraints
        if c.grammar not in _LOCALLY_EVALUABLE_GRAMMARS
    ]
    if opaque:
        # We cannot prove subset over constraints we cannot parse.
        # Forwarding is safe; minting a child is not.
        raise UnattenuableCapabilityError(
            "parent carries constraints in unparseable grammar(s) "
            f"{sorted({c.grammar for c in opaque})}; "
            "refuse to attenuate, use parent directly or request "
            "an issuer-attenuated token"
        )

    child = parent_token.derive(requested_child_constraints)
    if not local_evaluator.proves_subset(child.authority, parent_token.authority):
        raise UnattenuableCapabilityError(
            "child authority not provably a subset of parent authority; "
            "refuse to mint"
        )
    return child
