> ## Documentation Index
> Fetch the complete documentation index at: https://taskgraph-ai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Loop Command

> Run Claude Code in autonomous loops for batch task completion

# Loop Command

The `loop` command runs Claude Code in autonomous loops, spawning fresh agent sessions for each iteration. This approach, known as the "Ralph Wiggum pattern" (credited to Jeffrey Huntley, popularized by Matt Pocock), maintains context quality by avoiding long-running sessions that accumulate context fatigue.

## Overview

Instead of a single long-running agent session that degrades over time, the loop command:

1. **Spawns fresh sessions** - Each iteration starts with a clean context
2. **Uses preset prompts** - Built-in or custom prompts guide each iteration
3. **Tracks progress** - A progress file persists notes across sessions
4. **Detects completion** - Special markers signal when work is done or blocked

This pattern is ideal for batch operations like clearing task backlogs, improving test coverage, or fixing lint errors across a codebase.

## Basic Usage

Work through the backlog with the default task-completion preset, one iteration per pending task:

```bash theme={null}
taskgraph loop
```

Cap the run at 10 iterations:

```bash theme={null}
taskgraph loop -n 10
```

Run 5 iterations with the test-coverage preset:

```bash theme={null}
taskgraph loop -n 5 --prompt test-coverage
```

Run iterations with a custom prompt file:

```bash theme={null}
taskgraph loop -n 10 --prompt ./my-custom-prompt.md
```

Filter to specific task tag:

```bash theme={null}
taskgraph loop -n 10 --tag backend
```

Work on one task (or subtask) instead of the one `taskgraph next` picks. It runs one iteration unless you pass `-n`:

```bash theme={null}
taskgraph loop --id 3
taskgraph loop --id 3.2 --prompt tdd
```

`--id` works with the `default` and `tdd` presets and with custom prompt files. The other presets pick their own work, so `loop` refuses `--id` with them. A task ID that doesn't exist fails before Claude Code starts.

Watch Claude work as it goes, instead of seeing each iteration's output when it ends:

```bash theme={null}
taskgraph loop -n 5 --verbose
```

### Permission prompts

Each iteration runs `claude -p` with permission prompts off (`--dangerously-skip-permissions`), so Claude can read, edit and run anything in the project without asking. The first run in a project asks you to allow that and remembers your answer in `~/.taskgraph/loop-trusted.json`. In a script or CI, where nothing can answer, pass `--trust`. To keep Claude off your machine, pass `--sandbox` to run each iteration in a Docker sandbox (`docker sandbox run claude`) instead; the first sandbox run asks you to sign in.

## How It Works

Each loop iteration:

1. Builds a prompt from a short header (the progress file and `CLAUDE.md` as `@` references, the iteration number, the tag and any `--id` task) followed by the preset or custom prompt
2. Spawns `claude -p <prompt>` as a fresh subprocess in the project root
3. Captures output and checks for completion markers
4. Waits 5 seconds before the next iteration

The agent appends its own notes to the progress file as the prompt tells it to.

The loop stops when:

* An agent outputs `<loop-complete>REASON</loop-complete>` - all work done
* An agent outputs `<loop-blocked>REASON</loop-blocked>` - cannot proceed
* Maximum iterations reached

It then prints the number of iterations, the tasks completed and the final status. The exit code is 1 when the loop ended blocked or on an error, and 0 otherwise, so a script can tell a stuck loop from a finished one.

## CLI Options

