Skip to content

代码库感知

MyDeskBot 的代码库感知功能让 AI 助手深入理解您的整个项目,提供更精准的建议和更智能的帮助。

目录

什么是代码库感知

代码库感知是 MyDeskBot 的核心能力之一,它能够让 AI:

  • 🔍 理解项目结构 - 掌握整个项目的目录结构和模块组织
  • 🧠 学习代码模式 - 识别和应用项目中的编码模式和约定
  • 🔗 分析依赖关系 - 理解模块间的依赖和引用关系
  • 📚 阅读项目文档 - 利用项目文档理解业务逻辑
  • 🎯 上下文相关 - 基于整个代码库提供精准建议

代码库感知 vs 简单补全

特性简单补全代码库感知
上下文范围当前文件整个项目
模式学习深度学习
依赖分析全面分析
代码一致性
建议质量一般优秀

工作原理

1. 索引阶段

MyDeskBot 会在后台对您的代码库进行索引:

mermaid
graph TD
    A[文件扫描] --> B[语法分析]
    B --> C[符号提取]
    C --> D[依赖分析]
    D --> E[模式识别]
    E --> F[向量索引]
    F --> G[知识图谱]

索引内容

文件结构:

  • 目录层次
  • 文件类型分布
  • 模块组织方式

代码符号:

  • 类、函数、方法定义
  • 变量和常量声明
  • 接口和类型定义

依赖关系:

  • 导入/引用关系
  • 模块间依赖
  • 外部库依赖

代码模式:

  • 命名约定
  • 代码结构模式
  • 错误处理模式

配置文件:

  • package.json
  • tsconfig.json
  • pom.xml
  • requirements.txt
  • Dockerfile
  • CI/CD 配置

2. 查询阶段

当您使用 MyDeskBot 时,它会:

  1. 收集当前上下文 - 当前文件、光标位置、选中的代码
  2. 分析相关代码 - 查找相关的文件和模块
  3. 应用学习到的模式 - 使用项目中的模式生成建议
  4. 考虑依赖关系 - 确保建议与项目依赖兼容
  5. 生成智能建议 - 综合所有信息生成最佳建议

3. 学习阶段

MyDeskBot 会持续学习:

  • 接受的建议 - 加强这类模式
  • 拒绝的建议 - 调整权重
  • 📝 您的修改 - 学习您的编码风格

配置选项

索引范围配置

json
{
  "mydeskbot": {
    "codebase_awareness": {
      "enabled": true,
      "indexing": {
        "include_patterns": [
          "src/**/*.{ts,tsx,js,jsx}",
          "lib/**/*.{py,java,go}",
          "tests/**/*.{test.ts,spec.ts}"
        ],
        "exclude_patterns": [
          "node_modules/**",
          "dist/**",
          "build/**",
          "**/*.min.js",
          "**/vendor/**",
          ".git/**"
        ],
        "max_files": 5000,
        "max_file_size_mb": 2,
        "follow_symlinks": false
      }
    }
  }
}

深度配置

json
{
  "mydeskbot": {
    "codebase_awareness": {
      "depth": {
        "dependency_analysis": true,
        "pattern_learning": true,
        "documentation_reading": true,
        "cross_file_reference": true
      },
      "context": {
        "max_related_files": 10,
        "max_context_tokens": 8000,
        "include_imported_modules": true,
        "include_exported_symbols": true
      }
    }
  }
}

性能配置

json
{
  "mydeskbot": {
    "codebase_awareness": {
      "performance": {
        "index_on_startup": false,
        "incremental_indexing": true,
        "debounce_ms": 5000,
        "max_indexing_threads": 4,
        "cache_enabled": true,
        "cache_ttl_hours": 24
      }
    }
  }
}

最佳实践

1. 合理配置索引范围

不要索引不必要的文件:

json
{
  "include_patterns": [
    // 只包含源代码
    "src/**/*.{ts,tsx,js,jsx}",
    "lib/**/*.{py,java}"
  ],
  "exclude_patterns": [
    // 排除构建产物和第三方库
    "node_modules/**",
    "dist/**",
    "build/**",
    "*.min.js",
    "vendor/**"
  ]
}

