September 22, 2026 · How-to · EN

How to Write an AGENTS.md That Actually Works in 2026

Write a concise AGENTS.md with exact commands, scoped boundaries, nested instructions, validation rules, and clean-session proof that coding agents can actually follow.

How to Write an AGENTS.md That Actually Works in 2026

How to Write an AGENTS.md That Actually Works in 2026

The common way to write AGENTS.md is to describe the repository.

A project overview. A few style rules. A reminder to run tests.

That looks useful. It usually leaves the agent to guess the decisions that matter — which command proves the change, which source owns generated output, which boundary must not move, and when the task should stop.

Here is the better definition: AGENTS.md is a version-controlled operating contract for coding agents.

It should change the next action an agent takes. If a line does not affect file choice, command choice, scope, validation, safety, or handoff, it probably does not belong in the file.

The open AGENTS.md convention deliberately uses ordinary Markdown. There is no required schema. That freedom is useful only when the content stays specific.

Start with the decision test

Before keeping a line, ask:

If this line disappeared, could a capable agent make a plausible but wrong decision?

Keep the line when the answer is yes.

Examples:

Use clean architecture.

An agent cannot act on that. It does not identify a boundary, an authority, or a check.

`src/domain/**` must not import from `src/http/**`.
Run `npm run test:architecture` after changing either package.

That changes both implementation and proof.

The same test removes most filler:

  • “write clean code” does not name the repository’s local standard;
  • “run tests” does not identify the relevant command;
  • “follow existing patterns” does not identify the canonical example;
  • “be careful” does not define a stop condition;
  • “update documentation” does not name which document owns the changed behavior.

Write the instruction that prevents the first wrong decision.

The seven parts that earn space

A useful root file usually needs seven parts. Small repositories may combine them. Large repositories should keep the root concise and move package-specific details into nested files.

1. Repository purpose

Give the agent enough context to interpret a request without copying the README.

## Repository purpose

This repository provides a Rust CLI that installs and updates a coding-agent
harness in existing projects. `crates/harness` owns CLI behavior. Templates under
`templates/` are copied into user repositories and therefore require compatibility
and migration review.

Name the product, the primary implementation surface, and the expensive boundary. Two to four sentences are usually enough.

2. Read-first map

Tell the agent where authoritative context lives.

## Read first

- `docs/ARCHITECTURE.md` — package boundaries and dependency direction
- `docs/WORKFLOW.md` — task, review, and handoff lifecycle
- `docs/decisions/` — accepted decisions; do not reopen without new evidence
- `templates/` — user-facing installed output, not internal examples

A path map is more useful than an architecture essay. It lets the agent retrieve detail when the decision appears.

Name authority explicitly. “See docs” is still a search task.

3. Exact commands

Commands should be copyable and attached to a purpose.

## Commands

- Install: `npm ci`
- Focused unit test: `npm test -- --runInBand path/to/test`
- Full validation: `npm run lint && npm run typecheck && npm test && npm run build`
- Generated-output check: `npm run generate && git diff --exit-code`

Include the working directory when it is not the repository root. Include required setup when a command depends on a service, fixture, or environment variable.

Do not put credentials in the file. Name the setup path instead:

Integration tests require the local service described in `docs/local-stack.md`.
Never use production credentials for local validation.

4. Validation by change type

One global test command is often either too expensive or too weak. Map changes to proof.

## Validation contract

- Docs only: `npm run lint:docs`
- TypeScript source: `npm run lint && npm run typecheck && npm test`
- Public API: focused tests plus `npm run test:compat`
- Generated clients: regenerate, compile, then require a clean second generation
- Database migration: `npm run migration:validate`; stop before applying outside local fixtures

The agent now knows what “done” means for the current scope.

Keep tests attached to claims. A UI change needs UI proof. A schema change needs producer-consumer proof. A recovery change needs failure-path proof.

5. Boundaries and authorities

Name where a change may happen and which source wins.

## Boundaries

- OpenAPI files under `api/schema/` are the source of truth for generated clients.
- Never hand-edit `clients/generated/**`; change the schema or generator.
- `src/domain/**` may not import transport-layer modules.
- Public error codes require a compatibility note and tests.

This prevents the most expensive class of agent mistake: editing the visible output instead of the authoritative source.

For each generated or mirrored surface, record:

source -> generator -> output -> validation

If the chain is missing, the agent has to infer ownership from filenames.

6. Safety and stop conditions

“Ask before risky changes” is too vague. Define the trigger.

## Stop and ask when

- the request changes a public API or persisted format;
- two instruction files conflict;
- the required validation cannot run;
- a migration would touch non-local data;
- generated output changes outside the requested package;
- the task requires credentials or an external write not already authorized.

Stop conditions are not refusals. They are escalation points that prevent an agent from resolving ambiguity through code.

Separate guidance from enforcement. AGENTS.md can tell an agent not to publish, delete data, or edit a protected path. Hooks, permissions, CI, branch protection, and sandbox policy must enforce the hard boundary.

