Five Core Mechanisms of AI Coding Agents: Context, Rules, Hooks, Skills, and Subagents
This article explains the five core mechanisms behind mature AI coding agents—context management, persistent rules, hooks, skills, and subagent delegation—and how they interact. It examines what fills an agent’s context window, why compaction can cause instruction loss, and which practices help preserve critical information. It also covers rule-file design, lifecycle automation with hooks, on-demand skill loading, and Plan-and-Execute subagent workflows, ending with practical steps for building a more reliable coding workflow.
AI coding agents have become important infrastructure in modern development workflows. They can generate code, read files, execute commands, call tools, and even plan multi-step tasks autonomously. Yet many users still understand their internal operation as simply “input a prompt, receive a response.” In reality, a mature agent is driven by five core mechanisms: context management, persistent rules, hooks, skills, and subagent delegation. This article breaks down these mechanisms from first principles and provides actionable best practices.
1. Context Window: Seven Types of Information Beyond Chat History
Most developers assume the context window contains only “what you said and what the agent replied.” The reality is more complex—chat history is only one part of the context window. A complete context window typically holds the following seven types of content:
- Conversation history: The real-time interaction record between the user and the agent, including questions, instructions, answers, and clarifications.
- File contents: Source code, configuration files, and document excerpts that the agent has actively read or edited. This content is large and updates as operations proceed.
- Command output: Results returned after the agent executes terminal commands such as builds, tests, or searches. Output may include error logs, test reports, or runtime data.
- Persistent rules: Project-level rule files, such as a project guide or specification document, used to inject fixed behavioral constraints into every session—for example, coding style, prohibited APIs, or testing requirements.
- Automatic memory: “Learning records” the agent saves across sessions, such as user preferences, past decisions, and commonly used paths, helping it align quickly in the next conversation.
- Loaded skills: When a skill is triggered, its full instruction text—including examples and tool-call guidance—is injected into context, becoming a temporary but space-consuming part.
- System instructions: The agent framework’s own operating rules, available tool definitions, safety boundaries, and output-format requirements. This is “meta-information” that guides how the agent calls other tools.
Together, these seven types of information form the full basis for the agent’s decisions. Understanding them is a prerequisite for understanding agent behavior.
2. Context Compaction: The Source of Information Loss and Mitigation Strategies
When the context window approaches its limit, the agent must make trade-offs. Common handling typically proceeds in two steps:
- Step 1: Clear low-timeliness bulky items—prioritize removing earlier tool-call output, file-read results, and command execution logs. This data is large but often outdated; for example, an early build error log may have no value after later fixes.
- Step 2: Summarize and compress the entire conversation history—condense specific wording, values, and code snippets into a summary description. For example, “the user asked for REST style in round 3 and strongly opposed GraphQL” may be abstracted as “the user prefers REST.”
The direct consequence of compaction is reduced information precision. An architectural decision discussed in round 5 may become a vague summary after compaction. This is why agents “forget” instructions in long conversations—not because the model lacks capability, but because the context has been aggressively compressed.
Mitigation: Let Critical Information Escape Compaction
Option 1: Write rules that must persist across turns into a persistent rule file. Rule files are reinjected on every request, so their content remains intact no matter how many compactions occur. For example, if your project requires “all public functions must have type annotations,” write that into the rule file instead of repeating it in conversation. You can also add a “compression protection” section to the rule file that explicitly states: “When the conversation is compacted, the following information must be preserved verbatim: API change records, security conventions, and release process.”
Option 2: Actively trigger compaction and specify the focus. Many agents provide an active compaction command, such as /compact, allowing users to issue it during a conversation with focus keywords such as “focus on API changes.” The agent then preserves details relevant to the focus during compaction, reducing the loss of non-critical information. Use it proactively during long tasks rather than waiting for the window to overflow.
3. Persistent Rules: The Injection Mechanism for a Project-Level “Constitution”
Persistent rules—usually carried in specific filenames such as CLAUDE.md on some platforms or AGENTS.md in other projects—are plain-text instruction sets automatically loaded before each run. Their biggest difference from chat history is that they are never compacted and always present. They function like a project README, but for an AI agent rather than a human reader.
How to Write High-Quality Rule Files
- Clear responsibilities: Define the agent’s role, permission boundaries, and default behavior. For example: “You are the senior backend engineer for this project, responsible only for business logic and not for database migrations.”
- Coding conventions: List required code style (indentation, naming), prohibited patterns (such as unsafe SQL concatenation), and required test coverage.
- Workflow constraints: Specify execution order, for example: “Run unit tests before submitting a PR” and “Run lint after generating any file.”
- Compression protection clause: Add a separate “compression retention list” that names the types of information that must be fully preserved even under context compaction, such as “the branch currently being worked on” and “confirmed third-party dependency versions.”
A practical recommendation: treat the rule file as the “project constitution” and keep it concise and high-priority. An overly long rule file itself consumes context and may even distract the agent. Usually keep it under 200 lines and use clear hierarchical headings.
4. Hooks: Automating Lifecycle Events
The hook mechanism allows an agent to automatically trigger external commands or scripts before or after specific lifecycle events. It is an event-driven automation capability that makes the agent not merely responsive but actively integrated into the development workflow.
Common hook scenarios include:
- Before session start: Pull the latest dependencies, sync environment variables, and detect whether unfinished code changes already exist.
- After each file modification: Automatically run formatting and static checks, and instruct the agent to fix errors.
- Before each command execution: Validate the command against an allowlist and block dangerous operations, such as deleting a production database.
- Before context compaction: Save critical state to an external file or notify the user that compaction is about to occur.
Hooks work by defining an event table, where each event is bound to a script path and input parameters such as file paths or command content. Each time the agent enters that event, it synchronously launches the script and uses the script’s exit code to decide whether to continue subsequent operations. For example, if a pre-compaction hook finds that tests are failing, it can cancel compaction or prompt the user.
Used well, hooks can extend the agent’s “memory” to external storage—for example, writing important information to a log file before each compaction and reading that file through a hook after compaction to reinject context. This kind of external memory can significantly alleviate the limited context problem.
5. Skills: On-Demand Specialized Instruction Packs
A skill is a reusable capability encapsulation, similar to a module or plugin in programming. A skill usually contains a set of instructions, example code, tool usage guidance, and sometimes an embedded small prompt template. Unlike rule files, skills are not loaded every time; the agent automatically identifies and triggers them based on task intent.
Skill Design Principles
- Single responsibility: Each skill solves a problem in a specific domain, such as “generate REST API documentation,” “refactor a Python class,” or “analyze performance bottlenecks.”
- Self-contained: A skill must carry all background information needed to complete the task, including preconditions, step sequence, common pitfalls, and success criteria.
- Clear trigger conditions: The skill description should state, “When the user mentions X, load this skill.” The agent decides whether to inject it through semantic matching.
Skills and Context Management
Once a skill is triggered, its full instruction text is injected into context and occupies space. Therefore, skills should not be overly verbose. The best practice is to condense the skill’s core logic into an “action checklist plus decision rules,” place details that need long-term retention in external files, and have the skill provide only the path to those external files for the agent to read on demand. This uses the skill’s capabilities while avoiding filling the context all at once.
6. Subagent Delegation: An Execution Architecture for Hierarchical Collaboration
A subagent is a temporary “instance” generated by an agent to complete complex tasks. Subagents can execute subtasks in isolated contexts and return results to the main agent. This is the core implementation of multi-agent systems.
Why Delegation Matters
- Context isolation: The main agent does not need to carry all intermediate processes. Subagents handle the grunt work and return only concise results, saving main-context space.
- Parallel execution: Multiple subagents can handle independent tasks simultaneously—for example, one searches documentation while another generates test cases, with results aggregated at the end.
- Specialized division of labor: Subagents can be assigned different roles, such as code reviewer, algorithm designer, or test engineer, each with more focused system instructions.
Delegation Pattern: Plan-and-Execute
The most typical delegation pattern is plan first, then execute:
- Planning phase: The main agent analyzes the task, decomposes it into substeps, and assigns an appropriate subagent to each substep.
- Execution phase: The main agent launches subagents sequentially or in parallel. Each subagent has an independent context and completes concrete operations.
- Aggregation phase: Subagents return structured results, such as a list of modified files or a test report, and the main agent decides the next step based on those results.
For example, given the task “refactor the database access layer and update all callers,” the main agent might plan for subagent A to analyze existing call relationships, subagent B to generate new data access interfaces, and subagent C to update test cases. After the three execute asynchronously, the main agent aggregates the results and commits them together. This architecture greatly improves the completion rate and reliability of large tasks.
7. From Theory to Practice: Building a Stable AI Coding Workflow
After understanding the five mechanisms, you can improve your development workflow in three ways:
1. Build a “Rules + Skills” Two-Layer Safeguard
Write project constraints into the rule file and encapsulate reusable complex operations as skills. For example, the rule file declares that “all new code must support Python 3.10+,” while a skill contains a detailed template for “how to write asynchronous code.” The agent then both follows the baseline and has extensibility.
2. Design Hooks for External Memory
For high-frequency information that is easily lost—such as environment variable lists or an ongoing refactoring plan—write it to a .agent-memory.md file through a hook before each context compaction, and read it through a hook at the next session start. Even if it is forgotten after compaction, it can be recovered quickly.
3. Proactively Use Subagents for Long Tasks
When a task involves multiple files and multiple steps, do not expect to complete it step by step in the same context. Actively plan delegation: “First use subagent A to analyze all interface definitions and return a summary,” then have subagent B implement changes based on that summary. This effectively reduces main-context bloat and avoids “forgetting” caused by compaction.
Conclusion
The capability boundary of AI coding agents depends on how deeply you understand these five mechanisms. Context compaction is an unavoidable constraint, but persistent rules, hook-based external memory, on-demand skill loading, and hierarchical subagent delegation can minimize the impact of information loss while making the agent’s workflow more aligned with engineering conventions. Mastering these core concepts turns you from a “prompt writer” into an “architect” who truly steers AI agents. As agent frameworks evolve, these mechanisms will mature further, but the underlying trade-offs and design philosophy will remain valid for a long time.
