# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-aaif-credentials-when-a-scope-narrowing-revocation-arrives-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-aaif-credentials-when-a-scope-narrowing-revocation-arrives-mid-tool-call.warrant.json
# Markdown SHA-256:   97049359d003ba22b98b8cfd8b083e8f14b23a8a30c78c13c8a9f503e27e7544
# Code AST SHA-256:   6d1cb5633084fc1ba4d4ee078761122c5cc00d563efd37a5f37836ebe77ee087
# Verified Classes:   ScopeRevokedError, StaleDecisionError, Warrant, Decision
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class ScopeRevokedError(RuntimeError):
    """Raised when an operation's resource falls outside the current warrant scope."""
    pass


class StaleDecisionError(RuntimeError):
    """Raised when an authorization decision was evaluated under a superseded scope revision."""
    pass


@dataclass
class Warrant:
    credential_id: str
    scope: Callable[[str, str], bool]  # (action, resource) -> allowed
    rev: int = 0

    def narrow(self, new_scope: Callable[[str, str], bool]) -> None:
        # Monotone: rev only increases; scope only shrinks (caller's responsibility).
        self.scope = new_scope
        self.rev += 1


@dataclass
class Decision:
    warrant_id: str
    action: str
    resource: str
    rev: int
    allowed: bool


def authorize(w: Warrant, action: str, resource: str) -> Decision:
    return Decision(w.credential_id, action, resource, w.rev, w.scope(action, resource))


def apply_effect(
    w: Warrant,
    decision: Decision,
    effect: Callable[[], None],
) -> None:
    # Effect-time re-evaluation against current predicate and revision.
    if decision.rev != w.rev:
        # Predicate changed since decision: re-evaluate, do not trust stale ALLOW.
        if not w.scope(decision.action, decision.resource):
            raise ScopeRevokedError(
                f"warrant {w.credential_id} rev {decision.rev}->{w.rev} "
                f"revoked {decision.action} on {decision.resource}; "
                f"decision was stale and is now out of scope"
            )
        # Still in scope under new rev: re-stamp and proceed.
        decision.rev = w.rev
    if not decision.allowed:
        raise StaleDecisionError(
            f"decision for {decision.resource} was DENY under rev {decision.rev}"
        )
    effect()


def run_plan(w: Warrant, steps: list[tuple[str, str, Callable[[], None]]]) -> None:
    for action, resource, effect in steps:
        d = authorize(w, action, resource)
        apply_effect(w, d, effect)
