Claude Code Claude Code Created: 13 Apr 2026 Updated: 13 Apr 2026

Contents of the CLAUDE.md File

In the previous article, we learned that CLAUDE.md files form the backbone of Claude Code's memory system. They are loaded automatically at the start of every session and provide persistent instructions that shape how Claude behaves in your project. But knowing where to place CLAUDE.md files is only half the picture — the real power comes from knowing what to put inside them.

A well-written CLAUDE.md file transforms Claude from a generic coding assistant into a context-aware team member who understands your project's goals, business rules, technology stack, and coding conventions. A poorly written one — or worse, an empty one — forces Claude to guess at every turn, leading to wasted context and inconsistent results.

This article walks through the essential sections of a well-structured CLAUDE.md file: from project goals and business context to framework details, folder structure, and do's-and-don'ts. You will also learn how to use the /init command to auto-generate a starter file, how CLAUDE.md files evolve dynamically as your project grows, how to install Claude Code on your machine, and how to create a dedicated security review sub-agent that performs OWASP Top 10 analysis.

Installing Claude Code

What Is the Claude Code Installer?

Before you can create or use any CLAUDE.md file, you need Claude Code installed on your machine. Claude Code has a dedicated installer that works across macOS, Linux, Windows (via WSL), and native Windows. It is a standalone CLI tool — you do not need Docker, a virtual machine, or any complex setup.

Installation Commands

Choose the command that matches your operating system and shell:

macOS and Linux (or WSL on Windows)

curl -fsSL https://claude.ai/install.sh | sh

Windows PowerShell

irm https://claude.ai/install.ps1 | iex

Windows Command Prompt (CMD)

curl -fsSL https://claude.ai/install.bat | cmd

Alternative Package Managers

If you prefer a package manager, Claude Code is also available through Homebrew and WinGet:

# Homebrew (macOS/Linux)
brew install claude-code

# WinGet (Windows)
winget install Anthropic.ClaudeCode

Verifying Installation and First Login

After installation, launch Claude Code:

claude

On first run, Claude Code asks you to authenticate with your Anthropic account. Follow the browser-based login flow, then return to the terminal. Once authenticated, you are ready to work — and the first thing you should do is create a CLAUDE.md file for your project.

Generating CLAUDE.md with the /init Command

What Does /init Do?

Instead of writing a CLAUDE.md from scratch, you can ask Claude Code to generate one for you. The /init command analyzes your codebase — examining package files, configuration, project structure, and existing code patterns — and produces a starter CLAUDE.md tailored to what it finds.

/init

When you run /init, Claude Code:

  1. Scans your project's file structure and directory layout.
  2. Detects build systems (e.g., .csproj, package.json, Makefile).
  3. Identifies test frameworks and configuration files.
  4. Reads existing documentation like README.md if present.
  5. Generates a CLAUDE.md with project-specific sections based on what it discovered.

Important: /init Is a Starting Point

The generated file is a draft, not a finished product. Claude Code can detect tools and frameworks, but it cannot infer your team's coding conventions, business context, or architectural decisions. You should always review the output and refine it by adding the sections described in the rest of this article.

Think of /init as scaffolding — it gives you a solid foundation, but you need to add the walls, doors, and finishing touches yourself.

Section 1: Project Goal

Why Include the Project Goal?

The first thing your CLAUDE.md should communicate is what this project exists to do. Claude is a general-purpose coding agent — it can build APIs, UIs, database schemas, scripts, and more. Without a clear project goal, Claude has to infer your intent from code alone, which leads to misaligned suggestions.

When Claude knows the project goal, it can make better architectural decisions, name things consistently, and avoid generating features that conflict with the project's purpose.

How to Write It

Keep the project goal short — two to three sentences that describe what the application does and who it serves.

# Project: HealthTracker API

A RESTful API for a health and fitness tracking platform. Provides endpoints for
tracking workouts, nutrition, sleep, and health metrics. Serves both mobile apps
(iOS/Android) and a web dashboard.

C# / ASP.NET Core Example

For an ASP.NET Core project, you might write:

# Project: OrderManagement

An ASP.NET Core Web API for managing e-commerce orders. Handles order creation,
payment processing, inventory checks, and shipping notifications. Serves the
company's React storefront and a Blazor admin dashboard.

