Skip to content
| Marketplace
Sign in
Visual Studio Code>Programming Languages>Smart Code AnalyzerNew to Visual Studio Code? Get it now.
Smart Code Analyzer

Smart Code Analyzer

Lekhan HR

|
10 installs
| (0) | Free
Real-time code quality and security analysis - Grammarly for code
Installation
Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Copied to clipboard
More Info

CodeGuard

Real-time code quality and security analysis - Grammarly for code

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.

✨ Why CodeGuard?

  • ⚡ 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

Features

🔒 Security Analysis

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);

🔍 Secret Scanning

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";

⚡ Performance Analysis

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
}

🧹 Code Quality

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;
  // ...
}

🤖 AI-Powered Fixes (Optional)

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.

📦 Installation

From VSCode Marketplace (Recommended)

  1. Open VSCode
  2. Go to Extensions (Ctrl+Shift+X / Cmd+Shift+X)
  3. Search for "CodeGuard"
  4. Click Install

From VSIX File

code --install-extension codeguard-0.1.0.vsix

From Source

git clone https://github.com/lekhanpro/CodeGuard.git
cd codeguard
npm install
npm run compile
code --install-extension .

🚀 Quick Start

  1. Install the extension (see above)
  2. Open a supported file (JavaScript, TypeScript, Python, or Java)
  3. Start typing - CodeGuard automatically analyzes your code
  4. View issues in the editor, Problems panel, or status bar
  5. Apply fixes using quick actions (lightbulb icon or Ctrl+.)

First-Time Setup

For AI-powered features (optional):

  1. Open Settings (Ctrl+, / Cmd+,)
  2. Search for "CodeGuard"
  3. Enable AI: Set codeguard.ai.enabled to true
  4. Choose provider: Set codeguard.ai.provider to ollama, openai, or claude
  5. Configure credentials (if needed)

Alternative: Copy .env.example to .env and configure your API keys there (see .env.example for all available options).

💡 Usage

Automatic Analysis

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)

Viewing Issues

Issues appear in multiple places:

  1. Editor: Inline squiggly underlines

    • Red: Errors (security issues, secrets)
    • Yellow: Warnings (performance issues, high complexity)
    • Blue: Info (code smells, suggestions)
  2. Problems Panel: View → Problems (Ctrl+Shift+M / Cmd+Shift+M)

    • Grouped by file and severity
    • Click to jump to issue location
  3. Status Bar: Bottom-right corner

    • Shows total issue count by severity
    • Click to open Problems panel

Quick Actions

Hover over any issue or press Ctrl+. (Cmd+. on Mac) to see available actions:

1. Fix with AI 🤖

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

2. Ignore Issue 🚫

Suppress specific issues:

  • Adds rule to .codeguardignore file
  • 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"
    }
  ]
}

3. Explain Issue 📖

View detailed documentation:

  • What the issue is
  • Why it's problematic
  • How to fix it
  • Code examples (good and bad)
  • Related resources

Manual Analysis

Trigger analysis manually when needed:

Command Palette (Ctrl+Shift+P / Cmd+Shift+P):

  • CodeGuard: Analyze Current File - Analyze active file
  • CodeGuard: Clear All Diagnostics - Clear all issues
  • CodeGuard: Toggle Analysis On/Off - Enable/disable CodeGuard

Keyboard Shortcuts:

  • Ctrl+Shift+G / Cmd+Shift+G - Analyze current file
  • Ctrl+Shift+Alt+G / Cmd+Shift+Alt+G - Toggle on/off

Context Menu:

  • Right-click in editor → "CodeGuard: Analyze Current File"

⚙️ Configuration

CodeGuard can be configured through VSCode settings or a .codeguardrc.json file in your workspace root.

Configuration Priority

Settings are merged in this order (highest priority first):

  1. .codeguardrc.json in workspace root
  2. VSCode workspace settings
  3. VSCode user settings
  4. Default configuration

Basic Settings

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 }
  }
}

Analyzer Configuration

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"
      }
    }
  }
}

AI Configuration

Option 1: Local AI with Ollama (Recommended for Privacy)

Free, private, and runs on your machine

  1. Install Ollama: https://ollama.ai
  2. Pull a code model:
    ollama pull codellama
    # or
    ollama pull deepseek-coder
    
  3. 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 Llama
  • wizardcoder - WizardCoder models

Option 2: OpenAI GPT

Requires API key (paid)

  1. Get API key: https://platform.openai.com/api-keys
  2. 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, cheaper
  • gpt-3.5-turbo - Fastest, cheapest

Option 3: Anthropic Claude

Requires API key (paid)

  1. Get API key: https://console.anthropic.com/
  2. 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 capable
  • claude-3-sonnet-20240229 - Balanced (recommended)
  • claude-3-haiku-20240307 - Fastest, cheapest

Advanced AI Settings

{
  "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
}

Cache Configuration

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

Privacy Settings

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

Performance Tuning

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

Team Configuration

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.

🔐 Privacy & Security

CodeGuard is designed with privacy as a core principle:

Local-First Architecture

  • ✅ 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

AI Privacy

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

