Skill: komong/ai-agent-team-manager (version 1.0.0)

--- name: ai-agent-team-manager description: Professional AI agent team management system for coordinating multiple OpenClaw agents. Implements the proven Otter Camp methodology with task assignment, progress tracking, quality control, and performance evaluation. metadata: openclaw: requires: env: - OPENCLAW_WORKSPACE bins: - git - node - python3 --- # AI Agent Team Manager ## Overview This skill implements a professional AI agent team management system based on the Otter Camp methodology. It enables you to coordinate multiple OpenClaw agents working together on complex projects with proper task assignment, progress tracking, quality control, and performance evaluation. ## When to Use This Skill Use this skill when you need to: - Manage multiple AI agents working on the same project - Implement structured workflows for complex tasks - Track progress and ensure quality across agent teams - Evaluate agent performance and optimize workflows - Scale AI operations beyond single-agent capabilities ## Core Features ### Task Assignment & Coordination - Intelligent task decomposition and assignment - Agent role definition and specialization - Dependency management between tasks - Resource allocation and load balancing ### Progress Tracking & Monitoring - Real-time progress dashboards - Milestone tracking and deadline management - Automated status reporting - Issue detection and escalation ### Quality Control & Review - Multi-layer quality assurance processes - Peer review between agents - Human-in-the-loop checkpoints - Automated testing and validation ### Performance Evaluation - Agent performance metrics and scoring - Workflow optimization recommendations - Cost-benefit analysis of agent configurations - Continuous improvement through learning ## Usage Examples ### Basic Team Setup ```javascript const teamManager = new AIAgentTeamManager({ workspace: '/path/to/workspace', agents: ['xiaolv', 'laogou', 'xiaoqiu', 'xiaozhu'], methodology: 'otter-camp' }); ``` ### Task Coordination ```javascript await teamManager.assignTask({ taskId: 'email-analysis-2026', description: 'Analyze 3,418 emails from QQ mailbox', assignee: 'xiaolv', reviewers: ['laogou'], deadline: '2026-03-10', qualityChecks: ['accuracy', 'completeness', 'formatting'] }); ``` ### Performance Reporting ```javascript const report = await teamManager.generatePerformanceReport({ period: 'last-30-days', metrics: ['tasksCompleted', 'qualityScore', 'efficiency', 'cost'] }); ``` ## Integration Points - Works seamlessly with existing OpenClaw agents - Integrates with Git for version control - Supports custom agent roles and specializations - Compatible with all OpenClaw skill types ## Best Practices - Start with small teams (2-4 agents) and scale gradually - Implement regular quality reviews and checkpoints - Use human oversight for critical decisions - Continuously optimize based on performance data - Maintain clear documentation of team workflows ## Security & Compliance - All data remains in your local workspace - No external API calls without explicit permission - Full audit trail of all agent activities - Compliant with enterprise security requirements

path: task-allocator.js
content: /**
 * AI Agent Team Manager - Task Allocator
 * 智能任务分配系统，基于代理能力和工作负载进行优化分配
 */

class TaskAllocator {
  constructor() {
    this.agents = new Map();
    this.taskQueue = [];
    this.performanceMetrics = new Map();
  }

  /**
   * 注册AI代理
   * @param {string} agentId - 代理ID
   * @param {Object} capabilities - 代理能力描述
   * @param {number} maxConcurrentTasks - 最大并发任务数
   */
  registerAgent(agentId, capabilities, maxConcurrentTasks = 3) {
    this.agents.set(agentId, {
      id: agentId,
      capabilities: capabilities,
      maxConcurrentTasks: maxConcurrentTasks,
      currentTasks: 0,
      successRate: 1.0,
      avgResponseTime: 0,
      lastActive: Date.now()
    });
  }

  /**
   * 分配任务给最适合的代理
   * @param {Object} task - 任务对象
   * @returns {string|null} 分配的代理ID
   */
  allocateTask(task) {
    const suitableAgents = this.findSuitableAgents(task);
    if (suitableAgents.length === 0) {
      return null;
    }

    // 基于多因素选择最佳代理
    const bestAgent = this.selectBestAgent(suitableAgents, task);
    
    if (bestAgent) {
      this.assignTaskToAgent(bestAgent.id, task);
      return bestAgent.id;
    }
    
    return null;
  }

  /**
   * 查找适合任务的代理
   * @param {Object} task - 任务对象
   * @returns {Array} 适合的代理列表
   */
  findSuitableAgents(task) {
    const suitable = [];
    
    for (const [agentId, agent] of this.agents) {
      // 检查能力匹配
      if (this.canHandleTask(agent, task)) {
        // 检查负载
        if (agent.currentTasks < agent.maxConcurrentTasks) {
          suitable.push(agent);
        }
      }
    }
    
    return suitable;
  }

  /**
   * 检查代理是否能处理任务
   * @param {Object} agent - 代理对象
   * @param {Object} task - 任务对象
   * @returns {boolean}
   */
  canHandleTask(agent, task) {
    const requiredSkills = task.requiredSkills || [];
    const agentSkills = agent.capabilities.skills || [];
    
    // 检查是否具备所有必需技能
    return requiredSkills.every(skill => 
      agentSkills.includes(skill) || 
      this.isSkillCompatible(skill, agentSkills)
    );
  }

  /**
   * 检查技能兼容性
   * @param {string} requiredSkill - 需要的技能
   * @param {Array} availableSkills - 可用技能列表
   * @returns {boolean}
   */
  isSkillCompatible(requiredSkill, availableSkills) {
    // 技能兼容性映射
    const compatibilityMap = {
      'content-writing': ['blog-writing', 'copywriting', 'seo-content'],
      'data-analysis': ['financial-analysis', 'market-research'],
      'web-development': ['frontend', 'backend', 'fullstack'],
      'security-audit': ['vulnerability-scanning', 'compliance-check']
    };
    
    if (compatibilityMap[requiredSkill]) {
      return compatibilityMap[requiredSkill].some(skill => 
        availableSkills.includes(skill)
      );
    }
    
    return false;
  }

  /**
   * 选择最佳代理（基于性能、负载、响应时间）
   * @param {Array} agents - 代理列表
   * @param {Object} task - 任务对象
   * @returns {Object} 最佳代理
   */
  selectBestAgent(agents, task) {
    return agents.reduce((best, agent) => {
      const score = this.calculateAgentScore(agent, task);
      const bestScore = best ? this.calculateAgentScore(best, task) : -Infinity;
      
      return score > bestScore ? agent : best;
    }, null);
  }

  /**
   * 计算代理评分
   * @param {Object} agent - 代理对象
   * @param {Object} task - 任务对象
   * @returns {number} 评分
   */
  calculateAgentScore(agent, task) {
    const loadFactor = 1 - (agent.currentTasks / agent.maxConcurrentTasks);
    const performanceFactor = agent.successRate;
    const responseTimeFactor = Math.max(0, 1 - (agent.avgResponseTime / 10000)); // 10秒为基准
    
    // 任务紧急度影响
    const urgencyFactor = task.urgency === 'high' ? 1.2 : 
                         task.urgency === 'medium' ? 1.0 : 0.8;
    
    return (loadFactor * 0.4 + performanceFactor * 0.3 + responseTimeFactor * 0.3) * urgencyFactor;
  }

  /**
   * 分配任务给代理
   * @param {string} agentId - 代理ID
   * @param {Object} task - 任务对象
   */
  assignTaskToAgent(agentId, task) {
    const agent = this.agents.get(agentId);
    if (agent) {
      agent.currentTasks++;
      agent.lastActive = Date.now();
      
      // 记录任务分配
      console.log(`Task ${task.id} assigned to agent ${agentId}`);
    }
  }

  /**
   * 任务完成回调
   * @param {string} agentId - 代理ID
   * @param {Object} task - 任务对象
   * @param {boolean} success - 是否成功
   * @param {number} responseTime - 响应时间（毫秒）
   */
  onTaskComplete(agentId, task, success, responseTime) {
    const agent = this.agents.get(agentId);
    if (agent) {
      agent.currentTasks = Math.max(0, agent.currentTasks - 1);
      
      // 更新性能指标
      this.updatePerformanceMetrics(agent, success, responseTime);
    }
  }

  /**
   * 更新性能指标
   * @param {Object} agent - 代理对象
   * @param {boolean} success - 是否成功
   * @param {number} responseTime - 响应时间
   */
  updatePerformanceMetrics(agent, success, responseTime) {
    // 更新成功率（滑动平均）
    agent.successRate = agent.successRate * 0.9 + (success ? 1 : 0) * 0.1;
    
    // 更新平均响应时间（滑动平均）
    agent.avgResponseTime = agent.avgResponseTime * 0.9 + responseTime * 0.1;
  }

  /**
   * 获取团队状态报告
   * @returns {Object} 团队状态
   */
  getTeamStatus() {
    const totalAgents = this.agents.size;
    const activeAgents = Array.from(this.agents.values())
      .filter(agent => agent.currentTasks > 0).length;
    const totalTasks = Array.from(this.agents.values())
      .reduce((sum, agent) => sum + agent.currentTasks, 0);
    
    return {
      totalAgents,
      activeAgents,
      totalTasks,
      averageSuccessRate: this.getAverageSuccessRate(),
      averageResponseTime: this.getAverageResponseTime()
    };
  }

  /**
   * 获取平均成功率
   * @returns {number}
   */
  getAverageSuccessRate() {
    if (this.agents.size === 0) return 0;
    const total = Array.from(this.agents.values())
      .reduce((sum, agent) => sum + agent.successRate, 0);
    return total / this.agents.size;
  }

  /**
   * 获取平均响应时间
   * @returns {number}
   */
  getAverageResponseTime() {
    if (this.agents.size === 0) return 0;
    const total = Array.from(this.agents.values())
      .reduce((sum, agent) => sum + agent.avgResponseTime, 0);
    return total / this.agents.size;
  }
}

module.exports = TaskAllocator;

path: quality-controller.js
content: /**
 * AI Agent Team Manager - Quality Control Module
 * 
 * Implements comprehensive quality control for AI agent teams
 * Based on Otter Camp best practices and real-world experience
 */

class QualityController {
  constructor(config = {}) {
    this.config = {
      // Quality thresholds
      accuracyThreshold: config.accuracyThreshold || 0.95,
      completenessThreshold: config.completenessThreshold || 0.90,
      timelinessThreshold: config.timelinessThreshold || 0.85,
      
      // Review settings
      enablePeerReview: config.enablePeerReview !== false,
      enableHumanReview: config.enableHumanReview || false,
      reviewDepth: config.reviewDepth || 'comprehensive',
      
      // Performance metrics
      trackMetrics: config.trackMetrics !== false,
      performanceWindow: config.performanceWindow || 30, // days
      
      ...config
    };
    
    this.qualityStandards = this.loadQualityStandards();
    this.reviewCheckpoints = this.setupReviewCheckpoints();
  }

  /**
   * Load quality standards from configuration or defaults
   */
  loadQualityStandards() {
    return {
      // Output quality standards
      output: {
        accuracy: {
          description: "Factual accuracy and correctness",
          weight: 0.4,
          minScore: this.config.accuracyThreshold
        },
        completeness: {
          description: "Coverage of all required elements",
          weight: 0.3,
          minScore: this.config.completenessThreshold
        },
        clarity: {
          description: "Clear, concise, and well-structured",
          weight: 0.2,
          minScore: 0.8
        },
        relevance: {
          description: "Relevant to the original task",
          weight: 0.1,
          minScore: 0.9
        }
      },
      
      // Process quality standards
      process: {
        methodology: {
          description: "Sound methodology and approach",
          weight: 0.3,
          minScore: 0.85
        },
        documentation: {
          description: "Adequate documentation and reasoning",
          weight: 0.2,
          minScore: 0.8
        },
        efficiency: {
          description: "Resource and time efficiency",
          weight: 0.2,
          minScore: 0.75
        },
        compliance: {
          description: "Adherence to guidelines and constraints",
          weight: 0.3,
          minScore: 0.9
        }
      }
    };
  }

  /**
   * Setup automatic review checkpoints based on task complexity
   */
  setupReviewCheckpoints() {
    return {
      // Critical tasks: Full peer review + human review if enabled
      critical: {
        peerReview: true,
        humanReview: this.config.enableHumanReview,
        automatedChecks: ['accuracy', 'completeness', 'compliance']
      },
      
      // High priority tasks: Peer review + comprehensive automated checks
      high: {
        peerReview: true,
        humanReview: false,
        automatedChecks: ['accuracy', 'completeness', 'clarity', 'relevance']
      },
      
      // Medium priority tasks: Automated checks + spot peer review
      medium: {
        peerReview: 'spot', // Random selection for peer review
        humanReview: false,
        automatedChecks: ['accuracy', 'completeness']
      },
      
      // Low priority tasks: Basic automated checks only
      low: {
        peerReview: false,
        humanReview: false,
        automatedChecks: ['accuracy']
      }
    };
  }

  /**
   * Perform comprehensive quality assessment on agent output
   */
  async assessQuality(agentOutput, taskSpec, agentId) {
    const assessment = {
      taskId: taskSpec.id,
      agentId: agentId,
      timestamp: new Date().toISOString(),
      overallScore: 0,
      categoryScores: {},
      issues: [],
      recommendations: [],
      pass: false
    };

    // Assess output quality
    const outputAssessment = await this.assessOutputQuality(agentOutput, taskSpec);
    assessment.categoryScores.output = outputAssessment;
    
    // Assess process quality (if process logs available)
    if (taskSpec.processLogs) {
      const processAssessment = await this.assessProcessQuality(taskSpec.processLogs, taskSpec);
      assessment.categoryScores.process = processAssessment;
    }

    // Calculate overall score
    assessment.overallScore = this.calculateOverallScore(assessment.categoryScores);
    
    // Identify issues and recommendations
    assessment.issues = this.identifyIssues(assessment.categoryScores);
    assessment.recommendations = this.generateRecommendations(assessment.issues);
    
    // Determine if task passes quality threshold
    assessment.pass = assessment.overallScore >= this.config.accuracyThreshold;
    
    return assessment;
  }

  /**
   * Assess output quality against standards
   */
  async assessOutputQuality(output, taskSpec) {
    const scores = {};
    const weights = {};
    
    // Accuracy assessment
    scores.accuracy = await this.assessAccuracy(output, taskSpec);
    weights.accuracy = this.qualityStandards.output.accuracy.weight;
    
    // Completeness assessment  
    scores.completeness = await this.assessCompleteness(output, taskSpec);
    weights.completeness = this.qualityStandards.output.completeness.weight;
    
    // Clarity assessment
    scores.clarity = await this.assessClarity(output);
    weights.clarity = this.qualityStandards.output.clarity.weight;
    
    // Relevance assessment
    scores.relevance = await this.assessRelevance(output, taskSpec);
    weights.relevance = this.qualityStandards.output.relevance.weight;
    
    return {
      scores,
      weights,
      weightedAverage: this.calculateWeightedAverage(scores, weights)
    };
  }

  /**
   * Assess process quality from logs
   */
  async assessProcessQuality(processLogs, taskSpec) {
    const scores = {};
    const weights = {};
    
    // Methodology assessment
    scores.methodology = await this.assessMethodology(processLogs, taskSpec);
    weights.methodology = this.qualityStandards.process.methodology.weight;
    
    // Documentation assessment
    scores.documentation = await this.assessDocumentation(processLogs);
    weights.documentation = this.qualityStandards.process.documentation.weight;
    
    // Efficiency assessment
    scores.efficiency = await this.assessEfficiency(processLogs);
    weights.efficiency = this.qualityStandards.process.efficiency.weight;
    
    // Compliance assessment
    scores.compliance = await this.assessCompliance(processLogs, taskSpec);
    weights.compliance = this.qualityStandards.process.compliance.weight;
    
    return {
      scores,
      weights,
      weightedAverage: this.calculateWeightedAverage(scores, weights)
    };
  }

  /**
   * Assess factual accuracy of output
   */
  async assessAccuracy(output, taskSpec) {
    // Implementation would use fact-checking APIs, knowledge bases, etc.
    // For now, using heuristic assessment
    
    let score = 1.0;
    const issues = [];
    
    // Check for obvious hallucinations or contradictions
    if (this.containsHallucinations(output, taskSpec)) {
      score -= 0.3;
      issues.push('Potential hallucinations detected');
    }
    
    // Check for consistency with provided context
    if (!this.isConsistentWithContext(output, taskSpec.context)) {
      score -= 0.2;
      issues.push('Inconsistent with provided context');
    }
    
    // Check for logical errors
    if (this.containsLogicalErrors(output)) {
      score -= 0.15;
      issues.push('Logical inconsistencies detected');
    }
    
    // Ensure score doesn't go below 0
    score = Math.max(0, score);
    
    return {
      score,
      maxScore: 1.0,
      issues,
      confidence: this.calculateConfidence(issues.length)
    };
  }

  /**
   * Assess completeness of output
   */
  async assessCompleteness(output, taskSpec) {
    const requiredElements = taskSpec.requiredElements || [];
    let completeness = 1.0;
    const missingElements = [];
    
    for (const element of requiredElements) {
      if (!this.containsElement(output, element)) {
        completeness -= 1.0 / requiredElements.length;
        missingElements.push(element);
      }
    }
    
    return {
      score: Math.max(0, completeness),
      maxScore: 1.0,
      missingElements,
      coverage: requiredElements.length > 0 ? 
        (requiredElements.length - missingElements.length) / requiredElements.length : 1.0
    };
  }

  /**
   * Assess clarity and structure
   */
  async assessClarity(output) {
    // Assess readability, structure, and coherence
    const readabilityScore = this.calculateReadability(output);
    const structureScore = this.assessStructure(output);
    const coherenceScore = this.assessCoherence(output);
    
    const clarity = (readabilityScore + structureScore + coherenceScore) / 3;
    
    return {
      score: clarity,
      maxScore: 1.0,
      readability: readabilityScore,
      structure: structureScore,
      coherence: coherenceScore
    };
  }

  /**
   * Assess relevance to original task
   */
  async assessRelevance(output, taskSpec) {
    const taskKeywords = this.extractKeywords(taskSpec.description);
    const outputKeywords = this.extractKeywords(output);
    
    const relevance = this.calculateKeywordOverlap(taskKeywords, outputKeywords);
    
    return {
      score: relevance,
      maxScore: 1.0,
      keywordMatch: relevance,
      offTopicPenalty: this.calculateOffTopicPenalty(output, taskSpec)
    };
  }

  /**
   * Assess methodology quality from process logs
   */
  async assessMethodology(processLogs, taskSpec) {
    // Check if agent followed appropriate methodology
    const methodology = processLogs.methodology || 'unknown';
    const expectedMethodology = taskSpec.expectedMethodology || 'flexible';
    
    if (expectedMethodology === 'flexible') {
      return { score: 0.9, maxScore: 1.0, notes: 'Flexible methodology accepted' };
    }
    
    const matchScore = this.calculateMethodologyMatch(methodology, expectedMethodology);
    
    return {
      score: matchScore,
      maxScore: 1.0,
      methodologyUsed: methodology,
      methodologyExpected: expectedMethodology
    };
  }

  /**
   * Assess documentation quality
   */
  async assessDocumentation(processLogs) {
    const hasReasoning = !!processLogs.reasoning;
    const hasSteps = !!processLogs.steps;
    const hasSources = !!processLogs.sources;
    
    let documentationScore = 0;
    if (hasReasoning) documentationScore += 0.4;
    if (hasSteps) documentationScore += 0.3;
    if (hasSources) documentationScore += 0.3;
    
    return {
      score: documentationScore,
      maxScore: 1.0,
      hasReasoning,
      hasSteps,
      hasSources
    };
  }

