The Agent Loop and Supervision Contracts in AI Coding Tools

June 23, 2026 · updated June 25, 2026 · AI Agent Internals: How Coding Agents Really Work (part 3)

▶ Watch on YouTube & subscribe to The Stack Underflow

Every AI coding agent on the market — Cursor, Windsurf, Claude Code, Devin — looks different on the surface. Different UIs, different branding, different pitch decks. But underneath, they all run the same fundamental mechanism: an agent loop. The loop is not a product decision; it is a consequence of how language models work. What actually separates these tools is not the model, not the tooling, and not the UI. It is where you, the human, sit inside that loop — and how the tool enforces that position.

Anthropic’s own analysis of production Claude Code usage found that users approve approximately 93% of permission prompts. That one data point exposes everything: if nearly every prompt gets a rubber-stamp yes, the human is not really in the loop at all — they are just adding latency. The industry response to that problem, from smarter auto-classification to fully autonomous background agents, is what defines the competitive landscape in 2026. Understanding the loop is how you understand the whole field.

The one-sentence version: Every coding agent runs the same think-act-read-decide loop; the only real difference between tools is how often that loop pauses to ask for your approval — and what happens when it does not.

The Agent Loop: Think, Act, Read, Decide

A single tool call almost never finishes the job. Ask an agent to fix a bug and it will read files, run tests, see failures, edit code, and retry — many discrete actions, one coherent task. The mechanism that makes this work is the agent loop, also called the ReAct loop (Reasoning + Acting), a pattern established in the LLM research literature and now implemented by every production coding agent.

Here is the cycle in plain terms:

1. THINK  — the model reads the full context and decides what the next step is
2. ACT    — it emits a tool call (read file, run command, write code, search web...)
3. READ   — the orchestrator executes the tool; the result comes back as text appended
             to the conversation history
4. DECIDE — the model reads that result and asks: "Is the task done?"
            → YES: emit a final text response and exit the loop
            → NO:  go back to step 1

The loop repeats until the model itself decides the work is finished. There is no separate scheduler, no hard-coded sequence of five steps, and no external planner maintaining a to-do list. The model is the program that runs each iteration. Anthropic’s architectural analysis of Claude Code describes the core as “a simple reactive while-loop: the model generates reasoning and tool invocations, the harness executes actions, and results feed the next iteration” (arxiv 2604.14228, 2026).

The context window serves as working memory: each iteration appends the latest tool result to the conversation history that the model reads at the next step. The growing list of observations is the closest thing to a running plan — there is no separate plan object.

This connects directly to the other episodes in this series: the model produces text including tool calls, the orchestrator executes those calls, and MCP is the protocol the orchestrator uses to talk to real tools. The loop is just those components cycling in sequence.

The Context Window Is the Working Memory — and the Constraint

Before we get to supervision contracts, one architectural fact matters more than any other: the context window is not infinite, and what fills it determines what the agent can reason about.

At each loop iteration, the model reads the entire accumulated conversation — all prior tool calls, all results, all assistant reasoning. That accumulation is what gives the agent continuity. It is also what eventually breaks it.

Iteration 1:  [system prompt | user task]
Iteration 5:  [system prompt | user task | tool call 1 | result 1 | tool call 2 | result 2 ...]
Iteration 20: [system prompt | user task | all 19 prior steps — GROWING FAST]

The production problem this creates has a name: context rot — the measurable degradation in model reasoning as the context accumulates noise, failed attempts, and superseded decisions. Research in 2025-2026 found accuracy drops of 30% or more for information buried in the middle of long conversations (the “lost-in-the-middle” effect). Claude Code’s architecture responds to this with five sequential context shapers that run before every model call: budget reduction, lightweight historical trimming, fine-grained compression, context collapse, and as a last resort, model-generated semantic compression (arxiv 2604.14228, 2026). Long-running agent frameworks like Claude Code’s “Ralph loop” pattern add a configurable max-iterations ceiling — typically 20 — as a hard backstop. The loop also terminates when the model emits text without any tool call, when context overflows, or when hooks signal interruption.

Termination triggerWhat causes it
Model decisionModel emits text-only response — task considered done
Max turns reachedConfigurable safety ceiling (e.g. --max-turns 20)
Context overflowContext shapers cannot keep the window manageable
Hook interruptionA PreToolUse or Stop hook returns a block signal
Consecutive denialsIn auto mode: 3 consecutive or 20 total classifier blocks

Where the Human Sits: Six Supervision Contracts

The loop is structurally identical across every major coding agent. What differs is a single design decision: how often does the loop pause and wait for human input?

Claude Code formalizes this into six named permission modes as of v2.1.83 (code.claude.com/docs/en/permission-modes, 2026):

 SUPERVISION DIAL
 ─────────────────────────────────────────────────────────────

 Most oversight                                 Least oversight
      │                                               │
      ▼                                               ▼

 default → acceptEdits → plan → auto → dontAsk → bypassPermissions

 ─────────────────────────────────────────────────────────────
