Skip to content

Scaling Long-Horizon LLM Agent via Context-Folding

Skip →Demystifying agent evals
main track #7corefrontierpaperrubric 10/122025 · ~40 min

Weiwei Sun, Miao Lu, Zhan Ling, … Jiecao Chen

Read first: DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models

Status

TL;DR. Two papers from October 2025 use the word “fold” for two different methods. In Context-Folding (ByteDance Seed, CMU, Stanford), the agent opens a branch for a sub-task, does the token-heavy work there, and returns a short message; the branch is then removed from the context. It is trained with RL (FoldGRPO) that adds token-level penalties to the outcome reward. In AgentFold (Tongyi Lab; arXiv 2510.24699), the context is a list of summary blocks plus the latest step, and at every step the agent writes a fold directive that either condenses the latest step or merges a range of earlier blocks into one. It is trained only with supervised fine-tuning. Keep them separate: they differ in what is folded, when, and how the policy is trained.

Why it matters now. ReSum compresses the whole history when a system rule fires. Both folding methods hand that decision to the agent and make compression local: a finished sub-task or a range of steps, not everything. For an IR reader, this is still within-trajectory working context. The returned messages and summary blocks are written by the policy and are not an index; the retrieved documents themselves are gone once folded.

Two different folding methods: Context-Folding's branch and return versus AgentFold's per-step fold directive Left, Context-Folding (arXiv 2510.11967): the main thread holds the question and plan. The agent calls branch with a description and prompt, does token-heavy work such as searches and document reads in the branch, then calls return with a short message. On return the branch's steps are folded away, the KV cache is rolled back to the branch point, and only the message is appended to the main thread. Branches cannot be nested. FoldGRPO trains this with RL. Right, AgentFold (arXiv 2510.24699): at step 8 the context holds the question, the tools, a sequence of summary blocks covering step ranges 1, 2 to 4, 5 and 6, and the full latest interaction from step 7. Each response includes a fold directive with a range starting at k. Granular condensation with k equal to 7 appends a new block for step 7. Deep consolidation with k equal to 5 replaces blocks 5 and 6 and step 7 with one block covering 5 to 7. AgentFold is trained by supervised fine-tuning on filtered trajectories. One word, two methods: fold a sub-task, or fold history at any scale Context-Folding: branch / return question + plan branch(desc, prompt) + message only next branch … answer branch search, read many tokens … return(message) on return: branch steps folded away, KV cache rolled back to the branch point no nested branches; at most 10 per task trained with RL: FoldGRPO AgentFold: a fold directive every step context at step 8 = (Q, T, S, I) S: summary blocks (step ranges) 1 2–4 5 6 I: full latest interaction (step 7) fold directive: range [k, 7] + summary granular condensation, k = 7: append block 7 1 2–4 5 6 7 deep consolidation, k = 5: merge 5–7 1 2–4 5–7 trained by SFT on filtered data (no RL)
Original sketch. Left: Context-Folding replaces a finished branch with its return message. Right: AgentFold's fold directive either appends a block for the latest step or merges a range of blocks.

Context-Folding: branch and return (arXiv 2510.11967)

Section titled “Context-Folding: branch and return (arXiv 2510.11967)”

Problem. A ReAct agent appends every action and observation, so long tasks hit the context limit. Summary agents rewrite the history at arbitrary points.

Mechanism. Two extra tools.

  • branch(description, prompt) starts a sub-trajectory for a sub-task. Branches cannot be nested.
  • return(message) ends it. The steps inside the branch are folded: removed from the context, with only the message appended to the main thread.

At inference the KV cache is rolled back to the branch point, so the prefix before the branch is reused as is. The paper uses a plan–execution setup: in the main thread (planning) the agent should avoid token-heavy actions, and it does them in branches (execution). Formally the policy conditions on the folded history F(τ1:i−1)\mathcal{F}(\tau_{1:i-1}) rather than on the full trajectory:

pθ(τ∣q)=∏iπθ(ai∣q,F(τ1:i−1)).p_\theta(\tau \mid q) = \prod_i \pi_\theta\big(a_i \mid q, \mathcal{F}(\tau_{1:i-1})\big).

FoldGRPO. GRPO with token-level process rewards Qi,t≤0Q_{i,t} \le 0 added to the binary outcome reward RiR_i of rollout ii, clipped to [0,1][0, 1], and normalized by the group’s outcome rewards. Tool-observation tokens are masked from the loss.

