How to Write the Perfect AGENTS.md file

If you want to understand How to Write the Perfect AGENTS.md file, the big idea is simple: make life easier for coding agents before they ever touch your codebase. An AGENTS.md file is an operating manual for autonomous or semi-autonomous coding agents, written in plain Markdown and placed in a location that the repository can find.

Table of Contents

It defines the audience, explains the purpose, sets a quality bar, demands concrete commands, warns against vague advice, and even specifies required sections and a self-check before output. In other words, it is designed to reduce guesswork and increase the likelihood of safe execution.

That is exactly why AGENTS.md matters. When an agent opens a repo, it should not have to reverse-engineer how to run the app, where to make changes, how to test them, or what it must never do. A strong AGENTS.md tells it all of that upfront.

What Is AGENTS.md?

AGENTS.md is a Markdown file that provides AI coding agents with clear instructions for working within a specific software repository. Think of it as a repo-specific playbook. It explains what the project is, how to set it up, how to safely change code, how to test it, and how to follow the team’s workflow.

A README usually speaks to humans at a broad level. An AGENTS.md file speaks to execution.

It answers questions like:

  • What command installs dependencies?
  • Which port does the dev server run on?
  • Where is the domain logic?
  • What tests must pass before a PR?
  • Are migrations allowed?
  • Which actions are destructive?
  • What should never be run against production?

So, what is the AGENTS.md file in plain English? It is the instruction layer between your repository and the agent that is trying to work within it.

Why the File Exists

AI agents are fast, but speed without context is risky. Without repo-specific guidance, they guess. They may use the wrong command, change the wrong folder, skip an important test, or log something sensitive. AGENTS.md exists to stop that.

Who Reads It

The main audience is AI coding agents, but humans benefit too. New contributors, reviewers, and maintainers can all use the file to understand how work is expected to happen.

What Is the Purpose of an AGENTS.md File?

The purpose of an AGENTS.md file is to create a single, reliable, repository-level source of truth for agent behavior.

That sounds formal, but the idea is practical. Instead of hoping an agent infers conventions from scattered files, such as Project Overview, Tech Stack, Setup & Commands, Project Structure, Code Style, Testing, Security, Git & PR Workflow, and Agent Behavior Guidelines.

A good AGENTS.md serves five purposes at once.

1. It reduces guesswork

Agents should not have to search six folders to discover how to run the project. Give them the exact commands for install, dev, test, lint, typecheck, and build.

2. It protects code quality

If the repo forbids any, discourages @ts-ignore, requires typed errors, or expects tests in affected areas to pass before merge, say so. That turns style from a suggestion into a rule.

3. It protects the environment

Some commands are destructive. Some must never touch production. Some migrations require review. AGENTS.md is where those warnings should live.

4. It aligns agents with team workflow

Branch names, commit message format, CI requirements, rebase policy, and PR expectations all belong here. An agent should know how the team works before it opens a pull request.

5. It creates a predictable output

The more specific the instructions, the more consistent the results. That means fewer noisy diffs, fewer broken assumptions, and fewer human cleanup passes.

Benefits of Using AGENTS.md

The benefits of using AGENTS.md are bigger than they first appear. On the surface, it looks like one more documentation file. In practice, it can save hours, prevent mistakes, and improve trust in AI-assisted development.

Faster Onboarding

Every repo has hidden knowledge. Maybe tests live in a non-standard folder. Maybe the backend runs on one port and the frontend proxies to another. Maybe local secrets come from a template file. If that information only lives in someone’s head, every new contributor pays the price.

AGENTS.md turns tribal knowledge into written instructions.

Safer Automation

This is the big one. The file can tell agents:

  • never commit secrets
  • Never run destructive commands against production
  • Always review migrations before applying them
  • never log tokens or sensitive payloads
  • keep tests and docs in sync with code changes

A good AGENTS.md file calls for safety, concrete guardrails, and clear handling of missing information through TODO: markers instead of fake certainty.

More Consistent Changes

Without AGENTS.md, two different agent runs may produce two wildly different results. One may refactor too much. Another may ignore house style. Another may skip docs. A strong file narrows the variance.

Better Reviews

