# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-aaif-credential-whose-scope-narrows-below-the-task-warrant-it-inherited.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-a-delegated-aaif-credential-whose-scope-narrows-below-the-task-warrant-it-inherited.warrant.json
# Markdown SHA-256:   41e7b1cde77afa903b443a54424f22ad4ccb48bbb233da6ee02757a5f19c6ed6
# Code AST SHA-256:   3e784f0c5dd46dd28e294928ee4620332b1414526083d72c0810f6e6046f91bf
# Verified Classes:   PurposeAttenuationViolation, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Optional


class PurposeAttenuationViolation(RuntimeError):
    """Raised when a re-delegated AAIF credential does not preserve purpose monotonicity."""
    pass


@dataclass(frozen=True)
class Warrant:
    subject: str
    resource_scope: str
    purpose: Optional[str]          # None == absent claim, NOT unrestricted
    expires_at: int
    chain: tuple


def verify_delegation(parent: Warrant, child: Warrant, now: int) -> None:
    # 1. Structural subset on resource (necessary, not sufficient).
    if not _resource_subset(child.resource_scope, parent.resource_scope):
        raise PurposeAttenuationViolation(
            f"resource scope {child.resource_scope!r} not subset of {parent.resource_scope!r}"
        )

    # 2. Parent must still be live to prove ancestry.
    if parent.expires_at <= now:
        raise PurposeAttenuationViolation(
            f"parent warrant for {parent.subject} expired at {parent.expires_at}; "
            "cannot verify purpose ancestry"
        )

    # 3. THE NON-OBVIOUS GUARD: absence is deny-all, never default-open.
    if child.purpose is None:
        raise PurposeAttenuationViolation(
            f"child warrant for {child.subject} carries no purpose claim; "
            "absence is not a subset of any purpose and must be rejected, "
            "not defaulted to unrestricted"
        )

    # 4. Purpose monotonicity: child purpose must be a member of parent's purpose set.
    parent_purposes: FrozenSet[str] = _purpose_set(parent.purpose)
    if child.purpose not in parent_purposes:
        raise PurposeAttenuationViolation(
            f"child purpose {child.purpose!r} widens beyond parent purposes "
            f"{sorted(parent_purposes)} — resource narrowed but purpose broadened"
        )

    # 5. Chain must be complete and ordered.
    if child.chain[:-1] != parent.chain or child.chain[-1].subject != child.subject:
        raise PurposeAttenuationViolation(
            "attenuation chain is truncated or out of order; "
            "cannot verify multi-hop purpose inheritance"
        )


def _resource_subset(child: str, parent: str) -> bool:
    return child == parent or parent.endswith("*") and child.startswith(parent[:-1])


def _purpose_set(purpose: Optional[str]) -> FrozenSet[str]:
    if purpose is None:
        return frozenset()          # deny-all, not {unrestricted}
    return frozenset(p.strip() for p in purpose.split(","))
