Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,21 @@ claude mcp add -s user -t stdio codebase-intelligence -- npx -y codebase-intelli

## Features

- **22 CLI commands** for architecture analysis, dependency impact, duplicate families, focused map/context packs, content drift, Highways convergence, improvement opportunities, dead code detection, search, CI rules, and agent setup
- **23 CLI commands** for architecture analysis, dependency impact, duplicate families, focused map/context packs, content drift, health scoring, Highways convergence, improvement opportunities, dead code detection, search, CI rules, and agent setup
- **Machine-readable JSON output** (`--json`) for automation and CI pipelines
- **Auto-cached index** in `.codebase-intelligence/` for fast repeat queries
- **Cache migration facts** in JSON (`cacheDir`, `legacyCacheDir`, `migrated`, `gitignoreUpdated`, `warnings[]`)
- **11 architectural metrics** — PageRank, betweenness, coupling, cohesion, tension, churn, complexity, blast radius, dead exports, test coverage, escape velocity
- **Quality metrics** — PageRank, betweenness, coupling, cohesion, tension, churn, complexity, blast radius, dead exports, test coverage, escape velocity, risk, maintainability, and CRAP score
- **Symbol-level analysis** — callers/callees, symbol importance, impact blast radius
- **BM25 search** — ranked keyword search across files, symbols, and type/shape facts
- **Process tracing** — detect entry points and execution flows through the call graph
- **Codebase maps + context packs** — focused file/symbol/test graph with deterministic evidence IDs and token-bounded context for agents
- **Content drift** — report-only detection for file/name/scope/side-effect/shape/test placement mismatch with stable evidence
- **Health score** — CI-gateable composite score with per-file maintainability, CRAP, coverage source, and risk hotspots
- **Highways analysis** — find repeated routes that bypass canonical dataflow paths and synthesize safe proposed highways
- **Community detection** — Louvain clustering for natural file groupings
- **Agent adoption** — `init` writes per-agent instruction files + installs a skill so AI agents query CI before grep/read
- **MCP parity (secondary)** — same analysis and rules gate available as 23 MCP tools, 2 prompts, and 3 resources
- **MCP parity (secondary)** — same analysis and rules gate available as 24 MCP tools, 2 prompts, and 3 resources

## Installation

Expand Down Expand Up @@ -98,7 +99,7 @@ codebase-intelligence <command> <path> [options]
| Command | What it does |
|---|---|
| `overview` | High-level codebase snapshot |
| `hotspots` | Rank files by metric (coupling, churn, complexity, blast radius, coverage, etc.) |
| `hotspots` | Rank files by metric (coupling, churn, complexity, blast radius, coverage, risk, etc.) |
| `file` | Full context for one file |
| `search` | BM25 keyword and shape search |
| `changes` | Git diff analysis with risk metrics |
Expand All @@ -115,6 +116,7 @@ codebase-intelligence <command> <path> [options]
| `processes` | Entry-point execution flow tracing |
| `map` | Focused codebase graph + token-bounded context pack |
| `drift` | Report-only content drift findings with evidence and recommendations |
| `health` | CI-gateable health score with maintainability, CRAP, coverage, and risk hotspots |
| `highways` | Repeated route convergence, canonical path opportunities, and synthesis proposals |
| `clusters` | Community-detected file clusters |
| `check` | Rules-engine gate for CI, including opt-in dead-code and dependency gates |
Expand All @@ -135,7 +137,8 @@ codebase-intelligence <command> <path> [options]
| `--trace <id>` | Return token evidence for one duplicate family |
| `--focus <name>` | Focus `map` or `drift` on one symbol, file, or scope |
| `--context-budget <n>` | Bound `map` context pack size |
| `--min-score <n>` | Minimum drift score for `drift` findings |
| `--min-score <n>` | Minimum drift score for `drift` findings; minimum health score before `health` exits 1 |
| `--score` | Print compact `health` score text |
| `--format <fmt>` | Export `map` as `markdown`, `json`, `dot`, or `graphml`; export `check` as `text`, `json`, or `sarif` |
| `--operation <verb>` | Focus `highways` on one operation verb |
| `--shape <name>` | Focus `highways` on one type/DTO shape |
Expand Down Expand Up @@ -240,6 +243,9 @@ For MCP tool details, see [docs/mcp-tools.md](docs/mcp-tools.md).
| **Blast Radius** | Transitive dependents affected by a change |
| **Dead Exports** | Unused exports (safe to remove) |
| **Test Coverage** | Whether a test file exists for each source file |
| **Risk Score** | Composite file risk from complexity, churn, coupling, size, blast radius, and test reachability |
| **Maintainability Index** | Health-derived 0-100 per-file maintainability score |
| **CRAP Score** | Complexity x uncovered-code risk, using Istanbul coverage when present or static test reachability otherwise |

