面向AI IDE的代码拆分优化方案

文档信息

  • 创建日期: 2026-02-01
  • 版本: v1.0
  • 目的: 优化代码拆分方案以适配AI IDE(Cursor等)

📋 核心问题

原拆分方案的AI IDE盲区

当前 REPOSITORY_SPLIT_PLAN.md 主要考虑:

  • ✅ 安全隔离(闭源vs开源)
  • ✅ 权限管理
  • ✅ CI/CD独立
  • ✅ 商业模式

但忽略了

  • ❌ AI IDE的上下文理解能力
  • ❌ 跨仓库代码补全
  • ❌ 智能重构和导航
  • ❌ AI辅助调试效率

🤖 AI IDE的特殊需求

Cursor等AI IDE的工作原理

AI IDE的代码理解能力 = f(上下文完整度, 文件关系, 代码结构)

单仓库:
  上下文范围: [──────────────完整────────────────]
  AI理解度:   ████████████████ 100%
  
多仓库(8个):
  上下文范围: [──闭源──][──SDK──][──App1──][──App2──]...
  AI理解度:   ████░░░░░░░░░░░░ 25-40%

多仓库对AI IDE的影响

功能 单仓库 多仓库 影响
代码补全 ✅ 完整 ⚠️ 仅当前仓库 跨仓库引用无法补全
跳转定义 ✅ 一键跳转 ❌ 需手动切换仓库 效率降低70%
智能重构 ✅ 跨文件 ❌ 仅当前仓库 无法全局重构
AI问答 ✅ 理解整体架构 ⚠️ 上下文受限 回答质量下降
BUG诊断 ✅ 完整调用链 ❌ 需要跨仓库推理 诊断准确度下降
文档生成 ✅ 完整文档 ⚠️ 碎片化文档 需要手动整合

典型场景对比

# 场景1: 修改API接口
# ========================================

# 单仓库 (Cursor体验)
# 1. 修改 Core API
@app.post("/api/mbe/hope/detect-surprise")
def detect_surprise(data: SurpriseRequest):
    # 新增一个字段
    return {"surprise_score": 0.8, "confidence": 0.9}  # ← 新增

# 2. Cursor自动提示: "此API有2处调用,是否同步更新?"
#    - src/education/adaptive_tutor.py
#    - src/llm/llm_moe.py

# 3. 一键更新所有引用 ✅

# ----------------------------------------

# 多仓库 (Cursor体验)
# 1. 修改 mbe-core 中的API
@app.post("/api/mbe/hope/detect-surprise")
def detect_surprise(data: SurpriseRequest):
    return {"surprise_score": 0.8, "confidence": 0.9}  # ← 新增

# 2. Cursor提示: "此API在当前仓库无引用" ⚠️
#    (实际上有引用,但在其他仓库)

# 3. 手动打开 mbe-education 仓库
#    手动搜索引用
#    手动更新 ❌

# 效率对比: 10x slower!

💡 优化方案

方案A: Monorepo + 虚拟隔离(推荐 ⭐⭐⭐⭐⭐)

mbe-monorepo/                    # 单一Git仓库
├── .git/                        # 统一版本控制
│
├── private/                     # 🔒 私有代码区
│   ├── .gitignore               # 忽略不被公开的部分
│   ├── core/                    # MBE Core
│   │   ├── src/
│   │   ├── tests/
│   │   └── pyproject.toml
│   ├── platform/                # 平台后端
│   └── marketplaces/            # 市场服务
│
├── public/                      # ⭐ 公开代码区
│   ├── sdk-python/              # SDK
│   │   ├── src/mbe_sdk/
│   │   ├── .git-subtree         # Git subtree标记
│   │   └── pyproject.toml
│   ├── mcp-server/              # MCP Server
│   └── education/               # 教育应用
│
├── shared/                      # 共享代码
│   ├── types/                   # 类型定义
│   ├── protocols/               # 协议定义
│   └── docs/                    # 共享文档
│
└── tools/                       # 开发工具
    ├── dev-workspace/           # 开发环境
    ├── ci-cd/                   # CI/CD配置
    └── publish/                 # 发布脚本

