# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-revoked-capability-as-still-live-taint-label-escalation-racing-the-tool-call-commitment-window.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-revoked-capability-as-still-live-taint-label-escalation-racing-the-tool-call-commitment-window.warrant.json
# Markdown SHA-256:   e5253ab93937724154e74dab07aeffeafb4b599cef76b63c4b218066f696dddd
# Code AST SHA-256:   4d77d753867fac252a7d40e75e125e732b42d8c30f800be3ed0824895f3f9ec9
# Verified Classes:   CapabilityEpochStale, TaintAwareSandbox
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CapabilityEpochStale(RuntimeError):
    """Raised when a tool call's capability token was valid at emission
    but the sandbox epoch advanced (taint escalation) before execution."""
    def __init__(self, capability: str, emitted_epoch: int, current_epoch: int, taint_source: str):
        self.capability = capability
        self.emitted_epoch = emitted_epoch
        self.current_epoch = current_epoch
        self.taint_source = taint_source
        super().__init__(
            f"capability {capability!r} stale: emitted@{emitted_epoch} "
            f"current@{current_epoch} escalated by {taint_source!r}"
        )


class TaintAwareSandbox:
    def __init__(self):
        self.epoch = 1
        self.revoked = set()
        self.max_rederivations_per_step = 1

    def escalate(self, span_id: str, label: str, capability: str):
        # asynchronous label adjudication lands here, after the agent may
        # have already committed a call under the pre-escalation epoch
        if label == "untrusted":
            self.revoked.add(capability)
            self.epoch += 1

    def execute(self, capability: str, emitted_epoch: int, args: dict, step_id: str):
        if capability in self.revoked and emitted_epoch != self.epoch:
            raise CapabilityEpochStale(
                capability=capability,
                emitted_epoch=emitted_epoch,
                current_epoch=self.epoch,
                taint_source="read_web",
            )
        if capability in self.revoked and emitted_epoch == self.epoch:
            # genuine policy violation: agent used a capability it saw revoked
            raise PermissionError(f"capability {capability!r} revoked at current epoch")
        return {"ok": True, "step": step_id, "epoch": self.epoch}


def run_plan_step(sandbox: TaintAwareSandbox, capability: str, emitted_epoch: int, args: dict, step_id: str):
    attempts = 0
    while True:
        try:
            return sandbox.execute(capability, emitted_epoch, args, step_id)
        except CapabilityEpochStale as e:
            attempts += 1
            if attempts > sandbox.max_rederivations_per_step:
                raise CapabilityEpochStale(
                    capability=e.capability,
                    emitted_epoch=e.emitted_epoch,
                    current_epoch=e.current_epoch,
                    taint_source=e.taint_source,
                ) from e
            # re-derive the step against the new epoch, then retry once
            emitted_epoch = sandbox.epoch
            if capability in sandbox.revoked:
                raise PermissionError(
                    f"cannot re-derive {capability!r}: still revoked at epoch {sandbox.epoch}"
                )
