四哥还会聊AI

80后突围:当程序员不再是第一个梦想,AI成了第四个梦想

第8篇-重构噩梦-做好上下文管理才是vibe-coding的关键

重构噩梦:做好上下文管理才是vibe coding的关键

🎯 AI编程的终极痛点:为什么你的代码总是在"重构-崩溃"循环?

在AI编程中,最痛苦的莫过于"重构噩梦":本来只是想加一个小功能,结果牵一发而动全身,整个项目陷入无尽的修复循环。

问题的根源在于:上下文管理的缺失。AI没有记忆,更没有全局观,每次修改都是"盲人摸象",缺乏对项目整体结构的理解。

在希语低喃心绪笔记开发中,我总结出一套"上下文即架构"的方法论,让AI从"健忘的天才"变成"有全局观的专家"。

🧠 AI的健忘症:为什么AI总是忘记之前的设计?

1. 上下文窗口的物理限制

AI的记忆机制:

人类开发:长期记忆 + 短期记忆 + 全局架构理解
AI开发:   只有当前会话的短期记忆

AI的健忘表现:

  • 生成A文件时,设计了完美的接口
  • 生成B文件时,完全忘记了A的存在
  • 生成C文件时,又重新设计了一套不兼容的接口
  • 结果:三个文件,三套标准,互相冲突

真实案例:

// AI第一次生成的用户接口(file: types/user.ts)
interface UserData {
  id: number
  username: string
  email: string
  created_at: string
}

// AI第二次生成的消息接口(file: types/message.ts)
interface Message {
  id: string              // 注意:用了string而不是number
  userId: string          // 注意:用了userId而不是user_id
  content: string
  createTime: Date        // 注意:用了createTime而不是created_at
}

// AI第三次生成的评论接口(file: types/comment.ts)
interface Comment {
  id: number              // 又变回了number
  user_id: number         // 用了user_id而不是userId
  message_id: number      // 用了message_id而不是messageId
  content: string
  postedAt: string        // 又用了新的时间字段名
}

结果:

  • ID类型不统一(number vs string)
  • 字段命名不一致(created_at vs createTime vs postedAt)
  • 关联字段命名混乱(userId vs user_id)
  • 三个文件需要大量的适配和转换逻辑

2. 架构理解的全局性缺失

AI的局部最优陷阱:

AI的思考模式:
当前任务:实现用户登录功能
优化目标:让登录功能最完善

AI的设计决策:
- 需要密码强度验证 → 添加密码规则
- 需要防止暴力破解 → 添加登录失败计数
- 需要提升用户体验 → 添加记住密码功能
- 需要增强安全性 → 添加双因子认证

AI没考虑的:
- 这是一个小程序,用户只有10个
- 双因子认证对用户来说是负担
- 记住密码功能在小程序里不适用
- 这些功能增加了开发和维护成本

缺乏全局观的代价:

  • 过度设计:简单功能复杂化
  • 技术债务:不必要的功能和代码
  • 维护成本:需要维护用不上的功能
  • 用户体验:功能太多反而难用

3. 重构的连锁反应

重构噩梦的典型场景:

Day 1: AI生成了用户系统
Day 2: AI生成了消息系统(用了不同的ID类型)
Day 3: AI生成了评论系统(用了第三种ID类型)
Day 4: 你发现需要关联查询 → 类型不匹配
Day 5: 你开始修复类型问题 → 牵一发而动全身
Day 6: 修复了一个问题,引出了三个新问题
Day 7: 项目变成技术债务的重灾区

连锁反应的原因:

  • 缺乏统一的数据模型
  • 没有一致的编码规范
  • 缺少全局的架构约束
  • AI无法理解修改的连锁影响

🏗️ 上下文管理:给AI装上"记忆芯片"

1. 项目级上下文框架

解决方案:在项目根目录创建"上下文锚点"

# CLAUDE.md - AI的"记忆芯片"

## 项目全局上下文(不可更改)

