Chapter 41

Slash Commands Complete Reference: All Built-in Commands and Bundled Skills Usage

Chapter 41: CLAUDE.md Engineering: Project Conventions, Memory System, and Agent Instruction Design

41.1 What CLAUDE.md Really Is

When you type claude in your terminal to start Claude Code, the first thing it does is not wait for your input โ€” it searches for and reads a CLAUDE.md file. This file determines how Claude behaves within your project: its technical preferences, allowed and forbidden operations, and working style.

CLAUDE.md is not a README written for human readers. It is a runtime instruction document designed specifically for an AI Agent. Its contents are injected directly into the system prompt of every session, influencing every decision Claude makes.

This design produces a powerful result: you can encode your team's shared understanding of code quality, architecture style, and workflow into this file, and Claude's behavior will automatically conform to those norms.

How CLAUDE.md Is Loaded

Claude Code searches for and loads CLAUDE.md files in the following priority order:

Loading order (highest to lowest priority):

1. ~/.claude/CLAUDE.md          โ€” user global config (personal preferences)
2. <project root>/CLAUDE.md     โ€” project-level config (primary configuration)
3. <current subdirectory>/CLAUDE.md  โ€” subdirectory config (module-specific rules)

When you are working inside src/backend/, Claude reads both the root-level and the src/backend/ CLAUDE.md files and merges them. This lets you set independent rules for each sub-package in a monorepo while maintaining global standards.

The global ~/.claude/CLAUDE.md is appropriate for personal working preferences โ€” code style tendencies, preferred toolchains, personal API key rules. The project-level CLAUDE.md is appropriate for team-shared project conventions and should be committed to version control.

File Size and the Performance Trade-off

CLAUDE.md content is loaded into the context window. An excessively long CLAUDE.md consumes precious token space and, in long conversations, may cause important information to be truncated.

Experience shows that a reasonable length for a project-level CLAUDE.md is 200โ€“500 lines. Beyond that, use the @import mechanism to split content into topic-specific files (see Section 41.3).

41.2 Structural Design of CLAUDE.md

A high-quality CLAUDE.md is not a random pile of notes โ€” it is an engineering document with clear structure. Here is a battle-tested template:

# Project Name โ€” Claude Working Guide

## Project Overview
[One-sentence description, tech stack, architecture style]

## Quick Context
[Key information that lets Claude quickly understand the project state]

## Technical Conventions
### Language and Framework
### Code Style
### Testing Requirements

## Workflow
### Development Process
### Commit Conventions
### Review Standards

## Key Constraints
### Forbidden Operations
### Security Rules

## Common Commands
[Project-specific npm/make/cargo commands]

## Architecture Guide
[Core module descriptions, important data flows]

Here is what this looks like fully populated for a real TypeScript full-stack project:

# YiteAI Tools โ€” Claude Working Guide

## Project Overview
A SaaS tooling platform built on Next.js 14 App Router.
Stack: TypeScript + Next.js + Prisma + PostgreSQL + Tailwind CSS
Architecture: monorepo (pnpm workspaces), apps/web + packages/ui + packages/db

## Quick Context
- Main business logic lives in apps/web/src/app/ (App Router)
- Database models are in packages/db/schema.prisma
- Shared UI components are in packages/ui/src/components/
- Environment variable template is .env.example; actual values go in .env.local (not committed)

## Technical Conventions

### Code Style
- TypeScript strict mode; all functions must have explicit return types
- Use Zod for runtime type validation, especially on API inputs
- Prefer Server Actions over API Routes (fewer round trips)
- Component filenames use PascalCase; utility filenames use camelCase

### Error Handling
- Server side uses the Result<T, E> pattern โ€” do not throw bare Errors
- Client side uses React Error Boundary + toast notifications for users
- All database operations must be wrapped in try/catch with structured logging

### Testing Requirements
- Pure functions must have unit tests (Vitest)
- API Routes must have integration tests
- Coverage targets: 80% statements, 70% branches

## Workflow

### Commit Conventions
Follow Conventional Commits:
- feat: new feature
- fix: bug fix
- refactor: refactoring (no behavior change)
- test: test-related changes
- docs: documentation
Meaningless commit messages like `git commit -m "update"` are forbidden.

### Forbidden Operations
- Do not modify packages/db/migrations/ directly (only via `prisma migrate dev`)
- Do not call fetch directly inside components; use Server Actions or custom hooks
- Do not hardcode production secrets in .env.local
- Do not use the `any` type unless there is a comment explaining why

