A Practical Guide to Coding Agents with Million-Token Contexts
This article explains why long context alone does not make coding agents reliable, and how to turn a million-token window into dependable delivery. It covers a four-layer context structure, a six-step loop from patch to verification, controlled tool permissions, a three-tier evaluation system, common failure modes, and deployment guidance using general cloud components. The core takeaway is that reproduction, verification, regression checks, and evaluation—not generation—determine whether an agent can handle real engineering work.
1. The Real Problem: A Patch Is Only the Starting Point
Give a coding agent a bug ticket and it can usually produce a plausible-looking change within seconds. The hard part of engineering is never writing a piece of code. It is the chain of tedious work that follows: understanding the repository structure, locating the call chain that actually matters, reproducing the issue, filling in tests, handling dependency and environment differences, rolling back and retrying after failures, and finally proving that the change introduced no regressions.
The core tension can be stated in one sentence: generation is no longer the bottleneck; closed-loop verification is. The combination of open-weight models and million-token context makes it technically feasible to put the entire repository, logs, and tests into the model’s view. But a longer context does not automatically produce more accurate conclusions. This article takes a neutral perspective on how to convert long context into reliable delivery using general engineering methods.
2. Why Long Context Is Necessary but Not Sufficient
Long context brings three direct benefits:
- Cross-file reasoning: changing one function often affects interface definitions, configuration, tests, and documentation.
- Evidence cohesion: stack traces, reproduction steps, and relevant code can appear in the same view, reducing trial-and-error back-and-forth.
- Less information loss: no repeated summarization is needed, which lowers the risk of misdiagnosis caused by summarization bias.
The risks are equally clear:
- Attention dilution: key fragments get buried under large amounts of irrelevant content, and the model may latch onto superficially similar code.
- Higher cost and latency: the longer the context, the higher the per-request overhead, and serial trial and error becomes expensive.
- Confident hallucination: with more material available, the model is more likely to produce pseudo-evidence that appears to cite a specific piece of code.
In engineering terms, treat long context as a searchable evidence pool, not a dumping ground for one-shot content.
3. Layering the Context: Using a Million-Token Window Correctly
Divide the context into four layers and explicitly mark the source and trustworthiness of each in the prompt:
- L1 Task layer: the bug ticket, reproduction steps, expected behavior, acceptance criteria.
- L2 Evidence layer: stack traces, log excerpts, failing test output.
- L3 Code layer: relevant files, interface definitions, data structures, configuration.
- L4 Constraint layer: coding standards, dependency version limits, security and compliance requirements.
Illustrative context organization (pseudocode):
[Task] Fix: duplicate writes during bulk import under high concurrency[Acceptance] New concurrency test passes; all existing tests green; no new dependencies[Evidence] Failing test output (excerpt)...[Code] src/importer.py, src/store.py, tests/test_import.py[Constraints] Do not change public interface signatures; report logs through the unified logging service
Key practice: retrieve first, then load into the window. Use keywords, call graphs, and change history for coarse filtering, and place only fragments strongly related to the failure into L3 instead of injecting everything indiscriminately.
4. From Patch to Verification: Building an Executable Loop
A reliable automated development workflow contains at least six stages, none of which can be skipped:
- Reproduce: trigger the problem reliably in an isolated environment, with the failing test first.
- Locate: produce a verifiable evidence chain, requiring the model to cite file paths and line ranges.
- Modify: commit in small steps, addressing one root cause at a time.
- Verify: run unit tests, integration tests, and static checks in parallel.
- Regress: compare against baseline metrics to confirm no performance or security degradation.
- Archive: capture the failure cause and fix pattern as reusable knowledge.
Illustrative workflow orchestration:
def auto_fix(issue, repo, runner):ctx = build_context(issue, repo) # assemble layered contextrepro = runner.reproduce(ctx) # reproduction must come firstif not repro.failed:return {"status": "cannot_reproduce", "detail": repro.log}patch = model.propose(ctx, repro.log) # generate a minimal patchresult = runner.verify(patch) # tests + static checksif result.passed:return {"status": "fixed", "patch": patch}return {"status": "retry", "reason": result.summary, "attempt": 1}
The engineering point is that information from a failed verification must flow back as new evidence, rather than simply resending the same prompt.
5. Tooling and Permission Boundaries
The model itself cannot replace an execution environment. Capabilities need to be externalized as controlled tools:
- Code search and call graph queries (read-only)
- Test execution and coverage collection (inside a sandbox)
- Log and monitoring queries (read-only, desensitized)
- Change submission (requires human approval or branch isolation)
For permission design, follow the principle of least privilege: read-only by default, write operations performed in a separate branch or ephemeral container, artifacts passed through object storage and an artifact repository, and the whole process traced by logging and monitoring alerts for auditability and traceability.
6. Evaluation: Using Data to Decide Whether It Can Actually Do the Work
Automation without evaluation is just wishful thinking. Build three tiers of metrics:
- Outcome tier: fix success rate, regression introduction rate, mean time to fix.
- Process tier: reproduction success rate, number of wasted attempts, context hit rate.
- Cost tier: average cost per task, human intervention rate.
The evaluation set should come from real bug tickets and retain categories such as “cannot be fixed” and “insufficient information” to test whether the system stops honestly instead of fabricating a patch.
7. Common Failure Modes and How to Avoid Them
- Fixing only the surface: adjusting assertions or comments while avoiding the root cause; constrain this with behavioral tests.
- Over-modification: changing too many files at once; limit patch size and require an explanation of the impact scope.
- Environment drift: mismatched dependency versions cause “it passes locally”; pin the environment image.
- Fabricated evidence: require every conclusion to carry a locatable citation, and treat anything unlocatable as invalid.
- Endless retries: set a maximum number of rounds and a threshold for escalating to a human.
8. Deployment Recommendations
To build this kind of capability in an environment such as Baidu AI Cloud, you can compose general cloud components: a container platform hosts the isolated execution environment, object storage holds context snapshots and patch artifacts, a message queue decouples long-running tasks, logging and monitoring alerts provide observability, and the identity and permission system controls the boundary of write operations. On the model side, prefer open-weight options for private deployment and data control, and use a unified gateway for canary releases and rate limiting.
The overall conclusion is that million-token context and open weights only amplify what is possible. What really determines whether an agent can finish the tedious work for you is whether the engineering loop of reproduction, verification, regression, and evaluation is solid. Get the loop right, and automated development can move from demo to daily production.
