Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

第五章:Agent 系统

Agent 系统是 OpenMatrix 的执行层,负责实际任务执行。

5.1 Agent 架构总览

Agent 类型定义

type AgentType = 
  | 'planner'    // 规划 Agent - 任务拆解
  | 'coder'      // 编码 Agent - 功能实现
  | 'tester'     // 测试 Agent - 编写测试
  | 'reviewer'   // 审查 Agent - 代码审查
  | 'researcher' // 研究 Agent - 信息收集
  | 'executor';  // 执行 Agent - 运行验证

Agent 层级结构

graph TD
    subgraph "Agent 基础架构"
        BA[BaseAgent<br/>抽象基类]
        AR[AgentRunner<br/>配置生成]
    end
    
    subgraph "具体 Agent 实现"
        PA[PlannerAgent]
        CA[CoderAgent]
        TA[TesterAgent]
        RA[ReviewerAgent]
        REA[ResearcherAgent]
        EXA[ExecutorAgent]
    end
    
    BA --> PA
    BA --> CA
    BA --> TA
    BA --> RA
    BA --> REA
    BA --> EXA
    
    AR --> BA

Agent 职责矩阵

Agent执行阶段主要职责输入输出
Planner规划拆解任务用户指令任务列表
TesterTDD编写测试任务描述测试文件
CoderDevelop实现功能任务 + 测试实现代码
ExecutorVerify运行验证代码验证报告
ReviewerAccept代码审查代码 + 报告审查报告
Researcher辅助信息收集问题调研报告

5.2 BaseAgent 基类

BaseAgent 定义所有 Agent 的通用行为。

核心接口

// agents/base-agent.ts

abstract class BaseAgent {
  protected taskId: string;
  protected agentType: AgentType;
  protected stateManager: StateManager;
  protected fileStore: FileStore;
  
  /**
   * Agent 执行入口
   * 子类必须实现
   */
  abstract execute(context: AgentContext): Promise<AgentResult>;
  
  /**
   * 读取累积的 Agent 上下文
   */
  protected readContext(): string {
    return this.fileStore.readMd('.openmatrix/context.md');
  }
  
  /**
   * 写入新的上下文内容
   */
  protected writeContext(content: string): void {
    this.fileStore.atomicAppend('.openmatrix/context.md', content);
  }
  
  /**
   * 记录决策到上下文
   */
  protected logDecision(decision: Decision): void {
    const entry = `
## Decision [${this.agentType}]
- **Task**: ${this.taskId}
- **Decision**: ${decision.description}
- **Reason**: ${decision.reason}
- **Impact**: ${decision.impact}
`;
    this.writeContext(entry);
  }
  
  /**
   * 记录文件变更
   */
  protected logFileChange(change: FileChange): void {
    const entry = `
## File Change [${this.agentType}]
- **Task**: ${this.taskId}
- **Action**: ${change.action}  // create/modify/delete
- **File**: ${change.file}
- **Purpose**: ${change.purpose}
`;
    this.writeContext(entry);
  }
}

AgentContext 结构

interface AgentContext {
  taskId: string;
  task: Task;
  phase: PhaseType;
  accumulatedContext: string;    // 前序 Agent 的上下文
  projectContext: {
    techStack: string[];
    structure: string;
    conventions: string;
  };
}

AgentResult 结构

interface AgentResult {
  taskId: string;
  agentType: AgentType;
  status: 'success' | 'blocked' | 'failed';
  
  // 成功时
  output?: {
    artifacts: string[];         // 生成的文件
    contextUpdate: string;       // 新增的上下文内容
    suggestions?: string[];      // 给后续 Agent 的建议
  };
  
  // 阻塞时
  blockInfo?: BlockInfo;
  
  // 失败时
  error?: {
    message: string;
    stack?: string;
    retryable: boolean;
  };
}

5.3 AgentRunner 配置器

AgentRunner 负责生成 Agent 执行配置。

核心接口

// agents/agent-runner.ts

