Skip to Content
Repo2RLEnv
Full prompts (generated)

Native generation and PR-diff judging: prompt reference

Edit on GitHub

Read the prompt stage map first. These files contain the bootstrap instructions, authoring prompts and request assembly. PR-diff's judge runs during grading, not generation. Source is shown for inspection; this documentation executes none of it.

bootstrap/prompts.py

Source: src/repo2rlenv/bootstrap/prompts.py · SHA-256 da119f02446bb71cc77de63e8f53db25053a8987cbfb9d6659aba65c570d6064

Source hash covers the original file; trailing whitespace is omitted below.

Read bootstrap/prompts.py
"""Prompts for the bootstrap agent. Original — not derived from RepoLaunch."""

from __future__ import annotations

from repo2rlenv.bootstrap.presets import preset_hints_block
from repo2rlenv.bootstrap.spec import LanguageHint

SYSTEM_TEMPLATE = """\
You are r2e-bootstrap, an autonomous agent whose job is to take a repository and
make it build cleanly + run its test suite inside a Linux Docker container.

You are inside a long-lived container. The repository is checked out at
`/workspace`. State carries between commands — files you create, packages
you install, and environment variables you set all persist.

You have these tools. Emit EXACTLY ONE tool call per turn, in this format:

  Thought: <one or two sentences of reasoning>
  Action: <TOOL_NAME>
  Input: <argument string>

IMPORTANT: emit ONE Thought/Action/Input block per response, NEVER multiple.
If you have two things to do, do the first; the next turn lets you do the
second. Multiple Action blocks in one response cause the second to be
parsed as part of the first command and FAIL.

Tools:

  Action: BASH
  Input: any shell command (will be wrapped in `bash -lc`).
  → returns combined stdout/stderr + exit code

  Action: READ_FILE
  Input: a path inside the container (typically `/workspace/...`)
  → returns the file contents (truncated at 50KB)

  Action: LIST_DIR
  Input: a directory path inside the container
  → returns the entries

  Action: SAVE_SETUP
  Input: a JSON object: {{"rebuild_cmds": [...], "test_cmds": [...], "summary": "..."}}
  Call this AS SOON AS the environment can BUILD and TESTS CAN RUN.
  → Individual test failures are FINE — that's not your concern.
  → What matters: `pip install -e .` (or equivalent) succeeds AND
    `pytest --collect-only` (or equivalent) succeeds without import or
    missing-dependency errors.
  → You are verifying the BUILD ENVIRONMENT, not the repo's correctness.
    Real PRs that we later run will fix the failing tests — your job is
    just to make sure the env can run them at all.
  → DO NOT iterate trying to fix failing tests. Once you've confirmed
    `pytest --collect-only` works, declare success.
  → For test_cmds, save the ACTUAL execution command (e.g. `python -m pytest -v`),
    NOT `--collect-only`. Exit code 1 (tests ran but some failed) is fine — downstream
    pipelines need per-test pass/fail output, which `--collect-only` cannot provide.

  ★ STOP CONDITION — read carefully ★
  When `pytest --collect-only` reports a count like "N tests collected"
  (even with "W warnings" or "M errors during collection" listed below
  the count), the environment IS WORKING — call SAVE_SETUP IMMEDIATELY.
  Collection errors / warnings are almost always missing optional plugins
  (pytest-asyncio version drift, pytest-trio missing, etc.) that don't
  prevent the suite from running. Real PRs we later evaluate will exercise
  only a subset of tests; the noisy warnings are NOT your problem to fix.
  Spending iterations chasing these is exactly how runs hit max_iterations.

  ★ CRITICAL — test_cmds MUST be SELF-CONTAINED ★
  After SAVE_SETUP we commit the container and then run `test_cmds` in a
  FRESH shell (a new `bash -lc` from the committed image — no inherited
  state, no activated venv, no exported PATH). If you used a virtualenv
  (uv / venv / poetry), EVERY entry in `test_cmds` must include the
  activation prefix, e.g.:
      ". /workspace/.venv/bin/activate && python -m pytest -v"
  Similarly `rebuild_cmds`: if the install requires the venv, prefix it
  with the activation. Prefer system-wide installs (`pip install ...`
  without a venv) when possible — they survive the fresh-shell verify
  without any prefix and are simpler to reason about.

  After SAVE_SETUP we commit the container as the bootstrap image.

  Action: GIVE_UP
  Input: a one-line explanation
  Call this if you've tried hard and can't make the build work. Better
  than burning iterations on a dead end.

Constraints:

- The container is {platform}. Don't install GUI stuff.
- Prefer minimal installs over kitchen-sink installs. apt-get install only
  what's needed.
- After installing system deps, set DEBIAN_FRONTEND=noninteractive.
- Detected language: {language}.
- Suggested base setup is already in the image: {base_image}.

Language-specific guidance for this run:
{preset_hints}

Workflow expectations:

1. Look at the repo structure (`ls`, `cat README.md` snippets, find setup files)
2. Install system dependencies if any
3. Install the project's own dependencies (pip / npm / cargo / go mod / etc.)
4. Try to build / install the package itself
5. Run the test suite once with a SMALL subset (e.g. `pytest --collect-only` or
   one fast test) to verify the env works
6. Call SAVE_SETUP with the rebuild and test commands

Be efficient. Each turn is an LLM call costing money. If a command's output
is huge, redirect to /dev/null or grep for the part you need.
"""


def system_prompt(*, language: LanguageHint, base_image: str, platform: str) -> str:
    return SYSTEM_TEMPLATE.format(
        language=language.value,
        base_image=base_image,
        platform=platform,
        preset_hints=preset_hints_block(language),
    )


INITIAL_USER_PROMPT = """\
Repository: {repo}
Ref: {ref}
You are now in /workspace. The repository is checked out at HEAD={short_ref}.

Begin. Explore the repo structure first, then plan your installation steps.
"""


def initial_user_prompt(*, repo: str, ref: str) -> str:
    return INITIAL_USER_PROMPT.format(repo=repo, ref=ref, short_ref=ref[:12])

bootstrap/presets.py

Source: src/repo2rlenv/bootstrap/presets.py · SHA-256 f77e6fb424a4a3451d4ecf6e048db3a70b8058115e5ea06f6096583e902fc3d3

Source hash covers the original file; trailing whitespace is omitted below.

Read bootstrap/presets.py
"""Per-language presets to seed the bootstrap agent with known-good patterns.

The agent works for any repo, but giving it language-specific hints (where
the manifest file lives, what install command to try first, which sanity
check is fastest, what known gotchas to avoid) reliably cuts iterations and
cost by 30-50% on common stacks.

These are *hints*, not policy: the agent is free to ignore them when the
repo looks unusual. The prompts module injects them into the system prompt.

Keep this file dependency-free: imported during prompt construction in cold
paths, so we don't want it to drag in heavy modules.
"""

from __future__ import annotations

from dataclasses import dataclass

from repo2rlenv.bootstrap.spec import LanguageHint


@dataclass(slots=True, frozen=True)
class LanguagePreset:
    """Recipe of known-good patterns for a single language ecosystem."""

    base_image: str
    apt_packages: tuple[str, ...] = ()
    install_hints: tuple[str, ...] = ()
    sanity_checks: tuple[str, ...] = ()
    known_pitfalls: tuple[str, ...] = ()


# Common gotchas we've hit across pipelines — apply to every preset.
# Keep terse; the agent reads these inside its system prompt every turn.
_UNIVERSAL_PITFALLS: tuple[str, ...] = (
    "POSIX character classes like `[:(]` are malformed — write `[(:]` instead.",
    "`grep` on a non-existent dir exits 2 and looks like 'no match'; search from `.` only.",
    "Prefer `python -m pytest` over bare `pytest` — non-interactive shells often lack pytest on PATH.",
    "Bash backticks inside echo strings command-substitute; use single quotes for literal names.",
    "Local image digests aren't pullable via BuildKit; refer to images by tag when running locally.",
)


PRESETS: dict[LanguageHint, LanguagePreset] = {
    LanguageHint.PYTHON: LanguagePreset(
        base_image="python:3.12-slim",
        apt_packages=("git", "build-essential", "curl", "ca-certificates"),
        install_hints=(
            "Look for `pyproject.toml`, `setup.py`, `setup.cfg`, or `requirements.txt`.",
            "PREFER SYSTEM-WIDE installs over venvs — `pip install -e .[dev,test]` directly. "
            "The container IS the venv. System-wide installs survive `docker commit` AND "
            "the post-commit fresh-shell verify without any activation prefix.",
            "If you MUST use uv/venv (e.g. the project's deps force it), remember test_cmds "
            "will run in a fresh `bash -lc` shell — every test_cmd entry must include "
            "`. /workspace/.venv/bin/activate &&` as a prefix.",
            "Prefer `pip install -e .[dev,test]` or `[test]` extras when declared; "
            "fall back to `-e .` plus the explicit dev/test requirements file. "
            "Some projects declare optional components via separate extras (e.g. black's `[d]` "
            "extra installs blackd needed by tests) — check `pyproject.toml`'s `[project.optional-dependencies]`.",
            "After install, defensively run `pip install pytest pytest-xdist` — many repos "
            "declare these via extras the agent can miss.",
        ),
        sanity_checks=(
            "python -c 'import sys; print(sys.version)'",
            "python -m pytest --collect-only -q | head -50",
        ),
        known_pitfalls=(
            "Some packages need `xprocess`, `pytest-asyncio`, `pytest-trio`, etc. — "
            "if collection fails with import errors, install the missing plugin.",
            "Editable installs of namespaced packages require `pip install -e . --config-settings "
            "editable_mode=compat` on newer pip versions.",
            "Use `python -m pytest` (NEVER bare `pytest`) — agent's verifier shells often lack it on PATH.",
            "SHALLOW CLONE + version-from-git: the workspace is a depth=1 clone, so projects using "
            "`hatch-vcs` or `setuptools_scm` cannot derive a version from git tags. Symptom: "
            "`pip install` fails inside the build hook with a version detection error. "
            "Fix: prepend an env var BEFORE the install, e.g. "
            "`SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 pip install -e .` or "
            "`HATCH_VCS_PRETEND_VERSION=0.0.0 pip install -e .`. Do NOT try to sed pyproject.toml.",
            "CYTHON-COMPILED packages (aiohttp, lxml, sqlalchemy[c], pyzmq, ...): `setup.py` "
            "expects pre-generated `.c` files alongside the `.pyx` sources. A fresh `pip install` "
            "without those files fails with 'No such file or directory: <pkg>.c'. Fix: run the "
            "project's own codegen step BEFORE pip install. Most repos ship a `make cythonize` "
            "(check the Makefile); otherwise `pip install cython && cython <path>/*.pyx` works.",
        ),
    ),
    LanguageHint.NODE: LanguagePreset(
        base_image="node:22-slim",
        apt_packages=("git", "build-essential", "python3", "ca-certificates"),
        install_hints=(
            "Detect package manager from lockfile: `pnpm-lock.yaml` → pnpm, "
            "`yarn.lock` → yarn, `package-lock.json` or none → npm.",
            "Use `corepack enable` then `pnpm install` / `yarn install` / `npm ci`.",
            "Monorepos: look for `pnpm-workspace.yaml` or `workspaces` in `package.json`; "
            "install at the root, then `cd` into the target package.",
            "Native modules (better-sqlite3, sharp) need `python3` + `build-essential`.",
        ),
        sanity_checks=(
            "node --version && npm --version",
            "npm test -- --listTests 2>/dev/null | head -20 "
            "|| npx mocha --dry-run 2>/dev/null | head -20",
        ),
        known_pitfalls=(
            "Express uses `mocha` not `jest` — `npm test` runs mocha directly.",
            "`npm ci` requires a lockfile; if absent, fall back to `npm install`.",
            "`prepare` scripts run husky/lefthook hooks that may fail in CI; "
            "set `HUSKY=0` or `--ignore-scripts` if hooks block install.",
        ),
    ),
    LanguageHint.GO: LanguagePreset(
        base_image="golang:1.23",
        apt_packages=("git", "ca-certificates"),
        install_hints=(
            "Look for `go.mod`. Run `go mod download` to fetch deps, then `go build ./...`.",
            "Most Go repos pass `go test ./...` straight away — no separate install step.",
            "Pin GOFLAGS to avoid surprises: `export GOFLAGS=-mod=mod`.",
            "If the repo vendors deps (`vendor/` dir), use `go build -mod=vendor`.",
        ),
        sanity_checks=(
            "go version",
            "go test -list '.*' ./... 2>&1 | head -30",
        ),
        known_pitfalls=(
            "`go test ./...` is the convention but pkg-by-pkg may be needed for slow suites.",
            "Some CLIs build a binary first (`make build`); check `Makefile` for the test target.",
            "Cgo deps (e.g. SQLite via mattn/go-sqlite3) need `apt-get install build-essential`.",
        ),
    ),
    LanguageHint.RUST: LanguagePreset(
        base_image="rust:1-slim",
        apt_packages=("git", "build-essential", "pkg-config", "libssl-dev", "ca-certificates"),
        install_hints=(
            "Look for `Cargo.toml`. `cargo fetch` to download deps, then `cargo build`.",
            "`cargo test --no-run` compiles tests without executing — fastest signal that the env works.",
            "Workspaces declare members in the root `Cargo.toml`; `cargo build --workspace` covers all.",
            "On slim images, expect to apt-install `pkg-config` and `libssl-dev` for crates using OpenSSL.",
        ),
        sanity_checks=(
            "rustc --version && cargo --version",
            "cargo test --no-run 2>&1 | tail -20",
        ),
        known_pitfalls=(
            "First `cargo build` is slow (~5 min for big repos); the agent should not assume a stalled command.",
            "Some crates need a `nightly` toolchain; install via `rustup toolchain install nightly`.",
            "`cargo test --doc` is required to exercise doctest blocks but is often slow — skip unless needed.",
        ),
    ),
    LanguageHint.JAVA: LanguagePreset(
        base_image="eclipse-temurin:21-jdk",
        apt_packages=("git", "ca-certificates"),
        install_hints=(
            "Look for `pom.xml` (Maven) or `build.gradle[.kts]` (Gradle).",
            "Maven: `mvn -B -DskipTests=false test-compile` validates env without running tests.",
            "Gradle: `./gradlew testClasses` is the dry-run equivalent.",
        ),
        sanity_checks=(
            "java --version",
            "mvn --version 2>/dev/null || ./gradlew --version 2>/dev/null",
        ),
        known_pitfalls=(
            "Gradle wrapper may need execute bit: `chmod +x gradlew`.",
            "Some projects require a specific JDK (8/11/17/21); check `.java-version` or `pom.xml` `<maven.compiler.source>`.",
        ),
    ),
    LanguageHint.C_CPP: LanguagePreset(
        base_image="ubuntu:24.04",
        apt_packages=("git", "build-essential", "cmake", "pkg-config", "ca-certificates"),
        install_hints=(
            "Detect from `CMakeLists.txt`, `configure.ac`, `Makefile`, or `meson.build`.",
            "CMake: `cmake -S . -B build && cmake --build build -j`.",
            "Autotools: `./autogen.sh || autoreconf -i && ./configure && make`.",
        ),
        sanity_checks=("gcc --version && cmake --version",),
        known_pitfalls=(
            "Header-only deps via `apt-get install lib<x>-dev` — guess based on `pkg-config --list-all`.",
        ),
    ),
    LanguageHint.UNKNOWN: LanguagePreset(
        base_image="ubuntu:24.04",
        apt_packages=("git", "build-essential", "curl", "ca-certificates"),
        install_hints=(
            "No language marker detected. Start with `ls -la` and `cat README.md | head -80` to inspect.",
            "Look for `Makefile` targets first — they're usually the canonical entry point.",
        ),
        sanity_checks=(),
        known_pitfalls=(),
    ),
}


def preset_for(lang: LanguageHint) -> LanguagePreset:
    """Return the preset for a language, falling back to UNKNOWN."""
    return PRESETS.get(lang, PRESETS[LanguageHint.UNKNOWN])


def preset_hints_block(lang: LanguageHint) -> str:
    """Render the preset as a prompt-ready bullet list. Includes universal pitfalls."""
    p = preset_for(lang)
    parts: list[str] = []

    if p.apt_packages:
        parts.append("Useful apt packages (install if missing): " + ", ".join(p.apt_packages))

    if p.install_hints:
        parts.append("Install hints:")
        parts.extend(f"  - {h}" for h in p.install_hints)

    if p.sanity_checks:
        parts.append("Quick sanity checks once env is built:")
        parts.extend(f"  - `{c}`" for c in p.sanity_checks)

    pitfalls = (*p.known_pitfalls, *_UNIVERSAL_PITFALLS)
    if pitfalls:
        parts.append("Known pitfalls:")
        parts.extend(f"  - {pit}" for pit in pitfalls)

    return "\n".join(parts) if parts else "(no language-specific presets available)"


def universal_pitfalls() -> tuple[str, ...]:
    """Exposed for tests / docs that want the raw list."""
    return _UNIVERSAL_PITFALLS

bootstrap/agent.py

Source: src/repo2rlenv/bootstrap/agent.py · SHA-256 e8ae8e0741b5c326dc31b5916696b087ef8a58901b6122b62dd4e2c2382c8b57

Source hash covers the original file; trailing whitespace is omitted below.

Read bootstrap/agent.py
"""ReAct-style bootstrap agent loop. Original implementation, not from RepoLaunch."""

from __future__ import annotations

import json
import logging
import re
import time
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, Literal

from repo2rlenv.bootstrap.docker import DockerSandbox, ExecResult
from repo2rlenv.bootstrap.prompts import initial_user_prompt, system_prompt
from repo2rlenv.bootstrap.spec import LanguageHint
from repo2rlenv.llm import complete
from repo2rlenv.spec.input import LLMSpec

logger = logging.getLogger(__name__)


ActionName = Literal["BASH", "READ_FILE", "LIST_DIR", "SAVE_SETUP", "GIVE_UP", "INVALID"]


@dataclass(slots=True)
class AgentAction:
    name: ActionName
    input: str
    raw: str = ""


@dataclass(slots=True)
class AgentTurn:
    step: int
    thought: str
    action: AgentAction
    observation: str
    cost_estimate_usd: float = 0.0
    prompt_tokens: int = 0
    completion_tokens: int = 0
    duration_sec: float = 0.0


@dataclass(slots=True)
class AgentOutcome:
    success: bool
    reason: str
    rebuild_cmds: list[str] = field(default_factory=list)
    test_cmds: list[str] = field(default_factory=list)
    summary: str = ""
    iterations: int = 0
    transcript: list[AgentTurn] = field(default_factory=list)
    total_cost_estimate_usd: float = 0.0


# Loose regex parser. Stops capturing Input at the next Action:/Thought:/
# Observation: header so a runaway LLM that hallucinates its own observation
# inline doesn't get that fake text fed into bash as part of the command.
_ACTION_RE = re.compile(
    r"Thought:\s*(?P<thought>.*?)\n+Action:\s*(?P<action>\w+)\s*\n+Input:\s*"
    r"(?P<input>.*?)(?=\n+Action:|\n+Thought:|\n+Observation:|\Z)",
    re.DOTALL | re.IGNORECASE,
)

# Common XML / tool-call artifacts that some models (e.g. Sonnet) leak into
# action inputs when they slip back into native tool-call mode. Stripped
# from both ends BEFORE execution so they don't crash bash with syntax errors.
_TOOL_CALL_TAGS = (
    "</parameter>",
    "</invoke>",
    "</function_calls>",
    "</function>",
    "</tool_use>",
)


def _sanitize_input(inp: str) -> str:
    """Strip trailing tool-call XML artifacts + simulated Observation: tails."""
    s = inp.strip()
    # Drop anything after a simulated `Observation:` header inside the input —
    # models sometimes write the command AND simulate its output.
    obs_match = re.search(r"\n\s*Observation\s*:", s, flags=re.IGNORECASE)
    if obs_match:
        s = s[: obs_match.start()].rstrip()
    # Repeatedly strip known tag artifacts from the end.
    changed = True
    while changed:
        changed = False
        stripped = s.rstrip()
        for tag in _TOOL_CALL_TAGS:
            if stripped.endswith(tag):
                s = stripped[: -len(tag)].rstrip()
                changed = True
                break
    return s


def parse_action(text: str) -> tuple[str, AgentAction]:
    """Extract (thought, action) from an LLM response. Lenient."""
    m = _ACTION_RE.search(text)
    if not m:
        return ("", AgentAction(name="INVALID", input=text.strip()[:500], raw=text))
    thought = m.group("thought").strip()
    name = m.group("action").strip().upper()
    inp = _sanitize_input(m.group("input"))
    if name not in ("BASH", "READ_FILE", "LIST_DIR", "SAVE_SETUP", "GIVE_UP"):
        return (thought, AgentAction(name="INVALID", input=inp, raw=text))
    return (thought, AgentAction(name=name, input=inp, raw=text))  # type: ignore[arg-type]


