ralph-claude-code - Framework do Autonomicznego Programowania
Czym jest Ralph?
Ralph to przełomowy framework do w pełni autonomicznego programowania z wykorzystaniem Claude Code. W przeciwieństwie do standardowego użycia Claude Code, gdzie developer prowadzi konwersację i nadzoruje każdą zmianę, Ralph pozwala Claude działać samodzielnie przez dłuższe okresy - analizując, planując, implementując, testując i commitując kod bez ciągłej interakcji człowieka.
Nazwa "Ralph" nawiązuje do koncepcji "AI programming assistant that does the work while you ralph (relax)" - asystenta, który wykonuje pracę podczas gdy Ty odpoczywasz. Framework został zaprojektowany z myślą o bezpieczeństwie: zawiera wbudowane zabezpieczenia, snapshoty Git przed każdą zmianą, automatyczny rollback przy błędach i opcjonalne punkty kontrolne wymagające zatwierdzenia człowieka.
Ralph reprezentuje ewolucję od "AI-assisted coding" do "AI-autonomous coding" - zmianę paradygmatu, gdzie developer staje się bardziej architektem i nadzorcą, a mniej wykonawcą kodu.
GitHub
Repository: github.com/anthropics/ralph-claude-code
Status: Version 0.10.1 | 310 passing tests | Aktywny development
Dlaczego Ralph?
Problem z tradycyjnym AI-assisted coding
Standardowa praca z Claude Code wygląda tak:
Developer: "Dodaj walidację do formularza"
Claude: "Oto kod walidacji..."
Developer: "OK, teraz dodaj testy"
Claude: "Oto testy..."
Developer: "Teraz zintegruj z backendem"
Claude: "Oto integracja..."Wymaga to ciągłej uwagi developera, który musi:
- Formułować kolejne kroki
- Weryfikować każdą zmianę
- Decydować co dalej
- Łączyć wszystko w całość
Rozwiązanie Ralph
Z Ralph workflow wygląda tak:
ralph "Dodaj pełną funkcjonalność formularza kontaktowego
z walidacją, testami i integracją z API"
# Ralph automatycznie:
# 1. Analizuje istniejący kod
# 2. Planuje implementację
# 3. Tworzy komponent formularza
# 4. Dodaje walidację Zod
# 5. Pisze testy jednostkowe
# 6. Integruje z API route
# 7. Uruchamia testy
# 8. Commituje działający kodKluczowe zalety
- Pełna autonomia - Ralph sam decyduje o kolejnych krokach
- Bezpieczeństwo - Git snapshots i automatyczny rollback
- Ciągły development - Cykle analyze→plan→implement→test→commit
- Skalowalność - Obsługuje złożone, wieloetapowe zadania
- Human-in-the-loop - Opcjonalne checkpointy wymagające zatwierdzenia
- Transparentność - Szczegółowe logi każdej decyzji i akcji
- Odporność na błędy - Automatyczne naprawianie i retry
- Konfigurowalność - Dostosuj poziom autonomii do potrzeb
Instalacja i konfiguracja
Wymagania systemowe
- Node.js 18+ lub Python 3.10+
- Git 2.30+
- Claude Code CLI zainstalowany
- ANTHROPIC_API_KEY skonfigurowany
- Repozytorium Git (Ralph wymaga Git do snapshotów)
Instalacja
# Klonowanie repozytorium
git clone https://github.com/anthropics/ralph-claude-code
cd ralph-claude-code
# Instalacja
./install.sh
# Lub przez npm
npm install -g ralph-claude-code
# Weryfikacja
ralph --version
# ralph v0.10.1Konfiguracja projektu
# Inicjalizacja Ralph w projekcie
cd my-project
ralph-setup .
# Utworzy pliki:
# .ralph/config.json - Konfiguracja
# .ralph/prompts/ - Szablony promptów
# .ralph/snapshots/ - Snapshoty Git
# .ralph/logs/ - Logi sesjiPlik konfiguracyjny
// .ralph/config.json
{
"model": "claude-sonnet-4-5-20241022",
"maxCycles": 50,
"cycleTimeout": 300000,
"safety": {
"gitSnapshots": true,
"autoRollback": true,
"requireApproval": ["delete", "production", "database"],
"maxFilesPerCycle": 10,
"maxLinesChanged": 500
},
"testing": {
"runTests": true,
"testCommand": "npm test",
"minCoverage": 80,
"failOnTestError": true
},
"commit": {
"autoCommit": true,
"signCommits": false,
"conventionalCommits": true
},
"monitoring": {
"logLevel": "info",
"webhookUrl": null,
"slackChannel": null
}
}Cykl Development
Ralph działa w cyklicznych iteracjach, gdzie każdy cykl składa się z określonych faz:
Faza 1: Analyze
┌─────────────────────────────────────────┐
│ ANALYZE │
│ ──────── │
│ • Czytanie istniejącego kodu │
│ • Zrozumienie struktury projektu │
│ • Identyfikacja zależności │
│ • Ocena stanu projektu │
│ • Określenie wymagań zadania │
└─────────────────────────────────────────┘Ralph analizuje codebase, rozumie architekturę, identyfikuje pliki do modyfikacji i ocenia co jest potrzebne do wykonania zadania.
Faza 2: Plan
┌─────────────────────────────────────────┐
│ PLAN │
│ ──── │
│ • Tworzenie planu implementacji │
│ • Rozbicie na subtaski │
│ • Określenie kolejności │
│ • Identyfikacja ryzyk │
│ • Checkpoint: Human approval? │
└─────────────────────────────────────────┘Na podstawie analizy, Ralph tworzy szczegółowy plan: jakie pliki utworzyć/modyfikować, w jakiej kolejności, jakie są potencjalne ryzyka.
Faza 3: Implement
┌─────────────────────────────────────────┐
│ IMPLEMENT │
│ ───────── │
│ • Git snapshot przed zmianami │
│ • Pisanie/modyfikacja kodu │
│ • Formatowanie i linting │
│ • Aktualizacja importów │
│ • Sprawdzanie typów │
└─────────────────────────────────────────┘Ralph wykonuje zaplanowane zmiany, tworząc Git snapshot przed każdą modyfikacją.
Faza 4: Test
┌─────────────────────────────────────────┐
│ TEST │
│ ──── │
│ • Uruchamianie testów jednostkowych │
│ • Sprawdzanie TypeScript │
│ • Weryfikacja linting │
│ • Analiza pokrycia kodu │
│ • Jeśli testy fail → powrót do PLAN │
└─────────────────────────────────────────┘Automatyczne uruchomienie testów. Jeśli testy nie przechodzą, Ralph wraca do fazy planowania z informacją o błędach.
Faza 5: Review
┌─────────────────────────────────────────┐
│ REVIEW │
│ ────── │
│ • Self-review zmian │
│ • Sprawdzenie best practices │
│ • Weryfikacja bezpieczeństwa │
│ • Dokumentacja zmian │
│ • Checkpoint: Human review? │
└─────────────────────────────────────────┘Ralph sam przegląda swoje zmiany, szukając potencjalnych problemów.
Faza 6: Commit
┌─────────────────────────────────────────┐
│ COMMIT │
│ ────── │
│ • Staging zmienionych plików │
│ • Generowanie commit message │
│ • Git commit │
│ • Aktualizacja changelog │
│ • Powiadomienie (jeśli skonfigurowane) │
└─────────────────────────────────────────┘Jeśli wszystko przeszło, Ralph commituje zmiany z odpowiednim komunikatem.
Faza 7: Repeat
┌─────────────────────────────────────────┐
│ REPEAT │
│ ────── │
│ • Sprawdzenie czy zadanie ukończone │
│ • Wybór następnego subtaska │
│ • Powrót do ANALYZE │
│ • Lub: zakończenie sesji │
└─────────────────────────────────────────┘Ralph sprawdza czy główne zadanie zostało ukończone. Jeśli nie - przechodzi do następnego subtaska.
Podstawowe użycie
Uruchomienie prostego zadania
# Podstawowe wywołanie
ralph "Dodaj endpoint GET /api/users zwracający listę użytkowników"
# Z monitorowaniem w czasie rzeczywistym
ralph --monitor "Zaimplementuj paginację dla listy produktów"
# Z limitem cykli
ralph --max-cycles 20 "Dodaj walidację formularza"
# Tryb dry-run (bez rzeczywistych zmian)
ralph --dry-run "Zrefaktoruj komponent Dashboard"Zadania wieloetapowe
# Złożone zadanie
ralph "Stwórz pełny system autentykacji:
1. Endpoint POST /api/auth/register
2. Endpoint POST /api/auth/login
3. Endpoint POST /api/auth/logout
4. Middleware do weryfikacji JWT
5. Komponenty React: LoginForm, RegisterForm
6. Testy dla wszystkich endpointów
7. Dokumentacja API w Swagger"
# Ralph automatycznie:
# - Rozbije na subtaski
# - Wykona każdy krok
# - Zintegruje wszystko razem
# - Napisze testy
# - Wygeneruje dokumentacjęTryb interaktywny
# Uruchom z punktami kontrolnymi
ralph --interactive "Przeprojektuj architekturę modułu płatności"
# Ralph zatrzyma się i zapyta o zatwierdzenie przed:
# - Usunięciem plików
# - Zmianami w produkcyjnym kodzie
# - Modyfikacją bazy danych
# - Innymi "ryzykownymi" operacjamiKontynuowanie sesji
# Ralph zapisuje stan sesji
ralph "Długie zadanie..."
# Przerwij Ctrl+C
# Kontynuuj później
ralph --continue
# Lista sesji
ralph sessions list
# Wznów konkretną sesję
ralph sessions resume abc123Zabezpieczenia
Git Snapshots
# Przed każdą zmianą Ralph tworzy snapshot
.ralph/snapshots/
├── 2025-01-25_143022_pre-implement/
├── 2025-01-25_143045_pre-implement/
└── 2025-01-25_143112_pre-test/
# Ręczne przywrócenie
ralph rollback 2025-01-25_143022_pre-implement
# Automatyczny rollback przy błędach
# Konfiguracja w .ralph/config.json:
# "autoRollback": trueAutomatyczny Rollback
# Ralph automatycznie przywraca zmiany gdy:
# 1. Testy nie przechodzą
# 2. Kod nie kompiluje się
# 3. Linting zwraca błędy
# 4. Przekroczono limit zmian
# Log rollbacku
[14:32:15] ❌ Tests failed: 3 failing
[14:32:15] 🔄 Rolling back to snapshot 2025-01-25_143112
[14:32:16] ✅ Rollback complete
[14:32:16] 📝 Analyzing failure...
[14:32:18] 🔧 Adjusting plan to fix issuesHuman-in-the-Loop
// Konfiguracja wymaganych zatwierdzeń
{
"safety": {
"requireApproval": [
"delete", // Usuwanie plików
"production", // Zmiany w produkcji
"database", // Zmiany schematów DB
"security", // Kod związany z bezpieczeństwem
"payment", // Kod płatności
"api-breaking" // Breaking changes w API
]
}
}# Podczas sesji
[14:35:22] ⚠️ APPROVAL REQUIRED
[14:35:22] Action: Delete file src/old-component.tsx
[14:35:22] Reason: Component replaced by new implementation
[14:35:22] Continue? [y/N/review]:Rate Limiting
{
"safety": {
"maxFilesPerCycle": 10, // Max plików na cykl
"maxLinesChanged": 500, // Max linii na cykl
"maxCyclesPerHour": 100, // Max cykli/godzinę
"cooldownOnError": 30000 // Przerwa po błędzie (ms)
}
}Ograniczenia dostępu
{
"safety": {
"allowedPaths": [
"src/**",
"tests/**",
"docs/**"
],
"forbiddenPaths": [
".env*",
"secrets/**",
"*.key",
"node_modules/**"
],
"forbiddenCommands": [
"rm -rf",
"sudo",
"chmod 777"
]
}
}Zaawansowane użycie
Custom Prompts
# Szablony promptów w .ralph/prompts/
.ralph/prompts/
├── analyze.md # Prompt dla fazy analizy
├── plan.md # Prompt dla planowania
├── implement.md # Prompt dla implementacji
├── review.md # Prompt dla code review
└── custom/ # Własne prompty<!-- .ralph/prompts/custom/security-audit.md -->
# Security Audit Task
Przeprowadź audyt bezpieczeństwa dla {{files}}:
1. Sprawdź podatności OWASP Top 10
2. Zweryfikuj sanityzację inputów
3. Sprawdź obsługę autentykacji
4. Zweryfikuj autoryzację
5. Znajdź potencjalne SQL injection
6. Sprawdź XSS vulnerabilities
Dla każdego problemu:
- Opisz podatność
- Oceń severity (Critical/High/Medium/Low)
- Zaproponuj fix
- Zaimplementuj poprawkę# Użycie custom promptu
ralph --prompt security-audit "Zaudytuj moduł auth"Integracja z CI/CD
# .github/workflows/ralph-autofix.yml
name: Ralph Autofix
on:
push:
branches: [main]
jobs:
autofix:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Ralph
run: npm install -g ralph-claude-code
- name: Run Linting
id: lint
continue-on-error: true
run: npm run lint
- name: Autofix with Ralph
if: steps.lint.outcome == 'failure'
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
ralph --non-interactive \
--max-cycles 10 \
"Napraw wszystkie błędy ESLint w projekcie"
- name: Create PR
if: steps.lint.outcome == 'failure'
uses: peter-evans/create-pull-request@v5
with:
title: "fix: Ralph autofix for linting errors"
branch: ralph-autofixWebhooks i notyfikacje
{
"monitoring": {
"webhookUrl": "https://api.example.com/ralph-events",
"slackChannel": "#dev-automation",
"events": ["cycle_complete", "task_complete", "error", "approval_needed"]
}
}// Webhook payload
interface RalphEvent {
type: 'cycle_complete' | 'task_complete' | 'error' | 'approval_needed'
sessionId: string
timestamp: string
data: {
task: string
cycle: number
filesChanged: string[]
testsResult?: 'pass' | 'fail'
error?: string
}
}API Programistyczne
import { Ralph, RalphConfig, RalphSession } from 'ralph-claude-code'
// Konfiguracja
const config: RalphConfig = {
model: 'claude-sonnet-4-5-20241022',
maxCycles: 30,
safety: {
autoRollback: true,
requireApproval: ['delete', 'production']
}
}
// Utworzenie instancji
const ralph = new Ralph(config)
// Uruchomienie zadania
const session = await ralph.run({
task: 'Dodaj endpoint /api/products z CRUD',
onCycleComplete: (cycle) => {
console.log(`Cycle ${cycle.number} complete`)
},
onApprovalNeeded: async (action) => {
// Automatyczne zatwierdzanie lub...
const approved = await askUser(action)
return approved
}
})
// Monitorowanie
session.on('log', (message) => console.log(message))
session.on('error', (error) => console.error(error))
session.on('complete', (result) => console.log('Done!', result))
// Zatrzymanie
await session.stop()
// Wznowienie
await session.resume()Multi-Agent Mode (Eksperymentalne)
# Uruchom wielu agentów równolegle
ralph --agents 3 "Zrefaktoruj wszystkie komponenty React"
# Agent 1: src/components/Auth/*
# Agent 2: src/components/Dashboard/*
# Agent 3: src/components/Settings/*
# Koordynacja przez głównego agentaMonitoring i logi
Logi sesji
# Podgląd logów w czasie rzeczywistym
ralph --monitor "Zadanie..."
# Logi zapisywane są w .ralph/logs/
.ralph/logs/
├── session_abc123.log # Log sesji
├── session_abc123.json # Strukturalny log
└── session_abc123.md # Human-readable raportDashboard (opcjonalny)
# Uruchom lokalny dashboard
ralph dashboard
# Otwórz http://localhost:3333
# Monitoruj:
# - Aktywne sesje
# - Historia zadań
# - Statystyki (cykle, czas, sukces/fail)
# - Logi w czasie rzeczywistymMetryki
# Statystyki projektu
ralph stats
# Output:
# ═══════════════════════════════════════
# Ralph Statistics for my-project
# ═══════════════════════════════════════
# Total sessions: 47
# Successful: 43 (91.5%)
# Failed: 4 (8.5%)
# Total cycles: 892
# Avg cycles/task: 19
# Files modified: 234
# Lines changed: 12,450
# Tests written: 89
# Commits: 43
# ═══════════════════════════════════════Ralph vs alternatywy
| Funkcja | Ralph | Claude Code | Devin | GitHub Copilot |
|---|---|---|---|---|
| Autonomia | Pełna | Nadzorowana | Pełna | Sugestie |
| Cykle dev | Tak | Nie | Tak | Nie |
| Git safety | Wbudowane | Ręczne | Wbudowane | Brak |
| Testy auto | Tak | Ręczne | Tak | Nie |
| Human-in-loop | Konfigurowalne | Zawsze | Konfigurowalne | N/A |
| Open-source | Tak | Częściowo | Nie | Nie |
| Koszt | API Claude | API Claude | $500/mies | $10-19/mies |
| Setup | Średni | Prosty | Złożony | Prosty |
Rozwiązywanie problemów
Typowe problemy
# Problem: Ralph utknął w pętli
ralph --max-cycles 10 "Zadanie..." # Ogranicz cykle
# Problem: Zbyt wiele zmian naraz
# Konfiguracja w .ralph/config.json:
# "maxFilesPerCycle": 5
# Problem: Testy ciągle failują
ralph --skip-tests "Zadanie..." # Tymczasowo pomiń
# LUB: Napraw testy najpierw
ralph "Napraw failing testy przed kontynuacją"
# Problem: Rate limit API
ralph --cycle-delay 5000 "Zadanie..." # Przerwa między cyklami
# Problem: Niezrozumiałe zmiany
ralph --verbose "Zadanie..." # Więcej szczegółów w logachDebug mode
# Pełne logi debug
export RALPH_DEBUG=1
ralph "Zadanie..."
# Zatrzymaj po każdym cyklu
ralph --step-by-step "Zadanie..."
# Zapisz pełny kontekst Claude
ralph --save-context "Zadanie..."FAQ - Najczęściej zadawane pytania
Czy mogę zostawić Ralph bez nadzoru?
Tak, ale z odpowiednią konfiguracją. Dla bezpieczeństwa ustaw:
maxCycles- limit cyklirequireApprovaldla ryzykownych operacji- Notyfikacje Slack/webhook
- Regularne przeglądy commitów
Jak kosztowny jest Ralph?
Ralph używa API Claude, więc koszty zależą od:
- Liczby cykli (każdy cykl = kilka wywołań API)
- Rozmiaru projektu (więcej kodu = więcej tokenów)
- Typowo: $5-50 za złożone zadanie
Czy Ralph jest bezpieczny dla produkcji?
Z odpowiednią konfiguracją - tak. Rekomendacje:
requireApproval: ["production"]- Osobna gałąź dla zmian Ralph
- Code review przed merge
- CI/CD z testami
Jak Ralph radzi sobie z dużymi projektami?
Ralph obsługuje projekty z setkami plików. Używa:
- Inteligentnego filtowania plików
- Inkrementalnej analizy
- Cached embeddings dla wyszukiwania
Czy mogę użyć Ralph z innymi modelami AI?
Obecnie Ralph jest zoptymalizowany dla Claude. Wsparcie dla innych modeli jest w roadmapie.
Podsumowanie
Ralph zmienia paradygmat programowania z AI:
- Pełna autonomia - Developer jako architekt, nie wykonawca
- Cykle development - Analyze → Plan → Implement → Test → Commit
- Wbudowane bezpieczeństwo - Git snapshots, rollback, human-in-the-loop
- Skalowalność - Złożone, wieloetapowe zadania
- Transparentność - Szczegółowe logi każdej decyzji
Ralph to przyszłość software developmentu - gdzie AI wykonuje implementację, a deweloperzy skupiają się na architekturze i nadzorze.
ralph-claude-code - framework for autonomous programming
What is Ralph?
Ralph is a groundbreaking framework for fully autonomous programming using Claude Code. Unlike the standard use of Claude Code, where a developer leads a conversation and oversees every change, Ralph allows Claude to work independently for extended periods - analyzing, planning, implementing, testing, and committing code without constant human interaction.
The name "Ralph" refers to the concept of an "AI programming assistant that does the work while you ralph (relax)" - an assistant that does the work while you take a break. The framework was designed with safety in mind: it includes built-in safeguards, Git snapshots before every change, automatic rollback on errors, and optional checkpoints requiring human approval.
Ralph represents the evolution from "AI-assisted coding" to "AI-autonomous coding" - a paradigm shift where the developer becomes more of an architect and supervisor, and less of a code executor.
GitHub
Repository: github.com/anthropics/ralph-claude-code
Status: Version 0.10.1 | 310 passing tests | Active development
Why Ralph?
The problem with traditional AI-assisted coding
Standard work with Claude Code looks like this:
Developer: "Add validation to the form"
Claude: "Here's the validation code..."
Developer: "OK, now add tests"
Claude: "Here are the tests..."
Developer: "Now integrate with the backend"
Claude: "Here's the integration..."This requires the developer's constant attention, as they need to:
- Formulate the next steps
- Verify every change
- Decide what to do next
- Connect everything together
The Ralph solution
With Ralph, the workflow looks like this:
ralph "Add full contact form functionality
with validation, tests, and API integration"
# Ralph automatically:
# 1. Analyzes existing code
# 2. Plans the implementation
# 3. Creates the form component
# 4. Adds Zod validation
# 5. Writes unit tests
# 6. Integrates with the API route
# 7. Runs the tests
# 8. Commits working codeKey advantages
- Full autonomy - Ralph decides on next steps by itself
- Safety - Git snapshots and automatic rollback
- Continuous development - Analyze->plan->implement->test->commit cycles
- Scalability - Handles complex, multi-step tasks
- Human-in-the-loop - Optional checkpoints requiring approval
- Transparency - Detailed logs of every decision and action
- Error resilience - Automatic fixing and retry
- Configurability - Adjust the level of autonomy to your needs
Installation and configuration
System requirements
- Node.js 18+ or Python 3.10+
- Git 2.30+
- Claude Code CLI installed
- ANTHROPIC_API_KEY configured
- A Git repository (Ralph requires Git for snapshots)
Installation
# Clone the repository
git clone https://github.com/anthropics/ralph-claude-code
cd ralph-claude-code
# Install
./install.sh
# Or via npm
npm install -g ralph-claude-code
# Verify
ralph --version
# ralph v0.10.1Project configuration
# Initialize Ralph in a project
cd my-project
ralph-setup .
# This creates:
# .ralph/config.json - Configuration
# .ralph/prompts/ - Prompt templates
# .ralph/snapshots/ - Git snapshots
# .ralph/logs/ - Session logsConfiguration file
// .ralph/config.json
{
"model": "claude-sonnet-4-5-20241022",
"maxCycles": 50,
"cycleTimeout": 300000,
"safety": {
"gitSnapshots": true,
"autoRollback": true,
"requireApproval": ["delete", "production", "database"],
"maxFilesPerCycle": 10,
"maxLinesChanged": 500
},
"testing": {
"runTests": true,
"testCommand": "npm test",
"minCoverage": 80,
"failOnTestError": true
},
"commit": {
"autoCommit": true,
"signCommits": false,
"conventionalCommits": true
},
"monitoring": {
"logLevel": "info",
"webhookUrl": null,
"slackChannel": null
}
}Development cycle
Ralph works in cyclical iterations, where each cycle consists of specific phases:
Phase 1: Analyze
┌─────────────────────────────────────────┐
│ ANALYZE │
│ ──────── │
│ • Reading existing code │
│ • Understanding project structure │
│ • Identifying dependencies │
│ • Assessing project state │
│ • Determining task requirements │
└─────────────────────────────────────────┘Ralph analyzes the codebase, understands the architecture, identifies files to modify, and assesses what is needed to complete the task.
Phase 2: Plan
┌─────────────────────────────────────────┐
│ PLAN │
│ ──── │
│ • Creating an implementation plan │
│ • Breaking down into subtasks │
│ • Determining the order │
│ • Identifying risks │
│ • Checkpoint: Human approval? │
└─────────────────────────────────────────┘Based on the analysis, Ralph creates a detailed plan: which files to create/modify, in what order, and what the potential risks are.
Phase 3: Implement
┌─────────────────────────────────────────┐
│ IMPLEMENT │
│ ───────── │
│ • Git snapshot before changes │
│ • Writing/modifying code │
│ • Formatting and linting │
│ • Updating imports │
│ • Type checking │
└─────────────────────────────────────────┘Ralph executes the planned changes, creating a Git snapshot before each modification.
Phase 4: Test
┌─────────────────────────────────────────┐
│ TEST │
│ ──── │
│ • Running unit tests │
│ • Checking TypeScript │
│ • Verifying linting │
│ • Analyzing code coverage │
│ • If tests fail → back to PLAN │
└─────────────────────────────────────────┘Automatic test execution. If the tests do not pass, Ralph returns to the planning phase with information about the errors.
Phase 5: Review
┌─────────────────────────────────────────┐
│ REVIEW │
│ ────── │
│ • Self-review of changes │
│ • Checking best practices │
│ • Verifying security │
│ • Documenting changes │
│ • Checkpoint: Human review? │
└─────────────────────────────────────────┘Ralph reviews its own changes, looking for potential problems.
Phase 6: Commit
┌─────────────────────────────────────────┐
│ COMMIT │
│ ────── │
│ • Staging changed files │
│ • Generating commit message │
│ • Git commit │
│ • Updating changelog │
│ • Notification (if configured) │
└─────────────────────────────────────────┘If everything passed, Ralph commits the changes with an appropriate message.
Phase 7: Repeat
┌─────────────────────────────────────────┐
│ REPEAT │
│ ────── │
│ • Checking if task is complete │
│ • Selecting the next subtask │
│ • Returning to ANALYZE │
│ • Or: ending the session │
└─────────────────────────────────────────┘Ralph checks whether the main task has been completed. If not, it moves on to the next subtask.
Basic usage
Running a simple task
# Basic invocation
ralph "Add a GET /api/users endpoint returning a list of users"
# With real-time monitoring
ralph --monitor "Implement pagination for the product list"
# With a cycle limit
ralph --max-cycles 20 "Add form validation"
# Dry-run mode (no actual changes)
ralph --dry-run "Refactor the Dashboard component"Multi-step tasks
# Complex task
ralph "Create a full authentication system:
1. POST /api/auth/register endpoint
2. POST /api/auth/login endpoint
3. POST /api/auth/logout endpoint
4. JWT verification middleware
5. React components: LoginForm, RegisterForm
6. Tests for all endpoints
7. API documentation in Swagger"
# Ralph automatically:
# - Breaks it down into subtasks
# - Executes each step
# - Integrates everything together
# - Writes tests
# - Generates documentationInteractive mode
# Run with checkpoints
ralph --interactive "Redesign the payment module architecture"
# Ralph will stop and ask for approval before:
# - Deleting files
# - Changes to production code
# - Database modifications
# - Other "risky" operationsContinuing a session
# Ralph saves session state
ralph "Long task..."
# Interrupt with Ctrl+C
# Continue later
ralph --continue
# List sessions
ralph sessions list
# Resume a specific session
ralph sessions resume abc123Safety features
Git snapshots
# Before every change, Ralph creates a snapshot
.ralph/snapshots/
├── 2025-01-25_143022_pre-implement/
├── 2025-01-25_143045_pre-implement/
└── 2025-01-25_143112_pre-test/
# Manual restore
ralph rollback 2025-01-25_143022_pre-implement
# Automatic rollback on errors
# Configuration in .ralph/config.json:
# "autoRollback": trueAutomatic rollback
# Ralph automatically reverts changes when:
# 1. Tests fail
# 2. Code doesn't compile
# 3. Linting returns errors
# 4. Change limit exceeded
# Rollback log
[14:32:15] ❌ Tests failed: 3 failing
[14:32:15] 🔄 Rolling back to snapshot 2025-01-25_143112
[14:32:16] ✅ Rollback complete
[14:32:16] 📝 Analyzing failure...
[14:32:18] 🔧 Adjusting plan to fix issuesHuman-in-the-loop
// Configuration of required approvals
{
"safety": {
"requireApproval": [
"delete", // Deleting files
"production", // Production changes
"database", // DB schema changes
"security", // Security-related code
"payment", // Payment code
"api-breaking" // Breaking changes in API
]
}
}# During a session
[14:35:22] ⚠️ APPROVAL REQUIRED
[14:35:22] Action: Delete file src/old-component.tsx
[14:35:22] Reason: Component replaced by new implementation
[14:35:22] Continue? [y/N/review]:Rate limiting
{
"safety": {
"maxFilesPerCycle": 10, // Max files per cycle
"maxLinesChanged": 500, // Max lines per cycle
"maxCyclesPerHour": 100, // Max cycles per hour
"cooldownOnError": 30000 // Pause after error (ms)
}
}Access restrictions
{
"safety": {
"allowedPaths": [
"src/**",
"tests/**",
"docs/**"
],
"forbiddenPaths": [
".env*",
"secrets/**",
"*.key",
"node_modules/**"
],
"forbiddenCommands": [
"rm -rf",
"sudo",
"chmod 777"
]
}
}Advanced usage
Custom prompts
# Prompt templates in .ralph/prompts/
.ralph/prompts/
├── analyze.md # Prompt for the analysis phase
├── plan.md # Prompt for planning
├── implement.md # Prompt for implementation
├── review.md # Prompt for code review
└── custom/ # Custom prompts<!-- .ralph/prompts/custom/security-audit.md -->
# Security Audit Task
Perform a security audit for {{files}}:
1. Check for OWASP Top 10 vulnerabilities
2. Verify input sanitization
3. Check authentication handling
4. Verify authorization
5. Find potential SQL injection
6. Check for XSS vulnerabilities
For each issue:
- Describe the vulnerability
- Assess severity (Critical/High/Medium/Low)
- Suggest a fix
- Implement the correction# Using a custom prompt
ralph --prompt security-audit "Audit the auth module"CI/CD integration
# .github/workflows/ralph-autofix.yml
name: Ralph Autofix
on:
push:
branches: [main]
jobs:
autofix:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Ralph
run: npm install -g ralph-claude-code
- name: Run Linting
id: lint
continue-on-error: true
run: npm run lint
- name: Autofix with Ralph
if: steps.lint.outcome == 'failure'
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
ralph --non-interactive \
--max-cycles 10 \
"Fix all ESLint errors in the project"
- name: Create PR
if: steps.lint.outcome == 'failure'
uses: peter-evans/create-pull-request@v5
with:
title: "fix: Ralph autofix for linting errors"
branch: ralph-autofixWebhooks and notifications
{
"monitoring": {
"webhookUrl": "https://api.example.com/ralph-events",
"slackChannel": "#dev-automation",
"events": ["cycle_complete", "task_complete", "error", "approval_needed"]
}
}interface RalphEvent {
type: 'cycle_complete' | 'task_complete' | 'error' | 'approval_needed'
sessionId: string
timestamp: string
data: {
task: string
cycle: number
filesChanged: string[]
testsResult?: 'pass' | 'fail'
error?: string
}
}Programmatic API
import { Ralph, RalphConfig, RalphSession } from 'ralph-claude-code'
const config: RalphConfig = {
model: 'claude-sonnet-4-5-20241022',
maxCycles: 30,
safety: {
autoRollback: true,
requireApproval: ['delete', 'production']
}
}
const ralph = new Ralph(config)
const session = await ralph.run({
task: 'Add /api/products endpoint with CRUD',
onCycleComplete: (cycle) => {
console.log(`Cycle ${cycle.number} complete`)
},
onApprovalNeeded: async (action) => {
const approved = await askUser(action)
return approved
}
})
session.on('log', (message) => console.log(message))
session.on('error', (error) => console.error(error))
session.on('complete', (result) => console.log('Done!', result))
await session.stop()
await session.resume()Multi-agent mode (experimental)
# Run multiple agents in parallel
ralph --agents 3 "Refactor all React components"
# Agent 1: src/components/Auth/*
# Agent 2: src/components/Dashboard/*
# Agent 3: src/components/Settings/*
# Coordination by the main agentMonitoring and logs
Session logs
# View logs in real time
ralph --monitor "Task..."
# Logs are saved in .ralph/logs/
.ralph/logs/
├── session_abc123.log # Session log
├── session_abc123.json # Structured log
└── session_abc123.md # Human-readable reportDashboard (optional)
# Run the local dashboard
ralph dashboard
# Open http://localhost:3333
# Monitor:
# - Active sessions
# - Task history
# - Statistics (cycles, time, success/fail)
# - Real-time logsMetrics
# Project statistics
ralph stats
# Output:
# ═══════════════════════════════════════
# Ralph Statistics for my-project
# ═══════════════════════════════════════
# Total sessions: 47
# Successful: 43 (91.5%)
# Failed: 4 (8.5%)
# Total cycles: 892
# Avg cycles/task: 19
# Files modified: 234
# Lines changed: 12,450
# Tests written: 89
# Commits: 43
# ═══════════════════════════════════════Ralph vs alternatives
| Feature | Ralph | Claude Code | Devin | GitHub Copilot |
|---|---|---|---|---|
| Autonomy | Full | Supervised | Full | Suggestions |
| Dev cycles | Yes | No | Yes | No |
| Git safety | Built-in | Manual | Built-in | None |
| Auto tests | Yes | Manual | Yes | No |
| Human-in-loop | Configurable | Always | Configurable | N/A |
| Open-source | Yes | Partially | No | No |
| Cost | Claude API | Claude API | $500/mo | $10-19/mo |
| Setup | Medium | Simple | Complex | Simple |
Troubleshooting
Common issues
# Problem: Ralph stuck in a loop
ralph --max-cycles 10 "Task..." # Limit cycles
# Problem: Too many changes at once
# Configuration in .ralph/config.json:
# "maxFilesPerCycle": 5
# Problem: Tests keep failing
ralph --skip-tests "Task..." # Temporarily skip
# OR: Fix tests first
ralph "Fix failing tests before continuing"
# Problem: API rate limit
ralph --cycle-delay 5000 "Task..." # Pause between cycles
# Problem: Incomprehensible changes
ralph --verbose "Task..." # More details in logsDebug mode
# Full debug logs
export RALPH_DEBUG=1
ralph "Task..."
# Stop after each cycle
ralph --step-by-step "Task..."
# Save full Claude context
ralph --save-context "Task..."FAQ - frequently asked questions
Can I leave Ralph unsupervised?
Yes, but with proper configuration. For safety, set:
maxCycles- cycle limitrequireApprovalfor risky operations- Slack/webhook notifications
- Regular commit reviews
How expensive is Ralph?
Ralph uses the Claude API, so costs depend on:
- Number of cycles (each cycle = several API calls)
- Project size (more code = more tokens)
- Typically: $5-50 for a complex task
Is Ralph safe for production?
With proper configuration - yes. Recommendations:
requireApproval: ["production"]- A separate branch for Ralph changes
- Code review before merge
- CI/CD with tests
How does Ralph handle large projects?
Ralph handles projects with hundreds of files. It uses:
- Intelligent file filtering
- Incremental analysis
- Cached embeddings for search
Can I use Ralph with other AI models?
Currently Ralph is optimized for Claude. Support for other models is on the roadmap.
Summary
Ralph changes the paradigm of programming with AI:
- Full autonomy - Developer as architect, not executor
- Development cycles - Analyze -> Plan -> Implement -> Test -> Commit
- Built-in safety - Git snapshots, rollback, human-in-the-loop
- Scalability - Complex, multi-step tasks
- Transparency - Detailed logs of every decision
Ralph is the future of software development - where AI handles the implementation and developers focus on architecture and oversight.