← Blog
8 min readThe Moxie Docs team

How to Write the Perfect CLAUDE.md File for Claude Code

Claude Code relies on a CLAUDE.md file for instructions on build, test, and style conventions. Learn how to write, structure, and maintain a perfect CLAUDE.md that keeps your AI agent on track.

  • claude-code
  • ai-agents
  • developer-tools
  • documentation

Terminal-based AI agents have changed the way we write code. Unlike web-based chat interfaces or IDE sidebars that wait for you to copy-paste snippets, tools like Anthropic’s Claude Code run directly in your shell. They can run your compiler, execute tests, run linters, and edit files across your monorepo.

But giving an AI agent command-line access to your codebase is like hiring a junior developer who works at 100x speed: if they don't know the local rules, they can make mess at 100x speed too.

To keep the agent aligned, Claude Code looks for a special file at the root of your repository: CLAUDE.md.

This guide is a practical walkthrough of how to write, structure, and optimize a CLAUDE.md file for your codebase. We will cover the specific sections Claude expects, how to prevent expensive agent loops, how to combine it with .cursorrules, and how to automate its maintenance so it never drifts.


What is CLAUDE.md?#

CLAUDE.md is a Markdown file placed at the root of a repository that serves as the "onboarding manual" for Claude Code. Every time you start a Claude Code session (claude in your terminal), the tool reads this file to initialize its memory.

The instructions in CLAUDE.md tell the agent:

  1. How to run the project: The exact shell commands to build, lint, format, and test the code.
  2. How to write the code: The active conventions, architectural rules, and design system constraints.
  3. What to avoid: Common gotchas, deprecated libraries, and patterns that break your environment.

When Claude edits code, it doesn't just guess if its changes worked. It actually executes the test and build commands listed in your CLAUDE.md file to verify its work before presenting the diff to you.


The anatomy of a perfect CLAUDE.md file#

Claude Code expects a specific, lean structure. If you make the file too long, you waste valuable context window tokens on every single query. If you make it too short, Claude will hallucinate commands and waste time (and money) running commands like npm test on a Go codebase.

Here is the recommended structure for a production-grade CLAUDE.md file:

MARKDOWN
# Claude Code Guidelines

## CLI Commands
- Build: `npm run build`
- Dev: `npm run dev`
- Lint: `npm run lint`
- Format: `npx biome format --write`
- Test: `npm run test`
- Test single file: `npm run test -- <path>`

## Code Style & Conventions
- Prefer functional components and TypeScript types over interfaces.
- Always use named exports; do not use default exports.
- State management: Use Zustand for global client state, React Query for server sync.
- Design System: Only use semantic classes from `@moxie-docs/ui` (e.g., `bg-surface`, `text-ink-secondary`). Do not write raw hex colors or arbitrary margins.

## Project Structure & Architecture
- Next.js App Router: `apps/web/src/app/`
- Shared packages: `packages/`
- Supabase migrations: `supabase/migrations/`

Let's break down the three critical sections and how to optimize them.


1. CLI Commands: Prevent interactive hangs#

The CLI Commands section is the most important part of the file. Claude Code parses this section to find the exact commands it is allowed to execute.

When writing commands, you must follow three rules:

Rule A: Never list commands that block or hang#

AI agents do not know how to escape an active process. If you tell Claude that the test command is vitest, it might run it in watch mode. The terminal will hang waiting for input, and the agent will timeout or run in circles.

  • Bad: Test: npx vitest (enters interactive watch mode)
  • Good: Test: npx vitest run (runs once and exits)

Similarly, avoid commands that open browsers or start dev servers unless you label them clearly as background tasks:

  • Good: Dev (local server): npm run dev

Rule B: Provide a "single-file" test pattern#

If Claude edits a single component in a large monorepo, you do not want it running a 20-minute end-to-end test suite to verify a typo fix. Always provide a command format for testing a single file.

  • Good: Test single file: npm run test -- <path> or Test single file: npx jest <path> Claude is smart enough to replace <path> or <filename> with the actual path of the file it just edited.

Rule C: Use absolute commands#

Do not list commands that assume the agent is already in a specific subdirectory. The agent runs from the repository root.

  • Bad: Build: npm run build (if the build command must be run inside apps/web)
  • Good: Build: npm run build --workspace=apps/web or Build: cd apps/web && npm run build

2. Code Style & Conventions: Quality over quantity#

Do not copy-paste your entire 80-page team wiki into CLAUDE.md. The agent will spend half its token limit reading rules about variable naming that your linter would have caught anyway.

