repo2rlenv

repository·main·Indexed 19 days ago

https://github.com/huggingface/repo2rlenv

A tool to turn GitHub, GitLab, or local repositories into verifiable Reinforcement Learning (RL) environments. It synthesizes tasks from code changes (PRs, commits, CVEs) and exports them into the Harbor specification for training and evaluating coding agents. Version 0.8.8 includes six pipelines such as pr_diff, pr_runtime, and cve_patches, featuring contamination defenses like git-history scrubbing and egress guards.

Tokens
52K
Snippets
122
Records
228
Agent score
66%

What's inside repo2rlenv

  1. Overview of the `cve_patches` pipeline

    main

    The cve_patches pipeline is an experimental tool for the Python ecosystem that maps OSV (Open Source Vulnerabilities) records to fixing commits in a target repository. It creates reusable tasks for the Repo2RLEnv format by replaying the pre-fix state in a sandbox and using the upstream security patch as an oracle.

    Key Characteristics:

    • Status: Experimental (Python ecosystem).
    • Requirements: Requires a sandbox for generation and an LLM (for bootstrapping and PoC synthesis).
    • Reward Kinds: Emits test_execution and diff_similarity.
    • Yield: Typically low (~5–25%) because it requires a verifiable 'fail-to-pass' oracle (either a shipped regression test or a synthesized PoC).
  2. Overview of the `pr_diff` pipeline

    main
    The pr_diff pipeline is a SWE-RL-inspired tool for mining real-world GitHub Pull Requests (PRs) to create training tasks. It converts merged PRs into Harbor-runnable tasks where an agent attempts to replicate the PR's changes. The pipeline includes a multi-component verifier that scores the agent's output against the original (gold) diff using a combination of deterministic metrics and an optional LLM-as-judge.
  3. Compare available repo2rlenv pipelines

    main

    The project provides 6 pipelines, categorized by stability and use case.

    PipelineProducesSourceSandboxLLM UseReference Dataset
    pr_diffEnv + 6-component diff-similarity rewardGitHub/GitLabthin (Docker)at verify (judge)AdithyaSK/repo2rlenv-pr-diff
    pr_runtimeSandbox-verified PR with F2P/P2P oracleGitHub/GitLab✅ (Docker)at bootstrap (cached)AdithyaSK/repo2rlenv-pr-runtime
    commit_runtimeCommit-level oracleGitHub/GitLab/local✅ (Docker)at bootstrap (cached)
    code_instructLLM-authored problem + executable verifierGitHub/GitLab/local✅ (Docker)at synthesisrepo2rlenv-code-instruct
    equivalence_testsExtracted function + LLM equivalence testsGitHub/GitLab/local✅ (Docker)at synthesispending v0.8.8
    cve_patchesOSV CVE $\rightarrow$ fix commit $\rightarrow$ Harbor taskGitHub✅ (Docker)at bootstrap (cached)AdithyaSK/repo2rlenv-cve-patches

    Key Concepts:

    • Source: --repo can be a GitHub owner/name, a gitlab.com URL, or a local path (/abs, ./rel, ~, file://).
    • Sandbox: requires Docker. thin uses a lightweight python:3.12-slim image built at generation time. means text-only (no execution).
    • LLM Use: at synthesis is the heaviest spend (authoring content). at bootstrap (cached) runs once per repo and is cached. at verify is used for reward calculation (e.g., pr_diff's judge).
  4. What is the `code_instruct` pipeline?

    main

    The code_instruct pipeline is a specialized data generation pipeline that creates coding tasks grounded in a specific target repository. Unlike standard OSS-Instruct methods that produce text-only problem/solution pairs, code_instruct ensures every task is:

    1. Repo-anchored: The task is solvable within the target repository's specific environment.
    2. Verified by execution: Every task includes an executable pytest verifier.
    3. Validated by an oracle: The LLM-generated solution (the oracle) must pass the generated test within the repository's Docker sandbox.

    This pipeline is currently shipped (v0.8.6 hardened) and supports Python only. It requires both an LLM and a sandbox environment during the generation phase.

  5. What is Environment Bootstrap in repo2rlenv?

    main

    Bootstrapping is the process of creating a Docker image where a specific GitHub repository builds cleanly and its test suite runs. Because different repositories have diverse setup requirements (e.g., Python with uv/poetry, JS with pnpm/npm, Rust with specific toolchains), repo2rlenv uses an LLM agent to automate this.

    The agent reads the repo, executes shell commands in a sandbox, and iterates until build and tests succeed. The resulting Docker image is cached locally and reused for all subsequent tasks generated from that repo, ensuring you only pay the LLM cost once per (repo, commit).

  6. Understand the `cve_patches` pipeline algorithm

    main

    The cve_patches pipeline follows these steps to create a security task:

    1. Vulnerability Lookup: Queries the OSV database for vulnerabilities affecting the repository's package.
    2. Commit Resolution: Maps each vulnerability to its fixing commit URL using OSV references.
    3. Patch Extraction: Uses git show on the fixing commit to extract the source_patch and test_patch.
    4. Branching Logic:
      • Branch A (Test exists): If the CVE includes a test, it proceeds to standard validation (F2P/P2P) in a sandbox.
      • Branch B (No test): If no test is found (common for ~60-70% of entries), the PoC agent (_poc_agent.py) is triggered. An LLM with shell access inside the vulnerable sandbox writes a regression test that fails on the pre-fix state and passes on the post-fix state.
    5. Validation & Emission: Validates the resulting patch/test tuple and emits a Harbor task.
  7. Understand the relationship between the CLI and Python API

    main

    The repo2rlenv CLI is a thin wrapper around the Python API. Most CLI commands have a direct Python equivalent:

    CLI subcommandPython equivalent
    repo2rlenv generate ...pipelines.PIPELINES[name](input, opts).run(out_dir)
    repo2rlenv validate <path>Walk task.toml files + tomllib.loads
    repo2rlenv push <dir> <owner>/<name>hub.push_to_hub(local_dir, repo_id, auth, ...)
    repo2rlenv pull <owner>/<name> [<dir>]hub.pull_from_hub(repo_id, local_dir, auth, ...)
    repo2rlenv bootstrap ...bootstrap.ensure_bootstrap(repo, spec, llm)
    diff-similarity rewardreward.calculate_diff_similarity_reward(oracle, prediction) (Python only)
    test-execution rewardharbor run --agent <agent> --path <task> (separate tool)
  8. How the `test_synthesis` reward is calculated

    main

    The reward for a test_synthesis task is designed to encourage tests that are both accurate (pass on fixed, fail on broken) and useful (increase code coverage).

    Reward Formula:

    reward = (1 - coverage_weight) * b_pass * b_fail + coverage_weight * cov

    Components:

    • b_pass: The fraction of the agent's emitted tests that pass on the fixed variant.
    • b_fail: The fraction of the agent's emitted tests that fail on the broken variant.
    • cov: The coverage delta, calculated as min(1.0, added_lines_covered / target_new_lines). This measures how many new lines in the touched function were covered by the agent's tests compared to the baseline coverage of the existing test suite.

    Note that the product b_pass * b_fail ensures that tests which fail to discriminate (e.g., tests that pass on both or fail on both) result in a zero score for that component.

  9. Understand the `pr_diff` reward mechanism

    main

    The pr_diff pipeline uses a diff_similarity reward kind. The reward is a weighted sum of 6 components designed to measure how closely an agent's patch matches the original merged PR diff.

    Reward Components:

    ComponentWeightDescription
    format_valid0.00Guard: ensures the output parses as a unified diff.
    size_sanity0.08Ratio of oracle LOC to predicted LOC.
    file_targeting0.12F1 score over the set of changed files.
    region_overlap0.20Overlap of predicted hunks vs oracle hunks (with 5-line slack).
    similarity0.10SequenceMatcher score over +/- lines only.
    llm_judge0.50Semantic correctness rating via Anthropic Haiku 4.5.

    Constraints:

    • Catastrophic-size cap: If size_sanity < 0.10, the total reward is clamped to $\le 0.40$.
    • Graceful Degradation: If no LLM API key is provided, judge_status is set to no_api_key and the other 5 components are renormalized to sum to 1.0.
    • Oracle Invariant: The original merged diff always scores exactly 1.0.
  10. Handle dependency changes in PRs

    main

    Pipelines that generate per-PR tasks default to re-installing dependencies after a git checkout.

    • Additive dependencies: Automatically captured by the pipeline; no re-bootstrap required.
    • Build system replacements: If a PR changes the core build system, you must trigger a fresh bootstrap using the --force-bootstrap flag.
  11. Anti-contamination measures in `cve_patches`

    main

    Because CVE tasks have high contamination risk (public advisories, PyPI release notes, etc.), the pipeline implements multiple layers of defense:

    • Network Isolation: An egress guard (_env_guard.py) blackholes PyPI to prevent the environment from downloading the already-patched version of a package.
    • Git-history Scrubbing: Mandatory scrubbing of git history during emission.
    • Leak-stripped Instructions: The pipeline strips CVE/GHSA IDs, PR/commit URLs, and phrases like "fixed in vX.Y" or "Closes #N" from the LLM prompts. The prompt only contains the symptom.
    • Agent Constraints: The PoC agent is both prompted and regex-checked to ensure it does not include the fix commit SHA or CVE ID in the synthesized test.
  12. Contamination defenses in pipelines

    main

    To prevent agents from accessing 'gold patches' or fixes via the network or git history, repo2rlenv pipelines implement three layers of defense during generation (via pipelines/_env_guard.py):

    1. Git-history scrub: After checking out the base_commit, the environment removes the origin remote and prunes all refs/commits past the base. This prevents agents from using git diff origin/main or git show to find the fix.
    2. Egress guard: A environment/docker-compose.yaml overlay blackholes major package indices and code hosts (e.g., pypi.org, github.com, files.pythonhosted.org). This prevents pip download or git fetch from retrieving the fix while allowing model API access.
    3. Instruction leak-strip: Synthesized or CVE-based instructions are stripped of fix-pointers (such as CVE/GHSA IDs, PR/commit URLs, or version numbers), leaving only the symptom.

    Note: For maximum security and trustworthy evaluation, run with allow_internet=false to use an offline, self-contained image.