Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Loop Engineering: From ReAct to Autonomous Agent Loop Design

This article traces the evolution of AI agent design from ReAct to Loop Engineering, detailing its five core primitives (trigger, goal, actions, verification, memory), verification strategies, termination safeguards, context management techniques, and a concrete example of automating CI repair, while highlighting practical principles and pitfalls.

Origin of Loop Engineering

In June 2026, developer Peter Steinberger posted "stop making prompts, start designing loops," claiming prompt engineering would become obsolete within 18 months. The post gained ~6.5 million views. A week later, Google Chrome engineering lead Addy Osmani published an article titled "Loop Engineering," structuring the scattered practices and incorporating views from Anthropic's Boris Cherny (Claude Code author) and Steinberger. The term was thus coined.

The explosion was driven by converging curves: model reliability crossed a threshold (average iterations per task dropped from 40+ to 3–5), context windows reached million-token scale (enough for entire codebases), and unit cost fell enough to sustain long loops. When the model is no longer the bottleneck, the bottleneck shifts to "how to orchestrate it" — the same focus as Harness Engineering. Cherny noted that Claude now writes over 80% of Anthropic's production code, but only after teams stopped manual line-by-line review and switched to programmatic verification loops.

One-Sentence Definition

Loop Engineering is the engineering practice of designing the iterative loop that an agent runs — deciding what it does between two tool calls, when it verifies its own output, and how it judges task completion — instead of hand-crafting every prompt.

It represents a control transfer:

Prompt Engineering asks: What should I say to get the best output?

Loop Engineering asks: What system should I build so the agent can find work, do work, verify work, remember — without me in the loop?

Human engineers only define three things: task, verification criteria, exit conditions — the loop runs all intermediate steps autonomously. (Model capability remains critical: reasoning, tool use, structured output; distilled small models may not suffice for such complex engineering.)

Position in the Technical Lineage

Industry abstraction levels for "how to collaborate with agents" have risen over two years:

Prompt Engineering — Engineering object: Text you send. Core question: How to phrase for best output?

Context Engineering — Engineering object: All information model sees. Core question: What goes in the context window?

Harness Engineering — Engineering object: Agent's runtime environment. Core question: What tools, sandboxes, permissions?

Loop Engineering — Engineering object: Iterative loop driving agent toward goal . Core question: What system lets it self-drive?

Loop Engineering does not replace the previous three; it is a higher-layer orchestration built on top of them.

Evolutionary Lineage: From ReAct to Loop Engineering

Loops themselves are not new; what's new is treating "loop design" as an independent discipline. The technical lineage:

ReAct (2022) — Foundation. Interleaves reasoning and action; each observation feeds next reasoning, allowing adjustment on unexpected results instead of blind retry. Baseline for almost all production frameworks.

Reflexion (NeurIPS 2023) — Adds self-evaluation layer and episodic memory: agent writes a verbal lesson after failure, stores in memory, retrieves for later attempts. Cost: higher compute.

Plan-and-Execute — Separates strategic planning from stepwise execution, enabling parallel independent steps and replanning when execution deviates. Achieves ~3.6× speedup over serial ReAct and significantly reduces drift.

Evaluator-Optimizer (generate-evaluate loop) — One model generates, another evaluates against standards; they iterate until pass. Prototype of later "independent verification" idea.

Inner/Outer dual loops & Orchestrator-Workers — Exemplified by Microsoft Magentic-One: outer loop does strategic planning, inner loop does tactical execution; when inner loop stalls, reset strategy entirely instead of local retry. Orchestrator-Workers formalizes: central orchestrator dynamically decomposes tasks, assigns each subtask to a worker sub-agent with its own clean context window , then aggregates results.

Loop Engineering (2026) — Converges all above into a complete design practice.

Anatomy of a Loop: Five Core Primitives

Regardless of pattern, an engineerable agent loop decomposes into five primitives:

Trigger — What starts the loop: timer, event, human command, or another agent.

Goal — A verifiable end state, not a vague purpose.

Actions — Available tools: file ops, shell, API, MCP server.

Verification — How to confirm completion: tests, CI pipeline, independent supervisor agent.

Memory — Cross-iteration persistence: session continuation, disk state files, vector store, or external DB.

Internal execution typically repeats five phases: Perceive → Reason → Plan → Act → Observe . Addy Osmani further lists a mature loop's "anatomy": automated triggers, parallel isolated worktrees, reusable skill packs, external connectors, sub-agents, and cross-run external state.

Verification: The Key to Reliable Loops

