The Ralph Wiggum Loop: Fresh-Context Iteration Pattern¶
The Ralph Wiggum Loop runs each iteration in a fresh context window, persisting state to disk so context never accumulates to the point of degradation.
The Pattern¶
Long agent sessions degrade as context fills. Early instructions get pushed out. The agent starts ignoring conventions it followed hours ago. Accumulated context is not a feature — it's a liability.
The Ralph Wiggum Loop addresses this by design: each iteration starts with a clean context window, reads persistent state from disk, completes a bounded unit of work, and writes results back before restarting. State lives in files, not in conversation history.
It works because LLM quality degrades non-linearly past roughly 60–70% context fill — a range practitioners call the "dumb zone". At that point, compaction begins discarding tokens to make room for new content; if the discarded tokens include original instructions or accumulated conventions, instruction-following deteriorates. Restarting with a fresh window prevents compaction entirely, keeping every iteration at full capacity.
Named and popularized by Geoff Huntley — see ghuntley.com/loop and ghuntley/how-to-ralph-wiggum — the pattern is now widely used for unattended and long-running agent workflows.
Cycle Structure¶
graph TD
A[Read state from disk] --> B[Plan bounded task]
B --> C[Execute]
C --> D[Write results to disk]
D --> E{More work?}
E -->|Yes| F[Restart fresh context]
F --> A
E -->|No| G[Done]
Read: The agent reads specs, AGENTS.md, task lists, progress markers, and any other persistent state from the file system at session start.
Plan: The agent identifies one bounded unit of work from the state. "Bounded" means completable within a single session without context pressure.
Execute: The agent completes the task using its tools.
Write: The agent writes results — output files, updated task lists, progress markers — back to disk before the session ends.
Restart: The next iteration opens a fresh context and reads the updated state.
What Counts as Persistent State¶
Any information the agent needs across iterations should live in files:
- Task lists and progress markers (which items are done, which are next)
- Specs and requirements
- AGENTS.md — conventions the agent reads at session start
- Partial outputs when a deliverable spans multiple iterations
Natural Recovery¶
If an iteration fails, the disk state reflects the last successful write. The next iteration reads that state and continues from there, without inheriting the failed session's context or misconceptions. Recovery is automatic.
Unattended Operation¶
The pattern enables unattended loops: a script restarts the agent after each iteration, checks CI or test results, and feeds the outcome back into disk state for the next cycle. The human reviews results periodically rather than supervising continuously.
This pairs well with worktree isolation — each iteration runs in a sandboxed environment, and failures don't contaminate the working directory.
Anti-Pattern: Infinite Session¶
Running one continuous session across many tasks means:
- Context fills over time, degrading instruction adherence
- Early session state colors later decisions
- A failure midway requires recovering from an unknown state
- No natural verification point between tasks
When This Backfires¶
The pattern assumes each iteration can be meaningfully bounded and verified. Several conditions break that assumption:
- Unbounded tasks: If a single unit of work cannot be completed in one context window, the loop stalls or produces partial output every cycle. Decompose further before looping.
- No progress signal: Without a reliable completion check (test suite, task-list marker, CI result), the loop can cycle indefinitely on a task it cannot solve, consuming tokens without converging.
- Shared mutable state: If multiple concurrent loop iterations write to the same files, later iterations may overwrite earlier progress. Use per-iteration output paths or explicit locking.
- Context-sensitive tasks: Tasks requiring deep continuity — extended negotiation, multi-turn clarification, stateful debugging sessions — do not benefit from fresh context. The lost context is load-bearing.
Practitioner reports add three caveats. Architectural coherence suffers — generated code reflects the agent's path to a working state, not an intentional structure (Wiggum breakdown). Cost scales fast: a fifty-iteration loop on a medium codebase typically runs $50–100+ in API credits (Leanware analysis). Worst, an agent facing an impossible task can "overbake" — iterate destructively, chasing a spurious error for hours — so Sondera's "Supervising Ralph" argues every loop needs a supervisor that detects non-convergence and halts; an iteration cap alone is a financial circuit breaker, not a quality gate.
Example¶
A bash wrapper script implements the loop externally, restarting the agent after each iteration:
#!/usr/bin/env bash
# loop-runner.sh - restarts the agent each cycle until the task list is empty
TASK_FILE="tasks.md"
MAX_CYCLES=20
CYCLE=0
while [[ $CYCLE -lt $MAX_CYCLES ]]; do
remaining=$(grep -c "^- \[ \]" "$TASK_FILE" 2>/dev/null || echo 0)
if [ "$remaining" -eq 0 ]; then
echo "All tasks complete."
exit 0
fi
echo "=== Cycle $((CYCLE + 1)) ==="
claude --no-cache --prompt "Read $TASK_FILE. Complete the next unchecked task. Mark it done. Write all output files. Stop."
CYCLE=$((CYCLE + 1))
done
echo "Max cycles reached." && exit 1
The agent prompt instructs it to read state, complete one bounded task, and write results. The --no-cache flag ensures a genuinely fresh context each cycle. The script exits when the task list is empty.
Key Takeaways¶
- Fresh context each iteration prevents the "dumb zone" that accumulates in long sessions.
- Persistent state belongs on disk, not in conversation history.
- Bounded tasks per iteration ensure each cycle is verifiable and recoverable.
- Failed iterations leave disk state at the last successful write — the next cycle continues cleanly.
Related¶
- AGENTS.md: A README for AI Coding Agents — project instruction file that agents read at session start for conventions and context
- Session Initialization Ritual — the disk-state read that opens each fresh-context cycle
- Worktree Isolation — sandboxes each iteration so failures don't contaminate the working directory
- Loop Strategy Spectrum — where fresh-context looping sits among other agent loop strategies
- Convergence Detection — the progress signal that stops a loop cycling on an unsolvable task
- Idempotent Agent Operations — design operations for safe retry across iterations
- Goal Monitoring and Progress Tracking — tracking progress across the multi-session iterations this pattern creates
- Cross-Cycle Consensus Relay — structured relay document that preserves decisions and forward momentum across fresh-context cycles