def _execute(action: AgentAction, sandbox: DockerSandbox) -> str:
    """Run a tool and return the observation string."""
    if action.name == "BASH":
        r: ExecResult = sandbox.exec(action.input)
        return f"exit={r.exit_code}\n{r.truncated()}"
    if action.name == "READ_FILE":
        try:
            return sandbox.read_file(action.input)
        except Exception as exc:
            return f"ERROR reading file: {exc}"
    if action.name == "LIST_DIR":
        entries = sandbox.list_dir(action.input or ".")
        return "\n".join(entries) if entries else "(empty or missing directory)"
    return ""  # SAVE_SETUP / GIVE_UP / INVALID handled by the loop


def _parse_save_setup(input_str: str) -> dict[str, Any]:
    """Tolerantly parse SAVE_SETUP JSON. Returns dict or raises.

    Uses `JSONDecoder.raw_decode()` so trailing text after the first complete
    JSON object is ignored — some models append a stray sentence, a second
    JSON object, or a literal `</invoke>` after the payload.
    """
    s = input_str.strip()
    # Strip code fences if present
    if s.startswith("```"):
        s = re.sub(r"^```(?:json)?\s*\n", "", s)
        s = re.sub(r"\n```\s*$", "", s)
    # Find the first `{` and parse just the first complete object from there.
    brace = s.find("{")
    if brace == -1:
        raise ValueError("SAVE_SETUP input contains no JSON object")
    payload, _ = json.JSONDecoder().raw_decode(s[brace:])
    if not isinstance(payload, dict):
        raise ValueError("SAVE_SETUP input must be a JSON object")
    for key in ("rebuild_cmds", "test_cmds"):
        if key not in payload:
            raise ValueError(f"SAVE_SETUP missing required key: {key!r}")
        if not isinstance(payload[key], list) or not all(isinstance(c, str) for c in payload[key]):
            raise ValueError(f"SAVE_SETUP {key!r} must be a list[str]")
    return payload


def run_agent_loop(
    sandbox: DockerSandbox,
    *,
    repo: str,
    ref: str,
    language: LanguageHint,
    base_image: str,
    llm: LLMSpec,
    max_iterations: int = 20,
    max_seconds: int = 1800,
    max_spend_usd: float | None = None,
    platform: str = "linux/amd64",
    on_turn: Callable[[AgentTurn, float], None] | None = None,
    on_thinking: Callable[[int], None] | None = None,
    on_executing: Callable[[int, AgentAction], None] | None = None,
) -> AgentOutcome:
    """Drive the bootstrap agent until it succeeds, gives up, or hits a budget."""
    system = system_prompt(language=language, base_image=base_image, platform=platform)
    history: list[str] = [initial_user_prompt(repo=repo, ref=ref)]
    transcript: list[AgentTurn] = []
    total_cost = 0.0
    start = time.monotonic()

    for step in range(max_iterations):
        if time.monotonic() - start > max_seconds:
            return AgentOutcome(
                success=False,
                reason=f"timeout after {max_seconds}s",
                iterations=step,
                transcript=transcript,
                total_cost_estimate_usd=total_cost,
            )
        if max_spend_usd is not None and total_cost >= max_spend_usd:
            return AgentOutcome(
                success=False,
                reason=f"cost budget exceeded: ${total_cost:.4f} ≥ ${max_spend_usd:.2f}",
                iterations=step,
                transcript=transcript,
                total_cost_estimate_usd=total_cost,
            )

        if on_thinking is not None:
            try:
                on_thinking(step)
            except Exception as exc:
                logger.debug("on_thinking callback failed: %s", exc)

        user_msg = "\n\n".join(history)
        turn_start = time.monotonic()
        response = complete(llm, system=system, user=user_msg, max_tokens=2048, temperature=0.2)
        total_cost += response.cost_usd
        thought, action = parse_action(response.content)
        logger.info(
            "step=%d action=%s cost=$%.4f thought=%.80s",
            step,
            action.name,
            response.cost_usd,
            thought,
        )

        if on_executing is not None and action.name not in ("INVALID", "GIVE_UP", "SAVE_SETUP"):
            try:
                on_executing(step, action)
            except Exception as exc:
                logger.debug("on_executing callback failed: %s", exc)

        if action.name == "INVALID":
            history.append(
                "Your previous response did not match the expected format.\n"
                "Re-emit using EXACTLY:\n  Thought: ...\n  Action: BASH|READ_FILE|LIST_DIR|SAVE_SETUP|GIVE_UP\n  Input: ..."
            )
            transcript.append(AgentTurn(step, thought, action, "format-error"))
            continue

        if action.name == "GIVE_UP":
            return AgentOutcome(
                success=False,
                reason=f"agent gave up: {action.input[:200]}",
                iterations=step + 1,
                transcript=transcript,
                total_cost_estimate_usd=total_cost,
            )

        if action.name == "SAVE_SETUP":
            try:
                payload = _parse_save_setup(action.input)
            except (json.JSONDecodeError, ValueError) as exc:
                history.append(
                    f"SAVE_SETUP rejected: {exc}. Re-emit with valid JSON containing rebuild_cmds and test_cmds."
                )
                transcript.append(AgentTurn(step, thought, action, f"save-rejected: {exc}"))
                continue
            return AgentOutcome(
                success=True,
                reason="agent declared success",
                rebuild_cmds=payload["rebuild_cmds"],
                test_cmds=payload["test_cmds"],
                summary=payload.get("summary", ""),
                iterations=step + 1,
                transcript=transcript,
                total_cost_estimate_usd=total_cost,
            )

        # BASH / READ_FILE / LIST_DIR
        observation = _execute(action, sandbox)
        history.append(
            f"Action: {action.name}\nInput: {action.input}\n\nObservation:\n{observation}\n"
        )
        turn = AgentTurn(
            step=step,
            thought=thought,
            action=action,
            observation=observation,
            cost_estimate_usd=response.cost_usd,
            prompt_tokens=response.prompt_tokens,
            completion_tokens=response.completion_tokens,
            duration_sec=time.monotonic() - turn_start,
        )
        transcript.append(turn)
        if on_turn is not None:
            try:
                on_turn(turn, total_cost)
            except Exception as exc:
                logger.debug("on_turn callback failed: %s", exc)

    return AgentOutcome(
        success=False,
        reason=f"hit max_iterations={max_iterations}",
        iterations=max_iterations,
        transcript=transcript,
        total_cost_estimate_usd=total_cost,
    )

pipelines/_oss_instruct.py

Source: src/repo2rlenv/pipelines/_oss_instruct.py · SHA-256 75d75ae91717b1ff7ece7b2498a3d135fada167e1cb8bfddaffe6384d90aee9b

Source hash covers the original file; trailing whitespace is omitted below.

Read pipelines/_oss_instruct.py
"""Helpers for the `code_instruct` pipeline: sampling, parsing, decontam.

Magicoder OSS-Instruct is a recipe (prompt template + sampling + parsing),
not a reusable library. This module is the recipe.

Acknowledgment
--------------
Algorithms inspired by Magicoder
(`references/magicoder/src/magicoder/generate_data.py:79-102` and
`magicoder/decontamination/find_substrings.py`). No code copied; we
reimplement against Python stdlib only.
"""

from __future__ import annotations

import ast
import fnmatch
import hashlib
import logging
import random
import re
import tomllib
from dataclasses import dataclass
from pathlib import Path

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Repo package detection — the LLM's oracle must import from THIS package
# ---------------------------------------------------------------------------


def detect_repo_package(clone_dir: Path, repo_name: str) -> str | None:
    """Find the top-level Python package name of the target repo.

    Order of attempts:
      1. `pyproject.toml` → `[project.name]` (normalized to underscores)
         or `[tool.poetry.name]`.
      2. `src/<candidate>/__init__.py` for candidate in {repo_name,
         repo_name.replace('-', '_'), 'attr'} (attrs ships as `attr`).
      3. `<candidate>/__init__.py` at repo root, same candidates.

    Returns the package name (a valid Python identifier), or None if
    detection fails — callers should skip repo-anchoring enforcement
    in that case rather than block generation.
    """
    # Try pyproject
    py = clone_dir / "pyproject.toml"
    if py.is_file():
        try:
            data = tomllib.loads(py.read_text(encoding="utf-8"))
        except (tomllib.TOMLDecodeError, OSError):
            data = {}
        name = (data.get("project", {}).get("name")) or (
            data.get("tool", {}).get("poetry", {}).get("name")
        )
        if name:
            candidate = name.replace("-", "_").lower()
            # Confirm the folder actually exists
            for base in (clone_dir / "src" / candidate, clone_dir / candidate):
                if (base / "__init__.py").is_file():
                    return candidate
    # Try well-known conventions
    candidates: list[str] = [
        repo_name.replace("-", "_").lower(),
        repo_name.lower(),
    ]
    # attrs is packaged as `attr`
    if repo_name.lower() in ("attrs",):
        candidates.insert(0, "attr")
    for candidate in candidates:
        for base in (clone_dir / "src" / candidate, clone_dir / candidate):
            if (base / "__init__.py").is_file():
                return candidate
    return None


def list_repo_top_level_symbols(clone_dir: Path, pkg_name: str) -> set[str]:
    """Return the set of top-level class/function names defined anywhere in
    the repo's Python package. Used by the symbol-collision guard so that
    the LLM's `task_module.py` doesn't reuse a name that would let an agent
    solve the task by re-exporting the repo's own implementation.

    Cheap: one AST walk per .py file under the package directory.
    Errors are swallowed — corrupt files are treated as contributing no names.
    """
    for base in (clone_dir / "src" / pkg_name, clone_dir / pkg_name):
        if base.is_dir():
            root = base
            break
    else:
        return set()
    names: set[str] = set()
    for py in root.rglob("*.py"):
        try:
            tree = ast.parse(py.read_text(encoding="utf-8", errors="replace"))
        except (SyntaxError, OSError):
            continue
        for node in tree.body:
            if isinstance(node, ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef):
                names.add(node.name)
    return names


# ---------------------------------------------------------------------------
# Seed sampling
# ---------------------------------------------------------------------------


@dataclass(slots=True, frozen=True)
class Seed:
    """One sampled snippet from the target repo."""

    relative_path: str  # POSIX-style, e.g. "src/foo/bar.py"
    start_line: int  # 1-indexed
    end_line: int  # 1-indexed, inclusive
    text: str  # the snippet itself (no line numbers)


def is_excluded(relative_path: str, exclude_globs: list[str]) -> bool:
    return any(fnmatch.fnmatch(relative_path, pat) for pat in exclude_globs)


def list_source_files(clone_dir: Path, *, file_glob: str, exclude_glob: list[str]) -> list[Path]:
    """Walk the repo tree matching `file_glob` minus `exclude_glob`."""
    out: list[Path] = []
    for p in clone_dir.glob(file_glob):
        if not p.is_file():
            continue
        rel = p.relative_to(clone_dir).as_posix()
        if is_excluded(rel, exclude_glob):
            continue
        out.append(p)
    return out


def sample_seed(
    files: list[Path],
    clone_dir: Path,
    *,
    rng: random.Random,
    min_loc: int,
    max_loc: int,
    max_attempts: int = 20,
) -> Seed | None:
    """Pick a random file, pick a random window of `[min_loc..max_loc]` lines.

    Skips files that are too short. Skips windows that are dominated by
    blank lines, imports, docstrings, or comments (those snippets give
    the LLM nothing to work with). Returns None after `max_attempts`.
    """
    if not files:
        return None
    for _ in range(max_attempts):
        f = rng.choice(files)
        try:
            text = f.read_text(encoding="utf-8", errors="replace")
        except OSError:
            continue
        lines = text.splitlines()
        if len(lines) < min_loc:
            continue
        window = rng.randint(min_loc, min(max_loc, len(lines)))
        start = rng.randint(0, max(0, len(lines) - window))
        end = start + window
        chunk_lines = lines[start:end]
        chunk = "\n".join(chunk_lines)
        if _looks_substantive(chunk_lines):
            return Seed(
                # POSIX on every OS: feeds the task ID, reference URL and metadata
                relative_path=f.relative_to(clone_dir).as_posix(),
                start_line=start + 1,
                end_line=end,
                text=chunk,
            )
    return None


_COMMENT_OR_IMPORT_RE = re.compile(r"^\s*(?:#|from\s|import\s)")


def _looks_substantive(chunk_lines: list[str]) -> bool:
    """Reject snippets that are 80%+ comments / imports / blanks."""
    if not chunk_lines:
        return False
    boring = 0
    for ln in chunk_lines:
        s = ln.strip()
        if not s or _COMMENT_OR_IMPORT_RE.match(s):
            boring += 1
    return (boring / len(chunk_lines)) < 0.8


# ---------------------------------------------------------------------------
# Decontamination — substring match against well-known eval benchmarks
# ---------------------------------------------------------------------------


# A minimal seed set. The real Magicoder corpus is huge (~10K+ substrings);
# we cover the most common contamination vectors. Extend per-need.
DEFAULT_BENCHMARK_PHRASES: tuple[str, ...] = (
    # HumanEval-style canonical phrasings (both definition and bare-name forms)
    "from typing import list",
    "def has_close_elements",
    "has_close_elements",
    "def separate_paren_groups",
    "separate_paren_groups",
    "def truncate_number",
    "truncate_number",
    # MBPP common phrasings
    "write a python function to",
    "write a function to find the",
    # APPS competitive phrasings
    "the first line of input contains an integer",
    "given a non-empty array of integers",
    # GSM8K (math word problems)
    "natalia sold clips to",
    "if a car travels",
    # DS-1000
    "import pandas as pd",
    "import numpy as np",
)


def has_benchmark_overlap(text: str, phrases: tuple[str, ...] = DEFAULT_BENCHMARK_PHRASES) -> bool:
    """True if any known benchmark phrase appears as a substring (case-insensitive)."""
    lower = text.lower()
    return any(p.lower() in lower for p in phrases)


# ---------------------------------------------------------------------------
# Prompting + parsing
# ---------------------------------------------------------------------------


PROMPT_SYSTEM = """You are a senior Python engineer designing a programming exercise that is genuinely anchored in a specific open-source library. You will be given a code snippet from the library `{pkg_name}` and asked to produce a task that requires the solver to USE `{pkg_name}`'s public API to solve it.

The goal is a task that CANNOT be solved without importing from `{pkg_name}` — a solver working in an isolated file without the library available would be stuck.

Produce three sections — exactly in this order, exactly with these section headers:

[Problem Description]
A clear problem statement that names `{pkg_name}` explicitly. Describe what to implement, what `{pkg_name}` primitive(s) to build on (subclass, extend, wrap, or compose), and the expected behavior. Include 1-2 short input/output examples. Under 200 words.

[Test]
A pytest test file. It MUST `from task_module import ...` (literal module name). Write 3-6 assertions covering normal cases AND edge cases (including at least one `pytest.raises` on an error condition). Use plain `def test_...(): assert ...` — no fixtures. The test may also import from `{pkg_name}` to construct inputs or verify behavior against the library's own types.

[Solution]
The Python source for `task_module.py`. It MUST contain at least one `from {pkg_name} import ...` (or `import {pkg_name}`) that is actually used by the code — subclass a `{pkg_name}` class, call a `{pkg_name}` function, wrap a `{pkg_name}` type, etc. Provide a complete, runnable Python file. Beyond `{pkg_name}` and the Python stdlib, do NOT import any other third-party libraries.

Do NOT name any top-level class or function the same as an existing `{pkg_name}` public symbol — the task-module symbol must be new (e.g. prefix or suffix it so a `grep` of the library source would not find it verbatim).

Output only those three sections in that order. No preamble, no closing notes."""


PROMPT_USER_TEMPLATE = """Target library: `{pkg_name}`.

Inspiration snippet (from `{path}`, lines {start}-{end}):

```python
{snippet}
```

Design a task that requires the solver to import and use `{pkg_name}`'s public API. The solution's `task_module.py` MUST contain a used `from {pkg_name} import ...` (or `import {pkg_name}`). Do not reuse any existing `{pkg_name}` symbol name for your task-module's top-level classes/functions."""


@dataclass(slots=True)
class ParsedTask:
    problem: str
    test_code: str
    solution_code: str


def parse_task_response(text: str) -> ParsedTask | None:
    """Extract the three sections from the LLM's response.

    Tolerant: section markers are matched case-insensitively. Returns
    None if any section is missing or empty.
    """
    problem = _extract_section(text, "Problem Description")
    test = _extract_section(text, "Test")
    solution = _extract_section(text, "Solution")
    if not (problem and test and solution):
        return None
    return ParsedTask(
        problem=problem.strip(),
        test_code=_strip_code_fence(test),
        solution_code=_strip_code_fence(solution),
    )


_SECTION_RE_CACHE: dict[str, re.Pattern[str]] = {}


def _section_re(name: str) -> re.Pattern[str]:
    if name not in _SECTION_RE_CACHE:
        # Match `[Section Name]` markers, with optional leading/trailing whitespace
        pattern = rf"(?im)^\s*\[\s*{re.escape(name)}\s*\]\s*$"
        _SECTION_RE_CACHE[name] = re.compile(pattern)
    return _SECTION_RE_CACHE[name]


def _extract_section(text: str, name: str) -> str:
    """Return the text between `[<name>]` and the next `[...]` marker (or EOF)."""
    pattern = _section_re(name)
    m = pattern.search(text)
    if not m:
        return ""
    start = m.end()
    # Find the next section marker after this one
    next_marker = re.search(r"(?im)^\s*\[\s*[A-Za-z][A-Za-z ]+\s*\]\s*$", text[start:])
    end = start + next_marker.start() if next_marker else len(text)
    return text[start:end].strip()


_CODE_FENCE_RE = re.compile(r"^```(?:python|py)?\s*\n(.*?)\n```\s*$", re.DOTALL)


def _strip_code_fence(text: str) -> str:
    """Strip a single surrounding ``` code fence if present."""
    text = text.strip()
    m = _CODE_FENCE_RE.match(text)
    if m:
        return m.group(1).strip()
    return text


# ---------------------------------------------------------------------------
# Test syntactic validation
# ---------------------------------------------------------------------------


def references_task_module(test_code: str) -> bool:
    """True iff the test code imports from `task_module` (our convention).

    Without this check, the LLM could write a self-sufficient test that
    passes whether or not we apply the oracle — making the task trivial.

    Named without a `test_` prefix so pytest doesn't try to collect this
    helper as a test function.
    """
    pattern = re.compile(
        r"^\s*(?:from\s+task_module\s+import|import\s+task_module)\b", re.MULTILINE
    )
    return bool(pattern.search(test_code))


# ---------------------------------------------------------------------------
# Quality gates — the four post-LLM checks
# ---------------------------------------------------------------------------


def check_repo_anchoring(solution_code: str, pkg_name: str) -> tuple[bool, str]:
    """The oracle `task_module.py` must import the target repo and USE it.

    Passes iff:
      1. AST parses.
      2. At least one `Import`/`ImportFrom` node names `pkg_name` (or a
         submodule `pkg_name.foo`).
      3. Any of the imported names appear in the file body (not just the
         import line). "Used" here is a coarse substring/name check on the
         rest of the source — cheap and catches the common failure mode of
         a bare `import X` that never references X.

    Returns (accepted, reason). Reason is empty on accept.
    """
    try:
        tree = ast.parse(solution_code)
    except SyntaxError as exc:
        return False, f"solution_syntax_error:{exc.msg}"
    imported: list[str] = []  # local names introduced by the imports
    has_repo_import = False
    import_lines: set[int] = set()
    for node in ast.walk(tree):
        if isinstance(node, ast.ImportFrom):
            if node.module and (node.module == pkg_name or node.module.startswith(f"{pkg_name}.")):
                has_repo_import = True
                import_lines.add(node.lineno)
                for alias in node.names:
                    imported.append(alias.asname or alias.name)
        elif isinstance(node, ast.Import):
            for alias in node.names:
                if alias.name == pkg_name or alias.name.startswith(f"{pkg_name}."):
                    has_repo_import = True
                    import_lines.add(node.lineno)
                    imported.append(alias.asname or alias.name.split(".", 1)[0])
    if not has_repo_import:
        return False, "no_repo_import"
    # Check "used" — any imported name appears outside its import line
    lines = solution_code.splitlines()
    body_text = "\n".join(ln for i, ln in enumerate(lines, 1) if i not in import_lines)
    for name in imported:
        # `*` from a star-import — impossible to verify usage; accept as used
        if name == "*":
            return True, ""
        if re.search(rf"\b{re.escape(name)}\b", body_text):
            return True, ""
    return False, "repo_import_unused"


def check_symbol_collision(solution_code: str, repo_symbols: set[str]) -> tuple[bool, str]:
    """Reject if any top-level class/function name in the oracle collides
    with a real symbol in the target repo — that lets an agent `grep`
    the on-disk source and re-export the real implementation to pass the
    binary test.
    """
    try:
        tree = ast.parse(solution_code)
    except SyntaxError:
        # already caught by anchoring check; don't double-report
        return True, ""
    for node in tree.body:
        if (
            isinstance(node, ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef)
            and node.name in repo_symbols
        ):
            return False, f"symbol_collides_with_repo:{node.name}"
    return True, ""


