Field Manual
Loop Engineering
DOC-LOOP-2026
Architecture Field Handbook · June 2026

Loop
Engineering

// "Stop prompting the agent. Design the loop that prompts it."
— 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.

Agentic AI Claude Code OpenAI Codex Verifier Patterns No Standing Humans MCP Connectors
01

What Is Loop Engineering

// FOUNDATIONAL DOCTRINE · COINED JUNE 2026

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.

Discover Work

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.

Execute & Verify

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.

Remember & Improve

The loop writes durable memory about failure patterns, fix strategies, and domain knowledge. The next iteration starts faster and smarter than the last.

Prompt engineering is table stakes. Loop engineering is the next layer. Prompt engineering optimizes a single instruction you type by hand, one turn at a time. Loop engineering optimizes the autonomous system that decides what to prompt, when to prompt it, and whether the result is acceptable.
02

The Evolution Stack

// PROMPT → CONTEXT → HARNESS → LOOP

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.

2022 – 2023
Prompt Engineering
Optimizing the wording of a single instruction: temperature, few-shot examples, chain-of-thought formatting. The agent is a tool you hold, one turn at a time. Skill = crafting instructions that keep the model on track.
2024 – mid 2025
Context Engineering
The focus shifted from words to everything the model sees at inference time — conversation history, retrieved documents, tool outputs, agent state. Shopify's Tobi Lütke defined it as "providing all the context needed for the task to be plausibly solvable by the model." Andrej Karpathy called it "the delicate art of filling the context window with just the right information." Anthropic formalized it as curating the optimal set of tokens during inference. Context engineering became the craft; prompt engineering became a subset.
Late 2025 – early 2026
Harness Engineering
As agents started doing multi-step autonomous work in production, the harness emerged as a distinct concern: the full environment of scaffolding, tools, constraints, worktree isolation, and feedback loops around an agent. The harness is what keeps an agent from touching the wrong things, running too long, or accumulating side effects.
June 2026 →
Loop Engineering
The autonomous control structure that drives harnesses, manages context, and writes prompts — without a human in the middle. Trigger, task discovery, execution, verification, memory, and scheduling combine into a self-running agent system. Context engineering does not go away; the loop still puts the right files, history, and tool definitions in front of the model on each turn. What loop engineering adds is the recursive control layer around all of that.
✕ Old Workflow — Prompt-by-Prompt
  • 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
✓ Loop Engineering — Autonomous System
  • 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
03

Anatomy of a Loop

// THE CORE CYCLE — STRIPPED OF HYPE

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.

Start
Trigger
🔍
Find
Discover Work
⚙️
Act
Execute
Check
Verify
🧠
Learn
Write Memory
↩ Repeat until stop condition holds
The verifiable end state is the most important design decision. Not "make things better" — but "all tests pass" or "zero open P1 issues" or "bundle size under 200KB." A loop with a vague goal runs forever and produces nothing trustworthy. A loop with a concrete, checkable goal terminates reliably and produces auditable evidence.

A Concrete Example — Health-Driven Fix Loop

Loop Design — Production Health Monitor
# Hermes Agent — deterministic loop example Trigger: cron every 15 minutes State Check: read production health checks / test results Decision: if all checks PASS → log "healthy", stop loop if anything FAILS → open fix loop Execution: launch coding agent in a fresh git worktree goal: "Fix the failing tests: [paste output]" budget: 20 turns, 30 minutes max Feedback: run test suite after each agent change pipe results back as next loop context Verification: stop ONLY when all health checks pass agent's self-assessment does not count Memory: write to memory/fix-log.md: - what failed - root cause identified - fix applied - time to resolve (so next occurrence is faster) Stop conditions: ✓ All health checks GREEN ✕ Budget exceeded → escalate to human (PagerDuty P2) ✕ Same failure 3 consecutive times → escalate (P1)
04

The Five Blocks

// UNIVERSAL PRIMITIVES — TOOL-AGNOSTIC

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.

Trigger
Cron, event, webhook, or user initiation
🛠️
Skills
Persistent knowledge that survives across sessions
🔗
Connectors
MCP tools to act on external systems
🤖
Subagents
Specialized models for verification, review, or parallel work
🌿
Worktrees
Isolated workspaces so parallel loops don't collide
BlockClaude CodeOpenAI CodexPurpose
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
Claude Code added /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.
05

