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
22 changes: 18 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ claude mcp add -s user -t stdio codebase-intelligence -- npx -y codebase-intelli
- **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[]`)
- **Quality metrics** — PageRank, betweenness, coupling, cohesion, tension, churn, complexity, blast radius, dead exports, test coverage, escape velocity, risk, maintainability, and CRAP score
- **Quality metrics** — PageRank, betweenness, coupling, cohesion, tension, churn, cyclomatic/cognitive 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
Expand Down Expand Up @@ -100,7 +100,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, risk, etc.) |
| `hotspots` | Rank files by metric (coupling, churn, complexity, cognitive 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 @@ -121,7 +121,18 @@ codebase-intelligence <command> <path> [options]
| `boundaries` | Architecture boundary zones, allow/forbid import rules, and violation evidence |
| `highways` | Repeated route convergence, canonical path opportunities, and synthesis proposals |
| `clusters` | Community-detected file clusters |
| `owners` | Ownership, bus-factor, and risk grouping |
| `architecture` | Evidence-backed extraction/seam/locality recommendations |
| `workspaces` | Package workspace scope and changed-workspace detection |
| `lsp` | Advisory editor diagnostics snapshot or minimal LSP server |
| `watch` | Local watch readiness and debounced analysis events |
| `check` | Rules-engine gate for CI, including opt-in dead-code and dependency gates |
| `ci` | One PR quality gate around check, changes, health, formats, baselines, and history |
| `doctor` | Read-only setup auditor for local, CI, MCP, and agent workflows |
| `explain` | Explain one analyzer rule and next action |
| `migrate-config` | Dry-run config migration to `codebase-intelligence.json` |
| `hooks` | Plan or install local hooks that run the same CI gate |
| `history` | Read local finding history from `.codebase-intelligence/` |
| `init` | Set up AI agents to use CI — writes per-agent instruction files (skill opt-in via `--skill`) |

### Useful flags
Expand All @@ -143,9 +154,12 @@ codebase-intelligence <command> <path> [options]
| `--score` | Print compact `health` score text |
| `--preset <name>` | Run `boundaries` with `bulletproof`, `layered`, `hexagonal`, or `feature-sliced` |
| `--list` | List resolved `boundaries` zones and rules |
| `--format <fmt>` | Export `map` as `markdown`, `json`, `dot`, or `graphml`; export `check` as `text`, `json`, or `sarif` |
| `--format <fmt>` | Export `map` as `markdown`, `json`, `dot`, or `graphml`; export `check`/`ci` as `text`, `json`, `sarif`, `markdown`, `annotations`, `pr-comment-github`, `pr-comment-gitlab`, `badge`, `codeclimate`, or `compact` |
| `--operation <verb>` | Focus `highways` on one operation verb |
| `--shape <name>` | Focus `highways` on one type/DTO shape |
| `--production` | Exclude test/dev files from production-risk `check`/`ci` output |
| `--changed-since <ref>` | Line-level `check`/`ci` filtering from a git diff |
| `--diff-file <path>` | Line-level `check`/`ci` filtering from a unified diff file |

The scanner always excludes common generated and agent-workspace directories such as `.codebase-intelligence/`, legacy `.code-visualizer/`, `.next/`, `dist/`, `coverage/`, `.worktrees/`, and `.claude/worktrees/`.

Expand Down Expand Up @@ -243,7 +257,7 @@ For MCP tool details, see [docs/mcp-tools.md](docs/mcp-tools.md).
| **Tension** | Is a file torn between modules? (entropy of cross-module pulls) |
| **Escape Velocity** | Should this module be its own package? |
| **Churn** | Git commit frequency |
| **Complexity** | Average cyclomatic complexity of exports |
| **Complexity** | Average cyclomatic and cognitive complexity of exports/symbols |
| **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 |
Expand Down
23 changes: 18 additions & 5 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ CLI (commander)
|
v
Parser (TS Compiler API)
| extracts: files, exports, symbols, type facts, duplicate tokens, imports, LOC, complexity, churn, test mapping
| extracts: files, exports, symbols, type facts, duplicate tokens, imports, LOC, cyclomatic/cognitive complexity, churn, test mapping
v
Graph Builder (graphology)
| creates: nodes (file + function), edges (imports with symbols/weights)
| detects: circular dependencies (iterative DFS)
v
Analyzer
| computes: PageRank, betweenness, coupling, tension, cohesion
| computes: churn, complexity, blast radius, dead exports, test coverage
| computes: churn, cyclomatic/cognitive complexity, blast radius, dead exports, test coverage
| produces: ForceAnalysis (tension files, bridges, extraction candidates)
v
Core (shared computation)
Expand All @@ -25,7 +25,7 @@ Core (shared computation)
| typed descriptors, input schemas, CLI/MCP adapters, result wrappers, text formatters
v
MCP (stdio) CLI (terminal/CI)
| 25 tools, 2 prompts, | 24 commands with text + JSON
| 29 tools, 2 prompts, | 35 commands with text + JSON
| 3 resources for LLMs | output for humans and CI
```

