claude-git-hooks
Version:
Git hooks with Claude CLI for code analysis and automatic commit messages
194 lines (146 loc) • 4.7 kB
Markdown
AI/CLI Code Quality Guidelines
# Claude API Best Practices
## Model Selection
✅ **Haiku**: Simple tasks, fast responses, cost-effective
✅ **Sonnet**: Balanced performance, most use cases
✅ **Opus**: Complex reasoning, highest quality
❌ Don't use Opus when Haiku would suffice
## API Usage
✅ Implement proper timeout handling
✅ Handle rate limiting gracefully
✅ Retry with exponential backoff on failures
✅ Validate API responses before use
✅ Log API errors (but never log API keys!)
✅ Calculate and monitor token usage
## Error Handling
```javascript
// ✅ Good
try {
const response = await callClaudeAPI(prompt);
if (!response || !response.content) {
throw new Error('Invalid API response');
}
return parseResponse(response);
} catch (error) {
if (error.status === 429) {
// Handle rate limiting
} else if (error.status === 500) {
// Handle server error
}
logger.error('API call failed', error);
throw new UserFriendlyError('Failed to analyze code');
}
```
# Prompt Engineering
## Structure
✅ Clear role/context at the beginning
✅ Specific task instructions
✅ Well-defined output format (usually JSON)
✅ Relevant examples when helpful
✅ Appropriate length (token-efficient)
## Quality Checklist
✅ Instructions are unambiguous
✅ Output format is machine-parseable
✅ Context is sufficient but not excessive
✅ Examples match expected usage
✅ Placeholders are replaced correctly
## Common Prompt Issues
❌ Vague instructions
❌ No output format specification
❌ Too much unnecessary context
❌ Ambiguous requirements
❌ Missing examples for complex tasks
# CLI User Experience
## Error Messages
✅ Clear, actionable error messages
✅ Suggest solutions when possible
✅ Use appropriate log levels
✅ Color-code for readability (error=red, success=green)
✅ Include context (what was being attempted)
## User Feedback
✅ Show progress for long operations
✅ Confirm destructive operations
✅ Provide helpful usage information
✅ Display meaningful results
✅ Log debug info only when debug mode enabled
# Git Operations Safety
## Safe Practices
✅ Validate repository state before operations
✅ Use `--cached` for staged changes
✅ Handle special characters in filenames
✅ Cross-platform path handling
✅ Graceful handling of git errors
## Dangerous Operations
❌ Never run git commands that modify history without explicit user confirmation
❌ Avoid hard resets
❌ Be careful with force pushes
❌ Validate before bulk operations
# Security
## API Keys
✅ Load from environment variables
✅ Never log or display API keys
✅ Never commit API keys to repository
✅ Use secure storage methods
✅ Clear keys from memory when done
## Command Injection
✅ Validate all user input
✅ Use parameterized commands when possible
✅ Escape special characters
✅ Avoid `eval()` and similar
✅ Sanitize file paths
## Sensitive Data
✅ Don't send secrets to Claude API
✅ Filter sensitive data from diffs
✅ Be careful with error messages (don't expose internals)
# Code Organization
## File Structure
```
lib/
hooks/ # Git hook implementations
utils/ # Utility functions
claude-client.js
git-operations.js
file-operations.js
logger.js
config.js # Configuration management
templates/ # Prompt templates
bin/ # CLI entry points
```
## Module Design
✅ Single responsibility principle
✅ Clear, descriptive function names
✅ Comprehensive error handling
✅ Proper logging at decision points
✅ Export reusable functions
# Common Issues to Avoid
## Critical Issues
❌ Exposed API keys or secrets
❌ Command injection vulnerabilities
❌ Destructive git operations without confirmation
❌ Unhandled promise rejections
## Major Issues
❌ Missing error handling
❌ Poor user experience (unclear errors)
❌ Cross-platform incompatibility
❌ Memory leaks (large file handling)
❌ Missing input validation
## Minor Issues
❌ Insufficient logging
❌ Unclear variable names
❌ Missing documentation
❌ Inefficient token usage
❌ Poor code organization
# Testing
✅ Test with various input sizes
✅ Test error scenarios (API failures, git errors)
✅ Test cross-platform compatibility
✅ Mock external dependencies (Claude API, git)
✅ Test with edge cases (special characters, large files)
✅ Verify token usage calculations
# Documentation
✅ Document API usage patterns
✅ Explain prompt design decisions
✅ Document configuration options
✅ Provide usage examples
✅ Keep README up to date
✅ Document breaking changes