### 核心信息
- 项目名称:希语低喃心绪笔记(智能情绪助手)
- 目标用户:焦虑和失眠患者
- 平台:微信小程序 + H5
- 用户规模:预计100-1000人
- 技术原则:KISS + Let it Crash

### 强制数据模型(全局统一)
```typescript
// 所有实体必须遵循的基础数据模型
interface BaseEntity {
  id: string              // 统一使用string类型的UUID
  createdAt: Date         // 统一使用createdAt
  updatedAt: Date         // 统一使用updatedAt
}

// 用户相关字段的命名规范
interface UserNaming {
  userId: string          // 统一使用userId(驼峰命名)
  sessionId: string       // 统一使用sessionId
  userName: string        // 统一使用userName
  userRole: string        // 统一使用userRole
}

// 时间相关字段的命名规范
interface TimeNaming {
  createdAt: Date         // 创建时间
  updatedAt: Date         // 更新时间
  deletedAt?: Date        // 软删除时间
  expiresAt?: Date        // 过期时间
  lastActiveAt?: Date     // 最后活跃时间
}

强制技术栈(锁死,不可更改)

  • 前端:Taro 4.1.7 + React 18 + TypeScript 5.4.5
  • 后端:Node.js 18 + Fastify + TypeScript
  • 数据库:PostgreSQL 14 + Prisma ORM
  • 状态管理:React Context + useReducer
  • 样式:SCSS + CSS变量
  • 禁止使用:任何UI组件库、工具库、验证库

强制文件结构(不可违背)

frontend/tidepool/src/
├── context/           # 全局状态,每个文件不超过200行
├── pages/            # 页面组件,每个文件不超过300行
├── components/       # 通用组件,每个文件不超过200行
├── services/         # API服务,每个文件不超过300行
└── types/           # 类型定义,每个文件不超过150行

**效果:AI每次生成代码前,都会先读取这个"记忆芯片",确保与项目整体保持一致**

### 2. 模块级上下文模板

**创建模块上下文模板:**
```typescript
// templates/context-template.ts
// 每个新模块开发前的上下文初始化脚本

interface ModuleContext {
  moduleName: string
  moduleDependencies: string[]
  dataModels: Record<string, any>
  apiEndpoints: Record<string, any>
  businessRules: string[]
}

export function createContext(moduleName: string): ModuleContext {
  return {
    moduleName,
    moduleDependencies: ['基础依赖:Prisma, Winston, TypeScript'],
    dataModels: {
      // 强制使用统一的基础模型
      [`${moduleName}Base`]: {
        id: 'string: UUID',
        createdAt: 'Date',
        updatedAt: 'Date',
        deletedAt: 'Date?: nullable'
      }
    },
    apiEndpoints: {
      // 强制使用RESTful命名规范
      [`create${capitalize(moduleName)}`]: 'POST',
      [`get${capitalize(moduleName)}ById`]: 'GET /:id',
      [`update${capitalize(moduleName)}`]: 'PUT /:id',
      [`delete${capitalize(moduleName)}`]: 'DELETE /:id'
    },
    businessRules: [
      '1. 错误处理:logger.exception + throw',
      '2. 输入验证:简单的if判断',
      '3. 函数长度:不超过50行',
      '4. 类长度:不超过300行',
      '5. 禁止使用any类型'
    ]
  }
}

// 使用示例
const commentContext = createContext('comment')
console.log(commentContext.dataModels.commentBase)
// 输出:
// {
//   id: 'string: UUID',
//   createdAt: 'Date',
//   updatedAt: 'Date',
//   deletedAt: 'Date?: nullable'
// }

3. 代码生成的上下文约束

为AI提供上下文感知的生成模板:

