CodeGraph 架構總覽

分層 pipeline + 各模組職責——讀源碼前的導航圖

分層 Pipeline

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.tsCodeGraph class:init/open/close、indexAll、sync、searchNodes、getCallers/Callees、getImpactRadius、buildContext、watch/unwatchmain
src/db/DatabaseConnection、QueryBuilder(prepared statements)、schema.sql、sqlite-adapter;Node 內建 node:sqlite(DatabaseSync)+ WAL + FTS5,無原生 builddb
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 全文搜尋的查詢解析與 helperdb
src/sync/FileWatcher(原生 FSEvents/inotify/RDCW)debounce + filter、git-hook helpersauto-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.tsCLI(commander):install、init、uninit、index、sync、status、query、files、context、affected、serve --mcpcli
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 後保留。

設計要點

看完這頁你應該能說出:分層 pipeline 的四層、CodeGraph class 是唯一公開入口、新增一個 agent target 只需「一個新檔案 + registry 一列」、以及 Rust kernel 與可攜引擎的關係。

🎓 教學解說

CodeGraph 的架構核心是「單一入口、分層處理」。所有使用方式——CLI 指令、MCP 工具、Library 呼叫——最終都走到同一個 CodeGraph class。這意味著你學會一個入口,就等於學會全部。

四層 pipeline 的設計讓每一層都可以獨立替換或擴展:

Worked Example:追蹤一個 API 請求的完整路徑

假設你有一個 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 moduletree-sitter grammar 未載入執行 codegraph init 重新初始化
Database is locked多個 process 同時寫入確認只有一個 MCP server 在跑,或設 CODEGRAPH_NO_DAEMON=1
No such file: .codegraph/專案未初始化在專案根目錄執行 codegraph init

練習:驗收清單


🔍 進階真實情境 Worked Example:大型 monorepo × 跨服務 trace × MCP

前面的範例只在一支 app 內追蹤請求。真實世界更常見的場景是40+ package 的 monorepo:前端(TS)、後端 API(Go)、資料處理(Python)混在一起,服務之間靠 HTTP / message queue 溝通。你被要求在大規模 refactor 前產出「跨服務依賴報告」,並把結論交給 AI agent 驗證。

monorepo 分析工作流
# ① 零設定索引整個 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 數萬次的差別。

大家以為分析正確但其實有誤:很多人以為「Rust kernel = 20 份獨立的完整解析器」。實際上 kernel 是共享的 tree-sitter runtime + 每語言一份 walker 規格;而且「解析成什麼節點」的規格同時存在 TS 可攜引擎與 Rust 兩邊,靠「逐位元組驗證」保證一致——Rust 只負責「快」,不負責「決定語意」。另一個常被誤解的假設是「pipeline 是同步直線」:其實 resolver 有多輪 pass、WAL checkpoint 有背景 valve、重解析在 worker pool——看到「index 花了 1.7s」不是單執行緒跑完的。

🩺 診斷式疑難排解表

症狀可能原因解決方案
某語言的檔案永遠不進圖走 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 未設

🧩 進階挑戰題

  1. 假設你要新增「module」節點層級,讓 explore 能回傳「某 package 的邊界摘要」。從 schema.sql、extraction、resolution 到 context 格式,各列一處你必須改動的地方。
  2. 解釋「一個檔案只跨界一次」為何是效能關鍵。對 1000 檔、每檔平均 30 個符號的專案,「每檔一次」vs「每符號一次」的跨界次數各是多少?
  3. 給定「查某 symbol 的 callers 回傳空結果」,列出至少三種可能原因,並為每一種寫出對應的驗證指令。

🏗️ 專案級端到端 Worked Example:大型 monorepo 完整分析專案

假設你拿到一個 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 是操作手冊,程式碼對照是實作

✅ 進階互動式檢核清單

- [ ] 能畫出完整的四層 pipeline 圖,並標出每層的輸入/輸出資料格式 - [ ] 能解釋 CodeGraph 的 facade pattern 為何對「單一入口」原則至關重要 - [ ] 能用 codegraph init + codegraph explore + codegraph impact 完成一個跨語言 monorepo 的依賴審計 - [ ] 能解釋 Rust kernel 的「逐位元組驗證」如何保證跨語言抽取一致性 - [ ] 能在 10 分鐘內用 CLI 產出一份 JSON 格式的 blast radius 報告 - [ ] 能區分 heuristic 邊與 AST 邊的可信度差異,並用 synthesizedBy 追蹤來源