optave/codegraph

GitHub: optave/codegraph

一个本地优先的代码智能 CLI 工具,为代码库构建函数级依赖图,支持 AI agent 集成、CI 质量门和架构边界强制执行。

Stars: 21 | Forks: 1

codegraph

codegraph

在 AI 开始探索之前,先给它一张地图。

npm version Apache-2.0 License CI Node >= 20

问题所在 · 功能介绍 · 快速开始 · 命令 · 语言支持 · AI 集成 · 工作原理 · 最佳实践 · 路线图

## 问题所在 大型代码库是不透明的。其结构存在于人们的脑海中,而不在工具里。 开发者接手一个项目,需要花几天时间使用 grep 来理解什么调用了什么。AI agent 在 `grep`、`find`、`cat` 上消耗了一半的 token 预算——每次会话都在重新发现相同的结构。架构师在白板上绘制边界规则,几周内就会失效,因为没有任何东西强制执行它们。CI pipeline 能捕获测试失败,但无法告诉你_"这次更改悄无声息地影响了 9 个文件中的 14 个调用者"_。 信息就在那里——它就在代码本身中。但如果没有结构化的地图,每个人都在盲目导航:开发者在猜测,AI agent 在产生幻觉,而架构则随着每一次未经审查的更改而退化。 ## Codegraph 的功能 Codegraph 为你的整个代码库构建函数级别的依赖关系图——每个函数、每个调用者、每个依赖项——并通过亚秒级的增量重构保持其最新状态。 它使用 [tree-sitter](https://tree-sitter.github.io/)(原生 Rust 或 WASM)解析你的代码,将图存储在 SQLite 中,并为你提供多种使用方式: - **CLI** —— 开发者从终端探索、查询和审计他们的代码 - **MCP server** —— AI agent 通过 30 个工具直接查询关系图 - **CI gates** —— `check` 和 `manifesto` 命令通过退出代码强制执行质量阈值 - **Programmatic API** —— 通过 `npm install` 将 codegraph 嵌入到你自己的工具中 与其进行 30 次工具调用却可能只发现一半的依赖关系,你可以瞬间获得_"此函数在 9 个文件中有 14 个调用者"_的信息。与其寄希望于架构规则被遵守,不如强制执行它们。与其在生产环境中发现故障,不如通过 `diff-impact --staged` 在提交前捕获它。 **免费。开源。完全本地化。** 零网络调用,零遥测。你的代码保留在你的机器上。当你需要更深入的智能分析时,带上你自己的 LLM provider——你的代码只会去往你选择发送的地方。 **三条命令即可开始:** ``` npm install -g @optave/codegraph cd your-project codegraph build ``` 就是这样。无需配置文件,无需 Docker,无需 JVM,无需 API keys,无需账户。关系图已准备好被查询。 ### 为什么这很重要 | | 没有 codegraph | 拥有 codegraph | |---|---|---| | **AI agents** | 每次会话花费 20+ 次工具调用重新发现代码结构 | 一次 MCP 调用即可获得完整的依赖上下文 | | **AI agents** | 在不知道有 9 个文件导入 `parseConfig()` 的情况下修改它 | `fn-impact parseConfig` 在编辑前显示每个调用者 | | **开发者** | 接手代码库并花费数小时使用 grep 理解调用关系 | `context handleAuth -T` 通过一条命令提供源码、依赖、调用者和测试信息 | | **开发者** | 重命名函数,静默破坏 14 个调用点 | `diff-impact --staged` 在提交前捕获破坏性更改 | | **CI pipelines** | 捕获测试失败但遗漏结构性退化 | 当影响范围或复杂度阈值超标时,`check --staged` 使构建失败 | | **架构师** | 绘制在几周内就会失效的边界规则 | `manifesto` 和 `boundaries` 在每次提交时强制执行架构规则 | ### 功能比较 比较最后验证时间:2026 年 3 月。完整分析:COMPETITIVE_ANALYSIS.md | 能力 | codegraph | [joern](https://github.com/joernio/joern) | [narsil-mcp](https://github.com/postrv/narsil-mcp) | [code-graph-rag](https://github.com/vitali87/code-graph-rag) | [cpg](https://github.com/Fraunhofer-AISEC/cpg) | [GitNexus](https://github.com/abhigyanpatwari/GitNexus) | [CodeMCP](https://github.com/SimplyLiz/CodeMCP) | [axon](https://github.com/harshkedia177/axon) | |---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| | 函数级别分析 | **Yes** | **Yes** | **Yes** | **Yes** | **Yes** | **Yes** | **Yes** | **Yes** | | 多语言支持 | **11** | **14** | **32** | **11** | **~10** | **12** | **12** | **3** | | 语义搜索 | **Yes** | — | **Yes** | **Yes** | — | **Yes** | — | **Yes** | | 混合 BM25 + 语义 | **Yes** | — | — | — | — | **Yes** | — | **Yes** | | CODEOWNERS 集成 | **Yes** | — | — | — | — | — | — | — | | 架构边界规则 | **Yes** | — | — | — | — | — | — | — | | CI 验证断言 | **Yes** | — | — | — | — | — | — | — | | 复合审计命令 | **Yes** | — | — | — | — | — | — | — | | 批量查询 | **Yes** | — | — | — | — | — | — | — | | 图快照 | **Yes** | — | — | — | — | — | — | — | | MCP / AI agent 支持 | **Yes** | — | **Yes** | **Yes** | **Yes** | **Yes** | **Yes** | **Yes** | | Git diff 影响 | **Yes** | — | — | — | — | **Yes** | **Yes** | **Yes** | | 分支结构对比 | **Yes** | — | — | — | — | — | — | **Yes** | | Git 共变分析 | **Yes** | — | — | — | — | — | — | **Yes** | | 监听模式 | **Yes** | — | **Yes** | **Yes** | — | — | **Yes** | **Yes** | | 死代码 / 角色分类 | **Yes** | — | **Yes** | — | — | — | **Yes** | **Yes** | | 循环检测 | **Yes** | — | — | — | — | — | — | — | | 增量重构 | **O(changed)** | — | O(n) Merkle | — | — | — | 仅 Go | **Yes** | | 零配置 | **Yes** | — | **Yes** | — | — | **Yes** | — | **Yes** | | 可嵌入 JS 库 (`npm install`) | **Yes** | — | — | — | — | — | — | — | | 可选 LLM(无需 API keys 即可工作) | **Yes** | **Yes** | **Yes** | **Yes** | **Yes** | **Yes** | **Yes** | **Yes** | | 数据流分析 | **Yes** | **Yes** | — | — | **Yes** | — | — | — | | 控制流图 (CFG) | **Yes** | **Yes** | — | — | **Yes** | — | — | — | | AST 节点查询 | **Yes** | **Yes** | — | — | **Yes** | — | — | — | | 扩展节点/边类型 | **Yes** | **Yes** | — | — | **Yes** | — | — | — | | GraphML / Neo4j 导出 | **Yes** | **Yes** | — | — | — | — | — | — | | 交互式图查看器 | **Yes** | — | — | — | — | — | — | — | | 允许商业用途 | **Yes** | **Yes** | **Yes** | **Yes** | **Yes** | No | 付费 | **Yes** | | 开源 | **Yes** | Yes | Yes | Yes | Yes | No | No | Yes | ### codegraph 的独特之处 | | 差异化优势 | 实际效果 | |---|---|---| | **⚡** | **始终保持最新的关系图** | 三层变更检测:journal (O(changed)) → mtime+size (O(n) stats) → hash (O(changed) reads)。即使在大型代码库上也能实现亚秒级重构 | | **🔓** | **零成本核心,按需 LLM 增强** | 完整的图分析无需 API keys、账户或费用。可选择自带 LLM provider——你的代码只会去往你选择的地方 | | **🔬** | **函数级别,不仅仅是文件** | 追踪 `handleAuth()` → `validateToken()` → `decryptJWT()`,并显示如果 `decryptJWT` 更改,9 个文件中的 14 个调用者将受到影响 | | **🏷️** | **角色分类** | 每个符号自动标记为 `entry`/`core`/`utility`/`adapter`/`dead`/`leaf`——agent 可以立即知道它们正在查看什么 | | **🤖** | **专为 AI agent 打造** | 30 工具 [MCP server](https://modelcontextprotocol.io/)——AI 助手直接查询你的关系图。默认为单仓库模式 | | **🌐** | **多语言,单一 CLI** | 在单个图中支持 JS/TS + Python + Go + Rust + Java + C# + PHP + Ruby + HCL | | **💥** | **Git diff 影响** | `codegraph diff-impact` 显示更改的函数、其调用者以及完整的影响范围——并通过 git 共变分析丰富历史耦合文件。附带 GitHub Actions 工作流 | | **🧠** | **混合搜索** | 通过 RRF 融合 BM25 关键词 + 语义嵌入——支持 `hybrid`(默认)、`semantic` 或 `keyword` 模式;通过 `"auth; token; JWT"` 进行多查询 | | **🔬** | **数据流 + CFG** | 跟踪数据如何在函数间流动(`flows_to`、`returns`、`mutates`),并为所有 11 种语言可视化过程内控制流图 | ## 🚀 快速开始 ``` # 安装 npm install -g @optave/codegraph # 为任何项目构建 graph cd your-project codegraph build # → .codegraph/graph.db created # 开始探索 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 ``` 或从源码安装: ``` git clone https://github.com/optave/codegraph.git cd codegraph && npm install && npm link ``` ### 对于 AI agent 将 codegraph 添加到你的 agent 指令中(例如 `CLAUDE.md`): ``` Before modifying code, always: 1. `codegraph where ` — find where the symbol lives 2. `codegraph context -T` — get full context (source, deps, callers) 3. `codegraph fn-impact -T` — check blast radius before editing After modifying code: 4. `codegraph diff-impact --staged -T` — verify impact before committing ``` 或通过 MCP 直接连接: ``` codegraph mcp # 30-tool MCP server — AI queries the graph directly ``` 完整 agent 设置:[AI Agent 指南](docs/guides/ai-agent-guide.md) · [CLAUDE.md 模板](docs/guides/ai-agent-guide.md#claudemd-template) ## ✨ 功能特性 | | 功能 | 描述 | |---|---|---| | 🔍 | **符号搜索** | 按名称查找任何函数、类或方法——优先精确匹配、相关性评分、`--file` 和 `--kind` 过滤器 | | 📁 | **文件依赖** | 查看文件导入了什么以及什么导入了它 | | 💥 | **影响分析** | 追踪受更改影响的每个文件(传递性) | | 🧬 | **函数级别追踪** | 调用链、调用者树、函数级别影响,以及带有合格调用解析的 A→B 寻路 | | 🎯 | **深度上下文** | `context` 通过一次调用为 AI agent 提供函数的源码、依赖、调用者、签名和测试;`audit --quick` 提供文件或函数的结构摘要 | | 📍 | **快速查找** | `where` 精确显示符号定义和使用的位置——最小化、快速 | | 📊 | **Diff 影响** | 解析 `git diff`,查找重叠函数,追踪其调用者 | | 🔗 | **共变分析** | 分析 git 历史中总是一起更改的文件——揭示静态图无法看到的隐藏耦合;用历史耦合文件丰富 `diff-impact` | | 🗺️ | **模块地图** | 你连接最紧密的文件的鸟瞰图 | | 🏗️ | **结构与热点** | 目录内聚分数、扇入/扇出热点检测、模块边界 | | 🏷️ | **节点角色分类** | 每个符号根据连接模式自动标记为 `entry`/core`/`utility`/`adapter`/`dead`/`leaf`——agent 立即知道架构角色 | | 🔄 | **循环检测** | 在文件或函数级别查找循环依赖 | | 📤 | **导出** | DOT、Mermaid、JSON、GraphML、GraphSON 和 Neo4j CSV 图导出 | | 🧠 | **语义搜索** | 基于嵌入的自然语言搜索,带有多查询 RRF 排序 | | 👀 | **监听模式** | 随文件更改增量更新关系图 | | 🤖 | **MCP server** | 为 AI 助手提供的 30 工具 MCP server;默认为单仓库,可选多仓库 | | ⚡ | **始终保持最新** | 三层增量检测——即使在大型代码库上也能实现亚秒级重构 | | 🧮 | **复杂度指标** | 每个函数的认知、圈、嵌套深度、Halstead 和可维护性指数 | | 🏘️ | **社区检测** | Louvain 聚类用于发现自然模块边界和架构漂移 | | 📜 | **Manifesto 规则引擎** | 可配置的通过/失败规则,通过 `check` 为 CI gates 提供警告/失败阈值(失败时退出代码为 1) | | 👥 | **CODEOWNERS 集成** | 将图节点映射到 CODEOWNERS 条目——查看谁拥有每个函数,`diff-impact` 中的所有权边界 | | 💾 | **图快照** | `snapshot save`/`restore` 用于即时 DB 备份和回滚——重构前检查点,无需重构即可恢复 | | 🔎 | **混合 BM25 + 语义搜索** | 通过倒数排名融合 (RRF) 融合 FTS5 关键词搜索 + 基于嵌入的语义搜索——`hybrid`、`semantic` 或 `keyword` 模式 | | 📄 | **分页 & NDJSON 流** | 所有 MCP 工具和 CLI 命令上通用的 `--limit`/`--offset` 分页;`--ndjson` 用于换行符分隔的 JSON 流 | | 🔀 | **分支结构对比** | 比较两个 git refs 之间的代码结构——添加/删除/更改的符号及其传递性调用者影响 | | 🛡️ | **架构边界** | 模块之间用户定义的依赖规则,带有洋葱架构预设——在 manifesto 和 CI 中标记违规 | | ✅ | **CI 验证断言** | 带有可配置 gates 的 `check` 命令:复杂度、影响范围、循环、边界违规——CI 退出代码 0/1 | | 📋 | **复合审计** | 单个 `audit` 命令结合每个函数的 explain + impact + health 指标——一次调用代替 3-4 次 | | 🚦 | **分诊队列** | `triage` 将连接性、热点、角色和复杂度合并为排名的审计优先级队列 | | 📦 | **批量查询** | 接受目标列表并在一个 JSON payload 中返回所有结果——支持多 agent 并行分发 | | 🔬 | **数据流分析** | 通过 `flows_to`、`returns` 和 `mutates` 边跟踪数据如何在函数间移动——通过 `build --dataflow` (JS/TS) 选择加入 | | 🧩 | **控制流图** | 为所有 11 种语言构建过程内 CFG——`cfg` 命令提供 text/DOT/Mermaid 输出,通过 `build --cfg` 选择加入 | | 🔎 | **AST 节点查询** | 存储可查询的 AST 节点(调用、`new`、string、regex、throw、await)——带 SQL GLOB 模式匹配的 `ast` 命令 | | 🧬 | **扩展节点/边类型** | `parameter`、`property`、`constant` 节点类型,带有用于子声明查询的 `parent_id`;`contains`、`parameter_of`、`receiver` 边类型 | | 📊 | **导出分析** | `exports ` 显示所有导出符号及其每个符号的消费者、重导出检测和计数 | | 📈 | **交互式查看器** | `codegraph plot` 生成交互式 HTML 图查看器,支持分层/力导向/径向布局、复杂度覆盖和钻取 | | 🏷️ | **稳定的 JSON schema** | `normalizeSymbol` 工具确保所有命令输出一致的 7 字段(name、kind、file、line、endLine、role、fileHash) | 参见 [docs/examples](docs/examples) 获取真实世界的 CLI 和 MCP 使用示例。 ## 📦 命令 ### 构建与监听 ``` codegraph build [dir] # Parse and build the dependency graph codegraph build --no-incremental # Force full rebuild codegraph build --engine wasm # Force WASM engine (skip native) codegraph watch [dir] # Watch for changes, update graph incrementally ``` ### 查询与探索 ``` codegraph query # Find a symbol — shows callers and callees codegraph deps # File imports/exports codegraph map # Top 20 most-connected files codegraph map -n 50 --no-tests # Top 50, excluding test files codegraph where # Where is a symbol defined and used? codegraph where --file src/db.js # List symbols, imports, exports for a file codegraph stats # Graph health: nodes, edges, languages, quality score codegraph roles # Node role classification (entry, core, utility, adapter, dead, leaf) codegraph roles --role dead -T # Find dead code (unreferenced, non-exported symbols) codegraph roles --role core --file src/ # Core symbols in src/ codegraph exports src/queries.js # Per-symbol consumer analysis (who calls each export) codegraph children # List parameters, properties, constants of a symbol ``` ### 深度上下文(AI 优化) ``` codegraph context # Full context: source, deps, callers, signature, tests codegraph context --depth 2 --no-tests # Include callee source 2 levels deep codegraph audit --quick # Structural summary: public API, internals, data flow codegraph audit --quick # Function summary: signature, calls, callers, tests ``` ### 影响分析 ``` codegraph impact # Transitive reverse dependency trace codegraph query # Function-level: callers, callees, call chain codegraph query --no-tests --depth 5 codegraph fn-impact # What functions break if this one changes codegraph path # Shortest path between two symbols (A calls...calls B) codegraph path --reverse # Follow edges backward codegraph path --depth 5 --kinds calls,imports codegraph diff-impact # Impact of unstaged git changes codegraph diff-impact --staged # Impact of staged changes codegraph diff-impact HEAD~3 # Impact vs a specific ref codegraph diff-impact main --format mermaid -T # Mermaid flowchart of blast radius codegraph branch-compare main feature-branch # Structural diff between two refs codegraph branch-compare main HEAD --no-tests # Symbols added/removed/changed vs main codegraph branch-compare v2.4.0 v2.5.0 --json # JSON output for programmatic use codegraph branch-compare main HEAD --format mermaid # Mermaid diagram of structural changes ``` ### 共变分析 分析 git 历史以查找总是一起更改的文件——揭示静态图无法看到的隐藏耦合。需要一个 git 仓库。 ``` codegraph co-change --analyze # Scan git history and populate co-change data codegraph co-change src/queries.js # Show co-change partners for a file codegraph co-change # Show top co-changing file pairs globally codegraph co-change --since 6m # Limit to last 6 months of history codegraph co-change --min-jaccard 0.5 # Only show strong coupling (Jaccard >= 0.5) codegraph co-change --min-support 5 # Minimum co-commit count codegraph co-change --full # Include all details ``` 共变数据也会丰富 `diff-impact`——历史耦合文件出现在 `historicallyCoupled` 部分中,与静态依赖分析并列。 ### 结构与热点 ``` codegraph structure # Directory overview with cohesion scores codegraph triage --level file # Files with extreme fan-in, fan-out, or density codegraph triage --level directory --sort coupling --no-tests ``` ### 代码健康与架构 ``` codegraph complexity # Per-function cognitive, cyclomatic, nesting, MI codegraph complexity --health -T # Full Halstead health view (volume, effort, bugs, MI) codegraph complexity --sort mi -T # Sort by worst maintainability index codegraph complexity --above-threshold -T # Only functions exceeding warn thresholds codegraph communities # Louvain community detection — natural module boundaries codegraph communities --drift -T # Drift analysis only — split/merge candidates codegraph communities --functions # Function-level community detection codegraph check # Pass/fail rule engine (exit code 1 on fail) codegraph check -T # Exclude test files from rule evaluation ``` ### 数据流、CFG 与 AST ``` codegraph dataflow # Data flow edges for a function (flows_to, returns, mutates) codegraph dataflow --impact # Transitive data-dependent blast radius codegraph cfg # Control flow graph (text format) codegraph cfg --format dot # CFG as Graphviz DOT codegraph cfg --format mermaid # CFG as Mermaid diagram codegraph ast # List all stored AST nodes codegraph ast "handleAuth" # Search AST nodes by pattern (GLOB) codegraph ast -k call # Filter by kind: call, new, string, regex, throw, await codegraph ast -k throw --file src/ # Combine kind and file filters ``` ### 审计、分诊与批处理 用于风险驱动工作流和多 agent 分发的复合命令。 ``` codegraph audit # Combined structural summary + impact + health in one report codegraph audit --quick # Structural summary only (skip impact and health) codegraph audit src/queries.js -T # Audit all functions in a file codegraph triage # Ranked audit priority queue (connectivity + hotspots + roles) codegraph triage -T --limit 20 # Top 20 riskiest functions, excluding tests codegraph triage --level file -T # File-level hotspot analysis codegraph triage --level directory -T # Directory-level hotspot analysis codegraph batch target1 target2 ... # Batch query multiple targets in one call codegraph batch --json targets.json # Batch from a JSON file ``` ### CI 验证 `codegraph check` 为 CI gates 和状态机提供可配置的通过/失败断言。退出代码 0 = 通过,1 = 失败。 ``` codegraph check # Run manifesto rules on whole codebase codegraph check --staged # Check staged changes (diff predicates) codegraph check --staged --rules # Run both diff predicates AND manifesto rules codegraph check --no-new-cycles # Fail if staged changes introduce cycles codegraph check --max-complexity 30 # Fail if any function exceeds complexity threshold codegraph check --max-blast-radius 50 # Fail if blast radius exceeds limit codegraph check --no-boundary-violations # Fail on architecture boundary violations codegraph check main # Check current branch vs main ``` ### CODEOWNERS 将图符号映射到 CODEOWNERS 条目。显示谁拥有每个函数并揭示所有权边界。 ``` codegraph owners # Show ownership for all symbols codegraph owners src/queries.js # Ownership for symbols in a specific file codegraph owners --boundary # Show ownership boundaries between modules codegraph owners --owner @backend # Filter by owner ``` 所有权数据也会丰富 `diff-impact`——受影响的所有者和建议的审查者与静态依赖分析一起显示。 ### 快照 轻量级 SQLite DB 备份和恢复——重构前检查点,无需重构即可立即回滚。 ``` codegraph snapshot save before-refactor # Save a named snapshot codegraph snapshot list # List all snapshots codegraph snapshot restore before-refactor # Restore a snapshot codegraph snapshot delete before-refactor # Delete a snapshot ``` ### 导出与可视化 ``` codegraph export -f dot # Graphviz DOT format codegraph export -f mermaid # Mermaid diagram codegraph export -f json # JSON graph codegraph export -f graphml # GraphML (XML standard) codegraph export -f graphson # GraphSON (TinkerPop v3 / Gremlin) codegraph export -f neo4j # Neo4j CSV (bulk import, separate nodes/relationships files) codegraph export --functions -o graph.dot # Function-level, write to file codegraph plot # Interactive HTML viewer with force/hierarchical/radial layouts codegraph cycles # Detect circular dependencies codegraph cycles --functions # Function-level cycles ``` ### 语义搜索 为每个函数、方法和类提供本地嵌入——通过自然语言搜索。一切都在本地使用 [@huggingface/transformers](https://huggingface.co/docs/transformers.js) 运行——无需 API keys。 ``` codegraph embed # Build embeddings (default: nomic-v1.5) codegraph embed --model nomic # Use a different model codegraph search "handle authentication" codegraph search "parse config" --min-score 0.4 -n 10 codegraph search "parseConfig" --mode keyword # BM25 keyword-only (exact names) codegraph search "auth flow" --mode semantic # Embedding-only (conceptual) codegraph search "auth flow" --mode hybrid # BM25 + semantic RRF fusion (default) codegraph models # List available models ``` #### 多查询搜索 用 `;` 分隔查询以从多个角度进行搜索。结果使用 [Reciprocal Rank Fusion (RRF)](https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf) 排名——在多个查询中排名靠前的项目会上升到顶部。 ``` codegraph search "auth middleware; JWT validation" codegraph search "parse config; read settings; load env" -n 20 codegraph search "error handling; retry logic" --kind function codegraph search "database connection; query builder" --rrf-k 30 ``` 单个尾随分号被忽略(回退到单查询模式)。`--rrf-k` 标志控制 RRF 平滑常数(默认 60)——较低的值给排名靠前的结果更多的权重。 #### 可用模型 | 标志 | 模型 | 维度 | 大小 | 许可证 | 备注 | |---|---|---|---|---|---| | `minilm` | all-MiniLM-L6-v2 | 384 | ~23 MB | Apache-2.0 | 最快,适合快速迭代 | | `jina-small` | jina-embeddings-v2-small-en | 512 | ~33 MB | Apache-2.0 | 更好的质量,仍然很小 | | `jina-base` | jina-embeddings-v2-base-en | 768 | ~137 MB | Apache-2.0 | 高质量,8192 token 上下文 | | `jina-code` | jina-embeddings-v2-base-code | 768 | ~137 MB | Apache-2.0 | 最适合代码搜索,在代码+文本上训练(需要 HF token) | | `nomic` | nomic-embed-text-v1 | 768 | ~137 MB | Apache-2.0 | 良好的质量,8192 上下文 | | `nomic-v1.5` (默认) | nomic-embed-text-v1.5 | 768 | ~137 MB | Apache-2.0 | **改进的 nomic,Matryoshka 维度** | | `bge-large` | bge-large-en-v1.5 | 1024 | ~335 MB | MIT | 最佳通用检索,顶级 MTEB 分数 | 在 `embed` 期间使用的模型存储在数据库中,因此 `search` 会自动检测它——搜索时无需传递 `--model`。 ### 多仓库注册表 管理 codegraph 项目的全局注册表。注册表存储构建图的路径,以便 MCP server 在启用多仓库模式时可以查询它们。 ``` codegraph registry list # List all registered repos codegraph registry list --json # JSON output codegraph registry add # Register a project directory codegraph registry add -n my-name # Custom name codegraph registry remove # Unregister ``` `codegraph build` 自动注册项目——无需手动设置。 ### 通用标志 | 标志 | 描述 | |---|---| | `-d, --db ` | `graph.db` 的自定义路径 | | `-T, --no-tests` | 排除 `.test.`、`.spec.`、`__test__` 文件(适用于大多数查询命令,包括 `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`) | | `--depth ` | 传递追踪深度(默认值因命令而异) | | `-j, --json` | 输出为 JSON | | `-v, --verbose` | 启用 debug 输出 | | `--engine ` | 解析引擎:`native`、`wasm` 或 `auto`(默认:`auto`) | | `-k, --kind ` | 按类型过滤:`function`、`method`、`class`、`interface`、`type`、`struct`、`enum`、`trait`、`record`、`module`、`parameter`、`property`、`constant` | | `-f, --file ` | 限定到特定文件(`fn`、`context`、`where`) | | `--mode ` | 搜索模式:`hybrid`(默认)、`semantic` 或 `keyword`(`search`) | | `--ndjson` | 输出为换行符分隔的 JSON(每行一个对象) | | `--limit ` | 限制结果数量 | | `--offset ` | 跳过前 N 个结果(分页) | | `--rrf-k ` | 多查询搜索的 RRF 平滑常数(默认 60) | ## 🌐 语言支持 | 语言 | 扩展名 | 覆盖范围 | |---|---|---| | ![JavaScript](https://img.shields.io/badge/-JavaScript-F7DF1E?style=flat-square&logo=javascript&logoColor=black) | `.js`, `.jsx`, `.mjs`, `.cjs` | 完整——函数、类、导入、调用点 | | ![TypeScript](https://img.shields.io/badge/-TypeScript-3178C6?style=flat-square&logo=typescript&logoColor=white) | `.ts`, `.tsx` | 完整——接口、类型别名、`.d.ts` | | ![Python](https://img.shields.io/badge/-Python-3776AB?style=flat-square&logo=python&logoColor=white) | `.py` | 函数、类、方法、导入、装饰器 | | ![Go](https://img.shields.io/badge/-Go-00ADD8?style=flat-square&logo=go&logoColor=white) | `.go` | 函数、方法、结构体、接口、导入、调用点 | | ![Rust](https://img.shields.io/badge/-Rust-000000?style=flat-square&logo=rust&logoColor=white) | `.rs` | 函数、方法、结构体、traits、`use` 导入、调用点 | | ![Java](https://img.shields.io/badge/-Java-ED8B00?style=flat-square&logo=openjdk&logoColor=white) | `.java` | 类、方法、构造函数、接口、导入、调用点 | | ![C#](https://img.shields.io/badge/-C%23-512BD4?style=flat-square&logo=dotnet&logoColor=white) | `.cs` | 类、结构体、记录、接口、枚举、方法、构造函数、using 指令、调用 | | ![PHP](https://img.shields.io/badge/-PHP-777BB4?style=flat-square&logo=php&logoColor=white) | `.php` | 函数、类、接口、traits、枚举、方法、命名空间 use、调用 | | ![Ruby](https://img.shields.io/badge/-Ruby-CC342D?style=flat-square&logo=ruby&logo=white) | `.rb` | 类、模块、方法、单例方法、require/require_relative、include/extend | | ![Terraform](https://img.shields.io/badge/-Terraform-844FBA?style=flat-square&logo=terraform&logoColor=white) | `.tf`, `.hcl` | Resource、data、variable、module、output blocks | ## ⚙️ 工作原理 ``` ┌──────────┐ ┌───────────┐ ┌───────────┐ ┌──────────┐ ┌─────────┐ │ Source │──▶│ tree-sitter│──▶│ Extract │──▶│ Resolve │──▶│ SQLite │ │ Files │ │ Parse │ │ Symbols │ │ Imports │ │ DB │ └──────────┘ └───────────┘ └───────────┘ └──────────┘ └─────────┘ │ ▼ ┌─────────┐ │ Query │ └─────────┘ ``` 1. **Parse(解析)** —— tree-sitter 将每个源文件解析为 AST(原生 Rust 引擎或 WASM 回退) 2. **Extract(提取)** —— 提取函数、类、方法、接口、导入、导出、调用点、参数、属性和常量 3. **Resolve(解析)** —— 将导入解析为实际文件(处理 ESM 约定、`tsconfig.json` 路径别名、`baseUrl`) 4. **Store(存储)** —— 一切都作为节点 + 边存储在 SQLite 中,带有 tree-sitter 节点边界,以及结构边(`contains`、`parameter_of`、`receiver`) 5. **Analyze(分析,选填)** —— 复杂度指标、控制流图(`--cfg`)、数据流边(`--dataflow`)和 AST 节点存储 6. **Query(查询)** —— 所有查询都在本地针对 SQLite DB 运行——通常在 100ms 以下 ### 增量重构 关系图保持最新,无需重新解析整个代码库。三层变更检测确保重构与更改的内容成比例,而不是项目的大小: 1. **Tier 0 — Journal (O(changed)):** 如果 `codegraph watch` 正在运行,更改日志会记录确切哪些文件被触及。下次构建读取日志并仅处理这些文件——零文件系统扫描 2. **Tier 1 — mtime+size (O(n) stats, O(changed) reads):** 没有日志?Codegraph 获取每个文件的 stat 并将 mtime + size 与存储的值进行比较。匹配的文件在不读取单个字节的情况下被跳过 3. **Tier 2 — Hash (O(changed) reads):** 未通过 mtime/size 检查的文件将被读取并进行 MD5 哈希。只有哈希实际更改的文件才会被重新解析和重新插入 **结果:** 在 3,000 个文件的项目中更改一个文件,重构在不到一秒内完成。把它放在提交钩子、文件监视器中,或者让你的 AI agent 触发它。 ### 双引擎 Codegraph 附带两个解析引擎: | 引擎 | 工作原理 | 何时使用 | |--------|-------------|----------------| | **Native** (Rust) | 从 `crates/codegraph-core/` 构建的 napi-rs 插件——通过 rayon 进行并行多核解析 | 当预构建二进制文件可用时自动选择 | | **WASM** | `web-tree-sitter` 在 `grammars/` 中使用预构建的 `.wasm` 语法 | 当原生插件未安装时回退 | 两个引擎产生相同的输出。使用 `--engine native|wasm|auto` 控制选择(默认:`auto`)。 ### 调用解析 调用通过**合格解析**进行解析——方法调用(`obj.method()`)与独立函数调用区分开来,内置接收器(`console`、`Math`、`JSON`、`Array`、`Promise` 等)被自动过滤掉。导入范围受到尊重:对 `foo()` 的调用仅解析为实际导入或在同一文件中定义的函数,从而消除名称冲突导致的误报。 | 优先级 | 来源 | 置信度 | |---|---|---| | 1 | **Import-aware** —— `import { foo } from './bar'` → 链接到 `bar` | `1.0` | | 2 | **Same-file** —— 当前文件中的定义 | `1.0` | | 3 | **Same directory** —— 同级文件中的定义(仅限独立调用) | `0.7` | | 4 | **Same parent directory** —— 同级目录中的定义(仅限独立调用) | `0.5` | | 5 | **Method hierarchy** —— 通过 `extends`/`implements` 解析 | varies | 未知接收器上的方法调用完全跳过全局回退——`stmt.run()` 永远不会解析为另一个文件中的独立 `run` 函数。重复的调用者/被调用者边会自动去重。动态模式如 `fn.call()`、`fn.apply()`、`fn.bind()` 和 `obj["method"]()` 也会尽力检测。 Codegraph 还从常见的回调模式中提取符号:Commander `.command().action()` 回调(作为 `command:build`)、Express 路由处理器(作为 `route:GET /api/users`)和事件发射器监听器(作为 `event:data`)。 ## 📊 性能 每次发布通过 CI 自我测量([构建基准测试](generated/benchmarks/BUILD-BENCHMARKS.md) | [嵌入基准测试](generated/benchmarks/EMBEDDING-BENCHMARKS.md)): | 指标 | 最新值 | |---|---| | 构建速度 (native) | **4.4 ms/file** | | 构建速度 (WASM) | **13.7 ms/file** | | 查询时间 | **3ms** | | 空操作重构 (native) | **4ms** | | 1 文件重构 (native) | **325ms** | | 查询:fn-deps | **0.8ms** | | 查询:path | **0.8ms** | | ~50,000 个文件(估计) | **~220.0s build** | 指标按文件标准化以便跨版本比较。以上时间是完整初始构建的时间——增量重构仅重新解析更改的文件。 ### 轻量级占用 npm unpacked size 仅有 **3 个运行时依赖**——其他所有都是可选的或 devDependency: | 依赖 | 功能 | | | |---|---|---|---| | [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) | 快速、同步的 SQLite 驱动 | ![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) | | [commander](https://github.com/tj/commander.js) | CLI 参数解析 | ![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) | | [web-tree-sitter](https://github.com/tree-sitter/tree-sitter) | WASM tree-sitter 绑定 | ![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) | 可选:`@huggingface/transformers`(语义搜索)、`@modelcontextprotocol/sdk`(MCP server)——仅在需要时延迟加载。 ## 🤖 AI Agent 集成 ### MCP Server Codegraph 包含一个内置的 [Model Context Protocol](https://modelcontextprotocol.io/) server,拥有 30 个工具(多仓库模式下为 31 个),以便 AI 助手可以直接查询你的依赖图: ``` codegraph mcp # Single-repo mode (default) — only local project codegraph mcp --multi-repo # Enable access to all registered repos codegraph mcp --repos a,b # Restrict to specific repos (implies --multi-repo) ``` **单仓库模式(默认):** 工具仅在本地 `.codegraph/graph.db` 上运行。`repo` 参数和 `list_repos` 工具不会暴露给 AI agent。 **多仓库模式(`--multi-repo`):** 所有工具获得一个可选的 `repo` 参数以定位任何已注册的仓库,并且 `list_repos` 变为可用。使用 `--repos` 限制 agent 可以访问的仓库。 ### CLAUDE.md / Agent 指令 将此添加到项目的 `CLAUDE.md` 以帮助 AI agent 使用 codegraph(完整模板见 [AI Agent 指南](docs/guides/ai-agent-guide.md#claudemd-template)): ``` ## Code Navigation This project uses codegraph. The database is at `.codegraph/graph.db`. ### 修改代码前,务必: 1. `codegraph where ` — find where the symbol lives 2. `codegraph audit --quick` — understand the structure 3. `codegraph context -T` — get full context (source, deps, callers) 4. `codegraph fn-impact -T` — check blast radius before editing ### 修改代码后: 5. `codegraph diff-impact --staged -T` — verify impact before committing ### 其他有用的命令 - `codegraph build .` — rebuild the graph (incremental by default) - `codegraph map` — module overview - `codegraph query -T` — function call chain (callers + callees) - `codegraph path -T` — shortest call path between two symbols - `codegraph deps ` — file-level dependencies - `codegraph roles --role dead -T` — find dead code (unreferenced symbols) - `codegraph roles --role core -T` — find core symbols (high fan-in) - `codegraph co-change ` — files that historically change together - `codegraph complexity -T` — per-function complexity metrics (cognitive, cyclomatic, MI) - `codegraph communities --drift -T` — module boundary drift analysis - `codegraph check -T` — pass/fail rule check (CI gate, exit code 1 on fail) - `codegraph audit -T` — combined structural summary + impact + health in one report - `codegraph triage -T` — ranked audit priority queue - `codegraph triage --level file -T` — file-level hotspot analysis - `codegraph check --staged` — CI validation predicates (exit code 0/1) - `codegraph batch target1 target2` — batch query multiple targets at once - `codegraph owners [target]` — CODEOWNERS mapping for symbols - `codegraph snapshot save ` — checkpoint the graph DB before refactoring - `codegraph branch-compare main HEAD -T` — structural diff between two refs (added/removed/changed symbols) - `codegraph exports ` — per-symbol consumer analysis (who calls each export) - `codegraph children ` — list parameters, properties, constants of a symbol - `codegraph dataflow ` — data flow edges (flows_to, returns, mutates) - `codegraph cfg ` — intraprocedural control flow graph - `codegraph ast ` — search stored AST nodes (calls, new, string, regex, throw, await) - `codegraph plot` — interactive HTML dependency graph viewer - `codegraph search ""` — hybrid search (requires `codegraph embed`) - `codegraph search "" --mode keyword` — BM25 keyword search - `codegraph cycles` — check for circular dependencies ### Flags - `-T` / `--no-tests` — exclude test files (use by default) - `-j` / `--json` — JSON output for programmatic use - `-f, --file ` — scope to a specific file - `-k, --kind ` — filter by symbol kind ### Semantic search Use `codegraph search` to find functions by intent rather than exact name. When a single query might miss results, combine multiple angles with `;`: codegraph search "validate auth; check token; verify JWT" codegraph search "parse config; load settings" --kind function Multi-query search uses Reciprocal Rank Fusion — functions that rank highly across several queries surface first. This is especially useful when you're not sure what naming convention the codebase uses. When writing multi-queries, use 2-4 sub-queries (2-4 words each) that attack the problem from different angles. Pick from these strategies: - **Naming variants**: cover synonyms the author might have used ("send email; notify user; deliver message") - **Abstraction levels**: pair high-level intent with low-level operation ("handle payment; charge credit card") - **Input/output sides**: cover the read half and write half ("parse config; apply settings") - **Domain + technical**: bridge business language and implementation ("onboard tenant; create organization; provision workspace") Use `--kind function` to cut noise. Use `--file ` to scope. ``` ## 📋 推荐实践 参见 **[docs/guides/recommended-practices.md](docs/guides/recommended-practices.md)** 获取集成指南: - **Git hooks** —— 提交时自动重构、推送时影响检查、提交消息丰富 - **CI/CD** —— PR 影响评论、阈值 gates、图缓存 - **AI agents** —— MCP server、CLAUDE.md 模板、Claude Code hooks - **开发者工作流** —— 监听模式、先探索后编辑、语义搜索 - **安全凭证** —— `apiKeyCommand` 配合 1Password、Bitwarden、Vault、macOS Keychain、`pass` 对于 AI 特定的集成,请参阅 **[AI Agent 指南](docs/guides/ai-agent-guide.md)** —— 一份综合参考,涵盖 6 步 agent 工作流、完整的命令到 MCP 映射、Claude Code hooks 和节省 token 的模式。 ## 🔁 CI / GitHub Actions Codegraph 附带一个现成可用的 GitHub Actions 工作流,在每个 pull request 上评论影响分析。 将 `.github/workflows/codegraph-impact.yml` 复制到你的仓库,每个 PR 都会收到如下评论: ## 🛠️ 配置 在项目根目录创建一个 `.codegraphrc.json` 来自定义行为: ``` { "include": ["src/**", "lib/**"], "exclude": ["**/*.test.js", "**/__mocks__/**"], "ignoreDirs": ["node_modules", ".git", "dist"], "extensions": [".js", ".ts", ".tsx", ".py"], "aliases": { "@/": "./src/", "@utils/": "./src/utils/" }, "build": { "incremental": true }, "query": { "excludeTests": true } } ``` ### Manifesto 规则 为 `codegraph check`(manifesto 模式)配置通过/失败阈值: ``` { "manifesto": { "rules": { "cognitive_complexity": { "warn": 15, "fail": 30 }, "cyclomatic_complexity": { "warn": 10, "fail": 20 }, "nesting_depth": { "warn": 4, "fail": 6 }, "maintainability_index": { "warn": 40, "fail": 20 }, "halstead_bugs": { "warn": 0.5, "fail": 1.0 } } } } ``` 当任何函数超过 `fail` 阈值时,`codegraph check` 以代码 1 退出——非常适合 CI gates。 ### LLM 凭证 Codegraph 支持 `apiKeyCommand` 字段以进行安全的凭证管理。你可以通过 shell 在运行时调用密钥管理器,而不是将 API keys 存储在配置文件或环境变量中: ``` { "llm": { "provider": "openai", "apiKeyCommand": "op read op://vault/openai/api-key" } } ``` 命令在空白处分割并使用 `execFileSync` 执行(无 shell 注入风险)。优先级:**命令输出 > `CODEGRAPH_LLM_API_KEY` 环境变量 > 文件配置**。失败时,codegraph 会警告并回退到下一个来源。 适用于任何密钥管理器:1Password CLI (`op`)、Bitwarden (`bw`)、`pass`、HashiCorp Vault、macOS Keychain (`security`)、AWS Secrets Manager 等。 ## 📖 编程 API Codegraph 还导出一个完整的 API 供你自己的工具使用: ``` import { buildGraph, queryNameData, findCycles, exportDOT, normalizeSymbol } from '@optave/codegraph'; // Build the graph buildGraph('/path/to/project'); // Query programmatically const results = queryNameData('myFunction', '/path/to/.codegraph/graph.db'); // All query results use normalizeSymbol for a stable 7-field schema ``` ``` import { parseFileAuto, getActiveEngine, isNativeAvailable } from '@optave/codegraph'; // Check which engine is active console.log(getActiveEngine()); // 'native' or 'wasm' console.log(isNativeAvailable()); // true if Rust addon is installed // Parse a single file (uses auto-selected engine) const symbols = await parseFileAuto('/path/to/file.ts'); ``` ``` import { searchData, multiSearchData, buildEmbeddings } from '@optave/codegraph'; // Build embeddings (one-time) await buildEmbeddings('/path/to/project'); // Single-query search const { results } = await searchData('handle auth', dbPath); // Multi-query search with RRF ranking const { results: fused } = await multiSearchData( ['auth middleware', 'JWT validation'], dbPath, { limit: 10, minScore: 0.3 } ); // Each result has: { name, kind, file, line, rrf, queryScores[] } ``` ## ⚠️ 局限性 - **无完整类型推断** —— 解析 `.d.ts` 接口,但不使用 TypeScript 的类型检查器进行重载解析 - **动态调用是尽力而为** —— 复杂的计算属性访问和 `eval` 模式不被解析 - **Python 导入** —— 解析相对导入,但不遵循 `sys.path` 或虚拟环境包 - **数据流分析** —— 目前仅限 JS/TS;过程内(单函数范围),非过程间 ## 🗺️ 路线图 参见 **[ROADMAP.md](docs/roadmap/ROADMAP.md)** 获取完整的开发路线图,以及 **[STABILITY.md](STABILITY.md)** 获取稳定性策略和版本保证。当前计划: 1. ~~**Rust Core**~~ —— **完成** (v1.3.0) —— 通过 napi-rs 进行原生 tree-sitter 解析、并行多核解析、增量重新解析、Rust 中的导入解析和循环检测 2. ~~**Foundation Hardening**~~ —— **完成** (v1.4.0) —— 解析器注册表、支持多仓库的 12 工具 MCP server、测试覆盖率 62%→75%、`apiKeyCommand` 密钥解析、全局仓库注册表 3. ~~**Deep Analysis**~~ —— **完成** (v3.0.0) —— 数据流分析(flows_to、returns、mutates)、所有 11 种语言的过程内 CFG、存储 AST 节点、扩展节点/边类型(parameter、property、constant、contains、parameter_of、receiver)、GraphML/GraphSON/Neo4j CSV 导出、交互式 HTML 查看器、CLI 整合、稳定的 JSON schema 4. **架构重构** —— 解析器插件系统、仓库模式、pipeline 构建器、引擎策略、域错误、精选 API 5. **自然语言查询** —— `codegraph ask` 命令、对话式会话 6. **扩展语言支持** ——8 种新语言(12 → 20) 7. **GitHub 集成 & CI** —— 可重用的 GitHub Action、PR review、SARIF 输出 8. **TypeScript 迁移** —— 从 JS 逐步迁移到 TypeScript ## 🤝 贡献 欢迎贡献!参见 **[CONTRIBUTING.md](CONTRIBUTING.md)** 获取完整指南——设置、工作流、提交约定、测试和架构说明。 ``` git clone https://github.com/optave/codegraph.git cd codegraph npm install npm test ``` 想要添加新语言?查看 **[添加新语言](docs/guides/adding-a-language.md)**。 ## 📄 许可证 [Apache-2.0](LICENSE)

使用 tree-sitterbetter-sqlite3 构建。你的代码保留在你的机器上。

标签:AI代理工具, CI/CD质量门禁, Git差异影响分析, GNU通用公共许可证, MCP服务器, MITM代理, Node.js, 代码复杂度分析, 代码库可视化, 代码搜索引擎, 代码智能, 依赖关系图, 函数级依赖, 协同变更分析, 可视化界面, 大模型上下文, 威胁情报, 开发者工具, 本地离线运行, 架构治理, 自定义脚本, 自定义脚本, 语义搜索, 软件供应链, 错误基检测, 零API密钥, 静态代码分析