diff --git a/agent/evolution/code_refactorer.py b/agent/evolution/code_refactorer.py new file mode 100644 index 000000000..f36c09afe --- /dev/null +++ b/agent/evolution/code_refactorer.py @@ -0,0 +1,60 @@ +"""Phase 9: Codebase-Wide Refactoring & Optimization. + +Performs a "Deep Audit" of the codebase to identify bottlenecks and vulnerabilities. +""" + +import logging +import json +from typing import List, Dict, Any +from agent.gemini_adapter import GeminiAdapter + +logger = logging.getLogger(__name__) + +class CodeRefactorer: + def __init__(self): + self.adapter = GeminiAdapter() + + def audit_codebase(self, file_contents: Dict[str, str]) -> Dict[str, Any]: + """Performs a deep audit of the provided codebase files.""" + logger.info(f"Auditing {len(file_contents)} files for refactoring and optimization.") + + # Combine file contents for context + context = "\n".join([f"--- {path} ---\n{content}" for path, content in file_contents.items()]) + + prompt = f""" +Codebase Context: +{context} + +Please perform a 'Deep Audit' of this codebase. +Identify: +1. Performance bottlenecks (e.g., inefficient loops, redundant API calls). +2. Security vulnerabilities (e.g., hardcoded keys, PII leaks, insecure defaults). +3. Architectural debt (e.g., tight coupling, lack of modularity). + +Generate a set of 'Refactoring Patches' to address these issues. + +Format the output as JSON: +{{ + "audit_report": "...", + "vulnerabilities": [...], + "performance_issues": [...], + "patches": [ + {{ + "file": "...", + "description": "...", + "original_code": "...", + "replacement_code": "..." + }} + ] +}} +""" + result = self.adapter.generate( + model="gemini-3.1-pro-preview", + prompt=prompt, + system_instruction="You are Timmy's Code Refactorer. Your goal is to make the codebase as efficient, secure, and sovereign as possible.", + thinking=True, + response_mime_type="application/json" + ) + + audit_data = json.loads(result["text"]) + return audit_data