Blog

Claude Code overnight: loop engineering and Ralph Loop in 2026

Markdown

How to run Claude Code in an autonomous loop: Ralph Loop, /loop, /goal, /batch. Ready-to-use scenarios and protection against burning through tokens in 2026.

Read full article

Key takeaways

Loop engineering is an approach where you don't prompt Claude Code by hand every time, but build a loop. The loop receives your task, takes a step, checks the result, and decides for itself whether to continue or stop. This guide shows you how to set up your first Ralph Loop in one evening so it works for you every day.

Ailoot reference documentation: ailoot.ai/docs/.

What is loop engineering for an AI agent, and why use it?

Key takeaways

Loop engineering is a change in your role. Before, you sat and prompted the agent: “do X, fix Y, check Z.” Now you write a small system that does this for you in a loop: submits a task—gets a result—checks it—decides what to do next. You stop typing, and the agent keeps producing.

Behind this is a new engineering role: you're the architect of loops, not a keyboard operator.

Do it once today, and every day the leads grow, articles are published automatically, the bot handles correspondence, and the metrics report lands on your desk by 9 a.m. You build it, and it works every day without you.

If you still open Claude Code, write a prompt, wait, read, and write another prompt, you're missing the biggest shift of 2026. Models have become powerful enough to work in loops without supervision.

How Ralph Loop differs from a regular Claude Code request

Key takeaways

A regular Claude Code request is one-off: you write “do X,” Claude does it, and the chat ends. Ralph Loop does the same thing, but in a loop: every time Claude tries to exit, a hook catches the exit and feeds your prompt back in. The files Claude has already created remain, so each new iteration builds on the previous one. The loop stops when it receives a completion signal (Claude outputs the word “DONE”) or reaches the iteration limit.

At its core, the technique is a simple bash loop around an agent:

The minimal version:

while :; do cat PROMPT.md | claude-code ; done

One prompt in a file, an infinite loop around it.

Anthropic packaged the same logic in the ralph-loop plugin and in the /loop, /goal, and /batch commands in Claude Code—they're available right in the terminal without scripts.

Three built-in Claude Code commands: /loop, /goal, /batch

Key takeaways

Claude Code v2.1+ has three commands for different levels of autonomy. /loop repeats a task at an interval (hourly, daily, monitoring). /goal works turn by turn until an evaluator model says “done.” /batch performs a large mechanical change across parallel worktree agents. Each has its own niche.

CommandWhen to use itVersionLimit
/loop 30m <prompt>Repeat at an interval (monitoring, polling)v2.1.72+7 days, 50 tasks/session
/goal <condition>Work until a goal is reached (verifier pattern)v2.1.139+Condition up to 4000 characters
/batch <change>Parallel mechanical refactoringv2.1.63+Each unit gets its own git worktree

/goal is the command most similar to Ralph Loop. Under the hood, an evaluator model (Haiku by default) checks on each turn whether the goal has been reached. If not, the next iteration comes with a hint about what exactly to fix. If yes, it stops. I covered /goal in detail in the guide on running Claude Code autonomously overnight with /goal—it includes ready-to-use scenarios for 14 hours of work.

/batch is a rare but powerful command. When you need to make the same change across 100+ files (API migration, component replacement, renaming), /batch sends each file to a separate subagent in its own git worktree. The changes don't conflict—each agent works in an isolated copy. For more about subagents, see the guide on nested subagents.

Hard limits for /loop and /goal:

  • A task runs as long as Claude Code is open. Close the terminal and the loop dies. For a serious overnight cycle, use a remote server or your own shell wrapper.
  • The maximum lifetime of a recurring task is 7 days (after that, it is automatically deleted as protection against forgotten loops).
  • Up to 50 concurrent tasks in one session.

How to launch your first autonomous loop in 5 minutes

Key takeaways

The quickest way to start is with the built-in /goal. Open Claude Code, enter a command with a goal and a verifiable stop condition, and go about your business. Claude generates code, runs tests, reads errors, fixes them, and runs the tests again until they pass.

