6  Loop Engineering: Getting Started with Loops

6.1 From Turns to Loops

For most of the history of interacting with AI, the unit of work was a turn: you send a prompt, the model responds, and the interaction is complete. Even as agents grew more capable — reading files, running commands, editing code — the fundamental shape remained a turn: prompt, work, done.

On June 30, 2026, Anthropic formalized a shift beyond the turn with the concept of loops: agents that repeat cycles of work until a stop condition is met, sometimes without any human in the loop at all. The post, titled “Loop Engineering,” defined four types of loops, explained when to use each, and offered best practices for making them reliable.

The significance of loops is that they change the persistence and autonomy of agent work. A turn-based agent is a tool you pick up and put down. A loop-based agent is a process that runs — potentially for hours, potentially on a schedule, potentially making decisions on its own. This is the substrate on which proactive, always-on agentic systems are built.

6.2 What Is a Loop?

A loop is an agent (or set of agents) that repeats a cycle of work until a stop condition is satisfied. The cycle typically involves: observing state, deciding on an action, executing the action, and checking whether the stop condition is met. If not, the cycle repeats.

The stop condition is what distinguishes a loop from a turn. A turn ends when the agent finishes its response. A loop ends when an explicit criterion is satisfied — a goal is achieved, a time is reached, or an event triggers a halt.

Note

The stop condition is the most important design decision in a loop. A loop without a clear, checkable stop condition will either run forever (consuming tokens) or stop arbitrarily (producing incomplete work). Always define how the loop knows it’s done before you start it.

6.3 The Four Types of Loops

The post defined four types of loops, distinguished by what triggers each cycle and whether a human is involved.

6.3.1 Type 1: Turn-Based Loops

A turn-based loop is the familiar pattern: a user sends a prompt, the agent works until the task is done, and the cycle ends. It’s called a “loop” rather than a “turn” because the agent may internally repeat cycles (read, edit, test, check) before responding — but from the user’s perspective, it’s a single interaction.

  • Trigger: User prompt
  • Human involvement: Yes (the user initiates)
  • Stops when: The task is complete
  • Example: “Fix the failing tests in the auth module.”

Turn-based loops are the default mode of Claude Code. Most day-to-day work is turn-based.

6.3.2 Type 2: Goal-Based Loops

A goal-based loop uses the /goal command (or equivalent) to set an explicit exit criterion. The agent works in cycles until the criterion is met, checking itself after each cycle. The human sets the goal but does not intervene in each cycle.

# Start a goal-based loop
/goal "All tests pass, lint is clean, and the build succeeds"
  • Trigger: A goal with exit criteria
  • Human involvement: Minimal (sets the goal, reviews the result)
  • Stops when: Exit criteria are met
  • Example: “Refactor the payment module until all tests pass and code coverage is above 90%.”

Goal-based loops are powerful for tasks where the definition of “done” is clear and checkable but the path to get there is uncertain.

6.3.3 Type 3: Time-Based Loops

A time-based loop runs on a schedule. The /loop and /schedule commands let you specify that an agent should run at intervals — every hour, every night, every Monday at 9 AM.

# Run a workflow every night at 2 AM
/schedule "0 2 * * *" "Run the security scan workflow and report findings"
  • Trigger: A schedule (cron expression)
  • Human involvement: None during execution (reviews results asynchronously)
  • Stops when: The schedule is cancelled or the task completes
  • Example: “Every night, scan for new vulnerabilities and open issues for any found.”

Time-based loops turn agents into background services — always running, always checking, reporting when there’s something to report.

6.3.4 Type 4: Proactive Loops

A proactive loop is triggered by events or schedules but, critically, requires no human initiation. The agent monitors for a condition and acts when it occurs. This is the most autonomous loop type.

  • Trigger: An event (e.g., a new PR is opened, a build fails, a metric crosses a threshold) or a schedule
  • Human involvement: None (the agent acts on its own, within pre-defined boundaries)
  • Stops when: The event-driven task is complete or the monitoring is stopped
  • Example: “When a new dependency is added, check it for known vulnerabilities and comment on the PR.”

Proactive loops are the foundation of agentic CI/CD, automated incident response, and always-on monitoring. They require careful design of permissions and boundaries because the agent acts without human initiation.

6.4 Comparison of the Four Loop Types

Type Trigger Human in Loop? Stop Condition Typical Duration
Turn-based User prompt Yes Task complete Minutes
Goal-based /goal + exit criteria Minimal (sets goal) Criteria met Minutes to hours
Time-based Schedule (/loop, /schedule) No (async review) Schedule cancelled Recurring
Proactive Event or schedule No (autonomous) Event resolved Continuous
Tip

