Claude Code Rules: How to Write CLAUDE.md and Manage Agentic Coding Context

Claude Code Rules: How to Write CLAUDE.md and Manage Agentic Coding Context

Claude Code rules live in CLAUDE.md files — markdown files you place in your project repo, home directory, or organization config that Claude reads at the start of every session. Combined with path-scoped rules in .claude/rules/, a settings.json for permissions, and auto memory for learned preferences, the rules system gives you precise, persistent control over how the coding agent behaves across any task.

What Are Claude Code Rules?

Each Claude Code session begins with an empty context window. Rules are how you pre-load the context Claude needs so it doesn’t start from scratch — or make the same mistake twice.

Two complementary systems handle this:

CLAUDE.md files are markdown files you write that Claude reads at the start of every session. Use them for instructions that should always apply: build commands, code conventions, architecture decisions, hard constraints.

Auto memory is notes Claude writes itself based on corrections and preferences you give it during sessions. These accumulate automatically; Claude decides what’s worth saving and reads those notes back in future sessions.

Both load into context at session start, but they’re not enforced configuration. They’re instructions Claude follows as context. For hard enforcement — blocking a specific command regardless of what Claude decides to do — you need a PreToolUse hook or a deny rule in settings.json. The distinction matters for autonomous runs where you want predictable behavior, not probabilistic compliance.

CLAUDE.md File Locations and Scope

Claude Code loads CLAUDE.md files from several locations, each covering a different scope. They load in order from broadest to most specific:

LocationScopeWhat it’s for
~/.claude/CLAUDE.mdAll projects on your machinePersonal preferences, global workflow habits
./CLAUDE.md (repo root)All sessions in that projectProject conventions, build commands, team-shared rules
./CLAUDE.local.md (repo root)Only your local sessionsPer-developer preferences; add to .gitignore
./src/CLAUDE.md (subdirectory)Sessions touching files in that directoryModule-specific rules that don’t apply project-wide

All discovered files are concatenated into context — they don’t override each other. Within that concatenation, content from the filesystem root to your working directory is ordered narrowest-last, so a project instruction appears after a user instruction. That gives you natural specificity: a project rule wins where it conflicts with a user-level one.

You can import additional files with @path references inside any CLAUDE.md:

@./docs/architecture.md
@./CONTRIBUTING.md

Imported files load at session start, the same as the CLAUDE.md itself. Imports are useful for organization but don’t save context — the imported content counts toward your token budget.

For teams: commit the project CLAUDE.md to source control. This ensures every developer’s Claude sessions — and any CI-based agent runs — start with the same shared context. Treat it like .eslintrc or pyproject.toml.

What to Put in CLAUDE.md

The most useful content is what you’d otherwise re-explain each session, or what a new team member would need to know in their first hour.

Good candidates:

  • Build and test commands that differ from obvious defaults (./scripts/test.sh --ci, not just npm test)
  • Code conventions that aren’t captured by the linter (“we use named exports everywhere; no default exports in shared utilities”)
  • Architecture decisions that aren’t obvious from reading the code (“the lib/ directory is shared across services — do not add service-specific logic there”)
  • Known gotchas (“the config.ts file is generated at build time; do not edit manually”)
  • Workflow constraints (“always branch before making changes; push to remote before opening a PR”)

Things to leave out:

  • Directory listings and file trees — Claude reads these from the repo
  • Dependency lists — available from package.json, pyproject.toml, and similar
  • Prose descriptions of what existing code does — Claude reads source code directly
  • Recent changes — Claude uses git log and git diff when it needs history

Keep CLAUDE.md focused on what can’t be derived from reading the codebase. Files over 200 lines consume more context and reduce adherence reliability. The /doctor command in Claude Code audits a checked-in CLAUDE.md and suggests removing content that’s derivable from the code — a useful way to trim a bloated file.

Writing effective rules

Specificity matters. Compare:

# Vague — less consistent
Follow project coding standards.

# Specific — more consistent
- Use pnpm, not npm or yarn
- Run pnpm test before every commit; do not commit if tests fail
- Export all shared types from src/types/index.ts — do not define types inline in component files
- The data/ directory is read-only in tests; use test fixtures from tests/fixtures/ instead

Every rule should be actionable without further explanation. If you’d need to explain a rule’s reasoning to someone, add the reasoning inline — it helps Claude apply the rule correctly in edge cases.

Path-Scoped Rules with .claude/rules/

The .claude/rules/ directory lets you attach rules to specific file patterns without loading them into every session. Claude discovers files in .claude/rules/ and loads them when you work with matching files.

A typical structure for a TypeScript monorepo:

.claude/rules/
  api.md             # rules for src/api/** — request validation, error formats
  components.md      # rules for src/components/** — prop types, styling conventions
  tests.md           # rules for tests/** — fixture patterns, mock setup
  database.md        # rules for migrations/ and models/ — migration naming, query patterns

