Systems Architecture··4 min read·By Sophia Stein

Loop Engineering: How Production AI Agents Run Without Breaking Code

Isolated git worktrees, deterministic tests, and hard dollar caps that stop chaos.

30-second summary · 3 key takeaways▾
  • ·Unbounded agent retry loops amplify hallucinations, dirty shared working trees, and burn runaway API spend overnight.
  • ·Production loop engineering pairs disposable git worktrees with deterministic compilers, test suites, and schema verifiers.
  • ·Hard retry caps and per-ticket dollar circuit breakers guarantee predictable unit economics and two-minute human reviews.
Architectural drafting table with geometric circle-and-line drawings, steel compass, and forest-green pencil
Jump to section (4)

Over the past two years, I have watched applied AI engineering climb four distinct rungs: single-turn prompt phrasing, versioned AGENTS.md context files, typed tool harnesses, and full loop engineering. Teams whose rollouts stall in week two almost always write repository instructions while skipping independent post-step verifiers and hard stopping budgets. Without an external check, a faster model simply ships plausible regressions faster.

The five building blocks of a closed-loop agent system

1. Scoped Trigger Labeled Linear issue, CI failure, or cron 2. Git Worktree Disposable branch or isolated microVM 3. External Verifier tsc + vitest / pytest JSON Schema + link check Feeds stderr to retry Max 3 tries / $1.50 cap 4. Draft PR Verifier receipt 2-min human merge
Figure 1: Never let a generator grade its own homework; gate every iteration on an independent deterministic verifier and hard retry budget.

Why generators must never grade their own output

Asking the same LLM "Does this diff look right?" is theater, not verification. Because the generator carries the exact blind spots that produced the bug, self-critique routinely rubber-stamps broken imports, subtle SQL drift, and hallucinated package flags. Closed-loop control replaces self-reflection with five deterministic engineering boundaries:

Loop Component Fragile Prototype Production Loop Standard
1. Trigger Manual copy-paste into chat sidebar Scoped webhook, CI failure event, or labeled ticket
2. Isolation Editing shared main or live records Disposable git worktree, container, or microVM
3. Tool Surface Unscoped 80-tool catalogs in prompt Concise AGENTS.md + audited least-privilege MCP set
4. Verifier Self-critique prompt from the generator Deterministic tsc + unit tests + regression evals
5. Circuit Breaker Open-ended retries until context overflows Max 3 repair passes + hard dollar cap -> human escalation

Notice how each row removes a class of silent human toil. Scoped triggers stop vague mega-prompts before they start, disposable worktrees protect your primary branch, and external verifiers give the model objective ground truth instead of subjective prose encouragement.

Separating inner, middle, and outer feedback loops

Inner loop: seconds-scale compiler and test repair

Inside a disposable git worktree, each worker checks out an isolated branch with its own temporary test database so five parallel tickets never clobber lockfiles or uncommitted edits. The agent proposes a diff, runs sub-ten-second typechecks and targeted unit tests, and receives only concise stderr diagnostics rather than thousand-line stack dumps.

Feeding exact compiler and schema errors back across at most three repair attempts routinely lifts task completion from roughly fifty-five percent on Attempt 1 past eighty-five percent by Attempt 3. If the third pass still fails, a clean git worktree remove discards the broken state cleanly with zero repository pollution.

Middle and outer loops: async draft queues and weekly hygiene

In the middle loop, scheduled background workers from daily coding-agent infrastructure process bounded maintenance queues (stale test repairs, schema syncs, doc updates) and open draft pull requests with verifier receipts attached. Every Friday in the outer loop, engineering leads inspect rejected traces, add one clarified rule to AGENTS.md, and tune model tiers using The Sovereign Stack.

Enforcing hard retry and dollar circuit breakers in TypeScript

Fail closed to a human gate instead of burning overnight spend

Unattended weekend queues without hard stopping rules eventually hit a pathological dependency conflict and burn hundreds of dollars repeating the exact same failed test command. Wrapping every loop in code-enforced retry, wall-clock, and dollar caps protects startup token budgets and routes stuck edge cases with full compiler context to a human approval gate:

export interface LoopBudget {
  maxIterations: number // e.g. 3 repair passes max
  maxCostUsd: number    // e.g. $1.50 per ticket ceiling
  timeoutMs: number     // e.g. 180_000 (3 minutes)
}

