# How the LoopX Quota Should-Run Mechanism Determines Agent Execution Rights

> Discover how the LoopX quota should-run mechanism validates plans, prepares candidates, and resolves routes to grant agents execution rights for the current tick.

- Repository: [huangruiteng/loopx](https://github.com/huangruiteng/loopx)
- Tags: deep-dive
- Published: 2026-09-02

---

**The quota should-run mechanism evaluates a three-phase pipeline—plan validation, candidate preparation, and route resolution—to determine whether an autonomous agent may execute its turn in the current tick.**

LoopX is an autonomous agent framework that uses a sophisticated quota system to govern when agents may execute actions. The **quota should-run mechanism** serves as the core decision engine that evaluates multiple constraints—including compute quotas, health states, pause flags, and replay precedence—to produce a binary run/no-run verdict for each tick.

## Overview of the Quota Should-Run Pipeline

The decision process implemented in [`loopx/control_plane/quota/should_run.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/quota/should_run.py) consists of three distinct phases:

1. **Load and validate the quota plan** – Constructs a quota plan from the global status payload containing per-goal compute quotas, health indicators, and pause states via `_build_quota_plan_for_goal`.
2. **Prepare the candidate item** – Examines the goal's presence in the plan; if paused, returns immediately; otherwise enriches the candidate with agent identity, automation liveness, and scheduler hints through `_prepare_quota_should_run_item`.
3. **Resolve the execution route** – Builds a decision route (`_QuotaDecisionRoute`), applies settled replay precedence, validates selected Todo guards, and produces the final payload via `_build_quota_should_run_payload`.

## Phase 1: Loading and Validating the Quota Plan

The mechanism begins by locating the target goal within the quota registry. If the goal does not exist, the routine immediately returns a `"goal_not_found"` response.

```python
safe_goal_id = str(goal_id or "").strip()
registry_goal = _registry_goal_by_id(status_payload).get(safe_goal_id) or {}

```

Once the goal is identified, the system extracts the quota plan using `_build_quota_plan_for_goal`. This function returns both the plan structure and a health status flag. The plan contains **quota items** (describing spendable slots and pause flags) and **health items** (indicating health-blocking conditions).

```python
plan, goal_health_ok = _build_quota_plan_for_goal(status_payload, goal_id=safe_goal_id)
item = next((c for c in _quota_plan_items(plan) if c.get("goal_id") == safe_goal_id), None)

```

If the goal is missing from the plan entirely, the mechanism returns a `"skip"` response, preventing the agent from proceeding.

## Phase 2: Pause, Health, and Candidate Preparation

Before enriching the candidate, the mechanism checks for blocking conditions that would force an early exit.

### Pause and Health Validation

If `_quota_item_is_paused(item)` returns `True`, the system invokes `build_quota_paused_should_run_payload`, which sets `should_run = False` and includes a `pause_cause` field explaining the suspension. Common causes include compute quota exhaustion or manual administrative pause.

If no quota item exists but a health item is present, the payload reports `should_run = False` with `state = "blocked_health"`, indicating the goal cannot proceed due to health constraints rather than quota limitations.

### Candidate Enrichment

When no blocking conditions exist, `_prepare_quota_should_run_item` enriches the candidate with:

- **Agent identity** – Via `build_quota_agent_identity`, attaching agent metadata and authentication context.
- **Automation liveness** – Through `build_automation_liveness`, verifying the agent's operational status.
- **Interaction contracts** – Using `build_interaction_contract`, which adds capability metadata and permission boundaries.
- **Scheduler hints** – Encoded via `_scheduler_hint`, instructing whether the scheduler should `run_now`, `wait`, or `stop`.
- **Focus-wait overrides** – Functions like `quota_with_handoff_outcome_floor` and `_quota_with_focus_wait_override` can force a `focus_wait` state that yields `should_run = False` even when quota exists.

## Phase 3: Route Resolution and Safety Guards

The enriched candidate proceeds to `_resolve_quota_should_run_route`, which constructs the initial decision route determining the **effective action** (`run_now`, `quiet_noop`, etc.) and whether **quota spend** is permitted.

### Replay Precedence

The route is immediately adjusted by `apply_settled_replay_route_precedence`, which ensures that any settled replay actions (previously executed spends) cannot be overridden by new decisions. This maintains consistency across ticks when replaying historical actions.

```python
route = _resolve_quota_should_run_route(prepared)
apply_settled_replay_route_precedence(route, replay_phase=prepared.receipt_bound_replay_phase)

```

### Todo and Boundary Guards

The mechanism validates the selected Todo through `selected_todo_projection`. If the agent's inbox priority is not due, a **workspace guard** (`build_agent_workspace_guard`) may block execution. Additionally, **boundary-projection repair hints** can suppress `should_run` when the agent would violate a projection boundary, acting as a final safety net before execution.

## Implementation Details and Code Examples

### CLI Usage

The public façade `build_quota_should_run` exposed in [`loopx/quota.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/quota.py) provides the primary interface:

```python
from loopx.quota import build_quota_should_run
import json

status = json.load(open("status.json"))
payload = build_quota_should_run(
    status,
    goal_id="my-goal",
    agent_id="agent-01",
    include_scheduler_detail=True,
)
print(payload)   # → {"should_run": true, "effective_action": "run_now", ...}

```

### Unit Testing

The test suite in [`tests/control_plane/test_quota_should_run_parity.py`](https://github.com/huangruiteng/loopx/blob/main/tests/control_plane/test_quota_should_run_parity.py) validates the decision logic:

```python
payload = build_quota_should_run(
    status_payload,
    goal_id=GOAL_ID,
    agent_id=AGENT_ID,
)
assert payload["should_run"] is True
assert payload["state"] == "eligible"

```

### Simulating Quota Exhaustion

To test pause behavior, inject a zero compute quota:

```python
status["goals"]["my-goal"]["quota"]["compute"] = 0
payload = build_quota_should_run(status, goal_id="my-goal")
assert payload["should_run"] is False
assert payload["pause_cause"] == "COMPUTE_QUOTA_ZERO"

```

## Source Code Architecture

The quota should-run mechanism spans several modules in the LoopX repository:

- **[`loopx/control_plane/quota/should_run.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/quota/should_run.py)** – Core implementation of `build_quota_should_run` and the three-phase decision pipeline.
- **[`loopx/control_plane/quota/should_run_prepare.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/quota/should_run_prepare.py)** – Candidate preparation logic including identity construction and scheduler hint generation.
- **[`loopx/control_plane/quota/should_run_packet.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/quota/should_run_packet.py)** – Payload construction, route logic, and final packet assembly.
- **[`loopx/quota.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/quota.py)** – Public API façade that forwards requests to the core control plane implementation.
- **[`loopx/cli_commands/quota_request.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/cli_commands/quota_request.py)** – Command-line interface for invoking quota checks during development and debugging.

## Summary

- The quota should-run mechanism operates through a **three-phase pipeline**: plan validation, candidate preparation, and route resolution.
- **Pause and health checks** provide early-exit conditions that prevent blocked or unhealthy goals from consuming resources.
- **Replay precedence** ensures settled historical actions cannot be overridden by new decisions, maintaining execution consistency.
- **Boundary guards and workspace checks** act as final safety nets that may veto execution even when quota is technically available.
- The system produces a **deterministic payload** containing `should_run`, `effective_action`, and detailed reasoning for every evaluation.

## Frequently Asked Questions

### What happens when an agent's quota is paused?

When an agent's quota is paused, the `_quota_item_is_paused` function detects the pause state and triggers `build_quota_paused_should_run_payload`. This immediately returns a payload with `should_run: false` and a `pause_cause` field indicating the specific reason, such as `COMPUTE_QUOTA_ZERO` or administrative suspension, preventing any further execution for that tick.

### How does LoopX handle replay precedence in quota decisions?

The mechanism calls `apply_settled_replay_route_precedence` during route resolution to ensure that any actions already settled in previous ticks (such as committed quota spends) maintain priority over new decisions. This prevents the system from overriding historical commitments when determining the current tick's execution rights.

### Can the should-run mechanism block execution even if compute quota is available?

Yes. Even with sufficient compute quota, the mechanism may block execution through **health blocks** (when `state = "blocked_health"`), **focus-wait overrides** (forcing the agent to wait for handoff completion), or **boundary-projection violations** (when workspace guards detect inbox priority mismatches or projection boundary violations).

### Where is the public API entry point for checking quota should-run status?

The public entry point is `build_quota_should_run` in [`loopx/quota.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/quota.py). This function accepts a status payload, goal ID, and optional agent ID, then delegates to the core implementation in [`loopx/control_plane/quota/should_run.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/control_plane/quota/should_run.py) to return a standardized payload containing the execution decision and supporting metadata.