Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:25:07 +08:00
commit f613de7a1a
13 changed files with 4333 additions and 0 deletions

View File

@@ -0,0 +1,534 @@
# Commit Message Guide
A comprehensive guide to writing clear, consistent, and maintainable commit messages using the Conventional Commits format.
---
## Why Good Commit Messages Matter
- **Documentation**: Git history becomes a changelog
- **Code Review**: Easier to understand what changed and why
- **Debugging**: Quickly find when bugs were introduced
- **Automation**: Enables automatic changelog generation and versioning
- **Professionalism**: Shows attention to detail and respect for maintainers
---
## Conventional Commits Format
```
<type>(<scope>): <subject>
[optional body]
[optional footer(s)]
```
### Components
**Type** (required): Category of change
**Scope** (optional): What section of codebase is affected
**Subject** (required): Brief description of change
**Body** (optional): Detailed explanation
**Footer** (optional): Issue references, breaking changes
---
## Types
### Primary Types
**feat**: New feature for the user
```
feat(auth): add OAuth2 support for Google and GitHub
```
**fix**: Bug fix for the user
```
fix(api): resolve memory leak in worker shutdown
```
**docs**: Documentation changes only
```
docs(readme): update installation instructions for v2.0
```
**style**: Code style changes (formatting, missing semicolons, etc.)
```
style(components): format code with Prettier
```
**refactor**: Code change that neither fixes bug nor adds feature
```
refactor(auth): extract middleware to separate module
```
**perf**: Performance improvement
```
perf(database): add index to user_id column
```
**test**: Adding or updating tests
```
test(auth): add OAuth flow integration tests
```
### Supporting Types
**build**: Changes to build system or dependencies
```
build(deps): upgrade React to v18.2.0
```
**ci**: CI configuration changes
```
ci(github): add automated release workflow
```
**chore**: Other changes that don't modify src or test files
```
chore(deps): update dev dependencies
```
**revert**: Revert a previous commit
```
revert: feat(auth): add OAuth2 support
This reverts commit abc123def456.
```
---
## Subject Line Rules
### The 7 Rules
1. **Limit to 50 characters** (hard limit: 72)
2. **Use imperative mood** ("Add" not "Added" or "Adds")
3. **Capitalize first word** after the colon
4. **Don't end with punctuation**
5. **Focus on WHAT changed** (body explains WHY)
6. **Be specific** but concise
7. **Start with type** (if using Conventional Commits)
### Examples
**Good:**
```
feat(api): add user authentication endpoint
fix(ui): resolve button alignment on mobile
docs(contributing): clarify PR submission process
refactor(utils): simplify date formatting logic
```
**Bad:**
```
Fixed stuff # Too vague
Added new feature to the authentication system that allows users to login with OAuth # Too long
updated code # Not specific, wrong tense
feat(api): add user authentication. # Don't end with period
Feat(api): add auth # Don't capitalize type
```
---
## Optional Scope
The scope provides context about what part of the codebase changed.
### Common Scopes
```
feat(auth): ... # Authentication
feat(api): ... # API layer
feat(ui): ... # User interface
feat(database): ... # Database
feat(docs): ... # Documentation
feat(tests): ... # Tests
fix(deps): ... # Dependencies
build(webpack): ... # Build tooling
```
### Project-Specific Scopes
Check the project's recent commits for conventions:
```bash
git log --oneline -20
```
### When to Omit Scope
Scope is optional. Omit when:
- Change affects multiple areas
- Project doesn't use scopes
- Scope would be too generic
```
feat: add dark mode support
docs: update README
```
---
## Body (Optional)
The body provides detailed explanation of WHAT and WHY (code shows HOW).
### Rules
- Separate from subject with blank line
- Wrap at 72 characters per line
- Explain motivation and context
- Contrast with previous behavior
- Use bullet points for multiple points
### Example
```
feat(api): add rate limiting to authentication endpoints
Users can now make up to 100 authentication attempts per hour
per IP address. This prevents brute force attacks while allowing
legitimate users to retry failed login attempts.
Implementation details:
- Uses Redis for distributed rate limiting
- Configurable via RATE_LIMIT_MAX environment variable
- Returns 429 status with Retry-After header when exceeded
- Resets hourly at top of the hour
Previous behavior allowed unlimited attempts, which was identified
as a security vulnerability in audit #456.
```
### When to Include Body
Include a body when:
- Change is complex or non-obvious
- Design decisions need explanation
- Previous behavior needs context
- Multiple related changes in one commit
- Security or performance implications
### When to Skip Body
Skip the body when:
- Change is self-explanatory
- Subject line tells the complete story
- Trivial changes (typos, formatting)
---
## Footer (Optional)
Footers provide metadata about the commit.
### Breaking Changes
Use `BREAKING CHANGE:` footer for breaking changes:
```
feat(api)!: change authentication endpoint path
BREAKING CHANGE: The authentication endpoint has moved from
/api/auth to /api/v2/auth. Update your API calls accordingly.
Migration guide available at docs/migration/v2.md
```
Note the `!` after the type indicates a breaking change.
### Issue References
Link issues using keywords for automatic closing:
```
fix(ui): resolve mobile layout issues
Fixes #123
Closes #456, #789
Relates to #234
```
**Closing Keywords:**
- `Closes #123`
- `Fixes #123`
- `Resolves #123`
- Also: close, fix, resolve (case insensitive)
### Co-authored-by
Credit co-authors:
```
feat(api): add GraphQL support
Co-authored-by: Jane Doe <jane@example.com>
Co-authored-by: John Smith <john@example.com>
```
### Other Footers
```
Reviewed-by: Name <email>
Signed-off-by: Name <email>
Acked-by: Name <email>
See-also: #123
```
---
## Complete Examples
### Example 1: Simple Feature
```
feat(ui): add dark mode toggle
Adds a toggle button in settings to switch between light and dark
themes. User preference is saved to localStorage and persists
across sessions.
Closes #234
```
### Example 2: Bug Fix
```
fix(api): prevent race condition in cache invalidation
The cache invalidation logic wasn't thread-safe, causing occasional
race conditions when multiple workers tried to invalidate the same
key simultaneously.
Solution:
- Added mutex locks around the critical section
- Implemented timeout for lock acquisition (5s)
- Added retry logic with exponential backoff
- Updated tests to verify thread-safety
Fixes #456
```
### Example 3: Breaking Change
```
feat(api)!: migrate to TypeScript and update endpoint contracts
BREAKING CHANGE: All API endpoints now return ISO 8601 date
strings instead of Unix timestamps. Update client code to parse
dates accordingly.
Additionally, authentication now requires JWT tokens in the
Authorization header instead of session cookies.
Migration guide: docs/migration/v3.md
Closes #567
```
### Example 4: Refactoring
```
refactor(auth): extract middleware to separate module
No functional changes, but auth logic is now easier to test and
maintain. Consolidated duplicate code from 5 route handlers into
reusable middleware functions.
Files affected:
- New: middleware/authenticate.js
- Updated: routes/*.js (5 files)
- Tests: tests/middleware/auth.test.js
Relates to #301 (technical debt epic)
```
### Example 5: Documentation
```
docs(api): add examples for authentication flows
Added code examples for:
- Basic authentication with username/password
- OAuth2 flow with Google
- API key authentication
- JWT token refresh
Examples include curl commands and JavaScript fetch() snippets.
Closes #678
```
### Example 6: Multiple Related Changes
```
fix(auth): resolve multiple OAuth edge cases
- Handle expired refresh tokens gracefully
- Prevent account linking when email doesn't match
- Add rate limiting to token refresh endpoint
- Log failed OAuth attempts for security monitoring
Each issue was related to OAuth implementation and fixing them
separately would have caused merge conflicts.
Fixes #123, #456, #789
```
---
## Tips for Writing Good Commit Messages
### Do:
✅ Write in imperative mood ("Add" not "Added")
```
feat: add user profile page
```
✅ Be specific about what changed
```
fix(api): resolve timeout in user search endpoint
```
✅ Explain WHY in the body
```
refactor(db): switch to connection pooling
The previous approach created a new connection for each request,
which caused performance issues under load. Connection pooling
reduces overhead and improves response times by 40%.
```
✅ Use the body for complex changes
✅ Reference issues and PRs
✅ Follow project conventions
### Don't:
❌ Use past tense
```
feat: added user profile page ❌
```
❌ Be vague
```
fix: bug fix ❌
update: changes ❌
```
❌ Write novels in the subject line
```
feat(api): add new user authentication endpoint with OAuth2 support for Google and GitHub that also includes rate limiting ❌
```
❌ Skip the type (if project uses Conventional Commits)
```
Add user profile page ❌
```
❌ Use abbreviations or jargon unnecessarily
```
fix(db): rm dup recs via opt idx ❌
```
❌ Combine unrelated changes in one commit
```
feat: add dark mode, fix typo in README, update dependencies ❌
```
---
## Real-World Examples from Popular Projects
### React
```
feat(react-dom): Add support for CSS Layers
Implements support for @layer, enabling better CSS encapsulation.
Fixes #24556
```
### Node.js
```
doc: add missing types to request and response
Added TypeScript type definitions for several Request and Response
methods that were previously missing from the declarations.
Fixes: #12345
Refs: #67890
```
### Kubernetes
```
fix: prevent pod creation with invalid security context
Adds validation to reject pods with both `runAsUser: 0` and
`allowPrivilegeEscalation: false`, which is an invalid combination.
Closes #12345
```
---
## Commit Message Checklist
Before committing, verify:
- [ ] Type is correct (feat, fix, docs, etc.)
- [ ] Subject line under 50 characters (max 72)
- [ ] Imperative mood ("Add" not "Added")
- [ ] First word capitalized
- [ ] No period at end
- [ ] Body explains WHY (if needed)
- [ ] Body wrapped at 72 characters
- [ ] Blank line between subject and body
- [ ] Issues referenced in footer
- [ ] Breaking changes noted with BREAKING CHANGE:
- [ ] Follows project conventions
---
## Tools & Automation
### Commitizen
Interactive tool for writing commits:
```bash
npm install -g commitizen
git cz
```
### Commitlint
Lint commit messages:
```bash
npm install --save-dev @commitlint/cli @commitlint/config-conventional
```
### Husky
Git hooks to enforce commit message format:
```bash
npm install --save-dev husky
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit ${1}'
```
---
## Resources
**Specifications:**
- Conventional Commits: https://www.conventionalcommits.org/
- Git Commit Guidelines: https://git-scm.com/book/en/v2/Distributed-Git-Contributing-to-a-Project
**Tools:**
- Commitizen: https://github.com/commitizen/cz-cli
- Commitlint: https://commitlint.js.org/
**Further Reading:**
- "How to Write a Git Commit Message": https://chris.beams.io/posts/git-commit/
- Angular Commit Guidelines: https://github.com/angular/angular/blob/main/CONTRIBUTING.md#commit

