Context Engineering Practices for Agentic Coding with LLMs

    Agentic coding has moved beyond simple code completion into repository-level tasks that require understanding, planning, retrieval, modification, execution, and verification. This article explores context engineering practices for LLM-based coding agents. It covers how to evaluate agents beyond raw code generation, why a balanced context "sweet spot" beats simply maximizing context length, and how to decompose tasks, control toolchains, and apply harness engineering. It also addresses state management in multi-turn tasks, routing and caching governance, and a typical end-to-end workflow, helping developers build systems that are reliable in real engineering processes rather than only superficially usable.

    1. From Code Completion to Agentic Coding: A Shift in Capability Boundaries

    Traditional code completion typically relies on the current file, the current line, and limited surrounding context, focusing on predicting the next block of code. It is better suited to short-range, low-context coding scenarios, such as completing a function body, generating simple expressions, or filling in logic based on comments. The evaluation of such capabilities is usually straightforward: whether the generated result is usable, syntactically correct, and quickly accepted by the developer.

    Agentic coding is entirely different. It targets repository-level, task-level, and workflow-level problems. The model is no longer just “writing a piece of code”; it must complete understanding, planning, retrieval, modification, execution, verification, and correction across multiple steps. For example, when a developer asks to “fix an exception that a certain module throws under specific input,” the agent needs to locate the relevant code, understand the call chain, determine the root cause, modify the implementation, and then run tests to confirm the result. If the tests fail, it must keep adjusting based on the failure information.

    This means the agentic coding experience no longer depends solely on whether the model can write code, but on the following factors:

    1. Code comprehension: the ability to quickly locate key files, functions, interfaces, and data structures.
    2. Multi-step reasoning: the ability to stay aligned with the goal through cycles of failure, feedback, and re-verification.
    3. Tool-use capability: the ability to correctly use capabilities such as reading, searching, editing, and running tests.
    4. Context management: the ability to retain key information during long tasks and avoid being distracted by irrelevant content.
    5. Result verification: the ability to confirm the correctness of changes through testing, static analysis, log inspection, and other means.

    Therefore, agentic coding is not simply “large model plus code completion,” but a comprehensive engineering capability. The model’s code-generation level is only the foundation; what truly determines the final experience is the combined effect of “model capability + outer task framework + context organization.”

    2. Observations on Chinese Large Models in Agentic Coding

    In recent years, large models developed in China have made clear progress in code comprehension, instruction following, structured output, multi-step reasoning, and tool use. In some agentic coding scenarios, these models can already handle relatively complex tasks, such as cross-file modification, test-driven fixes, interface refactoring, code explanation, and troubleshooting. In some hands-on experiences, they show certain strengths in understanding technical semantics, expressing business context, and following task constraints.

    However, agentic coding is not a contest of a single model’s capabilities. Even with a strong base model, a poorly designed outer framework can degrade the experience. For example:

    • Stuffing too much irrelevant content into the context, so the model loses focus;
    • Defining too many tools, or returning overly long tool outputs, crowding out effective reasoning space;
    • Describing the task too vaguely, so the model cannot determine the acceptance criteria;
    • No state accumulation across multiple turns, causing the model to forget the goal in long tasks;
    • Uncontrollable behavior at the server or routing layer, leading to cache misses, increased latency, or result fluctuation.

    In addition, some high-intensity reasoning models exhibit long thinking processes on complex tasks. This capability helps improve the quality of answers to complex problems, but it may also bring higher response latency, increased token consumption, and higher context-processing costs. In agentic coding scenarios, if the task itself requires multiple rounds of tool calls and long-context interaction, these costs are further amplified.

    Therefore, evaluating whether a model is suitable for agentic coding cannot rely only on single-pass code-generation quality; it must also consider its stability in real engineering workflows, context utilization, task-completion rate, and maintainability.

    3. Evaluation Dimensions of Agentic Coding: Beyond Code Generation

    Many developers, when trying a model, tend to use “how good is this code” as the main criterion. But in agentic coding, this evaluation is incomplete. A model may generate code that looks reasonable but fails the tests; it may also produce a correct change that is too broad in scope and introduces additional risk.

    A more reasonable evaluation should revolve around the engineering loop and include at least the following dimensions.

    1. Task Completion Rate

    Task completion rate is the most core metric. It measures whether the model actually solves the problem, rather than just producing something that “looks like an answer.” For code-fix tasks, it can be reflected in whether the relevant tests pass; for refactoring tasks, in whether behavior stays consistent; for feature-implementation tasks, in whether the acceptance criteria are met.

    2. First-Pass Success Rate

    First-pass success rate focuses on whether the model can directly produce usable results without major manual correction. This metric is critical to developer experience. If the model can generate code every time but it always needs repeated manual adjustment, the actual efficiency is not high.

    3. Context Efficiency

    Context efficiency concerns the ratio of useful information to useless information. In agentic coding, context typically includes the system prompt, task description, conversation history, tool descriptions, code snippets, error logs, and test results. If there is too much irrelevant content, the model is easily distracted, leading to loss of focus or redundant work.

    4. Stability and Reproducibility

    For the same task, under the same input and the same tool environment, whether the model can produce stable results is an important consideration for engineering adoption. If results fluctuate too much, additional manual procedures are needed for verification and fallback.

    5. Latency and Cost

    Agentic coding often involves multiple rounds of calls, so the latency of a single request, the token consumption per task round, and the context-compaction frequency all affect the overall experience. Long-thinking models may improve quality but can also significantly increase waiting time.

    6. Constraint Following

    In engineering scenarios, the model must not only “do it right” but also “do it as required.” For example, whether it modifies only the specified directory, maintains interface compatibility, avoids introducing new dependencies, and runs the specified tests first. Constraint-following capability directly determines whether a model can enter a real development workflow.

    4. The Context Sweet Spot: Why Longer Context Is Not Always Better

    Many developers assume that since a model supports longer context, putting all relevant content into it will yield better results. But in practice, longer context is not necessarily better. On the contrary, overly long context tends to introduce the following problems:

    1. Increased noise: conversation history, irrelevant files, and repeated logs distract the model’s attention.
    2. Dilution of key information: the truly important error messages may get buried.
    3. Higher processing cost: long context increases inference time, cache pressure, and call cost.
    4. State drift: the model may gradually deviate from the original goal over a long context.
    5. Difficult compaction: the more complex the context, the harder it is to preserve key decisions during compaction.

    Therefore, agentic coding calls more for a “context sweet spot” than simply pursuing “maximizing the context window.”

    The context sweet spot refers to choosing a context set that is moderate in size, dense in information, and clear in structure, while still meeting the task’s needs. Empirically, even if a model supports a large context window, it is advisable to reserve enough headroom for high-quality tasks. For common coding tasks, context usage can be kept within a relatively conservative range. For example, when context usage reaches around 50%, you should begin considering compaction, summarization, or starting a new session; when it approaches a higher threshold, you should restructure the context promptly to avoid subsequent quality degradation.

    A referenceable context strategy can be abstracted as:

    1. context_policy:
    2. keep_headroom: true
    3. compact_trigger: 0.5
    4. warning_trigger: 0.65
    5. hard_limit: 0.75
    6. must_keep:
    7. - task_statement
    8. - acceptance_criteria
    9. - current_scope
    10. - changed_files
    11. - failing_tests
    12. - recent_decisions
    13. should_reduce:
    14. - repeated_file_contents
    15. - long_history_logs
    16. - irrelevant_search_results
    17. - stale_error_messages

    The “50%”, “65%”, and “75%” here are not fixed parameters; they remind developers that context management needs to be designed in advance, rather than patched after a task has already failed.

    What Should Be Prioritized in Context

    In agentic coding, it is recommended to prioritize retaining the following types of information:

    1. Task goal: what problem is currently being solved.
    2. Acceptance criteria: how to judge that the task is complete.
    3. Modification scope: which directories or files are allowed to be modified.
    4. Current changes: which files have already been modified and which key decisions have been made.
    5. Failure information: the reason for test failures, error stack traces, and exceptional inputs.
    6. Next-step plan: what the model intends to try next.

    In contrast, the following information is generally not suitable for long-term retention:

    1. Repeated full file contents multiple times;
    2. Conversation history unrelated to the current task;
    3. Old errors that have been resolved and no longer have any impact;
    4. Too many tool descriptions and extended plugin definitions;
    5. Large, unorganized logs.

    The Right Way to Compact Context

    Context compaction is not simple truncation, but information restructuring. An effective compaction result should be able to answer four questions:

    • What is the current goal?
    • What has been done?
    • What is the current failure reason?
    • What is planned next?

    For example, a compacted context can preserve a structure like this:

    1. Task: Fix the exception caused when user input is empty.
    2. Scope: Only the data-validation module may be modified.
    3. Done: Added a null check in the entry function.
    4. Test status: Unit tests still fail with a type mismatch error.
    5. Failure reason: Empty strings are not uniformly converted to empty lists.
    6. Next step: Add unified null normalization logic before the validation function.

    This kind of structured compaction is more effective than simply keeping the raw conversation, because it preserves task continuity and the decision path while reducing noise.

    5. Task Decomposition: Keeping the Agent Within a Controllable Scope

    A common problem in agentic coding is not that the model cannot write code, but that the task is too large and the boundaries are unclear. A broad task description often leads the model to generate a lot of unnecessary content or even modify unrelated modules. To improve stability, developers should decompose the task into small, verifiable steps.

    A complete agentic coding task can be broken down into the following stages:

    1. Understand the task: clarify the problem background, inputs and outputs, the exception behavior, and the expected result.
    2. Locate the scope: find the relevant files, functions, interfaces, and dependencies.
    3. Make a plan: explain how the modification will be made and which modules will be affected.
    4. Execute the change: make only the necessary changes and avoid large-scale refactoring.
    5. Run verification: execute the relevant tests, static checks, or type checks.
    6. Analyze results: if it fails, extract the failure reason and adjust the plan.
    7. Summarize and output: provide a change summary, test results, and remaining risks.

    In prompt design, you can require the model to output a plan first and then execute the modification. For example:

    1. You are a coding agent. Please complete the fix according to the following task.
    2. Task goal: Resolve the exception caused when user input is empty.
    3. Constraints:
    4. 1. Only modify the data-validation module;
    5. 2. Do not change public interface signatures;
    6. 3. Do not introduce new third-party dependencies;
    7. 4. You must run the relevant unit tests after the modification.
    8. First output:
    9. 1. Possible causes;
    10. 2. Impact scope;
    11. 3. Modification plan.
    12. Then perform the code changes and provide the test results.

    The advantage of this approach is that the model does not dive into code details right away, but first establishes a clear solution path. For complex tasks, planning before executing can significantly reduce the probability of going off track.

    6. Toolchain Control: More Tools Do Not Mean More Intelligence

    Agentic coding usually depends on a toolchain. For example, reading files, searching code, editing content, executing commands, running tests, and viewing logs. The richer the toolchain, the stronger the model’s problem-solving ability in theory. But in practice, more tools are not necessarily better.

    Each tool brings three types of cost:

    1. Context cost: tool names, descriptions, parameter explanations, and return values all consume context.
    2. Decision cost: the more tools there are, the more the model must judge which tool to call at the moment.
    3. Error cost: tool-call failures, timeouts, and abnormal return formats can all interrupt the task flow.

    Therefore, in agentic coding, toolchain design should follow the “minimum viable principle”: keep only the tools the current task truly needs. For common code tasks, you can usually prioritize configuring the following capabilities:

    • Reading a specified file;
    • Searching code snippets;
    • Editing a specified range;
    • Running tests;
    • Returning structured error information.

    For complex toolchains, the following optimizations are recommended:

    1. Tool count control: avoid loading too many tools at once.
    2. Output truncation: truncate or summarize overly long logs.
    3. Error compaction: keep only the key error lines and stack traces.
    4. Call constraints: restrict certain tools to specific stages.
    5. Failure-retry strategy: avoid the model repeatedly trying the wrong tool.

    In addition, external extensions, add-on capability packs, and complex retrieval plugins should be used cautiously. They may improve capabilities in some scenarios, but they also add to the context burden. In most code tasks, a stable basic toolchain is often more effective than complex extensions.

    7. Harness Engineering: System Capabilities Beyond the Model

    Harness Engineering is a very important concept in agentic coding. Here, the harness can be understood as the execution and collaboration framework outside the model, including task description, context organization, tool invocation, verification loops, state recording, error feedback, and result aggregation.

    An excellent model without a good harness may also fail to realize its true capability. Conversely, a model of moderate capability, equipped with clear task boundaries, a stable toolchain, and efficient context management, may also complete high-quality tasks.

    The key designs of Harness Engineering include:

    1. Task templating: abstract common tasks into fixed templates to reduce ambiguity from ad hoc descriptions.
    2. Context structuring: manage task goals, constraints, changes, and test status separately.
    3. Automated verification: do not rely on the model’s self-judgment; confirm results through tests and checks.
    4. Standardized failure feedback: error information should include file location, error type, inputs and outputs, and expected results.
    5. Traceable state: every change should record its impact scope for easy rollback and review.

    For example, a stable agentic coding flow can be designed as:

    1. Input: task description, code repository, test entry.
    2. Step 1: The model outputs its understanding of the task and the modification plan.
    3. Step 2: A human or an automated check confirms whether the plan is reasonable.
    4. Step 3: The model executes the code changes.
    5. Step 4: The system runs the relevant tests.
    6. Step 5: If the tests fail, the failure summary is fed back to the model.
    7. Step 6: The model continues fixing until the tests pass or the maximum number of rounds is reached.
    8. Step 7: Output the change summary, test results, and remaining risks.

    This flow combines “model generation” with “engineering verification,” making it more reliable than simply letting the model improvise freely.

    8. State Management in Multi-Turn Tasks

    Agentic coding is often a multi-turn task. After the developer gives a goal, the model may go through multiple rounds of modification, failure, and re-modification. Without good state management, the model can easily forget the original goal midway, or repeatedly try approaches that have already failed.

    Therefore, it is recommended to maintain a structured state file or state object in long tasks. It does not have to be complex, but it should be able to express the key information of the current task. For example:

    1. {
    2. "goal": "Fix the exception caused when user input is empty",
    3. "constraints": [
    4. "Only modify the validation module",
    5. "Do not change the public interface",
    6. "Do not introduce new dependencies"
    7. ],
    8. "current_plan": "Add null normalization in the entry function",
    9. "changed_files": [
    10. "src/validator/input.ts"
    11. ],
    12. "test_status": "failed",
    13. "failure_reason": "Empty strings are not converted to empty arrays",
    14. "next_action": "Modify the normalization function"
    15. }

    This kind of state-based representation has several benefits:

    1. Key information is less likely to be lost during context compaction;
    2. A new session can be handed off directly;
    3. During manual review, the task progress can be understood quickly;
    4. The model stays more consistent across multiple turns;
    5. Failure retries do not repeat ineffective paths.

    For complex tasks, state management is even more important than simply increasing the context window. A clearly structured, continuously updated state is more valuable than a long but chaotic conversation history.

    9. Stability and Routing Governance: Reducing Uncontrollable Fluctuation

    In agentic coding systems with multiple models, multiple environments, and multiple service configurations, stability problems often come not only from the model itself, but also from request routing, server-side policies, caching mechanisms, and parameter configurations.

    For example, in some invocation scenarios, the system may automatically select different models based on load, policy, or configuration; different models may handle prompts, context, and caching differently, causing the same request to produce different results. Similarly, if the server’s prompt or caching strategy is opaque, developers may find it hard to judge whether a performance drop is due to a change in model capability or to a cache miss, context rewriting, or parameter adjustment.

    Therefore, in an agentic coding system, it is recommended to add a layer of unified invocation governance. This mechanism can take the form of a gateway, a proxy layer, or a local routing layer, and its core goal is not to simply forward requests, but to improve controllability and observability.

    Key recommendations include:

    1. Model version pinning: pin the model version and parameters for critical tasks to avoid uncontrollable switching.
    2. Prompt template management: version-control system prompts, task templates, and tool descriptions.
    3. Request isolation: use different sessions and configurations for different tasks and projects.
    4. Cache policy governance: monitor cache hit rates and analyze the causes of cache misses.
    5. Routing audit: record the model, parameters, latency, and result summary of each request’s path.
    6. Exception alerting: monitor for sudden latency spikes, rising failure rates, and abnormal token growth.
    7. Task-tiered scheduling: use lightweight configurations for simple explanation tasks and high-reasoning configurations for complex refactoring tasks.

    In this way, developers can better distinguish “model capability problems” from “system invocation problems.” When results are unstable, they can also more quickly locate whether the issue is with context, tools, caching, or server-side routing.

    10. A Typical Agentic Coding Workflow

    Combining the ideas above, we can organize a fairly general agentic coding workflow.

    1. Prepare the Repository and Verification Environment

    Before starting a task, ensure that the code repository is structurally complete, dependencies are installable, and tests are runnable. Agentic coding does not generate code out of thin air; it operates on a real repository. If the repository itself cannot build, all subsequent verification is unreliable.

    2. Clarify the Task Description

    The task description should include the following elements:

    • Goal: what to accomplish;
    • Scope: which parts can be modified;
    • Constraints: what must not be done;
    • Acceptance: how to judge whether it is complete.

    For example:

    1. Please fix the null-value exception in the input-validation module.
    2. Only input-validation-related files may be modified.
    3. Do not change the public interface.
    4. After completing the work, run the relevant unit tests.
    5. If the tests fail, output the failure reason and continue fixing.

    3. Plan First, Then Modify

    Require the model to first output its task understanding, impact scope, modification plan, and risk points. This avoids the model making large-scale changes directly and lets developers spot directional deviations early.

    4. Control the Context Size

    Before the model starts modifying, check whether the context contains too much irrelevant content. It is recommended to prioritize retaining the task description, constraints, relevant files, and the most recent error information.

    5. Execute Changes and Verify Automatically

    After the model completes the changes, the system should automatically run the relevant tests or static checks. Verification results should be as structured as possible, for example:

    1. Test command: failed
    2. Failed case: input_validator_empty_string
    3. Error type: TypeError
    4. Key error: expected array, received string
    5. Related file: validator/input.ts

    6. Failure Feedback and Second-Round Fixing

    If the tests fail, feed the failure summary back to the model rather than stuffing the entire log back in verbatim. The feedback should include the error location, expected result, actual result, and possible cause.

    7. Context Compaction and State Handoff

    When the context approaches the threshold, perform compaction. The compacted content should preserve the task goal, completed changes, failure reason, and next-step plan. When necessary, start a new session and complete the handoff through a structured state.

    8. Manual Review and Retrospective

    Regardless of whether the model’s result passes the tests, a final manual review should always be conducted. The focus includes: whether the changes meet expectations, whether extra dependencies were introduced, whether interfaces were broken, whether other modules are affected, and whether the testing is sufficient.

    11. Common Misconceptions and Optimization Suggestions

    Misconception 1: The Longer the Context, the Better the Result

    In fact, overly long context easily introduces noise. Agentic coding calls for a higher signal-to-noise ratio. Prioritize retaining the task goal, current changes, failure reason, and verification results.

    Misconception 2: More Tools Mean Stronger Capability

    More tools mean higher context pressure and decision cost. For most tasks, a small number of stable, controllable-output basic tools is enough.

    Misconception 3: It Is Enough If the Model Can Generate Code

    The key to agentic coding is not generation, but the loop. Results must be confirmed through testing, checking, and manual review.

    Misconception 4: Multi-Turn Conversations Can Continue Indefinitely

    Without state management, multi-turn conversations easily lead to goal drift. It is recommended to use a structured state to record current progress.

    Misconception 5: Ignoring Fluctuations Caused by Routing and Caching

    When results are unstable, do not attribute everything to model capability. Request routing, caching policies, parameter configurations, and server-side prompt handling can all affect the final experience.

    Optimization Suggestions

    1. Establish standard prompt templates for common tasks.
    2. Build a minimum toolset for agentic coding.
    3. Set clear compaction thresholds for context.
    4. Structure failure information rather than passing it back verbatim.
    5. Pin models and parameter configurations for critical tasks.
    6. Establish observable invocation logs and performance metrics.
    7. Incorporate agentic output into a version-review process.

    12. Conclusion

    Agentic coding represents a new way of doing code engineering: the model is no longer just an assistant for completion, but participates in the complete flow of understanding, modification, verification, and iteration. As large models developed in China continue to improve in code comprehension, instruction following, multi-step reasoning, and tool use, the usability of agentic coding keeps strengthening.

    But what truly determines the upper limit of the experience is not only the model itself, but the comprehensive capabilities of context engineering, task decomposition, toolchain design, state management, and routing governance. A stable agentic coding system should achieve clear task boundaries, high context information density, a reliable verification loop, traceable state changes, and an observable invocation process.

    In practice, developers need not blindly pursue larger context, more tools, or longer reasoning chains. A more reasonable approach is to start from the task, control the context sweet spot, streamline the toolset, establish structured state, and continuously improve result stability through automated verification. Only in this way can agentic coding truly move from “looking usable” to “engineering-reliable.”