betaFeedback

WorksComputer Science

Editing as Language: Teaching LLM Agents a Grammar for Native Context Editing

Abstract

A synopsis in novels folds a story into a few lines; a function in code gathers many steps with a single execution. Context editing is native to language itself. In this paper, we propose the Native Context Editing (NCE) framework, which gives language model agents a grammar for natively editing their own context. By encoding context-editing operations in a grammar of dedicated special tokens, we teach the agents to invoke edits through the language itself. We train agents on iteratively constructed trajectory segments, with each teacher edit conditioned on the evolving context. This establishes context editing as an atomic and inherent capability of LLM agents, enabling them to dynamically modify their context as they generate responses over long-horizon reasoning and interaction. Compared with context-editing methods that learn to generate tool-use code within specific external harness environments, our approach integrates context editing as an internal mechanism of the model's native generation process, enabling better generalization across diverse real-world workflows. On four long-horizon agentic benchmarks (Terminal-Bench 2.0, SWE-bench Verified, SWE-bench Multilingual, and SWE-bench Pro), NCE improves the average task success rate over the base model by 5.6 percentage points for LongCat-Flash-Lite-Sparse and by 4.5 for Qwen3.6-35B-A3B, while reducing average token usage by 36% and 15%, respectively.

[Code] | [Project page]

Introduction

Large language model (LLM) agents now tackle tasks that require many rounds of reasoning, tool use, and interaction with environments ([34, 27, 29]). In these long-horizon tasks, the interactions accumulate code, tool outputs, execution feedback, and intermediate decisions into increasingly long histories ([15]). Long-horizon agents therefore need to maintain useful working context within a finite window: retain evidence for upcoming decisions, shorten completed investigations, and remove information that is no longer needed.

Existing approaches manage context through either predefined rules or external tools. Even the most widely deployed coding agents rely on rules. Claude Code and Codex summarize the history once it crosses a fixed token threshold ([2, 20]), and simpler policies mask older observations ([15]). These triggers fire on context size alone and cannot tell which information the task still needs. Tool-based methods expose context management through external tool calls, letting the agent decide what to edit. Sculptor provides tools to fragment, summarize, hide, and restore the history ((Li et al., 2026)), and Context-Folding folds a finished sub-trajectory into a summary ([26]). Because the harness defines and executes these tools, the learned editing policy is bound to harness-specific interfaces and generalizes poorly across different environments.

Both families define context editing outside the model. Rules fix the policy in the harness, and tools, even when a learned policy calls them, take their meaning from schemas that the harness declares in the prompt. We therefore seek to answer:

How can we turn context editing into a native capability of language models?

We call context editing native when each edit takes its meaning from the model’s own vocabulary, as the end-of-sequence token <eos> does. No prompt needs to explain <eos>, and it ends generation the same way in every harness. Our answer is to make editing part of the language the model speaks. Language already provides natural primitives for organizing information, e.g., a summary compresses a story into a few lines, a function name abstracts a sequence of operations, and an updated note supersedes outdated information. Guided by this intuition, we introduce Native Context Editing (NCE), a framework that equips LLM agents with an executable grammar to compress, abstract, update, and restructure their own context as reasoning unfolds (Figure 1a).

Figure 1. Overview of NCE. (a) The agent writes edits inline with its output, each naming a target block by its icon: drop removes a file it no longer needs, rewrite condenses a failing test log to one line; the runtime applies them before the agent continues. (b) Success vs. tokens per task for LongCat-Flash-Lite-Sparse (69B-A3B) on Terminal-Bench 2.0 (Table 2). NCE succeeds most with the fewest tokens at every budget.

Specifically, NCE organizes the context into addressable blocks, and its grammar has three components: a vocabulary of dedicated tokens, in which address tokens name blocks and operator tokens (drop, rewrite, append) remove, replace, or add them; composition rules that define well-formed edits; and semantics that bind each well-formed edit to exactly one transition of the context state, executed by a task-agnostic runtime. The meaning of every edit thus ships with the model and holds in every harness. Recorded trajectories contain no edits, so we annotate them with two teachers. An offline teacher reads the full trajectory and assigns each block a release point, the turn after which the block may be edited. A block is released only when the teacher can cite the event that ended its use. An online teacher then uses the previous blocks and release annotations from the offline teacher to decide when and how to edit. The edits are thus safe to learn and executable by an agent that cannot see ahead.

We then train NCE through distillation over these editing trajectories, with supervision that follows the context as it is edited. Specifically, each edit is executed at the end of the turn that issues it, and every later editing decision and task action is constructed and supervised on the resulting context. Annotating all edits on the original history would condition later decisions on text that the agent has already deleted or rewritten, a mismatch that grows with every edit. By executing each edit before the next turn is built, NCE trains the agent on contexts shaped by its earlier edits. This is exactly the condition it faces at inference time, therefore bridging the train-test gap. During inference, the model generates each turn, the runtime executes the edits it contains, and generation resumes from the edited context, so the context can evolve throughout long-horizon reasoning.

In the experiments, we have implemented NCE on LongCat-Flash-Lite-Sparse (69B-A3B) and Qwen3.6-35B-A3B and evaluated both on four long-horizon agentic benchmarks, including Terminal-Bench 2.0 (Merrill et al., [19]), SWE-bench Verified (Jimenez et al., [10]), SWE-bench Multilingual (Yang et al., [35]), and SWE-bench Pro (Deng et al., [5]). On LongCat at 256K, NCE improves success over the base model by 4.8 to 6.3 points and reduces token usage by 31% to 44% on every benchmark (Table 1 and Figure 1b). A tool-call editing baseline trained on the same edits trails NCE by 5.2 to 8.0 points, so the gap comes from expressing the edits natively. The gains transfer to Qwen3.6, where NCE raises the average success rate over the base model by 4.5 points and cuts average token usage by 15%.

Benchmark| LongCat-Flash-Lite-Sparse (69B-A3B)| | | | | Qwen3.6-35B-A3B| | |
Success (%) ↑| | | Tokens (×106\times10^{6}) ↓| | | Success (%) ↑| | Tokens (×106\times10^{6}) ↓
RULES Comp.TOOLS ToolsNATIVE NCERULES Comp.TOOLS ToolsNATIVE NCERULES Comp.NATIVE NCERULES Comp.NATIVE NCE
TB 2.032.632.638.2 +5.66.626.384.60 −31%38.243.8 +5.62.983.04 +2%
SWE Verified65.262.470.0 +4.84.073.402.70 −34%69.874.0 +4.22.922.19 −25%
SWE Multiling.56.054.362.3 +6.310.8310.936.12 −44%58.064.3 +6.35.124.13 −19%
SWE Pro39.439.744.9 +5.29.508.466.42 −32%43.645.3 +1.75.824.92 −15%
Average48.347.353.9 +5.67.767.294.96 −36%52.456.9 +4.54.213.57 −15%

Table 1. Results at a 256K budget for harness compaction (Comp.), tool-call editing (Tools), and NCE; TB 2.0 is Terminal-Bench 2.0, SWE is SWE-bench, and tokens are per task. Bold marks the best per base model. Small numbers give the success gain of NCE over the best baseline and its token change relative to harness compaction.

We summarize our contributions below:

  • We introduce Native Context Editing (NCE), a framework that teaches LLM agents a grammar to dynamically manage their own active context through natively generated edits.

  • We develop a distillation framework with evolving contexts, where an offline teacher uses release analysis in hindsight to decide which blocks to edit, and an online teacher that sees only the present makes the edits.

  • We evaluate NCE on four long-horizon agentic benchmarks, demonstrating its effectiveness in improving task performance while also reducing both context and token usage over the base model with harness compaction.

Related Work

Long-horizon LLM agents. Research on long-horizon LLM agents has investigated how interaction with external environments can support reasoning and decision-making. For example, ReAct interleaves reasoning and action, while SWE-agent and OpenHands provide interfaces for code editing and execution [36, 34, 27]. Recent long-horizon agents learn to consolidate memory or fold their context as interactions accumulate [42, 37]. These approaches depend on retaining useful evidence across decisions, yet longer histories do not ensure reliable evidence access [17]. NCE addresses this shared challenge by maintaining the context available to ongoing reasoning and interaction.

Memory management and knowledge retrieval for LLM agents. Retrieval-augmented generation and agentic memory systems store information outside the context window and retrieve it whenever later decisions need it [12, 21, 31]. Memory managers decide what and when to store, update, or discard, often with database-like operations such as SQL or ADD/UPDATE/DELETE [7, 32], and some apply these decisions to the active context through tool calls [41, 18] (Yu et al. 2026). Unlike most memory management methods, NCE edits the active textual context of an ongoing task without introducing an external knowledge storage or information retrieval mechanism. Our approach is a parallel contribution to external memory, focusing specifically on active-context management within a fixed context-window budget.

Native Context Editing

