Coverage for /Users/les/Projects/crackerjack/crackerjack/agents/refactoring_agent.py: 0%

299 statements  

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

1import ast 

2import typing as t 

3from pathlib import Path 

4 

5from .base import ( 

6 FixResult, 

7 Issue, 

8 IssueType, 

9 SubAgent, 

10 agent_registry, 

11) 

12 

13 

14class RefactoringAgent(SubAgent): 

15 def get_supported_types(self) -> set[IssueType]: 

16 return {IssueType.COMPLEXITY, IssueType.DEAD_CODE} 

17 

18 async def can_handle(self, issue: Issue) -> float: 

19 if issue.type == IssueType.COMPLEXITY: 

20 return 0.9 

21 if issue.type == IssueType.DEAD_CODE: 

22 return 0.8 

23 return 0.0 

24 

25 async def analyze_and_fix(self, issue: Issue) -> FixResult: 

26 self.log(f"Analyzing {issue.type.value} issue: {issue.message}") 

27 

28 if issue.type == IssueType.COMPLEXITY: 

29 return await self._reduce_complexity(issue) 

30 if issue.type == IssueType.DEAD_CODE: 

31 return await self._remove_dead_code(issue) 

32 

33 return FixResult( 

34 success=False, 

35 confidence=0.0, 

36 remaining_issues=[f"RefactoringAgent cannot handle {issue.type.value}"], 

37 ) 

38 

39 async def _reduce_complexity(self, issue: Issue) -> FixResult: 

40 validation_result = self._validate_complexity_issue(issue) 

41 if validation_result: 

42 return validation_result 

43 

44 if issue.file_path is None: 

45 return FixResult( 

46 success=False, 

47 confidence=0.0, 

48 remaining_issues=["No file path provided for complexity issue"], 

49 ) 

50 

51 file_path = Path(issue.file_path) 

52 

53 if "detect_agent_needs" in issue.message: 

54 return await self._apply_known_complexity_fix(file_path, issue) 

55 

56 try: 

57 return await self._process_complexity_reduction(file_path) 

58 except SyntaxError as e: 

59 return self._create_syntax_error_result(e) 

60 except Exception as e: 

61 return self._create_general_error_result(e) 

62 

63 async def _apply_known_complexity_fix( 

64 self, file_path: Path, issue: Issue 

65 ) -> FixResult: 

66 content = self.context.get_file_content(file_path) 

67 if not content: 

68 return FixResult( 

69 success=False, 

70 confidence=0.0, 

71 remaining_issues=[f"Could not read file: {file_path}"], 

72 ) 

73 

74 refactored_content = self._refactor_detect_agent_needs_pattern(content) 

75 

76 if refactored_content != content: 

77 success = self.context.write_file_content(file_path, refactored_content) 

78 if success: 

79 return FixResult( 

80 success=True, 

81 confidence=0.9, 

82 fixes_applied=[ 

83 "Applied proven complexity reduction pattern for detect_agent_needs" 

84 ], 

85 files_modified=[str(file_path)], 

86 recommendations=["Verify functionality after complexity reduction"], 

87 ) 

88 else: 

89 return FixResult( 

90 success=False, 

91 confidence=0.0, 

92 remaining_issues=[ 

93 f"Failed to write refactored content to {file_path}" 

94 ], 

95 ) 

96 else: 

97 return FixResult( 

98 success=False, 

99 confidence=0.3, 

100 remaining_issues=[ 

101 "Refactoring pattern did not apply to current file content" 

102 ], 

103 recommendations=[ 

104 "File may have been modified since pattern was created" 

105 ], 

106 ) 

107 

108 def _validate_complexity_issue(self, issue: Issue) -> FixResult | None: 

109 if not issue.file_path: 

110 return FixResult( 

111 success=False, 

112 confidence=0.0, 

113 remaining_issues=["No file path specified for complexity issue"], 

114 ) 

115 

116 file_path = Path(issue.file_path) 

117 if not file_path.exists(): 

118 return FixResult( 

119 success=False, 

120 confidence=0.0, 

121 remaining_issues=[f"File not found: {file_path}"], 

122 ) 

123 

124 return None 

125 

