Skip to main content

Ralph Wiggum Autonomous Agent Guide

What is Ralph Wiggum?

Ralph Wiggum is CODITECT's autonomous agent loop pattern that enables long-running tasks to execute across multiple context windows while maintaining quality and avoiding degradation.

Core Insight: Single-context loops degrade over time due to context bloat, token exhaustion, and attention drift. Fresh-context iterations maintain quality by:

  • Checkpointing state between iterations
  • Starting each iteration with a clean context
  • Monitoring health and intervening when degradation occurs
  • Tracking token economics to prevent budget overruns

Named after the Ralph Wiggum pattern — a recognition that starting fresh often beats trying to salvage a degraded context.

Architecture

Ralph Wiggum combines four core services into a unified orchestration layer:

1. Checkpoint & Handoff (ADR-108)

Purpose: Save and restore agent state across context windows.

CheckpointService captures:

  • Task state (goals, progress, blockers)
  • Conversation history (condensed)
  • Decisions made and rationale
  • Next steps and dependencies
  • Files created/modified

Usage:

# Automatic checkpoints every N iterations
/ralph-loop start --checkpoint-interval 5

# Manual checkpoint
/checkpoint save --task X.n.n --message "Completed Phase 1"

# List checkpoints
/checkpoint list --task X.n.n

# Resume from checkpoint
/ralph-loop start --resume-from <checkpoint-id>

2. QA Agent Browser Automation (ADR-109)

Purpose: Automated testing and validation for agent-generated code.

QAAgentBrowserTools provides:

  • Visual regression testing
  • Accessibility validation (WCAG AA)
  • Responsive design verification
  • User flow testing

Integration: Loop orchestrator automatically triggers QA validation after code changes.

3. Health Monitoring (ADR-110)

Purpose: Detect degradation patterns and intervene before failure.

Health States:

  • HEALTHYDEGRADEDSTUCKFAILINGTERMINATED

Degradation Patterns:

  • stuck_loop: Same action repeated 3+ times
  • error_spiral: Consecutive errors increasing
  • budget_drift: Cost growth exceeds 20% per iteration
  • context_bloat: Token usage >80% of limit
  • diminishing_returns: Progress <10% of iteration cost

Circuit Breaker: Opens after 5 consecutive failures, half-open retry after cooldown.

Intervention Levels:

  • NUDGE: Warning logged, continue
  • ESCALATE: Pause loop, require human review
  • TERMINATE: Stop loop immediately

4. Token Economics (ADR-111)

Purpose: Track costs and enforce budgets across loop iterations.

TokenEconomicsService tracks:

  • Cost per iteration
  • Cumulative cost
  • Budget utilization %
  • Cost per unit of progress

Budget Actions:

  • ALLOW: Within budget
  • THROTTLE: 80-100% budget used, reduce model tier
  • DENY: Budget exhausted, stop loop
  • ALERT_ONLY: Log warning, continue

Loop Orchestrator

LoopOrchestrator (H.8.6) combines all services into a unified control plane.

Loop Lifecycle

INITIALIZING → RUNNING → [PAUSED/HANDOFF] → COMPLETING → [COMPLETED | FAILED | TERMINATED]

Configuration

LoopConfig(
max_iterations=10, # Stop after 10 iterations
max_cost=50.0, # Budget limit in USD
max_duration_minutes=120, # Timeout after 2 hours
agent_type="senior-architect",
model="claude-opus-4-6",
checkpoint_interval=5, # Checkpoint every 5 iterations
health_check_interval=1 # Check health every iteration
)

Termination Criteria (Priority Order)

  1. Circuit breaker open: Consecutive failures exceeded
  2. Health check failure: State reached FAILING
  3. Consecutive errors: 3+ errors in a row
  4. Budget exhausted: max_cost reached
  5. Max iterations: Iteration limit reached
  6. Max duration: Time limit exceeded
  7. No progress: 3+ iterations with no measurable progress

Commands

Start a Loop

# Basic loop
/ralph-loop start --task H.8.1 --goal "Implement user auth" --agent senior-architect

# With budget and iteration limits
/ralph-loop start --task H.8.1 --goal "Refactor API" \
--max-iterations 10 --max-cost 50 --agent backend-api-expert

# Resume from checkpoint
/ralph-loop start --resume-from checkpoint-abc123

Monitor Loops

# Check status
/ralph-loop status <loop-id>

# List all loops
/ralph-loop list

# View health
/health-status

# View token economics
/token-status

# Cost report
/cost-report

Control Loops

# Stop a loop
/ralph-loop stop <loop-id>

# Generate report
/ralph-loop report <loop-id>

# Pause (creates checkpoint)
/ralph-loop pause <loop-id>

Monitoring Agent

The ralph-loop-monitor agent continuously watches for degradation patterns:

# Deploy monitoring agent
/agent ralph-loop-monitor "Monitor loop-abc123"

Graduated Intervention:

PatternSeverityAction
Token usage >60%LowNUDGE: Log warning
Stuck loop (3 repeats)MediumESCALATE: Pause for review
Error spiral (5 errors)HighTERMINATE: Stop immediately

Example Workflows

Basic Feature Development Loop

# Start loop
/ralph-loop start \
--task A.9.1 \
--goal "Add OAuth2 authentication to API" \
--agent backend-api-expert \
--max-iterations 8 \
--max-cost 30

# Loop executes:
# 1. Analyze requirements
# 2. Generate implementation plan
# 3. Write code
# 4. Run tests (via QA browser tools)
# 5. Fix issues
# 6. Checkpoint progress
# 7. Repeat until complete or limits reached

# Monitor progress
/ralph-loop status loop-abc123

# Stop if needed
/ralph-loop stop loop-abc123

Resume After Degradation

# Loop degraded and paused at iteration 6
# Review checkpoint
/checkpoint list --task A.9.1

# Resume with fresh context
/ralph-loop start --resume-from checkpoint-def456 --max-iterations 5

Best Practices

  1. Set realistic budgets: Estimate $5-10 per iteration for complex tasks
  2. Checkpoint frequently: Every 3-5 iterations for long loops
  3. Monitor health: Watch for stuck loops and error spirals
  4. Use appropriate agents: Match agent expertise to task domain
  5. Define clear goals: Specific, measurable success criteria
  6. Review checkpoints: Before resuming, verify state is correct

Integration with CODITECT

Ralph Wiggum loops integrate seamlessly with:

  • Task Tracking: Loop progress updates TRACK files automatically
  • Session Logs: Each iteration logged with task ID and cost
  • ADR Compliance: Loops validate against architectural decisions
  • Component Registry: Created components auto-registered

Troubleshooting

IssueCauseSolution
Loop stuckRepeated actionsCheck health status, review last checkpoint
Budget overrunUnderestimated complexityIncrease max_cost or reduce scope
Context bloatLarge file operationsReduce checkpoint detail level
QA failuresCode quality issuesReview agent selection, add explicit requirements

Reference

  • ADR-108: Checkpoint & Handoff Protocol
  • ADR-109: QA Agent Browser Automation
  • ADR-110: Health Monitoring System
  • ADR-111: Token Economics
  • Track H.8: Ralph Wiggum Implementation

Next Steps:

  1. Read Loop Orchestrator Design
  2. Try starting your first loop: /ralph-loop start --task X.n.n --goal "..."
  3. Monitor with: /ralph-loop status <loop-id>