View File

@@ -0,0 +1,533 @@
# Files to Exclude from Pull Requests
A comprehensive reference of files that should NEVER be included in open source pull requests, organized by category.
---
## Personal Development Artifacts
### Session & Notes Files
```
❌ SESSION.md # Session tracking
❌ NOTES.md # Development notes
❌ TODO.md # Personal todo lists
❌ SCRATCH.md # Scratch notes
❌ DEBUGGING.md # Debugging notes
❌ TESTING.md # Testing notes
❌ JOURNAL.md # Development journal
❌ IDEAS.md # Personal ideas
❌ THOUGHTS.md # Random thoughts
❌ WIP.md # Work in progress notes
```
### Planning Documents
```
❌ planning/ # Entire planning directory
❌ IMPLEMENTATION_PHASES.md # Phase-based planning
❌ DATABASE_SCHEMA.md # Database planning (unless adding to project)
❌ ARCHITECTURE.md # Architecture planning (unless adding to project)
❌ API_ENDPOINTS.md # API planning (unless adding to project)
❌ UI_COMPONENTS.md # UI planning (unless adding to project)
❌ PROJECT_SPEC.md # Project specifications
❌ ROADMAP.md # Personal roadmap
❌ MILESTONES.md # Personal milestones
```
### Research & Reference
```
❌ research-logs/ # Research directory
❌ references/ # Personal references (skill-specific)
❌ research-*.md # Research documents
❌ analysis-*.md # Analysis documents
❌ comparison-*.md # Comparison documents
❌ evaluation-*.md # Evaluation documents
```
---
## Screenshots & Visual Assets
### Debug & Development Screenshots
```
❌ screenshots/debug-*.png # Debugging screenshots
❌ screenshots/test-*.png # Testing screenshots
❌ screenshots/scratch-*.png # Scratch screenshots
❌ screenshot-*.png # Ad-hoc screenshots
❌ screen-recording-*.mp4 # Screen recordings
❌ before-after-local.png # Local comparisons
❌ demo-local.* # Local demos
❌ temp-visual.* # Temporary visuals
```
### When Screenshots ARE Okay
```
✅ docs/assets/ui-example.png # Documentation assets
✅ screenshots/feature-demo.png # Demonstrating feature in PR description
✅ docs/images/architecture.png # Architecture diagrams for project docs
```
**Rule of Thumb**: Only include screenshots if they:
1. Demonstrate a feature for the PR description
2. Are part of documentation updates
3. Would be useful to all users/developers
---
## Test Files (Situational)
### Temporary Test Files (NEVER Include)
```
❌ test-manual.js # Manual testing scripts
❌ test-debug.ts # Debugging tests
❌ test-quick.py # Quick validation tests
❌ scratch-test.sh # Scratch test scripts
❌ example-local.json # Local test data
❌ quick-test.* # Quick test files
❌ debug-test.* # Debug test files
❌ temp-test.* # Temporary tests
❌ playground.* # Playground files
❌ experiment.* # Experimental files
```
### Proper Test Files (Include These)
```
✅ tests/feature.test.js # Proper test suite
✅ tests/fixtures/data.json # Required test fixtures
✅ __tests__/component.tsx # Component tests
✅ spec/feature_spec.rb # RSpec tests
✅ test_feature.py # Python tests
```
**Rule**: Only include tests that:
1. Are part of the project's test suite structure
2. Follow project's testing conventions
3. Will be run by CI/other developers
4. Test the specific feature/fix in the PR
---
## Build Artifacts & Dependencies
### Build Output
```
❌ dist/ # Build output
❌ build/ # Build directory
❌ out/ # Output directory
❌ target/ # Rust/Java build directory
❌ bin/ # Binary output (usually)
❌ lib/ # Library output (usually)
❌ *.exe, *.dll, *.so # Compiled binaries
❌ *.o, *.obj # Object files
❌ *.pyc, *.pyo # Python compiled files
❌ __pycache__/ # Python cache
❌ .next/ # Next.js build
❌ .nuxt/ # Nuxt build
❌ .output/ # Nitro build
```
### Dependencies
```
❌ node_modules/ # Node dependencies
❌ vendor/ # Ruby/PHP dependencies
❌ venv/ # Python virtual environment
❌ .venv/ # Python virtual environment
❌ env/ # Environment directory
❌ Cargo.lock # Rust dependencies (situational)
❌ package-lock.json # NPM lock (situational)
❌ yarn.lock # Yarn lock (situational)
❌ pnpm-lock.yaml # PNPM lock (situational)
```
**Lock File Rule**: Only include lock files if:
- Project explicitly requires them (check CONTRIBUTING.md)
- You're adding/updating dependencies
- Project uses lock files (check existing files in repo)
### Cache & Temporary Build Files
```
❌ .cache/ # Cache directory
❌ .tmp/ # Temporary files
❌ .temp/ # Temporary files
❌ tmp/ # Temporary directory
❌ temp/ # Temporary directory
❌ *.cache # Cache files
❌ .eslintcache # ESLint cache
❌ .parcel-cache/ # Parcel cache
❌ .turbo/ # Turborepo cache
```
---
## IDE & Editor Files
### VS Code
```
❌ .vscode/ # VS Code settings (use global gitignore)
❌ *.code-workspace # Workspace files
```
### JetBrains (IntelliJ, WebStorm, etc.)
```
❌ .idea/ # IntelliJ settings
❌ *.iml # Module files
❌ *.ipr # Project files
❌ *.iws # Workspace files
```
### Vim
```
❌ *.swp # Swap files
❌ *.swo # Swap files
❌ *~ # Backup files
❌ .*.sw? # Swap files pattern
```
### Emacs
```
❌ *~ # Backup files
❌ \#*\# # Auto-save files
❌ .\#* # Lock files
```
### Sublime Text
```
❌ *.sublime-project # Project files
❌ *.sublime-workspace # Workspace files
```
**Exception**: If the project provides official IDE configurations (like .vscode/settings.json in the repo), you may update those if needed for the feature.
---
## Operating System Files
### macOS
```
❌ .DS_Store # Finder metadata
❌ .AppleDouble # Resource forks
❌ .LSOverride # Icon metadata
❌ ._* # Resource forks
```
### Windows
```
❌ Thumbs.db # Thumbnail cache
❌ ehthumbs.db # Thumbnail cache
❌ Desktop.ini # Folder settings
❌ $RECYCLE.BIN/ # Recycle bin
```
### Linux
```
❌ .directory # KDE directory settings
❌ .Trash-*/ # Trash directory
```
---
## Secrets & Credentials (CRITICAL!)
### Environment Files
```
❌ .env # Environment variables (NEVER!)
❌ .env.local # Local environment
❌ .env.development # Development environment
❌ .env.production # Production environment (NEVER!)
❌ .env.*.local # Any local env files
❌ config/local.json # Local configuration
❌ config/secrets.json # Secrets configuration
```
### Credentials
```
❌ credentials.json # Credentials file
❌ secrets.json # Secrets file
❌ auth.json # Authentication file
❌ token.txt # Token files
❌ api-keys.json # API keys
❌ service-account.json # Service account credentials
```
### Keys & Certificates
```
❌ *.key # Private keys
❌ *.pem # PEM certificates
❌ *.p12 # PKCS#12 certificates
❌ *.pfx # PFX certificates
❌ id_rsa # SSH private key
❌ id_dsa # SSH private key
❌ *.crt (sometimes) # Certificates
```
### Password & Secret Patterns
Look for these in file contents:
```
❌ password=
❌ api_key=
❌ api-key=
❌ apiKey=
❌ secret=
❌ token=
❌ access_token=
❌ private_key=
```
**CRITICAL**: Even if deleted later, secrets in git history are compromised. Use `git filter-branch` or BFG Repo-Cleaner if secrets are committed.
---
## Logs & Debugging
### Log Files
```
❌ *.log # Log files
❌ logs/ # Logs directory
❌ debug.log # Debug logs
❌ error.log # Error logs
❌ npm-debug.log # NPM debug logs
❌ yarn-debug.log # Yarn debug logs
❌ yarn-error.log # Yarn error logs
❌ lerna-debug.log # Lerna debug logs
```
### Debug Files
```
❌ debug-*.js # Debug scripts
❌ debug-*.py # Debug scripts
❌ trace-*.txt # Trace files
❌ profile-*.json # Profiling output
❌ *.prof # Profiling files
❌ *.trace # Trace files
```
### Crash Dumps
```
❌ core # Core dumps
❌ core.* # Core dumps
❌ *.dmp # Dump files
❌ crash-*.log # Crash logs
```
---
## Database & Data Files
### Database Files (Local Development)
```
❌ *.db # SQLite databases (local)
❌ *.sqlite # SQLite databases (local)
❌ *.sqlite3 # SQLite databases (local)
❌ dump.sql # Database dumps
❌ backup.sql # Database backups
❌ *.mdb # Access databases
```
### Data Files (Local/Personal)
```
❌ data/local/ # Local data directory
❌ data/personal/ # Personal data
❌ data/test-data.json # Test data (unless fixtures)
❌ sample-data-local.json # Local sample data
```
**Exception**: Include database files if:
- They're part of the project's test fixtures
- They're example/seed data for the project
- Project explicitly includes them (check existing repo)
---
## Coverage & Reports
### Test Coverage
```
❌ coverage/ # Coverage reports
❌ .coverage # Coverage data
❌ htmlcov/ # HTML coverage
❌ .nyc_output/ # NYC coverage
❌ lcov.info # LCOV coverage
```
### Reports
```
❌ reports/ # Generated reports
❌ test-results/ # Test results
❌ junit.xml # JUnit reports
❌ cypress/videos/ # Cypress videos
❌ cypress/screenshots/ # Cypress screenshots (unless demonstrating bug)
```
---
## Version Control (Other Than Git)
### SVN
```
❌ .svn/ # SVN metadata
```
### Mercurial
```
❌ .hg/ # Mercurial metadata
❌ .hgignore # Mercurial ignore
```
### CVS
```
❌ CVS/ # CVS metadata
❌ .cvsignore # CVS ignore
```
---
## What SHOULD Be Included
For reference, these ARE okay to include:
### Source Code
```
✅ src/ # Source code
✅ lib/ # Library code (if source, not compiled)
✅ app/ # Application code
✅ components/ # Component files
✅ utils/ # Utility functions
```
### Tests
```
✅ tests/ # Test directory
✅ __tests__/ # Jest tests
✅ spec/ # RSpec tests
✅ test_*.py # Python tests
```
### Documentation
```
✅ README.md # Project readme
✅ CHANGELOG.md # Changelog
✅ CONTRIBUTING.md # Contributing guide
✅ LICENSE # License file
✅ docs/ # Documentation directory
```
### Configuration (Project-level)
```
✅ .gitignore # Git ignore rules
✅ .eslintrc # ESLint config (if updating)
✅ .prettierrc # Prettier config (if updating)
✅ tsconfig.json # TypeScript config (if updating)
✅ package.json # NPM package file (if updating)
✅ Cargo.toml # Rust config (if updating)
✅ pyproject.toml # Python config (if updating)
```
### CI/CD (if part of feature)
```
✅ .github/workflows/ # GitHub Actions
✅ .gitlab-ci.yml # GitLab CI
✅ .travis.yml # Travis CI
✅ Jenkinsfile # Jenkins
```
### Migrations & Schema (if part of feature)
```
✅ migrations/ # Database migrations
✅ schema.sql # Database schema (if adding to project)
✅ seeds/ # Seed data (if part of project)
```
---
## How to Prevent Including These Files
### 1. Project .gitignore
Add patterns that benefit ALL developers:
```gitignore
# Build
dist/
build/
*.pyc
# Dependencies
node_modules/
vendor/
# Logs
*.log
# Secrets
.env
.env.local
*.key
*.pem
```
### 2. Global .gitignore (Recommended)
Add personal/OS-specific patterns:
```bash
# Configure global gitignore
git config --global core.excludesfile ~/.gitignore_global
# Add your patterns
echo ".DS_Store" >> ~/.gitignore_global
echo ".vscode/" >> ~/.gitignore_global
echo ".idea/" >> ~/.gitignore_global
echo "*.swp" >> ~/.gitignore_global
```
### 3. Local Exclusions (.git/info/exclude)
For patterns specific to YOUR workflow only:
```bash
echo "SESSION.md" >> .git/info/exclude
echo "NOTES.md" >> .git/info/exclude
echo "planning/" >> .git/info/exclude
echo "screenshots/debug-*" >> .git/info/exclude
```
**Difference**:
- `.gitignore` → Committed, affects everyone
- `~/.gitignore_global` → Your global settings, affects all your repos
- `.git/info/exclude` → This repo only, not committed
---
## Quick Check Commands
### List all tracked files:
```bash
git ls-files
```
### Check for specific patterns:
```bash
git ls-files | grep -E "SESSION|NOTES|TODO|planning"
```
### Find large files:
```bash
git ls-files | while read file; do
[ -f "$file" ] && stat -f%z "$file" "$file"
done | sort -rn | head -20
```
### Search for secrets in staged files:
```bash
git diff --cached | grep -iE "password|secret|api[_-]?key|token"
```
### Use the pre-PR check script:
```bash
./scripts/pre-pr-check.sh
```
---
## Resources
- **Pre-PR Check Script**: Automated scanning for these patterns
- **Clean Branch Script**: Remove common artifacts safely
- **GitHub's gitignore templates**: https://github.com/github/gitignore
---
**Remember**: When in doubt, DON'T include it. You can always add files later if needed, but removing them from git history is much harder.