| Option | Type | Default | Description |
| - | - | - | - |
| `-n, --iterations` | number | see description | Maximum number of iterations to run. Without it: 1 with `--id`; the number of pending tasks and subtasks with the `default` and `tdd` presets (10 when none are pending); otherwise 10. |
| `-i, --id` | string | - | Work on this task or subtask (`3`, `3.2`) instead of the next one. Runs 1 iteration unless `-n` is given. Works with the `default` and `tdd` presets and custom prompt files. |
| `-p, --prompt` | string | `default` | Preset name or path to a custom prompt file. Accepts: `default`, `tdd`, `test-coverage`, `linting`, `duplication`, `entropy`, or a file path like `./my-prompt.md`. |
| `--progress-file` | string | `.taskgraph/progress.txt` | Path to the progress log file, attached to every iteration's prompt. |
| `-t, --tag` | string | - | Filter to only work on tasks with this tag. |
| `--project` | string | - | Project root directory. Auto-detected if not provided. |
| `--sandbox` | flag | - | Run each iteration in a Docker sandbox (`docker sandbox run claude`) instead of on this machine. |
| `--trust` | flag | - | Run Claude with permission prompts off without asking first. For scripts and CI. |
| `--no-output` | flag | - | Leave Claude's full output out of the iteration results. |
| `-v, --verbose` | flag | - | Show Claude's work (its messages and tool calls) as it happens. |
| `--parallel` | number | - | Run up to N ready tasks at once, each in its own git worktree and branch. See [Run tasks in parallel](https://taskgraph-ai.com/capabilities/loop-parallel.md). |

### Option Details

**`--prompt` accepts two types of values:**

* **Preset names**: Use built-in presets like `default`, `tdd`, `test-coverage`, `linting`, `duplication`, or `entropy`
* **File paths**: Provide a path to a custom prompt file (e.g., `./my-custom-loop.md`)

## Run tasks in parallel

`taskgraph loop --parallel N` runs up to N independent tasks side by side, each in its own git worktree and branch. See [Run tasks in parallel](https://taskgraph-ai.com/capabilities/loop-parallel.md).

## Built-in Presets

Six built-in presets cover common workflows: `default` (the TaskGraph backlog), `tdd` (the backlog, test-first), `test-coverage`, `linting`, `duplication` and `entropy`. See [Loop Presets](https://taskgraph-ai.com/capabilities/loop-presets.md) for what each one does.

## Custom Prompts

You can create custom prompt files for specialized workflows that aren't covered by the built-in presets.

### Specifying a Custom Prompt

Pass the file path to the `--prompt` option:

```bash theme={null}
taskgraph loop -n 10 --prompt ./my-custom-loop.md
```

The path can be absolute or relative to the current directory.

### Required Structure

Custom prompts should follow this structure to work effectively with the loop system:

```markdown theme={null}
# Your Loop Title

Brief description of what this loop does.

## Files Available

- @.taskgraph/tasks/tasks.json - Your task backlog
- @path/to/other/file.ts - Any other files the agent needs

## Process

1. Step one of the workflow
2. Step two of the workflow
3. ... more steps

## Important

- Complete ONLY ONE task per session
- Keep changes small and focused
- Do NOT start another task after completing one
- If work is complete, output: <loop-complete>REASON</loop-complete>
- If blocked, output: <loop-blocked>REASON</loop-blocked>
```

### File References with @ Syntax

The `@` prefix makes files available to the agent. Claude Code will read these files when processing the prompt:

```markdown theme={null}
## Files Available

- @src/index.ts - Main entry point
- @package.json - Dependencies and scripts
```

Without the `@` prefix, file paths are just text. With `@`, the agent can actually read and reference the file contents.

### Completion Markers

The loop watches for two special markers in agent output:

| Marker | Purpose | Example |
| - | - | - |
| `<loop-complete>REASON</loop-complete>` | Signal that all work is done | `<loop-complete>ALL_TESTS_PASSING</loop-complete>` |
| `<loop-blocked>REASON</loop-blocked>` | Signal that work cannot proceed | `<loop-blocked>MISSING_ENV_VAR</loop-blocked>` |

When either marker is detected, the loop exits early. The reason text is captured in the final result.

**Example usage in a custom prompt:**

```markdown theme={null}
## Important

- If all migrations are complete, output: <loop-complete>MIGRATIONS_DONE</loop-complete>
- If a migration fails with an unrecoverable error, output: <loop-blocked>MIGRATION_FAILED: describe error</loop-blocked>
```

### Best Practices

1. **Be specific**: Clearly define what "done" means for your workflow
2. **One task per iteration**: Instruct agents to complete exactly one unit of work
3. **Use the progress file**: It is attached to every prompt; tell agents to append a note to it so the next iteration sees what was done
4. **Include quality checks**: Add steps for running tests or type checks before completing
5. **Define completion criteria**: Tell agents exactly when to output `<loop-complete>`
6. **Handle edge cases**: Define when to output `<loop-blocked>` to avoid infinite loops

## Progress File

The progress file is a shared log that persists notes across loop iterations. Since each iteration spawns a fresh agent session, this file provides continuity.

### Default Location

```
.taskgraph/progress.txt
```

Override with the `--progress-file` option:

```bash theme={null}
taskgraph loop -n 10 --progress-file ./my-progress.txt
```

### How It Works

1. **Start**: The loop appends a header to the file, creating it if needed. Earlier runs' notes are kept.
2. **Each iteration**: The prompt attaches the file with an `@` reference, and the agent appends notes about its work
3. **End**: The loop appends a summary of the run

### File Format

The loop writes the header and the summary; the lines in between are whatever the agents append:

```
# TaskGraph Loop Progress
# Started: 2026-01-09T10:30:00.000Z
# Preset: default
# Max Iterations: 10
# Tag: backend

---

Task 5.2: added the login endpoint. Learned: tokens live in src/auth/token.ts
Task 5.3: validated the login form input

---
# Loop Complete: 2026-01-09T10:41:12.000Z
- Total iterations: 2
- Tasks completed: 2
- Final status: all_complete
```

The `# Tag:` line appears only with `--tag`.

### Using Progress in Custom Prompts

The loop attaches the progress file to every prompt, so a custom prompt doesn't need to reference it. Tell agents to append notes:

```markdown theme={null}
## Process

...
7. Append a brief note to the progress file about what was done
```

This creates a chain of context that helps each iteration build on previous work.

## Real-World Examples

Here are practical scenarios for using the loop command in your development workflow.

### Weekend Automation

Run a loop overnight or over the weekend to clear your task backlog while you're away:

```bash theme={null}
taskgraph loop -n 50 --trust && notify-send "Loop finished"
```

This runs up to 50 iterations, completing tasks one by one. `--trust` skips the permission question so nothing waits for you, and `&&` sends a desktop notification only if the loop didn't end blocked or on an error.

### Test Coverage Sprint

Push your test coverage from 60% to 80% systematically:

```bash theme={null}
taskgraph loop -n 20 --prompt test-coverage
```

Each iteration identifies the most important untested user-facing behavior and writes a meaningful test. The agent prioritizes error handling, API endpoints, and CLI commands over internal utilities.

### Tech Debt Day

Dedicate a day to cleaning up lint errors across your codebase:

```bash theme={null}
taskgraph loop -n 30 --prompt linting
```

The agent systematically addresses type errors first (they break builds), then security-related lint errors, then others.

### Code Review Prep

Reduce code duplication before opening a PR:

```bash theme={null}
taskgraph loop -n 10 --prompt duplication
```

Each iteration finds and refactors one instance of duplicated code into a shared utility.

### Multi-Tag Workflow

Process different parts of your codebase in sequence:

```bash theme={null}
# First, handle critical backend tasks
taskgraph loop -n 10 --tag backend

# Then, address frontend tasks
taskgraph loop -n 10 --tag frontend
```

### Custom Migration Script

For complex migrations, create a custom prompt and run it:

```bash theme={null}
# Create custom-migration.md with your specific steps
taskgraph loop -n 20 --prompt ./custom-migration.md --progress-file ./migration-progress.txt
```

Use a separate progress file to track migration-specific notes.

***

> [!NOTE]
>
> **Related documentation:**
>
> * [CLI Root Commands](https://taskgraph-ai.com/capabilities/cli-root-commands.md) - Full command reference
> * [Task Structure](https://taskgraph-ai.com/capabilities/task-structure.md) - Understanding task organization

> [!TIP]
>
> The loop command is perfect for "overnight automation" - start a loop before leaving and return to a cleaned-up codebase.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.