К основному содержанию
плагин официальный · Anthropic

ralph-loop — плагин для Claude Code: циклы до готовой задачи

Запускает Claude по кругу с одним и тем же промптом, пока задача не будет выполнена. Пригодится там, где нужен перебор итераций: тесты, отладка, сборка API.

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin install ralph-loop@claude-plugins-official
/plugin marketplace add anthropics/claude-plugins-official
Открыть на GitHub

Что делает ralph-loop

Плагин реализует технику Ralph Wiggum: Claude работает над задачей, пытается завершить сессию, а Stop hook из hooks/stop-hook.sh не даёт выйти и подсовывает тот же промпт заново. Цикл идёт внутри текущей сессии, внешний while true не нужен. Промпт между итерациями не меняется, зато файлы и история git остаются — на следующем проходе Claude читает собственную работу и правит её.

Запуск делается один раз: /ralph-loop "описание задачи" --completion-promise "DONE". Опция --max-iterations <n> останавливает цикл после N проходов, по умолчанию лимита нет. Остановить вручную — /cancel-ralph. Сравнение с фразой завершения идёт по точному совпадению строки, поэтому несколько условий выхода так не задать.

На Windows хук может сломаться: команда bash уходит в WSL вместо Git Bash. Тогда правят hooks/hooks.json в кэше плагина и прописывают путь к Git/bin/bash.exe явно. Для задач, где нужны решения человека или размытые критерии успеха, цикл не подходит — Claude будет крутиться впустую.

Какие задачи решает

  • довести падающие тесты до зелёного прогона
  • собрать REST API по списку требований
  • пройти фазы задачи по очереди без ручного перезапуска
  • отладить код по выводу линтера и тестов
  • добить фичу, когда критерии готовности расписаны заранее

Примеры запросов агенту

  • /ralph-loop "Собери REST API для todos: CRUD, валидация входа, тесты. Выведи <promise>COMPLETE</promise> когда закончишь." --completion-promise "COMPLETE" --max-iterations 50
  • /ralph-loop "Реализуй фичу X по TDD: сначала падающие тесты, потом код, гоняй тесты пока все не станут зелёными" --max-iterations 20
  • /cancel-ralph

Как установить ralph-loop

Через маркетплейс плагинов

/plugin install ralph-loop@claude-plugins-official
/plugin marketplace add anthropics/claude-plugins-official

По шагам, с командами для каждой платформы: Плагины Claude Code: маркетплейсы, установка и как собрать свой

Из того же набора123

Весь набор →
security-guidance Три слоя проверки кода, который пишет Claude: мгновенные предупреждения по regex, разбор диффа через LLM и агентная проверка коммитов. ★ 44 635звёзд репо rust-analyzer-lsp Подключает языковой сервер rust-analyzer к Claude, чтобы агент видел структуру Rust-кода и анализировал его. ★ 44 635звёзд репо ruby-lsp Плагин подключает языковой сервер Ruby к Claude Code для анализа кода и навигации по файлам .rb, .rake, .gemspec, .ru и .erb. ★ 44 635звёзд репо receipts Собирает отчёт из ваших сессий Claude: что сделано, в каких проектах и какая доля использования у каждого. ★ 44 635звёзд репо pyright-lsp Подключает языковой сервер Pyright к Claude Code для статической проверки типов. Помогает находить ошибки в файлах Python с расширениями .py и .pyi. ★ 44 635звёзд репо project-artifact Плагин собирает живую страницу статуса проекта и публикует её как артефакт claude.ai. Обновление повторно читает источники и сохраняет тот же URL. ★ 44 635звёзд репо pr-review-toolkit Шесть субагентов для ревью пул-реквестов: комментарии, тесты, обработка ошибок, типы, качество кода и упрощение. ★ 44 635звёзд репо plugin-dev Набор из семи навыков и пошаговой команды для создания плагинов к Claude Code. Помогает настроить хуки, MCP-серверы, слэш-команды и агентов. ★ 44 635звёзд репо