// 上下文感知的服务生成模板
export function generateServiceCode(
  serviceName: string,
  projectContext: ProjectContext
): string {
  return `
// ${serviceName} Service - 基于项目全局上下文生成
import { ${projectContext.baseTypes} } from '../types/base'
import { logger } from '../utils/logger'

// 强制使用项目统一的错误处理模式
export class ${capitalize(serviceName)}Service {
  constructor(
    private ${serviceName}Repository: ${capitalize(serviceName)}Repository,
    private logger: Logger
  ) {}

  // 强制使用项目统一的创建模式
  async create(data: Create${capitalize(serviceName)}Input): Promise<${capitalize(serviceName)}> {
    try {
      const result = await this.${serviceName}Repository.create({
        ...data,
        id: generateUUID(),           // 使用项目统一的ID生成策略
        createdAt: new Date(),         // 使用项目统一的时间命名
        updatedAt: new Date()
      })
      this.logger.info(\`${serviceName} created: \${result.id}\`)
      return result
    } catch (error) {
      this.logger.exception('Failed to create ${serviceName}', error)
      throw error
    }
  }

  // 强制使用项目统一的查询模式
  async findById(id: string): Promise<${capitalize(serviceName)} | null> {
    return await this.${serviceName}Repository.findById(id)
  }

  // 其他方法遵循相同的模式...
}
`
}

// 使用这个模板生成的新服务,自动符合项目规范
const userServiceCode = generateServiceCode('user', projectContext)
const messageServiceCode = generateServiceCode('message', projectContext)
const commentServiceCode = generateServiceCode('comment', projectContext)

🎪 实战案例:用上下文管理驯服AI

案例1:数据模型的统一化改造

问题:AI生成的数据模型不一致

// AI生成的混乱数据模型
interface User {
  id: number           // 数字ID
  username: string
  email: string
  created_at: string   // 下划线命名
  lastLogin: Date      // 驼峰命名
}

interface Message {
  id: string           // 字符串ID
  userId: number       // 外键类型不一致
  content: string
  createTime: Date     // 不同的时间字段名
}

interface Comment {
  id: string           // 字符串ID
  user_id: string      // 下划线命名 + 字符串类型
  message_id: string   // 下划线命名
  text: string         // 不同的字段名
  posted_at: string    // 不同的时间字段名
}

解决方案:建立统一的上下文模型

# CLAUDE.md 中的数据模型统一约束

## 强制数据模型规范(不可违背)

### 基础实体模型(所有实体必须继承)
```typescript
interface BaseEntity {
  id: string              // 强制:UUID字符串
  createdAt: Date         // 强制:创建时间
  updatedAt: Date         // 强制:更新时间
  deletedAt?: Date        // 可选:软删除时间
}

关联字段命名规范

interface RelationFields {
  userId: string          // 用户外键,统一命名
  sessionId: string       // 会话外键,统一命名
  messageId: string       // 消息外键,统一命名
  commentId: string       // 评论外键,统一命名
}

内容字段命名规范

interface ContentFields {
  title?: string          // 标题字段
  content: string         // 内容字段,统一命名
  summary?: string        // 摘要字段
  tags?: string[]         // 标签字段
}

**上下文约束后的AI生成:**
```typescript
// AI基于统一上下文生成的一致模型
interface User extends BaseEntity {
  userName: string        // 统一使用userName
  email: string
  lastActiveAt?: Date     // 统一使用lastActiveAt
}

interface Message extends BaseEntity {
  userId: string          // 统一外键命名和类型
  content: string         // 统一内容字段命名
  sessionId: string       // 统一会话关联
}

interface Comment extends BaseEntity {
  userId: string          // 统一外键命名和类型
  messageId: string       // 统一外键命名和类型
  content: string         // 统一内容字段命名
}

对比效果:

  • 字段命名一致性:100%
  • 类型安全性:显著提升
  • 关联查询简单:不再需要类型转换
  • 维护成本:降低80%

案例2:API接口的标准化

问题:AI生成的API接口混乱

// AI生成的混乱API接口
// 用户API
POST /api/users           // 创建用户
GET /api/user/:id         // 获取单个用户(注意是单数)
PUT /api/users/:id        // 更新用户
DELETE /api/user/:id      // 删除用户(又是单数)

