# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-signs-its-own-delegation-chain-aaif-credential-issuance-under-recursive-self-authorization.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-signs-its-own-delegation-chain-aaif-credential-issuance-under-recursive-self-authorization.warrant.json
# Markdown SHA-256:   d980c32e492b8ddbb1b63a06f3410ec9d35dc943c541d6ffae75fd8ea07b3025
# Code AST SHA-256:   46bb5fec6b20c6909f8cf68df631423ec5e88e76c2942e58d070c532d87ce1a2
# Verified Classes:   DelegationDepthViolation, Credential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class DelegationDepthViolation(RuntimeError):
    """Raised when a credential's depth is not derivable from its verified parent."""


@dataclass(frozen=True)
class Credential:
    subject: str
    issuer: str
    scopes: frozenset
    depth: int
    max_delegation_depth: int
    jti: str


def issue_child(parent: Credential, subject: str, scopes: frozenset, client_claimed_depth: int) -> Credential:
    # Invariant: depth is derived from the verified parent, never trusted from the caller.
    if parent.depth >= parent.max_delegation_depth:
        raise DelegationDepthViolation(
            f"issuer {parent.subject} at depth {parent.depth} cannot delegate "
            f"(max_delegation_depth={parent.max_delegation_depth})"
        )
    derived_depth = parent.depth + 1
    if client_claimed_depth != derived_depth:
        # This is the exact condition that produced the P->E->H->W breach:
        # a compacted-context retry wrote a shallower depth than the parent implies.
        raise DelegationDepthViolation(
            f"client claimed depth {client_claimed_depth} but parent {parent.subject} "
            f"at depth {parent.depth} implies {derived_depth}"
        )
    if not scopes.issubset(parent.scopes):
        raise DelegationDepthViolation(
            f"scope escalation: {scopes - parent.scopes} not held by {parent.subject}"
        )
    return Credential(
        subject=subject,
        issuer=parent.subject,
        scopes=scopes,
        depth=derived_depth,
        max_delegation_depth=parent.max_delegation_depth,
        jti=f"{parent.jti}:{subject}:{hash(scopes)}",
    )