Each rule file uses YAML frontmatter with a paths field to control when it loads:

---
paths:
  - "src/api/**/*.ts"
  - "src/api/**/*.test.ts"
---

# API Development Rules

- All route handlers must validate input with zod before any business logic
- Return errors as `{ error: string; code: string }` — never plain strings
- Rate limiting is applied at the gateway; do not add it inside handlers

Rules without a paths field load unconditionally at session start, the same as content in the project CLAUDE.md. Rules with paths load only when Claude opens files matching those patterns.

This keeps the project root CLAUDE.md concise and ensures detailed conventions for one layer of the stack don’t fill context during sessions focused on a different area.

settings.json vs CLAUDE.md

CLAUDE.md controls what Claude knows and intends to do. settings.json controls what Claude is actually permitted to do.

CLAUDE.mdsettings.json
PurposeInstructions and contextPermissions and configuration
Enforced?No — Claude acts on it as guidanceYes — deny rules block tool calls unconditionally
FormatFree-form markdownStructured JSON
Lives at./CLAUDE.md, ~/.claude/CLAUDE.md.claude/settings.json, ~/.claude/settings.json

A project settings.json at .claude/settings.json:

{
  "permissions": {
    "allow": [
      "Bash(pnpm test)",
      "Bash(pnpm build)",
      "Bash(git status)",
      "Bash(git diff *)"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(git push --force*)",
      "Bash(git reset --hard*)"
    ]
  }
}

The allow list pre-approves specific commands so Claude can run them without prompting. This speeds up interactive sessions for operations you trust. The deny list blocks commands unconditionally — regardless of what Claude decides to do, regardless of what CLAUDE.md says. Use deny for irreversible operations on production data or infrastructure.

User-level settings at ~/.claude/settings.json apply to all projects. Project settings at .claude/settings.json apply only in that repo. Project settings take precedence over user settings where they overlap.

Auto Memory: Claude’s Notes

Auto memory is the counterpart to CLAUDE.md. While CLAUDE.md is instructions you write, auto memory is notes Claude writes itself based on what it learns during your sessions.

When you correct Claude during a session — “we use Vitest, not Jest in this project” — it can save that as a note in ~/.claude/projects/<repo>/memory/. The next session, Claude reads that note back and applies the correction without being told again.

The memory directory contains:

~/.claude/projects/<repo>/memory/
  MEMORY.md          # index Claude uses to find other files; first 200 lines load each session
  debugging.md       # patterns Claude discovered solving problems in this repo
  conventions.md     # conventions Claude learned from your corrections

This is machine-local and per-repository. Auto memory complements CLAUDE.md rather than replacing it: CLAUDE.md is for team-shared project rules; auto memory is for personal patterns Claude learned from working with you.

Auto memory is readable markdown you can edit or delete at any time. Run /memory inside a session to browse and edit the files. If something is stale or wrong, delete it — Claude will stop applying the stale rule.

Best Practices for Agentic Coding

Running Claude Code autonomously — through claude -p, the Agent SDK, or CI pipelines — raises the stakes for your rules setup. The agent may complete dozens of tool calls without pausing, and there’s no interactive back-and-forth to catch misunderstandings mid-run.

Write explicit constraints, not just preferences. Interactive Claude can ask you to clarify. An autonomous run works with what it finds in context. If “never modify migration files without creating a database snapshot first” matters, it needs to be in CLAUDE.md. Don’t assume Claude will infer the constraint from the codebase structure.

Use deny rules for anything hard to reverse. Pre-approving Bash(pnpm build) speeds up interactive sessions and is low-risk. But for autonomous runs, the deny list is your safety net for operations that touch production infrastructure, commit permanently to git history, or delete data.

Keep project CLAUDE.md in version control. A committed CLAUDE.md at the repo root applies consistently to interactive sessions, CI runs, and any team member’s local agent. This is the right place for the rules that define what “correct” means for your codebase.

Use .claude/rules/ for domain-specific content. If your project has distinct layers — frontend components, backend API, database schema, infrastructure scripts — put the rules for each layer in .claude/rules/ with path scoping. A single 400-line CLAUDE.md with everything in it is harder for Claude to navigate and costs more context per session.

Move reference material to skills. Skills (.claude/skills/) load on demand, not at session start. Long API documentation, multi-step deployment procedures, and troubleshooting playbooks belong in skills you invoke with /deploy or /debug — not in CLAUDE.md where they consume context even when irrelevant.

Review auto memory periodically. Auto memory accumulates over time. Build commands change, conventions get refactored, test patterns shift. A stale memory note that says “use the v1 API client” when you’ve migrated to v2 will cause subtle bugs in autonomous runs. Audit ~/.claude/projects/<repo>/memory/ when you make significant changes to the project structure.

