Skip to content

Instinct 智能感知

MyDeskBot 的 Instinct 功能通过深度学习您的编码模式和项目上下文,提供超前的智能预测和建议。

目录

什么是 Instinct

Instinct 是 MyDeskBot 的上下文感知引擎,它不仅理解您当前编辑的代码,还能:

  • 🧠 学习您的编码风格 - 模拟您的命名习惯、代码结构偏好
  • 🔍 理解项目架构 - 掌握整个项目的结构、模式和约定
  • 🎯 预测下一步操作 - 基于上下文预测您接下来要做什么
  • 📚 复用项目知识 - 从现有代码中学习并应用模式

核心能力

1. 模式学习

Instinct 会分析您的代码库,识别重复出现的模式:

识别的模式:

typescript
// 项目中重复的模式
class UserService {
  async findById(id: number): Promise<User | null> {}
  async findAll(): Promise<User[]> {}
  async create(data: CreateUserDto): Promise<User> {}
  async update(id: number, data: UpdateUserDto): Promise<User> {}
  async delete(id: number): Promise<void> {}
}

// Instinct 学到这个模式后,在创建新服务时会自动建议类似结构
class ProductService {
  // 自动建议完整的 CRUD 方法实现
  async findById(id: number): Promise<Product | null> {}
  // ...
}

2. 上下文预测

基于当前代码和项目结构预测您的下一步:

场景 1: 创建了 Controller

typescript
// 您创建了控制器
@Controller("users")
export class UsersController {
  @Get()
  findAll() {}
}

// Instinct 预测您需要:
// 1. Service 层 - 自动建议创建 UserService
// 2. DTO 类 - 自动建议 CreateUserDto, UpdateUserDto
// 3. Entity 类 - 自动建议 User 实体
// 4. Repository - 自动建议 UserRepository

场景 2: 编写测试

typescript
// 您编写了服务函数
export function calculateDiscount(price: number, quantity: number) {
  return quantity > 10 ? price * 0.9 : price;
}

// Instinct 预测并自动建议测试用例
describe("calculateDiscount", () => {
  it("should apply 10% discount for quantity > 10", () => {
    expect(calculateDiscount(100, 15)).toBe(90);
  });

  it("should not apply discount for quantity <= 10", () => {
    expect(calculateDiscount(100, 5)).toBe(100);
  });

  // 还会建议边界情况测试
  it("should handle edge cases", () => {
    expect(calculateDiscount(0, 11)).toBe(0);
    expect(calculateDiscount(100, 10)).toBe(100);
  });
});

3. 代码风格同步

Instinct 学习并应用您的编码风格:

学习命名习惯:

python
# 您的项目中偏好这种命名
class UserDatabaseConnection:
    def get_user_by_id(self, user_id: str) -> User:
        pass

# Instinct 会学习并应用到新代码
class ProductDatabaseConnection:
    def get_product_by_id(self, product_id: str) -> Product:
        pass

学习结构习惯:

java
// 您习惯这种异常处理结构
try {
    // 操作
} catch (SpecificException e) {
    log.error("Specific error", e);
    throw new BusinessException("Error message", e);
} catch (Exception e) {
    log.error("Unexpected error", e);
    throw new SystemException("Unexpected error", e);
}

// Instinct 会在新代码中应用相同模式

4. 智能导入

根据上下文自动建议正确的导入:

typescript
// 您使用了 User 类型
const user = new User();

// Instinct 自动建议导入
import { User } from "../entities/user.entity";

// 如果有多个同名类型,Instinct 会根据上下文选择正确的一个

工作原理

1. 索引阶段

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

mermaid
graph LR
    A[代码扫描] --> B[语法分析]
    B --> C[模式提取]
    C --> D[向量索引]
    D --> E[模型训练]

索引内容:

  • 文件结构和依赖关系
  • 类、函数、方法的定义和使用
  • 命名约定和风格模式
  • 常见代码模式
  • 测试模式

2. 推理阶段

当您编码时,Instinct 实时分析:

  1. 当前上下文: 光标位置、当前文件、最近编辑
  2. 项目上下文: 相关文件、依赖关系、历史模式
  3. 用户偏好: 命名风格、结构习惯、常用模式
  4. AI 推理: 综合分析生成建议

