GitNexus 学习教程

GitNexus 学习教程

从零开始掌握 GitNexus - Zero-Server Code Intelligence Engine

教程日期:2026-03-28


目录

  1. 环境准备
  2. 快速开始
  3. 核心概念
  4. CLI 命令详解
  5. 知识图谱分析
  6. MCP 集成
  7. Graph RAG 使用
  8. Web UI 使用
  9. 高级功能
  10. 最佳实践
  11. 常见问题

一、环境准备

1.1 前置知识

学习 GitNPTus 前建议了解:

知识领域 重要程度 说明
命令行基础 ⭐⭐⭐⭐ CLI 工具使用
Git 基础 ⭐⭐⭐⭐ 仓库操作
代码结构理解 ⭐⭐⭐ 类、函数、模块
AI Agent 概念 ⭐⭐⭐ MCP 协议基础

1.2 系统要求

Node.js 版本:18+
npm 或 pnpm

支持平台:
├── macOS ✅
├── Linux ✅
└── Windows ✅

浏览器(Web UI):
├── Chrome ✅
├── Firefox ✅
└── Safari ✅

1.3 安装

# 全局安装(推荐)
npm install -g gitnexus

# 或使用 pnpm
pnpm add -g gitnexus

# 验证安装
gitnexus --version
# 输出: 1.4.10

1.4 验证安装

# 查看帮助
gitnexus --help

# 输出:
# GitNexus - Zero-Server Code Intelligence Engine
#
# Commands:
#   analyze   Index a repository into a knowledge graph
#   mcp       Start MCP server for AI agents
#   serve     Start local HTTP server for web UI
#   wiki      Generate repository wiki
#   setup     Configure MCP for editors

二、快速开始

2.1 分析第一个仓库

# 分析 GitHub 仓库
gitnexus analyze https://github.com/vercel/next.js

# 输出:
# ✓ Cloning repository...
# ✓ Parsing files with Tree-sitter...
# ✓ Building knowledge graph...
# ✓ Indexing symbols...
# ✓ Done! Indexed 15,234 symbols in 2.3s

2.2 启动 Web UI

# 启动本地 Web 服务
gitnexus serve

# 输出:
# Server running at http://localhost:3000
# Open in browser to explore the knowledge graph

2.3 配置 AI Agent

# 配置 Claude Code
gitnexus setup --client claude

# 输出:
# ✓ MCP server configured for Claude Code
# ✓ Restart Claude Code to use GitNexus tools

2.4 完整示例

# 1. 分析本地项目
gitnexus analyze ./my-project

# 2. 启动 MCP 服务器
gitnexus mcp &

# 3. 在 Claude Code 中使用
# Claude: 查找项目中的认证相关函数
# (GitNexus 会通过 MCP 提供精确的代码定位)

三、核心概念

3.1 知识图谱

┌─────────────────────────────────────────────────────────────────────┐
│                    Knowledge Graph Structure                         │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   节点类型 (Nodes):                                                 │
│   ┌─────────────────────────────────────────────────────────────┐  │
│   │  Symbol Nodes:                                               │  │
│   │  ├── Class (类)                                              │  │
│   │  ├── Function (函数)                                         │  │
│   │  ├── Variable (变量)                                         │  │
│   │  ├── Interface (接口)                                        │  │
│   │  ├── Type (类型)                                             │  │
│   │  └── Method (方法)                                           │  │
│   │                                                              │  │
│   │  Container Nodes:                                            │  │
│   │  ├── File (文件)                                             │  │
│   │  ├── Module (模块)                                           │  │
│   │  └── Package (包)                                            │  │
│   └─────────────────────────────────────────────────────────────┘  │
│                                                                     │
│   边类型 (Edges):                                                   │
│   ┌─────────────────────────────────────────────────────────────┐  │
│   │  CALLS          A 调用 B                                     │  │
│   │  DEPENDS_ON     A 依赖 B                                     │  │
│   │  IMPORTS        A 导入 B                                     │  │
│   │  EXTENDS        A 继承 B                                     │  │
│   │  IMPLEMENTS     A 实现 B                                     │  │
│   │  DEFINES        A 定义 B                                     │  │
│   │  REFERENCES     A 引用 B                                     │  │
│   └─────────────────────────────────────────────────────────────┘  │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

