CLAUDE.md Advanced Configuration Patterns

Overview

Advanced patterns and enterprise-scale configurations for CLAUDE.md files. This guide covers monorepo strategies, performance optimization, security patterns, and complex team workflows.

Quick Navigation

Monorepo Strategies

Hierarchical Configuration

monorepo/
├── CLAUDE.md                    # Global rules
├── packages/
│   ├── shared/
│   │   └── CLAUDE.md           # Shared lib rules
│   ├── ui-components/
│   │   └── CLAUDE.md           # UI component rules
│   └── api/
│       └── CLAUDE.md           # API service rules
├── apps/
│   ├── web/
│   │   └── CLAUDE.md           # Web app rules
│   └── mobile/
│       └── CLAUDE.md           # Mobile app rules
└── tools/
    └── CLAUDE.md               # Build tool rules

Root CLAUDE.md Example

# Monorepo: E-Commerce Platform
- Workspace: pnpm workspaces
- Node: 20.x LTS
- TypeScript: 5.3 workspace-wide
 
# Global Commands
- install: pnpm install
- dev: pnpm -r dev
- build: turbo run build
- test: turbo run test
 
# Architecture
@./docs/architecture/architecture-overview.md
@./docs/standards/typescript.md
@./docs/standards/testing.md
 
# Package Rules
- Shared types in @company/types
- UI components in @company/ui
- No circular dependencies

Package-Specific CLAUDE.md

# Package: @company/api
- Framework: Fastify 4.x
- Database: PostgreSQL + Prisma
- Auth: JWT with refresh tokens
 
# Local Commands
- dev: tsx watch src/index.ts
- db:push: prisma db push
- db:studio: prisma studio
 
# API Patterns
- Route handlers in /routes
- Middleware in /middleware
- DTOs with Zod validation
- Service layer pattern

Performance Optimization

Context Window Management

# Performance Config
- Max imports: 3 levels deep
- Exclude: node_modules, dist, .next
- Focus: Current package only
 
# Smart Imports
@./src/types/index.ts      # Only type definitions
@./docs/api-endpoints.md   # Only when working on API
@./tests/setup.ts          # Only when writing tests
 
# Session Management
- /compact after 10 interactions
- /clear before major refactors
- Use SCRATCHPAD.md for planning

Token Optimization Patterns

# ❌ Wasteful
The application uses React 18 with TypeScript for the frontend,
Express with TypeScript for the backend, PostgreSQL for the
database, and Redis for caching...
 
# ✅ Optimized
Stack: React 18, Express, PostgreSQL, Redis
Lang: TypeScript 5.3 strict

Selective Loading

# Context Switching
## Frontend Work
@./docs/frontend-only.md
 
## Backend Work  
@./docs/backend-only.md
 
## Full-Stack
@./docs/frontend-only.md
@./docs/backend-only.md

Security Patterns

Environment Management

# Security Rules
- No hardcoded secrets
- Use process.env only
- Validate env on startup
- .env.example for reference
 
# Secret Patterns
DATABASE_URL=process.env.DATABASE_URL
API_KEY=process.env.API_KEY
Never: password="hardcoded"
 
# Forbidden Paths
- /.env
- /.env.local
- /secrets/
- /**/*.key

Access Control Documentation

# API Security
- Auth: Bearer token required
- Rate limit: 100 req/min
- CORS: Configured origins only
- Input: Zod validation required
 
# Database Access
- Prisma client only
- No raw SQL
- Row-level security enabled
- Audit logs required

Team Collaboration at Scale

Multi-Team Setup

# Team Structure
@./teams/frontend/CLAUDE.md    # Frontend team rules
@./teams/backend/CLAUDE.md     # Backend team rules
@./teams/devops/CLAUDE.md      # DevOps team rules
 
# Shared Standards
@./standards/code-review.md
@./standards/git-workflow.md
@./standards/release-process.md
 
# Personal Overrides
@~/.claude/personal-prefs.md

Role-Based Configuration

# Junior Developer CLAUDE.md
- Always write tests first
- Get PR review before merge
- Use existing patterns
- Ask in Slack if unsure
 
# Senior Developer CLAUDE.md  
- Review junior PRs
- Document new patterns
- Performance profiling required
- Mentor through comments

Cross-Team Communication

# API Contract Updates
When changing API:
1. Update OpenAPI spec
2. Run contract tests  
3. Notify frontend team
4. Version endpoints
 
# Shared Types Process
1. Define in @company/types
2. Generate from Prisma schema
3. Export through index
4. Version bump required

CI/CD Integration

GitHub Actions Integration

# CI/CD Workflow
- Trigger: PR, push to main
- Checks: lint, type, test, build
- Deploy: Staging on main, prod on tag
 
# Claude Code CI
on:
  issue_comment:
    types: [created]
  pull_request_comment:
    types: [created]
 
# Automation Commands
/claude-fix: Auto-fix linting
/claude-test: Generate tests
/claude-review: Code review

Deployment Patterns

# Deployment Strategy
- Preview: PR deploys to Vercel
- Staging: Auto-deploy main
- Production: Tag-triggered
- Rollback: Previous tag
 
# Pre-deploy Checklist
1. All tests passing
2. Type coverage >95%
3. Bundle size check
4. Lighthouse score >90

