IamBishal
AI Engineering

Context Engineering for AI Agents: What Goes in the Window and What Stays Out

What piles up in an agent's context window shapes how long tasks go, so budget it like memory: trim tool output, retrieve just in time, compact, offload and isolate.

Bishal Saha

18 min read

The window is a budget, and the first job is finding out what you're spending it on.
Bishal Saha

Picture a coding agent asked to migrate a service's auth middleware across a repository. The first steps look sensible: it lists the routes, reads the middleware, runs the tests and makes a reasonable first edit. By step 30 it re-reads files it has already opened, drifts from the user's instruction to leave the public API alone, and calls a text search when it needed the symbol finder.

Context engineering is deciding what occupies the model's context window at every step of that run. Prompt engineering words one input well. Context engineering is a systems job: deciding, on every step, what to load, evict, cache and persist as tool results and history pile up. Agents run for dozens of steps, and what accumulates over those steps is easy to overlook: stale tool output, too many tools, instructions buried under history.

My argument is that long-task reliability depends less on prompt wording than on what occupies the window at each step, so the window should be budgeted like memory in a constrained system.

1. Context engineering is a runtime problem, not a wording problem

You write a prompt once. An agent's context is rebuilt at every step from the system prompt, tool definitions, retrieved content, memory and the growing record of turns and tool results. When nothing decides what goes into the next request, the default is "everything, in order of arrival".

Anthropic's write-up on context engineering describes the work as iterative, unlike the discrete task of writing a prompt: you curate on every model call.

That makes it a memory-hierarchy problem: the window is the small, fast, expensive tier, and everything else lives further out and is promoted only when a step needs it. For the migration agent, the repository belongs on disk and behind search tools, not in the window.

2. Why a fuller window can make the model worse

In Lost in the Middle: How Language Models Use Long Contexts, published in TACL in 2024, GPT-3.5-Turbo, Claude-1.3, MPT-30B-Instruct and LongChat-13B often performed best when the relevant information sat at the beginning or end of the input, and worse when it sat in the middle.

Two other findings from the paper matter more for agents. Extended-context versions of models scored nearly the same as their standard versions when the input fit in both windows: in that study, a bigger window bought more room, not better use of what was already there. And reader performance saturated far before retriever recall: handing the model more passages stopped helping long before retrieval stopped finding relevant ones.

Chroma's Context Rot report held task complexity constant and varied only input length across 18 LLMs, closed-source and open-weights. Performance grew increasingly non-uniform as input grew, even on simple tasks such as non-lexical retrieval and text replication. Chroma doesn't explain the mechanism. Attention dilution, a fixed attention capacity spread over more tokens, is a plausible mental model, not an established cause.

Neither result is about agents, and I'm not aware of either effect being measured inside a tool loop. So for the migration agent this is a hypothesis, not a diagnosis. At step 30, the user's API constraint hasn't moved: it still sits right after the tools and system prompt, near the beginning of the input, which is a position the paper found favourable. What changed is everything after it. The input is far longer than at step one, and input length is the one variable Chroma varied. Shrink what follows the constraint and see whether the behaviour changes.

3. What is actually in the window at step 30

Each consumer of the window behaves differently:

  • System instructions. Small, written by you, stable for the whole task.
  • Tool definitions. Every name, description and schema, sent with every request whether the tool is used or not.
  • Retrieved knowledge. Files, docs or search results for the current step. Useful now, dead weight a few steps later.
  • Memory. Notes, plans and state carried across compactions or sessions. Cheap when curated, harmful when stale.
  • Conversation and tool-result history. Every message and tool output so far.
flowchart LR
  subgraph S1["Step 1: mostly prefix"]
    direction TB
    P1["Stable prefix<br/>tools + system + task block"]
    R1["Retrieved<br/>conventions, repo map"]
    V1["Volatile state<br/>plan"]
  end
  subgraph S10["Step 10: history growing"]
    direction TB
    P10["Stable prefix"]
    H10["History<br/>turns + trimmed tool results"]
    R10["This step's reads<br/>arrive as tool results"]
    V10["Volatile state<br/>open errors, decisions"]
  end
  subgraph S30["Step 30: after crossing the budget threshold"]
    direction TB
    P30["Stable prefix"]
    C30["Compacted summary<br/>previous summary + evicted turns"]
    H30["Recent turns<br/>stubs keep references"]
    R30["This step's reads<br/>arrive as tool results"]
    V30["Volatile state<br/>re-read from state file"]
  end
  M[("External memory<br/>state file, notes, full logs")]
  S1 --> S10
  S10 -- "threshold crossed: clear, then summarise" --> S30
  S10 -- "agent writes progress" --> M
  M -- "read back on demand" --> S30