NCE lets an agent edit its own context by generating edits in an executable grammar (§3.1). Recorded trajectories contain no edits, so we derive them with two teachers (§3.2). Each edit changes what the agent reads next, so training follows the evolving context (§3.3).

A Native Grammar for Context Editing

Notations. An edit must name its target, so NCE first organizes the context into addressable blocks.

Context management for LLM agents. Rule-based methods mask older tool outputs [15] or summarize the history once it crosses a token threshold, as Claude Code [2] and Codex [20] do; prompt compressors keep the tokens that information scores or learned predictors rate as useful [14, 8, 9, 22, 30]. Such criteria track size or salience, which need not coincide with the turn at which a piece of evidence stops being needed. Tool-based methods let the agent decide what to edit and when, through tools that fragment, summarize, hide, and restore its history (Li et al., 2026) or fold completed sub-trajectories into summaries [26]. The harness defines these tools, which ties the learned policy to that harness. NCE represents each edit with the model’s vocabulary (§3.1) and trains on edits that modify a block only after release analysis finds it no longer needed (§3.2).

Learning model-native capabilities. Native multimodal models learn images inside one model, as shared-vocabulary tokens or raw patches trained jointly with text [4, 28, 6, 25]; earlier vision systems attach a separate encoder through an adapter [1, 16]. Nativeness thus keeps a capability in the model’s own sequence and parameters. By this standard, learned control is only partly native: tool calls and folding directives draw meaning from external tools or prompts [24, 37], reflection tokens trigger an external retriever [3], and reduction tokens act only on reasoning [33, 11]. Following native multimodal models, NCE incorporates context editing directly into the model’s vocabulary through operator and address tokens, which are processed and generated inline with text. At turn tt, a block bt=(α,x)b_t = (\alpha, x) pairs a persistent address α\alpha with text xx, which may include system prompts, task descriptions, observations, or agent-written notes. The agent’s action at turn tt, such as a tool call, is denoted by ata_t. Context editing at turn tt is conditioned on the current state St=(Bt,At)S_t = (B_t, A_t), where the block history Bt=[b1,…,bt−1]B_t = [b_1, \ldots, b_{t-1}] contains the preceding context blocks, and the action history At=[a1,…,at−1]A_t = [a_1, \ldots, a_{t-1}] records the agent’s earlier actions. The model reads Render⁡(St)\operatorname{Render}(S_t), which interleaves the blocks and actions in interaction order, with each block text prefixed by its address, and generates zero or more edits ete_t (Figure 2). When the turn ends, a task-agnostic runtime executes the edits and updates the histories with the current block btb_t and action ata_t:

An abridged excerpt of an NCE training trajectory

Figure 2. An abridged excerpt of an NCE training trajectory on a Go repository. (a) The rendered context at turn tt; (b) the model’s output, a rationale followed by three edits and an action; (c) the blocks after execution. More detailed examples can be found in Appendix § 13.

St+1=Execute⁡(St,et)⊕(at,bt),(1)S_{t+1} = \operatorname{Execute}(S_t, e_t) \oplus(a_t, b_t), \tag*{(1)}

where ⊕\oplus appends ata_t to the action history AtA_t and btb_t to the edited block history BtB_t. With ete_t empty, Eq. (1) is the ordinary growth of an agent’s context.

Vocabulary. NCE reserves 70 dedicated tokens. Each block address is encoded as a two-token pair <sid_hi_h> <sid_lo_ℓ>, drawn from 32 high-order and 32 low-order address tokens. These 64 tokens support 1,024 distinct addresses. With addresses numbered from zero, the 72nd block is represented by <sid_hi_02> <sid_lo_07>. The model targets a block by copying its two address tokens. The remaining six tokens comprise three operators (🗑drop, 🖉rewrite, ⊞append), two envelope delimiters (<ctx> and </ctx>), and a marker for locked blocks.

Composition rules. An edit is one envelope around one operator:

e::=<ctx> 🗑drop α1⋯αm </ctx>∣<ctx> 🖉rewrite α x </ctx>∣<ctx> ⊞append x </ctx>e ::= \texttt{<ctx>} \ 🗑\text{drop}\ \alpha_1 \cdots\alpha_m\ \texttt{</ctx>} \mid\texttt{<ctx>} \ 🖉\text{rewrite}\ \alpha\ x\ \texttt{</ctx>} \mid\texttt{<ctx>} \ \boxplus\text{append}\ x\ \texttt{</ctx>}

where each α\alpha is a block address, m≥1m \ge1, and xx is text represented by ordinary tokens. One turn may carry several edits, explained by a one-sentence rationale in plain text.

Semantics. Each edit denotes exactly one transition of the block history. 🗑drop removes blocks α1,…,αm\alpha_1, \ldots, \alpha_m and retires their addresses for good, 🖉rewrite replaces the text of block α\alpha with xx while preserving its address, and ⊞append adds an editable block with text xx under a fresh address. Execute checks addresses and permissions and applies the edits in ete_t in order. The edit instructions themselves are not retained in the context. Render⁡(St+1)\operatorname{Render}(S_{t+1}) contains the updated blocks and action history, and its KV cache is computed from that rendered text alone, indicating that dropped blocks are excluded from subsequent rendering and cache computation.

Faithful Supervision from Two Teachers

We derive editing supervision from recorded agent trajectories, which contain no edits. A trajectory τ\tau runs for TT turns from a task, and at turn tt the agent takes action ata_t and receives observation btb_t. Replaying τ\tau through Eq. (1) with every ete_t empty yields its states S1,…,STS_1, \ldots, S_T, in which the task and each observation form a block. The central question is how long each block remains needed. A block bb is needed until the last turn whose action uses it,

rb=max⁡{t:at uses b},(2)r_b = \max\{t : a_t\ \text{uses}\ b\}, \tag*{(2)}

and rbr_b is the turn at which bb enters if no action uses it. An edit to bb after turn rbr_b is safe because no later action reads bb, and delaying it further only keeps bb in context.

Offline teacher: release analysis. The offline teacher reads the whole trajectory and assigns each block a release point r^b\hat{r}_b, the turn after which the block may be edited (Figure 3, left). Release analysis keeps every block by default and releases one only when the teacher cites the event that ended its use, typically an action that consumed the block or an observation that superseded it. Let kbk_b denote the turn of the cited event, with kb=Tk_b = T if no event is cited. A mechanical check then traces the rare literals of the block, such as paths, hashes, and line numbers, through later actions. We use λb\lambda_b to denote the last turn at which one of them reappears. The release point is

Figure 3. Editing supervision from two teachers. Left: the offline teacher reads the whole trajectory and releases a block only by citing the event that ended its use (bi⊆bjb_i \subseteq b_j: bjb_j supersedes or consumes bib_i). Right: the online teacher reads only up to b4b_4 and edits released blocks, here rewriting b2b_2 and dropping b3b_3.

r^b=max⁡(kb,λb).(3)\hat{r}_b = \max(k_b,\lambda_b). \tag*{(3)}

A reappearing literal counts as a use, so λb≤rb\lambda_b \le r_b. The literal check can only postpone release; premature release (r^b<rb\hat{r}_b < r_b) therefore requires both an incorrect release judgment and a final use that leaves no literal trace. An omitted citation merely prolongs retention. Directly labeling rbr_b requires identifying the exact last use, with errors leading to either premature release or unnecessary retention. Release analysis instead defaults to retention when evidence is missing, much as conservative liveness analysis keeps a value live while it may still be read. A second pass over the complete trajectory revisits blocks retained during the first pass, including those from abandoned lines of investigation, and releases them only with a cited event and after the same literal check.

Online teacher: edit generation. The online teacher decides when and how to edit the released blocks, seeing the present blocks and block-level eligibility markers derived from offline release analysis (Figure 3, right). It acts as the agent at turn tt: it reads Render⁡(St)\operatorname{Render}(S_t), in which a block becomes editable only after its release point r^b\hat{r}_b from the offline teacher, and writes the edits ete_t, choosing the operators and the replacement text. Every summary is drawn from the context in view, so no edit relies on anything the agent has yet to see. By default, it rewrites and drops only blocks that carry no information. Decision points arise when a reminder signals that the context is nearing its budget or when a subgoal has just been completed, and the teacher may decline when little is editable. A final audit rejects edits whose removed literals reappear later and summaries that state facts absent from their source.

Distillation with Evolving Contexts

An edit changes every later rendering, so training on the recorded history would condition later turns on context the agent has already modified. We therefore build each training trajectory by running Eq. (1) forward along τ\tau: ata_t and oto_t are the recorded action and observation, and ete_t is the online teacher’s output at a decision point and empty elsewhere. Each editing decision is thus made on a context shaped by the earlier ones, as the decisions of the trained agent will be, and a summary written at one decision point is what the teacher reads at the next, where it may be revised or dropped in turn. Release analysis keeps the recorded actions valid on this edited context, since an edit removes only what the recorded continuation no longer uses.

