Skip to content

xnt/codexray

Repository files navigation

Codexray

A local-first code-health and refactoring analysis tool for TypeScript repositories.

Overview

Codexray scans TypeScript codebases, detects maintainability and structural issues, scores overall health with a letter grade (A–F), generates actionable refactor plans, and visualises symbol-level relationships — all entirely offline. It runs locally after install and is designed to be easy to Dockerize.

Features

  • CLI-first UX — Simple command-line interface with six commands: scan, fix, report, explain, plan, symbols
  • Local-first — No network dependencies at runtime
  • TypeScript only — Focused analysis for TypeScript projects
  • 10 built-in rules — Complexity, nesting, params, abstraction mixing, error handling, god modules, boolean traps, switch polymorphism, and more
  • Maintainability rating — A–F letter grade with penalty breakdowns and hotspot identification
  • Refactor planner — Findings are clustered, root-causes inferred, and prioritised plan items generated with rationale and steps
  • Symbol analysis — Discovers functions, classes, methods, and arrow functions; builds a call/containment graph; visualises relationships in TUI and HTML
  • Multi-format output — Terminal (coloured), JSON, and HTML reports for scans, plans, and symbols
  • Safe autofixes — Limited transformations for clearly safe cases (e.g., early-return refactoring)
  • Extensible — Designed to support more rules, reporters, and clustering strategies

Quick Start

# Clone and build
git clone <repo-url>
cd codexray
npm install
npm run build

# Scan the sample fixture project
npm run scan:sample

# Scan Codexray's own source code
npm run scan:src

# Scan any TypeScript project (use -- to pass arguments)
npm run scan -- /path/to/your/project

# Scan with options
npm run scan -- ./src --verbose
npm run scan -- ./src --format json
npm run scan -- ./src --rules max-params,no-large-functions

# Generate a refactor plan
npm run plan:sample

# Visualise symbols and their relationships
npm run symbols:sample

# Preview autofixes (dry-run)
npm run fix:dry

# Run all tests
npm test

# Run tests with coverage
npm test -- --coverage

Installation

npm install -g codexray

Or use directly with npx:

npx codexray scan ./src

Usage

Scan a project

# Scan a directory
codexray scan ./src

# Scan with JSON output
codexray scan ./src --format json

# Scan with HTML output
codexray scan ./src --format html --output report.html

# Scan with specific rules
codexray scan ./src --rules max-params,no-large-functions

# Verbose output
codexray scan ./src --verbose

# Save output to file
codexray scan ./src --format json --output report.json

Fix issues

# Preview fixes (dry-run)
codexray fix ./src --dry-run

# Apply fixes
codexray fix ./src

# Fix specific rules only
codexray fix ./src --rules prefer-early-return

# Create backups before fixing
codexray fix ./src --backup

Generate reports

# Generate terminal report
codexray report ./src

# Generate JSON report
codexray report ./src --format json --output report.json

# Generate HTML report
codexray report ./src --format html --output report.html

Explain rules

# List all available rules
codexray explain

# Explain a specific rule
codexray explain no-large-functions

Generate a refactor plan

# Terminal plan (default)
codexray plan ./src

# JSON plan
codexray plan ./src --format json --output plan.json

# HTML plan
codexray plan ./src --format html --output plan.html

# Plan for specific rules only
codexray plan ./src --rules no-large-functions,no-deep-nesting

The planner clusters related findings, infers root causes, and produces prioritised plan items with:

  • Rationale — why this refactoring is needed
  • Proposed steps — concrete, ordered actions
  • Impact / effort / confidence estimates
  • Symbol-aware clustering — groups findings that affect related functions or methods

Explore symbols

# Terminal symbol explorer (default)
codexray symbols ./src

# HTML symbol report
codexray symbols ./src --format html --output symbols.html

The symbols command discovers all functions, classes, methods, arrow functions, constructors, and accessors. It builds a call/containment graph and renders:

  • Per-file symbol tree with call edges
  • Kind breakdown and summary statistics
  • TLDR — busiest files, largest classes, most-connected symbols, and export surface at a glance

Built-in Rules

no-large-functions

Detects functions that exceed a configurable line threshold.

  • Default threshold: 50 lines
  • Severity: warning
  • Options: maxLines - Maximum allowed lines
{
  "rules": {
    "no-large-functions": {
      "enabled": true,
      "severity": "warning",
      "options": { "maxLines": 50 }
    }
  }
}

max-params

Detects functions with too many parameters.

  • Default threshold: 4 parameters
  • Severity: warning
  • Options: maxParams - Maximum allowed parameters
{
  "rules": {
    "max-params": {
      "enabled": true,
      "severity": "warning",
      "options": { "maxParams": 4 }
    }
  }
}

no-deep-nesting

Detects functions whose nesting depth exceeds a threshold.

  • Default threshold: 4 levels
  • Severity: warning
  • Options: maxDepth - Maximum allowed nesting depth
{
  "rules": {
    "no-deep-nesting": {
      "enabled": true,
      "severity": "warning",
      "options": { "maxDepth": 4 }
    }
  }
}

prefer-early-return

Detects nested conditionals that could be simplified with guard clauses.

  • Default threshold: 2 levels of nesting
  • Severity: info
  • Has autofix: Yes (for safe cases)
  • Options: minNestingLevel - Minimum nesting to report
{
  "rules": {
    "prefer-early-return": {
      "enabled": true,
      "severity": "info",
      "options": { "minNestingLevel": 2 }
    }
  }
}

boolean-parameter-trap

Detects boolean parameters that create ambiguous call sites.

  • Severity: warning
  • Options: minPosition - Minimum parameter position to flag (0-indexed)
{
  "rules": {
    "boolean-parameter-trap": {
      "enabled": true,
      "severity": "warning",
      "options": { "minPosition": 0 }
    }
  }
}

