claude_agent/session/
compact.rs

1//! Context Compaction (Claude Code CLI compatible)
2//!
3//! Summarizes the entire conversation when context exceeds threshold.
4//! Ported from Claude Code CLI's compact implementation for full compatibility.
5
6use serde::{Deserialize, Serialize};
7
8use super::state::{Session, SessionMessage};
9use super::types::CompactRecord;
10use super::{SessionError, SessionResult};
11use crate::client::DEFAULT_SMALL_MODEL;
12use crate::types::{CompactResult, ContentBlock, DEFAULT_COMPACT_THRESHOLD, Role};
13
14/// Strategy for context compaction.
15///
16/// Controls when and how conversation history is summarized to fit within
17/// context limits. The `keep_coding_instructions` flag determines whether
18/// detailed coding information (code snippets, file changes, function
19/// signatures) is preserved in summaries.
20///
21/// This flag mirrors `OutputStyle::keep_coding_instructions` for consistency.
22#[derive(Clone, Debug, Serialize, Deserialize)]
23pub struct CompactStrategy {
24    pub enabled: bool,
25    pub threshold_percent: f32,
26    pub summary_model: String,
27    pub max_summary_tokens: u32,
28    /// When true, includes detailed coding information in summaries:
29    /// - Full code snippets
30    /// - File names and changes
31    /// - Function signatures
32    /// - Error details and fixes
33    ///
34    /// When false, creates a minimal summary focusing on:
35    /// - Primary request and intent
36    /// - Key decisions made
37    /// - Current work status
38    /// - Next steps
39    ///
40    /// This mirrors `OutputStyle::keep_coding_instructions` for API consistency.
41    #[serde(default = "default_keep_coding_instructions")]
42    pub keep_coding_instructions: bool,
43    /// Optional custom instructions to append to the compact prompt.
44    /// These are user-provided instructions for customizing the summary.
45    #[serde(default)]
46    pub custom_instructions: Option<String>,
47}
48
49fn default_keep_coding_instructions() -> bool {
50    true
51}
52
53impl Default for CompactStrategy {
54    fn default() -> Self {
55        Self {
56            enabled: true,
57            threshold_percent: DEFAULT_COMPACT_THRESHOLD,
58            summary_model: DEFAULT_SMALL_MODEL.to_string(),
59            max_summary_tokens: 4000,
60            keep_coding_instructions: true,
61            custom_instructions: None,
62        }
63    }
64}
65
66impl CompactStrategy {
67    pub fn disabled() -> Self {
68        Self {
69            enabled: false,
70            ..Default::default()
71        }
72    }
73
74    pub fn with_threshold(mut self, percent: f32) -> Self {
75        self.threshold_percent = percent.clamp(0.5, 0.95);
76        self
77    }
78
79    pub fn with_model(mut self, model: impl Into<String>) -> Self {
80        self.summary_model = model.into();
81        self
82    }
83
84    /// Set whether to keep detailed coding information in summaries.
85    ///
86    /// This mirrors the `keep_coding_instructions` flag in `OutputStyle`.
87    pub fn with_keep_coding_instructions(mut self, keep: bool) -> Self {
88        self.keep_coding_instructions = keep;
89        self
90    }
91
92    /// Set custom instructions for the compact prompt.
93    pub fn with_custom_instructions(mut self, instructions: impl Into<String>) -> Self {
94        self.custom_instructions = Some(instructions.into());
95        self
96    }
97
98    /// Create a CompactStrategy that inherits coding instruction preference from OutputStyle.
99    #[cfg(feature = "cli-integration")]
100    pub fn from_output_style(style: &crate::output_style::OutputStyle) -> Self {
101        Self {
102            keep_coding_instructions: style.keep_coding_instructions,
103            ..Default::default()
104        }
105    }
106}
107
108pub struct CompactExecutor {
109    strategy: CompactStrategy,
110}
111
112impl CompactExecutor {
113    pub fn new(strategy: CompactStrategy) -> Self {
114        Self { strategy }
115    }
116
117    pub fn needs_compact(&self, current_tokens: u64, max_tokens: u64) -> bool {
118        if !self.strategy.enabled {
119            return false;
120        }
121        let threshold = (max_tokens as f32 * self.strategy.threshold_percent) as u64;
122        current_tokens >= threshold
123    }
124
125    pub fn prepare_compact(&self, session: &Session) -> SessionResult<PreparedCompact> {
126        if !self.strategy.enabled {
127            return Err(SessionError::Compact {
128                message: "Compact is disabled".to_string(),
129            });
130        }
131
132        let messages = session.get_current_branch();
133        if messages.is_empty() {
134            return Ok(PreparedCompact::NotNeeded);
135        }
136
137        let summary_prompt = self.format_for_summary(&messages);
138
139        Ok(PreparedCompact::Ready {
140            summary_prompt,
141            message_count: messages.len(),
142        })
143    }
144
145    pub fn apply_compact(&self, session: &mut Session, summary: String) -> CompactResult {
146        let original_count = session.messages.len();
147
148        let removed_chars: usize = session
149            .messages
150            .iter()
151            .map(|m| {
152                m.content
153                    .iter()
154                    .filter_map(|c| c.as_text())
155                    .map(|t| t.len())
156                    .sum::<usize>()
157            })
158            .sum();
159        let saved_tokens = (removed_chars / 4) as u64;
160
161        session.messages.clear();
162        session.summary = Some(summary.clone());
163
164        let summary_msg = SessionMessage::user(vec![ContentBlock::text(format!(
165            "[Previous conversation summary]\n\n{}",
166            summary
167        ))])
168        .as_compact_summary();
169
170        session.add_message(summary_msg);
171
172        CompactResult::Compacted {
173            original_count,
174            new_count: 1,
175            saved_tokens: saved_tokens as usize,
176            summary,
177        }
178    }
179
180    pub fn record_compact(&self, session: &mut Session, result: &CompactResult) {
181        if let CompactResult::Compacted {
182            original_count,
183            new_count,
184            saved_tokens,
185            summary,
186        } = result
187        {
188            let record = CompactRecord::new(session.id)
189                .with_counts(*original_count, *new_count)
190                .with_summary(summary.clone())
191                .with_saved_tokens(*saved_tokens);
192            session.record_compact(record);
193        }
194    }
195
196    fn format_for_summary(&self, messages: &[&SessionMessage]) -> String {
197        let mut formatted = String::new();
198
199        // Select prompt based on keep_coding_instructions flag
200        let prompt = if self.strategy.keep_coding_instructions {
201            COMPACTION_PROMPT_FULL
202        } else {
203            COMPACTION_PROMPT_MINIMAL
204        };
205
206        formatted.push_str(prompt);
207
208        // Append custom instructions if provided
209        if let Some(ref instructions) = self.strategy.custom_instructions {
210            formatted.push_str("\n\n");
211            formatted.push_str("# Custom Summary Instructions\n\n");
212            formatted.push_str(instructions);
213        }
214
215        formatted.push_str("\n\n---\n\n");
216        formatted.push_str("# Conversation to summarize:\n\n");
217
218        for msg in messages {
219            let role = match msg.role {
220                Role::User => "Human",
221                Role::Assistant => "Assistant",
222            };
223
224            formatted.push_str(&format!("**{}**:\n", role));
225
226            for block in &msg.content {
227                if let Some(text) = block.as_text() {
228                    // Truncate very long messages but keep more context than before
229                    let display_text = if text.len() > 8000 {
230                        format!(
231                            "{}... [truncated, {} chars total]",
232                            &text[..8000],
233                            text.len()
234                        )
235                    } else {
236                        text.to_string()
237                    };
238                    formatted.push_str(&display_text);
239                    formatted.push('\n');
240                }
241            }
242            formatted.push('\n');
243        }
244
245        formatted
246    }
247
248    pub fn strategy(&self) -> &CompactStrategy {
249        &self.strategy
250    }
251}
252
253/// Full compaction prompt with detailed coding information.
254/// Ported from Claude Code CLI for full compatibility.
255const COMPACTION_PROMPT_FULL: &str = r#"Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
256
257This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
258
259Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
260
2611. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
262   - The user's explicit requests and intents
263   - Your approach to addressing the user's requests
264   - Key decisions, technical concepts and code patterns
265   - Specific details like:
266     - file names
267     - full code snippets
268     - function signatures
269     - file edits
270   - Errors that you ran into and how you fixed them
271   - Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
272
2732. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
274
275Your summary should include the following sections:
276
2771. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
278
2792. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
280
2813. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
282
2834. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
284
2855. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
286
2876. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
288
2897. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
290
2918. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
292
2939. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
294   If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
295
296Here's an example of how your output should be structured:
297
298<example>
299<analysis>
300[Your thought process, ensuring all points are covered thoroughly and accurately]
301</analysis>
302
303<summary>
3041. Primary Request and Intent:
305   [Detailed description]
306
3072. Key Technical Concepts:
308   - [Concept 1]
309   - [Concept 2]
310   - [...]
311
3123. Files and Code Sections:
313   - [File Name 1]
314      - [Summary of why this file is important]
315      - [Summary of the changes made to this file, if any]
316      - [Important Code Snippet]
317   - [File Name 2]
318      - [Important Code Snippet]
319   - [...]
320
3214. Errors and fixes:
322    - [Detailed description of error 1]:
323      - [How you fixed the error]
324      - [User feedback on the error if any]
325    - [...]
326
3275. Problem Solving:
328   [Description of solved problems and ongoing troubleshooting]
329
3306. All user messages:
331    - [Detailed non tool use user message]
332    - [...]
333
3347. Pending Tasks:
335   - [Task 1]
336   - [Task 2]
337   - [...]
338
3398. Current Work:
340   [Precise description of current work]
341
3429. Optional Next Step:
343   [Optional Next step to take]
344</summary>
345</example>
346
347Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response."#;
348
349/// Minimal compaction prompt without detailed coding information.
350/// Used when keep_coding_instructions is false.
351const COMPACTION_PROMPT_MINIMAL: &str = r#"Your task is to create a concise summary of the conversation so far, focusing on the essential context needed to continue the interaction.
352
353Before providing your final summary, briefly analyze the conversation in <analysis> tags.
354
355Your summary should include the following sections:
356
3571. Primary Request and Intent: What the user is trying to accomplish
358
3592. Key Decisions Made: Important choices and approaches decided upon
360
3613. Current Status: What has been completed and what remains
362
3634. Next Steps: If applicable, what should be done next
364
365Here's an example of how your output should be structured:
366
367<example>
368<analysis>
369[Brief thought process]
370</analysis>
371
372<summary>
3731. Primary Request and Intent:
374   [Concise description]
375
3762. Key Decisions Made:
377   - [Decision 1]
378   - [Decision 2]
379
3803. Current Status:
381   [What's done and what remains]
382
3834. Next Steps:
384   [What to do next, if applicable]
385</summary>
386</example>
387
388Please provide a focused summary based on the conversation so far."#;
389
390#[derive(Debug)]
391pub enum PreparedCompact {
392    NotNeeded,
393    Ready {
394        summary_prompt: String,
395        message_count: usize,
396    },
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402    use crate::session::state::SessionConfig;
403
404    fn create_test_session(message_count: usize) -> Session {
405        let mut session = Session::new(SessionConfig::default());
406
407        for i in 0..message_count {
408            let content = if i % 2 == 0 {
409                format!("User message {}", i)
410            } else {
411                format!("Assistant response {}", i)
412            };
413
414            let msg = if i % 2 == 0 {
415                SessionMessage::user(vec![ContentBlock::text(content)])
416            } else {
417                SessionMessage::assistant(vec![ContentBlock::text(content)])
418            };
419
420            session.add_message(msg);
421        }
422
423        session
424    }
425
426    #[test]
427    fn test_compact_strategy_default() {
428        let strategy = CompactStrategy::default();
429        assert!(strategy.enabled);
430        assert_eq!(strategy.threshold_percent, 0.8);
431        assert!(strategy.keep_coding_instructions);
432        assert!(strategy.custom_instructions.is_none());
433    }
434
435    #[test]
436    fn test_compact_strategy_disabled() {
437        let strategy = CompactStrategy::disabled();
438        assert!(!strategy.enabled);
439    }
440
441    #[test]
442    fn test_compact_strategy_with_keep_coding_instructions() {
443        let strategy = CompactStrategy::default().with_keep_coding_instructions(false);
444        assert!(!strategy.keep_coding_instructions);
445
446        let strategy = CompactStrategy::default().with_keep_coding_instructions(true);
447        assert!(strategy.keep_coding_instructions);
448    }
449
450    #[test]
451    fn test_compact_strategy_with_custom_instructions() {
452        let strategy = CompactStrategy::default()
453            .with_custom_instructions("Focus on test output and code changes.");
454
455        assert_eq!(
456            strategy.custom_instructions,
457            Some("Focus on test output and code changes.".to_string())
458        );
459    }
460
461    #[test]
462    fn test_needs_compact() {
463        let executor = CompactExecutor::new(CompactStrategy::default().with_threshold(0.8));
464
465        assert!(!executor.needs_compact(70_000, 100_000));
466        assert!(executor.needs_compact(80_000, 100_000));
467        assert!(executor.needs_compact(90_000, 100_000));
468    }
469
470    #[test]
471    fn test_prepare_compact_empty() {
472        let session = Session::new(SessionConfig::default());
473        let executor = CompactExecutor::new(CompactStrategy::default());
474
475        let result = executor.prepare_compact(&session).unwrap();
476        assert!(matches!(result, PreparedCompact::NotNeeded));
477    }
478
479    #[test]
480    fn test_prepare_compact_ready_full_prompt() {
481        let session = create_test_session(10);
482        let executor =
483            CompactExecutor::new(CompactStrategy::default().with_keep_coding_instructions(true));
484
485        let result = executor.prepare_compact(&session).unwrap();
486
487        match result {
488            PreparedCompact::Ready {
489                summary_prompt,
490                message_count,
491            } => {
492                // Full prompt should contain detailed sections
493                assert!(summary_prompt.contains("Primary Request and Intent"));
494                assert!(summary_prompt.contains("Key Technical Concepts"));
495                assert!(summary_prompt.contains("Files and Code Sections"));
496                assert!(summary_prompt.contains("Errors and fixes"));
497                assert!(summary_prompt.contains("All user messages"));
498                assert!(summary_prompt.contains("Optional Next Step"));
499                assert_eq!(message_count, 10);
500            }
501            _ => panic!("Expected Ready"),
502        }
503    }
504
505    #[test]
506    fn test_prepare_compact_ready_minimal_prompt() {
507        let session = create_test_session(10);
508        let executor =
509            CompactExecutor::new(CompactStrategy::default().with_keep_coding_instructions(false));
510
511        let result = executor.prepare_compact(&session).unwrap();
512
513        match result {
514            PreparedCompact::Ready {
515                summary_prompt,
516                message_count,
517            } => {
518                // Minimal prompt should be concise
519                assert!(summary_prompt.contains("Primary Request and Intent"));
520                assert!(summary_prompt.contains("Key Decisions Made"));
521                assert!(summary_prompt.contains("Current Status"));
522                assert!(summary_prompt.contains("Next Steps"));
523                // Should NOT contain detailed coding sections
524                assert!(!summary_prompt.contains("Files and Code Sections"));
525                assert!(!summary_prompt.contains("All user messages"));
526                assert_eq!(message_count, 10);
527            }
528            _ => panic!("Expected Ready"),
529        }
530    }
531
532    #[test]
533    fn test_prepare_compact_with_custom_instructions() {
534        let session = create_test_session(5);
535        let executor = CompactExecutor::new(
536            CompactStrategy::default()
537                .with_custom_instructions("Focus on Rust code changes and test results."),
538        );
539
540        let result = executor.prepare_compact(&session).unwrap();
541
542        match result {
543            PreparedCompact::Ready { summary_prompt, .. } => {
544                assert!(summary_prompt.contains("# Custom Summary Instructions"));
545                assert!(summary_prompt.contains("Focus on Rust code changes and test results."));
546            }
547            _ => panic!("Expected Ready"),
548        }
549    }
550
551    #[test]
552    fn test_apply_compact() {
553        let mut session = create_test_session(10);
554        let executor = CompactExecutor::new(CompactStrategy::default());
555
556        let result = executor.apply_compact(&mut session, "Test summary".to_string());
557
558        match result {
559            CompactResult::Compacted {
560                original_count,
561                new_count,
562                ..
563            } => {
564                assert_eq!(original_count, 10);
565                assert_eq!(new_count, 1);
566            }
567            _ => panic!("Expected Compacted"),
568        }
569
570        assert!(session.summary.is_some());
571        assert_eq!(session.messages.len(), 1);
572        assert!(session.messages[0].is_compact_summary);
573    }
574
575    #[test]
576    fn test_prompt_contains_analysis_tags() {
577        // Both prompts should instruct to use <analysis> tags
578        assert!(COMPACTION_PROMPT_FULL.contains("<analysis>"));
579        assert!(COMPACTION_PROMPT_MINIMAL.contains("<analysis>"));
580    }
581
582    #[test]
583    fn test_prompt_contains_summary_tags() {
584        // Both prompts should show <summary> in examples
585        assert!(COMPACTION_PROMPT_FULL.contains("<summary>"));
586        assert!(COMPACTION_PROMPT_MINIMAL.contains("<summary>"));
587    }
588}