Every turn with edits closes a segment, and the next segment opens with the rendering of the state those edits produce. Each segment is an ordinary causal sequence whose prefix reflects every earlier edit, so the three editing turns in Figure 4 yield four training sequences. We fine-tune on these sequences with the usual next-token loss on the model’s outputs, which covers actions, rationales, and edits alike; rendered prefixes and observations serve only as conditioning. Stretches where the teacher declined to edit, including whole trajectories, are trained in the same way, so the model learns when to leave its context alone as well as how to edit it.

Figure 4. Distillation with evolving contexts. Each row supervises one turn (solid box) on the prefix left by all earlier edits (dotted box). Each editing turn closes a training sequence, so the five rows form four sequences (rows 1, 2–3, 4, and 5). Dropped blocks are drawn only for alignment.

Inference. Inference runs Eq. (1) with the model writing ete_t and ata_t and the environment returning btb_t: at each turn the model reads Render⁡(St)\operatorname{Render}(S_t) and generates its output, and the runtime executes the edits and appends the action and its observation.

Experiments and Results

Experimental Setup

Benchmarks. We evaluate on Terminal-Bench 2.0 (Merrill et al., [19]) (89 tasks), SWE-bench Verified (Jimenez et al., [10]) (500 issues), SWE-bench Multilingual (Yang et al., [35]) (300 issues), and SWE-bench Pro (Deng et al., [5]) (731 issues in the public set). Terminal-Bench runs in Terminus-2, its reference agent, and the SWE-bench variants run in Claude Code (Anthropic, [2]). Neither harness is aware of NCE: the runtime sits between the harness and the model server, executes edits there, and returns ordinary responses, so a single checkpoint serves both harnesses without any editing interface. We report two metrics: the success rate of a single run, counting runs that end without a result as failures, and token usage, the prompt and output tokens of all model calls in a task, including compaction, averaged over tasks after excluding the 10% with the highest and the

10% with the lowest usage. Such a trimmed mean is used to avoid the influence of long-tail data. All four benchmarks are evaluated with a 256K-token budget. Terminal-Bench accumulates much longer histories than SWE-bench, so we also evaluate it at 128K, 64K, and 48K.

Models and training. We train NCE on LongCat-Flash-Lite-Sparse (69B-A3B) (Zan et al., [40]) and Qwen3.6-35B-A3B (Qwen Team, [23]), two mixture-of-experts models with 3B active parameters, starting from their instruction-tuned checkpoints. We use GLM 5.3 (Z.ai, [39]) as the two teachers of § 3.2 to annotate nearly 180K recorded agent trajectories on software engineering and terminal tasks, which we split into training segments (§ 3.3). Each model is fully fine-tuned on these segments for three epochs. Appendix § 11 details data, hyperparameters, and the budget configuration.

Baselines. We compare NCE with one baseline from each family of the Introduction, marked RULES and TOOLS in the tables. Harness compaction (Comp.) runs the base model that NCE is trained from, with the built-in compaction of each harness, which replaces the history with a model-written summary once it reaches the budget. Tool-call editing (Tools) is our implementation of tool-based editing following MemAct (Zhang et al., [41]). We train it on LongCat only, using the same trajectories, edit supervision, and training recipe as NCE. Each edit invokes one of three tools that mirror NCE’s operators (Appendix § 11), enabling a controlled comparison between tool-call and native editing. Our evaluation focuses on the active context under a fixed budget, so systems that store and retrieve information outside it fall outside this comparison.

Main Results

NCE achieves higher success with fewer tokens. At 256K, NCE leads both baselines on every benchmark while spending 36% fewer tokens per task than harness compaction on average (Table 1). The gains hold in Claude Code and Terminus-2 alike, neither of which exposes an editing interface.

Native edits outperform the same edits as tool calls. Trained on the same edits, tool-call editing falls below harness compaction in average success and saves only 6% of its tokens, while NCE saves 36%. The edits pay off only when the model writes them in its own grammar.

The gains hold at every budget. On Terminal-Bench, NCE leads both baselines at every budget from 256K down to 48K, improving success over harness compaction by 5.6 to 10.1 points with 26% to 39% fewer tokens, and NCE at 64K matches both baselines at 256K with less than 40% of their tokens (Table 2 and Figure 1b).

Budget| Success (%) ↑| | | Tokens (×106\times10^{6}) ↓
Comp.ToolsNCEComp.ToolsNCE
256K32.632.638.2 +5.66.626.384.60 −31%
128K25.830.334.8 +4.56.084.963.70 −39%
64K27.029.232.6 +3.43.423.582.52 −26%
48K20.227.030.3 +3.33.403.172.15 −37%

Table 2. LongCat on Terminal-Bench 2.0 as the context budget shrinks.

The gains transfer across base models. On Qwen3.6, NCE improves all four benchmarks and cuts average token usage by 15%: the same grammar and supervision teach a second model family to edit its own context.

Ablation Study

We compare NCE with other context managers, ablate how its supervision is built, and examine its edits at inference.

Native editing reaches the best success at the lowest cost. On Terminal-Bench under a 128K budget, we replace NCE with four context managers on the base model: harness compaction, a sliding window over recent turns, a fixed 4K memory state, and prompt compression of old tool outputs (Figure 5, Appendix § 12.§ 1). NCE reaches the highest success rate (34.8% against 25.8–32.6%) with the fewest tokens per task (3.7M against 4.6–6.1M) and the smallest context (30.5K against 38–44K on average). The other four managers act on position, size, or the budget alone, while our NCE edits by what the task still needs, so its context stays below theirs throughout the task.

Figure 5. Context management on Terminal-Bench 2.0 with LongCat under a 128K budget. (a) Success rate vs. tokens per task. (b) Context length vs. unmanaged history length (median and interquartile range); the drop of NCE at 128K is the harness compaction it keeps.

Supervision needs both teachers and the evolving context. We build supervision for the same 40 trajectories in three ways: by one teacher in one pass, by the two teachers on the original history, and by the two teachers on the evolving context, as in NCE. We check every edit against what the agent could see when it was made (Figure 6, Appendix § 12.§ 2). Labeling in one pass leaks hindsight: in 30.0% of trajectories a summary uses future information. Labeling on the original history misses that earlier edits have removed part of it, a median of 37% by the fifth decision, so in 95.0% of trajectories an edit targets a block that is already gone. NCE lowers these defects to 5.0% and 0.0%, and the share of trajectories with any defective edit from 80.0% (one pass) and 100.0% (original history) to 37.5%.

Figure 6. Building editing supervision. (a, c) Share of the 40 trajectories with at least one edit of each kind (95% bootstrap intervals). (b) Share of the original history no longer in the agent’s context at each editing decision, over 4,250 training trajectories (median and interquartile range).

Operator use of NCE with LongCat at 256K

Figure 7. Operator use of NCE with LongCat at 256K. (a) Claude Code pools the three SWE-bench sets, and Terminus-2 runs Terminal-Bench 2.0; append removes no tokens. (b) Each operator’s removed tokens by the tool that produced the block.

NCE drops what it has used and condenses what it still needs. drop accounts for most operations, yet rewrite removes slightly more tokens (Figure 7): it condenses long blocks, mostly file reads and sub-agent reports, to about a fifth of their length, while drop also clears shell output and edit results. Both harnesses show the same pattern, and 99.1% of the 73K edits NCE writes execute as written. Most edits are proactive: 89% come before any budget reminder. Editing also frees budget early: when the unedited history first fills a 48K budget, NCE’s context fills only 73% of it, leaving over a quarter of the budget free (Appendix § 12.§ 3).

Re-prefill does not slow the agent. An edit invalidates the KV cache from the first edited block onward. Without any overlap, re-prefilling takes only 0.2–0.4% of a task’s wall-clock time. Since a turn writes its edits before its action, the runtime can start the re-prefill as soon as the last edit closes, while the action is still being generated and executed; on measured timings, this hides it entirely in 98% of editing turns under Terminus-2 and 81% under Claude Code. In compute, the edits remove 4 to 22 times as many tokens from later prompts as the re-prefill adds (Appendix § 12.§ 4).

Conclusion

We introduced Native Context Editing (NCE), which makes context editing part of the language an LLM agent speaks. A grammar of dedicated tokens binds each edit to one transition of an addressable context state, so the meaning of every edit ships with the model and holds in every harness. Two teachers supply causal edits, while training follows the context produced by earlier edits. Across benchmarks, base models, and harnesses, NCE improves task success with fewer tokens and outperforms the same edits issued as tool calls. Context management thereby moves from the harness into the model’s own language.

Limitations

We evaluate NCE on software engineering and terminal tasks, where long tool outputs make context editing especially consequential; extending it to other long-horizon settings, such as web navigation and deep research, is a natural next step. Both base models are mixture-of-experts models with 3B active parameters, and scaling NCE to larger models remains to be explored. NCE learns to edit through supervised distillation, and reinforcement learning on task outcomes could further refine when and how the agent edits. Finally, this study manages the active context within a fixed budget, and combining NCE with external memory and retrieval is left for future work.

Ethical Considerations

This work trains LLM agents on recorded trajectories of software engineering and terminal tasks and evaluates them on public benchmarks. It involves no human subjects, and we collect no personal data. We use all models and datasets in accordance with their licenses and intended research use, and we do not foresee ethical concerns beyond those common to LLM agents.

LLM Usage

We used large language models (LLMs) only to check grammar and refine the language of this paper. The research ideas, analyses, results, and conclusions are entirely the authors’ own.

The NCE Grammar and Runtime

This appendix specifies the grammar of § 3.1 in full: the dedicated tokens (A.1), how a context state is rendered (A.2), how the runtime executes edits (A.3), the reminders it issues (A.4), and how it serves an unmodified harness (A.5).

Vocabulary

Table 3 lists the 70 tokens NCE adds to the vocabulary of the base model. Block nn, counted from zero in order of creation, receives the address <sid_hi_h> <sid_lo_l> with h=⌊n/32⌋h = \lfloor n/32 \rfloor and ℓ=n mod 32\ell= n \bmod32. An address is never reused within a session, so it names the same block for as long as the block lives, and a dropped block cannot be confused with a later one. The role tags that open each block (<longcat_user>, <longcat_observation>, and so on) are the existing tokens of the base chat template.

Rendering

Render(S_t) writes each block as its two address tokens, the lock marker if the block is locked, and the block text in the chat format of the base model, opened by its role tag. No closing token is needed: the address of the next block marks where a block ends. Actions are written as ordinary assistant turns and carry no address, so an edit can reach observations, the task, and notes, and leaves the agent’s own actions intact. Every tool result forms a block of its own, which lets the agent drop one result of a batch and keep the others. Figure 8 shows the beginning of a rendered context from a SWE-bench Multilingual task under Claude Code.

Rendered context at turn 22 (abridged)

Figure 8. The beginning of a rendered context. Each block opens with its address; the system prompt carries the lock marker. Actions, set in italics here, are assistant turns without an address. Contents are abridged with [. . .].

Execution

When a turn ends, the runtime extracts every envelope <ctx>…</ctx> from the output and executes the edits in the order they were written. An edit executes only if it is well formed: the envelope opens with exactly one operator, 🗑 drop lists at least one address, 🖊 rewrite names one address followed by its replacement text, and ⊞ append carries non-empty text. Every address must name a live block, and no edit may touch the locked block. An edit that fails these checks changes nothing, with one exception: a rewrite of a block that is no longer live is applied as an append, so that its text is kept. An edit repeated verbatim within a turn executes once. The runtime then strips the envelopes from the output, and the remaining text, the rationale and the action, enters the action history. If at least one edit executed, the next prompt is rendered afresh from the new state; otherwise it extends the previous prompt and reuses its prefix cache.

Figure 9 traces one editing turn from the task of Figure 8. After four rounds of reading and editing the same function, the agent has fixed the bug and turns to the regression test. Without a reminder, it writes a one-sentence rationale and fourteen edits before its next action. It drops the four superseded reads of the function and the four confirmations of its intermediate edits, keeps the latest read, which shows the fixed code, and rewrites four exploration results into one-line references that keep their file paths and line numbers. The context shrinks from 41.1K to 29.0K tokens, and the agent continues with the test.

Reminders

Under a budget WW, the runtime appends a transient reminder to the prompt once the context reaches 70% of WW (soft) or 95% of WW (hard). The text contains no numbers, so the model cannot read off how much room is left, and the same text serves NCE and tool-call editing:

Soft reminder (70% of WW)

[context-monitor] Your context has grown sizeable; this is a good moment to tidy it up. If anything in it is no longer needed, condense or remove all of it in one pass — clear out everything that has served its purpose and leave the rest untouched; do not trim a little and save the rest for later. If there is very little worth cleaning up, or everything is still in use, you may explain why and decline — that is a reasonable choice.

Hard reminder (95% of WW)

[context-monitor] Your context is close to its limit and must be cleaned up now. Before anything else is written, condense or remove everything that is no longer needed — clear all of it out and leave what you still rely on untouched. This is not optional; only if there is genuinely nothing that can be cleaned up may you explain why and skip it.

A soft reminder may be declined. After any reminder the runtime waits four turns before the next one, eight after a declined soft reminder, and it stops issuing soft reminders once two have been declined; hard reminders are not limited. A reminder stays in the prompt only until the next edit executes. The online teacher sees reminders of the same form when it builds the supervision (Appendix § 10), and at evaluation most edits are issued without any reminder (Table 7).

TB2VerifiedMulti.Pro
Tasks with edits89.793.297.093.4
Edits without reminder71.694.685.088.8
Operations per task32.036.155.848.0
Editing turns per task1.61.82.31.9
Editing turns of all turns2.92.01.71.5
Editing turns of all output3.89.08.78.9
🗑 drop59756970
🖊 rewrite39242928
⊞ append2222
Removed per editing turn12.7K7.9K11.1K16.7K
Executed as written99.999.898.099.3
Ops. losing evidence0.151.211.231.35
Peak context reduction8.111.313.414.3

Table 7. Editing behavior of NCE at 256K, in percent except the two per-task counts and the tokens removed per editing turn. On Terminal-Bench, peak context reduction covers the turns before the first harness compaction.

Serving an Unmodified Harness

The runtime runs as a proxy between the harness and the model server and keeps one context state per agent session, including each sub-agent that Claude Code launches. For every chat request it (i) matches the request to its session and adds the new observations as blocks, (ii) appends a reminder if one is due, (iii) renders the state and forwards it to the model server, (iv) executes the edits in the response, and (v) returns the response to the harness with the envelopes removed and the action in the format of the harness. The harness therefore sees an ordinary model: its prompts, tool definitions, and compaction logic stay unchanged. Requests outside the agent loop, such as the title requests of Claude Code, pass through to the base chat template. Because the runtime holds the state, the same checkpoint serves Claude Code and Terminus-2 without any harness-specific code beyond request parsing.

One editing turn, executed

Figure 9. One editing turn, executed. Left: the output of NCE at turn 22 of a SWE-bench Multilingual task under Claude Code, with no reminder pending; the edits are typeset with chips of Table 3. Right: every block of the context before the turn and its size after it. Blocks 10, 12, 14, and 16 are earlier reads of the function that block 19 shows in its fixed form; blocks 13, 15, 17, and 18 confirm intermediate edits to it. Rewritten blocks keep their addresses; dropped addresses are retired.

Token#Role
<sid_hi_00> … <sid_hi_31>32high address digit
<sid_lo_00> … <sid_lo_31>32low address digit
🗑 drop1remove blocks
🖊 rewrite1replace a block’s text
⊞ append1add a note block
<ctx>2delimit one edit
<m_ro>1mark a locked block
Total70

Table 3. The dedicated tokens of NCE. Operators are shown with the chips used throughout the paper; their token strings are <op_drop>, <op_rewrite>, and <op_append>.

Building the Editing Supervision

Figure 10 summarizes how a recorded trajectory becomes training segments. This section gives the rules behind each stage, the two teacher prompts, an annotated example, and statistics of the resulting data.

The annotation pipeline: recorded trajectory, blocks, offline teacher, online teacher, final audit, and segments

Figure 10. The annotation pipeline. Only the online teacher writes edits; the offline teacher decides which blocks it may touch, and the audit removes edits that fail a mechanical check.

Pipeline

Blocks. We replay each trajectory with every ete_t empty and split it into blocks: the system prompt

(locked), the task, every tool result, and every user message each form one block, and the block that enters before turn tt has entry turn tt. Reasoning and actions stay in the action history.

Offline teacher, forward pass. The teacher reads the whole trajectory, with each block labeled by its index and entry turn, and keeps every block by default. It releases a block only by citing the event that ended its use: an action that consumed the block, such as writing the file it was read from into new code, or a later observation that superseded it, such as a full read of a file that a search result only pointed to. Each release names the turn after which the block may be edited and states its cause in one sentence that names the turn and the action. A release has one of two strengths: to summary, when the fact that the block existed and its conclusion still help navigation, and to drop, when the block carries no information, such as an operation receipt or an empty search result. The forward pass also marks at most two subgoal milestones per trajectory, which later become decision points.