Example:

// ❌ Bad - what does true mean?
createUser('john', true);

// ✅ Better - use options object
createUser('john', { isAdmin: true });

// ✅ Or split into separate functions
createAdminUser('john');

mixed-abstraction-levels

Detects functions that mix high-level orchestration with low-level implementation.

  • Severity: warning
  • Options:
    • minHighLevelScore - Minimum high-level signals (default: 1)
    • minLowLevelScore - Minimum low-level signals (default: 2)
{
  "rules": {
    "mixed-abstraction-levels": {
      "enabled": true,
      "severity": "warning",
      "options": { "minHighLevelScore": 1, "minLowLevelScore": 2 }
    }
  }
}

High-level signals: function calls, branching, orchestration verbs in name Low-level signals: loops, new expressions, property assignments, string formatting

inconsistent-error-handling

Detects files using multiple error handling strategies.

  • Severity: warning
  • Options: minFunctionCount - Minimum functions to check (default: 2)
{
  "rules": {
    "inconsistent-error-handling": {
      "enabled": true,
      "severity": "warning",
      "options": { "minFunctionCount": 2 }
    }
  }
}

Strategies detected:

  • throw - throws exceptions
  • null-return - returns null on error
  • undefined-return - returns undefined on error
  • result-object - returns { ok, data, error } style objects
  • fallback-in-catch - catches and returns fallback value

switch-wants-polymorphism

Detects switch statements that would be better as handler maps or polymorphism.

  • Severity: info
  • Options:
    • minCases - Minimum cases to consider (default: 3)
    • minStructuralSimilarity - Similarity threshold 0-1 (default: 0.6)
{
  "rules": {
    "switch-wants-polymorphism": {
      "enabled": true,
      "severity": "info",
      "options": { "minCases": 3 }
    }
  }
}

Detects:

  • Type-like discriminants (type, kind, status, mode, provider)
  • Similar case structures
  • Repeated assignment targets across cases

god-module

Detects files that are doing too much.

  • Severity: warning
  • Options: minScore - Minimum score to trigger (default: 3)
{
  "rules": {
    "god-module": {
      "enabled": true,
      "severity": "warning",
      "options": { "minScore": 3 }
    }
  }
}

Scoring:

  • Lines: +1 for >300, +2 for >600
  • Exports: +1 for >8, +2 for >15
  • Functions/methods: +1 for >10
  • Classes: +1 for >2
  • Top-level statements: +1 for >20
  • Import areas: +1 for >8

Configuration

Create a codexray.config.json file in your project root:

{
  "version": "1.0.0",
  "include": ["**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules/**", "dist/**", "**/*.d.ts"],
  "rules": {
    "no-large-functions": {
      "enabled": true,
      "options": { "maxLines": 40 }
    },
    "max-params": {
      "enabled": true,
      "options": { "maxParams": 3 }
    },
    "no-deep-nesting": {
      "enabled": true,
      "options": { "maxDepth": 3 }
    },
    "prefer-early-return": {
      "enabled": true
    }
  }
}

Exit Codes

  • 0 - No errors found
  • 1 - Errors found or command failed

Development

# Install dependencies
npm install

# Build
npm run build

# Run tests
npm test
npm run test:watch    # Watch mode
npm test -- --coverage  # Coverage report

# Scan shortcuts
npm run scan          # Scan (pass path after --)
npm run scan:sample   # Scan sample fixture
npm run scan:src      # Scan Codexray's source
npm run scan:json     # Scan with JSON output
npm run scan:html     # Scan with HTML output

# Plan shortcuts
npm run plan:sample   # Plan for sample fixture
npm run plan:json     # Plan as JSON
npm run plan:html     # Plan as HTML

# Symbol shortcuts
npm run symbols:sample  # Symbols for sample fixture
npm run symbols:html    # Symbols as HTML

# Fix shortcuts
npm run fix:dry       # Preview autofixes

Passing Arguments

Use -- to pass arguments to npm scripts:

npm run scan -- ./your-project
npm run scan -- ./src --verbose --format json
npm run plan -- ./your-project --format html --output plan.html
npm run symbols -- ./your-project

Architecture

Codexray is designed with clean separation of concerns:

src/
├── cli/           # CLI layer (commands: scan, fix, report, explain, plan, symbols)
├── core/          # Analysis engine (scanner, analyzer, project loader)
├── rules/         # Rule system (types, registry, 10 implementations)
├── findings/      # Finding model (types)
├── fixes/         # Fix/edit model (types, apply logic)
├── planner/       # Refactor planner (clustering, inference, priority, generation)
├── rating/        # Maintainability rating engine (A–F grading)
├── symbols/       # Symbol subsystem (discovery, graph, index, call resolution)
├── reporters/     # Output adapters (terminal, JSON, HTML — for scans, plans, symbols)
├── config/        # Configuration (types, defaults)
└── utils/         # AST helpers, error-handling helpers, scoring helpers

Extension Points

  • Rules: Add new rules by implementing the Rule interface in src/rules/implementations/
  • Reporters: Add new output formats by implementing the reporter pattern in src/reporters/
  • Fixes: Add autofix capabilities by implementing AutoFixableRule
  • Planner patterns: Add inference heuristics in src/planner/inference.ts
  • Clustering strategies: Add new grouping strategies in src/planner/clustering.ts
  • Symbol analysis: Extend the symbol graph with new edge types or cross-file resolution

License

MIT

About

A local-first code-health and refactoring analysis tool for TypeScript repositories. Scans codebases, detects maintainability and structural issues, reports findings in a clean structured way, and optionally applies a limited set of safe autofixes. It runs entirely offline after install and is designed to be easy to use and extend.

Topics

Resources

License

Stars

2 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors