Metadata-Version: 2.4
Name: codefix-env
Version: 0.2.2
Summary: A high-performance PyTorch-based RL environment for automated code debugging and LLM agent evaluation
Author-email: Shailendra Dhakad <dhakarshailendra829@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
        
Project-URL: Homepage, https://github.com/dhakarshailendra829/codefix-env
Project-URL: Repository, https://github.com/dhakarshailendra829/codefix-env
Project-URL: Issues, https://github.com/dhakarshailendra829/codefix-env/issues
Keywords: reinforcement-learning,pytorch,llm,code-debugging,gymnasium,openenv,rl-environment,genai
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi>=0.110.0
Requires-Dist: uvicorn[standard]>=0.29.0
Requires-Dist: pydantic>=2.6.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: websockets>=12.0
Requires-Dist: torch>=2.2.0
Requires-Dist: numpy>=1.26.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: structlog>=24.1.0
Requires-Dist: rich>=13.7.0
Requires-Dist: typer>=0.12.0
Provides-Extra: dev
Requires-Dist: pytest>=8.1.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Requires-Dist: pytest-timeout>=2.3.0; extra == "dev"
Requires-Dist: ruff>=0.4.0; extra == "dev"
Requires-Dist: black>=24.3.0; extra == "dev"
Requires-Dist: isort>=5.13.0; extra == "dev"
Requires-Dist: mypy>=1.9.0; extra == "dev"
Requires-Dist: pre-commit>=3.7.0; extra == "dev"
Provides-Extra: llm
Requires-Dist: transformers>=4.40.0; extra == "llm"
Requires-Dist: trl>=0.8.6; extra == "llm"
Requires-Dist: accelerate>=0.29.0; extra == "llm"
Requires-Dist: datasets>=2.19.0; extra == "llm"
Requires-Dist: sentencepiece>=0.2.0; extra == "llm"
Provides-Extra: all
Requires-Dist: pytest>=8.1.0; extra == "all"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "all"
Requires-Dist: pytest-cov>=5.0.0; extra == "all"
Requires-Dist: pytest-timeout>=2.3.0; extra == "all"
Requires-Dist: ruff>=0.4.0; extra == "all"
Requires-Dist: black>=24.3.0; extra == "all"
Requires-Dist: isort>=5.13.0; extra == "all"
Requires-Dist: mypy>=1.9.0; extra == "all"
Requires-Dist: pre-commit>=3.7.0; extra == "all"
Requires-Dist: transformers>=4.40.0; extra == "all"
Requires-Dist: trl>=0.8.6; extra == "all"
Requires-Dist: accelerate>=0.29.0; extra == "all"
Requires-Dist: datasets>=2.19.0; extra == "all"
Requires-Dist: sentencepiece>=0.2.0; extra == "all"
Dynamic: license-file

<div align="center">

<h1>CodeFix-Env</h1>

<p>A sandboxed reinforcement learning environment for training and evaluating LLM agents on automated code debugging, and the fast, verifiable feedback loop that kind of training requires.</p>

<p align="center">
  <a href="https://github.com/dhakarshailendra829/codefix-env/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/dhakarshailendra829/codefix-env/ci.yml?branch=main&style=for-the-badge" alt="CI status"></a>
  <a href="https://pypi.org/project/codefix-env/"><img src="https://img.shields.io/pypi/v/codefix-env?style=for-the-badge&color=blue" alt="PyPI version"></a>
  <a href="https://github.com/dhakarshailendra829/codefix-env/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=for-the-badge" alt="Apache 2.0 License"></a>
  <a href="tests/"><img src="https://img.shields.io/badge/tests-197%20passing-brightgreen?style=for-the-badge" alt="Tests passing"></a>
</p>

<p align="center">
  <strong>
    <a href="#quick-start">Quick Start</a> ·
    <a href="ARCHITECTURE.md">Architecture</a> ·
    <a href="SECURITY.md">Security</a> ·
    <a href="CONTRIBUTING.md">Contributing</a>
  </strong>
</p>

</div>

---

> **Status: active development.** The environment, sandbox, reward pipeline, and task registry are stable and tested. A trained-policy result and a larger, mined task set are in progress — see [Roadmap](#roadmap).

---

## Table of Contents

- [Why CodeFix-Env?](#why-codefix-env)
- [Install](#install)
- [Quick Start](#quick-start)
- [Deployment](#deployment)
- [How It Works](#how-it-works)
- [Benchmark](#benchmark)
- [Capabilities](#capabilities)
- [Roadmap](#roadmap)
- [Contributing](#contributing)
- [Security](#security)
- [License](#license)
- [Citations](#citations)

---

## Why CodeFix-Env?

Training a coding agent to debug software requires more than static examples of correct code. It requires a tight loop: propose a fix, execute it against a real test suite, and receive a signal that reflects genuine progress rather than superficial activity.

We do that because SWE-bench<sup>1</sup> gave coding agents a scalable, realistic evaluation standard, built on full repositories and real GitHub issues. What it does not give is a fast enough loop for on-policy reinforcement learning, where thousands of cheap episodes per training step are typically required.

Most environments used for this today sit at one of two extremes: repository-scale benchmarks that are realistic but slow to sandbox, or ad-hoc code execution with no meaningful isolation at all. CodeFix-Env is built for the space between them.

CodeFix-Env is building that middle layer:

> a sandboxed, densely-rewarded reinforcement learning environment for single-function code repair, fast enough to serve as a rollout source, with a stated threat model rather than an assumed one

We do that by:

- executing every agent action inside a layered sandbox — static AST filtering, restricted builtins, and OS-level process isolation — documented in full in [SECURITY.md](SECURITY.md), including two hardening attempts that failed under load and were reverted rather than left unreported
- computing a dense, per-step reward from hidden test-pass-rate deltas, rather than a single pass/fail signal at episode end
- mining task candidates directly from real, merged bug-fix pull requests on GitHub, so tasks can be traced back to an actual historical defect (`scripts/mine_tasks.py`)
- publishing the environment as an installable, continuously tested package rather than a static research repository

Our goal is to grow this into a task set and training result large enough to serve as a genuine benchmark and training ground for code-repair agents, in the same way SWE-bench did for repository-scale evaluation.

<sup>1</sup> https://arxiv.org/abs/2310.06770

---

## Install

```bash
pip install codefix-env
```

For development, or to use the training extras:

```bash
git clone https://github.com/dhakarshailendra829/codefix-env.git
cd codefix-env
python -m venv venv
source venv/bin/activate      # Windows: venv\Scripts\activate
pip install -e ".[dev]"       # add ",llm" for transformers/TRL/accelerate
```

Verify:

```bash
codefix-server info
```

---

## Quick Start

**Local environment** — run episodes directly in Python, no server required:

```python
from codefix_env import CodeFixEnvironment, CodeFixAction, ActionType

env = CodeFixEnvironment()
obs = env.reset(task_id="easy-001-missing-return")

result = env.step(CodeFixAction(action_type=ActionType.RUN_TESTS))
print(f"{result.observation.tests_passed}/{result.observation.tests_total} tests passing")

result = env.step(CodeFixAction(
    action_type=ActionType.EDIT_LINE,
    line_number=3,
    new_content="    return result",
))

result = env.step(CodeFixAction(action_type=ActionType.SUBMIT_FIX))
print("solved" if result.observation.all_tests_pass else "not solved", result.reward)
```

**Server mode** — expose the environment over HTTP for remote or multi-language clients:

```bash
codefix-server serve --port 8000
```

**Task inspection** — list and filter the task registry:

```bash
codefix-server tasks
```

**Baseline evaluation** — run oracle and random policies across the full task set:

```bash
python scripts/run_baseline_eval.py --episodes 3
```

---

## Deployment

The repository includes a `Dockerfile` for running the environment as a standalone service:

```bash
docker build -t codefix-env .
docker run -p 8000:8000 codefix-env
```

Set `CODEFIX_REWARD_MODEL_PATH` if using a trained neural reward checkpoint (see [ARCHITECTURE.md](ARCHITECTURE.md)). No other environment variables are required for the default, rule-based reward configuration.

---

## How It Works

When an episode runs, CodeFix-Env:

1. **Loads** a task — a buggy function, a hidden test suite, and graduated hints
2. **Receives** a structured action from the agent: run tests, edit a line, insert, delete, request a hint, view the code, or submit
3. **Executes** any code-mutating action inside the sandbox, isolated from the host process
4. **Computes** a unified diff against the original code and a dense, shaped reward from the test-pass-rate change
5. **Returns** the updated observation, including test output and the diff, so the agent can decide its next action
6. **Terminates** the episode on a full solve, an explicit submission, or the step budget running out

Full design detail, including the reward formula and the sandbox's layered isolation model, is in [ARCHITECTURE.md](ARCHITECTURE.md).

---

## Benchmark

Regenerate these numbers with `python scripts/run_baseline_eval.py --episodes 3`.

<!-- BENCHMARK-START -->

Oracle policy (applies the known-correct fix) versus a random policy, across all 21 tasks:

| Policy | Easy | Medium | Hard |
|---|---|---|---|
| Oracle | 100% | 87.5% | 60% |
| Random | 0% | 0% | 20% |

No trained-policy result yet — this compares two fixed baselines to confirm the reward signal discriminates genuine problem-solving from undirected action. A GRPO training result is in progress; see [Roadmap](#roadmap).

<!-- BENCHMARK-END -->

---

## Capabilities

| | |
|---|---|
| **Sandboxed execution** | Static AST filtering, restricted builtins, and OS-level process isolation, with a documented threat model |
| **Dense reward shaping** | Per-step reward from test-pass-rate deltas, hint-usage and step-count penalties, and a solve bonus |
| **Graded task registry** | 21 tasks across easy, medium, and hard tiers, each with hidden tests and progressive hints |
| **Task mining pipeline** | Extracts candidate tasks from real, merged GitHub bug-fix pull requests for human review |
| **Server and async client** | FastAPI HTTP server with a session-scoped API, plus an async client for training loops |
| **Framework-compatible** | Gymnasium-style `reset()`/`step()`/`state()` interface; usable with SFT, DPO, GRPO, and PPO training code |
| **CI-gated** | 197 tests, linting, and type checking on every change, across Python 3.10 through 3.12 |

---

## Roadmap

- Closed-loop RL training result: fine-tune a small open-weight code model against the environment and publish a measured pass-rate curve
- A trained checkpoint for the optional learned reward model, calibrated against oracle judgment
- Task registry expansion from 21 to several hundred tasks, mined and reviewed from real repositories
- Multi-file task support, extending beyond single-function scope
- Container-level sandbox isolation (namespace and capability restrictions, seccomp filtering)
- Support for a second programming language
- Horizontally scalable session handling for distributed rollout collection
- Listing on the OpenEnv Hub

---

## Contributing

Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for local setup, the task-authoring template, and the pull request workflow.

---

## Security

Execution isolation is treated as a first-class design concern, not an afterthought — including reporting what the current sandbox does not protect against. See [SECURITY.md](SECURITY.md) for the full threat model and for responsible disclosure of any suspected sandbox escape.

---

## License

Apache License 2.0 — see [LICENSE](LICENSE).

## Citations
<sup>2</sup> Dhakad, S. CodeFix-Env: A Sandboxed Reinforcement Learning Environment for Automated Code Debugging. arXiv:2607.XXXXX, 2026.

