Skip to content
Back to search

ops-codegraph-tool

Code intelligence CLI — function-level dependency graph across 34 languages, 34-tool MCP server for AI agents, complexity metrics, architecture boundary enforcement, CI quality gates, git diff impact with co-change analysis, hybrid semantic search. Fully local, zero API keys required.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/optave/ops-codegraph-tool with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/optave/ops-codegraph-tool'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/optave--ops-codegraph-tool/badge.svg)](/listings/optave--ops-codegraph-tool)

HTML

<a href="/listings/optave--ops-codegraph-tool"><img src="/api/listings/optave--ops-codegraph-tool/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npm install -g @optave/codegraph
cd your-project
codegraph build        # → .codegraph/graph.db created

That's it. The graph is ready. Now connect your AI agent.

For AI agents (primary use case)

Connect directly via MCP — your agent gets 34 tools to query the graph:

codegraph mcp          # 34-tool MCP server — AI queries the graph directly

Or add codegraph to your agent's instructions (e.g. `CLAUDE.md`):

Before modifying code, always:
1. `codegraph where <name>` — find where the symbol lives
2. `codegraph context <name> -T` — get full context (source, deps, callers)
3. `codegraph fn-impact <name> -T` — check blast radius before editing

After modifying code:
4. `codegraph diff-impact --staged -T` — verify impact before committing

