trusty_code/agent_loop/compaction.rs
1//! Non-destructive context compaction trigger + summary generation (#2070).
2//!
3//! Why: vision spec §5.4 ("Non-Destructive Compaction + Last-Message Replay")
4//! calls for a token-efficiency middleware in the agent-loop message buffer:
5//! once the running transcript grows past a threshold, older turns should be
6//! collapsed into a short summary rather than sent verbatim on every
7//! subsequent request — while never discarding the original content. This
8//! module holds the two pure, transcript-shape-agnostic pieces of that
9//! mechanism — the trigger decision and the summary text — so
10//! `super::transcript::Transcript` (which owns the actual entries and their
11//! `compacted` flags) can stay focused on state management. Splitting the
12//! policy (when / what to say) from the mechanism (marking entries, replaying
13//! the last user turn) keeps both halves independently testable.
14//! What: [`CompactionConfig`] (the tunable threshold + active-zone size),
15//! [`estimate_tokens`] (a cheap chars/4 heuristic — no tokenizer dependency),
16//! [`should_compact`] (threshold check), and [`summarize_span`] (a
17//! deterministic one-line summary of a compacted message span, built from
18//! role counts and any tool names invoked — never an LLM call, so compaction
19//! never blocks the loop on network I/O).
20//! Test: `compaction::tests::*`.
21
22use crate::llm::ChatMessage;
23
24/// Tuning knobs for non-destructive context compaction (#2070, §5.4).
25///
26/// Why: A caller (production: `AgentLoop`; tests: unit tests exercising
27/// `Transcript` directly) needs to control both "how big is too big" and
28/// "how much of the recent conversation counts as the active work zone" —
29/// bundling them avoids two separate parameters threading through every call
30/// site.
31/// What: `token_threshold` is compared against the transcript's
32/// [`estimate_tokens`] total; `keep_last_messages` is the number of the most
33/// recent messages (the active work zone, §5.4 item 4) that are never
34/// eligible for compaction regardless of size.
35/// Test: `compaction::tests::default_is_sane`.
36#[derive(Debug, Clone, Copy)]
37pub struct CompactionConfig {
38 /// Estimated-token threshold that triggers compaction once exceeded.
39 pub token_threshold: usize,
40 /// Number of most-recent messages kept verbatim (the active work zone).
41 pub keep_last_messages: usize,
42}
43
44impl Default for CompactionConfig {
45 /// §5.4 gives no exact numbers; these defaults keep several full
46 /// tool-call round-trips (a handful of assistant+tool pairs) uncompacted
47 /// while triggering well before a typical model's context window is at
48 /// risk.
49 fn default() -> Self {
50 Self {
51 token_threshold: 6_000,
52 keep_last_messages: 6,
53 }
54 }
55}
56
57/// Estimate the token count of a text span using a cheap chars/4 heuristic.
58///
59/// Why: The agent loop has no tokenizer dependency today and adding one only
60/// to gate a compaction trigger would be disproportionate; the standard
61/// chars-divided-by-four rule of thumb is accurate enough to decide "is this
62/// transcript getting large", which is all the trigger needs.
63/// What: Returns `text.chars().count() / 4`, floor-divided.
64/// Test: `compaction::tests::estimate_tokens_uses_chars_over_four`.
65pub fn estimate_tokens(text: &str) -> usize {
66 text.chars().count() / 4
67}
68
69/// Sum the estimated token count across a span of messages.
70///
71/// Why: The trigger decision operates on the whole transcript's estimated
72/// size, not any single message. (#2261) `content` alone systematically
73/// undercounts coding sessions: `write_file`/`edit` tool calls carry their
74/// argument bodies (the actual file contents being written) in
75/// `ChatMessage.tool_calls[].function.arguments`, not `content` — an
76/// assistant turn that only calls a tool has `content: None` entirely. A
77/// real segment measured at 23,541 tokens (by this same heuristic applied to
78/// the full request body) never compacted under the old content-only sum
79/// because the default `token_threshold: 6_000` was never crossed.
80/// What: Sums `estimate_tokens` over each message's `content` PLUS, for
81/// every entry in `tool_calls`, `estimate_tokens` over that call's
82/// `function.arguments` JSON string. Role/name overhead is still
83/// intentionally ignored — the heuristic only needs to track growth trend,
84/// not byte-exact accounting.
85/// Test: `compaction::tests::estimate_total_tokens_sums_content`,
86/// `compaction::tests::estimate_total_tokens_sums_tool_call_arguments`.
87pub fn estimate_total_tokens(messages: &[ChatMessage]) -> usize {
88 messages
89 .iter()
90 .map(|m| {
91 let content_tokens = estimate_tokens(m.content.as_deref().unwrap_or_default());
92 let tool_call_tokens: usize = m
93 .tool_calls
94 .iter()
95 .flatten()
96 .map(|call| estimate_tokens(&call.function.arguments))
97 .sum();
98 content_tokens + tool_call_tokens
99 })
100 .sum()
101}
102
103/// Whether the transcript's estimated size warrants compaction.
104///
105/// Why: Centralises the threshold comparison so `Transcript::maybe_compact`
106/// reads as policy application, not arithmetic.
107/// What: `true` when `estimate_total_tokens(messages) > cfg.token_threshold`.
108/// Test: `compaction::tests::should_compact_respects_threshold`.
109pub fn should_compact(messages: &[ChatMessage], cfg: &CompactionConfig) -> bool {
110 estimate_total_tokens(messages) > cfg.token_threshold
111}
112
113/// Build a deterministic one-line summary of a span of messages being
114/// compacted (§5.4 item 2: "Replace their content with a one-line summary").
115///
116/// Why: A real LLM-generated summary would require a synchronous network
117/// call in the middle of the loop's turn boundary — expensive, and a new
118/// failure mode compaction must not introduce. A deterministic summary built
119/// from role counts and invoked tool names is cheap, always available, and
120/// gives the model (and a human auditor) enough of a pointer to know what was
121/// elided.
122/// What: Counts assistant/tool/other messages in `span` and collects the
123/// distinct tool names named in `tool` role messages (via their `name`
124/// field), rendering `"[compacted N earlier messages: A assistant turn(s),
125/// T tool call(s) (name1, name2, ...)]"`. Returns a fixed placeholder for an
126/// empty span (should not occur in practice, but must not panic).
127/// Test: `compaction::tests::summarize_span_counts_roles_and_tools`,
128/// `compaction::tests::summarize_span_handles_empty_span`.
129pub fn summarize_span(span: &[ChatMessage]) -> String {
130 if span.is_empty() {
131 return "[compacted 0 earlier messages]".to_string();
132 }
133
134 let assistant_count = span.iter().filter(|m| m.role == "assistant").count();
135 let mut tool_names: Vec<&str> = span
136 .iter()
137 .filter(|m| m.role == "tool")
138 .filter_map(|m| m.name.as_deref())
139 .collect();
140 tool_names.sort_unstable();
141 tool_names.dedup();
142
143 let tool_count = span.iter().filter(|m| m.role == "tool").count();
144 let tools_suffix = if tool_names.is_empty() {
145 String::new()
146 } else {
147 format!(" ({})", tool_names.join(", "))
148 };
149
150 format!(
151 "[compacted {} earlier message{}: {} assistant turn{}, {} tool call{}{}]",
152 span.len(),
153 plural_suffix(span.len()),
154 assistant_count,
155 plural_suffix(assistant_count),
156 tool_count,
157 plural_suffix(tool_count),
158 tools_suffix,
159 )
160}
161
162/// Return `"s"` unless `n == 1`, for readable pluralisation in the summary.
163fn plural_suffix(n: usize) -> &'static str {
164 if n == 1 { "" } else { "s" }
165}
166
167// ── Tests ─────────────────────────────────────────────────────────────────────
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 fn tool_msg(name: &str) -> ChatMessage {
174 ChatMessage::tool_result("call_1", name, "result")
175 }
176
177 #[test]
178 fn default_is_sane() {
179 let cfg = CompactionConfig::default();
180 assert!(cfg.token_threshold > 0);
181 assert!(cfg.keep_last_messages > 0);
182 }
183
184 #[test]
185 fn estimate_tokens_uses_chars_over_four() {
186 assert_eq!(estimate_tokens("abcd"), 1);
187 assert_eq!(estimate_tokens("abcdefgh"), 2);
188 assert_eq!(estimate_tokens(""), 0);
189 }
190
191 #[test]
192 fn estimate_total_tokens_sums_content() {
193 let messages = vec![
194 ChatMessage::user("abcd"),
195 ChatMessage::assistant("abcdefgh"),
196 ];
197 assert_eq!(estimate_total_tokens(&messages), 3);
198 }
199
200 /// A tool-call-only assistant turn (`content: None`, arguments carrying
201 /// the actual payload — e.g. a `write_file` body) contributes its
202 /// argument-string tokens to the total, not zero (#2261).
203 ///
204 /// Why: This is the exact bug #2261 reports: `estimate_total_tokens`
205 /// previously summed only `content`, so a transcript whose size lives
206 /// entirely in `write_file`/`edit` tool-call arguments was invisible to
207 /// the compaction trigger — `should_compact` never fired regardless of
208 /// how large those arguments grew.
209 /// What: Build an assistant message with `content: None` and one
210 /// `tool_calls` entry whose `function.arguments` is a known-length JSON
211 /// string; assert the total equals `estimate_tokens` of that arguments
212 /// string (content contributes 0 since it's `None`).
213 /// Test: this test.
214 #[test]
215 fn estimate_total_tokens_sums_tool_call_arguments() {
216 use crate::llm::{FunctionCall, ToolCall};
217
218 let arguments = r#"{"path":"src/main.rs","content":"fn main() {}"}"#;
219 let messages = vec![ChatMessage {
220 role: "assistant".into(),
221 content: None,
222 tool_calls: Some(vec![ToolCall {
223 id: "call_1".into(),
224 kind: "function".into(),
225 function: FunctionCall {
226 name: "write_file".into(),
227 arguments: arguments.into(),
228 },
229 }]),
230 tool_call_id: None,
231 name: None,
232 cache_control: None,
233 }];
234
235 assert_eq!(estimate_total_tokens(&messages), estimate_tokens(arguments));
236 }
237
238 /// A transcript whose size comes entirely from `write_file`/`edit`
239 /// tool-call arguments now crosses `should_compact`'s threshold, even
240 /// though every message's `content` is empty or trivial (#2261).
241 ///
242 /// Why: Reproduces the reported real-world case — a segment measured at
243 /// 23,541 real tokens that compacted zero times because the default
244 /// `token_threshold: 6_000` was gated on `content` alone.
245 /// What: Build a small transcript whose only assistant turn carries a
246 /// large `write_file` argument body (well over the default threshold)
247 /// and a matching `tool` result; assert `should_compact` now returns
248 /// `true` against `CompactionConfig::default()`.
249 /// Test: this test.
250 #[test]
251 fn should_compact_triggers_on_large_tool_call_arguments() {
252 use crate::llm::{FunctionCall, ToolCall};
253
254 // ~9,000 chars -> ~2,250 estimated tokens per call; three calls sum
255 // to ~6,750 tokens, comfortably clearing the 6,000-token default
256 // threshold via tool_calls alone, with every `content` field left
257 // `None`/trivial.
258 let big_content = "x".repeat(9_000);
259 let mut messages = vec![ChatMessage::system("s"), ChatMessage::user("do the thing")];
260 for i in 0..3 {
261 messages.push(ChatMessage {
262 role: "assistant".into(),
263 content: None,
264 tool_calls: Some(vec![ToolCall {
265 id: format!("call_{i}"),
266 kind: "function".into(),
267 function: FunctionCall {
268 name: "write_file".into(),
269 arguments: format!(r#"{{"content":"{big_content}"}}"#),
270 },
271 }]),
272 tool_call_id: None,
273 name: None,
274 cache_control: None,
275 });
276 messages.push(ChatMessage::tool_result(
277 format!("call_{i}"),
278 "write_file",
279 "ok",
280 ));
281 }
282
283 assert!(should_compact(&messages, &CompactionConfig::default()));
284 }
285
286 #[test]
287 fn should_compact_respects_threshold() {
288 let cfg = CompactionConfig {
289 token_threshold: 2,
290 keep_last_messages: 1,
291 };
292 let small = vec![ChatMessage::user("ab")];
293 let large = vec![ChatMessage::user("abcdefghijkl")];
294 assert!(!should_compact(&small, &cfg));
295 assert!(should_compact(&large, &cfg));
296 }
297
298 #[test]
299 fn summarize_span_counts_roles_and_tools() {
300 let span = vec![
301 ChatMessage::assistant("thinking"),
302 tool_msg("bash"),
303 tool_msg("read_file"),
304 tool_msg("bash"),
305 ];
306 let summary = summarize_span(&span);
307 assert!(summary.contains("4 earlier messages"));
308 assert!(summary.contains("1 assistant turn"));
309 assert!(summary.contains("3 tool calls"));
310 assert!(summary.contains("bash"));
311 assert!(summary.contains("read_file"));
312 }
313
314 #[test]
315 fn summarize_span_handles_empty_span() {
316 assert_eq!(summarize_span(&[]), "[compacted 0 earlier messages]");
317 }
318}