Back

Harness Adaptation
via Corrective SFT

Post-mortem: MiMo 9B on-policy SFT in Remy

Published Nov 6, 2026 · 13 min read

When deploying a coding agent into a new execution harness, raw model capability is rarely the initial bottleneck. Instead, the bottleneck is interface friction: the model repeatedly invokes undeclared tool names, passes invalid arguments, or hallucinates JSON schemas built into its pre-training priors.

In multi-turn reinforcement learning (RL), this friction is fatal. Invalid tool calls waste rollout budgets, inflate step latency, and drown task-level reward signals in formatting noise. If your team is adapting an open-weights model to an internal agent framework, fixing tool schemas before starting RL is critical to avoiding wasted compute.

Over eight iterations, we adapted MiMo-V2.6-Distill-Qwen-9B to Remy, our internal execution harness. By truncating the model’s own on-policy trajectories at the first formatting error and applying corrective Supervised Fine-Tuning (SFT), we reduced undeclared tool calls from 9.00% to 0.13%. However, end-to-end task resolution (pass@1) moved from 21.9% to 23.2%—within the noise floor.

Below is the empirical breakdown of every iteration: why standard off-policy cloning failed, how tokenizer mechanics caused probability overshoot, and what still separates a clean tool interface from solved tasks.

1.The Problem: Tool Schema Mismatch

Coding agents cannot manipulate repositories directly; they act entirely through tools declared by their execution harness—reading files, searching code, editing text, and running shell commands. As documented in FineEnvs’ Multi-Harness RL Guide, harnesses vary widely in tool names, argument schemas, and control flows. A model’s pre-trained tool habits rarely align out-of-the-box with a new target environment.

We evaluated MiMo-V2.6-Distill-Qwen-9B inside Remy. Remy declares run_command for shell execution and does not expose a bash tool. However, the base model is heavily biased toward invoking bash. Worse, Remy enforces atomic batch authorization:

Model output for one turnHarness returnsbash ls src/grep "TODO"read_file main.pyRemy auth checkFinds undeclared bash→ Rejects the batchbashgrep(collateral)read_file(collateral)bash is not declared in Remybatch_tool_not_authorizedNext turn: the model writes bash again (704 times after being rejected)In one RL run with 382 sessions, base wrote bash in 282 sessions, 2,301 times in total.

Fig. 01One bash call voids the whole batch

If a single tool call in a multi-tool turn references an undeclared tool, Remy rejects the entire batch of calls for that turn.

Across a 382-session baseline RL run, interface mismatches severely degraded throughput:

  • Cascading batch failures: 282 sessions invoked bash a total of 2,301 times—each time invalidating valid grep and read_file calls grouped in the same turn.
  • Zero in-context recovery: After receiving explicit harness rejection errors, the model still invoked bash an additional 704 times.
  • Schema & JSON errors: The model generated 1,467 calls with extraneous parameters (e.g., passing -n flags or undefined description fields to grep) and failed JSON parsing on 36% (752 / 2,113) of its edit_file calls.

2.Why Fix the Model Before RL?

When facing schema mismatches, engineers typically reach for two workarounds. We rejected both:

Rewriting calls in the training gateway (bash → run_command): A translation proxy only alters what the harness sees; the model’s generated tokens and logprobs are recorded as-is for RL updates. If we alias the tool in the gateway, the model continues generating bash, RL reinforces those exact tokens, and the model never learns run_command. Because our production deployment lacks a translation layer, our core engineering constraint is strict: treat the harness as a black box, keeping training and deployment environments identical.

Letting RL reward signals fix the formatting: Because the model repeated bash 704 times after seeing rejection messages, it clearly could not self-correct in-context. On our cluster, a single RL step (128 sessions) takes roughly two hours, gated by the slowest trajectory. Tool rejections add multiple wasted turns to every trajectory. Relying on RL to unlearn formatting habits burns massive compute while drowning true task rewards in syntax penalties.

Our goal became clear: run a lightweight, cold-start SFT phase prior to RL so the model natively speaks Remy’s tool interface.

3.Why This Is Harder Than It Looks: The Decision Token

Decision tokenbash (undeclared)<function=bash>run_command<function=run_command>read_file<function=read_file>grep<function=grep>At the decision position, =b, =, =read and =grep compete.Training =b → = raises =, which is run_command’s decision token.Other-tool positions (protocol A)0.00.20.40.60.80.7050.516P(own name)0.2830.487P(run_command)basev1After v1 (which only corrects =b → =), P(run_command) at other-tool positions rises from 0.283 to 0.487.

Fig. 02The decision token: where the tool name is decided

Left: How the tokenizer splits four tool names. The specific tool called is determined at the single token immediately following <function—which we call the decision token. At this position, =b, =, =read, and =grep compete directly. Right: After v1 training (which only penalized =b), the average probability of the decision token at other valid tool positions shifted dramatically toward = (see Section 5).

Tokenization mechanics turn a simple string replacement into a delicate probability balancing act. To change <function=bash> into <function=run_command>, the model must replace the merged token =b with the standalone token = (followed by run).

However, boosting the logit for = directly competes with every specialized tool whose name starts with a merged token (=read, =grep, =list). Suppressing one error pulls down the probabilities of valid tool calls across the board. Nearly all of our iterative engineering focused on managing this tension between error correction and capability retention.

4.Evaluation Methodology

As our understanding of the failure modes evolved, we updated our evaluation harness three times whenever existing metrics could no longer answer our next engineering question:

  • Protocol A — Session Holdout at the Decision Token (v0–v5): 60 held-out sessions from the model’s own trajectories. We feed the exact historical prefix and inspect the probability distribution at the decision token without running generation.
    • bash Correction Rate: Fraction of original bash positions where run_command becomes the top-1 token (Target: ≥ 0.85).
    • Retention Rate: Fraction of valid non-bash tool calls where the original tool remains top-1 (Base: 0.784). Target: retain ≥ 92% of base performance on grep (≥ 0.63), glob_files (≥ 0.53), and list_files (≥ 0.41).
  • Protocol B — Task Holdout on Full-Span Edits (v6–v7): Split by task rather than session to prevent data leakage. Measures accuracy at the critical token (the first token requiring modification) and exact full-span match across all tokens up to </function>.
  • Protocol C — eval32 Greedy Execution: End-to-end evaluation across 32 unseen tasks in a live sandbox (1 rollout per task, greedy decoding), graded by repository unit tests.
  • Protocol C′ — eval32 Sampled Execution: The same 32 tasks evaluated with 4 rollouts per task at temperature = 1.0, measuring pass@1 through pass@4.

(Note: Because Protocols A and B use different holdout splits and metrics, we do not plot v0–v7 on a single continuous curve. All SFT runs use single-seed LoRA: rank = 32, alpha = 64, applied to all linear layers, lr = 1e-4, 2 epochs.)

5.Eight Iterations of SFT

Overview of iterations v0–v7 plus the prod control experiment across three distinct phases. Each phase transition occurred when the previous paradigm hit a hard ceiling.

Stage 1 · Imitate demosv0 · prodSFT on other models’ demosbash correction 0.254 / 0.220Other tools got worseStage 2 · Patch own errorsv1 → v2 → v3 → v4 / v5Fix wrong token + keep labelsbash correction 0.73–0.89Retention 0.59–0.74Correction vs. retention trade-offStage 3 · Reframe the taskv6 → v7Clean prefix · full-call labelsTask-level holdoutKey position: 0.054 → 0.730Iterative correction, round 2Demos fail → own trajectoriesTuning stalls → fix the labelseval32, 4 samples/task: undeclared calls 9.0% → 0.13%; pass@1 21.9% → 23.2% (within noise)

Fig. 03Three stages across eight iterations

5.1Phase 1: Off-Policy Imitation (v0, prod)

v0 (Standard SFT on Expert Demonstrations):

  • Hypothesis: Show the model valid Remy trajectories from stronger models.
  • Method: Standard full-assistant-loss SFT on 34 successful Remy trajectories (9 tasks) generated by Claude and DeepSeek.
  • Result: bash correction rose from 0.099 to just 0.254. Worse, after one step of RL, malformed calls jumped from 0.05 to 0.60 per session, and the model began hallucinating nonexistent tools like create_patch and edit_project.
  • Takeaway: Classic behavior cloning distribution shift. Off-policy expert trajectories never visit the specific states where MiMo is tempted to write bash. The model learned to mimic expert surface style rather than correcting its own failure states.

prod (Scaling Up Expert Data 10x):

  • Hypothesis: Rule out sample size—perhaps 34 trajectories was simply too small.
  • Method: 335 filtered expert trajectories (~10x v0), truncated to match the exact RL tool declarations.
  • Result: bash correction stalled at 0.220 (47.1% of bash positions still preferred bash), while overall retention dropped from 0.784 to 0.663.
  • Takeaway: Scaling off-policy demonstrations does not fix on-policy formatting habits. We abandoned expert cloning entirely.

