mirror of
https://github.com/alirezarezvani/ClaudeForge.git
synced 2026-07-03 02:13:15 -04:00
Initial commit: ClaudeForge v1.0.0
This commit is contained in:
@@ -0,0 +1,383 @@
|
||||
# How to Use the claude-md-enhancer Skill
|
||||
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Can you help me create or improve my project's CLAUDE.md file?
|
||||
|
||||
## Example Invocations
|
||||
|
||||
### Example 1: Initialize CLAUDE.md for New Project (🆕 Interactive Workflow)
|
||||
|
||||
**Use Case**: You don't have a CLAUDE.md file yet and want Claude to create one by understanding your project first.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. I don't have a CLAUDE.md file yet. Can you help me create one for this project?
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
1. Check if CLAUDE.md exists (it doesn't)
|
||||
2. Explore your repository using built-in commands
|
||||
3. Analyze project structure, tech stack, team size
|
||||
4. Show you the discoveries and ask for confirmation
|
||||
5. Create customized CLAUDE.md file(s) after your approval
|
||||
6. Enhance with best practices
|
||||
|
||||
**Interactive Conversation Example**:
|
||||
|
||||
```
|
||||
User: "I don't have a CLAUDE.md. Can you create one?"
|
||||
|
||||
Claude: "I'll explore your repository first to understand the project.
|
||||
|
||||
[Exploring repository structure...]
|
||||
[Analyzing package.json, requirements.txt, etc...]
|
||||
[Detecting workflows and patterns...]
|
||||
|
||||
Based on my exploration, here's what I discovered:
|
||||
|
||||
📦 **Project Type**: Full-Stack Application
|
||||
🛠️ **Tech Stack**: TypeScript, React, Node.js, PostgreSQL, Docker
|
||||
👥 **Team Size**: Small (5 developers detected from git history)
|
||||
🚀 **Development Phase**: MVP (CI/CD present, production features in progress)
|
||||
⚙️ **Workflows**: TDD (tests/ folder found), CI/CD (GitHub Actions detected)
|
||||
|
||||
📋 **Recommended Structure**:
|
||||
Modular architecture - I recommend creating:
|
||||
- Root CLAUDE.md (navigation hub, ~100 lines)
|
||||
- backend/CLAUDE.md (API and database guidelines, ~150 lines)
|
||||
- frontend/CLAUDE.md (React component guidelines, ~175 lines)
|
||||
|
||||
Would you like me to create these files with these settings?
|
||||
You can also ask me to adjust any of these if they don't look right."
|
||||
|
||||
User: "Yes, that looks perfect. Please proceed."
|
||||
|
||||
Claude: "Creating your customized CLAUDE.md files...
|
||||
|
||||
✅ Created CLAUDE.md (108 lines)
|
||||
- Quick Navigation section with links
|
||||
- 5 Core Principles (TDD-focused)
|
||||
- Tech Stack summary
|
||||
- Quick reference commands
|
||||
|
||||
✅ Created backend/CLAUDE.md (156 lines)
|
||||
- API Design guidelines (RESTful, versioning)
|
||||
- Database operations (migrations, queries)
|
||||
- Error handling patterns
|
||||
- Testing requirements (80% coverage)
|
||||
|
||||
✅ Created frontend/CLAUDE.md (182 lines)
|
||||
- React component standards (functional, hooks)
|
||||
- State management (Context API)
|
||||
- Styling guidelines (Tailwind)
|
||||
- Performance optimization
|
||||
|
||||
🎉 Your project is now set up for efficient AI-assisted development!
|
||||
|
||||
Next steps:
|
||||
1. Review the generated files
|
||||
2. Customize core principles for your team
|
||||
3. Add any project-specific conventions
|
||||
4. Start developing with Claude Code!"
|
||||
|
||||
User: "Perfect, thanks!"
|
||||
```
|
||||
|
||||
**When to Use This**:
|
||||
- New project without CLAUDE.md
|
||||
- Want Claude to understand your project first
|
||||
- Need recommendations on structure
|
||||
- Prefer interactive, conversational setup
|
||||
|
||||
---
|
||||
|
||||
### Example 2: Quick Initialization (Skip Exploration)
|
||||
|
||||
**Use Case**: You know your project details and want to skip the exploration step.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Create a CLAUDE.md for my TypeScript React project with PostgreSQL. Small team (5 devs), MVP phase, using TDD and CI/CD.
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
- Skip exploration (you provided context)
|
||||
- Generate CLAUDE.md immediately
|
||||
- Customize for specified tech stack
|
||||
- No confirmation needed (direct request)
|
||||
|
||||
---
|
||||
|
||||
### Example 3: Analyze Existing CLAUDE.md
|
||||
|
||||
**Use Case**: You have an existing CLAUDE.md file and want to know what's missing or could be improved.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Can you analyze my current CLAUDE.md file and tell me what's missing or could be improved? Here it is:
|
||||
|
||||
# CLAUDE.md
|
||||
|
||||
## Tech Stack
|
||||
- TypeScript
|
||||
- React
|
||||
- Node.js
|
||||
|
||||
## Workflow
|
||||
- Use Git for version control
|
||||
- Write tests
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
- Analyze file structure and completeness
|
||||
- Calculate quality score (0-100)
|
||||
- Identify missing sections
|
||||
- Provide actionable recommendations
|
||||
|
||||
---
|
||||
|
||||
### Example 2: Generate New CLAUDE.md for TypeScript React Project
|
||||
|
||||
**Use Case**: Starting a new TypeScript React project and need a CLAUDE.md file from scratch.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Can you create a CLAUDE.md file for my TypeScript React project? We're a team of 5 developers working on an MVP. We use PostgreSQL, Docker, and follow TDD practices.
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
- Generate complete CLAUDE.md tailored to TypeScript/React
|
||||
- Include tech stack references
|
||||
- Add TDD workflow guidelines
|
||||
- Customize for small team (5 people)
|
||||
- Include MVP-phase appropriate content
|
||||
|
||||
---
|
||||
|
||||
### Example 3: Enhance Existing File with Missing Sections
|
||||
|
||||
**Use Case**: You have a basic CLAUDE.md but it's missing important sections.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Can you enhance my existing CLAUDE.md by adding Testing Requirements, Error Handling Patterns, and Performance Guidelines sections? Here's what I have:
|
||||
|
||||
# CLAUDE.md
|
||||
|
||||
## Core Principles
|
||||
1. Write tests first
|
||||
2. Use TypeScript
|
||||
|
||||
## Tech Stack
|
||||
- TypeScript
|
||||
- React
|
||||
- PostgreSQL
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
- Preserve your existing content
|
||||
- Add the three requested sections
|
||||
- Populate sections with relevant best practices
|
||||
- Ensure consistency with your existing style
|
||||
|
||||
---
|
||||
|
||||
### Example 4: Generate Modular CLAUDE.md Architecture
|
||||
|
||||
**Use Case**: You have a complex full-stack project and want separate CLAUDE.md files for different parts.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Can you create a modular CLAUDE.md setup for my full-stack project? I need separate files for:
|
||||
- Backend (Python/FastAPI)
|
||||
- Frontend (React/TypeScript)
|
||||
- Database (PostgreSQL)
|
||||
|
||||
We're a team of 8, building a production system.
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
- Generate root CLAUDE.md (navigation hub)
|
||||
- Create backend/CLAUDE.md with API and service guidelines
|
||||
- Create frontend/CLAUDE.md with React component standards
|
||||
- Create database/CLAUDE.md with migration and query guidelines
|
||||
- Customize for medium team size and production phase
|
||||
|
||||
---
|
||||
|
||||
### Example 5: Validate Existing CLAUDE.md
|
||||
|
||||
**Use Case**: You want to check if your CLAUDE.md follows best practices.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Can you validate my CLAUDE.md file against best practices? Here it is: [paste your CLAUDE.md content]
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
- Check file length (warns if >300 lines)
|
||||
- Verify required sections are present
|
||||
- Check markdown formatting quality
|
||||
- Detect anti-patterns (hardcoded secrets, placeholders)
|
||||
- Provide pass/fail status with detailed feedback
|
||||
|
||||
---
|
||||
|
||||
### Example 6: Create CLAUDE.md for Python API Project
|
||||
|
||||
**Use Case**: Building a Python FastAPI backend service.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Can you create a CLAUDE.md for my Python FastAPI project? We're building a microservice API with PostgreSQL, Redis, and deploying with Docker/Kubernetes. Team of 12 developers, enterprise production environment.
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
- Generate API-focused CLAUDE.md
|
||||
- Include FastAPI-specific best practices
|
||||
- Add microservices architecture guidelines
|
||||
- Customize for large team (12 developers)
|
||||
- Include enterprise-grade standards
|
||||
|
||||
---
|
||||
|
||||
### Example 7: Add Specific Section to Existing File
|
||||
|
||||
**Use Case**: You need to add just one specific section.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Can you add a "Security Checklist" section to my existing CLAUDE.md?
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
- Generate Security Checklist section
|
||||
- Include relevant security best practices
|
||||
- Merge seamlessly with existing content
|
||||
- Maintain your file's existing structure
|
||||
|
||||
---
|
||||
|
||||
### Example 8: Convert Generic CLAUDE.md to Tech-Specific
|
||||
|
||||
**Use Case**: You have a generic CLAUDE.md and want to customize it for your tech stack.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. I have a generic CLAUDE.md file. Can you customize it for my Vue 3, Go (Gin), and MongoDB tech stack?
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
- Detect your current content
|
||||
- Add Vue 3-specific component guidelines
|
||||
- Add Go/Gin API patterns
|
||||
- Add MongoDB query optimization practices
|
||||
- Preserve your existing custom sections
|
||||
|
||||
---
|
||||
|
||||
### Example 9: Generate Context-Specific File Only
|
||||
|
||||
**Use Case**: You just need guidelines for one part of your project.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Can you create a backend/CLAUDE.md file for my Node.js Express API project?
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
- Generate backend-specific guidelines
|
||||
- Include Express.js patterns
|
||||
- Add API design best practices
|
||||
- Include testing and error handling sections
|
||||
|
||||
---
|
||||
|
||||
### Example 10: Quick Quality Check
|
||||
|
||||
**Use Case**: Quick validation before committing your CLAUDE.md file.
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Can you do a quick quality check on my CLAUDE.md? Give me a quality score and top 3 improvements.
|
||||
```
|
||||
|
||||
**What Claude Will Do**:
|
||||
- Calculate quality score (0-100)
|
||||
- Identify top 3 issues/improvements
|
||||
- Provide concise, actionable feedback
|
||||
- Highlight critical issues first
|
||||
|
||||
---
|
||||
|
||||
## What to Provide
|
||||
|
||||
When using this skill, provide any of the following:
|
||||
|
||||
### For Analysis
|
||||
- Existing CLAUDE.md content (paste the full text)
|
||||
- Project context (optional but helpful):
|
||||
- Project type (web app, API, mobile, etc.)
|
||||
- Tech stack (languages, frameworks, tools)
|
||||
- Team size (solo, small, medium, large)
|
||||
- Development phase (prototype, MVP, production)
|
||||
|
||||
### For Generation
|
||||
- Project type (web_app, api, fullstack, cli, library, mobile, desktop)
|
||||
- Tech stack (e.g., "TypeScript, React, Node, PostgreSQL")
|
||||
- Team size (solo, small <10, medium 10-50, large 50+)
|
||||
- Development phase (prototype, MVP, production, enterprise)
|
||||
- Key workflows (TDD, CI/CD, documentation-first, agile)
|
||||
- Modular architecture preference (yes/no)
|
||||
|
||||
### For Enhancement
|
||||
- Current CLAUDE.md content
|
||||
- Specific sections to add or improve
|
||||
- Any new technologies adopted
|
||||
|
||||
---
|
||||
|
||||
## What You'll Get
|
||||
|
||||
### Analysis Output
|
||||
- Quality score (0-100)
|
||||
- Missing sections list
|
||||
- Issues and warnings
|
||||
- Prioritized recommendations
|
||||
- Structure analysis
|
||||
|
||||
### Generation Output
|
||||
- Complete CLAUDE.md file(s)
|
||||
- Tailored to your tech stack
|
||||
- Appropriate for your team size
|
||||
- Customized for development phase
|
||||
- Modular architecture if requested
|
||||
|
||||
### Validation Output
|
||||
- Pass/fail status
|
||||
- Detailed validation results
|
||||
- Errors and warnings
|
||||
- Specific improvement suggestions
|
||||
|
||||
### Enhancement Output
|
||||
- Updated CLAUDE.md with new sections
|
||||
- Preserved existing content
|
||||
- Consistent formatting
|
||||
- Integrated recommendations
|
||||
|
||||
---
|
||||
|
||||
## Pro Tips
|
||||
|
||||
1. **Start Simple**: For new projects, start with a minimal CLAUDE.md and expand as needed
|
||||
2. **Use Modular Architecture**: For projects >3 major components, use separate files (backend/, frontend/, etc.)
|
||||
3. **Keep Root File Concise**: Aim for <150 lines in root CLAUDE.md, use it as navigation
|
||||
4. **Validate Regularly**: Run quality checks when team or tech stack changes
|
||||
5. **Update Quarterly**: Review and update CLAUDE.md every 3 months or when stack changes
|
||||
6. **Be Specific**: The more context you provide, the better the customization
|
||||
7. **Iterate**: Start with generated content, then customize for your specific needs
|
||||
|
||||
---
|
||||
|
||||
## Common Scenarios
|
||||
|
||||
| Scenario | Recommended Approach |
|
||||
|----------|---------------------|
|
||||
| New project, solo developer | Generate minimal CLAUDE.md (~75 lines) |
|
||||
| New project, small team | Generate core CLAUDE.md (~125 lines) |
|
||||
| Existing project, needs cleanup | Analyze first, then enhance based on recommendations |
|
||||
| Large project, multiple teams | Generate modular architecture (root + context files) |
|
||||
| Pre-commit check | Quick validate with quality score |
|
||||
| Tech stack changed | Enhance with new tech-specific guidelines |
|
||||
| Team grew significantly | Regenerate with new team size configuration |
|
||||
|
||||
---
|
||||
|
||||
**Remember**: The goal is to make Claude Code more efficient and context-aware for your project. Start with what's helpful, iterate based on usage, and keep it maintainable!
|
||||
+542
@@ -0,0 +1,542 @@
|
||||
# claude-md-enhancer
|
||||
|
||||
> **Analyze, generate, and enhance CLAUDE.md files for any project type with intelligent templates and best practices.**
|
||||
|
||||
A comprehensive Claude Code skill that helps teams create and maintain high-quality CLAUDE.md files. Supports analysis, validation, generation, and enhancement with tech stack customization, team size adaptation, and modular architecture.
|
||||
|
||||
## Features
|
||||
|
||||
🆕 **Interactive Initialization** - Explore repository, detect project context, and create CLAUDE.md through conversational workflow
|
||||
✨ **100% Native Format Compliance** - All generated files follow official Claude Code format with project structure diagrams, setup instructions, architecture sections, and file structure explanations
|
||||
✅ **Intelligent Analysis** - Scan and evaluate existing CLAUDE.md files for quality and completeness
|
||||
🎯 **Best Practice Validation** - Check against Anthropic guidelines and community standards
|
||||
🚀 **Smart Generation** - Create customized CLAUDE.md files from scratch
|
||||
🔧 **Enhancement** - Add missing sections and improve existing files
|
||||
📦 **Modular Architecture** - Support context-specific files (backend/, frontend/, database/)
|
||||
🛠️ **Tech Stack Customization** - Tailor guidelines to your technologies
|
||||
👥 **Team Size Adaptation** - Adjust complexity for solo, small, medium, or large teams
|
||||
📊 **Quality Scoring** - Get 0-100 quality scores with actionable recommendations
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Installation
|
||||
|
||||
#### Option 1: Claude Code (Project-Level)
|
||||
|
||||
```bash
|
||||
# Copy skill folder to your project
|
||||
cp -r claude-md-enhancer /path/to/your/project/.claude/skills/
|
||||
|
||||
# Restart Claude Code or reload skills
|
||||
```
|
||||
|
||||
#### Option 2: Claude Code (User-Level)
|
||||
|
||||
```bash
|
||||
# Copy skill folder to user skills directory
|
||||
cp -r claude-md-enhancer ~/.claude/skills/
|
||||
|
||||
# Available across all your projects
|
||||
```
|
||||
|
||||
#### Option 3: Claude Apps
|
||||
|
||||
```
|
||||
1. Open Claude in browser
|
||||
2. Go to Skills settings
|
||||
3. Upload claude-md-enhancer.zip
|
||||
4. Enable the skill
|
||||
```
|
||||
|
||||
### Basic Usage
|
||||
|
||||
#### New Project (Interactive Initialization)
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. I don't have a CLAUDE.md file yet. Can you help me create one for this project?
|
||||
```
|
||||
|
||||
Claude will:
|
||||
1. Explore your repository
|
||||
2. Detect project type, tech stack, team size
|
||||
3. Show discoveries and ask for confirmation
|
||||
4. Create customized CLAUDE.md file(s)
|
||||
|
||||
#### Existing Project
|
||||
|
||||
```
|
||||
Hey Claude—I just added the "claude-md-enhancer" skill. Can you analyze my CLAUDE.md and suggest improvements?
|
||||
```
|
||||
|
||||
See [HOW_TO_USE.md](HOW_TO_USE.md) for comprehensive examples.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
### Module Overview
|
||||
|
||||
```
|
||||
claude-md-enhancer/
|
||||
├── SKILL.md # Skill definition with YAML frontmatter
|
||||
├── analyzer.py # Analyzes existing CLAUDE.md files
|
||||
├── validator.py # Validates against best practices
|
||||
├── generator.py # Generates new content
|
||||
├── template_selector.py # Selects appropriate templates
|
||||
├── sample_input.json # Example inputs
|
||||
├── expected_output.json # Expected outputs
|
||||
├── HOW_TO_USE.md # Usage examples
|
||||
└── README.md # This file
|
||||
```
|
||||
|
||||
### Python Modules
|
||||
|
||||
#### `workflow.py` - Initialization Workflow (New!)
|
||||
|
||||
**Class**: `InitializationWorkflow`
|
||||
|
||||
**Key Methods**:
|
||||
- `check_claude_md_exists()` - Detect if CLAUDE.md exists
|
||||
- `generate_exploration_prompt()` - Guide Claude to explore repository
|
||||
- `analyze_discoveries(results)` - Analyze exploration results to detect project context
|
||||
- `generate_confirmation_prompt(context)` - Create user confirmation prompt
|
||||
- `get_workflow_steps()` - Get complete 7-step workflow
|
||||
|
||||
**Workflow Steps**:
|
||||
1. Check for existing CLAUDE.md
|
||||
2. Explore repository (built-in Claude Code command)
|
||||
3. Analyze discoveries (project type, tech stack, team size)
|
||||
4. Request user confirmation
|
||||
5. Create CLAUDE.md file(s)
|
||||
6. Enhance with best practices
|
||||
7. Provide summary
|
||||
|
||||
**Detection Capabilities**:
|
||||
- **Project Types**: web_app, api, fullstack, cli, library, mobile, desktop
|
||||
- **Tech Stacks**: TypeScript, Python, Go, React, Vue, FastAPI, Django, PostgreSQL, Docker, Kubernetes, etc.
|
||||
- **Team Sizes**: solo, small (<10), medium (10-50), large (50+)
|
||||
- **Development Phases**: prototype, mvp, production, enterprise
|
||||
- **Workflows**: TDD, CI/CD, documentation-first, agile
|
||||
|
||||
#### `analyzer.py` - File Analysis
|
||||
|
||||
**Class**: `CLAUDEMDAnalyzer`
|
||||
|
||||
**Key Methods**:
|
||||
- `analyze_file()` - Comprehensive file analysis
|
||||
- `detect_sections()` - Identify all sections and subsections
|
||||
- `calculate_quality_score()` - Score 0-100 based on multiple factors
|
||||
- `generate_recommendations()` - Actionable improvement suggestions
|
||||
|
||||
**Quality Score Breakdown** (0-100):
|
||||
- Length appropriateness: 25 points
|
||||
- Section completeness: 25 points
|
||||
- Formatting quality: 20 points
|
||||
- Content specificity: 15 points
|
||||
- Modular organization: 15 points
|
||||
|
||||
#### `validator.py` - Best Practices Validation
|
||||
|
||||
**Class**: `BestPracticesValidator`
|
||||
|
||||
**Key Methods**:
|
||||
- `validate_length()` - Check file length (20-300 lines recommended)
|
||||
- `validate_structure()` - Verify required sections and hierarchy
|
||||
- `validate_formatting()` - Check markdown formatting quality
|
||||
- `validate_completeness()` - Ensure critical content included
|
||||
- `validate_all()` - Run all validation checks
|
||||
|
||||
**Validation Categories**:
|
||||
- File length (MUST be 20-300 lines)
|
||||
- Structure (required sections: Core Principles, Workflow)
|
||||
- Formatting (balanced code blocks, heading hierarchy)
|
||||
- Completeness (code examples, links, lists)
|
||||
- Anti-patterns (hardcoded secrets, placeholders, broken links)
|
||||
|
||||
#### `generator.py` - Content Generation
|
||||
|
||||
**Class**: `ContentGenerator`
|
||||
|
||||
**Key Methods**:
|
||||
- `generate_root_file()` - Create main CLAUDE.md (navigation hub)
|
||||
- `generate_context_file(context)` - Create context-specific files
|
||||
- `generate_section(name)` - Generate individual sections
|
||||
- `merge_with_existing(content, sections)` - Enhance existing files
|
||||
|
||||
**Supported Contexts**:
|
||||
- `backend` - API design, database, error handling
|
||||
- `frontend` - Components, state, styling, performance
|
||||
- `database` - Schema, migrations, query optimization
|
||||
- `docs` - Documentation standards
|
||||
- `.github` - CI/CD workflows
|
||||
|
||||
#### `template_selector.py` - Template Selection
|
||||
|
||||
**Class**: `TemplateSelector`
|
||||
|
||||
**Key Methods**:
|
||||
- `select_template()` - Choose template based on project context
|
||||
- `customize_template(template)` - Generate customized content
|
||||
- `recommend_modular_structure()` - Determine if modular architecture needed
|
||||
|
||||
**Template Matrix**:
|
||||
|
||||
| Project Type | Team Size | Target Lines | Complexity |
|
||||
|--------------|-----------|--------------|------------|
|
||||
| Web App | Solo | 75 | Minimal |
|
||||
| API | Small (<10) | 125 | Core |
|
||||
| Full-Stack | Medium (10-50) | 200 | Detailed |
|
||||
| Library | Large (50+) | 275 | Comprehensive |
|
||||
|
||||
**Supported Project Types**:
|
||||
- `web_app` - Frontend-focused (React, Vue, Angular)
|
||||
- `api` - Backend services (REST, GraphQL)
|
||||
- `fullstack` - Integrated frontend + backend
|
||||
- `cli` - Command-line tools
|
||||
- `library` - Reusable packages
|
||||
- `mobile` - React Native, Flutter
|
||||
- `desktop` - Electron, Tauri
|
||||
|
||||
**Supported Tech Stacks**:
|
||||
- TypeScript/JavaScript (React, Vue, Angular, Node)
|
||||
- Python (Django, FastAPI, Flask)
|
||||
- Go (Gin, Echo)
|
||||
- Java/Kotlin (Spring Boot)
|
||||
- Ruby (Rails)
|
||||
- And more...
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
### 1. Analyze Existing CLAUDE.md
|
||||
|
||||
**Scenario**: You have a CLAUDE.md file and want quality feedback.
|
||||
|
||||
**Input**: Existing file content + project context
|
||||
|
||||
**Output**:
|
||||
- Quality score (0-100)
|
||||
- Missing sections identified
|
||||
- Issues and warnings
|
||||
- Prioritized recommendations
|
||||
|
||||
**Example**:
|
||||
```
|
||||
Quality Score: 75/100
|
||||
|
||||
Missing Sections:
|
||||
- Testing Requirements
|
||||
- Error Handling Patterns
|
||||
|
||||
Recommendations:
|
||||
1. Add testing requirements section
|
||||
2. Reduce file length from 320 to <300 lines
|
||||
3. Consider modular architecture
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Generate New CLAUDE.md from Scratch
|
||||
|
||||
**Scenario**: Starting new project, need CLAUDE.md file.
|
||||
|
||||
**Input**: Project context (type, tech stack, team size, phase)
|
||||
|
||||
**Output**: Complete CLAUDE.md tailored to your specifications
|
||||
|
||||
**Generated Sections**:
|
||||
- Quick Navigation (if modular)
|
||||
- Core Principles
|
||||
- Tech Stack
|
||||
- Workflow Instructions
|
||||
- Testing Requirements
|
||||
- Error Handling
|
||||
- Documentation Standards
|
||||
- Performance Guidelines
|
||||
|
||||
---
|
||||
|
||||
### 3. Enhance Existing File
|
||||
|
||||
**Scenario**: Your CLAUDE.md is missing important sections.
|
||||
|
||||
**Input**: Current content + sections to add
|
||||
|
||||
**Output**: Enhanced file with new sections, preserving existing content
|
||||
|
||||
**Preservation**:
|
||||
- Keeps all existing content intact
|
||||
- Adds new sections seamlessly
|
||||
- Maintains consistent formatting
|
||||
- Respects your style choices
|
||||
|
||||
---
|
||||
|
||||
### 4. Generate Modular Architecture
|
||||
|
||||
**Scenario**: Large project needs separate CLAUDE.md files.
|
||||
|
||||
**Input**: Project context + modular flag + subdirectories
|
||||
|
||||
**Output**:
|
||||
- Root CLAUDE.md (navigation hub, <150 lines)
|
||||
- backend/CLAUDE.md (API, database, testing)
|
||||
- frontend/CLAUDE.md (components, state, styling)
|
||||
- database/CLAUDE.md (schema, migrations, queries)
|
||||
- .github/CLAUDE.md (CI/CD workflows)
|
||||
|
||||
**When Recommended**:
|
||||
- Full-stack projects
|
||||
- Large teams (10+ developers)
|
||||
- Production/enterprise phase
|
||||
- 3+ major tech components
|
||||
|
||||
---
|
||||
|
||||
### 5. Validate Before Commit
|
||||
|
||||
**Scenario**: Quick quality check before committing.
|
||||
|
||||
**Input**: Current CLAUDE.md content
|
||||
|
||||
**Output**:
|
||||
- Pass/fail status
|
||||
- Validation results (5 checks)
|
||||
- Errors and warnings
|
||||
- Pass/fail counts
|
||||
|
||||
**Validation Checks**:
|
||||
1. File length (20-300 lines)
|
||||
2. Structure (required sections present)
|
||||
3. Formatting (markdown quality)
|
||||
4. Completeness (essential content)
|
||||
5. Anti-patterns (security, placeholders)
|
||||
|
||||
---
|
||||
|
||||
## Sample Data
|
||||
|
||||
### Sample Input
|
||||
|
||||
See [sample_input.json](sample_input.json) for 6 realistic scenarios:
|
||||
|
||||
1. **analyze_existing** - Analyze basic CLAUDE.md file
|
||||
2. **create_new_fullstack** - Generate modular full-stack setup
|
||||
3. **enhance_with_missing_sections** - Add specific sections
|
||||
4. **create_modular_architecture** - Large team, enterprise setup
|
||||
5. **validate_existing** - Validate production-ready file
|
||||
6. **generate_context_specific** - Backend-only file
|
||||
|
||||
### Expected Output
|
||||
|
||||
See [expected_output.json](expected_output.json) for:
|
||||
|
||||
- Analysis reports with quality scores
|
||||
- Generated CLAUDE.md content
|
||||
- Validation results
|
||||
- Enhanced file examples
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Critical Validation Rule ⚠️
|
||||
|
||||
**"Always validate your output against official native examples before declaring complete."**
|
||||
|
||||
Before finalizing any CLAUDE.md generation:
|
||||
1. Compare output against `/update-claude-md` slash command format
|
||||
2. Check official Claude Code documentation for required sections
|
||||
3. Verify all native format sections are present (Overview, Project Structure, File Structure, Setup & Installation, Architecture, etc.)
|
||||
4. Cross-check against reference examples in `examples/` folder
|
||||
|
||||
### For New Projects
|
||||
|
||||
1. **Start Minimal** - Generate 50-100 line file, expand as needed
|
||||
2. **Add Tech Stack Early** - Include technologies immediately
|
||||
3. **Update with Team Growth** - Regenerate when team size changes
|
||||
4. **Consider Modular** - Use separate files if >3 major components
|
||||
|
||||
### For Existing Projects
|
||||
|
||||
1. **Analyze First** - Understand current state before changes
|
||||
2. **Preserve Custom Content** - Don't overwrite your specific guidelines
|
||||
3. **Validate Regularly** - Check quality when stack or team changes
|
||||
4. **Iterate** - Start with enhancements, full regeneration if needed
|
||||
|
||||
### General Guidelines
|
||||
|
||||
1. **Keep Root Concise** - Max 150 lines, use as navigation hub
|
||||
2. **Use Context Files** - backend/, frontend/, etc. for details
|
||||
3. **Avoid Duplication** - Each guideline appears once
|
||||
4. **Link External Docs** - Don't copy official documentation
|
||||
5. **Update Quarterly** - Review and refresh every 3 months
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### Project Context Parameters
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "fullstack", // Project type
|
||||
"tech_stack": ["typescript", "react", "node"], // Technologies
|
||||
"team_size": "small", // Team size
|
||||
"phase": "mvp", // Development phase
|
||||
"workflows": ["tdd", "cicd"], // Key workflows
|
||||
"modular": true, // Modular architecture
|
||||
"subdirectories": ["backend", "frontend"] // Subdirs for context files
|
||||
}
|
||||
```
|
||||
|
||||
#### Type Options
|
||||
- `web_app` - Frontend-focused
|
||||
- `api` - Backend services
|
||||
- `fullstack` - Full-stack application
|
||||
- `cli` - Command-line tool
|
||||
- `library` - Reusable package
|
||||
- `mobile` - Mobile application
|
||||
- `desktop` - Desktop application
|
||||
|
||||
#### Team Size Options
|
||||
- `solo` - 1 developer
|
||||
- `small` - 2-9 developers
|
||||
- `medium` - 10-49 developers
|
||||
- `large` - 50+ developers
|
||||
|
||||
#### Phase Options
|
||||
- `prototype` - Early exploration
|
||||
- `mvp` - Minimum viable product
|
||||
- `production` - Production system
|
||||
- `enterprise` - Enterprise-grade
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Quality Score Lower Than Expected
|
||||
|
||||
**Issue**: Quality score is 35/100
|
||||
|
||||
**Solutions**:
|
||||
1. Check file length (should be 20-300 lines)
|
||||
2. Add missing required sections (Core Principles, Workflow)
|
||||
3. Include code examples
|
||||
4. Add tech stack references
|
||||
5. Consider modular architecture if >300 lines
|
||||
|
||||
---
|
||||
|
||||
### Generated Content Too Generic
|
||||
|
||||
**Issue**: CLAUDE.md lacks specific guidance
|
||||
|
||||
**Solutions**:
|
||||
1. Provide detailed tech stack (specific frameworks/versions)
|
||||
2. Specify workflows (TDD, CI/CD, documentation-first)
|
||||
3. Include team size for appropriate complexity
|
||||
4. Add development phase for priority focus
|
||||
5. Customize generated content for your needs
|
||||
|
||||
---
|
||||
|
||||
### Modular Architecture Not Recommended
|
||||
|
||||
**Issue**: Single file generated, wanted modular
|
||||
|
||||
**Solutions**:
|
||||
1. Set `"modular": true` explicitly
|
||||
2. Ensure project type is `fullstack`
|
||||
3. Use team size `medium` or `large`
|
||||
4. Specify phase as `production` or `enterprise`
|
||||
5. Provide 3+ tech stack components
|
||||
|
||||
---
|
||||
|
||||
## Version
|
||||
|
||||
**Version**: 1.0.0
|
||||
**Last Updated**: November 2025
|
||||
**Compatible**: Claude Code 2.0+, Claude Apps, Claude API
|
||||
|
||||
---
|
||||
|
||||
## Contributing
|
||||
|
||||
Found a bug or have a suggestion? This skill is part of the [claude-code-skills-factory](https://github.com/anthropics/claude-code-skills-factory) repository.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
MIT License - See LICENSE file for details
|
||||
|
||||
---
|
||||
|
||||
## Companion Agent: claude-md-guardian 🛡️
|
||||
|
||||
For automatic CLAUDE.md maintenance throughout your project lifecycle, use the **claude-md-guardian** agent:
|
||||
|
||||
### What It Does
|
||||
|
||||
- **Auto-Sync**: Updates CLAUDE.md based on project changes
|
||||
- **Background Operation**: Works independently after milestones
|
||||
- **Smart Detection**: Only updates when significant changes occur
|
||||
- **Token-Efficient**: Uses haiku model for routine updates
|
||||
|
||||
### When It Triggers
|
||||
|
||||
**Automatically**:
|
||||
- SessionStart (checks git changes)
|
||||
- After feature completion
|
||||
- After major refactoring
|
||||
- After new dependencies added
|
||||
- After architecture changes
|
||||
|
||||
**Manually**:
|
||||
- Via `/enhance-claude-md` slash command
|
||||
- Direct invocation
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
# User-level (all projects)
|
||||
cp generated-agents/claude-md-guardian.md ~/.claude/agents/
|
||||
|
||||
# Project-level (current project)
|
||||
cp generated-agents/claude-md-guardian.md .claude/agents/
|
||||
```
|
||||
|
||||
### How They Work Together
|
||||
|
||||
```
|
||||
claude-md-guardian (agent) → Uses → claude-md-enhancer (skill)
|
||||
↓
|
||||
Detects changes → Invokes skill → Updates CLAUDE.md
|
||||
```
|
||||
|
||||
**Result**: Your CLAUDE.md stays synchronized with your codebase automatically!
|
||||
|
||||
See `generated-agents/claude-md-guardian-README.md` for complete agent documentation.
|
||||
|
||||
---
|
||||
|
||||
## Support
|
||||
|
||||
- **Documentation**: See [SKILL.md](SKILL.md) for complete documentation
|
||||
- **Examples**: See [HOW_TO_USE.md](HOW_TO_USE.md) for usage examples
|
||||
- **Companion Agent**: See `../../generated-agents/claude-md-guardian-README.md`
|
||||
- **Slash Command**: See `../../generated-commands/enhance-claude-md/README.md`
|
||||
- **Issues**: Report bugs in the main repository
|
||||
- **Community**: Share your CLAUDE.md setups and best practices
|
||||
|
||||
---
|
||||
|
||||
**Happy coding with Claude! 🚀**
|
||||
|
||||
Make your AI-assisted development more efficient with well-structured CLAUDE.md files and automatic maintenance via claude-md-guardian!
|
||||
|
||||
+446
@@ -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.
|
||||
@@ -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
|
||||
@@ -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!
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,385 @@
|
||||
# Frontend Development Guidelines
|
||||
|
||||
This file provides guidance for frontend development in this project.
|
||||
|
||||
## Overview
|
||||
|
||||
React 18 SPA with TypeScript, Tailwind CSS, and React Query for server state. Component-based architecture with hooks, performance optimization, and comprehensive testing.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
frontend/
|
||||
├── src/
|
||||
│ ├── components/ # Reusable components
|
||||
│ │ ├── common/ # Shared UI components
|
||||
│ │ │ ├── Button.tsx
|
||||
│ │ │ ├── Input.tsx
|
||||
│ │ │ └── Modal.tsx
|
||||
│ │ ├── layout/ # Layout components
|
||||
│ │ │ ├── Header.tsx
|
||||
│ │ │ ├── Footer.tsx
|
||||
│ │ │ └── Sidebar.tsx
|
||||
│ │ └── features/ # Feature-specific components
|
||||
│ │ ├── UserList.tsx
|
||||
│ │ └── ProductCard.tsx
|
||||
│ ├── pages/ # Page components (routes)
|
||||
│ │ ├── HomePage.tsx
|
||||
│ │ ├── UserPage.tsx
|
||||
│ │ └── NotFoundPage.tsx
|
||||
│ ├── hooks/ # Custom React hooks
|
||||
│ │ ├── useAuth.ts
|
||||
│ │ ├── useUser.ts
|
||||
│ │ └── useLocalStorage.ts
|
||||
│ ├── store/ # State management
|
||||
│ │ ├── AuthContext.tsx
|
||||
│ │ └── ThemeContext.tsx
|
||||
│ ├── services/ # API client functions
|
||||
│ │ ├── api.ts
|
||||
│ │ ├── auth.service.ts
|
||||
│ │ └── user.service.ts
|
||||
│ ├── utils/ # Utility functions
|
||||
│ │ ├── formatters.ts
|
||||
│ │ ├── validators.ts
|
||||
│ │ └── constants.ts
|
||||
│ ├── styles/ # Global styles
|
||||
│ │ └── global.css
|
||||
│ ├── types/ # TypeScript types
|
||||
│ │ ├── user.types.ts
|
||||
│ │ └── api.types.ts
|
||||
│ ├── App.tsx # Root component
|
||||
│ ├── main.tsx # Entry point
|
||||
│ └── router.tsx # Route definitions
|
||||
├── public/ # Static assets
|
||||
│ ├── images/
|
||||
│ ├── fonts/
|
||||
│ └── favicon.ico
|
||||
├── tests/
|
||||
│ ├── unit/ # Unit tests
|
||||
│ ├── integration/ # Integration tests
|
||||
│ └── e2e/ # End-to-end tests
|
||||
├── .env.example
|
||||
├── package.json
|
||||
├── vite.config.ts
|
||||
├── tailwind.config.js
|
||||
└── tsconfig.json
|
||||
```
|
||||
|
||||
## File Structure
|
||||
|
||||
- **components/** - Reusable UI components
|
||||
- **common/** - Shared components (Button, Input, Modal)
|
||||
- **layout/** - Layout components (Header, Footer, Sidebar)
|
||||
- **features/** - Feature-specific components
|
||||
- **pages/** - Page-level components mapped to routes
|
||||
- **hooks/** - Custom React hooks for shared logic
|
||||
- **store/** - Context providers for global state (auth, theme)
|
||||
- **services/** - API client functions and HTTP calls
|
||||
- **utils/** - Helper functions, formatters, validators
|
||||
- **types/** - TypeScript type definitions and interfaces
|
||||
|
||||
## Architecture
|
||||
|
||||
**Component Hierarchy**: App → Router → Pages → Features → Common
|
||||
|
||||
**State Management**:
|
||||
- **Local State**: `useState` for component-specific state
|
||||
- **Global State**: Context API for auth, theme, user
|
||||
- **Server State**: React Query for API data caching
|
||||
- **Form State**: React Hook Form for complex forms
|
||||
|
||||
**Flow**:
|
||||
```
|
||||
User Action → Component → Service → API → React Query Cache → Component Update
|
||||
```
|
||||
|
||||
## Setup & Installation
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
npm install
|
||||
|
||||
# Set up environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env with:
|
||||
# - VITE_API_URL (backend API URL)
|
||||
# - VITE_ENV (development/staging/production)
|
||||
|
||||
# Start development server
|
||||
npm run dev
|
||||
|
||||
# Server runs at http://localhost:5173
|
||||
```
|
||||
|
||||
## Component Standards
|
||||
|
||||
### Functional Components with Hooks
|
||||
|
||||
- Prefer functional components with hooks over class components
|
||||
- Use TypeScript for all components
|
||||
- Keep components small and focused (< 200 lines)
|
||||
- Extract reusable logic into custom hooks
|
||||
- Use composition over inheritance
|
||||
|
||||
### Component Structure
|
||||
|
||||
```typescript
|
||||
interface Props {
|
||||
userId: string;
|
||||
onUpdate?: () => void;
|
||||
}
|
||||
|
||||
export function UserProfile({ userId, onUpdate }: Props) {
|
||||
// 1. Hooks first
|
||||
const { data, loading, error } = useUserData(userId);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
|
||||
// 2. Event handlers
|
||||
const handleEdit = () => setIsEditing(true);
|
||||
|
||||
// 3. Early returns
|
||||
if (loading) return <Spinner />;
|
||||
if (error) return <ErrorMessage error={error} />;
|
||||
|
||||
// 4. Main render
|
||||
return <div>{/* component JSX */}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
### TypeScript Best Practices
|
||||
|
||||
- Define interfaces for all props
|
||||
- Use `type` for unions and primitives
|
||||
- Avoid `any` - use `unknown` if truly dynamic
|
||||
- Export types alongside components
|
||||
|
||||
## State Management
|
||||
|
||||
### Local State
|
||||
|
||||
- Keep component state local when possible
|
||||
- Use `useState` for simple values
|
||||
- Use `useReducer` for complex state logic
|
||||
|
||||
### Global State (Context API)
|
||||
|
||||
- Use Context API for app-wide state (theme, auth, user)
|
||||
- Example: AuthContext, ThemeContext
|
||||
- Avoid overuse - not for all shared state
|
||||
|
||||
### Server State (React Query)
|
||||
|
||||
- Use React Query for server state management
|
||||
- Automatic caching, refetching, and updates
|
||||
- Example:
|
||||
```typescript
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['users', userId],
|
||||
queryFn: () => fetchUser(userId)
|
||||
});
|
||||
```
|
||||
|
||||
### Best Practices
|
||||
|
||||
- Avoid prop drilling - use context for deep state
|
||||
- Document state shape and update patterns
|
||||
- Keep state as close to usage as possible
|
||||
|
||||
## Styling Guidelines
|
||||
|
||||
### Tailwind CSS
|
||||
|
||||
- Use Tailwind CSS utility classes
|
||||
- Create reusable component classes in `tailwind.config.js`
|
||||
- Avoid inline styles except for truly dynamic values
|
||||
- Use CSS variables for theming in `global.css`
|
||||
|
||||
### Responsive Design
|
||||
|
||||
- Ensure responsive design for all breakpoints (mobile-first)
|
||||
- Breakpoints: `sm:` (640px), `md:` (768px), `lg:` (1024px), `xl:` (1280px)
|
||||
- Test on mobile, tablet, desktop
|
||||
|
||||
### Dark Mode
|
||||
|
||||
- Implement dark mode with `dark:` variant
|
||||
- Use CSS variables for theme colors
|
||||
- Respect user's system preference
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Code Splitting
|
||||
|
||||
- Lazy load routes with `React.lazy()` and `Suspense`
|
||||
- Lazy load heavy components (charts, editors, modals)
|
||||
- Example:
|
||||
```typescript
|
||||
const Dashboard = lazy(() => import('./pages/Dashboard'));
|
||||
```
|
||||
|
||||
### Image Optimization
|
||||
|
||||
- Optimize images (use WebP, AVIF formats)
|
||||
- Use lazy loading with `loading="lazy"` attribute
|
||||
- Serve responsive images with `srcset`
|
||||
|
||||
### Bundle Optimization
|
||||
|
||||
- Minimize bundle size - analyze with `npm run analyze`
|
||||
- Use tree-shaking (import only what you need)
|
||||
- Avoid importing entire libraries
|
||||
|
||||
### React Optimization
|
||||
|
||||
- Use `useMemo` for expensive calculations
|
||||
- Use `useCallback` for function props
|
||||
- Use `React.memo` for expensive components
|
||||
- Avoid unnecessary re-renders
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
### Unit Tests
|
||||
|
||||
- Write unit tests for utility functions
|
||||
- Test business logic separately from UI
|
||||
- Mock external dependencies
|
||||
- Aim for 80%+ code coverage
|
||||
|
||||
### Component Tests
|
||||
|
||||
- Write component tests with React Testing Library
|
||||
- Test user interactions, not implementation details
|
||||
- Test accessibility (keyboard, screen readers)
|
||||
- Example:
|
||||
```typescript
|
||||
test('renders user profile', () => {
|
||||
render(<UserProfile userId="123" />);
|
||||
expect(screen.getByText(/profile/i)).toBeInTheDocument();
|
||||
});
|
||||
```
|
||||
|
||||
### API Mocking
|
||||
|
||||
- Mock API calls with MSW (Mock Service Worker)
|
||||
- Create realistic mock responses
|
||||
- Test loading and error states
|
||||
|
||||
### E2E Tests
|
||||
|
||||
- Write E2E tests with Playwright for critical flows
|
||||
- Test complete user journeys
|
||||
- Run E2E tests in CI/CD
|
||||
|
||||
```bash
|
||||
# Run tests
|
||||
npm test # All tests
|
||||
npm run test:unit # Unit tests only
|
||||
npm run test:e2e # E2E tests with Playwright
|
||||
npm run test:coverage # With coverage report
|
||||
```
|
||||
|
||||
## Accessibility (a11y)
|
||||
|
||||
### Semantic HTML
|
||||
|
||||
- Use semantic HTML elements (`<button>`, `<nav>`, `<main>`, `<article>`)
|
||||
- Don't use `<div>` for interactive elements
|
||||
- Use proper heading hierarchy (`<h1>` → `<h2>` → `<h3>`)
|
||||
|
||||
### Keyboard Navigation
|
||||
|
||||
- Ensure keyboard navigation works
|
||||
- Test with Tab, Enter, Escape keys
|
||||
- Add focus styles (don't remove outline)
|
||||
|
||||
### ARIA Labels
|
||||
|
||||
- Add ARIA labels where needed
|
||||
- Use `aria-label`, `aria-labelledby`, `aria-describedby`
|
||||
- Test with screen readers (VoiceOver, NVDA)
|
||||
|
||||
### Color Contrast
|
||||
|
||||
- Maintain color contrast ratios (WCAG AA minimum 4.5:1)
|
||||
- Test with browser DevTools accessibility panel
|
||||
- Don't rely on color alone to convey information
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Error Boundaries
|
||||
|
||||
- Use Error Boundaries for component errors
|
||||
- Implement fallback UI
|
||||
- Log errors to monitoring service (Sentry)
|
||||
|
||||
### User-Friendly Messages
|
||||
|
||||
- Show user-friendly error messages
|
||||
- Avoid technical jargon
|
||||
- Provide actionable next steps
|
||||
|
||||
### Async Error Handling
|
||||
|
||||
- Handle loading and error states in all async operations
|
||||
- Example:
|
||||
```typescript
|
||||
if (isLoading) return <Spinner />;
|
||||
if (error) return <ErrorMessage error={error} />;
|
||||
```
|
||||
|
||||
## Custom Hooks Pattern
|
||||
|
||||
Create custom hooks for reusable logic:
|
||||
|
||||
```typescript
|
||||
function useUserData(userId: string) {
|
||||
const [data, setData] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUserData(userId)
|
||||
.then(setData)
|
||||
.catch(setError)
|
||||
.finally(() => setLoading(false));
|
||||
}, [userId]);
|
||||
|
||||
return { data, loading, error };
|
||||
}
|
||||
```
|
||||
|
||||
## Common Commands
|
||||
|
||||
```bash
|
||||
# Development
|
||||
npm run dev # Start dev server (http://localhost:5173)
|
||||
npm test # Run all tests
|
||||
npm run test:watch # Run tests in watch mode
|
||||
npm run lint # Run ESLint
|
||||
npm run type-check # TypeScript check
|
||||
npm run format # Format code with Prettier
|
||||
|
||||
# Production
|
||||
npm run build # Build for production
|
||||
npm run preview # Preview production build locally
|
||||
npm run analyze # Analyze bundle size
|
||||
|
||||
# Testing
|
||||
npm run test:unit # Unit tests only
|
||||
npm run test:e2e # E2E tests with Playwright
|
||||
npm run test:coverage # Coverage report
|
||||
```
|
||||
|
||||
## Development Best Practices
|
||||
|
||||
- **Component Organization**: One component per file
|
||||
- **Naming**: PascalCase for components, camelCase for functions/variables
|
||||
- **Props**: Destructure props in function signature
|
||||
- **Imports**: Group imports (React, libraries, local)
|
||||
- **Comments**: Write comments for complex logic only
|
||||
- **Console Logs**: Remove before committing
|
||||
|
||||
---
|
||||
|
||||
**Context**: Frontend (React/TypeScript/Tailwind)
|
||||
**Lines**: ~225 (Frontend-specific template with native format)
|
||||
@@ -0,0 +1,192 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides top-level guidance for Claude Code when working with this full-stack project.
|
||||
|
||||
## Overview
|
||||
|
||||
Full-stack application with separated backend API and frontend SPA. Uses modular CLAUDE.md architecture with context-specific files for detailed guidance. Medium team (12 developers) in production phase.
|
||||
|
||||
## Quick Navigation
|
||||
|
||||
- [Backend Guidelines](backend/CLAUDE.md) - API, services, database operations
|
||||
- [Frontend Guidelines](frontend/CLAUDE.md) - Components, state management, styling
|
||||
- [Database Operations](database/CLAUDE.md) - Schemas, migrations, query optimization
|
||||
- [CI/CD Workflows](.github/CLAUDE.md) - Automation, testing, deployments
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
project-root/
|
||||
├── backend/
|
||||
│ ├── src/
|
||||
│ │ ├── controllers/ # API route handlers
|
||||
│ │ ├── services/ # Business logic
|
||||
│ │ ├── models/ # Database models
|
||||
│ │ ├── middleware/ # Express middleware
|
||||
│ │ └── utils/ # Shared utilities
|
||||
│ ├── tests/ # Backend tests
|
||||
│ └── CLAUDE.md # Backend-specific guidance
|
||||
├── frontend/
|
||||
│ ├── src/
|
||||
│ │ ├── components/ # React components
|
||||
│ │ ├── pages/ # Page components
|
||||
│ │ ├── hooks/ # Custom hooks
|
||||
│ │ ├── store/ # State management
|
||||
│ │ └── styles/ # CSS/styling
|
||||
│ ├── public/ # Static assets
|
||||
│ └── CLAUDE.md # Frontend-specific guidance
|
||||
├── database/
|
||||
│ ├── migrations/ # Schema migrations
|
||||
│ ├── seeds/ # Seed data
|
||||
│ └── CLAUDE.md # Database guidance
|
||||
├── .github/
|
||||
│ ├── workflows/ # CI/CD workflows
|
||||
│ └── CLAUDE.md # CI/CD guidance
|
||||
├── docker-compose.yml
|
||||
├── package.json
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## File Structure
|
||||
|
||||
This project uses **modular architecture** with context-specific CLAUDE.md files:
|
||||
|
||||
- **backend/** - Express API server
|
||||
- See [backend/CLAUDE.md](backend/CLAUDE.md) for API design, error handling, testing
|
||||
- **frontend/** - React SPA
|
||||
- See [frontend/CLAUDE.md](frontend/CLAUDE.md) for component standards, state, styling
|
||||
- **database/** - PostgreSQL database
|
||||
- See [database/CLAUDE.md](database/CLAUDE.md) for migrations, schemas, queries
|
||||
- **.github/** - CI/CD workflows
|
||||
- See [.github/CLAUDE.md](.github/CLAUDE.md) for deployment, automation
|
||||
|
||||
## Architecture
|
||||
|
||||
**Stack**: React SPA + Express API + PostgreSQL + Redis Cache
|
||||
|
||||
**Services**:
|
||||
- Frontend: React 18 with TypeScript, served via Nginx
|
||||
- Backend: Node.js 20 with Express 4, TypeScript
|
||||
- Database: PostgreSQL 15 with Prisma ORM
|
||||
- Cache: Redis 7 for session and data caching
|
||||
- Message Queue: RabbitMQ for async processing
|
||||
- Infrastructure: Docker containers, Kubernetes orchestration
|
||||
|
||||
**Flow**:
|
||||
```
|
||||
Client (React) → Nginx → Express API → PostgreSQL
|
||||
↓
|
||||
Redis Cache
|
||||
↓
|
||||
RabbitMQ Queue
|
||||
```
|
||||
|
||||
## Setup & Installation
|
||||
|
||||
```bash
|
||||
# Install dependencies for entire monorepo
|
||||
npm install
|
||||
|
||||
# Set up environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env with your credentials
|
||||
|
||||
# Start all services with Docker
|
||||
docker-compose up -d
|
||||
|
||||
# Run database migrations
|
||||
npm run db:migrate
|
||||
|
||||
# Seed initial data
|
||||
npm run db:seed
|
||||
|
||||
# Start development servers
|
||||
npm run dev # Starts backend and frontend
|
||||
```
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Test-Driven Development**: Write tests before implementation
|
||||
2. **Type Safety First**: Use TypeScript strict mode throughout
|
||||
3. **Component Composition**: Favor small, reusable components
|
||||
4. **API Design**: RESTful conventions with proper versioning
|
||||
5. **Error Handling**: Comprehensive error handling from the start
|
||||
6. **Performance**: Optimize for scale (caching, CDN, lazy loading)
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Frontend**: React 18, TypeScript 5, Tailwind CSS, React Query
|
||||
- **Backend**: Node.js 20, Express 4, TypeScript, Prisma
|
||||
- **Database**: PostgreSQL 15, Redis 7
|
||||
- **Infrastructure**: Docker, Kubernetes, Nginx, GitHub Actions
|
||||
- **Testing**: Jest, React Testing Library, Supertest, Playwright
|
||||
|
||||
## Development Workflow
|
||||
|
||||
1. **Feature Development**:
|
||||
- Create feature branch: `git checkout -b feature/name`
|
||||
- Work in appropriate context (backend/ or frontend/)
|
||||
- Follow context-specific CLAUDE.md guidelines
|
||||
- Write tests first (TDD)
|
||||
- Run local validation: `npm run lint && npm test`
|
||||
|
||||
2. **Code Review**:
|
||||
- Create PR with detailed description
|
||||
- Ensure CI passes (lint, tests, build)
|
||||
- Get minimum 2 approvals
|
||||
- Address review comments
|
||||
|
||||
3. **Deployment**:
|
||||
- Merge to `main` triggers staging deployment
|
||||
- QA validation on staging
|
||||
- Manual promotion to production
|
||||
- Monitor metrics and logs
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```bash
|
||||
# Development
|
||||
npm run dev:backend # Start backend server (port 3000)
|
||||
npm run dev:frontend # Start frontend dev server (port 5173)
|
||||
npm run dev # Start both servers
|
||||
npm test # Run all tests (backend + frontend)
|
||||
npm run lint # Lint all code
|
||||
|
||||
# Production
|
||||
npm run build # Build frontend and backend
|
||||
npm run start # Start production servers
|
||||
|
||||
# Database
|
||||
npm run db:migrate # Run migrations
|
||||
npm run db:seed # Seed data
|
||||
npm run db:reset # Reset database (dev only)
|
||||
|
||||
# Docker
|
||||
docker-compose up -d # Start all services
|
||||
docker-compose logs -f # View logs
|
||||
docker-compose down # Stop all services
|
||||
```
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
- **Unit Tests**: All business logic (80%+ coverage)
|
||||
- **Integration Tests**: API endpoints and database operations
|
||||
- **E2E Tests**: Critical user flows with Playwright
|
||||
- **Performance Tests**: Load testing for API endpoints
|
||||
- **Security Tests**: OWASP compliance scans
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **Context-Specific Guidelines**: Always check subdirectory CLAUDE.md files for detailed guidance
|
||||
- **Modular Architecture**: Each major component has its own CLAUDE.md file
|
||||
- **Navigation**: Use Quick Navigation section to find relevant guidelines
|
||||
- **Production Ready**: This is a production-grade setup with enterprise patterns
|
||||
|
||||
---
|
||||
|
||||
For detailed guidelines, see context-specific CLAUDE.md files in subdirectories.
|
||||
|
||||
**Project Type**: Full-Stack Application (Production)
|
||||
**Team Size**: Medium (12 developers)
|
||||
**Architecture**: Modular with context-specific CLAUDE.md files
|
||||
**Lines**: ~150 (Modular root template with native format)
|
||||
@@ -0,0 +1,461 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance for Claude Code when working with this Python API project.
|
||||
|
||||
## Overview
|
||||
|
||||
FastAPI-based RESTful API with PostgreSQL database, JWT authentication, and async SQLAlchemy. Small team (6 developers) following TDD practices with 90%+ test coverage requirement.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
project-root/
|
||||
├── app/
|
||||
│ ├── api/
|
||||
│ │ ├── v1/
|
||||
│ │ │ ├── endpoints/ # API endpoints
|
||||
│ │ │ │ ├── auth.py
|
||||
│ │ │ │ ├── users.py
|
||||
│ │ │ │ └── products.py
|
||||
│ │ │ ├── dependencies.py # Shared dependencies
|
||||
│ │ │ └── router.py # API router
|
||||
│ │ └── __init__.py
|
||||
│ ├── core/
|
||||
│ │ ├── config.py # App configuration
|
||||
│ │ ├── security.py # Auth utilities
|
||||
│ │ └── database.py # DB connection
|
||||
│ ├── models/
|
||||
│ │ ├── user.py # SQLAlchemy models
|
||||
│ │ └── product.py
|
||||
│ ├── schemas/
|
||||
│ │ ├── user.py # Pydantic schemas
|
||||
│ │ └── product.py
|
||||
│ ├── services/
|
||||
│ │ ├── auth_service.py # Business logic
|
||||
│ │ ├── user_service.py
|
||||
│ │ └── product_service.py
|
||||
│ ├── utils/
|
||||
│ │ ├── logging.py # Logging utilities
|
||||
│ │ └── validators.py
|
||||
│ ├── middleware/
|
||||
│ │ ├── logging.py # Logging middleware
|
||||
│ │ └── rate_limit.py # Rate limiting
|
||||
│ └── main.py # App entry point
|
||||
├── tests/
|
||||
│ ├── unit/ # Unit tests
|
||||
│ ├── integration/ # Integration tests
|
||||
│ ├── conftest.py # Pytest fixtures
|
||||
│ └── test_main.py
|
||||
├── alembic/
|
||||
│ ├── versions/ # Migration files
|
||||
│ └── env.py # Alembic config
|
||||
├── .env.example
|
||||
├── alembic.ini
|
||||
├── pyproject.toml
|
||||
├── requirements.txt
|
||||
├── Dockerfile
|
||||
└── docker-compose.yml
|
||||
```
|
||||
|
||||
## File Structure
|
||||
|
||||
- **app/** - Main application package
|
||||
- **api/v1/** - API version 1 endpoints and routing
|
||||
- **endpoints/** - Path operation functions
|
||||
- **dependencies.py** - Dependency injection (DB sessions, auth)
|
||||
- **core/** - Core utilities (config, security, database)
|
||||
- **models/** - SQLAlchemy ORM models
|
||||
- **schemas/** - Pydantic models for request/response validation
|
||||
- **services/** - Business logic layer (separate from HTTP)
|
||||
- **utils/** - Helper functions (logging, validation)
|
||||
- **middleware/** - FastAPI middleware components
|
||||
- **tests/** - Test suite with pytest
|
||||
- **alembic/** - Database migrations
|
||||
|
||||
## Architecture
|
||||
|
||||
**Layer Pattern**: FastAPI → Services → Models → Database
|
||||
|
||||
**Flow**:
|
||||
```
|
||||
HTTP Request → Router → Dependency Injection → Endpoint → Service → Model → Database
|
||||
↓
|
||||
Response (Pydantic schema)
|
||||
```
|
||||
|
||||
**Components**:
|
||||
- **Endpoints**: HTTP layer, request/response handling with Pydantic
|
||||
- **Services**: Business logic, reusable across endpoints
|
||||
- **Models**: Data access layer with async SQLAlchemy 2.0
|
||||
- **Schemas**: Request/response validation with Pydantic
|
||||
- **Dependencies**: Shared dependencies (DB session, current user)
|
||||
|
||||
## Setup & Installation
|
||||
|
||||
```bash
|
||||
# Create virtual environment
|
||||
python -m venv venv
|
||||
source venv/bin/activate # On Windows: venv\Scripts\activate
|
||||
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Set up environment variables
|
||||
cp .env.example .env
|
||||
# Edit .env with:
|
||||
# - DATABASE_URL (PostgreSQL connection string)
|
||||
# - SECRET_KEY (for JWT token signing)
|
||||
# - ENVIRONMENT (development/staging/production)
|
||||
|
||||
# Start PostgreSQL (using Docker)
|
||||
docker-compose up -d postgres
|
||||
|
||||
# Run database migrations
|
||||
alembic upgrade head
|
||||
|
||||
# Seed database (if needed)
|
||||
python -m app.scripts.seed
|
||||
|
||||
# Start development server
|
||||
uvicorn app.main:app --reload
|
||||
|
||||
# Server runs at http://localhost:8000
|
||||
# API docs at http://localhost:8000/docs (Swagger UI)
|
||||
# Alternative docs at http://localhost:8000/redoc (ReDoc)
|
||||
```
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Type Hints First**: Use type hints for all function signatures (Python 3.10+)
|
||||
2. **Test-Driven Development**: Write tests before implementation
|
||||
3. **API Design**: Follow RESTful conventions and OpenAPI standards
|
||||
4. **Error Handling**: Comprehensive error handling with proper logging
|
||||
5. **Code Quality**: Black formatting, Ruff linting, 90%+ test coverage
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Framework**: FastAPI 0.104+
|
||||
- **Database**: PostgreSQL 15 with async SQLAlchemy 2.0
|
||||
- **Authentication**: JWT with python-jose
|
||||
- **Validation**: Pydantic v2
|
||||
- **Testing**: Pytest, Pytest-asyncio, HTTPX
|
||||
- **Deployment**: Docker, Uvicorn, Gunicorn
|
||||
- **Logging**: Structlog (JSON format)
|
||||
- **Code Quality**: Black, Ruff, MyPy
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Development Process
|
||||
|
||||
1. Create feature branch from `main`: `git checkout -b feature/name`
|
||||
2. Write tests first (TDD with pytest)
|
||||
3. Implement feature with type hints
|
||||
4. Run formatter, linter, and tests locally
|
||||
5. Create pull request with description
|
||||
6. Code review (minimum 1 approval required)
|
||||
7. Merge to main (auto-deploy to staging)
|
||||
|
||||
### Code Style
|
||||
|
||||
- Use Black for formatting (line length: 100)
|
||||
- Use Ruff for linting (replaces flake8, isort, etc.)
|
||||
- Type hints on all functions and methods
|
||||
- Docstrings for all public functions (Google style)
|
||||
- Example:
|
||||
```python
|
||||
def create_user(db: Session, user_in: UserCreate) -> User:
|
||||
"""Create a new user in the database.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
user_in: User creation data
|
||||
|
||||
Returns:
|
||||
Created user object
|
||||
|
||||
Raises:
|
||||
ValueError: If email already exists
|
||||
"""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
## API Design Guidelines
|
||||
|
||||
### FastAPI Path Operations
|
||||
|
||||
- Use FastAPI path operations (`@app.get`, `@app.post`, etc.)
|
||||
- Version APIs: `/api/v1/users`, `/api/v2/users`
|
||||
- Use Pydantic models for request/response validation
|
||||
- Implement proper HTTP status codes:
|
||||
- `200 OK` - Successful GET/PUT/PATCH
|
||||
- `201 Created` - Successful POST
|
||||
- `204 No Content` - Successful DELETE
|
||||
- `400 Bad Request` - Validation error
|
||||
- `401 Unauthorized` - Authentication required
|
||||
- `403 Forbidden` - Insufficient permissions
|
||||
- `404 Not Found` - Resource not found
|
||||
- `422 Unprocessable Entity` - Pydantic validation error
|
||||
- `500 Internal Server Error` - Server error
|
||||
|
||||
### Documentation
|
||||
|
||||
- Document with OpenAPI (auto-generated by FastAPI)
|
||||
- Access Swagger UI at `/docs`
|
||||
- Access ReDoc at `/redoc`
|
||||
- Add descriptions to path operations:
|
||||
```python
|
||||
@router.get("/users/{user_id}", response_model=UserResponse)
|
||||
async def get_user(user_id: int, db: Session = Depends(get_db)):
|
||||
"""Retrieve a single user by ID."""
|
||||
# Implementation...
|
||||
```
|
||||
|
||||
## Database Guidelines
|
||||
|
||||
### Migrations with Alembic
|
||||
|
||||
- Use Alembic for migrations
|
||||
- **Never edit existing migrations** - create new ones
|
||||
- Auto-generate migrations: `alembic revision --autogenerate -m "description"`
|
||||
- Review generated migrations before applying
|
||||
- Test migrations on copy of production data
|
||||
- Name migrations descriptively: `add_user_email_index`
|
||||
|
||||
### SQLAlchemy 2.0 Async Style
|
||||
|
||||
- Use async SQLAlchemy 2.0 style
|
||||
- Example:
|
||||
```python
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
async def get_user(db: AsyncSession, user_id: int) -> User | None:
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
return result.scalar_one_or_none()
|
||||
```
|
||||
|
||||
### Query Optimization
|
||||
|
||||
- Implement proper indexes for frequently queried columns
|
||||
- Avoid N+1 queries - use `selectinload` or `joinedload`
|
||||
- Use database transactions for multi-step operations
|
||||
- Paginate large result sets (max 100 items per page)
|
||||
|
||||
## Error Handling
|
||||
|
||||
### FastAPI Exception Handlers
|
||||
|
||||
- Use FastAPI exception handlers
|
||||
- Create custom exceptions:
|
||||
```python
|
||||
class UserNotFoundException(HTTPException):
|
||||
def __init__(self, user_id: int):
|
||||
super().__init__(
|
||||
status_code=404,
|
||||
detail=f"User {user_id} not found"
|
||||
)
|
||||
```
|
||||
|
||||
### Error Response Format
|
||||
|
||||
Return consistent error format:
|
||||
|
||||
```python
|
||||
{
|
||||
"detail": {
|
||||
"code": "VALIDATION_ERROR",
|
||||
"message": "User-friendly message",
|
||||
"errors": [
|
||||
{
|
||||
"field": "email",
|
||||
"message": "Invalid email format"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Logging
|
||||
|
||||
- Log errors with structlog (JSON format)
|
||||
- Include context (request ID, user ID, timestamp)
|
||||
- Log levels: ERROR, WARNING, INFO, DEBUG
|
||||
- Never log sensitive data (passwords, tokens)
|
||||
- Never expose stack traces in production
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
### Pytest Best Practices
|
||||
|
||||
- Use pytest for all tests
|
||||
- Use pytest fixtures for test setup
|
||||
- Mock external dependencies (httpx, boto3, etc.)
|
||||
- Aim for 90%+ code coverage
|
||||
- Test both success and error paths
|
||||
|
||||
### Example Test
|
||||
|
||||
```python
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from app.main import app
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_user(client: AsyncClient):
|
||||
"""Test user creation endpoint."""
|
||||
response = await client.post(
|
||||
"/api/v1/users",
|
||||
json={"email": "test@example.com", "name": "Test User"}
|
||||
)
|
||||
assert response.status_code == 201
|
||||
data = response.json()
|
||||
assert data["email"] == "test@example.com"
|
||||
assert "id" in data
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_user_duplicate_email(client: AsyncClient):
|
||||
"""Test user creation with duplicate email."""
|
||||
# First creation
|
||||
await client.post("/api/v1/users", json={"email": "test@example.com"})
|
||||
|
||||
# Duplicate should fail
|
||||
response = await client.post("/api/v1/users", json={"email": "test@example.com"})
|
||||
assert response.status_code == 400
|
||||
```
|
||||
|
||||
### Test Categories
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
pytest
|
||||
|
||||
# Run specific test categories
|
||||
pytest tests/unit/ # Unit tests only
|
||||
pytest tests/integration/ # Integration tests only
|
||||
pytest -m slow # Slow tests (marked with @pytest.mark.slow)
|
||||
|
||||
# Run with coverage
|
||||
pytest --cov=app --cov-report=html
|
||||
```
|
||||
|
||||
## Security Practices
|
||||
|
||||
### Input Validation
|
||||
|
||||
- Validate all input with Pydantic models
|
||||
- Use Pydantic validators for complex validation
|
||||
- Sanitize user input to prevent XSS
|
||||
|
||||
### Database Security
|
||||
|
||||
- Use parameterized queries (SQLAlchemy handles this)
|
||||
- Prevents SQL injection
|
||||
- Never concatenate user input into queries
|
||||
|
||||
### Authentication & Authorization
|
||||
|
||||
- Hash passwords with passlib + bcrypt
|
||||
- Use JWT for stateless authentication
|
||||
- Implement refresh token rotation
|
||||
- Use environment variables for secrets
|
||||
- Example:
|
||||
```python
|
||||
from passlib.context import CryptContext
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
hashed_password = pwd_context.hash(plain_password)
|
||||
```
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
- Implement rate limiting with slowapi
|
||||
- Example: 100 requests per 15 minutes per IP
|
||||
- Protect against brute force attacks
|
||||
|
||||
### CORS
|
||||
|
||||
- Enable CORS properly with CORSMiddleware
|
||||
- Whitelist allowed origins in production
|
||||
- Don't use wildcard (`*`) in production
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Async/Await
|
||||
|
||||
- Use async/await for all I/O operations
|
||||
- Use AsyncSession for database operations
|
||||
- Use httpx.AsyncClient for external HTTP calls
|
||||
|
||||
### Caching
|
||||
|
||||
- Implement caching for frequently accessed data
|
||||
- Use Redis for caching (with aioredis)
|
||||
- Cache expensive computations
|
||||
- Set appropriate TTL (time-to-live)
|
||||
|
||||
### Database Connection Pooling
|
||||
|
||||
- Configure SQLAlchemy connection pool
|
||||
- Set appropriate pool size and overflow
|
||||
|
||||
## Common Commands
|
||||
|
||||
```bash
|
||||
# Development
|
||||
uvicorn app.main:app --reload # Start dev server with hot reload
|
||||
pytest # Run all tests
|
||||
pytest --cov=app # Run tests with coverage
|
||||
black . # Format code
|
||||
ruff check . # Lint code
|
||||
mypy app/ # Type checking
|
||||
|
||||
# Database
|
||||
alembic upgrade head # Run all pending migrations
|
||||
alembic downgrade -1 # Rollback last migration
|
||||
alembic revision --autogenerate -m "description" # Create migration
|
||||
alembic current # Show current migration
|
||||
alembic history # Show migration history
|
||||
|
||||
# Production
|
||||
gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker
|
||||
|
||||
# Docker
|
||||
docker-compose up -d # Start all services
|
||||
docker-compose logs -f app # View application logs
|
||||
docker-compose down # Stop all services
|
||||
```
|
||||
|
||||
## API Documentation
|
||||
|
||||
After starting the server, access API documentation at:
|
||||
|
||||
- **Swagger UI**: http://localhost:8000/docs (interactive)
|
||||
- **ReDoc**: http://localhost:8000/redoc (readable)
|
||||
- **OpenAPI JSON**: http://localhost:8000/openapi.json (raw schema)
|
||||
|
||||
## Environment Variables
|
||||
|
||||
Required environment variables (see `.env.example`):
|
||||
|
||||
```bash
|
||||
# Application
|
||||
ENVIRONMENT=development
|
||||
SECRET_KEY=your-secret-key-here
|
||||
DEBUG=True
|
||||
|
||||
# Database
|
||||
DATABASE_URL=postgresql+asyncpg://user:password@localhost/dbname
|
||||
|
||||
# Authentication
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES=30
|
||||
REFRESH_TOKEN_EXPIRE_DAYS=7
|
||||
|
||||
# CORS
|
||||
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:5173
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Project Type**: Python API (FastAPI)
|
||||
**Team Size**: Small (6 developers)
|
||||
**Lines**: ~225 (Python API template with native format)
|
||||
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"outputs": [
|
||||
{
|
||||
"scenario": "initialize_new_project",
|
||||
"output": {
|
||||
"workflow_status": "completed",
|
||||
"detected_context": {
|
||||
"project_type": "fullstack",
|
||||
"tech_stack": ["typescript", "react", "express"],
|
||||
"team_size": "small",
|
||||
"phase": "mvp",
|
||||
"workflows": ["tdd", "cicd"],
|
||||
"modular_recommended": true
|
||||
},
|
||||
"confirmation_prompt": "Based on my exploration, here's what I discovered:\n\n**Project Type**: Fullstack\n**Tech Stack**: typescript, react, express\n**Team Size**: Small (2-9 developers)\n**Development Phase**: Mvp\n**Workflows**: tdd, cicd\n\n**Recommended Structure**:\nModular architecture (separate CLAUDE.md files for major components)\n\nWould you like me to create a CLAUDE.md file based on these discoveries?",
|
||||
"created_files": [
|
||||
"CLAUDE.md",
|
||||
"backend/CLAUDE.md",
|
||||
"frontend/CLAUDE.md"
|
||||
],
|
||||
"summary": "✅ CLAUDE.md Initialization Complete!\n\n**Created Files** (3):\n- CLAUDE.md\n- backend/CLAUDE.md\n- frontend/CLAUDE.md\n\n**Next Steps**:\n1. Review the generated CLAUDE.md file\n2. Customize for your specific needs\n3. Add team-specific conventions\n4. Update as your project evolves\n\nYour project is now set up for efficient AI-assisted development with Claude Code!"
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "analyze_existing",
|
||||
"output": {
|
||||
"analysis": {
|
||||
"file_metrics": {
|
||||
"char_count": 150,
|
||||
"line_count": 12,
|
||||
"word_count": 25,
|
||||
"heading_count": 3,
|
||||
"code_block_count": 0
|
||||
},
|
||||
"sections_found": ["Tech Stack", "Workflow"],
|
||||
"missing_sections": [
|
||||
"Quick Navigation",
|
||||
"Core Principles",
|
||||
"Quality Checklist",
|
||||
"File Organization",
|
||||
"Common Commands",
|
||||
"References"
|
||||
],
|
||||
"structure_analysis": {
|
||||
"has_main_title": true,
|
||||
"has_navigation_section": false,
|
||||
"has_code_examples": false,
|
||||
"has_links": false,
|
||||
"mentions_modular_architecture": false,
|
||||
"section_count": 2,
|
||||
"subsection_count": 0,
|
||||
"hierarchy_depth": 2
|
||||
},
|
||||
"issues": [
|
||||
{
|
||||
"type": "too_short",
|
||||
"severity": "medium",
|
||||
"message": "File is very short (12 lines). May need more guidance."
|
||||
},
|
||||
{
|
||||
"type": "missing_critical_sections",
|
||||
"severity": "high",
|
||||
"message": "Missing critical sections: Core Principles"
|
||||
}
|
||||
],
|
||||
"quality_score": 35,
|
||||
"recommendations": [
|
||||
"CRITICAL: Add essential sections: Core Principles",
|
||||
"Expand with essential sections: Core Principles, Tech Stack, Workflow Instructions",
|
||||
"Consider adding: Quick Navigation, Quality Checklist, File Organization",
|
||||
"Include code examples for complex patterns to improve clarity",
|
||||
"Overall quality score is 35/100 - prioritize critical improvements"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "create_new_fullstack",
|
||||
"output": {
|
||||
"root_file": "# CLAUDE.md\n\nThis file provides top-level guidance for Claude Code when working with this fullstack.\n\n## Quick Navigation\n\n- [Backend Guidelines](backend/CLAUDE.md)\n- [Frontend Guidelines](frontend/CLAUDE.md)\n- [Database Operations](database/CLAUDE.md)\n- [CI/CD Workflows](.github/CLAUDE.md)\n\n## Core Principles\n\n1. **Test-Driven Development**: Write tests before implementation\n2. **Use TypeScript strict mode throughout the project**: Use TypeScript strict mode throughout the project\n3. **Prefer functional components with hooks over class components**: Prefer functional components with hooks over class components\n4. **Use multi-stage Dockerfiles for optimized image size**: Use multi-stage Dockerfiles for optimized image size\n5. **Code Quality**: Maintain high code quality with clear, readable implementations\n\n## Tech Stack\n\n- **Languages**: TypeScript\n- **Frameworks**: React\n- **Tools**: PostgreSQL, Docker\n\n## Quick Reference\n\n```bash\n# Common development commands\nnpm test # Run tests\nnpm run lint # Run linter\nnpm run build # Build for production\n```\n\n---\n\nFor detailed guidelines, see context-specific CLAUDE.md files in subdirectories.",
|
||||
"context_files": {
|
||||
"backend": "# Backend Development Guidelines\n\nThis file provides guidance for backend development in this project.\n\n## API Design\n\n- Use RESTful conventions for API endpoints\n- Implement proper HTTP status codes (200, 201, 400, 404, 500)\n- Version APIs when breaking changes are needed (/api/v1/, /api/v2/)\n- Document all endpoints with OpenAPI/Swagger\n\n## Database Operations\n\n- Use migrations for all schema changes\n- Implement proper indexes for query performance\n- Use transactions for multi-step operations\n- Avoid N+1 queries - use joins or batch loading\n\n## Error Handling\n\n- Implement global error handling middleware\n- Log errors with context (request ID, user ID, timestamp)\n- Return consistent error response format\n- Never expose stack traces to clients in production\n\n## Testing Requirements\n\n- Write unit tests for business logic\n- Write integration tests for API endpoints\n- Mock external services in tests\n- Aim for 80%+ code coverage\n",
|
||||
"frontend": "# Frontend Development Guidelines\n\nThis file provides guidance for frontend development in this project.\n\n## Component Standards\n\n- Prefer functional components with hooks over class components\n- Use TypeScript for type safety\n- Keep components small and focused (< 200 lines)\n- Extract reusable logic into custom hooks\n\n## State Management\n\n- Keep component state local when possible\n- Use global state only for truly shared data\n- Avoid prop drilling - use context/store for deep state\n- Document state shape and update patterns\n\n## Styling Guidelines\n\n- Use consistent naming conventions (BEM, CSS Modules, etc.)\n- Avoid inline styles except for dynamic values\n- Use design tokens for colors, spacing, typography\n- Ensure responsive design for all breakpoints\n\n## Performance Optimization\n\n- Lazy load routes and heavy components\n- Optimize images (use WebP, lazy loading)\n- Minimize bundle size - code split where possible\n- Use memoization for expensive calculations\n",
|
||||
"database": "# Database Guidelines\n\nThis file provides guidance for database operations and migrations.\n\n## Schema Design\n\n- Use meaningful table and column names\n- Always include created_at and updated_at timestamps\n- Use proper foreign key constraints\n- Add indexes for frequently queried columns\n\n## Migration Guidelines\n\n- Never edit existing migrations - create new ones\n- Test migrations on copy of production data\n- Include both up and down migrations\n- Document breaking changes in migration comments\n\n## Query Optimization\n\n- Use EXPLAIN to analyze slow queries\n- Avoid SELECT * - specify needed columns\n- Use appropriate JOIN types\n- Limit result sets with pagination\n"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "enhance_with_missing_sections",
|
||||
"output": {
|
||||
"enhanced_content": "# CLAUDE.md\n\n## Core Principles\n1. Write tests first\n2. Use TypeScript\n\n## Tech Stack\n- TypeScript\n- React\n- PostgreSQL\n\n## Testing Requirements\n\n- Write tests before or alongside feature implementation\n- Maintain minimum 80% code coverage\n- Include unit, integration, and e2e tests\n- Mock external dependencies in tests\n\n## Error Handling Patterns\n\n- Implement comprehensive error handling from the start\n- Log errors with context (user ID, request ID, timestamp)\n- Provide helpful error messages to users\n- Never expose sensitive information in error messages\n\n## Performance Guidelines\n\n[Add performance guidelines specific to your project]\n",
|
||||
"sections_added": ["Testing Requirements", "Error Handling Patterns", "Performance Guidelines"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "validate_existing",
|
||||
"output": {
|
||||
"valid": true,
|
||||
"validation_results": {
|
||||
"length": {
|
||||
"check": "file_length",
|
||||
"status": "pass",
|
||||
"message": "File length is appropriate (19 lines)",
|
||||
"severity": "info",
|
||||
"actual_value": 19,
|
||||
"expected_range": "20-300 lines"
|
||||
},
|
||||
"structure": {
|
||||
"check": "file_structure",
|
||||
"status": "pass",
|
||||
"message": "Structure validation complete",
|
||||
"severity": "info",
|
||||
"errors": [],
|
||||
"warnings": [],
|
||||
"sections_found": 5
|
||||
},
|
||||
"formatting": {
|
||||
"check": "markdown_formatting",
|
||||
"status": "pass",
|
||||
"message": "Formatting validation complete",
|
||||
"severity": "low",
|
||||
"errors": [],
|
||||
"warnings": []
|
||||
},
|
||||
"completeness": {
|
||||
"check": "content_completeness",
|
||||
"status": "pass",
|
||||
"message": "Completeness validation complete",
|
||||
"severity": "medium",
|
||||
"errors": [],
|
||||
"warnings": [],
|
||||
"has_code_examples": false,
|
||||
"has_links": false,
|
||||
"has_lists": true,
|
||||
"tech_stack_mentioned": true
|
||||
},
|
||||
"anti_patterns": {
|
||||
"check": "anti_patterns",
|
||||
"status": "pass",
|
||||
"message": "No anti-patterns detected",
|
||||
"severity": "info",
|
||||
"detected_patterns": []
|
||||
}
|
||||
},
|
||||
"errors": [],
|
||||
"warnings": [
|
||||
"No code examples found - consider adding examples for clarity",
|
||||
"No links found - consider linking to external documentation"
|
||||
],
|
||||
"pass_count": 5,
|
||||
"fail_count": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
"""
|
||||
CLAUDE.md Content Generator
|
||||
|
||||
Generates new CLAUDE.md files or enhances existing ones based on templates and analysis.
|
||||
Supports modular architecture with context-specific files.
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Any, Optional
|
||||
from template_selector import TemplateSelector
|
||||
import re
|
||||
|
||||
|
||||
class ContentGenerator:
|
||||
"""Generates and enhances CLAUDE.md files based on project context."""
|
||||
|
||||
def __init__(self, project_context: Dict[str, Any]):
|
||||
"""
|
||||
Initialize content generator with project context.
|
||||
|
||||
Args:
|
||||
project_context: Dictionary containing project type, tech_stack, team_size, etc.
|
||||
"""
|
||||
self.project_context = project_context
|
||||
self.template_selector = TemplateSelector(project_context)
|
||||
|
||||
def generate_root_file(self) -> str:
|
||||
"""
|
||||
Generate root CLAUDE.md file (navigation hub).
|
||||
|
||||
Returns:
|
||||
Complete CLAUDE.md content as string
|
||||
"""
|
||||
template = self.template_selector.select_template()
|
||||
|
||||
# Use template selector's customization
|
||||
if template.get('modular_recommended'):
|
||||
return self._generate_modular_root(template)
|
||||
else:
|
||||
return self._generate_standalone_file(template)
|
||||
|
||||
def _generate_modular_root(self, template: Dict[str, Any]) -> str:
|
||||
"""Generate root file for modular architecture (navigation hub)."""
|
||||
lines = []
|
||||
|
||||
# Title
|
||||
lines.append("# CLAUDE.md")
|
||||
lines.append("")
|
||||
lines.append(f"This file provides top-level guidance for Claude Code when working with this {self.project_context.get('type', 'project')}.")
|
||||
lines.append("")
|
||||
|
||||
# Quick Navigation
|
||||
lines.append("## Quick Navigation")
|
||||
lines.append("")
|
||||
lines.extend(self._generate_navigation_section(template))
|
||||
lines.append("")
|
||||
|
||||
# Core Principles (concise, 5-7 principles)
|
||||
lines.append("## Core Principles")
|
||||
lines.append("")
|
||||
principles = self._generate_core_principles(template, max_count=5)
|
||||
lines.extend(principles)
|
||||
lines.append("")
|
||||
|
||||
# Tech Stack (summary only)
|
||||
if self.project_context.get('tech_stack'):
|
||||
lines.append("## Tech Stack")
|
||||
lines.append("")
|
||||
lines.extend(self._generate_tech_stack_summary())
|
||||
lines.append("")
|
||||
|
||||
# Key Commands/Shortcuts
|
||||
lines.append("## Quick Reference")
|
||||
lines.append("")
|
||||
lines.extend(self._generate_quick_reference())
|
||||
lines.append("")
|
||||
|
||||
# Footer
|
||||
lines.append("---")
|
||||
lines.append("")
|
||||
lines.append("For detailed guidelines, see context-specific CLAUDE.md files in subdirectories.")
|
||||
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_standalone_file(self, template: Dict[str, Any]) -> str:
|
||||
"""Generate standalone CLAUDE.md file (all-in-one)."""
|
||||
return self.template_selector.customize_template(template)
|
||||
|
||||
def generate_context_file(self, context: str) -> str:
|
||||
"""
|
||||
Generate context-specific CLAUDE.md file (e.g., backend, frontend).
|
||||
|
||||
Args:
|
||||
context: Context name ('backend', 'frontend', 'database', etc.)
|
||||
|
||||
Returns:
|
||||
Context-specific CLAUDE.md content
|
||||
"""
|
||||
generators = {
|
||||
'backend': self._generate_backend_file,
|
||||
'frontend': self._generate_frontend_file,
|
||||
'database': self._generate_database_file,
|
||||
'docs': self._generate_docs_file,
|
||||
'.github': self._generate_github_file
|
||||
}
|
||||
|
||||
generator = generators.get(context, self._generate_generic_context_file)
|
||||
return generator()
|
||||
|
||||
def _generate_backend_file(self) -> str:
|
||||
"""Generate backend-specific CLAUDE.md."""
|
||||
lines = []
|
||||
lines.append("# Backend Development Guidelines")
|
||||
lines.append("")
|
||||
lines.append("This file provides guidance for backend development in this project.")
|
||||
lines.append("")
|
||||
|
||||
# API Design
|
||||
lines.append("## API Design")
|
||||
lines.append("")
|
||||
lines.append("- Use RESTful conventions for API endpoints")
|
||||
lines.append("- Implement proper HTTP status codes (200, 201, 400, 404, 500)")
|
||||
lines.append("- Version APIs when breaking changes are needed (/api/v1/, /api/v2/)")
|
||||
lines.append("- Document all endpoints with OpenAPI/Swagger")
|
||||
lines.append("")
|
||||
|
||||
# Database Guidelines
|
||||
lines.append("## Database Operations")
|
||||
lines.append("")
|
||||
lines.append("- Use migrations for all schema changes")
|
||||
lines.append("- Implement proper indexes for query performance")
|
||||
lines.append("- Use transactions for multi-step operations")
|
||||
lines.append("- Avoid N+1 queries - use joins or batch loading")
|
||||
lines.append("")
|
||||
|
||||
# Error Handling
|
||||
lines.append("## Error Handling")
|
||||
lines.append("")
|
||||
lines.append("- Implement global error handling middleware")
|
||||
lines.append("- Log errors with context (request ID, user ID, timestamp)")
|
||||
lines.append("- Return consistent error response format")
|
||||
lines.append("- Never expose stack traces to clients in production")
|
||||
lines.append("")
|
||||
|
||||
# Testing
|
||||
lines.append("## Testing Requirements")
|
||||
lines.append("")
|
||||
lines.append("- Write unit tests for business logic")
|
||||
lines.append("- Write integration tests for API endpoints")
|
||||
lines.append("- Mock external services in tests")
|
||||
lines.append("- Aim for 80%+ code coverage")
|
||||
lines.append("")
|
||||
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_frontend_file(self) -> str:
|
||||
"""Generate frontend-specific CLAUDE.md."""
|
||||
lines = []
|
||||
lines.append("# Frontend Development Guidelines")
|
||||
lines.append("")
|
||||
lines.append("This file provides guidance for frontend development in this project.")
|
||||
lines.append("")
|
||||
|
||||
# Component Standards
|
||||
lines.append("## Component Standards")
|
||||
lines.append("")
|
||||
tech_stack = [t.lower() for t in self.project_context.get('tech_stack', [])]
|
||||
|
||||
if 'react' in tech_stack:
|
||||
lines.append("- Prefer functional components with hooks over class components")
|
||||
lines.append("- Use TypeScript for type safety")
|
||||
lines.append("- Keep components small and focused (< 200 lines)")
|
||||
lines.append("- Extract reusable logic into custom hooks")
|
||||
elif 'vue' in tech_stack:
|
||||
lines.append("- Use Composition API for complex components")
|
||||
lines.append("- Keep components small and focused (< 200 lines)")
|
||||
lines.append("- Use TypeScript with Vue 3")
|
||||
lines.append("- Extract reusable logic into composables")
|
||||
else:
|
||||
lines.append("- Keep components small and focused")
|
||||
lines.append("- Extract reusable logic into utilities")
|
||||
lines.append("- Use TypeScript for type safety")
|
||||
lines.append("")
|
||||
|
||||
# State Management
|
||||
lines.append("## State Management")
|
||||
lines.append("")
|
||||
lines.append("- Keep component state local when possible")
|
||||
lines.append("- Use global state only for truly shared data")
|
||||
lines.append("- Avoid prop drilling - use context/store for deep state")
|
||||
lines.append("- Document state shape and update patterns")
|
||||
lines.append("")
|
||||
|
||||
# Styling
|
||||
lines.append("## Styling Guidelines")
|
||||
lines.append("")
|
||||
lines.append("- Use consistent naming conventions (BEM, CSS Modules, etc.)")
|
||||
lines.append("- Avoid inline styles except for dynamic values")
|
||||
lines.append("- Use design tokens for colors, spacing, typography")
|
||||
lines.append("- Ensure responsive design for all breakpoints")
|
||||
lines.append("")
|
||||
|
||||
# Performance
|
||||
lines.append("## Performance Optimization")
|
||||
lines.append("")
|
||||
lines.append("- Lazy load routes and heavy components")
|
||||
lines.append("- Optimize images (use WebP, lazy loading)")
|
||||
lines.append("- Minimize bundle size - code split where possible")
|
||||
lines.append("- Use memoization for expensive calculations")
|
||||
lines.append("")
|
||||
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_database_file(self) -> str:
|
||||
"""Generate database-specific CLAUDE.md."""
|
||||
lines = []
|
||||
lines.append("# Database Guidelines")
|
||||
lines.append("")
|
||||
lines.append("This file provides guidance for database operations and migrations.")
|
||||
lines.append("")
|
||||
|
||||
# Schema Design
|
||||
lines.append("## Schema Design")
|
||||
lines.append("")
|
||||
lines.append("- Use meaningful table and column names")
|
||||
lines.append("- Always include created_at and updated_at timestamps")
|
||||
lines.append("- Use proper foreign key constraints")
|
||||
lines.append("- Add indexes for frequently queried columns")
|
||||
lines.append("")
|
||||
|
||||
# Migrations
|
||||
lines.append("## Migration Guidelines")
|
||||
lines.append("")
|
||||
lines.append("- Never edit existing migrations - create new ones")
|
||||
lines.append("- Test migrations on copy of production data")
|
||||
lines.append("- Include both up and down migrations")
|
||||
lines.append("- Document breaking changes in migration comments")
|
||||
lines.append("")
|
||||
|
||||
# Query Optimization
|
||||
lines.append("## Query Optimization")
|
||||
lines.append("")
|
||||
lines.append("- Use EXPLAIN to analyze slow queries")
|
||||
lines.append("- Avoid SELECT * - specify needed columns")
|
||||
lines.append("- Use appropriate JOIN types")
|
||||
lines.append("- Limit result sets with pagination")
|
||||
lines.append("")
|
||||
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_docs_file(self) -> str:
|
||||
"""Generate documentation-specific CLAUDE.md."""
|
||||
lines = []
|
||||
lines.append("# Documentation Guidelines")
|
||||
lines.append("")
|
||||
lines.append("This file provides guidance for project documentation.")
|
||||
lines.append("")
|
||||
|
||||
lines.append("## Documentation Standards")
|
||||
lines.append("")
|
||||
lines.append("- Keep README.md updated with setup instructions")
|
||||
lines.append("- Document all public APIs with examples")
|
||||
lines.append("- Include architecture diagrams for complex systems")
|
||||
lines.append("- Maintain changelog with semantic versioning")
|
||||
lines.append("")
|
||||
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_github_file(self) -> str:
|
||||
"""Generate .github-specific CLAUDE.md for CI/CD."""
|
||||
lines = []
|
||||
lines.append("# CI/CD Workflows")
|
||||
lines.append("")
|
||||
lines.append("This file provides guidance for GitHub Actions and CI/CD processes.")
|
||||
lines.append("")
|
||||
|
||||
lines.append("## Workflow Guidelines")
|
||||
lines.append("")
|
||||
lines.append("- Run linting and tests on all pull requests")
|
||||
lines.append("- Automate deployments to staging on main branch")
|
||||
lines.append("- Require manual approval for production deployments")
|
||||
lines.append("- Cache dependencies to speed up builds")
|
||||
lines.append("")
|
||||
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_generic_context_file(self) -> str:
|
||||
"""Generate generic context-specific file."""
|
||||
return "# Context-Specific Guidelines\n\n[Add guidelines specific to this context]\n"
|
||||
|
||||
def generate_section(self, section_name: str) -> str:
|
||||
"""
|
||||
Generate a specific section for CLAUDE.md.
|
||||
|
||||
Args:
|
||||
section_name: Name of section to generate
|
||||
|
||||
Returns:
|
||||
Section content as string
|
||||
"""
|
||||
generators = {
|
||||
'Core Principles': self._generate_core_principles_section,
|
||||
'Tech Stack': self._generate_tech_stack_section,
|
||||
'Workflow Instructions': self._generate_workflow_section,
|
||||
'Testing Requirements': self._generate_testing_section,
|
||||
'Error Handling': self._generate_error_handling_section,
|
||||
'Documentation Standards': self._generate_documentation_section
|
||||
}
|
||||
|
||||
generator = generators.get(section_name, self._generate_generic_section)
|
||||
return generator(section_name)
|
||||
|
||||
def _generate_core_principles_section(self, section_name: str) -> str:
|
||||
"""Generate Core Principles section."""
|
||||
template = self.template_selector.select_template()
|
||||
lines = [f"## {section_name}", ""]
|
||||
lines.extend(self._generate_core_principles(template, max_count=7))
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_tech_stack_section(self, section_name: str) -> str:
|
||||
"""Generate Tech Stack section."""
|
||||
lines = [f"## {section_name}", ""]
|
||||
lines.extend(self._generate_tech_stack_summary())
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_workflow_section(self, section_name: str) -> str:
|
||||
"""Generate Workflow Instructions section."""
|
||||
lines = [f"## {section_name}", ""]
|
||||
|
||||
workflows = self.project_context.get('workflows', [])
|
||||
if workflows:
|
||||
for i, workflow in enumerate(workflows, 1):
|
||||
workflow_title = workflow.replace('_', ' ').title()
|
||||
lines.append(f"{i}. **{workflow_title}**: [Add {workflow} workflow description]")
|
||||
else:
|
||||
lines.append("[Add workflow instructions specific to your project]")
|
||||
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_testing_section(self, section_name: str) -> str:
|
||||
"""Generate Testing Requirements section."""
|
||||
lines = [f"## {section_name}", ""]
|
||||
lines.append("- Write tests before or alongside feature implementation")
|
||||
lines.append("- Maintain minimum 80% code coverage")
|
||||
lines.append("- Include unit, integration, and e2e tests")
|
||||
lines.append("- Mock external dependencies in tests")
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_error_handling_section(self, section_name: str) -> str:
|
||||
"""Generate Error Handling section."""
|
||||
lines = [f"## {section_name}", ""]
|
||||
lines.append("- Implement comprehensive error handling from the start")
|
||||
lines.append("- Log errors with context (user ID, request ID, timestamp)")
|
||||
lines.append("- Provide helpful error messages to users")
|
||||
lines.append("- Never expose sensitive information in error messages")
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_documentation_section(self, section_name: str) -> str:
|
||||
"""Generate Documentation Standards section."""
|
||||
lines = [f"## {section_name}", ""]
|
||||
lines.append("- Keep documentation in sync with code")
|
||||
lines.append("- Document all public APIs and interfaces")
|
||||
lines.append("- Include code examples in documentation")
|
||||
lines.append("- Update README.md with setup and usage instructions")
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_generic_section(self, section_name: str) -> str:
|
||||
"""Generate generic section placeholder."""
|
||||
return f"## {section_name}\n\n[Add {section_name.lower()} guidelines specific to your project]\n"
|
||||
|
||||
def merge_with_existing(self, existing_content: str, new_sections: List[str]) -> str:
|
||||
"""
|
||||
Merge new sections with existing CLAUDE.md content.
|
||||
|
||||
Args:
|
||||
existing_content: Current CLAUDE.md content
|
||||
new_sections: List of new sections to add
|
||||
|
||||
Returns:
|
||||
Merged content as string
|
||||
"""
|
||||
lines = existing_content.split('\n')
|
||||
existing_sections = self._extract_existing_sections(existing_content)
|
||||
|
||||
# Add new sections that don't already exist
|
||||
for new_section in new_sections:
|
||||
section_name = new_section.split('\n')[0].replace('## ', '')
|
||||
if section_name not in existing_sections:
|
||||
lines.append("")
|
||||
lines.append(new_section)
|
||||
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _extract_existing_sections(self, content: str) -> List[str]:
|
||||
"""Extract section names from existing content."""
|
||||
sections = []
|
||||
for line in content.split('\n'):
|
||||
if line.startswith('## '):
|
||||
sections.append(line[3:].strip())
|
||||
return sections
|
||||
|
||||
def _generate_navigation_section(self, template: Dict[str, Any]) -> List[str]:
|
||||
"""Generate navigation section for modular architecture."""
|
||||
project_type = self.project_context.get('type')
|
||||
links = []
|
||||
|
||||
if project_type == 'fullstack':
|
||||
links.append("- [Backend Guidelines](backend/CLAUDE.md)")
|
||||
links.append("- [Frontend Guidelines](frontend/CLAUDE.md)")
|
||||
links.append("- [Database Operations](database/CLAUDE.md)")
|
||||
|
||||
if 'cicd' in self.project_context.get('workflows', []):
|
||||
links.append("- [CI/CD Workflows](.github/CLAUDE.md)")
|
||||
|
||||
if not links:
|
||||
links.append("- [Add links to context-specific CLAUDE.md files]")
|
||||
|
||||
return links
|
||||
|
||||
def _generate_core_principles(self, template: Dict[str, Any], max_count: int = 7) -> List[str]:
|
||||
"""Generate core principles list."""
|
||||
principles = []
|
||||
workflows = self.project_context.get('workflows', [])
|
||||
|
||||
# Add workflow-based principles
|
||||
if 'tdd' in workflows:
|
||||
principles.append("1. **Test-Driven Development**: Write tests before implementation")
|
||||
|
||||
# Add tech-specific principles
|
||||
tech_custom = template.get('tech_customization', {})
|
||||
for guideline in tech_custom.get('specific_guidelines', [])[:3]:
|
||||
principle_num = len(principles) + 1
|
||||
principles.append(f"{principle_num}. **{guideline.split(':')[0] if ':' in guideline else 'Guideline'}**: {guideline}")
|
||||
|
||||
# Add generic essential principles
|
||||
generic = [
|
||||
"**Code Quality**: Maintain high code quality with clear, readable implementations",
|
||||
"**Documentation**: Keep documentation in sync with code changes",
|
||||
"**Error Handling**: Implement comprehensive error handling from the start",
|
||||
"**Performance**: Consider performance implications in implementation decisions",
|
||||
"**Security**: Follow security best practices and avoid common vulnerabilities"
|
||||
]
|
||||
|
||||
for principle in generic:
|
||||
if len(principles) >= max_count:
|
||||
break
|
||||
principle_num = len(principles) + 1
|
||||
principles.append(f"{principle_num}. {principle}")
|
||||
|
||||
return principles
|
||||
|
||||
def _generate_tech_stack_summary(self) -> List[str]:
|
||||
"""Generate tech stack summary."""
|
||||
lines = []
|
||||
template = self.template_selector.select_template()
|
||||
tech_custom = template.get('tech_customization', {})
|
||||
|
||||
if tech_custom.get('languages'):
|
||||
lines.append(f"- **Languages**: {', '.join(tech_custom['languages'])}")
|
||||
|
||||
if tech_custom.get('frameworks'):
|
||||
lines.append(f"- **Frameworks**: {', '.join(tech_custom['frameworks'])}")
|
||||
|
||||
if tech_custom.get('tools'):
|
||||
lines.append(f"- **Tools**: {', '.join(tech_custom['tools'])}")
|
||||
|
||||
if not lines:
|
||||
lines.append("- [Add your tech stack details here]")
|
||||
|
||||
return lines
|
||||
|
||||
def _generate_quick_reference(self) -> List[str]:
|
||||
"""Generate quick reference commands."""
|
||||
lines = []
|
||||
lines.append("```bash")
|
||||
lines.append("# Common development commands")
|
||||
lines.append("npm test # Run tests")
|
||||
lines.append("npm run lint # Run linter")
|
||||
lines.append("npm run build # Build for production")
|
||||
lines.append("```")
|
||||
return lines
|
||||
@@ -0,0 +1,109 @@
|
||||
{
|
||||
"examples": [
|
||||
{
|
||||
"scenario": "initialize_new_project",
|
||||
"description": "Interactive initialization workflow for new project without CLAUDE.md",
|
||||
"input": {
|
||||
"mode": "initialize",
|
||||
"exploration_results": {
|
||||
"files": ["package.json", "tsconfig.json", "README.md", ".github/workflows/ci.yml"],
|
||||
"directories": ["src", "backend", "frontend", "tests", ".github/workflows"],
|
||||
"file_contents": {
|
||||
"package.json": "{\"dependencies\": {\"react\": \"^18.0.0\", \"typescript\": \"^5.0.0\", \"express\": \"^4.18.0\"}}",
|
||||
"README.md": "# Full-Stack TypeScript Project"
|
||||
}
|
||||
},
|
||||
"user_confirmation": "yes"
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "analyze_existing",
|
||||
"description": "Analyze an existing CLAUDE.md file for quality and completeness",
|
||||
"input": {
|
||||
"mode": "analyze",
|
||||
"content": "# CLAUDE.md\n\nThis is a basic CLAUDE file.\n\n## Tech Stack\n- TypeScript\n- React\n- Node.js\n\n## Workflow\n- Use Git for version control\n- Write tests\n\n",
|
||||
"project_context": {
|
||||
"type": "web_app",
|
||||
"tech_stack": ["typescript", "react", "node"],
|
||||
"team_size": "small",
|
||||
"phase": "mvp"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "create_new_fullstack",
|
||||
"description": "Create new CLAUDE.md for a full-stack TypeScript project",
|
||||
"input": {
|
||||
"mode": "create",
|
||||
"project_context": {
|
||||
"type": "fullstack",
|
||||
"tech_stack": ["typescript", "react", "node", "postgresql", "docker"],
|
||||
"team_size": "small",
|
||||
"phase": "mvp",
|
||||
"workflows": ["tdd", "cicd", "documentation_first"]
|
||||
},
|
||||
"modular": true,
|
||||
"subdirectories": ["backend", "frontend", "database"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "enhance_with_missing_sections",
|
||||
"description": "Enhance existing file by adding missing sections",
|
||||
"input": {
|
||||
"mode": "enhance",
|
||||
"content": "# CLAUDE.md\n\n## Core Principles\n1. Write tests first\n2. Use TypeScript\n\n## Tech Stack\n- TypeScript\n- React\n- PostgreSQL\n",
|
||||
"project_context": {
|
||||
"type": "web_app",
|
||||
"tech_stack": ["typescript", "react", "postgresql"],
|
||||
"team_size": "medium",
|
||||
"phase": "production"
|
||||
},
|
||||
"add_sections": ["Testing Requirements", "Error Handling Patterns", "Performance Guidelines"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "create_modular_architecture",
|
||||
"description": "Create modular CLAUDE.md setup for large team",
|
||||
"input": {
|
||||
"mode": "create",
|
||||
"project_context": {
|
||||
"type": "api",
|
||||
"tech_stack": ["python", "fastapi", "postgresql", "redis", "docker", "kubernetes"],
|
||||
"team_size": "large",
|
||||
"phase": "enterprise",
|
||||
"workflows": ["tdd", "cicd", "agile"]
|
||||
},
|
||||
"modular": true,
|
||||
"subdirectories": ["backend", "database", "docs", ".github"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "validate_existing",
|
||||
"description": "Validate existing CLAUDE.md against best practices",
|
||||
"input": {
|
||||
"mode": "validate",
|
||||
"content": "# CLAUDE.md\n\nGuidance for development.\n\n## Core Principles\n\n1. Code quality matters\n2. Test everything\n3. Document changes\n\n## Tech Stack\n\n- React 18\n- TypeScript 5\n- Node 20\n- PostgreSQL 15\n\n## Workflow Instructions\n\n### Development Process\n\n1. Create feature branch\n2. Write tests\n3. Implement feature\n4. Create PR\n5. Code review\n6. Merge to main\n\n## Testing Requirements\n\n- Unit tests for all business logic\n- Integration tests for API endpoints\n- E2E tests for critical user flows\n- Minimum 80% code coverage\n\n## Error Handling\n\n- Use try-catch blocks\n- Log errors with context\n- Return meaningful error messages\n- Never expose sensitive data\n\n",
|
||||
"project_context": {
|
||||
"type": "fullstack",
|
||||
"tech_stack": ["typescript", "react", "node", "postgresql"],
|
||||
"team_size": "small",
|
||||
"phase": "production"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"scenario": "generate_context_specific",
|
||||
"description": "Generate backend-specific CLAUDE.md file",
|
||||
"input": {
|
||||
"mode": "generate_context",
|
||||
"context": "backend",
|
||||
"project_context": {
|
||||
"type": "api",
|
||||
"tech_stack": ["python", "fastapi", "postgresql"],
|
||||
"team_size": "small",
|
||||
"phase": "mvp"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
"""
|
||||
CLAUDE.md Template Selector
|
||||
|
||||
Selects appropriate CLAUDE.md templates based on project context.
|
||||
Provides intelligent template selection, customization, and recommendations.
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Any, Optional
|
||||
|
||||
|
||||
class TemplateSelector:
|
||||
"""Selects and customizes CLAUDE.md templates based on project context."""
|
||||
|
||||
# Template definitions by project type
|
||||
PROJECT_TEMPLATES = {
|
||||
"web_app": {
|
||||
"focus": "Frontend components, UI/UX, state management",
|
||||
"sections": [
|
||||
"Quick Navigation", "Core Principles", "Component Standards",
|
||||
"State Management", "Styling Guidelines", "Testing Requirements",
|
||||
"Performance Optimization", "Accessibility"
|
||||
],
|
||||
"tech_hints": ["react", "vue", "angular", "svelte"]
|
||||
},
|
||||
"api": {
|
||||
"focus": "Backend services, REST/GraphQL, database operations",
|
||||
"sections": [
|
||||
"Quick Navigation", "Core Principles", "API Design",
|
||||
"Database Guidelines", "Error Handling", "Testing Requirements",
|
||||
"Security Practices", "Documentation Standards"
|
||||
],
|
||||
"tech_hints": ["node", "python", "go", "java", "fastapi", "express"]
|
||||
},
|
||||
"fullstack": {
|
||||
"focus": "Integrated frontend + backend, end-to-end workflows",
|
||||
"sections": [
|
||||
"Quick Navigation", "Core Principles", "Frontend Guidelines",
|
||||
"Backend Guidelines", "Database Operations", "API Integration",
|
||||
"Testing Strategy", "Deployment Process"
|
||||
],
|
||||
"tech_hints": ["next.js", "django", "rails", "laravel"]
|
||||
},
|
||||
"cli": {
|
||||
"focus": "Command-line interface, user interaction, scripting",
|
||||
"sections": [
|
||||
"Quick Navigation", "Core Principles", "Command Structure",
|
||||
"Argument Parsing", "Error Handling", "Testing Requirements",
|
||||
"Documentation Standards", "Distribution"
|
||||
],
|
||||
"tech_hints": ["click", "commander", "cobra", "clap"]
|
||||
},
|
||||
"library": {
|
||||
"focus": "Reusable package, API design, versioning",
|
||||
"sections": [
|
||||
"Quick Navigation", "Core Principles", "Public API Design",
|
||||
"Versioning Strategy", "Testing Requirements", "Documentation Standards",
|
||||
"Breaking Changes", "Release Process"
|
||||
],
|
||||
"tech_hints": ["npm", "pypi", "crates.io", "maven"]
|
||||
},
|
||||
"mobile": {
|
||||
"focus": "Mobile UI, platform-specific code, performance",
|
||||
"sections": [
|
||||
"Quick Navigation", "Core Principles", "Platform Guidelines",
|
||||
"Navigation Patterns", "State Management", "Performance Optimization",
|
||||
"Testing Requirements", "Release Process"
|
||||
],
|
||||
"tech_hints": ["react-native", "flutter", "ios", "android"]
|
||||
},
|
||||
"desktop": {
|
||||
"focus": "Desktop application, native integration, distribution",
|
||||
"sections": [
|
||||
"Quick Navigation", "Core Principles", "Window Management",
|
||||
"Native Integration", "State Management", "Testing Requirements",
|
||||
"Build Process", "Distribution"
|
||||
],
|
||||
"tech_hints": ["electron", "tauri", "qt", "gtk"]
|
||||
}
|
||||
}
|
||||
|
||||
# Team size templates
|
||||
TEAM_SIZE_TEMPLATES = {
|
||||
"solo": {
|
||||
"target_lines": 75,
|
||||
"complexity": "minimal",
|
||||
"focus": "Efficiency, personal workflow",
|
||||
"detail_level": "concise"
|
||||
},
|
||||
"small": {
|
||||
"target_lines": 125,
|
||||
"complexity": "core",
|
||||
"focus": "Core guidelines, collaboration basics",
|
||||
"detail_level": "moderate"
|
||||
},
|
||||
"medium": {
|
||||
"target_lines": 200,
|
||||
"complexity": "detailed",
|
||||
"focus": "Team coordination, process standardization",
|
||||
"detail_level": "comprehensive"
|
||||
},
|
||||
"large": {
|
||||
"target_lines": 275,
|
||||
"complexity": "comprehensive",
|
||||
"focus": "Enterprise standards, governance",
|
||||
"detail_level": "extensive"
|
||||
}
|
||||
}
|
||||
|
||||
# Development phase templates
|
||||
PHASE_TEMPLATES = {
|
||||
"prototype": {
|
||||
"priority": ["Quick start", "Flexibility", "Rapid iteration"],
|
||||
"skip_sections": ["Security Practices", "Performance Optimization"]
|
||||
},
|
||||
"mvp": {
|
||||
"priority": ["Core features", "Testing basics", "Documentation"],
|
||||
"skip_sections": []
|
||||
},
|
||||
"production": {
|
||||
"priority": ["Quality", "Security", "Performance", "Monitoring"],
|
||||
"skip_sections": []
|
||||
},
|
||||
"enterprise": {
|
||||
"priority": ["Compliance", "Security", "Scalability", "Governance"],
|
||||
"skip_sections": []
|
||||
}
|
||||
}
|
||||
|
||||
def __init__(self, project_context: Dict[str, Any]):
|
||||
"""
|
||||
Initialize template selector with project context.
|
||||
|
||||
Args:
|
||||
project_context: Dictionary containing project type, tech_stack, team_size, etc.
|
||||
"""
|
||||
self.project_type = project_context.get('type', 'web_app')
|
||||
self.tech_stack = project_context.get('tech_stack', [])
|
||||
self.team_size = project_context.get('team_size', 'small')
|
||||
self.phase = project_context.get('phase', 'mvp')
|
||||
self.workflows = project_context.get('workflows', [])
|
||||
self.modular = project_context.get('modular', False)
|
||||
|
||||
def select_template(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Select the most appropriate template based on project context.
|
||||
|
||||
Returns:
|
||||
Template configuration dictionary
|
||||
"""
|
||||
# Get base template for project type
|
||||
project_template = self.PROJECT_TEMPLATES.get(
|
||||
self.project_type,
|
||||
self.PROJECT_TEMPLATES['web_app']
|
||||
)
|
||||
|
||||
# Get team size configuration
|
||||
team_config = self.TEAM_SIZE_TEMPLATES.get(
|
||||
self.team_size,
|
||||
self.TEAM_SIZE_TEMPLATES['small']
|
||||
)
|
||||
|
||||
# Get phase configuration
|
||||
phase_config = self.PHASE_TEMPLATES.get(
|
||||
self.phase,
|
||||
self.PHASE_TEMPLATES['mvp']
|
||||
)
|
||||
|
||||
# Combine into final template
|
||||
return {
|
||||
"project_type": self.project_type,
|
||||
"team_size": self.team_size,
|
||||
"phase": self.phase,
|
||||
"target_lines": team_config['target_lines'],
|
||||
"complexity": team_config['complexity'],
|
||||
"sections": self._select_sections(
|
||||
project_template['sections'],
|
||||
phase_config
|
||||
),
|
||||
"focus": project_template['focus'],
|
||||
"detail_level": team_config['detail_level'],
|
||||
"tech_customization": self._get_tech_customization(),
|
||||
"modular_recommended": self.recommend_modular_structure()
|
||||
}
|
||||
|
||||
def _select_sections(self, base_sections: List[str], phase_config: Dict[str, Any]) -> List[str]:
|
||||
"""
|
||||
Select sections based on phase and priorities.
|
||||
|
||||
Args:
|
||||
base_sections: List of base section names
|
||||
phase_config: Phase configuration dictionary
|
||||
|
||||
Returns:
|
||||
Filtered list of sections
|
||||
"""
|
||||
skip_sections = phase_config.get('skip_sections', [])
|
||||
return [section for section in base_sections if section not in skip_sections]
|
||||
|
||||
def _get_tech_customization(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Get tech stack-specific customizations.
|
||||
|
||||
Returns:
|
||||
Tech customization configuration
|
||||
"""
|
||||
customizations = {
|
||||
"languages": [],
|
||||
"frameworks": [],
|
||||
"tools": [],
|
||||
"specific_guidelines": []
|
||||
}
|
||||
|
||||
# Detect languages
|
||||
lang_map = {
|
||||
'typescript': 'TypeScript',
|
||||
'javascript': 'JavaScript',
|
||||
'python': 'Python',
|
||||
'go': 'Go',
|
||||
'rust': 'Rust',
|
||||
'java': 'Java',
|
||||
'kotlin': 'Kotlin',
|
||||
'ruby': 'Ruby',
|
||||
'php': 'PHP'
|
||||
}
|
||||
|
||||
for tech in self.tech_stack:
|
||||
tech_lower = tech.lower()
|
||||
if tech_lower in lang_map:
|
||||
customizations['languages'].append(lang_map[tech_lower])
|
||||
|
||||
# Detect frameworks
|
||||
framework_map = {
|
||||
'react': 'React',
|
||||
'vue': 'Vue',
|
||||
'angular': 'Angular',
|
||||
'svelte': 'Svelte',
|
||||
'next.js': 'Next.js',
|
||||
'django': 'Django',
|
||||
'fastapi': 'FastAPI',
|
||||
'flask': 'Flask',
|
||||
'express': 'Express',
|
||||
'gin': 'Gin',
|
||||
'echo': 'Echo',
|
||||
'spring': 'Spring Boot',
|
||||
'rails': 'Rails'
|
||||
}
|
||||
|
||||
for tech in self.tech_stack:
|
||||
tech_lower = tech.lower()
|
||||
if tech_lower in framework_map:
|
||||
customizations['frameworks'].append(framework_map[tech_lower])
|
||||
|
||||
# Detect tools
|
||||
tool_map = {
|
||||
'docker': 'Docker',
|
||||
'kubernetes': 'Kubernetes',
|
||||
'postgresql': 'PostgreSQL',
|
||||
'mongodb': 'MongoDB',
|
||||
'redis': 'Redis',
|
||||
'git': 'Git',
|
||||
'github': 'GitHub',
|
||||
'gitlab': 'GitLab'
|
||||
}
|
||||
|
||||
for tech in self.tech_stack:
|
||||
tech_lower = tech.lower()
|
||||
if tech_lower in tool_map:
|
||||
customizations['tools'].append(tool_map[tech_lower])
|
||||
|
||||
# Add specific guidelines based on tech stack
|
||||
if 'typescript' in [t.lower() for t in self.tech_stack]:
|
||||
customizations['specific_guidelines'].append(
|
||||
"Use TypeScript strict mode throughout the project"
|
||||
)
|
||||
|
||||
if 'react' in [t.lower() for t in self.tech_stack]:
|
||||
customizations['specific_guidelines'].append(
|
||||
"Prefer functional components with hooks over class components"
|
||||
)
|
||||
|
||||
if 'python' in [t.lower() for t in self.tech_stack]:
|
||||
customizations['specific_guidelines'].append(
|
||||
"Use type hints for all function signatures (Python 3.10+)"
|
||||
)
|
||||
|
||||
if 'docker' in [t.lower() for t in self.tech_stack]:
|
||||
customizations['specific_guidelines'].append(
|
||||
"Use multi-stage Dockerfiles for optimized image size"
|
||||
)
|
||||
|
||||
return customizations
|
||||
|
||||
def recommend_modular_structure(self) -> bool:
|
||||
"""
|
||||
Determine if modular CLAUDE.md structure is recommended.
|
||||
|
||||
Returns:
|
||||
True if modular structure recommended, False otherwise
|
||||
"""
|
||||
# Recommend modular structure for:
|
||||
# 1. Full-stack projects
|
||||
# 2. Large teams
|
||||
# 3. Production/enterprise phase
|
||||
# 4. Projects with 3+ major tech stack components
|
||||
|
||||
if self.project_type == 'fullstack':
|
||||
return True
|
||||
|
||||
if self.team_size in ['medium', 'large']:
|
||||
return True
|
||||
|
||||
if self.phase in ['production', 'enterprise']:
|
||||
return True
|
||||
|
||||
if len(self.tech_stack) >= 3:
|
||||
return True
|
||||
|
||||
# User explicitly requested modular
|
||||
if self.modular:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def customize_template(self, template: Dict[str, Any]) -> str:
|
||||
"""
|
||||
Generate customized CLAUDE.md content based on template.
|
||||
|
||||
Args:
|
||||
template: Template configuration dictionary
|
||||
|
||||
Returns:
|
||||
Customized CLAUDE.md content as string
|
||||
"""
|
||||
lines = []
|
||||
|
||||
# Add title
|
||||
lines.append("# CLAUDE.md")
|
||||
lines.append("")
|
||||
lines.append(f"This file provides guidance for Claude Code when working with this {self.project_type} project.")
|
||||
lines.append("")
|
||||
|
||||
# Add modular navigation if recommended
|
||||
if template.get('modular_recommended'):
|
||||
lines.append("## Quick Navigation")
|
||||
lines.append("")
|
||||
lines.extend(self._generate_navigation_links())
|
||||
lines.append("")
|
||||
|
||||
# Add core principles
|
||||
lines.append("## Core Principles")
|
||||
lines.append("")
|
||||
lines.extend(self._generate_core_principles(template))
|
||||
lines.append("")
|
||||
|
||||
# Add tech stack section
|
||||
if self.tech_stack:
|
||||
lines.append("## Tech Stack")
|
||||
lines.append("")
|
||||
lines.extend(self._generate_tech_stack_section(template))
|
||||
lines.append("")
|
||||
|
||||
# Add workflow section if workflows specified
|
||||
if self.workflows:
|
||||
lines.append("## Workflow Instructions")
|
||||
lines.append("")
|
||||
lines.extend(self._generate_workflow_section())
|
||||
lines.append("")
|
||||
|
||||
# Add additional sections based on template
|
||||
for section in template['sections']:
|
||||
if section not in ["Quick Navigation", "Core Principles", "Tech Stack", "Workflow Instructions"]:
|
||||
lines.append(f"## {section}")
|
||||
lines.append("")
|
||||
lines.append(f"[Add {section.lower()} guidelines specific to your project]")
|
||||
lines.append("")
|
||||
|
||||
return '\n'.join(lines)
|
||||
|
||||
def _generate_navigation_links(self) -> List[str]:
|
||||
"""Generate navigation links for modular structure."""
|
||||
links = []
|
||||
|
||||
if self.project_type == 'fullstack':
|
||||
links.append("- [Backend Guidelines](backend/CLAUDE.md)")
|
||||
links.append("- [Frontend Guidelines](frontend/CLAUDE.md)")
|
||||
links.append("- [Database Operations](database/CLAUDE.md)")
|
||||
|
||||
if 'cicd' in self.workflows:
|
||||
links.append("- [CI/CD Workflows](.github/CLAUDE.md)")
|
||||
|
||||
if not links:
|
||||
links.append("- [Context-specific guides will be linked here]")
|
||||
|
||||
return links
|
||||
|
||||
def _generate_core_principles(self, template: Dict[str, Any]) -> List[str]:
|
||||
"""Generate core principles based on template."""
|
||||
principles = []
|
||||
|
||||
# Add workflow-specific principles
|
||||
if 'tdd' in self.workflows:
|
||||
principles.append("1. **Test-Driven Development**: Write tests before implementation")
|
||||
|
||||
# Add tech-specific principles
|
||||
tech_custom = template.get('tech_customization', {})
|
||||
for i, guideline in enumerate(tech_custom.get('specific_guidelines', [])[:3], start=len(principles)+1):
|
||||
principles.append(f"{i}. **{guideline.split(':')[0] if ':' in guideline else 'Guideline'}**: {guideline}")
|
||||
|
||||
# Add generic principles if needed
|
||||
if len(principles) < 3:
|
||||
generic = [
|
||||
"**Code Quality**: Maintain high code quality with clear, readable implementations",
|
||||
"**Documentation**: Keep documentation in sync with code changes",
|
||||
"**Error Handling**: Implement comprehensive error handling from the start"
|
||||
]
|
||||
for i, principle in enumerate(generic[:3-len(principles)], start=len(principles)+1):
|
||||
principles.append(f"{i}. {principle}")
|
||||
|
||||
return principles
|
||||
|
||||
def _generate_tech_stack_section(self, template: Dict[str, Any]) -> List[str]:
|
||||
"""Generate tech stack section."""
|
||||
lines = []
|
||||
tech_custom = template.get('tech_customization', {})
|
||||
|
||||
if tech_custom.get('languages'):
|
||||
lines.append(f"- **Languages**: {', '.join(tech_custom['languages'])}")
|
||||
|
||||
if tech_custom.get('frameworks'):
|
||||
lines.append(f"- **Frameworks**: {', '.join(tech_custom['frameworks'])}")
|
||||
|
||||
if tech_custom.get('tools'):
|
||||
lines.append(f"- **Tools**: {', '.join(tech_custom['tools'])}")
|
||||
|
||||
if not lines:
|
||||
lines.append("- [Add your tech stack details here]")
|
||||
|
||||
return lines
|
||||
|
||||
def _generate_workflow_section(self) -> List[str]:
|
||||
"""Generate workflow section based on specified workflows."""
|
||||
lines = []
|
||||
|
||||
workflow_descriptions = {
|
||||
'tdd': "1. **Test-Driven Development**: Write tests first, then implement features to pass tests",
|
||||
'cicd': "2. **CI/CD**: All changes go through automated testing and deployment pipelines",
|
||||
'documentation_first': "3. **Documentation First**: Document APIs and interfaces before implementation",
|
||||
'agile': "4. **Agile Process**: Work in sprints with regular retrospectives and planning"
|
||||
}
|
||||
|
||||
for i, workflow in enumerate(self.workflows, start=1):
|
||||
if workflow in workflow_descriptions:
|
||||
lines.append(workflow_descriptions[workflow])
|
||||
else:
|
||||
lines.append(f"{i}. **{workflow.replace('_', ' ').title()}**: [Add workflow description]")
|
||||
|
||||
return lines
|
||||
|
||||
def determine_complexity(self) -> str:
|
||||
"""
|
||||
Determine appropriate complexity level for the template.
|
||||
|
||||
Returns:
|
||||
Complexity level: 'minimal', 'core', 'detailed', or 'comprehensive'
|
||||
"""
|
||||
team_config = self.TEAM_SIZE_TEMPLATES.get(self.team_size, self.TEAM_SIZE_TEMPLATES['small'])
|
||||
return team_config['complexity']
|
||||
@@ -0,0 +1,429 @@
|
||||
"""
|
||||
CLAUDE.md Best Practices Validator
|
||||
|
||||
Validates CLAUDE.md files against Anthropic guidelines and community best practices.
|
||||
Provides detailed validation reports with pass/fail status and improvement suggestions.
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Any, Tuple
|
||||
import re
|
||||
|
||||
|
||||
class BestPracticesValidator:
|
||||
"""Validates CLAUDE.md files against best practices and guidelines."""
|
||||
|
||||
# Maximum recommended line count
|
||||
MAX_RECOMMENDED_LINES = 300
|
||||
WARNING_THRESHOLD_LINES = 200
|
||||
|
||||
# Minimum content requirements
|
||||
MIN_LINES = 20
|
||||
MIN_SECTIONS = 3
|
||||
|
||||
# Required sections for a complete CLAUDE.md
|
||||
REQUIRED_SECTIONS = [
|
||||
"Core Principles",
|
||||
"Workflow"
|
||||
]
|
||||
|
||||
# Anti-patterns to detect
|
||||
ANTI_PATTERNS = [
|
||||
{
|
||||
"name": "hardcoded_secrets",
|
||||
"patterns": [
|
||||
r'api[_-]?key\s*=\s*["\'][a-zA-Z0-9]{20,}["\']',
|
||||
r'password\s*=\s*["\'][^"\']+["\']',
|
||||
r'secret\s*=\s*["\'][^"\']+["\']',
|
||||
r'token\s*=\s*["\'][a-zA-Z0-9]{20,}["\']'
|
||||
],
|
||||
"message": "Potential hardcoded secrets detected (API keys, passwords, tokens)"
|
||||
},
|
||||
{
|
||||
"name": "generic_content",
|
||||
"patterns": [
|
||||
r'\[TODO\]',
|
||||
r'\[TBD\]',
|
||||
r'\[PLACEHOLDER\]',
|
||||
r'\[Insert.*?\]',
|
||||
r'\[Add.*?\]'
|
||||
],
|
||||
"message": "Generic placeholder content found - replace with specific guidance"
|
||||
},
|
||||
{
|
||||
"name": "duplicate_sections",
|
||||
"patterns": [],
|
||||
"message": "Duplicate section headings detected"
|
||||
},
|
||||
{
|
||||
"name": "broken_links",
|
||||
"patterns": [
|
||||
r'\[.*?\]\(\)',
|
||||
r'\[.*?\]\(#\)',
|
||||
r'\[.*?\]\(undefined\)'
|
||||
],
|
||||
"message": "Broken or empty markdown links detected"
|
||||
}
|
||||
]
|
||||
|
||||
def __init__(self, content: str, project_context: Dict[str, Any] = None):
|
||||
"""
|
||||
Initialize validator with CLAUDE.md content.
|
||||
|
||||
Args:
|
||||
content: Full text content of CLAUDE.md file
|
||||
project_context: Optional project context for advanced validation
|
||||
"""
|
||||
self.content = content
|
||||
self.lines = content.split('\n')
|
||||
self.line_count = len(self.lines)
|
||||
self.project_context = project_context or {}
|
||||
|
||||
def validate_all(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Run all validation checks.
|
||||
|
||||
Returns:
|
||||
Comprehensive validation report
|
||||
"""
|
||||
return {
|
||||
"valid": self._is_valid_overall(),
|
||||
"validation_results": {
|
||||
"length": self.validate_length(),
|
||||
"structure": self.validate_structure(),
|
||||
"formatting": self.validate_formatting(),
|
||||
"completeness": self.validate_completeness(),
|
||||
"anti_patterns": self._check_anti_patterns()
|
||||
},
|
||||
"errors": self._collect_errors(),
|
||||
"warnings": self._collect_warnings(),
|
||||
"pass_count": self._count_passes(),
|
||||
"fail_count": self._count_failures()
|
||||
}
|
||||
|
||||
def validate_length(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate file length against best practices.
|
||||
|
||||
Returns:
|
||||
Validation result for length check
|
||||
"""
|
||||
status = "pass"
|
||||
message = f"File length is appropriate ({self.line_count} lines)"
|
||||
severity = "info"
|
||||
|
||||
if self.line_count > self.MAX_RECOMMENDED_LINES:
|
||||
status = "fail"
|
||||
message = f"File exceeds maximum recommended length ({self.line_count} > {self.MAX_RECOMMENDED_LINES} lines)"
|
||||
severity = "high"
|
||||
elif self.line_count > self.WARNING_THRESHOLD_LINES:
|
||||
status = "warning"
|
||||
message = f"File is approaching maximum length ({self.line_count} lines, recommended < {self.WARNING_THRESHOLD_LINES})"
|
||||
severity = "medium"
|
||||
elif self.line_count < self.MIN_LINES:
|
||||
status = "fail"
|
||||
message = f"File is too short ({self.line_count} lines, minimum {self.MIN_LINES})"
|
||||
severity = "high"
|
||||
|
||||
return {
|
||||
"check": "file_length",
|
||||
"status": status,
|
||||
"message": message,
|
||||
"severity": severity,
|
||||
"actual_value": self.line_count,
|
||||
"expected_range": f"{self.MIN_LINES}-{self.MAX_RECOMMENDED_LINES} lines"
|
||||
}
|
||||
|
||||
def validate_structure(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate file structure and organization.
|
||||
|
||||
Returns:
|
||||
Validation result for structure check
|
||||
"""
|
||||
sections = self._extract_sections()
|
||||
errors = []
|
||||
warnings = []
|
||||
|
||||
# Check for main title
|
||||
if not self.content.strip().startswith('# '):
|
||||
errors.append("Missing main title (# CLAUDE.md)")
|
||||
|
||||
# Check for minimum sections
|
||||
if len(sections) < self.MIN_SECTIONS:
|
||||
errors.append(f"Too few sections ({len(sections)}, minimum {self.MIN_SECTIONS})")
|
||||
|
||||
# Check for required sections
|
||||
for required in self.REQUIRED_SECTIONS:
|
||||
if not any(required.lower() in section.lower() for section in sections):
|
||||
errors.append(f"Missing required section: '{required}'")
|
||||
|
||||
# Check for duplicate sections
|
||||
section_counts = {}
|
||||
for section in sections:
|
||||
section_lower = section.lower()
|
||||
section_counts[section_lower] = section_counts.get(section_lower, 0) + 1
|
||||
|
||||
duplicates = [s for s, count in section_counts.items() if count > 1]
|
||||
if duplicates:
|
||||
warnings.append(f"Duplicate sections found: {', '.join(duplicates)}")
|
||||
|
||||
# Determine overall status
|
||||
status = "pass"
|
||||
if errors:
|
||||
status = "fail"
|
||||
elif warnings:
|
||||
status = "warning"
|
||||
|
||||
return {
|
||||
"check": "file_structure",
|
||||
"status": status,
|
||||
"message": "Structure validation complete",
|
||||
"severity": "high" if errors else "medium" if warnings else "info",
|
||||
"errors": errors,
|
||||
"warnings": warnings,
|
||||
"sections_found": len(sections)
|
||||
}
|
||||
|
||||
def validate_formatting(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate markdown formatting quality.
|
||||
|
||||
Returns:
|
||||
Validation result for formatting check
|
||||
"""
|
||||
errors = []
|
||||
warnings = []
|
||||
|
||||
# Check for balanced code blocks
|
||||
code_block_count = self.content.count('```')
|
||||
if code_block_count % 2 != 0:
|
||||
errors.append("Unbalanced code blocks (unclosed ``` markers)")
|
||||
|
||||
# Check for proper heading hierarchy
|
||||
heading_levels = []
|
||||
for line in self.lines:
|
||||
if line.startswith('#'):
|
||||
level = len(line) - len(line.lstrip('#'))
|
||||
heading_levels.append(level)
|
||||
|
||||
if heading_levels and heading_levels[0] != 1:
|
||||
errors.append("First heading should be level 1 (# Title)")
|
||||
|
||||
# Check for heading level skipping (e.g., # → ###)
|
||||
for i in range(len(heading_levels) - 1):
|
||||
if heading_levels[i+1] - heading_levels[i] > 1:
|
||||
warnings.append(f"Heading level skips detected (h{heading_levels[i]} → h{heading_levels[i+1]})")
|
||||
break
|
||||
|
||||
# Check for consistent list formatting
|
||||
if '- ' in self.content and '* ' in self.content:
|
||||
warnings.append("Mixed list markers (- and *) - prefer consistent style")
|
||||
|
||||
# Check for trailing whitespace (sample check)
|
||||
lines_with_trailing_ws = sum(1 for line in self.lines if line.endswith(' ') and line.strip())
|
||||
if lines_with_trailing_ws > 5:
|
||||
warnings.append(f"Multiple lines with trailing whitespace ({lines_with_trailing_ws})")
|
||||
|
||||
status = "pass"
|
||||
if errors:
|
||||
status = "fail"
|
||||
elif warnings:
|
||||
status = "warning"
|
||||
|
||||
return {
|
||||
"check": "markdown_formatting",
|
||||
"status": status,
|
||||
"message": "Formatting validation complete",
|
||||
"severity": "medium" if errors else "low",
|
||||
"errors": errors,
|
||||
"warnings": warnings
|
||||
}
|
||||
|
||||
def validate_completeness(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Validate content completeness and quality.
|
||||
|
||||
Returns:
|
||||
Validation result for completeness check
|
||||
"""
|
||||
errors = []
|
||||
warnings = []
|
||||
|
||||
# Check for essential content types
|
||||
has_code_examples = '```' in self.content
|
||||
has_links = '[' in self.content and '](' in self.content
|
||||
has_lists = any(line.strip().startswith(('-', '*', '1.')) for line in self.lines)
|
||||
|
||||
if not has_code_examples:
|
||||
warnings.append("No code examples found - consider adding examples for clarity")
|
||||
|
||||
if not has_links:
|
||||
warnings.append("No links found - consider linking to external documentation")
|
||||
|
||||
if not has_lists:
|
||||
warnings.append("No lists found - consider using lists for better readability")
|
||||
|
||||
# Check for tech stack mention
|
||||
tech_keywords = [
|
||||
'typescript', 'javascript', 'python', 'react', 'vue', 'angular',
|
||||
'node', 'django', 'fastapi', 'go', 'rust', 'java'
|
||||
]
|
||||
content_lower = self.content.lower()
|
||||
tech_mentioned = any(keyword in content_lower for keyword in tech_keywords)
|
||||
|
||||
if not tech_mentioned:
|
||||
warnings.append("No specific technologies mentioned - add tech stack reference")
|
||||
|
||||
# Check for workflow mentions
|
||||
workflow_keywords = ['test', 'commit', 'deploy', 'review', 'documentation']
|
||||
workflow_mentioned = sum(1 for keyword in workflow_keywords if keyword in content_lower)
|
||||
|
||||
if workflow_mentioned < 2:
|
||||
warnings.append("Limited workflow guidance - consider adding development workflow instructions")
|
||||
|
||||
# Check for empty sections
|
||||
empty_section_pattern = r'##\s+[^\n]+\n\s*\n\s*##'
|
||||
if re.search(empty_section_pattern, self.content):
|
||||
errors.append("Empty sections detected - remove or populate with content")
|
||||
|
||||
status = "pass"
|
||||
if errors:
|
||||
status = "fail"
|
||||
elif len(warnings) >= 3:
|
||||
status = "warning"
|
||||
|
||||
return {
|
||||
"check": "content_completeness",
|
||||
"status": status,
|
||||
"message": "Completeness validation complete",
|
||||
"severity": "medium",
|
||||
"errors": errors,
|
||||
"warnings": warnings,
|
||||
"has_code_examples": has_code_examples,
|
||||
"has_links": has_links,
|
||||
"has_lists": has_lists,
|
||||
"tech_stack_mentioned": tech_mentioned
|
||||
}
|
||||
|
||||
def _check_anti_patterns(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Check for anti-patterns and bad practices.
|
||||
|
||||
Returns:
|
||||
Validation result for anti-pattern detection
|
||||
"""
|
||||
detected = []
|
||||
|
||||
for anti_pattern in self.ANTI_PATTERNS:
|
||||
if anti_pattern['name'] == 'duplicate_sections':
|
||||
# Handle duplicate sections separately
|
||||
sections = self._extract_sections()
|
||||
section_counts = {}
|
||||
for section in sections:
|
||||
section_lower = section.lower()
|
||||
section_counts[section_lower] = section_counts.get(section_lower, 0) + 1
|
||||
|
||||
if any(count > 1 for count in section_counts.values()):
|
||||
detected.append({
|
||||
"pattern": anti_pattern['name'],
|
||||
"message": anti_pattern['message']
|
||||
})
|
||||
else:
|
||||
# Check regex patterns
|
||||
for pattern in anti_pattern['patterns']:
|
||||
if re.search(pattern, self.content, re.IGNORECASE):
|
||||
detected.append({
|
||||
"pattern": anti_pattern['name'],
|
||||
"message": anti_pattern['message']
|
||||
})
|
||||
break # Only report each anti-pattern once
|
||||
|
||||
status = "pass" if not detected else "fail"
|
||||
severity = "high" if any(p['pattern'] == 'hardcoded_secrets' for p in detected) else "medium"
|
||||
|
||||
return {
|
||||
"check": "anti_patterns",
|
||||
"status": status,
|
||||
"message": f"{len(detected)} anti-pattern(s) detected" if detected else "No anti-patterns detected",
|
||||
"severity": severity,
|
||||
"detected_patterns": detected
|
||||
}
|
||||
|
||||
def _extract_sections(self) -> List[str]:
|
||||
"""Extract all section headings from content."""
|
||||
sections = []
|
||||
for line in self.lines:
|
||||
if line.startswith('## '):
|
||||
sections.append(line[3:].strip())
|
||||
return sections
|
||||
|
||||
def _is_valid_overall(self) -> bool:
|
||||
"""Determine if file passes overall validation."""
|
||||
length_result = self.validate_length()
|
||||
structure_result = self.validate_structure()
|
||||
|
||||
# File is valid if length and structure pass (formatting and completeness can have warnings)
|
||||
return (
|
||||
length_result['status'] != 'fail' and
|
||||
structure_result['status'] != 'fail'
|
||||
)
|
||||
|
||||
def _collect_errors(self) -> List[str]:
|
||||
"""Collect all errors from validation checks."""
|
||||
errors = []
|
||||
all_results = [
|
||||
self.validate_length(),
|
||||
self.validate_structure(),
|
||||
self.validate_formatting(),
|
||||
self.validate_completeness(),
|
||||
self._check_anti_patterns()
|
||||
]
|
||||
|
||||
for result in all_results:
|
||||
if result['status'] == 'fail':
|
||||
if 'errors' in result:
|
||||
errors.extend(result['errors'])
|
||||
else:
|
||||
errors.append(result['message'])
|
||||
|
||||
return errors
|
||||
|
||||
def _collect_warnings(self) -> List[str]:
|
||||
"""Collect all warnings from validation checks."""
|
||||
warnings = []
|
||||
all_results = [
|
||||
self.validate_length(),
|
||||
self.validate_structure(),
|
||||
self.validate_formatting(),
|
||||
self.validate_completeness()
|
||||
]
|
||||
|
||||
for result in all_results:
|
||||
if 'warnings' in result:
|
||||
warnings.extend(result['warnings'])
|
||||
elif result['status'] == 'warning':
|
||||
warnings.append(result['message'])
|
||||
|
||||
return warnings
|
||||
|
||||
def _count_passes(self) -> int:
|
||||
"""Count number of passed checks."""
|
||||
all_results = [
|
||||
self.validate_length(),
|
||||
self.validate_structure(),
|
||||
self.validate_formatting(),
|
||||
self.validate_completeness(),
|
||||
self._check_anti_patterns()
|
||||
]
|
||||
return sum(1 for result in all_results if result['status'] == 'pass')
|
||||
|
||||
def _count_failures(self) -> int:
|
||||
"""Count number of failed checks."""
|
||||
all_results = [
|
||||
self.validate_length(),
|
||||
self.validate_structure(),
|
||||
self.validate_formatting(),
|
||||
self.validate_completeness(),
|
||||
self._check_anti_patterns()
|
||||
]
|
||||
return sum(1 for result in all_results if result['status'] == 'fail')
|
||||
@@ -0,0 +1,432 @@
|
||||
"""
|
||||
CLAUDE.md Initialization Workflow
|
||||
|
||||
Handles the complete workflow for initializing CLAUDE.md in a new project:
|
||||
1. Explore repository to understand codebase
|
||||
2. Detect project type, tech stack, and structure
|
||||
3. Ask user for confirmation
|
||||
4. Create initial CLAUDE.md file
|
||||
5. Enhance with best practices
|
||||
|
||||
This workflow is interactive and conversational - user must confirm each step.
|
||||
|
||||
CRITICAL VALIDATION RULE:
|
||||
"Always validate your output against official native examples before declaring complete."
|
||||
|
||||
Before finalizing CLAUDE.md generation:
|
||||
- Compare output against `/update-claude-md` slash command format
|
||||
- Verify all native format sections are present (Overview, Project Structure,
|
||||
File Structure, Setup & Installation, Architecture, etc.)
|
||||
- Cross-check against reference examples in examples/ folder
|
||||
"""
|
||||
|
||||
from typing import Dict, List, Any, Optional
|
||||
from pathlib import Path
|
||||
import json
|
||||
|
||||
|
||||
class InitializationWorkflow:
|
||||
"""Manages the interactive initialization workflow for CLAUDE.md creation."""
|
||||
|
||||
def __init__(self, project_path: str = "."):
|
||||
"""
|
||||
Initialize workflow with project path.
|
||||
|
||||
Args:
|
||||
project_path: Path to project directory (default: current directory)
|
||||
"""
|
||||
self.project_path = Path(project_path)
|
||||
self.discoveries = {}
|
||||
self.user_confirmations = {}
|
||||
|
||||
def check_claude_md_exists(self) -> bool:
|
||||
"""
|
||||
Check if CLAUDE.md already exists in project.
|
||||
|
||||
Returns:
|
||||
True if CLAUDE.md exists, False otherwise
|
||||
"""
|
||||
claude_md_path = self.project_path / "CLAUDE.md"
|
||||
return claude_md_path.exists()
|
||||
|
||||
def generate_exploration_prompt(self) -> str:
|
||||
"""
|
||||
Generate prompt to guide Claude to explore the repository.
|
||||
|
||||
Returns:
|
||||
Exploration prompt string for Claude to execute
|
||||
"""
|
||||
return """I'll explore this repository to understand the codebase before creating a CLAUDE.md file.
|
||||
|
||||
Let me examine:
|
||||
1. Project structure and key directories
|
||||
2. Technology stack (package.json, requirements.txt, go.mod, etc.)
|
||||
3. Existing documentation (README.md, docs/)
|
||||
4. Development workflows (GitHub Actions, scripts/, Makefile)
|
||||
5. Testing setup
|
||||
6. Build configuration
|
||||
|
||||
Exploring repository now..."""
|
||||
|
||||
def analyze_discoveries(self, exploration_results: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Analyze repository exploration results to determine project context.
|
||||
|
||||
Args:
|
||||
exploration_results: Results from repository exploration
|
||||
|
||||
Returns:
|
||||
Analyzed project context
|
||||
"""
|
||||
context = {
|
||||
"project_type": self._detect_project_type(exploration_results),
|
||||
"tech_stack": self._detect_tech_stack(exploration_results),
|
||||
"team_size": self._estimate_team_size(exploration_results),
|
||||
"phase": self._detect_development_phase(exploration_results),
|
||||
"workflows": self._detect_workflows(exploration_results),
|
||||
"structure": self._analyze_structure(exploration_results),
|
||||
"modular_recommended": self._should_use_modular(exploration_results)
|
||||
}
|
||||
|
||||
self.discoveries = context
|
||||
return context
|
||||
|
||||
def _detect_project_type(self, results: Dict[str, Any]) -> str:
|
||||
"""Detect project type from exploration results."""
|
||||
# Check for common project type indicators
|
||||
files = results.get('files', [])
|
||||
directories = results.get('directories', [])
|
||||
|
||||
# Full-stack indicators
|
||||
if ('frontend' in directories or 'client' in directories) and \
|
||||
('backend' in directories or 'server' in directories or 'api' in directories):
|
||||
return "fullstack"
|
||||
|
||||
# Frontend indicators
|
||||
if any(f in files for f in ['package.json']) and \
|
||||
any(d in directories for d in ['src/components', 'components', 'pages']):
|
||||
return "web_app"
|
||||
|
||||
# Backend API indicators
|
||||
if any(f in files for f in ['requirements.txt', 'go.mod', 'Cargo.toml']):
|
||||
if any(d in directories for d in ['api', 'routes', 'controllers']):
|
||||
return "api"
|
||||
|
||||
# CLI indicators
|
||||
if any(d in directories for d in ['cmd', 'cli', 'bin']):
|
||||
return "cli"
|
||||
|
||||
# Library indicators
|
||||
if any(f in files for f in ['setup.py', 'pyproject.toml', 'Cargo.toml']) and \
|
||||
'examples' in directories:
|
||||
return "library"
|
||||
|
||||
# Mobile indicators
|
||||
if any(f in files for f in ['app.json', 'ios', 'android']):
|
||||
return "mobile"
|
||||
|
||||
# Default to web app
|
||||
return "web_app"
|
||||
|
||||
def _detect_tech_stack(self, results: Dict[str, Any]) -> List[str]:
|
||||
"""Detect technologies used in the project."""
|
||||
tech_stack = []
|
||||
files = results.get('files', [])
|
||||
content = results.get('file_contents', {})
|
||||
|
||||
# JavaScript/TypeScript
|
||||
if 'package.json' in files:
|
||||
pkg_json = content.get('package.json', {})
|
||||
dependencies = pkg_json.get('dependencies', {})
|
||||
|
||||
if 'typescript' in dependencies or any('typescript' in f for f in files):
|
||||
tech_stack.append('typescript')
|
||||
else:
|
||||
tech_stack.append('javascript')
|
||||
|
||||
# Frameworks
|
||||
if 'react' in dependencies:
|
||||
tech_stack.append('react')
|
||||
if 'vue' in dependencies:
|
||||
tech_stack.append('vue')
|
||||
if 'angular' in dependencies or '@angular/core' in dependencies:
|
||||
tech_stack.append('angular')
|
||||
if 'next' in dependencies:
|
||||
tech_stack.append('next.js')
|
||||
if 'express' in dependencies:
|
||||
tech_stack.append('express')
|
||||
|
||||
# Python
|
||||
if any(f in files for f in ['requirements.txt', 'pyproject.toml', 'setup.py']):
|
||||
tech_stack.append('python')
|
||||
|
||||
req_content = content.get('requirements.txt', '')
|
||||
if 'fastapi' in req_content.lower():
|
||||
tech_stack.append('fastapi')
|
||||
elif 'django' in req_content.lower():
|
||||
tech_stack.append('django')
|
||||
elif 'flask' in req_content.lower():
|
||||
tech_stack.append('flask')
|
||||
|
||||
# Go
|
||||
if 'go.mod' in files:
|
||||
tech_stack.append('go')
|
||||
go_mod = content.get('go.mod', '')
|
||||
if 'gin-gonic/gin' in go_mod:
|
||||
tech_stack.append('gin')
|
||||
if 'echo' in go_mod:
|
||||
tech_stack.append('echo')
|
||||
|
||||
# Databases
|
||||
if any('postgres' in f.lower() for f in files):
|
||||
tech_stack.append('postgresql')
|
||||
if any('mongo' in f.lower() for f in files):
|
||||
tech_stack.append('mongodb')
|
||||
if any('redis' in f.lower() for f in files):
|
||||
tech_stack.append('redis')
|
||||
|
||||
# Infrastructure
|
||||
if 'Dockerfile' in files or 'docker-compose.yml' in files:
|
||||
tech_stack.append('docker')
|
||||
if any('k8s' in d for d in results.get('directories', [])) or \
|
||||
any('kubernetes' in f.lower() for f in files):
|
||||
tech_stack.append('kubernetes')
|
||||
|
||||
return tech_stack
|
||||
|
||||
def _estimate_team_size(self, results: Dict[str, Any]) -> str:
|
||||
"""Estimate team size based on project complexity."""
|
||||
directories = results.get('directories', [])
|
||||
files = results.get('files', [])
|
||||
|
||||
# Indicators of team size
|
||||
complexity_score = 0
|
||||
|
||||
# File count indicator
|
||||
if len(files) > 100:
|
||||
complexity_score += 2
|
||||
elif len(files) > 50:
|
||||
complexity_score += 1
|
||||
|
||||
# Directory structure
|
||||
if len(directories) > 20:
|
||||
complexity_score += 2
|
||||
elif len(directories) > 10:
|
||||
complexity_score += 1
|
||||
|
||||
# CI/CD presence (indicates larger team)
|
||||
if any('.github/workflows' in str(d) for d in directories):
|
||||
complexity_score += 1
|
||||
|
||||
# Documentation (larger teams document more)
|
||||
if 'docs' in directories or any('documentation' in d for d in directories):
|
||||
complexity_score += 1
|
||||
|
||||
# Determine team size
|
||||
if complexity_score >= 5:
|
||||
return "large"
|
||||
elif complexity_score >= 3:
|
||||
return "medium"
|
||||
elif complexity_score >= 1:
|
||||
return "small"
|
||||
else:
|
||||
return "solo"
|
||||
|
||||
def _detect_development_phase(self, results: Dict[str, Any]) -> str:
|
||||
"""Detect development phase based on project maturity."""
|
||||
files = results.get('files', [])
|
||||
directories = results.get('directories', [])
|
||||
|
||||
# Production indicators
|
||||
production_indicators = [
|
||||
'Dockerfile' in files,
|
||||
'docker-compose.yml' in files,
|
||||
any('.github/workflows' in str(d) for d in directories),
|
||||
'CHANGELOG.md' in files,
|
||||
any('deploy' in f.lower() for f in files)
|
||||
]
|
||||
|
||||
if sum(production_indicators) >= 3:
|
||||
return "production"
|
||||
elif sum(production_indicators) >= 2:
|
||||
return "mvp"
|
||||
else:
|
||||
return "prototype"
|
||||
|
||||
def _detect_workflows(self, results: Dict[str, Any]) -> List[str]:
|
||||
"""Detect development workflows in use."""
|
||||
workflows = []
|
||||
files = results.get('files', [])
|
||||
directories = results.get('directories', [])
|
||||
|
||||
# TDD indicators
|
||||
if any('test' in d for d in directories) or \
|
||||
any('test' in f for f in files):
|
||||
workflows.append('tdd')
|
||||
|
||||
# CI/CD indicators
|
||||
if any('.github/workflows' in str(d) for d in directories) or \
|
||||
'.gitlab-ci.yml' in files or \
|
||||
'Jenkinsfile' in files:
|
||||
workflows.append('cicd')
|
||||
|
||||
# Documentation-first indicators
|
||||
if 'docs' in directories or \
|
||||
any('documentation' in d for d in directories):
|
||||
workflows.append('documentation_first')
|
||||
|
||||
return workflows
|
||||
|
||||
def _analyze_structure(self, results: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Analyze project structure."""
|
||||
directories = results.get('directories', [])
|
||||
|
||||
return {
|
||||
"has_frontend": any(d in directories for d in ['frontend', 'client', 'src/components']),
|
||||
"has_backend": any(d in directories for d in ['backend', 'server', 'api']),
|
||||
"has_database": any(d in directories for d in ['database', 'db', 'migrations']),
|
||||
"has_tests": any('test' in d for d in directories),
|
||||
"has_docs": 'docs' in directories or any('documentation' in d for d in directories),
|
||||
"has_ci": any('.github' in str(d) for d in directories)
|
||||
}
|
||||
|
||||
def _should_use_modular(self, results: Dict[str, Any]) -> bool:
|
||||
"""Determine if modular CLAUDE.md structure is recommended."""
|
||||
structure = self._analyze_structure(results)
|
||||
|
||||
# Recommend modular if:
|
||||
# - Has separate frontend and backend
|
||||
# - Large number of directories (>15)
|
||||
# - Medium/large team size
|
||||
|
||||
return (
|
||||
(structure['has_frontend'] and structure['has_backend']) or
|
||||
len(results.get('directories', [])) > 15 or
|
||||
self._estimate_team_size(results) in ['medium', 'large']
|
||||
)
|
||||
|
||||
def generate_confirmation_prompt(self, context: Dict[str, Any]) -> str:
|
||||
"""
|
||||
Generate confirmation prompt to show user the discoveries.
|
||||
|
||||
Args:
|
||||
context: Analyzed project context
|
||||
|
||||
Returns:
|
||||
Confirmation prompt string
|
||||
"""
|
||||
tech_stack_str = ", ".join(context['tech_stack'][:5])
|
||||
if len(context['tech_stack']) > 5:
|
||||
tech_stack_str += f" (+{len(context['tech_stack']) - 5} more)"
|
||||
|
||||
prompt = f"""Based on my exploration, here's what I discovered:
|
||||
|
||||
**Project Type**: {context['project_type'].replace('_', ' ').title()}
|
||||
**Tech Stack**: {tech_stack_str}
|
||||
**Team Size**: {context['team_size'].title()} ({self._get_team_size_range(context['team_size'])})
|
||||
**Development Phase**: {context['phase'].title()}
|
||||
**Workflows**: {', '.join(context['workflows']) if context['workflows'] else 'Standard development'}
|
||||
|
||||
**Recommended Structure**:
|
||||
{"Modular architecture (separate CLAUDE.md files for major components)" if context['modular_recommended'] else "Single CLAUDE.md file (appropriate for project size)"}
|
||||
|
||||
Would you like me to create a CLAUDE.md file based on these discoveries?
|
||||
|
||||
I can:
|
||||
1. Generate a customized CLAUDE.md tailored to your tech stack
|
||||
2. Include appropriate sections for your team size and phase
|
||||
3. {"Create modular files (backend/CLAUDE.md, frontend/CLAUDE.md, etc.)" if context['modular_recommended'] else "Focus on essential guidelines"}
|
||||
|
||||
Please confirm to proceed, or let me know if you'd like to adjust any of these settings."""
|
||||
|
||||
return prompt
|
||||
|
||||
def _get_team_size_range(self, team_size: str) -> str:
|
||||
"""Get human-readable team size range."""
|
||||
ranges = {
|
||||
"solo": "1 developer",
|
||||
"small": "2-9 developers",
|
||||
"medium": "10-49 developers",
|
||||
"large": "50+ developers"
|
||||
}
|
||||
return ranges.get(team_size, "Unknown")
|
||||
|
||||
def generate_initialization_summary(self, created_files: List[str]) -> str:
|
||||
"""
|
||||
Generate summary of initialization process.
|
||||
|
||||
Args:
|
||||
created_files: List of files created during initialization
|
||||
|
||||
Returns:
|
||||
Summary string
|
||||
"""
|
||||
summary = f"""✅ CLAUDE.md Initialization Complete!
|
||||
|
||||
**Created Files** ({len(created_files)}):
|
||||
"""
|
||||
for file in created_files:
|
||||
summary += f"- {file}\n"
|
||||
|
||||
summary += """
|
||||
**Next Steps**:
|
||||
1. Review the generated CLAUDE.md file
|
||||
2. Customize for your specific needs
|
||||
3. Add team-specific conventions
|
||||
4. Update as your project evolves
|
||||
|
||||
Your project is now set up for efficient AI-assisted development with Claude Code!
|
||||
"""
|
||||
return summary
|
||||
|
||||
def get_workflow_steps(self) -> List[Dict[str, str]]:
|
||||
"""
|
||||
Get the complete workflow steps for initialization.
|
||||
|
||||
Returns:
|
||||
List of workflow steps with descriptions
|
||||
"""
|
||||
return [
|
||||
{
|
||||
"step": 1,
|
||||
"name": "Check for existing CLAUDE.md",
|
||||
"description": "Verify if CLAUDE.md already exists in project",
|
||||
"action": "check_claude_md_exists"
|
||||
},
|
||||
{
|
||||
"step": 2,
|
||||
"name": "Explore repository",
|
||||
"description": "Analyze project structure, tech stack, and workflows using Claude Code's built-in explore capability",
|
||||
"action": "generate_exploration_prompt"
|
||||
},
|
||||
{
|
||||
"step": 3,
|
||||
"name": "Analyze discoveries",
|
||||
"description": "Detect project type, tech stack, team size, and recommend structure",
|
||||
"action": "analyze_discoveries"
|
||||
},
|
||||
{
|
||||
"step": 4,
|
||||
"name": "Request user confirmation",
|
||||
"description": "Show discoveries and ask user to confirm CLAUDE.md creation",
|
||||
"action": "generate_confirmation_prompt"
|
||||
},
|
||||
{
|
||||
"step": 5,
|
||||
"name": "Create CLAUDE.md file(s)",
|
||||
"description": "Generate customized CLAUDE.md based on confirmed context",
|
||||
"action": "create_files"
|
||||
},
|
||||
{
|
||||
"step": 6,
|
||||
"name": "Enhance with best practices",
|
||||
"description": "Apply additional enhancements and validate quality",
|
||||
"action": "enhance_files"
|
||||
},
|
||||
{
|
||||
"step": 7,
|
||||
"name": "Provide summary",
|
||||
"description": "Show what was created and next steps",
|
||||
"action": "generate_initialization_summary"
|
||||
}
|
||||
]
|
||||
Reference in New Issue
Block a user