Skip to content

SOP-006: CLAUDE.md File Creation

Document Control

FieldValue
Document IDSOP-006
Version1.0
StatusActive
OwnerClaude AI Operations
Last Updated2024-12-01
Review Date2025-03-01

Overview

This SOP defines the procedures for creating, maintaining, and updating CLAUDE.md files. These configuration files define Claude AI behavior, capabilities, and operational parameters for specific projects or environments.

CLAUDE.md Architecture

┌─────────────────────────────────────────────────────────────┐
│                    CLAUDE.md Structure                      │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │
│  │   Header    │  │    Core     │  │  Advanced   │        │
│  │ Metadata    │  │ Configuration│ │ Configuration│        │
│  │             │  │             │  │             │        │
│  │ • Title     │  │ • Model     │  │ • Tools     │        │
│  │ • Version   │  │ • System    │  │ • Limits    │        │
│  │ • Purpose   │  │ • Context   │  │ • Security  │        │
│  └─────────────┘  └─────────────┘  └─────────────┘        │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        │
│  │ Operational │  │ Integration │  │ Validation  │        │
│  │ Parameters  │  │ Settings    │  │ & Testing   │        │
│  └─────────────┘  └─────────────┘  └─────────────┘        │
└─────────────────────────────────────────────────────────────┘

Prerequisites

  • Project directory access
  • Understanding of project requirements
  • Claude AI model knowledge
  • Template files or examples

Procedure

Step 1: Template Creation

1.1 Basic CLAUDE.md Template

bash
# Create templates directory
mkdir -p ~/.config/claude/templates

# Basic template
cat > ~/.config/claude/templates/basic-claude.md << 'EOF'
# Claude AI Configuration

## Project Information
- **Project Name**: [PROJECT_NAME]
- **Version**: 1.0.0
- **Created**: [DATE]
- **Updated**: [DATE]
- **Environment**: [ENVIRONMENT]

## Model Configuration
- **Model**: claude-3-sonnet-20240229
- **Temperature**: 0.7
- **Max Tokens**: 4096
- **System Role**: Assistant

## Behavior Instructions

### Primary Role
You are a helpful AI assistant for this project. Your role is to:
- [Define specific role and responsibilities]
- [List key capabilities]
- [Specify interaction style]

### Communication Style
- Be clear and concise
- Use professional language
- Provide actionable guidance
- Ask clarifying questions when needed

### Capabilities
- Code analysis and generation
- Documentation assistance
- Problem-solving support
- Technical guidance

## Project Context

### Project Overview
[Describe the project, its goals, and scope]

### Key Requirements
- [Requirement 1]
- [Requirement 2]
- [Requirement 3]

### Technologies Used
- [Technology 1]
- [Technology 2]
- [Technology 3]

## Operational Guidelines

### File Handling
- Prefer editing existing files over creating new ones
- Always backup before making significant changes
- Maintain coding standards and conventions

### Security Considerations
- Never expose sensitive information
- Validate all user inputs
- Follow security best practices

### Error Handling
- Provide clear error messages
- Suggest solutions when possible
- Log errors appropriately

## Limitations
- Cannot access external APIs without permission
- Cannot modify system files
- Cannot execute privileged operations

## See Also
- Project documentation
- API references
- Security guidelines
EOF

1.2 Advanced CLAUDE.md Template

bash
cat > ~/.config/claude/templates/advanced-claude.md << 'EOF'
# Claude AI Advanced Configuration

## Project Information
- **Project Name**: [PROJECT_NAME]
- **Version**: [VERSION]
- **Created**: [DATE]
- **Updated**: [DATE]
- **Environment**: [ENVIRONMENT]
- **Owner**: [OWNER]
- **Repository**: [REPO_URL]

## Model Configuration
- **Model**: claude-3-sonnet-20240229
- **Temperature**: 0.7
- **Max Tokens**: 4096
- **Top P**: 0.9
- **Frequency Penalty**: 0.0
- **Presence Penalty**: 0.0

## System Instructions

### Primary Role

