Production-ready AI commit validator with enhanced error detection including undeclared variables that cause ReferenceError. Focuses on meaningful code optimizations, critical error detection, unused code removal, and performance improvements.
npm install copilot-commit-validator[skip-ai] comments
bash
npm install -g ai-commit-validator
`
$3
`bash
npm install ai-commit-validator
`
āļø Configuration
$3
Create a .env file in your project root:
`bash
OPENAI_API_KEY=your_openai_api_key_here
`
Getting your OpenAI API Key:
1. Visit OpenAI Platform
2. Sign up or log in to your account
3. Navigate to API Keys section
4. Create a new secret key
5. Copy and paste it into your .env file
$3
| Variable | Required | Description | Default |
|----------|----------|-------------|---------|
| GITHUB_TOKEN | š§ Optional | GitHub Personal Access Token for Copilot API | - |
| AI_OPTIONAL_MODE | š” Recommended | Make AI validation optional (nice to have) | true |
| AI_AUTO_OPEN_ERRORS | ā No | Auto-open files at error locations | false |
| AI_DEFAULT_ON_CANCEL | ā No | Default action on prompt timeout | auto-apply |
| AI_PROMPT_TIMEOUT_MS | ā No | Timeout for interactive prompts (ms) | 30000 |
| AI_AUTO_SELECT | ā No | Auto-respond in non-interactive mode | - |
| AI_FORCE_PROMPT | ā No | Force prompts in non-TTY environments | false |
$3
Set AI_OPTIONAL_MODE=true in your .env file to make AI validation optional:
`dotenv
Make AI validation non-blocking (nice to have)
AI_OPTIONAL_MODE=true
GITHUB_TOKEN=ghp_your_github_token_here
`
Benefits of Optional Mode:
- ā
Never blocks commits - Always allows commits to proceed
- š¤ Best effort AI review - Provides suggestions when available
- š Network resilient - Works offline or with connectivity issues
- ā” Fast commits - No waiting for AI when services are unavailable
- š§ Manual fallback - Shows clear guidance when AI review fails
šÆ Usage
$3
`bash
Validate staged changes
validate-commit
`
$3
#### Option 1: Pre-commit Hook (Recommended)
Create .git/hooks/pre-commit:
`bash
#!/bin/sh
Run AI commit validator
npx validate-commit
`
Make it executable:
`bash
chmod +x .git/hooks/pre-commit
`
#### Option 2: Manual Validation
`bash
Stage your changes
git add .
Run validation
validate-commit
If validation passes, commit
git commit -m "Your commit message"
`
$3
`javascript
import { validateCommit } from 'ai-commit-validator';
// Run validation
await validateCommit();
`
š Workflow
1. Stage Changes: Add files to git staging area
`bash
git add .
`
2. AI Analysis: The validator automatically:
- Analyzes your staged changes
- Sends the diff to OpenAI for review
- Receives intelligent feedback
3. Interactive Decision: Based on AI feedback, you can:
- ā
Apply suggestions - Make recommended changes
- ā ļø Skip with justification - Bypass with required reason
- ā Cancel commit - Stop the commit process
4. Commit: If validation passes or is bypassed, proceed with commit
š Example Output
`bash
š Checking your staged changes...
š§ Sending code diff to AI for review...
š¤ AI Review Feedback:
I found a few areas for improvement:
1. Security Issue: The API key is hardcoded in line 15. Consider using environment variables.
2. Performance: The loop in processData() could be optimized using map() instead of forEach().
3. Error Handling: Missing try-catch block around the database query on line 23.
What do you want to do?
⯠Apply suggestions and continue
Skip validation with comment
Cancel commit
`
šØ Features in Detail
$3
- Code Quality: Identifies potential bugs, security issues, and performance problems
- Best Practices: Suggests improvements following coding standards
- Documentation: Recommends better comments and documentation
- Refactoring: Suggests cleaner, more maintainable code patterns
$3
- Colored Output: Beautiful terminal interface with chalk.js
- Progress Indicators: Clear feedback during AI processing
- Smart Prompts: Contextual questions based on analysis results
$3
- Justification Required: Must provide reason when skipping suggestions
- Audit Trail: Logs bypass reasons for team accountability
- Configurable: Can be customized for team requirements
š ļø Advanced Configuration
$3
Modify the model in index.js:
`javascript
const response = await openai.chat.completions.create({
model: "gpt-4", // Change to your preferred model
messages: [{ role: "user", content: prompt }],
});
`
$3
Customize the AI prompt for your team's needs:
`javascript
const prompt =
;
`
š§ Troubleshooting
$3
Error: No OpenAI API Key
`bash
Error: OpenAI API key not found
`
Solution: Ensure .env file exists with OPENAI_API_KEY=your_key
Error: No staged changes
`bash
ā ļø No staged changes found
`
Solution: Stage files first with git add .
Error: API Rate Limit
`bash
Error: Rate limit exceeded
`
Solution: Wait a moment and try again, or upgrade your OpenAI plan
$3
Add debug logging by modifying index.js:
`javascript
console.log('Debug: Staged diff:', diff);
console.log('Debug: AI Response:', aiFeedback);
`
š Performance
- Average Analysis Time: 2-5 seconds
- API Cost: ~$0.001-0.01 per commit (depending on change size)
- Supported File Types: All text-based files (JS, TS, Python, etc.)
š¤ Contributing
1. Fork the repository
2. Create a feature branch: git checkout -b feature/amazing-feature
3. Stage your changes: git add .
4. Run the validator: validate-commit
5. Commit your changes: git commit -m "Add amazing feature"
6. Push to the branch: git push origin feature/amazing-feature
7. Open a pull request
š Requirements
- Node.js: >= 16.0.0
- Git: Any recent version
- OpenAI API Key: Required for AI analysis
- Internet Connection: Required for API calls
š v2.2.0 - Auto-Open Error Locations
The validator now automatically opens files at error locations with intelligent editor detection!
Features:
- š Opens files directly in VS Code, Sublime Text, or Vim
- šÆ Navigates to the exact error line
- š” Shows fix suggestions in the terminal
- ā
Fully optional (disabled by default)
Quick Start:
`bash
export AI_AUTO_OPEN_ERRORS=true
git commit -m "Your commit message"
Files with errors open automatically in your editor!
``