Skip to content

AnandPilania/CodeCortex

Repository files navigation

CodeCortex ⚡

npm version License: MIT Node.js

A modular, multi-language static code analyzer with a hierarchical driver architecture, persistent file cache, CI quality gates, Mermaid/mindmap reporters, and a real-time web dashboard.


✨ What's new in v0.1.0

  • 10 languages — PHP, JS/TS, React, Vue, Blade, Python, Go, Ruby, CSS/SCSS, Shell, YAML, Markdown
  • Auto-detection — detects Laravel, Node, Python, Go, Ruby projects automatically
  • File cache — SHA1 content-addressed cache; subsequent runs are ~10× faster
  • Quality gate--threshold 80 exits 1 in CI when score drops below threshold
  • Three reporters--html, --mermaid, --mindmap generate standalone files
  • --watch mode — live dashboard that re-analyzes on file change
  • codecortex --init — scaffolds codecortex.config.js in your project
  • Persistent dashboard — server stores last analysis to disk, survives restarts

📦 Installation

# Global (recommended — use anywhere)
npm install -g codecortex

# Local (per-project)
npm install --save-dev codecortex
npx codecortex .

Requirements: Node.js ≥ 18.0.0


🚀 Quick start

# Analyze current directory (auto-detects project type)
codecortex .

# Laravel project — full quality analysis
codecortex . --analyzer laravel

# Live dashboard with auto-refresh
codecortex . --ui --watch

# CI pipeline with quality gate
codecortex . --threshold 80 --json report.json

# Generate all reports at once
codecortex . --html report.html --mermaid docs/arch.md --mindmap docs/mindmap.md

# Scaffold a config file
codecortex --init

📊 Output modes

1. Terminal (default)

CodeCortex v0.1.0

Directories                                        42
Files                                              312
  Analyzed                                         287
  Cached                                           241    ← 84% cache hit rate
  Skipped                                          25

Files by Language/Framework
  PHP                                              89 (31.01%)
  JavaScript                                       67 (23.35%)
  TypeScript                                       44 (15.33%)
  Vue                                              31 (10.80%)
  Python                                           18 (6.27%)
  ...

Size (Aggregate)
  Lines of Code (LOC)                              24,108
  Comment Lines (CLOC)                             3,214 (13.33%)
  Non-Comment Lines (NCLOC)                        20,894 (86.67%)
  Logical Lines (LLOC)                             12,301 (51.02%)

Analysis completed in 1.4s (cache: 84.0% hit rate)

2. Laravel analyzer (--analyzer laravel)

🚀 LARAVEL ANALYSIS REPORT
════════════════════════════════════════════════════════════

📋 Project Information
  Type                      Laravel
  Version                   ^11.0

🎨 Frontend Stack
  - Vue 3.4.0
  - Inertia.js
  - Tailwind CSS

📊 Code Quality Score: 87/100 ✅

🧹 Dead Code
  Unused Classes            2
  Unused Methods            8
  Unused Imports            14

💡 Recommendations
  1. Remove 2 unused classes to reduce codebase size
  2. Clean up 8 unused methods
  3. Remove 14 unused imports

3. Web dashboard (--ui)

# Terminal 1 — start server once
codecortex --server

# Terminal 2 — analyze and push to dashboard (add --watch for live)
codecortex . --ui --watch

Opens http://localhost:3000 with:

  • Language distribution doughnut chart
  • LOC/CLOC/NCLOC/LLOC bar chart
  • Quality score ring gauge
  • Dead code and security issue panels
  • Tech stack badge cloud (auto-detected from package.json / composer.json)
  • File breakdown table
  • Export panel with copy-ready CLI commands

4. HTML report (--html)

codecortex . --html report.html

Generates a single self-contained HTML file with Chart.js visualizations — no server needed. Perfect for attaching to pull requests or uploading to S3.

5. Mermaid diagrams (--mermaid)

codecortex . --mermaid docs/architecture.md

Produces a Markdown file with:

  • Flowchart of project architecture
  • Pie chart of language distribution
  • xychart-beta bar chart of code metrics
  • Laravel component map (if applicable)
  • Full driver inheritance classDiagram

Renders natively in GitHub, GitLab, Notion, Obsidian, and any Mermaid-aware viewer.

6. Mindmap (--mindmap)

codecortex . --mindmap docs/mindmap.md

A Mermaid mindmap branching into: Files & Languages → Code Size → Frontend → Build Tools → Testing → State Management → Quality signals. Drop it straight into your project wiki.


🛠️ CLI reference

codecortex <directory> [options]

Analysis options:
  --analyzer <type>    project | laravel | auto (default: auto)
  --threshold <n>      Fail with exit 1 if quality score < n (CI gate)
  --no-cache           Bypass the file result cache for this run

Output options:
  --json   <file>      Raw JSON results (machine-readable)
  --html   <file>      Self-contained HTML report with charts
  --mermaid <file>     Mermaid diagrams (.md) — arch, pie, class, xychart
  --mindmap <file>     Mermaid mindmap of the full project
  --ui                 Push results to the web dashboard

