---
title: Context engineering
summary: Deciding what the model sees, from instruction files to notes and fresh sessions, so a long task stays sharp instead of drifting.
section: ai
phase: any
order: 2
last_reviewed: 2026-11-20
---

# Context engineering

Prompt engineering is how you word a request. Context engineering is everything around it: which instructions, files, tool results and notes are in front of the model at each step, and which are not.

## You'll be able to

- Write a short instruction file (like `AGENTS.md`) that agents actually follow
- Decide what belongs in the prompt, in the instruction file, in a note, or nowhere
- Keep a long task on track with summaries, notes and fresh sessions
- Spot when too much or conflicting context is the real cause of a bad result

## The mental model

Context is a budget, not a bucket. [How LLMs work](/docs/ai-agents/how-llms-work.md) covered why: accuracy and recall can degrade as the window fills ("context rot"), so every extra token competes for the model's attention. Anthropic's engineering team frames the goal as the smallest set of high-signal information that gets the result you want.

Think of onboarding a contractor. You hand them a one-page brief with the commands, conventions and rules that apply every day. You tell them where the rest lives (the repo, the docs) and let them look things up when needed. You do not read them the entire codebase on day one.

## Key concepts

- **Context engineering:** Curating what is in the window over the whole task, not just the first message. It covers system prompts, instruction files, retrieved files, tool results, and notes carried between sessions.
- **Instruction file:** A plain-text file in your repo that the agent reads automatically, so you stop repeating the same rules. `AGENTS.md` is an open convention for this: a "README for agents" at the repo root. There is no required structure, just Markdown. Some tools use their own name (Claude Code uses `CLAUDE.md`).
- **Nesting and precedence:** In a monorepo you can add an instruction file inside each package. With `AGENTS.md`, the nearest file to the code being edited wins, and anything you say directly in the chat overrides the files.
- **Just-in-time retrieval:** Keep pointers (file paths, search commands) and let the agent load files when it needs them, instead of pasting everything up front. Claude Code combines both: the instruction file is loaded at the start, and file search fetches the rest on demand.
- **Compaction:** Summarizing a long conversation and continuing from the summary. Clearing old tool results is the lightest version.
- **Notes outside the window:** The agent writes progress to a file (a to-do list, a `NOTES.md`) and reads it back later, so the state survives a fresh session.
- **Sub-agents:** Focused helpers that work in their own clean context and hand back a short summary, so the main thread stays small.

## Decisions you make (not the agent)

| Decision | Sensible default | Choose otherwise when… |
|---|---|---|
| Where the rules live | An instruction file at the repo root, committed to git | A rule is personal (your editor habits): keep it in a local file that is not committed |
| Which file name | `AGENTS.md`, since many tools read it | Your main tool expects its own name: use that, and point it at the shared file if it supports imports |
| How long the file is | Short: aim for a page (Claude Code's docs suggest under about 200 lines) | Never grow it for completeness; move procedures to skills and package-specific rules to nested files |
| What goes in it | Facts needed every session: commands, layout, conventions, always-do and never-do rules | One-off task detail: put that in the prompt instead |
| Long task going stale | Write notes to a file, then restart with a fresh session | The thread is short and coherent: just continue |
| Big codebase | Point to paths and let the agent search | The task is one file: include it directly |
| Parallel or noisy subtasks | Hand to a sub-agent and ask for a summary | The subtask needs your running decisions: keep it in the main thread |

## What good output looks like

- The agent uses your real commands (the right package manager, the right test command) without being told each time
- It follows conventions that are only written down once
- Late in a long task it still respects early constraints
- When it needs a file it didn't have, it finds it instead of guessing
- It can say which instruction it followed and why

## Red flags

- **An instruction file that keeps growing** → trim to what matters every session; long files dilute the important rules.
- **Conflicting rules** ("always use X" in one place, "prefer Y" in another) → the agent picks one at random. Remove the conflict instead of adding another rule.
- **Vague rules** ("write clean code") → replace with checkable ones ("run `pnpm lint` and fix all errors before finishing").
- **Stale commands** (a script that no longer exists) → verify every command in the file by running it.
- **Secrets or tokens in the file** → never. Instruction files are committed and read by tools. See [Environments and secrets](/docs/shipping/environments-and-secrets.md) and [Security of agentic workflows](/docs/ai-agents/agent-security.md).
- **Pasting entire files "just in case"** → name the path and let the agent read what it needs.
- **Quality dropping late in a long session** → the context has grown and muddied. Save notes and start fresh.

## Worked example

**Task:** The agent keeps running `npm install` and `npm test` in a repo that uses pnpm, and puts new components in the wrong folder.

You stop repeating yourself and write an instruction file with the commands and layout. A good result is short and verifiable:

```markdown
# AGENTS.md

## Commands
- Install: `pnpm install`
- Dev server: `pnpm dev`
- Lint: `pnpm lint`; typecheck: `pnpm typecheck`; tests: `pnpm test`
- Run lint, typecheck and tests before saying a task is done.

## Layout
- `app/` routes (Next.js App Router), `components/` shared UI, `lib/` data and helpers.
- New components go in `components/`, one per file, named in PascalCase.

## Rules
- Use TypeScript strict mode; do not add `any` or `@ts-ignore`.
- Do not add dependencies without asking first.
- Never commit secrets or `.env` files.
```

**The wrong turn:** over the next weeks the file grows to several hundred lines. Someone adds "prefer functional components" next to an older "use classes for stateful widgets". The agent starts producing a mix of both and ignores some of the rules.

**How review catches it:** ask the agent which rules it applied to a recent diff and where each came from. Contradictions and rules it can't cite show up immediately. Then trim: delete what's obvious or stale, resolve the conflicts, and move multi-step procedures out of the file.

## Sample prompts

### Weak vs strong
```compare
## Weak
Create an AGENTS.md for my project.
## Why it fails
The agent will invent generic advice ("write clean code") and may guess commands that don't exist.
## Strong
Create an AGENTS.md at the repo root for this project.
Stack: Next.js (App Router), TypeScript, Postgres via Drizzle, pnpm.
Include only: exact commands to install, run, lint, typecheck and test; the folder layout; and 5-8 concrete rules you can verify from this codebase.
Constraints: under 60 lines; no generic advice; no secrets; every command must be one you have actually run here.
Non-goals: don't restate things any developer would assume, and don't change any source files.
Verify: run each command you list and tell me which ones failed.
## Why it works
It limits length, demands verifiable content, and makes the agent prove the commands work.
## What changed
- **Length is capped**, so the file stays short
- **Content is limited** to commands, layout and verifiable rules
- **Every command must have been run**, so stale commands don't creep in
- **Non-goals and verification** stop the agent from rewriting code and make it prove the commands work
```

### Audit an instruction file
```text
Review AGENTS.md. List (1) rules that conflict with each other, (2) vague rules that can't be checked, (3) commands or paths that no longer exist in this repo, and (4) rules the agent would follow anyway. For each, propose a one-line fix or deletion. Do not edit the file yet.
```
*Why it works:* It targets the four ways these files rot and keeps you in control of the edits.

### Make the agent cite its instructions
```text
For the change you just made, list which instructions from AGENTS.md (or this conversation) you followed, quoting the line for each. Then list any instruction you were unsure about or chose to ignore, and why.
```
*Why it works:* It exposes missing or conflicting rules. Treat the answer as a lead to check, not proof.

### Carry state across sessions
```text
Before we stop: write NOTES.md with the goal, decisions made and why, what is done, what is next, and open questions. Keep it under 40 lines. I'll start a fresh session and ask you to read it first.
```
*Why it works:* It moves state out of the window into a file, so a clean session loses almost nothing.

### Put context on a diet
```text
Task: <describe the task>. Before reading any files, list the 3-5 files or directories you think are relevant and why. Read only those. If you need more, say what and why before reading it.
```
*Why it works:* It forces just-in-time loading instead of pulling in everything.

## Check your understanding

```quiz
Q: What does "context engineering" cover that prompt wording doesn't?
- [ ] Only the system prompt
- [x] Everything in the model's context across the whole task: instructions, files, tool results and notes
- [ ] Choosing which model to use
> Why: The window is a budget. What you put in, keep out and carry between sessions matters as much as how you phrase the request.

---

Q: A monorepo has an AGENTS.md at the root and another in packages/web. An agent edits a file in packages/web. Which one applies most?
- [ ] The root file, always
- [x] The nearest one, in packages/web. Anything you say directly in the chat overrides the files
- [ ] Whichever is longer
> Why: The AGENTS.md convention is that the closest file to the code being edited takes precedence.

---

Q: Which belongs in an instruction file?
- [ ] Your production API key
- [x] Commands, layout and rules that matter every session, kept short and checked
- [ ] The full text of this week's task
> Why: Instruction files are committed and loaded every time. One-off task detail belongs in the prompt, and secrets never belong in the file.

---

Q: Quality drops late in a long session. What is a good move?
- [ ] Keep going; it will recover
- [x] Write down the decisions in a notes file and start a fresh session
- [ ] Paste more files into the conversation
> Why: Context can degrade as it fills. A short, curated hand-off carries forward what matters without the noise.
```

## Checklist

- [ ] An instruction file exists at the repo root and is under about a page long
- [ ] Every command in it has been run and works
- [ ] No conflicting, vague or obvious rules remain
- [ ] No secrets in it
- [ ] Long tasks write progress to a notes file and restart fresh when quality drops

## Go deeper

- [AGENTS.md](https://agents.md): the open format for agent instruction files, including nested files and precedence
- [How Claude remembers your project (Claude Code docs)](https://code.claude.com/docs/en/memory): how one tool loads instruction files, imports and path-scoped rules; check your own tool's docs for its behavior
- [Effective context engineering for AI agents (Anthropic)](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents): context as a finite budget, compaction, note-taking, sub-agents and just-in-time retrieval
- [Context windows (Claude docs)](https://platform.claude.com/docs/en/build-with-claude/context-windows): compaction and clearing old tool results for long conversations
- [How LLMs work, for builders](/docs/ai-agents/how-llms-work.md): why context size and quality matter
- [Working with coding agents](/docs/start-here/working-with-coding-agents.md): project rules files and the agent loop
