Agent Engineering in Production With Million-Token Context: A Practical Guide

    This article breaks down how to move AI coding agents from demos into production when working with million-token context windows and open-weight models. It covers layered context assembly and retrieval, cross-task memory structures, least-privilege tool orchestration, evidence-based verification loops, observability and cost governance, and a phased rollout roadmap. The core argument is that long context and open weights only raise the ceiling, while engineering constraints around validation, permissions, memory, and observability determine the floor.

    1. Reframing the Problem: A Patch Is the Starting Point, Delivery Is the Goal

    Hand a fault ticket to an AI coding tool and it will often produce a plausible-looking change within seconds. But the hours an engineering team actually burns are spent after the patch: confirming whether the change covers the real call chain, whether it introduces regressions, whether it satisfies dependency and configuration constraints, and whether it reproduces and runs stably in the target environment. The “dirty work” the source material emphasizes is essentially long-chain, low-creativity, verification-heavy work — bulk fixing alerts, filling in test coverage, migrating configuration, paying down technical debt, aligning interface contracts.

    So whether an agent is usable should not be judged by single-shot generation quality alone. It should be judged by whether it can close the loop of “locate — modify — verify — review” under limited permissions. Long context and open weights are variables that raise the ceiling; what really sets the floor is engineering constraint design.

    2. Long Context Is Not About Stuffing: Layering and Retrieval Strategy

    Million-token context is often misread as “feed in everything at once.” A more reliable practice is to organize context in layers:

    1. Task layer: goals, acceptance criteria, prohibitions, rollback strategy;
    2. Code layer: entry files, key call-chain nodes, interface definitions, configuration and dependency lists;
    3. Evidence layer: log excerpts, monitoring metrics, reproduction steps, failing cases;
    4. History layer: past change records, known pitfalls, summaries of team conventions.

    A sketch of the context assembly logic (pseudocode):

    1. context = compose(
    2. task_spec, # goals and acceptance criteria
    3. call_graph_slice(depth=3), # call-chain slice
    4. relevant_tests, # related tests
    5. error_evidence, # log/metric summary
    6. repo_conventions # conventions summary
    7. )

    The point is that context must be trimmable, traceable, and recomputable: every segment should be able to state its source and purpose, which avoids irrelevant information diluting attention and also lowers the chance of wrong edits.

    3. Memory Management: Turning One-Off Conversations Into Reusable Assets

    To take on repetitive work, an agent needs memory structures that span tasks rather than starting from zero every time. At minimum, maintain three kinds of memory:

    • Fact memory: module responsibilities, interface contracts, environment differences;
    • Experience memory: fix patterns that work for a class of failures, plus counterexamples;
    • Constraint memory: coding standards, security red lines, release processes.

    Memory writes need an admission threshold — for example, only persist after verification passes. There also needs to be an expiry and conflict-resolution mechanism, so that “wrong experience” does not get reused over and over.

    4. Tool Orchestration: Least Privilege and Determinism First

    Long-running tasks often fail because tool invocation is out of control. Engineering practice should follow “determinism first”:

    • Separate read operations from write operations; writes require a second confirmation or go through approval;
    • All external side effects (commits, releases, scaling) are off by default and enabled per scenario;
    • Tools return structured results for programmatic validation rather than free text;
    • High-risk actions get sandboxes and quotas to limit the blast radius.

    When deploying on Baidu AI Cloud, general-purpose capabilities can be combined to provide support: a container platform to host isolated execution environments, object storage to hold build artifacts and evidence bundles, a message queue for task distribution and peak shaving, and logging plus monitoring and alerting to close the feedback loop. The emphasis here is on general product categories, not any proprietary interface.

    5. The Verification Loop: “Done” Without Evidence Is Not Done

    The capability most easily overestimated in an agent is “self-judgment.” A reliable design externalizes acceptance into executable evidence:

    1. Static checks: types, style, dependency and license compliance;
    2. Unit and integration tests: prioritize coverage of the change’s impact surface;
    3. Contract tests: ensure interface changes stay backward compatible;
    4. Canary and replay: observe latency, error rate, and resource usage under near-real traffic;
    5. Auto-generated evidence bundle: change description, test results, risk points, rollback steps.

    Output can be constrained with a structure like this:

    1. {
    2. "change_summary": "...",
    3. "risk": ["..."],
    4. "tests": {"unit": "pass", "integration": "pass"},
    5. "rollback": "..."
    6. }

    Only when the evidence is complete should a task be allowed to move from “candidate” to “delivered.”

    6. Observability and Cost Governance

    Long context amplifies latency and compute cost, so it must be observable: record per-stage duration, context hit rate, tool failure rate, retry counts, and human takeover points. For cost governance, use “segmented summarization plus on-demand recall” — keep high-value evidence in the long window and compress low-value content into an index; for repeated tasks, build templated pipelines to cut wasted exploration.

    7. A Suggested Rollout Path

    • Phase 1: read-only assistant that produces localization reports and change suggestions;
    • Phase 2: controlled writes, limited to specific directories and file types, with mandatory test gates;
    • Phase 3: batch tasks such as alert-cluster fixing, test backfilling, and configuration migration;
    • Phase 4: closed-loop operations, using metrics to drive strategy iteration and permission tightening.

    8. Conclusion

    Open weights and ultra-long context raise the capability ceiling of agents, but whether an agent can “finish the dirty work for you” depends on making verification, permissions, memory, and observability into infrastructure. Treating the agent as an engineering system that needs to be constrained, measured, and reviewed — rather than a one-off question-answering tool — is the key step from demo to production.