关键技术: Git Subtree

# 工作流程

# 1. 开发时:在Monorepo工作(AI IDE友好)
cd mbe-monorepo
code .  # Cursor打开整个仓库,完整上下文 ✅

# 2. 发布时:使用Git Subtree推送到独立仓库
# SDK发布
git subtree push --prefix=public/sdk-python \
  https://github.com/mbe-org/mbe-sdk-python.git main

# MCP Server发布
git subtree push --prefix=public/mcp-server \
  https://github.com/mbe-org/mbe-mcp-server.git main

# Education App发布
git subtree push --prefix=public/education \
  https://github.com/mbe-org/mbe-education.git main

# 3. 对外:看起来是独立仓库
# https://github.com/mbe-org/mbe-sdk-python     ⭐ 公开
# https://github.com/mbe-org/mbe-mcp-server      ⭐ 公开
# https://github.com/mbe-org/mbe-education       ⭐ 公开

# 私有部分永远不会被推送 🔒

优势

AI IDE体验:
  - ✅ 完整的代码上下文
  - ✅ 跨模块代码补全
  - ✅ 一键跳转定义
  - ✅ 全局智能重构
  - ✅ 准确的AI问答
  - ✅ 完整的调用链追踪

安全性:
  - ✅ Git历史隔离(subtree不包含私有历史)
  - ✅ 权限控制(公开仓库只读)
  - ✅ 自动化发布(脚本控制)

开发效率:
  - ✅ 单一开发环境
  - ✅ 统一的CI/CD
  - ✅ 简化的依赖管理

权限控制

# .gitignore (在public/子目录中)
# 确保敏感引用不被包含

# public/sdk-python/.gitignore
# 私有模块引用(如果误写)
**/private/**
../../private/**

# private/目录的引用检查
*/private/*
# tools/publish/validate_public.py
"""发布前验证公开代码无私有依赖"""

import ast
import os
from pathlib import Path

def check_private_imports(file_path):
    """检查是否导入了私有模块"""
    with open(file_path) as f:
        tree = ast.parse(f.read())
    
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                if 'private' in alias.name:
                    return f"❌ 检测到私有导入: {alias.name} in {file_path}"
        elif isinstance(node, ast.ImportFrom):
            if node.module and 'private' in node.module:
                return f"❌ 检测到私有导入: {node.module} in {file_path}"
    
    return None

def validate_public_code(public_dir):
    """验证公开代码"""
    errors = []
    
    for py_file in Path(public_dir).rglob("*.py"):
        error = check_private_imports(py_file)
        if error:
            errors.append(error)
    
    if errors:
        print("\n".join(errors))
        return False
    else:
        print("✅ 公开代码验证通过")
        return True

if __name__ == "__main__":
    validate_public_code("public/")

方案B: Meta Repository + Workspace(次选 ⭐⭐⭐⭐)

mbe-workspace/                   # Meta仓库(不是代码仓库)
├── .git/                        # 仅管理workspace配置
├── repos/                       # 子仓库(Git submodules)
│   ├── mbe-core/               # ← git submodule
│   ├── mbe-sdk-python/         # ← git submodule
│   ├── mbe-mcp-server/         # ← git submodule
│   └── mbe-education/          # ← git submodule
│
├── .cursor/                     # Cursor配置
│   ├── settings.json           # 跨仓库搜索配置
│   └── rules/
│       └── cross-repo.md       # AI规则:理解仓库关系
│
└── mbe-workspace.code-workspace # VSCode多根工作区

VSCode多根工作区配置

// mbe-workspace.code-workspace
{
  "folders": [
    {
      "name": "🔒 MBE Core",
      "path": "./repos/mbe-core"
    },
    {
      "name": "📦 SDK Python",
      "path": "./repos/mbe-sdk-python"
    },
    {
      "name": "🤖 MCP Server",
      "path": "./repos/mbe-mcp-server"
    },
    {
      "name": "🎓 Education",
      "path": "./repos/mbe-education"
    }
  ],
  "settings": {
    "search.exclude": {
      "**/node_modules": true,
      "**/.git": true,
      "**/venv": true
    },
    "files.watcherExclude": {
      "**/node_modules/**": true
    },
    // Cursor特殊配置
    "cursor.aiContext": {
      "includeAllWorkspaceFolders": true,
      "maxFileSize": 1000000
    }
  }
}