You are an expert AI assistant specialized in [DOMAIN]. Your responsibilities include:

  1. Technical Expertise: Provide expert-level guidance on [TECHNOLOGIES]
  2. Code Quality: Ensure all code follows best practices and conventions
  3. Documentation: Maintain clear, comprehensive documentation
  4. Testing: Promote thorough testing practices
  5. Security: Apply security best practices consistently

Your approach should be methodical, thorough, and focused on maintainability.


### Communication Protocols
- Use structured responses with clear sections
- Provide code examples with explanations
- Include verification steps for implementations
- Reference relevant documentation
- Escalate complex decisions to human oversight

## Advanced Features

### Tool Configuration
```yaml
enabled_tools:
  - file_system: 
      read: true
      write: true
      execute: false
  - code_execution:
      languages: [python, javascript, bash]
      sandbox: true
  - web_access:
      allowed_domains: [docs.company.com, github.com]
      proxy: true
  - database_access:
      read_only: true
      allowed_schemas: [public, analytics]

Rate Limiting

  • Requests per minute: 60
  • Tokens per hour: 100000
  • Concurrent sessions: 5

Context Management

  • Context window: 200k tokens
  • Context retention: 24 hours
  • Priority contexts: project_docs, recent_changes, user_preferences

Project-Specific Configuration

Codebase Structure

project/
├── src/           # Source code
├── tests/         # Test files
├── docs/          # Documentation
├── config/        # Configuration files
├── scripts/       # Utility scripts
└── .claude/       # Claude configuration

Coding Standards

  • Language: [PRIMARY_LANGUAGE]
  • Style Guide: [STYLE_GUIDE_URL]
  • Linting: [LINTER_CONFIG]
  • Formatting: [FORMATTER_CONFIG]
  • Testing Framework: [TEST_FRAMEWORK]

Dependencies

yaml
required:
  - python: ">=3.9"
  - node: ">=16.0"
  
optional:
  - docker: latest
  - kubernetes: ">=1.20"

Operational Procedures

Development Workflow

  1. Analyze requirements thoroughly
  2. Check existing implementations
  3. Follow established patterns
  4. Write comprehensive tests
  5. Update documentation
  6. Request code review

Quality Assurance

  • Code coverage minimum: 80%
  • Documentation coverage: 100%
  • Security scan: Required
  • Performance benchmarks: Maintained

Deployment Process

  1. Validate in development
  2. Test in staging environment
  3. Security review
  4. Performance validation
  5. Production deployment
  6. Post-deployment monitoring

Integration Settings

Version Control

  • System: Git
  • Branch Strategy: GitFlow
  • Commit Standards: Conventional Commits
  • Review Process: Pull Requests

CI/CD Pipeline

yaml
stages:
  - lint_and_test
  - security_scan
  - build
  - staging_deploy
  - integration_tests
  - production_deploy
  - monitoring

Monitoring & Alerting

  • Error Tracking: Enabled
  • Performance Monitoring: Enabled
  • Log Aggregation: Centralized
  • Alert Channels: Slack, Email

Security Configuration

Access Controls

  • Authentication: Required
  • Authorization: RBAC
  • Session Timeout: 30 minutes
  • MFA: Required for production

Data Protection

  • Encryption at Rest: AES-256
  • Encryption in Transit: TLS 1.3
  • PII Handling: Automated detection and masking
  • Audit Logging: Full coverage

Compliance

  • Standards: SOC2, GDPR
  • Data Retention: 7 years
  • Geographic Restrictions: [REGIONS]

Custom Behaviors

Error Handling

python
def handle_error(error, context):
    """
    Custom error handling for this project
    """
    # Log error with context
    logger.error(f"Error in {context}: {error}")
    
    # Provide user-friendly message
    return format_user_error(error)

Validation Rules

  • Input validation required for all user data
  • Schema validation for API requests
  • Business rule validation before processing

Optimization Guidelines

  • Cache frequently accessed data
  • Optimize database queries
  • Minimize API calls
  • Use async processing where appropriate

Testing Configuration

Test Strategy

  • Unit Tests: 100% critical path coverage
  • Integration Tests: All API endpoints
  • End-to-End Tests: Core user workflows
  • Performance Tests: Load and stress testing

Test Data Management

  • Use synthetic data for testing
  • Anonymize production data if used
  • Maintain test data consistency

Documentation Requirements

Code Documentation

  • Inline comments for complex logic
  • Function/method docstrings
  • API documentation
  • Architecture decisions recorded

User Documentation

  • Installation guides
  • Configuration instructions
  • Troubleshooting guides
  • FAQ sections

Performance Targets

Response Time

  • API Response: < 200ms (95th percentile)
  • Page Load: < 2s (95th percentile)
  • Database Queries: < 50ms (average)

Scalability

  • Concurrent Users: 10,000
  • Requests per Second: 5,000
  • Data Volume: 1TB+

Maintenance Procedures

Regular Tasks

  • Weekly dependency updates
  • Monthly security scans
  • Quarterly performance reviews
  • Annual architecture reviews

Backup & Recovery

  • Backup Frequency: Daily
  • Retention Period: 30 days
  • Recovery Time: < 1 hour
  • Recovery Point: < 15 minutes

Change Management

Configuration Changes

  1. Create feature branch
  2. Update CLAUDE.md
  3. Test changes thoroughly
  4. Document impact assessment
  5. Peer review
  6. Staged rollout

Version Control

  • Semantic versioning (MAJOR.MINOR.PATCH)
  • Tag releases in Git
  • Maintain changelog
  • Backward compatibility considerations

Support & Escalation

Contact Information

  • Primary Contact: [EMAIL]
  • Backup Contact: [EMAIL]
  • Emergency Contact: [PHONE]

Escalation Matrix

  • Level 1: Development team
  • Level 2: Senior architect
  • Level 3: Engineering manager
  • Level 4: CTO

Metadata

  • Configuration Hash: [AUTO_GENERATED]
  • Last Validated: [AUTO_GENERATED]
  • Validation Status: [AUTO_GENERATED] EOF

### Step 2: Project-Specific Templates

#### 2.1 Web Development Template

```bash
cat > ~/.config/claude/templates/web-dev-claude.md << 'EOF'
# Claude AI - Web Development Project