Server options:
  --server             Start dashboard server only (no analysis)
  --port <n>           Server port (default: 3000)
  --watch              Re-analyze on file change (pair with --ui)

Utility commands:
  --init               Scaffold codecortex.config.js in the current directory
  --list-drivers       List all registered drivers with priority and extensions
  --show-hierarchy     Print driver inheritance tree
  --list-analyzers     List available analyzers and auto-detect keys
  --cache-clear        Delete the .codecortex-cache directory
  --version            Print version
  --help               Show this help

CI/CD integration

# .github/workflows/quality.yml
- name: Analyze code quality
  run: |
    npm install -g codecortex
    codecortex . --threshold 75 --json ci-report.json --mermaid docs/arch.md
  # Exits 1 if quality score < 75 — fails the build
# package.json scripts
"scripts": {
  "analyze":         "codecortex .",
  "analyze:laravel": "codecortex . --analyzer laravel",
  "analyze:ci":      "codecortex . --threshold 80 --json report.json",
  "analyze:docs":    "codecortex . --mermaid docs/arch.md --mindmap docs/mindmap.md"
}

Pre-commit hook

#!/bin/sh
# .git/hooks/pre-commit
codecortex . --threshold 70
if [ $? -ne 0 ]; then
  echo "Quality gate failed. Fix issues before committing."
  exit 1
fi

⚙️ Configuration

Run codecortex --init to scaffold a config file, or create it manually:

// codecortex.config.js
export default {
  // Directories to exclude from analysis
  ignore: ['node_modules', 'vendor', '.git', 'dist', 'build', 'coverage'],

  // CI quality gate: exit 1 if score drops below this. null = disabled
  threshold: null,

  // Web UI server port
  port: 3000,

  // 'project' | 'laravel' | null (null = auto-detect)
  analyzer: null,

  duplicate: {
    enabled:   true,
    maxFiles:  150,     // Skip O(n²) comparison above this file count
    threshold: 0.8,     // Similarity score 0–1
    minLines:  5,       // Minimum block size to compare
  },

  deadCode: {
    enabled:  true,
    maxFiles: 1000,     // Cap for large monorepos
  },

  cache: {
    enabled:    true,
    dir:        '.codecortex-cache',
    maxAgeDays: 30,
  },

  complexity: {
    warnAbove:  10,     // Per-function cyclomatic complexity
    errorAbove: 20,
  },

  quality: {
    deductPerUnusedClass:   2,
    deductPerUnusedMethod:  1,
    deductPerUnusedImport:  0.5,
    deductPerDuplicate:     3,
    deductPerHighSecurity:  10,
    deductPerMediumSecurity: 5,
    deductPerLowSecurity:   2,
  },
};

Config files are searched in order: codecortex.config.jscodecortex.config.json.codecortexrc.js.codecortexrc.json.codecortexrc. CLI flags always override config values.


🗣️ Language support

Core languages

Language Extensions Key metrics
PHP .php Classes, interfaces, traits, methods (public/protected/private/static), functions, namespaces, cyclomatic complexity
JavaScript .js, .mjs, .cjs Functions, arrow functions, async functions, classes, imports/exports, complexity
TypeScript .ts All JS metrics + interfaces, type aliases, enums, decorators, generics
React .jsx All JS metrics + components, hooks (useState/useEffect/etc.), JSX elements, props
React + TS .tsx All TS + React metrics
Vue .vue Detects lang="ts" and delegates to TS parser; Options API + Composition API, defineProps, defineEmits, v- directives
Blade .blade.php All PHP metrics + @ directives, {{ }} / {!! !!} echoes, Blade comments

Extended languages

Language Extensions Key metrics
Python .py, .pyw Classes, functions, decorators, async/await, type hints, docstrings, comprehensions, __dunder__ methods
Go .go Structs, interfaces, functions, methods, goroutines, channels, defer, if err != nil checks, tests/benchmarks
Ruby .rb Classes, modules, methods, attr_accessor/reader/writer, rescue/raise, lambdas, frozen string literal, tests
CSS/SCSS .css, .scss, .sass, .less Rules, selectors, variables (--custom-props, $sass-vars), media queries, nesting, @import/@use, animations
Markdown .md, .mdx Headings, code blocks (by language), links, images, task items, tables, front-matter
Shell .sh, .bash, .zsh Functions, variables, subshells, pipes, heredocs, exports, sources, shebang detection
YAML .yml, .yaml Keys, list items, anchors/aliases, env var refs; detects GitHub Actions, GitLab CI, Kubernetes, Docker Compose, CloudFormation

Config file drivers

File Extras
package.json Frameworks (React, Vue, Angular, Svelte, Solid, Next, Nuxt, Remix, Astro), build tools (Vite, Webpack, esbuild, Rspack, tsup), test frameworks (Jest, Vitest, Playwright, Cypress), UI libs (Tailwind, MUI, Radix, shadcn, DaisyUI), state management (Redux, Zustand, Jotai, Pinia, XState, TanStack Query), monorepo detection
composer.json Frameworks (Laravel, Symfony, Slim, Yii, CakePHP, CodeIgniter), Laravel packages (Sanctum, Passport, Horizon, Telescope, Breeze, Jetstream, Livewire, Inertia, Octane, Reverb, Folio, Volt), Vite cross-reference

