Engineering Practices for Million-Token Context Code Agents

    This article examines practical engineering challenges in building code agents with million-token context windows, covering capability boundaries, context organization, long-horizon execution, verifiable workflows, factuality and safety controls, cost optimization, and evaluation strategies. It provides actionable guidance for turning large context capacity into reliable, traceable, and cost-effective task delivery.

    When the context window grows from tens of thousands of tokens to a million, a model can hold an entire code repository, long documents, multi-step tool traces, and business rules in a single pass. However, the engineering challenge does not disappear—it shifts from “can we fit it all in” to “how do we organize, validate, and control cost.” The core value of a million-token context code agent is not generating longer text in a single turn, but maintaining goal alignment, traceable evidence, reversible actions, and verifiable results across long-running tasks. This article covers capability boundaries, context engineering, long-horizon execution, code and specialized workflows, factuality and safety, cost management, and evaluation.

    1. Capability Boundaries: A Million-Token Context Is Not a Universal Container

    A million-token context is well-suited for three categories of tasks:

    • Repository-level code understanding and cross-file refactoring: the model can simultaneously reference interface definitions, call chains, test cases, and historical changes in a single task.
    • Long-document-intensive workflows: financial modeling, investment analysis, industry research reports, and compliance reviews.
    • Long-horizon agent tasks: the model must continuously plan, call tools, observe results, and repair errors.

    However, the context window is a budget, not a dumpster. Indiscriminately stuffing all logs, all source code, and all historical conversations into the window creates three problems: attention dilution causes key constraints to be overlooked; input cost rises linearly with length; and noise and conflicting information in tool outputs interfere with decision-making. Therefore, engineering practice should follow the principle of “layered organization, on-demand retrieval, summarization and compression, and citable references.” For high-risk production changes, additional safeguards are required: isolated sandboxes, least-privilege access, timeout controls, and rollback plans. For open-ended tasks without acceptance criteria, break them into verifiable subtasks to prevent the agent from drifting off course in long loops.

    2. Context Engineering: Layering, Compression, Retrieval, and Caching

    It is recommended to structure the context in six layers:

    Layer Contents
    System instructions Safety policies and output format requirements
    Task contract Goals, constraints, acceptance criteria, permission boundaries
    Evidence Retrieved code snippets, document passages, data tables
    Working memory Confirmed facts, pending items, failure patterns
    Tool outputs Structured results and summaries
    Recent trajectory Recent turns of actions and observations

    Each layer gets an independent budget to prevent a single layer from consuming the entire window.

    Compression strategies should vary by content type:

    • Code: symbol indexes, syntax tree summaries, and change patches.
    • Documents: section-level summaries, entity tables, and timelines.
    • Tool outputs: retain status codes, key fields, error types, and reproducible parameters; convert long logs into statistical summaries.

    Retrieval should combine keyword search, vector search, and symbol indexes, with reranking before generation. The model should be required to attach citation numbers after key conclusions.

    Caching should be designed around prefix reuse: stable system instructions, task contracts, and shared evidence can hit the cache. Short-duration tasks use a shorter cache write period; long-duration tasks use a longer period. Standard and high-speed tiers can be separated by latency requirements—the high-speed tier typically charges a higher unit price for lower response time. Engineering teams should use model routing to reserve high-speed capacity for interactive debugging and critical paths.

    1. function assembleContext(task, memory, budget):
    2. contract = buildContract(task) // goals, constraints, acceptance, permissions
    3. evidence = hybridRetrieve(task, memory, budget.evidence)
    4. workMem = compress(memory.confirmed, budget.memory)
    5. recent = summarize(memory.trace, budget.trace)
    6. return layout(systemPolicy, contract, evidence, workMem, recent)

    3. Long-Horizon Agents: State Machines, Tool Contracts, and Verification Loops

    Long-horizon tasks should be explicitly modeled as a state machine: plan → execute → observe → verify → fix → deliver.

    Every tool call should have a structured contract that includes at minimum: tool name, parameters, expected effects, rollback plan, and verification method. Sandbox execution must restrict file access, network, resources, and time limits. Dangerous actions require a check before execution.

    The verifier should cover:

    • Static checks
    • Unit tests
    • Runtime output comparison
    • Fact and citation verification
    • Format validation

    On failure, only repairable error summaries should be fed back into the context, rather than re-injecting the full noisy logs.

    1. function runAgent(task):
    2. contract = buildContract(task)
    3. memory = newMemory()
    4. for step in 1..maxSteps:
    5. ctx = assembleContext(task, memory, budget)
    6. action = model.plan(ctx)
    7. checkPolicy(action, contract)
    8. obs = sandbox.execute(action, timeout, resourceLimit)
    9. memory.append(compress(action, obs))
    10. if verifier.pass(obs, contract): return deliver(obs)
    11. if verifier.repairable(obs): memory.append(repairHint(obs))
    12. if budget.exceeded(): break
    13. return escalate(memory)

    4. Code, 3D Scripts, and Financial Workflows: Executable Verification First

    For code tasks, follow a small-patch, test-driven approach: first locate symbols and call chains, then generate the minimal change, then run relevant tests and check for regressions.

    For 3D modeling script generation, pay additional attention to units, coordinate systems, parameter constraints, and geometric runnability. After tool calls, verify object counts, dimension ranges, and export results—do not rely solely on text descriptions.

    For financial workflows, fix data definitions, formula versions, and citation sources. Perform secondary checks on key calculations, and isolate and anonymize sensitive data.

    The value of such end-to-end tasks lies in turning “generation” into “runnable, reviewable, deliverable” outcomes.

    5. Factual Accuracy and Safety Governance

    Factual accuracy cannot rely on model self-checking alone. Engineering measures should include:

    • Retrieval augmentation: ground answers in retrieved evidence.
    • Citation constraints: require citations for key conclusions.
    • Multi-candidate consistency checking: compare multiple model outputs for agreement.
    • Refusal strategy: for conclusions without evidence, require explicit uncertainty labeling.
    • Cross-verification: cross-check key numbers and entities.
    • Stress test sets: build adversarial test cases for error-prone scenarios, tracking single-fact error rates and the proportion of answers containing errors.

    For safety, identify and remove high-risk attack and abuse data during training and reinforcement stages. Conduct red-team evaluation and abuse detection before release. Note that production-version capabilities may be lower than unfiltered versions due to safety filtering—this is a necessary trade-off. Production systems also require least-privilege access, operation auditing, output filtering, and human review channels.

    6. Cost Model and Model Routing

    Cost optimization should be structured around billing dimensions:

    • Input tokens
    • Output tokens
    • Cache hits
    • Cache writes (short period / long period)
    • High-speed tier multiplier

    Engineering measures include: improving cache hit rates, reusing task contracts and shared evidence, compressing tool outputs, limiting output length, batch-processing non-interactive tasks, routing models by task difficulty, and setting per-task budget caps. For trajectory, tool output, and cost metric archiving and observability, object storage, log services, and monitoring and alerting capabilities can be used.

    1. cost = in_tokens * P_in + out_tokens * P_out
    2. + cache_hit * P_hit
    3. + write_short * P_write_short
    4. + write_long * P_write_long

    7. Evaluation, Release, and Implementation Checklist

    Public benchmarks serve only as references. Internal benchmarks should reflect real business scenarios and track the following metrics simultaneously:

    • Task pass rate
    • Average repair rounds
    • Factual error rate
    • Safety pass rate
    • P95 latency
    • Cost per task

    Release strategy: start with small traffic canary testing, keep rollback switches and trajectory audits in place, then gradually expand.

    Implementation checklist:

    1. Write task contracts and acceptance criteria first.
    2. Implement context layering and hybrid retrieval.
    3. Ensure tool calls are sandboxed, idempotent, and reversible.
    4. Require citable references for key conclusions.
    5. Put safety filtering and red-team evaluation in place before release.
    6. Normalize cost monitoring and model routing.

    Only by combining long context, long-horizon execution, and verification loops can a million-token context model evolve from “reading a lot” to “delivering reliably.”