Authors’ overview
Coding agents solve repository-level software engineering tasks through long trajectories of code inspection, search, editing, and testing. As a task progresses, earlier exploration becomes stale, so managing context is more than avoiding overflow: an agent must decide when to compact, what working state to preserve, and how to continue from it. We introduce AutoCompact, which trains a coding agent to make these decisions as part of its policy. To collect training data, we run the base agent on coding tasks and use a judge to review its compaction decisions, summaries, and actions after compaction. Flawed outputs are replaced with corrected ones before being executed in the environment, so each trajectory continues from the corrected decisions. We use these trajectories for supervised fine-tuning, then jointly optimize coding and compaction through reinforcement learning with task-success rewards. Experiments on SWE-bench Verified and SWE-PolyBench Verified show that AutoCompact improves pass rates over the base model by an absolute 9.2% and 5.0%, respectively. The improvements hold across all evaluated inference budgets, with a 256K context window that never overflows and with a 16K window whose overflow triggers fallback compaction.
Introduction
Large language model (LLM) agents have demonstrated strong capabilities on repository-level software engineering tasks by inspecting code, searching the repository, editing files, and running tests. Resolving complex issues often requires investigating multiple candidate causes and iterating between implementation and validation, so trajectories accumulate code snippets, tool outputs, and intermediate findings. As the agent moves from one stage of a task to the next, much of this information, such as exploratory hypotheses, failed attempts, and detailed tool outputs, becomes stale. Keeping the full trajectory thus fills the context with outdated details, whereas the next stage needs only a compact working state: the conclusions reached so far, the relevant code and workspace status, and the remaining actions. Effective context management therefore requires an agent to decide when to compact, what information to preserve in the working state, and how to continue execution from it.
Existing approaches address only part of this problem. Length-triggered methods such as CompactionRL compact only when the remaining context budget falls below a fixed threshold, which ties compaction to context length rather than task progress: stale exploration accumulates until the threshold is reached, and compaction may then occur in the middle of an unresolved stage whose evidence is still needed. Proactive methods instead let the agent decide when to compact, either through an inference-time rubric or through fine-tuning on trajectories into which compression calls are inserted offline. However, deciding when to compact is not sufficient: the working state may omit or misrepresent key information, and even when it is correct, the agent may fail to follow it, revisiting completed exploration or ignoring the intended next action. Neither kind of proactive method addresses these failures: a rubric provides no training signal, and offline insertion keeps the original actions after each inserted call.
We introduce AutoCompact, which trains a coding agent to decide when to compact, what to preserve, and how to continue as part of its policy. To collect training data, we run the base agent on training tasks and use a judge to review its compaction decisions, the summaries it writes, and its actions after compaction. The judge replaces flawed outputs with corrected ones before they are executed in the environment, so each trajectory continues from the corrected decisions and shows how to act after compaction. We use these trajectories for supervised fine-tuning (SFT), and then apply outcome-based reinforcement learning (RL), which jointly optimizes coding and compaction with binary task success as the only reward signal.
Our main contributions are as follows. (1) We introduce AutoCompact, which corrects compaction decisions, summaries, and subsequent actions during data collection and executes the corrected outputs in place of the original ones. (2) We collect 1,052 judge-corrected trajectories on SWE-rebench to initialize the policy via SFT, followed by outcome-based RL that jointly optimizes coding and compaction without compaction-specific reward shaping. (3) We demonstrate improved task success on SWE-bench Verified and SWE-PolyBench Verified, with gains across inference budgets and context settings. To rule out that these gains stem from training alone, we ignore the compaction calls of the same trained model; the resulting drop in pass rates confirms that executing compaction itself contributes.
Method
AutoCompact equips a coding agent with a compact action (Section 2.1) and trains the policy in two stages. We first collect on-policy trajectories with judge-guided corrections to compaction timing, the generated working state, and the actions immediately following compaction (Section 2.2). These corrected trajectories provide the training data for SFT. We then apply outcome-based RL to jointly optimize coding and compaction using final task success as the reward (Section 2.3).
Proactive Context Compaction
We augment the agent with a compact action that can be invoked proactively during execution. The agent otherwise operates normally by inspecting files, editing code, and running tests. When it determines that the current stage has been sufficiently resolved and the accumulated history can be summarized, it may invoke compact before reaching the context limit. For example, the agent may compact after localizing the cause of an issue and before proceeding to implementation.
This mechanism makes compaction a model decision rather than solely a response to context-window pressure. Its effectiveness therefore depends on three behaviors: choosing an appropriate compaction point, constructing an accurate working state, and continuing reliably from that state. We next describe how we supervise these behaviors through judge-guided on-policy data collection.
Judge-Guided Data Collection and SFT
Prompting alone does not induce proactive compaction. In our preliminary experiments, the base model rarely invoked compact before the context limit, even when compaction rules were specified in the agent prompt. Proactive compaction introduces a behavior that is uncommon in the base policy: the model must interrupt an otherwise valid execution trajectory and replace its accumulated context before any context-limit constraint forces it to do so. We therefore collect training trajectories with online judge corrections and use them for SFT. These corrections provide demonstrations of compaction and subsequent execution that the base policy rarely produces on its own. The judge is used only during data collection; the trained agent runs without the judge at inference time.
We supervise three types of decisions corresponding to the main failure modes of compaction. Trigger correction checks whether the current point is appropriate for compaction: the agent should compact when the current stage has been sufficiently resolved, but continue exploring when intermediate evidence is still needed. Working-state correction checks whether the generated # Auto Context Summary accurately preserves the information needed for subsequent execution, including relevant conclusions, code and workspace state, and remaining actions. Continuation correction checks whether the first actions after compaction follow the resulting working state, rather than revisiting completed exploration or ignoring the intended next step, such as re-running a search whose result is already recorded in the working-state summary.
Corrections are applied before execution, so each one shapes the rest of the trajectory. When the judge identifies an output unsatisfactory, it writes a corrected output, which the environment executes in place of the original; the policy then generates the following actions from this corrected history. This differs from post-hoc annotation, where corrections do not influence later states.
Finally, we fine-tune the base policy on the corrected trajectories with the standard next-token prediction objective. The resulting policy, AutoCompact-SFT, learns both ordinary coding behavior and the three compaction behaviors introduced above: selecting appropriate compaction points, constructing actionable working states, and reliably continuing execution afterward. SFT provides a behavioral initialization for proactive compaction, but it optimizes the locally corrected decisions rather than their eventual effect on task completion. We then further optimize the policy using outcome-based RL, which directly targets task success.
Joint RL for Task Solving and Compaction
Starting from the SFT checkpoint, we further train the agent on SWE-Gym with end-to-end multi-turn RL, using group relative policy optimization (GRPO) and a fully asynchronous RL system. Each rollout receives a binary outcome reward based on whether the final patch passes the task tests. Within each rollout group, GRPO converts these outcomes into relative advantages, which provide a shared learning signal for all model-generated tokens in a trajectory, including regular coding actions, the decision to invoke compact, the generated context summary, and the continuation after compaction.
Compaction therefore requires neither a separate auxiliary objective nor compaction-specific reward shaping. Instead, task solving and context management are trained jointly under the final task reward, allowing the policy to learn when compaction is beneficial, what information should be preserved, and how execution should continue afterward.
Compaction also changes how trajectories are converted into training sequences, because each call to compact rewrites the context. As a result, a trajectory with compaction no longer forms a single sequence in which each model turn extends the previous context. We therefore split each trajectory into segments wherever the context prefix is rewritten, such that within each segment every model turn is conditioned on a prefix that only grows. All segments of a trajectory share its advantage, so the decision to compact, the summary, and the actions after compaction receive the same outcome-based signal even though they fall into different segments. The policy loss is averaged at the token level over all segments in a batch, without a KL penalty or an entropy bonus, so the binary outcome reward is the only training signal for both coding and compaction.
Experiments
Our experiments address three questions. First, does AutoCompact improve task success over full-history execution and over existing length-triggered and proactive compaction methods (Section 3.2)? Second, how do proactive compaction, outcome-based RL, and the execution of compaction itself contribute across inference budgets and context settings (Section 3.3)? Third, how do the summaries produced after SFT and after RL differ (Section 3.4)?
Experimental Setup
Baselines. We compare AutoCompact against several context-management strategies. Base uses the same underlying model and scaffold without learned proactive compaction. Fixed Compaction triggers compaction when the remaining context budget falls below a predefined threshold. SelfCompact uses an inference-time rubric to guide compaction decisions, while CompactionRL jointly trains task execution and summary generation under a length-triggered compaction mechanism. SWE-Compressor learns to invoke a context-management tool through supervised fine-tuning on trajectories reconstructed offline by inserting compression calls. For this SFT comparison, we collect trajectories from comparable SWE-rebench task sets and use similar numbers of training trajectories for SWE-Compressor and AutoCompact-SFT. Unlike these baselines, AutoCompact corrects the agent’s compaction decisions and subsequent actions during data collection, directly supervising how the agent uses the compacted state.
Main Results
Length-triggered compaction yields limited gains. Fixed Compaction underperforms Base by 1.6% and 0.9% on the two benchmarks, indicating a performance cost in this constrained-context setting. CompactionRL improves upon Fixed Compaction by 3.9% and 1.2% through RL. However, its gains over Base remain limited, leaving a substantial gap to AutoCompact.
Proactive compaction outperforms full-history execution. Under the 256K setting, all evaluated proactive methods, including SelfCompact, SWE-Compressor, and the AutoCompact variants, outperform Base on both benchmarks. SelfCompact achieves improvements through inference-time guidance alone, while SWE-Compressor learns compaction-tool use through SFT. These results suggest that proactive context management helps even when the full history fits in context.
Online judge-guided SFT and outcome-based RL both add gains. AutoCompact-SFT exceeds SWE-Compressor by 1.2% and 1.6% on the two benchmarks. Since both use the same base model, scaffold, and comparable training data, this comparison suggests that online judge-guided correction is more effective than offline insertion into completed trajectories. AutoCompact-SFT learns from trajectories in which the corrected outputs, including corrected actions after compaction, were actually executed, whereas SWE-Compressor inserts compaction calls into completed trajectories and keeps their original subsequent actions. Outcome-based RL then improves pass rates by a further 7.4% and 2.8% over AutoCompact-SFT on the two benchmarks.
Case Study: Summary Self-Consistency under SFT and RL
This contrast highlights summary self-consistency as a dimension of summary quality beyond information coverage. The difference may stem from the training objectives: SFT imitates demonstrated summaries, which does not ensure that the recorded state constrains the next action, whereas RL rewards a summary only through the success of the actions that follow it.
Related Work
Coding agents. Research on repository-level coding improves task-solving capabilities through both harness design and model training. Work on harness design organizes repository exploration, code editing, and validation through agent-computer interfaces, tool execution environments, and structured repair workflows. Work on model training improves coding and problem-solving capabilities through executable task environments, expanded task and trajectory datasets, and supervised or reinforcement learning. AutoCompact combines the two as model-harness co-design: the harness exposes a compact action, and the model learns to use it jointly with task execution rather than through a separate compression module.
Memory and context management. Long-horizon agents manage growing interaction histories through memory hierarchies, abstraction of raw observations, summaries of accumulated observations and interactions, or compression of sub-trajectories and selected history spans. These works mainly design how retained context is represented. AutoCompact uses a simple representation, a single working-state summary alongside the original task and recent turns, and focuses on when to compact and how to continue afterward.
Learning context-management policies. Rubric- and guideline-based methods steer compaction through instructions rather than training the agent’s own compaction behavior. Supervised methods learn from constructed trajectories, for example by inserting context-management actions into completed trajectories, which keeps the original actions after each insertion, or by synthesizing them, as in concurrent work SWE-MeM, where a stronger model decides when to compress a span of steps and writes the summary but generates no task actions. RL methods optimize context management through rewards, in SWE-MeM with additional step-level masks for memory-management failures, but do not directly supervise the actions that follow compaction. Unlike these methods, AutoCompact corrects the agent’s own compaction decisions, summaries, and subsequent actions during data collection, executes the corrected outputs, and refines this behavior with outcome-based RL alone.
Conclusion
AutoCompact trains coding agents to manage context as part of task execution. Judge-corrected trajectories provide supervision for compaction decisions, summary construction, and the actions that follow compaction, followed by outcome-based reinforcement learning that jointly optimizes coding and compaction. Experiments on SWE-bench Verified and SWE-PolyBench Verified show improved task success across all evaluated inference budgets, and ignoring the compaction calls of the same trained model lowers pass rates, showing that the gains do not come from training alone. These findings highlight the value of training not only the construction of compacted states but also the agent’s behavior that follows from these states, which prior methods leave unsupervised.
AI Use Statement
In this work, we used generative AI tools for language editing and trajectory correction for training. We have reviewed all AI-assisted work. We take responsibility for the final content of this work, including text, claims, or artifacts produced with the aid of generative AI.


