/ opencodehub / src / lib / analytics-advanced.ts
swadhinbiswas chore: update src/lib/analytics-advanced.ts · 2/18/2026
421bc6b
666 lines · 21.6 KB
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/**
 * Advanced Analytics & Insights Library
 * Hotspot detection, export metrics, custom dashboards
 */

import { pgTable, text, timestamp, integer, real, jsonb, boolean } from "drizzle-orm/pg-core";
import { getDatabase, schema } from "@/db";
import { eq, and, gte, lte, sql, desc } from "drizzle-orm";
import { logger } from "./logger";
import { repositories } from "@/db/schema/repositories";
import { users } from "@/db/schema/users";
import { compareBranches } from "@/lib/git";
import { resolveRepoPath } from "@/lib/git-storage";

// ============================================================================
// SCHEMA
// ============================================================================

export const fileHotspots = pgTable("file_hotspots", {
    id: text("id").primaryKey(),
    repositoryId: text("repository_id")
        .notNull()
        .references(() => repositories.id, { onDelete: "cascade" }),
    filePath: text("file_path").notNull(),
    changeCount: integer("change_count").default(0),
    bugCount: integer("bug_count").default(0),
    reviewCount: integer("review_count").default(0),
    complexityScore: real("complexity_score"),
    lastModified: timestamp("last_modified"),
    calculatedAt: timestamp("calculated_at").notNull().defaultNow(),
});

