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
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ npx codebase-intelligence duplicates ./src --mode mild --min-tokens 30
npx codebase-intelligence impact ./src parseCodebase
npx codebase-intelligence dead-exports ./src --limit 20
npx codebase-intelligence changes ./src --json
npx codebase-intelligence boundaries ./src --preset layered --list --json
```

### MCP (optional)
Expand All @@ -57,7 +58,7 @@ claude mcp add -s user -t stdio codebase-intelligence -- npx -y codebase-intelli

## Features

- **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
- **24 CLI commands** for architecture analysis, dependency impact, duplicate families, focused map/context packs, content drift, health scoring, boundary enforcement, 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[]`)
Expand All @@ -71,7 +72,7 @@ claude mcp add -s user -t stdio codebase-intelligence -- npx -y codebase-intelli
- **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 24 MCP tools, 2 prompts, and 3 resources
- **MCP parity (secondary)** — same analysis and rules gate available as 25 MCP tools, 2 prompts, and 3 resources

## Installation

Expand Down Expand Up @@ -117,6 +118,7 @@ codebase-intelligence <command> <path> [options]
| `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 |
| `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 |
| `check` | Rules-engine gate for CI, including opt-in dead-code and dependency gates |
Expand All @@ -139,6 +141,8 @@ codebase-intelligence <command> <path> [options]
| `--context-budget <n>` | Bound `map` context pack size |
| `--min-score <n>` | Minimum drift score for `drift` findings; minimum health score before `health` exits 1 |
| `--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` |
| `--operation <verb>` | Focus `highways` on one operation verb |
| `--shape <name>` | Focus `highways` on one type/DTO shape |
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)
| 24 tools, 2 prompts, | 23 commands with text + JSON
| 25 tools, 2 prompts, | 24 commands with text + JSON
| 3 resources for LLMs | output for humans and CI
```

Expand All @@ -50,8 +50,9 @@ src/
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
boundaries/ <- Architecture zones, allow/forbid edge rules, and violation evidence
highways/index.ts <- Repeated route convergence + bypass/cowpath/synthesis evidence
mcp/index.ts <- 24 MCP tools for LLM integration
mcp/index.ts <- 25 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 @@ -86,7 +87,7 @@ analyzeGraph(builtGraph, parsedFiles)
}

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

runOperation(operation, codebaseGraph, input, context)
-> { ok: true, data } | { ok: false, error, data? }
Expand All @@ -104,6 +105,7 @@ runOperation(operation, codebaseGraph, input, context)
- **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.
- **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.
- **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
22 changes: 20 additions & 2 deletions docs/cli-reference.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# CLI Reference

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.
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.

## Commands

Expand Down Expand Up @@ -202,6 +202,22 @@ codebase-intelligence health <path> [--score] [--min-score <n>] [--json] [--forc

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

### boundaries

Evaluate architecture boundary zones and import rules.

```bash
codebase-intelligence boundaries <path> [--config <path>] [--preset <preset>] [--list] [--json] [--force]
```

**Presets:** `bulletproof`, `layered`, `hexagonal`, `feature-sliced`.

**Config:** top-level `boundaries.zones[]` defines named areas with `patterns[]` and optional `autoDiscover`; `boundaries.rules[]` defines directed `from -> allow/forbid` import rules. Explicit `--preset` overrides discovered boundary config for ad hoc inspection.

**Output:** resolved zones, rules, checked edge count, unassigned file count, stable boundary violation IDs, `forbidden-edge`, `disallowed-edge`, and `risky-re-export-chain` kinds, source/target files, zones, imported/re-exported symbols, evidence, and advisory actions.

**Exit codes:** `0` when no boundary violations are found; `1` when violations are found; `2` for invalid input.

### highways

Find repeated routes that should converge on one canonical operation path.
Expand Down Expand Up @@ -238,7 +254,7 @@ codebase-intelligence check <path> [--config <path>] [--format <fmt>] [--fail-on

**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.

**Rules:** `no-comments` (off by default), `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`.
**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`.

### init