Left alone, the migration agent's window goes from almost all prefix at step 1 to mostly history by step 30: raw test output and file dumps from steps that finished long ago, describing the repository as it looked many edits back. The diagram shows steps 1, 10 and 30 once the techniques below are in place.

flowchart LR
  subgraph W[Context window at step N]
    P[Stable prefix: tools + system]
    T[Pinned task block]
    S[Compacted summary]
    H[Recent turns + tool results]
    V[Volatile state]
  end
  M[(External memory: notes, state)]
  K[(Repo, docs, stored outputs)]
  K -->|just-in-time reads| H
  H -->|over budget| C{Compaction}
  C -->|clear stale results| H
  C -->|summarise old turns| S
  C -->|write state| M
  M -->|read back| V
  H -->|unbounded growth| X[Context bloat]:::warn

4. Tool design decides most of what enters the window

Most of that history is tool output, so the tool layer is where the leverage is. It controls two inflows: definitions and outputs.

Definitions first. Anthropic reports that the most common tool failures are choosing the wrong tool and passing incorrect parameters, especially when tools have similar names. A migration agent with search_code, grep_repo and find_symbol invites the first failure. Merging them into one search tool with a mode parameter takes schemas out of every request, but it moves the choice into a parameter, which invites the second. I'd merge when the tools take the same inputs and differ only in how they search, and keep distinct, sharply described tools when the inputs differ. If you merge, validate the mode enum and return an error that names the valid values, so the model can correct itself on the next call.

Beyond a few dozen tools, Anthropic's tool search keeps deferred definitions out of the window until the model searches for them; the docs put the typical saving at over 85% of definition tokens and note that tool selection degrades beyond 30–50 tools.

Then outputs. Trim them at the tool boundary, in code, before anything reaches the model. A test run needs the counts, the failing tests and the top of each relevant stack trace, not the full log. When the detail might matter later, return a reference instead of the payload: a file path and line range, a log ID, or an MCP resource URI.

run-tests-tool.ts
// Illustrative MCP-style tool handler, not tied to a particular SDK version. Placeholder limits.
type Failure = { name: string; file: string; trace: string };
type TestRun = { passed: number; failed: number; failures: Failure[]; rawLog: string };

const MAX_FAILURES = 5;    // assumption: the agent works on a few failures at a time
const MAX_TRACE_LINES = 8; // assumption: the top frames usually point at the cause

export async function runTests(
  args: { path: string },
  deps: { exec: (p: string) => Promise<TestRun>; saveLog: (log: string) => Promise<string> },
) {
  const run = await deps.exec(args.path);
  const logId = await deps.saveLog(run.rawLog); // full log lives outside the window

  const shown = run.failures.slice(0, MAX_FAILURES).map((f) => ({
    name: f.name,
    file: f.file,
    // Drop dependency frames; keep the part of the stack that is your code.
    trace: f.trace.split("\n").filter((l) => !l.includes("node_modules"))
      .slice(0, MAX_TRACE_LINES).join("\n"),
  }));

  const summary = {
    passed: run.passed,
    failed: run.failed,
    failures: shown,
    // Count from the parsed list, not run.failed, so the number matches what was dropped.
    omittedFailures: run.failures.length - shown.length,
    fullLog: `logs://test-runs/${logId}`, // a reference, not the payload
  };
  return { content: [{ type: "text", text: JSON.stringify(summary) }] };
}

For steps with heavy fan-out, programmatic tool calling lets the model write code that calls your tools in a sandbox; intermediate results are not loaded into its context window, only the final output. Anthropic notes that orchestrating 20+ tool calls in one code block eliminates 19+ inference passes. The price is a sandbox, plus generated code you have to observe and bound, so I wouldn't make it the default.

5. Load knowledge when the step needs it

Pre-loading everything means you pay up front for tokens most steps never use, and every step then runs on a longer input than it needs, the variable Chroma varied, though on fixed tasks, not agents.

Just-in-time retrieval keeps lightweight identifiers in context, such as paths, queries and URIs, and promotes content on demand. The migration agent globs for middleware files and reads only the ones the current edit touches. The cost is more tool calls, more latency, and a blind spot: the agent can't search for something it doesn't know exists, such as a rule that the auth layer must log through a specific wrapper.

So I'd use a hybrid: pre-load what is small, stable and always relevant (project conventions, acceptance criteria, a short map of where things live) and fetch everything else on demand.

6. Compaction, and the things you never summarise away