Custom DSL Patterns

Domain-Specific Commands

# E-Commerce Commands
/product: Create product CRUD
/payment: Add payment method
/inventory: Update stock system
/order: Order processing flow
 
# Command Structure
/.claude/commands/
├── product.md
├── payment.md
├── inventory.md
└── order.md

Template System

# Component Template
/component $NAME creates:
- src/components/$NAME/$NAME.tsx
- src/components/$NAME/$NAME.test.tsx
- src/components/$NAME/$NAME.stories.tsx
- src/components/$NAME/$NAME.module.css
- src/components/$NAME/index.ts
 
With patterns:
- FC with explicit props
- Complete test coverage
- Storybook variants
- CSS modules styling

Workflow Automation

# Feature Workflow
/feature $NAME:
1. Create feature branch
2. Add feature flag
3. Create component structure
4. Add to routing
5. Create initial tests
6. Update documentation
 
# Bug Fix Workflow
/bugfix $ID:
1. Create fix branch from main
2. Add regression test
3. Implement fix
4. Verify all tests
5. Create PR with template

Enterprise Examples

Financial Services Pattern

# Compliance Requirements
- SOC2: Audit logging required
- PCI: No credit card storage
- GDPR: PII encryption required
- ISO27001: Access control
 
# Trading Platform Rules
- Decimal.js for money
- BigInt for quantities  
- UTC timestamps only
- Audit every transaction
 
# Testing Requirements
- Unit: 100% coverage
- Integration: Critical paths
- E2E: User journeys
- Performance: Sub-100ms

Healthcare System Pattern

# HIPAA Compliance
- PHI: Encrypted at rest
- Access: Role-based only
- Audit: Every PHI access
- Retention: 7 years
 
# Medical Records API
- FHIR standard required
- HL7 message format
- Terminology: SNOMED CT
- Drugs: RxNorm codes
 
# Security Layers
1. Network: VPN required
2. API: OAuth2 + MFA
3. Database: Encrypted
4. Backups: Encrypted

SaaS Platform Pattern

# Multi-Tenant Architecture
- Isolation: Schema-per-tenant
- Auth: JWT with tenant claim
- Data: Tenant ID required
- Cache: Tenant-prefixed keys
 
# Subscription Management
- Billing: Stripe integration
- Plans: Free, Pro, Enterprise
- Limits: Rate limit by plan
- Webhooks: Idempotent handlers
 
# Feature Flags
- Provider: LaunchDarkly
- Naming: feature-{area}-{name}
- Rollout: Percentage-based
- Cleanup: Remove after 30d

Advanced Import Patterns

Conditional Imports

# Development Only
@./docs/dev-setup.md #dev
@./docs/debugging.md #dev
 
# Production Focus
@./docs/performance.md #prod
@./docs/monitoring.md #prod
 
# Test Environment
@./docs/test-data.md #test
@./docs/mocking.md #test

Dynamic Module Loading

# Feature-Based Loading
## Payment Module
@./modules/payment/README.md
@./modules/payment/api.md
@./modules/payment/types.ts
 
## Analytics Module  
@./modules/analytics/README.md
@./modules/analytics/events.md
@./modules/analytics/types.ts

Performance Benchmarks

Optimal CLAUDE.md Sizes

# Size Guidelines
- Minimal: <1KB (50-100 lines)
- Standard: 1-3KB (100-300 lines)  
- Complex: 3-5KB (300-500 lines)
- Maximum: <10KB (token limit)
 
# Impact on Performance
- <1KB: No noticeable impact
- 1-3KB: 50-100ms added
- 3-5KB: 100-200ms added
- >5KB: Consider splitting

Loading Time Optimization

# Fast Loading Pattern
1. Core rules inline
2. Details in imports
3. Lazy load domains
4. Cache common imports
 
# Benchmarks
- Initial load: <500ms
- Import resolution: <100ms each
- Total context: <2s
- Interaction delay: <200ms

MCP Server Integration

Project Tools Configuration

# MCP Servers
- Database: @company/mcp-postgres
- Cache: @company/mcp-redis  
- Search: @company/mcp-elastic
- Queue: @company/mcp-rabbitmq
 
# OAuth Configuration
servers:
  - name: company-api
    client_id: $CLIENT_ID
    client_secret: $CLIENT_SECRET
    scope: read write admin

Custom Tool Development

# Tool Development Rules
- TypeScript required
- Zod for validation
- Tests required
- Documentation required
 
# Tool Interface
interface Tool {
  name: string
  description: string
  parameters: ZodSchema
  execute: (params: T) => Promise<R>
}

Troubleshooting Patterns

Common Issues

# Debug Checklist
1. Check /memory output
2. Verify import paths
3. Validate syntax
4. Check permissions
5. Review token usage
 
# Performance Issues
- Too many imports: Use selective loading
- Large files: Split into modules
- Slow loads: Check import depth
- Token limit: Use /compact

Error Recovery

# Recovery Patterns
## Import Failures
- Check file exists
- Verify permissions  
- Use absolute paths
- Reduce depth
 
## Context Overflow
- Run /compact
- Clear old context
- Split documentation
- Focus current task

Enterprise patterns require careful planning. Start simple, measure impact, optimize gradually.