Repo2RLEnv
CLAUDE.md696 starsChanged 2 months agoApache-2.0View on GitHub
Auto-loaded by Claude Code for anyone working in this repo. It is committed and shared, so it holds only what is true for any clone: architecture, invariants, and the mistakes that are easy to make here. It is not a changelog and not a contributor guide. Those live elsewhere: If anything here conflicts with the code, trust the code and fix this file. Repo2RLEnv (repo2rlenv on PyPI) turns a repository into a verifiable RL training/eval dataset. End-to-end: synthesis → standardize…
- Reads credentials
In this repositoryOne other file it gives its agents.
- docs/reference/AGENTS.mdAGENTS.md
The file
We split this CLAUDE.md into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 17
If anything here conflicts with the code, trust the code and fix this file.
- Very specific: line 44
Never hand-edit
pyproject.toml'sdependencies: Use uv add <pkg> / uv add --dev <pkg>, or it desyncs from uv.lock. - Very specific: line 201
Delete this last. Override with R2E_CACHE_DIR.
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md — project memory for Repo2RLEnv
Auto-loaded by Claude Code for anyone working in this repo. It is committed and shared, so it holds only what is true for any clone: architecture, invariants, and the mistakes that are easy to make here.
It is not a changelog and not a contributor guide. Those live elsewhere:
| You want | Read |
| Dev setup, PR/commit conventions, code style, releases | CONTRIBUTING.md |
| Install → first dataset → push | docs/quickstart.md |
| What each pipeline does, its yield and options | docs/pipelines/README.md |
| Why a pipeline exists in its shape | docs/rfcs/ |
| Version history | docs/release_notes/HISTORY.md |
If anything here conflicts with the code, trust the code and fix this file.
What this is
Repo2RLEnv (repo2rlenv on PyPI) turns a repository into a verifiable RL
training/eval dataset. End-to-end: synthesis → standardize → train + eval,
focused on training. Datasets are emitted in the
Harbor task format so they drop
straight into Harbor's runtime ecosystem (Local Docker / Modal / Daytona / E2B /
Runloop + 22 agent harnesses).
GitHub: https://github.com/huggingface/Repo2RLEnv · PyPI: repo2rlenv · Apache-2.0.
Three layers, only the first is ours:
| Layer | We ship | We delegate |
| Generation (pipelines that produce tasks) | src/repo2rlenv/pipelines/ — the moat | — |
| Spec (uniform output format) | [metadata.repo2env] extension to Harbor's task.toml | Harbor's task spec |
| Consumption (sandboxes / agents / runtime) | HF Hub publish bridge; planned TRL trainer bridge | Harbor's full stack |
Invariants
Break these and the build, the CI, or the science breaks:
- Never
print()in library or CLI code. Everything goes throughrepo2rlenv.ui.console— see UI conventions. - Never hand-edit
pyproject.toml'sdependencies. Useuv add <pkg>/uv add --dev <pkg>, or it desyncs fromuv.lock. - Run
uv run pytest tests/test_pipeline_contract.pyafter touchingpipelines/. It fails for any registered pipeline that breaks the Protocol. - Anti-contamination is enforced by the environment, never requested in the
prompt. Native patch tasks use
pipelines/_env_guard.py. Owned recipes use scrubbed build contexts, explicit Harbor network policies and fresh private verifiers;execution/harbor_offline.pyis the tested single-container route for remote kernels without Harbor's dynamic firewall support. Don't add "please don't look up the fix" to an instruction — scrub the history and cut the egress instead. - New pipeline ⇒ RFC first. Any new
PipelineNameentry needs adocs/rfcs/NNNN-*.mdbefore the implementation PR. - New docs page ⇒ add it to a
docs/**/meta.json(usuallydocs/meta.json), or it won't appear in the site's sidebar. Seedocs/contributing/DOCUMENTATION.md. from __future__ import annotationsat the top of every module.- Version bumps never ride along in a feature PR — they happen on
mainafter merge, as their own commit. - Don't commit generated artifacts. Datasets go to the HF Hub; local run output stays gitignored.
Pipelines
Registry: pipelines/__init__.py:PIPELINES. Names: spec/input.py:PipelineName.
Per-pipeline detail (yield, sources, options, reference datasets):
docs/pipelines/README.md.
| Pipeline | Shape | Status | RFC |
pr_diff | text-only generation; thin Docker env for the 6-component diff-similarity reward | stable | 0001 |
pr_runtime | mines PRs, verifies an F2P/P2P oracle in the bootstrap sandbox | stable | 0002 |
commit_runtime | same, at commit level (bypasses PR-review filters) | stable | 0003 |
code_instruct | LLM authors a problem + verifier anchored to real repo source | experimental | 0004 |
equivalence_tests | extract a pure function; LLM writes tests against a reference_<name> oracle | experimental | 0005 |
cve_patches | OSV CVE → fix commit → task; reuses the pr_runtime verifier | experimental | 0006 |
repo_mutate / swe_smith | owned procedural source mutation and issue generation; separate Harbor verifier | experimental | 0012 |
terminal_synth / seta_seed2synth, tmax | owned seed/skill-based terminal task generation | experimental | 0013, 0018 |
task_evolve / seta_evol | evolve existing tasks with retained strategy prompts | experimental | 0014 |
pr_to_env / swe_gen | supplied PRs, source reversal and execution-grounded instruction | experimental | 0015 |
repo_reconstruct / swe_flow | traced dependency scheduling and missing-function reconstruction | experimental | 0016 |
equivalence_tests / r2e | owned generate/execute/coverage loop and specification refinement | experimental | 0017 |
terminal_synth / endless_terminals, dataarc | seedless terminal authoring and task evolution | experimental | 0020, 0022 |
terminal_reconstruct / terminalworld | reconstruct tasks from public terminal recordings | experimental | 0019 |
env_repair / cli_gym | invert a healthy environment and author a repair task | experimental | 0021 |
pr_runtime / swe_next | mine supplied repository PR history and author repair tasks | experimental | 0023 |
commit_runtime / r2e_gym | mine commit history and validate old/new behavior | experimental | 0024 |
reasoning_synth / scaler | expand released problem families into reasoning instances | experimental | 0026 |
RFCs 0007 pr_to_env / 0008 env_setup / 0009 test_synthesis /
0010 issue_runtime are drafted but not built.
Owned recipe integration follows RFC 0011 and method RFCs 0012–0026. Use
repo2rlenv pipelines list for implemented versus planned status. An export is
not quality acceptance: fresh execution, specification, attack and blind rollout
evidence must match its complete bundle hash. See docs/pipelines/owned_recipes.md.
Names follow {source}_{shape}:
_diff— no sandbox at generation time. (pr_diffstill emits a Docker env so its reward runs underharbor; "no sandbox" refers to generation, not consumption.)_runtime— runs inside the bootstrap sandbox to verify the oracle._patches/_instruct/_tests— the artifact type, for synthesized pipelines._to_env— import-shape: the caller supplies candidates, the pipeline doesn't mine them. The owned SWE-gen recipe uses this shape.
_bugs and _synthesis were retired with mutation_bugs / refactor_synthesis.
The contract
class Pipeline(Protocol):
name: ClassVar[PipelineName]
def __init__(self, input: GenerationInput, options: BaseModel) -> None: ...
def run(self, out_dir: Path) -> PipelineResult: ...Walkthrough for adding one:
docs/contributing/ADDING_A_PIPELINE.md.
Repo map
src/repo2rlenv/
├── cli.py # argparse registration/dispatch; shared CLI error boundary
├── spec/
│ ├── input.py # GenerationInput, RepoSpec, PipelineName, LLMSpec, OutputSpec
│ └── options.py # per-pipeline options models (PRDiffOptions, …)
│ # NB: the OUTPUT model is emitter/harbor.py:HarborTask
├── pipelines/ # `_`-prefixed files are SHARED MACHINERY, not pipelines
│ ├── recipes/ # owned methods; canonical prompts and provenance per recipe
│ │ ├── catalog.py # discovery metadata and lazy implementation registry
│ │ └── repository/ · terminal/ · history/ # shared recipe infrastructure
│ ├── base.py # Pipeline Protocol + PipelineResult
│ ├── pr_diff.py · pr_runtime.py · commit_runtime.py
│ ├── code_instruct.py · equivalence_tests.py · cve_patches.py
│ ├── pr_runtime_validate.py # shared PR validation harness (pr_runtime, cve_patches)
│ ├── _env_guard.py # anti-contamination: git-history scrub + egress guard (EVERY task)
│ ├── _eval_script.py # verifier-script + diff helpers (make_unified_diff, all_tests_passed)
│ ├── _pr_diff_verifier.py # in-container 6-component diff-similarity reward (stdlib, base64-baked)
│ ├── _pr_runtime_verifier.py # in-container graded F2P/P2P reward
│ ├── _oss_instruct.py # code_instruct synthesis + its 4 quality gates
│ ├── _function_extractor.py # equivalence_tests: purity/self-containment filter, AST rename
│ └── _poc_agent.py # cve_patches: LLM+shell PoC-test synthesis in the vuln sandbox
├── bootstrap/ # LLM-driven Docker env generation
│ ├── runner.py # ensure_bootstrap() orchestrator
│ ├── agent.py # ReAct loop (enforces max_llm_spend_usd)
│ ├── docker.py # DockerSandbox primitives
│ ├── language.py # auto-detect Python/JS/Go/Rust/...
│ ├── cache.py # content-addressed cache, keyed on bootstrap opts
│ └── spec.py # BootstrapSpec / BootstrapResult
├── tasksmith/ # PR exploration, staged authoring and runtime adapters
├── quality/ # evidence review, probes, bounded repair and labels
├── campaigns/ # shared budgets, receipts, scheduling and releases
├── execution/ # provider workers, remote jobs and Harbor trials
├── registry/ # bootstrap-image distribution
│ ├── push.py · auth.py · naming.py · probe.py · visibility.py · integration.py
│ └── ecr.py · gar.py # AWS ECR + Google AR, beyond GHCR / Docker Hub
├── log_parsers/ # test output → F2P/P2P sets
│ └── pytest_parser.py · go_parser.py · cargo_parser.py · jest_parser.py
├── ui/ # Rich UI — every CLI surface goes through here
│ ├── console.py # singleton R2EConsole + install_logging()
│ ├── errors.py # JSON error records; diagnostics on stderr
│ ├── theme.py · primitives.py · live.py
│ └── views/{bootstrap,generation,recipe}.py
├── emitter/harbor.py # Task → Harbor task.toml directory writer
├── sources.py · provider.py # source kinds + Capability gating; provider dispatch
├── github.py · gitlab.py · git_local.py · osv.py # the four input backends
├── hub.py # HF Hub push/pull + Harbor-compatible registry.json
├── auth.py # token resolution (repo / LLM / registry / Hub)
├── llm.py # LiteLLM wrapper + completion_cost tracking
├── reward.py # SWE-RL-style diff-similarity reward (stdlib only)
├── validation.py # `validate --deep`: static task-asset + reproducibility checks
└── config.py # YAML/TOML config loader
tests/ # unit tests mirror the module they cover; e2e in test_e2e_*.py
docs/ # docs content (.md/.mdx) — sidebar lives in docs/**/meta.json
├── introduction.mdx # the site's landing page is website/app/(home)/page.tsx
├── quickstart.mdx
├── concepts/ guides/ # how it works, task anatomy, rewards, quality; how-to guides
├── pipelines/ # index.md + one page per pipeline (paths are linked from dataset cards)
├── rfcs/ # 0001–0010 + TEMPLATE.md + process README
├── reference/ # SPEC · API · AUTH · BOOTSTRAP · AGENTS · ENV
│ # · REWARD_SCHEMA · REGISTRY_AUTH · RELATED_WORK
├── contributing/ADDING_A_PIPELINE.md
└── release_notes/ # HISTORY.md + per-release deep dives
website/ # Fumadocs (Next.js) docs site, static export; `npm run dev` there
.github/workflows/ # ci.yml (lint + 3.12/3.13/3.14 matrix + build) · release.ymlLocal artifacts (all gitignored)
The tool writes everything under ./workspace/ by default; --out and
R2E_CACHE_DIR override it. Nothing there is committed, and it's all
regenerable — but at very different cost:
workspace/bootstrap/— per-repo Docker env cache, content-addressed on the bootstrap options. Each entry costs real LLM spend (~$3–8/repo) to rebuild. Delete this last. Override withR2E_CACHE_DIR.- Dataset stagings — cheap; the canonical copies live on the HF Hub and come
back with
repo2rlenv pull. harbor runoutput, fetched diffs, agent transcripts — free or cheap to re-fetch.
plans/ and references/ are also gitignored: internal working notes and shallow
clones of the inspiration repos (SWE-bench, SWE-smith, R2E-Gym, Magicoder, …). They
are per-developer and won't exist in a fresh clone — don't write code that assumes
either is present.
UI conventions
from repo2rlenv.ui import console
console.success("emitted task X") # ✓ green
console.info("starting pipeline...") # ⓘ cyan
console.warn("smoke gate exited 5") # ⚠ yellow
console.error("docker daemon down") # ✗ red
console.kv({"reward": 0.98, ...}, title="...") # panel with key/value table
with console.section("Pushing to Hub"): ... # bracketed ruleFor long-running work with a redrawing display, add a view under ui/views/:
with BootstrapView(...) as view:
ensure_bootstrap(..., on_turn=view.on_turn,
on_phase=view.on_phase,
on_thinking=view.on_thinking,
on_executing=view.on_executing)
view.set_outcome(success=True, ...)Logging routes through RichHandler via install_logging() (called from
cli.py:main()). Noisy loggers (litellm / httpx / anthropic / openai) are
auto-suppressed to WARNING while a Live is active.
Input sources + auth
--repo accepts a GitHub owner/name, a gitlab.com URL, or a local path
(/abs, ./rel, ~, file://; on Windows also C:\abs, .\rel, UNC —
canonicalized to file://<abspath>).
RepoSpec.source_kind classifies it; sources.py defines a Capability
(pull_requests / issues / commit_api) per source and per pipeline's
required_capabilities. cmd_generate gates incompatible combinations up front —
e.g. pr_diff against a local path is refused with a clear error.
- Any source:
commit_runtime,code_instruct,equivalence_tests - GitHub or GitLab:
pr_diff,pr_runtime(gitlab.com MRs viagitlab.py, dispatched byprovider.py) - GitHub only:
cve_patches(needs OSV + the GitHub commit API)
auth.resolve_repo_token() dispatches by source: local → None (no gh
shell-out); gitlab → repo.auth_token_env then $GITLAB_TOKEN; github →
resolve_github_token(), which tries in order:
repo.auth_token_envenv var (if set in config)gh auth token(default — works for anyone who has rungh auth login)$GITHUB_TOKENNone(anonymous; fails on private repos)
HF Hub auth uses huggingface_hub's own resolution
(~/.cache/huggingface/token or $HF_TOKEN). LLM keys come from provider-default
env vars (ANTHROPIC_API_KEY, OPENAI_API_KEY, …) via auth.resolve_llm_api_key() —
only for the providers in auth.LLM_KEY_ENV_DEFAULTS. Anything else is left to LiteLLM's
own lookup, and a self-hosted LLMSpec.endpoint (--llm-endpoint) needs no key at all
(llm._resolve_api_key).
Registry push credentials resolve from explicit env vars first: GHCR reads
GHCR_TOKEN / GITHUB_TOKEN (needs a one-time
gh auth refresh -h github.com -s write:packages); Docker Hub reads
DOCKER_USERNAME + DOCKER_TOKEN (a PAT — the credstore's OAuth token is
pull-only) and pushes under the Docker Hub user's namespace. ECR and Google AR
have their own modules. Multi-repo datasets push one image per repo and rewrite
each task to its own digest. Details: docs/reference/REGISTRY_AUTH.md; full env
var list: docs/reference/ENV.md.
Cost tracking
llm.complete() returns LLMResponse.cost_usd via
litellm.completion_cost(response), accumulated into
AgentOutcome.total_cost_estimate_usd and BootstrapResult.llm_cost_estimate_usd.
BootstrapSpec.max_llm_spend_usd is enforced inside agent.py:run_agent_loop —
at total_cost ≥ max_spend_usd the loop short-circuits with
success=False, reason="cost budget exceeded: ...". The runner logs the budget at
startup.
Any change that adds LLM calls should thread cost through these fields rather than introducing a parallel counter.
Tests
uv run pytest -q is the canonical command; CI runs it on Python 3.12 / 3.13 / 3.14.
Conventions (fixtures over mocks, specific exception types, where files live) are in
CONTRIBUTING.md. Two things worth knowing before you
debug a red run:
- Some tests are opt-in and skip by default — they need live network or
credentials, and are gated behind env vars (
R2E_LIVE_PROBE_GHCR,R2E_E2E_HUB_BUILD,R2E_LIVE_GITLAB). Skips here are expected. tests/test_e2e_public.py::test_e2e_public_trlis flaky by construction. It hits the live GitHub API and asserts that ≥1 task is emitted from the two most recent PRs onhuggingface/trl, so it fails withskip_reasons={'diff_too_small': N}whenever those PRs happen to be small. That is not a regression — don't chase it.
Design decisions
- No bind mounts for the bootstrap container — the repo is
docker cp'd in sodocker commitcaptures it. Bind mounts are runtime overlays and aren't included in committed images.bootstrap/docker.py:DockerSandbox.start. - Lenient smoke gate — pytest exit codes 0, 1 and 5 all mean "env works"
(1 = tests ran and failed; 5 = nothing collected). Only 2+ is a real env problem.
bootstrap/runner.py. - Test commands are joined with
&&—test_cmdsruns as a single bash invocation soexport PATH=…carries into the next command. Don't loopsandbox.exec()over the list. registry_urluses Harbor's legacy format — we publish aregistry.jsonthatharbor download --registry-url <url>consumes directly, so no Harbor patches are needed.- No
repo2rlenv run, no parallel sandbox runtime — running full tasks isharbor run's job. This project is synthesis-only. - Multi-repo datasets work in both push modes —
inlinebakes each task's own bootstrap recipe from the verifiedrebuild_cmds(NOT the agent transcript);registrypushes each distinct image and rewrites each task to its digest.pushclean-syncstasks/**(a deleted task disappears from the Hub) and auto-writesmanifest.json. Runtime pipelines shiptests/{verifier.py,f2p.json,p2p.json}as plain files — Harbor mountstests/at/tests, so no base64 intest.sh. - The environment enforces, the prompt never asks —
_env_guard.pyscrubs git history back tobase_commitand blackholes PyPI/GitHub egress for every emitted task, because a sandbox-verified task is otherwise gameable by fetching the published fix. Background:docs/release_notes/HISTORY.md.
External dependencies
- Harbor (
uv tool install harbor) — runs the generated tasks. We deliberately don't ship a parallel runtime. - Docker — required for
bootstrapand every_runtimepipeline.pr_diffgenerates without it, though its emitted task runs in Docker (thinpython:3.12-slim); setemit_harbor_env=Falsefor pure text output. - LiteLLM — the single client across providers (Anthropic / OpenAI / HF Router / Bedrock / Ollama / vLLM).
- Rich — every CLI surface; foundation of
ui/. - huggingface_hub — dataset publish/pull.
ghCLI — clone + PR listing; the least-friction GitHub auth path.
Common commands
# Generate a sandbox-verified dataset (auto-triggers bootstrap if needed)
uv run repo2rlenv generate \
--repo <owner>/<repo> --pipeline pr_runtime \
--pipeline-opt limit=10 \
--llm anthropic/claude-sonnet-4-6 \
--out ./workspace/datasets/<name>
# Validate a dataset (fast structural check — no LLM, no Docker)
uv run repo2rlenv validate ./workspace/datasets/<name>
# ...plus task assets + reproducibility metadata (still static); --oracle adds solution/
uv run repo2rlenv validate ./workspace/datasets/<name> --deep
# Publish / retrieve (a bare name resolves its owner via whoami)
uv run repo2rlenv push ./workspace/datasets/<name> <org>/<name>
uv run repo2rlenv pull <org>/<name>
# Everything CI runs
uv run pytest -q && uv run ruff check . && uv run ruff format --check .
# Dependencies
uv add <pkg> # runtime
uv add --dev <pkg> # dev onlyStatus
Version is whatever pyproject.toml says (__version__ reads package metadata).
Native pipelines and owned recipe families share the registry. Use repo2rlenv pipelines list for current availability; see
docs/release_notes/HISTORY.md for how it got here.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

