BeClaude

claude-md-skill-v3

New
GitHub TrendingGeneralby fiazrf

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.

First seen 5/24/2026

Overview

CLAUDE.md Skill v3

Expert guidance for the Claude Code memory system. Synthesizes:

  1. Anthropic's official CLAUDE.md architecture — file locations, scoping, token economics, import behavior, path-scoped rules
  2. 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.

  1. System prompt (Anthropic-controlled, cannot be changed)
  2. ~/.claude/CLAUDE.md — user-level, applies to all projects
  3. Project root CLAUDE.md or .claude/CLAUDE.md — shared via git
  4. CLAUDE.local.md — personal project notes, gitignored
  5. .claude/rules/*.md without paths: — every session
  6. All @-imports from the above — inlined at load time, same as embedding
  7. <subdir>/CLAUDE.md files — on-demand only when Claude reads files there
  8. .claude/rules/*.md with paths: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 /memory to 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.md files 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 /memory command. 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.md at 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

LocationScopeLoaded
./CLAUDE.md or ./.claude/CLAUDE.mdProject (team-shared via git)Every session
./CLAUDE.local.mdPersonal project notes (gitignored)Every session
~/.claude/CLAUDE.mdUser-level (all projects)Every session
<subdir>/CLAUDE.mdSubdirectoryOn-demand when Claude reads files there
.claude/rules/*.md (no paths:)Project rulesEvery session
.claude/rules/*.md (with paths:)Path-scoped rulesOnly when Claude reads matching files
Managed policy paths (OS-specific)Org-wideEvery 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 signalMode
"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:

  1. Project name + one-line purpose
  2. Tech stack (languages, frameworks, key libraries)
  3. Mistakes Claude has made or is likely to make in this codebase
  4. Hard constraints (security, compliance, branch rules)
  5. Non-obvious commands (skip standard ones — Claude knows npm test, cargo build)
  6. Whether this is a monorepo (affects nesting strategy)
  7. 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.

markdown
# [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/ or docs/

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>.md with paths: 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

code
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 session

REFINE Mode

Run AUDIT internally first. Then apply rewrites in this order:

  1. Resolve conflicts — pick one rule, delete the other
  2. Tighten phrasing

- Hedges → imperatives: "try to use" → "use" - Orphan prohibitions → prohibition + alternative: "Never X" → "Never X; do Y instead" - Vague rules → concrete and verifiable

  1. 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

  1. Embed behavioral guardrails if history shows repeated failure modes (see Behavioral Layer)
  2. Add emphasis to genuinely critical rules using IMPORTANT or YOU MUST. Max 3–5 total.
  3. Strip dead weight — outdated rules, duplicates, prose explanations Claude doesn't need
  4. 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

code
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 reference

Path-Scoped Rule Template

markdown
---
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 transitions

Decision Matrix

Rule characterBelongs in
Applies to every session, every fileCLAUDE.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-specificCLAUDE.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 claudeMdExcludes in .claude/settings.local.json to 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:

FilePurpose
.claude/settings.jsonShared project settings (hooks, permissions) — commit to git
.claude/settings.local.jsonPersonal 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:

json
{
  "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:

FailurePrincipleWhat to embed
Added unrequested features or abstractionsSimplicity firstShort form or targeted Simplicity rule
Touched code not related to the taskSurgical changesShort form or targeted Surgical rule
Assumed scope and ran with itThink before codingShort form or targeted Think rule
Declared done without verifyingGoal-driven executionShort 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 ## Behavior section to root CLAUDE.md
  • All projects: Add to ~/.claude/CLAUDE.md instead — 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

SymptomRoot causeFix
Claude ignores rules from the startFile too long OR rule too vagueAUDIT the file; apply 6 tests
Claude follows rules early, ignores laterLong-session degradationUse /compact proactively; shorten file
Rules disappeared after /compactRules were in subdirectory CLAUDE.mdMove to root CLAUDE.md or always-loaded rules
Session starts slow / feels heavyToo many always-loaded sourcesRun budget worksheet; move to path-scoped rules
Rules conflict with each otherMultiple loaded sources contradictRun /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 /compact earlier
  • 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.

SectionTypical costBudget
Header + stack line3–5 linesAlways
Commands4–8 linesOnly non-obvious ones
Architecture4–8 linesOnly non-inferable rules
Code Style4–6 linesOnly what differs from Claude defaults
Workflow3–5 linesOnly project-specific steps
Constraints3–5 linesHard limits only, max 5 IMPORTANT
Glossary3–8 linesProject-specific terms only
Behavior10–20 linesShort form unless failures are recurring
Reference Docs3–5 linesPointer text only
Total target~40–70 linesNever 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:

code
- Full spec: `docs/spec.md` — read when modifying the UI or adding features
- DB schema: `docs/schema.md` — read before any DDL or query work

Claude 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:

code
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:

  1. Identify the largest loaded source (usually root CLAUDE.md or always-loaded rules files)
  2. Run the 6 AUDIT tests on it — most oversized files have 30–50% deletable lines
  3. Move path-specific sections to .claude/rules/<topic>.md with paths: frontmatter (ARCHITECT mode)
  4. Replace embedded docs with pointer text references
  5. Move behavioral guardrails to ~/.claude/CLAUDE.md if 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 /compactDoes 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)

markdown
## 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)

markdown
## 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?

FailureRoot causeGuardrail
Claude added features nobody asked forOver-engineeringSimplicity first
Claude refactored code while fixing a different bugSurgical sprawlSurgical changes
Claude assumed wrong scope and ran with itSilent assumptionsThink before coding
Claude said "done" but the task wasn't verifiedWeak success criteriaGoal-driven execution
Claude changed code style while adding a featureStyle driftSurgical changes
Claude built an abstraction for one use casePremature abstractionSimplicity first
Claude didn't ask when there were two valid interpretationsHidden ambiguityThink before coding

Output Rules (Apply to All Generated Content)

  1. Concrete > vague. "Use 2-space indentation" — not "Format properly."
  2. Imperative voice for rules. "Use X" — not "You should probably use X."
  3. Pair NEVER with an alternative. "Never use any; prefer unknown with type guards." Bare prohibitions cause Claude to halt or guess.
  4. Reserve IMPORTANT / YOU MUST for ≤5 genuinely critical rules. Overuse dilutes effect to zero.
  5. No prose explanations of WHY in CLAUDE.md — Claude doesn't need the rationale to follow the rule.
  6. Reference, don't embed. Pointer text for large docs; @-import only for small companion files that genuinely belong inline.
  7. Markdown structure — headers + bullets. Claude scans structure the way humans scan documentation.
  8. Consistency across files — when the user has multiple loaded sources, surface conflicts.
  9. 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/ with paths: 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 /memory to 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.md at the top of CLAUDE.md and add Claude-specific rules below.
  • "Will @-imports save context?" No. Imports are inlined at launch. Use .claude/rules/ with paths: 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 /memory to 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 ## Behavior section (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>.md with paths: frontmatter — they load on-demand instead of every session. (3) Use pointer text for large docs instead of @-imports or embedding.
  • "Claude follows rules early in the session but ignores them later." Context window pressure — rules move further back as conversation grows. Use /compact proactively. 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.md files 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`?" /compact summarizes the conversation and keeps going — CLAUDE.md files reload. /clear wipes the session entirely and starts fresh — everything reloads from scratch. Use /clear when context is deeply confused; /compact for 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.json no — gitignore it (personal overrides). .claude/settings.json and .claude/rules/*.md yes — 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

1
Create the skills directory
mkdir -p .claude/skills
2
Download the skill file
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
3
Invoke in Claude Code
/claude-md-skill-v3
View source on GitHub
agent

Security Audits

LicenseUnknownSourceWarnRepositoryPass

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.