# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-peer-s-typed-capability-claim-before-verifying-the-warrant-chain-that-authorized-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-peer-s-typed-capability-claim-before-verifying-the-warrant-chain-that-authorized-it.warrant.json
# Markdown SHA-256:   242818d8249f48ba3622510b9a9f3943ab29f768dc7bd4890632fbc3d243de66
# Code AST SHA-256:   daafab2f20558b921e85a5071d15ff68a9e53b707f53945a0ce6cbd43b4a073f
# Verified Classes:   WarrantChainError, CapabilityNotAuthorized, WarrantLink, CapabilityClaim, CapabilityRecord
# Defensive Guards:   11 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class WarrantChainError(RuntimeError):
    """Raised when a peer's warrant chain fails structural or authorization checks."""
    pass


class CapabilityNotAuthorized(WarrantChainError):
    """Raised when provisioning is attempted against an unverified capability claim."""
    pass


@dataclass
class WarrantLink:
    issuer: str
    subject: str
    granted_scope: frozenset
    granted_ceiling: int
    delegation_depth: int
    signature_valid: bool


@dataclass
class CapabilityClaim:
    tool: str
    scope: frozenset
    ceiling: int


@dataclass
class CapabilityRecord:
    claim: CapabilityClaim
    state: str = "pending_authorization"  # pending_authorization | active
    effective_scope: frozenset = field(default_factory=frozenset)
    effective_ceiling: int = 0


MAX_DELEGATION_DEPTH = 3
TRUSTED_ROOT = "root-ca"


def verify_and_provision(
    claim: CapabilityClaim,
    chain: list[WarrantLink],
    registry: dict,
) -> CapabilityRecord:
    """
    Walk the warrant chain to a trusted root BEFORE provisioning.
    Provisioned scope = intersection of all links' grants, not the terminal claim.
    """
    if not chain:
        raise WarrantChainError("empty warrant chain")

    if chain[0].issuer != TRUSTED_ROOT:
        raise WarrantChainError(
            f"chain does not root at trusted anchor: {chain[0].issuer!r}"
        )

    # Fail fast on depth violation at the earliest offending link, so a peer
    # cannot pad the chain to widen the verification/dispatch race window.
    for i, link in enumerate(chain):
        if link.delegation_depth > MAX_DELEGATION_DEPTH:
            raise WarrantChainError(
                f"delegation depth {link.delegation_depth} exceeds max "
                f"{MAX_DELEGATION_DEPTH} at link {i} ({link.issuer}->{link.subject})"
            )
        if not link.signature_valid:
            raise WarrantChainError(f"invalid signature at link {i}")

    # Delegation-narrowing: each link must grant a subset of its parent.
    for i in range(1, len(chain)):
        parent, child = chain[i - 1], chain[i]
        if not child.granted_scope.issubset(parent.granted_scope):
            raise WarrantChainError(
                f"scope widening at link {i}: {child.granted_scope} not subset "
                f"of parent {parent.granted_scope}"
            )
        if child.granted_ceiling > parent.granted_ceiling:
            raise WarrantChainError(
                f"ceiling widening at link {i}: {child.granted_ceiling} > "
                f"parent {parent.granted_ceiling}"
            )

    # Effective authority is the intersection, never the terminal claim.
    effective_scope = frozenset(chain[0].granted_scope)
    effective_ceiling = chain[0].granted_ceiling
    for link in chain[1:]:
        effective_scope &= link.granted_scope
        effective_ceiling = min(effective_ceiling, link.granted_ceiling)

    if not claim.scope.issubset(effective_scope):
        raise WarrantChainError(
            f"claim scope {claim.scope} exceeds warranted {effective_scope}"
        )
    if claim.ceiling > effective_ceiling:
        raise WarrantChainError(
            f"claim ceiling {claim.ceiling} exceeds warranted {effective_ceiling}"
        )

    record = CapabilityRecord(
        claim=claim,
        state="active",
        effective_scope=effective_scope,
        effective_ceiling=effective_ceiling,
    )
    registry[claim.tool] = record
    return record


def dispatch(registry: dict, tool: str, amount: int) -> None:
    """Planner-side dispatch. Must refuse pending_authorization capabilities."""
    record: Optional[CapabilityRecord] = registry.get(tool)
    if record is None:
        raise CapabilityNotAuthorized(f"tool {tool!r} not registered")
    if record.state != "active":
        raise CapabilityNotAuthorized(
            f"tool {tool!r} is {record.state!r}; refusing dispatch before "
            f"warrant verification completes"
        )
    if amount > record.effective_ceiling:
        raise CapabilityNotAuthorized(
            f"amount {amount} exceeds warranted ceiling {record.effective_ceiling}"
        )