A^i,t=clip⁡(Ri+Qi,t, 0, 1)−mean⁡({Rj}j=1G)std⁡({Rj}j=1G)\hat{A}_{i,t} = \frac{\operatorname{clip}(R_i + Q_{i,t},\, 0,\, 1) - \operatorname{mean}(\{R_j\}_{j=1}^{G})}{\operatorname{std}(\{R_j\}_{j=1}^{G})}
  • Unfolded-token penalty. Q=−1Q = -1 on all main-thread tokens once the main thread exceeds 50% of the working context limit, except the turns that create a branch.
  • Out-of-scope penalty. Q=−0.2Q = -0.2 on all tokens of a branch that GPT-5-nano judges, from the branch prompt and returned message, to have gone beyond its sub-task.
  • Failure penalty. Q=−1Q = -1 on tokens of a failed tool-call turn.

The authors added these because with the outcome reward alone the agent did token-heavy work in the main thread and drifted inside branches. Note that with Ri=0R_i = 0 the clip makes every token’s value 0, so the penalties only change credit inside successful rollouts.

Worked trace (illustrative). The question asks for a paper that meets three constraints. Main thread: plan. Branch 1 (“find candidates for constraint A”): eight searches and four page reads, about 30k tokens, returns “candidates X and Y, from pages p1, p2”. Branch 2 (“check B and C for X and Y”): returns “Y satisfies both; X fails C”. The main thread now holds the plan and two short messages, a few thousand tokens, and answers Y.

AgentFold: a fold directive at every step (arXiv 2510.24699)

Section titled “AgentFold: a fold directive at every step (arXiv 2510.24699)”

Context. At step tt the agent sees

Ct=(Q, T, St−2, It−1),C_t = (Q,\ T,\ S_{t-2},\ I_{t-1}),

the question QQ, tool descriptions TT, an ordered list of multi-scale state summaries St−2S_{t-2} (each block sx,ys_{x,y} summarizes the contiguous steps xx to yy, and the blocks partition steps 1 to t−2t-2), and the full latest interaction It−1I_{t-1}.

Response. Each response has thinking, a folding directive, an explanation, and an action (tool call or answer). The directive is a JSON object {"range": [k, t-1], "summary": σ}:

  • Granular condensation (k=t−1k = t-1): the latest interaction becomes a new block, e.g. “[Compressed Step 5] Found a new candidate…”.
  • Deep consolidation (k<t−1k \lt t-1): the latest interaction and the blocks covering steps kk to t−2t-2 are removed and replaced by one coarser block, e.g. after a dead-end sub-investigation.

Why not summarize everything each step? The paper’s argument: if each full re-summary loses a given detail with probability 1%, it survives 100 steps with probability 0.99100≈36.6%0.99^{100} \approx 36.6\% and 500 steps with 0.99500≈0.66%0.99^{500} \approx 0.66\%. AgentFold leaves earlier blocks untouched unless a consolidation covers them.

Training. A “Fold-Generator” pipeline uses open-source LLMs on the WebSailor question set to produce trajectories in this format; rejection sampling discards steps that break the format and trajectories with too many environment errors. The policy, AgentFold-30B-A3B, is Qwen3-30B-A3B-Instruct-2507 trained by SFT only. RL is named as the next step. Code: Alibaba-NLP/DeepResearch.

ReSumContext-FoldingAgentFold
What is compressedWhole historyA finished branchLatest step, or a range of blocks
WhenSystem trigger near the limitWhen the agent calls returnEvery step
Who decidesRuleAgentAgent
TrainingReSum-GRPOFoldGRPO (RL with process rewards)SFT only
What did not changeSearch tools, binary outcome judge, no raw log kept
EvidenceReSum Tables 1–3Tables 1–2 (below)Table 1 and context analysis (below)

Setup: Seed-OSS-36B-Instruct, trained with VeRL (batch 32, group 8, learning rate 1e-6, no KL, clip 0.2 / 0.28, 50 steps). The folding agent has a 32,768-token context and up to 10 branches (327,680 tokens in theory). BrowseComp-Plus is split into 680 training and 150 evaluation questions (with Qwen3-Embed-8B as retriever and the official LLM judge), so its numbers are not comparable to the full-set BrowseComp-Plus leaderboard. SWE-Bench Verified uses all 500 instances, with 740 training instances from SWE-Gym and SWE-Rebench.

Table 1, pass@1 (BrowseComp-Plus / SWE-Bench Verified), Seed-OSS-36B unless stated:

AgentContextBase+ GRPO+ FoldGRPO
ReAct32K0.286 / 0.4360.446 / 0.480–
ReAct327K0.478 / 0.5520.540 / 0.574–
Summary32K × 100.386 / 0.4880.527 / 0.550–
Folding32K × 100.420 / 0.4920.567 / 0.5640.620 / 0.580
GPT-5 ReAct327K0.793 / 0.718––
  • RL lifts the folding agent from 0.420 to 0.620 on BrowseComp-Plus and from 0.492 to 0.580 on SWE-Bench Verified.
  • Discrepancy. The text says FoldGRPO beats plain GRPO by “+7.7% on BrowseComp”; Table 1 gives 0.567 → 0.620, 5.3 points. The SWE gain (+1.6) matches the table.
  • Table 2 (BrowseComp-Plus; Finish / main-thread length / Scope / branches): untrained 0.806 / 12,195 / 0.774 / 3.51; GRPO 0.738 / 22,285 / 0.762 / 3.88; FoldGRPO 0.935 / 7,752 / 0.895 / 4.98. On SWE-Bench, FoldGRPO cuts the main thread from 47,475 to 8,885 tokens.
  • The trained agent keeps its main thread at about 8K tokens while processing over 100K in total. Gains come with more tool calls (BrowseComp-Plus: 12.9 → 19.2 per question).
  • In one case study, 4 branches compress a 107K-token context to 6K.

Setup: up to 100 tool calls; longer runs are stopped. Benchmarks with fewer than 200 questions are averaged over 3 runs. Several baseline numbers are taken from their papers or leaderboards, so tools and budgets differ.