Literal check. For each released block, we extract its rare literals: paths of at least four characters, identifiers containing an underscore, integers of five or more digits, hexadecimal strings of eight or more characters, decimals with four or more fractional digits, and four-digit numbers in line-number position, such as 1589: in a search result. A literal is rare if it is at least four characters long and occurs at most eight times in the whole trajectory. We then scan every action after the cited turn, including tool-call arguments. If a literal reappears, the release moves to the last turn where one reappears, and a drop becomes a summary. Identifiers are traced only for drops, since a summary keeps them. Two further clamps only postpone as well: a block read from a file is not released before the last turn that edits that file, and a block that serves as the blueprint of the final solution is not released before the turn that writes the solution out.

Offline teacher, second pass. The forward pass is conservative and keeps blocks such as the outputs of abandoned lines of investigation. A second pass collects candidates from the kept blocks in three ways: the teacher nominates blocks that, looking back over the finished trajectory, sit on an abandoned or superseded branch, with recall as the goal; a mechanical rule adds tool results whose rare literals stop reappearing at least three turns before the end; and injected reminders and bare continuation messages are added as well. A strict review then judges every candidate. A release must name the turn and action that ended the use of the block, and the review must find no residual dependency in a turn-by-turn scan of the rest of the trajectory, covering literals copied into later tool arguments (such as a line offset), later code checked against the block, and candidate options of an open decision. When the reviewer claims that a later block supersedes a candidate, we verify mechanically that the distinctive lines of the candidate appear in that block and reject the release otherwise. Approved releases pass the same literal check.

Decision points. Each trajectory is assigned a context budget WW from 32K, 48K, 64K, and 128K, the largest tier under which its peak context crosses the soft line while its incompressible floor still fits. Replaying the trajectory turn by turn with exact token counts, we create a decision point when (i) the context first reaches 0.70W0.70W, which inserts a soft reminder that the agent may decline; (ii) it reaches 0.95W0.95W, which inserts a hard reminder that it may decline only when nothing is editable; or (iii) a milestone of the forward pass is reached. Each trigger has a cool-down of two turns, and a milestone fires only if the last edit lies at least two turns back. At soft and milestone decision points, if the editable blocks together hold less than 8% of the current context, the teacher is not called and the turn becomes a declined decision. The reminder text contains no numbers, and the teacher never sees token counts.

Online teacher. At a decision point the teacher plays the agent at turn tt. It sees the trigger and every block still in context, each marked editable if t>r^bt > \hat{r}_b and off-limits otherwise; it does not see release points, release reasons, or anything after turn tt. Editing is all or nothing: once the teacher edits, it disposes of every editable block, rewriting by default, dropping only blocks without information, and appending a note when several blocks share a conclusion that the note consolidates. Every fact in a summary must come from the block it replaces. The teacher writes the one-sentence rationale that precedes the edits in training. If the edits free less than 8% of the context at a soft or milestone point, the whole decision is discarded and the turn is trained as a decline. The edits execute immediately, so the next decision point sees the rewritten blocks; a summary is editable again only if it is still long.

Final audit. The audit rejects an edit when (i) a number, path, identifier, or quoted string in a summary or note does not occur in its source block, or in the trajectory for a note; (ii) a literal that the edit removes reappears in a later action without having appeared in a summary or in visible output first; or (iii) the editing turn frees less than 3% of the context. It discards a trajectory when a hard reminder ends without an edit, or when more than six turns, and more than 15% of all turns, carry edits. About 4% of annotated trajectories are discarded.

Segments. We render each surviving trajectory along the evolving context (§ 3.3) and cut a segment at every turn with edits. Reminders enter as transient user messages that are kept only in the segment in which they appear.

Teacher Prompts

Figure 11 shows the prompt of the forward pass of the offline teacher and the prompt of the online teacher, abridged. The second pass uses two further prompts with the same output conventions: a nomination prompt that asks for high recall and a review prompt that enforces the release conditions above.

Teacher prompts for offline release analysis and online edit generation

Figure 11. Teacher prompts, abridged ([...]). Placeholders filled by the annotation driver are highlighted. The online teacher sees no turn after tt, no release point, and no token count.

An Annotated Example

The trajectory fixes a channel-validation bug in a Go repository in 19 turns and 20 blocks (Figure 12); outputs are abridged and shown in English. The offline teacher releases two edit receipts at the turn after the edit, citing that they acknowledge an operation and nothing else. The literal check finds the edited path in a Read at a later turn and postpones both releases to that read, turning the drops into summaries. The online teacher acts at the milestone after turn 12, when all three code changes have been verified, and rewrites the original read of the edited file together with the receipts; each receipt summary keeps the path that the literal check traced.

Annotation of one trajectory

Figure 12. Annotation of one trajectory. (a) Release points of four blocks; kbk_b is the turn of the cited event and λb\lambda_b the last turn at which a rare literal of the block reappears. (b) The online teacher’s rationale and edits at a decision point, in the NCE grammar; block nn has address <sid_hi_00> <sid_lo_n>.

Data Statistics

Table 4 summarizes one annotation batch of about 50K trajectories. Decision points arise mostly at milestones and soft reminders; hard reminders are rare because edits at earlier decision points keep the context below 0.95W0.95W. Edits make up close to a third of the supervised tokens, and close to a third

BlockContentCited event (teacher, abridged)kbk_bλb\lambda_br^b\hat{r}_b
5search hits for validateCCVChannelParamsTurn 4 read provider/ibc_module.go in full; the hit list only pointed the way.5–5
9receipt: edit to provider/keeper/proposal.goPure success receipt; turn 11 verifies the change with a Read.81111
10receipt: edit to consumer/ibc_module.goPure success receipt; turn 10 verifies the change with a Read.91010
14one unit test passesSuperseded by the full consumer test run at turn 14.13–13

Table 4. Statistics of one annotation batch. A drop that names several blocks counts once per block.

Shaded: the literal check postpones the release, since the path in the receipt reappears in Read(file_path=...) at the shaded turn; the teacher proposed a drop, which becomes a summary.

(b) Online teacher: decision point after turn 12 (milestone: all three changes verified)

The three code changes are done and verified, so I condense the original file contents I read before the change and the edit receipts into key points, keep the conclusions, and move on to testing.

<ctx> ✎ rewrite <sid_hi_00> <sid_lo_02> Read the original x/ccv/consumer/ibc_module.go (package consumer, before the change). [...] validateCCVChannelParams (around lines 91–99) checks portID == boundPort (else ErrInvalidPort) and version == ccv.Version (else ErrInvalidVersion). [...] </ctx>

<ctx> ✎ rewrite <sid_hi_00> <sid_lo_09> Edit receipt: /testbed/x/ccv/provider/keeper/proposal.go updated successfully. </ctx>

<ctx> ✎ rewrite <sid_hi_00> <sid_lo_10> Edit receipt: /testbed/x/ccv/consumer/ibc_module.go, first change applied. </ctx>

[three further rewrites: the second half of the original file read, the second receipt, and an earlier read of proposal.go]

StatisticValue
Segments per trajectory≈2.9
Decision points per trajectory≈2.0
milestone / soft / hard60 / 38 / 2%
Segments without edits31%
Edited blocks: rewrite / drop35 / 65%
Appended notes, share of operations2%
Supervised tokens that are edits31%
Trajectories discarded by the audit4%

of the segments carry no edit at all, which teaches the model when to leave its context alone.

Experimental Details

Harnesses. The SWE-bench variants run in Claude Code (version 2.1.7) and Terminal-Bench 2.0 runs in Terminus-2 on Harbor. Both harnesses send ordinary chat requests to the NCE runtime, which serves them as described in Appendix § 9.§ 5; neither harness needs any change to its prompts or tool definitions.

Context budgets. For a budget WW, the compaction threshold of each harness is set to WW: Claude Code through its auto-compaction setting and Terminus-2 through its context limit. Terminus-2 counts its own copy of the history, which keeps the text NCE has edited away, so it also compacts NCE runs once that copy reaches WW. The runtime issues a soft reminder when the context reaches 70% of WW and a hard reminder at 95% (Appendix § 9.§ 4); the reminder text contains no numbers and is identical for NCE and tool-call editing.

Training data. The training trajectories, nearly 180K in total, are downsampled from agentic data that LongCat has already been trained on. Appendix § 10 describes how we annotate them with edits.

Training. LongCat is trained with Megatron on a large-scale GPU cluster. Qwen3.6 is trained with ms-swift using AdamW (β1=0.9\beta_1 = 0.9, β2=0.95\beta_2 = 0.95, weight decay 5×10−55 \times10^{-5}) at a peak learning rate of 1×10−51 \times10^{-5}, with 3% linear warmup and cosine decay to 1×10−61 \times10^{-6}. Sequences are packed to 98,304 tokens, each global batch holds 128 packed sequences, and gradients are clipped to a norm of 1.0. Training runs in bfloat16 for three epochs (2,628 steps). For both models, the loss covers assistant tokens only.

Tool-call editing. The three tools take block identifiers shown in the rendered context: drop_context(ids) removes blocks, rewrite_context(id, summary) replaces a block in place, and append_note(note) adds a note. Each call returns a result message, and a dropped or rewritten block leaves a short stub in the history. Every edit in the NCE training data is mapped to the corresponding tool call, so the two training sets contain the same edits at the same turns. Figure 13 shows one edit in both forms.

The same two edits in NCE and in tool-call editing

Figure 13. The same two edits in NCE and in tool-call editing. NCE edits vanish once executed, while each tool call stays in the history with its result message.

Decoding. All methods sample with temperature 1.0, top-pp 0.95, and top-kk 50, with at most 32,768 output tokens per model call. Thinking is off in every run.

Analysis

This appendix details the ablations of § 4.3: context management (D.1), building supervision (D.2), the edits NCE writes at inference (D.3), and the cost of re-prefilling after an edit (D.4).

Context Management

Methods. All five methods run on Terminal-Bench 2.0 under a 128K budget. The four baselines use the LongCat base model from which NCE is trained. Harness compaction is the built-in mechanism of Terminus-2: once the history reaches the budget, the harness asks the model for a summary, lets a fresh instance ask questions about it, and continues from the summary, the questions, and their answers. The other three baselines run inside the runtime in place of harness compaction and always keep the system prompt and the task description. The sliding window drops the oldest turns once the prompt exceeds the budget, down to 75% of the budget, and leaves a one-line marker in their place. The fixed memory state drops turns the same way and adds a memory block of at most 4,096 tokens, which the base model rewrites from the previous memory and the dropped turns at every eviction. Prompt compression has the base model compress every tool output longer than 1,024 tokens to at most 256 tokens once it is older than the two most recent turns, and falls back to the sliding window when the prompt still exceeds the budget. NCE keeps harness compaction as in Table 2; since the harness counts its own copy of the history, it also compacts some NCE tasks.

Accounting. Tokens per task sum the prompt and output tokens of all model calls, including compaction calls. As in Table 1, tokens are averaged over tasks with a 10% trimmed mean. The context of a turn is the number of prompt tokens the model receives; we average the mean and the peak of each task over tasks. A reduction is one harness handoff, one eviction of the sliding window or the memory state, one compression call, or one NCE turn with an executed edit. Table 5 lists the results.

MethodSolvedSuccess (%)Tokens (M)Context (K) MeanContext (K) PeakReductionsTurns
Harness compaction2325.86.0838.379.70.6119
Sliding window2325.84.6243.671.51.792
Fixed memory state2629.25.5944.072.91.995
Prompt compression2932.64.6838.366.014.095
NCE3134.83.7030.561.13.199

Table 5. Five ways to manage context on Terminal-Bench 2.0 with LongCat under a 128K budget. Solved counts are out of 89 tasks; tokens, context, reductions, and turns are per task.

Building Supervision

Designs. We compare three ways to build editing supervision on 40 trajectories sampled from our long-trajectory training pool, stratified by source and by the number of editing decisions (26 terminal tasks and 14 software engineering issues, 97 decisions in total). All three use the same teacher model, decide at the same turns, and receive the same trigger signals; the decision turns are those at which the production pipeline edited. One teacher, one pass reads the whole trajectory and writes the edits of every decision in a single response; its prompt states that the agent at decision turn tt has seen only the blocks and actions up to tt and requires every summary to use that information alone. Two teachers, original history keeps the release points of the offline teacher and runs the online teacher at every decision on the unedited history. Two teachers, evolving context is NCE: each decision is made on the context that the earlier edits produced. The two two-teacher designs share their first decision, since no edit precedes it, and differ only from the second decision on.

Defects. We execute the edits of each design in order on the recorded trajectory and check every edit against what the agent could see at that moment. A literal is a path, file name, identifier with an underscore or an inner capital, number with at least four digits, decimal number, IPv4 address, or hexadecimal hash, of at least five characters, that occurs in fewer than 2% of 1,000 reference trajectories; the frequency filter removes strings such as os.path that an agent can write from general knowledge. An edit at turn tt

  • uses future information if its text contains a literal that first appears in the trajectory after turn tt and is absent from the action of turn tt;

  • deletes evidence used later if it removes from the context a literal that a later action uses before any later observation supplies it again;

  • edits a removed block if it targets a block that is no longer in the context;

  • restates removed text if its text contains a literal that occurs in the original history but no longer in the context.

A trajectory has a defect of a type if at least one of its edits does. Intervals are 95% bootstrap intervals over trajectories, and pp-values come from an exact paired sign test over trajectories.

Results. Table 6 lists all rates. Against the single pass, NCE has fewer trajectories with future information (2 against 12 discordant trajectories, p=0.013p = 0.013), with deleted evidence (2 against 16, p=0.0013p = 0.0013), and with any defect (1 against 18, p=7.6×10−5p = 7.6 \times10^{-5}). Against the original history, NCE has fewer trajectories with edits of removed blocks (0 against 38, p=7×10−12p = 7 \times10^{-12}) and with restated removed text (0 against 33, p=2×10−10p = 2 \times10^{-10}). The original-history design re-edits the blocks its earlier decisions already handled: 810 of its 4,229 edits target a removed block.

Trajectories (%)One passOriginalNCE
Uses future information30.012.55.0
Deletes evidence used later72.540.037.5
Edits a removed block0.095.00.0
Restates removed text7.585.02.5
Any defect80.0100.037.5
Defective edits (%)4.522.51.1
Edits3,2134,2292,484

Table 6. Defects of three ways to build supervision on 40 trajectories. Original: two teachers on the original history.

Drift. Figure 6b measures the drift on 4,250 annotated training trajectories. At each editing decision, the drift is the share of the tokens of the unedited history that are no longer in the agent’s context, computed from the context lengths of the same trajectory replayed with and without its edits under the same renderer and tokenizer. Of the training trajectories, 75% have at least two editing decisions, and 47% of supervised turns follow the first edit. We exclude trajectories whose two replays already differ by more than 1% before the first edit (2,640 of 6,890 sampled, 2,582 of them from a single data batch).

Editing at Inference

We read every turn the NCE runtime served in the LongCat runs of Table 1 and Table 2. An operation is one envelope <ctx> . . . </ctx>; an editing turn contains at least one operation that executes. Table 7 reports each benchmark at 256K and Figure 14 summarizes the analysis.

Figure 14. Editing at inference. (a) Context NCE maintains when the unedited history first fills the budget on Terminal-Bench, as a share of the budget (median and interquartile range). (b) Operation mix at 256K and share of edits executed as written. (c) Cumulative share of editing turns by re-prefill time over idle time at 9.5K tokens/s; turns left of 1 hide the re-prefill entirely.

Token cost. We count the tokens processed per task as the sum of prompt and output tokens over all model calls, including compaction calls, and average them over tasks with a 10% trimmed mean. At 256K, NCE processes 64% of the tokens of harness compaction on average across the four benchmarks, and on Terminal-Bench the ratio stays between 61% and 74% at every budget.

Editing behavior. Editing turns make up 1.7% of all turns and 8.1% of output tokens, and the edits themselves take 5.7% of output tokens. A task receives 45 operations in 1.9 editing turns on average, 🗑 drop accounts for 71% of operations, and an editing turn removes 12.7K tokens on average. Of the 73,148 edits the model writes, 99.1% are well formed, address live blocks, and execute as written; the rest mostly address a block that an earlier edit already removed or repeat an edit verbatim. Tighter budgets raise the share of reminded edits: on Terminal-Bench, edits issued without a reminder fall from 72% at 256K to 27% at 48K, and editing turns rise from 2.9% to 5.0% of turns.

Compaction. Because the edited context grows more slowly, the harness rarely needs to compact. Under Claude Code at 256K, it compacts in 3 of the 1,531 SWE-bench tasks of NCE (0.2%), against 14 of 1,531 under tool-call editing (0.9%) at the same threshold.

Evidence. Edits rarely remove evidence the agent still needs. We trace the rare literals of every block an 🗑 drop or 🖊 rewrite removes, with the literal definition of Appendix § 12.§ 2, through the agent’s later actions. Of the removed literals, 1.4% reappear in a later action, and 0.45% reappear while absent from the agent’s context. Only 1.2% of 🗑 drop and 🖊 rewrite operations remove a literal that the agent later writes without seeing it, and 0.2% when only paths, numbers, and hashes count. Most of these are framework names the model writes from knowledge, such as django.core, or paths a rewritten sub-agent report left out.

Budget. Edits free a quarter of the budget before compaction is due. On Terminal-Bench, Terminus-2 compacts once the unedited history reaches the budget, and NCE’s context is always smaller than that history, so we compare the two only before the first harness compaction of each task, where neither side has been compacted. When the unedited history first fills a budget of 48K, 64K, or 128K, the context NCE maintains fills a median of 73%, 69%, and 73% of it (Figure 14a): by then NCE has freed over a quarter of the budget on its own. Over the same turns, edits lower the peak context of a task by a median of 19%.