  /**
   * Assess efficiency from process logs
   */
  async assessEfficiency(processLogs) {
    const executionTime = processLogs.executionTime || 0;
    const tokenUsage = processLogs.tokenUsage || 0;
    const toolCalls = processLogs.toolCalls || 0;
    
    // Normalize against task complexity
    const complexity = processLogs.taskComplexity || 1;
    const timeEfficiency = Math.max(0, 1 - (executionTime / (complexity * 300))); // 5 minutes per complexity unit
    const resourceEfficiency = Math.max(0, 1 - (tokenUsage / (complexity * 10000))); // 10k tokens per complexity unit
    const toolEfficiency = Math.max(0, 1 - (toolCalls / (complexity * 10))); // 10 tool calls per complexity unit
    
    const efficiency = (timeEfficiency + resourceEfficiency + toolEfficiency) / 3;
    
    return {
      score: efficiency,
      maxScore: 1.0,
      timeEfficiency,
      resourceEfficiency,
      toolEfficiency,
      executionTime,
      tokenUsage,
      toolCalls
    };
  }

  /**
   * Assess compliance with guidelines
   */
  async assessCompliance(processLogs, taskSpec) {
    const guidelines = taskSpec.guidelines || [];
    let compliance = 1.0;
    const violations = [];
    
    for (const guideline of guidelines) {
      if (!this.compliesWithGuideline(processLogs, guideline)) {
        compliance -= 1.0 / guidelines.length;
        violations.push(guideline);
      }
    }
    
    return {
      score: Math.max(0, compliance),
      maxScore: 1.0,
      violations,
      complianceRate: guidelines.length > 0 ? 
        (guidelines.length - violations.length) / guidelines.length : 1.0
    };
  }

  /**
   * Calculate overall quality score
   */
  calculateOverallScore(categoryScores) {
    if (!categoryScores.output) return 0;
    
    let totalScore = 0;
    let totalWeight = 0;
    
    // Output quality (70% weight)
    totalScore += categoryScores.output.weightedAverage * 0.7;
    totalWeight += 0.7;
    
    // Process quality (30% weight) if available
    if (categoryScores.process) {
      totalScore += categoryScores.process.weightedAverage * 0.3;
      totalWeight += 0.3;
    }
    
    return totalWeight > 0 ? totalScore / totalWeight : 0;
  }

  /**
   * Calculate weighted average of scores
   */
  calculateWeightedAverage(scores, weights) {
    let total = 0;
    let weightSum = 0;
    
    for (const [key, score] of Object.entries(scores)) {
      const weight = weights[key] || 0;
      total += score * weight;
      weightSum += weight;
    }
    
    return weightSum > 0 ? total / weightSum : 0;
  }

  /**
   * Identify quality issues from assessment
   */
  identifyIssues(categoryScores) {
    const issues = [];
    
    if (categoryScores.output) {
      const output = categoryScores.output.scores;
      const standards = this.qualityStandards.output;
      
      if (output.accuracy < standards.accuracy.minScore) {
        issues.push({
          category: 'accuracy',
          severity: 'high',
          description: `Accuracy below threshold (${output.accuracy.toFixed(2)} < ${standards.accuracy.minScore})`
        });
      }
      
      if (output.completeness < standards.completeness.minScore) {
        issues.push({
          category: 'completeness', 
          severity: 'medium',
          description: `Completeness below threshold (${output.completeness.toFixed(2)} < ${standards.completeness.minScore})`
        });
      }
      
      if (output.clarity < standards.clarity.minScore) {
        issues.push({
          category: 'clarity',
          severity: 'low',
          description: `Clarity below threshold (${output.clarity.toFixed(2)} < ${standards.clarity.minScore})`
        });
      }
    }
    
    if (categoryScores.process) {
      const process = categoryScores.process.scores;
      const standards = this.qualityStandards.process;
      
      if (process.compliance < standards.compliance.minScore) {
        issues.push({
          category: 'compliance',
          severity: 'high',
          description: `Compliance below threshold (${process.compliance.toFixed(2)} < ${standards.compliance.minScore})`
        });
      }
    }
    
    return issues;
  }

  /**
   * Generate recommendations based on identified issues
   */
  generateRecommendations(issues) {
    const recommendations = [];
    
    const issueMap = {
      accuracy: 'Review fact-checking procedures and verify sources',
      completeness: 'Ensure all required elements are addressed in output',
      clarity: 'Improve structure and readability of responses',
      compliance: 'Strictly adhere to provided guidelines and constraints'
    };
    
    for (const issue of issues) {
      recommendations.push({
        issue: issue.category,
        recommendation: issueMap[issue.category] || 'General quality improvement needed',
        priority: issue.severity
      });
    }
    
    return recommendations;
  }

  /**
   * Determine if peer review is needed based on task priority
   */
  needsPeerReview(taskPriority) {
    const checkpoint = this.reviewCheckpoints[taskPriority] || this.reviewCheckpoints.medium;
    return checkpoint.peerReview;
  }

  /**
   * Determine if human review is needed
   */
  needsHumanReview(taskPriority) {
    const checkpoint = this.reviewCheckpoints[taskPriority] || this.reviewCheckpoints.medium;
    return checkpoint.humanReview;
  }

  /**
   * Get required automated checks for task priority
   */
  getRequiredAutomatedChecks(taskPriority) {
    const checkpoint = this.reviewCheckpoints[taskPriority] || this.reviewCheckpoints.medium;
    return checkpoint.automatedChecks;
  }

  // Helper methods (simplified implementations)
  containsHallucinations(output, taskSpec) {
    // Simplified check - in reality would use more sophisticated methods
    return output.toLowerCase().includes('i made up') || 
           output.toLowerCase().includes('fictional') ||
           this.hasInconsistentClaims(output);
  }
  
  isConsistentWithContext(output, context) {
    if (!context) return true;
    // Check if output contradicts context
    return !this.hasContradictions(output, context);
  }
  
  containsLogicalErrors(output) {
    // Simplified logic error detection
    return this.hasInternalContradictions(output);
  }
  
  containsElement(output, element) {
    return output.toLowerCase().includes(element.toLowerCase());
  }
  
  calculateReadability(output) {
    // Simplified readability calculation
    const words = output.split(/\s+/).length;
    const sentences = output.split(/[.!?]+/).length;
    const avgWordsPerSentence = words / Math.max(1, sentences);
    // Prefer 10-20 words per sentence
    if (avgWordsPerSentence >= 10 && avgWordsPerSentence <= 20) return 0.9;
    if (avgWordsPerSentence >= 5 && avgWordsPerSentence <= 25) return 0.7;
    return 0.5;
  }
  
  assessStructure(output) {
    // Check for clear structure (headings, paragraphs, lists)
    const hasHeadings = /[#*].+\n/.test(output);
    const hasParagraphs = output.split('\n\n').length > 2;
    const hasLists = /[-*]\s/.test(output) || /\d+\.\s/.test(output);
    
    let score = 0.3; // Base score
    if (hasHeadings) score += 0.3;
    if (hasParagraphs) score += 0.2;  
    if (hasLists) score += 0.2;
    
    return Math.min(1.0, score);
  }
  
  assessCoherence(output) {
    // Check for logical flow and transitions
    const transitionWords = ['however', 'therefore', 'furthermore', 'consequently', 'meanwhile'];
    const hasTransitions = transitionWords.some(word => 
      output.toLowerCase().includes(word)
    );
    
    return hasTransitions ? 0.8 : 0.6;
  }
  
  extractKeywords(text) {
    // Simple keyword extraction
    const words = text.toLowerCase().match(/\b\w{3,}\b/g) || [];
    const commonWords = new Set(['the', 'and', 'for', 'are', 'but', 'not', 'you', 'all', 'can', 'had', 'her', 'was', 'one', 'our', 'out', 'day', 'get', 'has', 'him', 'his', 'how', 'its', 'may', 'new', 'now', 'old', 'see', 'two', 'who', 'boy', 'did', 'she', 'use', 'way', 'will', 'too']);
    return words.filter(word => !commonWords.has(word));
  }
  
  calculateKeywordOverlap(keywords1, keywords2) {
    if (keywords1.length === 0 || keywords2.length === 0) return 0;
    const set1 = new Set(keywords1);
    const set2 = new Set(keywords2);
    const intersection = new Set([...set1].filter(x => set2.has(x)));
    return intersection.size / Math.max(set1.size, set2.size);
  }
  
  calculateOffTopicPenalty(output, taskSpec) {
    // Simplified off-topic detection
    const taskWords = this.extractKeywords(taskSpec.description);
    const outputWords = this.extractKeywords(output);
    const overlap = this.calculateKeywordOverlap(taskWords, outputWords);
    return Math.max(0, 1 - overlap);
  }
  
  calculateMethodologyMatch(actual, expected) {
    // Simplified methodology matching
    return actual.toLowerCase() === expected.toLowerCase() ? 1.0 : 0.5;
  }
  
  compliesWithGuideline(processLogs, guideline) {
    // Simplified compliance check
    return processLogs.guidelinesFollowed?.includes(guideline) || 
           !processLogs.guidelinesViolated?.includes(guideline);
  }
  
  hasInconsistentClaims(output) {
    // Very simplified inconsistency detection
    return false; // Would need more sophisticated NLP in reality
  }
  
  hasContradictions(output, context) {
    return false; // Would need more sophisticated NLP in reality  
  }
  
  hasInternalContradictions(output) {
    return false; // Would need more sophisticated NLP in reality
  }
  
  calculateConfidence(issueCount) {
    if (issueCount === 0) return 0.95;
    if (issueCount === 1) return 0.85;
    if (issueCount === 2) return 0.75;
    return 0.6;
  }
}

module.exports = QualityController;

path: progress-tracker.js
content: /**
 * AI Agent Team Manager - Progress Tracker Module
 * 
 * 跟踪AI代理团队的工作进度，提供实时状态更新和性能指标
 */

class ProgressTracker {
  constructor() {
    this.tasks = new Map();
    this.agents = new Map();
    this.metrics = {
      completedTasks: 0,
      failedTasks: 0,
      avgCompletionTime: 0,
      successRate: 0
    };
  }