## Project Information
- **Project Name**: [WEB_PROJECT_NAME]
- **Type**: Web Application
- **Framework**: [React/Vue/Angular/etc]
- **Backend**: [Node.js/Python/etc]
- **Database**: [PostgreSQL/MongoDB/etc]

## Development Focus
You are a full-stack web development specialist. Your expertise includes:

### Frontend Development
- Modern JavaScript frameworks (React, Vue, Angular)
- CSS frameworks (Tailwind, Bootstrap, Material-UI)
- State management (Redux, Vuex, NgRx)
- Build tools (Webpack, Vite, Parcel)
- Testing (Jest, Cypress, Testing Library)

### Backend Development
- RESTful API design
- GraphQL implementation
- Authentication & authorization
- Database design and optimization
- Microservices architecture

### DevOps & Deployment
- Container orchestration (Docker, Kubernetes)
- CI/CD pipelines
- Cloud platforms (AWS, GCP, Azure)
- Monitoring and logging

## Code Standards
- Follow ESLint configuration
- Use Prettier for formatting
- Write comprehensive tests
- Document APIs with OpenAPI/Swagger
- Follow accessibility guidelines (WCAG)

## Security Guidelines
- Implement CORS properly
- Sanitize all inputs
- Use HTTPS everywhere
- Implement rate limiting
- Follow OWASP guidelines

## Performance Targets
- Lighthouse score > 90
- Core Web Vitals: Green
- Bundle size < 250KB
- API response time < 100ms
EOF

2.2 Data Science Template

bash
cat > ~/.config/claude/templates/data-science-claude.md << 'EOF'
# Claude AI - Data Science Project

## Project Information
- **Project Name**: [DATA_PROJECT_NAME]
- **Type**: Data Science/ML Project
- **Domain**: [Healthcare/Finance/etc]
- **Data Sources**: [List data sources]
- **Stakeholders**: [List stakeholders]

