# sisyphus-debatewiki-plugin 架构设计文档

## 1. 架构概览

### 1.1 Sisyphus编排模式
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   用户请求      │───▶│  Sisyphus Task   │───▶│  专业智能体     │
│ (User Request)  │    │  (Delegation)    │    │ (Specialist     │
└─────────────────┘    └──────────────────┘    │    Agent)       │
                                              └─────────────────┘
                                                      │
                                                      ▼
                                            ┌─────────────────┐
                                            │    工具执行     │
                                            │   (Tools)       │
                                            └─────────────────┘
                                                      │
                                                      ▼
                                            ┌─────────────────┐
                                            │   结果返回      │
                                            │ (Result)        │
                                            └─────────────────┘
```

### 1.2 系统架构图
```
┌─────────────────────────────────────────────────────────────────┐
│                    OpenCode Runtime                           │
├─────────────────────────────────────────────────────────────────┤
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐  │
│  │   论坛智能体     │  │   共识智能体     │  │   维基智能体     │  │
│  │  (Forum Agent)  │  │(Consensus Agent)│  │ (Wiki Agent)    │  │
│  └─────────────────┘  └─────────────────┘  └─────────────────┘  │
│              │                 │                   │           │
│              ▼                 ▼                   ▼           │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐  │
│  │   辩论工具      │  │   共识工具      │  │   维基工具      │  │
│  │   (Debate)      │  │  (Consensus)    │  │   (Wiki)        │  │
│  └─────────────────┘  └─────────────────┘  └─────────────────┘  │
│                                                                 │
│  ┌─────────────────────────────────────────────────────────────┐│
│  │                    Hook系统                                 ││
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐        ││
│  │  │ 事件监听器   │  │ 事件处理器   │  │ 事件广播器   │        ││
│  │  │(Listener)    │  │(Processor)  │  │(Broadcaster)│        ││
│  │  └─────────────┘  └─────────────┘  └─────────────┘        ││
│  └─────────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────────┘
```

## 2. 智能体设计

### 2.1 论坛智能体 (Forum Agent)
```
Forum Agent Responsibilities:
├── 协调多智能体辩论
├── 管理辩论流程和阶段
├── 跟踪待办事项和进度
├── 汇总消息和结果
└── 计算辩论共识
```

**接口定义**:
```typescript
interface ForumAgent {
  startDebate(topic: string, participants: string[], flowType: string): Promise<DebateSession>;
  executePhase(sessionId: string, phase: number): Promise<PhaseResult>;
  addMessage(sessionId: string, agentName: string, content: string): Promise<void>;
  getMessages(sessionId: string): Promise<Message[]>;
  calculateConsensus(sessionId: string): Promise<ConsensusResult>;
}
```

### 2.2 共识智能体 (Consensus Agent)
```
Consensus Agent Responsibilities:
├── 实现多种共识算法
├── 计算投票共识
├── 执行审议共识
├── 计算加权共识
└── 生成共识报告
```

**接口定义**:
```typescript
interface ConsensusAgent {
  calculateVotingConsensus(messages: Message[], threshold: number): Promise<ConsensusResult>;
  calculateDeliberationConsensus(messages: Message[], maxRounds: number, threshold: number): Promise<ConsensusResult>;
  calculateWeightedConsensus(messages: Message[], weights: Record<string, number>, threshold: number): Promise<ConsensusResult>;
  extractVotes(messages: Message[]): Promise<Vote[]>;
}
```

### 2.3 维基智能体 (Wiki Agent)
```
Wiki Agent Responsibilities:
├── 创建和管理维基页面
├── 处理版本控制
├── 解决编辑冲突
├── 管理协作工作流
└── 执行页面搜索
```

**接口定义**:
```typescript
interface WikiAgent {
  createPage(title: string, content: string, author: string): Promise<WikiPage>;
  updatePage(pageId: string, content: string, author: string, changelog?: string): Promise<WikiPage>;
  getPage(pageId: string): Promise<WikiPage>;
  searchPages(query: string): Promise<WikiPage[]>;
  listPages(): Promise<WikiPage[]>;
}
```

### 2.4 扎根理论智能体 (Grounded Theory Agent)
```
Grounded Theory Agent Responsibilities:
├── 创建和管理研究项目
├── 执行开放编码
├── 执行主轴编码
├── 执行选择编码
└── 检验理论饱和度
```

**接口定义**:
```typescript
interface GroundedTheoryAgent {
  createProject(name: string, description: string, documents: string[], coders: string[]): Promise<GTProject>;
  performOpenCoding(projectId: string, documentId: string, content: string, coder: string): Promise<OpenCode[]>;
  performAxialCoding(projectId: string, category: string, codes: string[], conditions: string, actions: string, consequences: string): Promise<AxialCode>;
  testSaturation(projectId: string, newContent: string, newCodes: string[]): Promise<SaturationResult>;
  generateReport(projectId: string): Promise<string>;
}
```

## 3. 工具系统设计

### 3.1 工具接口
```typescript
interface Tool {
  name: string;
  description: string;
  execute(params: any): Promise<any>;
}
```

### 3.2 辩论工具
- **StartDebateTool**: 启动辩论会话
- **AddMessageTool**: 添加消息到辩论
- **GetMessagesTool**: 获取辩论消息
- **CompleteSessionTool**: 完成辩论会话

### 3.3 共识工具
- **VotingConsensusTool**: 投票共识计算
- **DeliberationConsensusTool**: 审议共识计算
- **WeightedConsensusTool**: 加权共识计算
- **VoteExtractionTool**: 投票提取

### 3.4 维基工具
- **CreatePageTool**: 创建维基页面
- **UpdatePageTool**: 更新维基页面
- **GetPageTool**: 获取维基页面
- **SearchPagesTool**: 搜索维基页面
- **ListPagesTool**: 列出维基页面

### 3.5 扎根理论工具
- **CreateProjectTool**: 创建研究项目
- **OpenCodingTool**: 开放编码
- **AxialCodingTool**: 主轴编码
- **SaturationTestTool**: 饱和度检验
- **ReportGenerationTool**: 报告生成

## 4. Hook系统设计

### 4.1 Hook接口
```typescript
interface Hook {
  event: string;
  handler: (payload: any) => Promise<void>;
  priority: number;
}
```

### 4.2 事件类型
- **debate.started**: 辩论开始事件
- **debate.message_added**: 消息添加事件
- **debate.completed**: 辩论完成事件
- **consensus.reached**: 共识达成事件
- **wiki.page_created**: 页面创建事件
- **wiki.page_updated**: 页面更新事件
- **gt.project_created**: 项目创建事件
- **gt.saturation_tested**: 饱和度检验事件

### 4.3 事件处理流程
```
事件发生 → Hook系统 → 事件分发 → 处理器执行 → 结果处理
```

## 5. 数据模型

### 5.1 辩论会话模型
```typescript
interface DebateSession {
  id: string;
  topic: string;
  participants: string[];
  flow_type: string;
  phase: number;
  messages: Message[];
  todos: TodoItem[];
  created_at: Date;
  updated_at: Date;
  completed: boolean;
}
```

### 5.2 共识结果模型
```typescript
interface ConsensusResult {
  achieved: boolean;
  agreement_ratio: number;
  summary: string;
  votes?: Record<string, boolean>;
  convergence_history?: number[];
}
```

### 5.3 维基页面模型
```typescript
interface WikiPage {
  id: string;
  title: string;
  content: string;
  author: string;
  version: number;
  versions: WikiVersion[];
  created_at: Date;
  updated_at: Date;
  status: 'draft' | 'pending_review' | 'approved' | 'published';
}