🏗️ Architecture

Driver inheritance tree

BaseDriver (abstract)
├── PhpDriver
│   ├── BladeDriver               extends PHP + Blade directives
│   └── LaravelDriver             extends PHP + Laravel components, security, performance
├── JavaScriptDriver
│   ├── TypeScriptDriver          extends JS + types, interfaces, enums, decorators
│   │   └── ReactTypeScriptDriver extends TS + React patterns
│   ├── ReactDriver               extends JS + React patterns (shared react-patterns.js)
│   └── VueDriver                 extends JS + Vue Options/Composition API, TS-aware
├── JsonDriver
│   ├── PackageJsonDriver         extends JSON + full npm ecosystem detection
│   └── ComposerJsonDriver        extends JSON + PHP/Laravel ecosystem detection
├── PythonDriver
├── GoDriver
├── RubyDriver
├── CssDriver
├── MarkdownDriver
├── ShellDriver
└── YamlDriver

How driver selection works:

  1. All drivers are sorted by priority (descending) at startup
  2. For each file, the first driver whose canHandle(filePath) returns true wins
  3. canHandle checks includePatterns first, then excludePatterns, then extensions
  4. BladeDriver (priority 20) outbids PhpDriver (priority 10) for .blade.php files

Adding a new driver

// src/drivers/rust-driver.js
import BaseDriver from './base-driver.js';
import { countMatches } from '../utils/regex.js';

export default class RustDriver extends BaseDriver {
    constructor() {
        super();
        this.name       = 'Rust';
        this.extensions = ['.rs'];
        this.priority   = 10;

        this.patterns = {
            singleLineComment: /\/\/.*$/gm,
            fn:     /\bfn\s+\w+/g,
            struct: /\bstruct\s+\w+/g,
            trait:  /\btrait\s+\w+/g,
            impl:   /\bimpl\s+/g,
            derive: /#\[derive\(/g,
            test:   /#\[test\]/g,
        };
    }

    parse(content, filePath) {
        const clean = this.removeComments(content, [this.patterns.singleLineComment]);
        const lines = this.countLines(content, clean);
        return {
            ...lines,
            lloc:    this.countLogicalLines(clean),
            fns:     countMatches(this.patterns.fn,     clean),
            structs: countMatches(this.patterns.struct, clean),
            traits:  countMatches(this.patterns.trait,  clean),
            impls:   countMatches(this.patterns.impl,   clean),
            derives: countMatches(this.patterns.derive, clean),
            tests:   countMatches(this.patterns.test,   content),
            complexity: this.calculateComplexity(clean),
            files: 1,
        };
    }

    formatMetrics(metrics) {
        return {
            'Rust': {
                'Functions': metrics.fns     || 0,
                'Structs':   metrics.structs || 0,
                'Traits':    metrics.traits  || 0,
                'Impl blocks': metrics.impls || 0,
                'Derive macros': metrics.derives || 0,
                'Tests':     metrics.tests   || 0,
            },
        };
    }
}

Then register it in src/drivers/index.js and add new RustDriver() to the array in src/code-cortex.js. That's it.


📈 Metrics explained

Size metrics

Metric Meaning
LOC Total lines including blanks and comments
CLOC Lines that contain comments
NCLOC Lines that contain code (LOC − CLOC − blank)
LLOC Logical lines — actual statements (semicolons + keywords)

Complexity

Cyclomatic complexity counts decision points: if, for, while, case, catch, &&, ||, ternary. Higher = harder to test. ≤10 is considered good; >20 signals refactoring.

Quality score (0–100)

Starting at 100, points are deducted for:

Issue Default deduction
Each unused class −2
Each unused method −1
Each unused import −0.5
Each duplicate block −3
Each high-severity security issue −10
Each medium-severity security issue −5
Each low-severity security issue −2

All deductions are configurable in codecortex.config.js under the quality key.


🌐 REST API

The server (codecortex --server) exposes:

Method Path Description
GET /api/health Status, port, data age
GET /api/analysis Latest analysis result (404 if none)
POST /api/analysis Submit results from CLI
DELETE /api/analysis Clear stored data

Analysis is persisted to .codecortex-server/latest-analysis.json and reloaded on restart — the dashboard never shows an error just because the server was restarted.


🤝 Contributing

See CONTRIBUTING.md. The quick version:

  1. Fork → git checkout -b feature/rust-driver
  2. Add your driver in src/drivers/, export from src/drivers/index.js, register in src/code-cortex.js
  3. Test: node src/cli.js ./your-test-project --list-drivers
  4. PR with a description of what the driver detects

📄 License

MIT © Anand Pilania

🔗 Links


Made with ❤️ by Anand Pilaniastar ⭐ if it's useful!

About

A modular, multi-language project analyzer with hierarchical driver architecture for PHP, JavaScript, TypeScript, React, Vue, and Blade.

Resources

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors