claude-md-skill-v3
NewUse when the user asks to write, audit, improve, split, or fix a CLAUDE.md file or the .claude/ memory system. Also use for: "why does Claude keep over-engineering", "how do I stop Claude touching unrelated code", "Claude ignores my rules", "set up Claude Code memory", "my CLAUDE.md is too long", "split my CLAUDE.md", "what should go in CLAUDE.md", "should I use AGENTS.md", context management, token budget, what loads at session start, rules stopping working mid-session, or anything about .claude/rules/ or @-imports.
Overview
CLAUDE.md Skill v3
Expert guidance for the Claude Code memory system. Synthesizes:
- Anthropic's official CLAUDE.md architecture — file locations, scoping, token economics, import behavior, path-scoped rules
- Karpathy's behavioral engineering principles — the four failure modes that make AI agents unreliable and the guardrails that fix them
Output is production-ready: concrete, verified against Anthropic's official docs, structured to prevent the most common Claude Code failure modes, and free of redundancy.
Ground Truth — Non-Negotiable Facts
These are canonical. Treat them as immutable.
Session loading sequence (order matters for conflict resolution):
Each session, Claude loads files in this order. Later sources can contradict earlier ones — Claude picks arbitrarily when rules conflict, so resolving conflicts explicitly is critical.
- System prompt (Anthropic-controlled, cannot be changed)
~/.claude/CLAUDE.md— user-level, applies to all projects- Project root
CLAUDE.mdor.claude/CLAUDE.md— shared via git CLAUDE.local.md— personal project notes, gitignored.claude/rules/*.mdwithoutpaths:— every session- All
@-importsfrom the above — inlined at load time, same as embedding <subdir>/CLAUDE.mdfiles — on-demand only when Claude reads files there.claude/rules/*.mdwithpaths:— on-demand only when Claude reads matching files
This sequence is why:
- •User-level rules can be overridden by project rules (intended for project-specific exceptions)
- •Path-scoped rules are the only way to reduce per-session token cost
- •Subdirectory CLAUDE.md files don't survive
/compact(they're on-demand, not always loaded) - •Conflicts between sources (#2–#6) are common in large setups — run
/memoryto see the full loaded set
Memory system mechanics:
- •CLAUDE.md loads as a user message after the system prompt. It is context, not enforced configuration. Adherence is probabilistic, not guaranteed.
- •Target size: under 200 lines per file. Files over 200 lines reduce adherence — important rules get lost in noise.
- •Project-root CLAUDE.md survives `/compact`. Nested
<subdir>/CLAUDE.mdfiles do NOT — they reload only when Claude touches a file in that subdir. - •`@path/to/file` imports load at launch alongside the parent CLAUDE.md. They do NOT reduce context; they help organization only. Max import depth: 5 hops.
- •`.claude/rules/*.md` without `paths:` frontmatter loads every session — same priority as
.claude/CLAUDE.md. - •`.claude/rules/*.md` WITH `paths:` frontmatter loads ONLY when Claude reads matching files. This is the ONLY mechanism that genuinely reduces per-session token cost while keeping rules in scope.
- •Block-level HTML comments `<!-- ... -->` are stripped before injection — free maintainer notes that cost zero tokens.
- •Auto memory is a separate system — Claude writes its own memory file (distinct from project CLAUDE.md); first 200 lines / 25KB load every session. Managed via
/memorycommand. Never confuse with project CLAUDE.md. - •`/init` generates a starter CLAUDE.md — recommend for new projects.
- •`/memory` shows which CLAUDE.md, CLAUDE.local.md, and rules files are currently loaded.
- •Emphasis like `IMPORTANT` or `YOU MUST` measurably improves adherence — officially endorsed, but only when used sparingly.
- •AGENTS.md is NOT read by Claude Code. If a repo has one, use
@AGENTS.mdat the top of CLAUDE.md.
Karpathy's behavioral facts (derived from systematic observation):
- •LLMs make silent assumptions and run with them without asking.
- •LLMs over-engineer by default — abstractions for single-use code, "flexibility" that wasn't requested, 200 lines when 50 would do.
- •LLMs touch adjacent code when making surgical fixes — reformatting, refactoring, deleting comments not related to the task.
- •LLMs succeed at verification loops — give them success criteria and they loop until met; give them vague instructions and they guess.
File Locations & Scope
| Location | Scope | Loaded |
|---|---|---|
./CLAUDE.md or ./.claude/CLAUDE.md | Project (team-shared via git) | Every session |
./CLAUDE.local.md | Personal project notes (gitignored) | Every session |
~/.claude/CLAUDE.md | User-level (all projects) | Every session |
<subdir>/CLAUDE.md | Subdirectory | On-demand when Claude reads files there |
.claude/rules/*.md (no paths:) | Project rules | Every session |
.claude/rules/*.md (with paths:) | Path-scoped rules | Only when Claude reads matching files |
| Managed policy paths (OS-specific) | Org-wide | Every session, cannot be excluded |
Mode Detection
Map the request to one mode. When a request spans structural modes (DRAFT/AUDIT/REFINE/ARCHITECT), do the earlier mode first.
| User signal | Mode |
|---|---|
| "write", "create", "start", "from scratch", "/init equivalent" | DRAFT |
| "review", "audit", "check", "what's wrong", "too long", "is it good" | AUDIT |
| "improve", "optimize", "clean up", "tighten", "rewrite" | REFINE |
| "split", "restructure", "break up", "modular", "path-scoped" | ARCHITECT |
| "why does Claude keep doing X", "stop Claude from Y", "Claude keeps over-engineering / touching unrelated code / assuming wrong scope" | BEHAVIORAL |
| "context is getting full", "Claude forgot my rules", "rules stopped working mid-session", "how do I reduce tokens", "what loads at session start", "why is Claude ignoring my CLAUDE.md after /compact" | CONTEXT MANAGEMENT |
CONTEXT MANAGEMENT mode: See the ## Context Management section. Start by diagnosing: is it a token budget problem (file too long), a loading problem (rules in wrong location), or a long-session degradation problem?
BEHAVIORAL mode: Run AUDIT first to check whether a guardrail already exists. If it does and Claude is still ignoring it, the rule may be vague — REFINE it. If no guardrail exists, embed the appropriate Karpathy principle from the Behavioral Layer section. See the dedicated ## BEHAVIORAL Mode section below for step-by-step guidance.
File provided vs described: If the user pastes or uploads a CLAUDE.md, default to AUDIT. If they describe their project without providing a file, default to DRAFT.
If unclear: ask one question to disambiguate. Do not guess.
DRAFT Mode
Step 1 — Recommend /init first (if applicable)
If the project has an existing codebase and the user is in Claude Code, recommend running /init first. It auto-detects build systems, test frameworks, and codebase patterns. Then refine the output using this skill.
If they want to author manually, or /init output needs improvement, proceed.
Step 2 — Gather (only what cannot be inferred)
Ask for:
- Project name + one-line purpose
- Tech stack (languages, frameworks, key libraries)
- Mistakes Claude has made or is likely to make in this codebase
- Hard constraints (security, compliance, branch rules)
- Non-obvious commands (skip standard ones — Claude knows
npm test,cargo build) - Whether this is a monorepo (affects nesting strategy)
- Whether over-engineering, silent assumptions, or drive-by refactoring have been problems — if yes, embed behavioral guardrails (see Behavioral Layer section below)
Do NOT ask:
- •Folder structure (infer from stack conventions)
- •Code style enforced by linter/formatter (unless adherence has been poor)
- •Standard language conventions
Step 3 — Draft using the section template
Omit any section the user has nothing meaningful for. A short, honest CLAUDE.md beats a padded one.
# [Project Name]
[One sentence: what it is + stack]
<!-- Last reviewed: [date]. Owner: [name]. -->
## Commands
- [name]: `[exact command]`
(Only commands Claude cannot guess or with non-standard flags.)
## Architecture
- [Non-obvious structural rule]
(What Claude cannot infer from reading files. Max ~8 lines.)
## Code Style
- [Rule that differs from Claude's default]
(Concrete and verifiable only. Skip anything tooling already enforces silently.)
## Workflow
- [How Claude should operate in this repo]
- [Branch / commit / PR conventions specific to this repo]
## Constraints
- IMPORTANT: [Hard rule] — [alternative if NEVER rule]
(Use IMPORTANT or YOU MUST for genuinely critical rules only. Max 3–5 total.)
## Glossary
- [Term]: [definition + path]
(Project-specific vocabulary only. Skip industry-standard terms.)
## Behavior
(Optional — omit if behavioral failures haven't been a problem. Add short form if they have.
See Behavioral Layer section for the embeddable block.)
## Reference Docs
- [topic]: `path/to/doc.md` — read when [condition]
(Pointer text, NOT @-imports, so they don't load every session.)Step 4 — Budget check
Report:
- •Line count (target: <200, hard ceiling: 300)
- •Estimated token cost (~15 tokens per line; range is 12–18 depending on line density)
- •Any rule that fails the Verifiability Test ("Format code properly" → flag it)
- •Whether behavioral guardrails should be added (see Behavioral Layer)
AUDIT Mode
Read the file fully before commenting. Run every line through the 6 tests.
The 6 Tests
1. Removal Test — "If I delete this line, will Claude make a concrete, repeatable mistake?"
- •FAIL → delete or move to
.claude/rules/ordocs/
2. Verifiability Test — "Is this rule concrete enough to verify?"
- •"Format code nicely" → FAIL (vague)
- •"Use 2-space indentation" → PASS (concrete)
- •FAIL → rewrite to be specific, or delete
3. Frequency Test — "Does this rule apply to most sessions, or only when Claude touches specific files?"
- •Universal → keep in CLAUDE.md
- •File-type-specific → move to
.claude/rules/<topic>.mdwithpaths:frontmatter
4. Conflict Test — "Does this contradict another rule in this file or another loaded file?"
- •FAIL → resolve. Conflicts cause Claude to pick arbitrarily.
5. Inferability Test — "Will Claude reliably follow this from reading existing code patterns alone?"
- •If yes AND Claude historically does follow it → consider removing
- •If yes BUT Claude has been ignoring the existing patterns → keep, possibly add IMPORTANT
- •If no → keep
6. Behavioral Test — "Does Claude repeatedly violate this type of rule (over-engineering, silent assumptions, surgical sprawl)?"
- •If yes → add Karpathy guardrail from the Behavioral Layer section
Audit Report Format
AUDIT — [filename]
Lines: X | Est. tokens: Y | Sections: Z
🔴 DELETE — [count] lines
L12: "Write clean code" — vague, fails Verifiability Test
L34: "Use good variable names" — Claude does this by default
🟡 MOVE TO PATH-SCOPED RULE — [count] lines
L20–24: Frontend-only rules → .claude/rules/frontend.md (paths: src/components/**)
L30–32: API-only rules → .claude/rules/api.md (paths: src/api/**)
🟠 MERGE — [count] lines
L8 + L41 both forbid class components → keep L8, delete L41
🔵 REWRITE — [count] lines
L15: "Try to use TypeScript" → "Use TypeScript for all .ts files"
L22: "Never use any" → "Never use any; prefer unknown with type guards"
🟢 ADD BEHAVIORAL GUARDRAIL — [which principle]
Observation: Claude repeatedly adds unrequested abstractions
Fix: Add Karpathy Simplicity guardrail (see Behavioral Layer)
✅ KEEP — [count] lines
Estimated savings: ~Y lines | ~Z tokens per sessionREFINE Mode
Run AUDIT internally first. Then apply rewrites in this order:
- Resolve conflicts — pick one rule, delete the other
- Tighten phrasing
- Hedges → imperatives: "try to use" → "use" - Orphan prohibitions → prohibition + alternative: "Never X" → "Never X; do Y instead" - Vague rules → concrete and verifiable
- Move out misplaced content
- Path-specific rules → .claude/rules/<topic>.md with paths: frontmatter - Long docs/specs → docs/ directory; pointer text reference in CLAUDE.md - Workflows only needed sometimes → .claude/skills/<name>/SKILL.md
- Embed behavioral guardrails if history shows repeated failure modes (see Behavioral Layer)
- Add emphasis to genuinely critical rules using
IMPORTANTorYOU MUST. Max 3–5 total. - Strip dead weight — outdated rules, duplicates, prose explanations Claude doesn't need
- Add maintainer notes as `<!-- ... -->` — stripped from context, zero token cost
Output: complete rewritten file + diff summary listing what changed and why.
ARCHITECT Mode
Use when CLAUDE.md exceeds ~250 lines, the project has multiple distinct domains, or audit finds many path-specific rules.
The Architecture
project-root/
├── CLAUDE.md # Universal rules + behavioral guardrails (<200 lines)
├── CLAUDE.local.md # Personal notes (gitignored)
├── .claude/
│ ├── rules/
│ │ ├── frontend.md # paths: src/components/**, src/pages/**
│ │ ├── api.md # paths: src/api/**
│ │ ├── database.md # paths: supabase/**, migrations/**
│ │ └── testing.md # paths: **/*.test.ts, **/*.spec.ts
│ ├── skills/
│ │ └── <domain>/SKILL.md # On-demand domain workflows
│ └── commands/
│ └── <name>.md # Slash commands for repeatable flows
└── docs/
├── spec.md # Full product spec — pointer text reference
├── schema.md # DB schema — pointer text reference
└── ui-system.md # Design system — pointer text referencePath-Scoped Rule Template
---
paths:
- "src/components/**/*.{ts,tsx}"
- "src/pages/**/*.tsx"
---
# Frontend Rules
- Use functional components with hooks; never class components
- Styling: Tailwind classes only; never inline styles
- Animation: Motion library; never CSS transitionsDecision Matrix
| Rule character | Belongs in |
|---|---|
| Applies to every session, every file | CLAUDE.md |
| Behavioral guardrail (universal anti-pattern) | CLAUDE.md (Behavioral Layer section) |
| Applies only to specific file paths | .claude/rules/<topic>.md with paths: |
| Multi-step workflow invoked sometimes | .claude/skills/<name>/SKILL.md |
| Repeatable command with arguments | .claude/commands/<name>.md |
| Reference content (specs, schemas, examples) | docs/<file>.md (pointer text, not @-import) |
| Personal preference, project-specific | CLAUDE.local.md (gitignored) |
| Personal preference, all projects | ~/.claude/CLAUDE.md |
Monorepo Specifics
- •Each package can have its own
CLAUDE.md— loads on-demand when Claude touches that subdir - •Use
claudeMdExcludesin.claude/settings.local.jsonto suppress loading ancestor CLAUDE.md files that don't apply to a given subpackage - •Place truly global rules at the monorepo root; package-specific rules at the package root
.claude/ System Files (Beyond Rules)
These files exist alongside rules/, skills/, and commands/ and are part of the full .claude/ memory system:
| File | Purpose |
|---|---|
.claude/settings.json | Shared project settings (hooks, permissions) — commit to git |
.claude/settings.local.json | Personal project settings (claudeMdExcludes, API key overrides) — gitignore |
.claude/hooks/ | Lifecycle scripts (e.g. SessionStart, PreToolUse) — run shell commands at key points |
Hooks (in settings.json): Claude Code can run shell scripts at session start, before/after tool use, and on other lifecycle events. Common use: auto-generating knowledge graph files like CONNECTIONS.md so they're always fresh. Example:
{
"hooks": {
"SessionStart": [{ "hooks": [{ "type": "command", "command": "bash .claude/hooks/pre-session.sh", "timeout": 10 }] }]
}
}When a project uses hooks, reference the hook scripts in the CLAUDE.md Knowledge Graph or Workflow section so Claude knows they exist and what they produce.
BEHAVIORAL Mode
Use when the user reports a recurring Claude behavior failure: over-engineering, silent assumptions, drive-by refactoring, or vague task completion.
Step 1 — Identify the failure
Ask: "What is Claude doing that it shouldn't be?" Map to a category using references/behavioral-audit.md.
Step 2 — Check existing CLAUDE.md
Run AUDIT on the file. Check whether a guardrail for this failure already exists:
- •Guardrail exists and vague → REFINE it (make it concrete and actionable)
- •Guardrail exists and concrete → the problem may be file length or rule conflict; fix those first
- •No guardrail → proceed to Step 3
Step 3 — Embed the right guardrail
Match the failure to its principle and embed only what's needed:
| Failure | Principle | What to embed |
|---|---|---|
| Added unrequested features or abstractions | Simplicity first | Short form or targeted Simplicity rule |
| Touched code not related to the task | Surgical changes | Short form or targeted Surgical rule |
| Assumed scope and ran with it | Think before coding | Short form or targeted Think rule |
| Declared done without verifying | Goal-driven execution | Short form or targeted Goal rule |
Don't embed all four principles because one failed. Match and embed the minimum.
Step 4 — Choose placement
- •This project only: Add
## Behaviorsection to root CLAUDE.md - •All projects: Add to
~/.claude/CLAUDE.mdinstead — applies everywhere with zero per-project overhead - •Team project with recurring failures: Use long form; document which specific failure prompted it
Step 5 — Verify the guardrail passes the Output Rules
- •[ ] Concrete, not vague ("No abstractions for single-use code" not "Don't over-engineer")
- •[ ] Paired if prohibitive ("Mention dead code — don't delete it")
- •[ ] Not marked IMPORTANT (behavioral guidelines don't warrant it; reserve for project constraints)
- •[ ] Total file stays under 200 lines after addition
Context Management
Use this mode when the user asks about token budget, why rules stop working, what loads at session start, or how to recover after /compact.
Step 1 — Diagnose the problem
| Symptom | Root cause | Fix |
|---|---|---|
| Claude ignores rules from the start | File too long OR rule too vague | AUDIT the file; apply 6 tests |
| Claude follows rules early, ignores later | Long-session degradation | Use /compact proactively; shorten file |
Rules disappeared after /compact | Rules were in subdirectory CLAUDE.md | Move to root CLAUDE.md or always-loaded rules |
| Session starts slow / feels heavy | Too many always-loaded sources | Run budget worksheet; move to path-scoped rules |
| Rules conflict with each other | Multiple loaded sources contradict | Run /memory; resolve conflicts |
Step 2 — Run /memory first
Always start here. /memory shows exactly which files are loaded this session. Many "Claude ignores my rules" reports turn out to be "CLAUDE.md isn't loading at all."
Step 3 — Calculate the budget
Use the budget worksheet below. If over 2,000 tokens, apply the remediation path.
Step 4 — Apply the fix
- •File too long / vague rules → AUDIT mode
- •Path-specific rules in root → ARCHITECT mode
- •Rules in wrong location → move per the Decision Matrix
- •Long-session degradation → shorten file; use
/compactearlier - •Post-`/compact` rule loss → move critical rules to root CLAUDE.md
Context management is the practice of controlling what loads into Claude's context window at session start, and keeping that budget lean enough that rules have full effect.
Why it matters
Every file that loads at session start costs tokens. Claude's effective context window is shared between:
- •All loaded CLAUDE.md sources
- •Auto memory
- •The actual work: files being edited, tool outputs, conversation history
A CLAUDE.md that costs 3,000 tokens per session on a 200k-token context window is only 1.5% — negligible. But three or four large files loaded unconditionally can cost 10–20k tokens before any work begins, and more importantly, they dilute adherence. Rules buried at token position 15,000 get less attention than rules at position 500.
The three levers
Lever 1 — Keep root CLAUDE.md under 200 lines The single highest-impact decision. Under 200 lines, adherence is strong. Over 300, adherence degrades measurably. Budget every section.
| Section | Typical cost | Budget |
|---|---|---|
| Header + stack line | 3–5 lines | Always |
| Commands | 4–8 lines | Only non-obvious ones |
| Architecture | 4–8 lines | Only non-inferable rules |
| Code Style | 4–6 lines | Only what differs from Claude defaults |
| Workflow | 3–5 lines | Only project-specific steps |
| Constraints | 3–5 lines | Hard limits only, max 5 IMPORTANT |
| Glossary | 3–8 lines | Project-specific terms only |
| Behavior | 10–20 lines | Short form unless failures are recurring |
| Reference Docs | 3–5 lines | Pointer text only |
| Total target | ~40–70 lines | Never exceed 200 |
Lever 2 — Move path-specific rules to `.claude/rules/` with `paths:` frontmatter This is the ONLY mechanism that keeps rules available but out of the every-session token budget. A 40-line frontend rule file with paths: src/components/** costs zero tokens when editing a migration.
Example token savings per session by task type:
- •Editing a component: loads root + frontend rules = ~70 lines, ~900 tokens
- •Editing a migration: loads root + database rules = ~65 lines, ~850 tokens
- •Without path-scoping: all rules load every session = ~150 lines, ~2,000 tokens
Lever 3 — Reference large docs, don't embed them @-imports and embedded content load every session. For docs larger than ~20 lines, use pointer text:
- Full spec: `docs/spec.md` — read when modifying the UI or adding features
- DB schema: `docs/schema.md` — read before any DDL or query workClaude reads them on-demand. They cost zero tokens when not needed.
Context budget worksheet
Before finalizing any CLAUDE.md setup, estimate the per-session cost:
Per-session context budget:
~/.claude/CLAUDE.md : ___ lines × ~15 tok/line = ___ tokens
Root CLAUDE.md : ___ lines × ~15 tok/line = ___ tokens
CLAUDE.local.md : ___ lines × ~15 tok/line = ___ tokens
rules/ (no paths:) : ___ lines × ~15 tok/line = ___ tokens
@-imports : ___ lines × ~15 tok/line = ___ tokens
─────────────────────────────────────────────────────────────────
Total every-session cost : ___ tokens
On-demand (path-scoped):
rules/frontend.md : ___ lines (loads only when: src/components/**)
rules/database.md : ___ lines (loads only when: supabase/**)
rules/testing.md : ___ lines (loads only when: **/*.test.ts)Target: total every-session cost under 2,000 tokens. This is a practical floor — at ~1% of a 200k context window, it keeps memory sources from crowding out actual work context and maintains rule adherence throughout the session.
If your budget exceeds 2,000 tokens:
- Identify the largest loaded source (usually root CLAUDE.md or always-loaded rules files)
- Run the 6 AUDIT tests on it — most oversized files have 30–50% deletable lines
- Move path-specific sections to
.claude/rules/<topic>.mdwithpaths:frontmatter (ARCHITECT mode) - Replace embedded docs with pointer text references
- Move behavioral guardrails to
~/.claude/CLAUDE.mdif they apply to all projects
If budget is still over after these steps, the project likely needs full ARCHITECT mode restructuring.
/compact and context management
/compact summarizes the conversation to free up context window space. Know what survives and what doesn't:
Survives /compact | Does NOT survive /compact |
|---|---|
Root CLAUDE.md (reloads) | Subdirectory CLAUDE.md files (on-demand only) |
~/.claude/CLAUDE.md (reloads) | Conversation history (summarized) |
.claude/rules/*.md (reloads) | In-session tool outputs |
CLAUDE.local.md (reloads) | File content Claude read mid-session |
Implication: Critical rules must be in root CLAUDE.md or always-loaded rules files — not in subdirectory CLAUDE.md files — to survive /compact reliably. If a rule only loads when Claude touches a specific subdir, it won't be in context after /compact unless Claude touches that subdir again.
Long-session degradation
In very long sessions (100k+ tokens of conversation), even rules that loaded at session start can lose effectiveness as they move further back in context. Signs:
- •Claude starts ignoring rules it was following earlier
- •Errors that were absent early in the session reappear
Fix: Use /compact proactively before context degrades. Or /clear to start fresh (re-reads all CLAUDE.md files). The shorter and more targeted the CLAUDE.md, the longer adherence holds.
Behavioral Layer — Karpathy Guardrails
<!-- This is the layer clad-md-skill v1/v2 lacked. --> <!-- Derived from Andrej Karpathy's documented observations on LLM coding failure modes. --> <!-- Embed in CLAUDE.md when user reports these failure patterns, or proactively when relevant. -->
The four principles below fix the most common, most costly Claude Code failure modes. They are behavioral — not project-specific. They belong either in the project's root CLAUDE.md (permanent, shared) or in ~/.claude/CLAUDE.md (user-level, all projects).
When to embed: When the user reports (or audit reveals) any of: unrequested features, drive-by refactoring, silent wrong assumptions, vague task completion, or Claude not stopping when confused.
How to embed: Add as a section called ## Behavior in CLAUDE.md. Short form or long form (see below). The long form is for projects where these failures have occurred repeatedly. The short form for all others.
Short Form (embed as-is — ~20 lines, ~300 tokens)
## Behavior
**Before implementing anything:**
- State assumptions explicitly. If uncertain, ask — don't guess and run.
- If multiple interpretations exist, present them; don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
**While implementing:**
- Minimum code that solves the problem. No unrequested features, abstractions, or "flexibility."
- Touch only what the task requires. Don't improve adjacent code, comments, or formatting.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it — don't delete it.
**When verifying:**
- Transform tasks into verifiable goals: "Fix the bug" → "Reproduce in a test, then fix."
- For multi-step tasks, state a plan with explicit verify steps before starting.
- Every changed line must trace directly to the user's request.Long Form (for projects with repeated behavioral failures — ~35 lines, ~500 tokens)
## Behavior
### 1. Think before coding
- State assumptions explicitly before implementing. If uncertain, ask.
- If multiple interpretations exist, present them all — don't pick silently.
- If a simpler approach exists, say so. Push back when warranted.
- If something is unclear, stop. Name what's confusing. Ask.
### 2. Simplicity first
- Minimum code that solves the problem. Nothing speculative.
- No features beyond what was asked.
- No abstractions for single-use code.
- No "flexibility" or "configurability" that wasn't requested.
- No error handling for impossible scenarios.
- If 200 lines could be 50, flag it and ask before writing 200.
### 3. Surgical changes
- Touch only what the task requires. Don't "improve" adjacent code, comments, or formatting.
- Don't refactor things that aren't broken.
- Match existing style, even if you'd do it differently.
- If you notice unrelated dead code, mention it — don't delete it.
- When your changes make something unused: remove ONLY what YOUR changes orphaned.
### 4. Goal-driven execution
- Transform tasks into verifiable goals: "Add validation" → "Write tests for invalid inputs, then make them pass."
- For multi-step tasks, state a plan before starting: each step with an explicit verify check.
- Strong success criteria let you loop independently. Weak criteria require constant clarification — ask before starting.
- Every changed line must trace directly to the user's request.Which principle fixes which failure?
| Failure | Root cause | Guardrail |
|---|---|---|
| Claude added features nobody asked for | Over-engineering | Simplicity first |
| Claude refactored code while fixing a different bug | Surgical sprawl | Surgical changes |
| Claude assumed wrong scope and ran with it | Silent assumptions | Think before coding |
| Claude said "done" but the task wasn't verified | Weak success criteria | Goal-driven execution |
| Claude changed code style while adding a feature | Style drift | Surgical changes |
| Claude built an abstraction for one use case | Premature abstraction | Simplicity first |
| Claude didn't ask when there were two valid interpretations | Hidden ambiguity | Think before coding |
Output Rules (Apply to All Generated Content)
- Concrete > vague. "Use 2-space indentation" — not "Format properly."
- Imperative voice for rules. "Use X" — not "You should probably use X."
- Pair NEVER with an alternative. "Never use any; prefer unknown with type guards." Bare prohibitions cause Claude to halt or guess.
- Reserve IMPORTANT / YOU MUST for ≤5 genuinely critical rules. Overuse dilutes effect to zero.
- No prose explanations of WHY in CLAUDE.md — Claude doesn't need the rationale to follow the rule.
- Reference, don't embed. Pointer text for large docs;
@-importonly for small companion files that genuinely belong inline. - Markdown structure — headers + bullets. Claude scans structure the way humans scan documentation.
- Consistency across files — when the user has multiple loaded sources, surface conflicts.
- No hedges. "Try to use" → "Use". "When possible" → remove. "Generally" → remove.
Quality Gate (Before Delivering)
- •[ ] Every rule passes the Verifiability Test
- •[ ] All NEVER / prohibition rules paired with alternatives
- •[ ] No conflicts within the file or with referenced files
- •[ ] Total file ≤ 200 lines (hard ceiling: 300)
- •[ ] IMPORTANT / YOU MUST used sparingly (max 3–5 per file)
- •[ ] Path-specific rules moved to
.claude/rules/withpaths:frontmatter — not in root CLAUDE.md - •[ ] Large docs referenced via pointer text only — not embedded or
@-imported - •[ ] Critical rules in root CLAUDE.md or always-loaded rules — not in subdirectory CLAUDE.md files
- •[ ] Every-session token budget calculated (target: under 2,000 tokens total across all loaded sources)
- •[ ] Behavioral guardrails present if project has recurring LLM behavior failures
- •[ ] Behavioral guardrails use short form unless long form is warranted
- •[ ] Maintainer comment
<!-- Last reviewed: [date] -->at top of file - •[ ] Run
/memoryto confirm all expected sources are loaded before testing
If any check fails — fix before presenting.
Common Questions (Quick Answers)
- •"Should I use AGENTS.md or CLAUDE.md?" Claude Code only reads CLAUDE.md. If a repo has AGENTS.md for other tools, put
@AGENTS.mdat the top of CLAUDE.md and add Claude-specific rules below. - •"Will @-imports save context?" No. Imports are inlined at launch. Use
.claude/rules/withpaths:frontmatter to actually reduce per-session tokens. - •"My rules conflict with auto memory — what wins?" Both load as context. Claude may pick arbitrarily. Resolve conflicts by editing one or the other.
- •"Why isn't Claude following my CLAUDE.md?" Run
/memoryto confirm it's loaded. If loaded but ignored: file is likely too long, or the rule is vague (fails Verifiability Test). - •"What about CLAUDE.local.md?" Personal project notes, gitignored, loaded same as CLAUDE.md. Use it for credentials, personal dev preferences, notes you don't want in git.
- •"Why does Claude keep adding code I didn't ask for?" Silent assumptions + over-engineering. Embed the Karpathy
## Behaviorsection (short form). Specifically: Think before coding + Simplicity first. - •"Why does Claude reformat things I didn't ask it to touch?" Surgical sprawl. Embed Surgical Changes guardrail.
- •"How short can my CLAUDE.md be?" As short as it needs to be. A 20-line CLAUDE.md that actually works beats a 300-line one Claude ignores.
- •"What are `.claude/settings.json` hooks for?" Lifecycle scripts that run shell commands at key points (SessionStart, PreToolUse, etc.). Common use: auto-generating knowledge graph files so Claude always has fresh cross-reference data. Define in
settings.json; reference the hook scripts in CLAUDE.md so Claude knows what they produce. - •"How do I reduce tokens loaded every session?" Three levers: (1) Keep root CLAUDE.md under 200 lines. (2) Move path-specific rules to
.claude/rules/<topic>.mdwithpaths:frontmatter — they load on-demand instead of every session. (3) Use pointer text for large docs instead of@-importsor embedding. - •"Claude follows rules early in the session but ignores them later." Context window pressure — rules move further back as conversation grows. Use
/compactproactively. Keep CLAUDE.md short. Critical rules should be near the top of the file. - •"After `/compact`, Claude forgot rules it was following." Rules in subdirectory
CLAUDE.mdfiles don't survive/compact— they only reload on-demand when Claude touches that subdir again. Move critical rules to root CLAUDE.md or always-loaded.claude/rules/files. - •"What's the difference between `/compact` and `/clear`?"
/compactsummarizes the conversation and keeps going — CLAUDE.md files reload./clearwipes the session entirely and starts fresh — everything reloads from scratch. Use/clearwhen context is deeply confused;/compactfor routine context pruning. - •"How do I know if my CLAUDE.md is actually being followed?" Three checks: (1) Run
/memory— confirm the file is loaded. (2) Ask Claude to repeat a specific rule back to you ("what's the branch naming convention here?") — if it can't, the rule is too buried or too vague. (3) Give Claude a task that would trigger the rule and check the output. If it fails despite the file loading, run AUDIT mode — the rule likely fails the Verifiability Test. - •"Should CLAUDE.md be committed to git?" Root CLAUDE.md yes — it's team-shared instructions. CLAUDE.local.md no — gitignore it (personal preferences, credentials, local paths).
.claude/settings.local.jsonno — gitignore it (personal overrides)..claude/settings.jsonand.claude/rules/*.mdyes — they're team-shared.
Reference Files
- •
references/format-rules.md— Phrasing patterns, rewrites, token-saving techniques - •
references/antipatterns.md— 16 documented failure modes with concrete examples (12 architecture, 4 behavioral) - •
references/examples.md— Annotated good/bad CLAUDE.md examples, path-scoped architecture, full behavioral layer example - •
references/behavioral-audit.md— Deep-dive audit checklist for catching Karpathy failure modes
For context management guidance, see the ## Context Management section in this file.
Install & Usage
mkdir -p .claude/skillsmkdir -p .claude/skills && curl -o .claude/skills/claude-md-skill-v3.md https://raw.githubusercontent.com/fiazrf/claude-md-skill-v3/main/SKILL.md/claude-md-skill-v3Security Audits
Frequently Asked Questions
What is claude-md-skill-v3?
Use when the user asks to write, audit, improve, split, or fix a CLAUDE.md file or the .claude/ memory system. Also use for: "why does Claude keep over-engineering", "how do I stop Claude touching unrelated code", "Claude ignores my rules", "set up Claude Code memory", "my CLAUDE.md is too long", "split my CLAUDE.md", "what should go in CLAUDE.md", "should I use AGENTS.md", context management, token budget, what loads at session start, rules stopping working mid-session, or anything about .claude/rules/ or @-imports.
How to install claude-md-skill-v3?
To install claude-md-skill-v3: create the skills directory (mkdir -p .claude/skills), then run: mkdir -p .claude/skills && curl -o .claude/skills/claude-md-skill-v3.md https://raw.githubusercontent.com/fiazrf/claude-md-skill-v3/main/SKILL.md. Finally, /claude-md-skill-v3 in Claude Code.
What is claude-md-skill-v3 best for?
claude-md-skill-v3 is a skill categorized under General. It is designed for: agent. Created by fiazrf.