BUNDLED AGENT SKILL

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

bash
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.json

Run 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

PathWhat is there
x_harness/program/contract.pythe program contract: three methods, the action dict
x_harness/program/host.pyProgramHost: static audit, guarded builtins, per-call deadlines
x_harness/program/forms.pythe five structured code forms and their interpreters
x_harness/tools/vision.pyVision: 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*.pyperception 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.pyreference implementations (labeled as such)
x_harness/tools/skill_cards.pyhelper functions and lessons carried between tasks
x_harness/policies/policy interface and checkpoint catalog (base.py), adapters.py, transports.py
x_harness/harness/runner.pythe one episode loop, the three tiers, evaluate, recommend_tier
x_harness/harness/replay.pypure-stdlib + NumPy PNG encoder and self-contained HTML episode replay viewer
x_harness/harness/rescue.pywatchdog, rules, bounded take-over, records
x_harness/harness/evolution.pyselection gate, evolution loop, frozen programs
x_harness/harness/context.pywhat a model is told; how its reply is read
x_harness/harness/vlm.pymodel clients, ReplyCache, CachedVLM, ScriptedVLM
x_harness/benchmarks/base.pyBenchmark, Episode, BenchmarkSpec, ActionContract, scene graph, registry
x_harness/benchmarks/sim.pythe 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.pythe xharness command (list, doctor, wizard, run, evolve, freeze, serve-policy, serve-perception)
.agents/skills/xharness-quickstart/SKILL.mdstandard coding-agent onboarding skill
scripts/verify_released_logs.py, scripts/replay_released_policy.pyoffline verifier and policy replay CLI for Hugging Face dataset yuxianglai117/x-as-policies
scripts/serve_perception.pylocalhost 3D perception server (Grounding DINO + SAM 2 + CoTracker3)
docs/benchmarks.mdbenchmark protocols & #full-environment-setup isolated per-simulator + localhost server guide
docs/released_artifacts.mdHugging Face released policies & rollout logs guide
programs/frozen programs and FROZEN.json manifests
results/paper_tables.jsonsource 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.

  1. One program contract. class Program with set_task(instruction, obs, vision), get_action(), update_step(outcome, obs, vision). An action is a dict with "control". Each benchmark's contract.py defines which controls and fields it accepts; validate_action runs before any action reaches a simulator or a robot. Do not add a second contract or a per-benchmark calling convention.
  2. 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_w2c is world-to-camera in OpenCV axes. The gripper sign is +1 open, -1 closed everywhere. Each benchmark's action frame is stated in its contract.py.
  3. 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=True and is appended to an access log. Episode.diagnostics() raises on a test episode. Never route test information to a model.
  4. 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.
  5. 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 broad Exception around an episode and record a failure: that turns a broken setup into a 0% result. This was a bug of the previous code base.
  6. Light imports. import x_harness, every tasks.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 inside env.py / primitives.py, which load when an episode is made.
  7. Frozen artifacts are never overwritten. A frozen program's name is taken for good; FROZEN.json entries are added, not edited; a run directory is created new. To change a program, freeze a new one.
  8. Model-written code is untrusted. It runs only through ProgramHost (audit, guarded builtins, deadlines). Never exec or import a model's reply directly. The host is not a sandbox; say so wherever it matters.
  9. Real-robot gates are never weakened. Dry run by default; motion needs --execute-motion and 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 in finally; exit codes 0, 1, 2; masked phases; the memory-removed control. Tests in tests/test_real_yam*.py cover each.
  10. 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.py enforces a list of patterns.
  11. No new core dependency. The core needs numpy. Anything else goes behind an extra in pyproject.toml and is imported inside the function that needs it.

#Six failure modes to recognize

What you seeWhat it usually isWhat to do
0% success on every taskan infrastructure fault swallowed somewhere and counted as failureslook for a broad except around an episode; the runner must let InfrastructureError out
vision calls return nothing, programs fail quietlythe perception server is down or unreachableVision with no backend raises InfrastructureError; check XHARNESS_PERCEPTION_URL and the server's /health
plausible but wrong actions, low successa different checkpoint behind the right addresspin 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 onetwo jobs on one machine chose the same portbind 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 anotherversion 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 runa deadline that cannot fireoff 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, and docs/benchmarks.md come from results/paper_tables.json and benchmark specs through scripts/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, and git status shows 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)

