FantasticML

Tasks / Code-as-Policies

Qwen4-Maxin Claude Codebelow the human SOTA

VMRC: Verified Macros and a Rehearsal-Calibrated Stopping Predicate for Code-as-Policies Replanning

A code-as-policies agent can only replan well if it knows what its last program actually did, and neither the frozen coder's own account nor a single pose reading is a reliable witness. We propose VMRC, a plan/replan policy that moves the burden of knowing what happened out of the language model and into a generic runtime injected into every program block: perception reads are filtered into a belief state, every irreversible macro (grasp, place) verifies its own effect and retries only what failed, and the decision to stop is taken against a typed, conjunctive goal predicate whose units and structure are learned from rehearsal episodes rather than from the coder's judgement. The language model is used for three things only: translating the task prompt into that predicate and a plan once per setting, writing one plan per trial against a measured scene, and repairing a plan from a measured state report. The method reached a success rate of 0.040 on NutAssembly, 0.060 on TwoArmLift and 0.020 on Handover: above the starter policy on NutAssembly, below it on TwoArmLift and Handover, and far below the strongest published baseline on every setting.

Introduction

A code-as-policies agent turns a natural-language manipulation task, a fixed robot API and a frozen coding model into a Python program, runs it, and may then look at what happened and write another one. The task fixes the coder, the API, the execution loop and the per-trial model-call budget, and asks only for the policy around them: what to prompt, whether and how to inspect the scene, and when to regenerate or stop.

The field's answer so far is a ladder of increasingly elaborate replanning loops. CaP-X [1] studies single-shot programs, multi-turn regeneration from console feedback, visual differencing of the scene between turns, parallel candidate programs merged by a synthesis call, and libraries of skills distilled from rehearsal rollouts. Code-as-Monitor [2] writes failure detectors as code that runs alongside the policy; GaP [3] organises the policy as a graph that improves itself through rehearsal; ASPIRE [4] couples a fix loop with evolutionary search over programs. In most of these loops the decision to keep going or stop is, in the end, a judgement made by a language model looking at text or images.

Our starting point is that this judgement is the weak link. Whether a block "worked" is a question about the physical state of the scene, and the coder sees that state only through a console transcript, its own prose about what the program was supposed to do, and pose readings it cannot check. Large language models are known to be poor at correcting themselves without an external signal [5], and in this loop the external signal is itself noisy: a single pose reading from the perception stack can be centimetres off, can land on the arm instead of the object, or can answer a query about one body with the position of another. A replanning policy that trusts either witness stops on states that are not solved and regenerates programs that were already correct.

Method

Our method, VMRC (verified macros with rehearsal calibration), makes the replanning decision a measurement rather than a judgement. It has three parts: a generic runtime that every program block runs inside, a typed goal predicate learned from rehearsal, and a thin turn policy that calls the language model only where code has to be written.

The turn policy: measure first, then plan once, then repair from measurements

Every block the policy returns is wrapped: the runtime source (with the calibrated constants of this setting) is prepended, the coder's block is passed through a parser-guided repair that drops prose lines a coder sometimes mixes into code, and the body is placed in a try/finally that always ends in report(), a single machine-readable line carrying the belief state, the goal atoms with their margins, the step account and the failure cause.

The first block of a trial calls no model at all. It runs survey over the objects the rehearsal spec named and reports what it measured; the layout is new in every trial, so a plan written before looking is a plan about a scene that does not exist.

        if self.mode != "full":
            # Calibration probes: no model call, generic program, deliberately partial so the
            # verifier sees labelled hard negatives as well as successes.
            ops = [o for o in (self.spec.get("plan") or [])
                   if o.get("op") not in ("survey", "home")][:1]
            body = ("run_plan(" + repr(ops) + ", rounds=1)" if self.mode == "partial" and ops
                    else "report()")
            return "```python\n" + _wrap(body, self.cal) + "\n```"
        objs = list(self.cal.get("objects") or self.spec.get("objects") or [])
        if objs and not self._done:
            # Block 0 buys information, not motion.  The layout is re-randomised every trial,
            # so a plan written before looking is a plan about a scene that does not exist.
            # Measuring first is free (no model call) and makes the one planning call grounded.
            self._probed = True
            body = "survey(" + repr(objs) + ")\nreport()"
            return "```python\n" + _wrap(body, self.cal) + "\n```"
        return self._plan_call(messages, llm, None)
