Project Brain 低层设计文档(LLD)

1. 技术目标

1.1 核心职责

  • 理解项目
  • 组织知识
  • 提供查询
  • 提供推理

1.2 不负责

  • 编码
  • 测试执行
  • Agent Workflow

1.3 开发语言

Python(主版本)

1.4 支持语言(P0)

C、C++、Python、Rust、TypeScript

1.5 目标规模

  • 中型项目:10-100万行代码
  • 查询响应 < 5秒
  • 首次构建 < 3分钟(10万行)
  • 增量更新 < 10秒
  • 内存占用 < 2GB(10万行)

2. 项目结构

project-brain/
├── pyproject.toml
├── README.md
├── src/
│   └── project_brain/
│       ├── __init__.py
│       ├── __main__.py              # CLI 入口
│       ├── config.py                # 配置管理
│       ├── errors.py                # 错误定义
│       │
│       ├── mcp/                     # MCP Server
│       │   ├── __init__.py
│       │   └── server.py            # MCP Server 实现(含全部 20 个 Tool 注册)
│       │
│       ├── wiki/                    # 华为内源 Wiki 拉取(pull_wiki 工具)
│       │   ├── processor.py         # 爬取编排(PullResult)
│       │   ├── api.py               # wiki API 请求
│       │   ├── markdown.py          # HTML→Markdown
│       │   ├── files.py             # 文件落盘
│       │   └── config.py            # cookie/登录态
│       │
│       ├── query/                   # Query Engine
│       │   ├── __init__.py
│       │   ├── engine.py            # 查询引擎(Keyword/Graph/Freshness)
│       │   └── index.py             # 索引(KeywordIndex, SymbolIndex, FileIndex)
│       │
│       ├── reasoning/               # Reasoning Engine
│       │   ├── __init__.py
│       │   └── engine.py            # 影响分析 + 测试推荐
│       │
│       ├── graph/                   # Knowledge Graph
│       │   ├── __init__.py
│       │   ├── models.py            # 节点/边数据模型
│       │   ├── json_store.py        # JSON 存储实现
│       │   ├── sqlite_store.py      # SQLite 存储实现
│       │   └── store/               # 存储基类
│       │       ├── __init__.py
│       │       └── base.py          # GraphStore Protocol
│       │
│       ├── build/                   # Build Engine
│       │   ├── __init__.py
│       │   ├── scanner.py           # 文件扫描
│       │   ├── code_parser.py       # 代码解析(Tree-sitter)
│       │   ├── doc_parser.py        # 文档解析
│       │   ├── history_parser.py    # Git 历史解析
│       │   ├── test_parser.py       # 测试识别与关联
│       │   ├── link_engine.py       # 关联构建
│       │   ├── convention.py        # 约定提取 [P1]
│       │   └── languages/           # 语言特定规则
│       │       ├── __init__.py
│       │       ├── base.py
│       │       ├── c.py
│       │       ├── cpp.py
│       │       ├── python.py
│       │       ├── rust.py
│       │       ├── typescript.py
│       │       ├── go.py
│       │       └── java.py
│       │
│       └── watcher/                 # File Watcher
│           ├── __init__.py
│           ├── watcher.py           # 文件监听
│           └── updater.py           # 增量更新
│
├── skills/                          # Skill 文件(Agent 侧)
│   ├── opencode/
│   │   └── bot-brain.md
│   └── claude/
│       └── bot-brain.md
│
└── tests/
    ├── conftest.py
    ├── test_code_parser.py
    ├── test_doc_parser.py
    ├── test_query_engine.py
    ├── test_mcp_server.py
    ├── test_models.py
    ├── test_json_store.py
    ├── test_sqlite_store.py
    ├── test_index.py
    ├── test_scanner.py
    ├── test_link_engine.py
    ├── test_convention.py
    ├── test_history_parser.py
    ├── test_reasoning.py
    ├── test_watcher.py
    ├── test_watcher_manager.py
    ├── test_integration.py
    ├── test_language_base.py
    ├── test_python_rule.py
    ├── test_typescript_rule.py
    ├── test_rust_rule.py
    ├── test_c_rule.py
    ├── test_cpp_rule.py
    ├── test_config.py
    ├── test_errors.py
    └── test_store_protocol.py

3. 数据模型

3.1 节点定义

Repository

@dataclass
class RepositoryNode:
    id: str                    # "repo_{name_hash}"
    type: str = "repository"
    name: str                  # 仓库名称
    path: str                  # 本地路径
    languages: list[str]       # 检测到的语言列表
    branch: str                # 当前分支
    line_count: int            # 总代码行数
    file_count: int            # 总文件数
    created_at: float          # 首次构建时间
    updated_at: float          # 最后更新时间

Module

@dataclass
class ModuleNode:
    id: str                    # "mod_{path_hash}"
    type: str = "module"
    name: str                  # 模块名
    path: str                  # 相对路径
    parent: str | None         # 父模块 ID
    line_count: int            # 代码行数
    file_count: int            # 文件数
    language: str              # 主要语言

Class

@dataclass
class ClassNode:
    id: str                    # "cls_{file}_{name_hash}"
    type: str = "class"
    name: str                  # 类名
    kind: str                  # class / struct / enum / interface / trait
    file_id: str               # 所在文件
    module_id: str             # 所属模块
    line_start: int            # 起始行
    line_end: int              # 结束行
    visibility: str            # public / private / protected
    bases: list[str]           # 父类/接口 ID 列表
    docstring: str | None      # 文档注释

Function

@dataclass
class FunctionNode:
    id: str                    # "fn_{file}_{name_hash}"
    type: str = "function"
    name: str                  # 函数名
    signature: str             # 完整签名
    file_id: str               # 所在文件
    module_id: str             # 所属模块
    class_id: str | None       # 所属类(方法才有)
    line_start: int            # 起始行
    line_end: int              # 结束行
    visibility: str            # public / private / protected
    is_async: bool             # 是否异步
    is_static: bool            # 是否静态
    is_test: bool              # 是否为测试函数
    params: list[dict]         # 参数列表 [{name, type}]
    return_type: str | None    # 返回类型
    docstring: str | None      # 文档注释
    summary: str | None        # 自动生成的摘要

File

@dataclass
class FileNode:
    id: str                    # "file_{path_hash}"
    type: str = "file"
    path: str                  # 相对路径
    language: str              # 语言
    line_count: int            # 行数
    is_test: bool              # 是否为测试文件
    is_generated: bool         # 是否为生成代码
    md5: str                   # 文件内容哈希(用于增量检测)
    parse_status: str          # "ok" / "error" / "partial" / "skipped"

Document

@dataclass
class DocumentNode:
    id: str                    # "doc_{path_hash}"
    type: str = "document"
    title: str                 # 文档标题
    path: str                  # 相对路径
    format: str                # markdown / yaml / json
    line_count: int            # 行数
    md5: str                   # 文件内容哈希
    summary: str | None        # 文档摘要(从 front matter 或首段提取)
    section_titles: list[str]  # 标题树(供 LLM 浏览目录)

Section

@dataclass
class SectionNode:
    id: str                    # "sec_{doc_id}_{level}_{index}"
    type: str = "section"
    title: str                 # 标题
    level: int                 # 层级(1-6)
    doc_id: str                # 所属文档
    line_start: int            # 起始行
    line_end: int              # 结束行
    content: str               # 段落文本
    summary: str | None        # 自动生成的摘要

Concept

@dataclass
class ConceptNode:
    id: str                    # "concept_{name_hash}"
    type: str = "concept"
    name: str                  # 概念名称
    description: str | None    # 描述
    source: str                # 来源(doc_id 或 section_id)

Test

@dataclass
class TestNode:
    id: str                    # "test_{file}_{name_hash}"
    type: str = "test"
    name: str                  # 测试名
    file_id: str               # 所在文件
    framework: str             # pytest / unittest / googletest / ...
    targets: list[str]         # 被测目标 ID 列表
    line_start: int
    line_end: int

Commit

@dataclass
class CommitNode:
    id: str                    # "commit_{sha}"
    type: str = "commit"
    sha: str                   # Git SHA
    author: str                # 作者
    email: str                 # 邮箱
    timestamp: float           # 提交时间
    message: str               # 提交信息
    files_changed: int         # 修改文件数

PR

@dataclass
class PRNode:
    id: str                    # "pr_{number}"
    type: str = "pr"
    number: int                # PR 编号
    title: str                 # 标题
    author: str                # 作者
    timestamp: float           # 创建时间
    state: str                 # open / merged / closed
    commit_ids: list[str]      # 包含的 Commit ID

Convention

@dataclass
class ConventionNode:
    id: str                    # "conv_{category}_{name_hash}"
    type: str = "convention"
    category: str              # architecture / naming / error_handling / logging / testing
    name: str                  # 约定名称
    description: str           # 约定描述
    source: str                # 来源(code_analysis / doc / config)
    scope: str | None          # 作用范围(全局 / 模块 ID)

CodeChunk

@dataclass
class CodeChunkNode:
    id: str                    # "chunk_{source_id}_{kind}"
    type: str = "code_chunk"
    content: str               # 代码/文档文本
    kind: str                  # function_body / class_body / section / file_header
    source_id: str             # 关联的 Function/Class/Section ID
    line_start: int            # 起始行
    line_end: int              # 结束行
    token_count: int           # 预估 token 数
    keywords: str              # 预提取的关键词(用于倒排索引)

Diff

@dataclass
class DiffNode:
    id: str                    # "diff_{sha}_{file_hash}"
    type: str = "diff"
    commit_id: str             # 关联的 Commit ID
    file_path: str             # 文件路径
    change_type: str           # added / modified / deleted
    before: str | None         # 变更前代码
    after: str | None          # 变更后代码
    changed_functions: list[str]  # 受影响的函数 ID

3.2 边定义

@dataclass
class Edge:
    id: str                    # "{source_id}->{target_id}:{type}"
    type: str                  # 边类型
    source: str                # 源节点 ID
    target: str                # 目标节点 ID
    properties: dict           # 附加属性

3.3 图谱元信息

@dataclass
class GraphMetadata:
    schema_version: str        # 图谱格式版本 "1.0"
    build_version: str         # 软件版本 "0.1.0"
    build_time: float          # 最后构建时间
    language_stats: dict       # 语言行数统计 {"python": 80000, "typescript": 20000}
    parse_errors: int          # 解析失败文件数
    total_nodes: int           # 节点总数
    total_edges: int           # 边总数

存储于 .botbrain/graph/metadata.json,用于版本检查和迁移判断。

3.4 图谱接口

边类型 source → target properties 说明
CONTAIN Repository/Module → Module/Class/Function - 层级包含
CALL Function → Function call_site: str, line: int, confidence: "static" | "inferred" | "uncertain" 函数调用
DEPEND Module → Module import_path: str 模块依赖
IMPLEMENT Class → Class kind: "inherit" / "implement" 继承/实现
IMPORT File → File symbols: list[str] 文件导入
DESCRIBE Document/Section → Module/Class/Function method: "explicit" / "semantic" 文档描述代码
TEST Test → Function/Class method: str 测试关联
MODIFY Commit → File additions: int, deletions: int 提交修改文件
AUTHOR Commit → (author: str) - 提交作者
BELONG PR → Commit - PR 包含 Commit
GOVERN Convention → Module/Class/Function - 约定约束
CONTAINS_CHUNK Function/Class/Section → CodeChunk - 符号包含代码块
SUPERSEDE Diff → Function/Class - 变更替换了旧实现

3.3 图谱接口

class GraphStore(Protocol):
    # 读操作(在快照上执行)
    def get_node(self, node_id: str) -> dict | None: ...
    def get_nodes_by_type(self, node_type: str) -> list[dict]: ...
    def get_edges(self, node_id: str, edge_type: str | None = None,
                  direction: str = "out") -> list[Edge]: ...
    def get_neighbors(self, node_id: str, edge_types: list[str] | None = None,
                      direction: str = "both", depth: int = 1) -> list[dict]: ...

    # 写操作(读写分离)
    def snapshot(self) -> ReadSnapshot: ...           # 获取只读快照
    def begin_write(self) -> WriteTransaction: ...    # 开始写事务
    def commit_write(self, tx: WriteTransaction) -> None: ...   # 提交写事务
    def rollback_write(self, tx: WriteTransaction) -> None: ... # 回滚写事务

    # 项目切换
    def unload(self) -> None: ...                     # 卸载当前图谱
    def load_project(self, path: str) -> None: ...    # 加载指定项目图谱

    # 持久化
    def save(self, path: str) -> None: ...
    def load(self, path: str) -> None: ...

读写分离说明:

  • 查询请求在 snapshot() 返回的只读快照上执行,不阻塞
  • 增量构建通过 begin_write() / commit_write() 在写副本上操作
  • 构建完成后原子切换,查询自动获取新数据
  • SQLite 实现利用 WAL 模式;JSON 实现使用双文件切换

4. Code Parser

4.1 整体流程

项目目录
    │
    ▼
文件扫描:
    ├── 按扩展名识别语言
    ├── 排除 .gitignore / 生成代码 / 配置排除
    ├── 按语言分组
    └── 统计语言分布 → RepositoryNode.languages
    │
    ▼
逐文件 Tree-sitter 解析(按语言使用对应 grammar)
    │
    ▼
