feat(plugin): ship as Claude Code plugin with 150-line cap and sync command

Turns ClaudeForge into an installable Claude Code plugin and adds the
missing pieces for a clean lifecycle: hard line-cap enforcement, modular
chaining via @path imports, a sync/cleanup command, and Explore-agent
delegation for project discovery.

- .claude-plugin/plugin.json: plugin manifest registering both skills,
  both commands, and the guardian agent (installable via /plugin marketplace
  add alirezarezvani/ClaudeForge && /plugin install claudeforge)
- skill/validator.py: MAX_RECOMMENDED_LINES 300 -> 150 (warning at 120)
- skill/template_selector.py: target_lines capped at 150 across all
  team sizes (solo 75 / small 100 / medium 125 / large 150) so any
  single CLAUDE.md fits within the cap; bigger projects spread content
  across modular sub-files
- skill/analyzer.py: length thresholds, quality scoring, and recommendations
  rebased on the 150 cap (was 300/400)
- skill/generator.py: modular root now emits @path imports next to the
  human-readable links; every sub-CLAUDE.md gets a back-link header
  pointing to ../CLAUDE.md (markdown + @import) for bidirectional chaining
- command/sync-claude-md.md: new /sync-claude-md command that inventories
  every CLAUDE.md, prunes stale references, enforces the 150 cap by
  splitting into sub-files, and repairs the root <-> sub chain
- command/enhance-claude-md.md: discovery phase now delegates the deep
  codebase scan to the Explore subagent to keep context lean
- install.sh / install.ps1: each command in command/ installs as its own
  ~/.claude/commands/<name>.md (legacy bundle backed up on upgrade)
- skill/SKILL.md, CLAUDE.md, README.md, CHANGELOG.md: docs updated for
  the plugin install path, sync command, and new line cap

Verified via smoke test: validator constants, template targets, generator
output line counts across 5 presets (all <= 150), context files with
backlinks, @-import chain in modular root, idempotent merge_with_existing,
validator status transitions at the new cap, analyzer quality differential,
and plugin manifest JSON shape with all referenced paths existing on disk.
This commit is contained in:
Claude
2026-05-19 00:04:22 +00:00
parent ffff0fc4c3
commit a45e6f5dbd
13 changed files with 318 additions and 64 deletions
+32
View File
@@ -0,0 +1,32 @@
{
"name": "claudeforge",
"description": "CLAUDE.md lifecycle toolkit: initialise, enhance, sync, and modularise CLAUDE.md files with a 150-line cap, automatic chaining, and Karpathy behavioural guardrails.",
"version": "2.1.0",
"author": {
"name": "Alireza Rezvani",
"url": "https://github.com/alirezarezvani"
},
"license": "MIT",
"homepage": "https://github.com/alirezarezvani/ClaudeForge",
"keywords": [
"claude-md",
"documentation",
"best-practices",
"modular",
"sync",
"karpathy",
"guidelines",
"context-management"
],
"skills": [
"./skill",
"./skill/karpathy-guidelines"
],
"commands": [
"./command/enhance-claude-md.md",
"./command/sync-claude-md.md"
],
"agents": [
"./agent/claude-md-guardian.md"
]
}
+15 -4
View File
@@ -11,10 +11,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- **Karpathy Guidelines skill** (`skill/karpathy-guidelines/SKILL.md`): a behavioral-guardrail skill installed alongside ClaudeForge that applies to every coding, review, and refactoring task. Covers four principles — Think Before Coding, Simplicity First, Surgical Changes, Goal-Driven Execution — adapted with attribution from the MIT-licensed [forrestchang/andrej-karpathy-skills](https://github.com/forrestchang/andrej-karpathy-skills) repository.
- **Automatic embedding into every CLAUDE.md**: `skill/template_selector.py` and `skill/generator.py` now insert a `## Behavioral Guidelines` section into every generated and enhanced CLAUDE.md, so the principles ship with every project that runs `/enhance-claude-md`.
- **Installer support for the new skill**: `install.sh` and `install.ps1` now copy the skill to `~/.claude/skills/karpathy-guidelines/` (or the project-level equivalent) and include it in the uninstall instructions.
- **Slash command documentation**: `command/enhance-claude-md.md` documents the always-on Behavioral Guidelines section as a required part of the workflow.
- **Claude Code plugin manifest** (`.claude-plugin/plugin.json`): ClaudeForge is now installable as a Claude Code plugin via `/plugin marketplace add alirezarezvani/ClaudeForge && /plugin install claudeforge`. Manifest registers all skills, commands, and the guardian agent in one bundle.
- **`/sync-claude-md` slash command** (`command/sync-claude-md.md`): walks every CLAUDE.md in the project, prunes stale references (removed dependencies, deleted paths, broken modular links), enforces the 150-line cap, and repairs the root ↔ sub chain. Designed to run after refactors, dependency changes, or before a release.
- **Karpathy Guidelines skill** (`skill/karpathy-guidelines/SKILL.md`): behavioural-guardrail skill applied to every coding, review, and refactoring task. Covers four principles — Think Before Coding, Simplicity First, Surgical Changes, Goal-Driven Execution — adapted with attribution from the MIT-licensed [forrestchang/andrej-karpathy-skills](https://github.com/forrestchang/andrej-karpathy-skills) repository.
- **Automatic embedding into every CLAUDE.md**: `skill/template_selector.py` and `skill/generator.py` insert a `## Behavioral Guidelines` section into every generated and enhanced CLAUDE.md.
- **Modular chaining via `@path` imports**: the modular root generator emits both human-readable markdown links and Claude Code `@path/to/CLAUDE.md` imports for every sub-CLAUDE.md. Sub-files now get a back-link header pointing to the root file so navigation is bidirectional.
- **Explore-agent delegation in `/enhance-claude-md`**: deep project scans are delegated to the Explore subagent to keep the calling session's context lean.
### Changed
- **Hard 150-line cap per CLAUDE.md**: `validator.MAX_RECOMMENDED_LINES` lowered from 300 to 150 (warning at 120). `template_selector.TEAM_SIZE_TEMPLATES` target lines lowered to fit (solo 75 / small 100 / medium 125 / large 150). `analyzer` length thresholds and quality scoring rebased on the new cap. Projects that need more content split it across chained sub-files instead of growing the root.
- **Installers register commands as top-level files**: `install.sh` and `install.ps1` now install each `.md` under `command/` as its own `~/.claude/commands/<name>.md` (registering as `/<name>`) rather than bundling the whole directory under one path. Legacy `~/.claude/commands/enhance-claude-md/` bundles are backed up automatically on upgrade.
### Verified
- Smoke tests: validator constants, all four team-size templates, generator output for solo/small/medium/large + library presets (all ≤ 150 lines), context files with back-links, `@`-import chain in modular root, idempotent `merge_with_existing`, validator status transitions (pass / warning / fail) at the new cap, analyzer quality score differential between compliant and bloated files, plugin manifest JSON shape and that every referenced path exists on disk.
---
+6 -5
View File
@@ -6,12 +6,13 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview
**ClaudeForge** is a comprehensive toolkit for automated CLAUDE.md creation, enhancement, and maintenance for Claude Code projects. The repository consists of four integrated components:
**ClaudeForge** is a Claude Code plugin (manifest at `.claude-plugin/plugin.json`) and standalone toolkit for the CLAUDE.md lifecycle: initialise, enhance, sync, and modularise CLAUDE.md files with a hard 150-line cap, automatic chaining via `@path` imports, and Karpathy behavioural guardrails. Works in any Claude Code or Claude.cowork project. The repository consists of five integrated components:
1. **Skill** (`claudeforge-skill`) - Core Python modules for analysis, generation, and validation
2. **Slash Command** (`/enhance-claude-md`) - Interactive multi-phase discovery workflow
3. **Guardian Agent** (`claude-md-guardian`) - Background maintenance agent
4. **Karpathy Guidelines Skill** (`karpathy-guidelines`) - Behavioral guardrails embedded into every generated CLAUDE.md and installed as a standalone skill, adapted with attribution from the MIT-licensed [forrestchang/andrej-karpathy-skills](https://github.com/forrestchang/andrej-karpathy-skills) repository
1. **Skill** (`claudeforge-skill`) - Core Python modules for analysis, generation, and validation. Enforces a 150-line hard cap per CLAUDE.md.
2. **Slash Command** (`/enhance-claude-md`) - Interactive multi-phase discovery workflow. Delegates deep codebase scans to the Explore subagent to avoid context bloat.
3. **Slash Command** (`/sync-claude-md`) - Walks every CLAUDE.md in the project, prunes stale references, enforces the 150-line cap, and repairs the root ↔ subdirectory chain (markdown links + `@path` imports).
4. **Guardian Agent** (`claude-md-guardian`) - Background maintenance agent
5. **Karpathy Guidelines Skill** (`karpathy-guidelines`) - Behavioral guardrails embedded into every generated CLAUDE.md and installed as a standalone skill, adapted with attribution from the MIT-licensed [forrestchang/andrej-karpathy-skills](https://github.com/forrestchang/andrej-karpathy-skills) repository
---
+17 -3
View File
@@ -44,12 +44,15 @@ ClaudeForge is a comprehensive toolkit that eliminates the tedious process of ma
Core capability for CLAUDE.md analysis, generation, validation, and enhancement
### 2. **Slash Command** (`/enhance-claude-md`)
Interactive interface with multi-phase discovery workflow
Interactive interface with multi-phase discovery workflow. Delegates deep codebase scans to the Explore subagent so the discovery does not bloat the calling session.
### 3. **Guardian Agent** (`claude-md-guardian`)
### 3. **Slash Command** (`/sync-claude-md`)
Walks every CLAUDE.md in the project, prunes stale references (removed dependencies, deleted files, dead modular links), enforces the **150-line hard cap per file**, and repairs the root ↔ subdirectory chain (markdown links + `@path` imports). Run after refactors, dependency changes, or before cutting a release.
### 4. **Guardian Agent** (`claude-md-guardian`)
Background agent for automatic CLAUDE.md maintenance and synchronization
### 4. **Karpathy Guidelines Skill** (`karpathy-guidelines`)
### 5. **Karpathy Guidelines Skill** (`karpathy-guidelines`)
Behavioral guardrails — Think Before Coding, Simplicity First, Surgical Changes, Goal-Driven Execution — installed as a standalone skill and automatically embedded into every CLAUDE.md generated or enhanced by `/enhance-claude-md`. Adapted with attribution from the MIT-licensed [forrestchang/andrej-karpathy-skills](https://github.com/forrestchang/andrej-karpathy-skills) repository, inspired by Andrej Karpathy's observations on common LLM coding failure modes.
---
@@ -58,6 +61,17 @@ Behavioral guardrails — Think Before Coding, Simplicity First, Surgical Change
### Installation
#### **Claude Code Plugin (recommended)**
ClaudeForge ships as a Claude Code plugin. From any Claude Code session:
```text
/plugin marketplace add alirezarezvani/ClaudeForge
/plugin install claudeforge
```
This installs every component (skills, slash commands, guardian agent) and registers `/enhance-claude-md` and `/sync-claude-md` for any project. Works the same at the user level (available everywhere) or scoped to a single project.
#### **macOS / Linux**
```bash
curl -fsSL https://raw.githubusercontent.com/alirezarezvani/ClaudeForge/main/install.sh | bash
+8
View File
@@ -39,6 +39,14 @@ This command uses the `claude-md-enhancer` skill to initialize or enhance CLAUDE
!`ls -la`
### Deep project scan via Explore agent
For non-trivial repositories, delegate the codebase walk to the **Explore** subagent so the discovery does not bloat this command's context window. Ask it a single, scoped question — for example:
> Walk this repository and report: project type (web_app / api / fullstack / cli / library / mobile / desktop), languages and frameworks detected, primary tech stack files (package.json, requirements.txt, pyproject.toml, go.mod, Cargo.toml), team-size indicators (number of contributors, CODEOWNERS), workflow indicators (.github/workflows, Dockerfile, CI configs), and any subdirectories that warrant their own CLAUDE.md (backend/, frontend/, database/, docs/, .github/). Return findings as a compact JSON object. Under 250 words.
Use the **general-purpose** subagent only for research that requires synthesising findings across multiple agents (e.g. comparing detected stack against template registry). Keep agent prompts self-contained and ask for short, structured reports.
---
## Phase 2: Analysis - Determine Action
+115
View File
@@ -0,0 +1,115 @@
---
description: Walk every CLAUDE.md in the project, prune stale references, enforce the 150-line cap, and re-chain root ↔ subdirectory files.
permissions:
allow:
- Bash(ls:*)
- Bash(find:*)
- Bash(git status:*)
- Bash(git diff:*)
- Bash(wc:*)
- Bash(grep:*)
- Bash(cat:*)
- Bash(test:*)
- Read
- Edit
- Write
- Glob
- Grep
- Skill
hooks:
- matcher: ""
once: true
commands:
- echo "Starting CLAUDE.md sync workflow"
---
# /sync-claude-md — CLAUDE.md Sync & Cleanup
This command keeps every CLAUDE.md in the project current, lean, and chained. Apply the Karpathy behavioural guidelines (`~/.claude/skills/karpathy-guidelines/SKILL.md`) while running it: state assumptions, keep changes surgical, define verification per step.
---
## Phase 1: Inventory
Discover every CLAUDE.md in the project (skipping vendor directories) and report sizes.
!`find . -name "CLAUDE.md" -type f -not -path "./node_modules/*" -not -path "./.git/*" -not -path "./vendor/*" -not -path "./dist/*" -not -path "./build/*" -print -exec wc -l {} \;`
Then capture the project signal that drives staleness checks:
!`ls -la package.json requirements.txt pyproject.toml go.mod Cargo.toml 2>/dev/null || true`
!`git status --short 2>/dev/null || echo "Not a git repository"`
!`git diff --name-status HEAD~10 -- . 2>/dev/null | head -50 || true`
---
## Phase 2: Per-File Audit
For each CLAUDE.md found, run the `claude-md-enhancer` skill's analyzer to compute:
- Current line count (hard cap: **150 lines**)
- Sections present and their freshness
- Anti-patterns (TODO/placeholder text, hardcoded secrets, generic content)
- References to files, directories, packages, or scripts that may be stale
Stale references to flag and remove unless the user objects:
1. **Dependency references** — packages mentioned in CLAUDE.md but absent from `package.json` / `requirements.txt` / `pyproject.toml` / `go.mod` / `Cargo.toml`.
2. **File / directory references** — paths in the project structure section that no longer exist on disk.
3. **Script references** — commands in Quick Reference / Common Operations that point to removed npm scripts or Makefile targets.
4. **Modular link targets**`[Backend Guidelines](backend/CLAUDE.md)` or `@backend/CLAUDE.md` imports where the target file no longer exists.
5. **Version drift** — version numbers / "What's New in vX.Y" sections referencing releases older than what `CHANGELOG.md` shows as current.
For each finding, show the offending line(s) with file:line references before editing.
---
## Phase 3: Enforce the 150-Line Cap
Any CLAUDE.md exceeding 150 lines must be split. Prefer this order:
1. **Move detail to existing sub-files.** If `backend/CLAUDE.md` exists, push backend-specific content there.
2. **Create a new sub-file** in the appropriate directory (e.g. `database/CLAUDE.md`) using `claude-md-enhancer.generate_context_file()`. The generator automatically prepends a back-link to the root.
3. **Update the root file's navigation** — both the human-readable bullets and the `@path/to/CLAUDE.md` chain imports — using `claude-md-enhancer`.
After splitting, re-validate every modified file with `BestPracticesValidator` and confirm line count ≤ 150.
---
## Phase 4: Re-chain Root ↔ Sub Files
Verify the bidirectional chain:
- Root CLAUDE.md must contain a `Quick Navigation` block listing every existing sub-CLAUDE.md, plus a `@<relative-path>` import line for each.
- Every sub-CLAUDE.md must contain a back-link at the top pointing to `../CLAUDE.md` (or the correct relative path) with both a markdown link and a `@../CLAUDE.md` import.
Repair any missing or broken chain links. Remove chain entries for sub-files that have been deleted.
---
## Phase 5: Cleanup & Report
After edits, regenerate validator output for each file and show:
- Files modified
- Lines removed (stale content)
- Sections added / split / removed
- Final line count per file (must all be ≤ 150)
- Remaining warnings the user should review manually
Do not commit. Leave the diff staged-but-uncommitted so the user can review with `git diff` and choose when to commit.
---
## When to Run
- After completing a feature, major refactor, or dependency change.
- When `claude-md-guardian` flags drift on session start.
- Whenever any single CLAUDE.md grows past ~120 lines (warning threshold).
- Before cutting a release — keeps documentation truthful at the tag boundary.
## Companion Tools
- `/enhance-claude-md` — initialise or upgrade a CLAUDE.md when one is missing or thin.
- `claude-md-guardian` agent — runs sync automatically on session start when changes are detected.
- `karpathy-guidelines` skill — behavioural rules applied to every edit this command makes.
+26 -11
View File
@@ -178,7 +178,8 @@ Write-Host ""
Write-Info "Installation will create:"
Write-Host " • Skill: $skillsDir\claudeforge-skill\"
Write-Host " • Skill: $skillsDir\karpathy-guidelines\"
Write-Host " • Command: $commandsDir\enhance-claude-md\"
Write-Host " • Command: $commandsDir\enhance-claude-md.md"
Write-Host " • Command: $commandsDir\sync-claude-md.md"
Write-Host " • Agent: $agentsDir\claude-md-guardian.md"
Write-Host ""
@@ -231,17 +232,29 @@ if (Test-Path $nestedKarpathy) {
}
Write-Success "Karpathy guidelines installed → $karpathyPath\"
# Install slash command
Write-Info "Installing /enhance-claude-md command..."
$commandPath = "$commandsDir\enhance-claude-md"
if (Test-Path $commandPath) {
Write-Warning "Existing command found. Creating backup..."
# Install slash commands. Each .md file in command/ becomes its own
# top-level command file so it registers as /<name>. README.md is skipped.
Write-Info "Installing slash commands..."
# Migrate legacy bundle directory if present.
$legacyBundle = "$commandsDir\enhance-claude-md"
if (Test-Path $legacyBundle) {
Write-Warning "Legacy command bundle found. Creating backup..."
$backupName = "enhance-claude-md.backup.$(Get-Date -Format 'yyyyMMdd_HHmmss')"
Move-Item -Path $commandPath -Destination "$commandsDir\$backupName" -Force
Move-Item -Path $legacyBundle -Destination "$commandsDir\$backupName" -Force
Write-Success "Backup created"
}
Copy-Item -Path "command" -Destination $commandPath -Recurse -Force
Write-Success "Command installed → $commandPath\"
Get-ChildItem -Path "command" -Filter "*.md" -File | Where-Object { $_.Name -ne "README.md" } | ForEach-Object {
$cmdTarget = Join-Path $commandsDir $_.Name
if (Test-Path $cmdTarget) {
Write-Warning "Existing $($_.Name) found. Creating backup..."
$backupName = "$($_.Name).backup.$(Get-Date -Format 'yyyyMMdd_HHmmss')"
Move-Item -Path $cmdTarget -Destination (Join-Path $commandsDir $backupName) -Force
}
Copy-Item -Path $_.FullName -Destination $cmdTarget -Force
Write-Success "Command installed → $cmdTarget"
}
# Install guardian agent
Write-Info "Installing claude-md-guardian agent..."
@@ -363,12 +376,14 @@ Write-Host ""
if ($scope -eq "user-level") {
Write-Host " Remove-Item -Recurse -Force ~\.claude\skills\claudeforge-skill"
Write-Host " Remove-Item -Recurse -Force ~\.claude\skills\karpathy-guidelines"
Write-Host " Remove-Item -Recurse -Force ~\.claude\commands\enhance-claude-md"
Write-Host " Remove-Item -Force ~\.claude\commands\enhance-claude-md.md"
Write-Host " Remove-Item -Force ~\.claude\commands\sync-claude-md.md"
Write-Host " Remove-Item -Force ~\.claude\agents\claude-md-guardian.md"
} else {
Write-Host " Remove-Item -Recurse -Force .\.claude\skills\claudeforge-skill"
Write-Host " Remove-Item -Recurse -Force .\.claude\skills\karpathy-guidelines"
Write-Host " Remove-Item -Recurse -Force .\.claude\commands\enhance-claude-md"
Write-Host " Remove-Item -Force .\.claude\commands\enhance-claude-md.md"
Write-Host " Remove-Item -Force .\.claude\commands\sync-claude-md.md"
Write-Host " Remove-Item -Force .\.claude\agents\claude-md-guardian.md"
}
Write-Host ""
+28 -8
View File
@@ -159,7 +159,8 @@ echo ""
print_info "Installation will create:"
echo " • Skill: $SKILLS_DIR/claudeforge-skill/"
echo " • Skill: $SKILLS_DIR/karpathy-guidelines/"
echo " • Command: $COMMANDS_DIR/enhance-claude-md/"
echo " • Command: $COMMANDS_DIR/enhance-claude-md.md"
echo " • Command: $COMMANDS_DIR/sync-claude-md.md"
echo " • Agent: $AGENTS_DIR/claude-md-guardian.md"
echo ""
@@ -203,15 +204,32 @@ cp -r skill/karpathy-guidelines "$SKILLS_DIR/karpathy-guidelines"
rm -rf "$SKILLS_DIR/claudeforge-skill/karpathy-guidelines"
print_success "Karpathy guidelines installed → $SKILLS_DIR/karpathy-guidelines/"
# Install slash command
print_info "Installing /enhance-claude-md command..."
# Install slash commands. Each .md file in command/ is installed as its own
# top-level command file so it registers as /<name> rather than as a nested
# /<dir>:<name>. README.md and other non-command files are skipped.
print_info "Installing slash commands..."
# Migrate legacy bundle directory if present.
if [ -d "$COMMANDS_DIR/enhance-claude-md" ]; then
print_warning "Existing command found. Creating backup..."
print_warning "Legacy command bundle found. Creating backup..."
mv "$COMMANDS_DIR/enhance-claude-md" "$COMMANDS_DIR/enhance-claude-md.backup.$(date +%Y%m%d_%H%M%S)"
print_success "Backup created"
fi
cp -r command "$COMMANDS_DIR/enhance-claude-md"
print_success "Command installed → $COMMANDS_DIR/enhance-claude-md/"
for cmd_file in command/*.md; do
cmd_basename=$(basename "$cmd_file")
# Skip the directory's own README.
if [ "$cmd_basename" = "README.md" ]; then
continue
fi
cmd_target="$COMMANDS_DIR/$cmd_basename"
if [ -f "$cmd_target" ]; then
print_warning "Existing $cmd_basename found. Creating backup..."
mv "$cmd_target" "$cmd_target.backup.$(date +%Y%m%d_%H%M%S)"
fi
cp "$cmd_file" "$cmd_target"
print_success "Command installed → $cmd_target"
done
# Install guardian agent
print_info "Installing claude-md-guardian agent..."
@@ -319,12 +337,14 @@ echo ""
if [ "$SCOPE" == "user-level" ]; then
echo " rm -rf ~/.claude/skills/claudeforge-skill"
echo " rm -rf ~/.claude/skills/karpathy-guidelines"
echo " rm -rf ~/.claude/commands/enhance-claude-md"
echo " rm -f ~/.claude/commands/enhance-claude-md.md"
echo " rm -f ~/.claude/commands/sync-claude-md.md"
echo " rm -f ~/.claude/agents/claude-md-guardian.md"
else
echo " rm -rf ./.claude/skills/claudeforge-skill"
echo " rm -rf ./.claude/skills/karpathy-guidelines"
echo " rm -rf ./.claude/commands/enhance-claude-md"
echo " rm -f ./.claude/commands/enhance-claude-md.md"
echo " rm -f ./.claude/commands/sync-claude-md.md"
echo " rm -f ./.claude/agents/claude-md-guardian.md"
fi
echo ""
+6 -5
View File
@@ -294,7 +294,7 @@ Analyzes existing CLAUDE.md files to identify structure, sections, and quality i
Validates CLAUDE.md files against best practices and Anthropic guidelines.
**Key Functions**:
- `validate_length()` - Check file length (warn if >300 lines)
- `validate_length()` - Check file length (hard cap: 150 lines; warn from 120)
- `validate_structure()` - Verify required sections present
- `validate_formatting()` - Check markdown formatting quality
- `validate_completeness()` - Ensure critical information included
@@ -367,10 +367,11 @@ Before finalizing any CLAUDE.md generation:
## Template Categories
### By Size
- **Minimal** (50 lines) - Solo developers, prototypes, hackathons
- **Core** (100-150 lines) - Small teams, MVPs, standard projects
- **Detailed** (200-300 lines) - Large teams, production systems, enterprise
### By Size (single CLAUDE.md cap: 150 lines)
- **Minimal** (≤ 75 lines) - Solo developers, prototypes, hackathons
- **Core** (100 lines) - Small teams, MVPs, standard projects
- **Detailed** (≤ 125 lines) - Medium teams, production systems
- **Comprehensive** (≤ 150 lines + modular sub-files) - Large teams, enterprise; spread detail across chained sub-CLAUDE.md files instead of growing the root
### By Project Type
- **Web App** - Frontend-focused (React, Vue, Angular)
+17 -10
View File
@@ -165,17 +165,23 @@ class CLAUDEMDAnalyzer:
issues = []
# Check file length
if self.line_count > 400:
if self.line_count > 250:
issues.append({
"type": "length_critical",
"severity": "high",
"message": f"File is too long ({self.line_count} lines). Recommended: split into modular files."
"message": f"File is too long ({self.line_count} lines). Hard cap is 150; split into modular files."
})
elif self.line_count > 300:
elif self.line_count > 150:
issues.append({
"type": "length_warning",
"severity": "high",
"message": f"File exceeds the 150-line cap ({self.line_count} lines). Split now."
})
elif self.line_count > 120:
issues.append({
"type": "length_warning",
"severity": "medium",
"message": f"File exceeds recommended 300 lines ({self.line_count} lines). Consider splitting."
"message": f"File is approaching the 150-line cap ({self.line_count} lines)."
})
# Check if file is too short
@@ -238,12 +244,13 @@ class CLAUDEMDAnalyzer:
"""
score = 0
# Length appropriateness (25 points)
if 50 <= self.line_count <= 300:
# Length appropriateness (25 points). Hard cap is 150 lines; anything
# above that loses points sharply because it indicates context bloat.
if 50 <= self.line_count <= 150:
score += 25
elif 30 <= self.line_count < 50 or 300 < self.line_count <= 400:
elif 30 <= self.line_count < 50 or 150 < self.line_count <= 200:
score += 15
elif self.line_count > 400:
elif self.line_count > 200:
score += 5
else:
score += 10
@@ -329,9 +336,9 @@ class CLAUDEMDAnalyzer:
recommendations.append(f"CRITICAL: {issue['message']}")
# Length recommendations
if self.line_count > 300:
if self.line_count > 150:
recommendations.append(
"Reduce root CLAUDE.md to <150 lines - move detailed guides to context-specific files"
"Reduce this CLAUDE.md to <=150 lines (hard cap) - move detail to context-specific files and chain them via @path imports"
)
elif self.line_count < 30:
recommendations.append(
+36 -11
View File
@@ -99,7 +99,8 @@ class ContentGenerator:
context: Context name ('backend', 'frontend', 'database', etc.)
Returns:
Context-specific CLAUDE.md content
Context-specific CLAUDE.md content with a back-link to the root
CLAUDE.md so Claude can navigate back up the chain.
"""
generators = {
'backend': self._generate_backend_file,
@@ -110,7 +111,17 @@ class ContentGenerator:
}
generator = generators.get(context, self._generate_generic_context_file)
return generator()
body = generator()
# Depth-aware back-link: most context dirs are one level deep, but
# ``.github`` may sit at the repo root next to the root CLAUDE.md.
rel_root = "../CLAUDE.md"
backlink = (
"> Parent context: see the root [CLAUDE.md]"
f"({rel_root}) for project-wide guidelines and behavioural rules.\n"
f"> Chained import: `@{rel_root}`\n\n"
)
return backlink + body
def _generate_backend_file(self) -> str:
"""Generate backend-specific CLAUDE.md."""
@@ -412,22 +423,36 @@ class ContentGenerator:
return sections
def _generate_navigation_section(self, template: Dict[str, Any]) -> List[str]:
"""Generate navigation section for modular architecture."""
"""Generate navigation section for modular architecture.
Emits both human-readable markdown links and Claude Code ``@`` imports
so the chained CLAUDE.md files are loaded automatically when the root
file is read.
"""
project_type = self.project_context.get('type')
links = []
targets: List[tuple] = [] # (label, relative_path)
if project_type == 'fullstack':
links.append("- [Backend Guidelines](backend/CLAUDE.md)")
links.append("- [Frontend Guidelines](frontend/CLAUDE.md)")
links.append("- [Database Operations](database/CLAUDE.md)")
targets.append(("Backend Guidelines", "backend/CLAUDE.md"))
targets.append(("Frontend Guidelines", "frontend/CLAUDE.md"))
targets.append(("Database Operations", "database/CLAUDE.md"))
if 'cicd' in self.project_context.get('workflows', []):
links.append("- [CI/CD Workflows](.github/CLAUDE.md)")
targets.append(("CI/CD Workflows", ".github/CLAUDE.md"))
if not links:
links.append("- [Add links to context-specific CLAUDE.md files]")
if not targets:
return ["- [Add links to context-specific CLAUDE.md files]"]
return links
lines: List[str] = []
for label, path in targets:
lines.append(f"- [{label}]({path})")
lines.append("")
lines.append("Chained context (Claude Code auto-imports these):")
lines.append("")
for _, path in targets:
lines.append(f"@{path}")
return lines
def _generate_core_principles(self, template: Dict[str, Any], max_count: int = 7) -> List[str]:
"""Generate core principles list."""
+8 -4
View File
@@ -78,7 +78,11 @@ class TemplateSelector:
}
}
# Team size templates
# Team size templates. All targets stay <= MAX_LINES_PER_FILE (150) so any
# single CLAUDE.md remains within the hard cap; larger projects spread
# content across modular sub-files instead of growing the root file.
MAX_LINES_PER_FILE = 150
TEAM_SIZE_TEMPLATES = {
"solo": {
"target_lines": 75,
@@ -87,19 +91,19 @@ class TemplateSelector:
"detail_level": "concise"
},
"small": {
"target_lines": 125,
"target_lines": 100,
"complexity": "core",
"focus": "Core guidelines, collaboration basics",
"detail_level": "moderate"
},
"medium": {
"target_lines": 200,
"target_lines": 125,
"complexity": "detailed",
"focus": "Team coordination, process standardization",
"detail_level": "comprehensive"
},
"large": {
"target_lines": 275,
"target_lines": 150,
"complexity": "comprehensive",
"focus": "Enterprise standards, governance",
"detail_level": "extensive"
+4 -3
View File
@@ -12,9 +12,10 @@ import re
class BestPracticesValidator:
"""Validates CLAUDE.md files against best practices and guidelines."""
# Maximum recommended line count
MAX_RECOMMENDED_LINES = 300
WARNING_THRESHOLD_LINES = 200
# Hard cap: every CLAUDE.md (root or modular) must stay under this.
# Modular split is required when content would exceed this cap.
MAX_RECOMMENDED_LINES = 150
WARNING_THRESHOLD_LINES = 120
# Minimum content requirements
MIN_LINES = 20