# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-aaif-credential-binding-from-silently-degrading-across-delegated-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-aaif-credential-binding-from-silently-degrading-across-delegated-agent-hops.warrant.json
# Markdown SHA-256:   206aa8ded5a6a6921634e100825ea8967d4d77730e5cc29afd4ce1c04a668521
# Code AST SHA-256:   4835c3a8e83ea662eb793063c73a273abd1a0980c9e41e2a0e7ad7b8313cd054
# Verified Classes:   AAIFBindingError, Warrant
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, List, Optional


class AAIFBindingError(RuntimeError):
    """Raised when a delegated AAIF warrant chain violates the binding predicate."""


@dataclass(frozen=True)
class Warrant:
    subject: str              # principal the warrant is scoped to
    actor: str                # agent presenting the warrant
    audience: str             # relying-party AAIF identity (NOT a service class)
    capabilities: FrozenSet[str]
    attenuation_depth: int
    issuer: str
    signature_valid: bool


def verify_binding_chain(chain: List[Warrant], relying_party_id: str) -> None:
    """
    Recompute the AAIF binding predicate over a delegation chain.
    Called by the relying party at admission. Signature validity is necessary
    but NOT sufficient — this function enforces the semantic invariants.
    """
    if not chain:
        raise AAIFBindingError("empty warrant chain")

    for i, w in enumerate(chain):
        if not w.signature_valid:
            raise AAIFBindingError(f"hop {i}: invalid signature")

        # Audience must pin to THIS relying party, not a service class.
        if w.audience != relying_party_id:
            raise AAIFBindingError(
                f"hop {i}: audience {w.audience!r} != relying party {relying_party_id!r} "
                "(service-class audience enables cross-instance replay)"
            )

        if i == 0:
            continue

        prev = chain[i - 1]

        # Subject must be preserved (forward) or self-issued (re-mint by prior actor).
        if w.subject != prev.subject and w.subject != prev.actor:
            raise AAIFBindingError(
                f"hop {i}: subject {w.subject!r} neither preserved from {prev.subject!r} "
                f"nor self-issued by actor {prev.actor!r}"
            )

        # Capabilities must be monotonically non-increasing across the chain.
        if not w.capabilities.issubset(prev.capabilities):
            amplified = w.capabilities - prev.capabilities
            raise AAIFBindingError(
                f"hop {i}: capability amplification detected: {sorted(amplified)}"
            )

        # Attenuation depth must strictly decrement on re-mint.
        if w.subject != prev.subject and w.attenuation_depth != prev.attenuation_depth - 1:
            raise AAIFBindingError(
                f"hop {i}: re-mint did not decrement attenuation_depth "
                f"({prev.attenuation_depth} -> {w.attenuation_depth})"
            )


def delegate(chain: List[Warrant], next_actor: str, restrict: Optional[FrozenSet[str]]) -> Warrant:
    """
    Mint a derived warrant for the next hop. A re-mint WITHOUT an explicit
    restrict argument is a privilege amplification and must be rejected here,
    not silently executed as a capability copy.
    """
    if restrict is None:
        raise AAIFBindingError(
            "delegate() called without restrict=; refusing to re-mint with copied "
            "capabilities (this is the AAIF binding failure mode)"
        )
    parent = chain[-1]
    if not restrict.issubset(parent.capabilities):
        raise AAIFBindingError(
            f"restrict {sorted(restrict)} not a subset of parent capabilities "
            f"{sorted(parent.capabilities)}"
        )
    return Warrant(
        subject=next_actor,
        actor=next_actor,
        audience=parent.audience,
        capabilities=restrict,
        attenuation_depth=parent.attenuation_depth - 1,
        issuer=parent.actor,
        signature_valid=True,
    )
