Back to Knowledge
New

Context Engineering

The prompt is the part you type. The context window

Context Window

The amount of text an AI can 'see' at once, measured in tokens: your instructions, the conversation, files it read, and tool results. Current Claude models (Opus 5.5, Sonnet 5, Fable 5.1) offer 1M-token windows and Haiku 4.5 has 200K, but even huge windows work best when kept focused.

"Like short-term memory. The bigger the window, the more the AI can remember from your conversation."

is everything the model can see when it answers: instructions, files, tool output, and the whole conversation so far. Context engineering

Context Engineering

Deliberately curating everything the model sees, not just the prompt: instructions files, retrieved docs, tool results, conversation history. Good context engineering keeps the context window small and relevant using CLAUDE.md, skills that load on demand, subagents for side quests, and compaction.

"Like packing a carry-on for a trip. You can't bring the whole closet, so you choose exactly what the journey needs."

is the skill of deciding what goes in that window, what stays out, and when to clean it up. It's the difference between an agent that nails the task and one that forgets what you asked 40 minutes ago.

1Why it replaced prompt engineering

Prompt engineering was about wording one request well. That mattered when you pasted a question into a chat box and got one answer back. Agentic

Agentic AI

AI that can take actions autonomously — browsing files, running commands, making decisions — rather than just answering questions.

"Like a co-pilot who can actually fly the plane, not just give you directions."

tools like Claude Code

Claude Code

Anthropic's agentic coding tool. It lives in your terminal (and in VS Code, JetBrains, and on the web), reads your codebase, edits files, runs commands, and ships code. Install with the native installer (`curl -fsSL https://claude.ai/install.sh | bash` on macOS/Linux, `irm https://claude.ai/install.ps1 | iex` on Windows); it needs a Pro, Max, Team, Enterprise, or Console account.

"Like having a senior developer living in your terminal, ready to help 24/7."

work differently. They run a loop: read a file, run a command, read the output, edit, test, repeat. Your prompt might be 50 words. By turn 30, the context holds tens of thousands of tokens

Tokens

The units AI uses to process text. Roughly 1 token = 4 characters. You pay per token, and context windows are measured in tokens.

"Like words on a meter. The more you write (or the AI writes), the more tokens tick by."

of stuff the agent pulled in on its own.

So the question changed from "how do I phrase this?" to "what does the model know right now, and is it the right stuff?" Good wording still helps (see Prompting), but most bad agent sessions fail because of what was in the window, not how the request was phrased.

Prompt engineering

One message. Word choice, examples, format instructions. You control all of it.

Context engineering

A whole session. Memory files, tool results, history, what gets summarized or dropped. You shape it, the agent fills it.

2What actually fills the window

Think of the context window as a desk. Everything Claude is working with has to be on the desk at once. A lot lands on it before you type a word. Here's a rough, illustrative picture of a mid-session desk:

System prompt

Claude Code's own instructions for how to behave and use tools. Always there, you never see it.

CLAUDE.md + rules

Your project memory: user, project, and local CLAUDE.md files, plus any path-scoped rules that match.

Tool + skill listings

Names and one-line descriptions of skills, subagents, and MCP tools, so Claude knows what exists.

Files read

Every file Claude opens lands here in full. This is usually the biggest slice.

Tool results

Test output, build logs, grep hits, web pages, MCP responses.

Conversation

Your prompts and Claude's replies, including every false start.

Don't guess. Run this inside a session to see your real breakdown as a colored grid:

Claude Code

/context

3Context rot and the budget mindset

The current Opus 5.5 and Sonnet 5 models have a 1M-token window (Haiku 4.5 has 200K). That sounds endless. It isn't. Models pay less attention to details buried in the middle of a huge, noisy context. People call this context rot: the session still "remembers" the rule you set an hour ago, but it's competing with 300 lines of stale test output and three abandoned approaches.

Treat context like a budget, not a bucket. Every file read, every log dump, every "actually, try it the other way" costs attention (and money, since input tokens are billed). Signs you're over budget:

  • Claude re-introduces a bug you fixed earlier in the session.
  • It forgets a convention that's written right there in CLAUDE.md.
  • It starts re-reading files it already read.
  • Answers get vaguer and it asks questions you already answered.

