Skip to content

Your CLAUDE.md is too long: move procedures to skills and rules to hooks

From the work/ 16 min read

CLAUDE.md loads in full every session. Keep facts there, move procedures to skills that load on demand and must-hold rules to hooks Claude Code enforces.

  • Claude Code
  • AI
In this article (9)
  1. Everything in CLAUDE.md loads every session
  2. What belongs in CLAUDE.md
  3. Move procedures to skills
  4. Move must-hold rules to hooks
  5. A short CLAUDE.md template
  6. How to prune an existing CLAUDE.md
  7. Common mistakes
  8. Frequently asked questions
  9. Checklist

CLAUDE.md loads in full at the start of every Claude Code session and takes context on every request, whether you need it or not. Keep it to facts every session needs: commands, conventions and layout. Move multi-step procedures to skills, which load when used, and must-hold rules to hooks, which Claude Code runs every time.

Below: what loads when, according to the Claude Code documentation as read on November 19, 2026, a short template, a skill example, a tested Node hook and a method for pruning the file you already have. If your repo uses AGENTS.md, how the two files work together is covered in the AGENTS.md guide; it is not repeated here.

Everything in CLAUDE.md loads every session

The Claude Code memory page is explicit: CLAUDE.md and CLAUDE.local.md files in the directory where you start Claude Code and in every directory above it load at launch, along with your ~/.claude/CLAUDE.md and your organization's managed file if there is one. They do not override each other; they are concatenated, broadest first. CLAUDE.md files in subdirectories come later, once Claude reads, writes or edits a file inside that subdirectory.

Three details change how you should write it:

  • It is context, not configuration. The docs say Claude treats these files as context, not enforced configuration. To block something regardless of what Claude decides, the same page points you to a PreToolUse hook.
  • Longer is not clearer. The target is under 200 lines per file: longer files consume more context and reduce adherence. If a file goes past the recommended length, Claude Code warns you at startup and in /status.
  • Imports save nothing. A line with @docs/git.md imports that file (paths are relative to the importing file, up to four hops deep), but imported content loads together with the CLAUDE.md. Imports organize; they do not slim.

What is free: block-level HTML comments (<!-- note -->) are stripped before the content reaches the context, so they work for notes to whoever maintains the file. And the project-root CLAUDE.md survives /compact: Claude Code re-reads it from disk. To see what your session loaded, run /context all and check the list of memory files.

The Extend Claude Code page sums up the cost of each piece. This table combines what the three pages say:

WhatWhen it loadsWhat enters the context
Project, user and managed CLAUDE.mdSession startFull content, on every request
A subdirectory's CLAUDE.mdWhen Claude reads, writes or edits a file thereFull content from then on
.claude/rules/*.md without pathsSession startSame as .claude/CLAUDE.md
.claude/rules/*.md with pathsWhen Claude touches a matching fileOnly that rule
SkillDescription at start; body when invokedLittle until it is used
Skill with disable-model-invocation: trueOnly when you type /nameNothing until then
HookOn its event, for example before each tool callNothing, unless the hook returns output
Auto memory (MEMORY.md)Session startThe first 200 lines or 25 KB
what enters the context, and whensession start(and again after /compact)the task matchesor you type /nameeach event, e.g.before a tool callCLAUDE.mdfull content on every requestskilldescription from the start; body once it is usedhookruns outside the context; only its output gets inwhat always loads, you always pay forsource: code.claude.com/docs, features-overview

Scroll the figure sideways to see all of it

What belongs in CLAUDE.md

The docs draw the line like this: facts Claude should hold in every session, such as build commands, conventions, project layout and "always do X" rules. If an entry is a multi-step procedure or only matters for one part of the codebase, it goes to a skill or a path-scoped rule. They also say when to add something: when Claude makes the same mistake a second time, when a code review catches something Claude should have known, or when you type the same correction into chat that you typed last session.

Write instructions you can verify. "Use 2-space indentation" works; "format code properly" does not. "API handlers live in app/api/" works; "keep files organized" does not. If two instructions contradict each other, Claude may pick one arbitrarily, so reviewing the file is part of keeping it.

What most CLAUDE.md files that grew too long can drop:

  • What Claude can derive from the code. The directory tree, the dependency list and the architecture overview. The /doctor checkup proposes exactly those cuts for a checked-in CLAUDE.md, and keeps pitfalls, rationale and conventions that differ from tool defaults.
  • Procedures. How to cut a release, add a migration or prepare a deploy: those go to a skill.
  • Folder-specific rules. Conventions for app/api/ go to .claude/rules/api.md with paths, and load only when Claude touches those files.
  • Personal settings. Your sandbox URLs or test data go in CLAUDE.local.md, out of git.
  • Today's task. Acceptance criteria for one change belong in a spec, not in the file every session reads.

If you inherited the project, CLAUDE.md is where you write down what you learned reading it: the commands that work and the traps the code does not show. How to do that first read is in understanding a legacy codebase with Claude Code.

one long CLAUDE.md, split into three placesCLAUDE.md≈400 lines(illustrative)CLAUDE.mdfacts every session needs: commands, conventionsloads in full at the start of every session.claude/skills/<name>/SKILL.mdmulti-step proceduresdescription at start; body when it is used.claude/settings.json → hooksrules that must hold every timeClaude Code runs them; no context usedevery line where it loads when neededsource: Claude Code docs (memory, skills, hooks)

Scroll the figure sideways to see all of it

Move procedures to skills

A skill is a folder with a SKILL.md: in .claude/skills/<name>/ for the project, or in ~/.claude/skills/<name>/ for all your projects. At session start Claude sees only its name and description. The body loads when you type /name or when Claude decides the description matches your task. The docs put it this way: unlike CLAUDE.md content, a skill's body loads only when it is used, so long reference material costs almost nothing until you need it.

This is a "how to add a migration" section taken out of CLAUDE.md. The commands belong to an example project; replace them with yours:

---
name: add-migration
description: Creates a database migration and tests it. Use when a table, a column or an index has to be created or changed.
---

# Add a migration

1. Create db/migrations/NNNN_short_name.sql with the next free number.
2. Write the change so it can run twice: create table if not exists, add column if not exists.
3. Never edit a migration that is already on main: add a new one.
4. Run pnpm db:migrate against the local database, then pnpm test.
5. Reply with the file name and the test result.
  1. The --- lines open and close the YAML frontmatter.
  2. name is the command shown in the / menu. If you leave it out, the folder name is used.
  3. description is the only part Claude sees every session, and it decides from it whether to load the skill. Put what it does first and when to use it second, in the words you would use to ask. In the listing, the description and when_to_use together are cut at 1,536 characters, and with many skills Claude Code drops the descriptions of the ones you use least to fit a budget of 1% of the context window.
  4. The body is the steps. It loads once, enters the conversation and stays there; Claude Code does not re-read the file on later turns.
  5. Step 3 is a rule, but it only matters when migrating, so it lives here and not in CLAUDE.md.

For procedures with side effects, such as a deploy, add disable-model-invocation: true: Claude cannot invoke it on its own and its description stays out of the context; it runs only when you type /deploy. Keep SKILL.md under 500 lines and move long reference material to supporting files in the same folder. After the conversation is compacted, Claude Code re-attaches the first 5,000 tokens of each invoked skill, with a combined cap of 25,000, so put what matters at the top. Your old .claude/commands/ files keep working.

Move must-hold rules to hooks

"Never use npm" in CLAUDE.md is a request. The features page says it plainly: an instruction like "never edit .env" in CLAUDE.md or a skill is a request, not a guarantee; a PreToolUse hook that blocks the edit is enforcement. A hook is a command Claude Code runs on an event, without Claude deciding, and it takes no context unless it returns output.

This hook blocks npm and npx in a repo that uses pnpm. It goes in .claude/settings.json, which you commit for the whole team:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "node",
            "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/no-npm.mjs"]
          }
        ]
      }
    ]
  }
}
// PreToolUse hook: this repo uses pnpm, so block any Bash command that runs npm or npx.
import { readFileSync } from "node:fs";

let input;
try {
  input = JSON.parse(readFileSync(0, "utf8")); // Claude Code sends the event as JSON on stdin
} catch {
  process.exit(0); // unreadable input: no decision, the normal permission flow continues
}

const command = input.tool_input?.command ?? "";
// npm or npx at the start of the command or after ; & | ( or a newline
if (/(^|[;&|(\n]\s*)(npm|npx)(\s|$)/.test(command)) {
  console.error("This repo uses pnpm. Use pnpm instead of npm, and pnpm dlx instead of npx.");
  process.exit(2); // exit 2 on PreToolUse: the call is blocked and Claude reads stderr
}
process.exit(0);
  1. "PreToolUse" is the event: it runs before every tool call. "matcher": "Bash" limits it to terminal commands.
  2. "command": "node" with "args" is the exec form, with no shell: Claude Code substitutes ${CLAUDE_PROJECT_DIR} with the project root as plain text, so the same line works under Git Bash and PowerShell.
  3. readFileSync(0) reads stdin, where the event arrives as JSON with tool_name and tool_input.
  4. If the JSON cannot be parsed, the script exits 0 with no output. Per the docs that approves nothing; the call just goes through the normal permission flow.
  5. The regex looks for npm or npx as a word at the start of the command or after ;, &, |, ( or a newline, so it catches cd app && npm test but not pnpm test.
  6. On exit 2, Claude Code blocks the call and passes the stderr text to Claude. That is why the message names the alternative: Claude fixes the command on its next try.

We tested it by piping JSON in by hand, without opening Claude Code:

$ echo '{"tool_name":"Bash","tool_input":{"command":"cd app && npm test"}}' | node .claude/hooks/no-npm.mjs; echo "exit $?"
This repo uses pnpm. Use pnpm instead of npm, and pnpm dlx instead of npx.
exit 2
$ echo '{"tool_name":"Bash","tool_input":{"command":"pnpm test"}}' | node .claude/hooks/no-npm.mjs; echo "exit $?"
exit 0

Limits worth knowing. Any exit code other than 0 and 2 does not block: the action goes ahead. A hook that hits its timeout (600 seconds by default) does not block either. And the regex does not see npm called from inside a script, or sudo npm. It is a guard for the rule, not a sandbox. If all you need is to forbid a command without naming the alternative, a deny rule is enough: see Claude Code permissions in settings.json. For protecting files like .env, the full case is in the hook that protects .env.

A short CLAUDE.md template

With procedures in skills and rules in hooks, what is left fits on one screen. This is the template for the example project:

# Shop frontend

Next.js 15 with the App Router and strict TypeScript. Package manager: pnpm.

## Commands
- Dev: pnpm dev
- Before you call a task done: pnpm test and pnpm typecheck

## Conventions
- Server Components by default; "use client" only for state or events.
- Prices are stored as integer cents and formatted only in the UI.
- Do not commit or push unless I ask.

## Where things live
- API routes in app/api/. Shared logic in lib/.
- Migrations: follow the add-migration skill.
- Deploys: I run /deploy myself; do not deploy.

<!-- For maintainers (Claude never sees this):
     the npm and npx block lives in .claude/hooks/no-npm.mjs. -->
  1. The heading and first paragraph say what the project is and what it is built with. Nothing more: Claude reads the rest from the code.
  2. "Commands" is what Claude cannot guess: how to run things and what must pass before a task is done.
  3. "Conventions" are decisions you cannot see in a single file, written so they can be checked. If "do not commit" must hold every time, also add it as an ask rule in permissions.
  4. "Where things live" points at the skills. Claude already sees the migration skill through its description; it cannot see the deploy skill, which has disable-model-invocation, so the line tells it not to deploy.
  5. The HTML comment tells people why there is no npm rule in the file. Claude Code strips it before loading.

How to prune an existing CLAUDE.md

Do not rewrite it from memory. Measure, sort every line, then move it. The method:

  1. Measure. Count lines with wc -l CLAUDE.md and check /context all to see the weight of each memory file. Count the files you import with @ too.
  2. Flag candidates. The claude-md-check.mjs script below (Node, no dependencies) lists the longest sections and flags numbered lists of four steps or more, long code blocks and lines with "never", "always" or "must".
  3. Pick a destination for each line with the table below. The script only flags; you decide.
  4. Ask for proposals. /doctor proposes trims for a checked-in CLAUDE.md, and /doctor prompt-audit (version 2.1.283 or later) looks for outdated instructions, references to files or commands that no longer exist and contradictions between files. Nothing changes until you ask.
  5. Test. Open a new session, check /context all and ask for a task that needs a procedure you moved. If Claude does not load the skill, improve its description.

Save it as claude-md-check.mjs and run node claude-md-check.mjs CLAUDE.md:

// Usage: node claude-md-check.mjs [path/to/CLAUDE.md]
// Prints size, the longest sections, and lines worth moving out of CLAUDE.md.
import { readFileSync } from "node:fs";

const file = process.argv[2] ?? "CLAUDE.md";
const lines = readFileSync(file, "utf8").trimEnd().split(/\r?\n/);
console.log(`${file}: ${lines.length} lines${lines.length > 200 ? " (over the 200-line target)" : ""}`);

const sections = [];
const flags = [];
let inCode = false, codeStart = 0, steps = 0;
lines.forEach((line, i) => {
  const n = i + 1;
  if (line.startsWith("```")) {
    if (inCode && n - codeStart > 6) flags.push([codeStart, `code block of ${n - codeStart - 1} lines -> skill`]);
    inCode = !inCode;
    codeStart = n;
    return;
  }
  if (inCode) return;
  if (/^#{1,3} /.test(line)) sections.push({ title: line, start: n });
  steps = /^\s*\d+[.)] /.test(line) ? steps + 1 : 0;
  if (steps === 4) flags.push([n - 3, "numbered procedure -> skill"]);
  if (/\b(never|always|must|do not|don't|nunca|siempre|no hagas)\b/i.test(line)) flags.push([n, "hard rule -> hook if it must hold every time"]);
});

sections.forEach((s, i) => (s.size = (sections[i + 1]?.start ?? lines.length + 1) - s.start));
console.log("\nLongest sections:");
for (const s of [...sections].sort((a, b) => b.size - a.size).slice(0, 5)) console.log(`  ${String(s.size).padStart(4)}  ${s.title}`);
console.log("\nCandidates to move:");
for (const [n, why] of flags.sort((a, b) => a[0] - b[0])) console.log(`  line ${n}: ${why}`);
  1. It reads the file, drops the trailing newline and splits it into lines. Past 200, the first line of the output says so.
  2. It walks the lines once. A line that starts with three backticks opens or closes a code block; on closing, if the block had more than five lines, it is flagged as a skill candidate.
  3. Inside a code block it looks at nothing else, so an SQL always is not mistaken for a rule.
  4. Every #, ## or ### heading starts a section. At the end, each section's size is the distance to the next one, and the five longest are printed.
  5. steps counts consecutive numbered lines; at four it flags the start of the list as a procedure.
  6. Lines with "never", "always", "must", "nunca", "siempre" or "no hagas" are flagged as possible hooks. It is a hint: you decide whether the rule must hold every time.

This is the script's output on an example 32-line CLAUDE.md (illustrative):

$ node claude-md-check.mjs CLAUDE.md
CLAUDE.md: 32 lines

Longest sections:
    10  ## Database migrations
     7  ## Release process
     5  ## Conventions
     4  # Shop frontend
     4  ## Commands

Candidates to move:
  line 11: hard rule -> hook if it must hold every time
  line 12: hard rule -> hook if it must hold every time
  line 15: numbered procedure -> skill
  line 22: code block of 6 lines -> skill

Line 11 ("Never use npm in this repo") moves to the hook above. Line 12 ("Always run pnpm test before saying a task is done") stays: it is a convention Claude can follow, and a PreToolUse hook cannot block it. Line 15 starts the release process, which becomes a skill with disable-model-invocation. Line 22 is an SQL template, which goes inside the migration skill.

If the line is…It goes to
A command, convention or fact every session needsCLAUDE.md
A multi-step procedure or reference materialA skill in .claude/skills/
A procedure with side effects (deploy, publish)A skill with disable-model-invocation: true
A rule for one folder or file type.claude/rules/ with paths
A rule that must hold every timeA hook, or a deny rule in permissions
Something Claude can derive from the codeDeleted
A personal preferenceCLAUDE.local.md or ~/.claude/CLAUDE.md
CLAUDE.md, skill or hook: how each loadsCLAUDE.mdskillhookloadsat start, in fulland after /compactdescription at startbody when usednever: it runson each eventcontextevery requestlow until usedzero, unless itreturns outputwho decidesClaude interprets itClaude, or youwith /nameClaude Code, alwaysbest forfacts, conventionsmulti-stepproceduresrules that mustalways holda rule in CLAUDE.md is a request; a hook enforces iteach thing in its layersource: code.claude.com/docs/en/features-overview

Scroll the figure sideways to see all of it

Common mistakes

  • Splitting the file with imports and calling it short. Imported files load with the CLAUDE.md that imports them; the cost is the same.
  • Writing must-hold rules as text. If a rule must hold every time, a line in CLAUDE.md does not guarantee it. Use a hook or a permission rule.
  • Vague skill descriptions. "Helps with the database" does not tell Claude when to load it. Say what it does and when to use it, in the words you would use to ask.
  • Letting Claude invoke a deploy. A skill with side effects and no disable-model-invocation: true can run when Claude decides the code looks ready.
  • A hook that fails silently. An error that exits with code 1 blocks nothing. Test the script with hand-made JSON before you rely on it.
  • Copying the directory tree into CLAUDE.md. Claude reads it from the repo, and the copy goes stale at the next refactor.

Frequently asked questions

How many lines should my CLAUDE.md have?

The Claude Code docs recommend under 200 per file. It is not a hard limit: past it, Claude Code warns you, because a long file consumes more context and reduces adherence. What matters is that every line is useful to every session.

Do skills use context even when I don't use them?

A little: their name and description are in every request so Claude knows they exist. The body enters only when the skill is used. With disable-model-invocation: true not even the description enters, and the skill runs only when you type its name.

Can a hook replace CLAUDE.md?

No. A hook enforces one specific rule on one specific event, but it does not tell Claude how to work in your project. Use both: CLAUDE.md says what is expected and the hook stops what must never happen.

What is the difference between .claude/rules and a skill?

A rule without paths loads at session start, like CLAUDE.md, and a rule with paths loads when Claude touches a matching file. A skill loads when you invoke it or when its description matches the task. Rules are for conventions in one part of the code; skills are for procedures and reference material.

Checklist

  • CLAUDE.md is under 200 lines, counting what it imports with @.
  • It holds only commands, conventions and facts every session needs.
  • Every multi-step procedure lives in a skill with a concrete description.
  • Skills with side effects carry disable-model-invocation: true.
  • Folder-specific rules are in .claude/rules/ with paths.
  • Must-hold rules are hooks or permission rules, tested with hand-made JSON.
  • Notes for people go in HTML comments.
  • You checked /context all in a new session after pruning.

Saw this on Instagram? Every Reel guide is at ecomlabs.dev/guides.

Written by

Luis Morales

Luis Morales

Frontend and Shopify developer, EcomLabs

@luismoralesdev on Instagram

Published November 19, 2026 · updated November 20, 2026

← Blog