Section 2: Business Problem

Why Include the Business Problem?

The business problem gives Claude context about why the project exists, not just what it does. This is critical for making judgment calls. When Claude understands the business domain, it can choose appropriate error messages, validation rules, and naming conventions that align with the domain language.

For example, if Claude knows you are building a financial system, it will be more careful about decimal precision, audit logging, and transaction atomicity — without you having to spell out each rule individually.

How to Write It

## Business Context
This system replaces a legacy monolithic order management system. Key business
requirements:
- Orders must be idempotent to prevent duplicate charges
- All state changes must be audit-logged for compliance (SOX)
- The system processes approximately 50,000 orders per day
- Payment processing uses Stripe with PCI-DSS compliant tokenization

Section 3: How the Project Is Run

Why Include Build and Run Commands?

Claude Code can execute terminal commands, run tests, and build your project. But it cannot guess your specific build commands, especially if your project uses non-standard scripts, multiple environments, or custom tooling. Including exact commands prevents Claude from wasting time (and context) figuring out how to build, test, and run your project.

How to Write It

List every command Claude might need. Be specific — include flags, environment variables, and common variations:

## Commands
- Restore packages: `dotnet restore`
- Build: `dotnet build`
- Run: `dotnet run --project src/OrderManagement.Api`
- Test all: `dotnet test`
- Test single project: `dotnet test tests/OrderManagement.UnitTests`
- Test with filter: `dotnet test --filter "ClassName~OrderService"`
- Watch mode: `dotnet watch run --project src/OrderManagement.Api`
- Database migration: `dotnet ef database update --project src/OrderManagement.Infrastructure`
- Add migration: `dotnet ef migrations add MigrationName --project src/OrderManagement.Infrastructure`
- Lint: `dotnet format`
- Docker: `docker compose up -d`

Notice how each command is on a single line and includes the exact project path where necessary. Claude can copy and execute these commands directly — no guessing required.

Section 4: Frameworks and Technology Stack

Why List Your Frameworks?

Claude knows many frameworks, but it does not know which version or which specific libraries your project uses unless you tell it. Listing your technology stack prevents Claude from suggesting incompatible packages, deprecated APIs, or patterns from the wrong framework version.

How to Write It

Be explicit about versions. Version numbers are especially important for frameworks with breaking changes between major versions:

## Technology Stack
- Runtime: .NET 9
- Framework: ASP.NET Core Minimal APIs
- ORM: Entity Framework Core 9
- Database: PostgreSQL 16
- Caching: Redis via StackExchange.Redis
- Authentication: ASP.NET Core Identity + JWT Bearer tokens
- API Documentation: Swagger via Swashbuckle
- Testing: xUnit + FluentAssertions + NSubstitute
- Containerization: Docker with multi-stage builds
- CI/CD: GitHub Actions

With this section in place, Claude will use Minimal API patterns (not the older Controller-based approach), generate EF Core 9 syntax, and write xUnit tests with FluentAssertions — all without you having to correct it mid-conversation.

Section 5: Folder and Directory Structure

Why Describe the Folder Structure?

Claude Code can read your file system, but reading the full directory tree consumes context tokens. By describing the key directories and their purposes in CLAUDE.md, you give Claude an instant mental map of your codebase without burning tokens on file exploration.

This is especially important for projects following specific architectural patterns like Clean Architecture or Vertical Slice Architecture, where the folder structure is the architecture.

How to Write It

## Project Structure (Clean Architecture)
- src/
- OrderManagement.Api/ → Entry point: Minimal API endpoints, middleware, DI registration
- OrderManagement.Application/ → Use cases: MediatR handlers, DTOs, validators (FluentValidation)
- OrderManagement.Domain/ → Domain entities, value objects, domain events, interfaces
- OrderManagement.Infrastructure/ → EF Core DbContext, repository implementations, external services
- tests/
- OrderManagement.UnitTests/ → Domain and Application layer tests
- OrderManagement.IntegrationTests/ → Database and API integration tests
- OrderManagement.ArchTests/ → Architecture rule tests (NetArchTest)
- docker/ → Dockerfiles and docker-compose files
- docs/ → API documentation and architecture decision records

