This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Loop Engineering

Designing the loop as a system — its parts, its shapes, and when you need an SDK at all.

Goal

Answer the questions a builder actually asks about loops: what is loop engineering, what are its parts, how many loops do I need, how many shapes are there, why is it needed — and do you have to code one on an SDK, or can Claude Code / Codex do it? Each question has its own page; this is the map.

What it is

Loop engineering is designing the iteration itself, instead of doing the iterating. Prompt engineering shapes one model call; the harness runs one agent’s loop; loop engineering designs the system of loops: what repeats, who checks the result, what counts as “done”, and what stops it. In one line: you stop being the person who prompts the agent — you build the thing that prompts the agent.

Crucially, looping is a way of organising a system, not a model. It isn’t a feature you switch on; it’s a pattern almost any agent framework can run, depending on how you wire the pieces. That’s why the paradigm is shifting from Prompt → Output to Goal → Loop → Evaluate → Improve → Repeat → Result — and why both Anthropic and OpenAI now push engineers to build the loop, not just the prompt.

The maturity ladder

Each generation fixed the last one’s failure — this is the shape of the whole field, and the map for the pages below:

flowchart LR
    subgraph P1["1 · Prompt engineering — human drives every iteration"]
      H[Human] --> A1[Agent] --> O1[Output]
      O1 -. feedback .-> H
    end
    subgraph P2["2 · Loop engineering — agent improves its own work"]
      G2[Goal] --> A2[Agent] --> R2[Research] --> D2[Draft] --> E2[Evaluate] --> I2[Improve]
      I2 --> A2
    end
    subgraph P3["3 · Orchestrated looping — teams iterate until done"]
      G3[Goal] --> Orc[Orchestrator - breaks down the goal]
      Orc --> RA[Research agent] & CA[Coding agent] & TA[Testing agent]
      RA & CA & TA --> EV[Evaluation agent - checks quality]
      EV -. next round .-> Orc
    end
    P1 ==> P2 ==> P3
YearLoopLesson it taught
2022ReAct — reason → act → observe, one model, one loopIteration beats one-shot answers
2023AutoGPT — goal-seeking loopFamous for spinning forever → loops need stop conditions
2025Ralph loop — the same prompt re-run against fixed anchor filesPersistent anchors keep long runs coherent
Early 2026Productised loops — a validator decides when work is done“Done” must be checked, not self-declared
Mid 2026Orchestration — a supervisor schedules and coordinates worker loopsOne loop doesn’t scale; teams of loops do

The five pages

PageQuestion it answers
The parts of a loopWhat’s inside a production loop
The four levels of loopsHow many loops you need, and what each one buys
Open vs. closed loopsWhich shape to choose, and when
Fleet loopingHow looping scales to teams of agents
Building a loopOff-the-shelf tool or your own SDK

The two framings compose. Levels tell you how many loops to wrap around the work; the axes below describe each individual loop you end up with — so any loop you meet is a point on three independent axes:

AxisOptionsDetailed in
ArchitectureOpen (explore) vs closed (measured)Open vs. closed
TopologySingle worker vs orchestrated fleetFleet looping
OversightHuman in / on / out of the loopFleet looping

Why you need it

  • One-shot calls cap out — quality comes from iterate-and-verify, and doing that manually makes you the bottleneck.
  • Trust requires a validator — unreviewed agent output doesn’t ship; a loop with a checker turns “plausible” into “verified”.
  • Cost control requires closure — open exploration is unpredictable spend; closed loops with thresholds make cost and quality measurable per run, so each run can be improved.

You stop being the person who prompts the agent — you build the thing that prompts the agent.

When orchestration is warranted, the structure those coordinated loops run on is a graph — see From prompts to graphs for where loop engineering sits in the wider lineage.

Sources

1 - The Parts of a Loop

The six components of a production loop — and why the worker is the least interesting one.

What’s inside a production loop.

What it is

A production loop has six parts. The worker — the agent doing the task — is the least interesting one; the parts around it are what turn a demo into something you can trust unattended.

flowchart LR
    D[Discovery - finds work] --> B[Backlog and decomposition]
    B --> W[Worker loop - does the task]
    W --> V[Validator - checks the result]
    V -->|pass| Done[Merge and record]
    V -->|fail, with feedback| W
    S[Stop conditions - rounds, tokens, time] -.-> W
    M[Memory and anchors - skills, project rules] -.-> W