5.2Phase 2: On-Policy Token Patching (v1–v5)

To fix errors in states the model actually visits, we shifted to an iterative on-policy correction loop (similar to DAgger): collect rollouts from the current policy, apply deterministic rewrite rules to label errors, merge with retention data, and retrain.

v1 (Single-Token Correction):

  • Method: Using the model’s own trajectories, we relabeled all 1,392 =b decision tokens to =. To prevent forgetting, we added a 1:1 ratio of retention labels on the decision token of valid tool calls, continuing training from v0.
  • Result: bash correction jumped to 0.885 (with bash top-1 dropping to 0). However, retention crashed from 0.784 to 0.594; at valid tool positions, the probability of choosing run_command surged from 0.283 to 0.487 (Figure 2, Right).
  • Takeaway: On-policy supervision works immediately, but single-token patching causes severe probability overshoot into =.

v2 (Full Tool-Name Retention):

  • Method: Expanded retention labels to cover all tokens in valid tool names (e.g., =read, _file, >), increased the retention-to-correction ratio to 2:1, prioritized read_file and grep, and trained fresh from base.
  • Result: Overall retention recovered to 0.701, but specialized tools degraded heavily: grep (0.552), glob_files (0.359), and list_files (0.261).

v3 (Targeted Tool Protection + Forward KL Anchoring + Edit Fixes):

  • Method: Explicitly oversampled retention labels for the three degrading tools (1,001 grep, 310 glob_files, 146 list_files) at a 3:1 overall ratio. Added a forward KL penalty against base at 256 random anchor tokens per trajectory. Merged 313 bracket-repaired and context-verified edit_file samples.
  • Result: Overall retention reached 0.742 and grep passed the target bar (0.683), but bash correction fell to 0.731. On a 22-row edit_file holdout, critical-token accuracy hit 1.000, but full-JSON exact match was only 1/22.
  • Takeaway: Revealed a rigid Pareto frontier: stronger protection directly weakens bash correction. Furthermore, fixing the first token of a broken JSON edit does not mean the model can complete the rest of the payload.

v4 & v5 (Upweighting Correction Loss):

  • Method: Applied retention labels to 100% of calls for protected tools while increasing the loss weight on correction tokens (v5 served as a retrained RL candidate of v4).
  • Result: bash correction recovered to 0.796 (v4) and 0.805 (v5), but list_files retention collapsed to 0.261 and 0.239.
0.550.600.650.700.750.800.850.00.20.40.60.81.0Base retention 0.784v2: retention 0.701 (bash value unrecorded)Acceptance 0.85base (0.099, 0.784)prod (0.220, 0.663)v1 (0.885, 0.594)v3 (0.731, 0.742)v4 (0.796, 0.732)v5 (0.805, 0.737)bash correction rate (share of bash positions whose top choice is run_command)Retentionv0 only recorded a bash correction rate of 0.254 (no retention), so it is not drawn.

Fig. 04Protocol A: correcting bash vs. keeping other tools

Under Protocol A, iterations v1–v5 moved back and forth along a fixed trade-off curve.

No hyperparameter combination simultaneously met the bash correction threshold (≥ 0.85) and the specialized tool retention bars (glob_files and list_files never recovered, even when 100% of their training occurrences were protected).

0.00.20.40.60.8grep (threshold ≥ 0.63)glob_files (threshold ≥ 0.53)list_files (threshold ≥ 0.41)0.680.550.680.660.670.580.360.460.450.450.460.260.390.260.24basev2v3v4v5

Fig. 05Protocol A: retention of three specialized tools

5.3Phase 3: Redefining the Problem Formulation (v6, v7)

Why did four iterations of hyperparameter tuning just slide along the same trade-off line? Auditing the raw training examples revealed three fundamental flaws in our data formulation:

  • Contradictory Context-Label Pairs: A single trajectory often contained multiple sequential bash errors. v1–v5 applied correction labels to every occurrence. However, from the second error onward, the conversation history contained Remy’s explicit rejection message: “Error: tool bash is not declared.” The prompt context stated the model called bash and failed, while our SFT target forced the model to pretend it had called run_command all along.
  • Task Leakage in Session Holdouts: Splitting holdouts by session meant 12 of the 33 tasks (34% of evaluation rows) appeared in both train and test sets across different sessions.
  • Conflicting Semantic Signals (Post-hoc Analysis): Mapping every bash call to run_command—including bash ls and bash grep—taught the model to use run_command for directory listing, while retention labels simultaneously taught it to use list_files for the exact same intent.