interface AgentRunner {
  /**
   * 准备 SubagentTask 配置
   * 用于 Skills 调用 Agent tool
   */
  prepareSubagentTask(
    task: Task,
    phase: PhaseType
  ): SubagentTask;
  
  /**
   * 构建 Agent 执行 Prompt
   */
  buildPrompt(
    task: Task,
    phase: PhaseType,
    context: string
  ): string;
  
  /**
   * 确定超时时间
   */
  determineTimeout(phase: PhaseType, complexity: string): number;
  
  /**
   * 确定是否需要隔离执行
   */
  determineIsolation(task: Task): 'worktree' | undefined;
}

SubagentTask 配置生成

class AgentRunnerImpl implements AgentRunner {
  prepareSubagentTask(task: Task, phase: PhaseType): SubagentTask {
    const context = this.readContext(task.id);
    const prompt = this.buildPrompt(task, phase, context);
    
    return {
      subagent_type: this.mapSubagentType(task.agentType),
      description: this.buildDescription(task, phase),
      prompt,
      isolation: this.determineIsolation(task),
      taskId: task.id,
      agentType: task.agentType,
      timeout: this.determineTimeout(phase, task.estimatedComplexity),
      needsApproval: this.determineNeedsApproval(phase)
    };
  }
  
  private mapSubagentType(agentType: AgentType): string {
    const mapping: Record<AgentType, string> = {
      'planner': 'Plan',
      'coder': 'general-purpose',
      'tester': 'general-purpose',
      'reviewer': 'general-purpose',
      'researcher': 'Explore',
      'executor': 'general-purpose'
    };
    return mapping[agentType];
  }
}

超时时间配置

阶段复杂度超时时间
TDDlow180000 (3分钟)
TDDmedium300000 (5分钟)
TDDhigh600000 (10分钟)
Developlow300000 (5分钟)
Developmedium600000 (10分钟)
Develophigh1200000 (20分钟)
Verifyany300000 (5分钟)
Acceptany180000 (3分钟)

隔离执行策略

class AgentRunnerImpl {
  determineIsolation(task: Task): 'worktree' | undefined {
    // 高风险任务使用 worktree 隔离
    if (task.estimatedComplexity === 'high') {
      return 'worktree';
    }
    
    // 涉及重要文件的任务使用隔离
    const criticalFiles = ['package.json', 'tsconfig.json', 'config.*'];
    if (task.artifacts.some(a => criticalFiles.includes(a))) {
      return 'worktree';
    }
    
    return undefined;
  }
}

5.4 PlannerAgent 规划 Agent

PlannerAgent 负责将用户指令拆解为任务列表。

执行流程

flowchart TD
    A[execute 入口] --> B[读取用户指令]
    B --> C[分析项目结构]
    C --> D[识别子任务]
    D --> E[分析依赖关系]
    E --> F[分配优先级]
    F --> G[分配 Agent]
    G --> H[生成 Task 对象]
    H --> I[返回任务列表]

Prompt 构建

class PlannerAgent extends BaseAgent {
  protected buildPrompt(context: AgentContext): string {
    return `
# Task Planning Request

## User Instruction
${context.task.description}

## Project Context
- Tech Stack: ${context.projectContext.techStack.join(', ')}
- Structure: ${context.projectContext.structure}
- Conventions: ${context.projectContext.conventions}

## Your Task
Analyze the user instruction and break it down into actionable sub-tasks.

## Requirements for Each Task
1. **id**: Use TASK-XXX format (start from TASK-001)
2. **title**: Clear, concise title (max 50 chars)
3. **description**: Detailed description of what needs to be done
4. **dependencies**: List IDs of tasks this depends on (empty array if none)
5. **priority**: 
   - 10: Critical/blocking other tasks
   - 7-9: High priority/core features
   - 4-6: Medium priority/regular features
   - 1-3: Low priority/optional features
6. **estimatedComplexity**: low/medium/high
7. **agentType**: One of planner/coder/tester/reviewer/researcher/executor
8. **artifacts**: Expected output files (if known)

## Dependency Analysis
- Identify which tasks depend on others
- Ensure no circular dependencies
- Consider logical execution order

## Output Format
Return a JSON array of tasks. Each task must have all required fields.

Example:
[
  {
    "id": "TASK-001",
    "title": "Create data model",
    "description": "Define TypeScript interfaces...",
    "dependencies": [],
    "priority": 10,
    "estimatedComplexity": "low",
    "agentType": "coder",
    "artifacts": ["src/models/user.ts"]
  },
  ...
]

Now analyze and plan the tasks.
`;
  }
}

