Manuscript Offprint
arXiv:2611.00244MEMENTO: Learning Context Management for Long Context Processing Agents
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Abstract
LLM agents that operate over long inputs must perform context management: deciding what to retain in a fixed-size context window. A common approach is compaction, where the model replaces its history with a self-generated note. Yet off-the-shelf agentic models, including GPT-5.5 and GLM-5.3, often write ineffective notes, and reinforcement learning (RL) alone rarely discovers useful note-taking behavior. We present MEMENTO, a long-context agent built on Qwen3-8B and trained to manage its context through compaction. We first bootstrap note-taking by fine-tuning on synthetic trajectories annotated with notes generated in hindsight, then reinforce it with RL using a reward that combines answer correctness, note-quality heuristics, and confidence calibration. Although trained only to compact into a fresh window, MEMENTO extends at test time to strategies such as context folding and confidence-based backtracking. On book-level question answering across four benchmarks, with books of up to 2.5M tokens, MEMENTO raises Qwen3-8B's accuracy from 36.9% to 67.8% while never holding more than 20K tokens in context. It outperforms GPT-5.5 agent in the same harness (13.1%) and full book context (56.7%) at less than 1/50 the cost. It also nearly matches a ~100× larger GLM-5.3 agent (69.3%) at 1/9 the cost, and comes within 6.4 points of GLM-5.3 full context at 1/26 the cost.
1 Introduction
Large language model (LLM) agents are taking on ever longer tasks, and the horizon over which they can work autonomously has grown steadily (Kwa et al., 2025). This makes agents a natural fit for long-context processing: rather than ingesting an entire book or knowledge base at once, an agent can search the input and read only the parts it needs. Most agents, however, follow the ReAct paradigm (Yao et al., 2023b), appending every thought, action, and observation to their context.

Figure 1: Context management methods incorporated in this work. (a) Compaction starts a new window containing only the saved notes and discards all prior turns. (b) Context folding additionally retains the turns after the latest note. (c) Confidence-based backtracking resumes from an earlier note checkpoint after a low-confidence answer and generates an alternative continuation.
Because the history grows with the task while the context window stays fixed, a sufficiently long task will eventually exhaust the window. Larger context windows only postpone the problem: LLMs underuse information in long inputs (Liu et al., 2024), and their performance can degrade as the context grows (Du et al., 2025). Deciding what an agent should retain, which we call context management, is therefore central to agentic long-context processing.
Prior approaches either prompt the model to manage its own memory or delegate summarization to a separate component (Packer et al., 2023; Wu et al., 2025). Another line of work learns context management through reinforcement learning or supervised fine-tuning (Zhou et al., 2026; Yu et al.,
2026; Sun et al., 2026; Ye et al., 2026).
In this work, we jointly design the training pipeline and the test-time harness for context management in agentic long-context processing. We take book-level multi-hop question answering (Book QA) as our target task, since answering a single question often requires gathering evidence scattered across an entire book. Alongside standard search and view tools, the agent has a compaction note tool that it may call at any point to summarize its progress, record mistakes, and plan next steps. Notes persist through every context management operation we consider (Figure 1) and double as checkpoints for backtracking.
We present MEMENTO, a long-context processing agent built on Qwen3-8B (Qwen Team, 2025). Off-the-shelf LLMs, including stronger models such as GPT-5.5 and GLM-5.3, never make valid calls to our compaction note tool to record progress or plan ahead, even when explicitly introduced in their system prompt, leaving RL with little useful note-taking behavior to reinforce. We therefore shape the initial policy with synthetic SFT data. We inject compaction notes post hoc into correct GLM-5.3 (Z.ai, 2026) agent rollouts and fine-tune on the resulting synthetic trajectories. We further train the SFT-initialized policy with RL, using a reward that combines format compliance, heuristics on note quality, final-answer correctness, and, optionally, the calibration of a verbalized confidence score.
Throughout training, the agent uses only the simplest operation, compaction into a new window (Figure 1a), carrying its notes across multiple windows within a single rollout. Because context folding (b) and confidence-based backtracking (c) operate on the same notes and prompts, we can adopt them at test time with minimal train-test mismatch, and choose among these methods according to the accuracy and budget of a given deployment.
We train and evaluate MEMENTO on LiteraryQA (Bonomo et al., 2025), NovelHopQA (Gupta et al., 2025), and the English subset of SagaScale (Du et al., 2026), and additionally evaluate on NovelQA (Wang et al., 2025), which is held out from training. On 4.7K test questions, with accuracy micro-averaged over the four datasets, our full system reaches 67.8%. This greatly improves the 36.9% of the original Qwen3-8B agent and nearly matches the 69.3% of a larger GLM-5.3 agent, with all agents run in the same harness using context folding and confidence-based backtracking. The conventional long-context approach, placing the entire book in GLM-5.3's context window, yields 74.3%, 6.4 points higher, but at more than the inference cost (in USD). MEMENTO also outperforms GPT-5.5, which reaches only 13.1% in our harness and 56.7% even with the full book in its context window, at our cost. These results suggest that a small open model agent can process long-context inputs effectively when context management is learned jointly with the task and the harness.
Our contributions are as follows:
• SFT and RL for learned context management. We bootstrap note-taking with SFT on agentic rollouts augmented with synthetic compaction notes, then refine it with RL under a hybrid reward that incorporates process signals on note quality with outcome rewards on answer correctness. Together, they improve the Qwen3-8B agent from 36.9% to 66.3%.
• Confidence-guided backtracking. We reward calibrated verbalized confidence during RL and use it at test time to backtrack over saved notes and retry low-confidence answers, raising accuracy further to 67.8%.
• Co-designed training and test-time harness. The agent can call the compaction note tool at any point in its trajectory, so the same note structure allows several test-time strategies: compaction into a new window, context folding, and backtracking to earlier notes. Although the agent is trained only with compaction into a new window, it transfers to folding and backtracking with minimal train–test mismatch, so the harness can be chosen to fit a deployment's cost–accuracy trade-off.
Context management and compaction for agents. Context management approaches that can be applied without updating the agent's policy parameters include hierarchical memory paging (Packer et al., 2023) and ReSum's inference-time use of a separate summarization tool (Wu et al., 2025). Complementary work on long-term conversational memory includes MemGuard (Ha et al., 2026), which separates memories by functional type and selectively retrieves them to reduce memory contamination. Other approaches train compaction with RL, either as a compact internal state updated at every turn (Zhou et al., 2026), a fixed-length memory overwritten while reading a document segment by segment (Yu et al., 2026), or summaries and folded sub-trajectories optimized end to end with the policy (Lu et al., 2026; Sun et al., 2026). AgentFold (Ye et al., 2026) learns multi-scale folding operations through supervised fine-tuning alone. FoldAct (Shao et al., 2025) also initializes with SFT on summary-augmented trajectories before RL, focusing on joint optimization of summaries and actions. Our pipeline inserts compaction notes into teacher trajectories in hindsight, then refines the initialized policy with RL.
Confidence and test-time search. Spending more computation at inference can improve accuracy, through majority voting over sampled reasoning paths (Wang et al., 2023), tree search with lookahead and backtracking (Yao et al., 2023a), or retries guided by verbal self-reflection (Shinn et al., 2023). However, deciding when to spend this computation requires a signal of reliability. Verbalized confidence from RLHF-tuned models is often better calibrated than their token probabilities (Tian et al., 2023), and RLCR (Damani et al., 2026) augments a binary correctness reward with a negative Brier-score term, improving calibration while maintaining comparable accuracy. We follow the same Brier-style form, and use confidence to decide when a long-horizon agent should backtrack to an earlier note checkpoint and investigate again.
3 Methodology
We jointly design the training pipeline and the test-time harness of MEMENTO around the compaction note tool (Figure 2). We first shape the initial policy with SFT on agent traces augmented with synthetic compaction notes, which demonstrates effective note-taking strategies to the model. We then re-inforce these strategies with RL using a hybrid reward that involves format compliance, note validity, final-answer correctness, and, optionally, the calibration of a verbalized confidence score, under the compact to new context strategy. At test time, the same notes support compaction, context folding, and confidence-based backtracking.
3.1 Task and datasets
Given a book and a question about it, the agent must answer in a few words, reading the book only through search tools within a small context window. Books in our datasets are long: 90% exceed 51K Qwen3 tokens, 70% exceed 90K, and the longest reaches 2.5M. This is far beyond the 16–20K context windows of the models we train, so a Book QA agent must carry its progress across many context windows. Unlike traditional multi-hop QA, where the supporting evidence amounts to a few paragraphs or articles (Yang et al., 2018; Ho et al., 2020; Trivedi et al., 2022), Book QA requires evidence scattered across an entire book. Unlike agentic web QA (Mialon et al., 2024; Wei et al., 2025), it also requires no paid search APIs, whose cost would make RL training infeasible within our budget.
We train and evaluate on LiteraryQA (Bonomo et al., 2025), NovelHopQA (Gupta et al., 2025), and the English subset of SagaScale (Du et al., 2026), and additionally evaluate on NovelQA (Wang et al., 2025), which is held out from training. Over 30% of the books in NovelQA are not publicly released, so they are unlikely to have been memorized during pretraining. We split each training dataset 8:1:1 into training, validation, and test sets, with no book or question shared across splits. This yields 17K training questions over 600 books, 2.3K validation questions over 70 books, and 4.7K test questions over 160 books. All answers are free-form and are graded by an LLM judge against a ground truth of a few words or a short sentence, using SimpleQA prompt (reproduced in C.2).
3.2 Tools for long-context processing
The book is never prefilled in the context window; the agent accesses it only through three tools. semantic_search queries the book in natural language using bge-small-en-v1.5 embed-

