From ae7b808c30b2f2b7fc6e5f8b2df81c5860c07f06 Mon Sep 17 00:00:00 2001 From: wehub-resource-sync Date: Mon, 13 Jul 2026 09:51:29 +0000 Subject: [PATCH] docs: make Chinese README the default --- README.md | 548 +++++++++++++++++++++++++----------------------------- 1 file changed, 254 insertions(+), 294 deletions(-) diff --git a/README.md b/README.md index 73e00aa..5041e8f 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,28 @@ + +> [!NOTE] +> 本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。 +> [English](./README.en.md) · [原始项目](https://github.com/colbymchenry/codegraph) · [上游 README](https://github.com/colbymchenry/codegraph/blob/HEAD/README.md) +> 原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。 +
# CodeGraph -## 🎉 1.0 Released! +## 🎉 1.0 已发布! -Already installed? Run `codegraph upgrade` +已安装?运行 `codegraph upgrade` -Follow [@getcodegraph](https://x.com/getcodegraph) on X for updates. +在 X 上关注 [@getcodegraph](https://x.com/getcodegraph) 获取更新。 -### Supercharge Claude Code, Cursor, Codex, OpenCode, Hermes Agent, Gemini, Antigravity, and Kiro with Semantic Code Intelligence +### 用语义代码智能增强 Claude Code、Cursor、Codex、OpenCode、Hermes Agent、Gemini、Antigravity 和 Kiro -**Surgical context · fewer tool calls · faster answers · 100% local** +**精准上下文 · 更少的工具调用 · 更快的回答 · 100% 本地运行** -### [Documentation & Website →](https://colbymchenry.github.io/codegraph/) +### [文档与网站 →](https://colbymchenry.github.io/codegraph/) -[![npm version](https://img.shields.io/npm/v/@colbymchenry/codegraph.svg)](https://www.npmjs.com/package/@colbymchenry/codegraph) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Self-contained](https://img.shields.io/badge/Node.js-bundled%20%C2%B7%20none%20required-brightgreen.svg)](https://nodejs.org/) +[![npm 版本](https://img.shields.io/npm/v/@colbymchenry/codegraph.svg)](https://www.npmjs.com/package/@colbymchenry/codegraph) +[![许可证: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![自包含](https://img.shields.io/badge/Node.js-bundled%20%C2%B7%20none%20required-brightgreen.svg)](https://nodejs.org/) [![Windows](https://img.shields.io/badge/Windows-supported-blue.svg)](#supported-platforms) [![macOS](https://img.shields.io/badge/macOS-supported-blue.svg)](#supported-platforms) @@ -33,42 +39,42 @@ Follow [@getcodegraph](https://x.com/getcodegraph) on X for updates.
-**The CodeGraph platform is coming** — for every PR, know exactly what to test, what could break, which flows are affected, and whether business logic is compromised. +**CodeGraph 平台即将到来** —— 对于每个 PR,精确了解要测试什么、什么可能出错、哪些流程受影响、以及业务逻辑是否被破坏。 -Join the waitlist for early beta access +加入早期 Beta 访问等候名单 -Get early beta access to the hosted product · getcodegraph.com +获取托管产品的早期 Beta 访问权 · getcodegraph.com
-## Contents +## 目录 -- [Get Started](#get-started) -- [Language Support](#language-support) -- [Why CodeGraph?](#why-codegraph) -- [Key Features](#key-features) -- [Framework-aware Routes](#framework-aware-routes) -- [Mixed iOS / React Native / Expo bridging](#mixed-ios--react-native--expo-bridging) -- [Quick Start](#quick-start) -- [How It Works](#how-it-works) -- [CLI Reference](#cli-reference) -- [MCP Tools](#mcp-tools) -- [Library Usage](#library-usage) -- [Configuration](#configuration) -- [Telemetry](#telemetry) -- [Supported Platforms](#supported-platforms) -- [Supported Agents](#supported-agents) -- [Supported Languages](#supported-languages) -- [Measured cross-file coverage](#measured-cross-file-coverage) -- [Troubleshooting](#troubleshooting) -- [Star History](#star-history) -- [License](#license) +- [快速开始](#get-started) +- [语言支持](#language-support) +- [为什么选择 CodeGraph?](#why-codegraph) +- [关键特性](#key-features) +- [框架感知路由](#framework-aware-routes) +- [iOS / React Native / Expo 混合桥接](#mixed-ios--react-native--expo-bridging) +- [快速上手](#quick-start) +- [工作原理](#how-it-works) +- [CLI 参考](#cli-reference) +- [MCP 工具](#mcp-tools) +- [库使用](#library-usage) +- [配置](#configuration) +- [遥测](#telemetry) +- [支持平台](#supported-platforms) +- [支持的 Agent](#supported-agents) +- [支持的语言](#supported-languages) +- [实测跨文件覆盖率](#measured-cross-file-coverage) +- [故障排除](#troubleshooting) +- [Star 历史](#star-history) +- [许可证](#license) -## Get Started +## 快速开始 -### 1. Install the CLI +### 1. 安装 CLI -**No Node.js required** — one command grabs the right build for your OS: +**无需 Node.js** —— 一条命令即可获取适用于你操作系统的正确构建版本: ```bash # macOS / Linux @@ -79,36 +85,36 @@ irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | ```
-Already have Node? Use npm instead (works on any version) +已经有 Node?改用 npm(适用于任意版本) ```bash npm i -g @colbymchenry/codegraph ``` -CodeGraph bundles its own runtime — nothing to compile, no native build, works the same everywhere. The installer puts `codegraph` on your PATH but **doesn't change your current shell** — open a new terminal before the next step so the command resolves. +CodeGraph 自带运行时 —— 无需编译,无原生构建,在任何环境下运行一致。安装程序会将 `codegraph` 添加到 PATH,但不会更改你当前的 shell —— 在下一步之前请打开一个新终端,以便命令能被正确解析。 -**Upgrade any time** with `codegraph upgrade` — it detects how you installed (bundle, npm, or npx) and updates in place. Add `--check` to see if an update is available, or `codegraph upgrade ` to pin one. +**随时升级**,运行 `codegraph upgrade` —— 它会检测你的安装方式(bundle、npm 或 npx)并原地更新。添加 `--check` 查看是否有可用更新,或使用 `codegraph upgrade ` 锁定版本。
-### 2. Wire up your agent(s) +### 2. 连接你的 Agent -In a **new terminal**, run the installer to connect CodeGraph to the agents you use: +在一个**新终端**中,运行安装程序将 CodeGraph 连接到你使用的 Agent: ```bash codegraph install ``` -Detects and auto-configures Claude Code, Cursor, Codex CLI, opencode, Hermes Agent, Gemini CLI, Antigravity IDE, and Kiro — wiring the CodeGraph MCP server into each. **This is the step that connects CodeGraph to your agent;** installing the CLI in step 1 does not do it on its own. It only wires up your agent — it does **not** index any code; building each project's graph is the separate `codegraph init` in step 3. (Shortcut: `npx @colbymchenry/codegraph` downloads and runs this in one go.) +自动检测并配置 Claude Code、Cursor、Codex CLI、opencode、Hermes Agent、Gemini CLI、Antigravity IDE 和 Kiro —— 将 CodeGraph MCP 服务器接入每个 Agent。**这一步是将 CodeGraph 连接到你的 Agent 的关键;** 第 1 步中安装 CLI 并不会自动完成连接。它仅配置 Agent —— 并**不会**索引任何代码;构建每个项目图是第 3 步中独立的 `codegraph init` 命令。(快捷方式:`npx @colbymchenry/codegraph` 会一次性下载并运行全部操作。) -### 3. Initialize each project +### 3. 初始化每个项目 ```bash cd your-project codegraph init ``` -`codegraph init` creates the local `.codegraph/` directory and builds the full graph in the same step — one command, done. +`codegraph init` 会在同一步中创建本地的 `.codegraph/` 目录并构建完整图 —— 一条命令,一步完成。
@@ -116,27 +122,27 @@ codegraph init
-### 4. No more syncing! +### 4. 无需再同步! -Auto-sync is enabled by default. CodeGraph watches the project and updates the graph on every file change — while your agent edits code, or you add, modify, or delete files. **The index is never stale, and there is nothing to re-run.** +自动同步默认启用。CodeGraph 会监视项目,并在每次文件变更时更新图 —— 无论是你的 Agent 编辑代码,还是你添加、修改或删除文件。**索引永不过期,无需重新运行。** -### Uninstall +### 卸载 -Changed your mind? One command removes CodeGraph from every agent it configured **and** the CLI itself — every install it finds (standalone bundle, npm global package, launcher link), shown to you before anything is deleted: +改变主意了?一条命令即可从 CodeGraph 配置过的每个 Agent 中移除 CodeGraph **以及** CLI 本身 —— 它会找到所有已安装的版本(独立 bundle、npm 全局包、启动器链接),并在删除前展示给你: ```bash codegraph uninstall ``` -Pass `--keep-cli` to remove only the agent configurations and keep the CLI installed. +添加 `--keep-cli` 仅移除 Agent 配置而保留 CLI。 -Reverses the installer — strips CodeGraph's MCP server config, instructions, and permissions from each configured agent. Your project indexes (`.codegraph/`) are left untouched; remove those per-project with `codegraph uninit`. Use `--target` to remove from specific agents, or `--yes` to run non-interactively. +反转安装程序 —— 从每个已配置的 Agent 中移除 CodeGraph 的 MCP 服务器配置、指令和权限。你的项目索引(`.codegraph/`)保持不变;每个项目可使用 `codegraph uninit` 单独删除。使用 `--target` 从特定 Agent 中移除,或使用 `--yes` 以非交互方式运行。 --- -## Language Support +## 语言支持 -Every language below gets the same treatment — full structural extraction and cross-file resolution into one graph, no per-language setup: +以下每种语言都获得相同的处理 —— 完整的结构提取和跨文件解析,统一整合到一张图中,无需逐个语言配置:

TypeScript @@ -175,27 +181,27 @@ Every language below gets the same treatment — full structural extraction and Nix

-Per-language details — extensions, frameworks, and what exactly gets extracted — in [Supported Languages](#supported-languages). +各语言的具体说明——扩展、框架以及究竟会提取什么——见 [支持的语言](#supported-languages)。 --- -## Why CodeGraph? +## 为什么选择 CodeGraph? -When an AI agent needs to understand code — to answer a question or make a change — it discovers structure the slow way: grep, glob, and Read, one file at a time, rebuilding call paths and dependencies by hand. That's a pile of tool calls and round-trips before it even starts the real work. +当 AI agent 需要理解代码——回答问题或做出修改——它只能用最慢的方式摸索结构:grep、glob 和 Read,一次一个文件,手工重建调用路径和依赖关系。在真正开始干活之前,就已经堆了一大堆工具调用和往返。 -**CodeGraph hands the agent the exact code it needs in one call.** It's a pre-built knowledge graph of every symbol, call edge, and dependency in your codebase — so instead of crawling files, the agent asks one question and gets back the relevant source, the call paths between those symbols (including dynamic-dispatch hops grep can't follow), and the blast radius of a change. **Surgical context, not a file-by-file search** — which means fewer tool calls and faster answers on every codebase, large or small. +**CodeGraph 一次调用就把 agent 需要的精确代码交给它。** 它是你代码库中每个符号、调用边和依赖关系的预构建知识图谱——因此 agent 不必爬文件,而是问一个问题,就能拿回相关源码、这些符号之间的调用路径(包括 grep 跟不上的动态派发跳转),以及一次变更的影响范围。**精准上下文,而非逐文件搜索**——这意味着无论代码库大小,工具调用更少、回答更快。 token-cost-savings-scale -> **A note on cost:** CodeGraph's win on *every* codebase is precision and speed — fewer tool calls, faster answers. It cuts token and dollar cost too, but those savings are **scale-dependent**: small and noisy on a modest codebase, and material only once a repo is large and tangled — at the scale of a Google or Microsoft monorepo, multiplied by a whole team's daily agent usage — for them to compound into a real line item. On a 500-file project, adopt CodeGraph for the speed; the cost savings show up when the codebase (and the team) gets big. +> **关于成本的说明:** CodeGraph 在*每个*代码库上的优势都是精度与速度——更少的工具调用、更快的回答。它也能降低 token 和美元成本,但这些节省是**随规模变化的**:在规模适中的代码库上小而嘈杂,只有等到仓库又大又缠、达到 Google 或 Microsoft monorepo 那种规模,再乘以整个团队每日的 agent 使用量,才会累积成真正的成本项。在 500 个文件的项目上,采用 CodeGraph 是为了速度;当代码库(和团队)变大时,成本节省才会显现。 -### Benchmark Results +### 基准测试结果 -Tested across **7 real-world open-source codebases** spanning 7 languages, comparing an agent (Claude Code, headless) answering one architecture question **with** and **without** CodeGraph, at the **median of 4 runs per arm**. _Re-validated on Opus 4.8 (2026-06-02), on the current build (`codegraph_explore` as the primary tool)._ +在跨越 7 种语言的 **7 个真实开源代码库**上测试,比较 agent(Claude Code,headless)在**启用**与**未启用** CodeGraph 的情况下回答一个架构问题,**每臂 4 次运行的中位数**。_于 2026-06-02 在 Opus 4.8 上重新验证,使用当前构建(以 `codegraph_explore` 为主要工具)。_ -> **The universal win — every repo, every size: 58% fewer tool calls · 22% faster · file reads cut to ~zero.** +> **普遍收益——每个仓库、每种规模:工具调用减少 58% · 速度提升 22% · 文件读取降至约零。** -The reliable, universal payoff is **surgical context and speed**: CodeGraph collapses the agent's grep/find/Read crawl into a few direct queries — returning the exact methods you asked about even when they're buried in a multi-thousand-line file — so it answers with **near-zero file reads** while the no-CodeGraph agent spends its budget on discovery. The **Tokens** and **Cost** columns are real too, but — as noted above — they're **scale-dependent**: small and noisy per query, compounding into real money only at large-codebase, high-volume scale. +可靠、普遍的回报是**精准上下文与速度**:CodeGraph 把 agent 的 grep/find/Read 爬取压缩成少量直接查询——即使目标方法埋在上千行的文件里,也能返回你问的确切方法——因此它以**近乎零文件读取**作答,而未使用 CodeGraph 的 agent 却把预算花在发现上。**Tokens** 和 **Cost** 列也是真实的,但——如上所述——它们是**随规模变化的**:每次查询在绝对值上小而嘈杂,只有在大代码库、高用量规模下才会累积成真正的钱。 | Codebase | Language | Tool calls | Time | File reads | Tokens | Cost | |----------|----------|------------|------|------------|--------|------| @@ -207,10 +213,10 @@ The reliable, universal payoff is **surgical context and speed**: CodeGraph coll | **Gin** | Go · ~110 | 44% fewer | 24% faster | 1 vs 6 | 23% fewer | 19% cheaper | | **Alamofire** | Swift · ~110 | 58% fewer | 33% faster | 0 vs 9 | 64% fewer | 40% cheaper | -**File reads** = median files the agent opened **with** vs **without** CodeGraph — the surgical-context win in one column. **Tokens** and **Cost** are the same with-vs-without deltas; they're directional (they move run-to-run) and, per query, small in absolute terms — which is why they only become a line item at scale. `codegraph_explore` also collapses redundant interchangeable implementations to signatures, so a response is sized to the *answer* rather than the file count. +**File reads** = agent 在**启用**与**未启用** CodeGraph 时打开文件的中位数——精准上下文收益浓缩在一列。**Tokens** 和 **Cost** 同样是启用 vs 未启用的差值;它们具有方向性(各次运行会波动),且按单次查询的绝对值而言很小——这就是为什么只有在大规模下才会成为成本项。`codegraph_explore` 还会把冗余的可互换实现折叠为签名,因此响应大小按*答案*而非文件数量来定。
-Per-repo breakdown — WITH vs WITHOUT (median of 4) +各仓库明细——WITH vs WITHOUT(4 次中位数) **VS Code** · ~10k files | Metric | WITH cg | WITHOUT cg | Δ | @@ -285,11 +291,11 @@ The reliable, universal payoff is **surgical context and speed**: CodeGraph coll
-Full benchmark details +完整基准测试细节 -**Methodology.** Each arm is `claude -p` (Claude Opus 4.8) run headlessly against the repo with `--strict-mcp-config`: **WITH** = CodeGraph's MCP server enabled, **WITHOUT** = an empty MCP config. Built-in Read/Grep/Bash stay available to both. Same question per repo, **4 runs per arm, median reported**. Cost = the run's `total_cost_usd`; Tokens = total tokens processed (input incl. cached + output); Time = wall-clock; Tool calls = every tool invocation, including those inside any sub-agents the model spawns. Repos cloned at `--depth 1` and indexed by the same CodeGraph build that served them. Re-validated 2026-06-02 on the current build. These numbers are lower than the prior Opus 4.7 validation — not a CodeGraph regression but a stronger native baseline: Opus 4.8 greps/reads efficiently on the main thread instead of fanning out into large Explore-subagent sweeps, so the no-CodeGraph arm is leaner than it used to be. Per-repo numbers move run-to-run with how hard the without-arm thrashes (the median-of-4 smooths it, but tails remain — e.g. Django's without-arm hit $2.71/14m one batch). +**方法论。** 每臂为 `claude -p`(Claude Opus 4.8)headless 运行于仓库,配置 `--strict-mcp-config`:**WITH** = 启用 CodeGraph 的 MCP server,**WITHOUT** = 空 MCP 配置。内置 Read/Grep/Bash 对两臂均可用。每个仓库同一问题,**每臂 4 次运行,报告中位数**。Cost = 该次运行的 `total_cost_usd`;Tokens = 处理的总 token(输入含缓存 + 输出);Time = 挂钟时间;Tool calls = 每次工具调用,包括模型派生的任何 sub-agent 内部的调用。仓库克隆于 `--depth 1`,并由为其提供服务的同一 CodeGraph 构建索引。于 2026-06-02 在当前构建上重新验证。这些数字低于此前 Opus 4.7 验证——并非 CodeGraph 退步,而是更强的原生基线:Opus 4.8 在主线程上高效 grep/read,而不是扇出到大规模 Explore-subagent 扫描,因此 no-CodeGraph 臂比过去更精简。各仓库数字会随 without 臂的折腾程度而次次波动(4 次中位数能平滑,但尾部仍在——例如 Django 的 without 臂某一批达到 $2.71/14m)。 -**Queries:** +**查询:** | Codebase | Query | |----------|-------| | VS Code | "How does the extension host communicate with the main process?" | @@ -300,35 +306,36 @@ The reliable, universal payoff is **surgical context and speed**: CodeGraph coll | Gin | "How does gin route requests through its middleware chain?" | | Alamofire | "How does Alamofire build, send, and validate a request?" | -**Why CodeGraph wins:** with the index available, the agent answers directly — usually one `codegraph_explore` returns the relevant source — and stops, usually with zero file reads. Without it, the agent spends most of its budget on discovery (find/ls/grep) before reading the right code. CodeGraph only helps when queried *directly*, so its instructions steer agents to answer directly rather than delegate exploration to file-reading sub-agents — otherwise a sub-agent reads files regardless and CodeGraph becomes overhead. +**CodeGraph 为何胜出:** 有索引可用时,agent 直接作答——通常一次 `codegraph_explore` 就返回相关源码——然后停止,通常零文件读取。没有它时,agent 把大部分预算花在发现(find/ls/grep)上,然后才读到正确代码。CodeGraph 只有在被*直接*查询时才有帮助,因此其指令引导 agent 直接作答,而不是把探索委托给读文件的 sub-agent——否则 sub-agent 无论如何都会读文件,CodeGraph 就成了开销。 +
--- -## Key Features +## 核心特性 | | | |---|---| -| **Surgical Context** | One tool call returns entry points, related symbols, and code snippets — no slow file-by-file exploration | -| **Full-Text Search** | Find code by name instantly across your entire codebase, powered by FTS5 | -| **Impact Analysis** | Trace callers, callees, and the full impact radius of any symbol before making changes | -| **Always Fresh** | File watcher uses native OS events (FSEvents/inotify/ReadDirectoryChangesW) with debounced auto-sync — the graph stays current as you code, zero config | -| **20+ Languages** | TypeScript, JavaScript, ArkTS, Python, Go, Rust, Java, C#, VB.NET, PHP, Ruby, C, C++, CUDA, Objective-C, Metal, Swift, Kotlin, Scala, Dart, Lua, Luau, R, Nix, Erlang, CFML, COBOL, Solidity, Terraform/OpenTofu, Svelte, Vue, Astro, Liquid, Pascal/Delphi | -| **Framework-aware Routes** | Recognizes web-framework routing files and links URL patterns to their handlers across 17 frameworks | -| **Mixed iOS / React Native / Expo** | Closes cross-language flows that static parsing misses: Swift ↔ ObjC bridging, React Native legacy bridge + TurboModules + Fabric view components, native → JS event emitters, Expo Modules | -| **100% Local** | No data leaves your machine. No API keys. No external services. SQLite database only | +| **精准上下文(Surgical Context)** | 一次工具调用即可返回入口点、相关符号和代码片段——无需缓慢地逐文件探索 | +| **全文搜索(Full-Text Search)** | 借助 FTS5,在整个代码库中按名称即时查找代码 | +| **影响分析(Impact Analysis)** | 在修改前追踪任意符号的调用方、被调用方及完整影响范围 | +| **始终最新(Always Fresh)** | 文件监视器使用原生操作系统事件(FSEvents/inotify/ReadDirectoryChangesW)并配合防抖自动同步——图随你编码实时更新,零配置 | +| **20+ 种语言** | TypeScript、JavaScript、ArkTS、Python、Go、Rust、Java、C#、VB.NET、PHP、Ruby、C、C++、CUDA、Objective-C、Metal、Swift、Kotlin、Scala、Dart、Lua、Luau、R、Nix、Erlang、CFML、COBOL、Solidity、Terraform/OpenTofu、Svelte、Vue、Astro、Liquid、Pascal/Delphi | +| **框架感知路由(Framework-aware Routes)** | 识别 Web 框架路由文件,并在 17 种框架中将 URL 模式与其处理程序关联 | +| **混合 iOS / React Native / Expo** | 补全静态解析会遗漏的跨语言调用链:Swift ↔ ObjC 桥接、React Native 传统桥接 + TurboModules + Fabric 视图组件、原生 → JS 事件发射器、Expo Modules | +| **100% 本地** | 数据不会离开你的机器。无需 API 密钥。无外部服务。仅使用 SQLite 数据库 |
-How auto-syncing works — and why you don't need to run codegraph sync manually +自动同步如何工作——以及为何你无需手动运行 codegraph sync -When your agent (Claude Code, Cursor, Codex, opencode) launches `codegraph serve --mcp`, three layers keep the index in step with your code — and make sure the agent never gets a silent wrong answer in the brief window between an edit and the next sync: +当你的 agent(Claude Code、Cursor、Codex、opencode)启动 `codegraph serve --mcp` 时,三层机制让索引与代码保持同步——并确保 agent 在编辑与下一次同步之间的短暂窗口期内绝不会无声地得到错误答案: -1. **File watcher with debounced auto-sync.** A native FSEvents / inotify / ReadDirectoryChangesW watcher captures every source-file create / modify / delete and triggers a re-index after a debounce window (default `2000ms`, tunable via `CODEGRAPH_WATCH_DEBOUNCE_MS`, clamped to `[100ms, 60s]`). Bursts of edits collapse into a single sync. +1. **带防抖自动同步的文件监视器。** 原生 FSEvents / inotify / ReadDirectoryChangesW 监视器捕获每一次源文件的创建/修改/删除,并在防抖窗口后触发重新索引(默认 `2000ms`,可通过 `CODEGRAPH_WATCH_DEBOUNCE_MS` 调整,上限为 `[100ms, 60s]`)。连续编辑会合并为一次同步。 -2. **Per-file staleness banner.** During the brief debounce window, MCP tool responses that would reference a still-pending file prepend a `⚠️` banner naming it and telling the agent to `Read` it directly. Pending files NOT referenced by the response surface as a small footer instead. Either way, the agent gets an explicit signal — validated with Claude Code, where the agent literally says "Reading the file directly for the live content" before opening it. +2. **按文件的陈旧状态横幅。** 在短暂的防抖窗口内,会引用仍处于待同步状态的文件的 MCP 工具响应,会在开头附加 `⚠️` 横幅,标明该文件并告知 agent 直接 `Read`。响应未引用的待同步文件则显示为小页脚。无论哪种方式,agent 都会收到明确信号——已在 Claude Code 中验证,agent 会在打开文件前明确说出 "Reading the file directly for the live content"。 -3. **Connect-time catch-up.** When the MCP server (re)connects, codegraph runs a fast `(size, mtime)` + content-hash reconciliation against the working tree before answering the first query — so edits made while no MCP server was running (a `git pull` from the terminal, edits from another editor, a previous agent session that exited) get absorbed on the next session's first tool call. +3. **连接时追平。** 当 MCP 服务器(重新)连接时,codegraph 在回答第一个查询前会对工作树执行快速的 `(size, mtime)` + 内容哈希对账——因此在 MCP 服务器未运行期间所做的编辑(来自终端的 `git pull`、其他编辑器的修改、已退出的先前 agent 会话)会在下一次会话的首次工具调用时被吸收。 ``` agent writes src/Widget.ts @@ -338,60 +345,60 @@ agent writes src/Widget.ts → next agent query sees it ``` -**Verify any time** with `codegraph status` (CLI). If anything is pending, you'll see a `### Pending sync:` section naming the files and their edit age. +**随时验证**:使用 `codegraph status`(CLI)。如有待处理项,你会看到 `### Pending sync:` 部分,其中列出文件及其编辑时长。 -The handful of cases where manual `codegraph sync` makes sense: the watcher is disabled (sandboxed environments, or `CODEGRAPH_NO_DAEMON=1`), or you're scripting against the index outside an agent session and want a pre-flight sync at the start of your script. +少数情况下手动 `codegraph sync` 仍有意义:监视器被禁用(沙盒环境,或 `CODEGRAPH_NO_DAEMON=1`),或者你在 agent 会话外针对索引编写脚本,并希望在脚本开始时执行预检同步。 -→ Full deep-dive in [Guides → Indexing a Project](https://colbymchenry.github.io/codegraph/guides/indexing/#stay-fresh-automatically). +→ 完整深入解读见 [指南 → 为项目建立索引](https://colbymchenry.github.io/codegraph/guides/indexing/#stay-fresh-automatically).
--- -## Framework-aware Routes +## 框架感知路由 -CodeGraph detects web-framework routing files and emits `route` nodes linked by `references` edges to their handler classes or functions. Querying callers of a view/controller now surfaces the URL pattern that binds it. +CodeGraph 会检测 Web 框架路由文件,并发出 `route` 节点,通过 `references` 边与其处理类或函数关联。查询视图/控制器的调用方现在会显示绑定它的 URL 模式。 -| Framework | Shapes recognized | +| 框架 | 识别的形态 | |---|---| -| **Django** | `path()`, `re_path()`, `url()`, `include()` in `urls.py` (CBV `.as_view()`, dotted paths) | -| **Flask** | `@app.route('/path', methods=[...])`, blueprint routes | -| **FastAPI** | `@app.get(...)`, `@router.post(...)`, all standard methods | -| **Express** | `app.get(...)`, `router.post(...)` with middleware chains | -| **NestJS** | `@Controller` + `@Get/@Post/...`, GraphQL `@Resolver` + `@Query/@Mutation`, `@MessagePattern`/`@EventPattern`, `@SubscribeMessage` | -| **Laravel** | `Route::get()`, `Route::resource()`, `Controller@action`, tuple syntax | -| **Drupal** | `*.routing.yml` routes (`_controller`, `_form`, entity handlers); `hook_*` implementations in `.module`/`.theme`/`.install`/`.inc` | -| **Rails** | `get '/x', to: 'users#index'`, hash-rocket `=>` syntax | -| **Spring** | `@GetMapping`, `@PostMapping`, `@RequestMapping` on methods | -| **Play** | `GET`/`POST`/… verb routes in `conf/routes` → `Controller.method` actions (Scala + Java) | -| **Gin / chi / gorilla / mux** | `r.GET(...)`, `router.HandleFunc(...)` | +| **Django** | `path()`、`re_path()`、`url()`、`include()`,位于 `urls.py` 中(CBV `.as_view()`、dotted paths) | +| **Flask** | `@app.route('/path', methods=[...])`、blueprint routes | +| **FastAPI** | `@app.get(...)`、`@router.post(...)`,所有标准 HTTP 方法 | +| **Express** | `app.get(...)`、`router.post(...)`,含中间件链 | +| **NestJS** | `@Controller` + `@Get/@Post/...`,GraphQL `@Resolver` + `@Query/@Mutation`,`@MessagePattern`/`@EventPattern`,`@SubscribeMessage` | +| **Laravel** | `Route::get()`、`Route::resource()`、`Controller@action`,元组语法 | +| **Drupal** | `*.routing.yml` routes(`_controller`、`_form`、entity handlers);`hook_*` implementations 位于 `.module`/`.theme`/`.install`/`.inc` | +| **Rails** | `get '/x', to: 'users#index'`,哈希火箭 `=>` 语法 | +| **Spring** | `@GetMapping`、`@PostMapping`、`@RequestMapping`,标注在方法上 | +| **Play** | `GET`/`POST`/… 动词路由,位于 `conf/routes` → `Controller.method` actions(Scala + Java) | +| **Gin / chi / gorilla / mux** | `r.GET(...)`、`router.HandleFunc(...)` | | **Axum / actix / Rocket** | `.route("/x", get(handler))` | -| **ASP.NET** | `[HttpGet("/x")]` attributes on action methods | +| **ASP.NET** | `[HttpGet("/x")]` attributes,标注在 action 方法上 | | **Vapor** | `app.get("x", use: handler)` | -| **React Router** / **SvelteKit** | Route component nodes | -| **Vue Router** / **Nuxt** | `pages/` file-based routes, `server/api/` endpoints, route middleware | -| **Astro** | `src/pages/` file-based routes (`.astro` pages + `.ts` endpoints, `[param]`/`[...rest]` syntax) | +| **React Router** / **SvelteKit** | 路由组件节点 | +| **Vue Router** / **Nuxt** | `pages/` 基于文件的路由、`server/api/` 端点、route middleware | +| **Astro** | `src/pages/` 基于文件的路由(`.astro` pages + `.ts` 端点,`[param]`/`[...rest]` 语法) | --- -## Mixed iOS / React Native / Expo bridging +## 混合 iOS / React Native / Expo 桥接 -Real iOS and React Native codebases live across multiple languages — a Swift caller invokes an Objective-C selector that's been auto-bridged, a JS file calls into a native module via the React Native bridge, a JSX component delegates to a native view manager. Static tree-sitter extraction stops at each language boundary. CodeGraph bridges them so `codegraph_explore` connects the flow end-to-end across the gap — call paths and blast radius cross the boundary instead of stopping at it. +真实的 iOS 与 React Native 代码库横跨多种语言——Swift 调用方调用经自动桥接的 Objective-C 选择器,JS 文件通过 React Native bridge 调用原生模块,JSX 组件委托给原生视图管理器。静态 tree-sitter 提取会在每种语言边界处停止。CodeGraph 将它们桥接起来,使 `codegraph_explore` 跨越鸿沟端到端连接调用链——调用路径与影响半径会跨越边界,而不是在边界处中断。 -| Boundary | JS / Swift side | Native side | How | +| 边界 | JS / Swift 侧 | 原生侧 | 方式 | |---|---|---|---| -| **Swift → ObjC** | Swift `obj.foo(bar:)` | ObjC selector `-fooWithBar:` | `@objc` auto-bridging rules (including init/property/protocol forms) + Cocoa preposition prefixes (`With`/`For`/`By`/`In`/`On`/`At`/…) | -| **ObjC → Swift** | ObjC `[obj fooWithBar:]` | Swift `@objc func foo(bar:)` | Reverse-bridge name candidates; verifies `@objc` exposure from source | -| **React Native legacy bridge** | JS `NativeModules.X.fn(...)` | ObjC `RCT_EXPORT_METHOD` / `RCT_REMAP_METHOD` · Java/Kotlin `@ReactMethod` | Parses macro/annotation declarations to build a JS-name → native-method map | -| **React Native TurboModules** | JS `import M from './NativeM'; M.fn(...)` | Native impl matching the Codegen spec | Treats the `Native.ts` spec interface as ground truth | -| **RN native → JS events** | JS `new NativeEventEmitter(...).addListener('e', cb)` | ObjC `[self sendEventWithName:@"e" body:...]` · Swift `sendEvent(withName: "e", ...)` · Java/Kotlin `.emit("e", ...)` | Synthesized cross-language event channel keyed by literal event name | -| **Expo Modules** | JS `requireNativeModule('X').fn(...)` | Swift / Kotlin `Module { Name("X"); AsyncFunction("fn") { ... } }` | Parses the Expo DSL literals; synthetic method nodes resolve via existing name-match | -| **Fabric view components** | JSX `` | TS Codegen spec + native impl class | Spec → `component` node; convention-based name+suffix lookup (`View`/`ComponentView`/`Manager`/`ViewManager`) bridges to native | -| **Legacy Paper view managers** | JSX `` | ObjC `RCT_EXPORT_VIEW_PROPERTY` · Java/Kotlin `@ReactProp` | Same as Fabric — Paper-era declarations also produce `component` + `property` nodes | +| **Swift → ObjC** | Swift `obj.foo(bar:)` | ObjC selector `-fooWithBar:` | `@objc` auto-bridging rules(含 init/property/protocol 形式)+ Cocoa preposition prefixes(`With`/`For`/`By`/`In`/`On`/`At`/…) | +| **ObjC → Swift** | ObjC `[obj fooWithBar:]` | Swift `@objc func foo(bar:)` | 反向桥接名称候选;从源码验证 `@objc` exposure | +| **React Native legacy bridge** | JS `NativeModules.X.fn(...)` | ObjC `RCT_EXPORT_METHOD` / `RCT_REMAP_METHOD` · Java/Kotlin `@ReactMethod` | 解析宏/注解声明以构建 JS 名称 → 原生方法映射 | +| **React Native TurboModules** | JS `import M from './NativeM'; M.fn(...)` | 与 Codegen 规范匹配的原生实现 | 将 `Native.ts` spec interface 视为权威依据 | +| **RN native → JS events** | JS `new NativeEventEmitter(...).addListener('e', cb)` | ObjC `[self sendEventWithName:@"e" body:...]` · Swift `sendEvent(withName: "e", ...)` · Java/Kotlin `.emit("e", ...)` | 以字面事件名作为键的合成跨语言事件通道 | +| **Expo Modules** | JS `requireNativeModule('X').fn(...)` | Swift / Kotlin `Module { Name("X"); AsyncFunction("fn") { ... } }` | 解析 Expo DSL 字面量;合成方法节点通过现有名称匹配解析 | +| **Fabric view components** | JSX `` | TS Codegen spec + native impl class | Spec → `component` 节点;基于约定的名称+后缀查找(`View`/`ComponentView`/`Manager`/`ViewManager`)桥接到原生侧 | +| **Legacy Paper view managers** | JSX `` | ObjC `RCT_EXPORT_VIEW_PROPERTY` · Java/Kotlin `@ReactProp` | 与 Fabric 相同——Paper 时代的声明同样会生成 `component` + `property` 节点 | -**Validated on real codebases** (small + medium + large for each bridge): +**已在真实代码库上验证**(每种桥接均有小型 + 中型 + 大型项目): -| Bridge | Small | Medium | Large | +| 桥接 | 小型 | 中型 | 大型 | |---|---|---|---| | Swift ↔ ObjC | [Charts](https://github.com/danielgindi/Charts) | [realm-swift](https://github.com/realm/realm-swift) | [Wikipedia-iOS](https://github.com/wikimedia/wikipedia-ios) | | RN legacy bridge | [AsyncStorage](https://github.com/react-native-async-storage/async-storage) | [react-native-svg](https://github.com/software-mansion/react-native-svg) | [react-native-firebase](https://github.com/invertase/react-native-firebase) | @@ -399,28 +406,28 @@ Real iOS and React Native codebases live across multiple languages — a Swift c | Expo Modules | expo-haptics | expo-camera | expo SDK sweep (7 packages) | | Fabric / Paper views | [react-native-segmented-control](https://github.com/react-native-segmented-control/segmented-control) | [react-native-screens](https://github.com/software-mansion/react-native-screens) | [react-native-skia](https://github.com/Shopify/react-native-skia) | -Each bridge emits edges tagged `provenance:'heuristic'` with `metadata.synthesizedBy:` set to a stable channel name (e.g. `swift-objc-bridge`, `rn-event-channel`, `fabric-native-impl`, `expo-module-extract`), so the agent can tell at a glance how a hop got into the graph. +每个桥接器会发出带有 `provenance:'heuristic'` 标签的边,并将 `metadata.synthesizedBy:` 设置为稳定的通道名称(例如 `swift-objc-bridge`、`rn-event-channel`、`fabric-native-impl`、`expo-module-extract`),以便智能体一目了然地看出某个跳转是如何进入图的。 --- -## Quick Start +## 快速开始 -### 1. Run the Installer +### 1. 运行安装程序 ```bash npx @colbymchenry/codegraph ``` -The installer will: -- Ask which agent(s) to configure — auto-detects installed ones from: **Claude Code**, **Cursor**, **Codex CLI**, **opencode**, **Hermes Agent**, **Gemini CLI**, **Antigravity IDE**, **Kiro** -- Prompt to install `codegraph` on your PATH (so agents can launch the MCP server) -- Ask whether configs apply to all your projects or just this one -- Write each chosen agent's MCP server config, plus a small marker-fenced CodeGraph section in the agent's instructions file (`CLAUDE.md` / `AGENTS.md` / `GEMINI.md`) — that's how subagents and non-MCP agents learn the `codegraph explore` command, since the MCP server's own guidance only reaches the main agent. Removed cleanly by `codegraph uninstall`. -- Set up auto-allow permissions when Claude Code is one of the targets +安装程序将会: +- 询问要配置哪些智能体——自动检测已安装的:**Claude Code**、**Cursor**、**Codex CLI**、**opencode**、**Hermes Agent**、**Gemini CLI**、**Antigravity IDE**、**Kiro** +- 提示将 `codegraph` 安装到 PATH(以便智能体可以启动 MCP 服务器) +- 询问配置是应用于所有项目还是仅当前项目 +- 为每个所选智能体写入 MCP 服务器配置,并在智能体的说明文件中写入一小段带标记围栏的 CodeGraph 章节(`CLAUDE.md` / `AGENTS.md` / `GEMINI.md`)——子智能体和非 MCP 智能体正是通过这种方式学习 `codegraph explore` 命令,因为 MCP 服务器自身的指引只能到达主智能体。可通过 `codegraph uninstall` 干净地移除。 +- 当目标包含 Claude Code 时,设置自动允许权限 -The installer **wires up your agents only — it does not index your code.** After it finishes, build each project's graph yourself with `codegraph init` (step 3). One global `codegraph install` covers every project; you run `codegraph init` once per project. +安装程序**仅连接你的智能体——不会为代码建立索引。**完成后,请用 `codegraph init` 自行构建每个项目的图(步骤 3)。一个全局 `codegraph install` 覆盖所有项目;每个项目运行一次 `codegraph init`。 -**Non-interactive (scripting / CI):** +**非交互式(脚本/CI):** ```bash codegraph install --yes # auto-detect agents, install global @@ -429,38 +436,38 @@ codegraph install --target=auto --location=local # detected agents, project- codegraph install --print-config codex # print snippet, no file writes ``` -| Flag | Values | Default | +| 标志 | 取值 | 默认值 | |---|---|---| -| `--target` | `auto`, `all`, `none`, or csv (`claude,cursor,...`) | prompt | -| `--location` | `global`, `local` | prompt | -| `--yes` | (boolean) | prompt every step | -| `--no-permissions` | (boolean) skip Claude auto-allow list | permissions on | -| `--print-config ` | dump snippet for one agent and exit | — | +| `--target` | `auto`、`all`、`none`,或 csv(`claude,cursor,...`) | prompt | +| `--location` | `global`、`local` | prompt | +| `--yes` | (布尔值) | 每步均提示 | +| `--no-permissions` | (布尔值)跳过 Claude 自动允许列表 | 权限开启 | +| `--print-config ` | 导出单个智能体的代码片段后退出 | — | -### 2. Restart Your Agent +### 2. 重启智能体 -Restart your agent (Claude Code / Cursor / Codex CLI / opencode / Hermes Agent / Gemini CLI / Antigravity IDE / Kiro) for the MCP server to load. +重启你的智能体(Claude Code / Cursor / Codex CLI / opencode / Hermes Agent / Gemini CLI / Antigravity IDE / Kiro),以加载 MCP 服务器。 -### 3. Initialize Projects +### 3. 初始化项目 ```bash cd your-project codegraph init ``` -Builds the per-project knowledge graph index, which then auto-syncs on every file change. A single global `codegraph install` works in every project you open — no need to re-run the installer per project. +构建按项目的知识图谱索引,之后会在每次文件变更时自动同步。单个全局 `codegraph install` 在你打开的每个项目中都可用——无需为每个项目重新运行安装程序。 -That's it — your agent will use CodeGraph tools automatically when a `.codegraph/` directory exists. +就是这样——当存在 `.codegraph/` 目录时,你的智能体会自动使用 CodeGraph 工具。
-Manual Setup (Alternative) +手动设置(替代方案) -**Install globally:** +**全局安装:** ```bash npm install -g @colbymchenry/codegraph ``` -**Add to `~/.claude.json`:** +**添加到 `~/.claude.json`:** ```json { "mcpServers": { @@ -473,7 +480,7 @@ npm install -g @colbymchenry/codegraph } ``` -**Add to `~/.claude/settings.json` (optional, for auto-allow):** +**添加到 `~/.claude/settings.json`(可选,用于自动允许):** ```json { "permissions": { @@ -484,27 +491,27 @@ npm install -g @colbymchenry/codegraph } ``` -One wildcard auto-approves every CodeGraph tool — `codegraph_explore` is the only one listed by default, but if you re-enable others via `CODEGRAPH_MCP_TOOLS` they're already permitted, no prompt. +一个通配符即可自动批准所有 CodeGraph 工具——默认仅列出 `codegraph_explore`,但若你通过 `CODEGRAPH_MCP_TOOLS` 重新启用其他工具,它们也已获准,无需提示。
-Agent Tool Guidance +智能体工具指引 -CodeGraph's MCP server delivers its usage guidance to your agent **automatically**, in the MCP `initialize` response. In short, it tells the agent to: +CodeGraph 的 MCP 服务器会**自动**通过 MCP `initialize` 响应向你的智能体提供使用指引。简而言之,它告诉智能体: -- **Answer structural questions directly with CodeGraph** — it *is* the pre-built index, so a grep/read loop just repeats work it already did. Treat the returned source as already read. -- **Reach for `codegraph_explore` for almost anything** — "how does X work", a flow/"how does X reach Y", or surveying an area. One call returns the relevant symbols' verbatim source grouped by file, the call paths between them (dynamic-dispatch hops included), and a blast-radius summary. Name a file or symbol in the query to read its current line-numbered source. -- **Trust the results — don't re-verify with grep**, and check the staleness banner after edits. -- Works **per project**: query any project that has a `.codegraph/` index by passing `projectPath` — so a monorepo where only some services are indexed, or a second repo, works in one session. A path with no index returns clean guidance to use built-in tools; indexing stays your decision. +- **直接用 CodeGraph 回答结构性问题**——它*就是*预构建的索引,因此 grep/read 循环只是在重复它已完成的工作。将返回的源码视为已读。 +- **几乎所有情况都优先使用 `codegraph_explore`**——例如“X 如何工作”、流程/“X 如何到达 Y”,或调研某个区域。一次调用即可返回相关符号的逐字源码(按文件分组)、它们之间的调用路径(含动态分派跳转),以及影响范围摘要。在查询中指定文件或符号即可读取其当前带行号的源码。 +- **信任结果——不要用 grep 重新验证**,并在编辑后查看陈旧性横幅。 +- **按项目工作**:通过传入 `projectPath`,可查询任何已建立 `.codegraph/` 索引的项目——因此,在仅部分服务已索引的 monorepo 或第二个仓库中,单次会话即可工作。没有索引的路径会返回清晰指引以使用内置工具;是否建立索引仍由你决定。 -The exact text is `src/mcp/server-instructions.ts` — the single source of truth for the main agent. Because subagents and non-MCP harnesses never see the MCP guidance, the installer also writes a short marker-fenced section into the agent's instructions file pointing at the `codegraph explore` CLI equivalent. +确切文本为 `src/mcp/server-instructions.ts`——主智能体的唯一事实来源。由于子智能体和非 MCP 工具链看不到 MCP 指引,安装程序还会在智能体说明文件中写入一小段带标记围栏的章节,指向 `codegraph explore` CLI 等价物。
--- -## How It Works +## 工作原理 ``` ┌───────────────────────────────────────────────────────────────────┐ @@ -527,17 +534,17 @@ The exact text is `src/mcp/server-instructions.ts` — the single source of trut └───────────────────────────────────────────────────────────────────┘ ``` -1. **Extraction** — [tree-sitter](https://tree-sitter.github.io/) parses source code into ASTs. Language-specific queries extract nodes (functions, classes, methods) and edges (calls, imports, extends, implements). +1. **提取** — [tree-sitter](https://tree-sitter.github.io/) 将源代码解析为 AST。特定于语言的查询会提取节点(函数、类、方法)和边(调用、导入、继承、实现)。 -2. **Storage** — Everything goes into a local SQLite database (`.codegraph/codegraph.db`) with FTS5 full-text search. +2. **存储** — 所有内容存入本地 SQLite 数据库(`.codegraph/codegraph.db`),并支持 FTS5 全文搜索。 -3. **Resolution** — After extraction, references are resolved: function calls → definitions, imports → source files, class inheritance, and framework-specific patterns. +3. **解析** — 提取完成后解析引用:函数调用 → 定义、导入 → 源文件、类继承,以及框架特定模式。 -4. **Auto-Sync** — The MCP server watches your project using native OS file events. Changes are debounced (2-second quiet window), filtered to source files only, and incrementally synced. The graph stays fresh as you code — no configuration needed. +4. **自动同步** — MCP 服务器使用原生操作系统文件事件监听项目。变更会经过去抖(2 秒静默窗口)、仅过滤源文件,并增量同步。图谱会随你编码保持最新——无需配置。 --- -## CLI Reference +## CLI 参考 ```bash codegraph # Run interactive installer @@ -566,7 +573,7 @@ codegraph help [command] # Show help, optionally for one command ### `codegraph affected` -Traces import dependencies transitively to find which test files are affected by changed source files. +传递性地追踪 import 依赖,以找出哪些测试文件会受到已变更源文件的影响。 ```bash codegraph affected src/utils.ts src/api.ts # Pass files as arguments @@ -576,13 +583,13 @@ codegraph affected src/auth.ts --filter "e2e/*" # Custom test file pattern | Option | Description | Default | |--------|-------------|---------| -| `--stdin` | Read file list from stdin | `false` | -| `-d, --depth ` | Max dependency traversal depth | `5` | -| `-f, --filter ` | Custom glob to identify test files | auto-detect | -| `-j, --json` | Output as JSON | `false` | -| `-q, --quiet` | Output file paths only | `false` | +| `--stdin` | 从 stdin 读取文件列表 | `false` | +| `-d, --depth ` | 依赖遍历的最大深度 | `5` | +| `-f, --filter ` | 用于识别测试文件的自定义 glob | auto-detect | +| `-j, --json` | 以 JSON 格式输出 | `false` | +| `-q, --quiet` | 仅输出文件路径 | `false` | -**CI/hook example:** +**CI/hook 示例:** ```bash #!/usr/bin/env bash @@ -596,23 +603,21 @@ fi ## MCP Tools -When running as an MCP server, CodeGraph exposes a **single tool** — `codegraph_explore`. Measured agent behavior showed that one strong tool steers agents better than a menu of narrower ones — fewer mis-picks, and it saves context every session: +作为 MCP 服务器运行时,CodeGraph 仅暴露**一个工具** — `codegraph_explore`。实测的 agent 行为表明,一个强大的工具比一堆更窄的工具更能引导 agent — 误选更少,且每个会话都能节省上下文: | Tool | Purpose | |------|---------| -| `codegraph_explore` | Answer almost any question in one call — "how does X work", a flow ("how does X reach Y"), or surveying an area — returning the relevant symbols' verbatim source grouped by file, plus the call paths between them and a blast-radius summary. Surfaces dynamic-dispatch hops (callbacks, React re-render, interface→impl) grep can't follow. Name a file or symbol in the query to read its current line-numbered source, the same shape the Read tool gives you. | +| `codegraph_explore` | 一次调用即可回答几乎所有问题 — 例如「X 是如何工作的」、某个流程(「X 如何到达 Y」),或调研某个区域 — 返回按文件分组的、相关符号的逐字源代码,以及它们之间的调用路径和影响范围(blast-radius)摘要。可呈现 grep 无法跟进的动态分派跳转(回调、React 重渲染、interface→impl)。在查询中指定文件或符号,即可读取其带当前行号的源代码,格式与 Read 工具返回的一致。 | -The other tools (`codegraph_node`, `codegraph_search`, `codegraph_callers`, `codegraph_callees`, `codegraph_impact`, `codegraph_files`, `codegraph_status`) stay fully functional but **unlisted by default** — everything they return already arrives inline on `codegraph_explore` (its blast-radius section, the relationship map, a symbol's body as its callee list). Re-enable any of them for the MCP surface with the `CODEGRAPH_MCP_TOOLS` environment variable (e.g. `CODEGRAPH_MCP_TOOLS=explore,node,search,callers`), or use their CLI equivalents (`codegraph node` / `query` / `callers` / `callees` / `impact` / `files` / `status`). +其他工具(`codegraph_node`、`codegraph_search`、`codegraph_callers`、`codegraph_callees`、`codegraph_impact`、`codegraph_files`、`codegraph_status`)仍完全可用,但**默认不列出** — 它们返回的一切内容已内联出现在 `codegraph_explore` 中(其影响范围部分、关系图、符号体即其被调用方列表)。可通过 `CODEGRAPH_MCP_TOOLS` 环境变量(例如 `CODEGRAPH_MCP_TOOLS=explore,node,search,callers`)在 MCP 界面中重新启用其中任意一个,或使用其 CLI 等价命令(`codegraph node` / `query` / `callers` / `callees` / `impact` / `files` / `status`)。 -Even when the server's own root has no `.codegraph/` index, the tools stay available: pass `projectPath` to query any indexed project — a sub-service in a monorepo, or a second repo — in the same session. A path that has no index returns clean guidance to use built-in tools instead, so nothing fails loudly, and indexing stays your decision. +即使服务器自身的根目录没有 `.codegraph/` 索引,工具仍可用:传入 `projectPath` 即可在同一会话中查询任意已索引项目 — 单体仓库中的子服务,或第二个仓库。没有索引的路径会返回清晰指引,建议使用内置工具,因此不会大声报错,索引与否仍由你决定。 --- ## Library Usage -CodeGraph can be embedded directly. The npm package re-exports its programmatic -API, so both `import` and `require` resolve the `CodeGraph` class in your own -process — handy for embedding it in an app (e.g. an Electron main process). +CodeGraph 可直接嵌入。npm 包会重新导出其编程式 API,因此 `import` 和 `require` 都会在你自己的进程中解析出 `CodeGraph` 类 — 便于嵌入应用(例如 Electron 主进程)。 ```typescript import CodeGraph from '@colbymchenry/codegraph'; @@ -636,51 +641,29 @@ cg.unwatch(); // stop watching cg.close(); ``` -Lower-level building blocks are exported from the same entry point for callers -that drive the graph directly: `DatabaseConnection`, `QueryBuilder`, -`getDatabasePath`, `initGrammars` / `loadGrammarsForLanguages`, and `FileLock`. +更低层的构建块从同一入口点导出,供直接驱动图的调用方使用:`DatabaseConnection`、`QueryBuilder`、`getDatabasePath`、`initGrammars` / `loadGrammarsForLanguages`,以及 `FileLock`。 -**Embedding requirements** +**嵌入要求** -- Install from npm (`npm i @colbymchenry/codegraph`) so the matching - per-platform package — which carries the compiled library and its - dependencies — is fetched alongside the shim. -- The API runs on **your** runtime, so it needs **Node 22.5+** for the built-in - `node:sqlite` (Electron qualifies when its bundled Node is 22.5+). The CLI and - MCP server are unaffected — they run on the self-contained bundled runtime. -- TypeScript types ship with the package. As with any Node-targeting library, - keep `@types/node` available and `skipLibCheck: true` (the common default). +- 从 npm 安装(`npm i @colbymchenry/codegraph`),以便一并拉取匹配的各平台包 — 其中包含已编译库及其依赖 — 与 shim 一起安装。 +- API 运行在**你的**运行时上,因此需要 **Node 22.5+** 以使用内置的 `node:sqlite`(Electron 在其捆绑的 Node 为 22.5+ 时同样满足)。CLI 和 MCP 服务器不受影响 — 它们运行在自包含的捆绑运行时上。 +- TypeScript 类型随包提供。与任何面向 Node 的库一样,请保持 `@types/node` 可用,并设置 `skipLibCheck: true`(常见默认值)。 --- ## Configuration -Next to none — CodeGraph is **zero-config by default**, with nothing to write or -keep in sync to get started. Language support is automatic from the file -extension; there's nothing to wire up per language. The one optional file is for -mapping [custom file extensions](#custom-file-extensions). +几乎无需配置 — CodeGraph **默认零配置**,无需编写或同步任何内容即可上手。语言支持根据文件扩展名自动识别;无需按语言单独接线。唯一可选的文件用于映射[自定义文件扩展名](#custom-file-extensions)。 -What it skips out of the box: +开箱即会跳过: -- **Dependency, build, and cache directories** — `node_modules`, `vendor`, - `dist`, `build`, `target`, `.venv`, `Pods`, `.next`, and the like across every - [supported stack](#supported-languages) — so the graph is your code, not - third-party noise. This holds even with no `.gitignore`. -- **Anything in your `.gitignore`** — honored in git repos via git, and in - non-git projects by reading `.gitignore` directly (root and nested). -- **Files larger than 1 MB** — generated bundles, minified JS, vendored blobs. +- **依赖、构建与缓存目录** — `node_modules`、`vendor`、`dist`、`build`、`target`、`.venv`、`Pods`、`.next` 等,覆盖所有[受支持的技术栈](#supported-languages) — 使图谱反映的是你的代码,而非第三方噪音。即使没有 `.gitignore` 也如此。 +- **`.gitignore` 中的任何内容** — 在 git 仓库中通过 git 生效,在非 git 项目中则直接读取 `.gitignore`(根目录及嵌套)。 +- **大于 1 MB 的文件** — 生成的 bundle、压缩后的 JS、vendor 大文件。 -To keep something else out, add it to `.gitignore`. To pull a default-excluded -directory back **in** (say you really do want a vendored dependency indexed), -add a negation — `!vendor/`. The defaults apply uniformly, so committing a -dependency or build directory doesn't force it into the graph; the `.gitignore` -negation is the explicit opt-in. +若要排除其他内容,请将其加入 `.gitignore`。若要将默认排除的目录**重新纳入**(比如你确实希望索引某个 vendor 依赖),请添加否定规则 — `!vendor/`。默认规则统一适用,因此提交依赖或构建目录并不会强制将其纳入图谱;`.gitignore` 否定规则才是显式选择加入的方式。 -`.gitignore` can't drop a directory you've **committed**, though. For a vendored -theme or SDK that's checked into the repo (e.g. a Metronic theme under -`static/`), list it under `exclude` in `codegraph.json` — gitignore-style -patterns, matched against repo-root-relative paths, honored on index, sync, and -watch: +不过 `.gitignore` 无法排除你已**提交**的目录。对于已检入仓库的 vendor 主题或 SDK(例如 `static/` 下的 Metronic 主题),请在 `codegraph.json` 的 `exclude` 下列出 — 采用 gitignore 风格模式,按相对仓库根的路径匹配,在索引、同步与监听时生效: ```json { @@ -688,10 +671,7 @@ watch: } ``` -Conversely, when real source is gitignored on purpose — a project under a second -VCS (SVN, Perforce) that `.gitignore`s its own source so it stays out of Git — -force it back in with `include` (the opposite of `exclude`; `includeIgnored` -only revives embedded git repos, not plain source): +反之,当真实源码被有意 gitignore — 例如某个项目使用第二种 VCS(SVN、Perforce),由 `.gitignore` 管理其源码以使其不进入 Git — 可用 `include` 强制纳入(与 `exclude` 相反;`includeIgnored` 仅恢复嵌入式 git 仓库,而非普通源码): ```json { @@ -699,16 +679,11 @@ only revives embedded git repos, not plain source): } ``` -CodeGraph discovers those files off disk, overriding `.gitignore`, on index, -sync, and watch. An explicit `exclude` still wins, and built-in skips -(`node_modules`, `dist`, `.git`) are never re-included. +CodeGraph 会从磁盘发现这些文件,在索引、同步与监听时覆盖 `.gitignore`。显式的 `exclude` 仍然优先,内置跳过项(`node_modules`、`dist`、`.git`)永远不会被重新纳入。 ### Custom file extensions -If your project uses a non-standard extension for a [supported -language](#supported-languages) — say `.dota_lua` for Lua, or `.tpl` for PHP — -those files are skipped by default, because the extension isn't one CodeGraph -recognizes. Map them with an optional **`codegraph.json`** at your project root: +若项目对[受支持的语言](#supported-languages)使用非标准扩展名 — 例如 Lua 用 `.dota_lua`,PHP 用 `.tpl` — 这些文件默认会被跳过,因为 CodeGraph 不识别该扩展名。可在项目根目录用可选的 **`codegraph.json`** 进行映射: ```json { @@ -719,48 +694,33 @@ recognizes. Map them with an optional **`codegraph.json`** at your project root: } ``` -Each value is a supported language id. The mappings merge on top of the built-in -defaults and win on conflict, so you can also re-point a built-in (e.g. -`".h": "cpp"`). Commit the file to share the mapping with your team. A typo'd -language or a malformed file is warned about and skipped — it never breaks -indexing — and a project with no `codegraph.json` behaves exactly as before. -Re-index (`codegraph index`) after adding or changing mappings. +每个值为受支持的语言 id。映射会合并到内置默认值之上,冲突时以映射为准,因此也可重定向内置映射(例如 `".h": "cpp"`)。提交该文件即可与团队共享映射。拼写错误的语言或格式错误的文件会收到警告并被跳过 — 不会破坏索引 — 没有 `codegraph.json` 的项目行为与之前完全一致。添加或修改映射后请重新索引(`codegraph index`)。 ## Telemetry -CodeGraph collects **anonymous usage statistics** — which tools and commands get -used, which languages get indexed — to guide where language and agent support -work goes. **Never** any code, paths, file or symbol names, queries, or IP -addresses; usage is aggregated locally into daily totals before anything is -sent, and the ingest endpoint is [public code in this repo](telemetry-worker/) -that enforces the documented field list. The installer asks up front; turn it -off any time: +CodeGraph 会收集**匿名使用统计** — 哪些工具与命令被使用、哪些语言被索引 — 以指导语言与 agent 支持工作的投入方向。**绝不**包含任何代码、路径、文件或符号名、查询或 IP 地址;使用数据在本地聚合为每日总量后才会发送,接收端点是[本仓库中的公开代码](telemetry-worker/),并强制执行文档化的字段列表。安装程序会事先询问;可随时关闭: ```bash codegraph telemetry off # or: CODEGRAPH_TELEMETRY=0, or DO_NOT_TRACK=1 ``` -[`TELEMETRY.md`](TELEMETRY.md) lists every field, with the off-switches and the -full data-handling story. +[`TELEMETRY.md`](TELEMETRY.md) 列出了每个字段、关闭开关以及完整的数据处理说明。 -## Supported Platforms +## 支持的平台 -Every release ships a self-contained build (bundled Node runtime — nothing to -compile) for all three desktop OSes, on both Intel/AMD (x64) and ARM (arm64): +每个版本都会为全部三种桌面操作系统提供自包含构建(捆绑 Node 运行时 — 无需编译),同时支持 Intel/AMD (x64) 和 ARM (arm64): -| Platform | Architectures | Install | +| 平台 | 架构 | 安装 | |----------|---------------|---------| -| Windows | x64, arm64 | PowerShell installer or npm | -| macOS | x64, arm64 | shell installer or npm | -| Linux | x64, arm64 | shell installer or npm | +| Windows | x64, arm64 | PowerShell 安装器或 npm | +| macOS | x64, arm64 | shell 安装器或 npm | +| Linux | x64, arm64 | shell 安装器或 npm | -See [Get Started](#get-started) for the one-line install commands. +一行安装命令请参见 [Get Started](#get-started)。 -## Supported Agents +## 支持的 Agent -The interactive installer auto-detects and configures each of these — wiring up -the MCP server (which delivers its own usage guidance, so no instructions file -is written): +交互式安装程序会自动检测并配置以下各项 — 连接 MCP 服务器(该服务器自带使用指南,因此不会写入说明文件): - **Claude Code** - **Cursor** @@ -771,50 +731,50 @@ is written): - **Antigravity IDE** - **Kiro** -## Supported Languages +## 支持的语言 -| Language | Extension | Status | +| 语言 | 扩展名 | 状态 | |----------|-----------|--------| -| TypeScript | `.ts`, `.tsx` | Full support | -| JavaScript | `.js`, `.jsx`, `.mjs` | Full support | -| ArkTS (HarmonyOS) | `.ets` | Full support (everything TypeScript has, plus `@Component`/`@ComponentV2` structs with their ArkUI decorators (`@State`/`@Prop`/`@Link`/`@Local`/`@Builder`/…), `build()` view trees — parent→child component edges, chained-attribute links to `@Extend`/`@Styles` functions, `.onClick(this.handler)` event bindings — dynamic-dispatch bridges for state→`build()` re-renders, `@ohos.events.emitter` emit→subscriber pairs (static event keys only), and `router.pushUrl` literal urls → the target page struct; ohpm workspace modules resolve bare `import { X } from "data"` through `oh-package.json5` `file:` dependencies, honoring each module's `main` entry) | -| Python | `.py` | Full support | -| Go | `.go` | Full support | -| Rust | `.rs` | Full support | -| Java | `.java` | Full support | -| C# | `.cs` | Full support | -| PHP | `.php` | Full support | -| Ruby | `.rb` | Full support | -| C | `.c`, `.h` | Full support | -| C++ | `.cpp`, `.hpp`, `.cc` | Full support | -| Objective-C | `.m`, `.mm`, `.h` | Partial support (classes, protocols, methods, `@property`, `#import`, message sends; `.mm` ObjC++ may parse incompletely) | -| Metal | `.metal` | Full support (vertex/fragment/kernel functions, structs, type aliases, call edges — MSL parses as C++, with `[[attribute]]` annotations handled) | -| CUDA | `.cu`, `.cuh` | Full support (kernels and device/host functions, structs, classes, host→kernel call edges through `<<>>` launch syntax — templated launches, function-pointer launches (`auto kernel = &fn<...>`), `dim3{...}` configs, and macro-defined kernels included; `__global__`/`__device__`/`__launch_bounds__` specifiers handled; CUDA in plain `.h`/`.hpp` headers recognized by content) | -| Swift | `.swift` | Full support | -| Kotlin | `.kt`, `.kts` | Full support | -| Scala | `.scala`, `.sc` | Full support (classes, traits, methods, type aliases, Scala 3 enums) | -| Dart | `.dart` | Full support | -| Svelte | `.svelte` | Full support (script extraction, Svelte 5 runes, SvelteKit routes) | -| Vue | `.vue` | Full support (script + script-setup extraction, Nuxt page/API/middleware routes) | -| Astro | `.astro` | Full support (frontmatter + script extraction, template component/call references, `src/pages/` routes) | -| Liquid | `.liquid` | Full support | -| Pascal / Delphi | `.pas`, `.dpr`, `.dpk`, `.lpr` | Full support (classes, records, interfaces, enums, DFM/FMX form files) | -| Lua | `.lua` | Full support (functions, methods with receivers, local variables, `require` imports, call edges) | -| R | `.R` `.r` | Full support (functions in every assignment form, S4/R5/R6 classes with methods, `library`/`require` imports, `source()` file references, call edges) | -| Luau | `.luau` | Full support (everything in Lua, plus `type`/`export type` aliases, typed signatures, and Roblox instance-path `require`) | -| CFML | `.cfc`, `.cfm`, `.cfs` | Full support (tag-based ``/`` and bare-script `component { ... }` styles, `extends`/`implements`, embedded `` delegation, call edges) | -| COBOL | `.cbl`, `.cob`, `.cpy` | Full support (programs, sections/paragraphs with PERFORM/GO TO call edges, CALL 'literal' cross-program calls, COPY copybook imports — including standalone `.cpy` files — DATA DIVISION records/fields/88-levels, EXEC CICS LINK/XCTL and EXEC SQL INCLUDE targets; fixed and free format) | -| Visual Basic .NET | `.vb` | Full support (classes, Modules, interfaces, structures, enums, properties, events, `Declare` P/Invoke, `Handles`/`WithEvents`, `Inherits`/`Implements` edges, call edges through VB's call/index paren ambiguity, `As New` instantiation, interpolated strings, LINQ, Unicode identifiers) | -| Erlang | `.erl`, `.hrl`, `.escript`, `.app.src`, `.app` | Full support (functions with multi-clause/multi-arity grouping, `-spec` signatures, records with fields, `-type`/`-opaque` aliases, `-define` macros, `-include`/`-include_lib`/`-import` edges, local and `mod:fn` remote call edges, `fun name/arity` references, `spawn`/`apply`/`proc_lib`/`timer`/`rpc` MFA-argument call edges, `gen_server:call/cast(?MODULE)` → own `handle_call`/`handle_cast` links, `-behaviour` links, `-export`-based visibility) | -| Solidity | `.sol` | Full support (contracts, libraries, interfaces, structs, enums, modifiers, events, errors, state variables, `import`/`using` directives, `emit`/`revert` calls) | -| Terraform / OpenTofu | `.tf`, `.tfvars`, `.tofu` | Full support (resources, data sources, modules, variables, outputs, providers incl. aliases, `locals`; `var.`/`local.`/`module.`/resource references with Terraform's per-directory scoping enforced; module calls bridged across the boundary — inputs to the child module's variables, `module.M.out` to the child's output, `source` to the module's files; cloudposse/atmos `remote-state` cross-component wiring when the component is statically named; `provider = aws.east` selections resolved up the module tree; `moved`/`import`/`removed`/`check` block references; `.tfvars` assignments linked to the variables they set) | -| Nix | `.nix` | Full support (functions with simple/destructured/curried params, `let`/attrset bindings, `inherit`, `import ./path` file edges — `./dir` resolving through `default.nix` — plus NixOS module `imports = [ ./x.nix ]` lists and `callPackage ./pkg.nix` file edges; call edges; module-system option wiring — a config write like `launchd.user.agents.x = { ... }` links to the module declaring `options.launchd.user.agents`, so option flows trace across modules) | +| TypeScript | `.ts`, `.tsx` | 完全支持 | +| JavaScript | `.js`, `.jsx`, `.mjs` | 完全支持 | +| ArkTS (HarmonyOS) | `.ets` | 完全支持(具备 TypeScript 的全部能力,外加 `@Component`/`@ComponentV2` 结构体及其 ArkUI 装饰器(`@State`/`@Prop`/`@Link`/`@Local`/`@Builder`/…)、`build()` 视图树 — 父→子组件边、指向 `@Extend`/`@Styles` 函数的链式属性链接、`.onClick(this.handler)` 事件绑定 — 用于 state→`build()` 重新渲染的动态分发桥接、`@ohos.events.emitter` emit→subscriber 对(仅限静态事件键),以及 `router.pushUrl` 字面量 url → 目标页面结构体;ohpm 工作区模块通过 `oh-package.json5` `file:` 依赖解析裸 `import { X } from "data"`,并遵循各模块的 `main` 入口) | +| Python | `.py` | 完全支持 | +| Go | `.go` | 完全支持 | +| Rust | `.rs` | 完全支持 | +| Java | `.java` | 完全支持 | +| C# | `.cs` | 完全支持 | +| PHP | `.php` | 完全支持 | +| Ruby | `.rb` | 完全支持 | +| C | `.c`, `.h` | 完全支持 | +| C++ | `.cpp`, `.hpp`, `.cc` | 完全支持 | +| Objective-C | `.m`, `.mm`, `.h` | 部分支持(类、协议、方法、`@property`、`#import`、消息发送;`.mm` ObjC++ 可能无法完整解析) | +| Metal | `.metal` | 完全支持(顶点/片段/内核函数、结构体、类型别名、调用边 — MSL 按 C++ 解析,并处理 `[[attribute]]` 注解) | +| CUDA | `.cu`, `.cuh` | 完全支持(内核及 device/host 函数、结构体、类、通过 `<<>>` 启动语法建立的 host→kernel 调用边 — 含模板化启动、函数指针启动(`auto kernel = &fn<...>`)、`dim3{...}` 配置及宏定义内核;处理 `__global__`/`__device__`/`__launch_bounds__` 说明符;纯 `.h`/`.hpp` 头文件中的 CUDA 按内容识别) | +| Swift | `.swift` | 完全支持 | +| Kotlin | `.kt`, `.kts` | 完全支持 | +| Scala | `.scala`, `.sc` | 完全支持(类、trait、方法、类型别名、Scala 3 枚举) | +| Dart | `.dart` | 完全支持 | +| Svelte | `.svelte` | 完全支持(script 提取、Svelte 5 runes、SvelteKit 路由) | +| Vue | `.vue` | 完全支持(script + script-setup 提取、Nuxt 页面/API/中间件路由) | +| Astro | `.astro` | 完全支持(frontmatter + script 提取、模板组件/调用引用、`src/pages/` 路由) | +| Liquid | `.liquid` | 完全支持 | +| Pascal / Delphi | `.pas`, `.dpr`, `.dpk`, `.lpr` | 完全支持(类、记录、接口、枚举、DFM/FMX 窗体文件) | +| Lua | `.lua` | 完全支持(函数、带 receiver 的方法、局部变量、`require` 导入、调用边) | +| R | `.R` `.r` | 完全支持(各种赋值形式的函数、带方法的 S4/R5/R6 类、`library`/`require` 导入、`source()` 文件引用、调用边) | +| Luau | `.luau` | 完全支持(具备 Lua 的全部能力,外加 `type`/`export type` 别名、类型签名及 Roblox 实例路径 `require`) | +| CFML | `.cfc`, `.cfm`, `.cfs` | 完全支持(基于标签的 ``/`` 与裸脚本 `component { ... }` 风格、`extends`/`implements`、嵌入式 `` 委托、调用边) | +| COBOL | `.cbl`, `.cob`, `.cpy` | 完全支持(程序、带 PERFORM/GO TO 调用边的节/段落、CALL 'literal' 跨程序调用、COPY copybook 导入 — 含独立 `.cpy` 文件 — DATA DIVISION 记录/字段/88 级、EXEC CICS LINK/XCTL 与 EXEC SQL INCLUDE 目标;固定格式与自由格式) | +| Visual Basic .NET | `.vb` | 完全支持(类、Modules、接口、结构体、枚举、属性、事件、`Declare` P/Invoke、`Handles`/`WithEvents`、`Inherits`/`Implements` 边、通过 VB 调用/索引括号歧义建立的调用边、`As New` 实例化、插值字符串、LINQ、Unicode 标识符) | +| Erlang | `.erl`, `.hrl`, `.escript`, `.app.src`, `.app` | 完全支持(多子句/多 arity 分组的函数、`-spec` 签名、带字段的记录、`-type`/`-opaque` 别名、`-define` 宏、`-include`/`-include_lib`/`-import` 边、本地与 `mod:fn` 远程调用边、`fun name/arity` 引用、`spawn`/`apply`/`proc_lib`/`timer`/`rpc` MFA 参数调用边、`gen_server:call/cast(?MODULE)` → 自身 `handle_call`/`handle_cast` 链接、`-behaviour` 链接、基于 `-export` 的可见性) | +| Solidity | `.sol` | 完全支持(合约、库、接口、结构体、枚举、修饰符、事件、错误、状态变量、`import`/`using` 指令、`emit`/`revert` 调用) | +| Terraform / OpenTofu | `.tf`, `.tfvars`, `.tofu` | 完全支持(资源、数据源、模块、变量、输出、含别名的 provider、`locals`;`var.`/`local.`/`module.`/资源引用,并强制执行 Terraform 的按目录作用域;模块调用跨边界桥接 — 输入到子模块变量、`module.M.out` 到子模块输出、`source` 到模块文件;当组件静态命名时 cloudposse/atmos `remote-state` 跨组件连线;`provider = aws.east` 选择沿模块树向上解析;`moved`/`import`/`removed`/`check` 块引用;`.tfvars` 赋值链接到其设置的变量) | +| Nix | `.nix` | 完全支持(简单/解构/柯里化参数的函数、`let`/attrset 绑定、`inherit`、`import ./path` 文件边 — `./dir` 通过 `default.nix` 解析 — 以及 NixOS 模块 `imports = [ ./x.nix ]` 列表与 `callPackage ./pkg.nix` 文件边;调用边;模块系统选项连线 — 诸如 `launchd.user.agents.x = { ... }` 的配置写入会链接到声明 `options.launchd.user.agents` 的模块,从而使选项流可跨模块追踪) | -## Measured cross-file coverage +## 实测跨文件覆盖率 -Impact and blast-radius queries are only as good as the dependency graph behind them, so coverage is measured rather than asserted. **Fair coverage** = the share of symbol-bearing source files that have at least one *resolved cross-file dependent* — something that imports, calls, references, or (through a framework convention) routes to them — on a real-world benchmark repo per language. The residual is always a genuine static-analysis frontier (runtime dynamic dispatch, reflection / DI containers, framework-convention entry points, vendored third-party code), never hidden by gaming the denominator. +影响范围与爆炸半径(blast-radius)查询的效果取决于背后的依赖图,因此覆盖率采用实测而非断言。**公平覆盖率(Fair coverage)** = 在每种语言的真实基准仓库中,至少拥有一个*已解析的跨文件依赖方* — 即会导入、调用、引用或通过框架约定路由到它们的对象 — 的含符号源文件所占比例。剩余部分始终是真实的静态分析边界(运行时动态分发、反射/DI 容器、框架约定入口点、vendor 第三方代码),绝不会通过操纵分母来掩盖。 -| Language | Benchmark repo | Coverage | +| 语言 | 基准仓库 | 覆盖率 | |---|---|---| | TypeScript / JavaScript | this repo | 95.8% | | Python | psf/requests | 100% | @@ -839,26 +799,26 @@ Impact and blast-radius queries are only as good as the dependency graph behind | Liquid | Shopify/dawn | 73.8% | | Pascal / Delphi | PascalCoin | 77.4% | -Framework routing is validated the same way, on a canonical app per framework: Express 100%, FastAPI 98%, Flask 100%, NestJS 96.8%, Gin 96.5%, Axum 100%, Rocket 93.8%, Vapor 100%, Laravel 92%, Rails 89.6%, React Router 100% — and the convention/reflection-heavy ones at their honest static-analysis ceiling: ASP.NET 83.9%, Spring 83.3%, Drupal 78.9%, Play 76.3%, Django 74.1%. SvelteKit, Vue/Nuxt, and Astro use file-based routing, so their page/endpoint coverage is the Svelte/SvelteKit (100%), Vue/Nuxt (93.5%), and Astro (93.0% — every `src/pages/` file maps to a route node on the two validation repos) figures in the table above. +各框架的路由验证方式相同,均在每个框架的标准示例应用上进行:Express 100%、FastAPI 98%、Flask 100%、NestJS 96.8%、Gin 96.5%、Axum 100%、Rocket 93.8%、Vapor 100%、Laravel 92%、Rails 89.6%、React Router 100%——而依赖约定/反射较多的框架则达到其静态分析的真实上限:ASP.NET 83.9%、Spring 83.3%、Drupal 78.9%、Play 76.3%、Django 74.1%。SvelteKit、Vue/Nuxt 和 Astro 使用基于文件的路由(file-based routing),因此其页面/端点覆盖率即上表中的 Svelte/SvelteKit(100%)、Vue/Nuxt(93.5%)和 Astro(93.0%——在两个验证仓库中,每个 `src/pages/` 文件都对应一个路由节点)数据。 -## Troubleshooting +## 故障排查 -**"CodeGraph not initialized"** — Run `codegraph init` in your project directory first. +**"CodeGraph not initialized"** — 请先在项目目录中运行 `codegraph init`。 -**Indexing is slow** — Check that `node_modules` and other large directories are excluded. Use `--quiet` to reduce output overhead. +**索引较慢** — 请确认已排除 `node_modules` 及其他大型目录。使用 `--quiet` 降低输出开销。 -**MCP hits `database is locked`** — current builds shouldn't: CodeGraph bundles its own Node runtime and uses Node's built-in `node:sqlite` in WAL mode, where concurrent reads never block on a writer. If you still see it: +**MCP 遇到 `database is locked`** — 当前版本不应出现此问题:CodeGraph 自带 Node 运行时,并以 WAL 模式使用 Node 内置的 `node:sqlite`,并发读取不会被写入阻塞。若仍遇到: -- **You're on an old (pre-0.9) install.** Reinstall to get the bundled runtime — `curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh` (macOS/Linux), `irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iex` (Windows), or `npm i -g @colbymchenry/codegraph@latest`. -- **`codegraph status` shows `Journal:` other than `wal`** — WAL couldn't be enabled on this filesystem (common on network shares and WSL2 `/mnt`), so reads can block on writes. Move the project (with its `.codegraph/` folder) onto a local disk. +- **您使用的是旧版(0.9 之前)安装。** 重新安装以获取捆绑的运行时——`curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh`(macOS/Linux)、`irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iex`(Windows)或 `npm i -g @colbymchenry/codegraph@latest`。 +- **`codegraph status` 显示的 `Journal:` 不是 `wal`** — 此文件系统无法启用 WAL(常见于网络共享和 WSL2 的 `/mnt`),因此读取可能被写入阻塞。将项目(及其 `.codegraph/` 文件夹)移至本地磁盘。 -**MCP server not connecting** — Your agent starts the server itself, so you don't launch it by hand. Make sure the project is initialized and indexed (`codegraph status`) and that the path in your MCP config is correct. If it still won't connect, re-run `codegraph install` to rewrite the config. +**MCP 服务器无法连接** — 代理会自行启动服务器,无需手动启动。请确保项目已初始化并完成索引(`codegraph status`),且 MCP 配置中的路径正确。若仍无法连接,重新运行 `codegraph install` 以重写配置。 -**MCP tool calls fail with `Transport closed` while `codegraph status`/`sync` are healthy** — almost always WSL2 with the project on a Windows drive (a `/mnt/c` or `/mnt/d` path), where the local socket CodeGraph uses to share one background server across sessions is unreliable. CodeGraph now falls back to serving the session in-process instead of dropping the connection, but if you still hit it, set `CODEGRAPH_NO_DAEMON=1` in your MCP server's environment to skip the shared server entirely (each session runs in its own process). Moving the project onto the Linux-native filesystem (e.g. under `~/` instead of `/mnt/`) restores the shared server. +**`codegraph status`/`sync` 正常时,MCP 工具调用仍失败并出现 `Transport closed`** — 几乎总是因为 WSL2 下项目位于 Windows 驱动器(`/mnt/c` 或 `/mnt/d` 路径),CodeGraph 用于跨会话共享单一后台服务器的本地套接字不可靠。CodeGraph 现已回退为在进程内提供服务而非断开连接,但若仍遇到,请在 MCP 服务器环境中设置 `CODEGRAPH_NO_DAEMON=1` 以完全跳过共享服务器(每个会话在独立进程中运行)。将项目移至 Linux 原生文件系统(例如在 `~/` 下而非 `/mnt/`)可恢复共享服务器。 -**Missing symbols** — The MCP server auto-syncs on save (wait a couple seconds). Run `codegraph sync` manually if needed. Check that the file's language is supported and isn't inside a `.gitignore`d or default-excluded directory (e.g. `node_modules`, `dist`). +**符号缺失** — MCP 服务器会在保存时自动同步(等待几秒钟)。必要时可手动运行 `codegraph sync`。请确认文件语言受支持,且不在 `.gitignore`d 或默认排除的目录中(例如 `node_modules`、`dist`)。 -**Sharing one checkout between Windows and WSL** — Don't point both at the same `.codegraph/`: the background-server lock and the SQLite index are tied to the OS that wrote them, and SQLite locking across the WSL2/Windows filesystem boundary is unreliable. Give each side its own index in the same tree by setting `CODEGRAPH_DIR` to a distinct name on one of them — e.g. `CODEGRAPH_DIR=.codegraph-win` on Windows, leaving WSL on the default `.codegraph`. CodeGraph skips any sibling `.codegraph-*` directory when indexing and watching, so the two never trip over each other. +**在 Windows 与 WSL 之间共享同一份检出** — 不要让两侧指向同一个 `.codegraph/`:后台服务器锁和 SQLite 索引与写入它们的操作系统绑定,且跨 WSL2/Windows 文件系统边界的 SQLite 锁定不可靠。通过在其中一侧将 `CODEGRAPH_DIR` 设为不同名称,让同一代码树中各自拥有独立索引——例如在 Windows 上使用 `CODEGRAPH_DIR=.codegraph-win`,WSL 保持默认的 `.codegraph`。CodeGraph 在索引和监听时会跳过任何同级的 `.codegraph-*` 目录,因此两侧互不干扰。 ## Star History @@ -870,7 +830,7 @@ Framework routing is validated the same way, on a canonical app per framework: E -## License +## 许可证 MIT @@ -878,8 +838,8 @@ MIT
-**Made for AI coding agents — Claude Code, Cursor, Codex CLI, opencode, Hermes Agent, Gemini CLI, Antigravity IDE, and Kiro** +**为 AI 编程代理打造 — Claude Code、Cursor、Codex CLI、opencode、Hermes Agent、Gemini CLI、Antigravity IDE 和 Kiro** -[Report Bug](https://github.com/colbymchenry/codegraph/issues) · [Request Feature](https://github.com/colbymchenry/codegraph/issues) +[报告 Bug](https://github.com/colbymchenry/codegraph/issues) · [请求功能](https://github.com/colbymchenry/codegraph/issues)