Harnesses. The edits keep their meaning across harnesses. Claude Code and Terminus-2 differ in prompts, tools, and observation formats, yet NCE edits in 94% of SWE-bench tasks and 90% of Terminal-Bench tasks, 🗑 drop leads the operation mix in both (71% and 59%), an editing turn removes 12.7K tokens in both, and 99.1% and 99.9% of edits execute as written (Figure 14b). In Claude Code the removed blocks are tool results, led by shell output (31%), file reads (22%), and searches (16%); the task itself is edited in under 1% of operations.

Re-prefill After an Edit

An edit changes the rendered context from the first edited block onward, so the KV cache of everything after that block must be recomputed. Edits execute when the turn ends, and every token of the next prompt except the new observation is then known. A runtime can therefore issue the re-prefill as a separate request before the harness returns the observation. We measure how much time this re-prefill costs and how much of it fits into time the model server would otherwise leave idle for this agent.

Re-prefill length. For each editing turn we compare the next prompt with the sequence held in the prefix cache, the previous prompt followed by the model’s output. The re-prefill spans from the first differing token to the start of the new observation; the observation itself is excluded because every method must prefill it. Turns without edits differ only in the turn delimiter, a single token, which confirms the comparison. The model edits old blocks, and the oldest blocks sit right after the task, so an edit invalidates most of the context: the median re-prefill is 23K to 58K tokens on Terminal-Bench (86–97% of the prompt) and 13K to 22K tokens on SWE-bench (45–55%, behind roughly 18K tokens of Claude Code tool declarations that are never edited).

Prefill rate. The traces record when each request was sent and answered, but no time to first token. We regress the latency of every request on its prompt length, its output length, and its re-prefill length, with a separate intercept per run. Each re-prefilled token adds 0.105 s per 1K tokens on Claude Code (95% CI 0.083–0.123, bootstrap over tasks), an effective rate of 9.5K tokens/s under the load of our evaluation. An ordinary prompt token adds only 0.039 s per 1K, which shows that ordinary turns reuse the prefix cache. On Terminus-2 the estimate is noisier (0.044 s per 1K, CI −0.001–0.094), and we apply the Claude Code rate to both harnesses, which is conservative for Terminus-2.

Cost on our runs. Our runtime never overlaps the re-prefill with other work, so the measured cost is an upper bound. It adds 0.2–0.4% to the wall-clock time of a task on every benchmark and budget (90th percentile at most 0.8%), since a task has 1.6 to 5.4 editing turns among tens to hundreds of turns. In token terms, the re-prefill amounts to 0.7–4.8% of the tokens processed per task, while the edits remove 4 to 22 times as many tokens from the prompts of later turns.

Hiding the re-prefill. A turn writes its edits before its action, so the runtime knows the new context as soon as the last edit closes, while the model still writes the action and the harness then executes it. The idle time available to the re-prefill therefore runs from the last edit of the turn to the next request. We estimate its decoding part from the output tokens after the last edit and the measured decoding time per token, and take the rest from the harness timestamps. Starting at the last edit, the re-prefill fits entirely in 98% of editing turns under Terminus-2 and 81% under Claude Code (Table 8, Figure 15). These shares are computed from the measured timings of our runs.

Prefill rateTerminus-2Claude Code
5K tokens/s9262
9.5K tokens/s9881
20K tokens/s10093
40K tokens/s10098
Time hidden (9.5K)9881

Table 8. Share of editing turns (%) whose re-prefill fits entirely in the idle time, at four prefill rates; bold marks the rate measured from our traces. The last row gives the share of re-prefill time hidden.

Figure 15. Re-prefill time against idle time for every editing turn at 9.5K tokens/s. Points in the shaded region are hidden entirely.

Case Studies

Figure 16 follows NCE through one Terminal-Bench 2.0 task at a 48K budget. NCE solves the task, and both baselines fail it. All excerpts are verbatim model output from the evaluation logs, shortened with . . . .

NCE context length and model output at editing turns for a Terminal-Bench task

Figure 16. NCE keeps a Terminal-Bench task inside a 48K budget by folding finished experiments into notes. Left: context length per turn. The dashed line adds back the tokens removed by earlier edits; the shaded gap is what NCE keeps out of the context. Numbered markers are editing turns, colored by the operation that removes the most tokens. Right: rationale (italics) and edits at each editing turn, with the net tokens the turn removes. Each failed configuration becomes one line with its settings and error, and the raw logs go once a note covers them. Terminus-2 counts the unedited history and hands off at turn 40 (dotted line).

Figure 17 shows the same model in Claude Code on SWE-bench Verified at a 256K budget, where it edits without any reminder.

Model context editing turns under Claude Code

Figure 17. The same model edits its context the same way under Claude Code. Both editing turns come without a reminder. The first folds a finished reproduction phase into one note with the dead ends and the root cause, then drops the superseded scripts and failing runs; the second rewrites spent file reads and edits into one-line records, keeping which fix was replaced and which one is final. Plot and excerpt conventions follow Figure 16.