_ASSERT_TRIVIAL_RE = re.compile(
    r"^\s*assert\s+(True|1|\".+\"|'.+')\s*(?:,.*)?\s*$",
)


def check_test_strength(test_code: str, instruction: str) -> tuple[bool, str]:
    """Reject test files that are too weak to be worth grading.

    Rules:
      1. Parses cleanly.
      2. At least 3 top-level `test_*` `def`s OR one `test_*` def with
         ≥3 non-trivial `assert` statements. (Multiple tests preferred.)
      3. Total non-trivial `assert` statements across the file ≥ 3.
      4. If the instruction mentions an error condition (raise/error/
         invalid/must not/reject), the test file must contain at least
         one `pytest.raises(...)` block.
      5. No `assert True` / `assert 1` / `assert "literal"`.
    """
    try:
        tree = ast.parse(test_code)
    except SyntaxError as exc:
        return False, f"test_syntax_error:{exc.msg}"
    test_fns: list[ast.FunctionDef] = []
    for node in tree.body:
        if isinstance(node, ast.FunctionDef) and node.name.startswith("test_"):
            test_fns.append(node)
    if not test_fns:
        return False, "no_test_functions"

    total_asserts = 0
    trivial_asserts = 0
    for fn in test_fns:
        for sub in ast.walk(fn):
            if isinstance(sub, ast.Assert):
                total_asserts += 1
                # `assert True`, `assert False`, `assert <literal>`
                test = sub.test
                if isinstance(test, ast.Constant):
                    if test.value in (True, False) or isinstance(test.value, (int, str)):
                        trivial_asserts += 1
                # `assert x == x`
                elif (
                    isinstance(test, ast.Compare)
                    and isinstance(test.left, ast.Name)
                    and len(test.comparators) == 1
                    and isinstance(test.comparators[0], ast.Name)
                    and test.left.id == test.comparators[0].id
                ):
                    trivial_asserts += 1

    non_trivial = total_asserts - trivial_asserts
    if trivial_asserts > 0:
        return False, "trivial_assert_present"
    if non_trivial < 3:
        return False, "too_few_asserts"

    # Error-branch coverage
    err_re = re.compile(r"\b(?:raise|error|invalid|must not|reject|forbidden)\b", re.IGNORECASE)
    if (
        err_re.search(instruction)
        and "pytest.raises" not in test_code
        and "raises(" not in test_code
    ):
        return False, "missing_pytest_raises"

    return True, ""


def check_equivalence_test_strength(
    test_code: str, name: str, *, min_test_cases: int = 5
) -> tuple[bool, str]:
    """Reject weak equivalence-test files before sending them to the sandbox.

    Different shape than `check_test_strength`: for equivalence tests the
    LLM writes many `def test_*` bodies where each asserts
    `name(x) == reference_name(x)` on distinct inputs. Weakness modes we
    catch here (Stage-A / Stage-B in the sandbox catch the rest):

      1. Fewer than `min_test_cases` distinct `def test_*` functions.
      2. Any `def test_*` body that references only `reference_<name>` and
         never calls `<name>` (would pass while `<name>` is stubbed).
      3. `assert True` / `assert 1` / other trivial constant asserts.

    The Stage-A gate downstream catches the "test never actually exercises
    both names" case at the module level, so we don't reject candidates
    just because the equivalence assertion goes through intermediate
    variables (`a = name(x); b = ref(x); assert a == b` — very common
    LLM output pattern that a strict same-line gate would reject).

    Returns (accepted, reason). Reason is empty on accept.
    """
    try:
        tree = ast.parse(test_code)
    except SyntaxError as exc:
        return False, f"test_syntax_error:{exc.msg}"
    test_fns = [
        n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name.startswith("test_")
    ]
    if len(test_fns) < min_test_cases:
        return False, f"too_few_test_functions:{len(test_fns)}<{min_test_cases}"

    ref_name = f"reference_{name}"
    trivial_asserts = 0
    for fn in test_fns:
        body_calls_name = False
        body_calls_ref = False
        for sub in ast.walk(fn):
            if isinstance(sub, ast.Assert):
                test = sub.test
                if isinstance(test, ast.Constant) and (
                    test.value in (True, False) or isinstance(test.value, (int, str))
                ):
                    trivial_asserts += 1
            elif isinstance(sub, ast.Call) and isinstance(sub.func, ast.Name):
                if sub.func.id == name:
                    body_calls_name = True
                elif sub.func.id == ref_name:
                    body_calls_ref = True
        if not (body_calls_name and body_calls_ref):
            return False, f"test_fn_missing_both_names:{fn.name}"

    if trivial_asserts > 0:
        return False, "trivial_assert_present"
    return True, ""


def task_fingerprints(problem: str, solution_code: str = "") -> set[str]:
    """Return the set of dedup signals for a candidate task.

    Two independent signals — a match on EITHER counts as a duplicate:
      1. Problem-statement head (first 80 normalized chars) — catches
         reworded-but-same-task drift.
      2. Sorted top-level public symbol names in the oracle — catches the
         opposite failure mode where the LLM keeps the same class (e.g.
         `RangedFloatType`) but reframes the problem statement.

    Private/dunder names are ignored so that internal helper renames
    don't split an otherwise-duplicate task into two fingerprints.
    """
    fps: set[str] = set()
    norm = re.sub(r"\s+", " ", problem.strip().lower())
    fps.add("p:" + hashlib.sha256(norm[:80].encode("utf-8")).hexdigest()[:16])
    if solution_code:
        try:
            tree = ast.parse(solution_code)
        except SyntaxError:
            return fps
        symbols = sorted(
            n.name
            for n in tree.body
            if isinstance(n, ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef)
            and not n.name.startswith("_")
        )
        if symbols:
            fps.add("s:" + hashlib.sha256(",".join(symbols).encode("utf-8")).hexdigest()[:16])
    return fps


def task_fingerprint(problem: str, solution_code: str = "") -> str:
    """Legacy single-fingerprint (problem-only) — kept for compat.

    New callers should use `task_fingerprints` which returns a set of
    independent signals covering both problem-rewording and shared-class
    duplication modes.
    """
    norm = re.sub(r"\s+", " ", problem.strip().lower())
    return hashlib.sha256(norm[:80].encode("utf-8")).hexdigest()[:16]

pipelines/code_instruct.py

Source: src/repo2rlenv/pipelines/code_instruct.py · SHA-256 99100b230bb6a17b69c7543b06648bbc94fbdf60514745dfa574f9e42aefa5c1

Source hash covers the original file; trailing whitespace is omitted below.

Read pipelines/code_instruct.py
"""OSS-Instruct-style coding tasks, anchored to a target repo + verified by execution.

For each emitted task:

  1. Sample a seed snippet from the target repo (Python file, 30-200 LOC)
  2. Ask the LLM for [Problem Description], [Test], [Solution] in one call
  3. Verify in the bootstrap container:
     - With ONLY the test file in place: `pytest <test_file>` must FAIL
       (otherwise the test doesn't actually exercise the oracle — trivial)
     - With BOTH the test and oracle: `pytest <test_file>` must PASS
       (otherwise the LLM's oracle is wrong)
  4. Emit Harbor task whose gold patch adds `task_module.py` (the oracle)
     and `test_<task_id>.py` (the verifier) at the repo root

Different from Magicoder's OSS-Instruct:
  - Seeds come from one specific repo (verified-solvable in THAT env)
  - Each task has an executable pytest verifier (not just text)
  - The oracle has to actually pass the test in the repo's Docker env

----------------------------------------------------------------------------
Acknowledgment
----------------------------------------------------------------------------
Inspired by:

  Magicoder: Empowering Code Generation with OSS-Instruct
  (Wei et al., ICML '24, arXiv:2312.02120)
  https://github.com/ise-uiuc/magicoder        (MIT)

The seed-snippet → LLM-instruction recipe is adapted from their
`data_synthesis/` pipeline. Section parsing and decontamination
heuristics follow their patterns but are reimplemented against
the Python stdlib (see _oss_instruct.py).

Released under Apache-2.0 along with the rest of Repo2RLEnv.
----------------------------------------------------------------------------
"""

from __future__ import annotations

import hashlib
import logging
import random
import shutil
import tempfile
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from typing import ClassVar

from repo2rlenv.auth import resolve_repo_token
from repo2rlenv.bootstrap.runner import _shallow_clone_at_ref
from repo2rlenv.bootstrap.spec import BootstrapResult, LanguageHint
from repo2rlenv.emitter.harbor import HarborTask, write_harbor_task
from repo2rlenv.llm import complete
from repo2rlenv.pipelines._eval_script import (
    SUBMISSION_ARTIFACT,
    build_single_file_eval_script,
    run_python_tests,
    single_file_verifier_files,
    validate_single_file_mutants,
)
from repo2rlenv.pipelines._grading_time import GradingTime, fit_runs, measure
from repo2rlenv.pipelines._mutants import Mutants
from repo2rlenv.pipelines._oss_instruct import (
    PROMPT_SYSTEM,
    PROMPT_USER_TEMPLATE,
    ParsedTask,
    Seed,
    check_repo_anchoring,
    check_symbol_collision,
    check_test_strength,
    detect_repo_package,
    has_benchmark_overlap,
    list_repo_top_level_symbols,
    list_source_files,
    parse_task_response,
    references_task_module,
    sample_seed,
    task_fingerprints,
)
from repo2rlenv.pipelines.base import PipelineResult
from repo2rlenv.pipelines.pr_runtime import (
    MIN_HARBOR_VERSION,
    ensure_system_python,
    verifier_config,
)
from repo2rlenv.sources import blob_reference_url
from repo2rlenv.spec.input import GenerationInput, PipelineName
from repo2rlenv.spec.options import CodeInstructOptions

logger = logging.getLogger(__name__)


@dataclass(slots=True)
class _VerifyOutcome:
    accepted: bool = False
    reason: str = ""
    pre_log: str = ""
    post_log: str = ""
    # Test IDs the reference passed: the verifier requires exactly these.
    expected: list[str] = field(default_factory=list)
    timing: GradingTime | None = None
    mutants: Mutants | None = None


def new_file_hunk(content: str, path: str) -> str:
    """One `git apply`-compatible hunk that creates a NEW file at repo root.

    Standard `diff --git` + `new file mode` + index + `--- /dev/null` +
    `+++ b/<path>` headers, a single `@@ -0,0 +1,N @@` block, and `+`-prefixed
    body lines. Emits the `\\ No newline at end of file` marker when needed.
    """
    lines = content.splitlines()
    n = len(lines)
    header = (
        f"diff --git a/{path} b/{path}\n"
        f"new file mode 100644\n"
        f"index 0000000..0000001\n"
        f"--- /dev/null\n"
        f"+++ b/{path}\n"
        f"@@ -0,0 +1,{n} @@\n"
    )
    body = "".join(f"+{ln}\n" for ln in lines)
    if not content.endswith("\n"):
        body += "\\ No newline at end of file\n"
    return header + body


def make_solution_diff(*, task_module_code: str) -> str:
    """Gold patch: creates ONLY `task_module.py`.

    The grading test ships separately under `tests/` (Harbor mounts it at
    /tests for *every* agent) and is copied into /workspace by the verifier.
    Packing the test into the gold patch would land it via `solution/` only,
    which Harbor stages exclusively for the OracleAgent — so every other agent
    would run pytest against a missing file (exit 4 → reward 0). See issue #54.
    """
    return new_file_hunk(task_module_code, "task_module.py")


def build_code_instruct_dockerfile(bootstrap_image: str) -> str:
    """Per-task Dockerfile: FROM bootstrap + defensive git install. HEAD state.

    Unlike pr_runtime, code_instruct adds NEW files at
    test time (no patching needed at build time). The gold solution/patch.diff
    lands only `task_module.py`; the grading test ships under tests/ (mounted
    at /tests for every agent) and tests/test.sh copies it into /workspace
    before running pytest. See issue #54.
    """
    return (
        f"# Auto-generated by Repo2RLEnv code_instruct\n"
        f"FROM {bootstrap_image}\n"
        f"WORKDIR /workspace\n"
        f"RUN command -v git >/dev/null 2>&1 || \\\n"
        f"    (apt-get update && apt-get install -y --no-install-recommends git \\\n"
        f"     && rm -rf /var/lib/apt/lists/*) || \\\n"
        f"    apk add --no-cache git || true\n"
        f"RUN git config --global --add safe.directory /workspace\n" + ensure_system_python()
        # The separate verifier's grading steps run on the image's own python3.
    )


class CodeInstructPipeline:
    """Repo-anchored OSS-Instruct with executable verifiers."""

    name: ClassVar[PipelineName] = PipelineName.CODE_INSTRUCT
    requires_bootstrap: ClassVar[bool] = True
    experimental: ClassVar[bool] = True
    supported_languages: ClassVar[frozenset[LanguageHint] | None] = frozenset({LanguageHint.PYTHON})

    def __init__(
        self,
        input: GenerationInput,
        options: CodeInstructOptions,
        bootstrap: BootstrapResult | None = None,
    ):
        if bootstrap is None:
            raise RuntimeError(
                "code_instruct requires a BootstrapResult (set requires_bootstrap=True "
                "and let cmd_generate trigger it, or pass one explicitly)"
            )
        if input.llm is None:
            raise ValueError("code_instruct requires --llm (provider/model)")
        self.input = input
        self.options = options
        self.bootstrap = bootstrap
        self._progress_cb = None
        self._llm_cost_usd = 0.0

    def set_progress_callback(self, cb) -> None:
        self._progress_cb = cb

    def _emit_progress(self, name: str, outcome: str, reason: str = "") -> None:
        if self._progress_cb is not None:
            try:
                self._progress_cb(name=name, outcome=outcome, reason=reason)
            except Exception as exc:
                logger.debug("progress callback failed: %s", exc)

    # ----- run loop -----------------------------------------------------------

    def run(self, out_dir: Path) -> PipelineResult:
        out_dir.mkdir(parents=True, exist_ok=True)
        token = resolve_repo_token(self.input.repo, self.input.auth)
        if self.input.repo.access == "private" and not token:
            raise RuntimeError(
                "private repo specified but no GitHub token resolved. "
                "Run `gh auth login` or set GITHUB_TOKEN."
            )

        owner, name = self.input.repo.owner_name
        owner_name = f"{owner}/{name}"
        rng = random.Random(self.options.seed) if self.options.seed is not None else random.Random()

        skip_reasons: dict[str, int] = {}
        emitted = 0
        candidates_seen = 0
        sandbox = None

        with tempfile.TemporaryDirectory(prefix="r2e-code-instruct-") as tmp:
            clone_dir = Path(tmp) / "repo"
            try:
                _shallow_clone_at_ref(
                    self.input.repo.url, self.input.repo.ref, token, clone_dir, depth=1
                )
            except Exception as exc:
                raise RuntimeError(f"failed to clone {self.input.repo.url}: {exc}") from exc

            source_files = list_source_files(
                clone_dir,
                file_glob=self.options.file_glob,
                exclude_glob=self.options.exclude_glob,
            )
            logger.info("code_instruct: %d candidate source files", len(source_files))

            # Repo-anchoring context: which Python package should the LLM import,
            # and which top-level symbols already exist in it (collision guard).
            pkg_name = detect_repo_package(clone_dir, name)
            if pkg_name is None:
                logger.warning(
                    "code_instruct: could not detect Python package for %s — "
                    "repo-anchoring gate will be skipped",
                    owner_name,
                )
                repo_symbols: set[str] = set()
            else:
                logger.info("code_instruct: target package `%s`", pkg_name)
                repo_symbols = list_repo_top_level_symbols(clone_dir, pkg_name)
                logger.info(
                    "code_instruct: %d top-level symbols in `%s` (collision guard)",
                    len(repo_symbols),
                    pkg_name,
                )
            seen_fingerprints: set[str] = set()

            try:
                if not self.options.skip_validation:
                    sandbox = self._start_sandbox()

                while emitted < self.options.limit:
                    if candidates_seen >= self.options.limit * 5:
                        # Avoid spinning forever on a repo that resists synthesis
                        logger.info(
                            "code_instruct: candidate budget exhausted (seen=%d, emitted=%d)",
                            candidates_seen,
                            emitted,
                        )
                        break
                    candidates_seen += 1
                    seed = sample_seed(
                        source_files,
                        clone_dir,
                        rng=rng,
                        min_loc=self.options.seed_min_loc,
                        max_loc=self.options.seed_max_loc,
                    )
                    if seed is None:
                        skip_reasons["no_seed"] = skip_reasons.get("no_seed", 0) + 1
                        continue
                    label = f"{owner_name}:{seed.relative_path}#{seed.start_line}-{seed.end_line}"

                    # Retry the LLM call up to N times per seed. If any attempt
                    # produces a candidate that passes all gates, we advance.
                    parsed = None
                    last_skip_reason = ""
                    for attempt in range(max(1, self.options.max_attempts_per_seed)):
                        candidate = self._llm_synthesize(seed, pkg_name=pkg_name)
                        if candidate is None:
                            last_skip_reason = "llm_parse_failed"
                            continue
                        # Decontamination
                        if not self.options.skip_decontamination:
                            joined = candidate.problem + "\n" + candidate.solution_code
                            if has_benchmark_overlap(joined):
                                last_skip_reason = "benchmark_overlap"
                                continue
                        # Syntactic: test must reference task_module
                        if not references_task_module(candidate.test_code):
                            last_skip_reason = "test_does_not_use_task_module"
                            continue
                        # Repo-anchoring gate (skip if we couldn't detect the package)
                        if pkg_name is not None:
                            ok, reason = check_repo_anchoring(candidate.solution_code, pkg_name)
                            if not ok:
                                last_skip_reason = reason
                                continue
                            ok, reason = check_symbol_collision(
                                candidate.solution_code, repo_symbols
                            )
                            if not ok:
                                last_skip_reason = reason
                                continue
                        # Test-strength gate
                        ok, reason = check_test_strength(candidate.test_code, candidate.problem)
                        if not ok:
                            last_skip_reason = reason
                            continue
                        # Dedup against already-emitted tasks in this run.
                        # ANY overlap of fingerprints (problem-head OR
                        # symbol-set) counts as a duplicate.
                        fps = task_fingerprints(candidate.problem, candidate.solution_code)
                        if fps & seen_fingerprints:
                            last_skip_reason = "duplicate_task"
                            continue
                        # All gates passed
                        parsed = candidate
                        parsed_fps = fps
                        logger.debug("seed %s accepted on attempt %d", label, attempt + 1)
                        break

                    if parsed is None:
                        skip_reasons[last_skip_reason] = skip_reasons.get(last_skip_reason, 0) + 1
                        self._emit_progress(label, "skip", last_skip_reason)
                        continue

                    # Sandbox verification
                    test_filename = self._task_test_filename(seed, parsed)
                    expected: list[str] = []
                    timing = None
                    mutants = None
                    if not self.options.skip_validation:
                        outcome = self._verify_task(sandbox, parsed, test_filename=test_filename)
                        if not outcome.accepted:
                            skip_reasons[outcome.reason] = skip_reasons.get(outcome.reason, 0) + 1
                            self._emit_progress(label, "skip", outcome.reason)
                            continue
                        expected = outcome.expected
                        timing = outcome.timing
                        mutants = outcome.mutants

                    # Emit
                    task = self._build_task(
                        seed,
                        parsed,
                        test_filename=test_filename,
                        expected=expected,
                        timing=timing,
                        mutants=mutants,
                    )
                    write_harbor_task(task, out_dir)
                    seen_fingerprints.update(parsed_fps)
                    emitted += 1
                    logger.info("emitted task %s (seed=%s)", task.name, seed.relative_path)
                    self._emit_progress(task.name, "emit")
            finally:
                if sandbox is not None:
                    sandbox.cleanup()
                shutil.rmtree(clone_dir, ignore_errors=True)

        return PipelineResult(
            candidates=candidates_seen,
            emitted=emitted,
            skipped=sum(skip_reasons.values()),
            out_dir=out_dir,
            skip_reasons=skip_reasons,
        )

    # ----- LLM ---------------------------------------------------------------

    def _llm_synthesize(self, seed: Seed, *, pkg_name: str | None) -> ParsedTask | None:
        # If we couldn't detect the target package, we still fall back to a
        # library-agnostic prompt so single-file / plain-repo cases don't
        # bring the pipeline to a halt. The anchoring gate is skipped in
        # that path (see run()).
        effective_pkg = pkg_name or "the target library"
        system = PROMPT_SYSTEM.format(pkg_name=effective_pkg)
        user = PROMPT_USER_TEMPLATE.format(
            pkg_name=effective_pkg,
            path=seed.relative_path,
            start=seed.start_line,
            end=seed.end_line,
            snippet=seed.text,
        )
        try:
            resp = complete(
                self.input.llm,
                system=system,
                user=user,
                max_tokens=self.options.max_llm_tokens,
                temperature=self.options.llm_temperature,
            )
        except Exception as exc:
            logger.warning("code_instruct LLM call failed: %s", exc)
            return None
        self._llm_cost_usd += resp.cost_usd
        return parse_task_response(resp.content)

    # ----- sandbox -----------------------------------------------------------

    def _start_sandbox(self):
        from repo2rlenv.bootstrap.docker import DockerSandbox

        marker = Path(tempfile.mkdtemp(prefix="r2e-code-instruct-"))
        (marker / ".keep").write_text("")
        return DockerSandbox.start(
            base_image=self.bootstrap.image_tag,
            repo_dir=marker,
            platform=self.input.bootstrap.platform,
        )

    def _verify_task(self, sandbox, parsed: ParsedTask, *, test_filename: str) -> _VerifyOutcome:
        """Two-stage verification, run exactly the way the task is graded.

        Stage A: the test alone, no `task_module.py` → must NOT pass.
        Stage B: the test plus the oracle module → must pass (every test passed,
                 none skipped, pytest exit 0), the separate verifier's verdict.
        Both run through the grader launcher as the unprivileged user; the test
        IDs stage B passed become the task's expected list.
        """
        common = {
            "test_filename": test_filename,
            "timeout": self.options.validation_timeout_sec,
            "remove": ("task_module.py", "task_module.pyc"),
        }
        a = run_python_tests(sandbox, files={test_filename: parsed.test_code}, **common)
        if self.options.require_test_fails_without_oracle and a.passed:
            return _VerifyOutcome(
                accepted=False, reason="test_passes_without_oracle", pre_log=a.log
            )
        oracle = {"task_module.py": parsed.solution_code}
        b = run_python_tests(sandbox, files={**oracle, test_filename: parsed.test_code}, **common)
        if self.options.require_test_passes_with_oracle and not b.passed:
            return _VerifyOutcome(
                accepted=False,
                reason="oracle_does_not_satisfy_test",
                pre_log=a.log,
                post_log=b.log,
            )
        mutants = validate_single_file_mutants(
            sandbox,
            test_code=parsed.test_code,
            passing_files=oracle,
            reference=b,
            pre=a,
            seed=test_filename,
            **common,
        )
        timing = measure([run.sample for run in (a, b) if run.sample is not None])
        timing, checked = fit_runs(timing, mutants is not None)
        mutants = mutants if checked else None
        if timing is not None and timing.over_cap:
            return _VerifyOutcome(
                accepted=False, reason="verifier_timeout_over_cap", pre_log=a.log, post_log=b.log
            )
        return _VerifyOutcome(
            accepted=True,
            pre_log=a.log,
            post_log=b.log,
            expected=sorted(b.statuses),
            timing=timing,
            mutants=mutants,
        )

    # ----- task builder -------------------------------------------------------

    def _task_test_filename(self, seed: Seed, parsed: ParsedTask) -> str:
        """Content-derived filename — pytest discovers it by `test_*.py` glob."""
        h = hashlib.sha256()
        h.update(seed.relative_path.encode())
        h.update(b"\0")
        h.update(str(seed.start_line).encode())
        h.update(b"\0")
        h.update(parsed.problem.encode())
        return f"test_r2e_{h.hexdigest()[:10]}.py"

    def _build_task(
        self,
        seed: Seed,
        parsed: ParsedTask,
        *,
        test_filename: str,
        expected: list[str] | None = None,
        timing: GradingTime | None = None,
        mutants: Mutants | None = None,
    ) -> HarborTask:
        owner, name = self.input.repo.owner_name
        h = hashlib.sha256()
        h.update(seed.relative_path.encode())
        h.update(b"\0")
        h.update(str(seed.start_line).encode())
        h.update(b"\0")
        h.update(parsed.problem.encode())
        task_id = f"{owner}__{name}-cinst-{h.hexdigest()[:8]}"

        # Gold patch lands ONLY task_module.py. The grading test ships under
        # tests/ (mounted at /tests for every agent) so non-oracle agents can
        # run it too — see issue #54.
        gold_diff = make_solution_diff(task_module_code=parsed.solution_code)

        # The verifier copies the test out of /tests into /workspace, then runs
        # it specifically (NOT the bootstrap's recorded test_cmds — those are
        # for the original suite).
        eval_script = build_single_file_eval_script(
            test_filename,
            language=self.bootstrap.language.value,
            run_timeout=timing.run_timeout if timing is not None else None,
            mutants=mutants,
            copy_timeout=timing.copy_timeout if timing is not None else None,
        )
        image_ref = (
            self.bootstrap.image_digest
            if self.bootstrap.pushed_to_registry
            else self.bootstrap.image_tag
        )
        dockerfile = build_code_instruct_dockerfile(image_ref)

        reference = blob_reference_url(
            self.input.repo.source_kind,
            owner,
            name,
            self.input.repo.ref,
            seed.relative_path,
            seed.start_line,
            seed.end_line,
        )

        repo2env = {
            "pipeline": "code_instruct",
            "pipeline_version": "0.6.2",
            "repo": f"{owner}/{name}",
            "ref": self.input.repo.ref,
            # Omitted, not None, for a local checkout: TOML has no null and
            # tomli_w rejects it outright.
            **({"reference": reference} if reference is not None else {}),
            "source_access": self.input.repo.access,
            "built_at": datetime.now(UTC).isoformat(),
            "synthesis_llm": self.input.llm.qualified_name,
            "reward_kinds": ["test_execution"],
            "harbor_min_version": MIN_HARBOR_VERSION,
            **({"grading_time": timing.metadata()} if timing is not None else {}),
            "tamper_check": "mutants" if mutants is not None and mutants.ids else "unavailable",
            "code_instruct": {
                "seed_path": seed.relative_path,
                "seed_start_line": seed.start_line,
                "seed_end_line": seed.end_line,
                "test_filename": test_filename,
                "bootstrap_image": self.bootstrap.image_digest,
                "llm_cost_usd": round(self._llm_cost_usd, 6),
            },
        }

        # Append the filename contract to the agent-visible instruction.
        # The LLM's problem statement never mentions `task_module.py` — models
        # write the correct logic to naturally-named files (ranged_float.py,
        # fetcher.py, etc.) and pytest collection fails with
        # `ModuleNotFoundError: No module named 'task_module'`. Empirically
        # this was ~all of the 40% non-solve rate on iter1.
        agent_instruction = (
            parsed.problem
            + "\n\n---\n"
            + "**Delivery contract**: write your implementation to "
            + "`/workspace/task_module.py`. Do not modify any existing files "
            + "in the repository. The grading test imports directly from "
            + "`task_module` (i.e. `from task_module import ...`), so the "
            + "file MUST be at that exact path and MUST expose the symbols "
            + "the problem statement names."
        )
        return HarborTask(
            name=task_id,
            org=self.input.output.org,
            description=parsed.problem.split("\n", 1)[0][:120],
            instruction=agent_instruction,
            oracle_diff=gold_diff,
            repo2env=repo2env,
            difficulty="medium",
            category="feature",
            keywords=[name, "code_instruct"],
            environment_dockerfile=dockerfile,
            test_script=eval_script,
            verifier=verifier_config(timing),
            artifacts=SUBMISSION_ARTIFACT,
            aux_files=single_file_verifier_files(
                test_filename, parsed.test_code, expected or [], mutants=mutants
            ),
        )

