Context Management Strategies
Master context window management - when to use @codebase vs @file, the 7 files rule, and patterns for working with large codebases
One of the most overlooked skills in AI-assisted development is context management. Give AI too little context, it hallucinates. Too much, it gets confused. This guide teaches you the sweet spot.
The @ Symbol Decision Tree
Cursor's @ symbol gives you precise control over what AI sees. Here's when to use each:
@file - The Default Choice (80% of the time)
Use when:
- Working on specific feature in known files
- Bug is isolated to 1-3 files
- Implementing well-scoped task
Example:
"Add error handling to @src/orders/OrderService.ts
Follow patterns from @src/common/ErrorHandler.ts"Why it works: Precise context, no noise, AI focuses on what matters.
@folder - Exploring Related Code
Use when:
- Understanding a module or feature area
- Refactoring across related files
- Don't know exactly which file contains what you need
Example:
"Explain how authentication works in @src/auth/
Focus on the token refresh flow"Why it works: Captures related files without overwhelming context. Good for exploration.
Watch out: Large folders (10+ files) can overwhelm context. Start with @folder, then drill down to specific @files.
@codebase - Use Sparingly
Use when:
- Exploring completely unfamiliar codebase
- Finding where functionality lives (search-like query)
- Understanding cross-cutting concerns
Example:
"Where in @codebase do we handle user permissions?
Show me the main files involved."Why it works: AI searches semantically across entire codebase.
Watch out:
- Expensive (uses lots of tokens)
- Can miss details by trying to scan everything
- Results are often too broad
After using @codebase: Follow up with specific @file references for actual work.
@docs - For Documentation
Use when:
- Referencing README, architecture docs, API specs
- Ensuring AI follows documented patterns
- Teaching AI about business rules
Example:
"Implement user sync following @docs/api-integration-guide.md
Use the patterns for retry logic and error handling"The Decision Pattern
Step 1: Start narrow (default)
"Fix bug in @src/checkout/PaymentService.ts"
Step 2: Expand if AI needs more context
"Also reference @src/common/errors/ for error handling patterns"
Step 3: Rarely go broad
Only use @codebase if you don't know where to lookGolden rule: Start with the minimum context needed. Add more only if AI explicitly asks or gives generic answers.
The "7 Files Rule" for Agent Mode
Agent mode works best with focused context - roughly 5-7 files max.
Why 7 Files?
Based on real usage patterns:
3-7 files:
- Agent understands relationships
- Makes coordinated changes
- Maintains consistency
- Fast execution
10-15 files:
- Agent gets confused
- May miss edge cases
- Slower responses
- Generic solutions
20+ files:
- Agent overwhelms easily
- Hallucinations increase
- Loses track of changes
- High failure rate
Real Example: Refactoring Auth
Bad approach (20 files):
"Refactor entire @src/auth/ to use new token system
Update all files"
Problem: 20+ files, agent changes some inconsistently,
misses edge cases, breaks testsGood approach (7 files per iteration):
Iteration 1: Core token logic (5 files)
"Refactor token management in:
@src/auth/TokenService.ts
@src/auth/TokenRepository.ts
@src/auth/models/Token.ts
@src/auth/TokenValidator.ts
@tests/auth/TokenService.test.ts
Update to use new JWT library, preserve behavior"
[Review, test, verify]
Iteration 2: Auth middleware (4 files)
"Update auth middleware to use refactored TokenService:
@src/middleware/AuthMiddleware.ts
@src/middleware/RefreshMiddleware.ts
@tests/middleware/AuthMiddleware.test.ts
@tests/integration/auth-flow.test.ts
Tests must pass"
[Review, test, verify]
Iteration 3: Endpoints (6 files)
[Continue with endpoint updates...]Result: Each iteration is verifiable, reversible, and focused.
How to Break Down Large Tasks
Pattern:
- List all affected files
- Group by logical cohesion (what changes together)
- Order by dependency (core → dependent code)
- Tackle each group as separate agent task
Example breakdown:
## Task: Migrate from REST to GraphQL
### Affected files: 30+
### Iteration 1: GraphQL Setup (5 files)
- schema definition
- resolver base
- context setup
- types generation
- test infrastructure
### Iteration 2: User Resolvers (6 files)
- User query/mutations
- User type resolvers
- User tests
- Update auth context
### Iteration 3: Order Resolvers (6 files)
[Similar to users]
### Iteration 4: Frontend Migration (7 files per iteration)
[Break down by feature area]Context Budget Management
Think of context like RAM - you have a limited budget. Here's how to manage it.
Signs You've Overloaded Context
AI behavior changes:
- Responses become generic or vague
- Starts ignoring specific files you referenced
- Suggests solutions that don't match your stack
- Forgets earlier conversation points
- Responses get shorter/less detailed
What's happening: Context window is full, AI is "forgetting" earlier information.
How to Reset and Refocus
Tactic 1: Start New Chat
When context is overloaded, start fresh.
Summarize key decisions from old chat:
"Building user preferences feature.
Decided on: PostgreSQL table, REST API, no caching yet.
Now implement: [specific next step]"Tactic 2: Use Notepads for Persistent Context
Create Notepad with:
- Architecture decisions made
- Patterns to follow
- Files structure
- Edge cases to handle
Reference in each chat: @Notepad/preferences-feature
AI remembers decisions without cluttering contextTactic 3: Progressive Context Loading
Don't dump everything upfront.
Bad:
"Here's 15 files via @: [list]
Also review these docs: [list]
Also check these tests: [list]
Now implement feature X"
Good:
Chat 1: "Explain the pattern in @ServiceExample.ts"
Chat 2: "Now apply that pattern to create UserService..."
Chat 3: "Add error handling like @ErrorExample.ts"Context Budget by Mode
Chat mode:
- Budget: ~30-50 messages before reset
- Strategy: Start new chat for new feature/bug
- Use: Quick questions, code review, exploration
Composer mode:
- Budget: ~10-15 file references
- Strategy: Focus on files that change together
- Use: Multi-file features, refactoring
Agent mode:
- Budget: 5-7 active files, ~20 reference files
- Strategy: Clear task boundaries, iterate
- Use: Well-defined tasks with clear success criteria
Large Codebase Patterns
Working with 100+ files? These patterns help.
Pattern 1: Progressive Disclosure
Start narrow, expand as needed:
Step 1: Find entry point
"Where in @codebase is user creation handled?"
AI: "UserService.ts line 45"
Step 2: Understand core logic
"Explain the user creation flow in @UserService.ts"
Step 3: Expand to dependencies
"Show me how @UserService.ts uses @UserRepository.ts
and @EmailService.ts"
Step 4: Identify what to change
"I need to add phone verification to user creation.
Which of these files need to change?"
Step 5: Implement with focused context
"Update @UserService.ts to add phone verification:
- Follow email verification pattern
- Add validation
- Update tests"Why this works: Each step has manageable context. You learn before changing.
Pattern 2: Notepad as Project Memory
Use Notepads for decisions that span sessions:
## Notepad: E-commerce Refactor
### Architecture Decisions
- Event-driven for order processing
- CQRS for read-heavy operations
- Keep REST for now, GraphQL later
### Patterns to Follow
- Services in @src/services/
- Repositories in @src/repositories/
- Events in @src/events/
- Tests colocated with code
### Edge Cases to Handle
- Concurrent order updates (use optimistic locking)
- Payment failures (idempotent retries)
- Inventory sync (eventual consistency OK)
### Don't Change
- @src/legacy/billing/ (migration planned Q2)
- @src/reports/ (separate team owns this)Reference in every chat:
"Implement order cancellation
Follow patterns from @Notepad/e-commerce-refactor
Focus on @src/orders/"Pattern 3: Documentation as Context
For large codebases, maintain context docs:
# docs/cursor-context.md
## Architecture Overview
[High-level diagram or description]
## Key Files Guide
- **@src/core/Application.ts** - App initialization
- **@src/auth/AuthService.ts** - Authentication entry point
- **@src/orders/OrderService.ts** - Order business logic
- **@config/database.ts** - Database setup
## Common Patterns
- Error handling: See @src/common/errors/
- Validation: Use class-validator
- Testing: Jest + supertest
- Database: TypeORM repositories
## Reference: @docs/cursor-context.md in chatsUsage:
"Implement feature X
Context: @docs/cursor-context.md
Specific files: @src/relevant-file.ts"Pattern 4: The "Context Checkpoint" Technique
For multi-day features, checkpoint your context:
After each session, summarize:
## Session Summary: User Preferences Feature
### Completed
- ✅ Database schema and migration
- ✅ PreferenceRepository with CRUD
- ✅ PreferenceService with validation
- ✅ Unit tests (90% coverage)
### Decisions Made
- Store as JSONB for flexibility
- Validate on write, not read
- Cache per-user for 5 minutes
- Default values in service layer
### Next Session
- Create API endpoints (@src/api/preferences/)
- Add integration tests
- Update frontend to consume API
### Files Modified
@src/models/Preference.ts
@src/repositories/PreferenceRepository.ts
@src/services/PreferenceService.ts
@migrations/2025-12-01-preferences.tsStart next session:
"Continuing user preferences feature
Previous work: @Session-Summary.md
Next: Create API endpoints following @docs/api-patterns.md"Prompt Structuring for Complex Tasks
Template for complex prompts:
**Context:** [What AI needs to know]
@relevant-files, architecture decisions, constraints
**Task:** [Specific, actionable goal]
What to build/fix/refactor
**Constraints:** [What NOT to do, requirements]
- Follow pattern from X
- Don't change Y
- Must include Z
- Tests must pass
**Output format:** [How you want the response]
Explain approach first, then implement
Show before/after for changes
Include migration plan if needed
**Success criteria:** [How to verify it's done]
Tests pass, no linter errors, documentedExample: Database Migration
Generic (bad):
"Add created_at and updated_at to all tables"Structured (good):
**Context:**
@src/models/ - our TypeORM entities
@migrations/ - existing migration patterns
We use PostgreSQL 14
**Task:**
Add created_at and updated_at timestamps to all entities
missing them (User, Order, Product models have them already)
**Constraints:**
- Use TypeORM migration format
- Set created_at = NOW() for existing rows
- Follow naming from @migrations/2024-10-15-add-timestamps-users.ts
- Don't touch audit_log table (has different timestamp scheme)
- Make backwards compatible (default values for old rows)
**Output format:**
1. List affected entities
2. Show migration up/down
3. Show entity updates
4. Explain how existing data is handled
**Success criteria:**
- Migration runs without errors on dev database
- Entities updated with proper decorators
- Rollback works cleanly
- No data lossCommon Context Management Mistakes
Mistake 1: Context Dumping
Bad:
[Paste entire 500-line file]
"Fix the bug"Better:
"Bug in order total calculation @src/orders/OrderService.ts
Line 145-167 (calculateTotal method)
Issue: Doesn't handle percentage discounts correctly
Test case that fails: @tests/orders/discounts.test.ts line 23Mistake 2: Insufficient Context
Bad:
"Add validation"Better:
"Add validation to user registration @src/auth/RegisterController.ts
Requirements:
- Email format check
- Password strength (8+ chars, number, special char)
- Username uniqueness
- Follow patterns from @src/auth/LoginController.ts validation
Include both controller validation and service-level checks"Mistake 3: Mixing Multiple Tasks
Bad:
"Review @FileA.ts for bugs and refactor @FileB.ts and
add tests to @FileC.ts and update documentation"Better:
Three separate chats:
1. "Review @FileA.ts for bugs [focused bug hunt]"
2. "Refactor @FileB.ts [specific refactor goal]"
3. "Add tests to @FileC.ts [test generation]"Mistake 4: Not Resetting When Confused
Sign AI is confused:
AI: "Based on the React component you mentioned..."
You: "We're using Vue, not React"Action: Start new chat immediately. Don't try to correct in same thread.
New chat:
"Working in Vue 3 codebase
Add component following @components/ExampleComponent.vue
[Your actual task]"Quick Reference: Context Strategies
| Scenario | Context Strategy | Why |
|---|---|---|
| Simple bug fix | @file only | Focused, fast |
| Feature implementation | 5-7 @files | Manageable scope |
| Exploring unfamiliar code | @codebase then @folder | Discovery → focus |
| Refactoring module | @folder iteratively | Group related changes |
| Large feature (multi-day) | Notepad + checkpoints | Persistent memory |
| Architecture decision | @docs + key @files | Business context + code reality |
| Debug integration issue | @file for each service | Trace through layers |
| Generate tests | @file (code) + @file (existing tests) | Pattern matching |
Remember: Context management is a skill. Start conservative (fewer files), add more only when AI explicitly needs it. When in doubt, start a new chat with fresh focused context.