Introduction
In code-as-policies manipulation a frozen vision-language coder reads a task description and the docstrings of a robot API and writes a Python program; the program runs, and the policy may then show the coder the console output and a description of how the scene changed and ask for a replacement of the part not yet executed. The robot API, the execution loop, the coder and a per-trial budget of model calls are fixed. What is ours to design is the per-turn policy: what to put in each prompt, whether to look at the scene, when to regenerate and when to stop. The CaP-X framework [1] studies exactly this ladder of choices, from a single program to multi-turn text feedback, visual differencing, parallel candidates and rehearsal-built skill libraries.
Two judgements make the problem hard, and the coder is unreliable at both. The first is when to stop. The starter policy stops whenever the coder declines to regenerate, and the coder will happily conclude that the task is done because the program it wrote printed "done": a motion command that returned is not evidence that an object moved. Asking the same model to check its own conclusion is not obviously better, since self-correction without new information is known to be weak [2]. The second is what to do after a failure. A single regeneration tends to repeat the failed program with small changes, while sampling many candidates on every turn spends the budget on turns where nothing was wrong. Methods in the field answer these with explicit failure monitors written as code [3], with graphs of skills refined by rehearsal [4], or with fix loops and evolutionary search over programs [5].
We took the view that the shortfall is mostly one of state estimation and stopping, not of sampling, and built a policy in which stopping requires fresh, independently audited evidence and in which extra samples are spent only where a failure has actually been observed.
Method
The policy is a state machine around the starter's two calls. The initial program is generated exactly as in the starter, so that the distribution of first attempts is unchanged; apart from a repair of an initial program that violates the commit invariant below, everything we add acts after a block has run.
A goal contract written before any code
Before the first program, we ask the coder, without writing code, for a goal contract: the observable conditions that define success (DONE), the conditions later code must not undo and the actions that could fail irreversibly (PRESERVE), and a short list of commit points with measurable postconditions (STAGES). The prompt forbids inventing tolerances, dimensions or reference orientations that the task does not state, and asks that unmeasurable conditions be marked as such. The contract, together with generic rules on testing grasps before releasing them and on numeric preflight checks before contact, is appended to the conversation that every later decision sees. It is not added to the prompt of the initial program: in development, changing the initial prompt changed the coder's grasp behaviour and confounded every comparison of the replanning rule.
Stopping is a hypothesis that must be audited
Let be the coder's decision after block . In our policy a FINISH does not end the trial directly unless three attempts fail to produce a valid observation block. It is converted into a request for one block of observation-only code that re-queries every relevant pose and prints, for each DONE condition, the raw measured quantities, the expected relation and the data quality, with no success language.
prompt = self._feedback_prompt(feedback, diff)
if not audit_reason:
instruction = """
The controller proposed to stop, but stopping requires fresh evidence. Return exactly ONE fenced python block that performs OBSERVATION ONLY. Re-query all relevant object poses, extents and available robot state after the last motion. For every DONE condition print the raw measured quantities, expected relation, and data quality. Do not print COMPLETE, SUCCESS, PASS, a task-status conclusion, or claims based on commanded actions. Do not move, open, close, home, or otherwise change the scene. If a condition cannot be measured, print its raw evidence as UNCERTAIN.
"""
code, _ = self._generate_code(llm, self._append(prompt, instruction), attempts=3, observation=True)
if code is not None:
self.verification_turn = feedback.turn + 1
return "regenerate", self._completion(code)
return "finish", NoneObservation-only is enforced, not requested: the generated block is parsed and rejected if it calls any function whose name begins with an actuation verb (move, open, close, grasp and so on), and the coder is asked again. A verification turn therefore cannot move the robot or undo a success. Any block regenerated on an ordinary turn that passes this check is treated the same way, so observation blocks that the coder writes on its own initiative are also audited.
On the decision after an observation block we run an adversarial completion audit. The auditor is told it has not seen the controller's next action; it sees the task, the contract, the observation code itself and its output, the last three scene-change reports, and the before and after renders, and must return one of COMPLETE, INCOMPLETE or UNCERTAIN under constrained decoding. A COMPLETE is not yet final: an independent free-form call re-evaluates the same evidence and must also end with COMPLETE. Writing for the constrained verdict and for the free-form one, an audit ends the trial only if
A first disagreement is downgraded to UNCERTAIN, which produces another observation block and no motion; only an INCOMPLETE, from the constrained audit or from the free-form call at the second or later disagreement in a trial, authorises a physical recovery, and the audit's output is passed to the recovery prompt.
if self.verification_turn == feedback.turn:
self.verification_turn = -1
audit_prompt = self._audit_prompt(feedback, diff)
images = [image for image in feedback.images() if image]
existing_images = sum(1 for message in audit_prompt for part in message.get("content", []) if isinstance(part, dict) and part.get("type") == "image_url")
images = images[-2:][:max(0, 4 - existing_images)]
if images:
audit_prompt[-1]["content"].append({"type": "text", "text": "The attached before/after renders are direct evidence for this audit. Inspect object support, attachment, relative pose and gripper state yourself; the text scene reports may be wrong."})
for image in images:
audit_prompt[-1]["content"].append({"type": "image_url", "image_url": {"url": image}})
try:
audit = llm.chat(audit_prompt, max_tokens=20,
extra={"structured_outputs": {"choice": ["COMPLETE", "INCOMPLETE", "UNCERTAIN"]}})
except Exception:
audit = llm.chat(audit_prompt, max_tokens=700)
if _re.search(r"ALL_SATISFIED\s*:\s*YES", audit or "", _re.I):
verdict = "COMPLETE"
elif _re.search(r"ALL_SATISFIED\s*:\s*NO", audit or "", _re.I):
verdict = "INCOMPLETE"
else:
match = _re.search(r"\b(INCOMPLETE|COMPLETE|UNCERTAIN)\b", audit or "", _re.I)
verdict = match.group(1).upper() if match else "UNCERTAIN"
if verdict == "COMPLETE":
confirmation_prompt = self._append(audit_prompt, "Independently re-evaluate the evidence, especially any numeric or visual condition that is not satisfied. Explain briefly, then end with exactly one line: VERDICT: COMPLETE, VERDICT: INCOMPLETE, or VERDICT: UNCERTAIN. Do not simply anchor on a previous completion choice.")
try:
confirmation = llm.chat(confirmation_prompt, max_tokens=500)
except Exception:
confirmation = ""
matches = _re.findall(r"VERDICT\s*:\s*(INCOMPLETE|COMPLETE|UNCERTAIN)", confirmation or "", _re.I)
if not matches:
matches = _re.findall(r"\b(INCOMPLETE|COMPLETE|UNCERTAIN)\b", confirmation or "", _re.I)
confirmed = matches[-1].upper() if matches else "UNCERTAIN"
if confirmed == "COMPLETE":
self.audit_disagreements = 0
return "finish", None
self.audit_disagreements += 1
audit = confirmation
verdict = confirmed if self.audit_disagreements >= 2 else "UNCERTAIN"
audit_reason = "The independent audit found the task incomplete after fresh observation. Regenerate a physically different recovery for the unmet conditions; do not repeat verification: " + (audit or "")[-700:] if verdict == "INCOMPLETE" else ""The three-way verdict is deliberate. A binary audit turns every contradiction between channels into a reason to act, and acting after a success can destroy it; UNCERTAIN may not be used to justify motion. The auditor is also told that a numeric pose identical to its value before an action may be stale, and that a success confirmed by consistent fresh visual reports should not be undone because of one such query.
Commit safety across blocks
Many irreversible failures we saw came from releasing an object that had never been shown to be held,
or from generated code that hid a sweep of grasp attempts inside a loop and spent the trial's
execution horizon. We enforce a commit invariant statically on every proposed program: after a call
whose name begins with close, an open is allowed only if a motion call (goto, move, home)
comes between them. Because closing and releasing often happen in different blocks, the
"holding, awaiting a test" state is carried across blocks and is updated only from code that actually
executed.
@staticmethod
def _commit_events(code, pending=False):
events = []
loops = []
try:
tree = _ast.parse(code)
except SyntaxError:
return False, pending
for node in _ast.walk(tree):
if isinstance(node, (_ast.For, _ast.While)):
loops.append((node.lineno, node.end_lineno or node.lineno))
if isinstance(node, _ast.Call) and isinstance(node.func, _ast.Name):
events.append((node.lineno, node.col_offset, node.func.id.lower()))
for line, _, name in sorted(events):
if name.startswith("close"):
if any(start <= line <= end for start, end in loops):
return False, True
pending = True
elif name.startswith(("goto", "move", "home")):
pending = False
elif name.startswith("open"):
if pending:
return False, False
pending = False
return True, pending
@staticmethod
def _commit_safe(code, pending=False, recovery=False):
if recovery and CustomCodingPolicy._loop_actuation(code):
return False
return CustomCodingPolicy._commit_events(code, pending)[0]Loops with actuation inside them are not banned outright, since a wiping path is a legitimate loop. A gripper close inside a loop is always rejected by the commit check; other actuation loops are rejected only in regenerated code, and only after a block containing an actuation loop has raised an error in this trial.
Recovery allocated by failure mode
On every ordinary turn from the selected turn on, before the coder is asked for a decision, we first decide whether the outcome of the last block is new. We label it by the last exception type in the standard error, or as a physical stall if no exception was raised, with a separate label when the failure is a rejected completion audit. Each label receives at most one ensemble recovery per trial:
def _recover(self, llm, prompt, budget, feedback, audited=False):
if feedback.turn < self.ensemble_turn:
return None
stderr = (feedback.stderr or "").strip()
if "Traceback" in stderr:
last = [line.strip() for line in stderr.splitlines() if line.strip()]
mode = "exception:" + (last[-1].split(":", 1)[0] if last else "unknown")
else:
mode = "physical-stall"
if audited:
mode += ":rejected-completion"
if mode in self.recovery_modes:
return None
self.recovery_modes.add(mode)
return self._ensemble(llm, prompt, budget)The ensemble samples the decision prompt at six temperatures, , keeps the candidates that are valid, commit-safe programs, and asks one further call to synthesise a physically different recovery from them, preserving every satisfied condition. It is skipped when fewer than nine model calls remain or fewer than two valid candidates come back. All other turns use the starter's single regeneration call, with a bounded repair when the answer is invalid or truncated. Every replanning prompt carries the task, the contract and only the newly executed block with its output, not the whole history of failed programs.
Rehearsal chooses how early to explore
The policy has one free choice that we did not want to fix by hand: the earliest turn at which an ensemble recovery may be used. In the optional rehearsal phase we run two practice rollouts for each of (never, from the third decision of a trial, from the first) and select
lexicographically, so that ties go to cheaper and less exploratory variants. From up to two failed rehearsal rollouts of the selected schedule the coder distils at most four generic lessons, with coordinates, dimensions and object identities forbidden, which are shown to later replanning decisions only.
@staticmethod
def prepare(llm, rehearse, budget):
try:
contract = CustomCodingPolicy._make_contract(task_messages(), llm)
except Exception:
contract = ""
variants = [999, 2, 0]
results = {turn: [] for turn in variants}
with _cf.ThreadPoolExecutor(max_workers=3) as pool:
jobs = [(turn, pool.submit(rehearse, {"contract": contract, "ensemble_turn": turn}))
for _ in range(2) for turn in variants]
for turn, future in jobs:
try:
run = future.result()
if not str(run.error or "").startswith("harness fault"):
results[turn].append(run)
except RehearsalLimit:
break
except Exception:
continue
available = [turn for turn in variants if results[turn]]
if not available:
return {"contract": contract, "ensemble_turn": 2}
def rank(turn):
runs = results[turn]
return (sum(bool(run.success) for run in runs), -sum(int(run.model_calls) for run in runs), turn)
selected = max(available, key=rank)
outcomes = {str(turn): {"successes": sum(bool(run.success) for run in results[turn]),
"trials": len(results[turn]),
"model_calls": sum(int(run.model_calls) for run in results[turn])}
for turn in variants}
artifact = {"contract": contract, "ensemble_turn": selected, "outcomes": outcomes}The goal contract written during rehearsal is stored in the artifact and reused in every scored trial, which saves one call per trial. No robot program, scene constant or setting name is stored.
Results
| Method | ① | ② | ③ |
|---|---|---|---|
| Success rate ↑ | Success rate ↑ | Success rate ↑ | |
| Kimi K3.1 Pro | 0.020 | 0 | 0.020 |
| 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 policy did not work on the scored settings. Its success rate is 0.020 on NutAssembly, 0.000 on TwoArmLift and 0.020 on Handover. Against the starter it was built from, the multi-turn text-feedback policy, it is marginally ahead on NutAssembly (0.000) and behind on TwoArmLift (0.080) and Handover (0.040). It is level with the single-shot program on NutAssembly and below it on TwoArmLift and Handover, where that program reaches 0.120 and 0.160. The strongest baseline, the ASPIRE fix loop with evolutionary search [5], reaches 0.120, 0.560 and 0.600 on the three settings.
Our development measurements told a different story, and the gap between them is the main finding of this write-up. On a cube-stacking environment, the final policy succeeded on 2 of 4 scenes where the starter succeeded on 1 of 4, and on a noisy simulator of our own it succeeded on 2 of 3 paired seeds where the previous version succeeded on 1 of 3. These are very small samples, and a two-scene repeat of an earlier version with identical non-error logic went from 1 of 2 to 0 of 2. On the harder tasks we tried in development, no version of the policy succeeded: once both audits were required it refused false completions, as designed, but its recoveries did not succeed. The scored means are consistent with that: a policy whose gains come from refusing to stop early cannot help on a task where the coder's programs rarely achieve the goal at any turn, and the extra audit and observation turns consume regenerations that the starter spends on further attempts.
How we got here
We began from the observation that the starter spends one call per decision and stops whenever the coder declines to regenerate, and that execution globals persist across blocks while success is checked after every block. Both pointed to small, instrumented blocks with fresh postconditions. Alongside real trials we wrote a stochastic scratch simulator that replays generated programs under perception dropouts, grasp failures and unsafe releases, so that premature stops and regressions after success could be counted cheaply.
- Receding-horizon decomposition was abandoned. Our first design fixed a goal contract and forced each block to commit one stage, with a separate critic on every turn. In development it spent turns resampling grasps and missing where the starter's single program succeeded, and both critics accepted commanded motion as evidence of success. We kept the contract and the fresh-evidence gate and dropped the staging.
- A critic on every turn drove loops. One version that kept the starter's regeneration and added a per-turn critic drove loops, and we narrowed the change to the semantics of FINISH alone; its finished scratch run then succeeded but used all 11 blocks and 22 calls.
- An ensemble on every turn bought little. In the scratch simulator a 9-candidate ensemble succeeded in three blocks with 40 calls, where the starter used five. This is why sampling is triggered by observed failure.
- Raw images in recovery generation made things worse. Giving the current render to the ensemble candidates led all six of them to answer FINISH against contradicting geometry, the failure that the CaP-X study describes for image feedback [1]. Images are now given to the auditor only, never to the program writer.
- A formatting miss destroyed a success. The audit originally looked for a YES/NO marker in free text; when the coder omitted it, the parser read the miss as a failed audit and the policy re-grasped a cube it was already holding. Constrained decoding fixed it: in our development measurements, one scene went from 20 calls and a lost success to 6 calls and a success. A later run then showed the opposite fault, a constrained COMPLETE emitted while the model's own reasoning said the task was incomplete, which is why a COMPLETE must be confirmed by a free-form call.
- Stale numbers versus fresh pictures. The auditor once rejected a stack that several scene reports had confirmed, because a numeric pose query was stale, and the next block grasped the stack again. We added the last three scene reports to the audit and the rule not to undo a convergent success; we later had to restrict it, after the auditor dismissed a changed, valid numeric contradiction as stale.
- Prompts that grew with every failure. Long traces showed the coder anchoring on every earlier failed program while the context approached its limit; we switched to prompts that carry only the newly executed block.
- A global ban on actuation loops broke wiping. Rejecting all recovery loops removed blind grasp sweeps, which in one stacking trial had tried 13 heights inside a single block, but a wiping trial under that rule never executed a wiping motion. The final rule fires only after an actuation loop has actually raised an error. In our final paired runs it never fired, so the improvement we measured there is not attributable to it.
- Per-trial contracts did not clearly help. After a full rehearsal run in which five of six rehearsal rollouts succeeded and the following trial failed, we tried deriving a fresh contract in every trial. It showed no clear advantage and cost one call per trial, so the shared contract stayed.
- Truncated answers ended trials. A truncated coder answer raised an error and ended a trial during recovery; ensemble synthesis and ordinary regeneration now treat it as an invalid answer and retry with a bounded repair.
The final selection between our last two versions rested on 4 real scenes, and the decision to keep it on 3 further paired scratch seeds; in between, a repeat of the identical final policy failed one cube-lift trial that it had passed before, and one regression seed that its predecessor had passed. We reported these at the time and kept the version with the better paired count.
Limitations
- The policy failed on the scored settings. Its success rate is at or near zero on every setting, below the single-shot program on TwoArmLift and Handover and far below the ASPIRE baseline. Whatever the evidence gate contributes, it does not show in the measured results.
- The gate cannot create successes. Every mechanism we added either prevents a false stop, prevents a destructive action after a success, or reallocates samples. None of them makes the coder's programs better at reaching the goal, and when they rarely reach it, the observation and audit turns only take regenerations away from further attempts.
- Our development evidence was too small to select on. Versions were compared on two to four real scenes and three scratch seeds, and outcomes of identical code varied between runs by as much as the differences we acted on. Choosing among many variants on such samples overfits the selection itself [6]; the rehearsal phase repeats the problem on two rollouts per schedule.
- The audit is the same model. Both auditors are the frozen coder. A constrained verdict contradicted the model's own reasoning in our development runs, and requiring them to agree reduces but does not remove correlated errors.
- Static checks work by name. The commit and observation-only checks match function names by prefix. An API whose actuation calls do not begin with the listed verbs, or a program that actuates through an attribute call, passes them unchecked.
- The audit costs turns and calls. Each proposed stop costs at least one block and two model calls, which a trial with a tight regeneration limit may not be able to afford.
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.
- 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.
- Cynthia Dwork, Vitaly Feldman, Moritz Hardt et al. (2014). Preserving Statistical Validity in Adaptive Data Analysis.