3. 学习阶段

Instinct 持续学习您的反馈:

  • ✅ 接受的建议 → 加权学习这种模式
  • ❌ 拒绝的建议 → 调整模型权重
  • 📝 您的修改 → 更新用户偏好模型

使用场景

场景 1: 自动生成配套文件

您创建了一个组件,Instinct 自动建议所有相关文件:

您创建: src/components/Button.tsx

Instinct 建议创建:
├── src/components/Button.test.tsx      ✅
├── src/components/Button.stories.tsx   ✅
├── src/components/Button.module.css     ✅
└── src/types/button.ts                 ✅

场景 2: 补全功能实现

您定义了接口,Instinct 建议完整实现:

go
// 您定义
type UserService interface {
    GetUser(id string) (*User, error)
    CreateUser(user *User) error
    UpdateUser(user *User) error
    DeleteUser(id string) error
}

// Instinct 自动建议实现
type userService struct {
    repo UserRepository
}

func (s *userService) GetUser(id string) (*User, error) {
    return s.repo.FindByID(id)
}

// ... 其他方法也会自动生成

场景 3: API 端点补全

创建 REST API 端点:

python
# 您开始编写
@app.route('/users', methods=['GET'])
def get_users():
    pass

# Instinct 建议完整实现
@app.route('/users', methods=['GET'])
def get_users():
    """获取用户列表"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)

    pagination = User.query.paginate(
        page=page,
        per_page=per_page,
        error_out=False
    )

    return jsonify({
        'items': [user.to_dict() for user in pagination.items],
        'total': pagination.total,
        'pages': pagination.pages,
        'current_page': page
    })

场景 4: 数据库迁移

修改数据库 Schema 后,Instinct 建议迁移:

sql
-- 您修改了用户表
ALTER TABLE users ADD COLUMN phone VARCHAR(20);

-- Instinct 自动建议:
-- 1. 迁移文件
-- 2. 数据回滚脚本
-- 3. 模型更新
-- 4. DTO 更新
-- 5. API 更新

场景 5: 错误处理模式

您习惯使用特定的错误处理模式:

rust
// 您的模式
pub fn process_data(data: &str) -> Result<Data, Error> {
    data.parse::<Data>()
        .map_err(|e| Error::ParseError(e.to_string()))
}

// Instinct 在其他地方应用相同模式
pub fn validate_config(config: &str) -> Result<Config, Error> {
    config.parse::<Config>()
        .map_err(|e| Error::ConfigError(e.to_string()))
}

个性化定制

1. 配置学习范围

json
{
  "mydeskbot": {
    "instinct": {
      "enabled": true,
      "learning": {
        "include_patterns": [
          "src/**/*.{ts,tsx,js,jsx}",
          "lib/**/*.{py,java,go}"
        ],
        "exclude_patterns": [
          "node_modules/**",
          "**/*.test.ts",
          "**/*.spec.ts",
          "dist/**"
        ],
        "max_files": 1000,
        "max_lines_per_file": 5000
      }
    }
  }
}

2. 风格偏好

json
{
  "mydeskbot": {
    "instinct": {
      "style_preferences": {
        "naming": {
          "variables": "camelCase",
          "functions": "camelCase",
          "classes": "PascalCase",
          "constants": "UPPER_SNAKE_CASE",
          "private_prefix": "_"
        },
        "formatting": {
          "indent_size": 2,
          "indent_style": "space",
          "max_line_length": 100,
          "quote_style": "single"
        },
        "patterns": {
          "error_handling": "result_type",
          "async_pattern": "async_await",
          "state_management": "context"
        }
      }
    }
  }
}

3. 自定义模式

定义您自己的代码模式:

yaml
# .mydeskbot/patterns.yml
patterns:
  - name: "nest-service"
    description: "NestJS Service CRUD pattern"
    template: |
      @Injectable()
      export class {{EntityName}}Service {
        constructor(
          @InjectRepository({{EntityName}})
          private repo: Repository<{{EntityName}}>,
        ) {}

        async findAll(): Promise<{{EntityName}}[]> {
          return this.repo.find();
        }

        async findOne(id: number): Promise<{{EntityName}}> {
          const entity = await this.repo.findOne({ where: { id } });
          if (!entity) {
            throw new NotFoundException('{{EntityName}} not found');
          }
          return entity;
        }

        async create(dto: Create{{EntityName}}Dto): Promise<{{EntityName}}> {
          return this.repo.save(dto);
        }

        async update(id: number, dto: Update{{EntityName}}Dto): Promise<{{EntityName}}> {
          const entity = await this.findOne(id);
          return this.repo.save({ ...entity, ...dto });
        }

        async remove(id: number): Promise<void> {
          await this.findOne(id);
          await this.repo.delete(id);
        }
      }

  - name: "react-component"
    description: "React component with TypeScript"
    template: |
      import React from 'react';

      interface {{ComponentName}}Props {
        // Props will be suggested
      }

      export const {{ComponentName}}: React.FC<{{ComponentName}}Props> = ({
        // Destructured props
      }) => {
        return (
          <div>
            {/* Component content */}
          </div>
        );
      };

      export default {{ComponentName}};

4. 反馈训练

提供反馈帮助 Instinct 改进:

lua
-- Neovim 配置
require('mydeskbot').setup({
  instinct = {
    feedback = {
      enabled = true,
      auto_learn = true,

      -- 正面反馈
      on_accept = function(suggestion)
        -- 记录接受的类型
        require('mydeskbot.instinct').record_feedback('accept', suggestion)
      end,

      -- 负面反馈
      on_reject = function(suggestion)
        -- 记录拒绝的类型
        require('mydeskbot.instinct').record_feedback('reject', suggestion)
      end,

      -- 修改反馈
      on_modify = function(original, modified)
        -- 学习您的修改
        require('mydeskbot.instinct').learn_modification(original, modified)
      end
    }
  }
})

高级功能

1. 跨项目学习

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

json
{
  "mydeskbot.instinct": {
    "cross_project_learning": true,
    "shared_projects": ["/path/to/project-a", "/path/to/project-b"],
    "learn_from": ["patterns", "style", "naming", "architecture"]
  }
}

2. 模式库管理

查看和管理学习到的模式:

bash
# 查看所有学习的模式
mydeskbot instinct list-patterns

# 导出模式
mydeskbot instinct export-patterns > my-patterns.yml

# 导入模式
mydeskbot instinct import-patterns my-patterns.yml

# 清除学习数据
mydeskbot instinct clear-cache

3. 实时监控

查看 Instinct 的实时活动:

bash
# 监控 Instinct 活动
mydeskbot instinct monitor

# 输出示例:
# [14:23:45] Indexed 450 files
# [14:23:46] Identified 23 patterns
# [14:23:48] Learned naming convention: camelCase
# [14:23:50] Suggestion generated for UserService
# [14:23:51] User accepted suggestion (confidence: 0.92)

性能优化

1. 增量索引

只索引修改的文件:

json
{
  "mydeskbot.instinct": {
    "indexing": {
      "mode": "incremental",
      "debounce": 5000, // 5秒后开始索引
      "batch_size": 50 // 每批处理50个文件
    }
  }
}

2. 智能缓存

json
{
  "mydeskbot.instinct": {
    "cache": {
      "enabled": true,
      "max_size_mb": 512,
      "ttl_hours": 24,
      "compression": true
    }
  }
}

3. 选择性激活

只在需要时激活 Instinct:

json
{
  "mydeskbot.instinct": {
    "activation": {
      "mode": "smart", // smart, always, manual
      "triggers": ["new_file", "file_save", "idle_5s"]
    }
  }
}

隐私和安全

数据处理

  • ✅ 所有索引数据在本地处理
  • ✅ 不发送源代码到云端
  • ✅ 可以随时清除学习数据
  • ✅ 支持企业级本地部署

数据控制

bash
# 清除所有学习数据
mydeskbot instinct clear-all

# 导出学习数据
mydeskbot instinct export --format json

# 禁用特定类型的学习
mydeskbot instinct disable --type naming

下一步