语言特定规则提取(languages/*.py)
    │
    ▼
生成节点和边
    │
    ▼
写入 GraphStore

多语言项目处理:

  • 自动检测:按文件扩展名统计语言分布
  • 手动覆盖:通过 config.yaml 的 project.languages 指定
  • 独立解析:每种语言使用对应的 Tree-sitter grammar
  • 统一图谱:所有语言结果写入同一个 Knowledge Graph
  • P0 限制:不解析跨语言调用关系

4.2 Tree-sitter 集成

import tree_sitter as ts

class TreeSitterParser:
    def __init__(self):
        self.languages = {
            "c": ts.Language("tree-sitter-c"),
            "cpp": ts.Language("tree-sitter-cpp"),
            "python": ts.Language("tree-sitter-python"),
            "rust": ts.Language("tree-sitter-rust"),
            "typescript": ts.Language("tree-sitter-typescript"),
            "go": ts.Language("tree-sitter-go"),
            "java": ts.Language("tree-sitter-java"),
        }

    def parse_file(self, file_path: str, language: str) -> ParseResult:
        parser = ts.Parser(self.languages[language])
        source = read_file(file_path)
        tree = parser.parse(source)
        return self._extract(tree.root_node, source, language)

4.3 语言特定规则

每种语言实现一个 LanguageRule 接口:

class LanguageRule(Protocol):
    def detect_module(self, node: ts.Node, source: bytes) -> ModuleInfo | None: ...
    def detect_class(self, node: ts.Node, source: bytes) -> ClassInfo | None: ...
    def detect_function(self, node: ts.Node, source: bytes) -> FunctionInfo | None: ...
    def detect_import(self, node: ts.Node, source: bytes) -> ImportInfo | None: ...
    def detect_call(self, node: ts.Node, source: bytes) -> CallInfo | None: ...
    def detect_test(self, node: ts.Node, source: bytes) -> TestInfo | None: ...
    def file_patterns(self) -> FilePatterns: ...

各语言关键差异

语言 模块标识 类/结构体 函数 导入 测试识别
C 头文件/源文件对 struct / enum 函数声明 #include 无标准
C++ namespace class / struct 成员函数/自由函数 #include / using GoogleTest / Catch2
Python 文件/包 class def / async def import / from pytest / unittest
Rust mod / crate struct / enum / trait fn / impl use #[test] / #[cfg(test)]
TypeScript 文件/module class / interface / type function / method import describe/it / test

4.4 文件过滤

DEFAULT_EXCLUDE = [
    ".git/", "node_modules/", "target/", "build/", "dist/",
    "__pycache__/", ".venv/", "vendor/",
    "*.generated.*", "*.pb.*", "*_pb2.*",  # 生成代码
]

可通过 .botbrain/config.yaml 自定义排除规则。

4.5 Call Graph 构建

Tree-sitter 提供 CST,调用关系提取逻辑:

遍历 CST
    │
    ▼
识别函数调用表达式:
    ├── C/C++: call_expression
    ├── Python: call
    ├── Rust: call_expression
    └── TypeScript: call_expression / new_expression
    │
    ▼
解析调用目标:
    ├── 直接调用: foo() → FunctionNode(foo), confidence: "static"
    ├── 方法调用: obj.method() → 按名称匹配, confidence: "inferred"
    ├── 链式调用: a.b().c() → 拆解为多个调用
    └── 动态调用: getattr(obj, name)() → confidence: "uncertain"
    │
    ▼
生成 CALL 边(携带 confidence 属性)

P0 阶段方法调用按名称匹配,不做完整类型推断。调用置信度标记:

置信度 含义 示例
static 静态分析可确认 直接函数调用
inferred 基于名称推断 方法调用 obj.method()
uncertain 不确定 动态分发、函数指针

5. Document Parser

5.1 整体流程

项目内文档文件(Markdown/YAML/JSON)
    │
    ▼
摘要提取(summary):
    ├── YAML front matter 的 description/summary 字段
    ├── 文档开头到第一个 # 标题之间的正文段落
    ├── 前 3 行非标题、非空文本拼接截断到 200 字符
    └── 都没有 → null
    │
    ▼
标题树提取(section_titles):
    └── 正则提取所有 # 行 → [标题1, 标题2, ...]
    │
    ▼
标题层级解析 → Section 节点
    │
    ▼
内容分析:
    ├── 代码引用识别(反引号/代码块中的符号名)
    ├── 概念/术语提取
    └── 链接/交叉引用
    │
    ▼
生成节点和边

5.2 摘要与标题树提取

class DocumentParser:
    def parse_file(self, file_path: str) -> ParseResult:
        content = read_file(file_path)
        
        # 提取摘要
        summary = self._extract_summary(content)
        
        # 提取标题树
        section_titles = self._extract_section_titles(content)
        
        # 解析章节
        sections = self._parse_sections(content)
        
        # 概念提取
        concepts = self._extract_concepts(content)
        
        # 代码引用
        references = self._extract_references(content)
        
        return ParseResult(
            summary=summary,
            section_titles=section_titles,
            sections=sections,
            concepts=concepts,
            references=references,
        )
    
    def _extract_summary(self, content: str) -> str | None:
        """提取文档摘要,优先级:front matter > 首段 > 前3行"""
        # 1. YAML front matter
        if content.startswith("---"):
            end = content.find("---", 3)
            if end > 0:
                fm = yaml.safe_load(content[3:end])
                if fm and fm.get("description"):
                    return fm["description"][:200]
        
        # 2. 开头到第一个 # 之间的正文
        lines = content.splitlines()
        body_lines = []
        for line in lines:
            if line.startswith("#"):
                break
            stripped = line.strip()
            if stripped and not stripped.startswith("---"):
                body_lines.append(stripped)
        if body_lines:
            return " ".join(body_lines)[:200]
        
        # 3. 前 3 行非空非标题文本
        text_lines = [l.strip() for l in lines 
                      if l.strip() and not l.startswith("#")][:3]
        if text_lines:
            return " ".join(text_lines)[:200]
        
        return None
    
    def _extract_section_titles(self, content: str) -> list[str]:
        """提取所有标题,供 LLM 浏览目录"""
        return [line.strip("# ").strip() 
                for line in content.splitlines() 
                if line.startswith("#")]

5.3 代码引用识别

识别文档中对代码符号的引用:

扫描文档文本
    │
    ▼
匹配模式:
    ├── 行内代码: `SymbolName`
    ├── 代码块: ```language ... ```
    ├── 显式引用: @see SymbolName, @link SymbolName
    └── 路径引用: src/module/file.py:42
    │
    ▼
与 Code Graph 中的符号匹配
    │
    ▼
生成 DESCRIBE 边(method: "explicit")

5.5 Test Parser

5.5.1 整体流程

项目源代码 + 测试代码
    │
    ▼
测试文件识别(目录约定 + 文件命名)
    │
    ▼
测试函数识别(框架标记 + 命名约定)
    │
    ▼
关联建立(显式引用 + 命名匹配 + 目录映射)
    │
    ▼
生成 Test 节点 + TEST 边

5.5.2 测试解析器

class TestParser:
    def __init__(self, tree_sitter: TreeSitterParser, language_rules: dict):
        self.tree_sitter = tree_sitter
        self.language_rules = language_rules
    
    def parse_file(self, file_path: str, language: str) -> ParseResult:
        """识别文件中的测试,建立关联。"""
        rule = self.language_rules[language]
        
        # 1. 判断是否为测试文件
        if not self._is_test_file(file_path, rule):
            return ParseResult.empty()
        
        # 2. 提取测试函数
        tree = self.tree_sitter.parse(file_path, language)
        tests = rule.detect_tests(tree.root_node, file_path)
        
        # 3. 建立关联
        for test in tests:
            test.targets = self._resolve_targets(test, rule)
        
        return ParseResult(tests)
    
    def _is_test_file(self, path: str, rule) -> bool:
        """通过目录和文件名判断是否为测试文件。"""
        test_dirs = ["tests/", "test/", "__tests__/", "spec/"]
        test_patterns = ["*_test.*", "test_*.*", "*_spec.*", "*.test.*"]
        return any(path.startswith(d) for d in test_dirs) or \
               any(fnmatch.fnmatch(path, p) for p in test_patterns)
    
    def _resolve_targets(self, test: TestInfo, rule) -> list[str]:
        """解析测试关联的生产代码符号。"""
        targets = []
        # 显式引用(测试中调用的符号)
        targets.extend(self._find_explicit_refs(test))
        # 命名匹配
        targets.extend(self._match_by_name(test.name, rule))
        return targets

5.5.3 各语言测试识别差异

语言 测试框架 测试标记 测试目录 命名约定
Python pytest/unittest @pytest.mark, TestCase tests/ test_*.py
Rust lib test #[test] 同文件 #[cfg(test)] test_*
TypeScript Jest/Vitest describe/it/test __tests__/, *.test.ts *.test.ts
C++ GoogleTest TEST_F, TEST test/ *_test.cpp
C 无标准 无标准 test/ test_*.c

6. History Parser

6.1 整体流程

Git Repository
    │
    ▼
git log 解析(subprocess 调用 git)
    │
    ▼
提取:
    ├── Commit 信息 → CommitNode
    ├── 修改文件列表 → MODIFY 边
    ├── 作者信息 → AUTHOR 边
    └── PR 信息(从 commit message 中提取 PR 编号)→ PRNode + BELONG 边
    │
    ▼
聚合分析:
    ├── 模块热点统计
    ├── 高频修改路径
    └── Owner 推断(按修改行数/次数)

6.2 Git 交互

import subprocess

class GitClient:
    def log(self, path: str, max_count: int = None,
            since: str = None) -> list[CommitInfo]:
        cmd = ["git", "log", "--format=%H|%an|%ae|%at|%s", "--numstat"]
        if max_count:
            cmd.extend(["-n", str(max_count)])
        if since:
            cmd.extend(["--since", since])
        result = subprocess.run(cmd, capture_output=True, text=True, cwd=path)
        return self._parse_log(result.stdout)

    def diff(self, path: str, from_sha: str, to_sha: str = "HEAD") -> list[FileDiff]:
        ...

6.3 Owner 推断

对每个文件/模块:
    │
    ▼
统计每个作者的:
    ├── 提交次数
    ├── 修改行数(additions + deletions)
    └── 最近修改时间
    │
    ▼
综合评分 → 排序 → Top 贡献者为 Owner

遍历 Document 内容
    │
    ▼
提取代码符号引用(`ClassName`、`function_name` 等)
    │
    ▼
与 Code Graph 符号匹配:
    ├── 精确匹配: 符号名完全一致
    └── 路径匹配: module.ClassName, module.function_name
    │
    ▼
生成 DESCRIBE 边(method: "explicit")
从 History Parser 获取:
    ├── Commit → 修改文件列表 → MODIFY 边
    ├── Commit message 中的 PR 编号 → BELONG 边
    └── Commit 作者 → AUTHOR 边

注:Semantic Link(基于 Embedding 匹配)暂不支持,需要用户自配 Embedding API。


8. Convention Extractor [P1]

P0 阶段说明:自动提取能力为 P1。P0 仅支持读取 .botbrain/conventions.yaml 手动声明的约定。以下设计为 P1 完整方案。

8.1 代码结构分析

class StructureAnalyzer:
    def analyze(self, graph: GraphStore) -> list[ConventionNode]:
        conventions = []
        conventions.extend(self._detect_architecture(graph))
        conventions.extend(self._detect_layering(graph))
        return conventions

    def _detect_architecture(self, graph: GraphStore) -> list[ConventionNode]:
        # 分析目录结构模式
        # 识别 DDD / MVC / Clean Architecture / 扁平结构 等
        ...

    def _detect_layering(self, graph: GraphStore) -> list[ConventionNode]:
        # 分析模块间依赖方向
        # 推断分层规则(如 controller → service → repository)
        ...

8.2 命名模式分析

class NamingAnalyzer:
    def analyze(self, graph: GraphStore) -> list[ConventionNode]:
        conventions = []
        conventions.append(self._detect_file_naming(graph))
        conventions.append(self._detect_class_naming(graph))
        conventions.append(self._detect_function_naming(graph))
        conventions.append(self._detect_constant_naming(graph))
        return conventions

统计项目中各类标识符的命名风格分布,取占比最高的作为约定。

8.3 文档提取

从 README、CONTRIBUTING 等文档中提取显式声明的约定。

注:基于 LLM 的语义提取暂不支持,仅支持显式声明和代码模式分析。

8.4 手动配置 [P0]

P0 唯一交付项:读取手动声明的约定配置。

.botbrain/conventions.yaml:

conventions:
  architecture: DDD
  layers:
    - name: controller
      pattern: "src/**/controller/**"
    - name: service
      pattern: "src/**/service/**"
    - name: repository
      pattern: "src/**/repository/**"
  naming:
    file: snake_case
    class: PascalCase
    function: snake_case
    constant: UPPER_SNAKE_CASE
  error_handling: Result pattern
  logging: tracing

手动配置优先级最高,覆盖自动推断结果。


9. Query Engine

9.1 检索策略

class SearchStrategy:
    KEYWORD = "keyword"
    KEYWORD_GRAPH = "keyword+graph"

@dataclass
class FreshnessInfo:
    status: str          # "fresh" | "stale" | "building"
    last_updated: float  # 最后更新时间戳
    warning: str | None  # 警告信息

@dataclass
class QueryResult:
    data: dict
    freshness: FreshnessInfo

class QueryEngine:
    def __init__(self, config: Config, graph: GraphStore, indexes: IndexManager):
        self.strategy = config.search.strategy
        self.keyword = KeywordSearch(indexes.keyword_index)
        self.graph = GraphSearch(graph) if strategy == KEYWORD_GRAPH else None
        self.build_status = "idle"  # "idle" | "building" | "rebuilding"
        self.last_updated = 0.0

    def query(self, params: QueryParams) -> QueryResult:
        """执行查询,根据请求类型分发到对应搜索引擎。"""
        data = self._execute_query(params)
        freshness = self._get_freshness()
        return QueryResult(data=data, freshness=freshness)
    
    def _get_freshness(self) -> FreshnessInfo:
        status = "fresh" if self.build_status == "idle" else "building"
        warning = "图谱正在更新,结果基于旧版本数据" if status != "fresh" else None
        return FreshnessInfo(
            status=status,
            last_updated=self.last_updated,
            warning=warning
        )
    
    def _execute_query(self, params: QueryParams) -> dict:
        if params.type == "keyword":
            return self.keyword.search(params.query, params.scope, params.top_k)
        elif params.type == "symbol":
            return self._locate_symbol(params.symbol_name, params.kind)
        elif params.type == "call_graph":
            return self._get_call_graph(params.function_id, params.direction, params.depth)
        elif params.type == "dependencies":
            return self._get_dependencies(params.module_id, params.direction)
        # ... 其他查询类型
class KeywordSearch:
    """基于 BM25 的倒排索引检索,保底能力。"""

    def search(self, query: str, scope: str | None = None,
               top_k: int = 20) -> list[SearchHit]:
        tokens = self._tokenize(query)
        scores = {}
        for token in tokens:
            postings = self.index.lookup(token)
            for doc_id, tf in postings:
                scores[doc_id] = scores.get(doc_id, 0) + self._bm25(tf, token)
        return sorted(scores.items(), key=lambda x: -x[1])[:top_k]

支持正则表达式匹配(类似 grep):

    def grep(self, pattern: str, scope: str | None = None) -> list[SearchHit]:
        """类 grep 的正则搜索。"""
        regex = re.compile(pattern)
        results = []
        for doc in self.index.all_documents():
            matches = regex.findall(doc.content)
            if matches:
                results.append(SearchHit(doc.id, matches, score=len(matches)))
        return results
class GraphSearch:
    """基于图谱遍历的关系查询。"""

    def traverse(self, start_id: str, edge_types: list[str],
                 direction: str = "out", depth: int = 3) -> list[GraphPath]:
        paths = []
        queue = [(start_id, [])]
        visited = set()

        while queue:
            node_id, path = queue.pop(0)
            if node_id in visited or len(path) > depth:
                continue
            visited.add(node_id)

            edges = self.graph.get_edges(node_id, direction=direction)
            for edge in edges:
                if edge.type in edge_types:
                    new_path = path + [edge]
                    paths.append(GraphPath(new_path))
                    next_id = edge.target if direction == "out" else edge.source
                    queue.append((next_id, new_path))

        return paths

9.4 降级策略

  • 图谱未构建时,自动降级到 keyword
  • keyword 始终可用

10. Reasoning Engine

10.1 Impact Analysis

class ImpactAnalyzer:
    def analyze(self, target: str) -> ImpactResult:
        node = self.graph.find_node(target)

        # 依赖展开
        dependents = self.graph.traverse(node.id, ["DEPEND", "IMPORT"],
                                          direction="in", depth=5)

        # 调用展开
        callers = self.graph.traverse(node.id, ["CALL"],
                                       direction="in", depth=5)

        # 测试展开
        tests = self.graph.traverse(node.id, ["TEST"], direction="in", depth=2)

        # 风险评分
        risk = self._calculate_risk(node, dependents, callers, tests)

        return ImpactResult(
            affected_modules=self._collect_modules(dependents),
            affected_tests=self._collect_tests(tests),
            risk_level=risk.level,
            risk_reasons=risk.reasons,
        )

10.2 Test Recommendation

class TestRecommender:
    def recommend(self, modified_files: list[str]) -> TestRecommendation:
        # 文件 → 函数
        functions = self._get_functions_in_files(modified_files)

        # 函数 → 直接关联测试
        direct_tests = set()
        for fn in functions:
            direct_tests.update(self.graph.get_edges(fn.id, "TEST", direction="in"))

        # 函数 → 调用链上游 → 关联测试
        indirect_tests = set()
        for fn in functions:
            callers = self.graph.traverse(fn.id, ["CALL"], direction="in", depth=3)
            for caller in callers:
                indirect_tests.update(
                    self.graph.get_edges(caller.id, "TEST", direction="in"))

        return TestRecommendation(
            direct_tests=direct_tests,
            indirect_tests=indirect_tests - direct_tests,
            reason=self._generate_reason(functions),
        )

10.3 Change Risk Analysis

class RiskAnalyzer:
    def analyze(self, change_plan: list[str]) -> RiskResult:
        risks = []
        for target in change_plan:
            node = self.graph.find_node(target)
            impact = self.impact_analyzer.analyze(target)
            hotness = self._get_hotness(node)         # 历史变更频率
            coverage = self._get_test_coverage(node)   # 测试覆盖度(设计概念,当前未实现;可用 get_related_tests 近似)

            risk_score = (
                0.4 * impact.normalized_scope +
                0.3 * hotness.normalized +
                0.3 * (1 - coverage.normalized)        # 覆盖越低风险越高
            )
            risks.append(RiskItem(target, risk_score, impact, hotness, coverage))

        return RiskResult(
            risks=sorted(risks, key=lambda r: -r.score),
            overall_score=sum(r.score for r in risks) / len(risks),
        )

11. Storage 实现

11.1 存储自动选择

class StoreFactory:
    THRESHOLD = 100000  # 10万行

    @staticmethod
    def create(project_path: str) -> GraphStore:
        config = Config.load(project_path)
        store_path = Path(project_path) / ".botbrain" / "graph"
        
        # 用户手动锁定存储方案
        if config.storage.backend != "auto":
            return StoreFactory._create_by_type(config.storage.backend, store_path)
        
        line_count = count_lines(project_path)
        target_type = "json" if line_count < StoreFactory.THRESHOLD else "sqlite"
        
        # 检测现有格式,必要时迁移
        current_type = StoreFactory._detect_current(store_path)
        if current_type and current_type != target_type:
            StoreFactory._migrate(store_path, current_type, target_type)
        
        return StoreFactory._create_by_type(target_type, store_path)
    
    @staticmethod
    def _migrate(store_path: Path, from_type: str, to_type: str):
        """格式迁移:JSON ↔ SQLite"""
        # 1. 加载旧格式数据
        old_store = StoreFactory._create_by_type(from_type, store_path)
        old_store.load(store_path)
        
        # 2. 备份旧文件
        StoreFactory._backup(store_path, from_type)
        
        # 3. 写入新格式
        new_store = StoreFactory._create_by_type(to_type, store_path)
        new_store.import_from(old_store)
        new_store.save(store_path)

11.2 JSON Store

class JsonStore:
    """轻量级 JSON 文件存储,适合小型项目。"""

    def __init__(self, path: Path):
        self.nodes_file = path / "nodes.json"
        self.edges_file = path / "edges.json"
        self.nodes: dict[str, dict] = {}
        self.edges: list[dict] = []

    def save(self):
        write_json(self.nodes_file, self.nodes)
        write_json(self.edges_file, self.edges)

    def load(self):
        self.nodes = read_json(self.nodes_file)
        self.edges = read_json(self.edges_file)

11.3 SQLite Store

class SqliteStore:
    """SQLite 存储,适合中大型项目。"""

    def __init__(self, path: Path):
        self.db_path = path / "graph.db"
        self._init_tables()

    def _init_tables(self):
        self.conn.execute("""
            CREATE TABLE IF NOT EXISTS nodes (
                id TEXT PRIMARY KEY,
                type TEXT NOT NULL,
                data TEXT NOT NULL
            )
        """)
        self.conn.execute("""
            CREATE TABLE IF NOT EXISTS edges (
                id TEXT PRIMARY KEY,
                type TEXT NOT NULL,
                source TEXT NOT NULL,
                target TEXT NOT NULL,
                properties TEXT
            )
        """)
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_edge_source ON edges(source)")
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_edge_target ON edges(target)")
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_edge_type ON edges(type)")
        self.conn.execute("CREATE INDEX IF NOT EXISTS idx_node_type ON nodes(type)")

11.4 索引实现

class IndexManager:
    def __init__(self, config: Config):
        self.keyword_index = KeywordIndex()      # 必需
        self.symbol_index = SymbolIndex()         # 必需
        self.file_index = FileIndex()             # 必需

class KeywordIndex:
    """倒排索引,支持 BM25 和正则搜索。"""
    def __init__(self):
        self.postings: dict[str, list[tuple[str, int]]] = {}  # token → [(doc_id, tf)]

    def add(self, doc_id: str, content: str):
        tokens = tokenize(content)
        for token in tokens:
            self.postings.setdefault(token, []).append((doc_id, 1))

class SymbolIndex:
    """符号名 → 节点 ID 的哈希索引。"""
    def __init__(self):
        self.symbols: dict[str, list[str]] = {}  # symbol_name → [node_ids]

class FileIndex:
    """文件路径 → 节点信息的哈希索引。"""
    def __init__(self):
        self.files: dict[str, dict] = {}  # path → file_info

12. File Watcher

12.1 文件监听

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class ProjectBrainWatcher(FileSystemEventHandler):
    def __init__(self, project_path: str, updater: IncrementalUpdater):
        self.project_path = project_path
        self.updater = updater
        self.pending_changes: dict[str, float] = {}
        self.debounce_seconds = 5

    def on_modified(self, event):
        if self._should_ignore(event.src_path):
            return
        self.pending_changes[event.src_path] = time.time()

    def on_created(self, event):
        self.on_modified(event)

    def on_deleted(self, event):
        if self._should_ignore(event.src_path):
            return
        self.updater.handle_delete(event.src_path)

    def _should_ignore(self, path: str) -> bool:
        return is_excluded(path, self.exclude_patterns)

12.2 增量更新

class IncrementalUpdater:
    def update(self, changed_files: list[str]):
        for file_path in changed_files:
            # 1. 定位受影响的图谱节点
            affected = self.file_index.get_nodes_for_file(file_path)

            # 2. 删除旧节点和边
            for node_id in affected:
                self.graph.delete_node(node_id)

            # 3. 重新解析文件
            if is_code_file(file_path):
                result = self.code_parser.parse_file(file_path)
            elif is_doc_file(file_path):
                result = self.doc_parser.parse_file(file_path)
            else:
                continue

            # 4. 写入新节点和边
            self.graph.add_nodes(result.nodes)
            self.graph.add_edges(result.edges)

        # 5. 重建受影响的索引
        self.index_manager.rebuild(changed_files)

12.3 定时全量校准

class ScheduledRebuilder:
    def __init__(self, interval_seconds: int = 3600):
        self.interval = interval_seconds

    def start(self):
        while True:
            time.sleep(self.interval)
            self._full_rebuild()

    def _full_rebuild(self):
        # 全量扫描,对比现有图谱,修正差异
        ...

12.4 监听暂停/恢复(pull_wiki 使用)

pull_wiki 工具在下载 wiki 文档期间需要暂停文件监听,避免每个写入文件触发一次增量重建。 ProjectBrainServer 提供轻量暂停/恢复机制(mcp/server.py):

  • _pause_file_watcher():仅停止 OS observer(WatcherManager.stop),保留 self._updater 与 reconciler 存活。返回是否已暂停。区别于 _stop_watcher(会销毁 updater 并强制 reconcile)。
  • _create_watcher_manager():用配置参数重建并启动 WatcherManager(含 polling 回退), 供 _start_watcher 和 _resume_file_watcher 共用。
  • _resume_file_watcher():仅重建 observer(不重新 reconcile),恢复后 watcher 继续监听。

pull_wiki 调用顺序:pause → download → _updater.update(files) → resume(update 在 resume 前,避免 watcher 与显式更新竞争;resume 在 finally 块保证即使失败也恢复)。


13. MCP Server

13.1 MCP Server 实现

from mcp.server import Server
from mcp.types import Tool, TextContent

class ProjectBrainMCPServer:
    def __init__(self, query_engine: QueryEngine, reasoning: ReasoningEngine):
        self.server = Server("bot-brain")
        self.query_engine = query_engine
        self.reasoning = reasoning
        self._register_tools()

    def _register_tools(self):
        """注册所有 MCP Tools。"""
        tools = [
            Tool(
                name="keyword_search",
                description="关键词全文搜索,类似 grep",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "query": {"type": "string", "description": "搜索关键词或正则表达式"},
                        "scope": {"type": "string", "description": "限定搜索范围"},
                        "top_k": {"type": "integer", "default": 20}
                    },
                    "required": ["query"]
                }
            ),
            Tool(
                name="locate_symbol",
                description="符号定位(类/函数/模块)",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "symbol_name": {"type": "string"},
                        "kind": {"type": "string", "enum": ["class", "function", "module", "struct", "enum"]}
                    },
                    "required": ["symbol_name"]
                }
            ),
            # ... 其他 Tools
        ]

        for tool in tools:
            self.server.register_tool(tool.name, self._get_handler(tool.name), tool.inputSchema)

    def _get_handler(self, tool_name: str):
        """获取 Tool 对应的处理函数。"""
        handlers = {
            "keyword_search": self._handle_keyword_search,
            "locate_symbol": self._handle_locate_symbol,
            "get_call_graph": self._handle_get_call_graph,
            "get_dependencies": self._handle_get_dependencies,
            "get_module_contents": self._handle_get_module_contents,
            "get_related_tests": self._handle_get_related_tests,
            "get_history": self._handle_get_history,
            "get_owner": self._handle_get_owner,
            "get_conventions": self._handle_get_conventions,
            "impact_analysis": self._handle_impact_analysis,
            "test_recommendation": self._handle_test_recommendation,
            # ...
        }
        return handlers.get(tool_name)

    async def _handle_keyword_search(self, query: str, scope: str = None, top_k: int = 20):
        result = self.query_engine.keyword_search(query, scope, top_k)
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]

    async def _handle_locate_symbol(self, symbol_name: str, kind: str = None):
        result = self.query_engine.locate_symbol(symbol_name, kind)
        return [TextContent(type="text", text=json.dumps(result, ensure_ascii=False))]

    # ... 其他 handlers

    def run(self):
        """启动 MCP Server。"""
        self.server.run(transport="stdio")

13.2 Tool 处理器示例

class SymbolHandler:
    """符号相关 Tool 的处理器。"""

    def __init__(self, graph: GraphStore, indexes: IndexManager):
        self.graph = graph
        self.indexes = indexes

    def locate_symbol(self, symbol_name: str, kind: str = None) -> dict:
        # 从符号索引查找
        node_ids = self.indexes.symbol_index.lookup(symbol_name)

        # 过滤 kind
        results = []
        for node_id in node_ids:
            node = self.graph.get_node(node_id)
            if node and (kind is None or node.get("kind") == kind):
                results.append(self._format_symbol(node))

        return {"symbols": results}

    def get_symbol_info(self, symbol_id: str) -> dict:
        node = self.graph.get_node(symbol_id)
        if not node:
            return {"error": f"Symbol not found: {symbol_id}"}

        # 获取关联信息
        callers = self._get_callers(symbol_id)
        callees = self._get_callees(symbol_id)
        tests = self._get_related_tests(symbol_id)

        return {
            **self._format_symbol(node),
            "callers": callers,
            "callees": callees,
            "tests": tests
        }

14. 配置管理

14.1 配置文件

.botbrain/config.yaml:

project:
  name: "my-project"
  languages: [python, typescript]  # 手动指定,覆盖自动检测;留空则自动检测
  exclude:
    - "vendor/"
    - "*.generated.*"

search:
  strategy: keyword  # keyword | keyword+graph

watcher:
  debounce_seconds: 5
  full_rebuild_interval_seconds: 3600

storage:
  # auto | json | sqlite
  backend: auto
  threshold: 100000

history:
  max_commits: 10000
  include_prs: true

wiki:
  enabled: false              # 是否启用 wiki 拉取
  cookie_file: ""             # 登录 cookie,留空默认 ~/.botbrain/wiki_cookies.json
  output_dir: "docs/wiki"     # 下载目录(项目相对路径)

14.2 配置加载

@dataclass
class Config:
    project: ProjectConfig
    search: SearchConfig
    watcher: WatcherConfig
    storage: StorageConfig
    history: HistoryConfig

    @staticmethod
    def load(project_path: str) -> Config:
        config_file = Path(project_path) / ".botbrain" / "config.yaml"
        if config_file.exists():
            return Config.from_yaml(config_file)
        return Config.default()

15. 错误处理

15.1 错误分类

class ProjectBrainError(Exception):
    """基础错误类。"""

class ConfigError(ProjectBrainError):
    """配置错误。"""

class ParseError(ProjectBrainError):
    """解析错误(语法不支持等)。"""

class QueryError(ProjectBrainError):
    """查询错误。"""

class StorageError(ProjectBrainError):
    """存储错误。"""

15.2 降级策略

图谱未构建
    → 自动降级检索策略到 keyword
    → 提示用户执行构建

Tree-sitter 解析失败
    → 跳过该文件
    → File 节点标记 parse_status: "error" / "partial" / "skipped"
    → 记录错误日志
    → 继续解析其他文件
    → 查询涉及该文件时,结果携带 warning: "数据可能不完整"

Git 命令执行失败
    → 跳过历史解析
    → 记录警告日志
    → 图谱仍可用(无历史信息)

15.3 版本不兼容处理

图谱版本不兼容
    → 读取 metadata.json 中的 schema_version
    → 与当前代码版本对比
    
major 不兼容
    → 清空缓存
    → 全量重建
    → 日志提示用户

minor 不兼容
    → 执行迁移函数
    → 增量更新 metadata

迁移失败
    → 回退到全量重建

16. P0 实施计划

阶段一:基础框架

  • 项目骨架搭建
  • 配置管理
  • 数据模型定义
  • GraphStore 接口 + JSON/SQLite 实现
  • 索引基础(KeywordIndex、SymbolIndex、FileIndex)

阶段二:Build Engine

  • Tree-sitter 集成 + 5种语言规则
  • Document Parser(Markdown)
  • History Parser(Git)
  • Link Engine(Explicit Link + Historical Link)
  • Convention Extractor(代码结构 + 命名模式)

阶段三:Query Engine + MCP Server

  • Keyword Search(保底)
  • Graph Search(可选)
  • 检索策略调度
  • MCP Server 实现
  • MCP Tool 处理器

阶段四:Reasoning Engine

  • Impact Analysis
  • Test Recommendation

阶段五:Watcher + Skill

  • File Watcher
  • 增量更新
  • 定时全量校准
  • Skill 文件编写(OpenCode / Claude Code)

P0 完成标准

支持 Agent 完成四类核心任务:

  1. 增量功能开发:定位实现位置、理解项目约定、发现可复用组件
  2. 代码重构:理解现有结构、评估影响范围
  3. 代码修正:从现象定位根因、理解上下文后修复
  4. 测试保障:测试覆盖分析