Introduction
In code-as-policies robot manipulation, a frozen coding model turns a natural-language goal and the documentation of a robot API into a Python program, which a sandbox executes against the robot. After each executed block the policy sees the console output and renders of the scene, and it may regenerate the remainder of the program or finish. The question of this task is what that policy should do, given a fixed coder, a fixed API, a fixed execution loop and a fixed budget of model calls per trial: which prompting, inspection and regeneration policy turns the most trials into task successes?
CaP-X [1] studies this question with a ladder of agents: a single-shot program, multi-turn regeneration from text feedback, regeneration from a visual-differencing report that describes how the scene changed, parallel candidate programs merged by a synthesis call, and a skill library distilled from successful rehearsal rollouts. Code-as-Monitor [2] writes executable monitors that detect failures from visual constraints. GaP [3] organizes the work as a graph of agents that learns from rehearsal, and ASPIRE [4] wraps the coder in a fix loop and an evolutionary search over programs.
Three properties of the problem shaped our design. First, a single scene says little about a program. Object poses change from trial to trial, and a program that succeeds once may succeed by luck. Second, the coder's judgment of its own work is fallible: whether a motion achieved its goal is often not visible in the console, and a model asked to check its own output does not reliably correct it [5]. Third, the task interface offers a rehearsal phase: before the scored trials, the policy may run complete programs on fresh scenes and keep a small artifact for the scored trials. Every scored trial otherwise starts with nothing but the prompt. Our method puts most of its effort into that rehearsal phase, and spends the scored trials' calls on recovery.
Method
Our policy has two parts. The prepare step runs a rehearsal search that returns an artifact: a
selected program, up to three alternatives and a short list of lessons. The scored policy executes
the selected program directly and repairs it with a gated recovery ensemble. If the rehearsal finds no
program that succeeded on any scene, or fails with an exception, the artifact is empty and the scored
trials fall back to ordinary generation from the task prompt, followed by the same recovery loop.
Rehearsal search
The search runs in four stages.
A motion-free probe. The coder first writes one observation-only program that queries the documented perception functions for every object named in the goal and prints the returned poses, extents and grasp samples, without moving the robot. Its output and the first render of its scene are appended to the candidate prompt as noisy evidence, with the instruction never to copy a numeric pose or dimension from it into a program. The probe never enters the candidate pool.
Diverse decodes. We sample twelve complete programs at temperatures , , from a prompt that asks the coder to query object state at execution time, print measured poses and end with a perception-based check. A reply is kept only if its code parses and contains at least one call or import, and exact duplicates are dropped. Each candidate is then executed on a fresh rehearsal scene.
Evidence-driven synthesis and repair. Two rounds then ask the coder for four new programs each, at temperatures 0.25, 0.4, 0.6 and 0.8, from the six best-ranked candidates, their code, a summary of their last two outcomes (success, error, clipped stdout and stderr, the last executed block, the last model reply) and up to four rehearsal renders. The first round synthesizes; the second, which sees the outcomes of the first, repairs. For a candidate with mixed outcomes we show a failure render rather than a success, since the failure carries more diagnostic information.
# Two repair generations use different evidence snapshots. The second sees the first
# batch's fresh-scene outcomes, which turns rehearsal into an execution-grounded search.
for repair in (False, True):
ranked = self._ranked()[:6]
if not ranked:
break
pairs = [(idx, self.candidates[idx]) for idx in ranked]
prompt = _synthesis_messages(self.task_messages, pairs, self.results,
self._images_for(ranked), repair=repair)
temps = [0.25, 0.4, 0.6, 0.8]
new_ids = self._generate(prompt, temps)
self._run_batch(new_ids)Optimistic allocation of the remaining scenes. The rest of the rehearsal scenes go to a shortlist. For a candidate with successes in rehearsals we rank by
the posterior mean of the success probability under a prior plus an exploration bonus that shrinks with the number of trials, with ties broken by the raw success count. An untested candidate scores 1, above most tested candidates, although one that has succeeded in every rehearsal so far scores above 1.
def _optimistic(successes, attempts):
if attempts <= 0:
return 1.0
# A conservative empirical-Bayes upper score gives untested candidates room to be
# explored, then rewards candidates that remain successful on independent scenes.
mean = (successes + 1.5) / (attempts + 3.0)
return mean + 0.55 / _math.sqrt(attempts + 1.0)Rehearsals run in parallel batches, so the ranking is fixed for the length of a batch. Instead of giving one scene to each of the top candidates, we give a batch of eight scenes four to the current leader, two to the runner-up and one each to the third and fourth, which keeps challengers in play while concentrating evidence on the program most likely to be chosen. The loop stops when the rehearsal allowance is used or when a wall-clock estimate from the previous batch says the next batch would not finish in time.
# Batch requests run concurrently, so the rank is fixed until all outcomes return.
# Allocate more fresh scenes to the current posterior leader while retaining a few
# challengers. This is a batched analogue of optimistic bandit allocation, and it
# avoids spending exactly one scene on every weak member of the shortlist.
pattern = (0, 0, 0, 0, 1, 1, 2, 3)
ids = [ranked[pattern[i % len(pattern)] % len(ranked)] for i in range(n)]
self._run_batch(ids)Each rehearsal measures the same thing the scored policy will do, not only the first block: the candidate is executed, and the coder gets one corrective turn with the visual-differencing report and the same decision prompt as in scored trials, so a candidate is credited with the failures that a repair can fix. When the latest rehearsal of a candidate in a batch succeeds after a repair, the repaired final block is promoted into the candidate pool as a new program, which must then earn its own fresh-scene evaluation before it can be selected. The promotion happens after all workers of a batch have joined, so the candidate list is never changed from a rehearsal thread.
# A successful bounded recovery is itself a candidate. Promote only its final executable
# block after all workers have joined, so the shared candidate list is never mutated from
# a rehearsal thread. The promoted program receives fresh validation in a later batch.
for idx in ids:
result = self.results.get(idx, [])[-1] if self.results.get(idx) else None
if not isinstance(result, dict) or not result.get("success"):
continue
blocks = result.get("blocks") or []
if not isinstance(blocks, (list, tuple)) or len(blocks) < 2:
continue
final_block = blocks[-1] if isinstance(blocks[-1], dict) else {}
final_code = final_block.get("code") if isinstance(final_block, dict) else None
if isinstance(final_code, str):
self._add(final_code)Selection and lessons. Among candidates with at least one rehearsal we select by the posterior mean alone, without the bonus. If no rehearsal of any candidate succeeded, we return no artifact. When some rehearsals failed, one more call asks the coder, acting as a failure analyst, for at most six short lessons, each tied to an exact error, output or repeated code pattern in the evidence, with a remedy marked as a hypothesis when the evidence does not establish it and no scene-specific coordinates. The artifact holds the selected program, the next three programs by the same ranking, and the lessons; alternatives are dropped from the end if the artifact would exceed 240000 bytes.
Scored trials: direct execution and gated recovery
In a scored trial, initial_program returns the selected program without a generation call. It still
builds the context that later recovery prompts use: the task prompt, an initial scene description (a charged call),
the alternatives, labelled as independently rehearsed designs to draw on if the executed approach
fails, and the lessons.
After each executed block, decide clips the feedback (the cumulative executed code to 30000
characters, stdout and stderr to 8000 each, keeping head and tail) so that ten rounds of replanning
stay inside the coder's context. If at least 11 calls remain, it requests the visual-differencing
report (when two renders are available) and runs the recovery ensemble; with fewer calls left it asks the coder once, without the
report; with none left it finishes.
if feedback.regenerations_left <= 0:
return "finish", None
base = self.initial_messages or _prompt_with_text(messages, "\n" + MULTI_TURN_SUFFIX + "\n")
images = feedback.images()
diff = None
# Reserve ten calls for a 9-way recovery ensemble and its synthesis. The VDM call is
# made only when it can coexist with that reservation.
use_ensemble = budget.remaining >= 11
if use_ensemble and len(images) >= 2 and images[0] and images[1]:
try:
diff = feedback.visual_diff()
except Exception:
diff = None
elif budget.remaining >= 1:
# With one call left, ask the coder directly and avoid a VDM call that would consume
# the only remaining request.
diff = None
else:
return "finish", None
prompt = decision_messages(base, _bounded_feedback(feedback),
template=_M3_TEMPLATE, visual_diff=diff)
try:
reply = (_ensemble_decision(prompt, llm, budget,
allow_gate=not bool(str(feedback.stderr or "").strip()))
if use_ensemble else llm.chat(prompt))The ensemble is CaP-X's parallel-candidates-plus-synthesis [1] with an early exit. Most of the decisions after a block that completed the task are clear, and paying ten calls to confirm them is wasteful. So when the block produced no stderr, we first sample two judgments at temperatures 0.1 and 0.2 with an added instruction to say FINISH only when the execution evidence establishes every task goal, and not to assume that a motion succeeded because the call returned. If both say FINISH, we finish. Otherwise the two replies are kept as ensemble members, seven more are sampled at temperatures 0.3 to 0.9, and one synthesis call, given all candidate responses and their vote counts as a hint, writes the final FINISH or REGENERATE response. The worst case is therefore the same nine responses and one synthesis as an ungated ensemble. When the block wrote anything to stderr, the gate is skipped and the nine responses are sampled at once.
def _ensemble_decision(prompt, llm, budget, allow_gate=True):
"""Sample diverse recovery decisions, then let one call select a single response."""
temperatures = [0.1 + 0.1 * i for i in range(9)]
if budget.remaining < len(temperatures) + 1:
return llm.chat(prompt)
# A clear completion should not require the full ensemble. Two low-temperature quorum
# judgments act as a conservative early exit. If they disagree, their answers are retained
# as ensemble members and seven further samples keep the worst-case call count unchanged.
gate_prompt = _prompt_with_text(prompt, """
Before spending the full recovery ensemble, make a conservative completion judgment. Say FINISH
only when the execution evidence establishes every task goal. Otherwise say REGENERATE followed
by one complete corrective Python program. Do not assume that a motion succeeded merely because
the call returned without an exception.
""")
gate_candidates = []
if allow_gate:
try:
gate_candidates = [str(reply) for reply in
(llm.chat_many(gate_prompt, temperatures[:2], max_tokens=12000) or [])
if reply and str(reply).strip()]
except Exception:
gate_candidates = []
if (len(gate_candidates) >= 2 and
all(parse_decision(reply)[0] == "finish" for reply in gate_candidates[:2])):
return gate_candidates[0]If the synthesis call fails, we return the first sampled response that asks to regenerate, so that a single FINISH from the gate cannot end a trial its partner judged incomplete.
Results
| Method | ① | ② | ③ |
|---|---|---|---|
| Success rate ↑ | Success rate ↑ | Success rate ↑ | |
| GPT-6.2 Astra | 0.080 | 0.420 | 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
On NutAssembly and TwoArmLift our policy is ahead of every published baseline but one. Our success rate of 0.420 on TwoArmLift compares with 0.160 for the parallel-candidates-plus-synthesis baseline whose recovery step we reuse, and with 0.100 for multi-turn regeneration from the visual-differencing report. The strongest baseline on both settings is ASPIRE [4], at 0.120 on NutAssembly and 0.560 on TwoArmLift, against our 0.080 and 0.420.
On Handover our policy did not succeed in any scored trial: a success rate of 0.000, level with three baselines and below the other five, including the single-shot program at 0.160 and ASPIRE [4] at 0.600. We return to this in the limitations.
How we got here
We began from the interface and from the published baselines. Reading CaP-X [1], we noted that regeneration from text feedback helps most models, that the visual-differencing report improves on it, that a parallel ensemble with synthesis anticipates failures, and that an over-prescriptive debugging prompt lowered success, which is why our decision prompt stays short. The rehearsal phase then suggested the central idea: test complete programs on fresh scenes before the scored trials, and select by repeated outcomes rather than by one scene. Work on retaining executable programs together with textual feedback about their execution, which we read after our first version, later supported carrying programs and evidence, not scene coordinates, into the artifact.
Because the run could not execute the task's simulator during development, every design decision was tested on synthetic models or on hand-written prompts, never on rehearsal outcomes.
- Ranking rule. A first simulation with candidate success probabilities drawn from a distribution found that ranking by the raw success rate and by a Wilson lower bound selected equally good candidates for every pool size and repeat count we tried. A second, allocation simulation found that UCB, Thompson sampling and an optimistic rule of the same form as our final score, a smoothed success rate plus a bonus shrinking with the number of trials, all beat uniform evaluation: in our development measurements the true success of the selected candidate averaged 0.559 to 0.602 for uniform allocation and 0.610 to 0.633 for the optimistic rule. Our notes record that a further simulation favoured ten to twelve initial candidates, which supported the twelve decodes already in use.
- Batched allocation. Our first version gave one scene to each of the eight shortlisted candidates per batch. A later synthetic comparison, recorded in our notes, found that the 4-2-1-1 pattern selected the latent best candidate more often under several priors, so we replaced it.
- The recovery ensemble and its gate. With the selected program removing the initial generation call, we added a nine-way ensemble with synthesis to every recovery turn. To see whether an early exit was safe, we served the frozen coder locally and gave it a hand-written stacking task with three kinds of feedback, sampled at nine temperatures each. Clearly incomplete feedback produced REGENERATE in nine of nine samples, clearly complete feedback FINISH in nine of nine, and ambiguous movement REGENERATE in all eight samples that returned. That supported the two-sample quorum. A later change restricted the gate to error-free blocks, because its two sequential stages added latency on turns that already showed an error.
- Rehearsal that measures the whole policy. The first rehearsals executed each candidate without any recovery, so that the score would measure the program alone. We later allowed one corrective turn, so that selection estimates initial-plus-repair success; our notes record a synthetic model, with correlated, independent and anti-correlated initial and repair quality, in which selecting on these outcomes improved the expected full-trial success. Promoting successful repairs into the pool was the last addition.
- Guards found by tests. A fake harness showed that a reply such as
not codeparses as valid Python and could become the selected program, hence the requirement of a call or import. We also removed the initial scene description from rehearsal runs, where, with no replanning in rehearsal at the time, it cost a call without changing execution, and capped prompt sizes after an audit found that keeping full repair replies in the synthesis evidence could approach the coder's context limit. - A dead end. A probe of decoding diversity on more demanding hand-written prompts produced no output; we stopped it and kept the search as it was.
Limitations
- Handover is a failure. A success rate of 0.000 is below the single-shot baseline, which spends one call per trial. Whatever the cause, committing every scored trial to one selected program is a single point of failure: when that program fails for a reason shared across scenes, the alternatives and lessons in the prompt are the only route to a different approach, and they come in only after a failed block.
- ASPIRE remains ahead everywhere. On every setting ASPIRE [4] is better than our policy, so our gain over the CaP-X ladder on NutAssembly and TwoArmLift does not reach the strongest published method.
- No development measurement on the task. Every design choice was supported by synthetic simulations or by probes on hand-written prompts. None of the constants (the prior, the bonus of 0.55, the 4-2-1-1 pattern, the threshold of 11 calls) was tuned on rehearsal outcomes, and none of the stages was ablated on the task.
- Selection reuses its own evidence. The same rehearsal outcomes that rank the candidates also select the winner, so the selected program's rehearsal rate is an optimistic estimate of its true rate, the familiar problem of adaptive reuse of data [6]. The smoothing prior softens this but does not remove it.
- The early exit trusts two agreeing judgments. The gate's calibration was checked on three hand-written scenarios only. A block that looks complete to the coder but is not ends the trial after two calls, and there is no perception-based check outside the coder's own judgment.
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.
- Enshen Zhou, Qi Su, Cheng Chi et al. (2025). Code-as-Monitor: Constraint-aware Visual Programming for Reactive and Proactive Robotic Failure Detection. CVPR.
- Kaiyuan Chen, Shuangyu Xie, Letian Fu et al. (2026). GaP: A Graph-as-Policy Multi-Agent Self-Learning Harness For Variational Automation Tasks. CoRL.
- Runyu Lu, Yubo Wu, Ethan Kou et al. (2026). ASPIRE: Agentic /Skills Discovery for Robotics.
- Jie Huang, Xinyun Chen, Swaroop Mishra et al. (2024). Large Language Models Cannot Self-Correct Reasoning Yet. ICLR.
- Cynthia Dwork, Vitaly Feldman, Moritz Hardt et al. (2014). Preserving Statistical Validity in Adaptive Data Analysis.