When the window fills up, Claude Code performs compaction

Compaction

Summarizing a long conversation so it takes up less of the context window while keeping the important parts. Claude Code compacts automatically as the window fills, or on demand with `/compact`, and you can steer it: `/compact keep the test output`. `/context` shows how full your window is.

"Like condensing a 40-page meeting transcript into a one-page brief so the next meeting can start with the essentials."

: it replaces the conversation with a structured summary. Your system prompt, CLAUDE.md files, and memory reload; the most recently edited files get re-read; skills you invoked get re-injected. Full tool outputs and the blow-by-blow are gone. Better to do that on your terms than at a random moment.

4Six techniques that actually work

Layer your CLAUDE.md

Keep the project CLAUDE.md short: stack, commands, conventions, landmines. Put personal preferences in ~/.claude/CLAUDE.md and machine-specific notes in CLAUDE.local.md (gitignored). Move topic-specific rules into .claude/rules/*.md so they only load when Claude touches matching files.

Progressive disclosure with skills

A skill costs one line of context (its description) until Claude actually uses it. Then the full SKILL.md loads. That makes skills the right home for long how-tos: deploy checklists, migration recipes, review rubrics.

Send subagents to explore

A subagent reads 40 files in its own context window and hands you back a one-page summary. Your main session stays clean for the actual work.

Compact or clear on purpose

/compact summarizes the conversation so far and keeps going. /clear starts over with an empty conversation. Use compact mid-task, clear between tasks.

Retrieve just in time

Point Claude at the file or function that matters instead of pasting whole folders. Let it grep and open files as it needs them, instead of @-mentioning your entire src/ up front.

Write clean handoff docs

Before a session gets long, have Claude write the state of play to a markdown file: goal, decisions made, files touched, what's next. A fresh session reads that one file instead of inheriting 150K tokens of history.

Where CLAUDE.md files live

Claude Code layers several memory files. Broad rules go high, specific rules go low. It also reads AGENTS.md, and you can pull another file in with an @path/to/file import.

Memory layers

~/.claude/CLAUDE.md          # you, every project (tone, habits)
./CLAUDE.md                  # the project, committed (stack, commands)
./.claude/CLAUDE.md          # same thing, alternate location
./CLAUDE.local.md            # you, this project only (gitignore it)
./.claude/rules/*.md         # modular rules, can be scoped to paths

A lean project CLAUDE.md

CLAUDE.md

# Acme Dashboard

Next.js 16 App Router, TypeScript, Drizzle + Neon, Auth.js.

## Commands
- Dev: npm run dev
- Test: npm test (Vitest). Run before saying you're done.
- Typecheck: npx tsc --noEmit

## Conventions
- Server Components by default. "use client" only for interactivity.
- DB access only through lib/db/*. Never import drizzle in components.
- Route protection lives in proxy.ts.

## Landmines
- Stripe webhook route must read the raw body. Don't "clean it up".

## More detail (read when relevant)
- Before deploying, read docs/deploy.md

Aim for a page, not a novel. If a section only matters for one area of the code, move it into a rule file or a skill. Note the plain-text pointer to docs/deploy.md: an @ import would pull that file into every session, while a pointer lets Claude open it only when it's deploying. The docs suggest keeping each CLAUDE.md under about 200 lines.

A path-scoped rule

Rules with a paths field only load when Claude reads matching files. Rules without it load every session, just like CLAUDE.md.

.claude/rules/api.md

---
paths:
  - "app/api/**/*.ts"
---

# API route rules

- Validate every request body with Zod before touching the database.
- Return errors as { error: string } with a proper status code.
- Check the session with auth() at the top of every mutating handler.

Compaction, clearing, and side questions

Claude Code

