AgentSkillsCN

claude-md

管理 CLAUDE.md 文件。审计、审查、改进、重构并生成子目录上下文。发现所有 CLAUDE.md 文件,依据研究支持的标准评估其质量,生成改进建议,针对性地进行更新,采用渐进式披露的方式重组内容,并为那些受益于即时上下文的目录创建情境化的 CLAUDE.md 文件。当用户说“审计 CLAUDE.md”、“审查我的规则”、“改进说明”、“整理 Claude 配置”、“生成子目录上下文”,或“维护 CLAUDE.md”时使用此技能。

SKILL.md
--- frontmatter
name: claude-md
description: Manages CLAUDE.md files. Audits, reviews, improves, refactors, and generates subdirectory context. Discovers all CLAUDE.md files, evaluates quality against research-backed criteria, generates improvement reports, applies targeted updates, restructures using progressive disclosure, and creates contextual CLAUDE.md files for directories that benefit from instant context. Use when the user says "audit CLAUDE.md", "review my rules", "improve instructions", "organize Claude config", "generate subdirectory context", or "CLAUDE.md maintenance".
allowed-tools: Read, Glob, Grep, Bash, Edit
license: MIT
context: fork
agent: general-purpose
<!-- v1.1.0 | 2026-02-09 -->

Claude MD

Complete CLAUDE.md management: Audit, Review, Improve, and Refactor. Core insight: rules with reasoning outperform bare rules—models generalize from "why" explanations.


Quick Reference

ModeWhen to UseOutput
Audit"Audit CLAUDE.md", "Check all my rule files"Discovery + quality scores for all files
Review"Review my CLAUDE.md", "Check instruction quality"Detailed quality report + improvement suggestions
Improve"Improve my rules", "Fix my CLAUDE.md"Targeted updates with diffs
Refactor"Organize Claude config", "Split CLAUDE.md"Restructured files with progressive disclosure
Generate"Generate subdirectory context", "Create package CLAUDE.md files"New CLAUDE.md files for directories that need context

Mode Sequencing

Modes can be combined in workflows:

SequenceWhen to Use
Audit → GenerateAudit finds gaps in subdirectory coverage → Generate creates missing files
Audit → Review → ImproveFull assessment → quality check → targeted fixes
Generate → ReviewCreate new files → verify quality meets standards
Improve → RefactorFix issues → restructure if still bloated

Generate as follow-up: After running Audit, if subdirectories lack context files, Generate mode can create them. Generate reuses Phase 1 discovery if Audit was already run in the same session.


Workflow Overview

<instructions>

Phase 1: Discovery

Find all CLAUDE.md files in the repository:

bash
find . -name "CLAUDE.md" -o -name ".claude.md" -o -name ".claude.local.md" 2>/dev/null | head -50

File Types & Locations:

TypeLocationPurpose
Project root./CLAUDE.mdPrimary project context
Local overrides./.claude.local.mdPersonal/local settings (gitignored)
Global defaults~/.claude/CLAUDE.mdUser-wide defaults across all projects
Package-specific./packages/*/CLAUDE.mdModule-level context in monorepos
SubdirectoryAny nested locationFeature/domain-specific context
Rules directory./.claude/rules/*.mdAuto-loaded detailed rules
Reference docs./.claude/reference/*.mdLarge docs (NOT auto-loaded)

Note: Claude auto-discovers CLAUDE.md files in parent directories, making monorepo setups work automatically.

Phase 2: Quality Assessment

For each CLAUDE.md file, evaluate against quality criteria.

Quick Assessment Checklist (100 points total):

CriterionPointsCheck
Commands/workflows12Are build/test/deploy commands present?
Architecture clarity12Can Claude understand the codebase structure?
Non-obvious patterns10Are gotchas and quirks documented?
Conciseness8No verbose explanations or obvious info?
Currency8Does it reflect current codebase state?
Content Quality50See sub-criteria below

Content Quality Sub-Criteria (50 points):

Sub-criterionPointsCheck
Reasoning presence15Do rules explain "why"? Hybrid style: "Prefer X—it provides Y"
Actionability10No vague language without defaults? Executable instructions?
Degrees of freedom10Rigid for safety, flexible for style? Matches consequence?
Options discipline5Default + escape hatch? Max 3 alternatives?
AI-optimized format10Tables, examples, code blocks over prose walls?

Quality Grades:

  • A (90-100): Comprehensive, current, actionable
  • B (70-89): Good coverage, minor gaps
  • C (50-69): Basic info, missing key sections
  • D (30-49): Sparse or outdated
  • F (0-29): Missing or severely outdated

Rule Quality Dimensions (for Review mode):

DimensionScoreCriteriaApplies To
Reasoning0-30=no why, 1=some, 2=most, 3=all have reasoningRules, Patterns, Conventions only
Specificity0-30=vague, 1=mixed, 2=mostly specific, 3=all actionableRules, Patterns, Gotchas
Positive framing0-30=all negative, 1=mostly negative, 2=mixed, 3=mostly positiveRules only
Examples0-20=none, 1=some, 2=good/bad examplesComplex rules/patterns
Structure0-20=prose wall, 1=basic headers, 2=tables/hierarchyAll content
Conflicts0/-30=none, -1 per conflict foundAll content

What needs reasoning vs what doesn't:

Section TypeNeeds Reasoning?Example
Context/DescriptionNo"Stripe integration for subscriptions" — factual
Key FilesNo"stripe.ts - Stripe client" — factual
ArchitectureNoDirectory structure — factual
CommandsNo"pnpm test" — executable
Rules/Hard RulesYes"Never commit secrets — in history forever"
Patterns/ConventionsYes"One route per file — keeps routing predictable"
GotchasSometimesOnly if non-obvious why it's a gotcha

Phase 3: Quality Report Output

Output the quality report before making any updates.

Report Format:

<example> ```markdown ## CLAUDE.md Quality Report

Summary

  • Files found: X
  • Average score: X/100
  • Files needing update: X

File-by-File Assessment

1. ./CLAUDE.md (Project Root)

Score: XX/100 (Grade: X)

CriterionScoreNotes
Commands/workflowsX/12...
Architecture clarityX/12...
Non-obvious patternsX/10...
ConcisenessX/8...
CurrencyX/8...
Content QualityX/50...

Content Quality breakdown:

Sub-criterionScore
Reasoning presenceX/15
ActionabilityX/10
Degrees of freedomX/10
Options disciplineX/5
AI-optimized formatX/10

Issues:

  • [List specific problems]

Recommended additions:

  • [List what should be added]
code
</example>

### Phase 4: Issue Detection (Review Mode)

**Check rules and patterns for:** (not factual context sections)

| Issue Type | Detection | Example Problem | Applies To |
|------------|-----------|-----------------|------------|
| **Missing reasoning** | No "why", "because", explanation | "Never use any" (why?) | Rules, Patterns |
| **Vague instruction** | Not actionable, no concrete guidance | "Write clean code" | Rules, Patterns |
| **Negative-only framing** | "Don't", "Never", "Avoid" without positive alternative | "Don't hardcode URLs" | Rules only |
| **No examples** | Abstract rule without concrete illustration | Complex patterns need examples | Complex rules |
| **Conflicts** | Two rules that contradict | "Use Jest" + "Use Vitest" | All |
| **Redundant** | Duplicates another rule | Same instruction in two places | All |
| **Obvious** | Model does this without instruction | "Use correct syntax" | Rules |
| **Stale commands** | Build commands that no longer work | Outdated paths or scripts | Commands |
| **Missing dependencies** | Required tools not mentioned | Setup requirements omitted | Environment |

**Do NOT flag as issues:**
- Context sections without "why" (factual descriptions don't need reasoning)
- Key Files without explanations (file path + purpose is sufficient)
- Architecture sections without justification (structure is factual)

### Phase 5: Targeted Updates (Improve Mode)

After outputting the quality report, ask user for confirmation before updating.

**Update Guidelines (Critical):**

1. **Propose targeted additions only** - Focus on genuinely useful info:
   - Commands or workflows discovered during analysis
   - Gotchas or non-obvious patterns found in code
   - Package relationships that weren't clear
   - Testing approaches that work
   - Configuration quirks

2. **Keep it minimal** - Avoid:
   - Restating what's obvious from the code
   - Generic best practices already covered
   - One-off fixes unlikely to recur
   - Verbose explanations when a one-liner suffices

3. **Show diffs** - For each change, show:
   - Which CLAUDE.md file to update
   - The specific addition (as a diff or quoted block)
   - Brief explanation of why this helps future sessions

**Diff Format:**

<example>
```markdown
### Update: ./CLAUDE.md

**Why:** Build command was missing, causing confusion about how to run the project.

```diff
+ ## Quick Start
+
+ ```bash
+ npm install
+ npm run dev  # Start development server on port 3000
+ ```
code
</example>

### Phase 6: Refactoring (Refactor Mode)

For bloated files, restructure using progressive disclosure.

**Triage Assessment:**

| Signal | Score |
|--------|-------|
| Already uses `.claude/rules/` structure | +2 |
| Has clear hierarchy (headers, tables) | +1 |
| Contains reasoning ("why" explanations) | +1 |
| Rules are actionable and specific | +1 |
| Under 200 lines with dense content | +1 |
| Over 300 lines | -1 |
| Wall-of-text without structure | -2 |
| Contains contradictions | -2 |
| Mix of vague and specific rules | -1 |

| Score | Action |
|-------|--------|
| 4+ | **Skip** — already well-organized |
| 2-3 | **Light** — extract verbose sections |
| 0-1 | **Standard** — full refactoring |
| Negative | **Deep** — significant restructuring |

**Keep in root (high-value, frequently referenced):**

| Category | Example | Why Keep |
|----------|---------|----------|
| Project description | "React dashboard for analytics" | Sets context for all tasks |
| Commands | `pnpm build`, `pnpm test` | Used every session |
| Hard rules with reasoning | "Never commit secrets — in git history forever" | Safety reinforcement |
| Core principles (3-5) | "Type safety first", "Test behavior not implementation" | Philosophy that guides decisions |
| Priority hierarchy | "Safety > Core Principles > Style" | Conflict resolution |
| Critical @rules references | `@rules/safety.md` | Loads detailed content |

**Extract to `.claude/rules/` (detailed, topic-specific):**
- Detailed language conventions with examples
- Extensive testing patterns
- Framework-specific guidance
- Comprehensive workflow documentation
- Reference tables and checklists

**Output structure:**

project-root/ ├── CLAUDE.md # High-value content with @references └── .claude/ ├── rules/ # Auto-loaded by Claude Code │ ├── coding.md │ ├── testing.md │ ├── workflow.md │ └── safety.md └── reference/ # NOT auto-loaded (search-triggered) └── patterns.md

code

### Phase 7: Apply Updates

After user approval, apply changes using the Edit tool. Preserve existing content structure.

### Mode: Generate (Create Subdirectory Context)

**Triggers:** "Generate subdirectory context", "Create CLAUDE.md for packages", "Add directory context files"

#### Phase G1: Directory Discovery

**If Audit was run first:** Reuse Phase 1 discovery results — no need to rescan.

**Otherwise:** Scan project structure to identify candidate directories:

```bash
find . -type d -not -path '*/\.*' -not -path '*/node_modules/*' -not -path '*/dist/*' -not -path '*/__pycache__/*' -not -path '*/build/*' -not -path '*/coverage/*' | head -100

Skip directories: .git, node_modules, dist, build, coverage, __pycache__, .next, .nuxt, vendor

Phase G2: Directory Scoring

For each directory, calculate a "needs context" score:

SignalScoreDetection
File count >15+3`ls -1
Has index/entry file+2index.ts, main.py, mod.rs exists
Non-obvious naming+2Abbreviations, domain jargon, single letters
Deep nesting (>3 levels)+1Path depth from root
Has existing config+1tsconfig.json, package.json, .env.example
Is monorepo package+3Under packages/, apps/, services/
Has README+1Existing documentation to extract from
Already has CLAUDE.md-10Skip if exists
Standard framework dir-5node_modules, dist, .git, __pycache__
Shallow with few files-2<5 files, no nesting — not complex enough

Threshold:

  • Score >= 6: High priority — generate with full content
  • Score 4-5: Medium priority — generate minimal file
  • Score < 4: Skip — directory is self-explanatory

Phase G3: Content Extraction

For each candidate directory, extract:

  1. Purpose: From README, package.json description, or top-level comments
  2. Key files: Entry points, configs, main exports
  3. Patterns: Common conventions visible in file structure
  4. Dependencies: Internal imports to other project directories
  5. Gotchas: Non-obvious from naming alone

Phase G4: Preview Generation

Generate preview of proposed CLAUDE.md files. Present to user:

markdown
## Proposed Subdirectory CLAUDE.md Files

### 1. src/api/CLAUDE.md (Score: 7)
**Reason:** 23 files, has index.ts, API domain

**Content:**
# API Layer

@../CLAUDE.md

## Context
Express routes with Zod validation. All routes require auth middleware.

## Key Files
- `index.ts` - Route registration
- `middleware/auth.ts` - JWT validation

## Patterns
- One route file per resource — keeps routing predictable
- Validation schemas co-located with routes — easier to maintain

## Gotchas
- Rate limiting applies per-user, not per-IP

---

### 2. packages/shared/CLAUDE.md (Score: 6)
**Reason:** Monorepo package, 18 files
...

Phase G5: User Approval

Never create files without user confirmation.

Present options:

  1. Approve all proposed files
  2. Select specific files to create
  3. Request modifications before creation
  4. Cancel generation

Phase G6: File Creation

After approval, create files using Write tool. Verify each file:

  • Starts with @../CLAUDE.md to inherit parent context
  • Under 500 tokens (target 150-300)
  • Follows generated template from references/templates.md
  • No duplicate info from root CLAUDE.md
  • Specific to directory, not generic advice

See references/generation-workflow.md for detailed scoring algorithm and extraction heuristics.

</instructions>

References

FilePurpose
references/research-principles.mdAnthropic and academic research findings on reasoning vs rules
references/rule-quality-standards.mdHybrid format, transformation examples, positive reframing, preservation rules
references/quality-criteria.md100-point scoring rubric and rule quality dimensions
references/templates.mdCLAUDE.md templates for root, subfolder, monorepo, and rule files
references/examples.mdBefore/after refactoring transformations
references/anti-patterns.mdCommon mistakes to avoid when writing CLAUDE.md files
references/user-tips.mdShortcuts and features to share with users
references/execution-checklists.mdMode-specific progress checklists (Audit, Review, Improve, Refactor, Generate)
references/generation-workflow.mdDetailed Generate mode scoring algorithm and extraction heuristics
references/subfolder-examples.mdReal-world subfolder CLAUDE.md examples
references/update-guidelines.mdWhat to add vs what to skip when updating CLAUDE.md files
references/changelog.mdVersion history and update protocol