Introduction
In the code-as-policies setting a frozen coding model receives a natural-language goal and the documentation of a robot API, and writes a Python program that is executed against a simulated robot. The loop does not have to stop there: after each executed block the policy sees the console output and renders of the scene, and may regenerate the rest of the program. CaP-X [1] frames the question this task asks: with the coder, the API, the execution loop and a per-trial model-call budget all fixed, which plan and replan policy turns the most trials into task successes?
Three properties of the problem shape our method.
The coder's programs fail for reasons that are mechanical, not conceptual. A program that understands the goal still fails if it mixes quaternion conventions, unprojects depth with the wrong transform, trusts a side-tilted grasp proposal, or spends the episode's physics steps on a dense loop of blocking motions. None of these is visible from the goal text.
Self-verification is unreliable. Deciding whether to stop means asking the same model whether it succeeded, and a model asked to check its own work is not a reliable judge of it [2]. A false "done" ends a recoverable trial; a false "not done" sends a new block into a scene that was already solved, where it can undo the success.
The policy may rehearse. An optional preparation step runs once per setting before the scored trials, with its own trials in which the simulator reports success. The field already uses rehearsal and execution feedback in different ways: a fix loop with evolutionary search [3], a skill library built from rehearsal rollouts [1], a graph of sub-policies learned by rehearsal [4], and code-based monitors for failure detection [5]. Our method uses rehearsal for two things at once: to choose a program, and to calibrate the verifier that decides when to stop.
Method
We call the method RC-CLSP (rehearsal-calibrated closed-loop state-machine policy). It has an
offline part, run in prepare, and an online part, run in initial_program and decide. Both
share one prompt-side component, a set of pre-loaded geometric helpers and program rules.
Pre-loaded geometry and guarded programs
Every block we execute is prefixed with a small pure-NumPy library of SE(3) and SO(3) primitives in the scalar-first convention: conversions between quaternions and rotation matrices (with an SVD projection onto , so a matrix with determinant cannot leave it), frames built from an approach axis, slerp, point transforms, depth-mask unprojection, a robust percentile-based bounding box, two grasp helpers, and a solver for the hand pose that puts a held object at a target pose through the rigid hand-to-object transform,
def solve_hand_for_target_obj_wxyz(cur_hand_pos, cur_hand_quat, cur_obj_pos, cur_obj_quat, target_obj_pos, target_obj_quat):
T_w_h = pose_to_se3_wxyz(cur_hand_pos, cur_hand_quat)
T_w_o = pose_to_se3_wxyz(cur_obj_pos, cur_obj_quat)
T_h_o = _se3_np.linalg.inv(T_w_h) @ T_w_o
T_w_o_des = pose_to_se3_wxyz(target_obj_pos, target_obj_quat)
T_w_h_des = T_w_o_des @ _se3_np.linalg.inv(T_h_o)
return se3_to_pose_wxyz(T_w_h_des)The grasp selector takes the grasp proposals of the perception API, transforms them to the world
frame first, keeps only those whose approach axis points down () and lie within
0.038 m of the object centre in the plane, and falls back to a centred top-down grasp, aligned with
the object's long axis when the object is clearly elongated, when none qualifies. A rule text tells the coder to use these helpers and
states a set of program disciplines: open the gripper before grasping, keep one quaternion through
grasp and lift, verify capture by a rise in height rather than by planar proximity, bound retries,
and print a FINAL_TELEMETRY line at the end.
Generated programs are also guarded. A program that calls exit() or quit() is rewritten through
its syntax tree so that those names raise a private exception inside a try block; the program ends
early, but the worker process that runs it does not.
def _sanitize_program(code: str) -> str:
"""Prevent `exit()`/`quit()` (`_sitebuiltins.Quitter` closing fd 0 and hanging worker IPC)
and catch `SystemExit` cleanly while keeping top-level globals intact."""
code = _strip_helpers(code)
if "class _StageEarlyReturn(" in code:
return code
try:
tree = ast.parse(code)
except Exception: # noqa: BLE001
return code
needs_guard = False
for node in ast.walk(tree):
if isinstance(node, ast.Name) and node.id in ("exit", "quit", "SystemExit"):
needs_guard = True
break
if isinstance(node, ast.Attribute) and node.attr == "exit":
needs_guard = True
break
if not needs_guard:
return code
prefix, rest = _hoist_future_imports(code)
indented = "\n".join((" " + ln if ln.strip() else "") for ln in rest.splitlines())
wrapped = (
f"{prefix}"
"class _StageEarlyReturn(Exception):\n"
" pass\n"
"def exit(*_a, **_k):\n"
" raise _StageEarlyReturn()\n"
"quit = exit\n"
"try:\n"
f"{indented}\n"
"except (_StageEarlyReturn, SystemExit):\n"
" pass\n"
)
return wrapped.strip("\n") if _parses(wrapped) else codeOffline: a four-stage rehearsal campaign
prepare runs four stages under a wall-clock cap of 2400 s, a cap on its own model calls and a
reserve of the shared budget.
Stage 1, probe. The coder writes a read-only introspection program (no motion), which we run as one rehearsal. It prints the shapes of observations, the camera-to-world transform tested both ways, the return arities of the pose and grasp getters, and the offset between grasp proposals and box centres. From that output the coder writes a short verified specification of the API contract and frame conventions, which every later prompt carries.
Stage 2, diverse screen with successive halving. The coder proposes four structurally distinct strategies, one program is written per strategy at increasing temperatures, and each is rehearsed. A crash is repaired once from its trace and the rendered first and last frames. Candidates are ranked by a smoothed success rate penalised by crashes and truncated episodes,
with passes, crashes and truncations in rehearsals; ties fall to the raw rate, then to the number of rehearsals, then to the shorter program. The top two candidates, and a third if it has any pass, are promoted to more rehearsals.
def _cand_rank_key(cand: dict) -> tuple[float, float, int, int]:
p, n, cr, tr = _cand_stats(cand["runs"])
if n == 0:
return (-1.0, -1.0, 0, -len(cand["code"]))
eb_rate = (p + 0.5) / (n + 1.0) - 0.04 * ((cr + tr) / n)
raw_rate = p / n
return (round(eb_rate, 5), round(raw_rate, 5), n, -len(cand["code"]))Stage 3, contrastive repair. Unless the best candidate has passed every one of at least six rehearsals, the coder is shown a leaderboard, the two best programs, up to two passing and four failing traces with the renders of two failing ones, and, in each of up to two rounds, is asked for two improved candidates (one a targeted root-cause fix, one a hybrid). When no candidate has passed at all, the prompt adds a checklist of common mechanical failures and the raw probe output. New candidates enter the same screen.
Stage 4, verifier calibration. The coder is shown terminal traces labelled by the simulator's success flag and asked for a JSON calibration: whether the task ends with an object held, the completion checks, the near-miss failure states that must not be mistaken for success, and recovery rules. We attach the last telemetry lines of passing and failing rehearsals as exemplars. The deployable artefact is then rehearsed end to end, and if any of those closed-loop rehearsals fails, the calibration is redone with those traces.
+ "\n\nCalibrate the online task-completion verifier and state-aware recovery playbook from these "
"ground-truth simulator outcomes. Note any benign perception artifacts present in PASS scenes "
"(for example, when a top object occludes the top face of a bottom stacked object, the bottom "
"object's single-face OBB `extent[2]` is naturally ~0.003-0.015m even in 100% PASS runs -- NEVER "
"treat that benign occlusion artifact as a failure!). Respond with JSON ONLY:\n"
"{\n"
' "requires_holding_at_end": <bool: true ONLY if the robot must still hold/lift/align an object in its hand when the trial ends; false if objects rest released on a surface/stack/container>,\n'
' "completion_checks": ["<quantitative telemetry + visual conditions that confirm true task success>", ...],\n'
' "near_miss_traps": ["<true failure states seen in FAIL traces that must NOT be mistaken for success>", ...],\n'
' "recovery_rules": ["<specific failure symptom -> concrete non-destructive recovery action from live state>", ...]\n'
"}",
images=imgs,
temperature=0.15,
)
cal = _extract_json_obj(cal_raw)
if isinstance(cal, dict):
raw_hold = cal.get("requires_holding_at_end", None)
self.calibration = {
"requires_holding_at_end": raw_hold if isinstance(raw_hold, bool) else None,
"completion_checks": [str(x)[:400] for x in (cal.get("completion_checks") or [])[:8]],
"near_miss_traps": [str(x)[:400] for x in (cal.get("near_miss_traps") or [])[:8]],
"recovery_rules": [str(x)[:400] for x in (cal.get("recovery_rules") or [])[:8]],
"pass_telemetry_examples": pass_ex,
"fail_telemetry_examples": fail_ex,
}The artefact holds the best program and its rehearsal record, a backup program that differs from it and has at least one pass, the verified specification and the calibration.
Online: replay, then a three-valued closed loop
At the start of a trial we replay the best rehearsed program, with no model call, if its rehearsal pass rate is at least 0.5 and the goal text matches the one it was rehearsed on. Otherwise the coder is asked for a program with the initial image, the helpers, the specification and calibration, and, when it passed at least once, the rehearsed program as a reference; three samples at different temperatures are drawn together and a fourth call synthesises one program from them.
best_prog = self.artifact.get("best_program")
stats = self.artifact.get("best_stats") or [0, 0]
passes = int(stats[0]) if len(stats) >= 2 else 0
trials = int(stats[1]) if len(stats) >= 2 else 0
same_goal = (
not self.artifact.get("goal_header")
or _goal_header(messages) == str(self.artifact.get("goal_header")).strip()
)
if isinstance(best_prog, str) and best_prog.strip() and same_goal and trials > 0 and (passes / trials) >= 0.5:
clean_best = _strip_helpers(best_prog)
self.last_code = clean_best
return _fence_exec(clean_best)
img0 = initial_image()
sys_msg = _sys_text(messages)
task_txt = _user_text(messages)
ref_prog = ""
if isinstance(best_prog, str) and best_prog.strip() and passes > 0:
ref_prog = f"\n\nReference Rehearsal Program ({passes}/{trials} rehearsal scenes):\n{_fence_prompt(best_prog)}"
prompt = (
f"=== TASK & ROBOT API ===\n{task_txt}\n========================\n\n"
+ ("The attached image shows the initial state of this scene.\n\n" if img0 else "")
+ f"{_SE3_DOC}\n\n"
+ self._artifact_context()
+ ref_prog
+ "\n\nWrite the complete initial Python program to solve this task on the current scene.\n\n"
+ _STAGE_GATED_RULES
)
return self._ensemble_program(
llm, budget, sys_msg, prompt, images=[img0] if img0 else (), temps=(0.2, 0.45, 0.75)
)After each executed block the coder is asked for a verdict, COMPLETE, INCOMPLETE or UNCERTAIN,
with a confidence, the completed subgoals and a root cause. It sees the initial image and the
before and after renders, the history of the last five turns, the calibrated checks and near-miss
traps, and the passing and failing telemetry exemplars. UNCERTAIN exists for one case: the arm
occludes the objects, so the next block should retract and re-measure before touching anything.
Apart from running out of regenerations or budget, the verdict ends the trial only on COMPLETE
with confidence at least 0.78 and no exception or explicit abort in the block. Every other outcome
produces a recovery program that must first check whether the goal
already holds and must preserve the completed subgoals; the backup program is offered once as an
alternative strategy, and a warning derived from the calibrated "held at the end" flag keeps a
recovery from opening a gripper that must stay closed.
diag_raw = self._safe_chat(llm, budget, sys_msg, diag_prompt, images=verify_imgs, temperature=0.1)
diag = _extract_json_obj(diag_raw)
if not isinstance(diag, dict):
diag = {
"verdict": "INCOMPLETE" if (has_exc or explicit_abort) else "UNCERTAIN",
"confidence": 0.0,
"completed_subgoals": [],
"failed_stage": "exception" if has_exc else "unknown",
"root_cause": _clip(diag_raw, 400),
"recovery_plan": "Check live poses after clearing any camera occlusion, verify if goal is already met, and run only remaining stages.",
}
verdict = str(diag.get("verdict") or "").upper()
try:
conf = float(diag.get("confidence") or 0.0)
except Exception: # noqa: BLE001
conf = 0.0
if verdict == "COMPLETE" and conf >= 0.78 and not has_exc and not explicit_abort:
return "finish", None
if budget.remaining < 1:
return "finish", NoneResults
| Method | ① | ② | ③ |
|---|---|---|---|
| Success rate ↑ | Success rate ↑ | Success rate ↑ | |
| Gemini 4 Carbon | 0.060 | 0.060 | 0 |
| CaP-X, single-shot | 0.020 | 0.120 | 0.160 |
| Multi-turn text feedback | 0 | 0.080 | 0.040 |
| CaP-X, visual differencing | 0 | 0.100 | 0.120 |
| CaP-X, parallel synthesis | 0 | 0.160 | 0.320 |
| Code-as-Monitor | 0 | 0.040 | 0 |
| GaP | 0 | 0.020 | 0 |
| ASPIRE | 0.120 | 0.560 | 0.600 |
| CaP-X, skill library | 0.060 | 0.140 | 0 |
- ① RoboSuite CaP-Bench nut_assembly · perception tier · held-out scene variants · success
- ② RoboSuite CaP-Bench two_arm_lift · perception tier · held-out scene variants · success
- ③ RoboSuite CaP-Bench two_arm_handover · perception tier · held-out scene variants · success
The method does not transfer to the scored settings. On NutAssembly our success rate of 0.060 is level with 0.060 for the skill library and above most published baselines, but below the 0.120 reached by ASPIRE [3]. On TwoArmLift we reach 0.060, below six of the eight published baselines, among them the starter policy with text feedback (0.080) and the single-shot program (0.120), and far below ASPIRE [3] at 0.560. On Handover we reach 0.000, against 0.040 for the starter and 0.600 for ASPIRE [3].
This stands in sharp contrast to our development measurements on the task's development tasks, where the same design was well ahead of the reference policies the agent ran itself: across four development tasks (cube stacking, cube restacking, spill wiping and one more) a predecessor of the final version passed 31 of 32 trials, against 23 of 32 for the ASPIRE reference and 20 of 32 for the visual-feedback reference, and on held-out development scenes it kept 15 of 16 against 10 of 16. Those numbers come from the agent's own runs and are reported as its claims. The scored results say that whatever made the method strong on those tasks is not what the scored settings need. We cannot see why from our inputs; the most likely candidates are named under Limitations.
How we got here
We began by running the reference policies on the development tasks and classifying their failures. In our development runs most failures of the visual-feedback reference were truncated episodes: a missed grasp followed by a full transport sequence on an empty gripper, or a loop of hundreds of blocking waypoints, spent the physics step horizon before the policy could replan. That diagnosis set the direction: make the coder's programs mechanically sound, and decide well when to stop, rather than add more regeneration.
The method then went through nine versions, each driven by a failure we found in rehearsal traces:
- An early-exit deadlock. Generated programs that ended with
exit()closed a file descriptor the worker needed and hung the trial until its timeout. The AST guard came from this. - Probe output that misled the specification. An unclipped probe printed hundreds of masks, and the specification written from it invented a wrong transform and a double tool offset. The probe now slices every list, and the frame rule is decided by the measured grasp-to-centre offset rather than by a fixed offset in the prompt.
- A verifier that rejected solved scenes. On the restacking task the policy regenerated after a
block that had already succeeded: once one cube sits on another, the lower cube's visible box
collapses to one face and its height reads as millimetres, which an uncalibrated check took for
failure, and the arm itself merged into the box in close views. The
UNCERTAINverdict, the retract-before-checking rule, the telemetry exemplars and the robust bounding-box helper all address this. - A self-inflicted waypoint cap. An early rule capped motion counts, which made coverage programs on the wiping task collapse large regions into coarse grids. The rule now separates discrete point-to-point manipulation, where retries are bounded, from continuous coverage, where waypoints are dense but capped by a share of the step horizon.
- Grasps from the wrong frame. Grasp proposals filtered for a downward approach in the camera frame selected inverted grasps; the selector now transforms to the world frame first. A top-down grasp with zero yaw hit the corners of rotated boxes, which led to the long-axis alignment.
- Four-pick unstacking. Programs that moved both objects to the side and back ran out of steps; the rules now prescribe a two-pick unstacking.
The agent also ran ablations of an earlier version on development tasks. Across three tasks, where a later predecessor of the final version passed 23 of 24 trials, the ablation without the closed loop (the rehearsed program only) passed 16 of 24 and the one without rehearsal 20 of 24; without the helpers and rules the rehearsal pass rate on the restacking task was 2 of 45, against 12 of 34 for the final version with them. These are the agent's development measurements.
Looking back, the list above is also a record of how the rule text grew: most of its clauses encode a mechanism observed on one development task, and the scored settings exercise different mechanisms.
Limitations
- No transfer from development to scored settings. Our development measurements were near the ceiling, and our scored results are below the starter on TwoArmLift and Handover, with no success at all on Handover. Nine versions were tuned against the same small set of development tasks, and each version was kept because it won on them; repeated adaptation to a fixed set of checks is exactly the situation in which measured gains stop predicting performance on fresh data [6]. We had no estimate of performance on tasks we had not tuned on.
- The rule text is specific in substance, if not in names. We removed object names and coordinates from the prompts, but rules such as two-pick unstacking and serpentine coverage spacing are prescriptions for particular kinds of task. When a task is of another kind they lengthen the prompt and can steer the coder toward the wrong motion.
- Everything depends on rehearsal passes. Replay needs a rehearsal pass rate of at least one half, contrastive repair works best with at least one passing trace, and the calibration is only as good as its labelled examples. When rehearsal finds few or no passes, the policy falls back to generation from long prompts and a verifier calibrated on failures only, and our design has no cheaper path for that case. The campaign is also bounded by a fixed wall-clock cap, which may be short for settings whose rehearsals are slow.
- The verifier is the coder. The three-valued verdict, the confidence threshold of 0.78 and the calibration all come from the frozen model judging its own work. Rehearsal labels improve that judgement but do not make it reliable.
- Cost per turn. The initial ensemble spends four calls and each recovery turn up to four more, so a trial that is not solved by replay uses its budget quickly, and the number of recovery turns it can afford is small.
References
- Letian Fu, Justin Yu, Karim El-Refai et al. (2026). CaP-X: A Framework for Benchmarking and Improving Coding Agents for Robot Manipulation. ICML.
- Jie Huang, Xinyun Chen, Swaroop Mishra et al. (2024). Large Language Models Cannot Self-Correct Reasoning Yet. ICLR.
- Runyu Lu, Yubo Wu, Ethan Kou et al. (2026). ASPIRE: Agentic /Skills Discovery for Robotics.
- Kaiyuan Chen, Shuangyu Xie, Letian Fu et al. (2026). GaP: A Graph-as-Policy Multi-Agent Self-Learning Harness For Variational Automation Tasks. CoRL.
- Enshen Zhou, Qi Su, Cheng Chi et al. (2025). Code-as-Monitor: Constraint-aware Visual Programming for Reactive and Proactive Robotic Failure Detection. CVPR.
- Cynthia Dwork, Vitaly Feldman, Moritz Hardt et al. (2014). Preserving Statistical Validity in Adaptive Data Analysis.