Cursor AI规则配置

<!-- .cursor/rules/cross-repo.md -->
# MBE多仓库项目规则

## 仓库结构

此项目采用多仓库架构:

- `mbe-core`: 核心API服务(私有)
- `mbe-sdk-python`: Python SDK(公开)
- `mbe-mcp-server`: MCP Server(公开)
- `mbe-education`: 教育应用(公开)

## 依赖关系

mbe-education └─ depends on → mbe-sdk-python └─ calls → mbe-core API (HTTP)


## AI辅助规则

1. **跨仓库引用**: 当在education仓库看到`from mbe_sdk import MBEClient`时,
   请在sdk-python仓库中查找定义

2. **API调用**: 当看到`client.hope.detect_surprise()`时,
   对应的实现在`mbe-core/src/core/hope_moe.py`

3. **数据模型**: 共享的数据模型定义在各自仓库的`models.py`中

4. **修改影响**: 修改API时,需要检查:
   - mbe-core: API实现
   - mbe-sdk-python: SDK客户端
   - mbe-education: 应用层调用

## 快速导航

- Core API定义: `mbe-core/src/api/`
- SDK实现: `mbe-sdk-python/src/mbe_sdk/`
- 应用层: `mbe-education/src/mbe_education/`

优势

AI IDE体验:
  - ✅ 可以同时看到所有代码(多根工作区)
  - ⚠️ 代码补全受限(跨文件夹)
  - ✅ 全局搜索(所有仓库)
  - ⚠️ AI理解需要配置规则

安全性:
  - ✅ 完全独立的Git仓库
  - ✅ 权限管理更严格
  - ✅ Git历史完全隔离

开发效率:
  - ⚠️ 需要同步多个仓库
  - ⚠️ Git submodule管理复杂
  - ✅ CI/CD独立

方案C: 纯多仓库 + Cursor增强(当前方案 ⭐⭐⭐)

即当前 REPOSITORY_SPLIT_PLAN.md 的方案,但增加Cursor优化。

Cursor配置增强

// 每个仓库的 .cursor/settings.json
{
  "cursor.aiContext": {
    // 包含相关仓库的README,帮助AI理解依赖
    "additionalFiles": [
      "../mbe-core/README.md",
      "../mbe-sdk-python/README.md"
    ]
  }
}
<!-- mbe-education/.cursor/rules/dependencies.md -->
# 依赖说明

本项目依赖以下外部服务:

## MBE Core API

- 仓库: `mbe-core` (私有,本地路径: `../mbe-core/`)
- 基础URL: `http://localhost:8000`
- 主要端点:
  - `POST /api/mbe/hope/detect-surprise`: 惊讶度检测
  - `POST /api/mbe/experts/route`: 专家路由

## MBE SDK Python

- 仓库: `mbe-sdk-python` (公开)
- PyPI: `mbe-sdk`
- 本地开发: `../mbe-sdk-python/`
- 主要类:
  - `MBEClient`: 核心客户端
  - `HOPEService`: HOPE Learning服务

当需要理解API调用时,请参考上述仓库。

开发辅助脚本

# tools/cursor_helper.py
"""Cursor AI辅助工具"""

import subprocess
import json

def find_definition_across_repos(symbol, repos_dir="./repos"):
    """在所有仓库中搜索符号定义"""
    results = []
    
    for repo in ["mbe-core", "mbe-sdk-python", "mbe-education"]:
        repo_path = f"{repos_dir}/{repo}"
        try:
            # 使用ripgrep搜索
            output = subprocess.check_output(
                ["rg", f"def {symbol}|class {symbol}", repo_path, "-l"],
                text=True
            )
            for file_path in output.strip().split("\n"):
                results.append({
                    "repo": repo,
                    "file": file_path,
                    "type": "definition"
                })
        except subprocess.CalledProcessError:
            pass
    
    return results

