Initial commit: ClaudeForge v1.0.0

This commit is contained in:
Reza Rezvani
2025-11-12 11:19:48 +01:00
commit 37422c1667
42 changed files with 11812 additions and 0 deletions
+129
View File
@@ -0,0 +1,129 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
[INSERT CONTACT METHOD].
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
+47
View File
@@ -0,0 +1,47 @@
---
name: Bug Report
about: Report a bug or issue with ClaudeForge
title: '[BUG] '
labels: bug
assignees: ''
---
## Bug Description
A clear and concise description of the bug.
## Steps to Reproduce
1. Go to '...'
2. Run command '...'
3. See error '...'
## Expected Behavior
What you expected to happen.
## Actual Behavior
What actually happened.
## Environment
- **OS:** [e.g., macOS 13.5, Windows 11, Ubuntu 22.04]
- **Claude Code Version:** [e.g., 2.1.0]
- **ClaudeForge Version:** [e.g., 1.0.0]
- **Installation Method:** [user-level / project-level]
## Additional Context
Add any other context, screenshots, or logs about the problem.
## Relevant Files
If applicable, attach:
- Error logs
- Generated CLAUDE.md file
- Project structure
## Possible Solution
If you have ideas on how to fix this, please share.
+48
View File
@@ -0,0 +1,48 @@
---
name: Feature Request
about: Suggest a new feature or enhancement for ClaudeForge
title: '[FEATURE] '
labels: enhancement
assignees: ''
---
## Feature Description
A clear and concise description of the feature you'd like to see.
## Problem It Solves
What problem does this feature address? Why is it needed?
## Proposed Solution
Describe how you envision this feature working.
## Alternatives Considered
What other approaches did you consider? Why is your proposal better?
## Use Case
Provide a specific example of how you would use this feature.
**Example:**
```
/enhance-claude-md --with-new-feature
# Result: [Expected outcome]
```
## Additional Context
Add any other context, screenshots, or mockups about the feature request.
## Implementation Ideas
If you have technical ideas on how to implement this, please share.
## Would You Contribute?
- [ ] I'd like to work on this feature myself
- [ ] I can help test this feature
- [ ] I'm just suggesting an idea
+58
View File
@@ -0,0 +1,58 @@
# Pull Request
## Description
Provide a clear and concise description of your changes.
## Type of Change
- [ ] Bug fix (non-breaking change fixing an issue)
- [ ] New feature (non-breaking change adding functionality)
- [ ] Breaking change (fix or feature causing existing functionality to change)
- [ ] Documentation update
- [ ] Code refactoring
- [ ] Performance improvement
- [ ] Test addition/improvement
## Related Issues
Fixes #(issue_number)
## Changes Made
- Change 1
- Change 2
- Change 3
## Testing Performed
Describe the tests you ran to verify your changes:
- [ ] Tested installation (./install.sh)
- [ ] Tested slash command (/enhance-claude-md)
- [ ] Tested guardian agent
- [ ] Tested on new project
- [ ] Tested on existing project with CLAUDE.md
- [ ] Tested modular architecture
**Test Environment:**
- OS: [e.g., macOS 13.5]
- Claude Code Version: [e.g., 2.1.0]
## Screenshots (if applicable)
Add screenshots to help explain your changes.
## Checklist
- [ ] My code follows the project's style guidelines
- [ ] I have commented my code where necessary
- [ ] I have updated the documentation (if needed)
- [ ] I have updated CHANGELOG.md with my changes
- [ ] My changes generate no new warnings
- [ ] I have tested my changes thoroughly
- [ ] All existing tests still pass
## Additional Notes
Any additional information reviewers should know.
+162
View File
@@ -0,0 +1,162 @@
name: Validate ClaudeForge
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
validate-python:
name: Validate Python Modules
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Check Python syntax
run: |
python3 -m py_compile skill/analyzer.py
python3 -m py_compile skill/validator.py
python3 -m py_compile skill/generator.py
python3 -m py_compile skill/template_selector.py
python3 -m py_compile skill/workflow.py
- name: Test module imports
run: |
cd skill
python3 -c "from analyzer import CLAUDEMDAnalyzer; print('analyzer.py: OK')"
python3 -c "from validator import BestPracticesValidator; print('validator.py: OK')"
python3 -c "from generator import ContentGenerator; print('generator.py: OK')"
python3 -c "from template_selector import TemplateSelector; print('template_selector.py: OK')"
python3 -c "from workflow import InitializationWorkflow; print('workflow.py: OK')"
validate-structure:
name: Validate Repository Structure
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Check required files
run: |
test -f README.md || exit 1
test -f CHANGELOG.md || exit 1
test -f LICENSE || exit 1
test -f CLAUDE.md || exit 1
test -f install.sh || exit 1
test -f install.ps1 || exit 1
- name: Check required directories
run: |
test -d skill || exit 1
test -d command || exit 1
test -d agent || exit 1
test -d docs || exit 1
test -d examples || exit 1
- name: Check skill files
run: |
test -f skill/SKILL.md || exit 1
test -f skill/analyzer.py || exit 1
test -f skill/validator.py || exit 1
test -f skill/generator.py || exit 1
test -f skill/template_selector.py || exit 1
test -f skill/workflow.py || exit 1
- name: Check command files
run: |
test -f command/enhance-claude-md.md || exit 1
- name: Check agent files
run: |
test -f agent/claude-md-guardian.md || exit 1
validate-documentation:
name: Validate Documentation
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Check docs directory
run: |
test -f docs/INSTALLATION.md || exit 1
test -f docs/QUICK_START.md || exit 1
test -f docs/ARCHITECTURE.md || exit 1
test -f docs/TROUBLESHOOTING.md || exit 1
test -f docs/CONTRIBUTING.md || exit 1
- name: Check examples directory
run: |
test -f examples/basic-usage.md || exit 1
test -f examples/modular-setup.md || exit 1
test -f examples/integration-examples.md || exit 1
validate-installers:
name: Validate Installer Scripts
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
steps:
- uses: actions/checkout@v3
- name: Check install.sh syntax
if: matrix.os != 'windows-latest'
run: |
bash -n install.sh
- name: Test install.sh (dry run)
if: matrix.os != 'windows-latest'
run: |
# Create temporary directory
mkdir -p /tmp/test-claude
export HOME=/tmp/test-claude
# Test script runs without errors
# (Don't actually install, just check syntax and structure)
grep -q "claudeforge-skill" install.sh || exit 1
grep -q "enhance-claude-md" install.sh || exit 1
grep -q "claude-md-guardian" install.sh || exit 1
lint-markdown:
name: Lint Markdown Files
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Check markdown files exist
run: |
find . -name "*.md" -type f | wc -l
- name: Basic markdown validation
run: |
# Check for broken reference-style links
! grep -r "\[.*\]\[.*\]" --include="*.md" . | grep -v "http" | grep -v ".md"
security-check:
name: Security Checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Check for hardcoded secrets
run: |
# Check for common secret patterns
! grep -r "API_KEY\s*=" . --include="*.py" --include="*.md"
! grep -r "password\s*=" . --include="*.py" --include="*.md"
! grep -r "token\s*=" . --include="*.py" --include="*.md"
- name: Check for TODO/FIXME
run: |
# Warn about TODO/FIXME (not fail)
grep -r "TODO\|FIXME" . --include="*.py" --include="*.md" || true
+87
View File
@@ -0,0 +1,87 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Virtual Environments
venv/
ENV/
env/
.venv
# IDEs
.vscode/
.idea/
*.swp
*.swo
*~
.DS_Store
# Claude Code
.claude/cache/
.claude/logs/
.claude/temp/
# Testing
.pytest_cache/
.coverage
htmlcov/
.tox/
.nox/
# Distribution
*.zip
*.tar.gz
*.dmg
*.exe
# Logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# OS
Thumbs.db
.DS_Store
.Spotlight-V100
.Trashes
# Temporary files
*.tmp
*.bak
*.backup
.#*
\#*#
# Node modules (if any testing added)
node_modules/
# Backup files from installer
*.backup.*
# Legacy directories (old structure, now reorganized)
claude-md-enhancer/
slash-commands-enhance-claude-md/
subagent-claude-md-guardian/
# Optional project files
PROJECT_SUMMARY.md
+211
View File
@@ -0,0 +1,211 @@
# Changelog
All notable changes to ClaudeForge will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
---
## [1.0.0] - 2025-11-12
### 🎉 Initial Release
ClaudeForge v1.0.0 marks the first stable release of the automated CLAUDE.md management toolkit for Claude Code projects.
### Added
#### Core Features
- **Interactive Initialization Workflow** - Conversational workflow that explores repositories, detects project context, and creates customized CLAUDE.md files
- **100% Native Format Compliance** - All generated files follow official Claude Code format with project structure diagrams, setup instructions, and architecture sections
- **Intelligent Analysis** - Comprehensive file analysis with quality scoring (0-100) and actionable recommendations
- **Smart Enhancement** - Automatic addition of missing sections and structure improvements
- **Best Practice Validation** - Validation against Anthropic guidelines and community standards
#### Components
- **Skill:** `claudeforge-skill` v1.0.0
- `analyzer.py` - File analysis and quality scoring (382 lines)
- `validator.py` - Best practices validation (429 lines)
- `generator.py` - Content generation (480 lines)
- `template_selector.py` - Template selection logic (467 lines)
- `workflow.py` - Interactive initialization workflow (432 lines)
- **Slash Command:** `/enhance-claude-md` v1.0.0
- Multi-phase discovery workflow (Discovery → Analysis → Task)
- Auto-detection of initialization vs. enhancement scenarios
- Integration with skill and guardian agent
- **Guardian Agent:** `claude-md-guardian` v1.0.0
- Background maintenance and auto-sync
- Smart change detection (git-based)
- Token-efficient updates using haiku model
- Milestone-aware triggering
#### Templates
- **7 Reference CLAUDE.md Templates:**
- `minimal-solo-CLAUDE.md` - Solo developer projects
- `core-small-team-CLAUDE.md` - Small team projects (2-9 devs)
- `python-api-CLAUDE.md` - Python API projects
- `modular-root-CLAUDE.md` - Root navigation for modular setups
- `modular-backend-CLAUDE.md` - Backend-specific guidelines
- `modular-frontend-CLAUDE.md` - Frontend-specific guidelines
- Reference examples covering TypeScript, Python, React, FastAPI, and more
#### Tech Stack Support
- **Frontend:** React, Vue, Angular, TypeScript, JavaScript
- **Backend:** Node.js, Python (Django, FastAPI, Flask), Go, Java (Spring Boot), Ruby (Rails)
- **Databases:** PostgreSQL, MongoDB, Redis, MySQL
- **Infrastructure:** Docker, Kubernetes, CI/CD systems
#### Team Size Adaptation
- **Solo** - Minimal guidelines (50-75 lines)
- **Small (<10)** - Core guidelines (100-150 lines)
- **Medium (10-50)** - Detailed guidelines (200-300 lines)
- **Large (50+)** - Comprehensive guidelines (modular architecture)
#### Installation
- **Automated Installers:**
- `install.sh` - macOS/Linux bash installer
- `install.ps1` - Windows PowerShell installer
- **Installation Options:**
- User-level (`~/.claude/`) - Available in all projects
- Project-level (`./.claude/`) - Current project only
- **One-line Installation:**
```bash
curl -fsSL https://raw.githubusercontent.com/alirezarezvani/ClaudeForge/main/install.sh | bash
```
#### Documentation
- **Root Documentation:**
- `README.md` - Comprehensive project overview with badges and quick start
- `CHANGELOG.md` - Version history (this file)
- `LICENSE` - MIT License
- **Detailed Guides:**
- `docs/INSTALLATION.md` - Installation guide with troubleshooting
- `docs/QUICK_START.md` - 5-minute tutorial
- `docs/ARCHITECTURE.md` - Component architecture and data flow
- `docs/TROUBLESHOOTING.md` - Common issues and solutions
- `docs/CONTRIBUTING.md` - Contribution guidelines
- **Usage Examples:**
- `examples/basic-usage.md` - Basic usage scenarios
- `examples/modular-setup.md` - Modular architecture examples
- `examples/integration-examples.md` - Integration patterns
#### GitHub Integration
- **CI/CD:**
- `.github/workflows/validate.yml` - Automated validation workflow
- Quality checks on pull requests
- **Community Templates:**
- `.github/ISSUE_TEMPLATE/bug_report.md` - Bug report template
- `.github/ISSUE_TEMPLATE/feature_request.md` - Feature request template
- `.github/PULL_REQUEST_TEMPLATE.md` - Pull request template
- `.github/CODE_OF_CONDUCT.md` - Code of conduct
#### Quality Hooks
- **Pre-commit Hook** - `hooks/pre-commit.sh`
- Validates CLAUDE.md file quality before commits
- Ensures best practices compliance
- Optional installation during setup
### Quality Metrics
- **Quality Score Calculation (0-100):**
- Length appropriateness: 25 points
- Section completeness: 25 points
- Formatting quality: 20 points
- Content specificity: 15 points
- Modular organization: 15 points
- **Validation Checks (5 categories):**
- File length (20-300 lines recommended)
- Structure (required sections present)
- Formatting (markdown quality)
- Completeness (essential content)
- Anti-patterns (security, placeholders)
### Technical Details
- **Python Version:** 3.7+ compatible
- **Dependencies:** Standard library only (no external dependencies)
- **Total Code:** ~2,190 lines across 5 modules
- **Claude Code Compatibility:** 2.0+
- **Operating Systems:** macOS, Linux, Windows
### What's Next
See [Unreleased](#unreleased) section for planned features.
---
## [Unreleased]
### Planned for v1.1.0
- **Additional Templates:**
- Rust/Cargo projects
- Mobile (React Native, Flutter)
- Desktop (Electron, Tauri)
- Microservices architecture template
- **Enhanced Detection:**
- Improved tech stack detection accuracy
- Project phase detection from git history
- Team size estimation from commit patterns
- **Quality Improvements:**
- More granular quality scoring
- Section-specific recommendations
- Automated fix suggestions
### Planned for v1.2.0
- **VS Code Extension** (Future)
- Inline CLAUDE.md editing
- Real-time validation
- Quick actions panel
- **GitHub Actions** (Enhanced)
- Automated CLAUDE.md generation on repo creation
- PR checks for CLAUDE.md quality
- Auto-update on dependency changes
- **Advanced Hooks:**
- Pre-push validation
- Post-merge synchronization
- Automated quality reports
### Under Consideration
- **Multi-language Support** - i18n for generated content
- **Custom Template Creation** - User-defined templates
- **AI-Powered Suggestions** - Context-aware recommendations
- **Integration with Other Tools** - Slack, Discord notifications
- **Web Dashboard** - Project-wide CLAUDE.md management
- **Analytics** - Usage patterns and effectiveness metrics
---
## Version History
| Version | Date | Status | Highlights |
|---------|------|--------|------------|
| 1.0.0 | 2025-11-12 | ✅ Stable | Initial release with full feature set |
---
## Contributing
See [CONTRIBUTING.md](docs/CONTRIBUTING.md) for details on how to contribute to ClaudeForge.
---
## Links
- **Repository:** https://github.com/alirezarezvani/ClaudeForge
- **Issues:** https://github.com/alirezarezvani/ClaudeForge/issues
- **Discussions:** https://github.com/alirezarezvani/ClaudeForge/discussions
- **Releases:** https://github.com/alirezarezvani/ClaudeForge/releases
---
**Made with ❤️ for the Claude Code community**
+469
View File
@@ -0,0 +1,469 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
---
## Project Overview
**ClaudeForge** is a comprehensive toolkit for automated CLAUDE.md creation, enhancement, and maintenance for Claude Code projects. The repository consists of three 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
---
## Architecture
### Component Interaction Flow
```
User Project
/enhance-claude-md (Slash Command)
[Phase 1: Discovery] → [Phase 2: Analysis] → [Phase 3: Task]
claude-md-guardian (Agent) OR Direct Skill Invocation
claudeforge-skill (Python Modules)
workflow.py → analyzer.py → validator.py → template_selector.py → generator.py
CLAUDE.md Created/Updated with 100% Native Format
```
### Python Module Architecture
The skill consists of 5 core modules (~2,190 lines):
**workflow.py (432 lines)** - `InitializationWorkflow` class
- Orchestrates interactive initialization for new projects
- Methods: `check_claude_md_exists()`, `generate_exploration_prompt()`, `analyze_discoveries()`
- Detects: project type, tech stack, team size, development phase, workflows
- Returns: Project context dictionary for template selection
**analyzer.py (382 lines)** - `CLAUDEMDAnalyzer` class
- Analyzes existing CLAUDE.md files
- Methods: `analyze_file()`, `detect_sections()`, `calculate_quality_score()`, `generate_recommendations()`
- Quality scoring: 0-100 based on length (25pts), completeness (25pts), formatting (20pts), specificity (15pts), modularity (15pts)
- Returns: Analysis report with quality score and actionable recommendations
**validator.py (429 lines)** - `BestPracticesValidator` class
- Validates against Anthropic guidelines
- Methods: `validate_length()`, `validate_structure()`, `validate_formatting()`, `validate_completeness()`, `validate_all()`
- Checks: file length (20-300 lines), required sections, markdown formatting, anti-patterns
- Returns: Validation report with pass/fail status and detailed issues
**template_selector.py (467 lines)** - `TemplateSelector` class
- Selects appropriate template based on context
- Methods: `select_template()`, `customize_template()`, `recommend_modular_structure()`
- Logic: Maps project type + team size → template complexity
- Returns: Template configuration with target line count and modular recommendation
**generator.py (480 lines)** - `ContentGenerator` class
- Generates new or enhanced CLAUDE.md content
- Methods: `generate_root_file()`, `generate_context_file()`, `generate_section()`, `merge_with_existing()`
- Supports: Root files, context-specific files (backend/, frontend/, database/), individual sections
- Returns: Complete CLAUDE.md content with 100% native format compliance
### Critical Validation Rule
All generated CLAUDE.md files MUST include:
- Project structure (ASCII tree diagram)
- File structure explanations
- Setup & installation instructions
- Architecture section (for complex projects)
- Validation against `/update-claude-md` slash command format
- Cross-check against reference examples in `skill/examples/`
---
## Installation & Testing
### Test Installation Scripts
```bash
# macOS/Linux
./install.sh
# Choose option 1 (user-level) or 2 (project-level)
# Verify installation at ~/.claude/ or ./.claude/
# Windows
.\install.ps1
# Same options as above
# Verify components installed:
ls -la ~/.claude/skills/claudeforge-skill/
ls -la ~/.claude/commands/enhance-claude-md/
ls -la ~/.claude/agents/claude-md-guardian.md
```
### Directory Structure After Installation
```
~/.claude/ # User-level installation
├── skills/
│ └── claudeforge-skill/ # Copied from skill/
│ ├── SKILL.md
│ ├── analyzer.py
│ ├── validator.py
│ ├── generator.py
│ ├── template_selector.py
│ ├── workflow.py
│ └── examples/ # 7 reference templates
├── commands/
│ └── enhance-claude-md/ # Copied from command/
│ └── enhance-claude-md.md
└── agents/
└── claude-md-guardian.md # Copied from agent/
```
---
## Development Workflow
### Modifying Python Modules
When updating skill modules (analyzer.py, generator.py, etc.):
1. Edit files in `skill/` directory
2. Test changes by reinstalling: `./install.sh` (choose option 2 for project-level testing)
3. Test skill invocation in Claude Code: `/enhance-claude-md`
4. Validate output against reference examples in `skill/examples/`
5. Update `CHANGELOG.md` with changes
### Modifying Slash Command
When updating `/enhance-claude-md` command:
1. Edit `command/enhance-claude-md.md`
2. Key sections to modify:
- **Phase 1 (Discovery)**: Bash commands that check project state
- **Phase 2 (Analysis)**: Logic that determines initialize vs. enhance
- **Phase 3 (Task)**: Skill/agent invocation logic
3. Test by reinstalling command: `cp command/enhance-claude-md.md ~/.claude/commands/enhance-claude-md/`
4. Restart Claude Code and test: `/enhance-claude-md`
### Modifying Guardian Agent
When updating `claude-md-guardian` agent:
1. Edit `agent/claude-md-guardian.md`
2. Key YAML frontmatter fields:
- `tools`: Limited to Bash, Read, Write, Edit, Grep, Glob, Skill
- `model`: Set to `haiku` for token efficiency
- `color`: Visual indicator (purple)
3. Agent workflow phases:
- Phase 1: Assessment (check git changes)
- Phase 2: Analysis (determine scope)
- Phase 3: Update (invoke skill for targeted updates)
4. Test: `cp agent/claude-md-guardian.md ~/.claude/agents/`
### Adding New Templates
To add a new reference template (e.g., Rust, mobile):
1. Create new template file in `skill/examples/`
2. Follow native format structure:
- Project structure diagram (ASCII tree)
- Setup & installation
- Architecture section
- Tech-specific guidelines
3. Update `skill/examples/README.md` with new template description
4. Update `template_selector.py` logic to detect when to use new template
5. Add test case in `skill/sample_input.json`
---
## Testing & Validation
### Manual Testing Checklist
**Test New Project Initialization:**
```bash
# 1. Create test project
mkdir test-project && cd test-project
git init
npm init -y # or create package.json
# 2. Run slash command
/enhance-claude-md
# 3. Verify Claude:
# - Explores repository
# - Detects TypeScript/Node project
# - Shows discoveries
# - Asks for confirmation
# - Creates CLAUDE.md with native format
```
**Test Existing Project Enhancement:**
```bash
# 1. Create basic CLAUDE.md
echo "# CLAUDE.md\n\n## Tech Stack\n- TypeScript" > CLAUDE.md
# 2. Run slash command
/enhance-claude-md
# 3. Verify Claude:
# - Analyzes existing file
# - Calculates quality score (0-100)
# - Identifies missing sections (Project Structure, Setup, etc.)
# - Asks to enhance
# - Adds missing native format sections
```
**Test Guardian Agent:**
```bash
# 1. Make significant changes
npm install react # Add new dependency
mkdir src/components # New directory
# 2. Start new Claude Code session (triggers SessionStart)
# 3. Verify agent:
# - Detects changes via git diff
# - Updates CLAUDE.md automatically
# - Reports: "Tech Stack: Added react", "Project Structure: Updated diagram"
```
### Quality Validation
All generated CLAUDE.md files should pass these checks:
```python
# Use validator.py
validator = BestPracticesValidator(content)
results = validator.validate_all()
# Expected passes:
# - File length: 20-300 lines (or modular if >300)
# - Structure: Required sections present
# - Formatting: Valid markdown, proper heading hierarchy
# - Completeness: Code examples, tech stack, workflows
# - Anti-patterns: No hardcoded secrets, no TODOs/placeholders
```
---
## File Organization
### Repository Structure
```
ClaudeForge/
├── skill/ # Python modules (core capability)
│ ├── analyzer.py # File analysis
│ ├── validator.py # Best practices validation
│ ├── generator.py # Content generation
│ ├── template_selector.py # Template selection logic
│ ├── workflow.py # Interactive initialization
│ ├── SKILL.md # Skill definition (YAML frontmatter)
│ ├── sample_input.json # Test scenarios (6 examples)
│ ├── expected_output.json # Expected outputs
│ └── examples/ # 7 reference templates
├── command/ # Slash command definition
│ ├── enhance-claude-md.md # Multi-phase workflow
│ └── README.md
├── agent/ # Guardian agent definition
│ ├── claude-md-guardian.md # Background maintenance agent
│ └── README.md
├── docs/ # Documentation
│ ├── INSTALLATION.md
│ ├── QUICK_START.md
│ ├── ARCHITECTURE.md
│ ├── TROUBLESHOOTING.md
│ └── CONTRIBUTING.md
├── examples/ # Usage examples (markdown)
├── hooks/ # Quality hooks (pre-commit)
├── .github/ # GitHub templates & workflows
│ ├── workflows/validate.yml # CI/CD validation
│ ├── ISSUE_TEMPLATE/
│ ├── PULL_REQUEST_TEMPLATE.md
│ └── CODE_OF_CONDUCT.md
├── install.sh # macOS/Linux installer
├── install.ps1 # Windows installer
├── README.md # Project overview
├── CHANGELOG.md # Version history
├── LICENSE # MIT License
└── CLAUDE.md # This file
```
### Important: Dual Directory Structure
Note the duplication: `claude-md-enhancer/` (legacy) and `skill/` (current). When making changes:
- **Always edit `skill/`** - This is the active version used by installers
- `claude-md-enhancer/` is kept for reference but not actively maintained
---
## Common Operations
### Update Reference Templates
```bash
# Edit template
vim skill/examples/python-api-CLAUDE.md
# Test template selection
# 1. Create test project matching template criteria
mkdir test-python-api && cd test-python-api
echo "fastapi" > requirements.txt
# 2. Run slash command and verify template is used
/enhance-claude-md
```
### Update Quality Scoring Logic
```bash
# Edit analyzer.py
vim skill/analyzer.py
# Update calculate_quality_score() method
# Current scoring breakdown:
# - length_appropriateness: 25 points (20-300 lines ideal)
# - section_completeness: 25 points (required sections present)
# - formatting_quality: 20 points (markdown, headings, code blocks)
# - content_specificity: 15 points (project-specific, not generic)
# - modular_organization: 15 points (context files if needed)
# Test scoring
python3 -c "
from skill.analyzer import CLAUDEMDAnalyzer
with open('test-CLAUDE.md') as f:
analyzer = CLAUDEMDAnalyzer(f.read())
report = analyzer.analyze_file()
print(f'Quality Score: {report[\"quality_score\"]}/100')
"
```
### Update Installer Scripts
```bash
# Edit installer
vim install.sh # or install.ps1
# Key sections:
# - Installation paths (user-level vs project-level)
# - Component copying (skill, command, agent)
# - Backup logic (existing installations)
# - Quality hooks installation (optional)
# Test installer
./install.sh
# Choose test option and verify all components copied correctly
```
---
## Integration Points
### Skill ↔ Slash Command
The slash command invokes the skill via:
```markdown
# In command/enhance-claude-md.md, Phase 3:
I can invoke the `claude-md-enhancer` skill directly to handle the appropriate workflow based on what I discovered above.
```
Claude Code recognizes the skill name `claude-md-enhancer` and calls Python modules.
### Skill ↔ Guardian Agent
The agent uses the skill as its core capability:
```yaml
# In agent/claude-md-guardian.md:
tools: Bash, Read, Write, Edit, Grep, Glob, Skill
```
Agent invokes skill with: `Skill: claude-md-enhancer` in agent workflow.
### Agent ↔ Git
Agent detects changes via git commands:
```bash
git diff --name-status HEAD~10
git log --since="1 week ago" --oneline --no-merges
git diff HEAD~10 -- package.json requirements.txt
```
Triggers update when:
- 5+ files modified
- New dependencies added
- New directories created
- Manual invocation after milestone
---
## Tech Stack Detection Logic
The workflow and template selector detect tech stacks via:
**Frontend Detection:**
- React: `package.json` contains `"react"`
- Vue: `package.json` contains `"vue"`
- Angular: `angular.json` exists
- TypeScript: `tsconfig.json` exists
**Backend Detection:**
- Node.js: `package.json` exists
- Python: `requirements.txt`, `pyproject.toml`, `setup.py`
- Go: `go.mod` exists
- Java: `pom.xml`, `build.gradle`
- Rust: `Cargo.toml` exists
**Database Detection:**
- PostgreSQL: `package.json` or `requirements.txt` contains "pg" or "psycopg2"
- MongoDB: Contains "mongoose" or "pymongo"
- Redis: Contains "redis" or "ioredis"
Update detection logic in: `skill/workflow.py``_detect_tech_stack()` method
---
## Repository Naming
**Project Name:** ClaudeForge
**GitHub URL:** https://github.com/alirezarezvani/ClaudeForge
**Skill Name:** `claudeforge-skill` (installed as directory name)
**Slash Command:** `/enhance-claude-md` (fixed name, cannot be changed by user)
**Agent Name:** `claude-md-guardian` (file name)
When updating references:
- `skill/SKILL.md` → YAML frontmatter `name: claude-md-enhancer` (kept for compatibility)
- `README.md` → Use "ClaudeForge" as display name
- `install.sh` → Copies to `claudeforge-skill/` directory
- Internal documentation → Use "ClaudeForge" consistently
---
## Version Management
**Current Version:** 1.0.0 (see CHANGELOG.md)
**Versioning:** Semantic Versioning (MAJOR.MINOR.PATCH)
When releasing new version:
1. Update `CHANGELOG.md` with changes under new version header
2. Update version in `README.md` badge
3. Update version in `skill/SKILL.md` bottom section
4. Create git tag: `git tag -a v1.1.0 -m "Release v1.1.0"`
5. Push tag: `git push origin v1.1.0`
6. Create GitHub release with CHANGELOG excerpt
---
## License & Copyright
**License:** MIT License
**Copyright:** © 2025 Alireza Rezvani
All files should include appropriate copyright headers. The LICENSE file is authoritative.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Alireza Rezvani
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+278
View File
@@ -0,0 +1,278 @@
# ClaudeForge
> **Automated CLAUDE.md creation, enhancement, and maintenance for Claude Code projects**
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Version](https://img.shields.io/badge/version-1.0.0-blue.svg)](https://github.com/alirezarezvani/ClaudeForge/releases)
[![Claude Code](https://img.shields.io/badge/Claude_Code-2.0%2B-purple.svg)](https://claude.com/claude-code)
ClaudeForge is a comprehensive toolkit that eliminates the tedious process of manually creating and maintaining CLAUDE.md files. With intelligent analysis, automated generation, and background maintenance, your CLAUDE.md files stay perfectly synchronized with your codebase.
---
## ✨ Features
- 🚀 **Interactive Initialization** - Explores your repository, detects project context, and creates customized CLAUDE.md files through conversational workflow
-**Intelligent Analysis** - Scans and evaluates existing CLAUDE.md files with quality scoring (0-100) and actionable recommendations
- 🔧 **Smart Enhancement** - Adds missing sections and improves structure automatically
- 🛡️ **Background Maintenance** - Guardian agent keeps CLAUDE.md synchronized with codebase changes
- 📦 **Modular Architecture** - Supports complex projects with context-specific files (backend/, frontend/, database/)
- 🎯 **100% Native Format** - All generated files follow official Claude Code format with project structure diagrams, setup instructions, and architecture sections
- 🛠️ **Tech Stack Customization** - Tailors guidelines to TypeScript, Python, Go, React, Vue, FastAPI, and more
- 👥 **Team Size Adaptation** - Adjusts complexity based on team size (solo, small, medium, large)
---
## 📦 What's Included
### 1. **Skill** (`claudeforge-skill`)
Core capability for CLAUDE.md analysis, generation, validation, and enhancement
### 2. **Slash Command** (`/enhance-claude-md`)
Interactive interface with multi-phase discovery workflow
### 3. **Guardian Agent** (`claude-md-guardian`)
Background agent for automatic CLAUDE.md maintenance and synchronization
---
## 🚀 Quick Start
### Installation
#### **macOS / Linux**
```bash
curl -fsSL https://raw.githubusercontent.com/alirezarezvani/ClaudeForge/main/install.sh | bash
```
#### **Windows (PowerShell)**
```powershell
iwr https://raw.githubusercontent.com/alirezarezvani/ClaudeForge/main/install.ps1 -useb | iex
```
#### **Manual Installation**
```bash
git clone https://github.com/alirezarezvani/ClaudeForge.git
cd ClaudeForge
./install.sh # or .\install.ps1 on Windows
```
### Usage
After installation, restart Claude Code and run:
```bash
/enhance-claude-md
```
That's it! The command will:
1. ✅ Explore your project structure
2. ✅ Detect tech stack and project type
3. ✅ Show discoveries and ask for confirmation
4. ✅ Create customized CLAUDE.md file(s)
5. ✅ Apply best practices and native format
---
## 💡 Use Cases
### **New Project (No CLAUDE.md)**
```bash
/enhance-claude-md
# Claude explores your repository and responds:
#
# "Based on my exploration, here's what I discovered:
#
# 📦 Project Type: Full-Stack Application
# 🛠️ Tech Stack: TypeScript, React, Node.js, PostgreSQL, Docker
# 👥 Team Size: Small (5 developers)
# 🚀 Development Phase: MVP
#
# 📋 Recommended Structure:
# - Root CLAUDE.md (navigation hub, ~100 lines)
# - backend/CLAUDE.md (API guidelines, ~150 lines)
# - frontend/CLAUDE.md (React guidelines, ~175 lines)
#
# Would you like me to create these files?"
#
# You: "Yes"
#
# ✅ CLAUDE.md created (108 lines)
# ✅ backend/CLAUDE.md created (156 lines)
# ✅ frontend/CLAUDE.md created (182 lines)
```
### **Existing Project (Needs Improvement)**
```bash
/enhance-claude-md
# Claude analyzes your current CLAUDE.md:
#
# "Quality Score: 65/100
#
# Missing Sections:
# - Project Structure (ASCII diagram)
# - Setup & Installation
# - Architecture
#
# Would you like me to enhance your CLAUDE.md with these sections?"
#
# You: "Yes"
#
# ✅ CLAUDE.md enhanced (+2 sections, quality score: 65 → 88)
```
### **Background Maintenance**
```bash
# You start a new Claude Code session
# Guardian agent automatically checks for changes
#
# ✅ CLAUDE.md updated:
# - Tech Stack: Added 2 dependencies (react-query, tailwindcss)
# - Project Structure: Updated diagram with new components/ directory
# - Setup & Installation: New environment variables
#
# Changes: 3 sections, 12 lines
```
---
## 📚 Documentation
| Document | Description |
|----------|-------------|
| [Quick Start Guide](docs/QUICK_START.md) | 5-minute tutorial to get started |
| [Installation Guide](docs/INSTALLATION.md) | Detailed installation instructions and troubleshooting |
| [Architecture Overview](docs/ARCHITECTURE.md) | How components work together |
| [Troubleshooting](docs/TROUBLESHOOTING.md) | Common issues and solutions |
| [Contributing Guide](docs/CONTRIBUTING.md) | How to contribute to ClaudeForge |
---
## 📖 Examples
See the [examples/](examples/) directory for:
- Basic usage scenarios
- Modular architecture setup
- Integration with existing projects
- Advanced customization
---
## 🔧 Components Deep Dive
### **Skill: claudeforge-skill**
**Core Capabilities:**
- **Analysis** - Scans existing CLAUDE.md files for quality and completeness
- **Validation** - Checks against Anthropic guidelines and best practices
- **Generation** - Creates new CLAUDE.md files from scratch
- **Enhancement** - Adds missing sections and improves structure
- **Template Selection** - Chooses appropriate templates based on project context
**Quality Scoring (0-100):**
- Length appropriateness (25 pts)
- Section completeness (25 pts)
- Formatting quality (20 pts)
- Content specificity (15 pts)
- Modular organization (15 pts)
### **Slash Command: /enhance-claude-md**
**Multi-Phase Workflow:**
1. **Discovery** - Checks for existing CLAUDE.md, examines project structure
2. **Analysis** - Determines appropriate action (initialize vs. enhance)
3. **Task** - Invokes skill or agent to execute workflow
### **Agent: claude-md-guardian**
**Background Maintenance:**
- **Auto-Sync** - Updates CLAUDE.md based on detected changes
- **Smart Detection** - Only updates when significant changes occur
- **Token-Efficient** - Uses haiku model for routine updates
- **Milestone-Aware** - Triggers after feature completion, refactoring, etc.
---
## 🎯 Requirements
- **Claude Code** 2.0 or later
- **Git** (recommended for change detection)
- **Operating Systems:** macOS, Linux, Windows (PowerShell)
---
## 🤝 Contributing
We welcome contributions! Please see our [Contributing Guide](docs/CONTRIBUTING.md) for details.
### Quick Contribution Steps:
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
---
## 🐛 Issues & Support
- **Bug Reports:** [GitHub Issues](https://github.com/alirezarezvani/ClaudeForge/issues)
- **Feature Requests:** [GitHub Discussions](https://github.com/alirezarezvani/ClaudeForge/discussions)
- **Documentation:** [docs/](docs/)
---
## 📄 License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
**Copyright © 2025 Alireza Rezvani**
---
## 🙏 Acknowledgments
- Built for the [Claude Code](https://claude.com/claude-code) community
- Inspired by best practices from Anthropic's official documentation
- Special thanks to all contributors and early adopters
---
## 🚦 Project Status
**Version:** 1.0.0
**Status:** ✅ Stable & Production-Ready
**Last Updated:** November 12, 2025
---
## 📊 Quick Stats
- **7** reference CLAUDE.md templates included
- **100%** native Claude Code format compliance
- **5** Python modules
- **3** integrated components (skill, command, agent)
- **10+** usage examples and scenarios
---
## 🌟 Star History
If you find ClaudeForge helpful, please consider giving it a star on GitHub!
[![Star History Chart](https://api.star-history.com/svg?repos=alirezarezvani/ClaudeForge&type=Date)](https://star-history.com/#alirezarezvani/ClaudeForge&Date)
---
<div align="center">
**[⬆ Back to Top](#claudeforge)**
Made with ❤️ for the Claude Code community
</div>
+405
View File
@@ -0,0 +1,405 @@
# claude-md-guardian Agent
Background maintenance agent that keeps CLAUDE.md files synchronized with project changes.
## Overview
The `claude-md-guardian` is a specialized Claude Code agent that monitors your project and automatically updates CLAUDE.md files when significant changes occur. It works independently in the background without interrupting development workflows.
## Key Features
- 🔄 **Auto-Sync**: Updates CLAUDE.md based on git changes
- 🎯 **Smart Detection**: Only updates when significant changes occur
-**Token-Efficient**: Uses haiku model for routine updates
- 🔇 **Silent Operation**: No interruptions during active development
- 📦 **Milestone-Aware**: Triggers after feature completion, refactoring, etc.
-**Native Format**: Ensures 100% Claude Code format compliance
## When It's Invoked
### Automatic Triggers
**SessionStart** (beginning of each session):
- Checks git changes since last update
- Silent exit if no significant changes
- Updates only when needed
### Manual Triggers
**After Major Milestones**:
- ✅ Feature completion
- ✅ Major refactoring
- ✅ New dependencies added
- ✅ Architecture changes
- ✅ Configuration updates
**Via Commands**:
- `/enhance-claude-md` slash command
- Direct invocation: "Claude, invoke claude-md-guardian"
## Installation
### Option 1: User-Level (Recommended)
Available in all your Claude Code projects:
```bash
# Copy agent to user directory
cp generated-agents/claude-md-guardian/claude-md-guardian.md ~/.claude/agents/
# Restart Claude Code
```
### Option 2: Project-Level
Available only in current project:
```bash
# Create agents directory
mkdir -p .claude/agents
# Copy agent
cp generated-agents/claude-md-guardian/claude-md-guardian.md .claude/agents/
# Restart Claude Code
```
### Option 3: With SessionStart Hook
Automatically check for updates at session start:
```bash
# Add to .claude/settings.json or ~/.claude/settings.json
{
"hooks": {
"SessionStart": {
"command": "echo 'Checking CLAUDE.md updates...'",
"timeout": 5000,
"description": "Trigger claude-md-guardian awareness"
}
}
}
```
**Note**: The hook creates awareness, but the agent only updates if significant changes detected.
## Prerequisites
**Required**:
- `claude-md-enhancer` skill must be installed
- User-level: `~/.claude/skills/claude-md-enhancer/`
- Project-level: `.claude/skills/claude-md-enhancer/`
**Optional** (but recommended):
- `/enhance-claude-md` slash command
- Git repository (for change detection)
## Usage Examples
### Example 1: Session Start (Auto)
```
# You start Claude Code session
# Agent checks changes automatically
Agent: ✓ CLAUDE.md current (no significant changes detected)
# Silent - continues session normally
```
### Example 2: After Feature Completion (Manual)
```
You: "Feature complete - user authentication system implemented"
You: "Claude, invoke claude-md-guardian to update CLAUDE.md"
Agent: Analyzing changes for user authentication feature...
Updates applied:
- Architecture: Added authentication flow
- API Documentation: New /auth endpoints
- Security Practices: JWT implementation notes
- Database: User table schema
✅ CLAUDE.md updated to reflect authentication system
```
### Example 3: New Dependencies Added
```
# You added react-query and tailwindcss to package.json
# Next session starts
Agent: Detected 2 new dependencies.
Updating CLAUDE.md:
- Tech Stack section (added React Query, Tailwind CSS)
- Setup & Installation (updated installation steps)
✅ CLAUDE.md updated (2 sections modified)
```
### Example 4: Via Slash Command
```bash
/enhance-claude-md
# Slash command discovers changes and invokes agent
Agent: 🔄 Analyzing project changes...
Updates applied:
- Project Structure: New components/ directory
- File Structure: Updated directory explanations
- Common Commands: Added new npm scripts
✅ CLAUDE.md synchronized (3 sections modified)
```
## What the Agent Does
### 1. Change Detection
Analyzes git history for:
- New dependencies (package.json, requirements.txt, etc.)
- New directories/file structure changes
- Configuration updates (.env.example, config files)
- Architecture pattern changes
### 2. Scope Determination
**Minor Updates** (1-2 sections):
- New dependency added
- Single directory created
- Minor configuration change
**Moderate Updates** (3-4 sections):
- Multiple dependencies
- Structure reorganization
- Feature completion
**Major Updates** (Full quality check):
- Architecture refactoring
- Multiple major changes
- First-time generation
### 3. Targeted Updates
Uses `claude-md-enhancer` skill to update only affected sections:
- **Tech Stack**: Dependency changes
- **Project Structure**: Directory changes
- **Setup & Installation**: Configuration changes
- **Architecture**: Pattern changes
- **Common Commands**: Script changes
### 4. Validation
Ensures all updates follow:
- Native Claude Code format (project structure diagrams, etc.)
- 100% format compliance
- Critical validation rule
## Token Efficiency
### Model Selection
**haiku** (default):
- Routine updates
- Dependency additions
- Minor structure changes
- Cost-effective for background tasks
**sonnet** (escalation):
- Major architecture changes
- First-time CLAUDE.md generation
- Complex modular setups
### Update Strategy
**Targeted** (default):
- Edit specific sections only
- Preserve existing content
- Minimal token usage
**Full** (when necessary):
- Complete quality check
- Comprehensive enhancement
- Only for major milestones
## Coordination with Other Agents
### Works AFTER These Agents Complete
- `rr-frontend-engineer` - Frontend features
- `rr-backend-engineer` - Backend APIs
- `rr-fullstack-engineer` - Integration work
- Any agent marking tasks "completed"
### Independent Operation
- ✅ Doesn't block other agents
- ✅ Runs in background
- ✅ No interruptions to development
- ✅ Reports when done
### Never Invoked During
- ❌ Active development by other agents
- ❌ Minor code edits (typos, comments)
- ❌ Test-only changes
- ❌ Multiple times per session (unless milestones)
## Output Formats
### Silent (No Changes)
```
✓ CLAUDE.md current (no significant changes detected)
```
### Concise (Minor Updates)
```
✅ CLAUDE.md updated:
- Tech Stack: Added 2 dependencies
- Setup: New environment variable
Changes: 2 sections, 8 lines
```
### Detailed (Major Milestone)
```
🔄 Major changes detected - Full quality check performed
Updates applied:
- Architecture: New microservices pattern documented
- Tech Stack: 5 new dependencies added
- Setup & Installation: Updated for monorepo
- Common Commands: Added 3 new scripts
Quality Score: 75 → 88 (+13)
Changes: 6 sections, 45 lines
✅ CLAUDE.md fully synchronized
```
## Configuration
### Sensitivity Adjustment
In the agent file, you can adjust when updates trigger:
```yaml
# Current thresholds (in agent logic):
- Minimum files changed: 5
- Dependency threshold: 1 new dependency
- Structure change: 1 new directory
```
### Hook Timeout
```json
{
"hooks": {
"SessionStart": {
"timeout": 5000 // 5 seconds
}
}
}
```
## Troubleshooting
### Agent Not Triggering
**Problem**: Agent doesn't update CLAUDE.md
**Solutions**:
1. Check `claude-md-enhancer` skill is installed
2. Verify git repository exists
3. Ensure changes meet significance threshold
4. Manually invoke: "Claude, invoke claude-md-guardian"
### Too Many Updates
**Problem**: Agent updates too frequently
**Solutions**:
1. Increase significance thresholds in agent
2. Remove SessionStart hook
3. Use manual invocation only
### Skill Not Found Error
**Problem**: "claude-md-enhancer skill not found"
**Solution**:
```bash
# Install the skill
cp -r generated-skills/claude-md-enhancer ~/.claude/skills/
# Restart Claude Code
```
## Integration
### With claude-md-enhancer Skill
The agent uses this skill as its core capability:
```
Agent detects changes → Invokes skill → Skill updates sections → Agent validates
```
### With /enhance-claude-md Command
The slash command can invoke the agent:
```bash
/enhance-claude-md
# → Discovery → Analysis → Invokes claude-md-guardian → Updates
```
### With Development Workflow
```
1. Developer works on feature
2. Other agents (frontend/backend) build code
3. Feature marked complete
4. claude-md-guardian invoked
5. CLAUDE.md updated
6. Ready for next feature
```
## Best Practices
### When to Invoke Manually
- ✅ After completing major feature
- ✅ After significant refactoring
- ✅ Before creating pull request
- ✅ After adding multiple dependencies
- ✅ After architecture changes
### When to Let Auto-Trigger Handle It
- ✅ Session start checks
- ✅ Routine dependency updates
- ✅ Minor structure changes
### When NOT to Invoke
- ❌ During active development
- ❌ After minor code changes
- ❌ Multiple times without actual changes
## Version
- **Version**: 1.0.0
- **Last Updated**: November 2025
- **Compatible**: Claude Code 2.0+
- **Dependencies**: claude-md-enhancer skill v1.0.0+
## Related Resources
- **Skill**: `generated-skills/claude-md-enhancer/`
- **Slash Command**: `generated-commands/enhance-claude-md/`
- **Agent File**: `generated-agents/claude-md-guardian/claude-md-guardian.md`
---
**Quick Start**: Copy agent to `~/.claude/agents/`, restart Claude Code, and the guardian will automatically maintain your CLAUDE.md files!
+317
View File
@@ -0,0 +1,317 @@
---
name: claude-md-guardian
description: Background agent that maintains and updates CLAUDE.md files based on project changes. Invoked at session start and after major milestones (feature completion, refactoring, new dependencies, architecture changes). Works independently without interrupting other agents.
tools: Bash, Read, Write, Edit, Grep, Glob, Skill
model: haiku
color: purple
field: documentation
expertise: intermediate
mcp_tools: none
---
# CLAUDE.md Guardian Agent
I'm the CLAUDE.md Guardian - a background maintenance agent that keeps your project's CLAUDE.md file(s) synchronized with actual code changes.
## When I'm Invoked
**Automatically** (SessionStart hook):
- Beginning of each Claude Code session
- Checks git changes since last update
- Silent if no significant changes
**Manually** (After milestones):
- Feature completion
- Major refactoring
- New dependencies added
- Architecture changes
- Via `/enhance-claude-md` slash command
## What I Do
### 1. Detect Changes (Token-Efficient)
```bash
# Check recent changes
git diff --name-status HEAD~10 | head -20
# Focus on significant changes
git log --since="1 week ago" --oneline --no-merges | head -10
# Check for new files/dependencies
git diff HEAD~10 -- package.json requirements.txt go.mod Cargo.toml pom.xml 2>/dev/null | head -50
```
### 2. Determine Update Necessity
**Update CLAUDE.md if**:
- ✅ New major dependencies added
- ✅ Project structure changed (new directories)
- ✅ Architecture patterns modified
- ✅ Configuration files updated significantly
- ✅ Manual invocation (milestone reached)
**Skip update if**:
- ❌ Only minor code changes
- ❌ No structural changes
- ❌ Less than 5 files modified
- ❌ Only test files changed
### 3. Apply Concise Updates
I invoke the `claude-md-enhancer` skill to:
- Analyze current CLAUDE.md quality
- Identify missing sections (if any)
- Update specific sections based on changes:
- **Tech Stack**: New dependencies
- **Project Structure**: New directories
- **Architecture**: Pattern changes
- **Common Commands**: New scripts
- **Setup & Installation**: Configuration changes
**Token-Efficient Approach**:
- Only update affected sections
- Preserve existing content
- Concise diff-based updates
- No full regeneration unless necessary
## My Workflow
### Phase 1: Assessment (Quick)
```
1. Check git status and recent changes
2. Determine if CLAUDE.md update needed
3. If no significant changes → exit silently
4. If changes detected → proceed to Phase 2
```
### Phase 2: Analysis (Targeted)
```
1. Identify what changed:
- New dependencies? → Update Tech Stack
- New directories? → Update Project Structure
- Config changes? → Update Setup & Installation
- Architecture changes? → Update Architecture section
2. Calculate scope:
- Minor: Update 1-2 sections
- Moderate: Update 3-4 sections
- Major: Full quality check + enhancement
```
### Phase 3: Update (Concise)
```
1. Invoke claude-md-enhancer skill
2. Request targeted updates only
3. Apply changes using Edit tool (not Write)
4. Verify native format compliance
5. Report changes made
```
## My Execution Pattern
**Background Operation**:
- I run AFTER other agents complete their work
- I don't interrupt ongoing development
- I work independently
- I use minimal tokens (haiku model)
**Coordination**:
- SessionStart: Check changes → silent exit if none
- Post-milestone: Wait for completion signal → update
- Manual: Immediate response when invoked
## Example Usage
### Automatic (SessionStart)
```bash
# Session starts
# I check git changes automatically
# If significant changes detected:
"Detected 15 files changed since last CLAUDE.md update.
New dependencies: react-query, tailwindcss
New directory: src/components/
Updating CLAUDE.md:
- Tech Stack section (added React Query, Tailwind CSS)
- Project Structure (added components directory)
- Setup & Installation (updated installation steps)
✅ CLAUDE.md updated (3 sections modified)"
```
### Manual (After Feature Completion)
```bash
/enhance-claude-md
# Or direct invocation:
"Feature complete: user authentication system
Claude, invoke claude-md-guardian to update CLAUDE.md"
# I respond:
"Analyzing changes for user authentication feature...
Updates applied:
- Architecture: Added authentication flow
- API Documentation: New /auth endpoints
- Security Practices: JWT implementation notes
- Database: User table schema
✅ CLAUDE.md updated to reflect authentication system"
```
## Integration with claude-md-enhancer Skill
I use the `claude-md-enhancer` skill as my core capability:
```yaml
Skill: claude-md-enhancer
Purpose: CLAUDE.md generation and enhancement
Invocation: When updates needed
Mode: Enhancement (targeted section updates)
```
**My workflow with the skill**:
1. I detect what changed
2. I invoke skill with specific enhancement request
3. Skill analyzes + updates specific sections
4. I verify and report
## Integration with /enhance-claude-md Command
The slash command can invoke me:
```bash
/enhance-claude-md
# Command workflow:
# 1. Discovery phase → detects changes
# 2. Analysis phase → determines scope
# 3. Task phase → invokes me (claude-md-guardian)
# 4. I execute targeted updates
```
## Token Efficiency
**Why I use haiku model**:
- Most updates are routine (new dependencies, minor structure changes)
- haiku is sufficient for targeted section updates
- Saves tokens for development agents
**When I escalate to sonnet**:
- Major architecture changes requiring deep analysis
- First-time CLAUDE.md generation
- Complex modular architecture setup
## Safety & Validation
**Critical Validation Rule**:
"Always validate your output against official native examples before declaring complete."
**My validation checklist**:
- ✅ Project Structure diagram present
- ✅ Setup & Installation instructions current
- ✅ Architecture section reflects actual patterns
- ✅ Tech Stack lists all major dependencies
- ✅ Common Commands match package.json scripts
## Installation
### Option 1: User-Level (All Projects)
```bash
cp generated-agents/claude-md-guardian.md ~/.claude/agents/
```
### Option 2: Project-Level (Current Project)
```bash
mkdir -p .claude/agents
cp generated-agents/claude-md-guardian.md .claude/agents/
```
### Option 3: With SessionStart Hook
```json
{
"hooks": {
"SessionStart": {
"command": "echo 'Session started - checking CLAUDE.md updates'",
"timeout": 5000,
"description": "Trigger claude-md-guardian to check for CLAUDE.md updates"
}
}
}
```
**Note**: The hook triggers awareness, but I only update if changes detected.
## When NOT to Invoke Me
- ❌ During active development (wait for completion)
- ❌ For minor code edits (typo fixes, comments)
- ❌ When other agents are still running
- ❌ Multiple times per session (unless major milestone)
## Coordination with Other Agents
**I work AFTER**:
- rr-frontend-engineer completes feature
- rr-backend-engineer finishes API
- rr-fullstack-engineer integrates components
- Any agent marks task as "completed"
**I work INDEPENDENTLY**:
- Don't block other agents
- Run in background
- Report when done
- No interruptions
## Output Format
**Minimal (No changes)**:
```
✓ CLAUDE.md current (no significant changes detected)
```
**Concise (Updates applied)**:
```
✅ CLAUDE.md updated:
- Tech Stack: Added 2 dependencies
- Project Structure: Updated diagram
- Setup: New environment variable
Changes: 3 sections modified, 12 lines changed
```
**Detailed (Major milestone)**:
```
🔄 Major changes detected - Full quality check performed
Updates applied:
- Architecture: New microservices pattern documented
- Tech Stack: 5 new dependencies added
- Setup & Installation: Updated for monorepo structure
- Common Commands: Added 3 new scripts
Quality Score: 75 → 88 (+13)
Changes: 6 sections modified, 45 lines changed
✅ CLAUDE.md fully synchronized with project state
```
---
**Version**: 1.0.0
**Last Updated**: November 2025
**Dependencies**: claude-md-enhancer skill v1.0.0+
**Compatible**: Claude Code 2.0+
Remember: I'm a background guardian - silent when not needed, efficient when invoked, thorough when changes matter.
+390
View File
@@ -0,0 +1,390 @@
# /enhance-claude-md Slash Command
Initialize or enhance CLAUDE.md files using the `claude-md-enhancer` skill with interactive workflow and 100% native format compliance.
## Features
- **Multi-Phase Discovery**: Automatically detects if CLAUDE.md exists and determines appropriate action
- **Interactive Workflow**: For new projects, explores repository and asks for confirmation before creating files
- **Quality Analysis**: For existing projects, analyzes current CLAUDE.md and provides actionable recommendations
- **100% Native Format Compliance**: Generates files with project structure diagrams, setup instructions, architecture sections
- **Modular Architecture Support**: Creates context-specific CLAUDE.md files (backend/, frontend/, database/)
## Installation
### Option 1: Project-Level (Current Project Only)
```bash
# Copy command to your project
cp -r generated-commands/enhance-claude-md /path/to/your/project/.claude/commands/
# Or create symlink
ln -s $(pwd)/generated-commands/enhance-claude-md /path/to/your/project/.claude/commands/enhance-claude-md
```
### Option 2: User-Level (All Projects)
```bash
# Copy command to user commands directory
cp -r generated-commands/enhance-claude-md ~/.claude/commands/
# Restart Claude Code
```
## Usage
### Basic Usage (Auto-Detect)
```bash
/enhance-claude-md
```
Claude will:
1. Check if CLAUDE.md exists in your project
2. If **not found**: Run interactive initialization workflow
3. If **found**: Analyze and offer enhancement recommendations
### New Project (No CLAUDE.md)
When you run `/enhance-claude-md` on a new project:
```
Phase 1: Discovery
- Checks for existing CLAUDE.md files
- Examines project structure
- Reviews git status
Phase 2: Analysis
- Detects project type (web_app, api, fullstack, etc.)
- Identifies tech stack (TypeScript, Python, React, etc.)
- Estimates team size and development phase
Phase 3: Task
- Shows you the discoveries
- Asks for confirmation
- Creates customized CLAUDE.md file(s)
- Applies native format (project structure diagrams, setup, architecture)
```
**Example Output**:
```
Based on my exploration, here's what I discovered:
📦 Project Type: Full-Stack Application
🛠️ Tech Stack: TypeScript, React, Node.js, PostgreSQL
👥 Team Size: Small (5 developers)
🚀 Development Phase: MVP
📋 Recommended Structure:
- Root CLAUDE.md (~100 lines)
- backend/CLAUDE.md (~150 lines)
- frontend/CLAUDE.md (~175 lines)
Would you like me to create these files?
```
### Existing Project (CLAUDE.md exists)
When you run `/enhance-claude-md` on an existing project:
```
Phase 1: Discovery
- Finds existing CLAUDE.md
- Checks for modular files
Phase 2: Analysis
- Analyzes current file for quality
- Calculates quality score (0-100)
- Identifies missing sections
Phase 3: Task
- Shows quality report
- Recommends improvements
- Offers to enhance with missing sections
```
**Example Output**:
```
Current CLAUDE.md Quality Score: 65/100
Missing Sections:
- Project Structure (ASCII diagram)
- Setup & Installation
- Architecture
Issues:
- File length: 320 lines (recommend <300)
- No project structure diagram
- Missing setup instructions
Would you like me to enhance your CLAUDE.md with these sections?
```
## Command Structure
The command follows the **Multi-Phase Pattern** (similar to `codebase-analyze`):
### Phase 1: Discovery
- Checks for CLAUDE.md existence
- Examines project structure
- Reviews git status
### Phase 2: Analysis
- Determines appropriate workflow (initialize vs. enhance)
- Provides context about current state
### Phase 3: Task
- Invokes `claude-md-enhancer` skill
- Executes appropriate workflow based on analysis
## Prerequisites
**Required**:
- `claude-md-enhancer` skill must be installed
- Project-level: `.claude/skills/claude-md-enhancer/`
- User-level: `~/.claude/skills/claude-md-enhancer/`
**Recommended**:
- Git repository (for better context detection)
- Project files in place (package.json, requirements.txt, etc.)
## Advanced Usage
### Specify Project Type
```
/enhance-claude-md
"I need a CLAUDE.md for my Python FastAPI project with PostgreSQL"
```
### Request Modular Architecture
```
/enhance-claude-md
"Create a modular CLAUDE.md setup with separate files for backend, frontend, and database"
```
### Analyze Only
```
/enhance-claude-md
"Just analyze my current CLAUDE.md, don't make changes yet"
```
### Enhance Specific Sections
```
/enhance-claude-md
"Add Project Structure and Setup & Installation sections to my CLAUDE.md"
```
## Output
The command can invoke either the `claude-md-enhancer` skill directly OR the `claude-md-guardian` agent (recommended for maintenance).
### Option A: Direct Skill Invocation
The skill generates:
#### For New Projects
- **Root CLAUDE.md**: Navigation hub with native format sections
- **Context Files** (if modular): backend/CLAUDE.md, frontend/CLAUDE.md, etc.
**Native Format Sections Included**:
- Overview
- Project Structure (ASCII tree diagram)
- File Structure (directory explanations)
- Setup & Installation
- Architecture (for complex projects)
- Core Principles
- Tech Stack
- Development Workflow
- Testing Requirements
- Error Handling
- Common Commands
#### For Existing Projects
- **Quality Report**: Score, missing sections, issues, recommendations
- **Enhanced CLAUDE.md**: Updated with missing sections (if requested)
### Option B: Agent Invocation (Recommended for Maintenance)
The `claude-md-guardian` agent provides:
- **Auto-Sync**: Detects changes and updates CLAUDE.md automatically
- **Smart Detection**: Only updates when significant changes occur
- **Targeted Updates**: Modifies specific sections based on detected changes
- **Token-Efficient**: Uses haiku model for routine updates
- **Concise Reporting**: Reports only what changed
**Agent triggers on**:
- Feature completion
- Major refactoring
- New dependencies added
- Architecture changes
- Manual invocation via this command
**Agent output**:
```
✅ CLAUDE.md updated:
- Tech Stack: Added 2 dependencies
- Project Structure: Updated diagram
- Setup: New environment variable
Changes: 3 sections modified, 12 lines changed
```
## Validation
The command enforces the critical validation rule:
**"Always validate your output against official native examples before declaring complete."**
All generated CLAUDE.md files:
- Follow official `/update-claude-md` slash command format
- Include project structure diagrams
- Have setup & installation instructions
- Document architecture for complex projects
- Match native Claude Code format 100%
## Examples
### Example 1: New TypeScript React Project
```bash
/enhance-claude-md
```
**Claude Response**:
```
Discovered: TypeScript + React + Node.js project
Team size: Small (5 devs)
Phase: MVP
I'll create:
- CLAUDE.md (~125 lines) with full native format
Proceed?
```
### Example 2: Existing Project Missing Sections
```bash
/enhance-claude-md
```
**Claude Response**:
```
Quality Score: 55/100
Missing:
- Project Structure diagram
- Setup & Installation
- Architecture section
I can add these native format sections to improve quality to ~85/100.
Proceed?
```
### Example 3: Large Full-Stack Project
```bash
/enhance-claude-md
```
**Claude Response**:
```
Discovered: Full-stack TypeScript project
Recommend: Modular architecture
I'll create:
- Root CLAUDE.md (~100 lines)
- backend/CLAUDE.md (~200 lines)
- frontend/CLAUDE.md (~225 lines)
Proceed?
```
## Troubleshooting
### "Skill not found" error
**Solution**: Install the `claude-md-enhancer` skill first:
```bash
cp -r generated-skills/claude-md-enhancer ~/.claude/skills/
```
### Command not recognized
**Solution**: Ensure command is in correct location:
- Project: `.claude/commands/enhance-claude-md/enhance-claude-md.md`
- User: `~/.claude/commands/enhance-claude-md/enhance-claude-md.md`
Then restart Claude Code.
### No project structure detected
**Solution**: Ensure project has recognizable files:
- Node.js: `package.json`
- Python: `requirements.txt`, `pyproject.toml`
- Go: `go.mod`
- Rust: `Cargo.toml`
## Integration with claude-md-guardian Agent
This slash command can invoke the `claude-md-guardian` agent for automatic CLAUDE.md maintenance:
### How They Work Together
```
/enhance-claude-md (command)
Discovery → Analysis → Task
Invokes claude-md-guardian (agent)
Agent uses claude-md-enhancer (skill)
CLAUDE.md updated and synchronized
```
### When to Use the Agent
**Via this command**:
- After feature completion
- After major refactoring
- When new dependencies added
- After architecture changes
- For periodic synchronization
**Automatic** (with SessionStart hook):
- Beginning of each session
- Silent if no significant changes
- Updates only when needed
**See**: `generated-agents/claude-md-guardian-README.md` for complete agent documentation
## Related Resources
- **Skill Documentation**: `generated-skills/claude-md-enhancer/README.md`
- **Skill Examples**: `generated-skills/claude-md-enhancer/examples/`
- **Agent Documentation**: `generated-agents/claude-md-guardian-README.md`
- **Official Slash Command Reference**: `documentation/references/slash-command-update-claude-md-example.md`
## Version
- **Version**: 1.0.0
- **Last Updated**: November 2025
- **Compatible**: Claude Code 2.0+
- **Dependencies**: claude-md-enhancer skill v1.0.0+
---
**Quick Start**: Run `/enhance-claude-md` in any project to initialize or enhance your CLAUDE.md file with 100% native format compliance!
+99
View File
@@ -0,0 +1,99 @@
---
allowed-tools: Bash(ls:*), Bash(find:*), Bash(git status:*), Read, Glob, Skill
description: Initialize or enhance CLAUDE.md files using the claude-md-enhancer skill with interactive workflow and 100% native format compliance
---
# CLAUDE.md Enhancer Command
This command uses the `claude-md-enhancer` skill to initialize or enhance CLAUDE.md files for your project.
---
## Phase 1: Discovery - Check Current State
### Check if CLAUDE.md exists
!`ls -la CLAUDE.md 2>/dev/null || echo "CLAUDE.md not found"`
### Check for modular CLAUDE.md files
!`find . -name "CLAUDE.md" -type f -not -path "./node_modules/*" -not -path "./.git/*" | head -10`
### Get repository status
!`git status --short 2>/dev/null || echo "Not a git repository"`
### Check project structure
!`ls -la`
---
## Phase 2: Analysis - Determine Action
Based on the discovery above, I need to determine the appropriate action:
**If CLAUDE.md does NOT exist** → Interactive Initialization Workflow
**If CLAUDE.md exists** → Analysis and Enhancement Workflow
### For New Projects (No CLAUDE.md):
The `claude-md-enhancer` skill will:
1. Explore your repository structure
2. Detect project type, tech stack, team size, development phase
3. Show you the discoveries and ask for confirmation
4. Create customized CLAUDE.md file(s) after your approval
5. Apply 100% native format compliance (project structure diagrams, setup instructions, architecture sections)
### For Existing Projects (CLAUDE.md exists):
The `claude-md-enhancer` skill will:
1. Analyze current CLAUDE.md for quality and completeness
2. Calculate quality score (0-100)
3. Identify missing sections
4. Provide actionable recommendations
5. Offer to enhance with missing native format sections
---
## Phase 3: Task - Execute with Skill or Agent
### Option A: Direct Skill Invocation
I can invoke the `claude-md-enhancer` skill directly to handle the appropriate workflow based on what I discovered above.
The skill provides:
-**100% Native Format Compliance**: All generated files follow official Claude Code format with project structure diagrams, setup instructions, architecture sections, and file structure explanations
- 🆕 **Interactive Initialization**: For new projects, explores repository and asks for confirmation before creating files
-**Intelligent Analysis**: For existing projects, scans and evaluates for quality and completeness
- 🚀 **Smart Generation**: Creates customized CLAUDE.md files from scratch
- 🔧 **Enhancement**: Adds missing sections and improves existing files
- 📦 **Modular Architecture**: Supports context-specific files (backend/, frontend/, database/)
### Option B: Agent Invocation (Recommended for Maintenance)
For ongoing maintenance and automatic updates throughout your project lifecycle, I can invoke the `claude-md-guardian` agent instead:
**When to use the agent**:
- After feature completion
- After major refactoring
- When new dependencies are added
- After architecture changes
- For periodic CLAUDE.md synchronization
**Agent benefits**:
- 🔄 **Auto-Sync**: Updates CLAUDE.md based on detected changes
- 🎯 **Smart Detection**: Only updates when significant changes occur
-**Token-Efficient**: Uses haiku model for routine updates
- 📦 **Milestone-Aware**: Triggers after completion signals
-**Native Format**: Ensures 100% Claude Code format compliance
### Your Task
I'm ready to proceed. What would you like me to do?
**For new projects**: I'll run the interactive initialization workflow (skill)
**For existing projects**: I'll analyze your current CLAUDE.md and suggest improvements (skill)
**For maintenance**: I'll invoke claude-md-guardian agent to check for updates and synchronize
Please confirm how you'd like to proceed, or let me know if you have specific requirements (e.g., "Create a CLAUDE.md for my Python FastAPI project" or "Invoke claude-md-guardian to update my CLAUDE.md").
+548
View File
@@ -0,0 +1,548 @@
# Architecture Overview
Technical architecture and design decisions for ClaudeForge.
---
## System Design
### Component Architecture
```
┌─────────────────────────────────────────────────────────┐
│ User Project │
│ │
│ User runs: /enhance-claude-md │
└────────────────────┬────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ Slash Command (enhance-claude-md.md) │
│ │
│ Phase 1: Discovery - Check CLAUDE.md existence │
│ Phase 2: Analysis - Determine initialize/enhance │
│ Phase 3: Task - Invoke skill or agent │
└────────────────────┬────────────────────────────────────┘
┌───────────┴───────────┐
│ │
↓ ↓
┌──────────────────┐ ┌──────────────────┐
│ Guardian Agent │ │ Direct Skill │
│ (Background) │ │ Invocation │
│ │ │ │
│ • SessionStart │ │ • User request │
│ • Manual invoke │ │ • One-time gen │
└────────┬─────────┘ └─────────┬────────┘
│ │
└────────────┬───────────┘
┌────────────────────────┐
│ Skill: claudeforge │
│ │
│ Python Modules: │
│ • workflow.py │
│ • analyzer.py │
│ • validator.py │
│ • template_selector │
│ • generator.py │
└────────────┬───────────┘
┌────────────────────────┐
│ CLAUDE.md Output │
│ │
│ • Root file │
│ • Context files │
│ • Native format │
└────────────────────────┘
```
---
## Data Flow
### 1. New Project Initialization
```
1. User → /enhance-claude-md
2. Command checks: CLAUDE.md not found
3. Command → Skill (initialize mode)
4. Skill workflow.py:
- generate_exploration_prompt()
- Claude explores repository
- analyze_discoveries(exploration_results)
- Returns project_context
5. Skill template_selector.py:
- select_template(project_context)
- Returns template configuration
6. Skill generator.py:
- generate_root_file(template)
- Returns CLAUDE.md content
7. Skill validator.py:
- validate_all(generated_content)
- Returns validation report
8. Output → CLAUDE.md file(s) created
```
### 2. Existing Project Enhancement
```
1. User → /enhance-claude-md
2. Command checks: CLAUDE.md exists
3. Command → Skill (enhance mode)
4. Skill analyzer.py:
- analyze_file(current_content)
- calculate_quality_score()
- Returns analysis report
5. Skill validator.py:
- validate_all(current_content)
- Returns validation results
6. Skill shows user:
- Quality score (0-100)
- Missing sections
- Recommendations
7. User confirms enhancement
8. Skill generator.py:
- merge_with_existing(content, sections)
- Returns enhanced content
9. Output → CLAUDE.md updated
```
### 3. Background Maintenance
```
1. SessionStart event
2. Guardian agent triggered
3. Agent checks git changes:
- git diff --name-status HEAD~10
- git diff package.json requirements.txt
4. Agent determines significance:
- Files changed > 5?
- New dependencies?
- New directories?
5. If significant:
- Agent → Skill (enhance mode)
- Skill updates specific sections
- Agent validates changes
6. Output → CLAUDE.md synced
```
---
## Module Design
### workflow.py
**Purpose:** Interactive initialization for new projects
**Key Classes:**
- `InitializationWorkflow` - Main orchestrator
**Key Methods:**
```python
check_claude_md_exists() bool
generate_exploration_prompt() str
analyze_discoveries(results: Dict) Dict[str, Any]
_detect_project_type(results) str
_detect_tech_stack(results) List[str]
_estimate_team_size(results) str
_detect_development_phase(results) str
_detect_workflows(results) List[str]
_should_use_modular(results) bool
```
**Detection Logic:**
- Project type: Check for frontend/, backend/, src/ patterns
- Tech stack: Parse package.json, requirements.txt, go.mod
- Team size: Analyze git contributors, project complexity
- Phase: Check for CI/CD, production configs
- Workflows: Detect test/, .github/, documentation patterns
---
### analyzer.py
**Purpose:** Analyze existing CLAUDE.md files
**Key Classes:**
- `CLAUDEMDAnalyzer` - File analyzer
**Quality Scoring Algorithm:**
```python
def calculate_quality_score(self) int:
score = 0
# Length appropriateness (25 points)
if 20 <= line_count <= 300:
score += 25
elif 300 < line_count <= 400:
score += 15 # Warn: consider modular
else:
score += 5 # Poor: too short or too long
# Section completeness (25 points)
required = ["Core Principles", "Tech Stack", "Workflow"]
found = len([s for s in required if s in sections])
score += (found / len(required)) * 25
# Formatting quality (20 points)
# Check: headings, code blocks, lists, links
score += formatting_score
# Content specificity (15 points)
# Check: project-specific vs. generic
score += specificity_score
# Modular organization (15 points)
# Check: context files if needed
score += modular_score
return min(score, 100)
```
---
### validator.py
**Purpose:** Validate against best practices
**Validation Categories:**
1. **Length Validation**
- Recommended: 20-300 lines
- Warning: 300-400 lines (suggest modular)
- Error: < 20 or > 400 lines
2. **Structure Validation**
- Required sections: Core Principles, Tech Stack, Workflow
- Recommended sections: Testing, Error Handling
- Heading hierarchy: H1 → H2 → H3 (no skips)
3. **Formatting Validation**
- Balanced code blocks (open/close)
- Valid markdown syntax
- No broken links
4. **Completeness Validation**
- Has code examples
- Lists tech stack with versions
- Includes setup instructions
5. **Anti-Pattern Detection**
- No hardcoded secrets (API keys, tokens)
- No TODO placeholders
- No broken reference links
---
### template_selector.py
**Purpose:** Select appropriate template
**Selection Matrix:**
| Project Type | Team Size | Lines | Template |
|--------------|-----------|-------|----------|
| CLI/Library | Solo | 50-75 | minimal |
| Web App | Small | 100-150 | core |
| API | Small | 125-175 | api-focused |
| Full-Stack | Medium | 200-300 | detailed |
| Enterprise | Large | Modular | root + contexts |
**Modular Recommendation Logic:**
```python
def recommend_modular_structure(context: Dict) bool:
return (
context['type'] == 'fullstack' or
context['team_size'] in ['medium', 'large'] or
context['phase'] in ['production', 'enterprise'] or
len(context['tech_stack']) > 5
)
```
---
### generator.py
**Purpose:** Generate CLAUDE.md content
**Generation Modes:**
1. **Root File (Navigation Hub)**
- Quick Navigation section
- Core Principles (high-level)
- Tech Stack summary
- Links to context files
2. **Context File (Specific Area)**
- Detailed guidelines for backend/, frontend/, etc.
- Tech-specific patterns
- Common commands for that area
3. **Section Generation (Individual)**
- Generate single section
- Merge with existing content
**Native Format Template:**
```markdown
# CLAUDE.md
[Overview paragraph]
## Project Structure
```
project/
├── src/
│ ├── components/
│ └── services/
└── tests/
```
## File Structure
- `src/` - Source code
- `tests/` - Test files
## Setup & Installation
```bash
npm install
npm run dev
```
## Architecture
[Key design decisions]
## Core Principles
1. Principle one
2. Principle two
## Tech Stack
- React 18
- TypeScript 5
- Node.js 20
## Common Commands
```bash
npm run build # Build project
npm test # Run tests
```
```
---
## Integration Points
### Skill ↔ Slash Command
**File:** `command/enhance-claude-md.md`
```yaml
# YAML frontmatter
allowed-tools: Bash, Read, Glob, Skill
# Phase 3: Task section
I can invoke the `claude-md-enhancer` skill...
```
Claude Code recognizes skill name and loads Python modules.
### Skill ↔ Guardian Agent
**File:** `agent/claude-md-guardian.md`
```yaml
# YAML frontmatter
tools: Bash, Read, Write, Edit, Grep, Glob, Skill
model: haiku
# Agent workflow section
I invoke the `claude-md-enhancer` skill...
```
Agent uses `haiku` model for token efficiency, invokes skill for updates.
### Agent ↔ Git
Agent detects changes via bash commands:
```bash
git diff --name-status HEAD~10
git log --since="1 week ago" --oneline
git diff HEAD~10 -- package.json requirements.txt
```
Triggers update if:
- 5+ files changed
- Dependencies modified
- New directories created
---
## Design Decisions
### Why Python for Skill Modules?
- **Portability:** Standard library only, no dependencies
- **Readability:** Clear logic for community contributions
- **Performance:** Adequate for file analysis/generation
- **Integration:** Claude Code supports Python natively
### Why Separate Slash Command and Agent?
- **Slash Command:** User-initiated, interactive, immediate feedback
- **Agent:** Background, automatic, non-intrusive
- **Flexibility:** User chooses explicit control vs. automation
### Why Quality Scoring Algorithm?
- **Objectivity:** Consistent evaluation across projects
- **Actionable:** Specific areas to improve
- **Educational:** Users learn best practices
- **Gamification:** Encourages quality improvement
### Why Modular Architecture Support?
- **Scalability:** Large projects need organization
- **Context:** Different areas have different needs
- **Maintainability:** Easier to update specific sections
- **Team:** Different teams own different files
---
## Performance Considerations
### Token Efficiency
**Guardian Agent uses `haiku` model:**
- Routine updates: ~500-1000 tokens
- Targeted section updates only
- Saves 70-80% tokens vs. full regeneration
**Slash Command uses default model (sonnet):**
- Interactive, user-facing
- Requires better understanding
- More complex reasoning
### File Size Limits
- Single file: Max 400 lines (prefer 300)
- Modular files: Each 150-300 lines
- Total project: Unlimited with modular
### Caching Strategy
No caching implemented (stateless design):
- Each invocation reads fresh files
- Ensures accuracy with latest changes
- Simple implementation
---
## Security Considerations
### Anti-Pattern Detection
**validator.py** checks for:
- Hardcoded secrets: `API_KEY=`, `password=`, `token=`
- Placeholder TODOs: `TODO`, `FIXME`, `XXX`
- Broken links: Invalid URL patterns
### File Permissions
Installation respects user permissions:
- User-level: `~/.claude/` (user writable)
- Project-level: `./.claude/` (project writable)
- No system-level changes
### Git Integration
Agent only reads git:
- `git diff` (read-only)
- `git log` (read-only)
- `git status` (read-only)
- No git write operations
---
## Extensibility
### Adding New Project Types
1. Update `workflow.py``_detect_project_type()`
2. Add detection patterns
3. Update `template_selector.py` → selection matrix
4. Create new template in `skill/examples/`
### Adding New Tech Stacks
1. Update `workflow.py``_detect_tech_stack()`
2. Add file detection (e.g., `Cargo.toml` for Rust)
3. Update `generator.py` → tech-specific sections
### Adding New Validation Rules
1. Update `validator.py``validate_all()`
2. Add new validation method
3. Return validation result in standard format
---
## Testing Strategy
### Manual Testing
See [QUICK_START.md](QUICK_START.md) for test scenarios.
### Integration Testing
Test entire flow:
1. Install components
2. Run slash command
3. Verify output quality
4. Test guardian agent
5. Validate native format
### Unit Testing
(Not implemented in v1.0.0, planned for v1.1.0)
- Test each Python module independently
- Mock file I/O
- Validate scoring algorithms
---
## Future Architecture
### Planned for v1.1.0
- **VS Code Extension:** Inline editing, real-time validation
- **GitHub Action:** Auto-generate on repo creation
- **Custom Templates:** User-defined template system
- **Analytics:** Usage patterns, effectiveness metrics
### Planned for v2.0.0
- **AI-Powered Suggestions:** Context-aware recommendations
- **Multi-Language Support:** i18n for generated content
- **Web Dashboard:** Project-wide management
- **Plugin System:** Third-party extensions
---
## Related Documentation
- **Implementation Details:** [CLAUDE.md](../CLAUDE.md)
- **Installation:** [INSTALLATION.md](INSTALLATION.md)
- **Quick Start:** [QUICK_START.md](QUICK_START.md)
- **Troubleshooting:** [TROUBLESHOOTING.md](TROUBLESHOOTING.md)
---
**Questions about architecture?** Open an issue: https://github.com/alirezarezvani/ClaudeForge/issues
+490
View File
@@ -0,0 +1,490 @@
# Contributing to ClaudeForge
Thank you for your interest in contributing to ClaudeForge! This guide will help you get started.
---
## Code of Conduct
By participating in this project, you agree to abide by our [Code of Conduct](../.github/CODE_OF_CONDUCT.md).
---
## How Can I Contribute?
### 1. Reporting Bugs
**Before submitting a bug report:**
- Check existing issues to avoid duplicates
- Collect information about the bug
- Test with the latest version
**Submit a bug report:**
- Use the bug report template
- Provide clear title and description
- Include steps to reproduce
- Add relevant logs or screenshots
- Mention your environment (OS, Claude Code version)
**Template:** https://github.com/alirezarezvani/ClaudeForge/issues/new?template=bug_report.md
---
### 2. Suggesting Enhancements
**Before submitting:**
- Check if the feature already exists
- Review planned features in CHANGELOG.md
- Consider if it fits project scope
**Submit an enhancement:**
- Use the feature request template
- Explain the use case
- Describe proposed solution
- Consider alternatives
**Template:** https://github.com/alirezarezvani/ClaudeForge/issues/new?template=feature_request.md
---
### 3. Contributing Code
#### Quick Start
```bash
# Fork the repository
# Clone your fork
git clone https://github.com/YOUR-USERNAME/ClaudeForge.git
cd ClaudeForge
# Create a branch
git checkout -b feature/amazing-feature
# Make your changes
# Test your changes
./install.sh # Test installation
/enhance-claude-md # Test in Claude Code
# Commit your changes
git commit -m "Add amazing feature"
# Push to your fork
git push origin feature/amazing-feature
# Open a Pull Request
```
#### Development Setup
```bash
# Install development dependencies
# (None required - Python standard library only)
# Test Python modules
python3 -c "from skill.analyzer import CLAUDEMDAnalyzer; print('OK')"
# Test installation scripts
./install.sh
# Choose option 2 (project-level) for testing
```
---
## Development Guidelines
### Python Code Style
**Follow PEP 8:**
```python
# Good
def analyze_file(self, content: str) -> Dict[str, Any]:
"""Analyze CLAUDE.md file content."""
pass
# Bad
def analyzeFile(self,content):
pass
```
**Type Hints:**
```python
# Always use type hints
def calculate_score(sections: List[str]) int:
return len(sections) * 10
```
**Docstrings:**
```python
def validate_length(self, content: str) -> bool:
"""
Validate CLAUDE.md file length.
Args:
content: File content as string
Returns:
True if length is valid, False otherwise
"""
pass
```
---
### Markdown Style
**Headings:**
```markdown
# H1 - Document title
## H2 - Main sections
### H3 - Subsections
```
**Code Blocks:**
```markdown
```bash
# Use language-specific syntax highlighting
command here
```
```
**Links:**
```markdown
# Prefer relative links for internal docs
[Architecture](ARCHITECTURE.md)
# Use absolute URLs for external
[GitHub](https://github.com/alirezarezvani/ClaudeForge)
```
---
### Testing Your Changes
#### Test Python Modules
```bash
# Test analyzer
python3 << EOF
from skill.analyzer import CLAUDEMDAnalyzer
content = open('test-CLAUDE.md').read()
analyzer = CLAUDEMDAnalyzer(content)
report = analyzer.analyze_file()
print(f"Quality Score: {report['quality_score']}")
EOF
```
#### Test Installation
```bash
# Test install.sh
./install.sh
# Choose option 2 (project-level)
# Verify all components copied correctly
# Test uninstall
rm -rf ./.claude
```
#### Test in Claude Code
```bash
# Install your changes
./install.sh
# Restart Claude Code
# Test slash command
/enhance-claude-md
# Verify output matches expected behavior
```
---
## Contribution Areas
### 1. Adding New Templates
**Location:** `skill/examples/`
**Steps:**
1. Create new template file (e.g., `rust-cli-CLAUDE.md`)
2. Follow native format structure
3. Update `skill/examples/README.md`
4. Update `template_selector.py` detection logic
5. Add test case to `sample_input.json`
**Example:**
```bash
# Create Rust template
vim skill/examples/rust-cli-CLAUDE.md
# Update selector
vim skill/template_selector.py
# Add: if 'Cargo.toml' in files: return 'rust-cli'
# Test
# Create test Rust project, run /enhance-claude-md
```
---
### 2. Improving Detection Logic
**Location:** `skill/workflow.py`
**Methods to enhance:**
- `_detect_project_type()`
- `_detect_tech_stack()`
- `_estimate_team_size()`
- `_detect_development_phase()`
**Example:**
```python
# Add Flutter detection
def _detect_project_type(self, results):
files = results.get('files', [])
# Add Flutter check
if 'pubspec.yaml' in files:
return 'mobile'
# ... existing logic
```
---
### 3. Enhancing Quality Scoring
**Location:** `skill/analyzer.py`
**Method:** `calculate_quality_score()`
**Ideas:**
- Add more granular checks
- Weight sections by importance
- Detect project-specific customization
**Example:**
```python
def calculate_quality_score(self) -> int:
score = 0
# Add new check: Has examples
if self._has_code_examples():
score += 5 # Bonus points
# ... existing logic
return min(score, 100)
```
---
### 4. Adding New Validation Rules
**Location:** `skill/validator.py`
**Steps:**
1. Add new validation method
2. Call from `validate_all()`
3. Return standard validation result
**Example:**
```python
def validate_examples(self) -> Dict[str, Any]:
"""Validate code examples are present."""
code_blocks = re.findall(r'```.*?```', self.content, re.DOTALL)
return {
'passed': len(code_blocks) >= 3,
'message': 'At least 3 code examples required',
'severity': 'low'
}
```
---
### 5. Documentation Improvements
**Areas:**
- Fix typos or unclear explanations
- Add missing examples
- Improve installation instructions
- Translate to other languages (future)
**Process:**
1. Edit markdown files in `docs/`
2. Test markdown rendering locally
3. Submit pull request
---
## Pull Request Process
### 1. Before Submitting
- [ ] Code follows project style guidelines
- [ ] All tests pass (manual testing required)
- [ ] Documentation updated if needed
- [ ] CHANGELOG.md updated with your changes
- [ ] Commit messages are clear and descriptive
### 2. Submitting
1. **Create Pull Request** from your fork
2. **Fill out PR template** completely
3. **Link related issues** (if any)
4. **Request review** from maintainers
5. **Respond to feedback** promptly
### 3. After Submission
- **CI checks** will run automatically
- **Maintainers** will review your code
- **Address feedback** by pushing new commits
- **Don't force-push** after review started
- **Be patient** - reviews may take a few days
### 4. Merging
Once approved:
- Maintainer will merge your PR
- Your contribution will be in the next release
- You'll be added to contributors list
---
## Commit Message Guidelines
### Format
```
type(scope): Short description
Longer description if needed.
Fixes #123
```
### Types
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation changes
- `style`: Code style changes (no logic change)
- `refactor`: Code refactoring
- `test`: Adding tests
- `chore`: Maintenance tasks
### Examples
```
feat(analyzer): Add code example detection
Adds check for code examples in CLAUDE.md files.
Contributes to quality score calculation.
Fixes #45
```
```
fix(installer): Resolve Windows path issues
Fixes path separator issues on Windows platforms.
Updates install.ps1 to use platform-specific paths.
Fixes #67
```
```
docs(quick-start): Clarify installation steps
Adds more detailed explanations for each step.
Includes troubleshooting for common issues.
```
---
## Release Process
(For maintainers)
### Version Numbering
Follow Semantic Versioning (MAJOR.MINOR.PATCH):
- MAJOR: Breaking changes
- MINOR: New features (backward compatible)
- PATCH: Bug fixes (backward compatible)
### Release Checklist
1. **Update version:**
- `CHANGELOG.md` - Add new version section
- `README.md` - Update version badge
- `skill/SKILL.md` - Update version footer
2. **Create release:**
```bash
git tag -a v1.1.0 -m "Release v1.1.0"
git push origin v1.1.0
```
3. **GitHub Release:**
- Create release from tag
- Copy CHANGELOG excerpt to description
- Attach any binaries if needed
4. **Announce:**
- GitHub Discussions
- Social media (if applicable)
- Update documentation site
---
## Community
### Getting Help
- **GitHub Discussions:** Ask questions, share ideas
- **GitHub Issues:** Report bugs, request features
- **Documentation:** Comprehensive guides in `docs/`
### Staying Updated
- **Watch Repository:** Get notifications for releases
- **Star Repository:** Show support, stay informed
- **Follow Updates:** Check CHANGELOG.md for changes
---
## Recognition
Contributors are recognized in:
- **README.md** - Contributors section
- **CHANGELOG.md** - Version-specific contributors
- **GitHub** - Automatic contributors graph
Every contribution matters, from code to documentation to bug reports!
---
## Questions?
- **General Questions:** GitHub Discussions
- **Bug Reports:** GitHub Issues
- **Security Issues:** Email maintainers directly (see SECURITY.md if created)
- **Feature Requests:** GitHub Issues with feature template
---
## License
By contributing, you agree that your contributions will be licensed under the MIT License.
See [LICENSE](../LICENSE) for details.
---
**Thank you for contributing to ClaudeForge!** 🎉
Your contributions help make CLAUDE.md management better for everyone in the Claude Code community.
+412
View File
@@ -0,0 +1,412 @@
# Installation Guide
Complete installation instructions for ClaudeForge on all supported platforms.
---
## Prerequisites
### Required
- **Claude Code** 2.0 or later
- **Operating System:** macOS, Linux, or Windows
### Recommended
- **Git** (for change detection by guardian agent)
- Terminal access (macOS/Linux) or PowerShell (Windows)
---
## Installation Methods
### Method 1: One-Line Install (Recommended)
#### macOS / Linux
```bash
curl -fsSL https://raw.githubusercontent.com/alirezarezvani/ClaudeForge/main/install.sh | bash
```
#### Windows (PowerShell as Administrator)
```powershell
iwr https://raw.githubusercontent.com/alirezarezvani/ClaudeForge/main/install.ps1 -useb | iex
```
**What this does:**
1. Downloads the installer script
2. Prompts for installation scope (user-level or project-level)
3. Copies all components to appropriate directories
4. Creates backups of any existing installations
5. Optionally installs quality hooks
---
### Method 2: Manual Git Clone
```bash
# Clone the repository
git clone https://github.com/alirezarezvani/ClaudeForge.git
# Navigate to directory
cd ClaudeForge
# Run installer
./install.sh # macOS/Linux
# or
.\install.ps1 # Windows
```
---
### Method 3: Manual Installation (Advanced)
If you prefer to manually copy files:
#### Step 1: Download Components
Download the latest release from:
https://github.com/alirezarezvani/ClaudeForge/releases
#### Step 2: Choose Installation Scope
**User-Level (Recommended)** - Available in all Claude Code projects:
```bash
# macOS/Linux
INSTALL_DIR="$HOME/.claude"
# Windows
$INSTALL_DIR="$env:USERPROFILE\.claude"
```
**Project-Level** - Available only in current project:
```bash
# macOS/Linux
INSTALL_DIR="./.claude"
# Windows
$INSTALL_DIR=".\.claude"
```
#### Step 3: Copy Components
```bash
# Create directories
mkdir -p "$INSTALL_DIR/skills"
mkdir -p "$INSTALL_DIR/commands"
mkdir -p "$INSTALL_DIR/agents"
# Copy skill
cp -r skill "$INSTALL_DIR/skills/claudeforge-skill"
# Copy slash command
cp -r command "$INSTALL_DIR/commands/enhance-claude-md"
# Copy guardian agent
cp agent/claude-md-guardian.md "$INSTALL_DIR/agents/"
```
#### Step 4: Restart Claude Code
Close and restart Claude Code to load the new components.
---
## Installation Scopes
### User-Level Installation
**Location:** `~/.claude/` (or `%USERPROFILE%\.claude` on Windows)
**Advantages:**
- ✅ Available in all Claude Code projects
- ✅ Install once, use everywhere
- ✅ Automatic updates apply globally
**Use When:**
- You work on multiple projects
- You want consistent CLAUDE.md standards across all projects
- You're the primary developer on your machine
### Project-Level Installation
**Location:** `./.claude/` (in your project root)
**Advantages:**
- ✅ Project-specific configuration
- ✅ Version controlled with project (can commit to git)
- ✅ Team members get same tools
**Use When:**
- Different projects need different versions
- You want to version control the tools
- Team collaboration requires shared tooling
---
## Verification
After installation, verify all components are installed correctly:
### Check Skill Installation
```bash
# macOS/Linux
ls -la ~/.claude/skills/claudeforge-skill/
# Windows
dir $env:USERPROFILE\.claude\skills\claudeforge-skill\
```
**Expected output:**
```
analyzer.py
generator.py
template_selector.py
validator.py
workflow.py
SKILL.md
README.md
examples/
```
### Check Command Installation
```bash
# macOS/Linux
ls -la ~/.claude/commands/enhance-claude-md/
# Windows
dir $env:USERPROFILE\.claude\commands\enhance-claude-md\
```
**Expected output:**
```
enhance-claude-md.md
README.md
```
### Check Agent Installation
```bash
# macOS/Linux
ls -la ~/.claude/agents/claude-md-guardian.md
# Windows
dir $env:USERPROFILE\.claude\agents\claude-md-guardian.md
```
### Test in Claude Code
1. Restart Claude Code
2. Open any project
3. Run the command:
```
/enhance-claude-md
```
4. You should see the multi-phase workflow start
---
## Quality Hooks (Optional)
During installation, you'll be asked if you want to install quality hooks.
**What are Quality Hooks?**
- Pre-commit validation that checks CLAUDE.md quality before commits
- Ensures best practices compliance
- Only available for project-level installations
**To Install Hooks:**
```bash
# During installer
# When prompted: "Would you like to install quality hooks?"
# Type: y
# Or manually:
mkdir -p .claude/hooks
cp hooks/pre-commit.sh .claude/hooks/
chmod +x .claude/hooks/pre-commit.sh
```
**To Use Hooks:**
Configure git to use the hook:
```bash
# Add to .git/config or use git config
git config core.hooksPath .claude/hooks
```
---
## Troubleshooting Installation
### Issue: "Installation files not found"
**Cause:** Running installer from wrong directory
**Solution:**
```bash
cd ClaudeForge # Navigate to repository root
./install.sh # Run from correct directory
```
---
### Issue: "Permission denied"
**Cause:** Installer doesn't have execute permission
**Solution:**
```bash
chmod +x install.sh # macOS/Linux
# or run with bash explicitly
bash install.sh
```
---
### Issue: "~/.claude directory not found"
**Cause:** Claude Code not installed or hasn't been run yet
**Solution:**
1. Ensure Claude Code is installed
2. Run Claude Code at least once to create directory structure
3. Or let installer create directories (it will prompt)
---
### Issue: Command not recognized after installation
**Cause:** Claude Code hasn't reloaded components
**Solution:**
1. Fully quit Claude Code (not just close window)
2. Restart Claude Code
3. Wait a few seconds for components to load
4. Try command again: `/enhance-claude-md`
---
### Issue: "Skill not found" error
**Cause:** Skill directory name mismatch
**Solution:**
```bash
# Verify skill directory name is exactly:
ls ~/.claude/skills/
# Should show: claudeforge-skill
# If different, rename:
mv ~/.claude/skills/old-name ~/.claude/skills/claudeforge-skill
```
---
### Issue: Windows installer fails with execution policy error
**Cause:** PowerShell execution policy restricts scripts
**Solution:**
```powershell
# Run PowerShell as Administrator
# Set execution policy temporarily:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
# Then run installer:
.\install.ps1
```
---
## Updating ClaudeForge
To update to a newer version:
### Method 1: Using Installer
```bash
# Pull latest changes
cd ClaudeForge
git pull origin main
# Run installer (existing installation will be backed up)
./install.sh
```
### Method 2: Manual Update
```bash
# Backup current installation
mv ~/.claude/skills/claudeforge-skill ~/.claude/skills/claudeforge-skill.backup
# Copy new version
cp -r skill ~/.claude/skills/claudeforge-skill
# Repeat for command and agent
```
---
## Uninstallation
To completely remove ClaudeForge:
### User-Level Uninstall
```bash
# macOS/Linux
rm -rf ~/.claude/skills/claudeforge-skill
rm -rf ~/.claude/commands/enhance-claude-md
rm -f ~/.claude/agents/claude-md-guardian.md
# Windows (PowerShell)
Remove-Item -Recurse -Force $env:USERPROFILE\.claude\skills\claudeforge-skill
Remove-Item -Recurse -Force $env:USERPROFILE\.claude\commands\enhance-claude-md
Remove-Item -Force $env:USERPROFILE\.claude\agents\claude-md-guardian.md
```
### Project-Level Uninstall
```bash
# macOS/Linux
rm -rf ./.claude/skills/claudeforge-skill
rm -rf ./.claude/commands/enhance-claude-md
rm -f ./.claude/agents/claude-md-guardian.md
rm -rf ./.claude/hooks # If quality hooks were installed
# Windows (PowerShell)
Remove-Item -Recurse -Force .\.claude\skills\claudeforge-skill
Remove-Item -Recurse -Force .\.claude\commands\enhance-claude-md
Remove-Item -Force .\.claude\agents\claude-md-guardian.md
Remove-Item -Recurse -Force .\.claude\hooks
```
After uninstalling, restart Claude Code.
---
## Next Steps
After successful installation:
1. **Read Quick Start Guide:** [QUICK_START.md](QUICK_START.md)
2. **Test the command:** Run `/enhance-claude-md` in a project
3. **Review Architecture:** [ARCHITECTURE.md](ARCHITECTURE.md)
4. **Explore Examples:** Check `examples/` directory
---
## Support
If you encounter installation issues not covered here:
- **GitHub Issues:** https://github.com/alirezarezvani/ClaudeForge/issues
- **Troubleshooting Guide:** [TROUBLESHOOTING.md](TROUBLESHOOTING.md)
- **Discussions:** https://github.com/alirezarezvani/ClaudeForge/discussions
---
**Installation successful?** Proceed to [Quick Start Guide](QUICK_START.md) →
+407
View File
@@ -0,0 +1,407 @@
# Quick Start Guide
Get started with ClaudeForge in 5 minutes. This guide walks you through your first CLAUDE.md creation.
---
## 🚀 5-Minute Tutorial
### Step 1: Install ClaudeForge (1 minute)
```bash
# macOS / Linux
curl -fsSL https://raw.githubusercontent.com/alirezarezvani/ClaudeForge/main/install.sh | bash
# Windows (PowerShell)
iwr https://raw.githubusercontent.com/alirezarezvani/ClaudeForge/main/install.ps1 -useb | iex
```
**Choose:** Option 1 (user-level) for global availability
**Restart Claude Code** after installation
---
### Step 2: Navigate to Your Project (30 seconds)
```bash
cd /path/to/your/project
```
**Requirements:**
- Any code project (doesn't need to be git-initialized, but recommended)
- Works with TypeScript, Python, Go, Java, Ruby, and more
---
### Step 3: Run the Command (10 seconds)
In Claude Code, type:
```bash
/enhance-claude-md
```
---
### Step 4: Interactive Workflow (3 minutes)
ClaudeForge will now:
#### Phase 1: Discovery ✓
Claude explores your project:
```
Checking for existing CLAUDE.md... Not found
Exploring repository structure...
Analyzing package.json, requirements.txt, etc...
```
#### Phase 2: Analysis ✓
Claude shows discoveries:
```
Based on my exploration, here's what I discovered:
📦 Project Type: Full-Stack Application
🛠️ Tech Stack: TypeScript, React, Node.js, PostgreSQL, Docker
👥 Team Size: Small (5 developers detected from git history)
🚀 Development Phase: MVP
⚙️ Workflows: TDD, CI/CD
📋 Recommended Structure:
- Root CLAUDE.md (navigation hub, ~100 lines)
- backend/CLAUDE.md (API guidelines, ~150 lines)
- frontend/CLAUDE.md (React guidelines, ~175 lines)
```
#### Phase 3: Confirmation ✓
Claude asks for your approval:
```
Would you like me to create these files with these settings?
```
**You respond:** `Yes` or `Yes, proceed`
#### Phase 4: Generation ✓
Claude creates your CLAUDE.md files:
```
Creating customized CLAUDE.md files...
✅ Created CLAUDE.md (108 lines)
- Quick Navigation section
- 5 Core Principles
- Tech Stack summary
- Common commands
✅ Created backend/CLAUDE.md (156 lines)
- API design guidelines
- Database operations
- Testing requirements
✅ Created frontend/CLAUDE.md (182 lines)
- Component standards
- State management
- Performance tips
```
---
### Step 5: Review Your CLAUDE.md (1 minute)
Open the generated file:
```bash
cat CLAUDE.md
```
**You'll see:**
- **Overview** - Project description
- **Project Structure** - ASCII tree diagram
- **Setup & Installation** - How to get started
- **Architecture** - Key patterns and decisions
- **Core Principles** - Development guidelines
- **Tech Stack** - Technologies used
- **Common Commands** - Build, test, lint
- **Development Workflow** - How to contribute
All in **100% native Claude Code format**!
---
## 🎯 What Just Happened?
1. **Explored** your codebase automatically
2. **Detected** project type, tech stack, team size
3. **Generated** customized CLAUDE.md with:
- Native format compliance
- Tech-specific best practices
- Team-appropriate complexity
4. **Created** modular files (if needed)
**Result:** Future Claude Code sessions now have perfect context about your project!
---
## 🔄 Common Workflows
### Scenario A: New Project
```bash
# You: Create a new project
mkdir my-new-app && cd my-new-app
npm init -y
# You: Run ClaudeForge
/enhance-claude-md
# Claude: Explores → Analyzes → Creates CLAUDE.md
```
**Time:** ~2 minutes
---
### Scenario B: Existing Project (No CLAUDE.md)
```bash
# You: Navigate to existing project
cd my-existing-project
# You: Run ClaudeForge
/enhance-claude-md
# Claude: Explores → Detects tech → Creates CLAUDE.md
```
**Time:** ~3 minutes
---
### Scenario C: Improve Existing CLAUDE.md
```bash
# You: Have basic CLAUDE.md
cat CLAUDE.md
# Output: Basic file with just tech stack
# You: Run ClaudeForge
/enhance-claude-md
# Claude: Analyzes current file
# Shows: Quality Score: 55/100
# Missing: Project Structure, Setup, Architecture
# Claude: Adds missing sections
# Result: Quality Score: 55 → 88
```
**Time:** ~2 minutes
---
### Scenario D: Automatic Maintenance
```bash
# You: Make significant changes
npm install react-query
mkdir src/components/auth
# You: Start new Claude Code session
# Guardian agent automatically checks changes
# Agent output:
# ✅ CLAUDE.md updated:
# - Tech Stack: Added react-query
# - Project Structure: Updated diagram
# Changes: 2 sections, 8 lines
```
**Time:** Automatic, ~10 seconds
---
## 📚 Next Steps
### Learn More
- **Architecture:** [ARCHITECTURE.md](ARCHITECTURE.md) - How components work together
- **Examples:** [../examples/](../examples/) - Real-world usage patterns
- **Troubleshooting:** [TROUBLESHOOTING.md](TROUBLESHOOTING.md) - Common issues
### Customize Your CLAUDE.md
After generation, you can:
1. **Edit Core Principles** - Add team-specific guidelines
2. **Add Custom Sections** - Project-specific conventions
3. **Update Tech Stack** - Add missing dependencies
4. **Refine Workflows** - Adjust to your process
### Enable Automatic Maintenance
Set up the guardian agent to keep CLAUDE.md current:
```bash
# Agent runs automatically at session start
# Or invoke manually after major changes:
Claude, invoke claude-md-guardian to update CLAUDE.md
```
---
## 💡 Pro Tips
### Tip 1: Use Modular Architecture for Large Projects
If your CLAUDE.md exceeds 300 lines, split it:
```bash
/enhance-claude-md
# Tell Claude: "Use modular architecture"
# Result: Separate files for backend/, frontend/, database/
```
### Tip 2: Regenerate When Tech Stack Changes
```bash
# You: Added new major framework
npm install @nestjs/core
# You: Regenerate with new context
/enhance-claude-md
# Claude: Updates Tech Stack and patterns
```
### Tip 3: Validate Before Committing
```bash
# You: Made manual edits to CLAUDE.md
# You: Want to check quality
/enhance-claude-md
# Claude: Analyzes and shows quality score
# If score < 80, Claude suggests improvements
```
### Tip 4: Team Consistency
Install at user-level on all team machines:
```bash
# Each team member runs:
curl -fsSL https://raw.githubusercontent.com/alirezarezvani/ClaudeForge/main/install.sh | bash
# Choose option 1 (user-level)
# Result: Consistent CLAUDE.md standards across team
```
---
## 🎓 Understanding the Output
### What's in a Generated CLAUDE.md?
**Native Format Sections (Always Included):**
1. **Overview** - What this project does
2. **Project Structure** - ASCII tree diagram
3. **File Structure** - Directory explanations
4. **Setup & Installation** - Getting started steps
5. **Architecture** - Key design decisions (for complex projects)
**Team-Specific Sections:**
6. **Core Principles** - Development guidelines
7. **Tech Stack** - Technologies with versions
8. **Development Workflow** - How to contribute
9. **Testing Requirements** - Test standards
10. **Common Commands** - Build, test, lint scripts
**Optional Sections (Based on Project Type):**
- **Error Handling** - Error patterns
- **Performance Guidelines** - Optimization tips
- **Security Checklist** - Security requirements
- **Deployment Process** - How to deploy
---
## ⚡ Quick Reference
### Commands
| Command | Purpose |
|---------|---------|
| `/enhance-claude-md` | Initialize or enhance CLAUDE.md |
| `Claude, invoke claude-md-guardian` | Manually trigger maintenance |
### Quality Scores
| Score | Meaning | Action |
|-------|---------|--------|
| 0-40 | Poor | Major improvements needed |
| 41-70 | Fair | Add missing sections |
| 71-85 | Good | Minor improvements |
| 86-100 | Excellent | Maintain current quality |
### File Size Guidelines
| Team Size | Recommended Lines | Structure |
|-----------|-------------------|-----------|
| Solo | 50-100 | Single file |
| Small (2-9) | 100-200 | Single file |
| Medium (10-50) | 200-300 | Single or modular |
| Large (50+) | Modular | Multiple context files |
---
## 🆘 Having Issues?
### Issue: Command not recognized
**Solution:** Restart Claude Code after installation
### Issue: Quality score too low
**Solution:** Run `/enhance-claude-md` and let Claude add missing sections
### Issue: Generated file too generic
**Solution:** Provide more context:
```
/enhance-claude-md
"This is a Python FastAPI microservice project with PostgreSQL"
```
### More Help
See [TROUBLESHOOTING.md](TROUBLESHOOTING.md) for detailed solutions.
---
## 🎉 Success!
You now have a fully functional CLAUDE.md file that:
- ✅ Follows native Claude Code format
- ✅ Includes project-specific context
- ✅ Provides clear development guidelines
- ✅ Automatically maintains itself (via guardian agent)
**Future Claude Code sessions will be significantly more productive!**
---
## 📖 Further Reading
- **Installation Guide:** [INSTALLATION.md](INSTALLATION.md)
- **Architecture Deep Dive:** [ARCHITECTURE.md](ARCHITECTURE.md)
- **Contributing:** [CONTRIBUTING.md](CONTRIBUTING.md)
- **GitHub Repository:** https://github.com/alirezarezvani/ClaudeForge
---
**Ready to create amazing projects with ClaudeForge? Let's build! 🚀**
+551
View File
@@ -0,0 +1,551 @@
# Troubleshooting Guide
Common issues and solutions for ClaudeForge.
---
## Installation Issues
### Issue: Command not recognized after installation
**Symptoms:**
- `/enhance-claude-md` shows "command not found"
- Slash command doesn't autocomplete
**Causes:**
- Claude Code hasn't reloaded components
- Incorrect installation path
- Insufficient permissions
**Solutions:**
1. **Restart Claude Code completely:**
```bash
# Quit Claude Code entirely (not just close window)
# Reopen Claude Code
# Wait 5-10 seconds for components to load
```
2. **Verify installation paths:**
```bash
# macOS/Linux
ls -la ~/.claude/commands/enhance-claude-md/
ls -la ~/.claude/skills/claudeforge-skill/
ls -la ~/.claude/agents/claude-md-guardian.md
# Windows
dir %USERPROFILE%\.claude\commands\enhance-claude-md\
dir %USERPROFILE%\.claude\skills\claudeforge-skill\
dir %USERPROFILE%\.claude\agents\claude-md-guardian.md
```
3. **Reinstall with correct permissions:**
```bash
chmod +x install.sh # macOS/Linux
./install.sh
```
---
### Issue: "Skill not found" error
**Symptoms:**
- Error message: "claude-md-enhancer skill not found"
- Slash command runs but fails
**Cause:** Skill directory name mismatch or missing skill files
**Solutions:**
1. **Check skill directory name (must be exact):**
```bash
ls ~/.claude/skills/
# Must show: claudeforge-skill
```
2. **Verify skill files exist:**
```bash
ls ~/.claude/skills/claudeforge-skill/
# Must contain: SKILL.md, analyzer.py, generator.py, etc.
```
3. **Reinstall skill only:**
```bash
rm -rf ~/.claude/skills/claudeforge-skill
cp -r skill ~/.claude/skills/claudeforge-skill
```
---
### Issue: Windows PowerShell execution policy error
**Symptoms:**
- Error: "execution of scripts is disabled on this system"
**Cause:** PowerShell security settings
**Solution:**
```powershell
# Run PowerShell as Administrator
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
.\install.ps1
```
---
## Usage Issues
### Issue: Quality score unexpectedly low
**Symptoms:**
- Quality score < 50
- Many "missing section" warnings
**Causes:**
- Basic CLAUDE.md without native format sections
- File too short (< 20 lines) or too long (> 400 lines)
- Missing required sections
**Solutions:**
1. **Let ClaudeForge add missing sections:**
```bash
/enhance-claude-md
# Claude will identify missing sections
# Confirm enhancement
# Quality score will improve
```
2. **Check file length:**
```bash
wc -l CLAUDE.md
# Recommended: 20-300 lines
# If > 300: Consider modular architecture
```
3. **Manually add required sections:**
- Core Principles
- Tech Stack
- Workflow Instructions
- Project Structure (ASCII diagram)
- Setup & Installation
---
### Issue: Generated content too generic
**Symptoms:**
- CLAUDE.md doesn't mention specific tech stack
- No project-specific guidelines
- Feels like template without customization
**Causes:**
- Project detection failed (no package.json, requirements.txt, etc.)
- Insufficient project context
**Solutions:**
1. **Provide explicit context:**
```bash
/enhance-claude-md
# When Claude asks, specify:
"This is a Python FastAPI microservice with PostgreSQL, Redis, and Docker. Team of 8 developers, MVP phase."
```
2. **Add project files before running:**
```bash
# Ensure detection files exist:
touch package.json # Node.js
touch requirements.txt # Python
touch go.mod # Go
touch Cargo.toml # Rust
```
3. **Manual customization after generation:**
- Edit generated CLAUDE.md
- Add project-specific conventions
- Include team standards
---
### Issue: Modular architecture not recommended
**Symptoms:**
- Single CLAUDE.md generated for large project
- File exceeds 300 lines
**Causes:**
- Project type not detected as `fullstack`
- Team size estimated as `small`
**Solutions:**
1. **Explicitly request modular:**
```bash
/enhance-claude-md
# Tell Claude:
"Use modular architecture with separate files for backend, frontend, and database"
```
2. **Create backend/ and frontend/ directories:**
```bash
mkdir -p backend frontend
# Then run /enhance-claude-md
```
3. **Manual split if needed:**
```bash
# Create context files manually:
touch backend/CLAUDE.md
touch frontend/CLAUDE.md
# Then run enhancement on each:
cd backend && /enhance-claude-md
cd frontend && /enhance-claude-md
```
---
### Issue: Guardian agent not updating automatically
**Symptoms:**
- Made significant changes
- Started new session
- CLAUDE.md not updated
**Causes:**
- Agent not installed
- Changes below significance threshold
- Git repository not initialized
**Solutions:**
1. **Verify agent installation:**
```bash
ls ~/.claude/agents/claude-md-guardian.md
```
2. **Check git repository:**
```bash
git status
# Agent requires git for change detection
```
3. **Manually invoke agent:**
```bash
# In Claude Code:
Claude, invoke claude-md-guardian to update CLAUDE.md
```
4. **Lower significance threshold (if needed):**
Edit `agent/claude-md-guardian.md`:
```markdown
# Change from 5 to 3 files minimum
- Less than 5 files modified # Change to 3
```
---
## Output Issues
### Issue: CLAUDE.md missing Project Structure diagram
**Symptoms:**
- No ASCII tree diagram in output
- Native format incomplete
**Cause:** Template generation skipped structure section
**Solution:**
1. **Regenerate with explicit request:**
```bash
/enhance-claude-md
# Tell Claude:
"Add Project Structure section with ASCII tree diagram"
```
2. **Manual addition:**
```markdown
## Project Structure
```
project/
├── src/
│ ├── components/
│ └── services/
└── tests/
```
```
---
### Issue: Setup & Installation section generic
**Symptoms:**
- Says "npm install" for Python project
- Incorrect commands
**Cause:** Tech stack detection mismatch
**Solution:**
1. **Verify tech stack detection:**
```bash
# Check project files:
ls package.json requirements.txt go.mod
```
2. **Regenerate with correct context:**
```bash
/enhance-claude-md
"This is a Python project, not Node.js"
```
3. **Manual fix:**
Edit CLAUDE.md and correct commands
---
## Performance Issues
### Issue: Guardian agent too slow
**Symptoms:**
- Agent takes > 30 seconds
- Multiple updates in single session
**Causes:**
- Model set to sonnet instead of haiku
- Full regeneration instead of targeted update
**Solutions:**
1. **Verify agent model:**
```bash
grep "model:" ~/.claude/agents/claude-md-guardian.md
# Should be: model: haiku
```
2. **Check agent workflow:**
- Should use targeted section updates
- Not full file regeneration
---
### Issue: Slash command timeout
**Symptoms:**
- Command starts but never completes
- "Timeout" error
**Causes:**
- Large repository exploration
- Network issues (if fetching remote content)
**Solutions:**
1. **Run in smaller scope:**
```bash
cd specific-directory
/enhance-claude-md
```
2. **Skip exploration, provide context directly:**
```bash
/enhance-claude-md
"Skip exploration. Create CLAUDE.md for TypeScript React app with PostgreSQL."
```
---
## Integration Issues
### Issue: Git commands fail in agent
**Symptoms:**
- Agent error: "git: command not found"
- Agent can't detect changes
**Cause:** Git not installed or not in PATH
**Solutions:**
1. **Install git:**
```bash
# macOS
brew install git
# Ubuntu/Debian
sudo apt-get install git
# Windows
# Download from git-scm.com
```
2. **Verify git installation:**
```bash
git --version
# Should show: git version 2.x
```
---
### Issue: Quality hooks not working
**Symptoms:**
- Pre-commit hook doesn't run
- No validation before commit
**Causes:**
- Hook not executable
- Git not configured to use hooks
- Wrong hooks directory
**Solutions:**
1. **Make hook executable:**
```bash
chmod +x .claude/hooks/pre-commit.sh
```
2. **Configure git:**
```bash
git config core.hooksPath .claude/hooks
```
3. **Test hook manually:**
```bash
./.claude/hooks/pre-commit.sh
# Should validate CLAUDE.md
```
---
## Validation Errors
### Issue: "File length exceeds recommended maximum"
**Symptoms:**
- Validation warning: File > 300 lines
- Quality score penalty
**Cause:** Single file too large
**Solution:**
1. **Split into modular architecture:**
```bash
/enhance-claude-md
"Convert to modular architecture with separate backend and frontend files"
```
2. **Remove unnecessary content:**
- Delete redundant sections
- Move detailed examples to separate docs
- Link to external documentation
---
### Issue: "Missing required sections"
**Symptoms:**
- Validation fails
- Lists missing: Core Principles, Tech Stack, etc.
**Solution:**
1. **Let ClaudeForge add them:**
```bash
/enhance-claude-md
# Claude will identify and add missing sections
```
2. **Manual addition:**
Add required sections following native format
---
## Common Error Messages
### "CLAUDE.md not found"
**Meaning:** File doesn't exist (expected for new projects)
**Action:** Continue with initialization workflow
---
### "Quality score: 0/100"
**Meaning:** Empty or invalid file
**Action:** Regenerate completely
---
### "Invalid project structure"
**Meaning:** Cannot detect project type
**Action:** Add project files (package.json, etc.) or provide context manually
---
### "Template selection failed"
**Meaning:** No matching template for project
**Action:** Provide more specific project context
---
## Getting Help
If your issue isn't covered here:
1. **Check GitHub Issues:**
https://github.com/alirezarezvani/ClaudeForge/issues
2. **Search Discussions:**
https://github.com/alirezarezvani/ClaudeForge/discussions
3. **Open New Issue:**
- Describe the problem
- Include steps to reproduce
- Attach relevant logs or errors
- Mention your OS and Claude Code version
4. **Review Documentation:**
- [INSTALLATION.md](INSTALLATION.md)
- [QUICK_START.md](QUICK_START.md)
- [ARCHITECTURE.md](ARCHITECTURE.md)
- [CLAUDE.md](../CLAUDE.md)
---
## Debug Mode
To get more detailed output:
```bash
# Run installer with verbose output:
bash -x install.sh
# Check Claude Code logs:
# macOS: ~/Library/Logs/Claude Code/
# Linux: ~/.config/claude-code/logs/
# Windows: %APPDATA%\Claude Code\logs\
```
---
**Still having issues?** We're here to help!
Open an issue: https://github.com/alirezarezvani/ClaudeForge/issues/new
+152
View File
@@ -0,0 +1,152 @@
# Basic Usage Examples
Common ClaudeForge usage scenarios.
---
## Example 1: New TypeScript React Project
**Scenario:** Starting fresh project, need CLAUDE.md
**Setup:**
```bash
mkdir my-react-app
cd my-react-app
npm init -y
npm install react react-dom typescript
```
**Run ClaudeForge:**
```
/enhance-claude-md
```
**Claude's Response:**
```
Discovered:
- Project Type: Web App
- Tech Stack: TypeScript, React, Node.js
- Team Size: Solo
- Phase: Prototype
Creating CLAUDE.md (85 lines) with:
- Project structure diagram
- Setup instructions (npm install, npm start)
- Component guidelines
- TypeScript best practices
```
**Output:** Single `CLAUDE.md` file, ~85 lines
---
## Example 2: Python FastAPI Project
**Scenario:** API service, team of 6
**Setup:**
```bash
mkdir api-service
cd api-service
echo "fastapi[all]" > requirements.txt
echo "pytest" >> requirements.txt
mkdir app tests
```
**Run ClaudeForge:**
```
/enhance-claude-md
"This is a Python FastAPI API service. Team of 6 developers, MVP phase."
```
**Output:** `CLAUDE.md` with:
- FastAPI patterns
- Async/await guidelines
- Testing with pytest
- API documentation standards
---
## Example 3: Full-Stack Application
**Scenario:** Large project with backend + frontend
**Setup:**
```bash
mkdir fullstack-app
cd fullstack-app
mkdir backend frontend
cd backend && echo "express" > package.json
cd ../frontend && echo "react" > package.json
```
**Run ClaudeForge:**
```
/enhance-claude-md
```
**Output:** Modular structure
- `CLAUDE.md` (root navigation)
- `backend/CLAUDE.md` (API guidelines)
- `frontend/CLAUDE.md` (React patterns)
---
## Example 4: Enhance Existing Basic File
**Before:**
```markdown
# CLAUDE.md
## Tech Stack
- TypeScript
- React
```
**Run:**
```
/enhance-claude-md
```
**Claude Analyzes:**
```
Quality Score: 25/100
Missing:
- Project Structure
- Setup & Installation
- Core Principles
- Common Commands
```
**After:** Complete 120-line file with all sections
---
## Example 5: Quality Check Before Commit
**Scenario:** Made edits, verify quality
**Run:**
```
/enhance-claude-md
"Just validate, don't make changes"
```
**Output:**
```
Quality Score: 88/100
✅ Length: 245 lines (good)
✅ Structure: All required sections
✅ Formatting: Valid markdown
⚠️ Consider adding: Performance Guidelines
```
---
See also:
- [modular-setup.md](modular-setup.md) - Complex projects
- [integration-examples.md](integration-examples.md) - CI/CD integration
+142
View File
@@ -0,0 +1,142 @@
# Integration Examples
Integrating ClaudeForge with CI/CD and development workflows.
---
## GitHub Actions Integration
**`.github/workflows/validate-claude-md.yml`:**
```yaml
name: Validate CLAUDE.md
on: [push, pull_request]
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install ClaudeForge
run: |
curl -fsSL https://raw.githubusercontent.com/alirezarezvani/ClaudeForge/main/install.sh | bash
export PATH="$HOME/.claude/bin:$PATH"
- name: Validate CLAUDE.md
run: |
# Check file exists
test -f CLAUDE.md || exit 1
# Check minimum quality (requires Python validation)
python3 -c "
from skill.validator import BestPracticesValidator
content = open('CLAUDE.md').read()
validator = BestPracticesValidator(content)
results = validator.validate_all()
passed = sum(1 for r in results if r['passed'])
if passed < 4:
print(f'Quality check failed: {passed}/5 checks passed')
exit(1)
print(f'Quality check passed: {passed}/5 checks')
"
```
---
## Pre-Commit Hook
**`.claude/hooks/pre-commit.sh`:**
```bash
#!/bin/bash
# Validate CLAUDE.md before commit
if [ -f "CLAUDE.md" ]; then
echo "Validating CLAUDE.md..."
# Check file length
lines=$(wc -l < CLAUDE.md)
if [ $lines -lt 20 ] || [ $lines -gt 400 ]; then
echo "Error: CLAUDE.md length ($lines lines) outside recommended range (20-300)"
exit 1
fi
# Check required sections
for section in "Core Principles" "Tech Stack" "Workflow"; do
if ! grep -q "$section" CLAUDE.md; then
echo "Error: Missing required section: $section"
exit 1
fi
done
echo "✅ CLAUDE.md validation passed"
fi
```
**Setup:**
```bash
chmod +x .claude/hooks/pre-commit.sh
git config core.hooksPath .claude/hooks
```
---
## Package.json Scripts
**`package.json`:**
```json
{
"scripts": {
"validate:claude": "python3 -m skill.validator CLAUDE.md",
"update:claude": "echo 'Run: /enhance-claude-md in Claude Code'",
"precommit": "./.claude/hooks/pre-commit.sh"
}
}
```
**Usage:**
```bash
npm run validate:claude # Check CLAUDE.md quality
```
---
## Team Onboarding Automation
**`scripts/onboard-developer.sh`:**
```bash
#!/bin/bash
# Onboard new developer with ClaudeForge
echo "Setting up ClaudeForge for new team member..."
# Install ClaudeForge
curl -fsSL https://raw.githubusercontent.com/alirezarezvani/ClaudeForge/main/install.sh | bash
# Verify CLAUDE.md exists
if [ ! -f "CLAUDE.md" ]; then
echo "No CLAUDE.md found. Run /enhance-claude-md in Claude Code to create one."
fi
echo "✅ ClaudeForge installed. Restart Claude Code to use."
```
---
## CI/CD Pipeline Integration
**GitLab CI (`.gitlab-ci.yml`):**
```yaml
validate_claude:
stage: validate
script:
- python3 -c "import sys; sys.path.insert(0, 'skill'); from validator import BestPracticesValidator; v = BestPracticesValidator(open('CLAUDE.md').read()); results = v.validate_all(); sys.exit(0 if all(r['passed'] for r in results) else 1)"
only:
- merge_requests
```
---
See also:
- [basic-usage.md](basic-usage.md)
- [modular-setup.md](modular-setup.md)
+175
View File
@@ -0,0 +1,175 @@
# Modular Architecture Setup
Examples of modular CLAUDE.md structure for large projects.
---
## When to Use Modular Architecture
- Full-stack projects with distinct frontend/backend
- Team size > 10 developers
- Single CLAUDE.md would exceed 300 lines
- Different teams own different areas
---
## Example: E-Commerce Platform
**Project Structure:**
```
ecommerce/
├── CLAUDE.md # Root navigation
├── backend/
│ ├── CLAUDE.md # API guidelines
│ └── api/
├── frontend/
│ ├── CLAUDE.md # React guidelines
│ └── src/
├── mobile/
│ ├── CLAUDE.md # React Native guidelines
│ └── app/
└── database/
├── CLAUDE.md # Schema guidelines
└── migrations/
```
**Setup:**
```bash
mkdir -p ecommerce/{backend,frontend,mobile,database}
cd ecommerce
# Create basic files for detection
echo '{"dependencies":{"express":""}}' > backend/package.json
echo '{"dependencies":{"react":""}}' > frontend/package.json
echo '{"dependencies":{"react-native":""}}' > mobile/package.json
```
**Run:**
```
/enhance-claude-md
"Use modular architecture for this full-stack e-commerce platform"
```
**Output:**
- `CLAUDE.md` - 95 lines (navigation)
- `backend/CLAUDE.md` - 180 lines (API, auth, payments)
- `frontend/CLAUDE.md` - 165 lines (components, state, cart)
- `mobile/CLAUDE.md` - 145 lines (screens, navigation, offline)
- `database/CLAUDE.md` - 120 lines (schema, migrations, queries)
---
## Root CLAUDE.md (Navigation Hub)
**Content:**
```markdown
# CLAUDE.md
Quick navigation hub for this project.
## Quick Navigation
- [Backend API Guidelines](backend/CLAUDE.md)
- [Frontend React Guidelines](frontend/CLAUDE.md)
- [Mobile App Guidelines](mobile/CLAUDE.md)
- [Database Operations](database/CLAUDE.md)
## Core Principles
1. API-first development
2. Mobile-responsive design
3. Database integrity
4. Comprehensive testing
## Project Structure
```
[ASCII tree diagram]
```
## Common Commands
```bash
# Backend
cd backend && npm run dev
# Frontend
cd frontend && npm start
# Mobile
cd mobile && npm run ios
```
```
---
## Context-Specific Files
### backend/CLAUDE.md
**Focus:**
- API endpoints design (REST/GraphQL)
- Authentication & authorization
- Database queries and optimization
- Error handling patterns
- Testing strategies (unit, integration)
### frontend/CLAUDE.md
**Focus:**
- Component architecture
- State management
- Routing and navigation
- Performance optimization
- Accessibility standards
### mobile/CLAUDE.md
**Focus:**
- Screen layouts
- Native features (camera, GPS, etc.)
- Offline functionality
- Platform-specific patterns (iOS/Android)
- App store deployment
### database/CLAUDE.md
**Focus:**
- Schema design
- Migration procedures
- Query optimization
- Backup strategies
- Data integrity rules
---
## Benefits
✅ **Separation of Concerns:** Each area has focused guidelines
✅ **Team Ownership:** Different teams manage their files
✅ **Maintainability:** Easier to update specific areas
✅ **Scalability:** Add new areas without bloat
✅ **Readability:** Each file stays under 200 lines
---
## Maintenance
**Guardian Agent updates all files:**
```
# New backend dependency added
✅ backend/CLAUDE.md updated: Tech Stack section
# New frontend component pattern
✅ frontend/CLAUDE.md updated: Component Guidelines
# Database schema change
✅ database/CLAUDE.md updated: Schema Documentation
```
---
See also:
- [basic-usage.md](basic-usage.md) - Simple projects
- [integration-examples.md](integration-examples.md) - CI/CD
+156
View File
@@ -0,0 +1,156 @@
#!/bin/bash
# ClaudeForge Quality Hook - Pre-Commit Validation
# Validates CLAUDE.md file quality before allowing commits
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo "🔍 ClaudeForge Quality Hook: Validating CLAUDE.md..."
echo ""
# Check if CLAUDE.md exists
if [ ! -f "CLAUDE.md" ]; then
echo -e "${YELLOW}⚠ Warning: CLAUDE.md not found${NC}"
echo " Skipping validation (no CLAUDE.md to validate)"
exit 0
fi
# Check if skill modules are available (for advanced validation)
SKILL_AVAILABLE=false
if [ -f "skill/validator.py" ] || [ -f "$HOME/.claude/skills/claudeforge-skill/validator.py" ]; then
SKILL_AVAILABLE=true
fi
# Basic Validation (always run)
echo "Running basic validation checks..."
# 1. Check file length
echo -n " ✓ Checking file length... "
LINES=$(wc -l < CLAUDE.md)
if [ $LINES -lt 20 ]; then
echo -e "${RED}FAILED${NC}"
echo -e " ${RED}Error: CLAUDE.md too short ($LINES lines)${NC}"
echo " Minimum: 20 lines recommended"
exit 1
elif [ $LINES -gt 400 ]; then
echo -e "${YELLOW}WARNING${NC}"
echo -e " ${YELLOW}Warning: CLAUDE.md very long ($LINES lines)${NC}"
echo " Recommended: <300 lines (or use modular architecture)"
echo " Continuing anyway..."
else
echo -e "${GREEN}OK${NC} ($LINES lines)"
fi
# 2. Check required sections
echo -n " ✓ Checking required sections... "
MISSING_SECTIONS=()
for section in "Core Principles" "Tech Stack" "Workflow"; do
if ! grep -qi "$section" CLAUDE.md; then
MISSING_SECTIONS+=("$section")
fi
done
if [ ${#MISSING_SECTIONS[@]} -gt 0 ]; then
echo -e "${RED}FAILED${NC}"
echo -e " ${RED}Missing required sections:${NC}"
for section in "${MISSING_SECTIONS[@]}"; do
echo " - $section"
done
echo ""
echo " Run: /enhance-claude-md to add missing sections"
exit 1
else
echo -e "${GREEN}OK${NC}"
fi
# 3. Check for code blocks
echo -n " ✓ Checking for code examples... "
CODE_BLOCKS=$(grep -c '```' CLAUDE.md || echo "0")
if [ $CODE_BLOCKS -lt 2 ]; then
echo -e "${YELLOW}WARNING${NC}"
echo -e " ${YELLOW}Warning: Few code examples ($CODE_BLOCKS blocks)${NC}"
echo " Recommended: Include code examples in your CLAUDE.md"
else
echo -e "${GREEN}OK${NC} ($CODE_BLOCKS blocks)"
fi
# 4. Check for TODO/FIXME placeholders
echo -n " ✓ Checking for placeholders... "
if grep -qi "TODO\|FIXME\|XXX\|\[TBD\]" CLAUDE.md; then
echo -e "${YELLOW}WARNING${NC}"
echo -e " ${YELLOW}Warning: Found TODO/FIXME placeholders${NC}"
grep -n "TODO\|FIXME\|XXX\|\[TBD\]" CLAUDE.md | head -3
echo " Consider completing these before committing"
else
echo -e "${GREEN}OK${NC}"
fi
# 5. Check for potential secrets
echo -n " ✓ Checking for hardcoded secrets... "
if grep -Ei "API_KEY|password|token|secret" CLAUDE.md | grep -v "example\|sample\|placeholder"; then
echo -e "${RED}FAILED${NC}"
echo -e " ${RED}Error: Potential hardcoded secrets found${NC}"
grep -n -Ei "API_KEY|password|token|secret" CLAUDE.md
exit 1
else
echo -e "${GREEN}OK${NC}"
fi
# Advanced Validation (if skill modules available)
if [ "$SKILL_AVAILABLE" = true ]; then
echo ""
echo "Running advanced validation (using ClaudeForge skill)..."
# Determine skill path
if [ -f "skill/validator.py" ]; then
SKILL_PATH="skill"
else
SKILL_PATH="$HOME/.claude/skills/claudeforge-skill"
fi
# Run Python validation
python3 << EOF
import sys
sys.path.insert(0, '$SKILL_PATH')
try:
from validator import BestPracticesValidator
with open('CLAUDE.md', 'r') as f:
content = f.read()
validator = BestPracticesValidator(content)
results = validator.validate_all()
passed = sum(1 for r in results if r['passed'])
total = len(results)
print(f" ✓ Advanced validation: {passed}/{total} checks passed")
if passed < 4:
print(f"\n \033[0;31mError: Only {passed}/{total} validation checks passed\033[0m")
print(" Run: /enhance-claude-md to improve quality")
sys.exit(1)
except Exception as e:
print(f" ⚠ Advanced validation skipped (error: {e})")
pass
EOF
if [ $? -ne 0 ]; then
exit 1
fi
fi
# All checks passed
echo ""
echo -e "${GREEN}✅ CLAUDE.md validation passed!${NC}"
echo ""
echo "Proceeding with commit..."
exit 0
+236
View File
@@ -0,0 +1,236 @@
# ClaudeForge Installer for Windows
# PowerShell installation script
# Version: 1.0.0
#Requires -Version 5.1
$ErrorActionPreference = "Stop"
# Colors for output
function Write-Info {
param([string]$Message)
Write-Host " $Message" -ForegroundColor Blue
}
function Write-Success {
param([string]$Message)
Write-Host "$Message" -ForegroundColor Green
}
function Write-Warning {
param([string]$Message)
Write-Host "$Message" -ForegroundColor Yellow
}
function Write-Error-Custom {
param([string]$Message)
Write-Host "$Message" -ForegroundColor Red
}
# Banner
Write-Host ""
Write-Host "╔════════════════════════════════════════╗" -ForegroundColor Blue
Write-Host "║ ║" -ForegroundColor Blue
Write-Host "" -NoNewline -ForegroundColor Blue
Write-Host "ClaudeForge Installer" -NoNewline -ForegroundColor Green
Write-Host "" -ForegroundColor Blue
Write-Host "║ ║" -ForegroundColor Blue
Write-Host "║ Automated CLAUDE.md Management Tool ║" -ForegroundColor Blue
Write-Host "║ Version 1.0.0 ║" -ForegroundColor Blue
Write-Host "║ ║" -ForegroundColor Blue
Write-Host "╚════════════════════════════════════════╝" -ForegroundColor Blue
Write-Host ""
# Check if running from correct directory
if (-not (Test-Path "skill") -or -not (Test-Path "command") -or -not (Test-Path "agent")) {
Write-Error-Custom "Installation files not found!"
Write-Info "Please run this script from the ClaudeForge repository root."
Write-Info "Usage: cd ClaudeForge; .\install.ps1"
exit 1
}
# Check for Claude Code installation
Write-Info "Checking for Claude Code installation..."
$claudeDir = "$env:USERPROFILE\.claude"
if (-not (Test-Path $claudeDir)) {
Write-Warning "Claude Code user directory (~/.claude) not found."
Write-Info "Creating $claudeDir directory structure..."
New-Item -ItemType Directory -Path "$claudeDir\skills" -Force | Out-Null
New-Item -ItemType Directory -Path "$claudeDir\commands" -Force | Out-Null
New-Item -ItemType Directory -Path "$claudeDir\agents" -Force | Out-Null
Write-Success "Directory structure created"
}
# Ask for installation scope
Write-Host ""
Write-Info "Where would you like to install ClaudeForge?"
Write-Host ""
Write-Host " " -NoNewline
Write-Host "1)" -ForegroundColor Green -NoNewline
Write-Host " User-level (~/.claude/) - Available in all Claude Code projects"
Write-Host " " -NoNewline
Write-Host "2)" -ForegroundColor Green -NoNewline
Write-Host " Project-level (./.claude/) - Available only in current project"
Write-Host ""
$validChoice = $false
while (-not $validChoice) {
$choice = Read-Host "Enter choice [1/2]"
switch ($choice) {
"1" {
$skillsDir = "$env:USERPROFILE\.claude\skills"
$commandsDir = "$env:USERPROFILE\.claude\commands"
$agentsDir = "$env:USERPROFILE\.claude\agents"
$scope = "user-level"
Write-Success "Installing at user-level (all projects)"
$validChoice = $true
}
"2" {
$skillsDir = ".\.claude\skills"
$commandsDir = ".\.claude\commands"
$agentsDir = ".\.claude\agents"
$scope = "project-level"
Write-Success "Installing at project-level (current project only)"
$validChoice = $true
}
default {
Write-Error-Custom "Invalid choice. Please enter 1 or 2."
}
}
}
Write-Host ""
Write-Info "Installation will create:"
Write-Host " • Skill: $skillsDir\claudeforge-skill\"
Write-Host " • Command: $commandsDir\enhance-claude-md\"
Write-Host " • Agent: $agentsDir\claude-md-guardian.md"
Write-Host ""
# Confirm installation
$confirm = Read-Host "Proceed with installation? [Y/n]"
if ([string]::IsNullOrEmpty($confirm)) { $confirm = "Y" }
if ($confirm -notmatch "^[Yy]$") {
Write-Warning "Installation cancelled."
exit 0
}
Write-Host ""
Write-Info "Starting installation..."
Write-Host ""
# Create directories if they don't exist
New-Item -ItemType Directory -Path $skillsDir -Force | Out-Null
New-Item -ItemType Directory -Path $commandsDir -Force | Out-Null
New-Item -ItemType Directory -Path $agentsDir -Force | Out-Null
# Install skill
Write-Info "Installing ClaudeForge skill..."
$skillPath = "$skillsDir\claudeforge-skill"
if (Test-Path $skillPath) {
Write-Warning "Existing skill found. Creating backup..."
$backupName = "claudeforge-skill.backup.$(Get-Date -Format 'yyyyMMdd_HHmmss')"
Move-Item -Path $skillPath -Destination "$skillsDir\$backupName" -Force
Write-Success "Backup created"
}
Copy-Item -Path "skill" -Destination $skillPath -Recurse -Force
Write-Success "Skill installed → $skillPath\"
# 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..."
$backupName = "enhance-claude-md.backup.$(Get-Date -Format 'yyyyMMdd_HHmmss')"
Move-Item -Path $commandPath -Destination "$commandsDir\$backupName" -Force
Write-Success "Backup created"
}
Copy-Item -Path "command" -Destination $commandPath -Recurse -Force
Write-Success "Command installed → $commandPath\"
# Install guardian agent
Write-Info "Installing claude-md-guardian agent..."
$agentPath = "$agentsDir\claude-md-guardian.md"
if (Test-Path $agentPath) {
Write-Warning "Existing agent found. Creating backup..."
$backupName = "claude-md-guardian.md.backup.$(Get-Date -Format 'yyyyMMdd_HHmmss')"
Move-Item -Path $agentPath -Destination "$agentsDir\$backupName" -Force
Write-Success "Backup created"
}
Copy-Item -Path "agent\claude-md-guardian.md" -Destination $agentPath -Force
Write-Success "Agent installed → $agentPath"
# Optional: Install quality hooks
Write-Host ""
$installHooks = Read-Host "Would you like to install quality hooks (pre-commit validation)? [y/N]"
if ([string]::IsNullOrEmpty($installHooks)) { $installHooks = "N" }
if ($installHooks -match "^[Yy]$") {
if ($scope -eq "project-level") {
Write-Info "Installing quality hooks..."
New-Item -ItemType Directory -Path ".claude\hooks" -Force | Out-Null
Copy-Item -Path "hooks\pre-commit.sh" -Destination ".claude\hooks\" -Force
Write-Success "Quality hooks installed → .claude\hooks\"
} else {
Write-Warning "Quality hooks can only be installed at project-level"
Write-Info "Run installer with option 2 in your project directory"
}
}
# Installation complete
Write-Host ""
Write-Host "╔════════════════════════════════════════╗" -ForegroundColor Green
Write-Host "║ ║" -ForegroundColor Green
Write-Host "║ Installation completed successfully!║" -ForegroundColor Green
Write-Host "║ ║" -ForegroundColor Green
Write-Host "╚════════════════════════════════════════╝" -ForegroundColor Green
Write-Host ""
# Next steps
Write-Info "Next steps:"
Write-Host ""
Write-Host " " -NoNewline
Write-Host "1." -ForegroundColor Green -NoNewline
Write-Host " Restart Claude Code (important!)"
Write-Host " " -NoNewline
Write-Host "2." -ForegroundColor Green -NoNewline
Write-Host " Navigate to your project directory"
Write-Host " " -NoNewline
Write-Host "3." -ForegroundColor Green -NoNewline
Write-Host " Run the command:"
Write-Host ""
Write-Host " /enhance-claude-md" -ForegroundColor Blue
Write-Host ""
Write-Host " " -NoNewline
Write-Host "4." -ForegroundColor Green -NoNewline
Write-Host " Follow the interactive prompts"
Write-Host ""
# Additional information
Write-Info "Documentation:"
Write-Host ""
Write-Host " • Quick Start: docs\QUICK_START.md"
Write-Host " • Installation: docs\INSTALLATION.md"
Write-Host " • Architecture: docs\ARCHITECTURE.md"
Write-Host " • Troubleshooting: docs\TROUBLESHOOTING.md"
Write-Host ""
Write-Host " • GitHub: https://github.com/alirezarezvani/ClaudeForge" -ForegroundColor Blue
Write-Host ""
# Uninstall instructions
Write-Info "To uninstall, run:"
Write-Host ""
if ($scope -eq "user-level") {
Write-Host " Remove-Item -Recurse -Force ~\.claude\skills\claudeforge-skill"
Write-Host " Remove-Item -Recurse -Force ~\.claude\commands\enhance-claude-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\commands\enhance-claude-md"
Write-Host " Remove-Item -Force .\.claude\agents\claude-md-guardian.md"
}
Write-Host ""
Write-Success "Thank you for installing ClaudeForge!"
Write-Host ""
Executable
+213
View File
@@ -0,0 +1,213 @@
#!/bin/bash
# ClaudeForge Installer
# Automated installation script for macOS and Linux
# Version: 1.0.0
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Print colored output
print_info() {
echo -e "${BLUE}${NC} $1"
}
print_success() {
echo -e "${GREEN}${NC} $1"
}
print_warning() {
echo -e "${YELLOW}${NC} $1"
}
print_error() {
echo -e "${RED}${NC} $1"
}
# Banner
echo ""
echo -e "${BLUE}╔════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║ ║${NC}"
echo -e "${BLUE}${GREEN}ClaudeForge Installer${BLUE}${NC}"
echo -e "${BLUE}║ ║${NC}"
echo -e "${BLUE}║ Automated CLAUDE.md Management Tool ║${NC}"
echo -e "${BLUE}║ Version 1.0.0 ║${NC}"
echo -e "${BLUE}║ ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════╝${NC}"
echo ""
# Check if running from correct directory
if [ ! -d "skill" ] || [ ! -d "command" ] || [ ! -d "agent" ]; then
print_error "Installation files not found!"
print_info "Please run this script from the ClaudeForge repository root."
print_info "Usage: cd ClaudeForge && ./install.sh"
exit 1
fi
# Check for Claude Code installation
print_info "Checking for Claude Code installation..."
if [ ! -d "$HOME/.claude" ]; then
print_warning "Claude Code user directory (~/.claude) not found."
print_info "Creating ~/.claude directory structure..."
mkdir -p "$HOME/.claude"/{skills,commands,agents}
print_success "Directory structure created"
fi
# Ask for installation scope
echo ""
print_info "Where would you like to install ClaudeForge?"
echo ""
echo " ${GREEN}1)${NC} User-level (~/.claude/) - Available in all Claude Code projects"
echo " ${GREEN}2)${NC} Project-level (./.claude/) - Available only in current project"
echo ""
while true; do
read -p "$(echo -e ${BLUE}Enter choice [1/2]:${NC} )" choice
case $choice in
1)
SKILLS_DIR="$HOME/.claude/skills"
COMMANDS_DIR="$HOME/.claude/commands"
AGENTS_DIR="$HOME/.claude/agents"
SCOPE="user-level"
print_success "Installing at user-level (all projects)"
break
;;
2)
SKILLS_DIR="./.claude/skills"
COMMANDS_DIR="./.claude/commands"
AGENTS_DIR="./.claude/agents"
SCOPE="project-level"
print_success "Installing at project-level (current project only)"
break
;;
*)
print_error "Invalid choice. Please enter 1 or 2."
;;
esac
done
echo ""
print_info "Installation will create:"
echo " • Skill: $SKILLS_DIR/claudeforge-skill/"
echo " • Command: $COMMANDS_DIR/enhance-claude-md/"
echo " • Agent: $AGENTS_DIR/claude-md-guardian.md"
echo ""
# Confirm installation
read -p "$(echo -e ${BLUE}Proceed with installation? [Y/n]:${NC} )" confirm
confirm=${confirm:-Y}
if [[ ! $confirm =~ ^[Yy]$ ]]; then
print_warning "Installation cancelled."
exit 0
fi
echo ""
print_info "Starting installation..."
echo ""
# Create directories if they don't exist
mkdir -p "$SKILLS_DIR" "$COMMANDS_DIR" "$AGENTS_DIR"
# Install skill
print_info "Installing ClaudeForge skill..."
if [ -d "$SKILLS_DIR/claudeforge-skill" ]; then
print_warning "Existing skill found. Creating backup..."
mv "$SKILLS_DIR/claudeforge-skill" "$SKILLS_DIR/claudeforge-skill.backup.$(date +%Y%m%d_%H%M%S)"
print_success "Backup created"
fi
cp -r skill "$SKILLS_DIR/claudeforge-skill"
print_success "Skill installed → $SKILLS_DIR/claudeforge-skill/"
# Install slash command
print_info "Installing /enhance-claude-md command..."
if [ -d "$COMMANDS_DIR/enhance-claude-md" ]; then
print_warning "Existing command 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/"
# Install guardian agent
print_info "Installing claude-md-guardian agent..."
if [ -f "$AGENTS_DIR/claude-md-guardian.md" ]; then
print_warning "Existing agent found. Creating backup..."
mv "$AGENTS_DIR/claude-md-guardian.md" "$AGENTS_DIR/claude-md-guardian.md.backup.$(date +%Y%m%d_%H%M%S)"
print_success "Backup created"
fi
cp agent/claude-md-guardian.md "$AGENTS_DIR/"
print_success "Agent installed → $AGENTS_DIR/claude-md-guardian.md"
# Optional: Install quality hooks
echo ""
read -p "$(echo -e ${BLUE}Would you like to install quality hooks (pre-commit validation)? [y/N]:${NC} )" install_hooks
install_hooks=${install_hooks:-N}
if [[ $install_hooks =~ ^[Yy]$ ]]; then
if [ "$SCOPE" == "project-level" ]; then
print_info "Installing quality hooks..."
mkdir -p .claude/hooks
cp hooks/pre-commit.sh .claude/hooks/
chmod +x .claude/hooks/pre-commit.sh
print_success "Quality hooks installed → .claude/hooks/"
else
print_warning "Quality hooks can only be installed at project-level"
print_info "Run installer with option 2 in your project directory"
fi
fi
# Installation complete
echo ""
echo -e "${GREEN}╔════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║ ║${NC}"
echo -e "${GREEN}║ Installation completed successfully!${NC}"
echo -e "${GREEN}║ ║${NC}"
echo -e "${GREEN}╚════════════════════════════════════════╝${NC}"
echo ""
# Next steps
print_info "Next steps:"
echo ""
echo " ${GREEN}1.${NC} Restart Claude Code (important!)"
echo " ${GREEN}2.${NC} Navigate to your project directory"
echo " ${GREEN}3.${NC} Run the command:"
echo ""
echo " ${BLUE}/enhance-claude-md${NC}"
echo ""
echo " ${GREEN}4.${NC} Follow the interactive prompts"
echo ""
# Additional information
print_info "Documentation:"
echo ""
echo " • Quick Start: docs/QUICK_START.md"
echo " • Installation: docs/INSTALLATION.md"
echo " • Architecture: docs/ARCHITECTURE.md"
echo " • Troubleshooting: docs/TROUBLESHOOTING.md"
echo ""
echo " • GitHub: ${BLUE}https://github.com/alirezarezvani/ClaudeForge${NC}"
echo ""
# Uninstall instructions
print_info "To uninstall, run:"
echo ""
if [ "$SCOPE" == "user-level" ]; then
echo " rm -rf ~/.claude/skills/claudeforge-skill"
echo " rm -rf ~/.claude/commands/enhance-claude-md"
echo " rm -f ~/.claude/agents/claude-md-guardian.md"
else
echo " rm -rf ./.claude/skills/claudeforge-skill"
echo " rm -rf ./.claude/commands/enhance-claude-md"
echo " rm -f ./.claude/agents/claude-md-guardian.md"
fi
echo ""
print_success "Thank you for installing ClaudeForge!"
echo ""
+383
View File
@@ -0,0 +1,383 @@
# How to Use the claude-md-enhancer Skill
Hey Claude—I just added the "claude-md-enhancer" skill. Can you help me create or improve my project's CLAUDE.md file?
## Example Invocations
### Example 1: Initialize CLAUDE.md for New Project (🆕 Interactive Workflow)
**Use Case**: You don't have a CLAUDE.md file yet and want Claude to create one by understanding your project first.
```
Hey Claude—I just added the "claude-md-enhancer" skill. I don't have a CLAUDE.md file yet. Can you help me create one for this project?
```
**What Claude Will Do**:
1. Check if CLAUDE.md exists (it doesn't)
2. Explore your repository using built-in commands
3. Analyze project structure, tech stack, team size
4. Show you the discoveries and ask for confirmation
5. Create customized CLAUDE.md file(s) after your approval
6. Enhance with best practices
**Interactive Conversation Example**:
```
User: "I don't have a CLAUDE.md. Can you create one?"
Claude: "I'll explore your repository first to understand the project.
[Exploring repository structure...]
[Analyzing package.json, requirements.txt, etc...]
[Detecting workflows and patterns...]
Based on my exploration, here's what I discovered:
📦 **Project Type**: Full-Stack Application
🛠️ **Tech Stack**: TypeScript, React, Node.js, PostgreSQL, Docker
👥 **Team Size**: Small (5 developers detected from git history)
🚀 **Development Phase**: MVP (CI/CD present, production features in progress)
⚙️ **Workflows**: TDD (tests/ folder found), CI/CD (GitHub Actions detected)
📋 **Recommended Structure**:
Modular architecture - I recommend creating:
- Root CLAUDE.md (navigation hub, ~100 lines)
- backend/CLAUDE.md (API and database guidelines, ~150 lines)
- frontend/CLAUDE.md (React component guidelines, ~175 lines)
Would you like me to create these files with these settings?
You can also ask me to adjust any of these if they don't look right."
User: "Yes, that looks perfect. Please proceed."
Claude: "Creating your customized CLAUDE.md files...
✅ Created CLAUDE.md (108 lines)
- Quick Navigation section with links
- 5 Core Principles (TDD-focused)
- Tech Stack summary
- Quick reference commands
✅ Created backend/CLAUDE.md (156 lines)
- API Design guidelines (RESTful, versioning)
- Database operations (migrations, queries)
- Error handling patterns
- Testing requirements (80% coverage)
✅ Created frontend/CLAUDE.md (182 lines)
- React component standards (functional, hooks)
- State management (Context API)
- Styling guidelines (Tailwind)
- Performance optimization
🎉 Your project is now set up for efficient AI-assisted development!
Next steps:
1. Review the generated files
2. Customize core principles for your team
3. Add any project-specific conventions
4. Start developing with Claude Code!"
User: "Perfect, thanks!"
```
**When to Use This**:
- New project without CLAUDE.md
- Want Claude to understand your project first
- Need recommendations on structure
- Prefer interactive, conversational setup
---
### Example 2: Quick Initialization (Skip Exploration)
**Use Case**: You know your project details and want to skip the exploration step.
```
Hey Claude—I just added the "claude-md-enhancer" skill. Create a CLAUDE.md for my TypeScript React project with PostgreSQL. Small team (5 devs), MVP phase, using TDD and CI/CD.
```
**What Claude Will Do**:
- Skip exploration (you provided context)
- Generate CLAUDE.md immediately
- Customize for specified tech stack
- No confirmation needed (direct request)
---
### Example 3: Analyze Existing CLAUDE.md
**Use Case**: You have an existing CLAUDE.md file and want to know what's missing or could be improved.
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you analyze my current CLAUDE.md file and tell me what's missing or could be improved? Here it is:
# CLAUDE.md
## Tech Stack
- TypeScript
- React
- Node.js
## Workflow
- Use Git for version control
- Write tests
```
**What Claude Will Do**:
- Analyze file structure and completeness
- Calculate quality score (0-100)
- Identify missing sections
- Provide actionable recommendations
---
### Example 2: Generate New CLAUDE.md for TypeScript React Project
**Use Case**: Starting a new TypeScript React project and need a CLAUDE.md file from scratch.
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you create a CLAUDE.md file for my TypeScript React project? We're a team of 5 developers working on an MVP. We use PostgreSQL, Docker, and follow TDD practices.
```
**What Claude Will Do**:
- Generate complete CLAUDE.md tailored to TypeScript/React
- Include tech stack references
- Add TDD workflow guidelines
- Customize for small team (5 people)
- Include MVP-phase appropriate content
---
### Example 3: Enhance Existing File with Missing Sections
**Use Case**: You have a basic CLAUDE.md but it's missing important sections.
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you enhance my existing CLAUDE.md by adding Testing Requirements, Error Handling Patterns, and Performance Guidelines sections? Here's what I have:
# CLAUDE.md
## Core Principles
1. Write tests first
2. Use TypeScript
## Tech Stack
- TypeScript
- React
- PostgreSQL
```
**What Claude Will Do**:
- Preserve your existing content
- Add the three requested sections
- Populate sections with relevant best practices
- Ensure consistency with your existing style
---
### Example 4: Generate Modular CLAUDE.md Architecture
**Use Case**: You have a complex full-stack project and want separate CLAUDE.md files for different parts.
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you create a modular CLAUDE.md setup for my full-stack project? I need separate files for:
- Backend (Python/FastAPI)
- Frontend (React/TypeScript)
- Database (PostgreSQL)
We're a team of 8, building a production system.
```
**What Claude Will Do**:
- Generate root CLAUDE.md (navigation hub)
- Create backend/CLAUDE.md with API and service guidelines
- Create frontend/CLAUDE.md with React component standards
- Create database/CLAUDE.md with migration and query guidelines
- Customize for medium team size and production phase
---
### Example 5: Validate Existing CLAUDE.md
**Use Case**: You want to check if your CLAUDE.md follows best practices.
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you validate my CLAUDE.md file against best practices? Here it is: [paste your CLAUDE.md content]
```
**What Claude Will Do**:
- Check file length (warns if >300 lines)
- Verify required sections are present
- Check markdown formatting quality
- Detect anti-patterns (hardcoded secrets, placeholders)
- Provide pass/fail status with detailed feedback
---
### Example 6: Create CLAUDE.md for Python API Project
**Use Case**: Building a Python FastAPI backend service.
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you create a CLAUDE.md for my Python FastAPI project? We're building a microservice API with PostgreSQL, Redis, and deploying with Docker/Kubernetes. Team of 12 developers, enterprise production environment.
```
**What Claude Will Do**:
- Generate API-focused CLAUDE.md
- Include FastAPI-specific best practices
- Add microservices architecture guidelines
- Customize for large team (12 developers)
- Include enterprise-grade standards
---
### Example 7: Add Specific Section to Existing File
**Use Case**: You need to add just one specific section.
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you add a "Security Checklist" section to my existing CLAUDE.md?
```
**What Claude Will Do**:
- Generate Security Checklist section
- Include relevant security best practices
- Merge seamlessly with existing content
- Maintain your file's existing structure
---
### Example 8: Convert Generic CLAUDE.md to Tech-Specific
**Use Case**: You have a generic CLAUDE.md and want to customize it for your tech stack.
```
Hey Claude—I just added the "claude-md-enhancer" skill. I have a generic CLAUDE.md file. Can you customize it for my Vue 3, Go (Gin), and MongoDB tech stack?
```
**What Claude Will Do**:
- Detect your current content
- Add Vue 3-specific component guidelines
- Add Go/Gin API patterns
- Add MongoDB query optimization practices
- Preserve your existing custom sections
---
### Example 9: Generate Context-Specific File Only
**Use Case**: You just need guidelines for one part of your project.
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you create a backend/CLAUDE.md file for my Node.js Express API project?
```
**What Claude Will Do**:
- Generate backend-specific guidelines
- Include Express.js patterns
- Add API design best practices
- Include testing and error handling sections
---
### Example 10: Quick Quality Check
**Use Case**: Quick validation before committing your CLAUDE.md file.
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you do a quick quality check on my CLAUDE.md? Give me a quality score and top 3 improvements.
```
**What Claude Will Do**:
- Calculate quality score (0-100)
- Identify top 3 issues/improvements
- Provide concise, actionable feedback
- Highlight critical issues first
---
## What to Provide
When using this skill, provide any of the following:
### For Analysis
- Existing CLAUDE.md content (paste the full text)
- Project context (optional but helpful):
- Project type (web app, API, mobile, etc.)
- Tech stack (languages, frameworks, tools)
- Team size (solo, small, medium, large)
- Development phase (prototype, MVP, production)
### For Generation
- Project type (web_app, api, fullstack, cli, library, mobile, desktop)
- Tech stack (e.g., "TypeScript, React, Node, PostgreSQL")
- Team size (solo, small <10, medium 10-50, large 50+)
- Development phase (prototype, MVP, production, enterprise)
- Key workflows (TDD, CI/CD, documentation-first, agile)
- Modular architecture preference (yes/no)
### For Enhancement
- Current CLAUDE.md content
- Specific sections to add or improve
- Any new technologies adopted
---
## What You'll Get
### Analysis Output
- Quality score (0-100)
- Missing sections list
- Issues and warnings
- Prioritized recommendations
- Structure analysis
### Generation Output
- Complete CLAUDE.md file(s)
- Tailored to your tech stack
- Appropriate for your team size
- Customized for development phase
- Modular architecture if requested
### Validation Output
- Pass/fail status
- Detailed validation results
- Errors and warnings
- Specific improvement suggestions
### Enhancement Output
- Updated CLAUDE.md with new sections
- Preserved existing content
- Consistent formatting
- Integrated recommendations
---
## Pro Tips
1. **Start Simple**: For new projects, start with a minimal CLAUDE.md and expand as needed
2. **Use Modular Architecture**: For projects >3 major components, use separate files (backend/, frontend/, etc.)
3. **Keep Root File Concise**: Aim for <150 lines in root CLAUDE.md, use it as navigation
4. **Validate Regularly**: Run quality checks when team or tech stack changes
5. **Update Quarterly**: Review and update CLAUDE.md every 3 months or when stack changes
6. **Be Specific**: The more context you provide, the better the customization
7. **Iterate**: Start with generated content, then customize for your specific needs
---
## Common Scenarios
| Scenario | Recommended Approach |
|----------|---------------------|
| New project, solo developer | Generate minimal CLAUDE.md (~75 lines) |
| New project, small team | Generate core CLAUDE.md (~125 lines) |
| Existing project, needs cleanup | Analyze first, then enhance based on recommendations |
| Large project, multiple teams | Generate modular architecture (root + context files) |
| Pre-commit check | Quick validate with quality score |
| Tech stack changed | Enhance with new tech-specific guidelines |
| Team grew significantly | Regenerate with new team size configuration |
---
**Remember**: The goal is to make Claude Code more efficient and context-aware for your project. Start with what's helpful, iterate based on usage, and keep it maintainable!
+542
View File
@@ -0,0 +1,542 @@
# claude-md-enhancer
> **Analyze, generate, and enhance CLAUDE.md files for any project type with intelligent templates and best practices.**
A comprehensive Claude Code skill that helps teams create and maintain high-quality CLAUDE.md files. Supports analysis, validation, generation, and enhancement with tech stack customization, team size adaptation, and modular architecture.
## Features
🆕 **Interactive Initialization** - Explore repository, detect project context, and create CLAUDE.md through conversational workflow
**100% Native Format Compliance** - All generated files follow official Claude Code format with project structure diagrams, setup instructions, architecture sections, and file structure explanations
**Intelligent Analysis** - Scan and evaluate existing CLAUDE.md files for quality and completeness
🎯 **Best Practice Validation** - Check against Anthropic guidelines and community standards
🚀 **Smart Generation** - Create customized CLAUDE.md files from scratch
🔧 **Enhancement** - Add missing sections and improve existing files
📦 **Modular Architecture** - Support context-specific files (backend/, frontend/, database/)
🛠️ **Tech Stack Customization** - Tailor guidelines to your technologies
👥 **Team Size Adaptation** - Adjust complexity for solo, small, medium, or large teams
📊 **Quality Scoring** - Get 0-100 quality scores with actionable recommendations
---
## Quick Start
### Installation
#### Option 1: Claude Code (Project-Level)
```bash
# Copy skill folder to your project
cp -r claude-md-enhancer /path/to/your/project/.claude/skills/
# Restart Claude Code or reload skills
```
#### Option 2: Claude Code (User-Level)
```bash
# Copy skill folder to user skills directory
cp -r claude-md-enhancer ~/.claude/skills/
# Available across all your projects
```
#### Option 3: Claude Apps
```
1. Open Claude in browser
2. Go to Skills settings
3. Upload claude-md-enhancer.zip
4. Enable the skill
```
### Basic Usage
#### New Project (Interactive Initialization)
```
Hey Claude—I just added the "claude-md-enhancer" skill. I don't have a CLAUDE.md file yet. Can you help me create one for this project?
```
Claude will:
1. Explore your repository
2. Detect project type, tech stack, team size
3. Show discoveries and ask for confirmation
4. Create customized CLAUDE.md file(s)
#### Existing Project
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you analyze my CLAUDE.md and suggest improvements?
```
See [HOW_TO_USE.md](HOW_TO_USE.md) for comprehensive examples.
---
## Architecture
### Module Overview
```
claude-md-enhancer/
├── SKILL.md # Skill definition with YAML frontmatter
├── analyzer.py # Analyzes existing CLAUDE.md files
├── validator.py # Validates against best practices
├── generator.py # Generates new content
├── template_selector.py # Selects appropriate templates
├── sample_input.json # Example inputs
├── expected_output.json # Expected outputs
├── HOW_TO_USE.md # Usage examples
└── README.md # This file
```
### Python Modules
#### `workflow.py` - Initialization Workflow (New!)
**Class**: `InitializationWorkflow`
**Key Methods**:
- `check_claude_md_exists()` - Detect if CLAUDE.md exists
- `generate_exploration_prompt()` - Guide Claude to explore repository
- `analyze_discoveries(results)` - Analyze exploration results to detect project context
- `generate_confirmation_prompt(context)` - Create user confirmation prompt
- `get_workflow_steps()` - Get complete 7-step workflow
**Workflow Steps**:
1. Check for existing CLAUDE.md
2. Explore repository (built-in Claude Code command)
3. Analyze discoveries (project type, tech stack, team size)
4. Request user confirmation
5. Create CLAUDE.md file(s)
6. Enhance with best practices
7. Provide summary
**Detection Capabilities**:
- **Project Types**: web_app, api, fullstack, cli, library, mobile, desktop
- **Tech Stacks**: TypeScript, Python, Go, React, Vue, FastAPI, Django, PostgreSQL, Docker, Kubernetes, etc.
- **Team Sizes**: solo, small (<10), medium (10-50), large (50+)
- **Development Phases**: prototype, mvp, production, enterprise
- **Workflows**: TDD, CI/CD, documentation-first, agile
#### `analyzer.py` - File Analysis
**Class**: `CLAUDEMDAnalyzer`
**Key Methods**:
- `analyze_file()` - Comprehensive file analysis
- `detect_sections()` - Identify all sections and subsections
- `calculate_quality_score()` - Score 0-100 based on multiple factors
- `generate_recommendations()` - Actionable improvement suggestions
**Quality Score Breakdown** (0-100):
- Length appropriateness: 25 points
- Section completeness: 25 points
- Formatting quality: 20 points
- Content specificity: 15 points
- Modular organization: 15 points
#### `validator.py` - Best Practices Validation
**Class**: `BestPracticesValidator`
**Key Methods**:
- `validate_length()` - Check file length (20-300 lines recommended)
- `validate_structure()` - Verify required sections and hierarchy
- `validate_formatting()` - Check markdown formatting quality
- `validate_completeness()` - Ensure critical content included
- `validate_all()` - Run all validation checks
**Validation Categories**:
- File length (MUST be 20-300 lines)
- Structure (required sections: Core Principles, Workflow)
- Formatting (balanced code blocks, heading hierarchy)
- Completeness (code examples, links, lists)
- Anti-patterns (hardcoded secrets, placeholders, broken links)
#### `generator.py` - Content Generation
**Class**: `ContentGenerator`
**Key Methods**:
- `generate_root_file()` - Create main CLAUDE.md (navigation hub)
- `generate_context_file(context)` - Create context-specific files
- `generate_section(name)` - Generate individual sections
- `merge_with_existing(content, sections)` - Enhance existing files
**Supported Contexts**:
- `backend` - API design, database, error handling
- `frontend` - Components, state, styling, performance
- `database` - Schema, migrations, query optimization
- `docs` - Documentation standards
- `.github` - CI/CD workflows
#### `template_selector.py` - Template Selection
**Class**: `TemplateSelector`
**Key Methods**:
- `select_template()` - Choose template based on project context
- `customize_template(template)` - Generate customized content
- `recommend_modular_structure()` - Determine if modular architecture needed
**Template Matrix**:
| Project Type | Team Size | Target Lines | Complexity |
|--------------|-----------|--------------|------------|
| Web App | Solo | 75 | Minimal |
| API | Small (<10) | 125 | Core |
| Full-Stack | Medium (10-50) | 200 | Detailed |
| Library | Large (50+) | 275 | Comprehensive |
**Supported Project Types**:
- `web_app` - Frontend-focused (React, Vue, Angular)
- `api` - Backend services (REST, GraphQL)
- `fullstack` - Integrated frontend + backend
- `cli` - Command-line tools
- `library` - Reusable packages
- `mobile` - React Native, Flutter
- `desktop` - Electron, Tauri
**Supported Tech Stacks**:
- TypeScript/JavaScript (React, Vue, Angular, Node)
- Python (Django, FastAPI, Flask)
- Go (Gin, Echo)
- Java/Kotlin (Spring Boot)
- Ruby (Rails)
- And more...
---
## Use Cases
### 1. Analyze Existing CLAUDE.md
**Scenario**: You have a CLAUDE.md file and want quality feedback.
**Input**: Existing file content + project context
**Output**:
- Quality score (0-100)
- Missing sections identified
- Issues and warnings
- Prioritized recommendations
**Example**:
```
Quality Score: 75/100
Missing Sections:
- Testing Requirements
- Error Handling Patterns
Recommendations:
1. Add testing requirements section
2. Reduce file length from 320 to <300 lines
3. Consider modular architecture
```
---
### 2. Generate New CLAUDE.md from Scratch
**Scenario**: Starting new project, need CLAUDE.md file.
**Input**: Project context (type, tech stack, team size, phase)
**Output**: Complete CLAUDE.md tailored to your specifications
**Generated Sections**:
- Quick Navigation (if modular)
- Core Principles
- Tech Stack
- Workflow Instructions
- Testing Requirements
- Error Handling
- Documentation Standards
- Performance Guidelines
---
### 3. Enhance Existing File
**Scenario**: Your CLAUDE.md is missing important sections.
**Input**: Current content + sections to add
**Output**: Enhanced file with new sections, preserving existing content
**Preservation**:
- Keeps all existing content intact
- Adds new sections seamlessly
- Maintains consistent formatting
- Respects your style choices
---
### 4. Generate Modular Architecture
**Scenario**: Large project needs separate CLAUDE.md files.
**Input**: Project context + modular flag + subdirectories
**Output**:
- Root CLAUDE.md (navigation hub, <150 lines)
- backend/CLAUDE.md (API, database, testing)
- frontend/CLAUDE.md (components, state, styling)
- database/CLAUDE.md (schema, migrations, queries)
- .github/CLAUDE.md (CI/CD workflows)
**When Recommended**:
- Full-stack projects
- Large teams (10+ developers)
- Production/enterprise phase
- 3+ major tech components
---
### 5. Validate Before Commit
**Scenario**: Quick quality check before committing.
**Input**: Current CLAUDE.md content
**Output**:
- Pass/fail status
- Validation results (5 checks)
- Errors and warnings
- Pass/fail counts
**Validation Checks**:
1. File length (20-300 lines)
2. Structure (required sections present)
3. Formatting (markdown quality)
4. Completeness (essential content)
5. Anti-patterns (security, placeholders)
---
## Sample Data
### Sample Input
See [sample_input.json](sample_input.json) for 6 realistic scenarios:
1. **analyze_existing** - Analyze basic CLAUDE.md file
2. **create_new_fullstack** - Generate modular full-stack setup
3. **enhance_with_missing_sections** - Add specific sections
4. **create_modular_architecture** - Large team, enterprise setup
5. **validate_existing** - Validate production-ready file
6. **generate_context_specific** - Backend-only file
### Expected Output
See [expected_output.json](expected_output.json) for:
- Analysis reports with quality scores
- Generated CLAUDE.md content
- Validation results
- Enhanced file examples
---
## Best Practices
### Critical Validation Rule ⚠️
**"Always validate your output against official native examples before declaring complete."**
Before finalizing any CLAUDE.md generation:
1. Compare output against `/update-claude-md` slash command format
2. Check official Claude Code documentation for required sections
3. Verify all native format sections are present (Overview, Project Structure, File Structure, Setup & Installation, Architecture, etc.)
4. Cross-check against reference examples in `examples/` folder
### For New Projects
1. **Start Minimal** - Generate 50-100 line file, expand as needed
2. **Add Tech Stack Early** - Include technologies immediately
3. **Update with Team Growth** - Regenerate when team size changes
4. **Consider Modular** - Use separate files if >3 major components
### For Existing Projects
1. **Analyze First** - Understand current state before changes
2. **Preserve Custom Content** - Don't overwrite your specific guidelines
3. **Validate Regularly** - Check quality when stack or team changes
4. **Iterate** - Start with enhancements, full regeneration if needed
### General Guidelines
1. **Keep Root Concise** - Max 150 lines, use as navigation hub
2. **Use Context Files** - backend/, frontend/, etc. for details
3. **Avoid Duplication** - Each guideline appears once
4. **Link External Docs** - Don't copy official documentation
5. **Update Quarterly** - Review and refresh every 3 months
---
## Configuration
### Project Context Parameters
```json
{
"type": "fullstack", // Project type
"tech_stack": ["typescript", "react", "node"], // Technologies
"team_size": "small", // Team size
"phase": "mvp", // Development phase
"workflows": ["tdd", "cicd"], // Key workflows
"modular": true, // Modular architecture
"subdirectories": ["backend", "frontend"] // Subdirs for context files
}
```
#### Type Options
- `web_app` - Frontend-focused
- `api` - Backend services
- `fullstack` - Full-stack application
- `cli` - Command-line tool
- `library` - Reusable package
- `mobile` - Mobile application
- `desktop` - Desktop application
#### Team Size Options
- `solo` - 1 developer
- `small` - 2-9 developers
- `medium` - 10-49 developers
- `large` - 50+ developers
#### Phase Options
- `prototype` - Early exploration
- `mvp` - Minimum viable product
- `production` - Production system
- `enterprise` - Enterprise-grade
---
## Troubleshooting
### Quality Score Lower Than Expected
**Issue**: Quality score is 35/100
**Solutions**:
1. Check file length (should be 20-300 lines)
2. Add missing required sections (Core Principles, Workflow)
3. Include code examples
4. Add tech stack references
5. Consider modular architecture if >300 lines
---
### Generated Content Too Generic
**Issue**: CLAUDE.md lacks specific guidance
**Solutions**:
1. Provide detailed tech stack (specific frameworks/versions)
2. Specify workflows (TDD, CI/CD, documentation-first)
3. Include team size for appropriate complexity
4. Add development phase for priority focus
5. Customize generated content for your needs
---
### Modular Architecture Not Recommended
**Issue**: Single file generated, wanted modular
**Solutions**:
1. Set `"modular": true` explicitly
2. Ensure project type is `fullstack`
3. Use team size `medium` or `large`
4. Specify phase as `production` or `enterprise`
5. Provide 3+ tech stack components
---
## Version
**Version**: 1.0.0
**Last Updated**: November 2025
**Compatible**: Claude Code 2.0+, Claude Apps, Claude API
---
## Contributing
Found a bug or have a suggestion? This skill is part of the [claude-code-skills-factory](https://github.com/anthropics/claude-code-skills-factory) repository.
---
## License
MIT License - See LICENSE file for details
---
## Companion Agent: claude-md-guardian 🛡️
For automatic CLAUDE.md maintenance throughout your project lifecycle, use the **claude-md-guardian** agent:
### What It Does
- **Auto-Sync**: Updates CLAUDE.md based on project changes
- **Background Operation**: Works independently after milestones
- **Smart Detection**: Only updates when significant changes occur
- **Token-Efficient**: Uses haiku model for routine updates
### When It Triggers
**Automatically**:
- SessionStart (checks git changes)
- After feature completion
- After major refactoring
- After new dependencies added
- After architecture changes
**Manually**:
- Via `/enhance-claude-md` slash command
- Direct invocation
### Installation
```bash
# User-level (all projects)
cp generated-agents/claude-md-guardian.md ~/.claude/agents/
# Project-level (current project)
cp generated-agents/claude-md-guardian.md .claude/agents/
```
### How They Work Together
```
claude-md-guardian (agent) → Uses → claude-md-enhancer (skill)
Detects changes → Invokes skill → Updates CLAUDE.md
```
**Result**: Your CLAUDE.md stays synchronized with your codebase automatically!
See `generated-agents/claude-md-guardian-README.md` for complete agent documentation.
---
## Support
- **Documentation**: See [SKILL.md](SKILL.md) for complete documentation
- **Examples**: See [HOW_TO_USE.md](HOW_TO_USE.md) for usage examples
- **Companion Agent**: See `../../generated-agents/claude-md-guardian-README.md`
- **Slash Command**: See `../../generated-commands/enhance-claude-md/README.md`
- **Issues**: Report bugs in the main repository
- **Community**: Share your CLAUDE.md setups and best practices
---
**Happy coding with Claude! 🚀**
Make your AI-assisted development more efficient with well-structured CLAUDE.md files and automatic maintenance via claude-md-guardian!
+446
View File
@@ -0,0 +1,446 @@
---
name: claude-md-enhancer
description: Analyzes, generates, and enhances CLAUDE.md files for any project type using best practices, modular architecture support, and tech stack customization. Use when setting up new projects, improving existing CLAUDE.md files, or establishing AI-assisted development standards.
---
# CLAUDE.md File Enhancer
This skill provides comprehensive CLAUDE.md file generation and enhancement for Claude Code projects. It analyzes existing files, validates against best practices, and generates customized guidelines tailored to your project type, tech stack, and team size.
## Capabilities
- **🆕 Interactive Initialization**: Intelligent workflow that explores your repository, detects project type and tech stack, asks for confirmation, then creates customized CLAUDE.md files
- **✨ 100% Native Format Compliance**: All generated files follow official Claude Code format with project structure diagrams, setup instructions, architecture sections, and file structure explanations (matching `/update-claude-md` slash command)
- **Analyze Existing Files**: Scan and evaluate current CLAUDE.md files for structure, completeness, and quality
- **Validate Best Practices**: Check against Anthropic guidelines (file length, required sections, formatting standards)
- **Generate New Files**: Create complete CLAUDE.md files from scratch for new projects
- **Enhance Existing Files**: Add missing sections, improve structure, and update to latest best practices
- **Modular Architecture**: Support context-specific CLAUDE.md files in subdirectories (backend/, frontend/, docs/)
- **Tech Stack Customization**: Tailor guidelines to specific technologies (TypeScript, Python, Go, React, Vue, etc.)
- **Team Size Adaptation**: Adjust complexity based on team size (solo, small <10, large 10+)
- **Template Selection**: Choose appropriate template based on project complexity and development phase
## Input Requirements
### For Analysis and Enhancement
Provide existing CLAUDE.md file content or file path:
```json
{
"mode": "enhance",
"file_path": "CLAUDE.md",
"content": "[existing CLAUDE.md content]",
"project_context": {
"type": "web_app",
"tech_stack": ["typescript", "react", "node", "postgresql"],
"team_size": "small",
"phase": "mvp"
}
}
```
### For New File Generation
Provide project context:
```json
{
"mode": "create",
"project_context": {
"type": "api",
"tech_stack": ["python", "fastapi", "postgresql", "docker"],
"team_size": "medium",
"phase": "production",
"workflows": ["tdd", "cicd", "documentation_first"]
},
"modular": true,
"subdirectories": ["backend", "database", "docs"]
}
```
### Context Parameters
- **type**: Project type (`web_app`, `api`, `fullstack`, `cli`, `library`, `mobile`, `desktop`)
- **tech_stack**: Array of technologies (e.g., `["typescript", "react", "node"]`)
- **team_size**: `solo`, `small` (<10), `medium` (10-50), `large` (50+)
- **phase**: Development phase (`prototype`, `mvp`, `production`, `enterprise`)
- **workflows**: Key workflows (`tdd`, `cicd`, `documentation_first`, `agile`, etc.)
## Output Formats
### Analysis Report
```json
{
"analysis": {
"file_size": 450,
"line_count": 320,
"sections_found": [
"Quick Navigation",
"Core Principles",
"Tech Stack",
"Workflow Instructions"
],
"missing_sections": [
"Testing Requirements",
"Error Handling Patterns"
],
"issues": [
{
"type": "length_warning",
"severity": "medium",
"message": "File exceeds recommended 300 lines (320 lines)"
},
{
"type": "missing_section",
"severity": "low",
"message": "Consider adding 'Testing Requirements' section"
}
],
"quality_score": 75,
"recommendations": [
"Split into modular files (backend/CLAUDE.md, frontend/CLAUDE.md)",
"Add testing requirements section",
"Reduce root file to <150 lines"
]
}
}
```
### Generated Content
Complete CLAUDE.md file content or specific sections to add:
```markdown
# CLAUDE.md
This file provides guidance for Claude Code when working with this project.
## Quick Navigation
- [Backend Guidelines](backend/CLAUDE.md)
- [Frontend Guidelines](frontend/CLAUDE.md)
- [Database Operations](database/CLAUDE.md)
- [CI/CD Workflows](.github/CLAUDE.md)
## Core Principles
1. **Test-Driven Development**: Write tests before implementation
2. **Type Safety First**: Use TypeScript strict mode throughout
3. **Component Composition**: Favor small, reusable components
4. **Error Handling**: Always handle errors with proper logging
5. **Documentation Updates**: Keep docs in sync with code changes
[... additional sections based on template ...]
```
## How to Use
### Example 1: Initialize CLAUDE.md for New Project (Interactive)
```
Hey Claude—I just added the "claude-md-enhancer" skill. I don't have a CLAUDE.md file yet. Can you help me create one for this project?
```
**What Happens**:
1. Claude checks if CLAUDE.md exists (it doesn't)
2. Claude explores your repository using built-in commands
3. Claude analyzes: project type, tech stack, team size, workflows
4. Claude shows discoveries and asks for confirmation
5. You confirm the settings
6. Claude creates customized CLAUDE.md file(s)
7. Claude enhances with best practices
**Interactive Flow**:
- ✋ User must confirm before creation
- 🔍 Full visibility into what was discovered
- ⚙️ Option to adjust settings before proceeding
### Example 2: Analyze Existing CLAUDE.md
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you analyze my current CLAUDE.md file and tell me what's missing or could be improved?
```
### Example 2: Generate New CLAUDE.md for TypeScript Project
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you create a CLAUDE.md file for my TypeScript React project with a team of 5 developers? We use PostgreSQL, Docker, and follow TDD practices.
```
### Example 3: Enhance Existing File
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you enhance my existing CLAUDE.md by adding missing sections and improving the structure? Here's my current file: [paste content]
```
### Example 4: Generate Modular Architecture
```
Hey Claude—I just added the "claude-md-enhancer" skill. Can you create a modular CLAUDE.md setup for my full-stack project? I need separate files for backend (Python/FastAPI), frontend (React), and database (PostgreSQL).
```
## Initialization Workflow (New Projects)
When CLAUDE.md doesn't exist in your project, this skill provides an intelligent initialization workflow:
### Workflow Steps
**Step 1: Detection**
- Skill checks if CLAUDE.md exists in project root
- If not found, initialization workflow begins
**Step 2: Repository Exploration**
- Uses Claude Code's built-in `explore` command
- Analyzes project structure, files, and directories
- Examines configuration files (package.json, requirements.txt, go.mod, etc.)
- Reviews existing documentation
**Step 3: Intelligent Analysis**
- **Project Type Detection**: web_app, api, fullstack, cli, library, mobile, desktop
- **Tech Stack Detection**: TypeScript, Python, React, FastAPI, PostgreSQL, Docker, etc.
- **Team Size Estimation**: Based on project complexity (solo, small, medium, large)
- **Development Phase**: prototype, mvp, production, enterprise
- **Workflow Detection**: TDD, CI/CD, documentation-first, agile
- **Structure Recommendation**: Single file vs. modular architecture
**Step 4: User Confirmation**
- Displays all discoveries in clear format
- Shows recommended CLAUDE.md structure
- Asks user to confirm or adjust settings
- **User must explicitly approve** before proceeding
**Step 5: File Creation**
- Generates customized CLAUDE.md based on confirmed settings
- Creates modular files if recommended (backend/, frontend/, etc.)
- Applies tech-specific best practices
**Step 6: Enhancement**
- Validates generated content
- Adds quality improvements
- Ensures completeness
**Step 7: Summary**
- Shows what files were created
- Provides next steps
- Ready for immediate use
### Interactive Example
```
User: "I need a CLAUDE.md for this project"
Claude: "I'll explore your repository first to understand the project.
[Explores using built-in commands]
Based on my exploration, here's what I discovered:
Project Type: Full-Stack Application
Tech Stack: TypeScript, React, Node.js, PostgreSQL, Docker
Team Size: Small (2-9 developers)
Development Phase: MVP
Workflows: TDD, CI/CD
Recommended Structure: Modular architecture
- Root CLAUDE.md (navigation hub)
- backend/CLAUDE.md (API guidelines)
- frontend/CLAUDE.md (React guidelines)
Would you like me to create these files?"
User: "Yes, please proceed"
Claude: "Creating customized CLAUDE.md files...
✅ Created CLAUDE.md (100 lines)
✅ Created backend/CLAUDE.md (150 lines)
✅ Created frontend/CLAUDE.md (175 lines)
Your project is ready for AI-assisted development!"
```
## Scripts
### workflow.py
Manages the interactive initialization workflow for new projects.
**Key Functions**:
- `check_claude_md_exists()` - Detect if CLAUDE.md exists
- `generate_exploration_prompt()` - Guide Claude to explore repository
- `analyze_discoveries()` - Analyze exploration results
- `generate_confirmation_prompt()` - Create user confirmation prompt
- `get_workflow_steps()` - Get complete workflow steps
### analyzer.py
Analyzes existing CLAUDE.md files to identify structure, sections, and quality issues.
**Key Functions**:
- `analyze_file()` - Parse and analyze CLAUDE.md structure
- `detect_sections()` - Identify present and missing sections
- `calculate_quality_score()` - Score file quality (0-100)
- `generate_recommendations()` - Provide actionable improvement suggestions
### validator.py
Validates CLAUDE.md files against best practices and Anthropic guidelines.
**Key Functions**:
- `validate_length()` - Check file length (warn if >300 lines)
- `validate_structure()` - Verify required sections present
- `validate_formatting()` - Check markdown formatting quality
- `validate_completeness()` - Ensure critical information included
### generator.py
Generates new CLAUDE.md content or missing sections based on templates.
**Key Functions**:
- `generate_root_file()` - Create main CLAUDE.md orchestrator
- `generate_context_file()` - Create context-specific files (backend, frontend, etc.)
- `generate_section()` - Generate individual sections (tech stack, workflows, etc.)
- `merge_with_existing()` - Add new sections to existing files
### template_selector.py
Selects appropriate template based on project context.
**Key Functions**:
- `select_template()` - Choose template based on project type and team size
- `customize_template()` - Adapt template to tech stack
- `determine_complexity()` - Calculate appropriate detail level
- `recommend_modular_structure()` - Suggest subdirectory organization
## Best Practices
### Critical Validation Rule ⚠️
**"Always validate your output against official native examples before declaring complete."**
Before finalizing any CLAUDE.md generation:
1. Compare output against `/update-claude-md` slash command format
2. Check official Claude Code documentation for required sections
3. Verify all native format sections are present (Overview, Project Structure, File Structure, Setup & Installation, Architecture, etc.)
4. Cross-check against reference examples in `examples/` folder
### For New Projects
1. Start with minimal template (50-100 lines) and grow as needed
2. Use modular architecture for projects with >3 major components
3. Include tech stack reference immediately
4. Add workflow instructions before team grows beyond 5 people
### For Enhancement
1. Analyze before modifying - understand current structure first
2. Preserve custom content - only enhance, don't replace
3. Validate after changes - ensure improvements don't break existing patterns
4. Test with Claude Code - verify guidelines work as intended
### General Guidelines
1. **Keep root file concise** - Max 150 lines, use as navigation hub
2. **Use context-specific files** - backend/CLAUDE.md, frontend/CLAUDE.md, etc.
3. **Avoid duplication** - Each guideline should appear once
4. **Link to external docs** - Don't copy official documentation
5. **Update regularly** - Review guidelines quarterly or when stack changes
## Limitations
### Technical Constraints
- Requires valid project context for accurate template selection
- Tech stack detection is based on keywords, may need manual refinement
- Modular file generation assumes standard directory structure
### Scope Boundaries
- Focuses on CLAUDE.md structure, not project-specific business logic
- Best practice recommendations are general, may need industry-specific customization
- Validation is guideline-based, not enforcement (no automated fixes without approval)
### When NOT to Use
- For non-Claude AI tools (this is Claude Code specific)
- For projects that don't use Claude Code or similar AI assistants
- When you need highly specialized domain guidelines (legal, medical compliance)
## 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 Project Type
- **Web App** - Frontend-focused (React, Vue, Angular)
- **API** - Backend services (REST, GraphQL, microservices)
- **Full-Stack** - Integrated frontend + backend
- **CLI** - Command-line tools and utilities
- **Library** - Reusable packages and frameworks
- **Mobile** - React Native, Flutter, native iOS/Android
### By Tech Stack
- **TypeScript/Node** - Modern JavaScript ecosystem
- **Python** - Django, FastAPI, Flask
- **Go** - Gin, Echo, native services
- **Java/Kotlin** - Spring Boot, enterprise Java
- **Ruby** - Rails, Sinatra
## Quality Metrics
### File Quality Score (0-100)
Calculated based on:
- **Length appropriateness** (25 points) - Not too short or long
- **Section completeness** (25 points) - Required sections present
- **Formatting quality** (20 points) - Proper markdown structure
- **Content specificity** (15 points) - Tailored to project, not generic
- **Modular organization** (15 points) - Uses subdirectory files when appropriate
### Recommendations Priority
- **Critical** - Missing required sections, file too long (>400 lines)
- **High** - Missing important sections, formatting issues
- **Medium** - Could add optional sections, minor improvements
- **Low** - Nice-to-have enhancements, stylistic suggestions
## Advanced Features
### Modular Architecture Support
Automatically generates context-specific files:
```
project-root/
├── CLAUDE.md # Root orchestrator (100-150 lines)
├── backend/
│ └── CLAUDE.md # Backend-specific (150-200 lines)
├── frontend/
│ └── CLAUDE.md # Frontend-specific (150-200 lines)
├── database/
│ └── CLAUDE.md # Database operations (100-150 lines)
└── .github/
└── CLAUDE.md # CI/CD workflows (100-150 lines)
```
### Tech Stack Detection
Automatically detects technologies from:
- `package.json` (Node.js/TypeScript)
- `requirements.txt` or `pyproject.toml` (Python)
- `go.mod` (Go)
- `Cargo.toml` (Rust)
- `pom.xml` or `build.gradle` (Java)
### Team Size Adaptation
Adjusts detail level:
- **Solo**: Minimal guidelines, focus on efficiency
- **Small (<10)**: Core guidelines, workflow basics
- **Medium (10-50)**: Detailed guidelines, team coordination
- **Large (50+)**: Comprehensive guidelines, process enforcement
## References
- **Anthropic Claude Code Docs**: https://docs.claude.com/en/docs/claude-code
- **CLAUDE.md Best Practices**: Based on community patterns and Anthropic guidance
- **Example CLAUDE.md Files**: See `examples/` folder for 6 reference implementations covering different project types and team sizes
## Version
**Version**: 1.0.0
**Last Updated**: November 2025
**Compatible**: Claude Code 2.0+, Claude Apps, Claude API
Remember: The goal is to make Claude more efficient and context-aware, not to create bureaucracy. Start simple, iterate based on real usage, and automate quality checks where possible.
+382
View File
@@ -0,0 +1,382 @@
"""
CLAUDE.md File Analyzer
Analyzes existing CLAUDE.md files to identify structure, sections, and quality issues.
Provides detailed analysis reports with quality scores and actionable recommendations.
"""
from typing import Dict, List, Any, Tuple
import re
class CLAUDEMDAnalyzer:
"""Analyzes CLAUDE.md files for structure, completeness, and quality."""
# Standard sections that should be present in most CLAUDE.md files
RECOMMENDED_SECTIONS = [
"Quick Navigation",
"Core Principles",
"Tech Stack",
"Workflow Instructions",
"Quality Checklist",
"File Organization",
"Common Commands",
"References"
]
# Optional but valuable sections
OPTIONAL_SECTIONS = [
"Testing Requirements",
"Error Handling Patterns",
"Documentation Standards",
"Performance Guidelines",
"Security Checklist",
"Deployment Process",
"Troubleshooting"
]
def __init__(self, content: str):
"""
Initialize analyzer with CLAUDE.md file content.
Args:
content: Full text content of CLAUDE.md file
"""
self.content = content
self.lines = content.split('\n')
self.line_count = len(self.lines)
self.char_count = len(content)
self.sections = []
self.subsections = []
def analyze_file(self) -> Dict[str, Any]:
"""
Perform comprehensive analysis of CLAUDE.md file.
Returns:
Dictionary containing full analysis results
"""
return {
"file_metrics": self._get_file_metrics(),
"sections_found": self.detect_sections(),
"missing_sections": self._identify_missing_sections(),
"structure_analysis": self._analyze_structure(),
"issues": self._detect_issues(),
"quality_score": self.calculate_quality_score(),
"recommendations": self.generate_recommendations()
}
def _get_file_metrics(self) -> Dict[str, int]:
"""Calculate basic file metrics."""
return {
"char_count": self.char_count,
"line_count": self.line_count,
"word_count": len(self.content.split()),
"heading_count": len([line for line in self.lines if line.startswith('#')]),
"code_block_count": self.content.count('```') // 2
}
def detect_sections(self) -> List[str]:
"""
Detect all sections (headings) in the file.
Returns:
List of section titles found
"""
sections = []
subsections = []
for line in self.lines:
# Match markdown headings (## or ###)
if line.startswith('## '):
section_title = line[3:].strip()
sections.append(section_title)
elif line.startswith('### '):
subsection_title = line[4:].strip()
subsections.append(subsection_title)
self.sections = sections
self.subsections = subsections
return sections
def _identify_missing_sections(self) -> List[str]:
"""
Identify recommended sections that are missing.
Returns:
List of missing section names
"""
if not self.sections:
self.detect_sections()
missing = []
for recommended in self.RECOMMENDED_SECTIONS:
# Check if section exists (case-insensitive, partial match)
if not any(recommended.lower() in section.lower() for section in self.sections):
missing.append(recommended)
return missing
def _analyze_structure(self) -> Dict[str, Any]:
"""
Analyze the structural quality of the file.
Returns:
Dictionary with structure analysis
"""
has_title = self.content.startswith('# ')
has_navigation = any('navigation' in s.lower() for s in self.sections)
has_code_examples = '```' in self.content
has_links = '[' in self.content and '](' in self.content
# Check for modular architecture mentions
mentions_modular = any(
keyword in self.content.lower()
for keyword in ['backend/CLAUDE.md', 'frontend/CLAUDE.md', 'subdirectory', 'context-specific']
)
return {
"has_main_title": has_title,
"has_navigation_section": has_navigation,
"has_code_examples": has_code_examples,
"has_links": has_links,
"mentions_modular_architecture": mentions_modular,
"section_count": len(self.sections),
"subsection_count": len(self.subsections),
"hierarchy_depth": self._calculate_hierarchy_depth()
}
def _calculate_hierarchy_depth(self) -> int:
"""Calculate maximum heading depth."""
max_depth = 1 # Assumes at least # title
for line in self.lines:
if line.startswith('#'):
depth = len(line) - len(line.lstrip('#'))
max_depth = max(max_depth, depth)
return max_depth
def _detect_issues(self) -> List[Dict[str, str]]:
"""
Detect potential issues with the file.
Returns:
List of issue dictionaries with type, severity, and message
"""
issues = []
# Check file length
if self.line_count > 400:
issues.append({
"type": "length_critical",
"severity": "high",
"message": f"File is too long ({self.line_count} lines). Recommended: split into modular files."
})
elif self.line_count > 300:
issues.append({
"type": "length_warning",
"severity": "medium",
"message": f"File exceeds recommended 300 lines ({self.line_count} lines). Consider splitting."
})
# Check if file is too short
if self.line_count < 30:
issues.append({
"type": "too_short",
"severity": "medium",
"message": f"File is very short ({self.line_count} lines). May need more guidance."
})
# Check for missing critical sections
critical_sections = ["Core Principles", "Tech Stack", "Workflow"]
missing_critical = [
s for s in critical_sections
if not any(s.lower() in section.lower() for section in self.sections)
]
if missing_critical:
issues.append({
"type": "missing_critical_sections",
"severity": "high",
"message": f"Missing critical sections: {', '.join(missing_critical)}"
})
# Check for placeholder text
placeholders = ['TODO', 'TBD', 'FIXME', '[Insert', '[Add']
for placeholder in placeholders:
if placeholder in self.content:
issues.append({
"type": "placeholder_text",
"severity": "medium",
"message": f"Contains placeholder text: '{placeholder}'"
})
break
# Check for empty sections
empty_section_pattern = r'##\s+[^\n]+\n\s*\n\s*##'
if re.search(empty_section_pattern, self.content):
issues.append({
"type": "empty_sections",
"severity": "low",
"message": "Some sections appear to be empty"
})
return issues
def calculate_quality_score(self) -> int:
"""
Calculate overall quality score (0-100).
Scoring breakdown:
- Length appropriateness: 25 points
- Section completeness: 25 points
- Formatting quality: 20 points
- Content specificity: 15 points
- Modular organization: 15 points
Returns:
Quality score between 0 and 100
"""
score = 0
# Length appropriateness (25 points)
if 50 <= self.line_count <= 300:
score += 25
elif 30 <= self.line_count < 50 or 300 < self.line_count <= 400:
score += 15
elif self.line_count > 400:
score += 5
else:
score += 10
# Section completeness (25 points)
if not self.sections:
self.detect_sections()
found_count = len([
s for s in self.RECOMMENDED_SECTIONS
if any(s.lower() in section.lower() for section in self.sections)
])
section_score = (found_count / len(self.RECOMMENDED_SECTIONS)) * 25
score += int(section_score)
# Formatting quality (20 points)
formatting_score = 0
if self.content.startswith('# '):
formatting_score += 5
if '```' in self.content:
formatting_score += 5
if '[' in self.content and '](' in self.content:
formatting_score += 5
if any('navigation' in s.lower() for s in self.sections):
formatting_score += 5
score += formatting_score
# Content specificity (15 points)
# Check for specific tech mentions (not generic)
tech_keywords = [
'typescript', 'python', 'react', 'vue', 'angular', 'node',
'fastapi', 'django', 'postgresql', 'mongodb', 'docker'
]
content_lower = self.content.lower()
tech_mentions = sum(1 for keyword in tech_keywords if keyword in content_lower)
if tech_mentions >= 3:
score += 15
elif tech_mentions >= 2:
score += 10
elif tech_mentions >= 1:
score += 5
# Modular organization (15 points)
modular_keywords = [
'backend/CLAUDE.md', 'frontend/CLAUDE.md', 'context-specific',
'subdirectory', 'modular'
]
modular_mentions = sum(1 for keyword in modular_keywords if keyword.lower() in content_lower)
if modular_mentions >= 2:
score += 15
elif modular_mentions >= 1:
score += 10
return min(score, 100)
def generate_recommendations(self) -> List[str]:
"""
Generate actionable recommendations for improvement.
Returns:
List of recommendation strings
"""
recommendations = []
# Analyze first to ensure data is available
if not self.sections:
self.detect_sections()
missing = self._identify_missing_sections()
issues = self._detect_issues()
# Critical issues first
for issue in issues:
if issue['severity'] == 'high':
if issue['type'] == 'length_critical':
recommendations.append(
"CRITICAL: Split into modular files - create backend/CLAUDE.md, "
"frontend/CLAUDE.md, etc."
)
elif issue['type'] == 'missing_critical_sections':
recommendations.append(f"CRITICAL: {issue['message']}")
# Length recommendations
if self.line_count > 300:
recommendations.append(
"Reduce root CLAUDE.md to <150 lines - move detailed guides to context-specific files"
)
elif self.line_count < 30:
recommendations.append(
"Expand with essential sections: Core Principles, Tech Stack, Workflow Instructions"
)
# Missing sections
if missing:
high_priority = ["Core Principles", "Tech Stack", "Workflow Instructions"]
missing_high_priority = [s for s in missing if s in high_priority]
if missing_high_priority:
recommendations.append(
f"Add essential sections: {', '.join(missing_high_priority)}"
)
missing_optional = [s for s in missing if s not in high_priority]
if len(missing_optional) <= 3:
recommendations.append(
f"Consider adding: {', '.join(missing_optional)}"
)
# Structure recommendations
structure = self._analyze_structure()
if not structure['has_navigation_section'] and self.line_count > 100:
recommendations.append(
"Add Quick Navigation section with links to context-specific guides"
)
if not structure['has_code_examples']:
recommendations.append(
"Include code examples for complex patterns to improve clarity"
)
# Modular architecture
if self.line_count > 200 and not structure['mentions_modular_architecture']:
recommendations.append(
"Consider implementing modular architecture - separate files for major components"
)
# Quality improvements
quality_score = self.calculate_quality_score()
if quality_score < 60:
recommendations.append(
f"Overall quality score is {quality_score}/100 - prioritize critical improvements"
)
return recommendations[:8] # Limit to top 8 recommendations
+138
View File
@@ -0,0 +1,138 @@
# CLAUDE.md Reference Examples
This folder contains reference implementations of CLAUDE.md files for different project types and team sizes.
**✨ NEW**: All examples now follow **100% native Claude Code format** with proper project structure diagrams, setup instructions, architecture sections, and file structure explanations - matching the official `/update-claude-md` slash command format.
## Available Examples
### By Complexity Level
| Example | Lines | Team Size | Use Case |
|---------|-------|-----------|----------|
| `minimal-solo-CLAUDE.md` | ~75 | Solo | Prototypes, hackathons, quick projects |
| `core-small-team-CLAUDE.md` | ~175 | Small (5) | MVPs, small team projects |
| `modular-root-CLAUDE.md` | ~150 | Medium (12) | Full-stack production apps (root file) |
| `python-api-CLAUDE.md` | ~225 | Small (6) | Python FastAPI backend projects |
### By Project Type
| Example | Project Type | Tech Stack |
|---------|--------------|------------|
| `minimal-solo-CLAUDE.md` | Web App Prototype | TypeScript, React, Node |
| `core-small-team-CLAUDE.md` | Web Application MVP | React, Node, PostgreSQL |
| `python-api-CLAUDE.md` | Backend API | Python, FastAPI, PostgreSQL |
| `modular-root-CLAUDE.md` | Full-Stack App (root) | React, Node, PostgreSQL |
| `modular-backend-CLAUDE.md` | Backend (context-specific) | Node, Express, PostgreSQL |
| `modular-frontend-CLAUDE.md` | Frontend (context-specific) | React, TypeScript, Tailwind |
## Modular Architecture Examples
For projects with multiple major components, use separate CLAUDE.md files:
**Root Navigation Hub**:
- `modular-root-CLAUDE.md` - Root file with navigation (~150 lines)
**Context-Specific Files**:
- `modular-backend-CLAUDE.md` - Backend guidelines (~200 lines)
- `modular-frontend-CLAUDE.md` - Frontend guidelines (~225 lines)
## How to Use These Examples
### 1. Starting a New Project
```bash
# Copy appropriate template to your project
cp examples/core-small-team-CLAUDE.md /path/to/your/project/CLAUDE.md
# Customize for your tech stack and workflows
```
### 2. Setting Up Modular Architecture
```bash
# Copy root file to project root
cp examples/modular-root-CLAUDE.md /path/to/your/project/CLAUDE.md
# Copy context-specific files to subdirectories
cp examples/modular-backend-CLAUDE.md /path/to/your/project/backend/CLAUDE.md
cp examples/modular-frontend-CLAUDE.md /path/to/your/project/frontend/CLAUDE.md
```
### 3. Using with claude-md-enhancer Skill
These examples demonstrate the output quality you can expect from the skill:
```
Hey Claude—I just added the "claude-md-enhancer" skill.
Can you create a CLAUDE.md similar to the core-small-team example
but customized for my Go API project?
```
## Template Selection Guide
### Choose Minimal Template When:
- Solo developer
- Prototype or proof-of-concept
- Hackathon or time-boxed project
- Need quick setup with minimal guidance
### Choose Core Template When:
- Small team (2-10 developers)
- MVP or early-stage product
- Standard web application
- Need comprehensive but concise guidelines
### Choose Modular Architecture When:
- Medium/large team (10+ developers)
- Full-stack or complex application
- Multiple major components (frontend, backend, database, etc.)
- Production or enterprise environment
### Choose Tech-Specific Template When:
- Specific tech stack (Python/FastAPI, Go, etc.)
- Team needs stack-specific best practices
- Want language-specific examples and patterns
## Quality Metrics
### Native Format Sections (100% Compliance)
All examples now include these **native Claude Code sections**:
-**Overview** - Concise project description
-**Project Structure** - ASCII tree diagram showing folder hierarchy
-**File Structure** - Detailed explanations of directories and their purpose
-**Setup & Installation** - Step-by-step setup commands
-**Architecture** - System architecture and component flow (for complex projects)
-**Core Principles** - Development philosophies and standards
-**Tech Stack** - Technologies with versions
-**Development Workflow** - Step-by-step development process
-**Testing Requirements** - Testing strategy and coverage targets
-**Error Handling** - Error handling patterns and best practices
-**Common Commands** - Frequently used commands with descriptions
**Why This Matters**: These sections match the official `/update-claude-md` slash command format, ensuring Claude Code can navigate and understand your codebase efficiently.
### Expected Quality Scores
| Example | Quality Score |
|---------|---------------|
| `minimal-solo-CLAUDE.md` | 70-75/100 |
| `core-small-team-CLAUDE.md` | 85-90/100 |
| `modular-root-CLAUDE.md` | 80-85/100 |
| `modular-backend-CLAUDE.md` | 90-95/100 |
| `modular-frontend-CLAUDE.md` | 90-95/100 |
| `python-api-CLAUDE.md` | 85-90/100 |
## Customization Tips
1. **Update Tech Stack**: Replace technologies with your actual stack
2. **Adjust Workflows**: Modify development process to match your team
3. **Add Team Standards**: Include team-specific conventions
4. **Update Commands**: Replace commands with your actual npm/yarn/poetry scripts
5. **Add Context**: Include project-specific context that helps Claude understand your goals
## Contributing
These examples represent best practices as of November 2025. If you have improvements or additional examples, please contribute them!
+183
View File
@@ -0,0 +1,183 @@
# CLAUDE.md
This file provides guidance for Claude Code when working with this project.
## Overview
Full-stack web application built with React, Node.js, and PostgreSQL. Small team (5 developers) following TDD and code review practices for MVP development.
## Project Structure
```
project-root/
├── client/
│ ├── src/
│ │ ├── components/ # React components
│ │ ├── pages/ # Page components
│ │ ├── hooks/ # Custom hooks
│ │ ├── services/ # API client services
│ │ └── utils/ # Utility functions
│ ├── public/ # Static assets
│ └── package.json
├── server/
│ ├── src/
│ │ ├── controllers/ # Route handlers
│ │ ├── services/ # Business logic
│ │ ├── models/ # Database models
│ │ ├── middleware/ # Express middleware
│ │ └── routes/ # API routes
│ ├── tests/ # Server tests
│ └── package.json
├── database/
│ ├── migrations/ # Database migrations
│ └── seeds/ # Seed data
├── docker-compose.yml
└── README.md
```
## File Structure
- **client/** - React frontend application
- **src/components/** - Reusable UI components
- **src/pages/** - Route-level page components
- **src/services/** - API client functions
- **server/** - Node.js backend API
- **src/controllers/** - Request handlers and route logic
- **src/services/** - Business logic layer
- **src/models/** - Database models and schemas
- **src/middleware/** - Express middleware (auth, validation, logging)
- **database/** - Database migrations and seed data
## Architecture
**Stack**: React SPA + Express API + PostgreSQL
**Flow**: Client → Express API → PostgreSQL
- Frontend: React SPA with client-side routing
- Backend: RESTful API with Express
- Database: PostgreSQL with migration-based schema management
- Communication: JSON over HTTP/HTTPS
## Setup & Installation
```bash
# Install dependencies for both client and server
npm install
cd client && npm install
cd ../server && npm install
# Set up environment variables
cp .env.example .env
# Edit .env with your database credentials and API keys
# Start PostgreSQL (using Docker)
docker-compose up -d postgres
# Run database migrations
cd server && npm run migrate
# Seed database with initial data
npm run seed
# Start development servers
npm run dev # Starts both client and server
```
## Core Principles
1. **Test-Driven Development**: Write tests before implementation
2. **Code Quality**: Maintain high standards with clean, readable code
3. **Documentation**: Keep docs in sync with code changes
4. **Collaboration**: Clear communication and code reviews
5. **Performance**: Consider performance implications early
## Tech Stack
- **Frontend**: React 18, TypeScript 5, Tailwind CSS
- **Backend**: Node.js 20, Express 4, TypeScript
- **Database**: PostgreSQL 15, Prisma ORM
- **Testing**: Jest, React Testing Library, Supertest
- **Build**: Vite, Docker, GitHub Actions
## Development Workflow
### Development Process
1. Create feature branch from `main`: `git checkout -b feature/name`
2. Write tests first (TDD approach)
3. Implement feature with proper error handling
4. Run linter and tests locally: `npm run lint && npm test`
5. Create pull request with description
6. Code review (minimum 1 approval required)
7. Merge to main (auto-deploy to staging)
### Testing Requirements
- Unit tests for all business logic
- Integration tests for API endpoints
- E2E tests for critical user flows
- Minimum 80% code coverage
- All tests must pass before merge
## Error Handling
- Use try-catch blocks for async operations
- Log errors with context (user ID, request ID, timestamp)
- Return meaningful error messages to clients
- Never expose stack traces in production
- Implement global error handling middleware
## Code Review Checklist
Before requesting review, ensure:
- [ ] Tests written and passing (80%+ coverage)
- [ ] No console.log or debugger statements
- [ ] Error handling implemented properly
- [ ] Documentation updated (README, API docs)
- [ ] No hardcoded values (use environment variables)
- [ ] TypeScript types defined (no `any` types)
- [ ] Performance considerations addressed
- [ ] Security best practices followed
## Common Commands
```bash
# Development
npm run dev # Start both client and server
npm run dev:client # Start client only
npm run dev:server # Start server only
npm test # Run all tests
npm run test:watch # Run tests in watch mode
npm run lint # Run ESLint
npm run format # Format code with Prettier
# Production
npm run build # Build client and server
npm run start # Start production servers
# Database
npm run migrate # Run database migrations
npm run migrate:rollback # Rollback last migration
npm run seed # Seed database with test data
npm run db:reset # Reset database (dev only)
# Docker
docker-compose up # Start all services
docker-compose down # Stop all services
docker-compose logs -f # View logs
```
## API Documentation
API endpoints are documented using Swagger/OpenAPI. After starting the server, visit:
```
http://localhost:3000/api-docs
```
---
**Project Type**: Web Application (MVP)
**Team Size**: Small (5 developers)
**Lines**: ~175 (Core template with native format)
+80
View File
@@ -0,0 +1,80 @@
# CLAUDE.md
Quick guidance for this prototype project.
## Overview
Rapid prototyping project using TypeScript, React, and Node.js. Focus on speed and iteration over production-readiness.
## Project Structure
```
project-root/
├── src/
│ ├── components/ # React components
│ ├── pages/ # Page components
│ ├── hooks/ # Custom hooks
│ └── utils/ # Utility functions
├── public/ # Static assets
├── tests/ # Test files
├── package.json
├── tsconfig.json
└── README.md
```
## File Structure
- **src/components/** - Reusable UI components
- **src/pages/** - Route-level page components
- **src/hooks/** - Custom React hooks for shared logic
- **src/utils/** - Helper functions and utilities
- **tests/** - Unit and integration tests
## Setup & Installation
```bash
# Install dependencies
npm install
# Start development server
npm run dev
# Run tests
npm test
```
## Core Principles
1. **Move Fast**: Prioritize speed over perfection
2. **Keep It Simple**: Avoid unnecessary complexity
3. **Iterate Quickly**: Test and refine rapidly
## Tech Stack
- **Frontend**: TypeScript, React
- **Backend**: Node.js, Express
- **Build**: Vite
- **Testing**: Jest, React Testing Library
## Development Workflow
1. Create feature branch: `git checkout -b feature/name`
2. Implement and test locally
3. Commit changes: `git commit -m "Add feature"`
4. Push to remote: `git push`
5. Deploy to staging for testing
## Quick Commands
```bash
npm run dev # Start development server
npm test # Run all tests
npm run build # Build for production
npm run lint # Check code quality
```
---
**Project Type**: Prototype
**Team Size**: Solo
**Lines**: ~75 (Minimal template with native format)
+345
View File
@@ -0,0 +1,345 @@
# Backend Development Guidelines
This file provides guidance for backend development in this project.
## Overview
Express API backend with TypeScript, PostgreSQL database, and Redis caching. RESTful API design with comprehensive error handling, testing, and security practices.
## Project Structure
```
backend/
├── src/
│ ├── controllers/ # Route handlers
│ │ ├── auth.controller.ts
│ │ ├── user.controller.ts
│ │ └── product.controller.ts
│ ├── services/ # Business logic
│ │ ├── auth.service.ts
│ │ ├── user.service.ts
│ │ └── product.service.ts
│ ├── models/ # Database models
│ │ ├── User.ts
│ │ └── Product.ts
│ ├── middleware/ # Express middleware
│ │ ├── auth.middleware.ts
│ │ ├── validation.middleware.ts
│ │ └── error.middleware.ts
│ ├── routes/ # Route definitions
│ │ ├── auth.routes.ts
│ │ ├── user.routes.ts
│ │ └── product.routes.ts
│ ├── utils/ # Utilities
│ │ ├── logger.ts
│ │ ├── validators.ts
│ │ └── crypto.ts
│ ├── config/ # Configuration
│ │ ├── database.ts
│ │ └── redis.ts
│ └── index.ts # App entry point
├── tests/
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── fixtures/ # Test data
├── prisma/
│ ├── schema.prisma # Database schema
│ └── migrations/ # Migration files
├── .env.example
├── package.json
└── tsconfig.json
```
## File Structure
- **controllers/** - Handle HTTP requests, validate input, call services
- **services/** - Business logic layer, independent of HTTP
- **models/** - Database models and Prisma client usage
- **middleware/** - Express middleware (auth, validation, logging, errors)
- **routes/** - Route definitions mapping URLs to controllers
- **utils/** - Shared utility functions (logging, validation, crypto)
- **config/** - Configuration files for database, Redis, etc.
- **tests/** - Unit and integration tests
## Architecture
**Layer Pattern**: Controllers → Services → Models → Database
**Flow**:
```
HTTP Request → Route → Middleware → Controller → Service → Model → Database
Response
```
**Components**:
- **Controllers**: HTTP layer, request/response handling
- **Services**: Business logic, reusable across controllers
- **Models**: Data access layer with Prisma ORM
- **Middleware**: Cross-cutting concerns (auth, logging, validation)
## Setup & Installation
```bash
# Install dependencies
npm install
# Set up environment variables
cp .env.example .env
# Edit .env with:
# - DATABASE_URL (PostgreSQL connection string)
# - REDIS_URL (Redis connection string)
# - JWT_SECRET (secret for token signing)
# - PORT (default 3000)
# Start PostgreSQL and Redis (using Docker)
docker-compose up -d postgres redis
# Run database migrations
npx prisma migrate dev
# Generate Prisma client
npx prisma generate
# Seed database
npm run seed
# Start development server
npm run dev
```
## API Design
### RESTful Conventions
- Use RESTful conventions for API endpoints
- Implement proper HTTP status codes:
- `200 OK` - Successful GET/PUT/PATCH
- `201 Created` - Successful POST
- `204 No Content` - Successful DELETE
- `400 Bad Request` - Validation error
- `401 Unauthorized` - Authentication required
- `403 Forbidden` - Insufficient permissions
- `404 Not Found` - Resource not found
- `500 Internal Server Error` - Server error
### Versioning
- Version APIs when breaking changes are needed
- Format: `/api/v1/`, `/api/v2/`
- Example: `/api/v1/users`, `/api/v2/users`
### Documentation
- Document all endpoints with OpenAPI/Swagger
- Access docs at `/api-docs` when server running
- Include request/response examples
- Document authentication requirements
### Naming Conventions
- Use camelCase for JSON keys
- Use snake_case for database columns
- Use kebab-case for URL paths
## Database Operations
### Migrations
- Use migrations for all schema changes
- **Never edit existing migrations** - create new ones
- Test migrations on copy of production data
- Include both up and down migrations
- Name migrations descriptively: `20250112_add_user_email_index`
### Query Optimization
- Implement proper indexes for frequently queried columns
- Avoid N+1 queries - use joins or batch loading with Prisma `include`
- Use `EXPLAIN ANALYZE` to analyze slow queries
- Paginate large result sets (max 100 items per page)
### Transactions
- Use transactions for multi-step operations
- Example:
```typescript
await prisma.$transaction(async (tx) => {
await tx.user.update({ ... });
await tx.account.create({ ... });
});
```
## Error Handling
### Global Error Middleware
- Implement global error handling middleware
- Catch all errors in one place
- Log errors with context (request ID, user ID, timestamp)
### Error Response Format
Return consistent error response format:
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "User-friendly message",
"details": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
}
```
### Error Classes
- Use custom error classes for different error types
- Examples: `ValidationError`, `AuthenticationError`, `NotFoundError`
- Never expose stack traces to clients in production
- Log full stack traces server-side
## Testing Requirements
### Unit Tests
- Write unit tests for business logic (services, utils)
- Mock external dependencies (database, APIs, Redis)
- Test edge cases and error conditions
- Aim for 80%+ code coverage
### Integration Tests
- Write integration tests for API endpoints
- Test full request/response cycle
- Use test database (separate from dev/prod)
- Reset database state between tests
### Best Practices
- Use test databases, never production
- Use factories/fixtures for test data
- Test authentication and authorization
- Test error scenarios
```bash
# Run tests
npm test # All tests
npm run test:unit # Unit tests only
npm run test:integration # Integration tests only
npm run test:coverage # With coverage report
```
## Security Practices
### Input Validation
- Validate all input data with validation middleware
- Use schema validation (Joi, Zod, class-validator)
- Sanitize user input to prevent XSS
### Database Security
- Use parameterized queries (Prisma handles this)
- Prevents SQL injection
- Never concatenate user input into queries
### Authentication & Authorization
- Hash passwords with bcrypt (minimum 10 rounds)
- Use JWT for stateless authentication
- Implement refresh token rotation
- Use environment variables for secrets
### Rate Limiting
- Implement rate limiting on public endpoints
- Example: 100 requests per 15 minutes per IP
- Protect against brute force attacks
### CORS
- Implement proper CORS policies
- Whitelist allowed origins
- Don't use wildcard (`*`) in production
## Performance Optimization
### Caching
- Implement caching for frequently accessed data
- Use Redis for session storage and data caching
- Cache expensive computations
- Set appropriate TTL (time-to-live)
### Database
- Use database connection pooling (Prisma handles this)
- Optimize queries with proper indexes
- Monitor slow queries
- Use read replicas for heavy read workloads
### Async Operations
- Use async/await for I/O operations
- Never block the event loop
- Use worker threads for CPU-intensive tasks
- Queue background jobs with RabbitMQ/Bull
## Logging
- Use structured logging (Winston, Pino)
- Log levels: ERROR, WARN, INFO, DEBUG
- Include context: request ID, user ID, timestamp
- Never log sensitive data (passwords, tokens)
- Rotate log files in production
## Common Commands
```bash
# Development
npm run dev # Start dev server with hot reload
npm test # Run all tests
npm run test:watch # Run tests in watch mode
npm run lint # Run ESLint
npm run format # Format code with Prettier
# Database
npm run migrate # Run migrations
npm run migrate:rollback # Rollback last migration
npm run migrate:reset # Reset database (dev only)
npm run seed # Seed database with test data
npx prisma studio # Open Prisma Studio (DB GUI)
# Production
npm run build # Build TypeScript
npm start # Start production server
# Debugging
npm run dev:debug # Start with debugger
npm run logs # View application logs
```
## API Documentation
After starting the server, access API documentation at:
```
http://localhost:3000/api-docs
```
Swagger UI provides interactive API documentation with:
- All endpoints listed
- Request/response schemas
- Try-it-out functionality
- Authentication examples
---
**Context**: Backend (Node.js/Express/TypeScript/PostgreSQL)
**Lines**: ~200 (Backend-specific template with native format)
+385
View File
@@ -0,0 +1,385 @@
# Frontend Development Guidelines
This file provides guidance for frontend development in this project.
## Overview
React 18 SPA with TypeScript, Tailwind CSS, and React Query for server state. Component-based architecture with hooks, performance optimization, and comprehensive testing.
## Project Structure
```
frontend/
├── src/
│ ├── components/ # Reusable components
│ │ ├── common/ # Shared UI components
│ │ │ ├── Button.tsx
│ │ │ ├── Input.tsx
│ │ │ └── Modal.tsx
│ │ ├── layout/ # Layout components
│ │ │ ├── Header.tsx
│ │ │ ├── Footer.tsx
│ │ │ └── Sidebar.tsx
│ │ └── features/ # Feature-specific components
│ │ ├── UserList.tsx
│ │ └── ProductCard.tsx
│ ├── pages/ # Page components (routes)
│ │ ├── HomePage.tsx
│ │ ├── UserPage.tsx
│ │ └── NotFoundPage.tsx
│ ├── hooks/ # Custom React hooks
│ │ ├── useAuth.ts
│ │ ├── useUser.ts
│ │ └── useLocalStorage.ts
│ ├── store/ # State management
│ │ ├── AuthContext.tsx
│ │ └── ThemeContext.tsx
│ ├── services/ # API client functions
│ │ ├── api.ts
│ │ ├── auth.service.ts
│ │ └── user.service.ts
│ ├── utils/ # Utility functions
│ │ ├── formatters.ts
│ │ ├── validators.ts
│ │ └── constants.ts
│ ├── styles/ # Global styles
│ │ └── global.css
│ ├── types/ # TypeScript types
│ │ ├── user.types.ts
│ │ └── api.types.ts
│ ├── App.tsx # Root component
│ ├── main.tsx # Entry point
│ └── router.tsx # Route definitions
├── public/ # Static assets
│ ├── images/
│ ├── fonts/
│ └── favicon.ico
├── tests/
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── e2e/ # End-to-end tests
├── .env.example
├── package.json
├── vite.config.ts
├── tailwind.config.js
└── tsconfig.json
```
## File Structure
- **components/** - Reusable UI components
- **common/** - Shared components (Button, Input, Modal)
- **layout/** - Layout components (Header, Footer, Sidebar)
- **features/** - Feature-specific components
- **pages/** - Page-level components mapped to routes
- **hooks/** - Custom React hooks for shared logic
- **store/** - Context providers for global state (auth, theme)
- **services/** - API client functions and HTTP calls
- **utils/** - Helper functions, formatters, validators
- **types/** - TypeScript type definitions and interfaces
## Architecture
**Component Hierarchy**: App → Router → Pages → Features → Common
**State Management**:
- **Local State**: `useState` for component-specific state
- **Global State**: Context API for auth, theme, user
- **Server State**: React Query for API data caching
- **Form State**: React Hook Form for complex forms
**Flow**:
```
User Action → Component → Service → API → React Query Cache → Component Update
```
## Setup & Installation
```bash
# Install dependencies
npm install
# Set up environment variables
cp .env.example .env
# Edit .env with:
# - VITE_API_URL (backend API URL)
# - VITE_ENV (development/staging/production)
# Start development server
npm run dev
# Server runs at http://localhost:5173
```
## Component Standards
### Functional Components with Hooks
- Prefer functional components with hooks over class components
- Use TypeScript for all components
- Keep components small and focused (< 200 lines)
- Extract reusable logic into custom hooks
- Use composition over inheritance
### Component Structure
```typescript
interface Props {
userId: string;
onUpdate?: () => void;
}
export function UserProfile({ userId, onUpdate }: Props) {
// 1. Hooks first
const { data, loading, error } = useUserData(userId);
const [isEditing, setIsEditing] = useState(false);
// 2. Event handlers
const handleEdit = () => setIsEditing(true);
// 3. Early returns
if (loading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
// 4. Main render
return <div>{/* component JSX */}</div>;
}
```
### TypeScript Best Practices
- Define interfaces for all props
- Use `type` for unions and primitives
- Avoid `any` - use `unknown` if truly dynamic
- Export types alongside components
## State Management
### Local State
- Keep component state local when possible
- Use `useState` for simple values
- Use `useReducer` for complex state logic
### Global State (Context API)
- Use Context API for app-wide state (theme, auth, user)
- Example: AuthContext, ThemeContext
- Avoid overuse - not for all shared state
### Server State (React Query)
- Use React Query for server state management
- Automatic caching, refetching, and updates
- Example:
```typescript
const { data, isLoading, error } = useQuery({
queryKey: ['users', userId],
queryFn: () => fetchUser(userId)
});
```
### Best Practices
- Avoid prop drilling - use context for deep state
- Document state shape and update patterns
- Keep state as close to usage as possible
## Styling Guidelines
### Tailwind CSS
- Use Tailwind CSS utility classes
- Create reusable component classes in `tailwind.config.js`
- Avoid inline styles except for truly dynamic values
- Use CSS variables for theming in `global.css`
### Responsive Design
- Ensure responsive design for all breakpoints (mobile-first)
- Breakpoints: `sm:` (640px), `md:` (768px), `lg:` (1024px), `xl:` (1280px)
- Test on mobile, tablet, desktop
### Dark Mode
- Implement dark mode with `dark:` variant
- Use CSS variables for theme colors
- Respect user's system preference
## Performance Optimization
### Code Splitting
- Lazy load routes with `React.lazy()` and `Suspense`
- Lazy load heavy components (charts, editors, modals)
- Example:
```typescript
const Dashboard = lazy(() => import('./pages/Dashboard'));
```
### Image Optimization
- Optimize images (use WebP, AVIF formats)
- Use lazy loading with `loading="lazy"` attribute
- Serve responsive images with `srcset`
### Bundle Optimization
- Minimize bundle size - analyze with `npm run analyze`
- Use tree-shaking (import only what you need)
- Avoid importing entire libraries
### React Optimization
- Use `useMemo` for expensive calculations
- Use `useCallback` for function props
- Use `React.memo` for expensive components
- Avoid unnecessary re-renders
## Testing Requirements
### Unit Tests
- Write unit tests for utility functions
- Test business logic separately from UI
- Mock external dependencies
- Aim for 80%+ code coverage
### Component Tests
- Write component tests with React Testing Library
- Test user interactions, not implementation details
- Test accessibility (keyboard, screen readers)
- Example:
```typescript
test('renders user profile', () => {
render(<UserProfile userId="123" />);
expect(screen.getByText(/profile/i)).toBeInTheDocument();
});
```
### API Mocking
- Mock API calls with MSW (Mock Service Worker)
- Create realistic mock responses
- Test loading and error states
### E2E Tests
- Write E2E tests with Playwright for critical flows
- Test complete user journeys
- Run E2E tests in CI/CD
```bash
# Run tests
npm test # All tests
npm run test:unit # Unit tests only
npm run test:e2e # E2E tests with Playwright
npm run test:coverage # With coverage report
```
## Accessibility (a11y)
### Semantic HTML
- Use semantic HTML elements (`<button>`, `<nav>`, `<main>`, `<article>`)
- Don't use `<div>` for interactive elements
- Use proper heading hierarchy (`<h1>` → `<h2>` → `<h3>`)
### Keyboard Navigation
- Ensure keyboard navigation works
- Test with Tab, Enter, Escape keys
- Add focus styles (don't remove outline)
### ARIA Labels
- Add ARIA labels where needed
- Use `aria-label`, `aria-labelledby`, `aria-describedby`
- Test with screen readers (VoiceOver, NVDA)
### Color Contrast
- Maintain color contrast ratios (WCAG AA minimum 4.5:1)
- Test with browser DevTools accessibility panel
- Don't rely on color alone to convey information
## Error Handling
### Error Boundaries
- Use Error Boundaries for component errors
- Implement fallback UI
- Log errors to monitoring service (Sentry)
### User-Friendly Messages
- Show user-friendly error messages
- Avoid technical jargon
- Provide actionable next steps
### Async Error Handling
- Handle loading and error states in all async operations
- Example:
```typescript
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
```
## Custom Hooks Pattern
Create custom hooks for reusable logic:
```typescript
function useUserData(userId: string) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchUserData(userId)
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, [userId]);
return { data, loading, error };
}
```
## Common Commands
```bash
# Development
npm run dev # Start dev server (http://localhost:5173)
npm test # Run all tests
npm run test:watch # Run tests in watch mode
npm run lint # Run ESLint
npm run type-check # TypeScript check
npm run format # Format code with Prettier
# Production
npm run build # Build for production
npm run preview # Preview production build locally
npm run analyze # Analyze bundle size
# Testing
npm run test:unit # Unit tests only
npm run test:e2e # E2E tests with Playwright
npm run test:coverage # Coverage report
```
## Development Best Practices
- **Component Organization**: One component per file
- **Naming**: PascalCase for components, camelCase for functions/variables
- **Props**: Destructure props in function signature
- **Imports**: Group imports (React, libraries, local)
- **Comments**: Write comments for complex logic only
- **Console Logs**: Remove before committing
---
**Context**: Frontend (React/TypeScript/Tailwind)
**Lines**: ~225 (Frontend-specific template with native format)
+192
View File
@@ -0,0 +1,192 @@
# CLAUDE.md
This file provides top-level guidance for Claude Code when working with this full-stack project.
## Overview
Full-stack application with separated backend API and frontend SPA. Uses modular CLAUDE.md architecture with context-specific files for detailed guidance. Medium team (12 developers) in production phase.
## Quick Navigation
- [Backend Guidelines](backend/CLAUDE.md) - API, services, database operations
- [Frontend Guidelines](frontend/CLAUDE.md) - Components, state management, styling
- [Database Operations](database/CLAUDE.md) - Schemas, migrations, query optimization
- [CI/CD Workflows](.github/CLAUDE.md) - Automation, testing, deployments
## Project Structure
```
project-root/
├── backend/
│ ├── src/
│ │ ├── controllers/ # API route handlers
│ │ ├── services/ # Business logic
│ │ ├── models/ # Database models
│ │ ├── middleware/ # Express middleware
│ │ └── utils/ # Shared utilities
│ ├── tests/ # Backend tests
│ └── CLAUDE.md # Backend-specific guidance
├── frontend/
│ ├── src/
│ │ ├── components/ # React components
│ │ ├── pages/ # Page components
│ │ ├── hooks/ # Custom hooks
│ │ ├── store/ # State management
│ │ └── styles/ # CSS/styling
│ ├── public/ # Static assets
│ └── CLAUDE.md # Frontend-specific guidance
├── database/
│ ├── migrations/ # Schema migrations
│ ├── seeds/ # Seed data
│ └── CLAUDE.md # Database guidance
├── .github/
│ ├── workflows/ # CI/CD workflows
│ └── CLAUDE.md # CI/CD guidance
├── docker-compose.yml
├── package.json
└── README.md
```
## File Structure
This project uses **modular architecture** with context-specific CLAUDE.md files:
- **backend/** - Express API server
- See [backend/CLAUDE.md](backend/CLAUDE.md) for API design, error handling, testing
- **frontend/** - React SPA
- See [frontend/CLAUDE.md](frontend/CLAUDE.md) for component standards, state, styling
- **database/** - PostgreSQL database
- See [database/CLAUDE.md](database/CLAUDE.md) for migrations, schemas, queries
- **.github/** - CI/CD workflows
- See [.github/CLAUDE.md](.github/CLAUDE.md) for deployment, automation
## Architecture
**Stack**: React SPA + Express API + PostgreSQL + Redis Cache
**Services**:
- Frontend: React 18 with TypeScript, served via Nginx
- Backend: Node.js 20 with Express 4, TypeScript
- Database: PostgreSQL 15 with Prisma ORM
- Cache: Redis 7 for session and data caching
- Message Queue: RabbitMQ for async processing
- Infrastructure: Docker containers, Kubernetes orchestration
**Flow**:
```
Client (React) → Nginx → Express API → PostgreSQL
Redis Cache
RabbitMQ Queue
```
## Setup & Installation
```bash
# Install dependencies for entire monorepo
npm install
# Set up environment variables
cp .env.example .env
# Edit .env with your credentials
# Start all services with Docker
docker-compose up -d
# Run database migrations
npm run db:migrate
# Seed initial data
npm run db:seed
# Start development servers
npm run dev # Starts backend and frontend
```
## Core Principles
1. **Test-Driven Development**: Write tests before implementation
2. **Type Safety First**: Use TypeScript strict mode throughout
3. **Component Composition**: Favor small, reusable components
4. **API Design**: RESTful conventions with proper versioning
5. **Error Handling**: Comprehensive error handling from the start
6. **Performance**: Optimize for scale (caching, CDN, lazy loading)
## Tech Stack
- **Frontend**: React 18, TypeScript 5, Tailwind CSS, React Query
- **Backend**: Node.js 20, Express 4, TypeScript, Prisma
- **Database**: PostgreSQL 15, Redis 7
- **Infrastructure**: Docker, Kubernetes, Nginx, GitHub Actions
- **Testing**: Jest, React Testing Library, Supertest, Playwright
## Development Workflow
1. **Feature Development**:
- Create feature branch: `git checkout -b feature/name`
- Work in appropriate context (backend/ or frontend/)
- Follow context-specific CLAUDE.md guidelines
- Write tests first (TDD)
- Run local validation: `npm run lint && npm test`
2. **Code Review**:
- Create PR with detailed description
- Ensure CI passes (lint, tests, build)
- Get minimum 2 approvals
- Address review comments
3. **Deployment**:
- Merge to `main` triggers staging deployment
- QA validation on staging
- Manual promotion to production
- Monitor metrics and logs
## Quick Reference
```bash
# Development
npm run dev:backend # Start backend server (port 3000)
npm run dev:frontend # Start frontend dev server (port 5173)
npm run dev # Start both servers
npm test # Run all tests (backend + frontend)
npm run lint # Lint all code
# Production
npm run build # Build frontend and backend
npm run start # Start production servers
# Database
npm run db:migrate # Run migrations
npm run db:seed # Seed data
npm run db:reset # Reset database (dev only)
# Docker
docker-compose up -d # Start all services
docker-compose logs -f # View logs
docker-compose down # Stop all services
```
## Testing Strategy
- **Unit Tests**: All business logic (80%+ coverage)
- **Integration Tests**: API endpoints and database operations
- **E2E Tests**: Critical user flows with Playwright
- **Performance Tests**: Load testing for API endpoints
- **Security Tests**: OWASP compliance scans
## Important Notes
- **Context-Specific Guidelines**: Always check subdirectory CLAUDE.md files for detailed guidance
- **Modular Architecture**: Each major component has its own CLAUDE.md file
- **Navigation**: Use Quick Navigation section to find relevant guidelines
- **Production Ready**: This is a production-grade setup with enterprise patterns
---
For detailed guidelines, see context-specific CLAUDE.md files in subdirectories.
**Project Type**: Full-Stack Application (Production)
**Team Size**: Medium (12 developers)
**Architecture**: Modular with context-specific CLAUDE.md files
**Lines**: ~150 (Modular root template with native format)
+461
View File
@@ -0,0 +1,461 @@
# CLAUDE.md
This file provides guidance for Claude Code when working with this Python API project.
## Overview
FastAPI-based RESTful API with PostgreSQL database, JWT authentication, and async SQLAlchemy. Small team (6 developers) following TDD practices with 90%+ test coverage requirement.
## Project Structure
```
project-root/
├── app/
│ ├── api/
│ │ ├── v1/
│ │ │ ├── endpoints/ # API endpoints
│ │ │ │ ├── auth.py
│ │ │ │ ├── users.py
│ │ │ │ └── products.py
│ │ │ ├── dependencies.py # Shared dependencies
│ │ │ └── router.py # API router
│ │ └── __init__.py
│ ├── core/
│ │ ├── config.py # App configuration
│ │ ├── security.py # Auth utilities
│ │ └── database.py # DB connection
│ ├── models/
│ │ ├── user.py # SQLAlchemy models
│ │ └── product.py
│ ├── schemas/
│ │ ├── user.py # Pydantic schemas
│ │ └── product.py
│ ├── services/
│ │ ├── auth_service.py # Business logic
│ │ ├── user_service.py
│ │ └── product_service.py
│ ├── utils/
│ │ ├── logging.py # Logging utilities
│ │ └── validators.py
│ ├── middleware/
│ │ ├── logging.py # Logging middleware
│ │ └── rate_limit.py # Rate limiting
│ └── main.py # App entry point
├── tests/
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ ├── conftest.py # Pytest fixtures
│ └── test_main.py
├── alembic/
│ ├── versions/ # Migration files
│ └── env.py # Alembic config
├── .env.example
├── alembic.ini
├── pyproject.toml
├── requirements.txt
├── Dockerfile
└── docker-compose.yml
```
## File Structure
- **app/** - Main application package
- **api/v1/** - API version 1 endpoints and routing
- **endpoints/** - Path operation functions
- **dependencies.py** - Dependency injection (DB sessions, auth)
- **core/** - Core utilities (config, security, database)
- **models/** - SQLAlchemy ORM models
- **schemas/** - Pydantic models for request/response validation
- **services/** - Business logic layer (separate from HTTP)
- **utils/** - Helper functions (logging, validation)
- **middleware/** - FastAPI middleware components
- **tests/** - Test suite with pytest
- **alembic/** - Database migrations
## Architecture
**Layer Pattern**: FastAPI → Services → Models → Database
**Flow**:
```
HTTP Request → Router → Dependency Injection → Endpoint → Service → Model → Database
Response (Pydantic schema)
```
**Components**:
- **Endpoints**: HTTP layer, request/response handling with Pydantic
- **Services**: Business logic, reusable across endpoints
- **Models**: Data access layer with async SQLAlchemy 2.0
- **Schemas**: Request/response validation with Pydantic
- **Dependencies**: Shared dependencies (DB session, current user)
## Setup & Installation
```bash
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Set up environment variables
cp .env.example .env
# Edit .env with:
# - DATABASE_URL (PostgreSQL connection string)
# - SECRET_KEY (for JWT token signing)
# - ENVIRONMENT (development/staging/production)
# Start PostgreSQL (using Docker)
docker-compose up -d postgres
# Run database migrations
alembic upgrade head
# Seed database (if needed)
python -m app.scripts.seed
# Start development server
uvicorn app.main:app --reload
# Server runs at http://localhost:8000
# API docs at http://localhost:8000/docs (Swagger UI)
# Alternative docs at http://localhost:8000/redoc (ReDoc)
```
## Core Principles
1. **Type Hints First**: Use type hints for all function signatures (Python 3.10+)
2. **Test-Driven Development**: Write tests before implementation
3. **API Design**: Follow RESTful conventions and OpenAPI standards
4. **Error Handling**: Comprehensive error handling with proper logging
5. **Code Quality**: Black formatting, Ruff linting, 90%+ test coverage
## Tech Stack
- **Framework**: FastAPI 0.104+
- **Database**: PostgreSQL 15 with async SQLAlchemy 2.0
- **Authentication**: JWT with python-jose
- **Validation**: Pydantic v2
- **Testing**: Pytest, Pytest-asyncio, HTTPX
- **Deployment**: Docker, Uvicorn, Gunicorn
- **Logging**: Structlog (JSON format)
- **Code Quality**: Black, Ruff, MyPy
## Development Workflow
### Development Process
1. Create feature branch from `main`: `git checkout -b feature/name`
2. Write tests first (TDD with pytest)
3. Implement feature with type hints
4. Run formatter, linter, and tests locally
5. Create pull request with description
6. Code review (minimum 1 approval required)
7. Merge to main (auto-deploy to staging)
### Code Style
- Use Black for formatting (line length: 100)
- Use Ruff for linting (replaces flake8, isort, etc.)
- Type hints on all functions and methods
- Docstrings for all public functions (Google style)
- Example:
```python
def create_user(db: Session, user_in: UserCreate) -> User:
"""Create a new user in the database.
Args:
db: Database session
user_in: User creation data
Returns:
Created user object
Raises:
ValueError: If email already exists
"""
# Implementation...
```
## API Design Guidelines
### FastAPI Path Operations
- Use FastAPI path operations (`@app.get`, `@app.post`, etc.)
- Version APIs: `/api/v1/users`, `/api/v2/users`
- Use Pydantic models for request/response validation
- Implement proper HTTP status codes:
- `200 OK` - Successful GET/PUT/PATCH
- `201 Created` - Successful POST
- `204 No Content` - Successful DELETE
- `400 Bad Request` - Validation error
- `401 Unauthorized` - Authentication required
- `403 Forbidden` - Insufficient permissions
- `404 Not Found` - Resource not found
- `422 Unprocessable Entity` - Pydantic validation error
- `500 Internal Server Error` - Server error
### Documentation
- Document with OpenAPI (auto-generated by FastAPI)
- Access Swagger UI at `/docs`
- Access ReDoc at `/redoc`
- Add descriptions to path operations:
```python
@router.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int, db: Session = Depends(get_db)):
"""Retrieve a single user by ID."""
# Implementation...
```
## Database Guidelines
### Migrations with Alembic
- Use Alembic for migrations
- **Never edit existing migrations** - create new ones
- Auto-generate migrations: `alembic revision --autogenerate -m "description"`
- Review generated migrations before applying
- Test migrations on copy of production data
- Name migrations descriptively: `add_user_email_index`
### SQLAlchemy 2.0 Async Style
- Use async SQLAlchemy 2.0 style
- Example:
```python
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
async def get_user(db: AsyncSession, user_id: int) -> User | None:
result = await db.execute(select(User).where(User.id == user_id))
return result.scalar_one_or_none()
```
### Query Optimization
- Implement proper indexes for frequently queried columns
- Avoid N+1 queries - use `selectinload` or `joinedload`
- Use database transactions for multi-step operations
- Paginate large result sets (max 100 items per page)
## Error Handling
### FastAPI Exception Handlers
- Use FastAPI exception handlers
- Create custom exceptions:
```python
class UserNotFoundException(HTTPException):
def __init__(self, user_id: int):
super().__init__(
status_code=404,
detail=f"User {user_id} not found"
)
```
### Error Response Format
Return consistent error format:
```python
{
"detail": {
"code": "VALIDATION_ERROR",
"message": "User-friendly message",
"errors": [
{
"field": "email",
"message": "Invalid email format"
}
]
}
}
```
### Logging
- Log errors with structlog (JSON format)
- Include context (request ID, user ID, timestamp)
- Log levels: ERROR, WARNING, INFO, DEBUG
- Never log sensitive data (passwords, tokens)
- Never expose stack traces in production
## Testing Requirements
### Pytest Best Practices
- Use pytest for all tests
- Use pytest fixtures for test setup
- Mock external dependencies (httpx, boto3, etc.)
- Aim for 90%+ code coverage
- Test both success and error paths
### Example Test
```python
import pytest
from httpx import AsyncClient
from app.main import app
@pytest.mark.asyncio
async def test_create_user(client: AsyncClient):
"""Test user creation endpoint."""
response = await client.post(
"/api/v1/users",
json={"email": "test@example.com", "name": "Test User"}
)
assert response.status_code == 201
data = response.json()
assert data["email"] == "test@example.com"
assert "id" in data
@pytest.mark.asyncio
async def test_create_user_duplicate_email(client: AsyncClient):
"""Test user creation with duplicate email."""
# First creation
await client.post("/api/v1/users", json={"email": "test@example.com"})
# Duplicate should fail
response = await client.post("/api/v1/users", json={"email": "test@example.com"})
assert response.status_code == 400
```
### Test Categories
```bash
# Run all tests
pytest
# Run specific test categories
pytest tests/unit/ # Unit tests only
pytest tests/integration/ # Integration tests only
pytest -m slow # Slow tests (marked with @pytest.mark.slow)
# Run with coverage
pytest --cov=app --cov-report=html
```
## Security Practices
### Input Validation
- Validate all input with Pydantic models
- Use Pydantic validators for complex validation
- Sanitize user input to prevent XSS
### Database Security
- Use parameterized queries (SQLAlchemy handles this)
- Prevents SQL injection
- Never concatenate user input into queries
### Authentication & Authorization
- Hash passwords with passlib + bcrypt
- Use JWT for stateless authentication
- Implement refresh token rotation
- Use environment variables for secrets
- Example:
```python
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
hashed_password = pwd_context.hash(plain_password)
```
### Rate Limiting
- Implement rate limiting with slowapi
- Example: 100 requests per 15 minutes per IP
- Protect against brute force attacks
### CORS
- Enable CORS properly with CORSMiddleware
- Whitelist allowed origins in production
- Don't use wildcard (`*`) in production
## Performance Optimization
### Async/Await
- Use async/await for all I/O operations
- Use AsyncSession for database operations
- Use httpx.AsyncClient for external HTTP calls
### Caching
- Implement caching for frequently accessed data
- Use Redis for caching (with aioredis)
- Cache expensive computations
- Set appropriate TTL (time-to-live)
### Database Connection Pooling
- Configure SQLAlchemy connection pool
- Set appropriate pool size and overflow
## Common Commands
```bash
# Development
uvicorn app.main:app --reload # Start dev server with hot reload
pytest # Run all tests
pytest --cov=app # Run tests with coverage
black . # Format code
ruff check . # Lint code
mypy app/ # Type checking
# Database
alembic upgrade head # Run all pending migrations
alembic downgrade -1 # Rollback last migration
alembic revision --autogenerate -m "description" # Create migration
alembic current # Show current migration
alembic history # Show migration history
# Production
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker
# Docker
docker-compose up -d # Start all services
docker-compose logs -f app # View application logs
docker-compose down # Stop all services
```
## API Documentation
After starting the server, access API documentation at:
- **Swagger UI**: http://localhost:8000/docs (interactive)
- **ReDoc**: http://localhost:8000/redoc (readable)
- **OpenAPI JSON**: http://localhost:8000/openapi.json (raw schema)
## Environment Variables
Required environment variables (see `.env.example`):
```bash
# Application
ENVIRONMENT=development
SECRET_KEY=your-secret-key-here
DEBUG=True
# Database
DATABASE_URL=postgresql+asyncpg://user:password@localhost/dbname
# Authentication
ACCESS_TOKEN_EXPIRE_MINUTES=30
REFRESH_TOKEN_EXPIRE_DAYS=7
# CORS
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173
```
---
**Project Type**: Python API (FastAPI)
**Team Size**: Small (6 developers)
**Lines**: ~225 (Python API template with native format)
+155
View File
@@ -0,0 +1,155 @@
{
"outputs": [
{
"scenario": "initialize_new_project",
"output": {
"workflow_status": "completed",
"detected_context": {
"project_type": "fullstack",
"tech_stack": ["typescript", "react", "express"],
"team_size": "small",
"phase": "mvp",
"workflows": ["tdd", "cicd"],
"modular_recommended": true
},
"confirmation_prompt": "Based on my exploration, here's what I discovered:\n\n**Project Type**: Fullstack\n**Tech Stack**: typescript, react, express\n**Team Size**: Small (2-9 developers)\n**Development Phase**: Mvp\n**Workflows**: tdd, cicd\n\n**Recommended Structure**:\nModular architecture (separate CLAUDE.md files for major components)\n\nWould you like me to create a CLAUDE.md file based on these discoveries?",
"created_files": [
"CLAUDE.md",
"backend/CLAUDE.md",
"frontend/CLAUDE.md"
],
"summary": "✅ CLAUDE.md Initialization Complete!\n\n**Created Files** (3):\n- CLAUDE.md\n- backend/CLAUDE.md\n- frontend/CLAUDE.md\n\n**Next Steps**:\n1. Review the generated CLAUDE.md file\n2. Customize for your specific needs\n3. Add team-specific conventions\n4. Update as your project evolves\n\nYour project is now set up for efficient AI-assisted development with Claude Code!"
}
},
{
"scenario": "analyze_existing",
"output": {
"analysis": {
"file_metrics": {
"char_count": 150,
"line_count": 12,
"word_count": 25,
"heading_count": 3,
"code_block_count": 0
},
"sections_found": ["Tech Stack", "Workflow"],
"missing_sections": [
"Quick Navigation",
"Core Principles",
"Quality Checklist",
"File Organization",
"Common Commands",
"References"
],
"structure_analysis": {
"has_main_title": true,
"has_navigation_section": false,
"has_code_examples": false,
"has_links": false,
"mentions_modular_architecture": false,
"section_count": 2,
"subsection_count": 0,
"hierarchy_depth": 2
},
"issues": [
{
"type": "too_short",
"severity": "medium",
"message": "File is very short (12 lines). May need more guidance."
},
{
"type": "missing_critical_sections",
"severity": "high",
"message": "Missing critical sections: Core Principles"
}
],
"quality_score": 35,
"recommendations": [
"CRITICAL: Add essential sections: Core Principles",
"Expand with essential sections: Core Principles, Tech Stack, Workflow Instructions",
"Consider adding: Quick Navigation, Quality Checklist, File Organization",
"Include code examples for complex patterns to improve clarity",
"Overall quality score is 35/100 - prioritize critical improvements"
]
}
}
},
{
"scenario": "create_new_fullstack",
"output": {
"root_file": "# CLAUDE.md\n\nThis file provides top-level guidance for Claude Code when working with this fullstack.\n\n## Quick Navigation\n\n- [Backend Guidelines](backend/CLAUDE.md)\n- [Frontend Guidelines](frontend/CLAUDE.md)\n- [Database Operations](database/CLAUDE.md)\n- [CI/CD Workflows](.github/CLAUDE.md)\n\n## Core Principles\n\n1. **Test-Driven Development**: Write tests before implementation\n2. **Use TypeScript strict mode throughout the project**: Use TypeScript strict mode throughout the project\n3. **Prefer functional components with hooks over class components**: Prefer functional components with hooks over class components\n4. **Use multi-stage Dockerfiles for optimized image size**: Use multi-stage Dockerfiles for optimized image size\n5. **Code Quality**: Maintain high code quality with clear, readable implementations\n\n## Tech Stack\n\n- **Languages**: TypeScript\n- **Frameworks**: React\n- **Tools**: PostgreSQL, Docker\n\n## Quick Reference\n\n```bash\n# Common development commands\nnpm test # Run tests\nnpm run lint # Run linter\nnpm run build # Build for production\n```\n\n---\n\nFor detailed guidelines, see context-specific CLAUDE.md files in subdirectories.",
"context_files": {
"backend": "# Backend Development Guidelines\n\nThis file provides guidance for backend development in this project.\n\n## API Design\n\n- Use RESTful conventions for API endpoints\n- Implement proper HTTP status codes (200, 201, 400, 404, 500)\n- Version APIs when breaking changes are needed (/api/v1/, /api/v2/)\n- Document all endpoints with OpenAPI/Swagger\n\n## Database Operations\n\n- Use migrations for all schema changes\n- Implement proper indexes for query performance\n- Use transactions for multi-step operations\n- Avoid N+1 queries - use joins or batch loading\n\n## Error Handling\n\n- Implement global error handling middleware\n- Log errors with context (request ID, user ID, timestamp)\n- Return consistent error response format\n- Never expose stack traces to clients in production\n\n## Testing Requirements\n\n- Write unit tests for business logic\n- Write integration tests for API endpoints\n- Mock external services in tests\n- Aim for 80%+ code coverage\n",
"frontend": "# Frontend Development Guidelines\n\nThis file provides guidance for frontend development in this project.\n\n## Component Standards\n\n- Prefer functional components with hooks over class components\n- Use TypeScript for type safety\n- Keep components small and focused (< 200 lines)\n- Extract reusable logic into custom hooks\n\n## State Management\n\n- Keep component state local when possible\n- Use global state only for truly shared data\n- Avoid prop drilling - use context/store for deep state\n- Document state shape and update patterns\n\n## Styling Guidelines\n\n- Use consistent naming conventions (BEM, CSS Modules, etc.)\n- Avoid inline styles except for dynamic values\n- Use design tokens for colors, spacing, typography\n- Ensure responsive design for all breakpoints\n\n## Performance Optimization\n\n- Lazy load routes and heavy components\n- Optimize images (use WebP, lazy loading)\n- Minimize bundle size - code split where possible\n- Use memoization for expensive calculations\n",
"database": "# Database Guidelines\n\nThis file provides guidance for database operations and migrations.\n\n## Schema Design\n\n- Use meaningful table and column names\n- Always include created_at and updated_at timestamps\n- Use proper foreign key constraints\n- Add indexes for frequently queried columns\n\n## Migration Guidelines\n\n- Never edit existing migrations - create new ones\n- Test migrations on copy of production data\n- Include both up and down migrations\n- Document breaking changes in migration comments\n\n## Query Optimization\n\n- Use EXPLAIN to analyze slow queries\n- Avoid SELECT * - specify needed columns\n- Use appropriate JOIN types\n- Limit result sets with pagination\n"
}
}
},
{
"scenario": "enhance_with_missing_sections",
"output": {
"enhanced_content": "# CLAUDE.md\n\n## Core Principles\n1. Write tests first\n2. Use TypeScript\n\n## Tech Stack\n- TypeScript\n- React\n- PostgreSQL\n\n## Testing Requirements\n\n- Write tests before or alongside feature implementation\n- Maintain minimum 80% code coverage\n- Include unit, integration, and e2e tests\n- Mock external dependencies in tests\n\n## Error Handling Patterns\n\n- Implement comprehensive error handling from the start\n- Log errors with context (user ID, request ID, timestamp)\n- Provide helpful error messages to users\n- Never expose sensitive information in error messages\n\n## Performance Guidelines\n\n[Add performance guidelines specific to your project]\n",
"sections_added": ["Testing Requirements", "Error Handling Patterns", "Performance Guidelines"]
}
},
{
"scenario": "validate_existing",
"output": {
"valid": true,
"validation_results": {
"length": {
"check": "file_length",
"status": "pass",
"message": "File length is appropriate (19 lines)",
"severity": "info",
"actual_value": 19,
"expected_range": "20-300 lines"
},
"structure": {
"check": "file_structure",
"status": "pass",
"message": "Structure validation complete",
"severity": "info",
"errors": [],
"warnings": [],
"sections_found": 5
},
"formatting": {
"check": "markdown_formatting",
"status": "pass",
"message": "Formatting validation complete",
"severity": "low",
"errors": [],
"warnings": []
},
"completeness": {
"check": "content_completeness",
"status": "pass",
"message": "Completeness validation complete",
"severity": "medium",
"errors": [],
"warnings": [],
"has_code_examples": false,
"has_links": false,
"has_lists": true,
"tech_stack_mentioned": true
},
"anti_patterns": {
"check": "anti_patterns",
"status": "pass",
"message": "No anti-patterns detected",
"severity": "info",
"detected_patterns": []
}
},
"errors": [],
"warnings": [
"No code examples found - consider adding examples for clarity",
"No links found - consider linking to external documentation"
],
"pass_count": 5,
"fail_count": 0
}
}
]
}
+480
View File
@@ -0,0 +1,480 @@
"""
CLAUDE.md Content Generator
Generates new CLAUDE.md files or enhances existing ones based on templates and analysis.
Supports modular architecture with context-specific files.
"""
from typing import Dict, List, Any, Optional
from template_selector import TemplateSelector
import re
class ContentGenerator:
"""Generates and enhances CLAUDE.md files based on project context."""
def __init__(self, project_context: Dict[str, Any]):
"""
Initialize content generator with project context.
Args:
project_context: Dictionary containing project type, tech_stack, team_size, etc.
"""
self.project_context = project_context
self.template_selector = TemplateSelector(project_context)
def generate_root_file(self) -> str:
"""
Generate root CLAUDE.md file (navigation hub).
Returns:
Complete CLAUDE.md content as string
"""
template = self.template_selector.select_template()
# Use template selector's customization
if template.get('modular_recommended'):
return self._generate_modular_root(template)
else:
return self._generate_standalone_file(template)
def _generate_modular_root(self, template: Dict[str, Any]) -> str:
"""Generate root file for modular architecture (navigation hub)."""
lines = []
# Title
lines.append("# CLAUDE.md")
lines.append("")
lines.append(f"This file provides top-level guidance for Claude Code when working with this {self.project_context.get('type', 'project')}.")
lines.append("")
# Quick Navigation
lines.append("## Quick Navigation")
lines.append("")
lines.extend(self._generate_navigation_section(template))
lines.append("")
# Core Principles (concise, 5-7 principles)
lines.append("## Core Principles")
lines.append("")
principles = self._generate_core_principles(template, max_count=5)
lines.extend(principles)
lines.append("")
# Tech Stack (summary only)
if self.project_context.get('tech_stack'):
lines.append("## Tech Stack")
lines.append("")
lines.extend(self._generate_tech_stack_summary())
lines.append("")
# Key Commands/Shortcuts
lines.append("## Quick Reference")
lines.append("")
lines.extend(self._generate_quick_reference())
lines.append("")
# Footer
lines.append("---")
lines.append("")
lines.append("For detailed guidelines, see context-specific CLAUDE.md files in subdirectories.")
return '\n'.join(lines)
def _generate_standalone_file(self, template: Dict[str, Any]) -> str:
"""Generate standalone CLAUDE.md file (all-in-one)."""
return self.template_selector.customize_template(template)
def generate_context_file(self, context: str) -> str:
"""
Generate context-specific CLAUDE.md file (e.g., backend, frontend).
Args:
context: Context name ('backend', 'frontend', 'database', etc.)
Returns:
Context-specific CLAUDE.md content
"""
generators = {
'backend': self._generate_backend_file,
'frontend': self._generate_frontend_file,
'database': self._generate_database_file,
'docs': self._generate_docs_file,
'.github': self._generate_github_file
}
generator = generators.get(context, self._generate_generic_context_file)
return generator()
def _generate_backend_file(self) -> str:
"""Generate backend-specific CLAUDE.md."""
lines = []
lines.append("# Backend Development Guidelines")
lines.append("")
lines.append("This file provides guidance for backend development in this project.")
lines.append("")
# API Design
lines.append("## API Design")
lines.append("")
lines.append("- Use RESTful conventions for API endpoints")
lines.append("- Implement proper HTTP status codes (200, 201, 400, 404, 500)")
lines.append("- Version APIs when breaking changes are needed (/api/v1/, /api/v2/)")
lines.append("- Document all endpoints with OpenAPI/Swagger")
lines.append("")
# Database Guidelines
lines.append("## Database Operations")
lines.append("")
lines.append("- Use migrations for all schema changes")
lines.append("- Implement proper indexes for query performance")
lines.append("- Use transactions for multi-step operations")
lines.append("- Avoid N+1 queries - use joins or batch loading")
lines.append("")
# Error Handling
lines.append("## Error Handling")
lines.append("")
lines.append("- Implement global error handling middleware")
lines.append("- Log errors with context (request ID, user ID, timestamp)")
lines.append("- Return consistent error response format")
lines.append("- Never expose stack traces to clients in production")
lines.append("")
# Testing
lines.append("## Testing Requirements")
lines.append("")
lines.append("- Write unit tests for business logic")
lines.append("- Write integration tests for API endpoints")
lines.append("- Mock external services in tests")
lines.append("- Aim for 80%+ code coverage")
lines.append("")
return '\n'.join(lines)
def _generate_frontend_file(self) -> str:
"""Generate frontend-specific CLAUDE.md."""
lines = []
lines.append("# Frontend Development Guidelines")
lines.append("")
lines.append("This file provides guidance for frontend development in this project.")
lines.append("")
# Component Standards
lines.append("## Component Standards")
lines.append("")
tech_stack = [t.lower() for t in self.project_context.get('tech_stack', [])]
if 'react' in tech_stack:
lines.append("- Prefer functional components with hooks over class components")
lines.append("- Use TypeScript for type safety")
lines.append("- Keep components small and focused (< 200 lines)")
lines.append("- Extract reusable logic into custom hooks")
elif 'vue' in tech_stack:
lines.append("- Use Composition API for complex components")
lines.append("- Keep components small and focused (< 200 lines)")
lines.append("- Use TypeScript with Vue 3")
lines.append("- Extract reusable logic into composables")
else:
lines.append("- Keep components small and focused")
lines.append("- Extract reusable logic into utilities")
lines.append("- Use TypeScript for type safety")
lines.append("")
# State Management
lines.append("## State Management")
lines.append("")
lines.append("- Keep component state local when possible")
lines.append("- Use global state only for truly shared data")
lines.append("- Avoid prop drilling - use context/store for deep state")
lines.append("- Document state shape and update patterns")
lines.append("")
# Styling
lines.append("## Styling Guidelines")
lines.append("")
lines.append("- Use consistent naming conventions (BEM, CSS Modules, etc.)")
lines.append("- Avoid inline styles except for dynamic values")
lines.append("- Use design tokens for colors, spacing, typography")
lines.append("- Ensure responsive design for all breakpoints")
lines.append("")
# Performance
lines.append("## Performance Optimization")
lines.append("")
lines.append("- Lazy load routes and heavy components")
lines.append("- Optimize images (use WebP, lazy loading)")
lines.append("- Minimize bundle size - code split where possible")
lines.append("- Use memoization for expensive calculations")
lines.append("")
return '\n'.join(lines)
def _generate_database_file(self) -> str:
"""Generate database-specific CLAUDE.md."""
lines = []
lines.append("# Database Guidelines")
lines.append("")
lines.append("This file provides guidance for database operations and migrations.")
lines.append("")
# Schema Design
lines.append("## Schema Design")
lines.append("")
lines.append("- Use meaningful table and column names")
lines.append("- Always include created_at and updated_at timestamps")
lines.append("- Use proper foreign key constraints")
lines.append("- Add indexes for frequently queried columns")
lines.append("")
# Migrations
lines.append("## Migration Guidelines")
lines.append("")
lines.append("- Never edit existing migrations - create new ones")
lines.append("- Test migrations on copy of production data")
lines.append("- Include both up and down migrations")
lines.append("- Document breaking changes in migration comments")
lines.append("")
# Query Optimization
lines.append("## Query Optimization")
lines.append("")
lines.append("- Use EXPLAIN to analyze slow queries")
lines.append("- Avoid SELECT * - specify needed columns")
lines.append("- Use appropriate JOIN types")
lines.append("- Limit result sets with pagination")
lines.append("")
return '\n'.join(lines)
def _generate_docs_file(self) -> str:
"""Generate documentation-specific CLAUDE.md."""
lines = []
lines.append("# Documentation Guidelines")
lines.append("")
lines.append("This file provides guidance for project documentation.")
lines.append("")
lines.append("## Documentation Standards")
lines.append("")
lines.append("- Keep README.md updated with setup instructions")
lines.append("- Document all public APIs with examples")
lines.append("- Include architecture diagrams for complex systems")
lines.append("- Maintain changelog with semantic versioning")
lines.append("")
return '\n'.join(lines)
def _generate_github_file(self) -> str:
"""Generate .github-specific CLAUDE.md for CI/CD."""
lines = []
lines.append("# CI/CD Workflows")
lines.append("")
lines.append("This file provides guidance for GitHub Actions and CI/CD processes.")
lines.append("")
lines.append("## Workflow Guidelines")
lines.append("")
lines.append("- Run linting and tests on all pull requests")
lines.append("- Automate deployments to staging on main branch")
lines.append("- Require manual approval for production deployments")
lines.append("- Cache dependencies to speed up builds")
lines.append("")
return '\n'.join(lines)
def _generate_generic_context_file(self) -> str:
"""Generate generic context-specific file."""
return "# Context-Specific Guidelines\n\n[Add guidelines specific to this context]\n"
def generate_section(self, section_name: str) -> str:
"""
Generate a specific section for CLAUDE.md.
Args:
section_name: Name of section to generate
Returns:
Section content as string
"""
generators = {
'Core Principles': self._generate_core_principles_section,
'Tech Stack': self._generate_tech_stack_section,
'Workflow Instructions': self._generate_workflow_section,
'Testing Requirements': self._generate_testing_section,
'Error Handling': self._generate_error_handling_section,
'Documentation Standards': self._generate_documentation_section
}
generator = generators.get(section_name, self._generate_generic_section)
return generator(section_name)
def _generate_core_principles_section(self, section_name: str) -> str:
"""Generate Core Principles section."""
template = self.template_selector.select_template()
lines = [f"## {section_name}", ""]
lines.extend(self._generate_core_principles(template, max_count=7))
return '\n'.join(lines)
def _generate_tech_stack_section(self, section_name: str) -> str:
"""Generate Tech Stack section."""
lines = [f"## {section_name}", ""]
lines.extend(self._generate_tech_stack_summary())
return '\n'.join(lines)
def _generate_workflow_section(self, section_name: str) -> str:
"""Generate Workflow Instructions section."""
lines = [f"## {section_name}", ""]
workflows = self.project_context.get('workflows', [])
if workflows:
for i, workflow in enumerate(workflows, 1):
workflow_title = workflow.replace('_', ' ').title()
lines.append(f"{i}. **{workflow_title}**: [Add {workflow} workflow description]")
else:
lines.append("[Add workflow instructions specific to your project]")
return '\n'.join(lines)
def _generate_testing_section(self, section_name: str) -> str:
"""Generate Testing Requirements section."""
lines = [f"## {section_name}", ""]
lines.append("- Write tests before or alongside feature implementation")
lines.append("- Maintain minimum 80% code coverage")
lines.append("- Include unit, integration, and e2e tests")
lines.append("- Mock external dependencies in tests")
return '\n'.join(lines)
def _generate_error_handling_section(self, section_name: str) -> str:
"""Generate Error Handling section."""
lines = [f"## {section_name}", ""]
lines.append("- Implement comprehensive error handling from the start")
lines.append("- Log errors with context (user ID, request ID, timestamp)")
lines.append("- Provide helpful error messages to users")
lines.append("- Never expose sensitive information in error messages")
return '\n'.join(lines)
def _generate_documentation_section(self, section_name: str) -> str:
"""Generate Documentation Standards section."""
lines = [f"## {section_name}", ""]
lines.append("- Keep documentation in sync with code")
lines.append("- Document all public APIs and interfaces")
lines.append("- Include code examples in documentation")
lines.append("- Update README.md with setup and usage instructions")
return '\n'.join(lines)
def _generate_generic_section(self, section_name: str) -> str:
"""Generate generic section placeholder."""
return f"## {section_name}\n\n[Add {section_name.lower()} guidelines specific to your project]\n"
def merge_with_existing(self, existing_content: str, new_sections: List[str]) -> str:
"""
Merge new sections with existing CLAUDE.md content.
Args:
existing_content: Current CLAUDE.md content
new_sections: List of new sections to add
Returns:
Merged content as string
"""
lines = existing_content.split('\n')
existing_sections = self._extract_existing_sections(existing_content)
# Add new sections that don't already exist
for new_section in new_sections:
section_name = new_section.split('\n')[0].replace('## ', '')
if section_name not in existing_sections:
lines.append("")
lines.append(new_section)
return '\n'.join(lines)
def _extract_existing_sections(self, content: str) -> List[str]:
"""Extract section names from existing content."""
sections = []
for line in content.split('\n'):
if line.startswith('## '):
sections.append(line[3:].strip())
return sections
def _generate_navigation_section(self, template: Dict[str, Any]) -> List[str]:
"""Generate navigation section for modular architecture."""
project_type = self.project_context.get('type')
links = []
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)")
if 'cicd' in self.project_context.get('workflows', []):
links.append("- [CI/CD Workflows](.github/CLAUDE.md)")
if not links:
links.append("- [Add links to context-specific CLAUDE.md files]")
return links
def _generate_core_principles(self, template: Dict[str, Any], max_count: int = 7) -> List[str]:
"""Generate core principles list."""
principles = []
workflows = self.project_context.get('workflows', [])
# Add workflow-based principles
if 'tdd' in workflows:
principles.append("1. **Test-Driven Development**: Write tests before implementation")
# Add tech-specific principles
tech_custom = template.get('tech_customization', {})
for guideline in tech_custom.get('specific_guidelines', [])[:3]:
principle_num = len(principles) + 1
principles.append(f"{principle_num}. **{guideline.split(':')[0] if ':' in guideline else 'Guideline'}**: {guideline}")
# Add generic essential principles
generic = [
"**Code Quality**: Maintain high code quality with clear, readable implementations",
"**Documentation**: Keep documentation in sync with code changes",
"**Error Handling**: Implement comprehensive error handling from the start",
"**Performance**: Consider performance implications in implementation decisions",
"**Security**: Follow security best practices and avoid common vulnerabilities"
]
for principle in generic:
if len(principles) >= max_count:
break
principle_num = len(principles) + 1
principles.append(f"{principle_num}. {principle}")
return principles
def _generate_tech_stack_summary(self) -> List[str]:
"""Generate tech stack summary."""
lines = []
template = self.template_selector.select_template()
tech_custom = template.get('tech_customization', {})
if tech_custom.get('languages'):
lines.append(f"- **Languages**: {', '.join(tech_custom['languages'])}")
if tech_custom.get('frameworks'):
lines.append(f"- **Frameworks**: {', '.join(tech_custom['frameworks'])}")
if tech_custom.get('tools'):
lines.append(f"- **Tools**: {', '.join(tech_custom['tools'])}")
if not lines:
lines.append("- [Add your tech stack details here]")
return lines
def _generate_quick_reference(self) -> List[str]:
"""Generate quick reference commands."""
lines = []
lines.append("```bash")
lines.append("# Common development commands")
lines.append("npm test # Run tests")
lines.append("npm run lint # Run linter")
lines.append("npm run build # Build for production")
lines.append("```")
return lines
+109
View File
@@ -0,0 +1,109 @@
{
"examples": [
{
"scenario": "initialize_new_project",
"description": "Interactive initialization workflow for new project without CLAUDE.md",
"input": {
"mode": "initialize",
"exploration_results": {
"files": ["package.json", "tsconfig.json", "README.md", ".github/workflows/ci.yml"],
"directories": ["src", "backend", "frontend", "tests", ".github/workflows"],
"file_contents": {
"package.json": "{\"dependencies\": {\"react\": \"^18.0.0\", \"typescript\": \"^5.0.0\", \"express\": \"^4.18.0\"}}",
"README.md": "# Full-Stack TypeScript Project"
}
},
"user_confirmation": "yes"
}
},
{
"scenario": "analyze_existing",
"description": "Analyze an existing CLAUDE.md file for quality and completeness",
"input": {
"mode": "analyze",
"content": "# CLAUDE.md\n\nThis is a basic CLAUDE file.\n\n## Tech Stack\n- TypeScript\n- React\n- Node.js\n\n## Workflow\n- Use Git for version control\n- Write tests\n\n",
"project_context": {
"type": "web_app",
"tech_stack": ["typescript", "react", "node"],
"team_size": "small",
"phase": "mvp"
}
}
},
{
"scenario": "create_new_fullstack",
"description": "Create new CLAUDE.md for a full-stack TypeScript project",
"input": {
"mode": "create",
"project_context": {
"type": "fullstack",
"tech_stack": ["typescript", "react", "node", "postgresql", "docker"],
"team_size": "small",
"phase": "mvp",
"workflows": ["tdd", "cicd", "documentation_first"]
},
"modular": true,
"subdirectories": ["backend", "frontend", "database"]
}
},
{
"scenario": "enhance_with_missing_sections",
"description": "Enhance existing file by adding missing sections",
"input": {
"mode": "enhance",
"content": "# CLAUDE.md\n\n## Core Principles\n1. Write tests first\n2. Use TypeScript\n\n## Tech Stack\n- TypeScript\n- React\n- PostgreSQL\n",
"project_context": {
"type": "web_app",
"tech_stack": ["typescript", "react", "postgresql"],
"team_size": "medium",
"phase": "production"
},
"add_sections": ["Testing Requirements", "Error Handling Patterns", "Performance Guidelines"]
}
},
{
"scenario": "create_modular_architecture",
"description": "Create modular CLAUDE.md setup for large team",
"input": {
"mode": "create",
"project_context": {
"type": "api",
"tech_stack": ["python", "fastapi", "postgresql", "redis", "docker", "kubernetes"],
"team_size": "large",
"phase": "enterprise",
"workflows": ["tdd", "cicd", "agile"]
},
"modular": true,
"subdirectories": ["backend", "database", "docs", ".github"]
}
},
{
"scenario": "validate_existing",
"description": "Validate existing CLAUDE.md against best practices",
"input": {
"mode": "validate",
"content": "# CLAUDE.md\n\nGuidance for development.\n\n## Core Principles\n\n1. Code quality matters\n2. Test everything\n3. Document changes\n\n## Tech Stack\n\n- React 18\n- TypeScript 5\n- Node 20\n- PostgreSQL 15\n\n## Workflow Instructions\n\n### Development Process\n\n1. Create feature branch\n2. Write tests\n3. Implement feature\n4. Create PR\n5. Code review\n6. Merge to main\n\n## Testing Requirements\n\n- Unit tests for all business logic\n- Integration tests for API endpoints\n- E2E tests for critical user flows\n- Minimum 80% code coverage\n\n## Error Handling\n\n- Use try-catch blocks\n- Log errors with context\n- Return meaningful error messages\n- Never expose sensitive data\n\n",
"project_context": {
"type": "fullstack",
"tech_stack": ["typescript", "react", "node", "postgresql"],
"team_size": "small",
"phase": "production"
}
}
},
{
"scenario": "generate_context_specific",
"description": "Generate backend-specific CLAUDE.md file",
"input": {
"mode": "generate_context",
"context": "backend",
"project_context": {
"type": "api",
"tech_stack": ["python", "fastapi", "postgresql"],
"team_size": "small",
"phase": "mvp"
}
}
}
]
}
+467
View File
@@ -0,0 +1,467 @@
"""
CLAUDE.md Template Selector
Selects appropriate CLAUDE.md templates based on project context.
Provides intelligent template selection, customization, and recommendations.
"""
from typing import Dict, List, Any, Optional
class TemplateSelector:
"""Selects and customizes CLAUDE.md templates based on project context."""
# Template definitions by project type
PROJECT_TEMPLATES = {
"web_app": {
"focus": "Frontend components, UI/UX, state management",
"sections": [
"Quick Navigation", "Core Principles", "Component Standards",
"State Management", "Styling Guidelines", "Testing Requirements",
"Performance Optimization", "Accessibility"
],
"tech_hints": ["react", "vue", "angular", "svelte"]
},
"api": {
"focus": "Backend services, REST/GraphQL, database operations",
"sections": [
"Quick Navigation", "Core Principles", "API Design",
"Database Guidelines", "Error Handling", "Testing Requirements",
"Security Practices", "Documentation Standards"
],
"tech_hints": ["node", "python", "go", "java", "fastapi", "express"]
},
"fullstack": {
"focus": "Integrated frontend + backend, end-to-end workflows",
"sections": [
"Quick Navigation", "Core Principles", "Frontend Guidelines",
"Backend Guidelines", "Database Operations", "API Integration",
"Testing Strategy", "Deployment Process"
],
"tech_hints": ["next.js", "django", "rails", "laravel"]
},
"cli": {
"focus": "Command-line interface, user interaction, scripting",
"sections": [
"Quick Navigation", "Core Principles", "Command Structure",
"Argument Parsing", "Error Handling", "Testing Requirements",
"Documentation Standards", "Distribution"
],
"tech_hints": ["click", "commander", "cobra", "clap"]
},
"library": {
"focus": "Reusable package, API design, versioning",
"sections": [
"Quick Navigation", "Core Principles", "Public API Design",
"Versioning Strategy", "Testing Requirements", "Documentation Standards",
"Breaking Changes", "Release Process"
],
"tech_hints": ["npm", "pypi", "crates.io", "maven"]
},
"mobile": {
"focus": "Mobile UI, platform-specific code, performance",
"sections": [
"Quick Navigation", "Core Principles", "Platform Guidelines",
"Navigation Patterns", "State Management", "Performance Optimization",
"Testing Requirements", "Release Process"
],
"tech_hints": ["react-native", "flutter", "ios", "android"]
},
"desktop": {
"focus": "Desktop application, native integration, distribution",
"sections": [
"Quick Navigation", "Core Principles", "Window Management",
"Native Integration", "State Management", "Testing Requirements",
"Build Process", "Distribution"
],
"tech_hints": ["electron", "tauri", "qt", "gtk"]
}
}
# Team size templates
TEAM_SIZE_TEMPLATES = {
"solo": {
"target_lines": 75,
"complexity": "minimal",
"focus": "Efficiency, personal workflow",
"detail_level": "concise"
},
"small": {
"target_lines": 125,
"complexity": "core",
"focus": "Core guidelines, collaboration basics",
"detail_level": "moderate"
},
"medium": {
"target_lines": 200,
"complexity": "detailed",
"focus": "Team coordination, process standardization",
"detail_level": "comprehensive"
},
"large": {
"target_lines": 275,
"complexity": "comprehensive",
"focus": "Enterprise standards, governance",
"detail_level": "extensive"
}
}
# Development phase templates
PHASE_TEMPLATES = {
"prototype": {
"priority": ["Quick start", "Flexibility", "Rapid iteration"],
"skip_sections": ["Security Practices", "Performance Optimization"]
},
"mvp": {
"priority": ["Core features", "Testing basics", "Documentation"],
"skip_sections": []
},
"production": {
"priority": ["Quality", "Security", "Performance", "Monitoring"],
"skip_sections": []
},
"enterprise": {
"priority": ["Compliance", "Security", "Scalability", "Governance"],
"skip_sections": []
}
}
def __init__(self, project_context: Dict[str, Any]):
"""
Initialize template selector with project context.
Args:
project_context: Dictionary containing project type, tech_stack, team_size, etc.
"""
self.project_type = project_context.get('type', 'web_app')
self.tech_stack = project_context.get('tech_stack', [])
self.team_size = project_context.get('team_size', 'small')
self.phase = project_context.get('phase', 'mvp')
self.workflows = project_context.get('workflows', [])
self.modular = project_context.get('modular', False)
def select_template(self) -> Dict[str, Any]:
"""
Select the most appropriate template based on project context.
Returns:
Template configuration dictionary
"""
# Get base template for project type
project_template = self.PROJECT_TEMPLATES.get(
self.project_type,
self.PROJECT_TEMPLATES['web_app']
)
# Get team size configuration
team_config = self.TEAM_SIZE_TEMPLATES.get(
self.team_size,
self.TEAM_SIZE_TEMPLATES['small']
)
# Get phase configuration
phase_config = self.PHASE_TEMPLATES.get(
self.phase,
self.PHASE_TEMPLATES['mvp']
)
# Combine into final template
return {
"project_type": self.project_type,
"team_size": self.team_size,
"phase": self.phase,
"target_lines": team_config['target_lines'],
"complexity": team_config['complexity'],
"sections": self._select_sections(
project_template['sections'],
phase_config
),
"focus": project_template['focus'],
"detail_level": team_config['detail_level'],
"tech_customization": self._get_tech_customization(),
"modular_recommended": self.recommend_modular_structure()
}
def _select_sections(self, base_sections: List[str], phase_config: Dict[str, Any]) -> List[str]:
"""
Select sections based on phase and priorities.
Args:
base_sections: List of base section names
phase_config: Phase configuration dictionary
Returns:
Filtered list of sections
"""
skip_sections = phase_config.get('skip_sections', [])
return [section for section in base_sections if section not in skip_sections]
def _get_tech_customization(self) -> Dict[str, Any]:
"""
Get tech stack-specific customizations.
Returns:
Tech customization configuration
"""
customizations = {
"languages": [],
"frameworks": [],
"tools": [],
"specific_guidelines": []
}
# Detect languages
lang_map = {
'typescript': 'TypeScript',
'javascript': 'JavaScript',
'python': 'Python',
'go': 'Go',
'rust': 'Rust',
'java': 'Java',
'kotlin': 'Kotlin',
'ruby': 'Ruby',
'php': 'PHP'
}
for tech in self.tech_stack:
tech_lower = tech.lower()
if tech_lower in lang_map:
customizations['languages'].append(lang_map[tech_lower])
# Detect frameworks
framework_map = {
'react': 'React',
'vue': 'Vue',
'angular': 'Angular',
'svelte': 'Svelte',
'next.js': 'Next.js',
'django': 'Django',
'fastapi': 'FastAPI',
'flask': 'Flask',
'express': 'Express',
'gin': 'Gin',
'echo': 'Echo',
'spring': 'Spring Boot',
'rails': 'Rails'
}
for tech in self.tech_stack:
tech_lower = tech.lower()
if tech_lower in framework_map:
customizations['frameworks'].append(framework_map[tech_lower])
# Detect tools
tool_map = {
'docker': 'Docker',
'kubernetes': 'Kubernetes',
'postgresql': 'PostgreSQL',
'mongodb': 'MongoDB',
'redis': 'Redis',
'git': 'Git',
'github': 'GitHub',
'gitlab': 'GitLab'
}
for tech in self.tech_stack:
tech_lower = tech.lower()
if tech_lower in tool_map:
customizations['tools'].append(tool_map[tech_lower])
# Add specific guidelines based on tech stack
if 'typescript' in [t.lower() for t in self.tech_stack]:
customizations['specific_guidelines'].append(
"Use TypeScript strict mode throughout the project"
)
if 'react' in [t.lower() for t in self.tech_stack]:
customizations['specific_guidelines'].append(
"Prefer functional components with hooks over class components"
)
if 'python' in [t.lower() for t in self.tech_stack]:
customizations['specific_guidelines'].append(
"Use type hints for all function signatures (Python 3.10+)"
)
if 'docker' in [t.lower() for t in self.tech_stack]:
customizations['specific_guidelines'].append(
"Use multi-stage Dockerfiles for optimized image size"
)
return customizations
def recommend_modular_structure(self) -> bool:
"""
Determine if modular CLAUDE.md structure is recommended.
Returns:
True if modular structure recommended, False otherwise
"""
# Recommend modular structure for:
# 1. Full-stack projects
# 2. Large teams
# 3. Production/enterprise phase
# 4. Projects with 3+ major tech stack components
if self.project_type == 'fullstack':
return True
if self.team_size in ['medium', 'large']:
return True
if self.phase in ['production', 'enterprise']:
return True
if len(self.tech_stack) >= 3:
return True
# User explicitly requested modular
if self.modular:
return True
return False
def customize_template(self, template: Dict[str, Any]) -> str:
"""
Generate customized CLAUDE.md content based on template.
Args:
template: Template configuration dictionary
Returns:
Customized CLAUDE.md content as string
"""
lines = []
# Add title
lines.append("# CLAUDE.md")
lines.append("")
lines.append(f"This file provides guidance for Claude Code when working with this {self.project_type} project.")
lines.append("")
# Add modular navigation if recommended
if template.get('modular_recommended'):
lines.append("## Quick Navigation")
lines.append("")
lines.extend(self._generate_navigation_links())
lines.append("")
# Add core principles
lines.append("## Core Principles")
lines.append("")
lines.extend(self._generate_core_principles(template))
lines.append("")
# Add tech stack section
if self.tech_stack:
lines.append("## Tech Stack")
lines.append("")
lines.extend(self._generate_tech_stack_section(template))
lines.append("")
# Add workflow section if workflows specified
if self.workflows:
lines.append("## Workflow Instructions")
lines.append("")
lines.extend(self._generate_workflow_section())
lines.append("")
# Add additional sections based on template
for section in template['sections']:
if section not in ["Quick Navigation", "Core Principles", "Tech Stack", "Workflow Instructions"]:
lines.append(f"## {section}")
lines.append("")
lines.append(f"[Add {section.lower()} guidelines specific to your project]")
lines.append("")
return '\n'.join(lines)
def _generate_navigation_links(self) -> List[str]:
"""Generate navigation links for modular structure."""
links = []
if self.project_type == 'fullstack':
links.append("- [Backend Guidelines](backend/CLAUDE.md)")
links.append("- [Frontend Guidelines](frontend/CLAUDE.md)")
links.append("- [Database Operations](database/CLAUDE.md)")
if 'cicd' in self.workflows:
links.append("- [CI/CD Workflows](.github/CLAUDE.md)")
if not links:
links.append("- [Context-specific guides will be linked here]")
return links
def _generate_core_principles(self, template: Dict[str, Any]) -> List[str]:
"""Generate core principles based on template."""
principles = []
# Add workflow-specific principles
if 'tdd' in self.workflows:
principles.append("1. **Test-Driven Development**: Write tests before implementation")
# Add tech-specific principles
tech_custom = template.get('tech_customization', {})
for i, guideline in enumerate(tech_custom.get('specific_guidelines', [])[:3], start=len(principles)+1):
principles.append(f"{i}. **{guideline.split(':')[0] if ':' in guideline else 'Guideline'}**: {guideline}")
# Add generic principles if needed
if len(principles) < 3:
generic = [
"**Code Quality**: Maintain high code quality with clear, readable implementations",
"**Documentation**: Keep documentation in sync with code changes",
"**Error Handling**: Implement comprehensive error handling from the start"
]
for i, principle in enumerate(generic[:3-len(principles)], start=len(principles)+1):
principles.append(f"{i}. {principle}")
return principles
def _generate_tech_stack_section(self, template: Dict[str, Any]) -> List[str]:
"""Generate tech stack section."""
lines = []
tech_custom = template.get('tech_customization', {})
if tech_custom.get('languages'):
lines.append(f"- **Languages**: {', '.join(tech_custom['languages'])}")
if tech_custom.get('frameworks'):
lines.append(f"- **Frameworks**: {', '.join(tech_custom['frameworks'])}")
if tech_custom.get('tools'):
lines.append(f"- **Tools**: {', '.join(tech_custom['tools'])}")
if not lines:
lines.append("- [Add your tech stack details here]")
return lines
def _generate_workflow_section(self) -> List[str]:
"""Generate workflow section based on specified workflows."""
lines = []
workflow_descriptions = {
'tdd': "1. **Test-Driven Development**: Write tests first, then implement features to pass tests",
'cicd': "2. **CI/CD**: All changes go through automated testing and deployment pipelines",
'documentation_first': "3. **Documentation First**: Document APIs and interfaces before implementation",
'agile': "4. **Agile Process**: Work in sprints with regular retrospectives and planning"
}
for i, workflow in enumerate(self.workflows, start=1):
if workflow in workflow_descriptions:
lines.append(workflow_descriptions[workflow])
else:
lines.append(f"{i}. **{workflow.replace('_', ' ').title()}**: [Add workflow description]")
return lines
def determine_complexity(self) -> str:
"""
Determine appropriate complexity level for the template.
Returns:
Complexity level: 'minimal', 'core', 'detailed', or 'comprehensive'
"""
team_config = self.TEAM_SIZE_TEMPLATES.get(self.team_size, self.TEAM_SIZE_TEMPLATES['small'])
return team_config['complexity']
+429
View File
@@ -0,0 +1,429 @@
"""
CLAUDE.md Best Practices Validator
Validates CLAUDE.md files against Anthropic guidelines and community best practices.
Provides detailed validation reports with pass/fail status and improvement suggestions.
"""
from typing import Dict, List, Any, Tuple
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
# Minimum content requirements
MIN_LINES = 20
MIN_SECTIONS = 3
# Required sections for a complete CLAUDE.md
REQUIRED_SECTIONS = [
"Core Principles",
"Workflow"
]
# Anti-patterns to detect
ANTI_PATTERNS = [
{
"name": "hardcoded_secrets",
"patterns": [
r'api[_-]?key\s*=\s*["\'][a-zA-Z0-9]{20,}["\']',
r'password\s*=\s*["\'][^"\']+["\']',
r'secret\s*=\s*["\'][^"\']+["\']',
r'token\s*=\s*["\'][a-zA-Z0-9]{20,}["\']'
],
"message": "Potential hardcoded secrets detected (API keys, passwords, tokens)"
},
{
"name": "generic_content",
"patterns": [
r'\[TODO\]',
r'\[TBD\]',
r'\[PLACEHOLDER\]',
r'\[Insert.*?\]',
r'\[Add.*?\]'
],
"message": "Generic placeholder content found - replace with specific guidance"
},
{
"name": "duplicate_sections",
"patterns": [],
"message": "Duplicate section headings detected"
},
{
"name": "broken_links",
"patterns": [
r'\[.*?\]\(\)',
r'\[.*?\]\(#\)',
r'\[.*?\]\(undefined\)'
],
"message": "Broken or empty markdown links detected"
}
]
def __init__(self, content: str, project_context: Dict[str, Any] = None):
"""
Initialize validator with CLAUDE.md content.
Args:
content: Full text content of CLAUDE.md file
project_context: Optional project context for advanced validation
"""
self.content = content
self.lines = content.split('\n')
self.line_count = len(self.lines)
self.project_context = project_context or {}
def validate_all(self) -> Dict[str, Any]:
"""
Run all validation checks.
Returns:
Comprehensive validation report
"""
return {
"valid": self._is_valid_overall(),
"validation_results": {
"length": self.validate_length(),
"structure": self.validate_structure(),
"formatting": self.validate_formatting(),
"completeness": self.validate_completeness(),
"anti_patterns": self._check_anti_patterns()
},
"errors": self._collect_errors(),
"warnings": self._collect_warnings(),
"pass_count": self._count_passes(),
"fail_count": self._count_failures()
}
def validate_length(self) -> Dict[str, Any]:
"""
Validate file length against best practices.
Returns:
Validation result for length check
"""
status = "pass"
message = f"File length is appropriate ({self.line_count} lines)"
severity = "info"
if self.line_count > self.MAX_RECOMMENDED_LINES:
status = "fail"
message = f"File exceeds maximum recommended length ({self.line_count} > {self.MAX_RECOMMENDED_LINES} lines)"
severity = "high"
elif self.line_count > self.WARNING_THRESHOLD_LINES:
status = "warning"
message = f"File is approaching maximum length ({self.line_count} lines, recommended < {self.WARNING_THRESHOLD_LINES})"
severity = "medium"
elif self.line_count < self.MIN_LINES:
status = "fail"
message = f"File is too short ({self.line_count} lines, minimum {self.MIN_LINES})"
severity = "high"
return {
"check": "file_length",
"status": status,
"message": message,
"severity": severity,
"actual_value": self.line_count,
"expected_range": f"{self.MIN_LINES}-{self.MAX_RECOMMENDED_LINES} lines"
}
def validate_structure(self) -> Dict[str, Any]:
"""
Validate file structure and organization.
Returns:
Validation result for structure check
"""
sections = self._extract_sections()
errors = []
warnings = []
# Check for main title
if not self.content.strip().startswith('# '):
errors.append("Missing main title (# CLAUDE.md)")
# Check for minimum sections
if len(sections) < self.MIN_SECTIONS:
errors.append(f"Too few sections ({len(sections)}, minimum {self.MIN_SECTIONS})")
# Check for required sections
for required in self.REQUIRED_SECTIONS:
if not any(required.lower() in section.lower() for section in sections):
errors.append(f"Missing required section: '{required}'")
# Check for duplicate sections
section_counts = {}
for section in sections:
section_lower = section.lower()
section_counts[section_lower] = section_counts.get(section_lower, 0) + 1
duplicates = [s for s, count in section_counts.items() if count > 1]
if duplicates:
warnings.append(f"Duplicate sections found: {', '.join(duplicates)}")
# Determine overall status
status = "pass"
if errors:
status = "fail"
elif warnings:
status = "warning"
return {
"check": "file_structure",
"status": status,
"message": "Structure validation complete",
"severity": "high" if errors else "medium" if warnings else "info",
"errors": errors,
"warnings": warnings,
"sections_found": len(sections)
}
def validate_formatting(self) -> Dict[str, Any]:
"""
Validate markdown formatting quality.
Returns:
Validation result for formatting check
"""
errors = []
warnings = []
# Check for balanced code blocks
code_block_count = self.content.count('```')
if code_block_count % 2 != 0:
errors.append("Unbalanced code blocks (unclosed ``` markers)")
# Check for proper heading hierarchy
heading_levels = []
for line in self.lines:
if line.startswith('#'):
level = len(line) - len(line.lstrip('#'))
heading_levels.append(level)
if heading_levels and heading_levels[0] != 1:
errors.append("First heading should be level 1 (# Title)")
# Check for heading level skipping (e.g., # → ###)
for i in range(len(heading_levels) - 1):
if heading_levels[i+1] - heading_levels[i] > 1:
warnings.append(f"Heading level skips detected (h{heading_levels[i]} → h{heading_levels[i+1]})")
break
# Check for consistent list formatting
if '- ' in self.content and '* ' in self.content:
warnings.append("Mixed list markers (- and *) - prefer consistent style")
# Check for trailing whitespace (sample check)
lines_with_trailing_ws = sum(1 for line in self.lines if line.endswith(' ') and line.strip())
if lines_with_trailing_ws > 5:
warnings.append(f"Multiple lines with trailing whitespace ({lines_with_trailing_ws})")
status = "pass"
if errors:
status = "fail"
elif warnings:
status = "warning"
return {
"check": "markdown_formatting",
"status": status,
"message": "Formatting validation complete",
"severity": "medium" if errors else "low",
"errors": errors,
"warnings": warnings
}
def validate_completeness(self) -> Dict[str, Any]:
"""
Validate content completeness and quality.
Returns:
Validation result for completeness check
"""
errors = []
warnings = []
# Check for essential content types
has_code_examples = '```' in self.content
has_links = '[' in self.content and '](' in self.content
has_lists = any(line.strip().startswith(('-', '*', '1.')) for line in self.lines)
if not has_code_examples:
warnings.append("No code examples found - consider adding examples for clarity")
if not has_links:
warnings.append("No links found - consider linking to external documentation")
if not has_lists:
warnings.append("No lists found - consider using lists for better readability")
# Check for tech stack mention
tech_keywords = [
'typescript', 'javascript', 'python', 'react', 'vue', 'angular',
'node', 'django', 'fastapi', 'go', 'rust', 'java'
]
content_lower = self.content.lower()
tech_mentioned = any(keyword in content_lower for keyword in tech_keywords)
if not tech_mentioned:
warnings.append("No specific technologies mentioned - add tech stack reference")
# Check for workflow mentions
workflow_keywords = ['test', 'commit', 'deploy', 'review', 'documentation']
workflow_mentioned = sum(1 for keyword in workflow_keywords if keyword in content_lower)
if workflow_mentioned < 2:
warnings.append("Limited workflow guidance - consider adding development workflow instructions")
# Check for empty sections
empty_section_pattern = r'##\s+[^\n]+\n\s*\n\s*##'
if re.search(empty_section_pattern, self.content):
errors.append("Empty sections detected - remove or populate with content")
status = "pass"
if errors:
status = "fail"
elif len(warnings) >= 3:
status = "warning"
return {
"check": "content_completeness",
"status": status,
"message": "Completeness validation complete",
"severity": "medium",
"errors": errors,
"warnings": warnings,
"has_code_examples": has_code_examples,
"has_links": has_links,
"has_lists": has_lists,
"tech_stack_mentioned": tech_mentioned
}
def _check_anti_patterns(self) -> Dict[str, Any]:
"""
Check for anti-patterns and bad practices.
Returns:
Validation result for anti-pattern detection
"""
detected = []
for anti_pattern in self.ANTI_PATTERNS:
if anti_pattern['name'] == 'duplicate_sections':
# Handle duplicate sections separately
sections = self._extract_sections()
section_counts = {}
for section in sections:
section_lower = section.lower()
section_counts[section_lower] = section_counts.get(section_lower, 0) + 1
if any(count > 1 for count in section_counts.values()):
detected.append({
"pattern": anti_pattern['name'],
"message": anti_pattern['message']
})
else:
# Check regex patterns
for pattern in anti_pattern['patterns']:
if re.search(pattern, self.content, re.IGNORECASE):
detected.append({
"pattern": anti_pattern['name'],
"message": anti_pattern['message']
})
break # Only report each anti-pattern once
status = "pass" if not detected else "fail"
severity = "high" if any(p['pattern'] == 'hardcoded_secrets' for p in detected) else "medium"
return {
"check": "anti_patterns",
"status": status,
"message": f"{len(detected)} anti-pattern(s) detected" if detected else "No anti-patterns detected",
"severity": severity,
"detected_patterns": detected
}
def _extract_sections(self) -> List[str]:
"""Extract all section headings from content."""
sections = []
for line in self.lines:
if line.startswith('## '):
sections.append(line[3:].strip())
return sections
def _is_valid_overall(self) -> bool:
"""Determine if file passes overall validation."""
length_result = self.validate_length()
structure_result = self.validate_structure()
# File is valid if length and structure pass (formatting and completeness can have warnings)
return (
length_result['status'] != 'fail' and
structure_result['status'] != 'fail'
)
def _collect_errors(self) -> List[str]:
"""Collect all errors from validation checks."""
errors = []
all_results = [
self.validate_length(),
self.validate_structure(),
self.validate_formatting(),
self.validate_completeness(),
self._check_anti_patterns()
]
for result in all_results:
if result['status'] == 'fail':
if 'errors' in result:
errors.extend(result['errors'])
else:
errors.append(result['message'])
return errors
def _collect_warnings(self) -> List[str]:
"""Collect all warnings from validation checks."""
warnings = []
all_results = [
self.validate_length(),
self.validate_structure(),
self.validate_formatting(),
self.validate_completeness()
]
for result in all_results:
if 'warnings' in result:
warnings.extend(result['warnings'])
elif result['status'] == 'warning':
warnings.append(result['message'])
return warnings
def _count_passes(self) -> int:
"""Count number of passed checks."""
all_results = [
self.validate_length(),
self.validate_structure(),
self.validate_formatting(),
self.validate_completeness(),
self._check_anti_patterns()
]
return sum(1 for result in all_results if result['status'] == 'pass')
def _count_failures(self) -> int:
"""Count number of failed checks."""
all_results = [
self.validate_length(),
self.validate_structure(),
self.validate_formatting(),
self.validate_completeness(),
self._check_anti_patterns()
]
return sum(1 for result in all_results if result['status'] == 'fail')
+432
View File
@@ -0,0 +1,432 @@
"""
CLAUDE.md Initialization Workflow
Handles the complete workflow for initializing CLAUDE.md in a new project:
1. Explore repository to understand codebase
2. Detect project type, tech stack, and structure
3. Ask user for confirmation
4. Create initial CLAUDE.md file
5. Enhance with best practices
This workflow is interactive and conversational - user must confirm each step.
CRITICAL VALIDATION RULE:
"Always validate your output against official native examples before declaring complete."
Before finalizing CLAUDE.md generation:
- Compare output against `/update-claude-md` slash command format
- Verify all native format sections are present (Overview, Project Structure,
File Structure, Setup & Installation, Architecture, etc.)
- Cross-check against reference examples in examples/ folder
"""
from typing import Dict, List, Any, Optional
from pathlib import Path
import json
class InitializationWorkflow:
"""Manages the interactive initialization workflow for CLAUDE.md creation."""
def __init__(self, project_path: str = "."):
"""
Initialize workflow with project path.
Args:
project_path: Path to project directory (default: current directory)
"""
self.project_path = Path(project_path)
self.discoveries = {}
self.user_confirmations = {}
def check_claude_md_exists(self) -> bool:
"""
Check if CLAUDE.md already exists in project.
Returns:
True if CLAUDE.md exists, False otherwise
"""
claude_md_path = self.project_path / "CLAUDE.md"
return claude_md_path.exists()
def generate_exploration_prompt(self) -> str:
"""
Generate prompt to guide Claude to explore the repository.
Returns:
Exploration prompt string for Claude to execute
"""
return """I'll explore this repository to understand the codebase before creating a CLAUDE.md file.
Let me examine:
1. Project structure and key directories
2. Technology stack (package.json, requirements.txt, go.mod, etc.)
3. Existing documentation (README.md, docs/)
4. Development workflows (GitHub Actions, scripts/, Makefile)
5. Testing setup
6. Build configuration
Exploring repository now..."""
def analyze_discoveries(self, exploration_results: Dict[str, Any]) -> Dict[str, Any]:
"""
Analyze repository exploration results to determine project context.
Args:
exploration_results: Results from repository exploration
Returns:
Analyzed project context
"""
context = {
"project_type": self._detect_project_type(exploration_results),
"tech_stack": self._detect_tech_stack(exploration_results),
"team_size": self._estimate_team_size(exploration_results),
"phase": self._detect_development_phase(exploration_results),
"workflows": self._detect_workflows(exploration_results),
"structure": self._analyze_structure(exploration_results),
"modular_recommended": self._should_use_modular(exploration_results)
}
self.discoveries = context
return context
def _detect_project_type(self, results: Dict[str, Any]) -> str:
"""Detect project type from exploration results."""
# Check for common project type indicators
files = results.get('files', [])
directories = results.get('directories', [])
# Full-stack indicators
if ('frontend' in directories or 'client' in directories) and \
('backend' in directories or 'server' in directories or 'api' in directories):
return "fullstack"
# Frontend indicators
if any(f in files for f in ['package.json']) and \
any(d in directories for d in ['src/components', 'components', 'pages']):
return "web_app"
# Backend API indicators
if any(f in files for f in ['requirements.txt', 'go.mod', 'Cargo.toml']):
if any(d in directories for d in ['api', 'routes', 'controllers']):
return "api"
# CLI indicators
if any(d in directories for d in ['cmd', 'cli', 'bin']):
return "cli"
# Library indicators
if any(f in files for f in ['setup.py', 'pyproject.toml', 'Cargo.toml']) and \
'examples' in directories:
return "library"
# Mobile indicators
if any(f in files for f in ['app.json', 'ios', 'android']):
return "mobile"
# Default to web app
return "web_app"
def _detect_tech_stack(self, results: Dict[str, Any]) -> List[str]:
"""Detect technologies used in the project."""
tech_stack = []
files = results.get('files', [])
content = results.get('file_contents', {})
# JavaScript/TypeScript
if 'package.json' in files:
pkg_json = content.get('package.json', {})
dependencies = pkg_json.get('dependencies', {})
if 'typescript' in dependencies or any('typescript' in f for f in files):
tech_stack.append('typescript')
else:
tech_stack.append('javascript')
# Frameworks
if 'react' in dependencies:
tech_stack.append('react')
if 'vue' in dependencies:
tech_stack.append('vue')
if 'angular' in dependencies or '@angular/core' in dependencies:
tech_stack.append('angular')
if 'next' in dependencies:
tech_stack.append('next.js')
if 'express' in dependencies:
tech_stack.append('express')
# Python
if any(f in files for f in ['requirements.txt', 'pyproject.toml', 'setup.py']):
tech_stack.append('python')
req_content = content.get('requirements.txt', '')
if 'fastapi' in req_content.lower():
tech_stack.append('fastapi')
elif 'django' in req_content.lower():
tech_stack.append('django')
elif 'flask' in req_content.lower():
tech_stack.append('flask')
# Go
if 'go.mod' in files:
tech_stack.append('go')
go_mod = content.get('go.mod', '')
if 'gin-gonic/gin' in go_mod:
tech_stack.append('gin')
if 'echo' in go_mod:
tech_stack.append('echo')
# Databases
if any('postgres' in f.lower() for f in files):
tech_stack.append('postgresql')
if any('mongo' in f.lower() for f in files):
tech_stack.append('mongodb')
if any('redis' in f.lower() for f in files):
tech_stack.append('redis')
# Infrastructure
if 'Dockerfile' in files or 'docker-compose.yml' in files:
tech_stack.append('docker')
if any('k8s' in d for d in results.get('directories', [])) or \
any('kubernetes' in f.lower() for f in files):
tech_stack.append('kubernetes')
return tech_stack
def _estimate_team_size(self, results: Dict[str, Any]) -> str:
"""Estimate team size based on project complexity."""
directories = results.get('directories', [])
files = results.get('files', [])
# Indicators of team size
complexity_score = 0
# File count indicator
if len(files) > 100:
complexity_score += 2
elif len(files) > 50:
complexity_score += 1
# Directory structure
if len(directories) > 20:
complexity_score += 2
elif len(directories) > 10:
complexity_score += 1
# CI/CD presence (indicates larger team)
if any('.github/workflows' in str(d) for d in directories):
complexity_score += 1
# Documentation (larger teams document more)
if 'docs' in directories or any('documentation' in d for d in directories):
complexity_score += 1
# Determine team size
if complexity_score >= 5:
return "large"
elif complexity_score >= 3:
return "medium"
elif complexity_score >= 1:
return "small"
else:
return "solo"
def _detect_development_phase(self, results: Dict[str, Any]) -> str:
"""Detect development phase based on project maturity."""
files = results.get('files', [])
directories = results.get('directories', [])
# Production indicators
production_indicators = [
'Dockerfile' in files,
'docker-compose.yml' in files,
any('.github/workflows' in str(d) for d in directories),
'CHANGELOG.md' in files,
any('deploy' in f.lower() for f in files)
]
if sum(production_indicators) >= 3:
return "production"
elif sum(production_indicators) >= 2:
return "mvp"
else:
return "prototype"
def _detect_workflows(self, results: Dict[str, Any]) -> List[str]:
"""Detect development workflows in use."""
workflows = []
files = results.get('files', [])
directories = results.get('directories', [])
# TDD indicators
if any('test' in d for d in directories) or \
any('test' in f for f in files):
workflows.append('tdd')
# CI/CD indicators
if any('.github/workflows' in str(d) for d in directories) or \
'.gitlab-ci.yml' in files or \
'Jenkinsfile' in files:
workflows.append('cicd')
# Documentation-first indicators
if 'docs' in directories or \
any('documentation' in d for d in directories):
workflows.append('documentation_first')
return workflows
def _analyze_structure(self, results: Dict[str, Any]) -> Dict[str, Any]:
"""Analyze project structure."""
directories = results.get('directories', [])
return {
"has_frontend": any(d in directories for d in ['frontend', 'client', 'src/components']),
"has_backend": any(d in directories for d in ['backend', 'server', 'api']),
"has_database": any(d in directories for d in ['database', 'db', 'migrations']),
"has_tests": any('test' in d for d in directories),
"has_docs": 'docs' in directories or any('documentation' in d for d in directories),
"has_ci": any('.github' in str(d) for d in directories)
}
def _should_use_modular(self, results: Dict[str, Any]) -> bool:
"""Determine if modular CLAUDE.md structure is recommended."""
structure = self._analyze_structure(results)
# Recommend modular if:
# - Has separate frontend and backend
# - Large number of directories (>15)
# - Medium/large team size
return (
(structure['has_frontend'] and structure['has_backend']) or
len(results.get('directories', [])) > 15 or
self._estimate_team_size(results) in ['medium', 'large']
)
def generate_confirmation_prompt(self, context: Dict[str, Any]) -> str:
"""
Generate confirmation prompt to show user the discoveries.
Args:
context: Analyzed project context
Returns:
Confirmation prompt string
"""
tech_stack_str = ", ".join(context['tech_stack'][:5])
if len(context['tech_stack']) > 5:
tech_stack_str += f" (+{len(context['tech_stack']) - 5} more)"
prompt = f"""Based on my exploration, here's what I discovered:
**Project Type**: {context['project_type'].replace('_', ' ').title()}
**Tech Stack**: {tech_stack_str}
**Team Size**: {context['team_size'].title()} ({self._get_team_size_range(context['team_size'])})
**Development Phase**: {context['phase'].title()}
**Workflows**: {', '.join(context['workflows']) if context['workflows'] else 'Standard development'}
**Recommended Structure**:
{"Modular architecture (separate CLAUDE.md files for major components)" if context['modular_recommended'] else "Single CLAUDE.md file (appropriate for project size)"}
Would you like me to create a CLAUDE.md file based on these discoveries?
I can:
1. Generate a customized CLAUDE.md tailored to your tech stack
2. Include appropriate sections for your team size and phase
3. {"Create modular files (backend/CLAUDE.md, frontend/CLAUDE.md, etc.)" if context['modular_recommended'] else "Focus on essential guidelines"}
Please confirm to proceed, or let me know if you'd like to adjust any of these settings."""
return prompt
def _get_team_size_range(self, team_size: str) -> str:
"""Get human-readable team size range."""
ranges = {
"solo": "1 developer",
"small": "2-9 developers",
"medium": "10-49 developers",
"large": "50+ developers"
}
return ranges.get(team_size, "Unknown")
def generate_initialization_summary(self, created_files: List[str]) -> str:
"""
Generate summary of initialization process.
Args:
created_files: List of files created during initialization
Returns:
Summary string
"""
summary = f"""✅ CLAUDE.md Initialization Complete!
**Created Files** ({len(created_files)}):
"""
for file in created_files:
summary += f"- {file}\n"
summary += """
**Next Steps**:
1. Review the generated CLAUDE.md file
2. Customize for your specific needs
3. Add team-specific conventions
4. Update as your project evolves
Your project is now set up for efficient AI-assisted development with Claude Code!
"""
return summary
def get_workflow_steps(self) -> List[Dict[str, str]]:
"""
Get the complete workflow steps for initialization.
Returns:
List of workflow steps with descriptions
"""
return [
{
"step": 1,
"name": "Check for existing CLAUDE.md",
"description": "Verify if CLAUDE.md already exists in project",
"action": "check_claude_md_exists"
},
{
"step": 2,
"name": "Explore repository",
"description": "Analyze project structure, tech stack, and workflows using Claude Code's built-in explore capability",
"action": "generate_exploration_prompt"
},
{
"step": 3,
"name": "Analyze discoveries",
"description": "Detect project type, tech stack, team size, and recommend structure",
"action": "analyze_discoveries"
},
{
"step": 4,
"name": "Request user confirmation",
"description": "Show discoveries and ask user to confirm CLAUDE.md creation",
"action": "generate_confirmation_prompt"
},
{
"step": 5,
"name": "Create CLAUDE.md file(s)",
"description": "Generate customized CLAUDE.md based on confirmed context",
"action": "create_files"
},
{
"step": 6,
"name": "Enhance with best practices",
"description": "Apply additional enhancements and validate quality",
"action": "enhance_files"
},
{
"step": 7,
"name": "Provide summary",
"description": "Show what was created and next steps",
"action": "generate_initialization_summary"
}
]