With this structure documented, Claude knows immediately that a new MediatR handler goes in OrderManagement.Application, a new entity goes in OrderManagement.Domain, and a new repository implementation goes in OrderManagement.Infrastructure. It will not place business logic in the API layer or database code in the Domain layer.

Putting It All Together: A Complete CLAUDE.md

Full Example

Here is a complete, realistic CLAUDE.md for an ASP.NET Core project. Notice how all the sections we discussed come together into a concise, well-structured document:

# Project: OrderManagement

An ASP.NET Core Web API for managing e-commerce orders. Handles order creation,
payment processing, inventory checks, and shipping notifications.

## Business Context
Replaces a legacy monolithic system. Key requirements:
- Orders must be idempotent (prevent duplicate charges)
- All state changes audit-logged for SOX compliance
- ~50,000 orders/day throughput
- Stripe payment processing with PCI-DSS tokenization

## Technology Stack
- .NET 9 / ASP.NET Core Minimal APIs
- Entity Framework Core 9 + PostgreSQL 16
- Redis (StackExchange.Redis) for caching
- ASP.NET Core Identity + JWT Bearer
- xUnit + FluentAssertions + NSubstitute
- Docker with multi-stage builds
- GitHub Actions CI/CD

## Commands
- Build: `dotnet build`
- Run: `dotnet run --project src/OrderManagement.Api`
- Test: `dotnet test`
- Test single: `dotnet test --filter "ClassName~OrderService"`
- Migrate: `dotnet ef database update --project src/OrderManagement.Infrastructure`
- Format: `dotnet format`
- Docker: `docker compose up -d`

## Project Structure (Clean Architecture)
- src/OrderManagement.Api/ → Endpoints, middleware, DI
- src/OrderManagement.Application/ → MediatR handlers, DTOs, validators
- src/OrderManagement.Domain/ → Entities, value objects, domain events
- src/OrderManagement.Infrastructure/ → EF Core, repositories, external services
- tests/OrderManagement.UnitTests/ → Domain + Application tests
- tests/OrderManagement.IntegrationTests/ → DB and API tests

## Code Style
- Use file-scoped namespaces
- Use primary constructors where appropriate
- Use records for DTOs and value objects
- Prefer pattern matching over if-else chains
- All public methods must have XML documentation comments
- Use `var` only when the type is obvious from the right side

## Conventions
- One endpoint per file in Api/Endpoints/
- Use MediatR for all use cases (no direct service calls from endpoints)
- Validation with FluentValidation, registered via DI
- Exceptions: use Result pattern (no throwing for business logic errors)
- Logging: use ILogger<T> with structured logging, never string interpolation

## Do NOT
- Do not use Controllers — this project uses Minimal APIs exclusively
- Do not add NuGet packages without checking existing dependencies first
- Do not modify migration files that have already been applied
- Do not put business logic in the API layer
- Do not use Console.WriteLine — use ILogger

This file is around 50 lines — well within the recommended 200-line limit. Every section earns its place by telling Claude something it cannot reliably infer from code alone.

Dynamic Evolution of CLAUDE.md

CLAUDE.md Is a Living Document

Your CLAUDE.md file is not something you write once and forget. As your project evolves, so should your instructions. New frameworks get adopted, coding conventions change, team members discover new patterns, and old rules become irrelevant.

The official Claude Code documentation advises: "Treat CLAUDE.md like code: review it when things go wrong, prune it regularly, and test changes by observing whether Claude's behavior actually shifts."

When to Update CLAUDE.md

Here are common triggers for updating your CLAUDE.md:

  1. Claude keeps making the same mistake — Add a specific rule to prevent it. If Claude uses Controllers instead of Minimal APIs, add Do not use Controllers to the Do NOT section.
  2. You adopt a new library or tool — Update the Technology Stack section and add any relevant commands.
  3. A convention changes — If your team switches from FluentValidation to DataAnnotations, update the Conventions section immediately.
  4. The folder structure changes — If you add a new project or reorganize directories, reflect it in the Project Structure section.
  5. You notice ignored rules — If Claude ignores a rule, the file might be too long. Prune instructions that Claude already follows without being told.

The Feedback Loop

