# CodeLin 7.0 详细实施计划

**基于**: 25轮真实分析 + 代码审查 + 竞品研究  
**总时间**: 212小时 (10周)  
**更新**: 从164h调整到212h，增加关键功能  

---

## 📐 实施路线图

```
Phase 0: 架构重构 (32h, Week 1-2)
  ├─ Prompt分层架构 (16h)
  └─ Dual Mode System (16h)
         ↓
Phase 1: 核心功能 (84h, Week 3-6)
  ├─ CODELIN.md自动注入 (12h)
  ├─ Automatic Planning (20h)
  ├─ Git Context Integration (20h)
  ├─ Auto-Continue (8h)
  ├─ # 键快速更新 (8h)
  ├─ Extended Thinking增强 (8h)
  └─ VS Code Extension (40h)
         ↓
Phase 2: 体验优化 (48h, Week 7-8)
  ├─ Memories & Rules (16h)
  ├─ Named Checkpoints (12h)
  ├─ Web搜索增强 (12h)
  └─ 文档和示例 (8h)
         ↓
Phase 3: 性能优化 (48h, Week 9-10)
  ├─ 多模态支持 (16h)
  ├─ 性能监控 (16h)
  └─ 缓存优化 (16h)
```

---

## Phase 0: 架构重构 (32h)

### 0.1 Prompt 分层架构 (16h)

#### 目标
将1108行的巨型Prompt重构为150行的精简核心Prompt + 外部配置系统

#### 新架构设计

```
┌─────────────────────────────────────┐
│   Core System Prompt (150行)       │
│   ├─ Identity & Mission (10行)     │
│   ├─ Mode Explanation (15行)       │
│   ├─ Core Workflow (30行)          │
│   ├─ Critical Rules (40行)         │
│   ├─ SubAgent Overview (30行)      │
│   ├─ Extended Thinking (20行)      │
│   └─ Quick Reference (15行)        │
└─────────────────────────────────────┘
              ↓ 自动注入
┌─────────────────────────────────────┐
│   CODELIN.md (项目配置)             │
│   ├─ Project Context               │
│   ├─ Bash Commands                 │
│   ├─ Code Style                    │
│   └─ Workflows                     │
└─────────────────────────────────────┘
              ↓ 工具元数据
┌─────────────────────────────────────┐
│   Agent Descriptions                │
│   └─ 7个SubAgent的详细说明         │
└─────────────────────────────────────┘
              ↓ 按需检索
┌─────────────────────────────────────┐
│   Dynamic Context                   │
│   ├─ Git History                   │
│   ├─ Related Files                 │
│   └─ API Docs                      │
└─────────────────────────────────────┘
```

#### 新Prompt模板 (150行)

```markdown
## IDENTITY & MISSION (10行)
You are CodeLin, an elite AI coding assistant for Cangjie and general development.

Core capabilities:
- Deep codebase understanding via LSP
- Multi-agent collaboration (7 specialized SubAgents)
- Extended reasoning for complex problems
- Systematic planning and execution

## MODE SYSTEM (15行)
You operate in two modes:

**Code Mode** (Current: ${mode}):
- Full tool access for code modification
- Auto-planning for complex tasks
- Multi-step execution with verification
- Up to 25 tool calls per prompt

**Chat Mode**:
- Read-only tools for understanding
- Fast responses for questions
- Explanations and suggestions
- No code modifications

Switch: `/mode code` or `/mode chat`

## CORE WORKFLOW (30行)
Standard Pattern: Understand → Plan → Execute → Verify

**In Code Mode**:
1. **Understand**: Explore codebase with tools
   - Use ExplorerAgent for unfamiliar code
   - Never assume, always verify
   
2. **Plan**: Auto-generate execution plan
   - Planning Agent runs automatically
   - Creates Todo List for tracking
   - Shows dependencies and risks
   
3. **Execute**: Follow plan step-by-step
   - Use EditorAgent for precise edits
   - Mark tasks complete as you go
   - Verify each step before next
   
4. **Verify**: Ensure quality
   - Run tests and checks
   - Use ReviewerAgent if needed
   - Fix issues before completion

**In Chat Mode**:
- Explain and answer quickly
- Provide code suggestions
- No modifications

## CRITICAL RULES (40行)
### Path Handling
⚠️ **ABSOLUTE PATHS ONLY**
Pattern: `${CliConfig.cwd}/relative/path`
❌ Never: `./file.js` or `src/file.js`
✅ Always: `/full/path/to/project/src/file.js`

### SubAgent Calls
🤝 **INCLUDE WORKING DIRECTORY**
✅ Correct: `ExplorerAgent("Explore at ${CliConfig.cwd}")`
❌ Wrong: `ExplorerAgent("Explore project")`

### Tool Optimization
💡 **Performance Tips**:
- Use `batchReadFiles` for 3+ files (2-4x faster)
- Call SubAgents for complex tasks
- Use Extended Thinking for hard problems

### Code Quality
✅ **Always**:
- Follow project conventions
- Handle errors gracefully
- Include tests for new code
- Document complex logic

### Auto-Continue
🔄 Maximum 25 tool calls per prompt
If stopped: Type `continue` to resume

## SUBAGENT OVERVIEW (30行)
7 specialized agents available:

| Agent | Use Case |
|-------|----------|
| **PlannerAgent** | Complex task breakdown |
| **ExplorerAgent** | Codebase understanding |
| **EditorAgent** | Precise code edits |
| **ReviewerAgent** | Quality assurance |
| **TestGeneratorAgent** | Test generation |
| **RefactoringAgent** | Code improvement |
| **ExecutionLoopAgent** | Autonomous loops |

**Pattern**: Complex Task → Planner → Explorer → Editor → Reviewer

**Call Format**: Include `${CliConfig.cwd}` in every call
Example: `PlannerAgent("Plan for X at ${CliConfig.cwd}")`

## EXTENDED THINKING (20行)
🧠 **Trigger deeper reasoning with**:
- `"think"` → Quick analysis (1-3 steps)
- `"think hard"` → Deep analysis (4-8 steps)
- `"think harder"` → Comprehensive (9-15 steps)
- `"ultrathink"` → Maximum depth (15+ steps)

**Use for**:
- Architecture decisions
- Complex debugging
- Performance optimization
- Security analysis

**Example**: "think hard about how to optimize this query"

## QUICK REFERENCE (15行)
✅ **DO**:
- Explore with tools (never assume!)
- Use absolute paths always
- Call SubAgents for complex tasks
- Trigger Extended Thinking when needed
- Follow project conventions

❌ **DON'T**:
- Assume file contents
- Use relative paths
- Skip error handling
- Ignore existing patterns
- Guess when uncertain
```

