Agent Engineering in Practice: Delivering Reliable Coding Agents with Million-Token Contexts
This article explores how to turn long-context, open-weight models into dependable coding agents that can handle complex software engineering tasks in controlled environments. It clarifies what million-token context windows can and cannot solve, then walks through a practical engineering framework: layered context assembly, task decomposition into verifiable steps, automated verification gates, least-privilege sandboxing, and observability with cost metrics. It also lists common anti-patterns and a phased adoption roadmap, showing that context layering, task breakdown, verification loops, permission isolation, and measurement—not raw context size alone—determine whether AI coding tools can reliably take on repetitive yet rigorous engineering work.
1. The Real Problem: A Patch Is Just the Starting Point, Delivery Is the Goal
Hand a coding agent a bug ticket and it can often produce a plausible-looking patch in seconds. The hard part comes afterward: Are the tests sufficient? Are edge cases covered? Are dependencies broken? Can the change be rolled back? The industry is gradually recognizing that code generation is only one link in the R&D automation chain. The capability gains from long context and open weights must be combined with engineering constraints to turn “looks correct” into “verifiably correct.”
To be clear, open weights mean a model can be downloaded, deployed privately, and fine-tuned. Long context means a single request can hold more code and logs. These two properties address “information visibility” and “controllability”; they do not automatically deliver “correctness.” So this article does not discuss any specific product capabilities. Instead, it abstracts the problem into a general engineering question: how to make a model with long-context capability reliably complete complex R&D tasks in a controlled environment.
2. Capability Boundaries: What Long Context Can and Cannot Solve
The core value of long context is reducing misjudgments caused by information truncation. The traditional approach requires retrieval and summarization first, and summarization loses call relationships, configuration defaults, and historical decisions. An ultra-long window can bring relevant files, interface definitions, and log fragments into view at once, making the reasoning chain more complete.
But it cannot replace three things. First, it cannot replace real execution results—a model cannot determine concurrency timing issues just by reading. Second, it cannot replace business semantics—implicit constraints in requirement documents still need human clarification. Third, it cannot replace permission and compliance boundaries—automation does not mean opening up production access. Writing these three points into process design is the prerequisite for avoiding “automation that manufactures more incidents.”
3. Context Engineering: Layered Assembly, Not Stuffing Everything In
The recommended practice is to assemble context in layers rather than piling everything into the window. It can be divided into four layers:
- Task layer: the bug ticket, reproduction steps, expected behavior, and acceptance criteria;
- Structure layer: directory conventions, module boundaries, interface contracts, and dependency lists;
- Evidence layer: failing test cases, stack traces, key logs, and text descriptions corresponding to monitoring metric screenshots;
- History layer: records of similar past fixes and summaries of design decisions.
A schematic context assembly logic is shown below (pseudocode, expressing only the layering idea):
context = task_spec + repo_contract + failing_evidence + related_historybudget = allocate(0.2, 0.3, 0.4, 0.1) # per-layer quotas, adjusted by task typeprompt = render(context, budget, dedup=True, cite=True)
The point of quotas is to prevent the evidence layer from being squeezed out by the structure layer. Requiring the model to cite source fragments for key conclusions can significantly reduce the probability of “fabricated interfaces.”
4. Task Decomposition: Breaking Large Changes into Verifiable Small Steps
Complex defects often span modules, and generating one large patch at once has a high failure rate. A more reliable approach is to decompose the work:
- Locate: output a ranked list of suspects and verification methods, without changing code;
- Reproduce: add a minimal failing test case to ensure the problem can be triggered reliably;
- Fix: change only the minimum necessary scope and keep interfaces compatible;
- Regress: run the test suite for the affected scope;
- Review: record the root cause, impact scope, and changes in monitoring metrics.
Set entry and exit conditions for each step—for example, “reproduction steps must include a repeatable command sequence” and “the fix must not change public interface signatures.” This way, even if a step makes a wrong judgment, it can be intercepted within a small scope.
5. Verification Loop: Automation Must Bring Its Own Judge
Automation without verification just speeds up mistakes. A three-layer judging mechanism is recommended:
- Static layer: format, type, dependency, and license checks;
- Dynamic layer: unit and integration tests covering new branches;
- Observation layer: in a staging environment, use traffic replay or shadow calls to observe latency, error rate, and resource usage.
In environments such as Baidu AI Cloud, general capabilities like code hosting, pipelines, container platforms, log services, and monitoring alerts can be chained together: the pipeline handles execution and gating, object storage keeps build artifacts and evidence packages, and logs and monitoring provide before-and-after comparison data. All gate results are returned as structured reports, serving as the sole basis for whether a merge is allowed.
6. Security and Permissions: Least Privilege and Sandboxed Execution
To let automation tools “do the dirty and heavy work,” you must assume by default that they will make a wrong judgment at some point. So the execution environment should follow least privilege: mount the main repository read-only, perform writes on a temporary branch; prohibit direct access to production credentials; apply a whitelist for network egress; and require human confirmation for high-risk operations (deleting data, changing permissions, bulk-rewriting history).
Sandboxing also brings reproducibility: pinning the base image and dependency versions makes the same input produce comparable results. For auditing, retain complete prompt context summaries, tool call records, and artifact hashes to enable post-hoc tracing and accountability.
7. Observability and Cost: Turning “Intelligence” into Measurable Metrics
Measure at least four categories of metrics: first-pass rate, human rework time, rollback rate, and resource consumption per task. Long context significantly increases compute overhead, so caching and trimming strategies are needed: cache the stable, unchanged structure layer, deduplicate repeated logs, and summarize and compress irrelevant history.
If you adopt an open-weight model with private deployment, you also need to watch throughput and concurrency queuing, balancing interactive and batch tasks through batching and priority queues. The metrics dashboard should present quality and cost together, avoiding unlimited context expansion just to boost pass rates.
8. Common Anti-Patterns
- Giving conclusions without evidence, making review impossible;
- Having the model handle locating, fixing, and releasing at once, with no gates;
- Letting context grow without limit, diluting key evidence;
- Substituting “tests pass” for “acceptance met,” ignoring business semantics;
- Granting production write access directly, with no rollback plan.
9. Adoption Roadmap
Phase one: build a read-only assistant that produces locating results and patch suggestions. Phase two: connect to pipelines and test gates to enable controlled automatic commits. Phase three: introduce an observation data loop, using real metrics to drive prompt and process optimization. Every phase retains a human fallback and one-click rollback capability.
In summary, million-token context and open weights improve information completeness and controllable deployment. What truly determines results is context layering, task decomposition, verification loops, permission sandboxing, and a measurement system. Get these five things solid, and coding agents can reliably take on the repetitive, tedious, yet rigorous engineering work.