5 steps:

  1. Open the project in Claude Code

    Go to the project root in the terminal and run claude. Wait for Claude to read CLAUDE.md and index the repository.

  2. Define a goal and a stop condition

    The goal is what needs to be done. The stop condition is how Claude will know it's finished. Ideally, it's a command that returns 0 or 1. Example: “Goal: all 23 tests in tests/api/*.test.ts pass. Stop when pnpm test returns exit 0.”

  3. Run /goal

    Command:

    /goal All tests in tests/api/*.test.ts must pass. Run pnpm test, read the errors, fix them, and run it again. Stop when the exit code = 0. Maximum 20 iterations.
    

    Claude starts the loop: runs tests—sees a failure—opens the file—fixes it—runs them again.

  4. Set a budget cap

    In a background tab, use /usage to monitor usage. Set a token or money limit for the day so you don't burn your entire balance on one loop. More details in the guide on how not to burn through Claude Code limits.

  5. Go about your business

    Come back in 30 minutes. If the task is simple, it will already say “DONE, all tests pass.” If it's more complex, read the report: “stopped on iteration 20, reason X.” Fix by hand what the loop couldn't, then restart it.

Verifier pattern: how Claude checks its own work in a loop

Key takeaways

Claude should always have a way to check its work. Without a check, an agent in a loop starts hallucinating—it decides the task is done when everything is actually broken. A verifier is a command (tests, lint, evaluator model, custom check) that returns an unambiguous “done/not done.”

There are three types of verifiers:

1. Technical (exit code)—the most reliable. pnpm test, npm run lint, tsc --noEmit, playwright test. They return 0 or 1, with no interpretation required. /goal works this way too—it uses the Haiku evaluator model under the hood, which checks on each turn whether the condition has been met (up to 4000 characters).

2. Evaluator model—a second model looks at the first model's result and grades it against a rubric. Good for tasks without a formal check (“Is the writing style good?” “Does the design match the brand?”). At Anthropic, this is called Claude Code Review—a mode where a separate reviewer agent looks for logic errors, edge cases, and security issues in the main agent's work. According to Anthropic's internal data, it finds 84% of issues on large PRs (up from 16% with the baseline approach).

3. Custom check—a shell script you write yourself. “If the logs contain no word ERROR, it's done.” “If the file output.json exists and is parseable, it's done.” “If the /pricing page returns 200, it's done.”

In the author's approach, the skills include a separate adversarial pass for Claude after each phase. Here's a prompt template I put in CLAUDE.md or in a command:

Find 10 reasons why this project might have gone to shit. 
Put yourself in the position that something has gone wrong. 
I can run through this story many times - 
before I release it to the public.

The most common beginner mistake is starting a loop without a verifier. The agent spins its wheels: writes code, doesn't check it, thinks it's done, moves to the next iteration, and rewrites what it already did. Three hours later, it's a mess and the bill is $200.

The best rule I've learned: write the verifier first, then start the loop. If you can't state the stop condition in one line, the task isn't ready for autonomy.

How not to burn through thousands of dollars overnight: budget caps and stop conditions

Key takeaways

A loop without a budget cap, a cost stop condition, or a verifier can run up a large bill before anyone notices. Three safeguards can prevent this: an iteration limit, a token or money limit, and a stagnation detector.

Three essential brakes for any overnight loop:

1. Iteration limit. --max-iterations 20. The loop can't run more than N times—even if the verifier doesn't trigger. If it hasn't reached the stop condition after 20 iterations, the task is stuck and needs human intervention.

2. Token or money limit. /usage limit 50—no more than $50 a day. As it approaches the limit, the loop stops by itself and sends an alert. This protects against a runaway scenario.

3. Progress check with an explicit contract. The HEAD comparison below detects new commits, not all code changes. Use it only in an isolated worktree where every code-changing iteration records a local checkpoint commit before the comparison. Useful uncommitted edits do not change HEAD; without that contract, an unchanged hash can be a false stagnation signal. Also retain the verifier result: a new commit proves a recorded change, not that the task improved or passed.

Illustrative wrapper structure with these three checks. The cost-reporting and agent-invocation lines are runner-specific examples, not a verified CLI installation recipe; confirm those interfaces for the installed version before adapting it. For the commit-based progress check, require a local checkpoint commit for each code-changing iteration. If the runner leaves edits uncommitted, stop for review rather than labeling them “no progress.”

#!/bin/bash
PROMPT="$1"
MAX_ITER=20
MAX_COST_USD=50
COMPLETION="DONE"
PREV_HASH=""
STAGNATION=0

for i in $(seq 1 $MAX_ITER); do
  # Money limit
  CURRENT_COST=$(claude usage --json | jq '.cost_usd')
  if (( $(echo "$CURRENT_COST > $MAX_COST_USD" | bc -l) )); then
    echo "STOP: budget cap $MAX_COST_USD reached"
    break
  fi

  # Run
  OUTPUT=$(claude code -p "$PROMPT" --auto-accept)

  # Completion check
  if echo "$OUTPUT" | grep -q "$COMPLETION"; then
    echo "STOP: completion signal"
    break
  fi

  # Commit progress only: each code-changing iteration must checkpoint a commit.
  # HEAD cannot detect useful edits that remain uncommitted.
  CURRENT_HASH=$(git rev-parse HEAD 2>/dev/null)
  if [ "$CURRENT_HASH" = "$PREV_HASH" ]; then
    STAGNATION=$((STAGNATION + 1))
    if [ "$STAGNATION" -ge 3 ]; then
      echo "STOP: stagnation 3 iterations"
      break
    fi
  else
    STAGNATION=0
  fi
  PREV_HASH="$CURRENT_HASH"
done

Validate the progress check before extending this skeleton: an edit without a commit must be treated as unrecorded work; a checkpoint commit changes HEAD; only the separate verifier can establish success. Three unchanged commits indicate no recorded changes under the stated contract, not proof that all working files stayed unchanged. Next, you can add: a Slack alert when it stops, an automatic Telegram report in the morning, a push notification when the budget reaches 80%. The principle is the same: a loop needs brakes, not just an accelerator.

5 ready-to-use overnight loop scenarios

Key takeaways

Not every task is suited to an autonomous loop. Good candidates are tasks with an unambiguous verifier that work iteratively: tests, refactoring, monitoring, article pipelines, data imports. Poor candidates are tasks without formal checks or with multiple subjective criteria.

Scenario 1: Turn failing tests green

/goal There are 47 failing tests in the tests/ directory. Goal: make them all pass.
Run pnpm test, read stderr, open the file with the error, fix it, and run pnpm test again.
Stop when exit 0. Max 30 iterations.

Scenario 2: Large refactor across 200 files

/batch Replace the old apiV1 API client with the new apiV2 in all files under src/**/*.ts.
Each file gets its own worktree. After the replacement, run tsc --noEmit; fix any errors.
Merge the worktrees at the end.

