Loop Engineering
Running agents without being the keyboard — loop types, guards, building blocks, and failure modes on one page.
Loop engineering is designing the system around agent runs instead of steering each run by hand: when a run fires, what context it gets, how its output is checked and what stops it. The rows assume one principle. A loop multiplies whatever it wraps, so a flaw that costs one bad answer in a chat costs hundreds when it runs unattended.
That is why every loop type below needs stop guards a machine can evaluate, state kept outside the context window, and a human review rate that keeps pace with what the loop produces.
The ladder
- L1 Prompt engineering
- Shape one request — a single model call
- L2 Context engineering
- Shape everything one run sees — instructions, files, tools, memory
- L3 Loop engineering
- Shape the system around runs — when it fires, what it gets, how it’s checked, when it stops
- Climb in order
- move up a level only once the one below is solid — a loop amplifies a weak prompt
Four loop types
- Heartbeat
- Fires continuously on an interval · monitoring, triage · stops only by kill/budget
- Cron
- Fires on a schedule · nightly reviews, audits · each run ends with its batch
- Hook
- Fires on an event (PR push, CI fail) · reactive work · once per event
- Goal
- Iterates until a verifiable condition · migrations, refactors · always cap it
- Choosing one
- react to change → hook; regular sweep → cron; open-ended job → goal with caps
Stop guards
- Hard caps
max_iterations, wall-clock, token budget — catches runaways- Verifiable conditions
- Tests green, build passes, zero diff — machinery, not model judgment
- Independent verification
- Verifier ≠ implementer: test suite or reviewer subagent
- All three together
- caps catch runaways, conditions define done, verification catches a false done
- Kill switch
- one flag that halts every loop at once — test it before you need it
Six building blocks
- Automations
- Scheduled/triggered runs that find work
- Worktrees
- Isolated git dirs — parallel agents never collide
- Skills
- Codified conventions in version-controlled files
- Connectors (MCP)
- Reach: PRs, tickets, Slack, DBs
- Subagents
- Fresh-context verification split
- External memory
- Board/checkpoint outside the window — read first, write last
Failure modes → guards
- Token runaway
- Hard caps + budget, alert on trip
- State amnesia
- Checkpoint file, resume-point line, facts not vibes
- Overconfident termination
- Verifiable stop conditions + verification split
- Context degradation
- Fresh subagent per work item
- Silent quality drift
- Periodic human audit of merged output
- Comprehension debt
- Read what merges; throughput ≤ review bandwidth
- Duplicate work
- two runs claim the same item — claim atomically or lock it on the board
- Permission creep
- loops collect broad tool grants over time — audit what each one can touch
- Cascading failures
- one loop’s bad output feeds the next — validate at every hand-off
Cost levers
- Model routing
- Cheap watches, expensive acts, priciest only reviews · saves 60–80%
- Prompt caching
- Stable system prompt + skills re-sent each turn · saves 40–90% input
- Doing less
- Hooks over heartbeats; cheap pre-checks skip the agent entirely
- Batch APIs
- non-urgent runs through Anthropic’s or OpenAI’s batch API cost half the price
- Fresh context per item
- small, focused calls instead of one ever-growing conversation
Checkpoint file anatomy
- Goal line
- one sentence saying what done means, re-read at the start of every run
- Done · remaining
- finished and pending items as facts with IDs, never a vague summary
- Resume point
- the exact next action, written last so a crashed run restarts there
- Decisions
- choices made and why, so later runs don’t reopen them
- Budget used
- iterations and spend so far, checked against the caps before each run
Before you automate
- Trigger?
- what event or schedule starts a run — and what ends one
- Done condition?
- how a machine can tell the run succeeded without asking the model
- Worst case?
- the most damaging thing the loop could do, and what prevents it
- Who reviews?
- which human reads the output, how often, and at what volume
Vocabulary
- Verification split
- Generation and review are separate agents
- Intent debt
- Re-explaining context every run instead of writing skills
- Orchestration tax
- Ceiling = human review bandwidth, not model capability
- Cognitive surrender
- No longer having opinions about loop output
- Blast radius
- everything a loop could change if it goes wrong — shrink it before scaling up
- Human on the loop
- people review outcomes and samples rather than every step
- Idempotent run
- running twice on the same input leaves the same result, so retries are safe
Worked example: a CI-failure triage loop, end to end
Goal: when a test fails on main, a pull request with a proposed fix is waiting before anyone looks. It is a hook loop, because the work arrives as events.
- Trigger. The CI system calls a webhook when a job on
mainfails. Events caused by the loop’s own bot account are ignored, so its pushes cannot re-trigger it. - Pre-check, no model. A script compares the failing test with a list of known flaky tests and with open fix PRs. A match ends the run at zero model cost.
- Claim. The script marks the board entry for that test as claimed by this run in one atomic update. A second event for the same failure sees the claim and exits.
- Agent run. A fresh agent in its own worktree gets the failing log, the test file and the checkpoint. Its tools: read, search, edit, and run that one test. No push, no network.
- Verify. The harness, not the agent, runs the test three times and the full suite once. A reviewer subagent with fresh context reads the diff against the log and answers approve or reject.
- Output. On approval the harness opens a draft PR labelled
bot-fix. On rejection it writes the reviewer’s reason into the checkpoint, and the next attempt starts from there. - Caps. 3 attempts per failure, 20 minutes per attempt, 10 runs a day. Hitting any cap posts the checkpoint to the team channel.
Suppose a week brings 30 failures and the pre-check filters out 18 as flaky or already being fixed. Only 12 failures reach a model, and at most 12 draft PRs reach the reviewer. At 15 minutes per careful review that is 3 hours, which has to fit in someone’s week before any cap goes up.
Notice what the agent never does: decide whether there is work, mark its own work as passing, or merge. Each of those is a script or a person, which is what makes the loop safe to leave running.
Recipes
A capped goal loop with all three stop guards
for i in range(MAX_ITERATIONS): # hard cap
state = read("checkpoint.md") # read first
run_agent(task, context=state)
if tests_pass() and diff_is_clean(): # verifiable condition
verdict = reviewer_agent(diff()) # independent verification
if verdict.approved:
write("checkpoint.md", "DONE")
break
write("checkpoint.md", progress()) # write last
else:
alert("cap hit", read("checkpoint.md"))The cap, the machine-checked condition and a reviewer that did not write the code each stop a different failure. The for … else branch runs only when the cap is hit.
A nightly dependency-update loop (cron)
Trigger: cron, 02:00 daily
Find work: list outdated packages with a script (no model call)
Skip: nothing outdated → exit before any model runs
Per item: fresh subagent in its own worktree bumps one package, runs tests
Verify: CI green, plus a reviewer subagent reads the changelog for breaking changes
Output: one PR per package, labeled for human review
Caps: at most 5 PRs a night, 30 minutes per item, a daily token budgetThe cheap pre-check means most nights cost nothing, and one worktree per item stops a bad upgrade from contaminating the next.
A checkpoint file a run can resume from
# checkpoint.md
Goal: migrate all 42 API handlers from callbacks to async/await
Done: 17/42 (see list below)
Remaining: 25 — next is src/handlers/refunds.js
Resume point: rerun tests for refunds.js after the last edit
Decisions: keep error codes unchanged; wrap legacy calls with promisify
Budget used: iteration 9 of 30, about $4.10 of $15Counts, file names and the exact next action rather than impressions, so a run that crashes midway loses at most one item of work.
Review bandwidth math (worked example)
Loop output: 40 PRs per week
Careful review: ~15 min each → 10 hours per week
Reviewer capacity: 4 hours per week
Sustainable rate: 4 h ÷ 15 min = 16 PRs per week
Decision: cap the loop at 16, or raise what each PR must proveThroughput has to stay at or below review bandwidth; past that point, merged code nobody read turns into comprehension debt.
When to use it, and when not
Build a loop when the same kind of work keeps arriving, a machine can tell a good result from a bad one, and someone has the time to read what it produces. Dependency bumps, flaky-test triage, lint and type fixes, doc drift, and migrations backed by a test suite all qualify.
Stay with an interactive session when:
- the task happens once, so the loop costs more to build than the work does by hand;
- done is a matter of taste (naming, product copy, architecture) with no check a script can run;
- a wrong action is expensive and cannot be reversed: deleting data, messaging customers, changing production config;
- you cannot yet do the task reliably in a single run. A loop repeats the failure rate; it does not fix it.
Start a new loop as a suggestion engine that only drafts PRs or comments, and grant it more only after its output has a track record.
Trade-offs and limits
Loop types trade reaction time against how often the loop runs, and so against what it costs when there is nothing to do.
| Type | Runs per day | Reacts in | Idle cost | Main risk |
|---|---|---|---|---|
| Heartbeat, every 5 min | 288 | up to 5 min | every run, unless a pre-check exits first | spending while nothing happens |
| Cron, nightly | 1 | up to a day | one run | work waits; one bad batch is large |
| Hook | one per event | seconds | none | event storms, triggering itself |
| Goal | until done or capped | not applicable | none | never converging |
Two limits do not move with better models. Review bandwidth caps useful throughput, and every tool you grant widens the blast radius of a bad run. A loop that saves an hour of typing but adds an hour of careful review has saved nothing.
Common mistakes
- A hook loop that triggers itself. The loop fixes lint and pushes; the push fires the hook; the hook runs the loop again. Ignore events caused by the loop’s own account, and cap runs per day as well as per event.
- Calling the model to learn there is no work. If a script can see the queue is empty, the model should never run. Most nights of a well-built cron loop cost nothing.
- State kept in the conversation. A crash, a timeout or a compaction erases what the run knew. Anything the next run needs goes in the checkpoint file, as facts with IDs.
- Outputs that are not idempotent. A retried run opens a second PR or posts the same comment twice. Look for an existing PR or comment by a stable key before creating one.
- Caps that trip silently. A loop stopped by its budget looks exactly like a loop with nothing to do. Every cap trip should post or page, with the checkpoint attached.
- Letting the loop merge its own work. Auto-merge on green tests skips the only human check. Keep merge rights with people until the loop has a long, audited record.
Check yourself
In the capped goal-loop recipe, the reviewer approves on iteration 3 of 30. Does alert("cap hit", …) run?
No. Python runs a for loop’s else block only when the loop ends without break. Approval breaks out, so the alert fires only if all iterations pass without an approval.
A loop opens 25 PRs a week, each needs 12 minutes of careful review, and the reviewer has 3 hours a week. What weekly cap is sustainable?
180 min ÷ 12 min = 15 PRs a week. The other 10 either wait, growing a backlog, or merge unread, growing comprehension debt.
A heartbeat checks a queue every 10 minutes and each run costs $0.02 whether or not there is work. Events arrive about 8 times a day. What do a heartbeat and a hook cost per day?
Heartbeat: 144 runs × $0.02 = $2.88. Hook: 8 runs × $0.02 = $0.16. A script pre-check inside the heartbeat closes most of that gap by exiting before the model runs.
The agent reports “all tests pass”, but it had disabled two tests. Which stop guard catches this?
Independent verification: the harness runs the real suite and the reviewer reads the diff, where the disabled tests are visible. Hard caps cannot see it, and a verifiable condition alone fails too when the agent can change what the condition measures.
Questions about Loop Engineering Cheat Sheet
What is loop engineering?
Loop engineering is the practice of running AI agents as automated, repeating systems instead of one-off chats. It sits above prompt engineering, which shapes a single request, and context engineering, which shapes everything one run sees. A loop engineer decides what triggers each run, what state and tools it receives, how its result is verified, when it must stop, what it may cost and how humans review the output. The goal is agents that do useful work unattended without silently degrading quality or running up costs.
How do you stop an autonomous agent loop safely?
Layer three kinds of guard. Hard caps on iterations, wall-clock time and token or dollar budget catch runaways regardless of what the model believes. Verifiable conditions, such as tests passing, a build succeeding or an empty diff, define done in terms a machine can check. Independent verification, from a test suite or a reviewer agent that did not write the work, catches the case where the agent thinks it has finished but has not. Add a kill switch that halts every loop at once, and test it before you need it.
What is the difference between a cron loop and a hook loop?
A cron loop runs on a schedule, such as every night, and each run processes whatever work has piled up since the last one, which suits audits, reports and dependency updates. A hook loop runs in response to an event, such as a pull request being opened or a CI job failing, and handles just that event, which suits reactive work like triage and fix suggestions. Hooks usually cost less because they only run when something happens, while cron is simpler to reason about, schedule and cap.