A trajectory (simplified)task + prefixbash lsrejectedbash greprejectedbash catrejected …v1–v5: Every bash gets a correction label→ run_command→ run_commandContext: call just failed→ run_commandContext: call just failedv6: Stop at the first format error; rewrite the whole call by intentKept: prefix + first callbash ls → list_filesNothing after this point is usedv6’s rationale is written in the header of the 10-26 data script. Note: rewriting to list_fileswas barely learned by v6 (key-position accuracy 0.067); the model wrote a valid run_command instead.

Fig. 06Two ways to label the same trajectory

Comparison of trajectory labeling between v1–v5 (labeling all errors across polluted contexts) and v6 (truncating at the first error for a clean prefix).

v6 (Clean Prefix Truncation + Full-Span Semantic Rewriting):

  • Method:
    • Clean Prefix: Truncated every trajectory immediately after the first formatting error, ensuring zero prior rejection messages in the context.
    • Full-Span Labeling: Supervised the entire span from the first erroneous token through </function>, re-tokenized to match the model’s native serialization (97.8% round-trip fidelity).
    • Semantic Remapping: Rewrote bash commands by intent (ls/tree → list_files, find -name → glob_files, grep/rg → grep, cat/head/sed → read_file, and all others → run_command), while also repairing extraneous/missing arguments and edit_file formatting.
    • Task-Level Split: 348 training rows (28 tasks) and 74 holdout rows (5 tasks), disjoint from eval32. Dropped KL anchoring. We also trained three ablations: double correction weight (v6fw2), blind bash → run_command mapping (v6-noremap), and dropping extraneous-argument repairs (v6-noextra).
  • Metric (Protocol B: 74-Row Task Holdout):
    basev6v6fw2v6-noremapv6-noextra
    Critical-Token Accuracy0.0540.7300.7160.7300.527
    Exact Full-Span Match1/7423/7420/7418/7412/74
    bash → run_command (36 rows)0.0280.9170.9170.9440.889
    grep Extraneous Args (16 rows)0.0620.8750.8750.8750.125
    bash → list_files (15 rows)00.067000
  • End-to-End Execution (eval32 Greedy, Protocol C) & Takeaways:

In live greedy runs, undeclared bash calls dropped from 176 to 0 and extraneous arguments fell from 106 to ~5. However, both base and v6 solved exactly 7 tasks—because edit_file failures nearly doubled from 190 to 383.

01002003004001760Undeclared bash106≈5Extra params190383edit_file failuresbasev6edit_file calls rose from 312 to 550; edit calls missing a top-level relative_path rose from 9.9% to 17.1%.

Fig. 07After v6 fixed tool names, failures moved to edit

Eliminating bash errors unblocked trajectories early on, allowing the agent to reach deeper states where it instead failed on edit_file JSON structures. Additionally, v6-noextra (0.125 on grep args) proved that argument-hygiene requires dedicated supervision, while bash → list_files (0.067) showed the model defaulted to legal run_command calls rather than learning semantic tool remapping.

v7 (Round-2 Iterative Correction on Structural edit_file Errors):

  • Hypothesis: Because v6 truncated trajectories at the first error (almost always bash), its 348 training rows contained only 5 edit_file repairs. Now that v6 fixed tool names, we needed a second round of on-policy rollouts to capture and repair the newly exposed edit_file failures.
  • Method: Rolled out v6 twice across 64 new tasks, extracted first-error corrective labels, and merged them with v6 data (375 train rows; 79 holdout rows across 9 tasks). Added deterministic repairs for misplaced relative_path keys and unwrapped old_lines/new_lines objects, plus structural retention labels on JSON keys (v7), comparing against a tool-name-only retention baseline (v7nostruct).
Key-position accuracy0.00.20.40.60.80.089base0.684v60.671v70.722v7nostructRows fully correct01020303/79base24/79v620/79v724/79v7nostructv6’s own 74-row holdout uses different tasks and is not shown here.

Fig. 08Protocol B: correction on the 79-row task holdout

On the 79-row task holdout, v7 scored slightly lower on overall critical-token accuracy than v7nostruct, achieving 0.914 on bash → run_command (35 rows), 0.000 on bash → list_files (15 rows), and 1.000 on edit_file structure repairs (4 rows).
  • Metric (Protocol C: eval32 Greedy, Per-Session Avg):
    basev6v7nostructv7
    Tasks Solved (out of 31)7778
    Undeclared Tool Calls / Session6.130.130.060.19
    Total Failed Tool Calls / Session16.014.110.09.1
    Longest Consecutive Failure Streak3.843.842.482.13
  • Takeaway: In live execution, v7 achieved the lowest failure rate and shortest failure streaks per session. However, because solved tasks overlapped by only 2–4 problems across models, single-run greedy evaluation was too noisy to measure true capability—prompting our final sampled evaluation.

