The first exam for code agents in the physical world: frozen robot tasks from many benchmark suites, each answered with a program and verified in a separate sandbox. Runs on Harbor.
Python ai-agentsbenchmarkcoding-agentsembodied-aievaluationharborllm-agentsrobot-learningroboticssimulation
robot_coding_bench v0.1 scaffold: Harbor benchmark for coding agents on robot simulators (+7 more)
Kangrui Wangb5fabb98ee73
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 0000000000..b6d3539902--- /dev/null+++ b/.dockerignore@@ -0,0 +1,6 @@+**/.venv+**/__pycache__+**/outputs+exps/+jobs/+.gitdiff --git a/.env.example b/.env.examplenew file mode 100644index 0000000000..8c55c2f5f5--- /dev/null+++ b/.env.example@@ -0,0 +1,3 @@+# Harbor forwards these into the agent container. Copy to .env (gitignored) or export them.+ANTHROPIC_API_KEY= # or CLAUDE_CODE_OAUTH_TOKEN=... with CLAUDE_FORCE_OAUTH=1+OPENAI_API_KEY= # or CODEX_FORCE_AUTH_JSON=1 to reuse ~/.codex/auth.json (ChatGPT login)diff --git a/.github/pull_request_template.md b/.github/pull_request_template.mdnew file mode 100644index 0000000000..3c0ce50ed5--- /dev/null+++ b/.github/pull_request_template.md@@ -0,0 +1,14 @@+## What+<!-- New instance(s) of an existing family / new family / new simulator adapter / task repair -->++## Checklist+- [ ] `bash ci_checks/run_all.sh tasks/<my-task>` passes locally.+- [ ] `harbor run -p tasks/<my-task> -a oracle` gives reward 1 (paste the job summary below).+- [ ] `harbor run -p tasks/<my-task> -a nop` gives reward 0.+- [ ] Scene/verifier inputs under `environment/` and `tests/` are final (changing them later = new task).+- [ ] `instruction.md` states the deliverable and every convention the agent cannot infer (frames, quaternion order, paths).+- [ ] Fresh-process determinism evidence is included for a new simulator/family.+- [ ] If this touches `images/`: `images/VERSION` was bumped and dependent task Dockerfiles re-pinned.++## Evidence+<!-- oracle job summary; optional: one strong-model run and why it failed -->diff --git a/.github/workflows/static-checks.yml b/.github/workflows/static-checks.ymlnew file mode 100644index 0000000000..4fdda73e9c--- /dev/null+++ b/.github/workflows/static-checks.yml@@ -0,0 +1,15 @@+name: static-checks+on:+ pull_request:+ paths: ["tasks/**", "ci_checks/**"]+ push:+ branches: [main]+jobs:+ checks:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with: { python-version: "3.12" }+ - name: Static checks on all tasks+ run: bash ci_checks/run_all.shdiff --git a/.github/workflows/validate-task.yml b/.github/workflows/validate-task.ymlnew file mode 100644index 0000000000..66170cd84b--- /dev/null+++ b/.github/workflows/validate-task.yml@@ -0,0 +1,26 @@+name: validate-task+# Oracle must score 1 and the nop agent must score 0 for the given tasks. Pulls the ~20 GB base image,+# so this runs on demand (workflow_dispatch) or on a self-hosted runner; not on every PR push yet.+on:+ workflow_dispatch:+ inputs:+ tasks: { description: "space-separated task dirs (default: all)", required: false, default: "" }+jobs:+ validate:+ runs-on: [self-hosted, docker]+ steps:+ - uses: actions/checkout@v4+ - uses: astral-sh/setup-uv@v5+ - run: uv tool install harbor+ - name: oracle == 1+ run: |+ set -e; for t in ${{ inputs.tasks || 'tasks/*/' }}; do+ harbor run -p "$t" -a oracle -o jobs/validate --job-name "oracle-$(basename $t)"+ grep -qx 1 jobs/validate/oracle-$(basename $t)/*/verifier/reward.txt || { echo "oracle failed on $t"; exit 1; }+ done+ - name: nop == 0+ run: |+ set -e; for t in ${{ inputs.tasks || 'tasks/*/' }}; do+ harbor run -p "$t" -a nop -o jobs/validate --job-name "nop-$(basename $t)"+ grep -qx 0 jobs/validate/nop-$(basename $t)/*/verifier/reward.txt || { echo "nop passed on $t (verifier too weak)"; exit 1; }+ donediff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000000..dfba258190--- /dev/null+++ b/.gitignore@@ -0,0 +1,10 @@+__pycache__/+*.py[cod]+*.egg-info/+.venv/+/exps/+/jobs/+*.log+.env+.env.*+!.env.examplediff --git a/.gitmodules b/.gitmodulesnew file mode 100644index 0000000000..9d7159c538--- /dev/null+++ b/.gitmodules@@ -0,0 +1,3 @@+[submodule "third_party/cap-x"]+ path = third_party/cap-x+ url = https://github.com/capgym/cap-x.gitdiff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000000..1ad986890f--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,11 @@+# AGENTS.md — map for coding agents working in this repo++Read `README.md`, `docs/PROTOCOL.md` (the contract), `CONTRIBUTING.md` first.++- Tasks are self-contained Harbor task dirs under `tasks/`. To keep maximum flexibility there is currently+ no shared Python package: the example `tasks/robosuite-cube-stack-i00/` carries its own tooling+ (`environment/rcb_traj.py`) and verifier (`tests/grade.py`, `tests/rcb_traj.py`). To add a task, copy it.+- `images/<sim>/Dockerfile`: simulator base images, tagged from `images/VERSION`; `scripts/build_images.sh`.+- `ci_checks/run_all.sh [task dirs]`: contract checks. New check = `check-<thing>.sh <task_dir>`, registered in `run_all.sh`.+- `tasks/dataset.toml`: task manifest; refresh with `cd tasks && harbor add --scan .`.+- Local docker sandbox has no `[environment].gpus`; the current tasks don't need a GPU.diff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000000..4f018eb1cb--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,39 @@+# Contributing a task++A task is a plain Harbor task directory that follows [docs/PROTOCOL.md](docs/PROTOCOL.md). Start by copying+the example and changing what you need.++## Steps+1. `cp -r tasks/robosuite-cube-stack-i00 tasks/<simulator>-<family>-i<NN>` (or `harbor task init` for a+ blank one). Slug rules: `docs/TAXONOMY.md`.+2. Edit `task.toml`: `[task].name = "robot-coding-bench/<folder>"`, metadata fields, timeouts.+3. `environment/`: a `Dockerfile` that `FROM`s a **pinned** registry image and `COPY`s everything the agent+ needs (scene definition, tooling). Need a new simulator? Add `images/<sim>/Dockerfile`, build with+ `scripts/build_images.sh`, push with `scripts/push_images.sh`, bump `images/VERSION`.+4. `instruction.md`: human-written; states the deliverable under `/app/output/`, the action layout, frames,+ quaternion order, and the tools; never mentions `/tests/`.+5. `tests/test.sh` + your verifier: fresh-process verification, `reward.txt` 1/0, numeric-only `reward.json`+ with the field names from PROTOCOL §3. Keep the verifier's inputs (scene copy, tooling) under `tests/`.+6. `solution/solve.sh`: a human-written oracle that scores 1. Keep the reference code itself in `solution/` too;+ never bake it into `environment/` or a base image, and make sure agent-visible tooling does not reference it.+7. `README.md`: fill **Difficulty**, **Reference solution**, **Verification**.+8. Check and run:+ ```bash+ bash ci_checks/run_all.sh tasks/<your-task>+ harbor run -p tasks/<your-task> -a oracle # must be 1+ harbor run -p tasks/<your-task> -a nop # must be 0+ cd tasks && harbor add --scan . && cd .. # register in dataset.toml+ ```+9. Open a PR with the oracle job summary (and, ideally, one strong-model run and why it failed).++## Rules+- A shipped task's `environment/` and `tests/` inputs are immutable; changing the scene is a new task.+- Determinism is on you: `selftest`-style evidence (live run == replay, repeated) is required for a new+ simulator or family. For MuJoCo see the example's `_snapshot/_restore/_restore_wrapper_bookkeeping`.+- Pin everything (`FROM` tag, pip versions). No network fetches at verification time.+- Agents run as root inside the container; assume they can edit anything under `/app` and `/opt`. Only+ `/tests/` is trustworthy, and it is copied in after the agent finishes.++## Repairs+Fix PRs explain which agent behaviour the change closes and include before/after runs. Pass rates alone are+not evidence.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000000..68781b9014--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Kangrui Wang and robot_coding_bench contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000000..2189ecb144--- /dev/null+++ b/README.md@@ -0,0 +1,54 @@+# robot_coding_bench++Can a coding agent be a roboticist? **robot_coding_bench** is a [Harbor](https://github.com/harbor-framework/harbor)+benchmark: each task drops an agent (Claude Code, Codex, …) into a container with a robot simulator and a+Python tool API and asks for a deliverable — in the current tasks, **one replayable trajectory** that completes+a manipulation goal in a **frozen scene instance**. The verifier replays it in a fresh process; scoring is+binary with numeric diagnostics, no learned judge.++The repo is deliberately minimal: it adds a thin **contract** ([docs/PROTOCOL.md](docs/PROTOCOL.md)) on top of+the plain Harbor task format, and every task is **self-contained**. Shared kits will be factored out once+several tasks exist; until then, copy the example.++## Run++```bash+uv tool install harbor+export ANTHROPIC_API_KEY=… # or OPENAI_API_KEY; subscription-login variants in .env.example++harbor run --repo [email protected]:JamesKrW/robot_coding_bench.git -a claude-code -m anthropic/claude-fable-5-1 -k 3+harbor run --repo [email protected]:JamesKrW/robot_coding_bench.git -a codex -m openai/gpt-6-astra -k 3+# local checkout / subset / pinned release+harbor run -p tasks -i 'robosuite-*' -a claude-code -m anthropic/claude-sonnet-5+harbor run --repo [email protected]:JamesKrW/[email protected] -a oracle+harbor view jobs+```+Tasks `FROM` published base images (`ghcr.io/jameskrw/rcb-<sim>:<tag>`); the current tasks need no GPU, so+the default local Docker sandbox works (Modal too). Once on Harbor Hub: `harbor run -d robot-coding-bench/[email protected] …`.++## Layout++```+tasks/ # Harbor tasks, one dir each, + dataset.toml (allowlist, digests)+└── robosuite-cube-stack-i00/ # the example: self-contained+ ├── instruction.md task.toml README.md+ ├── environment/ Dockerfile (FROM base image), instance.npz (frozen scene), rcb_traj.py (agent tooling)+ ├── tests/ test.sh, grade.py (verifier), rcb_traj.py, instance.npz (verifier's own copies)+ └── solution/ solve.sh (oracle)+images/<sim>/Dockerfile # base images = simulator installs only; scripts/build_images.sh, push_images.sh+ci_checks/ # contract checks: structure, fields, pinned FROM, instruction, dataset manifest+docs/PROTOCOL.md TAXONOMY.md # the contract and the metadata vocabulary+third_party/cap-x # submodule used by images/robosuite+CONTRIBUTING.md AGENTS.md # how to add a task; map for coding agents+```++## The example task (`robosuite-cube-stack-i00`)+Franka Panda in robosuite/MuJoCo via [cap-x](https://github.com/capgym/cap-x) primitives+(`get_object_pose`, `goto_pose`, `open/close_gripper`, …). `rcb_traj.py` gives the agent `Session`: reset to+the frozen state as often as it likes, record `(T, 9)` joint-target + gripper actions, self-check by replay,+save `/app/output/trajectory.npz`. `tests/grade.py` restores the same state in a fresh process, replays twice+and passes iff the stack predicate holds and both final-state hashes agree. Verified: oracle 1, nop 0.++## Status+v0.1 (2026-09): one example task. Next: more instances/families (robosuite), LIBERO-PRO, BEHAVIOR,+`perception` tier, `policy` task type; then factor shared tooling into kits.diff --git a/ci_checks/check-dataset-manifest.sh b/ci_checks/check-dataset-manifest.shnew file mode 100755index 0000000000..8775a3c069--- /dev/null+++ b/ci_checks/check-dataset-manifest.sh@@ -0,0 +1,12 @@+#!/usr/bin/env bash+# Every task dir under tasks/ must be listed in tasks/dataset.toml and vice versa.+root="$(cd "$(dirname "$0")/.." && pwd)"; python3 - "$root" <<'PY'+import sys, tomllib, pathlib+root = pathlib.Path(sys.argv[1]); d = tomllib.load(open(root / "tasks" / "dataset.toml", "rb"))+listed = {t["name"].split("/")[-1] if "/" in t.get("name", "") else pathlib.Path(t.get("path", t.get("name"))).name for t in d.get("tasks", [])}+present = {p.name for p in (root / "tasks").iterdir() if p.is_dir() and (p / "task.toml").exists()}+rc = 0+for x in sorted(present - listed): print(f"FAIL tasks/{x}: not in tasks/dataset.toml"); rc = 1+for x in sorted(listed - present): print(f"FAIL dataset.toml lists missing task {x}"); rc = 1+sys.exit(rc)+PYdiff --git a/ci_checks/check-dockerfile.sh b/ci_checks/check-dockerfile.shnew file mode 100755index 0000000000..c647d360e1--- /dev/null+++ b/ci_checks/check-dockerfile.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+# Reproducibility: FROM must be a registry image with an explicit, non-'latest' tag or digest.+t="$1"; from=$(grep -m1 '^FROM ' "$t/environment/Dockerfile" | awk '{print $2}')+case "$from" in+ *@sha256:*) exit 0 ;;+ *:latest|*:*latest) echo "FAIL $t: Dockerfile FROM '$from' uses :latest"; exit 1 ;;+ */*:*) exit 0 ;;+ *) echo "FAIL $t: Dockerfile FROM '$from' must be <registry>/<image>:<tag> (pinned)"; exit 1 ;;+esacdiff --git a/ci_checks/check-instruction.sh b/ci_checks/check-instruction.shnew file mode 100755index 0000000000..101e957cd5--- /dev/null+++ b/ci_checks/check-instruction.sh@@ -0,0 +1,6 @@+#!/usr/bin/env bash+# instruction.md names the deliverable under /app/output/ and never leaks the verifier's /tests/ copy.+t="$1"; rc=0+grep -q '/app/output/' "$t/instruction.md" || { echo "FAIL $t: instruction.md must state the deliverable under /app/output/"; rc=1; }+grep -q '/tests/' "$t/instruction.md" && { echo "FAIL $t: instruction.md must not reference /tests/"; rc=1; }+exit $rcdiff --git a/ci_checks/check-task-fields.sh b/ci_checks/check-task-fields.shnew file mode 100755index 0000000000..0dc52f6e39--- /dev/null+++ b/ci_checks/check-task-fields.sh@@ -0,0 +1,18 @@+#!/usr/bin/env bash+# task.toml: name matches folder, required metadata (docs/TAXONOMY.md), deliverable dir, agent timeout cap.+t="$1"; python3 - "$t" <<'PY'+import sys, tomllib, pathlib+t = pathlib.Path(sys.argv[1]); d = tomllib.load(open(t / "task.toml", "rb")); rc = 0+def fail(m):+ global rc; print(f"FAIL {t}: {m}"); rc = 1+if d.get("task", {}).get("name") != f"robot-coding-bench/{t.name}": fail("[task].name must be robot-coding-bench/<folder>")+m = d.get("metadata", {})+for k in ["author_name", "task_type", "simulator", "robot", "family", "tier", "expert_time_estimate_hours"]:+ if k not in m: fail(f"[metadata].{k} missing")+if m.get("task_type") not in ("trajectory", "policy"): fail("task_type must be trajectory|policy")+if m.get("tier") not in ("privileged", "perception"): fail("tier must be privileged|perception")+if "/app/output/" not in d.get("artifacts", []): fail('top-level artifacts must include "/app/output/"')+if not d.get("agent", {}).get("timeout_sec"): fail("[agent].timeout_sec required")+elif d["agent"]["timeout_sec"] > 14400: fail("[agent].timeout_sec > 4h cap")+sys.exit(rc)+PYdiff --git a/ci_checks/check-task-structure.sh b/ci_checks/check-task-structure.shnew file mode 100755index 0000000000..7da462d805--- /dev/null+++ b/ci_checks/check-task-structure.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+# Harbor task contract: the canonical files exist and scripts are executable.+t="$1"; rc=0+for f in task.toml instruction.md README.md environment/Dockerfile tests/test.sh solution/solve.sh; do+ [ -f "$t/$f" ] || { echo "FAIL $t: missing $f"; rc=1; }+done+[ -x "$t/tests/test.sh" ] || { echo "FAIL $t: tests/test.sh not executable"; rc=1; }+[ -x "$t/solution/solve.sh" ] || { echo "FAIL $t: solution/solve.sh not executable"; rc=1; }+exit $rcdiff --git a/ci_checks/run_all.sh b/ci_checks/run_all.shnew file mode 100755index 0000000000..55136c56f3--- /dev/null+++ b/ci_checks/run_all.sh@@ -0,0 +1,13 @@+#!/usr/bin/env bash+# Run every per-task check on the given task dirs (default: all of tasks/*), then repo-level checks.+set -uo pipefail+root="$(cd "$(dirname "$0")/.." && pwd)"; rc=0+tasks=("$@"); [ ${#tasks[@]} -eq 0 ] && tasks=("$root"/tasks/*/)+for t in "${tasks[@]}"; do+ t="${t%/}"; [ -f "$t/task.toml" ] || continue+ for c in check-task-structure check-task-fields check-dockerfile check-instruction; do+ bash "$root/ci_checks/$c.sh" "$t" || rc=1+ done+done+bash "$root/ci_checks/check-dataset-manifest.sh" || rc=1+[ $rc -eq 0 ] && echo "all checks passed"; exit $rcdiff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.mdnew file mode 100644index 0000000000..1d936c221f--- /dev/null+++ b/docs/PROTOCOL.md@@ -0,0 +1,59 @@+# Protocol (the contract every task follows)++The benchmark imposes as little as possible beyond the Harbor task format. Anything not listed here is+the task's own business: which simulator, how the scene is defined, what the agent's tool API looks like,+how the verifier decides.++## 1. Task = Harbor task directory+`instruction.md`, `task.toml`, `README.md`, `environment/Dockerfile`, `tests/test.sh`, `solution/solve.sh`,+plus whatever files those need. Tasks are **self-contained**: all task code (agent tooling, verifier) lives+in the task directory and is `COPY`ed by its Dockerfile. Base images under `images/` are infrastructure only+(simulator installs) and contain no benchmark code. A task's identity is its directory digest in+`tasks/dataset.toml`; changing any file is a new task version.++## 2. Deliverable+The agent writes its result under `/app/output/` (declared as `artifacts = ["/app/output/"]` so Harbor+collects it). The format is defined by the task's `instruction.md` and checked by its verifier.++`task_type` (metadata) says what kind of deliverable it is:++| `task_type` | deliverable | grading idea |+|---|---|---|+| `trajectory` | a replayable action sequence for **this** frozen scene instance | open-loop replay in a fresh process |+| `policy` | code that solves held-out instances of the family | success rate over N instances |++## 3. Verifier output+`tests/test.sh` writes `/logs/verifier/reward.txt` (`1` or `0`) and `/logs/verifier/reward.json` with+**numeric fields only** (Harbor rejects strings). Field names, so results are comparable across tasks:++| field | meaning |+|---|---|+| `success` | 1 iff the deliverable completes the task (required) |+| `deterministic` | 1 iff repeated verification agreed (trajectory tasks) |+| `n_actions`, `sim_steps` | length of the deliverable / simulation steps replayed |+| `final_reward` | the simulator's own dense reward at the end, if any |+| `missing_trajectory`, `grader_error` | 1 on those failure modes (so failures are diagnosable) |+| `video_rendered` | 1 if the verifier also wrote a human-viewable `/logs/verifier/replay.mp4` (recommended; never affects the verdict) |++## 4. Reproducibility rules+- The verifier must reach the same verdict in a **fresh process** on the same inputs; for physics+ simulators that means restoring the exact initial state (for MuJoCo: `qpos`, `qvel`, `time`, and+ `qacc_warmstart`, then re-anchor controllers and refresh cached observables). The example task+ replays twice and requires identical final-state hashes.+- `environment/Dockerfile` must `FROM` a registry image with a pinned tag or digest (CI checks).+- The verifier's inputs live under `tests/` (copied in after the agent finishes); `instruction.md` never+ references `/tests/`.+- `solution/solve.sh` (oracle) must score 1 and the `nop` agent must score 0.+- **Reference solutions live only under `solution/`** (Harbor mounts it at `/solution/` for the oracle agent only).+ Nothing the agent can reach — the task image, base images, tooling, docs inside the container — may contain+ a solution or point to one. Lesson from the first agent run: it found cap-x's built-in `oracle_code` through+ the tooling's `run-oracle` command and replayed it; base images now scrub those strings.++## 5. Budget reporting+Report success **and** cost. Harbor records tokens, $, turns and wall-clock; tasks should additionally+expose simulation cost (`sim_steps`, resets) through their tooling so agents can be compared under equal+budgets (align `--ak reasoning_effort`, `max_turns`, budget caps and `[agent].timeout_sec` first).++## 6. Metadata+See `docs/TAXONOMY.md`: `simulator`, `robot`, `family`, `task_type`, `tier` (`privileged` = state-based+perception allowed; `perception` = RGB-D only), `expert_time_estimate_hours`, author fields.diff --git a/docs/TAXONOMY.md b/docs/TAXONOMY.mdnew file mode 100644index 0000000000..e943962614--- /dev/null+++ b/docs/TAXONOMY.md@@ -0,0 +1,12 @@+# Taxonomy (task.toml `[metadata]`, closed sets — extend by PR)++| Field | Values |+|---|---|+| `simulator` | `robosuite` · `libero` · `behavior` · `maniskill` · … |+| `robot` | `franka-panda` · `r1pro` · … |+| `family` | free-form slug naming the scene/goal, shared by its instances (e.g. `cube_stack`) |+| `task_type` | `trajectory` · `policy` |+| `tier` | `privileged` · `perception` |+| `instance_seed` | optional, informational |++Folder slug: `<simulator>-<family-with-dashes>-i<NN>` for instance tasks; `[task].name = "robot-coding-bench/<slug>"`.diff --git a/images/VERSION b/images/VERSIONnew file mode 100644index 0000000000..17e51c385e--- /dev/null+++ b/images/VERSION@@ -0,0 +1 @@+0.1.1diff --git a/images/robosuite/Dockerfile b/images/robosuite/Dockerfilenew file mode 100644index 0000000000..e084decb25--- /dev/null+++ b/images/robosuite/Dockerfile@@ -0,0 +1,25 @@+# rcb-robosuite: cap-x robosuite (MuJoCo / Franka) environment. Infrastructure only — contains no benchmark+# code; tasks `FROM` it and COPY their own tooling. Tag = images/VERSION.+# Privileged/no-render mode needs no GPU at runtime; osmesa gives optional CPU offscreen rendering.+# The CUDA *devel* base is only needed because cap-x's editable curobo source requires CUDA_HOME/nvcc+# while uv resolves package metadata.+# Build from repo root: scripts/build_images.sh+FROM nvidia/cuda:12.8.1-devel-ubuntu22.04+ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 UV_LINK_MODE=copy CUDA_HOME=/usr/local/cuda+# curobo derives its version with setuptools_scm; there is no git metadata in the build context, so pin it+# to the version recorded in cap-x's uv.lock (otherwise setuptools_scm crashes in _version_missing).+ENV SETUPTOOLS_SCM_PRETEND_VERSION_FOR_NVIDIA_CUROBO=0.7.7.post1.dev9+RUN apt-get update && apt-get install -y --no-install-recommends \+ python3 python3-pip curl ca-certificates git tmux build-essential ffmpeg \+ libegl1 libgl1 libosmesa6 libglew-dev libglfw3 libx11-6 && \+ rm -rf /var/lib/apt/lists/*+RUN curl -LsSf https://astral.sh/uv/install.sh | sh+ENV PATH="/root/.local/bin:${PATH}"+WORKDIR /opt/cap-x+COPY third_party/cap-x /opt/cap-x+RUN uv python install 3.10 && uv venv -p 3.10 && uv sync --extra robosuite && rm -rf /root/.cache/uv+ENV PATH="/opt/cap-x/.venv/bin:${PATH}" MUJOCO_GL=osmesa PYOPENGL_PLATFORM=osmesa+# Strip cap-x's built-in reference solutions: an agent found and replayed `env.oracle_code` on the first run.+COPY images/robosuite/scrub_oracles.py /tmp/scrub_oracles.py+RUN python /tmp/scrub_oracles.py && rm /tmp/scrub_oracles.py && find /opt/cap-x -name ".git" -prune -exec rm -rf {} ++WORKDIR /appdiff --git a/images/robosuite/scrub_oracles.py b/images/robosuite/scrub_oracles.pynew file mode 100644index 0000000000..e3c7b3492c--- /dev/null+++ b/images/robosuite/scrub_oracles.py@@ -0,0 +1,16 @@+"""Remove cap-x's human-written reference solutions from the image so agents cannot look them up.+ORACLE_CODE string constants -> None; env_configs/human_oracle_code/ deleted. Fails loudly if anything is left."""+import pathlib, re, shutil, sys+root = pathlib.Path("/opt/cap-x")+n = 0+for p in root.rglob("*.py"):+ if "third_party" in p.parts: continue+ s = p.read_text(errors="ignore")+ s2 = re.sub(r'ORACLE_CODE(\w*)\s*=\s*(r?"""|r?\'\'\')(.*?)\2', r'ORACLE_CODE\1 = None # scrubbed', s, flags=re.S)+ s2 = re.sub(r'oracle_code\s*=\s*(r?"""|r?\'\'\')(.*?)\1', r'oracle_code = None # scrubbed', s2, flags=re.S)+ if s2 != s: p.write_text(s2); n += 1+shutil.rmtree(root / "env_configs" / "human_oracle_code", ignore_errors=True)+left = [str(p) for p in root.rglob("*") if p.is_file() and "third_party" not in p.parts and p.suffix in {".py", ".yaml", ".yml", ".md", ".txt"}+ and re.search(r'sample_grasp_pose\("red cube"\)|ORACLE_CODE\w*\s*=\s*(r?"""|r?\'\'\')', p.read_text(errors="ignore"))]+print(f"scrubbed {n} files; leftovers: {left}")+sys.exit(1 if left else 0)diff --git a/scripts/build_images.sh b/scripts/build_images.shnew file mode 100755index 0000000000..269e8be7b6--- /dev/null+++ b/scripts/build_images.sh@@ -0,0 +1,11 @@+#!/usr/bin/env bash+# Build every base image under images/<name>/ as ghcr.io/jameskrw/rcb-<name>:<images/VERSION> (+ :latest).+set -euo pipefail+ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT"+REG="${RCB_IMAGE_REGISTRY:-ghcr.io/jameskrw}"; VER="$(cat images/VERSION)"+D=docker; docker ps >/dev/null 2>&1 || D="sg docker -c"+for dir in images/*/; do+ name="$(basename "$dir")"+ cmd="docker build -t $REG/rcb-$name:$VER -t $REG/rcb-$name:latest -f $dir/Dockerfile ."+ echo "+ $cmd"; if [ "$D" = docker ]; then eval "$cmd"; else sg docker -c "$cmd"; fi+donediff --git a/scripts/install.sh b/scripts/install.shnew file mode 100755index 0000000000..46ee5d9bc0--- /dev/null+++ b/scripts/install.sh@@ -0,0 +1,13 @@+#!/usr/bin/env bash+# Host setup for task authors: Harbor CLI + cap-x venv (for making instances / running selftests outside Docker).+# Running the benchmark only needs Harbor + Docker (images are pulled from GHCR).+set -euo pipefail+ROOT="$(cd "$(dirname "$0")/.." && pwd)"+command -v uv >/dev/null || curl -LsSf https://astral.sh/uv/install.sh | sh+uv tool install harbor || uv tool upgrade harbor+git -C "$ROOT" submodule update --init --depth 1 third_party/cap-x+git -C "$ROOT/third_party/cap-x" submodule update --init --depth 1 \+ capx/third_party/robosuite capx/third_party/sam3 capx/third_party/contact_graspnet_pytorch \+ capx/third_party/curobo capx/third_party/LIBERO-PRO capx/third_party/verl capx/third_party/libero_dependencies/robosuite+cd "$ROOT/third_party/cap-x" && uv python install 3.10 && uv venv -p 3.10 && uv sync --extra robosuite+echo "OK. Selftest: cd third_party/cap-x && MUJOCO_GL=egl uv run --no-sync python $ROOT/tasks/robosuite-cube-stack-i00/environment/rcb_traj.py selftest --task cube_stack"diff --git a/scripts/push_images.sh b/scripts/push_images.shnew file mode 100755index 0000000000..c33ada56dc--- /dev/null+++ b/scripts/push_images.sh@@ -0,0 +1,10 @@+#!/usr/bin/env bash+# Push base images (needs: gh auth login && gh auth token | docker login ghcr.io -u <user> --password-stdin).+set -euo pipefail+ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT"+REG="${RCB_IMAGE_REGISTRY:-ghcr.io/jameskrw}"; VER="$(cat images/VERSION)"+D=docker; docker ps >/dev/null 2>&1 || D="sg docker -c"+for dir in images/*/; do+ name="$(basename "$dir")"+ for tag in "$VER" latest; do cmd="docker push $REG/rcb-$name:$tag"; echo "+ $cmd"; if [ "$D" = docker ]; then eval "$cmd"; else sg docker -c "$cmd"; fi; done+donediff --git a/tasks/README.md b/tasks/README.mdnew file mode 100644index 0000000000..f6d79f6aa4--- /dev/null+++ b/tasks/README.md@@ -0,0 +1,5 @@+# robot-coding-bench++Harbor tasks where a coding agent controls a simulated robot through Python primitives and must leave one+replayable trajectory for a frozen scene instance. See the repo README for the one-line run and+`docs/PROTOCOL.md` for scoring.diff --git a/tasks/dataset.toml b/tasks/dataset.tomlnew file mode 100644index 0000000000..5f110c7b8c--- /dev/null+++ b/tasks/dataset.toml@@ -0,0 +1,17 @@+# Dataset manifest for robot-coding-bench/robot-coding-bench+# Add tasks using: harbor add <org>/<name>+# Publish using: harbor publish++[dataset]+name = "robot-coding-bench/robot-coding-bench"+version = "0.1.0"+description = "Coding agents controlling simulated robots via Python primitives; one replayable trajectory per frozen scene instance (cap-x robosuite)."+keywords = [ "robotics", "manipulation", "code-as-policy", "robosuite", "harbor",]+[[dataset.authors]]+name = "MLL Lab"+++[[tasks]]+name = "robot-coding-bench/robosuite-cube-stack-i00"+digest = "sha256:94abb8ea6211582e94464d7930368522ff554c4cc4925315144b32596537c275"+diff --git a/tasks/robosuite-cube-stack-i00/README.md b/tasks/robosuite-cube-stack-i00/README.mdnew file mode 100644index 0000000000..8d391a6651--- /dev/null+++ b/tasks/robosuite-cube-stack-i00/README.md@@ -0,0 +1,19 @@+# robosuite-cube-stack-i00++| | |+|---|---|+| Simulator / robot | robosuite / franka-panda |+| Family / instance | `cube_stack` / seed 00 |+| Task type / tier | trajectory / privileged |+| Base image | `ghcr.io/jameskrw/rcb-robosuite:0.1.0` |+| Agent budget | 3600 s |++## Difficulty+<!-- Why is this instance non-trivial for a coding agent? Which primitive interactions matter? -->++## Reference solution+cap-x's human-written oracle for `cube_stack` (`solution/solve.sh` records it into a trajectory).++## Verification+Open-loop replay of `/app/output/trajectory.npz` from `tests/instance.npz` in a fresh process, twice;+pass iff the task predicate holds after every replay and the final-state hashes agree (`rcb.grade`).diff --git a/tasks/robosuite-cube-stack-i00/environment/Dockerfile b/tasks/robosuite-cube-stack-i00/environment/Dockerfilenew file mode 100644index 0000000000..c386275165--- /dev/null+++ b/tasks/robosuite-cube-stack-i00/environment/Dockerfile@@ -0,0 +1,7 @@+# Base image = cap-x robosuite environment (see images/robosuite/). Everything task-specific is copied here.+FROM ghcr.io/jameskrw/rcb-robosuite:0.1.1+COPY instance.npz /app/instance.npz+COPY rcb_traj.py /opt/tools/rcb_traj.py+ENV PYTHONPATH=/opt/tools+RUN mkdir -p /app/output+WORKDIR /appdiff --git a/tasks/robosuite-cube-stack-i00/environment/instance.npz b/tasks/robosuite-cube-stack-i00/environment/instance.npznew file mode 100644index 0000000000..322f8a43deBinary files /dev/null and b/tasks/robosuite-cube-stack-i00/environment/instance.npz differdiff --git a/tasks/robosuite-cube-stack-i00/environment/rcb_traj.py b/tasks/robosuite-cube-stack-i00/environment/rcb_traj.pynew file mode 100644index 0000000000..f47a08bc49--- /dev/null+++ b/tasks/robosuite-cube-stack-i00/environment/rcb_traj.py@@ -0,0 +1,352 @@+"""+rcb_traj.py — task-local tooling: frozen-instance / record / deterministic-replay utilities for cap-x robosuite envs.++Concepts+--------+instance : a frozen initial MuJoCo state (qpos/qvel after cap-x reset+settle) saved to .npz.+ This *is* the task instance; seeds alone are not enough because robosuite's robot+ initialization noise uses an unseeded RNG.+trajectory : the sequence of low-level robosuite actions (T, 9) = 7 joint targets + 2 gripper,+ captured by hooking `_do_robosuite_step`. Replaying it open-loop from the same+ instance state must reproduce the outcome (MuJoCo is deterministic on CPU).++CLI+---+ python rcb_traj.py make-instance --task cube_stack --out inst.npz [--seed 3]+ python rcb_traj.py run-oracle --task cube_stack --instance inst.npz --code solution/oracle_cube_stack.py --out traj.npz+ python rcb_traj.py replay --task cube_stack --instance inst.npz --traj traj.npz [--repeat 3]+ python rcb_traj.py selftest --task cube_stack --seed 3 --code oracle.py # make-instance + oracle + replay, asserts equality+ python rcb_traj.py render --task cube_stack --instance inst.npz --traj traj.npz --out replay.mp4 [--wrist]++Python (what the agent gets)+----------------------------+ from rcb_traj import Session+ s = Session("cube_stack", instance="inst.npz") # starts pyroki IK server if needed+ s.reset() # always back to the frozen instance state+ s.primitives() # dict of privileged primitives (goto_pose, ...)+ s.record_start(); ...; actions = s.record_stop()+ s.save_trajectory(actions, "traj.npz")+ s.replay(actions) -> dict(success=bool, reward=float, n_steps=int)+"""+from __future__ import annotations++import argparse+import hashlib+import json+import os+import socket+import subprocess+import sys+import time+from pathlib import Path+from typing import Any, Callable++import numpy as np++os.environ.setdefault("MUJOCO_GL", "egl")++# --------------------------------------------------------------------------- task family registry+TASKS: dict[str, dict] = {+ "cube_stack": dict(+ exec_env="capx.envs.tasks.franka.franka_pick_place.FrankaPickPlaceCodeEnv",+ low_level="franka_robosuite_cubes_low_level",+ apis=["FrankaControlPrivilegedApi"],+ text="Stack the red cube on top of the green cube with the Franka arm, then release it so it stays stacked.",+ simulator="robosuite", robot="franka-panda", image="robosuite",+ ),+}+++PYROKI_PORT = int(os.environ.get("CAPX_PYROKI_PORT", "8116"))+++def _import(path: str):+ mod, _, name = path.rpartition(".")+ return getattr(__import__(mod, fromlist=[name]), name)+++def _port_open(port: int, host: str = "127.0.0.1") -> bool:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.settimeout(0.3)+ return s.connect_ex((host, port)) == 0+++def ensure_pyroki_server(port: int = PYROKI_PORT, timeout: float = 120.0) -> subprocess.Popen | None:+ """Start cap-x's pyroki IK server in a subprocess if nothing listens on `port`."""+ if _port_open(port):+ return None+ code = (+ "from capx.serving.launch_pyroki_server import main;"+ f"main(robot='panda_description', target_link='panda_hand', port={port}, host='127.0.0.1')"+ )+ log = open(os.environ.get("CAPX_PYROKI_LOG", "/tmp/pyroki_server.log"), "ab")+ proc = subprocess.Popen([sys.executable, "-c", code], stdout=log, stderr=subprocess.STDOUT)+ t0 = time.time()+ while time.time() - t0 < timeout:+ if _port_open(port):+ return proc+ if proc.poll() is not None:+ raise RuntimeError(f"pyroki server exited early (rc={proc.returncode}); see {log.name}")+ time.sleep(0.5)+ raise TimeoutError("pyroki server did not come up")+++# --------------------------------------------------------------------------- session+class Session:+ def __init__(self, task: str, instance: str | Path | None = None, enable_render: bool = False):+ if task not in TASKS:+ raise KeyError(f"unknown task {task!r}; known: {list(TASKS)}")+ self.task = task+ self._pyroki = ensure_pyroki_server()++ # cap-x resolves its controller config relative to the repo root; make the Session cwd-independent+ capx_root = os.environ.get("CAPX_ROOT", "/opt/cap-x")+ if not os.path.isdir("capx/integrations") and os.path.isdir(capx_root):+ os.chdir(capx_root)+ import capx.envs.tasks # noqa: F401 (registers envs/apis)+ from capx.envs.tasks.base import CodeExecEnvConfig++ spec = TASKS[task]+ cfg = CodeExecEnvConfig(+ low_level=spec["low_level"],+ apis=spec["apis"],+ privileged=True,+ enable_render=enable_render,+ )+ self.env = _import(spec["exec_env"])(cfg)+ self.low = self.env.low_level_env++ self._recording: list[np.ndarray] | None = None+ self._orig_step: Callable = self.low._do_robosuite_step+ self.low._do_robosuite_step = self._hooked_step # type: ignore[method-assign]++ self.instance_state: np.ndarray | None = None+ if instance is not None:+ self.load_instance(instance)++ @property+ def sim(self):+ # robosuite hard-resets recreate MjSim, so never cache it+ return self.low.robosuite_env.sim++ # ---- hooks+ def _hooked_step(self, action: np.ndarray) -> None:+ if self._recording is not None:+ self._recording.append(np.array(action, dtype=np.float64, copy=True))+ self._orig_step(action)++ # ---- instance handling+ def _fresh_reset(self, seed: int | None = None) -> None:+ if seed is not None:+ # in-place reseed so the placement sampler (which shares this rng) follows+ self.low.robosuite_env.rng.bit_generator.state = np.random.default_rng(seed).bit_generator.state+ np.random.seed(seed)+ self.env.reset(seed=seed)++ def _restore_wrapper_bookkeeping(self) -> None:+ """After sim.set_state: sync MuJoCo derived quantities, controller goals, robosuite's+ cached observables, and the cap-x wrapper's cached robot state."""+ rs = self.low.robosuite_env+ self.sim.forward()+ # controller interpolators were initialised from the (noisy) fresh-reset pose; re-anchor them+ for c in rs.robots[0].composite_controller.part_controllers.values():+ c.update(force=True)+ c.reset_goal()+ # robosuite caches observables (object poses!) — refresh so primitives see the restored scene+ rs._update_observables(force=True)+ idx = rs.robots[0]._ref_joint_pos_indexes+ self.low._current_joints = np.array(self.sim.data.qpos[idx], dtype=np.float64)+ self.low._set_gripper(1.0)+ self.low.gripper_link_wxyz_xyz = np.concatenate(+ [self.sim.data.xquat[self.low.gripper_link_idx], self.sim.data.xpos[self.low.gripper_link_idx]]+ )+ self.low._step_count = 0+ self.low._sim_step_count = 0+ for api in self.env._apis.values(): # drop IK warm-start caches+ if hasattr(api, "cfg"):+ api.cfg = None++ def _snapshot(self) -> np.ndarray:+ d = self.sim.data+ return np.concatenate([self.sim.get_state().flatten(), np.asarray(d.qacc_warmstart, dtype=np.float64)])++ def _restore(self, snap: np.ndarray) -> None:+ nwarm = self.sim.model.nv+ self.sim.set_state_from_flattened(snap[:-nwarm].copy())+ self.sim.data.qacc_warmstart[:] = snap[-nwarm:]++ def make_instance(self, seed: int | None = None) -> np.ndarray:+ self._fresh_reset(seed)+ self.instance_state = self._snapshot()+ return self.instance_state++ def save_instance(self, path: str | Path, seed: int | None = None) -> None:+ assert self.instance_state is not None+ np.savez(path, state=self.instance_state, task=self.task, seed=-1 if seed is None else seed,+ sha=self.state_sha())++ def load_instance(self, path: str | Path) -> None:+ d = np.load(path, allow_pickle=False)+ if str(d["task"]) != self.task:+ raise ValueError(f"instance task {d['task']} != session task {self.task}")+ self.instance_state = np.array(d["state"], dtype=np.float64)+ self.reset()++ def state_sha(self) -> str:+ return hashlib.sha1(np.ascontiguousarray(self._snapshot()).tobytes()).hexdigest()[:12]++ def reset(self) -> None:+ """Return to the frozen instance state (fresh controller, then restore qpos/qvel)."""+ if self.instance_state is None:+ raise RuntimeError("no instance loaded; call make_instance() or load_instance()")+ self._recording = None+ self._fresh_reset()+ self._restore(self.instance_state)+ self._restore_wrapper_bookkeeping()++ # ---- primitives for the agent+ def primitives(self) -> dict[str, Callable]:+ fns: dict[str, Callable] = {}+ for api in self.env._apis.values():+ fns.update(api.functions())+ return fns++ def exec_code(self, code: str) -> dict[str, Any]:+ """Run agent code with primitives in scope (same semantics as cap-x's executor)."""+ g: dict[str, Any] = {"__name__": "__main__", "np": np, "env": self.low, **self.primitives()}+ try:+ exec(code, g, g)+ return {"ok": True}+ except BaseException as exc: # noqa: BLE001+ return {"ok": False, "error": repr(exc)}++ # ---- recording+ def record_start(self) -> None:+ self._recording = []++ def record_stop(self) -> np.ndarray:+ acts = np.array(self._recording or [], dtype=np.float64).reshape(-1, 9)+ self._recording = None+ return acts++ def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:+ assert self.instance_state is not None+ np.savez(+ path,+ actions=np.asarray(actions, dtype=np.float64),+ task=self.task,+ instance_sha=hashlib.sha1(np.ascontiguousarray(self.instance_state).tobytes()).hexdigest()[:12],+ action_layout="7 joint position targets (rad) + 2 gripper (-1 open, +1 closed), one row per sim control step",+ meta=json.dumps(meta or {}),+ )++ # ---- status / replay+ def status(self) -> dict[str, Any]:+ return {+ "success": bool(self.low.task_completed()),+ "reward": float(self.low.compute_reward()),+ "sim_steps": int(self.low._sim_step_count),+ "state_sha": self.state_sha(),+ }++ def replay(self, actions: np.ndarray) -> dict[str, Any]:+ self.reset()+ for a in np.asarray(actions, dtype=np.float64):+ self._orig_step(a)+ self.low._sim_step_count += 1+ return self.status()++ def render_video(self, actions: np.ndarray, path: str | Path, *, every: int = 5, fps: int = 20,+ wrist: bool = False) -> dict[str, Any]:+ """Replay `actions` from the frozen instance and write a human-viewable MP4 (needs enable_render=True).+ Frames are taken every `every` sim steps from the scene camera (and the wrist camera if `wrist`).+ Returns status() plus n_frames. Rendering is for humans; the verdict comes from replay()."""+ import imageio.v2 as imageio+ if not getattr(self.env.cfg, "enable_render", False):+ raise RuntimeError("render_video needs Session(..., enable_render=True)")+ self.reset()+ grab = (lambda: np.concatenate([self.low.render(), self.low.render_wrist()], axis=1)) if wrist else self.low.render+ frames = [grab()]+ for i, a in enumerate(np.asarray(actions, dtype=np.float64)):+ self._orig_step(a)+ self.low._sim_step_count += 1+ if (i + 1) % every == 0:+ frames.append(grab())+ frames.append(grab())+ path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), np.ascontiguousarray(frames[-1]))+ return {**self.status(), "n_frames": len(frames), "video": str(path)}++ def close(self) -> None:+ if self._pyroki is not None:+ self._pyroki.terminate()+++# --------------------------------------------------------------------------- CLI+def _load_traj(path: str) -> np.ndarray:+ return np.load(path, allow_pickle=False)["actions"]+++def cmd_make_instance(a):+ s = Session(a.task)+ s.make_instance(a.seed)+ s.save_instance(a.out, a.seed)+ print(json.dumps({"instance": a.out, "sha": s.state_sha(), **s.status()}))+++def cmd_run_oracle(a):+ s = Session(a.task, instance=a.instance)+ code = open(a.code).read()+ s.record_start()+ r = s.exec_code(code)+ acts = s.record_stop()+ st = s.status()+ s.save_trajectory(acts, a.out, meta={"source": "oracle", "exec": r})+ print(json.dumps({"traj": a.out, "n_actions": int(len(acts)), "exec": r, **st}))+++def cmd_replay(a):+ s = Session(a.task, instance=a.instance)+ acts = _load_traj(a.traj)+ outs = [s.replay(acts) for _ in range(a.repeat)]+ print(json.dumps({"n_actions": int(len(acts)), "replays": outs,+ "all_success": all(o["success"] for o in outs),+ "deterministic": len({o["state_sha"] for o in outs}) == 1}))+++def cmd_render(a):+ s = Session(a.task, instance=a.instance, enable_render=True)+ out = s.render_video(_load_traj(a.traj), a.out, every=a.every, fps=a.fps, wrist=a.wrist)+ print(json.dumps(out))+++def cmd_selftest(a):+ s = Session(a.task)+ s.make_instance(a.seed)+ sha0 = s.state_sha()+ s.reset(); assert s.state_sha() == sha0, "reset() does not restore instance state"+ s.record_start(); r = s.exec_code(open(a.code).read()); acts = s.record_stop()+ live = s.status()+ rep = [s.replay(acts) for _ in range(a.repeat)]+ ok = live["success"] and all(x["success"] for x in rep) and len({x["state_sha"] for x in rep}) == 1 \+ and rep[0]["state_sha"] == live["state_sha"]+ print(json.dumps({"oracle_exec": r, "live": live, "replays": rep, "n_actions": int(len(acts)), "PASS": ok}, indent=1))+ sys.exit(0 if ok else 1)+++def main():+ p = argparse.ArgumentParser()+ sub = p.add_subparsers(dest="cmd", required=True)+ q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--out", required=True); q.add_argument("--seed", type=int); q.set_defaults(fn=cmd_make_instance)+ q = sub.add_parser("run-oracle"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True); q.add_argument("--code", required=True, help="python file run with primitives in scope"); q.add_argument("--out", required=True); q.set_defaults(fn=cmd_run_oracle)+ q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True); q.add_argument("--traj", required=True); q.add_argument("--repeat", type=int, default=2); q.set_defaults(fn=cmd_replay)+ q = sub.add_parser("render"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True); q.add_argument("--traj", required=True); q.add_argument("--out", required=True); q.add_argument("--every", type=int, default=5); q.add_argument("--fps", type=int, default=20); q.add_argument("--wrist", action="store_true"); q.set_defaults(fn=cmd_render)+ q = sub.add_parser("selftest"); q.add_argument("--task", default="cube_stack"); q.add_argument("--code", required=True); q.add_argument("--seed", type=int, default=0); q.add_argument("--repeat", type=int, default=2); q.set_defaults(fn=cmd_selftest)+ a = p.parse_args(); a.fn(a)+++if __name__ == "__main__":+ main()diff --git a/tasks/robosuite-cube-stack-i00/instruction.md b/tasks/robosuite-cube-stack-i00/instruction.mdnew file mode 100644index 0000000000..b041e67b51--- /dev/null+++ b/tasks/robosuite-cube-stack-i00/instruction.md@@ -0,0 +1,30 @@+# cube_stack — instance 00++You control a simulated franka-panda arm (robosuite / MuJoCo) via Python. **Task:** Stack the red cube on top of the green cube with the Franka arm, then release it so it stays stacked.++This is a *fixed scene instance*: object poses never change between resets. You may reset and retry as many+times as you want. Your deliverable is **one replayable trajectory**, not a general policy.++## Deliverable+Write the final trajectory to `/app/output/trajectory.npz` with `Session.save_trajectory(...)` (below).+It is replayed open-loop from the same initial state in a fresh process and scored 1 if the task is+completed at the end of the replay, else 0. Also leave the script that produced it at `/app/output/gen.py`.++## Tooling (already installed; run `python` from any directory)+```python+from rcb_traj import Session+s = Session("cube_stack", instance="/app/instance.npz") # builds the env, starts the IK server if needed+s.reset() # back to the frozen initial state (unlimited)+p = s.primitives() # dict of callables, e.g. p["goto_pose"](pos, quat_wxyz, z_approach=0.1)+help(p["goto_pose"]) # every primitive has a docstring; read them+s.low # low-level cap-x env (robosuite env at s.low.robosuite_env) for closed-loop control+s.record_start(); ...; actions = s.record_stop() # actions: (T, 9) joint targets + gripper, one row per sim step+s.status() # {'success': bool, 'reward': float, 'sim_steps': int, ...}+s.replay(actions) # resets, replays open-loop, returns status -> use this to self-check+s.save_trajectory(actions, "/app/output/trajectory.npz")+```+CLI equivalent of the grader:+`python /opt/tools/rcb_traj.py replay --task cube_stack --instance /app/instance.npz --traj /app/output/trajectory.npz`++Optional rendering: `Session("cube_stack", instance=..., enable_render=True)` then `s.low.render()` returns an RGB+array (software rendering, slow). Coordinates are in the robot base frame; quaternions are WXYZ.diff --git a/tasks/robosuite-cube-stack-i00/solution/oracle_cube_stack.py b/tasks/robosuite-cube-stack-i00/solution/oracle_cube_stack.pynew file mode 100644index 0000000000..cc56cd464d--- /dev/null+++ b/tasks/robosuite-cube-stack-i00/solution/oracle_cube_stack.py@@ -0,0 +1,32 @@+# Human-written reference solution for cube_stack (from cap-x FrankaPickPlaceCodeEnv.ORACLE_CODE, MIT).+# Runs inside Session.exec_code(): primitives are in scope. Never shipped in the agent image.+import numpy as np++_, _, green_ext = get_object_pose("green cube", return_bbox_extent=True)+_, _, red_ext = get_object_pose("red cube", return_bbox_extent=True)++# Sample a grasp pose for the red cube and pick it up+pick_pos, pick_quat = sample_grasp_pose("red cube")+goto_pose(pick_pos, pick_quat, z_approach=0.1)+close_gripper()+# Lift the red cube after grasping+post_pick_pos = pick_pos.copy()+post_pick_pos[2] += 0.2+goto_pose(post_pick_pos, pick_quat)++# Compute placement pose on top of the green cube+green_pos, _, _ = get_object_pose("green cube", return_bbox_extent=False)++place_pos = green_pos.copy()+place_pos[2] = green_pos[2] + green_ext[2]/2 + red_ext[2]/2+# Use down orientation for placement+place_quat = np.array([0.0, 0.0, 1.0, 0.0])++# Approach and place the red cube on the green cube+goto_pose(place_pos, pick_quat, z_approach=0.1)+open_gripper()++# Retract after placing+post_place_pos = place_pos.copy()+post_place_pos[2] += 0.1+goto_pose(post_place_pos, place_quat)diff --git a/tasks/robosuite-cube-stack-i00/solution/solve.sh b/tasks/robosuite-cube-stack-i00/solution/solve.shnew file mode 100755index 0000000000..2453065d10--- /dev/null+++ b/tasks/robosuite-cube-stack-i00/solution/solve.sh@@ -0,0 +1,7 @@+#!/bin/bash+# Oracle: run the human-written reference solution (kept in solution/, never in the agent image) and record it.+set -e+mkdir -p /app/output+cd /opt/cap-x+python /opt/tools/rcb_traj.py run-oracle --task cube_stack --instance /app/instance.npz --code /solution/oracle_cube_stack.py --out /app/output/trajectory.npz+cp /solution/oracle_cube_stack.py /app/output/gen.pydiff --git a/tasks/robosuite-cube-stack-i00/task.toml b/tasks/robosuite-cube-stack-i00/task.tomlnew file mode 100644index 0000000000..62d19d3f2e--- /dev/null+++ b/tasks/robosuite-cube-stack-i00/task.toml@@ -0,0 +1,29 @@+schema_version = "1.3"+artifacts = ["/app/output/"]++[task]+name = "robot-coding-bench/robosuite-cube-stack-i00"+description = "robosuite cube_stack: produce one replayable trajectory for frozen scene instance 00."+authors = [{ name = "kangrui" }]+keywords = ["robotics", "robosuite", "franka-panda", "code-as-policy", "trajectory", "cube_stack"]++[metadata]+author_name = "kangrui"+task_type = "trajectory" # trajectory | policy (see docs/PROTOCOL.md)+simulator = "robosuite"+robot = "franka-panda"+family = "cube_stack"+tier = "privileged" # privileged (state-based perception) | perception (RGB-D models)+instance_seed = 0 # scene = environment/instance.npz (frozen MuJoCo state); identity = dataset.toml digest+expert_time_estimate_hours = 0.5++[verifier]+timeout_sec = 900.0++[agent]+timeout_sec = 3600.0++[environment]+build_timeout_sec = 1800.0+cpus = 4+memory_mb = 16384diff --git a/tasks/robosuite-cube-stack-i00/tests/grade.py b/tasks/robosuite-cube-stack-i00/tests/grade.pynew file mode 100644index 0000000000..ccdae7fa36--- /dev/null+++ b/tasks/robosuite-cube-stack-i00/tests/grade.py@@ -0,0 +1,63 @@+"""Verifier entry point: replay /app/output/trajectory.npz from the frozen instance and write Harbor rewards.++ python /tests/grade.py --family cube_stack --instance /tests/instance.npz --traj /app/output/trajectory.npz++Writes /logs/verifier/reward.txt (1/0), reward.json (numeric fields only — Harbor rejects strings), and a+human-viewable replay video /logs/verifier/replay.mp4 (scene + wrist camera) plus replay.last.png.+Replays `--repeat` times in this fresh process; success requires every replay to complete the task AND+all final-state hashes to agree (bit-exact determinism), so a lucky non-deterministic run cannot pass.+"""+from __future__ import annotations+import argparse, json, os, sys, traceback+import numpy as np++LOG_DIR = os.environ.get("RCB_VERIFIER_LOG_DIR", "/logs/verifier")+++def write(ok: bool, out: dict) -> None:+ os.makedirs(LOG_DIR, exist_ok=True)+ open(os.path.join(LOG_DIR, "reward.txt"), "w").write("1\n" if ok else "0\n")+ json.dump(out, open(os.path.join(LOG_DIR, "reward.json"), "w"))+ print(json.dumps(out))+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--family", required=True); ap.add_argument("--instance", required=True)+ ap.add_argument("--traj", default="/app/output/trajectory.npz"); ap.add_argument("--repeat", type=int, default=2)+ ap.add_argument("--no-video", action="store_true"); ap.add_argument("--video-every", type=int, default=5); ap.add_argument("--video-fps", type=int, default=20)+ a = ap.parse_args()+ if not os.path.isfile(a.traj):+ write(False, {"success": 0, "missing_trajectory": 1, "grader_error": 0}); return 0+ try:+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))); from rcb_traj import Session+ s = Session(a.family, instance=a.instance)+ d = np.load(a.traj, allow_pickle=False)+ if str(d["task"]) != a.family:+ write(False, {"success": 0, "wrong_family": 1, "grader_error": 0}); return 0+ acts = d["actions"]+ outs = [s.replay(acts) for _ in range(a.repeat)]+ all_success = all(o["success"] for o in outs)+ deterministic = len({o["state_sha"] for o in outs}) == 1+ ok = all_success and deterministic+ out = {"success": int(ok), "all_success": int(all_success), "deterministic": int(deterministic),+ "n_actions": int(len(acts)), "final_reward": float(outs[0]["reward"]),+ "sim_steps": int(outs[0]["sim_steps"]), "grader_error": 0, "video_rendered": 0}+ # Human-viewable replay video (never affects the verdict): /logs/verifier/replay.mp4 + replay.last.png+ if not a.no_video:+ try:+ s.close()+ sv = Session(a.family, instance=a.instance, enable_render=True)+ sv.render_video(acts, os.path.join(LOG_DIR, "replay.mp4"), every=a.video_every, fps=a.video_fps, wrist=True)+ out["video_rendered"] = 1+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(ok, out)+ except Exception: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ write(False, {"success": 0, "grader_error": 1})+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tasks/robosuite-cube-stack-i00/tests/instance.npz b/tasks/robosuite-cube-stack-i00/tests/instance.npznew file mode 100644index 0000000000..322f8a43deBinary files /dev/null and b/tasks/robosuite-cube-stack-i00/tests/instance.npz differdiff --git a/tasks/robosuite-cube-stack-i00/tests/rcb_traj.py b/tasks/robosuite-cube-stack-i00/tests/rcb_traj.pynew file mode 100644index 0000000000..f47a08bc49--- /dev/null+++ b/tasks/robosuite-cube-stack-i00/tests/rcb_traj.py@@ -0,0 +1,352 @@+"""+rcb_traj.py — task-local tooling: frozen-instance / record / deterministic-replay utilities for cap-x robosuite envs.++Concepts+--------+instance : a frozen initial MuJoCo state (qpos/qvel after cap-x reset+settle) saved to .npz.+ This *is* the task instance; seeds alone are not enough because robosuite's robot+ initialization noise uses an unseeded RNG.+trajectory : the sequence of low-level robosuite actions (T, 9) = 7 joint targets + 2 gripper,+ captured by hooking `_do_robosuite_step`. Replaying it open-loop from the same+ instance state must reproduce the outcome (MuJoCo is deterministic on CPU).++CLI+---+ python rcb_traj.py make-instance --task cube_stack --out inst.npz [--seed 3]+ python rcb_traj.py run-oracle --task cube_stack --instance inst.npz --code solution/oracle_cube_stack.py --out traj.npz+ python rcb_traj.py replay --task cube_stack --instance inst.npz --traj traj.npz [--repeat 3]+ python rcb_traj.py selftest --task cube_stack --seed 3 --code oracle.py # make-instance + oracle + replay, asserts equality+ python rcb_traj.py render --task cube_stack --instance inst.npz --traj traj.npz --out replay.mp4 [--wrist]++Python (what the agent gets)+----------------------------+ from rcb_traj import Session+ s = Session("cube_stack", instance="inst.npz") # starts pyroki IK server if needed+ s.reset() # always back to the frozen instance state+ s.primitives() # dict of privileged primitives (goto_pose, ...)+ s.record_start(); ...; actions = s.record_stop()+ s.save_trajectory(actions, "traj.npz")+ s.replay(actions) -> dict(success=bool, reward=float, n_steps=int)+"""+from __future__ import annotations++import argparse+import hashlib+import json+import os+import socket+import subprocess+import sys+import time+from pathlib import Path+from typing import Any, Callable++import numpy as np++os.environ.setdefault("MUJOCO_GL", "egl")++# --------------------------------------------------------------------------- task family registry+TASKS: dict[str, dict] = {+ "cube_stack": dict(+ exec_env="capx.envs.tasks.franka.franka_pick_place.FrankaPickPlaceCodeEnv",+ low_level="franka_robosuite_cubes_low_level",+ apis=["FrankaControlPrivilegedApi"],+ text="Stack the red cube on top of the green cube with the Franka arm, then release it so it stays stacked.",+ simulator="robosuite", robot="franka-panda", image="robosuite",+ ),+}+++PYROKI_PORT = int(os.environ.get("CAPX_PYROKI_PORT", "8116"))+++def _import(path: str):+ mod, _, name = path.rpartition(".")+ return getattr(__import__(mod, fromlist=[name]), name)+++def _port_open(port: int, host: str = "127.0.0.1") -> bool:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ s.settimeout(0.3)+ return s.connect_ex((host, port)) == 0+++def ensure_pyroki_server(port: int = PYROKI_PORT, timeout: float = 120.0) -> subprocess.Popen | None:+ """Start cap-x's pyroki IK server in a subprocess if nothing listens on `port`."""+ if _port_open(port):+ return None+ code = (+ "from capx.serving.launch_pyroki_server import main;"+ f"main(robot='panda_description', target_link='panda_hand', port={port}, host='127.0.0.1')"+ )+ log = open(os.environ.get("CAPX_PYROKI_LOG", "/tmp/pyroki_server.log"), "ab")+ proc = subprocess.Popen([sys.executable, "-c", code], stdout=log, stderr=subprocess.STDOUT)+ t0 = time.time()+ while time.time() - t0 < timeout:+ if _port_open(port):+ return proc+ if proc.poll() is not None:+ raise RuntimeError(f"pyroki server exited early (rc={proc.returncode}); see {log.name}")+ time.sleep(0.5)+ raise TimeoutError("pyroki server did not come up")+++# --------------------------------------------------------------------------- session+class Session:+ def __init__(self, task: str, instance: str | Path | None = None, enable_render: bool = False):+ if task not in TASKS:+ raise KeyError(f"unknown task {task!r}; known: {list(TASKS)}")+ self.task = task+ self._pyroki = ensure_pyroki_server()++ # cap-x resolves its controller config relative to the repo root; make the Session cwd-independent+ capx_root = os.environ.get("CAPX_ROOT", "/opt/cap-x")+ if not os.path.isdir("capx/integrations") and os.path.isdir(capx_root):+ os.chdir(capx_root)+ import capx.envs.tasks # noqa: F401 (registers envs/apis)+ from capx.envs.tasks.base import CodeExecEnvConfig++ spec = TASKS[task]+ cfg = CodeExecEnvConfig(+ low_level=spec["low_level"],+ apis=spec["apis"],+ privileged=True,+ enable_render=enable_render,+ )+ self.env = _import(spec["exec_env"])(cfg)+ self.low = self.env.low_level_env++ self._recording: list[np.ndarray] | None = None+ self._orig_step: Callable = self.low._do_robosuite_step+ self.low._do_robosuite_step = self._hooked_step # type: ignore[method-assign]++ self.instance_state: np.ndarray | None = None+ if instance is not None:+ self.load_instance(instance)++ @property+ def sim(self):+ # robosuite hard-resets recreate MjSim, so never cache it+ return self.low.robosuite_env.sim++ # ---- hooks+ def _hooked_step(self, action: np.ndarray) -> None:+ if self._recording is not None:+ self._recording.append(np.array(action, dtype=np.float64, copy=True))+ self._orig_step(action)++ # ---- instance handling+ def _fresh_reset(self, seed: int | None = None) -> None:+ if seed is not None:+ # in-place reseed so the placement sampler (which shares this rng) follows+ self.low.robosuite_env.rng.bit_generator.state = np.random.default_rng(seed).bit_generator.state+ np.random.seed(seed)+ self.env.reset(seed=seed)++ def _restore_wrapper_bookkeeping(self) -> None:+ """After sim.set_state: sync MuJoCo derived quantities, controller goals, robosuite's+ cached observables, and the cap-x wrapper's cached robot state."""+ rs = self.low.robosuite_env+ self.sim.forward()+ # controller interpolators were initialised from the (noisy) fresh-reset pose; re-anchor them+ for c in rs.robots[0].composite_controller.part_controllers.values():+ c.update(force=True)+ c.reset_goal()+ # robosuite caches observables (object poses!) — refresh so primitives see the restored scene+ rs._update_observables(force=True)+ idx = rs.robots[0]._ref_joint_pos_indexes+ self.low._current_joints = np.array(self.sim.data.qpos[idx], dtype=np.float64)+ self.low._set_gripper(1.0)+ self.low.gripper_link_wxyz_xyz = np.concatenate(+ [self.sim.data.xquat[self.low.gripper_link_idx], self.sim.data.xpos[self.low.gripper_link_idx]]+ )+ self.low._step_count = 0+ self.low._sim_step_count = 0+ for api in self.env._apis.values(): # drop IK warm-start caches+ if hasattr(api, "cfg"):+ api.cfg = None++ def _snapshot(self) -> np.ndarray:+ d = self.sim.data+ return np.concatenate([self.sim.get_state().flatten(), np.asarray(d.qacc_warmstart, dtype=np.float64)])++ def _restore(self, snap: np.ndarray) -> None:+ nwarm = self.sim.model.nv+ self.sim.set_state_from_flattened(snap[:-nwarm].copy())+ self.sim.data.qacc_warmstart[:] = snap[-nwarm:]++ def make_instance(self, seed: int | None = None) -> np.ndarray:+ self._fresh_reset(seed)+ self.instance_state = self._snapshot()+ return self.instance_state++ def save_instance(self, path: str | Path, seed: int | None = None) -> None:+ assert self.instance_state is not None+ np.savez(path, state=self.instance_state, task=self.task, seed=-1 if seed is None else seed,+ sha=self.state_sha())++ def load_instance(self, path: str | Path) -> None:+ d = np.load(path, allow_pickle=False)+ if str(d["task"]) != self.task:+ raise ValueError(f"instance task {d['task']} != session task {self.task}")+ self.instance_state = np.array(d["state"], dtype=np.float64)+ self.reset()++ def state_sha(self) -> str:+ return hashlib.sha1(np.ascontiguousarray(self._snapshot()).tobytes()).hexdigest()[:12]++ def reset(self) -> None:+ """Return to the frozen instance state (fresh controller, then restore qpos/qvel)."""+ if self.instance_state is None:+ raise RuntimeError("no instance loaded; call make_instance() or load_instance()")+ self._recording = None+ self._fresh_reset()+ self._restore(self.instance_state)+ self._restore_wrapper_bookkeeping()++ # ---- primitives for the agent+ def primitives(self) -> dict[str, Callable]:+ fns: dict[str, Callable] = {}+ for api in self.env._apis.values():+ fns.update(api.functions())+ return fns++ def exec_code(self, code: str) -> dict[str, Any]:+ """Run agent code with primitives in scope (same semantics as cap-x's executor)."""+ g: dict[str, Any] = {"__name__": "__main__", "np": np, "env": self.low, **self.primitives()}+ try:+ exec(code, g, g)+ return {"ok": True}+ except BaseException as exc: # noqa: BLE001+ return {"ok": False, "error": repr(exc)}++ # ---- recording+ def record_start(self) -> None:+ self._recording = []++ def record_stop(self) -> np.ndarray:+ acts = np.array(self._recording or [], dtype=np.float64).reshape(-1, 9)+ self._recording = None+ return acts++ def save_trajectory(self, actions: np.ndarray, path: str | Path, meta: dict | None = None) -> None:+ assert self.instance_state is not None+ np.savez(+ path,+ actions=np.asarray(actions, dtype=np.float64),+ task=self.task,+ instance_sha=hashlib.sha1(np.ascontiguousarray(self.instance_state).tobytes()).hexdigest()[:12],+ action_layout="7 joint position targets (rad) + 2 gripper (-1 open, +1 closed), one row per sim control step",+ meta=json.dumps(meta or {}),+ )++ # ---- status / replay+ def status(self) -> dict[str, Any]:+ return {+ "success": bool(self.low.task_completed()),+ "reward": float(self.low.compute_reward()),+ "sim_steps": int(self.low._sim_step_count),+ "state_sha": self.state_sha(),+ }++ def replay(self, actions: np.ndarray) -> dict[str, Any]:+ self.reset()+ for a in np.asarray(actions, dtype=np.float64):+ self._orig_step(a)+ self.low._sim_step_count += 1+ return self.status()++ def render_video(self, actions: np.ndarray, path: str | Path, *, every: int = 5, fps: int = 20,+ wrist: bool = False) -> dict[str, Any]:+ """Replay `actions` from the frozen instance and write a human-viewable MP4 (needs enable_render=True).+ Frames are taken every `every` sim steps from the scene camera (and the wrist camera if `wrist`).+ Returns status() plus n_frames. Rendering is for humans; the verdict comes from replay()."""+ import imageio.v2 as imageio+ if not getattr(self.env.cfg, "enable_render", False):+ raise RuntimeError("render_video needs Session(..., enable_render=True)")+ self.reset()+ grab = (lambda: np.concatenate([self.low.render(), self.low.render_wrist()], axis=1)) if wrist else self.low.render+ frames = [grab()]+ for i, a in enumerate(np.asarray(actions, dtype=np.float64)):+ self._orig_step(a)+ self.low._sim_step_count += 1+ if (i + 1) % every == 0:+ frames.append(grab())+ frames.append(grab())+ path = Path(path); path.parent.mkdir(parents=True, exist_ok=True)+ with imageio.get_writer(str(path), fps=fps, format="FFMPEG", codec="libx264", macro_block_size=1) as w:+ for f in frames:+ w.append_data(np.ascontiguousarray(f))+ imageio.imwrite(str(path.with_suffix(".last.png")), np.ascontiguousarray(frames[-1]))+ return {**self.status(), "n_frames": len(frames), "video": str(path)}++ def close(self) -> None:+ if self._pyroki is not None:+ self._pyroki.terminate()+++# --------------------------------------------------------------------------- CLI+def _load_traj(path: str) -> np.ndarray:+ return np.load(path, allow_pickle=False)["actions"]+++def cmd_make_instance(a):+ s = Session(a.task)+ s.make_instance(a.seed)+ s.save_instance(a.out, a.seed)+ print(json.dumps({"instance": a.out, "sha": s.state_sha(), **s.status()}))+++def cmd_run_oracle(a):+ s = Session(a.task, instance=a.instance)+ code = open(a.code).read()+ s.record_start()+ r = s.exec_code(code)+ acts = s.record_stop()+ st = s.status()+ s.save_trajectory(acts, a.out, meta={"source": "oracle", "exec": r})+ print(json.dumps({"traj": a.out, "n_actions": int(len(acts)), "exec": r, **st}))+++def cmd_replay(a):+ s = Session(a.task, instance=a.instance)+ acts = _load_traj(a.traj)+ outs = [s.replay(acts) for _ in range(a.repeat)]+ print(json.dumps({"n_actions": int(len(acts)), "replays": outs,+ "all_success": all(o["success"] for o in outs),+ "deterministic": len({o["state_sha"] for o in outs}) == 1}))+++def cmd_render(a):+ s = Session(a.task, instance=a.instance, enable_render=True)+ out = s.render_video(_load_traj(a.traj), a.out, every=a.every, fps=a.fps, wrist=a.wrist)+ print(json.dumps(out))+++def cmd_selftest(a):+ s = Session(a.task)+ s.make_instance(a.seed)+ sha0 = s.state_sha()+ s.reset(); assert s.state_sha() == sha0, "reset() does not restore instance state"+ s.record_start(); r = s.exec_code(open(a.code).read()); acts = s.record_stop()+ live = s.status()+ rep = [s.replay(acts) for _ in range(a.repeat)]+ ok = live["success"] and all(x["success"] for x in rep) and len({x["state_sha"] for x in rep}) == 1 \+ and rep[0]["state_sha"] == live["state_sha"]+ print(json.dumps({"oracle_exec": r, "live": live, "replays": rep, "n_actions": int(len(acts)), "PASS": ok}, indent=1))+ sys.exit(0 if ok else 1)+++def main():+ p = argparse.ArgumentParser()+ sub = p.add_subparsers(dest="cmd", required=True)+ q = sub.add_parser("make-instance"); q.add_argument("--task", required=True); q.add_argument("--out", required=True); q.add_argument("--seed", type=int); q.set_defaults(fn=cmd_make_instance)+ q = sub.add_parser("run-oracle"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True); q.add_argument("--code", required=True, help="python file run with primitives in scope"); q.add_argument("--out", required=True); q.set_defaults(fn=cmd_run_oracle)+ q = sub.add_parser("replay"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True); q.add_argument("--traj", required=True); q.add_argument("--repeat", type=int, default=2); q.set_defaults(fn=cmd_replay)+ q = sub.add_parser("render"); q.add_argument("--task", required=True); q.add_argument("--instance", required=True); q.add_argument("--traj", required=True); q.add_argument("--out", required=True); q.add_argument("--every", type=int, default=5); q.add_argument("--fps", type=int, default=20); q.add_argument("--wrist", action="store_true"); q.set_defaults(fn=cmd_render)+ q = sub.add_parser("selftest"); q.add_argument("--task", default="cube_stack"); q.add_argument("--code", required=True); q.add_argument("--seed", type=int, default=0); q.add_argument("--repeat", type=int, default=2); q.set_defaults(fn=cmd_selftest)+ a = p.parse_args(); a.fn(a)+++if __name__ == "__main__":+ main()diff --git a/tasks/robosuite-cube-stack-i00/tests/test.sh b/tasks/robosuite-cube-stack-i00/tests/test.shnew file mode 100755index 0000000000..615a77fcc7--- /dev/null+++ b/tasks/robosuite-cube-stack-i00/tests/test.sh@@ -0,0 +1,6 @@+#!/bin/bash+# Verifier: replay /app/output/trajectory.npz from the frozen instance (the tests/ copy) in a fresh process.+# Writes /logs/verifier/reward.txt (1/0) and reward.json (numeric fields, see docs/PROTOCOL.md).+cd /opt/cap-x+python /tests/grade.py --family cube_stack --instance /tests/instance.npz --traj /app/output/trajectory.npz --repeat 2 \+ 2> /logs/verifier/grade.logdiff --git a/third_party/cap-x b/third_party/cap-xnew file mode 160000index 0000000000..53e9966d7a--- /dev/null+++ b/third_party/cap-x@@ -0,0 +1 @@+Subproject commit 53e9966d7a8e2fa7494676772bccc35280f5c0ed