Skip to content

Latest commit

Β 

History

History
359 lines (276 loc) Β· 9.09 KB

File metadata and controls

359 lines (276 loc) Β· 9.09 KB

CLAUDE.md Mastery

Your project's persistent memory - the most critical tool for consistency and quality

🧠 What is CLAUDE.md?

The CLAUDE.md file is automatically loaded into every Claude session, serving as your project's persistent memory. This single file ensures consistency across all interactions and is your primary tool for:

  • Architectural decisions and design patterns
  • Coding standards and style guidelines
  • Workflow rules and mandatory processes
  • Domain-specific logic and common patterns
  • Quality requirements and constraints

πŸ—οΈ Essential CLAUDE.md Structure

Complete Template

# Project Context

## Architecture Overview
[Brief description of system architecture, key components, and design philosophy]

## Tech Stack
- Frontend: React 18, TypeScript, Tailwind CSS
- Backend: Node.js, Express, PostgreSQL
- Testing: Jest, React Testing Library, Supertest
- Infrastructure: Docker, AWS, GitHub Actions

## Coding Standards

### Naming Conventions
- Components: PascalCase (`UserProfile.tsx`)
- Functions: camelCase (`getUserData`)
- Constants: SCREAMING_SNAKE_CASE (`API_BASE_URL`)
- Files: kebab-case (`user-profile.service.ts`)

### Code Style
- Use TypeScript strict mode
- Prefer functional components with hooks
- Always use explicit return types
- Maximum line length: 100 characters
- Use meaningful variable names, avoid abbreviations

### Error Handling
- Always use try-catch for async operations
- Return structured error objects: `{ success: false, error: string, code?: string }`
- Log errors with context using structured logging
- Never throw unhandled exceptions in production code

## Workflow Rules

### ALWAYS:
- Run tests after making any code changes
- Use TypeScript strict mode for all new files
- Add JSDoc comments for public functions
- Validate inputs at API boundaries
- Use environment variables for configuration

### NEVER:
- Commit code without running linter
- Use `any` type without explicit justification
- Hard-code sensitive values
- Skip error handling in async functions
- Modify files in `node_modules/`

## Domain-Specific Patterns

### API Response Format
All API responses must follow this structure:
```typescript
interface ApiResponse<T> {
  success: boolean;
  data?: T;
  error?: string;
  code?: string;
  timestamp: string;
}

Database Queries

  • Use parameterized queries to prevent SQL injection
  • Always include error handling and connection cleanup
  • Use transactions for multi-table operations
  • Index frequently queried columns

Component Patterns

  • Use custom hooks for complex state logic
  • Implement error boundaries for fault tolerance
  • Use React.memo for expensive renders
  • Keep components under 200 lines

Security Requirements

Input Validation

  • Validate all user inputs on both client and server
  • Use schema validation libraries (Joi, Yup, Zod)
  • Sanitize HTML content to prevent XSS
  • Implement rate limiting on API endpoints

Authentication

  • Use JWT tokens with reasonable expiration times
  • Implement refresh token rotation
  • Never store passwords in plain text
  • Use bcrypt with minimum 10 salt rounds

Performance Guidelines

  • Lazy load components and routes
  • Implement proper caching strategies
  • Use database connection pooling
  • Optimize images and static assets
  • Monitor bundle size and core web vitals

Testing Requirements

  • Minimum 80% code coverage for new features
  • Unit tests for all business logic
  • Integration tests for API endpoints
  • E2E tests for critical user journeys
  • Mock external dependencies in tests

Common Pitfalls to Avoid

  • Race conditions in async operations
  • Memory leaks from uncleaned event listeners
  • N+1 query problems in database operations
  • Blocking the event loop with synchronous operations
  • Missing null/undefined checks

Project-Specific Context

[Add specific business logic, custom libraries, integration requirements, etc.]


## πŸ“ Content Guidelines

### Use Strong Language for Critical Items

```markdown
## Critical Rules

### YOU MUST:
- Run tests after EVERY code change
- Validate ALL user inputs
- Use parameterized queries for database operations

### IMPORTANT: 
Never skip error handling in async functions