The six parts

  • Discovery / automations — finds work without a human trigger: a schedule, a webhook, a scanner. This is what lets a loop run unattended; see the four levels for the trigger types and where to put them.
  • Decomposition — an orchestrator breaks the goal into tasks a worker can own. See fleet looping when this goes multi-level.
  • Worker — an agent with tools and MCP connectors; parallel workers get git worktrees so they don’t overwrite each other.
  • Validator — a second judgment (LLM-as-judge, a test suite, or both) that decides pass/fail — never the worker grading itself.
  • Stop conditions — max rounds, token budget, loop detection: the AutoGPT lesson, inherited from the harness.
  • Memory & anchors — skills, project rules, and agent memory so each round builds on the last instead of rediscovering it.

Example

A nightly dependency-update loop: discovery is the cron trigger; decomposition splits “update all packages” into one task per package; the worker bumps a version and runs the build; the validator is the test suite; stop conditions cap it at three fix attempts per package; anchors are the project’s upgrade notes so it doesn’t re-learn known breakages. Only the worker is an “agent” — the other five are what make it safe to leave running overnight.

Sources

2 - The Four Levels of Loops

Loops nest — each level wraps the one below it and buys one thing the inner loop can’t give you.

How many loops you need, and what each one buys.

What it is

The four levels are not four kinds of loop. They are one loop wrapped four times — each level surrounds the level below it and adds a property the inner loop cannot produce on its own. So the question is never “which loop is this?” but how many do I need?

flowchart TB
    subgraph L4["Level 4 · Hill climbing — the harness gets better"]
      subgraph L3["Level 3 · Event-driven — something starts the run"]
        EV[Event - chat message, schedule, repo hook] --> M
        subgraph L2["Level 2 · Verification — a grader decides what done means"]
          subgraph L1["Level 1 · Agent loop — the work gets done"]
            M[Model] --> T[Tool call] --> O[Observation] --> M
          end
          M --> R[Agent output]
          R --> G{Meets the rubric}
          G -->|no, with feedback| M
        end
        G -->|yes| OUT[Result posted back to the system]
      end
      OUT --> TR[Traces of past runs]
      TR --> AN[Analysis agent - finds the repeating failure]
      AN --> UP[Better prompts, skills, memory]
      UP -.-> M
    end

The four levels

LevelWhat it addsWhat it costsDetailed in
1 · Agent loop — the model calls tools until it decides the task is doneAutomationA model call per stepThe agent harness
2 · Verification loop — a grader scores the result against a rubric and sends failures back with feedbackReliabilityLatency and tokens on every retryOpen vs. closed loops
3 · Event-driven loop — a signal from outside starts the runReach — the agent lives where the work already happensInfrastructure, and the risk of firing on the wrong thingThis page
4 · Hill-climbing loop — traces from past runs feed an agent that improves the harnessImprovement over timeAn eval set you trustSelf-improving agents

Level 2 also changes the economics of level 1. A grader that keeps sending work back is a correctness budget you can spend elsewhere: a cheaper model plus a strict grader often beats the strongest model alone, because the grader catches what the cheap model got wrong and the retries still cost less. You are trading latency for money. See choosing a model for the tier ladder that trade runs on.

Level 3 is the one nobody plans for. A loop nobody starts is a loop nobody uses. The trigger is a schedule, a message in a chat channel, a repository event (a PR opened, an issue labelled), an incoming email, or an alert from a scanner. The rule is to put the trigger where the work already is — an agent that needs people to visit a separate tool is how an internal agent quietly dies.

Example — a docs agent, level by level

The same agent, wrapped one level at a time:

  • Level 1 — it clones the repository, reads the current page, writes a new one, and opens a pull request with the diff. Useful, but somebody has to ask it, and somebody has to check it.
  • Level 2 — a grader now runs before it reports back: no dead links, and CI green. On a fail, the reasons go back to the agent and it tries again. Reviewers stop receiving broken PRs.
  • Level 3 — a message in the team’s #docs-please channel starts the run, and the finished PR is posted back to the same thread. Nobody learns a new tool, so people actually use it.
  • Level 4 — an analysis agent reads the traces of the last hundred runs and notices the same failure repeating: the agent keeps missing the style guide, because nothing ever put it in context. It proposes adding the guide as a skill. That change is itself a pull request.

