AIToday for AI

Guides · Beginner

Getting Started with Loops in Claude Code

About 30 min · No coding required

Related

Keep browsing related content.

Back to Guides

At the Claude Code team, Loops are defined as: An AI Agent repeatedly executing work cycles until a preset stop condition is met. To make it easier to understand, loops are categorized based on four dimensions:

  • How they are triggered
  • How they are stopped
  • Which Claude Code primitive (built-in command or core module) they use
  • What types of tasks are best suited for them

Next, we will introduce these main loop types, their ideal use cases, and how to control Token consumption while maintaining the quality of the generated code. Note that not all tasks require complex loops; it is recommended to start with the simplest approach and flexibly choose these patterns based on your actual needs.

Turn-based loops

                          ┌─────────────┐
                       ╭─▶│ Take action │──╮
                     ╭╯   └─────────────┘   ╰╮
                   ╭╯                         ╰╮
                 ╭╯                             ▼
┌─────────┐    ┌────────────────┐          ┌─────────────────┐      ┌──────────┐
│  Your   │ ──▶│ Gather context │          │ Verify the work │ ──▶  │ Response │
│ prompt  │    └────────────────┘          └─────────────────┘      └──────────┘
└─────────┘      ▲                                ╱
                   ╰╮                           ╭╯
                     ╰╮                       ╭╯
                       ╰─────────────────────╯

     Exits when Claude judges the task complete -- or the effort budget runs out.
  • Trigger: User inputs a Prompt.
  • Stop condition: Claude determines the task is complete or finds it needs more context from the user.
  • Best for: Short tasks that are not part of a routine or schedule.
  • Controlling usage: Write highly specific prompts and strengthen validation through the Skills feature to reduce back-and-forth interactions.

Every prompt you send to the AI actually initiates a loop manually guided by the user. In this loop, the user directs each turn: Claude gathers context, takes action, checks its work, repeats if necessary, and finally replies. This is called an agentic loop.

For example: Asking Claude to build a "Like" button. It reads the code, makes changes, runs tests, and hands back what it believes is a successful result. Then, the user manually reviews its work, finds it acceptable or in need of tweaks, and writes the next prompt.

In fact, you can document these manual checking steps into a SKILL.md file. This allows Claude to perform more checks end-to-end autonomously. In this file, you should provide tools or connectors that let Claude "see", measure, or genuinely interact with the final result. The more quantifiable and specific the validation criteria, the easier it is for Claude to judge itself.

For instance, you might define the following in SKILL.md:

--- 
name: verify-frontend-change 
description: End-to-end verification of any UI changes before declaring them complete. 
--- 

# Verifying frontend changes 
Never report UI changes as complete simply because the code modification succeeded. You must verify like a human code reviewer: 

1. Start the **dev server** and open the modified page in the browser. 
2. Directly interact with the changed content. For newly added controls (e.g., buttons, inputs, toggles): click them, confirm state changes as expected, and take screenshots before and after the operation. 
3. Check the **browser console**: ensure no new errors or warnings have been introduced. 
4. Use Chrome DevTools **MCP (Model Context Protocol)** to run performance traces and audit **Core Web Vitals**.

If any step fails, fix the issue and restart from step 1 — absolutely do not return half-verified work.

Goal-based loop (/goal)

 /goal get the homepage Lighthouse score to 90 or above, stop after 5 tries

                         tries to stop
                       ╭ ─ ─ ─ ─ ─ ─ ─ ─ ╮
                     ╭╯                   ▼

  ┌──────────────┐                         ┏━━━━━━━━━━━━━━━━━━━━━━━┓
  │ Claude works │                         ┃    Evaluator model    ┃      ┌───────────────────────┐
  │  on the task │                         ┃ checks your condition ┃ ───▶ │       Loop ends       │
  └──────────────┘                         ┗━━━━━━━━━━━━━━━━━━━━━━━┛      │ goal met, or the turn │
                                           ┃                              │    limit is reached   │
                     ▲                   ╭╯                               └───────────────────────┘
                       ╰ ─ ─ ─ ─ ─ ─ ─ ─╯
             condition not met -- sent back to work
  • Trigger: Real-time manual prompt input.
  • Stop condition: The goal is achieved, or the maximum number of attempts is reached.
  • Best for: Tasks with verifiable exit criteria (where success can be objectively judged by data).
  • Controlling usage: Set very specific completion criteria and a strict cap on iterations, e.g., "stop after 5 tries".

