Lightweight Local Code Knowledge Graph CLI Tool
Build persistent code index graphs for AI coding assistants — reduce 70%+ token consumption
CodeGraph 是一款轻量级本地代码知识图谱 CLI 工具,专为 AI 编码助手(Claude Code、Codex CLI、Cursor、Windsurf 等)构建持久化代码索引图谱。
使用 AI 编码助手时,每次对话都需要重新读取大量无关代码,导致:
- Token 浪费严重:每次对话消耗大量 Token,成本居高不下
- 响应速度慢:AI 需要处理大量无关上下文,响应延迟增加
- 代码理解不完整:缺乏全局代码结构视图,AI 难以准确理解项目架构
- 零外部依赖:纯 Python 标准库实现,无需安装任何第三方包,开箱即用
- 6 种主流语言支持:Python、JavaScript/TypeScript、Go、Rust、Java、C/C++
- 增量索引:基于文件修改时间戳和内容哈希,只更新变更文件,秒级更新
- 智能上下文推荐:根据查询关键词自动推荐相关代码实体,按相关性排序
- 多 AI 助手集成:一键生成适配 Claude Code、Codex CLI、Cursor、Windsurf 的上下文文件
- Token 估算与成本控制:精确估算 Token 消耗,有效降低 70%+ 的 Token 成本
- 多格式导出:支持 JSON、Markdown、Text、DOT/Graphviz 等多种格式
- 🗺️ 知识图谱引擎:自动构建代码实体关系图谱,包括类、函数、变量、导入等实体及其依赖关系
- ⚡ 增量索引:基于文件修改时间戳和内容哈希,只更新变更文件,秒级完成索引更新
- 🔍 智能查询:支持模糊搜索、依赖追踪、按类型/文件过滤,结果按相关性智能排序
- 🤖 AI 助手集成:一键生成适配不同 AI 助手的上下文文件,无缝对接 Claude Code、Codex CLI、Cursor、Windsurf
- 💰 Token 优化:精确估算 Token 消耗,智能裁剪上下文,降低 70%+ 的 API 调用成本
- 📦 多格式导出:支持 JSON、Markdown、Text、DOT(Graphviz)等多种导出格式
- 🌐 多语言支持:支持 Python、JavaScript/TypeScript、Go、Rust、Java、C/C++ 六种主流编程语言
- 🚀 零依赖:纯 Python 标准库实现,无需安装任何第三方依赖,开箱即用
- Python 3.8+(无需任何第三方依赖)
# 克隆仓库
git clone https://github.com/gitstq/codegraph.git
cd codegraph
# 安装(可选,注册 codegraph 命令)
pip install -e .
# 或直接使用
python -m codegraph --help# 初始化项目索引
codegraph init
# 构建代码索引
codegraph index
# 查询代码实体
codegraph query "function_name"
# 为 AI 助手生成上下文
codegraph context claude
# 查看统计信息
codegraph stats
# 导出图谱
codegraph export json在项目根目录创建 .codegraph 缓存目录,用于存储索引数据。
# 在当前目录初始化
codegraph init
# 指定项目路径
codegraph init /path/to/project扫描项目文件,解析代码实体,构建或更新代码知识图谱。
# 增量索引(默认,只更新变更文件)
codegraph index
# 强制全量重建索引
codegraph index --full
# 显示详细进度信息
codegraph index -v
# 指定并行工作线程数(默认: 4)
codegraph index --workers 8
# 添加额外的忽略模式
codegraph index --ignore "*/tests/*" --ignore "*/vendor/*"| 参数 | 说明 |
|---|---|
--full |
强制全量重建索引,忽略增量缓存 |
-v, --verbose |
显示详细的索引进度信息 |
-w, --workers N |
设置并行索引工作线程数(默认: 4) |
--ignore PATTERN |
添加额外的文件忽略模式(可多次指定) |
在代码图谱中搜索匹配的代码实体。
# 关键词搜索
codegraph query "parse"
# 按类型过滤(class、function、method、import 等)
codegraph query "User" --type class
# 多类型过滤
codegraph query "login" --type function --type method
# 按文件过滤
codegraph query "config" --file src/config.py
# 限制结果数量(默认: 20)
codegraph query "handler" --max 50
# 启动交互式查询模式
codegraph query --interactive| 参数 | 说明 |
|---|---|
keyword |
搜索关键词或模式 |
--type TYPE |
按节点类型过滤(可多次指定) |
--file PATH |
按文件路径过滤结果 |
-n, --max N |
最大结果数量(默认: 20) |
--interactive |
启动交互式查询模式 |
| 命令 | 说明 |
|---|---|
<keyword> |
搜索代码实体 |
file:<path> |
按文件路径搜索 |
type:<type> |
按类型过滤 |
stats |
显示图谱统计 |
files |
列出已索引文件 |
quit/exit |
退出交互模式 |
为 AI 编码助手生成优化的上下文文件,包含函数签名、类结构和关键文档。
# 列出所有支持的 AI 助手
codegraph context --list
# 为 Claude Code 生成上下文
codegraph context claude
# 为 Cursor 生成上下文
codegraph context cursor
# 指定包含的文件
codegraph context claude --files src/main.py src/utils.py
# 按关键词搜索相关代码
codegraph context claude --keywords "auth" "database"
# 设置 Token 上限
codegraph context claude --max-tokens 30000
# 指定输出目录
codegraph context claude --output /path/to/output| 参数 | 说明 |
|---|---|
assistant |
AI 助手名称:claude、codex、cursor、windsurf |
--files |
指定包含在上下文中的文件列表 |
--keywords |
搜索相关代码的关键词列表 |
--max-tokens N |
上下文最大 Token 数量 |
--output DIR |
输出目录(默认写入项目下的助手配置目录) |
--list |
列出所有可用的 AI 助手 |
| 助手 | 配置目录 | 默认 Token 上限 |
|---|---|---|
| Claude Code | .claude/ |
50,000 |
| Codex CLI | .codex/ |
50,000 |
| Cursor | .cursor/ |
80,000 |
| Windsurf | .windsurf/ |
80,000 |
显示代码图谱的详细统计信息。
# 查看基本统计
codegraph stats
# 包含 Token 估算报告
codegraph stats --token-report输出内容包括:总文件数、节点数、边数、节点类型分布、边类型分布、文件扩展名分布等。
将代码图谱导出为多种格式。
# 导出为 Markdown(默认)
codegraph export markdown
# 导出为 JSON
codegraph export json
# 导出为纯文本
codegraph export text
# 导出为 DOT(Graphviz 格式)
codegraph export dot
# 指定输出文件路径
codegraph export json -o output/graph.json| 参数 | 说明 |
|---|---|
format |
导出格式:json、markdown、text、dot(默认: markdown) |
-o, --output PATH |
输出文件路径(默认输出到标准输出) |
删除 .codegraph 缓存目录中的索引数据。
# 交互式确认后删除
codegraph clean
# 强制删除,跳过确认
codegraph clean --force| 参数 | 说明 |
|---|---|
-f, --force |
跳过确认提示,直接删除 |
- 本地优先:所有索引数据存储在本地
.codegraph目录,无需联网,保护代码隐私 - 零依赖:纯 Python 标准库实现,避免依赖冲突和安装复杂度
- 增量更新:基于文件修改时间戳和内容哈希的增量索引机制,大幅提升更新效率
| 决策 | 原因 |
|---|---|
| Python 标准库 | 零依赖,跨平台兼容性好,开发者上手成本低 |
| JSON 持久化 | 人类可读,调试方便,无需数据库依赖 |
| 多线程索引 | 充分利用多核 CPU,加速大型项目索引构建 |
| 基于哈希的增量更新 | 精确检测文件变更,避免不必要的重新解析 |
| 版本 | 功能 | 说明 |
|---|---|---|
| v1.1 | Web UI 可视化界面 | 提供浏览器端的图谱可视化浏览和交互查询 |
| v1.2 | Git 历史集成 | 追踪代码变更历史,支持按版本查看图谱演化 |
| v1.3 | LLM 增强智能摘要 | 利用 LLM 为代码实体生成智能摘要和注释 |
| v2.0 | 插件系统 | 支持自定义语言解析器和导出格式插件 |
# 从源码安装
git clone https://github.com/gitstq/codegraph.git
cd codegraph
pip install -e .安装后即可直接使用 codegraph 命令。
# 无需安装,直接以模块方式运行
git clone https://github.com/gitstq/codegraph.git
cd codegraph
python -m codegraph --help创建 Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY . .
# 无需 pip install,零依赖直接运行
ENTRYPOINT ["python", "-m", "codegraph"]构建并运行:
# 构建镜像
docker build -t codegraph .
# 运行索引
docker run --rm -v $(pwd):/workspace codegraph index /workspace
# 查询代码
docker run --rm -v $(pwd):/workspace codegraph query "function_name" --path /workspacename: CodeGraph Index
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
codegraph:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Clone CodeGraph
run: git clone https://github.com/gitstq/codegraph.git /tmp/codegraph
- name: Build Index
run: python -m codegraph index --full
- name: Generate Context
run: python -m codegraph context claude
- name: Export Graph
run: python -m codegraph export json -o codegraph-export.json
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: codegraph-data
path: |
.claude/
codegraph-export.json感谢你对 CodeGraph 的关注!我们欢迎任何形式的贡献。
遵循 Angular 提交规范:
<type>(<scope>): <subject>
<body>
<footer>
type 类型说明:
| 类型 | 说明 |
|---|---|
feat |
新功能 |
fix |
Bug 修复 |
docs |
文档变更 |
style |
代码格式调整(不影响功能) |
refactor |
代码重构(非新功能、非 Bug 修复) |
perf |
性能优化 |
test |
测试相关 |
chore |
构建过程或辅助工具的变动 |
示例:
feat(parser): add support for TypeScript type aliases
- Implement type alias parsing in TypeScript parser
- Add corresponding test cases
- Update supported node types documentation
Closes #42
- 使用 Bug Report 模板报告 Bug,请附上复现步骤和预期行为
- 使用 Feature Request 模板提交功能建议,请详细描述使用场景
- 在提交 Issue 前,请先搜索是否已有相同或相似的问题
- 遵循 PEP 8 编码规范
- 所有公共函数和类必须包含 docstring 文档
- 使用类型注解(Type Hints)标注函数参数和返回值
- 保持代码简洁,单个函数不超过 50 行(特殊情况除外)
- 提交前确保所有测试通过:
python -m pytest tests/
本项目基于 MIT 许可证 开源。
MIT License
Copyright (c) 2024 CodeGraph
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
这意味着你可以自由地使用、复制、修改、合并、发布、分发、再授权和/或销售本软件,唯一的要求是保留版权声明和许可声明。
CodeGraph 是一款輕量級本地程式碼知識圖譜 CLI 工具,專為 AI 編碼助手(Claude Code、Codex CLI、Cursor、Windsurf 等)建構持久化程式碼索引圖譜。
使用 AI 編碼助手時,每次對話都需要重新讀取大量無關程式碼,導致:
- Token 浪費嚴重:每次對話消耗大量 Token,成本居高不下
- 回應速度慢:AI 需要處理大量無關上下文,回應延遲增加
- 程式碼理解不完整:缺乏全域程式碼結構視圖,AI 難以準確理解專案架構
- 零外部依賴:純 Python 標準函式庫實作,無需安裝任何第三方套件,開箱即用
- 6 種主流語言支援:Python、JavaScript/TypeScript、Go、Rust、Java、C/C++
- 增量索引:基於檔案修改時間戳記和內容雜湊,只更新變更檔案,秒級更新
- 智慧上下文推薦:根據查詢關鍵字自動推薦相關程式碼實體,按相關性排序
- 多 AI 助手整合:一鍵產生適配 Claude Code、Codex CLI、Cursor、Windsurf 的上下文檔案
- Token 估算與成本控制:精確估算 Token 消耗,有效降低 70%+ 的 Token 成本
- 多格式匯出:支援 JSON、Markdown、Text、DOT/Graphviz 等多種格式
- 🗺️ 知識圖譜引擎:自動建構程式碼實體關係圖譜,包括類別、函式、變數、匯入等實體及其依賴關係
- ⚡ 增量索引:基於檔案修改時間戳記和內容雜湊,只更新變更檔案,秒級完成索引更新
- 🔍 智慧查詢:支援模糊搜尋、依賴追蹤、按類型/檔案過濾,結果按相關性智慧排序
- 🤖 AI 助手整合:一鍵產生適配不同 AI 助手的上下文檔案,無縫對接 Claude Code、Codex CLI、Cursor、Windsurf
- 💰 Token 最佳化:精確估算 Token 消耗,智慧裁剪上下文,降低 70%+ 的 API 呼叫成本
- 📦 多格式匯出:支援 JSON、Markdown、Text、DOT(Graphviz)等多種匯出格式
- 🌐 多語言支援:支援 Python、JavaScript/TypeScript、Go、Rust、Java、C/C++ 六種主流程式語言
- 🚀 零依賴:純 Python 標準函式庫實作,無需安裝任何第三方依賴,開箱即用
- Python 3.8+(無需任何第三方依賴)
# 複製倉庫
git clone https://github.com/gitstq/codegraph.git
cd codegraph
# 安裝(可選,註冊 codegraph 命令)
pip install -e .
# 或直接使用
python -m codegraph --help# 初始化專案索引
codegraph init
# 建構程式碼索引
codegraph index
# 查詢程式碼實體
codegraph query "function_name"
# 為 AI 助手產生上下文
codegraph context claude
# 查看統計資訊
codegraph stats
# 匯出圖譜
codegraph export json在專案根目錄建立 .codegraph 快取目錄,用於儲存索引資料。
# 在當前目錄初始化
codegraph init
# 指定專案路徑
codegraph init /path/to/project掃描專案檔案,解析程式碼實體,建構或更新程式碼知識圖譜。
# 增量索引(預設,只更新變更檔案)
codegraph index
# 強制全量重建索引
codegraph index --full
# 顯示詳細進度資訊
codegraph index -v
# 指定平行工作執行緒數(預設: 4)
codegraph index --workers 8
# 新增額外的忽略模式
codegraph index --ignore "*/tests/*" --ignore "*/vendor/*"| 參數 | 說明 |
|---|---|
--full |
強制全量重建索引,忽略增量快取 |
-v, --verbose |
顯示詳細的索引進度資訊 |
-w, --workers N |
設定平行索引工作執行緒數(預設: 4) |
--ignore PATTERN |
新增額外的檔案忽略模式(可多次指定) |
在程式碼圖譜中搜尋符合的程式碼實體。
# 關鍵字搜尋
codegraph query "parse"
# 按類型過濾(class、function、method、import 等)
codegraph query "User" --type class
# 多類型過濾
codegraph query "login" --type function --type method
# 按檔案過濾
codegraph query "config" --file src/config.py
# 限制結果數量(預設: 20)
codegraph query "handler" --max 50
# 啟動互動式查詢模式
codegraph query --interactive| 參數 | 說明 |
|---|---|
keyword |
搜尋關鍵字或模式 |
--type TYPE |
按節點類型過濾(可多次指定) |
--file PATH |
按檔案路徑過濾結果 |
-n, --max N |
最大結果數量(預設: 20) |
--interactive |
啟動互動式查詢模式 |
| 命令 | 說明 |
|---|---|
<keyword> |
搜尋程式碼實體 |
file:<path> |
按檔案路徑搜尋 |
type:<type> |
按類型過濾 |
stats |
顯示圖譜統計 |
files |
列出已索引檔案 |
quit/exit |
離開互動模式 |
為 AI 編碼助手產生最佳化的上下文檔案,包含函式簽章、類別結構和關鍵文件。
# 列出所有支援的 AI 助手
codegraph context --list
# 為 Claude Code 產生上下文
codegraph context claude
# 為 Cursor 產生上下文
codegraph context cursor
# 指定包含的檔案
codegraph context claude --files src/main.py src/utils.py
# 按關鍵字搜尋相關程式碼
codegraph context claude --keywords "auth" "database"
# 設定 Token 上限
codegraph context claude --max-tokens 30000
# 指定輸出目錄
codegraph context claude --output /path/to/output| 參數 | 說明 |
|---|---|
assistant |
AI 助手名稱:claude、codex、cursor、windsurf |
--files |
指定包含在上下文中的檔案列表 |
--keywords |
搜尋相關程式碼的關鍵字列表 |
--max-tokens N |
上下文最大 Token 數量 |
--output DIR |
輸出目錄(預設寫入專案下的助手設定目錄) |
--list |
列出所有可用的 AI 助手 |
| 助手 | 設定目錄 | 預設 Token 上限 |
|---|---|---|
| Claude Code | .claude/ |
50,000 |
| Codex CLI | .codex/ |
50,000 |
| Cursor | .cursor/ |
80,000 |
| Windsurf | .windsurf/ |
80,000 |
顯示程式碼圖譜的詳細統計資訊。
# 查看基本統計
codegraph stats
# 包含 Token 估算報告
codegraph stats --token-report輸出內容包括:總檔案數、節點數、邊數、節點類型分佈、邊類型分佈、副檔名分佈等。
將程式碼圖譜匯出為多種格式。
# 匯出為 Markdown(預設)
codegraph export markdown
# 匯出為 JSON
codegraph export json
# 匯出為純文字
codegraph export text
# 匯出為 DOT(Graphviz 格式)
codegraph export dot
# 指定輸出檔案路徑
codegraph export json -o output/graph.json| 參數 | 說明 |
|---|---|
format |
匯出格式:json、markdown、text、dot(預設: markdown) |
-o, --output PATH |
輸出檔案路徑(預設輸出到標準輸出) |
刪除 .codegraph 快取目錄中的索引資料。
# 互動式確認後刪除
codegraph clean
# 強制刪除,跳過確認
codegraph clean --force| 參數 | 說明 |
|---|---|
-f, --force |
跳過確認提示,直接刪除 |
- 本地優先:所有索引資料儲存在本地
.codegraph目錄,無需連網,保護程式碼隱私 - 零依賴:純 Python 標準函式庫實作,避免依賴衝突和安裝複雜度
- 增量更新:基於檔案修改時間戳記和內容雜湊的增量索引機制,大幅提升更新效率
| 決策 | 原因 |
|---|---|
| Python 標準函式庫 | 零依賴,跨平台相容性好,開發者上手成本低 |
| JSON 持久化 | 人類可讀,除錯方便,無需資料庫依賴 |
| 多執行緒索引 | 充分利用多核心 CPU,加速大型專案索引建構 |
| 基於雜湊的增量更新 | 精確偵測檔案變更,避免不必要的重新解析 |
| 版本 | 功能 | 說明 |
|---|---|---|
| v1.1 | Web UI 視覺化介面 | 提供瀏覽器端的圖譜視覺化瀏覽和互動查詢 |
| v1.2 | Git 歷史整合 | 追蹤程式碼變更歷史,支援按版本查看圖譜演化 |
| v1.3 | LLM 增強智慧摘要 | 利用 LLM 為程式碼實體產生智慧摘要和註解 |
| v2.0 | 外掛系統 | 支援自訂語言解析器和匯出格式外掛 |
# 從原始碼安裝
git clone https://github.com/gitstq/codegraph.git
cd codegraph
pip install -e .安裝後即可直接使用 codegraph 命令。
# 無需安裝,直接以模組方式執行
git clone https://github.com/gitstq/codegraph.git
cd codegraph
python -m codegraph --help建立 Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY . .
# 無需 pip install,零依賴直接執行
ENTRYPOINT ["python", "-m", "codegraph"]建構並執行:
# 建構映像檔
docker build -t codegraph .
# 執行索引
docker run --rm -v $(pwd):/workspace codegraph index /workspace
# 查詢程式碼
docker run --rm -v $(pwd):/workspace codegraph query "function_name" --path /workspacename: CodeGraph Index
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
codegraph:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Clone CodeGraph
run: git clone https://github.com/gitstq/codegraph.git /tmp/codegraph
- name: Build Index
run: python -m codegraph index --full
- name: Generate Context
run: python -m codegraph context claude
- name: Export Graph
run: python -m codegraph export json -o codegraph-export.json
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: codegraph-data
path: |
.claude/
codegraph-export.json感謝你對 CodeGraph 的關注!我們歡迎任何形式的貢獻。
遵循 Angular 提交規範:
<type>(<scope>): <subject>
<body>
<footer>
type 類型說明:
| 類型 | 說明 |
|---|---|
feat |
新功能 |
fix |
Bug 修復 |
docs |
文件變更 |
style |
程式碼格式調整(不影響功能) |
refactor |
程式碼重構(非新功能、非 Bug 修復) |
perf |
效能最佳化 |
test |
測試相關 |
chore |
建構過程或輔助工具的變動 |
範例:
feat(parser): add support for TypeScript type aliases
- Implement type alias parsing in TypeScript parser
- Add corresponding test cases
- Update supported node types documentation
Closes #42
- 使用 Bug Report 範本回報 Bug,請附上重現步驟和預期行為
- 使用 Feature Request 範本提交功能建議,請詳細描述使用場景
- 在提交 Issue 前,請先搜尋是否已有相同或相似的問題
- 遵循 PEP 8 編碼規範
- 所有公共函式和類別必須包含 docstring 文件
- 使用型別註解(Type Hints)標註函式參數和回傳值
- 保持程式碼簡潔,單個函式不超過 50 行(特殊情況除外)
- 提交前確保所有測試通過:
python -m pytest tests/
本專案基於 MIT 許可證 開源。
MIT License
Copyright (c) 2024 CodeGraph
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
這意味著你可以自由地使用、複製、修改、合併、發佈、分發、再授權和/或銷售本軟體,唯一的要求是保留著作權聲明和許可聲明。
CodeGraph is a lightweight local code knowledge graph CLI tool that builds persistent code index graphs for AI coding assistants such as Claude Code, Codex CLI, Cursor, and Windsurf.
When working with AI coding assistants, every conversation requires re-reading large amounts of irrelevant code, leading to:
- Excessive token waste: Each conversation burns through tokens, driving up costs
- Slower responses: AI must process unnecessary context, increasing response latency
- Incomplete code understanding: Without a global structural view, AI struggles to accurately understand project architecture
- Zero external dependencies: Built entirely with the Python standard library — no third-party packages needed
- 6 major languages supported: Python, JavaScript/TypeScript, Go, Rust, Java, and C/C++
- Incremental indexing: Uses file modification timestamps and content hashes to update only changed files in seconds
- Smart context recommendations: Automatically suggests relevant code entities based on query keywords, ranked by relevance
- Multi-assistant integration: One-click context generation for Claude Code, Codex CLI, Cursor, and Windsurf
- Token estimation and cost control: Accurately estimates token usage, reducing API costs by 70%+
- Multi-format export: JSON, Markdown, Text, and DOT/Graphviz formats
- 🗺️ Knowledge Graph Engine: Automatically builds a code entity relationship graph, including classes, functions, variables, imports, and their dependencies
- ⚡ Incremental Indexing: Updates only changed files based on modification timestamps and content hashes — updates complete in seconds
- 🔍 Smart Queries: Fuzzy search, dependency tracing, type/file filtering, with results intelligently ranked by relevance
- 🤖 AI Assistant Integration: One-click context file generation for Claude Code, Codex CLI, Cursor, and Windsurf
- 💰 Token Optimization: Precise token estimation with intelligent context trimming, cutting API costs by 70%+
- 📦 Multi-Format Export: Export to JSON, Markdown, Text, and DOT (Graphviz) formats
- 🌐 Multi-Language Support: Python, JavaScript/TypeScript, Go, Rust, Java, and C/C++
- 🚀 Zero Dependencies: Pure Python standard library — works out of the box with nothing to install
- Python 3.8+ (no third-party dependencies required)
# Clone the repository
git clone https://github.com/gitstq/codegraph.git
cd codegraph
# Install (optional — registers the `codegraph` command)
pip install -e .
# Or run directly without installing
python -m codegraph --help# Initialize the project index
codegraph init
# Build the code index
codegraph index
# Query code entities
codegraph query "function_name"
# Generate context for an AI assistant
codegraph context claude
# View statistics
codegraph stats
# Export the graph
codegraph export jsonCreates a .codegraph cache directory in the project root for storing index data.
# Initialize in the current directory
codegraph init
# Specify a project path
codegraph init /path/to/projectScans project files, parses code entities, and builds or updates the code knowledge graph.
# Incremental index (default — only updates changed files)
codegraph index
# Force a full rebuild
codegraph index --full
# Show detailed progress information
codegraph index -v
# Set the number of parallel worker threads (default: 4)
codegraph index --workers 8
# Add additional ignore patterns
codegraph index --ignore "*/tests/*" --ignore "*/vendor/*"| Flag | Description |
|---|---|
--full |
Force a full rebuild, ignoring the incremental cache |
-v, --verbose |
Show detailed indexing progress |
-w, --workers N |
Set the number of parallel indexing workers (default: 4) |
--ignore PATTERN |
Add additional file ignore patterns (can be specified multiple times) |
Search the code graph for matching code entities.
# Keyword search
codegraph query "parse"
# Filter by node type (class, function, method, import, etc.)
codegraph query "User" --type class
# Multiple type filters
codegraph query "login" --type function --type method
# Filter by file
codegraph query "config" --file src/config.py
# Limit the number of results (default: 20)
codegraph query "handler" --max 50
# Start interactive query mode
codegraph query --interactive| Flag | Description |
|---|---|
keyword |
Search keyword or pattern |
--type TYPE |
Filter by node type (can be specified multiple times) |
--file PATH |
Filter results by file path |
-n, --max N |
Maximum number of results (default: 20) |
--interactive |
Start interactive query mode |
| Command | Description |
|---|---|
<keyword> |
Search for code entities |
file:<path> |
Search by file path |
type:<type> |
Filter by type |
stats |
Show graph statistics |
files |
List indexed files |
quit/exit |
Exit interactive mode |
Generates optimized context files for AI coding assistants, including function signatures, class structures, and key documentation.
# List all supported AI assistants
codegraph context --list
# Generate context for Claude Code
codegraph context claude
# Generate context for Cursor
codegraph context cursor
# Specify files to include
codegraph context claude --files src/main.py src/utils.py
# Search for relevant code by keywords
codegraph context claude --keywords "auth" "database"
# Set a token limit
codegraph context claude --max-tokens 30000
# Specify an output directory
codegraph context claude --output /path/to/output| Flag | Description |
|---|---|
assistant |
AI assistant name: claude, codex, cursor, windsurf |
--files |
List of files to include in the context |
--keywords |
List of keywords to search for relevant code |
--max-tokens N |
Maximum token count for the context |
--output DIR |
Output directory (default: the assistant's config directory under the project) |
--list |
List all available AI assistants |
| Assistant | Config Directory | Default Token Limit |
|---|---|---|
| Claude Code | .claude/ |
50,000 |
| Codex CLI | .codex/ |
50,000 |
| Cursor | .cursor/ |
80,000 |
| Windsurf | .windsurf/ |
80,000 |
Displays detailed statistics about the code graph.
# View basic statistics
codegraph stats
# Include a token estimation report
codegraph stats --token-reportOutput includes: total files, nodes, edges, node type distribution, edge type distribution, and file extension distribution.
Exports the code graph in various formats.
# Export as Markdown (default)
codegraph export markdown
# Export as JSON
codegraph export json
# Export as plain text
codegraph export text
# Export as DOT (Graphviz format)
codegraph export dot
# Specify an output file path
codegraph export json -o output/graph.json| Flag | Description |
|---|---|
format |
Export format: json, markdown, text, dot (default: markdown) |
-o, --output PATH |
Output file path (default: stdout) |
Removes index data from the .codegraph cache directory.
# Remove with interactive confirmation
codegraph clean
# Force removal without confirmation
codegraph clean --force| Flag | Description |
|---|---|
-f, --force |
Skip the confirmation prompt |
- Local-first: All index data is stored locally in the
.codegraphdirectory — no network required, keeping your code private - Zero dependencies: Pure Python standard library implementation, avoiding dependency conflicts and installation complexity
- Incremental updates: Hash-based incremental indexing mechanism for dramatically faster updates
| Decision | Rationale |
|---|---|
| Python standard library | Zero dependencies, excellent cross-platform compatibility, low barrier to entry |
| JSON persistence | Human-readable, easy to debug, no database dependency |
| Multi-threaded indexing | Leverages multi-core CPUs to speed up indexing for large projects |
| Hash-based incremental updates | Accurately detects file changes, avoiding unnecessary re-parsing |
| Version | Feature | Description |
|---|---|---|
| v1.1 | Web UI Visualization | Browser-based graph visualization with interactive exploration |
| v1.2 | Git History Integration | Track code change history and view graph evolution across versions |
| v1.3 | LLM-Enhanced Summaries | Use LLMs to generate intelligent summaries and documentation for code entities |
| v2.0 | Plugin System | Support for custom language parsers and export format plugins |
# Install from source
git clone https://github.com/gitstq/codegraph.git
cd codegraph
pip install -e .After installation, the codegraph command is available directly.
# No installation needed — run as a module
git clone https://github.com/gitstq/codegraph.git
cd codegraph
python -m codegraph --helpCreate a Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY . .
# No pip install needed — zero dependencies
ENTRYPOINT ["python", "-m", "codegraph"]Build and run:
# Build the image
docker build -t codegraph .
# Build the index
docker run --rm -v $(pwd):/workspace codegraph index /workspace
# Query code
docker run --rm -v $(pwd):/workspace codegraph query "function_name" --path /workspacename: CodeGraph Index
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
codegraph:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- name: Clone CodeGraph
run: git clone https://github.com/gitstq/codegraph.git /tmp/codegraph
- name: Build Index
run: python -m codegraph index --full
- name: Generate Context
run: python -m codegraph context claude
- name: Export Graph
run: python -m codegraph export json -o codegraph-export.json
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: codegraph-data
path: |
.claude/
codegraph-export.jsonThank you for your interest in CodeGraph! Contributions of all forms are welcome.
Follow the Angular Commit Convention:
<type>(<scope>): <subject>
<body>
<footer>
Commit types:
| Type | Description |
|---|---|
feat |
New feature |
fix |
Bug fix |
docs |
Documentation changes |
style |
Code formatting (no functional changes) |
refactor |
Code refactoring (neither a feature nor a bug fix) |
perf |
Performance improvements |
test |
Test-related changes |
chore |
Build process or tooling changes |
Example:
feat(parser): add support for TypeScript type aliases
- Implement type alias parsing in TypeScript parser
- Add corresponding test cases
- Update supported node types documentation
Closes #42
- Use the Bug Report template for bugs — include reproduction steps and expected behavior
- Use the Feature Request template for suggestions — describe your use case in detail
- Search existing issues before submitting a new one to avoid duplicates
- Follow PEP 8 coding conventions
- All public functions and classes must include docstrings
- Use type hints for function parameters and return values
- Keep functions concise — aim for no more than 50 lines per function (exceptions allowed with good reason)
- Ensure all tests pass before submitting:
python -m pytest tests/
This project is released under the MIT License.
MIT License
Copyright (c) 2024 CodeGraph
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
You are free to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software, provided that the copyright notice and permission notice are preserved.