pipelines/equivalence_tests.py

Source: src/repo2rlenv/pipelines/equivalence_tests.py · SHA-256 722beabe08489d4c566508f34c02241b77ab7d926057131148b08820d82b2e8e

Source hash covers the original file; trailing whitespace is omitted below.

Read pipelines/equivalence_tests.py
"""R2E-style function-level equivalence-test synthesis.

For each module-level function in the target repo:

  1. Filter via AST (LOC range, has args + return, no obvious side effects)
  2. One LLM call asks for a pytest test that imports both `name` and
     `reference_name` from `task_module` and asserts equality across
     ≥5 inputs
  3. Verify two-stage in the bootstrap container:
       - Stage A: `name` stubbed (raise NotImplementedError), `reference_name`
                  is the original → test must FAIL
       - Stage B: `name = reference_name = original` → test must PASS
  4. Emit Harbor task whose gold patch adds `task_module.py` (with both
     `name` and `reference_name` set to the original implementation) plus
     a `test_r2e_<hash>.py` test file at the repo root.

Different from `code_instruct`:
  - The "problem" is grounded in a real function we extracted, not invented
  - The LLM only writes the test; we already have the ground truth
  - Yield scales with the number of qualifying functions in the repo

----------------------------------------------------------------------------
Acknowledgment
----------------------------------------------------------------------------
Inspired by:

  R2E: Turning any Github Repository into a Programming Agent Environment
  (Jain et al., ICML '24)
  https://github.com/r2e-project/r2e        (MIT)

The reference-oracle test pattern (`reference_<name>` as frozen oracle,
test compares both implementations) and the function-extractor filter
set are adapted from R2E's `repo_builder/fut_extractor/` + `generators/
testgen/prompt.py`. No code is copied; the implementation is original.

Released under Apache-2.0 along with the rest of Repo2RLEnv.
----------------------------------------------------------------------------
"""

from __future__ import annotations

import base64
import hashlib
import logging
import random
import re
import shutil
import tempfile
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from typing import ClassVar

from repo2rlenv.auth import resolve_repo_token
from repo2rlenv.bootstrap.runner import _shallow_clone_at_ref
from repo2rlenv.bootstrap.spec import BootstrapResult, LanguageHint
from repo2rlenv.emitter.harbor import HarborTask, write_harbor_task
from repo2rlenv.llm import complete
from repo2rlenv.pipelines._eval_script import (
    SUBMISSION_ARTIFACT,
    build_single_file_eval_script,
    is_module_importable,
    make_unified_diff,
    record_reference_calls,
    rename_function_ast,
    run_python_tests,
    signature_only_source,
    single_file_verifier_files,
    strip_annotations,
    validate_single_file_mutants,
)
from repo2rlenv.pipelines._function_extractor import FunctionCandidate, walk_repo
from repo2rlenv.pipelines._grading_time import GradingTime, fit_runs, measure
from repo2rlenv.pipelines._mutants import Mutants
from repo2rlenv.pipelines._oss_instruct import check_equivalence_test_strength
from repo2rlenv.pipelines.base import PipelineResult
from repo2rlenv.pipelines.pr_runtime import (
    MIN_HARBOR_VERSION,
    ensure_system_python,
    verifier_config,
)
from repo2rlenv.sources import blob_reference_url
from repo2rlenv.spec.input import GenerationInput, PipelineName
from repo2rlenv.spec.options import EquivalenceTestsOptions

logger = logging.getLogger(__name__)


PROMPT_SYSTEM = """You are a senior Python engineer writing differential equivalence tests.

You will be shown one function from an open-source library. Your job: write a single pytest test file that imports BOTH `<name>` and `reference_<name>` from the module `task_module`, and asserts they produce identical outputs across a set of inputs.

The reference implementation IS the ground truth. Do not try to write inputs that "trip up" the reference — pick inputs the reference clearly handles cleanly. The purpose of the test is to detect when a candidate diverges from the reference, not to exercise edge cases the reference itself doesn't handle.

STRICT REQUIREMENTS:
- Output ONE section labelled `[Test]` and nothing else (no preamble, no closing notes).
- Use plain `def test_*(): assert ...` style — NO unittest.TestCase, NO fixtures, NO mocks.
- The test MUST import both names from `task_module`: `from task_module import {name}, reference_{name}`.
- Write between 5 and 10 distinct `def test_*` functions, each with ONE assertion of the form:

      def test_name_case_N():
          expected = reference_{name}(<input>)
          actual = {name}(<input>)
          assert actual == expected

  Using this exact pattern is important — it means Stage-B (reference vs reference) is guaranteed to pass, and Stage-A (candidate stub raising vs reference) fails cleanly.
- Prefer inputs that produce clear, definite outputs. AVOID inputs where the reference would raise an exception; avoid inputs that require an ambient context (a Click context, a Flask request, filesystem state).
- Use literal Python values that can be constructed without third-party libraries. If the function takes complex types, build them in the test using only stdlib.
- DO NOT call any function other than `{name}` and `reference_{name}` (and Python builtins / stdlib).
- DO NOT redefine `{name}` or `reference_{name}` in the test.
- If the function's behavior depends on randomness, use `random.seed(0)` before each call.
"""


PROMPT_USER_TEMPLATE = """Reference function (from `{path}`, lines {start}-{end}):

```python
{source}
```

Signature args: {arg_names}.

Write the equivalence test now."""


@dataclass(slots=True)
class _VerifyOutcome:
    accepted: bool = False
    reason: str = ""
    stub_log: str = ""
    oracle_log: str = ""
    # Test IDs the reference passed: the verifier requires exactly these.
    expected: list[str] = field(default_factory=list)
    timing: GradingTime | None = None
    # The test as graded: the original's recorded results baked in.
    graded_test: str = ""
    mutants: Mutants | None = None


@dataclass(slots=True)
class _ParsedTest:
    code: str  # the test file body


def _extract_test_section(text: str) -> _ParsedTest | None:
    """Extract `[Test]` section content from an LLM response. Returns None if missing."""
    m = re.search(r"(?im)^\s*\[\s*test\s*\]\s*$", text)
    if not m:
        return None
    body = text[m.end() :]
    # Stop at next `[Something Else]` section if present
    nxt = re.search(r"(?im)^\s*\[\s*[a-zA-Z][a-zA-Z ]+\s*\]\s*$", body)
    if nxt:
        body = body[: nxt.start()]
    # Strip a surrounding code fence
    fence = re.match(r"^\s*```(?:python|py)?\s*\n(.*?)\n```\s*$", body.strip(), re.DOTALL)
    if fence:
        body = fence.group(1)
    body = body.strip()
    if not body:
        return None
    return _ParsedTest(code=body)


_IMPORT_PATTERN = re.compile(
    r"^\s*(?:from\s+task_module\s+import|import\s+task_module)\b",
    re.MULTILINE,
)


def uses_both_names(test_code: str, name: str) -> bool:
    """True iff the test imports from task_module AND references both names.

    Defense against the LLM writing a trivial test (e.g., only uses
    `reference_<name>` and never calls `<name>` — which would pass even
    when `<name>` is stubbed).
    """
    if not _IMPORT_PATTERN.search(test_code):
        return False
    # Both names must appear as bare identifiers somewhere in the test
    name_used = re.search(rf"\b{re.escape(name)}\b", test_code) is not None
    ref_used = re.search(rf"\breference_{re.escape(name)}\b", test_code) is not None
    return name_used and ref_used


def _stub_module(candidate: FunctionCandidate) -> str:
    """Build `task_module.py` with `<name>` STUBBED + `reference_<name>` original.

    This is the STARTING state every agent sees: it's baked into the image
    (see `build_equivalence_dockerfile`) so `reference_<name>` is present for
    the agent to be equivalent to, and the agent's job is to fill in `<name>`.
    Also used in Stage A of verification (confirms the test actually exercises
    `<name>` — else it would pass while `<name>` raises NotImplementedError).

    Annotations on the extracted function are stripped so the module imports
    cleanly even when the original signature referenced repo-internal types
    (e.g. `def foo(x: Argument) -> FC` → `def foo(x)`). See
    `strip_annotations` in `_eval_script.py`.
    """
    ref_source = _rename_function_source(
        candidate.source, candidate.name, f"reference_{candidate.name}"
    )
    ref_source = strip_annotations(ref_source)
    args = ", ".join(candidate.arg_names) if candidate.arg_names else "*args, **kwargs"
    stub = (
        f"def {candidate.name}({args}):\n"
        f'    raise NotImplementedError("implement {candidate.name}")\n'
    )
    return ref_source + "\n\n" + stub


def build_equivalence_dockerfile(bootstrap_image: str, stub_module: str) -> str:
    """Per-task Dockerfile: FROM bootstrap + bake the stub `task_module.py`.

    Every agent starts from the stub (`reference_<name>` + a `<name>` that
    raises NotImplementedError), so the reference oracle the test compares
    against is present for non-oracle agents too — see issue #54. The gold
    patch is a stub→oracle modify-diff that fills in `<name>`.
    """
    encoded = base64.b64encode(stub_module.encode("utf-8")).decode("ascii")
    return (
        f"# Auto-generated by Repo2RLEnv equivalence_tests\n"
        f"FROM {bootstrap_image}\n"
        f"WORKDIR /workspace\n"
        f"RUN command -v git >/dev/null 2>&1 || \\\n"
        f"    (apt-get update && apt-get install -y --no-install-recommends git \\\n"
        f"     && rm -rf /var/lib/apt/lists/*) || \\\n"
        f"    apk add --no-cache git || true\n"
        f"RUN git config --global --add safe.directory /workspace\n"
        f"RUN echo {encoded} | base64 -d > /workspace/task_module.py\n" + ensure_system_python()
        # The separate verifier's grading steps run on the image's own python3.
    )


def _oracle_module(candidate: FunctionCandidate) -> str:
    """Build `task_module.py` with both `<name>` AND `reference_<name>` set to the original.

    Used in Stage B of verification AND as the gold-patch payload: the
    agent's job is to make `<name>` equivalent to `reference_<name>`;
    the gold patch achieves that by giving them the same implementation.

    Annotations are stripped for the same reason as `_stub_module`.
    """
    ref_source = _rename_function_source(
        candidate.source, candidate.name, f"reference_{candidate.name}"
    )
    ref_source = strip_annotations(ref_source)
    own_source = strip_annotations(candidate.source)
    return ref_source + "\n\n" + own_source + "\n"


# At generation the test runs against the original implementation, which records
# what every `reference_<name>` call returned or raised, keyed by the test that
# made it and its position in that test (`PYTEST_CURRENT_TEST`; the test code
# fixes the order, and argument reprs such as an iterator's carry addresses).
# The graded test answers those calls from the recording, so no
# reference code exists at grading: `reference_<name>` in task_module.py is
# only there for the agent to read, and the submission can't redefine it
# (`reference_f = f`) or plant a module in its place.
REFERENCE_MODULE = "r2e_reference.py"
RECORD_FILE = "/workspace/.r2e-reference-calls.json"


def reference_module(candidate: FunctionCandidate) -> str:
    """The module holding `reference_<name>` for the recording run, annotations stripped."""
    source = _rename_function_source(
        candidate.source, candidate.name, f"reference_{candidate.name}"
    )
    return strip_annotations(source) + "\n"


def recording_test_code(test_code: str, name: str) -> str:
    """The test with `reference_<name>` wrapped to record each call (generation only)."""
    return (
        test_code.rstrip("\n")
        + f"""


# Recording run (generation only): each reference call and its result.
import json as _r2e_json  # noqa: E402
import os as _r2e_os  # noqa: E402
import sys as _r2e_sys  # noqa: E402
from r2e_reference import reference_{name} as _r2e_original  # noqa: E402
import task_module as _r2e_task_module  # noqa: E402

_R2E_CALLS = []
_R2E_SEEN = {{}}


def _r2e_key():
    test = _r2e_os.environ.get("PYTEST_CURRENT_TEST", "").rsplit(" (", 1)[0]
    _R2E_SEEN[test] = _R2E_SEEN.get(test, 0) + 1
    return f"{{test}}#{{_R2E_SEEN[test] - 1}}"


def reference_{name}(*args, **kwargs):
    if _r2e_sys._getframe(1).f_globals is not globals():
        return _r2e_original(*args, **kwargs)  # not the test's own call
    key = _r2e_key()
    try:
        value = _r2e_original(*args, **kwargs)
    except Exception as exc:
        _R2E_CALLS.append([key, "raise", type(exc).__name__, repr(str(exc))])
        _r2e_save()
        raise
    _R2E_CALLS.append([key, "return", repr(value)])
    _r2e_save()
    return value


def _r2e_save():
    with open({RECORD_FILE!r}, "w", encoding="utf-8") as handle:
        _r2e_json.dump(_R2E_CALLS, handle)


_r2e_task_module.reference_{name} = reference_{name}
"""
    )


def recorded_calls(runs: list[list]) -> dict[str, list[str]] | None:
    """{call key: ["return", repr] | ["raise", exception name, repr(message)]}, or
    None when the recording can't be replayed exactly.

    Every run (each under a different hash seed) must record the same calls with
    the same results, each result must be a literal that `ast.literal_eval`
    reads back to the same text, and a raised exception must be a builtin one.
    """
    import ast
    import builtins

    calls: dict[str, list[str]] = {}
    for run in runs:
        for entry in run:
            if not (isinstance(entry, list) and len(entry) in (3, 4)):
                return None
            if not all(isinstance(part, str) for part in entry):
                return None
            key, kind, *payload = entry
            if kind == "return":
                try:
                    if repr(ast.literal_eval(payload[0])) != payload[0]:
                        return None
                except (ValueError, SyntaxError, TypeError, MemoryError, RecursionError):
                    return None
            elif kind == "raise" and len(payload) == 2:
                error = getattr(builtins, payload[0], None)
                if not (isinstance(error, type) and issubclass(error, Exception)):
                    return None
            else:
                return None
            if calls.setdefault(key, [kind, *payload]) != [kind, *payload]:
                return None  # same arguments, different result: not deterministic
    if len(runs) > 1 and any(run != runs[0] for run in runs[1:]):
        return None
    return calls