输出处理

class PlannerAgent extends BaseAgent {
  async execute(context: AgentContext): Promise<AgentResult> {
    const prompt = this.buildPrompt(context);
    
    // Agent 执行(通过 Skills 委托)
    const response = await this.runAgent(prompt);
    
    // 解析 JSON 输出
    const tasks = this.parseTaskList(response);
    
    // 验证任务列表
    this.validateTasks(tasks);
    
    // 保存任务
    for (const task of tasks) {
      this.stateManager.saveTask(task);
    }
    
    // 记录决策
    this.logDecision({
      description: 'Created task breakdown',
      reason: 'Based on user instruction analysis',
      impact: `${tasks.length} tasks identified`
    });
    
    return {
      taskId: context.taskId,
      agentType: 'planner',
      status: 'success',
      output: {
        artifacts: [],
        contextUpdate: `## Planning Complete\n- Total tasks: ${tasks.length}`,
        suggestions: ['Review task dependencies before execution']
      }
    };
  }
}

5.5 TesterAgent 测试 Agent

TesterAgent 负责在 TDD 阶段编写测试。

执行流程

flowchart TD
    A[execute 入口] --> B[读取任务描述]
    B --> C[分析预期行为]
    C --> D[设计测试用例]
    D --> E[编写测试文件]
    E --> F[运行测试]
    F --> G{测试结果}
    
    G --> |"失败 (RED)"| H[通过 TDD]
    G --> |"通过"| I[重新设计测试]
    G --> |"无测试"| I
    
    H --> J[返回成功]
    I --> E

Prompt 构建

class TesterAgent extends BaseAgent {
  protected buildPrompt(context: AgentContext): string {
    return `
# Task: ${context.task.title}
# Phase: TDD (Test-Driven Development)

## Task Description
${context.task.description}

## Expected Behavior
Based on the description, tests should verify:
1. What is the expected functionality?
2. What are the edge cases?
3. What error scenarios should be handled?

## Context from Previous Agents
${context.accumulatedContext}

## Your Goal: RED Phase
Write comprehensive tests that **MUST FAIL** currently.

The tests should:
1. Define the expected behavior clearly
2. Cover normal cases, edge cases, and error scenarios
3. Be well-structured and readable
4. Use the project's test framework

## Test Framework
${this.detectTestFramework(context.projectContext)}

## Requirements
- Test files should be in appropriate test directory
- Test names should clearly describe what is being tested
- Each test should be independent
- Use descriptive assertions

## Output
1. Create test files
2. Report current test execution status
3. Explain what each test verifies

## Important
Tests MUST be failing (RED phase). If tests pass, the tests are not properly testing new functionality.
`;
  }
  
  private detectTestFramework(projectContext: any): string {
    // 检测项目使用的测试框架
    if (projectContext.techStack.includes('vitest')) {
      return 'Vitest - use describe/it/expect';
    }
    if (projectContext.techStack.includes('jest')) {
      return 'Jest - use describe/test/expect';
    }
    return 'Use existing test framework conventions';
  }
}

测试验证

class TesterAgent extends BaseAgent {
  async execute(context: AgentContext): Promise<AgentResult> {
    // ... 执行 Agent ...
    
    // 验证测试是否失败
    const testResult = await this.runTests();
    
    if (testResult.status === 'passed') {
      // TDD 要求测试失败(RED)
      return {
        taskId: context.taskId,
        agentType: 'tester',
        status: 'failed',
        error: {
          message: 'Tests passed - TDD requires failing tests (RED phase)',
          retryable: true
        }
      };
    }
    
    if (testResult.status === 'failed') {
      // 测试失败 = TDD 成功
      this.logFileChange({
        action: 'create',
        file: testResult.testFile,
        purpose: 'TDD test file'
      });
      
      return {
        taskId: context.taskId,
        agentType: 'tester',
        status: 'success',
        output: {
          artifacts: [testResult.testFile],
          contextUpdate: `## TDD Complete\n- Test file: ${testResult.testFile}\n- Tests failing: ${testResult.failedCount}`,
          suggestions: ['Implement functionality to pass these tests']
        }
      };
    }
  }
}

