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

    This article explains why the real bottleneck for AI coding agents is not producing a first patch but completing end-to-end delivery, and how long context, layered loading, verification loops, and permission boundaries address it. It covers a three-layer context structure, a five-stage delivery pipeline, tool orchestration and access governance, an evaluation system based on completion rather than similarity, and the practical limits of open-weight models. Readers will find concrete structures, pseudocode, and rollout guidance for putting agents on real maintenance work.

    1. Reframing the Problem: The Bottleneck Is the Wrap-Up, Not the Code

    Hand an AI coding tool a bug ticket and it will often produce a plausible-looking patch within minutes. The hard work comes afterward. When tests fail, someone has to read logs, locate the regression, and decide whether the cause is environmental or logical. When a build breaks, dependency conflicts, cache pollution, and missing artifacts all have to be ruled out. Before release, change notes, a rollback plan, and a canary strategy still need to be written. These stages share the same traits: long chains, many states, sparse feedback, and a high cost of failure.

    So the measure of whether an agent can actually do the job should not be how similar its first patch looks. It should be end-to-end task completion rate, average number of repair rounds, human takeover rate, and change rollback rate. This is where long context earns its place. The point is not to let the model read the entire codebase in one pass, but to let the agent keep continuous memory of the goal, the constraints, past decisions, and the failure trail across one task lifecycle, so it does not forget why it made a change while it is still making changes.

    2. Using Long Context Correctly: Layered Loading and Evidence Chains

    Treating a million-token context as a full dump is a common mistake. It wastes budget and dilutes attention. A safer approach is layered loading:

    • Layer 1: the task contract. The goal, acceptance criteria, directories and interfaces that must not be touched, and a time budget.
    • Layer 2: the evidence pack. Relevant file slices, call chains, failure logs, the last three commit diffs, and a snapshot of monitoring metrics.
    • Layer 3: the history trail. Approaches already tried, reasons they failed, and assumptions that were rejected, forming a reusable “negative results” store.

    A schematic context-loading structure looks like this:

    1. {
    2. "contract": {"goal": "fix settlement timeout", "acceptance": ["all unit tests green", "P99<300ms"], "deny_paths": ["config/prod"]},
    3. "evidence": {"files": ["src/billing/settle.ts"], "logs": ["trace-8821"], "diff": "HEAD~3..HEAD"},
    4. "memory": {"tried": ["add index", "raise timeout"], "rejected": ["change protocol"], "reason": "compatibility risk"}
    5. }

    The key is that every conclusion must trace back to evidence: a cited file and line number, a log fragment, a metric curve. Any assertion without evidence should be forcibly downgraded to a “hypothesis” and pushed into a verification queue rather than written straight into a patch.

    3. From Patch to Delivery: A Five-Stage Pipeline

    1. Reproduce and pin down. Write a minimal case that reproduces the problem reliably, turning “intermittent” into “always reproducible.” This step determines whether every later verification is trustworthy.
    2. Locate and hypothesize. Based on call chains and logs, propose two or three mutually exclusive hypotheses and design observation points that can tell them apart, instead of making one sweeping change.
    3. Minimal change. Touch only the code directly related to the acceptance criteria, add the observability instrumentation that is genuinely needed, and no opportunistic refactoring.
    4. Verification loop. Run in layers: static checks, unit tests, contract tests, integration tests, and a performance baseline comparison. On failure, feed the complete output back in as new evidence.
    5. Deliverable generation. Change notes, an impact inventory, rollback steps, and canary plus observability metrics are all produced together. Missing any one of them counts as not done.

    The main loop in pseudocode:

    1. while not done and rounds < MAX_ROUNDS:
    2. obs = run_checks(patch) # tests/build/static checks
    3. if obs.passed:
    4. done = package_delivery(patch, rollback_plan, metrics)
    5. else:
    6. memory.append(obs) # store the failure trail
    7. patch = propose_next(patch, evidence=memory)

    4. Tool Orchestration and Permission Governance

    The real risk with agents comes from write access that is too broad. Split capabilities into three tiers: read-only, sandboxed write, and controlled release. Read-only covers retrieval and analysis. Sandboxed write is confined to a temporary branch and a container, and can be discarded at any time. Controlled release must pass human approval and policy checks. Every external action (commits, deployments, config changes) should go through a single tool gateway that centralizes authentication, rate limiting, auditing, and idempotency control, so repeated execution cannot cause side effects.

    On the engineering side, a container platform can supply isolated environments, object storage can hold evidence packs and artifacts, a message queue can decouple long-running tasks, and logging plus monitoring and alerting services can receive verification results, forming a loop that is observable, traceable, and replayable.

    5. Evaluation: Do Not Measure “Does It Get Done” by “Does It Look Right”

    Keep a fixed internal benchmark set built from real bug tickets, and track four metrics: first-pass rate, average repair rounds, human takeover rate, and rollback rate. Record the cost dimension alongside them: context size, number of tool calls, and wall-clock time. Only when success and cost sit in the same table can you judge whether automation actually pays off.

    6. Why Open Weights Matter, and Where to Draw the Line

    Open weights let a team deploy, fine-tune, and isolate data inside its own environment, keeping sensitive code on the internal network, which matters most in settings with strict compliance requirements. But open does not mean maintenance-free: version upgrades, evaluation regression, security scanning, and cost accounting all need standing mechanisms. The pragmatic path is to get the loop working first in low-risk domains (test completion, log attribution, documentation and change notes), then widen it gradually to core paths, while always keeping a human gate and the ability to roll back quickly.

    7. Conclusion

    Million-token context and open weights only amplify what is possible. What actually decides success or failure is three fundamentals: context engineering, a closed verification loop, and permission boundaries. Treat the agent like a new colleague on probation: give it clear acceptance criteria, evidence it can check, limited permissions, and an explicit fallback plan, and it has a chance to finish the dirty work instead of leaving behind half-finished pieces for people to clean up.