Real-time code quality and security analysis - Grammarly for code
🎉 Now Available on VSCode Marketplace!
Smart Code Analyzer (CodeGuard) is a VSCode extension that provides instant feedback on code quality, security vulnerabilities, performance issues, and code smells as you type. It acts as your personal code reviewer, catching issues before they reach production.
- Open VSCode
- Go to Extensions (
Ctrl+Shift+X) - Search for "Smart Code Analyzer"
- Click Install
Or install directly: VSCode Marketplace
- Open any
.js,.ts,.py, or.javafile - Start coding - the extension analyzes automatically
- Check the status bar (bottom right) for issue counts
- Hover over underlined code for explanations
- Use
Ctrl+Shift+Gto manually analyze
- ⚡ Lightning Fast: Analysis completes in <100ms for most files
- 🔒 Privacy First: All analysis runs locally by default - your code never leaves your machine
- 🎯 Accurate: Advanced data flow analysis and entropy filtering minimize false positives
- 🤖 AI-Powered: Optional intelligent fix suggestions (supports OpenAI, Claude, and local Ollama)
- 🔧 Customizable: Fine-tune rules, severities, and behavior to match your team's standards
- 🌍 Multi-Language: Supports JavaScript, TypeScript, Python, and Java
Detect security vulnerabilities before they reach production:
- SQL Injection: Identifies unsafe string concatenation in SQL queries with data flow analysis
- XSS (Cross-Site Scripting): Detects unescaped user input in HTML contexts
- Command Injection: Finds user input in shell command execution
- Path Traversal: Catches unsafe file path operations
- Unsafe Deserialization: Identifies dangerous deserialization patterns
Example Detection:
// ❌ CodeGuard will flag this
const query = "SELECT * FROM users WHERE id = " + userId;
// ✅ This is safe
const query = db.prepare("SELECT * FROM users WHERE id = ?").bind(userId);Prevent credential leaks with intelligent secret detection:
- AWS Access Keys: Detects AKIA... patterns
- API Keys: Generic API key patterns with entropy analysis
- Hardcoded Passwords: Finds password assignments in plain text
- JWT Tokens: Identifies JWT token patterns
- Private Keys: Detects PEM-formatted private keys
Smart Entropy Filtering: Uses Shannon entropy to distinguish real secrets from test data, reducing false positives.
Example Detection:
// ❌ High entropy - flagged as potential secret
const apiKey = "sk-live-[REDACTED]";
// ✅ Low entropy - ignored as test data
const apiKey = "test_key_12345";Catch performance issues early:
- Nested Loops: Detects O(n³) or worse complexity
- Blocking Operations: Finds synchronous I/O in async contexts
- Memory Leaks: Identifies unclosed resources and event listeners
- Inefficient String Operations: Catches string concatenation in loops
- Unnecessary Re-computations: Detects redundant calculations
Example Detection:
// ❌ CodeGuard will warn about O(n³) complexity
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
for (let k = 0; k < n; k++) {
// nested operations
}
}
}
// ❌ Blocking operation in async context
async function loadData() {
const data = fs.readFileSync('file.txt'); // Should use readFile
}Maintain clean, maintainable code:
- Long Functions: Flags functions exceeding 50 lines
- Cyclomatic Complexity: Warns when complexity exceeds 10
- Duplicate Code: Detects duplicate blocks exceeding 6 lines
- Too Many Parameters: Flags functions with more than 5 parameters
- Deep Nesting: Warns about nesting exceeding 4 levels
Example Detection:
// ❌ Too many parameters
function createUser(name, email, age, address, phone, role, department) {
// ...
}
// ✅ Better approach
function createUser(userData) {
const { name, email, age, address, phone, role, department } = userData;
// ...
}Get intelligent, context-aware fix suggestions:
- Multiple AI Providers: OpenAI GPT-4, Anthropic Claude, or local Ollama
- Context-Aware: Understands your code context for better suggestions
- Detailed Explanations: Each fix includes why it's better
- Privacy Conscious: Only sends minimal code context (never entire files)
- Fallback Support: Rule-based fixes when AI is unavailable
Example AI Fix:
// Your code with issue
const query = "SELECT * FROM users WHERE id = " + userId;
// AI suggests (with explanation)
const query = db.prepare("SELECT * FROM users WHERE id = ?").bind(userId);
// Explanation: Using parameterized queries prevents SQL injection by
// separating SQL logic from user data. The database driver handles
// proper escaping automatically.🎉 Now Live!
- Open VSCode
- Go to Extensions (
Ctrl+Shift+X/Cmd+Shift+X) - Search for "Smart Code Analyzer"
- Click Install
Or visit: VSCode Marketplace
code --install-extension LekhanHR.codeguard-analyzergit clone https://github.com/lekhanpro/CodeGuard.git
cd codeguard
npm install
npm run compile
code --install-extension .- Install the extension (see above)
- Open a supported file (JavaScript, TypeScript, Python, or Java)
- Start typing - CodeGuard automatically analyzes your code
- View issues in the editor, Problems panel, or status bar
- Apply fixes using quick actions (lightbulb icon or Ctrl+.)
For AI-powered features (optional):
- Open Settings (Ctrl+, / Cmd+,)
- Search for "CodeGuard"
- Enable AI: Set
codeguard.ai.enabledtotrue - Choose provider: Set
codeguard.ai.providertoollama,openai, orclaude - Configure credentials (if needed)
Alternative: Copy .env.example to .env and configure your API keys there (see .env.example for all available options).
CodeGuard automatically activates when you open supported files and analyzes your code as you type:
- Debounced: Analysis triggers 500ms after you stop typing (configurable)
- Fast: Completes in <100ms for most files
- Non-blocking: Runs in background worker threads
- Incremental: Only analyzes changed regions in large files (>5000 lines)
Issues appear in multiple places:
-
Editor: Inline squiggly underlines
- Red: Errors (security issues, secrets)
- Yellow: Warnings (performance issues, high complexity)
- Blue: Info (code smells, suggestions)
-
Problems Panel: View → Problems (Ctrl+Shift+M / Cmd+Shift+M)
- Grouped by file and severity
- Click to jump to issue location
-
Status Bar: Bottom-right corner
- Shows total issue count by severity
- Click to open Problems panel
Hover over any issue or press Ctrl+. (Cmd+. on Mac) to see available actions:
Get intelligent, context-aware fix suggestions:
- Analyzes the issue and surrounding code
- Provides multiple fix options when applicable
- Includes detailed explanations
- Shows preview before applying
Requirements: AI must be enabled and configured
Suppress specific issues:
- Adds rule to
.codeguardignorefile - Can ignore by rule ID, file pattern, or line number
- Persists across sessions
- Team-shareable via version control
Example .codeguardignore:
{
"version": "1.0",
"rules": [
{
"ruleId": "sql-injection",
"filePattern": "src/legacy/**",
"reason": "Legacy code - scheduled for refactor"
},
{
"ruleId": "long-function",
"lineNumber": 42,
"reason": "Complex business logic - cannot be simplified"
}
]
}View detailed documentation:
- What the issue is
- Why it's problematic
- How to fix it
- Code examples (good and bad)
- Related resources
Trigger analysis manually when needed:
Command Palette (Ctrl+Shift+P / Cmd+Shift+P):
CodeGuard: Analyze Current File- Analyze active fileCodeGuard: Clear All Diagnostics- Clear all issuesCodeGuard: Toggle Analysis On/Off- Enable/disable CodeGuard
Keyboard Shortcuts:
Ctrl+Shift+G/Cmd+Shift+G- Analyze current fileCtrl+Shift+Alt+G/Cmd+Shift+Alt+G- Toggle on/off
Context Menu:
- Right-click in editor → "CodeGuard: Analyze Current File"
CodeGuard can be configured through VSCode settings or a .codeguardrc.json file in your workspace root.
Settings are merged in this order (highest priority first):
.codeguardrc.jsonin workspace root- VSCode workspace settings
- VSCode user settings
- Default configuration
Via VSCode Settings (Settings → Extensions → CodeGuard):
{
"codeguard.enabled": true,
"codeguard.debounceMs": 500,
"codeguard.maxAnalysisTimeMs": 5000
}Via .codeguardrc.json:
{
"enabled": true,
"debounceMs": 500,
"maxAnalysisTimeMs": 5000,
"analyzers": {
"security": { "enabled": true },
"performance": { "enabled": true },
"secrets": { "enabled": true },
"codeSmells": { "enabled": true }
}
}Enable or disable specific analyzers:
{
"codeguard.analyzers.security.enabled": true,
"codeguard.analyzers.performance.enabled": true,
"codeguard.analyzers.secrets.enabled": true,
"codeguard.analyzers.codeSmells.enabled": true
}Customize severity levels (in .codeguardrc.json):
{
"analyzers": {
"security": {
"enabled": true,
"severity": {
"sql-injection": "error",
"xss": "error",
"command-injection": "warning"
}
},
"codeSmells": {
"enabled": true,
"severity": {
"long-function": "info",
"high-complexity": "warning",
"too-many-params": "info"
}
}
}
}Free, private, and runs on your machine
- Install Ollama: https://ollama.ai
- Pull a code model:
ollama pull codellama # or ollama pull deepseek-coder - Configure CodeGuard:
{ "codeguard.ai.enabled": true, "codeguard.ai.provider": "ollama", "codeguard.ai.model": "codellama" }
Supported Ollama Models:
codellama- Meta's Code Llama (7B, 13B, 34B)deepseek-coder- DeepSeek Coder (1.3B, 6.7B, 33B)phind-codellama- Phind's fine-tuned Code Llamawizardcoder- WizardCoder models
Requires API key (paid)
- Get API key: https://platform.openai.com/api-keys
- Configure CodeGuard:
{ "codeguard.ai.enabled": true, "codeguard.ai.provider": "openai", "codeguard.ai.apiKey": "sk-...", "codeguard.ai.model": "gpt-4" }
Supported Models:
gpt-4- Most capable (recommended)gpt-4-turbo- Faster, cheapergpt-3.5-turbo- Fastest, cheapest
Requires API key (paid)
- Get API key: https://console.anthropic.com/
- Configure CodeGuard:
{ "codeguard.ai.enabled": true, "codeguard.ai.provider": "claude", "codeguard.ai.apiKey": "sk-ant-...", "codeguard.ai.model": "claude-3-sonnet-20240229" }
Supported Models:
claude-3-opus-20240229- Most capableclaude-3-sonnet-20240229- Balanced (recommended)claude-3-haiku-20240307- Fastest, cheapest
{
"codeguard.ai.enabled": true,
"codeguard.ai.provider": "openai",
"codeguard.ai.apiKey": "sk-...",
"codeguard.ai.model": "gpt-4",
"codeguard.ai.maxTokens": 1000,
"codeguard.ai.temperature": 0.2,
"codeguard.ai.timeout": 3000
}Control caching behavior for performance:
{
"codeguard.cache.enabled": true,
"codeguard.cache.maxMemoryMB": 50,
"codeguard.cache.maxDiskMB": 500,
"codeguard.cache.ttlSeconds": 3600
}Cache Behavior:
- Memory Cache: Fast LRU cache (50MB default)
- Disk Cache: Persistent SQLite cache (500MB default)
- Content-Based: Uses SHA-256 hash of file content as key
- Automatic Eviction: LRU eviction when limits exceeded
- Persistence: Survives VSCode restarts
Control network features and data sharing:
{
"codeguard.privacy.disableNetworkFeatures": false,
"codeguard.privacy.disableTelemetry": true
}Privacy Guarantees:
- ✅ All static analysis runs locally (no network calls)
- ✅ AI features are optional and disabled by default
- ✅ When AI is enabled, only minimal context is sent (never entire files)
- ✅ No telemetry or tracking by default
- ✅ No code logging or transmission to external services
Disable All Network Features:
{
"codeguard.privacy.disableNetworkFeatures": true
}This disables:
- AI fix suggestions
- Telemetry and error reporting
- Update checks
Optimize for your workflow:
{
"codeguard.debounceMs": 500, // Delay before analysis (ms)
"codeguard.maxAnalysisTimeMs": 5000, // Timeout per analyzer (ms)
"codeguard.cache.enabled": true, // Enable caching
"codeguard.incrementalThreshold": 5000 // Lines before incremental analysis
}Performance Tips:
- Increase debounce (e.g., 1000ms) if you type very fast
- Decrease debounce (e.g., 300ms) for more immediate feedback
- Disable analyzers you don't need for faster analysis
- Enable caching for instant results on unchanged files
- Incremental analysis automatically activates for large files
Share configuration across your team using .codeguardrc.json:
{
"version": "1.0",
"enabled": true,
"debounceMs": 500,
"analyzers": {
"security": {
"enabled": true,
"severity": {
"sql-injection": "error",
"xss": "error",
"command-injection": "error"
}
},
"codeSmells": {
"enabled": true,
"severity": {
"long-function": "warning",
"high-complexity": "warning"
},
"customRules": {
"maxFunctionLines": 100,
"maxComplexity": 15,
"maxParameters": 4
}
}
},
"ai": {
"enabled": false,
"provider": "none"
},
"privacy": {
"disableNetworkFeatures": false,
"disableTelemetry": true
}
}Commit this file to version control to ensure consistent analysis across your team.
CodeGuard is designed with privacy as a core principle:
- ✅ All static analysis runs locally on your machine
- ✅ No network requests for security, performance, secrets, or code smell detection
- ✅ No code transmission to external services by default
- ✅ No telemetry or tracking unless explicitly enabled
When AI features are enabled:
- ✅ Minimal context only: Sends problematic code snippet + 10 lines of context (never entire files)
- ✅ Optional feature: AI is disabled by default
- ✅ Local AI option: Use Ollama for completely local AI processing
- ✅ Transparent: You control what data is sent and when
- ✅ Local cache only: Analysis results cached locally in SQLite
- ✅ No cloud sync: Cache never leaves your machine
- ✅ Configurable: Can disable caching entirely if desired
Control network access:
{
"codeguard.privacy.disableNetworkFeatures": true
}This disables:
- AI fix suggestions
- Telemetry and error reporting
- Update checks
Result: CodeGuard functions entirely offline with zero network activity.
CodeGuard is optimized for speed and efficiency:
- ⚡ <100ms analysis for files under 1000 lines
- ⚡ Incremental analysis for large files (>5000 lines)
- ⚡ Parallel execution of all analyzers
- ⚡ Smart caching with content-based hashing
- ⚡ Worker threads for non-blocking analysis
- 💾 <5MB idle when no supported files are open
- 💾 50MB memory cache with LRU eviction
- 💾 500MB disk cache for persistent results
- 💾 Automatic cleanup when limits exceeded
- 🚀 <500ms activation time
- 🚀 Lazy loading of analyzers
- 🚀 Cached results available immediately on restart
- Debouncing: Waits 500ms after typing stops before analyzing
- Incremental Analysis: Only analyzes changed regions in large files
- Content Hashing: Skips analysis for unchanged files
- Parallel Execution: All analyzers run concurrently
- Worker Threads: CPU-intensive work runs off main thread
| Language | Security | Secrets | Performance | Code Smells |
|---|---|---|---|---|
| JavaScript | ✅ | ✅ | ✅ | ✅ |
| TypeScript | ✅ | ✅ | ✅ | ✅ |
| Python | ✅ | ✅ | ✅ | ✅ |
| Java | ✅ | ✅ | ✅ | ✅ |
JavaScript/TypeScript:
- Type-aware analysis for TypeScript
- React-specific patterns (XSS in JSX)
- Node.js security patterns
- Async/await performance checks
Python:
- Django/Flask security patterns
- Async/await performance checks
- Python-specific code smells
Java:
- JDBC security patterns
- Spring framework patterns
- Java-specific performance issues
Solution:
- Check file language is supported (JavaScript, TypeScript, Python, Java)
- Verify extension is enabled:
codeguard.enabled: true - Check Output panel (View → Output → CodeGuard) for errors
- Reload VSCode:
Developer: Reload Window
Solution:
- Enable caching:
codeguard.cache.enabled: true - Increase debounce:
codeguard.debounceMs: 1000 - Disable unused analyzers
- Check file size - incremental analysis activates at 5000 lines
Solution:
- Use "Ignore Issue" action to suppress specific warnings
- Adjust severity levels in
.codeguardrc.json - Disable specific rules you don't need
- Report false positives as issues on GitHub
Solution:
- Verify AI is enabled:
codeguard.ai.enabled: true - Check provider is configured:
codeguard.ai.provider - Verify API key (if using OpenAI/Claude)
- Check network connectivity (unless using Ollama)
- View Output panel for AI service errors
Solution:
- Reduce memory cache:
codeguard.cache.maxMemoryMB: 25 - Reduce disk cache:
codeguard.cache.maxDiskMB: 250 - Disable caching:
codeguard.cache.enabled: false - Close unused files
Enable verbose logging:
- Open Output panel (View → Output)
- Select "CodeGuard" from dropdown
- Set log level in settings:
{ "codeguard.logLevel": "debug" }
Before:
function getUser(userId) {
const query = "SELECT * FROM users WHERE id = " + userId;
return db.execute(query);
}CodeGuard Detection:
- ❌ Error: SQL injection vulnerability detected
- 💡 Suggestion: Use parameterized queries
After (with AI fix):
function getUser(userId) {
const query = "SELECT * FROM users WHERE id = ?";
return db.execute(query, [userId]);
}Before:
const config = {
apiKey: "sk-live-[REDACTED]",
dbPassword: "MySecretPassword123"
};CodeGuard Detection:
- ❌ Error: API key detected (high entropy)
- ❌ Error: Hardcoded password detected
After:
const config = {
apiKey: process.env.API_KEY,
dbPassword: process.env.DB_PASSWORD
};Before:
async function processData(items) {
let result = "";
for (let item of items) {
result += item.toString(); // Inefficient string concatenation
}
const data = fs.readFileSync('config.json'); // Blocking in async
return result;
}CodeGuard Detection:
⚠️ Warning: Inefficient string concatenation in loop⚠️ Warning: Blocking operation in async function
After:
async function processData(items) {
const result = items.map(item => item.toString()).join('');
const data = await fs.promises.readFile('config.json');
return result;
}Before:
function processOrder(orderId, userId, productId, quantity, price, discount, shippingAddress, billingAddress, paymentMethod) {
// 80 lines of complex logic...
if (condition1) {
if (condition2) {
if (condition3) {
if (condition4) {
if (condition5) {
// deeply nested code
}
}
}
}
}
}CodeGuard Detection:
- ℹ️ Info: Function exceeds 50 lines (80 lines)
- ℹ️ Info: Too many parameters (9 parameters)
⚠️ Warning: Deep nesting detected (5 levels)⚠️ Warning: High cyclomatic complexity (15)
After:
function processOrder(orderData) {
validateOrder(orderData);
const payment = processPayment(orderData);
const shipping = scheduleShipping(orderData);
return createOrderRecord(orderData, payment, shipping);
}
// Split into smaller, focused functions
function validateOrder(orderData) { /* ... */ }
function processPayment(orderData) { /* ... */ }
function scheduleShipping(orderData) { /* ... */ }
function createOrderRecord(orderData, payment, shipping) { /* ... */ }- README.md - Overview, features, and quick start
- CONFIGURATION.md - Complete configuration reference
- TROUBLESHOOTING.md - Troubleshooting guide and solutions
- CONTRIBUTING.md - Development setup and guidelines
- API Documentation - Extension API reference (coming soon)
- Architecture Guide - System design and architecture (coming soon)
Contributions are welcome! Please see CONTRIBUTING.md for details on:
- Development setup
- Code style guidelines
- Testing requirements
- Pull request process
- Adding new analyzers
- Adding new AI providers
MIT License - see LICENSE for details.
- Go language support
- Rust language support
- Custom rule configuration UI
- Team-shared rule sets via Git
- C++ language support
- Ruby language support
- CI/CD integration (GitHub Actions, GitLab CI)
- Git pre-commit hooks
- Hugging Face Inference API support
- More local AI models
- Rule marketplace
- VSCode web support
- Real-time collaboration features
- Code quality trends and analytics
- Integration with issue trackers
- Custom analyzer SDK
CodeGuard is built with:
- VSCode Extension API
- TypeScript
- Vitest for testing
- fast-check for property-based testing
- LRU Cache for caching
Special thanks to:
- The VSCode team for excellent extension APIs
- The open-source security community for vulnerability patterns
- All contributors and users providing feedback
Made with ❤️ for developers who care about code quality
Smart Code Analyzer - Catch issues before they reach production
🎉 Now available on VSCode Marketplace!