# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-delegated-aaif-capability-was-silently-downscoped-mid-task-and-reconcile-its-in-flight-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-delegated-aaif-capability-was-silently-downscoped-mid-task-and-reconcile-its-in-flight-tool-calls.warrant.json
# Markdown SHA-256:   c3085a996f7bcba9970bb6c2bc38bbacc61759c6998bd4fb670a5bd151f615d9
# Code AST SHA-256:   6446038597f79402df3a5464ad78efb1adca88874280bbbdc8109fde12c641b4
# Verified Classes:   ScopeDivergenceError, ScopeModel, RevalidatingAgent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class ScopeDivergenceError(RuntimeError):
    """Raised when a tool denial reveals a delegated scope change the plan did not account for."""
    pass


@dataclass
class ScopeModel:
    capabilities: frozenset[str]

    def diff(self, other: "ScopeModel") -> frozenset[str]:
        return self.capabilities - other.capabilities


@dataclass
class RevalidatingAgent:
    cached_scope: ScopeModel
    fetch_effective_scope: Callable[[], ScopeModel]
    emit_event: Callable[[dict], None] = lambda e: None
    _revalidated_this_step: bool = field(default=False)

    def call_capability(self, capability: str, invoke: Callable[[], object]) -> object:
        if capability not in self.cached_scope.capabilities:
            # Plan referenced a capability the cached model never held: programmer error, not downscope.
            raise ScopeDivergenceError(
                f"plan invoked {capability!r} absent from cached scope {sorted(self.cached_scope.capabilities)}"
            )
        try:
            return invoke()
        except PermissionError as denial:  # resource server: 403 insufficient_scope
            if self._revalidated_this_step:
                # Already re-validated and still denied: terminal, do not retry or substitute.
                raise ScopeDivergenceError(
                    f"capability {capability!r} denied after revalidation; terminal for task"
                ) from denial
            effective = self.fetch_effective_scope()
            removed = self.cached_scope.diff(effective)
            self._revalidated_this_step = True
            if removed:
                self.cached_scope = effective
                self.emit_event({
                    "type": "scope_changed",
                    "removed": sorted(removed),
                    "terminal": capability in removed,
                })
                raise ScopeDivergenceError(
                    f"delegated scope narrowed mid-task; removed={sorted(removed)}; "
                    f"task halted at {capability!r} pending principal re-authorization"
                ) from denial
            # Denial with no scope change: genuine transient fault, safe to surface for retry.
            raise ScopeDivergenceError(
                f"capability {capability!r} denied but effective scope unchanged; treat as transient"
            ) from denial
