Context Engineering
Context
Context engineering is the practice of supplying relevant, optimized information to AI coding agents to improve their awareness and output quality. It's distinct from prompt engineering:
|
Prompt Engineering |
Context Engineering |
| Focus |
The instruction you type |
What the model has access to under the hood |
| Scope |
Single conversation turn |
Persistent across sessions |
| Output |
Refined phrasing |
Structured knowledge and tool access |
| Analogy |
Telling a colleague what to do |
Giving a new hire all the docs, codebase knowledge, and tools they need |
"Without context, no amount of clever prompting will get you a reliable answer."
— Guy Gur-Ari, Augment Code
"The core best practice is to treat context like code: explicit, consistent, and testable."
— LeadDev, What is Context Engineering
The Context Balance Problem
Context is a double-edged sword:
Too little context Too much context
────────────────── ────────────────
Generic boilerplate answers Confused, unfocused answers
Ignores your conventions Bloated context window
Misses domain knowledge Wasted tokens / cost
Needs constant re-explanation Slow responses
The goal: give agents exactly what they need — no more, no less — for the task at hand.
What Belongs in Context
The Seven Context Categories (LeadDev)
| Category |
Examples |
Format |
| System behaviors |
Codebase conventions, coding standards, architectural patterns |
Markdown, code snippets |
| System architecture |
DB schemas, service map, deployment topology, environment config |
Markdown, JSON, YAML |
| Code events |
Recent commits, open PRs, review threads, changelogs |
Plain text, structured JSON |
| Error information |
Stack traces, build output, linter warnings, incident tickets |
Plain text, JSON |
| Rationale |
ADRs, design docs, chat history summaries, meeting notes |
Markdown |
| Business rules |
Compliance policies, SLAs, feature flag states, operating procedures |
Markdown, YAML |
| Team behaviors |
Common workflows, naming conventions, PR checklist, branching strategy |
Markdown |
Priority rules
ALWAYS include:
✅ Coding conventions (naming, file structure, patterns used)
✅ The specific files/modules being changed
✅ Acceptance criteria or task description
✅ Relevant error messages or test failures
INCLUDE when relevant:
✅ Related ADRs (why this was built this way)
✅ API contracts or schema definitions
✅ Team-specific processes (PR checklist, deploy steps)
EXCLUDE:
❌ Entire codebase dumps (use targeted file references instead)
❌ Unrelated modules or services
❌ Old, superseded documentation
❌ Verbose logs when a summary is enough
Repo-Level Context Files
The most impactful context engineering investment is a well-written repo-level context file. Each AI agent reads a specific file at the start of every session:
| Agent |
File |
Location |
| Claude Code |
CLAUDE.md |
Repo root (or ~/.claude/CLAUDE.md for global) |
| Codex CLI |
AGENTS.md |
Repo root |
| GitHub Copilot |
.github/copilot-instructions.md |
Repo root |
| Cursor |
.cursorrules |
Repo root |
What to put in a repo context file
# Project Context — <Project Name>
## What this is
<One paragraph: what the system does, who uses it, why it exists>
## Architecture
- **Stack:** <languages, frameworks, databases>
- **Structure:** <monorepo / polyrepo, key directories>
- **Services:** <list of main services and their purposes>
- **Deployment:** <how it deploys, environments>
## Coding conventions
- **Naming:** <camelCase, snake_case, file naming patterns>
- **Patterns:** <DI container used, error handling pattern, logging pattern>
- **Testing:** <unit test framework, where tests live, coverage target>
- **Commits:** <conventional commits, squash on merge, etc.>
## Key constraints
- <"Never modify X without Y">
- <"Always use the internal HTTP client, not fetch directly">
- <"Feature flags are required for all user-facing changes">
## How to run
- **Dev:** `<command>`
- **Test:** `<command>`
- **Lint:** `<command>`
## Key files to know
- `<path>` — <what it is>
- `<path>` — <what it is>
## Out of scope for this agent
- <"Don't touch the legacy billing module">
- <"Don't regenerate migrations — ask a human first">
Anti-patterns in context files
❌ "Please be helpful and accurate" — meaningless filler
❌ Pasting the entire README verbatim
❌ Listing every file in the repo
❌ Using jargon without definition ("use the standard pattern" — what pattern?)
❌ Outdated information that hasn't been maintained
✅ Specific conventions with examples
✅ Explicit constraints ("never", "always")
✅ Key file paths with one-line descriptions
✅ Updated when architecture changes
Just-in-Time Context with MCP
Instead of front-loading everything, use MCP to give agents context at the moment they need it:
Static context (always loaded) Just-in-time context (via MCP)
─────────────────────────── ──────────────────────────────
Coding conventions The specific Jira ticket being worked on
Architecture overview The Confluence page for this feature
Team workflows The current sprint's open issues
Key constraints Recent commits to the affected file
The runbook for the service being changed
MCP servers that provide context:
| MCP Server |
Context it provides |
When to use |
github-mcp-server |
PRs, commits, issues, reviews |
Code changes, code review, debugging |
jira-mcp |
Tickets, sprints, acceptance criteria |
Planning, refinement, implementation |
confluence-mcp |
Specs, ADRs, runbooks, docs |
Architecture decisions, on-call, documentation |
filesystem-mcp |
Local files, configs, schemas |
Any file-aware task |
postgres-mcp / sqlite-mcp |
Schema, sample data, query results |
Data modeling, migrations, debugging |
The sub-agent pattern for large contexts:
Instead of one agent with 200k tokens of context:
Orchestrator agent
→ lightweight catalog index
→ spawns Sub-agent A (only the files it needs)
→ spawns Sub-agent B (only the service docs it needs)
→ spawns Sub-agent C (only the error logs it needs)
→ aggregates results
Each sub-agent has a lean, focused context. Prevents confusion and controls costs.
Skill Files as Context Engineering
The SKILL.md files in this library are a form of context engineering — they define what the agent knows about a domain, what to do, and how to respond. When writing a new skill:
Context engineering principles applied to SKILL.md:
| Principle |
In a SKILL.md |
| Relevant, not exhaustive |
Include only what the agent needs for this specific skill |
| Structured format |
Use consistent headers: Context, Steps, Output Template, Agent Instructions |
| Testable |
Triggers should be specific enough to avoid false positives |
| Versioned |
Track changes in git; update when practices evolve |
| Just enough |
Avoid pasting full frameworks — reference them, apply them |
| Explicit constraints |
"Agent should NOT X" is as important as "Agent should Y" |
Testing Your Context
Treat context like code — test it, iterate on it.
Evaluation checklist
□ Does the agent correctly follow naming conventions without being reminded?
□ Does the agent avoid the explicitly excluded areas?
□ Are responses specific to the codebase, not generic?
□ Does the agent cite the right ADRs or docs when relevant?
□ Does the agent produce code that passes lint/tests on first attempt?
□ Does the agent ask for clarification on genuinely ambiguous requests?
□ Does the agent stay within its defined scope?
Red flags (context is underperforming)
⚠️ Agent uses different naming conventions than the codebase
⚠️ Agent suggests patterns the team explicitly deprecated
⚠️ Agent asks for information that's in the context file
⚠️ Responses feel generic, not project-specific
⚠️ Agent repeatedly hits the same error in the same module
Red flags (context is overloaded)
⚠️ Agent contradicts itself mid-response
⚠️ Responses are slower than expected
⚠️ Agent cites irrelevant sections
⚠️ Token costs are unexpectedly high
⚠️ "Lost in the middle" — ignores content at the center of a long context
Context Engineering Maturity Levels
| Level |
What you have |
Impact |
| 0 — None |
No context files, paste everything manually |
Generic answers, constant repetition |
| 1 — Repo file |
CLAUDE.md / AGENTS.md with conventions and architecture |
Agent follows your patterns |
| 2 — Structured |
Context file + scoped MCP for Jira, Confluence, GitHub |
Answers grounded in real work items |
| 3 — Just-in-time |
Sub-agents with targeted context, RAG for large doc sets |
Precise, cost-efficient, scalable |
| 4 — Tested |
Context evaluated with golden examples, updated on each arch change |
Trusted, consistent, production-quality |
Agent Instructions
When applying this skill, the agent should:
- Ask what the user is trying to improve (agent output quality, system prompt, context file, or MCP setup)
- Audit the existing context (if provided) against the priority rules and anti-patterns above
- Generate or improve the appropriate context file (
CLAUDE.md, AGENTS.md, copilot-instructions.md)
- Recommend which MCP servers would provide just-in-time context for this team's workflow
- Identify context that is missing, stale, or overloaded
- Produce a concise, structured context file with explicit constraints — not a wall of text
References
Source: a53ali/ai-dev — distributed by TomeVault.
1---2name: context-engineering3description: Design, structure, and optimize the context you give AI coding agents. Covers system prompts, repo-level context files (CLAUDE.md, AGENTS.md, COPILOT-INSTRUCTIONS.md), what to include vs. exclude, MCP as just-in-time context, sub-agent context scoping, and treating context like code — versioned, tested, and reusable. Improves agent trust, speed, and code quality. Grounded in LeadDev and industry practice. Use when this capability is needed.4---56# Context Engineering78## Context910Context engineering is the practice of supplying **relevant, optimized information** to AI coding agents to improve their awareness and output quality. It's distinct from prompt engineering:1112| | Prompt Engineering | Context Engineering |13|---|---|---|14| **Focus** | The instruction you type | What the model has access to under the hood |15| **Scope** | Single conversation turn | Persistent across sessions |16| **Output** | Refined phrasing | Structured knowledge and tool access |17| **Analogy** | Telling a colleague what to do | Giving a new hire all the docs, codebase knowledge, and tools they need |1819> *"Without context, no amount of clever prompting will get you a reliable answer."* 20> — Guy Gur-Ari, Augment Code2122> *"The core best practice is to treat context like code: explicit, consistent, and testable."* 23> — LeadDev, What is Context Engineering2425---2627## The Context Balance Problem2829Context is a double-edged sword:3031```32Too little context Too much context33────────────────── ────────────────34Generic boilerplate answers Confused, unfocused answers35Ignores your conventions Bloated context window36Misses domain knowledge Wasted tokens / cost37Needs constant re-explanation Slow responses38```3940**The goal:** give agents exactly what they need — no more, no less — for the task at hand.4142---4344## What Belongs in Context4546### The Seven Context Categories (LeadDev)4748| Category | Examples | Format |49|----------|----------|--------|50| **System behaviors** | Codebase conventions, coding standards, architectural patterns | Markdown, code snippets |51| **System architecture** | DB schemas, service map, deployment topology, environment config | Markdown, JSON, YAML |52| **Code events** | Recent commits, open PRs, review threads, changelogs | Plain text, structured JSON |53| **Error information** | Stack traces, build output, linter warnings, incident tickets | Plain text, JSON |54| **Rationale** | ADRs, design docs, chat history summaries, meeting notes | Markdown |55| **Business rules** | Compliance policies, SLAs, feature flag states, operating procedures | Markdown, YAML |56| **Team behaviors** | Common workflows, naming conventions, PR checklist, branching strategy | Markdown |5758### Priority rules5960```61ALWAYS include:62 ✅ Coding conventions (naming, file structure, patterns used)63 ✅ The specific files/modules being changed64 ✅ Acceptance criteria or task description65 ✅ Relevant error messages or test failures6667INCLUDE when relevant:68 ✅ Related ADRs (why this was built this way)69 ✅ API contracts or schema definitions70 ✅ Team-specific processes (PR checklist, deploy steps)7172EXCLUDE:73 ❌ Entire codebase dumps (use targeted file references instead)74 ❌ Unrelated modules or services75 ❌ Old, superseded documentation76 ❌ Verbose logs when a summary is enough77```7879---8081## Repo-Level Context Files8283The most impactful context engineering investment is a well-written **repo-level context file**. Each AI agent reads a specific file at the start of every session:8485| Agent | File | Location |86|-------|------|----------|87| Claude Code | `CLAUDE.md` | Repo root (or `~/.claude/CLAUDE.md` for global) |88| Codex CLI | `AGENTS.md` | Repo root |89| GitHub Copilot | `.github/copilot-instructions.md` | Repo root |90| Cursor | `.cursorrules` | Repo root |9192### What to put in a repo context file9394```markdown95# Project Context — <Project Name>9697## What this is98<One paragraph: what the system does, who uses it, why it exists>99100## Architecture101- **Stack:** <languages, frameworks, databases>102- **Structure:** <monorepo / polyrepo, key directories>103- **Services:** <list of main services and their purposes>104- **Deployment:** <how it deploys, environments>105106## Coding conventions107- **Naming:** <camelCase, snake_case, file naming patterns>108- **Patterns:** <DI container used, error handling pattern, logging pattern>109- **Testing:** <unit test framework, where tests live, coverage target>110- **Commits:** <conventional commits, squash on merge, etc.>111112## Key constraints113- <"Never modify X without Y">114- <"Always use the internal HTTP client, not fetch directly">115- <"Feature flags are required for all user-facing changes">116117## How to run118- **Dev:** `<command>`119- **Test:** `<command>`120- **Lint:** `<command>`121122## Key files to know123- `<path>` — <what it is>124- `<path>` — <what it is>125126## Out of scope for this agent127- <"Don't touch the legacy billing module">128- <"Don't regenerate migrations — ask a human first">129```130131### Anti-patterns in context files132133```134❌ "Please be helpful and accurate" — meaningless filler135❌ Pasting the entire README verbatim136❌ Listing every file in the repo137❌ Using jargon without definition ("use the standard pattern" — what pattern?)138❌ Outdated information that hasn't been maintained139140✅ Specific conventions with examples141✅ Explicit constraints ("never", "always")142✅ Key file paths with one-line descriptions143✅ Updated when architecture changes144```145146---147148## Just-in-Time Context with MCP149150Instead of front-loading everything, use MCP to give agents context *at the moment they need it*:151152```153Static context (always loaded) Just-in-time context (via MCP)154─────────────────────────── ──────────────────────────────155Coding conventions The specific Jira ticket being worked on156Architecture overview The Confluence page for this feature157Team workflows The current sprint's open issues158Key constraints Recent commits to the affected file159 The runbook for the service being changed160```161162**MCP servers that provide context:**163164| MCP Server | Context it provides | When to use |165|------------|--------------------|-|166| `github-mcp-server` | PRs, commits, issues, reviews | Code changes, code review, debugging |167| `jira-mcp` | Tickets, sprints, acceptance criteria | Planning, refinement, implementation |168| `confluence-mcp` | Specs, ADRs, runbooks, docs | Architecture decisions, on-call, documentation |169| `filesystem-mcp` | Local files, configs, schemas | Any file-aware task |170| `postgres-mcp` / `sqlite-mcp` | Schema, sample data, query results | Data modeling, migrations, debugging |171172**The sub-agent pattern for large contexts:**173174Instead of one agent with 200k tokens of context:175```176Orchestrator agent177 → lightweight catalog index178 → spawns Sub-agent A (only the files it needs)179 → spawns Sub-agent B (only the service docs it needs)180 → spawns Sub-agent C (only the error logs it needs)181 → aggregates results182```183Each sub-agent has a lean, focused context. Prevents confusion and controls costs.184185---186187## Skill Files as Context Engineering188189The SKILL.md files in this library are a form of context engineering — they define what the agent knows about a domain, what to do, and how to respond. When writing a new skill:190191**Context engineering principles applied to SKILL.md:**192193| Principle | In a SKILL.md |194|-----------|--------------|195| Relevant, not exhaustive | Include only what the agent needs for this specific skill |196| Structured format | Use consistent headers: Context, Steps, Output Template, Agent Instructions |197| Testable | Triggers should be specific enough to avoid false positives |198| Versioned | Track changes in git; update when practices evolve |199| Just enough | Avoid pasting full frameworks — reference them, apply them |200| Explicit constraints | "Agent should NOT X" is as important as "Agent should Y" |201202---203204## Testing Your Context205206Treat context like code — test it, iterate on it.207208### Evaluation checklist209210```211□ Does the agent correctly follow naming conventions without being reminded?212□ Does the agent avoid the explicitly excluded areas?213□ Are responses specific to the codebase, not generic?214□ Does the agent cite the right ADRs or docs when relevant?215□ Does the agent produce code that passes lint/tests on first attempt?216□ Does the agent ask for clarification on genuinely ambiguous requests?217□ Does the agent stay within its defined scope?218```219220### Red flags (context is underperforming)221222```223⚠️ Agent uses different naming conventions than the codebase224⚠️ Agent suggests patterns the team explicitly deprecated225⚠️ Agent asks for information that's in the context file226⚠️ Responses feel generic, not project-specific227⚠️ Agent repeatedly hits the same error in the same module228```229230### Red flags (context is overloaded)231232```233⚠️ Agent contradicts itself mid-response234⚠️ Responses are slower than expected235⚠️ Agent cites irrelevant sections236⚠️ Token costs are unexpectedly high237⚠️ "Lost in the middle" — ignores content at the center of a long context238```239240---241242## Context Engineering Maturity Levels243244| Level | What you have | Impact |245|-------|--------------|--------|246| **0 — None** | No context files, paste everything manually | Generic answers, constant repetition |247| **1 — Repo file** | CLAUDE.md / AGENTS.md with conventions and architecture | Agent follows your patterns |248| **2 — Structured** | Context file + scoped MCP for Jira, Confluence, GitHub | Answers grounded in real work items |249| **3 — Just-in-time** | Sub-agents with targeted context, RAG for large doc sets | Precise, cost-efficient, scalable |250| **4 — Tested** | Context evaluated with golden examples, updated on each arch change | Trusted, consistent, production-quality |251252---253254## Agent Instructions255256When applying this skill, the agent should:2572581. Ask what the user is trying to improve (agent output quality, system prompt, context file, or MCP setup)2592. Audit the existing context (if provided) against the priority rules and anti-patterns above2603. Generate or improve the appropriate context file (`CLAUDE.md`, `AGENTS.md`, `copilot-instructions.md`)2614. Recommend which MCP servers would provide just-in-time context for this team's workflow2625. Identify context that is missing, stale, or overloaded2636. Produce a concise, structured context file with explicit constraints — not a wall of text264265---266267## References268269- LeadDev: [What is Context Engineering](https://leaddev.com/ai/what-is-context-engineering)270- LeadDev: [AI won't fix developer productivity unless you fix context first](https://leaddev.com/technical-direction/ai-wont-fix-developer-productivity-unless-you-fix-context-first)271- Anthropic: [Claude Code — CLAUDE.md best practices](https://docs.anthropic.com/en/docs/claude-code)272- OpenAI / Codex: [AGENTS.md specification](https://openai.com/codex)273- Model Context Protocol: [MCP servers for context](https://modelcontextprotocol.io)274- Andrej Karpathy: ["Context engineering" — the new prompt engineering](https://twitter.com/karpathy)275- Mrinal Wadhwa (Autonomy): Sub-agent context scoping pattern276277---278> Source: [a53ali/ai-dev](https://github.com/a53ali/ai-dev) — distributed by [TomeVault](https://tomevault.io).279<!-- tomevault:4.0:skill_md:2026-06-16 -->