3.2 零服务器架构

GitNexus 完全在客户端运行:

传统方案:
  Client → Server → Database → Parser → 返回结果

GitNexus 方案:
  Browser → WebAssembly → LadybugDB (IndexedDB)
  ↑
  所有处理都在本地完成

优势: - 隐私保护:代码不离开本地 - 零运维:无需服务器 - 离线可用:不需要网络

3.3 Graph RAG

Graph RAG 结合了: - RAG:检索增强生成 - Graph:知识图谱遍历

问题 → 混合检索 → 图遍历 → 上下文组装 → LLM 生成

混合检索:
├── BM25: 关键词精确匹配
├── Semantic: 向量语义搜索
└── RRF: Reciprocal Rank Fusion 融合排序

图遍历:
├── 从匹配节点出发
├── 追踪调用链
├── 扩展依赖关系
└── 收集相关上下文

3.4 MCP (Model Context Protocol)

MCP 是 AI Agent 的标准化工具协议:

┌─────────────────┐                    ┌─────────────────┐
│   AI Agent      │                    │  GitNexus MCP   │
│  (Claude Code)  │◄──── MCP 协议 ────►│     Server      │
│                 │                    │                 │
│  调用工具        │                    │  7 个工具:       │
│  获取结果        │                    │  • list_repos   │
│                 │                    │  • query        │
│                 │                    │  • context      │
│                 │                    │  • impact       │
│                 │                    │  • detect_changes│
│                 │                    │  • rename       │
│                 │                    │  • cypher       │
└─────────────────┘                    └─────────────────┘

四、CLI 命令详解

4.1 analyze 命令

gitnexus analyze <source> [options]

参数

参数 说明 示例
source 源地址(URL/路径/ZIP) ./my-project
--output, -o 输出目录 --output ./graph
--languages, -l 指定语言 -l typescript,python
--exclude 排除模式 --exclude "test/**"
--include 包含模式 --include "src/**"

示例

# 分析 GitHub 仓库
gitnexus analyze https://github.com/facebook/react

# 分析本地目录
gitnexus analyze ./my-project

# 只分析 TypeScript 文件
gitnexus analyze ./my-project --languages typescript

# 排除测试文件
gitnexus analyze ./my-project --exclude "**/*.test.ts"

# 指定输出目录
gitnexus analyze ./my-project --output ./graph-data

4.2 mcp 命令

gitnexus mcp [options]

参数

参数 说明 默认值
--port, -p 服务端口 3000
--config, -c 配置文件 -
--repos, -r 仓库目录 ~/.gitnexus/repos

示例

# 启动 MCP 服务器
gitnexus mcp

# 指定端口
gitnexus mcp --port 4000

# 使用配置文件
gitnexus mcp --config ./gitnexus.config.json

配置文件示例

{
  "repos": [
    {
      "name": "my-project",
      "path": "/path/to/my-project"
    }
  ],
  "tools": {
    "query": { "enabled": true },
    "context": { "enabled": true },
    "impact": { "enabled": true },
    "rename": { "enabled": false }
  }
}

4.3 serve 命令

gitnexus serve [options]

参数

参数 说明 默认值
--port, -p 服务端口 3000
--host, -h 绑定主机 localhost
--open 自动打开浏览器 false

示例

# 启动 Web UI
gitnexus serve

# 指定端口
gitnexus serve --port 8080

# 开放外部访问
gitnexus serve --host 0.0.0.0

# 自动打开浏览器
gitnexus serve --open

4.4 wiki 命令

gitnexus wiki [options]

参数

参数 说明
--repo, -r 仓库名称
--output, -o 输出目录
--format, -f 输出格式 (markdown/html)

示例

# 生成 Wiki
gitnexus wiki --repo my-project --output ./wiki

# 生成 HTML 格式
gitnexus wiki --repo my-project --format html

4.5 setup 命令

