Skip to main content

Project Brain

面向 AI Agent 的项目知识图谱引擎

Project Brain 是一个本地化的代码知识图谱引擎,专为 AI 编程助手(如 Claude Code、Cursor、Cline、ZCode 等)设计。它通过分析项目代码、文档和 Git 历史,构建结构化的代码知识图谱,让 AI Agent 能深度理解项目架构。

核心特性

  • 多语言代码图谱:Python、TypeScript、JavaScript、Rust、C、C++、Go、Java,tree-sitter 静态分析,零 LLM 依赖
  • 混合检索:BM25 + FAISS 语义向量(RRF 融合)
  • 实时监听:文件变更自动增量更新知识图谱
  • MCP 协议:20 个工具,与 Claude Code、Cursor、ZCode 等无缝集成
  • 本地运行:代码数据不出本地,安全可控
  • 智能推理:影响分析、测试推荐、风险评估
  • Wiki 拉取:一键拉取华为内源 Wiki 为 Markdown 并增量更新图谱(pull_wiki)

快速开始

安装

# 使用 uv(推荐)
uv tool install bot-brain

# 或使用 pip
pip install bot-brain

# 如需刷新 wiki 登录态(可选)
pip install "bot-brain[wiki]"   # 安装 playwright

包名说明:本项目 PyPI 包名为 bot-brain(原名 project-brain 在 PyPI 已被占用,故更名);命令行入口同时保留 bot-brain 与 project-brain 两个名字,import 名仍为 project_brain。

安装后包含语义检索(FAISS + fastembed),默认使用 hybrid 策略(BM25 + 向量 RRF 融合)。嵌入模型 snowflake/arctic-embed-s 首次使用时自动下载,之后缓存在本地(model/ 目录),无需联网。

pull_wiki 工具只需 requests/urllib3(已随主依赖安装);[wiki] extra 仅在需要浏览器登录刷新 cookie 时才需要。

开发版/未发布功能:PyPI 上的发布版本可能落后于源码。若 bot-brain <命令> 不可用(如尚未发布的 pull-wiki),请用 python -m project_brain <命令> 运行源码版,或从源码安装:pip install -e . --force-reinstall 后用 python -m project_brain 确认入口指向本地源码。

查看版本:

bot-brain --version

在项目配置 .botbrain/config.yaml 中调整检索策略:

search:
  strategy: hybrid    # hybrid(默认,BM25 + 向量 RRF 融合)| semantic | keyword
  index_body: true    # 索引函数体,提升召回(增大索引体积)
  model_precision: int8  # 模型量化精度:int8(小/快)| full(大/准)
  • hybrid 策略同时用 BM25 和向量检索,RRF 融合排序,效果最佳(默认)
  • 语义索引按 test/normal 分离构建,keyword_search 支持 test_filter(normal/test/all)三态过滤

构建知识图谱

# 分析当前项目(默认 full Profile,包含全部符号、测试和 Git 历史)
bot-brain build

# 分析指定项目
bot-brain --project /path/to/project build

# 构建 mini Profile:只含公开 API 和文档,排除私有符号/测试/Git 历史
bot-brain build --profile mini

# 查看当前 Profile 的保留/排除计划(不触发构建)
bot-brain build --explain-profile

# 为指定文档保存可离线查询的完整构建快照(参数可重复)
bot-brain build \
  --store-doc-content "README.md" \
  --store-doc-content "docs/architecture/**"

# 只索引匹配的文件:include 白名单 + exclude 黑名单(参数均可重复,仅本次构建生效)
bot-brain build --include "src/**" --include "docs/*.md"
bot-brain build --exclude "docs/wiki/**" --exclude "*.generated.*"

构建范围 include / exclude

--include / --exclude 控制扫描阶段哪些文件进入图谱(代码与文档都受约束)。 两者是可选的按次生效 flag:每次调用 bot-brain build 时手动指定,仅影响 本次构建,不写回 .botbrain/config.yaml;未指定时按配置文件中的 project.include / project.exclude 扫描:

  • --include PATTERN:设置白名单;默认为空 = 包含一切。非空时只有命中 任一 pattern 的文件入图(pyproject.toml 等清单文件作为元数据来源不受白名单限制)
  • --exclude PATTERN:本次构建临时替换排除列表(.git/、node_modules/、 *.generated.* 等——传入即整体替换,请给出完整列表)
  • pattern 语法与 project.exclude 一致:glob(*.py)、路径前缀 (docs/wiki/,含 build/ 这类尾斜杠单段——锚定项目根目录, 不会匹配 src/pkg/build/ 等嵌套同名目录)、裸段名任意深度 (node_modules)
  • exclude 永远优先;隐藏文件与根级垃圾目录(.git、node_modules、 __pycache__ 等)无条件排除,include 无法覆盖。注意:这些目录深层 位置的排除依赖默认 project.exclude 列表,被 --exclude 整体替换后 深层同名目录会重新纳入扫描
  • --include 是范围控制而非性能优化:目录遍历不做白名单剪枝(避免 src/** 不匹配目录 src 自身导致整棵子树丢失),大仓仍会全树遍历后 过滤文件,扫描耗时不变
  • 需要持久化的扫描范围请直接编辑 .botbrain/config.yaml 的 project.include / project.exclude。watcher / serve 始终按配置文件的 范围工作:用 flag 收窄构建出的图谱与配置 digest 不一致,下次 serve 时会 触发全量重建回到配置范围

Mini Graph Profile

--profile mini 构建一个只包含公开 API 和文档的知识图谱:

  • 保留:公开函数/类/方法、公开模块、文档/Section/Concept/Convention、File/Module(作为内部基础设施)
  • 排除:私有符号、测试函数、Git 历史(commit/PR/diff)、TEST/MODIFY 边
  • Rust 特化:基于 pub mod/pub use/crate-root 可达性计算真实公开 API; trait 无方法体方法、inline module、#[cfg(test)] 模块均正确处理
  • 能力声明:mini Profile 下 get_history/get_owner/get_related_tests/ test_recommendation 返回结构化 tool_unavailable 错误;impact_analysis 不返回误导性 low 风险
  • 配置持久化:Profile 写入 .botbrain/config.yaml,变更自动触发全量重建
graph:
  profile: mini              # full(默认)| mini
  public_api:
    include_public_methods: true
    include_tests: false
    include_support_types: true    # P1 占位
    include_module_dependencies: true  # P1 占位

已知限制:pub use x::*(glob re-export)和 pub use x::Y as Z(alias) 尚未完整支持,详见 docs/mini-profile-known-issues.md。

--store-doc-content 会写回 .botbrain/config.yaml,保证后续 MCP 服务和文件监听增量更新继续使用同一策略。选中的正文只在 Document 节点 保存一份;搜索返回命中位置附近的短预览,完整正文通过 get_content 按需读取。 重复传入该参数会替换已有的 include 列表。路径必须使用项目相对的 POSIX glob(/ 分隔);exclude 优先于 include。

解析证据审计与可选 Clang 语义层

parser-audit 对真实仓库执行只读扫描,输出各语言的 clean/recovered/failed 文件数、字节加权解析覆盖率、符号数量和带源码范围的关系事实数量。通过期望 清单可以持续计算精确符号召回率:

bot-brain --project /path/to/libsmb2 parser-audit \
  --language c \
  --expectations benchmarks/parser/libsmb2-s01.json \
  --fail-under 1.0 \
  --output parser-audit.json

C/C++ 项目存在 compile_commands.json 且系统可找到 clang/clang++ 时, 默认的 auto 模式会保留 tree-sitter 的容错结构和原始源码范围,同时用 Clang JSON AST 补充确定的调用 owner、目标声明 ID 和证据 provenance。编译参数经过 白名单过滤,不执行原始编译器、插件或响应文件。

parsing:
  semantic_backend: auto  # off | auto(默认)| required

跨语言关系只在存在显式证据时生成:Rust/C extern "C" 声明与定义产生 FFI_BIND,Python ctypes.CDLL/cffi.dlopen 或 C ABI 调用产生 FFI_CALL。 普通同名函数不会跨语言自动连接。

C/C++ 关系解析还会保留类型前置声明、继承覆盖、模板使用和宏展开证据: DECLARE 同时支持函数与 struct/class/symbol 声明,OVERRIDES 要求继承关系及 规范化方法签名一致,TEMPLATE_SPECIALIZATION 区分函数模板显式调用和具体模板 类型绑定,MACRO_CALLS 覆盖函数到宏及宏到宏的展开链。直接回调关系仅在实参为 函数标识符、目标形参为函数指针或其 typedef,且回调目标唯一时生成 CALL。 重复调用位置按文件分别保存在边的 locations/lines_by_file 证据中。

查看项目信息

bot-brain info

输出示例:

Project: /path/to/project
Graph profile: full
Search strategy: keyword
Storage backend: auto

Knowledge Graph:
  Total nodes: 312
  Total edges: 580
  class: 12
  concept: 5
  document: 3
  file: 46
  Functions: 328
  Classes: 37
  Modules: 7
  Documents: 9
  Commits: 25
  Conventions: 3

启动 MCP 服务

# 使用 stdio 传输(默认,MCP 标准方式)
bot-brain serve

HTTP 传输(局域网访问)

# StreamableHTTP 无状态模式(推荐本机或反向代理后使用)
bot-brain serve --transport streamable-http --stateless --json-response

# 指定端口
bot-brain serve --transport streamable-http --port 9000 --stateless --json-response

客户端连接端点:http://127.0.0.1:8000/mcp

健康检查:GET http://127.0.0.1:8000/healthz → {"status": "ok"}

局域网部署(需安全反向代理):

# 绑定局域网 IP(必须显式确认风险 + 提供 allowed-host)
bot-brain serve --transport streamable-http \
  --host 0.0.0.0 \
  --insecure-allow-remote \
  --allowed-host 192.168.1.20:8000 \
  --stateless --json-response

⚠️ 安全警告:MCP 工具可读取源码、文档和 Git 历史。直接暴露到网络有数据泄露风险。 推荐方案:绑定 127.0.0.1 + 使用 Caddy/Nginx 反向代理(提供 TLS、认证、限流)。

CLI 参数:

参数 默认值 说明
--transport stdio 传输类型:stdio 或 streamable-http
--host 127.0.0.1 HTTP 绑定地址(非 loopback 需 --insecure-allow-remote)
--port 8000 HTTP 端口
--stateless false 无状态模式(每请求独立 session,仅 streamable-http)
--json-response false 纯 JSON 响应替代 SSE 流(仅 streamable-http)
--insecure-allow-remote false 允许非 loopback 绑定(风险确认)
--allowed-host [] 允许的 Host header(可重复,DNS-rebinding 防护)
--allowed-origin [] 允许的 Origin(浏览器客户端,可重复)

命令行查询

除了通过 MCP 给 Agent 用,19 个查询工具也支持命令行直接调用,便于脚本、调试和 CI 检查。默认输出人类可读表格,加 --json 输出与 MCP 一致的原始 JSON(适合管道处理)。此外还有 pull-wiki 命令用于拉取华为内源 Wiki(见下文)。

# 所有查询命令都支持 --project 指定项目(默认当前目录)
bot-brain --project /path/to/project <command> [options]

代码查询命令(19 个):

命令 说明 示例
search 关键词/语义搜索 bot-brain search "timeout" --top-k 5
locate 按名定位符号 bot-brain locate Poll --kind class
symbol 符号详情(含调用关系) bot-brain symbol Poll --include callers
calls 调用图查询 bot-brain calls spawn --direction callers --depth 2
context 多维上下文(RAG) bot-brain context Poll --scope callers
module 模块符号列表 bot-brain module ylong_io --exported-only
file 文件内符号 bot-brain file src/poll.rs
deps 模块依赖 bot-brain deps ylong_io --direction up
tests 关联测试 bot-brain tests Poll
history 修改历史 bot-brain history src/poll.rs --limit 20
owner 代码归属 bot-brain owner src/poll.rs
diff 变更 diff(样本对) bot-brain diff abc123 --format pair
docs 文档列表 bot-brain docs --pattern "*.md"
conventions 项目约定 bot-brain conventions
doc-links 文档-符号关联 bot-brain doc-links JsonValue
impact 影响分析 bot-brain impact Poll
recommend-tests 测试推荐 bot-brain recommend-tests src/poll.rs
code 代码/文档片段 bot-brain code Poll --kind class

Wiki 拉取命令:

命令 说明 示例
pull-wiki 拉取华为内源 Wiki 为 Markdown 并增量更新图谱 bot-brain pull-wiki --url "https://wiki.huawei.com/domains/123/wiki/456/SN001"
# 拉取单个 wiki 页面(默认不含引用/子页面)
bot-brain pull-wiki --url "https://wiki.huawei.com/domains/123/wiki/456/SN001"

# 拉取整个看板下所有文档
bot-brain pull-wiki --url "https://wiki.huawei.com/domains/123/wiki/456" -all

# 拉取单页及其引用页和子页面
bot-brain pull-wiki --url "https://wiki.huawei.com/domains/123/wiki/456/SN001" --ref --child

# 指定输出目录、JSON 输出
bot-brain pull-wiki --url "..." --output docs/my-wiki --json

pull-wiki 参数:

参数 说明
--url(必填) Wiki 页面 URL;末段带 SN(如 .../456/SN001)拉单页,不带 SN 配合 -all 拉整个看板
-all 拉取整个看板下所有文档(URL 不带 SN 时使用)
--ref 同时拉取文中引用的 wiki 页面(跨链接目标)
--child 递归拉取子页面
-no-ref 显式不拉引用页;优先级高于 --ref 和 wiki.include_refs 配置
-no-child 显式不拉子页面;优先级高于 --child 和 wiki.include_children 配置
--output 下载目录(默认 docs/wiki 或 wiki.output_dir 配置)
--json 输出原始 JSON(含 downloaded_count、graph_updated_files、build_status)

--ref/--child 都未给出时,回退到 wiki.include_refs / wiki.include_children 配置默认值(默认均为 false)。即优先级:显式旗标 > 配置默认 > false。

需要 wiki 登录 cookie(wiki.cookie_file 配置,默认 ~/.botbrain/wiki_cookies.json)。cookie 失效时会自动弹出浏览器要求手动登录 W3(需 pip install "bot-brain[wiki]")。

下载期间文件监听自动暂停(不触发逐文件重建),下载完成后恢复监听并对下载文件触发增量图谱更新。需有效的 wiki 登录 cookie(见 wiki.cookie_file 配置)。

输出格式:

# 默认:人类可读表格
bot-brain search "timeout"
# Found 3 result(s) (freshness: idle, 0.2s ago)
#
# SCORE  SYMBOL                          LOCATION
# 0.030  ClientBuilder::request_timeout  src/.../client.rs:246
# ...

# --json:原始 JSON(与 MCP 返回一致,适合 jq 等工具)
bot-brain search "timeout" --json | jq '.results[0]'

常用参数: --json(所有命令)、--top-k(search)、--kind(locate/code)、--direction(calls/deps)、--depth(calls/context)、--include(symbol)、--exported-only(module)、--limit(history)、--format(diff)、--scope/--pattern(docs)。

与 AI 工具集成

Claude Code

在 ~/.claude/claude_desktop_config.json 中添加:

{
  "mcpServers": {
    "bot-brain": {
      "command": "bot-brain",
      "args": ["serve"]
    }
  }
}

Cursor

在 .cursor/mcp.json 中添加:

{
  "mcpServers": {
    "bot-brain": {
      "command": "bot-brain",
      "args": ["serve"]
    }
  }
}

OpenCode

编辑 OpenCode 配置文件 ~/.config/opencode/opencode.json(Windows: %APPDATA%\opencode\opencode.json),添加 MCP 配置:

{
  "mcp": {
    "bot-brain": {
      "type": "local",
      "command": ["bot-brain", "--project", "/path/to/your/project", "serve"],
      "enabled": true
    }
  }
}

与 Claude Code/Cursor 的区别:

  • 字段名是 mcp(不是 mcpServers)
  • type: "local" 必填
  • command 是数组格式,包含命令和所有参数
  • --project 指定要分析的项目路径(不填则默认当前目录)

安装 Skill(可选,教 Agent 何时调用 bot-brain 工具):

# 将 skill 文件复制到项目的 .opencode/skills/ 目录
mkdir -p .opencode/skills/bot-brain
cp skills/opencode/bot-brain.md .opencode/skills/bot-brain/SKILL.md

Cline

在 Cline 的 MCP 设置中添加服务器:

  • Command: bot-brain
  • Args: serve

通过 HTTP 连接(streamable-http)

如果 MCP 服务器已通过 bot-brain serve --transport streamable-http 部署, 客户端可以通过 HTTP URL 连接,无需启动子进程。

Claude Code(支持 HTTP 的版本):

{
  "mcpServers": {
    "bot-brain": {
      "type": "streamable-http",
      "url": "http://127.0.0.1:8000/mcp"
    }
  }
}

Cursor(支持 HTTP 的版本):

{
  "mcpServers": {
    "bot-brain": {
      "type": "streamable-http",
      "url": "http://127.0.0.1:8000/mcp"
    }
  }
}

OpenCode:

{
  "mcp": {
    "bot-brain": {
      "type": "http",
      "url": "http://127.0.0.1:8000/mcp",
      "enabled": true
    }
  }
}

注意:不同 AI 工具对 HTTP 传输的支持程度和配置格式可能不同,请参考各工具的 MCP 文档。 如果工具不支持 streamable-http,继续使用 stdio 模式即可。

MCP 工具

Project Brain 提供 20 个 MCP 工具,分为 9 类:

搜索类

工具 说明 示例
keyword_search 关键词搜索(支持 test/normal 过滤) keyword_search("订单超时", test_filter="normal")
locate_symbol 符号定位 locate_symbol("OrderService")
get_symbol_info 符号详情(按需返回) get_symbol_info("cls_abc123", include="callers/tests")
list_documents 文档目录列表 list_documents(scope="docs/")

上下文类

工具 说明 示例
get_context 多维上下文组装 get_context("fn_abc123", scope="all", depth=2)
get_content 代码/文档片段;支持构建快照、行范围及游标续读 get_content("doc_abc123", source="graph", max_bytes=65536)
get_module_contents 模块内容(支持 exported_only、feature、max_items) get_module_contents("mod_order", exported_only=true)
get_file_symbols 文件符号 get_file_symbols("src/order.py")

关系类

工具 说明 示例
get_call_graph 调用图查询(callers/callees/both) get_call_graph("fn_abc123", direction="callers", depth=2)
get_dependencies 依赖关系 get_dependencies("mod_order", direction="both")

测试类

工具 说明 示例
get_related_tests 关联测试 get_related_tests("fn_abc123")

历史类

工具 说明 示例
get_history 修改历史 get_history("src/order.py", limit=10)
get_owner 代码归属 get_owner("src/order.py")
get_change_diff 变更 diff(样本对) get_change_diff("abc123", format="pair")

约定/文档类

工具 说明 示例
get_conventions 项目约定 get_conventions()
get_doc_links 文档关联 get_doc_links("cls_abc123")

推理类

工具 说明 示例
impact_analysis 影响分析 impact_analysis("fn_abc123")
test_recommendation 测试推荐 test_recommendation(["src/order.py"])

能力声明类

工具 说明 示例
get_graph_capabilities 查询 Profile、节点类型、工具能力表和语义搜索状态 get_graph_capabilities()

文档导入类

工具 说明 示例
pull_wiki 拉取华为内源 Wiki 为 Markdown 并增量更新图谱(下载时暂停监听) pull_wiki("https://wiki.huawei.com/.../SN001")

pull_wiki 可选参数:all_docs(拉整个看板)、include_refs/include_children(含引用/子页面,不传时回退 wiki.include_refs/wiki.include_children 配置默认值)、output_dir(覆盖下载目录)。需 wiki.cookie_file 配置有效的登录 cookie。

使用场景

场景 1:定位功能实现

用户:订单超时逻辑在哪里?

Agent 工作流:

1. keyword_search("订单超时")
2. locate_symbol("OrderTimeoutHandler")
3. get_call_graph("handleTimeout", direction="callers")
4. get_related_tests("handleTimeout")

Agent 回复:订单超时逻辑位于 src/order/timeout.rs:42,被 OrderService.process() 调用,相关测试在 tests/order/timeout_test.rs。

场景 2:重构影响评估

用户:我想修改 calculatePrice 的签名

Agent 工作流:

1. locate_symbol("calculatePrice")
2. impact_analysis("calculatePrice")
3. get_call_graph("calculatePrice", direction="callers", depth=3)
4. get_related_tests("calculatePrice")

Agent 回复:修改 calculatePrice 会影响 5 个调用方,涉及 3 个模块。风险等级:中等。需要更新测试:test_calculate_price、test_order_total。

场景 3:RAG 上下文组装

用户:如何实现订单超时处理?

Agent 工作流:

1. list_documents(scope="docs/")  # 查看文档目录
2. get_context("handleTimeout", scope="all", depth=2)  # 获取多维上下文
3. get_content("handleTimeout", kind="function")  # 获取代码片段

Agent 回复:订单超时处理的核心逻辑在 handleTimeout 函数中,它被 OrderService.process() 调用,调用了 cancelOrder 和 sendNotification。相关文档在 docs/order-design.md 的"超时处理"章节。

场景 4:代码样本对提取

用户:最近有哪些 bug 修复?

Agent 工作流:

1. get_history("src/order.py", limit=10)
2. get_change_diff("abc123", format="pair")  # 获取 before/after 代码对

Agent 回复:最近修复了 2 个 bug:

  1. commit abc123:修复了订单金额计算错误(修改了 calculateOrderTotal)
  2. commit def456:修复了超时处理竞态条件(修改了 handleTimeout)

场景 5:理解模块结构

用户:payment 模块是做什么的?

Agent 工作流:

1. locate_symbol("payment", kind="module")
2. get_module_contents("mod_payment")
3. get_dependencies("mod_payment", direction="both")
4. get_doc_links("mod_payment")

Agent 回复:payment 模块负责支付处理,包含 PaymentService、PaymentProcessor、RefundHandler。它依赖 order 模块,被 api 模块使用。详见 docs/payment-design.md。

场景 6:Bug 调查

用户:为什么订单金额计算错误?

Agent 工作流:

1. keyword_search("订单金额 计算")
2. locate_symbol("calculateOrderTotal")
3. get_call_graph("calculateOrderTotal", direction="callers", depth=2)
4. get_call_graph("calculateOrderTotal", direction="callees", depth=1)
5. get_history("calculateOrderTotal")

Agent 回复:calculateOrderTotal 最近 3 天被修改过 2 次(commit abc123, def456),调用了 applyDiscount 和 calculateTax。建议检查 applyDiscount 的逻辑。

场景 7:测试计划

用户:我修改了 order.py,应该运行哪些测试?

Agent 工作流:

1. get_file_symbols("src/order.py")
2. get_related_tests("fn_create_order")
3. get_related_tests("fn_validate_order")

Agent 回复:建议运行以下测试:

  • 直接测试:test_create_order、test_validate_order
  • 间接测试:test_order_workflow(测试了调用方)

配置

在项目根目录创建 .botbrain/config.yaml:

# 项目配置
project:
  name: "my-project"
  languages: [python, typescript]
  exclude:
    - "vendor"        # 裸段名:任意深度;仅匹配根级目录用 "vendor/"
    - "*.generated.*"
    - "migrations"    # 任意深度(Django 的 app 内嵌 migrations/ 也会排除)

# 搜索配置(代码图谱)
search:
  strategy: hybrid  # hybrid(默认)| keyword | semantic
  index_body: false
  model_precision: int8  # int8(小/快)| full(大/准)

# 图谱 Profile 配置
graph:
  profile: full  # full(默认,全部符号/测试/Git 历史)| mini(公开 API + 文档)
  public_api:
    include_public_methods: true
    include_tests: false
    include_support_types: true        # P1 占位
    include_module_dependencies: true  # P1 占位

# 选择性保存文档的完整构建快照
documents:
  stored_content:
    include:
      - "README.md"
      - "docs/architecture/**"
    exclude:
      - "docs/private/**"
      - "**/secrets.*"
    max_file_bytes: 2097152   # 原始文件和规范化正文各自最大 2 MiB
    max_total_bytes: 33554432 # 全部快照 32 MiB
    on_limit: error           # 超限时失败,不静默截断

# 监听配置
watcher:
  debounce_seconds: 5
  observer_type: auto

# 存储配置(代码图谱)
storage:
  backend: auto  # auto | json | sqlite

# 历史配置
history:
  max_commits: 10000

# Wiki 拉取配置(pull_wiki 工具 / pull-wiki 命令)
wiki:
  enabled: false              # 是否启用 wiki 拉取(pull_wiki 无论此值均可调用,仅作标记)
  cookie_file: ""             # 登录 cookie 文件,留空默认 ~/.botbrain/wiki_cookies.json
  output_dir: "docs/wiki"     # 下载目录(项目相对路径)
  include_refs: false         # 默认是否拉取引用页(显式 --ref/参数可覆盖)
  include_children: false     # 默认是否递归拉取子页面(显式 --child/参数可覆盖)

配置说明

配置项 说明 默认值
search.strategy 代码搜索策略 keyword
search.model_precision 嵌入模型精度 int8
documents.stored_content.include 保存完整构建快照的项目相对路径 glob []
documents.stored_content.exclude 即使被 include 命中也不保存的路径 glob []
documents.stored_content.max_file_bytes 原始文件字节数和规范化/转换正文 UTF-8 字节数各自的上限 2097152
documents.stored_content.max_total_bytes 当前图谱全部文档快照的最大字节数 33554432
documents.stored_content.on_limit 超过预算时的处理方式;error 不会静默截断 error
watcher.debounce_seconds 文件变更防抖时间 5
storage.backend 代码图谱存储后端 auto(=json)
wiki.cookie_file wiki 登录 cookie 文件路径(留空默认 ~/.botbrain/wiki_cookies.json) ""
wiki.output_dir wiki 文档下载目录(项目相对) docs/wiki
wiki.include_refs 默认是否拉取引用页(显式调用参数优先) false
wiki.include_children 默认是否递归拉取子页面(显式调用参数优先) false
history.max_commits 最大分析提交数 10000

服务运行期间,reconcile 检测到图谱配置或 Schema 变化时会阻断旧策略的增量写入, 重读 config.yaml 后执行干净全量重建。watcher.reconcile_interval_seconds: 0 表示显式关闭周期检测,此时仅修改配置不会主动唤醒服务,需要显式 reconcile 或重启服务。

on_limit: error 会在发布前中止整个构建或增量批次,保留上一份可用图谱; on_limit: omit 则按稳定路径顺序保留预算内快照,超限文档不保存完整正文或 Chunk,但仍可保留摘要、Section 和 Concept 等结构元数据。派生的 Section、Chunk、Concept 数量及重复标题长度也有硬上限,避免小文件放大为过大图谱。 未选中保存完整快照的文档仍会用于结构提取,但原始文件超过 16 MiB 时只做流式 哈希/行数统计并保留文档根元数据,不会把整个正文读入进程。 get_content 默认使用 source="auto",完整快照存在时优先读取图谱;响应被 截断时,把 next_cursor 原样传回即可继续。超长单行快照会自动使用字符游标, 不会在分页边界丢失内容;游标会绑定快照摘要,文档更新后旧游标会被拒绝。 max_bytes 是受服务器硬上限保护的软分页预算;为保证游标前进,1–3 字节预算下 一个 UTF-8 码点最多可超出 3 字节。非 Markdown 文档的 Section/Chunk 行号属于 转换后的 Markdown;若没有完整图谱快照,系统会返回 content_unavailable_reason,而不会错误地把这些行号应用到原始 HTML/RST/Office 文件。 keyword_search 始终只返回最多 100 项、每项最多 200 字符的正文预览;查询和 scope 各限制为 4096 字符。需要正文时应继续使用带游标的 get_content,不要依赖 搜索结果承载完整文档。

documents.stored_content.exclude 只禁止保存“完整快照”,不是保密边界; 文档仍可能产生摘要、Section 或 Concept 并进入索引。要让敏感文件完全不进入 图谱,请使用 project.exclude。这只影响后续构建,不会追溯擦除已发布的旧 generation 或 Git 历史;已发生敏感数据泄露时还需按运维流程清理缓存和历史。

架构

┌─────────────────────────────────────────────────────────────┐
│                    Agent 侧(Skill)                          │
│  意图解析 → 场景编排 → 多步调用 → 结果整合                      │
├─────────────────────────────────────────────────────────────┤
│                    MCP Server (单进程)                        │
│  20 个工具:19 代码 + 1 文档导入(pull_wiki)                   │
├─────────────────────────────────────────────────────────────┤
│   代码图谱引擎                                                │
│   Query Engine                                            │
│   Reasoning Engine                                        │
│   Build Engine                                            │
│   Watch Engine                                            │
├─────────────────────────────────────────────────────────────┤
│   graph/ (JsonStore)                                         │
│   nodes.json + edges.json                                   │
│   keyword_index.json                                        │
│   semantic_*.faiss                                          │
│   FAISS + KeywordIndex                                      │
│   arctic-embed-s (384维)                                    │
└─────────────────────────────────────────────────────────────┘

核心组件

  • Build Engine:使用 Tree-sitter 解析代码,提取函数、类、导入、调用关系;构建 CodeChunk 和 Diff 节点
  • Knowledge Graph:存储代码、文档、历史的图结构,支持 15 种代码节点类型和 7 种边类型
  • Query Engine:提供关键词搜索、符号定位、关系查询、上下文组装、代码片段获取
  • Reasoning Engine:基于图谱的推理分析(影响分析、测试推荐)
  • Watch Engine:监听文件变更,增量更新图谱,重建跨图谱链接,更新 Git 历史
  • MCP Server:实现 Model Context Protocol,20 个工具供 AI 工具调用

支持的场景

  • RAG(检索增强生成):通过 list_documents + get_context + get_content 组装上下文
  • text2code:通过文档目录和代码片段检索,辅助代码生成
  • code2code:通过 get_change_diff 提取代码变更对
  • 样本对查询:通过 get_change_diff 提取 before/after 代码对

开发

环境要求

  • Python 3.10+
  • uv(推荐)或 pip

安装依赖

# 克隆仓库
git clone https://gitcode.com/DeepRust/project-brain.git
cd project-brain

# 安装依赖
uv sync --extra dev

运行测试

# 运行所有测试
uv run pytest

# 运行特定测试
uv run pytest tests/test_code_parser.py -v

# 生成覆盖率报告
uv run pytest --cov=project_brain --cov-report=html

代码质量

# 类型检查
uv run mypy src/

# 代码格式化
uv run ruff format src/ tests/

# 代码检查
uv run ruff check src/ tests/

项目结构

project-brain/
├── src/project_brain/
│   ├── build/              # 构建引擎
│   │   ├── languages/      # 语言规则(Python/TS/Rust/C/C++/Go/Java)
│   │   ├── code_parser.py  # 代码解析器
│   │   ├── doc_parser.py   # 文档解析器(Markdown)
│   │   ├── history_parser.py # Git 历史解析
│   │   ├── link_engine.py  # 关联构建
│   │   ├── convention.py   # 约定提取
│   │   └── scanner.py      # 文件扫描
│   ├── graph/              # 知识图谱(代码域)
│   │   ├── models.py       # 15 种代码节点 + Edge
│   │   ├── store/          # GraphStore 抽象 + JsonStore + SqliteStore
│   │   └── ...
│   ├── query/              # 查询引擎(代码域)
│   │   ├── engine.py       # QueryEngine (18 查询方法)
│   │   ├── index.py        # KeywordIndex (BM25) + SymbolIndex + FileIndex
│   │   └── semantic_index.py # SemanticIndex (FAISS)
│   ├── reasoning/          # 推理引擎
│   ├── watcher/            # 文件监听
│   ├── wiki/               # 华为 Wiki 拉取(pull_wiki)
│   ├── mcp/                # MCP 服务 (20 工具)
│   ├── config.py           # 配置管理
│   └── __main__.py         # CLI 入口
├── skills/                 # 旧版 Skill 文件 (claude/opencode)
├── tests/                  # 测试用例 (772 passed, 35 skipped)
└── docs/                   # 文档

性能指标

指标 目标值 说明
查询响应时间 < 5秒 准实时响应
首次构建时间 < 3分钟 10万行代码
增量更新时间 < 10秒 文件变更后
项目切换时间 < 30秒 缓存快速加载
内存占用 < 2GB 10万行代码

支持的语言

P0 阶段(已支持)

  • Python:函数、类、装饰器、导入、调用关系
  • TypeScript/JavaScript:函数、类、接口、导入、调用关系
  • Rust:函数、结构体、枚举、trait、impl 块
  • C:函数、结构体、枚举、头文件包含
  • C++:函数、类、命名空间、模板、继承
  • Go:函数、方法(指针/值接收者)、结构体、接口(含嵌入展开)、隐式实现边(结构化满足)、导入、调用关系
  • Java:函数、类、接口、枚举、record、构造器、重载、继承/实现边(OVERRIDES)、javadoc

后续计划

  • Kotlin
  • Swift

技术栈

  • 开发语言:Python 3.10+
  • 代码解析:Tree-sitter(多语言统一解析)
  • 代码图谱存储:JsonStore(默认,全量内存)/ SqliteStore(可选)
  • 代码向量索引:FAISS(IndexFlatIP / IndexHNSWFlat,可选)
  • 嵌入模型:snowflake/arctic-embed-s(384 维)
  • 文件监听:watchdog
  • MCP 实现:mcp Python SDK (FastMCP)
  • Wiki 拉取:requests + urllib3(必需);playwright(可选 [wiki] extra,仅刷新登录态)
  • 包管理:uv

路线图

P0(已完成)

  • 多语言代码解析(Python/TS/Rust/C/C++/Go/Java)
  • 知识图谱构建(15 种节点 + 7 种边)
  • 19 个代码 MCP 工具
  • 影响分析、测试推荐
  • 文件监听与增量更新
  • 语义搜索(FAISS + fastembed,hybrid RRF 融合)
  • Skill 文件(OpenCode/Claude Code)
  • RAG 上下文组装 + 样本对提取
  • 华为内源 Wiki 拉取(pull_wiki 工具 + pull-wiki 命令)
  • Mini Graph Profile(公开 API 图谱 + 能力声明 + Rust pub mod/use 可达性)

P1(计划中)

  • Rust pub use glob/alias 完整解析(详见 docs/mini-profile-known-issues.md)
  • API 支撑类型闭包(参数/返回/基类类型补齐)
  • 用户自定义 Profile(--profile custom --node-type ...)

P2(计划中)

  • 更多语言支持(Java/Go)— 0.8.0 完成
  • 更多语言支持(Kotlin)
  • 多仓库分析
  • Web UI 可视化

P3(未来)

  • 多租户支持
  • 云端部署
  • 与其他知识源集成(Jira、Confluence)
  • 自定义规则引擎

常见问题

Q: Project Brain 会上传我的代码吗?

A: 不会。Project Brain 完全在本地运行,代码数据不会离开你的机器。

Q: 需要 API Key 吗?

A: 不需要——纯静态分析,零 LLM 依赖。

Q: 支持多大的项目?

A: 代码图谱默认用 JsonStore(全量内存),适合中小型项目(< 10 万行)。大型项目可在配置中切换 SqliteStore。

Q: 如何排除某些文件?

A: 在 .botbrain/config.yaml 中配置 project.exclude 字段。

Q: 图谱数据存储在哪里?

A: 代码图谱在 .botbrain/graph/ 目录(nodes.json + edges.json + 索引)。整个 .botbrain/ 目录可加入 .gitignore。

Q: 支持 Windows 吗?

A: 支持。已在 Windows 上测试通过。

贡献

欢迎贡献!请遵循以下步骤:

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 创建 Pull Request

许可证

MIT License

联系方式

致谢


Project Brain - 让 AI Agent 真正理解你的项目

Metadata

Release files for bot-brain 0.8.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bot-brain 0.8.0
File Size Uploaded Provenance Actions
bot_brain-0.8.0.tar.gz 26.4 MB Without provenance Details for bot_brain-0.8.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for bot-brain 0.8.0
File Interpreter ABI Platform Actions
bot_brain-0.8.0-py3-none-any.whl Python 3 none any Details for bot_brain-0.8.0-py3-none-any.whl

Total release size: 52.6 MB

Release files / bot_brain-0.8.0.tar.gz

Download URL bot_brain-0.8.0.tar.gz
Size 26.4 MB
Tags Source
SHA-256 checksum
How to use checksums
83cd0270dec89d1118fec58cdbaceaeda1dd66001d44611341a20179b844f0aa
BLAKE2b-256 checksum
How to use checksums
b8206cc0c381ba1f97eb5cd80decb4dd8657b05fea91efcfc4f0164a4a44eecf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.9

Release files / bot_brain-0.8.0-py3-none-any.whl

Download URL bot_brain-0.8.0-py3-none-any.whl
Size 26.1 MB
Tags Python 3
SHA-256 checksum
How to use checksums
69e6e3c5371cd20ab32492c3fe436795ec35831057ea34b6e2c3a4bea71da8a8
BLAKE2b-256 checksum
How to use checksums
18f471599948bff95b71346c14400becb8b63a89b6f118c1b5489025c00df14f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.9

Security for bot-brain 0.8.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.8.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page