AI Coding Agent Mechanisms Explained: Context Windows, Rule Files, Hooks, Skills, and Subagents

    This article breaks down the five core mechanisms that determine how well an AI coding agent (its agent harness) performs on real software engineering work: how the context window is assembled from seven distinct content types, how context compaction works and why instructions drift in long sessions, how rule files keep conventions durable and versionable, how hooks move deterministic logic out of prompts and into the framework, how skills load capability packs on demand, and how subagents isolate exploration work behind a separate context window. It also covers two task orchestration patterns, ReAct and Plan-and-Execute, and closes with five practical recommendations for turning these mechanisms into a working method.

    Introduction: Why Knowing the Commands Is Not the Same as Knowing the Mechanism

    When working with an AI coding agent — that is, an agent harness, the runtime framework that carries a large language model through software engineering tasks — developers run into a familiar set of problems. Coding conventions agreed on a few turns ago are forgotten late in a long session. Reading one large file noticeably degrades the quality of reasoning that follows. A task runs for half an hour, one requirement changes midway, and the agent throws out everything it already implemented and starts over.

    None of these are model capability problems. They follow from how the runtime framework is designed. Today’s mainstream AI coding agents generally provide five kinds of capability: context management, rule files, hooks, skills, and subagent delegation. Understanding how each of them works internally improves output quality more than memorizing another list of commands. This article takes a general architecture perspective and unpacks these five core concepts one at a time.

    1. The Context Window: Seven Types of Content Assembled Dynamically

    The most common misconception is treating the context window as a chat log. In reality, the conversation history is only one of its components. A typical context window is assembled from seven:

    1. Conversation history: the record of user inputs and model outputs;
    2. File contents: source fragments the agent has read or edited, usually the largest consumer of space;
    3. Command output: results from terminal commands, builds, and test runs;
    4. Persistent rules: project-level convention files (typically Markdown files maintained at the repository root);
    5. Automatic memory: user preferences and project background carried across sessions;
    6. Loaded skills: the full instruction text injected when a skill is triggered;
    7. System instructions: the framework’s own operating rules, tool signatures, and invocation constraints.

    The key insight is that all seven share one finite token budget. Reading a large file is equivalent to consuming the space of dozens of turns of conversation.

    Two Strategies for Reclaiming Context

    When the budget gets tight, the industry commonly applies a two-step reclamation mechanism.

    Step one: tool result cleanup. Contents that are “large in size, low in time sensitivity” — file read results, command execution output — are removed first, keeping only a summary or a path reference.

    Step two: history summary compression. The entire conversation is semantically condensed, replacing specific wording, numbers, and code snippets with general descriptions.

    Compression always loses information. A naming convention emphasized in turn three, an architecture decision finalized in turn seven — after compression these may survive as nothing more than “discussed the architecture.” That is the root cause of instruction drift in long sessions. It is not that the model is forgetful; the text carrying the instructions has been replaced.

    Three Engineering Responses

    Move long-term rules out of the conversation. Conventions that need to hold across turns or across sessions belong in a rule file at the repository root, not in repeated reminders inside the chat. A rule file has one critical property: it lives independently of the conversation history, so compression does not shrink it.

    Compress proactively, not reactively. Most frameworks support triggering compression manually and allow you to specify what to preserve — for example, explicitly requesting that interface changes and database schema adjustments be retained. Compared with the system compressing automatically at a threshold, proactive compression protects the information that actually matters.

    Control the granularity of what you ingest. Rather than reading a whole file, locate the relevant code block with retrieval. Rather than running a command that emits tens of thousands of log lines, add a filtering flag. Restraint on the input side beats any compression algorithm.

    2. Rule Files: Put Conventions in the Project, Not in the Conversation

    Rule files (named differently across frameworks, commonly an explanatory Markdown file at the project root) solve the problem of having to restate the same context in every session. Their value shows up on three levels:

    • Persistence: re-injected at the start of each session or after context compression, unaffected by summarization;
    • Versionability: as repository files they enter code review and change tracking, so team conventions evolve uniformly;
    • Layering: project-wide rules live at the root, subdirectories can maintain their own local rules, and those are layered on when the agent works inside that directory.

    In practice, a “concise plus index” style works best. Longer is not better — a rule file also consumes token budget. A sound structure states only the hard constraints that genuinely affect output (technology stack versions, directory conventions, prohibited actions, testing requirements) and leaves detailed documentation in the codebase, with the rule file pointing to it by path so the agent can read on demand.

    Pay particular attention to how you write the compression instructions. Some frameworks let you declare in the rule file what information must be preserved during compression, for example:

    1. ## Compression Retention Requirements
    2. When performing context compression, the following must be preserved in full:
    3. 1. Confirmed database schema changes
    4. 2. Implementation approaches the user has explicitly rejected
    5. 3. The outstanding to-do list

    Declarations like this significantly reduce decision loss caused by compression.

    3. Hooks: Injecting Deterministic Logic at Lifecycle Points

    The value of hooks is moving “things that must happen” from the prompt into the framework. A prompt depends on the model understanding and cooperating, which is probabilistic. A hook is enforced by the framework, which is deterministic.

    Common lifecycle points include session start, before user input is submitted, before a tool call, after a tool call, after a file write, and session end. Scripts can be attached at each point, and their result determines the flow: allow, block, or append information to the context.

    Several high-value uses:

    Automatic formatting and static analysis. Run formatting and linting after a file write so style issues are not left for human review.

    Dangerous command interception. Inspect the command content before a tool call and block destructive operations outright, requiring explicit confirmation.

    Automatic context supplementation. At session start, inject the current branch name, outstanding to-dos, and recently failing tests, eliminating manual handoff.

    Sensitive data checks. Before submission, scan for credentials such as keys and tokens that may have slipped in.

    A sample hook configuration (field names differ between frameworks; this only illustrates the structure):

    1. {
    2. "hooks": {
    3. "PostToolUse": [
    4. {
    5. "matcher": "Write|Edit",
    6. "command": "npm run format && npm run lint"
    7. }
    8. ],
    9. "PreToolUse": [
    10. {
    11. "matcher": "Bash",
    12. "command": "./scripts/check-dangerous-cmd.sh"
    13. }
    14. ]
    15. }
    16. }

    Two principles for writing hooks. First, be fast: hooks run on the critical path, so their latency directly affects interaction smoothness. Second, be idempotent: a hook may be triggered more than once, and its script should not accumulate side effects.

    4. Skills: Capability Packs Loaded on Demand

    Skills address the tension between having too many instructions and not needing all of them every time. If every domain convention, template, and best practice were pushed into the system prompt, the context budget would be consumed by static text almost immediately.

    Skills work through progressive disclosure: the framework keeps only the name and short description of each skill resident in the context, and loads the full instruction text when the model judges a skill relevant. Some implementations go further, letting a skill reference external files so reading can be staged across multiple levels.

    A typical skill package has three parts: metadata (name, description, trigger conditions), instruction body (execution steps and constraints), and supporting resources (templates, scripts, reference documents).

    When designing a skill, the description matters more than the body. Trigger accuracy depends on whether the description clearly expresses “when you should use me.” Too abstract, and the skill never activates. Too broad, and it fires on unrelated tasks, consuming context anyway.

    The division of labor with rule files also needs to be clear: rule files carry hard constraints that apply unconditionally, skills carry methodology that applies conditionally. The former is like law; the latter is like a handbook.

    5. Subagents: Context Isolation and Parallel Delegation

    When a task requires a large amount of intermediate exploration — searching the whole codebase, investigating several candidate approaches — the main session’s context gets polluted with low-value intermediate results. Subagent delegation moves that exploration outside entirely.

    The mechanism: the main agent hands the subtask along with the necessary background to an independent subagent. The subagent has its own context window, completes the exploration itself, and returns only a conclusive summary to the main session. The intermediate process never enters the main context.

    This yields three benefits:

    • Context protection: search results across dozens of files do not consume the main session’s budget;
    • Specialization: different subagents can be configured with different roles and tool sets, for example one each for code review, test writing, and dependency analysis;
    • Parallelism: independent subtasks can be dispatched simultaneously, shortening overall time.

    The costs are equally clear: a subagent sees only the background passed to it, so missing information must be supplied explicitly by the main agent at delegation time; shared state across subagents cannot be synchronized directly; and each delegation carries startup overhead. Delegation therefore suits tasks with clear boundaries that can be completed independently and whose output can be compressed. It does not suit tightly coupled work requiring frequent check-backs.

    Two related task orchestration patterns are also worth knowing. The ReAct pattern handles tasks needing external feedback through a loop of thought, action, and observation. The Plan-and-Execute pattern produces a complete plan first and then executes it step by step, which fits larger engineering work whose steps can be decomposed in advance; its strength is global consistency, its weakness is the cost of re-planning once the plan breaks down. A hybrid strategy is common in practice: a plan at the top level to fix the structure, loops locally to handle uncertainty.

    6. From Mechanisms to Method: Five Practical Recommendations

    1. Build a habit of maintaining the project rule file. Distill the issues that keep recurring in review into rule entries, so conventions evolve with the repository rather than traveling by memory.

    2. Manage your context cadence actively. In long tasks, compress deliberately at phase boundaries and specify what to keep, instead of waiting for the system to reclaim space automatically.

    3. Push deterministic logic down into hooks. Any check that must happen every time is worth moving from the prompt to an automated script.

    4. Split skills by trigger condition. Make high-frequency general methodology into skills, keep low-frequency hard constraints in the rule file, and avoid inflating the static prompt.

    5. Use subagents to isolate exploration. For large-scale code searches and multi-approach comparisons, delegate rather than do it yourself, preserving the reasoning quality of the main session.

    Conclusion

    Much of the difference in how AI coding agents perform comes not from the model itself but from how deeply the user understands the mechanisms. The finiteness of the context window cannot be avoided, but layered management works around it. Instruction following is probabilistic, but hooks can supply determinism. Intermediate noise in complex tasks cannot be eliminated, but delegation can isolate it.

    Put the rules in the project, the checks in scripts, the exploration in subagents, and compression under your own control — do those four things well and both the stability and predictability of the collaboration improve by an order of magnitude. If you want to validate these mechanisms further, starting from a lean command-line agent prototype and iterating on it is the lowest-cost, most direct path.