Levels 1 to 3 automate the work. Level 4 automates the improvement of the thing that does the work — which is why it compounds and the others don’t.

Where the human goes

Automating the loop is not the same as removing the person. Spend human judgment where it changes the outcome, and nowhere else:

LevelWhere the human sitsUse it when
1Approves a sensitive tool call before it runsThe action is irreversible or external — money moves, mail sends, records are deleted
2Is the grader, or reviews what the grader passedThe rubric is still forming, or the signal is too fuzzy to score automatically
3Reviews the finished artifactThe output is a proposal, not an action — a PR, a draft, a plan
4Approves changes to the harness before they mergeAlways, until the eval set is strong enough to merge on a score

Responsible AI owns the placements themselves and the warning that comes with them: a reviewer buried in approvals rubber-stamps, which is worse than no gate at all.

Sources

3 - Open vs. Closed Loops

The architecture axis — explore freely, or measure against criteria defined upfront.

The architecture axis — which shape to choose, and when.

What it is

The names come from control theory: a closed loop feeds its output back and corrects against a reference; an open loop runs without that feedback path. For agents:

  • Open loop — the agent gets a goal and freedom: it explores, reasons, and decides its own next steps. There are no predefined success criteria; the run ends when the agent declares itself done or the budget runs out, and a human judges the output afterwards.
  • Closed loop — the goal ships with explicit success criteria and a validator defined before the run. Every iteration is measured against them; failures feed back into the next round; “done” means the threshold was passed, not “the agent felt finished”.
flowchart LR
    subgraph O["Open loop"]
      G1[Goal] --> A1[Agent explores and decides] --> R1[Output]
      R1 --> H1[Human judges afterwards]
    end
    subgraph C["Closed loop"]
      G2[Goal + criteria] --> W2[Worker] --> V2[Validator]
      V2 -->|pass threshold| D2[Done]
      V2 -->|fail + feedback| W2
    end
QuestionOpen loopClosed loop
Who decides the next step?The model, at runtimeThe process, designed upfront
What does “done” mean?Agent self-declares, or budget diesValidator passes a threshold
Cost per runUnpredictableBounded (rounds × budget)
Result across runsVariesRepeatable
Can it improve?Hard — nothing is measuredRun over run — every run is scored
Main riskToken burn, drift, quality by luckA wrong rubric gets enforced at machine speed; solutions outside the frame get missed

When to choose which

Choose open when the problem itself is unexplored: you don’t yet know what “good” looks like, it’s a one-off spike (“figure out why these tests are flaky”, “map this legacy codebase”), and a human will read the output directly. Exploration is the one thing a closed loop can’t do — its criteria would have to exist already.

Choose closed when the task repeats, runs unattended (CI, schedules), spends real money, or its output ships without a human watching every step. Production defaults to closed for exactly those reasons.

They’re stages, not rivals

The two aren’t rivals — they’re stages of the same lifecycle: run the task open a few times to discover the criteria, then freeze those criteria into a validator and close the loop. The autofixer case study went exactly this way: the first fixes were exploratory and hand-reviewed; once the review rubric stabilised, it became the reviewer agent’s rubric.

Open to explore, closed to operate — a task that repeats enough deserves to be closed.

Sources

4 - Fleet Looping

How looping scales from one self-correcting agent to a coordinated team — and who watches it.

The topology and oversight axes — scaling looping up.

What it is

At the simplest level, one agent loops on its own work: research → draft → evaluate against the goal → fix the weak spots → repeat until it’s good enough. You no longer prompt each step; the agent runs the loop for you.

Fleet looping is that same idea at scale. An orchestrator takes the overall goal and breaks it into parts; it hands each part to a specialist agent; each specialist can further delegate narrower work to its own sub-agents. The whole task tree keeps cycling through four phases until the goal is met:

flowchart TB
    G[Goal] --> Orc[Orchestrator]
    Orc --> S1[Specialist - research] & S2[Specialist - build] & S3[Specialist - test]
    S1 --> A1[sub-agent] & A2[sub-agent]
    S2 --> A3[sub-agent] & A4[sub-agent]
    subgraph Cycle["Every node cycles"]
      Dc[Discover] --> Pl[Plan] --> Ex[Execute] --> Vf[Verify]
      Vf -. not done .-> Dc
    end