#### 实施步骤

**Day 1-2 (4h): 设计新Prompt结构**
```python
任务:
1. 提取核心规则和工作流
2. 设计分层架构
3. 确定外部化内容

交付:
- 新Prompt草稿 (150行)
- 外部化清单
```

**Day 3-4 (4h): 提取SubAgent说明**
```python
任务:
1. 将560行SubAgent说明移到工具描述
2. 在核心Prompt中仅保留30行概述
3. 更新Agent的description字段

交付:
- 精简后的SubAgent部分
- 7个Agent的description更新
```

**Day 5-6 (4h): 实现动态注入**
```cangjie
class PromptBuilder {
    public func buildPrompt(
        mode: CodeLinMode,
        projectContext: ProjectContext
    ): String {
        var prompt = CORE_SYSTEM_PROMPT
        
        // 注入模式说明
        prompt += "\nCurrent Mode: ${mode}\n"
        
        // 注入CODELIN.md内容
        if (projectContext.hasConfig()) {
            prompt += "\n## PROJECT CONTEXT\n"
            prompt += projectContext.codelinMd
        }
        
        // 注入工作目录
        prompt += "\nWorking Directory: ${projectContext.cwd}\n"
        
        return prompt
    }
}
```

**Day 7-8 (4h): 测试和优化**
```python
测试项:
1. Token计数验证 (<800 tokens)
2. AI理解度测试 (与旧Prompt对比)
3. 响应质量测试
4. 性能测试

调整:
- 根据测试结果调整措辞
- 优化分层结构
- 确保关键信息突出
```

#### 验收标准
- ✅ 核心Prompt < 200行
- ✅ Token减少 > 60%
- ✅ AI理解度提升 > 30%
- ✅ 响应速度提升 > 20%
- ✅ 所有功能正常工作

---

### 0.2 Dual Mode System (16h)

#### 目标
实现Code/Chat双模式，对标Windsurf和Cursor

#### 模式定义

```cangjie
// src/core/modes/cascade_mode.cj

public enum CodeLinMode <: ToString {
    | CodeMode
    | ChatMode
    
    public func toString(): String {
        match (this) {
            case CodeMode => "Code"
            case ChatMode => "Chat"
        }
    }
}

public class ModeConfig {
    public let mode: CodeLinMode
    public let allowedTools: ArrayList<String>
    public let maxIterations: Int64
    public let autoPlanning: Bool
    public let prompt: String
    
    public static func forCodeMode(): ModeConfig {
        ModeConfig(
            mode: CodeMode,
            allowedTools: ALL_TOOLS,
            maxIterations: 25,
            autoPlanning: true,
            prompt: CODE_MODE_PROMPT
        )
    }
    
    public static func forChatMode(): ModeConfig {
        ModeConfig(
            mode: ChatMode,
            allowedTools: READ_ONLY_TOOLS,
            maxIterations: 5,
            autoPlanning: false,
            prompt: CHAT_MODE_PROMPT
        )
    }
}

// 只读工具列表
let READ_ONLY_TOOLS = [
    "readFile",
    "batchReadFiles",
    "listDirectory",
    "grep",
    "find",
    "getFileSymbols",  // LSP
    "getReferences",   // LSP
    "getTypeDefinition" // LSP
]
```

