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
« 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
5from .base import (
6 FixResult,
7 Issue,
8 IssueType,
9 SubAgent,
10 agent_registry,
11)
14class RefactoringAgent(SubAgent):
15 def get_supported_types(self) -> set[IssueType]:
16 return {IssueType.COMPLEXITY, IssueType.DEAD_CODE}
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
25 async def analyze_and_fix(self, issue: Issue) -> FixResult:
26 self.log(f"Analyzing {issue.type.value} issue: {issue.message}")
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)
33 return FixResult(
34 success=False,
35 confidence=0.0,
36 remaining_issues=[f"RefactoringAgent cannot handle {issue.type.value}"],
37 )
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
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 )
51 file_path = Path(issue.file_path)
53 if "detect_agent_needs" in issue.message:
54 return await self._apply_known_complexity_fix(file_path, issue)
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)
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 )
74 refactored_content = self._refactor_detect_agent_needs_pattern(content)
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 )
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 )
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 )
124 return None
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 )
135 tree = ast.parse(content)
136 complex_functions = self._find_complex_functions(tree, content)
138 if not complex_functions:
139 return FixResult(
140 success=True,
141 confidence=0.7,
142 recommendations=["No overly complex functions found"],
143 )
145 return self._apply_and_save_refactoring(file_path, content, complex_functions)
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 )
158 if refactored_content == content:
159 return self._create_no_changes_result()
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 )
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 )
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 )
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 )
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 )
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
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 )
215 file_path = Path(issue.file_path)
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)
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 )
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 )
240 return None
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 )
251 tree = ast.parse(content)
252 dead_code_analysis = self._analyze_dead_code(tree, content)
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 )
261 return self._apply_and_save_cleanup(file_path, content, dead_code_analysis)
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)
271 if cleaned_content == content:
272 return self._create_no_cleanup_result()
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 )
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 )
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 )
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 )
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]] = []
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
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)
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)
354 analyzer = ComplexityAnalyzer(self._calculate_cognitive_complexity)
355 analyzer.visit(tree)
357 return complex_functions
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
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
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
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
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
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
398 def visit_BoolOp(self, node: ast.BoolOp) -> None:
399 self.complexity += len(node.values) - 1
400 self.generic_visit(node)
402 calculator = ComplexityCalculator()
403 calculator.visit(node)
404 return calculator.complexity
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")
413 for func_info in complex_functions:
414 func_name = func_info.get("name", "unknown")
416 if func_name == "detect_agent_needs":
417 refactored = self._refactor_detect_agent_needs_pattern(content)
418 if refactored != content:
419 return refactored
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
433 return content
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
440 original_pattern = """ recommendations = {
441 "urgent_agents": [],
442 "suggested_agents": [],
443 "workflow_recommendations": [],
444 "detection_reasoning": "",
445 }
447 if error_context:"""
449 replacement_pattern = """ recommendations = {
450 "urgent_agents": [],
451 "suggested_agents": [],
452 "workflow_recommendations": [],
453 "detection_reasoning": "",
454 }
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)
461 return json.dumps(recommendations, indent=2)
464def _add_urgent_agents_for_errors(recommendations: dict, error_context: str) -> None:
466 if not error_context:
467 return
469 error_lower = error_context.lower()
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 })
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 })
486def _add_python_project_suggestions(recommendations: dict, file_patterns: str) -> None:
488 if not file_patterns:
489 return
491 patterns_lower = file_patterns.lower()
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 ])
508def _set_workflow_recommendations(recommendations: dict) -> None:
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 ]
517def _generate_detection_reasoning(recommendations: dict) -> None:
519 agent_count = len(recommendations["urgent_agents"]) + len(recommendations["suggested_agents"])
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"])
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"
536 recommendations["detection_reasoning"] = reasoning
539 if error_context:"""
541 if original_pattern in content:
542 modified_content = content.replace(original_pattern, replacement_pattern)
544 import re
546 pattern = r"if error_context:.*?(?=return json\.dumps)"
547 modified_content = re.sub(pattern, "", modified_content, flags=re.DOTALL)
548 return modified_content
550 return content
552 def _extract_logical_sections(
553 self, func_content: str, func_info: dict[str, t.Any]
554 ) -> list[dict[str, str]]:
555 sections = []
557 lines = func_content.split("\n")
558 current_section = []
559 section_type = None
561 for line in lines:
562 stripped = line.strip()
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)
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 )
598 return [s for s in sections if len(s["content"].split("\n")) >= 5]
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))
606 if start_line <= 0 or end_line <= start_line:
607 return ""
609 func_lines = lines[start_line - 1 : end_line]
610 return "\n".join(func_lines)
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
618 return content
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 }
628 analyzer_result = self._collect_usage_data(tree)
629 self._process_unused_imports(analysis, analyzer_result)
630 self._process_unused_functions(analysis, analyzer_result)
632 return analysis
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]] = []
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"))
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"))
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)
659 def visit_Name(self, node: ast.Name) -> None:
660 if isinstance(node.ctx, ast.Load):
661 used_names.add(node.id)
663 analyzer = UsageAnalyzer()
664 analyzer.visit(tree)
666 return {
667 "defined_names": defined_names,
668 "used_names": used_names,
669 "import_lines": import_lines,
670 "unused_functions": unused_functions,
671 }
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}")
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']}")
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
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()
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)
732 return lines_to_remove
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)
738 filtered_lines = [
739 line for i, line in enumerate(lines) if i not in lines_to_remove
740 ]
742 return "\n".join(filtered_lines)
745agent_registry.register(RefactoringAgent)