  /**
   * 初始化任务跟踪
   * @param {string} taskId - 任务ID
   * @param {Object} taskInfo - 任务信息
   */
  initializeTask(taskId, taskInfo) {
    this.tasks.set(taskId, {
      id: taskId,
      name: taskInfo.name,
      description: taskInfo.description,
      assignedAgent: taskInfo.assignedAgent,
      status: 'pending',
      startTime: null,
      endTime: null,
      progress: 0,
      milestones: taskInfo.milestones || [],
      currentMilestone: 0,
      logs: []
    });
  }

  /**
   * 更新任务状态
   * @param {string} taskId - 任务ID
   * @param {string} status - 状态 ('pending', 'in_progress', 'completed', 'failed')
   * @param {number} progress - 进度百分比 (0-100)
   */
  updateTaskStatus(taskId, status, progress = 0) {
    const task = this.tasks.get(taskId);
    if (!task) {
      console.warn(`Task ${taskId} not found`);
      return;
    }

    task.status = status;
    task.progress = progress;

    if (status === 'in_progress' && !task.startTime) {
      task.startTime = new Date().toISOString();
    }

    if (status === 'completed' || status === 'failed') {
      task.endTime = new Date().toISOString();
      this.updateMetrics(task);
    }

    this.logTaskActivity(taskId, `Status updated to: ${status}, Progress: ${progress}%`);
  }

  /**
   * 记录里程碑完成
   * @param {string} taskId - 任务ID
   * @param {number} milestoneIndex - 里程碑索引
   */
  completeMilestone(taskId, milestoneIndex) {
    const task = this.tasks.get(taskId);
    if (!task) return;

    if (milestoneIndex >= task.milestones.length) {
      console.warn(`Invalid milestone index ${milestoneIndex} for task ${taskId}`);
      return;
    }

    task.currentMilestone = milestoneIndex + 1;
    const milestone = task.milestones[milestoneIndex];
    this.logTaskActivity(taskId, `Milestone completed: ${milestone.name}`);
  }

  /**
   * 注册代理信息
   * @param {string} agentId - 代理ID
   * @param {Object} agentInfo - 代理信息
   */
  registerAgent(agentId, agentInfo) {
    this.agents.set(agentId, {
      id: agentId,
      name: agentInfo.name,
      role: agentInfo.role,
      capabilities: agentInfo.capabilities,
      currentTasks: [],
      performance: {
        completedTasks: 0,
        failedTasks: 0,
        avgResponseTime: 0
      }
    });
  }

  /**
   * 分配任务给代理
   * @param {string} taskId - 任务ID
   * @param {string} agentId - 代理ID
   */
  assignTaskToAgent(taskId, agentId) {
    const task = this.tasks.get(taskId);
    const agent = this.agents.get(agentId);

    if (!task || !agent) {
      console.warn(`Task ${taskId} or agent ${agentId} not found`);
      return;
    }

    task.assignedAgent = agentId;
    agent.currentTasks.push(taskId);
    this.logTaskActivity(taskId, `Assigned to agent: ${agent.name}`);
  }

  /**
   * 获取任务详细状态
   * @param {string} taskId - 任务ID
   * @returns {Object} 任务状态详情
   */
  getTaskStatus(taskId) {
    return this.tasks.get(taskId) || null;
  }

  /**
   * 获取所有任务摘要
   * @returns {Object} 任务摘要信息
   */
  getAllTasksSummary() {
    const summary = {
      totalTasks: this.tasks.size,
      pending: 0,
      inProgress: 0,
      completed: 0,
      failed: 0,
      tasks: []
    };

    for (const task of this.tasks.values()) {
      switch (task.status) {
        case 'pending':
          summary.pending++;
          break;
        case 'in_progress':
          summary.inProgress++;
          break;
        case 'completed':
          summary.completed++;
          break;
        case 'failed':
          summary.failed++;
          break;
      }

      summary.tasks.push({
        id: task.id,
        name: task.name,
        status: task.status,
        progress: task.progress,
        assignedAgent: task.assignedAgent,
        startTime: task.startTime,
        endTime: task.endTime
      });
    }

    return summary;
  }

  /**
   * 获取代理性能报告
   * @param {string} agentId - 代理ID
   * @returns {Object} 代理性能报告
   */
  getAgentPerformance(agentId) {
    const agent = this.agents.get(agentId);
    if (!agent) return null;

    return {
      id: agent.id,
      name: agent.name,
      role: agent.role,
      currentTasks: agent.currentTasks.length,
      completedTasks: agent.performance.completedTasks,
      failedTasks: agent.performance.failedTasks,
      successRate: agent.performance.completedTasks > 0 ? 
        (agent.performance.completedTasks / (agent.performance.completedTasks + agent.performance.failedTasks)) * 100 : 0,
      avgResponseTime: agent.performance.avgResponseTime
    };
  }

  /**
   * 获取团队整体性能
   * @returns {Object} 团队性能报告
   */
  getTeamPerformance() {
    let totalCompleted = 0;
    let totalFailed = 0;
    let totalResponseTime = 0;
    let activeAgents = 0;

    for (const agent of this.agents.values()) {
      totalCompleted += agent.performance.completedTasks;
      totalFailed += agent.performance.failedTasks;
      totalResponseTime += agent.performance.avgResponseTime;
      if (agent.currentTasks.length > 0) {
        activeAgents++;
      }
    }

    const totalTasks = totalCompleted + totalFailed;
    const successRate = totalTasks > 0 ? (totalCompleted / totalTasks) * 100 : 0;
    const avgResponseTime = this.agents.size > 0 ? totalResponseTime / this.agents.size : 0;

    return {
      totalAgents: this.agents.size,
      activeAgents: activeAgents,
      totalTasks: totalTasks,
      completedTasks: totalCompleted,
      failedTasks: totalFailed,
      successRate: successRate,
      avgResponseTime: avgResponseTime,
      teamEfficiency: this.calculateTeamEfficiency()
    };
  }

  /**
   * 计算团队效率评分
   * @returns {number} 效率评分 (0-100)
   */
  calculateTeamEfficiency() {
    const performance = this.getTeamPerformance();
    // 综合考虑成功率、响应时间和活跃度
    const successWeight = 0.5;
    const responseWeight = 0.3;
    const activityWeight = 0.2;

    const successScore = performance.successRate;
    const responseScore = Math.max(0, 100 - (performance.avgResponseTime / 1000)); // 假设响应时间以毫秒为单位
    const activityScore = (performance.activeAgents / performance.totalAgents) * 100;

    return (successScore * successWeight) + (responseScore * responseWeight) + (activityScore * activityWeight);
  }

  /**
   * 记录任务活动日志
   * @param {string} taskId - 任务ID
   * @param {string} activity - 活动描述
   */
  logTaskActivity(taskId, activity) {
    const task = this.tasks.get(taskId);
    if (!task) return;

    task.logs.push({
      timestamp: new Date().toISOString(),
      activity: activity
    });

    // 限制日志数量，避免内存溢出
    if (task.logs.length > 100) {
      task.logs = task.logs.slice(-100);
    }
  }

  /**
   * 生成进度报告
   * @param {string} format - 报告格式 ('json', 'markdown', 'html')
   * @returns {string} 格式化的进度报告
   */
  generateProgressReport(format = 'json') {
    const summary = this.getAllTasksSummary();
    const teamPerformance = this.getTeamPerformance();

    switch (format) {
      case 'json':
        return JSON.stringify({
          summary: summary,
          teamPerformance: teamPerformance,
          timestamp: new Date().toISOString()
        }, null, 2);

      case 'markdown':
        return this.generateMarkdownReport(summary, teamPerformance);

      case 'html':
        return this.generateHtmlReport(summary, teamPerformance);

      default:
        return JSON.stringify({ error: 'Unsupported format' });
    }
  }

  /**
   * 生成Markdown格式报告
   */
  generateMarkdownReport(summary, teamPerformance) {
    return `
# AI Agent Team Progress Report

**Generated:** ${new Date().toISOString()}

## Team Performance
- **Total Agents:** ${teamPerformance.totalAgents}
- **Active Agents:** ${teamPerformance.activeAgents}
- **Success Rate:** ${teamPerformance.successRate.toFixed(2)}%
- **Team Efficiency:** ${teamPerformance.teamEfficiency.toFixed(2)}%
- **Average Response Time:** ${teamPerformance.avgResponseTime.toFixed(2)}ms

## Task Summary
- **Total Tasks:** ${summary.totalTasks}
- **Completed:** ${summary.completed}
- **In Progress:** ${summary.inProgress}
- **Pending:** ${summary.pending}
- **Failed:** ${summary.failed}

## Current Tasks
${summary.tasks.map(task => `- **${task.name}**: ${task.status} (${task.progress}%) - Assigned to: ${task.assignedAgent}`).join('\n')}

---
*Report generated by AI Agent Team Manager*
`;
  }

  /**
   * 生成HTML格式报告
   */
  generateHtmlReport(summary, teamPerformance) {
    return `
<!DOCTYPE html>
<html>
<head>
    <title>AI Agent Team Progress Report</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .section { margin-bottom: 20px; }
        .metric { display: inline-block; margin-right: 20px; }
        .task-item { margin: 5px 0; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>AI Agent Team Progress Report</h1>
    <p><strong>Generated:</strong> ${new Date().toISOString()}</p>

    <div class="section">
        <h2>Team Performance</h2>
        <div class="metric"><strong>Total Agents:</strong> ${teamPerformance.totalAgents}</div>
        <div class="metric"><strong>Active Agents:</strong> ${teamPerformance.activeAgents}</div>
        <div class="metric"><strong>Success Rate:</strong> ${teamPerformance.successRate.toFixed(2)}%</div>
        <div class="metric"><strong>Team Efficiency:</strong> ${teamPerformance.teamEfficiency.toFixed(2)}%</div>
        <div class="metric"><strong>Avg Response Time:</strong> ${teamPerformance.avgResponseTime.toFixed(2)}ms</div>
    </div>

    <div class="section">
        <h2>Task Summary</h2>
        <div class="metric"><strong>Total Tasks:</strong> ${summary.totalTasks}</div>
        <div class="metric"><strong>Completed:</strong> ${summary.completed}</div>
        <div class="metric"><strong>In Progress:</strong> ${summary.inProgress}</div>
        <div class="metric"><strong>Pending:</strong> ${summary.pending}</div>
        <div class="metric"><strong>Failed:</strong> ${summary.failed}</div>
    </div>

    <div class="section">
        <h2>Current Tasks</h2>
        <table>
            <thead>
                <tr>
                    <th>Task Name</th>
                    <th>Status</th>
                    <th>Progress</th>
                    <th>Assigned Agent</th>
                </tr>
            </thead>
            <tbody>
                ${summary.tasks.map(task => `
                <tr>
                    <td>${task.name}</td>
                    <td>${task.status}</td>
                    <td>${task.progress}%</td>
                    <td>${task.assignedAgent}</td>
                </tr>
                `).join('')}
            </tbody>
        </table>
    </div>
</body>
</html>
`;
  }