gitnexus setup --client <client>

支持的客户端

客户端 参数值
Claude Code claude
Cursor cursor
Windsurf windsurf
OpenCode opencode

示例

# 配置 Claude Code
gitnexus setup --client claude

# 配置 Cursor
gitnexus setup --client cursor

五、知识图谱分析

5.1 理解图谱结构

示例代码:

// user.ts
import { Database } from './database';
import { Logger } from './logger';

export class UserService {
  private db: Database;
  private logger: Logger;

  constructor(db: Database) {
    this.db = db;
  }

  async login(email: string): Promise<User> {
    this.logger.log('login attempt');
    return this.db.findUser(email);
  }
}

生成的知识图谱:

节点:
├── UserService (Class)
├── login (Method)
├── db (Field)
├── logger (Field)
├── Database (Class - 外部)
├── Logger (Class - 外部)
├── User (Type - 外部)
├── user.ts (File)

边:
├── UserService DEFINES login
├── UserService DEFINES db
├── UserService DEFINES logger
├── UserService IMPORTS Database
├── UserService IMPORTS Logger
├── login CALLS Logger.log
├── login CALLS Database.findUser
├── login RETURNS User

5.2 查询图谱

# 使用 CLI 查询
gitnexus query "authentication" --repo my-project

# 输出:
# Found 5 symbols:
# 1. UserService.login (Method)
#    File: src/services/user.ts:25
#    Calls: Logger.log, Database.findUser
#
# 2. AuthService.authenticate (Method)
#    File: src/auth/auth.service.ts:15
#    Calls: UserService.login, TokenService.generate
# ...

5.3 分析调用链

# 分析函数调用链
gitnexus call-chain "UserService.login" --repo my-project

# 输出:
# Call chain for UserService.login:
#
# Callers (谁调用了它):
# ├── AuthService.authenticate
# │   └── AuthController.login
#
# Callees (它调用了谁):
# ├── Logger.log
# └── Database.findUser
#     └── DatabaseConnection.query

5.4 爆炸半径分析

# 分析修改影响范围
gitnexus impact "UserService.login" --repo my-project

# 输出:
# Impact analysis for UserService.login:
#
# Direct dependents: 3
# ├── AuthService.authenticate
# ├── UserController.profile
# └── TestUserService.test_login
#
# Transitive dependents: 12
# └── (显示所有受影响的符号)
#
# Risk level: MEDIUM
# Recommendation: Run tests for AuthService before deploying

六、MCP 集成

6.1 配置 Claude Code

方式 1: 自动配置

gitnexus setup --client claude

方式 2: 手动配置

编辑 ~/.claude/settings.json:

{
  "mcpServers": {
    "gitnexus": {
      "command": "gitnexus",
      "args": ["mcp"],
      "env": {
        "GITNEXUS_REPOS_DIR": "/path/to/repos"
      }
    }
  }
}

6.2 使用 MCP 工具

在 Claude Code 中使用

你: 查找项目中所有的认证相关函数

Claude: [使用 GitNexus query 工具]
找到了以下认证相关函数:

1. UserService.login (src/services/user.ts:25)
   - 用户登录验证

2. AuthService.authenticate (src/auth/auth.service.ts:15)
   - JWT token 验证

3. TokenService.generate (src/auth/token.service.ts:10)
   - 生成访问令牌

6.3 MCP 工具详解

list_repos

// 列出所有已索引的仓库
const repos = await mcp.gitnexus.list_repos();

// 返回:
// [
//   { name: "my-project", symbols: 15234, edges: 45678 },
//   { name: "my-api", symbols: 5432, edges: 12345 }
// ]

query

// 混合搜索
const results = await mcp.gitnexus.query({
  q: "authentication",
  repo: "my-project",
  limit: 10,
  types: ["function", "class"]
});

// 返回:
// [
//   { name: "authenticate", file: "auth.ts", line: 15, score: 0.95 },
//   { name: "AuthService", file: "auth.service.ts", line: 5, score: 0.87 }
// ]

context

// 获取符号完整上下文
const context = await mcp.gitnexus.context({
  symbol: "UserService.login",
  repo: "my-project",
  depth: 2
});

// 返回:
// {
//   symbol: { name: "login", type: "method", file: "user.ts" },
//   callers: [{ name: "AuthService.authenticate", ... }],
//   callees: [{ name: "Logger.log", ... }, { name: "Database.findUser", ... }],
//   dependencies: [{ name: "Database", ... }],
//   definition: "async login(email: string): Promise<User> { ... }"
// }

impact

// 分析修改影响
const impact = await mcp.gitnexus.impact({
  symbol: "UserService.login",
  repo: "my-project"
});

// 返回:
// {
//   directDependents: [...],
//   transitiveDependents: [...],
//   riskLevel: "MEDIUM",
//   recommendations: ["Run AuthService tests", ...]
// }

rename

// 安全重命名
const result = await mcp.gitnexus.rename({
  oldName: "UserService",
  newName: "AccountService",
  repo: "my-project",
  dryRun: true  // 预览模式
});

// 返回:
// {
//   filesAffected: 12,
//   changes: [
//     { file: "user.ts", old: "UserService", new: "AccountService" },
//     { file: "auth.ts", old: "UserService", new: "AccountService" }
//   ]
// }

七、Graph RAG 使用

7.1 基本用法

# 在 Web UI 中使用 Graph RAG
gitnexus serve

# 访问 http://localhost:3000
# 在搜索框输入问题:
# "这个项目的认证流程是怎样的?"

7.2 在 AI Agent 中使用

你: 这个项目的认证流程是怎样的?

Claude (使用 GitNexus Graph RAG):

根据代码分析,认证流程如下:

1. 用户提交登录请求
   - 入口: AuthController.login()
   - 文件: src/controllers/auth.controller.ts

2. 验证用户凭据
   - 调用: AuthService.authenticate()
   - 文件: src/auth/auth.service.ts
   - 依赖: UserService.login()

3. 生成访问令牌
   - 调用: TokenService.generate()
   - 文件: src/auth/token.service.ts

4. 返回 JWT Token
   - 类型: AuthResponse
   - 字段: accessToken, refreshToken, expiresIn

相关代码关系图:
AuthController.login()
    → AuthService.authenticate()
        → UserService.login()
            → Database.findUser()
        → TokenService.generate()

7.3 调试场景

你: 我遇到了一个 Bug:用户登录后 token 无效

Claude (使用 GitNexus 追踪调用链):

让我追踪 token 生成和验证的调用链...

调用链分析:
TokenService.generate() --生成--> TokenService.verify()

发现可能的问题:
1. TokenService.generate() 使用 HS256 算法
2. TokenService.verify() 期望 RS256 算法
3. 算法不匹配导致验证失败

建议修改:
- src/auth/token.service.ts:15
- 将 verify() 的算法改为 HS256

八、Web UI 使用

8.1 启动 Web UI

gitnexus serve

# 输出:
# Server running at http://localhost:3000
# Graph visualization available

8.2 功能区域

┌─────────────────────────────────────────────────────────────────────┐
│                    GitNexus Web UI                                  │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │  Search Bar                                                   │   │
│  │  [搜索符号、文件、问题...]                                     │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                     │
│  ┌──────────────────┐ ┌─────────────────────────────────────────┐  │
│  │                  │ │                                         │  │
│  │  Graph View      │ │  Code View                              │  │
│  │                  │ │                                         │  │
│  │  ┌──────┐       │ │  // UserService.ts                       │  │
│  │  │User  │       │ │  export class UserService {              │  │
│  │  │Service│──┐    │ │    async login(email: string) {         │  │
│  │  └──────┘  │    │ │      // ...                             │  │
│  │            │    │ │    }                                    │  │
│  │  ┌──────┐  │    │ │  }                                      │  │
│  │  │Auth  │◄─┘    │ │                                         │  │
│  │  │Service│       │ │  [调用链] [依赖] [影响分析]              │  │
│  │  └──────┘       │ │                                         │  │
│  │                  │ │                                         │  │
│  └──────────────────┘ └─────────────────────────────────────────┘  │
│                                                                     │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │  Agent Chat                                                   │   │
│  │  [与 Graph RAG Agent 对话]                                    │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

