Part 2: Building blocks

Context engineering and memory

Treat the context window as a budget, and spend it on the few tokens that change the answer

BuilderSoloClaude9 min read

In short

Spend the context window like a budget: stable prefix first, a few labeled sources, and nothing the user may not see.

Key ideas

  • Context rot: more tokens can lower quality
  • Stable prefix, volatile tail: better attention and cache hits
  • Filter retrieval by permissions before ranking; memory needs write, read and deletion policies

A summary only. The reasoning, examples, checklist and what to do on Monday are in the chapter. Read it in the book

4

max cache breakpoints per request (Anthropic)

70%

of history allowance: illustrative compaction trigger

Inside the chapter

  1. 1Context is the scarce resource
  2. 2What goes in, and in what order
  3. 3Prompt caching shapes the design
  4. 4RAG in an agent world
  5. 5Compaction, notes and long-term memory
  6. 6Composite case: the internal RAG assistant

Try it: context window budget

Give each block an allowance and watch the total against the window.

Tokens used

78,000

Window used

39%

Headroom

122,000

Within budget

Headroom left for output and reasoning. Log tokens per block on every turn.

Illustrative: the 70% compaction line is a rule of thumb, not a standard.

Go further: free on this site

Questions readers asked about this chapter, a 5-question self-check with explanations, and every source it cites.

Questions readers ask (3)

3 questions. Open one to read the answer.

Does the ordering and caching advice apply to other providers?

Yes: the main prefix caches all reuse an exact prefix. OpenAI's caching is on by default for supported models, needs the whole rendered prefix to match, and has a 1,024-token minimum on GPT-5.6 and later (OpenAI docs). TTLs and breakpoint rules differ and change often (as of late 2026). Keep the design rule (stable prefix, volatile tail, sorted tools) and measure hit rate per provider; one badly ordered adapter cancels the savings.

Can a shared cached prefix leak data between tenants?

The provider cache is not the main risk: OpenAI states caches are not shared across organizations (OpenAI docs). Your design is. Never put tenant or user data in the shared prefix. And a home-built answer cache keyed only on question text will serve tenant A's answer to tenant B: include tenant id and permission scope in every key, or do not cache retrieval-based answers.

How do we carry out an erasure request across an agent's stores?

Keep a data map per agent listing every store that holds user data, make each one deletable by user id, and let the index follow the source system instead of deleting chunks by hand. Short trace retention shrinks the job. Confirm the list with your DPO (Chapter 12).

Answered in the book, not repeated here: See Chapter 5, What goes in, and in what order; See Chapter 5, Compaction, notes and long-term memory; See Chapter 5, Hybrid search, reranking, freshness

Self-check (5)

Score: 0 / 5 (0 answered)

  1. Question 1 of 5

    A teammate adds the current date and time, to the second, at the top of the system prompt so the model knows what day it is. What is the most likely production effect?

    Show the answer

    Answer: C.

    Caches reuse an exact prefix, so a value that changes on every call at the top invalidates everything behind it. The API returns no error; the cost rises silently, which is why the chapter recommends a cache-hit-rate alert.

  2. Question 2 of 5

    Your assistant answers with last year's rule although the current rule was also retrieved. What is the best first fix?

    Show the answer

    Answer: A.

    The model had both rules and no way to tell which one won; dated envelopes plus an explicit conflict rule fixed the opening story. More chunks or a bigger window add context rot, and an instruction without dates gives the model nothing to act on.

  3. Question 3 of 5

    An internal assistant indexes wikis with mixed access rights. Which control actually prevents a user from seeing a restricted page in an answer?

    Show the answer

    Answer: D.

    Access must be enforced in code before tokens reach the model; ACLs synced from the source and applied at retrieval do that. Prompt rules are a hope, and hiding citations still lets restricted content shape the answer.

  4. Question 4 of 5

    Your retrieval eval shows recall at 50 of 95%, but the right chunk is in the final top 5 only 60% of the time. Where should you work first?

    Show the answer

    Answer: B.

    High first-stage recall means the chunk comes back; losing it before the final top few is a precision problem, which the reranker and filters own. Chunking fixes low recall, and the generating model is not involved in either metric.

  5. Question 5 of 5

    What is the safest default write policy for a long-term memory store?

    Show the answer

    Answer: C.

    Memories written from untrusted content become persistent prompt injection (OWASP ASI06), so confirmed facts with provenance are the default. Refusing memory outright is a product choice, not a write policy, and saving everything creates a data-protection problem.

Sources

Sources cited

  • Anthropic, Effective context engineering for AI agents, September 2025. anthropic.com
  • Google, Introducing Gemini 4 Hydrogen, November 2026. blog.google
  • Arize AI (Aryan Kargwal), Why AI Agents Break: A Field Analysis of Production Failures, January 2026. arize.com
  • Anthropic, Prompt caching (Claude Platform documentation), accessed November 2026. platform.claude.com
  • Model Context Protocol, Specification 2026-07-28: changelog, July 2026. modelcontextprotocol.io
  • OpenTelemetry, Semantic conventions for GenAI agent and framework spans (status: Development), accessed November 2026. github.com
  • pgvector, pgvector: Open-source vector similarity search for Postgres (GitHub repository), accessed November 2026. github.com
  • LangChain, LangChain and LangGraph Agent Frameworks Reach v1.0 Milestones, October 2025. langchain.com
  • OpenAI, A framework for reporting model misalignment, September 2026 (2026-09-16 entry). openai.com
  • OpenAI, GPT-6 Astra: A new generation of intelligence, September 2026. openai.com
  • Google Cloud, Introducing Gemini Enterprise Agent Platform, powering the next wave of agents, April 2026. cloud.google.com
  • AWS, Amazon Bedrock AgentCore is now generally available, October 2025. aws.amazon.com
  • Anthropic, Using agent memory (Managed Agents documentation, beta), accessed November 2026. platform.claude.com
  • Microsoft Foundry Blog, Foundry Agent Service at Build 2026, June 2026. devblogs.microsoft.com
  • Anthropic, The components of agent memory, November 2026 (2026-11-06 entry). anthropic.com
  • European Union, Regulation (EU) 2016/679 (General Data Protection Regulation), Article 17, April 2016. eur-lex.europa.eu

Further reading

  • Chroma (Kelly Hong, Anton Troynikov, Jeff Huber), Context Rot: How Increasing Input Tokens Impacts LLM Performance, July 2025. trychroma.com
  • Nelson F. Liu et al., Lost in the Middle: How Language Models Use Long Contexts, July 2023. arxiv.org
  • Yichao "Peak" Ji, Context Engineering for AI Agents: Lessons from Building Manus, July 2025. manus.im
  • Anthropic, Introducing Contextual Retrieval, September 2024. anthropic.com