bada-terminal / src /dev-task-manager.js
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
10.3 kB
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;