Triggers & Scheduling

// WHAT MAKES THE LOOP AUTONOMOUS

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.

Cron / Interval Polling

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.

Event-Driven Reactive

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-Driven Run-Until-Done

/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."

Claude Code — /goal Prompt Structure
# A useful /goal prompt carries the full control contract. # The goal itself is the least important line. /goal "Fix all failing tests in packages/api" Context: - Failing tests: [paste output of `npm test 2>&1`] - Codebase: TypeScript, Express, Prisma ORM - Do NOT modify test files — fix the implementation only Verifier: run `npm test` after each change batch pass condition: exit code 0, 0 failed tests Evidence: paste final test output as proof of completion Budget: max_turns: 25 max_duration: 45 minutes max_cost: $2.00 Stop conditions: ✓ All tests pass (exit 0) ✗ Budget hit → summarize work done, open issues list, stop ✗ Same test fails 3 times in a row → stop, explain blocker Do NOT: - Skip or disable failing tests - Modify test expectations - Leave TODO comments as fixes
06

Verifiers & Stop Conditions

// THE AGENT IS A POOR JUDGE OF ITS OWN WORK

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.

✕ Weak 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
✓ Strong Verification
  • 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

TypeExampleUse WhenTrust 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
Use loops for task verification, not unsupervised self-modification. A bad suggestion in a self-improvement loop doesn't just produce one bad response — it gets written into the agent's permanent context, where it biases every subsequent response. The loop amplifies the error. Human review before any agent-written instruction becomes persistent context.
07

Memory & Skills

// WITHOUT SKILLS, EVERY LOOP RUN IS DAY ONE

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.

SKILL.md / CLAUDE.md Persistent

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.

Loop Memory Log Accumulating

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.

SKILL.md — Structure Template
# payments-service — Loop Skill # Loaded automatically at the start of every loop run targeting this service. ## Stack - TypeScript 5.4, Node 20, Fastify 4, Prisma 5, PostgreSQL 16 - Test runner: Vitest · Coverage threshold: 80% - Build: `npm run build` → `dist/` (tsc, ESM output) ## Common Failure Patterns & Known Fixes 1. Prisma migration drift Symptom: "P3006 Migration file not found" Fix: `npx prisma migrate reset --force` in test env (NEVER prod) 2. Stripe webhook signature failure in tests Symptom: "No signatures found matching the expected signature" Fix: Tests must use `stripe.webhooks.constructEvent` with `STRIPE_WEBHOOK_SECRET_TEST` 3. Port 3000 already in use Symptom: EADDRINUSE Fix: `lsof -ti:3000 | xargs kill -9` before test run ## Conventions - All currency amounts stored as integer cents, never floats - Error responses: { error: string, code: string, statusCode: number } - Logging: pino structured JSON, level INFO in tests (not TRACE) - No `console.log` in production code — ESLint rule enforced ## Anti-Patterns - NEVER disable TypeScript with @ts-ignore in this service - NEVER mock the database in integration tests — use testcontainers - NEVER commit .env files — use .env.test.template ## Acceptable Tool Commands - Read/write: src/, tests/, package.json - Execute: npm test, npm run build, npm run lint - Forbidden: git push, npm publish, any kubectl command
Memory distillation cadence: After every 10 sessions, run a /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.
08

Context Engineering in Loops

// WHAT GOES IN THE WINDOW ON EACH ITERATION

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 LayerWhat It ContainsLoaded 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
Context Budget — Per-Iteration Allocation
# Context window budget for a 200K-token model # Leaving room for model output (4K reserved) Skill layer: ~2,000 tokens (SKILL.md + conventions) Current task: ~1,500 tokens (goal + failing output + constraints) Relevant source: ~80,000 tokens (retrieved files, not full tree) Memory log: ~3,000 tokens (recent patterns, filtered by relevance) Turn history: ~20,000 tokens (last 5-10 turns, summarized if older) Buffer: ~93,500 tokens (room for large files, safety margin) # Why NOT to dump the entire codebase: # 1. Token cost per iteration multiplies across all loop turns # 2. Irrelevant context degrades model focus on the actual problem # 3. Retrieval + filtering = faster, cheaper, more precise # Retrieval strategy: file-level relevance scoring # 1. Parse import graph of failing test files # 2. Include direct imports + one level of transitive deps # 3. Include types referenced by the failing symbol # 4. Include relevant SKILL.md sections (keyword match)
09