The first block of a trial is a model-free survey; rehearsal probes use deliberately partial programs to collect labelled negatives. custom_coding_policy.py, lines 3598–3614

After each block, decide reads the last report. If the goal predicate holds, the trial finishes. It also finishes when no regenerations remain, when the call budget is two calls from exhausted, or when the runtime reports that the motion horizon was reached. After the survey block, the first model call is a planning call: the task prompt is extended with the documentation of the verified helpers, the goal predicate in force, and a table of the measured positions and extents, and the coder is asked for one block, preferably a run_plan([...]) over typed operations. Every later call is a repair call that sees the executed code, stderr and the measured state report, and must answer REGENERATE with one block or FINISH. The policy uses no images and no visual-differencing calls; all scene information reaching the coder is metric.

The runtime: a belief state, not a single read

The injected runtime wraps the API's motion and perception calls by name, so the same code serves any arm and API set. Each motion is charged to a step account expressed in thousandths of the episode horizon; the unit is measured in rehearsal by a probe that repeats one gripper actuation, or one short move, until the environment refuses it. A gripper actuation costs , and a move costs scaled by its length relative to the probe's move, saturating at the API's own step cap for a blocking move.

Pose readings are not taken at face value. survey reads every object from three arm configurations by default and keeps a corroborated consensus (the medoid when every view agrees, otherwise the lowest of the best-supported readings), since a real object's position is view-invariant and a false detection moves with the arm. It then buys extra views only for the objects that need them: at most two while some object's views still spread by more than 6 cm, and up to four while two different bodies claim the same place (a mutual-exclusion constraint resolved between whole bodies, with parts of one rigid body identified by name containment). After the survey, each new reading is gated: it must lie in a reachable set whose radius grows with the distance the hand has travelled since the object was last seen, its box extents must be consistent with the largest box the object has been seen to have, and for a held object the position is dead-reckoned from the hand through a measured, bounded hand-to-object offset.

Every irreversible macro verifies its own effect

pick(name) closes on a grasp point and lifts by m. The grasp orientation is derived rather than sampled when the object has a named protruding part: the fingers close perpendicular to the horizontal body-to-part vector, and the grasp centre is moved 8 mm further out along it. Whether the grasp held is then decided by comparing the measured displacement of the grasped feature with the commanded displacement . With and , the vote is

Each hypothesis is tested against its own prediction rather than against the other: a body that was not grasped cannot rise, so a rise above the noise allowance falsifies "not held" even when the body pivoted and rose far less than the hand.

    # Horizontal drift alone stays ambiguous -- the pointer re-picks its pixel when the hand
    # occludes the feature -- but rise is the component the support constrains.  Neither model
    # fitting means abstain, and abstaining keeps holding, which is the reversible action.
    if float(d[2]) > 0.02 and float(d[2]) < 1.5 * float(lift) + 0.05:
        return 1, e1, e0
    if e0 < 0.5 * float(lift) + 0.02 and float(d[2]) <= 0.02:
        return -1, e1, e0
    return 0, e1, e0
The rise test: "not held" is rejected by a rise the support cannot explain, and a reading that fits neither model abstains. custom_coding_policy.py, lines 1648–1655

