All posts

AI engineering · AI agents · Guides

Loop engineering: the discipline after prompt engineering

Loop engineering is designing the loop around an AI agent - its trigger, stop condition, budget, and verification - so it runs without you.Prompt engineering shapes one answer; loop engineering shapes autonomous runs. Coined mid-2026, it’s the skill behind every agent that works while its owner sleeps. Here’s the complete guide, with code.

Deric YeeDeric Yee Updated 24 August 2026 10 min read

From prompting to loops: why the discipline changed

For two years, working with AI meant a conversation: you prompt, it answers, you correct, it tries again. The skill was phrasing - prompt engineering. Then agents got good enough to run multi-step tasks, and a new bottleneck appeared that no amount of clever phrasing fixes: you. If a human has to start every run, check every result, and prompt every correction, the agent’s throughput is capped at the speed of its babysitter.

Loop engineering is the response. Instead of prompting the agent, you design the system that prompts, checks, and corrects the agent- and then you get out of the way. The shift sounds subtle; economically it isn’t. A prompted agent saves you minutes per task. A well-engineered loop works nights and weekends, catches its own failures, and only surfaces the runs that genuinely need a human. Developers noticed en masse around mid-2026, when tools like Claude Code shipped native looping (a /loop command, cron schedules, event hooks) and the term “loop engineering” stuck.

One prerequisite before we go further: this guide sits on top of the agent loop itself - the inner reason → act → observe cycle that makes a single run work. If that’s new to you, read how to build an AI agent first - we build that inner loop in ~50 lines there. Loop engineering is the outer loop: the machinery that decides when the inner one runs, and when it must stop.

The four loop types

Every autonomous agent setup in the wild is one of these four - or a composition of them.

Heartbeat loops

Trigger: A short, constant interval

The agent wakes every few minutes, checks its standing instructions against the current state of the world, acts if anything needs doing, and sleeps again. The always-on assistant pattern.

“Every 10 minutes: check the support inbox, triage anything new, escalate anything angry.”

Cron loops

Trigger: A schedule

The agent runs at fixed times with a fixed job. The simplest loop to reason about, because the trigger, the task, and the deliverable are all known in advance.

“Every weekday at 9am: pull yesterday’s analytics, write the anomalies report, post it to Slack.”

Hook loops

Trigger: An event

The agent is wired to something happening: a pull request opened, a CI run failing, a form submitted. Event-driven agents feel the most magical because work starts the moment it exists.

“On every PR: review the diff, comment on real issues, approve if clean.”

Goal loops

Trigger: A success condition not yet met

The agent iterates - attempt, verify, adjust - until an externally-checkable condition is true, then stops. The hardest type to engineer well, and the one that produces the most value when you do.

“Keep going until every test passes and the linter is clean - or you’ve used 15 attempts.”

Real systems compose these: a hook loop watches CI, and when a build fails it hands the failure to a goal loop that fixes it - bounded by a budget, reporting to a human only on defeat.

The anatomy of a well-engineered loop

Whatever the type, a loop that survives contact with production has five parts - and most homemade loops are missing at least two of them.

1. A trigger.Interval, schedule, event, or unmet goal - defined precisely. “Whenever needed” is not a trigger; it’s a human with a to-do list.

2. A verifiable stop condition.The single most important design decision, so it gets its own section below. The short version: the model’s opinion that it succeeded is not a stop condition. An exit code is.

3. Budgets.Two ceilings, always: a maximum iteration count and a token (or dollar) cap. A loop without budgets isn’t autonomous - it’s unsupervised. Budgets convert “what’s the worst that can happen?” from an unknown into a number you chose.

4. State between runs.A heartbeat agent that can’t remember what it already handled will handle it again - every ten minutes, forever. Loops need a durable record of what’s been seen and done (a file, a database row, a ticket label) that lives outside the model’s context.

5. An escalation path.Every loop eventually meets a task it can’t finish. The engineered response is designed in advance: stop, preserve the evidence, notify a human with enough context to act. Loops that retry silently until someone notices the bill are the genre’s horror stories.

The walkthrough: a goal loop that fixes tests

Here’s the canonical goal loop - the one most working developers meet first: keep fixing until the test suite is green. It wraps the inner agent from our previous guide in an outer loop with all five parts: an unmet-goal trigger, an objective verifier, both budgets, and an escalation path.

fix-until-green.ts - a complete goal loop
import { execSync } from 'child_process'

// The verifier lives OUTSIDE the model. Exit codes don't hallucinate.
function testsPass(): { ok: boolean; output: string } {
  try {
    return { ok: true, output: execSync('npm test 2>&1').toString() }
  } catch (err: any) {
    return { ok: false, output: err.stdout?.toString() ?? String(err) }
  }
}

// A goal loop: attempt -> verify -> adjust, inside hard budgets.
async function fixUntilGreen() {
  const MAX_ATTEMPTS = 15            // iteration budget
  let spentTokens = 0
  const TOKEN_BUDGET = 500_000       // cost budget

  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
    const check = testsPass()
    if (check.ok) return { done: true, attempts: attempt - 1 }

    // One agent turn: here, runAgent() is the reason-act-observe loop
    // from our build-an-agent guide, with file-edit and bash tools.
    const result = await runAgent(
      `The test suite is failing. Fix the code (never the tests unless
       they are objectively wrong). Failing output:\n${check.output}`
    )
    spentTokens += result.usage

    if (spentTokens > TOKEN_BUDGET) break   // cost ceiling beats optimism
  }

  // Budget exhausted without success: escalate, don't loop silently.
  return { done: false, escalate: 'Tests still failing - needs a human.' }
}