interface WikiVersion {
  version_number: number;
  content: string;
  author: string;
  timestamp: Date;
  changelog?: string;
}
```

### 5.4 扎根理论项目模型
```typescript
interface GTProject {
  id: string;
  name: string;
  description: string;
  documents: string[];
  coders: string[];
  open_codes: OpenCode[];
  axial_codes: AxialCode[];
  current_phase: 'open_coding' | 'axial_coding' | 'selective_coding' | 'saturation_testing';
  selective_code?: SelectiveCode;
  created_at: Date;
  updated_at: Date;
}

interface OpenCode {
  id: string;
  code_name: string;
  raw_data: string;
  property: string;
  dimension: string;
  memo?: string;
  coder: string;
  created_at: Date;
}

interface AxialCode {
  id: string;
  category: string;
  subcategory?: string;
  codes: string[]; // References to OpenCode IDs
  properties: Record<string, string>;
  conditions: string;
  actions: string;
  consequences: string;
  coder: string;
  created_at: Date;
}
```

## 6. 任务委托机制

### 6.1 Sisyphus Task接口
```typescript
interface SisyphusTask {
  agent: string;           // 目标智能体
  prompt: string;          // 任务描述
  skills: string[];        // 所需技能
  run_in_background: boolean; // 是否后台运行
  timeout?: number;        // 超时时间
}
```

### 6.2 任务执行流程
```
1. 用户发起sisyphus_task请求
2. 系统解析任务配置
3. 验证智能体可用性
4. 将任务委托给目标智能体
5. 智能体执行任务并返回结果
6. 系统处理结果并返回给用户
```

### 6.3 任务示例
```typescript
// 启动辩论
const debateResult = await sisyphus_task({
  agent: "forum-agent",
  prompt: "Start a debate on AI ethics with proponent, opponent, and moderator",
  skills: ["forum-operations", "session-management"],
  run_in_background: false
});

// 计算共识
const consensusResult = await sisyphus_task({
  agent: "consensus-agent", 
  prompt: "Calculate voting consensus from messages with 70% threshold",
  skills: ["voting-algorithm", "consensus-calculation"],
  run_in_background: false
});

// 创建维基页面
const wikiResult = await sisyphus_task({
  agent: "wiki-agent",
  prompt: "Create a wiki page about AI ethics principles",
  skills: ["wiki-operations", "page-management"],
  run_in_background: false
});
```

## 7. 错误处理机制

### 7.1 错误类型
- **ValidationError**: 输入参数验证错误
- **AgentError**: 智能体执行错误
- **ToolError**: 工具执行错误
- **CommunicationError**: 通信错误
- **ResourceError**: 资源不可用错误

### 7.2 错误处理策略
```
错误发生 → 错误捕获 → 错误分类 → 错误处理 → 用户反馈
```

### 7.3 重试机制
- 网络错误：指数退避重试
- 资源竞争：随机延迟重试
- 暂时性错误：固定间隔重试

## 8. 性能优化

### 8.1 缓存策略
- 智能体状态缓存
- 工具结果缓存
- 数据库查询缓存

### 8.2 并发控制
- 智能体任务队列
- 工具执行池
- 资源访问锁

### 8.3 内存管理
- 对象池复用
- 垃圾回收优化
- 内存泄漏检测

## 9. 安全考虑

### 9.1 输入验证
- 参数类型验证
- 长度限制检查
- 特殊字符过滤

### 9.2 访问控制
- 智能体权限验证
- 工具访问控制
- 数据访问权限

### 9.3 数据保护
- 敏感信息加密
- 数据传输加密
- 审计日志记录