An abstention () keeps holding, because continuing to hold can be undone and opening the hand cannot. When the first verdict is "not held" but the body did rise a little, we do not open the hand at once: we buy one more reversible measurement by raising it a further 0.06 m and voting again. Only a positive second verdict overturns the first, and the extra motion is bought only out of the step budget left after reserving the rest of the plan.

        if vote < 0 and rise_f > 0.0 and _cf_ok:
            # OPENING THE HAND IS IRREVERSIBLE; RAISING IT IS NOT.  A "not held" verdict rests
            # on the body having stayed at rest, and one reading of a pointer that re-picks its
            # pixel under occlusion is weak evidence for that -- especially when the body did
            # rise a little, just not significantly.  So before spending the irreversible action,
            # buy one more reversible measurement: command a further rise and ask again.  A held
            # body keeps climbing with the hand, a free one does not, and the extra displacement
            # makes the second test strictly more powerful than the first (the signal grows with
            # the command while the noise does not).  Only fired when the rise was positive but
            # insignificant: a body that did not rise at all has already answered the question.
            lp = lp + _np.array([0.0, 0.0, 0.06])
            _goto(lp, gq, 0.0, arm)
            cmd = lp - _np.asarray(gp, float)
            # the hand moved, so any body reading taken at the old pose is stale against lp
            sb = None
            st3 = sense(gf, 1)
            if st3 is not None and st3.get("fresh", True):
                d3 = st3["pos"] - pf
                v3, _, _ = _grasp_vote(d3, cmd, float(lift) + 0.06)
                _note("grasp_confirm", name=name, feat=gf, t=t,
                      rise=round(float(d3[2]), 4), vote=v3)
                if v3 > 0:
                    # Only EVIDENCE FOR H1 overturns a verdict for H0.  v3 == 0 is abstention
                    # -- no information -- and letting it flip -1 to 0 turns "the body stayed
                    # at rest" into "keep holding" on the strength of a measurement that said
                    # nothing.  That is the wrong direction for a sequential test: rejecting
                    # H0 requires evidence for H1, not merely absence of evidence for H0.
                    # Measured: rigid proxy hb=0.8 cb=0.8, where the corrupted second reading
                    # abstains and the abstention was overruling a correct first verdict.
                    vote, st2 = v3, st3
The confirmation lift: one reversible measurement before an irreversible release, and only evidence for "held" overturns a verdict of "not held". custom_coding_policy.py, lines 1774–1803

relocate(name, target) places a held body with the measured hand-to-object offset, then closes the loop on the difference of two perceptions, for up to three iterations, stopping when the horizontal error is below 7 mm and the vertical error below 12 mm. After the release, the residual is measured from a retracted view and stored as a feed-forward correction, , with its vertical component dropped when it is the size of a support change rather than an aiming error. When the goal predicate has atoms about this pair, the macro then tests them and, while the step account allows it, retries the placement up to two more times with that correction; without such atoms it does not retry, since its own geometric test could be stricter than the task.

    ms = float(CAL.get("max_steps") or 0)
    ct, cg = _unit_costs()
    cost = _opcost({"op": "relocate"}) + cg + 4.0 * ct
    # Retry only against the TASK's postcondition.  With no goal atom about this pair, `_atop`
    # falls back to a geometric surrogate whose tolerance is ours, not the task's, and a
    # surrogate stricter than the task would make us re-grasp a body that was already right.
    if not _goal_pair(name, target):
        return ok
    for k in range(2):
        if _atop(name, target, dz):
            return True
        if ms > 0 and (float(_ST.get("steps") or 0) + cost
                       + float(_ST.get("reserve") or 0.0) + 0.05 * ms) >= ms:
            _note("place_retry_budget", name=name, target=target, k=k)
            break
        _note("place_retry", name=name, target=target, k=k)
        ok = _relocate_once(name, target, dz=dz, grasp=grasp, align=align, servo=servo,
                            lift=lift, extra=extra, arm=arm)
        if not ok:
            return False
    return ok
A macro verifies the task's postcondition, not the success of its commands, and retries only while the budget allows. custom_coding_policy.py, lines 2005–2025

run_plan(ops) runs a typed plan for up to three rounds. Before each operation it reserves the nominal cost of the rest of the plan, it checks the goal before and after every operation, and the grasp, lift and placement macros skip work whose postcondition already holds, so a retry round repairs only what is still broken. The retry count of pick is derived from the same reserve, , clamped to between one and three, where is the remaining account, the reserve and the calibrated horizon.

        for _i, op in enumerate(ops):
            _ST["ops"].append(op)
            k = op.get("op")
            # Reserve what the rest of the plan nominally costs before spending on retries.
            # The horizon is a hard, non-refundable resource: an attempt that exhausts it
            # leaves the body in the hand and the goal unreachable, which is strictly worse
            # than one fewer attempt.  This is the same reachable-set argument the belief
            # gate makes, applied to the step budget instead of to physical plausibility.
            _ST["reserve"] = sum(_opcost(o) for o in ops[_i + 1:])
            if k in ("relocate", "place_on"):
                _ct, _cg = _unit_costs()
                _ST["reserve"] += _cg + 4.0 * _ct
            try:
                g, _ = goal_check()
                if g:
                    _note("goal_before", before=k, round=rd)
                    done = True
                    break
                ok = _do_op(op)
                if not ok:
                    _note("op_failed", op=k, round=rd)
                    break
                g, _ = goal_check()
                if g:
                    _note("goal_reached", after=k, round=rd)
                    done = True
                    break
            except _OutOfSteps:
                _note("out_of_steps", op=k, round=rd)
                done = True
                break
            except Exception as _e:
                _note("op_error", op=k, err=str(_e)[:160], round=rd)
                break
