Plan → Scoped Edit → Verify / Cursor Rules / small diffs / acceptance checklists / loop debugging
You open Cursor, Claude Code, or Copilot Workspace to ship a feature. Two hours later you are still at it: the Agent fixes file A, tests fail; it patches file B, and A breaks again. You say “try again,” and it rewrites code that worked yesterday. This is not a sign that the model is dumb. It is a sign that you are missing a repeatable AI Coding Workflow — planning, scoping, and verification are blended into one messy step, so the Agent keeps iterating on the same wrong assumption.
Across teams we work with in 2026, the pattern is consistent: engineers who treat AI as a junior pair programmer with a checklist finish faster than those who treat it as an oracle. The workflow that holds up is simple on paper and hard to stick to in practice: Plan before you touch code, change one small slice per round, and Verify before moving on. Combined with Cursor Rules and small Git commits, we have seen the same bug go from eight edit rounds down to two. If you are also standing up an MCP server on a cloud Mac or evaluating open-source AI Agent projects on GitHub, this same discipline applies — agents that call tools need boundaries even more than agents that only edit files.
Why does AI get stuck in endless edit loops?
Agent mode is, at its core, trial and error inside an uncertain environment. When you say “fix the login bug,” the model does not know whether you mean an OAuth callback mismatch, an expired session cookie, or a frontend route guard. It picks the most plausible hypothesis, edits code, runs tests, fails, and pivots. Each round partially invalidates the last round. Diffs grow. The conversation fills with contradictory patches. Eventually you are not debugging the original bug — you are debugging the debugging.
Humans fall into the same trap when they skip design and start coding. The difference is that a tired human will eventually stop and whiteboard. An Agent will happily generate round seventeen unless you change the process.
Three root causes
- Vague goals — Without a written definition of “done,” the model reverse-engineers intent from test failures. Stack traces point at symptoms, not root causes, so each guess is a coin flip.
- Uncontrolled scope — One task spans ten or more files. While fixing auth, the Agent refactors a shared util module and introduces a regression three layers away.
- No verification gate — There is no hard rule that says “tests must pass before the next task.” On failure, the default strategy becomes “generate another version” instead of “revert and re-plan.”
Rule of thumb: if you have said “no, try again” three times in a row, the problem is not the model. The task needs a fresh Plan.
Recognizing the loop early saves hours. Watch for these signals: the diff touches files you never mentioned; the Agent apologizes and promises a “complete rewrite”; test output shrinks to a single line while the real error lived ten lines higher in stderr. Each is a cue to stop editing and start planning.
Three-stage workflow: Plan → Scoped Edit → Verify
Splitting every AI collaboration into three non-skippable stages beats upgrading to a stronger model for most teams. The stages are sequential gates, not suggestions.
- Plan — Use Plan mode or a conversation-only session. List files to touch, files to leave alone, and the exact commands that prove success (e.g.
npm test -- auth). Output a pasteable task spec.Do not let the Agent start editing immediately— confirm the spec first. - Scoped Edit — State explicitly: “Only change
src/auth/login.ts; do not touch other files.” Target one to three files and fewer than 200 net lines per round. - Verify — Run tests, lint, and a manual smoke check. Pass → commit and move to the next task. Fail → return to Plan with the full error log, not a vague “still broken.”
The workflow sounds bureaucratic until you time it. A ten-minute Plan that prevents four wasted Agent rounds is a bargain. Teams that skip Plan often spend forty minutes watching the model thrash.
| Stage | Recommended tool / mode | Deliverable | Common mistake |
|---|---|---|---|
| Plan | Cursor Plan / chat-only | Task spec + file list | Spec is long but still vague |
| Scoped Edit | Agent + @file references | Small diff / PR | Opportunistic refactors in unrelated code |
| Verify | Terminal / CI / Cmd+test shortcut | Green tests + commit | Skipping tests and starting the next task |
Think of Verify as a contract between you and the Agent. If verification is fuzzy — “it should feel faster” — the Agent will declare victory at the first compile success. Write acceptance criteria the same way you would for a human contractor: observable, testable, bounded.
Prompt structure: goals, boundaries, and acceptance in one pass
A structured prompt removes guesswork. Copy the template below and replace the placeholders with your project details.
## Goal
(One sentence: user reaches dashboard within 3 seconds of clicking Login)
## Scope
- Change only: src/auth/login.ts, src/auth/session.ts
- Do not change: routing, styles, other modules
## Acceptance
- npm test -- --grep "login"
- Manual: wrong password shows "Invalid email or password" without revealing whether the account exists
## Context
- Current error: (paste full stack trace)
- Conventions: sessions stored in Redis; see docs/auth.md
This layout mirrors what Anthropic recommends in Claude Code best practices: state boundaries explicitly so the model does not infer them, and keep the regression surface visible.
A few details make the template work better in practice. Under Goal, prefer user-visible outcomes over implementation notes (“session persists across refresh” beats “use JWT” unless JWT is a hard constraint). Under Scope, name files and also name anti-patterns (“do not add new dependencies”). Under Acceptance, include at least one automated check and one manual step — Agents optimize for the checks you actually run. Under Context, paste errors verbatim; truncated logs are the single biggest cause of repeated failed edits.
When a task spans multiple rounds, append a short Status section: what passed Verify, what remains, and what must not be revisited. That turns a long chat into a living spec instead of a pile of diffs.
Rules / Skills: bake project constraints into the repo
Repeating “we use pnpm, no class components, tests live in __tests__” every session burns tokens and erodes consistency. The Agent will follow those rules sometimes and ignore them other times. Persist team conventions in .cursor/rules or a project-level AGENTS.md:
- Rules
- Standing constraints: naming style, forbidden patterns, commands that must run before commit. Cursor injects these on every Agent invocation.
- Skills
- Reusable playbooks — e.g. “add a new API endpoint” as a step-by-step checklist. Reduces rediscovery of your folder layout on every task.
- User Rules vs Project Rules
- Personal preferences (reply language, comment density) belong in User Rules. Team agreements (“do not modify backend unless explicitly asked”) belong in Project Rules so collaborators share the same guardrails.
See the Cursor Skills documentation for how to package multi-step flows. Once high-frequency tasks are encoded, repeat edits on the same class of mistake drop sharply — the Agent stops proposing the wrong package manager or test runner because the answer is already in context.
Good Rules read like code review comments, not essays. Prefer “never import from ../../legacy/” over “be thoughtful about dependencies.” Reference one canonical file as a style exemplar: “match patterns in src/auth/session.ts.” Update Rules when the codebase changes; stale Rules are worse than none because they teach the wrong habits.
Small diffs and Git discipline
Agents excel at generating large blocks of code. Humans are bad at reviewing large blocks. The mismatch creates merge anxiety and hidden bugs.
- One Agent task → one commit — Write the commit message from the Plan summary so
git revertmaps cleanly to a decision. - Reset when it goes sideways — Do not keep patching a bloated diff.
git checkout -- .back to the last green point and reopen with a smaller scope. - Branch for experiments — On a cloud Mac or CI runner, use
git worktreeor a throwaway branch so Agent chaos stays isolated from your main line.
Small diffs also make code review humane. A reviewer can see whether the Agent respected scope, whether tests were updated, and whether naming matches the repo — in five minutes instead of fifty.
Context management: don't drown the Agent in files
Dumping an entire monorepo into context is like asking someone to find a typo by reading every book in a library. Signal drowns in noise. More effective approaches:
- Reference three to five files with
@filenameinstead of asking the Agent to scan the whole tree. - Split large refactors into multiple Plans: interfaces first, implementation second, tests third — Verify after each.
- After fifteen or more turns, start a new conversation and paste the task spec plus current status. Carrying stale failed attempts forward pollutes the next edit.
Context budget is not just tokens — it is attention. Every unrelated file in context is a distraction the model may “fix” while ignoring your actual bug.
Deep dive: when to switch between Plan mode and Agent mode
Use Plan when requirements are fuzzy or architectural trade-offs matter. Switch to Agent when the spec is written and the file list is explicit. In Cursor you can SwitchMode to Plan deliberately — many loops happen because the Agent is thinking and editing at the same time. Step back, rewrite scope, then edit again.
For tool-using Agents — MCP servers, shell access, browser automation — context discipline matters even more. Each tool call can pull in megabytes of output. Filter what gets appended to the thread: log summaries, not raw JSON dumps, unless the summary hides the failure.
Four common loops and how to break them
| Symptom | Root cause | Fix |
|---|---|---|
| Fix A breaks B; fix B breaks A | Scope too large; tests not isolated | Narrow to one file; add mocks; split into two Plans |
| Same error after five attempts | Incomplete logs; model is guessing | Paste full stderr; instruct “read X before editing” |
| Inconsistent code style every round | Rules not configured | Add .cursor/rules; cite an existing file as the pattern |
| Agent says “done” but behavior is wrong | Acceptance criteria missing from the prompt | Write manual verification steps during Plan |
If you are orchestrating multi-step Agent pipelines — document batches, CI glue, MCP tool chains — the same layering applies: route, execute, validate. That is the same pattern we use in our batch PDF identification pipeline: classify before you process so not every job takes the slowest, error-prone path. Coding Agents benefit from the same separation. Do not let one mega-prompt both redesign architecture and fix a typo.
When you hit a loop, resist the urge to add more adjectives to the prompt (“please be careful”). Instead, shrink scope, add a failing test that encodes the bug, or revert to the last green commit. Pressure without structure rarely helps; structure without verification rarely sticks.
FAQ
- Does a stronger model mean fewer rounds? — Stronger models reduce syntax-level mistakes, but scope creep causes regressions at every tier. Workflow is the main lever.
- How do teams align? — Check Rules, PR templates, and acceptance checklists into the repo. Review whether each PR is a small, planned step.
- Can I hand everything to the Agent? — Execution can be automated; Plan and Verify should stay human-gated for payments, auth, and data migration.
- How does this fit with TDD? — Ask the AI to write a failing test (Plan), implement the minimum code (Scoped Edit), then refactor once green — naturally maps to all three stages.
Stopping AI from repeatedly rewriting your code is not about prompting harder or buying a bigger model. It is about Plan → Scoped Edit → Verify discipline, prompts that state goals and boundaries, Rules checked into the repo, and the willingness to git revert when a round goes wrong. Once the process is habitual, your time shifts from applying the Nth patch to defining the problem once — and that is where both you and the Agent do your best work.
Try Agents on an isolated cloud Mac — without risking your daily driver
Dedicated M4 node, rent by the day, SSH ready out of the box
Singapore · Japan · Korea · Hong Kong · US nodes available
AI Coding Workflow benefits from a sandbox: run Agents on a cloud Mac branch, snapshot and roll back when experiments go wrong, and keep your primary laptop clean. View ZekVPS cloud Mac mini plans — ideal for MCP, CI, and long-running Agent debugging in parallel.