def find_api_callers(endpoint):
    """查找API端点的所有调用方"""
    # 搜索类似 client.post("/api/mbe/hope/detect-surprise")
    # 的调用
    pass

if __name__ == "__main__":
    # 示例: 查找 detect_surprise 的定义
    results = find_definition_across_repos("detect_surprise")
    print(json.dumps(results, indent=2))

劣势

AI IDE体验:
  - ❌ 需要手动切换仓库
  - ❌ 代码补全不跨仓库
  - ❌ AI理解受限
  - ⚠️ 需要大量配置和脚本

开发效率:
  - ❌ 跨仓库修改繁琐
  - ❌ 调试困难(如DEBUGGING_COMPARISON.md所述)
  - ⚠️ 学习曲线陡峭

📊 方案对比

维度 方案A
Monorepo+Subtree
方案B
Meta Repo
方案C
纯多仓库
AI代码补全 ⭐⭐⭐⭐⭐ 完美 ⭐⭐⭐ 良好 ⭐⭐ 受限
跳转定义 ⭐⭐⭐⭐⭐ 一键 ⭐⭐⭐⭐ 较好 ⭐⭐ 需切换
AI问答质量 ⭐⭐⭐⭐⭐ 优秀 ⭐⭐⭐⭐ 良好 ⭐⭐⭐ 一般
智能重构 ⭐⭐⭐⭐⭐ 全局 ⭐⭐⭐ 受限 ⭐⭐ 仅单仓库
调试效率 ⭐⭐⭐⭐⭐ 高 ⭐⭐⭐⭐ 较高 ⭐⭐⭐ 中等
安全隔离 ⭐⭐⭐⭐ 良好 ⭐⭐⭐⭐⭐ 完美 ⭐⭐⭐⭐⭐ 完美
权限管理 ⭐⭐⭐ 一般 ⭐⭐⭐⭐⭐ 精细 ⭐⭐⭐⭐⭐ 精细
学习曲线 ⭐⭐⭐⭐ 平缓 ⭐⭐⭐ 中等 ⭐⭐ 陡峭
维护成本 ⭐⭐⭐⭐⭐ 低 ⭐⭐⭐ 中等 ⭐⭐ 高

推荐

🏆 推荐方案: A (Monorepo + Git Subtree)

理由:
1. AI IDE体验最佳(Cursor等)
2. 开发效率最高
3. 安全性足够(通过subtree隔离)
4. 维护成本最低

适用场景:
- 核心团队开发(5-20人)
- 重度使用AI IDE
- 频繁跨模块修改

🚀 实施方案A的步骤

Week 1: 重组为Monorepo

# Step 1: 备份现有仓库
cd ~
tar -czf mbe-backup-$(date +%Y%m%d).tar.gz mises-behavior-engine/

# Step 2: 创建Monorepo结构
mkdir mbe-monorepo
cd mbe-monorepo
git init

# Step 3: 移动代码到新结构
mkdir -p private/core
mkdir -p public/sdk-python
mkdir -p public/mcp-server
mkdir -p public/education
mkdir -p shared/types

# 复制私有代码
cp -r ~/mises-behavior-engine/src/* private/core/src/
cp -r ~/mises-behavior-engine/tests private/core/

# 复制公开代码
cp -r ~/mises-behavior-engine/opensource/mbe-sdk-python/* public/sdk-python/
cp -r ~/mises-behavior-engine/opensource/mbe-mcp-server/* public/mcp-server/
cp -r ~/mises-behavior-engine/opensource/mbe-education/* public/education/

# Step 4: 创建共享类型定义
# shared/types/api_models.py

Week 2: 配置Git Subtree

# 在public子目录创建.gitattributes
# public/sdk-python/.gitattributes
* export-ignore=../../private/**

# 配置subtree推送
# tools/publish/publish_sdk.sh
#!/bin/bash
git subtree split --prefix=public/sdk-python -b sdk-python-release
git push https://github.com/mbe-org/mbe-sdk-python.git sdk-python-release:main
git branch -D sdk-python-release

Week 3: 配置Cursor

// .cursor/settings.json
{
  "cursor.aiContext": {
    "includeAllWorkspaceFolders": true,
    "maxContextFiles": 100,
    "priorityPatterns": [
      "**/*.py",
      "**/*.md",
      "**/README.md"
    ]
  },
  "search.exclude": {
    "**/.git": true,
    "**/venv": true,
    "**/__pycache__": true,
    "**/node_modules": true
  }
}
<!-- .cursor/rules/project.md -->
# MBE项目AI规则