## Architecture

Expand Down
8 changes: 5 additions & 3 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Core (shared computation)
| typed descriptors, input schemas, CLI/MCP adapters, result wrappers, text formatters
v
MCP (stdio) CLI (terminal/CI)
| 23 tools, 2 prompts, | 22 commands with text + JSON
| 24 tools, 2 prompts, | 23 commands with text + JSON
| 3 resources for LLMs | output for humans and CI
```

Expand All @@ -49,8 +49,9 @@ src/
rules/index.ts <- Rules engine + registry (check command + MCP check tool)
map/index.ts <- Focused codebase maps + token-bounded context packs
drift/ <- Content drift scoring, profiles, findings, tokens, and stable evidence
health/ <- Health score, maintainability, CRAP, coverage lookup, and risk scoring
highways/index.ts <- Repeated route convergence + bypass/cowpath/synthesis evidence
mcp/index.ts <- 23 MCP tools for LLM integration
mcp/index.ts <- 24 MCP tools for LLM integration
mcp/hints.ts <- Operation-keyed next-step hints for MCP tool responses
impact/index.ts <- Symbol-level impact analysis + rename planning
search/index.ts <- BM25 search engine
Expand Down Expand Up @@ -85,7 +86,7 @@ analyzeGraph(builtGraph, parsedFiles)
}

startMcpServer(codebaseGraph)
-> stdio MCP server with 23 tools, 2 prompts, 3 resources
-> stdio MCP server with 24 tools, 2 prompts, 3 resources

runOperation(operation, codebaseGraph, input, context)
-> { ok: true, data } | { ok: false, error, data? }
Expand All @@ -102,6 +103,7 @@ runOperation(operation, codebaseGraph, input, context)
- **Highways H1/H2**: `highways` / `analyze_highways` enumerates entry-to-sink call routes, groups repeated routes by operation/shape/sink, detects bypasses and cowpaths around an existing canonical node, and with `--propose` synthesizes a read-only proposed highway with name, file, signature, skeleton, reroute plan, cycle safety, evidence, blast radius, recommendations, and a context pack for agents.
- **Codebase map context packs**: `map` / `get_codebase_map` builds deterministic file/symbol/test/scope graphs with stable evidence IDs. `get_scope_graph` and `get_context_pack` are MCP-only filtered views derived from the same result, so agents get compact context without a second analyzer path.
- **Content drift**: `drift` / `detect_content_drift` compares path/name/export intent with import/call/type/side-effect/test behavior. Findings are deterministic, evidence-backed, report-only, and baseline-gated before any future CI enforcement.
- **Health score**: `health` / `get_health_score` computes one gateable score plus per-file maintainability, CRAP, coverage, and risk evidence. `hotspots --metric risk` uses the same file-risk formula.
- **Shared graph-load pipeline**: CLI commands and MCP stdio startup both use `src/graph-loader/` for path checks, legacy cache migration, cache reuse, parse/build/analyze, optional persistence, and stderr progress events.
- **graphology**: In-memory graph with O(1) neighbor lookup. PageRank and betweenness computed via graphology-metrics.
- **Batch git churn**: Single `git log --all --name-only` call, parsed for all files. Avoids O(n) subprocess spawning.
Expand Down
19 changes: 16 additions & 3 deletions docs/cli-reference.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# CLI Reference

22 commands for terminal and CI use. The 20 analysis commands have full parity with MCP tools and auto-cache the index to `.codebase-intelligence/`; `check` runs the rules gate; `init` sets up agent adoption.
23 commands for terminal and CI use. The 21 analysis commands have full parity with MCP tools and auto-cache the index to `.codebase-intelligence/`; `check` runs the rules gate; `init` sets up agent adoption.

## Commands

Expand All @@ -22,7 +22,7 @@ Rank files by metric.
codebase-intelligence hotspots <path> [--metric <metric>] [--limit <n>] [--json] [--force]
```

