How to Prevent Context Loss When Coding with AI
The Problem
I hit the “month 3 wall” with my AI-coded application. Everything was working great in the beginning. Claude Code built features fast, the code looked clean, and I felt productive. Then suddenly, the codebase became a nightmare.
API routes bypassed my own middleware because Claude didn’t know it existed. Modules duplicated logic written elsewhere. Data flows contradicted patterns I had set up earlier. Each feature worked in isolation, but collectively, the codebase was incoherent.
I assumed I was prompting wrong. Maybe I needed to be more specific? Maybe I needed to provide better context?
Then I found a Reddit thread that explained exactly what was happening:
“The month 3 wall happens because the spec lives in your head, not in the repo. Each prompt session starts fresh. The AI doesn’t know what you decided last Tuesday about how auth should work, or that the billing module depends on a specific user state.” - u/thlandgraf
The problem was clear: each AI session starts without context of the whole system.
Why Context Loss Happens
AI coding assistants have a fundamental limitation: each prompt session starts with a blank slate. Unlike a human developer who maintains mental models over time, an LLM has no persistent memory between sessions.
Session 1 (Monday): Build auth → decides JWT with 24-hour expirationSession 2 (Wednesday): Build billing → decides session-based auth (conflicts!)Session 3 (Friday): Build API → creates new middleware (bypasses existing auth)
Result: Three individually reasonable solutions that collectively break the systemThis creates several critical issues:
Session Isolation: Each feature is built in isolation, without awareness of existing patterns, middleware, or architectural decisions made in previous sessions.
Contradictory Implementations: Claude implements authentication one way on Monday, then implements a conflicting approach on Wednesday because it doesn’t remember Monday’s decision.
Growing Context Burden: As the codebase grows, the amount of context Claude needs increases, creating a bottleneck that compounds over time.
Incoherent Codebase: Individual solutions make sense alone, but collectively create technical debt, duplicate logic, and architectural inconsistencies.
Month 1: Fast development, features work, feels productiveMonth 2: Small inconsistencies appear, easy to fixMonth 3: Codebase becomes hard to maintain, debug, extend ↓The wall: New features conflict with existing architecture ↓Debugging nightmare: Similar functionality implemented 3 different waysThe Solution: Intent Files
The fix is to externalize what would normally live in a developer’s head into persistent, structured documentation that gets injected into each AI session.
What Are Intent Files
Intent files document architectural decisions before they’re implemented. They record patterns, conventions, and constraints. They capture dependencies between modules. They provide context that survives across sessions.
# Intent: User Authentication Module
## Decision Date2024-01-15
## Context- Building user authentication for multi-tenant SaaS application- Must integrate with existing billing module (see billing-context.md)- All routes must pass through auth middleware (src/middleware/auth.ts)
## Constraints1. Use JWT tokens with 24-hour expiration2. Passwords must be hashed with bcrypt (cost factor 12)3. Session state stored in Redis (key format: session:<user_id>)
## Dependencies- Billing module expects `user.tier` property- WebSocket connections require authentication handshake- Rate limiting applied per-user, not per-IP
## Patterns to Follow- Repository pattern for data access (see src/repositories/UserRepository.ts)- Use existing Logger utility (src/utils/logger.ts)- Return ApiResponse<T> format for all endpoints
## Anti-Patterns to Avoid- Do NOT create new middleware—use existing auth middleware- Do NOT duplicate password validation logic- Do NOT bypass rate limitingContext Injection Pattern
Before each prompting session, I read existing context files and include them in my prompt:
# Before Prompting the AI:
1. Read existing context: - ARCHITECTURE.md - intent/auth-context.md - intent/billing-context.md
2. Prepare prompt with context: """ I need to add password reset functionality.
Context (READ THIS FIRST): [contents of auth-context.md] [relevant sections of ARCHITECTURE.md]
Task: Implement password reset flow following the patterns documented above. Ensure it integrates with existing auth middleware and uses the UserRepository. """
3. After implementation, update context files with new decisionsLiving Architecture Document
I also maintain an ARCHITECTURE.md that provides a high-level overview:
# ARCHITECTURE.md
## Module Overview- **Auth Module:** Handles authentication, authorization, session management - Middleware: src/middleware/auth.ts - Repository: src/repositories/UserRepository.ts - See: intent/auth-context.md for decisions
- **Billing Module:** Subscription management, payment processing - Depends on: Auth module (user.tier property) - See: intent/billing-context.md for decisions
## Global Patterns1. **Repository Pattern:** All data access through repository classes2. **ApiResponse Format:** All endpoints return `{ success, data?, error? }`3. **Error Handling:** Centralized error middleware catches exceptions4. **Logging:** Use Logger utility with context: `logger.info('message', { context })`
## Database Conventions- Tables: snake_case (e.g., user_sessions)- Models: PascalCase (e.g., UserSession)- Foreign keys: always indexed- Soft deletes: use `deleted_at` column
## Recent Decisions- 2024-01-15: Use JWT for auth (not sessions)- 2024-01-14: Redis for session storage- 2024-01-10: Repository pattern adoptedWhy This Matters
Without context preservation, AI-generated codebases suffer from:
Technical Debt Accumulation ↓ Each session adds code that doesn't align with previous decisions
Debugging Nightmares ↓ Bugs hard to trace because similar functionality may be implemented three different ways
Scalability Issues ↓ New features increasingly conflict with existing architecture
Knowledge Silos ↓ All context lives in developer's head, impossible for team members to understand the full systemWith intent files, I gained:
+ Consistent Architecture: All features follow the same patterns+ Faster Development: Claude doesn't need to re-learn the codebase+ Reduced Technical Debt: New code aligns with existing decisions+ Better Collaboration: Team members can understand and contributeWhat I Got Wrong About AI Context
I made several mistakes before I understood the problem:
Assuming Claude Remembers: I treated Claude like a human developer who maintains mental models across sessions. It doesn’t. Each session truly starts fresh.
Minimal Context Files: I created documentation that was too sparse or outdated. Intent files need enough detail to be useful, and they need to stay current.
No Session Preparation: I jumped straight into prompting without reviewing or updating context. This defeats the purpose of having context files.
Over-Reliance on Tool Memory: I expected Claude Code’s conversation history to suffice. It doesn’t scale across projects or time. The conversation history gets truncated, and I can’t rely on it for persistent context.
Siloed Context: I kept architectural decisions in separate places—comments, docs, tickets—instead of a unified, AI-readable format. Claude can’t find and use scattered information.
The Comparison
WITHOUT INTENT FILES WITH INTENT FILES────────────────────────────────────────────────────────────────────Session starts fresh Session starts with context │ │ ▼ ▼AI makes assumptions from AI reads intent filesincomplete prompt │ │ ▼ ▼ AI follows documented patternsFeature works in isolation │ │ ▼ ▼ New code aligns withNext session forgets existing architectureprevious decisions │ │ ▼ ▼ Consistent, maintainableContradictory code builds codebaseon contradictory code │ │ ▼ ▼ Team can understandMonth 3 wall: the systemincoherent mess │ │ ▼ ▼ Sustainable developmentStart over or abandonSummary
Preventing context loss in AI coding requires shifting the spec from your head to persistent, structured documentation that gets injected into each session. Intent files transform isolated, contradictory code generation into coherent, maintainable software development.
The key steps:
- Write intent files before prompting—document decisions, constraints, dependencies
- Inject context at the start of each session—include relevant intent files in your prompt
- Update files after implementation—new decisions go into the persistent record
- Maintain ARCHITECTURE.md—provide a high-level overview for quick reference
The spec doesn’t live in your head anymore. It lives in the repo. Each session starts with context. Claude knows what you decided last Tuesday.
Final Words + More Resources
My intention with this article was to help others share my knowledge and experience. If you want to contact me, you can contact by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!
Comments