# Ralph Loop The Ralph Loop is an AI agent execution pattern where an agent stubbornly iterates on tasks, failing repeatedly but never giving up until it finally succeeds. It's the core execution model of [[Ralph TUI]] and embodies the [[Ralph Wiggum Technique]]. Named after The Simpsons character [[Ralph Wiggum]]; known for being clueless yet relentlessly persistent—the loop recognizes that [[AI Agents]] may not succeed on the first try, but with persistence and good error handling, they can complete complex multi-step tasks autonomously. ## The Loop Structure ``` ┌─────────────────────────────────────────────┐ │ RALPH LOOP │ │ │ │ ┌─────────┐ │ │ │ START │ │ │ └────┬────┘ │ │ ▼ │ │ ┌─────────┐ ┌─────────┐ │ │ │ SELECT │────►│ BUILD │ │ │ │ TASK │ │ PROMPT │ │ │ └─────────┘ └────┬────┘ │ │ ▲ ▼ │ │ │ ┌─────────┐ │ │ │ │ RUN │ │ │ │ │ AGENT │ │ │ │ └────┬────┘ │ │ │ ▼ │ │ │ ┌─────────┐ ┌───────┐ │ │ │ │ CHECK │───►│ DONE │ │ │ │ │ RESULT │ └───────┘ │ │ │ └────┬────┘ │ │ │ │ │ │ │ fail │ │ │ └───────────────┘ │ │ │ └─────────────────────────────────────────────┘ ``` ## How It Works 1. **Select Task**: Pick the next available task from the task source ([[Beads]], prd.json) 2. **Build Prompt**: Construct a prompt with task details, context, and history 3. **Run Agent**: Execute the AI coding agent ([[Claude Code]], etc.) 4. **Check Result**: Detect completion token or failure 5. **Iterate**: On failure, loop back with error context; on success, move to next task ## Key Principles ### Persistence Over Perfection The loop doesn't expect the agent to succeed immediately. It expects: - Multiple attempts per task - Incremental progress through failures - Learning from error messages - Eventually reaching success ### Error as Input Failed attempts aren't discarded—they become context for the next iteration: - Error messages inform the next prompt - Failed approaches are documented - The agent builds understanding through failure ### Completion Detection The loop detects success via explicit tokens: ``` <promise>COMPLETE</promise> ``` This prevents premature termination and ensures tasks are truly finished. ## Comparison to Traditional Loops | Aspect | Traditional Script Loop | Ralph Loop | |--------|------------------------|------------| | Failure handling | Stop or retry same action | Adapt and try different approach | | Context | Lost between iterations | Preserved and accumulated | | Intelligence | None (mechanical retry) | LLM-powered reasoning | | Recovery | Manual intervention | Self-healing attempts | ## When to Use - Long-running autonomous coding tasks - Tasks with uncertain completion criteria - Multi-step workflows where steps may fail - Overnight or unattended agent execution ## References - https://ralph-tui.dev - https://github.com/subsy/ralph-tui ## Related - [[Ralph Wiggum Technique]] - [[Ralph TUI]] - [[AI Agents]] - [[AI Agent Swarms]] - [[Claude Code]] - [[Beads]]