def graded_test_code(test_code: str, name: str, calls: dict[str, list[str]]) -> str:
    """The test as graded: `reference_<name>` answers from the recorded calls.

    Appended after the test's own imports, so module-level lookups at test time
    get it, and so does `task_module.reference_<name>`. A call the recording
    doesn't have (by test and position) fails the test.
    """
    return (
        test_code.rstrip("\n")
        + f"""


# Graded against the original implementation's recorded results, not code the
# submission could change.
import ast as _r2e_ast  # noqa: E402
import builtins as _r2e_builtins  # noqa: E402
import os as _r2e_os  # noqa: E402
import sys as _r2e_sys  # noqa: E402
import task_module as _r2e_task_module  # noqa: E402

_R2E_CALLS = {calls!r}
_R2E_SEEN = {{}}
_r2e_submitted = getattr(_r2e_task_module, "reference_{name}", None)


def reference_{name}(*args, **kwargs):
    if _r2e_sys._getframe(1).f_globals is not globals() and _r2e_submitted is not None:
        # The submission's own call (it may build on the visible reference):
        # whatever it defined answers it. Only the test's calls are replayed.
        return _r2e_submitted(*args, **kwargs)
    test = _r2e_os.environ.get("PYTEST_CURRENT_TEST", "").rsplit(" (", 1)[0]
    _R2E_SEEN[test] = _R2E_SEEN.get(test, 0) + 1
    recorded = _R2E_CALLS.get(f"{{test}}#{{_R2E_SEEN[test] - 1}}")
    if recorded is None:
        raise AssertionError("reference_{name} was not recorded for this call")
    if recorded[0] == "raise":
        raise getattr(_r2e_builtins, recorded[1])(_r2e_ast.literal_eval(recorded[2]))
    return _r2e_ast.literal_eval(recorded[1])


_r2e_task_module.reference_{name} = reference_{name}
"""
    )


def _rename_function_source(source: str, old_name: str, new_name: str) -> str:
    """Rename `def OLD(...)` → `def NEW(...)` in the source text — recursion-safe.

    v0.7 used a regex on the `def` line only, so recursive functions still
    called themselves by the old name inside the body → `reference_<name>`
    and `<name>` executed the same code and Stage B silently passed on
    bogus tasks. v0.8.7 uses `rename_function_ast` from `_eval_script.py`,
    which walks the AST and rewrites `Call(func=Name(id=old))` nodes and
    bare `Name` loads too. Falls back to the regex behaviour if AST
    parsing fails (source with tabs/mixed indent that ast rejects).
    """
    renamed = rename_function_ast(source, old_name, new_name)
    if renamed != source:
        return renamed
    # AST parse failed OR the name wasn't found — fall through to the regex
    pattern = re.compile(rf"^(\s*)(async\s+def|def)\s+{re.escape(old_name)}\b", re.MULTILINE)
    return pattern.sub(rf"\1\2 {new_name}", source, count=1)


class EquivalenceTestsPipeline:
    """R2E-style function-level equivalence-test synthesis."""

    name: ClassVar[PipelineName] = PipelineName.EQUIVALENCE_TESTS
    requires_bootstrap: ClassVar[bool] = True
    experimental: ClassVar[bool] = True
    supported_languages: ClassVar[frozenset[LanguageHint] | None] = frozenset({LanguageHint.PYTHON})

    def __init__(
        self,
        input: GenerationInput,
        options: EquivalenceTestsOptions,
        bootstrap: BootstrapResult | None = None,
    ):
        if bootstrap is None:
            raise RuntimeError(
                "equivalence_tests requires a BootstrapResult (set requires_bootstrap=True "
                "and let cmd_generate trigger it, or pass one explicitly)"
            )
        if input.llm is None:
            raise ValueError("equivalence_tests requires --llm (provider/model)")
        self.input = input
        self.options = options
        self.bootstrap = bootstrap
        self._progress_cb = None
        self._llm_cost_usd = 0.0

    def set_progress_callback(self, cb) -> None:
        self._progress_cb = cb

    def _emit_progress(self, name: str, outcome: str, reason: str = "") -> None:
        if self._progress_cb is not None:
            try:
                self._progress_cb(name=name, outcome=outcome, reason=reason)
            except Exception as exc:
                logger.debug("progress callback failed: %s", exc)

    # ----- run loop -----------------------------------------------------------

    def run(self, out_dir: Path) -> PipelineResult:
        out_dir.mkdir(parents=True, exist_ok=True)
        token = resolve_repo_token(self.input.repo, self.input.auth)
        if self.input.repo.access == "private" and not token:
            raise RuntimeError(
                "private repo specified but no GitHub token resolved. "
                "Run `gh auth login` or set GITHUB_TOKEN."
            )

        owner, name = self.input.repo.owner_name
        owner_name = f"{owner}/{name}"
        rng = random.Random(self.options.seed) if self.options.seed is not None else random.Random()

        skip_reasons: dict[str, int] = {}
        emitted = 0
        candidates_seen = 0
        sandbox = None

        with tempfile.TemporaryDirectory(prefix="r2e-equiv-tests-") as tmp:
            clone_dir = Path(tmp) / "repo"
            try:
                _shallow_clone_at_ref(
                    self.input.repo.url, self.input.repo.ref, token, clone_dir, depth=1
                )
            except Exception as exc:
                raise RuntimeError(f"failed to clone {self.input.repo.url}: {exc}") from exc

            candidates = list(
                walk_repo(
                    clone_dir,
                    file_glob=self.options.file_glob,
                    exclude_glob=self.options.exclude_glob,
                    min_loc=self.options.min_loc,
                    max_loc=self.options.max_loc,
                )
            )
            logger.info("equivalence_tests: %d candidate functions", len(candidates))
            rng.shuffle(candidates)
            seen_fingerprints: set[str] = set()

            try:
                if not self.options.skip_validation:
                    sandbox = self._start_sandbox()

                for cand in candidates:
                    if emitted >= self.options.limit:
                        break
                    candidates_seen += 1
                    label = f"{owner_name}:{cand.relative_path}::{cand.name}"

                    # Retry the LLM synth + gates + Stage-A/B verify up to N
                    # times per candidate, feeding back the failure signal on
                    # each retry. Was documented in options but never wired
                    # pre-v0.8.7 — the dominant baseline skip reason was
                    # `oracle_does_not_satisfy_test` (Stage-B fail on a
                    # first-draft LLM test), so verify HAS to be inside the
                    # loop, not outside.
                    parsed = None
                    parsed_fp: str | None = None
                    outcome: _VerifyOutcome | None = None
                    expected: list[str] = []
                    timing: GradingTime | None = None
                    graded_test = ""
                    mutants: Mutants | None = None
                    last_skip_reason = ""
                    feedback: str | None = None
                    for attempt in range(max(1, self.options.max_attempts_per_function)):
                        candidate_test = self._llm_generate_test(cand, feedback=feedback)
                        if candidate_test is None:
                            last_skip_reason = "llm_parse_failed"
                            feedback = None
                            continue
                        # Syntactic: both names referenced
                        if not uses_both_names(candidate_test.code, cand.name):
                            last_skip_reason = "test_missing_both_names"
                            feedback = (
                                "The previous attempt did not import both "
                                f"`{cand.name}` and `reference_{cand.name}` "
                                "from `task_module`, or did not reference both "
                                "identifiers in the test body. Both are required."
                            )
                            continue
                        ok, reason = check_equivalence_test_strength(
                            candidate_test.code, cand.name, min_test_cases=5
                        )
                        if not ok:
                            last_skip_reason = reason
                            feedback = (
                                f"The previous attempt failed the test-strength "
                                f"gate with reason `{reason}`. Ensure ≥5 distinct "
                                f"`def test_*` functions, each asserting "
                                f"`{cand.name}(...) == reference_{cand.name}(...)` "
                                f"on a genuinely different input. No `assert True`."
                            )
                            continue
                        fp = _equivalence_fingerprint(cand.name, candidate_test.code)
                        if fp in seen_fingerprints:
                            last_skip_reason = "duplicate_task"
                            feedback = (
                                "This exact test suite was already emitted for "
                                "another candidate. Pick a different set of inputs."
                            )
                            continue
                        test_filename = self._task_test_filename(cand, candidate_test)
                        if self.options.skip_validation:
                            parsed = candidate_test
                            parsed_fp = fp
                            break
                        # Stage-A / Stage-B verification against the sandbox.
                        outcome = self._verify_task(
                            sandbox=sandbox,
                            cand=cand,
                            test_code=candidate_test.code,
                            test_filename=test_filename,
                        )
                        if outcome.accepted:
                            parsed = candidate_test
                            parsed_fp = fp
                            expected = outcome.expected
                            timing = outcome.timing
                            graded_test = outcome.graded_test
                            mutants = outcome.mutants
                            logger.debug(
                                "candidate %s accepted on attempt %d",
                                label,
                                attempt + 1,
                            )
                            break
                        # Give the LLM enough of the log to see WHY it failed.
                        # Truncated so the retry prompt stays cheap.
                        log_hint = outcome.oracle_log or outcome.stub_log
                        if log_hint:
                            log_hint = log_hint[-1200:]
                        feedback = (
                            f"The previous attempt's test was rejected at "
                            f"`{outcome.reason}`. Failure log tail:\n\n"
                            f"```\n{log_hint or '(no log captured)'}\n```\n\n"
                            f"Pick simpler inputs that the reference actually "
                            f"handles (avoid inputs that depend on ambient click "
                            f"context, mutable global state, or randomness). "
                            f"If the function raises for some inputs, that's OK — "
                            f"assert `reference_{cand.name}(x) == {cand.name}(x)` "
                            f"is what we need, so use inputs where both sides "
                            f"return the same value or both raise the same "
                            f"exception."
                        )
                        last_skip_reason = outcome.reason

                    if parsed is None:
                        skip_reasons[last_skip_reason] = skip_reasons.get(last_skip_reason, 0) + 1
                        # Dump the last-attempt artifacts to a debug dir so we
                        # can inspect why Stage-B keeps failing without running
                        # the whole pipeline again. Cheap; disk-only.
                        try:
                            debug_dir = out_dir / ".debug_skips" / cand.name
                            debug_dir.mkdir(parents=True, exist_ok=True)
                            if candidate_test is not None:
                                (debug_dir / "last_test.py").write_text(candidate_test.code)
                            if outcome is not None:
                                (debug_dir / "stub_log.txt").write_text(outcome.stub_log or "")
                                (debug_dir / "oracle_log.txt").write_text(outcome.oracle_log or "")
                        except Exception:
                            pass
                        logger.info(
                            "skipped %s after %d attempts (reason=%s)",
                            label,
                            self.options.max_attempts_per_function,
                            last_skip_reason,
                        )
                        self._emit_progress(label, "skip", last_skip_reason)
                        continue

                    test_filename = self._task_test_filename(cand, parsed)
                    task = self._build_task(
                        cand,
                        parsed.code,
                        test_filename=test_filename,
                        expected=expected,
                        timing=timing,
                        graded_test=graded_test,
                        mutants=mutants,
                    )
                    write_harbor_task(task, out_dir)
                    if parsed_fp is not None:
                        seen_fingerprints.add(parsed_fp)
                    emitted += 1
                    logger.info(
                        "emitted task %s (function=%s, loc=%d)",
                        task.name,
                        cand.name,
                        cand.body_loc,
                    )
                    self._emit_progress(task.name, "emit")
            finally:
                if sandbox is not None:
                    sandbox.cleanup()
                shutil.rmtree(clone_dir, ignore_errors=True)

        return PipelineResult(
            candidates=candidates_seen,
            emitted=emitted,
            skipped=sum(skip_reasons.values()),
            out_dir=out_dir,
            skip_reasons=skip_reasons,
        )

    # ----- LLM ---------------------------------------------------------------

    def _llm_generate_test(
        self, cand: FunctionCandidate, *, feedback: str | None = None
    ) -> _ParsedTest | None:
        user = PROMPT_USER_TEMPLATE.format(
            path=cand.relative_path,
            start=cand.lineno,
            end=cand.end_lineno,
            source=cand.source,
            arg_names=", ".join(cand.arg_names),
        )
        if feedback:
            user = (
                user
                + "\n\n"
                + "**Retry — this candidate failed the previous attempt. "
                + f"Adjust accordingly.**\n\n{feedback}"
            )
        try:
            resp = complete(
                self.input.llm,
                system=PROMPT_SYSTEM.format(name=cand.name),
                user=user,
                max_tokens=self.options.max_llm_tokens,
                temperature=self.options.llm_temperature,
            )
        except Exception as exc:
            logger.warning("equivalence_tests LLM call failed: %s", exc)
            return None
        self._llm_cost_usd += resp.cost_usd
        return _extract_test_section(resp.content)

    # ----- sandbox -----------------------------------------------------------

    def _start_sandbox(self):
        from repo2rlenv.bootstrap.docker import DockerSandbox

        marker = Path(tempfile.mkdtemp(prefix="r2e-equiv-tests-"))
        (marker / ".keep").write_text("")
        return DockerSandbox.start(
            base_image=self.bootstrap.image_tag,
            repo_dir=marker,
            platform=self.input.bootstrap.platform,
        )

    def _verify_task(
        self,
        *,
        sandbox,
        cand: FunctionCandidate,
        test_code: str,
        test_filename: str,
    ) -> _VerifyOutcome:
        """Two-stage verification.

        Stage A: stub `<name>`, keep `reference_<name>` correct → test must FAIL.
        Stage B: both `<name>` and `reference_<name>` are the original → test
                 must PASS.

        If either invariant breaks, the task is skipped.
        """
        stub_module = _stub_module(cand)
        oracle_module = _oracle_module(cand)

        # Pre-flight: the stub module must actually be importable. Post-
        # annotation-strip it usually is, but if the body still references
        # a repo-internal Name we haven't allowlisted, catch it here rather
        # than burning a full sandbox exec.
        if not is_module_importable(stub_module):
            return _VerifyOutcome(
                accepted=False,
                reason="stub_module_not_importable",
            )
        if not is_module_importable(oracle_module):
            return _VerifyOutcome(
                accepted=False,
                reason="oracle_module_not_importable",
            )

        # Record what the original implementation returns for every call the test
        # makes, twice under different hash seeds; the graded test replays it.
        runs = []
        for seed in (1, 2):
            run = record_reference_calls(
                sandbox,
                files={
                    "task_module.py": oracle_module,
                    test_filename: recording_test_code(test_code, cand.name),
                    REFERENCE_MODULE: reference_module(cand),
                },
                test_filename=test_filename,
                record_file=RECORD_FILE,
                hash_seed=seed,
                timeout=self.options.validation_timeout_sec,
            )
            if run is None:
                return _VerifyOutcome(accepted=False, reason="reference_not_recordable")
            runs.append(run)
        calls = recorded_calls(runs)
        if calls is None:
            return _VerifyOutcome(accepted=False, reason="reference_not_recordable")
        graded = graded_test_code(test_code, cand.name, calls)
        # Both stages run exactly the way the task is graded: through the grader
        # launcher as the unprivileged user, judged by the verifier's JUnit
        # verdict (every test passed, none skipped, pytest exit 0).
        common = {"test_filename": test_filename, "timeout": self.options.validation_timeout_sec}
        hidden = {test_filename: graded}
        stub = {"task_module.py": stub_module}
        a = run_python_tests(sandbox, files={**stub, **hidden}, **common)
        stub_log = a.log
        if self.options.require_test_fails_with_stub and a.passed:
            return _VerifyOutcome(
                accepted=False,
                reason="test_passes_with_stub",
                stub_log=stub_log,
            )

        oracle = {"task_module.py": oracle_module}
        b = run_python_tests(sandbox, files={**oracle, **hidden}, **common)
        oracle_log = b.log
        if self.options.require_test_passes_with_oracle and not b.passed:
            return _VerifyOutcome(
                accepted=False,
                reason="oracle_does_not_satisfy_test",
                stub_log=stub_log,
                oracle_log=oracle_log,
            )

        # Mutants of the graded test: a recorded reference result changed, so
        # the check it answers expects a value no honest result has.
        mutants = validate_single_file_mutants(
            sandbox,
            test_code=graded,
            passing_files=oracle,
            reference=b,
            pre=a,
            seed=test_filename,
            **common,
        )
        timing = measure([run.sample for run in (a, b) if run.sample is not None])
        timing, checked = fit_runs(timing, mutants is not None)
        mutants = mutants if checked else None
        if timing is not None and timing.over_cap:
            return _VerifyOutcome(
                accepted=False,
                reason="verifier_timeout_over_cap",
                stub_log=stub_log,
                oracle_log=oracle_log,
            )
        return _VerifyOutcome(
            accepted=True,
            stub_log=stub_log,
            oracle_log=oracle_log,
            expected=sorted(b.statuses),
            timing=timing,
            graded_test=graded,
            mutants=mutants,
        )

    # ----- task builder -------------------------------------------------------

    def _task_test_filename(self, cand: FunctionCandidate, parsed: _ParsedTest) -> str:
        h = hashlib.sha256()
        h.update(cand.relative_path.encode())
        h.update(b"\0")
        h.update(cand.name.encode())
        h.update(b"\0")
        h.update(parsed.code.encode())
        return f"test_r2e_{h.hexdigest()[:10]}.py"

    def _build_task(
        self,
        cand: FunctionCandidate,
        test_code: str,
        *,
        test_filename: str,
        expected: list[str] | None = None,
        timing: GradingTime | None = None,
        graded_test: str = "",
        mutants: Mutants | None = None,
    ) -> HarborTask:
        owner, name = self.input.repo.owner_name
        h = hashlib.sha256()
        h.update(cand.relative_path.encode())
        h.update(b"\0")
        h.update(cand.name.encode())
        task_id = f"{owner}__{name}-eqv-{h.hexdigest()[:8]}"

        # Every agent starts from the stub (reference_<name> present, <name>
        # stubbed), baked into the image. The gold patch is a stub→oracle
        # modify-diff that fills in <name>; the equivalence test ships under
        # tests/ (mounted at /tests for every agent) and is copied into
        # /workspace by the verifier — see issue #54.
        stub_module = _stub_module(cand)
        oracle_module = _oracle_module(cand)
        gold_diff = make_unified_diff(stub_module, oracle_module, "task_module.py")
        eval_script = build_single_file_eval_script(
            test_filename,
            language=self.bootstrap.language.value,
            run_timeout=timing.run_timeout if timing is not None else None,
            mutants=mutants,
            copy_timeout=timing.copy_timeout if timing is not None else None,
        )
        image_ref = (
            self.bootstrap.image_digest
            if self.bootstrap.pushed_to_registry
            else self.bootstrap.image_tag
        )
        dockerfile = build_equivalence_dockerfile(image_ref, stub_module)

        instruction = _build_instruction(cand)

        reference = blob_reference_url(
            self.input.repo.source_kind,
            owner,
            name,
            self.input.repo.ref,
            cand.relative_path,
            cand.lineno,
            cand.end_lineno,
        )

        repo2env = {
            "pipeline": "equivalence_tests",
            "pipeline_version": "0.7.1",
            "repo": f"{owner}/{name}",
            "ref": self.input.repo.ref,
            # Omitted, not None, for a local checkout: TOML has no null and
            # tomli_w rejects it outright.
            **({"reference": reference} if reference is not None else {}),
            "source_access": self.input.repo.access,
            "built_at": datetime.now(UTC).isoformat(),
            "synthesis_llm": self.input.llm.qualified_name,
            "reward_kinds": ["test_execution"],
            "harbor_min_version": MIN_HARBOR_VERSION,
            **({"grading_time": timing.metadata()} if timing is not None else {}),
            "tamper_check": "mutants" if mutants is not None and mutants.ids else "unavailable",
            "equivalence_tests": {
                "function_name": cand.name,
                "source_path": cand.relative_path,
                "source_lineno": cand.lineno,
                "source_end_lineno": cand.end_lineno,
                "body_loc": cand.body_loc,
                "arg_names": list(cand.arg_names),
                "test_filename": test_filename,
                "bootstrap_image": self.bootstrap.image_digest,
                "llm_cost_usd": round(self._llm_cost_usd, 6),
            },
        }

        return HarborTask(
            name=task_id,
            org=self.input.output.org,
            description=f"Implement {cand.name} equivalently to the reference",
            instruction=instruction,
            oracle_diff=gold_diff,
            repo2env=repo2env,
            difficulty="medium",
            category="equivalence",
            keywords=[name, "equivalence_tests"],
            environment_dockerfile=dockerfile,
            test_script=eval_script,
            verifier=verifier_config(timing),
            artifacts=SUBMISSION_ARTIFACT,
            aux_files=single_file_verifier_files(
                test_filename,
                graded_test or graded_test_code(test_code, cand.name, {}),
                expected or [],
                mutants=mutants,
            ),
        )


