Chapter 6 of 8
Roo Code Loop Engineering Guide
Building reliable autonomous loops with Roo Code — multi-model support, mode switching, and production loop patterns.
Roo Code Loop Engineering Guide
Roo Code (github.com/RooCodeInc/Roo-Code) is an open-source AI coding agent forked from Cline that has become one of the most capable tools for loop engineering workflows. Its defining advantage is multi-model support — you can route different loop iterations to Claude, GPT-4, Gemini, or local models through Ollama, switching providers per task without leaving your editor. Combined with its specialized modes and intelligent context condensing, Roo Code lets you build production-grade autonomous loops that run longer and cost less than single-model agents.
This guide maps Roo Code's architecture to loop engineering patterns, covers multi-model loop strategies, and walks through a real verify-and-fix loop implementation.
What Makes Roo Code Different
Roo Code stands apart from other AI coding agents in three ways that directly impact loop engineering:
| Feature | Roo Code | Claude Code | Cursor |
|---|---|---|---|
| Model providers | Claude, GPT-4, Gemini, local (Ollama), 500+ via API router | Anthropic only | Claude + GPT-4 |
| Specialized modes | Code, Architect, Ask, Debug, Orchestrator + custom modes | Single unified agent | Chat vs. Agent mode |
| Context management | Intelligent Context Condensing (automatic) | Cache-based optimization | Implicit management |
| Configuration | .clinerates custom modes, .roo/mcp.json | CLAUDE.md + hooks | .cursorrules + .cursor/mcp.json |
| IDE base | VS Code extension (fork of Cline) | CLI tool | Forked VS Code |
| Open source | Yes (MIT) | No | No |
| MCP support | Full support, per-project config | Full support | Full support |
| Mode-specific model routing | Yes — different model per mode | No — single model per session | No — single model per session |
The critical loop engineering advantage is mode-specific model routing. You can assign a fast, cheap model to Code mode for verification edits while running a powerful model in Architect mode for complex reasoning — something neither Claude Code nor Cursor supports natively.
Roo Code Architecture for Loop Engineering
Understanding Roo Code's internal architecture is essential for designing effective loops:
┌─────────────────────────────────────────────────────────────┐
│ ROO CODE AGENT │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ MODE ORCHESTRATOR │ │
│ │ Orchestrator → Architect → Code → Debug → Ask │ │
│ │ + Custom modes (user-defined) │ │
│ └────────────────────┬────────────────────────────────┘ │
│ │ Task + Mode Context │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ MODEL PROVIDER LAYER │ │
│ │ │ │
│ │ Mode-specific routing: │ │
│ │ Architect ──► Claude Opus 4 (deep reasoning) │ │
│ │ Code ──► Claude Sonnet 4 (balanced speed) │ │
│ │ Debug ──► GPT-4o (strong at error tracing) │ │
│ │ Ask ──► Claude Haiku 4.5 (fast, cheap) │ │
│ └────────────────────┬────────────────────────────────┘ │
│ │ Tool Calls │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ TOOL LAYER │ │
│ │ │ │
│ │ - File read/write/edit │ │
│ │ - Terminal command execution │ │
│ │ - Browser automation (web access, docs) │ │
│ │ - MCP servers (.roo/mcp.json) │ │
│ │ - Code search (grep, glob, semantic) │ │
│ └────────────────────┬────────────────────────────────┘ │
│ │ Results │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ CONTEXT MANAGER │ │
│ │ │ │
│ │ Intelligent Context Condensing: │ │
│ │ - Monitors token usage per threshold │ │
│ │ - Summarizes older conversation turns │ │
│ │ - Preserves critical decisions and context │ │
│ │ - Enables sessions beyond 200K token windows │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ FEEDBACK LOOP: Tool results → Context Manager → │
│ Mode Orchestrator → Model → Tools (iterate) │
└─────────────────────────────────────────────────────────────┘
Each layer maps to a stage in the loop engineering cycle. The Mode Orchestrator handles Define Goal, the Model Provider handles Act, the Tool Layer provides Observe, and the Context Manager ensures Verify by maintaining coherent state across iterations.
Loop Patterns with Roo Code Modes
Roo Code's modes map naturally to loop engineering phases. Understanding which mode to use at each stage of the loop is the key to building effective autonomous workflows.
Code Mode: The Execution Loop
Code mode is Roo Code's primary implementation mode. The agent reads files, writes edits, runs terminal commands, and iterates on errors. In loop engineering terms, this is your Act → Observe → Verify cycle.
Code mode excels at:
- Multi-file edits with automatic verification
- Running test suites and fixing failures iteratively
- Applying linting and formatting corrections
- Refactoring with type-checking feedback
Architect Mode: The Planning Loop
Architect mode reasons about systems without writing code directly. It analyzes codebase structure, identifies dependencies, and produces implementation plans. In loop engineering terms, this is your Define Goal phase.
Architect mode excels at:
- Breaking large features into implementation steps
- Identifying architectural constraints before coding
- Designing migration plans and upgrade paths
- Cross-referencing codebase patterns for consistency
Debug Mode: The Diagnostic Loop
Debug mode focuses on investigating failures — reading error logs, tracing stack traces, and identifying root causes. This maps to the Observe → Define Goal transition in a recovery loop.
Ask Mode: The Research Loop
Ask mode answers questions about the codebase and context without making changes. Use it to gather information before switching to Architect or Code mode for action.
Orchestrator Mode: The Meta-Loop
Orchestrator mode is Roo Code's top-level coordinator. It can autonomously delegate tasks to other modes, creating a multi-phase loop where Architect plans, Code executes, and Debug validates — all within a single unattended session.
┌──────────────────────────────────────────────────────┐
│ ORCHESTRATOR LOOP │
│ │
│ 1. RECEIVE user task │
│ 2. DELEGATE to Architect mode ──► generate plan │
│ 3. DELEGATE to Code mode ──► implement plan │
│ 4. DELEGATE to Debug mode ──► verify + fix │
│ 5. DELEGATE to Ask mode ──► assess quality │
│ 6. ITERATE if verification fails (back to step 3) │
│ 7. TERMINATE when all checks pass │
│ │
│ The switch_mode tool enables seamless transitions │
│ between modes without user intervention. │
└──────────────────────────────────────────────────────┘
The switch_mode tool is what makes this possible — the agent can autonomously transition between modes mid-session, something no other coding agent offers at this granularity.
Multi-Model Loop Strategy
The most powerful loop engineering pattern with Roo Code is model-per-mode routing. Rather than running every iteration on an expensive frontier model, you assign models based on the cognitive demands of each loop phase.
Cost-Optimized Model Assignment
| Loop Phase | Mode | Recommended Model | Rationale |
|---|---|---|---|
| Plan architecture | Architect | Claude Opus 4 | Deep reasoning for complex system design |
| Implement code | Code | Claude Sonnet 4 | Strong coding ability, moderate cost |
| Quick edits/fixes | Code | Claude Haiku 4.5 | Fast turnaround for simple changes |
| Diagnose errors | Debug | GPT-4o | Excellent at error tracing and log analysis |
| Answer queries | Ask | Claude Haiku 4.5 | Speed matters more than depth |
| Verify results | Code | Claude Sonnet 4 | Reliable test interpretation |
This tiering follows the same principle as Aider's --architect-model and --model flags, but applied at the mode level within a single agent. The cost savings are substantial — a typical refactoring session that might cost $2.50 running entirely on Opus drops to roughly $0.40–0.60 when verification and simple edits are offloaded to Sonnet and Haiku.
Configuring Model-per-Mode
In Roo Code's settings, you configure the model for each mode independently. The configuration lives in your Roo Code settings panel (accessible via the extension sidebar) and persists across sessions:
- Open Roo Code in VS Code
- Navigate to the mode selector
- For each mode, set the provider and model separately
- Save as a workspace profile for reuse
For teams, Roo Code supports workspace-level configuration that can be shared through version control, ensuring consistent model routing across all developers' loop engineering workflows.
Setting Up Roo Code for Loop Engineering
Step 1: Install and Configure Providers
Install Roo Code from the VS Code marketplace. Then configure your API providers:
- Anthropic: Add your API key for Claude models (Opus, Sonnet, Haiku)
- OpenAI: Add your API key for GPT-4o and other OpenAI models
- Google: Add your API key for Gemini models
- Local models: Configure Ollama endpoint for models like Llama, Mistral, or Qwen
Each provider is configured independently, and you can mix providers across modes in a single session.
Step 2: Configure MCP Servers
Roo Code uses .roo/mcp.json for MCP server configuration, introduced in version 3.11. This file lives at your project root and defines external tool integrations:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
"playwright": {
"command": "npx",
"args": ["-y", "@playwright/mcp@latest"]
}
}
}
MCP servers extend the tool layer, giving your loops access to GitHub operations, filesystem browsing, browser automation, and custom tools. For loop engineering specifically, the Playwright MCP server is valuable for verify loops that need to check rendered UI output, while the GitHub MCP server enables PR creation and review as loop termination conditions.
Step 3: Set Up .clinerates for Loop Rules
The .clinerates file (a convention inherited from Cline, which Roo Code extends) stores custom mode definitions and project-level instructions. Create one in your project root:
# Loop Engineering Configuration
## Verification Rules
- After any code change, run the project's test suite
- Check TypeScript types with `npx tsc --noEmit` before proceeding
- Run the linter (`eslint --fix`) automatically after edits
- If tests fail, attempt a fix no more than 3 times before requesting help
## Code Standards
- Follow existing patterns in the codebase
- No `any` types in TypeScript files
- All new functions must have corresponding tests
- Import paths must be relative, not absolute
## Loop Behavior
- In Code mode: always verify changes compile and pass tests
- In Architect mode: produce numbered implementation steps
- In Debug mode: always identify root cause, not just symptoms
- Maximum 5 iterations on a single subtask before escalation
Step 4: Enable Context Condensing
Roo Code's Intelligent Context Condensing is a critical feature for loop engineering. Long-running loops accumulate conversation history that eventually exhausts the model's context window. Context condensing solves this by:
- Monitoring token usage against a configurable threshold
- Automatically summarizing older conversation turns when the threshold is reached
- Preserving critical decisions, file states, and error context
- Replacing the full history with a condensed version in the model's input
This means your loops can run indefinitely — the context manager ensures the agent never loses track of what it is doing, even across hundreds of iterations. Enable it in Roo Code's settings under the experimental features section, and set the condensing threshold (typically 70–80% of your model's context window).
Comparison: Roo Code vs. Claude Code vs. Cursor for Loop Engineering
Each tool has distinct strengths for different loop engineering scenarios.
Architecture Comparison
CLAUDE CODE CURSOR ROO CODE
──────────── ────── ─────────
Single agent Chat / Agent modes 5 specialized modes
Single model 2 models (Claude/GPT) Model per mode
CLI-based IDE-based IDE-based
CLAUDE.md config .cursorrules config .clinerates config
Native hooks system Implicit workflow switch_mode tool
High code quality Fast tab completion Maximum flexibility
Anthropic ecosystem VS Code ecosystem Multi-provider ecosystem
Loop Engineering Feature Comparison
| Capability | Roo Code | Claude Code | Cursor |
|---|---|---|---|
| Multi-model routing | 5+ providers, per-mode | Anthropic only | 2 providers |
| Mode-specific behavior | 5 default + custom modes | Hooks + CLAUDE.md | Chat vs. Agent |
| Context condensing | Automatic, configurable | Cache-based | Implicit |
| Autonomous mode switching | Yes (switch_mode tool) | No | No |
| Terminal access | Yes | Yes | Yes |
| Browser tool | Yes | No | No |
| MCP support | Full | Full | Full |
| Parallel agents | No | Yes (subagents) | Yes (up to 8) |
| Open source | Yes | No | No |
| Cost optimization | Best (model tiering) | Limited (cache only) | Moderate |
| Loop persistence | Context condensing | Session-based | Session-based |
When to Choose Roo Code
Choose Roo Code when:
- You need multi-model flexibility — routing different loop phases to different providers
- Your loop requires specialized modes — planning separately from implementation
- Cost optimization matters — tiering models across modes can reduce costs by 80%
- You want open-source tooling with no vendor lock-in
- Your loops need context condensing for long-running sessions
Choose Claude Code when:
- You need the highest code quality (80.8% SWE-bench, roughly 3x edits-per-minute of Cline)
- Your workflow is CLI-native or runs in terminal environments
- You want the most polished agent loop out of the box
Choose Cursor when:
- You need parallel agents (up to 8 simultaneous loops in isolated worktrees)
- Tab completion speed is your primary concern
- You prefer the Composer UI for multi-file editing workflows
Real Example: Building a Verify-and-Fix Loop
Here is a practical loop engineering pattern: an automated verify-and-fix loop that runs tests, identifies failures, and iterates on fixes until the suite passes — all using Roo Code's mode system.
Loop Design
┌─────────────────────────────────────────────────────┐
│ VERIFY-AND-FIX LOOP (Roo Code) │
│ │
│ 1. ARCHITECT MODE │
│ Analyze failing tests → identify affected files │
│ Output: numbered fix plan │
│ │
│ 2. CODE MODE (Sonnet 4) │
│ Implement fixes from plan, one file at a time │
│ After each edit: run affected tests │
│ │
│ 3. DEBUG MODE (GPT-4o) │
│ If tests still fail: trace error to root cause │
│ Output: refined diagnosis │
│ │
│ 4. CODE MODE (Sonnet 4) │
│ Apply Debug diagnosis → edit → re-test │
│ │
│ 5. ASK MODE (Haiku 4.5) │
│ Verify: are all tests passing? Any regressions? │
│ │
│ 6. ITERATE: if failures remain, return to step 2 │
│ 7. TERMINATE: all tests pass, report summary │
│ │
│ Max iterations: 10 (safety bound) │
│ Context condensing: enabled at 75% threshold │
└─────────────────────────────────────────────────────┘
Implementation
To execute this loop in Roo Code, start in Orchestrator mode and describe the task:
I have 3 failing tests in the auth module:
- tests/auth/login.test.ts (test: "should reject expired tokens")
- tests/auth/refresh.test.ts (test: "should rotate refresh token")
- tests/auth/session.test.ts (test: "should invalidate on password change")
Run a verify-and-fix loop:
1. Use Architect mode to analyze the failing tests and create a fix plan
2. Use Code mode to implement fixes
3. Use Debug mode if tests still fail after fixes
4. Use Ask mode to confirm all tests pass
5. Repeat until all 3 tests pass
Maximum 10 iterations.
The Orchestrator delegates to each mode in sequence. The switch_mode tool handles transitions automatically. Context condensing ensures the loop can run the full 10 iterations without exhausting the context window, even if each iteration produces substantial tool output.
This pattern is particularly effective because Debug mode uses GPT-4o, which excels at error tracing, while Code mode uses Sonnet, which is faster and cheaper for the actual edits. You get the right model for each phase without manual switching.
Best Practices for Loop Engineering with Roo Code
Mode Switching Discipline
The most common mistake with Roo Code is over-using Code mode for everything. Each mode exists because different loop phases require different cognitive strategies:
- Always start complex tasks in Architect mode — the planning step prevents wasted iterations
- Use Debug mode for diagnosis, not Code mode — Debug mode's system prompt is optimized for error analysis
- Reserve Ask mode for verification questions — it is faster and cheaper than running Code mode for a simple status check
- Let Orchestrator handle multi-phase workflows — manual mode switching introduces coordination errors
Context Management
Long-running loops generate enormous context. Roo Code's context condensing helps, but you should also:
- Set the condensing threshold to 70–75% of your model's context window — too late and the agent loses coherence before condensing triggers
- Break large tasks into subtasks — a single loop should not attempt to modify more than 5–10 files
- Use Architect mode to produce a concise plan first — this plan serves as a persistent reference that survives context condensing
- Monitor the context indicator in Roo Code's UI to see when condensing has occurred
Cost Optimization with Multi-Model Routing
For teams running Roo Code at scale, model-per-mode routing is the single largest cost lever:
| Strategy | Cost Impact | Quality Impact |
|---|---|---|
| All iterations on Opus 4 | Baseline (highest cost) | Highest quality |
| Architect=Opus, Code=Sonnet, Ask=Haiku | ~60% reduction | Minimal quality loss |
| Architect=Opus, Code=Sonnet, Debug=GPT-4o, Ask=Haiku | ~70% reduction | Comparable quality |
| All iterations on Haiku | ~95% reduction | Significant quality loss on complex tasks |
The sweet spot for most loop engineering workflows is the three-tier configuration: Opus for planning, Sonnet for implementation, Haiku for verification. This preserves quality where it matters (architectural reasoning) while reducing cost on the high-volume phases (code edits and test verification).
Safety Bounds
Every autonomous loop needs termination conditions. Configure these in your .clinerates:
## Loop Safety
- Maximum 10 iterations per subtask
- Maximum 50 total tool calls per session
- If 3 consecutive iterations produce identical test results, stop and escalate
- If context has been condensed more than 3 times, pause for user review
- Never delete files without explicit confirmation
- Never modify CI/CD configuration without explicit confirmation
These bounds prevent runaway loops that waste tokens and potentially make destructive changes. The context condensing limit is particularly important — after several condensing cycles, the agent may lose critical context that a human reviewer should assess.
Key Takeaways
-
Roo Code's multi-model routing is its defining loop engineering advantage. Assign models per mode to optimize cost without sacrificing quality — use Opus for planning, Sonnet for coding, Haiku for verification.
-
Mode-specific behavior (Code, Architect, Debug, Ask, Orchestrator) maps directly to loop engineering phases. Use the right mode for each phase rather than forcing everything through a single interaction pattern.
-
Intelligent Context Condensing enables loops that run far beyond typical context window limits. Configure the threshold at 70–75% and pair it with concise Architect-mode plans that survive condensing.
-
The Orchestrator + switch_mode tool enables fully autonomous multi-phase loops. The agent can plan, implement, debug, and verify without manual intervention — something no other single coding agent provides at this granularity.
-
Roo Code complements, rather than replaces, Claude Code and Cursor. Use Roo Code when multi-model flexibility and mode specialization matter; use Claude Code for maximum code quality; use Cursor for parallel agent workflows.