Library
9 min read

Loop engineering

For the first few years of coding agents, the human was the loop. You prompted, read what came back, noticed the test that still failed, prompted again, and kept doing that until it was done. The agent did the typing. You did the steering, every few minutes, all day.

Loop engineering is the name that spread through 2026 for moving yourself out of that position: designing the system that prompts the agent, checks its work, and steers it, so that it can run many cycles without you. IBM's definition is a good one: the practice of designing agentic workflows, or loops, that iteratively guide AI agents toward user defined goals with minimal human intervention. Prompt engineering is writing one good instruction. Context engineering is deciding what the model sees on each call. Loop engineering is the layer above both: the cycle itself.

Your answer

You can either make your agent's single attempt more reliable, or let it retry with a check in between. Which one would you invest in first, and what decides it?

Anatomy of a loop#

Every loop has the same four beats, whether it is a coding agent fixing a test or a research agent writing a report.

Figure 1. The loop only works if the observation step can tell good from bad. Everything else is plumbing around that check.

Goal. Not "improve the checkout page" but "make test_checkout.py pass without changing the tests". A loop needs a stop condition a program can check, or it never knows it is finished.

Act. One attempt by the agent: an inner loop of tool calls, as in What an agent is.

Observe. Something other than the agent's own opinion judges the attempt: tests, a type checker, a linter, a schema validator, or a second model with its own instructions and rubric.

Adjust. What failed is written somewhere the next attempt will read, so it does not make the same mistake twice.

The five decisions#

1. The stop condition. Prefer checks that cannot be argued with: tests pass, the build is green, the JSON validates, the numbers reconcile. A rubric graded by a model is weaker but still far better than the agent deciding for itself.

2. The checker. A maker and checker split, where a separate verifier with its own instructions judges the work, catches more than asking the same agent "are you sure?". The agent that wrote the bug tends to believe its own explanation of why it is fine.

3. The spine. A persistent record of the task: the plan, what was tried, what failed and why. A markdown file in the repository is enough. It survives context compaction and restarts, and it keeps attempt five from repeating attempt two. This is the write it down outside move, made central.

4. Budgets. A maximum number of attempts, tokens, money and wall clock time, enforced by the loop code, not requested of the model.

5. Escalation. When the budget runs out or the checker keeps rejecting, the loop stops and hands a clean summary to a person: what was tried, the current state, the failing check. A loop that fails loudly is fine. One that fails silently is the real risk.

Tune it#

Here is the arithmetic of a loop. One attempt succeeds some of the time. The checker catches some of the failures, and each caught failure gets another attempt, up to a limit.

Tune the loop
60%
80%
3
Finished and correct85.3%
Shipped a wrong answer, checker missed it11.4%
Ran out of attempts, handed to a person3.3%
Average attempts per task: 1.42
Each extra attempt only runs on the failures the checker caught, so the cost grows slowly: 1.42 attempts per task on average. The 11.4% that ship wrong are the ones your checker cannot see, and no number of attempts fixes those.
Assumes the checker never rejects a correct attempt. Real checkers sometimes do, which adds wasted attempts.

Two lessons fall out of it. First, retries are only as good as the checker: with a weak check, failures ship as successes and extra attempts change almost nothing. Second, retries are cheap when they are rare: each extra attempt only runs on the failures that were caught, so allowing three attempts usually costs much less than three times as much.

That is the answer to the question at the top. If you can build a strong automatic check, invest in the loop first, because it multiplies whatever reliability the agent already has. If you cannot check the work automatically, retries cannot help you, and a more reliable single attempt plus a human review is the better investment.

The loop in code#

Strip away the framework and a task loop is short. The agent call can be any of the approaches in the frameworks chapter.

python
import subprocess
from pathlib import Path
 
SPINE = Path("PROGRESS.md")
MAX_ATTEMPTS = 4
 
def check() -> tuple[bool, str]:
    # The stop condition: the test suite, not the agent's opinion.
    run = subprocess.run(["pytest", "-x", "-q"], capture_output=True, text=True)
    return run.returncode == 0, run.stdout[-3000:]
 
def task_loop(goal: str) -> bool:
    SPINE.write_text(f"# Goal\n{goal}\n\n# Attempts\n")
    for attempt in range(1, MAX_ATTEMPTS + 1):
        run_agent(  # your agent: a tool loop that can read and edit the repo
            f"{goal}\n\nRead PROGRESS.md first. Do not repeat failed approaches."
        )
        ok, report = check()
        if ok:
            return True
        with SPINE.open("a") as f:
            f.write(f"\n## Attempt {attempt} failed\n```\n{report}\n```\n")
    escalate(SPINE.read_text())  # budget spent: hand the record to a person
    return False

Outer loops#

The same idea scales up a level. Instead of you starting each task, something else does:

  • A schedule. A cron job or CI workflow runs the loop nightly over open issues, failing flaky tests, or dependency updates. Coding tools now ship this directly; Claude Code, for example, has a /loop command that reruns a prompt on an interval.
  • An event. A new issue label, a failed deploy or a customer ticket triggers a loop.
  • Many at once. Several loops run in parallel, each in its own git worktree or sandbox so they cannot trample each other's files, each producing a pull request for a person to review.

At the extreme, people run the same prompt against a coding agent over and over in a plain shell while loop, letting the spine file and the test suite carry progress between runs. It works surprisingly often, and it shows how much of the reliability is in the check and the spine rather than in any single clever prompt.

ChoiceWhat you gainWhat you payPick it when
Human in the loop on every stepMaximum control, nothing unexpected ships.The human is the bottleneck, and their attention runs out first.New, risky or unverifiable tasks.
Automated loop with a strong checkerMany attempts without supervision, and reliability that multiplies.Building the check, and token cost per task.Tasks with an automatic stop condition: tests, builds, validators.
Scheduled or event driven outer loopsWork happens while nobody is watching.Comprehension debt: a pile of changes nobody has read yet.Routine, reviewable work, always ending in a review gate.
What is wrong with this loop?
The agent decides when the task is complete
Attempt four makes the same change as attempt two
A loop ran all weekend and spent the monthly budget
Thirty agent pull requests are waiting and nobody has time to review
Comprehension debt

A loop that produces working code faster than anyone reads it creates a codebase nobody fully understands. The loop's last step should always be a review a person can actually do: small diffs, a clear summary, the spine attached. Humans stay responsible for what ships.

Checkpoint#

Checkpoint

1. With a checker that catches only 20% of failures, what happens when you allow more attempts?

2. What is the spine of a loop?

3. Why use a separate checker instead of asking the agent to verify its own work?

Worth memorising
  • Loop: goal, act, observe, adjust, until a checkable stop condition or the budget.
  • Retries are only as good as the checker.
  • A spine file carries progress across attempts and restarts.
  • Budgets in code, escalation to a person, review before shipping.
Say this in 60 seconds

Loop engineering is designing the cycle that prompts, checks and steers an agent, so it can run many iterations without a person typing each prompt. Every loop is goal, act, observe, adjust. I would give it a stop condition a program can check, like tests passing, an independent checker rather than the agent grading itself, a spine file that records what was tried so attempts do not repeat, and budgets on attempts, tokens and time enforced in code, ending in a clean handoff to a person when it fails. The arithmetic matters: retries multiply reliability only when the checker catches failures, so I invest in the check first. And outer loops on schedules or events still end in a review a person can actually do.