New.space / artifacts /bounty-agent /code_evolution.py
Cryptostoner's picture
Deploy verified Autonomous Revenue Agent V2 Docker build
18535e8 verified
Raw History Blame Contribute Delete
11.6 kB
"""
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"],
}