# LEGO-RL: Harness-Native Reinforcement Learning for Coding Agents

> LEGO-RL enables native coding-agent harnesses to train with policy-gradient RL, boosting SWE-bench Verified scores by up to 9.4 points without altering their control flow.

- **Source:** [arXiv](https://arxiv.org/abs/2608.17393)
- **Published:** 2026-08-22
- **Permalink:** https://picx.dev/p/jBNH9m
- **Whiteboard:** https://picx.dev/p/jBNH9m/image

## Summary

# LEGO-RL: Harness-Native Reinforcement Learning for Coding Agents

## Summary (Overview)

- **LEGO-RL** is a framework that bridges native coding-agent harnesses (OpenHands SDK, Claude Code, OpenCode) with scalable policy-gradient optimization **without modifying their internal control flow**, preserving original agent workflows while enabling RL training.

- The framework is built on **three pillars**: (1) **faithful optimization** via in-process LLM proxying that captures raw generation streams for token-level alignment and robust trainer-side log-probability recomputation (including expert-routing replay for MoE models); (2) **reliable execution** via scalable sandbox orchestration with image caching and stage-wise defenses against reward hacking; (3) **observable training** through an integrated plugin with automated validation, monitoring, and a Live UI for granular trajectory diagnostics.

- Training the sparse MoE model **Qwen3.5-35B-A3B** with GSPO yields significant gains on SWE-bench Verified across all three harnesses: **OpenHands SDK 64.0% → 70.4%**, **Claude Code 62.4% → 68.2%**, **OpenCode 57.2% → 66.6%**, while maintaining **rollout-training probability correlation above 0.99**.

- The framework addresses critical challenges in agentic RL: harness-side history rewriting that corrupts trajectory reconstruction, reward hacking, sandbox failures, and the heavy right-tail distribution of agentic rollouts that reduces inference utilization under synchronized generation.

- LEGO-RL is open-sourced with complete framework, trained models, and datasets available at https://github.com/LegoX/Lego-RL and https://huggingface.co/LegoX/Lego-RL.

## Introduction and Theoretical Foundation

### Background and Motivation

Training coding agents with reinforcement learning requires optimizing long-horizon behavior over software repositories, tools, and execution environments. Unlike learning from isolated responses, RL updates the policy from **complete trajectories and their verifier rewards**. A single rollout may involve repeated model calls, repository inspection, tool calling, code modification, dependency installation, and test execution before producing a sparse executable reward.

The core challenge: these trajectories are generated by **native agent harnesses** that manage prompts, tools, context, and execution state. The optimization target is the policy behavior induced by the original agent control flow, but integrating these harnesses into policy-gradient training is difficult because:

- **Harness-side prompt construction, context compaction, and history rewriting** can cause the reconstructed trajectory to differ from the exact token sequence sampled during rollout, preventing faithful trainer-side probability recomputation.
- **Sparse mixture-of-experts models** introduce an additional mismatch when rollout-time expert routing is not reproduced during training.
- **Sandbox failures, dependency errors, verifier misconfiguration, timeouts, and reward hacking** can discard costly trajectories or corrupt reward signals, yet are difficult to localize in asynchronous pipelines.

### Problem Setup and Objective

A task instance $x = (q_x, R_x, V_x)$ pairs a problem statement $q_x$ and an initialized repository environment $R_x$ with a task-specific executable verifier $V_x$. The native coding-agent harness $\mathcal{H}$ is treated as part of the environment, and only the policy $\pi_\theta$ it calls is optimized. At turn $t = 1, \ldots, T$, the harness maps the current interaction and repository state $s_t$ to a context $c_t = \mathcal{H}(s_t)$, the policy generates an assistant token span $a_t \sim \pi_\theta(\cdot \mid c_t)$, and the harness executes the requested tool actions.

The trajectory log-likelihood is:

$$\log \pi_\theta(\tau) = \sum_{(t,j) \in \mathcal{M}(\tau)} \log \pi_\theta(a_{t,j} \mid c_t, a_{t,<j})$$

where $\mathcal{M}(\tau)$ denotes the set of token positions corresponding to policy-generated response tokens.

The expected verifier reward $J(\theta) = \mathbb{E}_{x\sim \mathcal{D},\tau \sim \mathcal{H}(\pi_{\theta})}\big[r(x,\tau)\big]$ is maximized with group-relative advantage estimation using the **GSPO** sequence-level surrogate:

$$
\mathcal{J}_{\mathrm{GSPO}}(\theta) = \mathbb{E} \left[ \frac{1}{G} \sum_{i=1}^{G} w(\tau_{i}) \min \Bigl(\sigma_{i}(\theta) \hat{A}_{i}, \operatorname{clip} \bigl(\sigma_{i}(\theta), 1 - \epsilon_{\mathrm{low}}, 1 + \epsilon_{\mathrm{high}} \bigr) \hat{A}_{i} \Bigr) \right]
$$

$$\sigma_{i}(\theta) = \left(\frac{\pi_{\theta}(\tau_{i})}{\pi_{\theta_{k'}}(\tau_{i})}\right)^{1 / |\mathcal{M}(\tau_{i})|}$$

where $\theta_{k'}$ is the policy version that generated the group, $w(\tau_{i}) \in \{0, 1\}$ filters invalid trajectories caused by infrastructure or execution failures, and $\hat{A}_i = (r_i - \bar{r}) / (\mathrm{std}(r_{1:G}) + \delta)$ with $\delta = 10^{-6}$.

### Faithfulness Requirement

The trajectory log-likelihood is well defined only if the trainer sees the **exact contexts, tokens, and mask** of the rollout. Let $\ell_{i,(t,j)}^{\mathrm{roll}}$ be the log-probability recorded at generation time and $\ell_{i,(t,j)}^{\mathrm{train}}(\theta)$ the value the trainer recomputes. Faithful optimization requires:

$$\ell_{i,(t,j)}^{\mathrm{train}}(\theta_{k'}) \approx \ell_{i,(t,j)}^{\mathrm{roll}}$$

for every $(t,j) \in \mathcal{M}(\tau_i)$. This holds only if token IDs, response masks, and policy weights match, and for sparse mixture-of-experts policies, only if training reuses the expert-routing decisions of the behavior policy.

## Methodology

### Training Infrastructure Architecture

LEGO-RL consists of a harness-native training infrastructure within a broader closed-loop operational workflow:

1. **Sandbox Execution Environment**: Every trial runs in a fresh, isolated sandbox (Docker, Kubernetes, or cloud container) with:
   - **Nydus lazy-pull snapshotter** for on-demand image chunk streaming, avoiding full image replication
   - Read-only mounting of agent runtime and grading toolchain (rather than reinstalling)
   - Stage-specific timeouts and asynchronous scheduling to handle heavy tail latency
   - **Reward-integrity defenses**: network restrictions via privileged sidecar, hidden repository history during execution, test dependencies packaged into task images

2. **In-Process Proxy**: Connects unmodified harnesses to the optimizer at the provider API boundary:
   - Captures token IDs, log-probabilities, response masks, and generation metadata directly from serving sessions
   - Aligns successive contexts at message granularity (tool calls matched by stable identifiers, not serialized arguments)
   - Records rollout-time routing decisions for MoE models and replays them during training via **R3** (rollout routing replay)
   - Isolates sub-agent calls from parent capture sessions

3. **Rollout and Training**: Fully asynchronous rollout generation with:
   - Termination-aware trajectory handling: execution failures masked from training, valid incomplete trajectories retained
   - Bounded policy staleness (maximum staleness of 1 in experiments)
   - Built on **verl** with support for PPO, GRPO, GSPO, vLLM serving, and multiple training backends (VeOmni, FSDP, Megatron)

### Closed-Loop Operational Workflow

The experiment lifecycle is organized into five stages:

1. **Data Preparation**: Converts task descriptions and repository snapshots into executable task instances with difficulty screening
2. **Run Validation**: Validates experiment configurations, cross-parameter constraints, and resource availability
3. **Training Run**: The sandbox-to-optimizer training loop
4. **Live UI**: Presents optimization metrics, rollout statistics, termination causes, and trajectory-level evidence
5. **Human Review**: Researchers diagnose failures, analyze learned behaviors, and guide subsequent experiments

The **agent plugin** provides reusable skills automating stages 2–4, while the **Live UI** offers three complementary views: termination-reason distributions, per-instance task grids, and consistency/in-batch distribution views.

## Empirical Validation / Results

### Main Results Across Three Harnesses

Training Qwen3.5-35B-A3B with GSPO across three native coding-agent harnesses yields:

| Coding Agent | Model | SWE-bench Verified (%) |
|---|---|---|
| **OpenHands SDK** | Qwen3.5-35B-A3B (base) | 64.0 |
| | Qwen3.6-35B-A3B | 67.4 |
| | KAT-Coder-V2.5-Dev | 67.0 |
| | **LEGO-RL-Qwen3.5-35B-A3B** | **70.4 (+6.4)** |
| **Claude Code** | Qwen3.5-35B-A3B (base) | 62.4 |
| | Qwen3.6-35B-A3B | 63.4 |
| | KAT-Coder-V2.5-Dev | 66.8 |
| | **LEGO-RL-Qwen3.5-35B-A3B** | **68.2 (+5.8)** |
| **OpenCode** | Qwen3.5-35B-A3B (base) | 57.2 |
| | Qwen3.6-35B-A3B | 60.6 |
| | KAT-Coder-V2.5-Dev | 64.8 |
| | **LEGO-RL-Qwen3.5-35B-A3B** | **66.6 (+9.4)** |

LEGO-RL-trained models outperform both the newer base generation (Qwen3.6-35B-A3B) and KAT-Coder-V2.5-Dev across all three harnesses. Notably, KAT-Coder's gains are harness-specific (3.4 points under Claude Code but -0.4 under OpenHands SDK), confirming that gains obtained under one agent control flow need not survive another.

### Task Reliability and Reward Integrity

- **Task validity**: From 36,884 OpenSWE-derived candidates, static filtering reduced the pool to 22,806 tasks; build/verifier validation further removed tasks to 21,681; rollout-based difficulty screening (retaining tasks solved 1–3 times in four trials) produced the final **2,699-task training index**.

- **Trajectory validity**: Termination-aware admission excluded 7.1% of Claude Code, 2.4% of OpenHands SDK, and 6.4% of OpenCode trajectories from optimization. Termination profiles differ across scaffolds (wall-clock timeouts dominate under Claude Code; environment-setup failures under OpenCode).

- **Reward informativeness**: With eight rollouts per task, groups solved either 0 or 8 times provide no within-group reward variation. Under OpenHands SDK, the proportion of zero-variation groups increased from 44.7% to 51.4% as the policy improved, showing that task difficulty is **policy-relative**.

- **Difficulty screening**: The full difficulty band and its upper half both improved (post-warmup validation averages of 0.671 and 0.670), whereas the lower half reached 0.640 and the unscreened pool showed no improvement.

### Rollout–Training Alignment

| Coding Agent | Pearson r | KL (×10⁻³) | \|Δlog p̄\| per trajectory (×10⁻³) |
|---|---|---|---|
| | | | p50 | p90 | p99 |
| OpenHands SDK | 0.9993 | 0.75 | 0.7 | 1.2 | 2.1 |
| Claude Code | 0.9980 | 1.35 | 0.7 | 1.3 | 2.7 |
| OpenCode | 0.9993 | 0.60 | 0.6 | 1.1 | 2.0 |

- **Routing consistency**: Replaying rollout-time routing decisions increased rollout-training correlation from 0.9946 to 0.9993 and reduced mean token log-probability discrepancy from 0.0062 to 0.0025. Expert overlap reached 0.996 with 0.985 top-1 agreement at the first training step.

- **History consistency**: In Claude Code production trajectories, matching tool calls by identifier rather than serialized arguments resolved 207 of 222 (93%) apparent mismatches. Sub-agent isolation reduced session mixing from 6.3% to 0%.

### System Efficiency

**Stage-wise wall-clock statistics** across 3,699 OpenHands SDK training trials:

| Stage | Mean (s) | p50 | p90 | p99 | Mean-time fraction |
|---|---|---|---|---|---|
| Sandbox setup | 21.6 | 7.7 | 41.8 | 275.2 | 2.3% |
| Agent setup | 4.2 | 4.0 | 4.8 | 8.4 | 0.5% |
| Agent execution | 840.5 | 708.4 | 1604.3 | 2801.1 | 91.3% |
| Verification | 35.9 | 4.1 | 29.6 | 928.5 | 3.9% |
| Other | 20.3 | 8.1 | 12.3 | 965.5 | 2.2% |
| **Trial total** | **920.4** | **770.0** | **1742.7** | **3189.1** | **100%** |

- **Asynchronous scheduling**: Over the same 7.5 hours, synchronous training completed 3 steps vs. 7 for asynchronous (2.5× reduction in step time; 1.9× after correcting for compute-rate differences).

- **Sandbox optimizations**: Prebuilt task images achieve 33.2× median speedup over inline Dockerfile execution; mounted agent runtime yields 15.4× speedup; lazy image pull improves median cold-start latency by 1.7× and maximum by 23×, reducing cumulative network traffic from 21.6 GB to 1.59 GB.

### Behavioral Analysis

- **Self-checking**: In the OpenHands SDK run, the proportion of trajectories that reread a file after modifying it rose from 73.6% to 98.1%; distinct files examined before first edit increased from 3.5 to 6.9.

- **Interaction horizon**: Mean response length increased from 43.5k to 90.9k tokens, driven primarily by more interaction steps (46.6 → 83.1 turns, +78%) rather than longer individual turns (+17%).

## Theoretical and Practical Implications

### Theoretical Contributions

1. **Faithfulness as a first-class requirement**: The paper formalizes that trainer-side probability recomputation must agree with rollout-time generation up to numerical tolerance, establishing a clear criterion for what constitutes faithful optimization in agentic RL.

2. **Harness-native vs. framework-defined rollouts**: By treating the harness as part of the environment and observing at the model API boundary, LEGO-RL preserves the original agent control flow, avoiding the distribution shift introduced by adapting agents to framework-defined interfaces.

3. **Policy-relative task difficulty**: The finding that zero-variation groups increase as the policy improves (44.7% → 51.4% under OpenHands SDK) demonstrates that task pools must be dynamically managed relative to policy capability, not statically curated.

4. **MoE routing replay**: The paper demonstrates that for sparse mixture-of-experts models, reproducing the token sequence is insufficient—rollout-time expert routing decisions must be replayed during training to maintain alignment (correlation 0.9946 → 0.9993).

### Practical Implications

1. **Cross-harness generalization**: The framework supports multiple harnesses with only a lightweight adapter, making it practical to train coding agents across different scaffolds without per-harness RL infrastructure.

2. **Reward integrity defenses**: The observed failure modes (agent-side shortcuts exposing grading information, environment-side failures making rewards behavior-independent) and their defenses provide a practical playbook for trustworthy executable verification.

3. **Operational workflow**: The closed-loop five-stage workflow (data prep → validation → training → live UI → human review) with agent-plugin automation demonstrates how to operationalize agentic RL at scale.

4. **Efficiency insights**: The finding that agent execution dominates (91.3% of wall-clock time) while sandbox setup and verification are minor (2.3% and 3.9%) motivates stage-specific timeouts and asynchronous scheduling over trial-wide limits.

## Conclusion

LEGO-RL connects native coding-agent harnesses to scalable policy-gradient optimization while preserving their original control flows. By integrating sandboxed execution and verification, token-faithful rollout capture, asynchronous training, reward-integrity safeguards, and trajectory-level observability, the framework enables reliable and faithful training across OpenHands SDK, Claude Code, and OpenCode. The results highlight that scaling coding-agent RL requires not only scalable optimization, but also **reliable execution environments, faithful trajectory capture, and feedback mechanisms that evolve with increasingly capable agents**.

### Limitations and Future Work

**Limitations**: All experiments use Qwen3.5-35B-A3B with each harness trained separately; production-scale training limits each configuration to a single run (run-to-run variance unquantified); binary executable rewards cannot assign intermediate credit to behaviors like error recovery; sandbox speedups depend on deployment environment.

**Future work**: Extending to mixed training (multiple task types, multiple harnesses in one policy), adding adapters for further harnesses, richer credit assignment beyond terminal binary rewards, and automated diagnosis in the Live UI. The framework is developed in the open with continued releases of framework updates, harness adapters, trained checkpoints, and task indices.

---

_Markdown view of https://picx.dev/p/jBNH9m, served by PicX — AI-generated visual whiteboard summaries of research papers._
