How to Write AI Coding Rules Files: The Complete Guide to CLAUDE.md, .cursorrules, and AGENTS.md
Learn how to write AI coding rules files like CLAUDE.md, .cursorrules, and AGENTS.md to get better code from AI assistants in 2026.
Saidul Islam
Author

Most developers using AI coding assistants are leaving performance on the table. They type a prompt, get mediocre output, manually fix it, and repeat. The missing piece is almost always the same: they never told the AI how their project actually works. Knowing how to write AI coding rules files is the single highest-leverage thing you can do to improve AI-assisted development in 2026.
These rules files go by different names depending on your tool. Anthropic's Claude Code reads CLAUDE.md. Cursor uses .cursorrules (and the newer .cursor/rules directory). GitHub Copilot looks for AGENTS.md and .github/copilot-instructions.md. The concept is identical across all of them: a plain-text file checked into your repo that tells the AI how to behave when working on your code.
Think of it as onboarding documentation, except the new hire is an AI that reads every word and follows instructions literally.
Why Rules Files Matter More Than Better Prompts
There is a widespread belief that prompt engineering is the key skill for working with AI coding tools. It is not. A well-crafted rules file eliminates the need for most prompt engineering because the context is already there, every single time.
Without a rules file, every conversation starts from zero. The AI does not know you use Tailwind instead of CSS modules. It does not know your API responses follow a specific envelope format. It does not know your team banned any types in TypeScript three months ago. You end up repeating yourself constantly, or worse, accepting code that technically works but violates your project's conventions.
With a rules file, the AI arrives pre-briefed. I have seen teams report 30-40% fewer manual edits on AI-generated code after adding a solid rules file. That number tracks with my experience. The first draft quality jumps noticeably when the AI knows your stack, your patterns, and your preferences before it writes a single line.
The Anatomy of a Good Rules File
A rules file is not a novel. It is a reference document that an AI will parse on every interaction, so brevity and clarity win. The best ones share a common structure, regardless of which tool they target.
Project overview. Two to three sentences about what the project is, what stack it uses, and any non-obvious architectural decisions. "This is a Next.js 15 app using the App Router, Drizzle ORM with PostgreSQL, and Tailwind CSS v4. Authentication is handled by Better Auth. The monorepo uses pnpm workspaces." That is enough. The AI does not need your company history.
Code style rules. Specific, actionable constraints. Not "write clean code" but "use named exports, not default exports" and "prefer interface over type for object shapes in TypeScript." The more concrete, the better.
File and folder conventions. Where things live. "API routes go in src/app/api/. Database schemas are in src/db/schema/. Shared UI components live in src/components/ui/." This prevents the AI from putting files in bizarre locations.
Banned patterns. What the AI should never do. "Never use enum in TypeScript, use as const objects instead." "Do not add console.log statements." "Never import from @/lib/utils directly, use the re-exports from @/lib." Negative instructions are surprisingly effective because AI models pay close attention to explicit prohibitions.
Testing expectations. How and when to write tests. "Every new utility function needs a test in the co-located __tests__ directory. Use Vitest. Mock external services with msw."
CLAUDE.md: Rules for Claude Code
Claude Code, Anthropic's terminal-based coding agent, reads CLAUDE.md files at three levels of specificity: the user's home directory (~/.claude/CLAUDE.md), the project root, and any subdirectory the AI is working in. This hierarchy is powerful. You can set global preferences at the user level and project-specific rules at the repo level.
One thing I appreciate about Claude Code's approach is the layering. Your ~/.claude/CLAUDE.md might say "always use TypeScript, prefer functional components, explain your reasoning before writing code." Then your project-level CLAUDE.md adds the specifics: framework versions, folder structure, database conventions. Subdirectory files can override or extend further. A CLAUDE.md inside your src/db/ folder might contain schema naming conventions that only matter for database work.
Here is a real-world excerpt that works well:
# Project: Acme Dashboard
Next.js 15 (App Router), TypeScript 5.7, Tailwind CSS v4, Drizzle ORM, PostgreSQL.
## Code Rules
- Use server components by default. Add "use client" only when needed.
- All database queries go through the data access layer in src/db/queries/.
- Use zod for all input validation. Schemas live next to the route that uses them.
- Error handling: throw typed errors from src/lib/errors.ts, catch in error.tsx boundaries.
- No relative imports that go up more than one level. Use the @/ path alias.
## Git
- Commit messages: imperative mood, under 72 chars. Example: "Add user settings page"
- Never force push to main.
## When Unsure
- Check existing patterns in the codebase before inventing new ones.
- Ask before deleting files or making large refactors.
Notice what is not in there: no motivational language, no explaining why these rules exist (the AI does not care about your reasoning), no redundant instructions. Every line is a directive the AI can act on.
.cursorrules and .cursor/rules: Rules for Cursor
Cursor's rules system has evolved. The original .cursorrules file in the project root still works, but Cursor has been pushing developers toward the .cursor/rules/ directory, where you can create multiple rule files with metadata about when they should apply.
The .cursor/rules approach lets you scope rules to specific file patterns. You might have a rule file that only activates when editing files matching *.test.ts, another for src/api/**, and a general one for everything else. This is genuinely useful for larger projects where database code has completely different conventions than frontend components.
A .cursorrules file follows the same principles as CLAUDE.md but tends to be consumed by a wider range of models (since Cursor supports Claude, GPT-4o, and others). Keep your rules model-agnostic. Do not reference Claude-specific features or OpenAI function calling. Stick to plain instructions about your code.
One practical difference: Cursor's rules tend to need more explicit instructions about file editing patterns because Cursor applies changes through its diff interface. Instructions like "when modifying a component, show the complete updated component, not just the changed lines" can reduce the back-and-forth of partial edits.
AGENTS.md and GitHub Copilot Instructions
GitHub Copilot uses AGENTS.md (primarily for Copilot coding agents working on issues and pull requests) and .github/copilot-instructions.md for general Copilot interactions. The AGENTS.md file is particularly relevant if you are using Copilot to automatically fix issues or generate PRs, since the agent operates with more autonomy than inline suggestions.
The structure is similar, but GitHub's ecosystem means you should include CI-specific guidance. Things like "run pnpm lint and pnpm test before considering a task complete" or "this project requires all PRs to pass the typecheck GitHub Action." Copilot's agent can actually run these commands, so telling it your verification steps prevents premature pull requests that fail in CI.
Worth noting: the .github/copilot-instructions.md file affects all Copilot users in the repository. If you are on a team, this is a shared configuration, so get buy-in before adding opinionated rules. AGENTS.md can also be placed in subdirectories for scoped instructions, similar to Claude Code's approach.
How to Write AI Coding Rules Files That Actually Work
The difference between a rules file that transforms your workflow and one that gets ignored comes down to a few principles.
Be specific, not aspirational. "Write performant code" means nothing. "Use React.memo on list item components that receive stable props" is actionable. Every rule should be something you could verify in a code review. If you cannot point to a specific line and say "this follows the rule" or "this violates the rule," the instruction is too vague.
Update regularly. A stale rules file is almost worse than none, because it gives you false confidence that the AI knows your conventions when it is actually following outdated ones. I treat the rules file like a living document. When your team adopts a new pattern, the rules file should reflect it within the same PR.
Test your rules. After updating, run a few typical prompts and see if the AI follows the new instructions. Models occasionally interpret ambiguous phrasing in unexpected ways. "Prefer functional style" might mean pure functions to you but the AI might interpret it as "use React function components." Specificity eliminates this.
Keep it under 500 lines. Seriously. If your rules file is a thousand lines, the AI's attention will degrade on the less prominent rules. Prioritize the instructions that matter most. If you need extensive documentation, that belongs in your actual docs, not your AI rules file.
Do not duplicate what the AI already knows. You do not need to explain how React hooks work or what TypeScript generics are. The AI knows. Focus on what is unique to your project, the stuff no model was trained on: your conventions, your architecture, your team's decisions.
Common Mistakes to Avoid
The biggest mistake is treating the rules file like a prompt. Rules files are persistent context, not conversational. Phrases like "I want you to.." or "Please make sure to.." add noise. Just state the rule. "Use named exports" beats "I would like you to please use named exports when writing modules."
Another mistake: contradictory rules. If one section says "keep functions under 20 lines" and another section describes a complex data transformation pattern that inherently requires 40 lines, the AI will struggle. Audit for contradictions, especially if multiple people contribute to the file.
Overloading with examples is also common. One example per concept is plenty. Three examples of the same naming convention waste tokens that could carry more useful context about your project.
Cross-Tool Compatibility
If your team uses multiple AI tools (which many do), maintaining separate rules files feels tedious. The good news: the content is 90% identical across formats. The core of your rules — code style, architecture, conventions — stays the same regardless of whether Claude Code or Cursor reads it.
My recommendation: maintain one canonical source of truth and generate tool-specific files from it. A simple build script that copies your base rules into CLAUDE.md, .cursorrules, and .github/copilot-instructions.md with minor tool-specific additions keeps everything in sync. Some developers use a rules.base.md file and a short script to distribute it. Low-tech, effective.
The tool-specific additions are minor. Claude Code benefits from instructions about terminal command behavior. Cursor needs guidance on diff formatting. Copilot's agent needs CI instructions. Everything else is shared.
Frequently Asked Questions
Do rules files work with every AI model?
They work with every model that the host tool supports. If you are using Cursor with Claude 3.5 Sonnet or GPT-4o, both will read the same .cursorrules file. The effectiveness varies slightly by model (Claude tends to follow detailed structural instructions more faithfully in my experience), but the format is universal within each tool.
How long should my rules file be?
Aim for 100-300 lines for most projects. Small projects can get away with 50 lines. Very large monorepos might push 500. Beyond that, you are likely including information that belongs in documentation rather than AI instructions. The AI processes the entire file on every interaction, so respect the context window.
Should I commit the rules file to version control?
Yes, absolutely. These files are project configuration, just like .eslintrc or tsconfig.json. They should be reviewed in PRs, versioned, and shared across the team. The exception is your personal ~/.claude/CLAUDE.md, which contains your individual preferences and stays local.
Can rules files replace code review?
No. They reduce the number of issues that make it to code review, which is valuable, but they cannot catch logical errors, business logic mistakes, or architectural problems that require human judgment. Think of rules files as shifting your code quality efforts left, not eliminating them.
What if the AI ignores a rule?
It happens, especially with complex or ambiguous rules. First, check if the rule is specific enough. "Handle errors properly" will be ignored. "Wrap all database calls in try-catch blocks and throw AppError from src/lib/errors.ts" will not. If the rule is clear and still gets ignored, try moving it higher in the file (models pay more attention to content near the top) or rephrasing it as a prohibition: "Never leave database calls without error handling."
Start Small, Iterate Fast
You do not need a perfect rules file on day one. Start with five rules that address the most common issues you manually fix in AI-generated code. Use it for a week. Notice what the AI still gets wrong, and add rules for those patterns. Within a month, you will have a rules file that genuinely changes how useful AI coding tools are in your workflow.
If you spend time organizing and searching through hundreds of AI conversations while building these workflows, AI Chat Organizer auto-organizes and instant-searches your ChatGPT conversations so you can find that one prompt where you nailed your rules file format three weeks ago.
Related from NexaSphere: If your ChatGPT and Claude conversations are scattered, AI Chat Organizer gives you folders, tags, and cross-platform search. Free Chrome extension.
Get more insights like this
Join our newsletter for weekly deep dives on AI tools, Chrome extensions, and software engineering.