# The Control Loop

> Foundry's control loop executes a fixed sequence per task:

Source: https://bifrost5.com/foundry/docs/control-loop/

# Control Loop

Information

Steer this loop from the web, the mobile app, the terminal or chat notifications, whichever is in reach, with Production-Grade.

[See editions](/foundry/docs/editions)

Foundry's control loop executes a fixed sequence per task:

- **Load persisted state** from DragonflyDB

- **Read injected operator goal** from state

- **Select next task** from queue (FIFO or via Scheduler in parallel mode)

- **Dispatch task to tool** via CLI adapter (injecting required state context into task prompt)

- **Await completion** (Provider CLI execution)

- **Validate output** (deterministic, rule-based)

- **Persist updated state** immediately after mutation

- **Halt or continue** per explicit instruction

## Task Retrieval Guards

Before executing a dequeued task, `TaskRetriever` applies:

- **Completed-task guard**: Skips tasks already in `completed_tasks` (prevents re-execution after retry).

- **Redis task lock**: Acquires `SET NX EX 15` lock on `tasklock:{task_id}` (prevents competing consumers). Lock is released after finalization.

- **Dedup safety net**: `TaskFinalizer` and scheduler deduplicate before pushing to `completed_tasks` / `blocked_tasks`.

## Execution Stages

- **Local pre-processing** (Before Agent Call): Deterministic checks: regex safety validation, file/byte capacity enforcement, semver compatibility checks, code structure analysis. Run locally without API token cost.

- **Provider dispatch**: Task sent to Agents/Providers with state/context injection and session reuse when available.

- **Helper agent fallback**: When deterministic checks or provider output leave validation gaps, helper agent generates verification commands. Helper sessions are reused per project to retain context and reduce token consumption.

- **Analytics & metrics**: JSONL metrics (helper durations avg/p95, cache-hit rate, deterministic attempts/success, token usage) persisted alongside audit logs for cost visibility.

**Important Rules:**

- The supervisor never generates or reorders tasks. The task list is treated as closed and authoritative.

- Do not implement planning, decomposition, or task generation.

- If the task list is exhausted and the goal is incomplete → ask agent if goal is met, then HALT if incomplete.