Data Storage

  • ✅ Local cache only: Analysis results cached locally in SQLite
  • ✅ No cloud sync: Cache never leaves your machine
  • ✅ Configurable: Can disable caching entirely if desired

Network Features

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.

⚡ Performance

CodeGuard is optimized for speed and efficiency:

Analysis Performance

  • ⚡ <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

Memory Efficiency

  • 💾 <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

Startup Performance

  • 🚀 <500ms activation time
  • 🚀 Lazy loading of analyzers
  • 🚀 Cached results available immediately on restart

Optimization Features

  1. Debouncing: Waits 500ms after typing stops before analyzing
  2. Incremental Analysis: Only analyzes changed regions in large files
  3. Content Hashing: Skips analysis for unchanged files
  4. Parallel Execution: All analyzers run concurrently
  5. Worker Threads: CPU-intensive work runs off main thread

🌍 Supported Languages

Language Security Secrets Performance Code Smells
JavaScript ✅ ✅ ✅ ✅
TypeScript ✅ ✅ ✅ ✅
Python ✅ ✅ ✅ ✅
Java ✅ ✅ ✅ ✅

Language-Specific Features

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

🛠️ Troubleshooting

Common Issues

Issue: CodeGuard not activating

Solution:

  1. Check file language is supported (JavaScript, TypeScript, Python, Java)
  2. Verify extension is enabled: codeguard.enabled: true
  3. Check Output panel (View → Output → CodeGuard) for errors
  4. Reload VSCode: Developer: Reload Window

Issue: Analysis is slow

Solution:

  1. Enable caching: codeguard.cache.enabled: true
  2. Increase debounce: codeguard.debounceMs: 1000
  3. Disable unused analyzers
  4. Check file size - incremental analysis activates at 5000 lines

Issue: Too many false positives

Solution:

  1. Use "Ignore Issue" action to suppress specific warnings
  2. Adjust severity levels in .codeguardrc.json
  3. Disable specific rules you don't need
  4. Report false positives as issues on GitHub

Issue: AI fixes not working

Solution:

  1. Verify AI is enabled: codeguard.ai.enabled: true
  2. Check provider is configured: codeguard.ai.provider
  3. Verify API key (if using OpenAI/Claude)
  4. Check network connectivity (unless using Ollama)
  5. View Output panel for AI service errors

Issue: High memory usage

Solution:

  1. Reduce memory cache: codeguard.cache.maxMemoryMB: 25
  2. Reduce disk cache: codeguard.cache.maxDiskMB: 250
  3. Disable caching: codeguard.cache.enabled: false
  4. Close unused files

Debug Mode

Enable verbose logging:

  1. Open Output panel (View → Output)
  2. Select "CodeGuard" from dropdown
  3. Set log level in settings:
    {
      "codeguard.logLevel": "debug"
    }
    

Getting Help

  • 🐛 Report a bug
  • 💡 Request a feature
  • 💬 Ask a question
  • 📖 Read the docs

📚 Examples

Example 1: Detecting SQL Injection

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]);
}

Example 2: Detecting Secrets

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
};

Example 3: Detecting Performance Issues

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;
}

Example 4: Detecting Code Smells

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) { /* ... */ }

📚 Documentation

User Documentation

  • README.md - Overview, features, and quick start
  • CONFIGURATION.md - Complete configuration reference
  • TROUBLESHOOTING.md - Troubleshooting guide and solutions

Developer Documentation

  • CONTRIBUTING.md - Development setup and guidelines
  • API Documentation - Extension API reference (coming soon)
  • Architecture Guide - System design and architecture (coming soon)

Additional Resources

  • 📖 User Guide
  • 🔧 Configuration Examples
  • 🤖 AI Setup Guide
  • 🔒 Security Best Practices
  • 📝 Changelog

🤝 Contributing

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

📄 License

MIT License - see LICENSE for details.

🗺️ Roadmap

v0.2.0 (Next Release)

  • [ ] Go language support
  • [ ] Rust language support
  • [ ] Custom rule configuration UI
  • [ ] Team-shared rule sets via Git

v0.3.0

  • [ ] C++ language support
  • [ ] Ruby language support
  • [ ] CI/CD integration (GitHub Actions, GitLab CI)
  • [ ] Git pre-commit hooks

v0.4.0

  • [ ] Hugging Face Inference API support
  • [ ] More local AI models
  • [ ] Rule marketplace
  • [ ] VSCode web support

Future

  • [ ] Real-time collaboration features
  • [ ] Code quality trends and analytics
  • [ ] Integration with issue trackers
  • [ ] Custom analyzer SDK

🙏 Acknowledgments

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

📞 Support

Documentation

  • 📖 User Guide
  • 🔧 Configuration Reference
  • 🤖 AI Setup Guide
  • 🔒 Security Best Practices

Community

  • 💬 Discussions
  • 🐛 Issue Tracker

Made with ❤️ for developers who care about code quality

CodeGuard - Catch issues before they reach production

  • Contact us
  • Jobs
  • Privacy
  • Manage cookies
  • Terms of use
  • Trademarks
© 2026 Microsoft