sharancreates's picture
bugs fixed
b7c56ea
Raw History Blame Contribute Delete
6.59 kB
import os
import ast
import random
from typing import Tuple, Dict, Any, Optional, List
# Updated imports based on your library's structure
from openenv.core.env_server import Environment
from models import Action, Observation, Reward, State
class CodeReviewEnv(Environment):
def __init__(self):
super().__init__()
self.current_task_id = "style-cleanup"
self.code = ""
self.step_count = 0
self.max_steps = 5
def reset(self, *, seed: Optional[int] = None, options: Optional[Dict[str, Any]] = None) -> Tuple[Observation, Dict[str, Any]]:
"""Standard OpenEnv Reset Protocol: returns (obs, info)"""
if seed is not None:
random.seed(seed)
task_id = options.get("task_id", "style-cleanup") if options else "style-cleanup"
self.current_task_id = task_id
self.step_count = 0
# Load the buggy code from our data folder
file_map = {
"style-cleanup": "data/style.py",
"efficiency-boost": "data/logic.py",
"security-audit": "data/security.py"
}
file_path = file_map.get(task_id, "data/style.py")
try:
with open(file_path, "r") as f:
self.code = f.read()
except Exception:
self.code = "# Error loading source file"
return self._get_observation(), {}
def step(self, action: Action) -> Tuple[Observation, float, bool, Dict[str, Any]]:
"""Standard OpenEnv Step Protocol: returns (obs, reward, done, info)"""
self.step_count += 1
reward_val = 0.01
done = False
if action.action_type == "apply_fix":
self.code = action.content
reward_val = self._calculate_reward()
elif action.action_type == "submit":
reward_val = self._calculate_reward()
done = True
if self.step_count >= self.max_steps:
done = True
# Mathematical Clamp Armor: min(max(reward, 0.01), 0.99)
clamped_reward = min(max(reward_val, 0.01), 0.99)
return self._get_observation(), clamped_reward, done, {}
def state(self) -> State:
"""Standard OpenEnv State Protocol: returns a State object"""
return State(
current_task_id=self.current_task_id,
step_count=self.step_count,
code=self.code
)
def _get_observation(self) -> Observation:
"""Returns what the agent sees right now."""
return Observation(
file_name=f"{self.current_task_id}.py",
code_content=self.code,
diff="Changes applied to buffer.",
linter_report=self._mock_linter(),
current_task=self.current_task_id
)
def _mock_linter(self):
"""A simple linter to guide the agent."""
errors = []
if "import sys" in self.code and self.current_task_id == "style-cleanup":
errors.append("L001: Unused import 'sys' detected.")
if "f\"SELECT" in self.code and self.current_task_id == "security-audit":
errors.append("S001: SQL Injection vulnerability detected.")
return errors
def _calculate_reward(self) -> float:
"""Smart AST Grader v2: Sophisticated code analysis."""
score = 0.01
try:
tree = ast.parse(self.code)
if self.current_task_id == "style-cleanup":
imported_names = set()
used_names = set()
for node in ast.walk(tree):
if isinstance(node, (ast.Import, ast.ImportFrom)):
for alias in node.names:
imported_names.add(alias.asname or alias.name)
elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
used_names.add(node.id)
if 'sys' not in imported_names: score += 0.49
if "Indentation" in self.code and "corrected" in self.code: score += 0.49
elif self.current_task_id == "security-audit":
query_vars_with_fstrings = set()
uses_vulnerable_execute = False
uses_parameterized_execute = False
for node in ast.walk(tree):
if isinstance(node, ast.Assign):
if isinstance(node.value, ast.JoinedStr):
for target in node.targets:
if isinstance(target, ast.Name):
query_vars_with_fstrings.add(target.id)
if isinstance(node, ast.Call) and hasattr(node.func, 'attr') and node.func.attr == 'execute':
arg0 = node.args[0]
if isinstance(arg0, ast.JoinedStr):
uses_vulnerable_execute = True
elif isinstance(arg0, ast.Name) and arg0.id in query_vars_with_fstrings:
uses_vulnerable_execute = True
if len(node.args) > 1:
uses_parameterized_execute = True
elif isinstance(arg0, (ast.Str, ast.Constant)):
val = arg0.s if hasattr(arg0, 's') else arg0.value
if "?" in val or "%s" in val:
uses_parameterized_execute = True
if not uses_vulnerable_execute: score += 0.5
if uses_parameterized_execute: score += 0.49
elif self.current_task_id == "efficiency-boost":
loop_nodes = (ast.For, ast.While, ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)
max_depth = 0
for node in ast.walk(tree):
if isinstance(node, loop_nodes):
current_depth = 1
for subnode in ast.walk(node):
if subnode is node: continue
if isinstance(subnode, loop_nodes):
current_depth = 2
break
max_depth = max(max_depth, current_depth)
if max_depth == 1: score = 0.99
elif max_depth >= 2: score = 0.2
else: score = 0.01
except Exception:
score = 0.01
return score