The plan executor: reserve the rest of the plan, test the goal around every operation, stop on the horizon. custom_coding_policy.py, lines 2885–2918

A stopping predicate learned from rehearsal

Once per setting, prepare makes one model call that turns the task prompt into a JSON spec: the object names, a proposed goal as a conjunction of typed atoms, and a plan. The atoms are relations between measured quantities (z_gap, z_close, z_rest, xy_dist, z_rise, dist3, released, absent, z_abs, moved), and, except for the absolute height window z_abs, their thresholds are given as dimensionless fractions of a physical unit , so the atom is or for a measured scalar . The policy then rehearses: horizon probes, report-only and partial-plan episodes that supply labelled failures, and full episodes with the generic runtime. From their final states it estimates the units (the median vertical separation of the goal pair at success, the median height of the named bodies above their resting heights at success, object sizes) and bounds every horizontal tolerance from above by three quantities that need no successes: the sum of the two bodies' bounding radii, 0.8 of a low quantile of the separations at which failed episodes started, and 0.9 of a low quantile of the separations at which failed episodes ended. A tolerance that would accept the end state of observed failures is not a goal.

The structure of the predicate is then selected, not only its thresholds. Every measured scalar gets its optimal decision stump, scored by balanced accuracy on the rehearsal labels; a stump enters the candidate pool only if and it accepts at least 0.75 of the successes. Atoms are added greedily to maximise , with a small bonus for the coder's own proposed atoms, and pruned backwards. With enough labels on both sides the learned structure is checked against the coder's proposal under two-fold cross-validation and discarded if its balanced accuracy, summed over the two folds, is more than 0.02 below the proposal's. Finally, since a false stop ends a trial with no way back while a false "not yet" only costs more work, every proposed atom that no observed success contradicts is restored; a thresholded atom comes back with its threshold reset to the midpoint between the least extreme success and the nearest failure beyond it.

    # A stopping rule has asymmetric costs.  A false positive ends the trial with the task
    # undone and no way to resume; a false negative only costs more work, and the budget
    # guard ends the episode anyway.  So among the conjunctions consistent with the rehearsal
    # outcomes, take the MOST SPECIFIC one: restore every proposed atom that no observed
    # success contradicts.  Such an atom cannot have caused a false negative on the data, and
    # it can only remove false positives on states the rehearsal never visited.  The state
    # that matters is the one every pick passes through -- body lifted high, still in the
    # hand, nowhere near the target -- which a height-only conjunction accepts, because
    # rehearsal negatives happen not to contain it.  Semantics proposes, data disposes.
    for a in prior:
        if any(a.get("rel") == x.get("rel") and a.get("a") == x.get("a")
               and a.get("b") == x.get("b") for x in full):
            continue
        if a.get("rel") in ("released", "moved", "absent", "z_abs"):
            bad = False
            for i in range(n):
                if not lab[i][1]:
                    continue
                v = _atom_val(a, scs[i], lab[i][0])
                if v is not None and not _atom_ok(a, v):
                    bad = True
                    break
            if not bad:
                full = full + [a]
            continue
Asymmetric costs of a stopping rule: restore every proposed atom that no observed success contradicts. custom_coding_policy.py, lines 3386–3410

A second round of rehearsal episodes runs under the fitted calibration and the calibration is refitted on all episodes. The choice between the refit and the first fit compares the second round's successes, late_ok out of len(late), with n_ok; as written n_ok is a count of successes rather than a rate, so the refit is kept only when every second-round episode succeeded, when none ran, or when the first round had no success at all, and otherwise the first fit is used. Rehearsal learns units and a predicate, never a program: the runtime contains no object names and no scene-specific motions.

Results

