# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-holds-a-delegated-aaif-warrant-whose-revocation-event-lands-between-its-scope-check-and-its-tool-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-holds-a-delegated-aaif-warrant-whose-revocation-event-lands-between-its-scope-check-and-its-tool-invocation.warrant.json
# Markdown SHA-256:   f679dc3ed9f9668cd95224409a8ad80c798a683f3ad824d214a32723f3938b31
# Code AST SHA-256:   95596e2fe926af5e7ccde34499d111c18caebba557de5a23230d8b7d87bcf730
# Verified Classes:   TornAuthorizationError, RevocationStatus, Warrant, Action, Broker, Agent
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TornAuthorizationError(RuntimeError):
    """Raised when a side-effect would commit under a warrant whose revocation
    was published before the commit timestamp, or when the agent attempts to
    retry / delegate an action after a terminal REVOKED verdict."""
    pass


class RevocationStatus(Enum):
    ACTIVE = "active"
    REVOKED = "revoked"
    UNRESOLVED = "unresolved"


@dataclass
class Warrant:
    warrant_id: str
    lease_id: str
    scope: frozenset
    delegated_from: Optional[str] = None
    revoked_at: Optional[float] = None  # authority-side publication time


@dataclass
class Action:
    tool: str
    resource: str
    lease_id: str
    commit_time: float = field(default_factory=time.time)


class Broker:
    def __init__(self, authority_reachable: bool = True):
        self.authority_reachable = authority_reachable

    def revocation_status(self, warrant: Warrant) -> RevocationStatus:
        if not self.authority_reachable:
            return RevocationStatus.UNRESOLVED
        return RevocationStatus.REVOKED if warrant.revoked_at is not None else RevocationStatus.ACTIVE

    def commit(self, warrant: Warrant, action: Action, chain: list[Warrant]) -> None:
        # Lease must match the one the agent was granted; a stale lease is a torn window.
        if action.lease_id != warrant.lease_id:
            raise TornAuthorizationError(
                f"lease mismatch: action holds {action.lease_id!r}, warrant grants {warrant.lease_id!r}"
            )
        # Walk the full delegation chain: a revoked ancestor revokes the descendant.
        for w in [warrant, *chain]:
            status = self.revocation_status(w)
            if status is RevocationStatus.UNRESOLVED:
                # Fail closed: park, do not allow on cached state.
                raise TornAuthorizationError(
                    f"cannot resolve revocation for {w.warrant_id!r}; denying commit"
                )
            if status is RevocationStatus.REVOKED and w.revoked_at is not None:
                if w.revoked_at <= action.commit_time:
                    raise TornAuthorizationError(
                        f"torn authorization: {w.warrant_id!r} revoked at {w.revoked_at:.3f} "
                        f"but action committed at {action.commit_time:.3f}"
                    )
        # Only here is the side-effect allowed to run.


class Agent:
    def __init__(self, broker: Broker):
        self.broker = broker
        self.warrants: dict[str, Warrant] = {}
        self.revoked: set[str] = set()

    def validate(self, warrant_id: str) -> bool:
        w = self.warrants[warrant_id]
        status = self.broker.revocation_status(w)
        if status is RevocationStatus.REVOKED:
            self.revoked.add(warrant_id)
            return False
        return status is RevocationStatus.ACTIVE

    def act(self, warrant_id: str, action: Action, chain: list[Warrant]) -> None:
        if warrant_id in self.revoked:
            raise TornAuthorizationError(
                f"warrant {warrant_id!r} is terminally REVOKED; no retry, no delegation"
            )
        # The agent may have validated earlier; the broker re-derives at commit.
        self.broker.commit(self.warrants[warrant_id], action, chain)


# Trace: the observed incident.
broker = Broker(authority_reachable=True)
parent = Warrant("w-parent", "lease-1", frozenset({"repo:acme/infra"}), revoked_at=100.0)
child = Warrant("w-child", "lease-1", frozenset({"repo:acme/infra"}), delegated_from="w-parent")

agent = Agent(broker)
agent.warrants["w-child"] = child

# Agent validated at T=99.8 (before revocation published), reasoned for 2.1s,
# and its tool call lands at T=101.9 -- after revocation. The broker must reject.
action = Action(tool="git.push", resource="repo:acme/infra", lease_id="lease-1", commit_time=101.9)
try:
    agent.act("w-child", action, chain=[parent])
except TornAuthorizationError as e:
    print(f"BLOCKED (expected): {e}")

# Second trace: the laundering attempt -- agent sees REVOKED and must not delegate.
child.revoked_at = 102.0
assert agent.validate("w-child") is False
try:
    agent.act("w-child", action, chain=[parent])
except TornAuthorizationError as e:
    print(f"BLOCKED (laundering): {e}")