#### Prompt差异

```markdown
Code Mode Prompt片段:
"""
You are in **Code Mode** - full access to modify codebase.

Capabilities:
✅ Read and write files
✅ Execute shell commands
✅ Modify multiple files
✅ Auto-planning for complex tasks
✅ All SubAgents available

Workflow:
1. Understand → 2. Auto-Plan → 3. Execute → 4. Verify

You can make up to 25 tool calls.
If stopped, user can type 'continue'.
"""

Chat Mode Prompt片段:
"""
You are in **Chat Mode** - read-only, fast responses.

Focus:
✅ Understand and explain code
✅ Answer questions quickly
✅ Provide suggestions and guidance
❌ NO code modifications

Tools Available:
- File reading (readFile, batchReadFiles)
- Directory listing
- Search (grep, find)
- LSP tools (symbols, references)

Keep responses concise and informative.
"""
```

#### 实施步骤

**Day 1-2 (4h): 模式框架实现**
```cangjie
// src/core/agents/general_code_agent.cj

public class CodeLinAgent {
    private var currentMode: CodeLinMode = CodeMode
    private var modeConfig: ModeConfig
    
    public init() {
        this.modeConfig = ModeConfig.forCodeMode()
    }
    
    public func switchMode(newMode: CodeLinMode): Unit {
        this.currentMode = newMode
        this.modeConfig = match (newMode) {
            case CodeMode => ModeConfig.forCodeMode()
            case ChatMode => ModeConfig.forChatMode()
        }
        
        // 更新Prompt
        updateSystemPrompt(this.modeConfig.prompt)
        
        // 更新工具权限
        updateToolPermissions(this.modeConfig.allowedTools)
        
        PrintUtils.printLine("✅ Switched to ${newMode} mode")
    }
}
```

**Day 3-4 (4h): 工具权限控制**
```cangjie
class ToolManager {
    private var allowedTools: HashSet<String>
    
    public func setAllowedTools(tools: ArrayList<String>): Unit {
        this.allowedTools = HashSet<String>()
        for (tool in tools) {
            this.allowedTools.add(tool)
        }
    }
    
    public func isToolAllowed(toolName: String): Bool {
        return this.allowedTools.contains(toolName)
    }
    
    public override func beforeToolCall(tool: Tool): Bool {
        if (!isToolAllowed(tool.name)) {
            PrintUtils.printLine(
                "❌ Tool '${tool.name}' not available in ${currentMode} mode"
            )
            return false
        }
        return true
    }
}
```

**Day 5-6 (4h): 模式切换命令**
```cangjie
// src/app/process_input.cj

func handleSlashCommand(command: String): Bool {
    match (command) {
        case "/mode code" => {
            agent.switchMode(CodeMode)
            return true
        }
        case "/mode chat" => {
            agent.switchMode(ChatMode)
            return true
        }
        case "/mode" => {
            // 显示当前模式
            PrintUtils.printLine("Current mode: ${agent.currentMode}")
            PrintUtils.printLine("Switch: /mode code or /mode chat")
            return true
        }
        case _ => false
    }
}
```

**Day 7-8 (4h): 测试和UI**
```python
测试场景:
1. Code Mode → 创建文件 → 成功
2. Chat Mode → 尝试创建文件 → 被阻止
3. Code Mode → 自动Planning → 成功
4. Chat Mode → 快速问答 → 成功
5. 模式切换 → 状态正确更新

UI改进:
- 显示当前模式图标
- 模式切换快捷键 (Ctrl+Shift+M)
- 提示可用工具
```

#### 验收标准
- ✅ 双模式流畅切换
- ✅ 工具权限正确控制
- ✅ Chat模式响应快 (< 1秒)
- ✅ Code模式功能完整
- ✅ 用户预期明确

---

## Phase 1: 核心功能 (84h)

### 1.1 CODELIN.md 自动注入 (12h)

#### 5层配置架构

```
优先级: Global < ProjectRoot < Parent < Current < Local

~/.codelin/CODELIN.md (Global)
  ↓ 默认配置
/project/CODELIN.md (ProjectRoot)
  ↓ 项目配置
/project/sub/CODELIN.md (Parent)
  ↓ 子模块配置
/project/sub/dir/CODELIN.md (Current)
  ↓ 当前目录配置
/project/sub/dir/CODELIN.local.md (Local)
  ↓ 本地配置（不提交git）

最终配置 = 合并所有层级
```

