Agentic Execution with a Million-Token Context: A Practical Guide
This article redefines the real bottleneck of coding agents, showing that the challenge is not writing a patch but maintaining factual consistency within a limited context budget. It presents a four-layer context window strategy, a five-stage pipeline from issue ticket to patch, a layered verification system with structured results, and guidance on permissions, sandboxes, and observability. Readers will learn how to treat long context as a scarce resource, reduce rework and review time through process design, and keep humans in charge of contracts and final approval.
1. Reframing the Problem: The Real Bottleneck Is Not Writing the Patch
Hand a coding agent a bug ticket and it will often produce a plausible-looking patch within minutes. The hard work comes in the second half: whether tests pass reliably, whether boundary and concurrency paths are covered, whether dependencies and configuration are reproducible, whether the change can be rolled back, and whether a reviewer can understand the intent of the change in a limited amount of time. The original phrase “one test failure” points to the key issue: an agent’s output is a candidate, not a deliverable conclusion.
So the standard for evaluating long-context capability should not be “how much code can you stuff in,” but “can you maintain factual consistency within a limited context budget.” The longer the context, the more noise it contains, and the more easily a model confuses similar functions, older logic, comments, and the actual implementation. Engineering practice must govern long context as a scarce resource, not treat it as a cache that can expand indefinitely.
2. Context Budget: Turning a Million-Token Window into a Searchable Workspace
In practice, divide the window into four layers, each with a clear quota and expiration policy:
| Layer | Content | Suggested Share | Expiration / Update Policy |
|---|---|---|---|
| Task contract | Bug ticket, reproduction steps, acceptance criteria | 5%–10% | Unchanged throughout, highest priority |
| Critical implementation | Target functions, direct dependencies, interface definitions | 20%–30% | Refreshed after every tool call |
| Retrieved evidence | Log snippets, call traces, similar historical changes | 30%–40% | Timestamped, evicted once expired |
| Draft space | Patch drafts, hypotheses to be verified | Remainder | Archived or discarded after verification |
The key principle is “contract first, then evidence, then implementation.” The task contract must stay resident and must not be overwritten by later content; otherwise the agent will gradually drift from the acceptance criteria over a long workflow. Retrieved evidence must carry its source and timestamp so that an already-fixed old log is not mistaken for the current state.
Illustrative context assembly logic:
def build_context(task, repo_index, logs, budget=200_000):parts = [("contract", render_contract(task), 0.10),("evidence", select_evidence(logs, task, ratio=0.35), 0.35),("code", repo_index.query(task.symbols, ratio=0.30), 0.30),("draft", "", 0.25),]out, used = [], 0for name, text, ratio in parts:limit = int(budget * ratio)out.append(f"<{name}>\n{text[:limit]}\n</{name}>")used += min(len(text), limit)return "\n".join(out), used
3. From Bug Ticket to Patch: A Five-Stage Pipeline
- Reproduce and pin down: Turn an intermittent failure into a repeatable minimal case, fixing the random seed, time source, and concurrency level. Problems that cannot be reproduced should not enter the automated repair flow.
- Locate and hypothesize: Produce no more than three verifiable hypotheses, each with “what should be observed if it holds,” avoiding a large sweeping change all at once.
- Minimal patch: Change only the code paths directly related to the acceptance criteria; no opportunistic refactoring or reformatting, to keep review costs low.
- Layered verification: unit tests → integration tests → regression and performance baselines. Any layer failing triggers a rollback; no “run and guess as you go.”
- Delivery notes: Include the motivation for the change, the blast radius, the rollback method, and uncovered risks, so a reviewer can build a mental model within minutes.
4. Verification System: Stop One Test Failure from Derailing the Whole Flow
The core of layered verification is that failures must be locatable. Each stage should produce a structured result rather than free-form text:
{"stage": "integration","passed": false,"failed_cases": ["test_timeout_under_load"],"duration_ms": 48213,"flaky_suspected": true,"next_action": "rerun_with_fixed_seed"}
For suspected flaky cases, first rerun with a fixed seed and in isolation, then decide whether it is a product defect or a problem with the test itself. Performance and resource baselines belong in the same gate, so that “functionality passes but latency degrades” is not let through. All verification artifacts should land in a logging service and object storage for traceability and auditing.
5. Permissions, Sandboxes, and Observability
The prerequisite for autonomous execution is a controllable blast radius. The recommended approach: run inside a containerized sandbox, mount the main repository read-only, restrict writes to a separate branch; allow network egress only against a whitelist; inject secrets via temporary credentials that never touch disk; and require human confirmation for high-risk operations (deleting data, changing permissions, publishing artifacts).
Observability should cover at least four signals: the tool call sequence, the context usage curve, the verification pass rate, and the number of human interventions. The number of human interventions is the most honest indicator of automation maturity; if it does not go down, the bottleneck is the process, not the model.
6. Common Anti-Patterns
- Stuffing the entire repository into the window, diluting critical constraints;
- Having the agent fix several unrelated defects at once, making the review impossible to split;
- Using free-form text instead of structured verification results, making automated gating impossible;
- Lacking a rollback plan, so a patch can only move forward and never back;
- Using “generation speed” as the only metric while ignoring the rework rate.
7. Implementation Advice and Benefits
If you need elastic compute and unified governance, you can use a container platform to host sandboxes, object storage to hold artifacts, a message queue to decouple long-running tasks, and logging plus monitoring and alerting for full-chain tracing. Baidu AI Cloud offers corresponding capabilities in these general categories, which can be combined as needed to avoid tight coupling to a single tool. The real value of open weights and long context lies in solidifying a verifiable engineering process: the agent takes on repetitive labor, while humans own contract definition and final sign-off. Following the approach above, teams typically see rework rates and review time drop together within a few weeks, and that benefit comes from process design rather than window length alone.