126 async def _process_complexity_reduction(self, file_path: Path) -> FixResult: 

127 content = self.context.get_file_content(file_path) 

128 if not content: 

129 return FixResult( 

130 success=False, 

131 confidence=0.0, 

132 remaining_issues=[f"Could not read file: {file_path}"], 

133 ) 

134 

135 tree = ast.parse(content) 

136 complex_functions = self._find_complex_functions(tree, content) 

137 

138 if not complex_functions: 

139 return FixResult( 

140 success=True, 

141 confidence=0.7, 

142 recommendations=["No overly complex functions found"], 

143 ) 

144 

145 return self._apply_and_save_refactoring(file_path, content, complex_functions) 

146 

147 def _apply_and_save_refactoring( 

148 self, 

149 file_path: Path, 

150 content: str, 

151 complex_functions: list[dict[str, t.Any]], 

152 ) -> FixResult: 

153 refactored_content = self._apply_complexity_reduction( 

154 content, 

155 complex_functions, 

156 ) 

157 

158 if refactored_content == content: 

159 return self._create_no_changes_result() 

160 

161 success = self.context.write_file_content(file_path, refactored_content) 

162 if not success: 

163 return FixResult( 

164 success=False, 

165 confidence=0.0, 

166 remaining_issues=[f"Failed to write refactored file: {file_path}"], 

167 ) 

168 

169 return FixResult( 

170 success=True, 

171 confidence=0.8, 

172 fixes_applied=[f"Reduced complexity in {len(complex_functions)} functions"], 

173 files_modified=[str(file_path)], 

174 recommendations=["Verify functionality after complexity reduction"], 

175 ) 

176 

177 def _create_no_changes_result(self) -> FixResult: 

178 return FixResult( 

179 success=False, 

180 confidence=0.5, 

181 remaining_issues=["Could not automatically reduce complexity"], 

182 recommendations=[ 

183 "Manual refactoring required", 

184 "Consider breaking down complex conditionals", 

185 "Extract helper methods for repeated patterns", 

186 ], 

187 ) 

188 

189 def _create_syntax_error_result(self, error: SyntaxError) -> FixResult: 

190 return FixResult( 

191 success=False, 

192 confidence=0.0, 

193 remaining_issues=[f"Syntax error in file: {error}"], 

194 ) 

195 

196 def _create_general_error_result(self, error: Exception) -> FixResult: 

197 return FixResult( 

198 success=False, 

199 confidence=0.0, 

200 remaining_issues=[f"Error processing file: {error}"], 

201 ) 

202 

203 async def _remove_dead_code(self, issue: Issue) -> FixResult: 

204 validation_result = self._validate_dead_code_issue(issue) 

205 if validation_result: 

206 return validation_result 

207 

208 if issue.file_path is None: 

209 return FixResult( 

210 success=False, 

211 confidence=0.0, 

212 remaining_issues=["No file path provided for dead code issue"], 

213 ) 

214 

215 file_path = Path(issue.file_path) 

216 

217 try: 

218 return await self._process_dead_code_removal(file_path) 

219 except SyntaxError as e: 

220 return self._create_syntax_error_result(e) 

221 except Exception as e: 

222 return self._create_dead_code_error_result(e) 

223 

224 def _validate_dead_code_issue(self, issue: Issue) -> FixResult | None: 

225 if not issue.file_path: 

226 return FixResult( 

227 success=False, 

228 confidence=0.0, 

229 remaining_issues=["No file path specified for dead code issue"], 

230 ) 

231 

232 file_path = Path(issue.file_path) 

233 if not file_path.exists(): 

234 return FixResult( 

235 success=False, 

236 confidence=0.0, 

237 remaining_issues=[f"File not found: {file_path}"], 

238 ) 

239 

240 return None 

241 

242 async def _process_dead_code_removal(self, file_path: Path) -> FixResult: 

243 content = self.context.get_file_content(file_path) 

244 if not content: 

245 return FixResult( 

246 success=False, 

247 confidence=0.0, 

248 remaining_issues=[f"Could not read file: {file_path}"], 

249 ) 

250 

251 tree = ast.parse(content) 

252 dead_code_analysis = self._analyze_dead_code(tree, content) 