If Loop Engineering has one iron law: Always trust deterministic verifiers, never trust the agent's self-report. Verification has two tiers:

Deterministic verification (preferred) : tests, type checkers, compilers, linters. They give objective pass/fail signals the model cannot bypass or talk its way past.

LLM-as-Judge : More flexible, but can be manipulated, even collude with the executor .

Best practice: Wherever deterministic checks exist, put them in the loop; reserve model judgment only for truly unquantifiable aspects (e.g., copy tone, design aesthetics). Tools like Claude Code have productized this: /loop expresses deterministic success conditions (tests pass, lint clean), /goal expresses longer goals with multiple checkpoints.

Termination & Cost: The Other Half of Design

Addy Osmani's oft-quoted line: "Termination is not an afterthought; it is half the design." Long loops risk runaway cost and false completion. Community has identified six typical failure modes, each with a guardrail:

Context overflow & rot — Window fills, quality silently degrades → compression, pruning, sub-agent isolation.

No-progress infinite loop — Repeats same failing action → no-progress detection + hard step limit.

Goal misalignment — Classic anti-pattern: agent deletes failing tests to turn CI green ; it optimizes a proxy metric, not real intent → verification must match true intent.

Hallucinated success — Claims done without verification → trust only deterministic verifiers.

Error accumulation — Early small errors snowball because each step consumes prior output → verify early, correct early.

Cost explosion — Long loop quietly burns budget → hard iteration cap, token/clock budget, prompt caching to cheapen repeated context.

Layered exit: verification passes ∨ MAX_STEPS reached ∨ budget exceeded ∨ no-progress detected — any one triggers stop.

Context Management: Keeping Loops Running Longer

To run loops long without degradation, actively manage context: compaction (summarize old steps), pruning (delete stale tool outputs), externalizing state (offload state to files/scratchpad, read on demand) , and sub-agent isolation (subtasks run in clean windows, only conclusions return). A representative pattern is Ralph Loop (July 2025) : each iteration re-reads state from disk — context window resets but filesystem state persists; plus a Stop Hook intercepts premature exit, validates against deterministic criteria.

while not done and within_budget:
    state   = read_fresh_state()        # reset context, keep disk state
    action = agent.decide(goal, state)  # Perceive→Reason→Plan→Act
    result = execute(action)
    done   = verifier.check(goal)       # independent verification, not self-eval
    if no_progress(result): break       # exit on no progress

Concrete Example: Fixing a CI Build

Goal: Make the payments-refactor branch CI build green. A well-designed loop runs as follows:

Works in an independent git worktree to avoid conflicts with your active code.

Has access to terminal, test runner, type checker.

Uses an external log recording every attempt to avoid re-entering dead ends.

After three consecutive failures on the same test, escalates (hand back to human or switch strategy).

Finally produces a draft PR plus a readable "what changed and why" trajectory.

Human only gates two ends: front-end defines success criteria, back-end reviews final output — not watching every intermediate step.

Engineering Practice Principles

Goals must be measurable : rewrite "improve code" into "make this test suite pass." Verification criteria = exit conditions.

Verification must be independent : use tests, CI, or independent agent to judge done; don't let executor grade itself.

Memory must persist : use state files/DB to avoid rework and allow periodic context reset.

Budget upfront : iteration cap, token budget, timeout set from start — saves money and prevents runaway.

Observability built-in : long loops must be traceable and debuggable.

Start with simplest pattern : if ReAct solves it, don't reach for heavy frameworks; compose patterns, don't stack frameworks .

Reality Check: Not a Silver Bullet

Under the hype, sobering counter-voices exist. Experts warn of self-improvement loop risks : when agents repeatedly feed auto-generated instructions (e.g., auto-updating CLAUDE.md) back to themselves, they "over-index" on self-made rules, letting errors accumulate across sessions. A telling counter-case: fashn.ai's Dan Bochman describes a real workflow: "explain task (5 min) → Claude implements (10 min) → iterate 87 times (13 hours) " — exactly what happens without exit conditions .

Both reminders point to the same essence: Loop Engineering is no silver bullet. It heavily depends on goal verifiability — tasks with deterministic checks (most coding, refactoring, test fixing) benefit most; tasks with fuzzy goals where right/wrong cannot be auto-judged only amplify errors faster. The deeper the automation, the more critical upfront goal definition and guardrail design become. Ultimately, the craft shifts from "writing prompts" to "designing bounded, observable, cost-controlled autonomous loops."

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

AI Agentsprompt engineeringReActAgent DesignContext ManagementVerificationAutonomous LoopsLoop Engineering

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion