/** * PriorityAnalyzer - Calculates task priorities based on multiple factors * Updated to use GitContextAnalyzer for accurate task aging (Zero-Dependency) */ const GitContextAnalyzer = require('./git-context-analyzer'); class PriorityAnalyzer { constructor(projectRoot = process.cwd()) { this.weights = { severity: 0.30, // Bug severity / security risk impact: 0.25, // Lines of code affected / number of files complexity: 0.20, // Implementation difficulty dependencies: 0.15, // Number of dependent tasks age: 0.10 // How long issue has existed }; this.severityScores = { CRITICAL: 100, HIGH: 75, MEDIUM: 50, LOW: 25, MINIMAL: 10 }; // Initialize Git context analyzer this.gitContext = new GitContextAnalyzer(projectRoot); } /** * Analyze and prioritize tasks with Git context enrichment */ analyze(tasks) { const prioritizedTasks = tasks.map(task => { // Enrich task with Git context (actual age, author, commit history) const enrichedTask = this.enrichTaskWithGitContext(task); const scores = { severity: this.calculateSeverityScore(enrichedTask), impact: this.calculateImpactScore(enrichedTask), complexity: this.calculateComplexityScore(enrichedTask), dependencies: this.calculateDependencyScore(enrichedTask), age: this.calculateAgeScore(enrichedTask) }; const priority = this.calculatePriority(scores); return { ...enrichedTask, scores, priority, priorityLevel: this.getPriorityLevel(priority), recommendation: this.generateRecommendation(enrichedTask, scores, priority) }; }); return this.sortByPriority(prioritizedTasks); } /** * Enrich task with Git context (actual age from git blame) */ enrichTaskWithGitContext(task) { // Skip if no file/line info or Git not available if (!task.filePath || !task.line) { return task; } try { const gitAge = this.gitContext.getAnnotationAge(task.filePath, task.line); if (gitAge) { return { ...task, actualAge: gitAge.days, author: gitAge.author, lastModified: gitAge.date, gitContext: true }; } } catch (error) { // Git not available or file not in Git - continue with estimated age } return task; } /** * Calculate severity score (0-100) */ calculateSeverityScore(task) { // For security issues if (task.type === 'security') { return this.severityScores[task.severity] || 50; } // For bugs if (task.type === 'bug') { if (task.severity === 'CRITICAL' || task.critical) return 100; if (task.severity === 'HIGH') return 75; if (task.severity === 'MEDIUM') return 50; return 25; } // For code quality issues if (task.type === 'code-smell' || task.type === 'quality') { return this.severityScores[task.severity] || 30; } // For features/improvements if (task.type === 'feature' || task.type === 'todo') { return 40; // Medium priority by default } return 25; } /** * Calculate impact score (0-100) */ calculateImpactScore(task) { let score = 0; // Files affected if (task.filesAffected) { score += Math.min(task.filesAffected * 5, 40); } // Lines of code affected if (task.linesAffected) { score += Math.min(task.linesAffected / 10, 30); } // User-facing impact if (task.userFacing) { score += 30; } // Breaking change if (task.breaking) { score += 40; } // Module criticality if (task.module) { if (/(?:auth|security|payment|database)/i.test(task.module)) { score += 20; } } return Math.min(score, 100); } /** * Calculate complexity score (0-100) * Lower complexity = higher priority (easier to fix) */ calculateComplexityScore(task) { let score = 50; // Default medium // Estimated effort if (task.effort) { const effortMap = { 'XS': 90, // Very quick fix 'S': 75, 'M': 50, 'L': 30, 'XL': 10 // Very complex }; score = effortMap[task.effort] || 50; } // Cyclomatic complexity if (task.complexity) { if (task.complexity > 20) score -= 30; else if (task.complexity > 10) score -= 15; } // Dependencies on other tasks if (task.blockedBy && task.blockedBy.length > 0) { score -= (task.blockedBy.length * 10); } // Technical debt if (task.type === 'tech-debt') { score += 20; // Easier to tackle sooner } return Math.max(0, Math.min(100, score)); } /** * Calculate dependency score (0-100) * More dependents = higher priority */ calculateDependencyScore(task) { let score = 0; // Tasks blocked by this one if (task.blocks && task.blocks.length > 0) { score += task.blocks.length * 20; } // Number of files importing this module if (task.dependents) { score += Math.min(task.dependents * 5, 50); } // Critical path if (task.criticalPath) { score += 50; } return Math.min(score, 100); } /** * Calculate age score (0-100) * Uses actual Git blame data when available, falls back to estimates * Older issues get higher priority */ calculateAgeScore(task) { // Use actual Git age if available (from enrichTaskWithGitContext) if (task.actualAge !== undefined) { const daysOld = task.actualAge; if (daysOld > 180) return 100; // 6+ months if (daysOld > 90) return 75; // 3-6 months if (daysOld > 30) return 50; // 1-3 months if (daysOld > 7) return 25; // 1-4 weeks return 10; // < 1 week } // Fallback to estimated age if (!task.createdAt && !task.age) return 25; let daysOld = 0; if (task.age) { daysOld = task.age; } else if (task.createdAt) { const created = new Date(task.createdAt); const now = new Date(); daysOld = Math.floor((now - created) / (1000 * 60 * 60 * 24)); } // Score increases with age if (daysOld > 180) return 100; // 6+ months if (daysOld > 90) return 75; // 3-6 months if (daysOld > 30) return 50; // 1-3 months if (daysOld > 7) return 25; // 1-4 weeks return 10; // < 1 week } /** * Calculate weighted priority score */ calculatePriority(scores) { let priority = 0; priority += scores.severity * this.weights.severity; priority += scores.impact * this.weights.impact; priority += scores.complexity * this.weights.complexity; priority += scores.dependencies * this.weights.dependencies; priority += scores.age * this.weights.age; return Math.round(priority); } /** * Get priority level */ getPriorityLevel(priority) { if (priority >= 80) return 'CRITICAL'; if (priority >= 60) return 'HIGH'; if (priority >= 40) return 'MEDIUM'; if (priority >= 20) return 'LOW'; return 'MINIMAL'; } /** * Generate recommendation */ generateRecommendation(task, scores, priority) { const recommendations = []; // Critical priority if (priority >= 80) { recommendations.push('Address immediately'); if (scores.severity > 75) { recommendations.push('High severity - production risk'); } if (scores.impact > 75) { recommendations.push('Wide impact - affects many users/files'); } if (scores.dependencies > 75) { recommendations.push('Blocking other tasks'); } } // High priority else if (priority >= 60) { recommendations.push('Schedule for current sprint'); if (scores.complexity > 60) { recommendations.push('Relatively easy fix - quick win'); } if (scores.age > 60) { recommendations.push('Long-standing issue - address soon'); } } // Medium priority else if (priority >= 40) { recommendations.push('Plan for next sprint'); if (scores.complexity < 40) { recommendations.push('Complex - may need team discussion'); } } // Low priority else { recommendations.push('Backlog - address when capacity allows'); if (task.type === 'tech-debt') { recommendations.push('Technical debt - consider during refactoring'); } } // Effort estimation if (scores.complexity > 70) { recommendations.push('Estimated effort: Small (1-2 hours)'); } else if (scores.complexity > 40) { recommendations.push('Estimated effort: Medium (3-8 hours)'); } else { recommendations.push('Estimated effort: Large (1-3 days)'); } return recommendations; } /** * Sort tasks by priority */ sortByPriority(tasks) { return tasks.sort((a, b) => { // First by priority score if (b.priority !== a.priority) { return b.priority - a.priority; } // Then by severity const severityOrder = { CRITICAL: 5, HIGH: 4, MEDIUM: 3, LOW: 2, MINIMAL: 1 }; return (severityOrder[b.priorityLevel] || 0) - (severityOrder[a.priorityLevel] || 0); }); } /** * Generate priority report */ generateReport(prioritizedTasks) { const summary = { totalTasks: prioritizedTasks.length, priorityDistribution: { CRITICAL: 0, HIGH: 0, MEDIUM: 0, LOW: 0, MINIMAL: 0 }, typeDistribution: {}, topPriorities: [], quickWins: [], blockers: [], averageAge: 0 }; let totalAge = 0; prioritizedTasks.forEach(task => { // Count by priority summary.priorityDistribution[task.priorityLevel]++; // Count by type summary.typeDistribution[task.type] = (summary.typeDistribution[task.type] || 0) + 1; // Calculate average age if (task.scores.age) { totalAge += task.scores.age; } }); summary.averageAge = prioritizedTasks.length > 0 ? Math.round(totalAge / prioritizedTasks.length) : 0; // Top 10 priorities summary.topPriorities = prioritizedTasks .slice(0, 10) .map(t => ({ title: t.title || t.message, priority: t.priority, priorityLevel: t.priorityLevel, type: t.type })); // Quick wins (high priority, low complexity) summary.quickWins = prioritizedTasks .filter(t => t.priority >= 60 && t.scores.complexity >= 70) .slice(0, 5) .map(t => ({ title: t.title || t.message, priority: t.priority, effort: 'Small' })); // Blockers (high priority, blocking others) summary.blockers = prioritizedTasks .filter(t => t.scores.dependencies >= 50) .slice(0, 5) .map(t => ({ title: t.title || t.message, priority: t.priority, blocks: t.blocks ? t.blocks.length : 0 })); return summary; } } module.exports = PriorityAnalyzer;