Back to materials

Understanding agent mistakes

Table of Contents

1. Overview

AI coding agents fail in specific ways: context loss, hallucination, and subtle bugs. This guide covers each and how to recover.

Key principle

Treat AI-generated code as a draft. You provide the judgment and verification the agent cannot.

2. Context management issues

Context management is the most common source of agent failures. A full context window leads to forgetting, repetition, and hallucination.

Context loss and infinite loops

Problem: The agent loses track of its progress within a task, repeatedly searching for the same information or applying the same fix.

Symptoms:

  • Repetitive output like "Let me search for..." followed by the same search
  • Agent re-asks questions you already answered
  • Same code changes applied multiple times

Solutions:

ActionHow to do it
Start freshOpen a new chat session to reset context
Break down tasksDivide complex work into smaller, focused requests
Monitor token usageWatch for signs of context saturation
Clear chat historyUse Settings > Clear All Chats periodically

Hallucination and irrelevant suggestions

Problem: The agent generates plausible but incorrect code: non-existent functions, wrong APIs, or code that ignores your project structure.

Symptoms:

  • Code references functions or variables that don't exist
  • Suggestions that ignore runtime errors or logs you provided
  • Generic solutions that don't fit your specific framework or architecture

Solutions:

  • Provide explicit context: Use @file or @folder to point the agent to relevant code
  • Include error messages: Paste actual error output rather than describing it
  • Specify constraints: Mention your framework, versions, and architectural patterns
# Bad prompt
"Fix the authentication bug"

# Good prompt
@file:src/auth/login.ts
"The login function throws 'TypeError: Cannot read property email of undefined'
when the user object is null. Add null checking before accessing user.email."

Lost in the middle

Problem: When context becomes very long, agents focus on information at the beginning and end and lose details in the middle.

Solutions:

  • Keep critical information near the start or end of your prompt
  • For long tasks, summarize key constraints at the end
  • Reference important files directly rather than relying on earlier mentions

3. Version control

Commit working code before significant AI-assisted changes for instant rollback.

For git undo commands (git reset, git restore), see Setup fundamentals > Undo commands.

4. Code quality issues

Subtle bugs and broken conventions

Agent code can compile and pass basic checks while hiding real defects.

Common issues:

  • Removing essential null checks or error handling
  • Breaking existing functionality while adding new features
  • Ignoring project conventions and patterns
  • Adding redundant or conflicting dependencies

Solutions:

  • Request incremental changes: Ask for small, focused modifications rather than large rewrites
  • Specify what to preserve: Explicitly mention code that should not be changed
  • Review diffs carefully: Check every change before accepting, not just the new code
# Risky prompt
"Refactor the user service to use async/await"

# Safer prompt
"In @file:src/services/userService.ts, convert the fetchUser function
(lines 45-60) to use async/await. Keep all existing error handling
and don't modify other functions."

Enforcing validation with tests

LLMs cannot self-verify their logic. Compensate by having the agent write tests alongside implementation.

Approach:

  1. Ask the agent to write tests first (TDD style)
  2. Then implement the feature
  3. Run tests to validate
"Using TDD, implement a validateEmail function:
1. First write tests for: valid emails, invalid formats, empty input, null input
2. Then implement the function to pass all tests"

5. Workflow best practices

Common workflow mistakes

AvoidDo instead
Accept suggestions blindlyReview every change critically
Fix AI mistakes in same sessionRollback and re-prompt with better context
One big requestMultiple small, focused requests
Hope it worksVerify with tests and manual review

Effective prompting strategies

Structure your prompts:

  1. Context: What file/function you're working with
  2. Goal: What you want to achieve
  3. Constraints: What should not change, frameworks to use, patterns to follow
  4. Success criteria: How you'll know it's correct

Example structured prompt:

Context: @file:src/components/UserProfile.tsx

Goal: Add loading state while fetching user data

Constraints:
- Use existing LoadingSpinner component from @file:src/components/ui/LoadingSpinner.tsx
- Keep current error handling
- Follow existing patterns in the codebase

Success criteria:
- Show spinner during API call
- Hide spinner when data loads or error occurs
- No layout shift when transitioning states

When to stop and restart

Signs the session needs a restart:

  • Agent is looping or repeating itself
  • Suggestions have become increasingly irrelevant
  • You've corrected the same mistake multiple times
  • Failed attempts have filled the context

Recovery steps:

  1. Stop the current session
  2. Commit or stash any good changes
  3. Rollback problematic changes: git restore .
  4. Start a fresh chat with lessons learned incorporated into the prompt

Use Plan Mode for complex tasks

For multi-step or architectural changes, use Plan Mode (Cmd+P / Ctrl+P) to:

  • Force the agent to research before implementing
  • Review the approach before code is written
  • Catch misunderstandings early

6. Troubleshooting

ProblemLikely causeSolution
Agent repeats same action or fixContext loss or failed editStart new session; confirm state with git diff
Suggestions ignore my codeInsufficient context providedUse @file to reference specific files
Code references non-existent functionsHallucinationProvide more explicit constraints and examples
Agent removes important codeUnclear about what to preserveSpecify what should NOT change
Performance is slowLarge context or heavy codebaseReduce context, use .cursorignore
Agent gets stuck on first promptLoop bugRestart Cursor, report to community forum

7. Reference

For Cursor settings, context symbols, and chat modes, see Setup fundamentals.

Documentation