## Expertise Areas
You are a data science specialist with expertise in:

### Data Engineering
- Data pipeline design and implementation
- ETL/ELT processes
- Data quality and validation
- Data warehousing solutions
- Real-time data processing

### Machine Learning
- Supervised and unsupervised learning
- Deep learning frameworks (TensorFlow, PyTorch)
- Model selection and evaluation
- Feature engineering
- Model deployment and monitoring

### Analytics & Visualization
- Statistical analysis
- Exploratory data analysis (EDA)
- Dashboard creation (Tableau, Power BI, Plotly)
- A/B testing and experimentation
- Business intelligence

## Data Governance
- Follow data privacy regulations (GDPR, CCPA)
- Implement data lineage tracking
- Ensure reproducible research
- Document data transformations
- Maintain data catalogs

## ML Lifecycle
1. Problem definition and scoping
2. Data collection and exploration
3. Feature engineering
4. Model development and training
5. Model evaluation and validation
6. Model deployment
7. Monitoring and maintenance

## Tools & Technologies
- **Languages**: Python, R, SQL
- **ML Libraries**: scikit-learn, TensorFlow, PyTorch
- **Data Processing**: Pandas, NumPy, Spark
- **Visualization**: Matplotlib, Seaborn, Plotly
- **Experiment Tracking**: MLflow, Weights & Biases
EOF

Step 3: CLAUDE.md Generator Script

bash
# Create CLAUDE.md generator
cat > ~/.local/bin/claude-md-generator << 'EOF'
#!/bin/bash
# CLAUDE.md File Generator

set -euo pipefail

TEMPLATE_DIR="$HOME/.config/claude/templates"
OUTPUT_FILE="${1:-CLAUDE.md}"
PROJECT_NAME="${2:-$(basename $(pwd))}"

show_help() {
    cat << EOF
Usage: claude-md-generator [OUTPUT_FILE] [PROJECT_NAME] [OPTIONS]

Generate CLAUDE.md configuration file for your project.

Arguments:
    OUTPUT_FILE     Output file path (default: CLAUDE.md)
    PROJECT_NAME    Project name (default: current directory name)

Options:
    -t, --template  Template type (basic|advanced|web|data|custom)
    -e, --env       Environment (dev|staging|prod)
    -i, --interactive  Interactive mode
    -v, --validate  Validate generated file
    -h, --help      Show this help

Templates:
    basic      Basic configuration template
    advanced   Advanced configuration with all options
    web        Web development focused template
    data       Data science/ML focused template
    custom     Custom template from file

Examples:
    claude-md-generator
    claude-md-generator CLAUDE.md my-project -t web
    claude-md-generator -i -e prod
EOF
}

interactive_mode() {
    echo "🔧 Claude.md Interactive Generator"
    echo "=================================="
    
    # Gather project information
    read -p "Project Name [$PROJECT_NAME]: " input_name
    PROJECT_NAME="${input_name:-$PROJECT_NAME}"
    
    read -p "Project Type (web/api/data/cli/other): " project_type
    read -p "Primary Language (python/javascript/go/rust/other): " language
    read -p "Environment (dev/staging/prod): " environment
    read -p "Description: " description
    
    # Select template based on project type
    case "$project_type" in
        "web")
            template="web"
            ;;
        "data")
            template="data"
            ;;
        "api"|"cli"|"other")
            template="advanced"
            ;;
        *)
            template="basic"
            ;;
    esac
    
    echo
    echo "📝 Selected template: $template"
    echo "📂 Project: $PROJECT_NAME"
    echo "🌍 Environment: $environment"
    echo
}