ModeWhat runs without askingBest for
defaultReads onlySensitive work, unfamiliar codebases
acceptEditsReads, file edits, safe filesystem commandsIterating on code you are reviewing
planReads only — proposes a plan first, no edits until approvedExploring before committing to changes
autoEverything, with a background safety classifierLong tasks, reducing approval fatigue
dontAskOnly pre-approved tools from your allow listLocked-down CI/CD pipelines
bypassPermissionsEverything, no checksIsolated containers and VMs only

Other tools map to similar positions on this dial without naming them formally. Cursor’s Composer runs closer to acceptEdits — each suggested diff requires explicit acceptance. Windsurf’s Cascade leans toward auto, executing multi-step workflows with minimal interruption. Devin and background agent platforms sit at the dontAsk end: you delegate a task and review the pull request when it is done.

None of these positions is inherently better. They reflect different trust levels and different task profiles:

  • High-stakes, unfamiliar codebasedefault or plan keeps you in control at the cost of more interruptions.
  • Well-scoped task in a codebase you knowacceptEdits or auto lets you review strategically without babysitting every step.
  • Long-running, well-defined, low-risk work — background agents or dontAsk free you to context-switch entirely.

The 93% Problem and How Auto Mode Solves It

The approval-fatigue data changes how you should think about supervision. If users approve 93% of prompts without meaningful review, then per-action confirmation is not actually supervision — it is theater. The human has left the loop while the UI still pretends otherwise.

Anthropic’s response was auto mode, shipped March 2026. Instead of replacing human approval with no approval, it replaces it with a separate, purpose-built classifier:

Without auto mode:
  Agent wants to run: git push origin main
  → prompt appears → developer clicks OK (probably without reading)
  → command runs

With auto mode:
  Agent wants to run: git push origin main
  → classifier checks: "Does this push to main?" → YES → BLOCKED
  → agent receives block reason → tries alternative branch instead
  → no human involved; no rubber-stamp needed

The classifier architecture uses a two-stage pipeline: a fast single-token filter runs first; only flagged actions proceed to full chain-of-thought reasoning. Critically, the classifier is reasoning-blind — it deliberately strips assistant messages and tool outputs, seeing only user messages and bare tool-call payloads. This prevents the agent from persuading the classifier through rationalization. The classifier runs on Claude Sonnet 4.6 (docs.anthropic.com, 2026).

Auto mode requires Claude Opus 4.6 or later, or Sonnet 4.6, on the Anthropic API. On Amazon Bedrock, Google Vertex AI, and Microsoft Foundry, only Claude Opus 4.7 and Opus 4.8 are supported.

What the classifier blocks by default is instructive — it is a map of what goes wrong in production autonomous agents:

BLOCKED BY DEFAULT IN AUTO MODE
────────────────────────────────────────────
curl | bash          (download + execute)
git push main        (force or direct push)
git reset --hard     (discard uncommitted work)
terraform destroy    (irreversible infra change)
rm -rf [pre-session] (delete files that existed before session started)
Send secrets outside your repo's configured remotes
Grant IAM / repo permissions
────────────────────────────────────────────
ALLOWED BY DEFAULT
────────────────────────────────────────────
Local file ops in working directory
Installing deps from lock files / manifests
Read-only HTTP requests
Pushing to the branch you started on

If the classifier blocks 3 actions in a row or 20 total, auto mode pauses and resumes interactive prompting. Sessions in non-interactive mode abort on repeated blocks — there is no user to consult.

An ASCII View of the Loop and Human Touchpoints

         ┌─────────────────────────────────────────────────┐
         │                   AGENT LOOP                   │
         │                                                 │
  ┌──────▼──────┐     ┌────────────┐     ┌─────────────┐  │
  │   THINK     │────▶│    ACT     │────▶│    READ     │  │
  │  (model)    │     │(tool call) │     │  (result    │  │
  │             │     │            │     │  appended   │  │
  └─────────────┘     └────────────┘     │  to context)│  │
         ▲                               └──────┬──────┘  │
         │            ┌────────────┐            │         │
         └────────────│   DECIDE   │◀───────────┘         │
                      │  done? y/n │                      │
                      └─────┬──────┘                      │
                            │ NO  → loop again            │
                            │ YES → EXIT                  │
         └─────────────────────────────────────────────────┘

Human touchpoints (choose one supervision contract):
  [default/acceptEdits] ── after every ACT that writes or runs
  [plan] ──────────────── once, before the first ACT
  [auto] ──────────────── classifier runs instead; human only on block
  [dontAsk/bypass] ────── only after EXIT (or never)

How to Apply This Right Now