  /**
   * 导出进度数据
   * @param {string} filePath - 导出文件路径
   * @param {string} format - 导出格式
   */
  async exportProgressData(filePath, format = 'json') {
    const report = this.generateProgressReport(format);
    // 这里需要集成文件系统操作
    console.log(`Exporting progress data to ${filePath} in ${format} format`);
    return report;
  }
}

module.exports = ProgressTracker;

path: example-usage.js
content: // AI Agent Team Manager - 使用示例

const { 
  TaskAllocator, 
  ProgressTracker, 
  QualityController,
  PerformanceEvaluator,
  TeamCoordinator,
  WorkflowManager,
  ProjectManager
} = require('./index');

// 1. 创建团队管理实例
const teamManager = new TeamCoordinator({
  teamName: "Otter Camp Team",
  members: [
    { name: "小吕", role: "运维监控专家", skills: ["monitoring", "devops"] },
    { name: "老狗", role: "程序开发专家", skills: ["coding", "debugging"] },
    { name: "小朱", role: "AI产品经理", skills: ["product", "design"] },
    { name: "小秋", role: "商业价值调研专家", skills: ["research", "analysis"] }
  ]
});

// 2. 创建项目
const project = new ProjectManager({
  projectName: "OpenClaw Skill Development",
  description: "开发赚钱的OpenClaw技能包",
  deadline: "2026-03-10"
});

// 3. 分配任务
const tasks = [
  {
    id: "task-001",
    title: "Chinese Content Creator 开发",
    assignee: "小朱",
    priority: "high",
    estimatedHours: 8
  },
  {
    id: "task-002", 
    title: "Security Auditor 开发",
    assignee: "老狗",
    priority: "high",
    estimatedHours: 12
  },
  {
    id: "task-003",
    title: "E-commerce Automation 开发", 
    assignee: "小秋",
    priority: "medium",
    estimatedHours: 10
  }
];

const allocator = new TaskAllocator(teamManager);
allocator.assignTasks(tasks);

// 4. 跟踪进度
const tracker = new ProgressTracker(project);
tracker.updateProgress("task-001", 100); // 完成
tracker.updateProgress("task-002", 80);  // 进行中
tracker.updateProgress("task-003", 60);  // 进行中

// 5. 质量控制
const qualityController = new QualityController();
qualityController.reviewTask("task-001", {
  codeQuality: 95,
  documentation: 90,
  testing: 85
});

// 6. 性能评估
const evaluator = new PerformanceEvaluator(teamManager);
const performanceReport = evaluator.generateReport();

// 7. 工作流管理
const workflow = new WorkflowManager({
  stages: ["planning", "development", "review", "testing", "deployment"]
});
workflow.advanceStage("task-001", "deployment");

console.log("AI Agent Team Manager 使用示例完成！");
console.log("项目进度:", tracker.getOverallProgress());
console.log("团队绩效:", performanceReport.overallScore);

path: project-manager.js
content: /**
 * AI Agent Team Manager - Project Manager Module
 * 
 * 负责AI代理团队的项目管理，包括任务分解、进度跟踪、资源分配等
 */

class ProjectManager {
  constructor() {
    this.projects = new Map();
    this.tasks = new Map();
    this.agents = new Map();
  }

  /**
   * 创建新项目
   * @param {Object} projectConfig - 项目配置
   * @param {string} projectConfig.name - 项目名称
   * @param {string} projectConfig.description - 项目描述
   * @param {Array} projectConfig.teamMembers - 团队成员列表
   * @param {Object} projectConfig.deadlines - 截止日期配置
   */
  createProject(projectConfig) {
    const projectId = this.generateProjectId();
    const project = {
      id: projectId,
      name: projectConfig.name,
      description: projectConfig.description,
      status: 'active',
      createdAt: new Date().toISOString(),
      teamMembers: projectConfig.teamMembers || [],
      deadlines: projectConfig.deadlines || {},
      milestones: [],
      tasks: [],
      metrics: {
        completionRate: 0,
        qualityScore: 0,
        efficiency: 0
      }
    };
    
    this.projects.set(projectId, project);
    return projectId;
  }

  /**
   * 分解项目为任务
   * @param {string} projectId - 项目ID
   * @param {Array} taskList - 任务列表
   */
  decomposeProject(projectId, taskList) {
    const project = this.projects.get(projectId);
    if (!project) {
      throw new Error(`Project ${projectId} not found`);
    }

    const tasks = taskList.map(task => {
      const taskId = this.generateTaskId();
      const taskObj = {
        id: taskId,
        projectId: projectId,
        title: task.title,
        description: task.description,
        status: 'pending',
        priority: task.priority || 'medium',
        assignee: task.assignee || null,
        dependencies: task.dependencies || [],
        estimatedTime: task.estimatedTime || 0,
        actualTime: 0,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };
      
      this.tasks.set(taskId, taskObj);
      project.tasks.push(taskId);
      return taskId;
    });

    this.projects.set(projectId, project);
    return tasks;
  }

  /**
   * 分配任务给代理
   * @param {string} taskId - 任务ID
   * @param {string} agentId - 代理ID
   */
  assignTask(taskId, agentId) {
    const task = this.tasks.get(taskId);
    if (!task) {
      throw new Error(`Task ${taskId} not found`);
    }

    task.assignee = agentId;
    task.status = 'assigned';
    task.updatedAt = new Date().toISOString();
    this.tasks.set(taskId, task);

    // 更新代理的任务列表
    if (!this.agents.has(agentId)) {
      this.agents.set(agentId, {
        id: agentId,
        tasks: [],
        performance: {
          completedTasks: 0,
          averageQuality: 0,
          efficiency: 0
        }
      });
    }

    const agent = this.agents.get(agentId);
    agent.tasks.push(taskId);
    this.agents.set(agentId, agent);

    return true;
  }

  /**
   * 更新任务状态
   * @param {string} taskId - 任务ID
   * @param {string} status - 新状态
   * @param {Object} updates - 其他更新信息
   */
  updateTaskStatus(taskId, status, updates = {}) {
    const task = this.tasks.get(taskId);
    if (!task) {
      throw new Error(`Task ${taskId} not found`);
    }

    task.status = status;
    task.updatedAt = new Date().toISOString();
    
    // 应用其他更新
    Object.keys(updates).forEach(key => {
      task[key] = updates[key];
    });

    this.tasks.set(taskId, task);
    
    // 如果任务完成，更新项目进度
    if (status === 'completed') {
      this.updateProjectProgress(task.projectId);
    }

    return true;
  }

  /**
   * 更新项目进度
   * @param {string} projectId - 项目ID
   */
  updateProjectProgress(projectId) {
    const project = this.projects.get(projectId);
    if (!project) {
      throw new Error(`Project ${projectId} not found`);
    }

    const totalTasks = project.tasks.length;
    if (totalTasks === 0) {
      project.metrics.completionRate = 100;
    } else {
      const completedTasks = project.tasks.filter(taskId => {
        const task = this.tasks.get(taskId);
        return task && task.status === 'completed';
      }).length;
      
      project.metrics.completionRate = (completedTasks / totalTasks) * 100;
    }

    this.projects.set(projectId, project);
    return project.metrics.completionRate;
  }

  /**
   * 获取项目报告
   * @param {string} projectId - 项目ID
   */
  getProjectReport(projectId) {
    const project = this.projects.get(projectId);
    if (!project) {
      throw new Error(`Project ${projectId} not found`);
    }

    const report = {
      projectName: project.name,
      status: project.status,
      completionRate: project.metrics.completionRate,
      teamPerformance: [],
      taskBreakdown: [],
      recommendations: []
    };

    // 团队绩效
    project.teamMembers.forEach(agentId => {
      const agent = this.agents.get(agentId);
      if (agent) {
        report.teamPerformance.push({
          agentId: agentId,
          completedTasks: agent.performance.completedTasks,
          averageQuality: agent.performance.averageQuality,
          efficiency: agent.performance.efficiency
        });
      }
    });

    // 任务分解
    project.tasks.forEach(taskId => {
      const task = this.tasks.get(taskId);
      if (task) {
        report.taskBreakdown.push({
          taskId: taskId,
          title: task.title,
          status: task.status,
          assignee: task.assignee,
          priority: task.priority
        });
      }
    });

    // 建议
    if (project.metrics.completionRate < 50) {
      report.recommendations.push('项目进度较慢，建议增加资源或调整优先级');
    }
    if (project.metrics.completionRate > 90) {
      report.recommendations.push('项目接近完成，准备验收和交付');
    }

    return report;
  }

  /**
   * 生成项目ID
   */
  generateProjectId() {
    return `proj_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 生成任务ID
   */
  generateTaskId() {
    return `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 导出项目数据
   * @param {string} projectId - 项目ID
   */
  exportProjectData(projectId) {
    const project = this.projects.get(projectId);
    if (!project) {
      throw new Error(`Project ${projectId} not found`);
    }

    const exportData = {
      project: project,
      tasks: project.tasks.map(taskId => this.tasks.get(taskId)),
      agents: project.teamMembers.map(agentId => this.agents.get(agentId))
    };

    return JSON.stringify(exportData, null, 2);
  }
}

module.exports = ProjectManager;

path: team-coordinator.js
content: /**
 * AI Agent Team Coordinator
 * 负责协调多个AI代理之间的协作和通信
 */

class AIAgentTeamCoordinator {
  constructor() {
    this.agents = new Map();
    this.activeTasks = new Map();
    this.communicationChannels = new Map();
  }

  /**
   * 注册新代理到团队
   * @param {string} agentId - 代理ID
   * @param {Object} agentConfig - 代理配置
   */
  registerAgent(agentId, agentConfig) {
    this.agents.set(agentId, {
      id: agentId,
      config: agentConfig,
      status: 'active',
      lastActive: Date.now(),
      performance: { tasksCompleted: 0, successRate: 1.0 }
    });
    
    console.log(`✅ 代理 ${agentId} 已注册到团队`);
    return true;
  }

  /**
   * 分配任务给合适的代理
   * @param {Object} task - 任务对象
   * @returns {string} 分配的代理ID
   */
  assignTask(task) {
    const suitableAgents = this.findSuitableAgents(task);
    if (suitableAgents.length === 0) {
      throw new Error('没有合适的代理可以处理此任务');
    }

    // 基于负载均衡选择最佳代理
    const bestAgent = this.selectBestAgent(suitableAgents);
    this.activeTasks.set(task.id, {
      taskId: task.id,
      assignedTo: bestAgent.id,
      startTime: Date.now(),
      status: 'assigned'
    });

    console.log(`📋 任务 ${task.id} 已分配给代理 ${bestAgent.id}`);
    return bestAgent.id;
  }

  /**
   * 查找适合处理任务的代理
   * @param {Object} task - 任务对象
   * @returns {Array} 适合的代理列表
   */
  findSuitableAgents(task) {
    const suitable = [];
    for (const [agentId, agent] of this.agents) {
      if (this.isAgentSuitable(agent, task)) {
        suitable.push(agent);
      }
    }
    return suitable;
  }

  /**
   * 检查代理是否适合处理任务
   * @param {Object} agent - 代理对象
   * @param {Object} task - 任务对象
   * @returns {boolean}
   */
  isAgentSuitable(agent, task) {
    // 检查代理状态
    if (agent.status !== 'active') {
      return false;
    }

    // 检查技能匹配
    const requiredSkills = task.requiredSkills || [];
    const agentSkills = agent.config.skills || [];
    
    for (const skill of requiredSkills) {
      if (!agentSkills.includes(skill)) {
        return false;
      }
    }

    return true;
  }

  /**
   * 基于性能和负载选择最佳代理
   * @param {Array} agents - 代理列表
   * @returns {Object} 最佳代理
   */
  selectBestAgent(agents) {
    return agents.reduce((best, current) => {
      // 优先选择成功率高的代理
      if (current.performance.successRate > best.performance.successRate) {
        return current;
      }
      // 如果成功率相同，选择任务完成数少的（负载更轻）
      if (current.performance.successRate === best.performance.successRate &&
          current.performance.tasksCompleted < best.performance.tasksCompleted) {
        return current;
      }
      return best;
    });
  }

  /**
   * 更新任务状态
   * @param {string} taskId - 任务ID
   * @param {string} status - 新状态
   * @param {Object} result - 任务结果（可选）
   */
  updateTaskStatus(taskId, status, result = null) {
    const task = this.activeTasks.get(taskId);
    if (!task) {
      console.warn(`⚠️ 任务 ${taskId} 未找到`);
      return false;
    }

    task.status = status;
    task.endTime = Date.now();
    task.result = result;

    // 更新代理性能统计
    if (status === 'completed' || status === 'failed') {
      const agent = this.agents.get(task.assignedTo);
      if (agent) {
        agent.performance.tasksCompleted++;
        if (status === 'completed') {
          agent.performance.successRate = 
            (agent.performance.successRate * (agent.performance.tasksCompleted - 1) + 1) / 
            agent.performance.tasksCompleted;
        } else {
          agent.performance.successRate = 
            (agent.performance.successRate * (agent.performance.tasksCompleted - 1)) / 
            agent.performance.tasksCompleted;
        }
        agent.lastActive = Date.now();
      }
    }

    console.log(`🔄 任务 ${taskId} 状态更新为: ${status}`);
    return true;
  }

  /**
   * 获取团队状态报告
   * @returns {Object} 团队状态
   */
  getTeamStatus() {
    const activeAgents = Array.from(this.agents.values())
      .filter(agent => agent.status === 'active');
    
    const totalTasks = this.activeTasks.size;
    const completedTasks = Array.from(this.activeTasks.values())
      .filter(task => task.status === 'completed').length;
    
    const avgSuccessRate = activeAgents.length > 0 
      ? activeAgents.reduce((sum, agent) => sum + agent.performance.successRate, 0) / activeAgents.length
      : 0;

    return {
      totalAgents: this.agents.size,
      activeAgents: activeAgents.length,
      totalTasks: totalTasks,
      completedTasks: completedTasks,
      averageSuccessRate: avgSuccessRate,
      agents: activeAgents.map(agent => ({
        id: agent.id,
        status: agent.status,
        tasksCompleted: agent.performance.tasksCompleted,
        successRate: agent.performance.successRate
      }))
    };
  }

  /**
   * 创建新的通信频道
   * @param {string} channelId - 频道ID
   * @param {Array} participants - 参与者列表
   */
  createCommunicationChannel(channelId, participants) {
    this.communicationChannels.set(channelId, {
      id: channelId,
      participants: participants,
      messages: [],
      createdAt: Date.now()
    });
    console.log(`📡 通信频道 ${channelId} 已创建`);
  }

  /**
   * 发送消息到频道
   * @param {string} channelId - 频道ID
   * @param {string} sender - 发送者
   * @param {string} message - 消息内容
   */
  sendMessageToChannel(channelId, sender, message) {
    const channel = this.communicationChannels.get(channelId);
    if (!channel) {
      throw new Error(`频道 ${channelId} 不存在`);
    }

    channel.messages.push({
      sender: sender,
      content: message,
      timestamp: Date.now()
    });

    // 通知所有参与者
    for (const participant of channel.participants) {
      if (participant !== sender) {
        this.notifyAgent(participant, `来自 ${sender} 的消息: ${message}`);
      }
    }
  }

  /**
   * 通知代理
   * @param {string} agentId - 代理ID
   * @param {string} message - 通知消息
   */
  notifyAgent(agentId, message) {
    const agent = this.agents.get(agentId);
    if (agent) {
      console.log(`🔔 通知 ${agentId}: ${message}`);
      // 这里可以集成实际的通知机制
    }
  }

  /**
   * 移除代理
   * @param {string} agentId - 代理ID
   */
  removeAgent(agentId) {
    if (this.agents.has(agentId)) {
      this.agents.delete(agentId);
      console.log(`❌ 代理 ${agentId} 已从团队移除`);
      return true;
    }
    return false;
  }
}

module.exports = AIAgentTeamCoordinator;

path: package.json
content: {
  "name": "ai-agent-team-manager",
  "version": "1.0.0",
  "description": "AI Agent Team Management System for OpenClaw - Task allocation, progress tracking, quality control, and performance evaluation",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "openclaw",
    "ai-agent",
    "team-management",
    "task-allocation",
    "quality-control"
  ],
  "author": "Xiao Zhuang",
  "license": "MIT",
  "dependencies": {}
}

path: publish.sh
content: #!/bin/bash
# AI Agent Team Manager - Publish Script

echo "🚀 Publishing AI Agent Team Manager to ClawHub..."

# Validate skill structure
if [ ! -f "SKILL.md" ]; then
    echo "❌ Error: SKILL.md not found"
    exit 1
fi

if [ ! -f "package.json" ]; then
    echo "❌ Error: package.json not found"
    exit 1
fi

echo "✅ Skill structure validated"

# Build and test
echo "🧪 Running tests..."
# Add test commands here when needed

echo "📤 Ready to publish!"
echo "Run: clawhub publish . --slug ai-agent-team-manager --name \"AI Agent Team Manager\" --version 1.0.0 --tags latest --changelog \"Initial release\""

echo "🎯 Pricing: $69/month (Professional), $129/month (Enterprise)"

path: README.md
content: # AI Agent Team Manager

基于 Otter Camp 模式的开源 AI 代理团队管理系统，专为 OpenClaw 设计。

## 🎯 核心功能

### 1. **任务分配与协调**
- 智能任务分解和分配
- 多代理协作协调
- 资源优化和负载均衡
- 实时进度同步

### 2. **进度跟踪与监控**
- 实时任务状态监控
- 进度可视化仪表板
- 自动化里程碑跟踪
- 异常检测和告警

### 3. **质量控制体系**
- 多层质量审查机制
- 代理互相审查
- 人工检查点集成
- 质量指标评估

### 4. **绩效评估**
- 代理绩效追踪
- 工作质量评分
- 效率指标分析
- 改进建议生成

### 5. **工作流管理**
- 标准化工作流程
- Git 版本控制集成
- 上下文隔离管理
- 自动化部署流程

### 6. **项目管理**
- 项目规划和排期
- 风险管理和缓解
- 资源分配优化
- 成本效益分析

## 💰 定价策略

- **个人版**: $59/月 - 适合个人开发者和小团队
- **专业版**: $99/月 - 适合中型团队和企业
- **企业版**: $199/月 - 适合大型组织和复杂项目

## 🎯 目标用户

- **AI 开发团队**: 需要管理多个 AI 代理的开发团队
- **企业用户**: 希望实现 AI 自动化的大型组织  
- **研究机构**: 进行多代理系统研究的学术团队
- **自由职业者**: 提供 AI 代理服务的独立开发者

## 🔧 技术特点

- **开源自托管**: 完全开源，可在任何环境中部署
- **OpenClaw 原生**: 专为 OpenClaw 架构优化
- **模块化设计**: 可根据需求选择功能模块
- **安全合规**: 内置企业级安全和合规功能
- **可扩展性**: 支持大规模代理团队管理

## 📈 市场优势

- **唯一性**: ClawHub 上首个专门的 AI 代理团队管理技能包
- **成熟度**: 基于已验证的 Otter Camp 最佳实践
- **完整性**: 提供端到端的团队管理解决方案
- **高价值**: 企业客户愿意为团队管理功能付费

## 🚀 快速开始

```javascript
const teamManager = require('ai-agent-team-manager');

// 初始化团队管理器
const team = teamManager.createTeam({
  name: 'My AI Team',
  agents: ['xiaolv', 'laogou', 'xiaoqiu', 'xiaozhu']
});

// 分配任务
team.assignTask({
  description: 'Analyze email inbox',
  priority: 'high',
  deadline: '2026-03-10'
});

// 监控进度
team.monitorProgress();

// 生成质量报告
team.generateQualityReport();
```

## 📊 预期收益

基于市场需求分析，预计：
- **月销量**: 15-25 份
- **月收入**: $1,500-3,000
- **年收入**: $18,000-36,000

## 🎯 下一步

1. 在 ClawHub 上发布技能包
2. 创建演示视频和案例研究  
3. 在龙虾社区推广
4. 收集用户反馈并持续优化

path: performance-evaluator.js
content: /**
 * AI Agent Team Manager - Performance Evaluator
 * 评估AI代理团队成员的工作表现和效率
 */

class PerformanceEvaluator {
  constructor() {
    this.metrics = {
      taskCompletionRate: 0,
      qualityScore: 0,
      responseTime: 0,
      collaborationScore: 0,
      learningGrowth: 0
    };
  }