Think of CLAUDE.md maintenance as a feedback loop:

  1. You give Claude a task.
  2. Claude produces output based on the current CLAUDE.md.
  3. You review the output and notice issues.
  4. You update CLAUDE.md to prevent those issues in the future.
  5. Next session, Claude reads the updated instructions and performs better.

Over time, this loop produces a highly refined instruction set that makes Claude increasingly effective in your specific project.

Adding Emphasis for Critical Rules

If a particular rule is especially important, the documentation suggests adding emphasis markers. Claude responds to urgency signals in instructions:

## IMPORTANT
- ALWAYS run `dotnet test` before committing
- NEVER modify files in the migrations/ directory
- YOU MUST use the Result pattern for error handling — do not throw exceptions for business logic

Use emphasis sparingly — if everything is marked as "IMPORTANT," nothing is.

Checking CLAUDE.md Into Version Control

Your project CLAUDE.md should live in version control alongside your code. This way:

  1. Every team member gets the same instructions when they use Claude Code.
  2. CI/CD pipelines running Claude (via claude -p) also get the same rules.
  3. Changes to instructions are tracked, reviewed, and reversible through normal git workflows.
  4. The file compounds in value over time as the team collaboratively refines it.

Security Review Sub-Agent

What Are Sub-Agents?

Claude Code supports sub-agents — specialized assistants that run in their own isolated context with their own set of allowed tools. Sub-agents are defined as Markdown files in the .claude/agents/ directory of your project.

Sub-agents are useful when you want Claude to perform a specific, focused task — like code review, security analysis, or database validation — without cluttering your main conversation context with all the files it needs to read.

Creating a Security Review Sub-Agent

One of the most practical sub-agents you can create is a security reviewer that analyzes your code for common vulnerabilities based on the OWASP Top 10. Here is an example:

---
name: security-reviewer
description: Reviews ASP.NET Core code for OWASP Top 10 vulnerabilities
tools: Read, Grep, Glob, Bash
model: opus
---

You are a senior application security engineer specializing in ASP.NET Core
applications. Your task is to review code for security vulnerabilities based
on the OWASP Top 10.

## Review Checklist (OWASP Top 10 - 2021)

### A01: Broken Access Control
- Check that all endpoints have proper [Authorize] attributes or equivalent
- Verify role-based and policy-based authorization is enforced
- Look for IDOR (Insecure Direct Object Reference) vulnerabilities
- Ensure users cannot access other users' resources

### A02: Cryptographic Failures
- Check for sensitive data exposure in logs or responses
- Verify passwords are hashed with bcrypt/Argon2, never SHA/MD5
- Ensure connection strings and secrets are not hardcoded
- Check TLS/HTTPS enforcement

### A03: Injection
- Look for raw SQL queries (use parameterized queries or EF Core)
- Check for command injection in Process.Start or Bash calls
- Verify XSS prevention in any HTML rendering
- Check for LDAP, XPath, or other injection vectors

### A04: Insecure Design
- Review authentication flows for logic flaws
- Check rate limiting on sensitive endpoints (login, password reset)
- Verify proper input validation with FluentValidation

### A05: Security Misconfiguration
- Check CORS configuration for overly permissive origins
- Verify error handling does not leak stack traces in production
- Check that debug/development features are disabled in production
- Review middleware pipeline ordering

### A06: Vulnerable and Outdated Components
- Flag any known vulnerable NuGet packages
- Check for deprecated API usage

### A07: Identification and Authentication Failures
- Verify JWT token validation (issuer, audience, expiration)
- Check for proper session management
- Look for hardcoded credentials or API keys

### A08: Software and Data Integrity Failures
- Check for insecure deserialization (avoid BinaryFormatter)
- Verify CI/CD pipeline security

### A09: Security Logging and Monitoring Failures
- Verify that authentication events are logged
- Check that sensitive operations have audit trails
- Ensure log injection is prevented

### A10: Server-Side Request Forgery (SSRF)
- Check for unvalidated URL parameters in HttpClient calls
- Verify URL allowlisting for external service calls

## Output Format
For each finding, report:
1. **Severity**: Critical / High / Medium / Low
2. **OWASP Category**: Which of the A01-A10 categories
3. **File and Line**: Exact location
4. **Description**: What the vulnerability is
5. **Recommendation**: How to fix it with a code example