253 

254 if not dead_code_analysis["removable_items"]: 

255 return FixResult( 

256 success=True, 

257 confidence=0.7, 

258 recommendations=["No obvious dead code found"], 

259 ) 

260 

261 return self._apply_and_save_cleanup(file_path, content, dead_code_analysis) 

262 

263 def _apply_and_save_cleanup( 

264 self, 

265 file_path: Path, 

266 content: str, 

267 analysis: dict[str, t.Any], 

268 ) -> FixResult: 

269 cleaned_content = self._remove_dead_code_items(content, analysis) 

270 

271 if cleaned_content == content: 

272 return self._create_no_cleanup_result() 

273 

274 success = self.context.write_file_content(file_path, cleaned_content) 

275 if not success: 

276 return FixResult( 

277 success=False, 

278 confidence=0.0, 

279 remaining_issues=[f"Failed to write cleaned file: {file_path}"], 

280 ) 

281 

282 removed_count = len(analysis["removable_items"]) 

283 return FixResult( 

284 success=True, 

285 confidence=0.8, 

286 fixes_applied=[f"Removed {removed_count} dead code items"], 

287 files_modified=[str(file_path)], 

288 recommendations=["Verify imports and functionality after cleanup"], 

289 ) 

290 

291 def _create_no_cleanup_result(self) -> FixResult: 

292 return FixResult( 

293 success=False, 

294 confidence=0.5, 

295 remaining_issues=["Could not automatically remove dead code"], 

296 recommendations=[ 

297 "Manual review required", 

298 "Check for unused imports with tools like vulture", 

299 ], 

300 ) 

301 

302 def _create_dead_code_error_result(self, error: Exception) -> FixResult: 

303 return FixResult( 

304 success=False, 

305 confidence=0.0, 

306 remaining_issues=[f"Error processing file: {error}"], 

307 ) 

308 

309 def _find_complex_functions( 

310 self, 

311 tree: ast.AST, 

312 content: str, 

313 ) -> list[dict[str, t.Any]]: 

314 complex_functions: list[dict[str, t.Any]] = [] 

315 

316 class ComplexityAnalyzer(ast.NodeVisitor): 

317 def __init__( 

318 self, 

319 calc_complexity: t.Callable[ 

320 [ast.FunctionDef | ast.AsyncFunctionDef], 

321 int, 

322 ], 

323 ) -> None: 

324 self.calc_complexity = calc_complexity 

325 

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

327 complexity = self.calc_complexity(node) 

328 if complexity > 15: 

329 complex_functions.append( 

330 { 

331 "name": node.name, 

332 "line_start": node.lineno, 

333 "line_end": node.end_lineno or node.lineno, 

334 "complexity": complexity, 

335 "node": node, 

336 }, 

337 ) 

338 self.generic_visit(node) 

339 

340 def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: 

341 complexity = self.calc_complexity(node) 

342 if complexity > 15: 

343 complex_functions.append( 

344 { 

345 "name": node.name, 

346 "line_start": node.lineno, 

347 "line_end": node.end_lineno or node.lineno, 

348 "complexity": complexity, 

349 "node": node, 

350 }, 

351 ) 

352 self.generic_visit(node) 

353 

354 analyzer = ComplexityAnalyzer(self._calculate_cognitive_complexity) 

355 analyzer.visit(tree) 

356 

357 return complex_functions 

358 

359 def _calculate_cognitive_complexity( 

360 self, 

361 node: ast.FunctionDef | ast.AsyncFunctionDef, 

362 ) -> int: 

363 class ComplexityCalculator(ast.NodeVisitor): 

364 def __init__(self) -> None: 

365 self.complexity = 0 

366 self.nesting_level = 0 

367 

368 def visit_If(self, node: ast.If) -> None: 

369 self.complexity += 1 + self.nesting_level 

370 self.nesting_level += 1 

371 self.generic_visit(node) 

372 self.nesting_level -= 1 

373 

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

375 self.complexity += 1 + self.nesting_level 

376 self.nesting_level += 1 

377 self.generic_visit(node) 

378 self.nesting_level -= 1 

379 

380 def visit_While(self, node: ast.While) -> None: 

