Handbook~18 min readIntermediate
Deep Dive

Stop prompting.
Design the loop.

In June 2026 a single idea reorganized how engineers talk about working with AI agents: stop typing prompts, and start building the system that prompts the agent for you. This is the field guide to loop engineering — the loop types, the building blocks, the stopping conditions, and the ways loops fail expensively when you skip them.

01

From prompting to loops

Loop engineering is the practice of designing the system that runs your AI agent in a repeating cycle — find work, do it, verify it, record it, repeat — instead of prompting the agent by hand each step. You stop being the person who types the next instruction and become the person who designs the machine that decides what the next instruction is.

"You shouldn't be prompting coding agents anymore. You should be designing loops that prompt your agents."

Peter Steinberger

"I don't prompt Claude anymore. I have loops running that prompt Claude and figure out what to do. My job is to write loops."

Boris Cherny — creator of Claude Code, Anthropic

The term went mainstream in June 2026 when Addy Osmani synthesized these ideas into a named discipline, and the framing stuck because it describes a real shift already underway: the folk version had existed for a year as the "run the agent in a while true loop" trick, and every serious agent team had independently invented pieces of it. Naming it made it designable.

The cleanest way to place it is as the third rung of a ladder, where each level contains the one below:

The abstraction ladder
L1Prompt engineeringShape one request — wording, examples, output format. Scope: a single model call.
L2Context engineeringShape everything the model sees for a task — instructions, files, tools, retrieved memory. Scope: a single agent run.
L3Loop engineeringShape the system that decides when the agent runs, what task it gets, how output is verified, and when it stops. Scope: work that continues without you.
Each level contains the one below it. A loop frames context; context frames prompts.
→ Mental model

Prompting an agent is adjusting the heater by hand every hour. Loop engineering is installing the thermostat — you encode the goal and the check, and the system does the adjusting. The skill moves from operating to designing.

02

The two loops — inner and outer

The word "loop" is doing double duty here, and separating the two meanings is the key to the whole discipline. The inner loop is the agent loop itself — plan → act → observe — the ReAct-style cycle inside every harness, where the model thinks, calls a tool, reads the result, and thinks again. That loop is largely built for you by whoever ships your agent.

The outer loop is the one you engineer. It wraps the entire agent run as a single step inside a bigger cycle:

The outer loop — what loop engineering actually designs
TriggerA schedule, an event, or a heartbeat decides it's time to run.
FrameThe loop assembles the task: reads state, picks the next item of work, loads the right skills and context.
RunThe agent executes its whole inner loop — plan, act, observe — until it produces a result.
VerifySomething other than the agent checks the result: tests, lint, a reviewer subagent.
RecordState is written down outside the model — what was done, what's next — so the next run remembers.
↑ repeat until the stopping condition is met — then stop
StopA verifiable condition (or a hard cap) ends the loop; leftovers surface to a human inbox.
The agent's entire run is one box. Everything around the box is loop engineering.

Every design decision in this handbook lives in one of those five outer stages. If your mental model of "agent" stops at the inner loop, the rest of this page is the missing half.

→ Run it yourself

Both loops are easier felt than read. The Agent Loop Simulator lets you step through the inner loop and watch the context window fill and compact. Then the Loop Designer puts you in charge of the outer loop: toggle the guards, run an unattended migration, and watch the failure modes below fire live.

03

The four loop types

Outer loops come in four shapes, distinguished by what triggers them and what stops them. Choosing the right shape is the first real design decision — most bad loops are a goal problem forced into a heartbeat shape, or vice versa.

TypeFiresGood forStops when
HeartbeatContinuously, on a short interval (seconds–minutes)Monitoring logs, watching queues, service health triageNever — it's killed, paused, or budget-capped
CronOn a schedule (daily 7am, weekly Monday)Nightly code review, dependency audits, morning triage reportsEach run ends when its batch completes
HookOn an event — PR push, CI failure, Slack messageReactive work: fix the failing build, review the new PROnce per event, when the response is done
GoalRepeatedly, until a success condition is metMigrations, refactors, "make all tests pass" — unknown scopeThe condition verifies true — or a hard iteration cap trips

They compose. A mature setup is usually a cron loop that discovers work, hook loops that react to events, and goal loops spawned per work item — each with its own stopping rule. The goal loop is the most powerful and the most dangerous: it's the only one whose natural state is "keep going," which is why it gets its own section on stopping conditions below.

04

The six building blocks

Across tools, working loops converge on the same six components. Five are primitives you configure; the sixth is a discipline you maintain.