Claude Code & Codex

// NATIVE LOOP PRIMITIVES IN BOTH TOOLS

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.

Claude Code — Loop Primitives Anthropic
  • /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
OpenAI Codex — Loop Primitives OpenAI
  • 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
Convergence means portability. An MCP connector written for Claude Code often ports to Codex with minimal changes. A SKILL.md written for one tool works in the other with naming adjustments. Design your loops against the abstract primitives, not the tool-specific syntax, and you can migrate between platforms as model capability evolves.
10

Deterministic vs Non-Deterministic Loops

// TEST GATES VS REVIEWER GATES

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.

Deterministic Loop Test / Compile Gates
  • 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
Non-Deterministic Loop Reviewer / Quality Gates
  • 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
Non-Deterministic Verifier — Rubric Pattern
# Verifier subagent prompt — given after implementer produces a diff You are a strict code reviewer. Review the following diff and answer ONLY with PASS or FAIL followed by a one-sentence reason. Rubric (ALL must be true to PASS): □ The change does not modify test files □ The change does not introduce `any` types in TypeScript □ The change does not add new external dependencies □ Error handling is present for all async operations □ No secrets or credentials appear in the diff □ The change is scoped to the described task and nothing else PASS means the implementer loop can stop. FAIL means the implementer loop must continue with your reason as context. DIFF: --- a/src/payments/processor.ts +++ b/src/payments/processor.ts [paste diff here] Respond with exactly one word (PASS or FAIL) then a colon and reason. Example: FAIL: Missing error handler on line 47 async call.
11

Subagents & Orchestration

// PARALLEL WORK, SEPARATE CONCERNS

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.

Implementer Agent

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.

Verifier Agent

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.

Orchestrator Agent

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.

Parallel Subagent Pattern — Worktree Isolation
# Orchestrator spawns parallel fix loops for independent failing tests # Each runs in its own git worktree to avoid filesystem collision failed_tests = parse_test_output(run("npm test 2>&1")) # → ["tests/auth.test.ts", "tests/payments.test.ts", "tests/notifications.test.ts"] for each failing_test in failed_tests: worktree = create_worktree(f"fix/{failing_test.name}-{timestamp}") spawn_subagent( model = "claude-sonnet-4-6", # fast model for impl context = [SKILL.md, failing_test.output, relevant_source_files], goal = f"Fix {failing_test.path} — all assertions must pass", verifier= f"cd {worktree} && npx vitest run {failing_test.path}", budget = { turns: 15, minutes: 20, cost: "$0.50" }, worktree= worktree ) # Collect results from all subagents (parallel, not sequential) results = await_all_subagents(timeout=30min) for each result in results: if result.passed: merge_worktree(result.worktree, target="main") write_memory(result.task, result.fix, result.duration) else: escalate_to_human(result.task, result.last_error, priority="P3")
12

MCP Connectors

// FROM COMMENTATOR TO OPERATOR

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.

Action Connectors Operator
  • 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
Read Connectors Observer
  • 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
Scope connectors narrowly. An unattended loop with write access to production systems is an unattended loop that can break production unattended. Principle of least privilege applies — read access only until the loop has proven reliability, then add targeted write access one connector at a time. Log all connector invocations with the loop's session ID for auditability.
13

Failure Modes

// THE 8 WAYS LOOPS GO WRONG

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 ModeSymptomFix
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
14

Security & Guardrails

// AN AUTONOMOUS LOOP WITH CONNECTOR ACCESS CAN TOUCH PRODUCTION

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.

Minimum Required Guardrails Non-Negotiable
  • 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
Prompt Injection Defenses Emerging Risk
  • 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
