How to Write an Effective AGENTS.md File for AI Coding Agents
I kept repeating myself. Every time I started a new session with Claude or Codex, I’d type the same instructions: “Use immutable patterns,” “Keep functions under 50 lines,” “Run tests before finishing.” It was exhausting and inconsistent—sometimes I’d forget a rule, sometimes I’d phrase it differently, and the AI would interpret it differently.
Then I discovered AGENTS.md.
The Problem: Context Amnesia
AI coding agents don’t remember previous sessions. Every conversation starts fresh. If you work with the same coding standards day after day, you’re wasting tokens and time repeating yourself.
Worse, when multiple team members use AI agents, everyone writes their own ad-hoc instructions. Team member A tells the AI to use tabs, Team member B tells it to use spaces. Chaos.
The Solution: AGENTS.md as Persistent Memory
AGENTS.md is a file at your project root that acts as the AI agent’s operational manual. Instead of stuffing rules into every prompt, you define them once in a file that persists across sessions and can be shared across your team.
Here’s what a minimal AGENTS.md looks like:
# Coding Standards- Use immutable patterns - never mutate parameters- All functions must be under 50 lines- Handle all errors with specific user-friendly messages
# Testing- Minimum 80% test coverage- Run `npm test` before marking any task completeThe AI reads this file at the start of each session and applies these rules automatically.
Why This Works Better Than Prompts
I tried the prompt-based approach first. I had a template saved in my notes that I’d paste into every conversation:
You are helping me with a TypeScript project. Please follow these rules:1. Use immutable patterns2. Keep functions under 50 lines3. Handle all errors properly4. Write tests for everything5. Use Zod for validation[... 20 more lines ...]This approach has three problems:
- Token waste - I’m spending 200+ tokens every session on the same content
- Inconsistency - I sometimes forget items or phrase them differently
- No team sharing - My teammates can’t see or use my prompt template
AGENTS.md solves all three. It’s version-controlled, team-shared, and automatically loaded.
What Goes In AGENTS.md
Not everything belongs in AGENTS.md. The key insight is: AGENTS.md is for rules you repeat across sessions, not documentation that changes frequently.
Good candidates:
- Coding style preferences
- Error handling requirements
- Testing standards
- File organization rules
- What “done” means for common tasks
- Security requirements
- Performance constraints
Bad candidates:
- API documentation (changes frequently)
- Current sprint tasks (temporary)
- Bug descriptions (one-time)
- Architecture diagrams (put in docs/)
Here’s a more complete example from my actual project:
# Coding Style
## Immutability (CRITICAL)ALWAYS create new objects, NEVER mutate:
```typescript// WRONG: Mutationfunction updateUser(user, name) { user.name = name // MUTATION! return user}
// CORRECT: Immutabilityfunction updateUser(user, name) { return { ...user, name }}File Organization
- Maximum 800 lines per file
- Organize by feature/domain, not by type
- Extract utilities from large components
Error Handling
ALWAYS handle errors comprehensively:
try { const result = await riskyOperation() return result} catch (error) { console.error('Operation failed:', error) throw new Error('Detailed user-friendly message')}Testing Requirements
Minimum Test Coverage: 80%
Test Types (ALL required):
- Unit Tests - Individual functions, utilities, components
- Integration Tests - API endpoints, database operations
- E2E Tests - Critical user flows (Playwright)
Test-Driven Development
MANDATORY workflow:
- Write test first (RED)
- Run test - it should FAIL
- Write minimal implementation (GREEN)
- Run test - it should PASS
- Refactor (IMPROVE)
Common Patterns
API Response Format
interface ApiResponse<T> { success: boolean data?: T error?: string meta?: { total: number page: number limit: number }}Custom Hooks Pattern
export function useDebounce<T>(value: T, delay: number): T { const [debouncedValue, setDebouncedValue] = useState<T>(value)
useEffect(() => { const handler = setTimeout(() => setDebouncedValue(value), delay) return () => clearTimeout(handler) }, [value, delay])
return debouncedValue}Notice how each rule is:- **Short and precise** - Not a 10-page essay- **Actionable** - The AI can follow it- **Constraining** - It limits what the AI can do- **Example-backed** - Shows correct vs incorrect patterns
## Common Mistakes
I've seen several anti-patterns in AGENTS.md files:
### Mistake 1: Too Vague
```text title="Bad AGENTS.md"Write clean code and test everything.This is useless. “Clean” is subjective. “Test everything” could mean anything. The AI can’t follow this.
Mistake 2: Too Long
I saw one AGENTS.md that was 50 pages of documentation. The AI skimmed it and missed critical rules. Keep it under 500 lines. If you have more, split into multiple files.
Mistake 3: Wrong Content
Another team put their API documentation in AGENTS.md. That changes weekly. Now their AGENTS.md is always out of date.
Mistake 4: No Team Alignment
One person on the team created an AGENTS.md with their personal preferences. Others didn’t know it existed. They kept giving conflicting instructions.
How AGENTS.md Differs from CLAUDE.md
If you use Claude Code, you might notice CLAUDE.md. Both serve similar purposes but have different scopes:
- CLAUDE.md - Personal, global instructions for all projects (in
~/.claude/CLAUDE.md) - AGENTS.md - Project-specific, team-shared instructions (in project root)
Use CLAUDE.md for personal preferences that apply everywhere (like “I don’t like sycophancy, be direct”). Use AGENTS.md for team standards specific to that project.
Iterating on AGENTS.md
AGENTS.md isn’t set-and-forget. I update mine weekly based on:
- Rules I find myself repeating verbally - If I keep saying “don’t forget to handle errors,” that goes in AGENTS.md
- Mistakes the AI makes repeatedly - If it keeps writing mutable code, I add an immutability rule
- Team feedback - In code review, if someone points out a consistent issue, we add a rule
Here’s my process:
1. Notice I'm repeating an instruction2. Check if AGENTS.md has this rule3. If no, add a short, actionable version4. If yes, check if it's specific enough5. Test in next session6. Refine based on AI behaviorThe “Done” Definition
One of the most valuable sections in my AGENTS.md is the “done criteria.” This tells the AI what completion looks like:
## Done Criteria- Feature is done when: tests pass, code reviewed, docs updated- Bug fix is done when: root cause identified, fix verified, regression test added- Refactor is done when: tests still pass, no behavior change, code cleanerWithout this, the AI might say “I implemented the feature” when tests are failing. With this, it knows exactly what “done” means.
Real-World Impact
Since adopting AGENTS.md:
- 50% fewer clarification rounds - The AI knows my standards upfront
- Consistent output across team members - We all get the same coding style
- Faster onboarding - New team members just read AGENTS.md
- Version-controlled standards - Changes are tracked in git
Starting Your AGENTS.md
Don’t overthink it. Start with your top 3 most-repeated instructions:
# Coding Standards- Use immutable patterns- Handle all errors with specific messages
# Testing- Run tests before finishing any taskUse it for a week. Notice what you still have to repeat. Add those rules. Iterate.
The goal isn’t a perfect AGENTS.md on day one—it’s a living document that grows with your team’s needs.
Final Words + More Resources
My intention with this article was to help others share my knowledge and experience. If you want to contact me, you can contact by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!
Comments