Expand All @@ -52,7 +52,18 @@ src/
health/ <- Health score, maintainability, CRAP, coverage lookup, and risk scoring
boundaries/ <- Architecture zones, allow/forbid edge rules, and violation evidence
highways/index.ts <- Repeated route convergence + bypass/cowpath/synthesis evidence
mcp/index.ts <- 25 MCP tools for LLM integration
ci/index.ts <- First-class PR gate wrapper around check, changes, health, formats, baselines, history
doctor/index.ts <- Read-only setup auditor with fix commands and docs links
ownership/index.ts <- CODEOWNERS/git ownership, bus-factor, package/directory grouping
recommendations/ <- Extraction, seam, tension, and locality recommendations with context packs
lsp/index.ts <- Advisory diagnostics/hover snapshot plus minimal stdio LSP server
workspaces/index.ts <- Package/workspace scope and changed-workspace detection
watch/index.ts <- Local watch readiness and debounced change events
migration/index.ts <- Config migration dry-run/write support
hooks/index.ts <- Local hook planning/install for the same CI gate
history/index.ts <- Local finding history under .codebase-intelligence/
explain/index.ts <- Rule explanation surface
mcp/index.ts <- 29 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 @@ -87,7 +98,7 @@ analyzeGraph(builtGraph, parsedFiles)
}

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

runOperation(operation, codebaseGraph, input, context)
-> { ok: true, data } | { ok: false, error, data? }
Expand All @@ -106,6 +117,8 @@ runOperation(operation, codebaseGraph, input, context)
- **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.
- **Architecture boundaries**: `boundaries` / `check_boundaries` evaluates graph import edges against preset or custom zones and directed allow/forbid rules. The `no-boundary-violations` check rule reuses the same analyzer so CLI, MCP, and CI emit one stable finding shape.
- **CI + agent ergonomics**: `ci` wraps `check`, `changes`, and health into one PR-friendly contract with SARIF, annotations, PR markdown, compact summaries, baseline filtering, production filtering, and local finding history. `doctor` is read-only and emits exact fix commands for local, CI, MCP, and agent setup.
- **Depth + ecosystem surfaces**: `hotspots`/`file`/`health` expose cognitive complexity alongside cyclomatic complexity. `owners`, `architecture`, `lsp`, `workspaces`, `watch`, `migrate-config`, `hooks`, `history`, and `explain` are read-only/advisory surfaces for 2.5.0 ergonomics and hardening.
- **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
121 changes: 115 additions & 6 deletions docs/cli-reference.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# CLI Reference