Reviewers do not just review code. They review the process. When AGENTS.md standardizes what the agent should have done, reviewers know what to expect.

Better Collaboration Between Humans and Agents

This is easy to miss. AGENTS.md is not just for bots. It gives humans a shared contract too. That makes collaboration smoother because expectations are visible and searchable

What Your Example Gets Right

Your example AGENTS.md prompt is not just useful; it is a very good model for how to think about these files. It gets several important things exactly right.

It defines the audience clearly

The file is for AI coding agents first, with human developers as secondary readers. That matters because the writing style changes. The file must be direct, operational, and unambiguous.

It defines the purpose clearly

It says the file should explain what the project is, how to set it up, how to safely change code, and how to test and ship it correctly. That is the heart of a good AGENTS.md.

Elsewhere On TurboGeek:  How to Boot Windows into Safe Mode (Windows 11/10 Guide)

It demands concrete detail

It asks for real commands, real paths, real tools, real ports, and project-specific rules. That is exactly what agents need.

It forbids vague filler

A good AGENTS.md warns against advice like “write clean code” or “follow best practices” unless those ideas are translated into project-specific rules. That is a huge win because vague instructions sound nice but do almost nothing.

It handles uncertainty honestly

Instead of inventing details, it tells the writer to use TODO: for missing information and clearly mark guesses. That is one of the strongest trust-building habits an AGENTS.md author can adopt.

It includes a self-check

A final self-check section is desirable. It makes the writer verify that the file contains concrete commands, clear workflow rules, explicit testing guidance, and no contradictions. In other words, it does quality control before the agent ever reads the file.

The Anatomy of a Great AGENTS.md

A great AGENTS.md file is not long for the sake of being long. It is complete, scannable, and actionable. Here are the sections that matter most.

Project Overview

Start with a short explanation of what the project does, who it serves, and whether the file is global or scoped to a subproject. Keep this tight. Agents do not need a marketing story. They need context.

Tech Stack

List the technologies by concern:

  • frontend
  • backend or APIs
  • data stores
  • messaging
  • dev tooling
  • infrastructure

If versions matter, include them.

Setup & Commands

Include the happy-path commands for:

  • installing dependencies
  • preparing environment files
  • starting local services
  • running dev servers
  • running tests
  • running lint and type checks
  • building for production

Also call out destructive commands and anything that must never be run against production.

Project Structure

Show the folder map that actually matters:

  • domain logic
  • UI or components
  • API handlers
  • tests
  • infra and deployment config
  • shared packages

This saves the agent from changing the wrong layer.

Code Style & Conventions

Be clear about:

  • formatter and linter
  • naming rules
  • preferred patterns
  • banned patterns
  • type-safety rules
  • logging rules
  • how errors should be handled

Testing

Say what framework is used, where tests live, how they are named, how to run them, and what must pass before commit or merge.

Development Environment

Include required tool versions, Docker or local service setup, env file names, and any OS-specific gotchas.

Security

This section should be blunt. No secrets in git. No sensitive logs. No casual external calls. No guessing around auth.

Git & PR Workflow

Spell out branch naming, commit format, local checks, CI expectations, and PR scope.

Important Context & File References

Point agents to the relevant docs. For Markdown formatting, tables, and code blocks, GitHub Docs and the Markdown Guide are solid references.

Agent Behavior Guidelines

This is where you define how the agent should behave, not just what the repo contains. For example:

  • prefer minimal changes over broad refactors
  • Update tests and docs with code changes
  • Use comments only when they add real value
  • get review before irreversible changes

How to Write the Perfect AGENTS.md file the Right Way

Now let’s make this practical. Here is the best way to draft one.

Start With Reality, Not Ideals

Do not write the file you wish the repo had. Write the file the repo needs right now.

That means checking:

  • actual commands in package.json, Makefile, pyproject.toml, or build scripts
  • actual folder names
  • actual ports
  • actual service names
  • actual CI checks

If something is missing, say so. Use TODO:. Honest gaps are better than polished fiction.

Write for Action

Every section should answer “What should the agent do?”

Bad:

  • Follow clean architecture principles.

Better:

  • Keep business logic in src/domain/.
  • Do not place API calls inside UI components.
  • Add tests under tests/unit/ for changed services.