Full agent setup: [AI Agent Guide](docs/guides/ai-agent-guide.md) &middot; [CLAUDE.md template](docs/guides/ai-agent-guide.md#claudemd-template)

For developers

The same graph is available via CLI:

codegraph map          # see most-connected files
codegraph query myFunc # find any function, see callers & callees
codegraph deps src/index.ts  # file-level import/export map

Or install from source:

git clone https://github.com/optave/ops-codegraph-tool.git
cd codegraph && npm install && npm link

> **Dev builds:** Pre-release tarballs are attached to [GitHub Releases](https://github.com/optave/ops-codegraph-tool/releases). Install with `npm install -g <path-to-tarball>`. Note that `npm install -g <tarball-url>` does not work because npm cannot resolve optional platform-specific dependencies from a URL — download the `.tgz` first, then install from the local file.

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,001 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <p align="center">
  2. <img src="https://img.shields.io/badge/codegraph-dependency%20intelligence-blue?style=for-the-badge&logo=graphql&logoColor=white" alt="codegraph" />
  3. </p>
  4. <h1 align="center">codegraph</h1>
  5. <p align="center">
  6. <strong>Give your AI the map before it starts exploring.</strong>
  7. </p>
  8. <p align="center">
  9. <a href="https://www.npmjs.com/package/@optave/codegraph"><img src="https://img.shields.io/npm/v/@optave/codegraph?style=flat-square&logo=npm&logoColor=white&label=npm" alt="npm version" /></a>
  10. <a href="https://github.com/optave/ops-codegraph-tool/blob/main/LICENSE"><img src="https://img.shields.io/github/license/optave/ops-codegraph-tool?style=flat-square&logo=opensourceinitiative&logoColor=white" alt="Apache-2.0 License" /></a>
  11. <a href="https://github.com/optave/ops-codegraph-tool/actions"><img src="https://img.shields.io/github/actions/workflow/status/optave/ops-codegraph-tool/codegraph-impact.yml?style=flat-square&logo=githubactions&logoColor=white&label=CI" alt="CI" /></a>
  12. <img src="https://img.shields.io/badge/node-%3E%3D22.12.0-339933?style=flat-square&logo=node.js&logoColor=white" alt="Node >= 22.12.0" />
  13. </p>
  14. <p align="center">
  15. <a href="#the-problem">The Problem</a> &middot;
  16. <a href="#what-codegraph-does">What It Does</a> &middot;
  17. <a href="#-quick-start">Quick Start</a> &middot;
  18. <a href="#-commands">Commands</a> &middot;
  19. <a href="#-language-support">Languages</a> &middot;
  20. <a href="#-ai-agent-integration-core">AI Integration</a> &middot;
  21. <a href="#-how-it-works">How It Works</a> &middot;
  22. <a href="#-recommended-practices">Practices</a> &middot;
  23. <a href="#-roadmap">Roadmap</a>
  24. </p>
  25. ---
  26. ## The Problem
  27. AI agents face an impossible trade-off. They either spend thousands of tokens reading files to understand a codebase's structure — blowing up their context window until quality degrades — or they assume how things work, and the assumptions are often wrong. Either way, things break. The larger the codebase, the worse it gets.
  28. An agent modifies a function without knowing 9 files import it. It misreads what a helper does and builds logic on top of that misunderstanding. It leaves dead code behind after a refactor. The PR gets opened, and your reviewer — human or automated — flags the same structural issues again and again: _"this breaks 14 callers,"_ _"that function already exists,"_ _"this export is now dead."_ If the reviewer catches it, that's multiple rounds of back-and-forth. If they don't, it can ship to production. Multiply that by every PR, every developer, every repo.
  29. The information to prevent these issues exists — it's in the code itself. But without a structured map, agents lack the context to get it right consistently, reviewers waste cycles on preventable issues, and architecture degrades one unreviewed change at a time.
  30. ## What Codegraph Does
  31. Codegraph builds a function-level dependency graph of your entire codebase — every function, every caller, every dependency — and keeps it current with sub-second incremental rebuilds.
  32. It parses your code with [tree-sitter](https://tree-sitter.github.io/) (native Rust or WASM), stores the graph in SQLite, and exposes it where it matters most:
  33. - **MCP server** — AI agents query the graph directly through 34 tools — one call instead of dozens of `grep`/`find`/`cat` invocations
  34. - **CLI** — developers and agents explore, query, and audit code from the terminal
  35. - **CI gates** — `check` and `manifesto` commands enforce quality thresholds with exit codes
  36. - **Programmatic API** — embed codegraph in your own tools via `npm install`
  37. Instead of an agent editing code without structural context and letting reviewers catch the fallout, it knows _"this function has 14 callers across 9 files"_ before it touches anything. Dead exports, circular dependencies, and boundary violations surface during development — not during review. The result: PRs that need fewer review rounds.
  38. **Free. Open source. Fully local.** Zero network calls, zero telemetry. Your code stays on your machine. When you want deeper intelligence, bring your own LLM provider — your code only goes where you choose to send it.
  39. **Three commands to a queryable graph:**
  40. ```bash
  41. npm install -g @optave/codegraph
  42. cd your-project
  43. codegraph build
  44. ```
  45. No config files, no Docker, no JVM, no API keys, no accounts. Point your agent at the MCP server and it has structural awareness of your codebase.
  46. ### Why it matters
  47. | | Without codegraph | With codegraph |
  48. |---|---|---|
  49. | **Code review** | Reviewers flag broken callers, dead code, and boundary violations round after round | Structural issues are caught during development — PRs pass review with fewer rounds |
  50. | **AI agents** | Modify `parseConfig()` without knowing 9 files import it — reviewer catches it | `fn-impact parseConfig` shows every caller before the edit — agent fixes it proactively |
  51. | **AI agents** | Leave dead exports and duplicate helpers behind after refactors | Dead code, cycles, and duplicates surface in real time via hooks and MCP queries |
  52. | **AI agents** | Produce code that works but doesn't fit the codebase structure | `context <name> -T` returns source, deps, callers, and tests — the agent writes code that fits |
  53. | **CI pipelines** | Catch test failures but miss structural degradation | `check --staged` fails the build when blast radius or complexity thresholds are exceeded |
  54. | **Developers** | Inherit a codebase and grep for hours to understand what calls what | `context handleAuth -T` gives the same structured view agents use |
  55. | **Architects** | Draw boundary rules that erode within weeks | `manifesto` and `boundaries` enforce architecture rules on every commit |
  56. ### Feature comparison
  57. <sub>Comparison last verified: August 2026 (full re-verification of every linked repo's live README + GitHub API on 2026-08-09). Full analysis: <a href="generated/competitive/COMPETITIVE_ANALYSIS.md">COMPETITIVE_ANALYSIS.md</a></sub>
  58. | Capability | codegraph (this repo) | [code-review-graph](https://github.com/tirth8205/code-review-graph) | [narsil-mcp](https://github.com/postrv/narsil-mcp) | [codegraph (other)¹](https://github.com/colbymchenry/codegraph) | [claude-context](https://github.com/zilliztech/claude-context) | [GitNexus](https://github.com/abhigyanpatwari/GitNexus) |
  59. |---|:---:|:---:|:---:|:---:|:---:|:---:|
  60. | GitHub stars | ![](https://img.shields.io/github/stars/optave/ops-codegraph-tool?style=flat-square&label=%E2%AD%90) | ![](https://img.shields.io/github/stars/tirth8205/code-review-graph?style=flat-square&label=%E2%AD%90) | ![](https://img.shields.io/github/stars/postrv/narsil-mcp?style=flat-square&label=%E2%AD%90) | ![](https://img.shields.io/github/stars/colbymchenry/codegraph?style=flat-square&label=%E2%AD%90) | ![](https://img.shields.io/github/stars/zilliztech/claude-context?style=flat-square&label=%E2%AD%90) | ![](https://img.shields.io/github/stars/abhigyanpatwari/GitNexus?style=flat-square&label=%E2%AD%90) |
  61. | Languages | **34** | 30+ | **32** | 20+ (34 named)² | 17³ | 14 |
  62. | CLI tool | **Yes** (44 commands) | **Yes** | Partial (config/serve only)⁴ | **Yes** | — (MCP + library only) | **Yes** |
  63. | API functionality (embeddable library) | **Yes** | — | — | **Yes** | **Yes** | Partial (HTTP API only)⁵ |
  64. | Dataflow + CFG + AST querying | **Yes** | Call graph only | **Yes** | — | — | PDG opt-in, TS/JS only |
  65. | Interprocedural dataflow (cross-function) | **Yes**⁶ | — | Partial (taint-only)⁷ | — | — | Partial (taint-only, opt-in)⁸ |
  66. | Hybrid search (BM25 + semantic) | **Yes** | **Yes** | **Yes** (local ONNX, no key needed) | Keyword only | **Yes** | **Yes** |
  67. | Git-aware (diff impact, co-change, branch diff) | **All 3** | Partial (co-change unreliable)⁹ | Partial (no co-change/branch-diff) | — | — | Partial (no co-change) |
  68. | Dead code / role classification | **Yes** | **Yes** | **Yes** | — | — | — |
  69. | Code health (complexity metrics) | **Yes** (cognitive, cyclomatic, Halstead, MI) | — | Partial (cyclomatic + cognitive)¹⁰ | — | — | — |
  70. | Incremental rebuilds | **O(changed)** | **O(changed)** | **O(changed)**¹¹ | **O(changed)**¹² | **O(changed)**¹³ | Partial (chunk cache-key)¹⁴ |
  71. | Architecture rules + CI gate | **Yes** | Partial (risk-gate, no boundary rules) | Partial (layer model, no CI gate) | — | — | — |
  72. | Security scanning (SAST / vuln detection) | Intentionally out of scope¹⁵ | — | **Yes** | — | — | Partial (opt-in taint, `--pdg` only) |
  73. | Zero config, `npm install` | **Yes** | — (pip) | **Yes** | **Yes** | No¹⁶ | **Yes** |
  74. | Runtime dependencies (direct packages)¹⁷ | **4** | 7 | **0**¹⁸ | 10 | 23¹⁹ | 36 |
  75. | Graph export (GraphML / Neo4j / DOT) | **Yes** | **Yes**²⁰ | Partial²¹ | — | — | — |
  76. | Open source + commercial use | **Yes** (Apache-2.0) | **Yes** (MIT) | **Yes** (Apache-2.0/MIT) | **Yes** (MIT) | **Yes** (MIT) | Non-commercial²² |
  77. <sup>¹ Unrelated tool sharing the name; focuses on AI token reduction via pre-indexed context, not structural analysis or CI gates. ² README says "20+ languages"; architecture docs list 34 across native + fallback grammar tiers. ³ Indexes 17 file extensions by default; AST-aware chunking covers ~10 — the rest fall back to plain text splitting. ⁴ narsil-mcp's CLI only manages config, lists tools, and serves the visualization frontend — no query commands; all graph queries require an MCP client. ⁵ GitNexus's local HTTP API (`gitnexus serve`, port 4747) only serves its own web UI — no importable library package. ⁶ Variable-level vertex model (`arg_in`/`return_out`/`def_use`) stitched across call edges — general-purpose, not just security, across all 34 languages. ⁷ `trace_taint`/`get_typed_taint_flow` cross function calls for security; general dataflow tools (`get_data_flow`, `get_reaching_definitions`) are per-function only. ⁸ Optional `--pdg` index (TS/JS only) adds taint source→sink tracking — security-scoped, not general cross-function flow. ⁹ Per its own README benchmark (2026-08-02), co-change eval returns 0 predicted files on every graded commit — "not yet a usable measurement." ¹⁰ `get_complexity` covers cyclomatic + cognitive complexity only — no Halstead metrics or maintainability index. ¹¹ Added Merkle-tree incremental indexing + watch mode (previously full re-index). ¹² OS-native file watcher reprocesses only changed files (debounced auto-sync); `--force` forces a full rebuild. ¹³ Merkle DAG + per-file MD5 hashing skips unchanged files, but each changed file still round-trips to the embedding provider + vector DB. ¹⁴ Cache-keyed, byte-budgeted chunk dispatch with incremental per-branch updates on checkout — finer than a full reprocess, but not per-file hashing. ¹⁵ Structural understanding, not vulnerability detection — use dedicated SAST tools (Semgrep, CodeQL, Snyk). ¹⁶ Requires an external Milvus vector DB + an embedding provider. A local keyless path exists (self-hosted Milvus + Ollama) but needs two running services; the managed path (Zilliz Cloud + OpenAI/VoyageAI/Gemini) trades that for cost. ¹⁷ Direct runtime deps declared in each project's own manifest (`package.json`/`pyproject.toml`), excluding dev/optional/transitive deps. ¹⁸ Single compiled binary — no separate packages to install. ¹⁹ `mcp` + `core` packages combined — plus the external vector DB + embedding provider noted above. ²⁰ Added GraphML, Neo4j Cypher, Obsidian vault, and SVG export. ²¹ Visualization frontend graph views, plus JSON-LD/N-Quads export for its Code Context Graph — but not GraphML or Neo4j specifically (a repo-wide code search found zero matches for either string); an internal DOT exporter exists (`to_dot()`) but isn't exposed via CLI or MCP. ²² PolyForm Noncommercial 1.0.0 license; separate commercial/enterprise licensing available.</sup>
  78. ### What makes codegraph different
  79. | | Differentiator | In practice |
  80. |---|---|---|
  81. | **🤖** | **AI-first architecture** | 34-tool [MCP server](https://modelcontextprotocol.io/) — agents query the graph directly instead of scraping the filesystem. One call replaces 20+ grep/find/cat invocations |
  82. | **🏷️** | **Role classification** | Every symbol auto-tagged as `entry`/`core`/`utility`/`adapter`/`dead`/`leaf` — agents understand a symbol's architectural role without reading surrounding code |
  83. | **🔬** | **Function-level, not just files** | Traces `handleAuth()` → `validateToken()` → `decryptJWT()` and shows 14 callers across 9 files break if `decryptJWT` changes |
  84. | **⚡** | **Always-fresh graph** | Three-tier change detection: journal (O(changed)) → mtime+size (O(n) stats) → hash (O(changed) reads). Sub-second rebuilds — agents work with current data |
  85. | **💥** | **Git diff impact** | `codegraph diff-impact` shows changed functions, their callers, and full blast radius — enriched with historically coupled files from git co-change analysis. Ships with a GitHub Actions workflow |
  86. | **🌐** | **Multi-language, one graph** | 34 languages in a single graph — JS/TS, Python, Go, Rust, Java, C#, PHP, Ruby, C/C++, Kotlin, Swift, Scala, Bash, HCL, Elixir, Lua, Dart, Zig, Haskell, OCaml, F#, Gleam, Clojure, Julia, R, Erlang, Solidity, Objective-C, CUDA, Groovy, Verilog — agents don't need per-language tools |
  87. | **🧠** | **Hybrid search** | BM25 keyword + semantic embeddings fused via RRF — `hybrid` (default), `semantic`, or `keyword` mode; multi-query via `"auth; token; JWT"` |
  88. | **🔬** | **Dataflow + CFG** | Track how data flows through and between functions — function-level edges (`flows_to`, `returns`, `mutates`), interprocedural variable-level edges (`arg_in`, `return_out`, `def_use`), and intraprocedural control flow graphs — all 34 languages |
  89. | **🔓** | **Fully local, zero cost** | No API keys, no accounts, no network calls. Optionally bring your own LLM provider — your code only goes where you choose |
  90. ---
  91. ## 🚀 Quick Start
  92. ```bash
  93. npm install -g @optave/codegraph
  94. cd your-project
  95. codegraph build # → .codegraph/graph.db created
  96. ```
  97. That's it. The graph is ready. Now connect your AI agent.
  98. ### For AI agents (primary use case)
  99. Connect directly via MCP — your agent gets 34 tools to query the graph:
  100. ```bash
  101. codegraph mcp # 34-tool MCP server — AI queries the graph directly
  102. ```
  103. Or add codegraph to your agent's instructions (e.g. `CLAUDE.md`):
  104. ```markdown
  105. Before modifying code, always:
  106. 1. `codegraph where <name>` — find where the symbol lives
  107. 2. `codegraph context <name> -T` — get full context (source, deps, callers)
  108. 3. `codegraph fn-impact <name> -T` — check blast radius before editing
  109. After modifying code:
  110. 4. `codegraph diff-impact --staged -T` — verify impact before committing
  111. ```
  112. Full agent setup: [AI Agent Guide](docs/guides/ai-agent-guide.md) &middot; [CLAUDE.md template](docs/guides/ai-agent-guide.md#claudemd-template)
  113. ### For developers
  114. The same graph is available via CLI:
  115. ```bash
  116. codegraph map # see most-connected files
  117. codegraph query myFunc # find any function, see callers & callees
  118. codegraph deps src/index.ts # file-level import/export map
  119. ```
  120. Or install from source:
  121. ```bash
  122. git clone https://github.com/optave/ops-codegraph-tool.git
  123. cd codegraph && npm install && npm link
  124. ```
  125. > **Dev builds:** Pre-release tarballs are attached to [GitHub Releases](https://github.com/optave/ops-codegraph-tool/releases). Install with `npm install -g <path-to-tarball>`. Note that `npm install -g <tarball-url>` does not work because npm cannot resolve optional platform-specific dependencies from a URL — download the `.tgz` first, then install from the local file.
  126. ---
  127. ## ✨ Features
  128. | | Feature | Description |
  129. |---|---|---|
  130. | 🤖 | **MCP server** | 34-tool MCP server for AI assistants; single-repo by default, opt-in multi-repo |
  131. | 🎯 | **Deep context** | `context` gives agents source, deps, callers, signature, and tests for a function in one call; `audit --quick` gives structural summaries |
  132. | 🏷️ | **Node role classification** | Every symbol auto-tagged as `entry`/`core`/`utility`/`adapter`/`dead`/`leaf` based on connectivity — agents instantly know architectural role |
  133. | 📦 | **Batch querying** | Accept a list of targets and return all results in one JSON payload — enables multi-agent parallel dispatch |
  134. | 💥 | **Impact analysis** | Trace every file affected by a change (transitive) |
  135. | 🧬 | **Function-level tracing** | Call chains, caller trees, function-level impact, and A→B pathfinding with qualified call resolution |
  136. | 📍 | **Fast lookup** | `where` shows exactly where a symbol is defined and used — minimal, fast |
  137. | 🔍 | **Symbol search** | Find any function, class, or method by name — exact match priority, relevance scoring, `--file` and `--kind` filters |
  138. | 📁 | **File dependencies** | See what a file imports and what imports it |
  139. | 📊 | **Diff impact** | Parse `git diff`, find overlapping functions, trace their callers |
  140. | 🔗 | **Co-change analysis** | Analyze git history for files that always change together — surfaces hidden coupling the static graph can't see; enriches `diff-impact` with historically coupled files |
  141. | 🗺️ | **Module map** | Bird's-eye view of your most-connected files |
  142. | 🏗️ | **Structure & hotspots** | Directory cohesion scores, fan-in/fan-out hotspot detection, module boundaries |
  143. | 🔄 | **Cycle detection** | Find circular dependencies at file or function level |
  144. | 📤 | **Export** | DOT, Mermaid, JSON, GraphML, GraphSON, and Neo4j CSV graph export |
  145. | 🧠 | **Semantic search** | Embeddings-powered natural language search with multi-query RRF ranking |
  146. | 👀 | **Watch mode** | Incrementally update the graph as files change |
  147. | ⚡ | **Always fresh** | Three-tier incremental detection — sub-second rebuilds even on large codebases |
  148. | 🔬 | **Data flow analysis** | Intraprocedural parameter tracking, return consumers, argument flows, and mutation detection — all 34 languages |
  149. | 🧮 | **Complexity metrics** | Cognitive, cyclomatic, nesting depth, Halstead, and Maintainability Index per function |
  150. | 🏘️ | **Community detection** | Leiden clustering to discover natural module boundaries and architectural drift |
  151. | 📜 | **Manifesto rule engine** | Configurable pass/fail rules with warn/fail thresholds for CI gates via `check` (exit code 1 on fail) |
  152. | 👥 | **CODEOWNERS integration** | Map graph nodes to CODEOWNERS entries — see who owns each function, ownership boundaries in `diff-impact` |
  153. | 💾 | **Graph snapshots** | `snapshot save`/`restore` for instant DB backup and rollback — checkpoint before refactoring, restore without rebuilding |
  154. | 🔎 | **Hybrid BM25 + semantic search** | FTS5 keyword search + embedding-based semantic search fused via Reciprocal Rank Fusion — `hybrid`, `semantic`, or `keyword` modes |
  155. | 📄 | **Pagination & NDJSON streaming** | Universal `--limit`/`--offset` pagination on all MCP tools and CLI commands; `--ndjson` for newline-delimited JSON streaming |
  156. | 🔀 | **Branch structural diff** | Compare code structure between two git refs — added/removed/changed symbols with transitive caller impact |
  157. | 🛡️ | **Architecture boundaries** | User-defined dependency rules between modules with onion architecture preset — violations flagged in manifesto and CI |
  158. | ✅ | **CI validation predicates** | `check` command with configurable gates: complexity, blast radius, cycles, boundary violations — exit code 0/1 for CI |
  159. | 📋 | **Composite audit** | Single `audit` command combining explain + impact + health metrics per function — one call instead of 3-4 |
  160. | 🚦 | **Triage queue** | `triage` merges connectivity, hotspots, roles, and complexity into a ranked audit priority queue |
  161. | 🔬 | **Dataflow analysis** | Track how data moves through and between functions — function-level (`flows_to`, `returns`, `mutates`) and interprocedural variable-level edges (`arg_in`, `return_out`, `def_use`) — all 34 languages, included by default, skip with `--no-dataflow` |
  162. | 🧩 | **Control flow graph** | Intraprocedural CFG construction for all 34 languages — `cfg` command with text/DOT/Mermaid output, included by default, skip with `--no-cfg` |
  163. | 🔎 | **AST node querying** | Stored queryable AST nodes (calls, `new`, string, regex, throw, await) — `ast` command with SQL GLOB pattern matching |
  164. | 🧬 | **Expanded node/edge types** | `parameter`, `property`, `constant` node kinds with `parent_id` for sub-declaration queries; `contains`, `parameter_of`, `receiver` edge kinds |
  165. | 📊 | **Exports analysis** | `exports <file>` shows all exported symbols with per-symbol consumers, re-export detection, and counts |
  166. | 📈 | **Interactive viewer** | `codegraph plot` generates an interactive HTML graph viewer with hierarchical/force/radial layouts, complexity overlays, and drill-down |
  167. | 🏷️ | **Stable JSON schema** | `normalizeSymbol` utility ensures consistent 7-field output (name, kind, file, line, endLine, role, fileHash) across all commands |
  168. See [docs/examples](docs/examples) for real-world CLI and MCP usage examples.
  169. ## 📦 Commands
  170. ### Build & Watch
  171. ```bash
  172. codegraph build [dir] # Parse and build the dependency graph
  173. codegraph build --no-incremental # Force full rebuild
  174. codegraph build --dataflow # Extract data flow edges (flows_to, returns, mutates)
  175. codegraph build --engine wasm # Force WASM engine (skip native)
  176. codegraph watch [dir] # Watch for changes, update graph incrementally
  177. ```
  178. ### Query & Explore
  179. ```bash
  180. codegraph query <name> # Find a symbol — shows callers and callees
  181. codegraph deps <file> # File imports/exports
  182. codegraph map # Top 20 most-connected files
  183. codegraph map -n 50 --no-tests # Top 50, excluding test files
  184. codegraph where <name> # Where is a symbol defined and used?
  185. codegraph where --file src/db.js # List symbols, imports, exports for a file
  186. codegraph stats # Graph health: nodes, edges, languages, quality score
  187. codegraph roles # Node role classification (entry, core, utility, adapter, dead, leaf)
  188. codegraph roles --role dead -T # Find dead code (unreferenced, non-exported symbols)
  189. codegraph roles --dynamic # Show dynamic call sink edges (eval, computed-key, unresolved)
  190. codegraph roles --role core --file src/ # Core symbols in src/
  191. codegraph exports src/queries.js # Per-symbol consumer analysis (who calls each export)
  192. codegraph children <name> # List parameters, properties, constants of a symbol
  193. ```
  194. ### Deep Context (designed for AI agents)
  195. ```bash
  196. codegraph context <name> # Full context: source, deps, callers, signature, tests
  197. codegraph context <name> --depth 2 --no-tests # Include callee source 2 levels deep
  198. codegraph brief <file> # Token-efficient file summary: symbols, roles, risk tiers
  199. codegraph audit <file> --quick # Structural summary: public API, internals, data flow
  200. codegraph audit <function> --quick # Function summary: signature, calls, callers, tests
  201. ```
  202. ### Impact Analysis
  203. ```bash
  204. codegraph impact <file> # Transitive reverse dependency trace
  205. codegraph query <name> # Function-level: callers, callees, call chain
  206. codegraph query <name> --no-tests --depth 5
  207. codegraph fn-impact <name> # What functions break if this one changes
  208. codegraph path <from> <to> # Shortest path between two symbols (A calls...calls B)
  209. codegraph path <from> <to> --reverse # Follow edges backward
  210. codegraph path <from> <to> --depth 5 --kinds calls,imports
  211. codegraph diff-impact # Impact of unstaged git changes
  212. codegraph diff-impact --staged # Impact of staged changes
  213. codegraph diff-impact HEAD~3 # Impact vs a specific ref
  214. codegraph diff-impact main --format mermaid -T # Mermaid flowchart of blast radius
  215. codegraph branch-compare main feature-branch # Structural diff between two refs
  216. codegraph branch-compare main HEAD --no-tests # Symbols added/removed/changed vs main
  217. codegraph branch-compare v2.4.0 v2.5.0 --json # JSON output for programmatic use
  218. codegraph branch-compare main HEAD --format mermaid # Mermaid diagram of structural changes
  219. ```
  220. ### Co-Change Analysis
  221. Analyze git history to find files that always change together — surfaces hidden coupling the static graph can't see. Requires a git repository.
  222. ```bash
  223. codegraph co-change --analyze # Scan git history and populate co-change data
  224. codegraph co-change src/queries.js # Show co-change partners for a file
  225. codegraph co-change # Show top co-changing file pairs globally
  226. codegraph co-change --since 6m # Limit to last 6 months of history
  227. codegraph co-change --min-jaccard 0.5 # Only show strong coupling (Jaccard >= 0.5)
  228. codegraph co-change --min-support 5 # Minimum co-commit count
  229. codegraph co-change --full # Include all details
  230. ```
  231. Co-change data also enriches `diff-impact` — historically coupled files appear in a `historicallyCoupled` section alongside the static dependency analysis.
  232. ### Structure & Hotspots
  233. ```bash
  234. codegraph structure # Directory overview with cohesion scores
  235. codegraph triage --level file # Files with extreme fan-in, fan-out, or density
  236. codegraph triage --level directory --sort coupling --no-tests
  237. ```
  238. ### Code Health & Architecture
  239. ```bash
  240. codegraph complexity # Per-function cognitive, cyclomatic, nesting, MI
  241. codegraph complexity --health -T # Full Halstead health view (volume, effort, bugs, MI)
  242. codegraph complexity --sort mi -T # Sort by worst maintainability index
  243. codegraph complexity --above-threshold -T # Only functions exceeding warn thresholds
  244. codegraph communities # Leiden community detection — natural module boundaries
  245. codegraph communities --drift -T # Drift analysis only — split/merge candidates
  246. codegraph communities --functions # Function-level community detection
  247. codegraph check # Pass/fail rule engine (exit code 1 on fail)
  248. codegraph check -T # Exclude test files from rule evaluation
  249. ```
  250. ### Dataflow, CFG & AST
  251. ```bash
  252. codegraph dataflow <name> # Data flow edges for a function (flows_to, returns, mutates)
  253. codegraph dataflow <name> --impact # Transitive data-dependent blast radius
  254. codegraph cfg <name> # Control flow graph (text format)
  255. codegraph cfg <name> --format dot # CFG as Graphviz DOT
  256. codegraph cfg <name> --format mermaid # CFG as Mermaid diagram
  257. codegraph ast # List all stored AST nodes
  258. codegraph ast "handleAuth" # Search AST nodes by pattern (GLOB)
  259. codegraph ast -k call # Filter by kind: call, new, string, regex, throw, await
  260. codegraph ast -k throw --file src/ # Combine kind and file filters
  261. ```
  262. > **Note:** Dataflow and CFG are included by default for all 34 languages. Use `--no-dataflow` / `--no-cfg` for faster builds.
  263. ### Audit, Triage & Batch
  264. Composite commands for risk-driven workflows and multi-agent dispatch.
  265. ```bash
  266. codegraph audit <file-or-function> # Combined structural summary + impact + health in one report
  267. codegraph audit <target> --quick # Structural summary only (skip impact and health)
  268. codegraph audit src/queries.js -T # Audit all functions in a file
  269. codegraph explain <target> # Alias for audit — same output, easier to discover
  270. codegraph triage # Ranked audit priority queue (connectivity + hotspots + roles)
  271. codegraph triage -T --limit 20 # Top 20 riskiest functions, excluding tests
  272. codegraph triage --level file -T # File-level hotspot analysis
  273. codegraph triage --level directory -T # Directory-level hotspot analysis
  274. codegraph batch target1 target2 ... # Batch query multiple targets in one call
  275. codegraph batch --json targets.json # Batch from a JSON file
  276. ```
  277. ### CI Validation
  278. `codegraph check` provides configurable pass/fail predicates for CI gates and state machines. Exit code 0 = pass, 1 = fail.
  279. ```bash
  280. codegraph check # Run manifesto rules on whole codebase
  281. codegraph check --staged # Check staged changes (diff predicates)
  282. codegraph check --staged --rules # Run both diff predicates AND manifesto rules
  283. codegraph check --staged --cycles # Fail if staged changes introduce cycles
  284. codegraph check --staged --blast-radius 50 # Fail if blast radius exceeds limit
  285. codegraph check --staged --boundaries # Fail on architecture boundary violations
  286. codegraph check --staged --signatures # Fail if an exported declaration's line was modified
  287. codegraph check main # Check current branch vs main
  288. ```
  289. ### CODEOWNERS
  290. Map graph symbols to CODEOWNERS entries. Shows who owns each function and surfaces ownership boundaries.
  291. ```bash
  292. codegraph owners # Show ownership for all symbols
  293. codegraph owners src/queries.js # Ownership for symbols in a specific file
  294. codegraph owners --boundary # Show ownership boundaries between modules
  295. codegraph owners --owner @backend # Filter by owner
  296. ```
  297. Ownership data also enriches `diff-impact` — affected owners and suggested reviewers appear alongside the static dependency analysis.
  298. ### Snapshots
  299. Lightweight SQLite DB backup and restore — checkpoint before refactoring, instantly rollback without rebuilding.
  300. ```bash
  301. codegraph snapshot save before-refactor # Save a named snapshot
  302. codegraph snapshot list # List all snapshots
  303. codegraph snapshot restore before-refactor # Restore a snapshot
  304. codegraph snapshot delete before-refactor # Delete a snapshot
  305. ```
  306. ### Export & Visualization
  307. ```bash
  308. codegraph export -f dot # Graphviz DOT format
  309. codegraph export -f mermaid # Mermaid diagram
  310. codegraph export -f json # JSON graph
  311. codegraph export -f graphml # GraphML (XML standard)
  312. codegraph export -f graphson # GraphSON (TinkerPop v3 / Gremlin)
  313. codegraph export -f neo4j # Neo4j CSV (bulk import, separate nodes/relationships files)
  314. codegraph export --functions -o graph.dot # Function-level, write to file
  315. codegraph plot # Interactive HTML viewer with force/hierarchical/radial layouts
  316. codegraph cycles # Detect circular dependencies
  317. codegraph cycles --functions # Function-level cycles
  318. ```
  319. ### Semantic Search
  320. Local embeddings for every function, method, and class — search by natural language. Everything runs locally using [@huggingface/transformers](https://huggingface.co/docs/transformers.js) — no API keys needed. Prefer a remote or self-hosted model instead? Set `embeddings.provider: "openai"` and `llm.baseUrl` in your config to call any OpenAI-compatible `/embeddings` endpoint — see [configuration.md](docs/guides/configuration.md#embeddings-embeddings).
  321. ```bash
  322. codegraph embed # Build embeddings (default: nomic)
  323. codegraph embed --model nomic-v1.5 # Use a different model
  324. codegraph search "handle authentication"
  325. codegraph search "parse config" --min-score 0.4 -n 10
  326. codegraph search "parseConfig" --mode keyword # BM25 keyword-only (exact names)
  327. codegraph search "auth flow" --mode semantic # Embedding-only (conceptual)
  328. codegraph search "auth flow" --mode hybrid # BM25 + semantic RRF fusion (default)
  329. codegraph models # List available models
  330. ```
  331. #### Multi-query search
  332. Separate queries with `;` to search from multiple angles at once. Results are ranked using [Reciprocal Rank Fusion (RRF)](https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf) — items that rank highly across multiple queries rise to the top.
  333. ```bash
  334. codegraph search "auth middleware; JWT validation"
  335. codegraph search "parse config; read settings; load env" -n 20
  336. codegraph search "error handling; retry logic" --kind function
  337. codegraph search "database connection; query builder" --rrf-k 30
  338. ```
  339. A single trailing semicolon is ignored (falls back to single-query mode). The `--rrf-k` flag controls the RRF smoothing constant (default 60) — lower values give more weight to top-ranked results.
  340. #### Available Models
  341. Per-model retrieval quality (Hit@N) and timing are measured on every release — see [EMBEDDING-BENCHMARKS.md](generated/benchmarks/EMBEDDING-BENCHMARKS.md).
  342. | Flag | Model | Dimensions | Size | License | Notes |
  343. |---|---|---|---|---|---|
  344. | `minilm` | all-MiniLM-L6-v2 | 384 | ~23 MB | Apache-2.0 | Fastest, good for quick iteration |
  345. | `jina-small` | jina-embeddings-v2-small-en | 512 | ~33 MB | Apache-2.0 | Better quality, still small |
  346. | `jina-base` | jina-embeddings-v2-base-en | 768 | ~137 MB | Apache-2.0 | High quality, 8192 token context |
  347. | `jina-code` | jina-embeddings-v2-base-code | 768 | ~137 MB | Apache-2.0 | Best for code search, trained on code+text |
  348. | `nomic` (default) | nomic-embed-text-v1 | 768 | ~137 MB | Apache-2.0 | Good quality, 8192 context |
  349. | `nomic-v1.5` | nomic-embed-text-v1.5 | 768 | ~137 MB | Apache-2.0 | Matryoshka MRL training (unused — codegraph stores full 768d); v1 scores higher on our benchmark |
  350. | `bge-large` | bge-large-en-v1.5 | 1024 | ~335 MB | MIT | Best general retrieval, top MTEB scores |
  351. | `mxbai-xsmall` | mxbai-embed-xsmall-v1 | 384 | ~50 MB | Apache-2.0 | Tiny + long context (4096) |
  352. | `mxbai-large` | mxbai-embed-large-v1 | 1024 | ~400 MB | Apache-2.0 | Top MTEB BERT-large |
  353. | `bge-m3` | bge-m3 | 1024 | ~600 MB | MIT | **Multilingual** (100+ languages), 8192 context |
  354. | `modernbert` | modernbert-embed-base | 768 | ~150 MB | Apache-2.0 | ModernBERT architecture, 8192 ctx, English |
  355. The model used during `embed` is stored in the database, so `search` auto-detects it — no need to pass `--model` when searching.
  356. ### Multi-Repo Registry
  357. Manage a global registry of codegraph-enabled projects. The registry stores paths to your built graphs so the MCP server can query them when multi-repo mode is enabled.
  358. ```bash
  359. codegraph registry list # List all registered repos
  360. codegraph registry list --json # JSON output
  361. codegraph registry add <dir> # Register a project directory
  362. codegraph registry add <dir> -n my-name # Custom name
  363. codegraph registry remove <name> # Unregister
  364. ```
  365. `codegraph build` auto-registers the project — no manual setup needed.
  366. ### Configuration
  367. Inspect and manage `.codegraphrc.json` settings.
  368. ```bash
  369. codegraph config # Show all config keys with values and sources
  370. codegraph config --json # JSON output of the merged config
  371. codegraph config --init # Scaffold a .codegraphrc.json with all sections pre-populated
  372. codegraph config --edit # Open .codegraphrc.json in $EDITOR
  373. codegraph config --enable-global # Opt this repo into user-level global config
  374. codegraph config --disable-global # Opt this repo out of user-level global config
  375. codegraph config --list-global # Show the contents of the global config file
  376. ```
  377. A user-level config file at `~/.config/codegraph/config.json` (XDG) or `~/.codegraph/config.json` lets you set personal defaults once and apply them to opted-in repos. The merge order is: DEFAULTS → global (if consented) → project → env. Non-interactive contexts (CI, MCP) never apply the global config without explicit consent. See [docs/guides/configuration.md](docs/guides/configuration.md) for full details.
  378. ### Common Flags
  379. | Flag | Description |
  380. |---|---|
  381. | `-d, --db <path>` | Custom path to `graph.db` |
  382. | `-T, --no-tests` | Exclude `.test.`, `.spec.`, `__test__` files (available on most query commands including `query`, `fn-impact`, `path`, `context`, `where`, `diff-impact`, `search`, `map`, `roles`, `co-change`, `deps`, `impact`, `complexity`, `communities`, `branch-compare`, `audit`, `triage`, `check`, `dataflow`, `cfg`, `ast`, `exports`, `children`) |
  383. | `--depth <n>` | Transitive trace depth (default varies by command) |
  384. | `-j, --json` | Output as JSON |
  385. | `-v, --verbose` | Enable debug output |
  386. | `--engine <engine>` | Parser engine: `native`, `wasm`, or `auto` (default: `auto`) |
  387. | `-k, --kind <kind>` | Filter by kind: `function`, `method`, `class`, `interface`, `type`, `struct`, `enum`, `trait`, `record`, `module`, `parameter`, `property`, `constant` |
  388. | `-f, --file <path>` | Scope to a specific file (`fn`, `context`, `where`) |
  389. | `--mode <mode>` | Search mode: `hybrid` (default), `semantic`, or `keyword` (`search`) |
  390. | `--ndjson` | Output as newline-delimited JSON (one object per line) |
  391. | `--table` | Output as auto-column aligned table |
  392. | `--csv` | Output as CSV (RFC 4180, nested objects flattened) |
  393. | `--limit <n>` | Limit number of results |
  394. | `--offset <n>` | Skip first N results (pagination) |
  395. | `--rrf-k <n>` | RRF smoothing constant for multi-query search (default 60) |
  396. | `--user-config [path]` | Apply global user config for this run; optionally specify a custom path instead of the XDG default (`~/.config/codegraph/config.json`) |
  397. | `--no-user-config` | Skip global user config for this run (CI/non-interactive safe) |
  398. ## 🌐 Language Support
  399. | Language | Extensions | Imports | Exports | Call Sites | Heritage¹ | Type Inference² | Dataflow |
  400. |---|---|:---:|:---:|:---:|:---:|:---:|:---:|
  401. | ![JavaScript](https://img.shields.io/badge/-JavaScript-F7DF1E?style=flat-square&logo=javascript&logoColor=black) | `.js`, `.jsx`, `.mjs`, `.cjs` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
  402. | ![TypeScript](https://img.shields.io/badge/-TypeScript-3178C6?style=flat-square&logo=typescript&logoColor=white) | `.ts`, `.tsx`, `.mts`, `.cts` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
  403. | ![Python](https://img.shields.io/badge/-Python-3776AB?style=flat-square&logo=python&logoColor=white) | `.py`, `.pyi` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
  404. | ![Go](https://img.shields.io/badge/-Go-00ADD8?style=flat-square&logo=go&logoColor=white) | `.go` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
  405. | ![Rust](https://img.shields.io/badge/-Rust-000000?style=flat-square&logo=rust&logoColor=white) | `.rs` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
  406. | ![Java](https://img.shields.io/badge/-Java-ED8B00?style=flat-square&logo=openjdk&logoColor=white) | `.java` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
  407. | ![C#](https://img.shields.io/badge/-C%23-512BD4?style=flat-square&logo=dotnet&logoColor=white) | `.cs` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
  408. | ![PHP](https://img.shields.io/badge/-PHP-777BB4?style=flat-square&logo=php&logoColor=white) | `.php`, `.phtml` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
  409. | ![Ruby](https://img.shields.io/badge/-Ruby-CC342D?style=flat-square&logo=ruby&logoColor=white) | `.rb`, `.rake`, `.gemspec` | ✓ | ✓ | ✓ | ✓ | —³ | ✓ |
  410. | ![C](https://img.shields.io/badge/-C-A8B9CC?style=flat-square&logo=c&logoColor=black) | `.c`, `.h` | ✓ | ✓ | ✓ | —⁴ | —⁴ | ✓ |
  411. | ![C++](https://img.shields.io/badge/-C++-00599C?style=flat-square&logo=cplusplus&logoColor=white) | `.cpp`, `.hpp`, `.cc`, `.cxx` | ✓ | ✓ | ✓ | ✓ | — | ✓ |
  412. | ![Kotlin](https://img.shields.io/badge/-Kotlin-7F52FF?style=flat-square&logo=kotlin&logoColor=white) | `.kt`, `.kts` | ✓ | ✓ | ✓ | ✓ | — | ✓ |
  413. | ![Swift](https://img.shields.io/badge/-Swift-F05138?style=flat-square&logo=swift&logoColor=white) | `.swift` | ✓ | ✓ | ✓ | ✓ | — | ✓ |
  414. | ![Scala](https://img.shields.io/badge/-Scala-DC322F?style=flat-square&logo=scala&logoColor=white) | `.scala`, `.sc` | ✓ | ✓ | ✓ | ✓ | — | ✓ |
  415. | ![Bash](https://img.shields.io/badge/-Bash-4EAA25?style=flat-square&logo=gnubash&logoColor=white) | `.sh`, `.bash` | ✓ | ✓ | ✓ | —⁴ | —⁴ | ✓ |
  416. | ![Elixir](https://img.shields.io/badge/-Elixir-4B275F?style=flat-square&logo=elixir&logoColor=white) | `.ex`, `.exs` | ✓ | ✓ | ✓ | — | — | ✓ |
  417. | ![Lua](https://img.shields.io/badge/-Lua-2C2D72?style=flat-square&logo=lua&logoColor=white) | `.lua` | ✓ | ✓ | ✓ | — | — | ✓ |
  418. | ![Dart](https://img.shields.io/badge/-Dart-0175C2?style=flat-square&logo=dart&logoColor=white) | `.dart` | ✓ | ✓ | ✓ | ✓ | — | ✓ |
  419. | ![Zig](https://img.shields.io/badge/-Zig-F7A41D?style=flat-square&logo=zig&logoColor=white) | `.zig` | ✓ | ✓ | ✓ | — | — | ✓ |
  420. | ![Haskell](https://img.shields.io/badge/-Haskell-5D4F85?style=flat-square&logo=haskell&logoColor=white) | `.hs` | ✓ | ✓ | ✓ | — | — | ✓ |
  421. | ![OCaml](https://img.shields.io/badge/-OCaml-EC6813?style=flat-square&logo=ocaml&logoColor=white) | `.ml`, `.mli` | ✓ | ✓ | ✓ | — | — | ✓ |
  422. | ![F#](https://img.shields.io/badge/-F%23-378BBA?style=flat-square&logo=fsharp&logoColor=white) | `.fs`, `.fsx`, `.fsi` | ✓ | ✓ | ✓ | — | — | ✓ |
  423. | ![Gleam](https://img.shields.io/badge/-Gleam-FFAFF3?style=flat-square&logoColor=black) | `.gleam` | ✓ | ✓ | ✓ | — | — | ✓ |
  424. | ![Clojure](https://img.shields.io/badge/-Clojure-5881D8?style=flat-square&logo=clojure&logoColor=white) | `.clj`, `.cljs`, `.cljc` | ✓ | ✓ | ✓ | — | — | ✓ |
  425. | ![Julia](https://img.shields.io/badge/-Julia-9558B2?style=flat-square&logo=julia&logoColor=white) | `.jl` | ✓ | ✓ | ✓ | — | — | ✓ |
  426. | ![R](https://img.shields.io/badge/-R-276DC3?style=flat-square&logo=r&logoColor=white) | `.r`, `.R` | ✓ | ✓ | ✓ | — | — | ✓ |
  427. | ![Erlang](https://img.shields.io/badge/-Erlang-A90533?style=flat-square&logo=erlang&logoColor=white) | `.erl`, `.hrl` | ✓ | ✓ | ✓ | — | — | ✓ |
  428. | ![Solidity](https://img.shields.io/badge/-Solidity-363636?style=flat-square&logo=solidity&logoColor=white) | `.sol` | ✓ | ✓ | ✓ | ✓ | — | ✓ |
  429. | ![Objective-C](https://img.shields.io/badge/-Objective--C-438EFF?style=flat-square&logoColor=white) | `.m` | ✓ | ✓ | ✓ | ✓ | — | ✓ |
  430. | ![CUDA](https://img.shields.io/badge/-CUDA-76B900?style=flat-square&logo=nvidia&logoColor=white) | `.cu`, `.cuh` | ✓ | ✓ | ✓ | ✓ | — | ✓ |
  431. | ![Groovy](https://img.shields.io/badge/-Groovy-4298B8?style=flat-square&logo=apachegroovy&logoColor=white) | `.groovy`, `.gvy` | ✓ | ✓ | ✓ | ✓ | — | ✓ |
  432. | ![Verilog](https://img.shields.io/badge/-Verilog-848484?style=flat-square&logoColor=white) | `.v`, `.sv` | ✓ | ✓ | ✓ | — | — | ✓ |
  433. | ![Terraform](https://img.shields.io/badge/-Terraform-844FBA?style=flat-square&logo=terraform&logoColor=white) | `.tf`, `.hcl` | ✓ | —³ | —³ | —³ | —³ | —³ |
  434. > ¹ **Heritage** = `extends`, `implements`, `include`/`extend` (Ruby), trait `impl` (Rust), receiver methods (Go).
  435. > ² **Type Inference** extracts a per-file type map from annotations (`const x: Router`, `MyType x`, `x: MyType`) and `new` expressions, enabling the edge resolver to connect `x.method()` → `Type.method()`.
  436. > ³ Not applicable — Ruby is dynamically typed; Terraform/HCL is declarative (no functions, classes, or type system).
  437. > ⁴ Not applicable — C and Bash have no class/inheritance system.
  438. > All languages have full **parity** between the native Rust engine and the WASM fallback.
  439. ## ⚙️ How It Works
  440. ```
  441. ┌──────────┐ ┌───────────┐ ┌───────────┐ ┌──────────┐ ┌─────────┐
  442. │ Source │──▶│ tree-sitter│──▶│ Extract │──▶│ Resolve │──▶│ SQLite │
  443. │ Files │ │ Parse │ │ Symbols │ │ Imports │ │ DB │
  444. └──────────┘ └───────────┘ └───────────┘ └──────────┘ └─────────┘
  445. │
  446. ▼
  447. ┌─────────┐
  448. │ Query │
  449. └─────────┘
  450. ```
  451. 1. **Parse** — tree-sitter parses every source file into an AST (native Rust engine or WASM fallback)
  452. 2. **Extract** — Functions, classes, methods, interfaces, imports, exports, call sites, parameters, properties, and constants are extracted
  453. 3. **Resolve** — Imports are resolved to actual files (handles ESM conventions, `tsconfig.json` path aliases, `baseUrl`)
  454. 4. **Store** — Everything goes into SQLite as nodes + edges with tree-sitter node boundaries, plus structural edges (`contains`, `parameter_of`, `receiver`)
  455. 5. **Analyze** (opt-in) — Complexity metrics, control flow graphs (`--cfg`), dataflow edges (`--dataflow`), and AST node storage
  456. 6. **Query** — All queries run locally against the SQLite DB — typically under 100ms
  457. ### Incremental Rebuilds
  458. The graph stays current without re-parsing your entire codebase. Three-tier change detection ensures rebuilds are proportional to what changed, not the size of the project:
  459. 1. **Tier 0 — Journal (O(changed)):** If `codegraph watch` was running, a change journal records exactly which files were touched. The next build reads the journal and only processes those files — zero filesystem scanning
  460. 2. **Tier 1 — mtime+size (O(n) stats, O(changed) reads):** No journal? Codegraph stats every file and compares mtime + size against stored values. Matching files are skipped without reading a single byte
  461. 3. **Tier 2 — Hash (O(changed) reads):** Files that fail the mtime/size check are read and MD5-hashed. Only files whose hash actually changed get re-parsed and re-inserted
  462. **Result:** change one file in a 3,000-file project and the rebuild completes in under a second. Put it in a commit hook, a file watcher, or let your AI agent trigger it.
  463. #### What incremental rebuilds refresh — and what they don't
  464. Incremental builds re-parse changed files and rebuild their edges, structure metrics, and role classifications. But some data is **only fully refreshed on a full rebuild:**
  465. | Data | Incremental | Full rebuild |
  466. |------|:-----------:|:------------:|
  467. | Symbols & edges for changed files | Yes | Yes |
  468. | Reverse-dependency cascade (importers of changed files) | Yes | Yes |
  469. | AST nodes, complexity, CFG, dataflow for changed files | Yes | Yes |
  470. | Directory-level cohesion metrics | Partial (skipped for ≤5 files) | Yes |
  471. | Advisory checks (orphaned embeddings, stale embeddings, unused exports) | Skipped | Yes |
  472. | Build metadata persistence | Skipped for ≤3 files | Yes |
  473. | Incremental drift detection | Skipped | Yes |
  474. **When to run a full rebuild:**
  475. ```bash
  476. codegraph build --no-incremental # Force full rebuild
  477. ```
  478. - **After large refactors** (renames, moves, deleted files) — the reverse-dependency cascade handles most cases, but a full rebuild ensures nothing is stale
  479. - **If you suspect stale analysis data** — complexity or dataflow results for files you didn't directly edit won't update incrementally
  480. - **If `codegraph info` nudges you** — it flags when an interface gained its first instantiated implementor since the last full build, a narrow CHA/RTA dispatch-edge gap incremental rebuilds can't self-heal (see [incremental-builds.md](docs/guides/incremental-builds.md#known-limitation-an-interfaces-first-instantiated-implementor))
  481. - **Periodically** — if you rely heavily on `complexity`, `dataflow`, `roles --role dead`, or `communities` queries, run a full rebuild weekly or after major merges
  482. - **After upgrading codegraph** — engine, schema, or version changes trigger an automatic full rebuild, but if you skip versions you may want to force one
  483. Codegraph auto-detects and forces a full rebuild when the engine, schema version, or codegraph version changes between builds. For everything else, incremental is the safe default — a full rebuild is a correctness guarantee, not a frequent necessity.
  484. > **Detailed guide:** See [docs/guides/incremental-builds.md](docs/guides/incremental-builds.md) for a complete breakdown of what each build mode refreshes and recommended rebuild schedules.
  485. ### Dual Engine
  486. Codegraph ships with two parsing engines:
  487. | Engine | How it works | When it's used |
  488. |--------|-------------|----------------|
  489. | **Native** (Rust) | napi-rs addon built from `crates/codegraph-core/` — parallel multi-core parsing via rayon | Auto-selected when the prebuilt binary is available |
  490. | **WASM** | `web-tree-sitter` with pre-built `.wasm` grammars in `grammars/` | Fallback when the native addon isn't installed |
  491. Both engines produce identical output. Use `--engine native|wasm|auto` to control selection (default: `auto`).
  492. On the native path, Rust handles the entire hot pipeline end-to-end:
  493. | Phase | What Rust does |
  494. |-------|---------------|
  495. | **Parse** | Parallel multi-file tree-sitter parsing via rayon (3.5× faster than WASM) |
  496. | **Extract** | Symbols, imports, calls, classes, type maps, AST nodes — all in one pass |
  497. | **Analyze** | Complexity (cognitive, cyclomatic, Halstead), CFG, and dataflow pre-computed per function during parse |
  498. | **Resolve** | Import resolution with 6-level priority system and confidence scoring |
  499. | **Edges** | Call, receiver, extends, and implements edge inference |
  500. | **DB writes** | All inserts (nodes, edges, AST nodes, complexity, CFG, dataflow) via rusqlite — `better-sqlite3` is lazy-loaded only for the WASM fallback path |
  501. The Rust crate (`crates/codegraph-core/`) exposes a `NativeDatabase` napi-rs class that holds a persistent `rusqlite::Connection` for the full build lifecycle, eliminating JS↔SQLite round-trips on every operation.
  502. ### Call Resolution
  503. Calls are resolved with **qualified resolution** — method calls (`obj.method()`) are distinguished from standalone function calls, and built-in receivers (`console`, `Math`, `JSON`, `Array`, `Promise`, etc.) are filtered out automatically. Import scope is respected: a call to `foo()` only resolves to functions that are actually imported or defined in the same file, eliminating false positives from name collisions.
  504. | Priority | Source | Confidence |
  505. |---|---|---|
  506. | 1 | **Import-aware** — `import { foo } from './bar'` → link to `bar` | `1.0` |
  507. | 2 | **Same-file** — definitions in the current file | `1.0` |
  508. | 3 | **Same directory** — definitions in sibling files (standalone calls only) | `0.7` |
  509. | 4 | **Same parent directory** — definitions in sibling dirs (standalone calls only) | `0.5` |
  510. | 5 | **Method hierarchy** — resolved through `extends`/`implements` | varies |
  511. Method calls on unknown receivers skip global fallback entirely — `stmt.run()` will never resolve to a standalone `run` function in another file. Duplicate caller/callee edges are deduplicated automatically. Dynamic patterns like `fn.call()`, `fn.apply()`, `fn.bind()`, and `obj["method"]()` are also detected on a best-effort basis.
  512. Codegraph also extracts symbols from common callback patterns: Commander `.command().action()` callbacks (as `command:build`), Express route handlers (as `route:GET /api/users`), and event emitter listeners (as `event:data`).
  513. ## 📊 Performance
  514. Self-measured on every release via CI ([build benchmarks](generated/benchmarks/BUILD-BENCHMARKS.md) | [embedding benchmarks](generated/benchmarks/EMBEDDING-BENCHMARKS.md) | [query benchmarks](generated/benchmarks/QUERY-BENCHMARKS.md) | [incremental benchmarks](generated/benchmarks/INCREMENTAL-BENCHMARKS.md) | [resolution precision/recall](tests/benchmarks/resolution/)):
  515. *Last updated: v3.17.0 (2026-08-17)*
  516. | Metric | Native | WASM |
  517. |---|---|---|
  518. | Build speed | **8.2 ms/file** | **26.8 ms/file** |
  519. | Query time | **10ms** | **14ms** |
  520. | No-op rebuild | **30ms** | **30ms** |
  521. | 1-file rebuild | **254ms** | **171ms** |
  522. | Query: fn-deps | **10.1ms** | **13.7ms** |
  523. | Query: path | **14.7ms** | **14.3ms** |
  524. | ~50,000 files (est.) | **~410.0s build** | **~1340.0s build** |
  525. | Resolution precision | **95.2%** | — |
  526. | Resolution recall | **70.3%** | — |
  527. Metrics are normalized per file for cross-version comparability. Times above are for a full initial build — incremental rebuilds only re-parse changed files.
  528. <details><summary>Per-language resolution precision/recall</summary>
  529. | Language | Precision | Recall | TP | FP | FN | Edges | Dynamic |
  530. |----------|----------:|-------:|---:|---:|---:|------:|--------:|
  531. | javascript | 100.0% | 100.0% | 47 | 0 | 0 | 47 | 17/32 |
  532. | typescript | 100.0% | 100.0% | 55 | 0 | 0 | 55 | — |
  533. | bash | 100.0% | 100.0% | 12 | 0 | 0 | 12 | 0/1 |
  534. | c | 100.0% | 100.0% | 9 | 0 | 0 | 9 | 9/9 |
  535. | clojure | 80.0% | 26.7% | 4 | 1 | 11 | 15 | — |
  536. | cpp | 100.0% | 57.1% | 8 | 0 | 6 | 14 | 13/14 |
  537. | csharp | 100.0% | 100.0% | 25 | 0 | 0 | 25 | — |
  538. | cuda | 50.0% | 33.3% | 4 | 4 | 8 | 12 | — |
  539. | dart | 100.0% | 81.0% | 17 | 0 | 4 | 21 | — |
  540. | dynamic-groovy | 100.0% | 100.0% | 1 | 0 | 0 | 1 | — |
  541. | dynamic-java | 100.0% | 100.0% | 1 | 0 | 0 | 1 | — |
  542. | dynamic-javascript | 100.0% | 100.0% | 4 | 0 | 0 | 4 | — |
  543. | dynamic-kotlin | 100.0% | 100.0% | 3 | 0 | 0 | 3 | — |
  544. | dynamic-scala | 100.0% | 100.0% | 1 | 0 | 0 | 1 | — |
  545. | dynamic-typescript | 100.0% | 100.0% | 4 | 0 | 0 | 4 | — |
  546. | elixir | 100.0% | 81.0% | 17 | 0 | 4 | 21 | — |
  547. | erlang | 100.0% | 100.0% | 12 | 0 | 0 | 12 | — |
  548. | fsharp | 0.0% | 0.0% | 0 | 11 | 12 | 12 | — |
  549. | gleam | 100.0% | 26.7% | 4 | 0 | 11 | 15 | — |
  550. | go | 100.0% | 69.2% | 9 | 0 | 4 | 13 | 13/14 |
  551. | groovy | 100.0% | 7.7% | 1 | 0 | 12 | 13 | — |
  552. | haskell | 100.0% | 33.3% | 4 | 0 | 8 | 12 | — |
  553. | hcl | 0.0% | 0.0% | 0 | 0 | 2 | 2 | — |
  554. | java | 100.0% | 81.0% | 17 | 0 | 4 | 21 | — |
  555. | julia | 100.0% | 73.3% | 11 | 0 | 4 | 15 | — |
  556. | kotlin | 92.3% | 63.2% | 12 | 1 | 7 | 19 | — |
  557. | lua | 100.0% | 15.4% | 2 | 0 | 11 | 13 | — |
  558. | objc | 100.0% | 46.2% | 6 | 0 | 7 | 13 | — |
  559. | ocaml | 100.0% | 8.3% | 1 | 0 | 11 | 12 | — |
  560. | php | 100.0% | 65.2% | 15 | 0 | 8 | 23 | — |
  561. | pts-javascript | 100.0% | 100.0% | 15 | 0 | 0 | 15 | — |
  562. | python | 100.0% | 68.4% | 13 | 0 | 6 | 19 | 15/15 |
  563. | r | 100.0% | 100.0% | 11 | 0 | 0 | 11 | — |
  564. | ruby | 100.0% | 100.0% | 11 | 0 | 0 | 11 | 11/11 |
  565. | rust | 100.0% | 100.0% | 24 | 0 | 0 | 24 | 23/23 |
  566. | scala | 100.0% | 100.0% | 7 | 0 | 0 | 7 | — |
  567. | solidity | 33.3% | 7.7% | 1 | 2 | 12 | 13 | — |
  568. | swift | 81.8% | 64.3% | 9 | 2 | 5 | 14 | 9/9 |
  569. | tsx | 100.0% | 100.0% | 13 | 0 | 0 | 13 | — |
  570. | verilog | 0.0% | 0.0% | 0 | 0 | 4 | 4 | — |
  571. | zig | 100.0% | 13.3% | 2 | 0 | 13 | 15 | — |
  572. **By resolution mode (all languages):**
  573. | Mode | Resolved | Expected | Recall |
  574. |------|--------:|---------:|-------:|
  575. | receiver-typed | 47 | 117 | 40.2% |
  576. | module-function | 49 | 115 | 42.6% |
  577. | static | 86 | 97 | 88.7% |
  578. | same-file | 71 | 91 | 78.0% |
  579. | interface-dispatched | 24 | 24 | 100.0% |
  580. | dynamic | 17 | 17 | 100.0% |
  581. | class-inheritance | 12 | 16 | 75.0% |
  582. | callback | 7 | 7 | 100.0% |
  583. | pts-spread | 4 | 4 | 100.0% |
  584. | pts-define-property | 3 | 3 | 100.0% |
  585. | pts-create-prototype | 2 | 2 | 100.0% |
  586. | points-to | 2 | 2 | 100.0% |
  587. | re-export | 2 | 2 | 100.0% |
  588. | pts-for-of | 2 | 2 | 100.0% |
  589. | pts-set | 2 | 2 | 100.0% |
  590. | pts-array-from | 2 | 2 | 100.0% |
  591. | pts-dispatch-table | 2 | 2 | 100.0% |
  592. | trait-dispatch | 2 | 2 | 100.0% |
  593. | define-property | 1 | 1 | 100.0% |
  594. | defineProperty-accessor | 1 | 1 | 100.0% |
  595. | package-function | 1 | 1 | 100.0% |
  596. </details>
  597. ### Lightweight Footprint
  598. <a href="https://www.npmjs.com/package/@optave/codegraph"><img src="https://img.shields.io/npm/unpacked-size/@optave/codegraph?style=flat-square&label=unpacked%20size" alt="npm unpacked size" /></a>
  599. Only **4 runtime dependencies** — everything else is optional or a devDependency:
  600. | Dependency | What it does | | |
  601. |---|---|---|---|
  602. | [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) | SQLite driver (WASM engine; lazy-loaded, not used for native-engine reads) | ![GitHub stars](https://img.shields.io/github/stars/WiseLibs/better-sqlite3?style=flat-square&label=%E2%AD%90) | ![npm downloads](https://img.shields.io/npm/dw/better-sqlite3?style=flat-square&label=%F0%9F%93%A5%2Fwk) |
  603. | [commander](https://github.com/tj/commander.js) | CLI argument parsing | ![GitHub stars](https://img.shields.io/github/stars/tj/commander.js?style=flat-square&label=%E2%AD%90) | ![npm downloads](https://img.shields.io/npm/dw/commander?style=flat-square&label=%F0%9F%93%A5%2Fwk) |
  604. | [smol-toml](https://github.com/squirrelchat/smol-toml) | TOML parsing — reads `Cargo.toml` for Rust `crate::` target overrides and `pyproject.toml` for Python import roots | ![GitHub stars](https://img.shields.io/github/stars/squirrelchat/smol-toml?style=flat-square&label=%E2%AD%90) | ![npm downloads](https://img.shields.io/npm/dw/smol-toml?style=flat-square&label=%F0%9F%93%A5%2Fwk) |
  605. | [web-tree-sitter](https://github.com/tree-sitter/tree-sitter) | WASM tree-sitter bindings | ![GitHub stars](https://img.shields.io/github/stars/tree-sitter/tree-sitter?style=flat-square&label=%E2%AD%90) | ![npm downloads](https://img.shields.io/npm/dw/web-tree-sitter?style=flat-square&label=%F0%9F%93%A5%2Fwk) |
  606. Optional: `@huggingface/transformers` (semantic search), `@modelcontextprotocol/sdk` (MCP server) — lazy-loaded only when needed.
  607. ## 🤖 AI Agent Integration (Core)
  608. ### MCP Server
  609. Codegraph is built around a [Model Context Protocol](https://modelcontextprotocol.io/) server with 34 tools (35 in multi-repo mode) — the primary way agents consume the graph:
  610. ```bash
  611. codegraph mcp # Single-repo mode (default) — only local project
  612. codegraph mcp --multi-repo # Enable access to all registered repos
  613. codegraph mcp --repos a,b # Restrict to specific repos (implies --multi-repo)
  614. ```
  615. **Single-repo mode (default):** Tools operate only on the local `.codegraph/graph.db`. The `repo` parameter and `list_repos` tool are not exposed to the AI agent.
  616. **Multi-repo mode (`--multi-repo`):** All tools gain an optional `repo` parameter to target any registered repository, and `list_repos` becomes available. Use `--repos` to restrict which repos the agent can access.
  617. ### CLAUDE.md / Agent Instructions
  618. Add this to your project's `CLAUDE.md` to help AI agents use codegraph. Full template with all commands in the [AI Agent Guide](docs/guides/ai-agent-guide.md#claudemd-template).
  619. ```markdown
  620. ## Codegraph
  621. This project uses codegraph for dependency analysis. The graph is at `.codegraph/graph.db`.
  622. ### Before modifying code:
  623. 1. `codegraph where <name>` — find where the symbol lives
  624. 2. `codegraph audit --quick <target>` — understand the structure
  625. 3. `codegraph context <name> -T` — get full context (source, deps, callers)
  626. 4. `codegraph fn-impact <name> -T` — check blast radius before editing
  627. ### After modifying code:
  628. 5. `codegraph diff-impact --staged -T` — verify impact before committing
  629. ### Other useful commands
  630. - `codegraph build .` — rebuild graph (incremental by default)
  631. - `codegraph map` — module overview · `codegraph stats` — graph health
  632. - `codegraph query <name> -T` — call chain · `codegraph path <from> <to> -T` — shortest path
  633. - `codegraph deps <file>` — file deps · `codegraph exports <file> -T` — export consumers
  634. - `codegraph audit <target> -T` — full risk report · `codegraph triage -T` — priority queue
  635. - `codegraph check --staged` — CI gate · `codegraph batch t1 t2 -T --json` — batch query
  636. - `codegraph search "<query>"` — semantic search · `codegraph cycles` — cycle detection
  637. - `codegraph roles --role dead -T` — dead code · `codegraph complexity -T` — metrics
  638. - `codegraph dataflow <name> -T` — data flow · `codegraph cfg <name> -T` — control flow
  639. ### Flags
  640. - `-T` — exclude test files (use by default) · `-j` — JSON output
  641. - `-f, --file <path>` — scope to file · `-k, --kind <kind>` — filter kind
  642. ```
  643. ## 📋 Recommended Practices
  644. See **[docs/guides/recommended-practices.md](docs/guides/recommended-practices.md)** for integration guides:
  645. - **Git hooks** — auto-rebuild on commit, impact checks on push, commit message enrichment
  646. - **CI/CD** — PR impact comments, threshold gates, graph caching
  647. - **AI agents** — MCP server, CLAUDE.md templates, Claude Code hooks
  648. - **Developer workflow** — watch mode, explore-before-you-edit, semantic search
  649. - **Secure credentials** — `apiKeyCommand` with 1Password, Bitwarden, Vault, macOS Keychain, `pass`
  650. For AI-specific integration, see the **[AI Agent Guide](docs/guides/ai-agent-guide.md)** — a comprehensive reference covering the 6-step agent workflow, complete command-to-MCP mapping, Claude Code hooks, and token-saving patterns.
  651. ## 🔁 CI / GitHub Actions
  652. Codegraph ships with a ready-to-use GitHub Actions workflow that comments impact analysis on every pull request.
  653. Copy `.github/workflows/codegraph-impact.yml` to your repo, and every PR will get a comment like:
  654. > **3 functions changed** → **12 callers affected** across **7 files**
  655. ## 🛠️ Configuration
  656. Create a `.codegraphrc.json` in your project root to customize behavior. The snippets below cover the most-used keys — see **[docs/guides/configuration.md](docs/guides/configuration.md)** for the full reference (every group, every key, every default).
  657. **Global (user-level) config:** you can also define personal defaults once at `~/.config/codegraph/config.json` and opt individual repos into it with `codegraph config --enable-global`. The global layer merges below the project config so repos always win, and non-interactive contexts (CI, MCP) never apply it without explicit consent. See [docs/guides/configuration.md#user-level-global-configuration](docs/guides/configuration.md#user-level-global-configuration).
  658. ```json
  659. {
  660. "include": ["src/**", "lib/**"],
  661. "exclude": ["**/*.test.js", "**/__mocks__/**"],
  662. "ignoreDirs": ["node_modules", ".git", "dist"],
  663. "ignoreAdditionalDirs": ["crates", "vendor"],
  664. "extensions": [".js", ".ts", ".tsx", ".py"],
  665. "aliases": {
  666. "@/": "./src/",
  667. "@utils/": "./src/utils/"
  668. },
  669. "build": {
  670. "incremental": true
  671. },
  672. "query": {
  673. "excludeTests": true
  674. }
  675. }
  676. ```
  677. > **Tip:** `excludeTests` can also be set at the top level as a shorthand — `{ "excludeTests": true }` is equivalent to nesting it under `query`. If both are present, the nested `query.excludeTests` takes precedence.
  678. ### Manifesto rules
  679. Configure pass/fail thresholds for `codegraph check` (manifesto mode):
  680. ```json
  681. {
  682. "manifesto": {
  683. "rules": {
  684. "cognitive_complexity": { "warn": 15, "fail": 30 },
  685. "cyclomatic_complexity": { "warn": 10, "fail": 20 },
  686. "nesting_depth": { "warn": 4, "fail": 6 },
  687. "maintainability_index": { "warn": 40, "fail": 20 },
  688. "halstead_bugs": { "warn": 0.5, "fail": 1.0 }
  689. }
  690. }
  691. }
  692. ```
  693. When any function exceeds a `fail` threshold, `codegraph check` exits with code 1 — perfect for CI gates.
  694. ### LLM credentials
  695. Codegraph supports an `apiKeyCommand` field for secure credential management. Instead of storing API keys in config files or environment variables, you can shell out to a secret manager at runtime:
  696. ```json
  697. {
  698. "llm": {
  699. "provider": "openai",
  700. "apiKeyCommand": "op read op://vault/openai/api-key"
  701. }
  702. }
  703. ```
  704. The command is split on whitespace and executed with `execFileSync` (no shell injection risk). Priority: **command output > `CODEGRAPH_LLM_API_KEY` env var > file config**. On failure, codegraph warns and falls back to the next source.
  705. Works with any secret manager: 1Password CLI (`op`), Bitwarden (`bw`), `pass`, HashiCorp Vault, macOS Keychain (`security`), AWS Secrets Manager, etc.
  706. ### MCP tool filtering
  707. Codegraph's MCP server exposes 34 tools by default. For models with a small context window, you can shrink the schema by disabling tools you don't use:
  708. ```json
  709. {
  710. "mcp": {
  711. "disabledTools": ["execution_flow", "sequence", "communities", "co_changes"]
  712. }
  713. }
  714. ```
  715. Names are matched case-insensitively and a leading `codegraph<digits>_` prefix (e.g. `codegraph2_module_map`) is stripped before comparison. Disabled tools are removed from `tools/list` and any `tools/call` invocation returns `Unknown tool: <name>`. See **[docs/guides/configuration.md#mcp-tool-filtering](docs/guides/configuration.md#mcp-tool-filtering)** for the full tool catalog, and the rest of that guide for every other config option.
  716. ## 📖 Programmatic API
  717. Codegraph also exports a full API for use in your own tools:
  718. ```js
  719. import { buildGraph, queryNameData, findCycles, exportDOT, normalizeSymbol } from '@optave/codegraph';
  720. // Build the graph
  721. buildGraph('/path/to/project');
  722. // Query programmatically
  723. const results = queryNameData('myFunction', '/path/to/.codegraph/graph.db');
  724. // All query results use normalizeSymbol for a stable 7-field schema
  725. ```
  726. ```js
  727. import { parseFileAuto, getActiveEngine, isNativeAvailable } from '@optave/codegraph';
  728. // Check which engine is active
  729. console.log(getActiveEngine()); // 'native' or 'wasm'
  730. console.log(isNativeAvailable()); // true if Rust addon is installed
  731. // Parse a single file (uses auto-selected engine)
  732. const symbols = await parseFileAuto('/path/to/file.ts');
  733. ```
  734. ```js
  735. import { searchData, multiSearchData, buildEmbeddings } from '@optave/codegraph';
  736. // Build embeddings (one-time)
  737. await buildEmbeddings('/path/to/project');
  738. // Single-query search
  739. const { results } = await searchData('handle auth', dbPath);
  740. // Multi-query search with RRF ranking
  741. const { results: fused } = await multiSearchData(
  742. ['auth middleware', 'JWT validation'],
  743. dbPath,
  744. { limit: 10, minScore: 0.3 }
  745. );
  746. // Each result has: { name, kind, file, line, rrf, queryScores[] }
  747. ```
  748. ## ⚠️ Limitations
  749. - **TypeScript compiler integration is auto-enabled** — when `typescript` is installed and a `tsconfig.json` is found, the TypeScript compiler API pass runs automatically; disable with `"build": { "typescriptResolver": false }` in `.codegraphrc.json` if you want faster builds without it; heuristic type inference (annotations, `new` expressions, assignment chains) is always active as a baseline
  750. - **Dynamic calls are best-effort** — complex computed property access and `eval` patterns are not resolved
  751. - **Dead-code dispatch tables** — object-literal properties on a proven local-closed literal (`const T = { k: fn }; T.k()`) are correlated to that literal's own invocations. Escaping literals (exported, passed as arguments, `this`-using methods, spreads, …) keep the coarser name-based check: any `x.k(...)` in the build still credits `{ k: fn }`. Disable the tighter check with `"analysis": { "correlatedPropertyEvidence": false }`
  752. - **Python imports** — resolves relative imports but doesn't follow `sys.path` or virtual environment packages
  753. - **Dataflow analysis** — interprocedural edges (`arg_in`, `return_out`) require a full build after adding new callee files; incremental re-stitch fires automatically on both the JS and native engine paths
  754. ## 🗺️ Roadmap
  755. See **[ROADMAP.md](docs/roadmap/ROADMAP.md)** for the full development roadmap and **[STABILITY.md](STABILITY.md)** for the stability policy and versioning guarantees. Current plan:
  756. 1. ~~**Rust Core**~~ — **Complete** (v1.3.0) — native tree-sitter parsing via napi-rs, parallel multi-core parsing, incremental re-parsing, import resolution & cycle detection in Rust
  757. 2. ~~**Foundation Hardening**~~ — **Complete** (v1.5.0) — parser registry, complete MCP, test coverage, enhanced config, multi-repo MCP
  758. 3. ~~**Analysis Expansion**~~ — **Complete** (v2.7.0) — complexity metrics, community detection, flow tracing, co-change, manifesto, boundary rules, check, triage, audit, batch, hybrid search
  759. 4. ~~**Deep Analysis & Graph Enrichment**~~ — **Complete** (v3.0.0) — dataflow analysis, intraprocedural CFG, AST node storage, expanded node/edge types, interactive viewer, exports command
  760. 5. ~~**Architectural Refactoring**~~ — **Complete** (v3.1.5) — unified AST analysis, composable MCP, domain errors, builder pipeline, graph model, qualified names, presentation layer, CLI composability
  761. 6. ~~**Resolution Accuracy**~~ — **Complete** (v3.3.1) — type inference, receiver type tracking, dead role sub-categories, resolution benchmarks, `package.json` exports, monorepo workspace resolution
  762. 7. ~~**TypeScript Migration**~~ — **Complete** (v3.4.0) — all 271 source files migrated from JS to TS, zero `.js` remaining
  763. 8. ~~**Native Analysis Acceleration**~~ — **Complete** (v3.5.0) — all build phases in Rust/rusqlite, sub-100ms incremental rebuilds, better-sqlite3 lazy-loaded as fallback only
  764. 9. ~~**Expanded Language Support**~~ — **Complete** (v3.8.0) — 23 new languages in 4 batches (11 → 34), dual-engine WASM + Rust support for all
  765. 10. ~~**Analysis Depth**~~ — **Complete** (v3.12.0) — TypeScript-native resolution, inter-procedural type propagation, field-based points-to analysis, barrel re-export chain resolution, CHA+RTA dynamic dispatch
  766. 11. **Runtime & Extensibility** — event-driven pipeline, plugin system, query caching, pagination
  767. 12. **Quality, Security & Technical Debt** — supply-chain security (SBOM, SLSA), CI coverage gates, timer cleanup, tech debt kill list
  768. 13. **Architectural Health** — split god files (`types.ts`, `dataflow.ts`), missing ADRs, language quality tiers, per-edge confidence transparency
  769. 14. **Intelligent Embeddings** — LLM-generated descriptions, enhanced embeddings, module summaries
  770. 15. **Natural Language Queries** — `codegraph ask` command, conversational sessions
  771. 16. **GitHub Integration & CI** — reusable GitHub Action, LLM-enhanced PR review, SARIF output
  772. 17. **Advanced Features** — dead code detection, monorepo support, agentic search
  773. ## 🤝 Contributing
  774. Contributions are welcome! See **[CONTRIBUTING.md](CONTRIBUTING.md)** for the full guide — setup, workflow, commit convention, testing, and architecture notes.
  775. ```bash
  776. git clone https://github.com/optave/ops-codegraph-tool.git
  777. cd codegraph
  778. npm install
  779. npm test
  780. ```
  781. Looking to add a new language? Check out **[Adding a New Language](docs/contributing/adding-a-language.md)**.
  782. ## 📄 License
  783. [Apache-2.0](LICENSE)
  784. ---
  785. <p align="center">
  786. <sub>Built with <a href="https://tree-sitter.github.io/">tree-sitter</a> and <a href="https://github.com/WiseLibs/better-sqlite3">better-sqlite3</a>. Your code stays on your machine.</sub>
  787. </p>

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.