Loop
Engineering
— Addy Osmani, June 2026
The definitive guide to designing autonomous agent systems that discover work, execute it, verify it, and remember it — without human intervention between turns. The shift from prompt-holder to loop-designer.
What Is Loop Engineering
Loop engineering is the practice of designing the system that prompts your AI agent, rather than typing each prompt yourself. The term was popularized in June 2026 by Addy Osmani (engineering lead at Google Chrome), synthesizing insights from Boris Cherny — creator of Claude Code at Anthropic — and Peter Steinberger, founder of PSPDFKit.
The catalyst was a single quote from Boris Cherny that circulated widely: "I don't prompt Claude anymore. I have loops that are running. They're the ones that are prompting Claude and figuring out what to do. My job is to write loops." By mid-2026, AI coding agents could run multi-step tasks autonomously for hours. The bottleneck shifted from model capability to orchestration design.
The loop finds what needs to be done — polling test suites, scanning issue trackers, monitoring health endpoints — without waiting for a human to assign it.
The agent acts on a task, then a verifier — often a separate model or a deterministic test gate — confirms the result meets the goal condition before moving on.
The loop writes durable memory about failure patterns, fix strategies, and domain knowledge. The next iteration starts faster and smarter than the last.
The Evolution Stack
Loop engineering did not appear from nothing. It is the latest layer in a four-step progression. Each layer absorbs the previous one — loop engineering still requires prompt craft and context curation. What it adds is the autonomous control structure around all of that.
- Write prompt, read output, write next prompt
- Human is the decision loop between every turn
- Agent is a tool you hold, not a process you run
- Skill = crafting better individual instructions
- Single-session context, no persistent state
- One model, one task, one human review per step
- System finds work, prompts agent, checks result
- Human watches, intervenes only on escalation
- Agent is a long-running process with scheduling
- Skill = designing triggers, verifiers, and memory
- Durable memory across sessions (SKILL.md, DB)
- Multi-model: implementer agent + verifier agent
Anatomy of a Loop
Strip away the hype and a loop is a bounded work cycle. Every loop — whether running on Claude Code, OpenAI Codex, Hermes, or a custom harness — has the same five questions to answer: what starts it, what does it do, how does it prove progress, what makes it stop, and what does it remember.
A Concrete Example — Health-Driven Fix Loop
The Five Blocks
Once you see that Claude Code and OpenAI Codex expose the same five primitives, you stop arguing about which tool and start designing loops that work in either. The tooling convergence is the signal: this "loop shape" is becoming the industry standard for agentic coding.
| Block | Claude Code | OpenAI Codex | Purpose |
|---|---|---|---|
| Scheduling | /loop (interval) · /goal (run-until-done) |
Automations tab · /goal (CLI 0.128.0) |
Start and repeat work without human initiation |
| Skills | CLAUDE.md + skills as plugins | SKILL.md + TOML-defined skills | Durable knowledge that survives session boundaries |
| Connectors | MCP servers (GitHub, Linear, Slack, DB...) | MCP servers (same protocol) | Let the loop act, not just suggest |
| Subagents | Task tool + nested Claude invocations | TOML-defined subagent configs | Separate implementer from verifier roles |
| Worktrees | Built-in git worktree isolation | Built-in worktrees | Parallel loops without filesystem collision |
/goal in v2.1.139 on May 11, 2026 — a native loop that runs across turns until a condition you wrote is true, with a separate fast model grading the work after every turn. Codex shipped the equivalent in CLI 0.128.0 on April 30, 2026, plus an Automations tab and triage inbox.Triggers & Scheduling
The trigger is what makes a loop autonomous rather than a well-organized prompt. The mistake most people make with /loop is treating it as a timer. The timer is the least interesting part. What matters is the work-discovery logic that runs when the trigger fires.
Run on a schedule regardless of external state. Good for: health checks, daily PR triage, dependency audit scans. Set cadence based on how frequently the state you're polling changes, not how fast you want results.
Triggered by a webhook or queue event — CI failure, PR opened, alert fired, ticket created. Zero idle cost. Lower latency than polling. Requires a listener or integration layer (MCP connector or webhook endpoint).
/goal in Claude Code and Codex: keep working until a verifiable condition holds. The loop self-terminates when the goal is met. Best for finite work with a clear end state: "all tests green" or "no open P1s."
Verifiers & Stop Conditions
The most critical design decision in loop engineering is the verifier. The agent that wrote the code is a structurally poor judge of its own output — not a model limitation, but a fundamental issue. One agent (or team) explores and implements. A different one, sometimes a stronger model with different instructions, verifies against specs and tests. Self-assessment is not verification.
- "Looks good" from the implementer model
- Agent marks task done when it runs out of ideas
- No objective exit criterion defined
- Loop continues until budget is exhausted
- Human must review every iteration manually
- Deterministic gate: tests, compiler, linter exit code
- Separate verifier model with independent instructions
- Objective exit criterion written before loop starts
- Budget + iteration limit as hard stop safety
- Evidence artifact produced: test output, diff, log
Verifier Types
| Type | Example | Use When | Trust Level |
|---|---|---|---|
| Deterministic | Test suite exit code, compiler, linter, type-checker | Task has a binary pass/fail criterion | HIGHEST — no model judgment involved |
| LLM Reviewer | A separate model with a rubric: "does this diff meet the spec?" | Quality, style, architecture review where tests don't cover it | MEDIUM — depends on rubric quality |
| Behavioral | Integration test, end-to-end test, user-flow simulation | Feature work where unit tests alone are insufficient | HIGH — reflects real system behavior |
| Human Gate | PR review required before merge, Slack approval step | Production changes, architecture decisions, sensitive data | DEFINITIVE — escalate to here for anything high-risk |
Memory & Skills
AI models are stateless. Without a memory layer, every loop iteration starts from scratch — the agent re-learns the codebase, rediscovers the conventions, and repeats the same mistakes. A SKILL.md (plus optional scripts and references) holds the knowledge that should survive across runs.
Structured knowledge file loaded into agent context at the start of every loop run. Contains: codebase conventions, common failure patterns and their fixes, tool usage instructions, acceptable solution approaches, anti-patterns to avoid. Think of it as the senior engineer's onboarding doc — never rewritten by the agent, only by humans.
A lightweight append-only log the agent writes after each successful or failed loop run. Format: what failed → root cause → fix applied → time to resolve. Periodically summarized and distilled (every 10 sessions) to prevent bloat. Gives the next loop run a head start on recurring failure patterns.
/goal that reads memory files and merges duplicates, removes obsolete entries, keeps only high-value patterns, and compresses to under 50KB total. Context windows are large but not infinite — uncontrolled memory growth eventually crowds out the working context.Context Engineering in Loops
Context engineering doesn't disappear in loop engineering — it becomes the most expensive per-iteration decision. A loop that loads the full codebase on each iteration was impractical until 1M-token context windows arrived in 2025-2026. With them, complete project context on every retry is now feasible for most codebases. But "can afford" is not "should include."
| Context Layer | What It Contains | Loaded When |
|---|---|---|
| Skill Layer | SKILL.md, conventions, anti-patterns, known fixes | Every loop iteration — always first |
| Task Layer | Current goal, failing test output, error messages, diff of previous attempt | Every iteration — the "what to do now" |
| Codebase Layer | Relevant source files, type definitions, related tests | Retrieved by relevance — not dumped wholesale |
| Memory Layer | Loop memory log, past failure patterns for this task type | Fetched when relevant to current failure mode |
| History Layer | Previous attempts in current loop run, verifier feedback | Last N turns — window-aware truncation |
Claude Code & Codex
By mid-2026, both Claude Code and OpenAI Codex had converged on the same five primitives. The "loop shape" is tool-agnostic. The choice between them comes down to model preference and connector availability, not architectural philosophy.
/loop— scheduling primitive: run a prompt repeatedly on an interval. Useful for polling deployments, babysitting PRs, checking long-running builds./goal(v2.1.139, May 11 2026) — run-until-done primitive: keep working until a verifiable completion condition holds. A separate fast model grades the work after every turn.CLAUDE.md+ skills packaged as shareable plugins- Task tool for spawning subagents with independent contexts
- MCP connectors as the action layer
- Git worktree isolation for parallel loops
- Hooks for pre/post execution side effects
- Automations tab — unprompted recurring work, triage inbox for reviewing loop outputs
/goal(CLI 0.128.0, April 30 2026) — same goal-driven loop primitive as Claude Code- TOML-defined skills and subagent configurations
- Built-in worktrees for parallel session isolation
- MCP connectors (same protocol — connectors port between tools)
- SKILL.md pattern for persistent knowledge
Deterministic vs Non-Deterministic Loops
The most important loop design choice is the verifier type. Deterministic loops use test/compile gates — objective, binary, fast. Non-deterministic loops use reviewer/quality gates — flexible, judgment-based, slower. Most real loops combine both.
- Verifier is: test runner, compiler, linter, type-checker
- Exit condition is a binary: pass or fail, exit code 0 or non-0
- No model judgment in the verification step
- Highest trust — the model cannot "convince" the tests
- Best for: bug fixes, refactors, dependency updates
- Token-efficient: verifier is a bash command, not an LLM call
- Verifier is: a second LLM model given a rubric and the diff
- Exit condition is qualitative: "meets the spec" as judged by the reviewer
- Adds LLM cost to every verification step
- Higher coverage: can verify style, architecture, security concerns
- Best for: feature work, PR review, documentation quality
- Risk: verifier model can be convinced — keep rubrics objective
Subagents & Orchestration
A single agent loop is a serial process. Subagents let you run parallel loops in isolated workspaces, separate concerns (implement vs. verify), and assign specialized models to specialized tasks. The orchestrator loop decides what to spawn; the subagent loops execute without coordination overhead.
Focuses solely on producing code that passes the verifier gate. Given a narrow task, a SKILL.md, and a test command. Optimized for iteration speed. Often uses a smaller, faster model for cost efficiency.
A different model, with different instructions, reviewing the implementer's output against a rubric. Structural separation: the agent that writes the code never reviews its own work. A stronger model is justified here — quality of judgment matters more than speed.
Manages the other agents. Decides which tasks to spawn, monitors budgets, collects results, and writes the final memory log. Routes escalations to humans. The orchestrator is the loop's brain; subagents are its hands.
MCP Connectors
A loop that can only read the filesystem is a loop that can only suggest. MCP-based connectors let the loop act: open PRs, update Linear tickets, post to Slack, query a database, trigger a runbook. The loop stops being a commentator and starts being an operator. MCP has become the common substrate — connectors written for one tool often port to another.
- GitHub MCP — open PRs, comment on issues, merge branches, create releases
- Linear / Jira MCP — create tickets, update status, close resolved issues
- Slack MCP — post summaries, escalate to humans, notify on completion
- Database MCP — read query results, run migrations in test environments
- Runbook MCP — trigger deployment pipelines, restart services
- CI/CD MCP — poll build status, fetch test results, read artifact logs
- Monitoring MCP — read Datadog/Grafana metrics, fetch alert states
- Search MCP — query codebase semantically, find relevant files
- Docs MCP — fetch API documentation, look up error codes
- ITSM MCP — read incident tickets, check SLA status
Failure Modes
An unattended loop is also a loop that makes mistakes unattended. The failure modes are predictable. Most can be prevented with explicit constraints written into the loop design before the first run.
| Failure Mode | Symptom | Fix |
|---|---|---|
| Weak Verification | Agent claims done without proof; loop terminates with task incomplete | Require deterministic gate (test exit code) before allowing loop termination |
| Infinite Loop | Loop runs forever; budget exhausted; task never converges | Hard turn limit + time budget + escalation path — always defined upfront |
| Comprehension Debt | Code ships faster than you can understand it; technical debt accumulates invisibly | Weekly loop summaries; require human review of significant diffs; measure test coverage |
| Scope Creep | Agent modifies files outside its declared scope; breaks unrelated features | Declare allowed file paths in SKILL.md; use worktrees; verifier checks diff scope |
| Cognitive Surrender | Engineer accepts loop output without judgment; code quality degrades over time | Mandatory review of all loop-produced PRs; set coverage and quality thresholds |
| Memory Poisoning | A bad agent-written memory entry biases all future loop runs | Human review before agent-written instructions become persistent; regular audit |
| Cost Spiral | Loop runs 40+ iterations per task; API cost exceeds value of work done | Token budget per iteration + cost limit per loop; alert at 50% budget consumed |
| Security Overreach | Loop touches production systems, rotates secrets, pushes to main unreviewed | Least-privilege MCP scopes; no direct-to-main pushes; audit log all connector calls |
Security & Guardrails
Loop engineering's security dimension deserves its own attention. The same connector access that lets a loop open PRs and update tickets can, if misconfigured, let it push to production, delete resources, or exfiltrate code. Security is not an afterthought — it's a primitive that must be designed in from the start.
- Least-privilege connectors — read-only until proven, write access scoped to exact operations needed
- Worktree isolation — every loop run in a fresh worktree, never directly on main
- No direct production access — loops write to staging environments or open PRs; humans merge
- Audit log all connector calls — session ID, timestamp, operation, arguments, result
- Budget hard limits — max turns, max cost, max duration before forced stop
- Human escalation path — every loop must have a defined escalation when budget is hit
- Treat external data (issue bodies, PR descriptions, file contents from untrusted sources) as untrusted input — sanitize before inserting into agent context
- Separate the loop's system instructions from dynamic content with clear structural delimiters
- Validate tool call arguments against an allowlist before execution
- Monitor for unusual connector call patterns (unexpected file reads, out-of-scope writes)
- Never give loops credentials that exceed what a junior engineer would have
Loop Engineering Maturity Model
Most teams are at Stage 1 or early Stage 2. The goal is not to race to Stage 4 — it's to advance identity-first: get verification right before adding automation, and add memory before adding subagents. A loop at Stage 2 with excellent verification is more valuable than a Stage 4 loop with weak exit conditions.
- Typing prompts turn by turn
- Human reviews every output
- No scheduling or triggers
- No persistent memory
- Session-scoped context only
- Single model, single task
- /goal for single tasks
- SKILL.md with conventions
- Deterministic verifier (tests)
- Manual trigger, human-initiated
- Budget and turn limits defined
- Loop memory log started
- Cron / event-driven triggers
- Worktree isolation per run
- Verifier subagent pattern
- MCP connectors for actions
- Escalation path defined
- Audit log all connector calls
- Parallel subagents in worktrees
- Orchestrator manages subagents
- Memory distillation on cadence
- Cost monitoring + auto-optimize
- Human review PR gate only
- Continuous posture measurement
Implementation Roadmap
Loop engineering is still early. Direct prompting is still effective for one-off tasks. The goal is balance: set up loops for the recurring, verifiable work, and keep direct control for the parts where your judgment is the value. Build the loop like someone who intends to stay the engineer, not just the person who presses go.
- Starting with non-deterministic verification (judge your own output)
- No budget limits — loop runs until cost threshold triggers panic
- Skipping SKILL.md — every run is day one, agent relearns from scratch
- Adding MCP write access before the loop has proven reliability
- Treating loop output as trusted without human review gate
- No escalation path — a stuck loop sends no signal
- Mean turns per completed task trending down (agent improves via memory)
- Human intervention rate below 20% of loop runs
- Cost per task under budget with room to spare
- Zero security incidents from loop connector access
- Test coverage maintained or improved by loop-produced code
- Engineers spending more time on design, less on mechanical fixes