Update environment.py
Browse files6 unmodified lines7891011121314151617181920212223247 unmodified lines3233343536373839404142434445464748495051525354555657585960616263646566676838 unmodified lines1071081091101111121131141151161171181191201211229 unmodified lines13213313413513613713813914014114214314414514614714814915015115215311 unmodified lines16516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020123 unmodified lines2252262272282292302312322332342352362372382392402412429 unmodified lines25225325425525625725825926018 unmodified lines27928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138236 unmodified lines41942042142242342442542642742842915 unmodified lines4454464474484494504511 unmodified line4534544554564574584594604614624634644659 unmodified lines4754764774784794804812 unmodified lines4844854864874884894904914924934944954964974984995005015025035045055066 unmodified lines5135145155165175185 unmodified lines5245255265275285295305315325335345355365375385395405415425435445455465471 unmodified line54955055155255355455555655755855956056156256356456556656756856914 unmodified lines5845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206 unmodified linesimport refrom dataclasses import dataclass, fieldfrom typing import Tuple, Dict, Any, Optional, Listfrom collections import Counterfrom models import (AnyAction, WriteComment, ProposeFix, Execute, Inspect,RunLinter, RunTests, QueryDocs, Skip, Done, AskQuestion,Observation, Reward, State)from grader import RigorousGraderfrom redteam import RedTeamfrom test_runner import TestRunnerfrom author import PersonaAuthorfrom rltool import ToolBox# ======================================================================# FULLY MARKOV OBSERVATION (NOTHING HIDDEN)7 unmodified lines# Code statecode_snippet: strlast_tool_output: str# Current metricscurrent_test_score: floatcurrent_lint_score: floatnegotiation_score: float# CRITICAL: Previous metrics (for understanding deltas)previous_test_score: floatprevious_lint_score: float# CRITICAL: Author internal state (affects reward gating)author_confidence: floatauthor_threshold: float # When author accepts# Progress trackingstep: intmax_steps: intprogress_ratio: float# Tool usage flagstests_run: boollinter_run: booldocs_queried: bool# Action history (with outcomes)last_action_type: straction_history: List[str] # Last 5 actions# Terminal flagdone: bool# Additional contextbug_description: strcomments_count: int38 unmodified linestask: str = "easy"max_steps: int = 10step_penalty: float = 0.01# Curriculum learningauto_difficulty: bool = Falsesuccess_threshold: float = 0.7# Reward shaping parametersdelta_weight: float = 0.3tool_usage_bonus: float = 0.05diversity_bonus: float = 0.03_red_team: Optional[RedTeam] = field(init=False, default=None)_author: Optional[PersonaAuthor] = field(init=False, default=None)9 unmodified lines_step_count: int = field(init=False, default=0)_done: bool = field(init=False, default=False)# State tracking for dense rewards_previous_test_score: float = field(init=False, default=0.0)_previous_lint_score: float = field(init=False, default=0.0)_current_test_score: float = field(init=False, default=0.0)_current_lint_score: float = field(init=False, default=0.0)# Tool usage tracking_tests_run: bool = field(init=False, default=False)_linter_run: bool = field(init=False, default=False)_docs_queried: bool = field(init=False, default=False)# Action history_action_history: List[str] = field(init=False, default_factory=list)_last_action_type: str = field(init=False, default="none")# FIXED: Track CUMULATIVE episode reward_episode_total_reward: float = field(init=False, default=0.0)_episode_rewards: List[float] = field(init=False, default_factory=list)11 unmodified linesself.task = taskself._red_team = RedTeam(task)self._author = PersonaAuthor()task_to_level = {"easy": 0, "medium": 1, "hard": 2,"harder": 3, "hardest": 4}self._difficulty_level = task_to_level[task]self._reset_internal()# ===================================================================def _reset_internal(self):self._step_count = 0self._comments = []self._test_results = Noneself._lint_results = Noneself._doc_results = Noneself._done = False# Reset state trackingself._previous_test_score = 0.0self._previous_lint_score = 0.0self._current_test_score = 0.0self._current_lint_score = 0.0self._tests_run = Falseself._linter_run = Falseself._docs_queried = Falseself._action_history = []self._last_action_type = "none"# FIXED: Reset episode cumulative rewardself._episode_total_reward = 0.023 unmodified lines"""Reset with optional curriculum adjustment."""if self.auto_difficulty and len(self._episode_rewards) > 0:recent_performance = sum(self._episode_rewards[-5:]) / min(5, len(self._episode_rewards))if recent_performance > self.success_threshold and self._difficulty_level < 4:self._difficulty_level += 1print(f"[Curriculum] Increasing difficulty to level {self._difficulty_level}")elif recent_performance < 0.3 and self._difficulty_level > 0:self._difficulty_level -= 1print(f"[Curriculum] Decreasing difficulty to level {self._difficulty_level}")level_to_task = {0: "easy", 1: "medium", 2: "hard", 3: "harder", 4: "hardest"}self.task = level_to_task[self._difficulty_level]self._red_team = RedTeam(self.task)self._reset_internal()return self._get_observation()9 unmodified linesreturn EnhancedObservation(code_snippet=self._current_code,last_tool_output=self._test_results or "",author_response=author_response, # ← fixedcurrent_test_score=self._current_test_score,current_lint_score=self._current_lint_score,negotiation_score=self._author.get_negotiation_score(),18 unmodified linesbug_description=self._bug_description,comments_count=len(self._comments),)# ===================================================================def _compute_dense_reward(self,action: AnyAction,base_reward: float,action_type: str) -> float:"""Stabilized dense reward:- Decoupled terminal bonus- Controlled base scaling- Symmetric delta handling- Reduced reward hacking surface"""# ============================================================# 0. BASE REWARD (controlled contribution)# ============================================================reward = 0.4 * base_reward # ↓ reduce dominance# ============================================================# 1. DELTA REWARDS (primary learning signal)# ============================================================effective_delta_weight = self.delta_weightif action_type == "propose_fix":effective_delta_weight *= 0.4 # stronger cut to avoid overlaptest_delta = self._current_test_score - self._previous_test_scorelint_delta = self._current_lint_score - self._previous_lint_score# symmetric (no artificial dampening for negatives)reward += effective_delta_weight * test_deltareward += 0.5 * effective_delta_weight * lint_delta# ============================================================# 2. TERMINAL SUCCESS BONUS (clean & isolated)# ============================================================if action_type == "propose_fix":if self._current_test_score > 0.95:reward += 0.4 # slightly reduced to prevent saturationelif self._current_test_score > 0.85:reward += 0.2 # smoother gradient instead of jump# ============================================================# 3. TOOL USAGE (early guidance only)# ============================================================if action_type == "run_tests":if not self._tests_run:reward += self.tool_usage_bonusreward += 0.015elif action_type == "run_linter":if not self._linter_run:reward += self.tool_usage_bonusreward += 0.015elif action_type == "query_docs":if not self._docs_queried:reward += self.tool_usage_bonus * 0.5elif action_type == "ask_question":if self._step_count <= 3:reward += 0.02 # tighter window# ============================================================# 4. EXPLORATION (less noisy)# ============================================================if len(self._action_history) >= 3:recent = self._action_history[-3:]unique = len(set(recent))if unique == 1:reward -= 0.05elif unique == 3:reward += self.diversity_bonus * 0.7 # reduce randomness bias# ============================================================# 5. ANTI-HACKING# ============================================================if action_type == "propose_fix":if not self._tests_run:reward -= 0.25 # stronger enforcementif self._step_count < 2:reward -= 0.1if self._tests_run and self._linter_run:reward += 0.02# ============================================================# 6. STEP PENALTY (progress pressure)# ============================================================reward -= self.step_penalty# ============================================================# 7. CLIP (final safety)# ============================================================return max(-1.0, min(1.0, reward))# ===================================================================def _get_action_type(self, action: AnyAction) -> str:36 unmodified lines# Store previous metrics for delta computationself._previous_test_score = self._current_test_scoreself._previous_lint_score = self._current_lint_scorebase_reward = 0.0info = {}action_type = self._get_action_type(action)# Update action historyself._action_history.append(action_type)self._last_action_type = action_type15 unmodified lineslint_output = ToolBox.run_linter(self._current_code)self._lint_results = lint_output[:500]self._test_results = f"[Linter]\n{self._lint_results}"self._current_lint_score = self._run_linter_score(self._current_code)self._linter_run = Truebase_reward = 0.0021 unmodified lineelif isinstance(action, RunTests):runner = TestRunner(self._current_bug_id)score, output = runner.run_tests(self._current_code)self._current_test_score = scoreself._tests_run = Trueself._test_results = f"[Tests] Score: {score:.2f}\n{output[:300]}"base_reward = 0.002if score > 0.8:base_reward += 0.0059 unmodified lines# ==============================================================elif isinstance(action, WriteComment):self._comments.append(f"Agent: {action.comment_text}")response = self._author.respond(agent_comment=action.comment_text,test_results=self._test_results,2 unmodified linesproposed_fix=None,original_code=self._current_code)self._comments.append(f"Author: {response}")self._test_results = f"[Comment] Author: {response[:200]}"base_reward = 0.001elif isinstance(action, AskQuestion):self._comments.append(f"Agent: {action.question}")response = self._author.respond(agent_question=action.question,test_results=self._test_results,lint_results=self._lint_results,doc_results=self._doc_results,proposed_fix=None,original_code=original_buggy)self._comments.append(f"Author: {response}")self._test_results = f"[Question] Author: {response[:200]}"base_reward = 0.0026 unmodified linesbase_reward = -0.05self._done = Trueelse:original_buggy = self._current_codeself._current_code = action.fix_code5 unmodified linesself._current_test_score = test_scoreself._current_lint_score = lint_scorecomponent_reward = (0.4 * test_score +0.15 * lint_score +0.15 * negotiation_score)efficiency = 1.0 - (self._step_count / self.max_steps)component_reward += 0.1 * efficiencyif test_score > 0.8 and lint_score < 0.3:component_reward *= 0.85if test_score < 0.3 and lint_score > 0.8:component_reward *= 0.75if test_score > 0.8 and negotiation_score < 0.3:component_reward *= 0.8threshold = self._author.thresholds.get(self._author.personality, 0.5)if self._author._confidence < threshold:component_reward = max(0.0, component_reward - 0.2)if self._step_count < self.max_steps:self._done = Falseelse:1 unmodified lineelse:self._done = True# Get author's verbal feedback (pushback or acceptance)author_feedback = self._author.respond(agent_comment=f"Proposed fix:\n{action.fix_code}",test_results=f"Score: {test_score:.2f}",lint_results=f"Score: {lint_score:.2f}",doc_results=self._doc_results,proposed_fix=action.fix_code,original_code=self._current_code # note: original should be the buggy code)# Keep the author's reply as the main output (so agent sees it)self._test_results = f"[Fix] Author: {author_feedback[:200]}"self._comments.append(f"Author: {author_feedback}")base_reward = component_rewardself._test_results = f"[Fix] Test: {test_score:.2f}, Lint: {lint_score:.2f}\n{test_output[:200]}"# ==============================================================# TERMINATION ACTIONS14 unmodified linesself._done = True# ==============================================================# COMPUTE FINAL DENSE REWARD (with action_type for fix detection)# ==============================================================final_reward = self._compute_dense_reward(action, base_reward, action_type)# FIXED: Track CUMULATIVE episode rewardself._episode_total_reward += final_reward# ==============================================================# STEP UPDATE# ==============================================================self._step_count += 1if self._step_count >= self.max_steps:self._done = True# FIXED: Store TOTAL episode reward, not just last stepif self._done:self._episode_rewards.append(self._episode_total_reward)obs = self._get_observation()info = {"test_score": self._current_test_score,"lint_score": self._current_lint_score,"test_delta": self._current_test_score - self._previous_test_score,"lint_delta": self._current_lint_score - self._previous_lint_score,"base_reward": base_reward,"final_reward": final_reward,"episode_total": self._episode_total_reward,}return obs, Reward(value=final_reward), self._done, info# ===================================================================6 unmodified lines789101112131415161718192021222324252627282930317 unmodified lines394041424344454647484950515253545556575859606162636465666768697071727374757638 unmodified lines1151161171181191201211221231241251261271281291309 unmodified lines14014114214314414514614714814915015115215315415515615715815916016111 unmodified lines17317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721823 unmodified lines2422432442452462472482492502512522532542552562572582599 unmodified lines26927027127227327427527627718 unmodified lines29629729829930030130236 unmodified lines33934034134234334434534634734815 unmodified lines3643653663673683693701 unmodified line3723733743753763773783793803813823833849 unmodified lines3943953963973983994002 unmodified lines4034044054064074084094104114124134144154164174184194204214224234244256 unmodified lines4324334344354364374385 unmodified lines4444454464474484494504514521 unmodified line45445545645745845946046146246346446546646746846947047147214 unmodified lines4874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285296 unmodified linesimport refrom dataclasses import dataclass, fieldfrom typing import Tuple, Dict, Any, Optional, Listfrom models import (AnyAction, WriteComment, ProposeFix, Execute, Inspect,RunLinter, RunTests, QueryDocs, Skip, Done, AskQuestion,Observation, Reward, State)from redteam import RedTeamfrom test_runner import TestRunnerfrom author import PersonaAuthorfrom rltool import ToolBoxfrom rubrics import (ToolUsageRubric,TestDeltaRubric,LintDeltaRubric,TerminalSuccessRubric,ExplorationRubric,AntiHackingRubric,StepPenaltyRubric,)# ======================================================================# FULLY MARKOV OBSERVATION (NOTHING HIDDEN)7 unmodified lines# Code statecode_snippet: strlast_tool_output: strauthor_response: str = "" # ← ADDED# Current metricscurrent_test_score: floatcurrent_lint_score: floatnegotiation_score: float# CRITICAL: Previous metrics (for understanding deltas)previous_test_score: floatprevious_lint_score: float# CRITICAL: Author internal state (affects reward gating)author_confidence: floatauthor_threshold: float # When author accepts# Progress trackingstep: intmax_steps: intprogress_ratio: float# Tool usage flagstests_run: boollinter_run: booldocs_queried: bool# Action history (with outcomes)last_action_type: straction_history: List[str] # Last 5 actions# Terminal flagdone: bool# Additional contextbug_description: strcomments_count: int38 unmodified linestask: str = "easy"max_steps: int = 10step_penalty: float = 0.01# Curriculum learningauto_difficulty: bool = Falsesuccess_threshold: float = 0.7# Reward shaping parametersdelta_weight: float = 0.3tool_usage_bonus: float = 0.05diversity_bonus: float = 0.03_red_team: Optional[RedTeam] = field(init=False, default=None)_author: Optional[PersonaAuthor] = field(init=False, default=None)9 unmodified lines_step_count: int = field(init=False, default=0)_done: bool = field(init=False, default=False)# State tracking for dense rewards_previous_test_score: float = field(init=False, default=0.0)_previous_lint_score: float = field(init=False, default=0.0)_current_test_score: float = field(init=False, default=0.0)_current_lint_score: float = field(init=False, default=0.0)# Tool usage tracking_tests_run: bool = field(init=False, default=False)_linter_run: bool = field(init=False, default=False)_docs_queried: bool = field(init=False, default=False)# Action history_action_history: List[str] = field(init=False, default_factory=list)_last_action_type: str = field(init=False, default="none")# FIXED: Track CUMULATIVE episode reward_episode_total_reward: float = field(init=False, default=0.0)_episode_rewards: List[float] = field(init=False, default_factory=list)11 unmodified linesself.task = taskself._red_team = RedTeam(task)self._author = PersonaAuthor()self.rubrics = [TestDeltaRubric(weight=self.delta_weight),LintDeltaRubric(weight=self.delta_weight),ToolUsageRubric(bonus=self.tool_usage_bonus),TerminalSuccessRubric(),ExplorationRubric(penalty=-0.05, bonus=self.diversity_bonus * 0.7),AntiHackingRubric(),StepPenaltyRubric(penalty=self.step_penalty),]task_to_level = {"easy": 0, "medium": 1, "hard": 2,"harder": 3, "hardest": 4}self._difficulty_level = task_to_level[task]self._reset_internal()# ===================================================================def _reset_internal(self):self._step_count = 0 # ← FIXEDself._comments = []self._test_results = Noneself._lint_results = Noneself._doc_results = Noneself._done = False# Reset state trackingself._previous_test_score = 0.0self._previous_lint_score = 0.0self._current_test_score = 0.0self._current_lint_score = 0.0self._tests_run = Falseself._linter_run = Falseself._docs_queried = Falseself._action_history = []self._last_action_type = "none"# FIXED: Reset episode cumulative rewardself._episode_total_reward = 0.023 unmodified lines"""Reset with optional curriculum adjustment."""if self.auto_difficulty and len(self._episode_rewards) > 0:recent_performance = sum(self._episode_rewards[-5:]) / min(5, len(self._episode_rewards))if recent_performance > self.success_threshold and self._difficulty_level < 4:self._difficulty_level += 1print(f"[Curriculum] Increasing difficulty to level {self._difficulty_level}")elif recent_performance < 0.3 and self._difficulty_level > 0:self._difficulty_level -= 1print(f"[Curriculum] Decreasing difficulty to level {self._difficulty_level}")level_to_task = {0: "easy", 1: "medium", 2: "hard", 3: "harder", 4: "hardest"}self.task = level_to_task[self._difficulty_level]self._red_team = RedTeam(self.task)self._reset_internal()return self._get_observation()9 unmodified linesreturn EnhancedObservation(code_snippet=self._current_code,last_tool_output=self._test_results or "",author_response=author_response, # ← now field existscurrent_test_score=self._current_test_score,current_lint_score=self._current_lint_score,negotiation_score=self._author.get_negotiation_score(),18 unmodified linesbug_description=self._bug_description,comments_count=len(self._comments),)# ===================================================================def _get_action_type(self, action: AnyAction) -> str:36 unmodified lines# Store previous metrics for delta computationself._previous_test_score = self._current_test_scoreself._previous_lint_score = self._current_lint_scorebase_reward = 0.0action_type = self._get_action_type(action)# Update action historyself._action_history.append(action_type)self._last_action_type = action_type15 unmodified lineslint_output = ToolBox.run_linter(self._current_code)self._lint_results = lint_output[:500]self._test_results = f"[Linter]\n{self._lint_results}"self._current_lint_score = self._run_linter_score(self._current_code)self._linter_run = Truebase_reward = 0.0021 unmodified lineelif isinstance(action, RunTests):runner = TestRunner(self._current_bug_id)score, output = runner.run_tests(self._current_code)self._current_test_score = scoreself._tests_run = Trueself._test_results = f"[Tests] Score: {score:.2f}\n{output[:300]}"base_reward = 0.002if score > 0.8:base_reward += 0.0059 unmodified lines# ==============================================================elif isinstance(action, WriteComment):self._comments.append(f"Agent: {action.comment_text}")response = self._author.respond(agent_comment=action.comment_text,test_results=self._test_results,2 unmodified linesproposed_fix=None,original_code=self._current_code)self._comments.append(f"Author: {response}")self._test_results = f"[Comment] Author: {response[:200]}"base_reward = 0.001elif isinstance(action, AskQuestion):self._comments.append(f"Agent: {action.question}")response = self._author.respond(agent_question=action.question,test_results=self._test_results,lint_results=self._lint_results,doc_results=self._doc_results,proposed_fix=None,original_code=self._current_code # ← FIXED)self._comments.append(f"Author: {response}")self._test_results = f"[Question] Author: {response[:200]}"base_reward = 0.0026 unmodified linesbase_reward = -0.05self._done = Trueelse:# Save original code BEFORE overwriting (for author.respond)original_buggy = self._current_codeself._current_code = action.fix_code5 unmodified linesself._current_test_score = test_scoreself._current_lint_score = lint_score# Author gating – determines if the episode ends, reward is separatethreshold = self._author.thresholds.get(self._author.personality, 0.5)if self._author._confidence < threshold:if self._step_count < self.max_steps:self._done = Falseelse:1 unmodified lineelse:self._done = True# Get author's verbal feedback (pushback/acceptance)author_feedback = self._author.respond(agent_comment=f"Proposed fix:\n{action.fix_code}",test_results=f"Score: {test_score:.2f}",lint_results=f"Score: {lint_score:.2f}",doc_results=self._doc_results,proposed_fix=action.fix_code,original_code=original_buggy # now correctly the buggy code, not the fix)self._test_results = f"[Fix] Author: {author_feedback[:200]}"self._comments.append(f"Author: {author_feedback}")base_reward = 0.001 # rubrics provide the real signal# ==============================================================# TERMINATION ACTIONS14 unmodified linesself._done = True# ==============================================================# STEP UPDATE (before rubric computation so info contains final step)# ==============================================================self._step_count += 1if self._step_count >= self.max_steps:self._done = True# Get fresh observation (needed for rubrics that may read obs)obs = self._get_observation()# Prepare info dict (rubrics may need action_type and deltas)info = {"action_type": action_type,"test_score": self._current_test_score,"lint_score": self._current_lint_score,"test_delta": self._current_test_score - self._previous_test_score,"lint_delta": self._current_lint_score - self._previous_lint_score,"base_reward": base_reward,}# ==============================================================# COMPUTE FINAL REWARD USING RUBRICS# ==============================================================rubric_score = sum(r(self, action, obs, None, self._done, info) for r in self.rubrics)final_reward = 0.4 * base_reward + rubric_scorefinal_reward = max(-1.0, min(1.0, final_reward)) # safety clip# Track cumulative episode rewardself._episode_total_reward += final_reward# Store episode total if doneif self._done:self._episode_rewards.append(self._episode_total_reward)# Complete infoinfo["final_reward"] = final_rewardinfo["episode_total"] = self._episode_total_rewardreturn obs, Reward(value=final_reward), self._done, info# ===================================================================
environment.py+88-179