381 self.complexity += 1 + self.nesting_level 

382 self.nesting_level += 1 

383 self.generic_visit(node) 

384 self.nesting_level -= 1 

385 

386 def visit_Try(self, node: ast.Try) -> None: 

387 self.complexity += 1 + self.nesting_level 

388 self.nesting_level += 1 

389 self.generic_visit(node) 

390 self.nesting_level -= 1 

391 

392 def visit_With(self, node: ast.With) -> None: 

393 self.complexity += 1 + self.nesting_level 

394 self.nesting_level += 1 

395 self.generic_visit(node) 

396 self.nesting_level -= 1 

397 

398 def visit_BoolOp(self, node: ast.BoolOp) -> None: 

399 self.complexity += len(node.values) - 1 

400 self.generic_visit(node) 

401 

402 calculator = ComplexityCalculator() 

403 calculator.visit(node) 

404 return calculator.complexity 

405 

406 def _apply_complexity_reduction( 

407 self, 

408 content: str, 

409 complex_functions: list[dict[str, t.Any]], 

410 ) -> str: 

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

412 

413 for func_info in complex_functions: 

414 func_name = func_info.get("name", "unknown") 

415 

416 if func_name == "detect_agent_needs": 

417 refactored = self._refactor_detect_agent_needs_pattern(content) 

418 if refactored != content: 

419 return refactored 

420 

421 func_content = self._extract_function_content(lines, func_info) 

422 if func_content: 

423 extracted_helpers = self._extract_logical_sections( 

424 func_content, func_info 

425 ) 

426 if extracted_helpers: 

427 modified_content = self._apply_function_extraction( 

428 content, func_info, extracted_helpers 

429 ) 

430 if modified_content != content: 

431 return modified_content 

432 

433 return content 

434 

435 def _refactor_detect_agent_needs_pattern(self, content: str) -> str: 

436 detect_func_start = "async def detect_agent_needs(" 

437 if detect_func_start not in content: 

438 return content 

439 

440 original_pattern = """ recommendations = { 

441 "urgent_agents": [], 

442 "suggested_agents": [], 

443 "workflow_recommendations": [], 

444 "detection_reasoning": "", 

445 } 

446 

447 if error_context:""" 

448 

449 replacement_pattern = """ recommendations = { 

450 "urgent_agents": [], 

451 "suggested_agents": [], 

452 "workflow_recommendations": [], 

453 "detection_reasoning": "", 

454 } 

455 

456 _add_urgent_agents_for_errors(recommendations, error_context) 

457 _add_python_project_suggestions(recommendations, file_patterns) 

458 _set_workflow_recommendations(recommendations) 

459 _generate_detection_reasoning(recommendations) 

460 

461 return json.dumps(recommendations, indent=2) 

462 

463 

464def _add_urgent_agents_for_errors(recommendations: dict, error_context: str) -> None: 

465 

466 if not error_context: 

467 return 

468 

469 error_lower = error_context.lower() 

470 

471 if any(term in error_lower for term in ["import", "module", "not found"]): 

472 recommendations["urgent_agents"].append({ 

473 "agent": "import-optimization-agent", 

474 "reason": "Import/module errors detected", 

475 "priority": "urgent" 

476 }) 

477 

478 if any(term in error_lower for term in ["test", "pytest", "assertion", "fixture"]): 

479 recommendations["urgent_agents"].append({ 

480 "agent": "test-specialist-agent", 

481 "reason": "Test-related errors detected", 

482 "priority": "urgent" 

483 }) 

484 

485 

486def _add_python_project_suggestions(recommendations: dict, file_patterns: str) -> None: 

487 

488 if not file_patterns: 

489 return 

490 

491 patterns_lower = file_patterns.lower() 

492 

493 if ".py" in patterns_lower: 

494 recommendations["suggested_agents"].extend([ 

495 { 

496 "agent": "python-pro", 

497 "reason": "Python files detected", 

498 "priority": "high" 

499 }, 

500 { 

501 "agent": "testing-frameworks", 

502 "reason": "Python testing needs", 

503 "priority": "medium" 

504 } 

505 ]) 

506 

507 

508def _set_workflow_recommendations(recommendations: dict) -> None: 

509 

510 recommendations["workflow_recommendations"] = [ 

511 "Run crackerjack quality checks first", 

512 "Use AI agent auto-fixing for complex issues", 

513 "Consider using crackerjack-architect for new features" 

514 ] 

515 

516 

517def _generate_detection_reasoning(recommendations: dict) -> None: 

518 

519 agent_count = len(recommendations["urgent_agents"]) + len(recommendations["suggested_agents"]) 

520 

521 if agent_count == 0: 

522 recommendations["detection_reasoning"] = "No specific agent recommendations based on current context" 

523 else: 

524 urgent_count = len(recommendations["urgent_agents"]) 

525 suggested_count = len(recommendations["suggested_agents"]) 

526 

527 reasoning = f"Detected {agent_count} relevant agents: " 

528 if urgent_count > 0: 

529 reasoning += f"{urgent_count} urgent priority" 

530 if suggested_count > 0: 

531 if urgent_count > 0: 

532 reasoning += f", {suggested_count} suggested priority" 

533 else: 

534 reasoning += f"{suggested_count} suggested priority" 

535 

536 recommendations["detection_reasoning"] = reasoning 

537 

538 

539 if error_context:""" 