351
references/pr-checklist.md Normal file
View File

@@ -0,0 +1,351 @@
# Pull Request Submission Checklist
A comprehensive checklist to ensure your PR is ready for review and meets open source contribution standards.
---
## Pre-Contribution Phase
**Before starting any work:**
- [ ] **Read CONTRIBUTING.md** - Found in root, .github/, or docs/
- [ ] **Read CODE_OF_CONDUCT.md** - Understand community expectations
- [ ] **Check if issue exists** - Search existing issues for your topic
- [ ] **Create issue first (if needed)** - For significant changes, discuss before coding
- [ ] **Comment on issue to claim work** - Prevents duplicate effort
```
"Hi! I'd like to work on this. My approach would be to [brief outline]."
```
- [ ] **Wait for acknowledgment** - Especially for large changes
- [ ] **Fork the repository** - If you don't have write access
- [ ] **Set up upstream remote**
```bash
git remote add upstream https://github.com/ORIGINAL/repo.git
```
- [ ] **Create feature branch** - NEVER work on main/master
```bash
git checkout -b feature/descriptive-name
```
- [ ] **Understand testing requirements** - Check what tests are expected
- [ ] **Identify code style tools** - Look for .eslintrc, .prettierrc, etc.
---
## Development Phase
**While coding:**
- [ ] **Follow project style guidelines** - Match existing code patterns
- [ ] **Write tests for new functionality** - Most projects require this
- [ ] **Update tests for changed behavior** - Keep tests in sync with code
- [ ] **Add/update documentation** - README, API docs, inline comments
- [ ] **Keep commits atomic** - One logical change per commit
- [ ] **Write good commit messages** - Follow Conventional Commits format
```
feat(scope): brief description
Longer explanation if needed
Fixes #123
```
- [ ] **Run linters and formatters** - Fix style issues during development
```bash
npm run lint
npm run format
```
- [ ] **Test locally frequently** - Don't wait until the end
- [ ] **Keep PR scope focused** - One feature/fix per PR
- [ ] **Sync with upstream regularly** - Avoid merge conflicts
```bash
git fetch upstream
git rebase upstream/main
```
---
## Pre-Submission Phase
### Code Quality
- [ ] **All tests pass locally**
```bash
npm test
# or
pytest
# or
cargo test
# or project's test command
```
- [ ] **Code builds successfully**
```bash
npm run build
```
- [ ] **Linter passes**
```bash
npm run lint
```
- [ ] **Formatter applied**
```bash
npm run format
```
- [ ] **Code coverage maintained** - If project has minimum thresholds
- [ ] **No compiler warnings** - Clean build output
- [ ] **Manual testing completed** - Test the actual functionality
### Code Review (Self)
- [ ] **Review your own diff**
```bash
git diff origin/main
```
- [ ] **No debugging code** - Remove console.logs, debugger statements
- [ ] **No commented-out code** - Remove dead code
- [ ] **No TODO comments** - Complete work or create follow-up issues
- [ ] **Consistent naming** - Variables, functions, files match conventions
- [ ] **Proper error handling** - Don't swallow errors silently
- [ ] **Edge cases considered** - Null checks, empty arrays, etc.
### Cleanup (Critical!)
Run the pre-PR check script:
```bash
./scripts/pre-pr-check.sh
```
- [ ] **Remove SESSION.md** - Personal session tracking
- [ ] **Remove NOTES.md** - Development notes
- [ ] **Remove TODO.md** - Personal todo lists
- [ ] **Remove planning/* directory** - Project planning documents
- [ ] **Remove debug screenshots** - Screenshots used during debugging
- Keep only screenshots demonstrating features for PR description
- [ ] **Remove temporary test files**
- test-manual.js, test-debug.ts, quick-test.py
- [ ] **Remove personal workflow files**
- scratch.*, temp.*, debug.*
- [ ] **No IDE/editor files**
- .vscode/, .idea/, *.swp
- Should be in global .gitignore, not committed
- [ ] **No OS-specific files**
- .DS_Store, Thumbs.db, desktop.ini
- [ ] **No build artifacts**
- dist/, build/, node_modules/, __pycache__/
- [ ] **No secrets or credentials**
- .env, credentials.json, *.key, *.pem
- Double-check with: `git diff | grep -i "password\|secret\|key"`
- [ ] **No large binary files** - Unless necessary for the PR
- [ ] **No unrelated changes** - Only changes relevant to this PR
### Git Hygiene
- [ ] **Commits are clean** - No "WIP" or "fix typo" commits
- Consider squashing if needed
- [ ] **Commit messages follow conventions** - Conventional Commits format
- [ ] **No merge conflicts** - Rebase on latest upstream/main
```bash
git fetch upstream
git rebase upstream/main
```
- [ ] **Branch is up to date** - Latest changes from main included
- [ ] **On feature branch** - Not on main/master
---
## PR Creation Phase
### PR Description
- [ ] **Title follows conventions** - Conventional Commits format
```
feat(auth): add OAuth2 support
fix(api): resolve memory leak
docs(readme): update installation
```
- [ ] **Uses What/Why/How structure**
- What: Brief description of changes
- Why: Reasoning and context
- How: Implementation approach
- [ ] **Testing instructions included** - Step-by-step how to test
- [ ] **Screenshots for visual changes** - Before/after if applicable
- [ ] **Breaking changes noted** - If any
- [ ] **Links to related issues** - Use closing keywords
```
Closes #123
Fixes #456
Relates to #789
```
- [ ] **Checklist included** - Tests, docs, CI status
- [ ] **Description is clear** - Reviewer can understand without asking questions
### PR Quality
- [ ] **PR is reasonably sized**
- Ideal: < 50 lines
- Good: < 200 lines
- Max: < 400 lines
- If larger, explain why or split into multiple PRs
- [ ] **PR is focused** - One feature/fix/refactor, not multiple unrelated changes
- [ ] **No unrelated changes** - No "drive-by fixes" in unrelated files
- [ ] **All changed files are intentional** - Review git status
### GitHub Settings
- [ ] **Pushed to feature branch on fork**
```bash
git push origin feature/my-feature
```
- [ ] **PR targets correct branch** - Usually main or develop
- [ ] **Assigned labels** - If you have permission
- [ ] **Requested reviewers** - If known and appropriate
- [ ] **Linked to project/milestone** - If applicable
- [ ] **Set as draft** - If not ready for full review yet
```bash
gh pr create --draft
```
---
## Post-Submission Phase
### Monitor CI/Checks
- [ ] **CI is running** - Green checkmarks appearing
- [ ] **All checks pass** - No failures
- [ ] **Fix failures immediately** - Don't wait for review if CI fails
- [ ] **Watch for build notifications** - Email/GitHub notifications
### Communication
- [ ] **Responsive to feedback** - Reply within 24-48 hours
- [ ] **Address all review comments** - Even if just "Acknowledged"
- [ ] **Mark conversations resolved** - After addressing feedback
- [ ] **Request re-review** - After making changes
```bash
gh pr ready # if was draft
```
- [ ] **Thank reviewers** - Shows appreciation for their time
- [ ] **Professional tone** - Courteous and respectful
- [ ] **Ask for clarification** - If feedback is unclear
- [ ] **Be patient** - Reviewers are often volunteers
### Updates
- [ ] **Keep PR updated** - Rebase if main moves forward
```bash
git fetch upstream
git rebase upstream/main
git push origin feature/my-feature --force-with-lease
```
- [ ] **Fix requested changes** - Implement feedback
- [ ] **Update documentation** - If requirements change
- [ ] **Squash commits** - If maintainer requests
---
## Ready to Submit?
**Final verification:**
```bash
# 1. Run pre-PR check
./scripts/pre-pr-check.sh
# 2. Review changes
git status
git diff origin/main --stat
# 3. Verify tests pass
npm test
# 4. Verify build succeeds
npm run build
# 5. Check commit messages
git log --oneline -5
# 6. Push to your fork
git push origin feature/my-feature
# 7. Create PR
gh pr create --fill
# or
gh pr create --title "feat: ..." --body "$(cat pr-description.md)"
```
---
## Common Mistakes Checklist
Avoid these common errors:
- [ ] ❌ Not reading CONTRIBUTING.md
- [ ] ❌ Including personal artifacts (SESSION.md, planning/*)
- [ ] ❌ Submitting massive PR (>400 lines)
- [ ] ❌ Not testing before submission
- [ ] ❌ Working on already assigned issue
- [ ] ❌ Not discussing large changes first
- [ ] ❌ Being impatient or unresponsive
- [ ] ❌ Not updating documentation
- [ ] ❌ Ignoring code style
- [ ] ❌ Ignoring CI failures
- [ ] ❌ Including unrelated changes
- [ ] ❌ Not linking issues properly
- [ ] ❌ Committing secrets
- [ ] ❌ Force-pushing without warning
- [ ] ❌ Working on main/master branch
---
## Project-Specific Checklist
Add project-specific items here based on CONTRIBUTING.md:
- [ ] _[Project-specific requirement 1]_
- [ ] _[Project-specific requirement 2]_
- [ ] _[Project-specific requirement 3]_
---
## Quick Reference: Essential Commands
```bash
# Setup
git clone https://github.com/YOUR-USERNAME/repo.git
git remote add upstream https://github.com/ORIGINAL/repo.git
git checkout -b feature/my-feature
# Development
npm run lint
npm test
npm run build
git add .
git commit -m "feat(scope): description"
# Pre-submission
./scripts/pre-pr-check.sh
git status
git diff origin/main
# Submission
git push origin feature/my-feature
gh pr create --fill
# After feedback
git fetch upstream
git rebase upstream/main
# make changes
git push origin feature/my-feature --force-with-lease
```
---
## Resources
- **Pre-PR Check Script**: `./scripts/pre-pr-check.sh`
- **Clean Branch Script**: `./scripts/clean-branch.sh`
- **PR Template**: `./references/pr-template.md`
- **Commit Message Guide**: `./references/commit-message-guide.md`
- **Files to Exclude**: `./references/files-to-exclude.md`
---
**Remember**: The goal is to make the maintainer's job as easy as possible. A well-prepared PR shows respect for their time and increases the likelihood of quick acceptance.

266
references/pr-template.md Normal file
View File

@@ -0,0 +1,266 @@
# Pull Request Template
Use this template when creating pull requests to open source projects. Adapt as needed based on the project's CONTRIBUTING.md guidelines.
---
## Standard PR Template (What/Why/How)
```markdown
## What?
[Brief, clear description of what this PR does - 1-2 sentences]
## Why?
[Explain the reasoning, problem being solved, or business value - 2-3 sentences]
## How?
[Describe the implementation approach and key decisions - bullet points work well]
- Key change 1
- Key change 2
- Key change 3
## Testing
[Step-by-step instructions for reviewers to test the changes]
1. Step 1
2. Step 2
3. Expected result
## Checklist
- [ ] Tests added/updated
- [ ] Documentation updated
- [ ] CI passing
- [ ] Breaking changes documented (if any)
- [ ] Follows project code style
## Related Issues
Closes #[issue number]
Relates to #[issue number]
## Screenshots (if applicable)
[Add screenshots for visual changes, UI updates, or bug fixes]
## Additional Notes
[Any other context, concerns, or questions for reviewers]
```
---
## Example: Feature Addition
```markdown
## What?
Add OAuth2 authentication support for Google and GitHub providers
## Why?
Users have requested social login to reduce friction during signup. This implements Key Result 2 of Q4 OKR1 and addresses multiple user requests from issue #234.
## How?
- Implemented OAuth2 flow using passport.js strategy pattern
- Added provider configuration via environment variables
- Created callback routes for each provider (/auth/google/callback, /auth/github/callback)
- Updated user model to link social accounts with existing email-based accounts
- Added middleware to merge accounts if user already exists
## Testing
1. Set up OAuth apps in Google and GitHub developer consoles
2. Add credentials to `.env` file (see `.env.example` for required variables)
3. Run `npm install` to ensure passport dependencies are installed
4. Start server: `npm start`
5. Navigate to `/login`
6. Click "Login with Google" button
7. Verify OAuth flow redirects correctly
8. Verify user profile data merges correctly with existing account (if applicable)
9. Test GitHub provider following same steps
## Checklist
- [x] Tests added for OAuth flow (see tests/auth/oauth.test.js)
- [x] Documentation updated (see docs/authentication.md)
- [x] CI passing
- [x] No breaking changes
- [x] Follows existing code style
- [x] Environment variables documented in .env.example
## Related Issues
Closes #234
Relates to #156 (social login epic)
## Screenshots
![OAuth Login Buttons](./screenshots/oauth-buttons.png)
*New social login buttons on login page*
## Additional Notes
- Chose passport.js over custom implementation for security and maintenance
- Used strategy pattern to make adding new providers easier in future
- Account merging happens automatically based on email address
- Consider adding rate limiting for OAuth endpoints in future PR
```
---
## Example: Bug Fix
```markdown
## What?
Fix memory leak in worker process shutdown
## Why?
The worker pool wasn't properly cleaning up connections when shutting down gracefully, leading to memory leaks over time. This was causing production issues on long-running instances and reported in #456.
## How?
- Added connection cleanup in worker shutdown handler
- Implemented timeout for graceful shutdown (30s default)
- Added mutex locks to prevent race conditions during cleanup
- Updated tests to verify proper cleanup
## Testing
1. Run load test: `npm run test:load`
2. Monitor memory usage: `npm run monitor:memory`
3. Trigger graceful shutdown: `kill -SIGTERM <pid>`
4. Verify memory is released (check monitor output)
5. Run for 24 hours to verify no gradual memory increase
Manual testing:
- Tested on staging for 48 hours with production load
- Memory usage remained stable at ~120MB
- Previous behavior showed gradual increase to 2GB+ over 24h
## Checklist
- [x] Tests added for shutdown cleanup
- [x] Documentation updated (shutdown behavior in README)
- [x] CI passing
- [x] No breaking changes
- [x] Tested on staging environment
## Related Issues
Fixes #456
## Additional Notes
- Considered force-killing workers after timeout, but went with graceful degradation
- Mutex implementation follows existing pattern in connection-pool.js
- Backward compatible with existing shutdown handlers
```
---
## Example: Refactoring
```markdown
## What?
Refactor authentication middleware to improve testability and reduce duplication
## Why?
The authentication logic was duplicated across 5 different route handlers, making it difficult to test and maintain. This refactoring consolidates the logic into reusable middleware.
## How?
- Extracted auth logic into `middleware/authenticate.js`
- Created composable middleware functions:
- `requireAuth()` - Basic authentication check
- `requireRole(role)` - Role-based access control
- `optionalAuth()` - Sets user if authenticated, continues if not
- Updated all routes to use new middleware
- Maintained backward compatibility with existing behavior
## Testing
1. Run full test suite: `npm test`
2. Verify authentication still works:
- Try accessing protected route without token (should get 401)
- Access with valid token (should succeed)
- Access with invalid token (should get 401)
3. Verify role-based access:
- User role trying admin endpoint (should get 403)
- Admin role trying admin endpoint (should succeed)
All existing tests pass without modification, demonstrating backward compatibility.
## Checklist
- [x] All existing tests pass
- [x] Added tests for new middleware functions
- [x] Documentation updated
- [x] CI passing
- [x] No breaking changes
- [x] Code coverage maintained
## Related Issues
Relates to #301 (technical debt epic)
## Additional Notes
- No changes to API contracts - purely internal refactoring
- Reduces code duplication from ~200 lines to ~50 lines
- Future PRs can add new auth strategies more easily
- All 5 route handlers tested individually to verify behavior unchanged
```
---
## Example: Documentation Update
```markdown
## What?
Update installation instructions for v2.0 and add troubleshooting section
## Why?
Users have reported confusion about new installation requirements in v2.0. Multiple support requests (#567, #589, #601) asking about the same issues.
## How?
- Updated README.md with new installation steps
- Added prerequisites section (Node.js 18+, npm 9+)
- Created troubleshooting guide for common issues
- Added examples for different deployment scenarios
- Fixed typos and outdated links
## Testing
- Followed installation steps on fresh Ubuntu 22.04 VM
- Tested on macOS Ventura
- Verified all links work
- Asked non-technical user to follow guide (successfully completed)
## Checklist
- [x] All links verified working
- [x] Code examples tested
- [x] Markdown formatting validated
- [x] Screenshots updated to v2.0 UI
- [x] Spelling and grammar checked
## Related Issues
Closes #567, #589, #601
## Screenshots
N/A (documentation only)
## Additional Notes
- Kept v1.0 migration guide in separate file (MIGRATION.md)
- Added FAQ section based on common support questions
- Consider adding video walkthrough in future
```
---
## Tips for Writing Good PR Descriptions
### Do:
✅ Be specific and clear
✅ Explain WHY, not just WHAT
✅ Provide testing instructions
✅ Link related issues
✅ Include screenshots for visual changes
✅ Note breaking changes prominently
✅ Keep it concise but complete
### Don't:
❌ Just repeat the commit message
❌ Leave sections empty ("TODO", "TBD")
❌ Assume reviewers know the context
❌ Include implementation details better suited for code comments
❌ Write a novel (keep it scannable)
❌ Skip testing instructions
---
## Project-Specific Variations
Some projects have specific PR template requirements. Check for:
- `.github/PULL_REQUEST_TEMPLATE.md` in the repository
- Instructions in CONTRIBUTING.md
- Examples in recently merged PRs
**Always adapt this template to match project expectations.**