5.6 CoderAgent 编码 Agent

CoderAgent 负责在 Develop 阶段实现功能。

执行流程

flowchart TD
    A[execute 入口] --> B[读取任务描述]
    B --> C[读取测试文件]
    C --> D[理解测试需求]
    D --> E[设计实现方案]
    E --> F[编写实现代码]
    F --> G[运行测试]
    G --> H{测试结果}
    
    H --> |"通过 (GREEN)"| I[通过 Develop]
    H --> |"失败"| J[继续开发]
    
    I --> K[返回成功]
    J --> E

Prompt 构建

class CoderAgent extends BaseAgent {
  protected buildPrompt(context: AgentContext): string {
    const testFiles = this.findTestFiles(context.task);
    
    return `
# Task: ${context.task.title}
# Phase: Develop (Implementation)

## Task Description
${context.task.description}

## Context from Previous Agents
${context.accumulatedContext}

## Test Files (from TDD phase)
${testFiles.map(f => `### ${f}\n${this.fileStore.read(f)}`).join('\n\n')}

## Your Goal: GREEN Phase
Implement functionality that passes **ALL** tests written in TDD phase.

## Implementation Guidelines
1. Read and understand each test case
2. Implement the required functionality
3. Follow project coding conventions
4. Keep code clean and maintainable
5. Add necessary comments for complex logic

## Coding Conventions
${context.projectContext.conventions}

## Requirements
- All tests must pass after implementation
- Code should be well-structured
- No unnecessary complexity
- Handle edge cases and errors as tests specify

## Output
1. Create/modify implementation files
2. Run tests and verify they pass
3. Report:
   - Files created/modified
   - Key implementation decisions
   - Any suggestions for verify/accept phases

## Important
Tests MUST pass (GREEN phase). If tests fail, continue implementation.
`;
  }
}

实现验证

class CoderAgent extends BaseAgent {
  async execute(context: AgentContext): Promise<AgentResult> {
    // ... 执行 Agent ...
    
    // 验证测试是否通过
    const testResult = await this.runTests();
    
    if (testResult.status === 'failed') {
      // 测试未通过,需要继续开发
      return {
        taskId: context.taskId,
        agentType: 'coder',
        status: 'blocked',
        blockInfo: {
          reason: 'Tests still failing after implementation',
          type: 'information',
          missingInfo: ['Implementation approach guidance']
        }
      };
    }
    
    // 测试通过 = Develop 成功
    const changedFiles = this.getChangedFiles();
    
    for (const file of changedFiles) {
      this.logFileChange({
        action: file.action,
        file: file.path,
        purpose: 'Feature implementation'
      });
    }
    
    this.logDecision({
      description: 'Implementation approach',
      reason: 'To pass all test cases',
      impact: changedFiles.map(f => f.path).join(', ')
    });
    
    return {
      taskId: context.taskId,
      agentType: 'coder',
      status: 'success',
      output: {
        artifacts: changedFiles.map(f => f.path),
        contextUpdate: `## Develop Complete\n- Implementation files: ${changedFiles.length}`,
        suggestions: ['Run quality gates in verify phase']
      }
    };
  }
}

5.7 ExecutorAgent 执行 Agent

ExecutorAgent 负责在 Verify 阶段运行质量门禁。

七个质量门禁

flowchart TD
    A[Verify 开始] --> B[Build 检查]
    B --> C[Test 运行]
    C --> D[Coverage 检查]
    D --> E[Lint 检查]
    E --> F[Security 扫描]
    F --> G[E2E 测试<br/>可选]
    G --> H[Acceptance 标准]
    
    H --> I{全部通过?}
    I --> |"是"| J[Verify 成功]
    I --> |"否"| K[Verify 失败]