  /**
   * 评估单个代理的表现
   * @param {Object} agentData - 代理的工作数据
   * @returns {Object} 评估结果
   */
  evaluateAgent(agentData) {
    const evaluation = {
      agentId: agentData.id,
      name: agentData.name,
      role: agentData.role,
      metrics: {},
      strengths: [],
      weaknesses: [],
      recommendations: []
    };

    // 任务完成率评估
    const completionRate = this.calculateTaskCompletionRate(agentData.tasks);
    evaluation.metrics.taskCompletionRate = completionRate;
    
    if (completionRate >= 0.9) {
      evaluation.strengths.push('高任务完成率');
    } else if (completionRate < 0.7) {
      evaluation.weaknesses.push('任务完成率需要提升');
      evaluation.recommendations.push('建议优化任务分配策略');
    }

    // 质量评分
    const qualityScore = this.calculateQualityScore(agentData.outputs);
    evaluation.metrics.qualityScore = qualityScore;
    
    if (qualityScore >= 85) {
      evaluation.strengths.push('输出质量优秀');
    } else if (qualityScore < 70) {
      evaluation.weaknesses.push('输出质量有待提高');
      evaluation.recommendations.push('建议加强质量控制流程');
    }

    // 响应时间评估
    const responseTime = this.calculateResponseTime(agentData.interactions);
    evaluation.metrics.responseTime = responseTime;
    
    if (responseTime <= 300) {
      evaluation.strengths.push('响应速度快');
    } else if (responseTime > 600) {
      evaluation.weaknesses.push('响应时间较长');
      evaluation.recommendations.push('建议优化处理流程或分配更多资源');
    }

    // 协作评分
    const collaborationScore = this.calculateCollaborationScore(agentData.collaborations);
    evaluation.metrics.collaborationScore = collaborationScore;
    
    if (collaborationScore >= 80) {
      evaluation.strengths.push('团队协作良好');
    } else if (collaborationScore < 60) {
      evaluation.weaknesses.push('协作能力需要加强');
      evaluation.recommendations.push('建议改进沟通机制和工作流程');
    }

    // 学习成长评估
    const learningGrowth = this.calculateLearningGrowth(agentData.history);
    evaluation.metrics.learningGrowth = learningGrowth;
    
    if (learningGrowth >= 75) {
      evaluation.strengths.push('持续学习和改进');
    } else if (learningGrowth < 50) {
      evaluation.weaknesses.push('学习成长缓慢');
      evaluation.recommendations.push('建议提供更多反馈和学习机会');
    }

    // 综合评分
    evaluation.overallScore = this.calculateOverallScore(evaluation.metrics);
    evaluation.grade = this.getGrade(evaluation.overallScore);

    return evaluation;
  }

  /**
   * 计算任务完成率
   */
  calculateTaskCompletionRate(tasks) {
    if (!tasks || tasks.length === 0) return 0;
    const completed = tasks.filter(t => t.status === 'completed').length;
    return Math.round((completed / tasks.length) * 100) / 100;
  }

  /**
   * 计算质量评分
   */
  calculateQualityScore(outputs) {
    if (!outputs || outputs.length === 0) return 0;
    let totalScore = 0;
    outputs.forEach(output => {
      totalScore += output.qualityScore || 0;
    });
    return Math.round(totalScore / outputs.length);
  }

  /**
   * 计算响应时间（毫秒）
   */
  calculateResponseTime(interactions) {
    if (!interactions || interactions.length === 0) return 0;
    let totalTime = 0;
    interactions.forEach(interaction => {
      totalTime += interaction.responseTime || 0;
    });
    return Math.round(totalTime / interactions.length);
  }

  /**
   * 计算协作评分
   */
  calculateCollaborationScore(collaborations) {
    if (!collaborations || collaborations.length === 0) return 0;
    let totalScore = 0;
    collaborations.forEach(collab => {
      totalScore += collab.score || 0;
    });
    return Math.round(totalScore / collaborations.length);
  }

  /**
   * 计算学习成长评分
   */
  calculateLearningGrowth(history) {
    if (!history || history.length < 2) return 0;
    // 基于历史表现的趋势分析
    const recentPerformance = history.slice(-5).reduce((sum, item) => sum + item.score, 0) / 5;
    const earlyPerformance = history.slice(0, 5).reduce((sum, item) => sum + item.score, 0) / 5;
    const growth = ((recentPerformance - earlyPerformance) / earlyPerformance) * 100;
    return Math.max(0, Math.min(100, Math.round(50 + growth)));
  }

  /**
   * 计算综合评分
   */
  calculateOverallScore(metrics) {
    const weights = {
      taskCompletionRate: 0.3,
      qualityScore: 0.3,
      responseTime: 0.2,
      collaborationScore: 0.1,
      learningGrowth: 0.1
    };

    let score = 0;
    score += metrics.taskCompletionRate * weights.taskCompletionRate * 100;
    score += metrics.qualityScore * weights.qualityScore;
    score += (1 - metrics.responseTime / 1000) * weights.responseTime * 100;
    score += metrics.collaborationScore * weights.collaborationScore;
    score += metrics.learningGrowth * weights.learningGrowth;

    return Math.round(Math.max(0, Math.min(100, score)));
  }

  /**
   * 根据分数获取等级
   */
  getGrade(score) {
    if (score >= 90) return 'A+';
    if (score >= 85) return 'A';
    if (score >= 80) return 'A-';
    if (score >= 75) return 'B+';
    if (score >= 70) return 'B';
    if (score >= 65) return 'B-';
    if (score >= 60) return 'C+';
    if (score >= 55) return 'C';
    if (score >= 50) return 'C-';
    return 'D';
  }

  /**
   * 生成团队整体表现报告
   */
  generateTeamReport(teamData) {
    const report = {
      teamName: teamData.name,
      evaluationDate: new Date().toISOString(),
      members: [],
      teamMetrics: {},
      insights: [],
      recommendations: []
    };

    // 评估每个成员
    teamData.members.forEach(member => {
      const evaluation = this.evaluateAgent(member);
      report.members.push(evaluation);
    });

    // 计算团队指标
    report.teamMetrics.averageScore = this.calculateTeamAverage(report.members);
    report.teamMetrics.highestPerformer = this.getHighestPerformer(report.members);
    report.teamMetrics.lowestPerformer = this.getLowestPerformer(report.members);
    report.teamMetrics.completionRate = this.calculateTeamCompletionRate(report.members);

    // 生成洞察
    this.generateInsights(report);
    
    // 生成建议
    this.generateRecommendations(report);

    return report;
  }

  calculateTeamAverage(members) {
    if (members.length === 0) return 0;
    const total = members.reduce((sum, member) => sum + member.overallScore, 0);
    return Math.round(total / members.length);
  }

  getHighestPerformer(members) {
    return members.reduce((best, current) => 
      current.overallScore > best.overallScore ? current : best
    );
  }

  getLowestPerformer(members) {
    return members.reduce((worst, current) => 
      current.overallScore < worst.overallScore ? current : worst
    );
  }

  calculateTeamCompletionRate(members) {
    if (members.length === 0) return 0;
    const total = members.reduce((sum, member) => sum + member.metrics.taskCompletionRate, 0);
    return Math.round((total / members.length) * 100) / 100;
  }

  generateInsights(report) {
    const avgScore = report.teamMetrics.averageScore;
    const completionRate = report.teamMetrics.completionRate;

    if (avgScore >= 85) {
      report.insights.push('团队整体表现优秀，可以承担更复杂的任务');
    } else if (avgScore >= 70) {
      report.insights.push('团队表现良好，有进一步提升空间');
    } else {
      report.insights.push('团队需要重点关注表现较弱的成员');
    }

    if (completionRate >= 0.9) {
      report.insights.push('任务完成率很高，团队执行力强');
    } else if (completionRate < 0.7) {
      report.insights.push('任务完成率偏低，需要优化工作流程');
    }
  }

  generateRecommendations(report) {
    const weakMembers = report.members.filter(m => m.overallScore < 70);
    if (weakMembers.length > 0) {
      report.recommendations.push(`为以下成员提供额外支持: ${weakMembers.map(m => m.name).join(', ')}`);
    }

    const slowResponders = report.members.filter(m => m.metrics.responseTime > 600);
    if (slowResponders.length > 0) {
      report.recommendations.push('优化响应较慢成员的资源配置');
    }

    if (report.teamMetrics.averageScore < 80) {
      report.recommendations.push('实施定期培训和技能提升计划');
    }
  }
}

module.exports = PerformanceEvaluator;

path: workflow-manager.js
content: // AI Agent Team Manager - Workflow Manager
// 管理复杂的多代理工作流和任务依赖关系

const fs = require('fs');
const path = require('path');

class WorkflowManager {
  constructor() {
    this.workflows = new Map();
    this.activeWorkflows = new Map();
  }

