# CLI Reference 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 ### overview High-level codebase snapshot. ```bash codebase-intelligence overview [--json] [--force] ``` **Output:** file count, function count, dependency count, analysis mode/call graph precision, modules (path, files, LOC, coupling, cohesion), top 5 depended files, avg LOC, max depth, circular dep count. ### hotspots Rank files by metric. ```bash codebase-intelligence hotspots [--metric ] [--limit ] [--json] [--force] ``` **Metrics:** `coupling` (default), `pagerank`, `fan_in`, `fan_out`, `betweenness`, `tension`, `churn`, `complexity`, `cognitive_complexity`, `blast_radius`, `coverage`, `risk`, `escape_velocity`. ### file Detailed file context. ```bash codebase-intelligence file [--json] [--force] ``` `` is relative to the codebase root (e.g., `parser/index.ts`). **Output:** LOC, exports (including additive `typeFacts` when known), imports, dependents, all FileMetrics. Error: prints top 3 similar path suggestions. ### search BM25 keyword search. ```bash codebase-intelligence search [--limit ] [--json] [--force] ``` **Output:** Ranked results grouped by file, with symbol name, type, LOC, relevance score, and additive `typeFacts` when known. Type facts are indexed, so shape names like `CreateUserInput` find producers/consumers. ### changes Git diff analysis with risk metrics. ```bash codebase-intelligence changes [--scope ] [--json] [--force] ``` **Scope:** `staged`, `unstaged`, `all` (default). ### dependents File-level blast radius: direct + transitive dependents. ```bash codebase-intelligence dependents [--depth ] [--json] [--force] ``` **Output:** direct dependents with symbols, transitive dependents with paths, total affected, risk level (LOW/MEDIUM/HIGH). ### modules Module architecture with cross-module dependencies. ```bash codebase-intelligence modules [--json] [--force] ``` **Output:** modules with cohesion/escape velocity, cross-module deps, circular deps. ### forces Architectural force analysis. ```bash codebase-intelligence forces [--cohesion ] [--tension ] [--escape ] [--json] [--force] ``` **Output:** module cohesion verdicts, tension files, bridge files, extraction candidates, shallow modules, deep modules, seam candidates, locality risks, summary. ### dead-exports Find unused exports across the codebase. ```bash codebase-intelligence dead-exports [--module ] [--limit ] [--json] [--force] ``` **Output:** dead export count, files with unused exports, confidence, package-entrypoint evidence, summary. ### opportunities Rank code quality and refactoring opportunities for AI agents. ```bash codebase-intelligence opportunities [--limit ] [--json] [--force] ``` **Output:** ranked opportunities with kind, priority, confidence, score, target, evidence, and suggested follow-up commands. ### duplicates Detect duplicate function families. ```bash codebase-intelligence duplicates [--mode ] [--min-tokens ] [--skip-local] [--trace ] [--json] [--force] ``` **Modes:** `strict` preserves identifiers/literals, `mild` normalizes identifiers/literals for renamed clones, `weak` uses deterministic sequence similarity for near-miss clones. **Output:** duplicate family IDs, member symbols, token counts, similarity threshold/score, and optional trace evidence for one family. ### groups Top-level directory groups with aggregate metrics. ```bash codebase-intelligence groups [--json] [--force] ``` **Output:** groups ranked by importance with files, LOC, coupling. ### symbol Function/class context with callers and callees. ```bash codebase-intelligence symbol [--json] [--force] ``` **Output:** symbol metadata, additive `typeFacts` when known, fan-in/out, PageRank, betweenness, callers, callees. ### impact Symbol-level blast radius with depth-grouped impact levels. ```bash codebase-intelligence impact [--json] [--force] ``` **Output:** impact levels (WILL BREAK / LIKELY / MAY NEED TESTING), total affected. ### rename Find all references for rename planning (read-only by default). ```bash codebase-intelligence rename [--no-dry-run] [--json] [--force] ``` **Output:** references with file, symbol, and confidence level. ### processes Entry point execution flows through the call graph. ```bash codebase-intelligence processes [--entry ] [--limit ] [--json] [--force] ``` **Output:** processes with entry point, steps, depth, modules touched. ### map Focused codebase graph plus token-bounded context pack for agents. ```bash codebase-intelligence map [--focus ] [--scope ] [--depth ] [--format ] [--context-budget ] [--json] [--force] ``` **Formats:** `markdown` (default), `json`, `dot`, `graphml`. **Output:** overview, focus node, nodes, edges, evidence, contextPack (ranked files, symbols, tests, token estimate/budget), and summary. JSON mode includes stable evidence IDs (`evidence-*`) and edge IDs (`edge-*`) for agent-safe references. ### drift Report-only content drift findings for files whose names, folders, side effects, type shapes, or tests no longer match behavior. ```bash codebase-intelligence drift [--focus ] [--scope ] [--min-score ] [--json] [--force] ``` **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 [--score] [--min-score ] [--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. ### boundaries Evaluate architecture boundary zones and import rules. ```bash codebase-intelligence boundaries [--config ] [--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. ```bash codebase-intelligence highways [--operation ] [--shape ] [--min-routes ] [--propose] [--trace ] [--json] [--force] ``` **Output:** route opportunities with `bypass`, `cowpath`, or `synthesis` kind, operation, shape, sink, canonical/proposed node, route chains, bypass routes, duplicated callees when present, evidence, blast radius, recommendation, context pack, and optional synthesis proposal (`name`, `file`, `signature`, `skeleton`, `reroutePlan`, `cycleSafety`). ### clusters Community-detected file clusters (Louvain algorithm). ```bash codebase-intelligence clusters [--min-files ] [--json] [--force] ``` **Output:** clusters with files, file count, cohesion. ### owners Group ownership and bus-factor risk. ```bash codebase-intelligence owners [--group-by owner|package|directory] [--effort ] [--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 [--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 [--base ] [--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 [--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 [--once] [--debounce ] [--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 [--config ] [--format ] [--fail-on ] [--gate ] [--base ] [--changed-since ] [--diff-file ] [--production] [--quiet] [--summary] [--json] [--force] ``` **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` 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. ```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] ``` **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 [--json] ``` ### migrate-config Dry-run config migration to `codebase-intelligence.json`. ```bash codebase-intelligence migrate-config [--source ] [--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 ] [--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 Set up AI agents to use codebase-intelligence by writing a managed instruction block into each selected agent's repo file (`AGENTS.md`, `CLAUDE.md`, `.cursor/rules/codebase-intelligence.mdc`, `.github/copilot-instructions.md`, `GEMINI.md`, `CONVENTIONS.md`) and optionally installing the portable skill to `~/.claude/skills/`. Idempotent — only content between the `codebase-intelligence:start`/`:end` markers is touched. Opt-in by design: on a TTY it shows an interactive picker (`AGENTS.md` + `CLAUDE.md` preselected). Non-interactively (or with `--yes`/`--json`) it defaults to those two. The global skill is never installed unless `--skill` is passed. ```bash codebase-intelligence init [path] [--agents ] [--all] [--skill] [--gitignore] [--yes] [--json] ``` **Output:** per-file actions (created / updated / unchanged), optional `.gitignore` action, skill install status, and cache facts in JSON mode. ## Flags | Flag | Available On | Description | |------|-------------|-------------| | `--json` | All commands | Output stable JSON to stdout | | `--force` | All commands | Re-parse even if cached index matches HEAD | | `--metric ` | hotspots | Metric to rank by (default: coupling) | | `--limit ` | hotspots, search, dead-exports, opportunities, processes | Max results | | `--mode ` | duplicates | Clone mode: strict, mild, weak | | `--min-tokens ` | duplicates | Minimum function body token count (default: 30) | | `--skip-local` | duplicates | Ignore families confined to one file | | `--trace ` | duplicates, highways | Return evidence for one family/opportunity id | | `--scope ` | changes, map, drift | Git diff scope for `changes`; directory/module scope for `map` and `drift` | | `--depth ` | dependents, map | Max traversal depth | | `--cohesion ` | forces | Min cohesion threshold (default: 0.6) | | `--tension ` | forces | Min tension threshold (default: 0.3) | | `--escape ` | forces | Min escape velocity threshold (default: 0.5) | | `--module ` | dead-exports | Filter by module path | | `--entry ` | processes | Filter by entry point name | | `--focus ` | map, drift | Focus on one symbol, file, or scope | | `--context-budget ` | map | Approximate token budget for context pack | | `--min-score ` | drift, health | Minimum drift score to report; minimum health score before exit 1 | | `--score` | health | Print compact score text | | `--preset ` | boundaries | Preset: bulletproof, layered, hexagonal, feature-sliced | | `--list` | boundaries | List resolved zones and rules | | `--operation ` | highways | Focus on one operation verb | | `--shape ` | highways | Focus on one type/DTO shape | | `--min-routes ` | highways | Minimum routes reaching a sink before reporting | | `--propose` | highways | Include reroute proposal metadata | | `--min-files ` | clusters | Min files per cluster | | `--no-dry-run` | rename | Actually perform the rename (default: dry run) | | `--format ` | map, check | Map export: markdown, json, dot, graphml. Check output: text, json, sarif | | `--fail-on ` | check | Severity that fails the gate: error, warn, never | | `--gate ` | check | Gate mode: all, new-only | | `--base ` | check | Base git ref for new-only gating | | `--quiet` | check | Suppress output when the result passes | | `--summary` | check | Print summary counts only | | `--agents ` | init | Comma-separated agents, non-interactive (default: agents,claude) | | `--all` | init | Target every agent (non-interactive) | | `--skill` | init | Also install the global Claude skill (opt-in) | | `--gitignore` | init | Add `.codebase-intelligence/` to `.gitignore` idempotently | | `-y, --yes` | init | Accept defaults without prompting | ## Behavior **Auto-caching:** First CLI invocation parses the codebase and saves the index to `.codebase-intelligence/`. Subsequent commands use the cache only when `git HEAD`, dirty/untracked file contents under the analyzed path, the CLI version, and parser cache settings match. Legacy `.code-visualizer/` is migrated when `.codebase-intelligence/` is absent. Add `.codebase-intelligence/` to `.gitignore` manually or run `codebase-intelligence init --gitignore`. **Cache JSON facts:** Analysis commands with `--json` and `init --json` include a top-level `cache` object: ```json { "cacheDir": "/repo/.codebase-intelligence", "legacyCacheDir": "/repo/.code-visualizer", "migrated": false, "gitignoreUpdated": false, "warnings": [] } ``` **Default scanner excludes:** The parser always skips `.git`, `node_modules`, `.codebase-intelligence`, legacy `.code-visualizer`, `.next`, `dist`, `coverage`, `.turbo`, `.cache`, `.worktrees`, and `.claude/worktrees`, even if the target repo has no matching `.gitignore` entry. **Large repo mode:** Repos above 1500 TypeScript files use a lightweight AST parser by default to avoid TypeScript program OOM. File/import/export/dependency metrics remain available; type-resolved call graph details are reduced. Set `CBI_FULL_PROGRAM_FILE_LIMIT=` to tune the cutoff. **stdout/stderr:** Results go to stdout. Progress messages go to stderr. Safe for piping (`| jq`, `> file.json`). **Exit codes:** - `0` — success - `1` — runtime error (file not found, no TS files, git unavailable) - `2` — bad args or usage error **MCP mode:** Running `codebase-intelligence ` without a subcommand starts the MCP stdio server (backward compatible). MCP-specific flags: - `--index` — persist graph index to `.codebase-intelligence/` (CLI auto-caches, MCP requires this flag) - `--status` — print index status and exit - `--clean` — remove `.codebase-intelligence/` and legacy `.code-visualizer/` indexes and exit - `--force` — re-index even if the cache signature matches