Instruction Files

The Pattern

Every major coding agent loads hierarchical markdown files at session start to shape its behavior throughout the session. These files --- CLAUDE.md, AGENTS.md, GEMINI.md --- form the persistent behavioral layer of an agentic system. They are the most fundamental pattern in agentic development because they survive across sessions, apply to every task, and require zero runtime orchestration.

The concept is simple: place a markdown file in a known location, and the agent reads it before doing anything else. The file contains plain-language instructions that influence how the agent writes code, runs commands, structures commits, and interacts with your project. Unlike chat messages that disappear after a session, instruction files persist in your repository and evolve with your codebase.

This pattern emerged independently across all major platforms, converging on nearly identical semantics: a global file for user preferences, a project-root file for team conventions, and local overrides for subdirectory-specific rules.


Cross-Platform Comparison

FeatureClaude CodeOpenAI CodexGemini CLI
File nameCLAUDE.mdAGENTS.mdGEMINI.md
Global (user)~/.claude/CLAUDE.md~/.codex/agents.md~/.gemini/GEMINI.md
Project root./CLAUDE.md.codex/agents.md./GEMINI.md
Local override./src/CLAUDE.md (any subdirectory)AGENTS.override.md./src/GEMINI.md (any subdirectory)
Import syntax@path/to/file.md@path/to/file.md@path/to/file.md
FormatMarkdown, free-formMarkdown, free-formMarkdown, free-form

All three systems follow the same layering model. Instructions closer to the working context take precedence over broader ones.


The 7 Essentials

Every instruction file should address these seven areas. An incomplete instruction file leads to inconsistent agent behavior --- the agent will fill gaps with its own defaults, which may not match your team’s expectations.

1. Project Conventions and Style Guide

Define formatting rules, naming conventions, and language idioms. Be explicit about what the agent might otherwise guess.

## Style

- Use `snake_case` for all Python identifiers except classes.
- Classes use `PascalCase`. No abbreviations in public APIs.
- Maximum line length: 100 characters.
- Prefer f-strings over `.format()` or `%` formatting.
- All functions require type hints for parameters and return values.

2. Tech Stack and Architecture Overview

Give the agent a map of your system. Without this, it will infer architecture from whatever files it happens to read first.

## Architecture

- **Backend**: Python 3.12, FastAPI, SQLAlchemy 2.0 (async).
- **Frontend**: TypeScript, React 19, Vite.
- **Database**: PostgreSQL 16 with pgvector extension.
- **Infra**: Terraform on AWS. ECS Fargate for services.
- Monorepo: `services/` contains backend, `web/` contains frontend.
- Shared types are generated from OpenAPI spec in `schema/`.

3. Testing Requirements and Patterns

Specify what “tested” means in your project. Agents will skip tests unless told otherwise.

## Testing

- Every new function must have a corresponding test.
- Use `pytest` with `pytest-asyncio` for async tests.
- Test files mirror source structure: `src/foo/bar.py` -> `tests/foo/test_bar.py`.
- Mock external services; never make real HTTP calls in tests.
- Run `make test` before considering any task complete.

4. Git Workflow and Branch Strategy

Without explicit instructions, agents default to committing directly or using generic messages.

## Git

- Branch from `main`. Branch names: `<type>/<ticket>-<short-desc>` (e.g., `fix/PROJ-123-null-check`).
- Commit messages follow Conventional Commits: `type(scope): description`.
- One logical change per commit. Do not bundle unrelated changes.
- Always rebase on `main` before opening a PR.
- Never force-push to shared branches.

5. Security and Compliance Rules

These are the instructions most likely to matter if violated. State them clearly and unconditionally.

## Security

- Never hardcode secrets, tokens, or credentials. Use environment variables.
- Never commit `.env` files, private keys, or certificates.
- All user input must be validated before use. No raw SQL concatenation.
- Dependencies must be pinned to exact versions in lock files.
- Do not disable TLS verification or certificate checks.

6. File Naming and Folder Conventions

Prevent the agent from creating files in unexpected locations.

## File Structure

- New API routes go in `services/api/routes/`.
- Database migrations go in `services/api/migrations/versions/`.
- Shared utilities go in `services/api/lib/`. Do not create new top-level directories.
- React components: one component per file, file name matches component name.
- No barrel exports (`index.ts` re-exporting everything). Import directly.

7. Review Checklist Before Commits

Give the agent a final gate to self-check its work. This reduces the number of iterations needed in code review.

## Pre-Commit Checklist

Before completing any task, verify:
- [ ] All new code has type hints / TypeScript types.
- [ ] Tests pass locally (`make test`).
- [ ] Linter passes (`make lint`).
- [ ] No secrets or credentials in the diff.
- [ ] Commit message follows Conventional Commits format.
- [ ] No unrelated changes included in the commit.

Hierarchy and Precedence

Instruction files are loaded in layers. When instructions conflict, the more specific layer wins.

graph TD
    A["Managed<br/><i>Platform defaults — cannot override</i>"] --> B
    B["User Global<br/><i>~/.claude/CLAUDE.md</i>"] --> C
    C["Project Root<br/><i>./CLAUDE.md — team conventions</i>"] --> D
    D["Local Override<br/><i>./src/backend/CLAUDE.md</i>"]

    style D fill:#eef2ff,stroke:#c7d2fe
    D -.- W["Most specific wins"]