If a single self-looping agent is one person endlessly revising their own draft, a fleet is a whole team running a project end to end. You define the goal; the system runs until it meets the criteria.

The two axes it introduces

Fleet looping is where two of the three loop axes come alive:

  • Topology — single loop (one worker; simpler and usually enough) vs orchestrated (a supervisor plus specialised workers). Orchestrate only when tasks genuinely parallelise or need separate maker and checker roles — a fleet multiplies both cost and failure modes.

  • Oversight — how far you step back:

    • Human in the loop — approves each step (highest control, lowest throughput).
    • Human on the loop — monitors and intervenes on exception.
    • Human out of the loop — reviews outcomes only.

    This is the same ladder as responsible AI’s placements, applied to loops: you graduate from sitting inside one loop to designing loops that watch other loops.

Why it needs discipline

A fleet without evaluation gates at each phase produces confident AI slop at scale — many loops amplifying a bad rubric faster than any human can catch it. The gate (a validator) is what keeps a fleet’s output above the “meets the standard” bar. That’s why most tasks still deserve one worker and a schedule, not a fleet: orchestration is a cost you pay only when the work truly parallelises.

Example

“Publish a launch article.” The orchestrator spawns a research specialist (which delegates sub-agents to gather sources and competitor pages), a drafting specialist, and an editing specialist that acts as the evaluation gate. Each cycles discover → plan → execute → verify; the editor rejects drafts that miss the brief, feeding notes back — until the piece clears the bar. One goal in, a finished article out, no human writing a single prompt per step.

Sources

5 - Building a Loop

Off-the-shelf coding agent or your own SDK — and a real closed loop, taken apart.

How you actually build one — and a worked example.

SDK, or Claude Code / Codex off the shelf?

The honest answer: start with the tools — you already own a production-grade loop. Claude Code and Codex are loop products: harness, tools, skills, MCP, stop conditions all built in. There’s a ladder, and each rung must be earned:

  1. Use the tool interactively — you are the orchestrator. Fine for daily work.
  2. Script the tool — run it headless in CI on a schedule with a fixed prompt, skills, and MCP servers. This is already loop engineering — no SDK, and it covers most closed-loop automation (nightly triage, lint-fix sweeps, doc updates).
  3. Code on an SDK (Agent SDK, LangGraph, Microsoft Agent Framework) only when the loop needs what a tool can’t give you: custom topology (a fixer and a reviewer with different models talking to each other), your own validator logic and thresholds, or the loop is your product and needs its own UI, state, and versioning.

Rule of thumb: if your loop is one worker + a schedule, script the tool you have. If it’s several roles negotiating, that’s when an SDK earns its complexity.

Case study — a static-analysis autofixer

A real closed loop I built when security scans (SonarQube) started piling up minor issues faster than humans cleared them:

flowchart LR
    Cron[Nightly schedule] --> Fix[Fixer agent - Sonnet]
    SQ[SonarQube MCP] --> Fix
    Fix -->|classify, label, patch, PR| Rev[Reviewer agent - Opus, judge with rubric]
    Rev -->|pass| PR[PR ready for humans]
    Rev -->|fail + feedback| Fix
    Lim[Hard limit - N rounds] -.-> Fix

A fixer (Sonnet) pulls issues via the SonarQube MCP server, classifies and labels them, patches the safe ones, and opens a PR. A reviewer (Opus) judges the patch against a rubric; on fail it feeds the reasons back to the fixer — at most N rounds (the hard limit), then it stops rather than spins. The whole thing runs on a schedule in GitHub Actions, orchestrated with an agent framework plus skills (guidelines, incremental-implementation, sonar-guardrails).

Every axis shows up: closed loop, human on the loop (they review PRs, not steps), orchestrated topology — and it only needed an SDK because two different models negotiate; the discovery half could have been a scripted coding agent.

Strengths & limitations

  • Strengths — throughput without a human bottleneck; a validator makes quality enforced, not hoped for; closed loops give you a cost ceiling and improve run over run; the maker–checker split catches what self-review can’t.
  • Limitations — validators can be gamed or wrong (judge bias — calibrate against human labels); loops amplify a bad prompt or rubric at machine speed; orchestration multiplies cost and failure modes — most tasks still deserve one worker and a schedule, not a fleet.

Sources