# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-scoped-capability-token-as-still-live-during-an-in-flight-delegated-sub-task-and-how-does-the-revoc.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-revoked-scoped-capability-token-as-still-live-during-an-in-flight-delegated-sub-task-and-how-does-the-revoc.warrant.json
# Markdown SHA-256:   3dcf2f2cd9b31139e6d9e777e27e5a1fc03b0205e44b9daac9085feab401dd6f
# Code AST SHA-256:   1a7f3a9ddd40eda0e4d535e94033744ba7d817cdf4cc03a169ecdfd2bf55e314
# Verified Classes:   RevocationFenceViolation, StepLoopFence
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RevocationFenceViolation(RuntimeError):
    """Raised when a delegated sub-task's capability was revoked mid-plan."""
    pass


class StepLoopFence:
    """
    Dispatcher-level fence for cross-org delegated agent sub-tasks.
    Wraps every tool call in the worker's plan. Fails closed.
    """

    def __init__(self, token_id: str, revocation_probe, ttl_s: float = 5.0):
        self.token_id = token_id
        self._probe = revocation_probe      # callable(token_id) -> bool (True = live)
        self._ttl = ttl_s
        self._last_check = 0.0
        self._last_live = True
        self._clock = 0.0

    def _now(self) -> float:
        # monotonic clock injected in real runtime
        return self._clock

    def check(self) -> None:
        if self._now() - self._last_check > self._ttl:
            self._last_live = self._probe(self.token_id)
            self._last_check = self._now()
        if not self._last_live:
            raise RevocationFenceViolation(
                f"capability {self.token_id} revoked mid-plan; "
                f"aborting sub-task, discarding partial state"
            )

    def dispatch(self, tool_call, execute):
        # Fence BEFORE side effect, never after.
        self.check()
        return execute(tool_call)


def run_delegated_plan(plan, fence: StepLoopFence, execute_tool):
    results = []
    for step in plan:
        try:
            results.append(fence.dispatch(step, lambda s=step: execute_tool(s)))
        except RevocationFenceViolation:
            # Do NOT surface to the LLM as a recoverable tool error.
            # Terminate the plan; partial results must not cross org boundary.
            raise
    return results