References

  1. [1]Jean-Baptiste Alayrac, Jeff Donahue, Pauline Luc, Antoine Miech, Iain Barr, Yana Hasson, Karel Lenc, Arthur Mensch, Katherine Millican, Malcolm Reynolds, et al. 2022. Flamingo: a visual language model for few-shot learning. Advances in neural information processing systems, 35:23716–23736.arxiv.org/abs/2204.14198
  2. [2]Anthropic. 2025. Claude code.
  3. [3]Akari Asai, Zeqiu Wu, Yizhong Wang, Avi Sil, and Hannaneh Hajishirzi. 2024. Self-RAG: Learning to retrieve, generate, and critique through self-reflection. In International conference on learning representations, volume 2024, pages 9112–9141.arxiv.org/abs/2310.11511
  4. [4]Chameleon Team. 2024. Chameleon: Mixed-modal early-fusion foundation models. arXiv preprint arXiv:2405.09818.arxiv.org/abs/2405.09818
  5. [5]Xiang Deng, Jeff Da, Edwin Pan, Yannis Yiming He, Charles Ide, Kanak Garg, Niklas Lauffer, Andrew Park, Nitin Pasari, Chetan Rane, et al. 2025. SWE-Bench Pro: Can AI agents solve long-horizon software engineering tasks? arXiv preprint arXiv:2509.16941.arxiv.org/abs/2509.16941
  6. [6]Haiwen Diao, Yufeng Cui, Xiaotong Li, Yueze Wang, Huchuan Lu, and Xinlong Wang. 2024. Unveiling encoder-free vision-language models. Advances in Neural Information Processing Systems, 37:52545–52567.arxiv.org/abs/2406.11832
  7. [7]Chenxu Hu, Jie Fu, Chenzhuang Du, Simian Luo, Junbo Zhao, and Hang Zhao. 2023. ChatDB: Augmenting LLMs with databases as their symbolic memory. arXiv preprint arXiv:2306.03901.arxiv.org/abs/2306.03901
  8. [8]Huiqiang Jiang, Qianhui Wu, Chin-Yew Lin, Yuqing Yang, and Lili Qiu. 2023. LLMLingua: Compressing prompts for accelerated inference of large language models. In Proceedings of the 2023 conference on empirical methods in natural language processing, pages 13358–13376.arxiv.org/abs/2310.05736
  9. [9]Huiqiang Jiang, Qianhui Wu, Xufang Luo, Dongsheng Li, Chin-Yew Lin, Yuqing Yang, and Lili Qiu. 2024. LongLLMLingua: Accelerating and enhancing LLMs in long context scenarios via prompt compression. In Proceedings of the 62nd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 1658–1677.arxiv.org/abs/2310.06839
  10. [10]Carlos E Jimenez, John Yang, Alexander Wettig, Shunyu Yao, Kexin Pei, Ofir Press, and Karthik Narasimhan. 2024. SWE-bench: Can language models resolve real-world GitHub issues? In International Conference on Learning Representations, volume 2024, pages 54107–54157.arxiv.org/abs/2310.06770
  11. [11]Vasilis Kontonis, Yuchen Zeng, Shivam Garg, Lingjiao Chen, Hao Tang, Ziyan Wang, Ahmed Awadallah, Eric Horvitz, John Langford, and Dimitris Papailiopoulos. 2026. Memento: Teaching LLMs to manage their own context. arXiv preprint arXiv:2604.09852.arxiv.org/abs/2604.09852
  12. [12]Patrick Lewis, Ethan Perez, Aleksandra Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich Küttler, Mike Lewis, Wen-tau Yih, Tim Rocktäschel, et al. 2020. Retrieval-augmented generation for knowledge-intensive NLP tasks. Advances in neural information processing systems, 33:9459–9474.arxiv.org/abs/2005.11401
  13. [14]Yucheng Li, Bo Dong, Frank Guerin, and Chenghua Lin. 2023. Compressing context to enhance inference efficiency of large language models. In Proceedings of the 2023 conference on empirical methods in natural language processing, pages 6342–6353.arxiv.org/abs/2310.06201
  14. [15]Tobias Lindenbauer, Igor Slinko, Ludwig Felder, Egor Bogomolov, and Yaroslav Zharov. 2025. The complexity trap: Simple observation masking is as efficient as LLM summarization for agent context management. arXiv preprint arXiv:2508.21433.arxiv.org/abs/2508.21433
  15. [16]Haotian Liu, Chunyuan Li, Qingyang Wu, and Yong Jae Lee. 2023. Visual instruction tuning. Advances in neural information processing systems, 36:34892–34916.
  16. [17]Nelson F Liu, Kevin Lin, John Hewitt, Ashwin Paranjape, Michele Bevilacqua, Fabio Petroni, and Percy Liang. 2024. Lost in the middle: How language models use long contexts. Transactions of the association for computational linguistics, 12:157–173.arxiv.org/abs/2307.03172
  17. [18]Xiaoyuan Liu, Tian Liang, Dongyang Ma, Deyu Zhou, Haitao Mi, Pinjia He, and Yan Wang. 2026. The pensive paradigm: Stateful language models mastering their own context. arXiv preprint arXiv:2602.12108.arxiv.org/abs/2602.12108
  18. [19]Mike Merrill, Alexander Shaw, Nicholas Carlini, Boxuan Li, Harsh Raj, Ivan Bercovich, Lin Shi, Jeong Shin, Thomas Walshe, E Kelly Buchanan, et al. 2026. Terminal-Bench: Benchmarking agents on hard, realistic tasks in command line interfaces. In International Conference on Learning Representations, volume 2026, pages 40903–40986.
  19. [20]OpenAI. 2025. Codex CLI.
  20. [21]Charles Packer, Sarah Wooders, Kevin Lin, Vivian Fang, Shishir G Patil, Ion Stoica, and Joseph E Gonzalez. 2023. MemGPT: Towards LLMs as operating systems. arXiv preprint arXiv:2310.08560.arxiv.org/abs/2310.08560
  21. [22]Zhuoshi Pan, Qianhui Wu, Huiqiang Jiang, Menglin Xia, Xufang Luo, Jue Zhang, Qingwei Lin, Victor Rühle, Yuqing Yang, Chin-Yew Lin, et al. 2024. LLMLingua-2: Data distillation for efficient and faithful task-agnostic prompt compression. In Findings of the Association for Computational Linguistics: ACL 2024, pages 963–981.arxiv.org/abs/2403.12968
  22. [23]Qwen Team. 2026. Qwen3.6-35B-A3B: Agentic coding power, now open to all.
  23. [24]Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, Roberta Raileanu, Maria Lomeli, Eric Hambro, Luke Zettlemoyer, Nicola Cancedda, and Thomas Scialom. 2023. Toolformer: Language models can teach themselves to use tools. Advances in neural information processing systems, 36:68539–68551.arxiv.org/abs/2302.04761
  24. [25]Mustafa Shukor, Enrico Fini, Victor Guilherme Turrisi da Costa, Matthieu Cord, Joshua Susskind, and Alaeddin El-Nouby. 2025. Scaling laws for native multimodal models. In 2025 IEEE/CVF International Conference on Computer Vision (ICCV), pages 12–23. IEEE.arxiv.org/abs/2504.07951
  25. [26]Weiwei Sun, Miao Lu, Zhan Ling, Kang Liu, Xuesong Yao, Yiming Yang, and Jiecao Chen. 2025. Scaling long-horizon LLM agent via context-folding. arXiv preprint arXiv:2510.11967.arxiv.org/abs/2510.11967
  26. [27]Xingyao Wang, Boxuan Li, Yufan Song, Frank F Xu, Xiangru Tang, Mingchen Zhuge, Jiayi Pan, Yueqi Song, Bowen Li, Jaskirat Singh, et al. 2025. OpenHands: An open platform for AI software developers as generalist agents. In International Conference on Learning Representations, volume 2025, pages 65882–65919.arxiv.org/abs/2407.16741
  27. [28]Xinlong Wang, Xiaosong Zhang, Zhengxiong Luo, Quan Sun, Yufeng Cui, Jinsheng Wang, Fan Zhang, Yueze Wang, Zhen Li, Qiying Yu, et al. 2024. Emu3: Next-token prediction is all you need. arXiv preprint arXiv:2409.18869.arxiv.org/abs/2409.18869
  28. [29]Yinjie Wang, Xuyang Chen, Xiaolong Jin, Mengdi Wang, and Ling Yang. 2026. OpenClaw-RL: Train any agent simply by talking. arXiv preprint arXiv:2603.10165.arxiv.org/abs/2603.10165
  29. [30]Tim Z. Xiao, Robert Bamler, Bernhard Schölkopf, and Weiyang Liu. 2025. Verbalized machine learning: Revisiting machine learning with language models. Transactions on Machine Learning Research.arxiv.org/abs/2406.04344
  30. [31]Wujiang Xu, Zujie Liang, Kai Mei, Hang Gao, Juntao Tan, and Yongfeng Zhang. 2026. A-MEM: Agentic memory for LLM agents. Advances in Neural Information Processing Systems, 38:17577–17604.arxiv.org/abs/2502.12110
  31. [32]Sikuan Yan, Xiufeng Yang, Zuchao Huang, Ercong Nie, Zifeng Ding, Zonggen Li, Xiaowen Ma, Jinhe Bi, Kristian Kersting, Jeff Z Pan, et al. 2026. Memory-R1: Enhancing large language model agents to manage and utilize memories via reinforcement learning. In Proceedings of the 64th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 12805–12825.
  32. [33]Chenxiao Yang, Nathan Srebro, David McAllester, and Zhiyuan Li. 2025a. PENCIL: Long thoughts with short memory. arXiv preprint arXiv:2503.14337.arxiv.org/abs/2503.14337
  33. [34]John Yang, Carlos Jimenez, Alexander Wettig, Kilian Lieret, Shunyu Yao, Karthik Narasimhan, and Ofir Press. 2024. SWE-agent: Agent-computer interfaces enable automated software engineering. Advances in Neural Information Processing Systems, 37:50528–50652.arxiv.org/abs/2405.15793
  34. [35]John Yang, Kilian Lieret, Carlos E. Jimenez, Alexander Wettig, Kabir Khandpur, Yanzhe Zhang, Binyuan Hui, Ofir Press, Ludwig Schmidt, and Divij Yang. 2025b. Swe-smith: Scaling data for software engineering agents. Preprint, arXiv:2504.21798.arxiv.org/abs/2504.21798
  35. [36]Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao. 2022. ReAct: Synergizing reasoning and acting in language models. arXiv preprint arXiv:2210.03629.arxiv.org/abs/2210.03629
  36. [37]Rui Ye, Zhongwang Zhang, Kuan Li, Huifeng Yin, Zhengwei Tao, Yida Zhao, Liangcai Su, Liwen Zhang, Zile Qiao, Xinyu Wang, et al. 2025. Agent-Fold: Long-horizon web agents with proactive context management. arXiv preprint arXiv:2510.24699.arxiv.org/abs/2510.24699
  37. [39]Z.ai. 2026. GLM-5.3: Frontier coding with emergent cyber capabilities.
  38. [40]Wen Zan, Jiaqi Zhang, Jianchao Tan, Hong Liu, Cunguang Wang, Xiang Li, Duyue Ma, Guanyu Wu, Yifan Lu, Fengcun Li, Yerui Sun, Peng Pei, Yuchen Xie, and Xunliang Cai. 2026. LongCat sparse attention: Taming the lightning via streaming-aware hierarchical cross-layer indexing. arXiv preprint arXiv:2608.01662.arxiv.org/abs/2608.01662
  39. [41]Yuxiang Zhang, Jiangming Shu, Ye Ma, Xueyuan Lin, Shangxi Wu, and Jitao Sang. 2026. Memory as action: Autonomous context curation for long-horizon agentic tasks. In Findings of the Association for Computational Linguistics: ACL 2026, pages 19149–19164.arxiv.org/abs/2510.12635
  40. [42]Zijian Zhou, Aoqi Ou, Zhaoxuan Wu, Sunghwan Kim, Alok Prakash, Daniela Rus, Bryan Kian Hsiang Low, and Paul Liang. 2026. MEM1: Learning to synergize memory and reasoning for efficient long-horizon agents. In International Conference on Learning Representations, volume 2026, pages 58413–58438.arxiv.org/abs/2506.15841

Paper details

vlnc:W_mwmbdexw
Version
v1 · latest
Published
Added
License
CC BY 4.0
Usage

views · 6

downloads · 0

A view counts once per browser per day, a download each time the PDF is requested.

  • Computer Science

large language models (LLMs)

View statement
Looking for related papers…
Contents