### COMPLETE FAILURE if:
Any functionality is broken after refactoring

Include Concrete Examples

## Component Pattern Example

βœ… GOOD:
```typescript
interface UserProfileProps {
  userId: string;
  onUpdate: (user: User) => void;
}

export const UserProfile: React.FC<UserProfileProps> = ({ userId, onUpdate }) => {
  // Implementation
};

❌ BAD:

export const UserProfile = (props: any) => {
  // Implementation
};

πŸ”§ Management Strategies

Initialization

# Create initial CLAUDE.md
claude init

# Quick additions during sessions
# (Use # key in Claude Code)

Version Control

# Always track CLAUDE.md changes
git add CLAUDE.md
git commit -m "Update coding standards in CLAUDE.md"

# Share across team
git push origin main

Session Management

## Adding New Context

Use the # key shortcut during sessions:
# Architecture Decision: Switched to event-driven architecture for better scalability
# New Rule: All API responses must include correlation IDs for tracing

Keep It Current

## Maintenance Schedule
- Review weekly during sprint planning
- Update after architectural changes  
- Document new patterns as they emerge
- Remove outdated constraints

🎯 Advanced Techniques

Reference-Based Development

## Code Examples

### Authentication Implementation
Reference: `src/auth/jwt.service.ts` 
Follow the same pattern for all auth-related features

### Database Service Pattern  
Reference: `src/services/user.service.ts`
All services should implement: find, create, update, delete methods

Constraint Hierarchies

## Priority Levels

### P0 (CRITICAL - Complete failure if violated):
- No functionality changes during refactoring
- All tests must pass before commit

### P1 (IMPORTANT - Strong preference):
- Use TypeScript strict mode
- Follow naming conventions

### P2 (PREFERRED - Style guide):
- Maximum line length 100 characters
- Use meaningful variable names

Context Inheritance

## Inherits From
- Company coding standards: `docs/coding-standards.md`
- Security policies: `docs/security-policy.md`
- Architecture decisions: `docs/architecture/adr/`

## Project-Specific Overrides
- Use React hooks instead of class components
- Prefer functional programming patterns

πŸ“Š Quality Metrics

Track CLAUDE.md effectiveness:

Consistency Indicators

  • Architectural pattern adherence across files
  • Naming convention compliance
  • Error handling consistency
  • Test coverage maintenance

Success Metrics

  • Reduced context clarification questions from Claude
  • Faster feature development with consistent patterns
  • Fewer code review comments on standards
  • Less debugging time due to consistent patterns

🚨 Common Mistakes

❌ Too Generic

# Bad
Use good coding practices and write clean code.

βœ… Specific and Actionable

# Good
Use TypeScript strict mode. All functions must have explicit return types.
Maximum cyclomatic complexity: 10. Use early returns to reduce nesting.

❌ Outdated Information

# Bad - if you switched from REST to GraphQL
All API endpoints should follow REST conventions

βœ… Current and Accurate

# Good
All API operations use GraphQL. Follow schema-first design.
Reference: `schema/user.graphql` for query patterns

❌ Missing Context

# Bad
Use the standard authentication pattern

βœ… Explicit Reference

# Good  
Authentication: Follow JWT implementation in `src/auth/jwt.service.ts`
Include refresh token rotation and proper error handling

πŸ”„ Integration with Workflows

TDD Integration

## Test-First Development
1. Write failing test covering requirements
2. Implement minimal code to pass
3. Refactor while maintaining green tests
4. Update CLAUDE.md with new patterns learned

Code Review Process

## Review Checklist Against CLAUDE.md
- [ ] Follows established naming conventions
- [ ] Implements required error handling
- [ ] Includes appropriate tests
- [ ] Meets performance guidelines
- [ ] Adheres to security requirements

πŸ“š Templates and Examples

πŸ”— Next Steps

  1. Context Management - Keep Claude aligned during sessions
  2. Prompt Engineering - Get exactly what you need
  3. Model Selection - Choose the right Claude model

Pro Tip: Your CLAUDE.md is only as good as you keep it. Schedule regular reviews and updates to maintain its effectiveness as your project evolves.