gitfamiliar 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ GitClient,
4
+ buildFileTree,
3
5
  computeFamiliarity,
4
- parseExpirationConfig
5
- } from "../chunk-DW2PHZVZ.js";
6
+ createFilter,
7
+ parseExpirationConfig,
8
+ processBatch,
9
+ resolveUser,
10
+ walkFiles
11
+ } from "../chunk-HA6XTZPE.js";
6
12
 
7
13
  // src/cli/index.ts
8
14
  import { Command } from "commander";
@@ -26,34 +32,64 @@ function parseOptions(raw, repoPath) {
26
32
  weights = parseWeights(raw.weights);
27
33
  }
28
34
  const expiration = raw.expiration ? parseExpirationConfig(raw.expiration) : DEFAULT_EXPIRATION;
35
+ let user;
36
+ if (raw.user && raw.user.length === 1) {
37
+ user = raw.user[0];
38
+ } else if (raw.user && raw.user.length > 1) {
39
+ user = raw.user;
40
+ }
41
+ let hotspot;
42
+ if (raw.hotspot !== void 0 && raw.hotspot !== false) {
43
+ if (raw.hotspot === "team") {
44
+ hotspot = "team";
45
+ } else {
46
+ hotspot = "personal";
47
+ }
48
+ }
49
+ const windowDays = raw.window ? parseInt(raw.window, 10) : void 0;
29
50
  return {
30
51
  mode,
31
- user: raw.user,
52
+ user,
32
53
  filter,
33
54
  expiration,
34
55
  html: raw.html || false,
35
56
  weights,
36
- repoPath
57
+ repoPath,
58
+ team: raw.team || false,
59
+ teamCoverage: raw.teamCoverage || false,
60
+ hotspot,
61
+ window: windowDays
37
62
  };
38
63
  }
39
64
  function validateMode(mode) {
40
- const valid = ["binary", "authorship", "review-coverage", "weighted"];
65
+ const valid = [
66
+ "binary",
67
+ "authorship",
68
+ "review-coverage",
69
+ "weighted"
70
+ ];
41
71
  if (!valid.includes(mode)) {
42
- throw new Error(`Invalid mode: "${mode}". Valid modes: ${valid.join(", ")}`);
72
+ throw new Error(
73
+ `Invalid mode: "${mode}". Valid modes: ${valid.join(", ")}`
74
+ );
43
75
  }
44
76
  return mode;
45
77
  }
46
78
  function validateFilter(filter) {
47
79
  const valid = ["all", "written", "reviewed"];
48
80
  if (!valid.includes(filter)) {
49
- throw new Error(`Invalid filter: "${filter}". Valid filters: ${valid.join(", ")}`);
81
+ throw new Error(
82
+ `Invalid filter: "${filter}". Valid filters: ${valid.join(", ")}`
83
+ );
50
84
  }
51
85
  return filter;
52
86
  }
53
87
  function parseWeights(s) {
54
88
  const parts = s.split(",").map(Number);
55
89
  if (parts.length !== 3 || parts.some(isNaN)) {
56
- throw new Error(`Invalid weights: "${s}". Expected format: "0.5,0.35,0.15"`);
90
+ throw new Error(
91
+ `Invalid weights: "${s}". Expected format: "0.5,0.35,0.15"`
92
+ );
57
93
  }
58
94
  const sum = parts[0] + parts[1] + parts[2];
59
95
  if (Math.abs(sum - 1) > 0.01) {
@@ -299,11 +335,11 @@ function scoreColor(score) {
299
335
  return d3.interpolateRgb('#f5a623', '#27ae60')(t);
300
336
  }
301
337
 
302
- function getFileScore(file) {
303
- if (mode !== 'binary') return file.score;
304
- if (currentFilter === 'written') return file.isWritten ? 1 : 0;
305
- if (currentFilter === 'reviewed') return file.isReviewed ? 1 : 0;
306
- return file.score;
338
+ function getNodeScore(node) {
339
+ if (mode !== 'binary') return node.score;
340
+ if (currentFilter === 'written') return node.isWritten ? 1 : 0;
341
+ if (currentFilter === 'reviewed') return node.isReviewed ? 1 : 0;
342
+ return node.score;
307
343
  }
308
344
 
309
345
  function findNode(node, path) {
@@ -317,17 +353,23 @@ function findNode(node, path) {
317
353
  return null;
318
354
  }
319
355
 
320
- function flattenFiles(node) {
321
- const files = [];
322
- function walk(n) {
323
- if (n.type === 'file') {
324
- files.push(n);
325
- } else if (n.children) {
326
- n.children.forEach(walk);
327
- }
356
+ function totalLines(node) {
357
+ if (node.type === 'file') return Math.max(1, node.lines);
358
+ if (!node.children) return 1;
359
+ let sum = 0;
360
+ for (const c of node.children) sum += totalLines(c);
361
+ return Math.max(1, sum);
362
+ }
363
+
364
+ function buildHierarchy(node) {
365
+ if (node.type === 'file') {
366
+ return { name: node.path.split('/').pop(), data: node, value: Math.max(1, node.lines) };
328
367
  }
329
- walk(node);
330
- return files;
368
+ return {
369
+ name: node.path.split('/').pop() || node.path,
370
+ data: node,
371
+ children: (node.children || []).map(c => buildHierarchy(c)),
372
+ };
331
373
  }
332
374
 
333
375
  function render() {
@@ -344,18 +386,13 @@ function render() {
344
386
  const targetNode = currentPath ? findNode(rawData, currentPath) : rawData;
345
387
  if (!targetNode) return;
346
388
 
389
+ const children = targetNode.children || [];
390
+ if (children.length === 0) return;
391
+
392
+ // Build full nested hierarchy from the current target
347
393
  const hierarchyData = {
348
394
  name: targetNode.path || 'root',
349
- children: (targetNode.children || []).map(function buildChild(c) {
350
- if (c.type === 'file') {
351
- return { name: c.path.split('/').pop(), data: c, value: Math.max(1, c.lines) };
352
- }
353
- return {
354
- name: c.path.split('/').pop(),
355
- data: c,
356
- children: (c.children || []).map(buildChild),
357
- };
358
- }),
395
+ children: children.map(c => buildHierarchy(c)),
359
396
  };
360
397
 
361
398
  const root = d3.hierarchy(hierarchyData)
@@ -365,7 +402,7 @@ function render() {
365
402
  d3.treemap()
366
403
  .size([width, height])
367
404
  .padding(2)
368
- .paddingTop(18)
405
+ .paddingTop(20)
369
406
  .round(true)(root);
370
407
 
371
408
  const svg = d3.select('#treemap')
@@ -375,77 +412,94 @@ function render() {
375
412
 
376
413
  const tooltip = document.getElementById('tooltip');
377
414
 
378
- // Draw groups (folders)
415
+ const nodes = root.descendants().filter(d => d.depth > 0);
416
+
379
417
  const groups = svg.selectAll('g')
380
- .data(root.descendants().filter(d => d.depth > 0))
418
+ .data(nodes)
381
419
  .join('g')
382
420
  .attr('transform', d => \`translate(\${d.x0},\${d.y0})\`);
383
421
 
422
+ // Rect
384
423
  groups.append('rect')
385
424
  .attr('width', d => Math.max(0, d.x1 - d.x0))
386
425
  .attr('height', d => Math.max(0, d.y1 - d.y0))
387
426
  .attr('fill', d => {
388
- if (d.data.data) {
389
- const score = d.children ? d.data.data.score : getFileScore(d.data.data);
390
- return scoreColor(score);
391
- }
392
- return '#333';
427
+ if (!d.data.data) return '#333';
428
+ return scoreColor(getNodeScore(d.data.data));
393
429
  })
394
- .attr('opacity', d => d.children ? 0.3 : 0.85)
430
+ .attr('opacity', d => d.children ? 0.35 : 0.88)
395
431
  .attr('stroke', '#1a1a2e')
396
- .attr('stroke-width', 1)
432
+ .attr('stroke-width', d => d.children ? 1 : 0.5)
397
433
  .attr('rx', 2)
398
- .style('cursor', d => d.children ? 'pointer' : 'default')
434
+ .style('cursor', d => (d.data.data && d.data.data.type === 'folder') ? 'pointer' : 'default')
399
435
  .on('click', (event, d) => {
400
- if (d.children && d.data.data && d.data.data.type === 'folder') {
436
+ if (d.data.data && d.data.data.type === 'folder') {
437
+ event.stopPropagation();
401
438
  zoomTo(d.data.data.path);
402
439
  }
403
440
  })
404
- .on('mouseover', (event, d) => {
441
+ .on('mouseover', function(event, d) {
405
442
  if (!d.data.data) return;
406
- const data = d.data.data;
407
- const name = data.path || d.data.name;
408
- const score = d.children ? data.score : getFileScore(data);
409
- let html = \`<strong>\${name}</strong><br>Score: \${Math.round(score * 100)}%<br>Lines: \${data.lines}\`;
410
- if (data.type === 'folder') {
411
- html += \`<br>Files: \${data.fileCount}\`;
412
- }
413
- if (data.blameScore !== undefined) {
414
- html += \`<br>Blame: \${Math.round(data.blameScore * 100)}%\`;
415
- }
416
- if (data.commitScore !== undefined) {
417
- html += \`<br>Commit: \${Math.round(data.commitScore * 100)}%\`;
418
- }
419
- if (data.reviewScore !== undefined) {
420
- html += \`<br>Review: \${Math.round(data.reviewScore * 100)}%\`;
421
- }
422
- tooltip.innerHTML = html;
423
- tooltip.style.display = 'block';
443
+ d3.select(this).attr('opacity', d.children ? 0.5 : 1).attr('stroke', '#fff');
444
+ showTooltip(d.data.data, event);
424
445
  })
425
446
  .on('mousemove', (event) => {
426
- tooltip.style.left = (event.pageX + 12) + 'px';
427
- tooltip.style.top = (event.pageY - 12) + 'px';
447
+ tooltip.style.left = (event.pageX + 14) + 'px';
448
+ tooltip.style.top = (event.pageY - 14) + 'px';
428
449
  })
429
- .on('mouseout', () => {
450
+ .on('mouseout', function(event, d) {
451
+ d3.select(this).attr('opacity', d.children ? 0.35 : 0.88).attr('stroke', '#1a1a2e');
430
452
  tooltip.style.display = 'none';
431
453
  });
432
454
 
433
455
  // Labels
434
456
  groups.append('text')
435
457
  .attr('x', 4)
436
- .attr('y', 13)
458
+ .attr('y', 14)
437
459
  .attr('fill', '#fff')
438
- .attr('font-size', '11px')
460
+ .attr('font-size', d => d.children ? '11px' : '10px')
439
461
  .attr('font-weight', d => d.children ? 'bold' : 'normal')
462
+ .style('pointer-events', 'none')
440
463
  .text(d => {
441
- const w = (d.x1 - d.x0);
464
+ const w = d.x1 - d.x0;
465
+ const h = d.y1 - d.y0;
442
466
  const name = d.data.name || '';
443
- if (w < 40) return '';
444
- if (w < name.length * 7) return name.slice(0, Math.floor(w / 7)) + '..';
467
+ if (w < 36 || h < 18) return '';
468
+ const maxChars = Math.floor((w - 8) / 6.5);
469
+ if (name.length > maxChars) return name.slice(0, maxChars - 1) + '\\u2026';
445
470
  return name;
446
471
  });
447
472
  }
448
473
 
474
+ function showTooltip(data, event) {
475
+ const tooltip = document.getElementById('tooltip');
476
+ const name = data.path || '';
477
+ const score = getNodeScore(data);
478
+ let html = '<strong>' + name + '</strong>';
479
+ html += '<br>Score: ' + Math.round(score * 100) + '%';
480
+ html += '<br>Lines: ' + data.lines.toLocaleString();
481
+ if (data.type === 'folder') {
482
+ html += '<br>Files: ' + data.fileCount;
483
+ html += '<br><em style="color:#5eadf7">Click to drill down \\u25B6</em>';
484
+ }
485
+ if (data.blameScore !== undefined) {
486
+ html += '<br>Blame: ' + Math.round(data.blameScore * 100) + '%';
487
+ }
488
+ if (data.commitScore !== undefined) {
489
+ html += '<br>Commit: ' + Math.round(data.commitScore * 100) + '%';
490
+ }
491
+ if (data.reviewScore !== undefined) {
492
+ html += '<br>Review: ' + Math.round(data.reviewScore * 100) + '%';
493
+ }
494
+ if (data.isExpired) {
495
+ html += '<br><span style="color:#e94560">Expired</span>';
496
+ }
497
+ tooltip.innerHTML = html;
498
+ tooltip.style.display = 'block';
499
+ tooltip.style.left = (event.pageX + 14) + 'px';
500
+ tooltip.style.top = (event.pageY - 14) + 'px';
501
+ }
502
+
449
503
  function zoomTo(path) {
450
504
  currentPath = path;
451
505
  updateBreadcrumb();
@@ -487,13 +541,1675 @@ async function generateAndOpenHTML(result, repoPath) {
487
541
  await openBrowser(outputPath);
488
542
  }
489
543
 
490
- // src/cli/index.ts
491
- function createProgram() {
492
- const program2 = new Command();
493
- program2.name("gitfamiliar").description("Visualize your code familiarity from Git history").version("0.1.0").option("-m, --mode <mode>", "Scoring mode: binary, authorship, review-coverage, weighted", "binary").option("-u, --user <user>", "Git user name or email (defaults to git config)").option("-f, --filter <filter>", "Filter mode: all, written, reviewed", "all").option("-e, --expiration <policy>", "Expiration policy: never, time:180d, change:50%, combined:365d:50%", "never").option("--html", "Generate HTML treemap report", false).option("-w, --weights <weights>", 'Weights for weighted mode: blame,commit,review (e.g., "0.5,0.35,0.15")').action(async (rawOptions) => {
494
- try {
495
- const repoPath = process.cwd();
496
- const options = parseOptions(rawOptions, repoPath);
544
+ // src/git/contributors.ts
545
+ var COMMIT_SEP = "GITFAMILIAR_SEP";
546
+ async function getAllContributors(gitClient, minCommits = 1) {
547
+ const output = await gitClient.getLog([
548
+ "--all",
549
+ `--format=%aN|%aE`
550
+ ]);
551
+ const counts = /* @__PURE__ */ new Map();
552
+ for (const line of output.trim().split("\n")) {
553
+ if (!line.includes("|")) continue;
554
+ const [name, email] = line.split("|", 2);
555
+ if (!name || !email) continue;
556
+ const key = email.toLowerCase();
557
+ const existing = counts.get(key);
558
+ if (existing) {
559
+ existing.count++;
560
+ } else {
561
+ counts.set(key, { name: name.trim(), email: email.trim(), count: 1 });
562
+ }
563
+ }
564
+ return Array.from(counts.values()).filter((c) => c.count >= minCommits).sort((a, b) => b.count - a.count).map((c) => ({ name: c.name, email: c.email }));
565
+ }
566
+ async function bulkGetFileContributors(gitClient, trackedFiles) {
567
+ const output = await gitClient.getLog([
568
+ "--all",
569
+ "--name-only",
570
+ `--format=${COMMIT_SEP}%aN|%aE`
571
+ ]);
572
+ const result = /* @__PURE__ */ new Map();
573
+ let currentAuthor = "";
574
+ for (const line of output.split("\n")) {
575
+ if (line.startsWith(COMMIT_SEP)) {
576
+ const parts = line.slice(COMMIT_SEP.length).split("|", 2);
577
+ currentAuthor = parts[0]?.trim() || "";
578
+ continue;
579
+ }
580
+ const filePath = line.trim();
581
+ if (!filePath || !currentAuthor) continue;
582
+ if (!trackedFiles.has(filePath)) continue;
583
+ let contributors = result.get(filePath);
584
+ if (!contributors) {
585
+ contributors = /* @__PURE__ */ new Set();
586
+ result.set(filePath, contributors);
587
+ }
588
+ contributors.add(currentAuthor);
589
+ }
590
+ return result;
591
+ }
592
+
593
+ // src/core/team-coverage.ts
594
+ async function computeTeamCoverage(options) {
595
+ const gitClient = new GitClient(options.repoPath);
596
+ if (!await gitClient.isRepo()) {
597
+ throw new Error(`"${options.repoPath}" is not a git repository.`);
598
+ }
599
+ const repoRoot = await gitClient.getRepoRoot();
600
+ const repoName = await gitClient.getRepoName();
601
+ const filter = createFilter(repoRoot);
602
+ const tree = await buildFileTree(gitClient, filter);
603
+ const trackedFiles = /* @__PURE__ */ new Set();
604
+ walkFiles(tree, (f) => trackedFiles.add(f.path));
605
+ const fileContributors = await bulkGetFileContributors(gitClient, trackedFiles);
606
+ const allContributors = await getAllContributors(gitClient);
607
+ const coverageTree = buildCoverageTree(tree, fileContributors);
608
+ const riskFiles = [];
609
+ walkCoverageFiles(coverageTree, (f) => {
610
+ if (f.contributorCount <= 1) {
611
+ riskFiles.push(f);
612
+ }
613
+ });
614
+ riskFiles.sort((a, b) => a.contributorCount - b.contributorCount);
615
+ return {
616
+ tree: coverageTree,
617
+ repoName,
618
+ totalContributors: allContributors.length,
619
+ totalFiles: tree.fileCount,
620
+ riskFiles,
621
+ overallBusFactor: calculateBusFactor(fileContributors)
622
+ };
623
+ }
624
+ function classifyRisk(contributorCount) {
625
+ if (contributorCount <= 1) return "risk";
626
+ if (contributorCount <= 3) return "moderate";
627
+ return "safe";
628
+ }
629
+ function buildCoverageTree(node, fileContributors) {
630
+ const children = [];
631
+ for (const child of node.children) {
632
+ if (child.type === "file") {
633
+ const contributors = fileContributors.get(child.path);
634
+ const names = contributors ? Array.from(contributors) : [];
635
+ children.push({
636
+ type: "file",
637
+ path: child.path,
638
+ lines: child.lines,
639
+ contributorCount: names.length,
640
+ contributors: names,
641
+ riskLevel: classifyRisk(names.length)
642
+ });
643
+ } else {
644
+ children.push(buildCoverageTree(child, fileContributors));
645
+ }
646
+ }
647
+ const fileScores = [];
648
+ walkCoverageFiles({ type: "folder", path: "", lines: 0, fileCount: 0, avgContributors: 0, busFactor: 0, riskLevel: "safe", children }, (f) => {
649
+ fileScores.push(f);
650
+ });
651
+ const totalContributors = fileScores.reduce((sum, f) => sum + f.contributorCount, 0);
652
+ const avgContributors = fileScores.length > 0 ? totalContributors / fileScores.length : 0;
653
+ const folderFileContributors = /* @__PURE__ */ new Map();
654
+ for (const f of fileScores) {
655
+ folderFileContributors.set(f.path, new Set(f.contributors));
656
+ }
657
+ const busFactor = calculateBusFactor(folderFileContributors);
658
+ return {
659
+ type: "folder",
660
+ path: node.path,
661
+ lines: node.lines,
662
+ fileCount: node.fileCount,
663
+ avgContributors: Math.round(avgContributors * 10) / 10,
664
+ busFactor,
665
+ riskLevel: classifyRisk(busFactor),
666
+ children
667
+ };
668
+ }
669
+ function walkCoverageFiles(node, visitor) {
670
+ if (node.type === "file") {
671
+ visitor(node);
672
+ } else {
673
+ for (const child of node.children) {
674
+ walkCoverageFiles(child, visitor);
675
+ }
676
+ }
677
+ }
678
+ function calculateBusFactor(fileContributors) {
679
+ const totalFiles = fileContributors.size;
680
+ if (totalFiles === 0) return 0;
681
+ const target = Math.ceil(totalFiles * 0.5);
682
+ const contributorFiles = /* @__PURE__ */ new Map();
683
+ for (const [file, contributors] of fileContributors) {
684
+ for (const contributor of contributors) {
685
+ let files = contributorFiles.get(contributor);
686
+ if (!files) {
687
+ files = /* @__PURE__ */ new Set();
688
+ contributorFiles.set(contributor, files);
689
+ }
690
+ files.add(file);
691
+ }
692
+ }
693
+ const coveredFiles = /* @__PURE__ */ new Set();
694
+ let count = 0;
695
+ while (coveredFiles.size < target && contributorFiles.size > 0) {
696
+ let bestContributor = "";
697
+ let bestNewFiles = 0;
698
+ for (const [contributor, files2] of contributorFiles) {
699
+ let newFiles = 0;
700
+ for (const file of files2) {
701
+ if (!coveredFiles.has(file)) newFiles++;
702
+ }
703
+ if (newFiles > bestNewFiles) {
704
+ bestNewFiles = newFiles;
705
+ bestContributor = contributor;
706
+ }
707
+ }
708
+ if (bestNewFiles === 0) break;
709
+ const files = contributorFiles.get(bestContributor);
710
+ for (const file of files) {
711
+ coveredFiles.add(file);
712
+ }
713
+ contributorFiles.delete(bestContributor);
714
+ count++;
715
+ }
716
+ return count;
717
+ }
718
+
719
+ // src/cli/output/coverage-terminal.ts
720
+ import chalk2 from "chalk";
721
+ function riskBadge(level) {
722
+ switch (level) {
723
+ case "risk":
724
+ return chalk2.bgRed.white(" RISK ");
725
+ case "moderate":
726
+ return chalk2.bgYellow.black(" MOD ");
727
+ case "safe":
728
+ return chalk2.bgGreen.black(" SAFE ");
729
+ default:
730
+ return level;
731
+ }
732
+ }
733
+ function riskColor(level) {
734
+ switch (level) {
735
+ case "risk":
736
+ return chalk2.red;
737
+ case "moderate":
738
+ return chalk2.yellow;
739
+ default:
740
+ return chalk2.green;
741
+ }
742
+ }
743
+ function renderFolder2(node, indent, maxDepth) {
744
+ const lines = [];
745
+ const sorted = [...node.children].sort((a, b) => {
746
+ if (a.type !== b.type) return a.type === "folder" ? -1 : 1;
747
+ return a.path.localeCompare(b.path);
748
+ });
749
+ for (const child of sorted) {
750
+ if (child.type === "folder") {
751
+ const prefix = " ".repeat(indent);
752
+ const name = (child.path.split("/").pop() || child.path) + "/";
753
+ const color = riskColor(child.riskLevel);
754
+ lines.push(
755
+ `${prefix}${chalk2.bold(name.padEnd(24))} ${String(child.avgContributors).padStart(4)} avg ${String(child.busFactor).padStart(2)} ${riskBadge(child.riskLevel)}`
756
+ );
757
+ if (indent < maxDepth) {
758
+ lines.push(...renderFolder2(child, indent + 1, maxDepth));
759
+ }
760
+ }
761
+ }
762
+ return lines;
763
+ }
764
+ function renderCoverageTerminal(result) {
765
+ console.log("");
766
+ console.log(
767
+ chalk2.bold(
768
+ `GitFamiliar \u2014 Team Coverage (${result.totalFiles} files, ${result.totalContributors} contributors)`
769
+ )
770
+ );
771
+ console.log("");
772
+ const bfColor = result.overallBusFactor <= 1 ? chalk2.red : result.overallBusFactor <= 2 ? chalk2.yellow : chalk2.green;
773
+ console.log(`Overall Bus Factor: ${bfColor.bold(String(result.overallBusFactor))}`);
774
+ console.log("");
775
+ if (result.riskFiles.length > 0) {
776
+ console.log(chalk2.red.bold(`Risk Files (0-1 contributors):`));
777
+ const displayFiles = result.riskFiles.slice(0, 20);
778
+ for (const file of displayFiles) {
779
+ const count = file.contributorCount;
780
+ const names = file.contributors.join(", ");
781
+ const label = count === 0 ? chalk2.red("0 people") : chalk2.yellow(`1 person (${names})`);
782
+ console.log(` ${file.path.padEnd(40)} ${label}`);
783
+ }
784
+ if (result.riskFiles.length > 20) {
785
+ console.log(
786
+ chalk2.gray(` ... and ${result.riskFiles.length - 20} more`)
787
+ );
788
+ }
789
+ console.log("");
790
+ } else {
791
+ console.log(chalk2.green("No high-risk files found."));
792
+ console.log("");
793
+ }
794
+ console.log(chalk2.bold("Folder Coverage:"));
795
+ console.log(
796
+ chalk2.gray(
797
+ ` ${"Folder".padEnd(24)} ${"Avg Contrib".padStart(11)} ${"Bus Factor".padStart(10)} Risk`
798
+ )
799
+ );
800
+ const folderLines = renderFolder2(result.tree, 1, 2);
801
+ for (const line of folderLines) {
802
+ console.log(line);
803
+ }
804
+ console.log("");
805
+ }
806
+
807
+ // src/cli/output/coverage-html.ts
808
+ import { writeFileSync as writeFileSync2 } from "fs";
809
+ import { join as join2 } from "path";
810
+ function generateCoverageHTML(result) {
811
+ const dataJson = JSON.stringify(result.tree);
812
+ const riskFilesJson = JSON.stringify(result.riskFiles);
813
+ return `<!DOCTYPE html>
814
+ <html lang="en">
815
+ <head>
816
+ <meta charset="UTF-8">
817
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
818
+ <title>GitFamiliar \u2014 Team Coverage \u2014 ${result.repoName}</title>
819
+ <style>
820
+ * { margin: 0; padding: 0; box-sizing: border-box; }
821
+ body {
822
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
823
+ background: #1a1a2e;
824
+ color: #e0e0e0;
825
+ overflow: hidden;
826
+ }
827
+ #header {
828
+ padding: 16px 24px;
829
+ background: #16213e;
830
+ border-bottom: 1px solid #0f3460;
831
+ display: flex;
832
+ align-items: center;
833
+ justify-content: space-between;
834
+ }
835
+ #header h1 { font-size: 18px; color: #e94560; }
836
+ #header .info { font-size: 14px; color: #a0a0a0; }
837
+ #breadcrumb {
838
+ padding: 8px 24px;
839
+ background: #16213e;
840
+ font-size: 13px;
841
+ border-bottom: 1px solid #0f3460;
842
+ }
843
+ #breadcrumb span { cursor: pointer; color: #5eadf7; }
844
+ #breadcrumb span:hover { text-decoration: underline; }
845
+ #breadcrumb .sep { color: #666; margin: 0 4px; }
846
+ #main { display: flex; height: calc(100vh - 90px); }
847
+ #treemap { flex: 1; }
848
+ #sidebar {
849
+ width: 300px;
850
+ background: #16213e;
851
+ border-left: 1px solid #0f3460;
852
+ overflow-y: auto;
853
+ padding: 16px;
854
+ }
855
+ #sidebar h3 { font-size: 14px; margin-bottom: 12px; color: #e94560; }
856
+ #sidebar .risk-file {
857
+ padding: 6px 0;
858
+ border-bottom: 1px solid #0f3460;
859
+ font-size: 12px;
860
+ }
861
+ #sidebar .risk-file .path { color: #e0e0e0; word-break: break-all; }
862
+ #sidebar .risk-file .meta { color: #888; margin-top: 2px; }
863
+ #tooltip {
864
+ position: absolute;
865
+ pointer-events: none;
866
+ background: rgba(22, 33, 62, 0.95);
867
+ border: 1px solid #0f3460;
868
+ border-radius: 6px;
869
+ padding: 10px 14px;
870
+ font-size: 13px;
871
+ line-height: 1.6;
872
+ display: none;
873
+ z-index: 100;
874
+ max-width: 320px;
875
+ }
876
+ #legend {
877
+ position: absolute;
878
+ bottom: 16px;
879
+ left: 16px;
880
+ background: rgba(22, 33, 62, 0.9);
881
+ border: 1px solid #0f3460;
882
+ border-radius: 6px;
883
+ padding: 10px;
884
+ font-size: 12px;
885
+ }
886
+ #legend .row { display: flex; align-items: center; gap: 6px; margin: 3px 0; }
887
+ #legend .swatch { width: 14px; height: 14px; border-radius: 3px; }
888
+ </style>
889
+ </head>
890
+ <body>
891
+ <div id="header">
892
+ <h1>GitFamiliar \u2014 Team Coverage \u2014 ${result.repoName}</h1>
893
+ <div class="info">${result.totalFiles} files | ${result.totalContributors} contributors | Bus Factor: ${result.overallBusFactor}</div>
894
+ </div>
895
+ <div id="breadcrumb"><span onclick="zoomTo('')">root</span></div>
896
+ <div id="main">
897
+ <div id="treemap"></div>
898
+ <div id="sidebar">
899
+ <h3>Risk Files (0-1 contributors)</h3>
900
+ <div id="risk-list"></div>
901
+ </div>
902
+ </div>
903
+ <div id="tooltip"></div>
904
+ <div id="legend">
905
+ <div>Contributors</div>
906
+ <div class="row"><div class="swatch" style="background:#e94560"></div> 0\u20131 (Risk)</div>
907
+ <div class="row"><div class="swatch" style="background:#f5a623"></div> 2\u20133 (Moderate)</div>
908
+ <div class="row"><div class="swatch" style="background:#27ae60"></div> 4+ (Safe)</div>
909
+ </div>
910
+
911
+ <script src="https://d3js.org/d3.v7.min.js"></script>
912
+ <script>
913
+ const rawData = ${dataJson};
914
+ const riskFiles = ${riskFilesJson};
915
+ let currentPath = '';
916
+
917
+ function coverageColor(count) {
918
+ if (count <= 0) return '#e94560';
919
+ if (count === 1) return '#d63c57';
920
+ if (count <= 3) return '#f5a623';
921
+ return '#27ae60';
922
+ }
923
+
924
+ function folderColor(riskLevel) {
925
+ switch (riskLevel) {
926
+ case 'risk': return '#e94560';
927
+ case 'moderate': return '#f5a623';
928
+ default: return '#27ae60';
929
+ }
930
+ }
931
+
932
+ function findNode(node, path) {
933
+ if (node.path === path) return node;
934
+ if (node.children) {
935
+ for (const child of node.children) {
936
+ const found = findNode(child, path);
937
+ if (found) return found;
938
+ }
939
+ }
940
+ return null;
941
+ }
942
+
943
+ function buildHierarchy(node) {
944
+ if (node.type === 'file') {
945
+ return { name: node.path.split('/').pop(), data: node, value: Math.max(1, node.lines) };
946
+ }
947
+ return {
948
+ name: node.path.split('/').pop() || node.path,
949
+ data: node,
950
+ children: (node.children || []).map(c => buildHierarchy(c)),
951
+ };
952
+ }
953
+
954
+ function render() {
955
+ const container = document.getElementById('treemap');
956
+ container.innerHTML = '';
957
+
958
+ const headerH = document.getElementById('header').offsetHeight;
959
+ const breadcrumbH = document.getElementById('breadcrumb').offsetHeight;
960
+ const width = container.offsetWidth;
961
+ const height = window.innerHeight - headerH - breadcrumbH;
962
+
963
+ const targetNode = currentPath ? findNode(rawData, currentPath) : rawData;
964
+ if (!targetNode || !targetNode.children || targetNode.children.length === 0) return;
965
+
966
+ const hierarchyData = {
967
+ name: targetNode.path || 'root',
968
+ children: targetNode.children.map(c => buildHierarchy(c)),
969
+ };
970
+
971
+ const root = d3.hierarchy(hierarchyData)
972
+ .sum(d => d.value || 0)
973
+ .sort((a, b) => (b.value || 0) - (a.value || 0));
974
+
975
+ d3.treemap()
976
+ .size([width, height])
977
+ .padding(2)
978
+ .paddingTop(20)
979
+ .round(true)(root);
980
+
981
+ const svg = d3.select('#treemap')
982
+ .append('svg')
983
+ .attr('width', width)
984
+ .attr('height', height);
985
+
986
+ const tooltip = document.getElementById('tooltip');
987
+ const nodes = root.descendants().filter(d => d.depth > 0);
988
+
989
+ const groups = svg.selectAll('g')
990
+ .data(nodes)
991
+ .join('g')
992
+ .attr('transform', d => \`translate(\${d.x0},\${d.y0})\`);
993
+
994
+ groups.append('rect')
995
+ .attr('width', d => Math.max(0, d.x1 - d.x0))
996
+ .attr('height', d => Math.max(0, d.y1 - d.y0))
997
+ .attr('fill', d => {
998
+ if (!d.data.data) return '#333';
999
+ if (d.data.data.type === 'file') return coverageColor(d.data.data.contributorCount);
1000
+ return folderColor(d.data.data.riskLevel);
1001
+ })
1002
+ .attr('opacity', d => d.children ? 0.35 : 0.88)
1003
+ .attr('stroke', '#1a1a2e')
1004
+ .attr('stroke-width', d => d.children ? 1 : 0.5)
1005
+ .attr('rx', 2)
1006
+ .style('cursor', d => (d.data.data && d.data.data.type === 'folder') ? 'pointer' : 'default')
1007
+ .on('click', (event, d) => {
1008
+ if (d.data.data && d.data.data.type === 'folder') {
1009
+ event.stopPropagation();
1010
+ zoomTo(d.data.data.path);
1011
+ }
1012
+ })
1013
+ .on('mouseover', function(event, d) {
1014
+ if (!d.data.data) return;
1015
+ d3.select(this).attr('opacity', d.children ? 0.5 : 1).attr('stroke', '#fff');
1016
+ showTooltip(d.data.data, event);
1017
+ })
1018
+ .on('mousemove', (event) => {
1019
+ tooltip.style.left = (event.pageX + 14) + 'px';
1020
+ tooltip.style.top = (event.pageY - 14) + 'px';
1021
+ })
1022
+ .on('mouseout', function(event, d) {
1023
+ d3.select(this).attr('opacity', d.children ? 0.35 : 0.88).attr('stroke', '#1a1a2e');
1024
+ tooltip.style.display = 'none';
1025
+ });
1026
+
1027
+ groups.append('text')
1028
+ .attr('x', 4)
1029
+ .attr('y', 14)
1030
+ .attr('fill', '#fff')
1031
+ .attr('font-size', d => d.children ? '11px' : '10px')
1032
+ .attr('font-weight', d => d.children ? 'bold' : 'normal')
1033
+ .style('pointer-events', 'none')
1034
+ .text(d => {
1035
+ const w = d.x1 - d.x0;
1036
+ const h = d.y1 - d.y0;
1037
+ const name = d.data.name || '';
1038
+ if (w < 36 || h < 18) return '';
1039
+ const maxChars = Math.floor((w - 8) / 6.5);
1040
+ if (name.length > maxChars) return name.slice(0, maxChars - 1) + '\\u2026';
1041
+ return name;
1042
+ });
1043
+ }
1044
+
1045
+ function showTooltip(data, event) {
1046
+ const tooltip = document.getElementById('tooltip');
1047
+ let html = '<strong>' + data.path + '</strong>';
1048
+ if (data.type === 'file') {
1049
+ html += '<br>Contributors: ' + data.contributorCount;
1050
+ if (data.contributors.length > 0) {
1051
+ html += '<br>' + data.contributors.slice(0, 8).join(', ');
1052
+ if (data.contributors.length > 8) html += ', ...';
1053
+ }
1054
+ html += '<br>Lines: ' + data.lines.toLocaleString();
1055
+ } else {
1056
+ html += '<br>Files: ' + data.fileCount;
1057
+ html += '<br>Avg Contributors: ' + data.avgContributors;
1058
+ html += '<br>Bus Factor: ' + data.busFactor;
1059
+ html += '<br><em style="color:#5eadf7">Click to drill down \\u25B6</em>';
1060
+ }
1061
+ tooltip.innerHTML = html;
1062
+ tooltip.style.display = 'block';
1063
+ tooltip.style.left = (event.pageX + 14) + 'px';
1064
+ tooltip.style.top = (event.pageY - 14) + 'px';
1065
+ }
1066
+
1067
+ function zoomTo(path) {
1068
+ currentPath = path;
1069
+ const el = document.getElementById('breadcrumb');
1070
+ const parts = path ? path.split('/') : [];
1071
+ let html = '<span onclick="zoomTo(\\'\\')">root</span>';
1072
+ let accumulated = '';
1073
+ for (const part of parts) {
1074
+ accumulated = accumulated ? accumulated + '/' + part : part;
1075
+ const p = accumulated;
1076
+ html += '<span class="sep">/</span><span onclick="zoomTo(\\'' + p + '\\')">' + part + '</span>';
1077
+ }
1078
+ el.innerHTML = html;
1079
+ render();
1080
+ }
1081
+
1082
+ // Render risk sidebar
1083
+ function renderRiskSidebar() {
1084
+ const container = document.getElementById('risk-list');
1085
+ if (riskFiles.length === 0) {
1086
+ container.innerHTML = '<div style="color:#888">No high-risk files found.</div>';
1087
+ return;
1088
+ }
1089
+ let html = '';
1090
+ for (const f of riskFiles.slice(0, 50)) {
1091
+ const countLabel = f.contributorCount === 0 ? '0 people' : '1 person (' + f.contributors[0] + ')';
1092
+ html += '<div class="risk-file"><div class="path">' + f.path + '</div><div class="meta">' + countLabel + '</div></div>';
1093
+ }
1094
+ if (riskFiles.length > 50) {
1095
+ html += '<div style="color:#888;padding:8px 0">... and ' + (riskFiles.length - 50) + ' more</div>';
1096
+ }
1097
+ container.innerHTML = html;
1098
+ }
1099
+
1100
+ window.addEventListener('resize', render);
1101
+ renderRiskSidebar();
1102
+ render();
1103
+ </script>
1104
+ </body>
1105
+ </html>`;
1106
+ }
1107
+ async function generateAndOpenCoverageHTML(result, repoPath) {
1108
+ const html = generateCoverageHTML(result);
1109
+ const outputPath = join2(repoPath, "gitfamiliar-coverage.html");
1110
+ writeFileSync2(outputPath, html, "utf-8");
1111
+ console.log(`Coverage report generated: ${outputPath}`);
1112
+ await openBrowser(outputPath);
1113
+ }
1114
+
1115
+ // src/core/multi-user.ts
1116
+ async function computeMultiUser(options) {
1117
+ const gitClient = new GitClient(options.repoPath);
1118
+ if (!await gitClient.isRepo()) {
1119
+ throw new Error(`"${options.repoPath}" is not a git repository.`);
1120
+ }
1121
+ const repoName = await gitClient.getRepoName();
1122
+ let userNames;
1123
+ if (options.team) {
1124
+ const contributors = await getAllContributors(gitClient, 3);
1125
+ userNames = contributors.map((c) => c.name);
1126
+ if (userNames.length === 0) {
1127
+ throw new Error("No contributors found with 3+ commits.");
1128
+ }
1129
+ console.log(`Found ${userNames.length} contributors with 3+ commits`);
1130
+ } else if (Array.isArray(options.user)) {
1131
+ userNames = options.user;
1132
+ } else if (options.user) {
1133
+ userNames = [options.user];
1134
+ } else {
1135
+ const user = await resolveUser(gitClient);
1136
+ userNames = [user.name || user.email];
1137
+ }
1138
+ const results = [];
1139
+ await processBatch(
1140
+ userNames,
1141
+ async (userName) => {
1142
+ const userOptions = {
1143
+ ...options,
1144
+ user: userName,
1145
+ team: false,
1146
+ teamCoverage: false
1147
+ };
1148
+ const result = await computeFamiliarity(userOptions);
1149
+ results.push({ userName, result });
1150
+ },
1151
+ 3
1152
+ );
1153
+ const users = results.map((r) => ({
1154
+ name: r.result.userName,
1155
+ email: ""
1156
+ }));
1157
+ const tree = mergeResults(results);
1158
+ const userSummaries = results.map((r) => ({
1159
+ user: { name: r.result.userName, email: "" },
1160
+ writtenCount: r.result.writtenCount,
1161
+ reviewedCount: r.result.reviewedCount,
1162
+ overallScore: r.result.tree.score
1163
+ }));
1164
+ return {
1165
+ tree,
1166
+ repoName,
1167
+ users,
1168
+ mode: options.mode,
1169
+ totalFiles: results[0]?.result.totalFiles || 0,
1170
+ userSummaries
1171
+ };
1172
+ }
1173
+ function mergeResults(results) {
1174
+ if (results.length === 0) {
1175
+ return {
1176
+ type: "folder",
1177
+ path: "",
1178
+ lines: 0,
1179
+ score: 0,
1180
+ fileCount: 0,
1181
+ userScores: [],
1182
+ children: []
1183
+ };
1184
+ }
1185
+ const baseTree = results[0].result.tree;
1186
+ const fileScoresMap = /* @__PURE__ */ new Map();
1187
+ for (const { result } of results) {
1188
+ const userName = result.userName;
1189
+ walkFiles(result.tree, (file) => {
1190
+ let scores = fileScoresMap.get(file.path);
1191
+ if (!scores) {
1192
+ scores = [];
1193
+ fileScoresMap.set(file.path, scores);
1194
+ }
1195
+ scores.push({
1196
+ user: { name: userName, email: "" },
1197
+ score: file.score,
1198
+ isWritten: file.isWritten,
1199
+ isReviewed: file.isReviewed
1200
+ });
1201
+ });
1202
+ }
1203
+ return convertFolder(baseTree, fileScoresMap, results);
1204
+ }
1205
+ function convertFolder(node, fileScoresMap, results) {
1206
+ const children = [];
1207
+ for (const child of node.children) {
1208
+ if (child.type === "file") {
1209
+ const userScores2 = fileScoresMap.get(child.path) || [];
1210
+ const avgScore2 = userScores2.length > 0 ? userScores2.reduce((sum, s) => sum + s.score, 0) / userScores2.length : 0;
1211
+ children.push({
1212
+ type: "file",
1213
+ path: child.path,
1214
+ lines: child.lines,
1215
+ score: avgScore2,
1216
+ userScores: userScores2
1217
+ });
1218
+ } else {
1219
+ children.push(convertFolder(child, fileScoresMap, results));
1220
+ }
1221
+ }
1222
+ const userScores = results.map(({ result }) => {
1223
+ const folderNode = findFolderInTree(result.tree, node.path);
1224
+ return {
1225
+ user: { name: result.userName, email: "" },
1226
+ score: folderNode?.score || 0
1227
+ };
1228
+ });
1229
+ const avgScore = userScores.length > 0 ? userScores.reduce((sum, s) => sum + s.score, 0) / userScores.length : 0;
1230
+ return {
1231
+ type: "folder",
1232
+ path: node.path,
1233
+ lines: node.lines,
1234
+ score: avgScore,
1235
+ fileCount: node.fileCount,
1236
+ userScores,
1237
+ children
1238
+ };
1239
+ }
1240
+ function findFolderInTree(node, targetPath) {
1241
+ if (node.type === "folder") {
1242
+ if (node.path === targetPath) return node;
1243
+ for (const child of node.children) {
1244
+ const found = findFolderInTree(child, targetPath);
1245
+ if (found) return found;
1246
+ }
1247
+ }
1248
+ return null;
1249
+ }
1250
+
1251
+ // src/cli/output/multi-user-terminal.ts
1252
+ import chalk3 from "chalk";
1253
+ var BAR_WIDTH2 = 20;
1254
+ var FILLED_CHAR2 = "\u2588";
1255
+ var EMPTY_CHAR2 = "\u2591";
1256
+ function makeBar2(score, width = BAR_WIDTH2) {
1257
+ const filled = Math.round(score * width);
1258
+ const empty = width - filled;
1259
+ const bar = FILLED_CHAR2.repeat(filled) + EMPTY_CHAR2.repeat(empty);
1260
+ if (score >= 0.8) return chalk3.green(bar);
1261
+ if (score >= 0.5) return chalk3.yellow(bar);
1262
+ if (score > 0) return chalk3.red(bar);
1263
+ return chalk3.gray(bar);
1264
+ }
1265
+ function formatPercent2(score) {
1266
+ return `${Math.round(score * 100)}%`;
1267
+ }
1268
+ function getModeLabel2(mode) {
1269
+ switch (mode) {
1270
+ case "binary":
1271
+ return "Binary mode";
1272
+ case "authorship":
1273
+ return "Authorship mode";
1274
+ case "review-coverage":
1275
+ return "Review Coverage mode";
1276
+ case "weighted":
1277
+ return "Weighted mode";
1278
+ default:
1279
+ return mode;
1280
+ }
1281
+ }
1282
+ function truncateName(name, maxLen) {
1283
+ if (name.length <= maxLen) return name;
1284
+ return name.slice(0, maxLen - 1) + "\u2026";
1285
+ }
1286
+ function renderFolder3(node, indent, maxDepth, nameWidth) {
1287
+ const lines = [];
1288
+ const sorted = [...node.children].sort((a, b) => {
1289
+ if (a.type !== b.type) return a.type === "folder" ? -1 : 1;
1290
+ return a.path.localeCompare(b.path);
1291
+ });
1292
+ for (const child of sorted) {
1293
+ if (child.type === "folder") {
1294
+ const prefix = " ".repeat(indent);
1295
+ const name = (child.path.split("/").pop() || child.path) + "/";
1296
+ const displayName = truncateName(name, nameWidth).padEnd(nameWidth);
1297
+ const scores = child.userScores.map((s) => formatPercent2(s.score).padStart(5)).join(" ");
1298
+ lines.push(`${prefix}${chalk3.bold(displayName)} ${scores}`);
1299
+ if (indent < maxDepth) {
1300
+ lines.push(...renderFolder3(child, indent + 1, maxDepth, nameWidth));
1301
+ }
1302
+ }
1303
+ }
1304
+ return lines;
1305
+ }
1306
+ function renderMultiUserTerminal(result) {
1307
+ const { tree, repoName, mode, userSummaries, totalFiles } = result;
1308
+ console.log("");
1309
+ console.log(
1310
+ chalk3.bold(
1311
+ `GitFamiliar \u2014 ${repoName} (${getModeLabel2(mode)}, ${userSummaries.length} users)`
1312
+ )
1313
+ );
1314
+ console.log("");
1315
+ console.log(chalk3.bold("Overall:"));
1316
+ for (const summary of userSummaries) {
1317
+ const name = truncateName(summary.user.name, 14).padEnd(14);
1318
+ const bar = makeBar2(summary.overallScore);
1319
+ const pct = formatPercent2(summary.overallScore);
1320
+ if (mode === "binary") {
1321
+ console.log(
1322
+ ` ${name} ${bar} ${pct.padStart(4)} (${summary.writtenCount + summary.reviewedCount}/${totalFiles} files)`
1323
+ );
1324
+ } else {
1325
+ console.log(` ${name} ${bar} ${pct.padStart(4)}`);
1326
+ }
1327
+ }
1328
+ console.log("");
1329
+ const nameWidth = 20;
1330
+ const headerNames = userSummaries.map((s) => truncateName(s.user.name, 7).padStart(7)).join(" ");
1331
+ console.log(
1332
+ chalk3.bold("Folders:") + " ".repeat(nameWidth - 4) + headerNames
1333
+ );
1334
+ const folderLines = renderFolder3(tree, 1, 2, nameWidth);
1335
+ for (const line of folderLines) {
1336
+ console.log(line);
1337
+ }
1338
+ console.log("");
1339
+ }
1340
+
1341
+ // src/cli/output/multi-user-html.ts
1342
+ import { writeFileSync as writeFileSync3 } from "fs";
1343
+ import { join as join3 } from "path";
1344
+ function generateMultiUserHTML(result) {
1345
+ const dataJson = JSON.stringify(result.tree);
1346
+ const summariesJson = JSON.stringify(result.userSummaries);
1347
+ const usersJson = JSON.stringify(result.users.map((u) => u.name));
1348
+ return `<!DOCTYPE html>
1349
+ <html lang="en">
1350
+ <head>
1351
+ <meta charset="UTF-8">
1352
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1353
+ <title>GitFamiliar \u2014 ${result.repoName} \u2014 Multi-User</title>
1354
+ <style>
1355
+ * { margin: 0; padding: 0; box-sizing: border-box; }
1356
+ body {
1357
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1358
+ background: #1a1a2e;
1359
+ color: #e0e0e0;
1360
+ overflow: hidden;
1361
+ }
1362
+ #header {
1363
+ padding: 16px 24px;
1364
+ background: #16213e;
1365
+ border-bottom: 1px solid #0f3460;
1366
+ display: flex;
1367
+ align-items: center;
1368
+ justify-content: space-between;
1369
+ }
1370
+ #header h1 { font-size: 18px; color: #e94560; }
1371
+ #header .controls { display: flex; align-items: center; gap: 12px; }
1372
+ #header select {
1373
+ padding: 4px 12px;
1374
+ border: 1px solid #0f3460;
1375
+ background: #1a1a2e;
1376
+ color: #e0e0e0;
1377
+ border-radius: 4px;
1378
+ font-size: 13px;
1379
+ }
1380
+ #header .info { font-size: 14px; color: #a0a0a0; }
1381
+ #breadcrumb {
1382
+ padding: 8px 24px;
1383
+ background: #16213e;
1384
+ font-size: 13px;
1385
+ border-bottom: 1px solid #0f3460;
1386
+ }
1387
+ #breadcrumb span { cursor: pointer; color: #5eadf7; }
1388
+ #breadcrumb span:hover { text-decoration: underline; }
1389
+ #breadcrumb .sep { color: #666; margin: 0 4px; }
1390
+ #treemap { width: 100%; }
1391
+ #tooltip {
1392
+ position: absolute;
1393
+ pointer-events: none;
1394
+ background: rgba(22, 33, 62, 0.95);
1395
+ border: 1px solid #0f3460;
1396
+ border-radius: 6px;
1397
+ padding: 10px 14px;
1398
+ font-size: 13px;
1399
+ line-height: 1.6;
1400
+ display: none;
1401
+ z-index: 100;
1402
+ max-width: 350px;
1403
+ }
1404
+ #legend {
1405
+ position: absolute;
1406
+ bottom: 16px;
1407
+ right: 16px;
1408
+ background: rgba(22, 33, 62, 0.9);
1409
+ border: 1px solid #0f3460;
1410
+ border-radius: 6px;
1411
+ padding: 10px;
1412
+ font-size: 12px;
1413
+ }
1414
+ #legend .gradient-bar {
1415
+ width: 120px; height: 12px;
1416
+ background: linear-gradient(to right, #e94560, #f5a623, #27ae60);
1417
+ border-radius: 3px; margin: 4px 0;
1418
+ }
1419
+ #legend .labels { display: flex; justify-content: space-between; font-size: 10px; color: #888; }
1420
+ </style>
1421
+ </head>
1422
+ <body>
1423
+ <div id="header">
1424
+ <h1>GitFamiliar \u2014 ${result.repoName}</h1>
1425
+ <div class="controls">
1426
+ <span style="color:#888;font-size:13px;">View as:</span>
1427
+ <select id="userSelect" onchange="changeUser()"></select>
1428
+ <div class="info">${result.mode} mode | ${result.totalFiles} files</div>
1429
+ </div>
1430
+ </div>
1431
+ <div id="breadcrumb"><span onclick="zoomTo('')">root</span></div>
1432
+ <div id="treemap"></div>
1433
+ <div id="tooltip"></div>
1434
+ <div id="legend">
1435
+ <div>Familiarity</div>
1436
+ <div class="gradient-bar"></div>
1437
+ <div class="labels"><span>0%</span><span>50%</span><span>100%</span></div>
1438
+ </div>
1439
+
1440
+ <script src="https://d3js.org/d3.v7.min.js"></script>
1441
+ <script>
1442
+ const rawData = ${dataJson};
1443
+ const userNames = ${usersJson};
1444
+ const summaries = ${summariesJson};
1445
+ let currentUser = 0;
1446
+ let currentPath = '';
1447
+
1448
+ // Populate user selector
1449
+ const select = document.getElementById('userSelect');
1450
+ userNames.forEach((name, i) => {
1451
+ const opt = document.createElement('option');
1452
+ opt.value = i;
1453
+ const summary = summaries[i];
1454
+ opt.textContent = name + ' (' + Math.round(summary.overallScore * 100) + '%)';
1455
+ select.appendChild(opt);
1456
+ });
1457
+
1458
+ function changeUser() {
1459
+ currentUser = parseInt(select.value);
1460
+ render();
1461
+ }
1462
+
1463
+ function scoreColor(score) {
1464
+ if (score <= 0) return '#e94560';
1465
+ if (score >= 1) return '#27ae60';
1466
+ if (score < 0.5) {
1467
+ const t = score / 0.5;
1468
+ return d3.interpolateRgb('#e94560', '#f5a623')(t);
1469
+ }
1470
+ const t = (score - 0.5) / 0.5;
1471
+ return d3.interpolateRgb('#f5a623', '#27ae60')(t);
1472
+ }
1473
+
1474
+ function getUserScore(node) {
1475
+ if (!node.userScores || node.userScores.length === 0) return node.score;
1476
+ const s = node.userScores[currentUser];
1477
+ return s ? s.score : 0;
1478
+ }
1479
+
1480
+ function findNode(node, path) {
1481
+ if (node.path === path) return node;
1482
+ if (node.children) {
1483
+ for (const child of node.children) {
1484
+ const found = findNode(child, path);
1485
+ if (found) return found;
1486
+ }
1487
+ }
1488
+ return null;
1489
+ }
1490
+
1491
+ function buildHierarchy(node) {
1492
+ if (node.type === 'file') {
1493
+ return { name: node.path.split('/').pop(), data: node, value: Math.max(1, node.lines) };
1494
+ }
1495
+ return {
1496
+ name: node.path.split('/').pop() || node.path,
1497
+ data: node,
1498
+ children: (node.children || []).map(c => buildHierarchy(c)),
1499
+ };
1500
+ }
1501
+
1502
+ function render() {
1503
+ const container = document.getElementById('treemap');
1504
+ container.innerHTML = '';
1505
+
1506
+ const headerH = document.getElementById('header').offsetHeight;
1507
+ const breadcrumbH = document.getElementById('breadcrumb').offsetHeight;
1508
+ const width = window.innerWidth;
1509
+ const height = window.innerHeight - headerH - breadcrumbH;
1510
+
1511
+ const targetNode = currentPath ? findNode(rawData, currentPath) : rawData;
1512
+ if (!targetNode || !targetNode.children || targetNode.children.length === 0) return;
1513
+
1514
+ const hierarchyData = {
1515
+ name: targetNode.path || 'root',
1516
+ children: targetNode.children.map(c => buildHierarchy(c)),
1517
+ };
1518
+
1519
+ const root = d3.hierarchy(hierarchyData)
1520
+ .sum(d => d.value || 0)
1521
+ .sort((a, b) => (b.value || 0) - (a.value || 0));
1522
+
1523
+ d3.treemap()
1524
+ .size([width, height])
1525
+ .padding(2)
1526
+ .paddingTop(20)
1527
+ .round(true)(root);
1528
+
1529
+ const svg = d3.select('#treemap')
1530
+ .append('svg')
1531
+ .attr('width', width)
1532
+ .attr('height', height);
1533
+
1534
+ const tooltip = document.getElementById('tooltip');
1535
+ const nodes = root.descendants().filter(d => d.depth > 0);
1536
+
1537
+ const groups = svg.selectAll('g')
1538
+ .data(nodes)
1539
+ .join('g')
1540
+ .attr('transform', d => \`translate(\${d.x0},\${d.y0})\`);
1541
+
1542
+ groups.append('rect')
1543
+ .attr('width', d => Math.max(0, d.x1 - d.x0))
1544
+ .attr('height', d => Math.max(0, d.y1 - d.y0))
1545
+ .attr('fill', d => {
1546
+ if (!d.data.data) return '#333';
1547
+ return scoreColor(getUserScore(d.data.data));
1548
+ })
1549
+ .attr('opacity', d => d.children ? 0.35 : 0.88)
1550
+ .attr('stroke', '#1a1a2e')
1551
+ .attr('stroke-width', d => d.children ? 1 : 0.5)
1552
+ .attr('rx', 2)
1553
+ .style('cursor', d => (d.data.data && d.data.data.type === 'folder') ? 'pointer' : 'default')
1554
+ .on('click', (event, d) => {
1555
+ if (d.data.data && d.data.data.type === 'folder') {
1556
+ event.stopPropagation();
1557
+ zoomTo(d.data.data.path);
1558
+ }
1559
+ })
1560
+ .on('mouseover', function(event, d) {
1561
+ if (!d.data.data) return;
1562
+ d3.select(this).attr('opacity', d.children ? 0.5 : 1).attr('stroke', '#fff');
1563
+ showTooltip(d.data.data, event);
1564
+ })
1565
+ .on('mousemove', (event) => {
1566
+ tooltip.style.left = (event.pageX + 14) + 'px';
1567
+ tooltip.style.top = (event.pageY - 14) + 'px';
1568
+ })
1569
+ .on('mouseout', function(event, d) {
1570
+ d3.select(this).attr('opacity', d.children ? 0.35 : 0.88).attr('stroke', '#1a1a2e');
1571
+ tooltip.style.display = 'none';
1572
+ });
1573
+
1574
+ groups.append('text')
1575
+ .attr('x', 4)
1576
+ .attr('y', 14)
1577
+ .attr('fill', '#fff')
1578
+ .attr('font-size', d => d.children ? '11px' : '10px')
1579
+ .attr('font-weight', d => d.children ? 'bold' : 'normal')
1580
+ .style('pointer-events', 'none')
1581
+ .text(d => {
1582
+ const w = d.x1 - d.x0;
1583
+ const h = d.y1 - d.y0;
1584
+ const name = d.data.name || '';
1585
+ if (w < 36 || h < 18) return '';
1586
+ const maxChars = Math.floor((w - 8) / 6.5);
1587
+ if (name.length > maxChars) return name.slice(0, maxChars - 1) + '\\u2026';
1588
+ return name;
1589
+ });
1590
+ }
1591
+
1592
+ function showTooltip(data, event) {
1593
+ const tooltip = document.getElementById('tooltip');
1594
+ let html = '<strong>' + (data.path || 'root') + '</strong>';
1595
+
1596
+ if (data.userScores && data.userScores.length > 0) {
1597
+ html += '<table style="margin-top:6px;width:100%">';
1598
+ data.userScores.forEach((s, i) => {
1599
+ const isCurrent = (i === currentUser);
1600
+ const style = isCurrent ? 'font-weight:bold;color:#5eadf7' : '';
1601
+ html += '<tr style="' + style + '"><td>' + userNames[i] + '</td><td style="text-align:right">' + Math.round(s.score * 100) + '%</td></tr>';
1602
+ });
1603
+ html += '</table>';
1604
+ }
1605
+
1606
+ if (data.type === 'folder') {
1607
+ html += '<br>Files: ' + data.fileCount;
1608
+ html += '<br><em style="color:#5eadf7">Click to drill down \\u25B6</em>';
1609
+ } else {
1610
+ html += '<br>Lines: ' + data.lines.toLocaleString();
1611
+ }
1612
+
1613
+ tooltip.innerHTML = html;
1614
+ tooltip.style.display = 'block';
1615
+ tooltip.style.left = (event.pageX + 14) + 'px';
1616
+ tooltip.style.top = (event.pageY - 14) + 'px';
1617
+ }
1618
+
1619
+ function zoomTo(path) {
1620
+ currentPath = path;
1621
+ const el = document.getElementById('breadcrumb');
1622
+ const parts = path ? path.split('/') : [];
1623
+ let html = '<span onclick="zoomTo(\\'\\')">root</span>';
1624
+ let accumulated = '';
1625
+ for (const part of parts) {
1626
+ accumulated = accumulated ? accumulated + '/' + part : part;
1627
+ const p = accumulated;
1628
+ html += '<span class="sep">/</span><span onclick="zoomTo(\\'' + p + '\\')">' + part + '</span>';
1629
+ }
1630
+ el.innerHTML = html;
1631
+ render();
1632
+ }
1633
+
1634
+ window.addEventListener('resize', render);
1635
+ render();
1636
+ </script>
1637
+ </body>
1638
+ </html>`;
1639
+ }
1640
+ async function generateAndOpenMultiUserHTML(result, repoPath) {
1641
+ const html = generateMultiUserHTML(result);
1642
+ const outputPath = join3(repoPath, "gitfamiliar-multiuser.html");
1643
+ writeFileSync3(outputPath, html, "utf-8");
1644
+ console.log(`Multi-user report generated: ${outputPath}`);
1645
+ await openBrowser(outputPath);
1646
+ }
1647
+
1648
+ // src/git/change-frequency.ts
1649
+ var COMMIT_SEP2 = "GITFAMILIAR_FREQ_SEP";
1650
+ async function bulkGetChangeFrequency(gitClient, days, trackedFiles) {
1651
+ const sinceDate = `${days} days ago`;
1652
+ const output = await gitClient.getLog([
1653
+ "--all",
1654
+ `--since=${sinceDate}`,
1655
+ "--name-only",
1656
+ `--format=${COMMIT_SEP2}%aI`
1657
+ ]);
1658
+ const result = /* @__PURE__ */ new Map();
1659
+ let currentDate = null;
1660
+ for (const line of output.split("\n")) {
1661
+ if (line.startsWith(COMMIT_SEP2)) {
1662
+ const dateStr = line.slice(COMMIT_SEP2.length).trim();
1663
+ currentDate = dateStr ? new Date(dateStr) : null;
1664
+ continue;
1665
+ }
1666
+ const filePath = line.trim();
1667
+ if (!filePath || !trackedFiles.has(filePath)) continue;
1668
+ let entry = result.get(filePath);
1669
+ if (!entry) {
1670
+ entry = { commitCount: 0, lastChanged: null };
1671
+ result.set(filePath, entry);
1672
+ }
1673
+ entry.commitCount++;
1674
+ if (currentDate && (!entry.lastChanged || currentDate > entry.lastChanged)) {
1675
+ entry.lastChanged = currentDate;
1676
+ }
1677
+ }
1678
+ return result;
1679
+ }
1680
+
1681
+ // src/core/hotspot.ts
1682
+ var DEFAULT_WINDOW = 90;
1683
+ async function computeHotspots(options) {
1684
+ const gitClient = new GitClient(options.repoPath);
1685
+ if (!await gitClient.isRepo()) {
1686
+ throw new Error(`"${options.repoPath}" is not a git repository.`);
1687
+ }
1688
+ const repoName = await gitClient.getRepoName();
1689
+ const repoRoot = await gitClient.getRepoRoot();
1690
+ const filter = createFilter(repoRoot);
1691
+ const tree = await buildFileTree(gitClient, filter);
1692
+ const timeWindow = options.window || DEFAULT_WINDOW;
1693
+ const isTeamMode = options.hotspot === "team";
1694
+ const trackedFiles = /* @__PURE__ */ new Set();
1695
+ walkFiles(tree, (f) => trackedFiles.add(f.path));
1696
+ const changeFreqMap = await bulkGetChangeFrequency(gitClient, timeWindow, trackedFiles);
1697
+ let familiarityMap;
1698
+ let userName;
1699
+ if (isTeamMode) {
1700
+ familiarityMap = await computeTeamAvgFamiliarity(gitClient, trackedFiles, options);
1701
+ } else {
1702
+ const userFlag = Array.isArray(options.user) ? options.user[0] : options.user;
1703
+ const result = await computeFamiliarity({ ...options, team: false, teamCoverage: false });
1704
+ userName = result.userName;
1705
+ familiarityMap = /* @__PURE__ */ new Map();
1706
+ walkFiles(result.tree, (f) => {
1707
+ familiarityMap.set(f.path, f.score);
1708
+ });
1709
+ }
1710
+ let maxFreq = 0;
1711
+ for (const entry of changeFreqMap.values()) {
1712
+ if (entry.commitCount > maxFreq) maxFreq = entry.commitCount;
1713
+ }
1714
+ const hotspotFiles = [];
1715
+ for (const filePath of trackedFiles) {
1716
+ const freq = changeFreqMap.get(filePath);
1717
+ const changeFrequency = freq?.commitCount || 0;
1718
+ const lastChanged = freq?.lastChanged || null;
1719
+ const familiarity = familiarityMap.get(filePath) || 0;
1720
+ const normalizedFreq = maxFreq > 0 ? changeFrequency / maxFreq : 0;
1721
+ const risk = normalizedFreq * (1 - familiarity);
1722
+ let lines = 0;
1723
+ walkFiles(tree, (f) => {
1724
+ if (f.path === filePath) lines = f.lines;
1725
+ });
1726
+ hotspotFiles.push({
1727
+ path: filePath,
1728
+ lines,
1729
+ familiarity,
1730
+ changeFrequency,
1731
+ lastChanged,
1732
+ risk,
1733
+ riskLevel: classifyHotspotRisk(risk)
1734
+ });
1735
+ }
1736
+ hotspotFiles.sort((a, b) => b.risk - a.risk);
1737
+ const summary = { critical: 0, high: 0, medium: 0, low: 0 };
1738
+ for (const f of hotspotFiles) {
1739
+ summary[f.riskLevel]++;
1740
+ }
1741
+ return {
1742
+ files: hotspotFiles,
1743
+ repoName,
1744
+ userName,
1745
+ hotspotMode: isTeamMode ? "team" : "personal",
1746
+ timeWindow,
1747
+ summary
1748
+ };
1749
+ }
1750
+ function classifyHotspotRisk(risk) {
1751
+ if (risk >= 0.6) return "critical";
1752
+ if (risk >= 0.4) return "high";
1753
+ if (risk >= 0.2) return "medium";
1754
+ return "low";
1755
+ }
1756
+ async function computeTeamAvgFamiliarity(gitClient, trackedFiles, options) {
1757
+ const contributors = await getAllContributors(gitClient, 1);
1758
+ const totalContributors = Math.max(1, contributors.length);
1759
+ const fileContributors = await bulkGetFileContributors(gitClient, trackedFiles);
1760
+ const result = /* @__PURE__ */ new Map();
1761
+ for (const filePath of trackedFiles) {
1762
+ const contribs = fileContributors.get(filePath);
1763
+ const count = contribs ? contribs.size : 0;
1764
+ result.set(filePath, Math.min(1, count / Math.max(1, totalContributors * 0.3)));
1765
+ }
1766
+ return result;
1767
+ }
1768
+
1769
+ // src/cli/output/hotspot-terminal.ts
1770
+ import chalk4 from "chalk";
1771
+ function riskBadge2(level) {
1772
+ switch (level) {
1773
+ case "critical":
1774
+ return chalk4.bgRed.white.bold(" CRIT ");
1775
+ case "high":
1776
+ return chalk4.bgRedBright.white(" HIGH ");
1777
+ case "medium":
1778
+ return chalk4.bgYellow.black(" MED ");
1779
+ case "low":
1780
+ return chalk4.bgGreen.black(" LOW ");
1781
+ }
1782
+ }
1783
+ function riskColor2(level) {
1784
+ switch (level) {
1785
+ case "critical":
1786
+ return chalk4.red;
1787
+ case "high":
1788
+ return chalk4.redBright;
1789
+ case "medium":
1790
+ return chalk4.yellow;
1791
+ case "low":
1792
+ return chalk4.green;
1793
+ }
1794
+ }
1795
+ function renderHotspotTerminal(result) {
1796
+ const { files, repoName, hotspotMode, timeWindow, summary, userName } = result;
1797
+ console.log("");
1798
+ const modeLabel = hotspotMode === "team" ? "Team Hotspots" : "Personal Hotspots";
1799
+ const userLabel = userName ? ` (${userName})` : "";
1800
+ console.log(
1801
+ chalk4.bold(`GitFamiliar \u2014 ${modeLabel}${userLabel} \u2014 ${repoName}`)
1802
+ );
1803
+ console.log(chalk4.gray(` Time window: last ${timeWindow} days`));
1804
+ console.log("");
1805
+ const activeFiles = files.filter((f) => f.changeFrequency > 0);
1806
+ if (activeFiles.length === 0) {
1807
+ console.log(chalk4.gray(" No files changed in the time window."));
1808
+ console.log("");
1809
+ return;
1810
+ }
1811
+ const displayCount = Math.min(30, activeFiles.length);
1812
+ const topFiles = activeFiles.slice(0, displayCount);
1813
+ console.log(
1814
+ chalk4.gray(
1815
+ ` ${"Rank".padEnd(5)} ${"File".padEnd(42)} ${"Familiarity".padStart(11)} ${"Changes".padStart(8)} ${"Risk".padStart(6)} Level`
1816
+ )
1817
+ );
1818
+ console.log(chalk4.gray(" " + "\u2500".repeat(90)));
1819
+ for (let i = 0; i < topFiles.length; i++) {
1820
+ const f = topFiles[i];
1821
+ const rank = String(i + 1).padEnd(5);
1822
+ const path = truncate(f.path, 42).padEnd(42);
1823
+ const fam = `${Math.round(f.familiarity * 100)}%`.padStart(11);
1824
+ const changes = String(f.changeFrequency).padStart(8);
1825
+ const risk = f.risk.toFixed(2).padStart(6);
1826
+ const color = riskColor2(f.riskLevel);
1827
+ const badge = riskBadge2(f.riskLevel);
1828
+ console.log(
1829
+ ` ${color(rank)}${path} ${fam} ${changes} ${color(risk)} ${badge}`
1830
+ );
1831
+ }
1832
+ if (activeFiles.length > displayCount) {
1833
+ console.log(
1834
+ chalk4.gray(` ... and ${activeFiles.length - displayCount} more files`)
1835
+ );
1836
+ }
1837
+ console.log("");
1838
+ console.log(chalk4.bold("Summary:"));
1839
+ if (summary.critical > 0) {
1840
+ console.log(
1841
+ ` ${chalk4.red.bold(`\u{1F534} Critical Risk: ${summary.critical} files`)}`
1842
+ );
1843
+ }
1844
+ if (summary.high > 0) {
1845
+ console.log(
1846
+ ` ${chalk4.redBright(`\u{1F7E0} High Risk: ${summary.high} files`)}`
1847
+ );
1848
+ }
1849
+ if (summary.medium > 0) {
1850
+ console.log(
1851
+ ` ${chalk4.yellow(`\u{1F7E1} Medium Risk: ${summary.medium} files`)}`
1852
+ );
1853
+ }
1854
+ console.log(
1855
+ ` ${chalk4.green(`\u{1F7E2} Low Risk: ${summary.low} files`)}`
1856
+ );
1857
+ console.log("");
1858
+ if (summary.critical > 0 || summary.high > 0) {
1859
+ console.log(
1860
+ chalk4.gray(
1861
+ " Recommendation: Focus code review and knowledge transfer on critical/high risk files."
1862
+ )
1863
+ );
1864
+ console.log("");
1865
+ }
1866
+ }
1867
+ function truncate(s, maxLen) {
1868
+ if (s.length <= maxLen) return s;
1869
+ return s.slice(0, maxLen - 1) + "\u2026";
1870
+ }
1871
+
1872
+ // src/cli/output/hotspot-html.ts
1873
+ import { writeFileSync as writeFileSync4 } from "fs";
1874
+ import { join as join4 } from "path";
1875
+ function generateHotspotHTML(result) {
1876
+ const activeFiles = result.files.filter((f) => f.changeFrequency > 0);
1877
+ const dataJson = JSON.stringify(
1878
+ activeFiles.map((f) => ({
1879
+ path: f.path,
1880
+ lines: f.lines,
1881
+ familiarity: f.familiarity,
1882
+ changeFrequency: f.changeFrequency,
1883
+ risk: f.risk,
1884
+ riskLevel: f.riskLevel
1885
+ }))
1886
+ );
1887
+ const modeLabel = result.hotspotMode === "team" ? "Team Hotspots" : "Personal Hotspots";
1888
+ const userLabel = result.userName ? ` (${result.userName})` : "";
1889
+ return `<!DOCTYPE html>
1890
+ <html lang="en">
1891
+ <head>
1892
+ <meta charset="UTF-8">
1893
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1894
+ <title>GitFamiliar \u2014 ${modeLabel} \u2014 ${result.repoName}</title>
1895
+ <style>
1896
+ * { margin: 0; padding: 0; box-sizing: border-box; }
1897
+ body {
1898
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1899
+ background: #1a1a2e;
1900
+ color: #e0e0e0;
1901
+ overflow: hidden;
1902
+ }
1903
+ #header {
1904
+ padding: 16px 24px;
1905
+ background: #16213e;
1906
+ border-bottom: 1px solid #0f3460;
1907
+ display: flex;
1908
+ align-items: center;
1909
+ justify-content: space-between;
1910
+ }
1911
+ #header h1 { font-size: 18px; color: #e94560; }
1912
+ #header .info { font-size: 14px; color: #a0a0a0; }
1913
+ #main { display: flex; height: calc(100vh - 60px); }
1914
+ #chart { flex: 1; position: relative; }
1915
+ #sidebar {
1916
+ width: 320px;
1917
+ background: #16213e;
1918
+ border-left: 1px solid #0f3460;
1919
+ overflow-y: auto;
1920
+ padding: 16px;
1921
+ }
1922
+ #sidebar h3 { font-size: 14px; margin-bottom: 12px; color: #e94560; }
1923
+ .hotspot-item {
1924
+ padding: 8px 0;
1925
+ border-bottom: 1px solid #0f3460;
1926
+ font-size: 12px;
1927
+ }
1928
+ .hotspot-item .path { color: #e0e0e0; word-break: break-all; }
1929
+ .hotspot-item .meta { color: #888; margin-top: 2px; }
1930
+ .hotspot-item .risk-badge {
1931
+ display: inline-block;
1932
+ padding: 1px 6px;
1933
+ border-radius: 3px;
1934
+ font-size: 10px;
1935
+ font-weight: bold;
1936
+ margin-left: 4px;
1937
+ }
1938
+ .risk-critical { background: #e94560; color: white; }
1939
+ .risk-high { background: #f07040; color: white; }
1940
+ .risk-medium { background: #f5a623; color: black; }
1941
+ .risk-low { background: #27ae60; color: white; }
1942
+ #tooltip {
1943
+ position: absolute;
1944
+ pointer-events: none;
1945
+ background: rgba(22, 33, 62, 0.95);
1946
+ border: 1px solid #0f3460;
1947
+ border-radius: 6px;
1948
+ padding: 10px 14px;
1949
+ font-size: 13px;
1950
+ line-height: 1.6;
1951
+ display: none;
1952
+ z-index: 100;
1953
+ max-width: 350px;
1954
+ }
1955
+ #zone-labels { position: absolute; pointer-events: none; }
1956
+ .zone-label {
1957
+ position: absolute;
1958
+ font-size: 12px;
1959
+ color: rgba(255,255,255,0.15);
1960
+ font-weight: bold;
1961
+ }
1962
+ </style>
1963
+ </head>
1964
+ <body>
1965
+ <div id="header">
1966
+ <h1>GitFamiliar \u2014 ${modeLabel}${userLabel} \u2014 ${result.repoName}</h1>
1967
+ <div class="info">${result.timeWindow}-day window | ${activeFiles.length} active files | Summary: ${result.summary.critical} critical, ${result.summary.high} high</div>
1968
+ </div>
1969
+ <div id="main">
1970
+ <div id="chart">
1971
+ <div id="zone-labels"></div>
1972
+ </div>
1973
+ <div id="sidebar">
1974
+ <h3>Top Hotspots</h3>
1975
+ <div id="hotspot-list"></div>
1976
+ </div>
1977
+ </div>
1978
+ <div id="tooltip"></div>
1979
+
1980
+ <script src="https://d3js.org/d3.v7.min.js"></script>
1981
+ <script>
1982
+ const data = ${dataJson};
1983
+ const margin = { top: 30, right: 30, bottom: 60, left: 70 };
1984
+
1985
+ function riskColor(level) {
1986
+ switch(level) {
1987
+ case 'critical': return '#e94560';
1988
+ case 'high': return '#f07040';
1989
+ case 'medium': return '#f5a623';
1990
+ default: return '#27ae60';
1991
+ }
1992
+ }
1993
+
1994
+ function render() {
1995
+ const container = document.getElementById('chart');
1996
+ const svg = container.querySelector('svg');
1997
+ if (svg) svg.remove();
1998
+
1999
+ const width = container.offsetWidth;
2000
+ const height = container.offsetHeight;
2001
+ const innerW = width - margin.left - margin.right;
2002
+ const innerH = height - margin.top - margin.bottom;
2003
+
2004
+ const maxFreq = d3.max(data, d => d.changeFrequency) || 1;
2005
+
2006
+ const x = d3.scaleLinear().domain([0, 1]).range([0, innerW]);
2007
+ const y = d3.scaleLinear().domain([0, maxFreq * 1.1]).range([innerH, 0]);
2008
+ const r = d3.scaleSqrt()
2009
+ .domain([0, d3.max(data, d => d.lines) || 1])
2010
+ .range([3, 20]);
2011
+
2012
+ const svgEl = d3.select('#chart')
2013
+ .append('svg')
2014
+ .attr('width', width)
2015
+ .attr('height', height);
2016
+
2017
+ const g = svgEl.append('g')
2018
+ .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
2019
+
2020
+ // Danger zone background (top-left quadrant)
2021
+ g.append('rect')
2022
+ .attr('x', 0)
2023
+ .attr('y', 0)
2024
+ .attr('width', x(0.3))
2025
+ .attr('height', y(maxFreq * 0.3))
2026
+ .attr('fill', 'rgba(233, 69, 96, 0.06)');
2027
+
2028
+ // X axis
2029
+ g.append('g')
2030
+ .attr('transform', 'translate(0,' + innerH + ')')
2031
+ .call(d3.axisBottom(x).ticks(5).tickFormat(d => Math.round(d * 100) + '%'))
2032
+ .selectAll('text,line,path').attr('stroke', '#555').attr('fill', '#888');
2033
+
2034
+ svgEl.append('text')
2035
+ .attr('x', margin.left + innerW / 2)
2036
+ .attr('y', height - 10)
2037
+ .attr('text-anchor', 'middle')
2038
+ .attr('fill', '#888')
2039
+ .attr('font-size', '13px')
2040
+ .text('Familiarity \\u2192');
2041
+
2042
+ // Y axis
2043
+ g.append('g')
2044
+ .call(d3.axisLeft(y).ticks(6))
2045
+ .selectAll('text,line,path').attr('stroke', '#555').attr('fill', '#888');
2046
+
2047
+ svgEl.append('text')
2048
+ .attr('transform', 'rotate(-90)')
2049
+ .attr('x', -(margin.top + innerH / 2))
2050
+ .attr('y', 16)
2051
+ .attr('text-anchor', 'middle')
2052
+ .attr('fill', '#888')
2053
+ .attr('font-size', '13px')
2054
+ .text('Change Frequency (commits) \\u2192');
2055
+
2056
+ // Zone labels
2057
+ const labels = document.getElementById('zone-labels');
2058
+ labels.innerHTML = '';
2059
+ const dangerLabel = document.createElement('div');
2060
+ dangerLabel.className = 'zone-label';
2061
+ dangerLabel.style.left = (margin.left + 8) + 'px';
2062
+ dangerLabel.style.top = (margin.top + 8) + 'px';
2063
+ dangerLabel.textContent = 'DANGER ZONE';
2064
+ dangerLabel.style.color = 'rgba(233,69,96,0.25)';
2065
+ dangerLabel.style.fontSize = '16px';
2066
+ labels.appendChild(dangerLabel);
2067
+
2068
+ const safeLabel = document.createElement('div');
2069
+ safeLabel.className = 'zone-label';
2070
+ safeLabel.style.right = (320 + 40) + 'px';
2071
+ safeLabel.style.bottom = (margin.bottom + 16) + 'px';
2072
+ safeLabel.textContent = 'SAFE ZONE';
2073
+ safeLabel.style.color = 'rgba(39,174,96,0.2)';
2074
+ safeLabel.style.fontSize = '16px';
2075
+ labels.appendChild(safeLabel);
2076
+
2077
+ const tooltip = document.getElementById('tooltip');
2078
+
2079
+ // Data points
2080
+ g.selectAll('circle')
2081
+ .data(data)
2082
+ .join('circle')
2083
+ .attr('cx', d => x(d.familiarity))
2084
+ .attr('cy', d => y(d.changeFrequency))
2085
+ .attr('r', d => r(d.lines))
2086
+ .attr('fill', d => riskColor(d.riskLevel))
2087
+ .attr('opacity', 0.7)
2088
+ .attr('stroke', 'none')
2089
+ .style('cursor', 'pointer')
2090
+ .on('mouseover', function(event, d) {
2091
+ d3.select(this).attr('opacity', 1).attr('stroke', '#fff').attr('stroke-width', 2);
2092
+ tooltip.innerHTML =
2093
+ '<strong>' + d.path + '</strong>' +
2094
+ '<br>Familiarity: ' + Math.round(d.familiarity * 100) + '%' +
2095
+ '<br>Changes: ' + d.changeFrequency + ' commits' +
2096
+ '<br>Risk: ' + d.risk.toFixed(2) + ' (' + d.riskLevel + ')' +
2097
+ '<br>Lines: ' + d.lines.toLocaleString();
2098
+ tooltip.style.display = 'block';
2099
+ tooltip.style.left = (event.pageX + 14) + 'px';
2100
+ tooltip.style.top = (event.pageY - 14) + 'px';
2101
+ })
2102
+ .on('mousemove', (event) => {
2103
+ tooltip.style.left = (event.pageX + 14) + 'px';
2104
+ tooltip.style.top = (event.pageY - 14) + 'px';
2105
+ })
2106
+ .on('mouseout', function() {
2107
+ d3.select(this).attr('opacity', 0.7).attr('stroke', 'none');
2108
+ tooltip.style.display = 'none';
2109
+ });
2110
+ }
2111
+
2112
+ // Sidebar
2113
+ function renderSidebar() {
2114
+ const container = document.getElementById('hotspot-list');
2115
+ const top = data.slice(0, 30);
2116
+ if (top.length === 0) {
2117
+ container.innerHTML = '<div style="color:#888">No active files in time window.</div>';
2118
+ return;
2119
+ }
2120
+ let html = '';
2121
+ for (let i = 0; i < top.length; i++) {
2122
+ const f = top[i];
2123
+ const badgeClass = 'risk-' + f.riskLevel;
2124
+ html += '<div class="hotspot-item">' +
2125
+ '<div class="path">' + (i + 1) + '. ' + f.path +
2126
+ ' <span class="risk-badge ' + badgeClass + '">' + f.riskLevel.toUpperCase() + '</span></div>' +
2127
+ '<div class="meta">Fam: ' + Math.round(f.familiarity * 100) + '% | Changes: ' + f.changeFrequency + ' | Risk: ' + f.risk.toFixed(2) + '</div>' +
2128
+ '</div>';
2129
+ }
2130
+ container.innerHTML = html;
2131
+ }
2132
+
2133
+ window.addEventListener('resize', render);
2134
+ renderSidebar();
2135
+ render();
2136
+ </script>
2137
+ </body>
2138
+ </html>`;
2139
+ }
2140
+ async function generateAndOpenHotspotHTML(result, repoPath) {
2141
+ const html = generateHotspotHTML(result);
2142
+ const outputPath = join4(repoPath, "gitfamiliar-hotspot.html");
2143
+ writeFileSync4(outputPath, html, "utf-8");
2144
+ console.log(`Hotspot report generated: ${outputPath}`);
2145
+ await openBrowser(outputPath);
2146
+ }
2147
+
2148
+ // src/cli/index.ts
2149
+ function collect(value, previous) {
2150
+ return previous.concat([value]);
2151
+ }
2152
+ function createProgram() {
2153
+ const program2 = new Command();
2154
+ program2.name("gitfamiliar").description("Visualize your code familiarity from Git history").version("0.1.1").option(
2155
+ "-m, --mode <mode>",
2156
+ "Scoring mode: binary, authorship, review-coverage, weighted",
2157
+ "binary"
2158
+ ).option(
2159
+ "-u, --user <user>",
2160
+ "Git user name or email (repeatable for comparison)",
2161
+ collect,
2162
+ []
2163
+ ).option(
2164
+ "-f, --filter <filter>",
2165
+ "Filter mode: all, written, reviewed",
2166
+ "all"
2167
+ ).option(
2168
+ "-e, --expiration <policy>",
2169
+ "Expiration policy: never, time:180d, change:50%, combined:365d:50%",
2170
+ "never"
2171
+ ).option("--html", "Generate HTML treemap report", false).option(
2172
+ "-w, --weights <weights>",
2173
+ 'Weights for weighted mode: blame,commit,review (e.g., "0.5,0.35,0.15")'
2174
+ ).option("--team", "Compare all contributors", false).option(
2175
+ "--team-coverage",
2176
+ "Show team coverage map (bus factor analysis)",
2177
+ false
2178
+ ).option("--hotspot [mode]", "Hotspot analysis: personal (default) or team").option(
2179
+ "--window <days>",
2180
+ "Time window for hotspot analysis in days (default: 90)"
2181
+ ).action(async (rawOptions) => {
2182
+ try {
2183
+ const repoPath = process.cwd();
2184
+ const options = parseOptions(rawOptions, repoPath);
2185
+ if (options.hotspot) {
2186
+ const result2 = await computeHotspots(options);
2187
+ if (options.html) {
2188
+ await generateAndOpenHotspotHTML(result2, repoPath);
2189
+ } else {
2190
+ renderHotspotTerminal(result2);
2191
+ }
2192
+ return;
2193
+ }
2194
+ if (options.teamCoverage) {
2195
+ const result2 = await computeTeamCoverage(options);
2196
+ if (options.html) {
2197
+ await generateAndOpenCoverageHTML(result2, repoPath);
2198
+ } else {
2199
+ renderCoverageTerminal(result2);
2200
+ }
2201
+ return;
2202
+ }
2203
+ const isMultiUser = options.team || Array.isArray(options.user) && options.user.length > 1;
2204
+ if (isMultiUser) {
2205
+ const result2 = await computeMultiUser(options);
2206
+ if (options.html) {
2207
+ await generateAndOpenMultiUserHTML(result2, repoPath);
2208
+ } else {
2209
+ renderMultiUserTerminal(result2);
2210
+ }
2211
+ return;
2212
+ }
497
2213
  const result = await computeFamiliarity(options);
498
2214
  if (options.html) {
499
2215
  await generateAndOpenHTML(result, repoPath);