28 KiB
[Project Name]
Version: 1.0.0 | Last Updated: YYYY-MM-DD | Maintainer: [Your Name/Team]
Project Overview
Purpose
Brief 2-3 sentence description of what this project does and why it exists.
Key Objectives
- Primary goal or feature 1
- Primary goal or feature 2
- Primary goal or feature 3
Project Type
- Web Application
- API/Backend Service
- CLI Tool
- Library/Package
- Mobile App
- Desktop Application
- Other: _________________
Target Users/Audience
Who is this project built for? What problems does it solve for them?
Technology Stack
Core Technologies
- Language(s): [e.g., Python 3.11, TypeScript 5.0, JavaScript ES6+]
- Framework(s): [e.g., React 18, Django 4.2, Express.js]
- Runtime: [e.g., Node.js 18+, Python 3.11+]
Frontend (if applicable)
- UI Framework: [e.g., React, Vue, Angular, Svelte]
- Styling: [e.g., Tailwind CSS, CSS Modules, Styled Components]
- State Management: [e.g., Redux, Zustand, Context API]
- Build Tool: [e.g., Vite, Webpack, Turbopack]
Backend (if applicable)
- Framework: [e.g., Express, FastAPI, Django, Rails]
- Database: [e.g., PostgreSQL 15, MongoDB 6, MySQL 8]
- ORM/Query Builder: [e.g., Prisma, SQLAlchemy, TypeORM]
- Authentication: [e.g., JWT, OAuth 2.0, Passport.js]
Infrastructure & DevOps
- Hosting: [e.g., AWS, Vercel, Railway, Heroku]
- CI/CD: [e.g., GitHub Actions, GitLab CI, CircleCI]
- Containers: [e.g., Docker, Docker Compose]
- Monitoring: [e.g., Sentry, DataDog, Prometheus]
Testing
- Test Framework: [e.g., Jest, Pytest, Vitest, Mocha]
- E2E Testing: [e.g., Playwright, Cypress, Selenium]
- Test Coverage Tool: [e.g., Coverage.py, Istanbul, c8]
Development Tools
- Package Manager: [e.g., npm, pnpm, yarn, pip, poetry]
- Linting: [e.g., ESLint, Pylint, Ruff]
- Formatting: [e.g., Prettier, Black, rustfmt]
- Type Checking: [e.g., TypeScript, mypy, Flow]
Project Structure
Directory Layout
project-root/
├── src/ # Source code
│ ├── components/ # Reusable components
│ ├── pages/ # Page components or routes
│ ├── services/ # Business logic and API calls
│ ├── utils/ # Utility functions
│ ├── hooks/ # Custom React hooks (if applicable)
│ ├── types/ # TypeScript type definitions
│ └── config/ # Configuration files
├── tests/ # Test files
│ ├── unit/ # Unit tests
│ ├── integration/ # Integration tests
│ └── e2e/ # End-to-end tests
├── public/ # Static assets
├── docs/ # Documentation
├── scripts/ # Build and utility scripts
├── .claude/ # Claude Code configuration
│ ├── commands/ # Custom slash commands
│ ├── skills/ # Agent skills
│ ├── hooks/ # Event hooks
│ └── settings.json # Claude settings
└── config/ # Application configuration
Key Files
- Entry Point: [e.g.,
src/index.ts,src/main.py,app.js] - Configuration: [e.g.,
config/app.config.ts,settings.py] - Routes/API: [e.g.,
src/routes/,src/api/] - Database Models: [e.g.,
src/models/,src/db/schema.ts]
Module Organization
Explain how code is organized into modules/packages and the reasoning behind the structure.
Code Style & Standards
Naming Conventions
Variables & Functions
- Use
camelCasefor variables and functions (JavaScript/TypeScript) - Use
snake_casefor variables and functions (Python) - Use descriptive names that reveal intent
- Avoid single-letter variables except in loops or mathematical contexts
// Good
const userProfile = getUserProfile();
const isAuthenticated = checkAuth();
// Avoid
const x = getUser();
const flag = check();
Classes & Components
- Use
PascalCasefor classes and React components - Name classes with nouns that describe what they represent
- Name components based on what they render
// Good
class UserRepository { }
function UserProfileCard() { }
// Avoid
class userData { }
function component1() { }
Constants
- Use
UPPER_SNAKE_CASEfor constants - Group related constants in enums or objects
// Good
const MAX_RETRY_ATTEMPTS = 3;
const API_BASE_URL = process.env.API_URL;
// Avoid
const maxretries = 3;
Files & Folders
- Use
kebab-casefor file and folder names - Match file name to primary export
- Use
.test.tssuffix for test files - Use
.spec.tsfor specification files
user-profile.tsx
user-repository.ts
user-profile.test.tsx
api-client.config.ts
Code Organization
File Size
- Keep files under 300 lines when possible
- Split large files into smaller, focused modules
- One component/class per file (exceptions for tightly coupled small helpers)
Function Complexity
- Functions should do one thing well
- Keep functions under 50 lines when possible
- Extract complex logic into well-named helper functions
- Maximum 3-4 parameters; use options objects for more
// Good - focused function
function calculateTotalPrice(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0);
}
// Avoid - doing too much
function processOrder(items, user, payment, shipping, discount) {
// 100+ lines of mixed concerns
}
Import Organization
Order imports in this sequence:
- External dependencies
- Internal modules (absolute imports)
- Relative imports
- Type imports (if separate)
- Styles
// External
import React from 'react';
import { useQuery } from '@tanstack/react-query';
// Internal
import { apiClient } from '@/services/api';
import { UserRepository } from '@/repositories/user';
// Relative
import { Button } from './components/Button';
import { formatDate } from './utils/date';
// Types
import type { User } from '@/types';
// Styles
import './styles.css';
Comments & Documentation
When to Comment
- DO: Explain why something is done, not what is done
- DO: Document complex algorithms or business logic
- DO: Add TODOs with tickets/issues:
// TODO(#123): refactor this - DO: Explain workarounds or non-obvious solutions
- DON'T: State the obvious
- DON'T: Leave commented-out code (use git history)
// Good - explains why
// Using a delay here to work around race condition in the API
// See issue #456 for details
await delay(100);
// Avoid - states the obvious
// Set user to null
user = null;
Docstrings/JSDoc
Document all public APIs, exported functions, and complex internal functions:
/**
* Calculates the user's subscription renewal date
*
* @param user - The user object containing subscription info
* @param includeGracePeriod - Whether to add the 7-day grace period
* @returns ISO 8601 date string of the renewal date
* @throws {ValidationError} If user has no active subscription
*
* @example
* const renewalDate = calculateRenewalDate(user, true);
* // Returns: "2024-12-01T00:00:00Z"
*/
function calculateRenewalDate(
user: User,
includeGracePeriod: boolean = false
): string {
// implementation
}
Error Handling
Strategy
- Use typed errors/exceptions
- Fail fast with clear error messages
- Never swallow errors silently
- Log errors with context
- Return errors, don't just throw (for critical paths)
// Good
try {
const user = await fetchUser(id);
if (!user) {
throw new NotFoundError(`User ${id} not found`);
}
return user;
} catch (error) {
logger.error('Failed to fetch user', { userId: id, error });
throw error;
}
// Avoid
try {
const user = await fetchUser(id);
return user;
} catch (error) {
// Silent failure
}
TypeScript/Type Hints Specific
Type Safety
- Enable strict mode in
tsconfig.json - Avoid
anytype; useunknownwhen type is truly unknown - Define explicit return types for functions
- Use branded types for IDs and sensitive data
// Good
function getUser(id: UserId): Promise<User | null> {
// implementation
}
// Avoid
function getUser(id: any): Promise<any> {
// implementation
}
Performance Considerations
- Avoid premature optimization
- Use memoization for expensive calculations
- Implement pagination for large datasets
- Use lazy loading for components and routes
- Profile before optimizing
Testing Requirements
Test Coverage Goals
- Minimum Coverage: 80% overall
- Critical Paths: 100% coverage required
- New Features: 90%+ coverage for new code
- Bug Fixes: Add regression test with every fix
Testing Pyramid
/\
/E2E\ <- 10% (Critical user flows)
/------\
/Integ. \ <- 20% (API/DB integration)
/----------\
/ Unit \ <- 70% (Pure functions, logic)
/--------------\
Test Organization
Unit Tests
- Test pure functions and business logic
- Mock external dependencies
- One assertion per test (generally)
- Use descriptive test names
describe('calculateTotalPrice', () => {
it('should return 0 for empty cart', () => {
expect(calculateTotalPrice([])).toBe(0);
});
it('should sum all item prices correctly', () => {
const items = [
{ price: 10 },
{ price: 20 },
{ price: 30 }
];
expect(calculateTotalPrice(items)).toBe(60);
});
it('should handle single item cart', () => {
expect(calculateTotalPrice([{ price: 15 }])).toBe(15);
});
});
Integration Tests
- Test component integration
- Test API endpoints
- Test database queries
- Use test database or mocks
E2E Tests
- Test critical user journeys
- Test authentication flows
- Test payment/checkout processes
- Run against staging environment
Test Naming Convention
describe('[Component/Function Name]', () => {
it('should [expected behavior] when [condition]', () => {
// test implementation
});
});
Before Committing
- All tests pass locally
- New code has corresponding tests
- No test files skipped or disabled
- Test coverage meets minimum thresholds
Git & Version Control
Branch Strategy
Branch Types
main/master- Production-ready codedevelop- Integration branch for featuresfeature/*- New features (feature/user-authentication)bugfix/*- Bug fixes (bugfix/login-error)hotfix/*- Urgent production fixes (hotfix/security-patch)release/*- Release preparation (release/v1.2.0)
Branch Naming
- Use lowercase with hyphens
- Include ticket/issue number when applicable
- Be descriptive but concise
# Good
feature/user-profile-page
bugfix/fix-memory-leak-in-cache
hotfix/critical-security-patch
# Avoid
feature/new-stuff
bugfix/fix
my-branch
Commit Message Format
Follow the Conventional Commits specification:
<type>(<scope>): <subject>
<body>
<footer>
Types
- feat: New feature
- fix: Bug fix
- docs: Documentation changes
- style: Formatting, missing semi-colons, etc. (no code change)
- refactor: Code refactoring (no functional changes)
- test: Adding or updating tests
- chore: Maintenance tasks, dependency updates
- perf: Performance improvements
- ci: CI/CD changes
- build: Build system or external dependency changes
Examples
# Simple commit
feat: add user authentication
# With scope
feat(auth): implement JWT token refresh
# With body and footer
fix(api): resolve race condition in user creation
The user creation endpoint was creating duplicate users when
called rapidly. Added a database constraint and improved the
locking mechanism to prevent this issue.
Closes #123
Reviewed-by: @username
Commit Message Rules
- Use imperative mood ("add" not "added" or "adds")
- Don't capitalize first letter after type
- No period at the end of subject
- Keep subject under 50 characters
- Wrap body at 72 characters
- Reference issues and PRs in footer
Pull Request Guidelines
PR Title
Follow commit message format: type(scope): description
PR Description Template
## Summary
Brief description of changes
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Changes Made
- Change 1
- Change 2
- Change 3
## Testing
- [ ] Unit tests added/updated
- [ ] Integration tests added/updated
- [ ] Manual testing completed
## Screenshots (if applicable)
[Add screenshots for UI changes]
## Related Issues
Closes #123
Related to #456
## Checklist
- [ ] Code follows project style guidelines
- [ ] Self-reviewed my code
- [ ] Commented complex logic
- [ ] Updated documentation
- [ ] No new warnings
- [ ] Tests pass locally
- [ ] Added tests for new features
Before Creating PR
- Branch is up to date with base branch
- All tests pass
- Code has been self-reviewed
- No debugging code or console logs
- Documentation updated if needed
Code Review Process
- Automated checks must pass (CI/CD, linting, tests)
- At least 1 approval required (adjust based on team size)
- All comments addressed or discussed
- No unresolved conversations
- Squash or rebase before merge (team preference)
Development Workflow
Initial Setup
# Clone repository
git clone <repository-url>
cd <project-name>
# Install dependencies
npm install # or: pip install -r requirements.txt
# Set up environment variables
cp .env.example .env
# Edit .env with your local configuration
# Set up database (if applicable)
npm run db:setup # or: python manage.py migrate
# Run tests to verify setup
npm test
# Start development server
npm run dev
Daily Development Workflow
# 1. Update your local main branch
git checkout main
git pull origin main
# 2. Create feature branch
git checkout -b feature/your-feature-name
# 3. Make changes, commit frequently
git add .
git commit -m "feat: implement user profile page"
# 4. Run tests before pushing
npm test
# 5. Push branch
git push origin feature/your-feature-name
# 6. Create Pull Request on GitHub/GitLab
# 7. After PR approval, merge and clean up
git checkout main
git pull origin main
git branch -d feature/your-feature-name
Running Tests
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
# Run specific test file
npm test path/to/test-file.test.ts
# Run E2E tests
npm run test:e2e
Building & Running
# Development mode (with hot reload)
npm run dev
# Production build
npm run build
# Run production build locally
npm start
# Type checking (TypeScript)
npm run type-check
# Linting
npm run lint
# Format code
npm run format
Environment Configuration
Environment Variables
Create a .env file based on .env.example:
# Application
NODE_ENV=development
PORT=3000
API_URL=http://localhost:3000/api
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
DB_SSL=false
# Authentication
JWT_SECRET=your-super-secret-key-change-in-production
JWT_EXPIRES_IN=7d
SESSION_SECRET=another-secret-key
# External Services
STRIPE_SECRET_KEY=sk_test_...
STRIPE_PUBLISHABLE_KEY=pk_test_...
SENDGRID_API_KEY=SG...
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
AWS_REGION=us-east-1
# Feature Flags
ENABLE_ANALYTICS=true
ENABLE_DEBUG_MODE=false
# Logging
LOG_LEVEL=info
Environment-Specific Config
- Development:
.env(local only, not committed) - Staging:
.env.staging(committed, non-sensitive values) - Production: Environment variables set in hosting platform
API Documentation
API Structure
- Base URL:
https://api.example.com/v1 - Authentication: Bearer token in Authorization header
- Response Format: JSON
- Error Format: Consistent error objects
Authentication
POST /auth/login
Content-Type: application/json
{
"email": "user@example.com",
"password": "password"
}
Response:
{
"token": "jwt-token-here",
"user": { "id": 1, "email": "user@example.com" }
}
Standard Endpoints Pattern
GET /api/resources - List all
GET /api/resources/:id - Get one
POST /api/resources - Create
PUT /api/resources/:id - Update (full)
PATCH /api/resources/:id - Update (partial)
DELETE /api/resources/:id - Delete
Response Codes
200- Success201- Created204- No Content (successful deletion)400- Bad Request (validation errors)401- Unauthorized (not authenticated)403- Forbidden (not authorized)404- Not Found422- Unprocessable Entity (semantic errors)500- Internal Server Error
Database
Schema Overview
Brief description of main tables/collections and their relationships.
Migrations
# Create new migration
npm run migration:create -- AddUserTable
# Run migrations
npm run migration:run
# Rollback last migration
npm run migration:revert
# Generate migration from schema changes
npm run migration:generate
Seeding
# Seed database with test data
npm run db:seed
# Reset and reseed
npm run db:reset
Deployment
Deployment Strategy
- Development: Auto-deploy from
developbranch to dev environment - Staging: Auto-deploy from
mainbranch to staging - Production: Manual deploy from tagged releases
Pre-Deployment Checklist
- All tests passing in CI/CD
- Code review completed and approved
- Database migrations prepared (if needed)
- Environment variables configured
- Monitoring and logging verified
- Rollback plan documented
Deployment Commands
# Build for production
npm run build
# Run production server
npm start
# Docker build
docker build -t project-name:latest .
# Docker compose
docker-compose up -d
Troubleshooting & Common Issues
Issue: Tests Failing Locally
Symptoms: Tests pass in CI but fail locally Solution:
- Clear node_modules and reinstall:
rm -rf node_modules && npm install - Check Node.js version matches CI
- Verify environment variables are set correctly
Issue: Build Errors
Symptoms: Build fails with TypeScript errors Solution:
- Run
npm run type-checkto see all type errors - Check that all dependencies are installed
- Verify tsconfig.json settings
Issue: Database Connection Fails
Symptoms: Cannot connect to database Solution:
- Verify DATABASE_URL in .env
- Check database is running:
docker psor service status - Test connection:
psql $DATABASE_URL
Dependencies & Third-Party Services
Core Dependencies
List and briefly explain key dependencies:
- [dependency-name] (v1.2.3) - Purpose and why it's used
- [another-dependency] (v2.0.0) - Purpose and why it's used
External Services
- Authentication: Auth0 / Firebase Auth / Custom JWT
- Email: SendGrid / Mailgun
- Payment: Stripe / PayPal
- Storage: AWS S3 / Cloudinary
- Monitoring: Sentry / DataDog
- Analytics: Google Analytics / Mixpanel
Security Considerations
Security Best Practices
- All passwords must be hashed (bcrypt, minimum 10 rounds)
- Use parameterized queries (prevent SQL injection)
- Validate and sanitize all user input
- Implement rate limiting on all public endpoints
- Use HTTPS in production (enforce with HSTS)
- Set secure HTTP headers (CSP, X-Frame-Options, etc.)
- Regularly update dependencies (
npm audit) - Never commit secrets to git
- Use environment variables for sensitive config
- Implement CSRF protection for state-changing operations
Secrets Management
- Development:
.envfile (not committed) - Production: Use secret management service (AWS Secrets Manager, Vault, etc.)
- Rotate secrets regularly
- Use different secrets for each environment
Performance Optimization
Frontend Performance
- Code splitting and lazy loading
- Image optimization (WebP, responsive images)
- Minimize bundle size (tree shaking, dead code elimination)
- Use CDN for static assets
- Implement caching strategies
Backend Performance
- Database query optimization (indexes, query planning)
- Caching layer (Redis) for frequently accessed data
- Connection pooling for database connections
- API response pagination
- Rate limiting to prevent abuse
Monitoring
- Track response times
- Monitor error rates
- Set up alerts for anomalies
- Regular performance audits
Team Conventions
Communication
- Slack/Discord: Quick questions, daily updates
- GitHub Issues: Bug reports, feature requests
- Pull Requests: Code discussion
- Weekly Standup: Team sync (if applicable)
Code Review Standards
- Review within 24 hours
- Be constructive and specific
- Approve only if you'd be comfortable deploying it
- Ask questions if something is unclear
- Suggest improvements, don't demand perfection
Documentation
- Update docs with code changes
- Document "why" decisions in comments or ADRs
- Keep README.md current
- Update API docs when endpoints change
Additional Resources
Documentation
External Links
Useful Commands Reference
# Quick command reference
npm run dev # Start development server
npm test # Run tests
npm run build # Build for production
npm run lint # Lint code
npm run format # Format code
npm run type-check # TypeScript type checking
npm run db:migrate # Run database migrations
Claude Code Specific Instructions
Mandatory Tooling Usage Policy
CRITICAL: Claude Code must maximize the use of available advanced features for efficiency and quality:
🎯 Agent Usage (REQUIRED)
-
ALWAYS consider using specialized agents for their intended tasks:
Exploreagent: For codebase exploration, file pattern searches, keyword searchestest-engineer: For generating comprehensive test suitescode-reviewer: For code quality and security reviewsrefactoring-specialist: For code cleanup and optimizationdebugger: For systematic bug diagnosisarchitect: For system design and technical planningdocumentation-writer: For comprehensive documentationsecurity-analyst: For security reviews and vulnerability assessments
-
When NOT to use agents:
- Single file reads with known path
- Simple, straightforward edits
- Tasks that can be completed in 1-2 tool calls
IF YOU DECIDE NOT TO USE AN AGENT: State explicitly at the beginning of your response:
🔧 Agent Decision: Not using agents for this task because [specific reason: e.g., "single file read", "straightforward edit", "no codebase exploration needed"]
⚡ Slash Command Usage (REQUIRED)
- ALWAYS check available slash commands before starting complex tasks
- Use custom commands when they match the task:
/test [file-or-path]: Generate and run tests/review [file-or-path]: Review code quality/optimize [file-or-function]: Performance optimization/implement [feature-description]: Feature implementation/explain [file-or-selection]: Code explanation/analyze [path]: Comprehensive code analysis/adr [operation]: Manage Architectural Decision Records/scaffold [type] [name]: Generate boilerplate code
IF YOU DECIDE NOT TO USE SLASH COMMANDS: State explicitly:
🔧 Slash Command Decision: Not using slash commands because [specific reason: e.g., "no matching command available", "task too specific for generic command"]
🔌 MCP Server Usage (REQUIRED)
- ALWAYS leverage MCP servers for their specialized capabilities:
serena: Advanced semantic code search, symbol manipulation, project memorycontext7: Up-to-date library documentationfetch: Web content retrievalsequential-thinking: Complex problem decompositionmemory: Knowledge graph for persistent contextplaywright: Browser automationwindows-mcp: Windows desktop interaction
IF YOU DECIDE NOT TO USE MCP SERVERS: State explicitly:
🔧 MCP Server Decision: Not using MCP servers because [specific reason: e.g., "no relevant MCP capability for this task", "using built-in tools is more direct"]
When Working with This Project
Claude should:
- ✅ ALWAYS provide tooling decision statements at the start of each task
- ✅ Follow all code style guidelines defined above
- ✅ Run tests before suggesting commits (consider using
/testcommand) - ✅ Use the defined commit message format
- ✅ Ask for clarification on ambiguous requirements
- ✅ Suggest tests for new features (consider using
test-engineeragent) - ✅ Reference issue numbers in commits when applicable
- ✅ Maintain consistency with existing code patterns
- ✅ Update documentation when changing functionality
- ✅ Use parallel tool calls whenever possible for efficiency
- ✅ Leverage specialized agents, slash commands, and MCP servers to their full extent
Important Project Context
Critical Files to Understand:
- [List 3-5 most important files for understanding the codebase]
- [e.g.,
src/index.ts- Application entry point] - [e.g.,
src/routes/api.ts- API route definitions]
Common Tasks:
- Adding a new feature: Create feature branch, implement with tests, update docs, create PR
- Fixing a bug: Reproduce issue, write failing test, fix bug, verify test passes, commit
- Refactoring: Ensure tests pass before and after, maintain behavior, improve code quality
Project-Specific Patterns:
- [Describe any unique patterns or architectural decisions]
- [e.g., "We use repository pattern for data access"]
- [e.g., "All API responses are wrapped in a Result type"]
Skills & Commands Available
- Review available skills:
/skillsor check.claude/skills/ - Review available commands:
/helpor check.claude/commands/
Task Initiation Requirements
MANDATORY: At the START of EVERY task response, provide:
🎯 Tooling Strategy Decision
Task Analysis: [Brief description of the task]
Tooling Decisions:
- Agents: Using [agent-name] / Not using agents - Reason: [specific justification]
- Slash Commands: Using [/command] / Not using - Reason: [specific justification]
- MCP Servers: Using [server: tool] / Not using - Reason: [specific justification]
- Approach: [Overall strategy for completing the task]
Task Completion Status Messages
IMPORTANT: At the end of EVERY response where you performed work, provide this summary:
📊 Task Completion Summary
What Was Done: [Brief description of tasks completed]
Features Involved:
- Agents: [Agent1, Agent2, or None - with usage justification]
- Slash Commands: [/command1, /command2, or None - with usage justification]
- MCP Servers: [Server1: tool1/tool2, Server2: tool3, or None - with usage justification]
- Core Tools: [Read, Write, Edit, Glob, Grep, Bash, WebFetch, WebSearch, Task]
- Files Modified: [file1.md, file2.ts, or None]
- Performance: [Parallel ops, extended thinking, or N/A]
Efficiency Notes: [Any observations about tooling choices and their impact]
Changelog
Version 1.0.0 (YYYY-MM-DD)
- Initial project setup
- Core features implemented
- Documentation created
License
[Specify license - MIT, Apache 2.0, Proprietary, etc.]
Contact & Support
Maintainers:
- [Name] - @github-handle - email@example.com
Getting Help:
- Check this documentation first
- Search existing GitHub issues
- Ask in team chat
- Create new GitHub issue
Last Updated: YYYY-MM-DD Template Version: 1.0.0