Skip to main content

harn_vm/orchestration/
compaction.rs

1//! Auto-compaction — transcript size management strategies.
2
3use std::rc::Rc;
4
5use crate::llm::{vm_call_llm_full, vm_value_to_json};
6use crate::value::{VmError, VmValue};
7
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub enum CompactStrategy {
10    Llm,
11    Truncate,
12    Custom,
13    ObservationMask,
14}
15
16pub fn parse_compact_strategy(value: &str) -> Result<CompactStrategy, VmError> {
17    match value {
18        "llm" => Ok(CompactStrategy::Llm),
19        "truncate" => Ok(CompactStrategy::Truncate),
20        "custom" => Ok(CompactStrategy::Custom),
21        "observation_mask" => Ok(CompactStrategy::ObservationMask),
22        other => Err(VmError::Runtime(format!(
23            "unknown compact_strategy '{other}' (expected 'llm', 'truncate', 'custom', or 'observation_mask')"
24        ))),
25    }
26}
27
28/// Configuration for automatic transcript compaction in agent loops.
29///
30/// Two-tier compaction:
31///   Tier 1 (`token_threshold` / `compact_strategy`): lightweight, deterministic
32///     observation masking that fires early. Masks verbose tool results while
33///     preserving assistant prose and error output.
34///   Tier 2 (`hard_limit_tokens` / `hard_limit_strategy`): aggressive LLM-powered
35///     summarization that fires when tier-1 alone isn't enough, typically as the
36///     transcript approaches the model's actual context window.
37#[derive(Clone, Debug)]
38pub struct AutoCompactConfig {
39    /// Tier-1 threshold: estimated tokens before lightweight compaction.
40    pub token_threshold: usize,
41    /// Maximum character length for a single tool result before microcompaction.
42    pub tool_output_max_chars: usize,
43    /// Number of recent messages to keep during compaction.
44    pub keep_last: usize,
45    /// Tier-1 strategy (default: ObservationMask).
46    pub compact_strategy: CompactStrategy,
47    /// Tier-2 threshold: fires when tier-1 result still exceeds this.
48    /// Typically set to ~75% of the model's actual context window.
49    /// When `None`, tier-2 is disabled.
50    pub hard_limit_tokens: Option<usize>,
51    /// Tier-2 strategy (default: Llm).
52    pub hard_limit_strategy: CompactStrategy,
53    /// Optional Harn callback used when a strategy is `custom`.
54    pub custom_compactor: Option<VmValue>,
55    /// Optional callback for domain-specific per-message masking during
56    /// observation mask compaction. Called with a list of archived messages,
57    /// returns a list of `Option<String>` — `Some(masked)` to override the
58    /// default mask for that message, `None` to use the default.
59    /// This lets the host (e.g. burin-code) inject AST outlines, file
60    /// summaries, etc. without putting language-specific logic in Harn.
61    pub mask_callback: Option<VmValue>,
62    /// Optional callback for per-tool-result compression. Called with
63    /// `{tool_name, output, max_chars}` and returns compressed output string.
64    /// When set, used INSTEAD of the built-in `microcompact_tool_output`.
65    /// This allows the pipeline to use LLM-based compression rather than
66    /// keyword heuristics.
67    pub compress_callback: Option<VmValue>,
68}
69
70impl Default for AutoCompactConfig {
71    fn default() -> Self {
72        Self {
73            token_threshold: 48_000,
74            tool_output_max_chars: 16_000,
75            keep_last: 12,
76            compact_strategy: CompactStrategy::ObservationMask,
77            hard_limit_tokens: None,
78            hard_limit_strategy: CompactStrategy::Llm,
79            custom_compactor: None,
80            mask_callback: None,
81            compress_callback: None,
82        }
83    }
84}
85
86/// Estimate token count from a list of JSON messages (chars / 4 heuristic).
87pub fn estimate_message_tokens(messages: &[serde_json::Value]) -> usize {
88    messages
89        .iter()
90        .map(|m| {
91            m.get("content")
92                .and_then(|c| c.as_str())
93                .map(|s| s.len())
94                .unwrap_or(0)
95        })
96        .sum::<usize>()
97        / 4
98}
99
100fn is_reasoning_or_tool_turn_message(message: &serde_json::Value) -> bool {
101    let role = message
102        .get("role")
103        .and_then(|value| value.as_str())
104        .unwrap_or_default();
105    role == "tool"
106        || message.get("tool_calls").is_some()
107        || message
108            .get("reasoning")
109            .map(|value| !value.is_null())
110            .unwrap_or(false)
111}
112
113fn find_prev_user_boundary(messages: &[serde_json::Value], start: usize) -> Option<usize> {
114    (0..=start)
115        .rev()
116        .find(|idx| messages[*idx].get("role").and_then(|value| value.as_str()) == Some("user"))
117}
118
119/// Microcompact a tool result: if it exceeds `max_chars`, keep the first and
120/// last portions with a snip marker in between.
121pub fn microcompact_tool_output(output: &str, max_chars: usize) -> String {
122    if output.len() <= max_chars || max_chars < 200 {
123        return output.to_string();
124    }
125    let diagnostic_lines = output
126        .lines()
127        .filter(|line| {
128            let trimmed = line.trim();
129            let lower = trimmed.to_lowercase();
130            let has_file_line = {
131                let bytes = trimmed.as_bytes();
132                let mut i = 0;
133                let mut found_colon = false;
134                while i < bytes.len() {
135                    if bytes[i] == b':' {
136                        found_colon = true;
137                        break;
138                    }
139                    i += 1;
140                }
141                found_colon && i + 1 < bytes.len() && bytes[i + 1].is_ascii_digit()
142            };
143            let has_strong_keyword =
144                trimmed.contains("FAIL") || trimmed.contains("panic") || trimmed.contains("Panic");
145            let has_weak_keyword = trimmed.contains("error")
146                || trimmed.contains("undefined")
147                || trimmed.contains("expected")
148                || trimmed.contains("got")
149                || lower.contains("cannot find")
150                || lower.contains("not found")
151                || lower.contains("no such")
152                || lower.contains("unresolved")
153                || lower.contains("missing")
154                || lower.contains("declared but not used")
155                || lower.contains("unused")
156                || lower.contains("mismatch");
157            let positional = lower.contains(" error ")
158                || lower.starts_with("error:")
159                || lower.starts_with("warning:")
160                || lower.starts_with("note:")
161                || lower.contains("panic:");
162            has_strong_keyword || (has_file_line && has_weak_keyword) || positional
163        })
164        .take(32)
165        .collect::<Vec<_>>();
166    if !diagnostic_lines.is_empty() {
167        let diagnostics = diagnostic_lines.join("\n");
168        let budget = max_chars.saturating_sub(diagnostics.len() + 64);
169        let keep = budget / 2;
170        if keep >= 80 && output.len() > keep * 2 {
171            let head = snap_to_line_end(output, keep);
172            let tail = snap_to_line_start(output, output.len().saturating_sub(keep));
173            return format!(
174                "{head}\n\n[diagnostic lines preserved]\n{diagnostics}\n\n[... output compacted ...]\n\n{tail}"
175            );
176        }
177    }
178    let keep = max_chars / 2;
179    let head = snap_to_line_end(output, keep);
180    let tail = snap_to_line_start(output, output.len().saturating_sub(keep));
181    let snipped = output.len().saturating_sub(head.len() + tail.len());
182    format!("{head}\n\n[... {snipped} characters snipped ...]\n\n{tail}")
183}
184
185/// Invoke the compress_callback to compress a tool result via pipeline-defined
186/// logic (typically an LLM call). Returns the compressed output, or falls back
187/// to `microcompact_tool_output` on error.
188pub(crate) async fn invoke_compress_callback(
189    callback: &VmValue,
190    tool_name: &str,
191    output: &str,
192    max_chars: usize,
193) -> String {
194    let VmValue::Closure(closure) = callback.clone() else {
195        return microcompact_tool_output(output, max_chars);
196    };
197    let mut vm = match crate::vm::clone_async_builtin_child_vm() {
198        Some(vm) => vm,
199        None => return microcompact_tool_output(output, max_chars),
200    };
201    let args_dict = VmValue::Dict(Rc::new({
202        let mut dict = std::collections::BTreeMap::new();
203        dict.insert(
204            "tool_name".to_string(),
205            VmValue::String(Rc::from(tool_name)),
206        );
207        dict.insert("output".to_string(), VmValue::String(Rc::from(output)));
208        dict.insert("max_chars".to_string(), VmValue::Int(max_chars as i64));
209        dict
210    }));
211    match vm.call_closure_pub(&closure, &[args_dict], &[]).await {
212        Ok(VmValue::String(s)) if !s.is_empty() => s.to_string(),
213        _ => microcompact_tool_output(output, max_chars),
214    }
215}
216
217/// Snap a byte offset to the nearest preceding line boundary (end of a complete line).
218/// Returns the substring from the start up to and including the last complete line
219/// that fits within `max_bytes`. Never cuts mid-line.
220fn snap_to_line_end(s: &str, max_bytes: usize) -> &str {
221    if max_bytes >= s.len() {
222        return s;
223    }
224    let search_end = s.floor_char_boundary(max_bytes);
225    match s[..search_end].rfind('\n') {
226        Some(pos) => &s[..pos + 1],
227        None => &s[..search_end], // single long line — fall back to char boundary
228    }
229}
230
231/// Snap a byte offset to the nearest following line boundary (start of a complete line).
232/// Returns the substring from the first complete line at or after `start_byte`.
233/// Never cuts mid-line.
234fn snap_to_line_start(s: &str, start_byte: usize) -> &str {
235    if start_byte == 0 {
236        return s;
237    }
238    let search_start = s.ceil_char_boundary(start_byte);
239    if search_start >= s.len() {
240        return "";
241    }
242    match s[search_start..].find('\n') {
243        Some(pos) => {
244            let line_start = search_start + pos + 1;
245            if line_start < s.len() {
246                &s[line_start..]
247            } else {
248                &s[search_start..]
249            }
250        }
251        None => &s[search_start..], // already at start of last line
252    }
253}
254
255fn format_compaction_messages(messages: &[serde_json::Value]) -> String {
256    messages
257        .iter()
258        .map(|msg| {
259            let role = msg
260                .get("role")
261                .and_then(|v| v.as_str())
262                .unwrap_or("user")
263                .to_uppercase();
264            let content = msg
265                .get("content")
266                .and_then(|v| v.as_str())
267                .unwrap_or_default();
268            format!("{role}: {content}")
269        })
270        .collect::<Vec<_>>()
271        .join("\n")
272}
273
274fn truncate_compaction_summary(
275    old_messages: &[serde_json::Value],
276    archived_count: usize,
277) -> String {
278    truncate_compaction_summary_with_context(old_messages, archived_count, false)
279}
280
281fn truncate_compaction_summary_with_context(
282    old_messages: &[serde_json::Value],
283    archived_count: usize,
284    is_llm_fallback: bool,
285) -> String {
286    let per_msg_limit = 500_usize;
287    let summary_parts: Vec<String> = old_messages
288        .iter()
289        .filter_map(|m| {
290            let role = m.get("role")?.as_str()?;
291            let content = m.get("content")?.as_str()?;
292            if content.is_empty() {
293                return None;
294            }
295            let truncated = if content.len() > per_msg_limit {
296                format!(
297                    "{}... [truncated from {} chars]",
298                    &content[..content.floor_char_boundary(per_msg_limit)],
299                    content.len()
300                )
301            } else {
302                content.to_string()
303            };
304            Some(format!("[{role}] {truncated}"))
305        })
306        .take(15)
307        .collect();
308    let header = if is_llm_fallback {
309        format!(
310            "[auto-compact fallback: LLM summarizer returned empty; {archived_count} older messages abbreviated to ~{per_msg_limit} chars each]"
311        )
312    } else {
313        format!("[auto-compacted {archived_count} older messages via truncate strategy]")
314    };
315    format!(
316        "{header}\n{}{}",
317        summary_parts.join("\n"),
318        if archived_count > 15 {
319            format!("\n... and {} more", archived_count - 15)
320        } else {
321            String::new()
322        }
323    )
324}
325
326fn compact_summary_text_from_value(value: &VmValue) -> Result<String, VmError> {
327    if let Some(map) = value.as_dict() {
328        if let Some(summary) = map.get("summary").or_else(|| map.get("text")) {
329            return Ok(summary.display());
330        }
331    }
332    match value {
333        VmValue::String(text) => Ok(text.to_string()),
334        VmValue::Nil => Ok(String::new()),
335        _ => serde_json::to_string_pretty(&vm_value_to_json(value))
336            .map_err(|e| VmError::Runtime(format!("custom compactor encode error: {e}"))),
337    }
338}
339
340async fn llm_compaction_summary(
341    old_messages: &[serde_json::Value],
342    archived_count: usize,
343    llm_opts: &crate::llm::api::LlmCallOptions,
344) -> Result<String, VmError> {
345    let mut compact_opts = llm_opts.clone();
346    let formatted = format_compaction_messages(old_messages);
347    compact_opts.system = None;
348    compact_opts.transcript_summary = None;
349    compact_opts.native_tools = None;
350    compact_opts.tool_choice = None;
351    compact_opts.response_format = None;
352    compact_opts.json_schema = None;
353    compact_opts.messages = vec![serde_json::json!({
354        "role": "user",
355        "content": format!(
356            "Summarize these archived conversation messages for a follow-on coding agent. Preserve goals, constraints, decisions, completed tool work, unresolved issues, and next actions. Output only the summary text.\n\nArchived message count: {archived_count}\n\nConversation:\n{formatted}"
357        ),
358    })];
359    let result = vm_call_llm_full(&compact_opts).await?;
360    let summary = result.text.trim();
361    if summary.is_empty() {
362        Ok(truncate_compaction_summary_with_context(
363            old_messages,
364            archived_count,
365            true,
366        ))
367    } else {
368        Ok(format!(
369            "[auto-compacted {archived_count} older messages]\n{summary}"
370        ))
371    }
372}
373
374async fn custom_compaction_summary(
375    old_messages: &[serde_json::Value],
376    archived_count: usize,
377    callback: &VmValue,
378) -> Result<String, VmError> {
379    let Some(VmValue::Closure(closure)) = Some(callback.clone()) else {
380        return Err(VmError::Runtime(
381            "compact_callback must be a closure when compact_strategy is 'custom'".to_string(),
382        ));
383    };
384    let mut vm = crate::vm::clone_async_builtin_child_vm().ok_or_else(|| {
385        VmError::Runtime(
386            "custom transcript compaction requires an async builtin VM context".to_string(),
387        )
388    })?;
389    let messages_vm = VmValue::List(Rc::new(
390        old_messages
391            .iter()
392            .map(crate::stdlib::json_to_vm_value)
393            .collect(),
394    ));
395    let result = vm.call_closure_pub(&closure, &[messages_vm], &[]).await;
396    let summary = compact_summary_text_from_value(&result?)?;
397    if summary.trim().is_empty() {
398        Ok(truncate_compaction_summary(old_messages, archived_count))
399    } else {
400        Ok(format!(
401            "[auto-compacted {archived_count} older messages]\n{summary}"
402        ))
403    }
404}
405
406/// Check whether a tool-result string should be preserved verbatim during
407/// observation masking. Uses content length as the primary heuristic:
408/// short results (< 500 chars) are kept since they're typically error messages,
409/// status lines, or concise answers that are cheap to retain and risky to mask.
410/// Long results are masked to save context budget.
411fn content_should_preserve(content: &str) -> bool {
412    content.len() < 500
413}
414
415/// Default per-message masking for tool results.
416fn default_mask_tool_result(role: &str, content: &str) -> String {
417    let first_line = content.lines().next().unwrap_or(content);
418    let line_count = content.lines().count();
419    let char_count = content.len();
420    if line_count <= 3 {
421        format!("[{role}] {content}")
422    } else {
423        let preview = &first_line[..first_line.len().min(120)];
424        format!("[{role}] {preview}... [{line_count} lines, {char_count} chars masked]")
425    }
426}
427
428/// Deterministic observation-mask compaction.
429#[cfg(test)]
430pub(crate) fn observation_mask_compaction(
431    old_messages: &[serde_json::Value],
432    archived_count: usize,
433) -> String {
434    observation_mask_compaction_with_callback(old_messages, archived_count, None)
435}
436
437fn observation_mask_compaction_with_callback(
438    old_messages: &[serde_json::Value],
439    archived_count: usize,
440    mask_results: Option<&[Option<String>]>,
441) -> String {
442    let mut parts = Vec::new();
443    parts.push(format!(
444        "[auto-compacted {archived_count} older messages via observation masking]"
445    ));
446    for (idx, msg) in old_messages.iter().enumerate() {
447        let role = msg.get("role").and_then(|v| v.as_str()).unwrap_or("user");
448        let content = msg
449            .get("content")
450            .and_then(|v| v.as_str())
451            .unwrap_or_default();
452        if content.is_empty() {
453            continue;
454        }
455        if role == "assistant" {
456            parts.push(format!("[assistant] {content}"));
457            continue;
458        }
459        if content_should_preserve(content) {
460            parts.push(format!("[{role}] {content}"));
461        } else if let Some(Some(custom)) = mask_results.and_then(|r| r.get(idx)) {
462            parts.push(custom.clone());
463        } else {
464            parts.push(default_mask_tool_result(role, content));
465        }
466    }
467    parts.join("\n")
468}
469
470/// Invoke the mask_callback to get per-message custom masks.
471async fn invoke_mask_callback(
472    callback: &VmValue,
473    old_messages: &[serde_json::Value],
474) -> Result<Vec<Option<String>>, VmError> {
475    let VmValue::Closure(closure) = callback.clone() else {
476        return Err(VmError::Runtime(
477            "mask_callback must be a closure".to_string(),
478        ));
479    };
480    let mut vm = crate::vm::clone_async_builtin_child_vm().ok_or_else(|| {
481        VmError::Runtime("mask_callback requires an async builtin VM context".to_string())
482    })?;
483    let messages_vm = VmValue::List(Rc::new(
484        old_messages
485            .iter()
486            .map(crate::stdlib::json_to_vm_value)
487            .collect(),
488    ));
489    let result = vm.call_closure_pub(&closure, &[messages_vm], &[]).await?;
490    let list = match result {
491        VmValue::List(items) => items,
492        _ => return Ok(vec![None; old_messages.len()]),
493    };
494    Ok(list
495        .iter()
496        .map(|v| match v {
497            VmValue::String(s) => Some(s.to_string()),
498            VmValue::Nil => None,
499            _ => None,
500        })
501        .collect())
502}
503
504/// Apply a single compaction strategy to a list of archived messages.
505async fn apply_compaction_strategy(
506    strategy: &CompactStrategy,
507    old_messages: &[serde_json::Value],
508    archived_count: usize,
509    llm_opts: Option<&crate::llm::api::LlmCallOptions>,
510    custom_compactor: Option<&VmValue>,
511    mask_callback: Option<&VmValue>,
512) -> Result<String, VmError> {
513    match strategy {
514        CompactStrategy::Truncate => Ok(truncate_compaction_summary(old_messages, archived_count)),
515        CompactStrategy::Llm => {
516            llm_compaction_summary(
517                old_messages,
518                archived_count,
519                llm_opts.ok_or_else(|| {
520                    VmError::Runtime(
521                        "LLM transcript compaction requires active LLM call options".to_string(),
522                    )
523                })?,
524            )
525            .await
526        }
527        CompactStrategy::Custom => {
528            custom_compaction_summary(
529                old_messages,
530                archived_count,
531                custom_compactor.ok_or_else(|| {
532                    VmError::Runtime(
533                        "compact_callback is required when compact_strategy is 'custom'"
534                            .to_string(),
535                    )
536                })?,
537            )
538            .await
539        }
540        CompactStrategy::ObservationMask => {
541            let mask_results = if let Some(cb) = mask_callback {
542                Some(invoke_mask_callback(cb, old_messages).await?)
543            } else {
544                None
545            };
546            Ok(observation_mask_compaction_with_callback(
547                old_messages,
548                archived_count,
549                mask_results.as_deref(),
550            ))
551        }
552    }
553}
554
555/// Auto-compact a message list in place using two-tier compaction.
556pub(crate) async fn auto_compact_messages(
557    messages: &mut Vec<serde_json::Value>,
558    config: &AutoCompactConfig,
559    llm_opts: Option<&crate::llm::api::LlmCallOptions>,
560) -> Result<Option<String>, VmError> {
561    if messages.len() <= config.keep_last {
562        return Ok(None);
563    }
564    let original_split = messages.len().saturating_sub(config.keep_last);
565    let mut split_at = original_split;
566    // Snap back to a user-role boundary so the kept suffix begins at a clean
567    // turn. OpenAI-compatible APIs reject tool results orphaned from their
568    // assistant request, so splitting mid-turn corrupts the transcript.
569    while split_at > 0
570        && messages[split_at]
571            .get("role")
572            .and_then(|r| r.as_str())
573            .is_none_or(|r| r != "user")
574    {
575        split_at -= 1;
576    }
577    // Fall back to the naive split (e.g. tool-heavy transcripts with the sole
578    // user message at index 0) rather than skipping compaction entirely.
579    if split_at == 0 {
580        split_at = original_split;
581    }
582    if let Some(volatile_start) = messages[split_at..]
583        .iter()
584        .position(is_reasoning_or_tool_turn_message)
585        .map(|offset| split_at + offset)
586    {
587        if let Some(boundary) = volatile_start
588            .checked_sub(1)
589            .and_then(|idx| find_prev_user_boundary(messages, idx))
590            .filter(|boundary| *boundary > 0)
591        {
592            split_at = boundary;
593        }
594    }
595    if split_at == 0 {
596        return Ok(None);
597    }
598    let old_messages: Vec<_> = messages.drain(..split_at).collect();
599    let archived_count = old_messages.len();
600
601    let mut summary = apply_compaction_strategy(
602        &config.compact_strategy,
603        &old_messages,
604        archived_count,
605        llm_opts,
606        config.custom_compactor.as_ref(),
607        config.mask_callback.as_ref(),
608    )
609    .await?;
610
611    if let Some(hard_limit) = config.hard_limit_tokens {
612        let summary_msg = serde_json::json!({"role": "user", "content": &summary});
613        let mut estimate_msgs = vec![summary_msg];
614        estimate_msgs.extend_from_slice(messages.as_slice());
615        let estimated = estimate_message_tokens(&estimate_msgs);
616        if estimated > hard_limit {
617            let tier1_as_messages = vec![serde_json::json!({
618                "role": "user",
619                "content": summary,
620            })];
621            summary = apply_compaction_strategy(
622                &config.hard_limit_strategy,
623                &tier1_as_messages,
624                archived_count,
625                llm_opts,
626                config.custom_compactor.as_ref(),
627                None,
628            )
629            .await?;
630        }
631    }
632
633    messages.insert(
634        0,
635        serde_json::json!({
636            "role": "user",
637            "content": summary,
638        }),
639    );
640    Ok(Some(summary))
641}
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646
647    #[test]
648    fn microcompact_short_output_unchanged() {
649        let output = "line1\nline2\nline3\n";
650        assert_eq!(microcompact_tool_output(output, 1000), output);
651    }
652
653    #[test]
654    fn microcompact_snaps_to_line_boundaries() {
655        let lines: Vec<String> = (0..20)
656            .map(|i| format!("line {:02} content here", i))
657            .collect();
658        let output = lines.join("\n");
659        let result = microcompact_tool_output(&output, 200);
660        assert!(result.contains("[... "), "should have snip marker");
661        let parts: Vec<&str> = result.split("\n\n[... ").collect();
662        assert!(parts.len() >= 2, "should split at marker");
663        let head = parts[0];
664        for line in head.lines() {
665            assert!(
666                line.starts_with("line "),
667                "head line should be complete: {line}"
668            );
669        }
670    }
671
672    #[test]
673    fn microcompact_preserves_diagnostic_lines_with_line_boundaries() {
674        let mut lines = Vec::new();
675        for i in 0..50 {
676            lines.push(format!("verbose output line {i}"));
677        }
678        lines.push("src/main.rs:42: error: cannot find value".to_string());
679        for i in 50..100 {
680            lines.push(format!("verbose output line {i}"));
681        }
682        let output = lines.join("\n");
683        let result = microcompact_tool_output(&output, 600);
684        assert!(result.contains("cannot find value"), "diagnostic preserved");
685        assert!(
686            result.contains("[diagnostic lines preserved]"),
687            "has diagnostic marker"
688        );
689    }
690
691    #[test]
692    fn snap_to_line_end_finds_newline() {
693        let s = "line1\nline2\nline3\nline4\n";
694        let head = snap_to_line_end(s, 12);
695        assert!(head.ends_with('\n'), "should end at newline");
696        assert!(head.contains("line1"));
697    }
698
699    #[test]
700    fn snap_to_line_start_finds_newline() {
701        let s = "line1\nline2\nline3\nline4\n";
702        let tail = snap_to_line_start(s, 12);
703        assert!(
704            tail.starts_with("line"),
705            "should start at line boundary: {tail}"
706        );
707    }
708
709    #[test]
710    fn auto_compact_preserves_reasoning_tool_suffix() {
711        let mut messages = vec![
712            serde_json::json!({"role": "user", "content": "old task"}),
713            serde_json::json!({"role": "assistant", "content": "old reply"}),
714            serde_json::json!({"role": "user", "content": "new task"}),
715            serde_json::json!({
716                "role": "assistant",
717                "content": "",
718                "reasoning": "think first",
719                "tool_calls": [{
720                    "id": "call_1",
721                    "type": "function",
722                    "function": {"name": "read", "arguments": "{\"path\":\"foo.rs\"}"}
723                }],
724            }),
725            serde_json::json!({"role": "tool", "tool_call_id": "call_1", "content": "file"}),
726        ];
727        let config = AutoCompactConfig {
728            keep_last: 2,
729            ..Default::default()
730        };
731
732        let runtime = tokio::runtime::Builder::new_current_thread()
733            .enable_all()
734            .build()
735            .expect("runtime");
736        let summary = runtime
737            .block_on(auto_compact_messages(&mut messages, &config, None))
738            .expect("compaction succeeds");
739
740        assert!(summary.is_some());
741        assert_eq!(messages[1]["role"], "user");
742        assert_eq!(messages[2]["role"], "assistant");
743        assert_eq!(messages[2]["tool_calls"][0]["id"], "call_1");
744        assert_eq!(messages[3]["role"], "tool");
745        assert_eq!(messages[3]["tool_call_id"], "call_1");
746    }
747}