6.The Interface Is Fixed—What About Task Resolution?

To measure true problem-solving capability without greedy decoding variance, we evaluated base and v7 across 4 sampled rollouts per task at temperature = 1.0 (Protocol C′, 128 total rollouts).

basev7
Valid / Missing Rollouts128 / 0126 / 2
pass@121.9%23.2%
pass@456.3% (18/32 tasks)59.4% (19/32 tasks)
0%10%20%30%40%50%60%70%21.923.2pass@137.539.6pass@248.451.6pass@356.259.4pass@4basev732 tasks (one task ≈ 3.1 points); v7 has 2 missing positions, not scored as 0; 29 base runs are reruns.No error bars: no validated confidence intervals were computed.

Fig. 09Protocol C′: pass@k on eval32 with 4 samples per task

Task resolution (pass@k) remained within the 1-task noise margin (9 tasks favored v7, 7 favored base, 16 tied).
0%5%10%15%20%base9.0%4.0%6.9%Total 20.0%v75.6%7.8%Total 13.5%Undeclared toolArg structureExecutionShare of all tool calls. v7’s undeclared share is 0.13%; the segment is too narrow to label.

Fig. 10Protocol C′: what the failed tool calls are

Tool-level hygiene transformed completely: all 727 bash calls vanished, shifting cleanly into run_command (rising from 2,262 to 3,722 calls) and edit_file (rising from 1,529 to 2,012 calls).

Crucially, how sessions terminated shifted underneath the surface:

base (128 runs)2046854v7 (126 runs)252572Completed · passCompleted · failTruncated · passTruncated · failCompleted = the model stopped; truncated = cut off by the budget. Reward uses the final repo state.Pass rate when completed: base 20/66, v7 25/50. Truncated: 54 of 62 failed for base, 72 of 76 for v7.

Fig. 11Protocol C′: how sessions end and whether they pass

Session termination dynamics.
  • Higher precision when self-terminating: v7 chose to finish early within budget less often than base (50/126 vs. 66/128 sessions), but when it did self-terminate, its success rate jumped from 30.3% (20/66) to 50.0% (25/50).
  • More budget exhaustion: Because v7 stopped wasting turns on rejected bash calls and engaged in deeper editing loops, more trajectories ran into the hard turn limit (76 vs. 62 sessions), failing 72 of those 76 cap-outs.

7.Key Takeaways for Agent Engineering

  1. Adapt models using their own on-policy mistakes, not expert demonstrations: Off-policy SFT (v0, prod) failed to stop bash invocations even when scaled 10x because expert trajectories never visit the model’s error states. On-policy single-token correction (v1) jumped correction accuracy to 0.885 in one step.
  2. Single-token supervision overshoots along tokenizer boundaries: Boosting = to turn bash into run_command directly cannibalized merged tokens like =read and =grep. Always audit how your tokenizer splits tool schemas before designing loss masks.
  3. Hyperparameter tuning cannot fix contradictory training contexts: Four iterations of tuning retention ratios, KL penalties, and loss weights (v1–v5) merely slid along a fixed trade-off curve because labels later in the trajectory contradicted prior error messages in the context window.
  4. Truncating to a clean prefix beats tuning loss weights: Truncating trajectories at the first formatting error and supervising the full tool call span (v6) lifted critical-token accuracy from 0.054 to 0.730 without collapsing retention. (Note: Because we introduced clean prefixes and full-span labels simultaneously without isolating them in ablations, we treat them as a combined recipe.)
  5. Fixing surface syntax exposes deeper downstream bottlenecks: Eliminating undeclared tool calls immediately shifted the failure distribution toward edit_file JSON structure errors—requiring a second round of on-policy iterative collection (v7).
  6. Interface compliance is a prerequisite for RL, not a substitute for it: Corrective SFT eliminated 98% of undeclared tool calls and cut overall tool failures by a third, clearing the formatting noise that previously blocked efficient RL rollouts. However, turning clean tool calls into higher pass@1 requires actual task-level reinforcement learning.

More research

All research
Harness Adaptation via Corrective SFT | Corepass Research - Corepass