Why AI Coding Assistants "Forget" in Long Sessions—and How to Fix It with Structured Context
AI coding assistants often drift from your project's rules during long sessions because of how context is supplied, not because the model lacks ability. This article explains three common causes—insufficient rule transfer, context decay, and context pollution—and shows how to address them with two context files: a persistent root-level CLAUDE.md and on-demand subdirectory files. You will learn four design principles for organizing layered context, a reusable file skeleton, common pitfalls to avoid, and a practical rollout plan for teams.
1. Where the Problem Comes From: Why AI Coding Assistants Stop Following Instructions
When working with an AI coding assistant, the most common frustration is not that it “cannot write code,” but that it “does not write code according to our project’s rules”: it runs the build with the wrong command, modifies directories it should not touch, generates branch names that violate the team’s coding conventions, or repeatedly asks about agreements that were already explained.
These behaviors are usually not model capability gaps. They are context-supply problems, and they fall into three categories:
- Insufficient rule transfer: Team conventions live only in verbal handoffs, internal documents, or one person’s memory, so the assistant has no way to know them.
- Context decay in long tasks: As the conversation grows, information provided early gets diluted within the effective attention window, and the model “forgets” the original requirements.
- Context pollution: Dumping a large amount of task-irrelevant information at once buries the engineering constraints that actually matter.
The fix is not to “say it louder.” It is to build a structured project-context supply mechanism: persist stable information as always-on instructions, and let access behavior drive the loading of locally relevant information.
2. Two Context Vehicles: Persistent and On-Demand
A common engineering approach is to place a Markdown project-instruction file, typically named CLAUDE.md, in the repository root. It is read at the start of a session, enters the context, and remains effective throughout the session. Content suited to this file includes:
- Standard commands for build, test, and formatting;
- Directory layout and the responsibility boundaries of each directory;
- Relationships and dependency directions among subpackages in a monorepo;
- Coding conventions, naming rules, and comment and commit-message requirements;
- Team-specific engineering agreements, such as directories that must not be modified and metadata files that must be updated in sync.
This mechanism generally has two loading modes. The difference is not “format” but “loading timing” and “scope of effect.”
2.1 Persistent: The Root-Level Instruction File
A persistent file lives in the repository root. It can be committed with the shared repository so that every member and every automation pipeline gains the same understanding of the project. It can also be kept locally and excluded from version control to carry personal preferences, such as a preferred level of logging detail or supplementary notes on personal code style.
Its defining property is that it stays “always on.” It is loaded at the very start of the session and is not lost or weakened during long sessions when context is compacted. When the assistant summarizes prior conversation, this persistent instruction is re-included, so it retains its authoritative status in the compacted context. This solves a very practical problem: at turn thirty of a long task, the assistant still knows “which package manager this project uses” and “where unit tests live.”
2.2 On-Demand: The Subdirectory Instruction File
An on-demand file sits in a specific subdirectory, for example app/api/CLAUDE.md. It is not loaded at session start; it enters the context only when the assistant actually reads a file under that subdirectory. This follows a path-scoped principle: the instruction’s effective range matches the coverage of its directory and does not spill over into unrelated modules.
Before it is triggered, this instruction is invisible to the model. Once triggered, it enters the context and follows the same rule during later compaction—it reappears only if the current task still involves that path. So in a large repository with dozens of modules, on-demand files provide fine-grained module-level constraints without bloating the global context.
2.3 How the Two Divide the Work
| Dimension | Persistent (root) | On-demand (subdirectory) |
|---|---|---|
| Loading timing | Loaded at session start | Loaded when a file in that directory is read |
| Scope | The entire repository | Its directory and subdirectories |
| Behavior after compaction | Re-included, effective long-term | Reappears when the path is touched again |
| Typical content | Build commands, overall architecture, general conventions | Module-specific constraints, local interface agreements |
| Suitable scale | All projects | Medium-to-large, multi-module, monorepos |
3. Four Design Principles for Layered Context
Once you understand the loading mechanism, what really determines results is how you organize the content. These four principles deliver the most in practice.
First, separate global from local. Anything true for “the whole project” goes in the root; anything true “only for a specific module” moves down into a subdirectory. The test is simple: if a rule placed in the root would mislead developers or the assistant working on other modules, it should move down.
Second, write only stable information. The value of a persistent file comes from being persistent, so it should not contain volatile content such as the current iteration’s task list, temporary debugging notes, or descriptions of an occasional defect. That content belongs to the session itself or to a task-tracking system; mixing it into persistent instructions continuously generates noise.
Third, use executable instructions instead of background description. “This project uses a unified code formatting tool” is background description. Giving the exact command to run and stating that it must be run before committing is an executable instruction. The assistant responds far more reliably to the latter.
Fourth, control volume and redundancy. The longer the persistent content, the lower the probability that any single rule is applied effectively. Treat these instruction files like code during review: before adding a rule, confirm it is not already covered by an existing entry.
4. Writing Tips: Making Rules Actually Followed
A reusable persistent instruction skeleton looks like this (illustrative):
# Project OverviewOne sentence describing the project's purpose, tech stack, and runtime form.# Common Commands- Install dependencies: <package manager command>- Start locally: <start command>- Unit tests: <test command>- Static checks: <lint command>- Code formatting: <format command># Directory Conventions- src/ Application code- packages/ Reusable subpackages- tests/ Test code- docs/ Design documents# Coding Standards- Unified requirements for naming, comments, logging, and error handling- Checks that must pass before committing# Off-Limits- Directories or auto-generated files that must not be modified- Operations that require human confirmation before execution
An on-demand instruction file should be narrow and deep, for example:
# app/api Module Guide## Responsibility BoundaryHandles only parameter validation and protocol conversion at the external interface layer; contains no business rules.## Must Follow- New endpoints must update the endpoint inventory document in sync- Use the unified error-code source; custom error structures are prohibited## Related Directories- Route definitions: <path>- Data access: <path>
Three additional techniques: first, state explicitly “what not to do,” since prohibitive constraints often change behavior more than encouraging descriptions; second, require confirmation before key operations, especially batch changes, file deletion, and running external commands; third, turn repeated human corrections into a rule—this is the most important way to maintain these files.
5. Common Pitfalls
Pitfall 1: Treating the instruction file as an all-purpose manual and stuffing in architecture designs, historical decisions, and even meeting notes. The result is that the assistant cannot grasp the key points and its output becomes more scattered.
Pitfall 2: Putting everything in the root, creating “global noise” that dilutes module-level constraints; or the reverse, splitting everything into subdirectories so that global facts are invisible early in the session.
Pitfall 3: Writing it once and abandoning it. As the repository evolves, outdated directory descriptions and deprecated commands keep causing the assistant to make the same mistakes, so these files should be included in code review.
Pitfall 4: Confusing instruction files with task context. The former describes “what the project is like over the long term”; the latter describes “what to do this time.” The two should stay separate, and persistent content should not drift over time.
6. Rollout Path and Team Collaboration
A four-step rollout works well. First, identify the three to five pieces of information most often re-explained during team handoffs and write them into the root instruction; this alone usually eliminates most redundant Q&A. Second, identify directories with clear module boundaries and add a narrow on-demand instruction to each. Third, bring instruction-file changes into normal review and commit them alongside code so all members get consistent context. Fourth, review periodically and delete entries that no longer apply.
At the team and engineering level, two extensions help: let the same set of instructions serve code review, onboarding, and automation pipelines to reduce inconsistency across multiple entry points; and in CI environments, use log services and monitoring alerts to observe whether the assistant’s changes frequently trigger formatting or static-check failures, treating such signals as a reverse measure of context quality.
Fundamentally, the payoff of this mechanism does not come from longer prompts but from making project knowledge explicit, structured, and maintainable: stable information stays persistent, local information appears on demand, and dynamic changes go to review and task systems. When these three layers are each in place, an AI coding assistant’s output shifts from “occasionally obedient” to “consistently controllable,” and team collaboration costs fall accordingly.
