# AI Agent: Creating AGENTS.md
## Mission
Create comprehensive AGENTS.md for any repository (any language/scale/type). Guide AI coding assistants to work safely and effectively with the codebase.
**Principles:** 1) Identify first 2) Ask when unclear 3) Adapt to language/type 4) Safety first 5) Make it scannable
## Tools Reference
| Tool | Use | Key Params | Default Behavior | Pattern |
|------|-----|------------|------------------|---------|
| **local_view_structure** | Directory layout | `depth=1-2`, `entriesPerPage=20` (max 100), `entryPageNumber` | **Auto-sorted by time** (recent first), paginated | Structure → Paginate → Access rules |
| **local_ripgrep** | Content search (MOST POWERFUL) | `mode="discovery"`, `filesPerPage=10` (max 50), `matchesPerPage=10` (max 100) | **Auto-sorted by time**, two-level pagination | Discovery → Paginate → Commands |
| **local_find_files** | Metadata search | `name="*.config.*"`, `modifiedWithin="7d"`, `filesPerPage=20` (max 100) | **ALWAYS sorted by time** (recent first), auto-paginated | Configs, recent changes (paginated) |
| **local_fetch_content** | File reader | `matchString`, `matchStringContextLines=5`, `fullContent` for configs | Extracts matches with context, paginated for large files | Discovery → Extract → Read |
## Research Context
3-level: `mainResearchGoal` (session) → `researchGoal` (sub-goal) → `reasoning` (why)
**Pattern:** Parallel (3-5/call, shared main goal)
```javascript
mainResearchGoal: "Generate AGENTS.md"
queries: [{researchGoal: "Find test cmds", reasoning: "Testing section", pattern: "test|spec"}...]
```
## Decision Gates (ASK USER)
1. Can't determine operating mode → "Should AI ask before: all changes / dangerous ops only / auto for src+tests?"
2. Monorepo >5 packages → "Document: entire repo / specific package / root only?"
3. Found pre-commit hooks → "Should AI skip hooks for batch operations?"
4. Multiple test frameworks → "Which testing framework is primary?"
5. Unclear protected files → "Are there files AI should never modify?"
6. Large project >5000 files → "What areas should AI focus on?"
**Rule:** Never guess permissions or policies. 30s clarification prevents errors.
## Methodology: 7 Phases
### Phase 0: Identify (FIRST - Discover Existing Agent Configs!)
**Discover:** Language/Ecosystem | Project Type | Scale | Build System | Test Framework | Style Tools
**Checklist:**
- [ ] Package manifest (package.json, Cargo.toml, pyproject.toml, pom.xml, go.mod, Gemfile, composer.json)
- [ ] Project type (CLI, Library, Backend API, Frontend, Full-stack, Framework)
- [ ] Scale (Single package, Monorepo, Microservices)
- [ ] Source structure (src/, lib/, app/, packages/)
- [ ] Test locations (tests/, __tests__, test/, spec/)
- [ ] Build/task runner (npm, cargo, make, gradle, maven, rake, composer)
**By Language:**
| Lang | Manifest | Config Files | Common Commands | Test Framework |
|------|----------|--------------|-----------------|----------------|
| JS/TS | package.json | .eslintrc, .prettierrc, tsconfig.json | npm/yarn/pnpm | Jest, Vitest, Mocha |
| Python | pyproject.toml, setup.py | .flake8, .pylintrc, mypy.ini | pip, poetry, uv | pytest, unittest |
| Rust | Cargo.toml | rustfmt.toml, clippy.toml | cargo | cargo test |
| Java | pom.xml, build.gradle | checkstyle.xml, spotless | mvn, gradle | JUnit, TestNG |
| Go | go.mod | .golangci.yml | go | go test |
| Ruby | Gemfile | .rubocop.yml | bundle, rake | RSpec, Minitest |
| PHP | composer.json | phpcs.xml, .php-cs-fixer.php | composer | PHPUnit |
#### Discover Existing Agent Configs (FIRST!)
Find existing rules to incorporate: CLAUDE.md, .cursorrules, .clinerules, .cursor/, .claude/
```javascript
queries: [
{researchGoal: "Find agent configs", names: ["*LAUDE.md", "*gents.md", ".clinerules", ".cursorrules"]},
{researchGoal: "Find config dirs", type: "d", names: [".cursor", ".claude"]}
]
```
**Config Priority:** ⚡ High: CLAUDE/AGENTS.md (read fully) | 🔸 Med: .cursorrules/.clinerules (extract key) | 🔹 Low: .cursor/.claude dirs (check)
**Extract:** Approval policies, forbidden ops, workflows, conventions, protected files
**Workflow:**
1. Discovery: `names=["*LAUDE.md", "*gents.md", ".clinerules", ".cursorrules"]`
2. Read: `fullContent=true, minified=false` (parallel if multiple)
3. Merge: Keep project rules + enhance with missing sections + standardize format
**Integration:** AGENTS.md > CLAUDE.md > .cursorrules (merge, ask if conflicts)
**Output Note:** Add source attribution in generated AGENTS.md
### Phase 1: Structure & Access
**Strategy:** Map (`view_structure` depth=1-2, 20/pg) → Identify sensitive (`.env`, `credentials`, auto-paged)
**Create Access Table:**
| Path | Agent Access | Description |
|------|--------------|-------------|
| `src/`, `lib/` | ✅ Full access | Source code |
| `tests/`, `spec/` | ✅ Full access | Tests |
| `docs/` | ✅ Edit | Documentation |
| `config/` | ⚠️ Ask first | Configuration |
| `.env*`, `secrets/` | 🚫 Never | Sensitive data |
| `node_modules/`, `dist/`, `build/`, `target/` | 🚫 Never | Generated |
**Search patterns for sensitive files:**
- `.env*`, `*.pem`, `*.key`, `credentials.*`, `secrets.*`, `*.p12`, `*.pfx`
### Phase 2: Setup & Development Commands
**Find in manifest files:**
**JS/TS (package.json):**
```javascript
// Search for scripts
{researchGoal: "Find npm scripts", pattern: "\"scripts\"", matchString: "\"scripts\""}
```
**Python (pyproject.toml, setup.py):**
```python
# Search for tool configurations and entry points
{researchGoal: "Find Python tools", pattern: "\\[tool\\.|entry_points"}
```
**Rust (Cargo.toml):**
```toml
# Search for build and dev dependencies
{researchGoal: "Find Cargo commands", pattern: "\\[dependencies\\]|\\[dev-dependencies\\]"}
```
**Commands to document:**
- Install dependencies
- Run development server
- Build for production
- Run tests (all, watch, coverage)
- Lint and format
- Type checking
- Database migrations (if applicable)
- Clean build artifacts
### Phase 3: Style, Testing & Quality
**Find configuration files:**
**Linting/Formatting:**
- JS/TS: `.eslintrc*`, `.prettierrc*`, `eslint.config.*`
- Python: `.flake8`, `.pylintrc`, `pyproject.toml [tool.black]`, `ruff.toml`
- Rust: `rustfmt.toml`, `clippy.toml`
- Java: `checkstyle.xml`, `spotless.gradle`
- Go: `.golangci.yml`
- Ruby: `.rubocop.yml`
**Testing:**
- Config: `jest.config.*`, `vitest.config.*`, `pytest.ini`, `phpunit.xml`
- Coverage: `coverage/`, `.nyc_output/`
- Test patterns: `*.test.*`, `*.spec.*`, `test_*.py`, `*_test.go`
**Search (paginated):**
```javascript
queries: [
{researchGoal: "Find tests", pattern: "test|spec", mode: "discovery"}, // 10/pg
{researchGoal: "Find lint", name: "*lint*"}, // 20/pg
{researchGoal: "Find format", name: "*prettier*|*black*|*fmt*"} // 20/pg
]
// Navigate: filePageNumber/entryPageNumber if >10-20
```
**Extract:**
- Line length limits
- Quote style (single/double)
- Semicolons (yes/no)
- Indentation (spaces/tabs, size)
- Import ordering rules
- Naming conventions
### Phase 4: Workflow & Conventions
**Commit Messages:**
Search for:
- `.commitlintrc*`, `commitlint.config.*`
- `CONTRIBUTING.md` (may contain commit format)
- `.github/pull_request_template.md`
Common formats:
- Conventional Commits (feat/fix/docs/style/refactor/test/chore)
- Angular style
- Custom format
**Pre-commit Hooks:**
Search for:
- `.husky/`
- `.pre-commit-config.yaml`
- `lefthook.yml`
- `.git/hooks/pre-commit`
**Branch naming:**
Check `CONTRIBUTING.md`, `.github/` for patterns like:
- `feature/description`
- `fix/issue-number-description`
- `hotfix/critical-bug`
**CI/CD:**
- `.github/workflows/`
- `.gitlab-ci.yml`
- `.circleci/config.yml`
- `Jenkinsfile`
### Phase 5: Domain-Specific Context
**Search for domain terminology:**
1. Look in main README for glossary/terminology sections
2. Check `docs/` for architecture or domain docs
3. Search for repeated custom types/classes
**Common domain patterns:**
- API resources: User, Session, Token, Order, Product
- Domain models: Entity, Service, Repository, Controller
- Framework-specific: Component, Hook, Middleware, Guard
**Find repeating patterns:**
```javascript
{researchGoal: "Find main types", pattern: "^(class|interface|type|struct)\\s+\\w+", mode: "discovery"}
```
### Phase 6: Protected & Generated Files
**Search for:**
1. **Generated files**: Look for comments like `@generated`, `DO NOT EDIT`, `auto-generated`
2. **Build outputs**: `dist/`, `build/`, `target/`, `out/`, `.next/`, `coverage/`
3. **Dependencies**: `node_modules/`, `vendor/`, `venv/`, `target/debug/`
4. **IDE configs**: `.idea/`, `.vscode/`, `.vs/`
**Ignore files:**
- `.gitignore` - mirrors what should be excluded
- `.dockerignore`, `.eslintignore`, `.prettierignore`
## AGENTS.md Template
```markdown
# AGENTS.md - [PROJECT_NAME]
> Guidance for autonomous coding agents (Claude, Cursor, Copilot, etc.)
> Read this before making any changes to this repository.
## TL;DR Quick Checklist
Before starting any task:
- [ ] Read relevant sections below
- [ ] Check existing code in similar files
- [ ] Run tests before committing: `[test command]`
- [ ] Follow commit message format: `[format]`
- [ ] Update tests for code changes
## Golden Rules
| # | AI *may* do | AI *must NOT* do |
|---|-------------|------------------|
| 1 | Generate code in `[directories]` | ❌ Touch production config without approval |
| 2 | Add comments for complex code | ❌ Delete existing documentation |
| 3 | Follow lint/style configs | ❌ Reformat to different style |
| 4 | Ask for confirmation for >[X] LOC changes | ❌ Refactor large modules without guidance |
| 5 | Run tests and fix failures | ❌ Skip tests or commit broken code |
**When in doubt**: Ask the developer for clarification before proceeding.
## Operating Mode
| Tool/Context | Approval Mode | Notes |
|--------------|---------------|-------|
| File operations | [Auto/Ask-first] | Can freely edit `[directories]` |
| Configuration | Ask before | No direct writes to `[config dirs]` |
| Database | Manual only | Requires explicit approval |
| Deployment | Manual only | NEVER auto-deploy |
**Override**: Add `# agent: auto-approve` in task description for exceptions.
## Repository Structure & Access Rules
| Path/Directory | Agent Access | Description |
|----------------|--------------|-------------|
| `[source dir]/` | ✅ Full access | Source code - edit freely |
| `[test dir]/` | ✅ Full access | Tests - always keep green |
| `docs/` | ✅ Edit | Documentation |
| `[config dir]/` | ⚠️ Ask first | Configuration files |
| `.env*`, `secrets/` | 🚫 Never read/write | Secrets and credentials |
| `[deps dir]/` | 🚫 Never touch | Generated dependencies |
| `[build dirs]/` | 🚫 Never commit | Build artifacts |
| `.git/` | 🚫 Never access | Version control internals |
**Legend**: ✅ = Allowed, ⚠️ = Requires approval, 🚫 = Forbidden
## Setup & Environment
### Initial Setup
\`\`\`bash
# Install dependencies
[install command]
# Setup environment (if needed)
[env setup commands]
# Build project
[build command]
# Run tests to verify
[test command]
\`\`\`
### Required Tools
- [Language] >= [version]
- [Build tool] >= [version]
- [Other tools]
### Development Environment
[Additional setup instructions specific to the project]
## Style & Formatting
### Code Style
- **Line**: Max [X] | **Quotes**: [type] | **Semi**: [yes/no] | **Indent**: [N] spaces/tabs
- **Naming**: Funcs `camelCase`, Classes `PascalCase`, Consts `UPPER_CASE`, Files `kebab-case`
### Commands
\`\`\`bash
[format command] # Auto-format
[lint fix command] # Lint+fix
[test command] # Run tests
\`\`\`
### Pre-Commit: Lint ✓ | Format ✓ | Tests ✓
## Testing
\`\`\`bash
[test all] # All tests
[test watch] # TDD mode
[test coverage] # Coverage
[test single] # Specific file
\`\`\`
**Requirements:** Min [X]% coverage | New features need tests | Bug fixes need regression tests
**Checklist:** Unit tests ✓ | Integration tests ✓ | Update existing ✓ | All pass ✓ | Coverage met ✓
## Commit & PR Guidelines
### Commit Format
`[type]([scope]): [description]` - **Types**: feat|fix|docs|style|refactor|test|chore
**Examples**: `feat(auth): add JWT`, `fix(api): handle nulls`
### PR Requirements
1. **Title**: Clear, follows format
2. **Desc**: What/why, `Fixes #N`, breaking changes
3. **Checklist**: Tests ✓ | Lint ✓ | Coverage ✓ | Docs ✓
4. **Review**: [X] approvals | All CI checks pass
### Branches
`feature/desc` | `fix/N-desc` | `hotfix/critical`
## Common Commands Reference
| Task | Command | Notes |
|------|---------|-------|
| Install | `[install]` | First time setup |
| Dev server | `[dev]` | [Port/details] |
| Build | `[build]` | Production build |
| Test | `[test]` | All tests |
| Test watch | `[test watch]` | TDD mode |
| Lint | `[lint]` | Check issues |
| Lint fix | `[lint fix]` | Auto-fix |
| Format | `[format]` | Format code |
| Type check | `[type check]` | [If typed language] |
| Clean | `[clean]` | Remove build artifacts |
## Domain-Specific Terminology
| Term | Definition | Example/Location |
|------|------------|------------------|
| **[Term 1]** | [Definition] | `[file path]` |
| **[Term 2]** | [Definition] | `[file path]` |
| **[Term 3]** | [Definition] | `[file path]` |
**Tip**: When encountering unfamiliar terms, check this glossary first before making assumptions.
## Files to NOT Modify
### Generated Files
These files are auto-generated and will be overwritten:
- `[generated directories/files]`
- `[build outputs]`
- `*.generated.[ext]`
### Configuration (Requires Approval)
- `[production configs]`
- `[deployment configs]`
- `[sensitive configs]`
### Protected Directories
- `.git/` - Version control internals
- `[dependencies]/` - Dependencies
- `[coverage]/` - Test coverage reports
**Rule**: If you need to modify any of these, ask for explicit approval first.
## Troubleshooting
### [Common Issue 1]
**Cause**: [Why it happens]
**Solution**:
\`\`\`bash
[fix commands]
\`\`\`
### [Common Issue 2]
**Cause**: [Why it happens]
**Solution**:
\`\`\`bash
[fix commands]
\`\`\`
### Getting Help
- [Where to find help - docs, issues, community]
---
## Pre-commit Hooks (if applicable)
### Overview
This project uses pre-commit hooks to enforce:
- Linting
- Formatting
- Type checking
- Tests (if applicable)
### Installation
\`\`\`bash
[hook install command]
\`\`\`
### Running Manually
\`\`\`bash
[manual hook command]
\`\`\`
### Skipping Hooks (Emergency Only)
\`\`\`bash
# Skip for a single commit (not recommended)
[skip command]
\`\`\`
**Important**: Only skip hooks when explicitly approved.
---
**Last Updated**: [Date]
**Questions**: [Contact/Issue tracker]
```
## AGENTS.md Template (Minimal - for Simple Projects)
```markdown
# AGENTS.md - [PROJECT_NAME]
> Guidance for AI coding assistants working on [PROJECT_NAME]
## Quick Start
\`\`\`bash
[install command]
[test command]
\`\`\`
## Repository Structure
- `[src dir]/` - Source code (edit freely)
- `[test dir]/` - Test files (edit freely)
- `[build dir]/` - Build output (never commit)
- `[config files]` - Ask before modifying
## Style
- [Key style requirements]
- Run `[lint/format command]` before committing
## Testing
- Run `[test command]` - all tests must pass
- Add tests for new features
- Minimum [X]% coverage
## Commits
Use format: `type(scope): description`
Examples: `feat(parser): add JSON support`, `fix(api): handle nulls`
## Commands
- Install: `[install]`
- Test: `[test]`
- Build: `[build]`
- Lint: `[lint]`
- Format: `[format]`
```
## Guidelines
**DO:**
- Use tables for structured information (✅ ⚠️ 🚫 indicators)
- Provide exact, copy-pasteable commands
- Be explicit about permissions and restrictions
- Include examples showing correct patterns
- Show file paths using inline code: `src/file.ts`
- Keep it updated when project structure changes
- Add decision trees for complex workflows
- Include validation commands
**DON'T:**
- Write long paragraphs - use bullets and tables
- Be vague about rules ("be careful with...")
- Assume knowledge - spell out conventions
- Skip setup instructions
- Forget edge cases
- Leave ambiguity about protected files
- Use relative terms ("usually", "sometimes")
- Omit testing requirements
## Token Efficiency ⚡
**Workflow:** Discovery (25x, auto-sorted) → Navigate (defaults) → Extract configs → Commands
**DO:** `mode="discovery"` first | `matchString` > `fullContent` | Batch 3-5 queries | `minified=false` for configs | `name` patterns | Default paging (10-20/pg)
**AVOID:** `fullContent` >100KB without `charLength` | `mode="detailed"` initially | Override paging needlessly | `depth=3+`
**Pattern:**
```javascript
// ✓ Parallel discovery (pagination aware)
queries: [
{pattern: "scripts", mode: "discovery", researchGoal: "npm"}, // 10/pg
{name: "*lint*|*prettier*", researchGoal: "style"} // 20/pg
]
// ✗ Sequential detailed: {pattern: "scripts", mode: "detailed"} // Token explosion
```
## Pagination 📄
**Auto-Sort:** All tools by mod time (recent first). `view_structure`=`sortBy="time"` default, `find_files`/`ripgrep` always.
| Tool | Items/Page (def/max) | Page Param | Per-File | Type |
|------|---------------------|------------|----------|------|
| ripgrep | 10/50 | `filePageNumber` | 10-100 | Two-level |
| view_structure | 20/100 | `entryPageNumber` | N/A | Single |
| find_files | 20/100 | `filePageNumber` | N/A | Single |
**Benefits:** Recent configs first, controlled output, efficient navigation
## Security & Constraints
**Blocked patterns:**
- Sensitive: `.env*`, `*.pem`, `*.key`, `credentials.*`, `secrets.*`, `*.p12`
- Artifacts: `node_modules/`, `dist/`, `build/`, `target/`, `venv/`, `vendor/`
- System: `.DS_Store`, `.git/`, `.vscode/`, `.idea/`
**Limits:** 30s timeout, 10MB output, 100MB global memory
**If blocked/timeout:** Focus on source code, use pagination, narrow scope
## Quality Checklist
AI assistant can answer quickly (<2min):
- [ ] What directories can I edit freely?
- [ ] What must I ask before changing?
- [ ] How do I run tests?
- [ ] How do I check code style?
- [ ] What's the commit message format?
- [ ] What commands do I need?
- [ ] What files should I never touch?
- [ ] What's the testing requirement?
## Pitfalls
| Pitfall | Wrong | Right |
|---------|-------|-------|
| Read all configs | `fullContent` all configs | Discovery → selective read |
| Ignore pagination | Override defaults | Use default pagination (10-20/page) |
| Guess permissions | Assume src/ is safe | Explicit access table |
| Miss hooks | Ignore pre-commit setup | Document hook workflow |
| Vague style | "Follow conventions" | Specific: quotes, semicolons, length |
| Generic rules | Same template for all | Adapt to language/type |
| Ignore existing | Skip CLAUDE.md/.cursorrules | **Discovery first**: Find & incorporate existing agent configs |
## Core Mantras
🔍 **Discover existing first** (CLAUDE.md, .cursorrules) | 🎯 **Scannable** not prose | 🔒 **Explicit** permissions | ⚡ **Actionable** commands | 🧪 **Test-aware** requirements | 📋 **Template** but adapt | 📄 **Use default pagination** | 🕐 **Recent first always** | 🎓 **Track** research context
## Success Criteria
1. AI can start working <2min after reading
2. Clear access rules prevent accidents
3. All common commands documented
4. Testing requirements explicit
5. Commit format shown with examples
6. Protected files clearly marked
7. Troubleshooting covers common issues
8. Stays relevant 6-12 months
---
**Key Workflow:**
1. **Phase 0**:
- **FIRST**: Discover existing agent configs (CLAUDE.md, .cursorrules, .cursor/, .claude/) → Read & incorporate
- Identify (language, type, scale) → Ask if unclear
2. **Phase 1**: Map structure → Access table
3. **Phase 2**: Extract commands → Setup section
4. **Phase 3**: Find style/test → Quality sections
5. **Phase 4**: Workflow → Commit/PR guidelines
6. **Phase 5**: Domain context → Terminology
7. **Phase 6**: Protected files → Security rules
8. **Generate**: Choose template (comprehensive/minimal) → Merge existing rules → Fill sections → Validate with checklist