This repository ships a standard coding-agent skill at .agents/skills/xharness-quickstart/SKILL.md alongside AGENTS.md and docs/AGENT_HANDOFF.md so Claude Code, Codex, Cursor, and Jetski automatically follow all 11 invariants.
Operating manual for coding agents working in this repository. Read this before changing anything. The symbol-level reference and the step-by-step playbooks are in docs/AGENT_HANDOFF.md.
#What this repository is
X-Harness: policy code between a vision-language model (VLM) and a robot's base policy (a VLA). The VLM writes a small program; the program calls the base policy, perception tools and motion primitives; the harness runs it, rescues it, and improves it from training episodes.
#Commands
pip install -e ".[dev]"
pytest -q # full CPU suite, no network (~1 min)
xharness wizard --non-interactive # preflight + recipe recommendation
xharness list # benchmarks and their status
xharness doctor # what this machine can run
xharness doctor libero # check simulator, env vars & extras
xharness run --program programs/mock/pick_cube/reference.py \
--replay replay.html
python examples/01_quickstart.py
python scripts/verify_released_logs.py --local-dir ./x-as-policies \
--check-integrity --summary
python scripts/replay_released_policy.py --local-dir ./x-as-policies \
--list --benchmark libero --runnable-only
python scripts/render_tables.py --check # tables vs results/paper_tables.jsonRun the whole suite before you call a change done. Tests in other files scan the source tree (tests/test_import_hygiene.py, tests/test_release_hygiene.py) and can fail on a file you only added.
#File map
| Path | What is there |
|---|---|
x_harness/program/contract.py | the program contract: three methods, the action dict |
x_harness/program/host.py | ProgramHost: static audit, guarded builtins, per-call deadlines |
x_harness/program/forms.py | the five structured code forms and their interpreters |
x_harness/tools/vision.py | Vision: detect, get_scene_graph, track, analyze_demo_video, depth, tools, call budgets; ColorPerception |
x_harness/tools/toolbox.py | @register_tool, ToolBox, built-in geometry tools |
x_harness/tools/perception*.py | perception client, server and model wrappers |
x_harness/tools/scene_graph.py, x_harness/tools/geometry/ | 3D scene graphs; multi-view geometry, boxes, in-hand pose, contact search |
x_harness/tools/metric_depth.py, tool_bank.py | reference implementations (labeled as such) |
x_harness/tools/skill_cards.py | helper functions and lessons carried between tasks |
x_harness/policies/ | policy interface and checkpoint catalog (base.py), adapters.py, transports.py |
x_harness/harness/runner.py | the one episode loop, the three tiers, evaluate, recommend_tier |
x_harness/harness/replay.py | pure-stdlib + NumPy PNG encoder and self-contained HTML episode replay viewer |
x_harness/harness/rescue.py | watchdog, rules, bounded take-over, records |
x_harness/harness/evolution.py | selection gate, evolution loop, frozen programs |
x_harness/harness/context.py | what a model is told; how its reply is read |
x_harness/harness/vlm.py | model clients, ReplyCache, CachedVLM, ScriptedVLM |
x_harness/benchmarks/base.py | Benchmark, Episode, BenchmarkSpec, ActionContract, scene graph, registry |
x_harness/benchmarks/sim.py | the adapter over the simulator packages |
x_harness/benchmarks/<name>/ | tasks.py, contract.py, and per benchmark env.py, primitives.py, perception.py, facts.py |
x_harness/benchmarks/real_yam/ | real-robot client: wire.py, env.py, runtime.py, run.py, profiles.py |
x_harness/core/ | errors.py, split_guard.py, stats.py |
x_harness/cli.py | the xharness command (list, doctor, wizard, run, evolve, freeze, serve-policy, serve-perception) |
.agents/skills/xharness-quickstart/SKILL.md | standard coding-agent onboarding skill |
scripts/verify_released_logs.py, scripts/replay_released_policy.py | offline verifier and policy replay CLI for Hugging Face dataset yuxianglai117/x-as-policies |
scripts/serve_perception.py | localhost 3D perception server (Grounding DINO + SAM 2 + CoTracker3) |
docs/benchmarks.md | benchmark protocols & #full-environment-setup isolated per-simulator + localhost server guide |
docs/released_artifacts.md | Hugging Face released policies & rollout logs guide |
programs/ | frozen programs and FROZEN.json manifests |
results/paper_tables.json | source of truth for rendered tables in README.md, docs/results.md, and docs/benchmarks.md |
tests/ | the suite; tests/golden/characterization.json holds recorded behavior |
#The eleven invariants
Break none of these. Each has a test; do not weaken the test to pass.
- One program contract.
class Programwithset_task(instruction, obs, vision),get_action(),update_step(outcome, obs, vision). An action is a dict with"control". Each benchmark'scontract.pydefines which controls and fields it accepts;validate_actionruns before any action reaches a simulator or a robot. Do not add a second contract or a per-benchmark calling convention. - Units and frames are fixed. Metres; degrees for angles in actions; z up. Image points and boxes are (row, col) and
[row0, col0, row1, col1], never xyxy. Depth is int16 millimetres with 0 for unknown.T_w2cis world-to-camera in OpenCV axes. The gripper sign is +1 open, -1 closed everywhere. Each benchmark's action frame is stated in itscontract.py. - Split discipline. Training and test seeds are disjoint sets per benchmark. Evolution, rescue tuning and any selection use training seeds only. A test episode needs
allow_test=Trueand is appended to an access log.Episode.diagnostics()raises on a test episode. Never route test information to a model. - No simulator state at test time. Policy code and tools get images, depth, calibration and the robot's own state: never ground-truth object poses, masks or success flags.
diagnostics()is for training episodes only. - Two error classes, never mixed.
ProgramError: the policy code is at fault; the episode fails.InfrastructureError: a simulator, server, network or model endpoint is at fault; it propagates and is never scored. Never catch a broadExceptionaround an episode and record a failure: that turns a broken setup into a 0% result. This was a bug of the previous code base. - Light imports.
import x_harness, everytasks.py,contract.py,perception.py,facts.py, and the command line import with numpy alone and read no environment variable at import. Simulator packages are imported only insideenv.py/primitives.py, which load when an episode is made. - Frozen artifacts are never overwritten. A frozen program's name is taken for good;
FROZEN.jsonentries are added, not edited; a run directory is created new. To change a program, freeze a new one. - Model-written code is untrusted. It runs only through
ProgramHost(audit, guarded builtins, deadlines). Neverexecor import a model's reply directly. The host is not a sandbox; say so wherever it matters. - Real-robot gates are never weakened. Dry run by default; motion needs
--execute-motionand a word typed by the operator; the bridge is localhost only; the policy server must match the profile; a whole reply is validated before its first target is sent; 30 Hz pacing; a hold infinally; exit codes 0, 1, 2; masked phases; the memory-removed control. Tests intests/test_real_yam*.pycover each. - No internal names. No experiment codes, version tags, cluster paths, job ids or private script names in any tracked file, docstrings included.
tests/test_release_hygiene.pyenforces a list of patterns. - No new core dependency. The core needs numpy. Anything else goes behind an extra in
pyproject.tomland is imported inside the function that needs it.
#Six failure modes to recognize
| What you see | What it usually is | What to do |
|---|---|---|
| 0% success on every task | an infrastructure fault swallowed somewhere and counted as failures | look for a broad except around an episode; the runner must let InfrastructureError out |
| vision calls return nothing, programs fail quietly | the perception server is down or unreachable | Vision with no backend raises InfrastructureError; check XHARNESS_PERCEPTION_URL and the server's /health |
| plausible but wrong actions, low success | a different checkpoint behind the right address | pin the server's identity: RoboMME's client and Real YAM's profile check the server's metadata |
| a server "fails to start" or a client talks to the wrong one | two jobs on one machine chose the same port | bind port 0 and read the port back (--ready-file), or give each job its own port |
| a test passes on one Python and fails on another | version differences (for example threading.Thread internals changed between 3.11 and 3.13) | do not name attributes after library internals; CI runs the suite across Python 3.10–3.13 |
| a program hangs the run | a deadline that cannot fire | off the main thread a call cannot be interrupted: the host stops waiting and refuses later calls (host.stuck); run episodes on the main thread when you can |
#How to work here
- Match the surrounding code: small modules, docstrings that state facts and units, no decorative comments.
- Keep documentation honest: a status of "Adapter ready (needs external sim)" means not run here. Do not write that something is verified unless a test in this repository runs it.
- Numbers in
README.md,docs/results.md, anddocs/benchmarks.mdcome fromresults/paper_tables.jsonand benchmark specs throughscripts/render_tables.py --write. Never type a result into a document. - When you add a module, add its test, then run the whole suite.
- Before you finish:
pytest -q,python scripts/render_tables.py --check, andgit statusshows no stray files.
#Agent Handoff: Schemas & Playbooks
For a coding agent that has to change this repository. AGENTS.md has the invariants; this file has the exact shapes and seven step-by-step playbooks. Every path is relative to the repository root.
#1. Schemas
#Program (policy code)
class Program: # built without arguments, one instance per episode
def set_task(self, instruction, obs, vision): ... # once
def get_action(self) -> dict: ... # the next action
def update_step(self, outcome, obs, vision): ... # after every actionSource: x_harness/program/contract.py (METHODS, CONTROLS, CONTRACT_TEXT, check_action_shape).
#obs
Built by the benchmark's Episode.observe(). Common keys:
| Key | Value |
|---|---|
cameras | {name: {"rgb": uint8 (H, W, 3), "depth": int16 (H, W) millimetres, 0 unknown, or None, "K": 3x3, "T_w2c": 3x4 or 4x4}} |
tcp | {"xyz": [x, y, z], "gripper_opening_m", "holding", "gripper_command", angles...}; two-arm robots: per arm |
controls | the control names this robot accepts |
xyz_bounds | [[x0, x1], [y0, y1], [z0, z1]] of positions in actions |
remaining_steps, env_step | ints |
demo_frames | list of uint8 (H, W, 3) RGB frames (RoboMME video-demo tasks only) |
Real YAM differs (no depth, no calibration): images, state, left, right, valid_prompts, phase_hint (x_harness/benchmarks/real_yam/env.py: program_obs).
#Action
{"control": name, ...fields, "note"?: str}. The union over benchmarks:
| Control | Fields | Notes |
|---|---|---|
move | xyz, yaw_deg?, pitch_deg?, roll_deg?, gripper? | angles relative to a top-down gripper |
pick, place | xyz, angles? | macros: approach, descend, close or open, lift |
push | xyz, xyz_end, angles?, gripper? | |
gripper | value in [-1, 1] | +1 open, -1 closed |
hold | steps | |
policy | instruction, steps | the base policy drives; RoboMME allows instruction: None |
done | the program says the task is complete | |
move_both | left: {...}, right: {...} | RoboTwin only; arm controls there also need "arm" |
abort | Real YAM only: refuse the episode |
Each benchmark's subset, bounds and caps: x_harness/benchmarks/<name>/contract.py. The check is shared: x_harness/benchmarks/base.py: ActionContract.validate.
#Outcome
A dict with at least control and status. Mock: status in reached, unreachable, done; plus steps, env_step, success, tcp_xyz, holding. Simulator packages add their own keys (each facts.py lists them in OUTCOME_TEXT).
#Episode result (run_episode, one row of evaluate)
status (success, done, failed, step_limit, program_error, rescue_done, rescue_exhausted, aborted), success, steps, budget, actions, program_error, vlm_calls, rescue (summary or None), latency, vision, tier, program_sha256; in evaluate also seed, progress, optionally trace (when trace=True, public camera frames, TCP/gripper state, actions, outcomes, rescue triggers — never diagnostics), and on the train split diagnostics.
#Rescue record
{"kind", "rescue_mode", "trigger", "turn", "outcome", "env_step", ...} with kind in trigger, turn, handback, exhausted, predone_check, progress_check, layer1_end. rescue.check_records(records, mode) returns the problems of an episode's records.
#FROZEN.json
See programs/README.md . Read with evolution.load_frozen(path), write with evolution.write_frozen / freeze_file / EvolutionLoop(out=...).
#BenchmarkSpec
name, display_name, robot, engine, cameras, depth, controls, train_seeds, test_seeds, shipped_tasks, paper_tasks, status, requires, setup, policies, example_tasks, notes (x_harness/benchmarks/base.py). status is one of four strings (STATUSES).
#Errors
| Class | Meaning | Handling |
|---|---|---|
ProgramError | the policy code is at fault | the episode fails (or a rescue takes over) |
AuditError (a ValueError) | a program source the audit refuses | before anything runs |
InfrastructureError | simulator, server, network, model endpoint | propagates; never scored |
ToolInputError (a ValueError) | a tool call with bad arguments | inside the program: the program's fault |
SplitViolation | a seed used outside its split, or test access without permission | propagates |
#2. Symbols by task
| I need to... | Use |
|---|---|
| build a benchmark | x_harness.make_benchmark(name, policy=..., allow_test=..., **options) |
| run guided setup & preflight | xharness wizard (or xharness wizard --non-interactive --json) |
| run a program over seeds | x_harness.evaluate(benchmark, source, task, seeds, split=, tier=, vlm=, trace=) |
| run one episode | x_harness.run_episode(host, episode, vision, rescue=None, trace=None) |
| export browser HTML replay | x_harness.export_replay(episodes, path, benchmark=, task=) or xharness run ... --replay out.html |
| load and audit a program | x_harness.ProgramHost(source, form=); audit_source(source) for the problems only |
| get the model's prompt | x_harness.harness.context.build_context(benchmark, task, form=) |
| call a model | x_harness.make_vlm(provider, model=, effort=); .generate(contents, system=, effort=) -> .text |
| script a model in a test | x_harness.ScriptedVLM([reply, ...]) or ScriptedVLM(lambda contents, system: reply) |
| evolve | x_harness.EvolutionLoop(benchmark, task, vlm, rounds=, out=, effort=, skill_library=).run() |
| rescue | x_harness.Rescue(vlm, mode=, thresholds=, effort=) passed to run_episode |
| register a tool | @x_harness.register_tool(category=) |
| register a benchmark | x_harness.register_benchmark(name, factory, spec) |
| compare two arms statistically | x_harness.core.stats.paired_table, pair_stats, holm |
| verify released rollout logs | python scripts/verify_released_logs.py --local-dir ./x-as-policies --check-integrity --summary |
| replay or dry-run a released policy | python scripts/replay_released_policy.py --local-dir ./x-as-policies --program-id <id> --dry-run |
| start localhost 3D perception server | python scripts/serve_perception.py --port 8765 --depth (or xharness serve-perception) |
#3. Playbooks
Each ends with the same check: pytest -q passes and git status shows only the files you meant to change.
#3.1 Add a benchmark
cp -r x_harness/benchmarks/_template x_harness/benchmarks/<name>.tasks.py: the task table,TRAIN_SEEDS,TEST_SEEDS(disjoint). Standard library only.contract.py: anActionContractwith your controls, bounds and caps;validate_action(action, robot).env.py: anEpisodesubclass:observe,execute(validate first; raiseInfrastructureErrorfor faults of the simulator),over,success,diagnostics(callsuper().diagnostics()first). Import the simulator here, not intasks.pyorcontract.py.__init__.py: aBenchmarkSpecwith an honeststatus, andmake(**options).- Register it in
x_harness/benchmarks/__init__.py(BUILT_IN), or callregister_benchmarkfrom your code. - Tests: a contract test (accepted and refused actions), and an episode test if it runs on a CPU. Add the name to the lists in
tests/test_benchmarks.pyandtests/test_import_hygiene.pythat it belongs to. python scripts/render_tables.py --writeupdates the README's benchmark table.
#3.2 Add a policy server
- In-process policy: any object with
predict(obs, instruction)(and optionallyreset(seed)), or a function. Pass it asmake_benchmark("mock", policy=...). - Over HTTP:
x_harness.policies.transports.serve_policy_http(policy, port=...)servesPOST /act; the client side isHTTPPolicy(url)or the address aspolicy=. - An OpenPI websocket server:
OpenPIWebSocketTransport(url); needs thewsextra. - For a simulator benchmark the observation is built by that package's
primitives.py(VLAClient); the address comes frommake_benchmark(name, policy="ws://...")orXHARNESS_POLICY_URL. To serve another checkpoint, write a server that answers that package's request format (documented in itsprimitives.pyorvla_server.py). - Every transport fault must raise
InfrastructureError.
#3.3 Add a tool
- Write a pure function in
x_harness/tools/(or your own module) and decorate it with@register_tool(category=...). The first paragraph of its docstring is what the model reads. - Inputs: plain arrays and the camera dict of
obs. Pixels are (row, col). RaiseToolInputErrorfor bad input. - No simulator state, no file or network access unless that is the tool's purpose (then say so).
- Test it on synthetic data with a known answer (
tests/test_tools.py).
#3.4 Add a code form
- In
x_harness/program/forms.py: add the name toFORMS, aGUIDE[name]text for the model, and an interpreter class withset_task,get_action,update_stepbuilt from the program's namespace. - Add it to
INTERPRETERS; giveform_problemsa static check if the form has rules a parser can check. - One runnable test in
tests/test_forms.py: a small program in the form, driven throughProgramHost.
#3.5 Add a rescue trigger
- A physical trigger: subclass
Watchdog(or passarms_of=and aThresholds) inx_harness/harness/rescue.py; return the trigger's name fromobserve. - Add the name to
TRIGGERS. If it should be gated by a question, add it toPROGRESS_TRIGGERSand ask inRescue.after_step. - Extend
check_recordsso a finished episode's records can be verified. - Tests in
tests/test_rescue.py: the trigger fires on synthetic outcomes, does not fire on healthy ones, and an end-to-end episode withScriptedVLM.
#3.6 Change the selection gate
SelectionGate(max_regressions=..., ungated=...)covers the paper's variants. For another rule, subclass and overridedecide(champion, candidate) -> {"accept", "verdict", "fixed", "regressed"}.- Add the verdict's sentence to
verdict_text(the model reads it in the next round). - Test the rule alone on stand-in evaluations and once in the loop (
tests/test_evolution.py). - Never let a gate read test episodes:
EvolutionLooponly has training seeds, keep it that way.
#3.7 Reproduce one cell of the results table
This needs what the repository does not ship: the simulator, the checkpoint behind a policy server, a perception server, and a model endpoint. You can also inspect, dry-run, or replay the paper's frozen evolved policies directly from Hugging Face (yuxianglai117/x-as-policies) using scripts/replay_released_policy.py and verify the released rollout logs offline on CPU with scripts/verify_released_logs.py (see released_artifacts.md).
- Follow Full environment setup to install the target simulator in an isolated conda/venv environment, then run
xharness doctor <benchmark>and install anything missing. - Start the local
127.0.0.1perception server (python scripts/serve_perception.py --port 8765 --depth/xharness serve-perception) and base policy server in separate terminals/envs as described in Full environment setup; setXHARNESS_PERCEPTION_URLandXHARNESS_POLICY_URL. - Baseline first: run the policy-alone wrapper on the training seeds of one task (
EvolutionLoop.wrapper_source()gives the program). If this fails withInfrastructureError, fix the setup before anything else. xharness evolve --benchmark <name> --task <task> --vlm-model <id> --cache replies.jsonl --out programs/<name>/<task>/<model>.py.xharness run --program programs/<name>/<task>/<model>.py --split test --allow-test(or replay a released frozen policy viapython scripts/replay_released_policy.py --local-dir ./x-as-policies --program-id <id> --split test --allow-test).- Compare with the paper using the same task set and seeds: full task tables ship here for
libero(40/40),maniskill(14/14),robocasa(50/50),robotwin(50/50),simpler(6/6), andvlabench(50/49); onlyrobomme(14/16, 2 stick tasks unadapted) androbodojo(0/42, external specification) remain partial (see benchmarks.md).
#Bundled Quickstart Skill (SKILL.md)
Follow this workflow when onboarding a user or setting up an X-Harness experiment.
#1. Read invariants before changing code
- Read AGENTS.md for the 11 architectural invariants (single
Programcontract,(row, col)pixel coordinates, int16 millimetre depth,+1open /-1closed gripper sign, train/test split discipline,ProgramErrorvsInfrastructureErrorseparation, lightweight NumPy-only core imports). - Use docs/AGENT_HANDOFF.md for exact symbol signatures and extension playbooks.
- Use docs/HUMAN_GUIDE.md for the 15-minute CPU walkthrough.
- Use docs/benchmarks.md#full-environment-setup for isolated per-simulator + localhost server setup, and docs/released_artifacts.md for the Hugging Face released policies and rollout logs.
#2. Install and run preflight
pip install -e .
xharness doctor
xharness listmockis always ready on CPU with NumPy alone.- External simulators report their exact missing packages and setup instructions via
xharness doctor <benchmark>.
#3. Pick a harness recipe with the wizard
Run the interactive setup wizard (or pass flags directly for scripting):
xharness wizard
# Non-interactive example:
xharness wizard --non-interactive --benchmark mock \
--task button_unmask_swap --vla shift --vlm frontier --tier semi_onlineThe wizard runs preflight checks, maps the user's robot regime through x_harness.recommend_tier(...), and prints ready-to-run xharness run and xharness evolve commands.
#4. Run and visually inspect an episode
xharness run --program programs/mock/button_unmask_swap/policy_alone.py \
--seeds 1000
xharness run --program programs/mock/button_unmask_swap/reference.py \
--seeds 1000 --replay replay.html
# Compares Offline vs. triggered Semi-online rescue
python examples/01_quickstart.pyOpening replay.html in a browser renders camera frames, TCP and gripper state, actions, outcomes, errors, and triggered rescue steps without requiring a server or extra packages. Pass --tier semi_online --vlm-model <model-id> to xharness run to enable live triggered rescue.
#5. Full benchmark environment setup (simulators + localhost servers)
Install each real simulator (robomme, libero, maniskill, robotwin, robocasa, simpler, vlabench) in its own isolated conda/venv environment, and run the 3D perception server (python scripts/serve_perception.py --port 8765) and base policy server as local 127.0.0.1 processes in separate terminals/envs (XHARNESS_PERCEPTION_URL, XHARNESS_POLICY_URL). Confirm readiness with xharness doctor <benchmark>. See docs/benchmarks.md#full-environment-setup.
#6. Verify & replay released policies and rollout logs
Download the companion Hugging Face dataset (yuxianglai117/x-as-policies) or pass --hf-repo yuxianglai117/x-as-policies to verify rollout logs offline on CPU and dry-run/replay released evolved policies:
hf download yuxianglai117/x-as-policies --repo-type dataset \
--local-dir ./x-as-policies
python scripts/verify_released_logs.py --local-dir ./x-as-policies \
--check-integrity --summary
python scripts/replay_released_policy.py --local-dir ./x-as-policies \
--list --benchmark libero --runnable-only
python scripts/replay_released_policy.py --local-dir ./x-as-policies \
--program-id <program_id> --dry-runSee docs/released_artifacts.md for full CLI flags and live simulator replay usage.
#7. Verify before finishing any repo edit
pytest -q
python scripts/render_tables.py --check