MocLab

界面主题

博客导航

本机与站点

节省 Token 与重构项目检索:CodeGraph 与 zvec-grep 深度实测与对比

拆解 Coding Agent 盲目 grep/Read 烧 Token 的根源,结合官方基准数据与本地配置经验,对比 CodeGraph 与 zvec-grep 的检索机制、适用边界与组合用法。

发布
阅读时间
约 11 分钟
目录4 节
  1. 1. CodeGraph:面向代码结构的本地知识图谱
    1. 1.1 工作原理
    2. 1.2 安装与使用
    3. 1.3 官方基准数据与重要边界
  2. 2. zvec-grep(zg):覆盖代码与文档的本地混合检索
    1. 2.1 工作原理
    2. 2.2 安装与使用
    3. 2.3 官方基准数据与边界
  3. 3. 正面对比:CodeGraph vs zvec-grep
  4. 4. 怎么选,以及两者同时装怎么分工
    1. 按场景选一个先装
    2. 两者共存时的路由习惯与可直接复用的提示词

用 Coding Agent 处理中大型代码库时,账单和耗时往往不是花在真正写代码上,而是花在动手之前的“找代码”上。

比如你只问了一句“请求是如何穿过中间件到达数据库的”,在没有外部索引的情况下,Agent 通常要连续跑十几轮 glob、grep、Read:先猜文件名,再搜关键字,读完半个文件发现只是接口定义,再顺着导入路径继续追实现类。每多一轮工具调用,前面读过的历史上下文就会被重新送进模型一遍,Token 和耗时呈滚雪球式上涨。

CodeGraph 和 zvec-grep(CLI 命令为 zg)是当下两条最具代表性的本地优先检索 MCP 路线:前者把代码提前解析成静态调用图与符号数据库,后者把 ripgrep、BM25 全文检索和语义向量检索统一到一个混合索引入口。下面按架构、实操、官方基准数据和组合分工拆开对比。

1. CodeGraph:面向代码结构的本地知识图谱

  • 项目地址:colbymchenry/codegraph · 官方文档
  • 协议与形态:MIT 开源,自带独立运行时(Rust 解析内核 + tree-sitter + 本地 SQLite/FTS5),完全本地运行,不依赖外部 API。

1.1 工作原理

CodeGraph 在项目根目录生成 .codegraph/codegraph.db,用编译后的 Rust 内核配合 tree-sitter 对源码做 AST 级提取,记录两类核心信息:

  1. 符号节点:函数、类、方法、类型、组件以及 20+ 种主流 Web 框架的路由节点(如 Express、FastAPI、Next.js、Django、NestJS、Astro 等)。
  2. 跨文件关系边:调用链(callers / callees)、导入依赖、类继承与接口实现、动态派发与跨语言桥接(如 Swift ↔ ObjC、React Native、Tauri 前后端 invoke)。

启用 MCP 后,后台文件监听(macOS 用 FSEvents、Linux 用 inotify)会在保存文件后自动增量同步索引,无需每次手动重建。

在 MCP 工具面设计上,CodeGraph 做了一个很克制的决定:默认只向 Agent 暴露一个核心工具 codegraph_explore(其余 node、search、callers、impact 等按需通过 CODEGRAPH_MCP_TOOLS 环境变量开启,或走 CLI 命令)。一次 codegraph_explore 调用就会把相关符号的原文源码、调用路径和改动影响面(blast radius)一并返回,减少模型在十几个窄工具间犹豫的开销。

1.2 安装与使用

安装 CLI、自动写入 Agent 配置,并初始化当前仓库索引:

终端
# 1. 安装 CLI(官方独立包,不依赖本机 Node 版本;也可用 npm i -g @colbymchenry/codegraph)
curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh
# 2. 自动检测并写入已安装的 Agent(支持 Claude Code、Codex、Cursor、OpenCode 等 18 种)
codegraph install
# 3. 在目标代码库根目录建立图谱索引
cd your-project
codegraph init

如果你只想看某个客户端对应的配置片段,可以跑 codegraph install --print-config codex 预览再决定是否写入。在 Claude Code(~/.claude.json)里,它对应的 stdio 配置非常简洁:

{
"mcpServers": {
"codegraph": {
"type": "stdio",
"command": "codegraph",
"args": ["serve", "--mcp"],
"alwaysLoad": true
}
}
}

命令行同样可以直接用,适合给子代理或在终端快速查影响面:

终端
codegraph explore "how does authentication validate tokens"
codegraph callers verifySession
codegraph impact AuthService
git diff --name-only | codegraph affected --stdin

1.3 官方基准数据与重要边界

根据 CodeGraph 官方仓库 2026 年 8 月公布的对照评测(Claude Code 无头模式 + Claude Opus 4.8,7 个不同语言的开源项目,每组跑 4 次取中位数,并在两组中同时屏蔽 CLI 以防对照组偷用):

仓库语言与规模工具调用(有 vs 无)耗时(有 vs 无)文件读取次数Token 变化费用变化
VS CodeTypeScript · ~11k 文件2 vs 2858s vs 2m 10s0 vs 12-77%-71%
ExcalidrawTypeScript · ~640 文件2 vs 4345s vs 2m 42s0 vs 18-84%-78%
DjangoPython · ~3k 文件3 vs 1454s vs 1m 23s0 vs 8.5-41%-13%
TokioRust · ~790 文件3 vs 291m 3s vs 2m 43s0 vs 19-65%-64%
OkHttpJava · ~645 文件1 vs 633s vs 58s0 vs 2-54%-21%
GinGo · ~110 文件1 vs 728s vs 46s0 vs 4-52%持平($0.31)
AlamofireSwift · ~110 文件4 vs 3354s vs 2m 22s0 vs 16.5-59%-57%

整体均值表现是:工具调用减少 88%、耗时缩短 53%、处理 Token 减少 62%、费用降低 44%,且 7 个仓库的文件读取次数全部降至 0。

但看这组数据时有两点现实边界值得注意,官方自己也写得很坦诚:

  1. 费用降幅取决于问题的探索深度,而不是单纯看仓库行数。在 Gin(110 文件,原版 7 次工具调用就能答完)上,Token 虽然少了 52%,但由于省下来的很大一部分是便宜的 Prompt Cache 读取 Token,最终美元账单几乎打平。越是需要跨十几个文件追踪调用链的问题,省钱幅度越明显。
  2. 单次吞吐省了,但会话驻留上下文反而更高。codegraph_explore 一次返回一大段高密度的完整源码,这段结果会一直留在后续多轮对话窗口里。官方在多轮会话实测中发现,结束时上下文窗口里的驻留检索内容平均比纯 grep/Read 模式多出约 80%(VS Code 案例里是 67k vs 18k Token)。如果是在小上下文窗口里跑超长对话,要记得适时做 /compact 或拆分新会话。
  3. 只覆盖支持的代码语言,不索引纯文档与数据。像 Markdown 文档、会议纪要、CSV/JSON 配置、论文笔记,CodeGraph 不会把它们纳入图谱。

2. zvec-grep(zg):覆盖代码与文档的本地混合检索

  • 项目地址:zvec-ai/zvec-grep · 官方文档
  • 协议与形态:Apache-2.0 开源,由 alibaba/zvec 驱动,把 ripgrep 精确匹配、BM25 词法全文检索与 Embedding 语义向量检索合在同一个本地工具里。

2.1 工作原理

CodeGraph 偏重“代码符号之间的静态图关系”,而 zvec-grep 要解决的是更宽的工作区检索问题:当你不记得确切函数名、不知道结论藏在代码还是设计文档里,或者面对一个混杂了源码、Markdown、JSON/TOML 配置、日志和数据的目录时,纯关键词 grep 很容易漏掉同义表述或跨文件线索。