**Metrics:** `coupling` (default), `pagerank`, `fan_in`, `fan_out`, `betweenness`, `tension`, `churn`, `complexity`, `blast_radius`, `coverage`, `escape_velocity`.
**Metrics:** `coupling` (default), `pagerank`, `fan_in`, `fan_out`, `betweenness`, `tension`, `churn`, `complexity`, `blast_radius`, `coverage`, `risk`, `escape_velocity`.

### file

Expand Down Expand Up @@ -190,6 +190,18 @@ codebase-intelligence drift <path> [--focus <fileOrSymbol>] [--scope <scope>] [-

**Output:** `mode: "report-only"`, baseline status, findings with stable `drift-*` IDs, `kind` (`name-drift`, `scope-drift`, `mixed-responsibility`, `hidden-side-effect`, `shape-drift`, `orphan-scope`, `misplaced-test`), score, severity, declared intent, actual behavior, evidence IDs/summaries, recommendations, and advisory actions. Drift does not fail CI until a baseline/gate is configured.

### health

Compute a CI-gateable codebase health score.

```bash
codebase-intelligence health <path> [--score] [--min-score <n>] [--json] [--force]
```

**Output:** `score`, `minScore`, `verdict`, component scores, coverage source (`static-tests` or root-local Istanbul coverage), per-file `maintainabilityIndex`, `crapScore`, `riskScore`, evidence, hotspots, and advisory actions.

**Exit codes:** `0` when score is at least `minScore`; `1` when score is below `minScore`; `2` for invalid input.

### highways

Find repeated routes that should converge on one canonical operation path.
Expand Down Expand Up @@ -268,7 +280,8 @@ codebase-intelligence init [path] [--agents <list>] [--all] [--skill] [--gitigno
| `--entry <name>` | processes | Filter by entry point name |
| `--focus <name>` | map, drift | Focus on one symbol, file, or scope |
| `--context-budget <n>` | map | Approximate token budget for context pack |
| `--min-score <n>` | drift | Minimum drift score to report |
| `--min-score <n>` | drift, health | Minimum drift score to report; minimum health score before exit 1 |
| `--score` | health | Print compact score text |
| `--operation <verb>` | highways | Focus on one operation verb |
| `--shape <name>` | highways | Focus on one type/DTO shape |
| `--min-routes <n>` | highways | Minimum routes reaching a sink before reporting |
Expand Down
50 changes: 50 additions & 0 deletions docs/data-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,56 @@ ContentDriftEvidence {
}
```

## Health Result

`health --json` and MCP `get_health_score` return a deterministic health envelope. CLI `health --min-score <n>` exits `1` when `score < minScore`.

```typescript
HealthResult {
score: number
minScore: number
verdict: "pass" | "fail"
summary: string
components: {
maintainability: number
complexity: number
churn: number
coupling: number
coverage: number
blastRadius: number
}
coverage: {
source: "istanbul" | "static-tests"
coveredFiles: number
totalFiles: number
warning?: string
}
files: HealthFileResult[]
hotspots: HealthFileResult[]
actions: Array<{ command: string; reason: string }>
}

HealthFileResult {
file: string
loc: number
maintainabilityIndex: number
crapScore: number
riskScore: number
coverage: number
coverageSource: "istanbul" | "static-tests"
metrics: {
complexity: number
churn: number
coupling: number
blastRadius: number
fanIn: number
fanOut: number
hasTests: boolean
}
evidence: string[]
}
```

## Highways Result

`highways --json` and MCP `analyze_highways` return deterministic route-convergence opportunities.
Expand Down
21 changes: 16 additions & 5 deletions docs/mcp-tools.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# MCP Tools Reference

23 tools available via MCP stdio.
24 tools available via MCP stdio.

Operation tools return JSON text payloads. Invalid operation inputs return `isError: true` with `{ "error": "..." }` using the same descriptor validation messages as CLI bad-argument exits.

Expand Down Expand Up @@ -41,7 +41,7 @@ File-level blast radius analysis — what breaks if this file changes.
Rank files by any metric.

**Input:** `{ metric: string, limit?: number }` (default limit: 10)
**Metrics:** coupling, pagerank, fan_in, fan_out, betweenness, tension, escape_velocity, churn, complexity, blast_radius, coverage
**Metrics:** coupling, pagerank, fan_in, fan_out, betweenness, tension, escape_velocity, churn, complexity, blast_radius, coverage, risk
**Returns:** ranked files with score + reason, summary

**Use when:** "What are the riskiest files?" "Which files need tests?" "Most complex files?"
Expand Down Expand Up @@ -209,7 +209,17 @@ Detect report-only mismatch between declared file/folder intent and observed beh
**Use when:** Finding file/folder/content drift before a refactor, roadmap cleanup, or baseline creation.
**Not for:** Failing CI without a baseline (use check or a future ci wrapper).

## 21. analyze_highways
## 21. get_health_score

Compute a CI-gateable codebase health score.

**Input:** `{ minScore?: number, score?: boolean }`
**Returns:** score, minScore, verdict, components, coverage source/counts, files[] (maintainabilityIndex, crapScore, riskScore, metrics, evidence), hotspots[], actions[], summary

**Use when:** Gating PR quality, ranking complexity/churn/coupling/size hotspots, or tracking maintainability.
**Not for:** Route discipline (use analyze_highways) or naming drift (use detect_content_drift).

## 22. analyze_highways

Detect repeated entry-to-sink routes that should converge on one canonical operation path.

Expand All @@ -219,7 +229,7 @@ Detect repeated entry-to-sink routes that should converge on one canonical opera
**Use when:** Enforcing dataflow discipline, finding ad-hoc routes, or planning canonical shared paths.
**Not for:** Raw execution flow listing (use get_processes).

## 22. get_clusters
## 23. get_clusters

Community-detected clusters of related files.

Expand Down Expand Up @@ -264,8 +274,9 @@ Rules: `no-comments` (off by default), `no-circular-deps` (error), `no-dead-expo
| "Tell me about file X" | `file_context` |
| "What breaks if I change file X?" | `get_dependents` |
| "What breaks if I change function X?" | `impact_analysis` |
| "What are the riskiest files?" | `find_hotspots` (coupling, churn, or blast_radius) |
| "What are the riskiest files?" | `find_hotspots` (risk, coupling, churn, or blast_radius) |
| "Which files need tests?" | `find_hotspots` (coverage) |
| "What is the PR quality score?" | `get_health_score` |
| "What should I improve first?" | `find_opportunities` |
| "Find refactoring opportunities." | `find_opportunities` |
| "Where is logic duplicated?" | `find_duplicates` |
Expand Down
10 changes: 9 additions & 1 deletion docs/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ All metrics are computed per-file and stored in `FileMetrics`. Module-level aggr
| **escapeVelocity** | number | 0-1 | Readiness for extraction. High = few internal deps, many external consumers. |
| **verdict** | string | LEAF/COHESIVE/MODERATE/JUNK_DRAWER | Single non-test file = LEAF (cohesion meaningless). Otherwise: cohesion >= 0.6 = COHESIVE, >= 0.4 = MODERATE, else JUNK_DRAWER. |

## Health Metrics

| Metric | Range | Source | Description |
|--------|-------|--------|-------------|
| **maintainabilityIndex** | 0-100 | derived | Per-file score from complexity, LOC, churn, coupling, blast radius, and test reachability. Higher is better. |
| **crapScore** | 0-N | derived | `complexity^2 * uncovered^3 + complexity`. Coverage comes from root-local Istanbul coverage when present, otherwise static test reachability. Lower is better. |
| **riskScore** | 0-100 | derived | Composite risk from low maintainability, complexity, churn, coupling, size, and blast radius. Used by `hotspots --metric risk`. Higher is riskier. |

## Force Analysis

| Signal | Threshold | Meaning |
Expand Down Expand Up @@ -66,4 +74,4 @@ The most dangerous files have all three:
- **High coupling** (many dependents)
- **Low coverage** (no tests)

Use `find_hotspots` with different metrics to find these files, or visually compare Churn and Coverage views.
Use `find_hotspots --metric risk` or `health --json` to find files where complexity, churn, coupling, size, and test reachability compound into one score.
Loading
Loading