The supervision contract is a configuration choice. Here is how to make it deliberately:

  1. Start every new codebase in plan mode. Let the agent read and propose — then read the plan before approving. You learn how the agent understands the code. This is also safer before you have established trust in how the agent behaves on this specific repo.

  2. Graduate to acceptEdits once you trust the direction. You get file changes without per-edit prompts, but shell commands still pause. This is the right mode for most iterative development sessions.

  3. Use auto for long, well-scoped tasks. Auto mode is not a shortcut — it is a different supervision model. The classifier watches for boundary violations; you review the final diff in git. Set up deny rules for anything the classifier does not know about (your deploy scripts, your secrets manager).

  4. Never use bypassPermissions outside a container. The December 2025 incident where rm -rf ~/ destroyed a user’s home directory happened in a session without proper isolation. Run bypass-permissions agents in a dev container or VM with no access to your host filesystem.

  5. Add PreToolUse hooks for irreversible actions. Even in auto mode, you can register hooks that fire before specific tools. A hook in front of git push, Bash(terraform*), or Bash(rm*) adds a deterministic check that the model cannot reason around.

  6. Set --max-turns for background jobs. Unbounded loops are how you get agents that spin for hours accomplishing nothing useful. A ceiling of 20-50 turns is a sensible starting point for most agentic tasks.

Common Misconceptions

“Different agents use fundamentally different AI architectures.” The think-act-read-decide loop is structurally the same across Claude Code, Cursor Agent Mode, Windsurf Cascade, and Devin. What changes is the supervision contract and the default tool access, not the loop architecture.

“The agent has a stored plan it works through step by step.” There is no separate plan object. The model re-evaluates the full conversation context at every iteration. The growing list of tool results in the context window is the closest thing to a plan. This is why agent behavior can look surprisingly adaptive — and why context rot eventually degrades it.

“Fully autonomous means the agent is smarter.” Autonomy is a trust setting, not a capability level. A fully autonomous agent with a bad initial prompt will confidently do the wrong thing for a long time without you noticing. The supervision contract controls how quickly you can catch and correct that.

“Per-action review keeps you safe.” The 93% approval rate shows it does not. If you approve everything on autopilot, you have created the illusion of oversight without the substance. Auto mode with a well-configured classifier is actually safer in practice for long tasks, because the classifier does not get fatigued.

Frequently Asked Questions

What actually stops the loop from running forever?

The model itself decides to stop — it emits a final text response instead of another tool call. Most agent frameworks also enforce a max-turns ceiling as a backstop. In Claude Code auto mode, the loop also falls back to interactive prompting if the classifier blocks 3 consecutive or 20 total actions. In non-interactive (-p) mode, repeated blocks abort the session entirely.

If the loop is the same everywhere, why do agents feel so different to use?

UX, supervision contract, and default tool access. Cursor’s per-action diff approval feels interactive and controlled. Windsurf’s Cascade feels like delegating a task. Devin’s background run feels hands-off. All three are the same loop with different pause points, different tool sets, and different default permission postures.

Can I change the supervision level mid-task?

Yes, in Claude Code. Press Shift+Tab to cycle through default, acceptEdits, and plan during a session. auto mode appears in the cycle once your account qualifies. You can also switch programmatically via the Agent SDK permissionMode option. In Cursor and Windsurf the contract is more tightly coupled to the product mode you started in.

Does the model remember what it did in previous sessions?

Only through the context window for the current session. Each iteration appends tool results to the history the model reads. Once a session ends and the context is cleared, the model starts fresh. Persistent memory across sessions is a separate architectural layer — CLAUDE.md files, external databases, structured memory MCP servers — not part of the base loop. The resume option in the Agent SDK lets you reattach to a saved session state, but the underlying model still only sees what is in the reconstructed context window.

How do background agents differ from in-session agents?

A background agent runs the same loop in a separate process or on remote infrastructure, outside your current terminal session. Cursor Background Agents (introduced mid-2025) can pick up Linear tickets and post pull requests. Claude Code’s Managed Agents run on Anthropic-hosted infrastructure with sandboxed sessions accessible via REST API. The loop mechanics are identical; what changes is who manages the execution environment, how you observe progress, and what the agent can reach.

What model should I use for auto mode?

As of mid-2026, Claude Code auto mode requires Claude Opus 4.6 or Sonnet 4.6 on the Anthropic API, or Claude Opus 4.7/Opus 4.8 on Amazon Bedrock, Google Vertex AI, and Microsoft Foundry (code.claude.com/docs/en/permission-modes, 2026). Older models including Haiku 4.5, Sonnet 4.5, and all claude-3 models are not supported for auto mode.

Where This Fits in the Series

This is episode three of AI Agent Internals. Episode one covered the model-plus-orchestrator split. Episode two explained MCP as the protocol connecting the orchestrator to real tools. This episode completes the picture by showing how those components cycle in a loop, and how the supervision contract is what you are actually choosing when you pick a coding agent.

To go deeper on the context window as working memory — including what context rot looks like in production and how to defend against it — read Context Rot Explained and Bigger Context Windows, Worse Memory.

Episode four goes granular: from a high-level instruction like “create a GitHub issue” all the way down to the raw API call that makes it happen — What Happens When an Agent Uses a Tool.

If you are seeing agents drift or fail silently over long sessions, Subagent Isolation and Context Rot covers the patterns that contain it.

Browse all tutorials to follow the full series.

Found this useful? The deep version lives on YouTube — new breakdowns of how AI dev tools actually work, weekly.

Subscribe on YouTube →