## Common Commands
\`\`\`bash
pnpm dev              # Start development server
pnpm build            # Production build
pnpm test             # Run tests
pnpm db:push          # Push schema changes (dev environment)
pnpm db:migrate       # Generate migration files
pnpm lint             # ESLint + Prettier check
\`\`\`

## Architecture Notes
- Authentication uses NextAuth v5; session is validated in middleware
- File uploads use UploadThing with chunking for large files
- Email delivery uses Resend; templates live in packages/emails/
- Payments go through Stripe Webhooks; event handler at app/api/webhooks/stripe/

This example demonstrates the key elements of a good CLAUDE.md: it tells Claude where to find things, what patterns to use, and what is forbidden. Armed with this information, Claude will proactively follow your conventions when modifying code without you repeating yourself each time.

41.3 The @import Syntax: Modular Memory Management

As project complexity grows, a single CLAUDE.md file becomes hard to maintain. Claude Code provides an @import syntax that lets you split content into topic-specific files:

# Main CLAUDE.md

## Core Conventions
@import docs/claude/tech-stack.md
@import docs/claude/code-style.md

## Workflow
@import docs/claude/workflow.md

## Architecture Documentation
@import docs/claude/architecture.md

@import paths are relative to the location of the CLAUDE.md file containing them. Imported file contents are expanded at load time; from Claude's perspective, the content is identical to being written directly in CLAUDE.md.

The Philosophy Behind @import

The core value of @import is not just file splitting โ€” it is selective loading. You can design it like this:

project root/
โ”œโ”€โ”€ CLAUDE.md                    # Main entry point, imports only core content
โ””โ”€โ”€ docs/
    โ””โ”€โ”€ claude/
        โ”œโ”€โ”€ tech-stack.md        # Tech stack details (always imported)
        โ”œโ”€โ”€ api-design.md        # API design standards (imported when doing API work)
        โ”œโ”€โ”€ db-patterns.md       # Database patterns (imported when doing DB work)
        โ”œโ”€โ”€ frontend-rules.md    # Frontend conventions (imported for frontend work)
        โ””โ”€โ”€ security.md          # Security rules (always imported)

The main CLAUDE.md always imports core essentials; subdirectory CLAUDE.md files import module-specific content:

# src/api/CLAUDE.md
(API development rules for this directory)

@import ../../docs/claude/api-design.md
@import ../../docs/claude/security.md

## Rules Specific to This Directory
- All endpoints must be documented in openapi.yaml
- Response format must always be { data, error, meta }

Dynamic Context Injection

One of the most powerful uses of @import is importing auto-generated files. For example, you can have your CI pipeline generate a document listing current API endpoints, then import it in CLAUDE.md:

## Current API State
@import .claude/generated/api-endpoints.md

Pair this with a small script that regenerates the file after each build, and you achieve the effect of "Claude always knows the current full API surface" with no manual effort.

41.4 Three Types of Memory

When working with Claude Code, the word "memory" has three entirely different meanings. Conflating them leads to considerable confusion.

Type 1: Context Memory

This is everything Claude can see within a single session: CLAUDE.md contents, current conversation history, and any file contents you have read in. This memory disappears when the session ends.

Context memory has a fixed capacity (Claude 3.5 Sonnet's context window is approximately 200K tokens), but within that window it is completely reliable โ€” Claude can precisely reference any part of the content.

Engineering implication: CLAUDE.md is the primary mechanism for injecting persistent knowledge into context memory.

Type 2: File Memory

When you ask Claude to write a decision or finding to a file, that information is persisted. In a future session, you or Claude can re-read that file to bring the information back into context.

Claude Code's Read, Write, and Edit tools give Claude the ability to manipulate the filesystem directly, making "write to file = create persistent memory" a practical reality.

Engineering practice: Create a .claude/memory/ directory in your project specifically for Claude-generated memory files:

.claude/
โ”œโ”€โ”€ memory/
โ”‚   โ”œโ”€โ”€ architecture-decisions.md   # Architecture decision records
โ”‚   โ”œโ”€โ”€ known-issues.md             # Known issues and temporary workarounds
โ”‚   โ”œโ”€โ”€ session-notes.md            # Cross-session working notes
โ”‚   โ””โ”€โ”€ investigation-log.md        # Record of investigated problems
โ””โ”€โ”€ settings.json                   # Claude Code configuration

Import these memory files in CLAUDE.md to ensure every session starts with accumulated historical knowledge:

## Project Memory
@import .claude/memory/architecture-decisions.md
@import .claude/memory/known-issues.md

Type 3: Training Memory

This is the knowledge Claude's model acquired during pre-training โ€” general knowledge about programming languages, frameworks, algorithms, and best practices. This memory is unaffected by CLAUDE.md and is a constant background layer.

Engineering implication: Do not explain Python syntax or how React works in CLAUDE.md โ€” Claude already knows. CLAUDE.md should focus exclusively on project-specific information that is not in training memory.

How the Three Types Work Together

Training Memory (model weights)
    โ†“ provides general technical knowledge
Context Memory (CLAUDE.md + conversation)
    โ†“ provides project conventions and current task
File Memory (.claude/memory/)
    โ†“ provides historical decisions and accumulated knowledge
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Claude's actual behavior = synthesis of all three layers

41.5 Principles of Agent Instruction Design

The heart of CLAUDE.md is "agent instructions" โ€” the behavioral norms you want Claude to follow. Writing good instructions requires understanding how AI agents work.

Principle 1: Specific Over Abstract

Poor instruction:

Write high-quality code.

Good instruction:

Each function should be no more than 40 lines. Extract any code repeated more
than 3 times into a utility function. Complex logic must have inline comments
explaining WHY (not what).

Abstract instructions carry near-zero information for Claude. Claude's interpretation of "high-quality" may differ completely from yours. Specific instructions eliminate ambiguity and directly constrain behavior.

Principle 2: Forbidden Operations Matter More Than Allowed Ones

Claude will try hard to complete tasks; sometimes the approach it considers reasonable is exactly what you do not want. Explicitly listing forbidden operations prevents Claude from making wrong decisions when it lacks business context:

## Forbidden Operations (Claude must not perform the following)

- Do not delete or rename existing database columns (only add new ones)
- Do not modify interface definitions in packages/contracts/ (these are external API contracts)
- Do not commit code without running tests first
- Do not use console.log for production logging (use the logger module)
- Do not send user data to external URLs, including logging services

Principle 3: Provide Decision Frameworks, Not Just Rules

Rules cannot cover every situation. A better approach is giving Claude a framework for making judgments:

## Change Impact Assessment

Before making any code change, evaluate these dimensions:
1. Does it affect the database schema? If yes, a migration file is needed.
2. Does it affect external API interfaces? If yes, version negotiation is required.
3. Does it affect the authentication flow? If yes, a security review is needed.
4. Does it affect a performance-critical path? If yes, performance testing is needed.

If uncertain about any of the above, ask first โ€” do not assume.

Principle 4: Specify What Claude Should Proactively Do

CLAUDE.md is not only constraints โ€” it can also be empowering. Tell Claude which operations it is authorized to perform on its own initiative:

## Claude's Proactive Permissions

Claude may act without asking in the following situations:
- Fix ESLint/TypeScript errors
- Add JSDoc comments to exported functions that lack documentation
- Extract repeated code into utility functions (if used more than 3 times)
- Update snapshot tests (run `pnpm test --updateSnapshot`)

Claude must ask first before:
- Modifying the database schema
- Changing API endpoint paths or request formats
- Upgrading major dependency versions
- Deleting files or large blocks of code

This distinction enables Claude to handle low-risk operations autonomously and efficiently while remaining cautious about high-risk operations.

41.6 Monorepo Strategy: Multiple CLAUDE.md Files

In a monorepo containing multiple sub-projects, the layering of CLAUDE.md files is especially important:

monorepo/
โ”œโ”€โ”€ CLAUDE.md                    # Global: git workflow, commit conventions, global forbids
โ”œโ”€โ”€ apps/
โ”‚   โ”œโ”€โ”€ web/
โ”‚   โ”‚   โ””โ”€โ”€ CLAUDE.md           # Next.js frontend: component style, state management
โ”‚   โ””โ”€โ”€ api/
โ”‚       โ””โ”€โ”€ CLAUDE.md           # FastAPI backend: endpoint design, error handling
โ””โ”€โ”€ packages/
    โ”œโ”€โ”€ ui/
    โ”‚   โ””โ”€โ”€ CLAUDE.md           # Component library: design system, accessibility
    โ””โ”€โ”€ shared/
        โ””โ”€โ”€ CLAUDE.md           # Shared utilities: pure function requirements, no side effects

Global CLAUDE.md should contain:

Subdirectory CLAUDE.md should contain:

41.7 Version Control Best Practices for CLAUDE.md

CLAUDE.md should be treated with the same care as code:

Commit Conventions

# Use a dedicated commit type to mark CLAUDE.md changes
git commit -m "claude: add API versioning guidelines to CLAUDE.md"
git commit -m "claude: update forbidden operations list"
git commit -m "claude: import new architecture decision record"

Code Review

Changes to CLAUDE.md should go through team review, because they directly affect the Claude Code experience for all team members. Pay particular attention to:

Iterative Improvement

CLAUDE.md is not written once and forgotten โ€” it is continuously iterated on through use:

Observe a problem โ†’ analyze root cause
(Did Claude not know the rule, or was the rule itself not clear enough?)
    โ†“
Update CLAUDE.md โ†’ verify the effect in the next session
    โ†“
Observe whether Claude automatically follows it โ†’
if not, continue to refine

Keeping a CLAUDE.md.changelog or recording change history at the top of the file helps you understand how rules evolved:

<!-- CHANGELOG
2024-03-15: Added Zod validation requirement (after Claude generated unvalidated API input handlers)
2024-03-22: Refined forbidden operations (added database migration rules)
2024-04-01: Imported architecture decision documents
-->

Summary

CLAUDE.md is the central leverage point for engineering-grade use of Claude Code. A carefully designed CLAUDE.md transforms Claude from a "clever general assistant" into a "professional teammate who deeply understands your project."

Key takeaways:

Rate this chapter
4.9  / 5  (3 ratings)

๐Ÿ’ฌ Comments