Engineering AI Agents with Million-Token Context: From Patch Generation to Reliable Delivery
This article explores how to engineer AI coding agents when open-weight models and million-token context windows make more information available than ever. It breaks the problem into three engineering challenges—context governance, execution loops, and delivery trust—and shows how to address each one. You will learn a four-layer context model, retrieval-first budgeting, evidence truncation strategies, a minimal toolset with structured returns, a state-machine workflow with rollback, a three-tier evaluation system, cost and latency controls, security boundaries, a four-stage rollout roadmap, and common anti-patterns to avoid.
1. The Real Problem: A Patch Is the Start, Not the Finish
Hand a coding agent a bug ticket and it can often produce a plausible-looking fix in seconds. But engineering teams rarely lose time writing the patch. The real cost comes afterward: getting tests to pass, tracking down regressions, covering edge cases, resolving dependency conflicts, writing change descriptions, and moving through review and staged rollout. The core tension is simple—generation quality has improved dramatically, while the reliability, verifiability, and operability of finishing the dirty work still lag behind.
Open-weight models combined with million-token context change the boundary of usable information. You can now feed larger code slices, more logs, and longer conversation histories into the model’s view at once. But a longer context does not automatically produce more reliable conclusions. This article frames the challenge as three engineering problems:
- Context governance: what to include, how to order it, and what to drop within a limited attention budget.
- Execution loops: the model must do more than emit text—it must call tools, observe results, and revise its plan.
- Delivery trust: every change needs an evidence chain, must be reversible, and must be measurable.
2. Using Long Context Correctly: Layering, Retrieval, and Budgets
2.1 Layer the Context
Split the input into four layers instead of dumping the whole repository into the window:
- Task layer: the bug ticket, reproduction steps, expected behavior, and acceptance criteria.
- Constraint layer: coding standards, pinned dependency versions, compatibility requirements, and security red lines.
- Evidence layer: structured descriptions of failing test output, stack traces, relevant log fragments, and monitoring metrics.
- Code layer: files strongly related to the bug, interface definitions, data structures, and callers.
2.2 Retrieve First, Then Fill
The value of a long window is that it can hold a lot; the engineering value is holding only what belongs there. The recommended approach is to locate a candidate set with retrieval first, then trim it to budget:
score = w1*symbol_similarity + w2*call_graph_distance + w3*historical_defect_density + w4*change_recencycontext_budget = task_layer(fixed) + evidence_layer(truncate, keep head and tail) + code_layer(greedy fill by score)
Here, “call graph distance” is the number of hops from the target symbol in the dependency graph, and “historical defect density” comes from statistics in the defect tracking system (a general capability, not tied to any specific product).
2.3 Truncation Strategy for the Evidence Layer
Logs and test output are often extremely long. Keep the first section (environment, version, command), the last section (assertion failures and summary), and every fragment containing exception keywords and line numbers. Fold the rest into a summary. This controls noise while preserving the clues needed for localization.
3. From Text Generation to an Execution Loop: Tool-Based Orchestration
3.1 The Minimal Toolset
A deliverable coding agent needs at least six categories of tools, each with structured returns:
- Code retrieval and reading (returns file paths, symbols, fragments)
- Change writing (patch or full file, with atomicity guarantees)
- Test execution (unit, integration, static checks)
- Dependency and build operations (install, compile, package)
- Version control operations (branch, diff, commit draft)
- Evidence collection (command, exit code, duration, key output)
3.2 A State Machine, Not Free-Form Chat
Free-form conversation tends to spiral into “the more you change, the messier it gets.” Constrain the flow with an explicit state machine where every step has entry and exit conditions:
Triage -> Reproduce -> Locate -> Patch -> Verify -> Regression -> Report| | | | | |fail fail not found build fail test fail still regressing└───────────┴────────────┴─────────┴─────────┴────────────┘ -> roll back and narrow scope
Key constraints: change only one semantic unit at a time; rerun the minimal verification set after every change; after two consecutive failures, switch hypotheses instead of continuing to tweak.
3.3 Rollback on Failure and Evidence Retention
Production readiness starts with being able to undo. Run each attempt on a separate branch or working copy, and discard it on failure. On success, keep the diff, test output, and timing data to form an auditable record. Evidence retention is not only for reviewers—it also provides retrieval material for the next similar bug, creating a positive feedback loop.
4. Evaluation: Turning “Looks Right” into “Measurable”
4.1 Three Tiers of Metrics
- Generation tier: whether the patch compiles and passes the target test case.
- Loop tier: average attempts, rollback rate, average time to locate.
- Delivery tier: regression introduction rate, first-pass review rate, change rollback rate.
4.2 Building an Offline Evaluation Set
Sample from historical bug tickets and construct triples of “bug ticket + repository snapshot + acceptance tests.” Pay attention to three points: isolate data leakage (evaluation samples must not appear in prompt examples), cover multiple languages and build systems, and retain a proportion of “insufficient information” samples to test questioning and clarification ability.
4.3 Regression Gatekeeping
Add automated gates to the pipeline (a common practice): static checks, unit tests, key integration cases, and change impact analysis. When a gate fails, feed the structured result back to the agent instead of just a block of free text.
5. Cost and Latency Governance
The cost of long context is explicit: prefill time, memory usage, and call cost all rise with length. Mitigation includes:
- Layered caching: prefix-cache the task and constraint layers; cache the evidence layer per session.
- Progressive expansion: use a small window to locate first, then do long-window close reading on candidate files.
- Batching and concurrency: run independent verification tasks in parallel to shorten end-to-end time.
- Budget guardrails: set caps on context and number of calls per task; on exceeding them, degrade to “provide localization suggestions + hand over to a human.”
6. Security and Compliance Boundaries
- Least privilege: grant the tool side only the permissions needed for the current repository and target environment; write operations must be auditable.
- Sensitive information governance: avoid carrying credentials in prompts and logs; apply redaction and placeholder substitution when necessary.
- Controlled changes: prohibit automatic direct pushes to the main branch; require branches, review, and staged rollout.
- Explainable output: change descriptions must include root cause, impact scope, verification method, and uncovered risks.
7. Rollout Roadmap (Four Suggested Stages)
- Read-only assistant: retrieval + explanation + localization suggestions, zero write permission, validate retrieval quality.
- Controlled writing: single-file patches + mandatory verification, automatic rollback on failure.
- Closed-loop execution: multi-file changes, test-fix iteration, automatic change description generation.
- Platformization: integrate with pipelines, defect tracking, and monitoring alerts to form a measurement loop and accumulate knowledge.
8. Common Anti-Patterns
- Feeding the entire repository at once, drowning key clues in noise.
- Letting the model only “change code” without letting it “see results,” missing the observe-and-correct loop.
- Continuing to tweak the same hypothesis after failure, wasting budget and masking the real root cause.
- Substituting demo results for metrics, lacking regression and rollback data.
- Excessive, unauditable permissions that make it impossible to scope impact during an incident.
9. Conclusion
Open-weight models and ultra-long context have pushed information availability to new heights, but whether an agent can finish the dirty work for you depends on whether the engineering constraints are in place: is the context layered, is execution closed-loop, are failures reversible, and is delivery measurable? Once this framework is in place, coding tools move from “can write patches” to “can deliver changes.” If you need a foundation to carry evaluation, logs, and pipelines, general capabilities such as container platforms, object storage, log services, and monitoring alerts on Baidu AI Cloud are sufficient, with no dependency on any proprietary interface.
