Coding Agent Harness Explained: The Five Core Mechanisms Behind AI Coding Tool Performance

    A practical deep dive into the five mechanisms that govern how AI coding agents behave—context window management, project rules files, lifecycle hooks, on-demand skills, and subagent delegation—and why the same model can perform several times differently depending on the harness around it. Covers how the context window is filled and compressed, how to structure layered persistent rules, how to enforce constraints with hooks, how progressive disclosure keeps reusable skill packs cheap, and how context isolation enables focus and parallelism, with config and script examples, an end-to-end walkthrough, and a practical adoption checklist.

    Introduction: The Model Sets the Ceiling, the Harness Sets the Floor

    When people actually use AI coding tools day to day, they often run into a counterintuitive phenomenon: the same model, wrapped in a different shell, can produce several-fold differences in coding efficiency. The reason has little to do with model capability and everything to do with the runtime framework that carries the model—what the industry usually calls the Agent Harness. The harness is responsible for four things: task orchestration, tool dispatch, context governance, and permissions plus observability.

    A useful analogy: the model is the engine, while the harness is the transmission, drivetrain, and braking system. A mature harness typically has the following characteristics:

    • A context management strategy that decides what goes into the window, when to evict, and when to compress;
    • A persistent rules mechanism that keeps project-level constraints in force across sessions and turns;
    • Lifecycle hooks that turn “what we hope the model follows” into “what the process enforces”;
    • On-demand capability packs that extend the methodology without permanently occupying the window;
    • Subagent delegation that trades context isolation for focus and parallelism.

    Two points are worth attention when choosing a tool. First, the degree of support for heterogeneous models—including how friendly the integration is for domestic models, the stability of tool calling (function calling), and the truncation behavior with long contexts; these differ noticeably across models. Second, whether the extension mechanism is open and whether configuration can be version-controlled. It is worth noting that different tools vary in how they name configuration fields, hook event names, and compression trigger thresholds. This article uses the mechanism names that are common in the industry; for specific fields, refer to the official documentation of the tool you use.


    1. The Context Window: It Holds Far More Than the Conversation

    1.1 Seven Types of Content Share the Window

    The intuition most people have is “the context is just what I said and what it replied.” In reality, the conversation history is only one category. A typical window contains seven:

    Category Content Space profile Time profile
    Conversation history User instructions and assistant replies Grows linearly with turns Medium
    File content Source code that has been read or edited A single file can occupy thousands of tokens Medium, easily stale
    Command output Terminal / test / build results Largest share; logs can reach tens of thousands of tokens Low, discarded after use
    Rule files Project-level persistent rules Small and stable High, valid long-term
    Automatic memory Learning records accumulated across sessions Small High
    Loaded capability packs Full instructions injected after a skill is triggered Medium, on demand Medium
    System instructions The framework’s own runtime rules and tool definitions Fixed overhead High

    The key insight: the context is a workbench, not a warehouse. The right way to use a workbench is to have “the materials needed for the current step within reach,” not “everything that might possibly be used spread out.”

    1.2 The Three Main Sources of Bloat

    Ordered by contribution to size, they are usually: command output (compile errors, test logs, dependency install output), whole-file reads (opening several large files at once), and repeated reads (the same file loaded again and again across turns). The first is often a difference of orders of magnitude—a build failure log with a full stack trace can be equivalent to hundreds of lines of code.

    1.3 Two-Level Compression Strategy

    When the window nears its limit, mainstream implementations use a two-step eviction that goes from “cheap” to “expensive”:

    First, clear the older, large, low-value content. File read results and command outputs are removed first, because in most scenarios they have already served their purpose. This step is nearly lossless; the only cost is that if the content is needed again later, it must be re-read.

    Second, summarize and compress entire spans of conversation history. The specific wording, numbers, and code snippets are condensed into high-level descriptions. This step causes genuine information loss.

    Different implementations use different trigger thresholds, but the strategic direction is highly consistent.

    1.4 The Real Reason for “Forgetting”

    This explains a common puzzle: the naming convention was emphasized in turn three, and an architecture decision was settled in turn five, yet the model “forgets” by turn twenty. This is not the model being absent-minded—the historical span containing that content has been covered by a summary, leaving only a vague generalization like “the user once discussed interface design.”

    There are four corresponding solutions, in priority order:

    1. Externalize rules. Constraints that need to stay in force across turns should be written into a project rules file rather than left in the conversation. The rules file is re-injected after compression and does not participate in summarization.
    2. Compress proactively with a specified focus. Most implementations offer a proactive compression command that can carry retention requirements—for example, limiting the focus to “this interface change and the migration steps.” Passive compression loses information uniformly; proactive compression retains it selectively, and the difference in outcome is significant.
    3. Reduce input noise. Use keyword search to locate code and submit only the necessary snippets; filter command output through a pipe to keep only failure lines and key counts.
    4. Persist to disk in stages. Break a long task into multiple sessions—explore, design, implement, verify—and write each stage’s conclusions into a design document, so the next session starts from the document. This is the most effective approach; essentially it uses the file system as long-term storage in place of the context window.

    2. Project Rules Files: Turning “Things You Say Every Time” into “Things Said Automatically”

    2.1 Role and Lifecycle

    A project rules file (commonly a rules Markdown at the repository root, named a project convention file or agent instructions file by different tools) plays the role of persistent constraints. Three properties determine its value: it is version-controlled along with the codebase, loaded at the start of a session, and re-injected after context compression.

    2.2 Layered Structure

    Practice has converged on a stable three-layer convention:

    • User-level: personal preferences, placed in the user’s home directory, in force across projects—for example, “reply in Chinese” or “write commit messages in English using the Conventional Commits format”;
    • Project-level: shared tech stack, directory conventions, and validation requirements, committed with the repository;
    • Subdirectory-level: supplementary rules that take effect locally, such as interface conventions that apply only to a specific module.

    The “takes effect locally” mechanism is important: when operating inside a subdirectory, its rules are appended to the current context, avoiding a project-level file bloating into an unmaintainable giant document.

    2.3 What to Write and What Not To

    Should be written in: executable hard constraints, automatically verifiable conventions, team-specific command and path conventions, and retention instructions that must survive compression.

    Should not be written in: project history, large architecture documents (these belong in separate docs that the model reads on demand), and facts that will quickly go stale with iteration (version numbers, the current owner). The first goal of a rules file is that “every line can change the model’s behavior”—a rule that cannot be verified or has already expired only dilutes attention.

    An illustrative structure (fields and section names can be adjusted as needed):

    1. # Project Collaboration Rules
    2. ## Tech Stack and Dependencies
    3. - Lock the language version in the config file; using higher-version syntax in code is forbidden
    4. - New dependencies must first state their purpose and size impact; unreviewed packages are forbidden
    5. ## Code Style
    6. - Functions must not exceed 60 lines; split them when they do
    7. - Error handling uniformly returns structured errors; swallowing exceptions is forbidden
    8. - Good: `return fmt.Errorf("load config: %w", err)`
    9. - Bad: `if err != nil { return nil }`
    10. ## Validation Requirements
    11. - After changes, `make lint && make test` must be run; fix failures before delivering
    12. - Database changes must include both forward and rollback scripts
    13. ## Compression Retention Instructions
    14. When compressing context, the following must be retained verbatim, item by item, without summarizing:
    15. 1. Confirmed data table field changes and migration order
    16. 2. Unfinished TODO items and their blocking reasons
    17. 3. Approaches the user has explicitly rejected

    2.4 Maintenance Strategy

    Rules files should be reviewed like code: changes go through a Pull Request, note the reason for the change, and periodically clean up stale entries. A rule of thumb is to keep it within a few hundred lines; once it exceeds a thousand, most of the content should be split into reference documents read on demand, or distilled into a capability pack.


    3. Hooks: Turning Reminders into an Enforced Process

    3.1 Mechanism Definition

    Hooks are user scripts that execute automatically at specific event points in the agent’s lifecycle. Typical event points include: before a tool call, after a tool call, after a file is written, at session start, at session end, and before context compression.

    Hooks are critical because they are fundamentally different from rules files: a rule is a hint that can be ignored; a hook is an execution that inevitably happens. When a constraint “must never be violated,” it should exist as a hook, not as a hoped-for sentence of natural-language instruction.

    3.2 Three Typical Uses

    • Guardrails: block dangerous commands (recursive deletes, force pushes, destructive database operations) and validate that the scope of changes has not overstepped bounds;
    • Automation: auto-format after edits, run static checks after saves, auto-append a change summary before commits;
    • Observability: log every tool call and its duration, output to a logging service or monitoring/alerting system, providing data for later cost accounting and effectiveness evaluation.

    3.3 Configuration and Script Example

    1. {
    2. "hooks": {
    3. "PreToolUse": [
    4. {
    5. "matcher": "Bash",
    6. "hooks": [{ "type": "command", "command": "./scripts/guard.sh" }]
    7. }
    8. ],
    9. "PostToolUse": [
    10. {
    11. "matcher": "Edit",
    12. "hooks": [{ "type": "command", "command": "./scripts/fmt.sh" }]
    13. }
    14. ]
    15. }
    16. }
    1. #!/usr/bin/env bash
    2. # Read the JSON passed to the hook from stdin and check whether the command matches dangerous patterns
    3. set -euo pipefail
    4. input=$(cat)
    5. cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // ""')
    6. patterns=('rm -rf /' 'git push --force' 'drop table' 'truncate table' ':(){')
    7. for p in "${patterns[@]}"; do
    8. if [[ "$cmd" == *"$p"* ]]; then
    9. echo "Blocked high-risk command: $p" >&2
    10. exit 2 # Exit with a code that signals blocking; the value differs by implementation—check the docs
    11. fi
    12. done

    3.4 Engineering Considerations

    • The exit-code convention that signals blocking varies by implementation; always follow the docs—getting it wrong will silently break the interception;
    • Hook scripts must return quickly; a slow script on the critical path will slow down every tool call;
    • Don’t put credentials in scripts; inject them via environment variables or a secrets management service;
    • Define a clear failure policy: when a script errors, choose whether to allow or block; for security scenarios, prefer blocking and alerting;
    • Don’t embed business logic in hooks; a hook should be a thin guard layer, with the real logic in a standalone tool.

    4. Skills: Reusable Capability Packs Loaded on Demand

    4.1 Mechanism and Progressive Disclosure

    A capability pack (skill) bundles the methodology, operational flow, reference documents, and helper scripts for a class of tasks together; it is triggered when the task matches its description, and its instruction body is injected into the context. Its core design idea is progressive disclosure, in three layers:

    1. Resident layer: keep only the name and a one-line description, occupying minimal window;
    2. Injection layer: after the trigger condition is met, inject the full instruction body;
    3. Reference layer: the reference docs, data templates, and executable scripts pointed to in the body, read or run only when needed.

    This layering is precisely the key to resolving the tension between “extending capabilities” and “the window budget”: capabilities can grow without limit, while the resident cost stays almost unchanged.

    4.2 Applicable Scenarios

    Team-standardized release and rollback flows, online incident troubleshooting playbooks (which metrics to check first, what the log-filtering commands are), coding best practices for a specific framework, periodic report generation, and code-standard checks with automatic fixes. The judgment criterion: the work has a stable flow, needs external scripts or reference material, and is executed repeatedly.

    4.3 Relationship with Other Mechanisms

    • Rule files are resident constraints, answering “what can’t be done”;
    • Capability packs are on-demand knowledge and methods, answering “how this kind of task should be done”;
    • Subagents are execution isolation, answering “who does it in an independent context”.

    The three are complementary and cannot replace one another.

    4.4 Structure and Writing Example

    1. skills/
    2. └── release-checklist/
    3. ├── SKILL.md
    4. ├── references/runbook.md
    5. └── scripts/verify_release.py
    1. ---
    2. name: release-checklist
    3. description: Use when the user needs to perform a production release, canary rollout, or rollback; includes the checklist, canary ratios, and rollback criteria
    4. ---
    5. # Production Release Checklist
    6. ## Pre-checks
    7. 1. Confirm the change list and database migration scripts have passed review
    8. 2. Run scripts/verify_release.py to validate config and dependency consistency
    9. ## Canary Steps
    10. 1. Canary on a single instance; observe error rate and P99 latency for 10 minutes
    11. 2. Raise the ratio to 20%, then observe for another 15 minutes
    12. 3. After full rollout, keep monitoring for 30 minutes
    13. ## Rollback Criteria
    14. - If the error rate exceeds 2x the baseline, or P99 latency doubles, roll back immediately
    15. - For rollback, follow the steps in section 3 of references/runbook.md

    Design points: the description must clearly state the “when to use” trigger condition, not just a feature summary—otherwise it will mis-trigger or never trigger; prefer providing executable scripts over making the model hand-write repeated logic each time; capability packs should be version-controlled with the repository and shared with the team; avoid namespace collisions, and manage them by domain in separate directories when there are too many.


    5. Subagents: Trading Context Isolation for Focus and Parallelism

    5.1 Mechanism Definition

    The main agent delegates a subtask to a subagent running in an independent context; when the subagent finishes, it reports only a summary of conclusions back to the main agent, while the intermediate file content, search results, and logs do not enter the main context.

    Illustrative configuration (field names vary by tool):

    1. {
    2. "subagents": {
    3. "code-reviewer": {
    4. "description": "Read-only code review; modifying any file is forbidden",
    5. "tools": ["Read", "Grep", "Glob"]
    6. },
    7. "test-writer": {
    8. "description": "Add unit tests for a specified module; changing business code is forbidden",
    9. "tools": ["Read", "Grep", "Glob", "Write", "Bash"]
    10. }
    11. }
    12. }

    5.2 Why It Works

    • Context isolation: a cross-repository investigation might read in dozens of files, yet only a three-line conclusion is reported back, so the main context is hardly polluted—a structural solution to the compression problem discussed earlier;
    • Role specialization: each subagent has its own prompt and tool allowlist; a read-only review role cannot mistakenly change code, and the security boundary is determined by configuration rather than by a prompt;
    • Parallel execution: independent investigation and troubleshooting tasks can proceed simultaneously, shortening end-to-end time.

    Abstracting the current mainstream agent paradigms helps avoid conflating concepts:

    • ReAct (the reason–act–observe loop) is the core runtime mode of a single agent; any tool-using agent is essentially looping through “think, call a tool, read the result”;
    • Plan-and-Execute adds an explicit planning phase on top, with the advantage that long-chain tasks are auditable and can be interrupted midway, at the cost that the plan can easily drift from the real code state, so re-planning must be allowed;
    • Multi-Agent (multi-role collaboration) divides roles on top of planning—for example, architecture, implementation, testing, and review each moving forward—suitable for large tasks, but the coordination cost, context synchronization, and result drift rise accordingly; when task boundaries are not cleanly separated, quality is often lower than a single strong agent.

    Engineering conclusion: first go deep with ReAct, then add a planning phase on long tasks as needed, and finally introduce multiple roles only when the task can genuinely be parallelized and the boundaries are clear. Don’t increase the number of agents just to make the architecture look nice.

    5.4 Usage Principles

    Require subagents to report conclusions, evidence, and file line numbers, not “done”; forbid multiple subagents from writing the same file at the same time; limit delegation depth to avoid recursion; log the token consumption and time of each delegation—otherwise the cost growth from parallelism is invisible.


    6. How the Five Work Together: An End-to-End Chain

    Take “adding idempotent writes to an order service” as an example. The entry points of each mechanism are as follows:

    1. The main agent reads the task; the rules file is automatically injected with team conventions (error handling, mandatory migration and rollback scripts);
    2. The main agent delegates a read-only subagent to investigate the existing write paths and callers; it reports the key files and line numbers, so the massive codebase does not enter the main context;
    3. It adopts plan mode to first produce an implementation plan and impact surface, and enters coding only after the user confirms;
    4. The main agent edits code; after each edit, a hook automatically formats and runs static checks, and a pre-call hook blocks any command that changes the database schema;
    5. Test failure logs, after being filtered through a pipe, keep only the failing cases, so the window is not flooded with logs;
    6. If the window nears its limit, proactive compression is triggered, retaining “field changes, migration order, unfinished items” while the rest of the history is summarized;
    7. The specific way to write something covered by company conventions is provided by a capability pack that matches the trigger condition, such as the release checklist;
    8. A session-end hook writes this session’s decisions into a design document, to serve as the starting point for the next session.

    The problems each mechanism solves and their failure symptoms can be cross-referenced for troubleshooting:

    Mechanism Problem solved Failure symptom Key metric
    Context management Window overflow and information loss Long sessions forgetting early conventions Number of compression triggers, token consumption per task
    Rule files Loss of cross-session constraints Repeatedly emphasizing the same convention Number of rules, rework rate
    Hooks Constraints that rely only on hints are unreliable Dangerous operations that shouldn’t happen appear Number of blocks, false-positive rate
    Capability packs Capability expansion crowding out the window The right skill not triggering, or mis-triggering Trigger accuracy, resident token share
    Subagents Main context polluted by process information Main session bloated, cost out of control Number of delegations, degree of parallelism, cost increment

    7. Common Pitfalls and an Adoption Checklist

    There are five high-frequency pitfalls: writing long-term rules in the conversation; turning the rules file into a project encyclopedia so attention gets diluted; too many hooks with slow scripts that slow down every tool call; vague capability-pack descriptions that cause mis-triggering; and subagents parallelized blindly without result verification, hiding rework into a later stage.

    A directly actionable adoption checklist:

    • Establish a layered rules file and externalize every requirement you’ve had to repeat three or more times this week;
    • Add a “compression retention instructions” section to the rules file, listing the information that must be retained item by item;
    • Configure a pre-call blocking hook for destructive operations, and a formatting hook for edits;
    • Distill the 1–2 most stable repeated flows into capability packs, with clear trigger conditions;
    • Configure a dedicated read-only subagent for read-only tasks (review, investigation);
    • Build a fixed regression task set to measure first-pass success rate, average number of turns, token consumption per task, and manual rework rate, and use data to judge whether an optimization is genuinely effective.

    Conclusion

    The context window, rules files, lifecycle hooks, capability packs, and subagent delegation—these five mechanisms are not a parallel list of features, but a complete governance chain: window management solves “it fits,” rules files solve “it remembers,” hooks solve “it does it,” capability packs solve “it knows more,” and subagents solve “it doesn’t interfere.” Understanding each one’s failure boundaries is more valuable than memorizing any single configuration field—tools will iterate and config formats will change, but four principles hold across almost all coding-agent frameworks: externalize volatile information, harden strong constraints into execution, load methodology on demand, and isolate noise inside subtasks.