npm package: @orenmaoz/ralph-loop
Description: Autonomous agent execution for feature specs — break specs into agent roles, run them in phased pipelines with coding agents
Latest version: 0.3.7

# ralph-loop

Autonomous agent execution for feature specs — break specs into agent roles, run them in phased pipelines with coding agents.

```
npx @orenmaoz/ralph-loop init                          # Scaffold into your repo
npx @orenmaoz/ralph-loop bootstrap <spec-dir>          # Analyze spec → create agents
npx @orenmaoz/ralph-loop run <spec-dir>                # Execute all phases
npx @orenmaoz/ralph-loop status <spec-dir>             # Show progress
npx @orenmaoz/ralph-loop reset <spec-dir>              # Remove bootstrap artifacts
```

## How It Works

```
Your Spec                        Ralph Loop
────────                        ──────────
spec.md   ─────────────────→  1. Bootstrapper analyzes spec
plan.md                        2. Creates agent roles
tasks.md                       3. Creates job directories
                               4. Creates orchestrator
                                      │
                                      ▼
                              ┌─── Orchestrator ──┐
                              │  Runs phases       │
                              │  Tracks progress   │
                              │  Sets env vars     │
                              └────────┬──────────┘
                                       │
                    ┌──────────────────┬┴──────────────────┐
                    ▼                  ▼                    ▼
            ralph-jobs/          ralph-jobs/           ralph-jobs/
            <spec>/agent-1/      <spec>/agent-2/       <spec>/agent-3/
              prompt.md            prompt.md             prompt.md
              stop-hook.ps1        stop-hook.ps1         stop-hook.ps1
```

Each agent:
- Gets a scoped `prompt.md` with the specific files it owns
- Runs iteratively until its tasks in `tasks.md` are checked off
- Is validated by a `stop-hook.ps1` with deterministic completion checks
- Is constrained by VS Code hooks (scope guard, lint, forbidden patterns)

## Prerequisites

- Node.js >= 18 (for npx)
- PowerShell 7+ (`pwsh`)
- A coding agent CLI (e.g., `copilot`, or use VS Code Copilot Chat in Agent Mode)

## Quick Start

### 1. Initialize

```bash
cd your-repo
npx @orenmaoz/ralph-loop init
```

This scaffolds into your repo:
- `ralph-loop.ps1` — core loop script
- `bootstrap-ralph-loop.md` — bootstrapper prompt
- `.github/hooks/` — VS Code agent hooks (scope guard, lint, stop validation)

### 2. Create a Spec (Recommended: spec-kit)

