Spaces:
Sleeping
fix: address 25 code quality issues from audit
Browse files- .gitignore: add output files (agent_output, grade_output, output.txt),
.venv, editor dirs (.cursor, .claude, .islstudio), runs/ folder
- config.py: centralise all constants (model names, reward values,
rate limits, file paths, token limits)
- agent.py: startup API-key validation with clear exit message;
log exceptions from both providers (no more silent swallowing);
system/user message separation for cleaner role context;
3 few-shot examples for reliable JSON compliance;
one automatic JSON-retry on malformed response
- grader.py: +5 reward for correctly approving clean code;
+5 partial credit when right decision but wrong category;
all reward constants wired from config.py; type annotations
- environment.py: shuffled-queue deduplication (exhausts all
episodes before cycling); config-driven paths; type annotations
- training_loop.py: checkpoint saved after every episode (resumable);
all outputs written to runs/ (timestamped); config-driven paths
- app.py: flask-limiter on /review, /upload, /review-text (20/min),
/auto-run (5/min); Retry-After header on 429; history moved to
runs/history.json; bare except replaced with logged exception
- requirements.txt: fully pinned via pip freeze
- git: untrack agent_output.txt, grade_output.txt, output.txt
- .gitignore +39 -1
- .vibecheck/last-score.json +1 -1
- agent.py +293 -173
- agent_output.txt +0 -29
- app.py +41 -14
- config.py +62 -0
- environment.py +120 -103
- grade_output.txt +0 -133
- grader.py +238 -163
- output.txt +0 -0
- requirements.txt +15 -3
- training_loop.py +132 -71
|
@@ -1,7 +1,45 @@
|
|
|
|
|
| 1 |
__pycache__/
|
| 2 |
*.pyc
|
| 3 |
*.pyo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
.env
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
history.json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
.vercel
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
__pycache__/
|
| 3 |
*.pyc
|
| 4 |
*.pyo
|
| 5 |
+
*.pyd
|
| 6 |
+
.Python
|
| 7 |
+
*.egg-info/
|
| 8 |
+
dist/
|
| 9 |
+
build/
|
| 10 |
+
|
| 11 |
+
# Virtual environments
|
| 12 |
+
.venv/
|
| 13 |
+
venv/
|
| 14 |
+
env/
|
| 15 |
+
|
| 16 |
+
# Environment / secrets
|
| 17 |
.env
|
| 18 |
+
.env.*
|
| 19 |
+
*.env
|
| 20 |
+
|
| 21 |
+
# Run outputs — stored in runs/ locally, never committed
|
| 22 |
+
runs/
|
| 23 |
+
agent_output.txt
|
| 24 |
+
grade_output.txt
|
| 25 |
+
output.txt
|
| 26 |
history.json
|
| 27 |
+
|
| 28 |
+
# IDE / editor
|
| 29 |
+
.vscode/
|
| 30 |
+
.idea/
|
| 31 |
+
*.iml
|
| 32 |
+
.cursor/
|
| 33 |
+
.claude/
|
| 34 |
+
.islstudio/
|
| 35 |
+
.vibecheck/
|
| 36 |
+
|
| 37 |
+
# Vercel
|
| 38 |
.vercel
|
| 39 |
+
|
| 40 |
+
# Backups
|
| 41 |
+
*.json.bak
|
| 42 |
+
|
| 43 |
+
# OS
|
| 44 |
+
.DS_Store
|
| 45 |
+
Thumbs.db
|
|
@@ -6,5 +6,5 @@
|
|
| 6 |
"runtimeProof": 0,
|
| 7 |
"contracts": 0,
|
| 8 |
"mockData": 0,
|
| 9 |
-
"lastUpdated": "2026-04-
|
| 10 |
}
|
|
|
|
| 6 |
"runtimeProof": 0,
|
| 7 |
"contracts": 0,
|
| 8 |
"mockData": 0,
|
| 9 |
+
"lastUpdated": "2026-04-07T22:05:27.724Z"
|
| 10 |
}
|
|
@@ -1,217 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
-
import
|
| 3 |
import os
|
| 4 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
bugs and vulnerabilities in Python code.
|
| 11 |
|
| 12 |
-
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
SECURITY (severity 4-5):
|
| 15 |
-
- SQL
|
| 16 |
-
|
| 17 |
-
-
|
| 18 |
-
|
| 19 |
-
-
|
| 20 |
-
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
- range(len(x) - 1) instead of range(len(x)) → off-by-one, skips last item
|
| 24 |
-
- Using > instead of >= or < instead of <= in comparisons
|
| 25 |
-
- Division without checking for zero first
|
| 26 |
-
- Functions that never return a value in all code paths
|
| 27 |
-
|
| 28 |
-
INSTRUCTIONS:
|
| 29 |
-
- Be aggressive — if you see any of the above patterns, FLAG it
|
| 30 |
-
- Do not approve code that contains these patterns
|
| 31 |
-
- For plain text passwords: if you see a variable assigned directly
|
| 32 |
-
to another variable called 'password' or 'hashed' without calling
|
| 33 |
-
any hash function, that IS a bug
|
| 34 |
-
- Respond ONLY with valid JSON, no markdown, no explanation
|
| 35 |
-
|
| 36 |
-
JSON format:
|
| 37 |
-
{{
|
| 38 |
-
"type": "flag" or "approve",
|
| 39 |
-
"category": "security" or "logic" or "style" or "ok",
|
| 40 |
-
"line_hint": "specific line description",
|
| 41 |
-
"comment": "clear explanation of the vulnerability",
|
| 42 |
-
"severity": 1-5
|
| 43 |
-
}}
|
| 44 |
-
|
| 45 |
-
Code to review:
|
| 46 |
-
{code}
|
| 47 |
"""
|
| 48 |
-
return prompt.strip()
|
| 49 |
|
| 50 |
-
|
| 51 |
-
"
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
try:
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
]
|
| 76 |
-
)
|
| 77 |
-
return response.choices[0].message.content
|
| 78 |
-
except Exception:
|
| 79 |
-
pass
|
| 80 |
-
|
| 81 |
-
# Return indicator for mock fallback
|
| 82 |
return None
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
code_lower = code.lower()
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
| 90 |
return {
|
| 91 |
"type": "flag",
|
| 92 |
"category": "security",
|
| 93 |
"line_hint": "password assignment line",
|
| 94 |
-
"comment": "Password assigned without hashing — plain
|
| 95 |
-
"severity": 5
|
| 96 |
}
|
| 97 |
-
|
| 98 |
-
# 2. SQL Injection
|
| 99 |
if 'f"select' in code_lower or "f'select" in code_lower:
|
| 100 |
return {
|
| 101 |
"type": "flag",
|
| 102 |
"category": "security",
|
| 103 |
"line_hint": "database query line",
|
| 104 |
-
"comment": "Vulnerable SQL query
|
| 105 |
-
"severity": 5
|
| 106 |
}
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
if 'range(len(' in code_lower:
|
| 110 |
return {
|
| 111 |
"type": "flag",
|
| 112 |
"category": "logic",
|
| 113 |
-
"line_hint": "loop range
|
| 114 |
-
"comment": "
|
| 115 |
-
"severity": 3
|
| 116 |
}
|
| 117 |
|
| 118 |
-
|
| 119 |
-
if ('> amount' in code_lower or '< amount' in code_lower) and '>=' not in code_lower and '<=' not in code_lower:
|
| 120 |
return {
|
| 121 |
"type": "flag",
|
| 122 |
"category": "logic",
|
| 123 |
"line_hint": "comparison check",
|
| 124 |
-
"comment": "Strict
|
| 125 |
-
"severity": 4
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
-
# 5. General password check
|
| 129 |
-
if 'password' in code_lower and 'hash' not in code_lower:
|
| 130 |
-
return {
|
| 131 |
-
"type": "flag",
|
| 132 |
-
"category": "security",
|
| 133 |
-
"line_hint": "password handling",
|
| 134 |
-
"comment": "Sensitive password data handled in plain text without cryptographic hashing.",
|
| 135 |
-
"severity": 5
|
| 136 |
}
|
| 137 |
-
|
| 138 |
-
# Default: Approve
|
| 139 |
return {
|
| 140 |
"type": "approve",
|
| 141 |
"category": "ok",
|
| 142 |
"line_hint": "",
|
| 143 |
"comment": "",
|
| 144 |
-
"severity": 0
|
| 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 |
if __name__ == "__main__":
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
test2 = """def find_max(numbers):
|
| 194 |
-
max_val = numbers[0]
|
| 195 |
-
for i in range(len(numbers) - 1):
|
| 196 |
-
if numbers[i] > max_val:
|
| 197 |
-
max_val = numbers[i]
|
| 198 |
-
return max_val"""
|
| 199 |
-
|
| 200 |
-
test3 = """def save_user(username, password, db):
|
| 201 |
-
db.insert('users', {'username': username, 'password': password})"""
|
| 202 |
-
|
| 203 |
-
tests = [
|
| 204 |
-
("Login Function (SQLi)", test1),
|
| 205 |
-
("Find Max (Off-by-one)", test2),
|
| 206 |
-
("Save User (Plain Pass)", test3)
|
| 207 |
]
|
| 208 |
-
|
| 209 |
-
print("
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
print(f"TEST: {name}")
|
| 213 |
-
# To make results predictable for this specific run, we could mock random
|
| 214 |
-
# but let's just let it run.
|
| 215 |
result = review(code)
|
| 216 |
-
print(
|
| 217 |
-
print(
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
agent.py — LLM-powered code reviewer with structured JSON output.
|
| 3 |
+
|
| 4 |
+
Key improvements:
|
| 5 |
+
- API key validated at import time with a clear startup message
|
| 6 |
+
- Exceptions are logged (never silently swallowed)
|
| 7 |
+
- System prompt carries persona + schema; user turn carries only the code
|
| 8 |
+
- Two few-shot examples are included for reliable JSON compliance
|
| 9 |
+
- One automatic retry when the first response is malformed JSON
|
| 10 |
+
- Model / token constants come from config.py
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
import json
|
| 14 |
+
import logging
|
| 15 |
import os
|
| 16 |
import re
|
| 17 |
+
import sys
|
| 18 |
+
|
| 19 |
+
from config import (
|
| 20 |
+
ANTHROPIC_MODEL,
|
| 21 |
+
OPENAI_MODEL,
|
| 22 |
+
MAX_TOKENS,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
# Logging
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
|
| 29 |
+
logging.basicConfig(
|
| 30 |
+
level=logging.INFO,
|
| 31 |
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
| 32 |
+
)
|
| 33 |
+
logger = logging.getLogger(__name__)
|
| 34 |
+
|
| 35 |
+
# ---------------------------------------------------------------------------
|
| 36 |
+
# Startup: API-key validation
|
| 37 |
+
# ---------------------------------------------------------------------------
|
| 38 |
+
|
| 39 |
+
def _check_api_keys() -> None:
|
| 40 |
+
"""
|
| 41 |
+
Called once at module load. Exits with a clear message if no usable
|
| 42 |
+
API key is present, rather than letting the server start and then die
|
| 43 |
+
mid-request with a cryptic SDK error.
|
| 44 |
+
"""
|
| 45 |
+
has_anthropic = bool(os.environ.get("ANTHROPIC_API_KEY", "").strip())
|
| 46 |
+
has_openai = bool(os.environ.get("OPENAI_API_KEY", "").strip())
|
| 47 |
+
|
| 48 |
+
if not has_anthropic and not has_openai:
|
| 49 |
+
print(
|
| 50 |
+
"\n"
|
| 51 |
+
"╔══════════════════════════════════════════════════════════╗\n"
|
| 52 |
+
"║ ERROR: No LLM API key found. ║\n"
|
| 53 |
+
"║ ║\n"
|
| 54 |
+
"║ Set at least one of: ║\n"
|
| 55 |
+
"║ ANTHROPIC_API_KEY (preferred — uses Claude Haiku) ║\n"
|
| 56 |
+
"║ OPENAI_API_KEY (fallback — uses GPT-4o-mini) ║\n"
|
| 57 |
+
"║ ║\n"
|
| 58 |
+
"║ Example (PowerShell): ║\n"
|
| 59 |
+
"║ $env:ANTHROPIC_API_KEY = 'sk-ant-...' ║\n"
|
| 60 |
+
"║ ║\n"
|
| 61 |
+
"║ The server will NOT start without a key. ║\n"
|
| 62 |
+
"╚══════════════════════════════════════════════════════════╝\n",
|
| 63 |
+
file=sys.stderr,
|
| 64 |
+
)
|
| 65 |
+
sys.exit(1)
|
| 66 |
+
|
| 67 |
+
if has_anthropic:
|
| 68 |
+
logger.info("API key found: Anthropic (primary)")
|
| 69 |
+
if has_openai:
|
| 70 |
+
logger.info("API key found: OpenAI (fallback)")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
_check_api_keys()
|
| 74 |
+
|
| 75 |
+
# ---------------------------------------------------------------------------
|
| 76 |
+
# Prompt construction
|
| 77 |
+
# ---------------------------------------------------------------------------
|
| 78 |
+
|
| 79 |
+
_SYSTEM_PROMPT = """\
|
| 80 |
+
You are an expert security-focused code reviewer.
|
| 81 |
+
Your ONLY job is to return a single valid JSON object — no markdown, no prose.
|
| 82 |
+
|
| 83 |
+
JSON schema (all fields required):
|
| 84 |
+
{
|
| 85 |
+
"type": "flag" | "approve",
|
| 86 |
+
"category": "security" | "logic" | "style" | "ok",
|
| 87 |
+
"line_hint": "<brief description of the suspicious line>",
|
| 88 |
+
"comment": "<clear explanation of the issue, or empty string>",
|
| 89 |
+
"severity": 1-5
|
| 90 |
+
}
|
| 91 |
|
| 92 |
+
Rules:
|
| 93 |
+
- "type" = "flag" when a bug or vulnerability is present
|
| 94 |
+
- "type" = "approve" when the code is clean (category = "ok", severity = 0)
|
| 95 |
+
- category must match the dominant bug class
|
|
|
|
| 96 |
|
| 97 |
+
--- FEW-SHOT EXAMPLES ---
|
| 98 |
|
| 99 |
+
Example 1 — SQL injection (flag):
|
| 100 |
+
Code:
|
| 101 |
+
query = f"SELECT * FROM users WHERE name='{username}'"
|
| 102 |
+
result = db.execute(query)
|
| 103 |
+
|
| 104 |
+
Response:
|
| 105 |
+
{"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}
|
| 106 |
+
|
| 107 |
+
Example 2 — clean code (approve):
|
| 108 |
+
Code:
|
| 109 |
+
def add(a: int, b: int) -> int:
|
| 110 |
+
return a + b
|
| 111 |
+
|
| 112 |
+
Response:
|
| 113 |
+
{"type":"approve","category":"ok","line_hint":"","comment":"","severity":0}
|
| 114 |
+
|
| 115 |
+
Example 3 — off-by-one (flag):
|
| 116 |
+
Code:
|
| 117 |
+
for i in range(len(items) - 1):
|
| 118 |
+
process(items[i])
|
| 119 |
+
|
| 120 |
+
Response:
|
| 121 |
+
{"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}
|
| 122 |
+
--- END EXAMPLES ---
|
| 123 |
+
|
| 124 |
+
ALWAYS look for:
|
| 125 |
SECURITY (severity 4-5):
|
| 126 |
+
- SQL built with f-strings / concatenation
|
| 127 |
+
- Passwords stored/passed without hashing
|
| 128 |
+
- Hardcoded secrets, API keys, or tokens
|
| 129 |
+
LOGIC (severity 2-4):
|
| 130 |
+
- range(len(x) - 1) off-by-one
|
| 131 |
+
- Strict > / < where >= / <= is needed
|
| 132 |
+
- Division without zero-check
|
| 133 |
+
- Missing return in all code paths
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
"""
|
|
|
|
| 135 |
|
| 136 |
+
_RETRY_SUFFIX = (
|
| 137 |
+
"\n\nYour previous response was not valid JSON. "
|
| 138 |
+
"Return ONLY the JSON object with the exact schema above — "
|
| 139 |
+
"no markdown fences, no extra keys, no prose."
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def build_user_message(code: str, retry: bool = False) -> str:
|
| 144 |
+
"""Return the user-turn content (code only, plus retry note if needed)."""
|
| 145 |
+
msg = f"Review this code:\n\n{code}"
|
| 146 |
+
if retry:
|
| 147 |
+
msg += _RETRY_SUFFIX
|
| 148 |
+
return msg
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# ---------------------------------------------------------------------------
|
| 152 |
+
# LLM call
|
| 153 |
+
# ---------------------------------------------------------------------------
|
| 154 |
+
|
| 155 |
+
def call_llm(prompt: str, *, system: str | None = None) -> str | None:
|
| 156 |
+
"""
|
| 157 |
+
Try Anthropic first, then OpenAI. Returns the raw text response or None.
|
| 158 |
+
Exceptions are always logged — never silently swallowed.
|
| 159 |
+
"""
|
| 160 |
+
# --- Anthropic ---
|
| 161 |
+
anthropic_key = os.environ.get("ANTHROPIC_API_KEY", "").strip()
|
| 162 |
+
if anthropic_key:
|
| 163 |
+
try:
|
| 164 |
+
import anthropic
|
| 165 |
+
client = anthropic.Anthropic(api_key=anthropic_key)
|
| 166 |
+
kwargs: dict = {
|
| 167 |
+
"model": ANTHROPIC_MODEL,
|
| 168 |
+
"max_tokens": MAX_TOKENS,
|
| 169 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 170 |
+
}
|
| 171 |
+
if system:
|
| 172 |
+
kwargs["system"] = system
|
| 173 |
+
message = client.messages.create(**kwargs)
|
| 174 |
+
return message.content[0].text
|
| 175 |
+
except Exception as exc:
|
| 176 |
+
logger.error("Anthropic call failed: %s: %s", type(exc).__name__, exc)
|
| 177 |
+
|
| 178 |
+
# --- OpenAI fallback ---
|
| 179 |
+
openai_key = os.environ.get("OPENAI_API_KEY", "").strip()
|
| 180 |
+
if openai_key:
|
| 181 |
+
try:
|
| 182 |
+
import openai
|
| 183 |
+
client = openai.OpenAI(api_key=openai_key)
|
| 184 |
+
messages = []
|
| 185 |
+
if system:
|
| 186 |
+
messages.append({"role": "system", "content": system})
|
| 187 |
+
messages.append({"role": "user", "content": prompt})
|
| 188 |
+
response = client.chat.completions.create(
|
| 189 |
+
model=OPENAI_MODEL,
|
| 190 |
+
max_tokens=MAX_TOKENS,
|
| 191 |
+
messages=messages,
|
| 192 |
+
)
|
| 193 |
+
return response.choices[0].message.content
|
| 194 |
+
except Exception as exc:
|
| 195 |
+
logger.error("OpenAI call failed: %s: %s", type(exc).__name__, exc)
|
| 196 |
+
|
| 197 |
+
logger.warning("All LLM providers failed — falling back to mock reviewer.")
|
| 198 |
+
return None
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# ---------------------------------------------------------------------------
|
| 202 |
+
# JSON parsing helper
|
| 203 |
+
# ---------------------------------------------------------------------------
|
| 204 |
+
|
| 205 |
+
def _parse_json(raw: str) -> dict | None:
|
| 206 |
+
"""Try direct parse, then regex-extracted substring."""
|
| 207 |
+
if not raw:
|
| 208 |
+
return None
|
| 209 |
try:
|
| 210 |
+
return json.loads(raw)
|
| 211 |
+
except json.JSONDecodeError:
|
| 212 |
+
match = re.search(r"(\{.*\})", raw, re.DOTALL)
|
| 213 |
+
if match:
|
| 214 |
+
try:
|
| 215 |
+
return json.loads(match.group(1))
|
| 216 |
+
except json.JSONDecodeError:
|
| 217 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
return None
|
| 219 |
|
| 220 |
+
|
| 221 |
+
# ---------------------------------------------------------------------------
|
| 222 |
+
# Mock reviewer (last-resort fallback)
|
| 223 |
+
# ---------------------------------------------------------------------------
|
| 224 |
+
|
| 225 |
+
def mock_review(code: str) -> dict:
|
| 226 |
+
"""
|
| 227 |
+
Rule-based fallback used only when both LLM providers are unavailable.
|
| 228 |
+
Checks for well-known patterns; deliberately conservative to avoid
|
| 229 |
+
false confidence.
|
| 230 |
+
"""
|
| 231 |
code_lower = code.lower()
|
| 232 |
+
|
| 233 |
+
if "hashed = password" in code_lower or (
|
| 234 |
+
"password" in code_lower and "hash" not in code_lower and "bcrypt" not in code_lower
|
| 235 |
+
):
|
| 236 |
return {
|
| 237 |
"type": "flag",
|
| 238 |
"category": "security",
|
| 239 |
"line_hint": "password assignment line",
|
| 240 |
+
"comment": "Password assigned without hashing — plain-text storage vulnerability.",
|
| 241 |
+
"severity": 5,
|
| 242 |
}
|
| 243 |
+
|
|
|
|
| 244 |
if 'f"select' in code_lower or "f'select" in code_lower:
|
| 245 |
return {
|
| 246 |
"type": "flag",
|
| 247 |
"category": "security",
|
| 248 |
"line_hint": "database query line",
|
| 249 |
+
"comment": "Vulnerable SQL query: f-string interpolation allows SQL injection.",
|
| 250 |
+
"severity": 5,
|
| 251 |
}
|
| 252 |
+
|
| 253 |
+
if "range(len(" in code_lower:
|
|
|
|
| 254 |
return {
|
| 255 |
"type": "flag",
|
| 256 |
"category": "logic",
|
| 257 |
+
"line_hint": "loop range call",
|
| 258 |
+
"comment": "range(len(x)) pattern detected — verify for off-by-one errors.",
|
| 259 |
+
"severity": 3,
|
| 260 |
}
|
| 261 |
|
| 262 |
+
if ("> amount" in code_lower or "< amount" in code_lower) and ">=" not in code_lower and "<=" not in code_lower:
|
|
|
|
| 263 |
return {
|
| 264 |
"type": "flag",
|
| 265 |
"category": "logic",
|
| 266 |
"line_hint": "comparison check",
|
| 267 |
+
"comment": "Strict > / < in balance check; may miss the equality edge case.",
|
| 268 |
+
"severity": 4,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
}
|
| 270 |
+
|
|
|
|
| 271 |
return {
|
| 272 |
"type": "approve",
|
| 273 |
"category": "ok",
|
| 274 |
"line_hint": "",
|
| 275 |
"comment": "",
|
| 276 |
+
"severity": 0,
|
| 277 |
}
|
| 278 |
|
| 279 |
+
|
| 280 |
+
# ---------------------------------------------------------------------------
|
| 281 |
+
# Main entry point
|
| 282 |
+
# ---------------------------------------------------------------------------
|
| 283 |
+
|
| 284 |
+
_REQUIRED_KEYS = {"type", "category", "line_hint", "comment", "severity"}
|
| 285 |
+
_DEFAULTS = {"type": "approve", "category": "ok", "line_hint": "", "comment": "", "severity": 0}
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def review(code: str) -> dict:
|
| 289 |
+
"""
|
| 290 |
+
Review a code snippet.
|
| 291 |
+
|
| 292 |
+
Flow:
|
| 293 |
+
1. Call LLM with system prompt + user message.
|
| 294 |
+
2. If JSON is malformed, retry once with an explicit correction hint.
|
| 295 |
+
3. If both attempts fail, fall back to the rule-based mock reviewer.
|
| 296 |
+
4. Fill any missing keys with safe defaults.
|
| 297 |
+
"""
|
| 298 |
+
user_msg = build_user_message(code)
|
| 299 |
+
raw = call_llm(user_msg, system=_SYSTEM_PROMPT)
|
| 300 |
+
result = _parse_json(raw)
|
| 301 |
+
|
| 302 |
+
if result is None:
|
| 303 |
+
# One retry: tell the model its output was invalid
|
| 304 |
+
logger.warning("LLM returned malformed JSON — retrying with correction hint.")
|
| 305 |
+
user_msg_retry = build_user_message(code, retry=True)
|
| 306 |
+
raw_retry = call_llm(user_msg_retry, system=_SYSTEM_PROMPT)
|
| 307 |
+
result = _parse_json(raw_retry)
|
| 308 |
+
|
| 309 |
+
if result is None:
|
| 310 |
+
logger.warning("Retry also failed — using mock reviewer.")
|
| 311 |
+
result = mock_review(code)
|
| 312 |
+
|
| 313 |
+
# Fill missing keys with safe defaults
|
| 314 |
+
for key, val in _DEFAULTS.items():
|
| 315 |
+
result.setdefault(key, val)
|
| 316 |
+
|
| 317 |
+
return result
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
# ---------------------------------------------------------------------------
|
| 321 |
+
# Test block (run with: python agent.py)
|
| 322 |
+
# ---------------------------------------------------------------------------
|
| 323 |
+
|
| 324 |
if __name__ == "__main__":
|
| 325 |
+
_TESTS = [
|
| 326 |
+
("SQL injection", "def login(u, p, db):\n q = f\"SELECT * FROM users WHERE username='{u}'\"\n return db.execute(q)"),
|
| 327 |
+
("Off-by-one", "def find_max(nums):\n mx = nums[0]\n for i in range(len(nums) - 1):\n if nums[i] > mx: mx = nums[i]\n return mx"),
|
| 328 |
+
("Plain password", "def save(u, pw, db):\n db.insert('users', {'username': u, 'password': pw})"),
|
| 329 |
+
("Clean code", "def add(a: int, b: int) -> int:\n return a + b"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
]
|
| 331 |
+
|
| 332 |
+
print("=== Agent Tests ===\n")
|
| 333 |
+
for name, code in _TESTS:
|
| 334 |
+
print(f"[{name}]")
|
|
|
|
|
|
|
|
|
|
| 335 |
result = review(code)
|
| 336 |
+
print(json.dumps(result, indent=2))
|
| 337 |
+
print()
|
|
@@ -1,29 +0,0 @@
|
|
| 1 |
-
Running Agent Code Review Tests...
|
| 2 |
-
|
| 3 |
-
TEST: Login Function (SQLi)
|
| 4 |
-
Result: {
|
| 5 |
-
"type": "flag",
|
| 6 |
-
"category": "security",
|
| 7 |
-
"line_hint": "database query line",
|
| 8 |
-
"comment": "Possible SQL injection \u2014 query uses string interpolation instead of parameterized queries.",
|
| 9 |
-
"severity": 5
|
| 10 |
-
}
|
| 11 |
-
----------------------------------------
|
| 12 |
-
TEST: Find Max (Off-by-one)
|
| 13 |
-
Result: {
|
| 14 |
-
"type": "approve",
|
| 15 |
-
"category": "ok",
|
| 16 |
-
"line_hint": "",
|
| 17 |
-
"comment": "",
|
| 18 |
-
"severity": 0
|
| 19 |
-
}
|
| 20 |
-
----------------------------------------
|
| 21 |
-
TEST: Save User (Plain Pass)
|
| 22 |
-
Result: {
|
| 23 |
-
"type": "flag",
|
| 24 |
-
"category": "security",
|
| 25 |
-
"line_hint": "password storage or transmission",
|
| 26 |
-
"comment": "Password may be stored or transmitted without hashing. Secure multi-factor authentication and hashing are recommended.",
|
| 27 |
-
"severity": 4
|
| 28 |
-
}
|
| 29 |
-
----------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,18 +1,41 @@
|
|
| 1 |
-
from flask import Flask, render_template, jsonify, request
|
| 2 |
-
import time
|
| 3 |
-
import threading
|
| 4 |
import json
|
|
|
|
| 5 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
from environment import CodeReviewEnv
|
| 9 |
from agent import review, call_llm
|
| 10 |
from grader import grade
|
| 11 |
-
|
|
|
|
| 12 |
|
| 13 |
app = Flask(__name__)
|
| 14 |
-
app.config['MAX_CONTENT_LENGTH'] =
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
def allowed_file(filename):
|
| 18 |
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
|
@@ -41,7 +64,7 @@ def save_history_file():
|
|
| 41 |
"overall_stats": stats,
|
| 42 |
"history": STATE["history"]
|
| 43 |
}
|
| 44 |
-
with open(
|
| 45 |
json.dump(data, f, indent=4)
|
| 46 |
|
| 47 |
def calculate_accuracy():
|
|
@@ -189,6 +212,7 @@ def next_episode():
|
|
| 189 |
})
|
| 190 |
|
| 191 |
@app.route("/api/review", methods=["POST"])
|
|
|
|
| 192 |
def perform_review():
|
| 193 |
data = request.json
|
| 194 |
code = data.get("code")
|
|
@@ -235,15 +259,15 @@ def perform_review():
|
|
| 235 |
@app.route("/api/history", methods=["GET"])
|
| 236 |
def get_history():
|
| 237 |
# If history is empty in state, try reading from file
|
| 238 |
-
if not STATE["history"] and os.path.exists(
|
| 239 |
try:
|
| 240 |
-
with open(
|
| 241 |
data = json.load(f)
|
| 242 |
STATE["history"] = data["history"]
|
| 243 |
STATE["total_reward"] = data["overall_stats"]["total_reward"]
|
| 244 |
STATE["episode_count"] = data["overall_stats"]["episodes_run"]
|
| 245 |
-
except:
|
| 246 |
-
|
| 247 |
|
| 248 |
return jsonify({
|
| 249 |
"history": STATE["history"],
|
|
@@ -254,6 +278,7 @@ def get_history():
|
|
| 254 |
})
|
| 255 |
|
| 256 |
@app.route("/api/auto-run", methods=["POST"])
|
|
|
|
| 257 |
def auto_run():
|
| 258 |
if STATE["is_running"]:
|
| 259 |
return jsonify({"error": "Already running"}), 400
|
|
@@ -297,6 +322,7 @@ def auto_run():
|
|
| 297 |
return jsonify({"status": "running", "count": count})
|
| 298 |
|
| 299 |
@app.route("/api/upload", methods=["POST"])
|
|
|
|
| 300 |
def upload_file():
|
| 301 |
if 'file' not in request.files:
|
| 302 |
return jsonify({"error": "No file provided"}), 400
|
|
@@ -315,6 +341,7 @@ def upload_file():
|
|
| 315 |
return process_raw_code(code, file.filename, note)
|
| 316 |
|
| 317 |
@app.route("/api/review-text", methods=["POST"])
|
|
|
|
| 318 |
def review_text():
|
| 319 |
data = request.json
|
| 320 |
code = data.get("code", "")
|
|
@@ -441,8 +468,8 @@ def reset_state():
|
|
| 441 |
STATE["episode_count"] = 0
|
| 442 |
STATE["history"] = []
|
| 443 |
STATE["is_running"] = False
|
| 444 |
-
if os.path.exists(
|
| 445 |
-
os.remove(
|
| 446 |
return jsonify({"status": "reset"})
|
| 447 |
|
| 448 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
+
import logging
|
| 3 |
import os
|
| 4 |
+
import re
|
| 5 |
+
import time
|
| 6 |
+
import threading
|
| 7 |
+
|
| 8 |
+
from flask import Flask, jsonify, render_template, request
|
| 9 |
+
from flask_limiter import Limiter
|
| 10 |
+
from flask_limiter.util import get_remote_address
|
| 11 |
|
| 12 |
+
from config import (
|
| 13 |
+
ALLOWED_EXTENSIONS,
|
| 14 |
+
MAX_CONTENT_LENGTH_MB,
|
| 15 |
+
RATE_LIMIT_AUTO_RUN,
|
| 16 |
+
RATE_LIMIT_DEFAULT,
|
| 17 |
+
RATE_LIMIT_REVIEW,
|
| 18 |
+
RUNS_DIR,
|
| 19 |
+
)
|
| 20 |
from environment import CodeReviewEnv
|
| 21 |
from agent import review, call_llm
|
| 22 |
from grader import grade
|
| 23 |
+
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
|
| 26 |
app = Flask(__name__)
|
| 27 |
+
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH_MB * 1024 * 1024
|
| 28 |
+
|
| 29 |
+
limiter = Limiter(
|
| 30 |
+
get_remote_address,
|
| 31 |
+
app=app,
|
| 32 |
+
default_limits=[RATE_LIMIT_DEFAULT],
|
| 33 |
+
headers_enabled=True, # Adds Retry-After + X-RateLimit-* headers
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# Ensure runs directory exists
|
| 37 |
+
os.makedirs(RUNS_DIR, exist_ok=True)
|
| 38 |
+
HISTORY_FILE = os.path.join(RUNS_DIR, "history.json")
|
| 39 |
|
| 40 |
def allowed_file(filename):
|
| 41 |
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
|
|
|
| 64 |
"overall_stats": stats,
|
| 65 |
"history": STATE["history"]
|
| 66 |
}
|
| 67 |
+
with open(HISTORY_FILE, "w") as f:
|
| 68 |
json.dump(data, f, indent=4)
|
| 69 |
|
| 70 |
def calculate_accuracy():
|
|
|
|
| 212 |
})
|
| 213 |
|
| 214 |
@app.route("/api/review", methods=["POST"])
|
| 215 |
+
@limiter.limit(RATE_LIMIT_REVIEW)
|
| 216 |
def perform_review():
|
| 217 |
data = request.json
|
| 218 |
code = data.get("code")
|
|
|
|
| 259 |
@app.route("/api/history", methods=["GET"])
|
| 260 |
def get_history():
|
| 261 |
# If history is empty in state, try reading from file
|
| 262 |
+
if not STATE["history"] and os.path.exists(HISTORY_FILE):
|
| 263 |
try:
|
| 264 |
+
with open(HISTORY_FILE) as f:
|
| 265 |
data = json.load(f)
|
| 266 |
STATE["history"] = data["history"]
|
| 267 |
STATE["total_reward"] = data["overall_stats"]["total_reward"]
|
| 268 |
STATE["episode_count"] = data["overall_stats"]["episodes_run"]
|
| 269 |
+
except Exception as exc:
|
| 270 |
+
logger.warning("Could not read history file: %s", exc)
|
| 271 |
|
| 272 |
return jsonify({
|
| 273 |
"history": STATE["history"],
|
|
|
|
| 278 |
})
|
| 279 |
|
| 280 |
@app.route("/api/auto-run", methods=["POST"])
|
| 281 |
+
@limiter.limit(RATE_LIMIT_AUTO_RUN)
|
| 282 |
def auto_run():
|
| 283 |
if STATE["is_running"]:
|
| 284 |
return jsonify({"error": "Already running"}), 400
|
|
|
|
| 322 |
return jsonify({"status": "running", "count": count})
|
| 323 |
|
| 324 |
@app.route("/api/upload", methods=["POST"])
|
| 325 |
+
@limiter.limit(RATE_LIMIT_REVIEW)
|
| 326 |
def upload_file():
|
| 327 |
if 'file' not in request.files:
|
| 328 |
return jsonify({"error": "No file provided"}), 400
|
|
|
|
| 341 |
return process_raw_code(code, file.filename, note)
|
| 342 |
|
| 343 |
@app.route("/api/review-text", methods=["POST"])
|
| 344 |
+
@limiter.limit(RATE_LIMIT_REVIEW)
|
| 345 |
def review_text():
|
| 346 |
data = request.json
|
| 347 |
code = data.get("code", "")
|
|
|
|
| 468 |
STATE["episode_count"] = 0
|
| 469 |
STATE["history"] = []
|
| 470 |
STATE["is_running"] = False
|
| 471 |
+
if os.path.exists(HISTORY_FILE):
|
| 472 |
+
os.remove(HISTORY_FILE)
|
| 473 |
return jsonify({"status": "reset"})
|
| 474 |
|
| 475 |
if __name__ == "__main__":
|
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
config.py — Central configuration for CodeBug.
|
| 3 |
+
|
| 4 |
+
All tuneable constants live here so you never have to hunt through
|
| 5 |
+
multiple source files to change a model name or a reward value.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
# ---------------------------------------------------------------------------
|
| 11 |
+
# API / Model
|
| 12 |
+
# ---------------------------------------------------------------------------
|
| 13 |
+
|
| 14 |
+
ANTHROPIC_MODEL = "claude-haiku-4-5-20251001"
|
| 15 |
+
OPENAI_MODEL = "gpt-4o-mini"
|
| 16 |
+
MAX_TOKENS = 300 # Max tokens for review calls
|
| 17 |
+
FIX_MAX_TOKENS = 600 # Max tokens for fix-suggestion calls
|
| 18 |
+
|
| 19 |
+
# ---------------------------------------------------------------------------
|
| 20 |
+
# Reward values
|
| 21 |
+
# ---------------------------------------------------------------------------
|
| 22 |
+
|
| 23 |
+
REWARD_SECURITY_CATCH = 25 # Correctly flagged a security bug
|
| 24 |
+
REWARD_LOGIC_CATCH = 15 # Correctly flagged a logic bug
|
| 25 |
+
REWARD_OTHER_CATCH = 10 # Correctly flagged a style/other issue
|
| 26 |
+
REWARD_CLEAN_APPROVE = 5 # Correctly approved clean code ← NEW
|
| 27 |
+
REWARD_PARTIAL_CREDIT = 5 # Right decision, wrong category ← NEW
|
| 28 |
+
|
| 29 |
+
REWARD_SEVERITY_EXACT = 5 # Severity matched exactly
|
| 30 |
+
REWARD_SEVERITY_CLOSE = 3 # Severity off by 1
|
| 31 |
+
|
| 32 |
+
REWARD_COMMENT_LONG = 5 # Comment longer than 40 chars
|
| 33 |
+
REWARD_COMMENT_SHORT = 2 # Comment between 16-40 chars
|
| 34 |
+
|
| 35 |
+
REWARD_LINE_HINT = 3 # Line location was specified
|
| 36 |
+
|
| 37 |
+
PENALTY_WRONG_CATEGORY = -10 # Flagged but wrong category
|
| 38 |
+
PENALTY_MISS_CRITICAL = -25 # Missed severity-5 bug
|
| 39 |
+
PENALTY_MISS_HIGH = -20 # Missed severity-4 bug
|
| 40 |
+
PENALTY_MISS_MEDIUM = -12 # Missed severity-3 bug
|
| 41 |
+
PENALTY_MISS_LOW = -5 # Missed severity ≤ 2 bug
|
| 42 |
+
PENALTY_UNKNOWN_ACTION = -5 # Unknown action type
|
| 43 |
+
|
| 44 |
+
# ---------------------------------------------------------------------------
|
| 45 |
+
# File paths
|
| 46 |
+
# ---------------------------------------------------------------------------
|
| 47 |
+
|
| 48 |
+
EPISODES_FILE = "episodes.json"
|
| 49 |
+
ANSWERS_FILE = "answers.json"
|
| 50 |
+
RUNS_DIR = "runs" # All run outputs go here
|
| 51 |
+
CHECKPOINT_FILE = os.path.join(RUNS_DIR, "checkpoint.json")
|
| 52 |
+
|
| 53 |
+
# ---------------------------------------------------------------------------
|
| 54 |
+
# Flask / Rate limiting
|
| 55 |
+
# ---------------------------------------------------------------------------
|
| 56 |
+
|
| 57 |
+
MAX_CONTENT_LENGTH_MB = 1 # Max upload size in MB
|
| 58 |
+
RATE_LIMIT_DEFAULT = "60 per minute"
|
| 59 |
+
RATE_LIMIT_REVIEW = "20 per minute" # Paid API — be conservative
|
| 60 |
+
RATE_LIMIT_AUTO_RUN = "5 per minute"
|
| 61 |
+
|
| 62 |
+
ALLOWED_EXTENSIONS = {"py", "js", "ts", "java", "cpp", "c", "go", "rb", "php", "txt"}
|
|
@@ -1,157 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
import random
|
| 3 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
class CodeReviewEnv:
|
| 6 |
-
def __init__(
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
| 14 |
for ep in self.episodes:
|
| 15 |
ep["code"] = ep["code"].replace("\r", "")
|
| 16 |
for ans in self.answers:
|
| 17 |
if "buggy_code" in ans:
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
self.current_episode = None
|
| 21 |
-
self.episode_index
|
| 22 |
-
self.total_reward
|
| 23 |
-
self.correct_count
|
| 24 |
-
self.best_score
|
| 25 |
-
self.worst_score
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
"instructions": (
|
| 36 |
"Review this code. Find bugs, security issues, or logic errors. "
|
| 37 |
-
"Respond in JSON with keys: type (flag or approve),
|
| 38 |
-
"
|
| 39 |
-
"
|
| 40 |
-
|
|
|
|
| 41 |
}
|
| 42 |
-
return observation
|
| 43 |
|
| 44 |
-
def step(self, ai_action):
|
| 45 |
-
"""Execute one
|
| 46 |
ground_truth = self._get_answer(self.current_episode["episode_id"])
|
| 47 |
-
|
| 48 |
-
# Use grader module
|
| 49 |
result = grade(ai_action, ground_truth)
|
| 50 |
reward = result.reward
|
| 51 |
-
|
| 52 |
-
self.total_reward
|
| 53 |
self.episode_index += 1
|
| 54 |
-
|
| 55 |
if result.correct:
|
| 56 |
self.correct_count += 1
|
| 57 |
-
|
| 58 |
if reward > self.best_score:
|
| 59 |
self.best_score = reward
|
| 60 |
if reward < self.worst_score:
|
| 61 |
self.worst_score = reward
|
| 62 |
-
|
| 63 |
-
done = True
|
| 64 |
-
|
| 65 |
-
# Determine truth string for metadata
|
| 66 |
if ground_truth and "bug" in ground_truth:
|
| 67 |
-
|
| 68 |
else:
|
| 69 |
-
|
| 70 |
|
| 71 |
info = {
|
| 72 |
"episode_id": self.current_episode["episode_id"],
|
| 73 |
-
"ai_said":
|
| 74 |
-
"truth":
|
| 75 |
-
"correct":
|
| 76 |
-
"breakdown":
|
| 77 |
}
|
| 78 |
-
|
| 79 |
-
return reward, done, info
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
|
|
|
| 83 |
for ans in self.answers:
|
| 84 |
if ans["episode_id"] == episode_id:
|
| 85 |
return ans
|
| 86 |
return None
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
"""Return summary statistics of the environment performance."""
|
| 91 |
-
avg_reward = self.total_reward / self.episode_index if self.episode_index > 0 else 0
|
| 92 |
accuracy = self.correct_count / self.episode_index if self.episode_index > 0 else 0
|
| 93 |
return {
|
| 94 |
-
"total_reward":
|
| 95 |
-
"episodes_run":
|
| 96 |
-
"average_reward":
|
| 97 |
-
"accuracy":
|
| 98 |
-
"best_score":
|
| 99 |
-
"worst_score":
|
| 100 |
}
|
| 101 |
|
| 102 |
-
def render(self, observation, ai_action, reward, info):
|
| 103 |
-
"""Print a summary of the turn to the terminal."""
|
| 104 |
-
# Ensure we only show a few lines and escape any weirdness
|
| 105 |
lines = observation["code"].splitlines()
|
| 106 |
-
code_preview = ""
|
| 107 |
-
|
| 108 |
-
code_preview += f" {line}\n"
|
| 109 |
-
|
| 110 |
print("\n" + "-" * 40)
|
| 111 |
print(f"Episode: {observation['episode_id']}")
|
| 112 |
-
print("Code snippet
|
| 113 |
print(code_preview, end="")
|
| 114 |
print(" ...")
|
| 115 |
-
print()
|
| 116 |
-
print(f"AI said: {info['ai_said']}")
|
| 117 |
print(f"Truth was: {info['truth']}")
|
| 118 |
print(f"Correct: {info['correct']}")
|
| 119 |
print(f"Reward: {reward:+d}")
|
| 120 |
print(f"Total so far: {self.total_reward}")
|
| 121 |
print("-" * 40)
|
| 122 |
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
if __name__ == "__main__":
|
| 125 |
-
env = CodeReviewEnv(
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
for i in range(5):
|
| 130 |
obs = env.reset()
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
"category": "security",
|
| 138 |
-
"line_hint": "line 3",
|
| 139 |
-
"comment": "This looks like a SQL injection vulnerability",
|
| 140 |
-
"severity": 5
|
| 141 |
-
}
|
| 142 |
-
else:
|
| 143 |
-
# Odd episodes: "Missed the bug" AI action
|
| 144 |
-
fake_action = {
|
| 145 |
-
"type": "approve",
|
| 146 |
-
"category": "ok",
|
| 147 |
-
"line_hint": "",
|
| 148 |
-
"comment": "",
|
| 149 |
-
"severity": 0
|
| 150 |
-
}
|
| 151 |
-
|
| 152 |
reward, done, info = env.step(fake_action)
|
| 153 |
env.render(obs, fake_action, reward, info)
|
| 154 |
-
|
| 155 |
-
print("\
|
| 156 |
-
|
| 157 |
-
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
environment.py — Code-review RL environment.
|
| 3 |
+
|
| 4 |
+
Key improvements:
|
| 5 |
+
- reset() uses a shuffled queue that exhausts all episodes before cycling,
|
| 6 |
+
preventing repeated sampling of the same snippet within an epoch.
|
| 7 |
+
- Episode/answer paths come from config.py.
|
| 8 |
+
- Type annotations on all public methods.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
import json
|
| 14 |
import random
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
from config import ANSWERS_FILE, EPISODES_FILE
|
| 18 |
+
from grader import GradeResult, grade
|
| 19 |
+
|
| 20 |
|
| 21 |
class CodeReviewEnv:
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
episodes_path: str = EPISODES_FILE,
|
| 25 |
+
answers_path: str = ANSWERS_FILE,
|
| 26 |
+
) -> None:
|
| 27 |
+
with open(episodes_path, "r") as f:
|
| 28 |
+
self.episodes: list[dict] = json.load(f)
|
| 29 |
+
with open(answers_path, "r") as f:
|
| 30 |
+
self.answers: list[dict] = json.load(f)
|
| 31 |
+
|
| 32 |
+
# Strip \r artifacts that cause terminal issues on Windows
|
| 33 |
for ep in self.episodes:
|
| 34 |
ep["code"] = ep["code"].replace("\r", "")
|
| 35 |
for ans in self.answers:
|
| 36 |
if "buggy_code" in ans:
|
| 37 |
+
ans["buggy_code"] = ans["buggy_code"].replace("\r", "")
|
| 38 |
+
|
| 39 |
+
self.current_episode: dict | None = None
|
| 40 |
+
self.episode_index = 0
|
| 41 |
+
self.total_reward = 0
|
| 42 |
+
self.correct_count = 0
|
| 43 |
+
self.best_score = -float("inf")
|
| 44 |
+
self.worst_score = float("inf")
|
| 45 |
+
|
| 46 |
+
# Shuffled queue — exhausted before refilling (deduplication)
|
| 47 |
+
self._queue: list[dict] = []
|
| 48 |
+
|
| 49 |
+
# ------------------------------------------------------------------
|
| 50 |
+
# Internal helpers
|
| 51 |
+
# ------------------------------------------------------------------
|
| 52 |
+
|
| 53 |
+
def _refill_queue(self) -> None:
|
| 54 |
+
"""Shuffle a fresh copy of all episodes into the queue."""
|
| 55 |
+
self._queue = list(self.episodes)
|
| 56 |
+
random.shuffle(self._queue)
|
| 57 |
+
|
| 58 |
+
# ------------------------------------------------------------------
|
| 59 |
+
# Public API
|
| 60 |
+
# ------------------------------------------------------------------
|
| 61 |
+
|
| 62 |
+
def reset(self) -> dict[str, Any]:
|
| 63 |
+
"""
|
| 64 |
+
Pick the next unseen episode from this epoch's shuffled queue.
|
| 65 |
+
Once all episodes have been seen, reshuffle and start a new epoch.
|
| 66 |
+
"""
|
| 67 |
+
if not self._queue:
|
| 68 |
+
self._refill_queue()
|
| 69 |
+
|
| 70 |
+
self.current_episode = self._queue.pop()
|
| 71 |
+
|
| 72 |
+
return {
|
| 73 |
+
"code": self.current_episode["code"],
|
| 74 |
+
"episode_id": self.current_episode["episode_id"],
|
| 75 |
+
"snippet_id": self.current_episode["snippet_id"],
|
| 76 |
"instructions": (
|
| 77 |
"Review this code. Find bugs, security issues, or logic errors. "
|
| 78 |
+
"Respond in JSON with keys: type (flag or approve), "
|
| 79 |
+
"category (security/logic/style/ok), "
|
| 80 |
+
"line_hint (brief description of where the issue is), "
|
| 81 |
+
"comment (your explanation), severity (1-5)"
|
| 82 |
+
),
|
| 83 |
}
|
|
|
|
| 84 |
|
| 85 |
+
def step(self, ai_action: dict) -> tuple[int, bool, dict]:
|
| 86 |
+
"""Execute one review step and return (reward, done, info)."""
|
| 87 |
ground_truth = self._get_answer(self.current_episode["episode_id"])
|
| 88 |
+
|
|
|
|
| 89 |
result = grade(ai_action, ground_truth)
|
| 90 |
reward = result.reward
|
| 91 |
+
|
| 92 |
+
self.total_reward += reward
|
| 93 |
self.episode_index += 1
|
| 94 |
+
|
| 95 |
if result.correct:
|
| 96 |
self.correct_count += 1
|
| 97 |
+
|
| 98 |
if reward > self.best_score:
|
| 99 |
self.best_score = reward
|
| 100 |
if reward < self.worst_score:
|
| 101 |
self.worst_score = reward
|
| 102 |
+
|
|
|
|
|
|
|
|
|
|
| 103 |
if ground_truth and "bug" in ground_truth:
|
| 104 |
+
truth_str = f"{ground_truth['bug']['type']} severity {ground_truth['bug']['severity']}"
|
| 105 |
else:
|
| 106 |
+
truth_str = "None"
|
| 107 |
|
| 108 |
info = {
|
| 109 |
"episode_id": self.current_episode["episode_id"],
|
| 110 |
+
"ai_said": f"{ai_action.get('type')} / {ai_action.get('category')}",
|
| 111 |
+
"truth": truth_str,
|
| 112 |
+
"correct": result.correct,
|
| 113 |
+
"breakdown": result.breakdown,
|
| 114 |
}
|
|
|
|
|
|
|
| 115 |
|
| 116 |
+
return reward, True, info
|
| 117 |
+
|
| 118 |
+
def _get_answer(self, episode_id: str) -> dict | None:
|
| 119 |
for ans in self.answers:
|
| 120 |
if ans["episode_id"] == episode_id:
|
| 121 |
return ans
|
| 122 |
return None
|
| 123 |
|
| 124 |
+
def get_stats(self) -> dict:
|
| 125 |
+
avg_r = self.total_reward / self.episode_index if self.episode_index > 0 else 0
|
|
|
|
|
|
|
| 126 |
accuracy = self.correct_count / self.episode_index if self.episode_index > 0 else 0
|
| 127 |
return {
|
| 128 |
+
"total_reward": self.total_reward,
|
| 129 |
+
"episodes_run": self.episode_index,
|
| 130 |
+
"average_reward": avg_r,
|
| 131 |
+
"accuracy": accuracy,
|
| 132 |
+
"best_score": self.best_score if self.best_score != -float("inf") else 0,
|
| 133 |
+
"worst_score": self.worst_score if self.worst_score != float("inf") else 0,
|
| 134 |
}
|
| 135 |
|
| 136 |
+
def render(self, observation: dict, ai_action: dict, reward: int, info: dict) -> None:
|
|
|
|
|
|
|
| 137 |
lines = observation["code"].splitlines()
|
| 138 |
+
code_preview = "".join(f" {l}\n" for l in lines[:3])
|
| 139 |
+
|
|
|
|
|
|
|
| 140 |
print("\n" + "-" * 40)
|
| 141 |
print(f"Episode: {observation['episode_id']}")
|
| 142 |
+
print("Code snippet:")
|
| 143 |
print(code_preview, end="")
|
| 144 |
print(" ...")
|
| 145 |
+
print(f"\nAI said: {info['ai_said']}")
|
|
|
|
| 146 |
print(f"Truth was: {info['truth']}")
|
| 147 |
print(f"Correct: {info['correct']}")
|
| 148 |
print(f"Reward: {reward:+d}")
|
| 149 |
print(f"Total so far: {self.total_reward}")
|
| 150 |
print("-" * 40)
|
| 151 |
|
| 152 |
+
|
| 153 |
+
# ---------------------------------------------------------------------------
|
| 154 |
+
# Test block
|
| 155 |
+
# ---------------------------------------------------------------------------
|
| 156 |
+
|
| 157 |
if __name__ == "__main__":
|
| 158 |
+
env = CodeReviewEnv()
|
| 159 |
+
print("Starting 5-episode simulation (shuffled queue)...\n")
|
| 160 |
+
|
|
|
|
| 161 |
for i in range(5):
|
| 162 |
obs = env.reset()
|
| 163 |
+
fake_action = (
|
| 164 |
+
{"type": "flag", "category": "security", "line_hint": "line 3",
|
| 165 |
+
"comment": "Possible SQL injection vulnerability", "severity": 5}
|
| 166 |
+
if i % 2 == 0
|
| 167 |
+
else {"type": "approve", "category": "ok", "line_hint": "", "comment": "", "severity": 0}
|
| 168 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
reward, done, info = env.step(fake_action)
|
| 170 |
env.render(obs, fake_action, reward, info)
|
| 171 |
+
|
| 172 |
+
print("\nFinal Stats:")
|
| 173 |
+
import pprint
|
| 174 |
+
pprint.pprint(env.get_stats())
|
|
@@ -1,133 +0,0 @@
|
|
| 1 |
-
RUNNING GRADER TESTS...
|
| 2 |
-
|
| 3 |
-
CASE 1:
|
| 4 |
-
GRADE SUMMARY
|
| 5 |
-
-------------------------
|
| 6 |
-
Reward: +38
|
| 7 |
-
Correct: Yes
|
| 8 |
-
Bug was: security (severity 5)
|
| 9 |
-
|
| 10 |
-
Breakdown:
|
| 11 |
-
+25: caught a security vulnerability
|
| 12 |
-
+5: severity rating was exact
|
| 13 |
-
+5: detailed comment provided
|
| 14 |
-
+3: line location was specified
|
| 15 |
-
-------------------------
|
| 16 |
-
Total: +38
|
| 17 |
-
|
| 18 |
-
CASE 2:
|
| 19 |
-
GRADE SUMMARY
|
| 20 |
-
-------------------------
|
| 21 |
-
Reward: +20
|
| 22 |
-
Correct: Yes
|
| 23 |
-
Bug was: logic (severity 3)
|
| 24 |
-
|
| 25 |
-
Breakdown:
|
| 26 |
-
+15: caught a logic bug
|
| 27 |
-
+5: severity rating was exact
|
| 28 |
-
+0: comment too short or missing
|
| 29 |
-
+0: no line location given
|
| 30 |
-
-------------------------
|
| 31 |
-
Total: +20
|
| 32 |
-
|
| 33 |
-
CASE 3:
|
| 34 |
-
GRADE SUMMARY
|
| 35 |
-
-------------------------
|
| 36 |
-
Reward: -10
|
| 37 |
-
Correct: No
|
| 38 |
-
Bug was: security (severity 5)
|
| 39 |
-
|
| 40 |
-
Breakdown:
|
| 41 |
-
-10: false positive ù flagged as 'logic' but was 'security'
|
| 42 |
-
-------------------------
|
| 43 |
-
Total: -10
|
| 44 |
-
|
| 45 |
-
CASE 4:
|
| 46 |
-
GRADE SUMMARY
|
| 47 |
-
-------------------------
|
| 48 |
-
Reward: -25
|
| 49 |
-
Correct: No
|
| 50 |
-
Bug was: security (severity 5)
|
| 51 |
-
|
| 52 |
-
Breakdown:
|
| 53 |
-
-25: missed a critical severity-5 bug (security)
|
| 54 |
-
-------------------------
|
| 55 |
-
Total: -25
|
| 56 |
-
|
| 57 |
-
CASE 5:
|
| 58 |
-
GRADE SUMMARY
|
| 59 |
-
-------------------------
|
| 60 |
-
Reward: -12
|
| 61 |
-
Correct: No
|
| 62 |
-
Bug was: logic (severity 3)
|
| 63 |
-
|
| 64 |
-
Breakdown:
|
| 65 |
-
-12: missed a medium severity-3 bug (logic)
|
| 66 |
-
-------------------------
|
| 67 |
-
Total: -12
|
| 68 |
-
|
| 69 |
-
CASE 6:
|
| 70 |
-
GRADE SUMMARY
|
| 71 |
-
-------------------------
|
| 72 |
-
Reward: +38
|
| 73 |
-
Correct: Yes
|
| 74 |
-
Bug was: security (severity 5)
|
| 75 |
-
|
| 76 |
-
Breakdown:
|
| 77 |
-
+25: caught a security vulnerability
|
| 78 |
-
+5: severity rating was exact
|
| 79 |
-
+5: detailed comment provided
|
| 80 |
-
+3: line location was specified
|
| 81 |
-
-------------------------
|
| 82 |
-
Total: +38
|
| 83 |
-
|
| 84 |
-
BATCH RESULTS:
|
| 85 |
-
{'accuracy': 0.5,
|
| 86 |
-
'average_reward': 8.166666666666666,
|
| 87 |
-
'best_score': 38,
|
| 88 |
-
'caught_logic': 1,
|
| 89 |
-
'caught_security': 2,
|
| 90 |
-
'false_positives': 1,
|
| 91 |
-
'missed_bugs': 2,
|
| 92 |
-
'results': [{'breakdown': ['+25: caught a security vulnerability',
|
| 93 |
-
'+5: severity rating was exact',
|
| 94 |
-
'+5: detailed comment provided',
|
| 95 |
-
'+3: line location was specified'],
|
| 96 |
-
'bug_severity': 5,
|
| 97 |
-
'bug_type': 'security',
|
| 98 |
-
'correct': True,
|
| 99 |
-
'reward': 38},
|
| 100 |
-
{'breakdown': ['+15: caught a logic bug',
|
| 101 |
-
'+5: severity rating was exact',
|
| 102 |
-
'+0: comment too short or missing',
|
| 103 |
-
'+0: no line location given'],
|
| 104 |
-
'bug_severity': 3,
|
| 105 |
-
'bug_type': 'logic',
|
| 106 |
-
'correct': True,
|
| 107 |
-
'reward': 20},
|
| 108 |
-
{'breakdown': ["-10: false positive ù flagged as 'logic' but was "
|
| 109 |
-
"'security'"],
|
| 110 |
-
'bug_severity': 5,
|
| 111 |
-
'bug_type': 'security',
|
| 112 |
-
'correct': False,
|
| 113 |
-
'reward': -10},
|
| 114 |
-
{'breakdown': ['-25: missed a critical severity-5 bug (security)'],
|
| 115 |
-
'bug_severity': 5,
|
| 116 |
-
'bug_type': 'security',
|
| 117 |
-
'correct': False,
|
| 118 |
-
'reward': -25},
|
| 119 |
-
{'breakdown': ['-12: missed a medium severity-3 bug (logic)'],
|
| 120 |
-
'bug_severity': 3,
|
| 121 |
-
'bug_type': 'logic',
|
| 122 |
-
'correct': False,
|
| 123 |
-
'reward': -12},
|
| 124 |
-
{'breakdown': ['+25: caught a security vulnerability',
|
| 125 |
-
'+5: severity rating was exact',
|
| 126 |
-
'+5: detailed comment provided',
|
| 127 |
-
'+3: line location was specified'],
|
| 128 |
-
'bug_severity': 5,
|
| 129 |
-
'bug_type': 'security',
|
| 130 |
-
'correct': True,
|
| 131 |
-
'reward': 38}],
|
| 132 |
-
'total_reward': 49,
|
| 133 |
-
'worst_score': -25}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,14 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
class GradeResult:
|
| 2 |
-
def __init__(
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
self.reward = reward
|
| 5 |
self.breakdown = breakdown
|
| 6 |
self.correct = correct
|
| 7 |
self.bug_type = bug_type
|
| 8 |
self.bug_severity = bug_severity
|
| 9 |
|
| 10 |
-
def summary(self):
|
| 11 |
-
"""Return a formatted multi-line summary of the grading result."""
|
| 12 |
lines = [
|
| 13 |
"GRADE SUMMARY",
|
| 14 |
"-" * 25,
|
|
@@ -16,7 +58,7 @@ class GradeResult:
|
|
| 16 |
f"Correct: {'Yes' if self.correct else 'No'}",
|
| 17 |
f"Bug was: {self.bug_type} (severity {self.bug_severity})",
|
| 18 |
"",
|
| 19 |
-
"Breakdown:"
|
| 20 |
]
|
| 21 |
for entry in self.breakdown:
|
| 22 |
lines.append(f" {entry}")
|
|
@@ -24,226 +66,259 @@ class GradeResult:
|
|
| 24 |
lines.append(f"Total: {self.reward:+d}")
|
| 25 |
return "\n".join(lines)
|
| 26 |
|
| 27 |
-
def to_dict(self):
|
| 28 |
-
"""Convert the grade result to a dictionary for batch processing."""
|
| 29 |
return {
|
| 30 |
"reward": self.reward,
|
| 31 |
"correct": self.correct,
|
| 32 |
"bug_type": self.bug_type,
|
| 33 |
"bug_severity": self.bug_severity,
|
| 34 |
-
"breakdown": self.breakdown
|
| 35 |
}
|
| 36 |
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
"""
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
ai_action keys: type, category, line_hint, comment, severity
|
| 42 |
-
ground_truth keys: bug
|
| 43 |
"""
|
| 44 |
if ground_truth is None or "bug" not in ground_truth:
|
| 45 |
return GradeResult(reward=0, breakdown=["No ground truth available"], correct=False)
|
| 46 |
-
|
| 47 |
bug = ground_truth["bug"]
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
ai_line_hint = ai_action.get("line_hint", "")
|
| 57 |
|
| 58 |
-
# ---
|
|
|
|
|
|
|
| 59 |
if ai_type == "flag":
|
| 60 |
-
|
|
|
|
|
|
|
| 61 |
correct = True
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
breakdown.append("+15: caught a logic bug")
|
| 70 |
else:
|
| 71 |
-
reward +=
|
| 72 |
-
breakdown.append("+
|
| 73 |
-
|
| 74 |
-
# Severity accuracy
|
| 75 |
-
|
| 76 |
-
if
|
| 77 |
-
reward +=
|
| 78 |
-
breakdown.append("+
|
| 79 |
-
elif
|
| 80 |
-
reward +=
|
| 81 |
-
breakdown.append("+
|
| 82 |
else:
|
| 83 |
-
breakdown.append("+0: severity rating
|
| 84 |
-
|
| 85 |
-
# Comment quality
|
| 86 |
if len(ai_comment) > 40:
|
| 87 |
-
reward +=
|
| 88 |
-
breakdown.append("+
|
| 89 |
elif len(ai_comment) > 15:
|
| 90 |
-
reward +=
|
| 91 |
-
breakdown.append("+
|
| 92 |
else:
|
| 93 |
breakdown.append("+0: comment too short or missing")
|
| 94 |
-
|
| 95 |
-
# Line hint
|
| 96 |
if len(ai_line_hint) > 5:
|
| 97 |
-
reward +=
|
| 98 |
-
breakdown.append("+
|
| 99 |
else:
|
| 100 |
breakdown.append("+0: no line location given")
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
else:
|
| 103 |
-
#
|
| 104 |
-
reward
|
| 105 |
-
breakdown.append(
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
elif ai_type == "approve":
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
reward
|
| 114 |
-
breakdown.append(f"
|
| 115 |
-
|
| 116 |
-
reward -= 12
|
| 117 |
-
breakdown.append(f"-12: missed a medium severity-3 bug ({bug['type']})")
|
| 118 |
else:
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
else:
|
| 124 |
-
reward
|
| 125 |
-
breakdown.append("
|
| 126 |
-
|
| 127 |
return GradeResult(
|
| 128 |
-
reward=reward,
|
| 129 |
-
breakdown=breakdown,
|
| 130 |
-
correct=correct,
|
| 131 |
-
bug_type=
|
| 132 |
-
bug_severity=
|
| 133 |
)
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
caught_security = 0
|
| 144 |
-
caught_logic
|
| 145 |
false_positives = 0
|
| 146 |
-
missed_bugs
|
| 147 |
-
|
|
|
|
| 148 |
for ep in episodes:
|
| 149 |
res = grade(ep["ai_action"], ep["ground_truth"])
|
| 150 |
-
|
| 151 |
-
results_list.append(
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
if res_dict["correct"]:
|
| 157 |
correct_count += 1
|
| 158 |
-
if
|
| 159 |
caught_security += 1
|
| 160 |
-
elif
|
| 161 |
caught_logic += 1
|
|
|
|
|
|
|
| 162 |
else:
|
| 163 |
ai_type = ep["ai_action"].get("type")
|
| 164 |
if ai_type == "flag":
|
| 165 |
false_positives += 1
|
| 166 |
elif ai_type == "approve":
|
| 167 |
missed_bugs += 1
|
| 168 |
-
|
| 169 |
-
if reward > best_score:
|
| 170 |
-
best_score = reward
|
| 171 |
-
if reward < worst_score:
|
| 172 |
-
worst_score = reward
|
| 173 |
-
|
| 174 |
count = len(episodes)
|
| 175 |
if count == 0:
|
| 176 |
return {"error": "no episodes provided"}
|
| 177 |
-
|
| 178 |
return {
|
| 179 |
-
"results":
|
| 180 |
-
"total_reward":
|
| 181 |
-
"average_reward":
|
| 182 |
-
"accuracy":
|
| 183 |
-
"best_score":
|
| 184 |
-
"worst_score":
|
| 185 |
"caught_security": caught_security,
|
| 186 |
-
"caught_logic":
|
|
|
|
| 187 |
"false_positives": false_positives,
|
| 188 |
-
"missed_bugs":
|
| 189 |
}
|
| 190 |
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 193 |
test_cases = [
|
| 194 |
# 1. Perfect security catch
|
| 195 |
-
{
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
# 2.
|
| 203 |
-
{
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
# 5. Missed medium bug
|
| 225 |
-
{"ai_action": {"type": "approve", "category": "ok",
|
| 226 |
-
"line_hint": "", "comment": "", "severity": 0},
|
| 227 |
-
"ground_truth": {"bug": {"type": "logic", "severity": 3,
|
| 228 |
-
"description": "off-by-one", "line_hint": "range call"}}},
|
| 229 |
-
|
| 230 |
-
# 6. Perfect catch with full detail
|
| 231 |
-
{"ai_action": {"type": "flag", "category": "security",
|
| 232 |
-
"line_hint": "db.insert line — password stored without hashing",
|
| 233 |
-
"comment": "Password is stored as plain text. Should use bcrypt or hashlib sha256 before inserting into the database.",
|
| 234 |
-
"severity": 5},
|
| 235 |
-
"ground_truth": {"bug": {"type": "security", "severity": 5,
|
| 236 |
-
"description": "plain text password", "line_hint": "db.insert line"}}}
|
| 237 |
]
|
| 238 |
-
|
| 239 |
print("RUNNING GRADER TESTS...\n")
|
| 240 |
-
|
| 241 |
for i, case in enumerate(test_cases, 1):
|
| 242 |
print(f"CASE {i}:")
|
| 243 |
result = grade(case["ai_action"], case["ground_truth"])
|
| 244 |
print(result.summary())
|
| 245 |
print()
|
| 246 |
-
|
| 247 |
print("BATCH RESULTS:")
|
| 248 |
-
import pprint
|
| 249 |
pprint.pprint(batch_grade(test_cases))
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
grader.py — Reward function for the CodeBug RL loop.
|
| 3 |
+
|
| 4 |
+
Key improvements over v1:
|
| 5 |
+
- Clean-code correctly approved → small positive reward (+5) ← NEW
|
| 6 |
+
- Right decision but wrong category → partial credit (+5) ← NEW
|
| 7 |
+
- All reward values imported from config.py
|
| 8 |
+
- Type annotations on public functions
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from config import (
|
| 14 |
+
PENALTY_MISS_CRITICAL,
|
| 15 |
+
PENALTY_MISS_HIGH,
|
| 16 |
+
PENALTY_MISS_LOW,
|
| 17 |
+
PENALTY_MISS_MEDIUM,
|
| 18 |
+
PENALTY_UNKNOWN_ACTION,
|
| 19 |
+
PENALTY_WRONG_CATEGORY,
|
| 20 |
+
REWARD_CLEAN_APPROVE,
|
| 21 |
+
REWARD_COMMENT_LONG,
|
| 22 |
+
REWARD_COMMENT_SHORT,
|
| 23 |
+
REWARD_LINE_HINT,
|
| 24 |
+
REWARD_LOGIC_CATCH,
|
| 25 |
+
REWARD_OTHER_CATCH,
|
| 26 |
+
REWARD_PARTIAL_CREDIT,
|
| 27 |
+
REWARD_SECURITY_CATCH,
|
| 28 |
+
REWARD_SEVERITY_CLOSE,
|
| 29 |
+
REWARD_SEVERITY_EXACT,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# ---------------------------------------------------------------------------
|
| 34 |
+
# GradeResult
|
| 35 |
+
# ---------------------------------------------------------------------------
|
| 36 |
+
|
| 37 |
+
|
| 38 |
class GradeResult:
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
reward: int,
|
| 42 |
+
breakdown: list[str],
|
| 43 |
+
correct: bool,
|
| 44 |
+
bug_type: str = "unknown",
|
| 45 |
+
bug_severity: int = 0,
|
| 46 |
+
) -> None:
|
| 47 |
self.reward = reward
|
| 48 |
self.breakdown = breakdown
|
| 49 |
self.correct = correct
|
| 50 |
self.bug_type = bug_type
|
| 51 |
self.bug_severity = bug_severity
|
| 52 |
|
| 53 |
+
def summary(self) -> str:
|
|
|
|
| 54 |
lines = [
|
| 55 |
"GRADE SUMMARY",
|
| 56 |
"-" * 25,
|
|
|
|
| 58 |
f"Correct: {'Yes' if self.correct else 'No'}",
|
| 59 |
f"Bug was: {self.bug_type} (severity {self.bug_severity})",
|
| 60 |
"",
|
| 61 |
+
"Breakdown:",
|
| 62 |
]
|
| 63 |
for entry in self.breakdown:
|
| 64 |
lines.append(f" {entry}")
|
|
|
|
| 66 |
lines.append(f"Total: {self.reward:+d}")
|
| 67 |
return "\n".join(lines)
|
| 68 |
|
| 69 |
+
def to_dict(self) -> dict:
|
|
|
|
| 70 |
return {
|
| 71 |
"reward": self.reward,
|
| 72 |
"correct": self.correct,
|
| 73 |
"bug_type": self.bug_type,
|
| 74 |
"bug_severity": self.bug_severity,
|
| 75 |
+
"breakdown": self.breakdown,
|
| 76 |
}
|
| 77 |
|
| 78 |
+
|
| 79 |
+
# ---------------------------------------------------------------------------
|
| 80 |
+
# grade()
|
| 81 |
+
# ---------------------------------------------------------------------------
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def grade(ai_action: dict, ground_truth: dict | None) -> GradeResult:
|
| 85 |
"""
|
| 86 |
+
Grade a single AI review against the ground truth.
|
| 87 |
+
|
| 88 |
+
ai_action keys : type, category, line_hint, comment, severity
|
| 89 |
+
ground_truth keys: bug → {type, severity, description, line_hint}
|
| 90 |
"""
|
| 91 |
if ground_truth is None or "bug" not in ground_truth:
|
| 92 |
return GradeResult(reward=0, breakdown=["No ground truth available"], correct=False)
|
| 93 |
+
|
| 94 |
bug = ground_truth["bug"]
|
| 95 |
+
bug_type = bug.get("type", "none")
|
| 96 |
+
bug_severity = bug.get("severity", 0)
|
| 97 |
+
is_clean = bug_type in ("none", "ok") or bug_severity == 0
|
| 98 |
+
|
| 99 |
+
reward = 0
|
| 100 |
+
breakdown: list[str] = []
|
| 101 |
+
correct = False
|
| 102 |
+
|
| 103 |
+
ai_type = ai_action.get("type", "approve")
|
| 104 |
+
ai_category = ai_action.get("category", "ok")
|
| 105 |
+
ai_comment = ai_action.get("comment", "")
|
| 106 |
+
ai_severity = ai_action.get("severity", 3)
|
| 107 |
ai_line_hint = ai_action.get("line_hint", "")
|
| 108 |
|
| 109 |
+
# ------------------------------------------------------------------
|
| 110 |
+
# CASE 1: AI flagged something
|
| 111 |
+
# ------------------------------------------------------------------
|
| 112 |
if ai_type == "flag":
|
| 113 |
+
|
| 114 |
+
if ai_category == bug_type:
|
| 115 |
+
# ✅ Perfect category match
|
| 116 |
correct = True
|
| 117 |
+
|
| 118 |
+
if bug_type == "security":
|
| 119 |
+
reward += REWARD_SECURITY_CATCH
|
| 120 |
+
breakdown.append(f"+{REWARD_SECURITY_CATCH}: caught a security vulnerability")
|
| 121 |
+
elif bug_type == "logic":
|
| 122 |
+
reward += REWARD_LOGIC_CATCH
|
| 123 |
+
breakdown.append(f"+{REWARD_LOGIC_CATCH}: caught a logic bug")
|
|
|
|
| 124 |
else:
|
| 125 |
+
reward += REWARD_OTHER_CATCH
|
| 126 |
+
breakdown.append(f"+{REWARD_OTHER_CATCH}: caught a style/other issue")
|
| 127 |
+
|
| 128 |
+
# Severity accuracy
|
| 129 |
+
sev_diff = abs(ai_severity - bug_severity)
|
| 130 |
+
if sev_diff == 0:
|
| 131 |
+
reward += REWARD_SEVERITY_EXACT
|
| 132 |
+
breakdown.append(f"+{REWARD_SEVERITY_EXACT}: severity rating exact")
|
| 133 |
+
elif sev_diff == 1:
|
| 134 |
+
reward += REWARD_SEVERITY_CLOSE
|
| 135 |
+
breakdown.append(f"+{REWARD_SEVERITY_CLOSE}: severity rating close")
|
| 136 |
else:
|
| 137 |
+
breakdown.append("+0: severity rating off")
|
| 138 |
+
|
| 139 |
+
# Comment quality
|
| 140 |
if len(ai_comment) > 40:
|
| 141 |
+
reward += REWARD_COMMENT_LONG
|
| 142 |
+
breakdown.append(f"+{REWARD_COMMENT_LONG}: detailed comment")
|
| 143 |
elif len(ai_comment) > 15:
|
| 144 |
+
reward += REWARD_COMMENT_SHORT
|
| 145 |
+
breakdown.append(f"+{REWARD_COMMENT_SHORT}: brief comment")
|
| 146 |
else:
|
| 147 |
breakdown.append("+0: comment too short or missing")
|
| 148 |
+
|
| 149 |
+
# Line hint
|
| 150 |
if len(ai_line_hint) > 5:
|
| 151 |
+
reward += REWARD_LINE_HINT
|
| 152 |
+
breakdown.append(f"+{REWARD_LINE_HINT}: line location specified")
|
| 153 |
else:
|
| 154 |
breakdown.append("+0: no line location given")
|
| 155 |
+
|
| 156 |
+
elif not is_clean:
|
| 157 |
+
# ⚠️ Right decision (it IS a bug), wrong category → partial credit
|
| 158 |
+
reward += REWARD_PARTIAL_CREDIT
|
| 159 |
+
breakdown.append(
|
| 160 |
+
f"+{REWARD_PARTIAL_CREDIT}: partial credit — flagged correctly but "
|
| 161 |
+
f"wrong category ('{ai_category}' vs '{bug_type}')"
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
else:
|
| 165 |
+
# ❌ False positive — code was clean
|
| 166 |
+
reward += PENALTY_WRONG_CATEGORY
|
| 167 |
+
breakdown.append(
|
| 168 |
+
f"{PENALTY_WRONG_CATEGORY}: false positive — code was clean, "
|
| 169 |
+
f"flagged as '{ai_category}'"
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
# ------------------------------------------------------------------
|
| 173 |
+
# CASE 2: AI approved
|
| 174 |
+
# ------------------------------------------------------------------
|
| 175 |
elif ai_type == "approve":
|
| 176 |
+
|
| 177 |
+
if is_clean:
|
| 178 |
+
# ✅ Correctly approved clean code — small positive reward
|
| 179 |
+
correct = True
|
| 180 |
+
reward += REWARD_CLEAN_APPROVE
|
| 181 |
+
breakdown.append(f"+{REWARD_CLEAN_APPROVE}: correctly approved clean code")
|
| 182 |
+
|
|
|
|
|
|
|
| 183 |
else:
|
| 184 |
+
# ❌ Missed a real bug
|
| 185 |
+
if bug_severity >= 5:
|
| 186 |
+
reward += PENALTY_MISS_CRITICAL
|
| 187 |
+
breakdown.append(f"{PENALTY_MISS_CRITICAL}: missed critical severity-5 bug ({bug_type})")
|
| 188 |
+
elif bug_severity >= 4:
|
| 189 |
+
reward += PENALTY_MISS_HIGH
|
| 190 |
+
breakdown.append(f"{PENALTY_MISS_HIGH}: missed high severity-4 bug ({bug_type})")
|
| 191 |
+
elif bug_severity >= 3:
|
| 192 |
+
reward += PENALTY_MISS_MEDIUM
|
| 193 |
+
breakdown.append(f"{PENALTY_MISS_MEDIUM}: missed medium severity-3 bug ({bug_type})")
|
| 194 |
+
else:
|
| 195 |
+
reward += PENALTY_MISS_LOW
|
| 196 |
+
breakdown.append(f"{PENALTY_MISS_LOW}: missed low severity bug ({bug_type})")
|
| 197 |
+
|
| 198 |
+
# ------------------------------------------------------------------
|
| 199 |
+
# CASE 3: Unknown action
|
| 200 |
+
# ------------------------------------------------------------------
|
| 201 |
else:
|
| 202 |
+
reward += PENALTY_UNKNOWN_ACTION
|
| 203 |
+
breakdown.append(f"{PENALTY_UNKNOWN_ACTION}: unknown action type '{ai_type}'")
|
| 204 |
+
|
| 205 |
return GradeResult(
|
| 206 |
+
reward=reward,
|
| 207 |
+
breakdown=breakdown,
|
| 208 |
+
correct=correct,
|
| 209 |
+
bug_type=bug_type,
|
| 210 |
+
bug_severity=bug_severity,
|
| 211 |
)
|
| 212 |
|
| 213 |
+
|
| 214 |
+
# ---------------------------------------------------------------------------
|
| 215 |
+
# batch_grade()
|
| 216 |
+
# ---------------------------------------------------------------------------
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def batch_grade(episodes: list[dict]) -> dict:
|
| 220 |
+
"""Summarise grading across multiple episodes."""
|
| 221 |
+
results_list: list[dict] = []
|
| 222 |
+
total_reward = 0
|
| 223 |
+
correct_count = 0
|
| 224 |
+
best_score = -float("inf")
|
| 225 |
+
worst_score = float("inf")
|
| 226 |
caught_security = 0
|
| 227 |
+
caught_logic = 0
|
| 228 |
false_positives = 0
|
| 229 |
+
missed_bugs = 0
|
| 230 |
+
clean_approved = 0
|
| 231 |
+
|
| 232 |
for ep in episodes:
|
| 233 |
res = grade(ep["ai_action"], ep["ground_truth"])
|
| 234 |
+
d = res.to_dict()
|
| 235 |
+
results_list.append(d)
|
| 236 |
+
|
| 237 |
+
total_reward += d["reward"]
|
| 238 |
+
if d["correct"]:
|
|
|
|
|
|
|
| 239 |
correct_count += 1
|
| 240 |
+
if d["bug_type"] == "security":
|
| 241 |
caught_security += 1
|
| 242 |
+
elif d["bug_type"] == "logic":
|
| 243 |
caught_logic += 1
|
| 244 |
+
elif d["bug_type"] in ("none", "ok"):
|
| 245 |
+
clean_approved += 1
|
| 246 |
else:
|
| 247 |
ai_type = ep["ai_action"].get("type")
|
| 248 |
if ai_type == "flag":
|
| 249 |
false_positives += 1
|
| 250 |
elif ai_type == "approve":
|
| 251 |
missed_bugs += 1
|
| 252 |
+
|
| 253 |
+
if d["reward"] > best_score:
|
| 254 |
+
best_score = d["reward"]
|
| 255 |
+
if d["reward"] < worst_score:
|
| 256 |
+
worst_score = d["reward"]
|
| 257 |
+
|
| 258 |
count = len(episodes)
|
| 259 |
if count == 0:
|
| 260 |
return {"error": "no episodes provided"}
|
| 261 |
+
|
| 262 |
return {
|
| 263 |
+
"results": results_list,
|
| 264 |
+
"total_reward": total_reward,
|
| 265 |
+
"average_reward": total_reward / count,
|
| 266 |
+
"accuracy": correct_count / count,
|
| 267 |
+
"best_score": best_score,
|
| 268 |
+
"worst_score": worst_score,
|
| 269 |
"caught_security": caught_security,
|
| 270 |
+
"caught_logic": caught_logic,
|
| 271 |
+
"clean_approved": clean_approved,
|
| 272 |
"false_positives": false_positives,
|
| 273 |
+
"missed_bugs": missed_bugs,
|
| 274 |
}
|
| 275 |
|
| 276 |
+
|
| 277 |
+
# ---------------------------------------------------------------------------
|
| 278 |
+
# Test block
|
| 279 |
+
# ---------------------------------------------------------------------------
|
| 280 |
+
|
| 281 |
if __name__ == "__main__":
|
| 282 |
+
import pprint
|
| 283 |
+
|
| 284 |
test_cases = [
|
| 285 |
# 1. Perfect security catch
|
| 286 |
+
{
|
| 287 |
+
"ai_action": {"type": "flag", "category": "security",
|
| 288 |
+
"line_hint": "line 3 query string",
|
| 289 |
+
"comment": "SQL injection — user input directly in query", "severity": 5},
|
| 290 |
+
"ground_truth": {"bug": {"type": "security", "severity": 5,
|
| 291 |
+
"description": "SQL injection", "line_hint": "query line"}},
|
| 292 |
+
},
|
| 293 |
+
# 2. Partial credit (right decision, wrong category)
|
| 294 |
+
{
|
| 295 |
+
"ai_action": {"type": "flag", "category": "logic",
|
| 296 |
+
"line_hint": "line 5", "comment": "this looks wrong", "severity": 2},
|
| 297 |
+
"ground_truth": {"bug": {"type": "security", "severity": 5,
|
| 298 |
+
"description": "plain text password", "line_hint": "db.insert"}},
|
| 299 |
+
},
|
| 300 |
+
# 3. Missed critical bug
|
| 301 |
+
{
|
| 302 |
+
"ai_action": {"type": "approve", "category": "ok",
|
| 303 |
+
"line_hint": "", "comment": "", "severity": 0},
|
| 304 |
+
"ground_truth": {"bug": {"type": "security", "severity": 5,
|
| 305 |
+
"description": "SQL injection", "line_hint": "query line"}},
|
| 306 |
+
},
|
| 307 |
+
# 4. Correctly approved clean code ← NEW
|
| 308 |
+
{
|
| 309 |
+
"ai_action": {"type": "approve", "category": "ok",
|
| 310 |
+
"line_hint": "", "comment": "", "severity": 0},
|
| 311 |
+
"ground_truth": {"bug": {"type": "none", "severity": 0,
|
| 312 |
+
"description": "clean code", "line_hint": ""}},
|
| 313 |
+
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
]
|
| 315 |
+
|
| 316 |
print("RUNNING GRADER TESTS...\n")
|
|
|
|
| 317 |
for i, case in enumerate(test_cases, 1):
|
| 318 |
print(f"CASE {i}:")
|
| 319 |
result = grade(case["ai_action"], case["ground_truth"])
|
| 320 |
print(result.summary())
|
| 321 |
print()
|
| 322 |
+
|
| 323 |
print("BATCH RESULTS:")
|
|
|
|
| 324 |
pprint.pprint(batch_grade(test_cases))
|
|
Binary file (3.62 kB)
|
|
|
|
@@ -1,3 +1,15 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
blinker==1.9.0
|
| 2 |
+
click==8.3.1
|
| 3 |
+
colorama==0.4.6
|
| 4 |
+
Deprecated==1.3.1
|
| 5 |
+
Flask==3.1.3
|
| 6 |
+
Flask-Limiter==4.1.1
|
| 7 |
+
itsdangerous==2.2.0
|
| 8 |
+
Jinja2==3.1.6
|
| 9 |
+
limits==5.8.0
|
| 10 |
+
MarkupSafe==3.0.3
|
| 11 |
+
ordered-set==4.1.0
|
| 12 |
+
packaging==26.0
|
| 13 |
+
typing_extensions==4.15.0
|
| 14 |
+
Werkzeug==3.1.8
|
| 15 |
+
wrapt==2.1.2
|
|
@@ -1,101 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
-
import sys
|
| 3 |
import os
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
| 5 |
from agent import review
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
"""
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
if verbose:
|
| 13 |
-
print(f"---
|
| 14 |
-
|
| 15 |
-
# Initialize the code review environment
|
| 16 |
-
env = CodeReviewEnv("episodes.json", "answers.json")
|
| 17 |
-
history = []
|
| 18 |
-
|
| 19 |
for i in range(1, num_episodes + 1):
|
| 20 |
-
|
| 21 |
-
obs = env.reset()
|
| 22 |
-
|
| 23 |
-
# 2. Get AI review
|
| 24 |
ai_action = review(obs["code"])
|
| 25 |
-
|
| 26 |
-
# 3. Step the environment
|
| 27 |
reward, done, info = env.step(ai_action)
|
| 28 |
-
|
| 29 |
-
|
|
|
|
| 30 |
record = {
|
| 31 |
-
"episode_index": i,
|
| 32 |
-
"episode_id":
|
| 33 |
-
"snippet_id":
|
| 34 |
-
"reward":
|
| 35 |
-
"ai_said":
|
| 36 |
-
"truth":
|
| 37 |
-
"correct":
|
| 38 |
-
"breakdown":
|
|
|
|
| 39 |
}
|
| 40 |
history.append(record)
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
if verbose:
|
| 43 |
status = "✓ CORRECT" if info["correct"] else "✗ WRONG"
|
| 44 |
-
print(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
# Generate summary statistics
|
| 47 |
stats = env.get_stats()
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
if verbose:
|
| 59 |
-
print("\n--- Training Complete ---")
|
| 60 |
-
print(f"Total Reward:
|
| 61 |
-
print(f"
|
| 62 |
-
print(f"
|
| 63 |
-
|
|
|
|
| 64 |
return output_data
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
|
|
|
|
|
|
| 70 |
return
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
stats = data["overall_stats"]
|
| 76 |
-
history = data["history"]
|
| 77 |
-
|
| 78 |
print("\n--- PERFORMANCE ANALYSIS ---")
|
| 79 |
-
print(f"Episodes:
|
| 80 |
-
print(f"
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
if __name__ == "__main__":
|
| 91 |
-
mode = "default"
|
| 92 |
-
|
| 93 |
-
mode = sys.argv[1]
|
| 94 |
-
|
| 95 |
if mode == "short":
|
| 96 |
run_training(num_episodes=10)
|
| 97 |
elif mode == "analyze":
|
| 98 |
analyze_history()
|
|
|
|
|
|
|
| 99 |
else:
|
| 100 |
-
# Default behavior: run 5 episodes
|
| 101 |
run_training(num_episodes=5)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
training_loop.py — CLI training loop with checkpointing.
|
| 3 |
+
|
| 4 |
+
Key improvements:
|
| 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 the training loop.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
num_episodes: How many episodes to run this session.
|
| 54 |
+
verbose: Print progress to stdout.
|
| 55 |
+
resume: If True, load and continue from the last checkpoint.
|
| 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 |
+
if verbose:
|
| 61 |
+
print(f"Resuming from checkpoint: {checkpoint['episodes_run']} episodes already run.")
|
| 62 |
+
|
| 63 |
+
env = CodeReviewEnv()
|
| 64 |
+
history: list[dict] = checkpoint["history"]
|
| 65 |
+
total_reward: int = checkpoint["total_reward"]
|
| 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 |
+
obs = env.reset()
|
|
|
|
|
|
|
|
|
|
| 74 |
ai_action = review(obs["code"])
|
|
|
|
|
|
|
| 75 |
reward, done, info = env.step(ai_action)
|
| 76 |
+
|
| 77 |
+
total_reward += reward
|
| 78 |
+
|
| 79 |
record = {
|
| 80 |
+
"episode_index": start_ep + i,
|
| 81 |
+
"episode_id": obs["episode_id"],
|
| 82 |
+
"snippet_id": obs["snippet_id"],
|
| 83 |
+
"reward": reward,
|
| 84 |
+
"ai_said": info["ai_said"],
|
| 85 |
+
"truth": info["truth"],
|
| 86 |
+
"correct": info["correct"],
|
| 87 |
+
"breakdown": info["breakdown"],
|
| 88 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 89 |
}
|
| 90 |
history.append(record)
|
| 91 |
+
|
| 92 |
+
# Save checkpoint after every episode
|
| 93 |
+
_save_checkpoint({
|
| 94 |
+
"total_reward": total_reward,
|
| 95 |
+
"episodes_run": start_ep + i,
|
| 96 |
+
"history": history,
|
| 97 |
+
})
|
| 98 |
+
|
| 99 |
if verbose:
|
| 100 |
status = "✓ CORRECT" if info["correct"] else "✗ WRONG"
|
| 101 |
+
print(
|
| 102 |
+
f"Ep {start_ep + i:03d} | {obs['episode_id']} | "
|
| 103 |
+
f"{info['ai_said']:22} | {status} | Reward: {reward:+3d} | "
|
| 104 |
+
f"Cumulative: {total_reward}"
|
| 105 |
+
)
|
| 106 |
|
|
|
|
| 107 |
stats = env.get_stats()
|
| 108 |
+
output_data = {"overall_stats": stats, "history": history}
|
| 109 |
+
|
| 110 |
+
# Save timestamped run file in runs/
|
| 111 |
+
os.makedirs(RUNS_DIR, exist_ok=True)
|
| 112 |
+
ts = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
|
| 113 |
+
run_file = os.path.join(RUNS_DIR, f"run_{ts}.json")
|
| 114 |
+
with open(run_file, "w") as f:
|
| 115 |
+
json.dump(output_data, f, indent=2)
|
| 116 |
+
|
|
|
|
| 117 |
if verbose:
|
| 118 |
+
print(f"\n--- Training Complete ---")
|
| 119 |
+
print(f"Total Reward: {total_reward}")
|
| 120 |
+
print(f"Session Acc.: {stats['accuracy'] * 100:.1f}%")
|
| 121 |
+
print(f"Run saved to: {run_file}")
|
| 122 |
+
print(f"Checkpoint: {CHECKPOINT_FILE}")
|
| 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)
|