## 项目结构

这是一个Monorepo,包含:
- `private/`: 闭源核心代码(MBE Core)
- `public/`: 开源代码(SDK, Apps)
- `shared/`: 共享类型和工具

## 跨模块引用

公开代码只能引用shared和public中的内容,不能引用private。

当看到跨模块调用时:
1. `from mbe_sdk import ...` → 查看 `public/sdk-python/src/mbe_sdk/`
2. API实现 → 查看 `private/core/src/api/`
3. 共享类型 → 查看 `shared/types/`

## 安全提醒

在public/目录编码时,绝对不要引用private/中的模块。

Week 4: 测试和验证

# 测试1: Cursor代码补全
# 在education模块中输入 `from mbe_sdk import `
# 应该能自动补全 MBEClient 等

# 测试2: 跳转定义
# Ctrl+Click `MBEClient` 应该跳转到 public/sdk-python/src/mbe_sdk/client.py

# 测试3: 全局搜索
# Ctrl+Shift+F 搜索 "detect_surprise"
# 应该能找到所有引用(private + public)

# 测试4: 智能重构
# 重命名一个API方法,Cursor应该提示更新所有引用

# 测试5: 发布验证
./tools/publish/publish_sdk.sh
# 验证GitHub上的仓库不包含private代码

🎯 最终建议

修改后的实施路线

原方案(REPOSITORY_SPLIT_PLAN.md):
  └─ 纯多仓库架构
  └─ AI IDE体验差
  └─ 调试困难

优化方案:
  └─ Monorepo + Git Subtree
  └─ AI IDE体验优秀
  └─ 开发效率高

时间线:
  Week 1-3:   修复BUG(不变)
  Week 4:     准备调试工具(不变)
  Week 5-8:   重组为Monorepo(替代原拆分方案)
  Week 9:     测试和验证
  Week 10:    团队培训和迁移

Total: 10周(vs 原9周,仅增加1周)

关键优势

开发体验:
  ✅ Cursor代码补全完美工作
  ✅ 一键跳转定义
  ✅ AI理解完整上下文
  ✅ 全局智能重构
  ✅ 调试效率高(单仓库)

安全性:
  ✅ Git Subtree隔离历史
  ✅ 发布前自动验证
  ✅ 公开仓库独立维护

商业模式:
  ✅ 对外看起来是独立仓库
  ✅ 开源社区友好
  ✅ 核心代码保护

团队效率:
  ✅ 学习曲线平缓
  ✅ 维护成本低
  ✅ CI/CD简化

📚 参考资料

Git Subtree vs Submodule

# Git Subtree 优势
✅ 子项目代码直接存储在主仓库中(单一clone)
✅ 更容易使用(无需特殊命令)
✅ 适合AI IDE(完整上下文)
✅ 对贡献者透明

# Git Submodule 劣势
❌ 子项目是外部引用(需要多次clone)
❌ 容易出错(忘记更新submodule)
❌ AI IDE上下文受限
❌ 新手不友好

Monorepo成功案例

  • Google: 单一巨型仓库(20亿行代码)
  • Facebook: Monorepo架构
  • Microsoft: 多个大型Monorepo
  • Vercel: Next.js等项目使用Monorepo

工具生态:

  • Turborepo: Monorepo构建工具
  • Nx: 企业级Monorepo工具
  • Lerna: JavaScript Monorepo管理

最后更新: 2026-02-01
文档状态: ✅ 强烈推荐采纳方案A