# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-verify-the-transitive-authority-chain-before-executing-a-delegated-action-and-what-breaks-when-it-cannot-reconstruct-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-verify-the-transitive-authority-chain-before-executing-a-delegated-action-and-what-breaks-when-it-cannot-reconstruct-provenance.warrant.json
# Markdown SHA-256:   83152925b17a16e6facf84bf20b552731344cb5f286aa0a45f461212ad5f87d1
# Code AST SHA-256:   e2356f2524d1f8750d67b7e0ac612c7ad042f98c437f8504dd4a9add7d880b67
# Verified Classes:   DelegationReconstructionError, Hop
# Defensive Guards:   9 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class DelegationReconstructionError(RuntimeError):
    """Raised when an executing instance cannot prove its authority is a
    transitive subset of the authority origin's grant."""


@dataclass
class Hop:
    hop_id: str
    delegator: str
    delegate: str
    limit_usd: Optional[float]          # None means "not expressed in lattice"
    scope: Optional[frozenset]          # None means "not expressed in lattice"
    renames: dict = field(default_factory=dict)  # field rename at this hop
    natural_language_clause: Optional[str] = None


def compose_authority(chain: list[Hop], executor: str) -> tuple[float, frozenset]:
    """Fold the chain from origin to executor, computing the effective
    authority. Raises if any hop escapes the lattice or the chain is broken."""
    if not chain:
        raise DelegationReconstructionError("empty delegation chain")
    if chain[0].delegator != chain[0].delegate and chain[-1].delegate != executor:
        raise DelegationReconstructionError(
            f"chain does not terminate at executor {executor!r}"
        )
    limit = float("inf")
    scope = frozenset({"*"})
    for i, hop in enumerate(chain):
        if hop.natural_language_clause is not None:
            raise DelegationReconstructionError(
                f"hop {hop.hop_id} carries lattice-escape clause "
                f"{hop.natural_language_clause!r}; authority uncomputable"
            )
        if hop.limit_usd is None or hop.scope is None:
            raise DelegationReconstructionError(
                f"hop {hop.hop_id} does not express limit/scope in lattice form"
            )
        if i > 0 and hop.delegator != chain[i - 1].delegate:
            raise DelegationReconstructionError(
                f"hop {hop.hop_id} delegator {hop.delegator!r} does not match "
                f"previous delegate {chain[i - 1].delegate!r}"
            )
        limit = min(limit, hop.limit_usd)
        scope = scope & hop.scope if scope != frozenset({"*"}) else hop.scope
    if limit == float("inf"):
        raise DelegationReconstructionError("no hop constrained the limit")
    return limit, scope


def authorize_action(
    chain: list[Hop],
    executor: str,
    action_limit_usd: float,
    action_payee: str,
    origin_limit_usd: float,
) -> None:
    limit, scope = compose_authority(chain, executor)
    if limit > origin_limit_usd:
        raise DelegationReconstructionError(
            f"composed limit {limit} exceeds origin grant {origin_limit_usd}"
        )
    if action_limit_usd > limit:
        raise DelegationReconstructionError(
            f"action {action_limit_usd} exceeds composed limit {limit}"
        )
    if action_payee not in scope:
        raise DelegationReconstructionError(
            f"payee {action_payee!r} not in composed scope {sorted(scope)}"
        )