Using Open-Source Models with Your Rules Setup

The CLAUDE.md context and .claude/rules/ you’ve built work the same regardless of which model handles inference. Once your rules are written, switching model backends preserves all of it — and open-source models through Novita AI’s LLM API are a practical option for high-volume agentic work.

The configuration is one environment variable:

export ANTHROPIC_BASE_URL="https://api.novita.ai/anthropic"
export ANTHROPIC_AUTH_TOKEN="<your-novita-api-key>"
export ANTHROPIC_MODEL="qwen/qwen3-coder-480b-a35b-instruct"

With ANTHROPIC_BASE_URL pointing to Novita AI, Claude Code sends all inference requests to Novita’s Anthropic-compatible endpoint instead of api.anthropic.com. Your CLAUDE.md, path-scoped rules, and settings.json all apply exactly as before — the rules layer is upstream of model selection.

Novita AI hosts coding-focused open-weight models including Qwen3-Coder, GLM-4.7, MiniMax M2.5, and DeepSeek V4. These models are optimized for multi-step tool use and function calling, which maps well to the tool-calling patterns Claude Code uses internally for file edits, shell commands, and repository navigation.

For teams running agentic tasks at scale — code review pipelines, automated refactoring across large repos, test generation — open-weight models on Novita typically cost significantly less per million tokens than closed-source alternatives, while still reading and applying your project rules effectively.

If you’re running agents against a production codebase and want an additional safety layer beyond deny rules, consider pairing Novita’s LLM API with Novita’s Agent Sandbox. The sandbox gives the agent a full Linux environment for file operations and command execution, isolated from your host system. Your CLAUDE.md context travels with the task; execution risk stays contained.

FAQ

What is CLAUDE.md in Claude Code?

CLAUDE.md is a markdown file that gives Claude Code persistent instructions across sessions. It loads at session start so Claude doesn’t need to be re-taught your project conventions each time. You can have CLAUDE.md files at multiple scopes: user-level (~/.claude/CLAUDE.md) for personal preferences that apply everywhere, project-level (repo root) for team-shared rules checked into version control, and subdirectory-level for module-specific rules.

What should I put in claude rules md files?

Write what you’d otherwise re-explain each session: build and test commands, coding conventions that differ from framework defaults, architecture constraints, and known codebase gotchas. Leave out content Claude can derive from the codebase itself — file trees, dependency lists, and descriptions of what existing code does. Keep files under 200 lines for consistent adherence.

What is the difference between CLAUDE.md and settings.json in Claude Code?

CLAUDE.md is instructions Claude follows as guidance. settings.json is configuration Claude Code enforces at the system level. A rule in CLAUDE.md shapes what Claude intends to do; a deny entry in settings.json blocks a tool call unconditionally. For anything that must not happen regardless of what Claude decides — irreversible deletes, force pushes, production environment operations — use settings.json, not CLAUDE.md.

What is the .claude/rules/ directory?

.claude/rules/ holds path-scoped rule files that load only when Claude is working with files matching the rule’s scope. This lets you write detailed, domain-specific rules without loading them into every session. Rules are markdown files with optional YAML frontmatter specifying paths glob patterns. Rules without paths frontmatter load unconditionally at session start, like additional CLAUDE.md content.

Does CLAUDE.md work in CI and automated claude code tasks?

Yes. Any claude -p invocation, Agent SDK call, or CI pipeline running in a repository directory loads the project’s CLAUDE.md. This makes CLAUDE.md effective for enforcing consistent behavior in both interactive and automated contexts. Committing it to version control ensures every run — local and CI — starts with the same shared context.

How does claude code context work and how do I manage it?

Context is the token budget for the current session. CLAUDE.md files, imported references, auto memory, and the conversation history all count toward it. Manage it by keeping CLAUDE.md concise, using .claude/rules/ to load domain content only when relevant, and using /compact to summarize long sessions without losing continuity. After /compact, Claude re-reads the project-root CLAUDE.md from disk and re-injects it into the session automatically.

How do I use claude code best practices for agentic coding in a team?

Commit the project CLAUDE.md to your repository so all team members and CI agents share the same rules. Use .claude/rules/ with path scoping for domain-specific content. Add deny rules to .claude/settings.json for operations that should never run in automated contexts. Keep auto memory out of CI — it’s machine-local and per-developer; the committed CLAUDE.md is the source of truth for shared behavior.

Novita AI is an AI cloud platform that offers developers an easy way to deploy AI models using our simple API, while also providing affordable and reliable GPU cloud for building and scaling.


Sources checked July 21, 2026: Claude Code memory docs, Claude Code features overview, Novita AI LLM API