AI Agents with Million-Token Context: From Writing Patches to Handling the Dirty Work
This article examines how to build an end-to-end AI agent that can take on the "dirty work" of software engineering once open-weight models with million-token context windows are available. It explains what long context does and does not solve, outlines a six-layer reference architecture, and details context budgeting, the failure-and-fix execution loop, evaluation gates, security boundaries, and common failure modes. The goal is a system that is controllable, auditable, and reproducible in real repositories.
1. The Problem: Why “a Patch in Minutes” Is Not a Finished Job
Hand an AI coding tool a bug ticket and it can often produce a plausible-looking change in seconds. But the hard part of engineering delivery has never been writing a snippet of code. It is turning that code into a result the team can accept: reproducing the issue, finding the root cause, assessing the blast radius, adding tests, getting the pipeline green, handling regressions, and writing the change description. The original point about the real grind coming after the patch captures the core tension: once tests fail, whether the agent can keep correcting itself determines if it is a “code completion tool” or a “task executor.”
So the topic here is not a specific model or product, but a general engineering question: now that open-weight models with million-token context windows are available, how do you build an agent system that can take on the dirty work, complete end-to-end tasks in real repositories, and stay controllable, auditable, and reproducible?
2. What Long Context Solves, and What It Doesn’t
The immediate benefit of long context is a larger field of view. You can put more source code, logs, configs, commit history, and interface docs in front of the model at once, reducing the semantic breaks caused by repeated retrieval. But it does not automatically deliver three capabilities:
- Relevance judgment: a longer context does not make the important parts stand out; noise dilutes attention.
- An execution loop: being able to “see” is not the same as being able to “do”; tool calls and interaction with external systems are still required.
- Cost control: attention and memory overhead grow with length, and blindly filling the context leads to runaway latency and cost.
The safer engineering approach is to treat long context as a “workspace,” not a “dumping ground”: organize material structurally, use retrieval and filtering to control what enters the workspace, compress history with layered summaries, and constrain output with clear goals and acceptance criteria.
3. A Reference Architecture for End-to-End Agents
A practical end-to-end agent typically has six layers:
- Task intake layer: receives bug tickets, feature requests, or alerts and extracts the title, reproduction steps, expected behavior, impact scope, and priority.
- Context construction layer: pulls data from the repository, log service, monitoring alerts, docs, and ticketing system to build a “task pack.”
- Planning and execution layer: breaks the task into verifiable sub-goals and calls tools to act (search, edit, run tests, submit changes).
- Verification and gating layer: uses tests, static checks, builds, and policy checks as hard gates; on failure, feeds error information back to trigger correction.
- Delivery layer: generates the change description, risks, rollback plan, and audit record.
- Observability and evaluation layer: records every tool call and result into a replayable trace for offline evaluation and continuous improvement.
A sketch of the task pack structure (pseudocode):
TaskPack {goal: stringacceptance: string[] // machine-checkable acceptance conditionsrepo_snapshot: ref // code snapshot identifierevidence: {logs, metrics} // redacted log and metric snippetsconstraints: {timeout, budget, forbidden_paths}}
4. Context Budgeting: Getting Efficiency Out of a Million Tokens
A “budget-based” approach to context management is recommended:
- Layered summaries: repository structure summary, module responsibility summary, and relevant call-chain summary, each with a fixed share.
- Evidence first: prioritize failed logs, stack traces, recent changes, and affected interface definitions.
- Dynamic retrieval: search candidate files by keyword, symbol, and call relationships, injecting only highly relevant snippets.
- History compression: compress multiple rounds of tool output into “conclusion + evidence pointers” to avoid repeated stacking.
- Hard limits: set caps and eviction policies per content type to keep latency stable.
A simplified budget allocation example:
Total budget 100%Goal and acceptance 5%Failure evidence 25%Relevant code snippets 40%Compressed history summary 20%Constraints and policy 10%
The payoff: the model stays more focused under limited attention, and its behavior is more predictable, making it easier to tell whether a failure came from insufficient context or faulty reasoning.
5. From Patch to Delivery: A Built-In Execution Loop
Replacing the dirty work for real means making “fail then fix” a loop rather than a one-shot generation. Recommended flow:
- Reproduce: run a minimal reproduction script or case in an isolated environment.
- Locate: combine logs and call chains to form a root-cause hypothesis and list verifiable criteria.
- Modify: keep changes minimal; forbid unrelated formatting and large-scale refactoring.
- Verify: run the relevant tests first, then regression and build.
- Correct: if it fails, feed the failure output back in a structured form, cap the maximum iterations, and avoid infinite loops.
- Deliver: output the change description, impact scope, risks, and rollback steps.
Sketch of the pseudocode:
for i in range(max_iters):patch = agent.propose(task_pack)result = ci.run(patch, scope="targeted")if result.passed:return deliver(patch, result.evidence)task_pack.add_evidence(result.failure)
The key engineering point is “structured evidence”: break a failure into error type, failing case, key stack trace, related files, and recent changes so the model can make an effective fix instead of blindly rewriting.
6. Evaluation and Gating: Proving the Work Is Actually Done
An agent without an evaluation system is not trustworthy. At least four kinds of gates are recommended:
- Functional gate: target cases pass with no new failures.
- Quality gate: static checks, complexity, and duplication do not degrade.
- Security gate: dependency and secret policies, sensitive-information scanning, and permission-boundary checks.
- Delivery gate: a complete change description, an executable rollback plan, and a full audit log.
The evaluation set should come from real historical tickets: input is a redacted bug ticket, and the expected output is a “mergeable change that passes tests.” Metrics should look beyond success rate to average iteration count, manual rework rate, wrong-change rate, and average time.
7. Security, Permissions, and Compliance Boundaries
End-to-end execution means higher privileges, so the principle of least privilege must apply: restrict writable paths, forbid touching production configs, whitelist external network access, and redact logs and data. All tool calls should be auditable, and key actions (commit, merge, release) should keep a human confirmation point. For on-premises deployment of open-weight models, container platforms and object storage can provide environment isolation and artifact archiving, while log services and monitoring alerts form a traceable chain.
8. Common Failure Modes and Countermeasures
- Context noise causing misjudgment: reduce noise with evidence-first and dynamic retrieval.
- Over-modification: limit the change scope and enforce minimal patches.
- Regression after tests pass: add regression gates and impact analysis.
- Iterations that don’t converge: set a maximum iteration count and an escalation-to-human policy.
- Delivery that isn’t auditable: require a change description and a call trace.
9. Conclusion
Million-token context and open weights move “an agent doing the work for you” from concept to engineering feasibility, but the real dividing line is whether the system has a closed execution loop, budgeted context, hard-gated evaluation, and auditable delivery. Build that system, and the dirty work goes from “looks like it can write code” to “reliably deliverable.”
