# [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 `camelCase` for variables and functions (JavaScript/TypeScript) - Use `snake_case` for variables and functions (Python) - Use descriptive names that reveal intent - Avoid single-letter variables except in loops or mathematical contexts ```typescript // Good const userProfile = getUserProfile(); const isAuthenticated = checkAuth(); // Avoid const x = getUser(); const flag = check(); ``` #### Classes & Components - Use `PascalCase` for classes and React components - Name classes with nouns that describe what they represent - Name components based on what they render ```typescript // Good class UserRepository { } function UserProfileCard() { } // Avoid class userData { } function component1() { } ``` #### Constants - Use `UPPER_SNAKE_CASE` for constants - Group related constants in enums or objects ```typescript // Good const MAX_RETRY_ATTEMPTS = 3; const API_BASE_URL = process.env.API_URL; // Avoid const maxretries = 3; ``` #### Files & Folders - Use `kebab-case` for file and folder names - Match file name to primary export - Use `.test.ts` suffix for test files - Use `.spec.ts` for 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 ```typescript // 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: 1. External dependencies 2. Internal modules (absolute imports) 3. Relative imports 4. Type imports (if separate) 5. Styles ```typescript // 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) ```typescript // 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: ```typescript /** * 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) ```typescript // 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 `any` type; use `unknown` when type is truly unknown - Define explicit return types for functions - Use branded types for IDs and sensitive data ```typescript // Good function getUser(id: UserId): Promise { // implementation } // Avoid function getUser(id: any): Promise { // 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 ```typescript 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 code - `develop` - Integration branch for features - `feature/*` - 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 ```bash # 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: ``` ():