The second version is concrete, testable, and useful.

Prefer Commands Over Explanations

Agents do not need a lecture on dependency management. They need the exact command:

npm ci
cp .env.example .env.local
docker compose up -d db redis
npm run dev
npm run test
npm run lint
npm run typecheck
npm run build

That is the difference between documentation that helps and documentation that delays.

Mark Unknowns Clearly

If information is missing but necessary, mark it with TODO: and say what still needs to be provided.

For example:

- TODO: confirm whether staging deploys use `scripts/deploy-staging.sh` or GitHub Actions only.
- TODO: provide local Redis startup command for macOS without Docker.

That keeps the file trustworthy.

Separate Rules From References

AGENTS.md should not become a copy of the README. Use it to summarize the critical rules and point to deeper docs when needed.

Good pattern:

  • critical commands and guardrails live in AGENTS.md
  • background and long explanations live elsewhere

Be Specific About Safety

A perfect AGENTS.md includes clear “do not cross” lines:

  • Never run database reset commands against shared environments.
  • Never commit .env files.
  • Never log bearer tokens or full auth payloads.
  • Get approval before schema migrations or large refactors.

Keep It Lean

A bloated file gets skimmed. A clean file gets used. The goal is signal, not ceremony.

Common Mistakes to Avoid

Even good teams make these mistakes when they first write AGENTS.md.

Being Too Generic

If the file could be dropped into any repo unchanged, it is probably too vague.

Repeating the README

AGENTS.md should complement the README, not clone it. Put execution-critical information here and leave broad project background elsewhere.

Inventing Commands

This is one of the worst mistakes. A made-up command looks authoritative until it fails. Then trust is gone.

Skipping Security Rules

If you do not state secret-handling, auth boundaries, and destructive-command rules, the file is incomplete.

Ignoring Workflow

An agent can write good code and still create a bad PR if it does not know branch naming, test expectations, or merge rules.

Forgetting Subprojects

In monorepos, the root file may not be enough. Subprojects often need their own AGENTS.md with local rules and precedence notes.

A Simple Template You Can Reuse

Here is a lightweight structure that works well in most repositories:

# AGENTS.md## Project Overview
## Tech Stack
## Setup & Commands
## Project Structure
## Code Style & Conventions
## Testing
## Development Environment
## Security
## Git & PR Workflow
## Important Context & File References
## Agent Behavior Guidelines
## Notes for Subprojects

That template aligns closely with the structure in your attached example, which is one reason your example is so strong. It is complete without being messy.

Example AGENTS.MD prompt

This is one of the very best AGENTS.MD files I have found online.

Elsewhere On TurboGeek:  How to Install and Use Glances on RHEL 9/8, Rocky Linux, & CentOS Stream

Credit to the Author: https://lmstudio.ai/dirty-data/agents.md-generator

You are an expert `AGENTS.md` author. Treat every output as if it will be used directly by autonomous coding agents working on a real repository.

Your sole responsibility is to generate a single, high-quality `AGENTS.md` file for a specific software project.

=== Audience and purpose ===
- Audience: AI coding agents (and human developers who read agent instructions), not end users.
- Purpose: Provide one authoritative, predictable place that explains how agents should work on this repository:
  - What the project is.
  - How to set up and run it.
  - How to change code safely.
  - How to test and ship it correctly.
- Relationship: Complement `README.md` and other docs; do not repeat them except for critical commands and rules.

=== Quality bar ===
The file must:
- Be concrete: real commands, real paths, real tools, real ports.
- Be actionable: every section should tell an agent what to do or avoid.
- Be consistent: no conflicts with existing configs or obvious conventions.
- Be safe: include clear guardrails for dangerous actions.
- Be lean: minimal prose, maximum signal.

Avoid:
- Vague advice (“write clean code”, “follow best practices”) without project-specific rules.
- Mixing user-personal preferences or global config instructions into this project file.
- Long stories or explanations that obscure the actual rules.
- Empty skeleton sections or template text that is not adapted to the project.

If information is missing but necessary:
- Mark it with `TODO:` plus what needs to be provided.
- Only infer concrete commands or paths when you clearly state they are guesses.

=== Inputs and interrogation ===
Before drafting, ensure you understand at least:

1) Repository shape
- Project name and one-sentence purpose.
- Monorepo vs single project.
- Major apps/packages and their roles (for monorepos).

2) Tech stack
- Main languages and frameworks.
- Frontend: framework, language, major libraries.
- Backend/APIs: frameworks, languages, protocols (REST/grpc/GraphQL, etc.).
- Data: databases, caches, search/search engines.
- Messaging: queues, brokers, topics.
- Dev tooling: package managers, build tools, test frameworks, linters, formatters, type-checkers.
- Infrastructure: cloud provider, containers, orchestration, CI/CD, observability tools.

3) Environment and commands
- Required tool versions (Node, Python, Go, Java, package managers, Docker, etc.).
- Required local services and how to start them.
- Env file layout and how secrets or dummy values are provided locally.
- Exact commands for:
  - Installing dependencies.
  - Starting dev server(s) and main ports.
  - Running tests (full and focused).
  - Running linters and type-checkers.
  - Building for production.
  - Any routine tasks (migrations, codegen, seeding, formatting).

4) Structure and conventions
- Directory layout and key entrypoints.
- Where domain logic, UI, APIs, tests, infra, and shared libraries live.
- Code style: formatting tools and settings, naming conventions.
- Architectural patterns and anti-patterns.
- Type-safety, error handling, logging policies.

5) Testing, security, and workflow
- Testing strategy and required coverage or practices.
- Security constraints: secrets, sensitive data, auth, network restrictions.
- Git and PR workflow: branching, commit messages, force-push policy, required checks.

Question policy:
- Ask the user targeted questions only about missing or ambiguous items.
- Use repository context (file layout, config files) to infer reasonable defaults.
- Clearly mark inferred commands/paths with `TODO:` and a short explanation.

Never silently invent specifics that look authoritative.

=== Output contract ===
- Output only the final `AGENTS.md` file, as Markdown ready to commit.
- Do not include explanations, analysis, or meta commentary outside the file content.
- Use clear headings, bullets, and code blocks.
- Prefer imperative, direct phrasing over descriptive prose.

=== Required structure ===
Use the following top-level sections unless the user explicitly requests another structure. Skip sections that obviously do not apply; do not add extra top-level sections without clear benefit.

1. `# AGENTS.md`
   - Title.

2. `## Project Overview`
   - 1–3 sentences describing:
     - What the project does and for whom.
     - Core architecture (e.g., SPA + API, service, CLI).
   - Note whether this file is global (root) or scoped to a subproject/package.

3. `## Tech Stack`
   - Group by concern (Frontend, Backend/APIs, Data Stores, Messaging/Streaming, Dev Tooling, Infrastructure).
   - Name specific technologies and versions where relevant.

4. `## Setup & Commands`
   - Present a single “happy path” shell code block for a new agent:
     - Install dependencies.
     - Prepare env files and local services.
     - Start dev servers (with ports).
     - Run tests, linters, and type-checkers.
     - Build and (if relevant) deploy.
   - Call out:
     - Commands that are destructive or environment-sensitive.
     - Commands that must never run against production.

5. `## Project Structure`
   - Provide a compact directory tree or bullet list of key paths.
   - Explicitly note locations for:
     - Domain/business logic.
     - UI/components.
     - API endpoints/handlers.
     - Tests.
     - Infrastructure/configuration (IaC, deployment).
     - Shared libraries/packages.
   - Document non-obvious conventions (e.g., feature folders, `src/` layout, `packages/` in monorepos).

6. `## Code Style & Conventions`
   - Specify:
     - Formatting tools (and how to run them).
     - Naming and casing rules.
     - Preferred patterns and explicitly banned patterns.
     - Type-safety requirements (e.g., discourage/forbid `any`, `@ts-ignore`).
     - Error handling and logging policies (where to log, what not to log).
   - Include the commands agents must execute to enforce style locally.

7. `## Testing`
   - Name the test frameworks and tools.
   - Provide commands to:
     - Run the full suite.
     - Run tests for a specific file/folder/pattern.
   - Document test file locations and naming conventions.
   - State the minimum bar before commit/merge (e.g., all tests in affected areas must pass).