Security Constraints — Loop Configuration
# Security configuration block — include in every loop design Filesystem access: read: ["src/", "tests/", "package.json", "tsconfig.json"] write: ["src/", "tests/"] # narrow to task scope forbidden: [".env", ".git/config", "dist/", "node_modules/"] Shell commands: allowed: ["npm test", "npm run build", "npm run lint", "npx tsc"] forbidden: ["git push", "npm publish", "kubectl", "docker push", "rm -rf"] Network access: allowed: [] # none — agent should not make outbound requests exception: MCP connectors only (routed through controlled gateway) MCP connector scopes: github: read:repo, write:pull_requests # NOT write:repo (no direct push) linear: read:issues, write:comments # NOT write:issues (no status changes without review) slack: write:messages (loop-alerts channel only) Escalation triggers: - Budget 50% consumed → Slack warning to engineer - Budget 100% consumed → PagerDuty P3, loop stops - Same failure 3 consecutive turns → PagerDuty P2, preserve state - Any forbidden command attempted → PagerDuty P1, loop killed
15

Loop Engineering Maturity Model

// WHERE ARE YOU TODAY

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.

Stage 01
Manual
  • Typing prompts turn by turn
  • Human reviews every output
  • No scheduling or triggers
  • No persistent memory
  • Session-scoped context only
  • Single model, single task
Stage 02
Semi-Auto
  • /goal for single tasks
  • SKILL.md with conventions
  • Deterministic verifier (tests)
  • Manual trigger, human-initiated
  • Budget and turn limits defined
  • Loop memory log started
Stage 03
Scheduled
  • Cron / event-driven triggers
  • Worktree isolation per run
  • Verifier subagent pattern
  • MCP connectors for actions
  • Escalation path defined
  • Audit log all connector calls
Stage 04
Autonomous
  • Parallel subagents in worktrees
  • Orchestrator manages subagents
  • Memory distillation on cadence
  • Cost monitoring + auto-optimize
  • Human review PR gate only
  • Continuous posture measurement
16

Implementation Roadmap

// 30-DAY ONRAMP FROM MANUAL TO SCHEDULED LOOPS

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.

30-Day Loop Engineering Rollout
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ WEEK 1 — INSTRUMENT (Days 1-7) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ✦ Write SKILL.md for your highest-traffic service → codebase conventions, known failure patterns, anti-patterns ✦ Identify your most recurring manually-prompted task type (common: "fix failing test", "update dependency", "resolve lint errors") ✦ Run that task manually once with /goal — observe the turn count and token cost ✦ Define the verifier for that task: what command proves it's done? ✦ Write the first loop prompt using the control-contract structure: task / verifier / evidence / budget / stop conditions ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ WEEK 2 — VALIDATE (Days 8-14) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ✦ Run 5 loop instances with that prompt on real tasks ✦ Track: turn count, cost per loop, false-positive completions ✦ Tune SKILL.md based on what the agent misses or repeats ✦ Add the memory log — after each run, agent appends a one-line summary ✦ Set up worktree isolation for the loop's runs ✦ Define and test the escalation path (what happens on budget hit?) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ WEEK 3 — SCHEDULE (Days 15-21) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ✦ Add a trigger: cron schedule or event webhook (CI failure → loop starts) ✦ Connect one read-only MCP connector (CI results, issue tracker) ✦ Run 10 autonomous loop instances — review all outputs ✦ Measure: how many required human intervention? Why? ✦ Add a verifier subagent for non-deterministic quality checks ✦ Security audit: confirm no connector has write access outside declared scope ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ WEEK 4 — SCALE (Days 22-30) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ✦ Add one action MCP connector (GitHub PR creation) ✦ Pilot parallel subagents for independent failing tests ✦ Set up memory distillation job (weekly compression run) ✦ Build a dashboard: loops run / tasks completed / escalations / cost ✦ Identify the second recurring task type for loop treatment ✦ Document what your loops can do — and what they explicitly cannot
Common Failure Modes at Rollout Avoid
  • 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
Success Indicators Measure These
  • 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
Reference implementations: Boris Cherny's talk clips (Anthropic, June 2026) · Addy Osmani's blog post and GitHub reference repo · The New Stack's June 2026 loop engineering breakdown · Cobus Greyling's Medium series on loop primitives · Lushbinary.com loop engineering guide · the-ai-corner.com's five-block system with copy-paste /goal conditions.
Back to Handbooks