File size: 10,282 Bytes
d739b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
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;