const crypto = require('crypto'); const db = require('../knowledge-db'); const PlanningEngine = require('./planning-engine'); const WikiJournalManager = require('./wiki-journal-manager'); const llmProviderService = require('./services/llm-provider-service'); class DevTaskManager { constructor() { this.planningEngine = new PlanningEngine(); } /** * Create a development plan from a requirement. * @param {string} projectId * @param {string} requirement * @param {Object} options */ async createPlan(projectId, requirement, options = {}) { // 취소/비용 원장 오류는 템플릿으로 우회하지 않는다. docs/specs/bong-goal-planning-budget.md v1.0.0 options.signal?.throwIfAborted(); const planId = 'plan_' + crypto.randomUUID(); // 1. Run Impact Analysis const impact = await this.planningEngine.analyzeImpact(projectId, requirement); options.signal?.throwIfAborted(); // 2. Task Decomposition let tasks = []; let decomposedSuccess = false; // Try LLM task decomposition if configured try { const prompt = `요구사항을 바탕으로 개발 계획을 수립하고 상세 하위 태스크(DAG 구조)로 분할하십시오. 요구사항: "${requirement}" 위험 수준: ${impact.riskLevel} 영향을 받는 파일: ${JSON.stringify(impact.affectedFiles)} 권장 테스트: ${JSON.stringify(impact.suggestedTests)} 반드시 다음 JSON 배열 형식으로만 응답하십시오. 설명이나 감탄사 없이 오직 JSON만 출력해야 합니다: [ { "id": "task_1", "name": "태스크 이름", "description": "태스크 상세 설명", "dependencies": [] }, { "id": "task_2", "name": "태스크 이름 2", "description": "태스크 상세 설명 2", "dependencies": ["task_1"] } ]`; const messages = [{ role: 'user', content: prompt }]; // Try to call chat completions using 'auto' or default group const response = options.modelCall ? await options.modelCall(messages) : await llmProviderService.callGroupChatCompletions('default', messages, {temperature:0.2,signal:options.signal}); options.signal?.throwIfAborted(); if (response.success && response.text) { // Parse JSON array const jsonMatch = response.text.match(/\[\s*\{[\s\S]*\}\s*\]/); if (jsonMatch) { tasks = JSON.parse(jsonMatch[0]); decomposedSuccess = true; } } if(options.modelCall&&!response.notConfigured&&(!decomposedSuccess||!Array.isArray(tasks)||!tasks.length||tasks.length>64))throw Error('계획 모델이 유효한 태스크를 반환하지 않았습니다.'); } catch (e) { options.signal?.throwIfAborted();if(options.modelCall)throw e; console.warn('[DevTaskManager] LLM task decomposition failed, falling back to template:', e.message); } // Fallback if LLM fails or is not configured if (!decomposedSuccess || tasks.length === 0) { tasks = [ { id: 'task_1', name: '코드 분석 및 상세 설계', description: `영향도 분석에 기반해 수정 대상을 분석합니다. (위험도: ${impact.riskLevel.toUpperCase()})`, dependencies: [] }, { id: 'task_2', name: '코드 구현 및 수정', description: `영향을 받는 파일 수정: ${impact.affectedFiles.join(', ') || '코드베이스 직접 수정'}`, dependencies: ['task_1'] }, { id: 'task_3', name: '테스트 및 검증', description: `수정 파일 유효성 검사 및 테스트 실행: ${impact.suggestedTests.join(', ') || '전체 테스트 실행'}`, dependencies: ['task_2'] }, { id: 'task_4', name: '작업 회고 보고서 작성', description: '변경 이력 기록 및 회고 보고서 작성', dependencies: ['task_3'] } ]; } // Sort tasks using PlanningEngine prioritize options.signal?.throwIfAborted(); tasks = this.planningEngine.prioritizeTasks(tasks, null); const planData = { planId, projectId, requirement, impact, tasks: tasks.map(t => ({ ...t, status: 'planned', startedAt: null, completedAt: null })), status: 'planned', createdAt: new Date().toISOString(), completedAt: null }; // Save plan to dev_preferences DB const preference={ category: 'dev_plans', preference_key: planId, preference_value: JSON.stringify(planData), confidence: 1.0, source: 'user_explicit' }; // 목표 체크포인트는 계획 DB 저장과 함께 커밋한다. Wiki 쓰기는 그 뒤의 별도 게시다. // docs/specs/bong-goal-planning-checkpoint.md v1.0.0 if(options.onPlanStored)db.runInTransaction(()=>{db.saveDevPreference(projectId,preference);options.onPlanStored(planData);}); else await db.saveDevPreference(projectId,preference); // Create Markdown Plan Note in Wiki options.signal?.throwIfAborted(); WikiJournalManager.createDevPlanNote(planId, planData); return planData; } /** * Update the status of a subtask. * @param {string} projectId * @param {string} planId * @param {string} taskId * @param {string} status - 'planned' | 'in_progress' | 'done' | 'failed' * @param {Object} result */ async updateTaskStatus(projectId, planId, taskId, status, result = null) { const prefs = await db.getDevPreferences(projectId, 'dev_plans'); const pref = prefs.find(p => p.preference_key === planId); if (!pref) { throw new Error(`계획을 찾을 수 없습니다: ${planId}`); } const planData = JSON.parse(pref.preference_value); const task = planData.tasks.find(t => t.id === taskId); if (task) { task.status = status; if (status === 'in_progress' && !task.startedAt) { task.startedAt = new Date().toISOString(); } else if ((status === 'done' || status === 'completed') && !task.completedAt) { task.completedAt = new Date().toISOString(); } task.result = result; } // Check if all tasks are done const allDone = planData.tasks.every(t => t.status === 'done' || t.status === 'completed'); if (allDone) { planData.status = 'done'; planData.completedAt = new Date().toISOString(); } else if (planData.tasks.some(t => t.status === 'in_progress')) { planData.status = 'in_progress'; } // Save updated plan back await db.saveDevPreference(projectId, { category: 'dev_plans', preference_key: planId, preference_value: JSON.stringify(planData), confidence: 1.0, source: 'user_explicit' }); // Update Wiki plan note WikiJournalManager.updateDevTaskStatusInPlan(planId, taskId, status); return planData; } /** * Get development task dashboard statistics. * @param {string} projectId */ async getDashboard(projectId) { const prefs = await db.getDevPreferences(projectId, 'dev_plans'); const plans = prefs.map(p => JSON.parse(p.preference_value)); let totalTasks = 0; let completedTasks = 0; let inProgressTasks = 0; let plannedTasks = 0; plans.forEach(plan => { plan.tasks.forEach(t => { totalTasks++; if (t.status === 'done' || t.status === 'completed') completedTasks++; else if (t.status === 'in_progress') inProgressTasks++; else plannedTasks++; }); }); // Get recent troubleshooting entries let recentTroubleshoots = []; try { recentTroubleshoots = await db.searchTroubleshoot(projectId, ''); } catch (e) { /* intentional: best-effort 처리, 실패 시 무시 */ } return { totalPlansCount: plans.length, plans: plans.slice(0, 10), // Recent 10 plans stats: { totalTasks, completedTasks, inProgressTasks, plannedTasks, completionRate: totalTasks > 0 ? (completedTasks / totalTasks) * 100 : 0 }, recentTroubleshoots: recentTroubleshoots.slice(0, 5) }; } /** * Generate retrospective report for a plan. * @param {string} projectId * @param {string} planId */ async generateRetro(projectId, planId) { const prefs = await db.getDevPreferences(projectId, 'dev_plans'); const pref = prefs.find(p => p.preference_key === planId); if (!pref) { throw new Error(`계획을 찾을 수 없습니다: ${planId}`); } const planData = JSON.parse(pref.preference_value); // Calculate duration let duration = 'N/A'; if (planData.completedAt && planData.createdAt) { const diffMs = new Date(planData.completedAt) - new Date(planData.createdAt); const diffHrs = Math.floor(diffMs / (1000 * 60 * 60)); const diffMins = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60)); duration = `${diffHrs}시간 ${diffMins}분`; } const completedTasksCount = planData.tasks.filter(t => t.status === 'done' || t.status === 'completed').length; // Load troubleshooting entries created during this plan period const allTroubleshoots = await db.searchTroubleshoot(projectId, ''); const planTroubleshoots = allTroubleshoots.filter(e => { const created = new Date(e.created_at || e.last_hit_at); return created >= new Date(planData.createdAt); }); // Load dev preferences learned const allPrefs = await db.getDevPreferences(projectId); const planPrefs = allPrefs.filter(p => { const created = new Date(p.created_at || p.updated_at); return created >= new Date(planData.createdAt) && p.category !== 'dev_plans' && p.category !== 'project_config'; }); const retroData = { planId, status: planData.status, duration, completedTasksCount, totalTasksCount: planData.tasks.length, troubleshootCount: planTroubleshoots.length, troubleshootEntries: planTroubleshoots, preferenceCount: planPrefs.length, preferences: planPrefs }; // Create Retro Note in Wiki WikiJournalManager.createDevRetroNote(planId, retroData); return retroData; } } module.exports = DevTaskManager;