export const customDashboards = pgTable("custom_dashboards", {
    id: text("id").primaryKey(),
    userId: text("user_id")
        .notNull()
        .references(() => users.id, { onDelete: "cascade" }),
    name: text("name").notNull(),
    description: text("description"),
    isPublic: boolean("is_public").default(false),
    layout: jsonb("layout").$type<DashboardLayout>(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
    updatedAt: timestamp("updated_at").notNull().defaultNow(),
});

export const dashboardWidgets = pgTable("dashboard_widgets", {
    id: text("id").primaryKey(),
    dashboardId: text("dashboard_id")
        .notNull()
        .references(() => customDashboards.id, { onDelete: "cascade" }),
    widgetType: text("widget_type").notNull(),
    title: text("title").notNull(),
    config: jsonb("config").$type<WidgetConfig>(),
    position: jsonb("position").$type<{ x: number; y: number; w: number; h: number }>(),
    createdAt: timestamp("created_at").notNull().defaultNow(),
});

export const metricSnapshots = pgTable("metric_snapshots", {
    id: text("id").primaryKey(),
    repositoryId: text("repository_id")
        .references(() => repositories.id, { onDelete: "cascade" }),
    organizationId: text("organization_id"),
    metricType: text("metric_type").notNull(),
    value: real("value").notNull(),
    dimensions: jsonb("dimensions").$type<Record<string, string>>(),
    timestamp: timestamp("timestamp").notNull().defaultNow(),
});

export type FileHotspot = typeof fileHotspots.$inferSelect;
export type CustomDashboard = typeof customDashboards.$inferSelect;
export type MetricSnapshot = typeof metricSnapshots.$inferSelect;

interface DashboardLayout {
    columns: number;
    rows: number;
}

interface WidgetConfig {
    repositoryId?: string;
    timeRange?: string;
    metrics?: string[];
    filters?: Record<string, string>;
}

// ============================================================================
// HOTSPOT FILE DETECTION
// ============================================================================

export async function calculateFileHotspots(repositoryId: string): Promise<FileHotspot[]> {
    const db = getDatabase();
    const repository = await db.query.repositories.findFirst({
        where: eq(schema.repositories.id, repositoryId),
    });
    if (!repository) return [];

    const repoPath = await resolveRepoPath(repository.diskPath);

    // Get all PRs for this repository
    const prs = await db.query.pullRequests.findMany({
        where: eq(schema.pullRequests.repositoryId, repositoryId),
    });

    const fileStats: Map<string, {
        changeCount: number;
        bugCount: number;
        reviewCount: number;
        lastModified: Date;
    }> = new Map();

    // Replace previous snapshot for this repository
    // @ts-expect-error - Drizzle multi-db union type issue
    await db.delete(schema.fileHotspots).where(eq(schema.fileHotspots.repositoryId, repositoryId));

    // Analyze each PR's changed files
    for (const pr of prs) {
        let changedFiles: string[] = [];
        try {
            const { diffs } = await compareBranches(repoPath, pr.baseBranch, pr.headBranch);
            changedFiles = diffs.map((d) => d.file).filter(Boolean);
        } catch (error) {
            logger.warn({ repositoryId, prId: pr.id, error }, "Failed to load changed files for hotspot analysis");
            continue;
        }
        const isBugFix = pr.title?.toLowerCase().includes("fix") ||
            pr.title?.toLowerCase().includes("bug");

        for (const file of changedFiles) {
            const current = fileStats.get(file) || {
                changeCount: 0,
                bugCount: 0,
                reviewCount: 0,
                lastModified: new Date(0),
            };

            current.changeCount++;
            if (isBugFix) current.bugCount++;
            current.reviewCount += pr.reviewCount || 0;
            if (pr.mergedAt && pr.mergedAt > current.lastModified) {
                current.lastModified = pr.mergedAt;
            }

            fileStats.set(file, current);
        }
    }

    // Calculate complexity scores and save hotspots
    const hotspots: FileHotspot[] = [];

    for (const [filePath, stats] of fileStats) {
        // Hotspot score = changes * 0.5 + bugs * 2 + reviews * 0.3
        const complexityScore = stats.changeCount * 0.5 + stats.bugCount * 2;

        const hotspot = {
            id: crypto.randomUUID(),
            repositoryId,
            filePath,
            changeCount: stats.changeCount,
            bugCount: stats.bugCount,
            reviewCount: stats.reviewCount,
            complexityScore,
            lastModified: stats.lastModified,
            calculatedAt: new Date(),
        };

        // @ts-expect-error - Drizzle multi-db union type issue
        await db.insert(schema.fileHotspots).values(hotspot);
        hotspots.push(hotspot as FileHotspot);
    }

    // Sort by complexity score descending
    hotspots.sort((a, b) => (b.complexityScore || 0) - (a.complexityScore || 0));

    logger.info({ repoId: repositoryId, hotspotCount: hotspots.length }, "Hotspots calculated");

    return hotspots.slice(0, 50); // Return top 50
}

export async function getFileHotspots(repositoryId: string, limit = 20): Promise<FileHotspot[]> {
    const db = getDatabase();

    try {
        return await db.query.fileHotspots?.findMany({
            where: eq(schema.fileHotspots.repositoryId, repositoryId),
            orderBy: (h, { desc }) => [desc(h.complexityScore)],
            limit,
        }) || [];
    } catch {
        return [];
    }
}

// ============================================================================
// METRICS EXPORT
// ============================================================================

export type ExportFormat = "json" | "csv" | "prometheus";

export interface MetricExportOptions {
    repositoryId?: string;
    organizationId?: string;
    metrics: string[];
    startDate: Date;
    endDate: Date;
    format: ExportFormat;
    groupBy?: "day" | "week" | "month";
}

export async function exportMetrics(options: MetricExportOptions): Promise<string> {
    const db = getDatabase();

    const snapshots = await db.query.metricSnapshots?.findMany({
        where: and(
            options.repositoryId
                ? eq(schema.metricSnapshots.repositoryId, options.repositoryId)
                : undefined,
            gte(schema.metricSnapshots.timestamp, options.startDate),
            lte(schema.metricSnapshots.timestamp, options.endDate)
        ),
        orderBy: (m, { asc }) => [asc(m.timestamp)],
    }) || [];

    // Filter by metric types
    const filtered = snapshots.filter(s => options.metrics.includes(s.metricType));

    switch (options.format) {
        case "json":
            return exportAsJSON(filtered);
        case "csv":
            return exportAsCSV(filtered);
        case "prometheus":
            return exportAsPrometheus(filtered);
        default:
            return exportAsJSON(filtered);
    }
}

function exportAsJSON(snapshots: MetricSnapshot[]): string {
    return JSON.stringify(snapshots, null, 2);
}

function exportAsCSV(snapshots: MetricSnapshot[]): string {
    const headers = ["timestamp", "metricType", "value", "repositoryId"];
    const rows = snapshots.map(s => [
        s.timestamp.toISOString(),
        s.metricType,
        s.value.toString(),
        s.repositoryId || "",
    ]);

    return [headers.join(","), ...rows.map(r => r.join(","))].join("\n");
}

function exportAsPrometheus(snapshots: MetricSnapshot[]): string {
    const lines: string[] = [];

    for (const snapshot of snapshots) {
        const labels = snapshot.dimensions
            ? Object.entries(snapshot.dimensions)
                .map(([k, v]) => `${k}="${v}"`)
                .join(",")
            : "";

        const metricName = snapshot.metricType.replace(/[^a-zA-Z0-9_]/g, "_");
        lines.push(`# TYPE ${metricName} gauge`);
        lines.push(`${metricName}{${labels}} ${snapshot.value} ${snapshot.timestamp.getTime()}`);
    }

    return lines.join("\n");
}

// ============================================================================
// CUSTOM DASHBOARDS
// ============================================================================

export async function createDashboard(options: {
    userId: string;
    name: string;
    description?: string;
    isPublic?: boolean;
}): Promise<CustomDashboard> {
    const db = getDatabase();

    const dashboard = {
        id: crypto.randomUUID(),
        userId: options.userId,
        name: options.name,
        description: options.description || null,
        isPublic: options.isPublic ?? false,
        layout: { columns: 12, rows: 8 },
        createdAt: new Date(),
        updatedAt: new Date(),
    };

    // @ts-expect-error - Drizzle multi-db union type issue
    await db.insert(schema.customDashboards).values(dashboard);

    return dashboard as CustomDashboard;
}

export async function addWidget(options: {
    dashboardId: string;
    widgetType: string;
    title: string;
    config?: WidgetConfig;
    position?: { x: number; y: number; w: number; h: number };
}): Promise<typeof dashboardWidgets.$inferSelect> {
    const db = getDatabase();

    const widget = {
        id: crypto.randomUUID(),
        dashboardId: options.dashboardId,
        widgetType: options.widgetType,
        title: options.title,
        config: options.config || {},
        position: options.position || { x: 0, y: 0, w: 4, h: 2 },
        createdAt: new Date(),
    };

    // @ts-expect-error - Drizzle multi-db union type issue
    await db.insert(schema.dashboardWidgets).values(widget);

    return widget;
}

export const WIDGET_TYPES = {
    pr_velocity: {
        name: "PR Velocity",
        description: "PRs merged over time",
        defaultConfig: { timeRange: "30d" },
    },
    review_time: {
        name: "Review Time",
        description: "Average time to first review",
        defaultConfig: { timeRange: "30d" },
    },
    cycle_time: {
        name: "Cycle Time",
        description: "Time from PR open to merge",
        defaultConfig: { timeRange: "30d" },
    },
    hotspot_files: {
        name: "Hotspot Files",
        description: "Most frequently changed files",
        defaultConfig: { limit: 10 },
    },
    team_workload: {
        name: "Team Workload",
        description: "Open PRs per team member",
        defaultConfig: {},
    },
    ci_success_rate: {
        name: "CI Success Rate",
        description: "Percentage of passing builds",
        defaultConfig: { timeRange: "7d" },
    },
    deploy_frequency: {
        name: "Deploy Frequency",
        description: "Deployments per day/week",
        defaultConfig: { timeRange: "30d" },
    },
    issue_burndown: {
        name: "Issue Burndown",
        description: "Issues opened vs closed",
        defaultConfig: { timeRange: "30d" },
    },
} as const;

export async function getDashboard(dashboardId: string): Promise<{
    dashboard: CustomDashboard;
    widgets: (typeof dashboardWidgets.$inferSelect)[];
} | null> {
    const db = getDatabase();

    const dashboard = await db.query.customDashboards?.findFirst({
        where: eq(schema.customDashboards.id, dashboardId),
    });

    if (!dashboard) return null;

    const widgets = await db.query.dashboardWidgets?.findMany({
        where: eq(schema.dashboardWidgets.dashboardId, dashboardId),
    }) || [];

    return { dashboard, widgets };
}

// ============================================================================
// AGGREGATED METRICS
// ============================================================================

export async function recordMetric(options: {
    repositoryId?: string;
    organizationId?: string;
    metricType: string;
    value: number;
    dimensions?: Record<string, string>;
}): Promise<void> {
    const db = getDatabase();

    // @ts-expect-error - Drizzle multi-db union type issue
    await db.insert(schema.metricSnapshots).values({
        id: crypto.randomUUID(),
        repositoryId: options.repositoryId || null,
        organizationId: options.organizationId || null,
        metricType: options.metricType,
        value: options.value,
        dimensions: options.dimensions || null,
        timestamp: new Date(),
    });
}

export async function getMetricTimeSeries(options: {
    repositoryId?: string;
    metricType: string;
    startDate: Date;
    endDate: Date;
    granularity?: "hour" | "day" | "week";
}): Promise<{ timestamp: Date; value: number }[]> {
    const db = getDatabase();

    const snapshots = await db.query.metricSnapshots?.findMany({
        where: and(
            options.repositoryId
                ? eq(schema.metricSnapshots.repositoryId, options.repositoryId)
                : undefined,
            eq(schema.metricSnapshots.metricType, options.metricType),
            gte(schema.metricSnapshots.timestamp, options.startDate),
            lte(schema.metricSnapshots.timestamp, options.endDate)
        ),
        orderBy: (m, { asc }) => [asc(m.timestamp)],
    }) || [];

    return snapshots.map(s => ({
        timestamp: s.timestamp,
        value: s.value,
    }));
}

// ============================================================================
// DORA METRICS
// ============================================================================

export async function getDORAMetrics(options: {
    repositoryId?: string;
    organizationId?: string;
    startDate: Date;
    endDate: Date;
}): Promise<{
    deploymentFrequency: number; // per day
    leadTimeForChanges: number; // hours
    changeFailureRate: number; // percentage
    timeToRestoreService: number; // hours
}> {
    const db = getDatabase();

    // Get deployments
    const deployments = await db.query.deployments?.findMany({
        where: and(
            gte(schema.deployments.createdAt, options.startDate),
            lte(schema.deployments.createdAt, options.endDate)
        ),
    }) || [];

    const daysDiff = (options.endDate.getTime() - options.startDate.getTime()) / (1000 * 60 * 60 * 24);

    // Deployment Frequency
    const deploymentFrequency = deployments.length / daysDiff;

    // Lead Time for Changes (time from commit to deploy)
    const leadTimes = deployments
        .filter(d => d.startedAt && d.completedAt)
        .map(d => (d.completedAt!.getTime() - d.startedAt!.getTime()) / (1000 * 60 * 60));

    const leadTimeForChanges = leadTimes.length > 0
        ? leadTimes.reduce((a, b) => a + b, 0) / leadTimes.length
        : 0;

    // Change Failure Rate
    const failedDeploys = deployments.filter(d => d.status === "failed").length;
    const changeFailureRate = deployments.length > 0
        ? (failedDeploys / deployments.length) * 100
        : 0;

    // Time to Restore (time between failure and next success)
    const timeToRestoreService = 0; // Would need incident tracking

    return {
        deploymentFrequency,
        leadTimeForChanges,
        changeFailureRate,
        timeToRestoreService,
    };
}

// ============================================================================
// DEVELOPER WORKLOAD INSIGHTS
// ============================================================================

export interface DeveloperWorkload {
    userId: string;
    userName: string;
    openPRs: number;
    pendingReviews: number;
    assignedIssues: number;
    recentCommits: number;
    avgReviewTime: number; // hours
    workloadScore: number; // 0-100
    trend: "increasing" | "stable" | "decreasing";
}

export async function getDeveloperWorkloads(options: {
    repositoryId?: string;
    organizationId?: string;
    days?: number;
}): Promise<DeveloperWorkload[]> {
    const db = getDatabase();
    const startDate = new Date(Date.now() - (options.days || 30) * 24 * 60 * 60 * 1000);

    // Get all users
    const users = await db.query.users.findMany({}) || [];

    const workloads: DeveloperWorkload[] = [];

    for (const user of users) {
        // Count open PRs authored
        const openPRs = await db.query.pullRequests.findMany({
            where: and(
                eq(schema.pullRequests.authorId, user.id),
                eq(schema.pullRequests.state, "open")
            ),
        }) || [];

        // Count pending reviews requested (simplified - get all assigned reviews)
        const pendingReviews = await db.query.pullRequestReviewers?.findMany({
            where: eq(schema.pullRequestReviewers.userId, user.id),
        }) || [];

        // Count assigned issues
        const assignedIssues = await db.query.issueAssignees?.findMany({
            where: eq(schema.issueAssignees.userId, user.id),
        }) || [];

        // Calculate workload score (weighted)
        const workloadScore = Math.min(100,
            openPRs.length * 10 +
            pendingReviews.length * 15 +
            assignedIssues.length * 5
        );

        // Determine trend (compare to previous period)
        const trend = workloadScore > 70 ? "increasing" :
            workloadScore < 30 ? "decreasing" : "stable";

        workloads.push({
            userId: user.id,
            userName: user.displayName || user.username,
            openPRs: openPRs.length,
            pendingReviews: pendingReviews.length,
            assignedIssues: assignedIssues.length,
            recentCommits: 0, // Would need commit data
            avgReviewTime: 0, // Would need review timing data
            workloadScore,
            trend,
        });
    }

    // Sort by workload score descending
    workloads.sort((a, b) => b.workloadScore - a.workloadScore);

    return workloads;
}

export async function getTeamBalanceReport(organizationId: string): Promise<{
    totalWorkload: number;
    averageWorkload: number;
    maxWorkload: number;
    minWorkload: number;
    imbalanceScore: number; // 0-100, higher = more imbalanced
    recommendations: string[];
}> {
    const workloads = await getDeveloperWorkloads({ organizationId });

    if (workloads.length === 0) {
        return {
            totalWorkload: 0,
            averageWorkload: 0,
            maxWorkload: 0,
            minWorkload: 0,
            imbalanceScore: 0,
            recommendations: [],
        };
    }

    const scores = workloads.map(w => w.workloadScore);
    const totalWorkload = scores.reduce((a, b) => a + b, 0);
    const averageWorkload = totalWorkload / scores.length;
    const maxWorkload = Math.max(...scores);
    const minWorkload = Math.min(...scores);

    // Calculate standard deviation for imbalance
    const variance = scores.reduce((sum, s) => sum + Math.pow(s - averageWorkload, 2), 0) / scores.length;
    const stdDev = Math.sqrt(variance);

    // Imbalance score based on coefficient of variation
    const imbalanceScore = averageWorkload > 0
        ? Math.min(100, (stdDev / averageWorkload) * 100)
        : 0;

    // Generate recommendations
    const recommendations: string[] = [];

    if (imbalanceScore > 50) {
        recommendations.push("Consider redistributing work more evenly across team members");
    }

    const overloaded = workloads.filter(w => w.workloadScore > 80);
    if (overloaded.length > 0) {
        recommendations.push(`${overloaded.length} team member(s) appear overloaded`);
    }

    const underutilized = workloads.filter(w => w.workloadScore < 20);
    if (underutilized.length > 0 && overloaded.length > 0) {
        recommendations.push("Redistribute reviews from overloaded to underutilized members");
    }

    return {
        totalWorkload,
        averageWorkload,
        maxWorkload,
        minWorkload,
        imbalanceScore,
        recommendations,
    };
}

export async function suggestReviewerAssignment(
    pullRequestId: string,
    excludeUserIds: string[] = []
): Promise<{ userId: string; userName: string; reason: string }[]> {
    const db = getDatabase();

    const pr = await db.query.pullRequests.findFirst({
        where: eq(schema.pullRequests.id, pullRequestId),
    });

    if (!pr) return [];

    // Get workloads excluding the PR author and excluded users
    const workloads = await getDeveloperWorkloads({ repositoryId: pr.repositoryId });

    const candidates = workloads
        .filter(w => w.userId !== pr.authorId && !excludeUserIds.includes(w.userId))
        .filter(w => w.workloadScore < 80) // Not overloaded
        .slice(0, 3); // Top 3 suggestions

    return candidates.map(c => ({
        userId: c.userId,
        userName: c.userName,
        reason: c.workloadScore < 30
            ? "Has low current workload"
            : c.pendingReviews < 3
                ? "Has few pending reviews"
                : "Balanced workload",
    }));
}