def _build_instruction(cand: FunctionCandidate) -> str:
    """Leak-free instruction — signature + docstring only, never the body.

    Pre-v0.8.7 the emitted `instruction.md` embedded the full source of the
    function under `**Source:**`, so any solving agent could copy the
    reference implementation verbatim. Baseline audit surfaced this on
    every emitted task. v0.8.7 ships only what the RFC always claimed:
    signature + docstring (see `signature_only_source` in `_eval_script.py`).
    A hand-written fallback preserves the RFC-documented shape if the AST
    parse fails.
    """
    sig = signature_only_source(cand.source)
    if sig is None:
        # Fallback — at worst show only the header line and rely on the
        # docstring block below.
        header = f"def {cand.name}({', '.join(cand.arg_names)}):\n    ..."
        sig_block = f"```python\n{header}\n```"
    else:
        sig_block = f"```python\n{sig}\n```"
    docstring_block = f"\n\n**Docstring**\n\n> {cand.docstring}\n" if cand.docstring else ""
    return (
        f"# Implement `{cand.name}`\n\n"
        f"Implement the function `{cand.name}` in `/workspace/task_module.py` "
        f"so that it is behaviorally equivalent to `reference_{cand.name}` "
        f"(which is already provided in `task_module.py`).\n\n"
        f"You are given the function's **signature and docstring only** — "
        f"the reference implementation lives in `task_module.py` alongside a "
        f"stub of `{cand.name}` that currently raises `NotImplementedError`.\n\n"
        f"**Contract (from `{cand.relative_path}` lines {cand.lineno}-{cand.end_lineno}):**\n\n"
        f"{sig_block}{docstring_block}\n\n"
        f"## How the grading works\n\n"
        f"The test file `test_r2e_*.py` imports both `{cand.name}` and "
        f"`reference_{cand.name}` from `task_module` and asserts equality "
        f"across ≥5 inputs. Your implementation passes when every assertion "
        f"holds. You may inspect `reference_{cand.name}` in `task_module.py` "
        f"to understand the behaviour to match — that's the intended "
        f"solve-path — but do NOT change the `reference_` implementation."
    )


def _equivalence_fingerprint(name: str, test_code: str) -> str:
    """Dedup fingerprint for equivalence-test candidates.

    Combines the extracted function name with a hash of the normalized test
    body (whitespace-collapsed + lowercased). Catches the case where the
    LLM re-emits the exact same test suite for the same function on
    different retries, or where two candidate functions across repos
    happen to share a name and get the same LLM-generated test.
    """
    norm = re.sub(r"\s+", " ", test_code.strip().lower())
    sig = f"{name}\0{norm}"
    return hashlib.sha256(sig.encode("utf-8")).hexdigest()[:16]

pipelines/commit_runtime.py

Source: src/repo2rlenv/pipelines/commit_runtime.py · SHA-256 a508f21f13622d0a9997e9ff41dc729c3dfabc678de473875b3d551ca34e95d2

Source hash covers the original file; trailing whitespace is omitted below.

Read pipelines/commit_runtime.py
"""Commit-level mining (SWE-GEN style).

For each commit on the target branch within scope:
  1. Walk `git log` (deeper clone than bootstrap's `--depth=1`)
  2. Filter at the metadata layer (skip merges, bots, short messages,
     too-many-source-files)
  3. `git show <sha>` → split into patch / test_patch using the same
     heuristic as pr_runtime
  4. Validate inside the bootstrap container (reuses pr_runtime's harness)
  5. Emit Harbor task with the same shape as pr_runtime

Unlike `pr_runtime`, there's no PR to link to. Instructions come from
the commit subject + body (after stripping conventional-commit prefixes
and `Closes #N` trailers).

----------------------------------------------------------------------------
Acknowledgment
----------------------------------------------------------------------------
Inspired by:

  R2E-Gym: Procedural Environments and Hybrid Verifiers for Scaling
  Open-Weights SWE Agents (Jain et al., COLM '25)
  https://github.com/R2E-Gym/R2E-Gym                            (MIT)

Their "SWE-GEN" curation approach — bypassing PR-review filters and
mining commits directly — informs this pipeline's design. We share their
finding that commit-level mining produces complementary, larger
candidate pools per repo. No code is copied; implementation is original.

Released under Apache-2.0 along with the rest of Repo2RLEnv.
----------------------------------------------------------------------------
"""

from __future__ import annotations

import logging
import re
import shutil
import tempfile
from datetime import UTC, datetime
from pathlib import Path
from typing import ClassVar

from repo2rlenv.auth import resolve_repo_token
from repo2rlenv.bootstrap.runner import _shallow_clone_at_ref
from repo2rlenv.bootstrap.spec import BootstrapResult
from repo2rlenv.emitter.harbor import HarborTask, write_harbor_task
from repo2rlenv.git_local import CommitInfo, GitError, list_commits, show_diff
from repo2rlenv.llm import complete
from repo2rlenv.pipelines._env_guard import egress_guard_compose, fix_source_hosts
from repo2rlenv.pipelines._grading_time import GradingTime
from repo2rlenv.pipelines._mutants import Mutants
from repo2rlenv.pipelines.base import PipelineResult
from repo2rlenv.pipelines.pr_runtime import (
    MIN_HARBOR_VERSION,
    WORKSPACE_ARTIFACT,
    _count_new_test_funcs,
    _diff_loc_changed,
    _difficulty_bucket,
    _files_in_patch,
    _linked_issue_number,
    _reflow_pr_body,
    _runtime_aux_files,
    _strip_info_leak,
    build_environment_dockerfile,
    build_eval_script,
    normalize_test_cmds_for_runtime,
    separate_verifier_files,
    split_patch_and_test_patch,
    targeted_test_cmds_for_pr,
    verifier_config,
)
from repo2rlenv.provider import provider_for
from repo2rlenv.sources import Capability, SourceKind, capabilities_for
from repo2rlenv.spec.input import GenerationInput, PipelineName
from repo2rlenv.spec.options import CommitRuntimeOptions

logger = logging.getLogger(__name__)


# Strips "Closes #N" / "Fixes [#N](...)" trailers from commit bodies.
# Includes the markdown form Arc 2 added (`fixes [#1234](url)`) and the
# bare `[#N](url)` link form too.
_CLOSES_RE = re.compile(
    r"\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s+\[?#\d+\]?(?:\([^)]*\))?",
    re.IGNORECASE,
)

# Strips conventional-commit prefixes ("fix: ", "feat(scope): ", etc.) from subjects
_CC_PREFIX_RE = re.compile(
    r"^(?:fix|feat|chore|docs|refactor|test|perf|build|ci|style|revert)(?:\([^)]+\))?:\s*",
    re.IGNORECASE,
)

# Conventional-commit types that are NOT bugfixes. These slip into the
# candidate pool today because `_CC_PREFIX_RE` only *strips* the prefix; it
# doesn't reject. Mirrors `pr_runtime._NON_BUG_TITLE_RE` for the commit world.
_NON_BUG_TYPE_RE = re.compile(
    r"^(?:chore|docs|feat|refactor|style|test|ci|build|perf|revert)(?:\([^)]+\))?:\s*",
    re.IGNORECASE,
)

# A bugfix-positive signal we look for when no `fix:` prefix is present and
# no `Closes #N` trailer links an issue. Avoids letting feature commits with
# no type prefix sail through.
_BUGFIX_KEYWORD_RE = re.compile(
    r"\b(?:fix(?:e[sd])?|fixing|bug(?:fix|s)?|regression|crash(?:e[sd]|ing)?|broken|"
    r"incorrect(?:ly)?|wrong(?:ly)?|fail(?:s|ed|ing|ure)?|defect|hotfix|patch(?:e[sd])?)\b",
    re.IGNORECASE,
)


def _word_count(text: str) -> int:
    return len(re.findall(r"\b\w+\b", text or ""))


# Synthesis prompt: turn the fix-commit / linked-issue text into a clean,
# leak-free, symptom-focused problem statement (the bug as a user would report
# it BEFORE the fix). Fixes both failure modes of raw commit text: solution
# leakage (changelog bullets naming the fix) and thinness (title-only subjects).
_SYNTH_SYSTEM = """You are writing a GitHub bug report for an AI coding agent to fix.

You are given the commit message (and maybe a linked issue) that FIXED a bug.
Rewrite it into a clear problem statement describing ONLY the observed problem
and expected behavior — the symptom, as a user would report it BEFORE any fix
existed.

STRICT RULES:
- Describe the symptom + expected vs actual behavior. Include a short
  reproduction if one is evident.
- Do NOT describe the solution, the fix approach, or which functions/files/tests
  to change. Do NOT mention "fix", "patch", commit SHAs, PR/issue numbers,
  file names, test names, "Signed-off-by", or changelog bullets.
- Output exactly: a `**Title:**` line, then a `## Description` section. Markdown
  allowed. Nothing else. Keep it concise (2-6 sentences)."""


def _files_changed_in_diff(unified_diff: str) -> list[str]:
    """Same `b/` path extractor pr_runtime uses; lifted here for the filter layer."""
    return _files_in_patch(unified_diff)


def _strip_commit_prefix(subject: str) -> str:
    """Drop conventional-commit type prefix from subject, leaving the description."""
    cleaned = _CC_PREFIX_RE.sub("", subject, count=1)
    return cleaned.strip()


def build_instruction_from_commit(
    commit: CommitInfo,
    *,
    issue: tuple[str, str] | None = None,
) -> str:
    """Render a commit's subject + body (or a linked issue) into the task prompt.

    Sourcing order — same lesson as Arc 2's `pr_runtime` fix:
      1. If the commit links an issue (``Closes #N``) and the caller has
         fetched it, use the **issue title + body** as the problem statement.
         The bug report is far less leak-prone than the commit message, which
         frequently names the function being fixed and points at fix-PRs.
      2. Otherwise fall back to the commit subject + body, run through
         `_strip_info_leak` + `_reflow_pr_body` to scrub cross-refs and trim
         template noise / line-wrap chatter.
    """
    if issue is not None:
        i_title, i_body = issue
        title = _strip_info_leak(i_title).strip()
        body = _reflow_pr_body(_strip_info_leak(_CLOSES_RE.sub("", i_body or ""))).strip()
    else:
        title = _strip_info_leak(_strip_commit_prefix(commit.subject)).strip()
        body = _reflow_pr_body(_strip_info_leak(_CLOSES_RE.sub("", commit.body or ""))).strip()
    if not title:
        title = _strip_commit_prefix(commit.subject) or "(no title)"
    parts = [f"# Issue\n\n**Title:** {title}"]
    if body:
        parts.append("## Description\n\n" + body)
    parts.append(
        "## Task\n\n"
        "Modify the repository so that the issue described above is resolved. "
        "The task's test suite verifies your patch by applying it on top of "
        f"the base commit `{commit.parent_sha[:12]}` and running the modified tests."
    )
    return "\n\n".join(parts)


class CommitRuntimePipeline:
    """Commit-level mining with sandbox-verified F2P/P2P oracles."""

    name: ClassVar[PipelineName] = PipelineName.COMMIT_RUNTIME
    requires_bootstrap: ClassVar[bool] = True
    experimental: ClassVar[bool] = (
        False  # stable (v0.8.4): synthesized instructions + graded F2P/P2P
    )

    def __init__(
        self,
        input: GenerationInput,
        options: CommitRuntimeOptions,
        bootstrap: BootstrapResult | None = None,
    ):
        if bootstrap is None:
            raise RuntimeError(
                "commit_runtime requires a BootstrapResult (set requires_bootstrap=True "
                "and let cmd_generate trigger it, or pass one explicitly)"
            )
        self.input = input
        self.options = options
        self.bootstrap = bootstrap
        self._progress_cb = None
        self._llm_cost_usd = 0.0

    def _synthesize_problem_statement(
        self, commit: CommitInfo, issue: tuple[str, str] | None
    ) -> str | None:
        """LLM-rewrite the commit/issue into a clean, leak-free problem statement.

        Returns the `**Title:** … ## Description …` body, or None on failure /
        too-thin output (caller falls back to the raw-text builder).
        """
        if self.input.llm is None:
            return None
        src = f"Commit subject: {commit.subject}\n\nCommit body:\n{commit.body or ''}\n"
        if issue is not None:
            src += f"\nLinked issue title: {issue[0]}\nLinked issue body:\n{issue[1] or ''}\n"
        try:
            resp = complete(
                self.input.llm,
                system=_SYNTH_SYSTEM,
                user=src,
                max_tokens=self.options.max_llm_tokens,
                temperature=self.options.llm_temperature,
            )
        except Exception as exc:
            logger.warning("commit_runtime synthesis failed: %s", exc)
            return None
        self._llm_cost_usd += resp.cost_usd
        body = (resp.content or "").strip()
        return body if _word_count(body) >= 10 else None

    def _build_instruction(self, commit: CommitInfo, *, issue: tuple[str, str] | None) -> str:
        """Synthesized (clean) problem statement when enabled, else raw commit text."""
        if self.options.synthesize_with_llm:
            synth = self._synthesize_problem_statement(commit, issue)
            if synth:
                return (
                    f"# Issue\n\n{synth}\n\n## Task\n\n"
                    "Modify the repository so that the issue described above is resolved. "
                    "The task's test suite verifies your patch by applying it on top of "
                    f"the base commit `{commit.parent_sha[:12]}` and running the modified tests."
                )
        return build_instruction_from_commit(commit, issue=issue)

    def set_progress_callback(self, cb) -> None:
        self._progress_cb = cb

    def _emit_progress(self, name: str, outcome: str, reason: str = "") -> None:
        if self._progress_cb is not None:
            try:
                self._progress_cb(name=name, outcome=outcome, reason=reason)
            except Exception as exc:
                logger.debug("progress callback failed: %s", exc)

    # ----- run loop -----------------------------------------------------------

    def run(self, out_dir: Path) -> PipelineResult:
        out_dir.mkdir(parents=True, exist_ok=True)
        token = resolve_repo_token(self.input.repo, self.input.auth)
        if self.input.repo.access == "private" and not token:
            raise RuntimeError(
                "private repo specified but no GitHub token resolved. "
                "Run `gh auth login` or set GITHUB_TOKEN."
            )

        owner, name = self.input.repo.owner_name
        owner_name = f"{owner}/{name}"
        skip_reasons: dict[str, int] = {}
        emitted = 0
        sandbox = None
        candidates: list[CommitInfo] = []

        with tempfile.TemporaryDirectory(prefix="r2e-commit-runtime-") as tmp:
            clone_dir = Path(tmp) / "repo"
            logger.info(
                "cloning %s @ %s (depth=%d) for commit walk",
                self.input.repo.url,
                self.input.repo.ref,
                self.options.clone_depth,
            )
            try:
                _shallow_clone_at_ref(
                    self.input.repo.url,
                    self.input.repo.ref,
                    token,
                    clone_dir,
                    depth=self.options.clone_depth,
                )
            except Exception as exc:
                raise RuntimeError(f"failed to clone {self.input.repo.url}: {exc}") from exc

            try:
                candidates = list_commits(
                    clone_dir,
                    since=self.options.since,
                    until=self.options.until,
                    limit=self.options.limit,
                    branch=self.options.branch,
                )
            except GitError as exc:
                raise RuntimeError(f"git log failed: {exc}") from exc
            logger.info(
                "commit_runtime: %d candidate commits in [%s, %s]",
                len(candidates),
                self.options.since,
                self.options.until,
            )
            if len(candidates) >= self.options.clone_depth:
                logger.warning(
                    "commit_runtime: candidate count (%d) reached clone_depth=%d — "
                    "the shallow clone may be truncating history. "
                    "Pass --pipeline-opt clone_depth=%d or higher to capture more commits.",
                    len(candidates),
                    self.options.clone_depth,
                    self.options.clone_depth * 2,
                )

            try:
                for commit in candidates:
                    label = f"{owner_name}@{commit.sha[:12]}"

                    # Metadata-level filters (cheap)
                    reason = self._metadata_filter(commit)
                    if reason:
                        skip_reasons[reason] = skip_reasons.get(reason, 0) + 1
                        self._emit_progress(label, "skip", reason)
                        continue

                    # Diff-level filters
                    try:
                        diff = show_diff(clone_dir, commit.sha)
                    except GitError as exc:
                        logger.warning("commit %s: git show failed: %s", commit.sha[:12], exc)
                        skip_reasons["diff_fetch_failed"] = (
                            skip_reasons.get("diff_fetch_failed", 0) + 1
                        )
                        self._emit_progress(label, "error", "diff_fetch_failed")
                        continue

                    patch, test_patch = split_patch_and_test_patch(diff)
                    if not patch.strip():
                        skip_reasons["empty_source_patch"] = (
                            skip_reasons.get("empty_source_patch", 0) + 1
                        )
                        self._emit_progress(label, "skip", "empty_source_patch")
                        continue
                    if not test_patch.strip():
                        skip_reasons["no_test_patch"] = skip_reasons.get("no_test_patch", 0) + 1
                        self._emit_progress(label, "skip", "no_test_patch")
                        continue

                    structural_reason = self._structural_filter(patch, test_patch)
                    if structural_reason:
                        skip_reasons[structural_reason] = skip_reasons.get(structural_reason, 0) + 1
                        self._emit_progress(label, "skip", structural_reason)
                        continue

                    if not commit.parent_sha:
                        skip_reasons["root_commit"] = skip_reasons.get("root_commit", 0) + 1
                        self._emit_progress(label, "skip", "root_commit")
                        continue

                    # Validation
                    fail_to_pass: list[str] = []
                    pass_to_pass: list[str] = []
                    validation_status = "skipped"
                    flaky_dropped = 0
                    timing: GradingTime | None = None
                    mutants: Mutants | None = None
                    validated_cmds: list[str] = []
                    if not self.options.skip_validation:
                        if sandbox is None:
                            sandbox = self._start_validation_sandbox()
                        from repo2rlenv.pipelines.pr_runtime_validate import validate_pr

                        targeted_cmds = targeted_test_cmds_for_pr(
                            normalize_test_cmds_for_runtime(self.bootstrap.test_cmds),
                            _files_in_patch(test_patch),
                        )
                        outcome = validate_pr(
                            sandbox=sandbox,
                            base_commit=commit.parent_sha,
                            patch=patch,
                            test_patch=test_patch,
                            test_cmds=targeted_cmds,
                            language=self.bootstrap.language.value,
                            timeout=self.options.validation_timeout_sec,
                        )
                        fail_to_pass = outcome.fail_to_pass
                        pass_to_pass = outcome.pass_to_pass
                        validation_status = outcome.status
                        flaky_dropped = len(outcome.flaky)
                        timing = outcome.timing
                        mutants = outcome.mutants
                        validated_cmds = outcome.test_cmds
                        # Cap the P2P regression set: whole-suite P2P (100s of
                        # tests) inflates flaky-reward risk + runtime. Prefer
                        # tests in the patched files, then fill to the cap.
                        cap = self.options.max_pass_to_pass
                        if cap and len(pass_to_pass) > cap:
                            changed = set(_files_in_patch(patch))
                            near = [
                                t
                                for t in pass_to_pass
                                if any(f.split("::")[0] in t for f in changed)
                            ]
                            far = [t for t in pass_to_pass if t not in set(near)]
                            pass_to_pass = (near + far)[:cap]
                        if (
                            self.options.require_fail_to_pass
                            and len(fail_to_pass) < self.options.min_fail_to_pass
                        ):
                            skip_reasons["no_fail_to_pass"] = (
                                skip_reasons.get("no_fail_to_pass", 0) + 1
                            )
                            self._emit_progress(label, "skip", outcome.reason or "no_fail_to_pass")
                            continue

                    # Issue-fetch fallback: when the commit links an issue
                    # (`Closes #N`), source the problem statement from the
                    # issue body — the bug report is far less leak-prone than
                    # the commit message. Same lesson as Arc 2 for pr_runtime.
                    # Issue enrichment is GitHub-only (gh API). On GitLab/local
                    # sources there's no issue API here, so fall back to the
                    # (scrubbed) commit message. Defensive try/except: a deleted
                    # or private issue must not abort the whole run.
                    issue_num = _linked_issue_number(commit.message or "")
                    issue = None
                    if issue_num is not None and Capability.ISSUES in capabilities_for(
                        self.input.repo.source_kind
                    ):
                        try:
                            issue = provider_for(self.input.repo).fetch_issue(
                                owner, name, issue_num, token=token
                            )
                        except Exception as exc:
                            logger.debug("issue fetch failed (%s); using commit message", exc)
                    task = self._build_task(
                        commit,
                        patch,
                        test_patch,
                        fail_to_pass=fail_to_pass,
                        pass_to_pass=pass_to_pass,
                        validation_status=validation_status,
                        issue=issue,
                        flaky_dropped=flaky_dropped,
                        timing=timing,
                        mutants=mutants,
                        test_cmds=validated_cmds or None,
                    )
                    write_harbor_task(task, out_dir)
                    emitted += 1
                    logger.info(
                        "emitted task %s (F2P=%d, P2P=%d)",
                        task.name,
                        len(fail_to_pass),
                        len(pass_to_pass),
                    )
                    self._emit_progress(task.name, "emit")
            finally:
                if sandbox is not None:
                    sandbox.cleanup()
                # tempfile cleanup happens automatically; make sure git's loose
                # objects don't keep ref to the clone
                shutil.rmtree(clone_dir, ignore_errors=True)

        return PipelineResult(
            candidates=len(candidates),
            emitted=emitted,
            skipped=sum(skip_reasons.values()),
            out_dir=out_dir,
            skip_reasons=skip_reasons,
        )

    # ----- filters ------------------------------------------------------------

    def _metadata_filter(self, commit: CommitInfo) -> str | None:
        """Cheap filters that don't need the diff content.

        Bugfix detection runs in two stages: (a) reject conventional-commit
        types that are explicitly not bugfixes (chore/docs/feat/refactor/
        style/test/ci/build/perf/revert), (b) require a positive bugfix
        signal — `fix:` prefix, a `Closes #N` / `Fixes #N` issue trailer,
        or a bugfix keyword in the subject. Together these mirror Arc 2's
        non-bug-PR rejection and stop feature/refactor commits from
        burning bootstrap cycles in validation.
        """
        if self.options.skip_merge_commits and commit.is_merge:
            return "merge_commit"
        if commit.author_email in self.options.exclude_authors:
            return "excluded_author"
        if _word_count(commit.message) < self.options.min_message_words:
            return "short_message"
        if (
            self.options.min_problem_statement_words > 0
            and _word_count(commit.message) < self.options.min_problem_statement_words
        ):
            return "problem_statement_too_short"
        subject = commit.subject or ""
        # (a) explicit non-bugfix type prefix → reject.
        if _NON_BUG_TYPE_RE.match(subject):
            return "non_bugfix_type"
        # (b) at least one bugfix signal must be present.
        has_fix_prefix = bool(re.match(r"^fix(?:\([^)]+\))?:\s*", subject, re.IGNORECASE))
        has_linked_issue = _linked_issue_number(commit.message or "") is not None
        has_keyword = bool(_BUGFIX_KEYWORD_RE.search(subject))
        if not (has_fix_prefix or has_linked_issue or has_keyword):
            return "no_bugfix_signal"
        return None

    def _structural_filter(self, source_patch: str, test_patch: str) -> str | None:
        """Diff-level filters (mirrors pr_runtime._structural_quality_filter)."""
        source_files = _files_changed_in_diff(source_patch)
        if (
            self.options.skip_ci_only
            and source_files
            and all(p.startswith(".github/") for p in source_files)
        ):
            return "ci_only_patch"
        if len(source_files) > self.options.max_source_files_per_commit:
            return "too_many_source_files"
        if self.options.require_new_test_funcs and _count_new_test_funcs(test_patch) < 1:
            return "no_new_test_funcs"
        return None

    # ----- sandbox -----------------------------------------------------------

    def _start_validation_sandbox(self):
        """Spin up a DockerSandbox from the bootstrap image (shared across commits)."""
        from repo2rlenv.bootstrap.docker import DockerSandbox

        marker = Path(tempfile.mkdtemp(prefix="r2e-commit-runtime-"))
        (marker / ".keep").write_text("")
        sandbox = DockerSandbox.start(
            base_image=self.bootstrap.image_tag,
            repo_dir=marker,
            platform=self.input.bootstrap.platform,
        )
        return sandbox

    # ----- task builder -------------------------------------------------------

    def _build_task(
        self,
        commit: CommitInfo,
        patch: str,
        test_patch: str,
        *,
        fail_to_pass: list[str],
        pass_to_pass: list[str],
        validation_status: str,
        issue: tuple[str, str] | None = None,
        flaky_dropped: int = 0,
        timing: GradingTime | None = None,
        mutants: Mutants | None = None,
        test_cmds: list[str] | None = None,
    ) -> HarborTask:
        owner, name = self.input.repo.owner_name
        # commit_runtime task ID convention: <owner>__<repo>-<sha12>
        # (analogous to pr_runtime's <owner>__<repo>-<pr_number>)
        task_id = f"{owner}__{name}-{commit.sha[:12]}"
        source_kind = self.input.repo.source_kind
        commit_path = "-/commit" if source_kind is SourceKind.GITLAB else "commit"
        commit_reference = (
            f"https://{'gitlab.com' if source_kind is SourceKind.GITLAB else 'github.com'}"
            f"/{owner}/{name}/{commit_path}/{commit.sha}"
            if source_kind is not SourceKind.LOCAL
            else None
        )

        eval_script = build_eval_script(
            base_commit=commit.parent_sha,
            test_patch=test_patch,
            # Grade with exactly what validation ran (Node script indirection resolved).
            test_cmds=test_cmds
            or targeted_test_cmds_for_pr(
                normalize_test_cmds_for_runtime(self.bootstrap.test_cmds),
                _files_in_patch(test_patch),
            ),
            language=self.bootstrap.language.value,
            # Without F2P/P2P, build_eval_script returns the binary exit-code
            # script and reward.json is never written. Pass them in so we get
            # the graded path + tracked/command_resolved breakdown.
            fail_to_pass=fail_to_pass,
            pass_to_pass=pass_to_pass,
            run_timeout=timing.run_timeout if timing is not None else None,
            copy_timeout=timing.copy_timeout if timing is not None else None,
            mutants=mutants,
        )
        image_ref = (
            self.bootstrap.image_digest
            if self.bootstrap.pushed_to_registry
            else self.bootstrap.image_tag
        )
        dockerfile = build_environment_dockerfile(
            bootstrap_image=image_ref,
            base_commit=commit.parent_sha,
        )

        loc_changed = _diff_loc_changed(patch)
        difficulty = _difficulty_bucket(len(fail_to_pass), loc_changed)
        repo2env = {
            "pipeline": "commit_runtime",
            "pipeline_version": "0.8.3",
            "repo": f"{owner}/{name}",
            "ref": commit.parent_sha,
            # Omitted, not None, for a local checkout: TOML has no null and
            # tomli_w rejects it outright.
            **({"reference": commit_reference} if commit_reference is not None else {}),
            "source_access": self.input.repo.access,
            "built_at": datetime.now(UTC).isoformat(),
            **({"synthesis_llm": self.input.llm.qualified_name} if self.input.llm else {}),
            "reward_kinds": ["test_execution", "diff_similarity"],
            "commit_runtime": {
                "commit_sha": commit.sha,
                "parent_sha": commit.parent_sha,
                "authored_at": commit.authored_at,
                "author_email": commit.author_email,
                "subject": commit.subject,
                "fail_to_pass": fail_to_pass,
                "pass_to_pass": pass_to_pass,
                "validation_status": validation_status,
                # Tests dropped at validation because their status varied across reruns.
                "flaky_dropped": flaky_dropped,
                "harbor_min_version": MIN_HARBOR_VERSION,
                **({"grading_time": timing.metadata()} if timing is not None else {}),
                "tamper_check": "mutants" if mutants is not None and mutants.ids else "unavailable",
                "bootstrap_image": self.bootstrap.image_digest,
                "instruction_synthesized": bool(
                    self.options.synthesize_with_llm and self.input.llm
                ),
                "llm_cost_usd": round(self._llm_cost_usd, 6),
            },
            # Calibration parity with pr_runtime: lets the manifest enricher
            # compute difficulty / p2p_count == 0 / loc_changed sliceability
            # without re-parsing the diff.
            "reward_calibration": {
                "f2p_count": len(fail_to_pass),
                "p2p_count": len(pass_to_pass),
                "source_files": len(_files_in_patch(patch)),
                "loc_changed": loc_changed,
                "difficulty": difficulty,
            },
        }

        return HarborTask(
            name=task_id,
            org=self.input.output.org,
            description=_strip_commit_prefix(commit.subject) or task_id,
            instruction=self._build_instruction(commit, issue=issue),
            oracle_diff=patch,
            repo2env=repo2env,
            difficulty=difficulty,
            category="bugfix",
            keywords=[name, "commit_runtime"],
            environment_dockerfile=dockerfile,
            test_script=eval_script,
            # Ship the graded verifier + F2P/P2P JSON as plain task artifacts
            # (Harbor mounts tests/ at /tests). Same shape pr_runtime ships
            # after Arc 2's plain-artifacts refactor — without this, test.sh
            # falls back to the exit-code reward and reward.json is never
            # written, so tracked/command_resolved + the breakdown are lost.
            # The egress guard blocks the hosts that serve this commit's
            # upstream fix so the agent cannot fetch it at run time.
            verifier=verifier_config(timing),
            artifacts=WORKSPACE_ARTIFACT,
            aux_files={
                **(_runtime_aux_files(fail_to_pass, pass_to_pass) if fail_to_pass else {}),
                **separate_verifier_files(mutants),
                "environment/docker-compose.yaml": egress_guard_compose(
                    fix_source_hosts(self.input.repo.source_kind)
                ),
            },
        )

