Anatomy of an Agent Loop
This content was developed with AI assistance and is regularly reviewed for accuracy.
Snapshot: October 2026. Model names, prices, and product features change monthly; What's New in AI is the maintained chronology.
A loop that runs itself is more than "an agent in a while statement". The difference between a loop you can trust overnight and one that burns money on repeat is a handful of specific parts. In 2026 those parts have first-party names: Claude Code ships /loop, /goal, Routines, Stop hooks, and budget flags, and Anthropic's engineering team has published the vocabulary it uses for the scaffolding around a model, which it calls a harness. This guide covers the six parts every reliable loop needs, maps each to those primitives, and introduces the harness terms you will meet in documentation and blog posts.
Learning focus
By the end of this guide, you'll understand:
- The six components of a dependable agent loop and what each is responsible for
- Which Claude Code feature implements each component
- The harness vocabulary: planner, generator, evaluator, context reset versus compaction
- Which parts people skip, and what breaks when they do
The six parts
Picture a loop as a small assembly line the agent runs around. Each part has one job.
1. Trigger
What it is: the thing that starts an iteration. A trigger is a schedule ("every night at 2am"), an event ("a new issue was labelled agent-ready"), or a queue that is not empty. Without a trigger you are back to starting each run by hand, which is prompt engineering with extra steps.
In Claude Code: /loop re-runs a prompt inside a live session, either on a fixed interval or on one Claude chooses between one minute and one hour; it is session-scoped, allows up to 50 tasks per session, and expires after seven days so a forgotten loop is bounded. A Routine runs in the cloud with your laptop closed, fired by a schedule (minimum interval one hour), an API call, or a GitHub event, and uses your claude.ai connectors. Choose by where the state lives: /loop when the work is in the session in front of you, a Routine when it must survive you closing the lid.
2. Task selection
What it is: how the loop decides what to work on this iteration. Usually "take the next item off the queue", with filters ("skip anything that needs human sign-off") and priorities ("smallest task first"). Good task selection is what keeps a loop from grabbing work it has no business doing unattended.
In Claude Code: the built-in maintenance prompt that /loop uses by default continues unfinished work, tends the open pull request, and runs cleanup; you replace it with your own loop.md when the queue is yours. A Routine's prompt should name the label, folder, or query that defines its queue.
3. Action
What it is: the agent doing the work: the brief plus the tools and context it needs. This is where your prompt and context engineering live. From the loop's point of view it is a single "do the task" beat that produces a result, even if the agent reads files, runs commands, and calls connectors along the way.
In harness terms: this is the generator role. Subagents are useful here to isolate verbose output (test logs, search results) so it never lands in the main context.
4. Evaluation (the check)
What it is: deciding whether the result is good enough. Evaluation can be automated and objective (tests pass, the schema validates, the number is in range), rubric-based (a second agent scores the output against explicit criteria), or human (a person approves before anything ships). If a loop cannot tell good output from bad, it cannot make good decisions. No evaluation means no trustworthy loop.
In Claude Code: /goal sets a completion condition, and after each turn a separate, smaller model checks whether it holds, reporting not yet met, met, or impossible. Under the hood it is a wrapper around a session-scoped, prompt-based Stop hook, which you can also write yourself. The docs put the division of labour neatly: auto mode removes per-tool prompts, and /goal removes per-turn prompts. In harness terms this is the evaluator, and the rule is that the generator never grades its own work. Evals for Agents shows how to build the checks that evaluator runs.
5. Stop condition
What it is: the rule that ends the loop. Every loop needs several: success (goal met, queue empty), budget (a cap on iterations, time, or money), failure (the same error twice), and escalation (hand control to a human instead of continuing).
In Claude Code: /goal stops on its own after several turns without progress, /loop tasks expire after seven days, and a headless run started with claude -p can carry --max-budget-usd so the runtime, not your billing dashboard, enforces the ceiling. Dynamic workflows cap a run at 1,000 agents and flag any run projected to use more than 25 agents or 1.5 million tokens. A budget stop condition is the single most expensive thing to forget. Write it before anything else.
6. Memory (state)
What it is: what the loop writes down between iterations, so it knows what it already tried, what is done, and what failed, and does not repeat itself or lose progress on restart. At minimum, log each iteration's task, result, and decision. This record is your debugging trail and your audit trail.
In harness terms: memory is where context reset versus compaction matters. Compaction summarises the current context in place and keeps going; a context reset starts a fresh agent and hands it a structured handoff artifact, a file that says what is done, what is next, and what was learned. Long-running harnesses lean on resets because a model near the end of its window shows what Anthropic's engineers call context anxiety: it wraps up early and declares victory.
The harness vocabulary
Anthropic's March 2026 post on harness design for long-running application development defines a harness as "the scaffolding of prompts, agents, tools, and orchestration around a model", and splits it into three roles: a planner that decides the work, a generator that does it, and an evaluator that grades it. The planner writes sprint contracts (small, checkable units of work); the generator works inside them; the evaluator decides whether the contract is met. The post's own measurement makes the case: a solo run of about 20 minutes and about $9 produced an application whose gameplay did not work, while the full harness took about 6 hours and about $200 and produced a playable game.
The post's last lesson matters most for anyone maintaining a loop. Every harness component "encodes an assumption about what the model cannot do", so a check that was load-bearing for one model may be dead weight, or harmful, for the next. Re-examine the harness with each new model. When a new model ships, re-run your loop with fewer guardrails in a sandbox and see which ones still earn their place.
One more distinction you will meet in the evals literature: the agent harness is the scaffold the agent runs in; the evaluation harness is the separate rig that scores trials of it. Keep them separate so the agent cannot influence its own grade.
A worked example
Here is the anatomy applied to a "fix flaky tests" loop in Claude Code:
| Part | In this loop |
|---|---|
| Trigger | A Routine at 01:00 on weekdays, with the GitHub connector and nothing else |
| Task selection | Picks the test file with the most CI failures this week; skips any file touched by an open pull request |
| Action | Claude Code reads the file, diagnoses the flake, and patches it on a branch named agent/flaky-[file] |
| Evaluation | CI re-runs the test 20 times; /goal "the test passes 20 consecutive CI runs" checks the condition after each turn |
| Stop condition | Stops after 3 files, or at --max-budget-usd 4, or when /goal reports no progress, or on any failed check |
| Memory | Appends each attempt (file, diagnosis, pass or fail) to loop-log.md, opens one pull request, and leaves a handoff note for the next run |
Notice that five of the six parts exist to keep the agent honest and bounded. The "smart" part, the agent action, is one beat.
What people skip (and what breaks)
- Skip the stop condition and the loop runs until you notice the bill.
- Skip evaluation and the loop "succeeds" on broken output and repeats the mistake at scale.
- Skip memory and the loop redoes finished work or circles the same failure forever.
- Skip task selection filtering and the loop grabs a high-stakes task it should not touch unattended.
- Skip re-examining the harness and you keep paying for guardrails a newer model no longer needs, or miss the ones it now does.
Key takeaways
- A reliable loop has six parts: trigger, task selection, action, evaluation, stop condition, and memory.
- In Claude Code they map to Routines or
/loop, yourloop.md, the agent,/goalor a Stop hook,--max-budget-usdand expiry, and handoff files. - The harness roles are planner, generator, and evaluator; the generator never grades itself.
- Prefer a context reset with a handoff artifact over compaction for long runs.
- Re-examine the harness with each new model; every component encodes an assumption that may have expired.
Next steps
Continue to: Loop Guardrails and Safety before you let any loop run unattended.
- Build the checks the evaluator runs in Evals for Agents.
- See
/loop,/goal, Routines, and hooks in context in Claude Code: Your AI Coding Agent.