python
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 action

Source: x_harness/program/contract.py (METHODS, CONTROLS, CONTRACT_TEXT, check_action_shape).

#obs

Built by the benchmark's Episode.observe(). Common keys:

KeyValue
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
controlsthe control names this robot accepts
xyz_bounds[[x0, x1], [y0, y1], [z0, z1]] of positions in actions
remaining_steps, env_stepints
demo_frameslist 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:

ControlFieldsNotes
movexyz, yaw_deg?, pitch_deg?, roll_deg?, gripper?angles relative to a top-down gripper
pick, placexyz, angles?macros: approach, descend, close or open, lift
pushxyz, xyz_end, angles?, gripper?
grippervalue in [-1, 1]+1 open, -1 closed
holdsteps
policyinstruction, stepsthe base policy drives; RoboMME allows instruction: None
donethe program says the task is complete
move_bothleft: {...}, right: {...}RoboTwin only; arm controls there also need "arm"
abortReal 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

ClassMeaningHandling
ProgramErrorthe policy code is at faultthe episode fails (or a rescue takes over)
AuditError (a ValueError)a program source the audit refusesbefore anything runs
InfrastructureErrorsimulator, server, network, model endpointpropagates; never scored
ToolInputError (a ValueError)a tool call with bad argumentsinside the program: the program's fault
SplitViolationa seed used outside its split, or test access without permissionpropagates

#2. Symbols by task

I need to...Use
build a benchmarkx_harness.make_benchmark(name, policy=..., allow_test=..., **options)
run guided setup & preflightxharness wizard (or xharness wizard --non-interactive --json)
run a program over seedsx_harness.evaluate(benchmark, source, task, seeds, split=, tier=, vlm=, trace=)
run one episodex_harness.run_episode(host, episode, vision, rescue=None, trace=None)
export browser HTML replayx_harness.export_replay(episodes, path, benchmark=, task=) or xharness run ... --replay out.html
load and audit a programx_harness.ProgramHost(source, form=); audit_source(source) for the problems only
get the model's promptx_harness.harness.context.build_context(benchmark, task, form=)
call a modelx_harness.make_vlm(provider, model=, effort=); .generate(contents, system=, effort=) -> .text
script a model in a testx_harness.ScriptedVLM([reply, ...]) or ScriptedVLM(lambda contents, system: reply)
evolvex_harness.EvolutionLoop(benchmark, task, vlm, rounds=, out=, effort=, skill_library=).run()
rescuex_harness.Rescue(vlm, mode=, thresholds=, effort=) passed to run_episode
register a tool@x_harness.register_tool(category=)
register a benchmarkx_harness.register_benchmark(name, factory, spec)
compare two arms statisticallyx_harness.core.stats.paired_table, pair_stats, holm
verify released rollout logspython scripts/verify_released_logs.py --local-dir ./x-as-policies --check-integrity --summary
replay or dry-run a released policypython scripts/replay_released_policy.py --local-dir ./x-as-policies --program-id <id> --dry-run
start localhost 3D perception serverpython 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

  1. cp -r x_harness/benchmarks/_template x_harness/benchmarks/<name>.
  2. tasks.py: the task table, TRAIN_SEEDS, TEST_SEEDS (disjoint). Standard library only.
  3. contract.py: an ActionContract with your controls, bounds and caps; validate_action(action, robot).
  4. env.py: an Episode subclass: observe, execute (validate first; raise InfrastructureError for faults of the simulator), over, success, diagnostics (call super().diagnostics() first). Import the simulator here, not in tasks.py or contract.py.
  5. __init__.py: a BenchmarkSpec with an honest status, and make(**options).
  6. Register it in x_harness/benchmarks/__init__.py (BUILT_IN), or call register_benchmark from your code.
  7. 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.py and tests/test_import_hygiene.py that it belongs to.
  8. python scripts/render_tables.py --write updates the README's benchmark table.

