一、核心理念
1.1 问题背景
传统多仓库开发的痛点:
- 前端、后端、AI服务各自独立仓库,代码分散
- Claude AI 无法跨仓库理解完整业务逻辑
- 缺少全局视角,导致接口对接、数据模型不一致
- 排查跨服务问题需要频繁切换项目
解决思路:
- 使用 VSCode Multi-root Workspace 整合多仓库
- 通过权限控制机制防止跨仓库误操作
- 优化 AI 上下文,提升协作效率
- 保持各仓库独立版本管理
1.2 核心原则
markdown
✅ 单一真相源(Single Source of Truth)
- 每个仓库独立管理自己的代码
- 接口契约文档作为跨仓库协作的桥梁
✅ 权限最小化(Principle of Least Privilege)
- 开发时只授予当前工作仓库的写权限
- 其他仓库默认只读
✅ 上下文最大化(Maximum Context)
- AI 能访问所有仓库代码(只读)
- 通过文档增强跨仓库理解
✅ 自动化防护(Automated Safeguards)
- Git Hooks 防止误提交
- 脚本工具辅助操作
二、Workspace 架构设计
2.1 目录结构
perl
my-app-workspace/
├── .workspace/ # Workspace 配置和工具
│ ├── config.json # 工作区配置
│ ├── scripts/ # 自动化脚本
│ ├── docs/ # 共享文档
│ └── .claudeignore # Claude 忽略规则
│
├── frontend/ # 前端仓库 (Git Repo)
│ ├── .git/
│ ├── src/
│ ├── package.json
│ └── .repo-config.json # 仓库元信息
│
├── backend/ # 后端仓库 (Git Repo)
│ ├── .git/
│ ├── src/
│ ├── requirements.txt
│ └── .repo-config.json
│
├── ai-service/ # AI服务仓库 (Git Repo)
│ ├── .git/
│ ├── src/
│ ├── requirements.txt
│ └── .repo-config.json
│
├── shared-contracts/ # 共享契约文档 (可选的独立仓库)
│ ├── api-specs/ # OpenAPI 规范
│ ├── data-models/ # 数据模型定义
│ ├── events/ # 事件定义
│ └── diagrams/ # 架构图
│
└── my-app.code-workspace # VSCode Workspace 配置文件
2.2 Workspace 配置文件
my-app.code-workspace
json
{
"folders": [
{
"name": "🎨 Frontend (Active)",
"path": "./frontend"
},
{
"name": "⚙️ Backend (Read-Only)",
"path": "./backend"
},
{
"name": "🤖 AI Service (Read-Only)",
"path": "./ai-service"
},
{
"name": "📄 Contracts",
"path": "./shared-contracts"
},
{
"name": "🛠️ Workspace Tools",
"path": "./.workspace"
}
],
"settings": {
// 全局设置
"files.autoSave": "onFocusChange",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true
},
// 搜索优化 - 排除不必要的目录
"search.exclude": {
"**/node_modules": true,
"**/dist": true,
"**/build": true,
"**/.git": true,
"**/venv": true,
"**/__pycache__": true,
"**/coverage": true,
"**/.next": true,
"**/.nuxt": true
},
// Git 配置
"git.detectSubmodules": false,
"git.ignoredRepositories": [],
// 文件关联
"files.associations": {
"*.yaml": "yaml",
".repo-config.json": "jsonc"
},
// Claude Code 优化配置
"search.followSymlinks": false,
"files.watcherExclude": {
"**/node_modules/**": true,
"**/.git/objects/**": true
}
},
"extensions": {
"recommendations": [
"eamodio.gitlens", // Git 增强
"usernamehw.errorlens", // 错误提示
"editorconfig.editorconfig", // 编码规范
"davidanson.vscode-markdownlint", // Markdown 检查
"42crunch.vscode-openapi" // OpenAPI 支持
]
}
}
2.3 仓库元信息配置
每个仓库根目录创建 .repo-config.json
:
json
{
"repoName": "frontend",
"repoType": "frontend",
"primaryLanguage": "typescript",
"owner": "frontend-team",
"protectionLevel": "active", // active | readonly | restricted
"dependencies": {
"internal": ["shared-contracts"],
"external": ["backend/api", "ai-service/recommendations"]
},
"interfaces": {
"consumes": [
"backend: /api/v1/*",
"ai-service: /api/recommendations/*"
],
"provides": [
"Web UI"
]
},
"contactPoints": {
"apiDocs": "../shared-contracts/api-specs/backend-api.yaml",
"dataModels": "../shared-contracts/data-models/user.json"
}
}
三、权限控制机制
3.1 多层次防护体系
yaml
Layer 1: Git Hooks (强制)
↓
Layer 2: VSCode 设置 (提示)
↓
Layer 3: AI Prompt Engineering (引导)
↓
Layer 4: 代码审查 (人工复核)
3.2 Git Hooks 防护
方案 A:Pre-commit Hook(推荐)
在每个仓库的 .git/hooks/pre-commit
中添加:
bash
#!/bin/bash
# 防止意外提交其他仓库的文件
REPO_NAME=$(basename $(git rev-parse --show-toplevel))
REPO_ROOT=$(git rev-parse --show-toplevel)
echo "🔍 检查提交文件范围..."
# 获取暂存文件的绝对路径
staged_files=$(git diff --cached --name-only --diff-filter=ACM)
for file in $staged_files; do
file_abs_path="$REPO_ROOT/$file"
# 检查文件是否在当前仓库内
if [[ ! "$file_abs_path" =~ ^"$REPO_ROOT" ]]; then
echo "❌ 错误:尝试提交仓库外的文件"
echo " 文件: $file"
echo " 当前仓库: $REPO_NAME"
echo ""
echo "💡 提示:请检查是否在正确的仓库中工作"
exit 1
fi
done
echo "✅ 文件检查通过"
exit 0
安装脚本(.workspace/scripts/install-hooks.sh):
bash
#!/bin/bash
WORKSPACE_ROOT=$(pwd)
HOOK_SCRIPT="$WORKSPACE_ROOT/.workspace/scripts/git-hooks/pre-commit"
# 为每个仓库安装 hooks
for repo in frontend backend ai-service; do
if [ -d "$repo/.git" ]; then
echo "📦 为 $repo 安装 Git Hooks..."
cp "$HOOK_SCRIPT" "$repo/.git/hooks/pre-commit"
chmod +x "$repo/.git/hooks/pre-commit"
echo " ✅ 完成"
fi
done
echo ""
echo "🎉 所有 Git Hooks 安装完成!"
3.3 VSCode 配置防护
方案 A:文件监控提示
创建 .workspace/extensions/file-guard.js
(需要自定义扩展,或使用现有扩展)
方案 B:使用 .editorconfig 标记只读区域
editorconfig
# .editorconfig (放在 workspace 根目录)
root = true
# 默认设置
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
# 前端仓库 - 可编辑
[frontend/**]
indent_style = space
indent_size = 2
# 后端和 AI 服务 - 标记为只读(通过注释提示)
[{backend,ai-service}/**]
# ⚠️ READ-ONLY: 修改前请确认工作模式
indent_style = space
indent_size = 4
3.4 Claude AI 引导机制
方案:工作模式系统
创建 .workspace/.claude/mode-config.json
:
json
{
"currentMode": "frontend-dev",
"modes": {
"frontend-dev": {
"description": "前端开发模式",
"writableRepos": ["frontend", "shared-contracts"],
"readOnlyRepos": ["backend", "ai-service"],
"aiInstructions": "你当前处于【前端开发模式】。只能修改 frontend/ 目录下的文件。如需修改其他仓库,请先询问用户切换工作模式。"
},
"backend-dev": {
"description": "后端开发模式",
"writableRepos": ["backend", "shared-contracts"],
"readOnlyRepos": ["frontend", "ai-service"],
"aiInstructions": "你当前处于【后端开发模式】。只能修改 backend/ 目录下的文件。"
},
"fullstack": {
"description": "全栈模式(需谨慎)",
"writableRepos": ["frontend", "backend", "ai-service", "shared-contracts"],
"readOnlyRepos": [],
"aiInstructions": "你当前处于【全栈模式】,可以修改所有仓库。在修改前请明确告知用户将要修改的仓库和文件。"
},
"readonly": {
"description": "只读模式(代码审查/学习)",
"writableRepos": [],
"readOnlyRepos": ["frontend", "backend", "ai-service", "shared-contracts"],
"aiInstructions": "你当前处于【只读模式】,不应该修改任何代码,仅用于分析、解释和建议。"
}
}
}
Claude 自定义指令(.claude/commands/check-mode.md):
markdown
---
name: check-mode
description: 检查当前工作模式和权限
---
请执行以下操作:
1. 读取 `.workspace/.claude/mode-config.json` 文件
2. 显示当前工作模式
3. 列出可写仓库和只读仓库
4. 提示用户如何切换模式(如有需要)
输出格式:
🎯 当前工作模式:[模式名称]
✅ 可修改仓库:
-
仓库列表
🔒 只读仓库:
-
仓库列表
💡 切换模式:运行 /switch-mode [模式名]
模式切换命令(.claude/commands/switch-mode.md):
markdown
---
name: switch-mode
description: 切换工作模式
---
参数:{mode} - 目标模式(frontend-dev/backend-dev/fullstack/readonly)
执行步骤:
1. 验证目标模式是否存在
2. 更新 `.workspace/.claude/mode-config.json` 中的 `currentMode`
3. 显示新模式的权限配置
4. 提醒用户注意事项
四、AI 上下文优化
4.1 .claudeignore 配置
bash
# .workspace/.claudeignore
# 依赖和构建产物
**/node_modules/
**/dist/
**/build/
**/.next/
**/.nuxt/
**/venv/
**/__pycache__/
# 版本控制
**/.git/
**/.svn/
# 测试覆盖率
**/coverage/
**/.nyc_output/
# 日志文件
**/*.log
**/logs/
# 锁文件(可选,视需求)
**/package-lock.json
**/yarn.lock
**/pnpm-lock.yaml
**/poetry.lock
# 编译缓存
**/.cache/
**/.parcel-cache/
**/.vite/
# 环境变量(敏感信息)
**/.env
**/.env.local
**/.env.*.local
# IDE 配置(个人配置)
**/.vscode/settings.json
**/.idea/
# 大型资源文件
**/assets/videos/
**/public/images/raw/
4.2 上下文增强文档
创建 .workspace/docs/context-guide.md
:
markdown
# AI 上下文指南
## 仓库概览
### Frontend (前端)
- **技术栈**:React 18 + TypeScript + Vite
- **职责**:用户界面、交互逻辑
- **关键目录**:
- `src/api/` - API 调用封装
- `src/types/` - TypeScript 类型定义
- `src/store/` - 状态管理
### Backend (后端)
- **技术栈**:Python FastAPI + PostgreSQL
- **职责**:业务逻辑、数据持久化
- **关键目录**:
- `src/api/` - API 路由
- `src/models/` - 数据模型
- `src/services/` - 业务服务
### AI Service
- **技术栈**:Python + TensorFlow
- **职责**:推荐算法、智能分析
- **关键目录**:
- `src/models/` - ML 模型
- `src/inference/` - 推理服务
## 跨仓库协作要点
### API 契约
- 所有 API 定义在 `shared-contracts/api-specs/`
- 使用 OpenAPI 3.0 规范
- 修改 API 需同时更新前后端
### 数据模型
- 共享类型定义在 `shared-contracts/data-models/`
- 使用 JSON Schema 描述
- 生成工具:
- TypeScript: `npm run generate:types`
- Python: `poetry run generate-models`
### 常见协作场景
#### 场景 1:添加新功能(涉及前后端)
1. 在 `shared-contracts/api-specs/` 定义 API
2. 后端实现 API(backend 仓库)
3. 前端对接 API(frontend 仓库)
4. 更新文档
#### 场景 2:修复跨服务 Bug
1. 在 readonly 模式下分析代码
2. 定位问题所在仓库
3. 切换到对应工作模式
4. 逐个仓库修复
#### 场景 3:重构公共逻辑
1. 使用 fullstack 模式(谨慎)
2. 先更新契约文档
3. 按依赖顺序修改(backend → frontend)
4.3 智能文档索引
创建 .workspace/docs/index.json
(元数据索引):
json
{
"version": "1.0",
"repositories": {
"frontend": {
"entryPoints": [
"frontend/src/main.tsx",
"frontend/src/App.tsx"
],
"keyModules": {
"auth": "frontend/src/features/auth/",
"api": "frontend/src/api/client.ts"
},
"docs": [
"frontend/README.md",
".workspace/docs/frontend-guide.md"
]
},
"backend": {
"entryPoints": [
"backend/src/main.py"
],
"keyModules": {
"auth": "backend/src/api/auth.py",
"database": "backend/src/db/"
},
"docs": [
"backend/README.md",
"backend/docs/api.md"
]
}
},
"contracts": {
"apis": "shared-contracts/api-specs/",
"models": "shared-contracts/data-models/",
"events": "shared-contracts/events/"
},
"quickLinks": {
"架构图": ".workspace/docs/architecture.md",
"工作流程": ".workspace/docs/workflows.md",
"常见问题": ".workspace/docs/faq.md"
}
}
五、实用工具脚本
5.1 Workspace 初始化
.workspace/scripts/init.sh
bash
#!/bin/bash
set -e
echo "🚀 初始化多仓库 Workspace..."
echo ""
WORKSPACE_ROOT=$(pwd)
# 1. 克隆仓库(如果不存在)
clone_repo() {
local repo_name=$1
local repo_url=$2
if [ ! -d "$repo_name" ]; then
echo "📦 克隆 $repo_name..."
git clone "$repo_url" "$repo_name"
else
echo "✓ $repo_name 已存在"
fi
}
# 读取配置(假设有 repos.conf 文件)
if [ -f ".workspace/repos.conf" ]; then
source .workspace/repos.conf
clone_repo "frontend" "$FRONTEND_REPO"
clone_repo "backend" "$BACKEND_REPO"
clone_repo "ai-service" "$AI_SERVICE_REPO"
clone_repo "shared-contracts" "$CONTRACTS_REPO"
fi
echo ""
echo "🔧 安装 Git Hooks..."
bash .workspace/scripts/install-hooks.sh
echo ""
echo "📋 安装依赖..."
# Frontend
if [ -d "frontend" ]; then
echo " → Frontend..."
cd frontend && npm install && cd ..
fi
# Backend
if [ -d "backend" ]; then
echo " → Backend..."
cd backend && pip install -r requirements.txt && cd ..
fi
# AI Service
if [ -d "ai-service" ]; then
echo " → AI Service..."
cd ai-service && pip install -r requirements.txt && cd ..
fi
echo ""
echo "✨ 初始化完成!"
echo ""
echo "📌 下一步:"
echo " 1. 在 VSCode 中打开 my-app.code-workspace"
echo " 2. 运行 /check-mode 检查当前工作模式"
echo " 3. 开始开发!"
5.2 模式切换工具
.workspace/scripts/switch-mode.sh
bash
#!/bin/bash
MODE=$1
CONFIG_FILE=".workspace/.claude/mode-config.json"
if [ -z "$MODE" ]; then
echo "用法: ./switch-mode.sh <mode>"
echo ""
echo "可用模式:"
echo " frontend-dev - 前端开发"
echo " backend-dev - 后端开发"
echo " fullstack - 全栈模式"
echo " readonly - 只��模式"
exit 1
fi
# 检查模式是否存在
if ! grep -q "\"$MODE\"" "$CONFIG_FILE"; then
echo "❌ 未知模式: $MODE"
exit 1
fi
# 更新配置
echo "🔄 切换到模式: $MODE"
# 使用 jq 更新 JSON(如果安装了 jq)
if command -v jq &> /dev/null; then
jq ".currentMode = \"$MODE\"" "$CONFIG_FILE" > "${CONFIG_FILE}.tmp"
mv "${CONFIG_FILE}.tmp" "$CONFIG_FILE"
else
# 简单的 sed 替换(不推荐,但作为 fallback)
sed -i.bak "s/\"currentMode\": \".*\"/\"currentMode\": \"$MODE\"/" "$CONFIG_FILE"
rm "${CONFIG_FILE}.bak"
fi
echo "✅ 模式已切换"
echo ""
echo "📋 运行 /check-mode 查看详情"
5.3 跨仓库状态检查
.workspace/scripts/status.sh
bash
#!/bin/bash
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📊 多仓库状态总览"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
check_repo() {
local repo=$1
if [ ! -d "$repo/.git" ]; then
return
fi
cd "$repo"
echo "📁 $repo"
echo " 分支: $(git branch --show-current)"
# 检查未提交的更改
if ! git diff-index --quiet HEAD --; then
echo " ⚠️ 有未提交的更改"
git status --short | head -5 | sed 's/^/ /'
else
echo " ✅ 工作区干净"
fi
# 检查未推送的提交
unpushed=$(git log @{u}.. --oneline 2>/dev/null | wc -l | tr -d ' ')
if [ "$unpushed" -gt 0 ]; then
echo " 📤 有 $unpushed 个未推送的提交"
fi
echo ""
cd ..
}
check_repo "frontend"
check_repo "backend"
check_repo "ai-service"
check_repo "shared-contracts"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
5.4 同步所有仓库
.workspace/scripts/sync-all.sh
bash
#!/bin/bash
OPERATION=${1:-status} # status/pull/fetch
sync_repo() {
local repo=$1
if [ ! -d "$repo/.git" ]; then
return
fi
echo "📁 $repo"
cd "$repo"
case $OPERATION in
pull)
git pull origin $(git branch --show-current)
;;
fetch)
git fetch --all --prune
;;
status)
git status --short
;;
esac
echo ""
cd ..
}
echo "🔄 执行操作: $OPERATION"
echo ""
sync_repo "frontend"
sync_repo "backend"
sync_repo "ai-service"
sync_repo "shared-contracts"
echo "✅ 完成"
5.5 依赖一致性检查
.workspace/scripts/check-dependencies.py
python
#!/usr/bin/env python3
"""
检查跨仓库的依赖一致性
"""
import json
import yaml
from pathlib import Path
def check_api_contracts():
"""检查 API 契约一致性"""
print("🔍 检查 API 契约...")
contracts_dir = Path("shared-contracts/api-specs")
if not contracts_dir.exists():
print(" ⚠️ 未找到 API 契约目录")
return
# 读取 OpenAPI 规范
for spec_file in contracts_dir.glob("*.yaml"):
with open(spec_file) as f:
spec = yaml.safe_load(f)
api_name = spec_file.stem
print(f" ✓ {api_name}: {len(spec.get('paths', {}))} 个端点")
def check_data_models():
"""检查数据模型一致性"""
print("\n🔍 检查数据模型...")
models_dir = Path("shared-contracts/data-models")
if not models_dir.exists():
print(" ⚠️ 未找到数据模型目录")
return
for model_file in models_dir.glob("*.json"):
with open(model_file) as f:
model = json.load(f)
model_name = model_file.stem
print(f" ✓ {model_name}")
def check_version_consistency():
"""检查版本一致性"""
print("\n🔍 检查版本一致性...")
# 检查前端
frontend_pkg = Path("frontend/package.json")
if frontend_pkg.exists():
with open(frontend_pkg) as f:
data = json.load(f)
print(f" Frontend: v{data.get('version', 'unknown')}")
# 检查后端
backend_pkg = Path("backend/pyproject.toml")
if backend_pkg.exists():
with open(backend_pkg) as f:
content = f.read()
# 简单解析版本号
for line in content.split('\n'):
if line.startswith('version'):
version = line.split('=')[1].strip().strip('"')
print(f" Backend: v{version}")
break
if __name__ == "__main__":
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
print("📋 依赖一致性检查")
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
print()
check_api_contracts()
check_data_models()
check_version_consistency()
print("\n✅ 检查完成")
六、工作流程
6.1 日常开发流程
单仓库功能开发
bash
# 1. 启动 Workspace
code my-app.code-workspace
# 2. 检查当前模式
# 在 Claude 中运行: /check-mode
# 3. 切换到目标模式(如需要)
.workspace/scripts/switch-mode.sh frontend-dev
# 4. 创建功能分支
cd frontend
git checkout -b feature/user-profile
# 5. 开发(AI 辅助)
# Claude 只能修改 frontend/ 目录
# 6. 提交代码
git add .
git commit -m "feat: add user profile page"
git push origin feature/user-profile
# 7. 创建 PR
gh pr create
跨仓库功能开发
场景:新增推荐功能(前端 + 后端 + AI 服务)
bash
# Phase 1: 定义契约
cd shared-contracts
git checkout -b feature/recommendations-api
# 创建 API 规范
# shared-contracts/api-specs/recommendations.yaml
git add .
git commit -m "docs: add recommendations API contract"
git push
# Phase 2: 后端实现
.workspace/scripts/switch-mode.sh backend-dev
cd backend
git checkout -b feature/recommendations-api
# AI 辅助开发:
# "参考 shared-contracts/api-specs/recommendations.yaml 实现 API"
git add .
git commit -m "feat: implement recommendations API"
git push
# Phase 3: AI 服务
.workspace/scripts/switch-mode.sh ai-service-dev
cd ai-service
git checkout -b feature/recommendation-model
# 开发推荐模型...
git push
# Phase 4: 前端对接
.workspace/scripts/switch-mode.sh frontend-dev
cd frontend
git checkout -b feature/recommendations-ui
# AI 辅助开发:
# "参考 shared-contracts/api-specs/recommendations.yaml 实现前端调用"
git push
# Phase 5: 联调测试
# 使用 docker-compose 或本地环境测试
# Phase 6: 依次合并 PR
# 1. shared-contracts PR
# 2. backend PR
# 3. ai-service PR
# 4. frontend PR
6.2 Bug 修复流程
bash
# 1. 定位问题(只读模式)
.workspace/scripts/switch-mode.sh readonly
# 在 Claude 中:
# "分析用户登录失败的原因,涉及 frontend/src/auth 和 backend/src/api/auth.py"
# 2. Claude 分析后给出结论:
# "问题在 backend/src/api/auth.py:45,token 过期时间配置错误"
# 3. 切换到后端模式修复
.workspace/scripts/switch-mode.sh backend-dev
cd backend
git checkout -b fix/auth-token-expiry
# AI 辅助修复...
git commit -m "fix: correct token expiry time"
git push
6.3 代码审查流程
bash
# 1. 拉取所有仓库最新代码
.workspace/scripts/sync-all.sh pull
# 2. 切换到只读模式
.workspace/scripts/switch-mode.sh readonly
# 3. 在 Claude 中:
# "审查 frontend PR #123 和 backend PR #456 的接口一致性"
# 4. Claude 会对比:
# - API 调用是否匹配契约
# - 数据模型是否一致
# - 错误处理是否完整
# 5. 输出审查报告
七、高级技巧
7.1 分支管理策略
统��分支命名规范:
bash
frontend/
├─ main
├─ develop
├─ feature/user-profile-v1
└─ fix/login-bug
backend/
├─ main
├─ develop
├─ feature/user-profile-v1 ← 同名分支
└─ fix/login-bug
ai-service/
├─ main
├─ develop
└─ feature/user-profile-v1
分支切换工具(.workspace/scripts/switch-branch-all.sh):
bash
#!/bin/bash
BRANCH_NAME=$1
if [ -z "$BRANCH_NAME" ]; then
echo "用法: ./switch-branch-all.sh <branch-name>"
exit 1
fi
switch_branch() {
local repo=$1
if [ ! -d "$repo/.git" ]; then
return
fi
cd "$repo"
if git show-ref --verify --quiet refs/heads/"$BRANCH_NAME"; then
echo "📁 $repo → $BRANCH_NAME"
git checkout "$BRANCH_NAME"
else
echo "📁 $repo (⊗ 分支不存在)"
fi
cd ..
}
echo "🔄 切换所有仓库到分支: $BRANCH_NAME"
echo ""
switch_branch "frontend"
switch_branch "backend"
switch_branch "ai-service"
echo ""
echo "✅ 完成"
7.2 环境变量管理
中心化环境变量(.workspace/.env.template):
bash
# 共享配置
APP_ENV=development
API_VERSION=v1
# 前端
VITE_API_BASE_URL=http://localhost:8000
VITE_AI_SERVICE_URL=http://localhost:8001
# 后端
DATABASE_URL=postgresql://localhost:5432/myapp
REDIS_URL=redis://localhost:6379
JWT_SECRET=your-secret-key
# AI Service
MODEL_PATH=./models/
INFERENCE_BATCH_SIZE=32
环境变量同步脚本(.workspace/scripts/sync-env.sh):
bash
#!/bin/bash
echo "🔄 同步环境变量..."
# 从模板复制
cp .workspace/.env.template frontend/.env.local
cp .workspace/.env.template backend/.env
cp .workspace/.env.template ai-service/.env
# 针对不同仓库过滤变量
grep "VITE_" .workspace/.env.template > frontend/.env.local
grep -v "VITE_" .workspace/.env.template | grep -E "(DATABASE|REDIS|JWT)" > backend/.env
grep "MODEL_" .workspace/.env.template > ai-service/.env
echo "✅ 环境变量已同步"
7.3 契约测试自动化
.workspace/scripts/contract-test.sh
bash
#!/bin/bash
echo "🧪 运行契约测试..."
# 1. 使用 Pact/Postman 验证 API 契约
echo " → 测试 Backend API..."
cd backend
npm run test:contract
cd ..
# 2. 验证前端对接
echo " → 测试 Frontend API 调用..."
cd frontend
npm run test:api
cd ..
# 3. 生成契约测试报告
echo " → 生成报告..."
node .workspace/scripts/generate-contract-report.js
echo "✅ 契约测试完成"
7.4 架构视图生成
使用工具自动生成依赖图:
bash
#!/bin/bash
# .workspace/scripts/generate-arch-diagram.sh
# 使用 Graphviz 生成依赖图
cat > /tmp/arch.dot <<EOF
digraph Architecture {
rankdir=LR;
node [shape=box, style=filled];
Frontend [fillcolor=lightblue];
Backend [fillcolor=lightgreen];
AIService [label="AI Service", fillcolor=lightyellow];
Database [fillcolor=lightgray];
Frontend -> Backend [label="REST API"];
Frontend -> AIService [label="Recommendations"];
Backend -> Database [label="SQL"];
Backend -> AIService [label="Training Data"];
}
EOF
dot -Tpng /tmp/arch.dot -o .workspace/docs/architecture.png
echo "✅ 架构图已生成: .workspace/docs/architecture.png"
八、故障排查
8.1 常见问题
❌ Git 提交了其他仓库的文件
原因:
- Git Hooks 未安装或被跳过(
--no-verify
) - 手动
git add
了错误的文件路径
解决:
bash
# 1. 撤销提交(未推送)
git reset --soft HEAD~1
# 2. 取消暂存错误文件
git reset HEAD path/to/wrong/file
# 3. 重新提交
git add correct/files/only
git commit -m "fix: correct commit scope"
预防:
bash
# 安装 Git Hooks
.workspace/scripts/install-hooks.sh
# 永远不使用 --no-verify
❌ Claude 修改了错误仓库的代码
原因:
- 未设置或错误理解工作模式
- Prompt 不够明确
解决:
bash
# 1. 撤销更改
cd wrong-repo
git checkout .
# 2. 切换到正确模式
.workspace/scripts/switch-mode.sh correct-mode
# 3. 重新指导 Claude
# "我刚切换到 [模式],请只修改 [仓库] 中的文件"
❌ Workspace 文件搜索很慢
原因:
- 未配置
search.exclude
- node_modules 等大型目录未忽略
解决: 检查 .code-workspace
配置,确保排除了:
- node_modules
- .git
- dist/build
- venv/pycache
❌ API 对接不一致
原因:
- 未遵循契约优先原则
- 前后端各自修改了接口
解决:
bash
# 1. 运行依赖检查
python .workspace/scripts/check-dependencies.py
# 2. 对比契约和实现
# 手动检查或使用 Pact 测试
# 3. 修复不一致的一方(通常是实现方)
8.2 紧急回滚
.workspace/scripts/emergency-rollback.sh
bash
#!/bin/bash
echo "🚨 紧急回滚工具"
echo ""
echo "选择操作:"
echo " 1) 回滚所有仓库到最后一次提交"
echo " 2) 回滚指定仓库"
echo " 3) 查看所有仓库的提交历史"
echo ""
read -p "输入选项 (1-3): " choice
case $choice in
1)
for repo in frontend backend ai-service; do
if [ -d "$repo/.git" ]; then
echo " 回滚 $repo..."
cd "$repo"
git reset --hard HEAD
cd ..
fi
done
echo "✅ 所有仓库已回滚"
;;
2)
read -p "输入仓库名 (frontend/backend/ai-service): " repo
if [ -d "$repo/.git" ]; then
cd "$repo"
git log --oneline -10
echo ""
read -p "输入要回滚到的 commit hash: " commit
git reset --hard "$commit"
cd ..
echo "✅ $repo 已回滚到 $commit"
fi
;;
3)
for repo in frontend backend ai-service; do
if [ -d "$repo/.git" ]; then
echo ""
echo "=== $repo ==="
cd "$repo"
git log --oneline -5
cd ..
fi
done
;;
esac
九、最佳实践
9.1 团队协作规范
✅ 推荐做法
-
契约优先
- 任何跨仓库功能必须先定义契约
- 契约 PR 必须先合并
-
模式显式声明
- 每次使用 AI 前运行
/check-mode
- 在 PR 描述中注明涉及的仓库
- 每次使用 AI 前运行
-
小步提交
- 每个 commit 只涉及一个仓库
- 相关的跨仓库更改分别提交
-
文档同步
- 代码变更必须同步更新文档
- 使用
shared-contracts/changelog/
记录接口变更
-
定期同步
bash# 每天开始工作前 .workspace/scripts/sync-all.sh pull .workspace/scripts/status.sh
❌ 避免做法
-
不要直接在 Workspace 根目录操作 Git
bash# ❌ 错误 git add . # ✅ 正确 cd frontend && git add .
-
不要跳过 Git Hooks
bash# ❌ 永远不要这样做 git commit --no-verify
-
不要在全栈模式下盲目修改
- 除非必要,避免使用 fullstack 模式
- 使用时必须明确告知 AI 每次要修改的仓库
-
不要将 .env 文件提交到仓库
- 使用 .env.template 或 .env.example
- 在 .gitignore 中排除 .env
9.2 Code Review 检查清单
跨仓库 PR 审查:
- API 契约是否更新?
- 前后端数据模型是否一致?
- 错误处理是否完整(前后端都有)?
- 是否更新了文档?
- 是否添加了契约测试?
- PR 标题是否注明涉及的仓库?
- 是否遵循了分支命名规范?
9.3 性能优化建议
-
减少 Claude 搜索范围
json// 针对大型仓库,在 folder 级别设置 { "folders": [ { "name": "Backend (Large)", "path": "./backend", "settings": { "search.exclude": { "**/migrations/": true, "**/tests/fixtures/": true } } } ] }
-
使用符号链接共享大型资源
bash# 避免重复存储大型文件 ln -s ../../shared-assets/videos frontend/public/videos ln -s ../../shared-assets/videos backend/static/videos
-
定期清理构建产物
bash# .workspace/scripts/clean-all.sh find . -name "node_modules" -type d -prune -exec rm -rf {} \; find . -name "__pycache__" -type d -prune -exec rm -rf {} \; find . -name "dist" -type d -prune -exec rm -rf {} \;
十、扩展功能
10.1 集成 CI/CD
.workspace/.github/workflows/multi-repo-ci.yml
yaml
name: Multi-Repo CI
on:
push:
branches: [main, develop]
jobs:
detect-changes:
runs-on: ubuntu-latest
outputs:
frontend: ${{ steps.changes.outputs.frontend }}
backend: ${{ steps.changes.outputs.backend }}
steps:
- uses: actions/checkout@v3
- uses: dorny/paths-filter@v2
id: changes
with:
filters: |
frontend:
- 'frontend/**'
backend:
- 'backend/**'
test-frontend:
needs: detect-changes
if: needs.detect-changes.outputs.frontend == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Test Frontend
run: |
cd frontend
npm install
npm test
test-backend:
needs: detect-changes
if: needs.detect-changes.outputs.backend == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Test Backend
run: |
cd backend
pip install -r requirements.txt
pytest
10.2 Docker Compose 整合
.workspace/docker-compose.yml
yaml
version: '3.8'
services:
frontend:
build: ./frontend
ports:
- "3000:3000"
environment:
- VITE_API_URL=http://backend:8000
volumes:
- ./frontend:/app
- /app/node_modules
depends_on:
- backend
backend:
build: ./backend
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql://postgres:password@db:5432/myapp
volumes:
- ./backend:/app
depends_on:
- db
ai-service:
build: ./ai-service
ports:
- "8001:8001"
volumes:
- ./ai-service:/app
- ./models:/models
db:
image: postgres:15
environment:
POSTGRES_PASSWORD: password
POSTGRES_DB: myapp
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
10.3 Monorepo 迁移路径
如果未来想迁移到真正的 Monorepo(如 Nx, Turborepo):
bash
# .workspace/scripts/migrate-to-monorepo.sh
#!/bin/bash
echo "🚀 准备迁移到 Monorepo..."
# 1. 创建新的 Monorepo 结构
mkdir -p monorepo/apps
mkdir -p monorepo/packages
# 2. 迁移仓库(保留 Git 历史)
git subtree add --prefix=monorepo/apps/frontend frontend main
git subtree add --prefix=monorepo/apps/backend backend main
git subtree add --prefix=monorepo/apps/ai-service ai-service main
# 3. 迁移共享代码
mv shared-contracts monorepo/packages/contracts
# 4. 设置 Monorepo 工具
cd monorepo
npx create-nx-workspace@latest --preset=apps
echo "✅ Monorepo 结构已创建"
echo "📌 下一步:手动配置 nx.json 和 package.json"
十一、总结
核心价值
✅ 可见性 :AI 能看到完整的业务逻辑链路 ✅ 可控性 :多层次防护防止误操作 ✅ 可维护性 :各仓库独立管理,互不干扰 ✅ 可扩展性:支持未来迁移到 Monorepo
快速开始清单
bash
# 1. 初始化 Workspace
.workspace/scripts/init.sh
# 2. 打开 Workspace
code my-app.code-workspace
# 3. 检查模式
# Claude: /check-mode
# 4. 开始开发
.workspace/scripts/switch-mode.sh frontend-dev
# 5. 定期同步
.workspace/scripts/status.sh
.workspace/scripts/sync-all.sh pull
# 6. 提交前检查
.workspace/scripts/check-dependencies.py
关键文件索引
文件 | 用途 |
---|---|
my-app.code-workspace |
VSCode 配置 |
.workspace/.claude/mode-config.json |
AI 工作模式 |
.workspace/.claudeignore |
AI 忽略规则 |
.workspace/scripts/init.sh |
初始化工具 |
.workspace/scripts/switch-mode.sh |
模式切换 |
.workspace/docs/index.json |
文档索引 |
shared-contracts/api-specs/ |
API 契约 |
进阶学习
文档版本 :v2.0 最后更新 :2025-10-13 维护者:开发团队
附录 A:完整目录结构
csharp
my-app-workspace/
│
├── my-app.code-workspace # VSCode 主配置
│
├── .workspace/ # Workspace 工具目录
│ ├── .claude/
│ │ ├── mode-config.json # AI 工作模式配置
│ │ └── commands/
│ │ ├── check-mode.md
│ │ └── switch-mode.md
│ │
│ ├── scripts/
│ │ ├── init.sh # 初始化脚本
│ │ ├── install-hooks.sh # 安装 Git Hooks
│ │ ├── switch-mode.sh # 模式切换
│ │ ├── status.sh # 状态检查
│ │ ├── sync-all.sh # 同步所有仓库
│ │ ├── check-dependencies.py # 依赖检查
│ │ ├── emergency-rollback.sh # 紧急回滚
│ │ ├── clean-all.sh # 清理工具
│ │ └── git-hooks/
│ │ └── pre-commit # Git Hook 模板
│ │
│ ├── docs/
│ │ ├── index.json # 文档索引
│ │ ├── context-guide.md # 上下文指南
│ │ ├── architecture.md # 架构文档
│ │ └── workflows.md # 工作流程
│ │
│ ├── .claudeignore # Claude 忽略规则
│ ├── .env.template # 环境变量模板
│ └── repos.conf # 仓库配置
│
├── frontend/ # 前端仓库
│ ├── .git/
│ ├── .repo-config.json
│ ├── src/
│ ├── package.json
│ └── .env.local
│
├── backend/ # 后端仓库
│ ├── .git/
│ ├── .repo-config.json
│ ├── src/
│ ├── requirements.txt
│ └── .env
│
├── ai-service/ # AI 服务仓库
│ ├── .git/
│ ├── .repo-config.json
│ ├── src/
│ ├── requirements.txt
│ └── .env
│
├── shared-contracts/ # 共享契约(可选独立仓库)
│ ├── .git/
│ ├── api-specs/
│ │ ├── backend-api.yaml
│ │ └── ai-service-api.yaml
│ ├── data-models/
│ │ ├── user.json
│ │ └── product.json
│ ├── events/
│ └── changelog/
│
└── docker-compose.yml # 本地开发环境
附录 B:常用命令速查表
bash
# === 初始化 ===
.workspace/scripts/init.sh
# === 状态检查 ===
.workspace/scripts/status.sh
.workspace/scripts/check-dependencies.py
# === 模式管理 ===
.workspace/scripts/switch-mode.sh frontend-dev
.workspace/scripts/switch-mode.sh backend-dev
.workspace/scripts/switch-mode.sh fullstack
.workspace/scripts/switch-mode.sh readonly
# === 同步操作 ===
.workspace/scripts/sync-all.sh status
.workspace/scripts/sync-all.sh pull
.workspace/scripts/sync-all.sh fetch
# === 分支管理 ===
.workspace/scripts/switch-branch-all.sh feature/new-feature
# === 清理 ===
.workspace/scripts/clean-all.sh
# === 紧急回滚 ===
.workspace/scripts/emergency-rollback.sh
# === Docker ===
docker-compose up -d
docker-compose logs -f [service]
docker-compose down
附录 C:Claude 自定义命令示例
检查跨仓库一致性(.claude/commands/check-consistency.md)
markdown
---
name: check-consistency
description: 检查跨仓库的API和数据模型一致性
---
请执行以下步骤:
1. 读取 `shared-contracts/api-specs/` 中的所有 API 规范
2. 检查 `backend/src/api/` 中的实现是否匹配规范
3. 检查 `frontend/src/api/` 中的调用是否匹配规范
4. 检查数据模型定义(TypeScript vs Python)是否一致
输出格式:
✅ 一致的接口:
- GET /api/users
- POST /api/auth/login
⚠️ 不一致的接口:
- GET /api/products • 契约定义:返回 { products: Product[] } • 后端实现:返回 { data: Product[] } • 建议:统一为契约定义