Best PracticesJune 11, 2026 Updated September 9, 2026 15 min read

AGENTS.md Best Practices: Write the File That Makes Your Agent Actually Follow Instructions

How to write an AGENTS.md file that AI coding agents actually follow. Template, real examples, size limits, Codex setup, and the mistakes to avoid.

Shabnam Katoch

Shabnam Katoch

Growth Head

AGENTS.md Best Practices: Write the File That Makes Your Agent Actually Follow Instructions
Free forever

Your agent. Working. Not broken.

One AI agent that just works.

No silent failures. Free forever, not a trial.

Start free

No credit card · No Docker · No config files

AGENTS.md is a Markdown file at the root of a code repository that tells AI coding agents how to work in that project. It covers the stack, build and test commands, code style, architecture constraints, and boundaries. It is read natively by 30+ AI tools including Claude Code, GitHub Copilot, Cursor, OpenAI Codex, and Gemini CLI.

60,000+ repos have one. 30+ AI tools read it. But most AGENTS.md files are either too long, too vague, or generated by an LLM (which makes your agent worse). Here's how to write one that works.

Our coding agent kept generating class components. The entire codebase was functional React with hooks. The README said "React 19, functional components." The contributing guide explained it in detail.

The agent didn't read the README. It doesn't know to.

Then we added an AGENTS.md file with one line in the style section: Always use functional components with hooks. Never use class components. Plus one code example showing the pattern.

The problem disappeared instantly.

Running more than one agent? See how to organise agents.md across multiple agents without conflicts or drift.

That's what AGENTS.md does. It's a Markdown file at the root of your repository that gives AI agents the project-specific context they need to work correctly. Not documentation for humans. Instructions for machines. And as of 2026, it's read natively by 30+ AI tools including Claude Code, GitHub Copilot, Cursor, OpenAI Codex, Gemini CLI, Windsurf, Devin, Aider, and Amazon Q.

The convention has been adopted by over 60,000 repositories and is now stewarded by the Agentic AI Foundation under the Linux Foundation. If you build with AI agents and don't have an AGENTS.md, your agents are guessing at conventions they should know.

Here's how to write one that actually improves agent behavior instead of wasting context tokens.

What goes in an AGENTS.md (and what doesn't)

The common mistake is treating AGENTS.md like documentation. Long explanations. Architecture philosophy. Design rationale. History of the project.

Your agent doesn't need to know why you chose Next.js over Remix. It needs to know that you use Next.js 15 with App Router, and the test command is pnpm test, not npm test.

Research across 2,500+ repositories found that AGENTS.md files over 150 lines deliver diminishing returns and can increase inference costs 20-23% without improving agent performance. The technical maximum is 32 KiB, but aim for under 150 lines.

Here are the sections that matter, in the order they should appear:

The AGENTS.md nutrition label: serving size under 150 lines, with project stack, build and test commands, code style with examples, architecture constraints, boundaries, and a short git workflow section.

Project stack (5-10 lines)

Language, framework, major dependencies, runtime. Be specific.

Good: Next.js 15 App Router, React 19, TypeScript 5.4, Tailwind CSS, Drizzle ORM, Bun

Bad: This is a modern web application built with React and various supporting libraries.

Build and test commands (5-10 lines)

Exact commands with exact flags. Package manager matters. Build targets matter.

Good: Build: bun run build. Test: bun test. Lint: bun run lint --fix. Deploy: bun run deploy:staging

Bad: Run the standard build and test commands as described in package.json.

Code style conventions (10-20 lines, with examples)

One code example per convention beats three paragraphs describing it. This is the single most important insight from studying effective AGENTS.md files. Show, don't tell.

Architecture constraints (5-15 lines)

Directory structure rules. Module boundaries. Import restrictions. Data flow patterns.

Boundaries (5-10 lines)

What the agent should never touch. "Never commit secrets" was the most common helpful constraint across the 2,500-repository analysis. Add: generated files, legacy modules, configuration files that shouldn't change, directories managed by other tools.

Git workflow (5 lines)

Branch naming, commit message format, PR conventions. Squash merge only. Conventional commits: feat:, fix:, chore:, docs:.

AGENTS.md size: what the research says

Keep it under 150 lines. That is the single number worth remembering, and it is the one most teams get wrong in the same direction: too long.

Two independent data points support it. The 2,500-repository analysis found diminishing returns past 150 lines, with inference costs rising 20-23% and no measurable improvement in agent behaviour. Separately, Coldtea's field study of the 100 biggest GitHub repos found the median AGENTS.md runs 1,198 words across roughly 14 headings, with a barbell distribution: 37% are sprawling constitutions past 1,500 words, while one file in ten comes in under 150 words.

Note the units. The 150-line guidance and the 1,198-word median measure different things, and a 150-line file with code blocks can easily exceed 1,198 words. Treat both as a ceiling signal rather than a target: the technical maximum is 32 KiB, but nothing in the data suggests longer files perform better.

The pattern across both studies is the same. Shorter, accurate, project-specific files beat comprehensive generic ones. Start at 30-50 lines covering stack, build commands, code style with examples, and boundaries. Add a section only when an agent consistently makes a specific mistake.

The three mistakes that make AGENTS.md useless

The AGENTS.md hall of shame: the three mistakes that make a file useless — letting an LLM generate it, describing conventions instead of showing them with code, and not updating it.

Mistake 1: Letting an LLM generate it

This is the most common mistake and the most damaging. Research found that LLM-generated AGENTS.md files reduce task success in 5 out of 8 tested settings and add 2.45-3.92 extra steps per task. The file-based approach is only one way to do this; on a no-code AI agent builder the same instructions live in the agent's role and are versioned for you.

Why? LLMs generate generic, verbose instructions that state the obvious. "Follow best practices for error handling." "Write clean, maintainable code." "Use descriptive variable names." Your agent already knows this. You're burning context tokens on advice the model was trained to follow by default.

Write your AGENTS.md by hand. Include only the conventions that are specific to YOUR project and that an agent wouldn't know without being told.

Mistake 2: Describing conventions instead of showing them

Bad:

Use our custom error handling approach where errors bubble up through
the service layer and are caught by the global error handler rather
than being caught at individual function level.

Good:

// Error handling: Let errors propagate. Do not wrap individual calls
// in try/catch. The global handler catches everything.

// CORRECT
async function getUser(id) {
  const user = await db.users.findById(id);
  return user;
}

// WRONG
async function getUser(id) {
  try {
    const user = await db.users.findById(id);
    return user;
  } catch (e) {
    logger.error(e);
    throw e;
  }
}

The code example communicates instantly what three paragraphs of description fail to convey.

Mistake 3: Not updating it

An AGENTS.md with stale table names, deprecated commands, or outdated architecture constraints is worse than no AGENTS.md. It actively misleads the agent.

Update your AGENTS.md in the same PR where conventions change. Set a quarterly review to remove stale guidance. A useful signal: when an agent repeatedly produces incorrect output, that's a gap in your AGENTS.md.

Does AGENTS.md actually work?

This gets asked often enough to deserve a direct answer, and the honest one is: yes, but only the hand-written kind.

The skepticism is earned. Generic, LLM-generated AGENTS.md files reduce task success in 5 out of 8 tested settings and add 2.45-3.92 extra steps per task. If you asked an agent to write your AGENTS.md, ran it, and saw no improvement, that result is exactly what the research predicts. The file wasn't neutral. It made things worse.

What works is narrow: instructions that tell the agent something it could not have inferred from the codebase. Your package manager. Your test command with its exact flags. The one directory it must never touch. The convention your codebase follows that looks unusual to a model trained on everyone else's code.

The test for any line in your AGENTS.md: would a competent developer who had never seen this repo get this wrong? If no, delete the line. It is costing you context tokens to restate the model's defaults back to itself.

AGENTS.md vs CLAUDE.md vs .cursorrules (which do you need?)

Here's the honest answer: start with AGENTS.md, add tool-specific files only if you need their unique features.

The universal file and its specialist cousins: AGENTS.md is the universal core read by 30+ tools, while CLAUDE.md adds @imports for Claude Code and .cursorrules adds glob-based rules for Cursor.

AGENTS.md has the broadest compatibility. 30+ tools read it natively. It's the universal format.

CLAUDE.md is Claude Code-specific. Its unique feature is @imports that compose instructions from multiple files. If your team uses Claude Code exclusively and needs modular instruction files, add CLAUDE.md alongside AGENTS.md.

.cursorrules is Cursor-specific. Its unique feature is MDC frontmatter with glob patterns that activate different instructions for different file types. If your team uses Cursor and needs per-filetype rules, add .cursorrules.

90% of the content across all three files is identical. Build commands, architecture rules, testing conventions, and boundaries don't change per tool. A converter tool called rule-porter can translate between formats if needed.

Write AGENTS.md first. It's the single source of truth that every tool reads. Add CLAUDE.md or .cursorrules only for features that AGENTS.md can't express.

Does AGENTS.md work with OpenAI Codex?

Yes. Codex reads AGENTS.md natively, and the same file works across Codex, Claude Code, Cursor, and Gemini CLI without changes. That is the whole point of the convention.

Codex is worth calling out separately because its resolution rules are more layered than most tools. It builds an instruction chain by walking from the top down and concatenating at most one file per directory:

  1. ~/.codex/AGENTS.md (your personal global file, applied across every project)
  2. <git-root>/AGENTS.md (the repository file, committed and shared with your team)
  3. Any AGENTS.md in intermediate directories on the path
  4. The AGENTS.md in your current working directory

Files closer to where you are working take precedence over the ones above them. If you need a subdirectory to replace inherited instructions rather than add to them, use AGENTS.override.md at that level. Codex rebuilds this chain on every run, so there is no cache to clear when you edit a file.

One practical warning. Codex executes the build and test commands from your AGENTS.md in its sandbox. A stale or wrong command doesn't produce a helpful error; the agent runs it, watches it fail, and works around it. Before you rely on any command in your AGENTS.md, run it verbatim in a fresh terminal. Copy the command that worked, not the one you remember writing.

Behaviour can differ between Codex CLI and Codex in ChatGPT, so check OpenAI's AGENTS.md documentation if you depend on a specific precedence detail.

Global vs directory-level AGENTS.md

There are three scopes, and mixing them up is a common source of "why is the agent ignoring my instructions."

Global (personal). A file in your tool's config directory, such as ~/.codex/AGENTS.md. It applies to every project you open. Use it for preferences that are about you rather than the project: how verbose you want explanations, whether you want the agent to ask before running destructive commands. It is not committed anywhere, so your teammates never see it.

Repository root. The file most people mean by "AGENTS.md." Committed to the repo, shared by the whole team. Use it for build commands, code style, architecture constraints, testing conventions, and boundaries that apply everywhere in the project.

Subdirectory. Overrides or extends the root file for one directory. Use it when a directory genuinely has different rules: a package with its own build command, a /mobile directory on a different framework than /web, a test suite that runs on a different runner.

Most projects need only the root file. Add subdirectory files when a directory has genuinely different rules, not to organise a root file that has grown too long. If your root AGENTS.md is too long, the fix is deleting lines, not distributing them.

Should AGENTS.md be committed to git?

Yes. AGENTS.md belongs in version control alongside the code it describes. It is project documentation, not a personal preference file.

Commit it at the root of the repo. Every contributor and every AI tool reads it from there, and it gets reviewed in the same PR as the convention change that prompted it. If team members keep their own local AGENTS.md instead, the agent gets different instructions depending on who triggered it, which is a genuinely difficult class of bug to notice.

Two exceptions. Personal preferences that are about you rather than the project belong in your global file (~/.codex/AGENTS.md), not the repo. And if your instructions need to reference secrets or internal URLs, keep those in .env or a gitignored file and reference them from AGENTS.md rather than inlining them.

Security: AGENTS.md is a prompt-injection surface

This is the part of the convention that gets least attention and deserves more.

NVIDIA's AI Red Team demonstrated an indirect AGENTS.md injection against OpenAI Codex, in which a malicious dependency hijacks the agent's behaviour by abusing instruction precedence. The attack requires an already-compromised dependency, so it is not a reason to panic about every repo you clone. But it illustrates something structural: agent instruction files are executable context, and they widen the supply-chain attack surface in a way that traditional prompt injection does not.

The practical mitigations are unglamorous:

  • Read the AGENTS.md in any repo you clone before you point an agent at it. It takes fifteen seconds and it is the entire defence for the common case.
  • Treat AGENTS.md the way you treat a Makefile or a postinstall script. It influences commands that run on your machine.
  • Review changes to AGENTS.md in code review with the same attention as changes to CI config. A one-line edit can redirect what an agent does across the whole repo.
  • Run agents in a sandbox where you can, so an instruction you missed has a smaller blast radius.

Beyond coding: AGENTS.md for business agents

Here's where things get interesting. The AGENTS.md convention was born in coding repositories. But the same principle applies to any AI agent: give the agent structured, project-specific context at session start, and it performs better.

For business agents (support, sales, operations), the equivalent configuration includes:

Same passport, two different languages: a coding agent's AGENTS.md (stack, commands, code style, boundaries) maps to a business agent's config (identity, capabilities, constraints, trust level, escalation, output format).

  • Identity: Who the agent is. Name, role, company, tone of voice.
  • Capabilities: What the agent can do. Which tools it has access to. Which integrations it can call.
  • Constraints: What the agent cannot do. Actions that require human approval. Topics it should escalate. Data it should never share.
  • Trust level: How much autonomy the agent has. Draft-only? Execute with approval? Fully autonomous within boundaries?
  • Escalation rules: When to hand off to a human. Sentiment triggers, confidence thresholds, sensitive categories.
  • Output format: How the agent should respond. Structured JSON? Natural language? Specific templates?

For coding agents, AGENTS.md is a file you write and maintain manually. For business agents, this configuration should be visual and managed through a platform.

This is exactly how BetterClaw's agent builder works. Every field that would go into a business AGENTS.md is a visual input in the builder. Identity, capabilities, constraints, trust levels (Intern, Specialist, Lead), escalation rules, output format. Version-controlled by the platform. No file management. No forgetting to update. Free plan with 1 agent and 100 credits a month, Basic at $19/month, and Pro at $49/month for 5 agents. BYOK with zero markup.

The annotated template (copy and adapt)

Here's a minimal, effective AGENTS.md template. Delete sections that don't apply. A shorter, accurate file outperforms a comprehensive, generic one.

# Project Name

Next.js 15 App Router, React 19, TypeScript 5.4, Tailwind CSS, Drizzle ORM, Bun.

## Commands

Build: `bun run build`
Test: `bun test`
Lint: `bun run lint --fix`
Single test: `bun test path/to/file.test.ts`

## Code Style

Functional components only. Never class components.
Use `const` exclusively. Never `var`, never `let` unless reassignment is needed.
Named exports only. Never default exports.

// Component pattern:
export const UserCard = ({ name, email }: UserCardProps) => {
  return <div className="p-4">{name}</div>;
};

## Error Handling

Let errors propagate. Do not wrap individual calls in try/catch.
The global error handler in middleware.ts catches everything.

## Architecture

/app         -> Routes and page components
/components  -> Shared UI components
/lib         -> Business logic and utilities
/db          -> Database schema and migrations

Never import from /app into /lib. Data flows one direction.

## Boundaries

Never modify files in /generated/.
Never commit .env or any file containing secrets.
The /legacy/ module uses sync patterns. Do not convert to async.

## Git

Squash merge only.
Conventional commits: feat:, fix:, chore:, docs:.
Branch format: type/short-description (e.g., feat/user-auth).

That's under 50 lines. It communicates everything an agent needs to work correctly in this codebase. Every line is specific. Every section has a reason to exist.

AGENTS.md examples: three files for three project types

The template above is deliberately generic. Real files are shorter and stranger than templates, because they only contain the things that specific project's agents kept getting wrong. These three are representative examples written to show that range, not copies of any named repository's file.

Example 1: a Next.js web app (12 lines)

# Storefront

Next.js 15 App Router, TypeScript, Tailwind, Bun.

Build: `bun run build` | Test: `bun test` | Lint: `bun run lint --fix`

Server Components by default. Add `'use client'` only for event handlers or hooks.
Never fetch in a Client Component. Fetch in the page, pass data down as props.
Named exports only.

Never edit `/app/generated/`. It is regenerated on every build.
Never add a dependency without asking. This bundle is size-budgeted.

What it gets right: the 'use client' rule is the one thing an agent reliably gets wrong in App Router projects, and it is stated as a rule with its exception, in one line.

Example 2: a Python FastAPI backend (16 lines)

# Billing API

Python 3.12, FastAPI, SQLAlchemy 2.0 (async), Alembic, uv.

Install: `uv sync` | Run: `uv run uvicorn app.main:app --reload`
Test: `uv run pytest -x` | Single test: `uv run pytest tests/test_invoices.py::test_name`

All DB access is async. Never use the sync Session. Never call `.commit()` in a
route handler; the dependency in `app/deps.py` handles the transaction boundary.

Pydantic models live in `app/schemas/`. SQLAlchemy models live in `app/models/`.
Never import a SQLAlchemy model into a route signature.

Schema changes require a migration: `uv run alembic revision --autogenerate -m "..."`.
Never edit an existing migration that has been merged.

Money is `Decimal`, never `float`. Amounts are stored in minor units (cents).

What it gets right: the money rule. It is one line, it is unambiguous, and it prevents a class of bug that is expensive to find later.

Example 3: a monorepo (22 lines)

# Platform monorepo

pnpm workspaces + Turborepo. Node 22.

apps/web    -> Next.js 15 storefront
apps/admin  -> Vite + React admin panel
packages/ui -> Shared component library
packages/db -> Drizzle schema and client

Always run commands from the repo root: `pnpm turbo build --filter=web`.
Never `cd` into a package and run `pnpm install` there.

Test: `pnpm turbo test` | Single app: `pnpm turbo test --filter=admin`

apps/* may import from packages/*. packages/* must never import from apps/*.
packages/ui must never import from packages/db. UI takes data as props.

Adding a dependency to a package: `pnpm add <pkg> --filter=<package-name>`.

Each app has its own AGENTS.md with framework-specific rules. This file covers
the workspace-level rules only.

What it gets right: the import direction rules, and the last line, which tells the agent that more specific instructions exist further down the tree.

The common thread across all three: every line is a rule an agent would break without being told, written as a constraint rather than an explanation. None of them describe what the project is for.

Gartner projects 40% of enterprise applications will embed AI agents by end of 2026. The teams that invest 30 minutes in a good AGENTS.md today will save hours of agent correction every week. The teams that skip it will keep wondering why their agent "doesn't follow instructions."

Treat it like a bonsai, not an encyclopedia: start small, prune stale guidance, and add a section only when an agent consistently gets something wrong. A shorter, accurate file beats a comprehensive, generic one.

The best AGENTS.md file is the one your team actually maintains. Not the one that comprehensively documents every edge case and is outdated by next sprint.

Start with 30 lines. Add a section when an agent consistently gets something wrong. Remove a section when the convention changes. Treat it like code, not documentation.

And if your agents are business agents, not coding agents, this entire configuration belongs in a visual builder, not a markdown file. Give BetterClaw a look. Free plan with 1 agent and 100 credits a month, Basic at $19/month, and Pro at $49/month for 5 agents. Agent configuration through the UI. No files to forget to update.

Frequently Asked Questions

What is an AGENTS.md file?

AGENTS.md is a Markdown file placed at the root of a code repository that provides AI coding agents with project-specific instructions: build commands, code style conventions, architecture constraints, testing procedures, and boundaries. It's read natively by 30+ AI tools including Claude Code, GitHub Copilot, Cursor, OpenAI Codex, and Gemini CLI. Over 60,000 repositories have adopted it, and it's now stewarded by the Agentic AI Foundation under the Linux Foundation.

How does AGENTS.md compare to CLAUDE.md and .cursorrules?

AGENTS.md has the broadest compatibility (30+ tools read it). CLAUDE.md adds Claude-specific features like @imports for modular instruction files. .cursorrules adds Cursor-specific features like glob-based auto-attach rules. 90% of the content is identical across all three. Start with AGENTS.md as your universal source of truth, and add tool-specific files only for features AGENTS.md can't express. A converter tool (rule-porter) can translate between formats.

How long should an AGENTS.md file be?

Under 150 lines. Research across 2,500+ repositories found that files beyond 150 lines deliver diminishing returns and can increase inference costs 20-23% without improving agent performance. The technical maximum is 32 KiB. Shorter, accurate files consistently outperform comprehensive, generic ones. Start with 30-50 lines covering stack, build commands, code style (with examples), and boundaries. Add sections only when an agent consistently makes a specific mistake.

Should I use an LLM to generate my AGENTS.md?

No. Research found that LLM-generated AGENTS.md files reduce task success in 5 out of 8 tested settings and add 2.45-3.92 extra steps per task. LLMs generate generic, verbose instructions that state things agents already know ("write clean code," "follow best practices"). Write your AGENTS.md by hand with only the conventions specific to your project that an agent wouldn't know without being told. One real code snippet is worth more than three paragraphs of description.

Can I use the same AGENTS.md for Codex and Claude Code?

Yes. One AGENTS.md serves both, plus Cursor, Gemini CLI, and 30+ other tools, with no per-tool changes. Codex reads it natively. Codex builds an instruction chain from your global ~/.codex/AGENTS.md, then the repository root file, then any AGENTS.md in intermediate directories, then the one in your current working directory, with closer files taking precedence. Use AGENTS.override.md in a subdirectory to replace inherited instructions instead of adding to them. Codex also executes the build and test commands in your AGENTS.md, so verify each one runs in a fresh terminal before relying on it. Behaviour can differ between Codex CLI and Codex in ChatGPT.

Do I commit AGENTS.md or add it to .gitignore?

Commit it. AGENTS.md is project documentation and belongs in version control at the repo root, so every contributor and every AI tool reads the same instructions. If team members keep local-only copies, the agent gets different instructions depending on who triggered it. Keep personal preferences in your tool's global file (such as ~/.codex/AGENTS.md) instead, and never inline secrets or internal URLs; reference them from .env or a gitignored file.

Can AGENTS.md principles apply to business agents, not just coding agents?

Yes. The core principle (give the agent structured, specific context about identity, capabilities, constraints, and boundaries) applies to any AI agent. For business agents, the equivalent sections are identity, capabilities, constraints, trust levels, escalation rules, and output format. The difference is that business agent configuration belongs in a visual builder (like BetterClaw) rather than a markdown file, since business agents don't operate from a code repository.

Want to skip the setup?

BetterClaw does this in 60 seconds. No Docker, no config files.

Start free
Tags:agents.md best practicesagents md fileagents md templateagent configuration fileagents md formatagents md guideagents md exampleagents md sizecodex agents mdglobal agents md
Share this article
Was this helpful?