Introduction
In code as policies, a frozen coding model turns a natural-language task and the docstrings of a robot API into a Python program, and the program is run on the robot. After each executed block the agent may read the console output, look at the scene and write a new block. The question of this task is which policy for this loop turns the most trials into successes, given a fixed coder, a fixed API and a fixed budget of model calls [1].
The usual answer is to close the loop at test time. The coder sees text feedback, a visual description of what changed, or several parallel candidates that it then merges [1]. Other methods monitor constraints with visual programs [2], organise the policy as a graph that learns from rehearsal [3], or repair and evolve skills from execution traces [4]. We started from a different reading of the problem, which our first development runs supported. A trial succeeds when the last executed block leaves the scene in the goal state, and failures have two sources: a systematic error in the program, which recurs in every scene, and bad luck in one scene, such as a poor grasp sample or a slip. Neither can be fixed by test-time reflection alone. The coder cannot see the success predicate, and in our early runs of the multi-turn text policy it almost always answered "finish" after the first block. Asking a model to review its own work without external evidence does not help and can turn correct answers into wrong ones [5].
The success predicate is visible in exactly one place: the rehearsal phase that the harness offers
before the scored trials, through prepare(llm, rehearse, budget). The starter does not use it.
We use it for three things at once. It is a search over programs with ground-truth feedback, which
addresses the systematic errors. It calibrates the success signals that a scored trial will have,
which makes a retry after bad luck a decision with a known error rate. And it measures properties
of the environment that the programs have to respect.
Method
We call the method rehearsed programs with calibrated replanning. It has four parts: a race between candidate programs during rehearsal, the calibration of two success signals on the same practice runs, a generic prelude that is prepended to every program block, and a decision rule for the scored trial.
A race between programs written by the coder
Rehearsal starts with one exploration program that only queries perception and prints what it finds. Its output and the initial camera image are shown to the coder as context for six independent first drafts. Half of them are asked for one careful attempt without retries, and the other half for a closed loop with at most one further attempt. Each draft is a candidate with successes and failures on practice scenes. Up to six practice runs are in flight at once, and the next candidate to run is chosen by Thompson sampling, with a run in flight counted as half a failure:
where is the number of runs of in flight. A fresh program has . A rewrite of a parent whose posterior mean is at least 0.5 starts at , so it inherits some of its parent's credit. A program that has never succeeded is dropped after three runs, or after two while no program has succeeded at all.
def pick(self):
"""Thompson sampling over the programs still worth a practice run (called with the lock held); a run in
flight counts as half a failure. While rewrites are being written, practice runs are kept for them:
only programs that still lack runs are measured (PACE_RUNS, or 3 once few runs are left)."""
alive = [c for c in self.cands if not self.dead(c)]
if self.writing > 0 and self.elapsed() < SOFT_SECONDS - 420:
cap = PACE_RUNS if MAX_REHEARSALS - self.started > PACE_KEEP else 3
alive = [c for c in alive if c["s"] + c["f"] + c["inflight"] < cap]
if not alive:
return None
return max(alive, key=lambda c: random.betavariate(c["prior"][0] + c["s"],
c["prior"][1] + c["f"] + 0.5 * c["inflight"]))A failed run of a program near the top of the race is handed back to the coder for a rewrite. The prompt carries the program, its console output, the final camera image, the ground truth set against the program's own verdict, and the diagnoses written for earlier failures. A verdict that disagrees with the ground truth is pointed out to the coder as a sign that the program checks the wrong thing. The rewrite joins the race. When every program has failed at least twice and none has succeeded, the coder is asked for a new program with a different approach. While no program has succeeded, up to four more independent drafts are also requested, because rewrites stay close to the drafts they repair.
Choosing the best of many candidates by their practice records rewards luck: the program with the best record among several similar ones is likely to be better on paper than in fact, since the same practice runs both select it and estimate it [6]. We therefore rank programs by a record shrunk toward the pooled success rate of all practice runs,
and ship the best among the programs with at least one success and at least four practice runs, or among all tried programs if none qualifies. A program is shipped only if it has succeeded at least once.
def score(self, c):
"""Expected success rate of a program: its record shrunk toward the success rate of all programs' runs
(an empirical-Bayes prior worth SHRINK runs), so that one lucky run does not outrank a long good record."""
s_all = sum(x["s"] for x in self.cands)
n_all = s_all + sum(x["f"] for x in self.cands)
m0 = (s_all + 1.0) / (n_all + 2.0)
return (c["s"] + SHRINK * m0) / (c["s"] + c["f"] + SHRINK)
def leader(self):
"""The program to ship if the phase ended now: the best shrunk success rate among the programs with at
least MIN_RUNS practice runs (a record of two or three runs is too easily luck), else among all tried."""
tried = [c for c in self.cands if c["s"] + c["f"] > 0]
solid = [c for c in tried if c["s"] > 0 and c["s"] + c["f"] >= MIN_RUNS]
pool = solid or tried
return max(pool, key=lambda c: (self.score(c), c["s"] + c["f"])) if pool else NoneCalibrating two success signals on the same practice runs
A scored trial has two signals about its outcome. The first is the verdict that every program must
print as its last line, TASK_VERDICT: SUCCESS or FAILURE, which we classify as ok, fail,
crash or none. The second is a judge: the coder is shown the first and the current camera
image and asked three times, independently, whether the goal holds now. The answer is the
number of YES votes, or ? if any of the three cannot be parsed. Neither signal is trusted as
it is. Both are counted against the ground truth of the practice runs.
For the verdict, the belief that the goal holds after a block of class is a Beta-binomial
estimate with a hand-set prior and the selected program's own practice counts,
; the prior is, for example, for ok and
for crash. The counts are used only while the block that just ran is the selected
program. For the judge, we estimate the likelihood of each answer under success and under failure
from the judge's record on all practice runs, again on top of a prior, and combine the two by
Bayes' rule:
Here counts practice runs with truth that received answer , and is the prior in pseudo-counts. The calibration matters because the judge is not equally informative everywhere. On one of our development tasks the outcome is hard to see from the camera, and the judge answered NO on most true successes. Its counts there made a NO weak evidence, and the verdict decided.
def _posterior(p_cls, said, counts=None):
"""P(goal state holds | the block's class, the judge's answer): the class belief times the judge's
likelihood ratio, the latter from the judge's record on the practice runs (counts[answer] = [successes,
failures] among the runs that got this answer)."""
counts = counts or {}
like = {}
for truth in (True, False):
prior = JUDGE_PRIOR[truth]
k = 0 if truth else 1
total = sum(prior.values()) + sum(v[k] for v in counts.values())
like[truth] = (prior.get(said, 0.3) + counts.get(said, [0, 0])[k]) / total
odds = p_cls / max(1e-6, 1.0 - p_cls) * like[True] / like[False]
return odds / (1.0 + odds)A generic prelude for every program
Every block the policy emits is prefixed with a fixed prelude that contains no task knowledge. It
wraps each API function listed in the task prompt: functions documented as returning None count
as actions, the others as queries. A query wrapper remembers the result of each call. When the
same call is repeated after the robot has moved, the wrapper prints a [perception-check] line
saying whether it returned exactly the same values. In some configurations of the environment
perception stays frozen at the initial scene. The rehearsal phase counts these lines, and once
a query has returned identical values after motion in at least two practice runs, and never
different ones, every later prompt states as a fact that re-queried poses say nothing about what
the robot achieved. Our first rewrites had been misled by exactly this: identical poses read as
"the cube was never grasped".
def _hp_query(name, fn):
# a perception / state query: report whether it returns the same values before and after robot motion
def call(*args, **kwargs):
_hp_guard()
out = fn(*args, **kwargs)
try:
key = name + repr(args) + repr(sorted(kwargs.items()))
sig = repr(out)
old = _HP["seen"].get(key)
if out is not None and old is not None and old[1] < _HP["acts"]:
kind = "exactly the same values as" if old[0] == sig else "different values than"
if (key, kind) not in _HP["told"]:
_HP["told"].add((key, kind))
print("[perception-check] " + name + repr(args) + " returned " + kind + " before the robot moved ("
+ str(_HP["acts"] - old[1]) + " motion commands in between)")
_HP["seen"][key] = (sig, _HP["acts"])
except Exception:
pass
return out
call.__name__ = name
return callThe prelude also gives programs a helper look(question), which asks the vision-language model
about a fresh camera capture, so that a program can verify its own outcome even when perception is
frozen. It ends a program that keeps commanding a finished episode or runs for more than 15
minutes, and it replaces exit(), quit(), input() and breakpoint() in the program's
namespace. That last change fixes a failure we found in development. The interpreter's own
exit() closes the standard input of the process that drives the program, which is the
harness's pipe, so a block that ended with exit() never returned and the trial hung.
def exit(code=None):
# the interpreter's own exit() / quit() close the console the program is driven through and never return
raise SystemExit(code)
quit = exit
def input(*args, **kwargs):
raise RuntimeError("no console input is available to the program")
def breakpoint(*args, **kwargs):
return NoneThe scored trial: replan only on strong evidence of failure
A scored trial runs the selected program as its first block, without any model call. After each block we compute as above. A replan replaces the present scene, in which the goal holds with probability , by the outcome of a new attempt, and much of the episode's control-step budget is already spent. It is therefore made only when . The first replan is one more run of the selected program. This happens on the first turn only, when the program's posterior mean on practice runs is at least 0.25, and only when the scene is untouched or perception is live, since with frozen perception a rerun after motion would act on stale poses. Otherwise the coder is shown the executed code, its output, the two signals, and the two images, and answers FINISH, REGENERATE or, when a program was shipped, RERUN. A regenerated program must begin by checking whether the goal already holds, and must then make one direct attempt. The trial ends after three replans, after 900 seconds, when the model-call budget is nearly spent, or as soon as the output shows that the episode's control steps are exhausted. If no program was shipped although at least 24 practice runs were made, only one replan is allowed.
if budget.remaining < 1:
return "finish", None
self.moved = self.moved or MOTION_TAG in (feedback.stdout or "")
if prog and self.standard and feedback.turn == 0 and (not self.moved or not self.art.get("frozen")):
s, n = (self.art.get("record") or [0, 0])[:2]
rate = (s + 1.0) / (n + 2.0)
if rate >= 0.25 and p < min(RERUN_GAIN * rate, REPLAN_BELOW):
# the selected program is the best approach known for this task and many of its failures are bad
# luck (a poor grasp sample, a slip, a perception error): when the scene is untouched or
# perception is live, the first replan is simply one more run of it, which measures the scene
# again and costs no model call. (With frozen perception a rerun after motion would act on
# stale poses.)
print("[policy] replan = the selected program once more", flush=True)
return "regenerate", _fenced(prog, task)
if p >= REPLAN_BELOW:
return "finish", NoneWithout a shipped program, the first block is written by the coder for the scene at hand, and the same decision rule runs on the prior counts. The method has no per-setting constants. Its one branch on the environment, frozen against live perception, is decided by measurement during rehearsal.
Results
| Method | ① | ② | ③ |
|---|---|---|---|
| Success rate ↑ | Success rate ↑ | Success rate ↑ | |
| Claude Fable 5.2 | 0.020 | 0.780 | 0.280 |
| 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 TwoArmLift our method reaches a success rate of 0.780, ahead of every published baseline; the strongest of them, ASPIRE [4], reaches 0.560, and the test-time feedback policies stay at or below 0.160.
On Handover we reach 0.280. That is above six of the eight baselines but below 0.320 for parallel candidates with synthesis and well below 0.600 for ASPIRE [4].
On NutAssembly we reach 0.020, level with the single-shot program (0.020) and below the skill library (0.060) and ASPIRE [4] (0.120). Our method stands or falls with the rehearsal race. When no candidate succeeds during rehearsal, nothing is shipped, and the scored trial falls back to a program written on the spot, whose verdict is read through the prior alone. The evaluation means cannot show whether this is what happened on NutAssembly, where every method stays low.
How we got here
The method was built in about thirty versions over one session. Most versions were run end to end in a local copy of the harness, on development tasks under both perception regimes.
- The starting point was a measurement and a literature review. In our first runs the multi-turn text baseline almost always answered FINISH after the first block, without verifying. Its failures were either undetected stochastic grasp failures or one systematic error repeated in every scene. A literature review that we commissioned at the start drew three conclusions. Between-turn replanning is a small lever at this API level [1]. A single program selected in rehearsal can carry most of the gain [4]. A small Monte-Carlo model of the selection problem favoured one Thompson-sampling race over six to twelve diverse candidates, and the review recommended shrinking a record toward the pooled rate because selection on few runs inflates the winner's estimate. The same review advised retrying only on external evidence [5]. It also cited a survey on when language models can correct their own mistakes and a paper on the complexity of best-arm identification, neither of which is among our references.
- Our first version (a race with failure-driven rewrites) failed on one development task
because perception was frozen. All rewrites diagnosed "the pose did not change, so the grasp
failed". This led to the
[perception-check]detector, whose finding is passed to the coder as a fact, and tolook()as a verification channel that always sees the current scene. - The judge had to be calibrated, not trusted. Measured offline on existing trials, the single-image YES/NO judge was right on almost every trial of most development tasks. On a task whose outcome the camera cannot show, it later said NO on true successes. In the first calibrated version, a replan fixed one failed trial and broke one true success in which both signals were wrong. The regenerated program re-grasped at a stale initial pose. From then on the judge votes three times, and every replan program must first check whether the goal already holds.
- Letting the coder choose between rerun and regenerate did not work. In one development run the coder never chose RERUN, in none of 32 replans. Re-measuring the selected program in isolation also showed that its rehearsal record had been luck, and that the six seeds were nearly equal. We made the first replan an automatic rerun of the selected program, with no model call.
exit()hung trials. Three of six searches in one batch stalled on practice runs that never returned. A stack dump of the hung worker showed the interpreter'sexit()blocked on closing the harness's input pipe. We replacedexit()in the program's namespace, and the search stopped waiting for runs that do not return.- Practice runs that imitate the scored pipeline were dropped. For several versions a practice run was given the same automatic rerun as a scored trial, so that the race would measure programs the way they are used. On one development task this version did clearly worse in our runs than the single-block practice runs, and the final design measures single blocks.
- The shipped program should have four practice runs. In one development run the search shipped a program with two successes in three runs, and the trial scored no successes. Since then, a program with at least four practice runs and one success is preferred, and the search falls back to the best of all tried programs only when no such program exists.
- The replan threshold was tightened last. For most of the session the policy also asked the coder for a new program when . Across our logs, replans at between 0.15 and 0.6 undid more successes than they repaired, while those below 0.05 repaired most failures. The final edit therefore requires for any replan. Earlier in the session, in our development measurements summed over the clean runs of that time, the first block alone succeeded in 109 of 144 trials and the full policy in 114, with five failures fixed and none broken. Most of the gain over the baselines therefore came from the race, not from replanning.
- Two further ideas were not kept. Top-two Thompson sampling showed no clear difference from plain Thompson sampling in a mock of the search. We used it for a few versions and returned to plain Thompson sampling after it spread the practice runs almost uniformly over the programs in one development run. A rule that keeps the search exploratory while the best program is weak showed no difference in the mock and was not adopted.
Limitations
- We are behind on two of the settings. On NutAssembly we are level with the single-shot program and below two baselines. On Handover we are below ASPIRE [4] by a wide margin. The gain is shown on TwoArmLift only.
- Everything rests on the rehearsal search finding a working program. On the hardest development tasks the search sometimes shipped a program with one success in fourteen practice runs, and repeated runs of the whole pipeline on the same task varied widely. The shrinkage and the four-run rule reduce this selection noise but cannot remove it with the practice runs available.
- The final threshold was not run end to end. The change to was made at the end of
the session and passed only offline branch tests before submission. A side effect is that the
rerun condition with always reduces to , so the
RERUN_GAINfactor no longer has any effect. The class docstring still describes the earlier threshold of 0.4 for model-written replans; the code uses 0.1. - The calibration counts are thin. The verdict table comes from the selected program's own practice runs, often only a handful, and the judge counts are pooled over all programs, including ones that behave quite differently. Both lean on hand-set priors that we did not tune systematically.
- Replanning is bounded by the episode. A program with internal retries can use most of the episode's control steps, which leaves no room for a replan. The policy stops when the output shows the steps are exhausted, but it does not budget them in advance.
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.