generate_from_template() {
    local template="$1"
    local template_file="$TEMPLATE_DIR/${template}-claude.md"
    
    if [ ! -f "$template_file" ]; then
        echo "❌ Template not found: $template_file"
        echo "Available templates:"
        ls -1 "$TEMPLATE_DIR"/*-claude.md 2>/dev/null | sed 's/.*\///; s/-claude\.md$//' | sed 's/^/  - /'
        exit 1
    fi
    
    echo "📝 Generating CLAUDE.md from template: $template"
    
    # Replace placeholders
    sed \
        -e "s/\[PROJECT_NAME\]/$PROJECT_NAME/g" \
        -e "s/\[DATE\]/$(date +%Y-%m-%d)/g" \
        -e "s/\[ENVIRONMENT\]/${environment:-development}/g" \
        -e "s/\[VERSION\]/1.0.0/g" \
        -e "s/\[OWNER\]/${USER}/g" \
        "$template_file" > "$OUTPUT_FILE"
    
    # Add additional project-specific sections if in interactive mode
    if [ "${interactive:-false}" = "true" ]; then
        cat >> "$OUTPUT_FILE" << EOF

## Project-Specific Information

### Project Description
$description

### Primary Language
$language

### Project Type
$project_type

### Generated Configuration
- **Generated On**: $(date --iso-8601=seconds)
- **Generated By**: $USER
- **Generator Version**: 1.0.0
EOF
    fi
    
    echo "✅ CLAUDE.md generated: $OUTPUT_FILE"
}

validate_claude_md() {
    local file="$1"
    
    echo "🔍 Validating CLAUDE.md: $file"
    
    # Check if file exists
    if [ ! -f "$file" ]; then
        echo "❌ File not found: $file"
        return 1
    fi
    
    # Basic structure validation
    local required_sections=("Project Information" "Model Configuration")
    local missing_sections=()
    
    for section in "${required_sections[@]}"; do
        if ! grep -q "## $section" "$file"; then
            missing_sections+=("$section")
        fi
    done
    
    if [ ${#missing_sections[@]} -gt 0 ]; then
        echo "❌ Missing required sections:"
        printf '  - %s\n' "${missing_sections[@]}"
        return 1
    fi
    
    # Check for placeholder values
    local placeholders=$(grep -o '\[.*\]' "$file" | sort -u)
    if [ -n "$placeholders" ]; then
        echo "⚠️  Found unreplaced placeholders:"
        echo "$placeholders" | sed 's/^/  - /'
        echo "   Consider updating these values"
    fi
    
    echo "✅ CLAUDE.md validation passed"
    return 0
}

# Parse command line arguments
template="basic"
environment="development"
interactive=false
validate=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -t|--template)
            template="$2"
            shift 2
            ;;
        -e|--env)
            environment="$2"
            shift 2
            ;;
        -i|--interactive)
            interactive=true
            shift
            ;;
        -v|--validate)
            validate=true
            shift
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        *)
            if [ -z "${OUTPUT_FILE_SET:-}" ]; then
                OUTPUT_FILE="$1"
                OUTPUT_FILE_SET=true
            elif [ -z "${PROJECT_NAME_SET:-}" ]; then
                PROJECT_NAME="$1"
                PROJECT_NAME_SET=true
            else
                echo "❌ Unknown argument: $1"
                show_help
                exit 1
            fi
            shift
            ;;
    esac
done

# Run interactive mode if requested
if [ "$interactive" = "true" ]; then
    interactive_mode
fi

# Generate CLAUDE.md
generate_from_template "$template"

# Validate if requested
if [ "$validate" = "true" ]; then
    validate_claude_md "$OUTPUT_FILE"
fi

echo "🎉 CLAUDE.md generation complete!"
EOF

chmod +x ~/.local/bin/claude-md-generator

Step 4: CLAUDE.md Validation Tools

4.1 Validation Script

bash
cat > ~/.local/bin/claude-md-validate << 'EOF'
#!/bin/bash
# CLAUDE.md Validation Tool

set -euo pipefail

validate_structure() {
    local file="$1"
    local errors=()
    
    echo "🔍 Validating CLAUDE.md structure..."
    
    # Required sections
    local required=(
        "Project Information"
        "Model Configuration"
        "Behavior Instructions"
    )
    
    for section in "${required[@]}"; do
        if ! grep -q "## $section" "$file"; then
            errors+=("Missing section: $section")
        fi
    done
    
    # Check for metadata
    local metadata=(
        "Project Name"
        "Version"
        "Model"
    )
    
    for meta in "${metadata[@]}"; do
        if ! grep -q "**$meta**:" "$file"; then
            errors+=("Missing metadata: $meta")
        fi
    done
    
    if [ ${#errors[@]} -gt 0 ]; then
        echo "❌ Structure validation failed:"
        printf '  - %s\n' "${errors[@]}"
        return 1
    fi
    
    echo "✅ Structure validation passed"
    return 0
}

validate_content() {
    local file="$1"
    local warnings=()
    
    echo "🔍 Validating CLAUDE.md content..."
    
    # Check for placeholder values
    local placeholders=$(grep -o '\[.*\]' "$file" 2>/dev/null | sort -u || true)
    if [ -n "$placeholders" ]; then
        warnings+=("Found placeholder values that should be replaced")
    fi
    
    # Check model configuration
    if ! grep -q "claude-3" "$file"; then
        warnings+=("Model configuration may be outdated")
    fi
    
    # Check for empty sections
    if grep -A1 "^## " "$file" | grep -q "^--$"; then
        warnings+=("Found potentially empty sections")
    fi
    
    if [ ${#warnings[@]} -gt 0 ]; then
        echo "⚠️  Content validation warnings:"
        printf '  - %s\n' "${warnings[@]}"
    fi
    
    echo "✅ Content validation completed"
    return 0
}

validate_syntax() {
    local file="$1"
    
    echo "🔍 Validating CLAUDE.md syntax..."
    
    # Check markdown syntax using pandoc if available
    if command -v pandoc >/dev/null 2>&1; then
        if ! pandoc -f markdown -t html "$file" >/dev/null 2>&1; then
            echo "❌ Markdown syntax validation failed"
            return 1
        fi
    fi
    
    # Check YAML frontmatter if present
    if head -1 "$file" | grep -q "^---"; then
        local yaml_section=$(awk '/^---$/{if(++c==2) exit} c==1' "$file")
        if [ -n "$yaml_section" ] && command -v yq >/dev/null 2>&1; then
            if ! echo "$yaml_section" | yq . >/dev/null 2>&1; then
                echo "❌ YAML frontmatter validation failed"
                return 1
            fi
        fi
    fi
    
    echo "✅ Syntax validation passed"
    return 0
}

# Main validation
file="${1:-CLAUDE.md}"

if [ ! -f "$file" ]; then
    echo "❌ File not found: $file"
    exit 1
fi

echo "🔍 Validating CLAUDE.md file: $file"
echo "=================================="

# Run all validations
validate_structure "$file" && struct_ok=true || struct_ok=false
validate_content "$file" && content_ok=true || content_ok=false
validate_syntax "$file" && syntax_ok=true || syntax_ok=false

echo
echo "📊 Validation Summary:"
echo "======================"
echo "Structure: $([ "$struct_ok" = "true" ] && echo "✅ PASS" || echo "❌ FAIL")"
echo "Content:   $([ "$content_ok" = "true" ] && echo "✅ PASS" || echo "⚠️  WARNINGS")"
echo "Syntax:    $([ "$syntax_ok" = "true" ] && echo "✅ PASS" || echo "❌ FAIL")"

if [ "$struct_ok" = "true" ] && [ "$syntax_ok" = "true" ]; then
    echo
    echo "🎉 CLAUDE.md validation successful!"
    exit 0
else
    echo
    echo "❌ CLAUDE.md validation failed!"
    exit 1
fi
EOF

chmod +x ~/.local/bin/claude-md-validate

4.2 Linting and Formatting

bash
cat > ~/.local/bin/claude-md-lint << 'EOF'
#!/bin/bash
# CLAUDE.md Linting and Formatting Tool

CLAUDE_MD="${1:-CLAUDE.md}"

lint_formatting() {
    local file="$1"
    local issues=()
    
    echo "🔍 Linting CLAUDE.md formatting..."
    
    # Check line length (max 80 chars for readability)
    local long_lines=$(awk 'length($0) > 100 {print NR ": " $0}' "$file")
    if [ -n "$long_lines" ]; then
        issues+=("Lines over 100 characters found")
    fi
    
    # Check for consistent heading levels
    local heading_jumps=$(grep "^#" "$file" | awk '
        prev_level = 0
        {
            level = length(gensub(/^(#+).*/, "\\1", 1))
            if (prev_level > 0 && level > prev_level + 1) {
                print "Line " NR ": Heading level jump from " prev_level " to " level
            }
            prev_level = level
        }
    ')
    if [ -n "$heading_jumps" ]; then
        issues+=("Inconsistent heading levels")
    fi
    
    # Check for trailing whitespace
    if grep -q '[[:space:]]$' "$file"; then
        issues+=("Trailing whitespace found")
    fi
    
    if [ ${#issues[@]} -gt 0 ]; then
        echo "⚠️  Formatting issues found:"
        printf '  - %s\n' "${issues[@]}"
        return 1
    fi
    
    echo "✅ Formatting check passed"
    return 0
}

auto_format() {
    local file="$1"
    local backup_file="$file.backup.$(date +%s)"
    
    echo "🔧 Auto-formatting CLAUDE.md..."
    
    # Create backup
    cp "$file" "$backup_file"
    echo "📄 Backup created: $backup_file"
    
    # Remove trailing whitespace
    sed -i 's/[[:space:]]*$//' "$file"
    
    # Ensure single blank line at end of file
    sed -i -e '$a\' "$file"
    
    # Format markdown tables if present
    if command -v prettier >/dev/null 2>&1; then
        prettier --write --parser markdown "$file"
    fi
    
    echo "✅ Auto-formatting completed"
    echo "📄 Original backed up as: $backup_file"
}

case "${1:-lint}" in
    "lint")
        lint_formatting "${2:-CLAUDE.md}"
        ;;
    "format")
        auto_format "${2:-CLAUDE.md}"
        ;;
    "check")
        claude-md-validate "${2:-CLAUDE.md}"
        ;;
    *)
        echo "Usage: $0 [lint|format|check] [file]"
        echo ""
        echo "Commands:"
        echo "  lint     Check formatting and style"
        echo "  format   Auto-format the file"
        echo "  check    Run full validation"
        ;;