zg 的索引存放在项目根目录 .zvec-grep/ 下,针对不同文件类型采用不同的切片策略:

  • 结构化源码(TS/JS/TSX/JSX、Python、Go、Rust、Java、C/C++、Vue、Svelte 等):保留符号、签名与作用域面包屑。
  • 通用代码与脚本文本(Shell、C#、Kotlin、PHP、Ruby、Swift、SQL、Dockerfile、CSS/SCSS 等):按文本块切分并保留精确行号来源。
  • 文档与数据文件(Markdown/MDX、HTML、JSON/JSONC、TOML、CSV、RST、TXT):按章节与语义块检索,同样带回文件路径和行号区间。

在 Embedding 模型上,它既支持纯离线本地模型(如轻量的 local/potion-code-16m-v2、local/potion-retrieval-32m、local/bge-small-en-v1.5,以及质量更高的 local/qwen3-embedding-0.6b、local/nomic-embed-text-v1.5),也可以在显式授权后接入远程 Embedding(如 qwen/qwen3.7-text-embedding 或多模态 qwen/qwen3-vl-embedding)。默认全本地运行,不会擅自把代码发往远端。

2.2 安装与使用

终端
# 1. 全局安装 CLI(提供 zg 命令)
npm install -g @zvec/zvec-grep --allow-scripts=@zvec/zvec-grep
# 2. 自动为本机已有的 Agent 写入 MCP 与路由规则
zg install
# 3. 进入需要语义检索的工作区,用本地模型建索引
cd your-workspace
zg index --embedding local/potion-code-16m-v2

在 Claude Code / Codex 中,它通过 zg server --stdio 提供 MCP 服务,主要暴露语义与混合检索入口(zvec_grep_search)以及受控的 ripgrep 精确搜索入口(zvec_grep_rg)。人在终端里也能直接查:

终端
# 语义 + 词法混合检索
zg query "where authentication is validated"
# 纯 BM25 全文检索
zg query --fts "AuthService"
# 托管 ripgrep 精确字面量搜索
zg query --rg -F "AuthService" src
# 查看当前工作区索引状态
zg status

需要注意一个小细节:如果一个目录你没有手动跑过 zg index,Agent 也可以只走精确匹配,或者按提示决定是否建索引;遵循正常工程习惯,创建或重建持久化索引最好由人明确授权,不要让 Agent 静默给磁盘上随便一个大目录拉起向量化任务。

2.3 官方基准数据与边界

根据 zvec-ai/zvec-grep 官方仓库公布的配对 A/B 评测(同模型、同 Prompt、同环境、同限制,仅区别是否启用 zvec-grep MCP;索引构建时间单独计入):

基准测试场景与配置答案质量变化输入 Token工具调用次数Agent 耗时
SWE-QA-Bench代码库问答(20 任务 / 11 仓库 / 3 次重复;Claude Code + Claude Opus 5)80.42 → 81.92(+1.50 pp)559K → 294K(-47.3%)23.42 → 9.70(-58.6%)127.5s → 79.7s(-37.5%)
BrowseComp-Plus10 万篇文档深度研究(100 用例 / 300 组配对;Codex gpt-5.6-sol)98.67% → 99.00%(+0.33 pp)1.68M → 1.05M(-37.56%)25.42 → 14.36(-43.52%)259.4s → 159.3s(-38.58%)

BrowseComp-Plus 报告中还披露了分布细节:平均输入 Token 下降 37.56%,中位数下降 25.8%,100 个用例中有 67 个在保持质量的前提下显著省了 Token。官方同样明确指出了收益变窄的场景——如果问题本身靠精确关键字一眼就能定位,或者语义召回的片段不够决定性,Agent 还是会回头用 grep 做二次核验,此时混合检索反而多了一步开销。

此外,官方评测使用的是远程 qwen/qwen3.7-text-embedding 模型;如果你在本地改用极轻量的 potion-code-16m-v2 等小模型,召回精度和 Token 省幅会略低于大模型,但换来的是完全离线、秒级建索引和零 API 费用。

3. 正面对比:CodeGraph vs zvec-grep

把两者的底层思路、覆盖面和成本账放到一张表里对比,差异非常直白:

对比维度CodeGraphzvec-grep(zg)
核心引擎Rust + tree-sitter AST 解析 + SQLite/FTS5 关系图zvec 向量索引 + BM25 全文 + 托管 ripgrep
索引目录.codegraph/.zvec-grep/
擅长的问题调用链追踪(谁调用了 X)、跨文件影响面、框架路由与动态派发、代码结构总览记不清确切名称的语义发现、跨文档/跨模块概念串联、设计原理与非结构化文本检索
覆盖文件类型30+ 种编程语言源码与主流前端/后端框架源码 + Markdown / HTML / JSON / TOML / CSV / 纯文本等混合工作区
MCP 工具形态默认收敛为单个 codegraph_explore(其余可按需开启)语义混合 zvec_grep_search + 精确 zvec_grep_rg 等
依赖与模型开销零 Embedding 模型,纯静态解析,冷启动快、无 GPU/API 依赖需本地下载轻量 Embedding 模型(几十 MB 起)或显式授权远程 Embedding API
增量维护内置文件监听,保存后秒级自动同步支持后台守护进程刷新与新鲜度提示
开源协议MITApache-2.0
主要短板不索引文档/配置;单次回传内容密,长对话驻留上下文偏高对复杂静态类型调用链、动态派发与精确影响面分析不如 AST 图谱精准

4. 怎么选,以及两者同时装怎么分工

这两个工具并不冲突,我自己在 Claude Code 和 Codex 里就是同时装着两者的。真正需要注意的是明确路由规则,别让 Agent 同一个问题先查一遍 CodeGraph、再查一遍 zvec-grep、最后再跑一轮 rg 把省下来的 Token 全吐回去。

按场景选一个先装

  • 纯代码仓库、经常做跨文件重构 / 查调用链 / 接手陌生大项目:先装 CodeGraph。零模型配置、零 API 成本,对“谁调用了这个函数”“改这个接口会影响哪几个路由和单测”这类结构问题命中率极高。
  • 代码 + 大量文档 / RFC / 笔记 / 科研资料混排的工作区,或者经常要做概念性搜索:先装 zvec-grep。哪怕完全不知道关键词怎么拼写,也能把相关的文档段落和代码片一起捞出来。
  • 文件很少的小仓库(几十个文件以内):其实两者都可以不开,原生的 rg 加直接读文件已经足够快,没必要维护额外索引目录。

两者共存时的路由习惯与可直接复用的提示词

如果在全局同时跑过 codegraph install 和 zg install,它们会各自往 CLAUDE.md / AGENTS.md 里写入一段带注释标记的规则块(<!-- CODEGRAPH_START --> 与 <!-- ZVEC_GREP_START -->)。这两段规则是两家各自独立写的,直接并排放在一起会出现三处重叠:

  1. 架构与调用流归属冲突:CodeGraph 要求理解代码时优先用 codegraph_explore,zvec-grep 则把 architecture, or data or control flow 也划给了 zvec_grep_search。同一仓库同时存在两个索引时,Agent 容易两边都查一遍。
  2. 精确字面量与单文件读取冲突:CodeGraph 提示可以直接传文件名/符号名读源码,zvec-grep 要求精确标识符、配置键、报错文本优先走 zvec_grep_rg 或 rg。
  3. 缺少互斥与索引门控:两段规则各自都没有写“第一个工具拿到足够证据就停手,不要再用另一个工具复查”,且 zvec-grep 侧对 .zvec-grep/ 不存在时跳过语义检索的约束不如 CodeGraph 明确。

修改时注意不要直接改注释标记内部的内容,否则下次执行 codegraph install、codegraph upgrade 或 zg install 时改动会被覆盖。更稳的做法是保留两个工具各自生成的标记块不动,在它们外面补一段简短的仲裁规则(Tie-breaker):

## Retrieval Routing (CodeGraph vs zvec-grep vs rg)
When both CodeGraph and zvec-grep are installed in the same environment, resolve overlap with these rules before picking a tool:
1. **Exact text, config keys, filenames, error strings, or regex**: use `zvec_grep_rg` (if listed) or native `Grep`/`rg` first — do not route simple literal lookups through CodeGraph or vector search.
2. **Code structure, symbols, callers/callees, call paths, or change impact** (when `.codegraph/` exists at repo root): use `codegraph_explore` first (even though zvec-grep also mentions architecture and control flow).
3. **Unknown wording, conceptual/semantic discovery, or mixed workspaces with docs/Markdown/configs/data** (when `.zvec-grep/` exists): use `zvec_grep_search` first.
4. **No duplicate retrieval**: if the first tool returns sufficient verbatim source or snippets, stop and answer — do not run the other tool to re-verify the same code unless a specific symbol, dynamic path, or non-code document is still missing.
5. **Respect index presence**: skip CodeGraph if `.codegraph/` is absent, and skip `zvec_grep_search` if `.zvec-grep/` is absent; never create or rebuild either index without explicit user authorization.

贴在两个自动生成块的前面或后面即可,既不会让系统提示词膨胀,也能在两个工具共存时把职责边界锁死。如果你是手动配置而非运行 codegraph install / zg install,下面这份完整三段式模板(仲裁规则 + 两个工具官方默认块)可以直接整段放进 CLAUDE.md 或 AGENTS.md:

展开查看完整三段式参考配置(仲裁规则 + CodeGraph & zvec-grep 官方默认块)
## Retrieval Routing (CodeGraph vs zvec-grep vs rg)
When both CodeGraph and zvec-grep are installed in the same environment, resolve overlap with these rules before picking a tool:
1. **Exact text, config keys, filenames, error strings, or regex**: use `zvec_grep_rg` (if listed) or native `Grep`/`rg` first — do not route simple literal lookups through CodeGraph or vector search.
2. **Code structure, symbols, callers/callees, call paths, or change impact** (when `.codegraph/` exists at repo root): use `codegraph_explore` first (even though zvec-grep also mentions architecture and control flow).
3. **Unknown wording, conceptual/semantic discovery, or mixed workspaces with docs/Markdown/configs/data** (when `.zvec-grep/` exists): use `zvec_grep_search` first.
4. **No duplicate retrieval**: if the first tool returns sufficient verbatim source or snippets, stop and answer — do not run the other tool to re-verify the same code unless a specific symbol, dynamic path, or non-code document is still missing.
5. **Respect index presence**: skip CodeGraph if `.codegraph/` is absent, and skip `zvec_grep_search` if `.zvec-grep/` is absent; never create or rebuild either index without explicit user authorization.
<!-- CODEGRAPH_START -->
## CodeGraph
In repositories indexed by CodeGraph (a `.codegraph/` directory exists at the repo root), reach for it BEFORE grep/find or reading files when you need to understand or locate code:
- **MCP tool** (when available): `codegraph_explore` answers most code questions in one call — the relevant symbols' verbatim source plus the call paths between them, including dynamic-dispatch hops grep can't follow. Name a file or symbol in the query to read its current line-numbered source. If it's listed but deferred, load it by name via tool search.
- **Shell** (always works): `codegraph explore "<symbol names or question>"` prints the same output.
If there is no `.codegraph/` directory, skip CodeGraph entirely — indexing is the user's decision.
<!-- CODEGRAPH_END -->
<!-- ZVEC_GREP_START -->
## zvec-grep
Choose the evidence source before the retrieval mode.
### Workspace evidence
- Use the current workspace as the evidence source when the user asks about local material, prior context establishes it as relevant, or the question concerns how the current project works—even if the workspace is not mentioned explicitly.
- A workspace may contain any mix of code, documents, configuration, and data.
- Do not use workspace retrieval for unrelated open-world questions, current external facts, or web content that does not depend on local evidence.
### Retrieval routing
- When an exact word, phrase, name, date, identifier, filename, path, configuration key, error message, source fragment, literal, or regex is known and locating its occurrences is sufficient, use `zvec_grep_rg` when it is listed by the current host; otherwise native Grep or `rg`.
- Use `zvec_grep_search` when wording or location is unknown, or when the answer requires semantic, conceptual, fuzzy, or paraphrase discovery; relationships, chronology, causality, architecture, or data or control flow; or comparison or synthesis across files, sections, or documents.
- For a mixed task with exact anchors that still requires relationships or cross-file synthesis, call `zvec_grep_search` with the concept and anchors, then use `zvec_grep_rg` when it is listed by the current host; otherwise native Grep or `rg` for focused follow-up.
- When no sufficient exact anchor is available and the user asks whether conceptually related material exists locally, make at most one focused `zvec_grep_search` probe using the question plus distinctive names, dates, or terms. This probe does not apply to exact quotations, configuration keys, filenames, regexes, or exhaustive occurrence requests. Continue only when results are relevant; otherwise stop and report that the indexed workspace did not establish the answer.
- Before broad file reads or delegating workspace discovery, use the appropriate search route. Do not delegate solely to locate material, and stop when the evidence is sufficient.
### Search evidence
- Search results include bounded source snippets. Treat a sufficient snippet as already-read evidence, and read a cited file only when a required detail falls outside the snippet.
### Freshness and index lifecycle
- Pass a daemon-visible absolute `root` on every zvec-grep workspace call.
- Read `freshness` and `background_refresh` from search results without a status preflight.
- When results are `served_from_current_index`, use them when sufficient instead of waiting for the background refresh.
- If the index is missing but exact or regex lookup can answer the task, use `zvec_grep_rg` when it is listed by the current host; otherwise native Grep or `rg`.
- Creating, rebuilding, or dropping a persistent index requires an explicit user request or authorization; never do so silently.
<!-- ZVEC_GREP_END -->

记得顺手把 .codegraph/ 和 .zvec-grep/ 加进全局 .gitignore(或仓库的 .git/info/exclude),避免把本地 SQLite / 向量索引文件误提交到 Git 仓库里。

关于如何把这两个 MCP 接入 Claude Code / Codex,或者直接让 Agent 自己跑完安装和自检流程,可以看上一篇:MCP 实用指南与配置实例:从手动接入到让 Agent 自己装 MCP;两个工具的官方入口也已经收录在 工具箱 的「开发与 AI 工作流」分组中。

输入关键词,搜索全部文章的标题和正文。

↑↓ 选择 Enter 打开 Esc 关闭