Loop Engineering: The Next Critical Skill for AI Programming
Loop Engineering extends the ReAct inner loop by adding an outer control system that automates task discovery, scheduling, verification, and termination, turning AI agents from manual schedulers into self‑directed machines, while highlighting necessary components, risks, and best‑practice guidelines for robust, scalable AI‑driven development.
Problem: manual scheduling of AI agents
When using tools such as Cursor, Claude Code, or Codex, developers often repeat a cycle: view the agent’s output, locate the problem, edit the prompt, and run again. The developer becomes a human scheduler inside the system.
View output
↓
Find problem
↓
Edit Prompt
↓
Run again
↓
View outputThis repetitive loop should be automated.
Loop Engineering
Loop Engineering adds an outer control loop on top of the agent’s inner ReAct cycle (Reason → Act → Observe → Reason …). The outer loop decides which tasks to discover, how to assign them, when to verify results, when to retry, and when to stop. Prompt Engineering remains the “fuel”; Loop Engineering builds the machine that knows which prompt to use and how to validate it.
"I no longer prompt Claude directly. I design a Loop that prompts Claude and then decides the next step." – Boris Cherny, Claude Code lead
Four engineering layers
Layer 1 – Prompt Engineering : Optimize wording and constraints of a single instruction. Suitable for short tasks, Q&A, code snippet generation.
Layer 2 – Context Engineering : Optimize the content placed in the model’s context window (documents, history, tool definitions, examples). Suitable for multi‑turn conversations and Retrieval‑Augmented Generation pipelines.
Layer 3 – Harness Engineering : Define the agent’s execution environment – tool calls, permission boundaries, sandboxing, memory location, sub‑agent orchestration. This determines what the agent can do.
Layer 4 – Loop Engineering : Optimize the control structure itself – when to trigger, how to define goals, how to verify completion, failure paths, and state storage. This determines how the system decides the next step and when to stop.
Harness Engineering – the chassis of a Loop
Model ≠ Agent. Model + Harness = Agent. Harness supplies tool calls, sandbox isolation, permission control, file‑system access, and sub‑agent scheduling. Claude Code, OpenAI Codex, and custom LangGraph orchestrations are examples of Harnesses. In MCP, integrations such as GitHub, Linear, and Slack are also part of the Harness.
模型 ≠ Agent
模型 + Harness = AgentThe five building blocks described later – Worktrees, Skills, Sub‑agents, Connectors – belong to the Harness; Automations, Goal definition, Verifier logic, Retry strategy, and Termination condition constitute the Loop.
Inner loop: the ReAct pattern
Every AI agent follows a ReAct cycle:
Reason (infer current state and goal)
↓
Act (call tools, write code, execute commands)
↓
Observe (read stdout, stderr, test output)
↓
Reason (re‑infer based on new observation)
↓
…Claude Code and Cursor run this inner loop automatically; a single user command may trigger seven or eight ReAct cycles (write code, run tests, read errors, fix code, rerun, etc.). Loop Engineering adds an outer loop that decides *what* tasks to run and *when* to start the next round.
Five building blocks that compose a Loop (plus state Memory)
Block 1 – Automations (heartbeat)
Automation turns a Loop into a truly autonomous system by providing a timed trigger.
Claude Code’s /loop command accepts a cron expression to schedule a prompt:
# Every weekday at 9 am, read yesterday’s CI failures and open issues, write to TODO.md
/loop "Read CI failures and open issues, prioritize, write to TODO.md" --schedule "0 9 * * 1-5"The /goal command is goal‑driven: the Loop runs until a condition is satisfied, then a separate small model decides whether to stop.
# Run until all tests in test/auth pass and lint is clean
/goal "All tests in test/auth pass, lint clean"/loop is frequency‑driven (runs on schedule regardless of work), while /goal is goal‑driven (stops when the condition is met).
Block 2 – Worktrees (concurrent isolation)
Git worktrees provide isolated working directories that share the same repository history, preventing two agents from writing the same file simultaneously.
# .claude/agents/feature-agent.md
---
name: feature-builder
isolation: worktree # sub‑agent gets its own worktree
model: claude-sonnet
---Worktrees solve tool‑level conflicts but do not eliminate review bottlenecks; ten parallel agents may produce ten PRs, overwhelming a human reviewer.
Block 3 – Skills (knowledge solidification)
Skills capture project conventions, naming rules, and known pitfalls in reusable SKILL.md files, eliminating “Intent Debt” – the hidden assumptions an agent makes when the developer does not state intent explicitly.
# auth-module SKILL
## Responsibilities
Handle user authentication, JWT issuance, refresh, revocation.
## Conventions
- Do not modify the user table directly; use UserService
- Tests must cover token expiry edge cases
- Never log JWT payload, only token ID
## Known traps
2025‑11 incident: direct refreshToken table edit caused cascade failure.
Now all session ops must go through SessionManager.Block 4 – Sub‑agents (Maker‑Checker separation)
One sub‑agent (Maker) implements code; a separate sub‑agent (Checker) independently verifies the result, avoiding self‑confirmation bias.
# .codex/agents/security-reviewer.toml
name = "security-reviewer"
description = "Check code for input validation, permission boundaries, sensitive data handling"
model = "o3"
reasoning_effort = "high"
instructions = """
You are a skeptical security reviewer.
Your job is not to say the code is fine, but to find why it might be problematic.
Run the test suite, check diff against CONVENTIONS.md, mark any unverified parts.
""" # .claude/agents/maker.md
---
name: feature-implementer
model: claude-sonnet # fast, suitable for implementation
isolation: worktree
---
Implement the feature, ensure all existing tests pass, output clear modification notes.The /goal command internally embeds this Maker‑Checker separation: one model writes code, another independent model decides whether the termination condition is satisfied.
Maker‑Checker separation is the only foundation that lets a Loop confidently claim “finished” without human oversight.
Block 5 – Plugins & Connectors (bridging the real world)
Connectors built on the Model Context Protocol (MCP) enable agents to interact with issue trackers, databases, staging APIs, Slack, and GitHub PRs. Because Claude Code and OpenAI Codex both support MCP, a connector written for one often works for the other.
Without Connectors:
"This bug can be fixed by editing auth.service.ts line 47. Suggest opening PR #234."
With Connectors:
[Open worktree] → [Edit auth.service.ts] → [Run tests pass]
→ [Submit PR #318 via GitHub MCP]
→ [Link Issue #234 via Linear MCP]
→ [Notify #engineering channel via Slack MCP]Block 6 – Memory (state persistence)
Models forget previous conversations; a Loop must persist state on disk to know what was done, what succeeded, and what failed.
# TODO.md (Loop state file)
## To‑do
- [ ] flaky test in test/auth/login.spec.ts (from CI run #4821)
- [ ] billing module deprecation warning (low priority)
## In‑progress
- [ ] fix rate‑limit middleware bypass (Sub‑agent round 2)
## Done
- [x] upgrade axios to 1.7.4 (PR #312, merged)
- [x] fix user‑avatar CORS issue (PR #309, merged)When the next Automation runs, the Loop reads this file to continue where it left off.
Complete Loop example
The following commands start a daily triage Loop that discovers high‑priority issues and runs a goal‑driven sub‑task for each.
# Start daily triage Loop (Claude Code)
/loop "
1. Read CI reports from the last 24 h
2. Scan open issues, find those tagged 'quick‑win'
3. Call $triage‑skill to prioritize
4. Write high‑priority tasks to TODO.md, low‑priority to BACKLOG.md
5. For the top 3 TODO items, spin up a feature worktree
" --schedule "0 9 * * 1-5"
# For each worktree, run until goal is met (goal‑driven)
/goal "All tests in test/auth pass, eslint clean, naming conventions in CONVENTIONS.md fully satisfied" --max-turns 15 /loophandles discovery and dispatch (outer loop); /goal runs each concrete task to completion (inner loop). No further human prompts are required.
Amplified risks
Risk 1 – Non‑linear token cost accumulation
Each iteration must carry forward prior context, Skill files, tool definitions, and operation history. With two sub‑agents (Maker + Checker), a 10‑iteration Loop that uses ~20 K tokens per round can consume 400 K–600 K tokens, inflating bills.
Mitigations:
Use a small model for triage tasks.
Launch the dual‑agent path only for tasks that truly need verification.
Set a hard iteration limit, e.g., /goal --max-turns 15, and escalate to a human after the limit.
Let Automation first check whether new work exists; if not, abort early.
Risk 2 – Comprehension Debt
Fast, automated merges reduce the time engineers spend reading code, creating hidden “Comprehension Debt.” Even if a Checker approves a change, the reason why it works may be opaque, making future debugging harder.
Countermeasure: after a Loop merges more than five PRs, manually review each change to retain mental model of the repository.
Comprehension Debt is a new kind of technical debt: the faster the Loop, the slower your grasp of the repository, and it surfaces at the worst possible moment.
Risk 3 – Cognitive surrender
When a Loop runs smoothly, engineers may develop a false sense of security, accepting any result as long as CI passes, without questioning underlying design decisions.
Two engineers can build identical Loops and obtain opposite outcomes: one uses the Loop to accelerate deep work, the other to avoid thinking altogether. The Loop cannot distinguish intent; only the human can.
Designing the Loop with explicit engineering judgment is the antidote; the Loop should augment, not replace, critical thinking.
Engineering selection: when to use a Loop
Short, one‑shot tasks – use a direct Prompt; Loop overhead outweighs benefit.
Tasks with clear test or verification criteria – use Loop + /goal to define a termination condition.
Cross‑day or cross‑session persistence needed – use Loop + Memory to store state between runs.
Multiple similar tasks can run in parallel – use Loop + Worktrees for isolated concurrent execution.
Final judgment must be human – keep a Human‑in‑the‑Loop for legal, safety, or business decisions.
Module not yet understood – start with Prompt Engineering, then design a Loop once the codebase is familiar.
Final observations
Loop Engineering is still early; token‑cost uncertainty, verification limits, and recovery expenses are real engineering constraints.
Both Claude Code and OpenAI Codex have already baked the five building blocks (Automations, Worktrees, Skills, Sub‑agents, Connectors) into their platforms, indicating industry consensus on the next paradigm for AI‑driven development.
If you are already using AI coding tools, you are running the inner ReAct loop. Loop Engineering asks you to decide whether to also own the outer loop design.
Loop Engineering’s core is not to let AI replace you, but to turn “when to do what and how to prove it’s done” from ad‑hoc decisions into a designed system. Prompt is conversation; Loop is engineering.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