540 

541 if original_pattern in content: 

542 modified_content = content.replace(original_pattern, replacement_pattern) 

543 

544 import re 

545 

546 pattern = r"if error_context:.*?(?=return json\.dumps)" 

547 modified_content = re.sub(pattern, "", modified_content, flags=re.DOTALL) 

548 return modified_content 

549 

550 return content 

551 

552 def _extract_logical_sections( 

553 self, func_content: str, func_info: dict[str, t.Any] 

554 ) -> list[dict[str, str]]: 

555 sections = [] 

556 

557 lines = func_content.split("\n") 

558 current_section = [] 

559 section_type = None 

560 

561 for line in lines: 

562 stripped = line.strip() 

563 

564 if stripped.startswith("if ") and len(stripped) > 50: 

565 if current_section: 

566 sections.append( 

567 { 

568 "type": section_type or "conditional", 

569 "content": "\n".join(current_section), 

570 "name": f"_handle_{section_type or 'condition'}_{len(sections) + 1}", 

571 } 

572 ) 

573 current_section = [line] 

574 section_type = "conditional" 

575 elif stripped.startswith(("for ", "while ")): 

576 if current_section and section_type != "loop": 

577 sections.append( 

578 { 

579 "type": section_type or "loop", 

580 "content": "\n".join(current_section), 

581 "name": f"_process_{section_type or 'loop'}_{len(sections) + 1}", 

582 } 

583 ) 

584 current_section = [line] 

585 section_type = "loop" 

586 else: 

587 current_section.append(line) 

588 

589 if current_section: 

590 sections.append( 

591 { 

592 "type": section_type or "general", 

593 "content": "\n".join(current_section), 

594 "name": f"_handle_{section_type or 'general'}_{len(sections) + 1}", 

595 } 

596 ) 

597 

598 return [s for s in sections if len(s["content"].split("\n")) >= 5] 

599 

600 def _extract_function_content( 

601 self, lines: list[str], func_info: dict[str, t.Any] 

602 ) -> str: 

603 start_line = func_info.get("line_start", 0) 

604 end_line = func_info.get("line_end", len(lines)) 

605 

606 if start_line <= 0 or end_line <= start_line: 

607 return "" 

608 

609 func_lines = lines[start_line - 1 : end_line] 

610 return "\n".join(func_lines) 

611 

612 def _apply_function_extraction( 

613 self, content: str, func_info: dict[str, t.Any], helpers: list[dict[str, str]] 

614 ) -> str: 

615 if not helpers: 

616 return content 

617 

618 return content 

619 

620 def _analyze_dead_code(self, tree: ast.AST, content: str) -> dict[str, t.Any]: 

621 analysis: dict[str, list[t.Any]] = { 

622 "unused_imports": [], 

623 "unused_variables": [], 

624 "unused_functions": [], 

625 "removable_items": [], 

626 } 

627 

628 analyzer_result = self._collect_usage_data(tree) 

