Context Engineering for AI Agents: Using a Code Action Space to Counter Context Rot

    This article explains why AI agents forget constraints and hallucinate as tasks grow, tracing the root cause to context management rather than model intelligence. It breaks down what fills a typical coding agent's context window, then presents a code-based action space (CodeAct-style) as the mitigation: the model writes and executes code instead of reading raw data into context. A minimal implementation architecture, scheduling example, common pitfalls, and boundaries are included.

    1. Background: Why Agents Drop the Ball

    Using language models to write code, query databases, and run automated workflows is now part of everyday development. Practices around “driving development with natural language” spread quickly over the past year, and most developers now rely on them to some degree for working with codebases, filling in documentation, and handling routine chores. But one long-standing problem remains unsolved: as tasks pile up, the agent starts missing constraints and may even fabricate facts with complete confidence.

    Many people blame this on the model “not being smart enough,” which is a misdiagnosis. The more critical reason is that context management has gotten out of control. The convenience of plugging in external tools (browser automation, data platforms, collaboration tools) does extend the agent’s capabilities, but the cost is that the context fills up quickly. This is what the industry commonly calls Context Rot: as input tokens accumulate, the model becomes less sensitive to critical information and output quality collapses.

    2. What Actually Fills the Context Window

    To solve the problem, you first need to understand the cost structure. Take a typical coding agent’s context allocation, which can be abstracted into four layers:

    • System-level instructions: define the role, boundaries, and output specifications. This is usually a small share (a single-digit percentage).
    • Tool and interface descriptions: schemas, parameter descriptions, and usage constraints for both built-in and externally integrated tools. This takes up noticeably more space than the system instructions.
    • Agent runtime context: skill descriptions, task state, conversation history, and intermediate artifacts. This is often the largest block and can occupy the majority of the window.
    • The user’s actual input space: what remains for the current prompt and business data is fairly limited.

    The industry consensus is that the portion reserved for system-level constraints is only about ten percent, while the rest is filled by history and tool output. When the total approaches the range of a hundred thousand to a couple hundred thousand tokens, the model struggles to reliably distinguish the “main task” from “noise.” Three typical failure modes then appear: constraint forgetting (missing earlier requirements), context confusion (applying conclusions from task A to task B), and hallucinated completion (making things up when information is insufficient).

    The conclusion is straightforward: Context Rot is the shared upstream cause of both forgetfulness and hallucination. Switching to a larger window only postpones the problem; it does not eliminate it.

    3. The Mitigation: Switch the Action Space from Text to Code

    A more engineering-oriented approach is to stop having the model read massive amounts of data into the context and then “understand” it. Instead, let it write code, execute it, and read the result. This is the core idea of using “code as the action space,” and it corresponds to the CodeAct-style paradigm discussed in the industry.

    Take the simplest example: looking up student records for students enrolled in 2025.

    1. SELECT * FROM students WHERE enrollment_year = 2025;

    A single statement does the job, and the data never has to enter the model’s context. If you reframe it as a natural-language request, “find the records of students enrolled in 2025,” the flow becomes:

    1. One model call for intent understanding and parameter extraction;
    2. Generate executable code (SQL, Python, or a script);
    3. Execute it in an isolated environment;
    4. Verify whether the output satisfies the constraints;
    5. Return the result if satisfactory; otherwise iterate and fix it with the error information.

    The key point: what flows through the context is “code plus a compact result,” not the raw data itself. No matter how large the dataset, the tokens consumed stay roughly constant.

    4. Why This Approach Works

    • Higher information density: the information a 20-line script can express often exceeds thousands of lines of logs.
    • Locatable errors: an execution error is structured feedback, far more reliable than the model “feeling” something is wrong.
    • Reusable and auditable: code is an explicit asset that can be accumulated, reviewed, and regression-tested.
    • Native support for parallelism and batching: splitting a task into several small scripts is more stable than making the model “think it all through” at once.
    • Suppressed hallucination: results come from real execution rather than the language model’s free association.

    A runnable minimal loop typically consists of five components:

    1. Intent parsing layer: converts natural language into a structured task description (goal, inputs, constraints, acceptance criteria).
    2. Code generation layer: produces scripts within a restricted syntax and a whitelist of APIs to avoid unauthorized operations.
    3. Sandbox execution layer: containerization, resource limits, network isolation, and timeout control to prevent side effects from spilling over.
    4. Result verification layer: uses assertions, schema validation, and sampling comparisons to confirm correctness.
    5. Context compression layer: returns only summaries and necessary fragments, retrieving history on demand rather than carrying it all.

    Illustrative scheduling logic:

    1. def run_task(task, max_iter=5):
    2. ctx = summarize(task) # compressed context
    3. for i in range(max_iter):
    4. code = generate_code(ctx) # generate code
    5. out = sandbox.exec(code) # isolated execution
    6. if verify(out, task.accept): # result verification
    7. return out
    8. ctx = append_error(ctx, out) # return only the error summary
    9. raise RuntimeError("task not converged")

    6. Common Pitfalls and Boundaries

    • Not every task is suited to being code-based: highly subjective creative tasks see limited benefit.
    • A sandbox is not optional: running generated code directly in production is extremely risky.
    • Verification must be independent: letting the generator grade itself is as good as no verification.
    • Context compression must preserve traceability: beyond summaries, you should be able to look up the original fragments on demand.

    7. Conclusion

    The stability bottleneck of agents is essentially not model intelligence but context engineering. Switching the action space from “piling up text” to “writing code, running code, reading results,” with a sandbox and verification layer as safeguards, is what keeps token usage low and accuracy high in long-running tasks. For teams that want to build reliable automation workflows, this approach can be embedded directly into existing toolchains and implemented on top of the container, logging, and monitoring capabilities of a general-purpose cloud platform, without depending on any vendor’s proprietary interfaces.