Skip to content

6. 记忆系统

6.1 持久化记忆

typescript
interface Memory {
  id: string;
  title: string;
  content: string;
  createdAt: Date;
  updatedAt: Date;
  tags: string[];
}

class MemoryStore {
  private storePath: string;
  private memories: Memory[] = [];
  
  constructor() {
    this.storePath = path.join(os.homedir(), '.claude-code', 'memories.json');
    this.load();
  }
  
  async create(title: string, content: string): Promise<string> {
    const memory: Memory = {
      id: crypto.randomUUID(),
      title,
      content,
      createdAt: new Date(),
      updatedAt: new Date(),
      tags: this.extractTags(content)
    };
    
    this.memories.push(memory);
    await this.save();
    
    return memory.id;
  }
  
  async update(id: string, content: string) {
    const memory = this.memories.find(m => m.id === id);
    if (memory) {
      memory.content = content;
      memory.updatedAt = new Date();
      memory.tags = this.extractTags(content);
      await this.save();
    }
  }
  
  async delete(id: string) {
    this.memories = this.memories.filter(m => m.id !== id);
    await this.save();
  }
  
  // 相关记忆检索
  async retrieve(query: string, limit: number = 5): Promise<Memory[]> {
    // 简单的关键词匹配
    const keywords = query.toLowerCase().split(' ');
    
    return this.memories
      .map(m => ({
        memory: m,
        score: this.relevanceScore(m, keywords)
      }))
      .filter(r => r.score > 0)
      .sort((a, b) => b.score - a.score)
      .slice(0, limit)
      .map(r => r.memory);
  }
  
  private relevanceScore(memory: Memory, keywords: string[]): number {
    const text = `${memory.title} ${memory.content}`.toLowerCase();
    return keywords.filter(k => text.includes(k)).length;
  }
}

6.2 项目特定记忆

typescript
class ProjectMemory {
  async getProjectContext(): Promise<string> {
    const projectRoot = await this.findProjectRoot();
    const memoryFile = path.join(projectRoot, '.claude-code', 'project.json');
    
    if (await fs.exists(memoryFile)) {
      const data = await fs.readJson(memoryFile);
      return this.formatProjectMemory(data);
    }
    
    return '';
  }
  
  formatProjectMemory(data: ProjectData): string {
    return `
## Project: ${data.name}

### Tech Stack
${data.techStack.join(', ')}

### Conventions
${data.conventions.map(c => `- ${c}`).join('\n')}

### Important Files
${data.importantFiles.map(f => `- ${f.path}: ${f.description}`).join('\n')}

### Recent Decisions
${data.decisions.map(d => `- ${d.date}: ${d.summary}`).join('\n')}
`;
  }
}

前端面试知识库