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:
Fig. 01One bash call voids the whole batch
Across a 382-session baseline RL run, interface mismatches severely degraded throughput:
- Cascading batch failures: 282 sessions invoked
basha total of 2,301 times—each time invalidating validgrepandread_filecalls grouped in the same turn. - Zero in-context recovery: After receiving explicit harness rejection errors, the model still invoked
bashan additional 704 times. - Schema & JSON errors: The model generated 1,467 calls with extraneous parameters (e.g., passing
-nflags or undefineddescriptionfields togrep) and failed JSON parsing on 36% (752 / 2,113) of itsedit_filecalls.
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
Fig. 02The decision token: where the tool name is decided
<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.
bashCorrection Rate: Fraction of originalbashpositions whererun_commandbecomes the top-1 token (Target: ≥ 0.85).- Retention Rate: Fraction of valid non-
bashtool calls where the original tool remains top-1 (Base: 0.784). Target: retain ≥ 92% of base performance ongrep(≥ 0.63),glob_files(≥ 0.53), andlist_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.
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:
bashcorrection 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 likecreate_patchandedit_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:
bashcorrection stalled at 0.220 (47.1% ofbashpositions still preferredbash), 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
=bdecision 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:
bashcorrection jumped to 0.885 (withbashtop-1 dropping to 0). However, retention crashed from 0.784 to 0.594; at valid tool positions, the probability of choosingrun_commandsurged 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, prioritizedread_fileandgrep, and trained fresh from base. - Result: Overall retention recovered to 0.701, but specialized tools degraded heavily:
grep(0.552),glob_files(0.359), andlist_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, 310glob_files, 146list_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-verifiededit_filesamples. - Result: Overall retention reached 0.742 and
greppassed the target bar (0.683), butbashcorrection fell to 0.731. On a 22-rowedit_fileholdout, 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
bashcorrection. 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:
bashcorrection recovered to 0.796 (v4) and 0.805 (v5), butlist_filesretention collapsed to 0.261 and 0.239.
Fig. 04Protocol A: correcting bash vs. keeping other tools
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).
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
basherrors. 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 calledbashand failed, while our SFT target forced the model to pretend it had calledrun_commandall 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
bashcall torun_command—includingbash lsandbash grep—taught the model to userun_commandfor directory listing, while retention labels simultaneously taught it to uselist_filesfor the exact same intent.
Fig. 06Two ways to label the same trajectory
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
bashcommands 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 andedit_fileformatting. - 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_commandmapping (v6-noremap), and dropping extraneous-argument repairs (v6-noextra).
- Metric (Protocol B: 74-Row Task Holdout):
base v6 v6fw2 v6-noremap v6-noextra Critical-Token Accuracy 0.054 0.730 0.716 0.730 0.527 Exact Full-Span Match 1/74 23/74 20/74 18/74 12/74 bash → run_command (36 rows) 0.028 0.917 0.917 0.944 0.889 grep Extraneous Args (16 rows) 0.062 0.875 0.875 0.875 0.125 bash → list_files (15 rows) 0 0.067 0 0 0 - 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.
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 5edit_filerepairs. Now that v6 fixed tool names, we needed a second round of on-policy rollouts to capture and repair the newly exposededit_filefailures. - 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_pathkeys and unwrappedold_lines/new_linesobjects, plus structural retention labels on JSON keys (v7), comparing against a tool-name-only retention baseline (v7nostruct).
Fig. 08Protocol B: correction on the 79-row task holdout
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):
base v6 v7nostruct v7 Tasks Solved (out of 31) 7 7 7 8 Undeclared Tool Calls / Session 6.13 0.13 0.06 0.19 Total Failed Tool Calls / Session 16.0 14.1 10.0 9.1 Longest Consecutive Failure Streak 3.84 3.84 2.48 2.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).
| base | v7 | |
|---|---|---|
| Valid / Missing Rollouts | 128 / 0 | 126 / 2 |
| pass@1 | 21.9% | 23.2% |
| pass@4 | 56.3% (18/32 tasks) | 59.4% (19/32 tasks) |
Fig. 09Protocol C′: pass@k on eval32 with 4 samples per task
Fig. 10Protocol C′: what the failed tool calls are
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:
Fig. 11Protocol C′: how sessions end and whether they pass
- 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
bashcalls 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
- Adapt models using their own on-policy mistakes, not expert demonstrations: Off-policy SFT (v0, prod) failed to stop
bashinvocations 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. - Single-token supervision overshoots along tokenizer boundaries: Boosting
=to turnbashintorun_commanddirectly cannibalized merged tokens like=readand=grep. Always audit how your tokenizer splits tool schemas before designing loss masks. - 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.
- 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.)
- Fixing surface syntax exposes deeper downstream bottlenecks: Eliminating undeclared tool calls immediately shifted the failure distribution toward
edit_fileJSON structure errors—requiring a second round of on-policy iterative collection (v7). - 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.