The progression from turn-based to proactive represents increasing autonomy and decreasing human involvement. Each step requires more robust verification, boundaries, and observability to ensure the agent behaves correctly without supervision.

6.5 Best Practices for Loop Engineering

The post offered a set of best practices that apply across loop types but become increasingly important as loops grow more autonomous.

6.5.1 Keep Your Codebase Clean

Loops amplify the state of your codebase. If your codebase is messy — inconsistent conventions, dead code, unclear architecture — a loop-based agent will propagate and compound that messiness across cycles. A clean codebase gives the agent a clear signal to follow.

This means: consistent naming, clear file structure, up-to-date documentation, and removing technical debt before deploying loops that will work across the codebase.

6.5.2 Use Verification Skills

Every loop should include verification — a way to check that each cycle’s work is correct before proceeding to the next. Verification can take the form of:

  • Test suites that the agent runs after each change.
  • Linters and type checkers that catch regressions.
  • Adversarial agents that review the work (Chapter 2, Chapter 3).
  • Rubrics that grade output quality (Chapter 13).

Without verification, a loop can drift — each cycle introducing subtle errors that accumulate until the output is far from the goal.

6.5.3 Use a Second Agent for Reviews

For loops that produce important work, use a second agent (a subagent with a fresh context) to review each cycle’s output. This is the adversarial verification pattern from dynamic workflows (Chapter 3), applied within a loop. The reviewing agent catches errors the working agent misses precisely because it brings a fresh perspective.

6.5.4 Manage Token Usage

Loops, especially time-based and proactive ones, can consume significant tokens over time. Best practices include:

  • Setting token budgets per cycle and per day.
  • Using cost-appropriate models — Sonnet for routine cycles, Opus for complex ones.
  • Compacting or clearing context between cycles when the previous cycle’s context isn’t needed.
  • Monitoring spend and setting alerts.
Note

Unmonitored proactive loops are the most common source of unexpected token bills. Always set budgets and spending limits for loops that run without human initiation.

6.6 Designing Effective Stop Conditions

The stop condition is the linchpin of a well-designed loop. The post emphasized several principles:

  1. Make it checkable. The agent must be able to evaluate the condition programmatically — “all tests pass” is checkable; “the code is good” is not.
  2. Make it unambiguous. The condition should have a clear true/false answer, not a judgment call.
  3. Include a fallback. Add a maximum cycle count or time limit so a loop that can’t satisfy the condition doesn’t run forever.
  4. Define failure behavior. What should the loop do if it can’t meet the condition after N cycles? Report failure? Roll back? Escalate to a human?
# Example goal-based loop configuration
goal:
  criteria: "all_tests_pass and lint_clean and coverage >= 90"
  max_cycles: 20
  on_failure: "report_and_escalate"
  token_budget: 500000

6.7 Composing Loops with Other Features

Loops compose powerfully with other Claude Code features:

  • Dynamic workflows (Chapter 2, Chapter 3) can be the body of a loop — a workflow runs each cycle.
  • Subagents (Chapter 10) can be spawned within loops for parallel work or fresh-perspective review.
  • Skills (Chapter 9) can be loaded within a loop to provide domain-specific procedures.
  • Hooks (Chapter 9) can enforce deterministic policies within loops (e.g., “no commits without passing tests”).

6.8 The Evolution from Turns to Loops

Understanding loops requires understanding the evolution of agent interaction patterns. Each stage of this evolution expanded what was practical.

6.8.1 Stage 1: Single-Turn Interactions

The earliest AI interactions were single-turn: a prompt, a response, done. No state, no continuity, no iteration. This is the model of a search query or a simple chatbot.

6.8.2 Stage 2: Multi-Turn Conversations

Multi-turn conversations added continuity within a session — the model could reference earlier parts of the conversation. This enabled iterative refinement (“make it better,” “try a different approach”) but still required human initiation for every cycle.

6.8.3 Stage 3: Agentic Turns (Tool Use)

Agentic turns added tool use — the model could read files, run commands, and edit code within a single turn. The “turn” became a mini-session where the agent did substantial work. But it still ended when the agent responded, and the next cycle required human initiation.

6.8.4 Stage 4: Loops

Loops remove the requirement for human initiation between cycles. The agent decides when to continue, based on the stop condition. This is the foundational shift that enables persistent, autonomous agent behavior.

Note

Each stage of this evolution expanded the unit of work. Single-turn: one prompt-response. Multi-turn: a conversation. Agentic turn: a task. Loop: an ongoing process. As the unit of work grows, the scope of what agents can accomplish grows with it — from answering questions to running services.

6.9 Designing Stop Conditions in Depth

