# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-aaif-credential-whose-attenuation-chain-was-silently-widened-by-an-intermediate-agent-s-re-signing.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-delegated-aaif-credential-whose-attenuation-chain-was-silently-widened-by-an-intermediate-agent-s-re-signing.warrant.json
# Markdown SHA-256:   fcdbadd02513867800e02cc0d652e3fc39061688f24d7b3218b30b7a78260c4d
# Code AST SHA-256:   34f18746c8bcd03a10747a859cd1f30cd2066da47871f828748ef01b9a3aac41
# Verified Classes:   DelegationViolation, Warrant
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class DelegationViolation(RuntimeError):
    """Raised when a child warrant is not a monotone attenuation of its parent."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    capabilities: FrozenSet[str]
    scope: FrozenSet[str]
    expiry: int
    depth: int
    normalizer_version: str
    parent: "Warrant | None" = None
    signature_valid: bool = True


def _normalize(caps: FrozenSet[str], version: str) -> FrozenSet[str]:
    # Pinned normalizer; version mismatch is a hard failure, not a warning.
    if version != "aaif-norm-v3":
        raise DelegationViolation(f"unsupported normalizer version {version!r}")
    return caps


def admit(child: Warrant, parent: Warrant) -> None:
    if not child.signature_valid:
        raise DelegationViolation(f"child signed by {child.issuer!r} failed signature check")

    if child.normalizer_version != parent.normalizer_version:
        raise DelegationViolation(
            f"normalizer skew: child={child.normalizer_version} parent={parent.normalizer_version}"
        )

    child_caps = _normalize(child.capabilities, child.normalizer_version)
    parent_caps = _normalize(parent.capabilities, parent.normalizer_version)

    widened = child_caps - parent_caps
    if widened:
        raise DelegationViolation(
            f"capability widening at hop {parent.issuer!r}->{child.issuer!r}: {sorted(widened)}"
        )

    if not child.scope <= parent.scope:
        raise DelegationViolation(
            f"scope widening: {sorted(child.scope - parent.scope)}"
        )

    if child.expiry > parent.expiry:
        raise DelegationViolation(
            f"temporal widening: child expiry {child.expiry} > parent {parent.expiry}"
        )

    if child.depth >= parent.depth:
        raise DelegationViolation(
            f"depth not decremented: child {child.depth} >= parent {parent.depth}"
        )


def admit_chain(leaf: Warrant, root: Warrant) -> None:
    # Walk leaf->root, verifying each hop's subset relation against its parent
    # artifact. A missing parent artifact is a hard failure, never optimistic.
    node = leaf
    while node.parent is not None:
        if node.parent is None:
            raise DelegationViolation(f"broken chain at {node.issuer!r}: parent artifact absent")
        admit(node, node.parent)
        node = node.parent
    if node.issuer != root.issuer:
        raise DelegationViolation(
            f"chain terminates at {node.issuer!r}, expected root {root.issuer!r}"
        )
