Skip to content

AI Agent Loop Engineering

Spinning Idea edited this page Jul 23, 2026 · 4 revisions

Loop Engineering: Stop Prompting, Start Building Loops

The most important shift in AI-assisted coding is from writing prompts to designing loops that prompt agents for you. You give the loop a goal, the tools it can use, and a definition of done. The loop prompts agents on its own, a separate agent verifies the work against the definition, and the loop repeats until the goal is met.

For the last two years the dominant skill in AI-assisted coding was prompt engineering. You write a good prompt, read the response, then write the next one. That is changing. In its place is a new discipline, loop engineering, in which your job is not to type prompts but to design the system that types them for you.

Addy Osmani defines the idea concisely. "Loop engineering is replacing yourself as the person who prompts the agent. You design the system that does it instead. A loop here can be thought of a recursive goal where you define a purpose and the AI iterates until complete."

What is a loop?

A loop is a small, autonomous control system that replaces manual prompting with a closed-loop execution cycle. It starts with a specific goal and a clear definition of done. The loop manages the primary agent-keeping it running on a schedule, spawning helpers, and feeding it new work. As the agent works, the loop continuously saves progress to a durable state, evaluates the gap between the current state and the goal, and runs separate subagents to verify the results. It then retries on any remaining gaps, repeating this cycle of action, state-saving, and verification until the "done criteria" are met or the retry limit is reached.

The same parts are showing up in Claude Code, OpenAI Codex, Pi.dev, and in community tools like the cobusgreyling/loop-engineering repository.

Define done up front

A loop only succeeds when the agent knows what success looks like. Before the loop starts, write a clear definition of done. State the exact conditions, outputs, or tests that must be true before the loop can stop. A vague goal causes the loop to wander, spin, or declare victory too early. A concrete, verifiable definition of done makes the loop self-correcting and improves the quality of every result it produces.

The six parts of a loop

A real loop is not one long prompt. It is a small system of six parts plus a durable memory.

1. Automations and scheduling

This is the rhythm. Without a schedule you have a one-off session. With one, you have discovery and triage on a cadence. In Claude Code, think of /loop, /schedule, or /goal. In OpenAI Codex, think of the Automations tab. In Grok, scheduler tools like scheduler_create, scheduler_list, and scheduler_delete fire recurring prompts. The /goal primitive is especially useful. It keeps running until a verifiable condition is true, and a separate model checks whether the goal is met so the worker does not grade its own homework.

2. Worktrees

Two agents writing the same files at once is the same problem as two engineers committing to the same lines. Git worktrees, or equivalent isolated checkouts, give each agent its own working directory while sharing history. Codex builds worktree support in. Claude Code offers --worktree and an isolation: worktree setting for subagents. Grok supports passing isolation: "worktree" when spawning subagents. Cleanup matters. A loop that leaves orphaned worktrees behind is a loop you will regret.

3. Skills

Every session starts cold. Unless you externalise conventions, build commands, review standards, and the history of why "we do not do it that way", the agent re-derives it from zero every time. A skill is a package, usually a SKILL.md plus optional scripts and references, that holds project knowledge outside the conversation. Claude Code uses CLAUDE.md and skills. Codex uses the same SKILL.md pattern. Plugins bundle skills and connectors so they can be shared across repos. This is how the loop builds on knowledge rather than re-learning it each cycle.

4. Plugins and connectors

A loop that only reads the filesystem can only suggest. MCP-based connectors let the loop act inside your real environment. It can open a PR, update a Linear ticket, post to Slack, query a database, or trigger a runbook. The loop stops being a commentator and starts being an operator. Because both Claude Code and Codex speak MCP, a connector written for one usually works in the other.

5. Sub-agents

The agent that wrote the code is a poor judge of its own work. This is a structural problem, not a model limitation. One sub-agent explores or implements. Another, sometimes a stronger model, verifies against the spec, skills, and tests. Codex defines agents in .codex/agents/ as TOML files. Claude Code uses .claude/agents/ and agent teams. Grok supports subagents with worktree isolation. In unattended loops, the verifier is the only reason you can walk away.

6. Memory

The sixth piece is the core. The loop must read and write durable state, e.g., a STATE.md, a LOOP.md, a LOOP-STATE.json, a Linear board, or a GitHub Project view. Good memory answers three questions. What are we working on right now? What did we try last time? What is waiting for a human? The model forgets everything between runs. The repo must not.

Anatomy of a loop

Put together, a single thread turns into a small control system. A typical loop, from the cobusgreyling/loop-engineering repo, looks like this:

Schedule or Automation -> Triage Skill -> Read/Write State -> Isolated Worktree -> Implementer Sub-agent -> Verifier Sub-agent -> MCP/Git/Tickets -> Human Gate -> Commit/PR or Escalate -> Loop.

For example, an automation runs every morning. It calls a triage skill that reads yesterday's CI failures, open issues, and recent commits, and writes the findings into a state file or a Linear board. For each finding worth acting on, the loop opens an isolated worktree, sends an implementer to draft a fix, and sends a verifier to review the draft against project skills and existing tests. Connectors open the PR and update the ticket. Anything the loop cannot handle lands in a triage inbox for a human. Tomorrow morning the run picks up where today stopped.

You designed the loop once, and you did not prompt any of the individual steps.

A practical reference

Cobus Greyling's GitHub repository is a practical reference for loop engineering. It includes patterns you can clone, checklists you can ship against, and starter implementations across multiple tools. The patterns include Daily Triage, PR Babysitter, CI Sweeper, Dependency Sweeper, Changelog Drafter, Post-Merge Cleanup, and Issue Triage.

