Coverage for /Users/les/Projects/crackerjack/crackerjack/services/pattern_detector.py: 0%

204 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-03 15:39 -0700

1import ast 

2import logging 

3import typing as t 

4from collections.abc import Awaitable, Callable 

5from dataclasses import dataclass 

6from pathlib import Path 

7 

8from ..agents.base import Issue, IssueType, Priority 

9from .pattern_cache import CachedPattern, PatternCache 

10 

11DetectorMethod = Callable[[Path, str, ast.AST], Awaitable[list["AntiPattern"]]] 

12 

13 

14class AntiPatternConfig(t.TypedDict): 

15 detector: DetectorMethod 

16 description: str 

17 prevention: str 

18 

19 

20@dataclass 

21class AntiPattern: 

22 pattern_type: str 

23 severity: Priority 

24 file_path: str 

25 line_number: int | None 

26 description: str 

27 suggestion: str 

28 prevention_strategy: str 

29 

30 

31class PatternDetector: 

32 def __init__(self, project_path: Path, pattern_cache: PatternCache) -> None: 

33 self.project_path = project_path 

34 self.pattern_cache = pattern_cache 

35 self.logger = logging.getLogger(__name__) 

36 

37 self._anti_patterns: dict[str, AntiPatternConfig] = { 

38 "complexity_hotspot": { 

39 "detector": self._detect_complexity_hotspots, 

40 "description": "Functions approaching complexity limits", 

41 "prevention": "Extract methods, use helper functions", 

42 }, 

43 "code_duplication": { 

44 "detector": self._detect_code_duplication, 

45 "description": "Repeated code patterns across files", 

46 "prevention": "Extract common functionality to utilities", 

47 }, 

48 "performance_issues": { 

49 "detector": self._detect_performance_issues, 

50 "description": "Inefficient code patterns", 

51 "prevention": "Use optimized algorithms and data structures", 

52 }, 

53 "security_risks": { 

54 "detector": self._detect_security_risks, 

55 "description": "Potentially unsafe code patterns", 

56 "prevention": "Apply secure coding practices", 

57 }, 

58 "import_complexity": { 

59 "detector": self._detect_import_complexity, 

60 "description": "Complex or problematic import patterns", 

61 "prevention": "Organize imports, avoid circular dependencies", 

62 }, 

63 } 

64 

65 async def analyze_codebase(self) -> list[AntiPattern]: 

66 self.logger.info("Starting proactive anti-pattern analysis") 

67 

68 anti_patterns = [] 

69 python_files = list(self.project_path.glob("**/*.py")) 

70 

71 for file_path in python_files: 

72 if self._should_skip_file(file_path): 

73 continue 

74 

75 file_anti_patterns = await self._analyze_file(file_path) 

76 anti_patterns.extend(file_anti_patterns) 

77 

78 self.logger.info(f"Detected {len(anti_patterns)} potential anti-patterns") 

79 return anti_patterns 

80 

81 async def _analyze_file(self, file_path: Path) -> list[AntiPattern]: 

82 anti_patterns = [] 

83 

84 try: 

85 content = file_path.read_text(encoding="utf-8") 

86 

87 try: 

88 tree = ast.parse(content, filename=str(file_path)) 

89 except SyntaxError as e: 

90 self.logger.warning(f"Syntax error in {file_path}: {e}") 

91 return [] 

92 

93 for pattern_name, pattern_info in self._anti_patterns.items(): 

94 detector_method = pattern_info["detector"] 

95 try: 

96 detected = await detector_method(file_path, content, tree) 

97 anti_patterns.extend(detected) 

98 except Exception as e: 

99 self.logger.warning( 

100 f"Error in {pattern_name} detector for {file_path}: {e}" 

101 ) 

102 

103 except Exception as e: 

104 self.logger.warning(f"Failed to analyze {file_path}: {e}") 

105 

106 return anti_patterns 

107 

108 async def _detect_complexity_hotspots( 

109 self, file_path: Path, content: str, tree: ast.AST 

110 ) -> list[AntiPattern]: 

111 anti_patterns = [] 

112 

113 class ComplexityVisitor(ast.NodeVisitor): 

114 def __init__(self) -> None: 

115 self.functions: list[tuple[str, int, int]] = [] 

116 

117 def visit_FunctionDef(self, node: ast.FunctionDef) -> None: 

118 complexity = 1 

119 

120 for child in ast.walk(node): 

121 if isinstance(child, ast.If | ast.For | ast.While | ast.With): 

122 complexity += 1 

123 elif isinstance(child, ast.Try): 

124 complexity += 1 

125 elif isinstance(child, ast.ExceptHandler): 

126 complexity += 1 

127 elif isinstance(child, ast.BoolOp): 

128 complexity += len(child.values) - 1 

129 

130 self.functions.append((node.name, node.lineno, complexity)) 

131 self.generic_visit(node) 

132 

133 visitor = ComplexityVisitor() 

134 visitor.visit(tree) 

135 

136 for func_name, line_no, complexity in visitor.functions: 

137 if complexity >= 10: 

138 anti_patterns.append( 

139 AntiPattern( 

140 pattern_type="complexity_hotspot", 

141 severity=Priority.HIGH if complexity >= 12 else Priority.MEDIUM, 

142 file_path=str(file_path), 

143 line_number=line_no, 

144 description=f"Function '{func_name}' has complexity {complexity} (approaching limit of 13)", 

145 suggestion=f"Break down '{func_name}' into smaller helper methods", 

146 prevention_strategy="extract_method", 

147 ) 

148 ) 

149 

150 return anti_patterns 

151 

152 async def _detect_code_duplication( 

153 self, file_path: Path, content: str, tree: ast.AST 

154 ) -> list[AntiPattern]: 

155 anti_patterns = [] 

156 

157 lines = content.split("\n") 

158 line_groups = {} 

159 

160 for i, line in enumerate(lines, 1): 

161 stripped = line.strip() 

162 if len(stripped) > 20 and not stripped.startswith("#"): 

163 if stripped in line_groups: 

164 line_groups[stripped].append(i) 

165 else: 

166 line_groups[stripped] = [i] 

167 

168 for line_content, line_numbers in line_groups.items(): 

169 if len(line_numbers) >= 3: 

170 anti_patterns.append( 

171 AntiPattern( 

172 pattern_type="code_duplication", 

173 severity=Priority.MEDIUM, 

174 file_path=str(file_path), 

175 line_number=line_numbers[0], 

176 description=f"Line appears {len(line_numbers)} times: '{line_content[:50]}...'", 

177 suggestion="Extract common functionality to a utility function", 

178 prevention_strategy="extract_utility", 

179 ) 

180 ) 

181 

182 return anti_patterns 

183 

184 async def _detect_performance_issues( 

185 self, file_path: Path, content: str, tree: ast.AST 

186 ) -> list[AntiPattern]: 

187 anti_patterns = [] 

188 

189 class PerformanceVisitor(ast.NodeVisitor): 

190 def __init__(self) -> None: 

191 self.issues: list[tuple[int, str, str]] = [] 

192 

193 def visit_For(self, node: ast.For) -> None: 

194 for child in ast.walk(node.body[0] if node.body else node): 

195 if isinstance(child, ast.For | ast.While) and child != node: 

196 self.issues.append( 

197 ( 

198 node.lineno, 

199 "Nested loop detected-potential O(n²) complexity", 

200 "Consider using dictionary lookups or set operations", 

201 ) 

202 ) 

203 break 

204 

205 for stmt in node.body: 

206 if ( 

207 isinstance(stmt, ast.AugAssign) 

208 and isinstance(stmt.op, ast.Add) 

209 and isinstance(stmt.target, ast.Name) 

210 ): 

211 self.issues.append( 

212 ( 

213 stmt.lineno, 

214 "List concatenation in loop-inefficient", 

215 "Use list.append() and join at the end", 

216 ) 

217 ) 

218 

219 self.generic_visit(node) 

220 

221 visitor = PerformanceVisitor() 

222 visitor.visit(tree) 

223 

224 for line_no, description, suggestion in visitor.issues: 

225 anti_patterns.append( 

226 AntiPattern( 

227 pattern_type="performance_issues", 

228 severity=Priority.MEDIUM, 

229 file_path=str(file_path), 

230 line_number=line_no, 

231 description=description, 

232 suggestion=suggestion, 

233 prevention_strategy="optimize_algorithm", 

234 ) 

235 ) 

236 

237 return anti_patterns 

238 

239 async def _detect_security_risks( 

240 self, file_path: Path, content: str, tree: ast.AST 

241 ) -> list[AntiPattern]: 

242 anti_patterns = [] 

243 

244 hardcoded_path_patterns = self._check_hardcoded_paths(file_path, content) 

245 anti_patterns.extend(hardcoded_path_patterns) 

246 

247 subprocess_patterns = self._check_subprocess_security(file_path, tree) 

248 anti_patterns.extend(subprocess_patterns) 

249 

250 return anti_patterns 

251 

252 def _check_hardcoded_paths( 

253 self, file_path: Path, content: str 

254 ) -> list[AntiPattern]: 

255 anti_patterns = [] 

256 

257 if "/tmp/" in content or "C:\\" in content: # nosec B108 

258 lines = content.split("\n") 

259 for i, line in enumerate(lines, 1): 

260 if "/tmp/" in line or "C:\\" in line: # nosec B108 

261 anti_patterns.append( 

262 AntiPattern( 

263 pattern_type="security_risks", 

264 severity=Priority.HIGH, 

265 file_path=str(file_path), 

266 line_number=i, 

267 description="Hardcoded path detected-potential security risk", 

268 suggestion="Use tempfile module for temporary files", 

269 prevention_strategy="use_secure_temp_files", 

270 ) 

271 ) 

272 break 

273 

274 return anti_patterns 

275 

276 def _check_subprocess_security( 

277 self, file_path: Path, tree: ast.AST 

278 ) -> list[AntiPattern]: 

279 anti_patterns = [] 

280 

281 class SecurityVisitor(ast.NodeVisitor): 

282 def __init__(self) -> None: 

283 self.issues: list[tuple[int, str, str]] = [] 

284 

285 def visit_Call(self, node: ast.Call) -> None: 

286 if ( 

287 isinstance(node.func, ast.Attribute) 

288 and isinstance(node.func.value, ast.Name) 

289 and node.func.value.id == "subprocess" 

290 ): 

291 for keyword in node.keywords: 

292 if ( 

293 keyword.arg == "shell" 

294 and isinstance(keyword.value, ast.Constant) 

295 and keyword.value.value is True 

296 ): 

297 self.issues.append( 

298 ( 

299 node.lineno, 

300 "subprocess with shell=True-security risk", 

301 "Avoid shell=True or validate inputs carefully", 

302 ) 

303 ) 

304 

305 self.generic_visit(node) 

306 

307 visitor = SecurityVisitor() 

308 visitor.visit(tree) 

309 

310 for line_no, description, suggestion in visitor.issues: 

311 anti_patterns.append( 

312 AntiPattern( 

313 pattern_type="security_risks", 

314 severity=Priority.HIGH, 

315 file_path=str(file_path), 

316 line_number=line_no, 

317 description=description, 

318 suggestion=suggestion, 

319 prevention_strategy="secure_subprocess", 

320 ) 

321 ) 

322 

323 return anti_patterns 

324 

325 async def _detect_import_complexity( 

326 self, file_path: Path, content: str, tree: ast.AST 

327 ) -> list[AntiPattern]: 

328 anti_patterns = [] 

329 

330 class ImportVisitor(ast.NodeVisitor): 

331 def __init__(self) -> None: 

332 self.imports: list[tuple[int, str]] = [] 

333 self.import_count = 0 

334 

335 def visit_Import(self, node: ast.Import) -> None: 

336 self.import_count += len(node.names) 

337 for alias in node.names: 

338 if alias.name.count(".") > 2: 

339 self.imports.append((node.lineno, f"Deep import: {alias.name}")) 

340 self.generic_visit(node) 

341 

342 def visit_ImportFrom(self, node: ast.ImportFrom) -> None: 

343 if node.module: 

344 self.import_count += len(node.names) if node.names else 1 

345 if node.names and len(node.names) > 10: 

346 self.imports.append( 

347 (node.lineno, f"Many imports from {node.module}") 

348 ) 

349 self.generic_visit(node) 

350 

351 visitor = ImportVisitor() 

352 visitor.visit(tree) 

353 

354 if visitor.import_count > 50: 

355 anti_patterns.append( 

356 AntiPattern( 

357 pattern_type="import_complexity", 

358 severity=Priority.MEDIUM, 

359 file_path=str(file_path), 

360 line_number=1, 

361 description=f"File has {visitor.import_count} imports-may indicate tight coupling", 

362 suggestion="Consider breaking file into smaller modules", 

363 prevention_strategy="modular_design", 

364 ) 

365 ) 

366 

367 for line_no, description in visitor.imports: 

368 anti_patterns.append( 

369 AntiPattern( 

370 pattern_type="import_complexity", 

371 severity=Priority.LOW, 

372 file_path=str(file_path), 

373 line_number=line_no, 

374 description=description, 

375 suggestion="Simplify import structure", 

376 prevention_strategy="clean_imports", 

377 ) 

378 ) 

379 

380 return anti_patterns 

381 

382 def _should_skip_file(self, file_path: Path) -> bool: 

383 skip_patterns = [ 

384 "__pycache__", 

385 ".git", 

386 ".venv", 

387 "venv", 

388 ".tox", 

389 "build", 

390 "dist", 

391 ".pytest_cache", 

392 "node_modules", 

393 ] 

394 

395 path_str = str(file_path) 

396 return any(pattern in path_str for pattern in skip_patterns) 

397 

398 async def suggest_proactive_refactoring( 

399 self, anti_patterns: list[AntiPattern] 

400 ) -> list[Issue]: 

401 issues = [] 

402 

403 for anti_pattern in anti_patterns: 

404 issue_type_map = { 

405 "complexity_hotspot": IssueType.COMPLEXITY, 

406 "code_duplication": IssueType.DRY_VIOLATION, 

407 "performance_issues": IssueType.PERFORMANCE, 

408 "security_risks": IssueType.SECURITY, 

409 "import_complexity": IssueType.IMPORT_ERROR, 

410 } 

411 

412 issue_type = issue_type_map.get( 

413 anti_pattern.pattern_type, IssueType.FORMATTING 

414 ) 

415 

416 issue = Issue( 

417 id=f"proactive_{anti_pattern.pattern_type}_{hash(anti_pattern.file_path + str(anti_pattern.line_number))}", 

418 type=issue_type, 

419 severity=anti_pattern.severity, 

420 message=f"Proactive: {anti_pattern.description}", 

421 file_path=anti_pattern.file_path, 

422 line_number=anti_pattern.line_number, 

423 details=[ 

424 anti_pattern.suggestion, 

425 f"Prevention strategy: {anti_pattern.prevention_strategy}", 

426 ], 

427 stage="proactive_analysis", 

428 ) 

429 

430 issues.append(issue) 

431 

432 return issues 

433 

434 async def get_cached_solutions( 

435 self, anti_patterns: list[AntiPattern] 

436 ) -> dict[str, CachedPattern]: 

437 solutions = {} 

438 

439 for anti_pattern in anti_patterns: 

440 solution_key = self._generate_solution_key(anti_pattern) 

441 cached_pattern = self._find_cached_pattern_for_anti_pattern(anti_pattern) 

442 

443 if cached_pattern: 

444 solutions[solution_key] = cached_pattern 

445 

446 return solutions 

447 

448 def _generate_solution_key(self, anti_pattern: AntiPattern) -> str: 

449 return f"{anti_pattern.pattern_type}_{anti_pattern.file_path}_{anti_pattern.line_number}" 

450 

451 def _find_cached_pattern_for_anti_pattern( 

452 self, anti_pattern: AntiPattern 

453 ) -> CachedPattern | None: 

454 issue_type = self._map_anti_pattern_to_issue_type(anti_pattern.pattern_type) 

455 if not issue_type: 

456 return None 

457 

458 temp_issue = self._create_temp_issue_for_lookup(anti_pattern, issue_type) 

459 return self.pattern_cache.get_best_pattern_for_issue(temp_issue) 

460 

461 def _map_anti_pattern_to_issue_type(self, pattern_type: str) -> IssueType | None: 

462 return { 

463 "complexity_hotspot": IssueType.COMPLEXITY, 

464 "code_duplication": IssueType.DRY_VIOLATION, 

465 "performance_issues": IssueType.PERFORMANCE, 

466 "security_risks": IssueType.SECURITY, 

467 }.get(pattern_type) 

468 

469 def _create_temp_issue_for_lookup( 

470 self, anti_pattern: AntiPattern, issue_type: IssueType 

471 ) -> Issue: 

472 return Issue( 

473 id="temp", 

474 type=issue_type, 

475 severity=anti_pattern.severity, 

476 message=anti_pattern.description, 

477 file_path=anti_pattern.file_path, 

478 )