7. Handoff requirements

Require evidence that survives the chat session.

## Handoff

Report:
- outcome and changed paths;
- commands run with results;
- checks not run and why;
- contract or behavior changes;
- residual risks;
- one exact next action when work remains.

A handoff should let a reviewer or clean agent session verify the work without reconstructing the conversation.

Use the coding-agent handoff template when the task moves between agents or sessions.

A copyable root template

Start here, then delete every section that does not change behavior in your repository.

# AGENTS.md — [Repository name]

## Repository purpose
[What this repository does, the primary implementation surface, and one expensive boundary.]

## Read first
- `[path]` — [authority or purpose]
- `[path]` — [authority or purpose]

## Commands
- Setup: `[exact command]`
- Focused validation: `[exact command]`
- Full validation: `[exact command]`

## Validation contract
- [Change type]: `[required checks]`
- [Change type]: `[required checks]`

## Boundaries and sources of truth
- `[path]` owns [contract or behavior].
- Never edit `[generated path]` directly; update `[source]` and run `[generator]`.
- [Dependency or compatibility rule].

## Stop and ask when
- [specific ambiguity, approval, data, migration, or security trigger]
- [specific condition that invalidates the task assumptions]

## Handoff
Report changed paths, commands and results, omitted checks, contract changes,
residual risks, and the next action.

The full AGENTS.md template adds optional architecture, story-packet, and decision sections for larger repositories.

Use nested AGENTS.md files for real scope

A root file should contain repository-wide truth. It should not contain every command for every package.

Use nested files when a subproject has different:

  • setup or validation commands;
  • architecture and dependency boundaries;
  • generated sources;
  • security or data constraints;
  • language or framework conventions;
  • release and compatibility rules.

A monorepo might use:

AGENTS.md
packages/
  api/
    AGENTS.md
  web/
    AGENTS.md
  cli/
    AGENTS.md

The root file answers repository-wide questions. packages/api/AGENTS.md answers API-specific questions. packages/web/AGENTS.md should not repeat the root safety rules unless repetition is needed for a tool that does not compose instructions.

The general convention is that the nearest applicable file provides the most specific guidance. Exact discovery, concatenation, and conflict precedence still vary by tool. Avoid contradictions and verify the tool you use.

For Codex, the official custom instructions guide documents root-to-working-directory discovery and AGENTS.override.md behavior. The Codex repository setup guide shows how to test the active instruction chain.

Keep one portable contract and thin tool adapters

AGENTS.md is widely supported. It is not a universal native entry point for every coding tool.

Do not solve that by copying the full contract into five files. Copies drift.

Use one portable source:

AGENTS.md

Then keep tool-specific adapters thin:

CLAUDE.md
.cursor/rules/
.github/copilot-instructions.md
GEMINI.md

Claude Code is the important correction. It uses CLAUDE.md and .claude/rules/ as native project instructions. It does not automatically treat AGENTS.md as its native memory file. A small CLAUDE.md can import or point to the shared contract, then add only Claude-specific behavior.

Cursor supports version-controlled Project Rules and AGENTS.md, including nested instructions. Codex has native layered AGENTS.md discovery. Other tools may require configuration or an explicit read path.

The current coding-agent context file comparison covers discovery and precedence across Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Aider, and OpenCode.

Write commands as contracts, not suggestions

A command line alone is not enough when the expected result is unclear.

Weak:

Run `npm test`.

Stronger:

For changes under `src/parser/**`, run `npm test -- parser`.
The command must exit 0. Do not update snapshots unless the requested behavior changed.

Strongest when generated state is involved:

Run `npm run generate`, then run it a second time and require `git diff --exit-code`.
A second-run diff means generation is not deterministic or generated output is stale.

Each validation rule should make four things clear:

  1. Trigger — which change requires the check;
  2. Command — exactly what to run and where;
  3. Expected result — exit code, clean diff, output, or user-visible behavior;
  4. Failure behavior — repair, report, or stop.

That is a validation contract. “Run tests” is a reminder.

AGENTS.md should route decisions to authoritative detail.

Put these in linked documents:

  • architecture diagrams and long package descriptions;
  • accepted decision records;
  • release procedures;
  • migration playbooks;
  • incident and recovery runbooks;
  • long style guides;
  • detailed local-environment setup.

The root file should say when to read them:

Read `docs/recovery.md` before changing journal replay, compensation, or retry logic.

A bare link list is not enough. Name the decision that triggers retrieval.

Remove rules that do not survive verification

A useful instruction can be checked.

Prefer small functions.

There is no local definition or proof.

Keep HTTP handlers under 40 lines and move business logic to `src/domain/**`.
Run `npm run test:architecture` after changing handlers.

Now the rule names a boundary and a check.

