File size: 14,629 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
/**

 * BugTracker - Identifies, categorizes, and tracks bugs with detailed analysis

 * Provides bug severity, root cause analysis, and fix recommendations

 */
class BugTracker {
    constructor() {
        this.version = '1.0.0';
    }

    /**

     * Track and analyze bugs from tasks and code findings

     * @param {Array} tasks - All tasks

     * @param {Array} files - All files

     * @returns {Object} Bug analysis

     */
    track(tasks, files) {
        const bugs = this.identifyBugs(tasks, files);
        const categorized = this.categorizeBugs(bugs);
        const blockers = this.identifyBlockers(bugs);
        const recommendations = this.generateFixRecommendations(bugs);

        return {
            bugs,
            categorized,
            blockers,
            recommendations,
            summary: this.generateBugSummary(bugs)
        };
    }

    /**

     * Identify bugs from tasks and files

     * @param {Array} tasks - All tasks

     * @param {Array} files - All files

     * @returns {Array} Identified bugs

     */
    identifyBugs(tasks, files) {
        const bugs = [];
        let bugId = 1;

        // Bugs from security findings
        tasks.filter(t => t.type === 'security').forEach(task => {
            bugs.push({
                id: `BUG-SEC-${String(bugId++).padStart(3, '0')}`,
                title: task.title || task.message,
                severity: this.mapSeverity(task.severity || task.priorityLevel),
                category: 'SECURITY',
                filePath: task.filePath,
                line: task.line,
                rootCause: this.analyzeRootCause(task, 'security'),
                impact: this.assessImpact(task, 'security'),
                fixRecommendation: this.generateFixRecommendation(task, 'security'),
                status: task.completed ? 'FIXED' : 'OPEN',
                priority: task.priority || 0
            });
        });

        // Bugs from code quality issues
        tasks.filter(t => t.type === 'quality' && this.isActualBug(t)).forEach(task => {
            bugs.push({
                id: `BUG-QUAL-${String(bugId++).padStart(3, '0')}`,
                title: task.title || task.message,
                severity: this.mapSeverity(task.severity || task.priorityLevel),
                category: 'QUALITY',
                filePath: task.filePath,
                line: task.line,
                rootCause: this.analyzeRootCause(task, 'quality'),
                impact: this.assessImpact(task, 'quality'),
                fixRecommendation: this.generateFixRecommendation(task, 'quality'),
                status: task.completed ? 'FIXED' : 'OPEN',
                priority: task.priority || 0
            });
        });

        // Bugs from architecture issues
        tasks.filter(t => t.type === 'architecture' && this.isCriticalArchitectureBug(t)).forEach(task => {
            bugs.push({
                id: `BUG-ARCH-${String(bugId++).padStart(3, '0')}`,
                title: task.title || task.message,
                severity: 'CRITICAL',
                category: 'ARCHITECTURE',
                filePath: task.filePath,
                line: task.line,
                rootCause: this.analyzeRootCause(task, 'architecture'),
                impact: this.assessImpact(task, 'architecture'),
                fixRecommendation: this.generateFixRecommendation(task, 'architecture'),
                status: task.completed ? 'FIXED' : 'OPEN',
                priority: task.priority || 0
            });
        });

        // Bugs from test failures
        tasks.filter(t => t.type === 'test' && t.message.includes('fail')).forEach(task => {
            bugs.push({
                id: `BUG-TEST-${String(bugId++).padStart(3, '0')}`,
                title: task.title || task.message,
                severity: 'HIGH',
                category: 'TEST_FAILURE',
                filePath: task.filePath,
                line: task.line,
                rootCause: 'Test case failing - may indicate regression or incomplete implementation',
                impact: 'Test suite incomplete, may allow bugs to slip through',
                fixRecommendation: 'Investigate test failure root cause and fix implementation or test',
                status: task.completed ? 'FIXED' : 'OPEN',
                priority: task.priority || 0
            });
        });

        return bugs.sort((a, b) => b.priority - a.priority);
    }

    /**

     * Check if quality task is an actual bug

     */
    isActualBug(task) {
        const bugKeywords = ['error', 'fail', 'crash', 'exception', 'undefined', 'null', 'broken'];
        const text = `${task.title} ${task.message}`.toLowerCase();
        return bugKeywords.some(kw => text.includes(kw));
    }

    /**

     * Check if architecture issue is critical

     */
    isCriticalArchitectureBug(task) {
        const criticalKeywords = ['circular', 'coupling', 'anti-pattern', 'violation'];
        const text = `${task.title} ${task.message}`.toLowerCase();
        return criticalKeywords.some(kw => text.includes(kw));
    }

    /**

     * Map task severity to bug severity

     */
    mapSeverity(severity) {
        if (!severity) return 'MEDIUM';
        
        const severityUpper = String(severity).toUpperCase();
        if (severityUpper.includes('CRITICAL') || severityUpper.includes('FATAL')) return 'CRITICAL';
        if (severityUpper.includes('HIGH')) return 'HIGH';
        if (severityUpper.includes('MEDIUM')) return 'MEDIUM';
        if (severityUpper.includes('LOW')) return 'LOW';
        
        return 'MEDIUM';
    }

    /**

     * Analyze root cause of bug

     */
    analyzeRootCause(task, category) {
        const message = task.message || task.title || '';

        if (category === 'security') {
            if (message.includes('SQL')) return 'SQL injection vulnerability - user input not sanitized';
            if (message.includes('XSS')) return 'Cross-site scripting - HTML not escaped properly';
            if (message.includes('secret') || message.includes('key')) return 'Hardcoded credentials - sensitive data in source code';
            if (message.includes('path')) return 'Path traversal - insufficient path validation';
            return 'Security vulnerability detected - requires investigation';
        }

        if (category === 'quality') {
            if (message.includes('undefined')) return 'Variable used before definition or null/undefined check missing';
            if (message.includes('duplicate')) return 'Code duplication - violates DRY principle';
            if (message.includes('complexity')) return 'High cyclomatic complexity - function too complex';
            if (message.includes('long')) return 'Function exceeds size limits - needs refactoring';
            return 'Code quality issue - requires refactoring';
        }

        if (category === 'architecture') {
            if (message.includes('circular')) return 'Circular dependency - modules depend on each other';
            if (message.includes('coupling')) return 'High coupling - modules too tightly interconnected';
            if (message.includes('anti-pattern')) return 'Anti-pattern detected - violates design principles';
            return 'Architectural issue - needs design review';
        }

        return 'Root cause requires investigation';
    }

    /**

     * Assess bug impact

     */
    assessImpact(task, category) {
        const severity = this.mapSeverity(task.severity || task.priorityLevel);

        if (severity === 'CRITICAL') {
            return 'CRITICAL IMPACT: System may crash, data loss possible, or security breach imminent';
        }

        if (severity === 'HIGH') {
            if (category === 'security') return 'HIGH IMPACT: Security vulnerability that could be exploited';
            if (category === 'quality') return 'HIGH IMPACT: Likely to cause errors or unexpected behavior';
            return 'HIGH IMPACT: Significant degradation of functionality or performance';
        }

        if (severity === 'MEDIUM') {
            return 'MEDIUM IMPACT: Affects code quality or maintainability but not immediate functionality';
        }

        return 'LOW IMPACT: Minor issue that should be addressed during refactoring';
    }

    /**

     * Generate fix recommendation

     */
    generateFixRecommendation(task, category) {
        const message = task.message || task.title || '';

        if (category === 'security') {
            if (message.includes('SQL')) return 'Use parameterized queries or ORM; never concatenate user input into SQL';
            if (message.includes('XSS')) return 'Escape all HTML output; use template engine with auto-escaping';
            if (message.includes('secret')) return 'Move credentials to environment variables or secure vault';
            if (message.includes('path')) return 'Validate and sanitize file paths; use path.normalize() and whitelist';
            return 'Review security best practices and apply appropriate mitigations';
        }

        if (category === 'quality') {
            if (message.includes('undefined')) return 'Add null/undefined checks; use optional chaining (?.) or default values';
            if (message.includes('duplicate')) return 'Extract common code into reusable function; apply DRY principle';
            if (message.includes('complexity')) return 'Break down into smaller functions; reduce nested conditionals';
            if (message.includes('long')) return 'Split function into smaller, single-responsibility functions';
            return 'Refactor code to improve quality and maintainability';
        }

        if (category === 'architecture') {
            if (message.includes('circular')) return 'Refactor to remove circular dependency; introduce dependency injection or event bus';
            if (message.includes('coupling')) return 'Apply SOLID principles; use interfaces and dependency injection';
            if (message.includes('anti-pattern')) return 'Refactor to proper design pattern; consult architecture guide';
            return 'Review and refactor architecture to follow best practices';
        }

        return 'Investigate issue and apply appropriate fix based on root cause analysis';
    }

    /**

     * Categorize bugs

     */
    categorizeBugs(bugs) {
        return {
            bySeverity: {
                critical: bugs.filter(b => b.severity === 'CRITICAL'),
                high: bugs.filter(b => b.severity === 'HIGH'),
                medium: bugs.filter(b => b.severity === 'MEDIUM'),
                low: bugs.filter(b => b.severity === 'LOW')
            },
            byCategory: {
                security: bugs.filter(b => b.category === 'SECURITY'),
                quality: bugs.filter(b => b.category === 'QUALITY'),
                architecture: bugs.filter(b => b.category === 'ARCHITECTURE'),
                test: bugs.filter(b => b.category === 'TEST_FAILURE')
            },
            byStatus: {
                open: bugs.filter(b => b.status === 'OPEN'),
                fixed: bugs.filter(b => b.status === 'FIXED')
            }
        };
    }

    /**

     * Identify blocker bugs

     */
    identifyBlockers(bugs) {
        return bugs
            .filter(b => b.severity === 'CRITICAL' && b.status === 'OPEN')
            .map(b => ({
                bugId: b.id,
                title: b.title,
                reason: `${b.category} bug blocking progress`,
                affectedPhases: this.identifyAffectedPhases(b),
                urgency: 'IMMEDIATE'
            }));
    }

    /**

     * Identify phases affected by bug

     */
    identifyAffectedPhases(bug) {
        const phases = [];
        
        if (bug.category === 'SECURITY') {
            phases.push('Security & Performance Phase');
            phases.push('Release Preparation');
        }
        
        if (bug.category === 'QUALITY') {
            phases.push('Core Implementation Phase');
            phases.push('Testing & QA Phase');
        }
        
        if (bug.category === 'ARCHITECTURE') {
            phases.push('Core Implementation Phase');
            phases.push('Migration & Refactoring Phase');
        }
        
        if (bug.category === 'TEST_FAILURE') {
            phases.push('Testing & QA Phase');
        }

        return phases;
    }

    /**

     * Generate fix recommendations summary

     */
    generateFixRecommendations(bugs) {
        const openBugs = bugs.filter(b => b.status === 'OPEN');
        
        return {
            immediate: openBugs
                .filter(b => b.severity === 'CRITICAL')
                .map(b => ({
                    bugId: b.id,
                    title: b.title,
                    recommendation: b.fixRecommendation,
                    priority: 'IMMEDIATE'
                })),
            urgent: openBugs
                .filter(b => b.severity === 'HIGH')
                .map(b => ({
                    bugId: b.id,
                    title: b.title,
                    recommendation: b.fixRecommendation,
                    priority: 'URGENT'
                })),
            scheduled: openBugs
                .filter(b => b.severity === 'MEDIUM' || b.severity === 'LOW')
                .map(b => ({
                    bugId: b.id,
                    title: b.title,
                    recommendation: b.fixRecommendation,
                    priority: 'SCHEDULED'
                }))
        };
    }

    /**

     * Generate bug summary

     */
    generateBugSummary(bugs) {
        const open = bugs.filter(b => b.status === 'OPEN');
        const fixed = bugs.filter(b => b.status === 'FIXED');

        return {
            totalBugs: bugs.length,
            openBugs: open.length,
            fixedBugs: fixed.length,
            criticalBugs: bugs.filter(b => b.severity === 'CRITICAL' && b.status === 'OPEN').length,
            highPriorityBugs: bugs.filter(b => b.severity === 'HIGH' && b.status === 'OPEN').length,
            securityBugs: bugs.filter(b => b.category === 'SECURITY' && b.status === 'OPEN').length,
            fixRate: bugs.length > 0 ? Math.round((fixed.length / bugs.length) * 100) : 0
        };
    }
}

module.exports = BugTracker;