Save this file at .claude/agents/security-reviewer.md in your project.

Understanding the Frontmatter

The YAML block at the top of the sub-agent file (between --- markers) configures how the sub-agent behaves:

  1. name — A unique identifier used to invoke the sub-agent.
  2. description — A short summary that Claude reads to decide when this sub-agent is relevant. If you say "review this code for security issues," Claude matches that intent to this description.
  3. tools — The tools this sub-agent is allowed to use. Read, Grep, Glob, and Bash let it read files, search codebases, and run commands. By restricting tools, you limit what the sub-agent can do (e.g., no Edit or Write tools means it cannot modify your code).
  4. model — Which model the sub-agent runs on. Using opus gives the sub-agent the most capable model for thorough security analysis.

Invoking the Security Reviewer

Once the file is saved, you can invoke the security reviewer in several ways:

Natural Language (Automatic Delegation)

Simply describe the task, and Claude will automatically delegate to the appropriate sub-agent:

Review the authentication middleware for security vulnerabilities.

Claude recognizes that this matches the security-reviewer sub-agent's description and delegates the task.

Explicit Invocation

You can explicitly ask Claude to use the sub-agent:

Use the security-reviewer agent to analyze the files in src/OrderManagement.Api/Endpoints/

From the Command Line

You can also invoke sub-agents directly from the CLI using the --agent flag:

claude --agent security-reviewer "Review all authentication and authorization code"

Why Sub-Agents Work Well for Security Reviews

Security reviews are ideal candidates for sub-agents because:

  1. They read many files — A thorough security review might scan dozens of files. Running this in a sub-agent keeps your main context clean.
  2. They are read-only — By restricting the sub-agent to Read, Grep, Glob, and Bash (no Edit or Write), you ensure it cannot accidentally modify your code.
  3. They return a summary — The sub-agent reports back its findings as a structured summary, which consumes far less context than all the files it had to read.
  4. They are reusable — The same sub-agent works across all your ASP.NET Core projects.

Example: Security Review in Action

Here is what a typical exchange looks like. Suppose you have the following ASP.NET Core Minimal API endpoint:

// src/OrderManagement.Api/Endpoints/GetOrderEndpoint.cs

app.MapGet("/api/orders/{id}", async (int id, AppDbContext db) =>
{
var order = await db.Orders.FindAsync(id);
return order is not null ? Results.Ok(order) : Results.NotFound();
});

The security reviewer would flag this with findings like:

  1. A01 — Broken Access Control (High): No [Authorize] attribute or .RequireAuthorization() call. Any unauthenticated user can access any order.
  2. A01 — Insecure Direct Object Reference (High): No check that the authenticated user owns the requested order. A user could access another user's order by guessing the ID.

The reviewer would then suggest a fixed version:

// Fixed version with authorization and ownership check

app.MapGet("/api/orders/{id}", async (
int id,
ClaimsPrincipal user,
AppDbContext db) =>
{
var userId = user.FindFirstValue(ClaimTypes.NameIdentifier);
var order = await db.Orders
.FirstOrDefaultAsync(o => o.Id == id && o.UserId == userId);

return order is not null ? Results.Ok(order) : Results.NotFound();
})
.RequireAuthorization();

The fix applies .RequireAuthorization() to enforce authentication and filters the query by the authenticated user's ID to prevent IDOR vulnerabilities.

Summary

A well-structured CLAUDE.md file is the single most effective way to make Claude Code consistently useful in your project. By including a clear project goal, business context, build commands, technology stack, and folder structure, you eliminate guesswork and give Claude the context it needs to make intelligent decisions from the very first prompt.

Use /init to bootstrap the file, then refine it over time as your project evolves. Treat it as a living document — prune what is no longer relevant, add rules when Claude misbehaves, and check it into version control so the whole team benefits. For specialized tasks like security reviews, create dedicated sub-agents that run in isolated contexts with focused instructions.

Remember: every line in your CLAUDE.md should earn its place. Ask yourself, "Would removing this cause Claude to make mistakes?" If the answer is no, cut it. A concise, well-maintained CLAUDE.md beats a bloated one every time.


Share this lesson: