Skip to content
published Visibility internal Owner erik@uvilo.com Approver _ Created _ Updated _

6. Coding Agents — The Ralph Loop and Parallel Execution

Why Single Coding Sessions Fail

When you give a coding agent a big task and let it run, here’s what happens:

  1. The agent starts strong, making clean commits
  2. Around 30-40 minutes in, it accumulates context and starts degrading
  3. It hallucinates file paths, forgets earlier decisions, gets stuck in loops
  4. Eventually it crashes, stalls, or declares “done” when it obviously isn’t

This isn’t a model intelligence problem. It’s a context management problem. The longer a session runs, the more noise accumulates in the context window. Signal-to-noise degrades until the agent is effectively working drunk — confident but wrong.

The fix is almost embarrassingly simple: instead of one long session, run many short ones.


The Ralph Loop — Many Sprints, Not One Marathon

A Ralph loop (named after a concept popularized by Geoffrey Huntley) is a wrapper that repeatedly launches a coding agent with the same prompt until the work is actually done. Each iteration starts completely fresh — zero accumulated context. The agent picks up where the last one left off by reading the file system and git history.

┌─────────────────────────────────┐
│       Ralph Loop Wrapper        │
│                                 │
│  ┌──────────┐   Stalled?       │
│  │ Agent    │   Crashed?       │
│  │ Run #1   │   "Done" but     │
│  │          │   not really?    │
│  └────┬─────┘       │          │
│       │         ┌───▼────┐     │
│       │         │ Kill & │     │
│       │         │Restart │     │
│       │         └───┬────┘     │
│       │             │          │
│  ┌────▼─────┐       │          │
│  │ Agent    │◄──────┘          │
│  │ Run #2   │                  │
│  │ (fresh)  │  Actually done?  │
│  └────┬─────┘       │          │
│       │         ┌───▼────┐     │
│       ▼         │ Done!  │     │
│                 └────────┘     │
└─────────────────────────────────┘

The key insight: context is a cache, not state. If your agent can’t reconstruct its situation from the file system alone, your architecture has a single point of failure sitting in a context window that will inevitably degrade.


Writing Specs That Agents Can Execute — The PRD

The agent needs to know what “done” looks like. Use PRDs (Product Requirements Documents) written as markdown checklists:

# Beacon Auth Module — PRD

## Requirements
- JWT-based authentication with refresh tokens
- Rate limiting: 100 requests/min per user
- Support for API keys (service-to-service)

## Tasks
- [ ] Create POST /auth/login endpoint
- [ ] Create POST /auth/refresh endpoint  
- [ ] Create POST /auth/register endpoint
- [ ] Add input validation for all endpoints
- [ ] Implement rate limiting middleware
- [ ] Add API key authentication for service accounts
- [ ] Write integration tests for all auth flows
- [ ] Write unit tests for token generation/validation
- [ ] Update API documentation
- [ ] Run full test suite — all tests pass

The Ralph loop validates completion by checking if all boxes are ticked. Agent claims it’s done but 6/10 tasks are still open? Restarted. No negotiating with a confused model.

This sounds rigid. It is. A non-deterministic worker needs deterministic acceptance criteria. That’s the whole secret.


The Two-Model Split

Your best results come from splitting planning and execution across different models:

Planning (Opus/Claude — your role): Writing PRDs, breaking down architecture, defining task specs, reviewing output. Slower, more expensive, but excels at reasoning and system design.

Execution (Codex/Sonnet — the spawned agent’s role): The actual coding — implementing features, writing tests, fixing bugs. Fast, cheaper, optimized for code generation.

Think of it like a tech company: the architect doesn’t write every line of code, and the developer doesn’t redesign the system for every ticket. Each model plays to its strengths.


Test-Driven Prompts — The Secret Weapon

This single technique cuts post-merge failure rate significantly:

Write failing tests first that define the expected behavior,
then implement the code to make them pass. Run the test suite
before committing. All tests must pass.

Always include this in your PRD. Always.

Why it works: tests are deterministic acceptance criteria for a non-deterministic worker. When the agent writes the test first, it crystallizes exactly what “correct” means before writing any implementation. The test becomes a contract that the code must satisfy.

Skip this for trivial changes (config updates, copy edits, formatting). For anything with real logic — auth flows, data processing, API endpoints — TDD prompts are mandatory.


Running Agents in Parallel

Once the Ralph loop works for one project, the natural next step is parallelization. Run 3-4 agents simultaneously, each in its own isolated workspace using git worktrees:

# Each agent gets its own git worktree
git worktree add -b feature/auth /tmp/agent-auth main
git worktree add -b feature/api /tmp/agent-api main
git worktree add -b feature/ui /tmp/agent-ui main

# Launch parallel Ralph loops
ralphy --codex --prd auth-prd.md -C /tmp/agent-auth &
ralphy --codex --prd api-prd.md -C /tmp/agent-api &
ralphy --codex --prd ui-prd.md -C /tmp/agent-ui &

Three agents, three feature branches, zero interference. Each one has its own filesystem, its own git state, its own context. They can’t confuse each other because they literally can’t see each other.

Personal best: 108 tasks across 3 projects in about 4 hours. That’s a small engineering team’s weekly output.

⚠️ The main bottleneck with parallel agents is API rate limits. When all three compete for the same API quota, you’ll hit 429 errors. Space out launches by a few minutes, or use different API keys if available.


Git Worktrees — The Unsung Hero

