# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-authority-escalation-in-agent-to-agent-delegation-chains-under-aaif-identities.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-authority-escalation-in-agent-to-agent-delegation-chains-under-aaif-identities.warrant.json
# Markdown SHA-256:   b8eafa864fa09eac9d6dd6fad465e59bfe685e31bafd7549268ddd2309ad4192
# Code AST SHA-256:   a0e1f6dce217e12baad8baf4925ad52c157ebfbb454fe04c2c8534394f5375c3
# Verified Classes:   DelegationAttenuationError, DelegationToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class DelegationAttenuationError(RuntimeError):
    """Raised when a hop's scope is not a subset of its parent's scope,
    or when provenance binding to the parent token is broken."""


@dataclass(frozen=True)
class DelegationToken:
    principal_aaif_id: str
    scope: FrozenSet[str]
    parent_hash: str | None


def mint_child_token(
    parent: DelegationToken,
    child_id: str,
    requested_scope: FrozenSet[str],
    parent_hash: str,
) -> DelegationToken:
    # Provenance binding: child must reference the exact parent token.
    if parent_hash is None or parent_hash == "":
        raise DelegationAttenuationError(
            f"hop {child_id}: missing parent_hash; token is not hash-linked "
            f"to parent {parent.principal_aaif_id}"
        )
    # Attenuation invariant: scope must narrow, never widen.
    widened = requested_scope - parent.scope
    if widened:
        raise DelegationAttenuationError(
            f"hop {child_id} under {parent.principal_aaif_id} requested "
            f"scope {sorted(widened)} not present in parent grant "
            f"{sorted(parent.scope)}; authority escalation refused at mint time"
        )
    return DelegationToken(
        principal_aaif_id=child_id,
        scope=requested_scope,
        parent_hash=parent_hash,
    )
