Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/reference/SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
166 changes: 127 additions & 39 deletions src/repo2rlenv/emitter/harbor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>/ 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
----------------------------------------------------------------------------
Expand Down Expand Up @@ -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>/."""

name: str
instruction: str
oracle_diff: str
test_script: str | None = None
# Extra files under steps/<name>/ (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:
Expand All @@ -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/<task.name>. Returns the path."""
if task.steps:
_check_steps(task)
task_path = dest_dir / task.name
task_path.mkdir(parents=True, exist_ok=True)

Expand Down Expand Up @@ -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.).
Expand All @@ -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
Loading