Coverage for little_loops / issue_history / coupling.py: 100%

71 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-04 01:17 -0600

1"""Issue history file coupling analysis.""" 

2 

3from __future__ import annotations 

4 

5from pathlib import Path 

6 

7from little_loops.issue_history.models import ( 

8 CompletedIssue, 

9 CouplingAnalysis, 

10 CouplingPair, 

11) 

12from little_loops.issue_history.parsing import _extract_paths_from_issue 

13 

14 

15def analyze_coupling( 

16 issues: list[CompletedIssue], 

17 contents: dict[Path, str] | None = None, 

18) -> CouplingAnalysis: 

19 """Identify files that frequently change together across issues. 

20 

21 Uses Jaccard similarity to calculate coupling strength between file pairs. 

22 Files with coupling strength >= 0.3 and at least 2 co-occurrences are included. 

23 

24 Args: 

25 issues: List of completed issues 

26 contents: Pre-loaded issue file contents (path -> content) 

27 

28 Returns: 

29 CouplingAnalysis with coupled pairs, clusters, and hotspots 

30 """ 

31 # Build file -> set of issue IDs mapping 

32 file_to_issues: dict[str, set[str]] = {} 

33 

34 for issue in issues: 

35 if contents is not None and issue.path in contents: 

36 content = contents[issue.path] 

37 else: 

38 try: 

39 content = issue.path.read_text(encoding="utf-8") 

40 except Exception: 

41 continue 

42 

43 paths = _extract_paths_from_issue(content) 

44 for path in paths: 

45 if path not in file_to_issues: 

46 file_to_issues[path] = set() 

47 file_to_issues[path].add(issue.issue_id) 

48 

49 # Calculate pairwise coupling 

50 files = list(file_to_issues.keys()) 

51 pairs: list[CouplingPair] = [] 

52 

53 for i, file_a in enumerate(files): 

54 for file_b in files[i + 1 :]: 

55 a_issues = file_to_issues[file_a] 

56 b_issues = file_to_issues[file_b] 

57 co_occur = a_issues & b_issues 

58 union = a_issues | b_issues 

59 

60 if len(co_occur) < 2: # Require at least 2 co-occurrences 

61 continue 

62 

63 # Jaccard similarity 

64 strength = len(co_occur) / len(union) if union else 0.0 

65 

66 if strength >= 0.3: # Only include significant coupling 

67 pairs.append( 

68 CouplingPair( 

69 file_a=file_a, 

70 file_b=file_b, 

71 co_occurrence_count=len(co_occur), 

72 coupling_strength=strength, 

73 issue_ids=sorted(co_occur), 

74 ) 

75 ) 

76 

77 # Sort by coupling strength descending 

78 pairs.sort(key=lambda p: (-p.coupling_strength, -p.co_occurrence_count)) 

79 

80 # Build clusters using simple connected components 

81 clusters = _build_coupling_clusters(pairs) 

82 

83 # Identify hotspots (files coupled with 3+ others) 

84 file_coupling_count: dict[str, int] = {} 

85 for pair in pairs: 

86 file_coupling_count[pair.file_a] = file_coupling_count.get(pair.file_a, 0) + 1 

87 file_coupling_count[pair.file_b] = file_coupling_count.get(pair.file_b, 0) + 1 

88 

89 hotspots = [f for f, count in file_coupling_count.items() if count >= 3] 

90 hotspots.sort(key=lambda f: -file_coupling_count[f]) 

91 

92 return CouplingAnalysis( 

93 pairs=pairs[:20], # Top 20 pairs 

94 clusters=clusters[:10], # Top 10 clusters 

95 hotspots=hotspots[:10], # Top 10 hotspots 

96 ) 

97 

98 

99def _build_coupling_clusters(pairs: list[CouplingPair]) -> list[list[str]]: 

100 """Build clusters of coupled files using connected components. 

101 

102 Args: 

103 pairs: List of coupling pairs 

104 

105 Returns: 

106 List of file clusters (each cluster is a list of file paths) 

107 """ 

108 # Build adjacency for high-coupling pairs (strength >= 0.5) 

109 adjacency: dict[str, set[str]] = {} 

110 for pair in pairs: 

111 if pair.coupling_strength >= 0.5: 

112 if pair.file_a not in adjacency: 

113 adjacency[pair.file_a] = set() 

114 if pair.file_b not in adjacency: 

115 adjacency[pair.file_b] = set() 

116 adjacency[pair.file_a].add(pair.file_b) 

117 adjacency[pair.file_b].add(pair.file_a) 

118 

119 # Find connected components 

120 visited: set[str] = set() 

121 clusters: list[list[str]] = [] 

122 

123 for start in adjacency: 

124 if start in visited: 

125 continue 

126 # BFS to find component 

127 cluster: list[str] = [] 

128 queue = [start] 

129 while queue: 

130 node = queue.pop(0) 

131 if node in visited: 

132 continue 

133 visited.add(node) 

134 cluster.append(node) 

135 for neighbor in adjacency.get(node, set()): 

136 if neighbor not in visited: 

137 queue.append(neighbor) 

138 

139 if len(cluster) >= 2: # Only include clusters with 2+ files 

140 cluster.sort() 

141 clusters.append(cluster) 

142 

143 # Sort clusters by size descending 

144 clusters.sort(key=lambda c: -len(c)) 

145 return clusters