Context Engineering
Learning objectives
By the end of this chapter, you will be able to:
- Explain why context engineering is a distinct concept from prompt engineering, using the attention-budget and context-rot framing.
- Describe the four Claude Code context strategies — Write, Select, Compress, Isolate — and give one concrete mechanism for each.
- Identify the three failure modes of unmanaged context: poisoning, confusion, and clash.
- Distinguish project memory, user memory, and dynamic memory imports in Claude Code.
- Map the book's slash commands (/clear, /compact) to the underlying Anthropic API primitives (clearing, compaction, memory) and pick the right one for a given workload.
- Evaluate a system prompt against the Goldilocks zone and explain whether it is too specific, too vague, or balanced.
Before we start — agent, prompt, and context in plain language
If you're already comfortable with what AI agents, prompts, and context windows are, skim this and move on. If you're not, read it before anything else in the chapter — every section below assumes these three ideas.
An LLM (large language model) is software that takes text in and produces text out. Claude, GPT, Gemini, Llama — all LLMs. They don't act on their own; they answer a question and stop.
A prompt is the text you send to the LLM. The simplest case is a single question. The LLM produces a single answer and stops.
An AI agent is an LLM wrapped in extra software that lets it do more than answer once. The wrapping software (the book calls it an agent harness) can:
- send the LLM extra instructions before the user's question (a system prompt)
- give the LLM tools it can call — read a file, search the web, run code
- read each tool's results back to the LLM and ask, "what next?"
- repeat — until the task is done
Claude Code is an agent. You ask "fix this bug," and Claude reads files, runs tests, writes code, re-runs tests — in a loop — until the bug is fixed.
Context is everything the LLM can see at the moment it's about to answer. That includes:
- the system prompt (instructions the harness added on your behalf)
- the conversation so far (your messages and the LLM's previous answers)
- the results of every tool call the agent made
- any extra files or notes the harness injected (
CLAUDE.md, project memory)
The LLM has a context window — a hard cap on how much of all that it can see at once. Today's biggest models hold roughly a short novel's worth. Past that limit, older material has to be dropped, summarized, or paged out somehow.
Why this chapter exists. In a real agent, that context window fills up fast. The whole job of context engineering — this chapter's topic — is deciding what goes into the window, what comes out, and when.
How to read this chapter. Each section ends with an > Analogy — ... box that restates the idea in plain language. Skim them or lean on them as you like.
Why this chapter matters
Most production agent failures are not model failures. They are context failures — the wrong information, the wrong tools, or too much of either reaches the model. This chapter gives you a shared mental model and vocabulary you will use for the rest of the course.
Lesson
1. From prompt engineering to context engineering
A prompt is static. Context is dynamic — it changes every turn as users interact, tools execute, and prior decisions accumulate. Static prompts cannot keep up with dynamic context, which is why the field shifted from prompt engineering to context engineering.
The orchestration layer around the LLM has a name: the agent harness. The harness manages tool calls, controls the agent loop, handles errors, enforces guardrails, and — most importantly — decides what context is sent to the model at each step.
Analogy — recipe card vs. running a kitchen A prompt is a recipe card: it tells the cook what to make. Prompt engineering is making the recipe card clearer. Context engineering is everything else that happens in the kitchen — what's already on the counter, what's in the fridge, what the sous-chef did an hour ago, whether the oven is clean. The recipe matters. But a kitchen that runs well is what wins the night.
2. Where context comes from, and why it grows
Context arrives from several places:
- the developer (system prompts, tool schemas, scaffolding)
- the user (the immediate request, files, references)
- previous interactions (tool outputs, prior turns, retrieved data)
On long-running tool-using tasks, every tool result is appended to the context window. The window keeps growing, which causes:
- exceeding the context window size limit
- rising cost and latency
- gradual performance degradation
Anthropic frames this same problem with two complementary terms. The first is attention budget: like humans with limited working memory, LLMs have a finite capacity for processing context, and "every new token introduced depletes this budget by some amount." The second is context rot — the gradual loss of recall accuracy as the window fills, observable well before any hard size limit is hit.
Out of that framing falls the single sentence most worth memorizing from Anthropic's guidance: "Good context engineering means finding the smallest possible set of high-signal tokens." Treat context as precious, not free.
Analogy — the desk that won't stop filling with paper Picture a desk. Every meeting, someone drops a stack of paper on it. By 3pm the desk is buried, you can't find the contract you actually need, and you start making mistakes. The fix isn't a bigger desk. The fix is filing — deciding what stays out, what goes in a drawer, and what goes in the bin. The context window is that desk.
3. Three ways unmanaged context fails
| Failure mode | What happens |
|---|---|
| Context poisoning | A hallucination from a tool call or model output enters context and corrupts future outputs. |
| Context confusion | Irrelevant context influences the response even though it has nothing to do with the task. |
| Context clash | Different parts of the context contradict each other. |
Anthropic groups these three failures together with the gradual recall degradation under the broader heading of context rot. The important corollary: "context windows of all sizes will be subject to context pollution and relevance concerns" — including the 1M-token windows now available on the newest models. The fix is curation, not capacity.
Analogy — the rumor, the loud neighbor, and the two bosses Poisoning is a false rumor someone whispered at the morning standup. By afternoon everyone in the office is repeating it as fact, and nobody can remember who said it first. Confusion is the loud neighbor at the next desk talking about their fantasy football team while you're trying to write a contract — it has nothing to do with your work, but it bends your focus and slows your writing. Clash is when your two managers send you opposite instructions in the same week and you freeze, because doing either one upsets the other.
4. The four Claude Code strategies
| Strategy | Idea | Concrete mechanism in Claude Code |
|---|---|---|
| Write | Persist context across sessions | ./CLAUDE.md (project), ~/.claude/CLAUDE.md (user), @file imports |
| Select | Pull only what is relevant | Folder discovery, parent-folder walk-up, ask Claude to remember (auto-memory) or to add a line to CLAUDE.md, tool-specific context |
| Compress | Keep the context window healthy | /clear (wipe conversation, keep memory), /compact (summarize) |
| Isolate | Scope context per task | Sub-agents with their own isolated context window |
Analogy — running a restaurant kitchen Think of an agent's working day as a long restaurant shift. The four strategies are how a good kitchen survives it: post the standing notes on the fridge so every cook reads them (Write), keep only what tonight's menu needs on the prep counter (Select), wipe the counter when it's piled up (Compress), and put each specialty on its own station so the grill cook isn't trying to plate desserts too (Isolate). The same kitchen image carries through the next four sub-sections.
Write — the three memory tiers
- Project memory
./CLAUDE.md— team-shared, version-controlled, scoped to the repo. - User memory
~/.claude/CLAUDE.md— personal preferences across all projects, not committed. - Dynamic imports —
@path/to/file.mdlets aCLAUDE.mdpull in other memory files.
Dynamic, hook-driven context (e.g. a UserPromptSubmit hook that appends branch- or query-specific imports) is powerful, but must be idempotent: an unguarded >> will fill CLAUDE.md with duplicates. The book's pattern uses grep -qxF to check before appending.
Anthropic calls this broader pattern structured note-taking (or agentic memory): the agent regularly writes notes that persist outside the context window, then reads them back on demand. Their most vivid example is Claude playing Pokémon — across thousands of game steps, Claude maintains a precise tally ("for the last 1,234 steps I've been training my Pokémon in Route 1, Pikachu has gained 8 levels toward the target of 10"), keeps maps of explored regions, and tracks combat strategy. The note file is what gives multi-hour continuity even when the conversation context resets.
The same pattern shows up in coding work. CLAUDE.md is the "note the agent always reads first." And the file system itself — filenames, folder hierarchies, timestamps — is implicit memory the agent can consult without reading any file: test_utils.py inside tests/ versus inside src/core_logic/ means different things, and that signal is free.
Analogy — sticky notes on the fridge, the notebook in your back pocketCLAUDE.md(project memory) is the sticky note on the office fridge that the whole team reads every morning: "we ship from main; never push on Friday after 4pm."~/.claude/CLAUDE.md(user memory) is the notebook in your back pocket — your personal shortcuts that nobody else needs to see. Dynamic@imports are like saying "see the orientation packet" instead of taping the whole packet to the fridge.
Select — discovery and /memory
Claude Code walks folders looking for context, prefers the most specific file available, and prioritizes recently and frequently used context. To push a new fact in mid-session, you have two documented options: (1) ask Claude in natural language to "remember X" — Claude saves it to auto-memory (Claude-written notes, scoped per repository, kept under ~/.claude/projects/<project>/memory/); or (2) ask Claude to "add this to CLAUDE.md" (or open /memory to edit the file yourself), which puts the rule into the version-controlled project memory. The /memory command opens the editor and lets you inspect every memory file currently loaded.
Tool-specific context is also injected automatically. When the edit tool is about to run, Claude is reminded to check existing code style and look for existing functions. When the bash tool is about to run, it is reminded to prefer an existing npm script and verify file paths.
Anthropic separates retrieval into three styles, and Claude Code uses all three:
- Just-in-time retrieval — the agent holds only lightweight identifiers (file paths, URLs, queries) and dereferences them with tools at runtime. Claude Code's
globandgrep, plus piping large files throughhead/tailto inspect them without loading the whole thing into context, are the canonical examples. - Pre-inference retrieval — embedding-based RAG that surfaces context before the model runs.
- Hybrid retrieval — pre-compute a small upfront set for speed, then let the agent explore further on its own. Claude Code is hybrid by default: it drops
CLAUDE.mdin upfront, then uses tools to navigate at runtime.
The reusable heuristic: "progressive disclosure allows agents to incrementally discover relevant context through exploration." Don't put everything in the context window — put pointers to it, plus tools that can dereference them.
Anthropic also flags tool design itself as part of context engineering. Three principles they call out:
- Tools should be self-contained, robust to error, and clear about their intended use.
- Parameters should be descriptive and unambiguous. Play to the model's strengths — natural-language names beat opaque IDs.
- Minimize overlap between tools. Their gut-check: "if humans can't definitively say which tool to use, agents can't do better." Bloated tool sets with overlapping responsibilities cause the agent to dither at the decision point.
Analogy — what the sous-chef actually brings out A good sous-chef doesn't dump the entire pantry on the counter when you ask for risotto. They bring the rice, the stock, the parmesan, the onion — and they leave the cinnamon and the canned beans on the shelf. Selecting context is the same: bring what the next move needs, leave the rest on the shelf where the agent can fetch it later if it actually needs to.
Compress — /clear vs /compact
/clear— wipe the conversation, keep memory. Good when the conversation has gone the wrong direction./compact— summarize the conversation into a shorter form, preserving key decisions. Reduces cost and latency without losing the thread.
What the book shows as two slash commands is a user-facing surface on a richer set of platform primitives. The Anthropic API exposes three of them directly, and they compose:
| Primitive | Scope | Cost | When to reach for it |
|---|---|---|---|
Compaction (compact_20260112) | Whole transcript — user messages, assistant messages, tool calls and results | Inference cost (the model writes the summary) | Long conversations where the agent's own reasoning has accumulated |
Tool-result clearing (clear_tool_uses_20250919) | Just the old tool_result blocks; the tool_use record stays | None — mechanical edit, no inference | Re-fetchable tool outputs (file reads, API queries) |
Memory (memory_20250818) | Cross-session, external file storage | None (client-side) | Knowledge that must survive between sessions |
The cookbook's research-agent experiment makes two findings worth internalizing:
- Compaction preserves high-level facts and drops obscure specifics. In their run, lifespan figures and organism names survived the summary; appendix-table heterogeneity statistics did not (3/3 high-level facts recalled, 0/3 obscure specifics). If a fact is essential, say so in the compaction
instructionsparameter — otherwise the default summarizer is allowed to drop it. - Tool-result clearing is the cheapest compaction you can do. Anthropic describes it as one of the "safest, lightest-touch" options: drop old re-fetchable results, keep the record that the call happened. The agent can re-call the tool if it needs the result again.
Analogy — the end-of-prep cleanup Halfway through service, the prep counter is chaos: cutting boards everywhere, half-empty stock pots, scraps. Two options. Scrape everything off and start fresh — that's/clear. Or take what's still useful and pack it into one labeled container so you can keep working without the mess — that's/compact. Tool-result clearing is the bus-tub variant: throw the dirty plates in the bus tub but keep the ticket that says who ordered what.
Isolate — sub-agents
Sub-agents run in their own isolated context window and do not inherit the main agent's full history. The model behaves better when each specialist sees only what its task needs: a code-review agent sees a PR and a security focus; a research agent sees a research question. The book notes that the Task(...) snippet in the chapter is illustrative — real sub-agent definitions use YAML frontmatter, covered later.
Anthropic frames sub-agents as one of three core long-horizon techniques, alongside compaction and structured note-taking: "specialized agents handle focused tasks with clean context windows; the main agent coordinates the high-level plan." The book's intuition — that without isolation, Claude tries to do everything at once — matches Anthropic's own framing exactly. The two views are the same idea at two altitudes.
Analogy — stations in a restaurant kitchen A real kitchen doesn't have one cook trying to grill, fry, plate desserts, and answer the phone. It has stations — grill, sauté, garde manger, pastry — each with its own counter and only the tools that station needs. The sub-agents are stations. The main agent is the head chef walking between them with the ticket, deciding who cooks what next.
5. System prompts and the Goldilocks zone
System prompts still matter, and they should land in the Goldilocks zone — not too rigid, not too vague.
- Too specific treats the LLM as a deterministic state machine. Hardcoded numbers ("ask three follow-up questions"), exhaustive enumeration of edge cases, and rigid branching all break the moment the world doesn't match the script.
- Too vague ("solve the issue in line with the brand's principles, escalate if needed") gives no actionable signal. The model assumes shared context that it doesn't have, and behavior varies wildly between runs.
- Just right establishes a clear identity and scope, empowers the agent with a goal rather than a script, gives it a reusable reasoning framework (identify → gather → resolve → confirm), and states a small number of crisp principles ("choose the simplest solution that fully addresses the issue").
Good system prompts compress general principles. Bad ones either over-specify procedure or leave the model to guess what "good" means.
Beyond hitting the Goldilocks zone, Anthropic gives two concrete structural recommendations for system prompts:
- Organize sections explicitly. Use Markdown headers or XML tags —
<background_information>,<instructions>,## Tool guidance— so the model can tell sections apart. Stream-of-consciousness prompts hide their own structure. - Use diverse, canonical examples rather than exhaustive edge cases. Their phrasing: "Examples are the pictures worth a thousand words for an LLM." A handful of well-chosen examples teaches a principle better than a laundry list of rules.
The unifying heuristic from their conclusion: "Do the simplest thing that works." Start with a minimal prompt and the best available model, then add instructions or examples only when you observe a specific failure mode — not preemptively.
Analogy — three styles of GPS directions Too vague: "head somewhere north." Too specific: "in 0.3 miles change to the right-most lane, then in 0.4 miles ease left, then in 0.7 miles…" (4,000 more steps). Just right: "take I-5 north, exit at Bell Street, the diner is on your right after the second light." The model is the driver. A good system prompt is the third one — enough to find the place, not so much that the driver tunes out.
6. From slash commands to platform primitives
This section is not from the book. It bridges the chapter's user-facing view (/clear, /compact, CLAUDE.md) to the platform-level reality that Claude Code is built on — useful whenever you start integrating Claude Code patterns into your own agentic apps.
The cookbook ends with diagnostic mapping: given a real workload, which primitive should you reach for?
| Workload characteristic | Underlying problem | Primary tool |
|---|---|---|
| Long dialogue, agent reasoning accumulates | Context rot in reasoning | Compaction |
| Many tool calls with large re-fetchable results | Bloated tool results dominate the window | Tool-result clearing |
| Knowledge needed across sessions | Cross-session amnesia | Memory |
| Re-readable tool outputs (files, APIs) | Unnecessary bulk from tool payloads | Clearing (agent can re-call) |
| Single-session reasoning task | Agent's own thinking matters most | Compaction |
| Multi-session learning task | Building knowledge over time | Memory |
When you use more than one primitive, Anthropic recommends an order:
- Clearing first — cheap, no inference cost; drops old re-fetchable tool results.
- Compaction second — moderate cost; handles accumulated reasoning.
- Memory third — persistent across sessions.
If you enable both clearing and memory, exclude the memory tool from clearing (exclude_tools=["memory"]) so memory operations are not stripped out from under the agent.
The takeaway for this course: the book's four strategies (Write / Select / Compress / Isolate) and the cookbook's three primitives (Memory / Clearing / Compaction) are not different theories. They are the same idea at two altitudes — the book teaches the vocabulary, the cookbook ships the knobs.
Analogy — dashboard vs. the engine The slash commands (/clear,/compact) are the dashboard knobs in your car: the steering wheel, the gear shift, the cruise control. Easy to use and they cover 95% of driving. The platform primitives (compaction, tool-result clearing, memory) are the engine systems those knobs are wired to. You don't need to know the engine to drive. But if you're building cars — writing your own agent on top of the API — you need to know both.
The whole chapter in one image — the long-shift chef
Analogy — pedagogical summary, drawing on all six sections
Run an agent the way a good chef runs a long shift.
The recipe (the prompt) tells you what to cook. But the night is won by what surrounds the recipe.
There are standing notes on the fridge that every cook reads before they tie an apron — kitchen rules, allergen sheet, who's expediting tonight. That's CLAUDE.md. Each cook also carries their own pocket notebook for personal shortcuts. That's user memory.
The sous-chef is selective. When the ticket says risotto, they bring the rice, the stock, the parmesan — and they leave the cinnamon on the shelf. They don't dump the pantry on the counter "just in case." That's just-in-time retrieval.
The prep counter fills up. Every dish leaves boards, scraps, half-pots behind. By the rush, the counter is buried and the next cook can't find the chinois. So you compress: bus the dirty plates, pack the still-useful prep into a single labeled container, and keep going. That's /compact and tool-result clearing.
The kitchen has stations. The grill cook doesn't try to plate desserts. The pastry chef doesn't sear steaks. Each station has its own counter, its own tools, its own focus — and the head chef walks between them with the ticket. That's sub-agents.
And the head chef's instructions to each station hit the Goldilocks zone. Not "go cook somewhere." Not a 200-page manual covering every possible substitution. Something in the middle: here's what good plating looks like; if something looks wrong, fix it; here are the three things we never compromise on. Principles, not scripts.
That's context engineering. The recipe matters — but the kitchen is what ships dinner.
Activity — Audit one of your own prompts
Pick a system prompt or CLAUDE.md you have written (or a public one from a repo you trust). Spend ten minutes:
- Mark each line as identity/scope, framework, principle/heuristic, hardcoded rule, or vague aspiration.
- Count how many lines fall into "hardcoded rule" and "vague aspiration."
- Pick the worst offender from each category and rewrite it as a principle or as part of a reasoning framework.
- Note one place where you would add a tool-specific reminder (e.g. "before running bash, prefer an existing npm script").
Capture your before/after in a comment or note — refining prompts this way is a habit you'll keep using throughout the book.
Stretch task (enrichment)
Pick one agent or workflow you are already building. Use the diagnostic table from §6 to decide which platform primitive — compaction, tool-result clearing, or memory — would address its biggest context-window problem first. Write two sentences: what the problem is, and which primitive you would try first and why.
Practical exercise — Drive context engineering in Claude Code
~30–45 minutes. Hands-on follow-up to the lesson. Prerequisites: Claude Code installed and authenticated, a terminal, and a text editor. You'll work in a throwaway scratch folder — nothing in this exercise touches the training repo or any real project of yours.
You've read the theory. Now drive each of the four strategies (Write / Select / Compress / Isolate) and the Goldilocks zone in a real Claude Code session. You'll set up a tiny sandbox project, watch context shape Claude's behavior, fill the context window, compress it, run a sub-agent in an isolated window, and iterate a sub-agent's system prompt from too vague into the Goldilocks zone.
Setup (5 min)
Create a scratch directory and the seed files. Run:
mkdir -p ~/cct-exercise/archive
cd ~/cct-exercise
Create notes.md:
# Project Notes
## TODOs
- [ ] Add input validation to /signup
- [ ] Migrate analytics to v2
- [ ] Refactor billing module
- [ ] Document deploy process
Create bug-report.md:
# Bug Report: BR-2026-014
**Severity:** Medium
**Reporter:** Sam
**Date:** 2026-06-01
## Description
When a user submits the /signup form with an email that already exists, the server returns a 500 error instead of a 409 Conflict. The user sees a generic "Something went wrong" message.
## Steps to reproduce
1. Sign up with email [email protected].
2. Open a new browser session.
3. Sign up again with [email protected].
## Expected
HTTP 409 with a clear message: "An account with this email already exists."
## Actual
HTTP 500. Stack trace shows a `UniqueConstraintViolation` at insert time.
Create CHANGELOG.md:
# Changelog
Create archive/old-design-doc.md:
# Old design doc — DO NOT EDIT
Archived 2025-12-01.
Now start Claude Code in the scratch directory:
claude
You should land at the Claude Code prompt. Leave it open — every step below either runs there or edits one of these files in another terminal/editor.
Step 1 — Write: pin project rules with CLAUDE.md (5 min)
Goal: see how project memory shapes Claude's behavior on the very next prompt.
1.1 In a second terminal or your editor, create ~/cct-exercise/CLAUDE.md:
# Project Context
## Rules
- Always preserve existing TODO ordering in `notes.md`. New TODOs go at the bottom.
- Every code change that fixes a bug must add an entry under a `## Bug Fixes` section in `CHANGELOG.md`, dated YYYY-MM-DD.
- Never modify files in `archive/`.
- Prefer tables over bullet lists when summarizing structured data.
1.2 Back in Claude Code, type:
Read notes.md and add a new TODO for "wire up CI". Then read bug-report.md and add a CHANGELOG entry for fixing it — don't fix the bug yet, just log it.
Expected outcome:
notes.mdgets the new TODO appended to the bottom; existing TODOs are unchanged and in the same order.CHANGELOG.mdgets a## Bug Fixessection with today's date and a one-line entry about BR-2026-014.archive/old-design-doc.mdis untouched.
Reflection: if you had skipped step 1.1 and started cold, Claude wouldn't know any of those rules. What three things did CLAUDE.md save you from having to type in every single prompt for the rest of the session?
Step 2 — Select: inject specific context with @ and /memory (5 min)
Goal: feel the difference between context Claude finds on its own and context you push at it.
2.1 In Claude Code, type (the leading @ is important — it tells Claude to inject the file's content directly into the prompt rather than going hunting for it):
@bug-report.md Summarize this bug in one sentence and propose a fix in two sentences.
Expected: Claude answers fast and does not do a separate "read the file" tool call first — the @ injection means the file content was already in the prompt.
2.2 Mid-conversation, you decide a project preference matters. Type:
Add this rule to CLAUDE.md: "Prefer pytest over unittest in this project."
Claude will propose an edit to CLAUDE.md and ask for permission to write — approve it.
2.3 Open CLAUDE.md in your editor. You should see the new line added (Claude updated the file for you). If you'd rather not commit the preference to the repo, you can instead ask Claude "remember that I prefer pytest in this project" — Claude will save it to auto-memory (kept under ~/.claude/projects/<project>/memory/ and not checked in). Run /memory in Claude Code to see all loaded memory files and toggle auto-memory.
2.4 Ask a follow-up that involves tests:
Write a test for the proposed fix to BR-2026-014.
Expected: Claude reaches for pytest, not unittest — because the preference is now in project memory.
Reflection: when is @file better than letting Claude search? (Two reasons: it skips a tool call, and it stops Claude from accidentally reading a different file that happened to match its search.)
Step 3 — Compress: fill the window, then /compact and /clear (10 min)
Goal: watch a real context window grow, then shrink. This is the most visceral part of the exercise.
3.1 Run a few rounds of meaningful work. Ask Claude in order:
Refactor notes.md so the TODOs are a Markdown table with columns: Item, Priority (guess), Estimated effort (guess).
List every file in this directory tree and explain in one sentence what each is for.
Suggest three concrete improvements to the project structure.
3.2 Type:
/cost
If /cost isn't available in your Claude Code version, try /status or /usage. You'll see token usage. Write down the input tokens number — that's roughly how full your context window is right now.
3.3 Type:
/compact
Claude will summarize the conversation. Wait for it to finish. Then run /cost again. The input-token count should drop sharply — often by an order of magnitude.
3.4 Now ask something that depends on a specific detail you discussed earlier:
What was the exact second bullet from your "three improvements" answer? Use only the conversation history — don't re-read the project.
Expected: Claude probably gives you the gist of that bullet but not the exact wording. That matches the chapter finding from §4.3 — high-level facts survive compaction, fine-grained specifics often don't.
3.5 Type:
/clear
Then ask:
What was your last answer about?
Expected: Claude has no idea — the conversation is gone. But now ask:
What are the rules in this project?
Claude should list the rules from CLAUDE.md. /clear wipes conversation; project memory persists. That's the exact line the chapter drew between Write and Compress.
Reflection: look at the §6 diagnostic table. Which row of the table matches what /compact did for you here? Which row would have wanted /clear instead?
Step 4 — Isolate: run a sub-agent in its own context window (5 min)
Goal: see context isolation in action — including what the sub-agent cannot see.
4.1 Type:
Use a sub-agent to review notes.md and report which TODOs look stale or unclear. Keep the report under 100 words.
Claude invokes the Agent tool (formerly called Task; you may still see Task as an alias). In its narration you'll see something like "I'll use a general-purpose sub-agent to review the TODOs in notes.md." The sub-agent runs in its own context window — it does not inherit the conversation above.
4.2 After the sub-agent reports back, ask the main Claude:
What did the sub-agent see, and what didn't it see?
Expected: the honest answer is "it saw the description I gave it, its own system prompt, and the files it chose to read. It did not see our earlier conversation about refactoring or the bug report." That's the isolation guarantee from §4.4.
Reflection: in your run so far, which earlier turns would have been pure noise — or worse, context confusion — for that sub-agent if it had inherited them?
Step 5 — Goldilocks: write a sub-agent prompt and iterate it (10 min)
Goal: feel the Goldilocks zone by deliberately landing too vague first, then iterating.
5.1 Create .claude/agents/code-reviewer.md in your scratch directory:
---
name: code-reviewer
description: Reviews code changes.
---
You review code. Be thorough.
5.2 In Claude Code, type:
Use the code-reviewer agent to review my recent edits to notes.md and CHANGELOG.md.
Expected: the review is vague — generic things like "consider clarity" and "make sure it's tested." The sub-agent has almost no signal to work with.
5.3 Now rewrite .claude/agents/code-reviewer.md into the Goldilocks zone:
---
name: code-reviewer
description: Reviews changes in this project for correctness, consistency with CLAUDE.md, and clarity.
---
You review changes in this project. Your goal is to catch the issues a busy reviewer would catch on a careful first read.
Review framework — apply in order:
1. Read the changed files end to end. Get the full picture before commenting.
2. Read CLAUDE.md. Note every project rule the change touches.
3. Find rule violations. Mark each as must-fix (rule violated) or nit (style preference). Be specific about which rule.
4. Look for a simpler alternative. If the change could be smaller or clearer, say what you would do.
Guidelines:
- Prefer concrete suggestions over abstract advice.
- Don't enumerate every style preference; trust your judgment on style.
- If you find nothing wrong, say so in one line — don't manufacture issues.
5.4 Trigger the review again:
Use the code-reviewer agent to review my recent edits to notes.md and CHANGELOG.md.
Expected: a focused review that explicitly references the rules in CLAUDE.md (TODO ordering, the ## Bug Fixes section, the date format), and that distinguishes must-fix from nit.
Reflection: put your two versions side by side. Which Goldilocks moves from §5 did the rewrite apply? (Clear identity and scope. Reasoning framework, not flowchart. Principles instead of hardcoded rules. No magic numbers like "always make three suggestions.")
Success checklist
Before you call this exercise done, you should be able to point to evidence of all of these:
- [ ]
CLAUDE.mdexists in~/cct-exercise/and has rules. - [ ]
notes.mdhas a TODO Claude added in the right position (bottom, existing order preserved). - [ ]
CHANGELOG.mdhas a dated entry under## Bug Fixes. - [ ]
archive/old-design-doc.mdwas never modified. - [ ] You saw the
/costtoken number drop measurably after/compact. - [ ] You triggered a sub-agent via the Agent tool (formerly Task) at least once and saw its narrated invocation.
- [ ] You have two versions of
.claude/agents/code-reviewer.md(vague and Goldilocks) and saw measurably different reviews from each.
What to record (for your own notes)
The app doesn't collect any of this — capture it for yourself.
- The input-token count before and after
/compact. The ratio is the cheapest context-engineering win in your toolkit; keep an eye on it across real projects. - One specific thing the vague code-reviewer missed that the Goldilocks one caught.
- One Claude Code behavior that surprised you. If it's worth keeping, add it to memory — ask Claude to "remember X" (saved to auto-memory) or to "add this rule to CLAUDE.md" (committed to the project). Use
/memoryto inspect either.
Common pitfalls -@filenot injecting. Make sure the file path is relative to your current directory and there's a space after the filename before the rest of your prompt. - Not sure where a remembered fact landed. "Add this to CLAUDE.md" writes to the version-controlled project file (./CLAUDE.md). "Remember X" saves to auto-memory under~/.claude/projects/<project>/memory/. Run/memoryto see every loaded memory file and figure out which path your line ended up in. - Sub-agent invocation not visible. Claude's narration of "I'll use a sub-agent" can be subtle. If you're not sure it really delegated, ask: "did your last answer use a sub-agent? quote the tool call."
Knowledge check — try the quiz
Once you have read the lesson and finished the activity, take the chapter quiz from the navigation bar. Six questions: five from the book chapter, one synthesis question that ties the book to the platform primitives from §6. You can retake the quiz until you are confident.
Further reading & enrichment sources
- Anthropic engineering blog — "Effective Context Engineering for AI Agents" (
https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents). Source of the attention budget, context rot, just-in-time vs pre-inference retrieval, structured note-taking, and anatomy of effective context framings used in the enrichment callouts. - Anthropic cookbook — "Context Engineering: Memory, Compaction, and Tool Clearing" (
https://platform.claude.com/cookbook/tool-use-context-engineering-context-engineering-tools). Source of the platform-primitive table (§4.3 and §6), the composition order (clearing → compaction → memory), and theexclude_toolsguidance for memory. Includes a runnable Jupyter notebook if you want to reproduce the quantitative results.
Knowledge check
6 questions. Passing score: 5.
Instructor notes & source coverage
Source Ledger — Chapter 1: Context Engineering
Primary source (the book)
- Source PDF:
source-pdfs/01-chapter-01.pdf(21 pages) - Extracted source:
extracted-chapters/01-chapter-01.md(cleaned) andextracted-chapters/01-chapter-01.txt(raw, form-feed page boundaries preserved) - Extraction tool:
pdftotext -layout -enc UTF-8(Poppler, shipped with Git for Windows) - OCR needed: No — extraction was clean text.
Enrichment sources
The lesson silently incorporates material from two external Anthropic publications. Per project convention, no inline > Source: or > Enrichment — ... labels appear in the learner-facing lesson — the labels caused visual confusion. This source ledger is the single source of provenance: every per-section mapping below tells you which paragraphs came from the book, which from Anthropic, and which were authored as pedagogical scaffolding for this training.
- [E1] Anthropic engineering blog — "Effective Context Engineering for AI Agents" —
https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents - [E2] Anthropic cookbook — "Context Engineering: Memory, Compaction, and Tool Clearing" —
https://platform.claude.com/cookbook/tool-use-context-engineering-context-engineering-tools
Pedagogical enrichment by the training author
The following additions are not from the book and not from Anthropic — they are pedagogical material written for this training. They are inventoried here so a reviewer can audit them separately. No inline labels are placed in the learner-facing lesson; only the > Analogy — ... callouts carry an in-lesson label.
- Newcomer preface (
## Before we start — agent, prompt, and context in plain language). Defines LLM, prompt, agent, harness, context, and context window in plain English for readers new to agent engineering. - Per-section analogies. Eleven
> Analogy — ...callouts: one per numbered lesson section (§1–§6), one per Strategy sub-section (§4.1–§4.4), one at the top of §4 setting up the running "kitchen" analogy, and one closing whole-chapter analogy. - Whole-chapter analogy (
## The whole chapter in one image — the long-shift chef). A sustained restaurant-kitchen analogy that re-frames the chapter's six sections for less-technical readers. - Four SVG diagrams authored for this training (not reproduced from the book's figures, which we do not have rights to):
- Figure P.1 — "What's in the context window?" (preface).
- Figure 1.A — "Context growth across turns" (§2).
- Figure 1.B — "The four strategies at a glance" (§4 intro).
- Figure 1.C — "The Goldilocks scale for system prompts" (§5).
- Each figure has a
figcaptionthat explicitly notes it is pedagogical and not from the book. - Practical exercise — "Drive context engineering in Claude Code." A ~30–45 minute hands-on walkthrough that takes the learner through Write / Select / Compress / Isolate plus a Goldilocks-zone sub-agent prompt rewrite, on a small sandbox project the learner creates locally. Includes seed file contents, step-by-step commands, expected outcomes, reflection prompts, and a success checklist. Sandbox project is created by the learner outside the training repo; nothing in the exercise modifies the training repo itself.
Quiz items and learning objectives remain grounded in the book chapter and the labeled Anthropic enrichment sources — none of the pedagogical analogies, diagrams, or exercise steps are themselves assessed.
Objective → Source Mapping
| Learning Objective | Source Section (page) | Confidence | Notes |
|---|---|---|---|
| Explain why context engineering is a distinct concept from prompt engineering. | "From prompt engineering to context engineering" (p. 3) | High | Direct claim: prompts are static, context is dynamic. |
| Describe the four Claude Code context strategies (Write/Select/Compress/Isolate). | "Claude Code and its context engineering strategies" intro + Strategies 1–4 (pp. 5–13) | High | Strategies named explicitly in the source. |
| Identify the three failure modes of unmanaged context: poisoning, confusion, clash. | "Why context matters for agents" (p. 4) | High | Each failure mode is defined in the source. |
| Distinguish project memory, user memory, and dynamic memory imports. | "Strategy 1: Writing context and persistent memory" (pp. 6–8) | High | Three tiers and @ import syntax shown in source. |
| Evaluate a system prompt against the Goldilocks zone. | "System prompts and why they matter" → "Goldilocks zone" + worked examples (pp. 14–20) | High | Source provides specific/vague/middle examples used in quiz Q5. |
| (enrichment) Explain context engineering with the attention-budget and context-rot framing. | [E1] §"Why context engineering is important" | High | Adds Anthropic's named terms on top of the book's "degradation" framing. |
| (enrichment) Map slash commands to Anthropic API primitives and pick the right one for a workload. | [E2] §"The Problem" + composition-strategy table | High | Source of §6 in the lesson and of quiz Q6. |
Lesson Section → Source Mapping
| Lesson section | Source location | Confidence |
|---|---|---|
| Agent harness definition | pp. 2–3 | High |
| Sources of context (developer / user / prior interactions) | p. 3 | High |
| Context window growth and degradation | pp. 3–4 (Figures 1.1–1.3) | High |
| Poisoning / confusion / clash | p. 4 | High |
Three-tier memory + @ imports | pp. 6–8 | High |
Idempotent add_context helper using grep -qxF | pp. 8–10 | High — quoted directly from source |
Hook example (UserPromptSubmit) | p. 10 | High |
Folder discovery + /memory editor + ask-Claude-to-remember + tool-specific reminders | pp. 10–11 (book) + current Anthropic memory docs | High — corrected on post-launch audit. The book's /memory add ... CLI syntax was replaced. Current Claude Code uses /memory as an interactive editor and exposes two documented ways to push a fact in: ask Claude in natural language to "remember X" (Claude saves to auto-memory under ~/.claude/projects/<project>/memory/) or ask Claude to "add this to CLAUDE.md" (Claude edits the file). Source: https://code.claude.com/docs/en/memory §"View and edit with /memory" and §"Auto memory"; https://code.claude.com/docs/en/commands /memory description. |
/clear vs /compact | pp. 11–12 | High |
| Sub-agents and the YAML caveat | pp. 12–13 | High — caveat about illustrative Task(...) syntax is quoted from source |
| Goldilocks zone (too specific / too vague / middle ground) | pp. 14–20 | High — bakery assistant examples used verbatim in quiz Q5 |
Enrichment section → source mapping
| Lesson location | Enrichment content | External source |
|---|---|---|
| §2 (context growth) | "Attention budget", "context rot", "smallest set of high-signal tokens" quote | [E1] §"Why context engineering is important" |
| §3 (failure modes) | All three failures + recall degradation framed under "context rot"; context windows of all sizes affected | [E1] §"Why context engineering is important" |
| §4.1 (Write) | Structured note-taking; Pokémon multi-step tally example; file system as implicit memory | [E1] §"Context engineering for long-horizon tasks" |
| §4.2 (Select) — retrieval | Just-in-time vs pre-inference vs hybrid retrieval; progressive disclosure | [E1] §"Context retrieval and agentic search" |
| §4.2 (Select) — tool design | Self-contained / robust / clear tools; descriptive parameters; minimize overlap | [E1] tool-design discussion |
| §4.3 (Compress) | Platform-primitive table (compaction / clearing / memory); "high-level survives, obscure lost" finding; clearing as cheapest compaction | [E2] §"How the Three APIs Map to the Problem" + experimental results |
| §4.4 (Isolate) | Sub-agents framed alongside compaction and structured note-taking | [E1] §"Context engineering for long-horizon tasks" |
| §5 (Goldilocks) | "Anatomy of effective context" — XML/markdown section organization; "examples are pictures worth a thousand words"; "do the simplest thing that works" | [E1] §"The anatomy of effective context" + §"Conclusion" |
| §6 (NEW — all enrichment) | Diagnostic mapping workload→primitive; composition order (clearing→compaction→memory); exclude_tools=["memory"] guidance | [E2] §"All-Three Primitives Combined" + diagnostic output |
Quiz Items → Source Mapping
| Quiz ID | Item | Source location | Confidence |
|---|---|---|---|
| q1 | Prompt vs context engineering | p. 3 | High |
| q2 | Four strategies | p. 5 | High |
| q3 | Idempotent context-switcher hook | pp. 8–10 | High |
| q4 | /clear vs /compact | pp. 11–12 | High |
| q5 | Goldilocks-zone bakery prompt | pp. 14–20 | High |
| q6 | Workload → platform primitive (synthesis) | [E2] diagnostic mapping table + composition strategy | High — answer grounded in lesson §6 enrichment |
Figures Referenced In Source (not reproduced in training)
| Figure | Caption (paraphrased) | Status |
|---|---|---|
| 1.1 | LLM Context Window | Referenced in lesson text; image not reproduced — described in prose. |
| 1.2 | LLM Tool Calling Loop | Referenced; described in prose. |
| 1.3 | Context Growth Across Multiple Turns | Referenced; described in prose. |
| 1.4 | Categories of context engineering | Referenced; replaced by the four-strategy table. |
| 1.5 | Goldilocks Zone for System Prompts | Referenced; described in prose with link to Anthropic source. |
Unsupported Or Unclear Items
| Item | Issue | Action |
|---|---|---|
| Exact pages for each strategy heading | Form-feed extraction puts each chapter PDF "page" at roughly one screen — book page numbers may differ from PDF page numbers. | Confidence ranges based on PDF page positions. Cross-check with the printed book if exact pagination is required. |
Task(...) sub-agent syntax | Source explicitly labels it illustrative; real YAML format comes later in the book. | Lesson preserves the caveat verbatim. |
Optional Enrichment
None added in this unit. All lesson content is grounded in the chapter source.
Source PDF: source-pdfs/01-chapter-01.pdf
Extracted source: extracted-chapters/01-chapter-01.md