ModelBrowseCompBrowseComp-ZHWideSearch-en (Item-F1)GAIA (text)
AgentFold-30B-A3B36.247.362.167.0
DeepSeek-V3.1-671B30.049.2–63.1
GLM-4.5-355B26.437.5–66.0
WebSailor-72B12.030.1–55.4
OpenAI o349.758.160.070.5
Claude-4-Sonnet14.722.562.068.3
  • Context size (200 BrowseComp trajectories): the context grows from about 3.5k to 7k tokens over 100 turns. At turn 100 it is over 84k tokens (92%) smaller than a ReAct context, which the authors estimate saves about 7 GB of memory.
  • Over 20% of tasks reach the 100-turn limit while using only about 7k of a 128k window.
  • Turn scaling. With budgets up to 256 turns, AgentFold keeps improving; GLM-4.5 saturates and fails beyond 64. In a 500-turn run the context mostly stays under 20k and is not monotonic, because consolidating dead ends shrinks it.
  • Different papers, different evidence. Context-Folding reports a controlled comparison (same base model, data and RL budget) on a 150-question BrowseComp-Plus split. AgentFold reports a leaderboard-style table with mixed sources. Neither compares against the other.
  • Text vs table. Context-Folding’s “+7.7%” FoldGRPO gain does not match its own Table 1 (5.3 points).
  • Judge in the loop. The out-of-scope penalty and the Scope metric both use GPT-5-nano; Scope accuracy is not an independent check.
  • No reward for folding in AgentFold. It imitates filtered trajectories; whether RL improves its folding decisions is open.
  • Irreversible loss in both. A wrong return message or deep consolidation removes evidence for good. Keeping document ids in messages and blocks, plus a tool to re-open them, is an obvious untested fix.
  • Interleaved, not parallel. Context-Folding’s branches run one at a time; a parallel-branching variant scored 0.6133 on BrowseComp-Plus, similar to the single-branch agent, while reading more pages (about 110 vs 80). Whether parallel branches help is left open.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    FoldGRPO computes each token's advantage as clip(R + Q, 0, 1) minus the group mean of R, divided by the group standard deviation of R, with binary outcome reward R. In a group of 8 rollouts, 4 are correct. Compute the advantage of (a) an ordinary token in a correct rollout, (b) a main-thread token in a correct rollout after the main thread passed 50% of the context limit, (c) a token in an out-of-scope branch of a correct rollout, (d) a failed-tool-call token in an incorrect rollout, and (e) an ordinary token in an incorrect rollout. What does the result say about when the process penalties actually change the gradient?

    What a strong answer covers
    • Group mean of R is 0.5 and the standard deviation is 0.5, so the advantage is (clip(R + Q, 0, 1) − 0.5) / 0.5.
    • (a) clip(1) = 1, advantage +1. (b) clip(1 − 1) = 0, advantage −1. (c) clip(1 − 0.2) = 0.8, advantage +0.6.
    • (d) clip(0 − 1, 0, 1) = 0, advantage −1. (e) clip(0) = 0, advantage −1, the same as (d).
    • Because of the clip at 0, penalties have no extra effect in failed rollouts; they only lower the credit of tokens inside successful rollouts.
    • So FoldGRPO shapes how a correct answer was reached (keep the main thread short, stay on scope, avoid failed calls) rather than punishing failures harder.
  2. Mechanism

    Explain what happens to the context and to the KV cache when a Context-Folding agent calls branch and then return, and why the paper adds an unfolded-token penalty and an out-of-scope penalty instead of training with the outcome reward alone.

    What a strong answer covers
    • branch(description, prompt) starts a sub-trajectory for one sub-task in the same context; branches cannot be nested.
    • return(message) folds the branch: its intermediate steps are removed and only the short message is added to the main thread.
    • At inference the KV cache is rolled back to the branch point, so the prefix is reused and nothing is recomputed.
    • With outcome reward only, the agent tended to do token-heavy work in the main thread (filling the context) and to drift or not return from branches.
    • The unfolded-token penalty (−1 once the main thread exceeds half the limit, except branch-creating turns) pushes heavy work into branches; the out-of-scope penalty (−0.2, judged by GPT-5-nano from the branch prompt and returned message) keeps branches on their sub-task.
  3. What if…

    Table 2 of the Context-Folding paper compares the untrained folding agent, the same agent trained with plain GRPO, and with FoldGRPO, on Finish rate, main-thread length, Scope accuracy and number of branches. Read the BrowseComp-Plus row values and explain what plain GRPO learned that FoldGRPO prevents. Which of these statistics are measured by an LLM judge rather than directly?

    What a strong answer covers
    • Untrained: Finish 0.806, main length 12,195, Scope 0.774, 3.51 branches. GRPO: 0.738, 22,285, 0.762, 3.88. FoldGRPO: 0.935, 7,752, 0.895, 4.98.
    • Plain GRPO raises accuracy but nearly doubles the main-thread length and lowers the finish rate: it learned to do more work without folding it, so more runs hit the context limit.
    • FoldGRPO shortens the main thread, raises the finish rate and creates more, better-scoped branches.
    • Scope accuracy depends on the GPT-5-nano judge that also produces the training penalty, so it is not an independent measurement.
    • The accuracy difference between GRPO and FoldGRPO is 0.567 vs 0.620 on BrowseComp-Plus, a 5.3-point gain, although the text says +7.7%.
  4. Critique

    AgentFold argues that summarizing the full history at every step loses information: if each re-summary drops a given detail with probability 0.01, the detail survives 100 steps with probability about 0.366 and 500 steps with about 0.0066. Check the arithmetic, then critique the argument and the paper's evidence: what does AgentFold's own design still risk, and which parts of its headline comparison are not controlled?

    What a strong answer covers
    • 0.99 to the power 100 is about 0.366 and to the power 500 is about 0.0066; the argument assumes independent, equal loss at every rewrite.
    • AgentFold reduces repeated rewriting of the same detail, because granular blocks stay untouched until a deep consolidation covers them; but a single wrong consolidation can still erase a clue for good, and there is no raw log to re-read.
    • The policy is trained only by SFT on trajectories filtered by format and error checks; there is no reward for folding well, and RL is left for future work.
    • Several baselines in Table 1 are taken from papers or leaderboards, so tools, budgets and judges are not matched; BrowseComp scores of different systems are not a controlled comparison.
    • Over 20% of BrowseComp tasks hit the 100-turn limit, so the reported score also depends on the turn cap.
  5. Design

    You want to compare ReSum, Context-Folding and AgentFold fairly on BrowseComp-Plus. Design the experiment: what must be held fixed, what to measure besides accuracy, and how to tell whether a wrong answer came from retrieval or from folding.

    What a strong answer covers
    • Hold fixed: the same base model, retriever and corpus, the same search and open_page tools, the same turn or tool-call budget, the same judge, and the same evaluation questions (not the 150-question split for one and the full set for others).
    • Train each with comparable data and compute, or report all three both untrained and trained, since Context-Folding uses RL and AgentFold uses SFT.
    • Measure: accuracy, total and peak context tokens, number of tool calls, finish rate within budget, and evidence recall from the BrowseComp-Plus relevance labels.
    • Attribution: if a gold document was opened but its key fact is missing from every summary, block or returned message at answer time, the error is a folding loss; if no gold document was ever retrieved, it is a retrieval failure.
    • Report per-question paired differences with confidence intervals, because the evaluation sets are small.
  6. Connect

    Context-Folding's branch and return look like a parent agent calling a sub-agent, and the paper says so. Compare it with a multi-agent orchestrator and with a recursive language model that calls itself on parts of a long input. What is shared, what is different, and what does each give up?

    What a strong answer covers
    • Shared: work happens in a separate context and only a short result comes back, which keeps the caller's context small.
    • Context-Folding: one policy, sub-tasks created on the fly, a shared context prefix (so the KV cache can be reused), and branch and main thread take turns instead of running in parallel.
    • Multi-agent orchestrators usually have predefined sub-agent roles, separate contexts and can run in parallel, at the cost of no shared cache and more coordination.
    • Recursive language models put the long input in an environment and let the model call itself on chunks, so the recursion is over the input; Context-Folding's branches are over sub-tasks in the trajectory.
    • All three lose whatever the returned message or result leaves out; none keeps a retrievable log by default.

Done with this page?

Status