All files first-principle-decomposer.js

81.94% Statements 59/72
55.55% Branches 15/27
100% Functions 18/18
84.05% Lines 58/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215                  14x         14x 14x       5x 5x 5x 5x 5x 5x   5x                               7x 7x               7x 35x 35x         7x 7x     7x       7x 7x 7x   7x 7x 7x                       7x       7x 7x   7x                                 7x       5x 5x   5x               5x           5x       5x       15x         5x           5x 15x 15x     5x       5x 5x             5x 20x 20x         5x       5x                 5x 5x 5x   5x 40x                   5x       1x     1x 3x         1x  
/**
 * First Principle Decomposer - 第一性原理任务分解器
 * 版本:v1.0.0
 * 
 * 灵感来源:第一性原理思维学习(2026-03-30 23:00)
 */
 
class FirstPrincipleDecomposer {
  constructor(options = {}) {
    this.options = {
      maxWhyDepth: options.maxWhyDepth || 5,
      minAtomicLevel: options.minAtomicLevel || 3,
      ...options
    };
    this.assumptions = [];
    this.firstPrinciples = [];
  }
 
  decompose(task) {
    console.log('[FirstPrincipleDecomposer] 开始分解任务:', task);
    this.assumptions = this._identifyAssumptions(task);
    const whyAnalysis = this._fiveWhys(task);
    this.firstPrinciples = this._extractFirstPrinciples(whyAnalysis);
    const reconstructedTask = this._reconstructTask(this.firstPrinciples, task);
    const atomicTasks = this._decomposeToAtomic(reconstructedTask);
    
    return {
      originalTask: task,
      assumptions: this.assumptions,
      whyAnalysis,
      firstPrinciples: this.firstPrinciples,
      reconstructedTask,
      atomicTasks,
      metadata: {
        decomposedAt: new Date().toISOString(),
        whyDepth: whyAnalysis.depth,
        atomicTaskCount: atomicTasks.length
      }
    };
  }
 
  _identifyAssumptions(task) {
    const assumptions = [];
    const patterns = [
      { pattern: /必须 (.*?) 才能/, type: '必要性假设' },
      { pattern: /只有 (.*?) 才能/, type: '唯一性假设' },
      { pattern: /因为 (.*?)(,|。)/, type: '因果假设' },
      { pattern: /一直 (.*?) 所以/, type: '经验假设' },
      { pattern: /应该 (.*?) 因为/, type: '规范性假设' }
    ];
    
    patterns.forEach(({ pattern, type }) => {
      const matches = task.match(pattern);
      Iif (matches) {
        assumptions.push({ type, content: matches[1], questioned: false });
      }
    });
    
    Eif (assumptions.length === 0) {
      assumptions.push({ type: '隐含假设', content: '当前任务描述是最优解', questioned: false });
    }
    
    return assumptions;
  }
 
  _fiveWhys(task) {
    const analysis = [];
    let currentWhy = task;
    let depth = 0;
    
    while (depth < this.options.maxWhyDepth) {
      const why = this._askWhy(currentWhy);
      Eif (!why || why === currentWhy) break;
      
      analysis.push({
        level: depth + 1,
        question: `为什么${depth > 0 ? '要' : ''}${currentWhy}?`,
        answer: why
      });
      
      currentWhy = why;
      depth++;
    }
    
    return { depth, analysis };
  }
 
  _askWhy(statement) {
    const verbPattern = /(需要 | 要 | 必须 | 应该)(.*?)(以 | 来 | 为了 | 才能)/;
    const match = statement.match(verbPattern);
    
    Iif (match) {
      const action = match[2];
      const purposes = {
        '完成任务': '达成目标',
        '解决问题': '消除障碍',
        '实现功能': '满足需求',
        '优化性能': '提升效率',
        '改进质量': '增加价值'
      };
      
      for (const [key, value] of Object.entries(purposes)) {
        if (action.includes(key)) return value;
      }
      
      return `理解${action}的本质目的`;
    }
    
    return null;
  }
 
  _extractFirstPrinciples(whyAnalysis) {
    const principles = [];
    const lastAnalysis = whyAnalysis.analysis[whyAnalysis.analysis.length - 1];
    
    Iif (lastAnalysis) {
      principles.push({
        principle: lastAnalysis.answer,
        confidence: 0.8,
        source: '5Why 分析'
      });
    }
    
    principles.push(
      { principle: '任务应该分解到可执行的最小单元', confidence: 0.9, source: '任务管理最佳实践' },
      { principle: '每个子任务应该有明确的输入输出', confidence: 0.9, source: '系统工程' },
      { principle: '依赖关系应该显式声明', confidence: 0.85, source: '工作流管理' }
    );
    
    return principles;
  }
 
  _reconstructTask(principles, originalTask) {
    return {
      goal: this._extractGoal(originalTask),
      constraints: this._extractConstraints(originalTask),
      successCriteria: this._defineSuccessCriteria(originalTask),
      principles: principles.map(p => p.principle)
    };
  }
 
  _extractGoal(task) {
    const patterns = [
      /目标 [是:]?(.*?)(。|$)/,
      /为了 (.*?)(。|$)/,
      /实现 (.*?)(。|$)/
    ];
    
    for (const pattern of patterns) {
      const match = task.match(pattern);
      Iif (match) return match[1].trim();
    }
    
    return task;
  }
 
  _extractConstraints(task) {
    const constraints = [];
    const patterns = [
      { pattern: /在 (.*?) 内/, type: '时间约束' },
      { pattern: /使用 (.*?) 来/, type: '工具约束' },
      { pattern: /不超过 (.*?)(。|,)/, type: '资源约束' },
      { pattern: /必须 (.*?)(。|,)/, type: '质量约束' }
    ];
    
    patterns.forEach(({ pattern, type }) => {
      const matches = task.match(pattern);
      Iif (matches) {
        constraints.push({ type, content: matches[1] });
      }
    });
    
    return constraints;
  }
 
  _defineSuccessCriteria(task) {
    return [
      '任务目标明确且可衡量',
      '所有子任务可独立执行',
      '依赖关系清晰',
      '结果可验证'
    ];
  }
 
  _decomposeToAtomic(reconstructedTask) {
    const atomicTasks = [];
    const goal = reconstructedTask.goal;
    const actionWords = ['分析', '设计', '实现', '测试', '优化', '评估', '创建', '验证'];
    
    actionWords.forEach((action, index) => {
      atomicTasks.push({
        id: `atomic_${index + 1}`,
        action,
        description: `${action}${goal}`,
        dependencies: index > 0 ? [`atomic_${index}`] : [],
        estimatedEffort: 'medium',
        isAtomic: true
      });
    });
    
    return atomicTasks;
  }
 
  getSummary() {
    return {
      assumptionsIdentified: this.assumptions.length,
      firstPrinciplesExtracted: this.firstPrinciples.length,
      assumptions: this.assumptions.map(a => a.content),
      principles: this.firstPrinciples.map(p => p.principle)
    };
  }
}
 
module.exports = { FirstPrincipleDecomposer };