CONTENTS
CHAPTER 4

Context engineering

7 MIN READ

In June 2025, Shopify's CEO Tobi Lütke wrote that he preferred the term "context engineering" to "prompt engineering". Andrej Karpathy agreed a few days later, describing it as the "delicate art and science of filling the context window with just the right information for the next step." The new name stuck because it describes the actual job. The words of your instructions matter less than you'd think. What matters is the whole package the model sees at each step: instructions, examples, retrieved documents, tool definitions, tool results, history and memory.

The model knows nothing about your situation except what's in that window. Context engineering is the discipline of deciding what goes in it.

Context is a budget, not a bucket

Modern models accept hundreds of thousands of tokens, sometimes more. It's tempting to treat that as a bucket: throw everything in and let the model sort it out. The research says no.

Lost in the middle. Liu and colleagues (2023, published in TACL) put a relevant fact at different positions in a long context and asked models to use it. Performance was highest when the fact sat at the beginning or end, and dropped significantly when it was in the middle, even for models built for long contexts.

Context rot. In July 2025, Chroma's researchers tested 18 models, including GPT-4.1, Claude 4, Gemini 2.5 and Qwen3, on deliberately simple tasks while growing the input. Performance grew increasingly unreliable as input length grew. Adding even one distracting passage hurt. The less the relevant passage resembled the question, the faster quality fell.

Anthropic's "Effective context engineering for AI agents" (September 2025) gives the mechanism an intuitive frame: the model has an attention budget. Every token attends to every other token, so the number of relationships grows with the square of the length, and each additional token dilutes the attention available to the ones that matter. Their stated goal is "the smallest set of high-signal tokens" that gets the job done.

Key insight: A context window's advertised size is its capacity, not its sweet spot. Treat every token as a cost to quality as well as money, and earn its place.

How contexts fail

Drew Breunig's "How Long Contexts Fail" (June 2025) gives you names for the four failure modes you'll see in practice:

  • Context poisoning. A mistake (a hallucinated fact, a wrong tool result) enters the context and the model keeps building on it.
  • Context distraction. The history gets so long that the model leans on repeating past actions instead of reasoning fresh.
  • Context confusion. Irrelevant material, such as dozens of unused tool definitions, degrades the answer.
  • Context clash. New information contradicts something earlier in the context, and the model gets stuck between them.

Naming the failure is half the fix. When an agent goes off the rails, read the trace and ask which of the four happened.

Four moves: write, select, compress, isolate

Lance Martin's "Context Engineering for Agents" (June 2025) sorts the techniques into four strategies. They're a good checklist.

Write: save information outside the window. Give the model a scratchpad, a notes file or a memory store, so information survives without occupying the context. Anthropic calls this structured note-taking: an agent keeps a progress file or to-do list and reads it back when needed.

Select: pull in only what's relevant now. Retrieval (Chapter 5), choosing which tools to expose, picking which memories to load. Anthropic describes just-in-time context: instead of loading every document up front, give the agent lightweight references (file paths, queries, links) and tools to fetch what it needs. Coding agents work this way; they don't read the whole repo, they search it.

Compress: keep the meaning, drop the tokens. Summarize old turns when the conversation nears the limit (compaction), or simply clear old tool results that are no longer needed. The Manus team adds an important rule: make compression restorable. If you drop a web page's contents, keep its URL so the agent can fetch it again.

Isolate: split context across separate windows. Give a sub-task to a sub-agent with a clean context, and have it return only a condensed result. Anthropic reports sub-agents typically return summaries of 1,000–2,000 tokens after exploring far more. Chapter 8 covers the trade-offs, which are real.

Anatomy of a well-built context

Here's a layout that works for most assistants and agents. The order matters for two reasons you've already met: models attend best to the start and end, and providers can only cache a stable prefix.

┌──────────────────────────────────────────────┐
│ 1. System instructions (stable)              │ ◄─ cacheable prefix
│ 2. Tool definitions (stable)                 │
│ 3. Long-lived reference: policies, examples  │
├──────────────────────────────────────────────┤
│ 4. Session memory / user profile             │ ◄─ changes per user
│ 5. Conversation history (append-only)        │ ◄─ grows each turn
│ 6. Retrieved documents for this turn         │
│ 7. Current request + reminder of the goal    │ ◄─ end: strongest attention
└──────────────────────────────────────────────┘

Some guidance for each layer:

System instructions. Anthropic recommends writing them at the "right altitude": specific enough to guide behaviour, general enough not to be a brittle list of if-then rules. Describe the role, the goal, the constraints and the output format. Explain why a rule exists; models generalize better from reasons than from bare commands.

Examples. A few diverse, canonical examples beat a long list of edge cases. The Manus post warns about the opposite failure: if the context fills with many near-identical past actions, the model falls into a rut and imitates them. They add small structured variations to break the pattern.

History. Keep it append-only where you can (the next section explains why) and compact it deliberately rather than letting it truncate silently.

Retrieved documents. Label each with its source and date. Put them in clear delimiters. Put the question after them, not before.

The goal reminder. For long tasks, restate the objective near the end. Manus does this with recitation: their agent keeps a todo.md and rewrites it as it works, which pushes the plan into the most recent part of the context, where attention is strongest. A typical Manus task takes around 50 tool calls, long enough for the original goal to drift into the middle.

Concept deep dive: designing for the cache

The Manus team, in "Context Engineering for AI Agents: Lessons from Building Manus" (July 2025), calls the KV-cache hit rate "the single most important metric" for a production agent. Here's why that follows from Chapter 3.

An agent loop re-sends its whole context at every step, adding a little each time: the last action and its result. If the provider can reuse the cached KV for everything except the new bit, each step only pays full price for a few hundred tokens. If something near the start of the context changes, the cache misses from that point on, and you pay full price (and full prefill latency) for the entire history again.

They cite the numbers for one model at the time: cached input at $0.30 per million tokens versus $3 uncached, a 10× difference. With a 100:1 input-to-output ratio, the cache hit rate dominates the bill.

Their rules, all of which follow from "keep the prefix stable":

  1. No volatile data at the top. A timestamp to the second in the system prompt invalidates the cache on every call. Put dates at day granularity, or later in the context.
  2. Append, don't edit. Don't rewrite earlier messages or observations.
  3. Serialize deterministically. If your code emits JSON with keys in a random order, two identical states produce different tokens and the cache misses.
  4. Mask tools rather than removing them. Adding or removing tool definitions mid-task changes the prefix. Instead, keep all tools defined and restrict which ones the model may pick at this step (Manus does this by constraining decoding; with hosted APIs, a tool-choice setting or a validation layer can play a similar role).
  5. Keep errors in. When an action fails, leave the error and stack trace in the context. Seeing the failure helps the model avoid repeating it. Deleting it hides evidence and also edits the history.

Common confusion: "Context engineering is about writing a better system prompt." The system prompt is one layer of seven. In agents, most of the context is history and tool results, which your code decides how to record, trim and compress. Context engineering is mostly software engineering.

Memory

Anything that has to outlive one context window is memory. Lilian Weng's 2023 agent survey maps it onto human memory: short-term memory is what's in the context window; long-term memory is an external store the agent can read from and write to.

The MemGPT paper (Packer et al., 2023) took the operating-system analogy literally: treat the context window like RAM and external storage like disk, and let the model page information between them with function calls. You don't need that much machinery for most products, but the questions it raises are the right ones:

  • What gets written? User preferences, facts learned, decisions made, task progress.
  • When is it read? Always (a short profile in every prompt), on demand (a search tool), or by rule (load project notes when the project is opened).
  • How is it corrected? Memories go stale or are wrong. Users should be able to see and delete them, and newer facts should supersede older ones.
  • Whose is it? Memory must be scoped to a user or tenant. A retrieval bug that crosses that line is a data leak.

Start simple: a small structured profile and a notes file get you far. Add semantic search over memories only when you have too many to load.

Key takeaways

  • Longer contexts degrade quality (lost in the middle, context rot). Aim for the smallest set of high-signal tokens.
  • Learn the four failure modes: poisoning, distraction, confusion, clash.
  • Use Lance Martin's four moves: write, select, compress, isolate.
  • Order context for caching (stable first) and attention (goal and question last).
  • In agents, KV-cache hit rate is a first-class metric: keep prefixes stable, append-only, deterministic.
  • Memory needs rules for writing, reading, correcting and scoping.

Exercises

  1. Take a prompt you've written for a real feature. Rearrange it into the seven-layer layout. What moved? What would break the cache today?
  2. Read a long agent trace (yours or a public one). Find one instance of each of Breunig's four failure modes, or explain why it didn't occur.
  3. Design the memory for a personal fitness coach chatbot: what's written, when it's read, how it's corrected, and how it's scoped.