Not every convention needs a numeric limit. But every durable rule should answer at least one of these:

  • Which file or path shows the accepted example?
  • Which command detects a violation?
  • Which reviewer owns the decision?
  • Which condition requires escalation?

If none apply, the line may be preference disguised as policy.

Test the file in a clean session

Do not validate AGENTS.md with the same chat that wrote it. That session already knows the missing context.

Use this sequence:

1. Start clean

Open a new agent session at the repository root. Do not paste prior planning messages.

2. Probe discovery

Ask:

Summarize the active repository instructions for this working directory.
Name the required validation commands, prohibited changes, and stop conditions.
Cite the instruction file for each rule.

Repeat from a nested package. Confirm the scoped instructions change where expected.

3. Give one bounded task

Choose a real change with one non-obvious boundary. Do not remind the agent about that boundary in the prompt.

4. Inspect the first decision

Check whether the agent reads the correct files, edits the authoritative source, and selects the right focused validation before implementation expands.

5. Inspect the handoff

Require commands and results, not “tests pass.” Confirm omitted checks and residual risks are visible.

6. Repair the first wrong decision

Do not add the whole transcript to AGENTS.md. Add or improve the smallest rule, path map, command, or stop condition that would have prevented the error.

This is the same clean-session gate used in the AGENTS.md before-and-after case study.

Common failure patterns

The README copy

It explains the project but not how an agent should operate. Keep user-facing onboarding in README.md. Put agent decisions and proof in AGENTS.md.

The giant root file

It mixes repository-wide policy with frontend, backend, deployment, and migration detail. Split by scope and link to depth.

The vague rule collection

“Follow best practices.” “Keep changes small.” “Run relevant tests.” None identify a local decision or proof.

The tool-support assumption

The file says every agent reads AGENTS.md automatically. That is false. Native entry points and precedence vary. Keep a portable contract, configure thin adapters, and probe discovery.

The hand-edited generated output

The file names generated directories but does not name their source or generator. Record the full source-to-output chain.

The missing stop condition

The agent encounters conflicting docs or a blocked check and guesses. Define when work must pause.

The stale command

The file is correct on the day it ships and wrong after the build system changes. Review instructions in the same pull request that changes commands, paths, or architecture.

The AGENTS.md mistakes guide covers ten failure modes and their repairs. The maintenance guide provides the ongoing review loop.

Review AGENTS.md like code

An instruction change can alter every future agent session. Review it with the same care as automation.

Require the pull request to answer:

  • Which repeated failure or new repository fact triggered this rule?
  • Is the rule global or scoped to one package?
  • Does it name authority and validation?
  • Does it conflict with a parent, child, or tool-specific file?
  • Can a clean session discover and apply it?
  • Which old line became redundant?

Prefer replacing weak instructions over appending more text. Instruction files accumulate contradictions when every incident adds a new rule but no review removes the obsolete one.

What to do today

You do not need a complete repository handbook.

Add a root AGENTS.md. Name the exact validation commands. Map the authoritative files. Mark generated output. Define three stop conditions. Require an evidence handoff.

Then open a clean session and watch the first decision.

If the agent still guesses, repair the repository contract—not the prompt.

repository-harness provides a working starting point for repository instructions, source-of-truth maps, validation contracts, task envelopes, handoffs, checkpoints, and recovery-aware agent workflows.


FAQ

What should an AGENTS.md file contain?

An effective AGENTS.md should name the repository’s purpose, exact setup and validation commands, important paths, architectural boundaries, generated-file rules, safety constraints, and clear stop conditions. Link to deeper documents instead of copying them into the file.

How long should an AGENTS.md file be?

There is no official line limit. Keep each file as short as possible while preserving the non-obvious instructions needed for its scope. Use nested files and linked documentation when one root file starts mixing unrelated package-specific rules.

Where should AGENTS.md live?

Start with AGENTS.md at the repository root. In a monorepo, add nested files inside packages or subprojects that need more specific instructions. The closest applicable file normally provides the most specific guidance, but exact discovery and precedence vary by tool.

Does Claude Code read AGENTS.md automatically?

No. Claude Code uses CLAUDE.md as its native project-memory entry point. A common portable setup keeps shared repository instructions in AGENTS.md and references them from a small CLAUDE.md, while Claude-specific rules stay under .claude/.

Does Codex support nested AGENTS.md files?

Yes. Codex discovers project instructions from the repository root toward the current working directory and applies more specific instructions closer to the working path. AGENTS.override.md can replace AGENTS.md at a given level.

How do you test whether AGENTS.md is working?

Start a clean session, ask the agent to summarize active instructions and validation commands for a specific subdirectory, then give it a bounded task. Verify that it chooses the correct files, respects stop conditions, runs the required checks, and reports evidence rather than only claiming success.

What should not go in AGENTS.md?

Do not put temporary ticket context, secrets, credentials, long architecture essays, duplicated README content, personal preferences, vague slogans, or rules that no executable check or reviewer can verify in AGENTS.md.