# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-capability-buried-mid-chain-in-a2a-delegation-before-it-acts-on-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-capability-buried-mid-chain-in-a2a-delegation-before-it-acts-on-it.warrant.json
# Markdown SHA-256:   b4c148e240be107841aa2c3d4f818a6e731d2972a4fbde9062d45bf5d50c157d
# Code AST SHA-256:   67787976992195d7477ea36e36f1a3142e8b35b881e2a1d3bc74b0c709caa60b
# Verified Classes:   RevokedAncestorError, UnresolvableAncestryError, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class RevokedAncestorError(RuntimeError):
    """Raised when a delegated warrant has a revoked ancestor in its chain."""
    pass


class UnresolvableAncestryError(RuntimeError):
    """Raised when the leaf cannot prove non-ancestry within its budget."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    parent_hash: Optional[str]   # hash of parent warrant; None for root
    scope: str


def _hash(w: Warrant) -> str:
    return hashlib.sha256(f"{w.warrant_id}:{w.parent_hash}:{w.scope}".encode()).hexdigest()


def check_ancestry(
    leaf: Warrant,
    chain: dict[str, Warrant],          # hash -> Warrant, walkable to root
    revoked_ids: set[str],              # root's revocation set, by warrant_id
    budget: int = 8,
) -> None:
    """
    Walk leaf -> root. Block if any ancestor is revoked.
    Block if ancestry cannot be resolved within budget.
    """
    seen = 0
    cur = leaf
    while True:
        if seen > budget:
            raise UnresolvableAncestryError(
                f"ancestry budget {budget} exceeded at {cur.warrant_id}"
            )
        if cur.warrant_id in revoked_ids:
            raise RevokedAncestorError(
                f"warrant {cur.warrant_id} is revoked (ancestor of leaf)"
            )
        if cur.parent_hash is None:
            return  # reached root, clean
        parent = chain.get(cur.parent_hash)
        if parent is None:
            raise UnresolvableAncestryError(
                f"missing parent {cur.parent_hash} for {cur.warrant_id}"
            )
        cur = parent
        seen += 1


def guarded_act(leaf: Warrant, chain: dict[str, Warrant], revoked_ids: set[str]) -> str:
    try:
        check_ancestry(leaf, chain, revoked_ids)
    except (RevokedAncestorError, UnresolvableAncestryError) as e:
        # fail closed: do not act on a warrant we cannot clear
        raise RevokedAncestorError(f"action blocked: {e}") from e
    return f"acted under {leaf.warrant_id} scope={leaf.scope}"