The stop condition is the most critical design element of a loop. Let’s examine each type’s stop conditions in detail.

6.9.1 Turn-Based Stop Conditions

For turn-based loops, the stop condition is implicit: the task is complete when the agent says it’s done. The risk is that “done” is subjective — the agent may consider a task complete when the human doesn’t. Mitigation: define acceptance criteria in the prompt so the agent can self-check.

6.9.2 Goal-Based Stop Conditions

Goal-based stop conditions must be:

  1. Programmatically checkable: The agent must be able to verify the condition without human judgment. “All tests pass” is checkable; “the code is elegant” is not.
  2. Binary or threshold-based: A clear pass/fail, or a measurable threshold (“coverage ≥ 90%”).
  3. Accompanied by a fallback: A maximum cycle count or time limit to prevent infinite loops.
# A well-specified goal-based loop
/goal "All tests pass, lint is clean, type checking passes, and coverage is above 90%"   --max-cycles 20   --on-failure "report what's still failing and stop"

6.9.3 Time-Based Stop Conditions

Time-based loops stop based on the schedule, not a task condition. The “stop” is the completion of one scheduled run; the loop continues by running again at the next scheduled time. The design question is: what should each run accomplish? Each run should be a self-contained task that produces a useful result (a report, a set of fixes, a notification).

6.9.4 Proactive Stop Conditions

Proactive loops stop when the triggering event is resolved. The design question is: what constitutes “resolved”? For a vulnerability-scanning proactive loop, “resolved” might be “all found vulnerabilities have been reported or fixed.” Define resolution clearly to avoid the loop acting indefinitely on a single event.

6.10 Token Economics of Loops

Loops can consume significant tokens, especially unattended ones. Understanding the token economics is essential for cost management.

Loop Type Token Profile Cost Control
Turn-based Bounded by the task Standard budgeting
Goal-based Bounded by max cycles Set max cycles and per-cycle budget
Time-based Unbounded (recurring) Set per-run budget and daily cap
Proactive Unbounded (event-driven) Set per-event budget and rate limits
Note

The danger zone for token costs is proactive loops without budgets. An agent that triggers on every event, with no spending cap, can accumulate costs rapidly — especially if events are frequent. Always set budgets and rate limits for proactive loops before deploying them.

6.10.1 Budget Strategies

  • Per-cycle budget: Cap the tokens for each loop iteration. If the budget is exceeded, the cycle stops and reports what it accomplished.
  • Daily/weekly caps: Cap total tokens across all cycles in a period. Prevents runaway costs from frequent triggering.
  • Model selection: Use cheaper models (Sonnet) for routine cycles and reserve expensive models (Opus) for complex ones. A time-based loop might use Sonnet for routine scans and escalate to Opus only when it finds something requiring deeper analysis.

6.11 Observability for Loops

Unattended loops require observability — you need to know what they did, what they found, and whether they’re healthy. Key observability practices:

  • Logging: Every cycle should log what it did, what it found, and any errors.
  • Notifications: For proactive and time-based loops, notify stakeholders of significant findings (not every cycle — only when there’s something worth reporting).
  • Health checks: Monitor whether loops are running on schedule and completing successfully. A loop that silently stops running is a common failure mode.
  • Result archiving: Store each cycle’s results for audit and trend analysis.

6.12 Security Considerations for Autonomous Loops

Loops that act without human initiation require careful security design:

  • Principle of least privilege: The loop’s agent should have only the permissions it needs — no more.
  • Action boundaries: Define what the loop can do automatically (e.g., open issues, post comments) versus what requires human approval (e.g., merge code, modify production).
  • Audit trails: Log every action the loop takes, for accountability and debugging.
  • Rollback capability: Ensure that actions taken by autonomous loops can be rolled back if they’re wrong.

6.13 Key Takeaways

  • Loops extend agents beyond single turns. A loop repeats cycles until a stop condition is met, enabling persistent and autonomous work.
  • Four types of loops: turn-based (user prompt), goal-based (/goal with exit criteria), time-based (/loop, /schedule), and proactive (event/schedule triggered, no human).
  • The stop condition is paramount. Make it checkable, unambiguous, and include a fallback (max cycles/time).
  • Keep the codebase clean. Loops amplify codebase state — messiness compounds across cycles.
  • Use verification in every loop. Tests, linters, adversarial agents, or rubrics should check each cycle’s work.
  • Use a second agent for reviews to catch errors through fresh-perspective review.
  • Manage token usage with budgets, cost-appropriate models, and context management — especially for unattended loops.
  • Loops compose with workflows, subagents, skills, and hooks to build sophisticated agentic systems.