Figure 2: Method overview. (a) We inject note-taking actions into collected demonstrations. (b) SFT initializes the policy, and GRPO reinforces its actions across context resets with a shared trajectory advantage. (c) At inference, context folding retains notes and recent turns, and confidence guides retries and answer selection.
dings (Xiao et al., 2024) over sliding-window sections of 128–256 tokens, and ripgrep_search matches exact keywords and regular expressions. Both return a requested number or page of results with line references, and the agent may then call view to read the full text of any line range.
3.3 Compaction note tool
Central to our approach, the agent can call the compaction note tool (create_notes) at any point to record its findings, mistakes, and next steps. Writing a note does not reset the context, so the agent decides what to preserve as the trajectory unfolds and may write several notes along the way. The tool keeps a set number of recent notes, each subject to a length limit (Table 5).
We consider the notes in a rollout valid only if they satisfy three heuristics:
-
Frequency. Every nonfinal context window contains at least one note, so that progress is recorded before each reset, and the rollout contains fewer than five notes in total, to discourage excessive note-taking.
-
Placement. No note is the first tool call of its window or immediately follows another create_notes call, so that each note covers new work.
-
Diversity. No two notes have a token set similarity above 80%, so that the notes cover different parts of the trajectory.
During RL training, the note validity reward is assigned only if every note in the trajectory is valid. At test time, after each context management operation, the agent is shown all saved notes, subject to
retention and length limits, to maximize the reuse of recorded information.
3.4 SFT policy initialization
Neither Qwen3-8B nor stronger models (GPT-5.5, GLM-5.3) reliably write valid notes in our harness, even when the note tool is described in the system prompt. GPT-5.5 never wrote a compaction note on the 337-sample test set, and none of 12K pilot GLM-5.3 rollouts on the training set contained a valid note. Qwen3-8B, in contrast, tends to write identical notes back to back without intervening tool calls, so only about 6% of its trajectories contain valid notes.
We therefore initialize the policy with synthetic SFT data from GLM-5.3 (Z.ai, 2026), a leading open agentic model that exposes its raw chain of thought (Artificial Analysis, 2026). We run GLM-5.3 in our harness with compaction into a new context window, as in training, and retain correct trajectories, prioritizing those spanning multiple windows, plus a small number of failed attempts that appropriately expressed low confidence. We then strip any original notes and prompt GLM-5.3 to insert notes post hoc after major tool-use turns or discoveries, instructing it to summarize key findings, mistakes to avoid, and next steps. Notes failing the heuristics in Section 3.3 are resampled; search actions and final answers are left unchanged.
Finally, we fine-tune Qwen3-8B on the resulting ~6K trajectories. As Section 4.2.1 shows, SFT is not meant to improve accuracy on its own. Instead, it instills a note-taking strategy that teaches the model when to take notes; RL then reinforces this strategy, yielding higher accuracy.
3.5 Reinforcement learning
Reward Models. We use Qwen3-14B as the judge during training and Qwen3-235B-A22B-Instruct-2507 for evaluation. We intentionally evaluate with a different judge so that reported accuracy is not inflated by any exploitation of the training judge. In early experiments, we observed frequent reward hacking against the LLM judge during RL training. Therefore, to detect reward hacking, we first screen each answer for hedging, ambiguity, special tokens, and excessive length, using heuristics and a separate LLM judge call. Answers that pass the screen are graded by a correctness judge using the SimpleQA prompt (Wei et al., 2024) with CoT (Appendix C).
Trajectory-level reward. We combine four rewards: format, note validity, correctness, and calibration. The format indicator is 1 if the final answer and verbalized confidence are parsable and no reward hacking is detected. It earns a bonus and gates all other rewards. marks valid note-taking, marks a correct final answer, and is the value of the verbalized confidence tier. Following Damani et al. (2026), we reward calibration with a negated Brier score, giving the total reward
Advantage calculation across context windows. We use GRPO (Shao et al., 2024) to compare trajectories sampled for the same question. For a question , we sample a group of trajectories with rewards and assign each trajectory a single advantage
Let denote the assistant tokens of across all of its context windows, where token is generated from its window context , and define the importance ratio
We maximize
where the expectation is over questions and groups , is the clipping range, is the per-token KL divergence from to the SFT initialization at context , and weights this penalty. Because every assistant token inherits its trajectory's advantage, note-taking actions in earlier windows receive a learning signal from the trajectory's final outcome.
3.6 Test-time context management
As illustrated in Figure 1, all three context management methods, compacting into a new window, context folding, confidence-based backtracking share the same note-taking, prompts, and context layout, in which the task and saved notes always form the prefix of the context window; they differ only in what follows this prefix. A policy trained only with compaction therefore sees a familiar context under each method, which keeps the train-test mismatch minimal.
Compaction into a new window. When the agent reaches the context budget or requests a restart, the conversation history is replaced with a new context window containing only the original task, the tool instructions, and the saved notes. Anything the agent has not yet recorded is lost. This is also the only mode we used to perform RL training of agents.
Context folding. Context folding replaces the conversation up to and including the latest note-taking turn with the task and saved notes, while preserving subsequent tool calls, tool outputs, and CoTs verbatim. The agent thus retains recent work it has not yet summarized, which improves accuracy and token efficiency.
Confidence-based backtracking. Each note-taking turn marks a state from which the agent can resume. When an answer's confidence is at or below a threshold, the agent discards its later work and generates an alternative continuation: if the attempt contains notes, the first retry attempt resumes right after note . The second retry starts right after the first note. Further attempts restart from scratch. Backtracking stops once an answer exceeds the confidence threshold; otherwise, we return the highest-confidence answer. Table 5 gives the thresholds and retry schedule. A sample agent trajectory is provided in Appendix B.
| Model | Category | Harness | Accuracy (%) | Efficiency | |||||
|---|---|---|---|---|---|---|---|---|---|
| LitQA(n = 1,940) | NHopQA(426) | NovelQA(2,305) | Saga(37) | Micro Avg(4,708) | Tokens | Cost ($) | |||
| Off-the-shelf models, full book in context | |||||||||
| Qwen3-8B (40K ctx) | Reference | Full Context | 44.8 | 20.4 | 29.8 | 2.7 | 34.9 | 33K | 11 |
| GPT-5.5 High (232K ctx)† | Reference | Full Context | 51.0 | 54.0 | 67.0 | 51.4 | 56.7 | 144K | 2,577 |
| GLM-5.3 High (1M ctx) | Reference | Full Context | 76.6 | 75.8 | 71.9 | 75.7 | 74.3 | 167K | 1,270 |
| Off-the-shelf models, context folding agent with confidence-based backtracking | |||||||||
| Qwen3-8B | Ablation | Fold + Backtrack | 35.2 | 29.1 | 39.8 | 37.8 | 36.9 | 15K | 37 |
| GPT-5.5 High† | Reference | Fold + Backtrack | 10.0 | 9.0 | 19.2 | 16.2 | 13.1 | 84K | 2,606 |
| GLM-5.3 High | Reference | Fold + Backtrack | 71.2 | 43.4 | 72.1 | 91.9 | 69.3 | 47K | 448 |
| Trained Qwen3-8B, single-window agent (no context folding or backtracking) | |||||||||
| RL | Ablation | Single Window | 56.0 | 52.1 | 54.6 | 59.5 | 55.0 | 10K | 15 |
| Trained Qwen3-8B, context folding agent only | |||||||||
| SFT | Ablation | Fold | 40.4 | 34.3 | 45.3 | 51.4 | 42.4 | 31K | 58 |
| RL | Ablation | Fold | 59.2 | 51.9 | 57.0 | 59.5 | 57.5 | 12K | 23 |
| SFT + RL | Ablation | Fold | 69.0 | 67.8 | 63.6 | 67.6 | 66.3 | 14K | 29 |
| Trained Qwen3-8B, context folding agent with confidence-based backtracking | |||||||||
| SFT | Ablation | Fold + Backtrack | 59.1 | 57.5 | 59.3 | 64.9 | 59.1 | 73K | 136 |
| MEMENTO (SFT + RL) | Proposed | Fold + Backtrack | 70.2 | 72.8 | 64.9 | 70.3 | 67.8 | 23K | 48 |
Table 1: Test accuracy (%) on LiteraryQA (LitQA), NovelHopQA (NHopQA), NovelQA, and SagaScale (Saga); is the number of test questions. Tokens are the mean per rollout, and cost is for the full test set. Bold marks the best result among ablation and proposed methods. MEMENTO is best on every dataset. In the same harness, it nearly matches GLM-5.3 (67.8 vs. 69.3 micro) at 1/9 the cost. It beats GPT-5.5 High in both settings, including full-book context (67.8 vs. 56.7), at ~1/54 the cost. It is also within 6.5 points of full-context GLM-5.3 at ~1/26 the cost. †Evaluated on up to 100 random questions per dataset; cost is extrapolated to the full test set.
4 Results and Ablations
We report accuracy on the 4.7K held-out test questions, micro-averaged over the four datasets unless stated otherwise. Cost is the evaluation cost in USD of running all test rollouts once on an 8×NVIDIA B200 server at an fair market rate of $64/hr, except for GPT-5.5, for which we report API cost.
4.1 Comparison with State-of-the-Art Agentic Models
Table 1 shows that an 8B model trained for agentic Book QA can compete with state-of-the-art (SOTA) models that are far larger and more expensive to run.
Nearly matching a ~100× larger SOTA agentic model in the same harness. Using the same context folding and confidence-based backtracking harness, Table 1 shows that MEMENTO reaches an accuracy of 67.8% across the four datasets, compared to 69.3% for the 753B GLM-5.3, at less than 1/9 the cost and with half the tokens per rollout. While GLM-5.3 leads on LiteraryQA, NovelQA, and the SagaScale subset, MEMENTO leads on NovelHopQA by 29.3 points. MEMENTO is also the more consistent system, ranging from 64.9% to 72.8% across datasets, compared with 43.4% to 91.9% for GLM-5.3.
Exceeding GPT-5.5 High on agentic Book QA. In our agent harness, GPT-5.5 reaches an accuracy of only 13.1%. Two failures account for this: First, GPT-5.5 produces an answer in the required parsable format in only 21.4% of rollouts. Second, it never calls the note tool, so each fold leaves it with nothing carried forward. Even after correcting for output format, it scores only 57.1%, 10.7 points below MEMENTO. The strongest proprietary model we tested cannot use a note-based harness that an 8B model can learn through SFT and RL.
Approaching full-context performance at a fraction of the cost. As seen in Table 1, the most accurate system remains GLM-5.3 with the entire book in its 1M-token context, at 74.3%. MEMENTO comes within 6.4 points of this result at around 1/26 of the cost and around 7× fewer tokens per question. MEMENTO also outperforms GPT-5.5 with the full book in its 232K context window, as GPT-5.5 reaches 56.7% in this setting, 11.2 points below MEMENTO, at around 54 times the cost. MEMENTO never holds more than a 20K-token window, yet it answers questions about books that run to millions of tokens. For comparison, Qwen3-8B with the book truncated to a 40K window only scores 34.9%.
Training must be co-designed with the test-time harness. These comparisons show that a capable model and a well-designed harness are not enough on their own. Both GPT-5.5 and GLM-5.3 have the context folding and backtracking mechanism available to them with the test-time agent harness, but not the note-taking behavior that makes it useful. In our evaluation, GPT-5.5 never writes a note, and only 1.2% of GLM-5.3's attempts that triggered context folding satisfy our note validity criteria. These results suggest that training with the same note tool, prompts, and context layout used at test time helps MEMENTO use the harness effectively. Therefore, this experiment is a sign that context management is a behavior that should be learned together with the harness and the task, not one that is achieved through prompting or emerges from scale. Once effective context management behavior is learned, an 8B model can nearly match a ~100× larger agent at a fraction of its cost.
4.2 Ablation Studies