Prompt 构建

class ExecutorAgent extends BaseAgent {
  protected buildPrompt(context: AgentContext): string {
    const qualityConfig = this.getQualityConfig();

    return `
# Task: ${context.task.title}
# Phase: Verify (Quality Gates)

## Task Description
${context.task.description}

## Context from Previous Agents
${context.accumulatedContext}

## Quality Configuration
- Level: ${qualityConfig.level}
- TDD: ${qualityConfig.tdd ? 'Yes' : 'No'}
- Min Coverage: ${qualityConfig.minCoverage}%
- Strict Lint: ${qualityConfig.strictLint ? 'Yes' : 'No'}
- Security Scan: ${qualityConfig.securityScan ? 'Yes' : 'No'}
- E2E Tests: ${qualityConfig.e2eTests ? 'Yes' : 'No'}

## Your Task: Run Quality Gates

Execute the following checks in order:

### 1. Build Check
```bash
npm run build
```
Must complete without errors.

### 2. Test Run
```bash
npm test
```
All tests must pass.

### 3. Coverage Check
Run coverage tool and verify minimum threshold.
- Required: ${qualityConfig.minCoverage}% coverage
- Report: Line, function, and branch coverage

### 4. Lint Check
${qualityConfig.strictLint ? 'Run strict lint mode' : 'Run standard lint'}
```bash
npm run lint
```
No errors allowed.

### 5. Security Scan
${qualityConfig.securityScan ? `Run security audit
```bash
npm audit
```
No high/critical vulnerabilities allowed.` : 'Skipped'}

### 6. E2E Tests
${qualityConfig.e2eTests ? `Run end-to-end tests if available
```bash
npm run e2e
``` ` : 'Skipped'}

### 7. Acceptance Criteria
Verify task-specific acceptance criteria from description.

## Output Format
Return a JSON report:
{
  "build": { "status": "pass/fail", "details": "..." },
  "test": { "status": "pass/fail", "passed": N, "failed": M },
  "coverage": { "status": "pass/fail", "percentage": X },
  "lint": { "status": "pass/fail", "errors": N },
  "security": { "status": "pass/fail", "vulnerabilities": [...] },
  "e2e": { "status": "pass/fail/skipped", "..." },
  "acceptance": { "status": "pass/fail", "criteria": [...] }
}

## Important
Run ALL gates. Report failures honestly. Do not skip gates.
`;
  }
}

验证结果处理

interface QualityReport {
  build: GateResult;
  test: GateResult;
  coverage: CoverageResult;
  lint: GateResult;
  security: SecurityResult;
  e2e: GateResult;
  acceptance: AcceptanceResult;
  overallStatus: 'pass' | 'fail';
}

interface GateResult {
  status: 'pass' | 'fail';
  details?: string;
}

interface CoverageResult extends GateResult {
  line: number;
  function: number;
  branch: number;
  threshold: number;
}

class ExecutorAgent extends BaseAgent {
  async execute(context: AgentContext): Promise<AgentResult> {
    const report = await this.runQualityGates(context);
    
    // 保存验证报告
    this.stateManager.savePhaseResult(
      context.taskId,
      'verify',
      report
    );
    
    if (report.overallStatus === 'pass') {
      return {
        taskId: context.taskId,
        agentType: 'executor',
        status: 'success',
        output: {
          artifacts: [],
          contextUpdate: `## Verify Complete\n- All quality gates passed`,
          suggestions: ['Proceed to accept phase for final review']
        }
      };
    }
    
    // 有失败的质量门禁
    const failedGates = this.getFailedGates(report);
    
    return {
      taskId: context.taskId,
      agentType: 'executor',
      status: 'failed',
      error: {
        message: `Quality gates failed: ${failedGates.join(', ')}`,
        retryable: this.isRetryable(report)
      }
    };
  }
}

5.8 ReviewerAgent 审查 Agent

