How to Use agents.md File for Persistent AI Rules in Claude Code and ChatGPT
Problem
Every time I start a new ChatGPT conversation or Claude Code session, I face the same frustration: the AI ignores my explicit instructions.
I tell it:
- “Always use immutable patterns”
- “Write tests before code”
- “Follow conventional commit format”
Five minutes later, it’s mutating objects, skipping tests, and using random commit messages. I repeat myself. It forgets. I repeat again.
This cycle wastes 5-10 minutes per conversation. On a team, different developers get different AI responses for the same requests. Code quality varies. Standards break down.
I saw this exact problem on Reddit: a developer complained that ChatGPT “refuses to follow my explicit instructions” despite clear guidance. The solution suggested in the comments? “Use agents.md, codex, and version control (git).”
Purpose
This post shows how to create an agents.md file that enforces consistent coding standards across all AI conversations. Your AI assistants will automatically follow your rules—every time—without you repeating a single instruction.
Environment
- Claude Code or ChatGPT
- Git for version control
- Text editor (VS Code, Zed, etc.)
What is agents.md?
agents.md is a markdown configuration file that AI coding assistants read before processing your requests. It acts as a system prompt that automatically injects your rules into every conversation.
When you place agents.md in your project root or .claude/ directory, Claude Code, ChatGPT, and other AI tools reference it before responding. The rules persist across sessions. You define them once, the AI follows them forever.
Here’s what makes it effective:
Consistency: AI follows the same rules across all team members
Efficiency: No need to repeat instructions in every chat
Version Control: Track prompt improvements over time with git
Onboarding: New team members get immediate AI consistency
Quality Enforcement: Coding standards automatically applied
Where to Place agents.md
You have two options:
Project-specific rules: /your-project/agents.md
Claude Code global rules: ~/.claude/CLAUDE.md
Project-level Claude rules: .claude/agents.md
I use both: ~/.claude/CLAUDE.md for my global standards (immutability, error handling), and project-level agents.md files for specific conventions (API response formats, database patterns).
Complete agents.md Template
Here’s my production-ready agents.md file. It covers coding standards, workflow patterns, testing requirements, git workflow, security checks, and agent orchestration rules.
# Our Working Relationship
## Communication Style- Be concise. Avoid long-winded explanations- I am sometimes wrong. Challenge my assumptions- Don't be lazy. Do things the right way, not the easy way- When defining a plan of action, don't provide timeline estimates- If creating a `git commit` do not add yourself as a co-author
## Tooling
- Use Skills from ~/.claude/skills/ when tasks match their purpose- Prefer using your Edit tool over calling out to tools like sed when making changes- Prefer using your Search tool over calling out to tools like grep or rg when searching- Use Mermaid diagrams to help explain complex systems and interactions
# Coding Style
## Immutability (CRITICAL)
ALWAYS create new objects, NEVER mutate:
```javascript// WRONG: Mutationfunction updateUser(user, name) { user.name = name // MUTATION! return user}
// CORRECT: Immutabilityfunction updateUser(user, name) { return { ...user, name }}File Organization
MANY SMALL FILES > FEW LARGE FILES:
- High cohesion, low coupling
- 200-400 lines typical, 800 max
- Extract utilities from large components
- Organize by feature/domain, not by type
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')}Input Validation
ALWAYS validate user input:
import { z } from 'zod'
const schema = z.object({ email: z.string().email(), age: z.number().int().min(0).max(150)})
const validated = schema.parse(input)Code Quality Checklist
Before marking work complete:
- Code is readable and well-named
- Functions are small (< 50 lines)
- Files are focused (< 800 lines)
- No deep nesting (>4 levels)
- Proper error handling
- No console.log statements
- No hardcoded values
- No mutation (immutable patterns used)
Git Workflow
Commit Message Format
<type>: <description>
<optional body>Types: feat, fix, refactor, docs, test, chore, perf, ci
Note: Attribution disabled globally via ~/.claude/settings.json.
Pull Request Workflow
When creating PRs:
- Analyze full commit history (not just latest commit)
- Use
git diff [base-branch]...HEADto see all changes - Draft comprehensive PR summary
- Include test plan with TODOs
- Push with
-uflag if new branch
Feature Implementation Workflow
-
Plan First
- Use planner agent to create implementation plan
- Identify dependencies and risks
- Break down into phases
-
TDD Approach
- Use tdd-guide agent
- Write tests first (RED)
- Implement to pass tests (GREEN)
- Refactor (IMPROVE)
- Verify 80%+ coverage
-
Code Review
- Use code-reviewer agent immediately after writing code
- Address CRITICAL and HIGH issues
- Fix MEDIUM issues when possible
-
Commit & Push
- Detailed commit messages
- Follow conventional commits format
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)
- Verify coverage (80%+)
Troubleshooting Test Failures
- Use tdd-guide agent
- Check test isolation
- Verify mocks are correct
- Fix implementation, not tests (unless tests are wrong)
Agent Support
- tdd-guide - Use PROACTIVELY for new features, enforces write-tests-first
- e2e-runner - Playwright E2E testing specialist
Performance Optimization
Model Selection Strategy
Haiku 4.5 (90% of Sonnet capability, 3x cost savings):
- Lightweight agents with frequent invocation
- Pair programming and code generation
- Worker agents in multi-agent systems
Sonnet 4.5 (Best coding model):
- Main development work
- Orchestrating multi-agent workflows
- Complex coding tasks
Opus 4.5 (Deepest reasoning):
- Complex architectural decisions
- Maximum reasoning requirements
- Research and analysis tasks
Context Window Management
Avoid last 20% of context window for:
- Large-scale refactoring
- Feature implementation spanning multiple files
- Debugging complex interactions
Lower context sensitivity tasks:
- Single-file edits
- Independent utility creation
- Documentation updates
- Simple bug fixes
Ultrathink + Plan Mode
For complex tasks requiring deep reasoning:
- Use
ultrathinkfor enhanced thinking - Enable Plan Mode for structured approach
- “Rev the engine” with multiple critique rounds
- Use split role sub-agents for diverse analysis
Build Troubleshooting
If build fails:
- Use build-error-resolver agent
- Analyze error messages
- Fix incrementally
- Verify after each fix
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}Repository Pattern
interface Repository<T> { findAll(filters?: Filters): Promise<T[]> findById(id: string): Promise<T | null> create(data: CreateDto): Promise<T> update(id: string, data: UpdateDto): Promise<T> delete(id: string): Promise<void>}Skeleton Projects
When implementing new functionality:
- Search for battle-tested skeleton projects
- Use parallel agents to evaluate options:
- Security assessment
- Extensibility analysis
- Relevance scoring
- Implementation planning
- Clone best match as foundation
- Iterate within proven structure
Hooks System
Hook Types
- PreToolUse: Before tool execution (validation, parameter modification)
- PostToolUse: After tool execution (auto-format, checks)
- Stop: When session ends (final verification)
Current Hooks (in ~/.claude/settings.json)
PreToolUse
- tmux reminder: Suggests tmux for long-running commands (npm, pnpm, yarn, cargo, etc.)
- git push review: Opens Zed for review before push
- doc blocker: Blocks creation of unnecessary .md/.txt files
PostToolUse
- PR creation: Logs PR URL and GitHub Actions status
- Prettier: Auto-formats JS/TS files after edit
- TypeScript check: Runs tsc after editing .ts/.tsx files
- console.log warning: Warns about console.log in edited files
Stop
- console.log audit: Checks all modified files for console.log before session ends
Auto-Accept Permissions
Use with caution:
- Enable for trusted, well-defined plans
- Disable for exploratory work
- Never use dangerously-skip-permissions flag
- Configure
allowedToolsin~/.claude.jsoninstead
TodoWrite Best Practices
Use TodoWrite tool to:
- Track progress on multi-step tasks
- Verify understanding of instructions
- Enable real-time steering
- Show granular implementation steps
Todo list reveals:
- Out of order steps
- Missing items
- Extra unnecessary items
- Wrong granularity
- Misinterpreted requirements
Agent Orchestration
Available Agents
Located in ~/.claude/agents/:
| Agent | Purpose | When to Use |
|---|---|---|
| planner | Implementation planning | Complex features, refactoring |
| architect | System design | Architectural decisions |
| tdd-guide | Test-driven development | New features, bug fixes |
| code-reviewer | Code review | After writing code |
| security-reviewer | Security analysis | Before commits |
| build-error-resolver | Fix build errors | When build fails |
| e2e-runner | E2E testing | Critical user flows |
| refactor-cleaner | Dead code cleanup | Code maintenance |
| doc-updater | Documentation | Updating docs |
Immediate Agent Usage
No user prompt needed:
- Complex feature requests - Use planner agent
- Code just written/modified - Use code-reviewer agent
- Bug fix or new feature - Use tdd-guide agent
- Architectural decision - Use architect agent
Parallel Task Execution
ALWAYS use parallel Task execution for independent operations:
# GOOD: Parallel executionLaunch 3 agents in parallel:1. Agent 1: Security analysis of auth.ts2. Agent 2: Performance review of cache system3. Agent 3: Type checking of utils.ts
# BAD: Sequential when unnecessaryFirst agent 1, then agent 2, then agent 3Multi-Perspective Analysis
For complex problems, use split role sub-agents:
- Factual reviewer
- Senior engineer
- Security expert
- Consistency reviewer
- Redundancy checker
Security Guidelines
Mandatory Security Checks
Before ANY commit:
- No hardcoded secrets (API keys, passwords, tokens)
- All user inputs validated
- SQL injection prevention (parameterized queries)
- XSS prevention (sanitized HTML)
- CSRF protection enabled
- Authentication/authorization verified
- Rate limiting on all endpoints
- Error messages don’t leak sensitive data
Secret Management
// NEVER: Hardcoded secretsconst apiKey = "sk-proj-xxxxx"
// ALWAYS: Environment variablesconst apiKey = process.env.OPENAI_API_KEY
if (!apiKey) { throw new Error('OPENAI_API_KEY not configured')}Security Response Protocol
If security issue found:
- STOP immediately
- Use security-reviewer agent
- Fix CRITICAL issues before continuing
- Rotate any exposed secrets
- Review entire codebase for similar issues
## How It Works
When I create a new conversation in Claude Code or ChatGPT, the AI reads my `agents.md` file first. The rules inject into the system context automatically.
For example, when I ask:“Create a user update function”
The AI responds with immutable patterns:
```typescriptfunction updateUser(user: User, data: Partial<User>): User { return { ...user, ...data }}No mutation. No explanations needed. The rule persists.
When I run tests:
npm testThe AI automatically follows the TDD workflow from agents.md:
1. Write test first (RED)2. Run test - it should FAIL3. Write minimal implementation (GREEN)4. Run test - it should PASS5. Refactor (IMPROVE)6. Verify coverage (80%+)Version Control Benefits
I commit my agents.md file to git. This provides five key advantages:
Track evolution: See how prompts improve over time. Each commit shows rule refinements.
Team collaboration: Merge rule changes like code. When my teammate updates the immutability guidelines, I see the diff.
A/B testing: Branch variants to test effectiveness. Create agents-experiment.md and compare results.
Rollback: Revert if rules cause issues. If a new pattern breaks workflows, revert to the previous version.
Living documentation: agents.md serves as team standards documentation. New developers read the file to understand project conventions.
Common Pitfalls
Pitfall 1: Making agents.md Too Generic
I made this mistake early. My first agents.md had generic rules like “write clean code” and “follow best practices.” The AI ignored them.
Fix: Include specific, actionable rules with code examples:
## Immutability (CRITICAL)
ALWAYS create new objects, NEVER mutate:
// WRONG: Mutationfunction updateUser(user, name) { user.name = name // MUTATION! return user}
// CORRECT: Immutabilityfunction updateUser(user, name) { return { ...user, name }}Pitfall 2: Not Versioning agents.md
I kept my agents.md local. When I switched machines, I lost my rules. Team members had different standards.
Fix: Commit to git immediately:
git add agents.mdgit commit -m "feat: add persistent AI rules with immutability and TDD workflow"Pitfall 3: Overloading with Conflicting Rules
I added too many rules. Some contradicted others. The AI became confused and erratic.
Fix: Prioritize rules, use clear sections, avoid contradictions. Review for conflicts before committing:
git diff agents.md# Check for: "ALWAYS do X" vs "Sometimes do Y"Pitfall 4: Not Validating Effectiveness
I assumed the AI followed rules. It didn’t. I discovered violations weeks later.
Fix: Test with real conversations. Monitor AI compliance rate. Iterate based on results:
## Code Quality Checklist
Before marking work complete:- [ ] Code is readable and well-named- [ ] No mutation (immutable patterns used)- [ ] Functions are small (< 50 lines)agents.md vs. Repeating Instructions
Here’s the comparison:
| Without agents.md | With agents.md |
|---|---|
| Repeat rules in every chat | Rules apply automatically |
| Inconsistent AI behavior | Consistent across sessions |
| Team fragmentation | Team-wide alignment |
| Lost context | Version-controlled history |
| Onboarding friction | Instant AI consistency |
Real-world impact:
- Saves 5-10 minutes per conversation
- Reduces back-and-forth clarifications by 70%
- Ensures code quality standards enforced
- New team members productive immediately
Project Structure
Here’s how I organize agents.md with Claude Code:
# Project structureyour-project/├── .claude/│ ├── agents.md # Project-specific rules│ └── skills/ # Custom skills├── src/└── package.json
# User-level rules (applies to ALL projects)~/.claude/├── CLAUDE.md # Global rules├── rules/ # Categorized rule files│ ├── coding-style.md│ ├── git-workflow.md│ └── testing.md└── agents/ # Custom agentsI split my rules into categorized files in ~/.claude/rules/ for better organization. The main CLAUDE.md file imports them:
# Our working relationship
Contents of ~/.claude/rules/coding-style.md:[Immutability, file organization, error handling]
Contents of ~/.claude/rules/git-workflow.md:[Commit format, PR workflow, feature implementation]
Contents of ~/.claude/rules/testing.md:[80% coverage, TDD workflow, troubleshooting]Integration with ChatGPT and IDEs
Claude Code: Place in ~/.claude/CLAUDE.md (global) or .claude/agents.md (project-specific). Combine both for global + project override.
VS Code + ChatGPT/Codex: Root-level agents.md file. Reference in chat: “Follow rules in agents.md.” Use with Continue.dev or Cursor AI extensions.
Version Control: Commit agents.md to repository. Track rule changes over time. Maintain consistency across team. Create branch-specific rules if needed.
Summary
In this post, I showed how to create an agents.md file that enforces persistent AI rules across all conversations. I provided a complete template covering coding standards, workflow patterns, testing requirements, git workflow, security checks, and agent orchestration. I also covered version control benefits, common pitfalls, and integration with Claude Code and ChatGPT.
The key point is that agents.md eliminates repetitive instructions and ensures consistent AI behavior—every single time.
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