Skip to content

Latest commit

 

History

History
461 lines (297 loc) · 18.8 KB

File metadata and controls

461 lines (297 loc) · 18.8 KB

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.

codebase-intelligence overview <path> [--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.

codebase-intelligence hotspots <path> [--metric <metric>] [--limit <n>] [--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.

codebase-intelligence file <path> <file> [--json] [--force]

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

codebase-intelligence search <path> <query> [--limit <n>] [--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.

codebase-intelligence changes <path> [--scope <scope>] [--json] [--force]

Scope: staged, unstaged, all (default).

dependents

File-level blast radius: direct + transitive dependents.

codebase-intelligence dependents <path> <file> [--depth <n>] [--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.

codebase-intelligence modules <path> [--json] [--force]

Output: modules with cohesion/escape velocity, cross-module deps, circular deps.

forces

Architectural force analysis.

codebase-intelligence forces <path> [--cohesion <n>] [--tension <n>] [--escape <n>] [--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.

codebase-intelligence dead-exports <path> [--module <module>] [--limit <n>] [--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.

codebase-intelligence opportunities <path> [--limit <n>] [--json] [--force]

Output: ranked opportunities with kind, priority, confidence, score, target, evidence, and suggested follow-up commands.

duplicates

Detect duplicate function families.

codebase-intelligence duplicates <path> [--mode <mode>] [--min-tokens <n>] [--skip-local] [--trace <id>] [--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.

codebase-intelligence groups <path> [--json] [--force]

Output: groups ranked by importance with files, LOC, coupling.

symbol

Function/class context with callers and callees.

codebase-intelligence symbol <path> <name> [--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.

codebase-intelligence impact <path> <symbol> [--json] [--force]

Output: impact levels (WILL BREAK / LIKELY / MAY NEED TESTING), total affected.

rename

Find all references for rename planning (read-only by default).

codebase-intelligence rename <path> <oldName> <newName> [--no-dry-run] [--json] [--force]

Output: references with file, symbol, and confidence level.

processes

Entry point execution flows through the call graph.

codebase-intelligence processes <path> [--entry <name>] [--limit <n>] [--json] [--force]

Output: processes with entry point, steps, depth, modules touched.

map

Focused codebase graph plus token-bounded context pack for agents.

codebase-intelligence map <path> [--focus <symbolOrFile>] [--scope <scope>] [--depth <n>] [--format <format>] [--context-budget <n>] [--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.

codebase-intelligence drift <path> [--focus <fileOrSymbol>] [--scope <scope>] [--min-score <n>] [--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.

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.

boundaries

Evaluate architecture boundary zones and import rules.

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.

codebase-intelligence highways <path> [--operation <verb>] [--shape <name>] [--min-routes <n>] [--propose] [--trace <id>] [--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).

codebase-intelligence clusters <path> [--min-files <n>] [--json] [--force]

Output: clusters with files, file count, cohesion.

owners

Group ownership and bus-factor risk.

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.

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.

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.

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.

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.

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

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.

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.

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

migrate-config

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

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.

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.

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.

codebase-intelligence init [path] [--agents <list>] [--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 <m> hotspots Metric to rank by (default: coupling)
--limit <n> hotspots, search, dead-exports, opportunities, processes Max results
--mode <m> duplicates Clone mode: strict, mild, weak
--min-tokens <n> duplicates Minimum function body token count (default: 30)
--skip-local duplicates Ignore families confined to one file
--trace <id> duplicates, highways Return evidence for one family/opportunity id
--scope <s> changes, map, drift Git diff scope for changes; directory/module scope for map and drift
--depth <n> dependents, map Max traversal depth
--cohesion <n> forces Min cohesion threshold (default: 0.6)
--tension <n> forces Min tension threshold (default: 0.3)
--escape <n> forces Min escape velocity threshold (default: 0.5)
--module <m> dead-exports Filter by module path
--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, 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
--propose highways Include reroute proposal metadata
--min-files <n> clusters Min files per cluster
--no-dry-run rename Actually perform the rename (default: dry run)
--format <fmt> map, check Map export: markdown, json, dot, graphml. Check output: text, json, sarif
--fail-on <severity> check Severity that fails the gate: error, warn, never
--gate <mode> check Gate mode: all, new-only
--base <ref> check Base git ref for new-only gating
--quiet check Suppress output when the result passes
--summary check Print summary counts only
--agents <list> 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:

{
  "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=<n> 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 <path> 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