629 self._process_unused_imports(analysis, analyzer_result) 

630 self._process_unused_functions(analysis, analyzer_result) 

631 

632 return analysis 

633 

634 def _collect_usage_data(self, tree: ast.AST) -> dict[str, t.Any]: 

635 defined_names: set[str] = set() 

636 used_names: set[str] = set() 

637 import_lines: list[tuple[int, str, str]] = [] 

638 unused_functions: list[dict[str, t.Any]] = [] 

639 

640 class UsageAnalyzer(ast.NodeVisitor): 

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

642 for alias in node.names: 

643 name = alias.asname or alias.name 

644 defined_names.add(name) 

645 import_lines.append((node.lineno, name, "import")) 

646 

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

648 for alias in node.names: 

649 name = alias.asname or alias.name 

650 defined_names.add(name) 

651 import_lines.append((node.lineno, name, "from_import")) 

652 

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

654 defined_names.add(node.name) 

655 if not node.name.startswith("_"): 

656 unused_functions.append({"name": node.name, "line": node.lineno}) 

657 self.generic_visit(node) 

658 

659 def visit_Name(self, node: ast.Name) -> None: 

660 if isinstance(node.ctx, ast.Load): 

661 used_names.add(node.id) 

662 

663 analyzer = UsageAnalyzer() 

664 analyzer.visit(tree) 

665 

666 return { 

667 "defined_names": defined_names, 

668 "used_names": used_names, 

669 "import_lines": import_lines, 

670 "unused_functions": unused_functions, 

671 } 

672 

673 def _process_unused_imports( 

674 self, 

675 analysis: dict[str, t.Any], 

676 analyzer_result: dict[str, t.Any], 

677 ) -> None: 

678 import_lines: list[tuple[int, str, str]] = analyzer_result["import_lines"] 

679 for line_no, name, import_type in import_lines: 

680 if name not in analyzer_result["used_names"]: 

681 analysis["unused_imports"].append( 

682 { 

683 "name": name, 

684 "line": line_no, 

685 "type": import_type, 

686 }, 

687 ) 

688 analysis["removable_items"].append(f"unused import: {name}") 

689 

690 def _process_unused_functions( 

691 self, 

692 analysis: dict[str, t.Any], 

693 analyzer_result: dict[str, t.Any], 

694 ) -> None: 

695 all_unused_functions: list[dict[str, t.Any]] = analyzer_result[ 

696 "unused_functions" 

697 ] 

698 unused_functions = [ 

699 func 

700 for func in all_unused_functions 

701 if func["name"] not in analyzer_result["used_names"] 

702 ] 

703 analysis["unused_functions"] = unused_functions 

704 for func in unused_functions: 

705 analysis["removable_items"].append(f"unused function: {func['name']}") 

706 

707 def _should_remove_import_line( 

708 self, line: str, unused_import: dict[str, str] 

709 ) -> bool: 

710 if unused_import["type"] == "import": 

711 return f"import {unused_import['name']}" in line 

712 elif unused_import["type"] == "from_import": 

713 return ( 

714 "from " in line 

715 and unused_import["name"] in line 

716 and line.strip().endswith(unused_import["name"]) 

717 ) 

718 return False 

719 

720 def _find_lines_to_remove( 

721 self, lines: list[str], analysis: dict[str, t.Any] 

722 ) -> set[int]: 

723 lines_to_remove: set[int] = set() 

724 

725 for unused_import in analysis["unused_imports"]: 

726 line_idx = unused_import["line"] - 1 

727 if 0 <= line_idx < len(lines): 

728 line = t.cast(str, lines[line_idx]) 

729 if self._should_remove_import_line(line, unused_import): 

730 lines_to_remove.add(line_idx) 

731 

732 return lines_to_remove 

733 

734 def _remove_dead_code_items(self, content: str, analysis: dict[str, t.Any]) -> str: 

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

736 lines_to_remove = self._find_lines_to_remove(lines, analysis) 

737 

738 filtered_lines = [ 

739 line for i, line in enumerate(lines) if i not in lines_to_remove 

740 ] 

741 

742 return "\n".join(filtered_lines) 

743 

744 

745agent_registry.register(RefactoringAgent)