AI Agents with a Million-Token Context: From Writing Patches to Finishing the Dirty Work

    A million-token context window is often treated as the missing piece that would let AI coding agents handle messy engineering work end to end. This article argues that a larger context is a necessary but insufficient condition. The real bottleneck is the long tail of delivery: reproducing failures, running tests, interpreting logs, checking dependencies, and proving a change is safe. It outlines a vendor-neutral five-layer architecture (evidence, memory, planning, execution, and acceptance), context engineering practices such as layered summarization and token budgeting, a sandboxed execution loop, and machine-readable acceptance gates. It also covers common failure modes and a phased adoption path for teams.

    1. Reframing the Problem: The Hard Part Is Finishing, Not Writing

    Hand a coding agent a bug ticket and it will often produce a plausible-looking patch within minutes. The real cost comes after the patch: Do the tests pass? Is the failure reproducible? Are the logs interpreted correctly? Are dependencies present? Does the change introduce regressions? Does it follow the repository’s existing conventions? Together, these steps form the long tail of engineering delivery.

    So asking whether a million-token context can let an agent finish the dirty work is really asking three questions:

    1. Can the context hold enough evidence for a long-chain task?
    2. Does the agent have a stable execution and feedback loop?
    3. Can the result be verified by machine rather than by a human reading a diff?

    The conclusion up front: a longer context is a necessary condition, not a sufficient one. Without an execution environment and acceptance criteria, a long context only amplifies noise and hallucination.

    2. Why a Long Context Is Necessary but Not Sufficient

    The value of a long context is that it reduces the overhead of moving evidence around. Traditionally, someone has to trim logs, extract stack traces, and pick relevant files by hand — a slow process that easily drops key details. With a window that scales to a million tokens, you can load far more raw material at once: complete failure logs, source code for the relevant modules, dependency manifests, historical commit messages, test cases, and configuration.

    More capacity, however, introduces three new problems:

    • Lower signal-to-noise ratio: irrelevant content takes up more space and dilutes the model’s attention.
    • Localization drift: key evidence buried in a long text leads to vague, generic answers.
    • Higher cost and latency: stuffing everything into the window is not economical and needs retrieval and tiering to work well.

    The more robust engineering pattern is therefore layered memory with on-demand recall, not putting everything into the window.

    3. A Reference Architecture: Five Layers That Carry a Task to Completion

    The following is a vendor-neutral, general-purpose architecture for long-chain automated repair.

    1. Evidence layer: logs, monitoring alerts, distributed traces, code repositories, build outputs, and artifact stores are catalogued together into a searchable evidence pool.
    2. Memory layer: split into short-term (the current task context), mid-term (a summary of repository structure and conventions), and long-term (historical defect patterns and repair experience), recalled through summarization and vector retrieval.
    3. Planning layer: breaks “fix and deliver” into verifiable sub-goals, such as reproduce, localize, make the minimal change, add tests, run regression, and produce a write-up.
    4. Execution layer: a container platform provides an isolated sandbox with compile, test, and static-analysis capabilities; all write operations happen on a branch or a working copy.
    5. Acceptance layer: test results and quality gates are the sole arbiter; it emits a structured report, and humans only do sampled review.

    Illustrative task orchestration (pseudocode that expresses the flow only and points to no specific tool):

    1. task = {
    2. "goal": "fix the defect and pass regression",
    3. "evidence": ["logs", "trace", "repo", "deps"],
    4. "constraints": ["minimal change", "do not modify public interfaces", "add a reproduction test"]
    5. }
    6. def run_agent(task):
    7. ctx = build_layered_context(task) # assemble context in layers
    8. plan = planner(ctx) # generate verifiable sub-goals
    9. for step in plan:
    10. patch = coder(ctx, step) # produce a minimal patch
    11. sandbox.apply(patch) # run in an isolated environment
    12. report = sandbox.verify() # compile / unit test / regression
    13. if report.passed:
    14. return finalize(patch, report)
    15. ctx = ctx.update(report.evidence) # feed failure evidence back
    16. return escalate_to_human(ctx) # escalate beyond the threshold

    The key point is that report must be a machine-readable structured result, not a block of natural-language description.

    4. Context Engineering: Making a Million-Token Window Actually Usable

    1. Layered summarization: generate repository-level, module-level, and file-level summaries in sequence, so you localize coarsely first and read closely later.
    2. Hybrid retrieval: keyword recall handles precise symbol lookup, while vector recall finds semantically similar historical defects.
    3. Evidence citation: attach a source identifier to every conclusion (file and line number, log timestamp) so it can be reviewed and traced.
    4. Budget control: set a token budget and priority for the context, and drop low-value fragments when the limit is exceeded.
    5. Structural constraints: require output in a fixed schema, for example four sections: patch, impact surface, verification commands, and residual risk.

    A simplified context budget allocation example:

    1. Total budget 100%
    2. ├─ Current failure evidence 35%
    3. ├─ Relevant source and call chain 30%
    4. ├─ Tests and configuration 15%
    5. ├─ Similar historical defects 10%
    6. └─ Repository conventions and summaries 10%

    5. The Execution Loop: No Sandbox, No Trustworthy Delivery

    Dirty work is exhausting because it takes repeated iterations of do, verify, and fix again. That requires the execution layer to provide:

    • Isolation: a containerized environment that avoids polluting the main branch and local dependencies.
    • Reproducibility: locked dependency versions and a deterministic build process.
    • Rollback: each attempt runs in a separate working copy and is discarded on failure.
    • Resource quotas: limits on duration and compute to prevent infinite loops.
    • Least privilege: the code repository is read-only by default, and write operations require explicit authorization.

    In practice, set a maximum iteration count plus structured feedback of failure evidence. When the threshold is exceeded, escalate to a human automatically so the agent does not keep circling the same spot.

    6. Acceptance and Observability: Turning “Looks Right” into “Provably Right”

    The acceptance layer is the dividing line for the whole approach. It should include at least four kinds of gates:

    1. Compile and static checks: syntax, types, style, and common defect patterns.
    2. Unit tests: a newly added reproduction case must go from failing to passing.
    3. Regression tests: the existing test suite must show no new failures.
    4. Change audit: a checklist output of the change scope, affected interfaces, and configuration changes.

    For observability, record the input summary, decision rationale, executed commands, output results, and elapsed time of each attempt to form a traceable chain. This both explains why the agent changed the wrong thing and accumulates into long-term memory that improves the hit rate next time.

    A structured acceptance report example:

    1. {
    2. "change_scope": ["module_a/service.py"],
    3. "tests": {"new": "passed", "regression": "passed"},
    4. "commands": ["build", "unit-test", "lint"],
    5. "residual_risk": ["concurrent path not covered"],
    6. "needs_human": false
    7. }

    7. Common Failure Modes and How to Avoid Them

    • A stuffed context causes localization drift: switch to layered recall and budget control.
    • Fixing the symptom instead of the root cause: require a root-cause analysis and an impact-surface write-up.
    • Tests get “adjusted along the way”: treat changes to test files as high-risk items that need an explicit justification.
    • Missing dependencies lead to wrong conclusions: validate environment and dependency consistency before execution.
    • Delivering with no acceptance criteria: define the gates first, then let the agent start.

    8. Adoption Roadmap and Team Roles

    Phase one, make it reproducible: unify the entry points for logs, builds, and tests so that one command runs the whole flow. Phase two, make it searchable: build evidence cataloguing and hybrid retrieval to form layered memory. Phase three, make it deliverable: connect the sandbox and quality gates and output a structured acceptance report. Phase four, make it operable: accumulate a defect-pattern library and continuously evaluate hit rate, rework rate, and human-intervention rate.

    Keep role boundaries clear: the agent handles evidence organization, patch candidates, and regression execution; engineers own standard definition, risk adjudication, and the final merge. If a company needs elastic compute and isolated environments, it can combine general cloud product categories such as container platforms, object storage, logging services, and monitoring and alerting, without binding to any specific implementation.

    9. Conclusion

    Million-token contexts and open weights have lowered the barrier to long-chain automation, but what really decides success is context engineering quality, sandbox execution capability, and a machine-based acceptance system. Get those three solid, and an agent can move from “producing a patch” to “delivering a verifiable artifact” — only then is it fair to say the dirty work is truly taken over.