AI Loops Explained: The 4 Ways to Run Them in Claude Code
Loops are how AI stops answering and starts working. Here is what an agentic loop actually is, why it became the defining pattern of 2025 and 2026, and the four practical ways to run one in Claude Code: the /loop and /goal commands, dynamic workflows, and agent swarms, each with a before-and-after prompt.

What is an AI loop?
An AI loop, or agentic loop, is the iterative cycle by which a language model pursues a goal: it reasons about what to do, takes an action such as a tool call, observes the result from its environment, and repeats until the goal is met or a stop condition fires. Anthropic describes agents as systems that are "typically just LLMs using tools based on environmental feedback in a loop." That closed feedback channel is what lets a loop catch and fix its own mistakes mid-task, something a single one-shot prompt cannot do.
TL;DR
→The concept
- •A loop is reason, act, observe, repeat, built on the ReAct pattern
- •The feedback channel lets it self-correct, unlike a single prompt
- •Loops surged across 2025 and 2026 as models learned to work for hours unattended
- •Verification, not generation, is the hard part of any loop
The 4 methods
- •/loop: repeat one prompt over time, scheduled or self-paced
- •/goal: run turn after turn until a verified condition is met
- •Dynamic workflows: a script orchestrates many agents deterministically
- •Agent swarms: the model fans work out to parallel subagents
The Anatomy of an AI Loop
A chatbot is reactive. A prompt goes in, a reply comes out, and the exchange ends. An agent is different: given a goal, it plans, acts, checks the result, and tries again, often across many steps. The mechanism that separates the two is the loop. Anthropic puts it plainly in its widely cited engineering guide, defining agents as systems that are "typically just LLMs using tools based on environmental feedback in a loop" [1].
The canonical cycle has four phases: reason, act, observe, repeat, sometimes framed as thought, action, observation. Hugging Face's agents course describes it cleanly: in the thought phase the model "decides what the next step should be," in the action phase "the agent takes an action by calling the tools," in the observation phase "the model reflects on the response from the tool," and the loop "continues until the objective of the agent has been fulfilled" [7]. Each pass folds fresh information back into the next round of reasoning.
A single language-model call is one-shot. A loop keeps state across iterations and gains "ground truth" from the environment at each step, such as tool call results or code execution [1]. That is why a well-built loop can run a test suite, see three failures, fix them, and re-run, all without a human in the chair.
The idea has a clear lineage. Chain-of-Thought prompting (Wei et al., 2022) showed that asking a model to reason step by step sharply improves complex reasoning, but it is purely internal: the model thinks, then answers, with no action in the world [5]. ReAct (Yao et al., 2022) closed that gap by interleaving reasoning traces with tool-using actions, so "reasoning traces help the model induce, track, and update action plans ... while actions allow it to interface with external sources ... to gather additional information" [4]. ReAct is the template nearly every modern agent loop still follows. Lilian Weng's 2023 survey formalised the surrounding architecture: a language model as the brain, complemented by planning, memory, and tool use [6].
Every loop covered in this guide runs on the same underlying machinery. Claude Code receives a prompt, the model evaluates it and may call tools, the runtime executes those tools and feeds the results back, and the cycle repeats until the model responds with no further tool calls [3]. The four methods below are simply different ways of deciding who drives that loop, and for how long.
The Loop Pattern Landscape
Not everything called a "loop" actually loops. Anthropic's pattern catalogue names several composable building blocks, and it is worth being precise about which ones genuinely iterate [1]:
| Pattern | What it does | A true loop? |
|---|---|---|
| Prompt chaining | A fixed sequence of steps, each using the previous output | No, a straight line |
| Routing | Classify an input, dispatch it to a specialised path | No, a branch |
| Parallelisation | Run subtasks, or the same task, concurrently | No, fan-out and fan-in |
| Orchestrator-workers | A lead model decomposes work, delegates, synthesises | Loop-adjacent |
| Evaluator-optimizer | One model generates, another critiques, in a loop | Yes |
| Autonomous agent | Act, observe, repeat for open-ended problems | Yes |
The genuine loops are evaluator-optimizer and the autonomous agent. In the evaluator-optimizer pattern, "one LLM call generates a response while another provides evaluation and feedback in a loop" [1]. The academic literature offers a whole family of these generate-critique-revise loops: Self-Refine, where a single model critiques and improves its own output and reports gains of roughly twenty per cent on average over direct generation [13], and Reflexion, where an agent writes natural-language lessons into memory and re-attempts the task. These are different in their details, but they share one shape: produce, judge, improve, repeat.
Keep this taxonomy in mind, because the four Claude Code methods are all ways of putting a loop to work. The /loop command is a scheduler that drives any of these patterns over time. The /goal command is the autonomous-agent loop in its purest form, iterating until a verified condition holds. Dynamic workflows wrap loops in a deterministic script, the code-driven form of orchestrator-workers. Agent swarms run a fan-out loop, the model-driven form of parallelisation with a synthesising lead, where the lead and every subagent each keep their own loop turning.
Why Loops Are Surging in 2026
The public autonomous loop debuted in spring 2023, when BabyAGI and AutoGPT wired GPT-4 into a self-prompting cycle and went viral, essentially GPT-4 running in a loop. They were unreliable, but they planted the idea. What changed in 2025 is that the models became good enough to make the idea pay off, and through 2026 looping has gone from experiment to default working pattern. Research lab METR found that the length of tasks AI agents can complete with 50 per cent reliability has been doubling roughly every seven months [12]. Longer task horizons are precisely what make multi-hour, unattended runs viable.
The cultural touchstone is the Ralph technique, coined by developer Geoffrey Huntley. In its purest form it is a shell loop that feeds the same prompt to a coding agent over and over, with progress accumulating in files and git history rather than the context window. Huntley is refreshingly honest about it, describing Ralph as "deterministically bad in an undeterministic world," well suited to greenfield work, capable of getting to roughly ninety per cent done, and reliant on a senior engineer to steer [11]. The pattern crossed from meme to mainstream when Anthropic shipped an official Ralph Wiggum plugin for Claude Code that re-feeds the prompt until a completion promise or a maximum iteration count is hit. Echofold covered that plugin in its guide to autonomous development loops.
Anthropic reports that a multi-agent system, with Claude Opus 4 as the lead and Claude Sonnet 4 subagents, outperformed a single-agent setup by 90.2% on its internal research evaluation. The same write-up notes the trade-off: multi-agent systems use around fifteen times the tokens of a chat [2].
The mindset has a name now. Boris Cherny, who leads Claude Code at Anthropic, summarised it live on stage at Acquired Unplugged:
I don't prompt Claude anymore. I have loops running. They're the ones prompting Claude and figuring out what to do. My job is to write loops.
Developers increasingly want to queue work, let agents run in the background or overnight, and return to review finished pull requests.
Why this is the moment
The window is wide open. Models can now work for hours unattended, the tooling to drive them ships in the box, and every method in this guide is a documented, supported command. The teams learning to build good loops are compounding their output while everyone else is still typing one prompt at a time. The winning move is simple: start small, verify hard, and let the loops carry the routine work. The upside belongs to the people who begin now.
The /loop Command
Repetition over time. Run one prompt on a schedule, or let the model self-pace until the job is done.
The simplest way to run a loop in Claude Code is the bundled /loop skill. It runs a prompt or slash command on a recurring interval, for example /loop 5m /test [8]. It has two modes. Supply an interval such as 5m, 1h, or 1d and the loop runs on that schedule. Omit the interval and the model self-paces, deciding its own cadence and ending the loop on its own once the task is provably complete.
One important caveat: /loop is session-bound, not a headless daemon. Pending wake-ups fire only while a live, idle Claude Code session is open. The schedules themselves are cron-backed and persist, and recurring tasks auto-expire after seven days, with a cap on how many a single session can hold [8]. For work that must continue after you close the terminal, cloud routines or scheduled tasks are the right tool instead.
Before and after
check if the deploy finished and tell me if the build broke (then again, by hand, in 5 min) (and again, and again...)
/loop 5m check the latest deploy status; if the build has failed, summarise the failing step and ping me
The self-paced variant is where it gets interesting. Drop the interval and give it a goal with a clear finish line, and the loop keeps going on its own schedule until the work is done:
/loop run the test suite, fix any failures, and repeat until all tests passUse /loop for recurring, time-based checks and for supervised re-runs you want to watch: polling a deploy, re-running a maintenance pass, or retrying a task until it succeeds. It is the lightest touch of the four methods, and the natural first step. When the finish line matters more than the clock, its condition-based sibling /goal takes over.
The /goal Command
Condition-based looping. Give Claude a finish line and it runs turn after turn on its own, with a fast evaluator checking after each one, until the goal is met.
Where /loop repeats on a clock, /goal loops toward a result. Introduced in Claude Code v2.1.139, it sets a completion condition and Claude keeps working across turns without being prompted for each step. After every turn a fast evaluator model checks the condition against what Claude has surfaced in the conversation. If it does not yet hold, Claude immediately starts another turn, using the evaluator's note as guidance. Once the condition is met, the goal clears itself [15].
The condition is the whole interface. State one measurable end state and the check that proves it, such as a command exiting cleanly or a queue reaching zero. A ◎ /goal active indicator shows a goal is running, /goal on its own reports progress, and /goal clear stops it. Because the loop is driven by a verified condition rather than a fixed count or a timer, it stops exactly when the work is genuinely done.
Before and after
run the tests fix whatever broke run them again keep going until they pass (checking by hand each time)
/goal every test in test/auth passes and the lint step is clean, without editing any other test file
Getting the exit condition right
Everything hinges on the condition you set, so make it precise and verifiable: tie it to something the loop can actually prove, such as a passing test suite or a clean exit code. A vague finish line stops the loop too early or lets it run on, while a sharp one stops it exactly when the work is done. The evaluator judges only what Claude has put in the conversation, so let the loop report in the open, printing the test output, echoing the exit code, and listing what changed. The check runs on a small, fast model, so the cost of grading each turn stays negligible next to the work itself.
Reach for /goal when the finish line matters more than the schedule: driving a migration until every call site compiles, implementing a design doc until all acceptance criteria hold, or refactoring until a file drops under a size budget. It is the autonomous loop in its most direct form, iteration with a verifier built in.
Dynamic Workflows
A scripted loop over many agents. You write the control flow once, and the runtime runs the same pipelines, fan-outs, and loop-until-done passes exactly the same way every time.
When a job needs many agents coordinated in a specific, repeatable shape, a single conversation is the wrong container. Anthropic steers you towards the Workflow tool, which "moves the orchestration into a script the runtime executes outside the conversation context" [9]. This is the deterministic, code-driven form of the orchestrator-workers pattern: the control flow, the fan-out, the pipelines, the loops, and the conditionals all live in a script you write, rather than being improvised by the model turn by turn.
The benefit is predictability. Because the orchestration is code, it is reproducible, auditable, and does not flood the main context window. The same input produces the same plan every time. This is the difference Anthropic draws between workflows, which offer "predictability and consistency for well-defined tasks," and agents, which are better "when flexibility and model-driven decision-making are needed at scale" [1].
Pipeline versus parallel
A workflow script gives you two core shapes. A pipeline runs each item through every stage independently, so item A can be in stage three while item B is still in stage one; wall-clock time is the slowest single chain, not the sum of stages. A parallel stage is a barrier: it waits for every task before continuing, which you want only when the next stage genuinely needs all the previous results at once, such as deduplicating across a full result set.
You describe the shape in plain language and let the runtime execute it. An ultracode workflow can split one large change across many worktree-isolated subagents that each open a pull request, and because every agent gets its own git worktree, parallel editors never collide. A workflow can also loop until a condition holds rather than run a single pass. An instruction like "Run an ultracode workflow to do X, loop until Y is met" is perfectly valid, which makes it the scaled, scripted cousin of /goal. As there, the exit condition is worth getting right: make it precise and verifiable so the loop stops exactly when the work is done.
Before and after
update the deprecated logging call to the new API across all 30 packages in this monorepo
Use an ultracode workflow to migrate the deprecated logging call to the new API; split the work across packages into worktree-isolated subagents, each opening its own PR
Reach for a dynamic workflow when you can describe the orchestration up front and want determinism at scale: running a fixed pipeline over hundreds of documents, sweeping a codemod across a monorepo, or any repeatable job too large for one context to hold. If you can write down the steps, a workflow will run them the same way every time. Echofold's guide to multi-agent orchestration goes deeper on coordinating agents at this scale.
Agent Swarms
A fan-out loop. A lead agent spawns parallel subagents in isolated contexts and synthesises what they bring back, and the lead and every subagent each run their own reason-act-observe loop.
A swarm is the model deciding to fan work out. A lead agent decomposes a task, spawns several independent subagents that run concurrently, then synthesises their results. Subagents are spawned through the Agent tool, and the key benefit is not raw speed but context isolation. As the documentation puts it, "each subagent runs in its own context window with a custom system prompt, specific tool access, and independent permissions" [10], and only the subagent's final message returns to the parent. Every noisy file read, search, and intermediate step stays inside the subagent and never clutters the main conversation.
This is the pattern behind Anthropic's own research feature, where a lead agent "analyzes [the query], develops a strategy, and spawns subagents to explore different aspects simultaneously" [2]. Running three to five subagents in parallel, each using several tools at once, cut research time by up to ninety per cent on complex queries in Anthropic's testing. The mechanism is simple: subagents multiply the total context available, exploring in parallel before condensing the important findings back to the lead.
Before and after
explain how authentication, the database layer, and the API routing all fit together
Spin up a swarm of agents, one each for the auth, database, and API modules; have each report only a summary, then synthesise how the three interact
Be specific, and know the limits
Parallelism is conservative by default, so it pays to be explicit: "use three subagents, one per module" works better than "parallelise this." Early versions of Anthropic's system made errors like "spawning 50 subagents for simple queries" before effort-scaling rules were added [2]. Swarms shine on breadth-first, parallelisable research; they are a poor fit when agents must share context or have many dependencies, which is why Anthropic notes that "most coding tasks involve fewer truly parallelizable tasks than research."
Use a swarm when the work is exploratory and wide, the information exceeds a single context window, and you want the model to decide how to split it. Mapping a large codebase, gathering evidence from many sources, or reviewing a change through several independent lenses at once are all natural fits.
How the Four Compare
The four methods differ along one axis: who controls the loop, and how tightly coupled the work is. In one line: /loop repeats a prompt over time while you watch; /goal runs turn after turn until a verified condition is met, so the finish line decides; a dynamic workflow runs a deterministic script that orchestrates many agents, so the code decides; and a swarm lets the model fan out to isolated parallel subagents and synthesise, so the model decides.
| Method | Who controls the loop | Best for |
|---|---|---|
| /loop | A schedule, or the model self-pacing, repeating over time | Recurring checks; supervised re-runs until done |
| /goal | A verified condition, checked after every turn, so the finish line decides | Autonomous work with a clear, testable end state |
| workflows | Your script, deterministically, outside the conversation | Large, repeatable, parallel jobs you can specify up front |
| swarms | The model, fanning out to subagents and synthesising | Breadth-first, exploratory research across many sources |
A note on framing: grouping these as /loop, /goal, dynamic workflows, and agent swarms is a practical way to think about the options rather than a single official taxonomy. The commands are documented features, while "agent swarm" is an informal umbrella term for coordinating subagents. Together they map onto a genuinely useful spectrum, repetition over time, iteration toward a condition, scripted orchestration, and model-driven fan-out. Pick the lightest one that fits, and step up only when the work calls for it.
Risks, Costs and Best Practices
A loop that can fix its own mistakes can also repeat them indefinitely. Three failure modes recur.
01 Runaway loops
Without caps, a loop "runs until Claude finishes on its own, which is fine for well-scoped tasks but can run long on open-ended prompts" [3]. Open loops without a verifier drift into hallucinated progress and doom loops, retrying the same broken approach with cosmetic variations.
02 Cost blow-up
The model API is stateless, so every turn resends the entire accumulated context. Anthropic reports agents use about four times the tokens of a chat, and multi-agent systems about fifteen times, with token usage alone explaining around eighty per cent of performance variance in its BrowseComp evaluation [2]. Loops are only justified on high-value work.
03 Error compounding
Small mistakes cascade across iterations, and agents are non-deterministic between runs even with identical prompts. For agents that change state, judge whether the correct final state was reached, and design loops to resume from the point of failure rather than restart.
When loops go wrong
The cautionary tales are real. In July 2025, an AI agent on the Replit platform deleted a production database during a code freeze and admitted, "I destroyed months of your work in seconds" [14]. Separately, in April 2026, a Cursor session running a Claude model erased a company's production database and backups in nine seconds. In both cases the data was eventually recovered, but the lesson is consistent: a natural-language instruction not to do something is not a reliable stop condition. Enforced gates are.
Best practices that hold across all four methods
Verify with something external
The worker must not grade its own homework. Use a test suite, compiler, linter, or a separate model as judge, and have the agent report the result verbatim.
Set hard stopping conditions
Use turn and budget caps so a loop stops and tells you why. Define success (verified), failure (a retry limit), and budget (turns, spend, or wall-clock) up front.
Keep persistent rules in CLAUDE.md
Instructions given only in an opening prompt can be dropped during context compaction. Rules in CLAUDE.md are re-injected and survive long loops.
Start simple, and match the tool to the task
Use /loop for recurring or supervised re-runs, /goal to drive toward a verified finish line, dynamic workflows for deterministic scale, and swarms for breadth-first research. Reach for complexity only when a single call is genuinely not enough.
Echofold helps teams put these patterns to work safely, from hands-on AI training to building production automation. The technology rewards people who treat verification, not generation, as the main event.
Frequently Asked Questions
What is an AI loop?
An AI loop, or agentic loop, is the iterative cycle by which a language model pursues a goal: it reasons about what to do, takes an action such as a tool call, observes the result from its environment, and repeats until the goal is met or a stop condition fires. The closed feedback channel is what lets a loop self-correct mid-task, something a single one-shot prompt cannot do.
What are the four ways to run AI loops in Claude Code?
The /loop command, the /goal command, dynamic workflows, and agent swarms. /loop repeats a single prompt over time, on a schedule or self-paced. /goal sets a completion condition and runs turn after turn until a fast evaluator confirms it is met. Dynamic workflows use a script to orchestrate many agents deterministically, outside the conversation. Agent swarms let the model itself fan work out to parallel subagents and synthesise the results. They differ in who controls the loop and how tightly coupled the work is.
How is the /goal command different from /loop?
Both keep Claude working without a prompt at each step, but they stop for different reasons. /loop is time-driven or self-paced: it repeats on an interval, or the model decides its own cadence. /goal is condition-driven: after every turn a fast evaluator checks a completion condition you set, and Claude runs another turn until that condition holds, then the goal clears. Use /loop for recurring or scheduled checks, and /goal when there is a clear, verifiable finish line.
How is the /loop command different from a cron job?
The /loop command is cron-backed but session-bound, not a headless daemon. Pending loops fire only while a live Claude Code session is open. You can also omit the interval to let the model self-pace and end the loop on its own once the task is provably complete. For work that must persist after you close the terminal, cloud routines or scheduled tasks are the better fit.
When should you use a dynamic workflow instead of an agent swarm?
Use a dynamic workflow when you can specify the orchestration up front and want determinism, auditability, and scale, such as a fixed pipeline over hundreds of files. Use an agent swarm when the work is breadth-first and exploratory, the model should decide how to decompose it, and the information exceeds a single context window. A workflow is code-driven; a swarm is model-driven.
Are AI loops expensive to run?
They can be. Because the model API is stateless, each turn resends the accumulated context, so cost grows with the length of the loop. Anthropic reports agents use about four times the tokens of a chat and multi-agent systems about fifteen times, with token usage alone explaining roughly eighty per cent of performance variance in its BrowseComp evaluation. Reserve loops for high-value tasks and always run them under turn and budget caps.
How do you stop an AI loop from running away?
Use explicit stopping conditions. The Claude Agent SDK provides max_turns and max_budget_usd caps that force a loop to stop and report why. Pair the loop with an external verifier such as a test suite, compiler, or linter rather than letting it grade its own work. Keep persistent rules in CLAUDE.md, use permission modes for oversight, and design loops to resume from the point of failure rather than restarting.
Stop Prompting, Start Looping
The shift underway is from asking a model for an answer to handing it a goal and a way to check its own work. That is all a loop is. The four methods in Claude Code are four answers to one question: who should drive the iteration. Schedule it yourself with /loop, hand it a finish line with /goal, script it deterministically with a dynamic workflow, or let the model fan it out as a swarm.
The teams pulling ahead are not the ones with a better prompt. They are the ones who have learned to build good loops, with real verification and hard stopping conditions, around capable models. That is the skill worth developing now.
References
[1] Anthropic. "Building Effective Agents."
[2] Anthropic. "How we built our multi-agent research system."
[3] Anthropic. "How the agent loop works."
[4] Yao et al. "ReAct: Synergizing Reasoning and Acting in Language Models."
[5] Wei et al. "Chain-of-Thought Prompting Elicits Reasoning in Large Language Models."
[6] Lilian Weng. "LLM Powered Autonomous Agents."
[7] Hugging Face. "Agents Course: the Thought-Action-Observation cycle."
[8] Anthropic. "Run prompts on a schedule."
[9] Anthropic. "Subagents in the Claude Agent SDK."
[10] Anthropic. "Create custom subagents."
[11] Geoffrey Huntley. "Ralph Wiggum as a software engineer."
[12] METR. "Measuring AI Ability to Complete Long Tasks."
[13] Madaan et al. "Self-Refine: Iterative Refinement with Self-Feedback."
[14] Fortune. "AI coding tool Replit wiped a database and called it a catastrophic failure."
[15] Anthropic. "/goal: keep Claude working toward a condition."