Skip to main content

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:
Cap the run at 10 iterations:
Run 5 iterations with the test-coverage preset:
Run iterations with a custom prompt file:
Filter to specific task tag:
Work on one task (or subtask) instead of the one taskgraph next picks. It runs one iteration unless you pass -n:
--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:

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 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.

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 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:
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:

File References with @ Syntax

The @ prefix makes files available to the agent. Claude Code will read these files when processing the prompt:
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: When either marker is detected, the loop exits early. The reason text is captured in the final result. Example usage in a custom prompt:

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

Override with the --progress-file option:

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:
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:
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:
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:
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:
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:
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:

Custom Migration Script

For complex migrations, create a custom prompt and run it:
Use a separate progress file to track migration-specific notes.
Related documentation:
The loop command is perfect for “overnight automation” - start a loop before leaving and return to a cleaned-up codebase.