BlockWhat it doesWithout it
AutomationsScheduled or triggered runs that find work — triage CI, scan issues, audit deps — and feed a triage inboxYou remain the task dispatcher
WorktreesIsolated git working directories so parallel agents never collide on filesTwo agents edit one file; both branches break
SkillsCodified project knowledge in version-controlled instruction files, loaded on demandYou re-explain conventions every run — "intent debt"
Connectors (MCP)Standardized access to external systems — issue trackers, DBs, Slack — so loops can open PRs and update ticketsThe loop can think but not touch anything
SubagentsSeparate agents (fresh context, sometimes different models) that split implementing from verifyingThe model grades its own homework
External memoryA markdown board, state file, or tracker outside the context window recording done/nextEvery run starts from amnesia and repeats work

The same blocks exist under different names in every major harness:

The same primitives, two implementations

Claude Code

  • /loop, scheduled agents (cron), hooks, GitHub Actions
  • git worktree / worktree isolation per agent
  • SKILL.md files, auto- or explicitly invoked
  • MCP servers + plugins
  • Subagents in .claude/agents/, agent teams

Codex app

  • Automations tab (project + prompt + cadence), /goal run-until-done
  • Built-in worktree per thread
  • SKILL.md invoked with $name
  • MCP + plugins
  • Subagents as TOML in .codex/agents/
Convergent evolution: automations, isolation, codified knowledge, connectors, verification split, memory.

The pattern to internalize: discovery (automations find work), isolation (worktrees keep parallel work safe), knowledge (skills stop you re-explaining), reach (connectors let it act), judgement (subagents verify), memory (state survives the run). Miss one and the loop leaks — usually money.

05

Stopping conditions & verification

The hardest part of a loop is not making it run. It's making it stop — correctly, and for the right reason.

A loop's stopping condition must be checked by machinery, not judged by the model. "The refactor looks complete" is a judgement; 0 failing tests && 0 lint errors is a condition. Models are systematically overconfident about their own completions, so a loop that lets the agent declare victory will terminate early on plausible-looking work — and a loop with no condition at all simply never stops.

Layer three guards, in order of bluntness:

GuardWhat it isCatches
Hard capsmax_iterations, wall-clock limit, token budgetRunaway loops, oscillation, cost blowups
Verifiable conditionsTests green, build passes, zero diff on re-run, metric under thresholdEarly stopping on unfinished work
Independent verificationA separate verifier — test suite, reviewer subagent, different model — judges the outputConfident, wrong, "done"

The third guard is the architectural pattern worth naming: the verification split. The agent that wrote the change must not be the agent that approves it — the same failure of incentives as a developer reviewing their own PR, except the model fails it more reliably. In practice: one subagent implements in a worktree, a second subagent with fresh context reviews against the project's skills and runs the tests, and only a pass releases the work downstream. Evaluating agent output rigorously is its own discipline — the Agent Evals handbook covers it.

→ Key insight

A loop without a verifier is a machine for shipping plausible mistakes at scale. Everything a loop produces must pass a gate that can fail — if the result can't be measured, the loop treats it as a failure, not a pass.

06

State across runs

Models forget everything between runs. The loop can't. External memory — state kept outside the context window — is what turns a series of isolated agent runs into a system that makes progress. Without it you get state amnesia: the Monday run re-fixes what Friday's run fixed, the migration loop re-converts the same ten files, and iteration count stops correlating with progress.

Where loops keep state

Lightweight — start here

  • A markdown board in the repo: done / in-progress / next
  • A JSON checkpoint file the loop reads first, writes last
  • Git itself — branches, commit messages, tags as progress markers

Heavier — when loops multiply

  • An issue tracker (Linear, GitHub Issues) as the shared work queue
  • A database when state outgrows files
  • A triage inbox where unhandled findings await a human

Two rules make state trustworthy. First, the loop reads state before framing the task and writes state after verification — never mid-run, so a crashed run can't record work it didn't finish. Second, state records facts, not vibes: "converted auth/session.ts, tests pass" is replayable; "made good progress on auth" is amnesia with extra steps. A resume-point convention — one line saying exactly where the next run picks up — is the cheapest reliability upgrade a loop can get.

07

Cost engineering

Loops multiply whatever they touch — including your bill. A manual prompt costs one conversation; a heartbeat loop with a verifier subagent is dozens of model calls an hour, all day, whether or not there's work to do. A goal loop with no iteration cap can burn hundreds of dollars in an hour while making no progress at all. Cost isn't a footnote to loop engineering; it's a design axis.

