# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-mints-a-scoped-token-for-a-sub-agent-whose-requested-scope-is-a-strict-superset-of-the-minting-instance-s-own-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-mints-a-scoped-token-for-a-sub-agent-whose-requested-scope-is-a-strict-superset-of-the-minting-instance-s-own-scope.warrant.json
# Markdown SHA-256:   93e360ecf0965046daa70cb36b6b45b8dac2da4cb32e7f7212a5fea2c188f653
# Code AST SHA-256:   d4ae4f52df6cc2433e3294a05ae119370d8b96c908549bf059edeceea1430713
# Verified Classes:   AttenuationDirectiveViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AttenuationDirectiveViolation(RuntimeError):
    """Raised when a mint request would drop a permission preserved by an inherited directive."""
    pass


def mint_scoped_token(parent_token, requested_scope):
    """
    AAIF-compliant mint with attenuation-directive reconciliation.

    parent_token.scope            -> set of permissions the parent holds
    parent_token.attenuation      -> dict of directives, e.g. {"preserve": {"write:orders"}}
    requested_scope               -> set of permissions for the child

    The subset check alone is insufficient: a requested scope can be a strict
    subset of the parent scope while still dropping a permission that an
    inherited `preserve` directive forbids dropping.
    """
    if not requested_scope.issubset(parent_token.scope):
        raise AttenuationDirectiveViolation(
            f"requested scope {sorted(requested_scope)} is not a subset of "
            f"parent scope {sorted(parent_token.scope)}"
        )

    dropped = parent_token.scope - requested_scope
    preserved = parent_token.attenuation.get("preserve", set())
    violated = dropped & preserved

    if violated:
        # The subset check passed, but the attenuation chain forbids this drop.
        # Reject locally so the failure is attributed to the minter, not the leaf.
        raise AttenuationDirectiveViolation(
            f"mint would drop {sorted(violated)}, which is preserved by an "
            f"inherited attenuation directive; the resulting token would pass "
            f"local validation and fail remote chain replay"
        )

    return _sign_child_token(
        parent_id=parent_token.id,
        scope=requested_scope,
        attenuation=_derive_child_attenuation(parent_token.attenuation, requested_scope),
    )