24 commands for terminal and CI use. The 22 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.
35 commands for terminal and CI use. Graph-backed analysis commands have MCP parity and auto-cache the index to `.codebase-intelligence/`; workflow commands cover `check`, `ci`, `doctor`, local hooks/history, config migration, and 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`, `risk`, `escape_velocity`.
**Metrics:** `coupling` (default), `pagerank`, `fan_in`, `fan_out`, `betweenness`, `tension`, `churn`, `complexity`, `cognitive_complexity`, `blast_radius`, `coverage`, `risk`, `escape_velocity`.

### file

Expand Down Expand Up @@ -238,23 +238,132 @@ codebase-intelligence clusters <path> [--min-files <n>] [--json] [--force]

**Output:** clusters with files, file count, cohesion.

### owners

Group ownership and bus-factor risk.

```bash
codebase-intelligence owners <path> [--group-by owner|package|directory] [--effort <n>] [--json] [--force]
```

**Output:** files, groups, hotspots, owner/package/directory keys, bus-factor, churn, risk score, and evidence.

### architecture

Rank extraction, seam, tension, and locality recommendations.

```bash
codebase-intelligence architecture <path> [--json] [--force]
```

**Output:** recommendations with stable IDs, kind, title, effort, score, affected files, evidence, and contextPack commands.

### workspaces

Detect package scopes, changed workspaces, and cross-package cycles.

```bash
codebase-intelligence workspaces <path> [--base <ref>] [--changed] [--json] [--force]
```

**Output:** workspace name/path/file count, changed flag, per-workspace cycle evidence, cross-package cycle evidence, and summary.

### lsp

Start a minimal advisory LSP server or print a diagnostics snapshot.

```bash
codebase-intelligence lsp <path> [--diagnostics] [--json] [--force]
```

**Output:** diagnostics and hover facts when `--diagnostics` or `--json` is used. Without those flags, the command starts a stdio LSP server with advisory diagnostics and hovers.

### watch

Keep analysis warm while editing.

```bash
codebase-intelligence watch <path> [--once] [--debounce <ms>] [--json] [--force]
```

**Output:** readiness snapshot in `--once`/`--json` mode. Without `--once`, emits debounced change events.

### check

Rules-engine gate for CI.

```bash
codebase-intelligence check <path> [--config <path>] [--format <fmt>] [--fail-on <severity>] [--gate <mode>] [--base <ref>] [--quiet] [--summary] [--json] [--force]
codebase-intelligence check <path> [--config <path>] [--format <fmt>] [--fail-on <severity>] [--gate <mode>] [--base <ref>] [--changed-since <ref>] [--diff-file <path>] [--production] [--quiet] [--summary] [--json] [--force]
```

**Formats:** `text` (default), `json`, `sarif`.
**Formats:** `text` (default), `json`, `sarif`, `markdown`, `annotations`, `pr-comment-github`, `pr-comment-gitlab`, `badge`, `codeclimate`, `compact`.

**Fail-on:** `error` (default), `warn`, `never`.

**Gate modes:** `all` (default), `new-only`.

**Output:** pass/warn/fail verdict, findings, suppression ledger, and summary counts. Findings include stable `fingerprint`; cleanup findings may also include `kind`, `confidence`, and `evidence`. Summary counts include `suppressed` and `staleSuppressions`; `--summary` prints those counts when present. Exit code `0` on pass, `1` when the configured gate fails, `2` for invalid config or arguments.
**Output:** pass/warn/fail verdict, findings, suppression ledger, and summary counts. Findings include stable `fingerprint` and advisory `actions[]`; cleanup/security findings may also include `kind`, `confidence`, and `evidence`. Summary counts include `suppressed` and `staleSuppressions`; `--summary` prints those counts when present. Exit code `0` on pass, `1` when the configured gate fails, `2` for invalid config or arguments.

**Rules:** `no-comments` (off by default), `no-boundary-violations` (error when top-level `boundaries` config exists), `no-circular-deps` (error), `no-dead-exports` (warn), `no-stale-suppressions` (warn), plus opt-in cleanup/security gates: `no-dead-files`, `no-unused-types`, `no-unused-members`, `no-unused-deps`, `no-secrets`. Dependency findings are scoped to the nearest `package.json` / workspace manifest and include unused, unlisted, type-only, test-only, and runtime-from-devDependencies drift. `ci-ignore-file`, `ci-ignore-next-line`, and JSDoc `@expected-unused` suppressions are reported as active/stale; JSDoc `@public` protects exported cleanup declarations while `@internal` remains checkable. Configure severities in `codebase-intelligence.json`.

### ci

One PR-friendly quality gate around `check`, `changes`, health, baselines, formats, changed workspaces, and local history.

**Rules:** `no-comments` (off by default), `no-boundary-violations` (error when top-level `boundaries` config exists), `no-circular-deps` (error), `no-dead-exports` (warn), `no-stale-suppressions` (warn), plus opt-in cleanup gates: `no-dead-files`, `no-unused-types`, `no-unused-members`, `no-unused-deps`. Dependency findings are scoped to the nearest `package.json` / workspace manifest and include unused, unlisted, type-only, test-only, and runtime-from-devDependencies drift. `ci-ignore-file`, `ci-ignore-next-line`, and JSDoc `@expected-unused` suppressions are reported as active/stale; JSDoc `@public` protects exported cleanup declarations while `@internal` remains checkable. Configure severities in `codebase-intelligence.json`.
```bash
codebase-intelligence ci <path> [--base <ref>] [--new-only] [--all] [--fail-on error|warn|never] [--min-score <n>] [--max-new <n>] [--baseline <path>] [--format <fmt>] [--output <path>] [--comment markdown] [--summary] [--production] [--changed-since <ref>] [--diff-file <path>] [--changed-workspaces] [--history] [--json] [--force]
```

**Exit codes:** `0` pass, `1` gate failed, `2` invalid config/args, `3` analyzer error.

**Formats:** same as `check`. `--comment markdown` emits a PR-comment-safe markdown envelope. `--changed-workspaces` includes changed workspace and cross-package cycle facts in JSON output. `--history` writes finding fingerprints and counts to `.codebase-intelligence/history.json`.

### doctor

Read-only setup auditor.

```bash
codebase-intelligence doctor [path] [--profile local|ci|agent|mcp] [--agent codex|claude|cursor|generic] [--json]
```

**Output:** status, checks, evidence, exact fix commands, and docs links. Doctor checks runtime, package manager, config schema, graph build, cache path, CLI help, MCP registry, CI workflow, and agent instructions.

### explain

Explain one rule.

```bash
codebase-intelligence explain <rule> [--json]
```

### migrate-config

Dry-run config migration to `codebase-intelligence.json`.

```bash
codebase-intelligence migrate-config <path> [--source <name>] [--write] [--json]
```

Default is dry-run and does not mutate source.

### hooks

Plan or install local hooks that run the same CI gate.

```bash
codebase-intelligence hooks install [path] [--apply] [--command <cmd>] [--json]
codebase-intelligence hooks uninstall [path] [--apply] [--json]
```

Default is dry-run. Use `--apply` to write `.git/hooks/pre-commit`.

### history

Read local finding history.

```bash
codebase-intelligence history [path] [--json]
```

### init

Expand Down
Loading
Loading