npm 套件 re-export 它的程式化 API,import 和 require 都會解析到你自己 process 裡的 CodeGraph class:
import CodeGraph from '@colbymchenry/codegraph';
// CommonJS 也行:
// const { CodeGraph } = require('@colbymchenry/codegraph');
const cg = await CodeGraph.init('/path/to/project');
// 或:const cg = await CodeGraph.open('/path/to/project');
await cg.indexAll({
onProgress: (p) => console.log(`${p.phase}: ${p.current}/${p.total}`)
});
const results = cg.searchNodes('UserService');
const callers = cg.getCallers(results[0].node.id);
const context = await cg.buildContext('fix login bug', { maxNodes: 20, includeCode: true, format: 'markdown' });
const impact = cg.getImpactRadius(results[0].node.id, 2);
cg.watch(); // 檔案變動自動同步
cg.unwatch(); // 停止 watch
cg.close();
更底層的積木也從同一入口 export(給直接驅動圖的 caller):DatabaseConnection、QueryBuilder、getDatabasePath、initGrammars / loadGrammarsForLanguages、FileLock。
npm i @colbymchenry/codegraph),這樣配對的 per-platform 套件(載編譯好的 library 與依賴)會一起被 fetch。node:sqlite;Electron 的 bundled Node ≥22.5 也算)。CLI 與 MCP server 不受影響——它們跑在 self-contained bundle runtime。@types/node 並設 skipLibCheck: true(常見預設)。| 方法 | 用途 |
|---|---|
CodeGraph.init(root) | 建新專案 + (可選)初始索引 |
CodeGraph.open(root) | 開既有專案(可選 sync) |
indexAll() | 全量索引(帶進度回呼) |
sync() | 增量同步 |
searchNodes(name) | 依名稱搜尋節點 |
getCallers / getCallees | 誰呼叫它 / 它呼叫誰 |
getImpactRadius(id, depth) | 影響半徑 |
buildContext(task, opts) | 為某任務組出 AI 要的上下文(markdown/JSON) |
watch / unwatch | 啟動 / 停止檔案監看自動同步 |
CodeGraph Library 的設計目標是「像使用資料庫一樣使用知識圖譜」——你只需要 init、query、close,所有複雜性都封裝在內部。
嵌入的典型場景:
# 步驟 1:建立專案
mkdir my-analyzer && cd my-analyzer
npm init -y
npm i @colbymchenry/codegraph
# 步驟 2:建立分析腳本
cat > analyze.js << 'EOF'
const CodeGraph = require('@colbymchenry/codegraph');
async function main() {
// 初始化
const cg = await CodeGraph.init('/path/to/project', { index: true });
// 搜尋所有 controller
const controllers = cg.searchNodes('Controller');
console.log(`Found ${controllers.length} controllers`);
// 分析每個 controller 的 callers
for (const ctrl of controllers.slice(0, 5)) {
const callers = cg.getCallers(ctrl.node.id);
console.log(`${ctrl.node.name}: ${callers.length} callers`);
}
// 為特定任務組出上下文
const context = await cg.buildContext(
'fix login bug',
{ maxNodes: 20, includeCode: true, format: 'markdown' }
);
console.log(context.substring(0, 500));
// 關閉
cg.close();
}
main().catch(console.error);
EOF
# 步驟 3:執行分析
node analyze.js
關鍵觀察:Library API 與 CLI/MCP 工具完全對應——searchNodes 對應 codegraph query,getCallers 對應 codegraph callers,buildContext 對應 codegraph explore。
| 錯誤訊息 | 原因 | 解法 |
|---|---|---|
Cannot find module '@colbymchenry/codegraph' | 未安裝或路徑錯誤 | 執行 npm i @colbymchenry/codegraph |
node:sqlite is not supported | Node 版本太舊 | 更新到 Node 22.5+ |
Database is locked | 多個 process 同時寫入 | 確認只有一個 CodeGraph 實例在跑 |
| 回傳結果不完整 | 索引過期或未建立 | 執行 cg.indexAll() 或 cg.sync() |
import 和 require 兩種方式嵌入 CodeGraphsearchNodes 搜尋符號getCallers 分析呼叫關係buildContext 組出 AI 要的上下文前面的範例是互動式分析腳本。這裡是把它做成 CI 產物:每次 build 前自動產生「這次改動會影響誰」的報告,貼到 PR 上,讓 reviewer 不用自己跑指令。
// impact-report.mjs — 用 Library API 組 PR 報告
import CodeGraph from '@colbymchenry/codegraph';
const cg = await CodeGraph.open(process.cwd(), { sync: true });
const changedFiles = process.argv.slice(2); // 從 git diff 餵入
const report = [];
for (const f of changedFiles) {
const nodes = cg.searchNodes(f); // 該檔的符號
for (const { node } of nodes.slice(0, 20)) {
const radius = cg.getImpactRadius(node.id, 2);
if (radius.length) report.push({ file: f, symbol: node.name, affected: radius.length });
}
}
console.log(JSON.stringify(report, null, 2));
cg.close();
為什麼走這條路徑:用 open({ sync: true }) 讓報告永遠基於最新索引;searchNodes + getImpactRadius 是 CLI query/impact 的程式化對等——同一份資料,只是跑在 CI 的 Node runtime。把「影響清單」變成每個 PR 的常駐產物,等於讓整個團隊無痛享用 blast radius。
內部架構:private constructor 的意義。CodeGraph 的 constructor 是 private,一律走 static factory(init/open/recreate)——因為初始化順序有硬性依賴(grammars → DB → layers),開放 new 等於讓使用者踩坑。三個方法預設行為不同:init 預設不索引、open 預設不 sync——都要明確傳旗標。CLI 的 codegraph init 之所以「建目錄 + 建圖一步完成」,是因為它內部傳了 { index: true }。這是「library 保守、CLI 方便」的刻意分歧。
import 與 require 是兩套實作。實際是同一個 class 的兩種語法,行為一致。另一個誤解:以為 library 與 CLI 是不同入口、可能不同步——其實 CLI、MCP server、library 全部驅動同一個 CodeGraph class,這是架構頁「單一入口」原則的直接後果:你在 CLI 學到的行為,在 library 裡 100% 適用。| 症狀 | 可能原因 | 解決方案 |
|---|---|---|
node:sqlite is not supported | Node < 22.5 | 升級 Node,或用 bundle runtime(CLI/MCP 不受此限) |
Database is locked | 多個 CodeGraph 實例同時寫入 | 確認單實例;file lock 會擋住並發索引 |
| watch 回呼 throw LockUnavailableError | 另一 process 正在索引 | 這是設計行為——watcher 保留 pending files 並重排,等鎖釋放 |
indexAll 沒有進度輸出 | 沒傳 onProgress 回呼 | 傳 onProgress: (p) => ... |
| 記憶體暴漲 | 大 repo 一次全量載入 | 改用 sync() 增量;或分批處理查詢結果 |
new CodeGraph(),會有哪些「錯誤初始化順序」?列出具體的失敗情境(例如:DB 未建就 indexAll)。codegraph init 自動建圖——這個「預設值分歧」的設計理由是什麼?如果你是 API 設計者,會怎麼決定?用 CodeGraph Library API 建立一個 Node.js CLI 工具,自動產生「每次 PR 的影響報告」+「架構違規偵測」:
# ① 建立專案
mkdir code-analyzer && cd code-analyzer
npm init -y && npm i @colbymchenry/codegraph
# ② 建立分析腳本
cat > analyze.mjs << 'EOF'
import CodeGraph from '@colbymchenry/codegraph';
const cg = await CodeGraph.open(process.cwd(), { sync: true });
// Part A:找出所有 controller 及其 callers 數量
const controllers = cg.searchNodes('Controller');
for (const { node } of controllers.slice(0, 10)) {
const callers = cg.getCallers(node.id);
console.log(`[CONTROLLER] ${node.name}: ${callers.length} callers`);
}
// Part B:偵測架構違規(底層直接呼叫 DB)
const dbNodes = cg.searchNodes('DatabaseConnection');
for (const { node } of dbNodes) {
const callers = cg.getCallers(node.id);
for (const c of callers) {
if (c.source.includes('controller') || c.source.includes('route')) {
console.log(`[VIOLATION] ${c.name} directly calls DB — should go through service layer`);
}
}
}
// Part C:為特定任務組出上下文
const ctx = await cg.buildContext(
'refactor payment module to use dependency injection',
{ maxNodes: 30, includeCode: true, format: 'markdown' }
);
console.log(`\n[CONTEXT] ${ctx.length} chars of structured context ready`);
cg.close();
EOF
# ③ 執行分析
node analyze.mjs
關鍵觀察:Library API 與 CLI/MCP 完全對應——searchNodes = codegraph query,getCallers = codegraph callers,buildContext = codegraph explore。同一個 CodeGraph class,三種入口。
| 面向 | 考量 | 實務建議 |
|---|---|---|
| 效能 | 大 repo 一次全量載入可能 memory 暴漲 | 用 sync() 增量更新而非 indexAll();分批處理查詢結果 |
| 品質 | private constructor 防止初始化順序錯誤 | 一律走 static factory(init/open/recreate);init 預設不索引,open 預設不 sync |
| 安全 | Node 22.5+ 的 node:sqlite 需求 | Electron bundled Node ≥22.5 也算;CLI/MCP server 跑在 self-contained bundle,不受此限 |
| 面向 | 本文(Library 用法) | 相關文 | 差異說明 |
|---|---|---|---|
| API 對應 | searchNodes / getCallers / buildContext | CLI 指令 | Library 是 JS 物件返回值,CLI 是文字排版輸出 |
| CodeGraph class | private constructor + static factory | 架構總覽 | Library 講 API 使用,架構頁講 facade pattern 設計 |
| init/open 行為 | init 預設不索引、open 預設不 sync | 運作原理 | Library 的預設值更保守,CLI 的 init 自動建圖 |
| watch/unwatch | 啟動/停止檔案監看自動同步 | 自動同步 | Library 講 API,auto-sync 講三層機制的內部運作 |
import 和 require 兩種方式嵌入 CodeGraph Library
- [ ] 能解釋 CodeGraph.init() vs CodeGraph.open() 的預設行為差異
- [ ] 能用 Library API 建立一個自動產生 PR 影響報告的腳本
- [ ] 能解釋 private constructor 為什麼是必要的(防止初始化順序錯誤)
- [ ] 能用 buildContext() 為特定任務組出 AI 要的上下文
- [ ] 能區分 Library(JS runtime)vs CLI/MCP(self-contained bundle)的 Node 版本需求