diff --git a/docs/reference/SPEC.md b/docs/reference/SPEC.md index c85430b2..cf3b14f0 100644 --- a/docs/reference/SPEC.md +++ b/docs/reference/SPEC.md @@ -280,7 +280,7 @@ What deep validation deliberately does **not** do: - **Require `solution/`** without `--oracle`. Harbor solutions are optional. - **Check the executable bit.** Harbor `chmod +x`es scripts itself. - **Reject text-only `pr_diff` output** for lacking `environment/` and `tests/`. That's a supported shape. -- **Prove the task runs.** It's static: it can't tell whether the Dockerfile builds, whether a shell script's dependencies exist, or whether the patch applies at `base_commit`. Pre-v0.2 datasets without a reproducibility subtable, and non-Repo2RLEnv Harbor tasks, only get the checks for assets they actually ship; multi-step `[[steps]]` tasks skip the layout checks. `harbor run --agent oracle` remains the ground truth. +- **Prove the task runs.** It's static: it can't tell whether the Dockerfile builds, whether a shell script's dependencies exist, or whether the patch applies at `base_commit`. Pre-v0.2 datasets without a reproducibility subtable, and non-Repo2RLEnv Harbor tasks, only get the checks for assets they actually ship; multi-step `[[steps]]` tasks get per-step instruction, test-script and (with `--oracle`) solution checks, but no pipeline-specific verifier checks. `harbor run --agent oracle` remains the ground truth. ## Versioning diff --git a/src/repo2rlenv/emitter/harbor.py b/src/repo2rlenv/emitter/harbor.py index f382c82e..6891c971 100644 --- a/src/repo2rlenv/emitter/harbor.py +++ b/src/repo2rlenv/emitter/harbor.py @@ -9,6 +9,11 @@ also emits environment/Dockerfile + tests/test.sh and seeds the [metadata.repo2env.reproducibility] subtable. +A task with `steps` is a Harbor multi-step task: one `[[steps]]` entry per +step in task.toml, and steps// holding that step's instruction.md, +tests/ and solution/. The steps share one environment, so each step's oracle +patch applies on top of the earlier steps' patches. + ---------------------------------------------------------------------------- Acknowledgment ---------------------------------------------------------------------------- @@ -41,6 +46,27 @@ import tomli_w +# Harbor's portable step-name rule (`harbor.models.task.step_name`), narrowed +# to the characters every filesystem and shell handles without quoting. +_STEP_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") + + +@dataclass(slots=True) +class HarborStep: + """One step of a multi-step task, written to steps//.""" + + name: str + instruction: str + oracle_diff: str + test_script: str | None = None + # Extra files under steps// (relative path -> content), e.g. + # {"tests/f2p.json": ...}. Harbor exposes the step's tests/ at /tests. + aux_files: dict[str, str] = field(default_factory=dict) + # Harbor stops the trial after this step when its reward is below this. + min_reward: float | None = None + agent_timeout_sec: float = 1800.0 + verifier_timeout_sec: float = 300.0 + @dataclass(slots=True) class HarborTask: @@ -66,18 +92,96 @@ class HarborTask: # agent-container paths Harbor copies into that separate verifier. verifier: dict[str, Any] = field(default_factory=dict) artifacts: list[dict[str, Any]] = field(default_factory=list) + # Multi-step tasks only. With steps, the task-level instruction and + # oracle_diff must be empty: each step carries its own. A task-level + # test_script is Harbor's fallback for steps that ship no tests/. + steps: list[HarborStep] = field(default_factory=list) + # "mean" or "final"; Harbor defaults to "mean" for multi-step tasks. + multi_step_reward_strategy: str | None = None def _content_hash(task: HarborTask) -> str: h = hashlib.sha256() - h.update(task.instruction.encode("utf-8")) - h.update(b"\0") - h.update(task.oracle_diff.encode("utf-8")) + parts = [(s.instruction, s.oracle_diff) for s in task.steps] or [ + (task.instruction, task.oracle_diff) + ] + for index, (instruction, oracle_diff) in enumerate(parts): + if index: + h.update(b"\0\0") + h.update(instruction.encode("utf-8")) + h.update(b"\0") + h.update(oracle_diff.encode("utf-8")) return f"sha256:{h.hexdigest()}" +def _check_steps(task: HarborTask) -> None: + if task.instruction or task.oracle_diff: + raise ValueError("a multi-step task carries its instruction and oracle_diff per step") + if task.multi_step_reward_strategy not in (None, "mean", "final"): + raise ValueError( + f"multi_step_reward_strategy must be 'mean' or 'final', " + f"got {task.multi_step_reward_strategy!r}" + ) + seen: set[str] = set() + for step in task.steps: + if not _STEP_NAME_RE.fullmatch(step.name): + raise ValueError(f"step name must match {_STEP_NAME_RE.pattern}: {step.name!r}") + if step.name.lower() in seen: + raise ValueError(f"duplicate step name: {step.name!r}") + seen.add(step.name.lower()) + + +def _write_solution(sol_dir: Path, oracle_diff: str) -> None: + sol_dir.mkdir(parents=True, exist_ok=True) + # patch.diff is the canonical SWE-bench-style oracle (what trainers + # consume). solve.sh is the shim Harbor's oracle agent runs inside the + # container: Harbor uploads the solution dir to /solution, so the patch + # sits next to the script. + (sol_dir / "patch.diff").write_text(oracle_diff, encoding="utf-8") + (sol_dir / "solve.sh").write_text( + "#!/bin/bash\n" + "set -euxo pipefail\n" + "cd /workspace\n" + "git config --global --add safe.directory /workspace\n" + 'PATCH="$(dirname "$0")/patch.diff"\n' + 'git apply --verbose --reject "$PATCH"\n', + encoding="utf-8", + ) + (sol_dir / "solve.sh").chmod(0o755) + + +def _write_test_script(tests_dir: Path, test_script: str) -> None: + tests_dir.mkdir(parents=True, exist_ok=True) + (tests_dir / "test.sh").write_text(test_script, encoding="utf-8") + # mark executable; harbor expects test.sh to be runnable + (tests_dir / "test.sh").chmod(0o755) + + +def _write_aux_files(root: Path, aux_files: dict[str, str]) -> None: + for rel_path, content in aux_files.items(): + # Defensive: keep aux files inside the task dir. + target = (root / rel_path).resolve() + if not str(target).startswith(str(root.resolve())): + raise ValueError(f"aux_file path escapes task dir: {rel_path!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content, encoding="utf-8") + + +def _step_entry(step: HarborStep) -> dict[str, Any]: + entry: dict[str, Any] = { + "name": step.name, + "agent": {"timeout_sec": step.agent_timeout_sec}, + "verifier": {"timeout_sec": step.verifier_timeout_sec}, + } + if step.min_reward is not None: + entry["min_reward"] = step.min_reward + return entry + + def write_harbor_task(task: HarborTask, dest_dir: Path) -> Path: """Materialize the task directory at dest_dir/. Returns the path.""" + if task.steps: + _check_steps(task) task_path = dest_dir / task.name task_path.mkdir(parents=True, exist_ok=True) @@ -141,32 +245,26 @@ def write_harbor_task(task: HarborTask, dest_dir: Path) -> Path: } if task.artifacts: payload["artifacts"] = [dict(artifact) for artifact in task.artifacts] + if task.steps: + # Multi-step tasks use Harbor task schema 1.1. + payload["version"] = "1.1" + if task.multi_step_reward_strategy is not None: + payload["multi_step_reward_strategy"] = task.multi_step_reward_strategy + payload["steps"] = [_step_entry(step) for step in task.steps] (task_path / "task.toml").write_bytes(tomli_w.dumps(payload).encode("utf-8")) - # instruction.md - (task_path / "instruction.md").write_text(task.instruction, encoding="utf-8") - - # solution/patch.diff — canonical SWE-bench-style oracle (what trainers consume) - sol_dir = task_path / "solution" - sol_dir.mkdir(exist_ok=True) - (sol_dir / "patch.diff").write_text(task.oracle_diff, encoding="utf-8") - - # solution/solve.sh — Harbor's oracle agent runs this script inside the - # container; it should leave the working tree in the "fixed" state. We - # `git apply` the canonical patch.diff so we keep one oracle artifact - # (patch.diff) and just provide the execution shim Harbor needs. - (sol_dir / "solve.sh").write_text( - "#!/bin/bash\n" - "set -euxo pipefail\n" - "cd /workspace\n" - "git config --global --add safe.directory /workspace\n" - # Harbor uploads the whole solution/ dir into the container under - # /solution; the patch.diff sits next to this script. - 'PATCH="$(dirname "$0")/patch.diff"\n' - 'git apply --verbose --reject "$PATCH"\n', - encoding="utf-8", - ) - (sol_dir / "solve.sh").chmod(0o755) + if task.steps: + for step in task.steps: + step_dir = task_path / "steps" / step.name + step_dir.mkdir(parents=True, exist_ok=True) + (step_dir / "instruction.md").write_text(step.instruction, encoding="utf-8") + _write_solution(step_dir / "solution", step.oracle_diff) + if step.test_script is not None: + _write_test_script(step_dir / "tests", step.test_script) + _write_aux_files(step_dir, step.aux_files) + else: + (task_path / "instruction.md").write_text(task.instruction, encoding="utf-8") + _write_solution(task_path / "solution", task.oracle_diff) # Optional environment/Dockerfile + tests/test.sh — written only for # sandbox-required tasks (pr_runtime, future commit_runtime, etc.). @@ -175,23 +273,13 @@ def write_harbor_task(task: HarborTask, dest_dir: Path) -> Path: env_dir.mkdir(exist_ok=True) (env_dir / "Dockerfile").write_text(task.environment_dockerfile, encoding="utf-8") if task.test_script is not None: - tests_dir = task_path / "tests" - tests_dir.mkdir(exist_ok=True) - (tests_dir / "test.sh").write_text(task.test_script, encoding="utf-8") - # mark executable; harbor expects test.sh to be runnable - (tests_dir / "test.sh").chmod(0o755) + _write_test_script(task_path / "tests", task.test_script) # Auxiliary task files (relative paths under the task dir). Harbor mounts # the task's tests/ dir into the container at /tests, so a pipeline can # ship e.g. tests/verifier.py + tests/f2p.json + tests/p2p.json as plain, # inspectable artifacts and have test.sh read them — instead of baking # everything as base64 blobs inside test.sh. - for rel_path, content in (task.aux_files or {}).items(): - # Defensive: keep aux files inside the task dir. - target = (task_path / rel_path).resolve() - if not str(target).startswith(str(task_path.resolve())): - raise ValueError(f"aux_file path escapes task dir: {rel_path!r}") - target.parent.mkdir(parents=True, exist_ok=True) - target.write_text(content, encoding="utf-8") + _write_aux_files(task_path, task.aux_files) return task_path diff --git a/src/repo2rlenv/validation.py b/src/repo2rlenv/validation.py index d9729a8a..f8154ac3 100644 --- a/src/repo2rlenv/validation.py +++ b/src/repo2rlenv/validation.py @@ -24,8 +24,12 @@ Limits: this is static validation. It cannot tell whether a Dockerfile builds, whether a shell script's dependencies exist, or whether the oracle patch applies at `base_commit` — `harbor run --agent oracle` is still the ground truth. Only -the verifier assets Repo2RLEnv itself emits are checked in detail. Multi-step -(`[[steps]]`) Harbor tasks skip the asset-layout checks. +the verifier assets Repo2RLEnv itself emits are checked in detail. + +Multi-step (`[[steps]]`) tasks are checked per step: each step needs +steps//instruction.md, and a test script either in steps//tests/ +or at the top-level tests/ Harbor falls back to. Pipeline-specific verifier +assets are not checked per step. """ from __future__ import annotations @@ -33,6 +37,7 @@ import ast import json import re +import unicodedata from dataclasses import dataclass from pathlib import Path from typing import Any, Literal, get_args @@ -66,6 +71,12 @@ _SHA256_RE = re.compile(r"^sha256:[0-9a-f]{64}$") _FROM_LINE_RE = re.compile(r"^\s*FROM\s+(\S+)", re.IGNORECASE | re.MULTILINE) _DIFF_FILE_HEADER_RE = re.compile(r"^(diff --git |\+\+\+ )", re.MULTILINE) +# Harbor's step-name rule (`harbor.models.task.step_name`): one portable +# directory name on every host OS. +_STEP_NAME_INVALID_RE = re.compile(r'[<>:"/\\|?*\x00-\x1f\x7f]') +_WINDOWS_DEVICE_NAME_RE = re.compile( + r"^(CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|(?:COM|LPT)[1-9¹²³])$", re.IGNORECASE +) @dataclass(frozen=True, slots=True) @@ -111,18 +122,20 @@ def validate_task(task_dir: Path, data: dict[str, Any], *, oracle: bool = False) report.error("task.toml", "[metadata.repo2env] must be a table") r2e = None - if data.get("steps"): - report.warn( - "task.toml", - "multi-step [[steps]] task: per-step instruction/tests/solution are not checked", - ) + steps = data.get("steps") + if steps: + step_names = _check_steps_layout(task_dir, steps, env_cfg, r2e, script_ext, report) else: + step_names = [] _check_layout(task_dir, env_cfg, r2e, script_ext, report) _check_separate_verifier(task_dir, data, r2e, report) if r2e is not None: _check_repro(task_dir, r2e, report) - if oracle and not data.get("steps"): + if oracle and steps: + for name in step_names: + _check_oracle(task_dir, r2e, script_ext, report, prefix=f"steps/{name}/") + elif oracle: _check_oracle(task_dir, r2e, script_ext, report) return report.findings @@ -138,9 +151,7 @@ def _check_layout( _check_nonempty_file(task_dir, "instruction.md", report) env_dir = task_dir / "environment" - has_env_definition = bool(env_cfg.get("docker_image")) or any( - (env_dir / name).is_file() for name in ("Dockerfile", "docker-compose.yaml") - ) + has_env_definition = _has_env_definition(task_dir, env_cfg) test_script = f"tests/test{script_ext}" has_tests_dir = (task_dir / "tests").is_dir() @@ -184,6 +195,74 @@ def _check_layout( _check_diff_verifier(task_dir, report) +def _has_env_definition(task_dir: Path, env_cfg: dict[str, Any]) -> bool: + env_dir = task_dir / "environment" + return bool(env_cfg.get("docker_image")) or any( + (env_dir / name).is_file() for name in ("Dockerfile", "docker-compose.yaml") + ) + + +def _check_steps_layout( + task_dir: Path, + steps: Any, + env_cfg: dict[str, Any], + r2e: dict[str, Any] | None, + script_ext: str, + report: _Report, +) -> list[str]: + """Check a multi-step task's shared environment and per-step assets. + + Returns the usable step names, in order. Harbor runs a step's verifier + with steps//tests/ when it ships a test script and falls back to + the task-level tests/ otherwise, so either location satisfies a step. + """ + if not isinstance(steps, list) or not all(isinstance(step, dict) for step in steps): + report.error("task.toml", "[[steps]] must be an array of tables") + return [] + + env_dir = task_dir / "environment" + if (r2e is not None or env_dir.is_dir()) and not _has_env_definition(task_dir, env_cfg): + report.error("environment", _no_env_definition_msg()) + + test_script = f"tests/test{script_ext}" + if (task_dir / "tests").is_dir(): + _check_nonempty_file(task_dir, test_script, report) + has_fallback_tests = (task_dir / test_script).is_file() + + names: list[str] = [] + seen: set[str] = set() + for index, step in enumerate(steps): + name = step.get("name") + if not _is_portable_step_name(name): + report.error("task.toml", f"steps[{index}].name is not a portable name: {name!r}") + continue + key = unicodedata.normalize("NFC", name).casefold() + if key in seen: + report.error("task.toml", f"duplicate step name {name!r}") + continue + seen.add(key) + names.append(name) + + prefix = f"steps/{name}/" + _check_nonempty_file(task_dir, f"{prefix}instruction.md", report) + step_tests = task_dir / prefix / "tests" + if step_tests.is_dir() or (r2e is not None and not has_fallback_tests): + _check_nonempty_file(task_dir, f"{prefix}{test_script}", report) + return names + + +def _is_portable_step_name(name: Any) -> bool: + return ( + isinstance(name, str) + and bool(name.strip()) + and name not in (".", "..") + and not name.endswith((".", " ")) + and not _STEP_NAME_INVALID_RE.search(name) + and not _WINDOWS_DEVICE_NAME_RE.fullmatch(name.partition(".")[0].rstrip(" ")) + and len(name.encode("utf-8")) <= 255 + ) + + def _reward_kinds(r2e: dict[str, Any], report: _Report) -> list[str]: kinds = r2e.get("reward_kinds") if kinds is None: @@ -378,21 +457,23 @@ def _check_repro(task_dir: Path, r2e: dict[str, Any], report: _Report) -> None: report.error("task.toml", f"{where}.inline_recipe_lines must be a non-negative integer") -def _check_oracle(task_dir: Path, r2e: dict[str, Any], script_ext: str, report: _Report) -> None: +def _check_oracle( + task_dir: Path, r2e: dict[str, Any], script_ext: str, report: _Report, *, prefix: str = "" +) -> None: + # `prefix` is "steps//" for a step of a multi-step task. # Named recipes can restore files or run commands directly in solve.sh. # Preserve the stricter patch contract for existing native tasks, and # validate any patch a recipe actually includes. requires_patch = r2e.get("recipe", "native") == "native" patch = None - if requires_patch or (task_dir / "solution/patch.diff").exists(): - patch = _check_nonempty_file(task_dir, "solution/patch.diff", report) + patch_rel = f"{prefix}solution/patch.diff" + if requires_patch or (task_dir / patch_rel).exists(): + patch = _check_nonempty_file(task_dir, patch_rel, report) pr_diff = r2e.get("pr_diff") search_replace = isinstance(pr_diff, dict) and pr_diff.get("diff_format") == "search_replace" if patch is not None and not search_replace and not _DIFF_FILE_HEADER_RE.search(patch): - report.error( - "solution/patch.diff", "not a unified diff (no 'diff --git' or '+++' file header)" - ) - _check_nonempty_file(task_dir, f"solution/solve{script_ext}", report) + report.error(patch_rel, "not a unified diff (no 'diff --git' or '+++' file header)") + _check_nonempty_file(task_dir, f"{prefix}solution/solve{script_ext}", report) def _check_nonempty_file(task_dir: Path, rel: str, report: _Report) -> str | None: diff --git a/tests/test_emitter.py b/tests/test_emitter.py index 03e4cace..334740a0 100644 --- a/tests/test_emitter.py +++ b/tests/test_emitter.py @@ -6,7 +6,9 @@ import tomllib from pathlib import Path -from repo2rlenv.emitter.harbor import HarborTask, write_harbor_task +import pytest + +from repo2rlenv.emitter.harbor import HarborStep, HarborTask, write_harbor_task def _assert_executable(path: Path) -> None: @@ -193,3 +195,81 @@ def test_shared_verifier_by_default(tmp_path: Path): config = tomllib.loads((write_harbor_task(_make_task(), tmp_path) / "task.toml").read_text()) assert config["verifier"] == {"timeout_sec": 300.0} assert "artifacts" not in config + + +def _make_multi_step_task(**kwargs) -> HarborTask: + task = _make_task() + task.instruction = "" + task.oracle_diff = "" + task.steps = [ + HarborStep( + name="implement", + instruction="add the feature", + oracle_diff="--- a/x.py\n+++ b/x.py\n@@\n-1\n+2\n", + test_script="#!/bin/bash\necho implement\n", + aux_files={"tests/f2p.json": "[]"}, + min_reward=1.0, + ), + HarborStep(name="extend", instruction="extend it", oracle_diff="--- a/y.py\n"), + ] + for key, value in kwargs.items(): + setattr(task, key, value) + return task + + +def test_multi_step_task_toml_and_layout(tmp_path: Path): + out = write_harbor_task(_make_multi_step_task(multi_step_reward_strategy="mean"), tmp_path) + data = tomllib.loads((out / "task.toml").read_text(encoding="utf-8")) + assert data["version"] == "1.1" + assert data["multi_step_reward_strategy"] == "mean" + assert data["steps"] == [ + { + "name": "implement", + "agent": {"timeout_sec": 1800.0}, + "verifier": {"timeout_sec": 300.0}, + "min_reward": 1.0, + }, + {"name": "extend", "agent": {"timeout_sec": 1800.0}, "verifier": {"timeout_sec": 300.0}}, + ] + assert not (out / "instruction.md").exists() + assert not (out / "solution").exists() + step = out / "steps" / "implement" + assert (step / "instruction.md").read_text(encoding="utf-8") == "add the feature" + assert (step / "solution" / "patch.diff").read_text(encoding="utf-8").startswith("--- a/x.py") + assert (step / "tests" / "f2p.json").read_text(encoding="utf-8") == "[]" + _assert_executable(step / "tests" / "test.sh") + _assert_executable(step / "solution" / "solve.sh") + assert not (out / "steps" / "extend" / "tests").exists() + + +def test_multi_step_content_hash_covers_every_step(tmp_path: Path): + def digest(task: HarborTask, dest: Path) -> str: + out = write_harbor_task(task, dest) + data = tomllib.loads((out / "task.toml").read_text(encoding="utf-8")) + return data["metadata"]["repo2env"]["content_hash"] + + base = digest(_make_multi_step_task(), tmp_path / "a") + changed = _make_multi_step_task() + changed.steps[1].instruction = "extend it differently" + assert digest(changed, tmp_path / "b") != base + + +@pytest.mark.parametrize( + "kwargs", + [ + {"instruction": "top-level instruction"}, + {"oracle_diff": "--- a/z.py\n"}, + {"multi_step_reward_strategy": "max"}, + ], +) +def test_multi_step_rejects_task_level_fields(tmp_path: Path, kwargs): + with pytest.raises(ValueError): + write_harbor_task(_make_multi_step_task(**kwargs), tmp_path) + + +@pytest.mark.parametrize("names", [["a/b"], ["../up"], ["round 1"], ["dup", "DUP"]]) +def test_multi_step_rejects_bad_step_names(tmp_path: Path, names): + task = _make_multi_step_task() + task.steps = [HarborStep(name=n, instruction="x", oracle_diff="y") for n in names] + with pytest.raises(ValueError): + write_harbor_task(task, tmp_path) diff --git a/tests/test_validation.py b/tests/test_validation.py index 12990fa9..84842189 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -17,7 +17,7 @@ from rich.console import Console from repo2rlenv.cli import main -from repo2rlenv.emitter.harbor import HarborTask, write_harbor_task +from repo2rlenv.emitter.harbor import HarborStep, HarborTask, write_harbor_task from repo2rlenv.pipelines._env_guard import egress_guard_compose from repo2rlenv.pipelines.code_instruct import build_code_instruct_dockerfile from repo2rlenv.pipelines.pr_diff import ( @@ -312,11 +312,112 @@ def test_non_r2e_task_only_checks_what_exists(tmp_path: Path): assert _errors(validate_task(tmp_path, data)) == {"environment", "tests/test.sh"} -def test_multi_step_task_skips_layout_checks(tmp_path: Path): - data = {"version": "1.0", "task": {"name": "org/steps"}, "steps": [{"name": "one"}]} - findings = validate_task(tmp_path, data) - assert _errors(findings) == set() - assert _warnings(findings) == {"task.toml"} +def _multi_step(tmp_path: Path, **kwargs) -> Path: + steps = [ + HarborStep( + name=name, + instruction=f"do {name}", + oracle_diff=PATCH, + test_script="#!/bin/bash\npytest -q\n", + ) + for name in ("implement", "extend") + ] + task = HarborTask( + name="demo__repo-steps", + org="myorg", + description="example", + instruction="", + oracle_diff="", + repo2env={ + "pipeline": "pr_runtime", + "repo": "demo/repo", + "reward_kinds": ["test_execution"], + }, + environment_dockerfile=build_environment_dockerfile( + "local/r2e-bootstrap/demo__repo:abc", BASE + ), + steps=steps, + **kwargs, + ) + return write_harbor_task(task, tmp_path) + + +def test_emitted_multi_step_task_is_valid(tmp_path: Path): + task_dir = _multi_step(tmp_path) + assert _errors(validate_task(task_dir, _load(task_dir), oracle=True)) == set() + + +@pytest.mark.parametrize( + "rel", + [ + "steps/extend/instruction.md", + "steps/extend/tests/test.sh", + "steps/extend/solution/solve.sh", + "steps/extend/solution/patch.diff", + ], +) +def test_multi_step_missing_step_asset_errors(tmp_path: Path, rel: str): + task_dir = _multi_step(tmp_path) + (task_dir / rel).unlink() + assert _errors(validate_task(task_dir, _load(task_dir), oracle=True)) == {rel} + + +def test_multi_step_solution_only_checked_with_oracle(tmp_path: Path): + task_dir = _multi_step(tmp_path) + (task_dir / "steps/extend/solution/solve.sh").unlink() + assert _errors(validate_task(task_dir, _load(task_dir))) == set() + + +def test_multi_step_falls_back_to_task_level_tests(tmp_path: Path): + task_dir = _multi_step(tmp_path, test_script="#!/bin/bash\npytest -q\n") + for name in ("implement", "extend"): + (task_dir / f"steps/{name}/tests/test.sh").unlink() + (task_dir / f"steps/{name}/tests").rmdir() + assert _errors(validate_task(task_dir, _load(task_dir))) == set() + + +def test_multi_step_requires_environment(tmp_path: Path): + task_dir = _multi_step(tmp_path) + (task_dir / "environment" / "Dockerfile").unlink() + assert _errors(validate_task(task_dir, _load(task_dir))) == {"environment"} + + +def test_multi_step_windows_uses_bat_scripts(tmp_path: Path): + task_dir = _multi_step(tmp_path) + for name in ("implement", "extend"): + step = task_dir / "steps" / name + (step / "tests" / "test.sh").rename(step / "tests" / "test.bat") + (step / "solution" / "solve.sh").rename(step / "solution" / "solve.bat") + data = _rewrite(task_dir, lambda d: d.update(environment={"os": "windows"})) + assert _errors(validate_task(task_dir, data, oracle=True)) == set() + + +@pytest.mark.parametrize( + "steps", + [ + [{"name": "a/b"}], + [{"name": "nul"}], + [{"name": "trailing."}], + [{"name": "Same"}, {"name": "same"}], + [{}], + ["implement"], + ], +) +def test_multi_step_rejects_bad_step_names(tmp_path: Path, steps): + (tmp_path / "steps" / "Same").mkdir(parents=True) + (tmp_path / "steps" / "Same" / "instruction.md").write_text("x", encoding="utf-8") + data = {"version": "1.1", "task": {"name": "org/steps"}, "steps": steps} + assert _errors(validate_task(tmp_path, data)) == {"task.toml"} + + +def test_non_r2e_multi_step_task_only_checks_what_exists(tmp_path: Path): + (tmp_path / "steps" / "one").mkdir(parents=True) + (tmp_path / "steps" / "one" / "instruction.md").write_text("do it", encoding="utf-8") + data = {"version": "1.1", "task": {"name": "org/steps"}, "steps": [{"name": "one"}]} + assert validate_task(tmp_path, data, oracle=True) == [] + + (tmp_path / "steps" / "one" / "tests").mkdir() + assert _errors(validate_task(tmp_path, data)) == {"steps/one/tests/test.sh"} def test_unknown_pipeline_and_reward_kind_warn(tmp_path: Path):