Похожие

loop-worker ruvnet Запускает фоновых воркеров Ruflo по расписанию /loop и проверяет их через MCP. Нужен для повторяющихся проверок кода и задач. CX Codex +1 744установок loop-library Forward-Future Алиас совместимости для Loopy, который находит повторяющиеся задачи в коде, подбирает готовые циклы с точками выхода или проектирует новые через интервью. CX Codex +1 2 400установок autopilot-loop ruvnet Скилл запускает одну итерацию автономного цикла: проверяет прогресс, выбирает следующую задачу и расписывает пробуждение агента. Нужен, если вы хотите, чтобы Claude работал без перерывов между задачами. CX Codex +1 752установок ralph-wiggum fstandhartinger Автономный цикл разработки по спецификациям. Скилл перезапускает контекст на каждой итерации, чтобы агент не терял нить задачи при долгой работе. CX Codex +1 1 400установок design-control-loop humanlayer Скилл проводит интервью и вместе с вами проектирует агентскую петлю контроля: уставка, датчик, контроллер, актуатор. Потом собирает её прямо в вашем репозитории. CX Codex +1 1 600установок design-loop jezweb Скилл ведёт цикл: читает задачу из файла-эстафеты, генерирует страницу в HTML/Tailwind, встраивает её в сайт и пишет следующую задачу. CX Codex +1 1 000установок continuous-agent-loop affaan-m Скилл задаёт схему автономного цикла агента: выбор режима, контроль качества, прогон evals и выход из сбоев. Пригодится, когда агент работает без присмотра. CX Codex +1 4 500установок

Рядом в теме «Настройка агента: память, контекст, субагенты»

Все плагины по теме «Настройка агента: память, контекст, субагенты» →

Вопросы о ralph-loop

Как установить ralph-loop в Claude?

Сначала добавьте маркетплейс: /plugin marketplace add anthropics/claude-plugins-official. Затем поставьте плагин: /plugin install ralph-loop@claude-plugins-official.

Что делает ralph-loop?

Гоняет Claude по одному и тому же промпту, пока задача не выполнена. Выход из сессии блокирует Stop hook, поэтому итерации идут в текущей сессии.

Чем ограничен цикл ralph-loop?

Опцией --max-iterations <n> — без неё лимита нет. Фраза завершения из --completion-promise сравнивается точно, так что несколько условий выхода через неё не задать.

Исходный текст

ralph-loop · Apache-2.0
# Ralph Loop Plugin

Implementation of the Ralph Wiggum technique for iterative, self-referential AI development loops in Claude Code.

## What is Ralph Loop?

Ralph Loop is a development methodology based on continuous AI agent loops. As Geoffrey Huntley describes it: **"Ralph is a Bash loop"** - a simple `while true` that repeatedly feeds an AI agent a prompt file, allowing it to iteratively improve its work until completion.

This technique is inspired by the Ralph Wiggum coding technique (named after the character from The Simpsons), embodying the philosophy of persistent iteration despite setbacks.

### Core Concept

This plugin implements Ralph using a **Stop hook** that intercepts Claude's exit attempts:

```bash
# You run ONCE:
/ralph-loop "Your task description" --completion-promise "DONE"

# Then Claude Code automatically:
# 1. Works on the task
# 2. Tries to exit
# 3. Stop hook blocks exit
# 4. Stop hook feeds the SAME prompt back
# 5. Repeat until completion
```

The loop happens **inside your current session** - you don't need external bash loops. The Stop hook in `hooks/stop-hook.sh` creates the self-referential feedback loop by blocking normal session exit.

This creates a **self-referential feedback loop** where:
- The prompt never changes between iterations
- Claude's previous work persists in files
- Each iteration sees modified files and git history
- Claude autonomously improves by reading its own past work in files

## Quick Start

```bash
/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
```

