From 37422c1667091d90b66a1cbf396b61fcc07e80e4 Mon Sep 17 00:00:00 2001 From: Reza Rezvani Date: Wed, 12 Nov 2025 11:19:48 +0100 Subject: [PATCH] Initial commit: ClaudeForge v1.0.0 --- .github/CODE_OF_CONDUCT.md | 129 +++++ .github/ISSUE_TEMPLATE/bug_report.md | 47 ++ .github/ISSUE_TEMPLATE/feature_request.md | 48 ++ .github/PULL_REQUEST_TEMPLATE.md | 58 +++ .github/workflows/validate.yml | 162 +++++++ .gitignore | 87 ++++ CHANGELOG.md | 211 +++++++++ CLAUDE.md | 469 ++++++++++++++++++ LICENSE | 21 + README.md | 278 +++++++++++ agent/README.md | 405 ++++++++++++++++ agent/claude-md-guardian.md | 317 +++++++++++++ command/README.md | 390 +++++++++++++++ command/enhance-claude-md.md | 99 ++++ docs/ARCHITECTURE.md | 548 +++++++++++++++++++++ docs/CONTRIBUTING.md | 490 +++++++++++++++++++ docs/INSTALLATION.md | 412 ++++++++++++++++ docs/QUICK_START.md | 407 ++++++++++++++++ docs/TROUBLESHOOTING.md | 551 ++++++++++++++++++++++ examples/basic-usage.md | 152 ++++++ examples/integration-examples.md | 142 ++++++ examples/modular-setup.md | 175 +++++++ hooks/pre-commit.sh | 156 ++++++ install.ps1 | 236 +++++++++ install.sh | 213 +++++++++ skill/HOW_TO_USE.md | 383 +++++++++++++++ skill/README.md | 542 +++++++++++++++++++++ skill/SKILL.md | 446 +++++++++++++++++ skill/analyzer.py | 382 +++++++++++++++ skill/examples/README.md | 138 ++++++ skill/examples/core-small-team-CLAUDE.md | 183 +++++++ skill/examples/minimal-solo-CLAUDE.md | 80 ++++ skill/examples/modular-backend-CLAUDE.md | 345 ++++++++++++++ skill/examples/modular-frontend-CLAUDE.md | 385 +++++++++++++++ skill/examples/modular-root-CLAUDE.md | 192 ++++++++ skill/examples/python-api-CLAUDE.md | 461 ++++++++++++++++++ skill/expected_output.json | 155 ++++++ skill/generator.py | 480 +++++++++++++++++++ skill/sample_input.json | 109 +++++ skill/template_selector.py | 467 ++++++++++++++++++ skill/validator.py | 429 +++++++++++++++++ skill/workflow.py | 432 +++++++++++++++++ 42 files changed, 11812 insertions(+) create mode 100644 .github/CODE_OF_CONDUCT.md create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/workflows/validate.yml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CLAUDE.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 agent/README.md create mode 100644 agent/claude-md-guardian.md create mode 100644 command/README.md create mode 100644 command/enhance-claude-md.md create mode 100644 docs/ARCHITECTURE.md create mode 100644 docs/CONTRIBUTING.md create mode 100644 docs/INSTALLATION.md create mode 100644 docs/QUICK_START.md create mode 100644 docs/TROUBLESHOOTING.md create mode 100644 examples/basic-usage.md create mode 100644 examples/integration-examples.md create mode 100644 examples/modular-setup.md create mode 100755 hooks/pre-commit.sh create mode 100644 install.ps1 create mode 100755 install.sh create mode 100644 skill/HOW_TO_USE.md create mode 100644 skill/README.md create mode 100644 skill/SKILL.md create mode 100644 skill/analyzer.py create mode 100644 skill/examples/README.md create mode 100644 skill/examples/core-small-team-CLAUDE.md create mode 100644 skill/examples/minimal-solo-CLAUDE.md create mode 100644 skill/examples/modular-backend-CLAUDE.md create mode 100644 skill/examples/modular-frontend-CLAUDE.md create mode 100644 skill/examples/modular-root-CLAUDE.md create mode 100644 skill/examples/python-api-CLAUDE.md create mode 100644 skill/expected_output.json create mode 100644 skill/generator.py create mode 100644 skill/sample_input.json create mode 100644 skill/template_selector.py create mode 100644 skill/validator.py create mode 100644 skill/workflow.py diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..1761270 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -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. diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..54db43e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -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. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..47e5bfe --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -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 diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..51409cb --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -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. diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml new file mode 100644 index 0000000..00e8586 --- /dev/null +++ b/.github/workflows/validate.yml @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7ed86e6 --- /dev/null +++ b/.gitignore @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ab816ad --- /dev/null +++ b/CHANGELOG.md @@ -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** diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..be2a7bc --- /dev/null +++ b/CLAUDE.md @@ -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. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c3e30bc --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2b9cc82 --- /dev/null +++ b/README.md @@ -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) + +--- + +
+ +**[⬆ Back to Top](#claudeforge)** + +Made with ❤️ for the Claude Code community + +
diff --git a/agent/README.md b/agent/README.md new file mode 100644 index 0000000..7929b75 --- /dev/null +++ b/agent/README.md @@ -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! diff --git a/agent/claude-md-guardian.md b/agent/claude-md-guardian.md new file mode 100644 index 0000000..6ead7ff --- /dev/null +++ b/agent/claude-md-guardian.md @@ -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. diff --git a/command/README.md b/command/README.md new file mode 100644 index 0000000..3f58bc4 --- /dev/null +++ b/command/README.md @@ -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! diff --git a/command/enhance-claude-md.md b/command/enhance-claude-md.md new file mode 100644 index 0000000..f6b771b --- /dev/null +++ b/command/enhance-claude-md.md @@ -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"). diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..e9b7bc8 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -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 diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md new file mode 100644 index 0000000..e3bd1af --- /dev/null +++ b/docs/CONTRIBUTING.md @@ -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. diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md new file mode 100644 index 0000000..fd4ad6e --- /dev/null +++ b/docs/INSTALLATION.md @@ -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) → diff --git a/docs/QUICK_START.md b/docs/QUICK_START.md new file mode 100644 index 0000000..e4016f5 --- /dev/null +++ b/docs/QUICK_START.md @@ -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! 🚀** diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md new file mode 100644 index 0000000..871915a --- /dev/null +++ b/docs/TROUBLESHOOTING.md @@ -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 diff --git a/examples/basic-usage.md b/examples/basic-usage.md new file mode 100644 index 0000000..d845d58 --- /dev/null +++ b/examples/basic-usage.md @@ -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 diff --git a/examples/integration-examples.md b/examples/integration-examples.md new file mode 100644 index 0000000..75a54e2 --- /dev/null +++ b/examples/integration-examples.md @@ -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) diff --git a/examples/modular-setup.md b/examples/modular-setup.md new file mode 100644 index 0000000..c46ab00 --- /dev/null +++ b/examples/modular-setup.md @@ -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 diff --git a/hooks/pre-commit.sh b/hooks/pre-commit.sh new file mode 100755 index 0000000..f6369e0 --- /dev/null +++ b/hooks/pre-commit.sh @@ -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 diff --git a/install.ps1 b/install.ps1 new file mode 100644 index 0000000..135ebd6 --- /dev/null +++ b/install.ps1 @@ -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 "" diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..f78a4cb --- /dev/null +++ b/install.sh @@ -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 "" diff --git a/skill/HOW_TO_USE.md b/skill/HOW_TO_USE.md new file mode 100644 index 0000000..dc89d56 --- /dev/null +++ b/skill/HOW_TO_USE.md @@ -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! diff --git a/skill/README.md b/skill/README.md new file mode 100644 index 0000000..f5784e2 --- /dev/null +++ b/skill/README.md @@ -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! + diff --git a/skill/SKILL.md b/skill/SKILL.md new file mode 100644 index 0000000..5052d0a --- /dev/null +++ b/skill/SKILL.md @@ -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. diff --git a/skill/analyzer.py b/skill/analyzer.py new file mode 100644 index 0000000..39c3c8a --- /dev/null +++ b/skill/analyzer.py @@ -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 diff --git a/skill/examples/README.md b/skill/examples/README.md new file mode 100644 index 0000000..d5c203d --- /dev/null +++ b/skill/examples/README.md @@ -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! diff --git a/skill/examples/core-small-team-CLAUDE.md b/skill/examples/core-small-team-CLAUDE.md new file mode 100644 index 0000000..2d2c73f --- /dev/null +++ b/skill/examples/core-small-team-CLAUDE.md @@ -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) diff --git a/skill/examples/minimal-solo-CLAUDE.md b/skill/examples/minimal-solo-CLAUDE.md new file mode 100644 index 0000000..623c55c --- /dev/null +++ b/skill/examples/minimal-solo-CLAUDE.md @@ -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) diff --git a/skill/examples/modular-backend-CLAUDE.md b/skill/examples/modular-backend-CLAUDE.md new file mode 100644 index 0000000..badb38c --- /dev/null +++ b/skill/examples/modular-backend-CLAUDE.md @@ -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) diff --git a/skill/examples/modular-frontend-CLAUDE.md b/skill/examples/modular-frontend-CLAUDE.md new file mode 100644 index 0000000..df4eda6 --- /dev/null +++ b/skill/examples/modular-frontend-CLAUDE.md @@ -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 ; + if (error) return ; + + // 4. Main render + return
{/* component JSX */}
; +} +``` + +### 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(); + 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 (`