Expand Down Expand Up @@ -282,6 +298,8 @@ codebase-intelligence init [path] [--agents <list>] [--all] [--skill] [--gitigno
| `--context-budget <n>` | map | Approximate token budget for context pack |
| `--min-score <n>` | drift, health | Minimum drift score to report; minimum health score before exit 1 |
| `--score` | health | Print compact score text |
| `--preset <name>` | boundaries | Preset: bulletproof, layered, hexagonal, feature-sliced |
| `--list` | boundaries | List resolved zones and rules |
| `--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
42 changes: 42 additions & 0 deletions docs/data-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,48 @@ HealthFileResult {
}
```

## Boundaries Result

`boundaries --json` and MCP `check_boundaries` return deterministic architecture-boundary findings. CLI `boundaries` exits `1` when violations exist.

```typescript
BoundariesResult {
preset: "custom" | "none" | "bulletproof" | "layered" | "hexagonal" | "feature-sliced"
zones: Array<{
name: string
patterns: string[]
matchedFiles: string[]
}>
rules: Array<{
from: string
allow?: string[]
forbid?: string[]
}>
violations: BoundaryViolation[]
summary: {
checkedEdges: number
violations: number
unassignedFiles: number
}
verdict: "pass" | "fail"
}

BoundaryViolation {
id: string
kind: "forbidden-edge" | "disallowed-edge" | "risky-re-export-chain"
ruleId: string
source: string
target: string
fromZone: string
toZone: string
symbols: string[]
isTypeOnly: boolean
message: string
evidence: string[]
actions: Array<{ command: string; reason: 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

24 tools available via MCP stdio.
25 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 @@ -219,7 +219,17 @@ Compute a CI-gateable codebase health score.
**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
## 22. check_boundaries

Evaluate architecture boundary zones against import edges.

**Input:** `{ preset?: "bulletproof"|"layered"|"hexagonal"|"feature-sliced", list?: boolean }`
**Returns:** preset, zones, rules, summary, verdict, and violations. Violations include stable IDs, kind (`forbidden-edge`, `disallowed-edge`, `risky-re-export-chain`), source/target files, source/target zones, symbols, evidence, and advisory actions.

**Use when:** Enforcing layering, ports/adapters, feature-sliced imports, or custom zone rules.
**Not for:** General quality gates with suppressions/new-only behavior (use check).

## 23. analyze_highways

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

Expand All @@ -229,7 +239,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).

## 23. get_clusters
## 24. get_clusters

Community-detected clusters of related files.

Expand All @@ -239,14 +249,14 @@ Community-detected clusters of related files.
**Use when:** "What files are related?" "Find natural groupings." Discovering emergent groupings that differ from directory structure.
**Not for:** Directory-based modules (use get_module_structure).

## 23. check
## 25. check

Run the configurable rules engine and gate on findings.

**Input:** `{}` (uses the loaded graph + discovered config)
**Returns:** `{ verdict: "pass"|"warn"|"fail", summary: { error, warn, suppressed, staleSuppressions, rules }, configPath, suppressions[], findings[] }`. Each finding has ruleId, severity, file, line, column, message, fingerprint, optional `kind`, optional `confidence`, optional `evidence[]`, and optional advisory `actions[]` (the tool is read-only — actions are hints, never applied). Each suppression records directive, status, file, line, targetLine, matched rule IDs, and suppressed count.

Rules: `no-comments` (off by default), `no-circular-deps` (error), `no-dead-exports` (warn), `no-stale-suppressions` (warn), and 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 and options in `codebase-intelligence.json` (validated by `schema.json`).
Rules: `no-comments` (off by default), `no-boundary-violations` (error when `boundaries` config exists), `no-circular-deps` (error), `no-dead-exports` (warn), `no-stale-suppressions` (warn), and 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 and options in `codebase-intelligence.json` (validated by `schema.json`).

**Use when:** Linting a codebase or enforcing a CI gate. "What rule violations exist?"
**Not for:** Architecture metrics (use analyze_forces).
Expand Down Expand Up @@ -277,6 +287,7 @@ Rules: `no-comments` (off by default), `no-circular-deps` (error), `no-dead-expo
| "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` |
| "Which imports violate architecture boundaries?" | `check_boundaries` |
| "What should I improve first?" | `find_opportunities` |
| "Find refactoring opportunities." | `find_opportunities` |
| "Where is logic duplicated?" | `find_duplicates` |
Expand Down
Loading
Loading