The Tech ArchiveThe Tech ArchiveThe Tech Archive
Small BusinessMarketingDevelopers
ArticlesTopicsSeriesAbout

Get the practical AI brief

Verified, no-hype AI tips you can actually use - in your inbox. Free.

No spam. We verify what we send. Unsubscribe anytime.

The Tech ArchiveThe Tech Archive

The Tech Archive

AI news, analysis & explainers

AboutSmall BusinessMarketingDevelopersArticlesTopicsSeriesMethodologyAI DisclosureCorrections

© 2026 All rights reserved.

Back to home
0 readers reading
  1. Home
  2. Articles
  3. Artificial Intelligence
  4. How to Engineer AI Agent Loops That Are Safe for Production Codebases (2026)

Contents

How to Engineer AI Agent Loops That Are Safe for Production Codebases (2026)
Artificial Intelligence

How to Engineer AI Agent Loops That Are Safe for Production Codebases (2026)

Agent loop engineering turns control theory into a safe framework for AI coding agents. Here's how to build sense-decide-act loops with sensors, controllers, and human feedback.

Sham

Sham

AI Engineer & Founder, The Tech Archive

18 min read
2 views
July 30, 2026

The safest way to put an AI coding agent in charge of a production codebase is to stop feeding it prompts and start building a control loop around it — a sense-decide-act cycle borrowed from control systems engineering that drives your codebase toward a desired state one small, reviewable change at a time. The "blind loop" (a bash script that prompts an agent forever and dumps 40,000-line PRs nobody reads) is the failure mode everyone is cautioning against. The fix is a sensor that measures violations, a controller that picks the smallest safe change, and an actuator agent that applies it and opens a PR you can actually review.

This approach works where it matters: large, complex codebases with real customers, regulatory obligations, and SLAs — not just solo greenfield projects with unlimited token budgets.

Last verified: 2026-07-30 · A control-theory framework for agentic coding loops · Best for: teams on shared codebases with human review gates

TL;DR

  • Agent loop engineering applies control theory to AI coding agents: define a set point (desired state), build a sensor (measure violations), design a controller (pick the smallest change), and actuate (agent + skill applies it).
  • The blind loop is the enemy: prompting an agent indefinitely produces massive PRs nobody reviews — the opposite of what control loops achieve.
  • Sensors can be deterministic (ast-grep patterns, ESLint rules, type checks) or non-deterministic (agent + natural language rules, or a hybrid).
  • A version-controlled feedback file lets humans steer the loop by leaving /iterate comments on PRs — the agent updates the file, so corrections persist across runs.
  • Flow control prevents PR stacking: if the last PR from a loop is still open, the loop shuts down until a human reviews it.
  • This is a real pattern used in production, and the broader ecosystem calls it "loop engineering" — named by Peter Steinberger and Boris Cherny's June 2026 statements.

What Is an Agentic Control Loop?

An agentic control loop is a cyclic process that drives a codebase toward a desired state by repeatedly measuring the gap between current and desired states, deciding on an incremental change, and applying it — using an AI agent as the actuator. It is the software engineering equivalent of what a thermostat does for temperature, or what a Kubernetes controller does for cluster state.

The five components map directly from control theory:

Component Control theory role In an agent loop
Set point The desired state of the system "All RPC procedures use Effect for error handling" or "zero ESLint warnings"
Sensor Measures current state and computes error ast-grep scan, ESLint, type checker, or an agent reading the codebase
Controller Reads the error and decides the change Picks the smallest violation, or uses telemetry to prioritize the highest-error procedure
Actuator Applies the change to the system Your coding agent (Claude Code, Codex, etc.) + a skill/prompt that tells it what to do
Disturbance External changes to the system Teammates shipping code that introduces new violations

Control loops work because they change a system incrementally rather than trying to reach the end state all at once. This minimizes risk, avoids oversteering, and — critically for AI agents — produces changes small enough that a human can actually review them.

Why Blind Loops Fail (and Control Loops Don't)

The discourse around AI coding agents in 2026 centers on the idea that you should "design loops that prompt your agents," as Peter Steinberger, creator of OpenClaw, wrote on June 8, 2026 in a post that reached over 6.5 million views. Boris Cherny, who created Claude Code at Anthropic, said the same thing: "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." (source)

But there is a trap hiding in that advice. A blind loop — a simple bash loop that pipes a prompt to an agent and lets it run indefinitely — does not implement control theory. It has no sensor, no measured error, no controller picking the smallest safe change. It just generates code until you stop it. The result is exactly what teams are warning about: PRs so large that nobody reviews them, and code so expensive that "bad code is much more expensive in the age of agents than it has ever been at any point in the past" (as Matt Peco and others have observed).

A well-tuned control loop is the opposite:

  1. It senses a specific, measurable problem (e.g., "37 unmigrated procedures").
  2. It picks one — the smallest, lowest-risk violation.
  3. It actuates — the agent applies the change to that one procedure.
  4. It commits and PRs — deterministically, using the agent's response as the PR description.
  5. It stops until a human reviews the PR (flow control).

The difference is not academic. One produces PRs a human can review in 5 minutes. The other produces PRs that take 3 hours and get rubber-stamped — or worse, never reviewed at all.

For a deeper look at the broader agent evaluation methodology that informs these loops, see our guide on how to build closed-loop AI agent evaluation at production scale.

How Do You Build the Sensor?

The sensor is the component that measures the current state of your codebase and identifies the gap between it and your set point. It is the foundation of the entire loop — without a reliable sensor, you have no measured error, and the controller is flying blind.

Deterministic sensors

The most reliable sensors are deterministic tools that run outside your agent's context:

  • ast-grep (sg): A CLI tool for structural code search, lint, and rewriting based on abstract syntax trees. It is language-agnostic, works out-of-band from your TypeScript config or ESLint rules (which agents can disable with inline comments), and lets you write code-like patterns to find violations. For example, a rule can find all unmigrated procedures by matching a specific syntactic pattern.
  • ESLint / Prettier: Standard linting rules that catch code quality issues.
  • TypeScript compiler (tsc): Catches type errors and missing implementations.
  • 打包 (pack) / build checks: Ensures the codebase compiles.

The advantage of deterministic sensors is reliability — they always produce the same output for the same input, which means your controller can sort violations deterministically and always pick the same one first.

Non-deterministic sensors

You can also use an agent as a sensor: give it a skill (a set of natural language rules describing what to look for) and let it scan the codebase. This is less reliable but more flexible — it can catch patterns that are hard to express in ast-grep syntax.

Hybrid sensors (the practical choice)

In practice, the best sensors combine both: a deterministic tool (ast-grep) produces a raw list of violations, and an agent — optionally — filters or contextualizes them. For instance, you can use ast-grep to find all unmigrated procedures, then have an agent check which ones are actually imported and used (to avoid migrating dead code).

How Do You Design the Controller?

The controller reads the sensor output (the list of violations) and decides which change to make. This is where "incremental" becomes the operative word.

Simple controller: pick the first violation

The simplest controller deterministically picks the first violation from a sorted list. Sort by file path and line number, and you always get the same violation. Use bash and jq to extract it:

# Sort violations deterministically, pick the first one
cat violations.json | jq -r '.[] | "\(.path):\(.line) \(.rule)"' | sort | head -1

Smarter controller: pick the smallest violation

Use ast-grep to measure the size (line count) of each unmigrated procedure, and always pick the smallest one. This reduces risk — smaller procedures are easier to migrate correctly and produce smaller PRs.

Telemetry-driven controller: prioritize by impact

The most powerful controller doesn't just migrate for the sake of migration — it looks at your telemetry (APM, error logs) to figure out which unmigrated procedures have the most errors or the least instrumentation, and migrates those first. When you send the control signal to the actuator agent, you include not just the procedure to migrate but all the data about why — so the agent can actually improve the code rather than just doing a one-to-one translation.

Controller type How it picks Risk level Best for
First violation (sorted) Deterministic sort, head -1 Low Getting started, uniform tasks
Smallest violation ast-grep line count, min Lowest Complex migrations where errors are costly
Telemetry-driven Highest-error procedure from APM Medium Maximizing impact per iteration
Agent-picked LLM reads violations, decides Highest Pattern detection beyond deterministic rules

Rule of thumb: Never send an agent to do deterministic code's job. Use bash, jq, and ast-grep for the parts you can — and reserve LLM reasoning for the parts you genuinely cannot express deterministically.

For the broader framework on treating agent improvements like machine learning rollouts, see our guide on agent evaluation as a rollout.

How Do You Build the Actuator?

The actuator is your coding agent plus a skill — a set of instructions that tells it how to do the specific task (migrate a procedure, fix a lint violation, refactor a component). The skill should include:

  1. Golden patterns: Hand-written, idiomatic examples that the agent should follow. Agents are pattern replicators — without gold-standard examples, you get whatever is in the docs or the training data, which is often outdated or wrong for your specific codebase.
  2. A response template: The agent's final output should follow a consistent format so you can deterministically parse it, commit the code, and generate the PR description from it.
  3. Context from the controller: The control signal (which procedure to migrate, why it matters, what data from telemetry shows the problem).

The actuator does not need to be one-shot. Your agent may work through several iterations within its context window before producing a final response. But the key is that the loop's actuator produces one PR per loop iteration — not an unbounded stream of changes.

How Do You Run the Loop in CI/CD?

You don't need a new cluster or orchestration system. Use the CI/CD tool you already have — GitHub Actions, GitLab CI, CircleCI — because it already has access to your code, your secrets, and great dispatch and scheduling primitives.

Here's the workflow:

  1. Schedule: Run once a day (or on a cron schedule).
  2. Sense: Run the sensor (ast-grep, linters) on the latest main.
  3. Control: Pick the next violation (smallest, highest-impact, or first sorted).
  4. Actuate: Feed the skill + control signal to your coding agent; it produces a change.
  5. Commit and PR: Deterministically commit, push, and create a PR using the agent's response as the description.
  6. Label: Attach a unique label to the PR (e.g., loop:effect-migration) so the workflow can identify its own PRs later.

The result: every morning you walk in to a small, incremental PR that is low-risk and takes minutes to review.

How Do You Steer the Loop Without Stopping It?

The first time you run a loop, it will produce bad PRs. The skill won't be right, the agent will make mistakes, and you'll need to update the skill constantly. This is where most teams give up.

The solution is a feedback file — a markdown file tracked in version control that the loop loads into the actuator agent's context on every run. Here's how it works:

  1. Create a FEEDBACK.md file in your repo (or in the loop's config directory).
  2. The workflow deterministically loads this file into the agent's context after running the controller.
  3. Add a comment trigger to the workflow: when a reviewer leaves /iterate on a PR created by the loop, the workflow picks it up, loads all the PR context (diff, comments, review comments, description) into the agent, and instructs it to fix the code and update the feedback file.

The benefit: the feedback file becomes a version-controlled log of how you've steered the loop over time. You can see every correction, revert bad feedback, and watch the agent's behavior improve as the feedback file grows. This is especially powerful because the corrections survive across runs — the next time the loop runs, it loads the updated feedback file and avoids the same mistakes.

How Do You Prevent PR Stacking With Flow Control?

If you travel for a week or spend six days on slides instead of reviewing code, your daily loops will stack up: duplicate work, conflicting branches, and a backlog of unreviewed PRs. The fix is simple:

Before running sense-control-actuate, check if any PR with this loop's label is still open. If yes, shut down this run.

# GitHub Actions workflow (simplified)
- name: Check for open PRs from this loop
  run: |
    OPEN_PRS=$(gh pr list --label "loop:effect-migration" --state open | wc -l)
    if [ "$OPEN_PRS" -gt 0 ]; then
      echo "Open PR exists from this loop — skipping this run."
      exit 0
    fi

This ensures exactly one PR is open per loop at any time. No stacking, no duplication, no conflicts — and no work generated that nobody gets around to reviewing. The loop only runs again after a human has reviewed and merged (or closed) the previous PR.

How Do You Speed Up Once You Trust the Loop?

When you have 150 procedures to migrate at one per day, the full migration takes six months. Once you trust the loop, there are three ways to increase velocity:

  1. Batch the controller output: Pick 3 or 5 procedures per iteration instead of 1.
  2. Separate context windows: Pick 3 procedures, then run each migration in a separate implementation phase (separate agent context window). This is both cheaper and more reliable — each migration gets its own clean context.
  3. Distribute to the team: Run the workflow 4 times and give one PR to each of 4 engineers. This scales linearly with team size and distributes the review load.
Velocity strategy PRs per day Risk Review load
1 procedure per iteration 1 Lowest 1 reviewer, 5 min
3-5 procedures per iteration 3-5 Medium 1 reviewer, 15-25 min
Separate context windows 3-5 Low 1 reviewer, 15 min (cleaner diffs)
Run 4x, distribute to 4 engineers 4 Low 4 reviewers, 5 min each

Start with 1 per day until you trust the loop. Then scale — don't start fast and scale back.

What Can You Use Control Loops For Beyond Migrations?

The control loop pattern is not limited to code migrations. Any codebase property you can measure, change incrementally, and get feedback on is a candidate:

  • API compliance: Ensure your API matches an OpenAPI spec or MCP specification version.
  • Cross-language mirroring: Mirror a project from Python to TypeScript (or vice versa), keeping the port in sync with upstream changes.
  • Slop cleanup: Continuously remove AI-generated code patterns that don't match your team's standards (React Doctor is a great example of a hybrid sensor/controller for React).
  • Dependency updates: Detect outdated dependencies, pick the smallest update, and have the agent apply it and run tests.
  • Test coverage gaps: Find untested functions, generate tests, and open PRs — one at a time, each one reviewable. For the broader pattern of building self-improving agent loops, see our deep dive on building a signal-to-PR loop.
  • Documentation drift: Detect functions whose comments are out of sync with their implementation and have the agent update them.

The key questions are always the same: Can you measure it? Can you apply changes incrementally? Can you get feedback on the quality of those changes? If yes, you can build a control loop for it.

What This Means for You

If you're an engineering team lead or a developer working on a shared codebase with real customers:

  1. Start with one measurable property — pick something your team has been deferring (a migration, lint cleanup, test coverage). Define the set point and build a sensor with ast-grep or your existing linters.
  2. Keep the first loop simple: one violation per day, deterministic controller, small PRs that take 5 minutes to review.
  3. Invest in the skill upfront and iterate on it via feedback files — the skill is where the quality comes from, not the model.
  4. Add flow control early: prevent PR stacking before it becomes a problem, not after.
  5. Scale gradually: batch only after you trust the loop, and distribute to the team when you need more velocity.

The future of agentic coding is not swarms of agents designating loops to prompt agents building swarms for loops. It is controlled, incremental, human-reviewed loops that make your codebase better — one PR at a time. For setting up an agent fleet to manage multiple loops, our Hermes Agent fleet setup guide walks through the infrastructure.

FAQ

Q: What is the difference between a blind loop and a control loop?

A: A blind loop prompts an agent indefinitely without measuring the result — it produces large, unreviewable PRs. A control loop has a sensor that measures violations, a controller that picks the smallest safe change, and an actuator that applies it. The control loop stops after each iteration and waits for human review.

Q: Do I need a special orchestration tool to run agent loops?

A: No. Use your existing CI/CD system (GitHub Actions, GitLab CI, CircleCI). It already has access to your code, secrets, and scheduling primitives. You do not need a new cluster or specialized agent orchestration platform.

Q: What tool should I use as the sensor?

A: ast-grep is ideal for structural code pattern matching — it is language-agnostic, runs out-of-band from your project config (so agents can't disable it), and uses AST matching rather than text matching. Combine it with ESLint, tsc, or your existing linters for full coverage. For patterns that cannot be expressed structurally, use an agent with natural language rules.

Q: How do I correct an agent loop that is producing bad PRs?

A: Create a feedback file (e.g., FEEDBACK.md) tracked in version control. When you leave a /iterate comment on a PR, the workflow loads the PR's diff, comments, and review feedback into the agent's context, fixes the code, and updates the feedback file. The corrected instructions persist across all future runs. You can see how the feedback evolved over time in git history and revert bad corrections.

Q: How do I prevent PR stacking when I'm away from reviewing?

A: Add a flow control step at the beginning of the workflow: query your Git provider's API for PRs with the loop's label. If any are still open, skip the entire run. This ensures at most one open PR per loop at any time.

Q: Is loop engineering only for solo developers with unlimited token budgets?

A: No. The control loop pattern is specifically designed for teams on shared codebases with review gates. The incremental, one-PR-at-a-time approach is what makes it safe for production systems with customers, regulatory obligations, and SLAs. Cloud-native infrastructure like Kubernetes has used reconciliation control loops for years — the pattern is battle-tested at scale.

Sources
  1. ast-grep: Structural code search, lint, and rewriting tool — ast-grep.github.io · GitHub: ast-grep/ast-grep
  2. Effect: Production-grade TypeScript standard library — effect.website
  3. Kubernetes reconciliation loop pattern — kubernetes.io/docs/concepts/architecture/controller
  4. Peter Steinberger, "You should be designing loops that prompt your agents" (June 8, 2026) — x.com/steipete/status/2063697162748260627
  5. Boris Cherny on loop engineering — Pebblous summary: blog.pebblous.ai/blog/loop-engineering/en · Knowledge base: cocodedk.github.io/loop-engineering
  6. Anthropic 2026 Agentic Coding Trends Report — resources.anthropic.com
  7. Geoffrey Huntley: Ralph (the "blind loop" archetype) — ghuntley.com/ralph · HumanLayer: Brief history of ralph — humanlayer.dev/blog/brief-history-of-ralph
Updates & Corrections
  • 2026-07-30 — Initial publication. Verified all tool names (ast-grep, Effect, GitHub Actions), quotes (Steinberger, Cherny), and the Kubernetes control loop parallel against primary sources.

Get the practical AI brief

Verified, no-hype AI tips you can actually use - in your inbox. Free.

No spam. We verify what we send. Unsubscribe anytime.

Tags

#"agent loops"#["AI agents"#"agentic coding"#"Coding Agents"]#"control theory"#"Loop Engineering"

Discussion

0 comments
Sham

Sham

AI Engineer & Founder, The Tech Archive

AI engineer (Azure AI-102/AI-900). Writes practical, tested, hype-free guides on using AI for real work and small business at The Tech Archive.

Related Articles

View all
Google Antigravity for Business Automation: How to Build Your First Agent Dashboard in 2026
Artificial Intelligence

Google Antigravity for Business Automation: How to Build Your First Agent Dashboard in 2026

16 min
Hermes Agent New Features in 2026: Session DB Optimization, Offline Whiteboards, and Agent Swarms Explained
Artificial Intelligence

Hermes Agent New Features in 2026: Session DB Optimization, Offline Whiteboards, and Agent Swarms Explained

15 min
Genspark SecondBrain: How Persistent Memory Makes AI Agents Actually Remember Your Work (2026)
Artificial Intelligence

Genspark SecondBrain: How Persistent Memory Makes AI Agents Actually Remember Your Work (2026)

18 min
Claude Code iOS Simulator Integration in 2026: Setup, Use, and the Enterprise Catch Nobody Talks About
Artificial Intelligence

Claude Code iOS Simulator Integration in 2026: Setup, Use, and the Enterprise Catch Nobody Talks About

19 min
How to Automate Email Outreach With an AI Agent in 2026 (The Self-Driving Inbox)
Artificial Intelligence

How to Automate Email Outreach With an AI Agent in 2026 (The Self-Driving Inbox)

15 min
Gemini Notebook (Formerly NotebookLM) in 2026: The Complete Update Guide for SEO and Content Research
Artificial Intelligence

Gemini Notebook (Formerly NotebookLM) in 2026: The Complete Update Guide for SEO and Content Research

14 min