  // 创建新的工作流
  createWorkflow(workflowConfig) {
    const workflowId = `wf_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    const workflow = {
      id: workflowId,
      name: workflowConfig.name || 'Untitled Workflow',
      description: workflowConfig.description || '',
      createdAt: new Date().toISOString(),
      steps: workflowConfig.steps || [],
      dependencies: workflowConfig.dependencies || {},
      parallelTasks: workflowConfig.parallelTasks || false,
      maxRetries: workflowConfig.maxRetries || 3,
      timeout: workflowConfig.timeout || 3600000, // 1 hour default
      status: 'created',
      results: {},
      errors: []
    };
    
    this.workflows.set(workflowId, workflow);
    return workflowId;
  }

  // 验证工作流配置
  validateWorkflow(workflowConfig) {
    const issues = [];
    
    if (!workflowConfig.steps || !Array.isArray(workflowConfig.steps)) {
      issues.push('Workflow must have steps array');
    }
    
    if (workflowConfig.steps.length === 0) {
      issues.push('Workflow must have at least one step');
    }
    
    // 验证每个步骤
    workflowConfig.steps.forEach((step, index) => {
      if (!step.id) {
        issues.push(`Step ${index} missing id`);
      }
      if (!step.agentId) {
        issues.push(`Step ${index} (${step.id}) missing agentId`);
      }
      if (!step.task) {
        issues.push(`Step ${index} (${step.id}) missing task`);
      }
      
      // 验证依赖关系
      if (step.dependsOn) {
        if (!Array.isArray(step.dependsOn)) {
          issues.push(`Step ${index} (${step.id}) dependsOn must be array`);
        } else {
          step.dependsOn.forEach(dep => {
            const depExists = workflowConfig.steps.some(s => s.id === dep);
            if (!depExists) {
              issues.push(`Step ${index} (${step.id}) depends on non-existent step ${dep}`);
            }
          });
        }
      }
    });
    
    // 检测循环依赖
    const dependencyGraph = new Map();
    workflowConfig.steps.forEach(step => {
      dependencyGraph.set(step.id, step.dependsOn || []);
    });
    
    if (this.hasCircularDependency(dependencyGraph)) {
      issues.push('Workflow has circular dependencies');
    }
    
    return issues;
  }

  // 检测循环依赖
  hasCircularDependency(graph) {
    const visited = new Set();
    const recursionStack = new Set();
    
    for (const node of graph.keys()) {
      if (this.isCyclicUtil(node, visited, recursionStack, graph)) {
        return true;
      }
    }
    return false;
  }

  isCyclicUtil(node, visited, recursionStack, graph) {
    if (!visited.has(node)) {
      visited.add(node);
      recursionStack.add(node);
      
      const neighbors = graph.get(node) || [];
      for (const neighbor of neighbors) {
        if (!visited.has(neighbor) && this.isCyclicUtil(neighbor, visited, recursionStack, graph)) {
          return true;
        } else if (recursionStack.has(neighbor)) {
          return true;
        }
      }
    }
    recursionStack.delete(node);
    return false;
  }

  // 执行工作流
  async executeWorkflow(workflowId, context = {}) {
    const workflow = this.workflows.get(workflowId);
    if (!workflow) {
      throw new Error(`Workflow ${workflowId} not found`);
    }
    
    // 验证工作流状态
    if (workflow.status === 'running') {
      throw new Error(`Workflow ${workflowId} is already running`);
    }
    
    workflow.status = 'running';
    workflow.startedAt = new Date().toISOString();
    workflow.context = context;
    this.activeWorkflows.set(workflowId, workflow);
    
    try {
      const result = await this.executeWorkflowSteps(workflow);
      workflow.status = 'completed';
      workflow.completedAt = new Date().toISOString();
      workflow.results = result;
      return result;
    } catch (error) {
      workflow.status = 'failed';
      workflow.failedAt = new Date().toISOString();
      workflow.errors.push({
        timestamp: new Date().toISOString(),
        error: error.message,
        stack: error.stack
      });
      throw error;
    } finally {
      this.activeWorkflows.delete(workflowId);
    }
  }

  // 执行工作流步骤
  async executeWorkflowSteps(workflow) {
    const results = {};
    const completedSteps = new Set();
    
    // 找到所有没有依赖的步骤（入口点）
    const entrySteps = workflow.steps.filter(step => 
      !step.dependsOn || step.dependsOn.length === 0
    );
    
    // 并行执行入口步骤
    const entryPromises = entrySteps.map(step => 
      this.executeStep(step, workflow, results, completedSteps)
    );
    
    await Promise.all(entryPromises);
    
    // 继续执行剩余步骤
    let remainingSteps = workflow.steps.filter(step => !completedSteps.has(step.id));
    let iterations = 0;
    const maxIterations = workflow.steps.length * 2; // 防止无限循环
    
    while (remainingSteps.length > 0 && iterations < maxIterations) {
      iterations++;
      
      const readySteps = remainingSteps.filter(step => {
        if (!step.dependsOn) return true;
        return step.dependsOn.every(dep => completedSteps.has(dep));
      });
      
      if (readySteps.length === 0) {
        // 检查是否有死锁
        const allDependencies = new Set();
        remainingSteps.forEach(step => {
          if (step.dependsOn) {
            step.dependsOn.forEach(dep => allDependencies.add(dep));
          }
        });
        
        const unresolvedDeps = Array.from(allDependencies).filter(dep => 
          !completedSteps.has(dep) && !remainingSteps.some(s => s.id === dep)
        );
        
        if (unresolvedDeps.length > 0) {
          throw new Error(`Unresolved dependencies: ${unresolvedDeps.join(', ')}`);
        }
        
        // 可能是并行任务，继续等待
        await new Promise(resolve => setTimeout(resolve, 100));
        remainingSteps = workflow.steps.filter(step => !completedSteps.has(step.id));
        continue;
      }
      
      // 执行就绪的步骤
      const stepPromises = readySteps.map(step => 
        this.executeStep(step, workflow, results, completedSteps)
      );
      
      await Promise.all(stepPromises);
      remainingSteps = workflow.steps.filter(step => !completedSteps.has(step.id));
    }
    
    if (remainingSteps.length > 0) {
      throw new Error(`Workflow execution timed out or deadlocked. Remaining steps: ${remainingSteps.map(s => s.id).join(', ')}`);
    }
    
    return results;
  }

  // 执行单个步骤
  async executeStep(step, workflow, results, completedSteps) {
    const stepId = step.id;
    const maxRetries = step.maxRetries || workflow.maxRetries || 3;
    let lastError = null;
    
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      try {
        // 准备步骤上下文
        const stepContext = {
          ...workflow.context,
          stepId: stepId,
          stepName: step.name,
          attempt: attempt,
          previousResults: results,
          workflowId: workflow.id
        };
        
        // 调用代理执行任务
        const stepResult = await this.callAgent(step.agentId, step.task, stepContext);
        
        results[stepId] = {
          success: true,
          result: stepResult,
          attempt: attempt,
          timestamp: new Date().toISOString()
        };
        
        completedSteps.add(stepId);
        return stepResult;
        
      } catch (error) {
        lastError = error;
        console.warn(`Step ${stepId} attempt ${attempt} failed:`, error.message);
        
        if (attempt < maxRetries) {
          // 等待后重试
          const delay = Math.min(1000 * Math.pow(2, attempt - 1), 30000); // 指数退避
          await new Promise(resolve => setTimeout(resolve, delay));
        }
      }
    }
    
    // 所有重试都失败了
    results[stepId] = {
      success: false,
      error: lastError.message,
      stack: lastError.stack,
      attempts: maxRetries,
      timestamp: new Date().toISOString()
    };
    
    completedSteps.add(stepId);
    throw lastError;
  }

  // 调用代理执行任务（模拟）
  async callAgent(agentId, task, context) {
    // 这里应该集成实际的 OpenClaw 代理调用
    // 目前作为模拟实现
    console.log(`Calling agent ${agentId} with task:`, task);
    console.log(`Context:`, context);
    
    // 模拟成功结果
    return {
      status: 'success',
      output: `Task completed by agent ${agentId}`,
      metadata: {
        agentId: agentId,
        taskId: context.stepId,
        workflowId: context.workflowId,
        timestamp: new Date().toISOString()
      }
    };
  }

  // 获取工作流状态
  getWorkflowStatus(workflowId) {
    const workflow = this.workflows.get(workflowId);
    if (!workflow) {
      return null;
    }
    
    return {
      id: workflow.id,
      name: workflow.name,
      status: workflow.status,
      createdAt: workflow.createdAt,
      startedAt: workflow.startedAt,
      completedAt: workflow.completedAt,
      failedAt: workflow.failedAt,
      stepCount: workflow.steps.length,
      completedSteps: Object.keys(workflow.results || {}).length,
      errors: workflow.errors
    };
  }

  // 列出所有工作流
  listWorkflows() {
    return Array.from(this.workflows.values()).map(wf => ({
      id: wf.id,
      name: wf.name,
      status: wf.status,
      createdAt: wf.createdAt
    }));
  }

  // 删除工作流
  deleteWorkflow(workflowId) {
    if (this.activeWorkflows.has(workflowId)) {
      throw new Error(`Cannot delete active workflow ${workflowId}`);
    }
    return this.workflows.delete(workflowId);
  }

  // 导出工作流配置
  exportWorkflow(workflowId) {
    const workflow = this.workflows.get(workflowId);
    if (!workflow) {
      throw new Error(`Workflow ${workflowId} not found`);
    }
    
    return {
      name: workflow.name,
      description: workflow.description,
      steps: workflow.steps,
      dependencies: workflow.dependencies,
      parallelTasks: workflow.parallelTasks,
      maxRetries: workflow.maxRetries,
      timeout: workflow.timeout
    };
  }

  // 从配置导入工作流
  importWorkflow(workflowConfig) {
    const issues = this.validateWorkflow(workflowConfig);
    if (issues.length > 0) {
      throw new Error(`Invalid workflow configuration: ${issues.join('; ')}`);
    }
    
    return this.createWorkflow(workflowConfig);
  }
}

module.exports = WorkflowManager;

Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (MEDIUM)