# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-widening-drift-across-an-agent-s-multi-turn-tool-call-sandbox-when-least-privilege-escalation-is-reviewed-asynchro.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-widening-drift-across-an-agent-s-multi-turn-tool-call-sandbox-when-least-privilege-escalation-is-reviewed-asynchro.warrant.json
# Markdown SHA-256:   504199d4ace8662ac8cdfa6819b624e7da3771bd03862a81014eb123aa8666d3
# Code AST SHA-256:   56ec2b9972d1a5bf0c698f8b484672f83969530b5ba1f2ff1e308d9a321bcba8
# Verified Classes:   CapabilityDriftError, EscalationRequest, SandboxState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CapabilityDriftError(RuntimeError):
    """Raised when a tool dispatch or grant application violates plan-epoch coherence."""


@dataclass
class EscalationRequest:
    capability: str
    epoch: int
    review_id: str
    verdict: Optional[str] = None  # None | "granted" | "denied"


@dataclass
class SandboxState:
    enforced_caps: set = field(default_factory=set)
    pending: dict = field(default_factory=dict)  # capability -> EscalationRequest
    plan_epoch: int = 0

    def advance_plan(self) -> None:
        self.plan_epoch += 1

    def request_capability(self, cap: str, review_id: str) -> EscalationRequest:
        req = EscalationRequest(capability=cap, epoch=self.plan_epoch, review_id=review_id)
        self.pending[cap] = req
        return req

    def apply_verdict(self, review_id: str, verdict: str) -> None:
        for cap, req in list(self.pending.items()):
            if req.review_id != review_id:
                continue
            if req.epoch != self.plan_epoch:
                # Grant belongs to a dead plan; discard, do not widen the live set.
                del self.pending[cap]
                raise CapabilityDriftError(
                    f"verdict {verdict!r} for {cap!r} arrived at epoch {self.plan_epoch} "
                    f"but was requested at epoch {req.epoch}; grant discarded, reissue required"
                )
            req.verdict = verdict
            if verdict == "granted":
                self.enforced_caps.add(cap)
            del self.pending[cap]
            return
        raise CapabilityDriftError(f"no pending request with review_id {review_id!r}")

    def dispatch(self, cap: str) -> None:
        if cap in self.pending and self.pending[cap].verdict is None:
            raise CapabilityDriftError(
                f"dispatch of {cap!r} blocked: escalation pending in epoch {self.plan_epoch}; "
                f"plan must not advance past a dependency on an unresolved capability"
            )
        if cap not in self.enforced_caps:
            # Distinct, non-retryable denial — must not be mistaken for transient failure.
            raise CapabilityDriftError(
                f"capability_denied: {cap!r} not in enforced set at epoch {self.plan_epoch}"
            )


def run_turn(sandbox: SandboxState, requested_cap: str, review_lag_turns: int) -> None:
    sandbox.request_capability(requested_cap, review_id=f"r-{requested_cap}")
    for _ in range(review_lag_turns):
        sandbox.advance_plan()  # agent keeps planning while review is out-of-band
    # Dispatch before the (now stale) verdict lands must fail loudly, not silently retry.
    sandbox.dispatch(requested_cap)
    raise CapabilityDriftError(
        f"reached unreachable dispatch path for {requested_cap!r}; "
        f"epoch coherence guard failed to fire"
    )
