Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

feat: overhaul memory-manager — three-layer audit, quality scoring, project detection

Jez01b6ff9ae2a4
diff --git a/skills/memory-manager/SKILL.md b/skills/memory-manager/SKILL.md
index 4414c7b1..b6bf69f7 100644
--- a/skills/memory-manager/SKILL.md
+++ b/skills/memory-manager/SKILL.md
@@ -1,135 +1,169 @@
---
name: memory-manager
-description: >
- Manage CLAUDE.md memory hierarchy across repositories. Audit for bloat, split
- oversized files into topic-specific sub-files, create directory-level CLAUDE.md
- files, and verify the hierarchy loads correctly. Use when CLAUDE.md exceeds
- 100 lines, when a directory needs its own context, or when project memory
- needs restructuring.
+description: "Audit, restructure, and maintain the full Claude Code memory hierarchy: CLAUDE.md files, .claude/rules/ topic files, auto-memory, and project documentation. Detects project type and suggests appropriate docs. Use when CLAUDE.md needs updating, memory needs restructuring, or a project needs its docs audited. Trigger with 'audit memory', 'update CLAUDE.md', 'restructure memory', 'session capture', 'memory cleanup', 'check project docs', or 'what docs does this project need'."
compatibility: claude-code-only
---
# Memory Manager
-Audit and restructure the CLAUDE.md memory hierarchy in a repository. Produces a clean, well-organised set of CLAUDE.md files that follow size guidelines and progressive disclosure.
+Manage the full Claude Code memory hierarchy across three layers. Produces well-organised, correctly-placed memory files that follow size guidelines and progressive disclosure.
-## How CLAUDE.md Loading Works
+## Three Memory Layers
-Claude Code loads CLAUDE.md from the current working directory AND all parent directories. Deeper files take precedence. This means:
+| Layer | Location | Purpose | Managed by this skill |
+|-------|----------|---------|----------------------|
+| CLAUDE.md hierarchy | `./CLAUDE.md`, subdirs, parent dirs | Project context, commands, architecture, rules | Yes |
+| Rules topic files | `.claude/rules/*.md` | Correction rules, patterns, technical facts | Yes |
+| Auto-memory | `~/.claude/projects/*/memory/MEMORY.md` | Session-specific patterns | No (Claude manages automatically) |
-- `~/CLAUDE.md` — global context (always loaded)
-- `~/project/CLAUDE.md` — project context
-- `~/project/src/CLAUDE.md` — src-specific context
-- `~/project/src/api/CLAUDE.md` — api-specific context
+## Operating Modes
-All four load when working in `src/api/`. Use this hierarchy to keep each file small and focused.
+### Mode 1: Session Capture
-## Workflow
+**When**: End of session, "capture learnings", "update CLAUDE.md with what we learned"
-### Step 1: Audit current state
+1. Review the conversation for discoveries worth preserving:
+ - Commands that worked (or didn't)
+ - Gotchas and workarounds found
+ - Architecture decisions made
+ - Configuration quirks discovered
+ - Patterns that would help future sessions
+2. Categorise each discovery using the placement decision tree below
+3. Draft all changes as diffs in a single batch
+4. Present the batch — apply after a single yes/no confirmation
-Run the audit script to get a size report:
+**Keep it concise**: one line per concept. No verbose explanations, no generic advice.
-```bash
-python3 skills/memory-manager/scripts/audit_memory.py [repo-path]
-```
-
-This reports:
-- All CLAUDE.md files with line counts
-- Files exceeding size targets
-- Directories that might benefit from their own CLAUDE.md
-- Content that could be split into topic files
-
-### Step 2: Identify splits
-
-For each oversized CLAUDE.md, identify sections that can become:
-
-1. **Directory-level CLAUDE.md** — context specific to that directory
-2. **Topic files in `.claude/rules/`** — correction rules and patterns
-3. **Deletable content** — duplicates parent, states the obvious, or Claude already knows
-
-**Size targets:**
-- Root CLAUDE.md: 50–150 lines (project identity, key commands, architecture)
-- Sub-directory CLAUDE.md: 20–50 lines (integrations, gotchas, commands)
-- Topic files in rules/: 20–80 lines each
-
-### Step 3: Create directory-level files
-
-For directories with external integrations, non-obvious config, or common gotchas, create a focused CLAUDE.md:
+### Mode 2: Full Audit
-```markdown
-# [Component Name]
+**When**: "audit memory", "check project docs", periodic maintenance, working in a neglected project
-## Key Integrations
-- **Service X**: endpoint, auth method, secret location
+1. Run the audit script:
+ ```bash
+ python3 skills/memory-manager/scripts/audit_memory.py [repo-path]
+ ```
+2. Review the output: sizes, quality scores, project type, missing docs, stale references
+3. Generate changes autonomously — create, update, or flag files as needed
+4. Present all changes as a single batch for approval
+5. Apply approved changes
-## Commands
-npm run deploy
-npm run test
-
-## Gotchas
-- Always run migrations before testing
+For large repos, delegate to a sub-agent:
+```
+Task(subagent_type: "general-purpose",
+ prompt: "Run python3 skills/memory-manager/scripts/audit_memory.py /path/to/repo
+ and summarise the findings.")
```
-**Don't create one when:**
-- Parent CLAUDE.md already covers it
-- The directory is simple/self-explanatory
-- Content would be fewer than 10 lines
+### Mode 3: Restructure
-### Step 4: Restructure root CLAUDE.md
+**When**: "restructure memory", root CLAUDE.md over 200 lines, first-time memory setup
-The root CLAUDE.md should contain ONLY:
+1. Run full audit (Mode 2) first
+2. Split oversized files:
+ - Extract topic sections from root CLAUDE.md into `.claude/rules/<topic>.md`
+ - Extract directory-specific content into sub-directory CLAUDE.md files
+3. Create missing documentation files based on project type
+4. Present the restructure plan, apply after approval
-- Project identity (what this is, who owns it)
-- Architecture overview (stack, key directories)
-- Essential commands (build, deploy, test)
-- Critical rules (things that break if forgotten)
-- Links to deeper docs
+## Placement Decision Tree
-Everything else moves to sub-directory files or `.claude/rules/`.
+```
+Would this still apply if I switched to a completely different project?
+├── YES → ~/.claude/rules/<topic>.md
+│ (correction rules, API patterns, coding standards)
+└── NO → Is it specific to a subdirectory?
+ ├── YES → <dir>/CLAUDE.md
+ │ (integrations, directory-specific gotchas)
+ └── NO → ./CLAUDE.md (project root)
+ (identity, stack, commands, architecture, critical rules)
+```
-### Step 5: Verify
+## Size Targets
-Re-run the audit script to confirm all files are within targets. Test by working in various directories and checking Claude has the right context.
+| File Type | Target | Maximum |
+|-----------|--------|---------|
+| Root CLAUDE.md | 50-150 lines | 200 |
+| Sub-directory CLAUDE.md | 15-50 lines | 80 |
+| Rules topic file | 20-80 lines | 120 |
-## Guidelines
+## What Belongs Where
-### What belongs in root CLAUDE.md
+### Root CLAUDE.md
- Project name, purpose, owner
- Tech stack summary
-- Key commands (build, deploy, test)
-- Critical "never do X" rules
+- Build/deploy/test commands (copy-paste ready)
- Directory structure overview
+- Critical "never do X" rules
+- Key integrations and secrets locations
-### What belongs in sub-directory CLAUDE.md
+### Sub-directory CLAUDE.md
- External service integrations for that component
-- Non-obvious configuration
+- Non-obvious configuration specific to this area
- Directory-specific commands
-- Common gotchas when working in that area
+- Gotchas when working in this directory
+
+**Don't create when**: parent covers it, directory is self-explanatory, content would be under 10 lines.
-### What belongs in .claude/rules/
-- Correction rules (bridging training cutoff)
-- Coding patterns specific to this project
+### .claude/rules/ topic files
+- Correction rules bridging training cutoff (e.g. API changes, deprecated patterns)
+- Coding patterns and standards
+- Platform-specific formatting rules
- Error prevention patterns
### What to delete
- Content Claude already knows from training
-- Verbose explanations of standard tools
-- Changelogs and version history
-- Duplicated content from parent files
+- Verbose explanations of standard frameworks
+- Changelogs or version history (use git)
+- Duplicated content from parent CLAUDE.md files
+- "TODO" items that were never completed
+- Generic advice not specific to the project
-## Delegation
+## Project Type Detection
-For large repos, delegate the audit to a sub-agent to preserve main context:
+The audit script detects project type from file presence and suggests appropriate documentation:
-```
-Task(subagent_type: "general-purpose",
- prompt: "Run python3 skills/memory-manager/scripts/audit_memory.py /path/to/repo
- and summarise the findings. List files over target size and suggest splits.")
-```
+| Indicator | Type | Suggested Docs |
+|-----------|------|---------------|
+| `wrangler.jsonc` / `wrangler.toml` | Cloudflare Worker | ARCHITECTURE.md |
+| `vite.config.*` + `.tsx` files | Vite/React | ARCHITECTURE.md |
+| `next.config.*` | Next.js | ARCHITECTURE.md |
+| MCP patterns in `src/index.ts` | MCP Server | ARCHITECTURE.md, API_ENDPOINTS.md |
+| `src/routes/` or `src/api/` | API Project | API_ENDPOINTS.md, DATABASE_SCHEMA.md |
+| Drizzle/Prisma config | Database | DATABASE_SCHEMA.md |
+
+All projects get CLAUDE.md. Additional docs only when the project type warrants them. See [references/project-types.md](references/project-types.md) for full detection heuristics and doc templates.
+
+## Autonomy Rules
+
+- **Just do it**: Run audit, detect project type, identify gaps, draft changes
+- **Brief confirmation**: Apply changes (single batch yes/no, not item-by-item)
+- **Ask first**: Delete existing content, major restructures (moving 50+ lines), create new project docs from scratch where there's ambiguity about content
+
+## Quality Scoring
+
+The audit script scores each CLAUDE.md on 6 criteria (100 points):
+
+| Criterion | Points | What it measures |
+|-----------|--------|-----------------|
+| Commands/Workflows | 20 | Build, test, deploy documented |
+| Architecture Clarity | 20 | Structure, relationships, entry points |
+| Non-Obvious Patterns | 15 | Gotchas, quirks, warnings |
+| Conciseness | 15 | Dense content, no filler |
+| Currency | 15 | References valid, commands work |
+| Actionability | 15 | Copy-paste ready, real paths |
+
+See [references/quality-criteria.md](references/quality-criteria.md) for the full rubric.
+
+## Reference Files
-The agent absorbs the verbose output and returns only actionable recommendations.
+| When | Read |
+|------|------|
+| Scoring CLAUDE.md quality | [references/quality-criteria.md](references/quality-criteria.md) |
+| Detecting project type and expected docs | [references/project-types.md](references/project-types.md) |
+| Creating new CLAUDE.md or rules files | [references/templates.md](references/templates.md) |
## Scripts
-- `scripts/audit_memory.py` — Scan repo for CLAUDE.md files, report sizes, suggest improvements
+- `scripts/audit_memory.py` — Scan all three layers, score quality, detect project type, flag issues
+ - `python3 audit_memory.py [repo-path]` — human-readable report
+ - `python3 audit_memory.py [repo-path] --json` — structured JSON output
diff --git a/skills/memory-manager/references/project-types.md b/skills/memory-manager/references/project-types.md
new file mode 100644
index 00000000..a31d83f5
--- /dev/null
+++ b/skills/memory-manager/references/project-types.md
@@ -0,0 +1,136 @@
+# Project Types
+
+Detect project type from file presence to determine which documentation files are expected. Only suggest docs that match — no enterprise bloat.
+
+## Detection Heuristics
+
+Check indicators in priority order (first match wins for primary type, but types can stack):
+
+| Indicator Files | Project Type |
+|----------------|-------------|
+| `wrangler.jsonc` or `wrangler.toml` | cloudflare-worker |
+| `vite.config.*` + `src/` with `.tsx` files | vite-react |
+| `vite.config.*` without React | vite-app |
+| `next.config.*` | nextjs |
+| `src/index.ts` + `FastMCP` or `McpAgent` imports | mcp-server |
+| `skills/` dir + SKILL.md files within | skills-repo |
+| `src/routes/` or `src/api/` or `app/api/` | api-project |
+| `drizzle.config.*` or `prisma/schema.prisma` or D1 bindings in wrangler | database-project |
+| `.claude/agents/` + operational scripts | claude-ops |
+| `package.json` only (generic Node) | node-project |
+| `pyproject.toml` or `setup.py` | python-project |
+
+**Stacking**: A Cloudflare Worker with D1 bindings is both `cloudflare-worker` and `database-project`. Union the expected docs.
+
+## Expected Documentation Per Type
+
+### All projects
+
+| Doc | Purpose |
+|-----|---------|
+| `CLAUDE.md` (root) | Project identity, stack, commands, critical rules |
+
+### cloudflare-worker
+
+| Doc | Purpose |
+|-----|---------|
+| `ARCHITECTURE.md` | Worker entry point, bindings, routes, middleware |
+
+### vite-react / nextjs
+
+| Doc | Purpose |
+|-----|---------|
+| `ARCHITECTURE.md` | Component tree, routing, state management, build pipeline |
+
+### mcp-server
+
+| Doc | Purpose |
+|-----|---------|
+| `ARCHITECTURE.md` | Server structure, tool registration, auth flow |
+| `API_ENDPOINTS.md` | Tool catalogue with parameters and return types |
+
+### api-project
+
+| Doc | Purpose |
+|-----|---------|
+| `API_ENDPOINTS.md` | Routes, methods, request/response schemas, auth requirements |
+| `DATABASE_SCHEMA.md` | Tables, relationships, indexes, migration workflow |
+
+### database-project
+
+| Doc | Purpose |
+|-----|---------|
+| `DATABASE_SCHEMA.md` | Tables, relationships, indexes, migration commands |
+
+### skills-repo
+
+| Doc | Purpose |
+|-----|---------|
+| Per-skill `SKILL.md` | Each skill directory needs its own SKILL.md |
+
+### claude-ops
+
+No additional docs beyond CLAUDE.md — operational repos are typically self-documenting through their agents and scripts.
+
+## Doc Templates
+
+### ARCHITECTURE.md outline
+
+```markdown
+# Architecture
+
+## Overview
+[One paragraph: what this project does and how it's structured]
+
+## Stack
+[Tech stack with versions]
+
+## Directory Structure
+[Tree with purpose annotations]
+
+## Key Flows
+[1-3 main data/request flows through the system]
+
+## Deployment
+[How to deploy, what happens on deploy]
+```
+
+### DATABASE_SCHEMA.md outline
+
+```markdown
+# Database Schema
+
+## Tables
+[Table per section: name, columns, types, constraints]
+
+## Relationships
+[Foreign keys, join patterns]
+
+## Migrations
+[How to create/run migrations, local vs remote]
+
+## Indexes
+[Non-obvious indexes and why they exist]
+```
+
+### API_ENDPOINTS.md outline
+
+```markdown
+# API Endpoints
+
+## Authentication
+[Auth method, where tokens come from]
+
+## Endpoints
+[Per endpoint: method, path, params, response shape, auth required]
+
+## Error Handling
+[Standard error format, common error codes]
+```
+
+## Rules
+
+- Only suggest docs that match detected project type
+- Simple projects (node-project, python-project) just need CLAUDE.md
+- Don't create empty template docs — only suggest when there's content to fill
+- Prefer one well-maintained doc over three sparse ones
diff --git a/skills/memory-manager/references/quality-criteria.md b/skills/memory-manager/references/quality-criteria.md
new file mode 100644
index 00000000..c28561f5
--- /dev/null
+++ b/skills/memory-manager/references/quality-criteria.md
@@ -0,0 +1,97 @@
+# Quality Criteria
+
+Score CLAUDE.md files on a 100-point scale across 6 criteria. Use this when running a full audit (Mode 2) or restructure (Mode 3).
+
+## Scoring Rubric
+
+### Commands/Workflows (20 points)
+
+Build, test, deploy, and dev commands documented with context.
+
+| Score | Meaning |
+|-------|---------|
+| 20 | All essential commands with context (when to use, flags) |
+| 15 | Most commands documented, some missing context |
+| 10 | Basic commands only (e.g. `npm run dev`) |
+| 5 | Few commands, no context |
+| 0 | None documented |
+
+### Architecture Clarity (20 points)
+
+Directory structure, module relationships, entry points, data flow.
+
+| Score | Meaning |
+|-------|---------|
+| 20 | Clear codebase map with relationships and entry points |
+| 15 | Good overview, minor gaps |
+| 10 | Basic directory listing only |
+| 5 | Vague or incomplete |
+| 0 | None |
+
+### Non-Obvious Patterns (15 points)
+
+Gotchas, quirks, edge cases, workarounds, "why" for unusual decisions.
+
+| Score | Meaning |
+|-------|---------|
+| 15 | Gotchas and quirks captured with explanations |
+| 10 | Some patterns documented |
+| 5 | Minimal |
+| 0 | None |
+
+### Conciseness (15 points)
+
+Dense, valuable content. No filler, no redundancy, each line earns its place.
+
+| Score | Meaning |
+|-------|---------|
+| 15 | Every line adds value, no filler |
+| 10 | Mostly concise, minor bloat |
+| 5 | Verbose in places |
+| 0 | Mostly filler or generic advice |
+
+### Currency (15 points)
+
+Reflects the actual current codebase. Commands work, files exist, stack is correct.
+
+| Score | Meaning |
+|-------|---------|
+| 15 | All references valid, commands work, stack current |
+| 10 | Mostly current, minor staleness |
+| 5 | Several outdated references |
+| 0 | Severely outdated |
+
+### Actionability (15 points)
+
+Instructions are executable. Copy-paste ready commands, real paths, concrete steps.
+
+| Score | Meaning |
+|-------|---------|
+| 15 | Copy-paste ready, concrete, real paths |
+| 10 | Mostly actionable |
+| 5 | Some vague instructions |
+| 0 | Theoretical or generic |
+
+## Grading Scale
+
+| Grade | Score | Meaning |
+|-------|-------|---------|
+| 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 |
+
+## Red Flags
+
+Flag these during audit — each indicates a quality problem:
+
+- Commands that fail when run
+- References to files/directories that don't exist
+- Outdated technology versions or deprecated APIs
+- Generic advice not specific to the project (e.g. "write clean code")
+- Copy-paste templates that weren't customised
+- "TODO" items that were never completed
+- Duplicated content across multiple CLAUDE.md files
+- Verbose explanations of things Claude already knows
+- Changelogs or version history (belongs in git, not CLAUDE.md)
diff --git a/skills/memory-manager/references/templates.md b/skills/memory-manager/references/templates.md
new file mode 100644
index 00000000..7e05c189
--- /dev/null
+++ b/skills/memory-manager/references/templates.md
@@ -0,0 +1,149 @@
+# Templates
+
+Reference templates for CLAUDE.md files, rules topic files, and sub-directory context. Use these when creating new files or restructuring existing ones.
+
+## Root CLAUDE.md (Minimal)
+
+For simple projects with a single developer:
+
+```markdown
+# [Project Name]
+
+[One-line description]
+
+## Stack
+
+[Tech stack summary]
+
+## Commands
+
+| Command | Purpose |
+|---------|---------|
+| `npm run dev` | Start dev server |
+| `npm run build` | Production build |
+| `npm run deploy` | Deploy to [platform] |
+
+## Gotchas
+
+- [Non-obvious thing 1]
+- [Non-obvious thing 2]
+```
+
+Target: 30-60 lines.
+
+## Root CLAUDE.md (Comprehensive)
+
+For projects with external integrations, multiple contributors, or complex workflows:
+
+```markdown
+# [Project Name]
+
+**Repository**: [URL]
+**Owner**: [Name]
+
+[One-line description]
+
+## Stack
+
+[Tech stack with key decisions noted]
+
+## Directory Structure
+
+[Annotated tree of key directories]
+
+## Commands
+
+| Command | Purpose |
+|---------|---------|
+| `npm run dev` | Start dev server |
+| `npm run build` | Production build |
+| `npm run deploy` | Deploy to [platform] |
+| `npm test` | Run test suite |
+
+## Key Files
+
+| File | Purpose |
+|------|---------|
+| `src/index.ts` | Entry point |
+| `wrangler.jsonc` | Cloudflare config |
+
+## Critical Rules
+
+- [Never do X because Y]
+- [Always do A before B]
+
+## Gotchas
+
+- [Non-obvious thing 1]
+- [Non-obvious thing 2]
+```
+
+Target: 60-150 lines.
+
+## Sub-Directory CLAUDE.md
+
+For directories with external integrations, non-obvious config, or common gotchas:
+
+```markdown
+# [Component Name]
+
+## Key Integrations
+
+- **[Service]**: [endpoint], [auth method], [secret location]
+
+## Commands
+
+[Directory-specific commands if different from root]
+
+## Gotchas
+
+- [Non-obvious thing specific to this directory]
+```
+
+Target: 15-50 lines.
+
+**Don't create when**: parent CLAUDE.md covers it, directory is self-explanatory, content would be under 10 lines.
+
+## Rules Topic File (.claude/rules/*.md)
+
+For correction rules, patterns, and technical facts that apply across projects:
+
+```markdown
+# [Topic Name]
+
+## [Pattern/Rule Category]
+
+| If Claude suggests... | Use instead... |
+|----------------------|----------------|
+| [Wrong pattern] | [Correct pattern] |
+
+[Code example if helpful]
+
+**Last Updated**: [date]
+```
+
+Target: 20-80 lines per topic file.
+
+## Section Placement Guide
+
+| Content Type | Where It Goes |
+|-------------|---------------|
+| Project name, owner, purpose | Root CLAUDE.md |
+| Tech stack, architecture overview | Root CLAUDE.md |
+| Build/deploy/test commands | Root CLAUDE.md |
+| Critical "never do X" rules | Root CLAUDE.md |
+| Directory structure | Root CLAUDE.md |
+| External service integrations | Sub-directory CLAUDE.md (near the code that uses them) |
+| Directory-specific gotchas | Sub-directory CLAUDE.md |
+| Correction rules (training cutoff) | `.claude/rules/<topic>.md` |
+| Coding patterns for this project | `.claude/rules/<topic>.md` or root CLAUDE.md |
+| Session-specific discoveries | Auto-memory (managed by Claude Code, not this skill) |
+
+## Anti-Patterns
+
+- Verbose explanations of standard tools or frameworks
+- Changelogs or version history (use git)
+- Content Claude already knows from training
+- Duplicating parent CLAUDE.md content in child files
+- Generic best practices not specific to the project
+- Empty template sections with placeholder text
diff --git a/skills/memory-manager/scripts/audit_memory.py b/skills/memory-manager/scripts/audit_memory.py
index 9f2e6476..aa86b47e 100644
--- a/skills/memory-manager/scripts/audit_memory.py
+++ b/skills/memory-manager/scripts/audit_memory.py
@@ -1,30 +1,95 @@
#!/usr/bin/env python3
-"""Audit CLAUDE.md memory hierarchy in a repository.
+"""Audit memory hierarchy across all three layers.
-Scans for all CLAUDE.md files, reports sizes, identifies bloat,
-and suggests directories that could benefit from their own CLAUDE.md.
+Scans CLAUDE.md files, .claude/rules/ topic files, and auto-memory.
+Reports sizes, quality scores, project type, missing docs, and staleness.
Usage:
python3 audit_memory.py [repo-path]
- python3 audit_memory.py # uses current directory
+ python3 audit_memory.py # uses current directory
+ python3 audit_memory.py --json # JSON output for programmatic use
"""
+import json
import os
+import re
import sys
from pathlib import Path
-# Size targets (lines)
+# ---------------------------------------------------------------------------
+# Configuration
+# ---------------------------------------------------------------------------
+
ROOT_TARGET = 150
SUBDIR_TARGET = 50
RULES_TARGET = 80
-# Directories to skip
SKIP_DIRS = {
"node_modules", ".git", "dist", "build", ".wrangler",
".output", ".vercel", ".cache", "__pycache__", ".venv",
- "vendor", ".next", ".nuxt",
+ "vendor", ".next", ".nuxt", ".turbo", ".parcel-cache",
+}
+
+# Sections that indicate quality (used for scoring)
+COMMAND_PATTERNS = re.compile(
+ r"(##\s*(commands?|scripts?|workflow|usage|quick\s*start))",
+ re.IGNORECASE,
+)
+ARCH_PATTERNS = re.compile(
+ r"(##\s*(architect|directory|structure|stack|overview|layout))",
+ re.IGNORECASE,
+)
+GOTCHA_PATTERNS = re.compile(
+ r"(##\s*(gotcha|caveat|warning|critical|never|important|rules?))",
+ re.IGNORECASE,
+)
+
+# Project type detection indicators
+PROJECT_INDICATORS = {
+ "cloudflare-worker": {
+ "files": ["wrangler.jsonc", "wrangler.toml"],
+ "docs": ["ARCHITECTURE.md"],
+ },
+ "mcp-server": {
+ "content_patterns": [r"FastMCP|McpAgent|mcp.*server"],
+ "docs": ["ARCHITECTURE.md", "API_ENDPOINTS.md"],
+ },
+ "vite-react": {
+ "files_glob": ["vite.config.*"],
+ "content_check": {"dir": "src", "ext": ".tsx"},
+ "docs": ["ARCHITECTURE.md"],
+ },
+ "vite-app": {
+ "files_glob": ["vite.config.*"],
+ "docs": ["ARCHITECTURE.md"],
+ },
+ "nextjs": {
+ "files_glob": ["next.config.*"],
+ "docs": ["ARCHITECTURE.md"],
+ },
+ "api-project": {
+ "dirs": ["src/routes", "src/api", "app/api"],
+ "docs": ["API_ENDPOINTS.md", "DATABASE_SCHEMA.md"],
+ },
+ "database-project": {
+ "files_glob": ["drizzle.config.*", "prisma/schema.prisma"],
+ "docs": ["DATABASE_SCHEMA.md"],
+ },
+ "skills-repo": {
+ "dirs": ["skills"],
+ "content_check_dir": {"subdir": "skills", "file": "SKILL.md"},
+ "docs": [],
+ },
+ "claude-ops": {
+ "dirs": [".claude/agents"],
+ "docs": [],
+ },
}
+# ---------------------------------------------------------------------------
+# Core scanning functions
+# ---------------------------------------------------------------------------
+
def count_lines(path: Path) -> int:
try:
@@ -33,6 +98,13 @@ def count_lines(path: Path) -> int:
return -1
+def read_text(path: Path) -> str:
+ try:
+ return path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ return ""
+
+
def find_claude_md(repo: Path) -> list[Path]:
"""Find all CLAUDE.md files, skipping ignored directories."""
results = []
@@ -52,12 +124,39 @@ def find_rules(repo: Path) -> list[Path]:
return sorted(rules_dir.glob("*.md"))
-def find_complex_dirs(repo: Path, existing: set[Path]) -> list[Path]:
- """Find directories that might benefit from a CLAUDE.md.
+def find_auto_memory() -> list[Path]:
+ """Find auto-memory MEMORY.md files in ~/.claude/projects/."""
+ home = Path.home()
+ projects_dir = home / ".claude" / "projects"
+ if not projects_dir.is_dir():
+ return []
+ results = []
+ for project_dir in sorted(projects_dir.iterdir()):
+ memory_file = project_dir / "memory" / "MEMORY.md"
+ if memory_file.is_file():
+ results.append(memory_file)
+ return results
+
+
+def extract_sections(path: Path) -> list[tuple[str, int]]:
+ """Extract H2 sections with line counts."""
+ lines = read_text(path).splitlines()
+ sections = []
+ current_heading = "(preamble)"
+ current_start = 0
+ for i, line in enumerate(lines):
+ if line.startswith("## "):
+ if current_heading:
+ sections.append((current_heading, i - current_start))
+ current_heading = line.lstrip("# ").strip()
+ current_start = i
+ if current_heading:
+ sections.append((current_heading, len(lines) - current_start))
+ return sections
- Heuristic: directories with config files, external integrations,
- or many source files but no CLAUDE.md.
- """
+
+def find_complex_dirs(repo: Path, existing: set[Path]) -> list[Path]:
+ """Find directories that might benefit from a CLAUDE.md."""
indicators = {
"wrangler.jsonc", "wrangler.toml", ".env.example",
"docker-compose.yml", "Dockerfile", "firebase.json",
@@ -69,7 +168,8 @@ def find_complex_dirs(repo: Path, existing: set[Path]) -> list[Path]:
root_path = Path(root)
if root_path in existing:
continue
- # Skip if parent already has CLAUDE.md very close
+ if root_path == repo:
+ continue
has_indicator = bool(set(files) & indicators)
src_count = sum(1 for f in files if f.endswith((".ts", ".tsx", ".py", ".go")))
if has_indicator or src_count > 10:
@@ -77,91 +177,430 @@ def find_complex_dirs(repo: Path, existing: set[Path]) -> list[Path]:
return sorted(suggestions)
-def extract_sections(path: Path) -> list[tuple[str, int]]:
- """Extract H2 sections with line counts."""
- lines = path.read_text(encoding="utf-8").splitlines()
- sections = []
- current_heading = "(preamble)"
- current_start = 0
- for i, line in enumerate(lines):
- if line.startswith("## "):
- if current_heading:
- sections.append((current_heading, i - current_start))
- current_heading = line.strip("# ").strip()
- current_start = i
- if current_heading:
- sections.append((current_heading, len(lines) - current_start))
- return sections
+# ---------------------------------------------------------------------------
+# Project type detection
+# ---------------------------------------------------------------------------
+
+
+def detect_project_type(repo: Path) -> list[dict]:
+ """Detect project types from file presence. Returns list of matching types."""
+ detected = []
+
+ for type_name, indicators in PROJECT_INDICATORS.items():
+ matched = False
+
+ # Check specific files
+ if "files" in indicators:
+ for f in indicators["files"]:
+ if (repo / f).exists():
+ matched = True
+ break
+
+ # Check glob patterns
+ if not matched and "files_glob" in indicators:
+ for pattern in indicators["files_glob"]:
+ if list(repo.glob(pattern)):
+ matched = True
+ break
+
+ # Check directories
+ if not matched and "dirs" in indicators:
+ for d in indicators["dirs"]:
+ if (repo / d).is_dir():
+ matched = True
+ break
+
+ # Content pattern check (e.g. MCP server detection)
+ if not matched and "content_patterns" in indicators:
+ src_index = repo / "src" / "index.ts"
+ if src_index.exists():
+ content = read_text(src_index)
+ for pattern in indicators["content_patterns"]:
+ if re.search(pattern, content):
+ matched = True
+ break
+
+ # Vite-react needs .tsx files in src/
+ if matched and type_name == "vite-react":
+ src_dir = repo / "src"
+ if not src_dir.is_dir() or not list(src_dir.glob("**/*.tsx")):
+ matched = False
+
+ # Vite-app should not match if vite-react already matched
+ if type_name == "vite-app" and matched:
+ if any(d["type"] == "vite-react" for d in detected):
+ matched = False
+
+ # Skills repo needs SKILL.md files inside skills/
+ if matched and type_name == "skills-repo":
+ skills_dir = repo / "skills"
+ if not list(skills_dir.glob("*/SKILL.md")):
+ matched = False
+
+ if matched:
+ detected.append({
+ "type": type_name,
+ "docs": indicators.get("docs", []),
+ })
+
+ return detected if detected else [{"type": "generic", "docs": []}]
+
+
+def get_expected_docs(project_types: list[dict]) -> list[str]:
+ """Union all expected docs from detected project types."""
+ docs = {"CLAUDE.md"}
+ for pt in project_types:
+ for d in pt.get("docs", []):
+ docs.add(d)
+ return sorted(docs)
+
+
+def check_missing_docs(repo: Path, expected: list[str]) -> list[str]:
+ """Check which expected docs are missing."""
+ missing = []
+ for doc in expected:
+ # Check root and docs/ directory
+ if not (repo / doc).exists() and not (repo / "docs" / doc).exists():
+ missing.append(doc)
+ return missing
+
+
+# ---------------------------------------------------------------------------
+# Quality scoring
+# ---------------------------------------------------------------------------
+
+
+def score_claude_md(path: Path, repo: Path) -> dict:
+ """Score a CLAUDE.md file on 6 criteria (100 points total)."""
+ content = read_text(path)
+ lines = content.splitlines()
+ line_count = len(lines)
+
+ scores = {}
+
+ # 1. Commands/Workflows (20 pts)
+ has_commands = bool(COMMAND_PATTERNS.search(content))
+ has_code_blocks = content.count("```") >= 2
+ has_table = "|" in content and "---" in content
+ cmd_score = 0
+ if has_commands and has_code_blocks:
+ cmd_score = 20
+ elif has_commands or has_code_blocks:
+ cmd_score = 15 if has_table else 10
+ elif has_table:
+ cmd_score = 5
+ scores["commands"] = cmd_score
+
+ # 2. Architecture Clarity (20 pts)
+ has_arch = bool(ARCH_PATTERNS.search(content))
+ has_tree = "├" in content or "└" in content
+ arch_score = 0
+ if has_arch and has_tree:
+ arch_score = 20
+ elif has_arch:
+ arch_score = 15
+ elif has_tree:
+ arch_score = 10
+ scores["architecture"] = arch_score
+
+ # 3. Non-Obvious Patterns (15 pts)
+ has_gotchas = bool(GOTCHA_PATTERNS.search(content))
+ has_never = "never" in content.lower() or "don't" in content.lower()
+ gotcha_score = 0
+ if has_gotchas and has_never:
+ gotcha_score = 15
+ elif has_gotchas or has_never:
+ gotcha_score = 10
+ scores["patterns"] = gotcha_score
+
+ # 4. Conciseness (15 pts)
+ is_root = path.parent == repo
+ target = ROOT_TARGET if is_root else SUBDIR_TARGET
+ ratio = line_count / target if target > 0 else 2.0
+ if 0.3 <= ratio <= 1.0:
+ concise_score = 15
+ elif ratio <= 1.5:
+ concise_score = 10
+ elif ratio <= 2.0:
+ concise_score = 5
+ else:
+ concise_score = 0
+ scores["conciseness"] = concise_score
+
+ # 5. Currency (15 pts) — check for stale references
+ stale_refs = check_staleness(path, repo)
+ if not stale_refs:
+ currency_score = 15
+ elif len(stale_refs) <= 2:
+ currency_score = 10
+ elif len(stale_refs) <= 5:
+ currency_score = 5
+ else:
+ currency_score = 0
+ scores["currency"] = currency_score
+
+ # 6. Actionability (15 pts)
+ has_inline_code = "`" in content
+ actionability_score = 0
+ if has_code_blocks and has_inline_code and has_table:
+ actionability_score = 15
+ elif has_code_blocks and has_inline_code:
+ actionability_score = 10
+ elif has_inline_code:
+ actionability_score = 5
+ scores["actionability"] = actionability_score
+
+ total = sum(scores.values())
+ grade = (
+ "A" if total >= 90 else
+ "B" if total >= 70 else
+ "C" if total >= 50 else
+ "D" if total >= 30 else
+ "F"
+ )
+
+ return {
+ "scores": scores,
+ "total": total,
+ "grade": grade,
+ "stale_refs": stale_refs,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Staleness detection
+# ---------------------------------------------------------------------------
+
+
+def check_staleness(path: Path, repo: Path) -> list[str]:
+ """Check for references to non-existent files/directories."""
+ content = read_text(path)
+ stale = []
+
+ # Find file path references (backticked paths, markdown links)
+ path_patterns = [
+ r"`([a-zA-Z0-9_./-]+\.[a-zA-Z]{1,5})`", # `path/to/file.ext`
+ r"\[.*?\]\(([a-zA-Z0-9_./-]+\.[a-zA-Z]{1,5})\)", # [text](path)
+ r"`([a-zA-Z0-9_/-]+/)`", # `path/to/dir/`
+ ]
+
+ checked = set()
+ for pattern in path_patterns:
+ for match in re.finditer(pattern, content):
+ ref = match.group(1).rstrip("/")
+ if ref in checked:
+ continue
+ checked.add(ref)
+
+ # Skip URLs, commands, common patterns
+ if ref.startswith(("http", "//", "npm ", "git ", "$")):
+ continue
+ if ref.startswith(("*.","**/")):
+ continue
+ # Skip short refs that are likely code, not file paths
+ if "/" not in ref and not ref.startswith("."):
+ continue
+
+ # Check relative to the CLAUDE.md's directory and repo root
+ ref_path = Path(ref)
+ candidates = [
+ path.parent / ref_path,
+ repo / ref_path,
+ ]
+ if not any(c.exists() for c in candidates):
+ stale.append(ref)
+
+ return stale
+
+
+# ---------------------------------------------------------------------------
+# Report generation
+# ---------------------------------------------------------------------------
+
+
+def print_header(text: str) -> None:
+ print(f"\n{'=' * 60}")
+ print(f" {text}")
+ print(f"{'=' * 60}\n")
def main():
- repo = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
+ json_output = "--json" in sys.argv
+ args = [a for a in sys.argv[1:] if a != "--json"]
+ repo = Path(args[0] if args else ".").resolve()
+
if not repo.is_dir():
- print(f"Error: {repo} is not a directory")
+ print(f"Error: {repo} is not a directory", file=sys.stderr)
sys.exit(1)
- print(f"Auditing CLAUDE.md hierarchy in: {repo}\n")
+ report = {
+ "repo": str(repo),
+ "project_types": [],
+ "claude_md_files": [],
+ "rules_files": [],
+ "auto_memory_files": [],
+ "missing_docs": [],
+ "suggestions": [],
+ "summary": {},
+ }
+
+ # --- Project Type Detection ---
+ project_types = detect_project_type(repo)
+ report["project_types"] = [pt["type"] for pt in project_types]
+ expected_docs = get_expected_docs(project_types)
+ missing_docs = check_missing_docs(repo, expected_docs)
+ report["missing_docs"] = missing_docs
- # Find CLAUDE.md files
+ if not json_output:
+ print(f"Auditing: {repo}\n")
+ type_names = ", ".join(pt["type"] for pt in project_types)
+ print(f"Project type(s): {type_names}")
+ print(f"Expected docs: {', '.join(expected_docs)}")
+ if missing_docs:
+ print(f"Missing docs: {', '.join(missing_docs)}")
+ else:
+ print("Missing docs: none")
+
+ # --- Layer 1: CLAUDE.md Files ---
claude_files = find_claude_md(repo)
existing_dirs = {f.parent for f in claude_files}
+ if not json_output:
+ print_header("Layer 1: CLAUDE.md Hierarchy")
+
if not claude_files:
- print("No CLAUDE.md files found.\n")
+ if not json_output:
+ print(" No CLAUDE.md files found.\n")
else:
- print(f"Found {len(claude_files)} CLAUDE.md file(s):\n")
+ if not json_output:
+ print(f" Found {len(claude_files)} file(s):\n")
- oversized = []
for f in claude_files:
lines = count_lines(f)
- rel = f.relative_to(repo)
+ rel = str(f.relative_to(repo))
is_root = f.parent == repo
target = ROOT_TARGET if is_root else SUBDIR_TARGET
status = "OK" if lines <= target else "OVER"
+ quality = score_claude_md(f, repo)
+
+ file_info = {
+ "path": rel,
+ "lines": lines,
+ "target": target,
+ "status": status,
+ "quality": quality,
+ }
+ report["claude_md_files"].append(file_info)
- marker = " <<< OVER TARGET" if status == "OVER" else ""
- print(f" {rel}: {lines} lines (target: {target}){marker}")
-
- if status == "OVER":
- oversized.append((f, lines, target))
-
- if oversized:
- print(f"\n--- Oversized files ({len(oversized)}) ---\n")
- for f, lines, target in oversized:
- rel = f.relative_to(repo)
- print(f" {rel}: {lines}/{target} lines (+{lines - target} over)")
- sections = extract_sections(f)
- if sections:
- print(" Sections:")
- for name, count in sections:
- big = " <<<" if count > 30 else ""
- print(f" {name}: {count} lines{big}")
+ if not json_output:
+ marker = f" <<< +{lines - target} over" if status == "OVER" else ""
+ print(f" {rel}: {lines} lines (target: {target}){marker}")
+ print(f" Score: {quality['total']}/100 ({quality['grade']})")
+ scores = quality["scores"]
+ parts = [f"{k}={v}" for k, v in scores.items()]
+ print(f" [{', '.join(parts)}]")
+ if quality["stale_refs"]:
+ print(f" Stale refs: {', '.join(quality['stale_refs'])}")
print()
- # Find rules
+ # --- Layer 2: Rules Files ---
rules = find_rules(repo)
+
+ if not json_output:
+ print_header("Layer 2: .claude/rules/")
+
if rules:
- print(f"\nFound {len(rules)} rule file(s) in .claude/rules/:\n")
+ if not json_output:
+ print(f" Found {len(rules)} rule file(s):\n")
for r in rules:
lines = count_lines(r)
- status = " <<< OVER TARGET" if lines > RULES_TARGET else ""
- print(f" {r.name}: {lines} lines{status}")
+ status = "OVER" if lines > RULES_TARGET else "OK"
+ file_info = {
+ "path": f".claude/rules/{r.name}",
+ "lines": lines,
+ "target": RULES_TARGET,
+ "status": status,
+ }
+ report["rules_files"].append(file_info)
+ if not json_output:
+ marker = f" <<< +{lines - RULES_TARGET} over" if status == "OVER" else ""
+ print(f" {r.name}: {lines} lines{marker}")
+ else:
+ if not json_output:
+ print(" No .claude/rules/ directory found.")
+
+ # --- Layer 3: Auto-Memory ---
+ auto_memory = find_auto_memory()
+
+ if not json_output:
+ print_header("Layer 3: Auto-Memory")
+
+ if auto_memory:
+ if not json_output:
+ print(f" Found {len(auto_memory)} auto-memory file(s):\n")
+ for m in auto_memory:
+ lines = count_lines(m)
+ # Extract project name from directory
+ project_name = m.parent.parent.name
+ file_info = {
+ "path": str(m),
+ "project": project_name,
+ "lines": lines,
+ "empty": lines <= 1,
+ }
+ report["auto_memory_files"].append(file_info)
+ if not json_output:
+ empty_note = " (empty)" if lines <= 1 else ""
+ print(f" {project_name}: {lines} lines{empty_note}")
+ else:
+ if not json_output:
+ print(" No auto-memory files found.")
- # Suggest new CLAUDE.md locations
+ # --- Suggestions ---
suggestions = find_complex_dirs(repo, existing_dirs)
- if suggestions:
- print(f"\n--- Suggested new CLAUDE.md locations ({len(suggestions)}) ---\n")
+ report["suggestions"] = [str(s.relative_to(repo)) for s in suggestions]
+
+ if suggestions and not json_output:
+ print_header("Suggestions")
+ print(f" {len(suggestions)} director(ies) could benefit from a CLAUDE.md:\n")
for s in suggestions:
- rel = s.relative_to(repo)
- print(f" {rel}/CLAUDE.md")
-
- # Summary
- total_lines = sum(count_lines(f) for f in claude_files)
- print(f"\n--- Summary ---")
- print(f" CLAUDE.md files: {len(claude_files)}")
- print(f" Total lines: {total_lines}")
- print(f" Rules files: {len(rules)}")
- print(f" Suggested additions: {len(suggestions)}")
+ print(f" {s.relative_to(repo)}/CLAUDE.md")
+
+ # --- Summary ---
+ total_claude_lines = sum(count_lines(f) for f in claude_files)
+ total_rules_lines = sum(count_lines(r) for r in rules)
+ oversized_count = sum(
+ 1 for f in report["claude_md_files"] if f["status"] == "OVER"
+ )
+ avg_score = 0
+ if report["claude_md_files"]:
+ avg_score = round(
+ sum(f["quality"]["total"] for f in report["claude_md_files"])
+ / len(report["claude_md_files"])
+ )
+
+ report["summary"] = {
+ "claude_md_count": len(claude_files),
+ "claude_md_total_lines": total_claude_lines,
+ "claude_md_oversized": oversized_count,
+ "claude_md_avg_score": avg_score,
+ "rules_count": len(rules),
+ "rules_total_lines": total_rules_lines,
+ "auto_memory_count": len(auto_memory),
+ "missing_docs": len(missing_docs),
+ "suggestion_count": len(suggestions),
+ }
+
+ if not json_output:
+ print_header("Summary")
+ print(f" CLAUDE.md files: {len(claude_files)} ({total_claude_lines} lines, {oversized_count} oversized)")
+ print(f" Average quality: {avg_score}/100")
+ print(f" Rules files: {len(rules)} ({total_rules_lines} lines)")
+ print(f" Auto-memory files: {len(auto_memory)}")
+ print(f" Missing docs: {len(missing_docs)}")
+ print(f" Suggested additions: {len(suggestions)}")
+ else:
+ print(json.dumps(report, indent=2))
if __name__ == "__main__":