8. `## Development Environment`
   - List required tool versions.
   - Describe how to start required services locally (Docker compose, dev containers, emulators).
   - Explain env file usage:
     - Which files exist.
     - How values are obtained (or mocked) for local development.
   - Note any OS-specific issues, limits, or performance tips that might affect agents.

9. `## Security`
   - Explicitly forbid committing secrets and describe how to handle them correctly.
   - Call out sensitive domains (PII, financial, tokens) and handling rules.
   - Highlight critical auth/authorization code and relevant files.
   - Document restrictions on external calls, telemetry, and logging of sensitive data.

10. `## Git & PR Workflow`
    - Branching scheme and naming conventions.
    - Commit message format (including prefixes, tags, or scopes).
    - Policies for force-push, rebase, and merge.
    - Required local checks and CI checks before opening/merging PRs.
    - Expectations for PR size, scope, and accompanying updates (tests, docs).

11. `## Important Context & File References`
    - List key docs with explicit paths (e.g., `README.md`, `docs/ARCHITECTURE.md`, `docs/API.md`, `docs/SECURITY.md`).
    - For monorepos:
      - Enumerate additional `AGENTS.md` files in subdirectories.
      - State that the closest `AGENTS.md` to a file takes precedence on conflicts.

12. `## Agent Behavior Guidelines`
    - Describe how agents should:
      - Prioritize minimal changes vs broader refactors.
      - Keep tests and docs in sync with changes.
      - Use comments and logging responsibly.
      - Handle migrations and other irreversible changes (review, backups, approvals).

13. `## Notes for Subprojects` (monorepos)
    - List major apps/packages and how they relate.
    - Clarify when to edit root vs subproject `AGENTS.md`.
    - Give brief rules for when and how to add new `AGENTS.md` files in subdirectories.

=== Self-check before output ===
Before you respond, internally verify that:
- Every included top-level section contains concrete, project-specific information or clearly marked `TODO:` items.
- All critical commands (install, dev, test, lint, typecheck, build) are present or clearly marked as missing.
- Testing, security, and Git/PR expectations are explicit enough that an agent could follow them without guessing.
- There are no obvious contradictions with the described stack or structure.

Then output the `AGENTS.md` file content only.


FAQ

What is Agents.MD used for?

Agents.MD, usually written as AGENTS.md, is used to tell AI coding agents how to work inside a repository safely, consistently, and efficiently.

Elsewhere On TurboGeek:  Accessing Amazon Workspaces

Is AGENTS.md the same as README.md?

No. A README explains the project broadly. AGENTS.md gives repo-specific execution instructions, guardrails, workflows, and change rules for agents.

Should AGENTS.md include exact commands?

Yes. Exact commands are one of the most useful parts of the file because they reduce guesswork and improve reliability.

What should never go into AGENTS.md?

Do not include secrets, vague filler, fake commands, or project rules you have not confirmed.

Can humans benefit from AGENTS.md too?

Absolutely. New contributors, maintainers, and reviewers can all use it to understand repository expectations.

What if I do not know every detail yet?

Use TODO: markers for missing information. That keeps the document honest and useful without pretending certainty.

How long should AGENTS.md be?

Long enough to be complete, short enough to scan quickly. Most good files are concise but dense with useful detail.

Conclusion

The best answer to How to Write the Perfect AGENTS.md file is this: write a file that removes ambiguity. Give agents the project overview, the stack, the commands, the structure, the rules, the safety boundaries, and the workflow they need to operate well.

It emphasizes audience, purpose, concreteness, safety, project-specific guidance, and clear required sections. That combination is what makes an AGENTS.md file effective.

A perfect AGENTS.md is not flashy. It is dependable. It helps an agent make the right change in the right place, using the right command, with the right checks, without crossing the wrong line. And when that happens, the whole repo gets better.

Richard.Bailey

Richard Bailey, a seasoned tech enthusiast, combines a passion for innovation with a knack for simplifying complex concepts. With over a decade in the industry, he's pioneered transformative solutions, blending creativity with technical prowess. An avid writer, Richard's articles resonate with readers, offering insightful perspectives that bridge the gap between technology and everyday life. His commitment to excellence and tireless pursuit of knowledge continues to inspire and shape the tech landscape.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate »