Skip to content

All lessons

Area 03 // AI AgentsLesson 61 / 14016 min read

Loop engineering: agents that run on repeat

Loop engineering is designing the automated loops around agents (what triggers a run, how each result is checked, when the loop stops, what it may cost, and where humans review) so agents do useful work repeatedly without someone prompting them step by step.

Think of it like this

Analogy

Think of a bakery. In the early days the owner bakes each loaf by hand, checking the oven every few minutes. Later they design a production line: dough arrives on a schedule, machines shape it, the oven bakes it, a quality inspector checks every tray (too pale goes back in, burnt goes in the bin), counters track how much flour was used, and the owner only steps in for unusual problems. The owner's job changed from baking to designing the line.

Loop engineering is designing that production line for AI agents.

The problem it solves

Even with a great harness, using an agent interactively means a person types a request, watches, corrects, types again. That doesn't scale: there are hundreds of flaky tests to fix, dependency updates to apply, tickets to triage, docs to keep in sync. The work is repetitive and verifiable, but someone still has to start each task and check each result.

In mid-2026 practitioners started calling the answer loop engineering: designing the automated loops that find work, run agents on it, verify the results and repeat.

How it works: loop engineering

Loop engineering designs a few building blocks:

  1. Trigger: what starts a run. A schedule (every night), an event (CI failed, new issue, new PR comment), or a queue of tasks.
  2. Task source: where work comes from (failing tests, a backlog label, alerts) and how each task is described to the agent.
  3. The agent and its harness: tools, instructions, permissions and sandbox (harness engineering).
  4. Verifier: a machine-checkable definition of "done" (tests pass, lint clean, eval score above a threshold, a reviewer agent approves).
  5. Stop conditions and budgets: attempt caps, token and cost caps, time limits (stop conditions).
  6. Human gates: where people review (usually the final output, like a pull request), never every step.
  7. State and memory: what the loop records between runs (what was tried, what failed) so it doesn't repeat mistakes.
  8. Observability: runs, pass rates, costs and failure reasons on a dashboard.
Prompt-by-promptLoop engineering
Who starts each taskA personA trigger
Who checks the resultA person, every timeA verifier, then a person at the gate
ScaleOne task at a timeMany tasks in parallel
Engineer's jobWrite promptsDesign triggers, checks, budgets and gates

How it works: maker-checker loops

  1. The maker (an agent) produces something: a code change, a document, a data fix.
  2. The checker verifies it independently: run the tests, the linter, the type checker, an eval, or a separate reviewer agent with a strict rubric. Independence matters: a maker grading itself is too lenient (reflection).
  3. On failure, the checker's specific feedback goes back to the maker for another attempt.
  4. On success, the result moves to the human gate (e.g. a pull request).
  5. The loop is bounded: a maximum number of attempts and a budget, then it reports failure with what it learned.

How it works: scheduled and event-triggered runs

  1. Schedules: cron-style triggers for routine work (nightly dependency updates, weekly doc sync). CI systems (GitHub Actions schedule) and hosted agent platforms offer scheduling.
  2. Events: webhooks and CI events (a failed build on main, a new issue with a label, a security alert) start a run with that event as the task.
  3. Queues: tasks wait in a queue; workers pick them up with concurrency limits (message queues).
  4. Idempotency and dedupe: the same event shouldn't start two runs on the same task.
  5. Output where people already work: pull requests, ticket comments, chat messages.

How it works: long-running autonomous agents

  1. Long tasks outgrow one context: keep a plan and a progress file (or checkpointed state) that records what's done, what's next and decisions made.
  2. Work in small verified increments: change, test, commit; never hours of unverified work.
  3. Resume cleanly: a new session (or a restarted process) reads the progress file and continues (context compaction, checkpoints).
  4. Budget the whole run (tokens, time, money) and report progress regularly.
  5. Stop at the gate: autonomous runs end in something a person reviews.
A maker-checker loop started by a trigger, bounded by budgets, ending at a human gate.

See it in code

Needs
Nothing: plain Python 3. The maker is scripted; the checker really runs test cases.

A bounded maker-checker loop. The checker's exact failure message drives the next attempt.

maker_checker.py
# A maker-checker loop: one agent proposes, an independent checker verifies, repeat until it passes.
def maker(task: str, feedback: str | None, attempt: int) -> str:
    """Stand-in for a coding agent. Each attempt uses the checker's feedback."""
    drafts = ["def add(a, b): return a - b",
              "def add(a, b): return a + b"]
    return drafts[min(attempt, 1)]
 
def checker(code: str) -> str | None:
    """Machine-checkable: run the tests. Returns None if they pass, else the failure."""
    scope = {}
    exec(code, scope)
    cases = [((2, 3), 5), ((-1, 1), 0)]
    for args, want in cases:
        got = scope["add"](*args)
        if got != want:
            return f"add{args} returned {got}, expected {want}"
    return None
 
def run_loop(task: str, max_attempts: int = 4) -> str:
    feedback = None
    for attempt in range(max_attempts):              # bounded: the loop always ends
        code = maker(task, feedback, attempt)
        feedback = checker(code)
        print(f"attempt {attempt + 1}: {'PASS' if feedback is None else 'FAIL - ' + feedback}")
        if feedback is None:
            return "open a pull request for human review"
    return "give up, report what failed"
 
print("->", run_loop("Implement add(a, b)"))
Output
attempt 1: FAIL - add(2, 3) returned -1, expected 5
attempt 2: PASS
-> open a pull request for human review

And a trigger: a GitHub Actions workflow that starts the loop every night (the agent step would call your agent with the task list):

.github/workflows/nightly-agent.yml
name: nightly-fix-flaky-tests
on:
  schedule:
    - cron: "0 2 * * *"          # every day at 02:00 UTC
  workflow_dispatch: {}          # also allow manual runs
jobs:
  loop:
    runs-on: ubuntu-latest
    timeout-minutes: 60          # hard time budget for the whole loop
    steps:
      - uses: actions/checkout@v4
      - run: python scripts/agent_loop.py --task flaky-tests --max-attempts 4 --max-cost-usd 5
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

A real example

Example

Dependency updates on autopilot

A platform team spent half a day a week on dependency updates across 40 services. They built a loop: every Monday a trigger lists outdated dependencies per service; for each, a coding agent updates the version, fixes compile errors and breaking API changes, and runs the test suite (the checker); on green it opens a pull request labelled "agent-update" with a summary; on red after four attempts it opens an issue with the failure log instead. Budgets: 30 minutes and $3 per service.

Humans now spend about an hour a week reviewing PRs. Around 85% merge with no changes; the rest are fixed or closed. The loop's dashboard (runs, pass rate, cost, failure reasons) told them which services needed better tests.

The easy way

Start here

Pick one boring, verifiable chore (fix lint errors, update a dependency, add missing docstrings). Script it: a trigger (manual first, then a schedule), one agent call with a clear task, your test or lint command as the checker, a max of three attempts, and a pull request as the output. Review the first ten PRs carefully before trusting it.

When you grow: the production setup

Teams run loops on hosted agent platforms or CI with: task queues and dedupe, sandboxed harnesses with least privilege, layered checkers (tests, linters, evals, a reviewer agent), per-run and per-day budgets, state about past attempts, human gates on every output, kill switches, and dashboards. They grow loops gradually: start with read-only or reversible tasks, measure merge rates, then expand.

Trade-offs

What you gain

  • Agents do repetitive, verifiable work continuously without someone prompting them.
  • Machine checks catch most bad outputs before people see them.
  • Engineers spend time on design and review rather than step-by-step supervision.

What it costs you

  • Needs good verifiers; without tests, loops just produce plausible mistakes faster.
  • Cost and noise can grow quickly (many runs, many PRs).
  • Security risk: unattended agents with write access need strict sandboxes and gates.

When not to use it

  • Tasks without a machine-checkable definition of done.
  • Work where a wrong result is costly and can't be caught before it takes effect.

Common mistakes

  • Loops with no attempt cap or budget.
  • The maker grading its own work instead of an independent checker.
  • Auto-merging without a human gate, on day one.
  • No dedupe, so the same event starts several runs on the same task.
  • No dashboard, so failing or expensive loops go unnoticed.

Interview questions

Try answering out loud first, then open the model answer.

What is loop engineering and how does it relate to harness engineering?

Model answer

Loop engineering designs the automated control structures that repeatedly run agents: triggers (schedules, events, queues), task sourcing, machine-checkable verification, stop conditions, budgets, human gates, state and observability. Harness engineering designs the environment of a single agent run (instructions, tools, permissions, hooks, context). Loops run harnessed agents; a good loop needs a good harness and a good verifier.

Design a maker-checker loop for fixing failing tests.

Model answer

Trigger on CI failure on the main branch or nightly. Task: the failing test names and logs. Maker: a coding agent in a sandboxed checkout with file, shell and test tools, instructions from AGENTS.md. Checker: rerun the failing tests and the full suite, linters and type checks; optionally a reviewer agent for scope. Loop up to N attempts with the checker's output as feedback, bounded by time and cost. On pass, open a PR with a summary for human review; on failure, file an issue with findings. Dedupe per test, log and dashboard everything.

How do you keep long-running autonomous agents on track?

Model answer

Externalise state: a plan and progress file or checkpointed state recording completed steps, decisions and next actions; work in small increments with frequent verification and commits; manage context with compaction and sub-agents; enforce budgets and stop conditions; report progress; resume from saved state after interruptions; and end at a human review gate.

Quiz

Pick an answer to see whether it’s right and why.

  1. 01What is loop engineering?
  2. 02In a maker-checker loop, what makes a good checker?
  3. 03Which is a good trigger for an automated agent loop?
  4. 04Why must each loop run have a machine-checkable stop condition?
  5. 05What should a long-running autonomous agent keep to survive many hours of work?
  6. 06Where do humans fit in a well-designed loop?

0 of 6 answered

Key terms

Loop engineering
Designing automated loops around agents (triggers, verifiers, stop conditions, budgets, human gates) so they do repeated work without step-by-step prompting.
Maker-checker loop
One agent produces work and an independent checker (tests, linters, evals or another agent) verifies it, repeating until it passes or a limit is hit.
Scheduled agent run
An agent task started automatically by a schedule (like nightly) or an event (like a failed build), rather than by a person.
Stop condition
A rule that ends an agent loop, such as a final answer, a maximum number of steps, a token or time budget, or an error.
Harness engineering
Designing the system around a model that makes it a reliable agent, including instructions, tools, context, permissions, hooks, verification, state and tracing.

Before and after

Progress is saved in this browser only.