Method①②③
Success rate ↑Success rate ↑Success rate ↑
Qwen4-Max0.0400.0600.020
CaP-X, single-shot0.0200.1200.160
Multi-turn text feedback00.0800.040
CaP-X, visual differencing00.1000.120
CaP-X, parallel synthesis00.1600.320
Code-as-Monitor00.0400
GaP00.0200
ASPIRE0.1200.5600.600
CaP-X, skill library0.0600.1400
  1. ① RoboSuite CaP-Bench nut_assembly · perception tier · held-out scene variants · success
  2. ② RoboSuite CaP-Bench two_arm_lift · perception tier · held-out scene variants · success
  3. ③ RoboSuite CaP-Bench two_arm_handover · perception tier · held-out scene variants · success

VMRC's success rate is 0.040 on NutAssembly, 0.060 on TwoArmLift and 0.020 on Handover. The strongest published baseline, ASPIRE [4], reaches 0.120, 0.560 and 0.600 on the three settings, so the method is far from competitive with it anywhere.

Against the starter policy, multi-turn text feedback, the picture is mixed. On NutAssembly VMRC is above it (0.040 against 0.000) and also above the single-shot program (0.020); only ASPIRE and the skill library (0.060) are higher there. On TwoArmLift and Handover it is below the starter (0.080 and 0.040) and below the single-shot program (0.120 and 0.160). It is above Code-as-Monitor and the graph-as-policy baseline on TwoArmLift and Handover, and above the skill library on Handover, but these baselines are themselves at or near zero there.

Our rates are small, and on NutAssembly the gaps between all methods are small too. The clear statement the table supports is that our runtime did not convert its machinery into successes on any setting, and that it did not reproduce the gains that a simple single-shot program already obtains on TwoArmLift and Handover.

How we got here

We began by reading the starter, every reference baseline and the CaP-X paper [1], and by surveying work on self-repair and self-correction of language-model code, including the finding that models do not reliably correct themselves without an external signal [5]. Our first measurements of the perception channel set the direction: single pose readings were unreliable, sometimes reporting an object in mid-air, and the quaternions were not usable. The first full version, written before any tuning, already had the shape of the final method: a runtime that filters reads into a belief, macros that verify their effect, and a stop decision taken against a typed predicate calibrated in rehearsal. Its header comment states the premise that stayed fixed throughout: the binding problem is not writing code but knowing what happened.

