Skip to main content

vtcode_core/compaction/
auto.rs

1//! Unified automatic compaction orchestration.
2//!
3//! This is the single entry point used by every runtime (the binary unified
4//! runloop and the `vtcode-core` `AgentRunner`) for *automatic* context
5//! compaction: when token pressure crosses the configured threshold, the
6//! conversation trace is compressed (provider-native or local LLM summary),
7//! a recoverable history artifact is written, and a session memory envelope is
8//! built and injected so the model keeps its conversational continuity.
9
10use std::path::Path;
11
12use anyhow::Result;
13
14use crate::compaction::memory_envelope::{
15    MemoryEnvelopePersistence, MemoryEnvelopePlacement, SessionMemoryEnvelopeUpdate,
16    dedup_repeated_file_reads_for_local_compaction, effective_compaction_threshold_with_reserve,
17    effective_context_budget, persist_memory_envelope_async_with_update, strip_existing_memory_envelope,
18};
19use crate::compaction::two_pass::fingerprint_prefix;
20use crate::compaction::{
21    CompactionConfig, CompactionParentContext, CompactionStrategy, ManualCompactionOptions, SUPPRESS_NONE,
22    build_local_compacted_history, build_summary_prompt, classify_suppress_reason,
23    compact_history_manual_with_parent_context, compacted_history_shrinks, manual_compaction_strategy,
24};
25use crate::exec::events::CompactionMode;
26use crate::llm::{
27    collect_single_response,
28    provider::{LLMProvider, LLMRequest, Message, ToolChoice},
29};
30use vtcode_config::loader::VTCodeConfig;
31
32/// Result of a successful automatic compaction pass.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct AutoCompactionOutcome {
35    pub original_len: usize,
36    pub compacted_len: usize,
37    pub mode: CompactionMode,
38    pub history_artifact_path: Option<String>,
39    /// The session memory envelope produced during compaction.
40    /// Used by the caller to write persistent checkpoints.
41    pub envelope: Option<crate::compaction::memory_envelope::SessionMemoryEnvelope>,
42}
43
44/// Inputs for [`auto_compact_messages`].
45pub struct AutoCompactionInput<'a> {
46    pub provider: &'a dyn LLMProvider,
47    pub model: &'a str,
48    pub session_id: &'a str,
49    pub workspace_root: &'a Path,
50    pub vt_cfg: Option<&'a VTCodeConfig>,
51    /// Current estimated token usage of the live history (before compaction).
52    pub current_token_usage: usize,
53    /// Output limit of the next request, excluding prompt/history overhead.
54    pub reserved_output_tokens: usize,
55    /// Files touched so far this session (enrich the memory envelope).
56    pub touched_files: &'a [String],
57    /// Engine configuration (thresholds, retention, summary prompt overrides).
58    pub engine_cfg: CompactionConfig,
59    /// Manual compaction options (instructions, max output, reasoning, verbosity).
60    pub manual_options: ManualCompactionOptions,
61    /// Where to place the injected memory envelope in the compacted history.
62    pub placement: MemoryEnvelopePlacement,
63    /// Prefire two-pass state (background NOTE₁ cache).
64    pub prefire: Option<&'a crate::compaction::PrefireState>,
65    /// Mutable auto-compaction suppression state. `SUPPRESS_NONE` allows
66    /// compaction; any other value gates automatic compaction until cleared
67    /// by success, model switch, or explicit `/compact`.
68    pub auto_compact_suppressed: &'a mut u8,
69    /// Force a pending soft-threshold compaction at the next outer turn
70    /// boundary. This is set only by the runloop boundary, never by a tool
71    /// loop, so no hidden model call is introduced mid-turn.
72    pub force_compaction: bool,
73    /// Live steering state to snapshot with the compaction envelope.
74    pub steering_update: Option<&'a SessionMemoryEnvelopeUpdate>,
75    /// Parent segment prefix for cache-safe forking (system prompt + ordered
76    /// tools from the live request envelope). When supplied, the local-summary
77    /// fork reuses the parent's cached prefix instead of re-paying full input
78    /// cost. Native strategies ignore it.
79    pub parent_context: Option<CompactionParentContext>,
80}
81
82impl AutoCompactionInput<'_> {
83    /// Check shared gates before a caller requests copy-on-write history.
84    pub(crate) fn should_compact(&self) -> bool {
85        if !self.vt_cfg.is_some_and(|cfg| cfg.agent.harness.auto_compaction_enabled)
86            || *self.auto_compact_suppressed != SUPPRESS_NONE
87        {
88            return false;
89        }
90        let Some(threshold) = effective_compaction_threshold_with_reserve(
91            self.vt_cfg,
92            self.provider,
93            self.model,
94            self.reserved_output_tokens,
95        ) else {
96            return false;
97        };
98        let window = effective_context_budget(self.vt_cfg, self.provider, self.model);
99        let threshold = crate::compaction::CompactionRoutePolicy::resolve(self.provider.name(), self.model)
100            .apply_threshold_cap(threshold, window);
101        self.force_compaction || self.current_token_usage >= threshold
102    }
103}
104
105/// Compress `history` in place when automatic compaction should fire.
106///
107/// Returns `None` when compaction is disabled, the history is below the trigger
108/// threshold, or the engine produced no change. On a successful pass the
109/// compacted history (with envelope injected) replaces `history` and an
110/// [`AutoCompactionOutcome`] is returned; the caller is responsible for
111/// emitting the `thread.compact_boundary` event and resetting token accounting.
112pub async fn auto_compact_messages(
113    input: AutoCompactionInput<'_>,
114    history: &mut Vec<Message>,
115) -> Result<Option<AutoCompactionOutcome>> {
116    if !input.should_compact() {
117        return Ok(None);
118    }
119    let AutoCompactionInput {
120        provider,
121        model,
122        session_id,
123        workspace_root,
124        vt_cfg,
125        touched_files,
126        engine_cfg,
127        manual_options,
128        placement,
129        prefire,
130        auto_compact_suppressed,
131        force_compaction,
132        steering_update,
133        parent_context,
134        ..
135    } = input;
136
137    // Use the same provider/session intersection as the trigger and preflight
138    // paths. This bounds local input and output, while native output remains
139    // provider-canonical and is not rewritten by the session budget.
140    let context_budget = match effective_context_budget(vt_cfg, provider, model) {
141        0 => None,
142        budget => Some(budget),
143    };
144    let mut compaction_input = history.clone();
145    strip_existing_memory_envelope(&mut compaction_input);
146    let original_history = compaction_input.clone();
147
148    let compaction_result: Result<Option<AutoCompactionOutcome>> = async {
149        // Try two-pass with prefire cache before falling back to single-pass.
150        if let Some(prefire_state) = prefire {
151            if let Some(mut compacted) = try_two_pass_with_prefire(
152                prefire_state,
153                provider,
154                model,
155                &original_history,
156                &engine_cfg,
157                context_budget,
158                parent_context.as_ref(),
159            )
160            .await?
161            {
162                let original_len = original_history.len();
163                let envelope = persist_memory_envelope_async_with_update(
164                    workspace_root,
165                    session_id,
166                    vt_cfg,
167                    &original_history,
168                    touched_files,
169                    &mut compacted,
170                    MemoryEnvelopePersistence::PersistToDisk,
171                    placement,
172                    None,
173                    steering_update,
174                )
175                .await?;
176                compacted =
177                    crate::compaction::bound_compacted_history_to_context(compacted, provider, model, context_budget);
178                let history_artifact_path = envelope.as_ref().and_then(|item| item.history_artifact_path.clone());
179                let compacted_len = compacted.len();
180                *history = compacted;
181                return Ok(Some(AutoCompactionOutcome {
182                    original_len,
183                    compacted_len,
184                    mode: CompactionMode::Local,
185                    history_artifact_path,
186                    envelope,
187                }));
188            }
189        }
190
191        // Route through the same strategy dispatch as the manual `/compact` command
192        // so every provider uses its correct native strategy (or falls back to a
193        // local LLM summary). Native outputs remain canonical replay windows, while
194        // local strategies provide the visible summary and session envelope.
195        let strategy = manual_compaction_strategy(provider, model);
196        let compaction_history = if matches!(strategy, CompactionStrategy::Local) {
197            dedup_repeated_file_reads_for_local_compaction(&compaction_input)
198        } else {
199            compaction_input.clone()
200        };
201
202        // Preserve the legacy small-segment short-circuit: skip tiny histories.
203        if !force_compaction
204            && !engine_cfg.always_summarize
205            && compaction_history.len() <= engine_cfg.keep_last_messages
206        {
207            return Ok(None);
208        }
209
210        let (mut compacted, mode) = compact_history_manual_with_parent_context(
211            provider,
212            model,
213            &compaction_history,
214            &engine_cfg,
215            &manual_options,
216            context_budget,
217            parent_context.as_ref(),
218        )
219        .await?;
220
221        if compacted == compaction_history {
222            return Ok(None);
223        }
224
225        // Never persist growth as a compaction: when the continuity tail
226        // already covers the history, the rebuild keeps every message and the
227        // envelope framing only adds more. Report already-compact instead.
228        if !compacted_history_shrinks(original_history.len(), compacted.len(), mode) {
229            return Ok(None);
230        }
231
232        let original_len = original_history.len();
233        // Memory-envelope persistence also injects a local system message. A
234        // native provider window is an opaque replay contract (for example an
235        // Anthropic signed compaction block must stay first), so persist the
236        // envelope against a private copy and leave the provider result intact.
237        let mut envelope_history = if mode == CompactionMode::Provider {
238            compacted.clone()
239        } else {
240            std::mem::take(&mut compacted)
241        };
242        let envelope = persist_memory_envelope_async_with_update(
243            workspace_root,
244            session_id,
245            vt_cfg,
246            &original_history,
247            touched_files,
248            &mut envelope_history,
249            MemoryEnvelopePersistence::PersistToDisk,
250            placement,
251            None,
252            steering_update,
253        )
254        .await?;
255        if mode == CompactionMode::Local {
256            compacted = envelope_history;
257            compacted =
258                crate::compaction::bound_compacted_history_to_context(compacted, provider, model, context_budget);
259        }
260        let history_artifact_path = envelope.as_ref().and_then(|item| item.history_artifact_path.clone());
261        let compacted_len = compacted.len();
262        *history = compacted;
263        Ok(Some(AutoCompactionOutcome {
264            original_len,
265            compacted_len,
266            mode,
267            history_artifact_path,
268            envelope,
269        }))
270    }
271    .await;
272
273    match &compaction_result {
274        Ok(Some(_)) => {
275            *auto_compact_suppressed = SUPPRESS_NONE;
276        }
277        Ok(None) => {}
278        Err(error) => {
279            let reason = classify_suppress_reason(&error.root_cause().to_string());
280            let new_state = reason.suppress_state();
281            // Only transition from SUPPRESS_NONE to a new state; don't downgrade
282            // a sticky/until-success suppression.
283            if *auto_compact_suppressed == SUPPRESS_NONE {
284                *auto_compact_suppressed = new_state;
285            }
286        }
287    }
288
289    compaction_result
290}
291
292/// Attempt two-pass compaction using a prefire-cached NOTE₁.
293///
294/// Returns `Some(compacted_history)` if the cache is valid and pass-2 produces
295/// a non-degenerate summary. `None` means the caller should fall back to
296/// single-pass compaction.
297///
298/// The pass-2 history already reuses the conversation prefix verbatim; the
299/// parent system/tools prefix is attached as well so the fork hits the
300/// provider prompt cache.
301async fn try_two_pass_with_prefire(
302    prefire: &crate::compaction::PrefireState,
303    provider: &dyn LLMProvider,
304    model: &str,
305    history: &[Message],
306    config: &CompactionConfig,
307    context_budget: Option<usize>,
308    parent: Option<&CompactionParentContext>,
309) -> Result<Option<Vec<Message>>> {
310    let cache = match prefire.take() {
311        Some(cache) => cache,
312        None => return Ok(None),
313    };
314
315    if cache.prefix_len == 0 || cache.prefix_len > history.len() {
316        return Ok(None);
317    }
318
319    if cache.model_slug != model {
320        return Ok(None);
321    }
322
323    let prefix = &history[..cache.prefix_len];
324    if fingerprint_prefix(prefix) != cache.fingerprint {
325        return Ok(None);
326    }
327
328    let tail = &history[cache.prefix_len..];
329    let prompt = build_summary_prompt(tail, &config.summary_prompt);
330    let pass2_history = crate::compaction::two_pass::build_two_pass_pass2_history(prefix, tail, &cache.note1, &prompt);
331
332    let request = LLMRequest {
333        messages: std::sync::Arc::new(pass2_history),
334        model: model.to_string(),
335        system_prompt: parent.and_then(|parent| parent.system_prompt.clone()),
336        tools: parent.and_then(|parent| parent.tools.clone()).filter(|tools| !tools.is_empty()),
337        tool_choice: Some(ToolChoice::none()),
338        ..Default::default()
339    };
340
341    let response = collect_single_response(provider, request).await?;
342    let note2 = response.content.unwrap_or_default().trim().to_string();
343
344    if note2.trim().is_empty() {
345        return Ok(None);
346    }
347
348    let effective_config =
349        crate::compaction::context_bounded_compaction_config(provider, model, history, config, context_budget);
350    let tail_target = crate::compaction::route_tail_target_tokens(provider, model, context_budget);
351    let compacted = build_local_compacted_history(
352        history,
353        &note2,
354        effective_config.retained_user_message_tokens,
355        effective_config.retained_user_messages,
356        true,
357        tail_target,
358    );
359
360    let compacted = crate::compaction::bound_compacted_history_to_context(compacted, provider, model, context_budget);
361    // A degenerate pass-2 (tail already covers the history) keeps every
362    // message and only adds framing; persisting it would grow the
363    // conversation, so fall back to single-pass instead.
364    if !compacted_history_shrinks(history.len(), compacted.len(), CompactionMode::Local) {
365        return Ok(None);
366    }
367
368    Ok(Some(compacted))
369}
370
371#[cfg(test)]
372mod tests;