Part 4 of 4
You've learned the fundamentals and mastered the methodology. Now let's dive into advanced techniques that separate hobbyists from professionals.
This is your advanced playbook—techniques for complex scenarios, comprehensive troubleshooting, and enterprise-grade patterns that will make you a Ralph expert.
Advanced Prompt Engineering
The Constraint Sandwich Pattern
One of the most effective patterns for Ralph prompts structures constraints around the task:
# BUILDING MODE## Pre-Constraints (What to consider first)- Read IMPLEMENTATION_PLAN.md- Check progress.txt for prior learnings- Study existing patterns in the codebase- Verify dependencies are installed## Core Task[Your main instruction here]## Quality Gates (Must pass before proceeding)- All tests pass: npm test- Type check passes: npm run type-check- Linter passes: npm run lint- No console.logs or debugger statements remain## Post-Task Actions- Commit with semantic message- Update IMPLEMENTATION_PLAN.md- Append learning to progress.txt
This pattern works because it guides Ralph's thinking in the right order, as documented in 11 Tips for AI Coding with Ralph Wiggum.
See real examples: Browse production prompt files from the community:
- snarktank/ralph — Complete prompt.md with constraint structure
- ClaytonFarr/ralph-playbook — PROMPT_plan.md and PROMPT_build.md templates
- peteristhegreat's gist — Ralph coding agent setup
The Socratic Prompting Technique
Instead of telling Ralph exactly what to do, ask it questions that lead to better solutions:
Weak prompt:
Implement caching for the API.
Strong prompt (Socratic):
We need to improve API performance. Before implementing:1. What are the slowest endpoints currently? (Analyze with profiler)2. Which data changes frequently vs rarely?3. What caching strategy best fits this access pattern?4. Where should the cache layer live (app, Redis, CDN)?After analysis, implement the most appropriate solution with tests.
This forces Ralph to think through the problem systematically, as emphasized in The Ralph Playbook.
The Escape Hatch Pattern
Always give Ralph a way out if it's stuck:
## If You Encounter a Blocker1. Document the issue in progress.txt2. Create a TODO.md file with:- What you tried- Why it didn't work- What needs human decision3. Mark the current task as "blocked" in IMPLEMENTATION_PLAN.md4. Move to the next independent taskDO NOT spin indefinitely on unsolvable problems.
The Learning Accumulation Pattern
Structure progress.txt to accumulate knowledge:
After completing each task, append:## [TIMESTAMP] [TASK-ID]: [Task Title]### What Was Built- Feature/change summary### Technical Decisions- Why this approach over alternatives### Challenges & Solutions- What went wrong and how it was fixed### Learnings for Next Tasks- Patterns to reuse- Pitfalls to avoid### Dependencies/Prerequisites for Related Tasks- What's now available for other tasks
This creates a knowledge base that Ralph references, preventing repeated mistakes.
Advanced File Organization
Multi-Mode Project Structure
For complex projects using all three phases:
project-root/├── ralph/ # Ralph-specific files│ ├── phases/│ │ ├── PROMPT_plan.md│ │ ├── PROMPT_build.md│ │ └── PROMPT_refactor.md # Optional: separate refactor mode│ ├── IMPLEMENTATION_PLAN.md│ ├── progress.txt│ ├── blockers.md # Current blockers needing human input│ └── loop.sh # Orchestrator script├── specs/ # Requirements│ ├── architecture.md│ ├── features/│ │ ├── auth.md│ │ └── api.md│ └── non-functional.md # Performance, security, etc.├── docs/ # Generated documentation├── src/ # Application code└── tests/ # Test suite
The Checkpoint System
Create checkpoints for long-running projects:
# ralph/checkpoints/checkpoint-YYYY-MM-DD-description.md## Project State- Branch: feature/user-management- Commit: abc123- Tasks completed: 15/30- Blockers: None## Ralph Configuration- Mode: Building- Max iterations: 100- Completion promise: "MILESTONE COMPLETE"## Next Steps1. Complete user role management (TASK-016 to TASK-020)2. Then regenerate plan for Phase 2 features3. Consider splitting into separate Ralph session## Learnings So Far- Database schema changes require migration strategy- Test data setup takes 2-3 iterations- Auth patterns now stable and reusable
Setting Up PRDs for Ralph
A well-structured PRD is critical for Ralph's success. This is an alternative to the specs/*.md + IMPLEMENTATION_PLAN.md approach—some teams prefer JSON for machine readability.
Tools to help: Ralph TUI includes
/ralph-tui-prdto create PRDs interactively and/ralph-tui-create-jsonto convert them to JSON. snarktank/ralph offers PRD-driven task management with automatic branching and flowchart visualization.
prd.json Template
{"project": "Todo API","schema_version": "2.0","final_tests": ["npm test", "npm run type-check", "npm run lint"],"stories": [{"id": "S001","priority": 1,"title": "User Authentication","category": "backend","description": "Implement JWT-based authentication with login/logout","acceptance": ["User can register with email/password","User can login and receive JWT token","Protected routes require valid JWT","User can logout and invalidate token"],"steps_to_verify": ["Run: npm test -- auth.test.ts","Verify all 12 auth tests pass","Check JWT is stored in httpOnly cookie","Verify token expiry works correctly"],"tests": ["npm test -- auth.test.ts"],"estimated_complexity": "medium","depends_on": [],"passes": false},{"id": "S002","priority": 2,"title": "Todo CRUD Endpoints","category": "backend","description": "Create POST, GET, PUT, DELETE endpoints for todos","acceptance": ["POST /api/todos creates a todo","GET /api/todos returns user's todos only","PUT /api/todos/:id updates a todo","DELETE /api/todos/:id deletes a todo"],"steps_to_verify": ["Run: npm test -- todos.test.ts","Test with Postman or curl","Verify authorization works"],"tests": ["npm test -- todos.test.ts"],"estimated_complexity": "medium","depends_on": ["S001"],"passes": false}]}
Key PRD Principles
Binary Pass/Fail Criteria: Each task needs automated verification. As The Ralph Playbook emphasizes: "Make it better" isn't testable—"All tests pass with 80%+ coverage" is.
Atomic Tasks: If a task requires 500+ lines of code, break it down. Each story should complete in 2-3 iterations.
The passes Field: Ralph updates this to true when complete. The loop continues until all tasks pass.
Test Requirements: Every story should specify how to verify completion automatically. No manual verification steps.
Common Pitfalls and How to Avoid Them
Starting Too Ambitious
Mistake: Running 50 iterations on your first Ralph project.
Fix: Start with 10-20 iterations to understand costs and behavior. As documented in community tips, a 50-iteration loop can cost $50-100+.
Vague Completion Criteria
Mistake: "Make the app faster" or "Improve the UI"
Fix: Use specific, testable criteria:
- ✅ "Reduce API response time to under 200ms (verified by load tests)"
- ✅ "All Lighthouse scores above 90"
- ✅ "Test coverage above 80% on all modules"
No Automated Verification
Mistake: Tasks that require human judgment like "make it look good"
Fix: Ralph needs binary pass/fail conditions. If you can't write an automated test for it, Ralph can't verify it. As The Ralph Playbook states: "Backpressure beats direction."
Tasks Too Large
Mistake: "Build entire authentication system" as one task
Fix: Break into smaller stories:
- S001: User registration endpoint
- S002: Login endpoint with JWT
- S003: Token refresh mechanism
- S004: Password reset flow
- S005: Email verification
Ignoring Context Limits
Mistake: Letting Ralph run indefinitely without fresh context
Fix: Use the Bash loop method instead of the plugin for long-running projects—each iteration gets a fresh context window. This is a key insight from Geoffrey Huntley's guide.
When to use which method:
- < 20 iterations: Plugin (
/ralph-loop) is fine—simpler setup, context stays manageable - 20-40 iterations: Either works; bash loop preferred for consistency
- > 40 iterations: Bash loop required—prevents context degradation and hallucination
The plugin runs everything in a single context window, which fills up over time. The bash loop method launches a fresh Claude instance per iteration, with only the codebase state carrying over.
No Cost Monitoring
Mistake: Not tracking API spending during development
Fix: Set billing alerts and start with low iteration counts. Monitor costs per iteration. Track your spending at https://console.anthropic.com
Wrong Task Types
Good Ralph tasks:
- Migrating tests from Jest to Vitest
- Adding CRUD endpoints with tests
- Implementing well-specified features
- Refactoring with existing test coverage
Bad Ralph tasks:
- "Figure out why the app is slow" (exploration)
- "Make the UI prettier" (subjective)
- "Fix this weird bug" (requires deep debugging context)
- UX decisions requiring aesthetic judgment
The Thrashing Problem
Symptom: Ralph gets stuck in a loop—same error, same fix attempt, same failure.
Solutions:
- Set
--max-iterationsto limit damage - Review your tests—are they too strict or unclear?
- Break the task into smaller, more atomic pieces
- Add explicit debugging steps to your prompt
- Check if dependencies are properly installed
Comprehensive Troubleshooting Guide
Problem: Ralph Keeps Making the Same Mistake
Symptoms:
- Same error across multiple iterations
- Tests fail with identical message
- Ralph tries same approach repeatedly
Root Causes:
- Test is ambiguous or incorrectly written
- Prompt doesn't include error feedback
- Ralph lacks context about why approach fails
Solutions:
Fix 1: Update the test
// Bad: Vague assertionexpect(result).toBeTruthy();// Good: Specific assertionexpect(result).toEqual({id: expect.any(String),email: 'test@example.com',createdAt: expect.any(Date)});
Fix 2: Add error feedback to prompt
If tests fail:1. Read the test output carefully2. Identify the specific assertion that failed3. Check if you're testing the wrong behavior4. Try a different approach if current one fails twice
Fix 3: Add explicit debugging steps
Before implementing:1. Add console.log to see actual vs expected values2. Run test in isolation: npm test -- --testNamePattern="specific test"3. Verify mock data matches what code expects
Fix 4: Use the Escape Hatch Pattern
If Ralph keeps failing after multiple attempts, use the Escape Hatch Pattern to document the blocker and move on to the next task instead of spinning indefinitely.
Problem: Ralph Generates Insecure Code
Symptoms:
- Passwords stored in plaintext
- SQL injection vulnerabilities
- Missing authentication checks
- CORS set to "*"
Prevention:
Add security checklist to prompt:
## Security Checklist (MUST verify before committing)Authentication:- [ ] Passwords hashed with bcrypt (min 12 rounds)- [ ] JWTs signed with secure secret (min 32 chars)- [ ] httpOnly cookies for token storage- [ ] No secrets in code (use env variables)Authorization:- [ ] All protected routes have auth middleware- [ ] User can only access own resources- [ ] Admin endpoints check roleInput Validation:- [ ] All user input validated with Zod/Joi- [ ] SQL/NoSQL injection prevented (use ORMs)- [ ] XSS prevention (sanitize HTML)- [ ] Rate limiting on sensitive endpointsCORS:- [ ] Specific origins only (not "*")- [ ] Credentials: true only with specific origin
Problem: Context Window Exhaustion
Symptoms:
- Ralph starts ignoring parts of prompts
- Quality degrades after iteration 30-40
- Ralph stops following constraints
As JeredBlu's guide explains, this is why the bash loop method with fresh context per iteration is "fundamentally better for long-running tasks."
Solutions:
Solution 1: Use Bash Loop Method
# loop.sh - Fresh context each iterationwhile true; doclaude < PROMPT_build.md# Check if doneif grep -q "ALL TASKS COMPLETE" progress.txt; thenecho "Build complete!"breakfisleep 2done
Solution 2: Context Compression Prompt
About
/compact: The/compactcommand compresses your conversation context, letting you continue working without losing important details. Use it proactively before hitting context limits. See Mastery Part 2 for when to use/compactvs/clear.
Every 10 iterations, before continuing:1. Run: /compact to compress context2. Summarize current state:- Tasks completed- Current task in progress- Key patterns established3. Continue with fresh focus
Solution 3: Split Long Sessions
# Session 1: Core features (Tasks 1-10)/ralph-loop "$(cat PROMPT_build.md)" --max-iterations 30# Review, commit, take a break# Session 2: Advanced features (Tasks 11-20)/ralph-loop "$(cat PROMPT_build.md)" --max-iterations 30
Problem: Ralph Won't Stop (Thrashing)
Symptoms:
- Hits max-iterations without completing
- Makes changes, reverts them, repeats
- Progress.txt shows circular logic
For deeper analysis of Ralph's decision-making when it thrashes, Braintrust's debugging guide shows how to use LLM observability tools to understand what's happening.
Diagnosis:
Check progress.txt for patterns:
[14:30] Trying approach A...[14:35] Approach A failed, trying approach B...[14:40] Approach B failed, trying approach A again...
Solutions:
Solution 1: Add attempt tracking
Track attempts in progress.txt:[Iteration X] TASK-005: Attempt #1 - Trying JWT with RSA[Iteration Y] TASK-005: Attempt #2 - Trying JWT with HS256[Iteration Z] TASK-005: Attempt #3 - Adding fallbackIf task has 3 failed attempts:1. Mark task as "blocked"2. Document in blockers.md3. Move to next task
Solution 2: Simplify acceptance criteria
# Too complex (causes thrashing)- API must be performant, secure, and scalable# Specific (Ralph can verify)- API responds in <200ms (verified by tests)- All endpoints require authentication (verified by tests)- Can handle 100 concurrent requests (load test passes)
Problem: Test Coverage Drops Over Time
Symptoms:
- Early tasks have great tests
- Later tasks have minimal tests
- Coverage below target
Root Cause: Ralph prioritizes shipping over testing when not enforced.
Solution: Add test coverage gate to prompt:
## Test Requirements (STRICT)Every commit MUST include tests for:1. Happy path (success case)2. Error cases (4xx, 5xx)3. Edge cases (empty input, missing fields)4. Authorization (access control)Before committing, run: npm test -- --coverageMINIMUM COVERAGE REQUIRED:- Statements: 80%- Branches: 75%- Functions: 80%- Lines: 80%If coverage drops below threshold:- DO NOT commit- Add missing tests- Re-run coverage
Problem: Ralph Ignores Existing Patterns
Symptoms:
- New code uses different patterns than existing code
- Inconsistent file structure
- Multiple ways to do the same thing
Solution: Add pattern documentation to your prompt. Include your project's actual file structure and naming conventions so Ralph follows them consistently:
## Codebase Patterns (MUST FOLLOW)Before implementing any feature:1. Study existing features as reference (e.g., the user module)2. Follow the same directory structure and file organization3. Reuse established naming conventions and code patterns4. Only deviate if specs explicitly require itIf unsure about a pattern, check how similar features are implementedin the codebase before writing new code.
Ralph-TUI Advanced Configuration
Ralph-TUI supports customization via a config file at ~/.ralph-tui/config.json.
Custom Task Priorities
Override default priority sorting:
{"taskPriority": {"TASK-001": 10,"TASK-005": 9,"TASK-002": 8}}
Ralph-TUI displays tasks in this order, even if IMPLEMENTATION_PLAN.md lists them differently.
Output Filtering
Filter log lines by keyword or regex:
{"logFilters": {"exclude": ["Reading", "Skipping"],"include": ["✓", "✗", "completed", "failed"]}}
This hides noisy lines (file reads) and highlights important events (test results, task completion).
Export Formats
Choose log export format:
{"exportFormat": "markdown"}
Options: txt, markdown, json, html
Markdown export generates:
# Ralph-TUI Log Export**Project:** my-saas-app**Duration:** 2h 15m**Tasks Completed:** 12 / 15## Iteration 1[10:05:12] Reading specs......
Integration with Other Tools
Send Ralph-TUI events to external systems:
{"webhooks": {"taskComplete": "https://myapp.com/api/ralph-task-complete","testFailure": "https://myapp.com/api/ralph-test-failed"}}
When Ralph completes a task, Ralph-TUI POSTs to your webhook:
{"event": "taskComplete","taskId": "TASK-003","timestamp": "2026-01-16T10:30:45Z","iteration": 12}
Use cases:
- Update project management tools (Linear, Jira)
- Send Slack notifications
- Trigger CI/CD pipelines on task completion
Ralph-TUI Troubleshooting
Ralph-TUI Not Detecting Ralph Loop
Symptom: ralph-tui run shows "Waiting for Ralph loop..." indefinitely.
Cause: Ralph-TUI looks for a running ralph process in the current directory. If you started Ralph in a different directory, Ralph-TUI won't find it.
Solution:
- Run
ps aux | grep ralphto find the Ralph process - Note the working directory from
lsof -p <pid> cdto that directory and runralph-tui runagain
Alternative: Explicitly specify the Ralph process ID:
ralph-tui run --pid 12345
Session Lost/Corrupted
Symptom: Ralph-TUI shows "Session data corrupted" on startup.
Cause: Ralph-TUI stores session state in ~/.ralph-tui/sessions/<project-name>.json. If Ralph crashes mid-iteration, the session file may be incomplete.
Solution:
- Delete the corrupted session:
rm ~/.ralph-tui/sessions/my-project.json - Restart Ralph-TUI:
ralph-tui run
Ralph-TUI creates a fresh session, but you lose historical context (previous iterations won't show in logs).
Prevention: Enable session backups in config:
{"sessionBackups": {"enabled": true,"interval": 300}}
This creates backups every 5 minutes in ~/.ralph-tui/sessions/backups/.
Performance Issues with Large Logs
Symptom: Ralph-TUI becomes slow or unresponsive after several hours of monitoring.
Cause: Log buffer grows to 100,000+ lines, slowing down rendering.
Solution:
- Export logs periodically: press
eevery hour - Enable log rotation in config:
{"logRotation": {"maxLines": 10000,"archiveOld": true}}
When logs hit 10,000 lines, Ralph-TUI archives old logs to ~/.ralph-tui/archives/ and clears the buffer.
Alternative: Increase terminal buffer size if your terminal supports it (e.g., iTerm2 → Preferences → Profiles → Terminal → Scrollback lines).
Port Conflicts
Symptom: ralph-tui run fails with "Port 9876 already in use".
Cause: Ralph-TUI uses port 9876 for internal communication. Another process is using it.
Solution:
- Find the conflicting process:
lsof -i :9876 - Kill it or use a different port:
ralph-tui run --port 9999
Permanent fix: Set default port in config:
{"port": 9999}
Headless Visual Feedback with Playwright MCP
For bash loop runs without a visible browser, JeredBlu recommends Playwright MCP for visual verification.
What is MCP? Model Context Protocol (MCP) is an open standard that lets Claude connect to external services—databases, APIs, browser automation, and more. MCP servers extend Claude's capabilities beyond text processing. See Mastery Part 7: MCP Servers for setup and configuration.
Create .mcp.json in your project root:
{"mcpServers": {"playwright": {"command": "npx","args": ["-y", "@playwright/mcp@latest", "--headless", "--output-dir", "screenshots"]}}}
Then reference it in your PROMPT_build.md:
After implementing, use Playwright to:1. Navigate to the local server URL2. Take a screenshot: screenshots/[task-name].pngInclude the screenshot filename in your progress.txt entry.
This gives you visual verification of Ralph's work without needing Claude for Chrome or a visible browser window. Screenshots accumulate in your project folder, providing a visual audit trail of what Ralph built.
When to use Playwright MCP vs Ralph-TUI:
- Ralph-TUI: Real-time log monitoring, task orchestration, keyboard controls
- Playwright MCP: Headless visual verification, screenshot audit trails, CI/CD integration
Both tools complement each other—use Ralph-TUI for live monitoring and Playwright MCP for visual verification.
Enterprise Patterns
Multi-Developer Ralph Coordination
When multiple developers use Ralph on the same project, coordination becomes critical. Several tools exist for this:
- ralph-orchestrator — Supports 7+ AI backends (Claude, Gemini, Copilot, etc.) with a persona/hat system for specialized tasks
- multi-agent-ralph-loop — Parallel workstream orchestration for running multiple Ralph instances simultaneously
- ralph-loop-agent — Vercel's TypeScript SDK wrapper for programmatic control
Pattern 1: Feature Branch Ralph
# Developer Agit checkout -b feature/auth# Run Ralph for auth tasks./loop.sh build --tasks "TASK-001 to TASK-005"# Developer B (different branch)git checkout -b feature/payments# Run Ralph for payment tasks./loop.sh build --tasks "TASK-010 to TASK-015"# Merge both when complete
Pattern 2: Shared Progress Tracking
# team-progress.md## Active Ralph Sessions### Developer: Alice- Branch: feature/auth- Tasks: TASK-001 to TASK-005- Status: In Progress (3/5 complete)- ETA: 2 hours### Developer: Bob- Branch: feature/payments- Tasks: TASK-010 to TASK-015- Status: Complete- Ready for: Code review## Blocked Tasks Needing Team Discussion- TASK-008: Payment provider API unclear- TASK-014: Architecture decision needed
Ralph + CI/CD Integration
Automate Ralph runs in your pipeline:
# .github/workflows/ralph-build.ymlname: Ralph Autonomous Buildon:workflow_dispatch:inputs:tasks:description: 'Task range (e.g., TASK-001 to TASK-005)'required: truejobs:ralph-build:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v3- name: Setup Claude Coderun: curl -fsSL https://claude.ai/install.sh | bash- name: Run Ralph Loopenv:ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}run: |./loop.sh build \--tasks "${{ github.event.inputs.tasks }}" \--max-iterations 30- name: Create Pull Requestuses: peter-evans/create-pull-request@v5with:title: "Ralph Build: ${{ github.event.inputs.tasks }}"body: |Autonomous build completed by Ralph WiggumTasks completed:${{ github.event.inputs.tasks }}See progress.txt for details.
Choosing a Claude Plan for Ralph
Ralph works with Claude subscriptions or API access. Here's the quick guide:
- Claude Pro ($20/mo) — 10-30 iterations/session, good for learning and side projects
- Claude Max 5x ($100/mo) — 50-150 iterations/session, ideal for daily development
- Claude Max 20x ($200/mo) — 200-600+ iterations/session, professional long-running loops
Recommendation: Start with Pro to learn the workflow. Upgrade to Max 5x once you're running Ralph daily—it's 5x the capacity for 5x the price, which is fair. Go Max 20x if you're doing client work or need extended autonomous sessions.
The ROI math: At $200/month for Max 20x, if Ralph saves you just 5 hours (at $40/hr billing), it's already paid for itself. Most serious users report 20-40+ hours saved monthly.
Cost Management Tips
- Always set
--max-iterations— Your real safety net - Start small — 10-20 iterations until you understand the costs
- Focused prompts = fewer iterations — Vague prompts burn tokens
- Track your usage — Check at https://claude.ai/settings
Conclusion
You've now covered the advanced techniques that will help you get more out of Ralph. These techniques enable you to tackle complex, production-grade projects with confidence. You know how to prevent problems before they occur and fix them quickly when they do.
For additional resources, explore The Ralph Playbook for comprehensive methodology documentation, Geoffrey Huntley's original guide for the philosophy behind the technique, and JeredBlu's practical guide for copy-paste-ready configurations.
Bash loop method (fresh context per iteration) — while true; do claude < PROMPT_build.md; done
Context compression — /compact
Check for thrashing — grep -E "Attempt #[0-9]+" progress.txt
Session management — ./loop.sh build --tasks "TASK-001 to TASK-005"
CI/CD integration — claude -p "$(cat PROMPT_build.md)" --output-format text
Key takeaways
Advanced prompt patterns (Constraint Sandwich, Socratic, Escape Hatch) improve Ralph's effectiveness
Context window exhaustion after 30-40 iterations signals time to use bash loop method
Thrashing problems can be diagnosed via progress.txt patterns
Enterprise patterns enable multi-developer coordination with Ralph
CI/CD integration automates Ralph runs in pipelines
Stay Updated
Get notified about new posts on automation, productivity tips, indie hacking, and web3.
No spam, ever. Unsubscribe anytime.