2. 定期更新索引

当项目结构变化时,更新索引:

bash
# 手动触发索引更新
mydeskbot index --rebuild

# 清除缓存并重建
mydeskbot index --clean --rebuild

3. 使用项目文档

将项目文档放在容易被发现的位置:

project/
├── docs/
│   ├── README.md
│   ├── API.md
│   ├── ARCHITECTURE.md
│   └── CONTRIBUTING.md
├── src/
└── package.json

4. 保持一致的代码风格

一致的代码风格能提高建议质量:

typescript
// 项目统一的错误处理模式
function fetchData(url: string): Promise<Data> {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  } catch (error) {
    console.error("Failed to fetch data:", error);
    throw error;
  }
}

5. 提供清晰的命名

清晰的命名帮助 AI 理解意图:

typescript
// ❌ 模糊的命名
const d = await getData();
const p = processData(d);

// ✅ 清晰的命名
const user = await fetchUser(userId);
const processedUser = normalizeUserData(user);

高级功能

1. 自定义模式

定义项目特定的代码模式:

yaml
# .mydeskbot/patterns.yml
patterns:
  - name: "error-handling"
    language: "typescript"
    pattern: |
      try {
        // operation
      } catch (error) {
        console.error('Failed to ...:', error);
        throw error;
      }
    description: "Standard error handling pattern"

  - name: "controller-route"
    language: "typescript"
    framework: "express"
    pattern: |
      router.get('/path', async (req, res) => {
        try {
          // implementation
          res.json(result);
        } catch (error) {
          res.status(500).json({ error: error.message });
        }
      });

2. 上下文提示

提供额外的上下文信息:

typescript
/**
 * @context 用户认证模块
 * @dependency UserRepository
 * @pattern 采用 JWT 认证
 */
async function authenticateUser(credentials: Credentials): Promise<User> {
  // MyDeskBot 会理解这些注释
}

3. 项目知识库

创建项目知识库文件:

markdown
# project-knowledge.md

## 项目架构

本项目采用分层架构:

- Controller 层:处理 HTTP 请求
- Service 层:业务逻辑
- Repository 层:数据访问

## 命名约定

- 文件名:kebab-case
- 类名:PascalCase
- 函数名:camelCase
- 常量:UPPER_SNAKE_CASE

## 代码模式

所有 API 响应统一格式:

```typescript
interface ApiResponse<T> {
  success: boolean;
  data?: T;
  error?: string;
}
```

### 4. 跨项目学习

在多个相关项目间共享学习:

```json
{
  "mydeskbot": {
    "codebase_awareness": {
      "cross_project": {
        "enabled": true,
        "shared_projects": [
          "../project-a",
          "../project-b"
        ],
        "share_patterns": true,
        "share_style": true
      }
    }
  }
}

监控和调试

查看索引状态

bash
# 查看索引统计
mydeskbot index --stats

# 输出示例
# Total files: 1,234
# Indexed files: 1,200
# Failed: 5
# Total symbols: 8,456
# Patterns learned: 23

调试索引问题

bash
# 详细日志
mydeskbot index --verbose

# 检查特定文件
mydeskbot index --check-file src/services/UserService.ts

# 导出索引信息
mydeskbot index --export index-info.json

性能监控

javascript
// 在代码中监控代码库感知性能
const start = Date.now();
const suggestions = await mydeskbot.getSuggestions();
const duration = Date.now() - start;
console.log(`Suggestions generated in ${duration}ms`);

故障排除

问题 1: 索引速度慢

解决方案:

json
{
  "indexing": {
    "max_files": 1000, // 减少索引文件数
    "max_file_size_mb": 1, // 减小文件大小限制
    "incremental_indexing": true // 使用增量索引
  }
}

问题 2: 建议不准确

解决方案:

  1. 确保代码风格一致
  2. 提供清晰的命名和注释
  3. 定期更新索引
  4. 检查排除模式是否正确

问题 3: 内存占用高

解决方案:

json
{
  "performance": {
    "cache_enabled": true,
    "cache_size_mb": 256,
    "lazy_loading": true
  }
}

下一步