Library 用法

CodeGraph 可以直接嵌進你的應用(例如 Electron main process)
npm 套件 re-export 程式化 API · import 與 require 都可用 · Node 22.5+

嵌入範例

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。

嵌入需求

類別方法速查

方法用途
CodeGraph.init(root)建新專案 + (可選)初始索引
CodeGraph.open(root)開既有專案(可選 sync)
indexAll()全量索引(帶進度回呼)
sync()增量同步
searchNodes(name)依名稱搜尋節點
getCallers / getCallees誰呼叫它 / 它呼叫誰
getImpactRadius(id, depth)影響半徑
buildContext(task, opts)為某任務組出 AI 要的上下文(markdown/JSON)
watch / unwatch啟動 / 停止檔案監看自動同步
看完這頁你應該能說出:嵌入的兩種語法、Node 22.5+ 的原因(node:sqlite)、以及 watch/unwatch 與 CLI 的 daemon 同步的關係。

🎓 教學解說

CodeGraph Library 的設計目標是「像使用資料庫一樣使用知識圖譜」——你只需要 init、query、close,所有複雜性都封裝在內部。

嵌入的典型場景:

Worked Example:建立自訂程式碼分析工具

Library 嵌入實作
# 步驟 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 supportedNode 版本太舊更新到 Node 22.5+
Database is locked多個 process 同時寫入確認只有一個 CodeGraph 實例在跑
回傳結果不完整索引過期或未建立執行 cg.indexAll() 或 cg.sync()

練習:驗收清單


🔍 進階真實情境 Worked Example:CI 自動影響報告產生器

前面的範例是互動式分析腳本。這裡是把它做成 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 supportedNode < 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() 增量;或分批處理查詢結果

🧩 進階挑戰題

  1. 如果允許 new CodeGraph(),會有哪些「錯誤初始化順序」?列出具體的失敗情境(例如:DB 未建就 indexAll)。
  2. 設計一個「每次 build 前自動產生影響報告」的 CI 腳本(用 Library API)。列出你選用的 API、失敗處理(索引不存在、lock 被佔)與輸出格式。
  3. init 預設不索引 vs CLI 的 codegraph init 自動建圖——這個「預設值分歧」的設計理由是什麼?如果你是 API 設計者,會怎麼決定?

🏗️ 專案級端到端 Worked Example:用 Library API 建立 IDE 級程式碼分析工具

用 CodeGraph Library API 建立一個 Node.js CLI 工具,自動產生「每次 PR 的影響報告」+「架構違規偵測」:

IDE 級分析工具
# ① 建立專案
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 / buildContextCLI 指令Library 是 JS 物件返回值,CLI 是文字排版輸出
CodeGraph classprivate 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 版本需求