Scenario 3: Overnight production monitoring

/loop 30m Every 30 minutes, check https://your-app.example.com/api/health.
If it doesn't return 200, read the logs, find the cause, fix it, and redeploy.
Log each iteration to /tmp/night-monitor.log.

Scenario 4: Import a large dataset with deduplication

/goal Import the CSV file /tmp/import.csv (12,000 rows) into the clients table.
For each row, check for a duplicate by email; if none, insert it; if one exists, update it.
Log conflicts to /tmp/conflicts.log. Stop when the last row has been processed.

Scenario 5: Article pipeline (typical setup)

For an online service or agency that regularly needs SEO articles, the scenario looks like this:

/loop 8h Every 8 hours: open the backlog file for topics with status 'queued'.
If a topic is available, run the skill for writing a guide.
Publish to dev. Change the status to 'review'. Notify the person responsible in Telegram.

What to supply in each iteration: CLAUDE.md and a knowledge folder as state

Key takeaways

Without memory, Claude starts each iteration from scratch—reopens the project, reads files, and forgets the previous iteration's decisions. Without CLAUDE.md, it doesn't know the architecture; without business/ (the knowledge folder), it doesn't know the product context; without skills, it doesn't remember your rules and style. State between iterations is kept in these three file layers. Without them, the loop degrades by iteration 5.

Three layers of project “memory” turn a one-off prompt into a controlled loop:

1. CLAUDE.md—the project's constitution. What the product is, what the stack is, what the rules are, and what must never be done. Claude reads this file when starting each session and each loop iteration. Without it, Claude has to “reopen” the project every time—using up context and increasing the risk of hallucinations. Find a ready-made template and 6 rules in the CLAUDE.md guide.

2. Knowledge folder—a folder of business knowledge: product, audience, goals, economics, marketing. Not code—meaning. When the loop writes an article or looks for an answer for support, it reads this folder and responds with the project context, not from a vacuum.