8.3 交互操作

操作 说明
点击节点 查看符号详情
拖拽节点 重新布局
双击节点 跳转到代码
右键菜单 影响分析、调用链
搜索 符号、文件、问题

九、高级功能

9.1 多仓库分析

# 分析多个仓库
gitnexus analyze ./frontend --name frontend
gitnexus analyze ./backend --name backend
gitnexus analyze ./shared --name shared

# MCP 服务器自动服务所有仓库
gitnexus mcp

9.2 自定义解析

# 只解析特定目录
gitnexus analyze ./my-project --include "src/**" --exclude "**/*.test.ts"

# 指定语言
gitnexus analyze ./my-project --languages typescript,python

9.3 增量更新

# 增量更新(只重新解析修改的文件)
gitnexus analyze ./my-project --incremental

9.4 导出图谱

# 导出为 JSON
gitnexus export ./my-project --format json --output graph.json

# 导出为 GraphML
gitnexus export ./my-project --format graphml --output graph.graphml

十、最佳实践

10.1 项目结构优化

好的结构(GitNexus 易于分析):
my-project/
├── src/
│   ├── services/          # 清晰的模块划分
│   ├── controllers/
│   └── models/
└── package.json

不好的结构(GitNexus 难以分析):
my-project/
├── all-in-one.js          # 所有代码在一个文件
├── utils/                 # 过于分散
│   └── *.js (100+ files)
└── package.json

10.2 命名规范

好的命名(GitNexus 易于理解):
- UserService
- AuthService
- DatabaseConnection

不好的命名(GitNexus 难以理解):
- US
- AS
- DC

10.3 定期更新

# 定期更新图谱(CI/CD 集成)
# .github/workflows/update-graph.yml
name: Update GitNexus Graph
on:
  push:
    branches: [main]
jobs:
  update:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - run: npm install -g gitnexus
      - run: gitnexus analyze . --output ./graph
      - uses: actions/upload-artifact@v3
        with:
          name: knowledge-graph
          path: ./graph

10.4 团队协作

# 共享图谱配置
# gitnexus.config.json
{
  "version": "1.0",
  "repos": [...],
  "exclude": ["**/*.test.ts", "**/dist/**"],
  "include": ["src/**"]
}

# 提交到版本控制
git add gitnexus.config.json

十一、常见问题

Q1: 分析大型仓库很慢

原因: 文件数量多,解析耗时

解决:

# 只包含需要的目录
gitnexus analyze ./large-project --include "src/**"

# 排除不需要的目录
gitnexus analyze ./large-project --exclude "test/**", "docs/**"

Q2: 图谱不完整

原因: 语言不支持或解析错误

解决:

# 查看支持的
gitnexus analyze ./my-project --languages typescript,python

# 查看解析日志
gitnexus analyze ./my-project --verbose

Q3: MCP 连接失败

原因: 端口被占用或配置错误

解决:

# 检查端口
lsof -i :3000

# 使用其他端口
gitnexus mcp --port 4000

Q4: 搜索结果不准确

原因: 图谱未更新或查询词不精确

解决:

# 更新图谱
gitnexus analyze ./my-project --incremental

# 使用更精确的查询
gitnexus query "UserService.login" --repo my-project

Q5: 商业使用问题

原因: GitNexus 使用 PolyForm Noncommercial License

解决: - 个人/非商业使用: 免费 - 商业使用: 联系作者获取商业许可


参考资源

官方资源

  • GitHub: https://github.com/abhigyanpatwari/GitNexus
  • 官网: https://gitnexus.vercel.app
  • NPM: https://www.npmjs.com/package/gitnexus
  • Discord: https://discord.gg/AAsRVT6fGb

文档

  • ARCHITECTURE.md - 架构详解
  • RUNBOOK.md - 运维手册
  • GUARDRAILS.md - 贡献规则
  • TESTING.md - 测试指南

教程生成时间:2026-03-28