Sometimes, a single interaction turn isn't enough, especially when tackling complex tasks. AI agents often perform better when they can continuously trial-and-error and iterate. You can use the /goal command to define what "done" actually looks like, giving Claude a longer runway to iterate.

With clearly defined success criteria, Claude doesn't need to guess what is "good enough" and stop prematurely. Every time Claude tries to wrap up, the underlying evaluation model checks the set conditions. If it falls short, it's sent back to work until the goal is met or the attempt limit is exhausted.

This is why deterministic criteria (like the number of passing tests or a specific score threshold) are so effective.

For example:

# Get the homepage Lighthouse score to 90 or above, stop after 5 tries.
/goal get the homepage Lighthouse score to 90 or above, stop after 5 tries.

Time-based loop (/loop and /schedule)

  • Trigger: A preset time interval.
  • Stop condition: Manually cancelled, or the work is entirely depleted (e.g., code is merged, queue is empty).
  • Best for: Periodically repeating tasks, or tasks requiring integration with external environments/systems.
  • Controlling usage: Set longer time intervals, or switch to event-driven triggers (rather than blindly running on a timer).

Some AI agent work is cyclical: the task itself remains the same, only the input data changes. For instance, summarizing Slack chat logs every morning. Other tasks rely on external systems, and the simplest way to integrate is to check periodically and react to changes. For example, monitoring a PR (Pull Request) that might receive code review comments or fail CI (Continuous Integration).

For these scenarios, you can use the /loop command to trigger Claude to repeatedly execute a specific prompt at set intervals. For example:

# Check my PR every 5 minutes, address review comments, and fix failing CI
/loop 5m check my PR, address review comments, and fix failing CI 

Note that /loop runs locally on your computer, so it stops once you shut down or exit. If you want to move the loop to the cloud for 24/7 execution, you can use the /schedule command to create a cloud-based routine.

Proactive loops

                              ╭┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄╮
                              ┆ RUNS IN THE CLOUD -- LAPTOP OPEN OR NOT                  ┆
                              ┆                                                          ┆
                              ┆                       ┌────────────────────────┐         ┆
                              ┆                       │ TRIGGER                │         ┆
                              ┆                       │ /schedule              │         ┆
                              ┆                    ╭─▶│ watches Slack or       │──╮      ┆
                              ┆                  ╭╯   │ GitHub for bug reports │   ╰╮    ┆
                              ┆                ╭╯     └────────────────────────┘     ▼   ┆
                              ┆              ╭╯                                       ╰╮ ┆
┌────────────────┐            ┆   ┌────────────────────────┐             ┌────────────────────┐┆
│      You       │            ┆   │ REVIEW                 │ runs until  │ GOAL + CHECK       │┆
│  decide what   │ ◀───────────── │ Second agent           │ you turn    │ Main agent         │┆
│   to merge     │            ┆   │ reviews, then notifies │ it off      │ loops until the    │┆
│                │            ┆   │ you                    │             │ verification skill │┆
└────────────────┘            ┆   └────────────────────────┘             │ passes             │┆
                              ┆              ▲                                        │  ┆
                              ┆               ╰╮                                      │  ┆
                              ┆                 ╰╮                                   ╭╯  ┆
                              ┆                   ╰╮      ┌────────────┐           ╭╯    ┆
                              ┆                     ╰─────│ Opens a PR │◀─────────╯      ┆
                              ┆                           └────────────┘                 ┆
                              ╰┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄╯
  • Trigger: Event-driven or scheduled, requiring no real-time human involvement.
  • Stop condition: Each sub-task exits when its specific goal is achieved. The overall routine runs continuously until manually shut down.
  • Best for: Well-defined, continuous repetitive workflows: e.g., user bug reports, issue triage, data migration, dependency upgrades.
  • Controlling usage: Delegate routine, simple flows to smaller, faster models, reserving the most capable large models for steps requiring complex judgment.