esac
EOF

chmod +x ~/.local/bin/claude-md-lint

Verification

Template Generation Test

bash
# Test basic template generation
claude-md-generator test-claude.md test-project -t basic

# Test interactive mode
claude-md-generator -i -t web

# Validate generated file
claude-md-validate CLAUDE.md

# Test all templates
for template in basic advanced web data; do
    echo "Testing template: $template"
    claude-md-generator "test-${template}.md" "test-project" -t "$template" -v
done

Validation Test

bash
# Create test file with issues
cat > test-invalid.md << 'EOF'
# Invalid CLAUDE.md
This file is missing required sections and has [PLACEHOLDER] values.
EOF

# Test validation
claude-md-validate test-invalid.md

# Test linting
claude-md-lint lint CLAUDE.md

Troubleshooting

Common Issues

IssueSymptomsResolution
Template not foundGenerator fails to locate templateCheck template directory and file names
Placeholder valuesValidation warns about unreplaced valuesUpdate placeholders manually or re-run generator
Invalid markdownSyntax validation failsCheck markdown structure and fix syntax errors
Missing sectionsStructure validation failsAdd required sections using template

Debug Commands

bash
# Check available templates
ls -la ~/.config/claude/templates/

# Verify template syntax
for template in ~/.config/claude/templates/*-claude.md; do
    echo "Checking $template"
    claude-md-validate "$template"
done

# Test generator with debug
bash -x ~/.local/bin/claude-md-generator CLAUDE.md test -t basic

Recovery Procedures

bash
# Reset templates
rm -rf ~/.config/claude/templates/
# Re-run Step 1-2 procedures

# Restore from backup
if [ -f CLAUDE.md.backup.* ]; then
    cp CLAUDE.md.backup.* CLAUDE.md
fi

See Also

Claude Code Documentation Hub