# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-credential-whose-aud-matches-but-whose-delegation-chain-exceeds-the-orchestrator-s-remaining-warrant-dep.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-aaif-credential-whose-aud-matches-but-whose-delegation-chain-exceeds-the-orchestrator-s-remaining-warrant-dep.warrant.json
# Markdown SHA-256:   7a3c1af6c54ca5d8deb0d0f95014814127c353279ec38b1cd8213e9256ecf48f
# Code AST SHA-256:   aa66923421b898390646eae83245b74e1e3b784e51c20fb8e11a787e8e1905d7
# Verified Classes:   WarrantDepthExceeded, SignedWarrant, VerifierPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class WarrantDepthExceeded(RuntimeError):
    """Raised when a delegated AAIF credential's signed depth exceeds the
    receiving verifier's local delegation bound, even though signatures,
    audience, and expiry all validate."""


@dataclass(frozen=True)
class SignedWarrant:
    issuer: str
    subject: str
    audience: str
    signed_depth: int          # edges from root issuer, signed per hop
    root_max_depth: int        # originator's ceiling
    signature_valid: bool
    expired: bool


@dataclass(frozen=True)
class VerifierPolicy:
    identity: str
    max_delegation_depth: int  # local floor of trust, edges from root


def admit(warrant: SignedWarrant, policy: VerifierPolicy) -> str:
    if not warrant.signature_valid:
        return "INVALID_SIGNATURE"
    if warrant.expired:
        return "EXPIRED"
    if warrant.audience != policy.identity:
        return "AUDIENCE_MISMATCH"

    # Depth check must run even though aud matched.
    effective_bound = min(warrant.root_max_depth, policy.max_delegation_depth)
    if warrant.signed_depth > effective_bound:
        raise WarrantDepthExceeded(
            f"leaf depth {warrant.signed_depth} exceeds effective bound "
            f"{effective_bound} (root_max={warrant.root_max_depth}, "
            f"local_max={policy.max_delegation_depth}); "
            f"verdict=OUT_OF_SCOPE, do not retry with same credential"
        )
    return "VALID"


def run_tool_gateway(warrant: SignedWarrant, policy: VerifierPolicy) -> None:
    verdict = admit(warrant, policy)
    if verdict != "VALID":
        raise WarrantDepthExceeded(f"tool call refused: {verdict}")
    # proceed with scoped tool call