#3.2 Add a policy server

  1. In-process policy: any object with predict(obs, instruction) (and optionally reset(seed)), or a function. Pass it as make_benchmark("mock", policy=...).
  2. Over HTTP: x_harness.policies.transports.serve_policy_http(policy, port=...) serves POST /act; the client side is HTTPPolicy(url) or the address as policy=.
  3. An OpenPI websocket server: OpenPIWebSocketTransport(url); needs the ws extra.
  4. For a simulator benchmark the observation is built by that package's primitives.py (VLAClient); the address comes from make_benchmark(name, policy="ws://...") or XHARNESS_POLICY_URL. To serve another checkpoint, write a server that answers that package's request format (documented in its primitives.py or vla_server.py).
  5. Every transport fault must raise InfrastructureError.

#3.3 Add a tool

  1. 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.
  2. Inputs: plain arrays and the camera dict of obs. Pixels are (row, col). Raise ToolInputError for bad input.
  3. No simulator state, no file or network access unless that is the tool's purpose (then say so).
  4. Test it on synthetic data with a known answer (tests/test_tools.py).

#3.4 Add a code form

  1. In x_harness/program/forms.py: add the name to FORMS, a GUIDE[name] text for the model, and an interpreter class with set_task, get_action, update_step built from the program's namespace.
  2. Add it to INTERPRETERS; give form_problems a static check if the form has rules a parser can check.
  3. One runnable test in tests/test_forms.py: a small program in the form, driven through ProgramHost.

#3.5 Add a rescue trigger

  1. A physical trigger: subclass Watchdog (or pass arms_of= and a Thresholds) in x_harness/harness/rescue.py; return the trigger's name from observe.
  2. Add the name to TRIGGERS. If it should be gated by a question, add it to PROGRESS_TRIGGERS and ask in Rescue.after_step.
  3. Extend check_records so a finished episode's records can be verified.
  4. Tests in tests/test_rescue.py: the trigger fires on synthetic outcomes, does not fire on healthy ones, and an end-to-end episode with ScriptedVLM.

#3.6 Change the selection gate

  1. SelectionGate(max_regressions=..., ungated=...) covers the paper's variants. For another rule, subclass and override decide(champion, candidate) -> {"accept", "verdict", "fixed", "regressed"}.
  2. Add the verdict's sentence to verdict_text (the model reads it in the next round).
  3. Test the rule alone on stand-in evaluations and once in the loop (tests/test_evolution.py).
  4. Never let a gate read test episodes: EvolutionLoop only 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).

  1. Follow Full environment setup to install the target simulator in an isolated conda/venv environment, then run xharness doctor <benchmark> and install anything missing.
  2. Start the local 127.0.0.1 perception 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; set XHARNESS_PERCEPTION_URL and XHARNESS_POLICY_URL.
  3. Baseline first: run the policy-alone wrapper on the training seeds of one task (EvolutionLoop.wrapper_source() gives the program). If this fails with InfrastructureError, fix the setup before anything else.
  4. xharness evolve --benchmark <name> --task <task> --vlm-model <id> --cache replies.jsonl --out programs/<name>/<task>/<model>.py.
  5. xharness run --program programs/<name>/<task>/<model>.py --split test --allow-test (or replay a released frozen policy via python scripts/replay_released_policy.py --local-dir ./x-as-policies --program-id <id> --split test --allow-test).
  6. 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), and vlabench (50/49); only robomme (14/16, 2 stick tasks unadapted) and robodojo (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 Program contract, (row, col) pixel coordinates, int16 millimetre depth, +1 open / -1 closed gripper sign, train/test split discipline, ProgramError vs InfrastructureError separation, 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

bash
pip install -e .
xharness doctor
xharness list
  • mock is 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):

bash
xharness wizard
# Non-interactive example:
xharness wizard --non-interactive --benchmark mock \
  --task button_unmask_swap --vla shift --vlm frontier --tier semi_online

The 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

bash
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.py

Opening 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:

bash
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-run

See docs/released_artifacts.md for full CLI flags and live simulator replay usage.

#7. Verify before finishing any repo edit

bash
pytest -q
python scripts/render_tables.py --check