Three levers, roughly in order of impact:

LeverHow it worksTypical saving
Model routingMatch model tier to step difficulty: small fast models for classification and scanning, mid-tier for drafting and summarizing, frontier models only for review and decisions60–80% on token spend
Prompt cachingLoops re-send the same system prompt, skills, and repo context every iteration — exactly the shape caching rewards40–90% on input tokens
Doing lessHook loops instead of heartbeats where events exist; cheap pre-checks ("anything new since last run?") that skip the expensive agent entirelyOften the biggest of all

And put a budget ceiling on every loop as a hard cap, not a dashboard you check later. A loop that stops at its budget is an inconvenience; a loop you discover on the invoice is a story you tell at conferences.

→ Worth knowing

The steady state to aim for: cheap models watch, expensive models act, and the most expensive model only ever reviews. If your frontier model is doing the scanning, the routing is upside down.

08

Failure modes & guardrails

Loops fail differently from prompts. A bad prompt wastes a reply; a bad loop compounds — all night, at full spend, in your repo.

The six ways loops break — and the guard for each

Token runaway

A goal loop with no cap iterates forever on an unachievable condition, burning budget while producing nothing.

Guard: max_iterations + token budget as hard stops, alert on trip.

State amnesia

No external memory, so each run repeats prior work; the loop is busy but not progressing.

Guard: checkpoint file or board, read-first write-last, resume-point line.

Overconfident termination

The agent declares the goal met; it isn't. The loop exits on plausible-looking output.

Guard: verifiable stop conditions; a verifier that isn't the implementer.

Context degradation

Long runs fill the window; compaction eats the constraints and quality decays mid-loop.

Guard: fresh subagent per work item instead of one marathon context.

Silent quality drift

Each iteration passes review in isolation while the codebase slowly accretes mediocrity nobody approved.

Guard: periodic human audit of merged loop output, not just per-PR gates.

Comprehension debt

The loop ships faster than you read; six weeks in, nobody on the team understands the code they own.

Guard: read what merges; keep loop throughput inside human review bandwidth.

The last two failures are human, not technical, and they're the ones Osmani's write-up dwells on. Orchestration tax is the ceiling loops eventually hit: not model capability, but your bandwidth to review what they produce — parallelism past that point manufactures unreviewed changes. And cognitive surrender is the failure past the ceiling: you stop having opinions about the output entirely. The same loop produces opposite results for an engineer who understands the system deeply and one who has delegated the understanding itself.

→ Key insight

Loops automate the prompting, not the responsibility. Verification stays yours, understanding stays yours, and design intent stays yours — the loop just stops you being the keyboard.

09

Design your first loop

Theory compresses into a worked example. Here is the reference architecture — a nightly triage-and-fix loop, the "hello world" of loop engineering — using every block from section 04:

Reference loop — nightly triage and fix
1 · Cron7am automation runs a triage skill over CI failures, open issues, and recent commits.
2 · BoardFindings land on a markdown board (or Linear) — the loop's external memory.
3 · BuildFor each actionable finding, a builder subagent drafts a fix in its own isolated worktree.
4 · VerifyA reviewer subagent with fresh context checks the draft against project skills and runs the tests.
5 · ShipMCP connectors open the PR and update the ticket; only verified work gets this far.
6 · InboxAnything unhandled surfaces in a triage inbox for a human decision.
7 · RecordThe state file records what shipped and what's next — tomorrow's run picks up exactly there.
Discovery → memory → isolated build → independent verify → ship → human escape hatch → state.

And because a loop is ultimately just code, here is the entire idea in one runnable file — a goal loop for a migration, with all three guards and both state rules from section 06. Swap the claude -p line for any agent harness you use:

import json, subprocess, sys

MAX_ITERATIONS = 8                      # guard 1 — hard cap
STATE_FILE = "loop-state.json"          # external memory

def load_state():
    try:
        return json.load(open(STATE_FILE))
    except FileNotFoundError:
        return {"queue": ["auth/session.py", "auth/token.py"], "done": []}

def verified():                         # guard 2 — checked by machinery, not the model
    return subprocess.run(["pytest", "-q"]).returncode == 0

def run_agent(task):                    # the whole inner loop is this one box
    subprocess.run(["claude", "-p", task])

for i in range(MAX_ITERATIONS):
    state = load_state()                # read state BEFORE framing the task
    if not state["queue"]:
        print("goal met"); sys.exit(0)  # verifiable stopping condition
    target = state["queue"][0]
    run_agent(f"Migrate {target} to the new session API. Done so far: {state['done']}")
    if verified():                      # guard 3 — verifier is not the implementer
        state["done"].append(state["queue"].pop(0))
        json.dump(state, open(STATE_FILE, "w"))   # write state AFTER verification
    # on failure: state untouched — the next iteration retries the same target