Instead, focus on lint-invisible constraints—architectural choices and patterns that are syntactically valid but violate your team's design:

  • Technology choices: "Use Tailwind v4 and semantic token classes. Do not use inline styles or raw Tailwind color scales (like text-blue-500)."
  • State paradigms: "Keep components stateless where possible. Route all asynchronous mutations through React Query mutations, not local useEffect blocks."
  • Authentication boundaries: "All routes under src/app/api/admin/ must execute requireInternalAdmin() before performing database mutations."

By keeping the list under 10-15 bullet points, you guarantee the agent has enough remaining context to solve complex problems.


3. Project Structure: Guide the file searches#

Claude Code has tools to search your files, but helping it narrow down the search space saves latency and tokens. List the main directories of your project, especially in a monorepo where the structure might not be obvious to a general model.

Identify where:

  • Your database schemas or migrations live (supabase/migrations/)
  • Your core components are defined (packages/ui/src/)
  • Your API endpoints are located (apps/web/src/app/api/)

CLAUDE.md vs. .cursorrules vs. AGENTS.md#

As the AI tooling landscape expands, you might find yourself maintaining multiple instruction files at your repository root. Here is how they compare and how to keep them from duplicating:

FileTarget ToolCore FocusPrimary Use Case
CLAUDE.mdClaude Code CLIShell commands (build, test) and high-level project conventions.Terminal-based agent execution.
.cursorrulesCursor IDEContextual editor prompting and inline chat generation.Interactive editor completions.
AGENTS.mdOpen ConventionTool-agnostic rules, architecture boundaries, and security rules.Multi-agent configurations.

The DRY (Don't Repeat Yourself) Best Practice#

To avoid copying your style conventions across CLAUDE.md, .cursorrules, and AGENTS.md, use imports.

Claude Code supports referencing other files. You can keep your core style conventions in AGENTS.md (a tool-agnostic standard) and structure your CLAUDE.md like this:

MARKDOWN
# Claude Code Guidelines

Please refer to the codebase standards in [@AGENTS.md](file:///AGENTS.md) for style conventions and architectural boundaries.

## CLI Commands
- Build: `npm run build`
...

This keeps your tool-specific files focused purely on execution commands, while your core development standards live in a single source of truth.


Common mistakes when writing CLAUDE.md#

Avoid these pitfalls when drafting your guidelines:

  1. Vague advice: Writing rules like "Write clean, readable code" or "Add tests when necessary" is useless. The model already aims for this. Be concrete: "All new utility functions must have a corresponding .test.ts file in the same directory."
  2. Interactive CLI tools: Do not list commands that require human prompts (e.g., git commit or interactive scaffolding scripts) without flags that bypass the prompts.
  3. Outdated commands: If you rename a script in package.json but forget to update CLAUDE.md, Claude will repeatedly fail the build step and waste execution loops trying to figure out why the command is missing.

Keeping guidelines alive with Moxie Docs#

A static markdown file is only useful until the next merge. The moment your team moves a folder, migrates a package, or updates a linter command, your CLAUDE.md becomes stale. Outdated instructions active misguide your AI assistants, leading to broken code edits and failed test suites.

This is where Moxie Docs fits in.

Moxie Docs connects to your GitHub repository and continuously indexes your project structure, package manifests, and code conventions.

  • Drift Detection: If your build commands or dependencies change, Moxie notices the mismatch between your codebase and your guidelines.
  • Automated PRs: Moxie opens a clean, docs-only Pull Request to keep files like CLAUDE.md and AGENTS.md updated as your repository evolves.
  • MCP Integration: Moxie hosts a Model Context Protocol (MCP) server for your repository, allowing Claude Code or Cursor to fetch live, structured codebase details beyond what fits in a static text file.

If you want to quickly bootstrap your repository's AI guidelines, use our free browser-based tools:

By keeping these guidelines clean and updated, you ensure your AI assistants operate with maximum accuracy, minimal token waste, and zero broken terminal commands.

Republish or cite this article

You're welcome to republish this piece in full or in part. We just ask that you credit the original with a link back. See our republishing guidelines.

Attribution snippet

<p>This article was originally published on <a href="https://moxiedocs.com/blog/how-to-write-the-perfect-claudemd-file-for-claude-code">Moxie Docs</a>.</p>

Cite this article

The Moxie Docs team. "How to Write the Perfect CLAUDE.md File for Claude Code." Moxie Docs, July 16, 2026, https://moxiedocs.com/blog/how-to-write-the-perfect-claudemd-file-for-claude-code.

Try it on your repo

Put your own codebase on the same footing.

Searchable docs, MCP-ready context, and Cleanup PRs that keep everything current as the code changes.