File size: 13,436 Bytes
4fea3ee | 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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 | /**
* 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;
|