# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-keep-honoring-a-delegated-capability-after-the-parent-revokes-it-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-keep-honoring-a-delegated-capability-after-the-parent-revokes-it-mid-chain.warrant.json
# Markdown SHA-256:   582bb64169cfd2376defa07354515826c65b10359ee09234cfd188463ec8ce05
# Code AST SHA-256:   c396f7632593e2b3607abbbf33d925f63552413b1ca06f7ff7f91950f1f8feef
# Verified Classes:   RevocationUnconfirmedError, ScopeRevokedError, ScopeDescriptor, Delegation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Callable


class RevocationUnconfirmedError(RuntimeError):
    """Raised when a parent cannot behaviorally confirm a descendant stopped."""


class ScopeRevokedError(RuntimeError):
    """Raised at tool-invocation time when a per-use check finds the scope revoked."""


@dataclass
class ScopeDescriptor:
    cap_id: str
    grants: list[str]
    revoked: bool = False
    loaded_at: float = field(default_factory=time.monotonic)


@dataclass
class Delegation:
    parent_id: str
    child_id: str
    scope: ScopeDescriptor
    # Budget within which the child MUST make an observable call after revoke.
    revocation_budget_s: float = 5.0


def revoke_and_confirm(
    delegation: Delegation,
    revoke_fn: Callable[[str], None],
    observe_next_call: Callable[[str], bool],
    clock: Callable[[], float] = time.monotonic,
) -> None:
    """
    Revoke a delegated capability and REQUIRE behavioral confirmation that the
    descendant stopped. Declarative 200-OK from revoke_fn is insufficient.
    """
    revoke_fn(delegation.scope.cap_id)
    delegation.scope.revoked = True

    deadline = clock() + delegation.revocation_budget_s
    while clock() < deadline:
        # observe_next_call returns True iff the child's next tool invocation
        # was rejected by a per-use scope check (i.e. it actually stopped).
        if observe_next_call(delegation.child_id):
            return
        time.sleep(0.05)

    # No observable rejection within budget: we cannot prove the child stopped.
    # Escalate to hard termination; do NOT report success.
    raise RevocationUnconfirmedError(
        f"child={delegation.child_id} cap={delegation.scope.cap_id} "
        f"did not exhibit a rejected call within {delegation.revocation_budget_s}s; "
        f"zombie authority suspected — escalate to hard kill"
    )


def invoke_tool(scope: ScopeDescriptor, tool: str, check_revoked_fn: Callable[[str], bool]) -> None:
    """Per-use check: never trust the cached descriptor's revoked flag alone."""
    if scope.revoked or check_revoked_fn(scope.cap_id):
        raise ScopeRevokedError(f"cap={scope.cap_id} tool={tool} revoked at use-time")
    # ... perform tool call ...