The repository also provides CLI tools:

  • loop-init scaffolds a loop and prints a Loop Ready score.
  • loop-audit checks how ready a project is for unattended loops.
  • loop-cost estimates token spend for a chosen pattern and cadence.
  • loop-sync keeps state files in sync.
  • loop-context audits context usage.
  • loop-worktree creates isolated worktrees for agent runs.
  • loop-mcp-server exposes loop state over MCP.

The recommended phased rollout is report-only at first, then assisted fixes, then fully unattended. Start with a low-risk, observable loop and watch what it does before letting it act on its own.

The caveats

Loop engineering does not delete the engineer. It changes where you add value, and it amplifies judgment both good and bad.

Verification is still on you

A loop running unattended is a loop making mistakes unattended. The whole reason you split the verifier from the maker is so that "done" means something. But even then, "done" is a claim, not a proof.

Token costs are real

Sub-agents and frequent cadences multiply fast. A 5-minute loop that spawns an implementer and verifier on every run can burn through a budget before breakfast. Triage should be cheap. Sub-agents should spawn only when state says the work is actionable.

You stop understanding the code faster

The faster the loop ships code you did not write, the bigger the gap between what exists and what you actually understand. Unless you read what the loop made, you lose track of your own codebase.

Giving up understanding is the trap

The same loop can accelerate someone who understands the work deeply, or let someone avoid understanding the work entirely. The loop does not know the difference. You do.

Addy Osmani puts it plainly. "Build the loop. But build it like someone who intends to stay the engineer, not just the person who presses go."

Getting started

The move is to take a task you keep re-prompting, describe it as a goal, and set up a loop or automation to carry it forward. The companion to the 9-minute video Loop Engineering in 9 Minutes summarises the core idea. Stop prompting, start building loops. Goals replace instructions, long-running beats one-shot, and automations build on each other. For a shorter, simplified introduction, the 8-minute walkthrough covers the same idea.

In a practical sense, start here:

  1. Pick one repeated task, such as daily issue triage or CI health checks.
  2. Define it as a goal, not a one-off instruction.
  3. Write the skill that captures the project conventions the agent will need.
  4. Choose a schedule or trigger.
  5. Start report-only, with no autonomous fixes in the first week.
  6. Add a worktree and a verifier sub-agent once the triage is reliable.
  7. Promote to assisted fixes, then unattended, only when the cost and risk are acceptable.

The bottom line

The model is becoming a commodity fast. What grows in value is the system you wrap around it. The rules, the orchestration, the verification, and the memory. Loop engineering is the shift from writing prompts to writing the control system that writes them.

References & Resources

Goal Examples

The goal command is a powerful feature that allows you to set a goal for the agent to achieve. It is available in Claude Code, Pi.dev, and OpenAI Codex. It also represents an example of the "loop" concept in AI agent engineering.

Below are concrete examples of the /goal primitive across the three main agentic coding tools mentioned earlier.

Claude Code

Claude Code's /goal command is available from v2.1.139 and turns a stop condition into a session-scoped loop. After each turn, a small fast evaluator model (default Haiku) checks whether the condition is satisfied against the conversation transcript. If not, Claude starts another turn automatically.

  • Set a goal: /goal all tests in test/auth pass
  • Check status: /goal
  • Clear a goal: /goal clear
  • Add a turn cap: /goal get the homepage Lighthouse score to 90 or above, stop after 5 tries.

A good condition is something Claude's own output can demonstrate, such as a test exit code or a build result. The evaluator does not run commands independently, so the proof must land in the transcript.

Pi.dev

Pi.dev supports long-running goals through extensions such as pi-goal, Pi-Agent-Goal, and @narumitw/pi-goal. A /goal creates a persistent, branch-aware objective that survives reloads and resumes. The agent first proposes a draft objective and acceptance criteria for review, then can auto-continue across turns until completion, pause, or a token budget is hit.

Common commands:

  • /goal <objective> - start a goal; review the agent's draft, then approve
  • /goal status - show objective, criteria, constraints, progress, and blockers
  • /goal import <path> - pull in a PRD or docs folder as goal context
  • /goal pause / /goal resume - control execution
  • /goal complete / /goal clear - finish or remove the goal

Example: /goal refactor the auth service so all unit tests pass and no public API signatures change, review the draft, then run /goal start (or approve in the UI) and let Pi iterate.

OpenAI Codex

Codex Goals are persistent objectives available from Codex 0.128.0. Enable them with features.goals = true in config.toml or by running codex features enable goals. Once active, /goal keeps Codex working across turns, evaluating the thread's own evidence after each step.

A strong Codex goal defines six things:

  1. Outcome: what should be true when done
  2. Verification surface: the test, benchmark, report, or artifact that proves it
  3. Constraints: what must not regress
  4. Boundaries: which files, tools, or data Codex may use
  5. Iteration policy: how to choose the next action after each attempt
  6. Blocked stop condition: when to stop and report that no defensible path remains

Template:

/goal <desired end state> verified by <specific evidence> while preserving <constraints>. Use <allowed inputs, tools, or boundaries>. Between iterations, <how Codex should choose the next best action>. If blocked or no valid paths remain, <what Codex should report and what would unlock progress>.

Example:

/goal Migrate this codebase from JavaScript to TypeScript. The app should compile in strict mode without explicit `any` type definitions.

Codex will inspect the code, make changes, run the build, and keep iterating until the condition is met, paused, blocked, or the budget runs out.

Clone this wiki locally