The harness Guide 08 of 25
Context engineering: deciding what the model sees
A model sees only what is in its context window. For an agent, your code rebuilds that window at every step, and choosing what goes in is where much of the real engineering happens.
Key takeaways
- Context engineering means choosing, at every model call, which instructions, tools, history, and data enter the window — not just how the prompt is worded.
- Bigger windows do not remove the problem: accuracy drops as inputs grow and when key facts sit mid-context, so less but sharper context usually wins.
- The core moves are a small stable prefix, retrieval by reference, pruning and compaction, notes kept outside the window, and sub-agents for isolation.
- Treat the context builder as code: log the exact window per call, budget tokens per component, and evaluate every change on long runs before shipping.
On this page 6 sections
In July 2025, Manus, which builds a general-purpose agent, reported that a typical task took about 50 tool calls, with roughly 100 input tokens for every token the model wrote. The model writes a little; your software decides what it reads, 50 times per task. A large language model (LLM) has no memory between calls, so that assembled input — instructions, tool definitions, history, and data — is everything it knows beyond its training.
That assembly step is where much of an agent’s quality is won or lost. When an agent forgets a constraint, repeats a failed step, or picks the wrong tool, teams tend to blame the model. Often the model did exactly what its context implied — the context was wrong, stale, or buried under pages of old tool output.
Context engineering is the practice of doing that assembly on purpose. This guide covers what the term means, why million-token windows have not made it obsolete, and the techniques that matter in production.
What is context engineering, and how is it different from prompt engineering?
Prompt engineering is about wording: how to phrase an instruction so the model follows it. Context engineering is about selection and order: which tokens belong in the window at this step, where they go, and what stays out. Anthropic’s Applied AI team calls it the natural next stage of prompt engineering, and frames the goal as identifying “the smallest possible set of high-signal tokens” for the outcome you want.
A helpful mental model comes from Google’s Agent Development Kit (ADK). Tech lead Hangfei Lin describes the context as a compiled view over a richer system. Session logs, long-term memory, and large files live in durable storage, and each model call gets a fresh view built just for it. The window is a working set, closer to a processor cache than a database.
The window has five tenants competing for one budget:
| Component | What it holds | Typical failure | Main lever |
|---|---|---|---|
| System prompt | Role, rules, house style | Stuffed with every edge case, or too vague to act on | Clear principles plus a few canonical examples |
| Tool definitions | Names, descriptions, parameters | Dozens of overlapping tools that blur the choice | Fewer, sharper tools; load rare ones on demand |
| Retrieved data | Documents, records, search hits | Near-misses that distract from the real answer | Fetch by reference when needed; rank and trim |
| History | Earlier turns and tool results | Raw output from 40 steps ago still taking space | Clear spent results; compact into summaries |
| Memory | Notes that outlive the window | A wrong note reread as fact for days | Write deliberately; date and revise entries |
Why doesn’t a bigger context window solve this?
By mid-2025, several leading models already accepted a million tokens or more, so including everything is tempting. The evidence says it is usually a mistake, for three reasons.
Accuracy falls as inputs grow
Models use long inputs unevenly. The 2023 “Lost in the Middle” study found accuracy highest when the useful passage came first or last and lowest in the middle. Chroma’s July 2025 context rot report found reliability slipping as inputs grew across 18 models, even on simple tasks. Our guide to tokens and context windows walks through that evidence, including a test where a short, focused prompt beat the full conversation history for every model family.
Anthropic traces part of this to how transformers work. Each token’s attention is spread across every token before it, so pairwise interactions grow with the square of input length. Training data also contains relatively few very long sequences. Whatever the full cause, the practical rule holds: a token that does not help the current step is not neutral, because it dilutes the ones that do.
Cost and latency scale with input
Agents read far more than they write, so the input side is the bill. At the Claude Sonnet prices Manus cited in July 2025, cached input cost $0.30 per million tokens against $3 uncached — a tenfold difference on the largest line item.
Latency follows the same curve. Every uncached input token must be processed before the first output token appears, so, as Google’s ADK team notes, time to first token climbs with context size. Across 50 steps, that wait adds up.
Tools crowd the window before work starts
Tool definitions are context too, and connecting a few Model Context Protocol (MCP) servers can add tens of thousands of tokens before the conversation begins; our guide to tool use has the numbers. In November 2025, Anthropic shipped tool search as its fix: the model searches the tool library and loads only the definitions it needs. That guide also covers other providers’ support and the remaining techniques for large tool libraries.
Five techniques that decide what the model sees
Vendors slice these differently, but they reduce to five decisions you make for every agent.
1. Keep a small, stable prefix
Put what never changes first — system prompt, tool definitions, fixed reference text — and keep it byte-identical across calls. Providers can reuse the attention keys and values already computed for a recently seen prefix (the key-value, or KV, cache), so a stable start is cheaper and faster. Change one early token and everything after it must be recomputed.
Manus calls cache hit rate its most important production metric. It lists the usual ways teams break it: a timestamp at the top of the system prompt, serialization with unstable key order, and adding or removing tools mid-task. Its alternative to removing tools is to leave the definitions in place and restrict which ones the model may choose while decoding.
Lean matters as much as stable. Anthropic advises pitching the system prompt at the right altitude: specific enough to steer behavior, general enough to avoid a brittle wall of if-then rules. A handful of varied, representative examples usually teaches more than a page of edge cases.
2. Retrieve just in time, by reference
Instead of preloading every document the agent might need, hand it lightweight pointers — file paths, record numbers, saved queries — and tools to open them. Claude Code mixes up-front and on-demand loading, as Anthropic explains: project instruction files load up front, and search commands pull in source files only when needed. Google’s ADK keeps large payloads as artifacts referenced by name, loaded into one call and then dropped.
In February 2026, OpenAI described applying the same idea to instructions: while building an internal product with no hand-written code, its engineers found one giant AGENTS.md backfired. That file, which coding agents read before starting work, crowded out the task, and its rules went stale. They replaced it with a map of about 100 lines that points into a structured docs folder. The trade-off is speed: exploring at runtime takes more steps than reading a precomputed answer, so keep hot, stable facts in the prefix and fetch the long tail.
3. Prune and compact the history
Tool output is often the fastest-growing part of an agent’s context and usually the least useful once consumed. The lightest fix is clearing old tool results while leaving a stub that says the call happened. Clearing edits earlier history, which invalidates the cache from that point, so clear in batches rather than every turn. The heavier fix is compaction: near a token threshold, the model summarizes older history — decisions made, open problems, the current plan — and continues from that summary plus recent turns.
As of October 2026, compaction is built into some agent frameworks, such as Google’s ADK, and some model application programming interfaces (APIs). OpenAI’s Responses API, for instance, can compact automatically past a threshold you set, carrying state forward in an opaque, encrypted item, or on request through a separate endpoint. The risk is the same everywhere: an overeager summary can drop a detail whose importance only shows up later. Manus’s guard is to compress restorably, dropping a web page’s text but keeping its address so the agent can fetch it again.
Manus also keeps failed actions and error messages in the history, because a visible mistake helps the model avoid repeating it. Prune what is spent, not what is instructive.
4. Write state outside the window
Long tasks need memory that survives pruning, and the simplest version is a file the agent maintains: a plan, a to-do list, notes on what has been tried. Manus has its agent rewrite a todo.md file as it works, which also keeps restating the current goal at the end of the context, away from the neglected middle. Anthropic’s Pokémon-playing agent kept running tallies over thousands of steps. Treat these notes as data with a shelf life: a wrong note persists and gets reread, so date entries and let the agent revise them.
5. Isolate heavy work in sub-agents
When a subtask needs wide exploration, such as reading a codebase or searching the web, run it in a sub-agent with a clean window and have it return only a summary. Anthropic reports those summaries are often 1,000–2,000 tokens, even when the sub-agent burned through tens of thousands. Google’s ADK makes the scope explicit: an agent called as a tool sees only its instructions and needed artifacts, while a full handoff can pass along the caller’s history. The price is more total tokens, plus sub-agents that may make conflicting assumptions because they never saw each other’s work.
What a context builder looks like in code
All five techniques meet in one function your harness runs before every model call. A simplified sketch:
def build_context(task, session, memory, budget):
if session.token_count() > 0.8 * budget:
# Summarize old turns; clear spent tool output.
session.compact()
# Stable prefix, byte-identical on every call.
ctx = [SYSTEM_PROMPT, TOOL_DEFINITIONS]
# Changes only when compaction runs.
ctx += [session.summary]
# Append-only between compactions.
ctx += session.turns_since_summary()
# Per-step picks go after the cached part.
ctx += memory.search(task.goal, top_k=5)
# Names and paths, not file contents.
ctx += [ref(a) for a in session.artifacts]
# Live plan last: recent and hard to miss.
ctx += [session.plan]
# You cannot debug a window you never saw.
log_context(task.id, ctx)
return ctx
Order matters as much as contents. Stable material goes first so the cache holds; volatile, per-step material goes last, where it stays recent and changing it invalidates nothing cached before it.
How do you know your context is working?
Measure it like any other component. Four habits catch most problems early.
- Log the assembled window for every call. When an agent misbehaves, the first question is what it actually saw.
- Track tokens by component. Break each call into prefix, history, retrieval, and tool output, and watch cache hit rate and cost per completed task, not just per call.
- Run ablations. Shrink or remove one component and rerun your evaluation set. Given the context rot findings, do not be surprised when the shorter version scores higher.
- Test long runs on purpose. Check quality at step 5, step 40, and just after a compaction. Many context bugs only appear deep into a task.
What this means for your team
Make the context builder a first-class module with an owner, version history, and tests, reviewed with the same care as a public API. Prompts get attention in code review; the logic that decides what surrounds them often does not, and that is where agents quietly degrade.
Practical defaults that hold up:
- Budget per component. Decide how many tokens the prefix, history, retrieval, and tools may each use, and alert when one grows unexpectedly.
- Reach for retrieval before a bigger window. Feeding a 1-million-token model 900,000 tokens of loosely relevant text is usually worse, and always costlier, than giving the same model a tight, well-chosen slice.
- Audit your tools. Use Anthropic’s test: if an engineer cannot say which tool fits a situation, the model is unlikely to do better. Merge overlaps and load rarely used tools on demand.
- Protect the cache. No timestamps, request numbers, or shuffled keys in the prefix; keep history append-only between compactions.
- Tune compaction for recall first. As Anthropic suggests, start with a summary instruction that captures everything that might matter — identifiers, decisions, user constraints, open questions — then trim for brevity.
The common pitfalls are summary drift, where each compaction loses a little more; memory that hardens a past mistake into a rule; and over-isolated sub-agents that duplicate work. None is fatal if you log, measure, and review. In the agents and knowledge assistants SurgeX Labs builds, the context builder is the first module we instrument, because an agent that degrades on step 40 usually started reading the wrong tokens on step 10.
Sources
-
Effective context engineering for AI agents (opens in new tab) — Anthropic, 2025 anthropic.com
-
Lost in the Middle: How Language Models Use Long Contexts (opens in new tab) — Stanford University, UC Berkeley and Samaya AI (arXiv), 2023 arxiv.org
-
Context Rot: How Increasing Input Tokens Impacts LLM Performance (opens in new tab) — Chroma, 2025 trychroma.com
-
Context Engineering for AI Agents: Lessons from Building Manus (opens in new tab) — Manus, 2025 manus.im
-
Architecting efficient context-aware multi-agent framework for production (opens in new tab) — Google Developers Blog, 2025 developers.googleblog.com
-
Introducing advanced tool use on the Claude Developer Platform (opens in new tab) — Anthropic, 2025 anthropic.com
-
Harness engineering: leveraging Codex in an agent-first world (opens in new tab) — OpenAI, 2026 openai.com
-
Compaction (API guide) (opens in new tab) — OpenAI, 2026 developers.openai.com
Where this shows up in our work
- Solution blueprint Your knowledge, answering with citations — RAG knowledge assistant with citations
- Solution blueprint First drafts for every ticket — AI support copilot inside your helpdesk