3. Context engineering—what exactly you give Claude in each iteration. Not the entire knowledge folder, not the whole repository—only what's relevant. Plan Mode helps: Claude determines which files the task needs and reads only those. More details in the Plan Mode guide.

The main operational principle: one task, one chat. When your AI starts eating an unthinkable number of tokens, it means you're trying to do everything in one chat.

Without all three layers, the loop becomes an infinite cycle with a growing bill.

For an entrepreneur without programmers, parallel loops mean something concrete. You have one Claude account for $200/month and an ordinary laptop. You can launch 5 loops in parallel—support, articles, metrics, testing a new product, and competitor monitoring. Each runs in its own Claude Code tab. In the morning, you read the summary. This is already the norm for working in summer 2026.

Four common autonomous loop failures

Key takeaways

Most autonomous loop failures fit four patterns: no verifier—the agent decides for itself that it's done; no budget cap—the loop burns through the budget overnight; no state between iterations—decisions contradict each other; vague stop condition—the loop doesn't know when to stop.

Failure 1: “Hallucination loop”

The agent decides it's finished even though the verifier hasn't triggered. Or there's no verifier at all. Three hours later Claude says, “All done!”—but the tests are failing, the page won't open, and nothing works. You've already spent $80 on pointless iterations.

Fix: a strict verifier (the command's exit code), not a verbal check.

Failure 2: “Burned the budget overnight”

Without a budget cap, a loop becomes a grenade without a pin.

Fix: /usage limit or an external script using claude usage --json to stop the loop when it reaches a threshold.

Failure 3: “The loop lost context between iterations”

In iteration 1, Claude made an architectural decision. By iteration 7, it had forgotten and made the opposite decision. After 15 iterations, the code is a dump.

Fix: a state layer via CLAUDE.md and the knowledge folder. The loop writes every architectural decision to a file it reads in the next iteration.

Failure 4: “The stop condition is imprecise—the loop runs forever”

/goal "Make the page beautiful"—what does “beautiful” mean? With no unambiguous metric, the loop will never stop. It will keep running until it hits the iteration or budget limit.

Fix: the stop condition must always be measurable. Not “beautiful,” but “Lighthouse Performance ≥ 90, Accessibility ≥ 95.” Not “works,” but “tests in tests/pricing.test.ts pass.”

When loop engineering isn't needed

Key takeaways

Loop engineering is a tool for repetitive, verifiable tasks. It's unnecessary for one-off creative tasks, tasks without a formal verifier, and tasks requiring subjective evaluation. Knowing the limits matters more than knowing the technique.

Not suited to an autonomous loop:

  • One-off creative task. One website for a new product, one logo, one strategic memo. A loop is overkill here; it's easier to write one prompt and refine the result by hand.
  • Task without a verifier. If you can't express the stop condition as an exit code or unambiguous signal, don't start the loop; otherwise, it'll be an endless bonfire.
  • Task requiring subjective evaluation. “Make it sound better,” “improve the UX so it's more pleasant”—these need you, not a loop.
  • A new, unfamiliar domain. If you yourself don't understand what “done” should look like, don't run Claude in a loop. First understand it, then automate it.

And the main rule: if you don't manage the context and don't build clear skills that deliver the final result, then whether you run the routine or not, it'll all be nonsense.

The main question before starting a loop: Can I describe in one line how I'll know Claude is done? If yes, the loop can help. If not, first define a verifiable condition, then start.

Sources

Loop engineering is a layer on top of everything you already know about Claude Code. Continue exploring Ailoot at ailoot.ai.

More details

Questions about Claude Code overnight: loop engineering and Ralph Loop in 2026

Why can unchanged HEAD falsely suggest that a loop made no progress?

HEAD identifies a commit. Useful edits in the working tree do not change it until committed. The sample detector therefore requires a local checkpoint commit after each code-changing iteration; without that contract, pause and inspect uncommitted work instead of calling it stagnation.

Does a new commit prove the loop improved the result?

No. It proves only that a change was recorded. Keep the verifier result alongside the checkpoint, and stop on the actual acceptance condition. The wrapper’s runner-specific invocation and cost interfaces must be validated before it is used.

All articles