The 5 Core Mechanisms of AI Coding Agents: Context, Rules, Hooks, Skills, and Subagents

    AI coding agents are built on three layers: the underlying large model, the orchestration framework (the agent harness), and the extension mechanisms. The model sets the ceiling, but the harness determines whether that intelligence turns into correct results. This guide breaks down the five core mechanisms shared by mainstream coding agents—context window management, project-level rule files, hooks, skills, and subagents—and explains how they work together as a pipeline rather than a standalone feature checklist. You'll learn what actually fills the context window, why agents "forget" instructions in long sessions, how to structure rule files, how hooks differ from skills and retrieval, and the real trade-offs of subagent delegation.

    1. The Agent Harness Is What You Actually Work With Every Day

    An AI coding tool is usually made up of three layers:

    • The underlying large model — provides reasoning and coding ability.
    • The orchestration framework — commonly called the agent harness in the industry. It handles context organization, tool invocation, and task orchestration.
    • Extension mechanisms — rules, hooks, skills, subagents, and so on.

    The model determines how “smart” the agent is. The harness determines whether that intelligence turns into correct results. The same model can perform a full tier lower under a different harness. The reason is that how context is packed, how rules are injected, how tools are called, and how subtasks are split — all four of these are the harness’s responsibility.

    The five mechanisms below are the common capability foundation shared by mainstream coding agents. Understanding them is what lets you move past “tuning prompts by gut feel.”


    2. Mechanism 1: Context Window Management

    2.1 What is actually in the context

    Many people assume context is just “what I say and what it answers.” In reality, conversation history is only one of seven types of content:

    Category Content example Space characteristic
    Conversation history Records of user–model interactions Grows linearly over time
    File content Source files that were read or edited Largest share; a single file can reach thousands of tokens
    Command output Results of tests, builds, and searches Extremely high peaks; a single log can fill the window
    Project rules Rule files at the repository root Always resident, re-injected every turn
    Automatic memory Learning records saved across sessions Small footprint, long-lived
    Loaded skills Full instruction text injected once triggered Expands the moment it is triggered
    System instructions Framework runtime rules and tool definitions Always resident, not editable

    The point of this table is that context budget is a resource you must actively manage, not something you just “chat” with. Rule files plus system instructions typically take up 10%–20%, and only the rest is space for code and tool output.

    2.2 How compaction happens: two steps

    When context approaches the limit, mainstream tools use two-level handling:

    Step 1: Evict by “space-to-value ratio.” Earlier tool-call outputs — full-file read results, command execution results — take up a lot of space but have low time sensitivity, so they are cleared first. In practice, a record of “which files have already been read” is usually kept to avoid re-reading them.

    Step 2: Summarize and compress the conversation history. Specific wording, numbers, and code snippets are condensed into a summary.

    Both steps are lossy compression, and the consequences are directly observable:

    • A rule you emphasized in turn three may become a vague “user prefers a concise style” after compaction;
    • An architectural decision discussed in turn five is reduced to “solution decided,” with the reasoning lost — so the model changes it on its own;
    • Specific constants, field names, and interface signatures are flattened out of the summary, and the model starts to “guess.”

    This is the real reason a model “forgets” instructions in long conversations — it’s not that the model is incapable, it’s that the carrier of the context was compressed.

    2.3 Four hard rules for dealing with compaction

    ① Put persistent rules in rule files, not in the conversation. The content of a project rule file is re-injected on every request (including after compaction), making it the only stable context that is immune to summarization.

    ② Explicitly declare a “compaction keep-list” in your rule file. Turn “which conclusions must be preserved verbatim” from an implicit expectation into an explicit instruction — for example, require that interface signatures are never rewritten and that rejected options are never dropped during compaction.

    ③ Compromise proactively when switching phases and specify the focus. Mainstream tools provide a command to trigger compaction manually (a common form is /compact focus on the API changes). Compared with passive triggering, proactive compaction keeps the content most relevant to the current task.

    ④ Land output on disk instead of leaving it in the window. Write long test logs to a file, and keep only conclusions and key snippets in the context; read the details back when you need them. This is the most effective budget tactic.


    3. Mechanism 2: Project-Level Rule Files — Turning “Context” into an “Asset”

    Rule files (their exact naming follows the conventions in each tool’s documentation, but they are typically *.md files) are the asset most often underestimated in team collaboration.

    3.1 Layered structure

    • User-level global rules — personal preferences (language, comment style), effective across projects;
    • Project-level rules — tech stack versions, directory conventions, forbidden zones; they travel with the repository;
    • Directory-level rules — special conventions for a specific subdirectory, loaded only when you enter that directory.

    3.2 Writing principles

    Verifiable beats descriptive. “Write high-quality tests” is a description; “every new function must have a corresponding failing test case first” is verifiable.

    Give examples over adjectives. One side-by-side comparison of “write it this way, that’s wrong” beats three lines of style description.

    Keep it restrained. Rule files are injected every turn, so they are a resident cost. Keep them at the thousand-word level and review periodically to delete stale entries.

    Don’t repeat what the model already knows. General syntax and common library usage don’t need to be written down — it wastes budget with no benefit.

    A practical skeleton:

    1. # Project Rules
    2. ## Tech Stack
    3. - Language and framework version constraints (open an issue before upgrading)
    4. - Dependency approval process: only packages on the allowlist may be added
    5. ## Coding Conventions
    6. - Naming, error handling, and logging standards (one positive and one negative example each)
    7. - Every new public function must include parameter validation
    8. ## Pre-Commit Self-Check (run automatically by a hook, no manual step)
    9. - Formatting, static analysis, unit tests
    10. ## Compaction Keep-List (must be preserved verbatim during summary compression)
    11. - Agreed database schema changes
    12. - Rejected options and the reasons they were rejected
    13. - Interface signatures involving billing and permissions

    That last section is the highest-value few lines for long sessions.


    4. Mechanism 3: Hooks — Taking “Certainty” Back from the Model

    Rule files say “we want the model to do this.” Hooks say “the system guarantees it does this.” The two are complementary, and neither is sufficient alone.

    4.1 Event model

    Mainstream tools expose hook points around the tool-call lifecycle:

    Timing Typical use
    Session start Inject the current branch, environment variables, and pending-task context
    Before a tool call Intercept dangerous commands, validate write paths, require confirmation
    After a tool call Auto-format, run static analysis, feed lint results back to the model
    Before/after subagent dispatch Log the delegation chain, enforce concurrency limits
    Session end Archive logs, generate a change summary

    4.2 Configuration example

    1. {
    2. "hooks": {
    3. "PostToolUse": [
    4. { "matcher": "Edit|Write", "command": "make fmt && make lint" }
    5. ],
    6. "PreToolUse": [
    7. { "matcher": "Bash", "command": "scripts/guard-dangerous.sh" }
    8. ]
    9. }
    10. }

    The schema naming differs between tools; what’s shown here is a general semantic model, and the exact implementation should follow the documentation for the tool you use.

    4.3 Design principles

    • Fast: keep a single execution within a few hundred milliseconds, or it will slow down every interaction;
    • Idempotent: running the same input multiple times yields the same result, avoiding noise from repeated formatting;
    • Clear failure semantics: distinguish “warning” from “block”; a check that fails should feed information back rather than being silently discarded;
    • Default to allow, and log: a non-security hook failure should not block the normal flow — just log it and alert;
    • High-risk operations must be intercepted: deletions, force pushes, production config changes, and secret reads must all go through a hook confirmation.

    The real value of hooks is that they downgrade “the model behaving on its own accord” to “the model doesn’t need to behave on its own accord,” which sharply reduces rule drift in long sessions.


    5. Mechanism 4: Skills — On-Demand Capability Packages

    5.1 What a skill is

    A skill = metadata for when to use it + an operating manual for how to do it + optional scripts and reference material. It carries “procedural knowledge,” whereas RAG carries “factual knowledge,” and the two cannot replace each other.

    5.2 Progressive disclosure (three-level loading)

    1. Resident layer: the skill name plus a one-line description, only a few dozen tokens, so the model “knows this exists”;
    2. Load layer: once it’s judged relevant, the full instruction text is injected;
    3. On-demand layer: the large templates, reference docs, and scripts cited in the body are read only when the model needs them.

    The key to this mechanism is that capability can scale indefinitely while the resident cost stays almost flat. This is the fundamental advantage of skills over “cramming all prompts into the system instructions.”

    5.3 Design points

    • Write specific trigger conditions: state clearly “when to use / when not to use” to keep both false triggers and missed triggers low;
    • Single responsibility: one skill solves one class of problem — don’t lump release, migration, and troubleshooting together;
    • Example-driven: given input/output comparisons are far more effective than abstract descriptions;
    • Ship with a check: attach an executable script so the model can verify its own result and close the loop;
    • Avoid semantic overlap in descriptions: when two skills have vague descriptions, routing becomes unstable, showing up as “didn’t trigger when it should have.”

    5.4 The boundaries between three kinds of knowledge

    Dimension Rule files Skills RAG / retrieval
    Loading method Always resident By trigger condition By similarity search
    Nature of content Constraints and preferences Processes and methods Facts and reference material
    Typical use Coding standards, forbidden zones Release processes, migration manuals Internal docs, historical code

    Confusing these three is the main reason a skill library grows messier over time.


    6. Mechanism 5: Subagents — Delegation and Context Isolation

    6.1 Why you need subagents

    • Isolation from pollution: exploring a codebase generates a lot of intermediate content (dozens of file snippets). Put it in a sub-context, bring only the conclusions back to the main context, and keep the main window clean;
    • Parallel speed-up: independent search and review tasks can run concurrently;
    • Focus: a subagent’s system instructions contain only what the task needs, with fewer distractions;
    • Natural boundary: the delegation chain is itself a record of task decomposition, making it easy to review and audit.

    6.2 Four common patterns

    • Orchestrator–executor: the main agent decomposes and integrates; subagents execute;
    • Plan-and-Execute: produce a plan for human review first, then execute — suitable for high-risk changes;
    • ReAct loop: iterate repeatedly through observe–reason–act — suitable for exploration tasks with rich environmental feedback;
    • Multi-way review: multiple subagents produce independent proposals and the main agent picks the best — used for architecture selection.

    6.3 Costs and constraints (that must be faced)

    • Context is not shared: a subagent can’t see the main conversation, so the task description must be self-contained (goal, scope, constraints, delivery format);
    • Cost and latency rise: every delegation re-loads the system instructions and tool definitions — it’s not free;
    • Results can be distorted: a subagent returns a summary. Always agree on a return format: conclusion + key evidence + file paths + verification method.

    An orchestration skeleton:

    1. plan = decompose(task) # Main agent breaks it into independent subtasks
    2. results = parallel_map(subagent, plan) # Delegated in parallel, with self-contained task descriptions
    3. merged = merge(results) # Main agent consolidates and deduplicates
    4. assert verify(merged) # Tests / static checks gate it — don't trust "verbal conclusions"

    The last line is the discipline: a subagent saying “done” is not the same as done — it must be backed by executable verification.


    7. How the Five Mechanisms Work Together: What a Complete Task Looks Like

    1. Initialization: load system instructions, project rules, and automatic memory to form the initial context;
    2. Exploration: the main agent dispatches several subagents in parallel to read code, search docs, and map the impact surface;
    3. Planning: the main agent consolidates the subagents’ conclusions and produces a plan (high-risk scenarios go to review first);
    4. Execution: edit file by file; a PostToolUse hook auto-formats and runs static analysis, feeding failure info back;
    5. Compaction: as context approaches the limit, first clear old tool output, then summarize and compress, with rule files and the compaction keep-list staying in effect;
    6. Wrap-up: run tests, a PreToolUse hook blocks dangerous commits, and a session-end hook archives the logs.

    As you can see, the five mechanisms are not a flat feature list but a pipeline: rules govern “what to do,” skills govern “how to do it,” hooks govern “was it done right,” subagents govern “efficiency and isolation,” and context management governs “not breaking down along the way.”


    8. Common Pitfalls

    • Writing rules that need to stay in effect across turns in the conversation, where they vanish after compaction;
    • Turning the rule file into a model manual — thousands of lines injected on every turn, crowding out space for code;
    • Relying entirely on the model’s own discipline with no hooks at all, so in the later part of a long session it starts “freelancing”;
    • Writing skills too broadly with vague trigger conditions, causing routing instability;
    • Blindly parallelizing subagents — doubling cost while producing contradictory conclusions;
    • Assuming compaction is lossless and leaving key interface signatures in the conversation history;
    • Reading long logs straight into the context instead of landing them on disk and reading on demand.

    9. Team Collaboration and Engineering Recommendations

    • Put it under version control: rule files, skill packages, and hook scripts all go into the repo and through a code-review process, so changes are traceable and rollback-able;
    • Build budget awareness: observe the composition of each turn’s context to locate the biggest consumers (usually full-file reads and command output);
    • Use monitoring to see results: use log services and monitoring alerts to observe delegation failure rates, hook interception counts, and average number of turns, and optimize with data rather than gut feel;
    • Standardize the dev environment: on Baidu AI Cloud, common capabilities such as code hosting, container platforms, and object storage can host skill packages and rule repositories, enabling a distribution model of “rules as code, skills as artifacts”;
    • Run regression comparisons: after changing a rule or skill, run a fixed task set and compare success rate and token consumption, to avoid “fix one thing, break another.”