Resolution rules:

  1. Managed instructions are baked into the platform. You cannot override them (e.g., safety filters, tool restrictions). These are the baseline.
  2. User Global instructions apply to all your projects. Use this for personal preferences: editor behavior, commit signing, preferred language for comments.
  3. Project Root instructions apply to everyone working on the repository. This is where team conventions live. Checked into version control.
  4. Local Override instructions apply only when the agent is working within that subdirectory or its children. Use this for subproject-specific rules (e.g., a frontend/ directory with different linting rules than backend/).

When two layers say different things about the same topic, the more specific (deeper) layer takes precedence. For example, if the project root says “use tabs” but frontend/CLAUDE.md says “use 2-space indentation,” the agent uses 2-space indentation when working in frontend/.

If two instructions at the same layer conflict, behavior is undefined. The agent may follow either one. Remove the conflict.


Best Practices

Keep instruction files concise

Every line in an instruction file consumes context tokens at the start of every session. A 500-line instruction file wastes thousands of tokens on every request, reducing the context available for actual work.

Target: under 200 lines. If your instructions exceed this, you are likely including information the agent does not need on every task.

Use imports for detailed documentation

All three platforms support an import syntax for pulling in external files on demand:

## Architecture

High-level overview here. For detailed module documentation:

@docs/architecture.md
@docs/database-schema.md
@docs/api-contracts.md

The agent loads these files only when the referenced topic is relevant, keeping base context lean.

Write specific, verifiable instructions

Vague instructions produce vague compliance. Compare:

# Bad
- Write clean code.
- Follow best practices.
- Make sure things work.

# Good
- All functions must have docstrings with Args, Returns, and Raises sections.
- HTTP handlers must return appropriate status codes (not always 200).
- Database queries must use parameterized statements, never string interpolation.

Every instruction should be something a reviewer could verify by reading the diff.

Remove conflicting instructions

Conflicts between instructions at the same level cause unpredictable behavior. Audit your instruction files periodically. Common sources of conflict:

Separate concerns across layers

Do not duplicate project instructions in your global file. Do not put personal preferences in the project file.

LayerContents
GlobalEditor preferences, commit signing, preferred comment language, personal shortcuts
ProjectTeam conventions, architecture, testing, git workflow, security rules
LocalSubproject overrides, language-specific rules, module-specific patterns

Template

A complete, production-ready instruction file for a typical web application:

# CLAUDE.md

## Project

E-commerce platform. Python/FastAPI backend, React/TypeScript frontend.
Monorepo: `services/` (backend), `web/` (frontend), `infra/` (Terraform).

## Stack

- Python 3.12, FastAPI, SQLAlchemy 2.0 (async), Alembic.
- TypeScript 5.5, React 19, Vite 6, TanStack Query.
- PostgreSQL 16, Redis 7, S3 for media.
- CI: GitHub Actions. Deploy: ECS Fargate via Terraform.

## Style

- Python: black, ruff, mypy strict. snake_case. Type hints required.
- TypeScript: ESLint + Prettier. 2-space indent. Prefer `const`. No `any`.
- SQL migrations: one migration per change. Always include rollback.

## Architecture

- Backend follows hexagonal architecture. Domain logic in `services/core/domain/`.
- API routes in `services/api/routes/`. One file per resource.
- Frontend components in `web/src/components/`. One component per file.
- Shared API types generated from OpenAPI spec: `schema/openapi.yaml`.

For detailed docs: @docs/architecture.md

## Testing

- Backend: pytest + pytest-asyncio. Tests in `tests/` mirroring `services/`.
- Frontend: Vitest + Testing Library. Tests colocated as `*.test.tsx`.
- All new endpoints require integration tests with test database.
- Run `make test` to execute full suite. Must pass before commit.

## Git

- Branch: `<type>/<JIRA-ID>-<description>` from `main`.
- Commits: Conventional Commits. Scope required for backend/frontend.
  Examples: `feat(api): add product search endpoint`
            `fix(web): resolve cart total rounding error`
- One logical change per commit. Rebase before PR.

## Security

- No hardcoded secrets. Use `AWS_*` env vars or SSM Parameter Store.
- Never commit .env, *.pem, or credentials files.
- Validate all user input at the API boundary. Use Pydantic models.
- SQL via SQLAlchemy ORM only. No raw queries.

## Pre-Commit

Before finishing any task:
1. Types check: `make typecheck`
2. Lint passes: `make lint`
3. Tests pass: `make test`
4. No secrets in diff.
5. Commit message follows convention.

This template is 55 lines. It fits well within the 200-line guideline while covering all seven essentials.


Enforcement Model

Instruction files are guidelines — soft constraints the agent follows in most cases but cannot guarantee 100% compliance. They shape behavior but cannot prevent actions, block execution, or enforce safety boundaries.

For hard enforcement, use hooks (rules) and permissions (gates). The correct mental model:

Instruction Files (soft)  -->  What the agent SHOULD do (90% compliance)
Hooks / Rules (hard)      -->  What ALWAYS happens (deterministic)
Permissions / Gates       -->  What the agent CANNOT do (structural)

Treat instruction files as the first layer of defense. Build the remaining layers for cases where compliance must be enforced. See Three-Tier Enforcement for the full model.