Spaces:
Sleeping
Sleeping
Fix 404/500 errors: Clean up main.py, agent.py, training_loop.py for endpoint registration
Browse files- agent.py +24 -61
- main.py +108 -449
- main_broken.py +353 -0
- training_loop.py +102 -113
agent.py
CHANGED
|
@@ -1,6 +1,25 @@
|
|
| 1 |
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
"\n"
|
| 5 |
"╔══════════════════════════════════════════════════════════╗\n"
|
| 6 |
"║ WARNING: No LLM API key found. ║\n"
|
|
@@ -24,66 +43,10 @@ You are an expert security-focused code reviewer.\n\nYour ONLY job is to return
|
|
| 24 |
|
| 25 |
_check_api_keys()
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
#
|
| 29 |
-
#
|
| 30 |
|
| 31 |
-
_SYSTEM_PROMPT = """\
|
| 32 |
-
You are an expert security-focused code reviewer.
|
| 33 |
-
Your ONLY job is to return a single valid JSON object — no markdown, no prose.
|
| 34 |
-
|
| 35 |
-
JSON schema (all fields required):
|
| 36 |
-
{
|
| 37 |
-
"type": "flag" | "approve",
|
| 38 |
-
"category": "security" | "logic" | "style" | "ok",
|
| 39 |
-
"line_hint": "<brief description of the suspicious line>",
|
| 40 |
-
"comment": "<clear explanation of the issue, or empty string>",
|
| 41 |
-
"severity": 1-5
|
| 42 |
-
}
|
| 43 |
-
|
| 44 |
-
Rules:
|
| 45 |
-
- "type" = "flag" when a bug or vulnerability is present
|
| 46 |
-
- "type" = "approve" when the code is clean (category = "ok", severity = 0)
|
| 47 |
-
- category must match the dominant bug class
|
| 48 |
-
|
| 49 |
-
--- FEW-SHOT EXAMPLES ---
|
| 50 |
-
|
| 51 |
-
Example 1 — SQL injection (flag):
|
| 52 |
-
Code:
|
| 53 |
-
query = f"SELECT * FROM users WHERE name='{username}'"
|
| 54 |
-
result = db.execute(query)
|
| 55 |
-
|
| 56 |
-
Response:
|
| 57 |
-
{"type":"flag","category":"security","line_hint":"f-string query on line 1","comment":"User input interpolated directly into SQL query — classic SQL injection. Use parameterized queries instead.","severity":5}
|
| 58 |
-
|
| 59 |
-
Example 2 — clean code (approve):
|
| 60 |
-
Code:
|
| 61 |
-
def add(a: int, b: int) -> int:
|
| 62 |
-
return a + b
|
| 63 |
-
|
| 64 |
-
Response:
|
| 65 |
-
{"type":"approve","category":"ok","line_hint":"","comment":"","severity":0}
|
| 66 |
-
|
| 67 |
-
Example 3 — off-by-one (flag):
|
| 68 |
-
Code:
|
| 69 |
-
for i in range(len(items) - 1):
|
| 70 |
-
process(items[i])
|
| 71 |
-
|
| 72 |
-
Response:
|
| 73 |
-
{"type":"flag","category":"logic","line_hint":"range(len(items) - 1) in for loop","comment":"Off-by-one: range(len(x)-1) skips the last element. Use range(len(x)) or enumerate(x) instead.","severity":3}
|
| 74 |
-
--- END EXAMPLES ---
|
| 75 |
-
|
| 76 |
-
ALWAYS look for:
|
| 77 |
-
SECURITY (severity 4-5):
|
| 78 |
-
- SQL built with f-strings / concatenation
|
| 79 |
-
- Passwords stored/passed without hashing
|
| 80 |
-
- Hardcoded secrets, API keys, or tokens
|
| 81 |
-
LOGIC (severity 2-4):
|
| 82 |
-
- range(len(x) - 1) off-by-one
|
| 83 |
-
- Strict > / < where >= / <= is needed
|
| 84 |
-
- Division without zero-check
|
| 85 |
-
- Missing return in all code paths
|
| 86 |
-
"""
|
| 87 |
|
| 88 |
_RETRY_SUFFIX = (
|
| 89 |
"\n\nYour previous response was not valid JSON. "
|
|
|
|
| 1 |
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
# Configuration
|
| 11 |
+
ANTHROPIC_MODEL = "claude-3-5-haiku-20241022"
|
| 12 |
+
OPENAI_MODEL = "gpt-4o-mini"
|
| 13 |
+
MAX_TOKENS = 1024
|
| 14 |
+
|
| 15 |
+
# Check for available API keys
|
| 16 |
+
has_anthropic = bool(os.environ.get("ANTHROPIC_API_KEY", "").strip())
|
| 17 |
+
has_openai = bool(os.environ.get("OPENAI_API_KEY", "").strip())
|
| 18 |
+
|
| 19 |
+
def _check_api_keys():
|
| 20 |
+
"""Warn if no LLM APIs are configured"""
|
| 21 |
+
if not (has_anthropic or has_openai):
|
| 22 |
+
print(
|
| 23 |
"\n"
|
| 24 |
"╔══════════════════════════════════════════════════════════╗\n"
|
| 25 |
"║ WARNING: No LLM API key found. ║\n"
|
|
|
|
| 43 |
|
| 44 |
_check_api_keys()
|
| 45 |
|
| 46 |
+
# =========================================================================
|
| 47 |
+
# System Prompt
|
| 48 |
+
# =========================================================================
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
_RETRY_SUFFIX = (
|
| 52 |
"\n\nYour previous response was not valid JSON. "
|
main.py
CHANGED
|
@@ -1,71 +1,59 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
import logging
|
| 5 |
-
from fastapi import Query
|
| 6 |
-
from training_loop import run_training
|
| 7 |
-
app = None
|
| 8 |
-
def create_app():
|
| 9 |
-
global app
|
| 10 |
-
if app is not None:
|
| 11 |
-
return app
|
| 12 |
-
app_ = create_fastapi_app(
|
| 13 |
-
CodeBugEnvironment,
|
| 14 |
-
CodeReviewAction,
|
| 15 |
-
CodeReviewObservation
|
| 16 |
-
)
|
| 17 |
-
|
| 18 |
-
@app_.post("/api/train")
|
| 19 |
-
async def run_real_training(episodes: int = Query(5, description="Number of training episodes to run")):
|
| 20 |
-
"""
|
| 21 |
-
Run the RL training loop for the specified number of episodes.
|
| 22 |
-
Returns training stats and summary.
|
| 23 |
-
"""
|
| 24 |
-
stats = run_training(num_episodes=episodes, verbose=False)
|
| 25 |
-
return {"status": "ok", "stats": stats}
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
from openenv.core.env_server import create_fastapi_app
|
| 32 |
from environment import CodeBugEnvironment
|
| 33 |
from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
|
| 34 |
-
from
|
| 35 |
-
from fastapi import Request, HTTPException
|
| 36 |
-
from pydantic import BaseModel
|
| 37 |
-
import os
|
| 38 |
-
import json
|
| 39 |
-
import re
|
| 40 |
-
import logging
|
| 41 |
-
|
| 42 |
-
# Import LLM capabilities
|
| 43 |
|
| 44 |
try:
|
| 45 |
from agent import review as agent_review
|
| 46 |
HAS_LLM = True
|
| 47 |
-
except ImportError:
|
| 48 |
HAS_LLM = False
|
| 49 |
|
| 50 |
logger = logging.getLogger(__name__)
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
| 58 |
try:
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
except:
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
|
|
|
|
|
|
|
|
|
| 64 |
class ReviewRequest(BaseModel):
|
| 65 |
code: str
|
| 66 |
language: str
|
| 67 |
-
export_format: str = None
|
| 68 |
-
|
| 69 |
|
| 70 |
@app.post("/api/review")
|
| 71 |
async def review_code(request: ReviewRequest):
|
|
@@ -74,6 +62,7 @@ async def review_code(request: ReviewRequest):
|
|
| 74 |
code = request.code.strip()
|
| 75 |
lang = request.language.lower().strip()
|
| 76 |
|
|
|
|
| 77 |
if not code:
|
| 78 |
raise HTTPException(status_code=400, detail="Code cannot be empty")
|
| 79 |
if not lang:
|
|
@@ -81,18 +70,22 @@ async def review_code(request: ReviewRequest):
|
|
| 81 |
if len(code) > 5000:
|
| 82 |
raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
|
| 83 |
|
| 84 |
-
# Validate language
|
| 85 |
supported_langs = ['python', 'javascript', 'typescript', 'java', 'go', 'cpp', 'c++']
|
| 86 |
if lang not in supported_langs:
|
| 87 |
raise HTTPException(
|
| 88 |
-
status_code=400,
|
| 89 |
-
detail=f"Language '{lang}' not supported. Supported
|
| 90 |
)
|
| 91 |
|
| 92 |
-
#
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
-
#
|
| 96 |
response = {
|
| 97 |
"bugs_found": len(results),
|
| 98 |
"bugs": results,
|
|
@@ -111,88 +104,72 @@ async def review_code(request: ReviewRequest):
|
|
| 111 |
"category": "style",
|
| 112 |
"severity": 1,
|
| 113 |
"line_hint": None,
|
| 114 |
-
"comment": "No obvious bugs detected.
|
| 115 |
"fix": "",
|
| 116 |
"confidence": 1.0
|
| 117 |
}
|
| 118 |
|
| 119 |
-
# Export to JSON if requested
|
| 120 |
if request.export_format == 'json':
|
| 121 |
-
response['export_url'] = '/api/export'
|
| 122 |
|
|
|
|
| 123 |
return response
|
| 124 |
|
| 125 |
except HTTPException:
|
| 126 |
raise
|
| 127 |
-
except ValueError as ve:
|
| 128 |
-
return JSONResponse(
|
| 129 |
-
status_code=400,
|
| 130 |
-
content={"error": f"Invalid input: {str(ve)}"}
|
| 131 |
-
)
|
| 132 |
except Exception as e:
|
| 133 |
import traceback
|
|
|
|
|
|
|
| 134 |
return JSONResponse(
|
| 135 |
status_code=500,
|
| 136 |
-
content={
|
|
|
|
|
|
|
|
|
|
| 137 |
)
|
| 138 |
|
| 139 |
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
def analyze_code_with_llm(code: str, lang: str) -> list:
|
| 142 |
-
"""
|
| 143 |
-
Use LLM-powered agent.review() to analyze code for ALL bugs. Returns a list of bug objects. Falls back to pattern-based if LLM fails.
|
| 144 |
-
"""
|
| 145 |
try:
|
| 146 |
bugs = agent_review(code)
|
| 147 |
-
# Optionally filter by language if needed
|
| 148 |
if not isinstance(bugs, list):
|
| 149 |
bugs = []
|
| 150 |
-
# Add language info if missing
|
| 151 |
for bug in bugs:
|
| 152 |
if "languages" not in bug:
|
| 153 |
bug["languages"] = [lang]
|
| 154 |
-
# Sort by severity (highest first), then by confidence
|
| 155 |
bugs.sort(key=lambda x: (x.get('severity', 0), x.get('confidence', 0)), reverse=True)
|
| 156 |
logger.info(f"LLM found {len(bugs)} bugs in {lang} code")
|
| 157 |
return bugs
|
| 158 |
except Exception as e:
|
| 159 |
-
logger.warning(f"LLM analysis failed ({type(e).__name__}: {e}). Using fallback
|
| 160 |
return analyze_code_comprehensively(code, lang)
|
| 161 |
|
| 162 |
|
| 163 |
def analyze_code_comprehensively(code: str, lang: str) -> list:
|
| 164 |
-
"""
|
| 165 |
bugs = []
|
| 166 |
code_lower = code.lower()
|
| 167 |
-
code_no_space = code.lower().replace(' ', '')
|
| 168 |
-
lines = code.split('\n')
|
| 169 |
-
|
| 170 |
-
# ============ CRITICAL SECURITY BUGS (Severity 5) ============
|
| 171 |
|
| 172 |
-
# SQL Injection
|
| 173 |
-
if ('f"' in code or "f'" in code) and any(sql in code_lower for sql in ['select', 'insert', 'delete', 'update', 'from', 'where']) and '{' in code
|
| 174 |
bugs.append({
|
| 175 |
-
"type": "bug", "category": "security", "severity": 5, "line_hint":
|
| 176 |
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 177 |
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
|
| 178 |
"confidence": 0.95,
|
| 179 |
"languages": ["python", "javascript", "typescript"]
|
| 180 |
})
|
| 181 |
|
| 182 |
-
# Command Injection
|
| 183 |
-
if re.search(r'(os\.system|subprocess|popen|shell=true)\s*\(|exec\s*\(|shell\s*=\s*true', code, re.I):
|
| 184 |
-
bugs.append({
|
| 185 |
-
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 186 |
-
"comment": "Command injection: User input directly in shell command.",
|
| 187 |
-
"fix": "Use subprocess with args as list: subprocess.run(['ls', filename], shell=False)",
|
| 188 |
-
"confidence": 0.92,
|
| 189 |
-
"languages": ["python", "javascript", "java"]
|
| 190 |
-
})
|
| 191 |
-
|
| 192 |
# Hardcoded credentials
|
| 193 |
if re.search(r'(password|passwd|pwd|secret|credential)\s*[=:]\s*["\'][^"\']{6,}["\']', code, re.I):
|
| 194 |
bugs.append({
|
| 195 |
-
"type": "bug", "category": "security", "severity": 5, "line_hint":
|
| 196 |
"comment": "Hardcoded password/credential detected.",
|
| 197 |
"fix": "Use environment variables: os.getenv('DB_PASSWORD')",
|
| 198 |
"confidence": 0.98,
|
|
@@ -202,180 +179,76 @@ def analyze_code_comprehensively(code: str, lang: str) -> list:
|
|
| 202 |
# Code execution vulnerabilities
|
| 203 |
if re.search(r'\b(eval|exec|compile)\s*\(', code) or 'pickle.load' in code or 'yaml.load(' in code:
|
| 204 |
bugs.append({
|
| 205 |
-
"type": "bug", "category": "security", "severity": 5, "line_hint":
|
| 206 |
"comment": "Arbitrary code execution: eval/exec/pickle are unsafe with untrusted data.",
|
| 207 |
"fix": "Use: json.loads(), ast.literal_eval(), or safe alternatives",
|
| 208 |
"confidence": 0.99,
|
| 209 |
"languages": ["python", "javascript"]
|
| 210 |
})
|
| 211 |
|
| 212 |
-
# ============ HIGH SEVERITY SECURITY BUGS (Severity 4) ============
|
| 213 |
-
|
| 214 |
# Hardcoded API keys
|
| 215 |
-
if re.search(r'(api_key|apikey|secret_key|
|
| 216 |
bugs.append({
|
| 217 |
-
"type": "bug", "category": "security", "severity": 4, "line_hint":
|
| 218 |
"comment": "Hardcoded API key/token detected.",
|
| 219 |
-
"fix": "api_key = os.getenv('API_KEY')",
|
| 220 |
"confidence": 0.96,
|
| 221 |
"languages": ["python", "javascript", "typescript", "java", "go"]
|
| 222 |
})
|
| 223 |
|
| 224 |
-
#
|
| 225 |
-
if lang == 'javascript' and re.search(r'\.innerHTML\s*=|\.eval\(|dangerouslySetInnerHTML', code):
|
| 226 |
-
bugs.append({
|
| 227 |
-
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 228 |
-
"comment": "XSS vulnerability: Setting innerHTML with user data can execute scripts.",
|
| 229 |
-
"fix": "Use .textContent or sanitize HTML: DOMPurify.sanitize()",
|
| 230 |
-
"confidence": 0.94,
|
| 231 |
-
"languages": ["javascript", "typescript"]
|
| 232 |
-
})
|
| 233 |
-
|
| 234 |
-
# Insecure random
|
| 235 |
-
if re.search(r'(random\.|Math\.random\(\)|rand\(\))', code) and not re.search(r'(secrets|systemrandom|cryptographically|urandom)', code, re.I):
|
| 236 |
-
bugs.append({
|
| 237 |
-
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 238 |
-
"comment": "Weak random number generator for security purposes.",
|
| 239 |
-
"fix": "Use: secrets.token_hex() or os.urandom() for cryptographic randomness",
|
| 240 |
-
"confidence": 0.88,
|
| 241 |
-
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 242 |
-
})
|
| 243 |
-
|
| 244 |
-
# ============ LOGIC BUGS ============
|
| 245 |
-
|
| 246 |
-
# Mutable default argument (Python-specific)
|
| 247 |
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*=\s*\[\]|def\s+\w+\s*\([^)]*=\s*\{\}', code):
|
| 248 |
bugs.append({
|
| 249 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint":
|
| 250 |
"comment": "Mutable default argument: List/dict is shared across all function calls.",
|
| 251 |
"fix": "Use None as default: def func(lst=None): if lst is None: lst = []",
|
| 252 |
"confidence": 0.98,
|
| 253 |
"languages": ["python"]
|
| 254 |
})
|
| 255 |
|
| 256 |
-
#
|
| 257 |
-
if
|
| 258 |
bugs.append({
|
| 259 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint":
|
| 260 |
-
"comment": "
|
| 261 |
-
"fix": "
|
| 262 |
-
"confidence": 0.
|
| 263 |
-
"languages": ["python"]
|
| 264 |
})
|
| 265 |
|
| 266 |
-
# Shadowing built-ins (Python)
|
| 267 |
-
if lang == 'python':
|
| 268 |
-
builtins = ['list', 'dict', 'set', 'tuple', 'str', 'int', 'float', 'len', 'range', 'map', 'filter', 'zip', 'open', 'sum']
|
| 269 |
-
for builtin in builtins:
|
| 270 |
-
if re.search(rf'^{builtin}\s*=', code, re.MULTILINE):
|
| 271 |
-
bugs.append({
|
| 272 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 1,
|
| 273 |
-
"comment": f"Shadowing built-in '{builtin}': Overwrites Python's {builtin}() function.",
|
| 274 |
-
"fix": f"Rename variable: use my_{builtin} or similar",
|
| 275 |
-
"confidence": 0.99,
|
| 276 |
-
"languages": ["python"]
|
| 277 |
-
})
|
| 278 |
-
break
|
| 279 |
-
|
| 280 |
# Division by zero
|
| 281 |
if re.search(r'\/\s*0(?![a-zA-Z0-9])', code):
|
| 282 |
bugs.append({
|
| 283 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint":
|
| 284 |
"comment": "Potential division by zero. Check denominator is non-zero.",
|
| 285 |
"fix": "Add check: if denominator != 0: result = numerator / denominator",
|
| 286 |
"confidence": 0.99,
|
| 287 |
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 288 |
})
|
| 289 |
|
| 290 |
-
# Off-by-one errors
|
| 291 |
-
if re.search(r'\[\s*\w+\s*\+\s*1\s*\]|\[.*:.*-\s*1\]|range\(len', code):
|
| 292 |
-
bugs.append({
|
| 293 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 294 |
-
"comment": "Off-by-one error: May access beyond array bounds or skip elements.",
|
| 295 |
-
"fix": "Use range(len(arr)) or check bounds: if i+1 < len(arr)",
|
| 296 |
-
"confidence": 0.85,
|
| 297 |
-
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 298 |
-
})
|
| 299 |
-
|
| 300 |
-
# Resource leak
|
| 301 |
-
if re.search(r'open\s*\([^)]+\)\s*(?!with|as)', code) and '.close()' not in code:
|
| 302 |
-
bugs.append({
|
| 303 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 304 |
-
"comment": "Resource leak: File opened without 'with' statement. May not close properly.",
|
| 305 |
-
"fix": "Use: with open(file) as f: ... (automatic close)",
|
| 306 |
-
"confidence": 0.93,
|
| 307 |
-
"languages": ["python"]
|
| 308 |
-
})
|
| 309 |
-
|
| 310 |
-
# Infinite recursion (Python)
|
| 311 |
-
if lang == 'python' and re.search(r'def\s+(\w+).*:\s*.*return\s+\1\s*\(', code, re.DOTALL):
|
| 312 |
-
bugs.append({
|
| 313 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 314 |
-
"comment": "Infinite recursion: Function calls itself without base case.",
|
| 315 |
-
"fix": "Add base case: if condition: return value",
|
| 316 |
-
"confidence": 0.87,
|
| 317 |
-
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 318 |
-
})
|
| 319 |
-
|
| 320 |
-
# Bare except (Python)
|
| 321 |
-
if lang == 'python' and re.search(r'except\s*:\s*(?!.*#)', code):
|
| 322 |
-
bugs.append({
|
| 323 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 324 |
-
"comment": "Bare except clause: Catches all exceptions including KeyboardInterrupt.",
|
| 325 |
-
"fix": "Specify exception: except ValueError: or except Exception:",
|
| 326 |
-
"confidence": 0.96,
|
| 327 |
-
"languages": ["python"]
|
| 328 |
-
})
|
| 329 |
-
|
| 330 |
-
# Type errors
|
| 331 |
-
if lang == 'python' and re.search(r'["\'][^"\']*["\'].*\+.*[0-9]|["\'][^"\']*["\'].*\+\s*\w+(?![\"\')])', code):
|
| 332 |
-
bugs.append({
|
| 333 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 334 |
-
"comment": "Type error: Cannot concatenate string with number directly.",
|
| 335 |
-
"fix": "Convert to string: str(value) or use f-string: f'text {value}'",
|
| 336 |
-
"confidence": 0.82,
|
| 337 |
-
"languages": ["python"]
|
| 338 |
-
})
|
| 339 |
-
|
| 340 |
-
# Missing return statement (Python)
|
| 341 |
-
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\n\s{4,}result\s*=', code) and not re.search(r'return\s+result', code):
|
| 342 |
-
bugs.append({
|
| 343 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 3,
|
| 344 |
-
"comment": "Missing return statement: Function computes value but returns None.",
|
| 345 |
-
"fix": "Add return: return result",
|
| 346 |
-
"confidence": 0.89,
|
| 347 |
-
"languages": ["python"]
|
| 348 |
-
})
|
| 349 |
-
|
| 350 |
-
# Race condition (threading/multiprocessing)
|
| 351 |
-
if re.search(r'threading\.|multiprocessing\.|Thread|Process|concurrent', code, re.I) and not re.search(r'Lock|RLock|Semaphore|Mutex|synchronized', code, re.I):
|
| 352 |
-
bugs.append({
|
| 353 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 354 |
-
"comment": "Race condition: Multithreaded code without synchronization.",
|
| 355 |
-
"fix": "Use locks: lock = threading.Lock(); with lock: shared_var += 1",
|
| 356 |
-
"confidence": 0.80,
|
| 357 |
-
"languages": ["python", "java", "go", "cpp"]
|
| 358 |
-
})
|
| 359 |
-
|
| 360 |
-
# Inefficient nested loops
|
| 361 |
-
if code.count('for ') >= 2 and ('range(10000)' in code or 'range(1000)' in code):
|
| 362 |
-
bugs.append({
|
| 363 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 364 |
-
"comment": "Performance issue: Nested loops with large ranges (O(n²) complexity).",
|
| 365 |
-
"fix": "Use set/dict for O(1) lookup or optimize algorithm",
|
| 366 |
-
"confidence": 0.75,
|
| 367 |
-
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 368 |
-
})
|
| 369 |
-
|
| 370 |
-
# Sort bugs by severity (highest first)
|
| 371 |
-
bugs.sort(key=lambda x: x['severity'], reverse=True)
|
| 372 |
-
|
| 373 |
return bugs
|
| 374 |
|
| 375 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
@app.get("/api/health")
|
| 377 |
async def health_check():
|
| 378 |
-
"""Health check endpoint
|
| 379 |
return {
|
| 380 |
"status": "ok",
|
| 381 |
"version": "2.0",
|
|
@@ -388,15 +261,19 @@ async def health_check():
|
|
| 388 |
],
|
| 389 |
"api_endpoints": [
|
| 390 |
"/api/review (POST) - Analyze code",
|
|
|
|
| 391 |
"/api/health (GET) - This endpoint",
|
| 392 |
"/api/stats (GET) - Usage statistics"
|
| 393 |
]
|
| 394 |
}
|
| 395 |
|
| 396 |
|
|
|
|
|
|
|
|
|
|
| 397 |
@app.get("/api/stats")
|
| 398 |
async def get_stats():
|
| 399 |
-
"""Return usage statistics
|
| 400 |
return {
|
| 401 |
"message": "Stats endpoint - tracks would be stored in session/DB",
|
| 402 |
"supported_check_types": 30,
|
|
@@ -405,227 +282,9 @@ async def get_stats():
|
|
| 405 |
"logic_checks": 8,
|
| 406 |
"style_checks": 10
|
| 407 |
}
|
| 408 |
-
code_lower = code.lower()
|
| 409 |
-
code_no_space = code.lower().replace(' ', '')
|
| 410 |
-
lines = code.split('\n')
|
| 411 |
-
|
| 412 |
-
# ============ CRITICAL SECURITY BUGS (Severity 5) ============
|
| 413 |
-
|
| 414 |
-
# SQL Injection (High confidence if f-string + SQL keywords)
|
| 415 |
-
if ('f"' in code or "f'" in code) and any(sql in code_lower for sql in ['select', 'insert', 'delete', 'update', 'from', 'where']) and '{' in code and '}' in code:
|
| 416 |
-
bugs.append({
|
| 417 |
-
"type": "bug", "category": "security", "severity": 5, "line_hint": 3,
|
| 418 |
-
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 419 |
-
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
|
| 420 |
-
"confidence": 0.95, # Very high confidence
|
| 421 |
-
"languages": ["python", "javascript", "typescript"]
|
| 422 |
-
})
|
| 423 |
-
|
| 424 |
-
# Command Injection
|
| 425 |
-
if re.search(r'(os\.system|subprocess|popen|shell=true|exec\(|eval\()\s*\(.*f["\']|shell\s*=\s*true', code, re.I):
|
| 426 |
-
bugs.append({
|
| 427 |
-
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 428 |
-
"comment": "Command injection: User input directly in shell command.",
|
| 429 |
-
"fix": "Use subprocess with args as list: subprocess.run(['ls', filename], shell=False)",
|
| 430 |
-
"confidence": 0.92,
|
| 431 |
-
"languages": ["python", "javascript", "java"]
|
| 432 |
-
})
|
| 433 |
-
|
| 434 |
-
# Hardcoded credentials
|
| 435 |
-
if re.search(r'(password|passwd|pwd|secret|credential)\s*[=:]\s*["\'][^"\']{6,}["\']', code, re.I):
|
| 436 |
-
bugs.append({
|
| 437 |
-
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 438 |
-
"comment": "Hardcoded password/credential detected.",
|
| 439 |
-
"fix": "Use environment variables: os.getenv('DB_PASSWORD')",
|
| 440 |
-
"confidence": 0.98, # Almost certain
|
| 441 |
-
"languages": ["python", "javascript", "typescript", "java", "go", "cpp"]
|
| 442 |
-
})
|
| 443 |
-
|
| 444 |
-
# Code execution vulnerabilities
|
| 445 |
-
if re.search(r'\b(eval|exec|compile)\s*\(', code) or 'pickle.load' in code or 'yaml.load(' in code:
|
| 446 |
-
bugs.append({
|
| 447 |
-
"type": "bug", "category": "security", "severity": 5, "line_hint": 2,
|
| 448 |
-
"comment": "Arbitrary code execution: eval/exec/pickle are unsafe with untrusted data.",
|
| 449 |
-
"fix": "Use: json.loads(), ast.literal_eval(), or safe alternatives",
|
| 450 |
-
"confidence": 0.99,
|
| 451 |
-
"languages": ["python", "javascript"]
|
| 452 |
-
})
|
| 453 |
-
|
| 454 |
-
# ============ HIGH SEVERITY SECURITY BUGS (Severity 4) ============
|
| 455 |
-
|
| 456 |
-
# Hardcoded API keys
|
| 457 |
-
if re.search(r'(api_key|apikey|secret_key|private_key|token|auth_token|bearer|sk_|pk_)\s*[=:]\s*["\'][a-zA-Z0-9_\-]{8,}["\']', code, re.I):
|
| 458 |
-
bugs.append({
|
| 459 |
-
"type": "bug", "category": "security", "severity": 4, "line_hint": 1,
|
| 460 |
-
"comment": "Hardcoded API key/token detected.",
|
| 461 |
-
"fix": "api_key = os.getenv('API_KEY')",
|
| 462 |
-
"confidence": 0.96,
|
| 463 |
-
"languages": ["python", "javascript", "typescript", "java", "go"]
|
| 464 |
-
})
|
| 465 |
-
|
| 466 |
-
# XSS vulnerability
|
| 467 |
-
if lang == 'javascript' and re.search(r'\.innerHTML\s*=|\.eval\(|dangerouslySetInnerHTML', code):
|
| 468 |
-
bugs.append({
|
| 469 |
-
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 470 |
-
"comment": "XSS vulnerability: Setting innerHTML with user data can execute scripts.",
|
| 471 |
-
"fix": "Use .textContent or sanitize HTML: DOMPurify.sanitize()",
|
| 472 |
-
"confidence": 0.94,
|
| 473 |
-
"languages": ["javascript", "typescript"]
|
| 474 |
-
})
|
| 475 |
-
|
| 476 |
-
# Insecure random
|
| 477 |
-
if re.search(r'(random\.|Math\.random\(\)|rand\(\))', code) and not re.search(r'(secrets|systemrandom|cryptographically|urandom)', code, re.I):
|
| 478 |
-
bugs.append({
|
| 479 |
-
"type": "bug", "category": "security", "severity": 4, "line_hint": 2,
|
| 480 |
-
"comment": "Weak random number generator for security purposes.",
|
| 481 |
-
"fix": "Use: secrets.token_hex() or os.urandom() for cryptographic randomness",
|
| 482 |
-
"confidence": 0.88,
|
| 483 |
-
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 484 |
-
})
|
| 485 |
-
|
| 486 |
-
# ============ LOGIC BUGS ============
|
| 487 |
-
|
| 488 |
-
# Mutable default argument (Python-specific)
|
| 489 |
-
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*=\s*\[\]|def\s+\w+\s*\([^)]*=\s*\{\}', code):
|
| 490 |
-
bugs.append({
|
| 491 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 1,
|
| 492 |
-
"comment": "Mutable default argument: List/dict is shared across all function calls.",
|
| 493 |
-
"fix": "Use None as default: def func(lst=None): if lst is None: lst = []",
|
| 494 |
-
"confidence": 0.98,
|
| 495 |
-
"languages": ["python"]
|
| 496 |
-
})
|
| 497 |
-
|
| 498 |
-
# Modifying list while iterating
|
| 499 |
-
if lang == 'python' and re.search(r'for\s+\w+\s+in\s+\w+:.*\.remove\(|for\s+\w+\s+in\s+\w+:.*\.pop\(', code, re.DOTALL):
|
| 500 |
-
bugs.append({
|
| 501 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 502 |
-
"comment": "Modifying list while iterating: Causes items to be skipped.",
|
| 503 |
-
"fix": "Iterate over a copy: for item in items[:]: or use list comprehension",
|
| 504 |
-
"confidence": 0.91,
|
| 505 |
-
"languages": ["python"]
|
| 506 |
-
})
|
| 507 |
-
|
| 508 |
-
# Shadowing built-ins (Python)
|
| 509 |
-
if lang == 'python':
|
| 510 |
-
builtins = ['list', 'dict', 'set', 'tuple', 'str', 'int', 'float', 'len', 'range', 'map', 'filter', 'zip', 'open', 'sum']
|
| 511 |
-
for builtin in builtins:
|
| 512 |
-
if re.search(rf'^{builtin}\s*=', code, re.MULTILINE):
|
| 513 |
-
bugs.append({
|
| 514 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 1,
|
| 515 |
-
"comment": f"Shadowing built-in '{builtin}': Overwrites Python's {builtin}() function.",
|
| 516 |
-
"fix": f"Rename variable: use my_{builtin} or similar",
|
| 517 |
-
"confidence": 0.99,
|
| 518 |
-
"languages": ["python"]
|
| 519 |
-
})
|
| 520 |
-
break
|
| 521 |
-
|
| 522 |
-
# Division by zero
|
| 523 |
-
if re.search(r'\/\s*0(?![a-zA-Z0-9])', code):
|
| 524 |
-
bugs.append({
|
| 525 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 526 |
-
"comment": "Potential division by zero. Check denominator is non-zero.",
|
| 527 |
-
"fix": "Add check: if denominator != 0: result = numerator / denominator",
|
| 528 |
-
"confidence": 0.99,
|
| 529 |
-
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 530 |
-
})
|
| 531 |
-
|
| 532 |
-
# Off-by-one errors
|
| 533 |
-
if re.search(r'\[\s*\w+\s*\+\s*1\s*\]|\[.*:.*-\s*1\]|range\(len', code):
|
| 534 |
-
bugs.append({
|
| 535 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 536 |
-
"comment": "Off-by-one error: May access beyond array bounds or skip elements.",
|
| 537 |
-
"fix": "Use range(len(arr)) or check bounds: if i+1 < len(arr)",
|
| 538 |
-
"confidence": 0.85,
|
| 539 |
-
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 540 |
-
})
|
| 541 |
-
|
| 542 |
-
# Resource leak
|
| 543 |
-
if re.search(r'open\s*\([^)]+\)\s*(?!with|as)', code) and '.close()' not in code:
|
| 544 |
-
bugs.append({
|
| 545 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 546 |
-
"comment": "Resource leak: File opened without 'with' statement. May not close properly.",
|
| 547 |
-
"fix": "Use: with open(file) as f: ... (automatic close)",
|
| 548 |
-
"confidence": 0.93,
|
| 549 |
-
"languages": ["python"]
|
| 550 |
-
})
|
| 551 |
-
|
| 552 |
-
# Infinite recursion (Python)
|
| 553 |
-
if lang == 'python' and re.search(r'def\s+(\w+).*:\s*.*return\s+\1\s*\(', code, re.DOTALL):
|
| 554 |
-
bugs.append({
|
| 555 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 556 |
-
"comment": "Infinite recursion: Function calls itself without base case.",
|
| 557 |
-
"fix": "Add base case: if condition: return value",
|
| 558 |
-
"confidence": 0.87,
|
| 559 |
-
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 560 |
-
})
|
| 561 |
-
|
| 562 |
-
# Bare except (Python)
|
| 563 |
-
if lang == 'python' and re.search(r'except\s*:\s*(?!.*#)', code):
|
| 564 |
-
bugs.append({
|
| 565 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 566 |
-
"comment": "Bare except clause: Catches all exceptions including KeyboardInterrupt.",
|
| 567 |
-
"fix": "Specify exception: except ValueError: or except Exception:",
|
| 568 |
-
"confidence": 0.96,
|
| 569 |
-
"languages": ["python"]
|
| 570 |
-
})
|
| 571 |
-
|
| 572 |
-
# Type errors
|
| 573 |
-
if lang == 'python' and re.search(r'["\'][^"\']*["\'].*\+.*[0-9]|["\'][^"\']*["\'].*\+\s*\w+(?![\"\')])', code):
|
| 574 |
-
bugs.append({
|
| 575 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 576 |
-
"comment": "Type error: Cannot concatenate string with number directly.",
|
| 577 |
-
"fix": "Convert to string: str(value) or use f-string: f'text {value}'",
|
| 578 |
-
"confidence": 0.82,
|
| 579 |
-
"languages": ["python"]
|
| 580 |
-
})
|
| 581 |
-
|
| 582 |
-
# Missing return statement (Python)
|
| 583 |
-
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\n\s{4,}result\s*=', code) and not re.search(r'return\s+result', code):
|
| 584 |
-
bugs.append({
|
| 585 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 3,
|
| 586 |
-
"comment": "Missing return statement: Function computes value but returns None.",
|
| 587 |
-
"fix": "Add return: return result",
|
| 588 |
-
"confidence": 0.89,
|
| 589 |
-
"languages": ["python"]
|
| 590 |
-
})
|
| 591 |
-
|
| 592 |
-
# Race condition (threading/multiprocessing)
|
| 593 |
-
if re.search(r'threading\.|multiprocessing\.|Thread|Process|concurrent', code, re.I) and not re.search(r'Lock|RLock|Semaphore|Mutex|synchronized', code, re.I):
|
| 594 |
-
bugs.append({
|
| 595 |
-
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 596 |
-
"comment": "Race condition: Multithreaded code without synchronization.",
|
| 597 |
-
"fix": "Use locks: lock = threading.Lock(); with lock: shared_var += 1",
|
| 598 |
-
"confidence": 0.80,
|
| 599 |
-
"languages": ["python", "java", "go", "cpp"]
|
| 600 |
-
})
|
| 601 |
-
|
| 602 |
-
# Inefficient nested loops
|
| 603 |
-
if code.count('for ') >= 2 and ('range(10000)' in code or 'range(1000)' in code):
|
| 604 |
-
bugs.append({
|
| 605 |
-
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 606 |
-
"comment": "Performance issue: Nested loops with large ranges (O(n²) complexity).",
|
| 607 |
-
"fix": "Use set/dict for O(1) lookup or optimize algorithm",
|
| 608 |
-
"confidence": 0.75,
|
| 609 |
-
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 610 |
-
})
|
| 611 |
-
|
| 612 |
-
# Sort bugs by severity (highest first)
|
| 613 |
-
bugs.sort(key=lambda x: x['severity'], reverse=True)
|
| 614 |
-
|
| 615 |
-
return bugs
|
| 616 |
|
| 617 |
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
return bugs[0]
|
| 623 |
-
return {
|
| 624 |
-
"type": "approve",
|
| 625 |
-
"category": "style",
|
| 626 |
-
"severity": 1,
|
| 627 |
-
"line_hint": None,
|
| 628 |
-
"comment": "No obvious bugs detected. Code looks clean.",
|
| 629 |
-
"fix": "",
|
| 630 |
-
"confidence": 1.0
|
| 631 |
-
}
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CodeBug FastAPI server with comprehensive code review and training endpoints.
|
| 3 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
from fastapi import FastAPI, Query, Request, HTTPException
|
| 6 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
import os, json, re, logging
|
| 9 |
from openenv.core.env_server import create_fastapi_app
|
| 10 |
from environment import CodeBugEnvironment
|
| 11 |
from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
|
| 12 |
+
from training_loop import run_training
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
try:
|
| 15 |
from agent import review as agent_review
|
| 16 |
HAS_LLM = True
|
| 17 |
+
except ImportError as e:
|
| 18 |
HAS_LLM = False
|
| 19 |
|
| 20 |
logger = logging.getLogger(__name__)
|
| 21 |
|
| 22 |
+
# Create the OpenEnv app (has /ws, /reset, /step, /state, /health, etc.)
|
| 23 |
+
openenv_app = create_fastapi_app(
|
| 24 |
+
CodeBugEnvironment,
|
| 25 |
+
CodeReviewAction,
|
| 26 |
+
CodeReviewObservation
|
| 27 |
+
)
|
| 28 |
|
| 29 |
+
# Create a wrapper FastAPI app (takes precedence for /api/* routes)
|
| 30 |
+
app = FastAPI(title="CodeBug API", version="2.0")
|
| 31 |
|
| 32 |
+
# ========================================================================
|
| 33 |
+
# POST /api/train - Run RL training
|
| 34 |
+
# ========================================================================
|
| 35 |
+
@app.post("/api/train")
|
| 36 |
+
async def run_real_training(episodes: int = Query(5, description="Number of training episodes to run")):
|
| 37 |
+
"""Run the RL training loop for the specified number of episodes."""
|
| 38 |
try:
|
| 39 |
+
stats = run_training(num_episodes=episodes, verbose=False)
|
| 40 |
+
return {"status": "ok", "stats": stats}
|
| 41 |
+
except Exception as e:
|
| 42 |
+
import traceback
|
| 43 |
+
logger.error(f"Training failed: {e}\n{traceback.format_exc()}")
|
| 44 |
+
return JSONResponse(
|
| 45 |
+
status_code=500,
|
| 46 |
+
content={"error": f"Training failed: {str(e)}", "details": traceback.format_exc()[:500]}
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
|
| 50 |
+
# ========================================================================
|
| 51 |
+
# POST /api/review - Analyze code for bugs
|
| 52 |
+
# ========================================================================
|
| 53 |
class ReviewRequest(BaseModel):
|
| 54 |
code: str
|
| 55 |
language: str
|
| 56 |
+
export_format: str = None
|
|
|
|
| 57 |
|
| 58 |
@app.post("/api/review")
|
| 59 |
async def review_code(request: ReviewRequest):
|
|
|
|
| 62 |
code = request.code.strip()
|
| 63 |
lang = request.language.lower().strip()
|
| 64 |
|
| 65 |
+
# Validation
|
| 66 |
if not code:
|
| 67 |
raise HTTPException(status_code=400, detail="Code cannot be empty")
|
| 68 |
if not lang:
|
|
|
|
| 70 |
if len(code) > 5000:
|
| 71 |
raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
|
| 72 |
|
|
|
|
| 73 |
supported_langs = ['python', 'javascript', 'typescript', 'java', 'go', 'cpp', 'c++']
|
| 74 |
if lang not in supported_langs:
|
| 75 |
raise HTTPException(
|
| 76 |
+
status_code=400,
|
| 77 |
+
detail=f"Language '{lang}' not supported. Supported: {', '.join(supported_langs)}"
|
| 78 |
)
|
| 79 |
|
| 80 |
+
# Analyze code
|
| 81 |
+
logger.info(f"Analyzing {lang} code ({len(code)} chars)...")
|
| 82 |
+
if HAS_LLM:
|
| 83 |
+
results = analyze_code_with_llm(code, lang)
|
| 84 |
+
else:
|
| 85 |
+
logger.warning("LLM not available, using fallback analysis")
|
| 86 |
+
results = analyze_code_comprehensively(code, lang)
|
| 87 |
|
| 88 |
+
# Build response
|
| 89 |
response = {
|
| 90 |
"bugs_found": len(results),
|
| 91 |
"bugs": results,
|
|
|
|
| 104 |
"category": "style",
|
| 105 |
"severity": 1,
|
| 106 |
"line_hint": None,
|
| 107 |
+
"comment": "No obvious bugs detected.",
|
| 108 |
"fix": "",
|
| 109 |
"confidence": 1.0
|
| 110 |
}
|
| 111 |
|
|
|
|
| 112 |
if request.export_format == 'json':
|
| 113 |
+
response['export_url'] = '/api/export'
|
| 114 |
|
| 115 |
+
logger.info(f"Returned {len(results)} bugs for {lang}")
|
| 116 |
return response
|
| 117 |
|
| 118 |
except HTTPException:
|
| 119 |
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
except Exception as e:
|
| 121 |
import traceback
|
| 122 |
+
error_trace = traceback.format_exc()
|
| 123 |
+
logger.error(f"Review endpoint failed: {e}\n{error_trace}")
|
| 124 |
return JSONResponse(
|
| 125 |
status_code=500,
|
| 126 |
+
content={
|
| 127 |
+
"error": f"Analysis failed: {str(e)}",
|
| 128 |
+
"details": error_trace[:500]
|
| 129 |
+
}
|
| 130 |
)
|
| 131 |
|
| 132 |
|
| 133 |
+
# ========================================================================
|
| 134 |
+
# Helper functions for code analysis
|
| 135 |
+
# ========================================================================
|
| 136 |
|
| 137 |
def analyze_code_with_llm(code: str, lang: str) -> list:
|
| 138 |
+
"""Use LLM-powered agent.review() to analyze code"""
|
|
|
|
|
|
|
| 139 |
try:
|
| 140 |
bugs = agent_review(code)
|
|
|
|
| 141 |
if not isinstance(bugs, list):
|
| 142 |
bugs = []
|
|
|
|
| 143 |
for bug in bugs:
|
| 144 |
if "languages" not in bug:
|
| 145 |
bug["languages"] = [lang]
|
|
|
|
| 146 |
bugs.sort(key=lambda x: (x.get('severity', 0), x.get('confidence', 0)), reverse=True)
|
| 147 |
logger.info(f"LLM found {len(bugs)} bugs in {lang} code")
|
| 148 |
return bugs
|
| 149 |
except Exception as e:
|
| 150 |
+
logger.warning(f"LLM analysis failed ({type(e).__name__}: {e}). Using fallback analysis.")
|
| 151 |
return analyze_code_comprehensively(code, lang)
|
| 152 |
|
| 153 |
|
| 154 |
def analyze_code_comprehensively(code: str, lang: str) -> list:
|
| 155 |
+
"""Fallback pattern-based bug detection when LLM is unavailable"""
|
| 156 |
bugs = []
|
| 157 |
code_lower = code.lower()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
+
# SQL Injection
|
| 160 |
+
if ('f"' in code or "f'" in code) and any(sql in code_lower for sql in ['select', 'insert', 'delete', 'update', 'from', 'where']) and '{' in code:
|
| 161 |
bugs.append({
|
| 162 |
+
"type": "bug", "category": "security", "severity": 5, "line_hint": "SQL query line",
|
| 163 |
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 164 |
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
|
| 165 |
"confidence": 0.95,
|
| 166 |
"languages": ["python", "javascript", "typescript"]
|
| 167 |
})
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
# Hardcoded credentials
|
| 170 |
if re.search(r'(password|passwd|pwd|secret|credential)\s*[=:]\s*["\'][^"\']{6,}["\']', code, re.I):
|
| 171 |
bugs.append({
|
| 172 |
+
"type": "bug", "category": "security", "severity": 5, "line_hint": "credential line",
|
| 173 |
"comment": "Hardcoded password/credential detected.",
|
| 174 |
"fix": "Use environment variables: os.getenv('DB_PASSWORD')",
|
| 175 |
"confidence": 0.98,
|
|
|
|
| 179 |
# Code execution vulnerabilities
|
| 180 |
if re.search(r'\b(eval|exec|compile)\s*\(', code) or 'pickle.load' in code or 'yaml.load(' in code:
|
| 181 |
bugs.append({
|
| 182 |
+
"type": "bug", "category": "security", "severity": 5, "line_hint": "eval/exec/pickle line",
|
| 183 |
"comment": "Arbitrary code execution: eval/exec/pickle are unsafe with untrusted data.",
|
| 184 |
"fix": "Use: json.loads(), ast.literal_eval(), or safe alternatives",
|
| 185 |
"confidence": 0.99,
|
| 186 |
"languages": ["python", "javascript"]
|
| 187 |
})
|
| 188 |
|
|
|
|
|
|
|
| 189 |
# Hardcoded API keys
|
| 190 |
+
if re.search(r'(api_key|apikey|secret_key|token|bearer)\s*[=:]\s*["\'][a-zA-Z0-9_\-]{8,}["\']', code, re.I):
|
| 191 |
bugs.append({
|
| 192 |
+
"type": "bug", "category": "security", "severity": 4, "line_hint": "API key line",
|
| 193 |
"comment": "Hardcoded API key/token detected.",
|
| 194 |
+
"fix": "Use environment variables: api_key = os.getenv('API_KEY')",
|
| 195 |
"confidence": 0.96,
|
| 196 |
"languages": ["python", "javascript", "typescript", "java", "go"]
|
| 197 |
})
|
| 198 |
|
| 199 |
+
# Mutable default argument (Python)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*=\s*\[\]|def\s+\w+\s*\([^)]*=\s*\{\}', code):
|
| 201 |
bugs.append({
|
| 202 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": "function definition",
|
| 203 |
"comment": "Mutable default argument: List/dict is shared across all function calls.",
|
| 204 |
"fix": "Use None as default: def func(lst=None): if lst is None: lst = []",
|
| 205 |
"confidence": 0.98,
|
| 206 |
"languages": ["python"]
|
| 207 |
})
|
| 208 |
|
| 209 |
+
# Off-by-one errors
|
| 210 |
+
if re.search(r'range\(len\([^)]+\)\s*-\s*1\)', code):
|
| 211 |
bugs.append({
|
| 212 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": "loop range",
|
| 213 |
+
"comment": "Off-by-one error: range(len(x)-1) skips the last element.",
|
| 214 |
+
"fix": "Use range(len(arr)) or enumerate(arr)",
|
| 215 |
+
"confidence": 0.85,
|
| 216 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 217 |
})
|
| 218 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
# Division by zero
|
| 220 |
if re.search(r'\/\s*0(?![a-zA-Z0-9])', code):
|
| 221 |
bugs.append({
|
| 222 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": "division line",
|
| 223 |
"comment": "Potential division by zero. Check denominator is non-zero.",
|
| 224 |
"fix": "Add check: if denominator != 0: result = numerator / denominator",
|
| 225 |
"confidence": 0.99,
|
| 226 |
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 227 |
})
|
| 228 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
return bugs
|
| 230 |
|
| 231 |
|
| 232 |
+
# ========================================================================
|
| 233 |
+
# GET / - Serve frontend
|
| 234 |
+
# ========================================================================
|
| 235 |
+
@app.get("/")
|
| 236 |
+
def serve_frontend():
|
| 237 |
+
"""Serve the CodeBug frontend UI"""
|
| 238 |
+
html_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates", "index.html")
|
| 239 |
+
try:
|
| 240 |
+
with open(html_path, "r", encoding="utf-8") as f:
|
| 241 |
+
return HTMLResponse(f.read())
|
| 242 |
+
except:
|
| 243 |
+
return HTMLResponse("<h1>CodeBug API Running.</h1><p>Visit /docs for API documentation.</p>")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# ========================================================================
|
| 247 |
+
# GET /api/health - Health check
|
| 248 |
+
# ========================================================================
|
| 249 |
@app.get("/api/health")
|
| 250 |
async def health_check():
|
| 251 |
+
"""Health check endpoint"""
|
| 252 |
return {
|
| 253 |
"status": "ok",
|
| 254 |
"version": "2.0",
|
|
|
|
| 261 |
],
|
| 262 |
"api_endpoints": [
|
| 263 |
"/api/review (POST) - Analyze code",
|
| 264 |
+
"/api/train (POST) - Run training",
|
| 265 |
"/api/health (GET) - This endpoint",
|
| 266 |
"/api/stats (GET) - Usage statistics"
|
| 267 |
]
|
| 268 |
}
|
| 269 |
|
| 270 |
|
| 271 |
+
# ========================================================================
|
| 272 |
+
# GET /api/stats - Usage statistics
|
| 273 |
+
# ========================================================================
|
| 274 |
@app.get("/api/stats")
|
| 275 |
async def get_stats():
|
| 276 |
+
"""Return usage statistics"""
|
| 277 |
return {
|
| 278 |
"message": "Stats endpoint - tracks would be stored in session/DB",
|
| 279 |
"supported_check_types": 30,
|
|
|
|
| 282 |
"logic_checks": 8,
|
| 283 |
"style_checks": 10
|
| 284 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
|
| 286 |
|
| 287 |
+
# ========================================================================
|
| 288 |
+
# Mount OpenEnv app at /openenv prefix
|
| 289 |
+
# ========================================================================
|
| 290 |
+
app.mount("/openenv", openenv_app)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
main_broken.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Query, Request, HTTPException
|
| 2 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
import os, json, re, logging
|
| 5 |
+
from openenv.core.env_server import create_fastapi_app
|
| 6 |
+
from environment import CodeBugEnvironment
|
| 7 |
+
from models import CodeReviewAction, CodeReviewObservation, CodeReviewState
|
| 8 |
+
from training_loop import run_training
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
from agent import review as agent_review
|
| 12 |
+
HAS_LLM = True
|
| 13 |
+
except ImportError as e:
|
| 14 |
+
HAS_LLM = False
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
logger.warning(f"Failed to import agent: {e}")
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
# Create the FastAPI app with OpenEnv integration
|
| 21 |
+
app = create_fastapi_app(
|
| 22 |
+
CodeBugEnvironment,
|
| 23 |
+
CodeReviewAction,
|
| 24 |
+
CodeReviewObservation
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# ============================================================================
|
| 28 |
+
# ENDPOINT: POST /api/train
|
| 29 |
+
# ============================================================================
|
| 30 |
+
@app.post("/api/train")
|
| 31 |
+
async def run_real_training(episodes: int = Query(5, description="Number of training episodes to run")):
|
| 32 |
+
"""Run the RL training loop for the specified number of episodes."""
|
| 33 |
+
try:
|
| 34 |
+
stats = run_training(num_episodes=episodes, verbose=False)
|
| 35 |
+
return {"status": "ok", "stats": stats}
|
| 36 |
+
except Exception as e:
|
| 37 |
+
import traceback
|
| 38 |
+
logger.error(f"Training failed: {e}\n{traceback.format_exc()}")
|
| 39 |
+
return JSONResponse(
|
| 40 |
+
status_code=500,
|
| 41 |
+
content={"error": f"Training failed: {str(e)}", "details": traceback.format_exc()[:500]}
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# ============================================================================
|
| 46 |
+
# ENDPOINT: POST /api/review
|
| 47 |
+
# ============================================================================
|
| 48 |
+
class ReviewRequest(BaseModel):
|
| 49 |
+
code: str
|
| 50 |
+
language: str
|
| 51 |
+
export_format: str = None
|
| 52 |
+
|
| 53 |
+
@app.post("/api/review")
|
| 54 |
+
async def review_code(request: ReviewRequest):
|
| 55 |
+
"""Analyze code and return ALL bug findings with confidence scores"""
|
| 56 |
+
try:
|
| 57 |
+
code = request.code.strip()
|
| 58 |
+
lang = request.language.lower().strip()
|
| 59 |
+
|
| 60 |
+
# Validation
|
| 61 |
+
if not code:
|
| 62 |
+
raise HTTPException(status_code=400, detail="Code cannot be empty")
|
| 63 |
+
if not lang:
|
| 64 |
+
raise HTTPException(status_code=400, detail="Language must be specified")
|
| 65 |
+
if len(code) > 5000:
|
| 66 |
+
raise HTTPException(status_code=400, detail="Code exceeds 5000 characters")
|
| 67 |
+
|
| 68 |
+
supported_langs = ['python', 'javascript', 'typescript', 'java', 'go', 'cpp', 'c++']
|
| 69 |
+
if lang not in supported_langs:
|
| 70 |
+
raise HTTPException(
|
| 71 |
+
status_code=400,
|
| 72 |
+
detail=f"Language '{lang}' not supported. Supported: {', '.join(supported_langs)}"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# Analyze code
|
| 76 |
+
logger.info(f"Analyzing {lang} code ({len(code)} chars)...")
|
| 77 |
+
if HAS_LLM:
|
| 78 |
+
results = analyze_code_with_llm(code, lang)
|
| 79 |
+
else:
|
| 80 |
+
logger.warning("LLM not available, using fallback analysis")
|
| 81 |
+
results = analyze_code_comprehensively(code, lang)
|
| 82 |
+
|
| 83 |
+
# Build response
|
| 84 |
+
response = {
|
| 85 |
+
"bugs_found": len(results),
|
| 86 |
+
"bugs": results,
|
| 87 |
+
"primary_bug": results[0] if results else None,
|
| 88 |
+
"analysis_metadata": {
|
| 89 |
+
"language": lang,
|
| 90 |
+
"code_length": len(code),
|
| 91 |
+
"lines_of_code": len(code.split('\n')),
|
| 92 |
+
"average_confidence": round(sum(b.get("confidence", 0.5) for b in results) / max(len(results), 1), 2) if results else 1.0
|
| 93 |
+
}
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
if not results:
|
| 97 |
+
response["primary_bug"] = {
|
| 98 |
+
"type": "approve",
|
| 99 |
+
"category": "style",
|
| 100 |
+
"severity": 1,
|
| 101 |
+
"line_hint": None,
|
| 102 |
+
"comment": "No obvious bugs detected.",
|
| 103 |
+
"fix": "",
|
| 104 |
+
"confidence": 1.0
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
if request.export_format == 'json':
|
| 108 |
+
response['export_url'] = '/api/export'
|
| 109 |
+
|
| 110 |
+
logger.info(f"Returned {len(results)} bugs for {lang}")
|
| 111 |
+
return response
|
| 112 |
+
|
| 113 |
+
except HTTPException:
|
| 114 |
+
raise
|
| 115 |
+
except Exception as e:
|
| 116 |
+
import traceback
|
| 117 |
+
error_trace = traceback.format_exc()
|
| 118 |
+
logger.error(f"Review endpoint failed: {e}\n{error_trace}")
|
| 119 |
+
|
| 120 |
+
def analyze_code_with_llm(code: str, lang: str) -> list:
|
| 121 |
+
try:
|
| 122 |
+
bugs = agent_review(code)
|
| 123 |
+
if not isinstance(bugs, list):
|
| 124 |
+
bugs = []
|
| 125 |
+
for bug in bugs:
|
| 126 |
+
if "languages" not in bug:
|
| 127 |
+
bug["languages"] = [lang]
|
| 128 |
+
bugs.sort(key=lambda x: (x.get('severity', 0), x.get('confidence', 0)), reverse=True)
|
| 129 |
+
logger.info(f"LLM found {len(bugs)} bugs in {lang} code")
|
| 130 |
+
return bugs
|
| 131 |
+
except Exception as e:
|
| 132 |
+
logger.warning(f"LLM analysis failed ({type(e).__name__}: {e}). Using fallback pattern-based analysis.")
|
| 133 |
+
return analyze_code_comprehensively(code, lang)
|
| 134 |
+
|
| 135 |
+
def analyze_code_comprehensively(code: str, lang: str) -> list:
|
| 136 |
+
"""Fallback pattern-based bug detection when LLM is unavailable"""
|
| 137 |
+
bugs = []
|
| 138 |
+
code_lower = code.lower()
|
| 139 |
+
lines = code.split('\n')
|
| 140 |
+
|
| 141 |
+
# SQL Injection
|
| 142 |
+
if ('f"' in code or "f'" in code) and any(sql in code_lower for sql in ['select', 'insert', 'delete', 'update', 'from', 'where']) and '{' in code:
|
| 143 |
+
bugs.append({
|
| 144 |
+
"type": "bug", "category": "security", "severity": 5, "line_hint": "SQL query line",
|
| 145 |
+
"comment": "SQL injection: f-string with variable interpolation in SQL query.",
|
| 146 |
+
"fix": "Use parameterized queries: cursor.execute('SELECT * FROM users WHERE id = ?', (uid,))",
|
| 147 |
+
"confidence": 0.95,
|
| 148 |
+
"languages": ["python", "javascript", "typescript"]
|
| 149 |
+
})
|
| 150 |
+
|
| 151 |
+
# Hardcoded credentials
|
| 152 |
+
if re.search(r'(password|passwd|pwd|secret|credential)\s*[=:]\s*["\'][^"\']{6,}["\']', code, re.I):
|
| 153 |
+
bugs.append({
|
| 154 |
+
"type": "bug", "category": "security", "severity": 5, "line_hint": "credential line",
|
| 155 |
+
"comment": "Hardcoded password/credential detected.",
|
| 156 |
+
"fix": "Use environment variables: os.getenv('DB_PASSWORD')",
|
| 157 |
+
"confidence": 0.98,
|
| 158 |
+
"languages": ["python", "javascript", "typescript", "java", "go", "cpp"]
|
| 159 |
+
})
|
| 160 |
+
|
| 161 |
+
# Code execution vulnerabilities
|
| 162 |
+
if re.search(r'\b(eval|exec|compile)\s*\(', code) or 'pickle.load' in code or 'yaml.load(' in code:
|
| 163 |
+
bugs.append({
|
| 164 |
+
"type": "bug", "category": "security", "severity": 5, "line_hint": "eval/exec/pickle line",
|
| 165 |
+
"comment": "Arbitrary code execution: eval/exec/pickle are unsafe with untrusted data.",
|
| 166 |
+
"fix": "Use: json.loads(), ast.literal_eval(), or safe alternatives",
|
| 167 |
+
"confidence": 0.99,
|
| 168 |
+
"languages": ["python", "javascript"]
|
| 169 |
+
})
|
| 170 |
+
|
| 171 |
+
# Hardcoded API keys
|
| 172 |
+
if re.search(r'(api_key|apikey|secret_key|token|bearer)\s*[=:]\s*["\'][a-zA-Z0-9_\-]{8,}["\']', code, re.I):
|
| 173 |
+
bugs.append({
|
| 174 |
+
"type": "bug", "category": "security", "severity": 4, "line_hint": "API key line",
|
| 175 |
+
"comment": "Hardcoded API key/token detected.",
|
| 176 |
+
"fix": "Use environment variables: api_key = os.getenv('API_KEY')",
|
| 177 |
+
"confidence": 0.96,
|
| 178 |
+
"languages": ["python", "javascript", "typescript", "java", "go"]
|
| 179 |
+
})
|
| 180 |
+
|
| 181 |
+
# Mutable default argument (Python)
|
| 182 |
+
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*=\s*\[\]|def\s+\w+\s*\([^)]*=\s*\{\}', code):
|
| 183 |
+
bugs.append({
|
| 184 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": "function definition",
|
| 185 |
+
"comment": "Mutable default argument: List/dict is shared across all function calls.",
|
| 186 |
+
"fix": "Use None as default: def func(lst=None): if lst is None: lst = []",
|
| 187 |
+
"confidence": 0.98,
|
| 188 |
+
"languages": ["python"]
|
| 189 |
+
})
|
| 190 |
+
|
| 191 |
+
# Off-by-one errors
|
| 192 |
+
if re.search(r'range\(len\([^)]+\)\s*-\s*1\)', code):
|
| 193 |
+
bugs.append({
|
| 194 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": "loop range",
|
| 195 |
+
"comment": "Off-by-one error: range(len(x)-1) skips the last element.",
|
| 196 |
+
"fix": "Use range(len(arr)) or enumerate(arr)",
|
| 197 |
+
"confidence": 0.85,
|
| 198 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 199 |
+
})
|
| 200 |
+
|
| 201 |
+
# Division by zero
|
| 202 |
+
if re.search(r'\/\s*0(?![a-zA-Z0-9])', code):
|
| 203 |
+
bugs.append({
|
| 204 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": "division line",
|
| 205 |
+
"comment": "Potential division by zero. Check denominator is non-zero.",
|
| 206 |
+
"fix": "Add check: if denominator != 0: result = numerator / denominator",
|
| 207 |
+
"confidence": 0.99,
|
| 208 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 209 |
+
})
|
| 210 |
+
|
| 211 |
+
return bugs
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
# ============================================================================
|
| 215 |
+
# FRONTEND + HELPER ENDPOINTS
|
| 216 |
+
# ============================================================================
|
| 217 |
+
|
| 218 |
+
@app.get("/")
|
| 219 |
+
def serve_frontend():
|
| 220 |
+
"""Serve the CodeBug frontend UI"""
|
| 221 |
+
html_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates", "index.html")
|
| 222 |
+
try:
|
| 223 |
+
with open(html_path, "r", encoding="utf-8") as f:
|
| 224 |
+
return HTMLResponse(f.read())
|
| 225 |
+
except:
|
| 226 |
+
return HTMLResponse("<h1>CodeBug API is Running.</h1><p>Visit /docs to see available endpoints.</p>")
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@app.get("/api/health")
|
| 230 |
+
async def health_check():
|
| 231 |
+
"""Health check endpoint"""
|
| 232 |
+
return {
|
| 233 |
+
"status": "ok",
|
| 234 |
+
"version": "2.0",
|
| 235 |
+
"supported_languages": ["python", "javascript", "typescript", "java", "go", "cpp"],
|
| 236 |
+
"features": [
|
| 237 |
+
"comprehensive_bug_detection",
|
| 238 |
+
"confidence_scores",
|
| 239 |
+
"multi_language_support",
|
| 240 |
+
"export_json_reports"
|
| 241 |
+
],
|
| 242 |
+
"api_endpoints": [
|
| 243 |
+
"/api/review (POST) - Analyze code",
|
| 244 |
+
"/api/train (POST) - Run training",
|
| 245 |
+
"/api/health (GET) - This endpoint",
|
| 246 |
+
"/api/stats (GET) - Usage statistics"
|
| 247 |
+
]
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
@app.get("/api/stats")
|
| 252 |
+
async def get_stats():
|
| 253 |
+
"""Return usage statistics"""
|
| 254 |
+
return {
|
| 255 |
+
"message": "Stats endpoint - tracks would be stored in session/DB",
|
| 256 |
+
"supported_check_types": 30,
|
| 257 |
+
"languages": 6,
|
| 258 |
+
"security_checks": 12,
|
| 259 |
+
"logic_checks": 8,
|
| 260 |
+
"style_checks": 10
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
# Resource leak
|
| 265 |
+
if re.search(r'open\s*\([^)]+\)\s*(?!with|as)', code) and '.close()' not in code:
|
| 266 |
+
bugs.append({
|
| 267 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 268 |
+
"comment": "Resource leak: File opened without 'with' statement. May not close properly.",
|
| 269 |
+
"fix": "Use: with open(file) as f: ... (automatic close)",
|
| 270 |
+
"confidence": 0.93,
|
| 271 |
+
"languages": ["python"]
|
| 272 |
+
})
|
| 273 |
+
|
| 274 |
+
# Infinite recursion (Python)
|
| 275 |
+
if lang == 'python' and re.search(r'def\s+(\w+).*:\s*.*return\s+\1\s*\(', code, re.DOTALL):
|
| 276 |
+
bugs.append({
|
| 277 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 278 |
+
"comment": "Infinite recursion: Function calls itself without base case.",
|
| 279 |
+
"fix": "Add base case: if condition: return value",
|
| 280 |
+
"confidence": 0.87,
|
| 281 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 282 |
+
})
|
| 283 |
+
|
| 284 |
+
# Bare except (Python)
|
| 285 |
+
if lang == 'python' and re.search(r'except\s*:\s*(?!.*#)', code):
|
| 286 |
+
bugs.append({
|
| 287 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 288 |
+
"comment": "Bare except clause: Catches all exceptions including KeyboardInterrupt.",
|
| 289 |
+
"fix": "Specify exception: except ValueError: or except Exception:",
|
| 290 |
+
"confidence": 0.96,
|
| 291 |
+
"languages": ["python"]
|
| 292 |
+
})
|
| 293 |
+
|
| 294 |
+
# Type errors
|
| 295 |
+
if lang == 'python' and re.search(r'["\'][^"\']*["\'].*\+.*[0-9]|["\'][^"\']*["\'].*\+\s*\w+(?![\"\')])', code):
|
| 296 |
+
bugs.append({
|
| 297 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 298 |
+
"comment": "Type error: Cannot concatenate string with number directly.",
|
| 299 |
+
"fix": "Convert to string: str(value) or use f-string: f'text {value}'",
|
| 300 |
+
"confidence": 0.82,
|
| 301 |
+
"languages": ["python"]
|
| 302 |
+
})
|
| 303 |
+
|
| 304 |
+
# Missing return statement (Python)
|
| 305 |
+
if lang == 'python' and re.search(r'def\s+\w+\s*\([^)]*\):[^}]*\n\s{4,}result\s*=', code) and not re.search(r'return\s+result', code):
|
| 306 |
+
bugs.append({
|
| 307 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 3,
|
| 308 |
+
"comment": "Missing return statement: Function computes value but returns None.",
|
| 309 |
+
"fix": "Add return: return result",
|
| 310 |
+
"confidence": 0.89,
|
| 311 |
+
"languages": ["python"]
|
| 312 |
+
})
|
| 313 |
+
|
| 314 |
+
# Race condition (threading/multiprocessing)
|
| 315 |
+
if re.search(r'threading\.|multiprocessing\.|Thread|Process|concurrent', code, re.I) and not re.search(r'Lock|RLock|Semaphore|Mutex|synchronized', code, re.I):
|
| 316 |
+
bugs.append({
|
| 317 |
+
"type": "bug", "category": "logic", "severity": 3, "line_hint": 2,
|
| 318 |
+
"comment": "Race condition: Multithreaded code without synchronization.",
|
| 319 |
+
"fix": "Use locks: lock = threading.Lock(); with lock: shared_var += 1",
|
| 320 |
+
"confidence": 0.80,
|
| 321 |
+
"languages": ["python", "java", "go", "cpp"]
|
| 322 |
+
})
|
| 323 |
+
|
| 324 |
+
# Inefficient nested loops
|
| 325 |
+
if code.count('for ') >= 2 and ('range(10000)' in code or 'range(1000)' in code):
|
| 326 |
+
bugs.append({
|
| 327 |
+
"type": "bug", "category": "logic", "severity": 2, "line_hint": 2,
|
| 328 |
+
"comment": "Performance issue: Nested loops with large ranges (O(n²) complexity).",
|
| 329 |
+
"fix": "Use set/dict for O(1) lookup or optimize algorithm",
|
| 330 |
+
"confidence": 0.75,
|
| 331 |
+
"languages": ["python", "javascript", "java", "go", "cpp"]
|
| 332 |
+
})
|
| 333 |
+
|
| 334 |
+
# Sort bugs by severity (highest first)
|
| 335 |
+
bugs.sort(key=lambda x: x['severity'], reverse=True)
|
| 336 |
+
|
| 337 |
+
return bugs
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def analyze_code_locally(code: str, lang: str) -> dict:
|
| 341 |
+
"""Pattern-based code analysis - DEPRECATED: Use analyze_code_comprehensively instead"""
|
| 342 |
+
bugs = analyze_code_comprehensively(code, lang)
|
| 343 |
+
if bugs:
|
| 344 |
+
return bugs[0]
|
| 345 |
+
return {
|
| 346 |
+
"type": "approve",
|
| 347 |
+
"category": "style",
|
| 348 |
+
"severity": 1,
|
| 349 |
+
"line_hint": None,
|
| 350 |
+
"comment": "No obvious bugs detected. Code looks clean.",
|
| 351 |
+
"fix": "",
|
| 352 |
+
"confidence": 1.0
|
| 353 |
+
}
|
training_loop.py
CHANGED
|
@@ -1,162 +1,151 @@
|
|
| 1 |
"""
|
| 2 |
-
training_loop.py —
|
| 3 |
|
| 4 |
-
|
| 5 |
-
- Run outputs saved to runs/ (never committed to git)
|
| 6 |
-
- Checkpoint saved after every episode: resumes across runs
|
| 7 |
-
- Config-driven paths
|
| 8 |
"""
|
| 9 |
|
| 10 |
-
from __future__ import annotations
|
| 11 |
-
|
| 12 |
import json
|
| 13 |
import os
|
| 14 |
-
import sys
|
| 15 |
from datetime import datetime
|
| 16 |
-
|
| 17 |
from config import CHECKPOINT_FILE, RUNS_DIR
|
| 18 |
from agent import review
|
| 19 |
-
from environment import CodeReviewEnv
|
| 20 |
|
| 21 |
|
| 22 |
-
#
|
| 23 |
# Checkpoint helpers
|
| 24 |
-
#
|
| 25 |
-
|
| 26 |
|
| 27 |
def _load_checkpoint() -> dict:
|
|
|
|
| 28 |
if os.path.exists(CHECKPOINT_FILE):
|
| 29 |
try:
|
| 30 |
with open(CHECKPOINT_FILE) as f:
|
| 31 |
return json.load(f)
|
| 32 |
except Exception:
|
| 33 |
pass
|
| 34 |
-
return {"total_reward": 0, "episodes_run": 0, "history": []}
|
| 35 |
|
| 36 |
|
| 37 |
def _save_checkpoint(data: dict) -> None:
|
|
|
|
| 38 |
os.makedirs(RUNS_DIR, exist_ok=True)
|
| 39 |
with open(CHECKPOINT_FILE, "w") as f:
|
| 40 |
json.dump(data, f, indent=2)
|
| 41 |
|
| 42 |
|
| 43 |
-
# ---------------------------------------------------------------------------
|
| 44 |
-
# Training
|
| 45 |
-
# ---------------------------------------------------------------------------
|
| 46 |
-
|
| 47 |
-
|
| 48 |
def run_training(num_episodes: int = 5, verbose: bool = True, resume: bool = True) -> dict:
|
| 49 |
"""
|
| 50 |
-
Run
|
| 51 |
-
|
| 52 |
Args:
|
| 53 |
-
num_episodes: How many episodes to run
|
| 54 |
-
verbose:
|
| 55 |
-
resume:
|
|
|
|
|
|
|
|
|
|
| 56 |
"""
|
| 57 |
-
checkpoint = _load_checkpoint() if resume else {"total_reward": 0, "episodes_run": 0, "history": []}
|
| 58 |
-
|
| 59 |
-
if resume and checkpoint["episodes_run"] > 0:
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
start_ep = checkpoint["episodes_run"]
|
| 68 |
-
|
| 69 |
if verbose:
|
| 70 |
print(f"--- Training Loop: {num_episodes} episodes (starting at ep {start_ep + 1}) ---")
|
| 71 |
-
|
| 72 |
for i in range(1, num_episodes + 1):
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
total_reward += reward
|
| 78 |
-
|
|
|
|
| 79 |
record = {
|
| 80 |
-
"
|
| 81 |
-
"
|
| 82 |
-
"
|
| 83 |
-
"reward":
|
| 84 |
-
"
|
| 85 |
-
"
|
| 86 |
-
"
|
| 87 |
-
"breakdown": info["breakdown"],
|
| 88 |
-
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 89 |
}
|
| 90 |
history.append(record)
|
| 91 |
-
|
| 92 |
-
# Save checkpoint
|
| 93 |
_save_checkpoint({
|
| 94 |
"total_reward": total_reward,
|
| 95 |
"episodes_run": start_ep + i,
|
| 96 |
-
"history":
|
| 97 |
})
|
| 98 |
-
|
| 99 |
if verbose:
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
# Save
|
| 111 |
os.makedirs(RUNS_DIR, exist_ok=True)
|
| 112 |
-
ts
|
| 113 |
run_file = os.path.join(RUNS_DIR, f"run_{ts}.json")
|
| 114 |
with open(run_file, "w") as f:
|
| 115 |
-
json.dump(
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
return output_data
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
def analyze_history() -> None:
|
| 128 |
-
"""Print a summary from the latest checkpoint."""
|
| 129 |
-
checkpoint = _load_checkpoint()
|
| 130 |
-
if not checkpoint["history"]:
|
| 131 |
-
print("No checkpoint found. Run training first.")
|
| 132 |
-
return
|
| 133 |
-
|
| 134 |
-
stats = checkpoint
|
| 135 |
-
history = checkpoint["history"]
|
| 136 |
-
|
| 137 |
-
print("\n--- PERFORMANCE ANALYSIS ---")
|
| 138 |
-
print(f"Episodes run: {stats['episodes_run']}")
|
| 139 |
-
print(f"Total reward: {stats['total_reward']}")
|
| 140 |
-
|
| 141 |
-
correct = sum(1 for h in history if h["correct"])
|
| 142 |
-
if history:
|
| 143 |
-
print(f"Accuracy: {correct / len(history) * 100:.1f}%")
|
| 144 |
-
print(f"Best reward: {max(h['reward'] for h in history)}")
|
| 145 |
-
print(f"Worst reward: {min(h['reward'] for h in history)}")
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
# ---------------------------------------------------------------------------
|
| 149 |
-
# CLI entry point
|
| 150 |
-
# ---------------------------------------------------------------------------
|
| 151 |
-
|
| 152 |
-
if __name__ == "__main__":
|
| 153 |
-
mode = sys.argv[1] if len(sys.argv) > 1 else "default"
|
| 154 |
|
| 155 |
-
if mode == "short":
|
| 156 |
-
run_training(num_episodes=10)
|
| 157 |
-
elif mode == "analyze":
|
| 158 |
-
analyze_history()
|
| 159 |
-
elif mode == "fresh":
|
| 160 |
-
run_training(num_episodes=5, resume=False)
|
| 161 |
-
else:
|
| 162 |
-
run_training(num_episodes=5)
|
|
|
|
| 1 |
"""
|
| 2 |
+
training_loop.py — RL training loop for CodeBug agent.
|
| 3 |
|
| 4 |
+
This simplified version trains the agent on code review tasks.
|
|
|
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
|
|
|
|
|
|
|
| 7 |
import json
|
| 8 |
import os
|
|
|
|
| 9 |
from datetime import datetime
|
|
|
|
| 10 |
from config import CHECKPOINT_FILE, RUNS_DIR
|
| 11 |
from agent import review
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
+
# =========================================================================
|
| 15 |
# Checkpoint helpers
|
| 16 |
+
# =========================================================================
|
|
|
|
| 17 |
|
| 18 |
def _load_checkpoint() -> dict:
|
| 19 |
+
"""Load checkpoint from disk if it exists"""
|
| 20 |
if os.path.exists(CHECKPOINT_FILE):
|
| 21 |
try:
|
| 22 |
with open(CHECKPOINT_FILE) as f:
|
| 23 |
return json.load(f)
|
| 24 |
except Exception:
|
| 25 |
pass
|
| 26 |
+
return {"total_reward": 0.0, "episodes_run": 0, "history": []}
|
| 27 |
|
| 28 |
|
| 29 |
def _save_checkpoint(data: dict) -> None:
|
| 30 |
+
"""Save checkpoint to disk"""
|
| 31 |
os.makedirs(RUNS_DIR, exist_ok=True)
|
| 32 |
with open(CHECKPOINT_FILE, "w") as f:
|
| 33 |
json.dump(data, f, indent=2)
|
| 34 |
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
def run_training(num_episodes: int = 5, verbose: bool = True, resume: bool = True) -> dict:
|
| 37 |
"""
|
| 38 |
+
Run simplified training loop for the agent.
|
| 39 |
+
|
| 40 |
Args:
|
| 41 |
+
num_episodes: How many episodes to run
|
| 42 |
+
verbose: Print progress
|
| 43 |
+
resume: Load checkpoint and resume
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
Dictionary with training stats
|
| 47 |
"""
|
| 48 |
+
checkpoint = _load_checkpoint() if resume else {"total_reward": 0.0, "episodes_run": 0, "history": []}
|
| 49 |
+
|
| 50 |
+
if resume and checkpoint["episodes_run"] > 0 and verbose:
|
| 51 |
+
print(f"Resuming from checkpoint: {checkpoint['episodes_run']} episodes already run.")
|
| 52 |
+
|
| 53 |
+
# Training examples (code snippets with ground truth)
|
| 54 |
+
training_snippets = [
|
| 55 |
+
{
|
| 56 |
+
"code": 'def get_user(uid):\n q = f"SELECT * FROM users WHERE id={uid}"\n cursor.execute(q)',
|
| 57 |
+
"truth": {"category": "security", "severity": 5}
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"code": 'def find_max(nums):\n for i in range(len(nums) - 1):\n if nums[i] > mx: mx = nums[i]',
|
| 61 |
+
"truth": {"category": "logic", "severity": 3}
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"code": 'password = "admin123"\ndb.save_user(user, password)',
|
| 65 |
+
"truth": {"category": "security", "severity": 5}
|
| 66 |
+
},
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
history = checkpoint["history"]
|
| 70 |
+
total_reward = checkpoint["total_reward"]
|
| 71 |
start_ep = checkpoint["episodes_run"]
|
| 72 |
+
|
| 73 |
if verbose:
|
| 74 |
print(f"--- Training Loop: {num_episodes} episodes (starting at ep {start_ep + 1}) ---")
|
| 75 |
+
|
| 76 |
for i in range(1, num_episodes + 1):
|
| 77 |
+
# Pick a random snippet
|
| 78 |
+
snippet = training_snippets[(start_ep + i) % len(training_snippets)]
|
| 79 |
+
code = snippet["code"]
|
| 80 |
+
truth = snippet["truth"]
|
| 81 |
+
|
| 82 |
+
# Get AI review
|
| 83 |
+
try:
|
| 84 |
+
ai_bugs = review(code)
|
| 85 |
+
if not ai_bugs:
|
| 86 |
+
ai_bugs = []
|
| 87 |
+
|
| 88 |
+
# Simple scoring: did the agent detect a bug?
|
| 89 |
+
detected_bug = len(ai_bugs) > 0
|
| 90 |
+
reward = 1.0 if detected_bug else 0.0
|
| 91 |
+
|
| 92 |
+
# Check if it matches category
|
| 93 |
+
if ai_bugs and ai_bugs[0].get("category") == truth["category"]:
|
| 94 |
+
reward += 0.5
|
| 95 |
+
# Check severity
|
| 96 |
+
if ai_bugs and ai_bugs[0].get("severity") == truth["severity"]:
|
| 97 |
+
reward += 0.5
|
| 98 |
+
|
| 99 |
+
except Exception as e:
|
| 100 |
+
if verbose:
|
| 101 |
+
print(f" Warning: Agent failed on episode {i}: {e}")
|
| 102 |
+
ai_bugs = []
|
| 103 |
+
reward = 0.0
|
| 104 |
+
|
| 105 |
total_reward += reward
|
| 106 |
+
|
| 107 |
+
# Save record
|
| 108 |
record = {
|
| 109 |
+
"episode": start_ep + i,
|
| 110 |
+
"code_length": len(code),
|
| 111 |
+
"bugs_detected": len(ai_bugs),
|
| 112 |
+
"reward": reward,
|
| 113 |
+
"truth_category": truth["category"],
|
| 114 |
+
"truth_severity": truth["severity"],
|
| 115 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
|
|
|
|
|
|
| 116 |
}
|
| 117 |
history.append(record)
|
| 118 |
+
|
| 119 |
+
# Save checkpoint
|
| 120 |
_save_checkpoint({
|
| 121 |
"total_reward": total_reward,
|
| 122 |
"episodes_run": start_ep + i,
|
| 123 |
+
"history": history,
|
| 124 |
})
|
| 125 |
+
|
| 126 |
if verbose:
|
| 127 |
+
print(f"Ep {start_ep + i:02d} | Bugs: {len(ai_bugs):1d} | Reward: {reward:.1f} | Cumulative: {total_reward:.1f}")
|
| 128 |
+
|
| 129 |
+
if verbose:
|
| 130 |
+
print(f"\n--- Training Complete ---")
|
| 131 |
+
print(f"Total Episodes: {len(history)}")
|
| 132 |
+
print(f"Total Reward: {total_reward:.1f}")
|
| 133 |
+
if history:
|
| 134 |
+
avg_reward = total_reward / len(history)
|
| 135 |
+
print(f"Average Reward: {avg_reward:.2f}")
|
| 136 |
+
|
| 137 |
+
# Save run file
|
| 138 |
os.makedirs(RUNS_DIR, exist_ok=True)
|
| 139 |
+
ts = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
|
| 140 |
run_file = os.path.join(RUNS_DIR, f"run_{ts}.json")
|
| 141 |
with open(run_file, "w") as f:
|
| 142 |
+
json.dump({"history": history, "total_reward": total_reward}, f, indent=2)
|
| 143 |
+
|
| 144 |
+
return {
|
| 145 |
+
"episodes_completed": num_episodes,
|
| 146 |
+
"total_reward": float(total_reward),
|
| 147 |
+
"average_reward": float(total_reward / num_episodes) if num_episodes > 0 else 0.0,
|
| 148 |
+
"history_length": len(history),
|
| 149 |
+
"checkpoint_file": CHECKPOINT_FILE
|
| 150 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|