files → ExtractionOrchestrator (tree-sitter) → DB (nodes/edges/files)
↓
ReferenceResolver (imports, name-matching, framework patterns)
↓
GraphQueryManager / GraphTraverser (callers, callees, impact)
↓
ContextBuilder (markdown/JSON for AI consumption)
公開 API 面是 src/index.ts 的 CodeGraph class——把各層接起來並 re-export 型別。Library 使用者只碰這支檔案;MCP server 與 CLI 也驅動同一支。詳見 程式碼對照 · CodeGraph class。
| 模組 | 職責 | 教學頁 |
|---|---|---|
src/index.ts | CodeGraph class:init/open/close、indexAll、sync、searchNodes、getCallers/Callees、getImpactRadius、buildContext、watch/unwatch | main |
src/db/ | DatabaseConnection、QueryBuilder(prepared statements)、schema.sql、sqlite-adapter;Node 內建 node:sqlite(DatabaseSync)+ WAL + FTS5,無原生 build | db |
src/extraction/ | ExtractionOrchestrator、tree-sitter 包裝、per-language extractors(languages/)、Svelte/Vue/Liquid/DFM 等獨立 extractor;parse-worker.ts 主執行緒外解析 | extraction |
codegraph-kernel/ | Rust 原生解析 kernel(20 語言),逐位元組驗證對齊參考引擎;無 prebuilt 平台或語法錯誤自動 per-file 回退 | extraction |
src/resolution/ | ReferenceResolver 調度 import-resolver(含 tsconfig path aliases + cargo workspace)、name-matcher、frameworks/(Express、Laravel、Rails、FastAPI、Django、Flask、Spring、Gin、Axum…)產 route 節點與 references 邊 | resolution |
src/graph/ | GraphTraverser(BFS/DFS、影響半徑、路徑搜尋)與 GraphQueryManager(高階查詢) | graph |
src/context/ | ContextBuilder + markdown/JSON 格式化輸出 | context |
src/search/ | FTS5 全文搜尋的查詢解析與 helper | db |
src/sync/ | FileWatcher(原生 FSEvents/inotify/RDCW)debounce + filter、git-hook helpers | auto-sync |
src/mcp/ | MCP server(MCPServer、tools、transport);server-instructions.ts 是 initialize response 的指引來源 | mcp |
src/installer/ | 多 agent 安裝器;targets/registry.ts 列全部 agent,新增一個 agent = 一個新檔案 + registry 一列 | installer |
src/bin/codegraph.ts | CLI(commander):install、init、uninit、index、sync、status、query、files、context、affected、serve --mcp | cli |
src/telemetry/ | 匿名使用統計(聚合、可關) | security |
安裝器是 codegraph install(以及裸 codegraph / npx @colbymchenry/codegraph)的入口。目前 targets:claude.ts、cursor.ts、codex.ts、opencode.ts 等 9 個(含 Copilot 三種 surface)。opencode 讀 opencode.jsonc(偏好既有 .jsonc,fallback .json,greenfield 建 .jsonc);編輯用 jsonc-parser 做到 surgical,使用者註解與排版在 re-install/uninstall round-trip 後保留。
CodeGraph class。CodeGraph 的架構核心是「單一入口、分層處理」。所有使用方式——CLI 指令、MCP 工具、Library 呼叫——最終都走到同一個 CodeGraph class。這意味著你學會一個入口,就等於學會全部。
四層 pipeline 的設計讓每一層都可以獨立替換或擴展:
src/extraction/languages/ 加一個 extractor 檔案src/resolution/frameworks/ 加一個 pattern matcherGraphTraverser,方便新增 traversal 演算法src/mcp/tools.ts,新增工具只需加一個 function假設你有一個 Express app,想找出「/api/users 這個端點的 handler 做了什麼?」
# 步驟 1:初始化專案
codegraph init
# 步驟 2:搜尋 route 節點
codegraph query /api/users --kind route
# 步驟 3:找出 handler 的 callers
codegraph callers usersHandler
# 步驟 4:分析影響半徑
codegraph impact usersHandler --depth 2
預期產出:你會看到 route 節點 → handler 函式 → 呼叫的 service 層 → 影響的 test 檔案,形成完整的請求處理鏈。
| 錯誤訊息 | 原因 | 解法 |
|---|---|---|
Cannot find module | tree-sitter grammar 未載入 | 執行 codegraph init 重新初始化 |
Database is locked | 多個 process 同時寫入 | 確認只有一個 MCP server 在跑,或設 CODEGRAPH_NO_DAEMON=1 |
No such file: .codegraph/ | 專案未初始化 | 在專案根目錄執行 codegraph init |
codegraph query 找到 route 節點codegraph impact 分析改動影響前面的範例只在一支 app 內追蹤請求。真實世界更常見的場景是40+ package 的 monorepo:前端(TS)、後端 API(Go)、資料處理(Python)混在一起,服務之間靠 HTTP / message queue 溝通。你被要求在大規模 refactor 前產出「跨服務依賴報告」,並把結論交給 AI agent 驗證。
# ① 零設定索引整個 monorepo(副檔名自動分派語言)
codegraph init
# ② 先看 package 佈局,找服務邊界
codegraph files --max-depth 2
# ③ 鎖定跨服務的關鍵符號
codegraph query "PaymentGateway" --kind class
# ④ 一次 explore 拉出跨服務完整呼叫路徑(含 dynamic-dispatch hop)
codegraph explore "checkout 從 web → payment → notification 的完整路徑"
# ⑤ 量化 refactor 的 blast radius
codegraph impact PaymentGateway --depth 3
# ⑥ 把結果丟進 MCP agent session 驗證
# agent 用 codegraph_explore 就能自己追問「改 payment 會影響哪些服務」
為什麼走這條路徑:單一入口 + 零設定讓「一個 index 涵蓋整個 monorepo」成立;explore 的呼叫路徑包含 grep 追不到的 dynamic-dispatch 跳躍(callback、interface→impl),跨服務 hop 一次可見;impact 的數字直接變成 refactor 的風險清單。用 CLI 產出報告、用 MCP 讓 agent 接手追問——兩者驅動同一個 CodeGraph class,答案一定一致。
內部架構:facade 只是門面。CodeGraph class 是典型 facade pattern——它不做事,只把四層接起來:files → ExtractionOrchestrator(Rust kernel 一次跨界)→ DB(SQLite/WAL/FTS5)→ ReferenceResolver(多輪 pass)→ GraphTraverser → ContextBuilder。關鍵在「一個檔案只跨界一次」:Rust kernel 把 tree-sitter grammar 編進 binary,整份檔案一次解析完再回傳結果,而不是每個符號都穿越一次 N-API 邊界——1000 檔專案就是 1000 次跨界 vs 數萬次的差別。
| 症狀 | 可能原因 | 解決方案 |
|---|---|---|
| 某語言的檔案永遠不進圖 | 走 per-file fallback 且 grammar 載入失敗 | codegraph status 看 error 計數;重跑 codegraph init 重載 grammars |
| 查詢結果與磁碟內容不符 | 索引過期(watcher 未在跑) | codegraph sync,或確認 daemon 有啟動 |
| install 後新 agent 沒被列 | registry 沒註冊,或 target 的 detect() 回 false | 檢查 targets/registry.ts 與該 target 的偵測邏輯 |
| 跨服務 trace 斷在 route 節點 | framework resolver 沒認得該路由寫法 | 確認寫法符合慣例;檢查 runPostExtract 是否重跑 detect |
| index 卡住很久不動 | 大目錄未排除,或 WAL 延遲被關 | 排除 node_modules/dist;確認 CODEGRAPH_NO_WAL_DEFER 未設 |
假設你拿到一個 50+ package 的 monorepo(前端 React、後端 Go、資料處理 Python),要做一次大規模 refactor 前的完整依賴審計。以下是從零到產出報告的端到端流程:
# ① 初始化整個 monorepo(副檔名自動分派語言)
cd /path/to/monorepo
codegraph init
# ② 確認索引覆蓋率
codegraph status
# Backend: node:sqlite — built-in (full WAL)
# Indexed 3,842 files → 89,214 nodes, 245,678 edges
# ③ 建立 MCP 連線,讓 agent 參與分析
codegraph serve --mcp &
# ④ 在 agent session 中逐步分析
# ——先摸清 package 佈局
codegraph files --max-depth 3 --filter "packages/"
# ⑤ 鎖定跨服務的關鍵入口
codegraph query "PaymentGateway" --kind class --limit 20
codegraph query "OrderService" --kind class --limit 20
# ⑥ 追蹤從前端 → 後端 → 資料層的完整呼叫路徑
codegraph explore "checkout 從 React checkout page → Go payment API → Python fraud detection 的完整路徑"
# ⑦ 量化 refactor 的 blast radius
codegraph impact PaymentGateway --depth 3
# Impact of changing "PaymentGateway" — 347 affected symbols:
# 42 files, 12 packages, 3 languages
# ⑧ 找出受影響的測試
git diff --name-only HEAD~5 | codegraph affected --stdin --quiet
# → src/payment.test.ts
# → packages/api/payment_test.go
# → tests/test_fraud.py
# ⑨ 把結果產出為報告
codegraph impact PaymentGateway --depth 3 --json > impact-report.json
關鍵觀察:整個流程從 init 到報告只需幾分鐘。單一入口 + 零設定讓跨語言 monorepo 一個 init 涵蓋;explore 跨語言邊界的呼叫路徑是 grep 做不到的;impact 的數字直接變成 refactor 風險清單;affected 把「改什麼」轉成「跑哪些測試」。
| 面向 | 考量 | 實務建議 |
|---|---|---|
| 效能 | 大型 monorepo 的 index 時間與 memory 使用 | 排除 node_modules/dist 等大目錄;用 .gitignore 減少噪音;container-aware worker pool 會自動依核心數調整 |
| 品質 | 跨語言邊界的 heuristic 邊可信度 | 每個 heuristic 邊都標 provenance:'heuristic' + synthesizedBy channel;用 codegraph node 手動抽查關鍵 hop |
| 安全 | 圖譜資料是否洩漏敏感資訊 | 100% 本機 SQLite,無外部服務;telemetry 可關(codegraph telemetry off);verified releases 附 SLSA attestation |
| 面向 | 本文(架構總覽) | 相關文 | 差異說明 |
|---|---|---|---|
| 管線描述 | 四層 pipeline 總覽 + 模組職責表 | 運作原理 | 本文是靜態結構圖,運作原理是動態執行流程 |
| CodeGraph class | 唯一公開入口 + facade pattern | 程式碼對照 · main | 架構頁講角色,程式碼對照講實作細節 |
| Rust kernel | 「一個檔案只跨界一次」效能關鍵 | 語言支援 | 架構頁講跨界策略,語言支援講 20 語言的驗證覆蓋率 |
| 安裝器 | 9 個 target + registry 設計 | CLI 指令、installer 程式碼 | 架構頁是全景,CLI 是操作手冊,程式碼對照是實作 |
CodeGraph 的 facade pattern 為何對「單一入口」原則至關重要
- [ ] 能用 codegraph init + codegraph explore + codegraph impact 完成一個跨語言 monorepo 的依賴審計
- [ ] 能解釋 Rust kernel 的「逐位元組驗證」如何保證跨語言抽取一致性
- [ ] 能在 10 分鐘內用 CLI 產出一份 JSON 格式的 blast radius 報告
- [ ] 能區分 heuristic 邊與 AST 邊的可信度差異,並用 synthesizedBy 追蹤來源