# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-delegated-capability-token-whose-scope-was-partially-revoked-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-delegated-capability-token-whose-scope-was-partially-revoked-mid-execution.warrant.json
# Markdown SHA-256:   705b4de9a586a3c0a07bf97d4519d025e8f5994ece1c15e1aa2655f720ef5db2
# Code AST SHA-256:   55c5201c0dafcd24a5232b1e9c4926f3317ea880d68b89ce2d5f01d335f45dc5
# Verified Classes:   RevocationDivergenceError, Scope, Grant, Step
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Set


class RevocationDivergenceError(RuntimeError):
    """Raised when a pending plan step's effect closure intersects a revoked scope."""


@dataclass(frozen=True)
class Scope:
    action: str
    resource_prefix: str


@dataclass
class Grant:
    scopes: Set[Scope]

    def covers(self, action: str, resource: str) -> bool:
        return any(
            s.action == action and resource.startswith(s.resource_prefix)
            for s in self.scopes
        )


@dataclass
class Step:
    name: str
    # Mechanically-checked capability annotations, NOT free text.
    effect_closure: FrozenSet[Scope] = field(default_factory=frozenset)


def reconcile_after_revocation(
    pending: list[Step],
    current_grant: Grant,
    revoked: Set[Scope],
    checkpoint_index: int,
) -> int:
    """
    Return the index to resume from. Raises if a pending step's effect
    closure is partially uncovered by the surviving grant and cannot be
    proven disjoint from the revoked set.
    """
    for i, step in enumerate(pending):
        for cap in step.effect_closure:
            if cap in revoked:
                # Cannot surgically continue: this step depends on a revoked cap.
                if i <= checkpoint_index:
                    raise RevocationDivergenceError(
                        f"checkpoint {checkpoint_index} predates step {i} "
                        f"({step.name}) whose closure includes revoked {cap}"
                    )
                # Roll back to the last clean checkpoint before this step.
                return checkpoint_index
            if not current_grant.covers(cap.action, cap.resource_prefix):
                raise RevocationDivergenceError(
                    f"step {i} ({step.name}) requires {cap} not in surviving grant; "
                    f"effect closure unprovable, conservative re-plan required"
                )
    return len(pending)  # all pending steps clean
