Million-Token AI Agents for End-to-End Engineering Tasks
Long context can help AI agents handle complete engineering tasks, but generating a patch is only one step. This article explains how context budgeting, rollback-ready tools, environment-based verification, and observability support a workflow from diagnosis through delivery, with human review gates and practical acceptance metrics.
1. The Real Challenge Is Finishing the Work, Not Writing the Patch
Give an AI coding tool a bug report, and it can often produce a plausible patch within minutes. The real cost comes afterward: reproducing the issue requires reviewing logs and call chains; diagnosis requires comparing callers across more than a dozen files; the fix must preserve existing contracts; verification requires builds, unit tests, and integration tests; and delivery requires change notes and a rollback plan.
This less glamorous work has three defining characteristics: broad context requirements, expensive verification, and a high cost of failure.
A conventional approach splits the task into small chunks and feeds each one to the model. Each chunk may contain enough information on its own, but nobody is responsible for consistency across them. The result is familiar: patches that are locally correct but globally wrong, repeated requests for more information, and the same issue being fixed and then regressing multiple times.
2. What Long Context Changes—and What It Does Not
The main value of long context is not simply fitting more text into a prompt. It is allowing a single reasoning pass to consider the problem statement, relevant code, historical decisions, and verification results together. This makes it possible to assess cross-file consistency within the same reasoning process.
Million-token windows are commonly discussed as a long-context scale, but engineering teams must distinguish between two concepts:
- Context window capacity: The maximum number of tokens a model can receive.
- Effective context: The information that actually influences output quality, typically much smaller than the full window.
Long context therefore improves information accessibility. It does not automatically solve attention allocation or factual correctness. Loading an entire 800,000-token repository may be less effective than assembling 80,000 tokens selected for relevance to the task.
The practical conclusion is that long context is an enabling condition, not a substitute for retrieval and filtering.
3. The Four Stages of an End-to-End Workflow
A workflow that produces a deliverable result needs at least four stages, each with a distinct failure mode:
- Diagnosis: Start from the observed failure and trace logs, monitoring alerts, and call chains back to suspicious code. The failure mode is reaching a conclusion before collecting sufficient evidence.
- Repair: Make the smallest necessary change while preserving interface contracts and data structures. The failure mode is opportunistic refactoring that introduces unrelated diffs.
- Verification: Run builds, static checks, unit tests, integration tests, and, when necessary, a canary rollout. The failure mode is running only tests directly associated with the change.
- Delivery: Produce change notes, an impact assessment, and a rollback path. The failure mode is submitting changes automatically without a rollback plan.
4. Implementation Architecture: Four Layers
4.1 Context Assembly
This layer decides what the agent should see within a limited budget. Manage that budget explicitly rather than relying on the model to do so:
class ContextBudget:def __init__(self, total=100_000):self.total = totalself.items = [] # (priority, tokens, content)def add(self, priority, content, tokens):self.items.append((priority, tokens, content))def render(self):self.items.sort(key=lambda x: -x[0])used, out = 0, []for priority, tokens, content in self.items:if used + tokens > self.total:continueused += tokensout.append(content)return "\n\n".join(out), used
A recommended priority order is:
- Task description and acceptance criteria.
- Full contents of files directly affected by the change.
- Signatures of callers and callees.
- Relevant tests.
- Historical decision records.
- Repository-wide search summaries.
4.2 Tool Execution
All operations with side effects must be idempotent and reversible. Take snapshots before writing files, execute commands in a container sandbox, and grant network access and credentials according to least-privilege principles.
Tools should return a consistent structure so the model can evaluate results rather than guess:
{"ok": false, "stage": "unit_test", "exit_code": 1,"failed": ["tests/test_billing.py::test_refund"],"log_ref": "object-storage://run-8821/unit.log"}
Store full logs in object storage and include only references and summaries in the context. This is a key way to control token growth.
4.3 Verification Loop
Replace model self-assessment with results determined by the execution environment. A minimal loop can look like this:
def autoheal(task, tools, max_rounds=5):ctx, _ = ContextBudget().render()for i in range(max_rounds):patch = tools.plan(task, ctx)tools.apply(patch) # Idempotent writes + snapshotsr = tools.verify() # Build/static checks/testsif r.ok:return tools.report(task, patch, r)ctx = tools.summarize_failure(r) # Feed failure evidence into contextreturn tools.escalate(task, reason="rounds_exhausted")
Three design points matter:
- Cap the number of rounds to prevent unbounded spending.
- Feed structured failure evidence back into context rather than entire logs.
- Escalate to a human when the limit is reached instead of continuing indefinitely.
4.4 Observability
Use logging services and monitoring alerts to record token consumption, iteration counts, failure stages, and the final outcome of every run. These records can form an evaluation dataset for regression testing.
Without this data, claims of improved capability remain subjective.
5. Human Review Gates Must Remain
End-to-end automation does not mean removing people entirely. Require human review for three categories of change:
- Data migrations or irreversible writes.
- Changes to public interfaces or permission models.
- Changes whose verification coverage falls below the established threshold.
Other low-risk changes can be submitted automatically and proceed to canary monitoring.
6. Recommended Acceptance Metrics
- First-pass success rate: The proportion of tasks that complete builds and tests without human intervention.
- Average iteration count and token cost: Measures of economic efficiency.
- Regression rate: The proportion of changes that require another fix shortly after merging.
- Escalation precision: The proportion of requests for human assistance that genuinely require it.
7. Common Pitfalls
Four mistakes frequently separate a usable demo from a dependable daily workflow:
- Treating context window size as a measure of overall capability.
- Letting the model decide what to read without explicit controls, leading to context drift.
- Executing with production credentials and no sandbox.
- Evaluating patch quality while ignoring the verification loop.
Long context gives agents the information foundation needed to take on complete engineering tasks. Finishing the work, however, depends on four components: context budgets, idempotent tools, environment-based verification, and observability.
Model capability sets the ceiling; engineering constraints establish the floor.