print("cap hit with work remaining — escalate to a human")  # end loudly, never silently

Thirty lines, and every concept in this handbook is present: the cap, the condition, the verification split (pytest judges, not the agent), read-first/write-last state, facts-not-vibes checkpoints, and a loud ending. Production loops grow worktrees, subagents, and connectors around this skeleton — they never replace it.

How to actually start, without the fleet:

Pick one recurring chore you already do — triaging CI failures, dependency bumps, flaky-test hunting. Boring and frequent beats impressive and rare. Write the skill first: the conventions you'd explain to a new teammate go in a version-controlled instruction file, because an outer loop is only as good as the context it frames (that's the L2 layer doing its job inside L3). Give it the three guards from section 05 — a cap, a condition, a verifier — before its first unattended run, not after its first incident. Run it supervised for a week, reading everything it produces; you're calibrating trust, and you'll usually fix the skill file three times in the first five runs. Then schedule it and add the next loop only when reviewing this one costs you almost nothing.

One well-guarded loop that runs every night is worth more than five clever ones you had to turn off. The engineers getting leverage from this aren't the ones with the most agents — they're the ones whose loops they can stop thinking about.

10

A production loop, dissected

This isn't theory to us. The videos on the Vibe Engines YouTube channel are built, quality-gated, and uploaded by an autonomous loop. Here's its anatomy, mapped to everything above.

ConceptHow our video pipeline implements it
Trigger (cron)A scheduled system job kicks off a batch builder — deliberately not a terminal session, because a loop that dies when a laptop sleeps isn't a loop
Hard capsAn 11-hour wall-clock budget per batch, plus a queue governor that stops building when 6 videos are waiting to upload — production ahead of review is waste, not progress
Verification splitA 16-gate ship-gate scorecard judges every video before upload — motion checks on rendered frames, story-structure checks on the script, an LLM judge fact-checking the narration, a writing-craft scorer. The builder never grades itself, and unmeasurable means fail
External memoryA tracker file with a RESUME POINT block — every run reads it before framing work and rewrites it after shipping, so a crashed batch resumes exactly where it stopped, not where it guesses
Hook loopWhen the platform's daily upload cap clears, a paced drainer publishes the pending queue one per hour instead of dumping it
Human escape hatchA gate failure parks the video for review with its scorecard attached. Nothing ships on a red gate; nothing fails silently

The instructive part is why each guard exists — every one was added after its absence hurt. The ship-gate exists because early videos degraded quietly: each looked fine in isolation while the batch drifted mediocre — silent quality drift, caught only by a human audit. The queue governor exists because building faster than the upload cap just manufactured a warehouse. And the resume-point convention exists because the first crashed batch re-rendered work it had already finished — state amnesia, paid for in GPU-hours.

→ The honest summary

Every failure mode in section 08 showed up in this pipeline before its guard did. Loop engineering is mostly the discipline of installing the guard before the incident instead of after — this page exists so you can skip our invoices.

Frequently asked

Quick answers

What is loop engineering?

Designing the system that prompts your agent instead of prompting it yourself: a trigger, task framing, verification, external state, and an explicit stopping condition. Popularized in June 2026 by Addy Osmani, building on Peter Steinberger and Boris Cherny.

Loop engineering vs prompt / context engineering?

Prompt engineering shapes one request; context engineering shapes everything one run sees; loop engineering shapes the repeating system around runs — when the agent fires, what it works on, how output is checked, when it stops. Each level contains the one below.

What are the four loop types?

Heartbeat (continuous interval — monitoring), cron (scheduled — nightly reviews), hook (event-triggered — CI failure, PR push), and goal (iterate until a verifiable condition — migrations). Goal loops always need a hard iteration cap.

How do you stop a loop running forever?

Three layered guards: hard caps (max iterations, budget), verifiable conditions (tests green, zero lint errors), and independent verification — a test suite or second agent, never the implementer judging its own work.

What tools support loops today?

Claude Code (/loop, scheduled agents, hooks, subagents, skills, worktrees, MCP), the Codex app (automations, /goal, per-thread worktrees, skills, MCP), and GitHub Actions as trigger and runtime. The primitives are converging.

The Loop Engineering Handbook · Vibe Engines · 2026
Finished this one? 0 / 30 Handbooks done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.