ReviewerAgent 负责在 Accept 阶段进行最终审查。

审查维度

graph TD
    A[Accept 开始] --> B[代码质量审查]
    A --> C[最佳实践检查]
    A --> D[安全考虑审查]
    A --> E[文档完整性检查]
    
    B --> F{审查结果}
    C --> F
    D --> F
    E --> F
    
    F --> |"全部通过"| G[Accept 成功]
    F --> |"有问题"| H[Accept 失败]

Prompt 构建

class ReviewerAgent extends BaseAgent {
  protected buildPrompt(context: AgentContext): string {
    const changedFiles = this.getChangedFiles(context.taskId);
    const verifyReport = this.getVerifyReport(context.taskId);
    
    return `
# Task: ${context.task.title}
# Phase: Accept (Final Review)

## Task Description
${context.task.description}

## Context from Previous Agents
${context.accumulatedContext}

## Verify Phase Report
${JSON.stringify(verifyReport, null, 2)}

## Changed Files
${changedFiles.map(f => `### ${f}\n${this.fileStore.read(f)}`).join('\n\n')}

## Your Task: Final Review

Review the implementation for:

### 1. Code Quality
- Structure: Is the code well-organized?
- Naming: Are names clear and consistent?
- Complexity: Is complexity appropriate?
- Duplication: Is there unnecessary duplication?

### 2. Best Practices
- Patterns: Are appropriate patterns used?
- Conventions: Does code follow project conventions?
- Error Handling: Are errors handled properly?
- Testing: Is testing adequate?

### 3. Security Considerations
- Input Validation: Is input validated?
- Authentication: Is auth handled properly?
- Authorization: Are permissions checked?
- Data Protection: Is sensitive data protected?

### 4. Documentation Completeness
- Comments: Are complex parts commented?
- Types: Are types well-defined?
- README: Is README updated if needed?

## Output Format
Return a JSON review:
{
  "codeQuality": { 
    "score": 1-10,
    "issues": [...],
    "suggestions": [...]
  },
  "bestPractices": { 
    "score": 1-10,
    "issues": [...]
  },
  "security": { 
    "score": 1-10,
    "issues": [...]
  },
  "documentation": { 
    "score": 1-10,
    "issues": [...]
  },
  "overallScore": 1-10,
  "approved": true/false,
  "blockers": [...],
  "recommendations": [...]
}

## Important
Be thorough but practical. Focus on significant issues, not minor nitpicks.
Approve if code is good enough for production, suggest improvements separately.
`;
  }
}

审查结果处理

interface AcceptanceResult {
  codeQuality: ReviewDimension;
  bestPractices: ReviewDimension;
  security: ReviewDimension;
  documentation: ReviewDimension;
  overallScore: number;
  approved: boolean;
  blockers: string[];
  recommendations: string[];
}

interface ReviewDimension {
  score: number;       // 1-10
  issues: string[];
  suggestions?: string[];
}

class ReviewerAgent extends BaseAgent {
  async execute(context: AgentContext): Promise<AgentResult> {
    const review = await this.runReview(context);
    
    // 保存接受报告
    this.stateManager.savePhaseResult(
      context.taskId,
      'accept',
      review
    );
    
    if (review.approved) {
      this.logDecision({
        description: 'Accepted implementation',
        reason: `Overall score: ${review.overallScore}/10`,
        impact: 'Task marked complete'
      });
      
      return {
        taskId: context.taskId,
        agentType: 'reviewer',
        status: 'success',
        output: {
          artifacts: [],
          contextUpdate: `## Accept Complete\n- Score: ${review.overallScore}/10\n- Approved: Yes`,
          suggestions: review.recommendations
        }
      };
    }
    
    // 未通过审查
    return {
      taskId: context.taskId,
      agentType: 'reviewer',
      status: 'failed',
      error: {
        message: `Review not approved: ${review.blockers.join('; ')}`,
        retryable: true
      }
    };
  }
}

5.9 ResearcherAgent 研究 Agent

ResearcherAgent 是辅助 Agent,负责信息收集和调研。

使用场景

  • 任务开始前的技术调研
  • 阻塞问题的问题诊断
  • 最佳实践和方案选择

Prompt 构建

class ResearcherAgent extends BaseAgent {
  protected buildPrompt(context: AgentContext): string {
    return `
# Research Request

## Task Context
${context.task.description}

## Research Question
${context.task.researchQuestion}

## Research Goals
1. Understand existing approaches and best practices
2. Identify relevant tools and libraries
3. Gather information to unblock the task
4. Provide actionable recommendations

## Research Areas
- Technical feasibility
- Implementation patterns
- Alternative approaches
- Potential challenges

## Output Format
Return a structured research report:
{
  "summary": "Brief overview of findings",
  "approaches": [
    {
      "name": "Approach name",
      "description": "How it works",
      "pros": [...],
      "cons": [...],
      "recommendation": "Why choose/not choose"
    }
  ],
  "tools": [
    {
      "name": "Tool name",
      "purpose": "What it does",
      "usage": "How to use"
    }
  ],
  "challenges": [...],
  "recommendations": [...],
  "resources": [
    {
      "type": "documentation/article/example",
      "url": "...",
      "description": "..."
    }
  ]
}

## Important
Focus on actionable information. Provide specific recommendations.
`;
  }
}

5.10 Agent Memory (上下文传递)

Agent Memory 是 Agent 之间传递信息的机制。

上下文文件结构

.openmatrix/
├── context.md              # 全局上下文
└── tasks/
    └── TASK-001/
        └── context.md      # 任务特定上下文

全局上下文内容

## Decision [planner]
- **Task**: TASK-001
- **Decision**: Use Vitest as test framework
- **Reason**: Project already uses Vitest
- **Impact**: Tester Agent should use Vitest syntax

## File Change [tester]
- **Task**: TASK-001
- **Action**: create
- **File**: tests/user.test.ts
- **Purpose**: TDD test file for user model

## Decision [coder]
- **Task**: TASK-001
- **Decision**: Use interface for User type
- **Reason**: Better type safety and extensibility
- **Impact**: src/models/user.ts defines IUser interface

## File Change [coder]
- **Task**: TASK-001
- **Action**: create
- **File**: src/models/user.ts
- **Purpose**: User model implementation

## Suggestion [tester]
- **Task**: TASK-001
- **Suggestion**: Add edge case test for empty name
- **For**: Verify phase

## Decision [executor]
- **Task**: TASK-001
- **Decision**: All quality gates passed
- **Reason**: Coverage 85%, lint clean, security clean
- **Impact**: Proceed to accept phase

## Accept Complete [reviewer]
- **Task**: TASK-001
- **Score**: 8/10
- **Approved**: Yes
- **Recommendations**: Add JSDoc comments for public methods

上下文传递流程

sequenceDiagram
    participant P as Planner
    participant T as Tester
    participant C as Coder
    participant E as Executor
    participant R as Reviewer
    
    P->>P: 执行规划
    P->>CTX: 写入决策
    
    T->>CTX: 读取前序上下文
    T->>T: 执行 TDD
    T->>CTX: 写入文件变更
    
    C->>CTX: 读取累积上下文
    C->>C: 执行 Develop
    C->>CTX: 写入实现决策
    
    E->>CTX: 读取累积上下文
    E->>E: 执行 Verify
    E->>CTX: 写入验证结果
    
    R->>CTX: 读取完整上下文
    R->>R: 执行 Accept
    R->>CTX: 写入接受报告

上下文 API

interface ContextManager {
  /**
   * 读取全局上下文
   */
  readGlobalContext(): string;
  
  /**
   * 读取任务上下文
   */
  readTaskContext(taskId: string): string;
  
  /**
   * 追加全局上下文
   */
  appendGlobalContext(content: string): void;
  
  /**
   * 追加任务上下文
   */
  appendTaskContext(taskId: string, content: string): void;
  
  /**
   * 获取累积上下文(全局 + 任务)
   */
  getAccumulatedContext(taskId: string): string;
}

下一章将深入探讨 Storage 存储层 的设计与实现。