export async function runVerifiedLoop<T>(
  propose: (attempt: number, feedback: string) => Promise<{ output: T; costUsd: number }>,
  verifyDeterministic: (output: T) => Promise<{ passed: boolean; diagnostics: string }>,
  budget: LoopBudget,
) {
  let spentUsd = 0
  let feedback = ''
  const startedAt = Date.now()

  for (let attempt = 1; attempt <= budget.maxIterations; attempt++) {
    if (Date.now() - startedAt > budget.timeoutMs) {
      return { status: 'escalate_human' as const, reason: 'timeout_exceeded', spentUsd, feedback }
    }
    const step = await propose(attempt, feedback)
    spentUsd += step.costUsd
    const check = await verifyDeterministic(step.output)
    if (check.passed) {
      return { status: 'converged' as const, output: step.output, attempt, spentUsd }
    }
    feedback = check.diagnostics
    if (spentUsd >= budget.maxCostUsd) {
      return { status: 'escalate_human' as const, reason: 'cost_ceiling_hit', spentUsd, feedback }
    }
  }
  return { status: 'escalate_human' as const, reason: 'max_iterations_exhausted', spentUsd, feedback }
}

Notice what happens when maxIterations or maxCostUsd trips at two in the morning. Instead of force-committing a half-working workaround or spinning until rate limits fire, runVerifiedLoop halts cleanly and attaches the exact compiler failure and cumulative spend to the ticket for a morning engineer.

Telemetry metrics and a copy-paste loop readiness checklist

Four convergence metrics that matter more than demos

First, track First-Pass Verifier Rate: the share of scoped tickets clearing tsc, unit tests, and schema checks on Attempt 1. Whenever first-pass convergence drops below fifty percent, tighten AGENTS.md or split the ticket into smaller steps instead of raising maxIterations.

Second, monitor Three-Try Convergence Rate alongside All-In Cost per Merged PR, dividing total orchestrator and worker spend strictly by merged pull requests to expose chatty models that burn retries without converging. Fourth, measure Human Review Time to Merge; if reviewers need twenty minutes instead of two, shrink the trigger blast radius.

Logging these four numbers in a simple weekly table ends emotional debates over which coding model "feels smarter" in ad-hoc chats. Models and prompt revisions earn production traffic strictly by raising three-try convergence or lowering cost per merged diff against your simulation sandbox.

Copy-paste production loop readiness checklist

Verify every item below before enabling unattended agent loops in CI:

# Closed-Loop Agent Readiness Checklist
- [ ] Run every attempt inside a fresh `git worktree` or ephemeral container (zero shared working trees)
- [ ] Wire a deterministic external verifier (`tsc`, `vitest`/`pytest`, JSON Schema) returning concise `stderr`
- [ ] Enforce `maxIterations <= 3`, `timeoutMs <= 180000`, and a hard per-run `maxCostUsd` cap in code
- [ ] Attach full verifier receipts and token spend to every draft PR or escalated ticket
- [ ] Route exhausted or high-blast-radius runs to a Level-2 human gate (never force-merge red builds)
- [ ] Review failed weekly traces every Friday to add one `AGENTS.md` rule or golden test fixture

When deploying long-running workers, pair durable state checkpoints (Cloudflare Agents durable execution patterns) with single-owner state machines from Why Multi-Agent Swarms Fail in Production and the worker-escalation cascade in How to Cut AI Agent Costs by 70%.

To build production harnesses hands-on, explore Courses or book an architecture review on Work With Me.

INTERACTIVE EXPLANATORY WORKBENCH

Workflow Capacity & Readiness Calculator

Estimated Capacity Reclaimed

369 hours/yr (450 manual hrs)

Ship Draft-First Loop This Week (shared Markdown folder + 10-second review)

Reference URL · agenticarchitect.ai/blog/loop-engineering

Weekly field notes on what new AI makes possible

One concise dispatch each week bridging frontier capabilities, business implications, and systems you can actually run.

Written by Sophia Stein in Boulder, CO. Want practical guides or hands-on help for your team? Read the free lessons & email course, grab the Workflow Starter Kit, or explore fractional AI & consulting.

Read next in Systems Architecture

View track →