Claude will:
- Implement the API iteratively
- Run tests and see failures
- Fix bugs based on test output
- Iterate until all requirements met
- Output the completion promise when done

## Commands

### /ralph-loop

Start a Ralph loop in your current session.

**Usage:**
```bash
/ralph-loop "<prompt>" --max-iterations <n> --completion-promise "<text>"
```

**Options:**
- `--max-iterations <n>` - Stop after N iterations (default: unlimited)
- `--completion-promise <text>` - Phrase that signals completion

### /cancel-ralph

Cancel the active Ralph loop.

**Usage:**
```bash
/cancel-ralph
```

## Prompt Writing Best Practices

### 1. Clear Completion Criteria

❌ Bad: "Build a todo API and make it good."

✅ Good:
```markdown
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>
```

### 2. Incremental Goals

❌ Bad: "Create a complete e-commerce platform."

✅ Good:
```markdown
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.
```

### 3. Self-Correction

❌ Bad: "Write code for feature X."

✅ Good:
```markdown
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>
```

### 4. Escape Hatches

Always use `--max-iterations` as a safety net to prevent infinite loops on impossible tasks:

```bash
# Recommended: Always set a reasonable iteration limit
/ralph-loop "Try to implement feature X" --max-iterations 20

# In your prompt, include what to do if stuck:
# "After 15 iterations, if not complete:
#  - Document what's blocking progress
#  - List what was attempted
#  - Suggest alternative approaches"
```

**Note**: The `--completion-promise` uses exact string matching, so you cannot use it for multiple completion conditions (like "SUCCESS" vs "BLOCKED"). Always rely on `--max-iterations` as your primary safety mechanism.

## Philosophy

Ralph embodies several key principles:

### 1. Iteration > Perfection
Don't aim for perfect on first try. Let the loop refine the work.

### 2. Failures Are Data
"Deterministically bad" means failures are predictable and informative. Use them to tune prompts.

### 3. Operator Skill Matters
Success depends on writing good prompts, not just having a good model.

### 4. Persistence Wins
Keep trying until success. The loop handles retry logic automatically.

## When to Use Ralph

**Good for:**
- Well-defined tasks with clear success criteria
- Tasks requiring iteration and refinement (e.g., getting tests to pass)
- Greenfield projects where you can walk away
- Tasks with automatic verification (tests, linters)

**Not good for:**
- Tasks requiring human judgment or design decisions
- One-shot operations
- Tasks with unclear success criteria
- Production debugging (use targeted debugging instead)

## Real-World Results

- Successfully generated 6 repositories overnight in Y Combinator hackathon testing
- One $50k contract completed for $297 in API costs
- Created entire programming language ("cursed") over 3 months using this approach

## Windows Compatibility

The stop hook uses a bash script that requires Git for Windows to run properly.

**Issue**: On Windows, the `bash` command may resolve to WSL bash (often misconfigured) instead of Git Bash, causing the hook to fail with errors like:
- `wsl: Unknown key 'automount.crossDistro'`
- `execvpe(/bin/bash) failed: No such file or directory`

**Workaround**: Edit the cached plugin's `hooks/hooks.json` to use Git Bash explicitly:

```json
"command": "\"C:/Program Files/Git/bin/bash.exe\" ${CLAUDE_PLUGIN_ROOT}/hooks/stop-hook.sh"
```

**Location**: `~/.claude/plugins/cache/claude-plugins-official/ralph-wiggum/<hash>/hooks/hooks.json`

**Note**: Use `Git/bin/bash.exe` (the wrapper with proper PATH), not `Git/usr/bin/bash.exe` (raw MinGW bash without utilities in PATH).

## Learn More

- Original technique: https://ghuntley.com/ralph/
- Ralph Orchestrator: https://github.com/mikeyobrien/ralph-orchestrator

## For Help

Run `/help` in Claude Code for detailed command reference and examples.

© Anthropic · Apache-2.0 · anthropics/claude-plugins-official

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой