Free mini-course · Layer 4 of 5

Loop Engineering: make iteration converge

The fourth layer. A loop is the repeated cycle — reason, act, observe, adjust — that turns a single model call into an agent. The engineering is not making it loop; it is making it converge: real feedback, honest stop conditions, and brakes that prevent confident digging in the wrong direction. Twelve lessons, from the anatomy of a loop to its economics, failure modes, and the security tax of running unattended.

promptscontextharnessloopsgraphs
LESSON 01

The anatomy of a working loop

Every agent loop has four beats: plan the next action, take it with a tool, observe the actual result, and adjust. The observation is the load-bearing part — a loop that acts without reading real environmental feedback (test output, tool results, file diffs) is just a model talking to itself with extra steps.

Do this now: Watch one agent run and label each turn P/A/O/A. Find a turn where it acted without observing — that's where loops go bad.
LESSON 02

Stop conditions are the design

“Loop until done” is not a design — “done” must be checkable: tests pass, the file exists, the diff applies, the answer cites its source. Add the other exits too: max iterations, budget cap, and a stuck detector (same error twice = stop and report). An agent without honest exits either quits early or burns money forever.

Do this now: For your next agent task, write the completion check BEFORE the prompt: the command or condition that proves it worked. Give the agent that check.
LESSON 03

Evidence beats self-report

Models grade their own work kindly — measured self-preference bias runs 10–25%. So never accept “I'm done” as the loop's exit. The loop should prove completion with evidence it can't fabricate: run the tests, execute the code, fetch the URL it claims exists. Define success as a verifiable state of the world, not a sentence from the model.

Do this now: Add one line to your agent instructions: “Before declaring done, run the verification and paste its output.” Refuse done-claims without the paste.
LESSON 04

Bounded repair: iterate without spiraling

When verification fails, loop back — but with a budget. Two or three repair attempts, each required to change approach (not retry the same edit harder), then stop and escalate to a human with a clear report. Unbounded self-repair is how agents dig confident holes; a circuit breaker converts failure into a good question.

Do this now: Give your agent this rule: “3 fix attempts max; each must state what it's doing differently; then stop and summarize what you tried.” Compare with the unbounded version.
LESSON 05

When one loop isn’t enough

Some work outgrows a single loop: independent subtasks that could run in parallel, verification that needs fresh eyes, steps that need different models. Chaining more instructions into one loop makes it slower and blinder. That coordination problem — which loops run, in what order, who checks whom — is the graph layer, and it's a different discipline.

Do this now: Take your most overloaded agent prompt and split it on paper into 3 boxes: what's independent, what must be sequential, what needs a fresh-context check. You just drew your first graph.
LESSON 06

Should this even be a loop? The four-question test

A loop has setup cost, so it must earn its existence. Four questions decide: Does the task repeat? One-off work is faster as a manual prompt. Can the result be verified automatically? Tests, builds, rubrics, or a measurable condition — if only a human can reject bad output, the human is still the real verifier. Can the agent act end-to-end? If it needs permission every two minutes, it’s assisted manual work, not a loop. Is “done” objective? “Tests pass” is objective; “feels good” is not. Miss any one → keep it manual. And some things should never be first loops: payments, auth, production deploys, architecture rewrites, anything where done is a judgment call.

Do this now: List three tasks you’re tempted to automate. Run each through the four questions. Expect at most one to qualify — that one is your first loop.
LESSON 07

The six building blocks — and why state lives outside the model

A working loop is a system of six parts: a trigger (schedule, event, or condition — without it the loop only runs when you remember), reusable context (so runs don’t start cold), real action (“I did it and checked it”, not “here’s what I would do”), a verification gate that bad work can actually fail, external state, and a stop rule with both a success stop and a failure stop. The one most people skip is state: the model forgets, the file does not. What was tried, what failed, what passed, what to avoid — written to a notes file, an issue, or a log. If the loop doesn’t write state somewhere, every run starts from zero. No gate, no loop; no state, no learning.

Do this now: Draw your candidate loop as six labeled boxes. If the state box is empty, add a NOTES.md the loop must update and re-read every run — then re-draw.
LESSON 08

The economics: cost per accepted result and comprehension debt

Loops are not free, and they don’t fail loudly — they fail quietly, confidently, while spending. Each iteration re-carries the task, the state, and every previous failure, so the context and the bill compound. The metric that matters is not how many loops ran; it is cost per accepted result. A loop that opens five PRs of which you merge one may cost more than doing the work by hand — and a soft verifier converts token spend into review debt. The second bill is comprehension debt: when agent output lands faster than humans read it, the system works but nobody knows why. The fixes are limits, not abstinence: read the diffs, keep loops on small tasks, use gates that can fail, block sensitive areas, and never automate the judgment calls.

Do this now: For one running (or planned) loop, compute cost per accepted result: total tokens ÷ outputs you actually kept. If acceptance is under 50%, tighten the verifier before you scale anything.
LESSON 09

Report-only first: the autonomy ramp

Production loops are not switched on — they are promoted. The ladder runs L0 (not loop-ready) to L3 (autonomous with evidence), and each rung is earned: week one the loop only reports — it scans CI, issues, and commits and writes what it would do into a state file. Only after its judgment proves out does it graduate to small auto-wins, then to gated writes. And readiness is auditable, not vibes: does a state file exist, is there a verifier separate from the maker, are token budgets capped in a file, is there a run log with real timestamps? The top rung requires all four — verifier, durable state, cost observability, and proven run history. If you cannot score your loop, it is not ready to run unattended.

Do this now: Take one loop you want to automate and run it report-only for a week: every cycle appends what it would have done to a state file. Promote it only when a week of proposals is a week you would have approved.
LESSON 10

Verifier theater, infinite fixes, token burn

Three failure modes kill production loops. Infinite fix loops: the agent retries the same failing fix forever — the cure is a hard attempt cap (three is common) with a named escalation path. Verifier theater: a checker that always passes is worse than none, because it launders bad work as verified — the verifier must be able to fail, which means deterministic tests and policy gates, a separate context from the maker, and occasionally proving it still rejects a known-bad input. Token burn: an unbounded loop is a cost leak — budgets live in a file the loop reads, spend is logged per run, and budget-exceeded is a stop condition, not a warning. The safety rails around all three: a path denylist for what the loop may never touch, an explicit auto-merge policy, and least-privilege connectors.

Do this now: Feed your verifier one input you know is wrong. If it passes, you have verifier theater — fix the checker before the next run, because every green light it has ever given is now suspect.
LESSON 11

Should you even build this loop? The economics

The honest answer most roadmaps skip: loops favor whoever can spend. They pay off for teams with repetitive, machine-checkable work, strong test suites, and a budget that can absorb retries and re-reads. They are reckless for solo builders on metered consumer plans — the token bill arrives before the productivity gain — and useless for teams whose real bottleneck is review capacity: a loop generates more code, so it just makes the queue longer. Before building, run the 30-second check: the task recurs at least weekly; an automated gate (test, build, linter) can reject bad output; the agent can run what it changes; there is a hard stop (budget, attempts, or time); a human approves anything irreversible. Good first loops: CI-failure triage, dependency bumps, lint-and-fix, flaky-test reproduction. Bad first loops: architecture, auth or payments code, deploys, anything where “done” is a judgment call.

Do this now: Run the five-box check on the loop you most want to build. Miss one box and keep it as a manual prompt — for one-off or judgment work, a single well-aimed prompt still wins.
LESSON 12

The Ralph Wiggum loop, and the security tax

Geoffrey Huntley named the quietest failure: the Ralph Wiggum loop — the agent emits its completion signal early, the loop exits on a half-done job, and everything keeps spending. It happens when “done” is the agent’s opinion instead of an objective gate, and when the “verifier” is just a second agent asked to review — two optimists agreeing. The fix is a gate that can mechanically fail: a test that passes or fails, a build that compiles or doesn’t. And a loop running unattended is an attack surface running unattended: PRs merging faster than humans read them (put SAST, dependency audit, and secret scanning in the gate), community skills as injection vectors (in one audit, 520 of 17,022 skills leaked credentials — read the source before installing), secrets scattering into verbose logs, and permission scope creep — the read-only loop that gained “just one” write permission and was never re-audited. Beneath both: cognitive surrender. Designing the loop with judgment is the cure; designing it to avoid thinking is the accelerant.

Do this now: Security-audit one running loop: what can it write, which secrets can reach its logs, does its gate include a security check, and when were its permissions last reviewed? Put a 30-day re-audit on the calendar.
STARTER TEMPLATE

A self-checking loop you can run in any chat

Before automating anything, feel the shape manually. Give the model a task, explicit success criteria, and this protocol: PLAN the single next step → DO the work → VERIFY by scoring each criterion 1–10 → DECIDE: all criteria ≥8 means print FINAL and stop; otherwise print ITERATING and fix the weakest score first. Cap it at three iterations, forbid “done” until every criterion passes, and have it assume sensibly when unclear. No tools, no scheduler — just the mental shift from “answer once” to “work, check, improve, stop”.

Do this now: Run it on a real writing or coding task. Watch which criterion fails first — that criterion is your future automated verifier.
Go deeper — the sources this course is built on:
Anthropic: Building effective agents (the agent loop, evaluator-optimizer, simplicity first) · @LunarResearcher: Loop Engineering (the four-question test, six building blocks, cost per accepted result, comprehension debt — 1.3M views) · @akshay_pachaar on the loop→graph shift · @mfishbein’s software factory — loops with exams, circuit breakers and fresh reviewers · Cobus Greyling’s Loop Engineering (repo) — lessons 09–10 synthesize its L0–L3 autonomy ramp, report-only-first adoption, Loop Ready audit, and failure-mode catalog (infinite fix loops, verifier theater, token burn) · @0xCodez’s 9.3M-view “Loop engineering: 14-step roadmap” — lessons 11–12 synthesize its loop economics, the Ralph Wiggum failure mode, and the security tax