Context Engineering Guide
The complete guide to context engineering for AI coding agents. Learn what context engineering is, why it matters more than prompt engineering, how to configure every major AI tool's instruction files, and how to build a unified strategy that works across Cursor, GitHub Copilot, Claude Code, Gemini CLI, and Windsurf.
What Is Context Engineering?
Context engineering is the practice of designing the entire information ecosystem that an AI model operates within — not just the prompt you type, but everything the model can see when it processes your request. This includes system instructions, codebase files, git history, dependency information, conversation history, and more.
Key insight: The quality of what the model sees matters more than the quality of how you ask. A developer with clean, well-structured context on a weaker model consistently outperforms one with cluttered context on a stronger model.
Context Engineering vs. Prompt Engineering
Prompt engineering focuses on crafting the right question. Context engineering focuses on building the right environment around that question. Think of it this way:
Prompt Engineering (crafting the email):
"Write a React component that displays user
profiles in a grid with Tailwind CSS..."
Context Engineering (building the briefing package):
System instructions → Your project conventions
Codebase context → Existing component patterns
Dependencies → React 19, Tailwind v4, TypeScript
Architecture → App Router, Server Components
Git history → Recent refactoring decisions
Test patterns → Vitest + Testing Library setup
Then the prompt: "Add a user profile grid to the dashboard"
With proper context engineering, the prompt itself can be simple. The AI already knows your stack, your conventions, and your patterns. A February 2026 peer-reviewed study of 9,649 experiments confirmed this: the context surrounding a prompt influences output quality more than the prompt itself.
Why Context Engineering Matters Now
AI coding has reached a tipping point. Over 92% of US-based developers use AI coding tools daily, and roughly 42% of committed code is now AI-generated or AI-assisted. But there's a trust gap: developer trust in AI-generated code dropped from 40% to 29% between 2023 and 2025, even as usage skyrocketed.
Most AI coding failures don't come from model limitations — they come from poor context management. The model generates generic boilerplate because it doesn't know your project's conventions. It picks the wrong patterns because it can't see your architecture. It makes inconsistent decisions because each conversation starts from scratch.
Context engineering solves this by giving AI agents persistent, structured knowledge about your project. Every major AI coding tool now supports some form of configuration file for this purpose.
The Evolution
2023 Prompt Engineering
→ Carefully craft each individual prompt
→ Copy-paste instructions into every conversation
→ Results vary wildly between sessions
2025 Context Engineering
→ Configure persistent project context
→ AI automatically loads relevant conventions
→ Consistent results across every interaction
2026 Agentic Engineering
→ AI agents orchestrate multi-step workflows
→ Context files define roles, tools, and guardrails
→ Humans direct; agents execute with full context
The Context Stack
Every AI coding agent assembles a context window from multiple sources before generating a response. Understanding these layers helps you control which information reaches the model and how it's prioritized.
The Eight Layers
Layer 1 — System Instructions (you control this)
AGENTS.md, CLAUDE.md, .cursor/rules/, .windsurfrules,
copilot-instructions.md, GEMINI.md
→ Project conventions, coding standards, architecture
Layer 2 — Codebase Context (you influence this)
Files the agent can see or has indexed
→ Existing patterns, implementations, types
Layer 3 — Git History (you influence this)
Recent commits, diffs, branch context
→ Prevents undoing intentional decisions
Layer 4 — Dependencies (you influence this)
package.json, lock files, framework versions
→ Ensures compatible API usage
Layer 5 — Conversation History (tool-managed)
The current chat session and prior messages
→ Maintains continuity within a task
Layer 6 — Retrieved Context (tool-managed)
Documentation lookups, web search, RAG results
→ Supplements knowledge beyond training data
Layer 7 — Tool Outputs (tool-managed)
Linter results, test output, build logs, terminal
→ Grounds the agent in real project state
Layer 8 — Auto-Memory (tool-managed)
Learned patterns from corrections and feedback
→ Adapts over time without manual updates
What You Control
Layer 1 is where you have the most direct influence — your configuration files are loaded automatically on every interaction. This guide focuses primarily on this layer. Layers 2–4 are partially under your control through how you organize your codebase, write commit messages, and maintain dependencies. Layers 5–8 are managed by the AI tool itself.
The attention budget: LLMs have a finite context window. Every rule, file, and instruction you add competes for the model's attention. Research shows LLMs attend most to information at the beginning and end of the context window, with reduced attention to the middle (the "Lost in the Middle" effect). Keep your most critical instructions concise and positioned early.
Context Quality Signals
Signs of good context engineering versus poor context engineering:
Good Context:
✓ AI follows your naming conventions without reminders
✓ Generated code matches existing patterns in your codebase
✓ AI uses the correct framework APIs and versions
✓ Tests follow your project's testing patterns
✓ Imports use your project's path aliases
Poor Context:
✗ AI generates generic code that doesn't match your style
✗ Every conversation requires re-explaining your stack
✗ AI uses deprecated APIs or wrong framework versions
✗ Generated patterns conflict with existing architecture
✗ You constantly correct the same mistakes
The Config File Landscape
Every major AI coding tool reads configuration files from your project to build its context. The challenge: each tool has its own file format and conventions. This section is a unified reference for all of them.
Quick Reference
Tool Config File Location
───────────── ────────────────────────── ──────────────────────────
Cross-tool AGENTS.md Project root (+ subdirs)
Claude Code CLAUDE.md ~/, project root, subdirs
Cursor .cursor/rules/*.mdc .cursor/rules/
GitHub Copilot copilot-instructions.md .github/
Windsurf .windsurfrules Project root
Gemini CLI GEMINI.md ~/, project root, subdirs
AGENTS.md — The Cross-Tool Standard
AGENTS.md is an open standard governed by the Linux Foundation's Agentic AI Foundation. It's designed to be a "README for AI agents" — a single file that any compliant tool can read. It has been adopted across 60,000+ repositories and is natively supported by Claude Code, Cursor, GitHub Copilot, Codex CLI, Windsurf, Gemini CLI, Amp, Devin, and 30+ other tools.
# AGENTS.md
## Project Overview
E-commerce platform built with Next.js 15, TypeScript,
Prisma ORM, and Stripe for payments.
## Build & Run
- Install: `pnpm install`
- Dev server: `pnpm dev`
- Build: `pnpm build`
- Tests: `pnpm test` (Vitest)
## Architecture
- `src/app/` — Next.js App Router pages and layouts
- `src/components/` — Shared React components
- `src/lib/` — Utilities, database client, API helpers
- `src/actions/` — Server Actions for mutations
- `prisma/` — Database schema and migrations
## Code Style
- Use TypeScript strict mode. Never use `any`.
- Prefer Server Components. Use `"use client"` only when
the component needs browser APIs or event handlers.
- Use named exports for components and functions.
- Use Tailwind CSS v4 for styling. No CSS-in-JS.
## Testing
- Write tests for all new features and bug fixes.
- Use Vitest + Testing Library for component tests.
- Place test files adjacent to source: `*.test.ts(x)`.
Format: Plain Markdown, no required schema. Limits: None imposed by the spec (keep it practical — under 1,000 lines). Subdirectories: Place additional AGENTS.md files in subdirectories for package-specific or module-specific instructions in monorepos. Agents read the nearest file in the directory tree.
CLAUDE.md — Claude Code
CLAUDE.md is the configuration file for Anthropic's Claude Code CLI. It follows a hierarchical loading system where files at multiple levels are merged together. For a deep dive, see the Claude Skills Guide.
# CLAUDE.md hierarchy (all are loaded and merged)
~/.claude/CLAUDE.md # Global preferences (all projects)
./CLAUDE.md # Project-level (team-shared, git-tracked)
./.claude.local.md # Local overrides (gitignored, personal)
./.claude/rules/*.md # Modular topic-specific rules
# CLAUDE.md
## Commands
- Install: `pnpm install`
- Dev: `pnpm dev` (runs on port 3000)
- Test all: `pnpm test`
- Test single: `pnpm test -- path/to/file.test.ts`
- Lint: `pnpm lint`
- Type check: `pnpm typecheck`
## Architecture
App Router project. Pages in src/app/, components in
src/components/, server actions in src/actions/.
## Code Style
- TypeScript strict mode, never use `any`
- Named exports only, no default exports
- Use `import type` for type-only imports
- Server Components by default; `"use client"` only when needed
## Key Files
- src/lib/db.ts — Prisma client singleton
- src/lib/auth.ts — Authentication helpers
- src/middleware.ts — Auth and redirect logic
Best practice: The Commands section is the most important — without it, Claude wastes tokens guessing your build system. Structure matters more than size. Use imperative instructions ("Always use...") rather than descriptions ("This project uses...").
.cursor/rules/*.mdc — Cursor
Cursor uses a directory of .mdc files with YAML frontmatter for fine-grained control over when rules activate. This is the most feature-rich system, supporting glob-based activation, AI-requested activation, and manual @-mention activation. For a deep dive, see the Cursor Rules Guide.
# Cursor rules structure
.cursor/rules/
├── project-standards.mdc # alwaysApply: true
├── typescript-patterns.mdc # globs: "*.ts,*.tsx"
├── react-components.mdc # globs: "src/components/**/*.tsx"
├── api-routes.mdc # globs: "src/app/api/**/*.ts"
└── testing.mdc # globs: "*.test.ts,*.spec.ts"
---
description: "TypeScript coding standards"
globs: "*.ts,*.tsx"
alwaysApply: false
---
# TypeScript Standards
- Use strict mode. Never use `any` — use `unknown` and narrow.
- Prefer `interface` over `type` for object shapes.
- Use explicit return types on exported functions.
- Use `import type` for type-only imports.
- Group imports: external → internal → types.
Unique features: Cursor also reads AGENTS.md from your project root. Precedence order: Team Rules > Project Rules (.mdc) > User Rules > AGENTS.md.
Generate rules instantly: Use the Cursor Rules Generator to create .mdc files with a visual editor, curated templates, and proper frontmatter configuration.
copilot-instructions.md — GitHub Copilot
GitHub Copilot reads custom instructions from a Markdown file in the .github/ directory. It also supports path-specific instruction files for different parts of the codebase. For a deep dive, see the Copilot Instructions Guide.
# Copilot instructions structure
.github/
├── copilot-instructions.md # Repository-wide
└── instructions/
├── react-components.instructions.md # Path-specific
└── api-routes.instructions.md # Path-specific
# .github/copilot-instructions.md
## Project
Next.js 15 e-commerce app with TypeScript, Prisma, and Stripe.
## Conventions
- Use TypeScript strict mode. Never use `any`.
- Prefer Server Components. Mark client components with
`"use client"` only when they need interactivity.
- Use named exports. No default exports.
- Use Tailwind CSS v4 utility classes for styling.
## Testing
- Use Vitest and Testing Library.
- Place test files next to source files.
- Name test files `*.test.ts` or `*.test.tsx`.
Limits: Code review only reads the first 4,000 characters. Keep instructions concise. Scope: Applies across editor completions, Chat, pull request reviews, and Copilot Workspace. Also reads AGENTS.md from the project root.
.windsurfrules — Windsurf
Windsurf uses a single .windsurfrules file at the project root that acts as a system prompt for Cascade, Windsurf's AI agent. For a deep dive, see the Windsurf Rules Guide.
# .windsurfrules
## Project
Next.js 15 app with TypeScript, Prisma ORM, and Stripe.
## Architecture
- src/app/ — App Router pages and API routes
- src/components/ — Shared UI components
- src/lib/ — Utilities, database, and API helpers
## Standards
- TypeScript strict mode. No `any` types.
- Server Components by default.
- Named exports only.
- Tailwind CSS v4 for styling.
- Vitest + Testing Library for tests.
Limits: 6,000 characters/tokens across global and workspace rules combined. Scope: Loaded at startup and injected into every Cascade interaction. Also reads AGENTS.md.
GEMINI.md — Gemini CLI
Gemini CLI uses a hierarchical system similar to CLAUDE.md, loading GEMINI.md files from global, project, and subdirectory levels. For a deep dive, see the Gemini Gems & Skills Guide.
# GEMINI.md hierarchy
~/.gemini/GEMINI.md # Global preferences
./GEMINI.md # Project-level
./packages/api/GEMINI.md # Sub-directory (monorepo)
# Useful commands
/memory show # See all loaded context
/memory reload # Reload after editing
/memory add "instruction" # Append to global file
Unique features: Supports @file.md import syntax for modular context. Respects .gitignore and .geminiignore when scanning. The default filename is configurable via settings.json.
Compatibility Matrix
AGENTS.md Own Format Hierarchy Glob Matching
───────── ────────── ───────── ─────────────
Claude Code ✓ reads CLAUDE.md 3 levels ✗
Cursor ✓ reads .mdc files 4 levels ✓ (frontmatter)
GitHub Copilot ✓ reads .github/ 2 levels ✓ (path-specific)
Windsurf ✓ reads .windsurfrules 2 levels ✗
Gemini CLI ✓ reads GEMINI.md 3 levels ✗
Codex CLI ✓ reads AGENTS.md — ✗
Amp ✓ reads — — ✗
Devin ✓ reads — — ✗
Writing Effective Context Files
A well-structured context file dramatically improves AI output quality. A poorly written one wastes tokens and can actively degrade performance. These principles apply regardless of which tool or file format you use.
Imperative Over Descriptive
Anthropic's research shows imperative instructions ("Always do X") have a 94% application rate, while descriptive statements ("This project uses X") achieve only 73%. Frame your rules as clear commands, not descriptions.
# Descriptive (73% application rate)
This project uses TypeScript with strict mode.
The team prefers interfaces over type aliases.
We use CSS Modules for component styling.
# Imperative (94% application rate)
Always use TypeScript strict mode. Never use `any`.
Prefer `interface` over `type` for object shapes.
Use CSS Modules for all component styling.
Import styles as `import styles from './Name.module.css'`.
The Primacy Problem
LLMs attend most strongly to information at the beginning and end of the context window, with weaker attention to the middle. This is called the "Lost in the Middle" effect. Structure your files accordingly:
# Structure your files with priority positioning
## Commands (FIRST — most critical)
- Install: `pnpm install`
- Dev: `pnpm dev`
- Test: `pnpm test`
## Architecture (high priority)
...
## Code Style (high priority)
...
## Nice-to-Have Conventions (lower priority — middle)
...
## Critical Warnings (LAST — also high attention)
- Never commit .env files
- Never delete migration files
- Always run tests before committing
Compression: Say Only What Tools Can't
Don't restate what your linter, formatter, or type checker already enforces. Context files should carry persistent judgment — the things that can't be expressed by automated tools.
# Wasteful — your linter/formatter already handles this
- Use 2-space indentation
- Add semicolons at the end of statements
- Use single quotes for strings
- Maximum line length: 80 characters
# Valuable — judgment that tools can't enforce
- Prefer Server Components. Only add "use client" when
the component needs browser APIs or event handlers.
- Use optimistic updates for mutations that affect the
current user's data. Use await for shared state changes.
- When adding a new API route, follow the pattern in
src/app/api/products/route.ts as the canonical example.
The Pink Elephant Problem
Telling an agent what NOT to do often backfires — the negative instruction draws attention to the very pattern you want to avoid. Frame instructions positively.
# Problematic — focuses attention on the wrong pattern
- Do NOT use default exports
- Do NOT use the `any` type
- Do NOT use inline styles
- Do NOT use var for variable declarations
# Better — states the desired behavior directly
- Use named exports for all components and functions
- Use `unknown` with type guards instead of `any`
- Use CSS Modules or Tailwind for all styling
- Use `const` by default, `let` only when reassignment
is needed
Concrete Examples Beat Adjectives
One code example communicates more reliably than five descriptive sentences. When a pattern is critical, show it.
# Vague — open to interpretation
Create well-structured components with proper typing and
clean separation of concerns.
# Concrete — shows exactly what you want
When creating React components, follow this pattern:
```tsx
interface ProfileCardProps {
user: User;
onEdit: (id: string) => void;
}
export const ProfileCard = ({ user, onEdit }: ProfileCardProps) => {
return (
<div className={styles.card}>
<h2>{user.name}</h2>
<button onClick={() => onEdit(user.id)}>Edit</button>
</div>
);
};
```
Reference, Don't Duplicate
Point to canonical files in your codebase rather than copying code into your context files. Copied code goes stale as the codebase evolves; file references stay accurate.
# Fragile — this code will go stale
When creating an API route, use this exact pattern:
[50 lines of copied code...]
# Durable — always refers to the latest version
When creating a new API route, follow the pattern in
`src/app/api/products/route.ts`. This is the canonical
reference for error handling, validation, and response
formatting.
Scope Rules Narrowly
Broad, always-on rules consume token budget on every interaction, even when irrelevant. Use scoping mechanisms when available.
# Broad — loaded even when working on backend code
alwaysApply: true
→ "Use Tailwind CSS v4 utility classes..."
# Scoped — only loaded when editing component files
globs: "src/components/**/*.tsx"
→ "Use Tailwind CSS v4 utility classes..."
# Copilot equivalent — path-specific instructions
.github/instructions/frontend.instructions.md
→ applyTo: "src/components/**"
Single Source of Truth Strategy
If your team uses multiple AI coding tools (or individual members use different ones), maintaining separate configuration files for each tool quickly becomes unsustainable. Edits to one file don't propagate to the others, and instructions drift apart over time.
The Problem
# Maintaining all of these separately is fragile
your-project/
├── AGENTS.md # Codex, Amp, Devin
├── CLAUDE.md # Claude Code
├── .cursor/rules/standards.mdc # Cursor
├── .github/copilot-instructions.md # GitHub Copilot
├── .windsurfrules # Windsurf
└── GEMINI.md # Gemini CLI
# When conventions change, you'd need to update 6 files.
# Inevitably, some fall out of sync.
AGENTS.md as the Universal Base
AGENTS.md is read by virtually every major AI coding tool. Use it as your single source of truth for shared project context — the conventions, architecture, and commands that apply regardless of which tool someone uses.
# Recommended: AGENTS.md as the shared base
your-project/
├── AGENTS.md # Shared base (all tools read this)
├── CLAUDE.md # Claude-specific overrides only
├── .cursor/rules/ # Cursor-specific (glob patterns)
│ └── react-components.mdc # Auto-attaches to .tsx files
└── .github/
└── instructions/
└── api.instructions.md # Copilot path-specific rules
What Goes Where
AGENTS.md (shared by all tools):
✓ Project overview and tech stack
✓ Build, run, and test commands
✓ Architecture and directory structure
✓ Universal coding standards
✓ Key files and entry points
Tool-specific files (only when you need tool-unique features):
✓ Cursor .mdc — glob-based activation patterns
✓ Copilot .instructions.md — path-scoped overrides
✓ CLAUDE.md — Commands section (Claude Code's priority)
✓ GEMINI.md — @imports for modular context
The Symlink Strategy
For tools that require their own named file but don't need different content, you can symlink to AGENTS.md:
# Create AGENTS.md as the source of truth
# Then symlink for tools that need a specific filename
ln -s AGENTS.md CLAUDE.md
ln -s AGENTS.md GEMINI.md
# Now editing AGENTS.md updates all three automatically
# .windsurfrules also reads AGENTS.md natively, no symlink needed
When symlinks don't work: If a tool needs genuinely different content (e.g., CLAUDE.md's Commands section is especially important for Claude Code's behavior), maintain a separate file. Only symlink when the content would be identical.
Layered Strategy for Teams
For teams where members use different editors, use a layered approach:
Layer 1: AGENTS.md (everyone)
→ Project-wide conventions and architecture
→ Version-controlled, reviewed in PRs
→ The single source of truth for project context
Layer 2: Tool-specific configs (per tool)
→ Only contains tool-unique features
→ Cursor: glob patterns, activation modes
→ Copilot: path-specific instruction files
→ Claude: memory hierarchy, local overrides
Layer 3: Personal preferences (per developer)
→ Global user-level config (not project-specific)
→ ~/.claude/CLAUDE.md, Cursor user rules, etc.
→ NOT version-controlled
Real-World Examples
Three complete setups showing how context engineering works in practice, from simple to complex.
Example 1: Solo Developer — Next.js App
A solo developer building a SaaS product. Uses Cursor as their primary editor. Minimal setup, maximum impact.
# Directory structure
my-saas/
├── AGENTS.md # Shared context
├── .cursor/rules/
│ ├── project.mdc # alwaysApply: true
│ ├── components.mdc # globs: "src/components/**"
│ └── database.mdc # agent-requested
├── src/
│ ├── app/
│ ├── components/
│ └── lib/
├── prisma/
└── package.json
# AGENTS.md (kept short — under 50 lines)
## Project
SaaS invoicing app. Next.js 15, TypeScript, Prisma, Stripe.
## Commands
- `pnpm dev` — Start dev server (port 3000)
- `pnpm test` — Run Vitest test suite
- `pnpm db:push` — Push Prisma schema changes
- `pnpm db:studio` — Open Prisma Studio
## Architecture
- src/app/ — App Router (pages, layouts, API routes)
- src/components/ — Shared components (Server by default)
- src/lib/ — Database client, auth, utilities
- src/actions/ — Server Actions for all mutations
- prisma/schema.prisma — Database schema
## Standards
- TypeScript strict. No `any`.
- Server Components by default.
- Server Actions for mutations (no API routes for forms).
- Tailwind CSS v4 for styling. No CSS-in-JS.
Example 2: Frontend Team — Design System
A team of five frontend developers maintaining a component library. Team members use a mix of Cursor, Copilot, and Claude Code. AGENTS.md is the shared base, with Cursor rules for glob-based activation.
# Directory structure
design-system/
├── AGENTS.md # Shared base
├── .cursor/rules/
│ ├── components.mdc # globs: "src/components/**"
│ ├── tokens.mdc # globs: "src/tokens/**"
│ ├── testing.mdc # globs: "*.test.tsx"
│ └── documentation.mdc # agent-requested
├── .github/
│ ├── copilot-instructions.md # Copilot base
│ └── instructions/
│ └── components.instructions.md # Copilot path-specific
├── src/
│ ├── components/
│ │ ├── Button/
│ │ │ ├── Button.tsx
│ │ │ ├── Button.test.tsx
│ │ │ ├── Button.module.css
│ │ │ └── index.ts
│ │ └── ...
│ └── tokens/
├── docs/
└── package.json
# AGENTS.md
## Project
Shared design system component library. React 19,
TypeScript, CSS Modules, Storybook.
## Commands
- `pnpm dev` — Start Storybook (port 6006)
- `pnpm test` — Run Vitest tests
- `pnpm build` — Build library for publishing
- `pnpm lint` — ESLint + Stylelint
## Architecture
- src/components/ — One directory per component
(ComponentName/ComponentName.tsx, index.ts, test, styles)
- src/tokens/ — Design tokens (colors, spacing, typography)
- docs/ — Storybook documentation pages
## Component Pattern
Every component follows this structure:
- ComponentName.tsx — Implementation (see src/components/Button/)
- ComponentName.module.css — Scoped styles
- ComponentName.test.tsx — Unit and integration tests
- index.ts — Named re-export
Follow `src/components/Button/` as the canonical reference.
## Standards
- All components must accept a `className` prop for composition.
- All interactive components must support keyboard navigation.
- All components must have at minimum one unit test.
- Use design tokens from `src/tokens/` — never hardcode values.
- Export types for all component props.
Example 3: Full-Stack Monorepo
A monorepo with separate frontend, backend, and shared packages. Uses nested AGENTS.md files so each package provides its own context.
# Directory structure
platform/
├── AGENTS.md # Root — overall architecture
├── packages/
│ ├── web/
│ │ ├── AGENTS.md # Frontend-specific context
│ │ └── src/
│ ├── api/
│ │ ├── AGENTS.md # Backend-specific context
│ │ └── src/
│ └── shared/
│ ├── AGENTS.md # Shared utilities context
│ └── src/
├── .cursor/rules/
│ └── monorepo.mdc # alwaysApply: true
└── package.json
# Root AGENTS.md
## Project
Multi-package platform with web frontend, REST API, and
shared utilities. Turborepo monorepo with pnpm workspaces.
## Commands
- `pnpm install` — Install all dependencies
- `pnpm dev` — Start all packages in dev mode
- `pnpm build` — Build all packages
- `pnpm test` — Run tests across all packages
## Architecture
- packages/web — Next.js 15 frontend
- packages/api — Express + Prisma backend
- packages/shared — Shared types, utilities, and validators
## Cross-Package Rules
- Shared types live in packages/shared/src/types/
- Never duplicate type definitions across packages.
- Import shared code as `@platform/shared`.
- Database schema changes require a migration file.
# packages/api/AGENTS.md
## Package: API
Express REST API with Prisma ORM and PostgreSQL.
## Commands
- `pnpm dev` — Start API server (port 4000)
- `pnpm test` — Run API tests
- `pnpm db:migrate` — Run Prisma migrations
- `pnpm db:seed` — Seed development data
## Patterns
- Route handlers in src/routes/ (one file per resource)
- Business logic in src/services/ (never in route handlers)
- Validation with Zod schemas in src/schemas/
- Follow src/routes/products.ts as the canonical example
## Standards
- All routes must validate input with Zod before processing.
- All service methods must return typed Result objects.
- All database queries go through service layer, never in routes.
- Write integration tests for every route.
When working in packages/api/, AI agents will read both the root AGENTS.md (overall architecture) and the package-level AGENTS.md (API-specific context), giving them the full picture.
Common Mistakes
The most frequent context engineering pitfalls and how to avoid them.
Overloading Context
Problem:
Massive context files (1,000+ lines of rules) that try
to cover every possible scenario. The model's attention
is spread thin, and critical rules get lost in the noise.
Fix:
Start minimal. Add rules only when you notice repeated
mistakes. A focused 50-line AGENTS.md outperforms a
500-line kitchen-sink file. Remove rules that the AI
already follows without being told.
Duplicating Tool Enforcement
Problem:
Restating rules that your linter, formatter, or type
checker already enforces. These waste tokens without
adding value — the AI's output will be auto-corrected
by the tool regardless.
"Use 2-space indentation" ← Prettier handles this
"Add semicolons" ← ESLint handles this
"Sort imports alphabetically" ← eslint-plugin-import
Fix:
Only include judgment calls that automated tools can't
enforce: architectural decisions, pattern preferences,
domain-specific conventions, and "when to use what."
Descriptive Instead of Imperative
Problem:
Writing context files like README documentation rather
than clear instructions. Description informs but doesn't
direct. The AI may acknowledge the description without
acting on it.
"This project uses React Server Components and follows
the App Router conventions from Next.js 15."
Fix:
Use imperative language that leaves no ambiguity:
"Use Server Components by default. Only add the
'use client' directive when the component needs browser
APIs, event handlers, or React state."
Forgetting Version Control
Problem:
Context files are local-only and not committed to git.
Each team member has different (or missing) context,
causing inconsistent AI output across the team.
Fix:
Commit AGENTS.md, .cursor/rules/, and
.github/copilot-instructions.md to version control.
Treat context file changes like code changes — review
them in pull requests.
Use .claude.local.md (gitignored) for personal
preferences that shouldn't be shared.
Not Verifying Rules Take Effect
Problem:
You write rules but never verify the AI actually follows
them. Syntax errors in YAML frontmatter, wrong file
locations, or overly vague descriptions can silently
prevent rules from loading.
Fix:
After adding or changing a context file:
1. Start a new conversation
2. Ask the AI to describe the conventions it sees
3. Ask it to generate a small example and verify it
follows your stated patterns
4. In Cursor: check the Rules indicator in the chat panel
5. In Gemini CLI: run /memory show to see loaded context
Too Many Always-On Rules
Problem:
Setting every rule to alwaysApply or placing everything
in a single AGENTS.md that loads on every interaction.
Backend rules load when you're working on CSS. Database
rules load when you're writing documentation.
Fix:
Use scoping wherever possible:
- Cursor: globs to match file patterns
- Copilot: path-specific .instructions.md files
- Monorepos: nested AGENTS.md per package
- Keep alwaysApply for genuinely universal rules only
(project overview, commands, core standards)
Related Resources
Tool-Specific Guides on design.dev
- Cursor Rules Guide — Deep dive into
.cursor/rules/and.mdcfile configuration - Claude Skills Guide — Create SKILL.md files and configure CLAUDE.md for Claude Code
- Copilot Instructions Guide — Repository-wide and path-specific instructions for GitHub Copilot
- Gemini Gems & Skills Guide — Configure GEMINI.md and Gemini CLI context
- Windsurf Rules Guide — Global and workspace rules for Cascade AI
AI Generators on design.dev
- Cursor Rules Generator — Create
.mdcfiles visually with templates and frontmatter configuration - Claude Skills Generator — Generate SKILL.md files for Claude Code workflows
- Copilot Instructions Generator — Build custom instruction files for GitHub Copilot
- Gemini Gems Generator — Create GEMINI.md context files for Gemini CLI
- Windsurf Rules Generator — Configure .windsurfrules for Windsurf IDE
External References
- AGENTS.md Specification — Official standard from the Agentic AI Foundation
- Claude Code Memory Documentation — Official Anthropic docs on CLAUDE.md
- Cursor Rules Documentation — Official Cursor docs on rules configuration
- GitHub Copilot Custom Instructions — Official GitHub docs
- Gemini CLI GEMINI.md Guide — Official Google docs