Compaction is an eviction policy for history, and it should escalate from cheap to lossy:

  1. Clear stale tool results. A test log the agent has already acted on becomes a short stub with its reference, still in the window. Nearly lossless, because the reference survives.
  2. Summarise older turns, only if the window is still over budget, folding the previous summary in with the turns being evicted.
  3. Start a fresh window, seeded with the summary, the pinned items and external memory, only when the first two aren't enough.

Anthropic's API now offers versions of the first two tiers. Context editing clears old tool results to a placeholder, without your reference, so keep the pointer yourself, and server-side compaction replaces older turns with a summary, optionally keeping recent turns word for word. Both are in beta, and clearing invalidates the cached prefix, which is one more reason to clear in batches. The pinning rule below still applies.

Some items never go through the summariser. Static items (the original task, acceptance criteria, explicit user constraints, branch and ticket IDs) don't change for the life of the task. Volatile items (unresolved errors, decisions with their rationale, the exact files in play) change every few steps. Both stay verbatim because a summary paraphrases: "Don't change the public API" becomes "keep changes minimal", and src/auth/legacyMiddleware.ts becomes "the old middleware file". Capture these items in structured form when they're stated, rather than trusting the summariser to recognise them later.

compaction.py
# Illustrative policy. Placeholder values.
# estimate_tokens, summarise, stub, save_state and log_compaction are stand-ins.
COMPACT_AT = 0.7   # compact well before the hard limit, in one larger step
KEEP_RECENT = 6    # recent turns stay verbatim; the agent is mid-thought in them

def compact(ctx, window_limit):
    budget = COMPACT_AT * window_limit
    if estimate_tokens(ctx) < budget:
        return ctx

    save_state(ctx.state)  # write back before evicting anything
    old, recent = ctx.history[:-KEEP_RECENT], ctx.history[-KEEP_RECENT:]

    # Tier 1: stub tool results older than the recent turns (age stands in for "already acted on").
    # The references stay in the window.
    stale = {t.id for t in old if t.kind == "tool_result" and t.ref and not t.is_stub}
    old = [stub(t) if t.id in stale else t for t in old]  # stub(t) -> "[tool result -> ref]"
    ctx = ctx.replace(history=old + recent)
    if estimate_tokens(ctx) < budget:
        log_compaction(tier="clear", cleared=stale)
        return ctx

    # Tier 2: fold the previous summary forward together with the evicted turns.
    prior = [ctx.summary] if ctx.summary else []
    summary = summarise(prior + old, must_not_contradict=(ctx.task, ctx.state))  # extra model call
    log_compaction(tier="summarise", cleared=stale, evicted=[t.id for t in old], summary=summary)

    # ctx.task (static, cached prefix) and ctx.state (volatile, last) pass through verbatim.
    # Tier 3 is the caller's decision: if this is still over budget, start a fresh session.
    return ctx.replace(summary=summary, history=recent)

The function measures again after clearing, so the lossy step runs only when the cheap one wasn't enough. And the previous summary goes into the summariser with the evicted turns; without it, the second compaction would silently overwrite what the first one kept.

A bad summary fails silently, and the agent carries on with a wrong picture of the task, so log what each compaction removed and what the summary said.

7. Give the agent memory outside the window

External memory is the larger, slower tier behind the window: notes files, scratchpads and state that the agent writes, then reads back after a compaction or in a new session. The opening symptom, an agent re-reading files it has already opened, resembles thrashing: the working set doesn't fit, so the same data keeps getting paged back in. The fix is the cache-hierarchy one: write state back before you evict it, and keep a record of what has already been read.

Anything a program can track works better as structured state than as prose, because it can be validated, diffed and shown to a human reviewer:

migration-state.json
{
  "constraints": ["don't change the public API"],
  "plan_step": "update call sites",
  "files_migrated": ["src/routes/orders.ts", "src/routes/users.ts"],
  "files_remaining": ["src/routes/admin.ts"],
  "open_errors": ["users: token-expiry test fails after refresh"],
  "decisions": ["keep legacy middleware export until admin.ts is migrated"]
}

Anthropic's memory tool, now stable, is a client-side version of this: the model reads and writes files under /memories, and your application decides where they are stored.

Memory goes stale, bad tool output can poison it, and without scoping per task, user and tenant, one session's notes leak into another. Treat every write to memory as a correctness and security boundary, because the writer is a model that injected content can steer.

8. Sub-agents isolate context, and you pay for it

A sub-agent works like a function call with its own stack. The orchestrator delegates a bounded subtask, such as "find every call site of the old middleware and report path and line". The sub-agent explores in a clean window and returns a condensed result; its searches and file reads never reach the orchestrator's window.