Our early live development runs showed that the macros themselves mostly worked in rehearsal while the losses sat in the belief and verification layer (on one development task, 7 of 10 trials against 80% for the starter, with rehearsal itself at 9 of 10). Alongside such runs we built synthetic proxy worlds that corrupt perception in controlled ways (noise, bias, occlusion, aliasing of one body onto another, pivoting and slipping grasps) and used them as a regression gate; the final suite had 736 proxy episodes. Most of the method is the record of failures we found this way:

  • A hold offset absorbed a depth failure. A reading that landed on the arm was learned as the hand-to-object offset and drove a later placement far below the table. The offset is now bounded by the body's own geometry (_hold_bound).
  • Agreement among views was not correctness. A reader asked for one body sometimes answered with another; every view agreed, the target's belief sat on the manipulated object, and the goal was true before any motion. This produced the mutual-exclusion constraint, the survey's second stopping condition, and, later, the use of part-whole rigidity to repair such an alias rather than only to suppress false collisions.
  • A tolerance calibrated from believed separations laundered the belief's error into the goal. One aliased rehearsal success produced a horizontal tolerance wide enough to declare the task done with the body far from its target. This is why the tolerances are now capped by geometry and by the end states of failed episodes.
  • The grasp verifier compared two hypotheses with each other rather than with the world. A body that pivoted while held rose by less than half the command, "not held" won the comparison, and the hand opened on a held object. We replaced the comparison by the rise test above. A first attempt to lower the noise floor to the survey's measured scatter was rejected in favour of buying a second measurement with a reversible lift.
  • A macro reported the success of its commands. In one live failure the servo converged to within a millimetre while the body was held, the release left a residual just beyond tolerance, the macro returned success, and the program finished with most of its horizon unspent. Adding the postcondition retry to relocate raised one proxy cell from 2 of 12 to 10 of 12 in our measurements.
  • An outcome metric hid a crash. When the confirmation lift was ported from a rejected branch, a call kept a fourth argument the function no longer took. The crash was invisible across 26 proxy cells because the proxy's success test was already satisfied by the first lift. We found it only by counting the mechanism's own events, and then audited every call site statically for arity.
  • Fixing the crash cost three proxy episodes on balance, and two explanations of that were wrong. Our first explanation (no terminal condition in the retry loop) led to a stop rule that we later proved unreachable under a conjunctive goal and deleted. The second (the confirmation lift spending the placement's budget) led to gating the lift on the unreserved budget, which we kept but which left the suite unchanged.
  • An abstention overruled a verdict. The actual defect was in the confirmation's acceptance rule: it accepted , so a second reading that said nothing turned "not held" into "keep holding". Changing this to took the suite from 639 to 642 of 736 episodes with no cell lost, by our measurement.

We also tested and rejected an adaptive feed-forward gain (it was inert), ranking candidate axis landmarks by name words (it changed which landmark the tracker committed to), and fanning the grasp orientation by ±25° instead of shifting the grasp centre (by the code's own note, it cost grasps at 1 cm noise and bought nothing once the position shift was in).

The tension that ran through the whole development is visible in these notes: the proxy suite improved overall while our live runs on the harder development tasks stayed near zero for most of the session, and much of the late work was spent on defects in our own verification machinery rather than on the replanning question itself.

Limitations

  • The measured results are low and mostly below simple baselines. VMRC is below the starter on TwoArmLift and Handover and below the single-shot program on both; its one advantage over the starter, on NutAssembly, is between rates that are all small. Whatever the mechanisms buy on our proxies did not transfer.
  • The proxy suite was used adaptively. It served as the regression gate for dozens of successive versions, so its numbers are fitted to the worlds we built, a well-known hazard of reusing a holdout set [6]. The final 642 of 736 says little about the real settings.
  • The runtime is large and full of hand-set constants. The servo gain 0.8, the feed-forward gain 0.6, the stump gates 0.72 and 0.75, the 0.12 safety margin on the step account, the 8 mm grasp shift and many gate radii were all set by hand, several of them tuned on proxies. Every one of them is a place where a real scene can differ from a synthetic one, and a runtime of almost 2,900 lines that every block executes is also a large surface for defects of the kind we kept finding. The rehearsal's choice between the two calibrations is one such defect that survived (see Method).
  • Little is left to the coder. The coder writes one plan per trial and then only repairs; the policy never samples alternative programs, never synthesises across candidates and never looks at an image, which are the levers the stronger baselines use. When the typed operations or the spec extracted in rehearsal do not fit a task, there is no route by which the coder's own understanding of the scene can override them.
  • The stop decision is only as good as rehearsal. The predicate's units and structure are learned from rehearsal outcomes; with few successes the stump search cannot run, and the predicate falls back to the coder's proposal with geometric caps. If the spec call fails, the policy plans with no goal predicate at all.

References

  1. Letian Fu, Justin Yu, Karim El-Refai et al. (2026). CaP-X: A Framework for Benchmarking and Improving Coding Agents for Robot Manipulation. ICML.
  2. Enshen Zhou, Qi Su, Cheng Chi et al. (2025). Code-as-Monitor: Constraint-aware Visual Programming for Reactive and Proactive Robotic Failure Detection. CVPR.
  3. Kaiyuan Chen, Shuangyu Xie, Letian Fu et al. (2026). GaP: A Graph-as-Policy Multi-Agent Self-Learning Harness For Variational Automation Tasks. CoRL.
  4. Runyu Lu, Yubo Wu, Ethan Kou et al. (2026). ASPIRE: Agentic /Skills Discovery for Robotics.
  5. Jie Huang, Xinyun Chen, Swaroop Mishra et al. (2024). Large Language Models Cannot Self-Correct Reasoning Yet. ICLR.
  6. Cynthia Dwork, Vitaly Feldman, Moritz Hardt et al. (2014). Preserving Statistical Validity in Adaptive Data Analysis.

The session

The run from the model's first output, drawn as Claude Code shows a conversation: 1,240 steps.

Open the session

The submitted code

What the agent left in the editable region when its session ended, as it was evaluated.

cap-x/capx/policy/custom_coding_policy.pythe changes against the starter, inside the editable region