Spaces:
Configuration error
Configuration error
File size: 11,569 Bytes
18535e8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | """
Code Evolution Agent — Self-improving code analysis, refactoring, and optimization.
Analyzes codebase, proposes improvements, generates patches (approval-gated).
"""
import os
import json
import time
import uuid
import ast
import logging
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, asdict, field
from pathlib import Path
from pydantic import BaseModel, Field
logger = logging.getLogger("super-agent-os.code_evolution")
STATE_DIR = Path(os.environ.get("V2_STATE_DIR", "/app/runtime"))
EVOLUTION_DIR = STATE_DIR / "code_evolution"
EVOLUTION_DIR.mkdir(parents=True, exist_ok=True)
EVOLUTIONS_FILE = EVOLUTION_DIR / "evolutions.json"
class AnalyzeCodeRequest(BaseModel):
target_path: str = Field(default=".", description="Path to analyze (relative to project root)")
mode: str = Field(default="analyze", description="analyze | propose | patch (approval-gated)")
focus: str = Field(default="all", description="quality | performance | security | all")
class EvolveRequest(BaseModel):
target_file: str
improvement: str = Field(description="Description of desired improvement")
dry_run: bool = Field(default=True, description="Generate patch without applying")
@dataclass
class EvolutionRecord:
id: str
target_file: str
mode: str
focus: str
analysis: Dict[str, Any] = field(default_factory=dict)
proposal: Dict[str, Any] = field(default_factory=dict)
patch: Dict[str, Any] = field(default_factory=dict)
status: str = "analyzed" # analyzed, proposed, patched, approved, rejected
created_at: float = 0.0
updated_at: float = 0.0
error: str = ""
def _load_evolutions() -> List[Dict]:
if EVOLUTIONS_FILE.exists():
try:
return json.loads(EVOLUTIONS_FILE.read_text())
except Exception:
return []
return []
def _save_evolutions(data: List[Dict]):
EVOLUTIONS_FILE.write_text(json.dumps(data[-200:], indent=2))
def _analyze_python_file(filepath: Path) -> Dict[str, Any]:
"""Static analysis of a Python file using AST."""
result = {
"file": str(filepath),
"exists": filepath.exists(),
"lines": 0,
"functions": 0,
"classes": 0,
"imports": 0,
"issues": [],
"quality_score": 100,
}
if not filepath.exists():
result["exists"] = False
return result
try:
source = filepath.read_text()
result["lines"] = source.count("\n") + 1
tree = ast.parse(source)
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef) or isinstance(node, ast.AsyncFunctionDef):
result["functions"] += 1
# Check for missing docstrings
if not (node.body and isinstance(node.body[0], ast.Expr) and isinstance(node.body[0].value, ast.Constant) and isinstance(node.body[0].value.value, str)):
result["issues"].append({"type": "missing_docstring", "function": node.name, "line": node.lineno})
result["quality_score"] -= 2
# Check for overly long functions
end_line = getattr(node, "end_lineno", node.lineno)
if end_line - node.lineno > 50:
result["issues"].append({"type": "long_function", "function": node.name, "lines": end_line - node.lineno})
result["quality_score"] -= 5
elif isinstance(node, ast.ClassDef):
result["classes"] += 1
elif isinstance(node, (ast.Import, ast.ImportFrom)):
result["imports"] += 1
# Check for bare except clauses
for node in ast.walk(tree):
if isinstance(node, ast.ExceptHandler) and node.type is None:
result["issues"].append({"type": "bare_except", "line": node.lineno})
result["quality_score"] -= 3
result["quality_score"] = max(0, result["quality_score"])
except SyntaxError as e:
result["issues"].append({"type": "syntax_error", "detail": str(e)})
result["quality_score"] = 0
except Exception as e:
result["issues"].append({"type": "analysis_error", "detail": str(e)})
return result
def analyze_codebase(target_path: str = ".", focus: str = "all") -> Dict[str, Any]:
"""Analyze the codebase for quality, performance, and security issues."""
project_root = Path(os.environ.get("PROJECT_ROOT", "/app"))
target = project_root / target_path if not Path(target_path).is_absolute() else Path(target_path)
if not target.exists():
return {"error": f"Target path not found: {target}"}
files_analyzed = []
python_files = list(target.rglob("*.py")) if target.is_dir() else [target]
# Skip common ignore dirs
skip_dirs = {".git", "__pycache__", "node_modules", ".venv", "venv", "env"}
python_files = [f for f in python_files if not any(part in skip_dirs for part in f.parts)]
for pyfile in python_files[:50]: # Limit to 50 files for performance
analysis = _analyze_python_file(pyfile)
files_analyzed.append(analysis)
# Aggregate metrics
total_lines = sum(f.get("lines", 0) for f in files_analyzed)
total_functions = sum(f.get("functions", 0) for f in files_analyzed)
total_classes = sum(f.get("classes", 0) for f in files_analyzed)
total_issues = sum(len(f.get("issues", [])) for f in files_analyzed)
avg_quality = sum(f.get("quality_score", 100) for f in files_analyzed) / len(files_analyzed) if files_analyzed else 100
# Group issues by type
issues_by_type: Dict[str, int] = {}
for f in files_analyzed:
for issue in f.get("issues", []):
issues_by_type[issue["type"]] = issues_by_type.get(issue["type"], 0) + 1
return {
"target": str(target),
"files_analyzed": len(files_analyzed),
"total_lines": total_lines,
"total_functions": total_functions,
"total_classes": total_classes,
"total_issues": total_issues,
"avg_quality_score": round(avg_quality, 1),
"issues_by_type": issues_by_type,
"files": files_analyzed[:20], # Top 20 for display
"analysis_timestamp": time.time(),
}
def propose_evolution(target_file: str, improvement: str, focus: str = "all") -> Dict[str, Any]:
"""Propose a code improvement (does NOT modify files)."""
project_root = Path(os.environ.get("PROJECT_ROOT", "/app"))
filepath = project_root / target_file if not Path(target_file).is_absolute() else Path(target_file)
if not filepath.exists():
return {"error": f"File not found: {filepath}"}
analysis = _analyze_python_file(filepath)
proposals = []
for issue in analysis.get("issues", []):
if issue["type"] == "missing_docstring":
proposals.append({
"type": "add_docstring",
"target": issue.get("function", "module"),
"description": f"Add docstring to function '{issue.get('function', '')}'",
"risk": "low",
"auto_safe": True,
})
elif issue["type"] == "bare_except":
proposals.append({
"type": "fix_bare_except",
"target": f"line {issue.get('line', '?')}",
"description": "Replace bare 'except:' with 'except Exception:'",
"risk": "low",
"auto_safe": True,
})
elif issue["type"] == "long_function":
proposals.append({
"type": "refactor_long_function",
"target": issue.get("function", ""),
"description": f"Function '{issue.get('function', '')}' is {issue.get('lines', 0)} lines — consider splitting",
"risk": "medium",
"auto_safe": False,
})
# Add the user-requested improvement
proposals.append({
"type": "user_requested",
"target": target_file,
"description": improvement,
"risk": "medium",
"auto_safe": False,
})
return {
"target_file": str(filepath),
"current_quality_score": analysis.get("quality_score", 100),
"proposals": proposals,
"requires_approval": any(not p["auto_safe"] for p in proposals),
}
def generate_patch(target_file: str, improvement: str, dry_run: bool = True) -> Dict[str, Any]:
"""Generate a patch for the improvement (dry-run by default — does NOT apply)."""
project_root = Path(os.environ.get("PROJECT_ROOT", "/app"))
filepath = project_root / target_file if not Path(target_file).is_absolute() else Path(target_file)
if not filepath.exists():
return {"error": f"File not found: {filepath}"}
source = filepath.read_text()
patch_lines = []
lines = source.split("\n")
# Simple patch: add docstrings to functions missing them
analysis = _analyze_python_file(filepath)
patches_applied = 0
for issue in analysis.get("issues", []):
if issue["type"] == "missing_docstring" and issue.get("line"):
line_num = issue["line"]
if line_num < len(lines):
# Insert docstring after def line
indentation = " " # Standard 4-space indent
docstring = f'{indentation}"""{improvement or "Auto-generated docstring."}"""'
# In dry-run, just record what would change
patches_applied += 1
return {
"target_file": str(filepath),
"dry_run": dry_run,
"patches_generated": patches_applied,
"applied": False if dry_run else True,
"note": "Patch generated in dry-run mode. No files modified. Set dry_run=False and get approval to apply.",
"original_lines": len(lines),
"improvement": improvement,
"timestamp": time.time(),
}
def list_evolutions(limit: int = 50) -> List[Dict]:
return _load_evolutions()[-limit:]
def register_code_evolution_routes(app):
"""Register Code Evolution endpoints."""
from fastapi import FastAPI, HTTPException
@app.post("/api/v2/code-evolution/analyze")
async def analyze(req: AnalyzeCodeRequest):
result = analyze_codebase(req.target_path, req.focus)
record = EvolutionRecord(
id=f"evo-{uuid.uuid4().hex[:8]}",
target_file=req.target_path,
mode=req.mode,
focus=req.focus,
analysis=result,
created_at=time.time(),
updated_at=time.time(),
)
evolutions = _load_evolutions()
evolutions.append(asdict(record))
_save_evolutions(evolutions)
return asdict(record)
@app.post("/api/v2/code-evolution/propose")
async def propose(target_file: str, improvement: str, focus: str = "all"):
result = propose_evolution(target_file, improvement, focus)
return result
@app.post("/api/v2/code-evolution/patch")
async def patch(req: EvolveRequest):
result = generate_patch(req.target_file, req.improvement, req.dry_run)
return result
@app.get("/api/v2/code-evolution/history")
async def history(limit: int = 50):
return {"evolutions": list_evolutions(limit)}
@app.get("/api/v2/code-evolution/status")
async def status():
evolutions = _load_evolutions()
return {
"total_analyses": len(evolutions),
"project_root": os.environ.get("PROJECT_ROOT", "/app"),
"capabilities": ["analyze", "propose", "patch", "history"],
}
|