Trajectory generation: prompt reference
Read the trajectory walkthrough first. Repair replays an observed fix without authoring calls; build, extend and QA assemble model requests from the session and reference artifacts. These excerpts include the prompts, response handling and shared model budget.
pipelines/trajectory/families/build.py
Source: src/repo2rlenv/pipelines/trajectory/families/build.py · SHA-256 f9d1cd613ea462e89e48947484fa2e2c4d68c1beafd25101e7405e4220f8135a
Source hash covers the original file; trailing whitespace is omitted below.
Read pipelines/trajectory/families/build.py
"""build: build a project from the user's request; hidden tests give partial credit.
The reference is the agent's Python project at the end of the trajectory's first request.
Claude writes an interface contract, a behaviour-free stub and candidate tests. A test is kept
only if it passes on the reference (twice) and fails on both the stub and an empty workspace;
together the kept tests must catch most mutants of the reference. Reward = fraction passed.
"""
from __future__ import annotations
import ast
import json
import posixpath
import re
import shutil
from dataclasses import dataclass, field
from pathlib import Path
from pydantic import BaseModel, Field, field_validator
from .. import llm
from ..docker import run_in_container
from ..grading import project_image, python_verifier_files
from ..llm import ask
from ..mutants import make_mutants
from ..paths import relative_path, within
from ..task import AGENT_TOOLS, Family, Reject, Trial, task_toml, write_files
from ..trajectory import Trajectory
MINIMUM_TESTS, MINIMUM_MUTANT_KILL_RATE = 6, 0.6
CALIBRATION_SCRIPT = Path(__file__).resolve().parents[1] / "assets" / "calibrate.py"
NON_PYTHON_SOURCE = re.compile(r"\.(js|ts|tsx|jsx|go|rs)$")
PYTHON_CHECK = re.compile(r"\b(pytest|unittest|python3?\s+\S+\.py)")
SYSTEM_PROMPT = """You write hidden tests for a build-from-spec RL task.
A fresh agent receives only the user's request and your interface contract, and builds the
project from scratch in {root}. Your tests grade it with partial credit. You are shown a
reference implementation that satisfied the request.
1. contract: markdown with the minimum public interface the tests need: file/module paths
(relative to {root}), signatures with types, CLI usage, input/output formats, exit codes.
Anything a test asserts must be pinned down here or in the request.
2. stub_files: files with the contract's signatures and no behaviour (raise
NotImplementedError; CLI entry points print nothing and exit 1).
3. tests: one pytest module with 12-20 independent `test_*` functions checking behaviour the
request asks for, through the contract only. Locate code with
WS = os.environ.get("WORKSPACE", "{root}") on sys.path (and WS/src for a src layout); run CLIs
with subprocess and sys.executable, cwd=WS, timeout=60. Use tmp_path, no network, standard
library + pytest only, deterministic. Test what the request requires, not incidental choices
(help text, log wording). For error cases assert on more than the exit code."""
DOCKERFILE = (
"""FROM python:3.12-bookworm
"""
+ AGENT_TOOLS
+ """
RUN pip install --no-cache-dir pytest==8.4.2 pytest-timeout==2.4.0
ENV WORKSPACE={root}
WORKDIR {root}
"""
)
INSTRUCTION = """Build the following project from scratch in `{root}` (it is currently empty).
## Request
{request}
## Interface contract
Hidden tests use only this interface, so follow it exactly. Everything else is up to you.
{contract}
## Environment
Python 3.12, standard library only (pytest is installed). No internet. Each hidden test passed earns partial credit.
"""
class GeneratedFile(BaseModel):
path: str = Field(description="path relative to the project root")
content: str
_safe_path = field_validator("path")(relative_path)
class GeneratedTests(BaseModel):
contract: str
stub_files: list[GeneratedFile]
tests: str = Field(description="a single pytest module, test_hidden.py")
@dataclass
class BuildCandidate:
trajectory: Trajectory
project_root: str
request: str
reference_files: dict[str, str] # relative path -> content
generated: GeneratedTests | None = None
kept_tests: set[str] = field(default_factory=set)
mutant_kill_rate: float = 0.0
def keep_only_tests(test_module: str, kept_test_names: set[str]) -> str:
"""Remove test functions (and TestClass methods) whose pytest name isn't kept."""
tree = ast.parse(test_module)
kept_functions = {name.split("[", 1)[0] for name in kept_test_names}
def filter_body(body: list[ast.stmt], prefix: str = "") -> list[ast.stmt]:
kept = []
for node in body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name.startswith(
"test"
):
if prefix + node.name in kept_functions:
kept.append(node)
elif isinstance(node, ast.ClassDef) and node.name.startswith("Test"):
node.body = filter_body(node.body, node.name + "::") or [ast.Pass()]
kept.append(node)
else:
kept.append(node)
return kept
tree.body = filter_body(tree.body)
return ast.unparse(ast.fix_missing_locations(tree)) + "\n"
class Build(Family):
name = "build"
def find_candidates(self, trajectory: Trajectory) -> list[BuildCandidate]:
"""A self-contained Python project, finished (its last check passing) within the first request."""
user_messages = trajectory.user_messages()
if not user_messages:
return []
second_request = user_messages[1][0] if len(user_messages) > 1 else None
runs, filesystem = trajectory.replay(until_step=second_request)
python_files = [path for path in filesystem.files if path.endswith(".py")]
checks = [run for run in runs if PYTHON_CHECK.search(run.command)]
if (
len(python_files) < 2
or filesystem.lost_files
or not checks
or checks[-1].exit_code != 0
):
return []
root = posixpath.commonpath([posixpath.dirname(path) for path in python_files])
root = next((run.cwd for run in runs if run.cwd and root.startswith(run.cwd)), root)
files = {
posixpath.relpath(path, root): content
for path, content in filesystem.files.items()
if path.startswith(root + "/")
}
if any(NON_PYTHON_SOURCE.search(path) for path in files):
return []
return [BuildCandidate(trajectory, root, user_messages[0][1], files)]
def task_id(self, c: BuildCandidate) -> str:
return f"{c.trajectory.short_id()}-build"
def prepare(self, c: BuildCandidate) -> None:
reference = "\n\n".join(
f"### {path}\n```\n{content}\n```"
for path, content in sorted(c.reference_files.items())
)
if len(reference) + len(c.request) > 150_000:
raise Reject("project_too_large")
c.generated = ask(
SYSTEM_PROMPT.format(root=c.project_root),
f"<request>\n{c.request}\n</request>\n\n<reference>\n{reference}\n</reference>",
GeneratedTests,
)
if c.generated is None:
raise Reject("llm_declined")
def environment_files(self, c: BuildCandidate) -> dict[str, str]:
return {
"Dockerfile": DOCKERFILE.format(root=c.project_root) + project_image(c.project_root)
}
def check_in_image(self, c: BuildCandidate, image: str, scratch_dir: Path) -> None:
"""Run the candidate tests on the reference, the stub, an empty workspace and mutants."""
variants = {
"reference": c.reference_files,
"reference_again": c.reference_files,
"stub": self.stub_files(c),
"empty": {},
}
variants |= {
f"mutant_{index:02d}": files
for index, files in enumerate(make_mutants(c.reference_files))
}
for variant_name, files in variants.items():
(scratch_dir / "variants" / variant_name).mkdir(parents=True)
write_files(scratch_dir / "variants" / variant_name, files)
write_files(scratch_dir, {"test_hidden.py": c.generated.tests})
shutil.copy(CALIBRATION_SCRIPT, scratch_dir / "calibrate.py")
run_in_container(
image,
"python /calibration/calibrate.py",
{scratch_dir: "/calibration"},
timeout_seconds=3600,
)
results_file = within(scratch_dir, "results.json")
if not results_file.exists():
raise Reject("calibration_failed")
outcomes = json.loads(results_file.read_text()) # {variant: {test name: outcome}}
def passes(variant: str, test: str) -> bool:
return outcomes.get(variant, {}).get(test) == "passed"
all_tests = outcomes.get("reference", {})
c.kept_tests = {
test
for test in all_tests
if passes("reference", test)
and passes("reference_again", test)
and not passes("stub", test)
and not passes("empty", test)
}
mutants = [variant for variant in outcomes if variant.startswith("mutant_")]
caught = [
mutant for mutant in mutants if any(not passes(mutant, test) for test in c.kept_tests)
]
c.mutant_kill_rate = round(len(caught) / max(len(mutants), 1), 3)
if len(c.kept_tests) < MINIMUM_TESTS or c.mutant_kill_rate < MINIMUM_MUTANT_KILL_RATE:
raise Reject(
"weak_tests",
{"kept_tests": len(c.kept_tests), "mutant_kill_rate": c.mutant_kill_rate},
)
def stub_files(self, c: BuildCandidate) -> dict[str, str]:
return {file.path: file.content for file in c.generated.stub_files}
def task_files(self, c: BuildCandidate) -> dict[str, str]:
return {
"instruction.md": INSTRUCTION.format(
root=c.project_root, request=c.request, contract=c.generated.contract.strip()
),
**python_verifier_files(
keep_only_tests(c.generated.tests, c.kept_tests), c.kept_tests, set()
),
"solution/solve.sh": f"#!/usr/bin/env bash\nset -e\n# The original agent's implementation.\ncp -a /solution/files/. {c.project_root}/\n",
**{f"solution/files/{path}": content for path, content in c.reference_files.items()},
"task.toml": task_toml(
self.name,
self.task_id(c),
c.request,
{
"source_trace": c.trajectory.source,
"source_model": c.trajectory.model,
"hidden_tests": len(c.kept_tests),
"mutant_kill_rate": c.mutant_kill_rate,
"tests_written_by": llm.MODEL,
},
agent_timeout_sec=1800.0,
),
}
def trials(self, c: BuildCandidate, scratch_dir: Path) -> tuple[list[Trial], dict]:
stub_dir = scratch_dir / "trial_stub"
write_files(
stub_dir, self.stub_files(c)
) # mounted for the trial only: never shipped with the task
return [
Trial("reference", "bash /solution/solve.sh", "1.0000"),
Trial("stub", f"cp -a /stub/. {c.project_root}/", "0.0000"),
Trial("empty_workspace", "true", "0.0000"),
], {stub_dir: "/stub:ro"}
def summary(self, c: BuildCandidate) -> dict:
return {
"request": c.request[:200],
"hidden_tests": len(c.kept_tests),
"mutant_kill_rate": c.mutant_kill_rate,
}pipelines/trajectory/families/extend.py
Source: src/repo2rlenv/pipelines/trajectory/families/extend.py · SHA-256 90af68701df6c257d03e63a45882e389623a8513797befb3811f8750f8597624
Source hash covers the original file; trailing whitespace is omitted below.
Read pipelines/trajectory/families/extend.py
"""extend: implement the user's next request in the project the agent had built so far.
The task starts from the files at the end of request k (dependencies installed) and gives the
agent request k+1. The reference is the agent's project at the end of request k+1, whose last
Python check passed. The LLM writes a minimal contract and candidate tests; calibration in the
image sorts them like SWE-bench: a "new" test passes on the reference (twice) and fails on the
start state; an "existing" test passes on both. Kept tests must catch most mutants of the changed
code. Reward = fraction of new tests passed, or 0 if any existing test fails.
"""
from __future__ import annotations
import json
import posixpath
import shlex
import shutil
from dataclasses import dataclass, field
from pathlib import Path
from pydantic import BaseModel, Field
from .. import llm
from ..docker import run_in_container
from ..grading import project_image, python_verifier_files
from ..llm import ask
from ..mutants import make_mutants
from ..paths import within
from ..task import AGENT_TOOLS, Family, Reject, Trial, task_toml, write_files
from ..trajectory import Trajectory
from .build import NON_PYTHON_SOURCE, PYTHON_CHECK, keep_only_tests
from .repair import INSTALL_COMMAND, SCAFFOLD_COMMAND, SETUP_COMMAND, TEST_FILE
MINIMUM_NEW_TESTS, MINIMUM_MUTANT_KILL_RATE = 5, 0.5
MAXIMUM_PROMPT_CHARS = 150_000
CALIBRATION_SCRIPT = Path(__file__).resolve().parents[1] / "assets" / "calibrate.py"
SYSTEM_PROMPT = """You write hidden tests for a feature-request RL task.
An agent receives an existing Python project in {root} (shown as <before>), the user's earlier
requests, and the user's next request, which it must implement. You are shown how the original
agent implemented it (<after>: the files it changed or added). Write:
1. contract: markdown with only the interface details your tests rely on that the request does
not already fix: new module/file paths, function and class names with signatures, CLI flags,
input/output formats. Do not describe the implementation. Keep it short; it may be empty if
the tests only use the existing interface and the request's own wording. Anything a test
asserts (message substrings, keys, exit codes) must be pinned down here or in the request.
2. tests: one pytest module with 10-20 `test_*` functions checking the behaviour the next request
asks for, plus 2-5 `test_existing_*` functions checking behaviour the project already had and
must keep. Use the contract and the existing public interface only. Locate code with
WS = os.environ.get("WORKSPACE", "{root}") on sys.path (and WS/src for a src layout); run CLIs
with subprocess and sys.executable, cwd=WS, timeout=60. Import the project inside each test
(or a helper it calls), never at module level: a name the agent got wrong must fail only the
tests that use it, and the test_existing_* tests must run on the project as it was before.
Use tmp_path, no network, standard library + pytest + the project's own dependencies only,
deterministic. Test what the request requires, not incidental choices (help text, log
wording, private helpers)."""
DOCKERFILE_HEAD = [
"FROM python:3.12-bookworm",
AGENT_TOOLS,
"RUN pip install --no-cache-dir pytest==8.4.2 pytest-timeout==2.4.0",
]
INSTRUCTION = """You are working on an existing Python project in `{root}`.
## Earlier requests (already implemented)
{earlier_requests}
## Next request
{request}
## Interface notes
Hidden tests check the new behaviour through this interface (and the project's existing one), and
check that existing behaviour still works. Follow these names exactly; everything else is up to you.
{contract}
## Environment
Python 3.12 with the project's dependencies installed (pytest too). No internet. Each new-behaviour
test passed earns partial credit; breaking existing behaviour scores 0.
"""
class GeneratedTests(BaseModel):
contract: str
tests: str = Field(description="a single pytest module, test_hidden.py")
@dataclass
class ExtendCandidate:
trajectory: Trajectory
request_index: int # index (in trajectory.user_messages()) of the request to implement
project_root: str
files_before: dict[str, str] # relative path -> content, at the end of the previous request
files_after: dict[str, str] # ... at the end of this request (the reference)
setup_commands: list[tuple[str, str | None]]
generated: GeneratedTests | None = None
new_tests: set[str] = field(default_factory=set)
existing_tests: set[str] = field(default_factory=set)
mutant_kill_rate: float | None = None
@property
def request(self) -> str:
return self.trajectory.user_messages()[self.request_index][1]
@property
def changed_files(self) -> list[str]:
return sorted(
path
for path in set(self.files_before) | set(self.files_after)
if self.files_before.get(path) != self.files_after.get(path)
)
def project_files(root: str, files: dict[str, str]) -> dict[str, str]:
return {
posixpath.relpath(path, root): content
for path, content in files.items()
if path.startswith(root + "/")
}
def render_files(files: dict[str, str]) -> str:
return "\n\n".join(
f"### {path}\n```\n{content}\n```" for path, content in sorted(files.items())
)
class Extend(Family):
name = "extend"
def find_candidates(self, trajectory: Trajectory) -> list[ExtendCandidate]:
"""Each later request whose Python project existed before it and passed its checks after it."""
user_messages = trajectory.user_messages()
candidates = []
for index in range(1, len(user_messages)):
start_step = user_messages[index][0]
end_step = user_messages[index + 1][0] if index + 1 < len(user_messages) else None
runs_before, fs_before = trajectory.replay(until_step=start_step)
runs_after, fs_after = trajectory.replay(until_step=end_step)
checks = [
run for run in runs_after[len(runs_before) :] if PYTHON_CHECK.search(run.command)
]
python_files = [path for path in fs_after.files if path.endswith(".py")]
if (
fs_after.lost_files
or not checks
or checks[-1].exit_code != 0
or len(python_files) < 2
):
continue
root = posixpath.commonpath([posixpath.dirname(path) for path in python_files])
root = next(
(run.cwd for run in runs_after if run.cwd and root.startswith(run.cwd)), root
)
before, after = (
project_files(root, fs_before.files),
project_files(root, fs_after.files),
)
if (
sum(path.endswith(".py") for path in before) < 2
or any(NON_PYTHON_SOURCE.search(path) for path in after)
or any(path.startswith(root + "/") for path in fs_before.lost_files)
or not any(
path.endswith(".py")
and not TEST_FILE.search(path)
and before.get(path) != after.get(path)
for path in after
)
):
continue # no existing Python project, not Python, or no source change ("add tests for ...")
setup = [
(run.command, run.cwd)
for run in runs_before
if run.exit_code == 0 and SETUP_COMMAND.search(run.command)
]
setup += [
(run.command, run.cwd)
for run in runs_after[len(runs_before) :]
if run.exit_code == 0 and INSTALL_COMMAND.search(run.command)
] # offline: preinstall what it added
candidates.append(ExtendCandidate(trajectory, index, root, before, after, setup))
return candidates
def task_id(self, c: ExtendCandidate) -> str:
return f"{c.trajectory.short_id()}-extend-{c.request_index + 1}"
def prepare(self, c: ExtendCandidate) -> None:
changed = {path: c.files_after[path] for path in c.changed_files if path in c.files_after}
deleted = [path for path in c.changed_files if path not in c.files_after]
earlier = "\n\n".join(text for _, text in c.trajectory.user_messages()[: c.request_index])
prompt = (
f"<earlier_requests>\n{earlier}\n</earlier_requests>\n\n<next_request>\n{c.request}\n</next_request>\n\n"
f"<before>\n{render_files(c.files_before)}\n</before>\n\n<after>\n{render_files(changed)}\n"
f"{'Deleted: ' + ', '.join(deleted) if deleted else ''}\n</after>"
)
if len(prompt) > MAXIMUM_PROMPT_CHARS:
raise Reject("project_too_large", len(prompt))
c.generated = ask(SYSTEM_PROMPT.format(root=c.project_root), prompt, GeneratedTests)
if c.generated is None:
raise Reject("llm_declined")
def environment_files(self, c: ExtendCandidate) -> dict[str, str]:
def run_step(command: str, cwd: str) -> str:
return f"RUN mkdir -p {shlex.quote(cwd)} && cd {shlex.quote(cwd)} && bash -lc {shlex.quote(command)}"
dockerfile = [
*DOCKERFILE_HEAD,
f"ENV WORKSPACE={c.project_root}",
f"WORKDIR {c.project_root}",
*[
run_step(command, cwd or posixpath.dirname(c.project_root))
for command, cwd in c.setup_commands
if SCAFFOLD_COMMAND.search(command)
],
f"COPY before/ {c.project_root}/",
*[
run_step(command, cwd or c.project_root)
for command, cwd in c.setup_commands
if not SCAFFOLD_COMMAND.search(command)
],
f"COPY before/ {c.project_root}/", # installs must not rewrite the starting code
]
return {
"Dockerfile": "\n".join(dockerfile) + "\n" + project_image(c.project_root),
**{f"before/{path}": content for path, content in c.files_before.items()},
}
def check_in_image(self, c: ExtendCandidate, image: str, scratch_dir: Path) -> None:
"""Sort candidate tests into new (fail-to-pass) and existing (pass-to-pass); check they catch mutants."""
changed_python = {
path: c.files_after[path]
for path in c.changed_files
if path in c.files_after and path.endswith(".py")
}
variants = {"after": c.files_after, "after_again": c.files_after, "before": c.files_before}
variants |= {
f"mutant_{index:02d}": {**c.files_after, **mutant}
for index, mutant in enumerate(make_mutants(changed_python))
}
for variant_name, files in variants.items():
(scratch_dir / "variants" / variant_name).mkdir(parents=True)
write_files(scratch_dir / "variants" / variant_name, files)
write_files(
scratch_dir,
{
"test_hidden.py": c.generated.tests,
"known_files.json": json.dumps(sorted(set(c.files_before) | set(c.files_after))),
},
)
shutil.copy(CALIBRATION_SCRIPT, scratch_dir / "calibrate.py")
run_in_container(
image,
"python /calibration/calibrate.py",
{scratch_dir: "/calibration"},
timeout_seconds=3600,
)
results_file = within(scratch_dir, "results.json")
if not results_file.exists():
raise Reject("calibration_failed")
outcomes = json.loads(results_file.read_text()) # {variant: {test name: outcome}}
def passes(variant: str, test: str) -> bool:
return outcomes.get(variant, {}).get(test) == "passed"
stable = {
test
for test in outcomes.get("after", {})
if passes("after", test) and passes("after_again", test)
}
if not stable <= set(
outcomes.get("before", {})
): # the module itself failed to load before the request
raise Reject(
"tests_not_collected_before", sorted(stable - set(outcomes.get("before", {})))[:3]
)
c.new_tests = {test for test in stable if not passes("before", test)}
c.existing_tests = stable - c.new_tests
mutants = [variant for variant in outcomes if variant.startswith("mutant_")]
caught = [
mutant
for mutant in mutants
if any(not passes(mutant, test) for test in c.new_tests | c.existing_tests)
]
c.mutant_kill_rate = round(len(caught) / len(mutants), 3) if mutants else None
if len(c.new_tests) < MINIMUM_NEW_TESTS or (
c.mutant_kill_rate is not None and c.mutant_kill_rate < MINIMUM_MUTANT_KILL_RATE
):
raise Reject(
"weak_tests",
{
"new_tests": len(c.new_tests),
"existing_tests": len(c.existing_tests),
"mutant_kill_rate": c.mutant_kill_rate,
},
)
def task_files(self, c: ExtendCandidate) -> dict[str, str]:
root = shlex.quote(c.project_root)
deleted = [path for path in c.changed_files if path not in c.files_after]
earlier = [
f"> {' '.join(text[:600].split())}"
for _, text in c.trajectory.user_messages()[: c.request_index]
]
solve_sh = (
"#!/usr/bin/env bash\nset -e\n# The original agent's implementation of the request.\n"
f"cp -a /solution/files/. {root}/\n"
+ "".join(
f"rm -f {shlex.quote(posixpath.join(c.project_root, path))}\n" for path in deleted
)
)
return {
"instruction.md": INSTRUCTION.format(
root=c.project_root,
earlier_requests="\n>\n".join(earlier[-4:]),
request=c.request,
contract=c.generated.contract.strip() or "(none)",
),
**python_verifier_files(
keep_only_tests(c.generated.tests, c.new_tests | c.existing_tests),
c.new_tests,
c.existing_tests,
),
"tests/grading.json": json.dumps(
{"new": sorted(c.new_tests), "existing": sorted(c.existing_tests)}, indent=1
),
"solution/solve.sh": solve_sh,
**{
f"solution/files/{path}": c.files_after[path]
for path in c.changed_files
if path in c.files_after
},
"task.toml": task_toml(
self.name,
self.task_id(c),
c.request,
{
"source_trace": c.trajectory.source,
"source_model": c.trajectory.model,
"request_index": c.request_index,
"changed_files": c.changed_files,
"new_tests": len(c.new_tests),
"existing_tests": len(c.existing_tests),
"mutant_kill_rate": c.mutant_kill_rate,
"tests_written_by": llm.MODEL,
},
cpus=2,
memory_mb=4096,
agent_timeout_sec=2400.0,
),
}
def trials(self, c: ExtendCandidate, scratch_dir: Path) -> tuple[list[Trial], dict]:
return [
Trial("reference", "bash /solution/solve.sh", "1.0000"),
Trial("reference_again", "bash /solution/solve.sh", "1.0000"),
Trial("do_nothing", "true", "0.0000"),
Trial("delete_project", f"rm -rf {shlex.quote(c.project_root)}/*", "0.0000"),
], {}
def summary(self, c: ExtendCandidate) -> dict:
return {
"request": c.request[:200],
"new_tests": len(c.new_tests),
"existing_tests": len(c.existing_tests),
"mutant_kill_rate": c.mutant_kill_rate,
}pipelines/trajectory/families/qa.py
Source: src/repo2rlenv/pipelines/trajectory/families/qa.py · SHA-256 7dffda2ea82df7dc51b0a01d1ce71521f48ecec1389513648c8e9e6fb3a210c4
Source hash covers the original file; trailing whitespace is omitted below.
Read pipelines/trajectory/families/qa.py
"""qa: a question whose answer the agent computed from public Hugging Face data.
Claude proposes questions grounded in one tool output. Kept only if the gold answer appears
verbatim in that output, the question doesn't contain it, every input file resolves to the
dataset commit current at the trajectory's date, and in Docker the reference solution scores
1.0 while a wrong or missing answer scores 0.0 (deterministic grader, no LLM judge).
"""
from __future__ import annotations
import hashlib
import json
import re
import shutil
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Literal
from pydantic import BaseModel, field_validator
from repo2rlenv.pipelines.pr_runtime import separate_head, separate_verifier_files
from ..llm import ask
from ..paths import relative_path, within
from ..task import AGENT_TOOLS, Family, Reject, Trial, task_toml
from ..trajectory import Trajectory
GRADER = Path(__file__).resolve().parents[1] / "assets" / "grader.py"
INPUT_DIR = "/home/user/input"
SYSTEM_PROMPT = """You turn recorded agent trajectories into data-analysis RL tasks. Each task stages the
input files in /home/user/input, asks one question, and grades a single value by exact/numeric match.
Propose 1-3 tasks. Each must satisfy ALL of these:
- The gold answer appears verbatim in one tool call's output (cite step_id, call_id, an exact quote).
- Answerable from the staged files alone: no internet, no Hub metadata (downloads, likes, sizes).
- Unambiguous: spell out definitions that matter (split, empty vs NULL, rounding). No facts that
depend on the original agent's own heuristics (custom regexes, keyword lists).
- The question does not contain or hint at the answer.
- Inputs are public Hugging Face dataset files at the repo/revision/path the agent used; the
'/api/datasets/<id>/parquet/<config>/<split>/0.parquet' endpoint is revision 'refs/convert/parquet',
path '<config>/<split>/0000.parquet'.
- reference_solution reads os.environ['INPUT_DIR'] with pandas or duckdb and prints only the answer.
Return no tasks if the trajectory has no usable grounded fact."""
# Pinned: an unpinned image drifts (a newer duckdb broke reference solutions written against 1.x).
DOCKERFILE = f"""FROM python:3.12-slim
{AGENT_TOOLS}
RUN pip install --no-cache-dir pandas==2.2.3 numpy==2.1.3 scipy==1.14.1 pyarrow==18.1.0 duckdb==1.1.3 huggingface_hub==0.30.2
COPY pull_inputs.py inputs.json /opt/
RUN python3 /opt/pull_inputs.py
WORKDIR /workdir
"""
PULL_INPUTS = '''"""Stage pinned input files during image construction; execution stays offline."""
import json
import shutil
from pathlib import Path
from huggingface_hub import hf_hub_download
destination = Path("/home/user/input")
destination.mkdir(parents=True, exist_ok=True)
for file in json.loads(Path("/opt/inputs.json").read_text()):
if not (destination / file["local_name"]).exists():
local = hf_hub_download(file["repo_id"], file["path_in_repo"], repo_type="dataset", revision=file["commit"])
shutil.copyfile(local, destination / file["local_name"])
'''
TEST_SH = (
separate_head(None)
+ """
[ -f /workdir/answer.txt ] || r2e_finish graded missing_answer 'no answer submitted'
status="$("$R2E_PY" -B -I -S /tests/grader_tools.py check --path /workdir/answer.txt --max-bytes 65536)"
[ "$?" -eq 0 ] && [ "$status" = ok ] || r2e_finish graded invalid_answer 'missing or unsafe answer'
"$R2E_PY" -B -I -S /tests/grader.py < /workdir/answer.txt > /logs/verifier/reward.txt
[ "$?" -eq 0 ] || r2e_finish ungraded grader_error 'answer grader failed'
r2e_open_logs
"""
)
SOLVE_SH = f"""#!/usr/bin/env bash
# The reference solution, which reproduced the gold answer on the pinned inputs.
INPUT_DIR={INPUT_DIR} python3 /solution/solve.py | tail -n 1 | tr -d '\\n' > /workdir/answer.txt
"""
INSTRUCTION = """You are a data-analysis agent working in a sandbox. Use your code-execution tool to inspect the files and compute the answer.
Files (in /home/user/input, no subfolders):
{files}
Installed Python packages (use python3): pandas, numpy, scipy, pyarrow, duckdb. There is no duckdb command-line tool.
Question:
{question}
Answer with a single clean value: a bare number (no commas or units), a short label, yes/no, or a comma-separated list. Keep decimal precision.
Write only that value to /workdir/answer.txt (e.g. `echo -n "<value>" > /workdir/answer.txt`), then stop."""
class InputFile(BaseModel):
repo_id: str
revision: str
path_in_repo: str
local_name: str
@field_validator("local_name")
@classmethod
def safe_local_name(cls, value: str) -> str:
relative_path(value)
if "/" in value:
raise ValueError("QA inputs must be single filenames")
return value
class ProposedQuestion(BaseModel):
question: str
gold_answer: str
answer_kind: Literal["number", "label", "list", "yes_no"]
evidence_step_id: int
evidence_call_id: str
evidence_quote: str
inputs: list[InputFile]
reference_solution: str
class ProposedQuestions(BaseModel):
tasks: list[ProposedQuestion]
@dataclass
class QACandidate:
trajectory: Trajectory
proposal: ProposedQuestion
pinned_inputs: list[dict] = field(default_factory=list) # input + "commit" + "downloaded_path"
def normalize(text: str) -> str:
return " ".join(text.replace(",", "").lower().split())
def render_for_llm(trajectory: Trajectory, max_output_chars: int = 6000) -> str:
sections = []
for step in trajectory.steps:
if step["source"] == "user":
sections.append(f"### step {step['step_id']} USER\n{step.get('message', '')}")
elif step["source"] == "agent":
outputs = {
r["source_call_id"]: r["content"]
for r in (step.get("observation") or {}).get("results", [])
}
sections.append(f"### step {step['step_id']} AGENT\n{step.get('message', '')}")
for call in step.get("tool_calls", []):
sections.append(
f"--- call {call['tool_call_id']} {call['function_name']}\n{json.dumps(call['arguments'])[:3000]}\n"
f"--- output\n{outputs.get(call['tool_call_id'], '')[:max_output_chars]}"
)
return "\n\n".join(sections)
def cited_output(trajectory: Trajectory, step_id: int, call_id: str) -> str:
step = next((s for s in trajectory.steps if s["step_id"] == step_id), {})
results = (step.get("observation") or {}).get("results", [])
return next((r["content"] for r in results if r["source_call_id"] == call_id), "")
def pin_to_commit_at(input_file: InputFile, when: datetime) -> dict:
"""Resolve an input to the last commit on its revision at `when`, and download it."""
from huggingface_hub import HfApi, hf_hub_download
commits = HfApi().list_repo_commits(
input_file.repo_id, repo_type="dataset", revision=input_file.revision
)
eligible = [c for c in commits if c.created_at <= when]
if not eligible:
raise ValueError("No dataset commit exists at the trajectory date")
commit = eligible[0].commit_id # newest first
downloaded = hf_hub_download(
input_file.repo_id, input_file.path_in_repo, repo_type="dataset", revision=commit
)
return {**input_file.model_dump(), "commit": commit, "downloaded_path": downloaded}
class QA(Family):
name = "qa"
def find_candidates(self, trajectory: Trajectory) -> list[QACandidate]:
proposals = ask(
SYSTEM_PROMPT,
f"<trajectory>\n{render_for_llm(trajectory)}\n</trajectory>",
ProposedQuestions,
)
return [
QACandidate(trajectory, proposal) for proposal in (proposals.tasks if proposals else [])
]
def task_id(self, c: QACandidate) -> str:
return hashlib.sha256(f"{c.trajectory.source}|{c.proposal.question}".encode()).hexdigest()[
:12
]
def prepare(self, c: QACandidate) -> None:
p = c.proposal
output = cited_output(c.trajectory, p.evidence_step_id, p.evidence_call_id)
answer_parts = p.gold_answer.split(",") if p.answer_kind == "list" else [p.gold_answer]
if p.evidence_quote not in output or not all(
normalize(part) in normalize(p.evidence_quote) for part in answer_parts
):
raise Reject("answer_not_in_cited_output")
if re.search(
rf"(?<![\w.]){re.escape(normalize(p.gold_answer))}(?![\w.])", normalize(p.question)
):
raise Reject("answer_in_question")
first_timestamp = next(
(s["timestamp"] for s in c.trajectory.steps if s.get("timestamp")),
None,
)
if first_timestamp is None:
raise Reject("missing_trajectory_date")
when = datetime.fromisoformat(first_timestamp.replace("Z", "+00:00"))
if when.tzinfo is None:
raise Reject("missing_trajectory_timezone")
if not p.inputs or len({f.local_name for f in p.inputs}) != len(p.inputs):
raise Reject("invalid_inputs", "Need inputs with distinct local filenames")
try:
c.pinned_inputs = [pin_to_commit_at(input_file, when) for input_file in p.inputs]
except Exception as error:
raise Reject("input_not_resolvable", type(error).__name__) from error
def environment_files(self, c: QACandidate) -> dict[str, str]:
inputs_json = [
{key: f[key] for key in ("repo_id", "path_in_repo", "commit", "local_name")}
for f in c.pinned_inputs
]
return {
"Dockerfile": DOCKERFILE,
"pull_inputs.py": PULL_INPUTS,
"inputs.json": json.dumps(inputs_json, indent=1),
}
def verifier_env(self, c: QACandidate) -> dict[str, str]:
reward_mode = "strict_" + c.proposal.answer_kind
return {
"EXPECTED_ANSWER": c.proposal.gold_answer,
"QUESTION": c.proposal.question,
"REWARD_MODE": reward_mode,
"ATOL": "0.0",
"RTOL": "0.0",
}
def task_files(self, c: QACandidate) -> dict[str, str]:
p = c.proposal
return {
"instruction.md": INSTRUCTION.format(
files="\n".join(f"- {f['local_name']}" for f in c.pinned_inputs),
question=p.question,
),
"tests/test.sh": TEST_SH,
**separate_verifier_files(),
"tests/grader.py": GRADER.read_text(),
"tests/UPSTREAM_LICENSE": GRADER.with_name("UPSTREAM_LICENSE").read_text(),
"solution/solve.py": p.reference_solution,
"solution/solve.sh": SOLVE_SH,
"task.toml": task_toml(
self.name,
self.task_id(c),
p.question,
{
"source_trace": c.trajectory.source,
"source_model": c.trajectory.model,
"gold_answer": p.gold_answer,
"answer_kind": p.answer_kind,
"evidence_step_id": p.evidence_step_id,
"evidence_call_id": p.evidence_call_id,
"input_commits": [f["commit"] for f in c.pinned_inputs],
},
verifier_env=self.verifier_env(c),
allow_internet=False,
),
}
def trials(self, c: QACandidate, scratch_dir: Path) -> tuple[list[Trial], dict]:
# Reuse the pinned download for controls without a second runtime fetch.
staged_inputs = scratch_dir / "inputs"
staged_inputs.mkdir()
for f in c.pinned_inputs:
shutil.copyfile(f["downloaded_path"], within(staged_inputs, f["local_name"]))
wrong_answer = (
"-987654321" if c.proposal.answer_kind == "number" else "certainly not the answer"
)
return [
Trial("reference_solution", "mkdir -p /workdir && bash /solution/solve.sh", "1.0"),
Trial(
"wrong_answer",
f"mkdir -p /workdir && echo -n '{wrong_answer}' > /workdir/answer.txt",
"0.0",
),
Trial("no_answer", "mkdir -p /workdir", "0.0"),
], {staged_inputs: f"{INPUT_DIR}:ro"}
def summary(self, c: QACandidate) -> dict:
return {"question": c.proposal.question, "gold_answer": c.proposal.gold_answer}pipelines/trajectory/llm.py
Source: src/repo2rlenv/pipelines/trajectory/llm.py · SHA-256 855a269302f423f4ab670c338c0110ba108063eba2d1cac0e9e4ebddeff3b154
Source hash covers the original file; trailing whitespace is omitted below.
Read pipelines/trajectory/llm.py
"""The one LLM call the qa, build and extend families make: a structured-output request to a model.
`TrajectoryPipeline.__init__` calls `configure` with the generation input's `llm` and the
pipeline options (`max_llm_tokens`, `reasoning_effort`, `llm_cache_dir`, `max_llm_spend_usd`);
the call goes through repo2rlenv's LiteLLM client, so any provider it supports works.
Spend is the sum of `LLMResponse.cost_usd` over the calls this run made; cached replies are free.
Once it reaches the budget, `ask` raises BudgetExceeded before calling the model. Calls already
in flight still finish, so a run can overshoot by up to `jobs` calls.
The model only proposes (questions, contracts, tests); nothing it writes ships without passing
the checks in Docker. Responses are cached on disk, so re-running the pipeline is free and stable.
"""
from __future__ import annotations
import hashlib
import json
import threading
from pathlib import Path
import pydantic
from repo2rlenv.llm import complete
from repo2rlenv.spec.input import LLMSpec
SPEC: LLMSpec | None = None
MODEL = "none" # recorded in task metadata (tests_written_by); set with SPEC
CACHE_DIR = Path("workspace/cache/trajectory_to_env/llm")
# Reasoning models count their thinking against max_tokens: too small a budget ends in an empty answer.
MAX_OUTPUT_TOKENS = 32000
REASONING_EFFORT: str | None = None
BUDGET_USD: float | None = None # None: unlimited
SPENT_USD = 0.0
_SPEND_LOCK = threading.Lock()
class BudgetExceeded(Exception):
pass
def configure(
spec: LLMSpec | None,
*,
max_tokens: int = MAX_OUTPUT_TOKENS,
reasoning_effort: str | None = None,
cache_dir: Path = CACHE_DIR,
budget_usd: float | None = None,
) -> None:
global SPEC, MODEL, MAX_OUTPUT_TOKENS, REASONING_EFFORT, CACHE_DIR, BUDGET_USD, SPENT_USD
SPEC, MODEL = spec, spec.qualified_name if spec else "none"
MAX_OUTPUT_TOKENS, REASONING_EFFORT = max_tokens, reasoning_effort
CACHE_DIR = Path(cache_dir).expanduser()
BUDGET_USD, SPENT_USD = budget_usd, 0.0
def spent_usd() -> float:
with _SPEND_LOCK:
return SPENT_USD
def strict_schema(node):
"""Strict json_schema output requires additionalProperties: false on every object."""
if isinstance(node, dict):
if node.get("type") == "object":
node["additionalProperties"] = False
for value in node.values():
strict_schema(value)
elif isinstance(node, list):
for value in node:
strict_schema(value)
return node
def ask(system_prompt: str, user_prompt: str, response_schema):
"""Return a validated `response_schema` instance, or None if the model declined."""
if SPEC is None:
raise RuntimeError(
"this family needs an LLM: set `llm` in the generation config or pass --llm"
)
key = hashlib.sha256(
f"{MODEL}\n{response_schema.__name__}\n{system_prompt}\n{user_prompt}".encode()
).hexdigest()
cached = CACHE_DIR / f"{key}.json"
if cached.exists():
return response_schema.model_validate_json(cached.read_text())
global SPENT_USD
with _SPEND_LOCK:
if BUDGET_USD is not None and SPENT_USD >= BUDGET_USD:
raise BudgetExceeded(f"${SPENT_USD:.2f} spent, budget ${BUDGET_USD:.2f}")
response = complete(
SPEC,
system=system_prompt,
user=user_prompt,
max_tokens=MAX_OUTPUT_TOKENS,
reasoning_effort=REASONING_EFFORT,
response_schema=strict_schema(response_schema.model_json_schema()),
)
with _SPEND_LOCK:
SPENT_USD += response.cost_usd
content = (
response.content.strip().removeprefix("```json").removeprefix("```").removesuffix("```")
)
try:
parsed = response_schema.model_validate_json(content)
except pydantic.ValidationError as error:
# truncated, or a provider that ignores response_format: a decline
failure = {"usage": response.usage, "error": str(error)[:2000], "content": content}
(CACHE_DIR / "declined").mkdir(parents=True, exist_ok=True)
(
CACHE_DIR / "declined" / f"{hashlib.sha256(user_prompt.encode()).hexdigest()}.json"
).write_text(json.dumps(failure, default=str))
return None
CACHE_DIR.mkdir(parents=True, exist_ok=True)
cached.write_text(parsed.model_dump_json())
return parsed