/compact keep the failing test output and the API shape we agreed on
/clear
/btw what's the difference between cookies() and headers() again?
  • /compact with focus text tells the summary what to keep. Do it at a natural checkpoint, like after a feature passes tests.
  • /clear starts a new conversation with empty context. You can get the old one back with /resume.
  • /btw asks a side question without adding it to the conversation. Great for quick lookups that would otherwise clutter the task.

Delegate exploration to a subagent

Prompt

use a subagent to investigate how our auth system handles token refresh.
report back: the files involved, the flow in 5-10 steps, and anything that looks broken.

The subagent

Subagent

A specialized AI agent Claude Code can delegate a task to. It works in its own separate context window with its own tools and instructions, then reports back a summary. Define one as a Markdown file in `.claude/agents/` (project) or `~/.claude/agents/` (personal) with `name` and `description` frontmatter; Explore, Plan, and general-purpose are built in.

"Like hiring a specialist contractor for a specific part of a project. They work independently and report back when done."

reads files in its own context window and returns only the summary. More on this in Parallel Agents.

Curate your MCP tools

Every connected MCP

MCP (Model Context Protocol)

An open standard for connecting AI apps to external tools and data (databases, GitHub, docs, browsers). Servers run locally over stdio or remotely over Streamable HTTP, and remote servers use OAuth 2.1 for sign-in. In Claude Code: `claude mcp add --transport http <name> <url>`.

"Like USB ports for AI. A universal way to plug in new capabilities."

server adds tools. By default Claude Code lists MCP tool names and loads the full schemas on demand, which helps. But each server is still more choice, more noise, and another thing that can return a giant blob of JSON. Keep the ones you use on this project; remove the rest.

Terminal

claude mcp list
claude mcp remove <name>

5Before and after

Starting a feature

Before

@src @app @lib add a billing page. Also fix the navbar and look at why tests are slow.

After

Add a /billing page that lists the user's invoices from lib/billing/invoices.ts. Match the layout of app/settings/page.tsx. Don't touch the navbar. Run npm test when done.

The first version dumps three folders into context and mixes three tasks. The second names the two files that matter and one clear finish line. Claude will open anything else it needs.

A long debugging session

Before

Keep going in the same 3-hour session with five abandoned approaches and 20 pasted stack traces.

After

Ask Claude to write docs/handoff-auth-bug.md (symptom, what we ruled out, current theory, next step). /clear. Start fresh: "Read docs/handoff-auth-bug.md and continue from 'next step'."

The fresh session carries the lessons, not the noise.

Project rules

Before

A 900-line CLAUDE.md with the full Stripe integration guide, every API route, and last month's meeting notes.

After

A short CLAUDE.md with commands and conventions. The Stripe guide becomes a skill. API route rules move to .claude/rules/api.md, scoped to app/api/**.

CLAUDE.md loads every turn. Skills and scoped rules only load when relevant.

6Common traps

"More context is always better"

It isn't. Irrelevant context dilutes attention and costs tokens. Give the agent the right 5 files, not all 500.

Treating CLAUDE.md like a wiki

It rides along on every single turn. If it's long, you're paying for it constantly and burying the important rules.

Letting auto-compaction pick the moment

It can fire mid-refactor and summarize away the detail you needed. Compact yourself at checkpoints, with focus text.

Pasting huge logs

Paste the error and the 20 lines around it. Or ask Claude to run the command and grep the output itself.

Installing every plugin and MCP server you see

Each one adds descriptions to every session, even when unused. Install for the project in front of you.

One mega-session for the whole day

Different tasks deserve different sessions. Clear between them and keep handoff notes.

7Which tool for which job

If the info is...Put it in...
Needed on nearly every task (commands, stack, hard rules)Project CLAUDE.md
Only relevant to one folder or file type.claude/rules/*.md with a path scope
A repeatable procedure (deploy, release, review)A skill (.claude/skills/<name>/SKILL.md)
Research you need the answer to, not the processA subagent
State to carry into a fresh sessionA handoff markdown file
Live data from another systemAn MCP server, connected only where needed
A one-off question mid-task/btw

Official reference: Claude Code memory docs and the context window explorer .

Keep going

Context engineering is the foundation. These pages build on it.