Spaces:
Sleeping
Sleeping
databoysu commited on
Commit ·
2e11c6a
1
Parent(s): 9882200
TraceFix-RL v1
Browse filesFiles changed (15)
- .gitignore+2-1
- CLAUDE.md+2-2
- README.md+41-5
- __init__.py+3-9
- client.py+4-62
- context.py+3-56
- environment.py+10-120
- inference.py+8-8
- models.py+1-1
- openenv.yaml+1-1
- pyproject.toml+6-6
- sandbox.py-41
- server/__init__.py+3-9
- server/app.py+6-13
- server/swe_gym_environment.py → server/tracefix_rl_environment.pyRenamed+5-21
1 unmodified line23451 unmodified line.agents.envuv.lockclaude.md1 unmodified line234561 unmodified line.agents.envuv.lockclaude.md__pycache__/
1234254 unmodified lines259260261262263264265# CLAUDE.md — Python Debugging Gym (RL_ENV)Codebase knowledge for AI assistants. Read before making changes.254 unmodified lines**Exact stdout log format (regex-parsed by validation judge):**```[START] task=<task_name> env=PythonDebuggingGym model=<model_name>[STEP] step=<n> action=<action_type> reward=<r.rr> done=<true|false> error=<msg|null>[END] success=<true|false> steps=<n> score=<s.sss> rewards=<r1,r2,...,rn>```1234254 unmodified lines259260261262263264265# CLAUDE.md — TraceFix-RLCodebase knowledge for AI assistants. Read before making changes.254 unmodified lines**Exact stdout log format (regex-parsed by validation judge):**```[START] task=<task_name> env=TraceFixRL model=<model_name>[STEP] step=<n> action=<action_type> reward=<r.rr> done=<true|false> error=<msg|null>[END] success=<true|false> steps=<n> score=<s.sss> rewards=<r1,r2,...,rn>```
123457 unmodified lines13141516171819202122235 unmodified lines293031323334---title: SWE-Gym - Software Engineer Gymemoji: 🧑💻colorFrom: bluecolorTo: cyan7 unmodified lines- software-engineering---# SWE-Gym - Software Engineer GymSWE-Gym is an OpenEnv-compatible RL environment where an agent must debug brokenPython code by iteratively inspecting source, running tests, editing lines, andsubmitting once all tests pass.## Core Design5 unmodified lines- Curriculum-ready task sampling:easy/medium/hard buckets with safe random fallback for evaluator runs.## Environment Files- `models.py`: action/observation schemas123457 unmodified lines131415161718192021222324255 unmodified lines31323334353637383940414243444546474849505152535455565758596061626364656667686970---title: TraceFix-RLemoji: 🧑💻colorFrom: bluecolorTo: cyan7 unmodified lines- software-engineering---# TraceFix-RLTraceFix-RL is an OpenEnv-compatible environment designed to teach agent behaviorthat looks like real software engineering work. Instead of one-shot answers,the agent must inspect code, form a hypothesis, run tests, patch the code,verify outcomes, and only then submit. The loop rewards disciplined debuggingand penalizes random edits, forcing the model to learn an engineering workflow.## Core Design5 unmodified lines- Curriculum-ready task sampling:easy/medium/hard buckets with safe random fallback for evaluator runs.## State Machine Training PatternThe environment prompt in `environment.py` encodes a fixed operating patternthe agent is expected to follow:1. ORIENT: inspect code (`VIEW_CODE`)2. DIAGNOSE: run tests and read failures (`RUN_TESTS`)3. FIX: patch one region (`REPLACE_LINES`)4. VERIFY: rerun tests (`RUN_TESTS`)5. REPEAT: continue until all failures are resolved6. SUBMIT: finalize only after tests passThis structure is intentional: the environment trains planning, controlledediting, and verification behavior, not just raw code generation.## Task Tiers And Test StructureTasks are organized in `tasks.py` into three tiers.- Easy: 4 tasks, each with 4 unit tests.Focus: basic operators, indexing, and simple string/array logic.- Medium: 6 tasks, each with 4 unit tests.Focus: recursive behavior, branching correctness, and text normalization edge cases.- Hard: 6 tasks, each with 3-4 unit tests.Focus: data-structure invariants, eviction/promotion logic, bracket mapping, and interval merging edge behavior.Every task follows the same schema:- `name`, `description`, `difficulty`, `bug_type`- `code`: buggy implementation (line list)- `solution`: reference implementation- `tests`: callable assertions executed in the sandboxThis gives consistent training signals while scaling complexity across tiers.## Environment Files- `models.py`: action/observation schemas
123456789101112131415161718# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree."""SWE-Gym OpenEnv package."""from .client import MyEnv, SWEGymEnvfrom .models import CodeAction, CodeObservation, TestResult__all__ = ["CodeAction","CodeObservation","TestResult","SWEGymEnv","MyEnv",]123456789101112"""TraceFix-RL OpenEnv package."""from .client import MyEnv, TraceFixRLEnvfrom .models import CodeAction, CodeObservation, TestResult__all__ = ["CodeAction","CodeObservation","TestResult","TraceFixRLEnv","MyEnv",]
123456789107 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737419 unmodified lines949596979899100101102103104105106107108109110111112113# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree."""Client for the SWE-Gym OpenEnv environment."""from typing import Dict7 unmodified linesfrom models import CodeAction, CodeObservation, TestResultclass SWEGymEnv(EnvClient[CodeAction, CodeObservation, State]):"""Client for the SWE-Gym environment.This client maintains a persistent WebSocket connection to the environment server,enabling efficient multi-step interactions with lower latency.Each client instance has its own dedicated environment session on the server.Example:>>> # Connect to a running server>>> with SWEGymEnv(base_url="http://localhost:7860") as client:... result = client.reset()... print(result.observation.echoed_message)...... result = client.step(MyAction(message="Hello!"))... print(result.observation.echoed_message)Example with Docker:>>> # Automatically start container and connect>>> client = SWEGymEnv.from_docker_image("swe-gym:latest")>>> try:... result = client.reset()... result = client.step(MyAction(message="Test"))... finally:... client.close()"""def _step_payload(self, action: CodeAction) -> Dict:"""Convert MyAction to JSON payload for step message.Args:action: MyAction instanceReturns:Dictionary representation suitable for JSON encoding"""return action.model_dump(exclude_none=True)def _parse_result(self, payload: Dict) -> StepResult[CodeObservation]:"""Parse server response into StepResult[CodeObservation].Args:payload: JSON response data from serverReturns:StepResult with MyObservation"""obs_data = payload.get("observation", {})observation = CodeObservation(code_lines=obs_data.get("code_lines", []),19 unmodified lines)def _parse_state(self, payload: Dict) -> State:"""Parse server response into State object.Args:payload: JSON response from state requestReturns:State object with episode_id and step_count"""return State(episode_id=payload.get("episode_id"),step_count=payload.get("step_count", 0),)# Backward-compatible alias for older code paths.MyEnv = SWEGymEnv12347 unmodified lines12131415161718192021222324252619 unmodified lines46474849505152535455"""Client for TraceFix-RL."""from typing import Dict7 unmodified linesfrom models import CodeAction, CodeObservation, TestResultclass TraceFixRLEnv(EnvClient[CodeAction, CodeObservation, State]):"""Typed OpenEnv client."""def _step_payload(self, action: CodeAction) -> Dict:return action.model_dump(exclude_none=True)def _parse_result(self, payload: Dict) -> StepResult[CodeObservation]:obs_data = payload.get("observation", {})observation = CodeObservation(code_lines=obs_data.get("code_lines", []),19 unmodified lines)def _parse_state(self, payload: Dict) -> State:return State(episode_id=payload.get("episode_id"),step_count=payload.get("step_count", 0),)MyEnv = TraceFixRLEnv
12345678910111213141516171819202122232425262728292 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283842 unmodified lines8788899091929394"""context.py — Layered Context Compaction=========================================PRINCIPLE 10 — Layered Context CompactionFor large files, returning the full source on every observation would rapidlyfill the agent's context window, leaving no room for reasoning.Instead we return a *localized* view: a ±WINDOW_LINES slice of the codecentred on the last line that was edited. This gives the agent exactly thecontext it needs — the neighbourhood of its most recent change — withoutflooding the context with unrelated code.This module is intentionally pure (no environment state dependencies) soit can be unit-tested independently and reused across environment versions."""from __future__ import annotationsfrom typing import List, Optional# How many lines above and below the anchor to includeWINDOW_LINES: int = 10# Maximum characters for the localized context block# (Principle 9: all outputs must be bounded)MAX_CONTEXT_CHARS: int = 2_0002 unmodified linesanchor_line: Optional[int],window: int = WINDOW_LINES,) -> str:"""Return a ±`window`-line slice of `code_lines` centred on `anchor_line`.Parameters----------code_lines : Full list of source lines (0-indexed internally).anchor_line : The 1-indexed line number of the most recent edit.If None (no edits yet) returns an empty string.window : Number of lines to show above and below the anchor.Returns-------A formatted string with line numbers, bounded to MAX_CONTEXT_CHARS,annotated with the visible range and an anchor marker (▶).Example output--------------[Showing lines 3–13 of 20, anchor ▶ line 7]3 | left, right = 0, len(arr)4 | while left <= right:5 | mid = (left + right) // 26 | if arr[mid] == target:7 ▶ return mid ← last edit8 | elif arr[mid] < target:9 | left = mid + 110 | else:11 | right = mid - 112 | return -1"""if anchor_line is None or not code_lines:return ""total = len(code_lines)# Clamp anchor into valid rangeanchor_0 = max(0, min(anchor_line - 1, total - 1))# Compute slice bounds (inclusive on both ends, 0-indexed)start_0 = max(0, anchor_0 - window)end_0 = min(total - 1, anchor_0 + window)# Build headerstart_1 = start_0 + 1end_1 = end_0 + 1header = f"[Showing lines {start_1}–{end_1} of {total}, anchor ▶ line {anchor_line}]"# Build bodybody_lines = []for i in range(start_0, end_0 + 1):line_num = i + 12 unmodified linesresult = header + "\n" + "\n".join(body_lines)# PRINCIPLE 9 — hard cap on output sizeif len(result) > MAX_CONTEXT_CHARS:result = result[:MAX_CONTEXT_CHARS] + "\n... [context truncated]"return result12345678910112 unmodified lines141516171819202122232425262728293031322 unmodified lines35363738394041"""Localized context helpers for TraceFix-RL."""from __future__ import annotationsfrom typing import List, OptionalWINDOW_LINES: int = 10MAX_CONTEXT_CHARS: int = 2_0002 unmodified linesanchor_line: Optional[int],window: int = WINDOW_LINES,) -> str:"""Return a bounded ±window slice around the latest edited line."""if anchor_line is None or not code_lines:return ""total = len(code_lines)anchor_0 = max(0, min(anchor_line - 1, total - 1))start_0 = max(0, anchor_0 - window)end_0 = min(total - 1, anchor_0 + window)start_1 = start_0 + 1end_1 = end_0 + 1header = f"[Showing lines {start_1}–{end_1} of {total}, anchor ▶ line {anchor_line}]"body_lines = []for i in range(start_0, end_0 + 1):line_num = i + 12 unmodified linesresult = header + "\n" + "\n".join(body_lines)if len(result) > MAX_CONTEXT_CHARS:result = result[:MAX_CONTEXT_CHARS] + "\n... [context truncated]"return result
12345678910111213141516171819202122232425262728293031323334353637383940414243444513 unmodified lines59606162636465666768697071727374757677787980818283848586878889909184 unmodified lines1761771781791801811821831841851861871881891901911921931941951961971981993 unmodified lines20320420520620720820921021121221321421521621721821922022122222322422522622713 unmodified lines2412422432442452462472482492502512522533 unmodified lines2572582592602612622633 unmodified lines2672682692702712722737 unmodified lines2812822832842852862874 unmodified lines2922932942952962972982993003013023033043053063074 unmodified lines31231331431531631731818 unmodified lines3373383393403413423431 unmodified line34534634734834935035117 unmodified lines36937037137237337437537637737837938017 unmodified lines3983994004014024034044054064074084094104114123 unmodified lines41641741841942042142224 unmodified lines4474484494504514524534544554564574581 unmodified line4604614624634644654667 unmodified lines47447547647747847948048148248348448548648748848949049149221 unmodified lines51451551651751851952052152236 unmodified lines55956056156256356456514 unmodified lines5805815825835845855865875885895901 unmodified line592593594595596597598"""environment.py — Python Debugging Gym (Core RL Environment)=============================================================PRINCIPLE 1 — You Don't Design the Control FlowThe agent decides the sequence of actions. step() is a pure router:it receives whatever action the agent chose (in whatever order),processes it, and returns the new state. There is no forced sequence,no "you must VIEW_CODE before RUN_TESTS" gate. The system promptexplains what tools exist; the agent decides how to use them.PRINCIPLE 5 — Cost-Per-Turn Reward LogicEach call to step() costs R_STEP_COST = -0.01. This makes the episodea multi-turn budget problem: the agent is rewarded for solving quickly.An agent that solves in 4 steps scores ~0.14 more than one that takes18 steps to reach the same solution.PRINCIPLE 7 — The Prompt is CodeThe string returned by reset() is the agent's complete operationalcontract for the session. It states: the goal, the available actions(with exact JSON examples), the reward structure, the current code,and the expected termination condition. Ambiguity in this stringdirectly causes off-task behaviour.PRINCIPLE 10 — Layered Context Compaction_build_observation() tracks `_last_edited_line` and passes it tocontext.get_localized_context() to produce a focused ±10-line viewafter each write action. This prevents the observation from inflatingthe agent's context window on large files.Reward table (dense, non-sparse — every step emits a signal):+1.00 SUBMIT and ALL tests pass → episode solved+0.10 RUN_TESTS called → information-gathering rewarded+0.05 Per test transitioning fail→pass on a RUN_TESTS or SUBMIT-0.01 Every step taken → efficiency pressure (Principle 5)-0.10 Syntax error detected → broken code penalised immediately-0.10 UNDO_EDIT or RESET_TO_ORIGINAL → backtracking discouraged-0.02 Invalid line range supplied → hallucination deterrent-0.20 SUBMIT with tests still failingMax episode length: 50 steps."""from __future__ import annotations13 unmodified linesfrom tasks import ALL_TASKS, TASKS_BY_DIFFICULTY# ---------------------------------------------------------------------------# Reward constants# ---------------------------------------------------------------------------R_SUBMIT_ALL_PASS = +1.00R_SUBMIT_FAIL = -0.20R_SYNTAX_ERROR = -0.10R_RUN_TESTS = +0.10R_PER_NEW_PASS = +0.05R_STEP_COST = -0.01 # PRINCIPLE 5 — every step has a costR_INVALID_LINE = -0.02R_DESTRUCTIVE_PENALTY = -0.20R_UNDO_RESET = -0.10 # Mini-Git backtracking penaltyMAX_STEPS: int = 50# ---------------------------------------------------------------------------# System Prompt (PRINCIPLE 7 — The Prompt is Code)# ---------------------------------------------------------------------------# This string is the agent's entire operational contract.# It must be:# • Self-contained (no assumed context from training data)# • Precise (exact JSON examples, not vague descriptions)# • Non-directive about sequence (Principle 1: agent chooses order)# • Complete (goal, tools, rewards, termination — nothing omitted)_SYSTEM_PROMPT = """\╔══════════════════════════════════════════════════════╗║ PYTHON DEBUGGING GYM — EPISODE BRIEF ║84 unmodified lines"""# ---------------------------------------------------------------------------# Environment# ---------------------------------------------------------------------------class PythonDebuggingGym:"""Gymnasium-compatible RL environment for Python debugging.PRINCIPLE 1: step() is a stateless router — the agent chooses thesequence. No internal gates, no forced ordering between actions.Interface---------obs, system_prompt = env.reset()obs, reward, done, info = env.step(action: CodeAction)"""metadata = {"name": "PythonDebuggingGym-v1", "render_modes": []}def __init__(self,3 unmodified linesself._task_index = task_indexself._rng = random.Random(seed)# All mutable episode state lives here; reset() wipes every field.self._code_lines: List[str] = []self._task: Dict[str, Any] = {}self._step_count: int = 0self._prev_pass_count: int = 0self._last_test_results: List[TestResult] = []self._last_output: str = ""self._last_edited_line: Optional[int] = None # PRINCIPLE 10self._episode_id: str = ""self._done: bool = Falseself._cumulative_reward: float = 0.0self._accumulated_step_costs: float = 0.0 # Hackathon compliance# Mini-Git snapshot history (Phase 2)self._original_code: List[str] = [] # pristine copy set at reset()self._edit_history: List[List[str]] = [] # stack of pre-edit snapshots# Curriculum learning — persists across episodes, incremented externallyself.training_step: int = 0# ── Curriculum task sampler ──────────────────────────────────────────────def _sample_task(self, task_override=None) -> Dict[str, Any]:"""13 unmodified linesif isinstance(task_override, dict):return task_override# Judge-safe default: no training_step set → random from all tasksif self.training_step == 0:if not ALL_TASKS:raise RuntimeError("ALL_TASKS is empty — check tasks.py.")return self._rng.choice(ALL_TASKS)# Curriculum mode (trainer increments training_step between episodes)if self.training_step < 1000:bucket = "easy"elif self.training_step < 5000:3 unmodified linespool = TASKS_BY_DIFFICULTY.get(bucket, [])if not pool:# Fallback: any non-empty bucket rather than crashingfor b in ("easy", "medium", "hard"):pool = TASKS_BY_DIFFICULTY.get(b, [])if pool:3 unmodified linesreturn self._rng.choice(pool)# ── reset() ─────────────────────────────────────────────────────────────def reset(self, *, task_index: Optional[int] = None7 unmodified lines"""self._task = self._sample_task(task_index)# ── Complete state wipe ──────────────────────────────────────────self._code_lines = list(self._task["code"]) # deep copy — no aliasself._step_count = 0self._prev_pass_count = 04 unmodified linesself._done = Falseself._cumulative_reward = 0.0self._accumulated_step_costs = 0.0# Mini-Git: seed pristine snapshot and clear historyself._original_code = list(self._task["code"]) # separate copy from _code_linesself._edit_history = []# Anti-Loop historyself._last_action: Optional[str] = Noneself._consecutive_count: int = 0obs = self._build_observation(reward=0.0)# PRINCIPLE 7: build the operational contract stringsystem_prompt = _SYSTEM_PROMPT.format(task_name = self._task["name"],difficulty = self._task.get("difficulty", "unknown"),4 unmodified linesreturn obs, system_prompt# ── step() ──────────────────────────────────────────────────────────────def step(self, action: CodeAction18 unmodified linesreward = R_STEP_COST # PRINCIPLE 5: cost-per-turn baselineself._accumulated_step_costs += abs(R_STEP_COST) # Hackathon compliance# ── Repetition Penalty (Anti-Loop) ───────────────────────────────if action.action_type == self._last_action:self._consecutive_count += 1reward += -0.05 * self._consecutive_count1 unmodified lineself._consecutive_count = 0self._last_action = action.action_type# ── Route (PRINCIPLE 1: no forced sequence) ──────────────────────atype = action.action_typeif atype == "VIEW_CODE":17 unmodified linesreward += self._act_submit()self._done = True# ── Max-steps termination ────────────────────────────────────────if self._step_count >= MAX_STEPS and not self._done:self._done = True# Deterministic clamp — never trust the LLM to call SUBMIT.# Evaluate the current code and produce a valid [0.0, 1.0] score# regardless of how the episode ended._, results, syntax_err = run_code_with_tests(source=self._source(),test_callables=self._task["tests"],17 unmodified lines"step": self._step_count,}if self._done:# PRINCIPLE: Ensure Hackathon score leak doesn't occur. It must be strictly [0.0, 1.0].# During SUBMIT, reward might be negative if _act_submit returned 0.0 added to -0.01.info["final_score"] = max(0.0, min(1.0, round(reward, 4)))return obs, round(reward, 4), self._done, info# ── Action handlers ─────────────────────────────────────────────────────# Each returns the delta reward (R_STEP_COST already applied by step()).# Handlers update self._last_output and self._last_edited_line as needed.def _act_view_code(self) -> float:self._last_output = (3 unmodified linesfor i, line in enumerate(self._code_lines)))# VIEW_CODE does not change the code — localized_context stays where it wasreturn 0.0def _act_run_tests(self) -> float:24 unmodified linesif new_code_block is None:new_code_block = ""# ── Guard: Destructive Action (Anti-Deletion) ─────────────────────if len(new_code_block) == 0 and (end_line - start_line) > 5:self._last_output = "Error: Cannot delete more than 5 lines at once."return R_DESTRUCTIVE_PENALTY# ── Guard: inverted range ─────────────────────────────────────────if start_line > end_line:self._last_output = (f"Error: start_line ({start_line}) > end_line ({end_line}). "1 unmodified line)return R_INVALID_LINE# ── Guard: out-of-bounds ──────────────────────────────────────────if start_line < 1 or start_line > n:self._last_output = (f"Error: start_line {start_line} is out of range [1, {n}]. "7 unmodified lines)return R_INVALID_LINE# ── Slice assignment (PRINCIPLE 1: pure data transformation) ──────start_idx = start_line - 1 # convert to 0-indexedend_idx = end_line # exclusive upper bound for Python slice# ── Mini-Git: snapshot BEFORE mutating (Phase 2) ─────────────────self._edit_history.append(list(self._code_lines))new_lines = new_code_block.split("\n")self._code_lines[start_idx:end_idx] = new_lines# ── Anchor context at END of new block (PRINCIPLE 10) ─────────────# If the agent replaces lines 5–10 with 20 new lines, the anchor# settles at start_line + len(new_lines) - 1, clamped to file length.new_end = start_line + len(new_lines) - 1self._last_edited_line = min(new_end, len(self._code_lines))21 unmodified linesif syntax_err:self._last_output += "\n❌ SUBMIT rejected — syntax error in current code."# ── Hackathon compliance: final score ∈ [0.0, 1.0] ───────────────# raw = (tests_passed / total) - accumulated_step_costs# Then clamped so the grader always receives a value in spec.proportion = passes / total if total > 0 else 0.0raw_score = proportion - self._accumulated_step_costsfinal_score = max(0.0, min(1.0, raw_score))36 unmodified lines"Call VIEW_CODE to inspect the restored file.")# PRINCIPLE 10 desync fix: anchor is stale after rollback — wipe it.self._last_edited_line = Nonereturn R_UNDO_RESET14 unmodified lines"Call VIEW_CODE to inspect the file.")# PRINCIPLE 10 desync fix: context anchor is meaningless after full reset.self._last_edited_line = Nonereturn R_UNDO_RESET# ── Helpers ─────────────────────────────────────────────────────────────def _source(self) -> str:return "\n".join(self._code_lines)1 unmodified linedef _build_observation(self, reward: float) -> CodeObservation:syntax_valid, _ = check_syntax(self._source())# PRINCIPLE 10: localized context — only ±10 lines around last editlocalized = get_localized_context(self._code_lines, self._last_edited_line)return CodeObservation(123413 unmodified lines18192021222324252627282930313233343584 unmodified lines1201211221231241251261271281293 unmodified lines13313413513613713813914014114214314414514614714814915015115215313 unmodified lines1671681691701711721731741751761773 unmodified lines1811821831841851863 unmodified lines1901911921931941957 unmodified lines2032042052062072084 unmodified lines2132142152162172182192202212222232242254 unmodified lines23023123223323423518 unmodified lines2542552562572582591 unmodified line26126226326426526617 unmodified lines28428528628728828929029117 unmodified lines3093103113123133143153163173183 unmodified lines32232332432532632724 unmodified lines3523533543553563573583593603611 unmodified line3633643653663673687 unmodified lines37637737837938038138238338438538638738838921 unmodified lines41141241341441541636 unmodified lines45345445545645745814 unmodified lines4734744754764774784794804811 unmodified line483484485486487488"""Core TraceFix-RL environment implementation."""from __future__ import annotations13 unmodified linesfrom tasks import ALL_TASKS, TASKS_BY_DIFFICULTYR_SUBMIT_ALL_PASS = +1.00R_SUBMIT_FAIL = -0.20R_SYNTAX_ERROR = -0.10R_RUN_TESTS = +0.10R_PER_NEW_PASS = +0.05R_STEP_COST = -0.01R_INVALID_LINE = -0.02R_DESTRUCTIVE_PENALTY = -0.20R_UNDO_RESET = -0.10MAX_STEPS: int = 50_SYSTEM_PROMPT = """\╔══════════════════════════════════════════════════════╗║ PYTHON DEBUGGING GYM — EPISODE BRIEF ║84 unmodified lines"""class TraceFixRLGym:"""Gym-style environment with reset/step methods."""metadata = {"name": "TraceFixRL-v1", "render_modes": []}def __init__(self,3 unmodified linesself._task_index = task_indexself._rng = random.Random(seed)self._code_lines: List[str] = []self._task: Dict[str, Any] = {}self._step_count: int = 0self._prev_pass_count: int = 0self._last_test_results: List[TestResult] = []self._last_output: str = ""self._last_edited_line: Optional[int] = Noneself._episode_id: str = ""self._done: bool = Falseself._cumulative_reward: float = 0.0self._accumulated_step_costs: float = 0.0self._original_code: List[str] = []self._edit_history: List[List[str]] = []self.training_step: int = 0def _sample_task(self, task_override=None) -> Dict[str, Any]:"""13 unmodified linesif isinstance(task_override, dict):return task_overrideif self.training_step == 0:if not ALL_TASKS:raise RuntimeError("ALL_TASKS is empty — check tasks.py.")return self._rng.choice(ALL_TASKS)if self.training_step < 1000:bucket = "easy"elif self.training_step < 5000:3 unmodified linespool = TASKS_BY_DIFFICULTY.get(bucket, [])if not pool:for b in ("easy", "medium", "hard"):pool = TASKS_BY_DIFFICULTY.get(b, [])if pool:3 unmodified linesreturn self._rng.choice(pool)def reset(self, *, task_index: Optional[int] = None7 unmodified lines"""self._task = self._sample_task(task_index)self._code_lines = list(self._task["code"]) # deep copy — no aliasself._step_count = 0self._prev_pass_count = 04 unmodified linesself._done = Falseself._cumulative_reward = 0.0self._accumulated_step_costs = 0.0self._original_code = list(self._task["code"]) # separate copy from _code_linesself._edit_history = []self._last_action: Optional[str] = Noneself._consecutive_count: int = 0obs = self._build_observation(reward=0.0)system_prompt = _SYSTEM_PROMPT.format(task_name = self._task["name"],difficulty = self._task.get("difficulty", "unknown"),4 unmodified linesreturn obs, system_promptdef step(self, action: CodeAction18 unmodified linesreward = R_STEP_COST # PRINCIPLE 5: cost-per-turn baselineself._accumulated_step_costs += abs(R_STEP_COST) # Hackathon complianceif action.action_type == self._last_action:self._consecutive_count += 1reward += -0.05 * self._consecutive_count1 unmodified lineself._consecutive_count = 0self._last_action = action.action_typeatype = action.action_typeif atype == "VIEW_CODE":17 unmodified linesreward += self._act_submit()self._done = Trueif self._step_count >= MAX_STEPS and not self._done:self._done = True_, results, syntax_err = run_code_with_tests(source=self._source(),test_callables=self._task["tests"],17 unmodified lines"step": self._step_count,}if self._done:info["final_score"] = max(0.0, min(1.0, round(reward, 4)))return obs, round(reward, 4), self._done, infodef _act_view_code(self) -> float:self._last_output = (3 unmodified linesfor i, line in enumerate(self._code_lines)))return 0.0def _act_run_tests(self) -> float:24 unmodified linesif new_code_block is None:new_code_block = ""if len(new_code_block) == 0 and (end_line - start_line) > 5:self._last_output = "Error: Cannot delete more than 5 lines at once."return R_DESTRUCTIVE_PENALTYif start_line > end_line:self._last_output = (f"Error: start_line ({start_line}) > end_line ({end_line}). "1 unmodified line)return R_INVALID_LINEif start_line < 1 or start_line > n:self._last_output = (f"Error: start_line {start_line} is out of range [1, {n}]. "7 unmodified lines)return R_INVALID_LINEstart_idx = start_line - 1 # convert to 0-indexedend_idx = end_line # exclusive upper bound for Python sliceself._edit_history.append(list(self._code_lines))new_lines = new_code_block.split("\n")self._code_lines[start_idx:end_idx] = new_linesnew_end = start_line + len(new_lines) - 1self._last_edited_line = min(new_end, len(self._code_lines))21 unmodified linesif syntax_err:self._last_output += "\n❌ SUBMIT rejected — syntax error in current code."proportion = passes / total if total > 0 else 0.0raw_score = proportion - self._accumulated_step_costsfinal_score = max(0.0, min(1.0, raw_score))36 unmodified lines"Call VIEW_CODE to inspect the restored file.")self._last_edited_line = Nonereturn R_UNDO_RESET14 unmodified lines"Call VIEW_CODE to inspect the file.")self._last_edited_line = Nonereturn R_UNDO_RESETdef _source(self) -> str:return "\n".join(self._code_lines)1 unmodified linedef _build_observation(self, reward: float) -> CodeObservation:syntax_valid, _ = check_syntax(self._source())localized = get_localized_context(self._code_lines, self._last_edited_line)return CodeObservation(
1234518 unmodified lines2425262728293031323 unmodified lines3637383940414243126 unmodified lines1701711721731741751763 unmodified lines180181182183184185186187188"""Inference script for SWE-Gym - Software Engineer Gym.Mandatory env vars expected in deployment config:API_BASE_URL18 unmodified linesfrom openai import OpenAItry:from swe_gym import CodeAction, SWEGymEnvexcept ImportError:from client import SWEGymEnvfrom models import CodeAction3 unmodified linesLOCAL_IMAGE_NAME = os.getenv("LOCAL_IMAGE_NAME", "")ENV_BASE_URL = os.getenv("ENV_BASE_URL", "http://localhost:7860")TASK_NAME = os.getenv("TASK_NAME", "swe_gym")BENCHMARK = os.getenv("BENCHMARK", "swe_gym")MAX_STEPS = int(os.getenv("MAX_STEPS", "50"))SUCCESS_SCORE_THRESHOLD = float(os.getenv("SUCCESS_SCORE_THRESHOLD", "0.99"))126 unmodified linesasync def main() -> None:client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)env: SWEGymEnv | None = Nonerewards: list[float] = []history: list[str] = []steps_taken = 03 unmodified linestry:if LOCAL_IMAGE_NAME:env = await SWEGymEnv.from_docker_image(LOCAL_IMAGE_NAME)else:env = SWEGymEnv(base_url=ENV_BASE_URL)result = await env.reset()task_name = result.observation.info.get("task_name") or TASK_NAME1234518 unmodified lines2425262728293031323 unmodified lines3637383940414243126 unmodified lines1701711721731741751763 unmodified lines180181182183184185186187188"""Inference script for TraceFix-RL.Mandatory env vars expected in deployment config:API_BASE_URL18 unmodified linesfrom openai import OpenAItry:from tracefix_rl import CodeAction, TraceFixRLEnvexcept ImportError:from client import TraceFixRLEnvfrom models import CodeAction3 unmodified linesLOCAL_IMAGE_NAME = os.getenv("LOCAL_IMAGE_NAME", "")ENV_BASE_URL = os.getenv("ENV_BASE_URL", "http://localhost:7860")TASK_NAME = os.getenv("TASK_NAME", "tracefix_rl")BENCHMARK = os.getenv("BENCHMARK", "tracefix_rl")MAX_STEPS = int(os.getenv("MAX_STEPS", "50"))SUCCESS_SCORE_THRESHOLD = float(os.getenv("SUCCESS_SCORE_THRESHOLD", "0.99"))126 unmodified linesasync def main() -> None:client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)env: TraceFixRLEnv | None = Nonerewards: list[float] = []history: list[str] = []steps_taken = 03 unmodified linestry:if LOCAL_IMAGE_NAME:env = await TraceFixRLEnv.from_docker_image(LOCAL_IMAGE_NAME)else:env = TraceFixRLEnv(base_url=ENV_BASE_URL)result = await env.reset()task_name = result.observation.info.get("task_name") or TASK_NAME
1234"""Pydantic schema layer for SWE-Gym - Software Engineer Gym."""from __future__ import annotations1234"""Pydantic schema layer for TraceFix-RL."""from __future__ import annotations
12345spec_version: 1name: swe_gymtype: spaceruntime: fastapiapp: server.app:app12345spec_version: 1name: tracefix_rltype: spaceruntime: fastapiapp: server.app:app
8 unmodified lines9101112131415161720 unmodified lines383940414243444546478 unmodified linesbuild-backend = "setuptools.build_meta"[project]name = "openenv-swe-gym"version = "0.1.0"description = "SWE-Gym - Software Engineer Gym environment for OpenEnv"requires-python = ">=3.10"dependencies = [# Core OpenEnv runtime (provides FastAPI server + HTTP client types)20 unmodified lines[project.scripts]# Server entry point - enables running via: uv run --project . server# or: python -m swe_gym.server.appserver = "swe_gym.server.app:main"[tool.setuptools]include-package-data = truepackages = ["swe_gym", "swe_gym.server"]package-dir = { "swe_gym" = ".", "swe_gym.server" = "server" }8 unmodified lines9101112131415161720 unmodified lines383940414243444546478 unmodified linesbuild-backend = "setuptools.build_meta"[project]name = "openenv-tracefix-rl"version = "0.1.0"description = "TraceFix-RL environment for OpenEnv"requires-python = ">=3.10"dependencies = [# Core OpenEnv runtime (provides FastAPI server + HTTP client types)20 unmodified lines[project.scripts]# Server entry point - enables running via: uv run --project . server# or: python -m tracefix_rl.server.appserver = "tracefix_rl.server.app:main"[tool.setuptools]include-package-data = truepackages = ["tracefix_rl", "tracefix_rl.server"]package-dir = { "tracefix_rl" = ".", "tracefix_rl.server" = "server" }
43 unmodified lines44454647484950515253545556575859607 unmodified lines68697071727374757677787980818283848586878889909192932 unmodified lines9697989910010110210310410510610710810 unmodified lines11912012112212312412512612710 unmodified lines13813914014114214314414514615 unmodified lines1621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012024 unmodified lines2072082092102112122132 unmodified lines2162172182192202212221 unmodified line2242252262272282292302 unmodified lines23323423523623723823924024129 unmodified lines2712722732742752762778 unmodified lines28628728828929029129243 unmodified linesfrom models import TestResult# ---------------------------------------------------------------------------# Constants# ---------------------------------------------------------------------------EXEC_TIMEOUT_SECONDS: int = 5 # Hard wall-clock kill limit (Principle 8)MAX_OUTPUT_CHARS: int = 1_000 # Tail-truncate limit (Principle 9)# ---------------------------------------------------------------------------# Restricted builtins (Principle 8)# ---------------------------------------------------------------------------def _make_safe_stub(name: str) -> Callable:"""Return a callable that raises RuntimeError — used to block dangerous builtins."""7 unmodified linesreturn _stub# Whitelist: safe builtins the agent's code is allowed to use.# Everything not in this dict is blocked._SAFE_BUILTINS: Dict[str, Any] = {# Type constructors"int": int, "float": float, "str": str, "bool": bool,"list": list, "dict": dict, "set": set, "tuple": tuple,"bytes": bytes, "bytearray": bytearray, "frozenset": frozenset,"complex": complex,# Inspection / iteration"len": len, "range": range, "enumerate": enumerate, "zip": zip,"map": map, "filter": filter, "reversed": reversed, "sorted": sorted,"iter": iter, "next": next, "sum": sum, "min": min, "max": max,"abs": abs, "round": round, "divmod": divmod, "pow": pow,# Introspection"isinstance": isinstance, "issubclass": issubclass, "type": type,"hasattr": hasattr, "getattr": getattr, "setattr": setattr,"callable": callable, "repr": repr, "hash": hash, "id": id,# I/O (stdout only — stderr is captured separately)"print": print,# Exceptions & control"Exception": Exception, "ValueError": ValueError, "TypeError": TypeError,"KeyError": KeyError, "IndexError": IndexError, "AttributeError": AttributeError,"StopIteration": StopIteration, "RuntimeError": RuntimeError,2 unmodified lines"RecursionError": RecursionError, "MemoryError": MemoryError,"KeyboardInterrupt": KeyboardInterrupt,"BaseException": BaseException,# Functional"any": any, "all": all,"chr": chr, "ord": ord, "hex": hex, "oct": oct, "bin": bin,"format": format,"object": object, "property": property, "staticmethod": staticmethod,"classmethod": classmethod, "super": super,# Blocked with stubs (Principle 8)"open": _make_safe_stub("open"),"__import__": _make_safe_stub("__import__"),"eval": _make_safe_stub("eval"),10 unmodified lines}# ---------------------------------------------------------------------------# Output truncation (Principle 9)# ---------------------------------------------------------------------------def _tail_truncate(s: str, limit: int = MAX_OUTPUT_CHARS) -> str:"""10 unmodified linesreturn f"[...truncated {dropped} chars...]\n" + s[-limit:]# ---------------------------------------------------------------------------# Worker (runs in isolated child process)# ---------------------------------------------------------------------------def _worker(source: str,15 unmodified linesfn_name = "<unknown>"try:# ── Phase 1: Syntax check ─────────────────────────────────────────# Compile before exec() so SyntaxError is caught cleanly.try:code_obj = compile(source, "<agent_code>", "exec")except SyntaxError as exc:had_syntax_error = True# Restore streams before writing the errorsys.stdout, sys.stderr = old_stdout, old_stderrerr = f"SyntaxError at line {exc.lineno}: {exc.msg}\n >> {exc.text or ''}"result_queue.put((_tail_truncate(err), [], True))return# ── Phase 2: Execute agent code into a sandboxed namespace ───────# Use full __builtins__ to prevent __build_class__ errors for class-based tasks.namespace: Dict[str, Any] = {"__builtins__": __builtins__}try:exec(code_obj, namespace) # noqa: S102except Exception: # noqa: BLE001# PRINCIPLE 2: execution crash is data, not a crashtb = traceback.format_exc()sys.stdout, sys.stderr = old_stdout, old_stderrresult_queue.put((_tail_truncate(buf.getvalue() + "\n" + tb), [], False))return# ── Phase 3: Run each test function ──────────────────────────────# PRINCIPLE 2: each test is isolated inside its own try-except so a# crash in test N does not prevent tests N+1..M from running.for test_src in test_sources:fn_name = "<unknown>"try:# Inject the test function into the existing namespace so it# can access the agent's defined symbols.exec(test_src, namespace) # noqa: S102# Extract the last `def` name from the test source.fn_name = [ln.split("(")[0].replace("def ", "").strip()for ln in test_src.splitlines()4 unmodified linestest_results.append({"test_name": fn_name, "passed": True})except AssertionError as exc:# PRINCIPLE 2: assertion failure is structured datatest_results.append({"test_name": fn_name,"passed": False,2 unmodified lines),})except Exception: # noqa: BLE001# PRINCIPLE 2: all other exceptions also become structured datatest_results.append({"test_name": fn_name,"passed": False,1 unmodified line})except Exception: # noqa: BLE001# Catch-all for any unexpected failure in the harness itselftraceback.print_exc(file=buf)finally:sys.stdout, sys.stderr = old_stdout, old_stderr2 unmodified linesresult_queue.put((captured, test_results, had_syntax_error))# ---------------------------------------------------------------------------# Public API# ---------------------------------------------------------------------------def check_syntax(source: str) -> Tuple[bool, str]:"""29 unmodified lines-------(output_str, test_results, had_syntax_error)"""# Serialise callables → source strings (required for pickling across processes)test_sources = [textwrap.dedent(inspect.getsource(fn))for fn in test_callables8 unmodified linesproc.start()proc.join(timeout)# PRINCIPLE 8 — hard kill (SIGTERM first, SIGKILL if still alive)if proc.is_alive():proc.terminate()proc.join(2) # Give it 2s to handle SIGTERM gracefully43 unmodified lines44454647484950515253547 unmodified lines626364656667686970717273747576777879802 unmodified lines838485868788899091929310 unmodified lines10410510610710810910 unmodified lines12012112212312412515 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671681694 unmodified lines1741751761771781792 unmodified lines1821831841851861871 unmodified line1891901911921931942 unmodified lines19719819920020120229 unmodified lines2322332342352362378 unmodified lines24624724824925025143 unmodified linesfrom models import TestResultEXEC_TIMEOUT_SECONDS: int = 5 # Hard wall-clock kill limit (Principle 8)MAX_OUTPUT_CHARS: int = 1_000 # Tail-truncate limit (Principle 9)def _make_safe_stub(name: str) -> Callable:"""Return a callable that raises RuntimeError — used to block dangerous builtins."""7 unmodified linesreturn _stub_SAFE_BUILTINS: Dict[str, Any] = {"int": int, "float": float, "str": str, "bool": bool,"list": list, "dict": dict, "set": set, "tuple": tuple,"bytes": bytes, "bytearray": bytearray, "frozenset": frozenset,"complex": complex,"len": len, "range": range, "enumerate": enumerate, "zip": zip,"map": map, "filter": filter, "reversed": reversed, "sorted": sorted,"iter": iter, "next": next, "sum": sum, "min": min, "max": max,"abs": abs, "round": round, "divmod": divmod, "pow": pow,"isinstance": isinstance, "issubclass": issubclass, "type": type,"hasattr": hasattr, "getattr": getattr, "setattr": setattr,"callable": callable, "repr": repr, "hash": hash, "id": id,"print": print,"Exception": Exception, "ValueError": ValueError, "TypeError": TypeError,"KeyError": KeyError, "IndexError": IndexError, "AttributeError": AttributeError,"StopIteration": StopIteration, "RuntimeError": RuntimeError,2 unmodified lines"RecursionError": RecursionError, "MemoryError": MemoryError,"KeyboardInterrupt": KeyboardInterrupt,"BaseException": BaseException,"any": any, "all": all,"chr": chr, "ord": ord, "hex": hex, "oct": oct, "bin": bin,"format": format,"object": object, "property": property, "staticmethod": staticmethod,"classmethod": classmethod, "super": super,"open": _make_safe_stub("open"),"__import__": _make_safe_stub("__import__"),"eval": _make_safe_stub("eval"),10 unmodified lines}def _tail_truncate(s: str, limit: int = MAX_OUTPUT_CHARS) -> str:"""10 unmodified linesreturn f"[...truncated {dropped} chars...]\n" + s[-limit:]def _worker(source: str,15 unmodified linesfn_name = "<unknown>"try:try:code_obj = compile(source, "<agent_code>", "exec")except SyntaxError as exc:had_syntax_error = Truesys.stdout, sys.stderr = old_stdout, old_stderrerr = f"SyntaxError at line {exc.lineno}: {exc.msg}\n >> {exc.text or ''}"result_queue.put((_tail_truncate(err), [], True))returnnamespace: Dict[str, Any] = {"__builtins__": __builtins__}try:exec(code_obj, namespace) # noqa: S102except Exception: # noqa: BLE001tb = traceback.format_exc()sys.stdout, sys.stderr = old_stdout, old_stderrresult_queue.put((_tail_truncate(buf.getvalue() + "\n" + tb), [], False))returnfor test_src in test_sources:fn_name = "<unknown>"try:exec(test_src, namespace) # noqa: S102fn_name = [ln.split("(")[0].replace("def ", "").strip()for ln in test_src.splitlines()4 unmodified linestest_results.append({"test_name": fn_name, "passed": True})except AssertionError as exc:test_results.append({"test_name": fn_name,"passed": False,2 unmodified lines),})except Exception: # noqa: BLE001test_results.append({"test_name": fn_name,"passed": False,1 unmodified line})except Exception: # noqa: BLE001traceback.print_exc(file=buf)finally:sys.stdout, sys.stderr = old_stdout, old_stderr2 unmodified linesresult_queue.put((captured, test_results, had_syntax_error))def check_syntax(source: str) -> Tuple[bool, str]:"""29 unmodified lines-------(output_str, test_results, had_syntax_error)"""test_sources = [textwrap.dedent(inspect.getsource(fn))for fn in test_callables8 unmodified linesproc.start()proc.join(timeout)if proc.is_alive():proc.terminate()proc.join(2) # Give it 2s to handle SIGTERM gracefully
1234567891011# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree."""SWE-Gym server components."""from .swe_gym_environment import SWEGymEnvironment__all__ = ["SWEGymEnvironment"]12345"""TraceFix-RL server components."""from .tracefix_rl_environment import TraceFixRLEnvironment__all__ = ["TraceFixRLEnvironment"]
123456789104 unmodified lines1516171819202122232425262728293031323334353637# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree."""FastAPI entry point for SWE-Gym - Software Engineer Gym."""try:from openenv.core.env_server.http_server import create_app4 unmodified linestry:from ..models import CodeAction, CodeObservationfrom .swe_gym_environment import SWEGymEnvironmentexcept ImportError:import sysfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1]))from models import CodeAction, CodeObservationfrom server.swe_gym_environment import SWEGymEnvironment# Create the app with web interface and README integrationapp = create_app(SWEGymEnvironment,CodeAction,CodeObservation,env_name="swe_gym",max_concurrent_envs=1, # increase this number to allow more concurrent WebSocket sessions)12344 unmodified lines9101112131415161718192021222324252627282930"""FastAPI entry point for TraceFix-RL."""try:from openenv.core.env_server.http_server import create_app4 unmodified linestry:from ..models import CodeAction, CodeObservationfrom .tracefix_rl_environment import TraceFixRLEnvironmentexcept ImportError:import sysfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1]))from models import CodeAction, CodeObservationfrom server.tracefix_rl_environment import TraceFixRLEnvironmentapp = create_app(TraceFixRLEnvironment,CodeAction,CodeObservation,env_name="tracefix_rl",max_concurrent_envs=1,)
12345678910111213141516171819202122232425262728293031323322 unmodified lines56575859606162636465# Copyright (c) Meta Platforms, Inc. and affiliates.# All rights reserved.## This source code is licensed under the BSD-style license found in the# LICENSE file in the root directory of this source tree."""OpenEnv adapter around the SWE-Gym core environment."""from openenv.core.env_server.interfaces import Environmentfrom openenv.core.env_server.types import Statetry:from ..environment import PythonDebuggingGymfrom ..models import CodeAction, CodeObservationexcept ImportError:from environment import PythonDebuggingGymfrom models import CodeAction, CodeObservationclass SWEGymEnvironment(Environment):"""Environment implementation compatible with OpenEnv's server interface."""# Enable concurrent WebSocket sessions.# Set to True if your environment isolates state between instances.# When True, multiple WebSocket clients can connect simultaneously, each# getting their own environment instance (when using factory mode in app.py).SUPPORTS_CONCURRENT_SESSIONS: bool = Truedef __init__(self):self._gym = PythonDebuggingGym()self._state = State(episode_id="", step_count=0)def reset(self) -> CodeObservation:22 unmodified lines@propertydef state(self) -> State:"""Get the current environment state.Returns:Current State with episode_id and step_count"""return self._state123456789101112131415161718192021222322 unmodified lines46474849"""OpenEnv adapter around the TraceFix-RL core environment."""from openenv.core.env_server.interfaces import Environmentfrom openenv.core.env_server.types import Statetry:from ..environment import TraceFixRLGymfrom ..models import CodeAction, CodeObservationexcept ImportError:from environment import TraceFixRLGymfrom models import CodeAction, CodeObservationclass TraceFixRLEnvironment(Environment):"""Environment implementation compatible with OpenEnv's server interface."""SUPPORTS_CONCURRENT_SESSIONS: bool = Truedef __init__(self):self._gym = TraceFixRLGym()self._state = State(episode_id="", step_count=0)def reset(self) -> CodeObservation:22 unmodified lines@propertydef state(self) -> State:return self._state
.gitignore+2-1
CLAUDE.md+2-2
README.md+41-5
__init__.py+3-9
client.py+4-62
context.py+3-56
environment.py+10-120
inference.py+8-8
models.py+1-1
openenv.yaml+1-1
pyproject.toml+6-6
sandbox.py-41
server/__init__.py+3-9
server/app.py+6-13
server/swe_gym_environment.py → server/tracefix_rl_environment.pyRenamed+5-21