pipelines/cve_patches.py

Source: src/repo2rlenv/pipelines/cve_patches.py · SHA-256 e3bc118d60b82249c9ba1b03c7f5ff53f69d510c372216a416ff3fe86f88d4f6

Source hash covers the original file; trailing whitespace is omitted below.

Read pipelines/cve_patches.py
"""Map OSV vulnerability records to fixing commits in the target repo.

Workflow:
  1. Query OSV's `/v1/query` for the repo's ecosystem + package
  2. For each vuln, scan `references[]` for a github.com/<owner>/<repo>/commit/<sha> URL
  3. Fetch that commit's diff via `gh api`; split into source/test patches
  4. Validation (when test_patch is non-empty): same harness as pr_runtime —
     two-stage F2P/P2P inside the bootstrap container
  5. Emit a Harbor task whose instruction is the CVE description and whose
     oracle is the fix diff

Unlike `pr_runtime` / `commit_runtime`, many CVE fixes don't ship a test
patch in the same commit (the test came later, or the regression was
covered by an existing case). When `test_patch` is empty, we emit the
task with `validation_status="no_test_patch"` — the verifier signal is
just "tests still pass with the fix applied", which is weaker than F2P
but still useful as training data.

----------------------------------------------------------------------------
Acknowledgment
----------------------------------------------------------------------------
Inspired by:

  PatchSeeker (Le et al.) — LLM + embedding similarity for NVD→commit mapping
  https://github.com/hungkien05/PatchSeeker        (MIT)

  CVE-Bench (Zhu et al., NAACL '25) — benchmark of CVE-fixing tasks

We use the OSV (Open Source Vulnerabilities) public API instead of NVD
because OSV pre-resolves the `references[]` block to include fix-commit
URLs in a structured way, removing the need for LLM-driven CVE→commit
mapping for the common case. No code is copied; the OSV client is
stdlib-only, the validation harness is reused verbatim from pr_runtime.

Released under Apache-2.0 along with the rest of Repo2RLEnv.
----------------------------------------------------------------------------
"""

from __future__ import annotations

import logging
import os
import re
import tempfile
from datetime import UTC, datetime
from pathlib import Path
from typing import ClassVar

from repo2rlenv.auth import resolve_github_token
from repo2rlenv.bootstrap.spec import BootstrapResult
from repo2rlenv.emitter.harbor import HarborTask, write_harbor_task
from repo2rlenv.github import (
    GitHubError,
    fetch_commit_diff,
    fetch_commit_parent,
    fetch_file_at_ref,
)
from repo2rlenv.llm import complete
from repo2rlenv.osv import OSVError, OSVVuln, guess_ecosystem, query_vulns, severity_at_least
from repo2rlenv.pipelines._env_guard import egress_guard_compose, fix_source_hosts
from repo2rlenv.pipelines._grading_time import GradingTime
from repo2rlenv.pipelines._mutants import Mutants
from repo2rlenv.pipelines.base import PipelineResult
from repo2rlenv.pipelines.code_instruct import new_file_hunk
from repo2rlenv.pipelines.pr_runtime import (
    MIN_HARBOR_VERSION,
    WORKSPACE_ARTIFACT,
    _files_in_patch,
    _runtime_aux_files,
    build_environment_dockerfile,
    build_eval_script,
    normalize_test_cmds_for_runtime,
    separate_verifier_files,
    split_patch_and_test_patch,
    targeted_test_cmds_for_pr,
    verifier_config,
)
from repo2rlenv.sources import Capability
from repo2rlenv.spec.input import GenerationInput, PipelineName
from repo2rlenv.spec.options import CVEPatchesOptions

logger = logging.getLogger(__name__)

# Synthesis prompt: write the regression test the CVE fix never shipped. The
# test must FAIL on the pre-fix (vulnerable) code and PASS once the fix is
# applied — that's what turns a CVE into a verifiable F2P oracle.
_POC_SYSTEM = """You write a pytest regression test that proves a security fix.

You are given a CVE description and the unified diff of the commit that FIXED it.
Write ONE pytest test file that exercises the vulnerable behavior such that:
- on the code BEFORE the fix it FAILS (the vulnerability/incorrect behavior is present),
- on the code AFTER the fix it PASSES.

STRICT RULES:
- Output ONLY the Python test file content — no prose, no markdown fences.
- Use plain `def test_*():` functions with `assert` (no unittest.TestCase, no network, no sleep/timing).
- Import from the library under test by its real package name; build inputs as literals.
- The test must be deterministic and self-contained. Target the SPECIFIC behavior the
  diff changes (e.g. the now-rejected input, the corrected parse result), not unrelated APIs.
- Do NOT reference the fix, commit SHAs, or that a patch exists."""


def _poc_user_prompt(vuln: OSVVuln, patch: str, vuln_code: str = "") -> str:
    desc = (vuln.summary or "") + "\n\n" + (vuln.details or "")
    parts = [f"CVE: {vuln.cve_id or vuln.id}\n\nDescription:\n{desc.strip()[:3000]}\n"]
    if vuln_code:
        parts.append(
            "\nVulnerable source BEFORE the fix (use this for the real import paths "
            f"and how to call the affected code):\n```python\n{vuln_code[:9000]}\n```\n"
        )
    parts.append(f"\nThe fix (what changed):\n```diff\n{patch[:6000]}\n```\n")
    parts.append("Write the regression test now (file content only).")
    return "\n".join(parts)


# Headings that point at the FIX rather than describe the symptom. An agent
# with web access could follow these straight to the patch, so we drop the
# whole section (heading + body until the next heading).
_LEAK_SECTION_RE = re.compile(
    r"(?ims)^[ \t]*#{1,6}[ \t]*"
    r"(workarounds?|remediation|mitigations?|references?|fix(?:es|ed)?|patch(?:es|ed)?|"
    r"solutions?|credits?|acknowledge?ments?|resources?|links?|see also|further reading)\b"
    r".*?(?=^[ \t]*#{1,6}[ \t]|\Z)"
)
# Inline fix-pointers: vuln ids (direct lookup keys to the published patch),
# github pull/commit/compare/release URLs, bare PR refs, "fixed in vX.Y",
# "upgrade to …", "apply … PR #N", and naked 7–40 char commit SHAs.
_LEAK_LINE_RES = [
    re.compile(r"(?im)^.*\b(?:apply|see|refer to|backport|cherry[- ]pick)\b.*$"),
    re.compile(r"(?im)^.*\b(?:fixed|resolved|patched|addressed)\b.*\bin\b.*\bv?\d+\.\d+.*$"),
    re.compile(r"(?im)^.*\bupgrade\b.*\b(?:to|version)\b.*$"),
]
_LEAK_TOKEN_RES = [
    re.compile(r"https?://\S*github\.com/\S+", re.I),
    re.compile(r"https?://\S+", re.I),
    re.compile(r"\b(?:CVE-\d{4}-\d{4,7}|GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4})\b", re.I),
    re.compile(r"\b(?:PR|pull request|pull|commit|issue)\s*#?\d+\b", re.I),
    re.compile(r"(?<![\w/])#\d{2,}\b"),
    re.compile(r"\b[0-9a-f]{7,40}\b", re.I),  # bare commit SHAs
]


def _strip_fix_leaks(text: str) -> str:
    """Remove fix-pointers so a web-capable agent can't fetch the patch.

    Drops fix-oriented sections, then scrubs inline ids/URLs/PR refs/SHAs.
    Keeps the *symptom* description — that's the actual task signal.
    """
    text = _LEAK_SECTION_RE.sub("", text)
    for rx in _LEAK_LINE_RES:
        text = rx.sub("", text)
    for rx in _LEAK_TOKEN_RES:
        text = rx.sub("", text)
    # collapse blank-line runs left by the removals
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()


def _build_instruction(vuln: OSVVuln) -> str:
    """Render the CVE description into a leak-free, task-prompt-shaped string.

    The visible prompt never names the CVE/GHSA id, the fixing PR/commit, or a
    "fixed in version" — those are direct lookup keys to the published patch and
    a web-capable agent would just fetch it. Provenance lives in task.toml
    metadata; the agent sees only the vulnerability *symptom* + its CWE class.
    """
    title = _strip_fix_leaks(vuln.summary or "") or "A security vulnerability in this project"
    body = _strip_fix_leaks(vuln.details) or "(no detailed description available)"
    cwe = ", ".join(vuln.cwe_ids) or "(no CWE tag)"
    return (
        f"# Security advisory\n\n"
        f"**Title:** {title}\n\n"
        f"**Severity:** {vuln.severity_text or 'unknown'}\n"
        f"**CWE:** {cwe}\n\n"
        f"## Description\n\n{body}\n\n"
        f"## Task\n\n"
        f"Patch the repository to address the vulnerability described above. "
        f"The task's test suite verifies your patch by applying it on top of "
        f"the parent of the original fixing commit and running the tests.\n\n"
        f"Solve this by analyzing the source code and reasoning about the root "
        f"cause, then writing the fix yourself. Do not search for, fetch, or "
        f"reproduce the upstream patch, the fixing commit/PR, a newer release of "
        f"this package, or any published advisory — work the fix out from the "
        f"code in front of you."
    )


