Agent Engineering at Scale: Practical Lessons from Million-Token Contexts
This article examines why the real bottleneck in coding agents is not code generation but verification and convergence. It breaks down the benefits and costs of long contexts, proposes a four-layer context budgeting strategy, and explains how to combine short-term, working, and long-term memory with hybrid retrieval to prevent context drift. It also covers controlled tool orchestration, structured feedback, layered validation loops, observability and governance for open-weight models, common anti-patterns, and a four-stage adoption roadmap for teams that want reliable, auditable automation.
1. Reframing the Problem: The Bottleneck Is Not Writing Code
Give a coding agent a bug ticket and it will often produce a plausible-looking patch within seconds. The real difficulty starts after the patch: Do the tests pass? Are boundary conditions covered? Do dependencies conflict? Does the change affect other modules? Can failure logs be attributed correctly? Generation is only the first link in the chain; verification and convergence are where the cost concentrates.
Recent industry discussion around “million-token context” and “open weights” essentially amplifies two variables at once: how much information can be loaded in a single pass, and how much freedom you have to deploy locally and fine-tune. But amplifying variables does not make the problem disappear. The longer the context, the higher the noise ratio; the more open the weights, the higher the cost of governing versions and behavior. The engineering focus should therefore shift from “how much the model can read” to “how to organize information, constrain behavior, and verify results.”
2. The Benefits and Costs of Long Contexts
The direct benefits of long contexts are cross-file understanding, cross-version comparison, long-log attribution, and the ability to bring requirement documents, interface contracts, and historical defects into the same reasoning scope. The costs are equally clear:
- Attention dilution: key information gets buried under large amounts of irrelevant content, causing conclusions to drift.
- Higher cost and latency: growing input size linearly increases resource consumption and response time.
- More complex caching and consistency: context keeps changing across multi-turn tasks, making it easy to end up “looking at an old version of the code.”
- Lower reproducibility: the same prompt produces different patches under different retrieval results, making regression difficult.
The conclusion: treat long context as a scarce resource that needs budget management, not something to fill without limit.
3. Context Layering: Spend a Limited Budget Where It Matters
Divide context into four layers, each with a clear budget and priority:
- Task layer: the bug ticket, acceptance criteria, and constraints (must / must not).
- Code layer: target files, direct dependencies, callers, and related tests.
- Evidence layer: failure logs, stack traces, reproduction steps, and recent change records.
- Spec layer: coding conventions, directory structure notes, and dependency version constraints.
Illustrative budget allocation (pseudocode):
context_budget = 100%task <= 10% # acceptance criteria must not be trimmedcode <= 45% # prioritize the direct call chainevidence<= 30% # truncate logs, keep head, tail, and key framesspec <= 15% # keep only entries relevant to this task
For trimming: keep exception frames plus the head and tail of logs, prioritize the call chain over a full-repo scan for code, and inject only spec entries relevant to the current language and framework. This significantly reduces noise and improves patch hit rate.
4. Memory and Retrieval: Staying Consistent Across Turns
The most common failure in multi-turn repair is context drift. Three types of memory can work together:
- Short-term memory: intermediate conclusions for the current task, approaches already tried, and reasons they failed.
- Working memory: a structured fact table, such as the list of affected functions, config items, and data table fields.
- Long-term memory: summaries of historical defect patterns and repair paradigms, tagged with version and timestamp.
On the retrieval side, a hybrid strategy works best: keyword retrieval guarantees exact hits, vector retrieval fills in semantic similarity, and a final reranking step narrows results to a few highly relevant fragments. Every fragment that enters the context should carry a source identifier (file path, version number, time) for auditing and rollback.
5. Tool Orchestration: Making the Agent Act, Not Just Talk
The value of open weights and local deployment is that tool calls can be brought into a controlled loop. A robust orchestration should include:
- Read: controlled file-reading and retrieval interfaces, with no unauthorized access.
- Change: submit modifications as patches, with mandatory diff review.
- Execute: run builds and tests in an isolated container, with network and resource limits.
- Feedback: feed structured results (pass/fail, failing cases, duration) back into the context.
- Converge: set a maximum iteration count and stop conditions to avoid infinite loops.
Pseudocode example:
for i in range(MAX_ITER):ctx = build_context(task, budget)patch = agent.propose(ctx)if not review(patch):return reject("patch violates constraints")result = sandbox.run(build_and_test, patch)if result.passed:return patchctx.update(result.failure_summary)return give_up()
The key is structured feedback. Describing failures in natural language invites misunderstanding; standardized fields (case identifier, assertion diff, error category) markedly improve the accuracy of the next repair round.
6. The Verification Loop: Turning “Looks Right” into “Provably Right”
Verification should proceed in layers, from low to high cost:
- Static checks: syntax, types, style, and dependency consistency.
- Unit tests: covering changed functions and boundary conditions.
- Integration tests: verifying cross-module calls and configuration wiring.
- Regression and performance baselines: confirming no degradation.
The practical recommendation is “fail fast, minimize reproduction.” When a test fails, automatically compress the scenario to the smallest reproduction first, then let the agent handle it, avoiding wasted context on long logs. Also retain the patch and result of every attempt to form a comparable trial record.
7. Observability and Governance
Open weights mean behavior can be customized, which also means stronger governance is required:
- Version pinning: record the model version, prompt template version, and retrieval index version.
- Full-chain tracing: link task input, retrieved fragments, tool calls, and test output.
- Least privilege: separate read and write; default to read-only in production.
- Audit and replay: any deliverable can replay the process that generated it.
- Cost control: set context and iteration budgets per task; downgrade or escalate to a human when exceeded.
If you use cloud resources, general-purpose service categories can carry the load: object storage for trial records, a message queue to decouple long tasks, a container platform to run isolated sandboxes, and logging plus monitoring with alerts to track failure rates and latency.
8. Common Anti-Patterns
- Stuffing the entire repository into the context, drowning key constraints.
- Letting the model only “explain” without running tests, delivering something unverifiable.
- No stop condition, iterating dozens of rounds without converging.
- Feedback as long natural-language text, raising the odds of misjudgment in the next round.
- Ignoring version information, generating patches against stale code.
9. A Phased Adoption Roadmap
Phase one: deliver “verifiable single-point fixes” scoped to a limited directory and limited tests, with mandatory diff review. Phase two: introduce layered context and structured feedback to raise the first-pass success rate. Phase three: add long-term memory and cross-version regression to handle more complex defect families. Phase four: complete governance and cost budgeting so the automation is reproducible and auditable across the team.
Overall judgment: million-token contexts and open weights are capability amplifiers, but an amplifier does not automatically deliver reliability. Treating context as a budget, tools as controlled executors, and verification as the delivery gate is the practical path to letting automation take on repetitive work.
