# Codebase Intelligence — Full Documentation > TypeScript codebase analysis engine — dependency graphs, architectural metrics, MCP + CLI interfaces. --- # Architecture ## Pipeline ``` CLI (commander) | v Parser (TS Compiler API) | extracts: files, exports, 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, cyclomatic/cognitive complexity, blast radius, dead exports, test coverage | produces: ForceAnalysis (tension files, bridges, extraction candidates) v Core (shared computation) | result builders used by MCP, CLI, and operation descriptors |\ | \-> Operation Registry | typed descriptors, input schemas, CLI/MCP adapters, result wrappers, text formatters v MCP (stdio) + CLI | MCP: 29 tools, 2 prompts, 3 resources for LLM agents | CLI: 35 public commands with formatted + JSON output for humans/CI ``` ## Module Map ``` src/ types/index.ts <- ALL interfaces (single source of truth) parser/index.ts <- Parse orchestration + imports/exports/call sites + git churn/test detection parser/type-facts.ts <- Type signatures, parameters, consumed/produced shape facts parser/symbols.ts <- Symbol inventory + symbol cyclomatic/cognitive complexity graph/index.ts <- graphology graph + symbol/type graph + circular dep detection analyzer/index.ts <- All metric computation graph-loader/index.ts <- Shared parse/build/analyze/cache pipeline + progress events core/index.ts <- Shared result computation (MCP + CLI) operations/index.ts <- Analysis operation descriptors + typed input schemas operations/formatters.ts <- Result-object text formatters for CLI commands parser/duplication.ts <- Function-body clone token extraction duplication/index.ts <- Duplicate family detection + trace evidence map/index.ts <- Focused codebase maps + token-bounded context packs drift/ <- Content drift findings, profiles, tokens, and stable evidence boundaries/ <- Architecture zones, allow/forbid edge rules, and violation evidence highways/index.ts <- Repeated route convergence + bypass/cowpath/synthesis evidence health/ <- Health score, maintainability, CRAP, coverage lookup, and risk scoring ci/ <- PR-friendly quality gate over check, changes, health, baselines, history, and workspace scope doctor/ <- Read-only setup auditor for local, CI, MCP, and coding-agent workflows ownership/ <- CODEOWNERS/git/package/directory ownership and bus-factor signals recommendations/ <- Architecture recommendations with effort, evidence, and context commands lsp/ <- Advisory diagnostics/hover facts and minimal stdio LSP server workspaces/ <- Workspace detection, changed-scope summaries, and cross-package cycle evidence watch/ <- Watch readiness snapshots and debounce-aware change reporting migration/ <- Dry-run-first config migration into codebase-intelligence.json hooks/ <- Dry-run-first local hook install/uninstall for the same CI gate history/ <- Local finding-history fingerprints under .codebase-intelligence/ explain/ <- Rule explanations and action hints 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 process/index.ts <- Entry point detection + call chain tracing community/index.ts <- Louvain clustering persistence/index.ts <- Graph export/import to .codebase-intelligence/ persistence/index-dir.ts <- Canonical cache path + legacy .code-visualizer/ migration persistence/cache-key.ts <- Cache signature from HEAD, worktree content, CLI version, parser settings server/graph-store.ts <- Global graph state (shared by CLI + MCP) cli.ts <- Entry point, CLI commands + MCP fallback ``` ## Data Flow ``` loadCodebaseGraph(rootDir) -> cached CodebaseGraph when cache key matches -> otherwise emits progress events through parse/build/analyze/cache parseCodebase(rootDir) -> ParsedFile[] (with churn, cyclomatic/cognitive complexity, test mapping, symbol type facts, duplicate token facts) buildGraph(parsedFiles) -> BuiltGraph { graph: Graph, nodes: GraphNode[], edges: GraphEdge[] } analyzeGraph(builtGraph, parsedFiles) -> CodebaseGraph { nodes, edges, symbolNodes, callEdges, symbolMetrics, fileMetrics, moduleMetrics, forceAnalysis, stats, groups, processes, clusters } runOperation(operation, codebaseGraph, input, context) -> { ok: true, data } | { ok: false, error, data? } ``` ## Key Design Decisions - **graphology**: In-memory graph with O(1) neighbor lookup. PageRank and betweenness computed via graphology-metrics. - **Operation registry foundation**: Analysis operations have typed descriptors in `src/operations/` with operation names, CLI command names, MCP tool names, input schemas, discriminated run results, and result-object text formatters. MCP tool registration and CLI command execution consume those descriptors; CLI JSON remains raw result data plus cache facts. - **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. - **Architecture boundaries**: `boundaries` / `check_boundaries` evaluates graph import edges against preset or custom zones and directed allow/forbid rules. `no-boundary-violations` reuses the same analyzer for CI gating. - **Batch git churn**: Single `git log --all --name-only` call, parsed for all files. Avoids O(n) subprocess spawning. - **Dead export detection**: Cross-references parsed exports against edge symbol lists. May miss `import *` or re-exports. - **Graceful degradation**: Non-git dirs get churn=0, no-test codebases get coverage=false. Never crashes. - **Auto-caching**: CLI commands always cache the graph index to `.codebase-intelligence/`. MCP mode requires `--index` to persist. Legacy `.code-visualizer/` is migrated when canonical cache is absent. - **Cache JSON facts**: Analysis commands with `--json` and `init --json` include top-level `cache`: `cacheDir`, `legacyCacheDir`, `migrated`, `gitignoreUpdated`, `warnings[]`. --- # Data Model All types defined in `src/types/index.ts`. ## Parser Output ```typescript ParsedFile { path: string // Absolute filesystem path relativePath: string // Relative to root (used as graph node ID) loc: number // Lines of code exports: ParsedExport[] // Named exports symbols?: ParsedSymbol[] // Exported/local symbols with type facts imports: ParsedImport[] // Relative imports (external skipped) churn: number // Git commit count (0 if non-git) isTestFile: boolean // Matches *.test.ts / *.spec.ts / __tests__/ testFile?: string // Path to matching test file (for source files) } ParsedExport { name: string // Export name ("default" for default exports) type: "function" | "class" | "variable" | "type" | "interface" | "enum" loc: number // Lines of code for this export isDefault: boolean complexity: number // Cyclomatic complexity (branch count, min 1) cognitiveComplexity?: number // Nesting-aware cognitive complexity typeFacts?: SymbolTypeFacts } ParsedSymbol extends ParsedExport { isExported: boolean } SymbolTypeFacts { signature: string parameters: Array<{ name: string, type: string, optional: boolean, rest: boolean }> returnType?: string typeParameters: Array<{ name: string, constraint?: string, default?: string }> consumes: string[] produces: string[] confidence: "resolved" | "syntax" } ParsedImport { from: string // Raw import path resolvedFrom: string // Resolved relative path (after .js->.ts mapping) symbols: string[] // Imported names (["default"] for default import) isTypeOnly: boolean // import type { X } } ``` ## Graph Structure ```typescript GraphNode { id: string // = relativePath for files, parentFile+name for functions type: "file" | "function" path: string // Display path label: string // File basename or function name loc: number module: string // Top-level directory parentFile?: string // For function nodes: which file owns this } GraphEdge { source: string // Importer file ID target: string // Imported file ID symbols: string[] // What's imported isTypeOnly: boolean // Type-only import weight: number // Edge weight (default 1) } ``` ## Computed Metrics ```typescript FileMetrics { pageRank: number betweenness: number fanIn: number fanOut: number coupling: number // fanOut / (max(fanIn, 1) + fanOut) tension: number // Entropy of multi-module pulls isBridge: boolean // betweenness > 0.1 churn: number // Git commit count hasTests: boolean // Test file exists testFile: string // Path to test file cyclomaticComplexity: number // Avg complexity of exports cognitiveComplexity?: number // Avg nesting-aware complexity of symbols blastRadius: number // Transitive dependent count deadExports: string[] // Unused export names totalExports: number // Named export count used as dead-export denominator isPackageEntrypoint: boolean // package.json exports/main/types/bin point here packageEntrypointReason: string // package.json field/path evidence isTestFile: boolean // Whether this file is a test } ModuleMetrics { path: string files: number loc: number exports: number internalDeps: number externalDeps: number cohesion: number // internalDeps / totalDeps escapeVelocity: number // Extraction readiness dependsOn: string[] dependedBy: string[] } ``` Graph stats include `analysisMode` (`full-program` or `ast-only`), `callGraphPrecision` (`type-resolved` or `syntax-only`), and `fullProgramFileLimit`. In `ast-only` mode, file/import/export/dependency metrics remain available while type-resolved call graph detail is reduced. ## Codebase Map Result `map --json`, MCP `get_codebase_map`, `get_scope_graph`, and `get_context_pack` return deterministic graph/context data with stable IDs. ```typescript CodebaseMapResult { overview: { focus?: string; scope?: string; depth: number; contextBudget: number; totalNodes: number; totalEdges: number; totalEvidence: number } focus?: CodebaseMapNode nodes: CodebaseMapNode[] edges: CodebaseMapEdge[] evidence: CodebaseMapEvidence[] contextPack: CodebaseContextPack summary: string } CodebaseMapNode { id: string kind: "file" | "symbol" | "test" | "scope" label: string file?: string symbol?: string score: number evidenceIds: string[] } CodebaseMapEdge { id: string kind: "calls" | "contains" | "imports" | "tests" from: string to: string label: string weight: number evidenceIds: string[] } CodebaseContextPack { tokenBudget: number tokenEstimate: number rankedFiles: Array<{ path: string; rank: number; reason: string; tokenEstimate: number; evidenceIds: string[] }> rankedSymbols: Array<{ file: string; symbol: string; rank: number; reason: string; tokenEstimate: number; evidenceIds: string[] }> tests: Array<{ path: string; covers: string; rank: number; reason: string; tokenEstimate: number; evidenceIds: string[] }> evidenceIds: string[] nextCommands: string[] } ``` ## 2.5.0 Workflow Result Envelopes ```typescript FindingAction { kind: "remove-comment" | "inspect-boundary" | "inspect-file" | "inspect-symbol" | "run-check" | "review-finding" | "create-baseline" auto_fixable: boolean range?: { start: number; end: number } command?: string reason?: string } CiResult { verdict: "pass" | "fail" exitCode: 0 | 1 base: string newOnly: boolean gates: Array<{ name: string; verdict: "pass" | "warn" | "fail"; summary: string }> check: CheckResult health: HealthResult changes: ChangesResult workspaces?: WorkspacesResult baseline: { path?: string; ignoredFindings: number } } DoctorResult { status: "pass" | "warn" | "fail" profile: "local" | "ci" | "agent" | "mcp" agent: "codex" | "claude" | "cursor" | "generic" checks: Array<{ id: string; level: "pass" | "warn" | "fail"; title: string; evidence: string[]; fix?: string; docs?: string }> } OwnershipResult { groupBy: "owner" | "package" | "directory"; files: Array<{ file: string; owner: string; hasTests: boolean; coverageGap: boolean }>; groups: Array<{ key: string; coverageGaps: number; riskScore: number }>; hotspots: Array } ArchitectureRecommendationsResult { recommendations: Array<{ id: string; effort: "small" | "medium" | "large"; affectedFiles: string[]; evidence: string[]; contextPack: object }> } LspSnapshot { diagnostics: Array; hovers: Array; summary: string } WorkspacesResult { base: string; changedOnly: boolean; workspaces: Array<{ name: string; path: string; files: number; changed: boolean; cycles: string[][]; evidence: string[] }>; crossPackageCycles: string[][]; summary: string } ``` --- # Metrics Reference ## Per-File Metrics | Metric | Range | Description | |--------|-------|-------------| | pageRank | 0-1 | Importance in dependency graph | | betweenness | 0-1 | Bridge frequency between shortest paths | | fanIn | 0-N | Files that import this file | | fanOut | 0-N | Files this file imports | | coupling | 0-1 | fanOut / (max(fanIn, 1) + fanOut) | | tension | 0-1 | Multi-module pull evenness. >0.3 = tension | | isBridge | bool | betweenness > 0.1 | | churn | 0-N | Git commits touching this file | | cyclomaticComplexity | 1-N | Avg complexity of exports | | cognitiveComplexity | 0-N | Avg nesting-aware complexity of symbols | | blastRadius | 0-N | Transitive dependents affected by change | | deadExports | list | Export names not consumed by any import | | totalExports | count | Named exports used as dead-export denominator | | isPackageEntrypoint | bool | True when package.json exports/main/types/bin point at file | | packageEntrypointReason | string | package.json entry evidence for public API confidence | | hasTests | bool | Matching test file exists | ## Module Metrics | Metric | Description | |--------|-------------| | cohesion | internalDeps / totalDeps. 1=fully internal | | escapeVelocity | Extraction readiness. High = few internal deps, many consumers | | verdict | LEAF / COHESIVE / MODERATE / JUNK_DRAWER | ## Force Analysis | Signal | Threshold | Meaning | |--------|-----------|---------| | Tension file | tension > 0.3 | Pulled by 2+ modules equally. Split candidate | | Bridge file | betweenness > 0.05 | Removing disconnects graph. Critical path | | Junk drawer | cohesion < 0.4 | Mostly external deps. Needs restructuring | | Extraction candidate | escapeVelocity >= 0.5 | 0 internal deps, many consumers. Extract to package | ## Risk Trifecta The most dangerous files have: high churn + high coupling + low coverage. --- # MCP Tools Reference 29 tools available via MCP stdio. ## 1. codebase_overview High-level summary. Input: `{ depth?: number }`. Returns: totalFiles, totalFunctions, modules, topDependedFiles, metrics, and analysis mode/call graph precision. ## 2. file_context Detailed file context. Input: `{ filePath: string }`. Returns: exports, imports, dependents, all FileMetrics. ## 3. get_dependents File-level blast radius. Input: `{ filePath: string, depth?: number }`. Returns: direct + transitive dependents, riskLevel. ## 4. find_hotspots Rank files by metric. Input: `{ metric: string, limit?: number }`. Metrics: coupling, pagerank, fan_in, fan_out, betweenness, tension, escape_velocity, churn, complexity, cognitive_complexity, blast_radius, coverage, risk. ## 5. get_module_structure Module architecture. Input: `{ depth?: number }`. Returns: modules with metrics, cross-module deps, circular deps. ## 6. analyze_forces Architectural force analysis. Input: `{ cohesionThreshold?, tensionThreshold?, escapeThreshold? }`. Returns: cohesion verdicts, tension files, bridge files, extraction candidates. ## 7. find_dead_exports Unused exports. Input: `{ module?: string, limit?: number }`. Returns: files with dead exports plus confidence. Package public entrypoints from `exports`, `main`, `types`, and `bin` are low confidence because external consumers may use them. ## 8. find_opportunities Rank code quality and refactoring opportunities. Input: `{ limit?: number }`. Returns: ranked opportunities with priority, confidence, evidence, and suggested commands. ## 9. find_duplicates Duplicate function families. Input: `{ mode?: "strict" | "mild" | "weak", minTokens?: number, skipLocal?: boolean, trace?: string }`. Returns: family IDs, members, token counts, similarity thresholds, and optional trace evidence. ## 10. get_groups Top-level directory groups. Input: `{}`. Returns: groups with rank, files, loc, importance, coupling. ## 11. symbol_context Function/class/method context. Input: `{ name: string }`. Returns: callers, callees, metrics, additive typeFacts when known. ## 12. search Keyword/search shape facts (BM25). Input: `{ query: string, limit?: number }`. Returns: ranked files + symbols with additive typeFacts when known. ## 13. detect_changes Git diff analysis. Input: `{ scope?: "staged" | "unstaged" | "all" }`. Returns: changed files, affected files, risk metrics. ## 14. impact_analysis Symbol-level blast radius. Input: `{ symbol: string }`. Returns: depth-grouped impact levels. ## 15. rename_symbol Reference finder for rename planning. Input: `{ oldName: string, newName: string, dryRun?: boolean }`. Returns: references with confidence. ## 16. get_processes Entry point execution flows. Input: `{ entryPoint?: string, limit?: number }`. Returns: processes with steps and depth. ## 17. get_codebase_map Focused codebase graph. Input: `{ focus?: string, scope?: string, depth?: number, format?: "json" | "markdown" | "dot" | "graphml", contextBudget?: number }`. Returns: overview, focus node, nodes, edges, evidence, contextPack, summary. ## 18. get_scope_graph File/scope/test topology from the same map result. Input: same as `get_codebase_map`. Returns: overview, focus node, file/test/scope nodes, imports/tests edges, evidence, summary. ## 19. get_context_pack Token-bounded context pack from the same map result. Input: same as `get_codebase_map`. Returns: tokenBudget, tokenEstimate, rankedFiles, rankedSymbols, tests, evidenceIds, nextCommands. ## 20. detect_content_drift Content drift. Input: `{ focus?: string, scope?: string, minScore?: number }`. Returns: report-only findings with stable IDs, kind, score, severity, declaredIntent, actualBehavior, evidence, recommendation, actions, and baseline status. ## 21. get_health_score Health score. Input: `{ minScore?: number, score?: boolean }`. Returns: score, minScore, verdict, components, coverage source/counts, per-file maintainabilityIndex, crapScore, riskScore, hotspots, actions, and summary. ## 22. check_boundaries Architecture boundaries. Input: `{ preset?: "bulletproof" | "layered" | "hexagonal" | "feature-sliced", list?: boolean }`. Returns: preset, zones, rules, summary, verdict, and stable violations with kind, source/target files, zones, symbols, evidence, and advisory actions. ## 23. analyze_highways Repeated route convergence. Input: `{ operation?: string, shape?: string, minRoutes?: number, propose?: boolean, trace?: string }`. Returns: bypass/cowpath/synthesis opportunities with route chains, evidence, blast radius, proposed canonical node, optional synthesis proposal, and context pack. ## 24. get_clusters Community-detected file clusters. Input: `{ minFiles?: number }`. Returns: clusters with cohesion. ## 25. get_ownership Ownership and bus-factor grouping. Input: `{ groupBy?: "owner" | "package" | "directory", effort?: number }`. Returns: groups with files, owners, churn, risk, busFactor, and evidence. ## 26. get_architecture_recommendations Rank extraction, seam, tension, and locality recommendations. Input: `{}`. Returns: stable recommendation IDs, effort, score, affected files, evidence, and contextPack commands. ## 27. get_lsp_snapshot Advisory editor facts from the same graph as batch analysis. Input: `{}`. Returns: diagnostics and hover facts for dead exports, circular deps, complexity, and risk. ## 28. get_workspaces Workspace/package scopes. Input: `{ base?: string, changedOnly?: boolean }`. Returns: workspaces with name, path, files, changed, cycles, evidence, crossPackageCycles, and summary. ## 29. check Rules-engine gate. Input: `{}`. Returns: pass/warn/fail verdict, findings, suppression ledger, config path, and summary counts. Findings always include ruleId, severity, file, line, column, message, and fingerprint; cleanup findings may also include kind, confidence, and evidence. Suppressions include directive, active/stale status, file, line, targetLine, ruleIds, and suppressed count. ## Tool Selection Guide | Question | Tool | |----------|------| | What does this codebase look like? | codebase_overview | | 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 (risk) | | 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 | | What can I safely delete? | find_dead_exports | | How are modules organized? | get_module_structure | | What's architecturally wrong? | analyze_forces | | Who calls this function? | symbol_context | | Find files related to X | search | | What changed? | detect_changes | | Find all references to X | rename_symbol | | How does data flow? | get_processes | | What context should I give an LLM for this task? | get_context_pack | | Show a focused codebase graph | get_codebase_map | | Which file names lie about behavior? | detect_content_drift | | Which routes bypass canonical dataflow? | analyze_highways | | What files naturally belong together? | get_clusters | | Who owns this risky scope? | get_ownership | | What architecture cleanup should happen next? | get_architecture_recommendations | | What editor diagnostics match batch analysis? | get_lsp_snapshot | | Which workspaces changed in this PR? | get_workspaces | | What rule violations exist? | check | --- # CLI Reference 35 public commands — 29 MCP-backed analysis tools plus `ci`, `doctor`, `watch`, `migrate-config`, `hooks`, `history`, `explain`, `check`, and `init`. ## Commands ### overview ```bash codebase-intelligence overview [--json] [--force] ``` High-level codebase snapshot: files, functions, modules, dependencies. ### hotspots ```bash codebase-intelligence hotspots [--metric ] [--limit ] [--json] [--force] ``` Rank files by metric. Default: coupling. Available: coupling, pagerank, fan_in, fan_out, betweenness, tension, churn, complexity, cognitive_complexity, blast_radius, coverage, risk, escape_velocity. ### file ```bash codebase-intelligence file [--json] [--force] ``` Detailed file context: exports, imports, dependents, all metrics. ### search ```bash codebase-intelligence search [--limit ] [--json] [--force] ``` BM25 keyword search across files, symbols, and type/shape facts. ### changes ```bash codebase-intelligence changes [--scope ] [--json] [--force] ``` Git diff analysis with risk metrics. Scope: staged, unstaged, all (default). ### dependents ```bash codebase-intelligence dependents [--depth ] [--json] [--force] ``` File-level blast radius: direct + transitive dependents, risk level. ### modules ```bash codebase-intelligence modules [--json] [--force] ``` Module architecture: cohesion, cross-module deps, circular deps. ### forces ```bash codebase-intelligence forces [--cohesion ] [--tension ] [--escape ] [--json] [--force] ``` Architectural force analysis: tension files, bridges, extraction candidates. ### dead-exports ```bash codebase-intelligence dead-exports [--module ] [--limit ] [--json] [--force] ``` Find unused exports across the codebase. ### opportunities ```bash codebase-intelligence opportunities [--limit ] [--json] [--force] ``` Rank code quality and refactoring opportunities with evidence, confidence, and suggested commands. ### duplicates ```bash codebase-intelligence duplicates [--mode ] [--min-tokens ] [--skip-local] [--trace ] [--json] [--force] ``` Detect strict, renamed, and near-miss duplicate function families. ### groups ```bash codebase-intelligence groups [--json] [--force] ``` Top-level directory groups with aggregate metrics. ### symbol ```bash codebase-intelligence symbol [--json] [--force] ``` Function/class context: callers, callees, metrics. ### impact ```bash codebase-intelligence impact [--json] [--force] ``` Symbol-level blast radius with depth-grouped impact levels. ### rename ```bash codebase-intelligence rename [--no-dry-run] [--json] [--force] ``` Find all references for rename planning (read-only by default). ### processes ```bash codebase-intelligence processes [--entry ] [--limit ] [--json] [--force] ``` Entry point execution flows through the call graph. ### map ```bash codebase-intelligence map [--focus ] [--scope ] [--depth ] [--format ] [--context-budget ] [--json] [--force] ``` Focused codebase graph plus token-bounded context pack. Formats: markdown, json, dot, graphml. ### drift ```bash codebase-intelligence drift [--focus ] [--scope ] [--min-score ] [--json] [--force] ``` Report-only content drift findings. Returns stable `drift-*` IDs, drift kind, score/severity, declaredIntent, actualBehavior, evidence, recommendation, advisory actions, and baseline status. ### health ```bash codebase-intelligence health [--score] [--min-score ] [--json] [--force] ``` CI-gateable health score. Returns score/verdict, components, root-local Istanbul or static-test coverage source, per-file maintainabilityIndex, crapScore, riskScore, hotspots, evidence, and actions. Exits 1 when score is below `--min-score`. ### boundaries ```bash codebase-intelligence boundaries [--config ] [--preset ] [--list] [--json] [--force] ``` Evaluate architecture boundary zones and import rules. Presets: bulletproof, layered, hexagonal, feature-sliced. Top-level `boundaries.zones[]` config defines named areas; `boundaries.rules[]` config defines directed `from -> allow/forbid` imports. Returns stable violations for forbidden edges, disallowed edges, and risky re-export chains. Exits 1 when violations exist. ### highways ```bash codebase-intelligence highways [--operation ] [--shape ] [--min-routes ] [--propose] [--trace ] [--json] [--force] ``` Find repeated routes that should converge on one canonical operation path. Returns bypass/cowpath findings with route chains, canonical node, evidence, blast radius, recommendation, and context pack. With `--propose`, no-canonical route groups can return `synthesis` findings with proposed name, file, signature, skeleton, reroute plan, and cycle-safety check. ### clusters ```bash codebase-intelligence clusters [--min-files ] [--json] [--force] ``` Community-detected file clusters (Louvain algorithm). ### owners ```bash codebase-intelligence owners [--group-by owner|package|directory] [--effort ] [--json] [--force] ``` Ownership, package, or directory grouping with bus-factor and risk evidence. ### architecture ```bash codebase-intelligence architecture [--json] [--force] ``` Rank graph-backed extraction, seam, tension, and locality recommendations. ### workspaces ```bash codebase-intelligence workspaces [--base ] [--changed] [--json] [--force] ``` Detect package/workspace scopes, changed workspaces, and cross-package cycle evidence. ### lsp ```bash codebase-intelligence lsp [--diagnostics] [--json] [--force] ``` Start the advisory LSP server, or print diagnostics/hover facts with `--diagnostics`. ### watch ```bash codebase-intelligence watch [--once] [--debounce ] [--json] [--force] ``` Keep analysis warm while editing; use `--once` for CI-safe readiness snapshots. ### ci ```bash codebase-intelligence ci [--base ] [--new-only] [--all] [--fail-on error|warn|never] [--min-score ] [--max-new ] [--baseline ] [--format ] [--output ] [--comment markdown] [--summary] [--production] [--changed-since ] [--diff-file ] [--changed-workspaces] [--history] [--json] [--force] ``` One PR-friendly quality gate around `check`, `changes`, health, baselines, local history, and optional changed-workspace summaries. Exit codes: 0 pass, 1 gate failed, 2 config/usage error, 3 analyzer error. Formats: text, json, sarif, markdown, annotations, pr-comment-github, pr-comment-gitlab, badge, codeclimate, compact. ### doctor ```bash codebase-intelligence doctor [path] [--profile local|ci|agent|mcp] [--agent codex|claude|cursor|generic] [--json] ``` Read-only setup auditor for runtime, package manager, config schema, graph build, cache path, CLI help, MCP registry, CI workflow, and agent instructions. ### explain ```bash codebase-intelligence explain [--json] ``` Explain a rule and safe next actions. ### migrate-config ```bash codebase-intelligence migrate-config [--source ] [--write] [--json] ``` Dry-run-first config migration into `codebase-intelligence.json`. ### hooks ```bash codebase-intelligence hooks install [path] [--apply] [--command ] [--json] codebase-intelligence hooks uninstall [path] [--apply] [--json] ``` Plan or install local hooks that run the same CI gate. Default is dry-run. ### history ```bash codebase-intelligence history [path] [--json] ``` Read local finding-history fingerprints and counts from `.codebase-intelligence/history.json`. ### init ```bash codebase-intelligence init [path] [--agents ] [--all] [--skill] [--gitignore] [--yes] [--json] ``` Set up AI agents to use codebase-intelligence. Writes an idempotent, marked instruction block ("query CI before grep/read") into each selected agent's repo file — `AGENTS.md`, `CLAUDE.md`, `.cursor/rules/codebase-intelligence.mdc`, `.github/copilot-instructions.md`, `GEMINI.md`, `CONVENTIONS.md`. Opt-in: on a TTY it shows an interactive picker (`AGENTS.md` + `CLAUDE.md` preselected); non-interactively (or `--yes`/`--json`) it defaults to those two. `--agents` selects explicitly, `--all` targets every agent, `--skill` also installs the portable skill to `~/.claude/skills/codebase-intelligence/SKILL.md` (never installed otherwise). Only content between the `codebase-intelligence:start`/`:end` markers is ever touched. ### check ```bash codebase-intelligence check [--config ] [--format ] [--fail-on ] [--gate ] [--base ] [--changed-since ] [--diff-file ] [--production] [--quiet] [--summary] [--json] [--force] ``` Rules-engine gate for CI. Formats: text, json, sarif, markdown, annotations, pr-comment-github, pr-comment-gitlab, badge, codeclimate, compact. Fail-on: error, warn, never. Gate modes: all, new-only. Returns pass/warn/fail verdict, findings with advisory `actions[]`, suppression ledger, and summary counts. Built-in rules include no-comments, no-boundary-violations, no-circular-deps, no-dead-exports, no-stale-suppressions, and opt-in no-dead-files, no-unused-types, no-unused-members, no-unused-deps, no-secrets. Dependency findings are scoped to the nearest package/workspace manifest and include unused, unlisted, type-only, test-only, and runtime-from-devDependencies drift. Reports active/stale `ci-ignore-*` and `@expected-unused` suppressions; `@public` protects exported cleanup declarations while `@internal` remains checkable. ## Global Behavior - **Auto-caching**: First run parses and saves index to `.codebase-intelligence/`. Subsequent runs use cache only when HEAD, dirty/untracked file contents under the analyzed path, CLI version, and parser cache settings match. Legacy `.code-visualizer/` is migrated when canonical cache is absent. - **Cache JSON facts**: Analysis commands with `--json` and `init --json` include top-level `cache`: `cacheDir`, `legacyCacheDir`, `migrated`, `gitignoreUpdated`, `warnings[]`. - **Default scanner excludes**: `.git`, `node_modules`, `.codebase-intelligence`, legacy `.code-visualizer`, `.next`, `dist`, `coverage`, `.turbo`, `.cache`, `.worktrees`, and `.claude/worktrees`. - **Monorepo imports**: Root tsconfig path aliases and local package.json package names resolve to source files before graph construction. - **Large repo mode**: Above 1500 TypeScript files, use AST-only extraction to avoid TypeScript program OOM. Override with `CBI_FULL_PROGRAM_FILE_LIMIT`. - **Real-repo verification**: `pnpm verify:cli-real` runs the default matrix. `pnpm verify:cli-real:heavy` sets `CBI_REAL_PROFILE=heavy` and verifies large `/home/ubuntu` repos with minimum file/dependency thresholds. - **Progress**: All progress messages go to stderr. Results go to stdout. - **JSON mode**: `--json` outputs stable JSON schema to stdout. - **Exit codes**: 0 = success, 1 = runtime error, 2 = bad args/usage. - **MCP mode**: `codebase-intelligence ` (no subcommand) starts MCP stdio server. - **MCP operation errors**: Invalid operation inputs return `isError: true` with JSON text `{ "error": "..." }` using the same descriptor validation messages as CLI bad-argument exits.