class CVEPatchesPipeline:
    """OSV-driven CVE → fix-commit pipeline."""

    name: ClassVar[PipelineName] = PipelineName.CVE_PATCHES
    required_capabilities: ClassVar[frozenset[Capability]] = frozenset({Capability.COMMIT_API})
    requires_bootstrap: ClassVar[bool] = True
    experimental: ClassVar[bool] = True

    def __init__(
        self,
        input: GenerationInput,
        options: CVEPatchesOptions,
        bootstrap: BootstrapResult | None = None,
    ):
        if bootstrap is None:
            raise RuntimeError(
                "cve_patches requires a BootstrapResult (set requires_bootstrap=True "
                "and let cmd_generate trigger it, or pass one explicitly)"
            )
        self.input = input
        self.options = options
        self.bootstrap = bootstrap
        self._progress_cb = None
        self._llm_cost_usd = 0.0

    def _synthesize_poc_test(
        self, vuln: OSVVuln, patch: str, owner: str, name: str, base_sha: str, token: str | None
    ) -> str | None:
        """LLM-write the regression test the CVE fix omitted. Returns file content or None.

        Feeds the LLM the *full vulnerable source* of the changed files (not just
        the diff) so it knows the real import paths + how to call the affected
        code — the diff alone is rarely enough to write a runnable test.
        """
        if self.input.llm is None:
            return None
        vuln_code = ""
        for f in _files_in_patch(patch)[:2]:
            content = fetch_file_at_ref(owner, name, f, base_sha, token=token)
            if content:
                vuln_code += f"# ===== {f} =====\n{content}\n\n"
        try:
            resp = complete(
                self.input.llm,
                system=_POC_SYSTEM,
                user=_poc_user_prompt(vuln, patch, vuln_code),
                max_tokens=self.options.max_llm_tokens,
                temperature=self.options.llm_temperature,
            )
        except Exception as exc:
            logger.warning("cve_patches PoC synthesis failed for %s: %s", vuln.id, exc)
            return None
        self._llm_cost_usd += resp.cost_usd
        code = (resp.content or "").strip()
        # strip an accidental ```python fence if the model added one
        if code.startswith("```"):
            code = code.split("\n", 1)[-1].rsplit("```", 1)[0].strip()
        if os.environ.get("R2E_POC_DEBUG") and code:  # debug aid: inspect generated tests
            dbg = Path("/tmp/poc_debug")
            dbg.mkdir(exist_ok=True)
            (dbg / f"{(vuln.cve_id or vuln.id).replace('/', '_')}.py").write_text(code)
        return code if ("def test" in code and len(code) > 40) else None

    @staticmethod
    def _poc_test_patch(test_code: str, slug: str) -> str:
        """Wrap synthesized test code as a new-file `git apply` diff under tests/."""
        path = f"tests/test_cve_{slug.lower().replace('-', '_')}.py"
        return new_file_hunk(test_code if test_code.endswith("\n") else test_code + "\n", path)

    def set_progress_callback(self, cb) -> None:
        self._progress_cb = cb

    def _emit_progress(self, name: str, outcome: str, reason: str = "") -> None:
        if self._progress_cb is not None:
            try:
                self._progress_cb(name=name, outcome=outcome, reason=reason)
            except Exception as exc:
                logger.debug("progress callback failed: %s", exc)

    # ----- run loop -----------------------------------------------------------

    def run(self, out_dir: Path) -> PipelineResult:
        out_dir.mkdir(parents=True, exist_ok=True)
        token = resolve_github_token(self.input.repo, self.input.auth)
        if self.input.repo.access == "private" and not token:
            raise RuntimeError(
                "private repo specified but no GitHub token resolved. "
                "Run `gh auth login` or set GITHUB_TOKEN."
            )

        owner, name = self.input.repo.owner_name
        label_root = f"{owner}/{name}"

        ecosystem = self.options.osv_ecosystem or guess_ecosystem(owner)
        package = self.options.osv_package or name.lower()
        logger.info(
            "cve_patches: querying OSV ecosystem=%s package=%s for %s/%s",
            ecosystem,
            package,
            owner,
            name,
        )
        try:
            vulns = query_vulns(package, ecosystem)
        except OSVError as exc:
            raise RuntimeError(f"OSV query failed: {exc}") from exc

        # Filter by severity + must have at least one fix commit
        in_scope: list[tuple[OSVVuln, str]] = []
        for v in vulns:
            if not severity_at_least(v, self.options.min_severity):
                continue
            commits = v.fix_commits(owner=owner, repo=name)
            if not commits:
                continue
            # If multiple commits, pick the first — usually the primary fix
            in_scope.append((v, commits[0]))

        logger.info(
            "cve_patches: %d vulns total, %d in scope (have fix commit in %s/%s)",
            len(vulns),
            len(in_scope),
            owner,
            name,
        )

        skip_reasons: dict[str, int] = {}
        emitted = 0
        sandbox = None

        try:
            for vuln, fix_sha in in_scope:
                if emitted >= self.options.limit:
                    break
                label = f"{label_root}#{vuln.id}"

                # Resolve parent commit
                parent_sha = fetch_commit_parent(owner, name, fix_sha, token=token)
                if not parent_sha:
                    skip_reasons["no_parent_commit"] = skip_reasons.get("no_parent_commit", 0) + 1
                    self._emit_progress(label, "skip", "no_parent_commit")
                    continue

                # Fetch the fix commit's diff
                try:
                    diff = fetch_commit_diff(owner, name, fix_sha, token=token)
                except GitHubError as exc:
                    logger.warning("CVE %s: diff fetch failed: %s", vuln.id, exc)
                    skip_reasons["diff_fetch_failed"] = skip_reasons.get("diff_fetch_failed", 0) + 1
                    self._emit_progress(label, "error", "diff_fetch_failed")
                    continue

                patch, test_patch = split_patch_and_test_patch(diff)
                if not patch.strip():
                    skip_reasons["empty_source_patch"] = (
                        skip_reasons.get("empty_source_patch", 0) + 1
                    )
                    self._emit_progress(label, "skip", "empty_source_patch")
                    continue

                source_files = _files_in_patch(patch)
                if len(source_files) > self.options.max_source_files_per_fix:
                    skip_reasons["too_many_source_files"] = (
                        skip_reasons.get("too_many_source_files", 0) + 1
                    )
                    self._emit_progress(label, "skip", "too_many_source_files")
                    continue

                # Build the F2P oracle. Two sources of a fail→pass test:
                #   1. a real test_patch shipped in the fix commit (rare for CVEs)
                #   2. an LLM-synthesized PoC test (default) — must FAIL pre-fix,
                #      PASS post-fix, validated below. This is what makes a CVE
                #      whose fix shipped no test into a verifiable, non-gameable env.
                fail_to_pass: list[str] = []
                pass_to_pass: list[str] = []
                validation_status = "no_test_patch"
                flaky_dropped = 0
                timing: GradingTime | None = None
                mutants: Mutants | None = None
                validated_cmds: list[str] = []
                effective_test_patch = test_patch
                lang = self.bootstrap.language.value

                def _validate(tp: str, base: str, src_patch: str, language: str):
                    nonlocal sandbox
                    if sandbox is None:
                        sandbox = self._start_validation_sandbox()
                    from repo2rlenv.pipelines.pr_runtime_validate import validate_pr

                    return validate_pr(
                        sandbox=sandbox,
                        base_commit=base,
                        patch=src_patch,
                        test_patch=tp,
                        test_cmds=targeted_test_cmds_for_pr(
                            normalize_test_cmds_for_runtime(self.bootstrap.test_cmds),
                            _files_in_patch(tp),
                        ),
                        language=language,
                        timeout=self.options.validation_timeout_sec,
                    )

                if self.options.skip_validation:
                    pass
                elif test_patch.strip():
                    outcome = _validate(test_patch, parent_sha, patch, lang)
                    fail_to_pass, pass_to_pass, validation_status = (
                        outcome.fail_to_pass,
                        outcome.pass_to_pass,
                        outcome.status,
                    )
                    flaky_dropped = len(outcome.flaky)
                    timing = outcome.timing
                    mutants = outcome.mutants
                    validated_cmds = outcome.test_cmds
                elif self.options.synthesize_poc_test and lang == "python" and self.input.llm:
                    if sandbox is None:
                        sandbox = self._start_validation_sandbox()
                    candidates: list[str] = []
                    if self.options.poc_agent:
                        # Agentic: an LLM with shell access in the vulnerable sandbox
                        # explores the repo, writes the test, runs pytest, iterates —
                        # so the test imports correctly and reproduces the CVE.
                        from repo2rlenv.pipelines._poc_agent import synthesize_poc_agentic

                        vuln_desc = (vuln.summary or "") + "\n\n" + (vuln.details or "")
                        result, c = synthesize_poc_agentic(
                            sandbox,
                            parent_sha=parent_sha,
                            vuln_desc=vuln_desc,
                            fix_diff=patch,
                            llm=self.input.llm,
                            max_spend_usd=self.options.poc_agent_max_spend_usd,
                        )
                        self._llm_cost_usd += c
                        if result:
                            code = (
                                result.test_code
                                if result.test_code.endswith("\n")
                                else result.test_code + "\n"
                            )
                            candidates.append(new_file_hunk(code, result.test_path.lstrip("/")))
                    else:
                        # One-shot prompt synthesis (fallback), retried.
                        for _ in range(max(1, self.options.poc_max_attempts)):
                            code = self._synthesize_poc_test(
                                vuln, patch, owner, name, parent_sha, token
                            )
                            if code:
                                candidates.append(
                                    self._poc_test_patch(code, vuln.cve_id or vuln.id)
                                )

                    for cand in candidates:
                        outcome = _validate(cand, parent_sha, patch, lang)
                        if len(outcome.fail_to_pass) >= self.options.min_fail_to_pass:
                            effective_test_patch = cand
                            fail_to_pass, pass_to_pass = outcome.fail_to_pass, outcome.pass_to_pass
                            flaky_dropped = len(outcome.flaky)
                            timing = outcome.timing
                            mutants = outcome.mutants
                            validated_cmds = outcome.test_cmds
                            validation_status = "poc_synthesized"
                            break

                # Require a real oracle: drop dead (0-reward) envs.
                if (
                    self.options.require_fail_to_pass
                    and len(fail_to_pass) < self.options.min_fail_to_pass
                ):
                    skip_reasons["no_verifiable_oracle"] = (
                        skip_reasons.get("no_verifiable_oracle", 0) + 1
                    )
                    self._emit_progress(label, "skip", "no_verifiable_oracle")
                    continue

                # Cap the P2P regression set (bounds flaky-reward + runtime).
                cap = self.options.max_pass_to_pass
                if cap and len(pass_to_pass) > cap:
                    pass_to_pass = pass_to_pass[:cap]

                # Emit the Harbor task
                task = self._build_task(
                    vuln=vuln,
                    fix_sha=fix_sha,
                    parent_sha=parent_sha,
                    patch=patch,
                    test_patch=effective_test_patch,
                    fail_to_pass=fail_to_pass,
                    pass_to_pass=pass_to_pass,
                    validation_status=validation_status,
                    flaky_dropped=flaky_dropped,
                    timing=timing,
                    mutants=mutants,
                    test_cmds=validated_cmds or None,
                )
                write_harbor_task(task, out_dir)
                emitted += 1
                logger.info(
                    "emitted task %s (CVE=%s, F2P=%d, P2P=%d)",
                    task.name,
                    vuln.cve_id or vuln.id,
                    len(fail_to_pass),
                    len(pass_to_pass),
                )
                self._emit_progress(task.name, "emit")
        finally:
            if sandbox is not None:
                sandbox.cleanup()

        return PipelineResult(
            candidates=len(in_scope),
            emitted=emitted,
            skipped=sum(skip_reasons.values()),
            out_dir=out_dir,
            skip_reasons=skip_reasons,
        )

    # ----- sandbox -----------------------------------------------------------

    def _start_validation_sandbox(self):
        from repo2rlenv.bootstrap.docker import DockerSandbox

        marker = Path(tempfile.mkdtemp(prefix="r2e-cve-patches-"))
        (marker / ".keep").write_text("")
        return DockerSandbox.start(
            base_image=self.bootstrap.image_tag,
            repo_dir=marker,
            platform=self.input.bootstrap.platform,
        )

    # ----- task builder -------------------------------------------------------

    def _build_task(
        self,
        *,
        vuln: OSVVuln,
        fix_sha: str,
        parent_sha: str,
        patch: str,
        test_patch: str,
        fail_to_pass: list[str],
        pass_to_pass: list[str],
        validation_status: str,
        flaky_dropped: int = 0,
        timing: GradingTime | None = None,
        mutants: Mutants | None = None,
        test_cmds: list[str] | None = None,
    ) -> HarborTask:
        owner, name = self.input.repo.owner_name
        # Use the CVE id (or fallback to OSV id) for the task slug — stable + human-readable
        slug_id = (vuln.cve_id or vuln.id).replace("/", "_")
        task_id = f"{owner}__{name}-cve-{slug_id}"

        # Graded, *targeted* verifier (reward = f2p_rate × p2p_rate over the
        # F2P/P2P lists) — same as pr_runtime. Passing fail_to_pass switches
        # build_eval_script off its binary whole-suite fallback, which would
        # otherwise score the oracle 0.0 on any unrelated suite failure.
        eval_script = build_eval_script(
            base_commit=parent_sha,
            test_patch=test_patch,
            # Grade with exactly what validation ran (Node script indirection resolved).
            test_cmds=test_cmds
            or targeted_test_cmds_for_pr(
                normalize_test_cmds_for_runtime(self.bootstrap.test_cmds),
                _files_in_patch(test_patch),
            ),
            language=self.bootstrap.language.value,
            fail_to_pass=fail_to_pass or None,
            pass_to_pass=pass_to_pass or None,
            run_timeout=timing.run_timeout if timing is not None else None,
            copy_timeout=timing.copy_timeout if timing is not None else None,
            mutants=mutants,
        )
        image_ref = (
            self.bootstrap.image_digest
            if self.bootstrap.pushed_to_registry
            else self.bootstrap.image_tag
        )
        dockerfile = build_environment_dockerfile(
            bootstrap_image=image_ref,
            base_commit=parent_sha,
        )

        repo2env = {
            "pipeline": "cve_patches",
            "pipeline_version": "0.8.5",
            "repo": f"{owner}/{name}",
            "ref": parent_sha,
            "reference": f"https://github.com/{owner}/{name}/commit/{fix_sha}",
            "source_access": self.input.repo.access,
            "built_at": datetime.now(UTC).isoformat(),
            **({"synthesis_llm": self.input.llm.qualified_name} if self.input.llm else {}),
            "reward_kinds": ["test_execution", "diff_similarity"],
            "cve_patches": {
                "cve_id": vuln.cve_id or "",
                "osv_id": vuln.id,
                "aliases": vuln.aliases,
                "cwe_ids": vuln.cwe_ids,
                "severity": vuln.severity_text,
                "published": vuln.published,
                "fix_commit": fix_sha,
                "parent_commit": parent_sha,
                "fail_to_pass": fail_to_pass,
                "pass_to_pass": pass_to_pass,
                "validation_status": validation_status,
                # Tests dropped at validation because their status varied across reruns.
                "flaky_dropped": flaky_dropped,
                "harbor_min_version": MIN_HARBOR_VERSION,
                **({"grading_time": timing.metadata()} if timing is not None else {}),
                "tamper_check": "mutants" if mutants is not None and mutants.ids else "unavailable",
                "poc_synthesized": validation_status == "poc_synthesized",
                "llm_cost_usd": round(self._llm_cost_usd, 6),
                "bootstrap_image": self.bootstrap.image_digest,
            },
        }

        return HarborTask(
            name=task_id,
            org=self.input.output.org,
            description=vuln.summary or task_id,
            instruction=_build_instruction(vuln),
            oracle_diff=patch,
            repo2env=repo2env,
            difficulty="hard",  # CVE fixes are harder than vanilla bugs
            category="security",
            keywords=[name, "cve_patches", "security"],
            environment_dockerfile=dockerfile,
            test_script=eval_script,
            # Ship the graded verifier + F2P/P2P lists as plain task artifacts
            # (Harbor mounts tests/ at /tests). Without these the test.sh's
            # `verifier.py` call can't run and the reward is never written. The
            # egress guard blackholes the hosts that serve this CVE's published
            # fix so the agent cannot fetch the answer at run time.
            verifier=verifier_config(timing),
            artifacts=WORKSPACE_ARTIFACT,
            aux_files={
                **(_runtime_aux_files(fail_to_pass, pass_to_pass) if fail_to_pass else {}),
                **separate_verifier_files(mutants),
                "environment/docker-compose.yaml": egress_guard_compose(
                    fix_source_hosts(self.input.repo.source_kind)
                ),
            },
        )

reward.py

Source: src/repo2rlenv/reward.py · SHA-256 e15337ee97dce11edd7e2454193e1305639f116d34942efe5686e7f44ce535ac

Source hash covers the original file; trailing whitespace is omitted below.

Read reward.py
"""Diff-similarity reward.

Computes a [0, 1] score by comparing a predicted unified diff against an oracle
diff using sequence similarity. Verifiable: identical diffs ⇒ 1.0; unrelated
diffs ⇒ near 0. Uses only stdlib (`difflib`).

----------------------------------------------------------------------------
Acknowledgment
----------------------------------------------------------------------------
The reward concept (sequence-similarity over normalized diffs) is inspired by:

  SWE-RL: Advancing LLM Reasoning via Reinforcement Learning on Open Software
  Evolution (Wei et al., NeurIPS '25, arXiv:2502.18449)
  https://github.com/facebookresearch/swe-rl
  Reward library license: CC BY-NC 4.0 (non-commercial)

This file is an INDEPENDENT REIMPLEMENTATION. No code is copied from SWE-RL —
we use only Python's standard library (`difflib.SequenceMatcher`). The CC
BY-NC license therefore does not apply to this file. This file is released
under Apache-2.0 along with the rest of Repo2RLEnv. See LICENSE at repo root.
----------------------------------------------------------------------------
"""

from __future__ import annotations

import difflib
import re
from dataclasses import dataclass

_HUNK_HEADER_RE = re.compile(r"^@@.*@@")
_FILE_HEADER_RE = re.compile(r"^(?:---|\+\+\+) ")
_INDEX_LINE_RE = re.compile(r"^index ")
_DIFF_GIT_RE = re.compile(r"^diff --git ")
_SIMILARITY_LINE_RE = re.compile(r"^(?:similarity index|dissimilarity index)\b")
_MODE_OR_RENAME_RE = re.compile(
    r"^(?:old mode|new mode|new file mode|deleted file mode|copy from|copy to|rename from|rename to)\b"
)
_NO_NEWLINE_RE = re.compile(r"^\\ No newline at end of file")


@dataclass(slots=True)
class DiffRewardMetadata:
    similarity: float
    pred_lines: int
    oracle_lines: int
    matched_lines: int
    parse_error: str | None = None


def _split_diff_sections(diff: str) -> list[list[str]]:
    sections: list[list[str]] = []
    current: list[str] = []
    for line in diff.splitlines():
        if _DIFF_GIT_RE.match(line):
            if current:
                sections.append(current)
            current = [line]
        else:
            current.append(line)
    if current:
        sections.append(current)
    return sections


def _normalize_diff(diff: str) -> list[str]:
    """Strip volatile metadata while preserving mode-only and rename-only changes."""
    lines: list[str] = []
    for section in _split_diff_sections(diff):
        has_hunks = any(_HUNK_HEADER_RE.match(line) for line in section)
        has_file_headers = any(_FILE_HEADER_RE.match(line) for line in section)

        for line in section:
            if _DIFF_GIT_RE.match(line):
                # Keep diff --git if there are no ---/+++ markers (e.g. mode-only or rename-only changes)
                if not has_file_headers:
                    lines.append(line.strip())
                continue
            if _INDEX_LINE_RE.match(line):
                continue
            if _SIMILARITY_LINE_RE.match(line):
                continue
            if _NO_NEWLINE_RE.match(line):
                continue
            if _MODE_OR_RENAME_RE.match(line):
                # Extended headers are volatile when content hunks are present,
                # but essential to preserve when there are mode-only or rename-only changes.
                if not has_hunks:
                    lines.append(line.strip())
                continue
            if _HUNK_HEADER_RE.match(line):
                lines.append("@@")  # keep as a separator but drop line numbers
                continue
            if _FILE_HEADER_RE.match(line):
                # Keep filename markers but normalize whitespace
                lines.append(line.split("\t")[0].strip())
                continue
            lines.append(line)
    return lines


def calculate_diff_similarity_reward(
    oracle_diff: str, predicted_diff: str
) -> tuple[float, DiffRewardMetadata]:
    """Score a predicted diff against an oracle diff.

    Returns (reward, metadata) where reward ∈ [0, 1]:
      - 1.0 if normalized diffs are identical
      - 0.0 if predicted_diff is empty or unparseable
      - else difflib.SequenceMatcher ratio over normalized lines
    """
    if not predicted_diff.strip():
        return 0.0, DiffRewardMetadata(0.0, 0, 0, 0, "empty prediction")

    oracle_lines = _normalize_diff(oracle_diff)
    pred_lines = _normalize_diff(predicted_diff)

    if not oracle_lines:
        return 0.0, DiffRewardMetadata(
            0.0, len(pred_lines), 0, 0, "empty oracle after normalization"
        )

    matcher = difflib.SequenceMatcher(a=oracle_lines, b=pred_lines, autojunk=False)
    ratio = matcher.ratio()
    matched = sum(triple.size for triple in matcher.get_matching_blocks())

    return ratio, DiffRewardMetadata(
        similarity=ratio,
        pred_lines=len(pred_lines),
        oracle_lines=len(oracle_lines),
        matched_lines=matched,
    )


# ----------------------------------------------------------------------------
# SWE-bench-style test-execution grading (used by pr_runtime + Harbor verifiers)
# ----------------------------------------------------------------------------


@dataclass(slots=True)
class ExecutionReport:
    """Per-task report after running the model patch through the eval script.

    Mirrors SWE-bench's report shape so we can interop with their tooling.
    """

    fail_to_pass_success: list[str]
    fail_to_pass_failure: list[str]
    pass_to_pass_success: list[str]
    pass_to_pass_failure: list[str]

    @property
    def f2p_rate(self) -> float:
        total = len(self.fail_to_pass_success) + len(self.fail_to_pass_failure)
        return 1.0 if total == 0 else len(self.fail_to_pass_success) / total

    @property
    def p2p_rate(self) -> float:
        total = len(self.pass_to_pass_success) + len(self.pass_to_pass_failure)
        return 1.0 if total == 0 else len(self.pass_to_pass_success) / total

    @property
    def resolution_status(self) -> str:
        """SWE-bench's FULL / PARTIAL / NO labelling."""
        f2p, p2p = self.f2p_rate, self.p2p_rate
        if f2p == 1.0 and p2p == 1.0:
            return "FULL"
        if 0.0 < f2p < 1.0 and p2p == 1.0:
            return "PARTIAL"
        return "NO"


def grade_test_execution(
    fail_to_pass: list[str],
    pass_to_pass: list[str],
    test_status: dict[str, str],
) -> ExecutionReport:
    """Compute the per-task report from the post-prediction test status map.

    Args:
        fail_to_pass: oracle list of tests that must transition FAIL → PASS
        pass_to_pass: oracle list of tests that must stay PASSED
        test_status: parser output {test_name -> {PASSED|FAILED|SKIPPED|ERROR}}

    Tests not present in `test_status` count as failures (silent skip).
    """
    f2p_success, f2p_failure = [], []
    for t in fail_to_pass:
        (f2p_success if test_status.get(t) == "PASSED" else f2p_failure).append(t)
    p2p_success, p2p_failure = [], []
    for t in pass_to_pass:
        (p2p_success if test_status.get(t) == "PASSED" else p2p_failure).append(t)
    return ExecutionReport(
        fail_to_pass_success=f2p_success,
        fail_to_pass_failure=f2p_failure,
        pass_to_pass_success=p2p_success,
        pass_to_pass_failure=p2p_failure,
    )

On this page