// 消息API
POST /api/message         // 创建消息(单数)
GET /api/messages/:id     // 获取消息(复数)
PATCH /api/message/:id    // 更新消息(用了PATCH而不是PUT)
DELETE /api/messages/:id  // 删除消息(复数)

// 评论API
POST /api/comments/create     // 创建评论(多了一层/create)
GET /api/comment/:id          // 获取评论(单数)
UPDATE /api/comment/:id       // 更新评论(用了UPDATE而不是PUT)
REMOVE /api/comment/:id       // 删除评论(用了REMOVE而不是DELETE)

解决方案:建立API接口上下文规范

# CLAUDE.md 中的API接口规范

## 强制API接口规范(RESTful标准)

### 资源命名规范
- 使用复数形式:/api/users, /api/messages, /api/comments
- 统一的资源层级:/api/{resource}/{id}

### HTTP方法规范
- POST   /api/{resource}           # 创建资源
- GET    /api/{resource}           # 获取资源列表
- GET    /api/{resource}/{id}      # 获取单个资源
- PUT    /api/{resource}/{id}      # 更新资源
- DELETE /api/{resource}/{id}      # 删除资源

### 禁止的接口模式
❌ POST /api/{resource}/create
❌ GET /api/{resource singular}
❌ PATCH /api/{resource}/{id}
❌ 自定义HTTP方法

上下文约束后的API接口:

// AI基于统一上下文生成的一致API接口
// 用户API(标准化)
POST /api/users           // 创建用户
GET /api/users           // 获取用户列表
GET /api/users/:id       // 获取单个用户
PUT /api/users/:id       // 更新用户
DELETE /api/users/:id    // 删除用户

// 消息API(标准化)
POST /api/messages       // 创建消息
GET /api/messages        // 获取消息列表
GET /api/messages/:id    // 获取单个消息
PUT /api/messages/:id    // 更新消息
DELETE /api/messages/:id // 删除消息

// 评论API(标准化)
POST /api/comments       // 创建评论
GET /api/comments        // 获取评论列表
GET /api/comments/:id    // 获取单个评论
PUT /api/comments/:id    // 更新评论
DELETE /api/comments/:id // 删除评论

对比效果:

  • 接口一致性:100%
  • 学习成本:降低90%
  • 开发效率:提升60%
  • 错误率:降低80%

案例3:错误处理的统一化

问题:AI生成的错误处理五花八门

// AI生成的混乱错误处理
// 方式1:返回null
async getUserById(id: string): Promise<User | null> {
  try {
    return await userRepository.findById(id)
  } catch (error) {
    return null  // 静默失败
  }
}

