How AI Coding Agents Really Work: 5 Core Context Management Mechanisms

    AI coding agents are often treated as smarter code-completion tools, but performance differences usually come from context management rather than the model itself. This article explains five core mechanisms behind CLI-based coding agents: the seven categories of content that share the context window, persistent project rule files, context compaction and information loss, on-demand Skills loading, and subagent delegation with context isolation. It also discusses how hooks, ReAct, RAG, and memory fit into the broader agent architecture, along with practical guidance on when to compact context and how to delegate complex work.

    Introduction: Why “Using It” Is Not the Same as “Using It Well”

    CLI-based AI coding agents, often called agent harnesses—the operational framework that runs an agent—have become everyday productivity tools for developers. Many people treat them as smarter code-completion tools: you ask a question and get an answer. Yet once you use one in depth, a clear difference emerges. With the same tool, some developers can complete a cross-file refactor independently, while others find that after three rounds of conversation, the agent has “forgotten” the original constraints, answers the wrong question, and repeats its mistakes.

    The root cause is usually not the model itself, but the understanding of how an agent works. A mature coding agent manages much more than conversation alone. It also handles the context window, rule files, Skills loading, subagent delegation, and context compaction. This article explains what an agent really remembers, what it forgets, and how to manage these mechanisms through engineering practices.

    1. What Is Actually Inside the Context Window

    A common misconception is that the context window contains only what you say and what the agent replies. In reality, conversation history is just one of seven types of content that share the window. Understanding these categories is the first step in context engineering:

    1. Conversation history: The interaction record between the user and the agent. It is the most readable content, but it can become outdated quickly.
    2. File content: Source files that the agent has read or edited. This is the core material for understanding the codebase.
    3. Command output: Results from terminal commands, such as builds, tests, and log queries. These outputs can be very large.
    4. Project rule files: Project-level constraints that persist across sessions, including coding standards and architectural conventions.
    5. Automatic memory: Learning records distilled from past interactions and retained across sessions.
    6. Loaded Skills: Full instruction text injected after a matching Skill is triggered. Each Skill represents a reusable area of expertise.
    7. System instructions: The framework’s operating rules, available tool definitions, and safety boundaries.

    All seven categories share the same limited token budget. This creates a hard constraint: any content that grows too large takes space away from everything else. File content and command output are especially important to manage. Reading one large file or running a full test suite can consume tens of thousands of tokens. In practice, managing context means making trade-offs and scheduling space across these seven categories.

    2. Project Rule Files: Keeping Constraints Across Turns

    Once you understand what fills the context window, it becomes clear why rules written directly in a conversation can stop working.

    The answer is that conversation history can be compacted, while project rule files are not. A project rule file—typically a structured document placed at the project root—is designed to preserve constraints over the long term. It holds information that must remain effective throughout the project’s lifecycle, such as:

    1. # Project Conventions
    2. ## Tech Stack
    3. - Language: TypeScript with strict mode enabled
    4. - Tests: All new logic must include unit tests
    5. ## Architecture Constraints
    6. - The domain layer must not depend directly on the infrastructure layer
    7. - Database access must go through the repository layer
    8. ## Compaction Directives (must be preserved during compaction)
    9. - The list of APIs currently being migrated
    10. - Unfinished refactoring tasks and their boundaries

    The most valuable section is the last one: compaction directives. These directives are reinjected together with the rule file after every context compaction, so they are not diluted by the summarization process. In other words, if a constraint must remain in effect across turns and sessions, the most reliable approach is to place it in a rule file. A practical guideline is this: anything you want the agent to remember consistently should not be written only in the conversation. It should be written into a rule file.

    3. Context Compaction: Why Long Conversations Cause “Amnesia”

    The context window is a limited resource. When its contents approach the limit, the agent must free up space. A mature implementation generally follows a two-step strategy:

    Step 1: Remove low-value, bulky content. Older tool-call outputs, stale file-reading results, and lengthy logs from earlier commands are cleared first because they take up space but have little ongoing value. The agent may still remember that a file was read, but the file’s actual content may no longer be in the context.

    Step 2: Summarize conversation history. The exact wording, numbers, and code snippets from earlier turns are condensed into general summaries.

    The problem is that compaction always loses information. A naming convention you emphasized in turn three or a technology choice you finalized in turn five may end up as a vague statement like “discussed the architecture approach.” This is why coding agents appear to forget earlier instructions in long conversations. They are not ignoring you; those instructions have physically disappeared from the context.

    There are two common ways to address this:

    • Persist information in advance: Write important details into the project rule file, as described in Section 2. The reinjection behavior after compaction helps prevent information loss.
    • Trigger compaction manually: Most tools provide a command for manual compaction, allowing you to specify what to retain. For example, after completing an API change, you can compact the context and state: “focus on the API contract and migration steps for this change.” This keeps your remaining context budget focused on the current task.

    A useful habit is this: when a task is about to move into a new phase, trigger compaction proactively instead of waiting for the context window to overflow. This gives you much more control.

    4. Loading Skills: On-Demand Domain Expertise

    If rule files provide constraints that are always in effect, Skills provide expertise for specific situations.

    A Skill is a structured set of instructions that an agent can discover and load. It packages the methodology for a particular type of task, such as how to write unit tests that follow the project’s conventions, how to perform database migrations, or how to generate documentation for a specific kind of API. Its key advantage is on-demand loading: the full instructions are injected only when a task matches a Skill’s trigger condition.

    This design follows the idea of progressive disclosure. Normally, only a short description, or metadata, for each Skill remains in the context, using very little space. When a Skill is triggered, its full instructions are loaded. This avoids wasting the context window on every available instruction while still providing detailed guidance when it is needed.

    In comparison, a rule file acts like background knowledge that is always available, while a Skill acts like a reference manual that you consult only when needed. Together, they form the two main sources of an agent’s knowledge.

    5. Subagent Delegation: Context Isolation and Parallel Work

    When a task becomes complex enough, the capacity of a single context becomes a bottleneck. The subagent mechanism addresses this through delegation.

    Its core idea is context isolation. Instead of loading every intermediate detail of a subtask into its own context, the main agent delegates the entire task to a subagent. The subagent explores, searches, and tests in its own separate context, then returns only the conclusion to the main agent, not the full process.

    1. Main Agent (keeps the global goal and constraints)
    2. │
    3. ├─ Delegate Subagent A: locate relevant files and return "3 files involved and their responsibilities"
    4. ├─ Delegate Subagent B: run the test suite and return "a summary of 2 failing cases"
    5. └─ Combine the results from A and B → create a modification plan → execute

    This approach offers two direct benefits:

    • A leaner main context: The main agent’s window holds conclusions rather than intermediate noise, which helps it stay focused during long tasks.
    • Parallel work and role separation: This is the foundation for common patterns such as Plan-and-Execute and Multi-Agent. A planning agent breaks down the task and assigns it to multiple execution subagents, while the main agent consolidates the results and checks quality.

    That said, more subagents are not always better. Delegation has coordination costs. Splitting work too early or too finely can introduce communication overhead and make result integration more complicated. A reasonable approach is to delegate only when a subtask has clear boundaries and will produce a large amount of intermediate information.

    6. Beyond the Basics: How Hooks, ReAct, RAG, and Memory Fit In

    These five mechanisms do not work in isolation. They are part of a broader agent system that also includes several established engineering patterns:

    • Hooks: Trigger predefined actions on specific events, such as before editing a file or after running a command. Hooks can enforce validation, apply automatic formatting, or inject reminders. They act as the glue for workflow orchestration.
    • ReAct (reasoning–action loop): The agent progresses through a cycle of “think → act → observe → think again.” Each round uses new observations from tool results to adjust the next decision. This is a fundamental pattern for autonomous execution.
    • RAG (retrieval-augmented generation): When relevant knowledge is not already in the context, RAG retrieves it dynamically and injects it into the context, addressing the challenge of not being able to retain every document.
    • Memory: Persists valuable information across sessions and recalls it as needed in later sessions, giving the agent a sense of long-term continuity.

    Put together, the picture becomes clear: rule files manage what stays in effect, Skills manage specialized capabilities, subagents manage the decomposition of complex tasks, compaction manages available space, hooks manage workflow constraints, RAG and memory manage knowledge supply, and ReAct drives the rhythm of the entire process.

    Conclusion

    Mastering AI coding agents is less about memorizing the commands of a particular tool and more about understanding the context engineering logic behind it. Once you understand that the context window holds seven types of content, that compaction causes information loss, that rule files can prevent this loss, that Skills are loaded on demand, and that subagents isolate context, you can manage these mechanisms intentionally. You can place constraints in rule files, trigger compaction when moving between phases, delegate routine or noisy work to subagents, and use Skills to capture reusable methods.

    Tools will continue to evolve, and their names will change, but these context management principles apply broadly. Understanding them means you are not just learning one product. You are learning how to work with an entire class of AI coding systems.