Notice what does the deciding. The modeldecides how to fix the code - that’s its job. But the loop decides everything else: whether the goal is met (an exit code, not a claim), whether to continue (budgets), and what happens on defeat (escalation, with the failing output preserved). The intelligence is rented; the judgement is engineered. That division of labour is the whole discipline in one sentence.

And one prompt detail worth stealing: “never fix the tests unless they are objectively wrong.”Goal loops optimise whatever you actually measure - an agent told to “make the tests pass” will eventually discover that deleting the tests makes them pass. Every stop condition you write will be probed by an optimiser with no shame. Write them the way you’d write rules for a genie.

The stop-condition problem

If loop engineering has one law, it’s this: never let the model grade its own homework. Language models are systematically overconfident about their own output - ask an agent “is this done?” and the answer skews yes, because the transcript it’s reading is a story of itself succeeding. A loop whose exit is the model’s self-assessment will exit early on hard tasks and, worse, exit wrong.

The hierarchy of stop conditions, best to worst: an objective check (tests, compilers, schema validators, a measurable number crossing a threshold); an independent judge(a second model call with fresh context whose only job is to find fault - imperfect, but uncorrelated with the worker’s optimism); and a human checkpoint(fine, and often right, for outward-facing or irreversible actions - the loop drafts, a person approves). Self-assessment isn’t on the list. If a task has no checkable success condition at all, that’s the signal it isn’t ready for a loop - run it interactively instead.

The other failure worth naming is non-convergence: loops that oscillate (fix A breaks B, fix B breaks A) or plateau (each attempt slightly rephrases the last failure). Detection is engineering, not hope - track progress across iterations (failing test count, error signatures), and treat “no improvement in N attempts” as a stop condition of its own. An agent that has stopped converging isn’t almost there; it’s burning your budget in a circle.

Loop engineering in the tools you already use

You don’t have to build the outer machinery from scratch to practise this. Claude Code ships all four loop types natively: a /loop command for interval and self-paced runs, cron-style scheduled tasks, and hooks that fire on events - and its coding agent is itself the inner loop. OpenAI’s Codex offers scheduled automations in the same spirit. Even CI systems double as loop infrastructure: a GitHub Action that runs an agent on every failing build is a hook loop you can ship this afternoon.

The tools lower the plumbing cost to near zero - which moves all the value into the design decisions this guide covers: what triggers the run, what verifies the result, what bounds the spend, who gets told on failure. That’s worth internalising because it generalises beyond code. The person who can define a job precisely enough for a loop to run it - measurable outcome, checkable success, bounded cost - has learned something no tool ships: how to delegate to machines. It’s exactly what we train in Phase 3 of the programme, where students direct an AI coding agent through a full spec → plan → review → deploy cycle - the human-designed loop, run for real. And when one loop isn’t enough - when you need many agents and feedback loops wired into a system that checks itself - that’s the next layer up: graph engineering, which we cover in its own guide.

FAQ

  • What is loop engineering?

    Loop engineering is the practice of designing the loop around an AI agent - its trigger, its stop condition, its budget, and its verification - so the agent can run repeatedly or continuously without a human prompting every step. Where prompt engineering shapes one response and context engineering shapes what the model sees, loop engineering shapes autonomous runs: when the agent wakes, how it knows it has succeeded, and what stops it when it hasn’t. The term took off in mid-2026 as developers moved from chatting with coding agents to putting them on repeat.

  • How is loop engineering different from prompt engineering?

    Prompt engineering optimises a single request: phrasing, examples, structure, to get one better answer. Loop engineering assumes the agent will run many times without you, and designs the system around those runs - triggers (schedule, event, or interval), stop conditions, iteration and token budgets, and verification the model cannot fake. A perfect prompt inside a badly-designed loop still produces runaway costs or confidently wrong output; a decent prompt inside a well-engineered loop self-corrects. The prompt is one component; the loop is the system.

  • What are the four types of agent loops?

    Heartbeat loops run on a short constant interval (an always-on assistant checking its inbox every few minutes). Cron loops run on a schedule (a report agent every weekday at 9am). Hook loops fire on events (review every pull request when it opens). Goal loops iterate until an externally-checked success condition is met (keep fixing until the tests pass), with a budget as the safety net. Real systems compose them - a hook loop can hand a failure to a goal loop that fixes it.

  • How do you stop an AI agent loop from running forever?

    Layer three mechanisms, because each fails differently. First, an objective stop condition checked outside the model - exit code from a test suite, a schema validation, a measurable threshold - never the agent’s own claim of success. Second, hard budgets: a maximum iteration count and a token or dollar ceiling, so a non-converging loop costs a bounded amount. Third, an escalation path: when the budget is hit without success, the loop stops and reports to a human rather than silently retrying. The pattern to avoid is any loop whose only exit is the model deciding it is done.

  • Is loop engineering a real discipline or just hype?

    The name is new (coined in June 2026); the problem is real and older. Anyone who has run a coding agent on a task has felt it: the value of an agent scales with how long it can run correctly without you, and that duration is determined almost entirely by loop design - stop conditions, verification, budgets, recovery. IBM, developer tool vendors, and the harness teams behind tools like Claude Code all treat it as a distinct design layer now. Whether the name survives, the skill it labels - designing systems that prompt, check, and correct agents - is compounding in value.

Learn to direct the machines.
Loops are delegation, engineered.

In the AI-Native Software Development Programme you don't just use AI tools - you learn to specify, verify, and direct them, including running an AI coding agent through a full spec-to-deploy cycle. That's loop engineering as a career skill.