Use [spec-kit](https://github.com/github/spec-kit) to generate well-structured input:

```powershell
# Install spec-kit (one-time)
uv tool install specify-cli --from git+https://github.com/github/spec-kit.git

# Initialize (one-time)
specify init . --ai copilot --script ps --force
```

Then in Copilot Chat:
```
/speckit.specify <describe your feature>
/speckit.plan <tech stack, constraints>
/speckit.tasks
```

This produces `spec.md`, `plan.md`, and `tasks.md` in your spec directory.

### 3. Bootstrap Agents

```bash
npx @orenmaoz/ralph-loop bootstrap specs/my-feature
```

This invokes a coding agent to analyze your spec and create:
- `agent-roles.md` — which agents are needed and their phases
- `create-ralph-jobs.ps1` — job directory generator
- `run-spec.ps1` — orchestrator with progress tracking
- `hooks/` — scope map, review patterns, stop validation
- Tagged tasks in `tasks.md` with `[agent-name]`
- `ralph-jobs/<spec>/` — per-agent job directories

Options:
```bash
npx @orenmaoz/ralph-loop bootstrap specs/my-feature --agent "claude"     # Use Claude CLI
npx @orenmaoz/ralph-loop bootstrap specs/my-feature --model "gpt-5.1"    # Different model
npx @orenmaoz/ralph-loop bootstrap specs/my-feature --yolo               # No confirmations
```

### 4. Run

```bash
npx @orenmaoz/ralph-loop run specs/my-feature
```

Options:
```bash
npx @orenmaoz/ralph-loop run specs/my-feature --start-phase 3           # Skip to phase 3
npx @orenmaoz/ralph-loop run specs/my-feature --start-job backend-agent  # Resume specific agent
npx @orenmaoz/ralph-loop run specs/my-feature --model claude-sonnet-4.5  # Override model
```

### 5. Monitor

```bash
npx @orenmaoz/ralph-loop status specs/my-feature
```

Shows:
- Which spec files and bootstrap artifacts exist
- Agent job status and iteration counts
- Task completion percentage
- Phase progress

## File Structure

After bootstrapping:

```
specs/my-feature/
├── spec.md                      # Your feature specification
├── plan.md                      # Implementation plan
├── tasks.md                     # Task checklist with [agent-name] tags
├── agent-roles.md               # Agent role definitions
├── create-ralph-jobs.ps1        # Job directory generator
├── run-spec.ps1                 # Orchestrator script
├── .progress.json               # Execution progress (runtime)
└── hooks/
    ├── scope-map.json           # Agent → allowed file paths
    ├── review-patterns.json     # Forbidden string patterns
    └── stop-validation.ps1      # Per-agent completion criteria

ralph-jobs/my-feature/
├── backend-agent/
│   ├── prompt.md                # Scoped instructions
│   ├── stop-hook.ps1            # Completion checks
│   └── sessions/                # Iteration logs (runtime)
├── api-agent/
│   └── ...
```

## VS Code Hooks

Hooks in `.github/hooks/` fire automatically during Copilot agent sessions:

| Hook | Script | Behavior |
|------|--------|----------|
| **SessionStart** | `session-start.ps1` | Injects spec context (tasks, plan, role) into the agent |
| **PreToolUse** | `scope-guard.ps1` | Blocks file edits outside the agent's allowed paths |
| **PostToolUse** | `post-edit-review.ps1` | Runs linters + forbidden pattern checks after edits |
| **Stop** | `stop-validation.ps1` | Validates agent completed its tasks and spec criteria |
| **Stop** | `pre-commit-review.ps1` | Full code review gate across all changed files |

Hooks are spec-aware via `$env:SPEC_DIR`:
- **No spec configured** → hooks pass through (linters still run)
- **Spec set, no hooks folder yet** → hooks pass through
- **Fully bootstrapped** → full enforcement
## Parallel Isolation with Git Worktrees

When multiple agents run in the same phase, each gets its own **Git worktree** — a separate working directory backed by the same repository. This provides physical isolation on top of the logical scope guard:

```
Phase 2 — parallel agents, each in its own worktree:

  repo/  (main branch)
    |
    |    .ralph-worktrees/my-feature/
    |        |
    |        |-- api-agent/                   full repo copy
    |        |     branch: ralph/my-feature/api-agent
    |        |     edits:  src/api/*
    |        |
    |        |-- docs-agent/                  full repo copy
    |              branch: ralph/my-feature/docs-agent
    |              edits:  docs/*
    |
    |    agents complete
    |        |
    |        |-- merge api-agent branch  --> main
    |        |-- merge docs-agent branch --> main
    |        |-- delete worktrees + branches
    v
  repo/  (main branch, all changes merged)
```

**Why this matters:**
- **Git staging** — each agent stages only its own files (no cross-contamination)
- **Commits** — each agent commits to its own branch independently
- **git status** — only shows the agent's changes (no noise from other agents)
- **Merge** — after the phase, branches merge back sequentially into the main branch

**How it works (automatic):**
1. Orchestrator creates a worktree per parallel agent before launching
2. Each agent runs in its worktree, editing files and committing freely
3. After all agents finish, branches are merged back and worktrees are cleaned up
4. If a merge conflict occurs (shouldn't happen with proper scope boundaries), execution stops for manual resolution

Sequential phases (single agent) skip worktrees entirely — zero overhead.
## Environment Variables

| Variable | Purpose |
|----------|---------|
| `SPEC_DIR` | Path to the spec directory |
| `TASKS_FILE` | Path to `tasks.md` |
| `JOB_DIR` | Path to the agent's job directory |
| `RALPH_AGENT_ROLE` | Current agent name |
| `RALPH_PHASE` | Current phase number |
| `MODEL_NAME` | LLM model for this agent |
| `MAX_RETRIES_PER_TASK` | Retries before skipping a task (default: 3) |
| `MAX_ITERATIONS` | Total iterations per agent (default: 5) |
| `COPILOT_ARGS` | Extra args for the agent CLI (default: `--yolo`) |
| `RALPH_WORKTREE` | Worktree path for parallel isolation (set automatically by orchestrator) |

## Commands

### `ralph-loop init`

Scaffold ralph-loop files into the current repo.

```bash
npx @orenmaoz/ralph-loop init
npx @orenmaoz/ralph-loop init --hooks-dir .vscode/hooks   # Custom hooks location
npx @orenmaoz/ralph-loop init --force                      # Overwrite existing files
```

### `ralph-loop bootstrap <spec-dir>`

Analyze a spec and create all agent infrastructure.

```bash
npx @orenmaoz/ralph-loop bootstrap specs/my-feature
npx @orenmaoz/ralph-loop bootstrap specs/my-feature --agent "copilot"
npx @orenmaoz/ralph-loop bootstrap specs/my-feature --model claude-opus-4.6
npx @orenmaoz/ralph-loop bootstrap specs/my-feature --yolo
```

### `ralph-loop run <spec-dir>`

Execute the orchestrator.

```bash
npx @orenmaoz/ralph-loop run specs/my-feature
npx @orenmaoz/ralph-loop run specs/my-feature --start-phase 2
npx @orenmaoz/ralph-loop run specs/my-feature --start-job docs-agent
npx @orenmaoz/ralph-loop run specs/my-feature --model claude-sonnet-4.5
```

### `ralph-loop status <spec-dir>`

Show progress.

```bash
npx @orenmaoz/ralph-loop status specs/my-feature
```

### `ralph-loop reset <spec-dir>`

Remove all bootstrap artifacts for a spec, preserving spec files (`spec.md`, `plan.md`, `tasks.md`) and init infrastructure.

```bash
npx @orenmaoz/ralph-loop reset specs/my-feature           # Dry-run: show what would be removed
npx @orenmaoz/ralph-loop reset specs/my-feature --force    # Actually delete the artifacts
```

Removes:
- `agent-roles.md`, `create-ralph-jobs.ps1`, `run-spec.ps1`, `.bootstrap-prompt.md`, `.progress.json`
- `hooks/` directory inside the spec dir
- `ralph-jobs/<spec>/` job directories

### `ralph-loop update`

Update ralph-loop files to the latest package version.

```bash
npx @orenmaoz/ralph-loop update
npx @orenmaoz/ralph-loop update --hooks-dir .vscode/hooks
```

## Troubleshooting

| Problem | Solution |
|---------|----------|
| Agent loops without progress | Check `ralph-jobs/<spec>/<agent>/sessions/` — if last 3 iterations repeat, update `prompt.md` with hints |
| Stop hook never passes | Run `stop-hook.ps1` manually to see which check fails |
| Agent edits wrong files | Verify `hooks/scope-map.json` has correct paths for each agent |
| `TASKS_FILE env var is required` | Run via `npx @orenmaoz/ralph-loop run` or the spec's `run-spec.ps1`, not `ralph-loop.ps1` directly |
| Parallel agents conflict | Agents in the same phase use Git worktrees for isolation (automatic). If you see merge conflicts, tighten `scope-map.json` so agents own non-overlapping file sets |
| Worktree merge fails | Resolve conflicts in the main repo (`git merge --continue`), then re-run the orchestrator |
| Need to re-bootstrap | Run `npx @orenmaoz/ralph-loop reset <spec-dir> --force`, then re-run bootstrap |

## Acknowledgments

This project stands on the shoulders of great ideas:

- **[Geoffrey Huntley](https://ghuntley.com/loop/)** — for his unique approach to autonomous agent looping that inspired the core execution model.
- **[Scott Hanselman](https://gist.github.com/shanselman/aa5e34a74b36404123dabed9394655f3)** — for the inspiration that helped shape this project.

## License

MIT