A Practical Guide to Building Coding Agents with Million-Token Context
This article explains why the bottleneck in AI coding agents is not code generation but closing the loop, and how million-token context changes the picture. It covers the capability gains and costs of long context, a four-layer context governance model (task, structure, evidence, deep read) with budget trimming rules, a six-stage execution loop that treats verification as mandatory, a three-tier evaluation approach with observability metrics, and an engineering deployment checklist. The goal is to turn a fragment-level assistant into an engineering participant through global visibility, verification discipline, and clear acceptance criteria.
1. Reframing the Problem: The Bottleneck Is Finishing the Job, Not Writing Code
Hand an AI coding tool a bug ticket and it will usually produce a plausible-looking patch within seconds. The real difficulty starts after the patch: do the tests pass, does the change introduce regressions, do the logs converge, and can the release be rolled back? The original observation matters because it points to a gap that is common across the industry: generation capability is already strong, while closed-loop execution capability remains weak.
Breaking the “dirty work” into pieces gives roughly four categories:
- Localization: finding the actually relevant call chains and configuration sources in a large codebase.
- Verification: running tests, reading failure stack traces, and separating environment noise from real defects.
- Repair: making consistent changes across multiple files without breaking interfaces or data contracts.
- Wrap-up: adding explanations, cleaning up temporary artifacts, and providing a rollback plan.
The direct value of million-token context is that it upgrades the first and third categories from “fragment reasoning” to “global reasoning.” It does not automatically solve the second and fourth, because those depend on the execution environment and feedback loops rather than on window size.
2. What Long Context Actually Changes
Long context brings three verifiable capability gains and three costs that must be faced.
Capability gains:
- Long-range dependencies become visible. Type definitions across modules, configuration defaults, and environment variable conventions can enter view at the same time, reducing patches that are locally correct but globally wrong.
- Cross-file refactoring becomes feasible. Renames, signature changes, and error code unification require seeing callers and implementations simultaneously.
- Fewer context switches. There is no need to repeatedly search and summarize, so the decision chain within a long session is preserved.
Cost constraints:
- Attention dilution. When relevant content is surrounded by large amounts of irrelevant content, key evidence may be ignored.
- Higher latency and resource overhead; the prefill stage for long inputs is noticeably slower.
- Cost and context consumption grow roughly linearly, so uncontrolled feeding is not economical.
The right posture, therefore, is not “stuff the whole repository in,” but layered feeding: give the model a global view when it needs one, and show it only the necessary evidence most of the time.
3. Layered Context Governance: Spend the Window Where It Counts
A four-layer structure that converges layer by layer is recommended:
- L0 task layer: the bug ticket, reproduction steps, expected behavior, and acceptance criteria. Keep it to roughly a thousand words, and make “what counts as done” explicit.
- L1 structure layer: directory tree, module responsibilities, dependency direction, build and test entry points. Kept resident as a summary.
- L2 evidence layer: call chains related to the defect, failure stack traces, and key configuration. Retrieved and loaded on demand.
- L3 deep-read layer: full text of a few core files, enabled only for refactoring and signature changes.
Illustrative context assembly logic (pseudocode, expressing only the layering idea):
def build_context(task, repo_index):ctx = [task.spec, repo_index.structure_summary] # L0 + L1ctx += repo_index.search(task.keywords, top_k=8) # L2 evidenceif task.needs_refactor:ctx += repo_index.read_full(task.core_files) # L3 deep readreturn trim_to_budget(ctx, keep=[task.spec]) # budget trimming; spec is never dropped
One hard rule applies when trimming: acceptance criteria and interface contracts that must not be broken have the highest priority, and no compression may remove them.
4. From Patch to Closed Loop: Designing the Execution Loop
The minimum viable closed loop has six stages: understand, plan, change, verify, diagnose, converge. The key is to make “verify” a first-class citizen that cannot be skipped.
bug ticket -> localization hypothesis -> minimal change -> run tests/static checks^ || vconvergence notes <- fix or rollback <- failure clustering and attribution
Engineering essentials:
- Environment isolation. Each verification runs in a separate container or working copy to avoid polluting the main branch and shared dependencies.
- Failure clustering. Group large numbers of failures by error signature instead of blindly patching one by one and playing whack-a-mole.
- Dual-track judgment. Distinguish “the test itself is outdated” from “the implementation is genuinely defective”; the former needs explicit annotation rather than silently changing assertions.
- Convergence conditions. Tests pass, static checks report no new warnings, and the change scope is explainable; all three must hold before finishing.
- Rollback plan. Any automated change should be restorable with one action, with the change list and verification records retained.
5. Evaluation and Acceptance: Do Not Use “Looks Right” as the Standard
A three-tier evaluation is recommended:
- Unit level: given a defect description, check localization hit rate and minimal-change rate.
- Task level: use “passes existing tests without breaking other cases” as the only hard metric.
- Long-range level: multi-turn, cross-day tasks that examine context retention and mid-course rework rate.
Observability metrics worth collecting: first-round localization accuracy, average verification rounds, number of unrelated files changed, share of time spent on verification, and human takeover rate. These metrics reflect real productivity better than “generation speed.”
6. Engineering Deployment Checklist
- Build a searchable structural index for the codebase and refresh it regularly with commits.
- Unify build, test, and static checks into scriptable entry points for automated invocation.
- Connect logs and monitoring data to a unified query channel so evidence can be gathered quickly during failure attribution.
- Least privilege: read-only retrieval by default; write operations require explicit authorization and scope limits.
- Redact sensitive information before it enters the context, and never put credentials into the conversation.
- If cloud-based general capabilities are used, object storage can hold build artifacts, a message queue can decouple long-running tasks, a container platform can host isolated verification environments, and logging and monitoring services can support observability; integrate all of these as general categories to avoid coupling to a specific implementation.
7. Conclusion
Million-token context is essentially infrastructure for “global visibility”: it pushes the agent from a fragment-level assistant toward an engineering participant. But what really determines success is the verification loop, context budget discipline, and acceptance criteria. Make those three solid and the dirty work can genuinely be taken over; otherwise, no matter how long the window is, it only makes the demo look prettier.
