# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-stale-capability-warrants-when-a-delegated-agent-s-attenuation-chain-outlives-its-revocation-the-revocation-shadow-gap-i.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-stale-capability-warrants-when-a-delegated-agent-s-attenuation-chain-outlives-its-revocation-the-revocation-shadow-gap-i.warrant.json
# Markdown SHA-256:   748bc61e82734ea54507d3dbaa9dcb30f7aa3bb4d3e40623533c9fadb8d08051
# Code AST SHA-256:   6f4cbe3c55ae7e328cc2cd415e9b26ff0de943396b10c58b8b538cb0588c4f1d
# Verified Classes:   RevocationShadowError, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class RevocationShadowError(RuntimeError):
    """Raised when a warrant cannot be proven unrevoked through its full ancestor chain."""
    pass


@dataclass(frozen=True)
class Warrant:
    digest: str
    parent_digest: str | None
    root_grant_id: str
    scope: str


def _digest(body: str) -> str:
    return hashlib.sha256(body.encode()).hexdigest()


def authorize(
    warrant: Warrant,
    warrant_store: dict[str, Warrant],
    revoked_root_ids: set[str],
    revoked_digests: set[str],
    *,
    side_effecting: bool,
    effect_committed: bool = False,
) -> bool:
    """
    Closed-path authorization. Sound for arbitrary delegation depth.
    Fast path: if root_grant_id is revoked -> deny immediately.
    Closed path: walk parent_digest to root, testing every ancestor.
    Fail closed if ancestry is unresolvable.
    """
    # Fast path is also the closed path when indexed by root identity.
    if warrant.root_grant_id in revoked_root_ids:
        return False

    # Walk the full ancestor chain; do not trust leaf-only membership.
    seen: set[str] = set()
    cursor: Warrant | None = warrant
    while cursor is not None:
        if cursor.digest in seen:
            raise RevocationShadowError(
                f"cycle in delegation chain at {cursor.digest!r}"
            )
        seen.add(cursor.digest)

        if cursor.digest in revoked_digests:
            return False

        if cursor.parent_digest is None:
            break  # reached root; root_grant_id already tested above

        parent = warrant_store.get(cursor.parent_digest)
        if parent is None:
            # Ancestry unresolvable: MUST fail closed, never fall back to leaf-only.
            raise RevocationShadowError(
                f"cannot resolve parent {cursor.parent_digest!r} of {cursor.digest!r}; "
                "refusing to authorize on leaf-only evidence"
            )
        cursor = parent

    # Check-to-effect gap: side-effecting calls must re-assert at commit.
    if side_effecting and effect_committed:
        # Re-run the closed check against a fresh revocation view by the caller;
        # here we require the caller to have passed a post-commit-clean view.
        if warrant.root_grant_id in revoked_root_ids or any(
            d in revoked_digests for d in seen
        ):
            raise RevocationShadowError(
                f"warrant {warrant.digest!r} revoked between entry and effect commit"
            )

    return True


def guarded_tool_call(
    warrant: Warrant,
    warrant_store: dict[str, Warrant],
    revoked_root_ids: set[str],
    revoked_digests: set[str],
) -> str:
    if not authorize(
        warrant,
        warrant_store,
        revoked_root_ids,
        revoked_digests,
        side_effecting=True,
        effect_committed=False,
    ):
        raise RevocationShadowError(
            f"denied: warrant {warrant.digest!r} (root {warrant.root_grant_id!r}) is revoked"
        )
    # ... perform effect ...
    # Re-assert at commit against the current revocation view:
    if not authorize(
        warrant,
        warrant_store,
        revoked_root_ids,
        revoked_digests,
        side_effecting=True,
        effect_committed=True,
    ):
        raise RevocationShadowError(
            f"aborted at commit: warrant {warrant.digest!r} revoked during execution"
        )
    return "ok"
