Master iterative AI loops, git worktrees, hybrid models, and power workflows
This lesson covers power-user techniques that combine everything you've learned into advanced workflows. The star of the show is the Ralph Wiggum technique — a continuous, self-referential AI loop that iterates until completion.
Ralph Wiggum is a development methodology created by Daisy Hollman at Anthropic. It's based on continuous, self-referential AI agent loops.
Named after Ralph Wiggum from The Simpsons, it embodies the philosophy of persistent iteration despite setbacks.
Traditional approach:
You → give Claude a task → Claude tries once → done (or stuck)
Ralph approach:
You → give Claude a task → Claude works → tries to exit →
hook blocks exit → feeds SAME prompt back →
Claude sees its previous work in files →
improves → tries to exit → hook blocks again →
repeat until completion signal
The key insight: the prompt never changes between iterations, but Claude's previous work persists in files. Each loop, Claude reads its own past output and improves on it.
Ralph is implemented as a Claude Code plugin that uses a Stop hook to intercept session exits:
/ralph-loop "Your task" --completion-promise "DONE"Full access
Unlock all 14 lessons, templates, and resources for Claude Code Mastery. Free.
The loop happens inside your current session — no external bash loops needed.
/plugin marketplace add anthropics/claude-code
/plugin install ralph-wiggum@claude-code-plugins
/ralph-loop "Build a REST API for todos. Requirements: CRUD operations,
input validation, tests. Output <promise>COMPLETE</promise> when done." \
--completion-promise "COMPLETE" \
--max-iterations 50
/cancel-ralph
Q: Why does the Ralph Wiggum technique work even though the prompt never changes?
Because Claude's previous work persists in files. Each iteration, Claude reads the files it created/modified in previous loops and sees what still needs to be done. The git history shows what changed. So even though the prompt is identical, the context is different every time — Claude builds on its own past output and progressively improves the work.
❌ Bad: "Build a todo API and make it good."
✅ Good:
Build a REST API for todos.
When complete:
- All CRUD endpoints working
- Input validation in place
- Tests passing (coverage > 80%)
- README with API docs
- Output: <promise>COMPLETE</promise>
Phase 1: User authentication (JWT, tests)
Phase 2: Product catalog (list/search, tests)
Phase 3: Shopping cart (add/remove, tests)
Output <promise>COMPLETE</promise> when all phases done.
Implement feature X following TDD:
1. Write failing tests
2. Implement feature
3. Run tests
4. If any fail, debug and fix
5. Refactor if needed
6. Repeat until all green
7. Output: <promise>COMPLETE</promise>
# ALWAYS set max-iterations as a safety net
/ralph-loop "Try to implement feature X" --max-iterations 20
Gotcha: Without
--max-iterations, the loop runs indefinitely. Always set a limit!
Include a stuck-state escape in your prompt:
After 15 iterations, if not complete:
- Document what's blocking progress
- List what was attempted
- Suggest alternative approaches
Q: What happens if you forget to set --max-iterations?
The loop runs indefinitely until Claude outputs the completion promise — or you manually cancel with /cancel-ralph. This can burn through tokens quickly. Always set --max-iterations as a safety net, even if you expect completion in fewer iterations.
Fill in the blanks:
/ralph-___ "prompt"/cancel-___--completion-___ "TEXT"/ralph-loop/cancel-ralph--completion-promiseRun multiple Claude Code instances on the same repo without conflicts:
# Create worktrees
git worktree add ../my-project-auth feat/auth
git worktree add ../my-project-api feat/api
git worktree add ../my-project-tests feat/tests
# Run Claude in each
cd ../my-project-auth && claude &
cd ../my-project-api && claude &
cd ../my-project-tests && claude &
Each worktree gets its own working directory, branch, Claude Code session, and auto memory directory.
| Approach | Best For |
|---|---|
| Worktrees | Independent features, long-running tasks, full isolation |
| Agent Teams | Coordinated work, shared context, communication needed |
The opusplan model alias automatically switches models based on mode:
| Mode | Model | Reasoning |
|---|---|---|
| Plan mode | Opus | Superior reasoning for architecture |
| Execution mode | Sonnet | Efficient for code generation |
claude --model opusplan
/model opus
> Plan the migration to microservices architecture
/model sonnet
> Implement phase 1 of the plan
Q: When would you use opusplan instead of just opus?
Use opusplan when you need Opus-quality reasoning for planning but don't want to pay Opus prices for the implementation. The hybrid model automatically uses Opus when Claude is thinking/planning and Sonnet when writing code. This gives you the best of both worlds — deep reasoning where it matters, efficient execution where it doesn't.
# 1. Research with Plan Mode
claude --permission-mode plan
> Analyze the authentication system and identify weaknesses
# 2. Plan the fix
> Create a detailed plan to migrate to OAuth2
# 3. Switch to execution (Shift+Tab)
> Implement the plan
# 4. Spawn a reviewer subagent
> Use the code reviewer agent to review these changes
#!/bin/bash
# Step 1: Review
issues=$(claude -p "Review staged changes" --output-format json | jq -r '.result')
# Step 2: Fix
if [ "$issues" != "No issues found" ]; then
claude -p "Fix these issues: $issues" --allowedTools "Read,Edit,Bash(npm run *)"
fi
# Step 3: Verify
claude -p "Run tests and confirm passing" --allowedTools "Bash(npm test *)" --max-turns 3
# Step 4: Commit
claude -p "Create a commit with appropriate message" --allowedTools "Bash(git *)"
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [
{"type": "command", "command": "npx prettier --write $(jq -r '.tool_input.file_path')"},
{"type": "command", "command": "npx eslint --fix $(jq -r '.tool_input.file_path')"}
]
}],
"Stop": [{
"matcher": "",
"hooks": [{"type": "command", "command": "npm test 2>&1 | tail -20"}]
}]
}
}
claude --resume abc123 --fork-session
Creates a new session from an existing one — useful for exploring different approaches without losing the original.
Fill in the blanks:
git worktree ___ ../path branch-name___plan--resume id --___-sessiongit worktree addopusplan--fork-sessionTry opusplan: Start a session with claude --model opusplan and ask it to plan a feature, then implement it. Notice how the model switches.
Try a headless pipeline:
claude -p "List 3 improvements for this codebase" --output-format json | jq '.result'
If adventurous, try Ralph Wiggum:
/plugin marketplace add anthropics/claude-code
/plugin install ralph-wiggum@claude-code-plugins
/ralph-loop "Create a simple CLI calculator in Python with tests. Output <promise>DONE</promise> when tests pass." --max-iterations 10
Reflection: How does the iterative Ralph approach compare to a single-shot request?
Scenario: You need to refactor a legacy module with no tests. The refactor is complex and likely to introduce bugs. How would you approach this with Claude Code's advanced features?
Use a Ralph Wiggum loop with TDD:
/ralph-loop "Refactor the legacy payments module:
Phase 1: Write comprehensive tests for current behavior
- Run tests to verify they pass against current code
- Aim for >90% coverage of the public API
Phase 2: Refactor incrementally
- Small, safe refactors
- Run tests after each change
- If any test fails, revert and try differently
Phase 3: Verify
- All original tests still pass
- Run full test suite
- Check for any TypeScript errors
Output <promise>COMPLETE</promise> when all phases done and all tests pass." \
--max-iterations 30 \
--completion-promise "COMPLETE"
Key techniques combined:
| Concept | One-Liner |
|---|---|
| Ralph Wiggum | Iterative loop: same prompt, but files change each iteration |
| How it works | Stop hook blocks exit, re-feeds prompt, Claude reads its past work |
| Safety | Always use --max-iterations |
| Completion signal | --completion-promise "TEXT" ends the loop |
| Git worktrees | Parallel Claude sessions on same repo, full isolation |
| opusplan | Opus for planning, Sonnet for execution |
| Session forking | --fork-session to explore alternatives |
| Headless pipelines | Chain claude -p commands in bash scripts |
Next up: Cost Management & Monitoring → — Track spending, reduce token usage, and set up enterprise monitoring.