Without worktrees, running multiple agents on the same repo means they’re fighting over the same working directory. Agent A changes a file, Agent B changes the same file — chaos.

Git worktrees solve this by creating multiple working directories from the same repository, each on its own branch:

# Create worktrees for parallel agents
git worktree add -b feature/auth /tmp/agent-auth main
git worktree add -b feature/api /tmp/agent-api main  
git worktree add -b feature/ui /tmp/agent-ui main

# Each worktree is a full working copy on its own branch
# Agents can't interfere with each other

# Clean up when done
git worktree remove /tmp/agent-auth
git worktree remove /tmp/agent-api
git worktree remove /tmp/agent-ui

Each agent gets its own isolated filesystem view of the repo. They share the same git history but can’t step on each other’s work. When they’re done, you merge each feature branch independently. This is the infrastructure that makes parallelization safe.


Keeping Agents Alive — tmux and Health Monitoring

Coding agents need to survive terminal restarts, network blips, and the occasional macOS housecleaning. Run every long-lived agent in a tmux session:

# Launch in a named tmux session
tmux new -d -s beacon-auth \
  "cd ~/Coding/beacon && ralphy --codex --prd auth-prd.md; \
   echo 'EXITED:' \$?; sleep 999999"

The sleep 999999 at the end keeps the session alive after the agent finishes so you can read the output.

Monitor on a heartbeat cycle:

  1. Is it alive? Check if the tmux session exists
  2. Is it making progress? Compare output to last check
  3. Is it stuck? Same output for two consecutive checks → kill and restart
  4. Is it done? Check if all PRD tasks are complete

If an agent dies, restart it. If it stalls, kill and relaunch. No human intervention required for routine failures.


Wake Hooks — Instant Completion Notification

Every tmux command includes a wake hook at the end:

; EXIT_CODE=$?; \
openclaw system event \
  --text "Ralph loop finished (exit $EXIT_CODE)" \
  --mode now; \
sleep 999999

When the agent finishes, this fires an event that pings you immediately. You know the moment work is done, whether you’re actively monitoring or not. No silent completions — no checking back an hour later to find it finished 55 minutes ago.


Avoiding the Common Failure Modes

“Agent reads files and exits.” The most common Ralph loop failure. The agent looks at the codebase, gets overwhelmed, and produces nothing. Fix: Make your PRD more specific. Break large tasks into smaller, unambiguous units.

“Agent marks tasks complete when they aren’t.” The loop checks PRD boxes, but the agent ticked them prematurely. Fix: Include verification steps — “Run test suite. All tests pass.” Not just “Write tests.”

“Agent fights itself across iterations.” Run 1 writes code, Run 2 reverts it, Run 3 rewrites it. Fix: Ensure each task is atomic. The agent should complete one task fully per iteration, not partially advance three.

“Works locally, fails in CI.” The agent tested locally but missed CI-specific requirements. Fix: Include “Run the full CI pipeline locally before marking complete” in your PRD.


When NOT to Use Coding Agents

Not everything should be delegated:

  • Exploratory/creative work — When you don’t know what the solution looks like, a human should explore first
  • One-line fixes — The overhead of a Ralph loop isn’t worth it. Just make the edit.
  • Security-critical code — Auth, encryption, payments: always human review, never auto-merge
  • Infrastructure changes — Database migrations, server config, DNS: too risky for autonomous agents

The sweet spot: well-defined feature work with clear acceptance criteria that would take a human developer a few hours to a full day. That’s where coding agents deliver 10x.


The Complete Daily Coding Workflow

  1. Morning planning (you, using Opus): Review what needs building. Write PRDs with clear task checklists and TDD requirements.
  2. Launch agents: Start Ralph loops in tmux sessions, one per project or feature branch. Log sessions in daily notes.
  3. Monitor on heartbeat: Every 15 minutes, check health of all running agents. Restart dead ones, kill stalled ones.
  4. Review output: When an agent completes, review the code — check git log, run tests, read the diff. Don’t blindly trust “all tasks complete.”
  5. Merge or iterate: Good code → merge the feature branch. Bad code → update PRD with corrections, relaunch.
  6. Evening wrap-up: Check all agents, kill stragglers, commit progress notes.

The Economics

Traditional approach: hire a contract developer at $100-150/hour. A 108-task backlog would take an experienced developer roughly 40-60 hours: $4,000-9,000.

The coding agent approach: API costs for running 3 parallel agents for 4 hours, plus coordination time on Opus: approximately $50-100 in API spend. Plus your operator’s review time: about 2 hours.

That’s not a typo. The cost difference is 50-100x.

Caveats: the AI-generated code needs review. Some tasks will need re-runs. The PRD writing takes time upfront. But even accounting for all of that, the economics are compelling enough to shift virtually all routine feature development to the coding agent pipeline.

The sweet spot isn’t “AI replaces developers.” It’s “AI handles the well-defined work while humans focus on architecture, design, and the problems that require genuine creativity.”

Your operator still architects every major feature. They still review every PR. They still make the decisions that matter. But the implementation grunt work — the forty endpoints that follow the same pattern, the test coverage that needs to exist, the CRUD operations that are tedious but necessary — that’s agent work now.

The mental shift that makes this work: you are the engineering manager, not the developer. Your job is to understand what needs to be built well enough to write a precise PRD, launch the right agent with the right spec, monitor health and restart failures, and review output before it gets merged. You don’t write the code. You shape the work, supervise the execution, and maintain the quality bar.