import math from typing import Dict, Any, Tuple from openenv_core.env_server.interfaces import Environment from models import CodeReviewAction, CodeReviewObservation, CodeReviewState # Hunk Dataset strictly adhering to the 15 required categories HUNKS_DATA = [ {"id": "h1", "language": "python", "diff": "- query = f'SELECT * FROM users WHERE username = {user_input}'\n+ query = 'SELECT * FROM users WHERE username = %s'", "true_issue": "security", "true_severity": "critical", "true_fix": "Use parameterized queries or prepared statements to prevent SQL injection vulnerability."}, {"id": "h2", "language": "python", "diff": "- result = eval(user_input)\n+ import ast\n+ result = ast.literal_eval(user_input)", "true_issue": "security", "true_severity": "critical", "true_fix": "Replace dangerous eval with ast literal_eval to prevent arbitrary code execution."}, {"id": "h3", "language": "python", "diff": "- db_pass = 'supersecret123'\n+ import os\n+ db_pass = os.environ.get('DB_PASS')", "true_issue": "security", "true_severity": "critical", "true_fix": "Remove hardcoded password and use environment variables for secrets."}, {"id": "h4", "language": "python", "diff": "- try:\n- process()\n- except:\n- pass\n+ try:\n+ process()\n+ except ValueError as e:\n+ logging.error(e)", "true_issue": "bug", "true_severity": "major", "true_fix": "Avoid bare except pass. Catch specific exceptions and log the error."}, {"id": "h5", "language": "python", "diff": "- for i in range(len(items) + 1):\n- print(items[i])\n+ for i in range(len(items)):\n+ print(items[i])", "true_issue": "bug", "true_severity": "major", "true_fix": "Fix off-by-one error in the loop to prevent IndexError bounds."}, {"id": "h6", "language": "python", "diff": "- return data['user']['profile']\n+ return data.get('user', {}).get('profile')", "true_issue": "bug", "true_severity": "major", "true_fix": "Add missing null check dictionary get method to avoid KeyError."}, {"id": "h7", "language": "python", "diff": "- squared = [x**2 for x in items]\n- return sum(squared)\n+ return sum(x**2 for x in items)", "true_issue": "performance", "true_severity": "minor", "true_fix": "Replace unnecessary list comprehension with a generator expression to save memory."}, {"id": "h8", "language": "python", "diff": "- for item in data:\n- if my_dict[key] == item:\n+ val = my_dict[key]\n+ for item in data:\n+ if val == item:", "true_issue": "performance", "true_severity": "minor", "true_fix": "Extract repeated dict lookup outside the loop to improve performance."}, {"id": "h9", "language": "python", "diff": "- def my_func(a,b=1):\n+ def my_func(a, b=1):", "true_issue": "style", "true_severity": "info", "true_fix": "Fix PEP8 spacing around default arguments."}, {"id": "h10", "language": "python", "diff": "- if is_valid == True:\n+ if is_valid:", "true_issue": "style", "true_severity": "minor", "true_fix": "Remove redundant True comparison for boolean variables."}, {"id": "h11", "language": "python", "diff": "- count = 0\n- def increment():\n- global count\n- count += 1\n+ class Counter:\n+ def __init__(self): self.count = 0", "true_issue": "bug", "true_severity": "major", "true_fix": "Avoid global variable mutation use a class or return values."}, {"id": "h12", "language": "python", "diff": "- ratio = total / count\n+ ratio = total / count if count != 0 else 0", "true_issue": "bug", "true_severity": "critical", "true_fix": "Add division without zero check to prevent ZeroDivisionError crash."}, {"id": "h13", "language": "python", "diff": "- def append_item(item, lst=[]):\n+ def append_item(item, lst=None):\n+ if lst is None: lst = []", "true_issue": "bug", "true_severity": "major", "true_fix": "Fix mutable default argument list to avoid shared state across calls."}, {"id": "h14", "language": "python", "diff": "- s = ''\n- for w in words:\n- s += w\n+ s = ''.join(words)", "true_issue": "performance", "true_severity": "minor", "true_fix": "Use string join instead of string concatenation in loop."}, {"id": "h15", "language": "python", "diff": "- def get_name(user_id):\n+ def get_name(user_id: int) -> str:", "true_issue": "style", "true_severity": "info", "true_fix": "Add missing return type annotation for better static analysis."} ] TASKS = { "easy_classify": {"hunks": 5, "max_steps": 15}, "medium_severity": {"hunks": 8, "max_steps": 25}, "hard_write_fix": {"hunks": 12, "max_steps": 40} } class CodeReviewEnv(Environment): def __init__(self): self._state = CodeReviewState() self.target_hunks = [] self.current_hunk_idx = 0 self.max_steps = 0 def reset(self, seed=None, episode_id=None, task_id="easy_classify", **kwargs): self._state = CodeReviewState(episode_id=episode_id, task_id=task_id) config = TASKS.get(task_id, TASKS["easy_classify"]) self.max_steps = config["max_steps"] self.target_hunks = HUNKS_DATA[:config["hunks"]] self.current_hunk_idx = 0 return self._get_obs(done=False, reward=0.0) @property def state(self) -> CodeReviewState: return self._state def _get_obs(self, done: bool, reward: float, feedback: str = None) -> CodeReviewObservation: remaining = [{"id": h["id"], "language": h["language"], "diff": h["diff"]} for h in self.target_hunks[self.current_hunk_idx:]] current = remaining[0] if remaining else None progress = self.current_hunk_idx / len(self.target_hunks) if self.target_hunks else 1.0 return CodeReviewObservation( done=done, reward=reward, hunks=remaining, current_hunk=current, task_id=self._state.task_id, progress=progress, step_count=self._state.step_count, last_feedback=feedback ) def _grade_classify(self, pred: str, true: str) -> float: if pred == true: return 1.0 close_misses = [{"bug", "security"}, {"style", "performance"}] if {pred, true} in close_misses: return 0.4 return 0.0 def _grade_severity(self, pred: str, true: str) -> float: mapping = {"critical": 4, "major": 3, "minor": 2, "info": 1} p_val = mapping.get(pred, 0) t_val = mapping.get(true, 0) if p_val == 0: return 0.0 return max(0.0, 1.0 - abs(p_val - t_val) * 0.3) def _grade_fix(self, pred: str, true: str) -> float: if not pred: return 0.0 score = 0.1 stopwords = {"a", "the", "is", "to", "of", "and", "or", "in", "it", "use", "with"} true_kws = set(true.lower().split()) - stopwords agent_kws = set(pred.lower().split()) - stopwords if true_kws: overlap = len(true_kws.intersection(agent_kws)) / len(true_kws) score += overlap * 0.7 if len(pred) > 50: score += 0.1 if len(pred) > 120: score += 0.1 return min(1.0, score) def step(self, action: CodeReviewAction, **kwargs) -> CodeReviewObservation: self._state.step_count += 1 reward = 0.0 feedback = "" done = False if self.current_hunk_idx >= len(self.target_hunks): return self._get_obs(done=True, reward=0.0, feedback="Episode complete.") true_hunk = self.target_hunks[self.current_hunk_idx] # Penalties if action.hunk_id != true_hunk["id"]: return self._get_obs(done=False, reward=0.001, feedback=f"Invalid hunk_id. Expected {true_hunk['id']}") if action.action_type == "skip": return self._get_obs(done=False, reward=0.001, feedback="Skip penalty applied.") if action.hunk_id in self._state.visited_hunks: return self._get_obs(done=False, reward=0.001, feedback="Already reviewed this hunk.") self._state.visited_hunks.append(action.hunk_id) # Grader Logic c_score = self._grade_classify(action.issue_type, true_hunk["true_issue"]) if true_hunk["true_issue"] in ["security", "bug"] and action.issue_type == "none": c_score = -0.05 s_score = self._grade_severity(action.severity, true_hunk["true_severity"]) f_score = self._grade_fix(action.suggestion, true_hunk["true_fix"]) if self._state.task_id == "easy_classify": reward = c_score elif self._state.task_id == "medium_severity": reward = (c_score * 0.4) + (s_score * 0.6) else: # hard_write_fix reward = (c_score * 0.2) + (s_score * 0.3) + (f_score * 0.5) # Strict bounds (0, 1) for Hackathon Validator reward = min(0.999, max(0.001, reward)) self._state.accumulated_rewards += reward self.current_hunk_idx += 1 if self._state.step_count >= self.max_steps or self.current_hunk_idx >= len(self.target_hunks): done = True return self._get_obs(done=done, reward=reward, feedback=f"Step scored: {reward:.2f}")