The exploration stays in the sub-agent's window; only the result crosses back, at the cost of extra tokens.

The isolation has costs. Each sub-agent builds its own context, and Anthropic reports that its multi-agent systems use about 15× more tokens than chats. You need coordination logic, whatever the handoff leaves out is lost, and tracing a bad outcome now spans several windows.

Sub-agents fit parallel, exploration-heavy subtasks with a small result, like surveying call sites. They fit badly with tightly coupled sequential edits, where the handoff drops exactly the context the next step needs. AI agent architecture patterns covers when a multi-agent shape pays off.

9. Lay out the window so the cache can help

In Anthropic's prompt caching implementation, cache prefixes are created in a fixed order: tools, then system, then messages. A request can define up to 4 cache breakpoints.

That order is what matters for layout. Tool definitions open every prefix and history closes it, so I'd put what changes least at the front: a tool set fixed for the life of the task, a system prompt without timestamps or request IDs, then the static task block.

Here context engineering pulls against itself. Swapping tools in and out by hand edits the front of that order (tool search avoids this by appending discovered definitions inline in the conversation), and compaction rewrites the history inside it. So I'd compact in larger, less frequent steps rather than trimming a little every turn, and avoid editing the tool list mid-task. Each compaction loses more at once, but the window changes less often.

The static/volatile split decides where state goes. Open errors and decisions change every few steps, so they belong at the end, after everything meant to stay stable:

text
[tools]               fixed for the task, never reordered
[system]              no timestamps, no request IDs
[static task block]   goal, criteria, user constraints     <- breakpoint (rarely moves)
[compacted summary]   changes only at compaction           <- breakpoint
[recent turns]        incl. this step's file reads; stubs  <- breakpoint (moves forward)
[volatile state]      constraints restated, open errors, decisions; uncached

That layout uses three breakpoints and leaves one spare. Files and results for the current step arrive as tool results inside recent turns; leave them where they land, because moving them rewrites the history the cache depends on. Two things protect the API constraint: compaction keeps the input between the static block and the end short, and the volatile state block can restate the constraint at the end, the other position the positional study found favourable.

10. Choosing techniques without overbuilding

TechniqueProblem it solvesCostWhen to use
Tool consolidation and output trimmingWrong tool choice; raw output flooding historyDesign work per tool; parameter errors after merging; risk of trimming something neededAlmost always; start here
Reference-returning toolsLarge payloads that are rarely re-readExtra dereference calls; a store to run and expireLogs, files and query results the agent may revisit
Just-in-time retrievalPre-loaded material most steps never useMore calls and latency; blind to unknown unknownsLarge repos or corpora, with a small pre-loaded core
CompactionUnbounded history; buried constraintsExtra model call; lossy; fails silentlyTasks that routinely approach the budget
External memory and structured stateProgress lost across compactions or sessionsStaleness, poisoning, scoping, storageMulti-session or very long tasks with trackable progress
Sub-agentsExploration noise in the main windowMore total tokens; coordination; handoff loss; harder tracingParallel, exploration-heavy subtasks with small outputs
Cache-aware layoutReprocessing an unchanged prefix on every callFixed tool set; batched compaction; volatile state placed lastAny agent making many calls with the same prefix

Short tasks rarely need any of this: every technique adds code to test and debug, and summaries and memory can be wrong while the window looks tidy. A long-running agent also needs hard limits on steps and spend, whatever its context looks like.

I assume a single agent on tasks of tens of steps, with tools you control. Under that assumption I'd start with tool-output trimming and a pinned task block, because both are cheap, deterministic and high-leverage. Add compaction and external memory once tasks routinely hit the budget. Add sub-agents last, and only for parallel exploration: they're the most expensive way to buy a clean window.

11. Measure the window before you touch the prompt

Pick a real task your agent struggles with. Log what occupies its context at step 1, step 10 and step 30, by component: instructions, tool definitions, retrieved content, history and tool results. Don't change any prompt until you have that breakdown.

If tool output dominates, start with tool design and trimming. If history dominates, start with compaction. If the instructions are present but ignored, start with pinning and layout. Rewording the prompt is the last lever: the window is a budget, and the first job is finding out what you're spending it on.

View All Articles

Bishal SahaLet's build together

Have a system to design, or an AI feature to get right?

Tell me about the problem. You'll get a clear, honest view of the best way forward.

  • Reply within 24 hoursOn business days, with my honest view and a next step.
  • Accepting select engagementsArchitecture, AI features and full builds.
  • Remote, worldwideWorking with startups, SMEs and enterprises.