The foundational primitives mentioned above, combined with other advanced Claude Code features (like auto mode and dynamic workflows), can be orchestrated into a "super loop" for long-running, complex tasks.

For example, to handle an influx of user feedback, you might combine them like this:

  1. Use /schedule (research preview) to run a routine checking for new feedback reports periodically.
  2. Use /goal to define the ultimate completion criteria and leverage skills to document how to verify the results.
  3. Utilize Dynamic workflows to orchestrate multiple AI agents, assigning them to categorize reports, fix issues, and review code concurrently.
  4. Enable Auto mode so the entire flow runs seamlessly and fully automated, without waiting for human confirmation.

Combined, the prompt might look like this:

# Run hourly: check the project-feedback channel for bug reports. Goal: don't stop until every report found this run is triaged, actioned, and responded to. When fixing a bug, use a workflow to explore three solutions in parallel worktrees and have a judge adversarially review them.
/schedule every hour: check the project-feedback channel for bug reports. /goal: don't stop until every report found this run is triaged, actioned, and responded to. When fixing a bug, use a workflow to explore three solutions in parallel worktrees and have a judge adversarially review them.

Maintaining code quality

The quality of output from a loop heavily depends on the peripheral systems built around it. When designing this system, follow these principles:

  • Keep the codebase pristine: Claude will inadvertently mimic existing patterns and conventions in your codebase. A solid foundation yields high-quality outputs.
  • Provide methods for self-validation: Use the Skills feature to codify your "excellent code standards" into rules, allowing the agent to self-verify against them.
  • Make documentation accessible: Official docs for frameworks and libraries contain the latest and greatest practices. Ensure your AI can easily access these materials.
  • Introduce cross-reviewing: Use a second agent with fresh context, uncontaminated by chat history, to conduct code reviews. It will carry less bias and won't be derailed by the primary agent's train of thought. You can use the built-in /code-review skill or dedicated GitHub review tools.

When a run fails to meet standards, don't just "fix the bug." Extract the lessons learned from the failure and solidify them into your rules, thereby improving the entire system across countless future iterations.

Managing token usage

To effectively manage Token consumption, loop designs must have clear boundaries:

  • Match the appropriate model: Simple tasks don't require multiple agents or complex loops; cheaper, faster models can solve them efficiently.
  • Set clear stop criteria: Be highly specific about what "done" looks like to help the agent converge faster.
  • Test small scale first: Dynamic workflows can spawn hundreds of agents. Before a large-scale rollout, carve out a small slice of work to test and gauge actual resource consumption.
  • Use scripts for deterministic logic: Running a script is much cheaper than having a large model step-by-step logically deduce the path. For example, a PDF-processing skill can embed a form-filling script; have Claude run the script instead of re-deriving the code every time.
  • Reasonable polling frequencies: The update frequency of the monitored target dictates the check interval. Don't let AI frequently poll low-frequency data sources.
  • Monitor usage regularly: Use the /usage command for a detailed breakdown of recent usage by skill, SubAgents, and MCPs; use /goal without arguments to check iteration counts and usage; use /workflows to monitor individual agent consumption and pause them at any time.

Summary

Summarizing the core differences of various loop types:

  • Turn-based: You hand off "The check", suitable for exploration or decision-making phases; tools are usually custom validation skills.
  • Goal-based: You hand off "The stop condition", suitable when you know exactly what "done" looks like; tool is /goal.
  • Time-based: You hand off "The trigger", suitable for work happening on a schedule outside your project; tools are /loop, /schedule.
  • Proactive: You hand off "The prompt", suitable for repetitive and highly-defined work; uses all above commands plus dynamic workflows.

When exploring loops, start by reviewing daily tasks to find efficiency bottlenecks. Think about what can be delegated to AI: Can you write automated validation checks? Is the goal clear enough? Does the work happen on a schedule?

Once you have an idea, fire up the loop and observe the results. Identify sticking points or excessive consumption, and don't be afraid to iterate and optimize the design.

References

Next step

See related AI updates

Keep exploring from this piece.

Browse the latest AI content