// 方式2:返回错误对象
async createMessage(data: MessageData): Promise<{success: boolean, error?: string}> {
  try {
    const message = await messageRepository.create(data)
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
}

// 方式3:抛出错误但没有日志
async deleteComment(id: string): Promise<void> {
  const comment = await commentRepository.findById(id)
  if (!comment) {
    throw new Error('Comment not found')  // 没有日志
  }
  await commentRepository.delete(id)
}

// 方式4:复杂的错误分类
class UserService {
  async handleError(error: Error, context: string): Promise<never> {
    if (error instanceof ValidationError) {
      throw new BadRequestError(error.message)
    } else if (error instanceof DatabaseError) {
      throw new InternalServerError('Database operation failed')
    } else if (error instanceof NetworkError) {
      throw new ServiceUnavailableError('External service unavailable')
    }
    throw new UnknownError('An unexpected error occurred')
  }
}

解决方案:建立错误处理上下文规范

# CLAUDE.md 中的错误处理规范

## 强制错误处理规范(Let it Crash原则)

### 统一错误处理模式
```typescript
// 标准错误处理模板(所有服务必须遵循)
async methodName(params: ParamType): Promise<ReturnType> {
  try {
    const result = await repository.operation(params)
    this.logger.info(`Operation completed: ${result.id}`)
    return result
  } catch (error) {
    this.logger.exception('Operation failed', error)
    throw new Error(`Operation failed: ${error.message}`)
  }
}

错误处理要求

✅ 必须使用 logger.exception 记录错误
✅ 必须抛出错误,不能返回null或错误对象
✅ 必须提供清晰的错误信息
✅ 错误信息要包含操作上下文

禁止的错误处理模式

❌ 返回null表示失败
❌ 返回 {success: boolean, error?: string} 格式
❌ 静默忽略错误
❌ 复杂的错误分类系统
❌ 不记录日志的抛出错误


**上下文约束后的统一错误处理:**
```typescript
// AI基于统一上下文生成的一致错误处理
export class UserService {
  async create(userData: CreateUserInput): Promise<User> {
    try {
      const user = await this.userRepository.create(userData)
      this.logger.info(`User created: ${user.id}`)
      return user
    } catch (error) {
      this.logger.exception('Failed to create user', error)
      throw new Error(`User creation failed: ${error.message}`)
    }
  }

  async findById(id: string): Promise<User> {
    try {
      const user = await this.userRepository.findById(id)
      if (!user) {
        throw new Error(`User not found: ${id}`)
      }
      return user
    } catch (error) {
      this.logger.exception('Failed to find user', error)
      throw error
    }
  }
}

export class MessageService {
  async create(messageData: CreateMessageInput): Promise<Message> {
    try {
      const message = await this.messageRepository.create(messageData)
      this.logger.info(`Message created: ${message.id}`)
      return message
    } catch (error) {
      this.logger.exception('Failed to create message', error)
      throw new Error(`Message creation failed: ${error.message}`)
    }
  }

  async findByUserId(userId: string): Promise<Message[]> {
    try {
      return await this.messageRepository.findByUserId(userId)
    } catch (error) {
      this.logger.exception('Failed to find messages by user', error)
      throw error
    }
  }
}

对比效果:

  • 错误处理一致性:100%
  • 调试效率:提升90%
  • 代码可读性:显著提升
  • 维护成本:降低70%

🔧 上下文管理的自动化工具

1. 上下文检查器

创建自动化上下文检查脚本:

// scripts/context-checker.ts
import fs from 'fs'
import path from 'path'

interface ContextRule {
  name: string
  check: (filePath: string, content: string) => boolean
  message: string
  category: 'data-model' | 'api-interface' | 'error-handling' | 'naming'
}

const contextRules: ContextRule[] = [
  // 数据模型一致性检查
  {
    name: 'base-entity-inheritance',
    check: (filePath, content) => {
      if (filePath.includes('types/') && content.includes('interface ')) {
        return content.includes('id: string') &&
               content.includes('createdAt: Date') &&
               content.includes('updatedAt: Date')
      }
      return true
    },
    message: 'Entity must inherit base entity structure (id: string, createdAt: Date, updatedAt: Date)',
    category: 'data-model'
  },

  // 命名一致性检查
  {
    name: 'field-naming-consistency',
    check: (filePath, content) => {
      // 检查是否混用驼峰命名和下划线命名
      const camelCaseFields = content.match(/\w*[a-z][A-Z]\w*/g) || []
      const snakeCaseFields = content.match(/\w*_\w*/g) || []

      // 如果同时存在两种命名方式,则报错
      return !(camelCaseFields.length > 0 && snakeCaseFields.length > 0)
    },
    message: 'Mixed naming conventions detected. Use either camelCase or snake_case consistently',
    category: 'naming'
  },

  // 错误处理一致性检查
  {
    name: 'error-handling-consistency',
    check: (filePath, content) => {
      if (filePath.includes('service') && content.includes('catch')) {
        return content.includes('logger.exception') && content.includes('throw')
      }
      return true
    },
    message: 'Service must use logger.exception + throw for error handling',
    category: 'error-handling'
  },

  // API接口一致性检查
  {
    name: 'api-interface-consistency',
    check: (filePath, content) => {
      if (filePath.includes('routes')) {
        // 检查是否使用了标准的RESTful接口
        const hasStandardMethods = content.includes('POST') ||
                                  content.includes('GET') ||
                                  content.includes('PUT') ||
                                  content.includes('DELETE')
        const hasNonStandardMethods = content.includes('PATCH') ||
                                     content.includes('UPDATE') ||
                                     content.includes('REMOVE')
        return hasStandardMethods && !hasNonStandardMethods
      }
      return true
    },
    message: 'Use standard RESTful methods (GET, POST, PUT, DELETE) only',
    category: 'api-interface'
  }
]

function checkContextConsistency() {
  const srcDir = './src'
  const files = getAllTypeScriptFiles(srcDir)
  const violations: Array<{file: string, rule: string, message: string, category: string}> = []

  files.forEach(file => {
    const content = fs.readFileSync(file, 'utf8')

    contextRules.forEach(rule => {
      if (!rule.check(file, content)) {
        violations.push({
          file: path.relative(process.cwd(), file),
          rule: rule.name,
          message: rule.message,
          category: rule.category
        })
      }
    })
  })

  if (violations.length > 0) {
    console.log('❌ Context Consistency Check Failed!')
    console.log('Violations by category:')

    // 按类别分组显示
    const byCategory = violations.reduce((acc, v) => {
      if (!acc[v.category]) acc[v.category] = []
      acc[v.category].push(v)
      return acc
    }, {} as Record<string, typeof violations>)

    Object.entries(byCategory).forEach(([category, items]) => {
      console.log(`\n🔍 ${category.toUpperCase()}:`)
      items.forEach(item => {
        console.log(`   ❌ ${item.file}: ${item.message}`)
      })
    })

    process.exit(1)
  } else {
    console.log('✅ Context Consistency Check Passed!')
  }
}

checkContextConsistency()

2. 上下文生成器

自动化上下文文件生成:

// scripts/context-generator.ts
import fs from 'fs'
import path from 'path'

interface ProjectContext {
  dataModels: Record<string, any>
  apiEndpoints: Record<string, any>
  errorHandling: string[]
  namingConventions: Record<string, string>
}

function generateProjectContext(): ProjectContext {
  // 扫描项目文件,生成上下文信息
  const typesDir = './src/types'
  const servicesDir = './src/services'
  const routesDir = './src/routes'

  const dataModels = extractDataModels(typesDir)
  const apiEndpoints = extractApiEndpoints(routesDir)
  const errorHandling = extractErrorHandlingPatterns(servicesDir)
  const namingConventions = extractNamingConventions(typesDir)

  return {
    dataModels,
    apiEndpoints,
    errorHandling,
    namingConventions
  }
}

function updateClaudeMdWithContext(context: ProjectContext) {
  const claudeMdPath = './CLAUDE.md'
  let content = fs.readFileSync(claudeMdPath, 'utf8')

  // 更新数据模型部分
  const dataModelSection = generateDataModelSection(context.dataModels)
  content = updateSection(content, '## 强制数据模型规范', dataModelSection)

  // 更新API接口部分
  const apiSection = generateApiSection(context.apiEndpoints)
  content = updateSection(content, '## 强制API接口规范', apiSection)

  // 更新错误处理部分
  const errorSection = generateErrorSection(context.errorHandling)
  content = updateSection(content, '## 强制错误处理规范', errorSection)

  fs.writeFileSync(claudeMdPath, content)
  console.log('✅ Project context updated in CLAUDE.md')
}

// 定期执行上下文同步
function syncContext() {
  const context = generateProjectContext()
  updateClaudeMdWithContext(context)

  // 验证上下文一致性
  const { execSync } = require('child_process')
  execSync('npm run context-check', { stdio: 'inherit' })
}

// 每次代码提交前自动执行
syncContext()

3. AI上下文注入器

在AI生成代码前自动注入上下文:

// scripts/context-injector.ts
interface ContextInjection {
  projectContext: string
  moduleContext: string
  bestPractices: string
}

function prepareContextForAI(moduleName: string): ContextInjection {
  const projectContext = readProjectContext()
  const moduleContext = generateModuleContext(moduleName)
  const bestPractices = extractBestPractices()

  return {
    projectContext: formatContextForAI(projectContext),
    moduleContext: formatContextForAI(moduleContext),
    bestPractices: formatContextForAI(bestPractices)
  }
}

function enhanceAIQueryWithContext(query: string, context: ContextInjection): string {
  return `
请基于以下项目上下文完成开发任务:

## 项目全局上下文
${context.projectContext}

## 当前模块上下文
${context.moduleContext}

## 最佳实践约束
${context.bestPractices}

## 开发任务
${query}

## 重要约束
- 严格遵循项目全局规范
- 不得违反已有的一致性原则
- 如有冲突,优先保持项目一致性
- 生成代码后自动执行上下文一致性检查
`
}

// 使用示例:增强AI查询
const context = prepareContextForAI('notification')
const enhancedQuery = enhanceAIQueryWithContext(
  '实现一个通知系统,支持创建通知和获取用户通知列表',
  context
)

// 将enhancedQuery发送给AI,确保生成符合项目规范的代码

🌟 总结:上下文管理即架构的核心原则

上下文管理的三个层次

1. 项目级上下文(全局记忆)

  • 统一的数据模型规范
  • 标准化的API接口格式
  • 一致的错误处理模式
  • 统一的命名约定

2. 模块级上下文(局部记忆)

  • 模块间的依赖关系
  • 模块内的设计模式
  • 模块的业务规则约束
  • 模块的扩展边界

3. 代码级上下文(即时记忆)

  • 函数的设计模式
  • 变量的命名规范
  • 注释的格式要求
  • 测试的编写标准

上下文管理的实施步骤

第一步:建立上下文锚点

  • 创建详细的CLAUDE.md文档
  • 定义全局的数据模型和接口规范
  • 建立统一的命名和编码标准
  • 设置强制性的约束规则

第二步:实现上下文同步

  • 创建自动化上下文检查脚本
  • 建立代码生成的上下文注入机制
  • 设置持续的一致性验证
  • 建立上下文更新的触发机制

第三步:培养上下文思维

  • 每次开发前先检查现有上下文
  • 新功能必须符合现有规范
  • 定期回顾和优化上下文规范
  • 建立团队共享的上下文认知

关键成功要素

1. 上下文的完整性

  • 覆盖项目的所有关键方面
  • 提供具体的实现示例
  • 包含正面和负面案例
  • 定期更新过时的规范

2. 工具的自动化

  • 减少人工检查的负担
  • 集成到开发工作流程中
  • 提供即时的上下文反馈
  • 自动同步项目变更

3. 约束的强制性

  • 上下文规范必须强制执行
  • 违反规范的代码不能合并
  • 定期检查规范的遵守情况
  • 建立违反规范的纠正机制

记住这些金句

关于AI的本质:

  • "AI没有记忆,但我们可以给它记忆"
  • "AI的健忘症需要我们的上下文管理来治愈"
  • "AI看到的是局部,我们需要给它全局"

关于上下文管理:

  • "上下文即架构,一致性即质量"
  • "好的上下文管理让AI从盲人摸象到全局在胸"
  • "上下文不是约束,而是AI编程的导航系统"

关于实践原则:

  • "先建上下文,再让AI编码"
  • "上下文越清晰,AI生成越一致"
  • "上下文检查要自动化,不能靠人工"

最终记住:vibe coding的关键不是让AI更聪明,而是让AI更有记忆。好的上下文管理就是给AI装上一个永不遗忘的"记忆芯片"。


下一篇预告: 《认知负荷革命:AI编程中如何管理自己的思考复杂度》


微信搜索"四哥还会聊AI",看这些上下文管理技巧如何在实际项目中终结重构噩梦

微信搜索"汐屿笔记",看这些架构原则如何在实际项目中应用

← 返回首页