# Thuban -- Code Intelligence Scanner

[![npm version](https://img.shields.io/npm/v/thuban.svg)](https://www.npmjs.com/package/thuban)
[![license](https://img.shields.io/npm/l/thuban.svg)](LICENSE)
[![tests](https://img.shields.io/badge/tests-746%20passing-brightgreen.svg)](#testing)
[![coverage](https://img.shields.io/badge/coverage-91.2%25-brightgreen.svg)](#testing)

Static analysis, security scanning, dead code detection, clone detection, AI-generated code scoring, dependency analysis, and mutation testing for 12 languages. One command. Zero runtime dependencies beyond `@babel/parser`.

---

## Quick Start

```bash
npm install -g thuban
thuban scan .
```

Or run without installing:

```bash
npx thuban scan .
```

JSON output for CI pipelines:

```bash
thuban scan . --json
```

---

## Feature Highlights

### Security Analysis

84 detection rules across multiple categories. Cross-file taint tracking follows user input from sources (`req.query`, `req.body`, `req.params`, `process.argv`, `process.env`) through assignment, concatenation, and template interpolation to dangerous SQL and XSS sinks -- across file boundaries via `require()`, `import`, destructured imports, and re-exports.

```bash
thuban scan src/ --json
```

### Control Flow Graph Analysis

Detects unreachable code, infinite loops, and dead branches through AST-based control flow graph construction.

### Clone Detection

Multi-language code clone detection with AST normalization. Finds duplicated logic across your codebase.

```bash
thuban clones src/
```

### AI-Generated Code Scoring

Scores files for likelihood of AI generation based on structural patterns, naming conventions, and code smells common in LLM output.

```bash
thuban aiscore src/
```

### Dependency Analysis

Maps dependency graphs, detects circular imports, and identifies unused or phantom dependencies.

```bash
thuban deps .
```

### Mutation Testing (Crucible)

Built-in mutation testing engine. 515 seed files generate 1,030 mutations. Validates that your test suite catches real bugs.

```bash
thuban crucible --mode kenny    # standard mode
thuban crucible --mode hell     # maximum mutation density
```

### Ghost Code Detection

Finds dead exports, unused functions, and unreachable modules.

```bash
thuban ghosts src/
```

### Auto-Fix

Automatically applies safe fixes for supported rule violations.

```bash
thuban fix src/
```

### HTML Dashboard

Generates a visual HTML report with charts, trends, and drill-down by category.

```bash
thuban dashboard .
```

### Executive Reports

PDF-ready executive summary with risk scores, trend data, and remediation priorities.

```bash
thuban executive .
thuban pdf .
```

### Baseline Scanning

Establish a baseline and track only new issues introduced after that point.

```bash
thuban baseline .          # save current state
thuban scan . --baseline   # report only new issues
thuban compare .           # compare current scan to baseline
```

### Pre-Commit Gate

Block commits that introduce issues above a configurable threshold.

```bash
thuban gate .
```

### Inline Suppression

Suppress specific rules on a per-line basis:

```javascript
const query = "SELECT * FROM " + input; // thuban-ignore SEC001
```

```python
password = "admin123"  # thuban-ignore SEC005
```

Suppress all rules on a line:

```javascript
eval(code); // thuban-ignore
```

---

## Supported Languages

| Language   | Extension(s)         | AST Engine     |
|------------|----------------------|----------------|
| JavaScript | `.js`, `.mjs`, `.cjs`| Babel          |
| TypeScript | `.ts`                | Babel          |
| JSX        | `.jsx`               | Babel          |
| TSX        | `.tsx`               | Babel          |
| Python     | `.py`                | Python `ast`   |
| Go         | `.go`                | `go/parser`    |
| Rust       | `.rs`                | Pattern-based  |
| Ruby       | `.rb`                | Pattern-based  |
| Java       | `.java`              | Pattern-based  |
| C#         | `.cs`                | Pattern-based  |
| Kotlin     | `.kt`                | Pattern-based  |
| PHP        | `.php`               | Pattern-based  |

Three AST engines provide deep analysis: Babel for JavaScript/TypeScript/JSX/TSX, Python `ast` for Python, and Go `go/parser` for Go. Remaining languages use pattern-based detection.

---

## Detection Rules

84 rules organized by category:

| Category    | Rule IDs              | Description                                      |
|-------------|-----------------------|--------------------------------------------------|
| Security    | SEC001--SEC019        | SQL injection, XSS, hardcoded secrets, eval, command injection, path traversal, insecure crypto, SSRF, prototype pollution, and more |
| Security    | RUST001--RUST002      | Rust-specific unsafe patterns                    |
| Quality     | QUAL001--QUAL004      | Code quality, naming, structure                  |
| Performance | PERF001               | Performance anti-patterns                        |
| AST         | AST001--AST005        | Phantom imports, deprecated APIs, unused variables, hallucinated APIs, empty catch blocks |
| AST         | AST011--AST014        | Advanced AST patterns                            |
| Taint       | TAINT001--TAINT002    | Cross-file taint tracking for SQLi and XSS       |
| CFG         | CFG001--CFG005        | Unreachable code, infinite loops, dead branches  |
| Nesting     | NEST001               | Excessive nesting depth                          |
| Complexity  | CMPLX001--CMPLX002   | Cyclomatic and cognitive complexity              |

---

## CLI Commands

28 commands grouped by function:

### Core Scanning

| Command       | Description                                      |
|---------------|--------------------------------------------------|
| `scan [path]` | Scan a codebase for issues                       |
| `diff [path]` | Scan only git-changed files                      |
| `deps [path]` | Map dependencies and detect circular imports     |
| `health [path]`| Run health check on codebase                    |
| `report [path]`| Full scan + deps + drift combined report        |

### Detection

| Command              | Description                                |
|----------------------|--------------------------------------------|
| `hallucinate [path]` | Detect AI hallucinations and phantom imports|
| `ghosts [path]`      | Detect dead code and unused exports        |
| `aiscore [path]`     | Score files for AI-generated code patterns |
| `clones [path]`      | Detect code clones across the codebase     |
| `drift [path]`       | Detect drift from Mother Code annotations  |
| `debt [path]`        | Analyze technical debt                     |
| `cost [path]`        | Calculate technical debt cost              |

### Remediation

| Command       | Description                                      |
|---------------|--------------------------------------------------|
| `fix [path]`  | Auto-fix supported rule violations               |
| `inject [path]`| Inject Mother Code DNA widget into files        |
| `gate [path]` | Pre-commit quality gate                          |

### Reporting

| Command            | Description                                   |
|--------------------|-----------------------------------------------|
| `dashboard [path]` | Generate visual HTML dashboard                |
| `executive [path]` | Generate executive summary report             |
| `pdf [path]`       | Generate PDF-ready report                     |
| `passport [path]`  | Generate codebase passport                    |

### Monitoring

| Command          | Description                                     |
|------------------|-------------------------------------------------|
| `watch [path]`   | Live sentinel -- continuous file monitoring     |
| `monitor [path]` | Recurring scans with history and alerts         |
| `history [path]` | View recurring scan history                     |
| `trend [path]`   | Show issue trends across scans                  |

### Baseline and Comparison

| Command          | Description                                     |
|------------------|-------------------------------------------------|
| `baseline [path]`| Save current scan state as baseline             |
| `compare [path]` | Compare current scan against baseline           |

### Licensing

| Command    | Description                                          |
|------------|------------------------------------------------------|
| `activate` | Activate a license key                               |
| `status`   | Show current license status                          |
| `upgrade`  | Upgrade license tier                                 |

### Mutation Testing

| Command    | Description                                          |
|------------|------------------------------------------------------|
| `crucible` | Run the Crucible mutation testing engine             |

---

## Configuration

### `.thubanrc.json`

Place a `.thubanrc.json` in your project root to configure scan behavior:

```json
{
  "$schema": "https://thuban.dev/schema/thubanrc.json",
  "minScore": 0,
  "ignore": [
    "node_modules",
    "dist",
    ".git",
    "coverage"
  ],
  "hallucination": {
    "enabled": true,
    "ignore": []
  },
  "motherCode": {
    "enabled": true,
    "autoInject": false
  },
  "report": {
    "format": "html",
    "outputDir": "."
  },
  "ci": {
    "failOnGrade": "F",
    "postComment": true
  }
}
```

### `.thubanignore`

Exclude files and directories from scanning, one glob pattern per line:

```
packages/crucible/seeds/**
tests/regression/fixtures/**
vendor/**
```

---

## JSON Output

All scan commands support `--json` for machine-readable output:

```bash
thuban scan src/ --json
```

```json
{
  "version": "0.4.5",
  "timestamp": "2026-07-04T12:00:00.000Z",
  "files": 42,
  "issues": [
    {
      "file": "src/api/handler.js",
      "line": 17,
      "rule": "SEC001",
      "severity": "critical",
      "category": "security",
      "message": "Potential SQL injection: unsanitized input in query string",
      "fix": "Use parameterized queries instead of string concatenation"
    }
  ],
  "summary": {
    "critical": 1,
    "warning": 3,
    "info": 5,
    "score": 72,
    "grade": "C"
  }
}
```

---

## Performance

| Metric         | Value              |
|----------------|--------------------|
| Throughput     | ~23,000 lines/sec  |
| Test suite     | 746 tests          |
| Code coverage  | 91.2%              |
| Dependencies   | 1 (`@babel/parser`) |

---

## Tiers

| Tier       | Limit     | Features                                          |
|------------|-----------|---------------------------------------------------|
| Free       | 100 files | Core scanning, all 84 rules, JSON output          |
| Pro        | Unlimited | Recurring scans, history, trends, notifications   |
| Team       | Unlimited | Dashboard, executive reports, baseline management |
| Enterprise | Unlimited | Custom rules, priority support, SSO               |

Activate a license:

```bash
thuban activate <license-key>
thuban status
```

---

## CI Integration

### GitHub Actions

```yaml
- name: Thuban Scan
  run: npx thuban scan . --json --baseline
  env:
    THUBAN_LICENSE: ${{ secrets.THUBAN_LICENSE }}
```

### Pre-Commit Hook

```bash
thuban gate . --fail-on critical
```

---

## Requirements

- Node.js >= 16.0.0

---

## Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/my-feature`)
3. Run the test suite (`npm test`)
4. Submit a pull request

Issues and feature requests: [github.com/SilverwingsBenefitsGit/thuban/issues](https://github.com/SilverwingsBenefitsGit/thuban/issues)

---

## License

[MIT](LICENSE)

---

[thuban.dev](https://thuban.dev)
