LearnThatStack Ace your next interview

Context Engineering

Claude Code, Cursor, Copilot and Aider in September 2026 Checked Sep 2026 24 code snippets

The model

  • A model knows only what's in its context window for this request. Rules, tool definitions, chat history, files and tool output all share that space.
  • The window is a budget. Every token costs money and attention, and accuracy drops as the window fills, even before it hits the limit.
  • Standing context like rules files and tool definitions goes out with every request, so keep it short and scoped. Load everything else when the task needs it.
  • Long sessions fill up with stale context. Compaction swaps the history for a lossy summary, so keep the plan and decisions in a file outside the chat.
  • Treat rules files as shared code that you review and prune. Treat fetched text as untrusted input, and keep secrets out of all of it.
Repo & toolsrules, code, MCPContext windowwhat the model seesTask fileplan, decisionsSubagentits own windowLOADrules, tools each turnfiles, logs on demandDELEGATEscoped taskshort findingsKEEPsave statereload next session
The agent resends everything it has read on every turn. Subagents keep their reading out of the window, and a task file survives compaction.

The context window

what the model sees, and what fills it

What context engineering is

Say how it differs from prompt engineeringIt shapes everything the model sees in a task. The prompt is one part of that.
Say what a context window holdsRules, history, files, tool output and the model's own reply.
Say what happens as the window fillsThe tool drops or summarizes old turns, and details get lost.

TrapA better prompt can't fix missing context. If the model can't see the current interface, it guesses.

What uses up tokens

Name what's sent with every requestThe system prompt, rules files and tool definitions.
Name what fills the window fastestBig test logs, generated files and broad search results.
Keep only the end of a long test lognpm test 2>&1 | tail -n 40

TipYou pay for repeated content on every request, unless the prompt cache covers it.

Rules & prompts

what the agent loads each session, and what you add per task

What goes in a rules file

# acme-api## Commands- Test one file: npm test -- <path>- Finish with: npm run lint && npm test## Architecture- routes/ -> services/ -> models/## Ask first- New dependencies, migrations, infra/
Say what problem a rules file solvesIt saves you repeating stable facts in every prompt.
List what belongs in a rules fileCommands, key folders, boundaries, naming rules, approved libraries and risky actions.
List what stays out of itSecrets, customer data, one-off notes, long tutorials and advice like "write good code".

TipLink to longer docs instead of copying them in. Aim for a map and a policy guide, not a handbook.

Keep rules lean

Say why a long rules file hurtsIt costs context on many requests and buries the key rules.
Handle a rule a linter already enforcesDelete it, unless the agent needs it to choose an approach.
Know when to revisit the fileAfter the agent repeats a mistake or the architecture changes.

TrapConflicting rules can make the agent follow the wrong one, or waste turns reconciling them.

Rules file, docs or prompt

Place a test command every task usesThe rules file. It's stable and needed on every task.
Place the reason behind a subsystem boundaryAn architecture doc, linked from the rules.
Place a limit for this task onlyThe prompt, with the task's goals and acceptance criteria.

TipAsk how long it stays true, how often it's needed and who needs it.

TrapDon't copy guidance into two layers. The copies drift apart.

Show, don't tell

Get new code in your project's styleAttach one good handler or test and say "follow this pattern".
Stop the agent copying values blindlySay how the new case differs from the example.

TipUse prose for hard rules and the example for structure.

TrapA poor example spreads its flaws. Pick a current one that shows the standard.

Rules files by tool

which files each tool reads, and which one wins

AGENTS.md and CLAUDE.md

Say what AGENTS.md isA README for agents, in an open format many coding agents read.
Scope AGENTS.md rules to one folderAdd a copy there. The file nearest the edited file wins.
Know when Claude Code reads AGENTS.mdBy default, only when the repo has no CLAUDE.md.
Make CLAUDE.md load AGENTS.md@AGENTS.mdPut this line in CLAUDE.md, so Claude Code and other agents read one file.
Generate a starter CLAUDE.md/init

TipCLAUDE.md can also hold features only Claude Code understands. Keep the shared rules in AGENTS.md.

Global, project and folder rules

Set personal defaults for every repo~/.claude/CLAUDE.mdYour style and safe command preferences.
Share rules for the whole repoCLAUDE.mdShared commands, architecture and policies.
Add rules for one subsystempackages/api/CLAUDE.mdClaude loads it when it reads files in that folder.
Say how Claude Code combines the layersIt loads them all together. No layer overrides another.
Set an order of authorityOrg policy, then repo, then folder rules, then the task.

TipPut each rule at the narrowest scope where it's true. A frontend test command shouldn't load during database work.

TrapA folder or personal rule may add detail to org policy. It must never weaken a security control.

Cursor rules

---description: API error handlingglobs: src/api/**/*.tsloads for these filesalwaysApply: false---Throw AppError subclasses. Never swallow errors.
Add a Cursor project rule.cursor/rules/errors.mdc
Name the four ways a rule loadsAlways, for matching files, when the agent picks it, or when you mention it.
Move off the legacy .cursorrules fileSplit it by concern, drop duplicates, and check which rules load.

TipCursor also reads AGENTS.md, so keep rules every tool needs there.

Trap.cursorrules always loads and can't scope a rule to part of the code. Cursor plans to deprecate it.

GitHub Copilot instructions

Add repo-wide instructions.github/copilot-instructions.md
Add rules for some paths only.github/instructions/api.instructions.mdSet an applyTo glob in its frontmatter.
Save a task you run on demand.github/prompts/release.prompt.md

TipTest the setup with a few standard tasks and review the diffs. Don't assume a file loaded.

TrapA matching path file adds to the repo-wide file. It doesn't replace it.

Long sessions & subagents

keep a long task on track as the window fills

Start fresh or keep going

Know when to start a fresh sessionThe goal changed, an approach failed, or the agent cites stale context.
Clear the conversation in Claude Code/clear
Write a handoff before you restartState, decisions, changed files, test results, next steps and risks.

TipPut the handoff in the new prompt or a task file. The agent can't recall details a summary dropped.

Compaction and long tasks

Say what compaction doesIt swaps a long history for a short summary to free space.
Compact now and say what to keep/compact keep the failing test names
Name what a summary can dropExact errors, subtle constraints, and why an approach was rejected.
Check the agent after compactionHave it restate the plan, check it against the spec and re-read key files.
Keep a long task coherentKeep the goal, decisions and next step in a file outside the chat.

TrapIf a summary drops why an approach failed, the agent tries it again. Write the reason down.

Subagents and handoffs

Say how subagents save contextThey explore in their own windows and return only short findings.
Define a Claude Code subagent.claude/agents/tester.md
Brief an agent you hand work toA bounded task, its inputs, what it may do and the output format.
Say what a handoff should returnFindings with file references, tests run, assumptions and risks.

TrapParallel subagents can duplicate work or assume different things. The main agent compares them and owns the result.

Context poisoning

Define context poisoningWrong, stale or malicious content that steers later actions.
Spot a poisoned sessionIt reuses a removed API or cites a decision nobody made.
Fix a poisoned sessionRemove or correct the bad source. Start fresh if the error has spread.

TipPrefer authoritative sources, label untrusted content and check key claims in code or docs.

Finding the right code

how the agent decides what to read

Grep or semantic search

rg -n "retryPayment"Find a known name, route or error text
Semantic search over an index.Find code by what it does, not its name
yesnothe index can lag the code

TipUse semantic search to orient and exact search for names, then read the source.

TrapSearch results guide you. They don't prove what the code does now.

Repo maps

Say what a repo map holdsFiles, key symbols and signatures, but no function bodies.
Give Aider's repo map more roomaider --map-tokens 2048The default is 1k tokens.
Say how Aider fits the map in its budgetIt ranks files by their dependency graph and sends the top ones.

TrapA map is only an index. The agent still reads the exact source before it edits.

Semantic index tradeoffs

Name what it costsUpkeep, stale or near-miss results, and code sent to another service.
Set one up safelySet exclusions and access first, then test it with known queries.

TipIt finds related code when the names differ, and saves sending whole folders.

TrapChunking can split a definition from the context it needs.

Explore an unfamiliar repo

Orient before searchingRead the docs, folder tree and build files, then list likely modules.
Narrow to one code pathIts interface, code, nearest tests and one caller per boundary.
Settle a clash between sourcesCurrent source and tests beat comments and old design notes.

TipBefore the first edit, have the agent sum up its evidence, assumptions and test plan.

Docs, MCP & skills

current docs, outside tools and reusable workflows

Current library docs

Stop the agent mixing up versionsTell it which library and version the project uses.
Give the agent current docsAttach the official page, or use a docs MCP server or browser tool.
Fetch a site's docs index for agentscurl -s <docs-site>/llms.txtIt's Markdown, and only an H1 with the project name is required.

TipFresh docs cut made-up APIs, but compiling and running tests is the stronger check.

Trapllms.txt is an index, not the truth. It can be stale, and not every tool reads it.

MCP servers

Say what MCP isA standard way for AI apps to find and call outside tools.
Connect a server to Claude Codeclaude mcp add <name> -- <command>
Pick servers worth addingSource control, issue tracker, internal docs, observability and read-only DB schemas.
Roll out a new server safelyStart read-only, and keep prod access separate from dev.

TrapMCP doesn't make a connection safe. You still need auth, limited actions and logs.

Design MCP tools

Say how much room tool definitions takeIn one Anthropic example, 58 tools used about 55K tokens upfront.
Merge related toolsOne schedule_event tool, not separate list and create tools.

TrapOverlapping tools with vague names cause wrong calls. A small trusted toolbox often does better.

Commands and skills

Say what a skill packagesA repeatable workflow with instructions, templates and scripts.
Create a Claude Code skill.claude/skills/qa/SKILL.mdIt adds /qa, and it can load on its own when relevant.
Know where custom commands went.claude/commands/qa.mdCommands merged into skills. This file also adds /qa.
Know when to make oneIt's frequent, stable and needs the same safeguards each time.
Explain progressive disclosureOnly its description loads upfront. The rest loads when the agent picks it.

TrapDon't put required policy in a skill. It may never load.

AI-legible code

a codebase the agent can read and check

AI-legible repos

Say what makes a repo AI-legibleClear names, small modules, typed interfaces, current docs, reliable tests and standard commands.
Name what makes an agent guessHidden setup, duplicate patterns, vague names and stale docs.
Say what a README gives the agentA starting map of the project, its layout and how to run checks.

TipA README tells the agent where to look. It doesn't replace reading the source.

Types, names and tests

Say how types help an agentThey spell out the contract, and the compiler flags a breaking change.
Say why small modules helpThey fit the window, and search finds the owning file.
Name things so search worksUse the same domain terms in code, tests and docs.
Write tests that teach an agentFocused, clearly named, deterministic and tied to public behavior.

TrapStatic types don't check incoming data. Validate untrusted input at runtime.

Rules for teams & monorepos

keep shared rules accurate as teams and code grow

Keep shared rules accurate

Say how rules files go staleThe code, commands or paths change and the file doesn't.
Keep a rule in step with the codeChange it in the same PR as the workflow it describes.
Catch a stale command automaticallyRun the documented commands in CI and check the links.
Decide what goes in GitCommit shared rules, but not secrets or personal preferences.
Review a rule changeSay why it's needed, which tools read it and how you tested it.

TipDelete an obsolete rule. Don't add exceptions around it.

TrapAgents follow these files confidently, so one stale rule can break every task that uses it.

One source for many tools

Pick the shared sourceAGENTS.mdCursor and Copilot read it, and CLAUDE.md can import it.
Serve a tool that can't read itGenerate its file, or add a thin file that points to the source.
Fail CI when a generated copy driftsgit diff --exit-codeRun it after regenerating the files.

TrapThe same words can act differently in each tool. Test sample tasks in every one.

Monorepos and many teams

Start a task in one packageLoad its public interfaces, its tests and one approved example.
Test one package, not the whole repopnpm --filter api test
Govern context across teamsCentral policy for tools and secrets. Teams own their folders' rules.

TipCheck links, commands and forbidden content in CI, and give teams templates and size limits.

TrapA team's rule must never weaken a central control.

Secrets & prompt injection

keep keys out, and treat outside text as hostile

Keep secrets out of context

Say how a secret in a rules file leaksThrough Git history, logs, chat records, indexes or a provider breach.
Show the agent a credential safelyName the env var and show a placeholder, never the value.
Keep a file out of Cursor's AI features.cursorignore
Give an agent credentialsShort-lived and least-privilege. The model never sees the value.
Handle a secret that reached the contextRotate it first. Then find where it may be stored.

TrapDeleting the line doesn't delete the secret. Copies stay in history, logs and chat records.

Prompt injection

Name where injected text comes fromRules files, retrieved docs and web pages, and MCP tool results.
Enforce security outside the promptLeast-privilege tools, a sandbox and limited network access.
Gate risky actionsRequire approval for writes and data export.

TipThe lethal trifecta is private data, untrusted input and a way to send data out. Never give one agent all three.

TrapAssume the model may follow hostile text. Text must never grant itself permission.

Cost, caching & evals

spend tokens well, and prove a change helps

Audit and budget tokens

Audit where a session's tokens wentSplit them into standing context, conversation and work output.
See what fills Claude Code's window/context
Get exact counts from the APIRead the usage field on each response.

TrapA big token count isn't waste if the work comes out right. Judge cost next to success and retries.

Prompt caching

Order context for the cacheStable parts first, like tools and rules. The task goes last.
Say what breaks the cacheAny change. Everything after it is processed again.
Recall Anthropic's cache numbersEntries last 5 minutes by default. Cached reads cost a tenth of the base input price.

TrapA cache isn't a privacy boundary. Sensitive data needs the same protection as before.

Prove a context change helps

Build the test setVersioned tasks from real work, with a start state and expected result.
Compare fairlyA baseline against one change at a time, several runs each.
Measure each runSuccess, retries, stray edits, tokens, latency and review time.
Pick what to fix firstThe biggest repeated failures, like setup, test commands and docs.

TipOne study found AGENTS.md files didn't generally raise success, but added over 20% to cost.

TrapAdd an index, MCP server or skill only for a measured gap, with an owner to maintain it.

Found this useful? Pass it on.
Pro · $10/mo

This sheet stays free. With Pro, you can:

  • Every answer on this sheet. Read the full answer to all 49 questions it links, not just the 7 free ones.
  • My sheet. The cards you star and the ones you miss in Quiz me, from every sheet, on one page to quiz and print.
  • PDFs. Download this sheet and My sheet, laid out for A4, with every question a link to its answer.
  • The rest of Pro. Every answer in the question library, and 1,000 AI credits a month.