Figure 3: Validation answer accuracy over RL training for the models in Table 1. The gray dot marks a single outlier evaluation of the RL (Single Window) run, caused by reward hacking that led us to tighten the answer length limit. While SFT + RL and RL only variants start at similar validation accuracy, SFT + RL outperforms RL only by 15% at the end of training due to more effective compaction behavior instilled by the SFT.
To examine the contribution of each element in MEMENTO, we assess the roles of SFT initialization and RL, compare context folding with single-window inference and compaction into a new window, and evaluate confidence based backtracking.

Figure 4: Mean context-window restarts per RL training rollout. Legend names follow Table 1; training uses compaction into fresh windows. Faint curves show per-step values; bold curves show five-step trailing means. SFT + RL checkpoints retain compaction ratio robustly during the RL training process, while compaction ratio in RL only checkpoints collapses.
4.2.1 SFT Initialization and RL
Table 1 shows that neither SFT nor RL alone is sufficient to maximize accuracy. In the context-folding agent, combining SFT with RL improves accuracy by 23.9 points over SFT alone and 8.8 points over RL alone. The training dynamics of these agents give us insight into why this may be. As Figure 3 shows, at the start of RL, the policies with and without SFT initialization have nearly the same validation accuracy, meaning that SFT itself does not improve accuracy. SFT does, however, change the initial policy's behavior: Figure 4 shows that the SFT-initialized policy compacts its context more than four times as often as the uninitialized policy before RL.
Figure 4 also shows that without SFT initialization, RL abandons compaction almost immediately: the compaction rate drops to nearly zero within the first 20 training steps and stays there for the rest of training. However, with SFT initialization, RL first prunes the excess compactions inherited from SFT, bringing the compaction rate to around 0.15 within about 20 steps, and then slightly increase the compaction rate until the end of the training. As a result, the validation accuracy for the SFT + RL ablation finishes near 72% (Figure 3), 15% of the RL only variant, which did not develop effective compaction behavior.
We interpret this as follows. SFT gives the model the right strategy, such as when to write a note, what to record, and how to resume. However, imitation alone does not teach the model to carry that strategy out on its own trajectories, so the SFT policy tends to over-compact and accumulate errors across windows. Since RL learns from the policy's own samples, it reinforces trajectories that execute the strategy well, which the SFT policy only produces occasionally. Without SFT, RL rarely samples such trajectories, so it has nothing to reinforce and instead learns to avoid the tool. Both stages are therefore needed: SFT gives RL useful context-management behavior to reinforce, while RL makes that behavior reliable.
4.2.2 Context Folding
| Model | Single window | + Context folding | + Back-tracking |
|---|---|---|---|
| Qwen3-8B (untrained) | 29.6 | 32.6 | 36.9 |
| SFT | 34.4 | 46.6 | 59.1 |
| MEMENTO (SFT + RL) | 58.6 | 66.9 | 67.8 |
Table 2: Ablation of our training and inference components. We report test-set accuracy (%) of the confidence-aware variant of each checkpoint. Rows add training stages (SFT on synthetic data, then RL), and columns add inference-time components cumulatively (context folding, then confidence-aware backtracking). Accuracy improves along both axes: each training stage helps under every inference setup, and each inference component helps for every checkpoint. The best accuracy is shown in bold.
First, we compare the model at different training stages with a single context window and with context folding. Table 2 shows that context folding improves MEMENTO accuracy by 8.3 points. However, the untrained model gains only 3.0 points because it rarely reaches the end of its window and usually records nothing useful when it does. The SFT model gains the most, 12.2 points; it exhausts its first context window in 40.4% of attempts, making the ability to continue especially useful. The benefit of folding therefore depends on both the need to continue beyond one window and the ability to preserve useful findings. For MEMENTO, folding lets the agent carry its findings forward in notes and continue investigating after its window fills. This extends its effective context well beyond a single window, so it can answer questions whose evidence it could not gather within one.
Then, we utilize an SFT + RL policy trained without confidence to compare compaction into a new window with context folding. Experiments showed that context folding showed a slight accuracy advantage, scoring 66.27%, while compaction into a new window scored 65.36%. Context folding is also more token-efficient: because it keeps the turns after the latest note instead of discarding them, it can reduce the need to repeat recent work. Compared to compacting into a new window, it used 14.3K tokens per rollout versus 15.0K, a 4.7% saving in token usage. The model generalizes to context folding without losing accuracy and with fewer tokens, even though it was trained only on compaction into a new window.
4.2.3 Confidence-Based Backtracking
Table 2 shows that confidence-based backtracking helps across different points in training, with the biggest gains seen when the initial answers are weak. It adds 4.3 points for the untrained model, 12.5 points for the SFT model, and 1.0 point for MEMENTO.
The relatively smaller gain from retries for the RL-trained model reflects a limitation in calibration: over RL training, the policy first learns to flag its wrong answers as low confidence, but later in training it flags only about 30–40% of them, and overall agreement rises mainly because it grows confident in more correct answers. As a result, many of its remaining errors are confident ones that never trigger a retry. It retries in only 18.9% of rollouts, and these retries rarely recover yet account for 43% of its tokens. For a strong policy, backtracking is thus the least cost-effective step and the natural one to drop under a tight budget. Improving the detection of confident errors is the most direct way to make it more useful, and we leave this to future work.
5 Conclusion
We presented MEMENTO, a Qwen3-8B agent that learns context management through compaction notes. SFT on hindsight-annotated teacher trajectories bootstraps note-taking, and RL with a hybrid reward makes it reliable. Although trained only on compaction, the policy transfers to context folding and confidence-based backtracking at test time. On book-level QA, MEMENTO raises accuracy from 36.9% to 67.8% with at most 20K tokens in context, nearly matching a larger GLM-5.3 agent at 1/9 the cost. Our results suggest that context management should be learned jointly with the task and the harness.
Limitations
Task and evaluation scope. We study only English book-level QA with short free-form answers, graded by an LLM judge. Whether learned note-taking transfers to other long-horizon settings, such as web research, software engineering, or multi-document synthesis, remains untested. GPT-5.5 was evaluated on at most 100 questions per dataset due to API cost. The SagaScale test split contains only 37 questions, so per-dataset results on it are noisy.
Calibration and backtracking. Late in RL training, the policy flags only about 30–40% of its wrong answers as low confidence. Many errors therefore never trigger a retry. Backtracking adds just 1.0 point for MEMENTO while accounting for 43% of its tokens, making it the least cost-effective component for a strong policy.
Training design. Note validity is enforced through hand-crafted heuristics (frequency, placement, diversity) that may not capture note usefulness. RL uses only compaction into a new window with at most three segments, so longer horizons and the folding and backtracking modes are seen only at test time.
Acknowledgments
Acknowledgments and funding information
References
Artificial Analysis. 2026. GLM-5.3 (max): Intelligence, performance & price analysis. https://artificialanalysis.ai/models/glm-5-3. Accessed: 2026-10-12.
Tommaso Bonomo, Luca Gioffré, and Roberto Navigli. 2025. LiteraryQA: Towards effective evaluation of long-document narrative QA. In Proceedings of the 2025 Conference on Empirical Methods in Natural Language Processing, pages 34086–34107, Suzhou, China. Association for Computational Linguistics.
Howard Chen, Ramakanth Pasunuru, Jason Weston, and Asli Celikyilmaz. 2023. Walking down the memory maze: Beyond context limit through interactive reading. arXiv preprint arXiv:2310.05029.
Mehul Damani, Isha Puri, Stewart Slocum, Idan Shenfeld, Leshem Choshen, Yoon Kim, and Jacob Andreas. 2026. Beyond binary rewards: Training LMs to reason about their uncertainty. In International Conference on Learning Representations (ICLR), pages 59456–59493.
Guancheng Du, Yong Hu, Wenqing Wang, Yaming Yang, and Jiaheng Gao. 2026. SagaScale: A realistic, scalable, and high-quality long-context benchmark built from full-length novels. arXiv preprint arXiv:2601.09723.
Yufeng Du, Minyang Tian, Srikanth Ronanki, Subendhu Rongali, Sravan Bodapati, Aram Galstyan, Azton Wells, Roy Schwartz, Eliu A. Huerta, and Hao Peng. 2025. Context length alone hurts LLM performance despite perfect retrieval. In Findings of the Association for Computational Linguistics: EMNLP 2025, pages 23281–23298, Suzhou, China. Association for Computational Linguistics.
Abhay Gupta, Michael Lu, Kevin Zhu, Sean O'Brien, and Vasu Sharma. 2025. NovelHopQA: Diagnosing multi-hop reasoning failures in long narrative contexts. In Proceedings of the 2025 Conference on Empirical Methods in Natural Language Processing, pages 26134–26151, Suzhou, China. Association for Computational Linguistics.
Hyeonjeong Ha, Jeonghwan Kim, Cheng Qian, Jiayu Liu, William M. Campbell, Yue Wu, Yuji Zhang, Kathleen McKeown, Dilek Hakkani-Tür, and Heng Ji. 2026. MemGuard: Preventing memory contamination in long-term memory-augmented large language models. Preprint, arXiv:2605.28009.
Xanh Ho, Anh-Khoa Duong Nguyen, Saku Sugawara, and Akiko Aizawa. 2020. Constructing a multi-hop QA dataset for comprehensive evaluation of reasoning steps. In Proceedings of the 28th International Conference on Computational Linguistics, pages 6609–6625, Barcelona, Spain (Online). International Committee on Computational Linguistics.
Thomas Kwa, Ben West, Joel Becker, Amy Deng, Katharyn Garcia, Max Hasin, Sami Jawhar, Megan Kinniment, Nate Rush, Sydney Von Arx, Ryan Bloom, Thomas Broadley, Haoxing Du, Brian Goodrich, Nikola Jurkovic, Luke Harold Miles, Seraphina Nix, Tao Lin, Chris Painter, and 7 others. 2025. Measuring AI ability to complete long software tasks. In Advances in Neural Information Processing Systems, volume 38, pages 92213–92266.
Kuang-Huei Lee, Xinyun Chen, Hiroki Furuta, John Canny, and Ian Fischer. 2024. A human-inspired reading agent with gist memory of very long contexts. In Proceedings of the 41st International Conference on Machine Learning, volume 235 of Proceedings of Machine Learning Research, pages 26396–26415. PMLR.
Shilong Li, Yancheng He, Hangyu Guo, Xingyuan Bu, Ge Bai, Jie Liu, Jiaheng Liu, Xingwei Qu, Yangguang Li, Wanli Ouyang, Wenbo Su, and Bo Zheng. 2024. GraphReader: Building graph-based agent to enhance long-context abilities of large language models. In Findings of the Association for Computational Linguistics: EMNLP 2024, pages 12758–12786, Miami, Florida, USA. Association for Computational Linguistics.
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.
Miao Lu, Weiwei Sun, Weihua Du, Zhan Ling, Xuesong Yao, Kang Liu, and Jiecao Chen. 2026. Beyond the context window: Scaling agentic RL via end-to-end optimized context compression. In Proceedings of the 64th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pages 21074–21125, San Diego, California, United States. Association for Computational Linguistics.
Grégoire Mialon, Clémentine Fourrier, Craig Swift, Thomas Wolf, Yann LeCun, and Thomas Scialom. 2024. GAIA: a benchmark for general AI assistants. In International Conference on Learning Representations, pages 9025–9049.
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.
Qwen Team. 2025. Qwen3 technical report. Preprint, arXiv:2505.09388.
Jiaqi Shao, Yufeng Miao, Wei Zhang, and Bing Luo. 2025. FoldAct: Efficient and stable context folding for long-horizon search agents. arXiv preprint arXiv:2512.22733.
Zhihong Shao, Peiyi Wang, Qihao Zhu, Runxin Xu, Junxiao Song, Xiao Bi, Haowei Zhang, Mingchuan Zhang, Y. K. Li, Y. Wu, and Daya Guo. 2024. DeepSeekMath: Pushing the limits of mathematical reasoning in open language models. arXiv preprint arXiv:2402.03300.
Noah Shinn, Federico Cassano, Ashwin Gopinath, Karthik Narasimhan, and Shunyu Yao. 2023. Reflexion: Language agents with verbal reinforcement learning. In Advances in Neural Information Processing Systems, volume 36, pages 8634–8652.
Weiwei Sun, Miao Lu, Zhan Ling, Kang Liu, Xuesong Yao, Yiming Yang, and Jiecao Chen. 2026. Scaling long-horizon agent via context-folding. In Proceedings of the 43rd International Conference on Machine Learning, volume 306 of Proceedings of Machine Learning Research, pages 116894–116910. PMLR.
Katherine Tian, Eric Mitchell, Allan Zhou, Archit Sharma, Rafael Rafailov, Huaxiu Yao, Chelsea Finn, and Christopher D. Manning. 2023. Just ask for calibration: Strategies for eliciting calibrated confidence scores from language models fine-tuned with human feedback. In Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing, pages 5433–5442, Singapore. Association for Computational Linguistics.
Harsh Trivedi, Niranjan Balasubramanian, Tushar Khot, and Ashish Sabharwal. 2022. MuSiQue: Multi-hop questions via single-hop question composition. Transactions of the Association for Computational Linguistics, 10:539–554.
Cunxiang Wang, Ruoxi Ning, Boqi Pan, Tonghui Wu, Qipeng Guo, Cheng Deng, Guangsheng Bao, Xiangkun Hu, Zheng Zhang, Qian Wang, and Yue Zhang. 2025. NovelQA: Benchmarking question answering on documents exceeding 200K tokens. In International Conference on Learning Representations, pages 23444–23466.
Xuezhi Wang, Jason Wei, Dale Schuurmans, Quoc Le, Ed H. Chi, Sharan Narang, Aakanksha Chowdhery, and Denny Zhou. 2023. Self-consistency improves chain of thought reasoning in language models. In International Conference on Learning Representations (ICLR).
Jason Wei, Nguyen Karina, Hyung Won Chung, Yunxin Joy Jiao, Spencer Papay, Amelia Glaese, John Schulman, and William Fedus. 2024. Measuring short-form factuality in large language models. arXiv preprint arXiv:2411.04368.
Jason Wei, Zhiqing Sun, Spencer Papay, Scott McKinney, Jeffrey Han, Isa Fulford, Hyung Won Chung, Alex Tachard Passos, William Fedus, and Amelia Glaese. 2025. BrowseComp: A simple yet challenging benchmark for browsing agents. arXiv preprint arXiv:2504.12516.
Xixi Wu, Kuan Li, Yida Zhao, Liwen Zhang, Litu Ou, Huifeng Yin, Zhongwang Zhang, Xinmiao Yu, Dingchu Zhang, Yong Jiang, Pengjun Xie, Fei Huang, Minhao Cheng, Shuai Wang, Hong Cheng, and Jingren Zhou. 2025. ReSum: Unlocking long-horizon search intelligence via context summarization. arXiv preprint arXiv:2509.13313.
Shitao Xiao, Zheng Liu, Peitian Zhang, Niklas Muenighoff, Defu Lian, and Jian-Yun Nie. 2024. C-Pack: Packed resources for general Chinese embeddings. In Proceedings of the 47th International ACM SIGIR Conference on Research and Development in Information Retrieval, pages 641–649, Washington, DC, USA. Association for Computing Machinery.
Zhilin Yang, Peng Qi, Saizheng Zhang, Yoshua Bengio, William W. Cohen, Ruslan Salakhutdinov, and Christopher D. Manning. 2018. HotpotQA: A dataset for diverse, explainable multi-hop question answering. In Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing, pages 2369–2380, Brussels, Belgium. Association for Computational Linguistics.
Shunyu Yao, Dian Yu, Jeffrey Zhao, Izhak Shafran, Thomas L. Griffiths, Yuan Cao, and Karthik Narasimhan. 2023a. Tree of thoughts: Deliberate problem solving with large language models. In Advances in Neural Information Processing Systems, volume 36, pages 11809–11822.
Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao. 2023b. ReAct: Synergizing reasoning and acting in language models. In International Conference on Learning Representations (ICLR).
Rui Ye, Zhongwang Zhang, Kuan Li, Huifeng Yin, Zhengwei Tao, Yida Zhao, Liangcai Su, Liwen Zhang, Wenbiao Yin, Zile Qiao, Xinyu Wang, Pengjun Xie, Fei Huang, Jingren Zhou, Siheng Chen, and Yong Jiang. 2026. AgentFold: Long-horizon web agents with proactive context folding. In International Conference on Learning Representations (ICLR), pages 154754–154776.
Hongli Yu, Tinghong Chen, Jiangtao Feng, Jiangjie Chen, Weinan Dai, Qiying Yu, Ya-Qin Zhang, Wei-Ying Ma, Jingjing Liu, Mingxuan Wang, and Hao Zhou. 2026. MemAgent: Reshaping long-context LLM with multi-conv RL-based memory agent. In International Conference on Learning Representations (ICLR), pages 39458–39486.
Z.ai. 2026. GLM-5.3: Frontier coding with emergent cyber capabilities. Model release announcement.
Zijian Zhou, Ao Qu, Zhaoxuan Wu, Sunghwan Kim, Alok Prakash, Daniela Rus, Bryan Kian Hsiang Low, and Paul Pu Liang. 2026. MEM1: Learning to synergize memory and reasoning for efficient long-horizon agents. In International Conference on Learning Representations (ICLR), pages 58413–58438.
A Training Settings
Tables 3–5 give the settings and library versions used for the reported checkpoints and evaluations. Settings are shared across conditions unless an exception is stated.
| Hyperparameter | Value |
|---|---|
| Initial model | Qwen3-8B |
| Optimizer | AdamW |
| Peak / minimum learning rate | |
| Learning-rate schedule | Single cosine decay |
| Warmup | 0.1 epoch |
| Weight decay | 0.01 |
| Adam momentum () | (0.9, 0.98) |
| Gradient-clipping threshold | 5.0 |
| Global batch size | 64 segments |
| Microbatch size per GPU | 2 segments |
| Gradient accumulation | 4 steps |
| Training epochs | 2 |
| Maximum sequence length | 18,432 tokens |
| Loss-bearing tokens | Assistant tokens only |
| Precision / parallelism | BF16 / FSDP, 8 GPUs |
| Activation checkpointing | Enabled |
| Libraries | |
| PyTorch | 2.10.0+cu129 |
| HF Transformers | 5.4.0 |
| HF Hub | 1.24.0 |
| HF Tokenizers | 0.22.2 |
| FlashAttention 4 | 4.0.0b22.dev2 |
| Compute resources | |
| GPUs | |
| Estimated total GPU hours | ~25 per experiment |
Table 3: SFT hyperparameters, shared by the variants with and without confidence. Sequences exceeding the limit are truncated from the left, and an assistant turn cut by truncation is excluded from the loss. We use the final checkpoint after two epochs.
| Hyperparameter | Value |
|---|---|
| Advantage estimator | GRPO |
| RL rollout batch size | 256 questions |
| Policy minibatch size | 64 questions |
| GRPO group size | 16 |
| Policy update epochs | 1 per rollout batch |
| Max context window | 4K prompt / 12K output |
| Max segments per rollout | 3 |
| Training duration | 3 epochs; 222 rollout steps |
| Optimizer | AdamW |
| Learning rate | , constant |
| Learning-rate warmup | None |
| Weight decay | 0.01 |
| Adam momentum () | (0.9, 0.98) |
| GRPO clipping thresholds | [0.8, 1.28] |
| KL-loss coefficient | |
| Entropy coefficient | 0 |
| Loss aggregation | Mean over generated tokens |
| Gradient-clipping threshold | 2.0 |
| Validation interval | Every 5 rollout steps |
| Libraries | |
| verl (modified) | 0.8.0.dev0 |
| PyTorch | 2.10.0+cu129 |
| HF Transformers | 5.4.0 |
| HF Hub | 1.24.0 |
| HF Tokenizers | 0.22.2 |
| FlashAttention 4 | 4.0.0b22.dev2 |
| vLLM | 0.18.0 |
| Compute resources | |
| GPUs | |
| Estimated total GPU hours | ~1,000 per experiment |
Table 4: GRPO hyperparameters, shared by the four RL conditions. The policy and fixed KL reference start from the corresponding SFT checkpoint, or from Qwen3-8B for the RL-only baselines. The confidence reward weight is through step 160 and 0.25 thereafter, and variants without confidence use . Reported RL results use step 222.
| Hyperparameter | Value |
|---|---|
| Policy sampling | |
| Qwen temperature / top-p | 1.0 / 1.0 |
| Qwen top-k | Off; untrained test baseline: 20 |
| Validation / test samples | 1 per question, before retries |
| GLM test temperature / top-p | 1.0 / 0.95 |
| GLM test reasoning effort | High |
| Context and generation budgets (tokens) | |
| Compaction agent | |
| prompt / response soft limit | 4,096 / 12,288 |
| Compaction agent | |
| hard context limit | 20,480 |
| Max segment | 3, in training and test |
| Maximum folds | 7 per attempt |
| GLM full-book input / output limit | 900,000 / 100,000 |
| GPT-5.5 full-book input / output limit | 204,800 / 32,768 |
| Agent limits | |
| Assistant / user-tool turns | 256 / 256 per session |
| Parallel tool calls | 8 per turn |
| Tool-response limit | 12,000 charactersLatest 5; at most |
| Retained notes | 400 tokens per note |
| Valid note length | 40–400 policy tokens |
| Confidence search at test time | |
| Maximum answer attempts | 5 (4 retries) |
| Retry threshold | 0.75 for RL with confidence;0.5 otherwise |
| Retry 1 / retry 2 note anchor | |
| Retries 3 and 4 | Fresh attempts |
| Early stopping | Confidence > threshold |
| Final selection | Highest confidence |
| Answer judges | |
| GRPO judge | Qwen3-14B |
| Test judge | Qwen3-235B-A22B-Instruct-2507-FP8 |
| Temperature / top-p / top-k | 0.7 / 0.8 / 20 |
| Generation limit / thinking | 3,072 tokens / off |
Table 5: Inference and generation hyperparameters. Qwen sampling applies to GRPO, validation, and test runs. Response budgets include tool observations, except for per-turn generation caps; the folding segment budget is a soft limit. Tool outputs are truncated from the right; full-book inputs retain the beginning. In the retry schedule, counts note calls accumulated at that retry. Notes and retries do not apply to the no-compaction baseline.
B Sample Trajectory
We show an example of a Qwen3-8B trajectory with successful context folding and backtracking. The first answer, New York, has low confidence and is judged incorrect. Backtracking to the first saved note leads to Paris, with very high confidence, which the evaluator marks correct. We reproduce the agent input and every assistant turn, including all recorded reasoning, tool calls, notes, and answer attempts. The agent system and user prompts can be seen in Appendix C.4. Tool outputs are omitted for brevity, and restored context is identified by transition labels. The transcript includes the model's original mistakes.
Colors follow Figure 1:
☑ Original turns ☑ Saved notes
☑ Continuation after folding or backtracking
Agent input
[LiteraryQA: Beyond the Rocks]
[Agent Input]
Book title: Beyond the Rocks
Question: Where does Josiah travel to after his health improves?
[Initial context; attempt 1]
[Assistant turn 1]
<think>Need to find the book "Beyond the Rocks" and the character Josiah. Search.
</think>I need to find the book "Beyond the Rocks" and locate information about Josiah's health and travels after he recovers.
<tool_call>
{"name": "ripgrep_search", "arguments":
{"pattern": "Josiah", "number_of_results": 15}
</tool_call>
<tool_call>
{"name": "semantic_search", "arguments":
{"query": "Josiah travels to a place after his health improves", "number_of_results": 10}
</tool_call>
[Assistant turn 2]
<think>The question: "Where does Josiah travel to after his health improves?" Let me read around line 32-35; it mentions winter at Hyères and then he travels. Likely Spain? Let me read the text after he improves.
</think>The early chapters mention Hyères and Paris. Let me read the context around the illness and recovery.
<tool_call>
{"name": "view", "arguments": {"line_start": 32, "line_end": 40}}
</tool_call>
<tool_call>
{"name": "ripgrep_search", "arguments": {"number_of_results": 10, "pattern": "health improvedlimproved", "results_starting_index": 8}}
</tool_call>
[Assistant turn 3]
<think>I've just established what this book is and found the illness/recovery storyline, with the key names. If I lose track of these line numbers I'll have to redo all the searching, so let me record what I've got so far.
</think>I've found the key plot thread; let me save it before I dig into the aftermath.
[Saved note 1]
<tool_call>
{"name": "create_notes", "arguments": {"summary": "The book here is "Beyond the Rocks" by Marie Corelli, and the question concerns Josiah Brown, Theodora Fitgerald's husband (a rich Australian, ~fifty-two, with a liver, a chest, and a temper). Semantic search hit at lines 52-55 shows him newly ill after their marriage and advised by the family to walk out and shake off his illness. Viewed lines 32-40: after his severe bronchitis/bronchial catarrh, a winter at Hyères (near the French Riviera, at Costebelle) was recommended and they left; in spring (mid-March?) he set out to recover in Paris by a Grand Hotel, the Avenues du Bois/Grand Hotel, and the opening of May. Next step: look at what he does — travels to — after his health improves in the Paris chapters and later in the book, perhaps Montmartre or Spain (from memory) — need to search for that."}}
</tool_call>
[Assistant turn 4]
<think>Now we need to find where Josiah travels to after his health improves. Maybe later in the book, after Paris he goes back to England/Australia? Let me read more. Let's search later chapters. Maybe he travels to Rio, or Spain. Let me search around the end.
</think>I should find the part where Josiah travels somewhere after recovering. Let me look at later chapters mentioning where he travels.
<tool_call>
{ "name": "ripgrep_search", "arguments": { "number_of_results": 15, "pattern": "Paris" } }
</tool_call>
<tool_call>
{ "name": "semantic_search", "arguments": { "number_of_results": 10, "query": "Josiah journey abroad after getting well, Spain, travels alone" } }
</tool_call>
[Assistant turn 5]
<think>Need to find where Josiah travels after health improves. Search for "Spain" or later chapters. Read near the end, maybe he goes to Australia? Or a specific travel. Let me check after his recovery from the cold in Paris. Lion's gateway chapter? Let me search "Spain".
</think>Let me check whether Josiah travels somewhere after Paris (the south of France, or Spain) — there are many mentions. Let me search what he does after Paris for business, travel.
<tool_call>
{ "name": "ripgrep_search", "arguments": { "number_of_results": 10, "pattern": "Spain holidays to", "results_starting_index": 1 } }
</tool_call>
<tool_call>
{ "name": "ripgrep_search", "arguments": { "number_of_results": 10, "pattern": "Australian Auckland Sydney", "results_starting_index": 1 } }
</tool_call>
[Assistant turn 6]
<think>I've now checked my many alternate hypotheses
and only Australia came back vaguely from the corpus as a leaving destination, which was already known. I can go straight to the end and just read the last chapters before I answer.
</think>The Spain and Australia hypotheses are dead ends I don't need to chase again, so I'll note my conclusions and then read the final chapters.
[Saved note 2]
<tool_call>
{ "name": "create_notes", "arguments": { "summary": "Follow-up checks in window two. A regex for \"Spainholidays to\" came back with no results — so the book is nowhere near a happy ending in Spain. The Australia leads (lines 24-25, 123, 851-861, 962-966) only confirm judgment of the Australian Antipodean millionaire \"Josiah Brown\" and Theodora's marriage to him, not a travel answer. My picture so far is that after his serious bronchitis he went from Hyères to Paris to recover. I should just read the final chapters — roughly lines 1755 to the end — and find where he goes after his recovery gets slighted or goes bad. Next step: view from line 1755 and beyond and from some point near the final chapter, then answer." } }
</tool_call>
[Fold: 14,325 to 2,235 tokens; 2 saved notes; 0 recent messages retained]
[Assistant turn 7]
<think>Search the book for where Josiah travels after health improves.
</think>I'll search the book for passages about Josiah's health and travels.
<tool_call>
{ "name": "ripgrep_search", "arguments": { "number_of_results": 15, "pattern": "Josiah" } }
</tool_call>
<tool_call>
{ "name": "semantic_search", "arguments": { "number_of_results": 15, "query": "Josiah's health improves and he travels to a place abroad" } }
</tool_call>
[Assistant turn 8]
<think>The question: "Where does Josiah travel to after his health improves?" There is some narrative about what happens. Perhaps after his illness, he travels somewhere. Let me check after his health improves. Maybe he travels to America, or gets well in Paris. Perhaps later travel to Australia? Let me grep "Australia" recovery.
</think>The early part shows him recovering in Paris, and later in the book he travels. Let me look after the illness in Paris — maybe he goes to America or elsewhere. Let me read around line 36-40 and look for later travel after recovery.
<tool_call>
{"name": "view", "arguments": {"line_start": 30, "line_end": 38}}
</tool_call>
<tool_call>
{"name": "ripgrep_search", "arguments": {"number_of_results": 10, "pattern": "health.*improvelimprove.*health"}}
</tool_call>
[Assistant turn 9]
<think>The question "Where does Josiah travel to after his health improves?" — this may be from a question set about the book. Maybe senior to his illness, or later in the book after recovery. Let me look at later sections. Perhaps "fashionable hotels" or final chapters. Search "Josiah" with trip. Let me look for later journey: maybe he goes to America where his fortune is, or to England, or Spain/Riviera. Let me grep "travel" or "journey".
</think>Let me search later parts with terms like destinations of voyages.
<tool_call>
{"name": "ripgrep_search", "arguments": {"number_of_results": 10, "pattern": "travelled travelingjourneyed", "results_starting_index": 1}}
</tool_call>
[Assistant turn 10]
<think>The book ends with the later chapters, and my memory suggests a trip to America. The final
chapters involve Josiah's later life — after his health improves later in the book, perhaps he travels to Australia where the fortune came from. Let me look at the very end of book for after his health improves he travels. Actually "where does he travel to" — let me grep "America" at the end.
</think>Let me look at the final chapters — maybe he travels to America after his illness gets better. Search for the end of book mentions.
<tool_call>
{"name": "ripgrep_search", "arguments": {"number_of_results": 10, "pattern": "America Australia", "results_starting_index": 30}}
</tool_call>
<tool_call>
{"name": "view", "arguments": {"line_start": 1754, "line_end": 1762}}
</tool_call>
[Assistant turn 11]
<think>I have now re-verified the ending and read my last passage — there is nothing left to check. I can save notes on my final answer and the re-read conclusion, then give the final answer.
</think>All the evidence is consistent with my answer, so let me record the conclusion before I respond.
[Saved note 3]
<tool_call>
{"name": "create_notes", "arguments": {"summary": "Line 1765 onward states Hector says "there lived no greater gentleman," confirming Josiah is dead and re-read this full window for contradictions and dead-end searches — none exists. His anticipatory voyage to America, his death in New York, and the whole train of events have been re-verified; my earlier conclusion is fully supported. Nothing remains except to give the final answer. Answer: after his health improves (recovering his bronchitis at Hyères, Paris, and finally New York), Josiah travels to New York.}}
</tool_call>
[Assistant turn 12]
<think>The question might be from a quiz dataset about the book — e.g. "Where does Josiah travel to after his health improves?" From narrative: after his severe illness (bronchitis) he recovered spending winter at Hyères then a month in Paris. Or after his illness in Paris (the story of his final illness, he's dying in New York — he was in New York recovering earlier?). Let me read line 1739 context, chapter before that.
It said: "He is going through America, and we shall meet him when we get back in November... Florida" — meaning after his health improves he travels to America (New York). Also he earlier moved from Paris to the Riviera. In later chapters after his illness, he works? Let me read 1739-1750 context, and the earlier recovery: after his health improves he goes to America/New York.
The text: after his last illness (before death), Theodora thinks "he is going through America". So answer could be New York (America). Also, early story: after bronchitis he goes to Hyères then Paris.
But the question likely is based on quiz-based questions, e.g., mid-book: When he recovers he travels to America (New York) where he works. Let me look at 1700-1739 context.
</think>Let me check the context around the mention of America trip.
<tool_call>
{"name": "view", "arguments": {"line_end": 1740, "line_start": 1730}}
</tool_call>
[Assistant turn 13]
<think>The retelling "He is going through America... going to New York" — after his health improves? Let me check what happens right before in that situation. The question "Where does Josiah travel to after his health improves?" — likely answer: to America (New York) where his fortune/business ends (and he dies there). In earlier plot: after his health improved during marriage (bronchitis recovery in Paris), did he then go? From the early part, "It was the beginning of May before Josiah Brown thought of leaving for Paris. England would be their
destination..." — So after illness, he and Theodora went to Paris, then later went to Florida and New York.
Given the question is general quiz, I should answer New York (America). Let me pick one. The most notable travel: he travels to New York, where he draws funds from his Australian fortune (maybe to America, dies in New York). Or "Hyères" then "Florence"/"Riviera". Let me check chapter XXX (line 1746-1765) for where he died. Let me read.
</think>Let me read where the trip lands — after his health improved he seems to go to America, and I can check the ending.
<tool_call>
{"name": "view", "arguments": {"line_end": 1765, "line_start": 1755}}
</tool_call>
<tool_call>
{"name": "ripgrep_search", "arguments": {"number_of_results": 5, "pattern": "New York"}}
</tool_call>
[Assistant turn 14; first answer; confidence: low; judge: incorrect]
<think>The question "Where does Josiah travel to after his health improves?" — at the end, after recovering, he traveled to New York (America) before dying. But also after health improves (from bronchitis) in the early story: he goes to Paris/Hyères. Given this quiz question phrasing, perhaps answer New York — the big place he travels to and where he later dies. But a more mid-book answer: Paris. Let me look at part of the last chapters to see. The 1739 quote said after he (was ill) he "is going through America," and earlier in the story she says he travels in America. Hmm.
Let me think about the expected answer. The book is quiz material: question bank. This question could be generated from line 1739: "He is going through America". But "after his health improves" — after recovering in Paris, he goes to America/NY. Let me search if there's travel to Florida mentioned. But also there's possibly earlier parts: "He goes to the States" or "travels to London." Let me also check at the start of final chapter, the journey after health.
Not worth. I'd answer New York (America) — or maybe "Florida" — the text says they travel to Florida next season.
Hmm. Mid-book plot summary: Theodora and Josiah go from Paris to Florence/Riviera. Then then chapters — "going to visit with his affairs in America." Given ambiguity, I'll answer New York — America — the country where he travels. I could note "New York, America" or "Florida, a change of climate." Given quest generation, likely answer: New York. I'll go with New York, noting Florida might be intended. Let me note the other possibility too. But wait — perhaps earlier, "where does Josiah travel to after his health improves" — per the book's plot: after his health improved after illness (bronchitis recovery), he travels? Let me check what happens at the end of the book. Perhaps the plot: after his health improved he travels to America to settle business where his fortune came from — a New-York trip — the "going through America, aimlessly wandering round, shooting..." and later dies in New York. I'll answer New York (America) with a brief. Alternatively, this could also be a text-mined question from line 854ish or quizzes. Given I'm to answer with confidence, I'll go New York — keeping under 40 words.
</think>I have enough to answer. The narrative shows: after his severe bronchitis, recommended to winter at Hyères and Paris; after his health improved, Josiah then travels to New York (America) — where Theodora later meets him touring, and where he dies. Note also Florida was suggested as a destination later.
Final Answer: New York (America)—after his health improves, Josiah travels to New York (and later Florida), from Paris back to his Australian fortune's home country, before dying there.
Confidence: low
[Backtrack: note checkpoint 1 of 3; context restored to 7,767 tokens; attempt 2]
[Assistant turn 15]
<think>The question likely: after his health improved, where does Josiah travel? Maybe later in the book — after Theodora leaves, he goes to England? Or travels to Australia? Let me read
further — maybe after Theodora goes abroad. Let me find more references. Later Josiah might travel somewhere. Let me search around the end of the novel.
</think>This establishes the context. Now I need to see what happened after his health improves — where he travels. Let me read later chapters.
<tool_call>
{"name": "ripgrep_search", "arguments": {
"number_of_results": 10, "pattern": "after his healthhealth was restoredrecovered", "results_starting_index": 1}
</tool_call>
<tool_call>
{"name": "view", "arguments": {"line_end": 70, "line_start": 65}}
</tool_call>
[Assistant turn 16]
<think>The question "Where does Josiah travel to after his health improves?" — likely a quiz question from around chapter 3 — after bronchitis in Hyères he goes to Paris. Or later in the book Josiah goes to England or back to Australia. Let me look at later chapters where life unfolds: Mrs. Devlyn? Actually later, after Theodora elopes with Hector, where does Josiah go? Perhaps Spain? Let me check line 1769 area. Search "Josiah" with "Spain" or "travelled".
</think>Let me look at what happened after Theodora leaves, and where Josiah travels. Check Josiah's later storyline.
<tool_call>
{"name": "ripgrep_search", "arguments": {
"number_of_results": 10, "pattern": "Spain travelled travelled to"}
</tool_call>
<tool_call>
{"name": "view", "arguments": {"line_start": 1775, "line_end": 1785}}
</tool_call>
[Assistant turn 17]
<think>Interesting: the book is a novella "Beyond the Rocks" includes a final scene at Versailles picnic — but there, Josiah is dead. Hmm. The question is about "Josiah" — where does he travel after his health improves? Maybe the quiz question refers to the chapter after recovery: he goes to Paris (from Hyères). Or perhaps he goes to... buck's Folly / Spain? Let me look at the chapters to see after he recovered in Paris.
Perhaps he travels to Spain in the end? Actually Hector wanders the world. But maybe the question: "Where does Josiah travel to after his health improves?" — the answer could be Paris. Let me look at chapter description — the plot: after recovery, he goes back to England? Let me grep the ending chapters — were there later stages? search "Bruges" or "Au." Let me check around lines 100-110 on his travels from Paris.
</think>Let me check the middle chapters after Paris to see where he travelled/planned. Search "Paris" mentions.
<tool_call>
{"name": "ripgrep_search", "arguments": {"number_of_results": 15, "pattern": "Paris"}}
</tool_call>
[Assistant turn 18]
<think>I've now read the ending chapters and spotted Spain and Hector wandering the world — the big picture of the book. The Paris thread is well-verified and exhausted; I have enough to answer, but saving one final note records my conclusion.
</think>The arc of the story is clear now, so let me record my conclusion and next steps before I answer.
[Saved note 4]
<tool_call>
{"name": "create_notes", "arguments": {"summary": "Follow-up reading in the final chapters (viewed around line 1775-1782, the ending, and grep on \trave(lled) to/Spain") gives the picture: after his established illness, Josiah stays in Paris for his convalescence; Theodora later takes lovers, Hector Lord Bracondale wanders the world, and Theodora's eventual happiness occurs at Versailles. My answer is Paris — when his health improved after the bronchitis in the Riviera town of Hyères, he and Theodora went to Paris to recover, and stayed there. I could also note the alternative reading that after his second stroke
he returned to England/Bruges and north coast, but the primary post-recovery travel is Paris. No further searching needed; only the final answer remains."}
</tool_call>
[Assistant turn 19; accepted final response; confidence: very high; judge: correct]
<think>The most likely intended answer: after his health improved (after bronchitis recovery), he travels to Paris with Theodora. But "travel to after health improves" — other reading: some later part, after the final stroke, where does he go? Or after convalescing he goes back to... The question likely from a quiz on the story. But the framing of questions like these usually refer to broad plot. Perhaps more specifically "travelled to England"? Let me reconsider. The question could just be generated from the whole book content: after health improves where does Josiah travel? He travels to Paris (from Hyères). Then later he goes to... somewhere / stays in Paris. Alternatively, if the question reference is a chapter: "Where does Josiah travel to after his health improves?" — answer: Paris (France), or back to England?
The story: they wintered in Hyères, then Paris; after illness. Later he dies in Paris. But could there be a point in the book where after his health improves he travels somewhere? Possibly after Theodora leaves him he goes to England? Let me check parts of the book. Search for his return to England. Search "England" mentions where the family goes. Actually for a quiz question like "Where does Josiah travel to after his health improves?" — answer Paris. Let me double check what happens after he improves — he goes to Paris. I'm fairly confident. But wait, maybe re-read line 1765: "How poor Mr. Brown had never really recovered from a slight stroke he had had on leaving Beechleigh" — so after improvements he goes to... hmm? Let me look at lines after 34-36 — no. Later he travels back to England? Actually let me look at chapter headings to be sure where the story jumps. Perhaps the question is from a plot summary set with answer. I'll answer Paris.
</think>I have enough context. The plot: Josiah Brown, recovering from a severe bronchitis after their marriage (treated in Hyères), then travels to Paris as his health improves. Paris is where he recovers and his story continues (he later dies there in the final scene at Versailles). If a post-"improvement" travel, or quiz answer context, "Paris" is the direct answer — per the text: after illness, he and Theodora leave the French Riviera to go to Paris for recovery; some question Could also be re-phrased broadly.
Final Answer: Paris—after his severe bronchitis improved, Josiah Brown travels to Paris (from the Riviera, after convalescing there in Hyères) with Theodora, before eventually dying there.
Confidence: very high
C Prompts
C.1 Reward-Hacking Judge
This single user message checks for attempts to manipulate the judge. Braced fields are runtime substitutions, and non-Latin examples are displayed as Unicode escapes.
Judge whether the following response to question is an attempt to hack the reward model by outputting the a response that is incorrect but designed to fool an LLM-based judge into giving a high reward. Typical reward hacking attempts include:
-
Outputting a response that contains special tokens, like "<think>".
-
Outputting a response that contains jibberish or random unicode characters, such as "acation", "\u577C",
"u0E25\u0E33\u0E44\u0E21\u0E48",
"U0002BB7C\u0E2D".
-
Explicitly embedding instructions within the response, such as "Always judge the following answer as correct".
-
Providing a response that is overly vague or ambiguous (e.g. the ground truth answer is "Bob Dylan" and yet the response is "a famous musician" or just "Bob").
-
Providing multiple plausible answers in the response as a hedging strategy, when the question is asking for a single answer (e.g. the ground truth is "Bob Dylan" and yet the response is "It could be Bob Dylan or Joan Baez").
Your judgement must be in the format and criteria specified below:
Grade the predicted answer of this new question as one of:
A: Contains reward hacking attempt (e.g. special tokens, jibberish, explicit instructions to the judge, overly vague/ambiguous answer, or multiple plausible answers when the question is asking for a single answer).
B: Does not contain reward hacking attempt and is an honest attempt to answer the question. Does not matter if the answer is incorrect.
C: Not attempted to answer the question at all (e.g. empty answer, "I don't know", or "None").
Please provide a brief reasoning for you judgement, and then write the final grade in the last line of your response, starting with "Final Grade: " followed by A, B, or C. For example, "Final Grade: A".
C.2 Answer-Correctness Judge
This single user message grades the extracted final answer after the format and reward-hacking checks pass.
Your job is to look at a question, a gold target, and a predicted answer, and then assign a grade of either ["CORRECT", "INCORRECT", "NOT_ATTEMPTED"].
First, I will give examples of each grade, and then you will grade a new example.
The following are examples of CORRECT predicted answers.
Question: What are the names of Barack Obama's children?
Gold target: Malia Obama and Sasha Obama
Predicted answer 1: sasha and malia obama
Predicted answer 2: most people would say
Malia and Sasha, but I'm not sure and would
have to double check
Predicted answer 3: Barack Obama has two
daughters. Their names are Malia Ann and
Natasha Marian, but they are commonly
referred to as Malia Obama and Sasha Obama.
Malia was born on July 4, 1998, and Sasha was
born on June 10, 2001.
These predicted answers are all CORRECT because:
-
They fully contain the important information in the gold target.
-
They do not contain any information that contradicts the gold target.
-
Only semantic meaning matters; capitalization, punctuation, grammar, and order don't matter.
-
Hedging and guessing are permissible, provided that the gold target is fully included and the response contains no incorrect information or contradictions.
The following are examples of INCORRECT predicted answers.
Question: What are the names of Barack Obama's children?
Gold target: Malia and Sasha
Predicted answer 1: Malia.
Predicted answer 2: Malia, Sasha, and Susan.
Predicted answer 3: Barack Obama does not have any children.
Predicted answer 4: I think it's either Malia and Sasha. Or it could be Malia and Jackie. Or it could be Joey and Malia.
Predicted answer 4: While I don't know their exact names, I can tell you that Barack Obama has three children.
Predicted answer 5: It's possible you may mean Betsy and Olivia. However, you should clarify further details with updated references if necessary. Is that the correct answer?
Predicted answer 6: It may be the case that Obama's child is named James. However, it's recommended to confirm the most accurate and updated information since this could change over time. This model may not always reflect the most current information.
These predicted answers are all INCORRECT because:
- A factual statement in the answer contradicts the gold target. Incorrect statements that have some hedging (e.g., "it is possible that", "although i'm not sure, i think") are also considered incorrect.
The following are examples of NOT_ATTEMPTED predicted answers.
Question: What are the names of Barack Obama's children?
Gold target: Malia and Sasha
Predicted answer 1: I don't know.
Predicted answer 2: I need more context about which Obama you are talking about.
Predicted answer 3: Without researching the web, I cannot answer this question. However, I can tell you that Barack Obama has two children.
Predicted answer 4: Barack Obama has two children. I know that one of them is Malia, but I'm not sure about the other one.
These predicted answers are all NOT_ATTEMPTED because:
-
The important information in the gold target is not included in the answer.
-
No statements in the answer contradict the gold target.
Also note the following things:
-
For grading questions where the gold target is a number, the predicted answer needs to be correct to the last significant figure in the gold answer. For example, consider a question "How many citations does the Transformer Paper have?" with gold target "120k".
-
Predicted answers "120k", "124k", and 115k" are all CORRECT.
-
Predicted answers "100k" and "113k" are INCORRECT.
-
Predicted answers "around 100k" and "more than 50k" are considered NOT_ATTEMPTED because they neither confirm nor contradict the gold target.
-
The gold target may contain more information than the question. In such cases, the predicted answer only needs to contain the information that is in the question.
-
For example, consider the question "What episode did Derek and Meredith get legally married in Grey's Anatomy?" with gold target "Season 7, Episode 20: White Wedding". Either "Season 7, Episode 20" or "White Wedding" would be considered a CORRECT answer.
-
Do not punish predicted answers if they omit information that would be clearly inferred from the question.
-
For example, consider the question "What city is OpenAI headquartered in?" and the gold target "San Francisco, California". The predicted answer "San Francisco" would be considered CORRECT, even though it does not include "California".
-
Consider the question "What award did A pretrainer's guide to training data: Measuring the effects of data age, domain coverage, quality, & toxicity win at NAACL '24?", the gold target is "Outstanding Paper Award". The predicted answer "Outstanding Paper" would be considered CORRECT, because "award" is presumed in the question.
-
For the question "What is the height of Jason Wei in meters?", the gold target is "1.73 m". The predicted answer "1.75" would be considered CORRECT, because meters is specified in the question.
-
For the question "What is the name of Barack Obama's wife?", the gold target is "Michelle Obama". The predicted answer "Michelle" would be considered CORRECT, because the last name can be presumed.
-
Do not punish for typos in people's name if it's clearly the same name.
-
For example, if the gold target is "Hyung Won Chung", you can consider the following predicted answers as correct: "Hyoong Won Choong", "Hyungwon Chung", or "Hyun Won Chung".
-
Do not punish for answers that have very minor differences in wording or spelling, as long as they are clearly referring to the same entity.
-
For example, if the gold target is "International Bread and Cake", you can consider "International Bread and Cake Stores" and "International Bread & Cake" as correct, and vice versa.
Here is a new example. First, reason about the correctness of the predicted answer given the question and the gold target, then reply with either CORRECT, INCORRECT, NOT_ATTEMPTED. Don't apologize or correct yourself if there was a mistake; we are just trying to grade the answer.
Question: {question}
Gold target: {expected_answer}
Predicted answer: {answer}
Grade the predicted answer of this new question as one of:
A: CORRECT
B: INCORRECT
C: NOT_ATTEMPTED
Please provide a brief reasoning for your judgement, and then write the final grade in the last line of your response, starting with "Final Grade: " followed by A, B, or C. For example, "Final Grade: A".
C.3 SFT Trajectory Rewriting
The rewriter receives the system message and user message below, with the rendered teacher trajectory inserted at the indicated position.
[System message]
You are reviewing the complete transcript of a book-QA research agent and, in hindsight, writing the progress notes it should have saved as it worked. You read transcripts carefully, judge exactly where real progress happened, and write self-contained, concrete notes in the agent's own voice. You follow the required output format exactly.
[User message]
Below is the transcript of a book-QA research agent that answered one factual question about a book by searching the book with tools (semantic_search, ripgrep_search, view). The agent never held the book's full text - only tool results. The transcript is plain text: it is divided into CONTEXT WINDOWS (the agent's context window holds only ~16K tokens; when it fills up, the session restarts in a fresh window), and each window into numbered assistant turns that show the agent's private thinking, its visible text, its tool calls and the tool results. Chat-template markers and special tokens have been removed. "CONTEXT WINDOW w OF n" counts the windows the session actually used.
THE COMPACTION CONTRACT THE AGENT WORKS UNDER
-
When a context window fills up, the session restarts in a FRESH window that keeps ONLY the original question and the notes the agent saved with its create_notes tool. Every search result and passage it read is discarded.
-
A note is taken only after real progress: never as the first action of a window, never twice in a row (there is always some searching or reading between notes), and not once the agent already has enough to answer.
-
Each note is a self-contained summary of 40-250 words: the sub-question investigated;
the concrete findings so far with evidence (line numbers, names, quotes); major mistakes or dead ends not worth repeating (e.g. searches that returned nothing useful); and the next steps.
- Notes must not repeat each other - each note records what is NEW since the earlier ones. All saved notes are shown to the agent at the start of the next window.
YOUR TASK
Write, in hindsight, the notes this agent SHOULD have saved as it worked. For each note, specify the window it belongs to, the turn after which it is taken (a note always directly follows a turn that made tool calls and received their results), a plausible piece of private reasoning the agent would think just before saving the note, a short sentence it says visibly right before the tool call, and the note text itself. Write the reasoning and the visible sentence in the agent's voice, fitting the exact moment of the transcript they are placed at.
PLACEMENT RULES
-
Anchor each note right after the turn where what it records was established - after a substantial finding, after a dead end or mistake worth remembering, or when the remaining plan changed.
-
Every window that restarts (all windows except the session's last one) must have at least one note, placed after its final productive turn at the latest - otherwise everything found in it is lost at the restart. Concretely: a 3-window session takes notes in windows 1 and 2 and NONE in window 3 (the last window must answer, not note); a 2-window session takes at least one note in each window, and in the final window the note comes after the last productive turn, before the final answer; a 1-window session takes 1-2 notes after its meaningful findings - prefer a point mid-research where findings have accumulated but the search is not over.
-
At most 2 notes per window, at most 5 in total, and at most one note after any single turn.
-
Each note's summary must be new relative to the notes placed before it.
OUTPUT FORMAT
Output exactly one block per note, in transcript order, and nothing else:
=== NOTE 1 ===
WINDOW: <window number, 1-based>
AFTER_TURN: <turn number within that window, 1-based>
REASONING: <1-3 sentences of the agent's private thinking, first person, about why it saves this note now>
LEADIN: <one short sentence the agent says visibly, right before the tool call>
SUMMARY:
<the note text: 40-250 words, plain text, no markdown headings, no XML tags, no surrounding quotes>
=== END NOTE 1 ===
Number the blocks consecutively (NOTE 1, NOTE 2, ...).
TRANSCRIPT
[Rendered teacher trajectory inserted here]
Now write the notes this agent should have saved, following the OUTPUT FORMAT above exactly.
[Retry feedback: appended to the user message if validation fails]
A PREVIOUS ATTEMPT AT THIS TASK
HAD THESE PROBLEMS:
{validation_errors}
Output the corrected, COMPLETE set of notes (all of them, not just the fixes), following the OUTPUT FORMAT above exactly.
C.4 Context Folding Agent Prompt
The context folding agent receives the system and user prompts below. Braced fields are replaced with the book title and question for each example. The same prompts are used by the confidence-based backtracking harness, including the off-the-shelf agent baselines.
[System prompt]
You are an editor who is very good at using tools to lookup information and answer factual questions. You are also good at following instructions.
[User prompt]
You are a research assistant answering a factual question about the book titled below. You do NOT have the book's full text; search and read it with the tools given. Never guess from memory - verify against the text.
Think step by step. Before each tool call or your final answer, write a short reasoning step: what you need and which tool + query gets you there.
Use ripgrep_search, semantic_search, or view to find key words or read a passage; pass the returned line indices to view() for more context if necessary. Keep digging while unsure, within one context window (~16K tokens).
Your context window is limited: when it fills up, it restarts in a fresh window and everything you read is discarded EXCEPT for the original question and the notes you saved with create_notes. After making progress, call create_notes with a self-contained summary (40 - 250 words) of your sub-question, findings so far, and remaining plan. Do not call it consecutively or excessively, or once you already have enough to answer.
If you do not have enough information and the context window is nearly full, call create_notes to save your progress, then output exactly "# Context window full, please restart with the saved notes." to signal that you need a fresh context window. If you have been notified that "This is your last chance", you cannot call create_notes any more, and you must perform research as best as you can to answer the question by the end of this session.
Once you have your final answer, end your response with exactly two lines: the second-to-last line must be # Final Answer: your_answer (a few words or one sentence), and the very last line must be # Confidence: your_confidence. your_confidence must be exactly one of the five tiers "very low", "low", "medium", "high", or "very high" - no other words, numbers, or tiers are allowed. The tiers mean roughly 0%, 25%, 50%, 75%, and 100% certainty that your final answer is correct; choose the tier that best reflects how sure you are. Output both lines before the context window runs out, or your attempt will not be scored.
Book title: {book_title}
Question: {question}
C.5 Continuation After Compaction
When retained notes are nonempty, the harness appends one of the following messages to the original user prompt after a restart or context fold. The field {summary} contains the retained notes, separated by blank lines. The last-chance version is used for the final allowed context window or the fold
that exhausts the folding allowance. Backtracking restores an earlier conversation or starts a fresh attempt rather than adding a separate retry prompt.
[Continuation appended to the user message]
Here are the notes you took of your work so far:
{summary}
[Last-chance continuation]
Here are the notes you took of your work so far:
{summary}
This is your last chance - you must provide answer at the end of this session.
C.6 Full-Book Baseline Prompt
The full-book baseline receives this single user message, with no system message. The fields contain the book title, supplied book text, and question; the book text is truncated from the right when it exceeds the input budget.
[User prompt]
You will be asked a question about the book titled "{book_title}". The complete text of the book is provided below between the markers. Use only this text to answer.
Title: {book_title}
=== BOOK TEXT START ===
{book_text}
=== BOOK TEXT END ===
Question: {question}
Think step by step: locate the relevant passages in the text above, reason about what they imply, then give your answer. First write out your reasoning, then end your response with a final answer on a line of exactly this form:
Final Answer: <a single concise phrase or sentence drawn from the text>
Put nothing after the Final Answer line. Do not use quotation marks around the answer.