#### 实施代码

```cangjie
class CodelinConfigManager {
    public static func loadAllConfigs(workingDir: String): MergedConfig {
        let configs = ArrayList<CodelinConfig>()
        
        // 1. Global
        let globalPath = getHomeDir() + "/.codelin/CODELIN.md"
        if (exists(globalPath)) {
            configs.add(loadConfig(globalPath, Level.Global))
        }
        
        // 2. ProjectRoot (查找.git)
        let projectRoot = findProjectRoot(workingDir)
        if (projectRoot.isSome()) {
            addConfigIfExists(configs, projectRoot.get(), Level.ProjectRoot)
        }
        
        // 3. Parents (向上查找)
        var current = workingDir
        while (current != projectRoot) {
            addConfigIfExists(configs, current, Level.Parent)
            current = getParentDir(current)
        }
        
        // 4. Current
        addConfigIfExists(configs, workingDir, Level.Current)
        
        // 5. Local
        let localPath = workingDir + "/CODELIN.local.md"
        if (exists(localPath)) {
            configs.add(loadConfig(localPath, Level.Local))
        }
        
        return mergeConfigs(configs)
    }
}
```

详细实施步骤见原计划...

---

### 1.2 Automatic Planning Agent (20h)

#### 核心设计

```cangjie
class AutoPlanningService {
    // 自动检测复杂度
    public func shouldAutoPlanning(query: String): Bool {
        let indicators = [
            query.contains("implement"),
            query.contains("create"),
            query.contains("refactor"),
            query.contains("feature"),
            query.size > 100
        ]
        return indicators.count { it } >= 2
    }
    
    // 后台生成计划
    public func autoGeneratePlan(query: String, context: ProjectContext): Plan {
        PrintUtils.printLine("🔄 Planning...")
        
        let planQuery = """
        Create detailed plan for: ${query}
        At: ${context.cwd}
        """
        
        let planJson = plannerAgent.execute(planQuery)
        return parsePlan(planJson)
    }
    
    // Todo List跟踪
    public func displayTodoList(): String {
        var display = "\n📋 Todo List:\n"
        for (item in todoList) {
            let icon = match (item.status) {
                case Pending => "⬜"
                case InProgress => "🔄"
                case Completed => "✅"
            }
            display += "${icon} ${item.description}\n"
        }
        return display
    }
}
```

详细实施步骤见原计划...

---

### 1.3 Git Context Integration (20h)

#### 实现Augment Context Lineage

```cangjie
class GitContextLineage {
    // 扫描提交历史
    public func scanHistory(projectRoot: Path, maxCommits: Int64 = 100): Unit {
        let commits = getRecentCommits(projectRoot, maxCommits)
        
        for (commit in commits) {
            let diff = getCommitDiff(commit)
            let summary = summarizer.summarize(commit, diff)
            
            vectorStore.index(CommitContext(
                hash: commit.hash,
                summary: summary,
                changedFiles: commit.files
            ))
        }
    }
    
    // 按需检索注入
    public func injectToContext(query: String): String {
        let relevant = vectorStore.search(query, topK: 3)
        
        var context = "\n## Relevant History:\n"
        for (commit in relevant) {
            context += "- ${commit.hash}: ${commit.summary}\n"
        }
        return context
    }
}
```

详细实施步骤见原计划...

---

## 验收和交付

### 总体验收标准

| 类别 | 指标 | 目标 | 测试方法 |
|------|------|------|----------|
| **Prompt** | 长度 | < 200行 | wc -l |
| **Prompt** | Token | < 800 | tiktoken count |
| **配置** | 自动注入率 | 100% | 测试自动加载 |
| **模式** | 切换流畅度 | < 100ms | 性能测试 |
| **Planning** | 自动化率 | 100% | 功能测试 |
| **Git** | 历史利用率 | > 80% | 检索测试 |
| **体验** | 用户评分 | > 90分 | 用户调研 |
| **质量** | AI成功率 | > 85% | 基准测试 |
| **性能** | 响应速度 | < 2秒 | 性能监控 |
| **综合** | 能力评分 | > 99% | 全面评估 |

### 交付文档

1. **技术文档**
   - 架构设计文档
   - API文档
   - 配置指南

2. **用户文档**
   - 快速开始指南
   - 最佳实践
   - 常见问题

3. **测试报告**
   - 功能测试报告
   - 性能测试报告
   - 用户验收报告

---

**计划完成**: 2025-11-20  
**状态**: ✅ 准备实施  
**下一步**: Phase 0开始

**CodeLin 7.0 - 真正的世界级改造！** 🚀
